memindex 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,30 +1,30 @@
1
1
  import { createRequire as __cmCreateRequire } from "node:module"; const require = __cmCreateRequire(import.meta.url);
2
- import{createRequire as Sn}from"node:module";var ds=Sn(import.meta.url);function E(e){return e==null}function yt(e){return e&&typeof e=="object"&&!Array.isArray(e)}function En(e,t){return Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n)))}function z(e,t){return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,t(n,r)]))}function kn(e,t,r){if(!t)return{...e};let n={};for(let o of t)(r||e[o]!==void 0)&&(n[o]=e[o]);return n}function q(e,t,r){return Object.defineProperty(e,t,{writable:!0,value:r,enumerable:!1})}var jn=Symbol.for("cosmokit.volatile.write");function Re(e){return typeof e=="object"&&e!==null&&jn in e}function U(e,t){return arguments.length===1?r=>U(e,r):e in globalThis&&t instanceof globalThis[e]||Object.prototype.toString.call(t).slice(8,-1)===e}function Pe(e){return U("ArrayBuffer",e)||U("SharedArrayBuffer",e)}function $n(e){return Pe(e)||ArrayBuffer.isView(e)}var M;(function(e){e.is=Pe,e.isSource=$n;function t(a){return ArrayBuffer.isView(a)?a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength):a}e.fromSource=t;function r(a){if(a=t(a),typeof Buffer<"u")return Buffer.from(a).toString("base64");let s="",l=new Uint8Array(a);for(let c=0;c<l.byteLength;c++)s+=String.fromCharCode(l[c]);return btoa(s)}e.toBase64=r;function n(a){return typeof Buffer<"u"?t(Buffer.from(a,"base64")):Uint8Array.from(atob(a),s=>s.charCodeAt(0))}e.fromBase64=n;function o(a){return a=t(a),typeof Buffer<"u"?Buffer.from(a).toString("hex"):Array.from(new Uint8Array(a),s=>s.toString(16).padStart(2,"0")).join("")}e.toHex=o;function i(a){if(typeof Buffer<"u")return t(Buffer.from(a,"hex"));let s=a.length%2===0?a:a.slice(0,a.length-1),l=[];for(let c=0;c<s.length;c+=2)l.push(parseInt(`${s[c]}${s[c+1]}`,16));return Uint8Array.from(l).buffer}e.fromHex=i})(M||(M={}));var ps=M.fromBase64,fs=M.toBase64,hs=M.fromHex,ms=M.toHex;function it(e,t=new Map){if(!e||typeof e!="object")return e;if(U("Date",e))return new Date(e.valueOf());if(U("RegExp",e))return new RegExp(e.source,e.flags);if(Pe(e))return e.slice(0);if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);let r=t.get(e);if(r)return r;if(Array.isArray(e)){let o=[];return t.set(e,o),e.forEach((i,a)=>{o[a]=Reflect.apply(it,null,[i,t])}),o}let n=Object.create(Object.getPrototypeOf(e));t.set(e,n);for(let o of Reflect.ownKeys(e)){let i={...Reflect.getOwnPropertyDescriptor(e,o)};"value"in i&&(i.value=Reflect.apply(it,null,[i.value,t])),Reflect.defineProperty(n,o,i)}return n}function st(e,t,r){let n=new Set;function o(i,a){if(i===a)return!0;if(Re(i)||Re(a))return Re(i)&&Re(a);if(!r&&E(i)&&E(a))return!0;if(typeof i!=typeof a||typeof i!="object"||!i||!a||n.has(i))return!1;function s(l,c){return l(i)?l(a)?c(i,a):!1:l(a)?!1:void 0}n.add(i);try{return s(Array.isArray,(l,c)=>{if(l.length!==c.length)return!1;for(let u=0;u<l.length;u++)if(!o(l[u],c[u]))return!1;return!0})??s(U("Date"),(l,c)=>l.valueOf()===c.valueOf())??s(U("URL"),(l,c)=>l.href===c.href)??s(U("RegExp"),(l,c)=>l.source===c.source&&l.flags===c.flags)??s(Pe,(l,c)=>{if(l.byteLength!==c.byteLength)return!1;let u=new Uint8Array(l),h=new Uint8Array(c);for(let f=0;f<u.length;f++)if(u[f]!==h[f])return!1;return!0})??((!r||[i,a].every(l=>Object.getPrototypeOf(l)===Object.prototype||Object.getPrototypeOf(l)===null))&&Object.keys({...i,...a}).every(l=>o(i[l],a[l])))}finally{n.delete(i)}}return o(e,t)}function _n(e,t,r){let n=[],o=0;for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a>=65&&a<=90){if(o===1){let s=e.charCodeAt(i+1);s>=97&&s<=122&&n.push(r),n.push(a+32)}else o!==0&&n.push(r),n.push(a+32);o=1}else a>=97&&a<=122?(n.push(a),o=2):t.includes(a)?(o!==0&&n.push(r),o=0):n.push(a)}return String.fromCharCode(...n)}function Rn(e){return _n(e,[45,95],45)}var An=Rn,Ut;(function(e){e.millisecond=1,e.second=1e3,e.minute=e.second*60,e.hour=e.minute*60,e.day=e.hour*24,e.week=e.day*7;let t=new Date().getTimezoneOffset();function r(p){t=p}e.setTimezoneOffset=r;function n(){return t}e.getTimezoneOffset=n;function o(p=new Date,m){return typeof p=="number"&&(p=new Date(p)),m===void 0&&(m=t),Math.floor((p.valueOf()/e.minute-m)/1440)}e.getDateNumber=o;function i(p,m){let y=new Date(p*e.day);return m===void 0&&(m=t),new Date(+y+m*e.minute)}e.fromDateNumber=i;let a=/\d+(?:\.\d+)?/.source,s=new RegExp(`^${["w(?:eek(?:s)?)?","d(?:ay(?:s)?)?","h(?:our(?:s)?)?","m(?:in(?:ute)?(?:s)?)?","s(?:ec(?:ond)?(?:s)?)?"].map(p=>`(${a}${p})?`).join("")}$`);function l(p){let m=s.exec(p);return m?(parseFloat(m[1])*e.week||0)+(parseFloat(m[2])*e.day||0)+(parseFloat(m[3])*e.hour||0)+(parseFloat(m[4])*e.minute||0)+(parseFloat(m[5])*e.second||0):0}e.parseTime=l;function c(p){let m=l(p);return m?p=Date.now()+m:/^\d{1,2}(:\d{1,2}){1,2}$/.test(p)?p=`${new Date().toLocaleDateString()}-${p}`:/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(p)&&(p=`${new Date().getFullYear()}-${p}`),p?new Date(p):new Date}e.parseDate=c;function u(p){let m=Math.abs(p);return m>=e.day-e.hour/2?Math.round(p/e.day)+"d":m>=e.hour-e.minute/2?Math.round(p/e.hour)+"h":m>=e.minute-e.second/2?Math.round(p/e.minute)+"m":m>=e.second?Math.round(p/e.second)+"s":p+"ms"}e.format=u;function h(p,m=2){return p.toString().padStart(m,"0")}e.toDigits=h;function f(p,m=new Date){return p.replace("yyyy",m.getFullYear().toString()).replace("yy",m.getFullYear().toString().slice(2)).replace("MM",h(m.getMonth()+1)).replace("dd",h(m.getDate())).replace("hh",h(m.getHours())).replace("mm",h(m.getMinutes())).replace("ss",h(m.getSeconds())).replace("SSS",h(m.getMilliseconds(),3))}e.template=f})(Ut||(Ut={}));var Fe=Symbol.for("schemastery"),br=Symbol.for("ValidationError");globalThis.__schemastery_index__??=0;globalThis.__schemastery_refs__=void 0;var w=class extends TypeError{options;name="ValidationError";constructor(e,t){let r="$";for(let n of t.path||[])typeof n=="string"?r+="."+n:typeof n=="number"?r+="["+n+"]":typeof n=="symbol"&&(r+=`[Symbol(${n.toString()})]`);r.startsWith(".")&&(r=r.slice(1)),super((r==="$"?"":`${r} `)+e),this.options=t}static is(e){return!!e?.[br]}};Object.defineProperty(w.prototype,br,{value:!0});var d=function(e){let t=function(r,n={}){return d.resolve(r,t,n)[0]};if(e.refs){let r=z(e.refs,o=>new d(o)),n=o=>r[o];for(let o in r){let i=r[o];i.sKey=n(i.sKey),i.inner=n(i.inner),i.list=i.list&&i.list.map(n),i.dict=i.dict&&z(i.dict,n)}return r[e.uid]}if(Object.assign(t,e),typeof t.callback=="string")try{t.callback=new Function("return "+t.callback)()}catch{}return Object.defineProperty(t,"uid",{value:globalThis.__schemastery_index__++}),Object.setPrototypeOf(t,d.prototype),t.meta||={},t.toString=t.toString.bind(t),t};d.prototype=Object.create(Function.prototype);d.prototype[Fe]=!0;Object.defineProperty(d.prototype,"~standard",{get(){return{version:1,vendor:"schemastery",validate:e=>{try{return{value:d.resolve(e,this,{})[0]}}catch(t){if(w.is(t))return{issues:[{message:t.message,path:t.options.path}]};throw t}}}}});d.ValidationError=w;d.prototype.toJSON=function(){if(globalThis.__schemastery_refs__)return globalThis.__schemastery_refs__[this.uid]??=JSON.parse(JSON.stringify({...this})),this.uid;globalThis.__schemastery_refs__={[this.uid]:{...this}},globalThis.__schemastery_refs__[this.uid]=JSON.parse(JSON.stringify({...this}));let e={uid:this.uid,refs:globalThis.__schemastery_refs__};return globalThis.__schemastery_refs__=void 0,e};d.prototype.set=function(e,t){return this.dict[e]=t,this};d.prototype.push=function(e){return this.list.push(e),this};function Nn(e,t){let r=typeof e=="string"?{"":e}:{...e};for(let n in t){let o=t[n];o?.$description||o?.$desc?r[n]=o.$description||o.$desc:typeof o=="string"&&(r[n]=o)}return r}function ce(e){return e?.$value??e?.$inner}function Ht(e){return En(e??{},t=>!t.startsWith("$"))}d.prototype.i18n=function(e){let t=d(this),r=Nn(t.meta.description,e);return Object.keys(r).length&&(t.meta.description=r),t.dict&&(t.dict=z(t.dict,(n,o)=>n.i18n(z(e,i=>ce(i)?.[o]??i?.[o])))),t.list&&(t.list=t.list.map((n,o)=>n.i18n(z(e,(i={})=>Array.isArray(ce(i))?ce(i)[o]:Array.isArray(i)?i[o]:Ht(i))))),t.inner&&(t.inner=t.inner.i18n(z(e,n=>ce(n)?ce(n):Ht(n)))),t.sKey&&(t.sKey=t.sKey.i18n(z(e,n=>n?.$key))),t};d.prototype.extra=function(e,t){let r=d(this);return r.meta={...r.meta,[e]:t},r};for(let e of["required","disabled","collapse","hidden","loose"])Object.assign(d.prototype,{[e](t=!0){let r=d(this);return r.meta={...r.meta,[e]:t},r}});d.prototype.deprecated=function(){let e=d(this);return e.meta.badges||=[],e.meta.badges.push({text:"deprecated",type:"danger"}),e};d.prototype.experimental=function(){let e=d(this);return e.meta.badges||=[],e.meta.badges.push({text:"experimental",type:"warning"}),e};d.prototype.pattern=function(e){let t=d(this),r=kn(e,["source","flags"]);return t.meta={...t.meta,pattern:r},t};d.prototype.simplify=function(e){if(st(e,this.meta.default,this.type==="dict"))return null;if(E(e))return e;if(this.type==="object"||this.type==="dict"){let t={};for(let r in e){let n=(this.type==="object"?this.dict[r]:this.inner)?.simplify(e[r]);(this.type==="dict"||!E(n))&&(t[r]=n)}return st(t,this.meta.default,this.type==="dict")?null:t}else if(this.type==="array"||this.type==="tuple"){let t=[];return e.forEach((r,n)=>{let o=this.type==="array"?this.inner:this.list[n],i=o?o.simplify(r):r;t.push(i)}),t}else if(this.type==="intersect"){let t={};for(let r of this.list)Object.assign(t,r.simplify(e));return t}else if(this.type==="union")for(let t of this.list)try{return d.resolve(e,t,{}),t.simplify(e)}catch{}return e};d.prototype.toString=function(e){return vr[this.type]?.(this,e)??`Schema<${this.type}>`};d.prototype.role=function(e,t){let r=d(this);return r.meta={...r.meta,role:e,extra:t},r};for(let e of["default","link","comment","description","max","min","step"])Object.assign(d.prototype,{[e](t){let r=d(this);return r.meta={...r.meta,[e]:t},r}});var wr={};d.extend=function(e,t){wr[e]=t};d.resolve=function(e,t,r={},n=!1){if(!t)return[e];if(r.ignore?.(e,t))return[e];if(E(e)&&t.type!=="lazy"){if(t.meta.required)throw new w("missing required value",r);let i=t,a=t.meta.default;for(;i?.type==="intersect"&&E(a);)i=i.list[0],a=i?.meta.default;if(E(a))return[e];e=it(a)}let o=wr[t.type];if(!o)throw new w(`unsupported type "${t.type}"`,r);try{return o(e,t,r,n)}catch(i){if(!t.meta.loose)throw i;return[t.meta.default]}};d.from=function(e){if(E(e))return d.any();if(["string","number","boolean"].includes(typeof e))return d.const(e).required();if(e[Fe])return e;if(typeof e=="function")switch(e){case String:return d.string().required();case Number:return d.number().required();case Boolean:return d.boolean().required();case Function:return d.function().required();default:return d.is(e).required()}else throw new TypeError(`cannot infer schema from ${e}`)};d.lazy=function(e){let t=()=>(r.inner[Fe]||(r.inner=r.builder(),r.inner.meta={...r.meta,...r.inner.meta}),r.inner.toJSON()),r=new d({type:"lazy",builder:e,inner:{toJSON:t}});return r};d.natural=function(){return d.number().step(1).min(0)};d.percent=function(){return d.number().step(.01).min(0).max(1).role("slider")};d.date=function(){return d.union([d.is(Date),d.transform(d.string().role("datetime"),(e,t)=>{let r=new Date(e);if(isNaN(+r))throw new w(`invalid date "${e}"`,t);return r},!0)])};d.regExp=function(e=""){return d.union([d.is(RegExp),d.transform(d.string().role("regexp",{flag:e}),(t,r)=>{try{return new RegExp(t,e)}catch(n){throw new w(n.message,r)}},!0)])};d.arrayBuffer=function(e){return d.union([d.is(ArrayBuffer),d.is(SharedArrayBuffer),d.transform(d.any(),(t,r)=>{if(M.isSource(t))return M.fromSource(t);throw new w(`expected ArrayBufferSource but got ${t}`,r)},!0),...e?[d.transform(d.string(),(t,r)=>{try{return e==="base64"?M.fromBase64(t):M.fromHex(t)}catch(n){throw new w(n.message,r)}},!0)]:[]])};d.extend("lazy",(e,t,r,n)=>(t.inner[Fe]||(t.inner=t.builder(),t.inner.meta={...t.meta,...t.inner.meta}),d.resolve(e,t.inner,r,n)));d.extend("any",e=>[e]);d.extend("never",(e,t,r)=>{throw new w(`expected nullable but got ${e}`,r)});d.extend("const",(e,{value:t},r)=>{if(st(e,t))return[t];throw new w(`expected ${t} but got ${e}`,r)});function bt(e,t,r,n,o=!1){let{max:i=1/0,min:a=-1/0}=t;if(e>i)throw new w(`expected ${r} <= ${i} but got ${e}`,n);if(e<a&&!o)throw new w(`expected ${r} >= ${a} but got ${e}`,n)}d.extend("string",(e,{meta:t},r)=>{if(typeof e!="string")throw new w(`expected string but got ${e}`,r);if(t.pattern){let n=new RegExp(t.pattern.source,t.pattern.flags);if(!n.test(e))throw new w(`expect string to match regexp ${n}`,r)}return bt(e.length,t,"string length",r),[e]});function Ve(e,t){let r=e.toString();if(r.includes("e"))return e*Math.pow(10,t);let n=r.indexOf(".");if(n===-1)return e*Math.pow(10,t);let o=r.slice(n+1),i=r.slice(0,n);return o.length<=t?+(i+o.padEnd(t,"0")):+(i+o.slice(0,t)+"."+o.slice(t))}function Cn(e,t,r){if(r=Math.abs(r),!/^\d+\.\d+$/.test(r.toString()))return(e-t)%r===0;let n=r.toString().indexOf("."),o=r.toString().slice(n+1).length;return Math.abs(Ve(e,o)-Ve(t,o))%Ve(r,o)===0}d.extend("number",(e,{meta:t},r)=>{if(typeof e!="number")throw new w(`expected number but got ${e}`,r);bt(e,t,"number",r);let{step:n}=t;if(n&&!Cn(e,t.min??0,n))throw new w(`expected number multiple of ${n} but got ${e}`,r);return[e]});d.extend("boolean",(e,t,r)=>{if(typeof e=="boolean")return[e];throw new w(`expected boolean but got ${e}`,r)});d.extend("bitset",(e,{bits:t,meta:r},n)=>{let o=0,i=[];if(typeof e=="number"){o=e;for(let a in t)e&t[a]&&i.push(a)}else if(Array.isArray(e)){i=e;for(let a of i){if(typeof a!="string")throw new w(`expected string but got ${a}`,n);a in t&&(o|=t[a])}}else throw new w(`expected number or array but got ${e}`,n);return o===r.default?[o]:[o,i]});d.extend("function",(e,t,r)=>{if(typeof e=="function")return[e];throw new w(`expected function but got ${e}`,r)});d.extend("is",(e,{constructor:t},r)=>{if(typeof t=="function"){if(e instanceof t)return[e];throw new w(`expected ${t.name} but got ${e}`,r)}else{if(E(e))throw new w(`expected ${t} but got ${e}`,r);let n=Object.getPrototypeOf(e);for(;n;){if(n.constructor?.name===t)return[e];n=Object.getPrototypeOf(n)}throw new w(`expected ${t} but got ${e}`,r)}});function qe(e,t,r,n){try{let[o,i]=d.resolve(e[t],r,{...n,path:[...n.path||[],t]});return i!==void 0&&(e[t]=i),o}catch(o){if(!n?.autofix)throw o;return delete e[t],r.meta.default}}d.extend("array",(e,{inner:t,meta:r},n)=>{if(!Array.isArray(e))throw new w(`expected array but got ${e}`,n);return bt(e.length,r,"array length",n,!E(t.meta.default)),[e.map((o,i)=>qe(e,i,t,n))]});d.extend("dict",(e,{inner:t,sKey:r},n,o)=>{if(!yt(e))throw new w(`expected object but got ${e}`,n);let i={};for(let a in e){let s;try{s=d.resolve(a,r,n)[0]}catch(l){if(o)continue;throw l}i[s]=qe(e,a,t,n),e[s]=e[a],a!==s&&delete e[a]}return[i]});d.extend("tuple",(e,{list:t},r,n)=>{if(!Array.isArray(e))throw new w(`expected array but got ${e}`,r);let o=t.map((i,a)=>qe(e,a,i,r));return n?[o]:(o.push(...e.slice(t.length)),[o])});function at(e,t){for(let r in t)r in e||(e[r]=t[r])}d.extend("object",(e,{dict:t},r,n)=>{if(!yt(e))throw new w(`expected object but got ${e}`,r);let o={};for(let i in t){let a=qe(e,i,t[i],r);(!E(a)||i in e)&&(o[i]=a)}return n||at(o,e),[o]});d.extend("union",(e,{list:t,toString:r},n,o)=>{let i=[];for(let a of t)try{return d.resolve(e,a,n,o)}catch(s){i.push(s)}throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n)});d.extend("intersect",(e,{list:t,toString:r},n,o)=>{if(!t.length)return[e];let i;for(let a of t){let s=d.resolve(e,a,n,!0)[0];if(!E(s))if(E(i))i=s;else{if(typeof i!=typeof s)throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n);if(typeof s=="object")at(i??={},s);else if(i!==s)throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n)}}return!o&&yt(e)&&at(i,e),[i]});d.extend("transform",(e,{inner:t,callback:r,preserve:n},o)=>{let[i,a=e]=d.resolve(e,t,o,!0);return n?[r(i)]:[r(i),r(a)]});var vr={};function k(e,t,r){vr[e]=r,Object.assign(d,{[e](...n){let o=new d({type:e});return t.forEach((i,a)=>{switch(i){case"sKey":o.sKey=n[a]??d.string();break;case"inner":o.inner=d.from(n[a]);break;case"list":o.list=n[a].map(d.from);break;case"dict":o.dict=z(n[a],d.from);break;case"bits":o.bits={};for(let s in n[a])typeof n[a][s]=="number"&&(o.bits[s]=n[a][s]);break;case"callback":{let s=o.callback=n[a];s.toJSON||=()=>s.toString();break}case"constructor":{let s=o.constructor=n[a];typeof s=="function"&&(s.toJSON||=()=>s.name);break}default:o[i]=n[a]}}),e==="object"||e==="dict"?o.meta.default={}:e==="array"||e==="tuple"?o.meta.default=[]:e==="bitset"&&(o.meta.default=0),o}})}k("is",["constructor"],({constructor:e})=>typeof e=="function"?e.name:e);k("any",[],()=>"any");k("never",[],()=>"never");k("const",["value"],({value:e})=>typeof e=="string"?JSON.stringify(e):e);k("string",[],()=>"string");k("number",[],()=>"number");k("boolean",[],()=>"boolean");k("bitset",["bits"],()=>"bitset");k("function",[],()=>"function");k("array",["inner"],({inner:e})=>`${e.toString(!0)}[]`);k("dict",["inner","sKey"],({inner:e,sKey:t})=>`{ [key: ${t.toString()}]: ${e.toString()} }`);k("tuple",["list"],({list:e})=>`[${e.map(t=>t.toString()).join(", ")}]`);k("object",["dict"],({dict:e})=>Object.keys(e).length===0?"{}":`{ ${Object.entries(e).map(([t,r])=>`${t}${r.meta.required?"":"?"}: ${r.toString()}`).join(", ")} }`);k("union",["list"],({list:e},t)=>{let r=e.map(({toString:n})=>n()).join(" | ");return t?`(${r})`:r});k("intersect",["list"],({list:e})=>`${e.map(t=>t.toString(!0)).join(" & ")}`);k("transform",["inner","callback","preserve"],({inner:e},t)=>e.toString(t));var wt=class{sn=0;map=new Map;weak=new WeakMap;get length(){return this.map.size}push(e){let t=++this.sn;return this.map.set(t,e),this.weak.set(e,t),()=>this.map.delete(t)}delete(e){let t=this.weak.get(e);return t?this.map.delete(t):!1}clear(){let e=[...this.map.values()];return this.map.clear(),e.reverse()}[Symbol.iterator](){return this.map.values()}[Symbol.for("nodejs.util.inspect.custom")](){return[...this]}},g={shadow:Symbol.for("cordis.shadow"),receiver:Symbol.for("cordis.receiver"),original:Symbol.for("cordis.original"),metadata:Symbol.for("cordis.metadata"),initHooks:Symbol.for("cordis.initHooks"),checkProto:Symbol.for("cordis.checkProto"),effect:Symbol.for("cordis.effect"),filter:Symbol.for("cordis.filter"),isolate:Symbol.for("cordis.isolate"),intercept:Symbol.for("cordis.intercept"),init:Symbol.for("cordis.init"),check:Symbol.for("cordis.check"),config:Symbol.for("cordis.config"),invoke:Symbol.for("cordis.invoke"),extend:Symbol.for("cordis.extend"),tracker:Symbol.for("cordis.tracker"),resolveConfig:Symbol.for("cordis.resolveConfig")},Tn=function*(){}.constructor,Kt=async function*(){}.constructor;function Dn(e){return!(!e.prototype||e instanceof Tn||Kt!==Function&&e instanceof Kt)}function vt(e,t){if(e===Object.prototype)return t;let r=Object.create(vt(Object.getPrototypeOf(e),t));for(let n of Reflect.ownKeys(e))Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(e,n));return r}function re(e){return e&&(typeof e=="object"||typeof e=="function")}function In(e,t){let r=e;for(;r;){let n=Reflect.getOwnPropertyDescriptor(r,t);if(n)return n;r=Object.getPrototypeOf(r)}}function Y(e,t){if(!re(t))return t;if(Object.hasOwn(t,g.shadow))return Object.getPrototypeOf(t);let r=t[g.tracker];return r?xt(e,t,r):t}function Ce(e,t){return t?new Proxy(e,{get:(r,n,o)=>n in t&&n!=="constructor"?Reflect.get(t,n,o):Reflect.get(r,n,o),set:(r,n,o,i)=>n in t&&n!=="constructor"?Reflect.set(t,n,o,i):Reflect.set(r,n,o,i)}):e}function lt(e,t,r){return Ce(e,Object.defineProperty(Object.create(null),t,{value:r,writable:!1}))}function Xe(e,t,r,n){if(!r)return n;let o=Reflect.getOwnPropertyDescriptor(t,r)?.value;return o?lt(n,r,e.extend({[g.shadow]:o})):n}function Mn(e,t,r,n){return new Proxy(t,{apply:(o,i,a)=>(i===r&&(i=n),Y(e,Reflect.apply(o,i,a)))})}function xt(e,t,r){e[g.shadow]&&!r.noShadow&&(e=Object.getPrototypeOf(e));let n=new Proxy(t,{get:(o,i,a)=>{if(i===g.original)return o;if(i===r.property)return e;if(typeof i=="symbol")return Reflect.get(o,i,a);if(r.associate&&e.reflect.props[`${r.associate}.${i}`])return Reflect.get(e,`${r.associate}.${i}`,lt(e,g.receiver,a));let s,l,c=In(o,i);c&&"value"in c?l=c.value:(s=Xe(e,o,r.property,a),l=Reflect.get(o,i,s));let u=l?.[g.tracker];return u?xt(e,l,u):!r.noShadow&&typeof l=="function"?(s??=Xe(e,o,r.property,a),Mn(e,l,a,s)):l},set:(o,i,a,s)=>{if(i===g.original||i===r.property)return!1;if(typeof i=="symbol")return Reflect.set(o,i,a,s);if(r.associate&&e.reflect.props[`${r.associate}.${i}`])return Reflect.set(e,`${r.associate}.${i}`,a,lt(e,g.receiver,s));let l=Xe(e,o,r.property,s);return Reflect.set(o,i,a,l)},apply:(o,i,a)=>xr(n,o,i,a)});return n}function xr(e,t,r,n){return t[g.invoke]?t[g.invoke].apply(e,n):Reflect.apply(t,r,n)}function ct(e,t,r){let n=function(...o){return xr(xt(n.ctx,n,r),n,this,o)};return q(n,"name",e),Object.setPrototypeOf(n,t)}function Vt(e,t,r){let n=e.error.stack.split(`
2
+ import{createRequire as Sn}from"node:module";var ds=Sn(import.meta.url);function E(e){return e==null}function yt(e){return e&&typeof e=="object"&&!Array.isArray(e)}function En(e,t){return Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n)))}function U(e,t){return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,t(n,r)]))}function kn(e,t,r){if(!t)return{...e};let n={};for(let o of t)(r||e[o]!==void 0)&&(n[o]=e[o]);return n}function q(e,t,r){return Object.defineProperty(e,t,{writable:!0,value:r,enumerable:!1})}var jn=Symbol.for("cosmokit.volatile.write");function Re(e){return typeof e=="object"&&e!==null&&jn in e}function z(e,t){return arguments.length===1?r=>z(e,r):e in globalThis&&t instanceof globalThis[e]||Object.prototype.toString.call(t).slice(8,-1)===e}function Pe(e){return z("ArrayBuffer",e)||z("SharedArrayBuffer",e)}function $n(e){return Pe(e)||ArrayBuffer.isView(e)}var M;(function(e){e.is=Pe,e.isSource=$n;function t(a){return ArrayBuffer.isView(a)?a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength):a}e.fromSource=t;function r(a){if(a=t(a),typeof Buffer<"u")return Buffer.from(a).toString("base64");let s="",l=new Uint8Array(a);for(let c=0;c<l.byteLength;c++)s+=String.fromCharCode(l[c]);return btoa(s)}e.toBase64=r;function n(a){return typeof Buffer<"u"?t(Buffer.from(a,"base64")):Uint8Array.from(atob(a),s=>s.charCodeAt(0))}e.fromBase64=n;function o(a){return a=t(a),typeof Buffer<"u"?Buffer.from(a).toString("hex"):Array.from(new Uint8Array(a),s=>s.toString(16).padStart(2,"0")).join("")}e.toHex=o;function i(a){if(typeof Buffer<"u")return t(Buffer.from(a,"hex"));let s=a.length%2===0?a:a.slice(0,a.length-1),l=[];for(let c=0;c<s.length;c+=2)l.push(parseInt(`${s[c]}${s[c+1]}`,16));return Uint8Array.from(l).buffer}e.fromHex=i})(M||(M={}));var ps=M.fromBase64,fs=M.toBase64,hs=M.fromHex,ms=M.toHex;function it(e,t=new Map){if(!e||typeof e!="object")return e;if(z("Date",e))return new Date(e.valueOf());if(z("RegExp",e))return new RegExp(e.source,e.flags);if(Pe(e))return e.slice(0);if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);let r=t.get(e);if(r)return r;if(Array.isArray(e)){let o=[];return t.set(e,o),e.forEach((i,a)=>{o[a]=Reflect.apply(it,null,[i,t])}),o}let n=Object.create(Object.getPrototypeOf(e));t.set(e,n);for(let o of Reflect.ownKeys(e)){let i={...Reflect.getOwnPropertyDescriptor(e,o)};"value"in i&&(i.value=Reflect.apply(it,null,[i.value,t])),Reflect.defineProperty(n,o,i)}return n}function st(e,t,r){let n=new Set;function o(i,a){if(i===a)return!0;if(Re(i)||Re(a))return Re(i)&&Re(a);if(!r&&E(i)&&E(a))return!0;if(typeof i!=typeof a||typeof i!="object"||!i||!a||n.has(i))return!1;function s(l,c){return l(i)?l(a)?c(i,a):!1:l(a)?!1:void 0}n.add(i);try{return s(Array.isArray,(l,c)=>{if(l.length!==c.length)return!1;for(let u=0;u<l.length;u++)if(!o(l[u],c[u]))return!1;return!0})??s(z("Date"),(l,c)=>l.valueOf()===c.valueOf())??s(z("URL"),(l,c)=>l.href===c.href)??s(z("RegExp"),(l,c)=>l.source===c.source&&l.flags===c.flags)??s(Pe,(l,c)=>{if(l.byteLength!==c.byteLength)return!1;let u=new Uint8Array(l),h=new Uint8Array(c);for(let f=0;f<u.length;f++)if(u[f]!==h[f])return!1;return!0})??((!r||[i,a].every(l=>Object.getPrototypeOf(l)===Object.prototype||Object.getPrototypeOf(l)===null))&&Object.keys({...i,...a}).every(l=>o(i[l],a[l])))}finally{n.delete(i)}}return o(e,t)}function _n(e,t,r){let n=[],o=0;for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a>=65&&a<=90){if(o===1){let s=e.charCodeAt(i+1);s>=97&&s<=122&&n.push(r),n.push(a+32)}else o!==0&&n.push(r),n.push(a+32);o=1}else a>=97&&a<=122?(n.push(a),o=2):t.includes(a)?(o!==0&&n.push(r),o=0):n.push(a)}return String.fromCharCode(...n)}function Rn(e){return _n(e,[45,95],45)}var An=Rn,zt;(function(e){e.millisecond=1,e.second=1e3,e.minute=e.second*60,e.hour=e.minute*60,e.day=e.hour*24,e.week=e.day*7;let t=new Date().getTimezoneOffset();function r(p){t=p}e.setTimezoneOffset=r;function n(){return t}e.getTimezoneOffset=n;function o(p=new Date,m){return typeof p=="number"&&(p=new Date(p)),m===void 0&&(m=t),Math.floor((p.valueOf()/e.minute-m)/1440)}e.getDateNumber=o;function i(p,m){let y=new Date(p*e.day);return m===void 0&&(m=t),new Date(+y+m*e.minute)}e.fromDateNumber=i;let a=/\d+(?:\.\d+)?/.source,s=new RegExp(`^${["w(?:eek(?:s)?)?","d(?:ay(?:s)?)?","h(?:our(?:s)?)?","m(?:in(?:ute)?(?:s)?)?","s(?:ec(?:ond)?(?:s)?)?"].map(p=>`(${a}${p})?`).join("")}$`);function l(p){let m=s.exec(p);return m?(parseFloat(m[1])*e.week||0)+(parseFloat(m[2])*e.day||0)+(parseFloat(m[3])*e.hour||0)+(parseFloat(m[4])*e.minute||0)+(parseFloat(m[5])*e.second||0):0}e.parseTime=l;function c(p){let m=l(p);return m?p=Date.now()+m:/^\d{1,2}(:\d{1,2}){1,2}$/.test(p)?p=`${new Date().toLocaleDateString()}-${p}`:/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(p)&&(p=`${new Date().getFullYear()}-${p}`),p?new Date(p):new Date}e.parseDate=c;function u(p){let m=Math.abs(p);return m>=e.day-e.hour/2?Math.round(p/e.day)+"d":m>=e.hour-e.minute/2?Math.round(p/e.hour)+"h":m>=e.minute-e.second/2?Math.round(p/e.minute)+"m":m>=e.second?Math.round(p/e.second)+"s":p+"ms"}e.format=u;function h(p,m=2){return p.toString().padStart(m,"0")}e.toDigits=h;function f(p,m=new Date){return p.replace("yyyy",m.getFullYear().toString()).replace("yy",m.getFullYear().toString().slice(2)).replace("MM",h(m.getMonth()+1)).replace("dd",h(m.getDate())).replace("hh",h(m.getHours())).replace("mm",h(m.getMinutes())).replace("ss",h(m.getSeconds())).replace("SSS",h(m.getMilliseconds(),3))}e.template=f})(zt||(zt={}));var Fe=Symbol.for("schemastery"),br=Symbol.for("ValidationError");globalThis.__schemastery_index__??=0;globalThis.__schemastery_refs__=void 0;var w=class extends TypeError{options;name="ValidationError";constructor(e,t){let r="$";for(let n of t.path||[])typeof n=="string"?r+="."+n:typeof n=="number"?r+="["+n+"]":typeof n=="symbol"&&(r+=`[Symbol(${n.toString()})]`);r.startsWith(".")&&(r=r.slice(1)),super((r==="$"?"":`${r} `)+e),this.options=t}static is(e){return!!e?.[br]}};Object.defineProperty(w.prototype,br,{value:!0});var d=function(e){let t=function(r,n={}){return d.resolve(r,t,n)[0]};if(e.refs){let r=U(e.refs,o=>new d(o)),n=o=>r[o];for(let o in r){let i=r[o];i.sKey=n(i.sKey),i.inner=n(i.inner),i.list=i.list&&i.list.map(n),i.dict=i.dict&&U(i.dict,n)}return r[e.uid]}if(Object.assign(t,e),typeof t.callback=="string")try{t.callback=new Function("return "+t.callback)()}catch{}return Object.defineProperty(t,"uid",{value:globalThis.__schemastery_index__++}),Object.setPrototypeOf(t,d.prototype),t.meta||={},t.toString=t.toString.bind(t),t};d.prototype=Object.create(Function.prototype);d.prototype[Fe]=!0;Object.defineProperty(d.prototype,"~standard",{get(){return{version:1,vendor:"schemastery",validate:e=>{try{return{value:d.resolve(e,this,{})[0]}}catch(t){if(w.is(t))return{issues:[{message:t.message,path:t.options.path}]};throw t}}}}});d.ValidationError=w;d.prototype.toJSON=function(){if(globalThis.__schemastery_refs__)return globalThis.__schemastery_refs__[this.uid]??=JSON.parse(JSON.stringify({...this})),this.uid;globalThis.__schemastery_refs__={[this.uid]:{...this}},globalThis.__schemastery_refs__[this.uid]=JSON.parse(JSON.stringify({...this}));let e={uid:this.uid,refs:globalThis.__schemastery_refs__};return globalThis.__schemastery_refs__=void 0,e};d.prototype.set=function(e,t){return this.dict[e]=t,this};d.prototype.push=function(e){return this.list.push(e),this};function Cn(e,t){let r=typeof e=="string"?{"":e}:{...e};for(let n in t){let o=t[n];o?.$description||o?.$desc?r[n]=o.$description||o.$desc:typeof o=="string"&&(r[n]=o)}return r}function ce(e){return e?.$value??e?.$inner}function Ht(e){return En(e??{},t=>!t.startsWith("$"))}d.prototype.i18n=function(e){let t=d(this),r=Cn(t.meta.description,e);return Object.keys(r).length&&(t.meta.description=r),t.dict&&(t.dict=U(t.dict,(n,o)=>n.i18n(U(e,i=>ce(i)?.[o]??i?.[o])))),t.list&&(t.list=t.list.map((n,o)=>n.i18n(U(e,(i={})=>Array.isArray(ce(i))?ce(i)[o]:Array.isArray(i)?i[o]:Ht(i))))),t.inner&&(t.inner=t.inner.i18n(U(e,n=>ce(n)?ce(n):Ht(n)))),t.sKey&&(t.sKey=t.sKey.i18n(U(e,n=>n?.$key))),t};d.prototype.extra=function(e,t){let r=d(this);return r.meta={...r.meta,[e]:t},r};for(let e of["required","disabled","collapse","hidden","loose"])Object.assign(d.prototype,{[e](t=!0){let r=d(this);return r.meta={...r.meta,[e]:t},r}});d.prototype.deprecated=function(){let e=d(this);return e.meta.badges||=[],e.meta.badges.push({text:"deprecated",type:"danger"}),e};d.prototype.experimental=function(){let e=d(this);return e.meta.badges||=[],e.meta.badges.push({text:"experimental",type:"warning"}),e};d.prototype.pattern=function(e){let t=d(this),r=kn(e,["source","flags"]);return t.meta={...t.meta,pattern:r},t};d.prototype.simplify=function(e){if(st(e,this.meta.default,this.type==="dict"))return null;if(E(e))return e;if(this.type==="object"||this.type==="dict"){let t={};for(let r in e){let n=(this.type==="object"?this.dict[r]:this.inner)?.simplify(e[r]);(this.type==="dict"||!E(n))&&(t[r]=n)}return st(t,this.meta.default,this.type==="dict")?null:t}else if(this.type==="array"||this.type==="tuple"){let t=[];return e.forEach((r,n)=>{let o=this.type==="array"?this.inner:this.list[n],i=o?o.simplify(r):r;t.push(i)}),t}else if(this.type==="intersect"){let t={};for(let r of this.list)Object.assign(t,r.simplify(e));return t}else if(this.type==="union")for(let t of this.list)try{return d.resolve(e,t,{}),t.simplify(e)}catch{}return e};d.prototype.toString=function(e){return vr[this.type]?.(this,e)??`Schema<${this.type}>`};d.prototype.role=function(e,t){let r=d(this);return r.meta={...r.meta,role:e,extra:t},r};for(let e of["default","link","comment","description","max","min","step"])Object.assign(d.prototype,{[e](t){let r=d(this);return r.meta={...r.meta,[e]:t},r}});var wr={};d.extend=function(e,t){wr[e]=t};d.resolve=function(e,t,r={},n=!1){if(!t)return[e];if(r.ignore?.(e,t))return[e];if(E(e)&&t.type!=="lazy"){if(t.meta.required)throw new w("missing required value",r);let i=t,a=t.meta.default;for(;i?.type==="intersect"&&E(a);)i=i.list[0],a=i?.meta.default;if(E(a))return[e];e=it(a)}let o=wr[t.type];if(!o)throw new w(`unsupported type "${t.type}"`,r);try{return o(e,t,r,n)}catch(i){if(!t.meta.loose)throw i;return[t.meta.default]}};d.from=function(e){if(E(e))return d.any();if(["string","number","boolean"].includes(typeof e))return d.const(e).required();if(e[Fe])return e;if(typeof e=="function")switch(e){case String:return d.string().required();case Number:return d.number().required();case Boolean:return d.boolean().required();case Function:return d.function().required();default:return d.is(e).required()}else throw new TypeError(`cannot infer schema from ${e}`)};d.lazy=function(e){let t=()=>(r.inner[Fe]||(r.inner=r.builder(),r.inner.meta={...r.meta,...r.inner.meta}),r.inner.toJSON()),r=new d({type:"lazy",builder:e,inner:{toJSON:t}});return r};d.natural=function(){return d.number().step(1).min(0)};d.percent=function(){return d.number().step(.01).min(0).max(1).role("slider")};d.date=function(){return d.union([d.is(Date),d.transform(d.string().role("datetime"),(e,t)=>{let r=new Date(e);if(isNaN(+r))throw new w(`invalid date "${e}"`,t);return r},!0)])};d.regExp=function(e=""){return d.union([d.is(RegExp),d.transform(d.string().role("regexp",{flag:e}),(t,r)=>{try{return new RegExp(t,e)}catch(n){throw new w(n.message,r)}},!0)])};d.arrayBuffer=function(e){return d.union([d.is(ArrayBuffer),d.is(SharedArrayBuffer),d.transform(d.any(),(t,r)=>{if(M.isSource(t))return M.fromSource(t);throw new w(`expected ArrayBufferSource but got ${t}`,r)},!0),...e?[d.transform(d.string(),(t,r)=>{try{return e==="base64"?M.fromBase64(t):M.fromHex(t)}catch(n){throw new w(n.message,r)}},!0)]:[]])};d.extend("lazy",(e,t,r,n)=>(t.inner[Fe]||(t.inner=t.builder(),t.inner.meta={...t.meta,...t.inner.meta}),d.resolve(e,t.inner,r,n)));d.extend("any",e=>[e]);d.extend("never",(e,t,r)=>{throw new w(`expected nullable but got ${e}`,r)});d.extend("const",(e,{value:t},r)=>{if(st(e,t))return[t];throw new w(`expected ${t} but got ${e}`,r)});function bt(e,t,r,n,o=!1){let{max:i=1/0,min:a=-1/0}=t;if(e>i)throw new w(`expected ${r} <= ${i} but got ${e}`,n);if(e<a&&!o)throw new w(`expected ${r} >= ${a} but got ${e}`,n)}d.extend("string",(e,{meta:t},r)=>{if(typeof e!="string")throw new w(`expected string but got ${e}`,r);if(t.pattern){let n=new RegExp(t.pattern.source,t.pattern.flags);if(!n.test(e))throw new w(`expect string to match regexp ${n}`,r)}return bt(e.length,t,"string length",r),[e]});function Ve(e,t){let r=e.toString();if(r.includes("e"))return e*Math.pow(10,t);let n=r.indexOf(".");if(n===-1)return e*Math.pow(10,t);let o=r.slice(n+1),i=r.slice(0,n);return o.length<=t?+(i+o.padEnd(t,"0")):+(i+o.slice(0,t)+"."+o.slice(t))}function Nn(e,t,r){if(r=Math.abs(r),!/^\d+\.\d+$/.test(r.toString()))return(e-t)%r===0;let n=r.toString().indexOf("."),o=r.toString().slice(n+1).length;return Math.abs(Ve(e,o)-Ve(t,o))%Ve(r,o)===0}d.extend("number",(e,{meta:t},r)=>{if(typeof e!="number")throw new w(`expected number but got ${e}`,r);bt(e,t,"number",r);let{step:n}=t;if(n&&!Nn(e,t.min??0,n))throw new w(`expected number multiple of ${n} but got ${e}`,r);return[e]});d.extend("boolean",(e,t,r)=>{if(typeof e=="boolean")return[e];throw new w(`expected boolean but got ${e}`,r)});d.extend("bitset",(e,{bits:t,meta:r},n)=>{let o=0,i=[];if(typeof e=="number"){o=e;for(let a in t)e&t[a]&&i.push(a)}else if(Array.isArray(e)){i=e;for(let a of i){if(typeof a!="string")throw new w(`expected string but got ${a}`,n);a in t&&(o|=t[a])}}else throw new w(`expected number or array but got ${e}`,n);return o===r.default?[o]:[o,i]});d.extend("function",(e,t,r)=>{if(typeof e=="function")return[e];throw new w(`expected function but got ${e}`,r)});d.extend("is",(e,{constructor:t},r)=>{if(typeof t=="function"){if(e instanceof t)return[e];throw new w(`expected ${t.name} but got ${e}`,r)}else{if(E(e))throw new w(`expected ${t} but got ${e}`,r);let n=Object.getPrototypeOf(e);for(;n;){if(n.constructor?.name===t)return[e];n=Object.getPrototypeOf(n)}throw new w(`expected ${t} but got ${e}`,r)}});function qe(e,t,r,n){try{let[o,i]=d.resolve(e[t],r,{...n,path:[...n.path||[],t]});return i!==void 0&&(e[t]=i),o}catch(o){if(!n?.autofix)throw o;return delete e[t],r.meta.default}}d.extend("array",(e,{inner:t,meta:r},n)=>{if(!Array.isArray(e))throw new w(`expected array but got ${e}`,n);return bt(e.length,r,"array length",n,!E(t.meta.default)),[e.map((o,i)=>qe(e,i,t,n))]});d.extend("dict",(e,{inner:t,sKey:r},n,o)=>{if(!yt(e))throw new w(`expected object but got ${e}`,n);let i={};for(let a in e){let s;try{s=d.resolve(a,r,n)[0]}catch(l){if(o)continue;throw l}i[s]=qe(e,a,t,n),e[s]=e[a],a!==s&&delete e[a]}return[i]});d.extend("tuple",(e,{list:t},r,n)=>{if(!Array.isArray(e))throw new w(`expected array but got ${e}`,r);let o=t.map((i,a)=>qe(e,a,i,r));return n?[o]:(o.push(...e.slice(t.length)),[o])});function at(e,t){for(let r in t)r in e||(e[r]=t[r])}d.extend("object",(e,{dict:t},r,n)=>{if(!yt(e))throw new w(`expected object but got ${e}`,r);let o={};for(let i in t){let a=qe(e,i,t[i],r);(!E(a)||i in e)&&(o[i]=a)}return n||at(o,e),[o]});d.extend("union",(e,{list:t,toString:r},n,o)=>{let i=[];for(let a of t)try{return d.resolve(e,a,n,o)}catch(s){i.push(s)}throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n)});d.extend("intersect",(e,{list:t,toString:r},n,o)=>{if(!t.length)return[e];let i;for(let a of t){let s=d.resolve(e,a,n,!0)[0];if(!E(s))if(E(i))i=s;else{if(typeof i!=typeof s)throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n);if(typeof s=="object")at(i??={},s);else if(i!==s)throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n)}}return!o&&yt(e)&&at(i,e),[i]});d.extend("transform",(e,{inner:t,callback:r,preserve:n},o)=>{let[i,a=e]=d.resolve(e,t,o,!0);return n?[r(i)]:[r(i),r(a)]});var vr={};function k(e,t,r){vr[e]=r,Object.assign(d,{[e](...n){let o=new d({type:e});return t.forEach((i,a)=>{switch(i){case"sKey":o.sKey=n[a]??d.string();break;case"inner":o.inner=d.from(n[a]);break;case"list":o.list=n[a].map(d.from);break;case"dict":o.dict=U(n[a],d.from);break;case"bits":o.bits={};for(let s in n[a])typeof n[a][s]=="number"&&(o.bits[s]=n[a][s]);break;case"callback":{let s=o.callback=n[a];s.toJSON||=()=>s.toString();break}case"constructor":{let s=o.constructor=n[a];typeof s=="function"&&(s.toJSON||=()=>s.name);break}default:o[i]=n[a]}}),e==="object"||e==="dict"?o.meta.default={}:e==="array"||e==="tuple"?o.meta.default=[]:e==="bitset"&&(o.meta.default=0),o}})}k("is",["constructor"],({constructor:e})=>typeof e=="function"?e.name:e);k("any",[],()=>"any");k("never",[],()=>"never");k("const",["value"],({value:e})=>typeof e=="string"?JSON.stringify(e):e);k("string",[],()=>"string");k("number",[],()=>"number");k("boolean",[],()=>"boolean");k("bitset",["bits"],()=>"bitset");k("function",[],()=>"function");k("array",["inner"],({inner:e})=>`${e.toString(!0)}[]`);k("dict",["inner","sKey"],({inner:e,sKey:t})=>`{ [key: ${t.toString()}]: ${e.toString()} }`);k("tuple",["list"],({list:e})=>`[${e.map(t=>t.toString()).join(", ")}]`);k("object",["dict"],({dict:e})=>Object.keys(e).length===0?"{}":`{ ${Object.entries(e).map(([t,r])=>`${t}${r.meta.required?"":"?"}: ${r.toString()}`).join(", ")} }`);k("union",["list"],({list:e},t)=>{let r=e.map(({toString:n})=>n()).join(" | ");return t?`(${r})`:r});k("intersect",["list"],({list:e})=>`${e.map(t=>t.toString(!0)).join(" & ")}`);k("transform",["inner","callback","preserve"],({inner:e},t)=>e.toString(t));var wt=class{sn=0;map=new Map;weak=new WeakMap;get length(){return this.map.size}push(e){let t=++this.sn;return this.map.set(t,e),this.weak.set(e,t),()=>this.map.delete(t)}delete(e){let t=this.weak.get(e);return t?this.map.delete(t):!1}clear(){let e=[...this.map.values()];return this.map.clear(),e.reverse()}[Symbol.iterator](){return this.map.values()}[Symbol.for("nodejs.util.inspect.custom")](){return[...this]}},g={shadow:Symbol.for("cordis.shadow"),receiver:Symbol.for("cordis.receiver"),original:Symbol.for("cordis.original"),metadata:Symbol.for("cordis.metadata"),initHooks:Symbol.for("cordis.initHooks"),checkProto:Symbol.for("cordis.checkProto"),effect:Symbol.for("cordis.effect"),filter:Symbol.for("cordis.filter"),isolate:Symbol.for("cordis.isolate"),intercept:Symbol.for("cordis.intercept"),init:Symbol.for("cordis.init"),check:Symbol.for("cordis.check"),config:Symbol.for("cordis.config"),invoke:Symbol.for("cordis.invoke"),extend:Symbol.for("cordis.extend"),tracker:Symbol.for("cordis.tracker"),resolveConfig:Symbol.for("cordis.resolveConfig")},Tn=function*(){}.constructor,Kt=async function*(){}.constructor;function In(e){return!(!e.prototype||e instanceof Tn||Kt!==Function&&e instanceof Kt)}function vt(e,t){if(e===Object.prototype)return t;let r=Object.create(vt(Object.getPrototypeOf(e),t));for(let n of Reflect.ownKeys(e))Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(e,n));return r}function re(e){return e&&(typeof e=="object"||typeof e=="function")}function Dn(e,t){let r=e;for(;r;){let n=Reflect.getOwnPropertyDescriptor(r,t);if(n)return n;r=Object.getPrototypeOf(r)}}function Y(e,t){if(!re(t))return t;if(Object.hasOwn(t,g.shadow))return Object.getPrototypeOf(t);let r=t[g.tracker];return r?xt(e,t,r):t}function Ne(e,t){return t?new Proxy(e,{get:(r,n,o)=>n in t&&n!=="constructor"?Reflect.get(t,n,o):Reflect.get(r,n,o),set:(r,n,o,i)=>n in t&&n!=="constructor"?Reflect.set(t,n,o,i):Reflect.set(r,n,o,i)}):e}function lt(e,t,r){return Ne(e,Object.defineProperty(Object.create(null),t,{value:r,writable:!1}))}function Xe(e,t,r,n){if(!r)return n;let o=Reflect.getOwnPropertyDescriptor(t,r)?.value;return o?lt(n,r,e.extend({[g.shadow]:o})):n}function Mn(e,t,r,n){return new Proxy(t,{apply:(o,i,a)=>(i===r&&(i=n),Y(e,Reflect.apply(o,i,a)))})}function xt(e,t,r){e[g.shadow]&&!r.noShadow&&(e=Object.getPrototypeOf(e));let n=new Proxy(t,{get:(o,i,a)=>{if(i===g.original)return o;if(i===r.property)return e;if(typeof i=="symbol")return Reflect.get(o,i,a);if(r.associate&&e.reflect.props[`${r.associate}.${i}`])return Reflect.get(e,`${r.associate}.${i}`,lt(e,g.receiver,a));let s,l,c=Dn(o,i);c&&"value"in c?l=c.value:(s=Xe(e,o,r.property,a),l=Reflect.get(o,i,s));let u=l?.[g.tracker];return u?xt(e,l,u):!r.noShadow&&typeof l=="function"?(s??=Xe(e,o,r.property,a),Mn(e,l,a,s)):l},set:(o,i,a,s)=>{if(i===g.original||i===r.property)return!1;if(typeof i=="symbol")return Reflect.set(o,i,a,s);if(r.associate&&e.reflect.props[`${r.associate}.${i}`])return Reflect.set(e,`${r.associate}.${i}`,a,lt(e,g.receiver,s));let l=Xe(e,o,r.property,s);return Reflect.set(o,i,a,l)},apply:(o,i,a)=>xr(n,o,i,a)});return n}function xr(e,t,r,n){return t[g.invoke]?t[g.invoke].apply(e,n):Reflect.apply(t,r,n)}function ct(e,t,r){let n=function(...o){return xr(xt(n.ctx,n,r),n,this,o)};return q(n,"name",e),Object.setPrototypeOf(n,t)}function Vt(e,t,r){let n=e.error.stack.split(`
3
3
  `);if(typeof t?.stack!="string"){let a=new Error(t),s=a.stack.split(`
4
4
  `);throw s.splice(1,1/0,...r()),a.stack=s.join(`
5
5
  `),a}let o=t.stack.split(`
6
6
  `),i=o.indexOf(n[2]);if(i===-1)throw t;for(i-=e.offset;i>0&&o[i-1].endsWith(" (<anonymous>)");)i-=1;throw o.splice(i,1/0,...r()),t.stack=o.join(`
7
7
  `),t}function Xt(e,t=Ot()){let r={offset:1,error:new Error};try{let n=e(r);return re(n)&&"then"in n?n.then(void 0,o=>Vt(r,o,t)):n}catch(n){Vt(r,n,t)}}function Ot(e=0){let t=new Error;return()=>t.stack.split(`
8
- `).slice(3+e)}function Gt(e){return e!==null&&e!==!1&&e!==void 0}var Pn=class{ctx;_hooks={};constructor(e){this.ctx=e,q(this,g.tracker,{property:"ctx",noShadow:!0}),this.on("internal/listener",function(t,r,n){if(t==="internal/update"&&!n.global)return(this.fiber._hooks["internal/update"]??=new wt)[n.prepend?"unshift":"push"](r)}),this.on("internal/update",function(t,r,n){let o=[...this._hooks["internal/update"]||[]],i=()=>(o.shift()??n).call(this,t,r,i);return i()},{global:!0,prepend:!0})}dispatch(e,t){let r=typeof t[0]=="object"||typeof t[0]=="function"?t.shift():null,n=t.shift();n.startsWith("internal/")||this.emit("internal/dispatch",e,n,t,r);let o=r?.[Q.filter];return(this._hooks[n]||[]).filter(i=>i.global||!o||o.call(r,i.ctx)).map(i=>i.callback.bind(r))}async parallel(...e){let t=(await Promise.allSettled(this.dispatch("emit",e).map(async r=>r(...e)))).filter(r=>r.status==="rejected");if(t.length)throw new AggregateError(t.map(r=>r.reason))}emit(...e){this.dispatch("emit",e).map(t=>t(...e))}async serial(...e){for(let t of this.dispatch("serial",e)){let r=await t(...e);if(Gt(r))return r}}bail(...e){for(let t of this.dispatch("bail",e)){let r=t(...e);if(Gt(r))return r}}waterfall(...e){let t=this.dispatch("waterfall",e),r=e.pop(),n=()=>(t.shift()??r)(...e);return e.push(n),n()}register(e,t,r,n){let o=n.prepend?"unshift":"push";return this.ctx.fiber.effect(()=>(t[o]({ctx:this.ctx,callback:r,...n}),()=>this.unregister(t,r)),e)}unregister(e,t){let r=e.findIndex(n=>n.callback===t);if(r>=0)return e.splice(r,1),!0}on(e,t,r){typeof r!="object"&&(r={prepend:r}),this.ctx.fiber.assertActive(),t=this.ctx.reflect.bind(t);let n=this.bail(this.ctx,"internal/listener",e,t,r);if(n)return n;let o=this._hooks[e]||=[],i=`ctx.on(${typeof e=="string"?JSON.stringify(e):e.toString()})`;return this.register(i,o,t,r)}once(e,t,r){let n=this.on(e,function(...o){return n(),t.apply(this,o)},r);return n}},Yt={s:e=>String(e),d:e=>Math.trunc(Number(e)),i:e=>Math.trunc(Number(e)),f:e=>Number(e),o:e=>JSON.stringify(e),O:e=>JSON.stringify(e),c:()=>"",C:(e,t,r)=>ut.color(t,ut.code(r.name,t.colors),e)};function Fn(e){return e instanceof Error&&Array.isArray(e.errors)}var ut=class{service;static color(e,t,r,n=""){return e.colors?`\x1B[3${t<8?t:"8;5;"+t}${e.colors>=2?n:""}m${r}\x1B[0m`:""+r}static code(e,t){let r=0;for(let o=0;o<e.length;o++)r=(r<<3)-r+e.charCodeAt(o)+13,r|=0;let n=t?t>=2?Jn:qn:[];return n[Math.abs(r)%n.length]}static format(e,t){let r=t.args.slice();r[0]instanceof Error?(r[0]=r[0].stack||r[0].message,r.unshift("%s")):typeof r[0]!="string"&&r.unshift("%o");let n=r.shift();n=n.replace(/%([a-zA-Z%])/g,(a,s)=>{if(a==="%%")return"%";let l=e.formatters?.[s]??Yt[s];return typeof l=="function"?l(r.shift(),e,t):a});let o=e.formatters?.o??Yt.o;for(let a of r)typeof a=="object"&&a&&(a=o(a,e,t)),n+=" "+a;let{maxLength:i=10240}=e;return n.split(/\r?\n/g).map(a=>a.slice(0,i)+(a.length>i?"...":"")).join(`
9
- `)}constructor(e,t){this.service=t,Object.assign(this,e),this.error=this._method("error",0),this.info=this._method("info",1),this.warn=this._method("warn",2),this.debug=this._method("debug",3)}_method(e,t){return(...r)=>{if(r.length===1&&r[0]instanceof Error){if(r[0].cause)this[e](r[0].cause);else if(Fn(r[0])){r[0].errors.forEach(i=>this[e](i));return}}let n=++this.service._snMessage,o=Date.now();for(let i of this.service.exporters.values()){if((i.levels?.[this.name]??i.levels?.default??this.level??1)<t)continue;let a={sn:n,ts:o,type:e,level:t,name:this.name,...this.meta,args:r};i.export(a)}}}},qn=[6,2,3,4,5,1],Jn=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221],Wn=class Or{bufferSize=1e3;buffer=[];ctx;_snMessage=0;_snExporter=0;exporters=new Map;constructor(t){let r={property:"ctx",noShadow:!0},n=ct("logger",vt(Object.getPrototypeOf(this),Function.prototype),r);return Object.assign(n,this),n.ctx=t,q(n,g.tracker,r),n.exporter({colors:3,export:o=>{n.buffer.push(o),n.buffer.length>n.bufferSize&&(n.buffer=n.buffer.slice(-n.bufferSize))}}),n}exporter(t){return this.ctx.effect(()=>(this.exporters.set(++this._snExporter,t),()=>this.exporters.delete(this._snExporter)),"ctx.logger.exporter()")}_resolveConfig(){let t=this.ctx[g.intercept],r=[];for(;"logger"in t;)Object.hasOwn(t,"logger")&&r.unshift(t.logger),t=Object.getPrototypeOf(t);return Object.assign({},...r)}[g.invoke](t){let r=this._resolveConfig(),n=(this.ctx[g.shadow]??this.ctx).fiber;return t??=r.name,t??=An(n.name),new ut({name:t,level:r.level,meta:{fiber:new WeakRef(n)}},this)}static{for(let t of["error","info","warn","debug"])Or.prototype[t]=function(...r){return this()[t](...r)}}};function Ge(e){let t=e.stack.split(`
8
+ `).slice(3+e)}function Gt(e){return e!==null&&e!==!1&&e!==void 0}var Pn=class{ctx;_hooks={};constructor(e){this.ctx=e,q(this,g.tracker,{property:"ctx",noShadow:!0}),this.on("internal/listener",function(t,r,n){if(t==="internal/update"&&!n.global)return(this.fiber._hooks["internal/update"]??=new wt)[n.prepend?"unshift":"push"](r)}),this.on("internal/update",function(t,r,n){let o=[...this._hooks["internal/update"]||[]],i=()=>(o.shift()??n).call(this,t,r,i);return i()},{global:!0,prepend:!0})}dispatch(e,t){let r=typeof t[0]=="object"||typeof t[0]=="function"?t.shift():null,n=t.shift();n.startsWith("internal/")||this.emit("internal/dispatch",e,n,t,r);let o=r?.[Q.filter];return(this._hooks[n]||[]).filter(i=>i.global||!o||o.call(r,i.ctx)).map(i=>i.callback.bind(r))}async parallel(...e){let t=(await Promise.allSettled(this.dispatch("emit",e).map(async r=>r(...e)))).filter(r=>r.status==="rejected");if(t.length)throw new AggregateError(t.map(r=>r.reason))}emit(...e){this.dispatch("emit",e).map(t=>t(...e))}async serial(...e){for(let t of this.dispatch("serial",e)){let r=await t(...e);if(Gt(r))return r}}bail(...e){for(let t of this.dispatch("bail",e)){let r=t(...e);if(Gt(r))return r}}waterfall(...e){let t=this.dispatch("waterfall",e),r=e.pop(),n=()=>(t.shift()??r)(...e);return e.push(n),n()}register(e,t,r,n){let o=n.prepend?"unshift":"push";return this.ctx.fiber.effect(()=>(t[o]({ctx:this.ctx,callback:r,...n}),()=>this.unregister(t,r)),e)}unregister(e,t){let r=e.findIndex(n=>n.callback===t);if(r>=0)return e.splice(r,1),!0}on(e,t,r){typeof r!="object"&&(r={prepend:r}),this.ctx.fiber.assertActive(),t=this.ctx.reflect.bind(t);let n=this.bail(this.ctx,"internal/listener",e,t,r);if(n)return n;let o=this._hooks[e]||=[],i=`ctx.on(${typeof e=="string"?JSON.stringify(e):e.toString()})`;return this.register(i,o,t,r)}once(e,t,r){let n=this.on(e,function(...o){return n(),t.apply(this,o)},r);return n}},Yt={s:e=>String(e),d:e=>Math.trunc(Number(e)),i:e=>Math.trunc(Number(e)),f:e=>Number(e),o:e=>JSON.stringify(e),O:e=>JSON.stringify(e),c:()=>"",C:(e,t,r)=>ut.color(t,ut.code(r.name,t.colors),e)};function Fn(e){return e instanceof Error&&Array.isArray(e.errors)}var ut=class{service;static color(e,t,r,n=""){return e.colors?`\x1B[3${t<8?t:"8;5;"+t}${e.colors>=2?n:""}m${r}\x1B[0m`:""+r}static code(e,t){let r=0;for(let o=0;o<e.length;o++)r=(r<<3)-r+e.charCodeAt(o)+13,r|=0;let n=t?t>=2?Ln:qn:[];return n[Math.abs(r)%n.length]}static format(e,t){let r=t.args.slice();r[0]instanceof Error?(r[0]=r[0].stack||r[0].message,r.unshift("%s")):typeof r[0]!="string"&&r.unshift("%o");let n=r.shift();n=n.replace(/%([a-zA-Z%])/g,(a,s)=>{if(a==="%%")return"%";let l=e.formatters?.[s]??Yt[s];return typeof l=="function"?l(r.shift(),e,t):a});let o=e.formatters?.o??Yt.o;for(let a of r)typeof a=="object"&&a&&(a=o(a,e,t)),n+=" "+a;let{maxLength:i=10240}=e;return n.split(/\r?\n/g).map(a=>a.slice(0,i)+(a.length>i?"...":"")).join(`
9
+ `)}constructor(e,t){this.service=t,Object.assign(this,e),this.error=this._method("error",0),this.info=this._method("info",1),this.warn=this._method("warn",2),this.debug=this._method("debug",3)}_method(e,t){return(...r)=>{if(r.length===1&&r[0]instanceof Error){if(r[0].cause)this[e](r[0].cause);else if(Fn(r[0])){r[0].errors.forEach(i=>this[e](i));return}}let n=++this.service._snMessage,o=Date.now();for(let i of this.service.exporters.values()){if((i.levels?.[this.name]??i.levels?.default??this.level??1)<t)continue;let a={sn:n,ts:o,type:e,level:t,name:this.name,...this.meta,args:r};i.export(a)}}}},qn=[6,2,3,4,5,1],Ln=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221],Wn=class Or{bufferSize=1e3;buffer=[];ctx;_snMessage=0;_snExporter=0;exporters=new Map;constructor(t){let r={property:"ctx",noShadow:!0},n=ct("logger",vt(Object.getPrototypeOf(this),Function.prototype),r);return Object.assign(n,this),n.ctx=t,q(n,g.tracker,r),n.exporter({colors:3,export:o=>{n.buffer.push(o),n.buffer.length>n.bufferSize&&(n.buffer=n.buffer.slice(-n.bufferSize))}}),n}exporter(t){return this.ctx.effect(()=>(this.exporters.set(++this._snExporter,t),()=>this.exporters.delete(this._snExporter)),"ctx.logger.exporter()")}_resolveConfig(){let t=this.ctx[g.intercept],r=[];for(;"logger"in t;)Object.hasOwn(t,"logger")&&r.unshift(t.logger),t=Object.getPrototypeOf(t);return Object.assign({},...r)}[g.invoke](t){let r=this._resolveConfig(),n=(this.ctx[g.shadow]??this.ctx).fiber;return t??=r.name,t??=An(n.name),new ut({name:t,level:r.level,meta:{fiber:new WeakRef(n)}},this)}static{for(let t of["error","info","warn","debug"])Or.prototype[t]=function(...r){return this()[t](...r)}}};function Ge(e){let t=e.stack.split(`
10
10
  `);return t.splice(0,2,`Error: ${e.message}`),e.stack=t.join(`
11
- `),e}var Ln=["prototype","then"];function Ye(e){return typeof e=="symbol"||Ln.includes(e)||parseInt(e).toString()===e||e.startsWith("_")}var Qt=class{ctx;static handler={get:(e,t,r)=>{if(Ye(t))return Reflect.get(e,t,r);if(Reflect.has(e,t))return Y(r,Reflect.get(e,t,r));let n=new Error(`cannot get property "${t}" without inject`);try{let o=e.reflect.props[t];return o?.type==="accessor"?o.get.call(r,r[g.receiver],n):r.fiber.runtime?r.events.waterfall("internal/get",r,t,n,()=>{let i=e[g.isolate][t],a=(r[g.shadow]??r).fiber;for(;;){let s=a.store?.[t];if(s)return Y(r,s.value);if(t in a.inject)throw n.message=`cannot get required service "${t}" in inactive context`,n;if(!a.runtime||a.parent[g.isolate][t]!==i)throw n;a=a.parent.fiber}}):r.reflect.get(t,!1)}catch(o){throw o===n?Ge(o):o}},set:(e,t,r,n)=>{if(Ye(t))return Reflect.set(e,t,r,n);let o=new Error(`cannot set property "${t}" without provide`),i=e.reflect.props[t];if(!i){if(!n.fiber.runtime)return Reflect.set(e,t,r,n);throw Ge(o)}try{return i.type==="accessor"?i.set?i.set.call(n,r,n[g.receiver],o):!1:n.events.waterfall("internal/set",n,t,r,o,()=>n.reflect.set(t,r,o))}catch(a){throw a===o?Ge(a):a}},has:(e,t)=>Ye(t)?Reflect.has(e,t):Reflect.has(e,t)?!0:!!e.reflect.props[t]};store=Object.create(null);props=Object.create(null);constructor(e){this.ctx=e,q(this,g.tracker,{property:"ctx",noShadow:!0}),this.mixin("reflect",["get","set","provide","accessor","mixin"]),this.mixin("fiber",["runtime","effect"]),this.mixin("registry",["inject","plugin"]),this.mixin("events",["on","once","parallel","emit","serial","bail","waterfall"])}get(e,t=!0){return Y(this.ctx,this._getImpl(e,t)?.value)}_getImpl(e,t=!0){let r=this.ctx[g.isolate][e],n=r&&this.store[r];if(n&&!(t&&n.fiber.state!==2))return n}set(e,t,r){let n=this.ctx[g.isolate][e],o=this.store[n];if(!o)throw new Error(`cannot set property "${e}" without provide`);if(o.fiber!==this.ctx.fiber)throw new Error(`cannot set property "${e}" in multiple fibers`);return o.value=t,!0}provide(e,t,r){return this.ctx.fiber.effect(()=>{if(!this.props[e])this.props[e]??={type:"service"};else if(this.props[e].type!=="service")throw new Error(`property "${e}" is already declared as ${this.props[e].type}`);this.props[e]={type:"service"},this.ctx.root[g.isolate][e]??=Symbol(e);let n=this.ctx[g.isolate][e],o={name:e,value:t,fiber:this.ctx.fiber,check:r};if(this.store[n])throw new Error(`service "${e}" has been registered at <${this.store[n].fiber.name}>`);return this.store[n]=o,this.ctx.fiber.store[e]=o,this.ctx.fiber.state===2&&this.notify([e]),async()=>{delete this.store[n];let i=this.notify([e]);await Promise.allSettled(i.map(a=>a.await())),delete this.ctx.fiber.store[e]}},`ctx.provide(${JSON.stringify(e)})`)}notify(e,t=(r,n)=>r[g.isolate][n]===this.ctx[g.isolate][n]){let r=[];for(let n of this.ctx.registry.values())for(let o of n.fibers){let i=!1;for(let a of e)a in o.inject&&t(o.ctx,a)&&(i=!0,o._checkImpl(a));i&&(o._refresh(),r.push(o))}for(let n of e){let o=Object.create(this.ctx);o[g.filter]=i=>t(i,n),this.ctx.events.emit(o,"internal/service",n,this._getImpl(n,!1)?.value)}return r}accessor(e,t){return this.ctx.fiber.effect(()=>{if(e in this.props)throw new Error(`property "${e}" is already declared as ${this.props[e].type}`);return this.props[e]={type:"accessor",...t},()=>delete this.props[e]},`ctx.accessor(${JSON.stringify(e)})`)}mixin(e,t){let r=this;return this.ctx.fiber.effect(function*(){let n=Array.isArray(t)?t.map(i=>[i,i]):Object.entries(t),o=(i,a)=>i[e];for(let[i,a]of n)yield r.accessor(a,{get(s,l){let c=o(this,l);if(E(c))return c;let u=s?Ce(s,c):c,h=Reflect.get(c,i,u);return typeof h!="function"?h:h.bind(u??c)},set(s,l,c){let u=o(this,c),h=l?Ce(l,u):u;return Reflect.set(u,i,s,h)}})},`ctx.mixin(${JSON.stringify(e)})`)}trace(e){return Y(this.ctx,e)}bind(e){return new Proxy(e,{apply:(t,r,n)=>Reflect.apply(t,this.trace(r),n.map(o=>this.trace(o))),construct:(t,r,n)=>Reflect.construct(t,r.map(o=>this.trace(o)),n)})}},Bn=Symbol.for("ValidationError"),Sr=class extends TypeError{name="ValidationError";constructor(e){super(`invalid config:
11
+ `),e}var Jn=["prototype","then"];function Ye(e){return typeof e=="symbol"||Jn.includes(e)||parseInt(e).toString()===e||e.startsWith("_")}var Qt=class{ctx;static handler={get:(e,t,r)=>{if(Ye(t))return Reflect.get(e,t,r);if(Reflect.has(e,t))return Y(r,Reflect.get(e,t,r));let n=new Error(`cannot get property "${t}" without inject`);try{let o=e.reflect.props[t];return o?.type==="accessor"?o.get.call(r,r[g.receiver],n):r.fiber.runtime?r.events.waterfall("internal/get",r,t,n,()=>{let i=e[g.isolate][t],a=(r[g.shadow]??r).fiber;for(;;){let s=a.store?.[t];if(s)return Y(r,s.value);if(t in a.inject)throw n.message=`cannot get required service "${t}" in inactive context`,n;if(!a.runtime||a.parent[g.isolate][t]!==i)throw n;a=a.parent.fiber}}):r.reflect.get(t,!1)}catch(o){throw o===n?Ge(o):o}},set:(e,t,r,n)=>{if(Ye(t))return Reflect.set(e,t,r,n);let o=new Error(`cannot set property "${t}" without provide`),i=e.reflect.props[t];if(!i){if(!n.fiber.runtime)return Reflect.set(e,t,r,n);throw Ge(o)}try{return i.type==="accessor"?i.set?i.set.call(n,r,n[g.receiver],o):!1:n.events.waterfall("internal/set",n,t,r,o,()=>n.reflect.set(t,r,o))}catch(a){throw a===o?Ge(a):a}},has:(e,t)=>Ye(t)?Reflect.has(e,t):Reflect.has(e,t)?!0:!!e.reflect.props[t]};store=Object.create(null);props=Object.create(null);constructor(e){this.ctx=e,q(this,g.tracker,{property:"ctx",noShadow:!0}),this.mixin("reflect",["get","set","provide","accessor","mixin"]),this.mixin("fiber",["runtime","effect"]),this.mixin("registry",["inject","plugin"]),this.mixin("events",["on","once","parallel","emit","serial","bail","waterfall"])}get(e,t=!0){return Y(this.ctx,this._getImpl(e,t)?.value)}_getImpl(e,t=!0){let r=this.ctx[g.isolate][e],n=r&&this.store[r];if(n&&!(t&&n.fiber.state!==2))return n}set(e,t,r){let n=this.ctx[g.isolate][e],o=this.store[n];if(!o)throw new Error(`cannot set property "${e}" without provide`);if(o.fiber!==this.ctx.fiber)throw new Error(`cannot set property "${e}" in multiple fibers`);return o.value=t,!0}provide(e,t,r){return this.ctx.fiber.effect(()=>{if(!this.props[e])this.props[e]??={type:"service"};else if(this.props[e].type!=="service")throw new Error(`property "${e}" is already declared as ${this.props[e].type}`);this.props[e]={type:"service"},this.ctx.root[g.isolate][e]??=Symbol(e);let n=this.ctx[g.isolate][e],o={name:e,value:t,fiber:this.ctx.fiber,check:r};if(this.store[n])throw new Error(`service "${e}" has been registered at <${this.store[n].fiber.name}>`);return this.store[n]=o,this.ctx.fiber.store[e]=o,this.ctx.fiber.state===2&&this.notify([e]),async()=>{delete this.store[n];let i=this.notify([e]);await Promise.allSettled(i.map(a=>a.await())),delete this.ctx.fiber.store[e]}},`ctx.provide(${JSON.stringify(e)})`)}notify(e,t=(r,n)=>r[g.isolate][n]===this.ctx[g.isolate][n]){let r=[];for(let n of this.ctx.registry.values())for(let o of n.fibers){let i=!1;for(let a of e)a in o.inject&&t(o.ctx,a)&&(i=!0,o._checkImpl(a));i&&(o._refresh(),r.push(o))}for(let n of e){let o=Object.create(this.ctx);o[g.filter]=i=>t(i,n),this.ctx.events.emit(o,"internal/service",n,this._getImpl(n,!1)?.value)}return r}accessor(e,t){return this.ctx.fiber.effect(()=>{if(e in this.props)throw new Error(`property "${e}" is already declared as ${this.props[e].type}`);return this.props[e]={type:"accessor",...t},()=>delete this.props[e]},`ctx.accessor(${JSON.stringify(e)})`)}mixin(e,t){let r=this;return this.ctx.fiber.effect(function*(){let n=Array.isArray(t)?t.map(i=>[i,i]):Object.entries(t),o=(i,a)=>i[e];for(let[i,a]of n)yield r.accessor(a,{get(s,l){let c=o(this,l);if(E(c))return c;let u=s?Ne(s,c):c,h=Reflect.get(c,i,u);return typeof h!="function"?h:h.bind(u??c)},set(s,l,c){let u=o(this,c),h=l?Ne(l,u):u;return Reflect.set(u,i,s,h)}})},`ctx.mixin(${JSON.stringify(e)})`)}trace(e){return Y(this.ctx,e)}bind(e){return new Proxy(e,{apply:(t,r,n)=>Reflect.apply(t,this.trace(r),n.map(o=>this.trace(o))),construct:(t,r,n)=>Reflect.construct(t,r.map(o=>this.trace(o)),n)})}},Bn=Symbol.for("ValidationError"),Sr=class extends TypeError{name="ValidationError";constructor(e){super(`invalid config:
12
12
  `+e.map(t=>t.path?` - ${t.message} (at ${t.path.join(".")})`:` - ${t.message}`).join(`
13
- `))}};Object.defineProperty(Sr.prototype,Bn,{value:!0});function zn(e,t){if(!e.Config)return t;let r=e.Config["~standard"].validate(t);if("then"in r)throw new TypeError("Async config validation is not supported");if(r.issues)throw new Sr(r.issues);return r.value}var Er=new WeakMap;function Qe(e){let t=e();return Er.get(e)?.()??t}function Un(e,t){let r=["internal/plugin",t],n;try{n=e.events.dispatch("emit",r)}catch(o){e.logger.error(o);return}for(let o of n)try{let i=o(...r);Promise.resolve(i).catch(a=>e.logger.error(a))}catch(i){e.logger.error(i)}}var Te=class kr extends Error{code;constructor(t,r){super(r??kr.Code[t]),this.code=t}};(function(e){e.Code={INACTIVE_EFFECT:"cannot create effect on inactive context"}})(Te||(Te={}));var I="__INACTIVE__",jr=class{parent;inject;runtime;uid;ctx;config;_config;state=0;dispose;store;inertia;_hooks=Object.create(null);_disposables=new wt;context;_error;_runner;_store=Object.create(null);constructor(e,t,r,n,o){this.parent=e,this.inject=r,this.runtime=n,this._config=t;let i=a=>{this._disposables.push(a)};if(n){this.uid=e.registry.counter,this.ctx=this.context=e.extend({fiber:this});let a=Object.entries(this.inject);if(a.length){this.ctx[Q.intercept]=Object.create(e[Q.intercept]);for(let[s,l]of a)E(l)||(this.ctx[Q.intercept][s]=l)}this._runner={epoch:I,getOuterStack:o,execute:function(){if(Dn(n.callback)){let s=new n.callback(this.ctx,this.config);for(let l of s?.[g.initHooks]??[])l();return s?.[g.init]?.()}else return n.callback(this.ctx,this.config)},collect:i},this.dispose=e.fiber.effect(()=>{let s=n.fibers.push(this);return async()=>{for(this.uid=null,Un(this.context,this),this.ctx.registry.has(n.callback)&&(s(),n.fibers.length||this.ctx.registry.delete(n.callback)),this._setEpoch(I),this.inertia||this._updateState(()=>(this.inertia=this._unload(),5));this.inertia;)await this.inertia}},"ctx.plugin()");try{this.context.emit("internal/plugin",this)}catch(s){throw Promise.resolve(this.dispose()).catch(l=>this.ctx.logger.error(l)),s}if(this.uid!==null&&e.fiber.state!==5){for(let s of Object.keys(this.inject))this._checkImpl(s);this._refresh()}}else this.uid=0,this.ctx=this.context=e,this.state=2,this.store=Object.create(null),this._runner={epoch:"",getOuterStack:o,execute:()=>{},collect:i},this.dispose=()=>this.restart()}get name(){let e=this;do{if(e.runtime?.name)return e.runtime.name;e=e.parent.fiber}while(e!==e.parent.fiber);return"root"}assertActive(){if(this.uid===null)throw new Te("INACTIVE_EFFECT")}_execute(e){let t=e.epoch;return Xt(r=>{let n=i=>{if(typeof i=="function")e.collect(i);else if(!E(i))throw new TypeError("Invalid effect")},o=e.execute.call(this);if(typeof o=="function")return e.collect(o);if(!E(o))if(re(o)){if("then"in o)return o.then(n);if(Symbol.iterator in o){r.error=new Error;let i=o[Symbol.iterator]();for(;;){let a=i.next();if(n(a.value),a.done)return}}else if(Symbol.asyncIterator in o){let i=o[Symbol.asyncIterator]();return(async()=>{for(await Promise.resolve(),r.error=new Error;;){if(e.epoch!==t)return;let a=await i.next();if(n(a.value),a.done)return}})()}else throw new TypeError("Invalid effect")}else throw new TypeError("Invalid effect")},e.getOuterStack)}effect(e,t="anonymous"){if(this.assertActive(),this.state===5)throw new Te("INACTIVE_EFFECT");let r=[],n=!1,o,i=()=>{if(n)return o;n=!0;let v;for(let O of r.splice(0).reverse())if(v)v=v.then(()=>Qe(O));else{let A=Qe(O);re(A)&&"then"in A&&(v=A)}return o=v},a={label:t,children:[]},s={execute:e,epoch:!0,collect:v=>{r.push(v),this._disposables.delete(v),v[g.effect]&&a.children.push(v[g.effect])},getOuterStack:Ot()},l,c=!0,u,h,f,p=!1,m,y=()=>!1,j=()=>(f??=new Promise((v,O)=>{u=v,h=O}),f),D=v=>Promise.resolve(v).then(()=>i(),async O=>{throw await i(),O}),R=v=>{let O;try{O=v()}catch(A){throw y(),A}if(re(O)&&"then"in O){let A=Promise.resolve(O).finally(()=>{y(),m===A&&(m=void 0)});return m=A}return y(),O},K=q(()=>s.epoch?(s.epoch=!1,R(()=>c?D(j()):l?D(l):i())):p?m:void 0,g.effect,a);Er.set(K,()=>m),y=this._disposables.push(K);try{l=this._execute(s)}catch(v){c=!1,p=!0,s.epoch=!1;let O;try{O=R(i)}finally{h?.(v)}throw re(O)&&"then"in O&&O.catch(A=>this.ctx.logger.error(A)),v}c=!1,f&&Promise.resolve(l).then(u,h),l?.catch(()=>s.epoch?R(i):i()).catch(v=>this.ctx.logger.error(v));let te=()=>{if(s.epoch)return s.epoch=!1,R(i)};return K.then=async(v,O)=>Promise.resolve(l).then(()=>te).then(v,O),K}getEffects(){return[...this._disposables].map(e=>e[g.effect]).filter(Boolean)}_getState(){return this.uid===null?4:this._error?3:this._runner.epoch!==I?2:0}_updateState(e){let t=this.state;if(this.state=e()??this._getState(),t!==this.state&&(this.context.emit("internal/status",this,t),!(t!==2&&this.state!==2)))for(let r of Reflect.ownKeys(this.ctx.reflect.store)){let n=this.ctx.reflect.store[r];n.fiber===this&&this.ctx.reflect.notify([n.name])}}_checkImpl(e){let t=this.ctx.reflect._getImpl(e,!0);if(!t)return delete this._store[e];try{if(t.check&&!t.check.call(Y(this.ctx,t.value)))return delete this._store[e]}catch(r){return t.fiber.ctx.logger.error(r),delete this._store[e]}this._store[e]=t}_refresh(){let e=!1;e="";for(let t of Object.keys(this.inject)){let r=this._store[t];if(!r){e=I;break}e+=":"+r.fiber.uid}this._setEpoch(e)}_setEpoch(e){let t=this._runner.epoch;e!==t&&(this._runner.epoch=e,!this.inertia&&this._updateState(()=>e!==I&&t===I?(this.inertia=this._reload(),1):(this.inertia=this._unload(),5)))}_resolveConfig(e){return e=this.context.waterfall(this,"internal/config",e,()=>e),this.runtime?zn(this.runtime,e):e}async _reload(){this.store={...this._store};let e=this._runner.epoch;try{await Promise.resolve(),this._runner.epoch===e&&(this.config=this._resolveConfig(this._config),await this._execute(this._runner),this._error=void 0)}catch(t){this.ctx.logger.error(t),this._error=t,this._runner.epoch=I}this._updateState(()=>{if(this._runner.epoch===e)this.inertia=void 0;else return this.inertia=this._unload(),5})}async _unload(){await Promise.all(this._disposables.clear().map(async e=>{try{await Xt(async t=>{await Promise.resolve(),t.error=new Error,await Qe(e)},this._runner.getOuterStack)}catch(t){this.ctx.logger.error(t)}})),this.store=void 0,this._updateState(()=>{if(this._runner.epoch===I)this.inertia=void 0;else return this.inertia=this._reload(),1})}async await(){for(;this.inertia;)await this.inertia;if(this._error)throw this._error;return this}async restart(){this.assertActive(),this._setEpoch(I),this._refresh(),await this.await()}update(e,t=!1){if(this.assertActive(),this._config=e,this.state!==2){this._error=void 0,this._setEpoch(I),this._refresh();return}return e=this._resolveConfig(e),this.context.waterfall(this,"internal/update",e,t,()=>(this.config=e,this._error=void 0,this.restart()))}};function Hn(e){return e&&typeof e=="object"&&typeof e.apply=="function"}function dt(e,t){return function(r,n){if(n.kind==="class")Object.hasOwn(r,"inject")||(q(r,"inject",Object.create(Object.getPrototypeOf(r).inject??null)),q(r.inject,g.checkProto,!0)),r.inject[e]=t;else if(n.kind==="method"){let o=(r[g.metadata]??={}).inject??=Object.create(null);o[e]=t,n.addInitializer(function(){let i=this[g.tracker]?.property;(this[g.initHooks]??=[]).push(()=>{this.ctx.inject(o,a=>r.call(i?Ce(this,{[i]:a}):this))})})}else throw new Error("@Inject() can only be used on class or class methods")}}(function(e){function t(r,n=Object.create(null)){if(!r)return n;if(Array.isArray(r))for(let o of r)n[o]=null;else if(Reflect.has(r,g.checkProto)){Object.assign(n,t(Object.getPrototypeOf(r)));for(let o of Object.keys(r))n[o]=r[o]??null}else for(let o of Object.keys(r))n[o]=r[o]??null;return n}e.resolve=t})(dt||(dt={}));var Kn=class{ctx;_counter=0;_internal=new Map;constructor(e){this.ctx=e,q(this,g.tracker,{property:"ctx",noShadow:!0})}get counter(){return++this._counter}get size(){return this._internal.size}resolve(e){try{if(typeof e=="function")return e;if(Hn(e))return e.apply}catch{}}get(e){let t=this.resolve(e);return t&&this._internal.get(t)}has(e){let t=this.resolve(e);return!!t&&this._internal.has(t)}delete(e){let t=this.resolve(e),r=t&&this._internal.get(t);if(r){this._internal.delete(t);for(let n of r.fibers)n.dispose();return r}}keys(){return this._internal.keys()}values(){return this._internal.values()}entries(){return this._internal.entries()}forEach(e){return this._internal.forEach(e)}inject(e,t){return this.plugin({inject:e,apply:t,name:t.name})}plugin(e,t,r=Ot()){let n=this.resolve(e);if(!n)throw new Error('invalid plugin, expect function or object with an "apply" method, received '+typeof e);this.ctx.fiber.assertActive();let o=this._internal.get(n);if(!o){let s=e.name;s==="apply"&&(s=void 0),o={name:s,callback:n,fibers:new wt,Config:e.Config},this._internal.set(n,o)}let i=new jr(this.ctx,t,dt.resolve(e.inject),o,r),a=Object.create(i);return a.then=(s,l)=>i.await().then(s,l),a}},Q=class me{static effect=g.effect;static filter=g.filter;static isolate=g.isolate;static intercept=g.intercept;static is(t){return!!t?.[me.is]}static{me.is[Symbol.toPrimitive]=()=>Symbol.for("cordis.is"),me.prototype[me.is]=!0}constructor(){this[g.isolate]=Object.create(null),this[g.intercept]=Object.create(null);let t=new Proxy(this,Qt.handler);return this.root=t,this.baseUrl=void 0,this.fiber=new jr(t,{},Object.create(null),null,()=>[]),this.reflect=new Qt(t),this.registry=new Kn(t),this.events=new Pn(t),this.logger=new Wn(t),this.fiber._disposables.clear(),t}[Symbol.for("nodejs.util.inspect.custom")](){return`Context <${this.fiber.name}>`}extend(t={}){let r=Reflect.getOwnPropertyDescriptor(this,g.shadow)?.value,n=Object.create(Y(this,this));for(let o of Reflect.ownKeys(t))Object.defineProperty(n,o,Reflect.getOwnPropertyDescriptor(t,o));return r?Object.assign(Object.create(n),{[g.shadow]:r}):n}isolate(t,r){let n=Object.create(this[g.isolate]);return n[t]=r??Symbol(t),this.extend({[g.isolate]:n})}intercept(t,r){let n=Object.create(this[g.intercept]);return n[t]=r,this.extend({[g.intercept]:n})}},Vn=class $r{ctx;static init=g.init;static check=g.check;static config=g.config;static invoke=g.invoke;static extend=g.extend;static tracker=g.tracker;static resolveConfig=g.resolveConfig;name;constructor(t,r){this.ctx=t,r??=this.constructor.provide;let n=this,o={associate:r,property:"ctx"};return n[g.invoke]&&(n=ct(r,vt(Object.getPrototypeOf(this),Function.prototype),o)),n.ctx=t,n.name=r,q(n,g.tracker,o),n.ctx.reflect.provide(r,n,this[g.check]),n}[g.filter](t){return t[g.isolate][this.name]===this.ctx[g.isolate][this.name]}[g.extend](t){let r;return this[$r.invoke]?r=ct(this.name,this,this[g.tracker]):r=Object.create(this),Object.assign(r,t)}[g.resolveConfig](t,r){let n=this.ctx[Q.intercept],o=[];for(;this.name in n;)Object.hasOwn(n,this.name)&&o.unshift(n[this.name]),n=Object.getPrototypeOf(n);return t&&o.unshift(t),r&&o.push(r),this.Config?.merge?this.Config.merge(...o):Object.assign({},...o)}static[Symbol.hasInstance](t){if(!t)return!1;let r=t.constructor;for(;r;){if(r=r.prototype?.constructor,r===this)return!0;r&&=Object.getPrototypeOf(r)}return!1}},Xn=class{duplicateError;data=new Map;constructor(e){this.duplicateError=e}insert(e,t){let r=this.data;if(r.has(e))throw this.duplicateError(e);r.set(e,t);let n=!0;return()=>{n&&(n=!1,r.delete(e),r.size===0&&this.data===r&&(this.data=new Map))}}get(e){return this.data.get(e)}has(e){return this.data.has(e)}keys(){return this.data.keys()}entries(){return this.data.entries()}values(){return this.data.values()}isEmpty(){return this.data.size===0}},Zt=class{data=new Map;append(e){let t=this.data,r=Symbol();t.set(r,e);let n=!0;return()=>{n&&(n=!1,t.delete(r),t.size===0&&this.data===t&&(this.data=new Map))}}values(){return this.data.values()}isEmpty(){return this.data.size===0}},Gn=class{createLayer;onChange;global;scoped=new Map;constructor(e,t){this.createLayer=e,this.onChange=t,this.global=e(void 0)}peek(e){if(e!==void 0)return this.scoped.get(e)}chainLayers(e){let t=[];for(let r of Zn(e).reverse()){let n=this.scoped.get(r);n!==void 0&&t.push(n)}return t}merge(e,t){let r=new Map(t(this.global).entries());for(let n of this.chainLayers(e))for(let[o,i]of t(n).entries())r.set(o,i);return r}effect(e,t,r){let n=De(e),o=r.notify??!0;return e.effect(function*(){let i,a=!1;if(n===void 0)i=this.global;else{let l=this.scoped.get(n);l===void 0?(i=this.createLayer(n),this.scoped.set(n,i),a=!0):i=l}let s;try{s=t(i)}catch(l){throw n!==void 0&&a&&i.isEmpty()&&this.scoped.delete(n),l}yield()=>{s(),n!==void 0&&i.isEmpty()&&this.scoped.delete(n),o&&this.onChange()},o&&this.onChange()}.bind(this),r.label)}},Yn=Symbol("dsh.scope"),Qn=new WeakMap,_r=new WeakMap;function Zn(e){let t=[];for(let r=e;r!==void 0;r=_r.get(r))t.push(r);return t}function De(e){return e[Yn]}function ue(e,t){let r=e[Q.filter],n={[Q.filter](o){if(r!==void 0&&!r.call(e,o))return!1;let i=De(o);if(i===void 0)return!0;for(let a=t;a!==void 0;a=_r.get(a))if(a===i)return!0;return!1}};return Qn.set(n,t),n}var er=2147483647;function ge(e){let t=new WeakSet,r=[{kind:"visit",node:e}];for(;r.length>0;){let n=r.pop();if(n===void 0)continue;if(n.kind==="property"){r.push({kind:"visit",node:n.source[n.key]});continue}let o=n.node;if(o===null||typeof o!="object"||o instanceof AbortSignal||t.has(o))continue;t.add(o),Object.freeze(o);let i=Object.keys(o);for(let a=i.length-1;a>=0;a--){let s=i[a];s!==void 0&&r.push({kind:"property",source:o,key:s})}}return e}function eo(e){return ge(structuredClone(e))}function to(e){return eo({...e,id:crypto.randomUUID()})}function Rr(e){return to({...e,role:"user"})}var oe=class extends Error{code;constructor(e,t,r){super(e,r),this.code=t,this.name=new.target.name}},ro="EMPTY_RESPONSE",gs=new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]`+String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`,"i"),ys=new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?`+String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?`+String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`,"i"),bs=new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}`+String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}`+String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`,"i"),no=2,oo=500,io=1e4,so=.1,ao=Object.freeze([ro,"RATE_LIMIT","SERVER","TIMEOUT","TRANSPORT"]),Ar=d.object({initialDelayMs:d.number().max(er).default(oo),maxDelayMs:d.number().max(er).default(io),jitterRatio:d.number().min(0).max(1).default(so)}),lo=d.object({mode:d.const("normal").required(),maxRetries:d.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(no),retryableCodes:d.array(d.string()).default([...ao]),backoff:Ar}),co=d.object({mode:d.const("always").required(),backoff:Ar}),ws=d.union([lo,co]),{version:vs}={version:"0.0.1-rc.1"};function ye(e,t){let r=JSON.stringify(e)??String(e);throw new Error(`unreachable variant${t?` in ${t}`:""}: ${r}`)}function Nr(e,t){let r=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(typeof r!="function")return!1;try{return r.name===t&&r.prototype===e&&Function.prototype.toString.call(r)===`function ${t}() { [native code] }`}catch{return!1}}function Cr(e){return Object.getPrototypeOf(e)===null&&Nr(e,"Object")}function uo(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Nr(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&Cr(r)}function po(e){let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Cr(t)}function fo(e){let t=Reflect.ownKeys(e);if(!t.some(r=>typeof r!="string"||!Object.prototype.propertyIsEnumerable.call(e,r)))return t}function Tr(e,t){let r=new Set,n,o=(a,s)=>{a!==void 0&&(a.kind==="root"?n=s:a.kind==="array"?a.target[a.index]=s:Object.defineProperty(a.target,a.key,{value:s,enumerable:!0,configurable:!0,writable:!0}))},i=[{kind:"visit",value:e,...t?{destination:{kind:"root"}}:{}}];for(let a=i.pop();a!==void 0;a=i.pop()){if(a.kind==="leave"){r.delete(a.source);continue}if(a.kind==="array-item"){if(!Object.prototype.hasOwnProperty.call(a.source,a.index))return;i.push({kind:"visit",value:a.source[a.index],...a.target===void 0?{}:{destination:{kind:"array",target:a.target,index:a.index}}});continue}if(a.kind==="object-property"){i.push({kind:"visit",value:a.source[a.key],...a.target===void 0?{}:{destination:{kind:"object",target:a.target,key:a.key}}});continue}let s=a.value;if(s===null){o(a.destination,null);continue}if(typeof s=="boolean"||typeof s=="string"){o(a.destination,s);continue}if(typeof s=="number"){if(!Number.isFinite(s)||Object.is(s,-0))return;o(a.destination,s);continue}if(typeof s!="object"||r.has(s))return;if(Array.isArray(s)){if(!uo(s))return;let u=s.length;if(Reflect.ownKeys(s).length!==u+1)return;let h=t?[]:void 0;h!==void 0&&o(a.destination,h),r.add(s),i.push({kind:"leave",source:s});for(let f=u-1;f>=0;f--)i.push({kind:"array-item",source:s,index:f,...h===void 0?{}:{target:h}});continue}if(!po(s))return;let l=fo(s);if(l===void 0)return;let c=t?{}:void 0;c!==void 0&&o(a.destination,c),r.add(s),i.push({kind:"leave",source:s});for(let u=l.length-1;u>=0;u--){let h=l[u];if(h===void 0)return;i.push({kind:"object-property",source:s,key:h,...c===void 0?{}:{target:c}})}}return t?n:!0}function H(e){return Tr(e,!0)}function Dr(e){return Tr(e,!1)===!0}var Ir=class extends oe{violations;constructor(e){super(`unsupported JSON schema: ${e.join("; ")}`,"UNSUPPORTED_SCHEMA"),this.name="JsonSchemaError",this.violations=e}},ho=new Set(["type","oneOf","properties","required","additionalProperties","items","enum","const"]),mo=new Set(["description","title","default","examples"]),pt=["object","array","string","number","integer","boolean","null"];function Mr(e,t){let r=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(typeof r!="function")return!1;try{return r.name===t&&r.prototype===e&&Function.prototype.toString.call(r)===`function ${t}() { [native code] }`}catch{return!1}}function Pr(e){return Object.getPrototypeOf(e)===null&&Mr(e,"Object")}function Fr(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Pr(t)}catch{return!1}}function go(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Mr(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&Pr(r)}function yo(e){try{return Reflect.ownKeys(e).every(t=>typeof t=="string"&&Object.prototype.propertyIsEnumerable.call(e,t))}catch{return!1}}function ne(e){return Fr(e)&&yo(e)}function be(e){if(!Array.isArray(e))return!1;try{if(!go(e)||Reflect.ownKeys(e).length!==e.length+1)return!1;for(let t=0;t<e.length;t++)if(!Object.hasOwn(e,t))return!1;return!0}catch{return!1}}function Ie(e){return typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0)}function tr(e,t){switch(e){case"string":return typeof t=="string";case"number":return Ie(t);case"integer":return Ie(t)&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;default:return ye(e,"JsonSchemaType")}}var rr=["properties","required","additionalProperties","items","enum","const"];function bo(e,t,r,n){let o=Object.hasOwn(e,"required"),i=o?e.required:void 0;if(o)if(!be(i)||i.some(a=>typeof a!="string"))n.push(`${t}.required must be an array of strings`);else{let a=ne(r)?r:{};for(let s of i)Object.hasOwn(a,s)||n.push(`${t}.required names "${s}" which is not in properties`)}Object.hasOwn(e,"additionalProperties")&&typeof e.additionalProperties!="boolean"&&n.push(`${t}.additionalProperties must be a boolean`)}function wo(e,t,r,n){let o=[{kind:"enter",node:e,path:t}];for(let i=o.pop();i!==void 0;i=o.pop()){if(i.kind==="leave"){n.delete(i.node);continue}if(i.kind==="one-of-tail"){for(let f of rr)Object.hasOwn(i.node,f)&&r.push(`${i.path}.${f} is not supported beside oneOf`);continue}if(i.kind==="object-tail"){bo(i.node,i.path,i.properties,r);continue}let{node:a,path:s}=i;if(!ne(a)){r.push(`${s} must be a schema object`);continue}if(n.has(a)){r.push(`${s} is circular`);continue}n.add(a),o.push({kind:"leave",node:a});for(let f of Object.keys(a))if(!ho.has(f)){if(mo.has(f)){try{Dr(a[f])||r.push(`${s}.${f} annotation must be lossless JSON data`)}catch{r.push(`${s}.${f} annotation must be lossless JSON data`)}continue}r.push(`${s}.${f} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`)}Object.hasOwn(a,"description")&&typeof a.description!="string"&&r.push(`${s}.description must be a string`),Object.hasOwn(a,"title")&&typeof a.title!="string"&&r.push(`${s}.title must be a string`);let l=Object.hasOwn(a,"type"),c=Object.hasOwn(a,"oneOf");if(l&&c){r.push(`${s} cannot declare both type and oneOf`);continue}if(!l&&!c){for(let f of rr)Object.hasOwn(a,f)&&r.push(`${s}.${f} requires type or oneOf`);continue}if(c){let f=a.oneOf;if(o.push({kind:"one-of-tail",node:a,path:s}),!be(f)||f.length<2)r.push(`${s}.oneOf must be an array of at least two schemas`);else for(let p=f.length-1;p>=0;p--)o.push({kind:"enter",node:f[p],path:`${s}.oneOf[${p}]`});continue}let u=a.type;if(typeof u!="string"||!pt.includes(u)){r.push(Array.isArray(u)?`${s}.type must be a single type string (type arrays are not supported)`:`${s}.type must be one of ${pt.join("/")}`);continue}let h=u;for(let[f,p]of Object.entries({properties:["object"],required:["object"],additionalProperties:["object"],items:["array"],enum:["string","number","integer","boolean","null"],const:["string","number","integer","boolean","null"]}))Object.hasOwn(a,f)&&!p.includes(h)&&r.push(`${s}.${f} is not supported on type "${h}"`);switch(h){case"object":{let f=Object.hasOwn(a,"properties")?a.properties:void 0;if(o.push({kind:"object-tail",node:a,path:s,properties:f}),Object.hasOwn(a,"properties"))if(!ne(f))r.push(`${s}.properties must be an object of schemas`);else{let p=Object.entries(f);for(let m=p.length-1;m>=0;m--){let y=p[m];y!==void 0&&o.push({kind:"enter",node:y[1],path:`${s}.properties.${y[0]}`})}}break}case"array":Object.hasOwn(a,"items")&&o.push({kind:"enter",node:a.items,path:`${s}.items`});break;case"string":case"number":case"integer":case"boolean":case"null":{let f=Object.hasOwn(a,"enum"),p=f?a.enum:void 0,m=be(p)&&p.length>0&&p.every(R=>tr(h,R));f&&!m&&r.push(`${s}.enum must be a non-empty array of ${h} values`);let y=Object.hasOwn(a,"const"),j=y?a.const:void 0,D=tr(h,j);y&&(D?m&&!p.includes(j)&&r.push(`${s}.const must be one of ${s}.enum when both are declared`):r.push(`${s}.const must be a ${h} value`));break}default:ye(h,"JsonSchemaType")}}}function xe(e){let t=[];if(wo(e,"schema",t,new Set),t.length>0)throw new Ir(t)}function Ze(e){try{return Dr(e)}catch{return!1}}function $(e){return e===""?"arguments":e}function et(e,t){return e===""?t:`${e}.${t}`}function tt(e){return[`"${$(e)}" must be a lossless JSON value`]}function nr(e,t){for(let r of t)e.push(r)}function or(e,t,r){return{node:e,value:t,path:r,catches:!1,phase:"start",children:[],childIndex:0,violations:[],tailViolations:[],matches:0}}function de(e,t,r){let n=Object.hasOwn(e,"enum")?e.enum:void 0;return n!==void 0&&!n.includes(t)?[`"${$(r)}" must be one of ${JSON.stringify(n)}`]:Object.hasOwn(e,"const")&&t!==e.const?[`"${$(r)}" must be ${JSON.stringify(e.const)}`]:[]}function vo(e,t,r){let n=[or(e,t,r)],o,i=s=>{let l=n.at(-1);if(l===void 0){o=s;return}l.kind==="oneOf"?s.length===0&&l.matches++:nr(l.violations,s)},a=s=>{n.pop(),i(s)};for(;n.length>0;){let s=n.at(-1);if(s===void 0)break;try{if(s.phase==="children"){if(s.childIndex<s.children.length){let u=s.children[s.childIndex];if(u===void 0)throw new Error("missing schema-value child frame");s.childIndex++,n.push(or(u.node,u.value,u.path));continue}if(s.kind==="oneOf"){a(s.matches===1?[]:[`"${$(s.path)}" must match exactly one oneOf branch (matched ${s.matches})`]);continue}nr(s.violations,s.tailViolations),s.violations.length>0?a(s.violations):s.kind==="object"?a(Ze(s.value)?[]:[`"${$(s.path)}" must be a lossless JSON object`]):a(Ze(s.value)?[]:[`"${$(s.path)}" must be a dense lossless JSON array`]);continue}let l=Object.hasOwn(s.node,"type")?s.node.type:void 0;s.catches=!(l!==void 0&&!pt.includes(l));let c=Object.hasOwn(s.node,"oneOf")?s.node.oneOf:void 0;if(c!==void 0){s.kind="oneOf",s.children=Array.from(c,u=>({node:u,value:s.value,path:s.path})),s.childIndex=0,s.matches=0,s.phase="children";continue}if(l===void 0){a(Ze(s.value)?[]:tt(s.path));continue}switch(l){case"object":{if(!Fr(s.value)){a([`"${$(s.path)}" must be an object`]);break}let u=Object.hasOwn(s.node,"properties")?s.node.properties??{}:{},h=[],f=Object.hasOwn(s.node,"required")?s.node.required??[]:[];for(let y of f)(!Object.hasOwn(s.value,y)||s.value[y]===void 0)&&h.push(`missing required property "${et(s.path,y)}"`);let p=[];for(let[y,j]of Object.entries(u))!Object.hasOwn(s.value,y)||s.value[y]===void 0||p.push({node:j,value:s.value[y],path:et(s.path,y)});let m=[];if(Object.hasOwn(s.node,"additionalProperties")&&s.node.additionalProperties===!1)for(let y of Object.keys(s.value))Object.hasOwn(u,y)||m.push(`"${et(s.path,y)}" is not a declared property (additionalProperties: false)`);s.kind="object",s.children=p,s.childIndex=0,s.violations=h,s.tailViolations=m,s.phase="children";break}case"array":{if(!Array.isArray(s.value)){a([`"${$(s.path)}" must be an array`]);break}let u=Object.hasOwn(s.node,"items")?s.node.items:void 0,h=u===void 0?[]:s.value.flatMap((f,p)=>[{node:u,value:f,path:`${s.path}[${p}]`}]);s.kind="array",s.children=h,s.childIndex=0,s.violations=[],s.phase="children";break}case"string":a(typeof s.value=="string"?de(s.node,s.value,s.path):[`"${$(s.path)}" must be a string`]);break;case"number":a(typeof s.value!="number"?[`"${$(s.path)}" must be a number`]:Ie(s.value)?de(s.node,s.value,s.path):[`"${$(s.path)}" must be a finite JSON number`]);break;case"integer":a(!Ie(s.value)||!Number.isInteger(s.value)?[`"${$(s.path)}" must be an integer`]:de(s.node,s.value,s.path));break;case"boolean":a(typeof s.value=="boolean"?de(s.node,s.value,s.path):[`"${$(s.path)}" must be a boolean`]);break;case"null":a(s.value===null?de(s.node,s.value,s.path):[`"${$(s.path)}" must be null`]);break;default:a(ye(l,"JsonSchemaType"))}}catch(l){let c=n.pop();for(;c!==void 0&&!c.catches;)c=n.pop();if(c===void 0)throw l;i(tt(c.path))}}return o??tt(r)}function qr(e,t,r="value"){return vo(e,t,r)}var xo=["description","title","default","examples"];function _(e){throw new Ir([e])}function pe(e,t){Object.hasOwn(e,"description")&&(t.description=e.description),Object.hasOwn(e,"title")&&(t.title=e.title),Object.hasOwn(e,"default")&&(t.default=e.default),Object.hasOwn(e,"examples")&&(t.examples=e.examples)}function fe(e,t,r){for(let n of Object.keys(e))r.includes(n)||_(`${t}.${n} is not supported by the value schema DSL`)}function Oo(e,t){switch(e.kind){case"root":e.holder.value=t;break;case"property":Object.defineProperty(e.target,e.key,{value:t,enumerable:!0,configurable:!0,writable:!0});break;case"item":e.target.items=t;break;case"one-of":e.target[e.index]=t;break}}function So(e,t){e.kind==="root"?e.holder.value=t:e.target.properties=t.properties}function Jr(e){let t=new Set,r=[e];for(let n=r.pop();n!==void 0;n=r.pop()){if(n.kind==="leave"){t.delete(n.input);continue}if(n.kind==="property-map-tail"){n.required.length>0&&(n.compiled.required=n.required,n.destination.kind==="object"&&(n.destination.target.required=n.required));continue}if(n.kind==="property"){ne(n.property)||_(`${n.path} must be a value schema object`),Object.hasOwn(n.property,"required")&&n.property.required!==!0&&_(`${n.path}.required must be true when present`),Object.hasOwn(n.property,"required")&&n.property.required===!0&&n.required.push(n.key),r.push({kind:"value",input:n.property,path:n.path,allowRequired:!0,destination:{kind:"property",target:n.properties,key:n.key}});continue}if(n.kind==="property-map"){ne(n.input)||_(`${n.path} must be an object of value schemas`),t.has(n.input)&&_(`${n.path} is circular`),t.add(n.input);let c={properties:{}},u=[];So(n.destination,c),r.push({kind:"leave",input:n.input}),r.push({kind:"property-map-tail",compiled:c,required:u,destination:n.destination});let h=Object.entries(n.input);for(let f=h.length-1;f>=0;f--){let p=h[f];p!==void 0&&r.push({kind:"property",property:p[1],path:`${n.path}.${p[0]}`,key:p[0],properties:c.properties,required:u})}continue}let{input:o,path:i}=n;ne(o)||_(`${i} must be a value schema object`),t.has(o)&&_(`${i} is circular`),t.add(o);let a=[...xo,...n.allowRequired?["required"]:[]],s={};if(Oo(n.destination,s),r.push({kind:"leave",input:o}),Object.hasOwn(o,"oneOf")){fe(o,i,[...a,"oneOf","type"]),Object.hasOwn(o,"type")&&_(`${i} cannot declare both type and oneOf`),be(o.oneOf)||_(`${i}.oneOf must be an array of at least two value schemas`);let c=[];s.oneOf=c,pe(o,s);for(let u=o.oneOf.length-1;u>=0;u--)r.push({kind:"value",input:o.oneOf[u],path:`${i}.oneOf[${u}]`,allowRequired:!1,destination:{kind:"one-of",target:c,index:u}});continue}let l=Object.hasOwn(o,"type")?o.type:void 0;switch(l){case"json":fe(o,i,[...a,"type"]),pe(o,s);break;case"object":fe(o,i,[...a,"type","properties","additionalProperties"]),(!Object.hasOwn(o,"additionalProperties")||typeof o.additionalProperties!="boolean")&&_(`${i}.additionalProperties must be explicitly true or false`),s.type="object",pe(o,s),s.additionalProperties=o.additionalProperties,Object.hasOwn(o,"properties")&&r.push({kind:"property-map",input:o.properties,path:`${i}.properties`,destination:{kind:"object",target:s}});break;case"array":fe(o,i,[...a,"type","items"]),s.type="array",pe(o,s),Object.hasOwn(o,"items")&&r.push({kind:"value",input:o.items,path:`${i}.items`,allowRequired:!1,destination:{kind:"item",target:s}});break;case"string":case"number":case"integer":case"boolean":case"null":fe(o,i,[...a,"type","enum","const"]),s.type=l,pe(o,s),Object.hasOwn(o,"enum")&&(be(o.enum)||_(`${i}.enum must be a non-empty array of scalar values`),s.enum=Array.from(o.enum,c=>c)),Object.hasOwn(o,"const")&&(s.const=o.const);break;default:_(`${i}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`)}}}function Eo(e,t){let r={};return Jr({kind:"property-map",input:e,path:t,destination:{kind:"root",holder:r}}),r.value??_(`${t} did not compile`)}function ko(e,t){let r={};return Jr({kind:"value",input:e,path:t,allowRequired:!1,destination:{kind:"root",holder:r}}),r.value??_(`${t} did not compile`)}function jo(e){let t=ko(e,"schema");return xe(t),t}function Wr(e){let t=Eo(e,"parameters"),r={type:"object",properties:t.properties,...t.required===void 0?{}:{required:t.required}};return xe(r),r}var $o=class extends oe{violations;constructor(e){super(`invalid arguments: ${e.join("; ")}`,"INVALID_ARGS"),this.name="ToolArgsError",this.violations=e}};function St(e){let t=e.execute,r=e.finalizeContent,n=e.output.render,o=e.output.presentationMeta,i=e.presentCall,a=e.presentResult,s=e.isConcurrencySafe;if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0))throw new Error(`defineTool(${e.name}): timeoutMs must be a positive finite number`);let l=Wr(e.parameters),c=jo(e.output.schema),u=f=>qr(l,f,""),h={name:e.name,description:e.description,parameters:l,output:{schema:c,render(f,p){return n(f,p)},...o!==void 0?{presentationMeta(f,p){return o(f,p)}}:{}},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},async execute(f,p){let m=u(f);if(m.length>0)throw new $o(m);return t(f,p)}};return r&&(h.finalizeContent=(f,p)=>r(f,p)),i&&(h.presentCall=f=>{if(!(u(f).length>0))return i(f)}),a&&(h.presentResult=(f,p)=>{if(!(u(f).length>0))return a(f,p)}),s&&(h.isConcurrencySafe=f=>u(f).length>0?!1:s(f)),h}var B="run_code",Me={description:"Execute a TypeScript program against the available tools. Write the BODY of an async function (erasable syntax only; top-level `await` and `return` work) and call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return comes back \u2014 curate it.",codeDescription:"The program: the body of an async TypeScript function."},rt={typescript:Me,python:{description:"Execute a Python program against the available tools. Write the BODY of an async function (top-level `await` and `return` work) and call tools as `await tools.name(args)` per the declarations in the system prompt. Answer with `print(...)` and/or `return <value>` \u2014 only that comes back, so curate it.",codeDescription:"The program: the body of an async Python function."}},ir='Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: "Count TODO markers across packages"; "Read failing test and its fixture"; "Rename config key in every cordis.yml".';function sr(e){let t=e();if(t===void 0)return Me;let r=rt[t.language];if(!Object.hasOwn(rt,t.language)||r===void 0){let n=Object.keys(rt).map(o=>JSON.stringify(o)).join(", ");throw new Error(`dsh-tools: no run_code schema flavor registered for runtime language ${JSON.stringify(t.language)} (known: ${n})`)}return r}var _o=class extends oe{constructor(e){super(e,"CODE_RUN_FAILED"),this.name="CodeRunFailedError"}};function Ro(e){let t;try{t=H(e)}catch(n){throw new Error(`tool arguments must be lossless JSON: ${n instanceof Error?n.message:String(n)}`)}if(t===void 0)throw new Error("tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)");let r=H(t);if(r===void 0)throw new Error("tool arguments could not be detached for durable logging");return{dispatched:t,logged:r}}var Ae=" ",Ao=10;function No(e){let t=[],r=[{kind:"value",value:e,depth:0,compact:!1}];for(let n=r.pop();n!==void 0;n=r.pop()){if(n.kind==="text"){t.push(n.text);continue}let o=n.value;if(o===null||typeof o=="boolean"||typeof o=="number"){t.push(String(o));continue}if(typeof o=="string"){t.push(JSON.stringify(o));continue}let i=n.compact||(n.depth+1)*2>Ao,a=n.depth+1;if(Array.isArray(o)){if(t.push("["),o.length===0){t.push("]");continue}r.push({kind:"text",text:i?"]":`
13
+ `))}};Object.defineProperty(Sr.prototype,Bn,{value:!0});function Un(e,t){if(!e.Config)return t;let r=e.Config["~standard"].validate(t);if("then"in r)throw new TypeError("Async config validation is not supported");if(r.issues)throw new Sr(r.issues);return r.value}var Er=new WeakMap;function Qe(e){let t=e();return Er.get(e)?.()??t}function zn(e,t){let r=["internal/plugin",t],n;try{n=e.events.dispatch("emit",r)}catch(o){e.logger.error(o);return}for(let o of n)try{let i=o(...r);Promise.resolve(i).catch(a=>e.logger.error(a))}catch(i){e.logger.error(i)}}var Te=class kr extends Error{code;constructor(t,r){super(r??kr.Code[t]),this.code=t}};(function(e){e.Code={INACTIVE_EFFECT:"cannot create effect on inactive context"}})(Te||(Te={}));var D="__INACTIVE__",jr=class{parent;inject;runtime;uid;ctx;config;_config;state=0;dispose;store;inertia;_hooks=Object.create(null);_disposables=new wt;context;_error;_runner;_store=Object.create(null);constructor(e,t,r,n,o){this.parent=e,this.inject=r,this.runtime=n,this._config=t;let i=a=>{this._disposables.push(a)};if(n){this.uid=e.registry.counter,this.ctx=this.context=e.extend({fiber:this});let a=Object.entries(this.inject);if(a.length){this.ctx[Q.intercept]=Object.create(e[Q.intercept]);for(let[s,l]of a)E(l)||(this.ctx[Q.intercept][s]=l)}this._runner={epoch:D,getOuterStack:o,execute:function(){if(In(n.callback)){let s=new n.callback(this.ctx,this.config);for(let l of s?.[g.initHooks]??[])l();return s?.[g.init]?.()}else return n.callback(this.ctx,this.config)},collect:i},this.dispose=e.fiber.effect(()=>{let s=n.fibers.push(this);return async()=>{for(this.uid=null,zn(this.context,this),this.ctx.registry.has(n.callback)&&(s(),n.fibers.length||this.ctx.registry.delete(n.callback)),this._setEpoch(D),this.inertia||this._updateState(()=>(this.inertia=this._unload(),5));this.inertia;)await this.inertia}},"ctx.plugin()");try{this.context.emit("internal/plugin",this)}catch(s){throw Promise.resolve(this.dispose()).catch(l=>this.ctx.logger.error(l)),s}if(this.uid!==null&&e.fiber.state!==5){for(let s of Object.keys(this.inject))this._checkImpl(s);this._refresh()}}else this.uid=0,this.ctx=this.context=e,this.state=2,this.store=Object.create(null),this._runner={epoch:"",getOuterStack:o,execute:()=>{},collect:i},this.dispose=()=>this.restart()}get name(){let e=this;do{if(e.runtime?.name)return e.runtime.name;e=e.parent.fiber}while(e!==e.parent.fiber);return"root"}assertActive(){if(this.uid===null)throw new Te("INACTIVE_EFFECT")}_execute(e){let t=e.epoch;return Xt(r=>{let n=i=>{if(typeof i=="function")e.collect(i);else if(!E(i))throw new TypeError("Invalid effect")},o=e.execute.call(this);if(typeof o=="function")return e.collect(o);if(!E(o))if(re(o)){if("then"in o)return o.then(n);if(Symbol.iterator in o){r.error=new Error;let i=o[Symbol.iterator]();for(;;){let a=i.next();if(n(a.value),a.done)return}}else if(Symbol.asyncIterator in o){let i=o[Symbol.asyncIterator]();return(async()=>{for(await Promise.resolve(),r.error=new Error;;){if(e.epoch!==t)return;let a=await i.next();if(n(a.value),a.done)return}})()}else throw new TypeError("Invalid effect")}else throw new TypeError("Invalid effect")},e.getOuterStack)}effect(e,t="anonymous"){if(this.assertActive(),this.state===5)throw new Te("INACTIVE_EFFECT");let r=[],n=!1,o,i=()=>{if(n)return o;n=!0;let v;for(let O of r.splice(0).reverse())if(v)v=v.then(()=>Qe(O));else{let A=Qe(O);re(A)&&"then"in A&&(v=A)}return o=v},a={label:t,children:[]},s={execute:e,epoch:!0,collect:v=>{r.push(v),this._disposables.delete(v),v[g.effect]&&a.children.push(v[g.effect])},getOuterStack:Ot()},l,c=!0,u,h,f,p=!1,m,y=()=>!1,j=()=>(f??=new Promise((v,O)=>{u=v,h=O}),f),I=v=>Promise.resolve(v).then(()=>i(),async O=>{throw await i(),O}),R=v=>{let O;try{O=v()}catch(A){throw y(),A}if(re(O)&&"then"in O){let A=Promise.resolve(O).finally(()=>{y(),m===A&&(m=void 0)});return m=A}return y(),O},K=q(()=>s.epoch?(s.epoch=!1,R(()=>c?I(j()):l?I(l):i())):p?m:void 0,g.effect,a);Er.set(K,()=>m),y=this._disposables.push(K);try{l=this._execute(s)}catch(v){c=!1,p=!0,s.epoch=!1;let O;try{O=R(i)}finally{h?.(v)}throw re(O)&&"then"in O&&O.catch(A=>this.ctx.logger.error(A)),v}c=!1,f&&Promise.resolve(l).then(u,h),l?.catch(()=>s.epoch?R(i):i()).catch(v=>this.ctx.logger.error(v));let te=()=>{if(s.epoch)return s.epoch=!1,R(i)};return K.then=async(v,O)=>Promise.resolve(l).then(()=>te).then(v,O),K}getEffects(){return[...this._disposables].map(e=>e[g.effect]).filter(Boolean)}_getState(){return this.uid===null?4:this._error?3:this._runner.epoch!==D?2:0}_updateState(e){let t=this.state;if(this.state=e()??this._getState(),t!==this.state&&(this.context.emit("internal/status",this,t),!(t!==2&&this.state!==2)))for(let r of Reflect.ownKeys(this.ctx.reflect.store)){let n=this.ctx.reflect.store[r];n.fiber===this&&this.ctx.reflect.notify([n.name])}}_checkImpl(e){let t=this.ctx.reflect._getImpl(e,!0);if(!t)return delete this._store[e];try{if(t.check&&!t.check.call(Y(this.ctx,t.value)))return delete this._store[e]}catch(r){return t.fiber.ctx.logger.error(r),delete this._store[e]}this._store[e]=t}_refresh(){let e=!1;e="";for(let t of Object.keys(this.inject)){let r=this._store[t];if(!r){e=D;break}e+=":"+r.fiber.uid}this._setEpoch(e)}_setEpoch(e){let t=this._runner.epoch;e!==t&&(this._runner.epoch=e,!this.inertia&&this._updateState(()=>e!==D&&t===D?(this.inertia=this._reload(),1):(this.inertia=this._unload(),5)))}_resolveConfig(e){return e=this.context.waterfall(this,"internal/config",e,()=>e),this.runtime?Un(this.runtime,e):e}async _reload(){this.store={...this._store};let e=this._runner.epoch;try{await Promise.resolve(),this._runner.epoch===e&&(this.config=this._resolveConfig(this._config),await this._execute(this._runner),this._error=void 0)}catch(t){this.ctx.logger.error(t),this._error=t,this._runner.epoch=D}this._updateState(()=>{if(this._runner.epoch===e)this.inertia=void 0;else return this.inertia=this._unload(),5})}async _unload(){await Promise.all(this._disposables.clear().map(async e=>{try{await Xt(async t=>{await Promise.resolve(),t.error=new Error,await Qe(e)},this._runner.getOuterStack)}catch(t){this.ctx.logger.error(t)}})),this.store=void 0,this._updateState(()=>{if(this._runner.epoch===D)this.inertia=void 0;else return this.inertia=this._reload(),1})}async await(){for(;this.inertia;)await this.inertia;if(this._error)throw this._error;return this}async restart(){this.assertActive(),this._setEpoch(D),this._refresh(),await this.await()}update(e,t=!1){if(this.assertActive(),this._config=e,this.state!==2){this._error=void 0,this._setEpoch(D),this._refresh();return}return e=this._resolveConfig(e),this.context.waterfall(this,"internal/update",e,t,()=>(this.config=e,this._error=void 0,this.restart()))}};function Hn(e){return e&&typeof e=="object"&&typeof e.apply=="function"}function dt(e,t){return function(r,n){if(n.kind==="class")Object.hasOwn(r,"inject")||(q(r,"inject",Object.create(Object.getPrototypeOf(r).inject??null)),q(r.inject,g.checkProto,!0)),r.inject[e]=t;else if(n.kind==="method"){let o=(r[g.metadata]??={}).inject??=Object.create(null);o[e]=t,n.addInitializer(function(){let i=this[g.tracker]?.property;(this[g.initHooks]??=[]).push(()=>{this.ctx.inject(o,a=>r.call(i?Ne(this,{[i]:a}):this))})})}else throw new Error("@Inject() can only be used on class or class methods")}}(function(e){function t(r,n=Object.create(null)){if(!r)return n;if(Array.isArray(r))for(let o of r)n[o]=null;else if(Reflect.has(r,g.checkProto)){Object.assign(n,t(Object.getPrototypeOf(r)));for(let o of Object.keys(r))n[o]=r[o]??null}else for(let o of Object.keys(r))n[o]=r[o]??null;return n}e.resolve=t})(dt||(dt={}));var Kn=class{ctx;_counter=0;_internal=new Map;constructor(e){this.ctx=e,q(this,g.tracker,{property:"ctx",noShadow:!0})}get counter(){return++this._counter}get size(){return this._internal.size}resolve(e){try{if(typeof e=="function")return e;if(Hn(e))return e.apply}catch{}}get(e){let t=this.resolve(e);return t&&this._internal.get(t)}has(e){let t=this.resolve(e);return!!t&&this._internal.has(t)}delete(e){let t=this.resolve(e),r=t&&this._internal.get(t);if(r){this._internal.delete(t);for(let n of r.fibers)n.dispose();return r}}keys(){return this._internal.keys()}values(){return this._internal.values()}entries(){return this._internal.entries()}forEach(e){return this._internal.forEach(e)}inject(e,t){return this.plugin({inject:e,apply:t,name:t.name})}plugin(e,t,r=Ot()){let n=this.resolve(e);if(!n)throw new Error('invalid plugin, expect function or object with an "apply" method, received '+typeof e);this.ctx.fiber.assertActive();let o=this._internal.get(n);if(!o){let s=e.name;s==="apply"&&(s=void 0),o={name:s,callback:n,fibers:new wt,Config:e.Config},this._internal.set(n,o)}let i=new jr(this.ctx,t,dt.resolve(e.inject),o,r),a=Object.create(i);return a.then=(s,l)=>i.await().then(s,l),a}},Q=class me{static effect=g.effect;static filter=g.filter;static isolate=g.isolate;static intercept=g.intercept;static is(t){return!!t?.[me.is]}static{me.is[Symbol.toPrimitive]=()=>Symbol.for("cordis.is"),me.prototype[me.is]=!0}constructor(){this[g.isolate]=Object.create(null),this[g.intercept]=Object.create(null);let t=new Proxy(this,Qt.handler);return this.root=t,this.baseUrl=void 0,this.fiber=new jr(t,{},Object.create(null),null,()=>[]),this.reflect=new Qt(t),this.registry=new Kn(t),this.events=new Pn(t),this.logger=new Wn(t),this.fiber._disposables.clear(),t}[Symbol.for("nodejs.util.inspect.custom")](){return`Context <${this.fiber.name}>`}extend(t={}){let r=Reflect.getOwnPropertyDescriptor(this,g.shadow)?.value,n=Object.create(Y(this,this));for(let o of Reflect.ownKeys(t))Object.defineProperty(n,o,Reflect.getOwnPropertyDescriptor(t,o));return r?Object.assign(Object.create(n),{[g.shadow]:r}):n}isolate(t,r){let n=Object.create(this[g.isolate]);return n[t]=r??Symbol(t),this.extend({[g.isolate]:n})}intercept(t,r){let n=Object.create(this[g.intercept]);return n[t]=r,this.extend({[g.intercept]:n})}},Vn=class $r{ctx;static init=g.init;static check=g.check;static config=g.config;static invoke=g.invoke;static extend=g.extend;static tracker=g.tracker;static resolveConfig=g.resolveConfig;name;constructor(t,r){this.ctx=t,r??=this.constructor.provide;let n=this,o={associate:r,property:"ctx"};return n[g.invoke]&&(n=ct(r,vt(Object.getPrototypeOf(this),Function.prototype),o)),n.ctx=t,n.name=r,q(n,g.tracker,o),n.ctx.reflect.provide(r,n,this[g.check]),n}[g.filter](t){return t[g.isolate][this.name]===this.ctx[g.isolate][this.name]}[g.extend](t){let r;return this[$r.invoke]?r=ct(this.name,this,this[g.tracker]):r=Object.create(this),Object.assign(r,t)}[g.resolveConfig](t,r){let n=this.ctx[Q.intercept],o=[];for(;this.name in n;)Object.hasOwn(n,this.name)&&o.unshift(n[this.name]),n=Object.getPrototypeOf(n);return t&&o.unshift(t),r&&o.push(r),this.Config?.merge?this.Config.merge(...o):Object.assign({},...o)}static[Symbol.hasInstance](t){if(!t)return!1;let r=t.constructor;for(;r;){if(r=r.prototype?.constructor,r===this)return!0;r&&=Object.getPrototypeOf(r)}return!1}},Xn=class{duplicateError;data=new Map;constructor(e){this.duplicateError=e}insert(e,t){let r=this.data;if(r.has(e))throw this.duplicateError(e);r.set(e,t);let n=!0;return()=>{n&&(n=!1,r.delete(e),r.size===0&&this.data===r&&(this.data=new Map))}}get(e){return this.data.get(e)}has(e){return this.data.has(e)}keys(){return this.data.keys()}entries(){return this.data.entries()}values(){return this.data.values()}isEmpty(){return this.data.size===0}},Zt=class{data=new Map;append(e){let t=this.data,r=Symbol();t.set(r,e);let n=!0;return()=>{n&&(n=!1,t.delete(r),t.size===0&&this.data===t&&(this.data=new Map))}}values(){return this.data.values()}isEmpty(){return this.data.size===0}},Gn=class{createLayer;onChange;global;scoped=new Map;constructor(e,t){this.createLayer=e,this.onChange=t,this.global=e(void 0)}peek(e){if(e!==void 0)return this.scoped.get(e)}chainLayers(e){let t=[];for(let r of Zn(e).reverse()){let n=this.scoped.get(r);n!==void 0&&t.push(n)}return t}merge(e,t){let r=new Map(t(this.global).entries());for(let n of this.chainLayers(e))for(let[o,i]of t(n).entries())r.set(o,i);return r}effect(e,t,r){let n=Ie(e),o=r.notify??!0;return e.effect(function*(){let i,a=!1;if(n===void 0)i=this.global;else{let l=this.scoped.get(n);l===void 0?(i=this.createLayer(n),this.scoped.set(n,i),a=!0):i=l}let s;try{s=t(i)}catch(l){throw n!==void 0&&a&&i.isEmpty()&&this.scoped.delete(n),l}yield()=>{s(),n!==void 0&&i.isEmpty()&&this.scoped.delete(n),o&&this.onChange()},o&&this.onChange()}.bind(this),r.label)}},Yn=Symbol("dsh.scope"),Qn=new WeakMap,_r=new WeakMap;function Zn(e){let t=[];for(let r=e;r!==void 0;r=_r.get(r))t.push(r);return t}function Ie(e){return e[Yn]}function ue(e,t){let r=e[Q.filter],n={[Q.filter](o){if(r!==void 0&&!r.call(e,o))return!1;let i=Ie(o);if(i===void 0)return!0;for(let a=t;a!==void 0;a=_r.get(a))if(a===i)return!0;return!1}};return Qn.set(n,t),n}var er=2147483647;function ge(e){let t=new WeakSet,r=[{kind:"visit",node:e}];for(;r.length>0;){let n=r.pop();if(n===void 0)continue;if(n.kind==="property"){r.push({kind:"visit",node:n.source[n.key]});continue}let o=n.node;if(o===null||typeof o!="object"||o instanceof AbortSignal||t.has(o))continue;t.add(o),Object.freeze(o);let i=Object.keys(o);for(let a=i.length-1;a>=0;a--){let s=i[a];s!==void 0&&r.push({kind:"property",source:o,key:s})}}return e}function eo(e){return ge(structuredClone(e))}function to(e){return eo({...e,id:crypto.randomUUID()})}function Rr(e){return to({...e,role:"user"})}var oe=class extends Error{code;constructor(e,t,r){super(e,r),this.code=t,this.name=new.target.name}},ro="EMPTY_RESPONSE",gs=new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]`+String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`,"i"),ys=new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?`+String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?`+String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`,"i"),bs=new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}`+String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}`+String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`,"i"),no=2,oo=500,io=1e4,so=.1,ao=Object.freeze([ro,"RATE_LIMIT","SERVER","TIMEOUT","TRANSPORT"]),Ar=d.object({initialDelayMs:d.number().max(er).default(oo),maxDelayMs:d.number().max(er).default(io),jitterRatio:d.number().min(0).max(1).default(so)}),lo=d.object({mode:d.const("normal").required(),maxRetries:d.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(no),retryableCodes:d.array(d.string()).default([...ao]),backoff:Ar}),co=d.object({mode:d.const("always").required(),backoff:Ar}),ws=d.union([lo,co]),{version:vs}={version:"0.0.1-rc.1"};function ye(e,t){let r=JSON.stringify(e)??String(e);throw new Error(`unreachable variant${t?` in ${t}`:""}: ${r}`)}function Cr(e,t){let r=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(typeof r!="function")return!1;try{return r.name===t&&r.prototype===e&&Function.prototype.toString.call(r)===`function ${t}() { [native code] }`}catch{return!1}}function Nr(e){return Object.getPrototypeOf(e)===null&&Cr(e,"Object")}function uo(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Cr(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&Nr(r)}function po(e){let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Nr(t)}function fo(e){let t=Reflect.ownKeys(e);if(!t.some(r=>typeof r!="string"||!Object.prototype.propertyIsEnumerable.call(e,r)))return t}function Tr(e,t){let r=new Set,n,o=(a,s)=>{a!==void 0&&(a.kind==="root"?n=s:a.kind==="array"?a.target[a.index]=s:Object.defineProperty(a.target,a.key,{value:s,enumerable:!0,configurable:!0,writable:!0}))},i=[{kind:"visit",value:e,...t?{destination:{kind:"root"}}:{}}];for(let a=i.pop();a!==void 0;a=i.pop()){if(a.kind==="leave"){r.delete(a.source);continue}if(a.kind==="array-item"){if(!Object.prototype.hasOwnProperty.call(a.source,a.index))return;i.push({kind:"visit",value:a.source[a.index],...a.target===void 0?{}:{destination:{kind:"array",target:a.target,index:a.index}}});continue}if(a.kind==="object-property"){i.push({kind:"visit",value:a.source[a.key],...a.target===void 0?{}:{destination:{kind:"object",target:a.target,key:a.key}}});continue}let s=a.value;if(s===null){o(a.destination,null);continue}if(typeof s=="boolean"||typeof s=="string"){o(a.destination,s);continue}if(typeof s=="number"){if(!Number.isFinite(s)||Object.is(s,-0))return;o(a.destination,s);continue}if(typeof s!="object"||r.has(s))return;if(Array.isArray(s)){if(!uo(s))return;let u=s.length;if(Reflect.ownKeys(s).length!==u+1)return;let h=t?[]:void 0;h!==void 0&&o(a.destination,h),r.add(s),i.push({kind:"leave",source:s});for(let f=u-1;f>=0;f--)i.push({kind:"array-item",source:s,index:f,...h===void 0?{}:{target:h}});continue}if(!po(s))return;let l=fo(s);if(l===void 0)return;let c=t?{}:void 0;c!==void 0&&o(a.destination,c),r.add(s),i.push({kind:"leave",source:s});for(let u=l.length-1;u>=0;u--){let h=l[u];if(h===void 0)return;i.push({kind:"object-property",source:s,key:h,...c===void 0?{}:{target:c}})}}return t?n:!0}function H(e){return Tr(e,!0)}function Ir(e){return Tr(e,!1)===!0}var Dr=class extends oe{violations;constructor(e){super(`unsupported JSON schema: ${e.join("; ")}`,"UNSUPPORTED_SCHEMA"),this.name="JsonSchemaError",this.violations=e}},ho=new Set(["type","oneOf","properties","required","additionalProperties","items","enum","const"]),mo=new Set(["description","title","default","examples"]),pt=["object","array","string","number","integer","boolean","null"];function Mr(e,t){let r=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(typeof r!="function")return!1;try{return r.name===t&&r.prototype===e&&Function.prototype.toString.call(r)===`function ${t}() { [native code] }`}catch{return!1}}function Pr(e){return Object.getPrototypeOf(e)===null&&Mr(e,"Object")}function Fr(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Pr(t)}catch{return!1}}function go(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Mr(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&Pr(r)}function yo(e){try{return Reflect.ownKeys(e).every(t=>typeof t=="string"&&Object.prototype.propertyIsEnumerable.call(e,t))}catch{return!1}}function ne(e){return Fr(e)&&yo(e)}function be(e){if(!Array.isArray(e))return!1;try{if(!go(e)||Reflect.ownKeys(e).length!==e.length+1)return!1;for(let t=0;t<e.length;t++)if(!Object.hasOwn(e,t))return!1;return!0}catch{return!1}}function De(e){return typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0)}function tr(e,t){switch(e){case"string":return typeof t=="string";case"number":return De(t);case"integer":return De(t)&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;default:return ye(e,"JsonSchemaType")}}var rr=["properties","required","additionalProperties","items","enum","const"];function bo(e,t,r,n){let o=Object.hasOwn(e,"required"),i=o?e.required:void 0;if(o)if(!be(i)||i.some(a=>typeof a!="string"))n.push(`${t}.required must be an array of strings`);else{let a=ne(r)?r:{};for(let s of i)Object.hasOwn(a,s)||n.push(`${t}.required names "${s}" which is not in properties`)}Object.hasOwn(e,"additionalProperties")&&typeof e.additionalProperties!="boolean"&&n.push(`${t}.additionalProperties must be a boolean`)}function wo(e,t,r,n){let o=[{kind:"enter",node:e,path:t}];for(let i=o.pop();i!==void 0;i=o.pop()){if(i.kind==="leave"){n.delete(i.node);continue}if(i.kind==="one-of-tail"){for(let f of rr)Object.hasOwn(i.node,f)&&r.push(`${i.path}.${f} is not supported beside oneOf`);continue}if(i.kind==="object-tail"){bo(i.node,i.path,i.properties,r);continue}let{node:a,path:s}=i;if(!ne(a)){r.push(`${s} must be a schema object`);continue}if(n.has(a)){r.push(`${s} is circular`);continue}n.add(a),o.push({kind:"leave",node:a});for(let f of Object.keys(a))if(!ho.has(f)){if(mo.has(f)){try{Ir(a[f])||r.push(`${s}.${f} annotation must be lossless JSON data`)}catch{r.push(`${s}.${f} annotation must be lossless JSON data`)}continue}r.push(`${s}.${f} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`)}Object.hasOwn(a,"description")&&typeof a.description!="string"&&r.push(`${s}.description must be a string`),Object.hasOwn(a,"title")&&typeof a.title!="string"&&r.push(`${s}.title must be a string`);let l=Object.hasOwn(a,"type"),c=Object.hasOwn(a,"oneOf");if(l&&c){r.push(`${s} cannot declare both type and oneOf`);continue}if(!l&&!c){for(let f of rr)Object.hasOwn(a,f)&&r.push(`${s}.${f} requires type or oneOf`);continue}if(c){let f=a.oneOf;if(o.push({kind:"one-of-tail",node:a,path:s}),!be(f)||f.length<2)r.push(`${s}.oneOf must be an array of at least two schemas`);else for(let p=f.length-1;p>=0;p--)o.push({kind:"enter",node:f[p],path:`${s}.oneOf[${p}]`});continue}let u=a.type;if(typeof u!="string"||!pt.includes(u)){r.push(Array.isArray(u)?`${s}.type must be a single type string (type arrays are not supported)`:`${s}.type must be one of ${pt.join("/")}`);continue}let h=u;for(let[f,p]of Object.entries({properties:["object"],required:["object"],additionalProperties:["object"],items:["array"],enum:["string","number","integer","boolean","null"],const:["string","number","integer","boolean","null"]}))Object.hasOwn(a,f)&&!p.includes(h)&&r.push(`${s}.${f} is not supported on type "${h}"`);switch(h){case"object":{let f=Object.hasOwn(a,"properties")?a.properties:void 0;if(o.push({kind:"object-tail",node:a,path:s,properties:f}),Object.hasOwn(a,"properties"))if(!ne(f))r.push(`${s}.properties must be an object of schemas`);else{let p=Object.entries(f);for(let m=p.length-1;m>=0;m--){let y=p[m];y!==void 0&&o.push({kind:"enter",node:y[1],path:`${s}.properties.${y[0]}`})}}break}case"array":Object.hasOwn(a,"items")&&o.push({kind:"enter",node:a.items,path:`${s}.items`});break;case"string":case"number":case"integer":case"boolean":case"null":{let f=Object.hasOwn(a,"enum"),p=f?a.enum:void 0,m=be(p)&&p.length>0&&p.every(R=>tr(h,R));f&&!m&&r.push(`${s}.enum must be a non-empty array of ${h} values`);let y=Object.hasOwn(a,"const"),j=y?a.const:void 0,I=tr(h,j);y&&(I?m&&!p.includes(j)&&r.push(`${s}.const must be one of ${s}.enum when both are declared`):r.push(`${s}.const must be a ${h} value`));break}default:ye(h,"JsonSchemaType")}}}function xe(e){let t=[];if(wo(e,"schema",t,new Set),t.length>0)throw new Dr(t)}function Ze(e){try{return Ir(e)}catch{return!1}}function $(e){return e===""?"arguments":e}function et(e,t){return e===""?t:`${e}.${t}`}function tt(e){return[`"${$(e)}" must be a lossless JSON value`]}function nr(e,t){for(let r of t)e.push(r)}function or(e,t,r){return{node:e,value:t,path:r,catches:!1,phase:"start",children:[],childIndex:0,violations:[],tailViolations:[],matches:0}}function de(e,t,r){let n=Object.hasOwn(e,"enum")?e.enum:void 0;return n!==void 0&&!n.includes(t)?[`"${$(r)}" must be one of ${JSON.stringify(n)}`]:Object.hasOwn(e,"const")&&t!==e.const?[`"${$(r)}" must be ${JSON.stringify(e.const)}`]:[]}function vo(e,t,r){let n=[or(e,t,r)],o,i=s=>{let l=n.at(-1);if(l===void 0){o=s;return}l.kind==="oneOf"?s.length===0&&l.matches++:nr(l.violations,s)},a=s=>{n.pop(),i(s)};for(;n.length>0;){let s=n.at(-1);if(s===void 0)break;try{if(s.phase==="children"){if(s.childIndex<s.children.length){let u=s.children[s.childIndex];if(u===void 0)throw new Error("missing schema-value child frame");s.childIndex++,n.push(or(u.node,u.value,u.path));continue}if(s.kind==="oneOf"){a(s.matches===1?[]:[`"${$(s.path)}" must match exactly one oneOf branch (matched ${s.matches})`]);continue}nr(s.violations,s.tailViolations),s.violations.length>0?a(s.violations):s.kind==="object"?a(Ze(s.value)?[]:[`"${$(s.path)}" must be a lossless JSON object`]):a(Ze(s.value)?[]:[`"${$(s.path)}" must be a dense lossless JSON array`]);continue}let l=Object.hasOwn(s.node,"type")?s.node.type:void 0;s.catches=!(l!==void 0&&!pt.includes(l));let c=Object.hasOwn(s.node,"oneOf")?s.node.oneOf:void 0;if(c!==void 0){s.kind="oneOf",s.children=Array.from(c,u=>({node:u,value:s.value,path:s.path})),s.childIndex=0,s.matches=0,s.phase="children";continue}if(l===void 0){a(Ze(s.value)?[]:tt(s.path));continue}switch(l){case"object":{if(!Fr(s.value)){a([`"${$(s.path)}" must be an object`]);break}let u=Object.hasOwn(s.node,"properties")?s.node.properties??{}:{},h=[],f=Object.hasOwn(s.node,"required")?s.node.required??[]:[];for(let y of f)(!Object.hasOwn(s.value,y)||s.value[y]===void 0)&&h.push(`missing required property "${et(s.path,y)}"`);let p=[];for(let[y,j]of Object.entries(u))!Object.hasOwn(s.value,y)||s.value[y]===void 0||p.push({node:j,value:s.value[y],path:et(s.path,y)});let m=[];if(Object.hasOwn(s.node,"additionalProperties")&&s.node.additionalProperties===!1)for(let y of Object.keys(s.value))Object.hasOwn(u,y)||m.push(`"${et(s.path,y)}" is not a declared property (additionalProperties: false)`);s.kind="object",s.children=p,s.childIndex=0,s.violations=h,s.tailViolations=m,s.phase="children";break}case"array":{if(!Array.isArray(s.value)){a([`"${$(s.path)}" must be an array`]);break}let u=Object.hasOwn(s.node,"items")?s.node.items:void 0,h=u===void 0?[]:s.value.flatMap((f,p)=>[{node:u,value:f,path:`${s.path}[${p}]`}]);s.kind="array",s.children=h,s.childIndex=0,s.violations=[],s.phase="children";break}case"string":a(typeof s.value=="string"?de(s.node,s.value,s.path):[`"${$(s.path)}" must be a string`]);break;case"number":a(typeof s.value!="number"?[`"${$(s.path)}" must be a number`]:De(s.value)?de(s.node,s.value,s.path):[`"${$(s.path)}" must be a finite JSON number`]);break;case"integer":a(!De(s.value)||!Number.isInteger(s.value)?[`"${$(s.path)}" must be an integer`]:de(s.node,s.value,s.path));break;case"boolean":a(typeof s.value=="boolean"?de(s.node,s.value,s.path):[`"${$(s.path)}" must be a boolean`]);break;case"null":a(s.value===null?de(s.node,s.value,s.path):[`"${$(s.path)}" must be null`]);break;default:a(ye(l,"JsonSchemaType"))}}catch(l){let c=n.pop();for(;c!==void 0&&!c.catches;)c=n.pop();if(c===void 0)throw l;i(tt(c.path))}}return o??tt(r)}function qr(e,t,r="value"){return vo(e,t,r)}var xo=["description","title","default","examples"];function _(e){throw new Dr([e])}function pe(e,t){Object.hasOwn(e,"description")&&(t.description=e.description),Object.hasOwn(e,"title")&&(t.title=e.title),Object.hasOwn(e,"default")&&(t.default=e.default),Object.hasOwn(e,"examples")&&(t.examples=e.examples)}function fe(e,t,r){for(let n of Object.keys(e))r.includes(n)||_(`${t}.${n} is not supported by the value schema DSL`)}function Oo(e,t){switch(e.kind){case"root":e.holder.value=t;break;case"property":Object.defineProperty(e.target,e.key,{value:t,enumerable:!0,configurable:!0,writable:!0});break;case"item":e.target.items=t;break;case"one-of":e.target[e.index]=t;break}}function So(e,t){e.kind==="root"?e.holder.value=t:e.target.properties=t.properties}function Lr(e){let t=new Set,r=[e];for(let n=r.pop();n!==void 0;n=r.pop()){if(n.kind==="leave"){t.delete(n.input);continue}if(n.kind==="property-map-tail"){n.required.length>0&&(n.compiled.required=n.required,n.destination.kind==="object"&&(n.destination.target.required=n.required));continue}if(n.kind==="property"){ne(n.property)||_(`${n.path} must be a value schema object`),Object.hasOwn(n.property,"required")&&n.property.required!==!0&&_(`${n.path}.required must be true when present`),Object.hasOwn(n.property,"required")&&n.property.required===!0&&n.required.push(n.key),r.push({kind:"value",input:n.property,path:n.path,allowRequired:!0,destination:{kind:"property",target:n.properties,key:n.key}});continue}if(n.kind==="property-map"){ne(n.input)||_(`${n.path} must be an object of value schemas`),t.has(n.input)&&_(`${n.path} is circular`),t.add(n.input);let c={properties:{}},u=[];So(n.destination,c),r.push({kind:"leave",input:n.input}),r.push({kind:"property-map-tail",compiled:c,required:u,destination:n.destination});let h=Object.entries(n.input);for(let f=h.length-1;f>=0;f--){let p=h[f];p!==void 0&&r.push({kind:"property",property:p[1],path:`${n.path}.${p[0]}`,key:p[0],properties:c.properties,required:u})}continue}let{input:o,path:i}=n;ne(o)||_(`${i} must be a value schema object`),t.has(o)&&_(`${i} is circular`),t.add(o);let a=[...xo,...n.allowRequired?["required"]:[]],s={};if(Oo(n.destination,s),r.push({kind:"leave",input:o}),Object.hasOwn(o,"oneOf")){fe(o,i,[...a,"oneOf","type"]),Object.hasOwn(o,"type")&&_(`${i} cannot declare both type and oneOf`),be(o.oneOf)||_(`${i}.oneOf must be an array of at least two value schemas`);let c=[];s.oneOf=c,pe(o,s);for(let u=o.oneOf.length-1;u>=0;u--)r.push({kind:"value",input:o.oneOf[u],path:`${i}.oneOf[${u}]`,allowRequired:!1,destination:{kind:"one-of",target:c,index:u}});continue}let l=Object.hasOwn(o,"type")?o.type:void 0;switch(l){case"json":fe(o,i,[...a,"type"]),pe(o,s);break;case"object":fe(o,i,[...a,"type","properties","additionalProperties"]),(!Object.hasOwn(o,"additionalProperties")||typeof o.additionalProperties!="boolean")&&_(`${i}.additionalProperties must be explicitly true or false`),s.type="object",pe(o,s),s.additionalProperties=o.additionalProperties,Object.hasOwn(o,"properties")&&r.push({kind:"property-map",input:o.properties,path:`${i}.properties`,destination:{kind:"object",target:s}});break;case"array":fe(o,i,[...a,"type","items"]),s.type="array",pe(o,s),Object.hasOwn(o,"items")&&r.push({kind:"value",input:o.items,path:`${i}.items`,allowRequired:!1,destination:{kind:"item",target:s}});break;case"string":case"number":case"integer":case"boolean":case"null":fe(o,i,[...a,"type","enum","const"]),s.type=l,pe(o,s),Object.hasOwn(o,"enum")&&(be(o.enum)||_(`${i}.enum must be a non-empty array of scalar values`),s.enum=Array.from(o.enum,c=>c)),Object.hasOwn(o,"const")&&(s.const=o.const);break;default:_(`${i}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`)}}}function Eo(e,t){let r={};return Lr({kind:"property-map",input:e,path:t,destination:{kind:"root",holder:r}}),r.value??_(`${t} did not compile`)}function ko(e,t){let r={};return Lr({kind:"value",input:e,path:t,allowRequired:!1,destination:{kind:"root",holder:r}}),r.value??_(`${t} did not compile`)}function jo(e){let t=ko(e,"schema");return xe(t),t}function Wr(e){let t=Eo(e,"parameters"),r={type:"object",properties:t.properties,...t.required===void 0?{}:{required:t.required}};return xe(r),r}var $o=class extends oe{violations;constructor(e){super(`invalid arguments: ${e.join("; ")}`,"INVALID_ARGS"),this.name="ToolArgsError",this.violations=e}};function St(e){let t=e.execute,r=e.finalizeContent,n=e.output.render,o=e.output.presentationMeta,i=e.presentCall,a=e.presentResult,s=e.isConcurrencySafe;if(e.timeoutMs!==void 0&&(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0))throw new Error(`defineTool(${e.name}): timeoutMs must be a positive finite number`);let l=Wr(e.parameters),c=jo(e.output.schema),u=f=>qr(l,f,""),h={name:e.name,description:e.description,parameters:l,output:{schema:c,render(f,p){return n(f,p)},...o!==void 0?{presentationMeta(f,p){return o(f,p)}}:{}},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},async execute(f,p){let m=u(f);if(m.length>0)throw new $o(m);return t(f,p)}};return r&&(h.finalizeContent=(f,p)=>r(f,p)),i&&(h.presentCall=f=>{if(!(u(f).length>0))return i(f)}),a&&(h.presentResult=(f,p)=>{if(!(u(f).length>0))return a(f,p)}),s&&(h.isConcurrencySafe=f=>u(f).length>0?!1:s(f)),h}var B="run_code",Me={description:"Execute a TypeScript program against the available tools. Write the BODY of an async function (erasable syntax only; top-level `await` and `return` work) and call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return comes back \u2014 curate it.",codeDescription:"The program: the body of an async TypeScript function."},rt={typescript:Me,python:{description:"Execute a Python program against the available tools. Write the BODY of an async function (top-level `await` and `return` work) and call tools as `await tools.name(args)` per the declarations in the system prompt. Answer with `print(...)` and/or `return <value>` \u2014 only that comes back, so curate it.",codeDescription:"The program: the body of an async Python function."}},ir='Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: "Count TODO markers across packages"; "Read failing test and its fixture"; "Rename config key in every cordis.yml".';function sr(e){let t=e();if(t===void 0)return Me;let r=rt[t.language];if(!Object.hasOwn(rt,t.language)||r===void 0){let n=Object.keys(rt).map(o=>JSON.stringify(o)).join(", ");throw new Error(`dsh-tools: no run_code schema flavor registered for runtime language ${JSON.stringify(t.language)} (known: ${n})`)}return r}var _o=class extends oe{constructor(e){super(e,"CODE_RUN_FAILED"),this.name="CodeRunFailedError"}};function Ro(e){let t;try{t=H(e)}catch(n){throw new Error(`tool arguments must be lossless JSON: ${n instanceof Error?n.message:String(n)}`)}if(t===void 0)throw new Error("tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)");let r=H(t);if(r===void 0)throw new Error("tool arguments could not be detached for durable logging");return{dispatched:t,logged:r}}var Ae=" ",Ao=10;function Co(e){let t=[],r=[{kind:"value",value:e,depth:0,compact:!1}];for(let n=r.pop();n!==void 0;n=r.pop()){if(n.kind==="text"){t.push(n.text);continue}let o=n.value;if(o===null||typeof o=="boolean"||typeof o=="number"){t.push(String(o));continue}if(typeof o=="string"){t.push(JSON.stringify(o));continue}let i=n.compact||(n.depth+1)*2>Ao,a=n.depth+1;if(Array.isArray(o)){if(t.push("["),o.length===0){t.push("]");continue}r.push({kind:"text",text:i?"]":`
14
14
  ${Ae.repeat(n.depth)}]`});for(let l=o.length-1;l>=0;l--){let c=o[l];if(c===void 0)throw new Error("cannot render a sparse JSON array");r.push({kind:"value",value:c,depth:a,compact:i}),r.push({kind:"text",text:i?l===0?"":",":`${l===0?`
15
15
  `:`,
16
16
  `}${Ae.repeat(a)}`})}continue}let s=Object.keys(o);if(t.push("{"),s.length===0){t.push("}");continue}r.push({kind:"text",text:i?"}":`
17
17
  ${Ae.repeat(n.depth)}}`});for(let l=s.length-1;l>=0;l--){let c=s[l];if(c===void 0)throw new Error("cannot render a missing JSON object key");let u=o[c];if(u===void 0)throw new Error("cannot render an undefined JSON object property");r.push({kind:"value",value:u,depth:a,compact:i}),r.push({kind:"text",text:i?`${l===0?"":","}${JSON.stringify(c)}:`:`${l===0?`
18
18
  `:`,
19
- `}${Ae.repeat(a)}${JSON.stringify(c)}: `})}}return t.join("")}function Co(e){return typeof e=="string"?e:No(e)}function To(e,t){let{requireRuntime:r,peekRuntime:n,maxParallel:o,shapeDispatchLog:i}=t,a=St({name:B,description:Me.description,parameters:{code:{type:"string",required:!0,description:Me.codeDescription},description:{type:"string",required:!0,description:ir}},output:{schema:{type:"object",additionalProperties:!1,properties:{logs:{type:"array",required:!0,items:{type:"string"}},result:{type:"json"}}},render:(s,l)=>{let c=l.result===void 0?"":Co(l.result),u=[l.logs.join(`
19
+ `}${Ae.repeat(a)}${JSON.stringify(c)}: `})}}return t.join("")}function No(e){return typeof e=="string"?e:Co(e)}function To(e,t){let{requireRuntime:r,peekRuntime:n,maxParallel:o,shapeDispatchLog:i}=t,a=St({name:B,description:Me.description,parameters:{code:{type:"string",required:!0,description:Me.codeDescription},description:{type:"string",required:!0,description:ir}},output:{schema:{type:"object",additionalProperties:!1,properties:{logs:{type:"array",required:!0,items:{type:"string"}},result:{type:"json"}}},render:(s,l)=>{let c=l.result===void 0?"":No(l.result),u=[l.logs.join(`
20
20
  `),c].filter(h=>h.length>0);return[{type:"text",text:u.length>0?u.join(`
21
- `):"(run_code completed with no output)"}]}},async execute(s,l){if(s.description.trim().length===0)throw new Error("invalid description: expected a non-empty string");let c=r(),u=new AbortController,h=()=>{u.abort(l.signal.reason)};l.signal.addEventListener("abort",h,{once:!0});let f=0,p=[],m=new Set,y=new Set,j=[],D=!1,R=!1,K=Promise.resolve(),te,v=()=>{let x=te;te=void 0,x?.()},O=()=>(R||(R=!0,K=(async()=>{try{for(;;){let x=new Promise(V=>{te=V}),J=j[0];if(J!==void 0&&J.settled){j.shift(),await J.commit(),J.mode==="exclusive"&&(D=!1);continue}let C=p[0];if(C!==void 0){if(u.signal.aborted){p.shift(),C.abandon();continue}let V=C.classify();if(!D&&(V==="exclusive"?m.size===0:m.size<o)){V==="exclusive"&&(D=!0),C.mode=V,p.shift(),j.push(C),await C.start();let X=C.flight.finally(()=>{m.delete(X),v()});m.add(X);continue}}if(p.length===0&&j.length===0&&m.size===0)return;await x}}finally{R=!1,te=void 0}})()),K),A=async()=>{for(await O();y.size>0;)await Promise.allSettled([...y])},Wt=()=>u.signal.aborted,bn=x=>async J=>{if(Wt())throw new Error(`run_code run is over (${String(u.signal.reason)}); ${x} not dispatched`);let C=Ro(J),V=++f,X=`${String(l.callId)}:code:${V}`,Bt={callId:X,rootCallId:l.rootCallId,name:x,arguments:C.dispatched,...l.agent?{agent:l.agent}:{},parent:l.token,signal:u.signal},_e=e[Hr],Ke=await new Promise((wn,vn)=>{let W,xn=S=>{wn(S.isError?{isError:!0,message:S.error.message}:{isError:!1,value:S.value});let L=l.agent;if(L===void 0)return;let zt=(async()=>{let On=await i({exec:l,agent:L,subCallId:X,name:x,isError:S.isError,content:S.content});L.session.append("tool/code-dispatch",{rootCallId:l.rootCallId,parentCallId:l.callId,subCallId:X,name:x,arguments:C.logged,isError:S.isError,content:On})})().finally(()=>{y.delete(zt)});y.add(zt)};p.push({flight:Promise.resolve(),settled:!1,classify:()=>e.executionMode(Bt).kind,abandon:()=>{vn(new Error(`run_code run is over (${String(u.signal.reason)}); ${x} tool call abandoned`))},async start(){l.agent?.session.append("tool/code-dispatch-start",{rootCallId:l.rootCallId,parentCallId:l.callId,subCallId:X,name:x,arguments:C.logged});let S=await _e.prepare(Bt);if(S.kind==="dispatch"){this.flight=_e.dispatch(S.exec).then(L=>{W={kind:L.kind,exec:S.exec,result:L.result},this.settled=!0});return}W={kind:S.kind,exec:S.exec,result:S.result},this.settled=!0},async commit(){if(W===void 0)return;let S=W.kind==="post-result"?await _e.finalize(W.exec,W.result):_e.finish(W.exec,W.result);for(let L of S.additionalContexts??[])l.deferContext(L);for(S.concludesTurn&&l.concludeTurn(),xn(S);y.size>o;)await Promise.race(y)}}),v(),O()});if(Wt())throw new Error(`run_code run is over (${String(u.signal.reason)}); ${x} result discarded`);if(Ke.isError)throw new Error(Ke.message);return Ke.value},Lt=Object.create(null);for(let x of e.schemas(l.agent))x.name!=="run_code"&&Object.defineProperty(Lt,x.name,{enumerable:!0,value:bn(x.name)});try{let x;try{x=await c.run({program:s.code,bindings:[{global:"tools",functions:Lt,errorClass:{name:"ToolCallError",memberNameProperty:"toolName"}}],signal:u.signal})}finally{u.abort("run_code settled"),await A()}if(x.error){let J=x.logs.length>0?`
21
+ `):"(run_code completed with no output)"}]}},async execute(s,l){if(s.description.trim().length===0)throw new Error("invalid description: expected a non-empty string");let c=r(),u=new AbortController,h=()=>{u.abort(l.signal.reason)};l.signal.addEventListener("abort",h,{once:!0});let f=0,p=[],m=new Set,y=new Set,j=[],I=!1,R=!1,K=Promise.resolve(),te,v=()=>{let x=te;te=void 0,x?.()},O=()=>(R||(R=!0,K=(async()=>{try{for(;;){let x=new Promise(V=>{te=V}),L=j[0];if(L!==void 0&&L.settled){j.shift(),await L.commit(),L.mode==="exclusive"&&(I=!1);continue}let N=p[0];if(N!==void 0){if(u.signal.aborted){p.shift(),N.abandon();continue}let V=N.classify();if(!I&&(V==="exclusive"?m.size===0:m.size<o)){V==="exclusive"&&(I=!0),N.mode=V,p.shift(),j.push(N),await N.start();let X=N.flight.finally(()=>{m.delete(X),v()});m.add(X);continue}}if(p.length===0&&j.length===0&&m.size===0)return;await x}}finally{R=!1,te=void 0}})()),K),A=async()=>{for(await O();y.size>0;)await Promise.allSettled([...y])},Wt=()=>u.signal.aborted,bn=x=>async L=>{if(Wt())throw new Error(`run_code run is over (${String(u.signal.reason)}); ${x} not dispatched`);let N=Ro(L),V=++f,X=`${String(l.callId)}:code:${V}`,Bt={callId:X,rootCallId:l.rootCallId,name:x,arguments:N.dispatched,...l.agent?{agent:l.agent}:{},parent:l.token,signal:u.signal},_e=e[Hr],Ke=await new Promise((wn,vn)=>{let W,xn=S=>{wn(S.isError?{isError:!0,message:S.error.message}:{isError:!1,value:S.value});let J=l.agent;if(J===void 0)return;let Ut=(async()=>{let On=await i({exec:l,agent:J,subCallId:X,name:x,isError:S.isError,content:S.content});J.session.append("tool/code-dispatch",{rootCallId:l.rootCallId,parentCallId:l.callId,subCallId:X,name:x,arguments:N.logged,isError:S.isError,content:On})})().finally(()=>{y.delete(Ut)});y.add(Ut)};p.push({flight:Promise.resolve(),settled:!1,classify:()=>e.executionMode(Bt).kind,abandon:()=>{vn(new Error(`run_code run is over (${String(u.signal.reason)}); ${x} tool call abandoned`))},async start(){l.agent?.session.append("tool/code-dispatch-start",{rootCallId:l.rootCallId,parentCallId:l.callId,subCallId:X,name:x,arguments:N.logged});let S=await _e.prepare(Bt);if(S.kind==="dispatch"){this.flight=_e.dispatch(S.exec).then(J=>{W={kind:J.kind,exec:S.exec,result:J.result},this.settled=!0});return}W={kind:S.kind,exec:S.exec,result:S.result},this.settled=!0},async commit(){if(W===void 0)return;let S=W.kind==="post-result"?await _e.finalize(W.exec,W.result):_e.finish(W.exec,W.result);for(let J of S.additionalContexts??[])l.deferContext(J);for(S.concludesTurn&&l.concludeTurn(),xn(S);y.size>o;)await Promise.race(y)}}),v(),O()});if(Wt())throw new Error(`run_code run is over (${String(u.signal.reason)}); ${x} result discarded`);if(Ke.isError)throw new Error(Ke.message);return Ke.value},Jt=Object.create(null);for(let x of e.schemas(l.agent))x.name!=="run_code"&&Object.defineProperty(Jt,x.name,{enumerable:!0,value:bn(x.name)});try{let x;try{x=await c.run({program:s.code,bindings:[{global:"tools",functions:Jt,errorClass:{name:"ToolCallError",memberNameProperty:"toolName"}}],signal:u.signal})}finally{u.abort("run_code settled"),await A()}if(x.error){let L=x.logs.length>0?`
22
22
  Captured output:
23
23
  ${x.logs.join(`
24
- `)}`:"";throw new _o(`code run failed (${x.error.kind}): ${x.error.message}${J}`)}return{logs:x.logs,...x.value!==void 0?{result:x.value}:{}}}finally{l.signal.removeEventListener("abort",h)}},presentCall:s=>({card:"generic",title:s.description,kind:"execute",rawInput:s.code})});return Object.defineProperty(a,"description",{enumerable:!0,get:()=>sr(n).description}),Object.defineProperty(a,"parameters",{enumerable:!0,get:()=>Wr({code:{type:"string",required:!0,description:sr(n).codeDescription},description:{type:"string",required:!0,description:ir}})}),a}var Do=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function ft(e){return Do.test(e)?e:JSON.stringify(e)}function we(e){return" ".repeat(e)}function Lr(e,t){if(typeof e!="string"||e.length===0)return[];let r=e.replace(/\s+/g," ").trim();return[`${we(t)}/** ${r.replaceAll("*/",String.raw`*\/`)} */`]}function ar(e){return JSON.stringify(e)}function Io(e,t){let r=t==="integer"?"number":t;return Object.hasOwn(e,"const")?ar(e.const):Object.hasOwn(e,"enum")?e.enum.map(ar).join(" | "):r}function ht(e){return{parts:e,containsUnionOrIntersection:e.some(t=>typeof t=="string"?t.includes("|")||t.includes("&"):t.containsUnionOrIntersection)}}function F(...e){return ht(e)}function Mo(e){let t=[],r=[e];for(let n=r.pop();n!==void 0;n=r.pop()){if(typeof n=="string"){t.push(n);continue}for(let o=n.parts.length-1;o>=0;o--){let i=n.parts[o];i!==void 0&&r.push(i)}}return t.join("")}function lr(e,t){return{node:e,indent:t,phase:"start",children:[],childIndex:0,childDocuments:[],entries:[]}}function Po(e,t){let r=[lr(e,t)],n,o=i=>{r.pop();let a=r.at(-1);a===void 0?n=i:a.childDocuments.push(i)};for(;r.length>0;){let i=r.at(-1);if(i===void 0)break;if(i.phase==="children"){if(i.childIndex<i.children.length){let u=i.children[i.childIndex];if(u===void 0)throw new Error("missing schema render child");i.childIndex++,r.push(lr(u.node,u.indent));continue}if(i.kind==="oneOf"){let u=[];for(let h=0;h<i.childDocuments.length;h++){h>0&&u.push(" | ");let f=i.childDocuments[h];f!==void 0&&u.push(f)}o(ht(u));continue}if(i.kind==="array"){let u=i.childDocuments[0];if(u===void 0)throw new Error("missing array item type");o(u.containsUnionOrIntersection?F("(",u,")[]"):F(u,"[]"));continue}let s=new Set(i.node.required),l=["{"];for(let u=0;u<i.entries.length;u++){let h=i.entries[u],f=i.childDocuments[u];if(h===void 0||f===void 0)throw new Error("missing object property type");let[p,m]=h;for(let y of Lr(m.description,i.indent+1))l.push(`
24
+ `)}`:"";throw new _o(`code run failed (${x.error.kind}): ${x.error.message}${L}`)}return{logs:x.logs,...x.value!==void 0?{result:x.value}:{}}}finally{l.signal.removeEventListener("abort",h)}},presentCall:s=>({card:"generic",title:s.description,kind:"execute",rawInput:s.code})});return Object.defineProperty(a,"description",{enumerable:!0,get:()=>sr(n).description}),Object.defineProperty(a,"parameters",{enumerable:!0,get:()=>Wr({code:{type:"string",required:!0,description:sr(n).codeDescription},description:{type:"string",required:!0,description:ir}})}),a}var Io=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function ft(e){return Io.test(e)?e:JSON.stringify(e)}function we(e){return" ".repeat(e)}function Jr(e,t){if(typeof e!="string"||e.length===0)return[];let r=e.replace(/\s+/g," ").trim();return[`${we(t)}/** ${r.replaceAll("*/",String.raw`*\/`)} */`]}function ar(e){return JSON.stringify(e)}function Do(e,t){let r=t==="integer"?"number":t;return Object.hasOwn(e,"const")?ar(e.const):Object.hasOwn(e,"enum")?e.enum.map(ar).join(" | "):r}function ht(e){return{parts:e,containsUnionOrIntersection:e.some(t=>typeof t=="string"?t.includes("|")||t.includes("&"):t.containsUnionOrIntersection)}}function F(...e){return ht(e)}function Mo(e){let t=[],r=[e];for(let n=r.pop();n!==void 0;n=r.pop()){if(typeof n=="string"){t.push(n);continue}for(let o=n.parts.length-1;o>=0;o--){let i=n.parts[o];i!==void 0&&r.push(i)}}return t.join("")}function lr(e,t){return{node:e,indent:t,phase:"start",children:[],childIndex:0,childDocuments:[],entries:[]}}function Po(e,t){let r=[lr(e,t)],n,o=i=>{r.pop();let a=r.at(-1);a===void 0?n=i:a.childDocuments.push(i)};for(;r.length>0;){let i=r.at(-1);if(i===void 0)break;if(i.phase==="children"){if(i.childIndex<i.children.length){let u=i.children[i.childIndex];if(u===void 0)throw new Error("missing schema render child");i.childIndex++,r.push(lr(u.node,u.indent));continue}if(i.kind==="oneOf"){let u=[];for(let h=0;h<i.childDocuments.length;h++){h>0&&u.push(" | ");let f=i.childDocuments[h];f!==void 0&&u.push(f)}o(ht(u));continue}if(i.kind==="array"){let u=i.childDocuments[0];if(u===void 0)throw new Error("missing array item type");o(u.containsUnionOrIntersection?F("(",u,")[]"):F(u,"[]"));continue}let s=new Set(i.node.required),l=["{"];for(let u=0;u<i.entries.length;u++){let h=i.entries[u],f=i.childDocuments[u];if(h===void 0||f===void 0)throw new Error("missing object property type");let[p,m]=h;for(let y of Jr(m.description,i.indent+1))l.push(`
25
25
  `,y);l.push(`
26
26
  `,`${we(i.indent+1)}${ft(p)}${s.has(p)?"":"?"}: `,f,";")}l.push(`
27
- `,`${we(i.indent)}}`);let c=ht(l);o(i.node.additionalProperties===!1?c:F(c," & Record<string, JsonValue>"));continue}let a=i.node;if(a.oneOf!==void 0){i.kind="oneOf",i.children=Array.from(a.oneOf,s=>({node:s,indent:i.indent})),i.childIndex=0,i.childDocuments=[],i.phase="children";continue}if(a.type===void 0){o(F("JsonValue"));continue}switch(a.type){case"string":case"number":case"integer":case"boolean":case"null":o(F(Io(a,a.type)));break;case"array":a.items===void 0?o(F("JsonValue[]")):(i.kind="array",i.children=[{node:a.items,indent:i.indent}],i.childIndex=0,i.childDocuments=[],i.phase="children");break;case"object":{let s=a.additionalProperties!==!1,l=Object.entries(a.properties??{});l.length===0?o(F(s?"Record<string, JsonValue>":"Record<string, never>")):(i.kind="object",i.entries=l,i.children=l.map(([,c])=>({node:c,indent:i.indent+1})),i.childIndex=0,i.childDocuments=[],i.phase="children");break}default:o(F("unknown"))}}return n??F("unknown")}function cr(e,t=0){try{return xe(e),Mo(Po(e,t))}catch{return"unknown"}}var Fo='## Writing code for run_code\n\nPass `run_code` the body of an async TypeScript function (erasable syntax only \u2014 no `enum` or namespaces; type annotations are advisory, the code runs type-stripped). Inside the program:\n\n- Call tools as `await tools.name(args)` \u2014 quoted access for exotic names: `tools["my-tool"](args)`. Every call resolves to the tool\'s typed canonical JSON value. Tool arguments must be lossless JSON.\n- A FAILED tool call rejects with `ToolCallError`, whose `toolName` identifies the failed tool and whose `message` is human-readable \u2014 `try/catch` it to handle and continue.\n- Independent read-only calls MAY overlap under `Promise.all` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with `await`.\n- Emit results with `return` and/or `console.log(...)`. ONLY what you print or return comes back to you \u2014 intermediate tool results never enter the conversation, so extract just what you need.\n\nThe available tools:';function qo(e){let t=[...e].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0),r=[],n=[];for(let o of t)r.push(...Lr(o.description,1)),r.push(`${we(1)}${ft(o.name)}: ${cr(o.parameters,1)};`),n.push(`${we(1)}${ft(o.name)}: ${cr(o.output,1)};`);return`${Fo}
27
+ `,`${we(i.indent)}}`);let c=ht(l);o(i.node.additionalProperties===!1?c:F(c," & Record<string, JsonValue>"));continue}let a=i.node;if(a.oneOf!==void 0){i.kind="oneOf",i.children=Array.from(a.oneOf,s=>({node:s,indent:i.indent})),i.childIndex=0,i.childDocuments=[],i.phase="children";continue}if(a.type===void 0){o(F("JsonValue"));continue}switch(a.type){case"string":case"number":case"integer":case"boolean":case"null":o(F(Do(a,a.type)));break;case"array":a.items===void 0?o(F("JsonValue[]")):(i.kind="array",i.children=[{node:a.items,indent:i.indent}],i.childIndex=0,i.childDocuments=[],i.phase="children");break;case"object":{let s=a.additionalProperties!==!1,l=Object.entries(a.properties??{});l.length===0?o(F(s?"Record<string, JsonValue>":"Record<string, never>")):(i.kind="object",i.entries=l,i.children=l.map(([,c])=>({node:c,indent:i.indent+1})),i.childIndex=0,i.childDocuments=[],i.phase="children");break}default:o(F("unknown"))}}return n??F("unknown")}function cr(e,t=0){try{return xe(e),Mo(Po(e,t))}catch{return"unknown"}}var Fo='## Writing code for run_code\n\nPass `run_code` the body of an async TypeScript function (erasable syntax only \u2014 no `enum` or namespaces; type annotations are advisory, the code runs type-stripped). Inside the program:\n\n- Call tools as `await tools.name(args)` \u2014 quoted access for exotic names: `tools["my-tool"](args)`. Every call resolves to the tool\'s typed canonical JSON value. Tool arguments must be lossless JSON.\n- A FAILED tool call rejects with `ToolCallError`, whose `toolName` identifies the failed tool and whose `message` is human-readable \u2014 `try/catch` it to handle and continue.\n- Independent read-only calls MAY overlap under `Promise.all` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with `await`.\n- Emit results with `return` and/or `console.log(...)`. ONLY what you print or return comes back to you \u2014 intermediate tool results never enter the conversation, so extract just what you need.\n\nThe available tools:';function qo(e){let t=[...e].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0),r=[],n=[];for(let o of t)r.push(...Jr(o.description,1)),r.push(`${we(1)}${ft(o.name)}: ${cr(o.parameters,1)};`),n.push(`${we(1)}${ft(o.name)}: ${cr(o.output,1)};`);return`${Fo}
28
28
 
29
29
  \`\`\`ts
30
30
  type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
@@ -40,8 +40,8 @@ ${n.join(`
40
40
  `)].join(`
41
41
 
42
42
  `)}
43
- \`\`\``}var Jo=new RegExp("^[\\p{XID_Start}_]\\p{XID_Continue}*$","u");function Br(e){return Jo.test(e)&&e.normalize("NFKC")===e}var zr=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","__debug__"]),Wo=["Any","Literal","NotRequired","Protocol","TypedDict"];function T(e){return" ".repeat(e)}var Lo=/[\u0000-\u0008\u000e-\u001f\u007f-\u009f]/g,Bo=/[\ud800-\udfff]/gu;function Et(e){let t=e.description;if(typeof t!="string")return;let r=t.replace(/\s+/g," ").replace(Lo,n=>`\\x${n.charCodeAt(0).toString(16).padStart(2,"0")}`).replace(Bo,n=>`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`).trim();return r.length===0?void 0:r}function zo(e,t){let r=Et({description:e});if(r===void 0)return[];let n=r.replaceAll("\\","\\\\").replaceAll('"','\\"');return[`${T(t)}"""${n}"""`]}function mt(e){let t=e.split(/[^\p{XID_Continue}]+|_+/u).filter(r=>r.length>0).map(r=>`${r.charAt(0).toUpperCase()}${r.slice(1)}`).join("").normalize("NFKC");return(new RegExp("^\\p{XID_Start}","u").test(t)?t:`Tool${t}`).normalize("NFKC")}var ur=120,Uo=180;function Ur(e){if(e.length<=ur)return e;let t=e.slice(0,ur);return/[\uD800-\uDBFF]$/.test(t)?t.slice(0,-1):t}function Ho(e,t){let r=Ur(e),n=r;if(t.usedClassNames.has(n)){let o=t.nextClassCounter.get(r)??2;for(;t.usedClassNames.has(`${r}${o}`);)o++;n=`${r}${o}`,t.nextClassCounter.set(r,o+1)}return t.usedClassNames.add(n),n}function dr(e,t){return Ur(`${e}${t}`.normalize("NFKC"))}function pr(e){return e===!0?"True":e===!1?"False":typeof e=="string"?JSON.stringify(e):typeof e=="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e)?BigInt(e).toString():String(e)}function Ne(e,t,r){return e.const!==void 0?(r.typing.add("Literal"),`Literal[${pr(e.const)}]`):e.enum!==void 0?(r.typing.add("Literal"),`Literal[${e.enum.map(pr).join(", ")}]`):t}function fr(e,t,r){let n=(o,i,a)=>({schema:o,className:i,phase:"start",listDepth:a,children:[],childIndex:0,childTypes:[],entries:[]});try{xe(e);let o=[n(e,t,0)],i,a=s=>{o.pop();let l=o.at(-1);l===void 0?i=s:l.childTypes.push(s)};for(;o.length>0;){let s=o.at(-1);if(s===void 0)break;if(s.phase==="children"){if(s.childIndex<s.children.length){let p=s.children[s.childIndex];if(p===void 0)throw new Error("missing python render child");s.childIndex++,o.push(n(p.schema,p.className,p.listDepth));continue}if(s.kind==="oneOf"){let p="";for(let[m,y]of s.childTypes.entries())p=m===0?y:`${p} | ${y}`;a(p);continue}if(s.kind==="array"){a(`list[${s.childTypes[0]??"Any"}]`);continue}let c=s.node,u=s.allocated;if(c===void 0||u===void 0)throw new Error("missing typeddict frame state");let h=new Set(c.required),f=[`class ${u}(TypedDict):`];for(let p=0;p<s.entries.length;p++){let m=s.entries[p],y=s.childTypes[p];if(m===void 0||y===void 0)throw new Error("missing typeddict field type");let[j,D]=m,R=Et(D);R!==void 0&&f.push(`${T(1)}# ${R}`),h.has(j)?f.push(`${T(1)}${j}: ${y}`):(r.typing.add("NotRequired"),f.push(`${T(1)}${j}: NotRequired[${y}]`))}c.additionalProperties!==!1&&f.push(`${T(1)}# Additional keys beyond those declared are allowed.`),f.length===1&&f.push(`${T(1)}pass`),r.classes.push(f.join(`
44
- `)),a(u);continue}s.phase="children";let l=s.schema;if(l.oneOf!==void 0){s.kind="oneOf",s.children=l.oneOf.map((c,u)=>({schema:c,className:dr(s.className,`${u+1}`),listDepth:s.listDepth}));continue}if(l.type===void 0){r.typing.add("Any"),a("Any");continue}switch(l.type){case"string":a(Ne(l,"str",r));break;case"number":a(Ne(l,"float",r));break;case"integer":a(Ne(l,"int",r));break;case"boolean":a(Ne(l,"bool",r));break;case"null":a("None");break;case"array":if(l.items===void 0){r.typing.add("Any"),a("list[Any]");break}if(s.listDepth>=Uo){r.typing.add("Any"),a("Any");break}s.kind="array",s.children=[{schema:l.items,className:s.className,listDepth:s.listDepth+1}];break;case"object":{let c=Object.entries(l.properties??{});if(t===""||!c.every(([u])=>Br(u)&&!zr.has(u)&&!(u.startsWith("__")&&!u.endsWith("__")))){r.typing.add("Any"),a("dict[str, Any]");break}if(c.length===0&&l.additionalProperties!==!1){r.typing.add("Any"),a("dict[str, Any]");break}s.kind="typeddict",s.node=l,s.allocated=Ho(s.className,r),r.typing.add("TypedDict"),s.entries=c,s.children=c.map(([u,h])=>({schema:h,className:dr(s.allocated??"",mt(u)),listDepth:1}));break}default:r.typing.add("Any"),a("Any")}}return i??"Any"}catch{return r.typing.add("Any"),"Any"}}var Ko='## Writing code for run_code\n\nPass `run_code` the body of an async Python function (top-level `await` and `return` both work). At run time exactly two of the names declared below are bound: `tools` and `ToolCallError`. Everything else is a STATIC STUB describing argument and return types \u2014 in particular the `TypedDict` classes do NOT exist at run time, so build arguments as plain `dict`/`list` JSON values: `await tools.name({"field": 1})`, never `FooArgs(field=1)`, which raises `NameError`. Inside the program:\n\n- Call tools as `await tools.name(args)` \u2014 subscript access for exotic, reserved, or underscore-leading names: `await tools["my-tool"](args)`. Every call resolves to the tool\'s typed canonical JSON value (each method\'s return type below). Tool arguments must be lossless JSON.\n- A FAILED tool call raises `ToolCallError`, whose `toolName` identifies the failed tool and whose message is human-readable \u2014 wrap in `try/except` to handle and continue.\n- Independent read-only calls MAY overlap under `asyncio.gather` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with `await`.\n- Emit the run\'s answer with `print(...)` and/or a top-level `return <value>`; the returned value must be lossless JSON. ONLY what you print and the returned value come back \u2014 intermediate tool results never enter the conversation, so extract just what you need.\n\nThe available tools:';function Vo(e){let t=[...e].sort((l,c)=>l.name<c.name?-1:l.name>c.name?1:0),r={classes:[],usedClassNames:new Set,nextClassCounter:new Map,typing:new Set(["Protocol"])},n=[],o=0;for(let l of t){let c=fr(l.parameters,`${mt(l.name)}Args`,r),u=fr(l.output,`${mt(l.name)}Output`,r);if(Br(l.name)&&!zr.has(l.name)&&!l.name.startsWith("_")){let h=zo(l.description,2);n.push(h.length>0?`${T(1)}async def ${l.name}(self, args: ${c}) -> ${u}:`:`${T(1)}async def ${l.name}(self, args: ${c}) -> ${u}: ...`),n.push(...h),o+=1}else{n.push(`${T(1)}# tools[${JSON.stringify(l.name)}](args: ${c}) -> ${u}`);let h=Et(l);h!==void 0&&n.push(`${T(1)}# ${h}`)}}let i=(o>0?n:[`${T(1)}pass`,...n]).join(`
43
+ \`\`\``}var Lo=new RegExp("^[\\p{XID_Start}_]\\p{XID_Continue}*$","u");function Br(e){return Lo.test(e)&&e.normalize("NFKC")===e}var Ur=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","__debug__"]),Wo=["Any","Literal","NotRequired","Protocol","TypedDict"];function T(e){return" ".repeat(e)}var Jo=/[\u0000-\u0008\u000e-\u001f\u007f-\u009f]/g,Bo=/[\ud800-\udfff]/gu;function Et(e){let t=e.description;if(typeof t!="string")return;let r=t.replace(/\s+/g," ").replace(Jo,n=>`\\x${n.charCodeAt(0).toString(16).padStart(2,"0")}`).replace(Bo,n=>`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`).trim();return r.length===0?void 0:r}function Uo(e,t){let r=Et({description:e});if(r===void 0)return[];let n=r.replaceAll("\\","\\\\").replaceAll('"','\\"');return[`${T(t)}"""${n}"""`]}function mt(e){let t=e.split(/[^\p{XID_Continue}]+|_+/u).filter(r=>r.length>0).map(r=>`${r.charAt(0).toUpperCase()}${r.slice(1)}`).join("").normalize("NFKC");return(new RegExp("^\\p{XID_Start}","u").test(t)?t:`Tool${t}`).normalize("NFKC")}var ur=120,zo=180;function zr(e){if(e.length<=ur)return e;let t=e.slice(0,ur);return/[\uD800-\uDBFF]$/.test(t)?t.slice(0,-1):t}function Ho(e,t){let r=zr(e),n=r;if(t.usedClassNames.has(n)){let o=t.nextClassCounter.get(r)??2;for(;t.usedClassNames.has(`${r}${o}`);)o++;n=`${r}${o}`,t.nextClassCounter.set(r,o+1)}return t.usedClassNames.add(n),n}function dr(e,t){return zr(`${e}${t}`.normalize("NFKC"))}function pr(e){return e===!0?"True":e===!1?"False":typeof e=="string"?JSON.stringify(e):typeof e=="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e)?BigInt(e).toString():String(e)}function Ce(e,t,r){return e.const!==void 0?(r.typing.add("Literal"),`Literal[${pr(e.const)}]`):e.enum!==void 0?(r.typing.add("Literal"),`Literal[${e.enum.map(pr).join(", ")}]`):t}function fr(e,t,r){let n=(o,i,a)=>({schema:o,className:i,phase:"start",listDepth:a,children:[],childIndex:0,childTypes:[],entries:[]});try{xe(e);let o=[n(e,t,0)],i,a=s=>{o.pop();let l=o.at(-1);l===void 0?i=s:l.childTypes.push(s)};for(;o.length>0;){let s=o.at(-1);if(s===void 0)break;if(s.phase==="children"){if(s.childIndex<s.children.length){let p=s.children[s.childIndex];if(p===void 0)throw new Error("missing python render child");s.childIndex++,o.push(n(p.schema,p.className,p.listDepth));continue}if(s.kind==="oneOf"){let p="";for(let[m,y]of s.childTypes.entries())p=m===0?y:`${p} | ${y}`;a(p);continue}if(s.kind==="array"){a(`list[${s.childTypes[0]??"Any"}]`);continue}let c=s.node,u=s.allocated;if(c===void 0||u===void 0)throw new Error("missing typeddict frame state");let h=new Set(c.required),f=[`class ${u}(TypedDict):`];for(let p=0;p<s.entries.length;p++){let m=s.entries[p],y=s.childTypes[p];if(m===void 0||y===void 0)throw new Error("missing typeddict field type");let[j,I]=m,R=Et(I);R!==void 0&&f.push(`${T(1)}# ${R}`),h.has(j)?f.push(`${T(1)}${j}: ${y}`):(r.typing.add("NotRequired"),f.push(`${T(1)}${j}: NotRequired[${y}]`))}c.additionalProperties!==!1&&f.push(`${T(1)}# Additional keys beyond those declared are allowed.`),f.length===1&&f.push(`${T(1)}pass`),r.classes.push(f.join(`
44
+ `)),a(u);continue}s.phase="children";let l=s.schema;if(l.oneOf!==void 0){s.kind="oneOf",s.children=l.oneOf.map((c,u)=>({schema:c,className:dr(s.className,`${u+1}`),listDepth:s.listDepth}));continue}if(l.type===void 0){r.typing.add("Any"),a("Any");continue}switch(l.type){case"string":a(Ce(l,"str",r));break;case"number":a(Ce(l,"float",r));break;case"integer":a(Ce(l,"int",r));break;case"boolean":a(Ce(l,"bool",r));break;case"null":a("None");break;case"array":if(l.items===void 0){r.typing.add("Any"),a("list[Any]");break}if(s.listDepth>=zo){r.typing.add("Any"),a("Any");break}s.kind="array",s.children=[{schema:l.items,className:s.className,listDepth:s.listDepth+1}];break;case"object":{let c=Object.entries(l.properties??{});if(t===""||!c.every(([u])=>Br(u)&&!Ur.has(u)&&!(u.startsWith("__")&&!u.endsWith("__")))){r.typing.add("Any"),a("dict[str, Any]");break}if(c.length===0&&l.additionalProperties!==!1){r.typing.add("Any"),a("dict[str, Any]");break}s.kind="typeddict",s.node=l,s.allocated=Ho(s.className,r),r.typing.add("TypedDict"),s.entries=c,s.children=c.map(([u,h])=>({schema:h,className:dr(s.allocated??"",mt(u)),listDepth:1}));break}default:r.typing.add("Any"),a("Any")}}return i??"Any"}catch{return r.typing.add("Any"),"Any"}}var Ko='## Writing code for run_code\n\nPass `run_code` the body of an async Python function (top-level `await` and `return` both work). At run time exactly two of the names declared below are bound: `tools` and `ToolCallError`. Everything else is a STATIC STUB describing argument and return types \u2014 in particular the `TypedDict` classes do NOT exist at run time, so build arguments as plain `dict`/`list` JSON values: `await tools.name({"field": 1})`, never `FooArgs(field=1)`, which raises `NameError`. Inside the program:\n\n- Call tools as `await tools.name(args)` \u2014 subscript access for exotic, reserved, or underscore-leading names: `await tools["my-tool"](args)`. Every call resolves to the tool\'s typed canonical JSON value (each method\'s return type below). Tool arguments must be lossless JSON.\n- A FAILED tool call raises `ToolCallError`, whose `toolName` identifies the failed tool and whose message is human-readable \u2014 wrap in `try/except` to handle and continue.\n- Independent read-only calls MAY overlap under `asyncio.gather` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with `await`.\n- Emit the run\'s answer with `print(...)` and/or a top-level `return <value>`; the returned value must be lossless JSON. ONLY what you print and the returned value come back \u2014 intermediate tool results never enter the conversation, so extract just what you need.\n\nThe available tools:';function Vo(e){let t=[...e].sort((l,c)=>l.name<c.name?-1:l.name>c.name?1:0),r={classes:[],usedClassNames:new Set,nextClassCounter:new Map,typing:new Set(["Protocol"])},n=[],o=0;for(let l of t){let c=fr(l.parameters,`${mt(l.name)}Args`,r),u=fr(l.output,`${mt(l.name)}Output`,r);if(Br(l.name)&&!Ur.has(l.name)&&!l.name.startsWith("_")){let h=Uo(l.description,2);n.push(h.length>0?`${T(1)}async def ${l.name}(self, args: ${c}) -> ${u}:`:`${T(1)}async def ${l.name}(self, args: ${c}) -> ${u}: ...`),n.push(...h),o+=1}else{n.push(`${T(1)}# tools[${JSON.stringify(l.name)}](args: ${c}) -> ${u}`);let h=Et(l);h!==void 0&&n.push(`${T(1)}# ${h}`)}}let i=(o>0?n:[`${T(1)}pass`,...n]).join(`
45
45
  `),a=Wo.filter(l=>r.typing.has(l)),s=r.classes.length>0?`${r.classes.join(`
46
46
 
47
47
  `)}
@@ -59,11 +59,11 @@ ${i}
59
59
 
60
60
  tools: Tools`}
61
61
  \`\`\``}var nt={typescript:qo,python:Vo},Hr=Symbol("@deepseek-ai/dsh-tools.scheduler"),Xo="ABORTED",Go="ABORTED_BEFORE_DISPATCH",ot=class extends oe{constructor(e){super(`unknown tool "${e}"`,"UNKNOWN_TOOL"),this.name="ToolNotFoundError"}},Z=class extends oe{violations;constructor(e,t){super(`tool "${e}" returned invalid output: ${t.join("; ")}`,"INVALID_TOOL_OUTPUT"),this.name="ToolOutputError",this.violations=t}};function gt(e,t,r){return new Z(e,[`output.${t} failed: ${ve(r)}`])}function hr(e,t,r){try{let n=H(r);if(n===void 0)throw new Z(e,[`output.${t} returned non-lossless JSON`]);return n}catch(n){throw n instanceof Z?n:gt(e,t,n)}}function Yo(e,t){try{let r=H(t);if(r===void 0)throw new Z(e,["value is not lossless JSON"]);return r}catch(r){throw r instanceof Z?r:new Z(e,[`value snapshot failed: ${ve(r)}`])}}function ve(e){try{return e instanceof Error||typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"?e.message:String(e)}catch{return"<unprintable thrown value>"}}function Qo(e){let t=e.map(r=>r.type==="text"?r.text:`[${r.type} content]`).join(`
62
- `);return t.length>0?t:"tool result blocked by post-execute policy"}function mr(e){let t=H(e);if(t===void 0)throw new TypeError("tool result must be losslessly JSON-serializable");return ge(t)}function Zo(e){try{return e instanceof oe?{name:e.name,code:e.code}:void 0}catch{return}}var ei=class{tools;restrictions=new Zt;guards=new Zt;mode;constructor(e){this.tools=new Xn(t=>new Error(e===void 0?`tool "${t}" is already registered (for a per-agent variant, register through that agent's \`agent.ctx\` instead)`:`tool "${t}" is already registered in this scope`))}isEmpty(){return this.tools.isEmpty()&&this.restrictions.isEmpty()&&this.guards.isEmpty()&&this.mode===void 0}admits(e){for(let t of this.restrictions.values())if(t.allow!==void 0&&!t.allow.has(e)||t.deny!==void 0&&t.deny.has(e))return!1;return!0}guardReason(e){for(let t of this.guards.values()){let r=t(e);if(r!==void 0)return r}}};function ti(e){let t=e??10;if(!Number.isInteger(t)||t<1)throw new Error("maxParallelSubCalls must be a positive integer");return t}var xs=class extends Vn{static inject=["systemPrompt"];static Config=d.object({mode:d.union(["native","code","both"]).default("native"),maxParallelSubCalls:d.natural().min(1).default(10)});[Hr]={prepare:e=>this.prepareScheduledExecution(e),dispatch:e=>this.dispatchScheduledExecution(e),finalize:(e,t)=>this.finalizeScheduledExecution(e,t),finish:(e,t)=>this.finishScheduledExecution(e,t)};deferredContexts=new WeakMap;concludingExecutions=new WeakSet;cancellationStates=new WeakMap;contentFinalizers=new WeakMap;layers=new Gn(e=>new ei(e),()=>{this.ctx.emit("tools/change")});defaultMode;maxParallelSubCalls;codeTransport;constructor(e,t={}){super(e,"tools"),this.defaultMode=t.mode??"native",this.maxParallelSubCalls=ti(t.maxParallelSubCalls),e.systemPrompt.tools(r=>this.wireSchemas(r.scope)),this.defaultMode!=="native"&&e.systemPrompt.section(this.sdkSection())}sdkSection(){return{name:"tools:sdk",order:150,text:e=>{let t=this.modeFor(e.scope);if(t==="native")return"";let r=this.requireCodeRuntime(t),n=nt[r.language];if(n===void 0)throw new Error(`dsh-tools: no SDK renderer for ${r.language}`);return n(this.sdkSchemas(e.scope))}}}modeFor(e){let t=this.layers.chainLayers(e);for(let r=t.length-1;r>=0;r-=1){let n=t[r]?.mode;if(n!==void 0)return n}return this.defaultMode}requireCodeTransport(){return this.codeTransport??=To(this,{requireRuntime:()=>this.requireCodeRuntime(this.defaultMode),peekRuntime:()=>this.ctx.get("codeRuntime"),maxParallel:this.maxParallelSubCalls,shapeDispatchLog:e=>this.shapeDispatchLog(e)}),this.codeTransport}presentAs(e){let t=this.ctx;if(De(t)===void 0)throw new Error("tools.presentAs() requires a scoped context (agent.ctx): a context-global presentation is the `mode` config field on the tools row");return t.effect(function*(){yield this.layers.effect(t,r=>{if(r.mode!==void 0)throw new Error(`tools.presentAs("${e}") conflicts with "${r.mode}" already declared for this agent; one composition selects one presentation`);return r.mode=e,()=>{r.mode=void 0}},{label:"tools.presentAs()"}),e!=="native"&&(yield t.systemPrompt.section(this.sdkSection()))}.bind(this),"tools.presentAs()")}wireSchemas(e){let t=this.view(e),r=this.modeFor(e);if(r==="native")return{schemas:[...t.visible.values()].map(o=>this.schemaOf(o,!1)),knownNames:[...t.knownNames]};this.requireCodeRuntime(r);let n=[...t.visible.values()].map(o=>this.schemaOf(o,!1));return r==="code"?{schemas:n.filter(o=>o.name===B),knownNames:[B]}:{schemas:n,knownNames:[...t.knownNames,B]}}requireCodeRuntime(e){let t=this.ctx.get("codeRuntime");if(!t)throw new Error(`dsh-tools: mode "${e}" requires a code runtime \u2014 load a ctx.codeRuntime implementation (e.g. @deepseek-ai/dsh-code-runtime-worker) or set tools mode to "native"`);if(!Object.hasOwn(nt,t.language)){let r=Object.keys(nt).map(n=>JSON.stringify(n)).join(", ");throw new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(t.language)} (known: ${r})`)}return t}register(e){let t=e.name,r=e.output;if(r===void 0||typeof r!="object"||typeof r.render!="function"||r.presentationMeta!==void 0&&typeof r.presentationMeta!="function")throw new TypeError(`tool "${t}" must declare output { schema, render, presentationMeta? }`);xe(r.schema);let n=e.timeoutMs;if(n!==void 0&&(!Number.isFinite(n)||n<=0))throw new TypeError(`tool "${t}" timeoutMs must be a positive finite number`);if(t==="run_code")throw new Error(`tool name "${B}" is reserved for the Code Mode presentation transport and cannot be registered or shadowed`);return this.layers.effect(this.ctx,o=>o.tools.insert(t,e),{label:"tools.register()"})}restrict(e){let t=De(this.ctx);if(t===void 0)throw new Error("tools.restrict() requires a scoped context (agent.ctx): a context-global restriction would mask every agent \u2014 deny the tool for the intended agent instead");let r=e.allow,n=e.deny;if(r===void 0&&n===void 0)throw new Error("tools.restrict({}) is a no-op: pass `allow` and/or `deny` (an empty filter is almost always a materialized-empty-config bug)");let o={...r!==void 0?{allow:new Set(r)}:{},...n!==void 0?{deny:new Set(n)}:{}};if([...r??[],...n??[]].includes("run_code"))throw new Error(`tools.restrict() cannot name reserved Code Mode presentation transport "${B}"; restrict end-capability tools instead`);let i=this.view(t).restrictableNames,a=[...r??[],...n??[]].filter(s=>!i.has(s));if(a.length>0)throw new Error(`tools.restrict() names unknown inherited tool${a.length>1?"s":""} ${a.map(s=>`"${s}"`).join(", ")}; a restriction filters what this scope inherits, never what it registers itself. Restrictable tools: ${[...i].sort().join(", ")||"(none)"}`);return this.layers.effect(this.ctx,s=>s.restrictions.append(o),{label:"tools.restrict()"})}guard(e){return this.layers.effect(this.ctx,t=>t.guards.append(e),{label:"tools.guard()",notify:!1})}guardReason(e){let t=this.layers.global.guardReason(e);if(t!==void 0)return t;if(e.agent!==void 0)for(let r of this.layers.chainLayers(e.agent)){let n=r.guardReason(e);if(n!==void 0)return n}}view(e){let t=this.layers.chainLayers(e),r=this.layers.peek(e),n=new Map(this.layers.global.tools.entries());for(let s of t)if(s!==r)for(let[l,c]of s.tools.entries())n.set(l,c);let o=new Map,i=new Set,a=new Set;for(let[s,l]of n)i.add(s),a.add(s),t.every(c=>c.admits(s))&&o.set(s,l);if(r!==void 0)for(let[s,l]of r.tools.entries())i.add(s),o.set(s,l);return this.modeFor(e)!=="native"&&o.set(B,this.requireCodeTransport()),{visible:o,knownNames:i,restrictableNames:a}}get(e,t){return this.view(t).visible.get(e)}schemas(e){return[...this.view(e).visible.values()].map(t=>this.schemaOf(t,!0))}sdkSchemas(e){return[...this.view(e).visible.values()].filter(t=>t.name!==B).map(t=>{let r=H(t.output.schema);if(r===void 0)throw new Error(`tool "${t.name}" output schema must be lossless JSON before SDK projection`);return{...this.schemaOf(t,!0),output:r}})}schemaOf(e,t){let{name:r,description:n,parameters:o}=e,i=t?H(o):o;if(i===void 0)throw new Error(`tool "${r}" parameters must be lossless JSON before schema projection`);return{name:r,description:n,parameters:i}}executionMode(e){let t=this.get(e.name,e.agent);if(!t?.isConcurrencySafe)return{kind:"exclusive"};try{return t.isConcurrencySafe(e.arguments)===!0?{kind:"parallel"}:{kind:"exclusive"}}catch{return{kind:"exclusive"}}}async shapeDispatchLog(e){try{return await this.ctx.waterfall(ue(this,e.agent),"tools/code-dispatch-log",e,()=>Promise.resolve(e.content))}catch(t){return this.ctx.logger.warn(`tools: code-dispatch-log listener failed for ${e.name}: ${ve(t)}; logging the original settled content`),e.content}}async execute(e){return this.prepareExecution(e,t=>this.completeScheduledExecution(t))}async completeScheduledExecution(e){switch(e.kind){case"dispatch":{let t=await this.dispatchScheduledExecution(e.exec);return t.kind==="post-result"?await this.finalizeScheduledExecution(e.exec,t.result):this.finishScheduledExecution(e.exec,t.result)}case"post-result":return await this.finalizeScheduledExecution(e.exec,e.result);case"final-result":return this.finishScheduledExecution(e.exec,e.result);default:return ye(e,"scheduled tool preparation")}}createExecution(e){let t=[],r=ri(),n=e.callId,o=e.rootCallId??n,i=e.name,a=e.agent,s=e.parent,l=e.signal,c=this.get(i,a),u=c?.finalizeContent?.bind(c),h=this.concludingExecutions,f={token:r,callId:n,rootCallId:o,name:i,signal:l,...a!==void 0?{agent:a}:{},...s!==void 0?{parent:s}:{},deferContext(p){t.push(p)},concludeTurn(){h.add(this)}};try{let p=H(e.arguments);if(p===void 0)throw new TypeError("tool execution arguments must be losslessly JSON-serializable");let m={...f,arguments:ge(p)};return this.deferredContexts.set(m,t),this.contentFinalizers.set(m,u),this.cancellationStates.set(m,{callerSignal:l,bodyInvoked:!1}),{kind:"ready",exec:m}}catch(p){let m={...f,arguments:void 0};return this.contentFinalizers.set(m,u),{kind:"final-result",exec:m,result:G(p)}}}async prepareScheduledExecution(e){return this.prepareExecution(e,t=>t)}async prepareExecution(e,t){let r=this.createExecution(e);if(r.kind!=="ready")return t(r);let n=r.exec;if(this.callerCancelled(n))return t({kind:"final-result",exec:n,result:he()});try{let o=ue(this,n.agent),i=await this.ctx.waterfall(o,"tools/pre-execute",n,()=>Promise.resolve({kind:"allow"})),a=i.kind==="ask"?await this.serviceAsk(n,i):{decision:i,approvalCancelled:!1},{decision:s}=a;if(this.callerCancelled(n)&&a.approvalCancelled)return await t({kind:"post-result",exec:n,result:he()});let l=s.kind==="allow"?this.guardReason(n):s.reason;return l!==void 0?await t({kind:"post-result",exec:n,result:this.materializeFinalResult({content:[{type:"text",text:`Error: ${l}`}],isError:!0,error:{message:l}})}):this.callerCancelled(n)?await t({kind:"post-result",exec:n,result:he()}):await t({kind:"dispatch",exec:n})}catch(o){return t({kind:"final-result",exec:n,result:G(o)})}}callerCancelled(e){let t=this.cancellationStates.get(e);if(t===void 0)throw new Error("tool registry scheduler invariant violated: missing cancellation state");return t.callerSignal.aborted}cancellationResult(e,t){let r=this.cancellationStates.get(e);if(r===void 0)throw new Error("tool registry scheduler invariant violated: missing cancellation state");return r.bodyInvoked?yr(t):he(t)}async dispatchToolBody(e){let t=this.cancellationStates.get(e);if(t===void 0)throw new Error("tool registry scheduler invariant violated: missing cancellation state");let r=e.signal,n=ni(t.callerSignal,r),o=n.signal;if(gr(o))return n.dispose(),he();e.signal=o;try{let i=this.get(e.name,e.agent);if(!i)throw new ot(e.name);t.bodyInvoked=!0;let a=await i.execute(e.arguments,e),s=this.createSuccessResult(e,i,a);return gr(o)?yr(s):s}catch(i){return G(i)}finally{n.dispose(),e.signal=r}}async dispatchScheduledExecution(e){try{let t=e,r=ue(this,e.agent),n=await this.ctx.waterfall(r,"tools/execute",t,()=>this.dispatchToolBody(t)),o=this.normalizeDispatchResult(e,n),i=this.deferredContexts.get(e);if(i===void 0)throw new Error("tool registry scheduler invariant violated: unprepared execution");let a=i.length===0?o:this.markCanonical(e,{...o,additionalContexts:[...i,...o.additionalContexts??[]]});return{kind:"post-result",result:this.callerCancelled(e)&&!a.isError?this.cancellationResult(e,a):a}}catch(t){return{kind:"final-result",result:G(t)}}}async finalizeScheduledExecution(e,t){try{let r=await this.postExecute(e,t);return this.finishScheduledExecution(e,this.callerCancelled(e)&&!r.isError?this.cancellationResult(e,r):r)}catch(r){return this.finishScheduledExecution(e,G(r))}}finishScheduledExecution(e,t){let r;try{r=this.materializeFinalResult(t)}catch(o){r=this.materializeFinalResult(G(o))}let n;try{n=this.materializeFinalResult(this.applyFinalContent(e,r))}catch(o){n=this.materializeFinalResult(G(o))}return this.notifyResult(e,n),n}applyFinalContent(e,t){let r=this.contentFinalizers.get(e);if(r===void 0)return t;let n=r(e,t);return n===void 0?t:{...t,content:n}}notifyResult(e,t){Object.freeze(e);let{name:r,callId:n}=e,o=a=>{this.ctx.logger.warn(`tool "${r}" (${n}): tools/result observer failed: ${ve(a)}`)},i=this.ctx.events.dispatch("emit",[ue(this,e.agent),"tools/result",e,t]);for(let a of i)try{let s=a(e,t);Promise.resolve(s).catch(o)}catch(s){o(s)}}async serviceAsk(e,t){let r=this.ctx.get("approval");if(r===void 0)return{decision:{kind:"deny",reason:t.reason??`tool "${e.name}" requires approval (not yet supported)`},approvalCancelled:!1};if(e.agent===void 0)return{decision:{kind:"deny",reason:`tool "${e.name}" requires approval, but the call has no agent to route it through`},approvalCancelled:!1};let n=await r.request({agent:e.agent,toolName:e.name,callId:e.callId,...t.reason!==void 0?{reason:t.reason}:{},signal:e.signal});switch(n){case"allowed-once":return{decision:{kind:"allow"},approvalCancelled:!1};case"rejected":return{decision:{kind:"deny",reason:`the user rejected tool "${e.name}"`},approvalCancelled:!1};case"cancelled":return{decision:{kind:"deny",reason:`approval for tool "${e.name}" was cancelled`},approvalCancelled:!0};case"unavailable":return{decision:{kind:"deny",reason:`tool "${e.name}" requires approval, but no approval channel is available`},approvalCancelled:!1};default:return ye(n,"ApprovalOutcome")}}async postExecute(e,t){let r=await this.ctx.waterfall(ue(this,e.agent),"tools/post-execute",e,t,()=>Promise.resolve({kind:"accept"})),n=r.additionalContexts??[];if(r.kind==="block"){let i=Qo(r.feedback);return this.markCanonical(e,{content:r.feedback,isError:!0,error:{message:i},...n.length>0?{additionalContexts:n}:{}})}if(Object.hasOwn(r,"content")&&Object.hasOwn(r,"value"))throw new TypeError("tools/post-execute accept decision cannot replace both value and content");let o=[...t.additionalContexts??[],...n];if(Object.hasOwn(r,"value")){if(t.isError)throw new TypeError("tools/post-execute cannot replace the value of a failed result");let i=this.get(e.name,e.agent);if(i===void 0)throw new ot(e.name);let a=this.createSuccessResult(e,i,r.value);return this.markCanonical(e,{...a,...o.length>0?{additionalContexts:o}:{}})}return this.markCanonical(e,{...t,...r.content!==void 0?{content:r.content}:{},...o.length>0?{additionalContexts:o}:{}})}canonicalResults=new WeakMap;markCanonical(e,t){return this.canonicalResults.set(t,e.token),t}createSuccessResult(e,t,r){let n=Yo(t.name,r),o=qr(t.output.schema,n,"value");if(o.length>0)throw new Z(t.name,o);let i=ge(n),a;try{a=t.output.render(e.arguments,i)}catch(u){throw gt(t.name,"render",u)}let s=hr(t.name,"render",a),l;if(e.parent===void 0&&t.output.presentationMeta!==void 0){let u;try{u=t.output.presentationMeta(e.arguments,i)}catch(h){throw gt(t.name,"presentationMeta",h)}l=hr(t.name,"presentationMeta",u)}let c=this.concludingExecutions.has(e);return this.markCanonical(e,this.materializeFinalResult({isError:!1,value:i,content:s,...l!==void 0?{meta:l}:{},...c?{concludesTurn:!0}:{}}))}normalizeDispatchResult(e,t){if(this.canonicalResults.get(t)===e.token)return t;if(t.isError)return this.markCanonical(e,{isError:!0,error:t.error,content:t.content,...t.meta!==void 0?{meta:t.meta}:{},...t.additionalContexts!==void 0?{additionalContexts:t.additionalContexts}:{}});let r=this.get(e.name,e.agent);if(r===void 0)throw new ot(e.name);let n=this.createSuccessResult(e,r,t.value);return this.markCanonical(e,{...n,...t.additionalContexts!==void 0?{additionalContexts:t.additionalContexts}:{}})}materializeFinalResult(e){let t={content:e.content,...e.meta!==void 0?{meta:e.meta}:{},...e.additionalContexts!==void 0?{additionalContexts:e.additionalContexts}:{}};return e.isError?mr({isError:!0,error:e.error,...t}):ge({...mr({isError:!1,...t,...e.concludesTurn===!0?{concludesTurn:!0}:{}}),value:e.value})}};function ri(){return Symbol("dsh.tool.execution")}function G(e){let t=Zo(e),r=ve(e);return{content:[{type:"text",text:`Error: ${r}`}],isError:!0,error:{message:r,...t?{info:t}:{}}}}function gr(e){return e.aborted}function ni(e,t){if(e===t)return{signal:e,dispose(){}};let r=new AbortController,n=!1,o=()=>{n&&(n=!1,e.removeEventListener("abort",a),t.removeEventListener("abort",s))},i=l=>{let c=l.reason;r.abort(c),o()},a=()=>{i(e)},s=()=>{i(t)};return t.aborted?s():e.aborted?a():(n=!0,e.addEventListener("abort",a,{once:!0}),t.addEventListener("abort",s,{once:!0})),{signal:r.signal,dispose:o}}function yr(e){let t=e?.additionalContexts??[];return{content:[{type:"text",text:"Error: tool call aborted"}],isError:!0,error:{message:"tool call aborted",info:{name:"AbortError",code:Xo}},...t.length>0?{additionalContexts:t}:{}}}function he(e){let t=e?.additionalContexts??[];return{content:[{type:"text",text:"Error: tool call aborted before dispatch"}],isError:!0,error:{message:"tool call aborted before dispatch",info:{name:"AbortError",code:Go}},...t.length>0?{additionalContexts:t}:{}}}var N=class extends Error{constructor(r,n,o){super(r,o);this.code=n;this.name="MemError"}code};var kt=e=>e.toLowerCase().replace(/\s+/gu," ").trim();function ii(e){let t=[e.title,e.subtitle,e.text,e.narrative].map(n=>kt(n??"")),r=(e.facts??[]).map(kt);return t.some(Boolean)||r.some(Boolean)?JSON.stringify([...t,r]):""}function Kr(e){let t=new Set;return e.filter(r=>{let n=ii(r);return n?t.has(n)?!1:(t.add(n),!0):!0})}function Vr(e){let t=new Set;return e.split(`
62
+ `);return t.length>0?t:"tool result blocked by post-execute policy"}function mr(e){let t=H(e);if(t===void 0)throw new TypeError("tool result must be losslessly JSON-serializable");return ge(t)}function Zo(e){try{return e instanceof oe?{name:e.name,code:e.code}:void 0}catch{return}}var ei=class{tools;restrictions=new Zt;guards=new Zt;mode;constructor(e){this.tools=new Xn(t=>new Error(e===void 0?`tool "${t}" is already registered (for a per-agent variant, register through that agent's \`agent.ctx\` instead)`:`tool "${t}" is already registered in this scope`))}isEmpty(){return this.tools.isEmpty()&&this.restrictions.isEmpty()&&this.guards.isEmpty()&&this.mode===void 0}admits(e){for(let t of this.restrictions.values())if(t.allow!==void 0&&!t.allow.has(e)||t.deny!==void 0&&t.deny.has(e))return!1;return!0}guardReason(e){for(let t of this.guards.values()){let r=t(e);if(r!==void 0)return r}}};function ti(e){let t=e??10;if(!Number.isInteger(t)||t<1)throw new Error("maxParallelSubCalls must be a positive integer");return t}var xs=class extends Vn{static inject=["systemPrompt"];static Config=d.object({mode:d.union(["native","code","both"]).default("native"),maxParallelSubCalls:d.natural().min(1).default(10)});[Hr]={prepare:e=>this.prepareScheduledExecution(e),dispatch:e=>this.dispatchScheduledExecution(e),finalize:(e,t)=>this.finalizeScheduledExecution(e,t),finish:(e,t)=>this.finishScheduledExecution(e,t)};deferredContexts=new WeakMap;concludingExecutions=new WeakSet;cancellationStates=new WeakMap;contentFinalizers=new WeakMap;layers=new Gn(e=>new ei(e),()=>{this.ctx.emit("tools/change")});defaultMode;maxParallelSubCalls;codeTransport;constructor(e,t={}){super(e,"tools"),this.defaultMode=t.mode??"native",this.maxParallelSubCalls=ti(t.maxParallelSubCalls),e.systemPrompt.tools(r=>this.wireSchemas(r.scope)),this.defaultMode!=="native"&&e.systemPrompt.section(this.sdkSection())}sdkSection(){return{name:"tools:sdk",order:150,text:e=>{let t=this.modeFor(e.scope);if(t==="native")return"";let r=this.requireCodeRuntime(t),n=nt[r.language];if(n===void 0)throw new Error(`dsh-tools: no SDK renderer for ${r.language}`);return n(this.sdkSchemas(e.scope))}}}modeFor(e){let t=this.layers.chainLayers(e);for(let r=t.length-1;r>=0;r-=1){let n=t[r]?.mode;if(n!==void 0)return n}return this.defaultMode}requireCodeTransport(){return this.codeTransport??=To(this,{requireRuntime:()=>this.requireCodeRuntime(this.defaultMode),peekRuntime:()=>this.ctx.get("codeRuntime"),maxParallel:this.maxParallelSubCalls,shapeDispatchLog:e=>this.shapeDispatchLog(e)}),this.codeTransport}presentAs(e){let t=this.ctx;if(Ie(t)===void 0)throw new Error("tools.presentAs() requires a scoped context (agent.ctx): a context-global presentation is the `mode` config field on the tools row");return t.effect(function*(){yield this.layers.effect(t,r=>{if(r.mode!==void 0)throw new Error(`tools.presentAs("${e}") conflicts with "${r.mode}" already declared for this agent; one composition selects one presentation`);return r.mode=e,()=>{r.mode=void 0}},{label:"tools.presentAs()"}),e!=="native"&&(yield t.systemPrompt.section(this.sdkSection()))}.bind(this),"tools.presentAs()")}wireSchemas(e){let t=this.view(e),r=this.modeFor(e);if(r==="native")return{schemas:[...t.visible.values()].map(o=>this.schemaOf(o,!1)),knownNames:[...t.knownNames]};this.requireCodeRuntime(r);let n=[...t.visible.values()].map(o=>this.schemaOf(o,!1));return r==="code"?{schemas:n.filter(o=>o.name===B),knownNames:[B]}:{schemas:n,knownNames:[...t.knownNames,B]}}requireCodeRuntime(e){let t=this.ctx.get("codeRuntime");if(!t)throw new Error(`dsh-tools: mode "${e}" requires a code runtime \u2014 load a ctx.codeRuntime implementation (e.g. @deepseek-ai/dsh-code-runtime-worker) or set tools mode to "native"`);if(!Object.hasOwn(nt,t.language)){let r=Object.keys(nt).map(n=>JSON.stringify(n)).join(", ");throw new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(t.language)} (known: ${r})`)}return t}register(e){let t=e.name,r=e.output;if(r===void 0||typeof r!="object"||typeof r.render!="function"||r.presentationMeta!==void 0&&typeof r.presentationMeta!="function")throw new TypeError(`tool "${t}" must declare output { schema, render, presentationMeta? }`);xe(r.schema);let n=e.timeoutMs;if(n!==void 0&&(!Number.isFinite(n)||n<=0))throw new TypeError(`tool "${t}" timeoutMs must be a positive finite number`);if(t==="run_code")throw new Error(`tool name "${B}" is reserved for the Code Mode presentation transport and cannot be registered or shadowed`);return this.layers.effect(this.ctx,o=>o.tools.insert(t,e),{label:"tools.register()"})}restrict(e){let t=Ie(this.ctx);if(t===void 0)throw new Error("tools.restrict() requires a scoped context (agent.ctx): a context-global restriction would mask every agent \u2014 deny the tool for the intended agent instead");let r=e.allow,n=e.deny;if(r===void 0&&n===void 0)throw new Error("tools.restrict({}) is a no-op: pass `allow` and/or `deny` (an empty filter is almost always a materialized-empty-config bug)");let o={...r!==void 0?{allow:new Set(r)}:{},...n!==void 0?{deny:new Set(n)}:{}};if([...r??[],...n??[]].includes("run_code"))throw new Error(`tools.restrict() cannot name reserved Code Mode presentation transport "${B}"; restrict end-capability tools instead`);let i=this.view(t).restrictableNames,a=[...r??[],...n??[]].filter(s=>!i.has(s));if(a.length>0)throw new Error(`tools.restrict() names unknown inherited tool${a.length>1?"s":""} ${a.map(s=>`"${s}"`).join(", ")}; a restriction filters what this scope inherits, never what it registers itself. Restrictable tools: ${[...i].sort().join(", ")||"(none)"}`);return this.layers.effect(this.ctx,s=>s.restrictions.append(o),{label:"tools.restrict()"})}guard(e){return this.layers.effect(this.ctx,t=>t.guards.append(e),{label:"tools.guard()",notify:!1})}guardReason(e){let t=this.layers.global.guardReason(e);if(t!==void 0)return t;if(e.agent!==void 0)for(let r of this.layers.chainLayers(e.agent)){let n=r.guardReason(e);if(n!==void 0)return n}}view(e){let t=this.layers.chainLayers(e),r=this.layers.peek(e),n=new Map(this.layers.global.tools.entries());for(let s of t)if(s!==r)for(let[l,c]of s.tools.entries())n.set(l,c);let o=new Map,i=new Set,a=new Set;for(let[s,l]of n)i.add(s),a.add(s),t.every(c=>c.admits(s))&&o.set(s,l);if(r!==void 0)for(let[s,l]of r.tools.entries())i.add(s),o.set(s,l);return this.modeFor(e)!=="native"&&o.set(B,this.requireCodeTransport()),{visible:o,knownNames:i,restrictableNames:a}}get(e,t){return this.view(t).visible.get(e)}schemas(e){return[...this.view(e).visible.values()].map(t=>this.schemaOf(t,!0))}sdkSchemas(e){return[...this.view(e).visible.values()].filter(t=>t.name!==B).map(t=>{let r=H(t.output.schema);if(r===void 0)throw new Error(`tool "${t.name}" output schema must be lossless JSON before SDK projection`);return{...this.schemaOf(t,!0),output:r}})}schemaOf(e,t){let{name:r,description:n,parameters:o}=e,i=t?H(o):o;if(i===void 0)throw new Error(`tool "${r}" parameters must be lossless JSON before schema projection`);return{name:r,description:n,parameters:i}}executionMode(e){let t=this.get(e.name,e.agent);if(!t?.isConcurrencySafe)return{kind:"exclusive"};try{return t.isConcurrencySafe(e.arguments)===!0?{kind:"parallel"}:{kind:"exclusive"}}catch{return{kind:"exclusive"}}}async shapeDispatchLog(e){try{return await this.ctx.waterfall(ue(this,e.agent),"tools/code-dispatch-log",e,()=>Promise.resolve(e.content))}catch(t){return this.ctx.logger.warn(`tools: code-dispatch-log listener failed for ${e.name}: ${ve(t)}; logging the original settled content`),e.content}}async execute(e){return this.prepareExecution(e,t=>this.completeScheduledExecution(t))}async completeScheduledExecution(e){switch(e.kind){case"dispatch":{let t=await this.dispatchScheduledExecution(e.exec);return t.kind==="post-result"?await this.finalizeScheduledExecution(e.exec,t.result):this.finishScheduledExecution(e.exec,t.result)}case"post-result":return await this.finalizeScheduledExecution(e.exec,e.result);case"final-result":return this.finishScheduledExecution(e.exec,e.result);default:return ye(e,"scheduled tool preparation")}}createExecution(e){let t=[],r=ri(),n=e.callId,o=e.rootCallId??n,i=e.name,a=e.agent,s=e.parent,l=e.signal,c=this.get(i,a),u=c?.finalizeContent?.bind(c),h=this.concludingExecutions,f={token:r,callId:n,rootCallId:o,name:i,signal:l,...a!==void 0?{agent:a}:{},...s!==void 0?{parent:s}:{},deferContext(p){t.push(p)},concludeTurn(){h.add(this)}};try{let p=H(e.arguments);if(p===void 0)throw new TypeError("tool execution arguments must be losslessly JSON-serializable");let m={...f,arguments:ge(p)};return this.deferredContexts.set(m,t),this.contentFinalizers.set(m,u),this.cancellationStates.set(m,{callerSignal:l,bodyInvoked:!1}),{kind:"ready",exec:m}}catch(p){let m={...f,arguments:void 0};return this.contentFinalizers.set(m,u),{kind:"final-result",exec:m,result:G(p)}}}async prepareScheduledExecution(e){return this.prepareExecution(e,t=>t)}async prepareExecution(e,t){let r=this.createExecution(e);if(r.kind!=="ready")return t(r);let n=r.exec;if(this.callerCancelled(n))return t({kind:"final-result",exec:n,result:he()});try{let o=ue(this,n.agent),i=await this.ctx.waterfall(o,"tools/pre-execute",n,()=>Promise.resolve({kind:"allow"})),a=i.kind==="ask"?await this.serviceAsk(n,i):{decision:i,approvalCancelled:!1},{decision:s}=a;if(this.callerCancelled(n)&&a.approvalCancelled)return await t({kind:"post-result",exec:n,result:he()});let l=s.kind==="allow"?this.guardReason(n):s.reason;return l!==void 0?await t({kind:"post-result",exec:n,result:this.materializeFinalResult({content:[{type:"text",text:`Error: ${l}`}],isError:!0,error:{message:l}})}):this.callerCancelled(n)?await t({kind:"post-result",exec:n,result:he()}):await t({kind:"dispatch",exec:n})}catch(o){return t({kind:"final-result",exec:n,result:G(o)})}}callerCancelled(e){let t=this.cancellationStates.get(e);if(t===void 0)throw new Error("tool registry scheduler invariant violated: missing cancellation state");return t.callerSignal.aborted}cancellationResult(e,t){let r=this.cancellationStates.get(e);if(r===void 0)throw new Error("tool registry scheduler invariant violated: missing cancellation state");return r.bodyInvoked?yr(t):he(t)}async dispatchToolBody(e){let t=this.cancellationStates.get(e);if(t===void 0)throw new Error("tool registry scheduler invariant violated: missing cancellation state");let r=e.signal,n=ni(t.callerSignal,r),o=n.signal;if(gr(o))return n.dispose(),he();e.signal=o;try{let i=this.get(e.name,e.agent);if(!i)throw new ot(e.name);t.bodyInvoked=!0;let a=await i.execute(e.arguments,e),s=this.createSuccessResult(e,i,a);return gr(o)?yr(s):s}catch(i){return G(i)}finally{n.dispose(),e.signal=r}}async dispatchScheduledExecution(e){try{let t=e,r=ue(this,e.agent),n=await this.ctx.waterfall(r,"tools/execute",t,()=>this.dispatchToolBody(t)),o=this.normalizeDispatchResult(e,n),i=this.deferredContexts.get(e);if(i===void 0)throw new Error("tool registry scheduler invariant violated: unprepared execution");let a=i.length===0?o:this.markCanonical(e,{...o,additionalContexts:[...i,...o.additionalContexts??[]]});return{kind:"post-result",result:this.callerCancelled(e)&&!a.isError?this.cancellationResult(e,a):a}}catch(t){return{kind:"final-result",result:G(t)}}}async finalizeScheduledExecution(e,t){try{let r=await this.postExecute(e,t);return this.finishScheduledExecution(e,this.callerCancelled(e)&&!r.isError?this.cancellationResult(e,r):r)}catch(r){return this.finishScheduledExecution(e,G(r))}}finishScheduledExecution(e,t){let r;try{r=this.materializeFinalResult(t)}catch(o){r=this.materializeFinalResult(G(o))}let n;try{n=this.materializeFinalResult(this.applyFinalContent(e,r))}catch(o){n=this.materializeFinalResult(G(o))}return this.notifyResult(e,n),n}applyFinalContent(e,t){let r=this.contentFinalizers.get(e);if(r===void 0)return t;let n=r(e,t);return n===void 0?t:{...t,content:n}}notifyResult(e,t){Object.freeze(e);let{name:r,callId:n}=e,o=a=>{this.ctx.logger.warn(`tool "${r}" (${n}): tools/result observer failed: ${ve(a)}`)},i=this.ctx.events.dispatch("emit",[ue(this,e.agent),"tools/result",e,t]);for(let a of i)try{let s=a(e,t);Promise.resolve(s).catch(o)}catch(s){o(s)}}async serviceAsk(e,t){let r=this.ctx.get("approval");if(r===void 0)return{decision:{kind:"deny",reason:t.reason??`tool "${e.name}" requires approval (not yet supported)`},approvalCancelled:!1};if(e.agent===void 0)return{decision:{kind:"deny",reason:`tool "${e.name}" requires approval, but the call has no agent to route it through`},approvalCancelled:!1};let n=await r.request({agent:e.agent,toolName:e.name,callId:e.callId,...t.reason!==void 0?{reason:t.reason}:{},signal:e.signal});switch(n){case"allowed-once":return{decision:{kind:"allow"},approvalCancelled:!1};case"rejected":return{decision:{kind:"deny",reason:`the user rejected tool "${e.name}"`},approvalCancelled:!1};case"cancelled":return{decision:{kind:"deny",reason:`approval for tool "${e.name}" was cancelled`},approvalCancelled:!0};case"unavailable":return{decision:{kind:"deny",reason:`tool "${e.name}" requires approval, but no approval channel is available`},approvalCancelled:!1};default:return ye(n,"ApprovalOutcome")}}async postExecute(e,t){let r=await this.ctx.waterfall(ue(this,e.agent),"tools/post-execute",e,t,()=>Promise.resolve({kind:"accept"})),n=r.additionalContexts??[];if(r.kind==="block"){let i=Qo(r.feedback);return this.markCanonical(e,{content:r.feedback,isError:!0,error:{message:i},...n.length>0?{additionalContexts:n}:{}})}if(Object.hasOwn(r,"content")&&Object.hasOwn(r,"value"))throw new TypeError("tools/post-execute accept decision cannot replace both value and content");let o=[...t.additionalContexts??[],...n];if(Object.hasOwn(r,"value")){if(t.isError)throw new TypeError("tools/post-execute cannot replace the value of a failed result");let i=this.get(e.name,e.agent);if(i===void 0)throw new ot(e.name);let a=this.createSuccessResult(e,i,r.value);return this.markCanonical(e,{...a,...o.length>0?{additionalContexts:o}:{}})}return this.markCanonical(e,{...t,...r.content!==void 0?{content:r.content}:{},...o.length>0?{additionalContexts:o}:{}})}canonicalResults=new WeakMap;markCanonical(e,t){return this.canonicalResults.set(t,e.token),t}createSuccessResult(e,t,r){let n=Yo(t.name,r),o=qr(t.output.schema,n,"value");if(o.length>0)throw new Z(t.name,o);let i=ge(n),a;try{a=t.output.render(e.arguments,i)}catch(u){throw gt(t.name,"render",u)}let s=hr(t.name,"render",a),l;if(e.parent===void 0&&t.output.presentationMeta!==void 0){let u;try{u=t.output.presentationMeta(e.arguments,i)}catch(h){throw gt(t.name,"presentationMeta",h)}l=hr(t.name,"presentationMeta",u)}let c=this.concludingExecutions.has(e);return this.markCanonical(e,this.materializeFinalResult({isError:!1,value:i,content:s,...l!==void 0?{meta:l}:{},...c?{concludesTurn:!0}:{}}))}normalizeDispatchResult(e,t){if(this.canonicalResults.get(t)===e.token)return t;if(t.isError)return this.markCanonical(e,{isError:!0,error:t.error,content:t.content,...t.meta!==void 0?{meta:t.meta}:{},...t.additionalContexts!==void 0?{additionalContexts:t.additionalContexts}:{}});let r=this.get(e.name,e.agent);if(r===void 0)throw new ot(e.name);let n=this.createSuccessResult(e,r,t.value);return this.markCanonical(e,{...n,...t.additionalContexts!==void 0?{additionalContexts:t.additionalContexts}:{}})}materializeFinalResult(e){let t={content:e.content,...e.meta!==void 0?{meta:e.meta}:{},...e.additionalContexts!==void 0?{additionalContexts:e.additionalContexts}:{}};return e.isError?mr({isError:!0,error:e.error,...t}):ge({...mr({isError:!1,...t,...e.concludesTurn===!0?{concludesTurn:!0}:{}}),value:e.value})}};function ri(){return Symbol("dsh.tool.execution")}function G(e){let t=Zo(e),r=ve(e);return{content:[{type:"text",text:`Error: ${r}`}],isError:!0,error:{message:r,...t?{info:t}:{}}}}function gr(e){return e.aborted}function ni(e,t){if(e===t)return{signal:e,dispose(){}};let r=new AbortController,n=!1,o=()=>{n&&(n=!1,e.removeEventListener("abort",a),t.removeEventListener("abort",s))},i=l=>{let c=l.reason;r.abort(c),o()},a=()=>{i(e)},s=()=>{i(t)};return t.aborted?s():e.aborted?a():(n=!0,e.addEventListener("abort",a,{once:!0}),t.addEventListener("abort",s,{once:!0})),{signal:r.signal,dispose:o}}function yr(e){let t=e?.additionalContexts??[];return{content:[{type:"text",text:"Error: tool call aborted"}],isError:!0,error:{message:"tool call aborted",info:{name:"AbortError",code:Xo}},...t.length>0?{additionalContexts:t}:{}}}function he(e){let t=e?.additionalContexts??[];return{content:[{type:"text",text:"Error: tool call aborted before dispatch"}],isError:!0,error:{message:"tool call aborted before dispatch",info:{name:"AbortError",code:Go}},...t.length>0?{additionalContexts:t}:{}}}var C=class extends Error{constructor(r,n,o){super(r,o);this.code=n;this.name="MemError"}code};var kt=e=>e.toLowerCase().replace(/\s+/gu," ").trim();function ii(e){let t=[e.title,e.subtitle,e.text,e.narrative].map(n=>kt(n??"")),r=(e.facts??[]).map(kt);return t.some(Boolean)||r.some(Boolean)?JSON.stringify([...t,r]):""}function Kr(e){let t=new Set;return e.filter(r=>{let n=ii(r);return n?t.has(n)?!1:(t.add(n),!0):!0})}function Vr(e){let t=new Set;return e.split(`
63
63
  `).filter(r=>{if(!/^\|\s*#\d+\s*\|.*\|$/u.test(r))return!0;let n=r.slice(1,-1).split("|");if(n.length<5)return!0;let o=JSON.stringify(n.slice(2).map(kt));return t.has(o)?!1:(t.add(o),!0)}).join(`
64
- `)}import{randomBytes as Qr}from"node:crypto";import{constants as Zr,openSync as tn,closeSync as rn,readFileSync as $i,writeFileSync as _i,fstatSync as Ri,fchmodSync as Ai,fsyncSync as Ni,linkSync as Ci,unlinkSync as Ti,mkdirSync as Di}from"node:fs";import{join as _t}from"node:path";import{join as se,dirname as yi,basename as bi}from"path";import{homedir as wi}from"os";import{fileURLToPath as vi}from"url";import{homedir as si}from"os";import{join as ai}from"path";function ee(e,t=process.platform,r=si()){return typeof e!="string"||e.length===0?e:e==="~"?r:e.startsWith("~/")||t==="win32"&&e.startsWith("~\\")?ai(r,e.slice(2)):e}import{existsSync as mi}from"fs";import{homedir as gi}from"os";import{join as Yr}from"path";import{closeSync as Gs,existsSync as Ys,fsyncSync as Qs,lstatSync as Zs,mkdirSync as ea,openSync as ta,readFileSync as li,readlinkSync as ra,realpathSync as na,renameSync as oa,statSync as ia,unlinkSync as sa,writeSync as aa}from"fs";var Hs=Promise.resolve();var ca=process.platform==="win32";function ci(e){return e.replace(/^\uFEFF/,"")}function ui(e){return JSON.parse(ci(e))}function jt(e){return ui(li(e,"utf-8"))}var ie="MEMINDEX_",di="AGENT_MEM_",Oe=[di];function Je(e){return e.startsWith(ie)||Oe.some(t=>e.startsWith(t))}function $t(e){if(!e.startsWith(ie))return[];let t=e.slice(ie.length);return Oe.map(r=>r+t)}function pi(e=process.env){for(let t of Oe)for(let r of Object.keys(e)){if(!r.startsWith(t))continue;let n=ie+r.slice(t.length);e[n]===void 0&&(e[n]=e[r])}}function Xr(e){let t=null;for(let r of Oe)for(let n of Object.keys(e)){if(!n.startsWith(r))continue;let o=ie+n.slice(r.length);(t??e)[o]===void 0&&(t??={...e},t[o]=e[n])}return t??e}pi();var fi=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function hi(e){let t=e.env;return fi(t)&&Object.keys(t).some(Je)?"nested":"flat"}function Gr(e){return hi(e)==="nested"?e.env:e}function Se(e=process.env,t=gi()){if(e.MEMINDEX_DATA_DIR)return ee(e.MEMINDEX_DATA_DIR,process.platform,t);let r=Yr(t,".memindex"),n=Yr(r,"settings.json");try{if(mi(n)){let o=jt(n);if(o===null||typeof o!="object"||Array.isArray(o))return r;let i=Xr(Gr(o));if(typeof i.MEMINDEX_DATA_DIR=="string"&&i.MEMINDEX_DATA_DIR)return ee(i.MEMINDEX_DATA_DIR,process.platform,t)}}catch{}return r}function xi(){return typeof __dirname<"u"?__dirname:yi(vi(import.meta.url))}var Aa=xi();function Oi(e){let t=process.env.MEMINDEX_TEST_FORBIDDEN_DATA_DIR;if(t&&e===t)throw new Error(`A test resolved the real data folder ${e}. Point MEMINDEX_DATA_DIR at a temporary directory (and pass env: process.env to any child process the test starts).`);return e}function Ee(){return Oi(Se())}var We=Ee(),Si=se(wi(),".claude"),Ei=process.env.CLAUDE_CONFIG_DIR||Si,Na=se(Ei,"plugins","marketplaces","memindex");var Ca=se(We,"logs"),Ta=se(We,"settings.json"),ki="memindex.db";var Da=se(We,ki),ji=se(We,"observer-sessions"),Ia=bi(ji);var en="X-Memindex-Secret",nn="worker-secret",Ii=/^[a-f0-9]{64}$/;function Rt(e=Ee()){let t=tn(_t(e,nn),Zr.O_RDONLY|(Zr.O_NOFOLLOW??0));try{let r=Ri(t);if(!r.isFile()||process.getuid&&r.uid!==process.getuid()||process.platform!=="win32"&&(r.mode&63)!==0)throw new Error("Worker secret must be an owner-only file");let n=$i(t,"utf8");if(!Ii.test(n))throw new Error("Invalid worker secret");return n}finally{rn(t)}}function Mi(e=Ee()){Di(e,{recursive:!0,mode:448});let t=_t(e,nn);try{return Rt(e)}catch(o){if(o.code!=="ENOENT")throw o}let r=_t(e,`.worker-secret-${Qr(16).toString("hex")}`),n=tn(r,"wx",384);try{Ai(n,384),_i(n,Qr(32).toString("hex")),Ni(n)}finally{rn(n)}try{try{Ci(r,t)}catch(o){if(o.code!=="EEXIST")throw o}}finally{Ti(r)}return Rt(e)}function Le(e,t=Ee()){let r=(e.method??"GET").toUpperCase(),n=r==="GET"||r==="HEAD",o=new Headers(e.headers);if(n)try{o.set(en,Rt(t))}catch{return e}else o.set(en,Mi(t));return{...e,headers:o,redirect:"error"}}function At(e,t={}){let r=new URLSearchParams;return Object.entries(e).forEach(([n,o])=>{o!==void 0&&r.set(t[n]??n,String(o))}),r.size?`?${r}`:""}var Be=class{constructor(t){this.settings=t}settings;search(t,r){return this.readIndex("/api/search",At({...t},{obsType:"obs_type"}),r)}timeline(t,r){let n=At({...t},{depthBefore:"depth_before",depthAfter:"depth_after"});return this.readIndex("/api/timeline",n,r)}async getObservations(t,r){if(!t.ids.length)throw new N("Choose at least one memory id.","MEM_INVALID_REQUEST");let n=await this.exchange("/api/observations/batch",r,t);return{items:Array.isArray(n)?n.map(sn):[]}}async save(t,r){if(!t.text.trim())throw new N("Enter some memory text.","MEM_INVALID_REQUEST");return await this.exchange("/api/memory/save",r,t)}async context(t,r){let n=t.projects?.trim(),o=t.cwd?.trim();if(!n&&!o)throw new N("Choose a project or checkout folder.","MEM_INVALID_REQUEST");let i=At({...t,projects:n||void 0,cwd:o||void 0});return await this.exchange(`/api/context/inject${i}`,r,void 0,!0)}async sessionInit(t,r){await this.exchange("/api/sessions/init",r,t)}async sessionSummarize(t,r){await this.exchange("/api/sessions/summarize",r,t)}async readIndex(t,r,n){let o=await this.exchange(`${t}${r}`,n),i=Nt(o),a=Array.isArray(o)?o:Array.isArray(i.items)?i.items:[],l=(Array.isArray(i.content)?i.content:[]).flatMap(h=>{let f=Nt(h);return f.type==="text"&&typeof f.text=="string"?[f.text]:[]}),c=a.map(sn),u=l.length?l.join(`
65
- `):void 0;return this.settings.dedupe!==!1&&(c=Kr(c),u!==void 0&&(u=Vr(u))),u===void 0?{items:c}:{items:c,content:u}}async exchange(t,r,n,o=!1){if(r?.aborted)throw new N("Memory operation cancelled.","MEM_ABORTED");let i=new AbortController,a=()=>i.abort(r?.reason);r?.addEventListener("abort",a,{once:!0});let s=!1,l=this.settings.timeoutMs>0?setTimeout(()=>{s=!0,i.abort()},this.settings.timeoutMs):void 0;try{let c={signal:i.signal,method:n===void 0?"GET":"POST"};n!==void 0&&(c.headers={"Content-Type":"application/json"},c.body=JSON.stringify(n));let u=await fetch(this.settings.baseUrl.replace(/\/+$/u,"")+t,Le(c));if(!u.ok){let h=await u.text();throw new N(`Worker HTTP ${u.status}: ${h.substring(0,500)}`,"MEM_PROVIDER_ERROR")}return o?await u.text():await u.json()}catch(c){if(s)throw new N(`Memory operation exceeded ${this.settings.timeoutMs} ms.`,"MEM_TIMEOUT");if(r?.aborted)throw new N("Memory operation cancelled.","MEM_ABORTED");if(c instanceof N)throw c;let u=c instanceof Error?c.message:String(c);throw new N(`Unable to read the memory worker: ${u}`,"MEM_PROVIDER_ERROR",{cause:c})}finally{clearTimeout(l),r?.removeEventListener("abort",a)}}};function Nt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function on(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var Pi={memory_session_id:"memorySessionId",type:"type",project:"project",subtitle:"subtitle",text:"text",narrative:"narrative",created_at:"createdAt",content_hash:"contentHash",generated_by_model:"generatedByModel",merged_into_project:"mergedIntoProject",agent_type:"agentType",agent_id:"agentId",origin_device_id:"originDeviceId",origin_local_id:"originLocalId",sync_rev:"syncRev"},Fi={created_at_epoch:"createdAtEpoch",prompt_number:"promptNumber",discovery_tokens:"discoveryTokens",relevance_count:"relevanceCount",synced_at:"syncedAt"},qi={facts:"facts",concepts:"concepts",files_read:"filesRead",files_modified:"filesModified"};function sn(e){let t=Nt(e),r=Number(t.id),n={id:Number.isFinite(r)?r:0,title:typeof t.title=="string"?t.title:""};Object.entries(Pi).forEach(([i,a])=>{typeof t[i]=="string"&&(n[a]=t[i])}),Object.entries(Fi).forEach(([i,a])=>{let s=t[i]??t[a];typeof s=="number"&&Number.isFinite(s)&&(n[a]=s)}),Object.entries(qi).forEach(([i,a])=>{let s=on(t[i]);Array.isArray(s)&&(n[a]=s.filter(l=>typeof l=="string"))});let o=on(t.metadata);return o&&typeof o=="object"&&!Array.isArray(o)&&(n.metadata=o),n}import{basename as as}from"node:path";import{existsSync as pn,readFileSync as os}from"node:fs";import{homedir as fn}from"node:os";import{join as ae}from"node:path";import{spawn as is}from"node:child_process";var Ji=new Set(["ECONNREFUSED","ConnectionRefused"]);function Ct(e,t){if(!e||typeof e!="object"||t.has(e))return!1;if(t.add(e),e instanceof Error&&e.message.includes("ECONNREFUSED"))return!0;let r=e;return typeof r.code=="string"&&Ji.has(r.code)||Ct(r.cause,t)?!0:Array.isArray(r.errors)&&r.errors.some(n=>Ct(n,t))}function an(e){return Ct(e,new Set)?!0:e instanceof Error&&e.message.includes("ECONNREFUSED")}import{createHash as un}from"crypto";import{realpathSync as Wi}from"fs";import{homedir as ze,tmpdir as ln}from"os";import{basename as Li,dirname as Bi,join as zi,resolve as Ui,sep as cn,win32 as Hi}from"path";var Ki=4e4,Vi=9e3,Xi=["/tmp","/private/tmp","/var/folders","/private/var/folders"];function ke(e){let t=Ui(e),r=[],n=t;for(;;)try{return zi(Wi.native(n),...r.reverse())}catch{let o=Bi(n);if(o===n)return t;r.push(Li(n)),n=o}}function Gi(e,t){let r=ke(t);return e===r||e.startsWith(r.endsWith(cn)?r:r+cn)}function Yi(e,t=ze()){let r=ke(e),n=ke(t);return(process.platform==="win32"?[ln()]:[ln(),...Xi]).some(i=>ke(i)!==n&&Gi(r,i))}function Qi(e=process.env,t=ze()){return e.MEMINDEX_TEST_FORBIDDEN_DATA_DIR?!0:Yi(Se(e,t),t)}var Zi=39e3,es=500;function ts(e){return un("sha256").update(Hi.resolve(e).toLowerCase()).digest().readUInt32BE(0)%es}function rs(e=process.platform,t=ze()){return e==="win32"?Zi+ts(t):38700+(process.getuid?.()??77)%100}function ns(e){let t=un("sha256").update(ke(e)).digest();return Ki+t.readUInt32BE(0)%Vi}function dn(e=process.env,t=ze()){return Qi(e,t)?ns(Se(e,t)):rs(process.platform,t)}var Tt=5e3;function Ue(){let e=ee(process.env.MEMINDEX_DATA_DIR||process.env.AGENT_MEM_DATA_DIR||ae(fn(),".memindex")),t={};try{let s=JSON.parse(os(ae(e,"settings.json"),"utf8").replace(/^\uFEFF/,"")),l=s?.env;t=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).some(Je)?l:s??{}}catch{}let r=s=>typeof t[s]=="string"&&t[s]?String(t[s]):"",n=(s,l)=>process.env[s]||$t(s).map(c=>process.env[c]).find(Boolean)||r(s)||$t(s).map(r).find(Boolean)||l,o=n("MEMINDEX_WORKER_HOST","127.0.0.1"),i=o==="localhost"?"127.0.0.1":o,a=n("MEMINDEX_WORKER_PORT",String(dn()));return"http://"+(i.includes(":")&&!i.startsWith("[")?"["+i+"]":i)+":"+a}var je;function ss(){if(je)return je;let e=ae(process.env.CLAUDE_CONFIG_DIR||ae(fn(),".claude"),"plugins","marketplaces","memindex"),t=ae(e,"plugin","scripts","bun-runner.js"),r=ae(e,"plugin","scripts","worker-service.cjs");return!pn(t)||!pn(r)?Promise.reject(new Error("Run npx memindex install to install the worker.")):(je=new Promise((o,i)=>{let a=is(process.execPath,[t,r,"start"],{stdio:"ignore",windowsHide:!0,timeout:15e3});a.once("error",i),a.once("close",s=>s===0?o():i(new Error("memindex worker could not start")))}).finally(()=>{je=void 0}),je)}function hn(){let e=Ue();return{reset(){e=Ue()},async ready(){try{let t=await fetch(e+"/api/health",{signal:AbortSignal.timeout(Tt)});if(t.ok)return;throw new Error("memindex health check returned "+t.status)}catch(t){if(!an(t))throw t;await ss()}},async request(t,r={}){let n=await fetch(e+t,Le({...r,signal:r.signal?AbortSignal.any([r.signal,AbortSignal.timeout(Tt)]):AbortSignal.timeout(Tt)}));if(!n.ok)throw new Error("memindex "+t+" returned "+n.status);return n},async post(t,r){return this.request(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}}}function mn(e,t,r){let n=r.platformSource?{platformSource:r.platformSource}:{},o=i=>r.project?.trim()?r.project:as(i.session.header.cwd||"")||"dsh";if(e.on("agent/created",async({agent:i})=>{if(r.injectContext)try{r.startLocalWorker&&await hn().ready();let a=i.session.header.cwd,s=r.project?.trim()?r.project:void 0;if(!a&&!s)return;let l=await t.context({...n,...a?{cwd:a}:{},...s?{projects:s}:{}});l&&i.inject(Rr({source:{kind:"plugin:memindex"},content:[{text:l,type:"text"}]}))}catch{}}),r.ingest){let i=new Set(r.toolFilter.names);e.on("tools/result",async(a,s)=>{if(s.isError||!a.agent||!i.has(a.name))return;let l=s.content.flatMap(c=>c.type==="text"&&typeof c.text=="string"?[c.text]:[]).join(`
66
- `).trim();if(l)try{await t.save({project:o(a.agent),text:`[${a.name}] ${l}`})}catch{}})}r.summarize&&e.on("agent/turn-stopping",async({agent:i})=>{try{await t.sessionSummarize({...n,project:o(i),contentSessionId:i.session.id})}catch{}})}var b=(e,t)=>t?{type:e,description:t}:{type:e},Pt=e=>({additionalProperties:!1,properties:e,type:"object"}),qt=e=>({items:e,type:"array"}),P=e=>({...e,required:!0}),ls=qt(b("string")),$e={title:P(b("string")),id:P(b("number")),narrative:b("string"),createdAtEpoch:b("number"),project:b("string"),type:b("string")},le={...$e};for(let e of["memorySessionId","subtitle","text","createdAt","contentHash","generatedByModel","mergedIntoProject","agentType","agentId","originDeviceId","originLocalId","syncRev"])le[e]=b("string");for(let e of["promptNumber","discoveryTokens","relevanceCount","syncedAt"])le[e]=b("number");for(let e of["facts","concepts","filesRead","filesModified"])le[e]=ls;le.metadata={additionalProperties:!0,type:"object"};var Dt=e=>Pt({content:b("string"),items:P(qt(Pt(e)))}),He=b("string","Keep records belonging to this project."),It=b("string","Limit recall to a host platform; leave unset for shared memory.");function Mt(e,t){let r=e.items.map(n=>Object.fromEntries(Object.keys(t).filter(o=>n[o]!==void 0).map(o=>[o,structuredClone(n[o])])));return e.content===void 0?{items:r}:{items:r,content:e.content}}function gn(e,t,r){function n(i,a,s,l,c,u){e.tools.register(St({name:i,parameters:s,description:a,execute:c,timeoutMs:r.timeoutMs,isConcurrencySafe:()=>!0,output:{schema:l,render:(h,f)=>[{text:u(f),type:"text"}]}}))}r.search!==!1&&n("mem_search","Find earlier work by topic. Review this compact list before opening individual memories.",{query:P(b("string","Words describing the work or decision to recall.")),project:He,platformSource:It,limit:b("integer","Upper bound on returned matches; the worker defaults to 20."),offset:b("integer","Number of matches already read."),type:b("string","Record collection: observations, sessions, or prompts."),obsType:b("string","Observation categories separated by commas."),dateStart:b("string","Earliest included ISO date."),dateEnd:b("string","Latest included ISO date."),orderBy:b("string","Chronological ordering: date_asc or date_desc.")},Dt($e),async(i,a)=>{let s={...i,query:i.query.trim()};return["date_asc","date_desc"].includes(s.orderBy)||delete s.orderBy,Mt(await t.search(s,a.signal),$e)},Ft),r.timeline!==!1&&n("mem_timeline","Read the neighboring memories around a known record or a matching topic.",{anchor:b("integer","Record identifier at the center of the window."),query:b("string","Topic used to locate the center when its identifier is unknown."),depthBefore:b("integer","Earlier records to include; defaults to 3."),depthAfter:b("integer","Later records to include; defaults to 3."),project:He,platformSource:It},Dt($e),async(i,a)=>Mt(await t.timeline(i,a.signal),$e),Ft),r.getObservations!==!1&&n("mem_get_observations","Open selected memory records with their complete stored details.",{ids:{...P(qt(b("integer"))),description:"Identifiers selected from recall results."},project:He},Dt(le),async(i,a)=>{if(!i.ids.length)throw new Error("Choose one or more memory identifiers.");return Mt(await t.getObservations(i,a.signal),le)},cs);let o={};for(let i of["title","project","message"])o[i]=P(b("string"));o.id=P(b("number")),o.success=P(b("boolean")),r.save!==!1&&n("mem_save","Keep a note for future sessions. The supplied text is stored directly.",{text:P(b("string","The durable note to record.")),title:b("string","Short heading for this note."),project:He,metadata:{type:"object",additionalProperties:!0,description:"Extra JSON attributes to retain with the note."}},Pt(o),(i,a)=>t.save({...i,text:i.text.trim()},a.signal),i=>`Saved observation #${i.id} (${i.title})`),r.context!==!1&&n("mem_context","Read the startup memory briefing prepared by the worker for the requested projects.",{projects:P(b("string","Comma-separated project ancestry, ending with the active project.")),platformSource:It,full:b("boolean","Include the expanded briefing."),colors:b("boolean","Allow ANSI color codes in the briefing.")},b("string"),(i,a)=>{if(!i.projects.trim())throw new Error("Choose a project for the memory briefing.");return t.context(i,a.signal)},i=>i)}function Ft(e){return e.content?e.content:e.items.length?e.items.map(t=>[`#${t.id} ${t.title}${t.type===void 0?"":` [${t.type}]`}${t.project===void 0?"":` (${t.project})`}`,...t.narrative===void 0?[]:[` ${t.narrative}`]].join(`
64
+ `)}import{createHmac as qa,randomBytes as Qr,timingSafeEqual as La}from"node:crypto";import{constants as Zr,openSync as tn,closeSync as rn,readFileSync as $i,writeFileSync as _i,fstatSync as Ri,fchmodSync as Ai,fsyncSync as Ci,linkSync as Ni,unlinkSync as Ti,mkdirSync as Ii}from"node:fs";import{join as _t}from"node:path";import{join as se,dirname as yi,basename as bi}from"path";import{homedir as wi}from"os";import{fileURLToPath as vi}from"url";import{homedir as si}from"os";import{join as ai}from"path";function ee(e,t=process.platform,r=si()){return typeof e!="string"||e.length===0?e:e==="~"?r:e.startsWith("~/")||t==="win32"&&e.startsWith("~\\")?ai(r,e.slice(2)):e}import{existsSync as mi}from"fs";import{homedir as gi}from"os";import{join as Yr}from"path";import{closeSync as Gs,existsSync as Ys,fsyncSync as Qs,lstatSync as Zs,mkdirSync as ea,openSync as ta,readFileSync as li,readlinkSync as ra,realpathSync as na,renameSync as oa,statSync as ia,unlinkSync as sa,writeSync as aa}from"fs";var Hs=Promise.resolve();var ca=process.platform==="win32";function ci(e){return e.replace(/^\uFEFF/,"")}function ui(e){return JSON.parse(ci(e))}function jt(e){return ui(li(e,"utf-8"))}var ie="MEMINDEX_",di="AGENT_MEM_",Oe=[di];function Le(e){return e.startsWith(ie)||Oe.some(t=>e.startsWith(t))}function $t(e){if(!e.startsWith(ie))return[];let t=e.slice(ie.length);return Oe.map(r=>r+t)}function pi(e=process.env){for(let t of Oe)for(let r of Object.keys(e)){if(!r.startsWith(t))continue;let n=ie+r.slice(t.length);e[n]===void 0&&(e[n]=e[r])}}function Xr(e){let t=null;for(let r of Oe)for(let n of Object.keys(e)){if(!n.startsWith(r))continue;let o=ie+n.slice(r.length);(t??e)[o]===void 0&&(t??={...e},t[o]=e[n])}return t??e}pi();var fi=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function hi(e){let t=e.env;return fi(t)&&Object.keys(t).some(Le)?"nested":"flat"}function Gr(e){return hi(e)==="nested"?e.env:e}function Se(e=process.env,t=gi()){if(e.MEMINDEX_DATA_DIR)return ee(e.MEMINDEX_DATA_DIR,process.platform,t);let r=Yr(t,".memindex"),n=Yr(r,"settings.json");try{if(mi(n)){let o=jt(n);if(o===null||typeof o!="object"||Array.isArray(o))return r;let i=Xr(Gr(o));if(typeof i.MEMINDEX_DATA_DIR=="string"&&i.MEMINDEX_DATA_DIR)return ee(i.MEMINDEX_DATA_DIR,process.platform,t)}}catch{}return r}function xi(){return typeof __dirname<"u"?__dirname:yi(vi(import.meta.url))}var Aa=xi();function Oi(e){let t=process.env.MEMINDEX_TEST_FORBIDDEN_DATA_DIR;if(t&&e===t)throw new Error(`A test resolved the real data folder ${e}. Point MEMINDEX_DATA_DIR at a temporary directory (and pass env: process.env to any child process the test starts).`);return e}function Ee(){return Oi(Se())}var We=Ee(),Si=se(wi(),".claude"),Ei=process.env.CLAUDE_CONFIG_DIR||Si,Ca=se(Ei,"plugins","marketplaces","memindex");var Na=se(We,"logs"),Ta=se(We,"settings.json"),ki="memindex.db";var Ia=se(We,ki),ji=se(We,"observer-sessions"),Da=bi(ji);var en="X-Memindex-Secret",nn="worker-secret",Di=/^[a-f0-9]{64}$/;function Rt(e=Ee()){let t=tn(_t(e,nn),Zr.O_RDONLY|(Zr.O_NOFOLLOW??0));try{let r=Ri(t);if(!r.isFile()||process.getuid&&r.uid!==process.getuid()||process.platform!=="win32"&&(r.mode&63)!==0)throw new Error("Worker secret must be an owner-only file");let n=$i(t,"utf8");if(!Di.test(n))throw new Error("Invalid worker secret");return n}finally{rn(t)}}function Mi(e=Ee()){Ii(e,{recursive:!0,mode:448});let t=_t(e,nn);try{return Rt(e)}catch(o){if(o.code!=="ENOENT")throw o}let r=_t(e,`.worker-secret-${Qr(16).toString("hex")}`),n=tn(r,"wx",384);try{Ai(n,384),_i(n,Qr(32).toString("hex")),Ci(n)}finally{rn(n)}try{try{Ni(r,t)}catch(o){if(o.code!=="EEXIST")throw o}}finally{Ti(r)}return Rt(e)}function Je(e,t=Ee()){let r=(e.method??"GET").toUpperCase(),n=r==="GET"||r==="HEAD",o=new Headers(e.headers);if(n)try{o.set(en,Rt(t))}catch{return e}else o.set(en,Mi(t));return{...e,headers:o,redirect:"error"}}function At(e,t={}){let r=new URLSearchParams;return Object.entries(e).forEach(([n,o])=>{o!==void 0&&r.set(t[n]??n,String(o))}),r.size?`?${r}`:""}var Be=class{constructor(t){this.settings=t}settings;search(t,r){return this.readIndex("/api/search",At({...t},{obsType:"obs_type"}),r)}timeline(t,r){let n=At({...t},{depthBefore:"depth_before",depthAfter:"depth_after"});return this.readIndex("/api/timeline",n,r)}async getObservations(t,r){if(!t.ids.length)throw new C("Choose at least one memory id.","MEM_INVALID_REQUEST");let n=await this.exchange("/api/observations/batch",r,t);return{items:Array.isArray(n)?n.map(sn):[]}}async save(t,r){if(!t.text.trim())throw new C("Enter some memory text.","MEM_INVALID_REQUEST");return await this.exchange("/api/memory/save",r,t)}async context(t,r){let n=t.projects?.trim(),o=t.cwd?.trim();if(!n&&!o)throw new C("Choose a project or checkout folder.","MEM_INVALID_REQUEST");let i=At({...t,projects:n||void 0,cwd:o||void 0});return await this.exchange(`/api/context/inject${i}`,r,void 0,!0)}async sessionInit(t,r){await this.exchange("/api/sessions/init",r,t)}async sessionSummarize(t,r){await this.exchange("/api/sessions/summarize",r,t)}async readIndex(t,r,n){let o=await this.exchange(`${t}${r}`,n),i=Ct(o),a=Array.isArray(o)?o:Array.isArray(i.items)?i.items:[],l=(Array.isArray(i.content)?i.content:[]).flatMap(h=>{let f=Ct(h);return f.type==="text"&&typeof f.text=="string"?[f.text]:[]}),c=a.map(sn),u=l.length?l.join(`
65
+ `):void 0;return this.settings.dedupe!==!1&&(c=Kr(c),u!==void 0&&(u=Vr(u))),u===void 0?{items:c}:{items:c,content:u}}async exchange(t,r,n,o=!1){if(r?.aborted)throw new C("Memory operation cancelled.","MEM_ABORTED");let i=new AbortController,a=()=>i.abort(r?.reason);r?.addEventListener("abort",a,{once:!0});let s=!1,l=this.settings.timeoutMs>0?setTimeout(()=>{s=!0,i.abort()},this.settings.timeoutMs):void 0;try{let c={signal:i.signal,method:n===void 0?"GET":"POST"};n!==void 0&&(c.headers={"Content-Type":"application/json"},c.body=JSON.stringify(n));let u=await fetch(this.settings.baseUrl.replace(/\/+$/u,"")+t,Je(c));if(!u.ok){let h=await u.text();throw new C(`Worker HTTP ${u.status}: ${h.substring(0,500)}`,"MEM_PROVIDER_ERROR")}return o?await u.text():await u.json()}catch(c){if(s)throw new C(`Memory operation exceeded ${this.settings.timeoutMs} ms.`,"MEM_TIMEOUT");if(r?.aborted)throw new C("Memory operation cancelled.","MEM_ABORTED");if(c instanceof C)throw c;let u=c instanceof Error?c.message:String(c);throw new C(`Unable to read the memory worker: ${u}`,"MEM_PROVIDER_ERROR",{cause:c})}finally{clearTimeout(l),r?.removeEventListener("abort",a)}}};function Ct(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function on(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var Pi={memory_session_id:"memorySessionId",type:"type",project:"project",subtitle:"subtitle",text:"text",narrative:"narrative",created_at:"createdAt",content_hash:"contentHash",generated_by_model:"generatedByModel",merged_into_project:"mergedIntoProject",agent_type:"agentType",agent_id:"agentId",origin_device_id:"originDeviceId",origin_local_id:"originLocalId",sync_rev:"syncRev"},Fi={created_at_epoch:"createdAtEpoch",prompt_number:"promptNumber",discovery_tokens:"discoveryTokens",relevance_count:"relevanceCount",synced_at:"syncedAt"},qi={facts:"facts",concepts:"concepts",files_read:"filesRead",files_modified:"filesModified"};function sn(e){let t=Ct(e),r=Number(t.id),n={id:Number.isFinite(r)?r:0,title:typeof t.title=="string"?t.title:""};Object.entries(Pi).forEach(([i,a])=>{typeof t[i]=="string"&&(n[a]=t[i])}),Object.entries(Fi).forEach(([i,a])=>{let s=t[i]??t[a];typeof s=="number"&&Number.isFinite(s)&&(n[a]=s)}),Object.entries(qi).forEach(([i,a])=>{let s=on(t[i]);Array.isArray(s)&&(n[a]=s.filter(l=>typeof l=="string"))});let o=on(t.metadata);return o&&typeof o=="object"&&!Array.isArray(o)&&(n.metadata=o),n}import{basename as as}from"node:path";import{existsSync as pn,readFileSync as os}from"node:fs";import{homedir as fn}from"node:os";import{join as ae}from"node:path";import{spawn as is}from"node:child_process";var Li=new Set(["ECONNREFUSED","ConnectionRefused"]);function Nt(e,t){if(!e||typeof e!="object"||t.has(e))return!1;if(t.add(e),e instanceof Error&&e.message.includes("ECONNREFUSED"))return!0;let r=e;return typeof r.code=="string"&&Li.has(r.code)||Nt(r.cause,t)?!0:Array.isArray(r.errors)&&r.errors.some(n=>Nt(n,t))}function an(e){return Nt(e,new Set)?!0:e instanceof Error&&e.message.includes("ECONNREFUSED")}import{createHash as un}from"crypto";import{realpathSync as Wi}from"fs";import{homedir as Ue,tmpdir as ln}from"os";import{basename as Ji,dirname as Bi,join as Ui,resolve as zi,sep as cn,win32 as Hi}from"path";var Ki=4e4,Vi=9e3,Xi=["/tmp","/private/tmp","/var/folders","/private/var/folders"];function ke(e){let t=zi(e),r=[],n=t;for(;;)try{return Ui(Wi.native(n),...r.reverse())}catch{let o=Bi(n);if(o===n)return t;r.push(Ji(n)),n=o}}function Gi(e,t){let r=ke(t);return e===r||e.startsWith(r.endsWith(cn)?r:r+cn)}function Yi(e,t=Ue()){let r=ke(e),n=ke(t);return(process.platform==="win32"?[ln()]:[ln(),...Xi]).some(i=>ke(i)!==n&&Gi(r,i))}function Qi(e=process.env,t=Ue()){return e.MEMINDEX_TEST_FORBIDDEN_DATA_DIR?!0:Yi(Se(e,t),t)}var Zi=39e3,es=500;function ts(e){return un("sha256").update(Hi.resolve(e).toLowerCase()).digest().readUInt32BE(0)%es}function rs(e=process.platform,t=Ue()){return e==="win32"?Zi+ts(t):38700+(process.getuid?.()??77)%100}function ns(e){let t=un("sha256").update(ke(e)).digest();return Ki+t.readUInt32BE(0)%Vi}function dn(e=process.env,t=Ue()){return Qi(e,t)?ns(Se(e,t)):rs(process.platform,t)}var Tt=5e3;function ze(){let e=ee(process.env.MEMINDEX_DATA_DIR||process.env.AGENT_MEM_DATA_DIR||ae(fn(),".memindex")),t={};try{let s=JSON.parse(os(ae(e,"settings.json"),"utf8").replace(/^\uFEFF/,"")),l=s?.env;t=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).some(Le)?l:s??{}}catch{}let r=s=>typeof t[s]=="string"&&t[s]?String(t[s]):"",n=(s,l)=>process.env[s]||$t(s).map(c=>process.env[c]).find(Boolean)||r(s)||$t(s).map(r).find(Boolean)||l,o=n("MEMINDEX_WORKER_HOST","127.0.0.1"),i=o==="localhost"?"127.0.0.1":o,a=n("MEMINDEX_WORKER_PORT",String(dn()));return"http://"+(i.includes(":")&&!i.startsWith("[")?"["+i+"]":i)+":"+a}var je;function ss(){if(je)return je;let e=ae(process.env.CLAUDE_CONFIG_DIR||ae(fn(),".claude"),"plugins","marketplaces","memindex"),t=ae(e,"plugin","scripts","bun-runner.js"),r=ae(e,"plugin","scripts","worker-service.cjs");return!pn(t)||!pn(r)?Promise.reject(new Error("Run npx memindex install to install the worker.")):(je=new Promise((o,i)=>{let a=is(process.execPath,[t,r,"start"],{stdio:"ignore",windowsHide:!0,timeout:15e3});a.once("error",i),a.once("close",s=>s===0?o():i(new Error("memindex worker could not start")))}).finally(()=>{je=void 0}),je)}function hn(){let e=ze();return{reset(){e=ze()},async ready(){try{let t=await fetch(e+"/api/health",{signal:AbortSignal.timeout(Tt)});if(t.ok)return;throw new Error("memindex health check returned "+t.status)}catch(t){if(!an(t))throw t;await ss()}},async request(t,r={}){let n=await fetch(e+t,Je({...r,signal:r.signal?AbortSignal.any([r.signal,AbortSignal.timeout(Tt)]):AbortSignal.timeout(Tt)}));if(!n.ok)throw new Error("memindex "+t+" returned "+n.status);return n},async post(t,r){return this.request(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}}}function mn(e,t,r){let n=r.platformSource?{platformSource:r.platformSource}:{},o=i=>r.project?.trim()?r.project:as(i.session.header.cwd||"")||"dsh";if(e.on("agent/created",async({agent:i})=>{if(r.injectContext)try{r.startLocalWorker&&await hn().ready();let a=i.session.header.cwd,s=r.project?.trim()?r.project:void 0;if(!a&&!s)return;let l=await t.context({...n,...a?{cwd:a}:{},...s?{projects:s}:{}});l&&i.inject(Rr({source:{kind:"plugin:memindex"},content:[{text:l,type:"text"}]}))}catch{}}),r.ingest){let i=new Set(r.toolFilter.names);e.on("tools/result",async(a,s)=>{if(s.isError||!a.agent||!i.has(a.name))return;let l=s.content.flatMap(c=>c.type==="text"&&typeof c.text=="string"?[c.text]:[]).join(`
66
+ `).trim();if(l)try{await t.save({project:o(a.agent),text:`[${a.name}] ${l}`})}catch{}})}r.summarize&&e.on("agent/turn-stopping",async({agent:i})=>{try{await t.sessionSummarize({...n,project:o(i),contentSessionId:i.session.id})}catch{}})}var b=(e,t)=>t?{type:e,description:t}:{type:e},Pt=e=>({additionalProperties:!1,properties:e,type:"object"}),qt=e=>({items:e,type:"array"}),P=e=>({...e,required:!0}),ls=qt(b("string")),$e={title:P(b("string")),id:P(b("number")),narrative:b("string"),createdAtEpoch:b("number"),project:b("string"),type:b("string")},le={...$e};for(let e of["memorySessionId","subtitle","text","createdAt","contentHash","generatedByModel","mergedIntoProject","agentType","agentId","originDeviceId","originLocalId","syncRev"])le[e]=b("string");for(let e of["promptNumber","discoveryTokens","relevanceCount","syncedAt"])le[e]=b("number");for(let e of["facts","concepts","filesRead","filesModified"])le[e]=ls;le.metadata={additionalProperties:!0,type:"object"};var It=e=>Pt({content:b("string"),items:P(qt(Pt(e)))}),He=b("string","Keep records belonging to this project."),Dt=b("string","Limit recall to a host platform; leave unset for shared memory.");function Mt(e,t){let r=e.items.map(n=>Object.fromEntries(Object.keys(t).filter(o=>n[o]!==void 0).map(o=>[o,structuredClone(n[o])])));return e.content===void 0?{items:r}:{items:r,content:e.content}}function gn(e,t,r){function n(i,a,s,l,c,u){e.tools.register(St({name:i,parameters:s,description:a,execute:c,timeoutMs:r.timeoutMs,isConcurrencySafe:()=>!0,output:{schema:l,render:(h,f)=>[{text:u(f),type:"text"}]}}))}r.search!==!1&&n("mem_search","Find earlier work by topic. Review this compact list before opening individual memories.",{query:P(b("string","Words describing the work or decision to recall.")),project:He,platformSource:Dt,limit:b("integer","Upper bound on returned matches; the worker defaults to 20."),offset:b("integer","Number of matches already read."),type:b("string","Record collection: observations, sessions, or prompts."),obsType:b("string","Observation categories separated by commas."),dateStart:b("string","Earliest included ISO date."),dateEnd:b("string","Latest included ISO date."),orderBy:b("string","Chronological ordering: date_asc or date_desc.")},It($e),async(i,a)=>{let s={...i,query:i.query.trim()};return["date_asc","date_desc"].includes(s.orderBy)||delete s.orderBy,Mt(await t.search(s,a.signal),$e)},Ft),r.timeline!==!1&&n("mem_timeline","Read the neighboring memories around a known record or a matching topic.",{anchor:b("integer","Record identifier at the center of the window."),query:b("string","Topic used to locate the center when its identifier is unknown."),depthBefore:b("integer","Earlier records to include; defaults to 3."),depthAfter:b("integer","Later records to include; defaults to 3."),project:He,platformSource:Dt},It($e),async(i,a)=>Mt(await t.timeline(i,a.signal),$e),Ft),r.getObservations!==!1&&n("mem_get_observations","Open selected memory records with their complete stored details.",{ids:{...P(qt(b("integer"))),description:"Identifiers selected from recall results."},project:He},It(le),async(i,a)=>{if(!i.ids.length)throw new Error("Choose one or more memory identifiers.");return Mt(await t.getObservations(i,a.signal),le)},cs);let o={};for(let i of["title","project","message"])o[i]=P(b("string"));o.id=P(b("number")),o.success=P(b("boolean")),r.save!==!1&&n("mem_save","Keep a note for future sessions. The supplied text is stored directly.",{text:P(b("string","The durable note to record.")),title:b("string","Short heading for this note."),project:He,metadata:{type:"object",additionalProperties:!0,description:"Extra JSON attributes to retain with the note."}},Pt(o),(i,a)=>t.save({...i,text:i.text.trim()},a.signal),i=>`Saved observation #${i.id} (${i.title})`),r.context!==!1&&n("mem_context","Read the startup memory briefing prepared by the worker for the requested projects.",{projects:P(b("string","Comma-separated project ancestry, ending with the active project.")),platformSource:Dt,full:b("boolean","Include the expanded briefing."),colors:b("boolean","Allow ANSI color codes in the briefing.")},b("string"),(i,a)=>{if(!i.projects.trim())throw new Error("Choose a project for the memory briefing.");return t.context(i,a.signal)},i=>i)}function Ft(e){return e.content?e.content:e.items.length?e.items.map(t=>[`#${t.id} ${t.title}${t.type===void 0?"":` [${t.type}]`}${t.project===void 0?"":` (${t.project})`}`,...t.narrative===void 0?[]:[` ${t.narrative}`]].join(`
67
67
  `)).join(`
68
68
  `):"No results found."}function cs(e){return e.content||!e.items.length?Ft(e):e.items.map(t=>{let r=[`#${t.id} ${t.title}`];for(let[n,o]of Object.entries(t))n==="id"||n==="title"||o===void 0||r.push(`${n}: ${typeof o=="object"?JSON.stringify(o):o}`);return r.join(`
69
69
  `)}).join(`
@@ -81,5 +81,5 @@ Search spans host platforms unless platformSource explicitly narrows it. Add a p
81
81
  filter when the question is about one codebase. mem_context provides that project's
82
82
  startup briefing. Use mem_save for a durable fact or decision the user wants retained;
83
83
  do not save guesses as established facts. Cite the records that support your answer.
84
- `};var Ol="memindex",Sl=["tools","skills"],Jt=["read","write","edit","bash"],El=d.object({project:d.string().default(""),platformSource:d.string().default(""),baseUrl:d.string().default(""),timeoutMs:d.number().default(3e4),dedupe:d.boolean().default(!0),injectContext:d.boolean().default(!0),ingest:d.boolean().default(!1),summarize:d.boolean().default(!1),toolFilter:d.object({names:d.array(d.string()).default(Jt)}).default({names:Jt})});function kl(e,t={}){let r=t.timeoutMs??3e4;if(!(Number.isSafeInteger(r)&&r>0))throw new Error("MemIndex timeoutMs must be a positive whole number.");let n=Ue(),i=(t.baseUrl||process.env.DSH_MEM_BASE_URL||n).replace(/\/+$/,""),a=new Be({baseUrl:i,timeoutMs:r,dedupe:t.dedupe??!0});e.skills.register(yn),gn(e,a,{timeoutMs:r}),mn(e,a,{injectContext:t.injectContext??!0,ingest:t.ingest??!1,summarize:t.summarize??!1,project:t.project??"",platformSource:t.platformSource??"",startLocalWorker:i===n.replace(/\/+$/,""),toolFilter:{names:t.toolFilter?.names??[...Jt]}})}export{El as Config,kl as apply,Sl as inject,Ol as name};
84
+ `};var El="memindex",kl=["tools","skills"],Lt=["read","write","edit","bash"],jl=d.object({project:d.string().default(""),platformSource:d.string().default(""),baseUrl:d.string().default(""),timeoutMs:d.number().default(3e4),dedupe:d.boolean().default(!0),injectContext:d.boolean().default(!0),ingest:d.boolean().default(!1),summarize:d.boolean().default(!1),toolFilter:d.object({names:d.array(d.string()).default(Lt)}).default({names:Lt})});function $l(e,t={}){let r=t.timeoutMs??3e4;if(!(Number.isSafeInteger(r)&&r>0))throw new Error("MemIndex timeoutMs must be a positive whole number.");let n=ze(),i=(t.baseUrl||process.env.DSH_MEM_BASE_URL||n).replace(/\/+$/,""),a=new Be({baseUrl:i,timeoutMs:r,dedupe:t.dedupe??!0});e.skills.register(yn),gn(e,a,{timeoutMs:r}),mn(e,a,{injectContext:t.injectContext??!0,ingest:t.ingest??!1,summarize:t.summarize??!1,project:t.project??"",platformSource:t.platformSource??"",startLocalWorker:i===n.replace(/\/+$/,""),toolFilter:{names:t.toolFilter?.names??[...Lt]}})}export{jl as Config,$l as apply,kl as inject,El as name};
85
85
  /*! Vendored DeepSeek public SDK helpers. See integrations/dsh/THIRD-PARTY-LICENSES.txt and vendor/provenance.json. */