memindex 1.4.6 → 1.6.0
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +15 -12
- package/.codex-plugin/plugin.json +17 -14
- package/.qoder-plugin/plugin.json +1 -1
- package/README.md +89 -110
- package/THIRD_PARTY_LICENSES +7 -0
- package/dist/bug-report/index.js +60 -60
- package/dist/npx-cli/index.js +316 -307
- package/dist/opencode-plugin/index.js +43 -43
- package/dist/pi-extension/index.js +6 -6
- package/integrations/dsh/lib/index.js +19 -19
- package/integrations/dsh/package.json +1 -1
- package/integrations/openclaw/install.sh +16 -10
- package/integrations/openclaw/openclaw.plugin.json +1 -1
- package/integrations/openclaw/test-install.sh +20 -13
- package/package.json +15 -12
- package/plugin/.claude-plugin/plugin.json +15 -12
- package/plugin/.codex-plugin/plugin.json +15 -12
- package/plugin/.qoder-plugin/plugin.json +1 -1
- package/plugin/hooks/codex-hooks.json +12 -0
- package/plugin/package.json +1 -1
- package/plugin/plugin.json +1 -1
- package/plugin/scripts/context-generator.cjs +62 -61
- package/plugin/scripts/context-generator.cjs.map +3 -3
- package/plugin/scripts/mcp-server.cjs +74 -73
- package/plugin/scripts/mcp-server.cjs.map +3 -3
- package/plugin/scripts/statusline.cjs +1 -1
- package/plugin/scripts/transcript-watcher.cjs +36 -35
- package/plugin/scripts/transcript-watcher.cjs.map +3 -3
- package/plugin/scripts/worker-service.cjs +638 -599
- package/plugin/scripts/worker-service.cjs.map +3 -3
- package/plugin/skills/cloud-sync/SKILL.md +5 -5
- package/plugin/skills/mode-creator/SKILL.md +7 -1
- package/plugin/skills/timeline-report/SKILL.md +8 -8
- package/plugin/skills/weekly-digests/SKILL.md +5 -5
- package/plugin/skills/worker-request.mjs +45 -0
- package/plugin/sqlite/SessionStore.js +128 -128
- package/plugin/sqlite/SessionStore.js.map +3 -3
- package/plugin/sqlite/observations/files.js +12 -9
- package/plugin/sqlite/observations/files.js.map +3 -3
- package/plugin/ui/assets/fonts/dm-sans-OFL.txt +93 -0
- package/plugin/ui/assets/fonts/dm-sans-latin.woff2 +0 -0
- package/plugin/ui/assets/fonts/ibm-plex-mono-OFL.txt +93 -0
- package/plugin/ui/assets/fonts/ibm-plex-mono-latin.woff2 +0 -0
- package/plugin/ui/assets/fonts/manrope-OFL.txt +93 -0
- package/plugin/ui/assets/fonts/manrope-latin.woff2 +0 -0
- package/plugin/ui/viewer-bundle.js +18 -18
- package/plugin/ui/viewer.html +450 -321
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
import { createRequire as __cmCreateRequire } from "node:module"; const require = __cmCreateRequire(import.meta.url);
|
|
2
|
-
import{createRequire as _n}from"node:module";var Cs=_n(import.meta.url);function E(e){return e==null}function xt(e){return e&&typeof e=="object"&&!Array.isArray(e)}function Rn(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 An(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 L(e,t,r){return Object.defineProperty(e,t,{writable:!0,value:r,enumerable:!1})}var Cn=Symbol.for("cosmokit.volatile.write");function Ce(e){return typeof e=="object"&&e!==null&&Cn in e}function H(e,t){return arguments.length===1?r=>H(e,r):e in globalThis&&t instanceof globalThis[e]||Object.prototype.toString.call(t).slice(8,-1)===e}function qe(e){return H("ArrayBuffer",e)||H("SharedArrayBuffer",e)}function Nn(e){return qe(e)||ArrayBuffer.isView(e)}var D;(function(e){e.is=qe,e.isSource=Nn;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})(D||(D={}));var Ns=D.fromBase64,Is=D.toBase64,Ts=D.fromHex,Ms=D.toHex;function ct(e,t=new Map){if(!e||typeof e!="object")return e;if(H("Date",e))return new Date(e.valueOf());if(H("RegExp",e))return new RegExp(e.source,e.flags);if(qe(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(ct,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(ct,null,[i.value,t])),Reflect.defineProperty(n,o,i)}return n}function ut(e,t,r){let n=new Set;function o(i,a){if(i===a)return!0;if(Ce(i)||Ce(a))return Ce(i)&&Ce(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(H("Date"),(l,c)=>l.valueOf()===c.valueOf())??s(H("URL"),(l,c)=>l.href===c.href)??s(H("RegExp"),(l,c)=>l.source===c.source&&l.flags===c.flags)??s(qe,(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 In(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 Tn(e){return In(e,[45,95],45)}var Mn=Tn,Vt;(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})(Vt||(Vt={}));var Le=Symbol.for("schemastery"),xr=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?.[xr]}};Object.defineProperty(w.prototype,xr,{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[Le]=!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 Dn(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 de(e){return e?.$value??e?.$inner}function Xt(e){return Rn(e??{},t=>!t.startsWith("$"))}d.prototype.i18n=function(e){let t=d(this),r=Dn(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=>de(i)?.[o]??i?.[o])))),t.list&&(t.list=t.list.map((n,o)=>n.i18n(z(e,(i={})=>Array.isArray(de(i))?de(i)[o]:Array.isArray(i)?i[o]:Xt(i))))),t.inner&&(t.inner=t.inner.i18n(z(e,n=>de(n)?de(n):Xt(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=An(e,["source","flags"]);return t.meta={...t.meta,pattern:r},t};d.prototype.simplify=function(e){if(ut(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 ut(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 Sr[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 Or={};d.extend=function(e,t){Or[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=ct(a)}let o=Or[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[Le])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[Le]||(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(D.isSource(t))return D.fromSource(t);throw new w(`expected ArrayBufferSource but got ${t}`,r)},!0),...e?[d.transform(d.string(),(t,r)=>{try{return e==="base64"?D.fromBase64(t):D.fromHex(t)}catch(n){throw new w(n.message,r)}},!0)]:[]])};d.extend("lazy",(e,t,r,n)=>(t.inner[Le]||(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(ut(e,t))return[t];throw new w(`expected ${t} but got ${e}`,r)});function Ot(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 Ot(e.length,t,"string length",r),[e]});function Qe(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 Pn(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(Qe(e,o)-Qe(t,o))%Qe(r,o)===0}d.extend("number",(e,{meta:t},r)=>{if(typeof e!="number")throw new w(`expected number but got ${e}`,r);Ot(e,t,"number",r);let{step:n}=t;if(n&&!Pn(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 We(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 Ot(e.length,r,"array length",n,!E(t.meta.default)),[e.map((o,i)=>We(e,i,t,n))]});d.extend("dict",(e,{inner:t,sKey:r},n,o)=>{if(!xt(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]=We(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)=>We(e,a,i,r));return n?[o]:(o.push(...e.slice(t.length)),[o])});function dt(e,t){for(let r in t)r in e||(e[r]=t[r])}d.extend("object",(e,{dict:t},r,n)=>{if(!xt(e))throw new w(`expected object but got ${e}`,r);let o={};for(let i in t){let a=We(e,i,t[i],r);(!E(a)||i in e)&&(o[i]=a)}return n||dt(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")dt(i??={},s);else if(i!==s)throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n)}}return!o&&xt(e)&&dt(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 Sr={};function k(e,t,r){Sr[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 St=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")},Fn=function*(){}.constructor,Gt=async function*(){}.constructor;function qn(e){return!(!e.prototype||e instanceof Fn||Gt!==Function&&e instanceof Gt)}function Et(e,t){if(e===Object.prototype)return t;let r=Object.create(Et(Object.getPrototypeOf(e),t));for(let n of Reflect.ownKeys(e))Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(e,n));return r}function ne(e){return e&&(typeof e=="object"||typeof e=="function")}function Ln(e,t){let r=e;for(;r;){let n=Reflect.getOwnPropertyDescriptor(r,t);if(n)return n;r=Object.getPrototypeOf(r)}}function Q(e,t){if(!ne(t))return t;if(Object.hasOwn(t,g.shadow))return Object.getPrototypeOf(t);let r=t[g.tracker];return r?kt(e,t,r):t}function Te(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 pt(e,t,r){return Te(e,Object.defineProperty(Object.create(null),t,{value:r,writable:!1}))}function Ze(e,t,r,n){if(!r)return n;let o=Reflect.getOwnPropertyDescriptor(t,r)?.value;return o?pt(n,r,e.extend({[g.shadow]:o})):n}function Wn(e,t,r,n){return new Proxy(t,{apply:(o,i,a)=>(i===r&&(i=n),Q(e,Reflect.apply(o,i,a)))})}function kt(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}`,pt(e,g.receiver,a));let s,l,c=Ln(o,i);c&&"value"in c?l=c.value:(s=Ze(e,o,r.property,a),l=Reflect.get(o,i,s));let u=l?.[g.tracker];return u?kt(e,l,u):!r.noShadow&&typeof l=="function"?(s??=Ze(e,o,r.property,a),Wn(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,pt(e,g.receiver,s));let l=Ze(e,o,r.property,s);return Reflect.set(o,i,a,l)},apply:(o,i,a)=>Er(n,o,i,a)});return n}function Er(e,t,r,n){return t[g.invoke]?t[g.invoke].apply(e,n):Reflect.apply(t,r,n)}function ft(e,t,r){let n=function(...o){return Er(kt(n.ctx,n,r),n,this,o)};return L(n,"name",e),Object.setPrototypeOf(n,t)}function Yt(e,t,r){let n=e.error.stack.split(`
|
|
2
|
+
import{createRequire as $n}from"node:module";var Cs=$n(import.meta.url);function E(e){return e==null}function xt(e){return e&&typeof e=="object"&&!Array.isArray(e)}function Rn(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 An(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 W(e,t,r){return Object.defineProperty(e,t,{writable:!0,value:r,enumerable:!1})}var Cn=Symbol.for("cosmokit.volatile.write");function Ce(e){return typeof e=="object"&&e!==null&&Cn in e}function H(e,t){return arguments.length===1?r=>H(e,r):e in globalThis&&t instanceof globalThis[e]||Object.prototype.toString.call(t).slice(8,-1)===e}function qe(e){return H("ArrayBuffer",e)||H("SharedArrayBuffer",e)}function Nn(e){return qe(e)||ArrayBuffer.isView(e)}var D;(function(e){e.is=qe,e.isSource=Nn;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})(D||(D={}));var Ns=D.fromBase64,Is=D.toBase64,Ts=D.fromHex,Ms=D.toHex;function ct(e,t=new Map){if(!e||typeof e!="object")return e;if(H("Date",e))return new Date(e.valueOf());if(H("RegExp",e))return new RegExp(e.source,e.flags);if(qe(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(ct,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(ct,null,[i.value,t])),Reflect.defineProperty(n,o,i)}return n}function ut(e,t,r){let n=new Set;function o(i,a){if(i===a)return!0;if(Ce(i)||Ce(a))return Ce(i)&&Ce(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(H("Date"),(l,c)=>l.valueOf()===c.valueOf())??s(H("URL"),(l,c)=>l.href===c.href)??s(H("RegExp"),(l,c)=>l.source===c.source&&l.flags===c.flags)??s(qe,(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 In(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 Tn(e){return In(e,[45,95],45)}var Mn=Tn,Vt;(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})(Vt||(Vt={}));var We=Symbol.for("schemastery"),xr=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?.[xr]}};Object.defineProperty(w.prototype,xr,{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[We]=!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 Dn(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 de(e){return e?.$value??e?.$inner}function Xt(e){return Rn(e??{},t=>!t.startsWith("$"))}d.prototype.i18n=function(e){let t=d(this),r=Dn(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=>de(i)?.[o]??i?.[o])))),t.list&&(t.list=t.list.map((n,o)=>n.i18n(z(e,(i={})=>Array.isArray(de(i))?de(i)[o]:Array.isArray(i)?i[o]:Xt(i))))),t.inner&&(t.inner=t.inner.i18n(z(e,n=>de(n)?de(n):Xt(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=An(e,["source","flags"]);return t.meta={...t.meta,pattern:r},t};d.prototype.simplify=function(e){if(ut(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 ut(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 Or[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 Sr={};d.extend=function(e,t){Sr[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=ct(a)}let o=Sr[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[We])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[We]||(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(D.isSource(t))return D.fromSource(t);throw new w(`expected ArrayBufferSource but got ${t}`,r)},!0),...e?[d.transform(d.string(),(t,r)=>{try{return e==="base64"?D.fromBase64(t):D.fromHex(t)}catch(n){throw new w(n.message,r)}},!0)]:[]])};d.extend("lazy",(e,t,r,n)=>(t.inner[We]||(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(ut(e,t))return[t];throw new w(`expected ${t} but got ${e}`,r)});function St(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 St(e.length,t,"string length",r),[e]});function Qe(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 Pn(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(Qe(e,o)-Qe(t,o))%Qe(r,o)===0}d.extend("number",(e,{meta:t},r)=>{if(typeof e!="number")throw new w(`expected number but got ${e}`,r);St(e,t,"number",r);let{step:n}=t;if(n&&!Pn(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 Le(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 St(e.length,r,"array length",n,!E(t.meta.default)),[e.map((o,i)=>Le(e,i,t,n))]});d.extend("dict",(e,{inner:t,sKey:r},n,o)=>{if(!xt(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]=Le(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)=>Le(e,a,i,r));return n?[o]:(o.push(...e.slice(t.length)),[o])});function dt(e,t){for(let r in t)r in e||(e[r]=t[r])}d.extend("object",(e,{dict:t},r,n)=>{if(!xt(e))throw new w(`expected object but got ${e}`,r);let o={};for(let i in t){let a=Le(e,i,t[i],r);(!E(a)||i in e)&&(o[i]=a)}return n||dt(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")dt(i??={},s);else if(i!==s)throw new w(`expected ${r()} but got ${JSON.stringify(e)}`,n)}}return!o&&xt(e)&&dt(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 Or={};function k(e,t,r){Or[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 Ot=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")},Fn=function*(){}.constructor,Gt=async function*(){}.constructor;function qn(e){return!(!e.prototype||e instanceof Fn||Gt!==Function&&e instanceof Gt)}function Et(e,t){if(e===Object.prototype)return t;let r=Object.create(Et(Object.getPrototypeOf(e),t));for(let n of Reflect.ownKeys(e))Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(e,n));return r}function ne(e){return e&&(typeof e=="object"||typeof e=="function")}function Wn(e,t){let r=e;for(;r;){let n=Reflect.getOwnPropertyDescriptor(r,t);if(n)return n;r=Object.getPrototypeOf(r)}}function Q(e,t){if(!ne(t))return t;if(Object.hasOwn(t,g.shadow))return Object.getPrototypeOf(t);let r=t[g.tracker];return r?kt(e,t,r):t}function Te(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 pt(e,t,r){return Te(e,Object.defineProperty(Object.create(null),t,{value:r,writable:!1}))}function Ze(e,t,r,n){if(!r)return n;let o=Reflect.getOwnPropertyDescriptor(t,r)?.value;return o?pt(n,r,e.extend({[g.shadow]:o})):n}function Ln(e,t,r,n){return new Proxy(t,{apply:(o,i,a)=>(i===r&&(i=n),Q(e,Reflect.apply(o,i,a)))})}function kt(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}`,pt(e,g.receiver,a));let s,l,c=Wn(o,i);c&&"value"in c?l=c.value:(s=Ze(e,o,r.property,a),l=Reflect.get(o,i,s));let u=l?.[g.tracker];return u?kt(e,l,u):!r.noShadow&&typeof l=="function"?(s??=Ze(e,o,r.property,a),Ln(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,pt(e,g.receiver,s));let l=Ze(e,o,r.property,s);return Reflect.set(o,i,a,l)},apply:(o,i,a)=>Er(n,o,i,a)});return n}function Er(e,t,r,n){return t[g.invoke]?t[g.invoke].apply(e,n):Reflect.apply(t,r,n)}function ft(e,t,r){let n=function(...o){return Er(kt(n.ctx,n,r),n,this,o)};return W(n,"name",e),Object.setPrototypeOf(n,t)}function Yt(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 Qt(e,t=jt()){let r={offset:1,error:new Error};try{let n=e(r);return ne(n)&&"then"in n?n.then(void 0,o=>Yt(r,o,t)):n}catch(n){Yt(r,n,t)}}function jt(e=0){let t=new Error;return()=>t.stack.split(`
|
|
8
|
-
`).slice(3+e)}function Zt(e){return e!==null&&e!==!1&&e!==void 0}var Jn=class{ctx;_hooks={};constructor(e){this.ctx=e,
|
|
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(Bn(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)}}}},Un=[6,2,3,4,5,1],zn=[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],Hn=class kr{bufferSize=1e3;buffer=[];ctx;_snMessage=0;_snExporter=0;exporters=new Map;constructor(t){let r={property:"ctx",noShadow:!0},n=ft("logger",Et(Object.getPrototypeOf(this),Function.prototype),r);return Object.assign(n,this),n.ctx=t,
|
|
8
|
+
`).slice(3+e)}function Zt(e){return e!==null&&e!==!1&&e!==void 0}var Jn=class{ctx;_hooks={};constructor(e){this.ctx=e,W(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 Ot)[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?.[Z.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(Zt(r))return r}}bail(...e){for(let t of this.dispatch("bail",e)){let r=t(...e);if(Zt(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}},er={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)=>ht.color(t,ht.code(r.name,t.colors),e)};function Bn(e){return e instanceof Error&&Array.isArray(e.errors)}var ht=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?zn:Un:[];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]??er[s];return typeof l=="function"?l(r.shift(),e,t):a});let o=e.formatters?.o??er.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(Bn(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)}}}},Un=[6,2,3,4,5,1],zn=[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],Hn=class kr{bufferSize=1e3;buffer=[];ctx;_snMessage=0;_snExporter=0;exporters=new Map;constructor(t){let r={property:"ctx",noShadow:!0},n=ft("logger",Et(Object.getPrototypeOf(this),Function.prototype),r);return Object.assign(n,this),n.ctx=t,W(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??=Mn(n.name),new ht({name:t,level:r.level,meta:{fiber:new WeakRef(n)}},this)}static{for(let t of["error","info","warn","debug"])kr.prototype[t]=function(...r){return this()[t](...r)}}};function et(e){let t=e.stack.split(`
|
|
10
10
|
`);return t.splice(0,2,`Error: ${e.message}`),e.stack=t.join(`
|
|
11
|
-
`),e}var Kn=["prototype","then"];function tt(e){return typeof e=="symbol"||Kn.includes(e)||parseInt(e).toString()===e||e.startsWith("_")}var tr=class{ctx;static handler={get:(e,t,r)=>{if(tt(t))return Reflect.get(e,t,r);if(Reflect.has(e,t))return Q(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 Q(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?et(o):o}},set:(e,t,r,n)=>{if(tt(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 et(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?et(a):a}},has:(e,t)=>tt(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,
|
|
11
|
+
`),e}var Kn=["prototype","then"];function tt(e){return typeof e=="symbol"||Kn.includes(e)||parseInt(e).toString()===e||e.startsWith("_")}var tr=class{ctx;static handler={get:(e,t,r)=>{if(tt(t))return Reflect.get(e,t,r);if(Reflect.has(e,t))return Q(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 Q(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?et(o):o}},set:(e,t,r,n)=>{if(tt(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 et(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?et(a):a}},has:(e,t)=>tt(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,W(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 Q(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?Te(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?Te(l,u):u;return Reflect.set(u,i,s,h)}})},`ctx.mixin(${JSON.stringify(e)})`)}trace(e){return Q(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)})}},Vn=Symbol.for("ValidationError"),jr=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(jr.prototype,Vn,{value:!0});function Xn(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 jr(r.issues);return r.value}var $r=new WeakMap;function rt(e){let t=e();return $r.get(e)?.()??t}function Gn(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 Me=class _r extends Error{code;constructor(t,r){super(r??_r.Code[t]),this.code=t}};(function(e){e.Code={INACTIVE_EFFECT:"cannot create effect on inactive context"}})(Me||(Me={}));var M="__INACTIVE__",Rr=class{parent;inject;runtime;uid;ctx;config;_config;state=0;dispose;store;inertia;_hooks=Object.create(null);_disposables=new St;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[Z.intercept]=Object.create(e[Z.intercept]);for(let[s,l]of a)E(l)||(this.ctx[Z.intercept][s]=l)}this._runner={epoch:M,getOuterStack:o,execute:function(){if(qn(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,Gn(this.context,this),this.ctx.registry.has(n.callback)&&(s(),n.fibers.length||this.ctx.registry.delete(n.callback)),this._setEpoch(M),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 Me("INACTIVE_EFFECT")}_execute(e){let t=e.epoch;return Qt(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(ne(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 Me("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(()=>rt(O));else{let C=rt(O);ne(C)&&"then"in C&&(v=C)}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:jt()},l,c=!0,u,h,f,p=!1,m,y=()=>!1,j=()=>(f??=new Promise((v,O)=>{u=v,h=O}),f),T=v=>Promise.resolve(v).then(()=>i(),async O=>{throw await i(),O}),R=v=>{let O;try{O=v()}catch(C){throw y(),C}if(ne(O)&&"then"in O){let C=Promise.resolve(O).finally(()=>{y(),m===C&&(m=void 0)});return m=C}return y(),O},V=L(()=>s.epoch?(s.epoch=!1,R(()=>c?T(j()):l?T(l):i())):p?m:void 0,g.effect,a);$r.set(V,()=>m),y=this._disposables.push(V);try{l=this._execute(s)}catch(v){c=!1,p=!0,s.epoch=!1;let O;try{O=R(i)}finally{h?.(v)}throw ne(O)&&"then"in O&&O.catch(C=>this.ctx.logger.error(C)),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 re=()=>{if(s.epoch)return s.epoch=!1,R(i)};return V.then=async(v,O)=>Promise.resolve(l).then(()=>re).then(v,O),V}getEffects(){return[...this._disposables].map(e=>e[g.effect]).filter(Boolean)}_getState(){return this.uid===null?4:this._error?3:this._runner.epoch!==M?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(Q(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=M;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!==M&&t===M?(this.inertia=this._reload(),1):(this.inertia=this._unload(),5)))}_resolveConfig(e){return e=this.context.waterfall(this,"internal/config",e,()=>e),this.runtime?Xn(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=M}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 Qt(async t=>{await Promise.resolve(),t.error=new Error,await rt(e)},this._runner.getOuterStack)}catch(t){this.ctx.logger.error(t)}})),this.store=void 0,this._updateState(()=>{if(this._runner.epoch===M)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(M),this._refresh(),await this.await()}update(e,t=!1){if(this.assertActive(),this._config=e,this.state!==2){this._error=void 0,this._setEpoch(M),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 Yn(e){return e&&typeof e=="object"&&typeof e.apply=="function"}function mt(e,t){return function(r,n){if(n.kind==="class")Object.hasOwn(r,"inject")||(L(r,"inject",Object.create(Object.getPrototypeOf(r).inject??null)),L(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?Te(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})(mt||(mt={}));var Qn=class{ctx;_counter=0;_internal=new Map;constructor(e){this.ctx=e,L(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(Yn(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=jt()){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 St,Config:e.Config},this._internal.set(n,o)}let i=new Rr(this.ctx,t,mt.resolve(e.inject),o,r),a=Object.create(i);return a.then=(s,l)=>i.await().then(s,l),a}},Z=class ye{static effect=g.effect;static filter=g.filter;static isolate=g.isolate;static intercept=g.intercept;static is(t){return!!t?.[ye.is]}static{ye.is[Symbol.toPrimitive]=()=>Symbol.for("cordis.is"),ye.prototype[ye.is]=!0}constructor(){this[g.isolate]=Object.create(null),this[g.intercept]=Object.create(null);let t=new Proxy(this,tr.handler);return this.root=t,this.baseUrl=void 0,this.fiber=new Rr(t,{},Object.create(null),null,()=>[]),this.reflect=new tr(t),this.registry=new Qn(t),this.events=new Jn(t),this.logger=new Hn(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(Q(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})}},Zn=class Ar{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=ft(r,Et(Object.getPrototypeOf(this),Function.prototype),o)),n.ctx=t,n.name=r,L(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[Ar.invoke]?r=ft(this.name,this,this[g.tracker]):r=Object.create(this),Object.assign(r,t)}[g.resolveConfig](t,r){let n=this.ctx[Z.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}},eo=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}},rr=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}},to=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 oo(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)}},ro=Symbol("dsh.scope"),no=new WeakMap,Cr=new WeakMap;function oo(e){let t=[];for(let r=e;r!==void 0;r=Cr.get(r))t.push(r);return t}function De(e){return e[ro]}function pe(e,t){let r=e[Z.filter],n={[Z.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=Cr.get(a))if(a===i)return!0;return!1}};return no.set(n,t),n}var nr=2147483647;function be(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 io(e){return be(structuredClone(e))}function so(e){return io({...e,id:crypto.randomUUID()})}function Nr(e){return so({...e,role:"user"})}var ie=class extends Error{code;constructor(e,t,r){super(e,r),this.code=t,this.name=new.target.name}},ao="EMPTY_RESPONSE",Ds=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"),Ps=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"),Fs=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"),lo=2,co=500,uo=1e4,po=.1,fo=Object.freeze([ao,"RATE_LIMIT","SERVER","TIMEOUT","TRANSPORT"]),Ir=d.object({initialDelayMs:d.number().max(nr).default(co),maxDelayMs:d.number().max(nr).default(uo),jitterRatio:d.number().min(0).max(1).default(po)}),ho=d.object({mode:d.const("normal").required(),maxRetries:d.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(lo),retryableCodes:d.array(d.string()).default([...fo]),backoff:Ir}),mo=d.object({mode:d.const("always").required(),backoff:Ir}),qs=d.union([ho,mo]),{version:Ls}={version:"0.0.1-rc.1"};function we(e,t){let r=JSON.stringify(e)??String(e);throw new Error(`unreachable variant${t?` in ${t}`:""}: ${r}`)}function Tr(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 Mr(e){return Object.getPrototypeOf(e)===null&&Tr(e,"Object")}function go(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Tr(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&Mr(r)}function yo(e){let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Mr(t)}function bo(e){let t=Reflect.ownKeys(e);if(!t.some(r=>typeof r!="string"||!Object.prototype.propertyIsEnumerable.call(e,r)))return t}function Dr(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(!go(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(!yo(s))return;let l=bo(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 K(e){return Dr(e,!0)}function Pr(e){return Dr(e,!1)===!0}var Fr=class extends ie{violations;constructor(e){super(`unsupported JSON schema: ${e.join("; ")}`,"UNSUPPORTED_SCHEMA"),this.name="JsonSchemaError",this.violations=e}},wo=new Set(["type","oneOf","properties","required","additionalProperties","items","enum","const"]),vo=new Set(["description","title","default","examples"]),gt=["object","array","string","number","integer","boolean","null"];function qr(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 Lr(e){return Object.getPrototypeOf(e)===null&&qr(e,"Object")}function Wr(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Lr(t)}catch{return!1}}function xo(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!qr(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&Lr(r)}function Oo(e){try{return Reflect.ownKeys(e).every(t=>typeof t=="string"&&Object.prototype.propertyIsEnumerable.call(e,t))}catch{return!1}}function oe(e){return Wr(e)&&Oo(e)}function ve(e){if(!Array.isArray(e))return!1;try{if(!xo(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 Pe(e){return typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0)}function or(e,t){switch(e){case"string":return typeof t=="string";case"number":return Pe(t);case"integer":return Pe(t)&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;default:return we(e,"JsonSchemaType")}}var ir=["properties","required","additionalProperties","items","enum","const"];function So(e,t,r,n){let o=Object.hasOwn(e,"required"),i=o?e.required:void 0;if(o)if(!ve(i)||i.some(a=>typeof a!="string"))n.push(`${t}.required must be an array of strings`);else{let a=oe(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 Eo(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 ir)Object.hasOwn(i.node,f)&&r.push(`${i.path}.${f} is not supported beside oneOf`);continue}if(i.kind==="object-tail"){So(i.node,i.path,i.properties,r);continue}let{node:a,path:s}=i;if(!oe(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(!wo.has(f)){if(vo.has(f)){try{Pr(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 ir)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}),!ve(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"||!gt.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 ${gt.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(!oe(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=ve(p)&&p.length>0&&p.every(R=>or(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,T=or(h,j);y&&(T?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:we(h,"JsonSchemaType")}}}function Se(e){let t=[];if(Eo(e,"schema",t,new Set),t.length>0)throw new Fr(t)}function nt(e){try{return Pr(e)}catch{return!1}}function $(e){return e===""?"arguments":e}function ot(e,t){return e===""?t:`${e}.${t}`}function it(e){return[`"${$(e)}" must be a lossless JSON value`]}function sr(e,t){for(let r of t)e.push(r)}function ar(e,t,r){return{node:e,value:t,path:r,catches:!1,phase:"start",children:[],childIndex:0,violations:[],tailViolations:[],matches:0}}function fe(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 ko(e,t,r){let n=[ar(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++:sr(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(ar(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}sr(s.violations,s.tailViolations),s.violations.length>0?a(s.violations):s.kind==="object"?a(nt(s.value)?[]:[`"${$(s.path)}" must be a lossless JSON object`]):a(nt(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&&!gt.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(nt(s.value)?[]:it(s.path));continue}switch(l){case"object":{if(!Wr(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 "${ot(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:ot(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(`"${ot(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"?fe(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`]:Pe(s.value)?fe(s.node,s.value,s.path):[`"${$(s.path)}" must be a finite JSON number`]);break;case"integer":a(!Pe(s.value)||!Number.isInteger(s.value)?[`"${$(s.path)}" must be an integer`]:fe(s.node,s.value,s.path));break;case"boolean":a(typeof s.value=="boolean"?fe(s.node,s.value,s.path):[`"${$(s.path)}" must be a boolean`]);break;case"null":a(s.value===null?fe(s.node,s.value,s.path):[`"${$(s.path)}" must be null`]);break;default:a(we(l,"JsonSchemaType"))}}catch(l){let c=n.pop();for(;c!==void 0&&!c.catches;)c=n.pop();if(c===void 0)throw l;i(it(c.path))}}return o??it(r)}function Jr(e,t,r="value"){return ko(e,t,r)}var jo=["description","title","default","examples"];function _(e){throw new Fr([e])}function he(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 me(e,t,r){for(let n of Object.keys(e))r.includes(n)||_(`${t}.${n} is not supported by the value schema DSL`)}function $o(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 _o(e,t){e.kind==="root"?e.holder.value=t:e.target.properties=t.properties}function Br(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"){oe(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"){oe(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=[];_o(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;oe(o)||_(`${i} must be a value schema object`),t.has(o)&&_(`${i} is circular`),t.add(o);let a=[...jo,...n.allowRequired?["required"]:[]],s={};if($o(n.destination,s),r.push({kind:"leave",input:o}),Object.hasOwn(o,"oneOf")){me(o,i,[...a,"oneOf","type"]),Object.hasOwn(o,"type")&&_(`${i} cannot declare both type and oneOf`),ve(o.oneOf)||_(`${i}.oneOf must be an array of at least two value schemas`);let c=[];s.oneOf=c,he(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":me(o,i,[...a,"type"]),he(o,s);break;case"object":me(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",he(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":me(o,i,[...a,"type","items"]),s.type="array",he(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":me(o,i,[...a,"type","enum","const"]),s.type=l,he(o,s),Object.hasOwn(o,"enum")&&(ve(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 Ro(e,t){let r={};return Br({kind:"property-map",input:e,path:t,destination:{kind:"root",holder:r}}),r.value??_(`${t} did not compile`)}function Ao(e,t){let r={};return Br({kind:"value",input:e,path:t,allowRequired:!1,destination:{kind:"root",holder:r}}),r.value??_(`${t} did not compile`)}function Co(e){let t=Ao(e,"schema");return Se(t),t}function Ur(e){let t=Ro(e,"parameters"),r={type:"object",properties:t.properties,...t.required===void 0?{}:{required:t.required}};return Se(r),r}var No=class extends ie{violations;constructor(e){super(`invalid arguments: ${e.join("; ")}`,"INVALID_ARGS"),this.name="ToolArgsError",this.violations=e}};function $t(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=Ur(e.parameters),c=Co(e.output.schema),u=f=>Jr(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 No(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 U="run_code",Fe={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."},st={typescript:Fe,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."}},lr='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 cr(e){let t=e();if(t===void 0)return Fe;let r=st[t.language];if(!Object.hasOwn(st,t.language)||r===void 0){let n=Object.keys(st).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 Io=class extends ie{constructor(e){super(e,"CODE_RUN_FAILED"),this.name="CodeRunFailedError"}};function To(e){let t;try{t=K(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=K(t);if(r===void 0)throw new Error("tool arguments could not be detached for durable logging");return{dispatched:t,logged:r}}var Ne=" ",Mo=10;function Do(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>Mo,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(jr.prototype,Vn,{value:!0});function Xn(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 jr(r.issues);return r.value}var _r=new WeakMap;function rt(e){let t=e();return _r.get(e)?.()??t}function Gn(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 Me=class $r extends Error{code;constructor(t,r){super(r??$r.Code[t]),this.code=t}};(function(e){e.Code={INACTIVE_EFFECT:"cannot create effect on inactive context"}})(Me||(Me={}));var M="__INACTIVE__",Rr=class{parent;inject;runtime;uid;ctx;config;_config;state=0;dispose;store;inertia;_hooks=Object.create(null);_disposables=new Ot;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[Z.intercept]=Object.create(e[Z.intercept]);for(let[s,l]of a)E(l)||(this.ctx[Z.intercept][s]=l)}this._runner={epoch:M,getOuterStack:o,execute:function(){if(qn(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,Gn(this.context,this),this.ctx.registry.has(n.callback)&&(s(),n.fibers.length||this.ctx.registry.delete(n.callback)),this._setEpoch(M),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 Me("INACTIVE_EFFECT")}_execute(e){let t=e.epoch;return Qt(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(ne(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 Me("INACTIVE_EFFECT");let r=[],n=!1,o,i=()=>{if(n)return o;n=!0;let v;for(let S of r.splice(0).reverse())if(v)v=v.then(()=>rt(S));else{let C=rt(S);ne(C)&&"then"in C&&(v=C)}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:jt()},l,c=!0,u,h,f,p=!1,m,y=()=>!1,j=()=>(f??=new Promise((v,S)=>{u=v,h=S}),f),T=v=>Promise.resolve(v).then(()=>i(),async S=>{throw await i(),S}),R=v=>{let S;try{S=v()}catch(C){throw y(),C}if(ne(S)&&"then"in S){let C=Promise.resolve(S).finally(()=>{y(),m===C&&(m=void 0)});return m=C}return y(),S},V=W(()=>s.epoch?(s.epoch=!1,R(()=>c?T(j()):l?T(l):i())):p?m:void 0,g.effect,a);_r.set(V,()=>m),y=this._disposables.push(V);try{l=this._execute(s)}catch(v){c=!1,p=!0,s.epoch=!1;let S;try{S=R(i)}finally{h?.(v)}throw ne(S)&&"then"in S&&S.catch(C=>this.ctx.logger.error(C)),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 re=()=>{if(s.epoch)return s.epoch=!1,R(i)};return V.then=async(v,S)=>Promise.resolve(l).then(()=>re).then(v,S),V}getEffects(){return[...this._disposables].map(e=>e[g.effect]).filter(Boolean)}_getState(){return this.uid===null?4:this._error?3:this._runner.epoch!==M?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(Q(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=M;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!==M&&t===M?(this.inertia=this._reload(),1):(this.inertia=this._unload(),5)))}_resolveConfig(e){return e=this.context.waterfall(this,"internal/config",e,()=>e),this.runtime?Xn(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=M}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 Qt(async t=>{await Promise.resolve(),t.error=new Error,await rt(e)},this._runner.getOuterStack)}catch(t){this.ctx.logger.error(t)}})),this.store=void 0,this._updateState(()=>{if(this._runner.epoch===M)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(M),this._refresh(),await this.await()}update(e,t=!1){if(this.assertActive(),this._config=e,this.state!==2){this._error=void 0,this._setEpoch(M),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 Yn(e){return e&&typeof e=="object"&&typeof e.apply=="function"}function mt(e,t){return function(r,n){if(n.kind==="class")Object.hasOwn(r,"inject")||(W(r,"inject",Object.create(Object.getPrototypeOf(r).inject??null)),W(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?Te(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})(mt||(mt={}));var Qn=class{ctx;_counter=0;_internal=new Map;constructor(e){this.ctx=e,W(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(Yn(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=jt()){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 Ot,Config:e.Config},this._internal.set(n,o)}let i=new Rr(this.ctx,t,mt.resolve(e.inject),o,r),a=Object.create(i);return a.then=(s,l)=>i.await().then(s,l),a}},Z=class ye{static effect=g.effect;static filter=g.filter;static isolate=g.isolate;static intercept=g.intercept;static is(t){return!!t?.[ye.is]}static{ye.is[Symbol.toPrimitive]=()=>Symbol.for("cordis.is"),ye.prototype[ye.is]=!0}constructor(){this[g.isolate]=Object.create(null),this[g.intercept]=Object.create(null);let t=new Proxy(this,tr.handler);return this.root=t,this.baseUrl=void 0,this.fiber=new Rr(t,{},Object.create(null),null,()=>[]),this.reflect=new tr(t),this.registry=new Qn(t),this.events=new Jn(t),this.logger=new Hn(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(Q(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})}},Zn=class Ar{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=ft(r,Et(Object.getPrototypeOf(this),Function.prototype),o)),n.ctx=t,n.name=r,W(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[Ar.invoke]?r=ft(this.name,this,this[g.tracker]):r=Object.create(this),Object.assign(r,t)}[g.resolveConfig](t,r){let n=this.ctx[Z.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}},eo=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}},rr=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}},to=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 oo(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)}},ro=Symbol("dsh.scope"),no=new WeakMap,Cr=new WeakMap;function oo(e){let t=[];for(let r=e;r!==void 0;r=Cr.get(r))t.push(r);return t}function De(e){return e[ro]}function pe(e,t){let r=e[Z.filter],n={[Z.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=Cr.get(a))if(a===i)return!0;return!1}};return no.set(n,t),n}var nr=2147483647;function be(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 io(e){return be(structuredClone(e))}function so(e){return io({...e,id:crypto.randomUUID()})}function Nr(e){return so({...e,role:"user"})}var ie=class extends Error{code;constructor(e,t,r){super(e,r),this.code=t,this.name=new.target.name}},ao="EMPTY_RESPONSE",Ds=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"),Ps=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"),Fs=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"),lo=2,co=500,uo=1e4,po=.1,fo=Object.freeze([ao,"RATE_LIMIT","SERVER","TIMEOUT","TRANSPORT"]),Ir=d.object({initialDelayMs:d.number().max(nr).default(co),maxDelayMs:d.number().max(nr).default(uo),jitterRatio:d.number().min(0).max(1).default(po)}),ho=d.object({mode:d.const("normal").required(),maxRetries:d.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(lo),retryableCodes:d.array(d.string()).default([...fo]),backoff:Ir}),mo=d.object({mode:d.const("always").required(),backoff:Ir}),qs=d.union([ho,mo]),{version:Ws}={version:"0.0.1-rc.1"};function we(e,t){let r=JSON.stringify(e)??String(e);throw new Error(`unreachable variant${t?` in ${t}`:""}: ${r}`)}function Tr(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 Mr(e){return Object.getPrototypeOf(e)===null&&Tr(e,"Object")}function go(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Tr(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&Mr(r)}function yo(e){let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Mr(t)}function bo(e){let t=Reflect.ownKeys(e);if(!t.some(r=>typeof r!="string"||!Object.prototype.propertyIsEnumerable.call(e,r)))return t}function Dr(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(!go(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(!yo(s))return;let l=bo(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 K(e){return Dr(e,!0)}function Pr(e){return Dr(e,!1)===!0}var Fr=class extends ie{violations;constructor(e){super(`unsupported JSON schema: ${e.join("; ")}`,"UNSUPPORTED_SCHEMA"),this.name="JsonSchemaError",this.violations=e}},wo=new Set(["type","oneOf","properties","required","additionalProperties","items","enum","const"]),vo=new Set(["description","title","default","examples"]),gt=["object","array","string","number","integer","boolean","null"];function qr(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 Wr(e){return Object.getPrototypeOf(e)===null&&qr(e,"Object")}function Lr(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Wr(t)}catch{return!1}}function xo(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!qr(t,"Array"))return!1;let r=Object.getPrototypeOf(t);return typeof r=="object"&&r!==null&&Wr(r)}function So(e){try{return Reflect.ownKeys(e).every(t=>typeof t=="string"&&Object.prototype.propertyIsEnumerable.call(e,t))}catch{return!1}}function oe(e){return Lr(e)&&So(e)}function ve(e){if(!Array.isArray(e))return!1;try{if(!xo(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 Pe(e){return typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0)}function or(e,t){switch(e){case"string":return typeof t=="string";case"number":return Pe(t);case"integer":return Pe(t)&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;default:return we(e,"JsonSchemaType")}}var ir=["properties","required","additionalProperties","items","enum","const"];function Oo(e,t,r,n){let o=Object.hasOwn(e,"required"),i=o?e.required:void 0;if(o)if(!ve(i)||i.some(a=>typeof a!="string"))n.push(`${t}.required must be an array of strings`);else{let a=oe(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 Eo(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 ir)Object.hasOwn(i.node,f)&&r.push(`${i.path}.${f} is not supported beside oneOf`);continue}if(i.kind==="object-tail"){Oo(i.node,i.path,i.properties,r);continue}let{node:a,path:s}=i;if(!oe(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(!wo.has(f)){if(vo.has(f)){try{Pr(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 ir)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}),!ve(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"||!gt.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 ${gt.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(!oe(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=ve(p)&&p.length>0&&p.every(R=>or(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,T=or(h,j);y&&(T?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:we(h,"JsonSchemaType")}}}function Oe(e){let t=[];if(Eo(e,"schema",t,new Set),t.length>0)throw new Fr(t)}function nt(e){try{return Pr(e)}catch{return!1}}function _(e){return e===""?"arguments":e}function ot(e,t){return e===""?t:`${e}.${t}`}function it(e){return[`"${_(e)}" must be a lossless JSON value`]}function sr(e,t){for(let r of t)e.push(r)}function ar(e,t,r){return{node:e,value:t,path:r,catches:!1,phase:"start",children:[],childIndex:0,violations:[],tailViolations:[],matches:0}}function fe(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 ko(e,t,r){let n=[ar(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++:sr(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(ar(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}sr(s.violations,s.tailViolations),s.violations.length>0?a(s.violations):s.kind==="object"?a(nt(s.value)?[]:[`"${_(s.path)}" must be a lossless JSON object`]):a(nt(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&&!gt.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(nt(s.value)?[]:it(s.path));continue}switch(l){case"object":{if(!Lr(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 "${ot(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:ot(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(`"${ot(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"?fe(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`]:Pe(s.value)?fe(s.node,s.value,s.path):[`"${_(s.path)}" must be a finite JSON number`]);break;case"integer":a(!Pe(s.value)||!Number.isInteger(s.value)?[`"${_(s.path)}" must be an integer`]:fe(s.node,s.value,s.path));break;case"boolean":a(typeof s.value=="boolean"?fe(s.node,s.value,s.path):[`"${_(s.path)}" must be a boolean`]);break;case"null":a(s.value===null?fe(s.node,s.value,s.path):[`"${_(s.path)}" must be null`]);break;default:a(we(l,"JsonSchemaType"))}}catch(l){let c=n.pop();for(;c!==void 0&&!c.catches;)c=n.pop();if(c===void 0)throw l;i(it(c.path))}}return o??it(r)}function Jr(e,t,r="value"){return ko(e,t,r)}var jo=["description","title","default","examples"];function $(e){throw new Fr([e])}function he(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 me(e,t,r){for(let n of Object.keys(e))r.includes(n)||$(`${t}.${n} is not supported by the value schema DSL`)}function _o(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 $o(e,t){e.kind==="root"?e.holder.value=t:e.target.properties=t.properties}function Br(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"){oe(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"){oe(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=[];$o(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;oe(o)||$(`${i} must be a value schema object`),t.has(o)&&$(`${i} is circular`),t.add(o);let a=[...jo,...n.allowRequired?["required"]:[]],s={};if(_o(n.destination,s),r.push({kind:"leave",input:o}),Object.hasOwn(o,"oneOf")){me(o,i,[...a,"oneOf","type"]),Object.hasOwn(o,"type")&&$(`${i} cannot declare both type and oneOf`),ve(o.oneOf)||$(`${i}.oneOf must be an array of at least two value schemas`);let c=[];s.oneOf=c,he(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":me(o,i,[...a,"type"]),he(o,s);break;case"object":me(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",he(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":me(o,i,[...a,"type","items"]),s.type="array",he(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":me(o,i,[...a,"type","enum","const"]),s.type=l,he(o,s),Object.hasOwn(o,"enum")&&(ve(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 Ro(e,t){let r={};return Br({kind:"property-map",input:e,path:t,destination:{kind:"root",holder:r}}),r.value??$(`${t} did not compile`)}function Ao(e,t){let r={};return Br({kind:"value",input:e,path:t,allowRequired:!1,destination:{kind:"root",holder:r}}),r.value??$(`${t} did not compile`)}function Co(e){let t=Ao(e,"schema");return Oe(t),t}function Ur(e){let t=Ro(e,"parameters"),r={type:"object",properties:t.properties,...t.required===void 0?{}:{required:t.required}};return Oe(r),r}var No=class extends ie{violations;constructor(e){super(`invalid arguments: ${e.join("; ")}`,"INVALID_ARGS"),this.name="ToolArgsError",this.violations=e}};function _t(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=Ur(e.parameters),c=Co(e.output.schema),u=f=>Jr(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 No(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 U="run_code",Fe={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."},st={typescript:Fe,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."}},lr='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 cr(e){let t=e();if(t===void 0)return Fe;let r=st[t.language];if(!Object.hasOwn(st,t.language)||r===void 0){let n=Object.keys(st).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 Io=class extends ie{constructor(e){super(e,"CODE_RUN_FAILED"),this.name="CodeRunFailedError"}};function To(e){let t;try{t=K(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=K(t);if(r===void 0)throw new Error("tool arguments could not be detached for durable logging");return{dispatched:t,logged:r}}var Ne=" ",Mo=10;function Do(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>Mo,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
|
${Ne.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
|
`}${Ne.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
|
${Ne.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
|
-
`}${Ne.repeat(a)}${JSON.stringify(c)}: `})}}return t.join("")}function Po(e){return typeof e=="string"?e:Do(e)}function Fo(e,t){let{requireRuntime:r,peekRuntime:n,maxParallel:o,shapeDispatchLog:i}=t,a
|
|
19
|
+
`}${Ne.repeat(a)}${JSON.stringify(c)}: `})}}return t.join("")}function Po(e){return typeof e=="string"?e:Do(e)}function Fo(e,t){let{requireRuntime:r,peekRuntime:n,maxParallel:o,shapeDispatchLog:i}=t,a=_t({name:U,description:Fe.description,parameters:{code:{type:"string",required:!0,description:Fe.codeDescription},description:{type:"string",required:!0,description:lr}},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?"":Po(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=[],T=!1,R=!1,V=Promise.resolve(),re,v=()=>{let x=re;re=void 0,x?.()},
|
|
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=[],T=!1,R=!1,V=Promise.resolve(),re,v=()=>{let x=re;re=void 0,x?.()},S=()=>(R||(R=!0,V=(async()=>{try{for(;;){let x=new Promise(X=>{re=X}),L=j[0];if(L!==void 0&&L.settled){j.shift(),await L.commit(),L.mode==="exclusive"&&(T=!1);continue}let N=p[0];if(N!==void 0){if(u.signal.aborted){p.shift(),N.abandon();continue}let X=N.classify();if(!T&&(X==="exclusive"?m.size===0:m.size<o)){X==="exclusive"&&(T=!0),N.mode=X,p.shift(),j.push(N),await N.start();let G=N.flight.finally(()=>{m.delete(G),v()});m.add(G);continue}}if(p.length===0&&j.length===0&&m.size===0)return;await x}}finally{R=!1,re=void 0}})()),V),C=async()=>{for(await S();y.size>0;)await Promise.allSettled([...y])},Ut=()=>u.signal.aborted,On=x=>async L=>{if(Ut())throw new Error(`run_code run is over (${String(u.signal.reason)}); ${x} not dispatched`);let N=To(L),X=++f,G=`${String(l.callId)}:code:${X}`,Ht={callId:G,rootCallId:l.rootCallId,name:x,arguments:N.dispatched,...l.agent?{agent:l.agent}:{},parent:l.token,signal:u.signal},Ae=e[Xr],Ye=await new Promise((En,kn)=>{let J,jn=O=>{En(O.isError?{isError:!0,message:O.error.message}:{isError:!1,value:O.value});let B=l.agent;if(B===void 0)return;let Kt=(async()=>{let _n=await i({exec:l,agent:B,subCallId:G,name:x,isError:O.isError,content:O.content});B.session.append("tool/code-dispatch",{rootCallId:l.rootCallId,parentCallId:l.callId,subCallId:G,name:x,arguments:N.logged,isError:O.isError,content:_n})})().finally(()=>{y.delete(Kt)});y.add(Kt)};p.push({flight:Promise.resolve(),settled:!1,classify:()=>e.executionMode(Ht).kind,abandon:()=>{kn(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:G,name:x,arguments:N.logged});let O=await Ae.prepare(Ht);if(O.kind==="dispatch"){this.flight=Ae.dispatch(O.exec).then(B=>{J={kind:B.kind,exec:O.exec,result:B.result},this.settled=!0});return}J={kind:O.kind,exec:O.exec,result:O.result},this.settled=!0},async commit(){if(J===void 0)return;let O=J.kind==="post-result"?await Ae.finalize(J.exec,J.result):Ae.finish(J.exec,J.result);for(let B of O.additionalContexts??[])l.deferContext(B);for(O.concludesTurn&&l.concludeTurn(),jn(O);y.size>o;)await Promise.race(y)}}),v(),S()});if(Ut())throw new Error(`run_code run is over (${String(u.signal.reason)}); ${x} result discarded`);if(Ye.isError)throw new Error(Ye.message);return Ye.value},zt=Object.create(null);for(let x of e.schemas(l.agent))x.name!=="run_code"&&Object.defineProperty(zt,x.name,{enumerable:!0,value:On(x.name)});try{let x;try{x=await c.run({program:s.code,bindings:[{global:"tools",functions:zt,errorClass:{name:"ToolCallError",memberNameProperty:"toolName"}}],signal:u.signal})}finally{u.abort("run_code settled"),await C()}if(x.error){let L=x.logs.length>0?`
|
|
22
22
|
Captured output:
|
|
23
23
|
${x.logs.join(`
|
|
24
|
-
`)}`:"";throw new Io(`code run failed (${x.error.kind}): ${x.error.message}${
|
|
24
|
+
`)}`:"";throw new Io(`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:()=>cr(n).description}),Object.defineProperty(a,"parameters",{enumerable:!0,get:()=>Ur({code:{type:"string",required:!0,description:cr(n).codeDescription},description:{type:"string",required:!0,description:lr}})}),a}var qo=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function yt(e){return qo.test(e)?e:JSON.stringify(e)}function xe(e){return" ".repeat(e)}function zr(e,t){if(typeof e!="string"||e.length===0)return[];let r=e.replace(/\s+/g," ").trim();return[`${xe(t)}/** ${r.replaceAll("*/",String.raw`*\/`)} */`]}function ur(e){return JSON.stringify(e)}function Wo(e,t){let r=t==="integer"?"number":t;return Object.hasOwn(e,"const")?ur(e.const):Object.hasOwn(e,"enum")?e.enum.map(ur).join(" | "):r}function bt(e){return{parts:e,containsUnionOrIntersection:e.some(t=>typeof t=="string"?t.includes("|")||t.includes("&"):t.containsUnionOrIntersection)}}function q(...e){return bt(e)}function Lo(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 dr(e,t){return{node:e,indent:t,phase:"start",children:[],childIndex:0,childDocuments:[],entries:[]}}function Jo(e,t){let r=[dr(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(dr(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(bt(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?q("(",u,")[]"):q(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 zr(m.description,i.indent+1))l.push(`
|
|
25
25
|
`,y);l.push(`
|
|
26
26
|
`,`${xe(i.indent+1)}${yt(p)}${s.has(p)?"":"?"}: `,f,";")}l.push(`
|
|
27
|
-
`,`${xe(i.indent)}}`);let c=bt(l);o(i.node.additionalProperties===!1?c:q(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(q("JsonValue"));continue}switch(a.type){case"string":case"number":case"integer":case"boolean":case"null":o(q(
|
|
27
|
+
`,`${xe(i.indent)}}`);let c=bt(l);o(i.node.additionalProperties===!1?c:q(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(q("JsonValue"));continue}switch(a.type){case"string":case"number":case"integer":case"boolean":case"null":o(q(Wo(a,a.type)));break;case"array":a.items===void 0?o(q("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(q(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(q("unknown"))}}return n??q("unknown")}function pr(e,t=0){try{return Oe(e),Lo(Jo(e,t))}catch{return"unknown"}}var Bo='## 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 Uo(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(...zr(o.description,1)),r.push(`${xe(1)}${yt(o.name)}: ${pr(o.parameters,1)};`),n.push(`${xe(1)}${yt(o.name)}: ${pr(o.output,1)};`);return`${Bo}
|
|
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 zo=new RegExp("^[\\p{XID_Start}_]\\p{XID_Continue}*$","u");function Hr(e){return zo.test(e)&&e.normalize("NFKC")===e}var Kr=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__"]),Ho=["Any","Literal","NotRequired","Protocol","TypedDict"];function I(e){return" ".repeat(e)}var Ko=/[\u0000-\u0008\u000e-\u001f\u007f-\u009f]/g,Vo=/[\ud800-\udfff]/gu;function
|
|
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:hr(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(Ie(l,"str",r));break;case"number":a(Ie(l,"float",r));break;case"integer":a(Ie(l,"int",r));break;case"boolean":a(Ie(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>=Go){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])=>Hr(u)&&!Kr.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=Yo(s.className,r),r.typing.add("TypedDict"),s.entries=c,s.children=c.map(([u,h])=>({schema:h,className:hr(s.allocated??"",wt(u)),listDepth:1}));break}default:r.typing.add("Any"),a("Any")}}return i??"Any"}catch{return r.typing.add("Any"),"Any"}}var Qo='## 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 Zo(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=gr(l.parameters,`${wt(l.name)}Args`,r),u=gr(l.output,`${wt(l.name)}Output`,r);if(Hr(l.name)&&!Kr.has(l.name)&&!l.name.startsWith("_")){let h=Xo(l.description,2);n.push(h.length>0?`${I(1)}async def ${l.name}(self, args: ${c}) -> ${u}:`:`${I(1)}async def ${l.name}(self, args: ${c}) -> ${u}: ...`),n.push(...h),o+=1}else{n.push(`${I(1)}# tools[${JSON.stringify(l.name)}](args: ${c}) -> ${u}`);let h
|
|
43
|
+
\`\`\``}var zo=new RegExp("^[\\p{XID_Start}_]\\p{XID_Continue}*$","u");function Hr(e){return zo.test(e)&&e.normalize("NFKC")===e}var Kr=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__"]),Ho=["Any","Literal","NotRequired","Protocol","TypedDict"];function I(e){return" ".repeat(e)}var Ko=/[\u0000-\u0008\u000e-\u001f\u007f-\u009f]/g,Vo=/[\ud800-\udfff]/gu;function $t(e){let t=e.description;if(typeof t!="string")return;let r=t.replace(/\s+/g," ").replace(Ko,n=>`\\x${n.charCodeAt(0).toString(16).padStart(2,"0")}`).replace(Vo,n=>`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`).trim();return r.length===0?void 0:r}function Xo(e,t){let r=$t({description:e});if(r===void 0)return[];let n=r.replaceAll("\\","\\\\").replaceAll('"','\\"');return[`${I(t)}"""${n}"""`]}function wt(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 fr=120,Go=180;function Vr(e){if(e.length<=fr)return e;let t=e.slice(0,fr);return/[\uD800-\uDBFF]$/.test(t)?t.slice(0,-1):t}function Yo(e,t){let r=Vr(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 hr(e,t){return Vr(`${e}${t}`.normalize("NFKC"))}function mr(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 Ie(e,t,r){return e.const!==void 0?(r.typing.add("Literal"),`Literal[${mr(e.const)}]`):e.enum!==void 0?(r.typing.add("Literal"),`Literal[${e.enum.map(mr).join(", ")}]`):t}function gr(e,t,r){let n=(o,i,a)=>({schema:o,className:i,phase:"start",listDepth:a,children:[],childIndex:0,childTypes:[],entries:[]});try{Oe(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,T]=m,R=$t(T);R!==void 0&&f.push(`${I(1)}# ${R}`),h.has(j)?f.push(`${I(1)}${j}: ${y}`):(r.typing.add("NotRequired"),f.push(`${I(1)}${j}: NotRequired[${y}]`))}c.additionalProperties!==!1&&f.push(`${I(1)}# Additional keys beyond those declared are allowed.`),f.length===1&&f.push(`${I(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:hr(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(Ie(l,"str",r));break;case"number":a(Ie(l,"float",r));break;case"integer":a(Ie(l,"int",r));break;case"boolean":a(Ie(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>=Go){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])=>Hr(u)&&!Kr.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=Yo(s.className,r),r.typing.add("TypedDict"),s.entries=c,s.children=c.map(([u,h])=>({schema:h,className:hr(s.allocated??"",wt(u)),listDepth:1}));break}default:r.typing.add("Any"),a("Any")}}return i??"Any"}catch{return r.typing.add("Any"),"Any"}}var Qo='## 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 Zo(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=gr(l.parameters,`${wt(l.name)}Args`,r),u=gr(l.output,`${wt(l.name)}Output`,r);if(Hr(l.name)&&!Kr.has(l.name)&&!l.name.startsWith("_")){let h=Xo(l.description,2);n.push(h.length>0?`${I(1)}async def ${l.name}(self, args: ${c}) -> ${u}:`:`${I(1)}async def ${l.name}(self, args: ${c}) -> ${u}: ...`),n.push(...h),o+=1}else{n.push(`${I(1)}# tools[${JSON.stringify(l.name)}](args: ${c}) -> ${u}`);let h=$t(l);h!==void 0&&n.push(`${I(1)}# ${h}`)}}let i=(o>0?n:[`${I(1)}pass`,...n]).join(`
|
|
45
45
|
`),a=Ho.filter(l=>r.typing.has(l)),s=r.classes.length>0?`${r.classes.join(`
|
|
46
46
|
|
|
47
47
|
`)}
|
|
@@ -58,17 +58,17 @@ ${s}class Tools(Protocol):
|
|
|
58
58
|
${i}
|
|
59
59
|
|
|
60
60
|
tools: Tools`}
|
|
61
|
-
\`\`\``}var at={typescript:Uo,python:Zo},Xr=Symbol("@deepseek-ai/dsh-tools.scheduler"),ei="ABORTED",ti="ABORTED_BEFORE_DISPATCH",lt=class extends ie{constructor(e){super(`unknown tool "${e}"`,"UNKNOWN_TOOL"),this.name="ToolNotFoundError"}},ee=class extends ie{violations;constructor(e,t){super(`tool "${e}" returned invalid output: ${t.join("; ")}`,"INVALID_TOOL_OUTPUT"),this.name="ToolOutputError",this.violations=t}};function vt(e,t,r){return new ee(e,[`output.${t} failed: ${
|
|
62
|
-
`);return t.length>0?t:"tool result blocked by post-execute policy"}function br(e){let t=K(e);if(t===void 0)throw new TypeError("tool result must be losslessly JSON-serializable");return be(t)}function oi(e){try{return e instanceof ie?{name:e.name,code:e.code}:void 0}catch{return}}var ii=class{tools;restrictions=new rr;guards=new rr;mode;constructor(e){this.tools=new eo(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 si(e){let t=e??10;if(!Number.isInteger(t)||t<1)throw new Error("maxParallelSubCalls must be a positive integer");return t}var Ws=class extends Zn{static inject=["systemPrompt"];static Config=d.object({mode:d.union(["native","code","both"]).default("native"),maxParallelSubCalls:d.natural().min(1).default(10)});[Xr]={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 to(e=>new ii(e),()=>{this.ctx.emit("tools/change")});defaultMode;maxParallelSubCalls;codeTransport;constructor(e,t={}){super(e,"tools"),this.defaultMode=t.mode??"native",this.maxParallelSubCalls=si(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=at[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??=Fo(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===U),knownNames:[U]}:{schemas:n,knownNames:[...t.knownNames,U]}}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(at,t.language)){let r=Object.keys(at).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? }`);Se(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 "${U}" 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 "${U}"; 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(U,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!==U).map(t=>{let r=K(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?K(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(pe(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}: ${Oe(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 we(e,"scheduled tool preparation")}}createExecution(e){let t=[],r=ai(),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=K(e.arguments);if(p===void 0)throw new TypeError("tool execution arguments must be losslessly JSON-serializable");let m={...f,arguments:be(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:Y(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:ge()});try{let o=pe(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:ge()});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:ge()}):await t({kind:"dispatch",exec:n})}catch(o){return t({kind:"final-result",exec:n,result:Y(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?vr(t):ge(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=li(t.callerSignal,r),o=n.signal;if(wr(o))return n.dispose(),ge();e.signal=o;try{let i=this.get(e.name,e.agent);if(!i)throw new lt(e.name);t.bodyInvoked=!0;let a=await i.execute(e.arguments,e),s=this.createSuccessResult(e,i,a);return wr(o)?vr(s):s}catch(i){return Y(i)}finally{n.dispose(),e.signal=r}}async dispatchScheduledExecution(e){try{let t=e,r=pe(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:Y(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,Y(r))}}finishScheduledExecution(e,t){let r;try{r=this.materializeFinalResult(t)}catch(o){r=this.materializeFinalResult(Y(o))}let n;try{n=this.materializeFinalResult(this.applyFinalContent(e,r))}catch(o){n=this.materializeFinalResult(Y(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: ${Oe(a)}`)},i=this.ctx.events.dispatch("emit",[pe(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 we(n,"ApprovalOutcome")}}async postExecute(e,t){let r=await this.ctx.waterfall(pe(this,e.agent),"tools/post-execute",e,t,()=>Promise.resolve({kind:"accept"})),n=r.additionalContexts??[];if(r.kind==="block"){let i=ni(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 lt(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=ri(t.name,r),o=Jr(t.output.schema,n,"value");if(o.length>0)throw new ee(t.name,o);let i=be(n),a;try{a=t.output.render(e.arguments,i)}catch(u){throw vt(t.name,"render",u)}let s=yr(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 vt(t.name,"presentationMeta",h)}l=yr(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 lt(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?br({isError:!0,error:e.error,...t}):be({...br({isError:!1,...t,...e.concludesTurn===!0?{concludesTurn:!0}:{}}),value:e.value})}};function ai(){return Symbol("dsh.tool.execution")}function Y(e){let t=oi(e),r=Oe(e);return{content:[{type:"text",text:`Error: ${r}`}],isError:!0,error:{message:r,...t?{info:t}:{}}}}function wr(e){return e.aborted}function li(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 vr(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:ei}},...t.length>0?{additionalContexts:t}:{}}}function ge(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:ti}},...t.length>0?{additionalContexts:t}:{}}}var A=class extends Error{constructor(r,n,o){super(r,o);this.code=n;this.name="MemError"}code};var Rt=e=>e.toLowerCase().replace(/\s+/gu," ").trim();function ui(e){let t=[e.title,e.subtitle,e.text,e.narrative].map(n=>Rt(n??"")),r=(e.facts??[]).map(Rt);return t.some(Boolean)||r.some(Boolean)?JSON.stringify([...t,r]):""}function Gr(e){let t=new Set;return e.filter(r=>{let n=ui(r);return n?t.has(n)?!1:(t.add(n),!0):!0})}function Yr(e){let t=new Set;return e.split(`
|
|
61
|
+
\`\`\``}var at={typescript:Uo,python:Zo},Xr=Symbol("@deepseek-ai/dsh-tools.scheduler"),ei="ABORTED",ti="ABORTED_BEFORE_DISPATCH",lt=class extends ie{constructor(e){super(`unknown tool "${e}"`,"UNKNOWN_TOOL"),this.name="ToolNotFoundError"}},ee=class extends ie{violations;constructor(e,t){super(`tool "${e}" returned invalid output: ${t.join("; ")}`,"INVALID_TOOL_OUTPUT"),this.name="ToolOutputError",this.violations=t}};function vt(e,t,r){return new ee(e,[`output.${t} failed: ${Se(r)}`])}function yr(e,t,r){try{let n=K(r);if(n===void 0)throw new ee(e,[`output.${t} returned non-lossless JSON`]);return n}catch(n){throw n instanceof ee?n:vt(e,t,n)}}function ri(e,t){try{let r=K(t);if(r===void 0)throw new ee(e,["value is not lossless JSON"]);return r}catch(r){throw r instanceof ee?r:new ee(e,[`value snapshot failed: ${Se(r)}`])}}function Se(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 ni(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 br(e){let t=K(e);if(t===void 0)throw new TypeError("tool result must be losslessly JSON-serializable");return be(t)}function oi(e){try{return e instanceof ie?{name:e.name,code:e.code}:void 0}catch{return}}var ii=class{tools;restrictions=new rr;guards=new rr;mode;constructor(e){this.tools=new eo(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 si(e){let t=e??10;if(!Number.isInteger(t)||t<1)throw new Error("maxParallelSubCalls must be a positive integer");return t}var Ls=class extends Zn{static inject=["systemPrompt"];static Config=d.object({mode:d.union(["native","code","both"]).default("native"),maxParallelSubCalls:d.natural().min(1).default(10)});[Xr]={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 to(e=>new ii(e),()=>{this.ctx.emit("tools/change")});defaultMode;maxParallelSubCalls;codeTransport;constructor(e,t={}){super(e,"tools"),this.defaultMode=t.mode??"native",this.maxParallelSubCalls=si(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=at[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??=Fo(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===U),knownNames:[U]}:{schemas:n,knownNames:[...t.knownNames,U]}}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(at,t.language)){let r=Object.keys(at).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? }`);Oe(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 "${U}" 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 "${U}"; 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(U,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!==U).map(t=>{let r=K(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?K(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(pe(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}: ${Se(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 we(e,"scheduled tool preparation")}}createExecution(e){let t=[],r=ai(),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=K(e.arguments);if(p===void 0)throw new TypeError("tool execution arguments must be losslessly JSON-serializable");let m={...f,arguments:be(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:Y(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:ge()});try{let o=pe(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:ge()});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:ge()}):await t({kind:"dispatch",exec:n})}catch(o){return t({kind:"final-result",exec:n,result:Y(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?vr(t):ge(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=li(t.callerSignal,r),o=n.signal;if(wr(o))return n.dispose(),ge();e.signal=o;try{let i=this.get(e.name,e.agent);if(!i)throw new lt(e.name);t.bodyInvoked=!0;let a=await i.execute(e.arguments,e),s=this.createSuccessResult(e,i,a);return wr(o)?vr(s):s}catch(i){return Y(i)}finally{n.dispose(),e.signal=r}}async dispatchScheduledExecution(e){try{let t=e,r=pe(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:Y(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,Y(r))}}finishScheduledExecution(e,t){let r;try{r=this.materializeFinalResult(t)}catch(o){r=this.materializeFinalResult(Y(o))}let n;try{n=this.materializeFinalResult(this.applyFinalContent(e,r))}catch(o){n=this.materializeFinalResult(Y(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: ${Se(a)}`)},i=this.ctx.events.dispatch("emit",[pe(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 we(n,"ApprovalOutcome")}}async postExecute(e,t){let r=await this.ctx.waterfall(pe(this,e.agent),"tools/post-execute",e,t,()=>Promise.resolve({kind:"accept"})),n=r.additionalContexts??[];if(r.kind==="block"){let i=ni(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 lt(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=ri(t.name,r),o=Jr(t.output.schema,n,"value");if(o.length>0)throw new ee(t.name,o);let i=be(n),a;try{a=t.output.render(e.arguments,i)}catch(u){throw vt(t.name,"render",u)}let s=yr(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 vt(t.name,"presentationMeta",h)}l=yr(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 lt(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?br({isError:!0,error:e.error,...t}):be({...br({isError:!1,...t,...e.concludesTurn===!0?{concludesTurn:!0}:{}}),value:e.value})}};function ai(){return Symbol("dsh.tool.execution")}function Y(e){let t=oi(e),r=Se(e);return{content:[{type:"text",text:`Error: ${r}`}],isError:!0,error:{message:r,...t?{info:t}:{}}}}function wr(e){return e.aborted}function li(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 vr(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:ei}},...t.length>0?{additionalContexts:t}:{}}}function ge(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:ti}},...t.length>0?{additionalContexts:t}:{}}}var A=class extends Error{constructor(r,n,o){super(r,o);this.code=n;this.name="MemError"}code};var Rt=e=>e.toLowerCase().replace(/\s+/gu," ").trim();function ui(e){let t=[e.title,e.subtitle,e.text,e.narrative].map(n=>Rt(n??"")),r=(e.facts??[]).map(Rt);return t.some(Boolean)||r.some(Boolean)?JSON.stringify([...t,r]):""}function Gr(e){let t=new Set;return e.filter(r=>{let n=ui(r);return n?t.has(n)?!1:(t.add(n),!0):!0})}function Yr(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(Rt));return t.has(o)?!1:(t.add(o),!0)}).join(`
|
|
64
|
-
`)}import{createHmac as Ii,randomBytes as It,timingSafeEqual as Ti}from"node:crypto";import{constants as tn,openSync as nn,closeSync as on,readFileSync as Mi,writeFileSync as Di,fstatSync as Pi,fchmodSync as Fi,fsyncSync as qi,linkSync as
|
|
65
|
-
`):void 0;return this.settings.dedupe!==!1&&(c=Gr(c),u!==void 0&&(u=Yr(u))),u===void 0?{items:c}:{items:c,content:u}}async exchange(t,r,n,o=!1){if(r?.aborted)throw new A("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=this.settings.baseUrl.replace(/\/+$/u,"")+t,h=await fetch(u,await ze(u,c,{signal:i.signal}));if(!h.ok){let f=await h.text();throw new A(`Worker HTTP ${h.status}: ${f.substring(0,500)}`,"MEM_PROVIDER_ERROR")}return o?await h.text():await h.json()}catch(c){if(s)throw new A(`Memory operation exceeded ${this.settings.timeoutMs} ms.`,"MEM_TIMEOUT");if(r?.aborted)throw new A("Memory operation cancelled.","MEM_ABORTED");if(c instanceof A)throw c;if(c instanceof le)throw new A(c.message,"MEM_PROVIDER_ERROR",{cause:c});let u=c instanceof Error?c.message:String(c);throw new A(`Unable to read the memory worker: ${u}`,"MEM_PROVIDER_ERROR",{cause:c})}finally{clearTimeout(l),r?.removeEventListener("abort",a)}}};function Dt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function dn(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var os={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"},is={created_at_epoch:"createdAtEpoch",prompt_number:"promptNumber",discovery_tokens:"discoveryTokens",relevance_count:"relevanceCount",synced_at:"syncedAt"},ss={facts:"facts",concepts:"concepts",files_read:"filesRead",files_modified:"filesModified"};function pn(e){let t=Dt(e),r=Number(t.id),n={id:Number.isFinite(r)?r:0,title:typeof t.title=="string"?t.title:""};Object.entries(os).forEach(([i,a])=>{typeof t[i]=="string"&&(n[a]=t[i])}),Object.entries(is).forEach(([i,a])=>{let s=t[i]??t[a];typeof s=="number"&&Number.isFinite(s)&&(n[a]=s)}),Object.entries(ss).forEach(([i,a])=>{let s=dn(t[i]);Array.isArray(s)&&(n[a]=s.filter(l=>typeof l=="string"))});let o=dn(t.metadata);return o&&typeof o=="object"&&!Array.isArray(o)&&(n.metadata=o),n}import{basename as
|
|
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},
|
|
64
|
+
`)}import{createHmac as Ii,randomBytes as It,timingSafeEqual as Ti}from"node:crypto";import{constants as tn,openSync as nn,closeSync as on,readFileSync as Mi,writeFileSync as Di,fstatSync as Pi,fchmodSync as Fi,fsyncSync as qi,linkSync as Wi,unlinkSync as Li,mkdirSync as Ji}from"node:fs";import{join as Tt}from"node:path";import{join as ae,dirname as Si,basename as Oi}from"path";import{homedir as Ei}from"os";import{fileURLToPath as ki}from"url";import{homedir as di}from"os";import{join as pi}from"path";function te(e,t=process.platform,r=di()){return typeof e!="string"||e.length===0?e:e==="~"?r:e.startsWith("~/")||t==="win32"&&e.startsWith("~\\")?pi(r,e.slice(2)):e}import{existsSync as vi}from"fs";import{homedir as xi}from"os";import{join as en}from"path";import{closeSync as ga,existsSync as ya,fsyncSync as ba,lstatSync as wa,mkdirSync as va,openSync as xa,readFileSync as fi,readlinkSync as Sa,realpathSync as Oa,renameSync as Ea,statSync as ka,unlinkSync as ja,writeSync as _a}from"fs";var pa=Promise.resolve();var Ra=process.platform==="win32";function hi(e){return e.replace(/^\uFEFF/,"")}function mi(e){return JSON.parse(hi(e))}function At(e){return mi(fi(e,"utf-8"))}var se="MEMINDEX_",gi="AGENT_MEM_",Ee=[gi];function Je(e){return e.startsWith(se)||Ee.some(t=>e.startsWith(t))}function Ct(e){if(!e.startsWith(se))return[];let t=e.slice(se.length);return Ee.map(r=>r+t)}function yi(e=process.env){for(let t of Ee)for(let r of Object.keys(e)){if(!r.startsWith(t))continue;let n=se+r.slice(t.length);e[n]===void 0&&(e[n]=e[r])}}function Qr(e){let t=null;for(let r of Ee)for(let n of Object.keys(e)){if(!n.startsWith(r))continue;let o=se+n.slice(r.length);(t??e)[o]===void 0&&(t??={...e},t[o]=e[n])}return t??e}yi();var bi=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function wi(e){let t=e.env;return bi(t)&&Object.keys(t).some(Je)?"nested":"flat"}function Zr(e){return wi(e)==="nested"?e.env:e}function ke(e=process.env,t=xi()){if(e.MEMINDEX_DATA_DIR)return te(e.MEMINDEX_DATA_DIR,process.platform,t);let r=en(t,".memindex"),n=en(r,"settings.json");try{if(vi(n)){let o=At(n);if(o===null||typeof o!="object"||Array.isArray(o))return r;let i=Qr(Zr(o));if(typeof i.MEMINDEX_DATA_DIR=="string"&&i.MEMINDEX_DATA_DIR)return te(i.MEMINDEX_DATA_DIR,process.platform,t)}}catch{}return r}function ji(){return typeof __dirname<"u"?__dirname:Si(ki(import.meta.url))}var Ga=ji();function _i(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 P(){return _i(ke())}var Be=P(),$i=ae(Ei(),".claude"),Ri=process.env.CLAUDE_CONFIG_DIR||$i,Ya=ae(Ri,"plugins","marketplaces","memindex");var Qa=ae(Be,"logs"),Za=ae(Be,"settings.json"),Ai="memindex.db";var el=ae(Be,Ai),Ci=ae(Be,"observer-sessions"),tl=Oi(Ci);var Ni=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"&&Ni.has(r.code)||Nt(r.cause,t)?!0:Array.isArray(r.errors)&&r.errors.some(n=>Nt(n,t))}function Ue(e){return Nt(e,new Set)?!0:e instanceof Error&&e.message.includes("ECONNREFUSED")}var rn="X-Memindex-Secret",sn="worker-secret",Bi=/^[a-f0-9]{64}$/,an=/^[a-f0-9]{64}$/,Ui="memindex-worker-identity:",zi="challenge",Hi=1e3;var le=class extends Error{constructor(t){super(t),this.name="WorkerIdentityError"}};function je(e=P()){let t=nn(Tt(e,sn),tn.O_RDONLY|(tn.O_NOFOLLOW??0));try{let r=Pi(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=Mi(t,"utf8");if(!Bi.test(n))throw new Error("Invalid worker secret");return n}finally{on(t)}}function ln(e=P()){Ji(e,{recursive:!0,mode:448});let t=Tt(e,sn);try{return je(e)}catch(o){if(o.code!=="ENOENT")throw o}let r=Tt(e,`.worker-secret-${It(16).toString("hex")}`),n=nn(r,"wx",384);try{Fi(n,384),Di(n,It(32).toString("hex")),qi(n)}finally{on(n)}try{try{Wi(r,t)}catch(o){if(o.code!=="EEXIST")throw o}}finally{Li(r)}return je(e)}function Ki(e,t=P()){let r=(e.method??"GET").toUpperCase(),n=r==="GET"||r==="HEAD",o=new Headers(e.headers);if(n)try{o.set(rn,je(t))}catch{return e}else o.set(rn,ln(t));return{...e,headers:o,redirect:"error"}}function Vi(){return It(32).toString("hex")}function Xi(e){return typeof e=="string"&&an.test(e)}function Gi(e,t){return Ii("sha256",e).update(Ui+t).digest("hex")}function Yi(e,t,r=P()){if(typeof e!="string"||!an.test(e)||!Xi(t))return!1;let n;try{n=je(r)}catch{return!1}let o=Buffer.from(Gi(n,t)),i=Buffer.from(e);return i.length===o.length&&Ti(i,o)}function cn(e){try{return new URL(e).origin}catch{return null}}var un=new Map;function Qi(e,t=P(),r=Date.now()){let n=cn(e);n!==null&&un.set(n,{dataDir:t,at:r})}function Zi(e,t=P(),r=Date.now()){let n=cn(e),o=n===null?void 0:un.get(n);return o!==void 0&&o.dataDir===t&&r-o.at<Hi}function es(e,t){let r=new URL("/api/health",e);return r.searchParams.set(zi,t),r.toString()}async function ts(e,t={}){let r=t.dataDir??P();if(!t.fresh&&Zi(e,r))return!0;let n=Vi(),i=await(t.fetchImpl??((l,c)=>fetch(l,c)))(es(e,n),{method:"GET",redirect:"error",signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(Math.max(1,t.timeoutMs??2e3))]):AbortSignal.timeout(Math.max(1,t.timeoutMs??2e3))}),a=null;try{a=await i.json()}catch{}let s=typeof a=="object"&&a!==null?a.proof:void 0;return Yi(s,n,r)?(Qi(e,r),!0):!1}var rs="The program answering on the MemIndex worker port could not be verified as this install's worker, so MemIndex sent it nothing. If you just updated, run npx memindex restart. If it keeps happening, run npx memindex doctor.";function ns(e){return`MemIndex could not read this install's worker secret in ${e}, so it could not check the program on the worker port and sent it nothing. Run the command as the user who runs MemIndex. If it keeps happening, run npx memindex doctor.`}async function ze(e,t={},r={}){let n=r.dataDir??P(),o=(t.method??"GET").toUpperCase();if(o==="GET"||o==="HEAD")try{je(n)}catch{throw new le(ns(n))}else ln(n);let i;try{i=await ts(new URL(e).origin,{...r,dataDir:n,fresh:!0})}catch(a){if(Ue(a)||r.signal?.aborted)throw a;i=!1}if(!i)throw new le(rs);return{...Ki(t,n),redirect:"error"}}function Mt(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 He=class{constructor(t){this.settings=t}settings;search(t,r){return this.readIndex("/api/search",Mt({...t},{obsType:"obs_type"}),r)}timeline(t,r){let n=Mt({...t},{depthBefore:"depth_before",depthAfter:"depth_after"});return this.readIndex("/api/timeline",n,r)}async getObservations(t,r){if(!t.ids.length)throw new A("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(pn):[]}}async save(t,r){if(!t.text.trim())throw new A("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 A("Choose a project or checkout folder.","MEM_INVALID_REQUEST");let i=Mt({...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=Dt(o),a=Array.isArray(o)?o:Array.isArray(i.items)?i.items:[],l=(Array.isArray(i.content)?i.content:[]).flatMap(h=>{let f=Dt(h);return f.type==="text"&&typeof f.text=="string"?[f.text]:[]}),c=a.map(pn),u=l.length?l.join(`
|
|
65
|
+
`):void 0;return this.settings.dedupe!==!1&&(c=Gr(c),u!==void 0&&(u=Yr(u))),u===void 0?{items:c}:{items:c,content:u}}async exchange(t,r,n,o=!1){if(r?.aborted)throw new A("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=this.settings.baseUrl.replace(/\/+$/u,"")+t,h=await fetch(u,await ze(u,c,{signal:i.signal}));if(!h.ok){let f=await h.text();throw new A(`Worker HTTP ${h.status}: ${f.substring(0,500)}`,"MEM_PROVIDER_ERROR")}return o?await h.text():await h.json()}catch(c){if(s)throw new A(`Memory operation exceeded ${this.settings.timeoutMs} ms.`,"MEM_TIMEOUT");if(r?.aborted)throw new A("Memory operation cancelled.","MEM_ABORTED");if(c instanceof A)throw c;if(c instanceof le)throw new A(c.message,"MEM_PROVIDER_ERROR",{cause:c});let u=c instanceof Error?c.message:String(c);throw new A(`Unable to read the memory worker: ${u}`,"MEM_PROVIDER_ERROR",{cause:c})}finally{clearTimeout(l),r?.removeEventListener("abort",a)}}};function Dt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function dn(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}var os={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"},is={created_at_epoch:"createdAtEpoch",prompt_number:"promptNumber",discovery_tokens:"discoveryTokens",relevance_count:"relevanceCount",synced_at:"syncedAt"},ss={facts:"facts",concepts:"concepts",files_read:"filesRead",files_modified:"filesModified"};function pn(e){let t=Dt(e),r=Number(t.id),n={id:Number.isFinite(r)?r:0,title:typeof t.title=="string"?t.title:""};Object.entries(os).forEach(([i,a])=>{typeof t[i]=="string"&&(n[a]=t[i])}),Object.entries(is).forEach(([i,a])=>{let s=t[i]??t[a];typeof s=="number"&&Number.isFinite(s)&&(n[a]=s)}),Object.entries(ss).forEach(([i,a])=>{let s=dn(t[i]);Array.isArray(s)&&(n[a]=s.filter(l=>typeof l=="string"))});let o=dn(t.metadata);return o&&typeof o=="object"&&!Array.isArray(o)&&(n.metadata=o),n}import{basename as _s}from"node:path";import{existsSync as yn,readFileSync as Es}from"node:fs";import{homedir as bn}from"node:os";import{join as ce}from"node:path";import{spawn as ks}from"node:child_process";import{createHash as mn}from"crypto";import{realpathSync as as}from"fs";import{homedir as Ke,tmpdir as fn}from"os";import{basename as ls,dirname as cs,join as us,resolve as ds,sep as hn,win32 as ps}from"path";var fs=4e4,hs=9e3,ms=["/tmp","/private/tmp","/var/folders","/private/var/folders"];function _e(e){let t=ds(e),r=[],n=t;for(;;)try{return us(as.native(n),...r.reverse())}catch{let o=cs(n);if(o===n)return t;r.push(ls(n)),n=o}}function gs(e,t){let r=_e(t);return e===r||e.startsWith(r.endsWith(hn)?r:r+hn)}function ys(e,t=Ke()){let r=_e(e),n=_e(t);return(process.platform==="win32"?[fn()]:[fn(),...ms]).some(i=>_e(i)!==n&&gs(r,i))}function bs(e=process.env,t=Ke()){return e.MEMINDEX_TEST_FORBIDDEN_DATA_DIR?!0:ys(ke(e,t),t)}var ws=39e3,vs=500;function xs(e){return mn("sha256").update(ps.resolve(e).toLowerCase()).digest().readUInt32BE(0)%vs}function Ss(e=process.platform,t=Ke()){return e==="win32"?ws+xs(t):38700+(process.getuid?.()??77)%100}function Os(e){let t=mn("sha256").update(_e(e)).digest();return fs+t.readUInt32BE(0)%hs}function gn(e=process.env,t=Ke()){return bs(e,t)?Os(ke(e,t)):Ss(process.platform,t)}var Ve=5e3;function Xe(){let e=te(process.env.MEMINDEX_DATA_DIR||process.env.AGENT_MEM_DATA_DIR||ce(bn(),".memindex")),t={};try{let s=JSON.parse(Es(ce(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]||Ct(s).map(c=>process.env[c]).find(Boolean)||r(s)||Ct(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(gn()));return"http://"+(i.includes(":")&&!i.startsWith("[")?"["+i+"]":i)+":"+a}var $e;function js(){if($e)return $e;let e=ce(process.env.CLAUDE_CONFIG_DIR||ce(bn(),".claude"),"plugins","marketplaces","memindex"),t=ce(e,"plugin","scripts","bun-runner.js"),r=ce(e,"plugin","scripts","worker-service.cjs");return!yn(t)||!yn(r)?Promise.reject(new Error("Run npx memindex install to install the worker.")):($e=new Promise((o,i)=>{let a=ks(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(()=>{$e=void 0}),$e)}function wn(){let e=Xe();return{reset(){e=Xe()},async ready(){try{let t=await fetch(e+"/api/health",{signal:AbortSignal.timeout(Ve)});if(t.ok)return;throw new Error("memindex health check returned "+t.status)}catch(t){if(!Ue(t))throw t;await js()}},async request(t,r={}){let n=e+t,o=await ze(n,r,{timeoutMs:Ve,signal:r.signal??void 0}),i=await fetch(n,{...o,signal:r.signal?AbortSignal.any([r.signal,AbortSignal.timeout(Ve)]):AbortSignal.timeout(Ve)});if(!i.ok)throw new Error("memindex "+t+" returned "+i.status);return i},async post(t,r){return this.request(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)})}}}function vn(e,t,r){let n=r.platformSource?{platformSource:r.platformSource}:{},o=i=>r.project?.trim()?r.project:_s(i.session.header.cwd||"")||"dsh";if(e.on("agent/created",async({agent:i})=>{if(r.injectContext)try{r.startLocalWorker&&await wn().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(Nr({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},Wt=e=>({additionalProperties:!1,properties:e,type:"object"}),Jt=e=>({items:e,type:"array"}),F=e=>({...e,required:!0}),$s=Jt(b("string")),Re={title:F(b("string")),id:F(b("number")),narrative:b("string"),createdAtEpoch:b("number"),project:b("string"),type:b("string")},ue={...Re};for(let e of["memorySessionId","subtitle","text","createdAt","contentHash","generatedByModel","mergedIntoProject","agentType","agentId","originDeviceId","originLocalId","syncRev"])ue[e]=b("string");for(let e of["promptNumber","discoveryTokens","relevanceCount","syncedAt"])ue[e]=b("number");for(let e of["facts","concepts","filesRead","filesModified"])ue[e]=$s;ue.metadata={additionalProperties:!0,type:"object"};var Pt=e=>Wt({content:b("string"),items:F(Jt(Wt(e)))}),Ge=b("string","Keep records belonging to this project."),Ft=b("string","Limit recall to a host platform; leave unset for shared memory.");function qt(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 xn(e,t,r){function n(i,a,s,l,c,u){e.tools.register(_t({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:F(b("string","Words describing the work or decision to recall.")),project:Ge,platformSource:Ft,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.")},Pt(Re),async(i,a)=>{let s={...i,query:i.query.trim()};return["date_asc","date_desc"].includes(s.orderBy)||delete s.orderBy,qt(await t.search(s,a.signal),Re)},Lt),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:Ge,platformSource:Ft},Pt(Re),async(i,a)=>qt(await t.timeline(i,a.signal),Re),Lt),r.getObservations!==!1&&n("mem_get_observations","Open selected memory records with their complete stored details.",{ids:{...F(Jt(b("integer"))),description:"Identifiers selected from recall results."},project:Ge},Pt(ue),async(i,a)=>{if(!i.ids.length)throw new Error("Choose one or more memory identifiers.");return qt(await t.getObservations(i,a.signal),ue)},Rs);let o={};for(let i of["title","project","message"])o[i]=F(b("string"));o.id=F(b("number")),o.success=F(b("boolean")),r.save!==!1&&n("mem_save","Keep a note for future sessions. The supplied text is stored directly.",{text:F(b("string","The durable note to record.")),title:b("string","Short heading for this note."),project:Ge,metadata:{type:"object",additionalProperties:!0,description:"Extra JSON attributes to retain with the note."}},Wt(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:F(b("string","Comma-separated project ancestry, ending with the active project.")),platformSource:Ft,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 Lt(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
|
-
`):"No results found."}function Rs(e){return e.content||!e.items.length?
|
|
68
|
+
`):"No results found."}function Rs(e){return e.content||!e.items.length?Lt(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(`
|
|
70
70
|
|
|
71
|
-
`)}var
|
|
71
|
+
`)}var Sn={source:"bundled",name:"mem-search",description:"Recall decisions, fixes, and context recorded during earlier work.",content:`# Recall earlier work
|
|
72
72
|
|
|
73
73
|
When an answer depends on work outside this conversation, look for recorded evidence.
|
|
74
74
|
Start with mem_search and a few distinctive words from the topic. Inspect the returned
|
|
@@ -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 Bl="memindex",Ul=["tools","skills"],Bt=["read","write","edit","bash"],zl=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(Bt)}).default({names:Bt})});function Hl(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=Xe(),i=(t.baseUrl||process.env.DSH_MEM_BASE_URL||n).replace(/\/+$/,""),a=new He({baseUrl:i,timeoutMs:r,dedupe:t.dedupe??!0});e.skills.register(
|
|
84
|
+
`};var Bl="memindex",Ul=["tools","skills"],Bt=["read","write","edit","bash"],zl=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(Bt)}).default({names:Bt})});function Hl(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=Xe(),i=(t.baseUrl||process.env.DSH_MEM_BASE_URL||n).replace(/\/+$/,""),a=new He({baseUrl:i,timeoutMs:r,dedupe:t.dedupe??!0});e.skills.register(Sn),xn(e,a,{timeoutMs:r}),vn(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??[...Bt]}})}export{zl as Config,Hl as apply,Ul as inject,Bl as name};
|
|
85
85
|
/*! Vendored DeepSeek public SDK helpers. See integrations/dsh/THIRD-PARTY-LICENSES.txt and vendor/provenance.json. */
|