dsh-edge 0.33.0 → 0.34.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.
@@ -11,7 +11,7 @@ var _Ot=Object.create;var ZD=Object.defineProperty;var EOt=Object.getOwnProperty
11
11
  `+e.map(t=>t.path?` - ${t.message} (at ${t.path.join(".")})`:` - ${t.message}`).join(`
12
12
  `))}};Object.defineProperty(MPe.prototype,MLt,{value:!0});a(j$,"resolveConfig");NPe=new WeakMap;a(wne,"runDisposable");a(NLt,"emitPluginDisposed");L$=class DPe extends Error{static{a(this,"CordisError")}code;constructor(t,n){super(n??DPe.Code[t]),this.code=t}};(function(e){e.Code={INACTIVE_EFFECT:"cannot create effect on inactive context"}})(L$||(L$={}));Ig="__INACTIVE__",$Pe=class{static{a(this,"Fiber")}parent;inject;runtime;uid;ctx;config;_config;state=0;dispose;store;inertia;_hooks=Object.create(null);_disposables=new Ene;context;_error;_runner;_store=Object.create(null);constructor(e,t,n,r,i){this.parent=e,this.inject=n,this.runtime=r,this._config=t;let s=a(o=>{this._disposables.push(o)},"collect");if(r){this.uid=e.registry.counter,this.ctx=this.context=e.extend({fiber:this});let o=Object.entries(this.inject);if(o.length){this.ctx[Es.intercept]=Object.create(e[Es.intercept]);for(let[l,c]of o)la(c)||(this.ctx[Es.intercept][l]=c)}this._runner={epoch:Ig,getOuterStack:i,execute:a(function(){if(_Lt(r.callback)){let l=new r.callback(this.ctx,this.config);for(let c of l?.[mn.initHooks]??[])c();return l?.[mn.init]?.()}else return r.callback(this.ctx,this.config)},"execute"),collect:s},this.dispose=e.fiber.effect(()=>{let l=r.fibers.push(this);return async()=>{for(this.uid=null,NLt(this.context,this),this.ctx.registry.has(r.callback)&&(l(),r.fibers.length||this.ctx.registry.delete(r.callback)),this._setEpoch(Ig),this.inertia||this._updateState(()=>(this.inertia=this._unload(),5));this.inertia;)await this.inertia}},"ctx.plugin()");try{this.context.emit("internal/plugin",this)}catch(l){throw Promise.resolve(this.dispose()).catch(c=>this.ctx.logger.error(c)),l}if(this.uid!==null&&e.fiber.state!==5){for(let l of Object.keys(this.inject))this._checkImpl(l);this._refresh()}}else this.uid=0,this.ctx=this.context=e,this.state=2,this.store=Object.create(null),this._runner={epoch:"",getOuterStack:i,execute:a(()=>{},"execute"),collect:s},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 L$("INACTIVE_EFFECT")}_execute(e){let t=e.epoch;return $$(n=>{let r=a(s=>{if(typeof s=="function")e.collect(s);else if(!la(s))throw new TypeError("Invalid effect")},"safeCollect"),i=e.execute.call(this);if(typeof i=="function")return e.collect(i);if(!la(i))if(v_(i)){if("then"in i)return i.then(r);if(Symbol.iterator in i){n.error=new Error;let s=i[Symbol.iterator]();for(;;){let o=s.next();if(r(o.value),o.done)return}}else if(Symbol.asyncIterator in i){let s=i[Symbol.asyncIterator]();return(async()=>{for(await Promise.resolve(),n.error=new Error;;){if(e.epoch!==t)return;let o=await s.next();if(r(o.value),o.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 L$("INACTIVE_EFFECT");let n=[],r=!1,i,s=a(()=>{if(r)return i;r=!0;let T;for(let A of n.splice(0).reverse())if(T)T=T.then(()=>wne(A));else{let R=wne(A);v_(R)&&"then"in R&&(T=R)}return i=T},"dispose"),o={label:t,children:[]},l={execute:e,epoch:!0,collect:a(T=>{n.push(T),this._disposables.delete(T),T[mn.effect]&&o.children.push(T[mn.effect])},"collect"),getOuterStack:Ine()},c,u=!0,d,p,h,m=!1,g,y=a(()=>!1,"removeWrapper"),v=a(()=>(h??=new Promise((T,A)=>{d=T,p=A}),h),"waitForSetup"),x=a(T=>Promise.resolve(T).then(()=>s(),async A=>{throw await s(),A}),"disposeAfter"),b=a(T=>{let A;try{A=T()}catch(R){throw y(),R}if(v_(A)&&"then"in A){let R=Promise.resolve(A).finally(()=>{y(),g===R&&(g=void 0)});return g=R}return y(),A},"finalizeDisposal"),_=bh(()=>l.epoch?(l.epoch=!1,b(()=>u?x(v()):c?x(c):s())):m?g:void 0,mn.effect,o);NPe.set(_,()=>g),y=this._disposables.push(_);try{c=this._execute(l)}catch(T){u=!1,m=!0,l.epoch=!1;let A;try{A=b(s)}finally{p?.(T)}throw v_(A)&&"then"in A&&A.catch(R=>this.ctx.logger.error(R)),T}u=!1,h&&Promise.resolve(c).then(d,p),c?.catch(()=>l.epoch?b(s):s()).catch(T=>this.ctx.logger.error(T));let S=a(()=>{if(l.epoch)return l.epoch=!1,b(s)},"disposeAsync");return _.then=async(T,A)=>Promise.resolve(c).then(()=>S).then(T,A),_}getEffects(){return[...this._disposables].map(e=>e[mn.effect]).filter(Boolean)}_getState(){return this.uid===null?4:this._error?3:this._runner.epoch!==Ig?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 n of Reflect.ownKeys(this.ctx.reflect.store)){let r=this.ctx.reflect.store[n];r.fiber===this&&this.ctx.reflect.notify([r.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(Rg(this.ctx,t.value)))return delete this._store[e]}catch(n){return t.fiber.ctx.logger.error(n),delete this._store[e]}this._store[e]=t}_refresh(){let e=!1;e="";for(let t of Object.keys(this.inject)){let n=this._store[t];if(!n){e=Ig;break}e+=":"+n.fiber.uid}this._setEpoch(e)}_setEpoch(e){let t=this._runner.epoch;e!==t&&(this._runner.epoch=e,!this.inertia&&this._updateState(()=>e!==Ig&&t===Ig?(this.inertia=this._reload(),1):(this.inertia=this._unload(),5)))}_resolveConfig(e){return e=this.context.waterfall(this,"internal/config",e,()=>e),this.runtime?j$(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=Ig}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 $$(async t=>{await Promise.resolve(),t.error=new Error,await wne(e)},this._runner.getOuterStack)}catch(t){this.ctx.logger.error(t)}})),this.store=void 0,this._updateState(()=>{if(this._runner.epoch===Ig)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(Ig),this._refresh(),await this.await()}update(e,t=!1){if(this.assertActive(),this._config=e,this.state!==2){this._error=void 0,this._setEpoch(Ig),this._refresh();return}e=this._resolveConfig(e),this.context.waterfall(this,"internal/update",e,t,()=>(this.config=e,this._error=void 0,this.restart()))}};a(DLt,"isApplicable");a(iR,"Inject");(function(e){function t(n,r=Object.create(null)){if(!n)return r;if(Array.isArray(n))for(let i of n)r[i]=null;else if(Reflect.has(n,mn.checkProto)){Object.assign(r,t(Object.getPrototypeOf(n)));for(let i of Object.keys(n))r[i]=n[i]??null}else for(let i of Object.keys(n))r[i]=n[i]??null;return r}a(t,"resolve"),e.resolve=t})(iR||(iR={}));$Lt=class{static{a(this,"RegistryService")}ctx;_counter=0;_internal=new Map;constructor(e){this.ctx=e,bh(this,mn.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(DLt(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),n=t&&this._internal.get(t);if(n){this._internal.delete(t);for(let r of n.fibers)r.dispose();return n}}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,n=Ine()){let r=this.resolve(e);if(!r)throw new Error('invalid plugin, expect function or object with an "apply" method, received '+typeof e);this.ctx.fiber.assertActive();let i=this._internal.get(r);if(!i){let l=e.name;l==="apply"&&(l=void 0),i={name:l,callback:r,fibers:new Ene,Config:e.Config},this._internal.set(r,i)}let s=new $Pe(this.ctx,t,iR.resolve(e.inject),i,n),o=Object.create(s);return o.then=(l,c)=>s.await().then(l,c),o}},Es=class rR{static{a(this,"Context")}static effect=mn.effect;static filter=mn.filter;static isolate=mn.isolate;static intercept=mn.intercept;static is(t){return!!t?.[rR.is]}static{rR.is[Symbol.toPrimitive]=()=>Symbol.for("cordis.is"),rR.prototype[rR.is]=!0}constructor(){this[mn.isolate]=Object.create(null),this[mn.intercept]=Object.create(null);let t=new Proxy(this,CPe.handler);return this.root=t,this.baseUrl=void 0,this.fiber=new $Pe(t,{},Object.create(null),null,()=>[]),this.reflect=new CPe(t),this.registry=new $Lt(t),this.events=new ALt(t),this.logger=new PLt(t),this.fiber._disposables.clear(),t}[Symbol.for("nodejs.util.inspect.custom")](){return`Context <${this.fiber.name}>`}extend(t={}){let n=Reflect.getOwnPropertyDescriptor(this,mn.shadow)?.value,r=Object.create(Rg(this,this));for(let i of Reflect.ownKeys(t))Object.defineProperty(r,i,Reflect.getOwnPropertyDescriptor(t,i));return n?Object.assign(Object.create(r),{[mn.shadow]:n}):r}isolate(t,n){let r=Object.create(this[mn.isolate]);return r[t]=n??Symbol(t),this.extend({[mn.isolate]:r})}intercept(t,n){let r=Object.create(this[mn.intercept]);return r[t]=n,this.extend({[mn.intercept]:r})}},Nt=class LPe{static{a(this,"Service")}ctx;static init=mn.init;static check=mn.check;static config=mn.config;static invoke=mn.invoke;static extend=mn.extend;static tracker=mn.tracker;static resolveConfig=mn.resolveConfig;name;constructor(t,n){this.ctx=t,n??=this.constructor.provide;let r=this,i={associate:n,property:"ctx"};return r[mn.invoke]&&(r=Sne(n,Tne(Object.getPrototypeOf(this),Function.prototype),i)),r.ctx=t,r.name=n,bh(r,mn.tracker,i),r.ctx.reflect.provide(n,r,this[mn.check]),r}[mn.filter](t){return t[mn.isolate][this.name]===this.ctx[mn.isolate][this.name]}[mn.extend](t){let n;return this[LPe.invoke]?n=Sne(this.name,this,this[mn.tracker]):n=Object.create(this),Object.assign(n,t)}[mn.resolveConfig](t,n){let r=this.ctx[Es.intercept],i=[];for(;this.name in r;)Object.hasOwn(r,this.name)&&i.unshift(r[this.name]),r=Object.getPrototypeOf(r);return t&&i.unshift(t),n&&i.push(n),this.Config?.merge?this.Config.merge(...i):Object.assign({},...i)}static[Symbol.hasInstance](t){if(!t)return!1;let n=t.constructor;for(;n;){if(n=n.prototype?.constructor,n===this)return!0;n&&=Object.getPrototypeOf(n)}return!1}}});function yc(e){if(typeof e=="object"&&e!==null&&e.isDSHRemoteError===!0&&typeof e.code=="string")return e}function x_(e){return Rne(e,new Set)}function Rne(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e)&&!Object.is(e,-0);if(typeof e!="object"||t.has(e))return!1;t.add(e);try{if(Array.isArray(e)){if(Object.getPrototypeOf(e)!==Array.prototype||Reflect.ownKeys(e).length!==e.length+1)return!1;for(let r=0;r<e.length;r++)if(!Object.hasOwn(e,r)||!Rne(e[r],t))return!1;return!0}let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return!1;for(let r of Reflect.ownKeys(e))if(typeof r!="string"||Object.getOwnPropertyDescriptor(e,r)?.enumerable!==!0||!Rne(Reflect.get(e,r),t))return!1;return!0}finally{t.delete(e)}}function cw(e){let t=e?.peer.principal;return t?.kind==="owner"?void 0:t}function jLt(e){return e!=="."&&e!==".."&&LLt.test(e)}function FLt(e,t,n={}){F$("service key",t);let r=n.namespace??t;F$("namespace",r);let i=Reflect.get(e,"ctx");return Es.is(i)&&ULt(i),Object.freeze({service:e,serviceKey:t,namespace:r})}function ULt(e){Object.hasOwn(e.root.reflect.props,"invocation")||e.root.accessor("invocation",{get:a(()=>{},"get")})}function Ft(e,t){if(typeof e=="string")return F$("Remote export name",e),jPe({kind:"direct"},{exportName:e});if(typeof e=="object")return jPe({kind:"direct"},WLt(e,qLt,'Remote options require name, mode: "stream", or resources'));if(t===void 0)throw new TypeError("typert-protocol: Remote decorator context is missing");qPe(t,{kind:"direct"})}function WLt(e,t,n){let r=Reflect.ownKeys(e);if(r.length===0||r.some(l=>typeof l!="string"||!t.has(l))||Object.hasOwn(e,"mode")&&e.mode!=="stream")throw new TypeError(`typert-protocol: ${n}`);let{mode:i,name:s,resources:o}=e;return s!==void 0&&F$("Remote export name",s),{...i===void 0?{}:{mode:i},...s===void 0?{}:{exportName:s},...o===void 0?{}:{resources:BLt(o)}}}function BLt(e){let t={};for(let[n,r]of Object.entries(e)){if(typeof r!="function")throw new TypeError(`typert-protocol: Remote resource reader "${n}" must be a function`);t[n]=r}if(Object.keys(t).length===0)throw new TypeError("typert-protocol: Remote resources require at least one reader");return Object.freeze(t)}function jPe(e,t={}){return function(n,r){qPe(r,e,t)}}function U$(e){let t=Object.getPrototypeOf(e);return t===null?[]:(UPe(t)?.methods??[]).map(n=>({...n}))}function UPe(e){let t=Object.getOwnPropertyDescriptor(e,FPe);if(t===void 0)return;let n=t.value;if(n===null||typeof n!="object")throw new TypeError("typert-protocol: Remote method descriptor must be an object");let r=Reflect.get(n,"version");if(r!==1)throw new TypeError(`typert-protocol: unsupported Remote method descriptor version ${String(r)}`);let i=Reflect.get(n,"methods");if(!Array.isArray(i))throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");return n}function qPe(e,t,n={}){if(e.private||e.static||typeof e.name!="string")throw new TypeError("typert-protocol: Remote decorators require a public instance method with a string name");let r=e.name;e.addInitializer(function(){let i=Object.getPrototypeOf(this);if(i===null)throw new TypeError(`typert-protocol: cannot mark Remote method "${r}" on an object without a prototype`);zLt(i,r,t,n)})}function zLt(e,t,n,{mode:r,exportName:i,resources:s}){let o=UPe(e),l=Object.freeze({method:t,...i===void 0||i===t?{}:{exportName:i},...r===void 0?{}:{mode:r},invocation:Object.freeze(n),...s===void 0?{}:{resources:s}}),c=o?.methods.find(u=>u.method===t);if(c!==void 0){if(c.exportName===l.exportName&&c.mode===l.mode&&c.resources===l.resources&&HLt(c.invocation,n))return;throw new Error(`typert-protocol: Remote method "${t}" has conflicting invocation markers`)}Object.defineProperty(e,FPe,{configurable:!0,value:Object.freeze({version:1,methods:Object.freeze([...o?.methods??[],l])})})}function HLt(e,t){return e.kind==="direct"?t.kind==="direct":t.kind==="direct"?!1:e.context===t.context}function F$(e,t){if(!jLt(t))throw new TypeError(`typert-protocol: ${e} must contain only RPC endpoint segment characters`)}var qe,LLt,FPe,fi,qLt,Ua=F(()=>{mr();qe=class extends Error{static{a(this,"RemoteError")}code;details;isDSHRemoteError=!0;constructor(e,t,n,r){super(t,r),this.code=e,this.details=n,this.name="RemoteError"}};a(yc,"remoteErrorOf");a(x_,"isRemoteJsonValue");a(Rne,"visitJsonValue");a(cw,"principalOf");LLt=/^[A-Za-z0-9_$.-]+$/;a(jLt,"isTypertRemoteSegment");FPe="@deepseek-ai/dsh-typert-protocol/remote-methods";a(FLt,"bindTypertRemote");fi=class extends Nt{static{a(this,"TypertRemoteService")}typertRemote;constructor(e,t,n={}){super(e,t),this.typertRemote=FLt(this,this.name,n)}};a(ULt,"provideInvocationAccessor");a(Ft,"Remote");qLt=new Set(["name","mode","resources"]);a(WLt,"markerOptions");a(BLt,"resourceReaders");a(jPe,"remoteDecorator");a(U$,"remoteMethods");a(UPe,"readRemoteMethodDescriptor");a(qPe,"addMarkerInitializer");a(zLt,"mark");a(HLt,"sameInvocation");a(F$,"validateName")});function Iv(e){return e===" "||e===`
13
13
  `||e==="\r"||e===" "}function VLt(e){return e>="0"&&e<="9"||e>="a"&&e<="f"||e>="A"&&e<="F"}function Ar(e,t){let n=JSON.stringify(e)??String(e);throw new Error(`unreachable variant${t?` in ${t}`:""}: ${n}`)}function BPe(e,t){let n=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(typeof n!="function")return!1;try{return n.name===t&&n.prototype===e&&Function.prototype.toString.call(n)===Function.prototype.toString.call(t==="Array"?Array:Object)}catch{return!1}}function zPe(e){return Object.getPrototypeOf(e)===null&&BPe(e,"Object")}function KLt(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!BPe(t,"Array"))return!1;let n=Object.getPrototypeOf(t);return typeof n=="object"&&n!==null&&zPe(n)}function QLt(e){let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&zPe(t)}function JLt(e){let t=Reflect.ownKeys(e);if(!t.some(n=>typeof n!="string"||!Object.prototype.propertyIsEnumerable.call(e,n)))return t}function HPe(e,t){let n=new Set,r,i=a((o,l)=>{o!==void 0&&(o.kind==="root"?r=l:o.kind==="array"?o.target[o.index]=l:Object.defineProperty(o.target,o.key,{value:l,enumerable:!0,configurable:!0,writable:!0}))},"assign"),s=[{kind:"visit",value:e,...t?{destination:{kind:"root"}}:{}}];for(let o=s.pop();o!==void 0;o=s.pop()){if(o.kind==="leave"){n.delete(o.source);continue}if(o.kind==="array-item"){if(!Object.prototype.hasOwnProperty.call(o.source,o.index))return;s.push({kind:"visit",value:o.source[o.index],...o.target===void 0?{}:{destination:{kind:"array",target:o.target,index:o.index}}});continue}if(o.kind==="object-property"){s.push({kind:"visit",value:o.source[o.key],...o.target===void 0?{}:{destination:{kind:"object",target:o.target,key:o.key}}});continue}let l=o.value;if(l===null){i(o.destination,null);continue}if(typeof l=="boolean"||typeof l=="string"){i(o.destination,l);continue}if(typeof l=="number"){if(!Number.isFinite(l)||Object.is(l,-0))return;i(o.destination,l);continue}if(typeof l!="object"||n.has(l))return;if(Array.isArray(l)){if(!KLt(l))return;let d=l.length;if(Reflect.ownKeys(l).length!==d+1)return;let p=t?[]:void 0;p!==void 0&&i(o.destination,p),n.add(l),s.push({kind:"leave",source:l});for(let h=d-1;h>=0;h--)s.push({kind:"array-item",source:l,index:h,...p===void 0?{}:{target:p}});continue}if(!QLt(l))return;let c=JLt(l);if(c===void 0)return;let u=t?{}:void 0;u!==void 0&&i(o.destination,u),n.add(l),s.push({kind:"leave",source:l});for(let d=c.length-1;d>=0;d--){let p=c[d];if(p===void 0)return;s.push({kind:"object-property",source:l,key:p,...u===void 0?{}:{target:u}})}}return t?r:!0}function js(e){return HPe(e,!0)}function b1(e){return HPe(e,!1)===!0}function Al(e,t){if(e===t)return!0;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,o)=>Al(s,t[o]));let n=e,r=t,i=Object.keys(n);return i.length!==Object.keys(r).length?!1:i.every(s=>s in r&&Al(n[s],r[s]))}function Ln(e){let t=new WeakSet,n=[{kind:"visit",node:e}];for(;n.length>0;){let r=n.pop();if(r===void 0)continue;if(r.kind==="property"){n.push({kind:"visit",node:r.source[r.key]});continue}let i=r.node;if(i===null||typeof i!="object"||i instanceof AbortSignal||t.has(i))continue;t.add(i),Object.freeze(i);let s=Object.keys(i);for(let o=s.length-1;o>=0;o--){let l=s[o];l!==void 0&&n.push({kind:"property",source:i,key:l})}}return e}var GLt,WPe,j6r,ps=F(()=>{GLt={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
14
- `,r:"\r",t:" "},WPe=/[\\\u0000-\u001f]/u;a(Iv,"isWhitespace");a(VLt,"isHex");j6r=class b_{static{a(this,"PartialArguments")}static EMPTY=b_.fromObject({});static fromText(t){let n=new b_;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new b_;return n.object=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},n.sealed=!0,n}chunks=[];object;sealed=!1;#e=[];#n=0;#r=0;#t="root";#i=!1;#s=0;#o=!1;#u="";#l=null;#a=[];#p=!1;#m;#h=!1;#c=new Map;#f=[];#d=new Map;get isSealed(){return this.sealed}get invalid(){return this.scan(),this.#t==="invalid"||this.#h}append(t){if(this.sealed)throw new Error("PartialArguments: cannot append to a sealed view");t.length!==0&&(this.chunks.push(t),this.#n+=t.length,this.#e.push(this.#n))}settle(t){if(this.object!==void 0||t.length!==this.#n)return b_.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return b_.fromText(t);n+=r.length}return this.chunks=t.length===0?[]:[t],this.#e=t.length===0?[]:[t.length],this.sealed=!0,this}refresh(){if(this.#d.size===0)return!1;this.scan();let t=!1,n=!1;for(let r of this.#d.values()){if(r.completion){n=!0;continue}t=this.refreshRead(r)||t}if(n)for(let r of this.#d.values())r.completion&&(t=this.refreshRead(r)||t);return this.sealed&&this.#d.clear(),t}refreshRead(t){let n=t.answer();return Object.is(n,t.last)?!1:(t.last=n,!0)}closed(){return this.remember("closed","",()=>this.closedNow())}keys(){return this.remember("keys","",()=>this.keysNow(),t=>t.length)}has(t){return this.remember("has",t,()=>this.hasNow(t))}complete(t){return this.remember("complete",t,()=>this.completeNow(t))}stringLength(t,n){let r=Math.max(1,Math.floor(n?.step??1)),i=n?.offset??0;return this.remember(`length:${r}:${i}`,t,()=>this.lengthNow(t),s=>s===void 0?void 0:Math.ceil((s+i)/r))}stringExceeds(t,n){let r=Math.max(0,Math.floor(n));return this.remember(`exceeds:${r}`,t,()=>(this.lengthNow(t,r+1)??0)>r)}text(t){return this.remember("text",t,()=>this.textNow(t))}textPrefix(t,n){let r=Math.max(1,Math.floor(n));return this.remember(`prefix:${r}`,t,()=>this.textPrefixNow(t,r))}value(t){return this.remember("value",t,()=>this.valueNow(t))}remember(t,n,r,i){this.scan();let s=r();if(!this.sealed){let o=`${t}/${n}`;this.#d.has(o)||this.#d.set(o,{completion:t==="complete",answer:i===void 0?r:()=>i(r()),last:i===void 0?s:i(s)})}return s}closedNow(){return this.sealed||this.#t==="closed"||this.#t==="invalid"}keysNow(){return this.object===void 0?this.#f:Object.keys(this.object)}hasNow(t){return this.object===void 0?this.#c.has(t):Object.hasOwn(this.object,t)}completeNow(t){if(this.object!==void 0)return Object.hasOwn(this.object,t);let n=this.#c.get(t);return n!==void 0&&n.end>=0&&(n.kind==="string"?n.invalidAt===void 0:!n.invalid)}lengthNow(t,n=Number.POSITIVE_INFINITY){if(this.object!==void 0){let s=Object.hasOwn(this.object,t)?this.object[t]:void 0;return typeof s=="string"?s.length:void 0}let r=this.#c.get(t);if(r?.kind!=="string")return;if(r.text!==void 0&&r.text.at===r.end)return r.text.length;let i=r.length??={at:r.start,length:0,text:""};return this.readString(r,i,n,!1),i.length}textNow(t){if(this.object!==void 0){let i=Object.hasOwn(this.object,t)?this.object[t]:void 0;return typeof i=="string"?i:void 0}let n=this.#c.get(t);if(n?.kind!=="string")return;if(n.text===void 0&&n.end>=0&&n.needsDecoding&&n.invalidAt===void 0){let i;try{i=JSON.parse(`"${this.slice(n.start,n.end)}"`)}catch{}i!==void 0&&(n.text={at:n.end,length:i.length,text:i})}let r=n.text??={at:n.start,length:0,text:""};return this.readString(n,r,Number.POSITIVE_INFINITY,!0),r.text}textPrefixNow(t,n){if(this.object!==void 0){let o=Object.hasOwn(this.object,t)?this.object[t]:void 0;return typeof o=="string"?o.slice(0,n):void 0}let r=this.#c.get(t);if(r?.kind!=="string")return;let i=r.prefixes??=new Map,s=i.get(n);return s===void 0&&(s={at:r.start,length:0,text:""},i.set(n,s)),this.readString(r,s,n,!0),s.text}valueNow(t){if(this.object!==void 0){if(!Object.hasOwn(this.object,t))return;let r=this.object[t];return typeof r=="string"?void 0:r}let n=this.#c.get(t);if(!(n?.kind!=="value"||n.end<0||n.invalid)){if(n.parsed===void 0)try{n.parsed=JSON.parse(this.slice(n.start,n.end))}catch{n.invalid=!0,this.#h=!0}return n.parsed}}chunkAt(t){let n=0,r=this.#e.length;for(;n<r;){let i=n+r>>>1;this.#e[i]<=t?n=i+1:r=i}return n}slice(t,n){if(t>=n)return"";let r=this.chunkAt(t),i=this.chunkAt(n-1),s=r===0?0:this.#e[r-1];if(r===i)return this.chunks[r].slice(t-s,n-s);let o=[this.chunks[r].slice(t-s)];for(let l=r+1;l<i;l++)o.push(this.chunks[l]);return o.push(this.chunks[i].slice(0,n-this.#e[i-1])),o.join("")}readString(t,n,r,i){let s=Math.min(t.end<0?this.#r:t.end,t.invalidAt??Number.POSITIVE_INFINITY,this.#m??Number.POSITIVE_INFINITY);if(!t.needsDecoding){let l=Math.min(s-n.at,r-n.length);if(l<=0)return;i&&(n.text+=this.slice(n.at,n.at+l)),n.at+=l,n.length+=l;return}let o=this.chunkAt(n.at);for(;n.at<s&&n.length<r;){let l=o===0?0:this.#e[o-1],c=this.chunks[o],u=c.slice(n.at-l,Math.min(c.length,s-l)),d=u.search(WPe),p=Math.min(d<0?u.length:d,r-n.length);if(p>0){i&&(n.text+=u.slice(0,p)),n.at+=p,n.length+=p,n.at===l+c.length&&o++;continue}let h=u.length>1?u[1]:n.at+1<s?this.chunks[o+1][0]:void 0,m,g=2;if(u[0]==="\\"&&h===void 0&&t.end<0)return;if(u[0]==="\\"&&h==="u"){let y=this.slice(n.at+2,Math.min(s,n.at+6)),v=!0;for(let x=0;x<y.length;x++)VLt(y[x])||(v=!1);if(v){if(y.length<4&&t.end<0)return;y.length===4&&(m=String.fromCharCode(Number.parseInt(y,16)))}g=6}else u[0]==="\\"&&h!==void 0&&(m=GLt[h]);if(m===void 0){t.invalidAt=n.at,this.#h=!0;return}for(i&&(n.text+=m),n.length++,n.at+=g;o<this.chunks.length&&n.at>=this.#e[o];)o++}}scan(){if(!(this.object!==void 0||this.#r===this.#n))for(let t=this.chunkAt(this.#r);t<this.chunks.length&&this.#m===void 0;t++){let n=this.chunks[t],r=t===0?0:this.#e[t-1];for(let i=this.#r-r;i<n.length&&this.#t!=="invalid";i++){if(this.#t==="string"||this.#t==="nested"&&this.#p){let s=this.stringBoundary(n,i);if(this.#r+=s-i,i=s,i===n.length)break}this.step(n[i],this.#r),this.#r++}}}stringBoundary(t,n){let r=n;for(;;){let i=t.indexOf('"',r),s=i<0?t.length:i;if(this.#t==="string"){let c=this.#l;!c.needsDecoding&&WPe.test(t.slice(r,s))&&(c.needsDecoding=!0)}let o=s;for(;o>r&&t[o-1]==="\\";)o--;let l=(s-o)%2===1!==(o===r&&this.#i);if(this.#i=i<0&&l,i<0||!l)return s;r=i+1}}step(t,n){switch(this.#t){case"root":if(Iv(t))return;if(t==="{"){this.#t="key-or-end";return}this.fail();return;case"key-or-end":if(Iv(t))return;if(t==="}"){this.#t="closed";return}if(t==='"'){this.beginKey(n);return}this.fail();return;case"key-only":if(Iv(t))return;if(t==='"'){this.beginKey(n);return}this.fail();return;case"key":this.stepKey(t,n);return;case"colon":if(Iv(t))return;if(t===":"){this.#t="value";return}this.fail();return;case"value":this.beginValue(t,n);return;case"string":{let r=this.#l;r.end=n,this.#l=null,this.#t="comma-or-end";return}case"scalar":this.stepScalar(t,n);return;case"nested":this.stepNested(t,n);return;case"comma-or-end":if(Iv(t))return;if(t===","){this.#t="key-only";return}if(t==="}"){this.#t="closed";return}this.fail();return;case"closed":if(Iv(t))return;this.fail();return;case"invalid":return;default:Ar(this.#t)}}fail(){this.#m=this.#r,this.#t="invalid",this.#l=null}beginKey(t){this.#t="key",this.#s=t+1,this.#o=!1,this.#i=!1}stepKey(t,n){if(t<" "){this.fail();return}if(this.#i){this.#i=!1;return}if(t==="\\"){this.#i=!0,this.#o=!0;return}if(t!=='"')return;let r=this.slice(this.#s,n);if(this.#o)try{this.#u=JSON.parse(`"${r}"`)}catch{this.fail();return}else this.#u=r;this.#t="colon"}open(t){this.#c.has(this.#u)||this.#f.push(this.#u),this.#c.set(this.#u,t),this.#l=t}beginValue(t,n){if(!Iv(t)){if(t==='"'){this.open({kind:"string",start:n+1,end:-1,needsDecoding:!1,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0}),this.#i=!1,this.#t="string";return}if(t==="}"||t===","||t===":"||t==="]"){this.fail();return}if(this.open({kind:"value",start:n,end:-1,parsed:void 0,invalid:!1}),t==="{"||t==="["){this.#t="nested",this.#a=[t==="{"?"}":"]"],this.#p=!1,this.#i=!1;return}this.#t="scalar"}}stepScalar(t,n){t!==","&&t!=="}"&&!Iv(t)||(this.closeValue(n),this.#t=t===","?"key-only":t==="}"?"closed":"comma-or-end")}stepNested(t,n){if(this.#p){this.#p=!1;return}if(t==='"'){this.#p=!0;return}if(t==="{"||t==="["){this.#a.push(t==="{"?"}":"]");return}if(t==="}"||t==="]"){if(this.#a.pop()!==t){this.fail();return}this.#a.length===0&&(this.closeValue(n+1),this.#t="comma-or-end")}}closeValue(t){let n=this.#l;n.end=t,this.#l=null}};a(Ar,"assertNever");a(BPe,"hasIntrinsicConstructor");a(zPe,"isIntrinsicObjectPrototype");a(KLt,"hasPlainArrayPrototype");a(QLt,"hasPlainObjectPrototype");a(JLt,"enumerableStringKeys");a(HPe,"walkJsonValue");a(js,"snapshotJsonValue");a(b1,"isJsonValue");a(Al,"deepEqualJson");a(Ln,"deepFreeze")});function q$(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16)),t=Array.from(e,(n,r)=>(r===6?n&15|64:r===8?n&63|128:n).toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Cne=F(()=>{a(q$,"randomUUID")});var ol=F(()=>{});function XLt(e,t){let n=typeof e=="string"?{"":e}:{...e};for(let r in t){let i=t[r];i?.$description||i?.$desc?n[r]=i.$description||i.$desc:typeof i=="string"&&(n[r]=i)}return n}function sR(e){return e?.$value??e?.$inner}function GPe(e){return SPe(e??{},t=>!t.startsWith("$"))}function w_(e,t=[],n=!1,r=new Map){let i=r.get(e)??new Set;if(i.has(n))return;if(i.add(n),r.set(e,i),e.meta?.volatile&&n)throw new hs("volatile fields require a fixed object path without an enclosing volatile field",{path:t});let s=n||!!e.meta?.volatile;if(e.dict)for(let[o,l]of Object.entries(e.dict))w_(l,[...t,o],s,r);if(e.sKey&&w_(e.sKey,[...t,"<key>"],!0,r),e.inner&&(e.type!=="lazy"||e.inner[oR])&&w_(e.inner,[...t,"*"],!0,r),e.list)for(let o=0;o<e.list.length;o++)w_(e.list[o],[...t,String(o)],!0,r)}function Mne(e,t,n,r,i=!1){let{max:s=1/0,min:o=-1/0}=t;if(e>s)throw new hs(`expected ${n} <= ${s} but got ${e}`,r);if(e<o&&!i)throw new hs(`expected ${n} >= ${o} but got ${e}`,r)}function Pne(e,t){let n=e.toString();if(n.includes("e"))return e*Math.pow(10,t);let r=n.indexOf(".");if(r===-1)return e*Math.pow(10,t);let i=n.slice(r+1),s=n.slice(0,r);return i.length<=t?+(s+i.padEnd(t,"0")):+(s+i.slice(0,t)+"."+i.slice(t))}function YLt(e,t,n){if(n=Math.abs(n),!/^\d+\.\d+$/.test(n.toString()))return(e-t)%n===0;let r=n.toString().indexOf("."),i=n.toString().slice(r+1).length;return Math.abs(Pne(e,i)-Pne(t,i))%Pne(n,i)===0}function W$(e,t,n,r){try{let[i,s]=L.resolve(e[t],n,{...r,path:[...r.path||[],t]});return s!==void 0&&(e[t]=s),i}catch(i){if(!r?.autofix)throw i;return delete e[t],n.meta.volatile?yne(n.meta.default):n.meta.default}}function One(e,t){for(let n in t)n in e||(e[n]=t[n])}function Yc(e,t,n){JPe[e]=n,Object.assign(L,{[e](...r){let i=new L({type:e});return t.forEach((s,o)=>{switch(s){case"sKey":i.sKey=r[o]??L.string();break;case"inner":i.inner=L.from(r[o]);break;case"list":i.list=r[o].map(L.from);break;case"dict":i.dict=Vm(r[o],L.from);break;case"bits":i.bits={};for(let l in r[o])typeof r[o][l]=="number"&&(i.bits[l]=r[o][l]);break;case"callback":{let l=i.callback=r[o];l.toJSON||=()=>l.toString();break}case"constructor":{let l=i.constructor=r[o];typeof l=="function"&&(l.toJSON||=()=>l.name);break}default:i[s]=r[o]}}),e==="object"||e==="dict"?i.meta.default={}:e==="array"||e==="tuple"?i.meta.default=[]:e==="bitset"&&(i.meta.default=0),i}})}var oR,KPe,hs,L,QPe,VPe,JPe,vn=F(()=>{Av();oR=Symbol.for("schemastery"),KPe=Symbol.for("ValidationError");globalThis.__schemastery_index__??=0;globalThis.__schemastery_refs__=void 0;hs=class extends TypeError{static{a(this,"ValidationError")}options;name="ValidationError";constructor(e,t){let n="$";for(let r of t.path||[])typeof r=="string"?n+="."+r:typeof r=="number"?n+="["+r+"]":typeof r=="symbol"&&(n+=`[Symbol(${r.toString()})]`);n.startsWith(".")&&(n=n.slice(1)),super((n==="$"?"":`${n} `)+e),this.options=t}static is(e){return!!e?.[KPe]}};Object.defineProperty(hs.prototype,KPe,{value:!0});L=a(function(e){let t=a(function(n,r={}){return L.resolve(n,t,r)[0]},"schema");if(e.refs){let n=Vm(e.refs,i=>new L(i)),r=a(i=>n[i],"getRef");for(let i in n){let s=n[i];s.sKey=r(s.sKey),s.inner=r(s.inner),s.list=s.list&&s.list.map(r),s.dict=s.dict&&Vm(s.dict,r)}return n[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,L.prototype),t.meta||={},t.toString=t.toString.bind(t),t},"Schema");L.prototype=Object.create(Function.prototype);L.prototype[oR]=!0;Object.defineProperty(L.prototype,"~standard",{get(){return{version:1,vendor:"schemastery",validate:a(e=>{try{return{value:L.resolve(e,this,{})[0]}}catch(t){if(hs.is(t))return{issues:[{message:t.message,path:t.options.path}]};throw t}},"validate")}}});L.ValidationError=hs;L.prototype.toJSON=a(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 t={uid:this.uid,refs:globalThis.__schemastery_refs__};return globalThis.__schemastery_refs__=void 0,t},"toJSON");L.prototype.set=a(function(t,n){return this.dict[t]=n,this},"set");L.prototype.push=a(function(t){return this.list.push(t),this},"push");a(XLt,"mergeDesc");a(sR,"getInner");a(GPe,"extractKeys");L.prototype.i18n=a(function(t){let n=L(this),r=XLt(n.meta.description,t);return Object.keys(r).length&&(n.meta.description=r),n.dict&&(n.dict=Vm(n.dict,(i,s)=>i.i18n(Vm(t,o=>sR(o)?.[s]??o?.[s])))),n.list&&(n.list=n.list.map((i,s)=>i.i18n(Vm(t,(o={})=>Array.isArray(sR(o))?sR(o)[s]:Array.isArray(o)?o[s]:GPe(o))))),n.inner&&(n.inner=n.inner.i18n(Vm(t,i=>sR(i)?sR(i):GPe(i)))),n.sKey&&(n.sKey=n.sKey.i18n(Vm(t,i=>i?.$key))),n},"i18n");L.prototype.extra=a(function(t,n){let r=L(this);return r.meta={...r.meta,[t]:n},r},"extra");for(let e of["required","disabled","collapse","hidden","loose"])Object.assign(L.prototype,{[e](t=!0){let n=L(this);return n.meta={...n.meta,[e]:t},n}});L.prototype.deprecated=a(function(){let t=L(this);return t.meta.badges||=[],t.meta.badges.push({text:"deprecated",type:"danger"}),t},"deprecated");L.prototype.experimental=a(function(){let t=L(this);return t.meta.badges||=[],t.meta.badges.push({text:"experimental",type:"warning"}),t},"experimental");L.prototype.pattern=a(function(t){let n=L(this),r=_Pe(t,["source","flags"]);return n.meta={...n.meta,pattern:r},n},"pattern");L.prototype.simplify=a(function(t){if(xh(t)&&(t=t.get()),Ep(t,this.meta.default,this.type==="dict"))return null;if(la(t))return t;if(this.type==="object"||this.type==="dict"){let n={};for(let r in t){let i=(this.type==="object"?this.dict[r]:this.inner)?.simplify(t[r]);(this.type==="dict"||!la(i))&&(n[r]=i)}return Ep(n,this.meta.default,this.type==="dict")?null:n}else if(this.type==="array"||this.type==="tuple"){let n=[];return t.forEach((r,i)=>{let s=this.type==="array"?this.inner:this.list[i],o=s?s.simplify(r):r;n.push(o)}),n}else if(this.type==="intersect"){let n={};for(let r of this.list)Object.assign(n,r.simplify(t));return n}else if(this.type==="union")for(let n of this.list)try{return L.resolve(t,n,{}),n.simplify(t)}catch{}return t},"simplify");L.prototype.toString=a(function(t){return JPe[this.type]?.(this,t)??`Schema<${this.type}>`},"toString");L.prototype.role=a(function(e,t){let n=L(this);return n.meta={...n.meta,role:e,extra:t},n},"role");for(let e of["default","link","comment","description","max","min","step"])Object.assign(L.prototype,{[e](t){let n=L(this);return n.meta={...n.meta,[e]:t},n}});L.prototype.volatile=a(function(){if(this.meta.volatile)throw new TypeError("volatile schema is already wrapped");return this.extra("volatile",!0)},"volatile");QPe={},VPe=Symbol("checked-volatile-schema");a(w_,"validateVolatileSchema");L.extend=a(function(t,n){QPe[t]=n},"extend");L.resolve=a(function(t,n,r={},i=!1){if(!n)return[t];if(r[VPe]||(w_(n,r.path),r={...r,[VPe]:!0}),n.meta?.volatile){let o=L(n);o.meta={...n.meta,volatile:!1};let[l,c]=L.resolve(t,o,r,i);try{return[yne(l),c]}catch(u){throw new hs(u instanceof Error?u.message:String(u),r)}}if(r.ignore?.(t,n))return[t];if(la(t)&&n.type!=="lazy"){if(n.meta.required)throw new hs("missing required value",r);let o=n,l=n.meta.default;for(;o?.type==="intersect"&&la(l);)o=o.list[0],l=o?.meta.default;if(la(l))return[t];t=C$(l)}let s=QPe[n.type];if(!s)throw new hs(`unsupported type "${n.type}"`,r);try{return s(t,n,r,i)}catch(o){if(!n.meta.loose)throw o;return[n.meta.default]}},"resolve");L.from=a(function(t){if(la(t))return L.any();if(["string","number","boolean"].includes(typeof t))return L.const(t).required();if(t[oR])return t;if(typeof t=="function")switch(t){case String:return L.string().required();case Number:return L.number().required();case Boolean:return L.boolean().required();case Function:return L.function().required();default:return L.is(t).required()}else throw new TypeError(`cannot infer schema from ${t}`)},"from");L.lazy=a(function(t){let n=a(()=>(r.inner[oR]||(r.inner=r.builder(),r.inner.meta={...r.meta,...r.inner.meta}),r.inner.toJSON()),"toJSON"),r=new L({type:"lazy",builder:t,inner:{toJSON:n}});return r},"lazy");L.natural=a(function(){return L.number().step(1).min(0)},"natural");L.percent=a(function(){return L.number().step(.01).min(0).max(1).role("slider")},"percent");L.date=a(function(){return L.union([L.is(Date),L.transform(L.string().role("datetime"),(t,n)=>{let r=new Date(t);if(isNaN(+r))throw new hs(`invalid date "${t}"`,n);return r},!0)])},"date");L.regExp=a(function(t=""){return L.union([L.is(RegExp),L.transform(L.string().role("regexp",{flag:t}),(n,r)=>{try{return new RegExp(n,t)}catch(i){throw new hs(i.message,r)}},!0)])},"regExp");L.arrayBuffer=a(function(t){return L.union([L.is(ArrayBuffer),L.is(SharedArrayBuffer),L.transform(L.any(),(n,r)=>{if(Gm.isSource(n))return Gm.fromSource(n);throw new hs(`expected ArrayBufferSource but got ${n}`,r)},!0),...t?[L.transform(L.string(),(n,r)=>{try{return t==="base64"?Gm.fromBase64(n):Gm.fromHex(n)}catch(i){throw new hs(i.message,r)}},!0)]:[]])},"arrayBuffer");L.extend("lazy",(e,t,n,r)=>(t.inner[oR]||(t.inner=t.builder(),t.inner.meta={...t.meta,...t.inner.meta},w_(t.inner,n.path,!0)),L.resolve(e,t.inner,n,r)));L.extend("any",e=>[e]);L.extend("never",(e,t,n)=>{throw new hs(`expected nullable but got ${e}`,n)});L.extend("const",(e,{value:t},n)=>{if(Ep(e,t))return[t];throw new hs(`expected ${t} but got ${e}`,n)});a(Mne,"checkWithinRange");L.extend("string",(e,{meta:t},n)=>{if(typeof e!="string")throw new hs(`expected string but got ${e}`,n);if(t.pattern){let r=new RegExp(t.pattern.source,t.pattern.flags);if(!r.test(e))throw new hs(`expect string to match regexp ${r}`,n)}return Mne(e.length,t,"string length",n),[e]});a(Pne,"decimalShift");a(YLt,"isMultipleOf");L.extend("number",(e,{meta:t},n)=>{if(typeof e!="number")throw new hs(`expected number but got ${e}`,n);Mne(e,t,"number",n);let{step:r}=t;if(r&&!YLt(e,t.min??0,r))throw new hs(`expected number multiple of ${r} but got ${e}`,n);return[e]});L.extend("boolean",(e,t,n)=>{if(typeof e=="boolean")return[e];throw new hs(`expected boolean but got ${e}`,n)});L.extend("bitset",(e,{bits:t,meta:n},r)=>{let i=0,s=[];if(typeof e=="number"){i=e;for(let o in t)e&t[o]&&s.push(o)}else if(Array.isArray(e)){s=e;for(let o of s){if(typeof o!="string")throw new hs(`expected string but got ${o}`,r);o in t&&(i|=t[o])}}else throw new hs(`expected number or array but got ${e}`,r);return i===n.default?[i]:[i,s]});L.extend("function",(e,t,n)=>{if(typeof e=="function")return[e];throw new hs(`expected function but got ${e}`,n)});L.extend("is",(e,{constructor:t},n)=>{if(typeof t=="function"){if(e instanceof t)return[e];throw new hs(`expected ${t.name} but got ${e}`,n)}else{if(la(e))throw new hs(`expected ${t} but got ${e}`,n);let r=Object.getPrototypeOf(e);for(;r;){if(r.constructor?.name===t)return[e];r=Object.getPrototypeOf(r)}throw new hs(`expected ${t} but got ${e}`,n)}});a(W$,"property");L.extend("array",(e,{inner:t,meta:n},r)=>{if(!Array.isArray(e))throw new hs(`expected array but got ${e}`,r);return Mne(e.length,n,"array length",r,!la(t.meta.default)),[e.map((i,s)=>W$(e,s,t,r))]});L.extend("dict",(e,{inner:t,sKey:n},r,i)=>{if(!P$(e))throw new hs(`expected object but got ${e}`,r);let s={};for(let o in e){let l;try{l=L.resolve(o,n,r)[0]}catch(c){if(i)continue;throw c}s[l]=W$(e,o,t,r),e[l]=e[o],o!==l&&delete e[o]}return[s]});L.extend("tuple",(e,{list:t},n,r)=>{if(!Array.isArray(e))throw new hs(`expected array but got ${e}`,n);let i=t.map((s,o)=>W$(e,o,s,n));return r?[i]:(i.push(...e.slice(t.length)),[i])});a(One,"merge");L.extend("object",(e,{dict:t},n,r)=>{if(!P$(e))throw new hs(`expected object but got ${e}`,n);let i={};for(let s in t){let o=W$(e,s,t[s],n);(!la(o)||s in e)&&(i[s]=o)}return r||One(i,e),[i]});L.extend("union",(e,{list:t,toString:n},r,i)=>{let s=[];for(let o of t)try{return L.resolve(e,o,r,i)}catch(l){s.push(l)}throw new hs(`expected ${n()} but got ${JSON.stringify(e)}`,r)});L.extend("intersect",(e,{list:t,toString:n},r,i)=>{if(!t.length)return[e];let s;for(let o of t){let l=L.resolve(e,o,r,!0)[0];if(!la(l))if(la(s))s=l;else{if(typeof s!=typeof l)throw new hs(`expected ${n()} but got ${JSON.stringify(e)}`,r);if(typeof l=="object")One(s??={},l);else if(s!==l)throw new hs(`expected ${n()} but got ${JSON.stringify(e)}`,r)}}return!i&&P$(e)&&One(s,e),[s]});L.extend("transform",(e,{inner:t,callback:n,preserve:r},i)=>{let[s,o=e]=L.resolve(e,t,i,!0);return r?[n(s)]:[n(s),n(o)]});JPe={};a(Yc,"defineMethod");Yc("is",["constructor"],({constructor:e})=>typeof e=="function"?e.name:e);Yc("any",[],()=>"any");Yc("never",[],()=>"never");Yc("const",["value"],({value:e})=>typeof e=="string"?JSON.stringify(e):e);Yc("string",[],()=>"string");Yc("number",[],()=>"number");Yc("boolean",[],()=>"boolean");Yc("bitset",["bits"],()=>"bitset");Yc("function",[],()=>"function");Yc("array",["inner"],({inner:e})=>`${e.toString(!0)}[]`);Yc("dict",["inner","sKey"],({inner:e,sKey:t})=>`{ [key: ${t.toString()}]: ${e.toString()} }`);Yc("tuple",["list"],({list:e})=>`[${e.map(t=>t.toString()).join(", ")}]`);Yc("object",["dict"],({dict:e})=>Object.keys(e).length===0?"{}":`{ ${Object.entries(e).map(([t,n])=>`${t}${n.meta.required?"":"?"}: ${n.toString()}`).join(", ")} }`);Yc("union",["list"],({list:e},t)=>{let n=e.map(({toString:r})=>r()).join(" | ");return t?`(${n})`:n});Yc("intersect",["list"],({list:e})=>`${e.map(t=>t.toString(!0)).join(" & ")}`);Yc("transform",["inner","callback","preserve"],({inner:e},t)=>e.toString(t))});function XPe(e,t){if(!Number.isFinite(e)||e<=0||e>2147483647)throw new Error(`${t} must be a positive finite number no greater than ${ms}`)}function YPe(e,t,n,r="timeoutMs"){if(e!==void 0&&(!Number.isFinite(e)||e<=0))throw new Error(`${r} must be a positive finite number`);return Math.min(e??t,n)}function Km(e,t,n){if(t<=0)return{signal:e??new AbortController().signal,[Symbol.dispose](){}};XPe(t,"deadline timeoutMs");let r=new AbortController,i=setTimeout(()=>{r.abort(new Nne(n,t))},t);return{signal:e!==void 0?AbortSignal.any([e,r.signal]):r.signal,[Symbol.dispose](){clearTimeout(i)}}}function B$(e,t,n){XPe(t,"idleWatchdog timeoutMs");let r=new AbortController,i=e===void 0?r.signal:AbortSignal.any([e,r.signal]),s=new Nne(n,t),o,l=!1,c=!1,u=a(()=>{o!==void 0&&clearTimeout(o),o=setTimeout(()=>{r.abort(s)},t)},"arm");return{signal:i,async next(d){if(c)throw new Error("idleWatchdog is disposed");if(l)throw new Error("idleWatchdog next is already outstanding");l=!0,u();let p=Promise.withResolvers(),h=a(()=>{p.reject(s)},"onAbort");r.signal.addEventListener("abort",h,{once:!0});try{return await Promise.race([d.next().finally(()=>{r.signal.removeEventListener("abort",h)}),p.promise])}finally{clearTimeout(o),o=void 0,l=!1}},pulse(){c||!l||u()},[Symbol.dispose](){c||(c=!0,o!==void 0&&clearTimeout(o),o=void 0)}}}function Qm(e,t){let n=e.reason;if(n instanceof Nne)return t===void 0||n.code===t?n:void 0}var Nne,ms,wh=F(()=>{Nne=class extends Error{static{a(this,"TimeoutReason")}code;timeoutMs;name="TimeoutReason";constructor(e,t){super(`${e} after ${t}ms`),this.code=e,this.timeoutMs=t}},ms=2147483647;a(XPe,"assertTimerDelay");a(YPe,"clampTimeout");a(Km,"deadline");a(B$,"idleWatchdog");a(Qm,"timeoutOf")});function Rv(e){return e.length<=120?e:`${e.slice(0,119)}\u2026`}function kh(e){return Ln(structuredClone(e))}function lR(e){return Ln(structuredClone({...e,id:q$()}))}function rOe(e){return lR({...e,role:"developer"})}function Yn(e){return lR({...e,role:"user"})}function H$(e){return lR({role:"assistant",content:e.content,source:{kind:"model",...e.source}})}function G$(e){return lR({role:"system",content:e.length===0?[]:[{type:"text",text:e}],source:{kind:"system-prompt"}})}function iOe(e){return lR({role:"tool",source:{kind:"tool",callId:e.callId},toolCallId:e.callId,content:e.content,isError:e.isError})}function K$(e){return ZLt.test(e)||/\b(?:maximum|max)(?:\s+(?:allowed|supported))?\s+context\s+(?:length|window)\b/i.test(e)||ejt.test(e)||/\b(?:input|prompt|request)\s+(?:is\s+)?too\s+(?:long|large)\s+for\s+(?:this|the)\s+model\b/i.test(e)||tjt.test(e)}function Q$(e){return/\binsufficient[\s_-]+(?:quota|balance|credits?)\b/i.test(e)||/\b(?:quota|usage[\s_-]+limit)[\s_-]+(?:exceeded|exhausted|reached)\b/i.test(e)||/\bexceed(?:ed|s)?[\s_-]+(?:(?:your|the)[\s_-]+)?(?:current[\s_-]+)?quota\b/i.test(e)||/\b(?:balance|credits?)[\s_-]+(?:exhausted|depleted)\b/i.test(e)||/\bout[\s_-]+of[\s_-]+(?:credits?|budget)\b/i.test(e)}function Zc(e){let t=new Set,n=a(r=>{if(t.has(r))return"<circular cause>";t.add(r);try{if(!(r instanceof Error)){if(typeof r=="object"&&r!==null){let l=Object.getOwnPropertyDescriptor(r,"message");if(l!==void 0&&"value"in l&&typeof l.value=="string")return l.value}return String(r)}let i=r.message===""?r.name:r.message,s=r instanceof AggregateError&&r.errors.length>0?` [${r.errors.map(n).join("; ")}]`:"",o=r.cause===void 0||r.cause===null?"":n(r.cause);return`${i}${s}${o===""||o===i?"":`: ${o}`}`}catch{return"<unrenderable value>"}finally{t.delete(r)}},"render");return n(e)}function Une(e,t,n){for(let r of Object.keys(e))if(!t.has(r))throw new Error(`${n}: unknown key "${r}"`)}function Dne(e,t){e!==void 0&&Une(e,ojt,t);let n=e?.initialDelayMs??oOe,r=e?.maxDelayMs??aOe,i=e?.jitterRatio??lOe;if(!Number.isFinite(n)||n<=0||n>ms)throw new Error(`${t}.initialDelayMs must be a positive finite number no greater than ${ms}`);if(!Number.isFinite(r)||r<=0||r>ms)throw new Error(`${t}.maxDelayMs must be a positive finite number no greater than ${ms}`);if(n>r)throw new Error(`${t}.initialDelayMs must be less than or equal to maxDelayMs`);if(!Number.isFinite(i)||i<0||i>1)throw new Error(`${t}.jitterRatio must be between 0 and 1`);return Object.freeze({initialDelayMs:n,maxDelayMs:r,jitterRatio:i})}function cR(e,t){if(e===void 0)return Object.freeze({mode:"normal",maxRetries:jne,retryableCodes:Fne,...Dne(void 0,`${t}.backoff`)});switch(e.mode){case"normal":{Une(e,ijt,t);let n=e.maxRetries??jne,r=e.retryableCodes??[...Fne];if(!Number.isSafeInteger(n)||n<0)throw new Error(`${t}.maxRetries must be a non-negative safe integer`);if(r.length===0)throw new Error(`${t}.retryableCodes must not be empty`);if(r.some(i=>typeof i!="string"||i.length===0))throw new Error(`${t}.retryableCodes must contain only non-empty strings`);if(new Set(r).size!==r.length)throw new Error(`${t}.retryableCodes must not contain duplicates`);return Object.freeze({mode:"normal",maxRetries:n,retryableCodes:Object.freeze([...r]),...Dne(e.backoff,`${t}.backoff`)})}case"always":return Une(e,sjt,t),Object.freeze({mode:"always",...Dne(e.backoff,`${t}.backoff`)});default:throw new Error(`${t}.mode must be "normal" or "always"`)}}function aR(e,t){return e.provider!==t.provider||e.model!==t.model||e.reasoningEffort!==t.reasoningEffort||e.temperature!==t.temperature||e.maxTokens!==t.maxTokens?!1:e.stop===void 0||t.stop===void 0?e.stop===t.stop:e.stop.length===t.stop.length&&e.stop.every((n,r)=>n===t.stop?.[r])}function dOe(e){return uOe.add(e),e}function pOe(e){return uOe.has(e)}function ajt(e){let t=e instanceof Error?e:new ni(ljt(e),"UNKNOWN",{cause:e}),n=ujt(t);return n!==void 0&&n.code===cjt(t)?n:Object.freeze({message:pjt(t),code:hjt(t)})}function ljt(e){try{let t=String(e);return t.length>0?t:"LLM adapter failed"}catch{return"LLM adapter failed"}}function cjt(e){try{let t=Object.getOwnPropertyDescriptor(e,"code");return t!==void 0&&"value"in t?t.value:void 0}catch{return}}function ujt(e){try{let t=Object.getOwnPropertyDescriptor(e,"failure");return t!==void 0&&"value"in t?djt(t.value):void 0}catch{return}}function djt(e){if(!(typeof e!="object"||e===null))try{let t=e,n=t.message,r=t.code,i=t.status,s=t.providerRetryAfterMs,o=t.requestId,l=t.offloadImages;return typeof n!="string"||n.length===0||typeof r!="string"||r.length===0||i!==void 0&&(!Number.isInteger(i)||i<100||i>599)||s!==void 0&&(!Number.isFinite(s)||s<=0)||o!==void 0&&(typeof o!="string"||o.length===0)||l!==void 0&&(!Number.isSafeInteger(l)||l<=0)?void 0:Object.freeze({message:n,code:r,...i===void 0?{}:{status:i},...s===void 0?{}:{providerRetryAfterMs:s},...o===void 0?{}:{requestId:o},...l===void 0?{}:{offloadImages:l}})}catch{return}}function pjt(e){try{let t=e.message;if(typeof t=="string"&&t.length>0)return t}catch{}return"LLM adapter failed"}function hjt(e){return e instanceof ni?e.code:"UNKNOWN"}function Bne(e){let t=e.trim();return t.length===0?{ok:!1,reason:"empty"}:mjt.test(t)?{ok:!0,value:t}:{ok:!1,reason:"illegalCharacters"}}function k_(e,t,n){let r=e.imageHostPath(n);if(r===void 0)return;let i=t(r);return i===void 0?void 0:{readonlyPath:i}}function z$(e){return JSON.stringify(e)}function hOe(e){return e.name===void 0?String(e.attachmentId):`${z$(e.name)} (${e.attachmentId})`}function fjt(e){switch(e){case"image/png":return".png";case"image/jpeg":return".jpg";case"image/webp":return".webp";case"image/gif":return".gif";default:return Ar(e,"image extension")}}function mOe(e,t){return` Normalized copy (read-only; may be resized or re-encoded): ${z$(t.readonlyPath)} (${e.width}x${e.height}px, ${e.mediaType}). Source dimensions, format, and byte size may differ. Copy to a writable path ending in ${fjt(e.mediaType)} before editing.`}function zne(e){return`[image omitted because this model accepts text only; attachment sha256:${String(e.attachmentId).slice(7,15)}]`}function uR(e,t,n){let r=`Image ${hOe(e)}; request preview ${t.width}x${t.height}px.`;return n===void 0?`${r} It may be resized or re-encoded; source dimensions, format, and byte size may differ.`:r+mOe(e,n)}function dR(e,t){let n=`image omitted to fit request image limits; ${hOe(e)}.`;return t===void 0?`[${n} No local normalized image path is available; ask the user to attach it again if needed.]`:`[${n}${mOe(e,t)}]`}function Id(e){return e.some(t=>t.type==="image")}function fOe(e){for(let t of e)if(t.type==="file")return!0;return!1}function gOe(e,t){let n=String(e.attachmentId).slice(7,15),r=`File ${z$(e.name)} (${e.bytes} bytes, sha256:${n})`;return t===void 0?`[${r} was uploaded, but the current execution environment cannot access a readable path. Report that limitation if its contents are needed; do not claim to have read it.]`:`[${r}: verbatim read-only copy saved at ${z$(t)}. Read that path with your file tools when its contents are needed; copy it to a writable location before modifying it. When delegating file work, include this saved path in the delegation prompt; only subagents sharing this execution environment can read it.]`}function gjt(e,t){let n;for(let[r,i]of e.entries()){if(i.type==="file"){n??=e.slice(0,r),n.push({type:"text",text:gOe(i.attachment,t(i.attachment))});continue}n?.push(i)}return n??e}function yjt(e,t){return e.some(n=>fOe(n.content))?e.map(n=>{let r=gjt(n.content,t);return r===n.content?n:{...n,content:r}}):e}function vjt(e){return Math.ceil(e/3)*4}function xjt(e,t){for(let n of e)n.type==="image"&&t(n)}function bjt(e,t){let n;for(let[r,i]of e.entries()){if(i.type==="image"&&i.offloaded===!0){n??=e.slice(0,r),n.push({type:"text",text:t(i.attachment)});continue}n?.push(i)}return n??e}function X$(e,t){return e.map(n=>{let r=bjt(n.content,t);return r===n.content?n:{...n,content:r}})}function wjt(e,t){let n=e.reduce((p,h)=>p+h,0),r=t.maxImages===void 0?0:Math.max(0,e.length-t.maxImages),i=t.maxBytes===void 0?0:Math.max(0,n-t.maxBytes);if(r===0&&i===0)return 0;let s=t.countQuantum??1,o=t.byteQuantum??1,l=r===0?0:Math.ceil(r/s)*s,c=i===0?0:Math.ceil(i/o)*o,u=0,d=0;for(let p of e){if(u>=l&&(c===0||(o===1?d>=c:d>c)))break;d+=p,u+=1}return u}function Y$(e,t,n){let r=[];for(let i of e)xjt(i.content,s=>{if(s.offloaded===!0)return;let o=n(s);r.push(t.representation==="base64"?vjt(o):o)});return wjt(r,t)}function kjt(e){let t;for(let[n,r]of e.entries()){if(r.type==="image"){t??=e.slice(0,n),t.push({type:"text",text:zne(r.attachment)});continue}t?.push(r)}return t??e}function Sjt(e){return e.some(t=>Id(t.content))?e.map(t=>{let n=kjt(t.content);return n===t.content?t:{...t,content:n}}):e}function $ne(e){let t=e.filter(n=>n.role!=="developer");return t.length===e.length?e:t}function _jt(e,t,n){let r=new Map(n.tools.map(i=>[i.name,i]));for(let i of n.updates)for(let s of i.additions)r.has(s.name)||r.set(s.name,{...s,deferLoading:!0});switch(t){case"in-history":return r;case"addition-only":{let i=new Set(e?.map(s=>s.name));for(let s of r.keys())i.has(s)||r.delete(s);return r}default:return Ar(t)}}function Ejt(e,t,n,r){if(n===void 0){let u=t;return t?.some(d=>d.deferLoading===!0)&&(u=t.map(({deferLoading:d,...p})=>p)),{messages:$ne(e),tools:u}}if(r===void 0)return{messages:$ne(e),tools:t};let i=new Set(e.flatMap(u=>u.role==="developer"?[u.id]:[]));if(r.updates.some(u=>!i.has(u.messageId)))return{messages:$ne(e),tools:t};let s=_jt(t,n,r),o=new Set(r.updates.map(u=>u.messageId)),l=new Set(r.tools.filter(u=>!u.deferLoading).map(u=>u.name)),c=[];for(let u of e){if(u.role!=="developer"){c.push(u);continue}if(!o.has(u.id))continue;let d=u.content.filter(p=>{switch(p.type){case"tool-addition":return!s.has(p.toolName)||l.has(p.toolName)?!1:(l.add(p.toolName),!0);case"tool-removal":return n!=="in-history"?!1:l.delete(p.toolName);default:return!0}});d.length!==0&&(d.length===u.content.length?c.push(u):c.push({...u,content:d}))}return{messages:c.length===e.length&&c.every((u,d)=>u===e[d])?e:c,tools:[...s.values()]}}function Ajt(e=Cv){return`${e.product}/${e.version} (+${e.url})`}function dw(e=Cv){return{"user-agent":Ajt(e)}}function Z$(e){return e}function pR(e){return e}function yOe(e){return e}function vOe(e){return e}function qa(e){return e}function Ijt(e){if(!Number.isSafeInteger(e))throw new TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function ZPe(e,t){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw new TypeError(`${t} index must be a non-negative safe integer`);return e}function Rjt(e){let t=js(e);if(t===void 0)throw new TypeError("Assistant stream chunk must be losslessly JSON-serializable");return t}function eOe(e,t){let n=t-e;return Number.isSafeInteger(n)&&e+n===t?n:void 0}function Cjt(e){switch(e.type){case"text-delta":case"reasoning-delta":return e.text!=="";case"tool-call-delta":return e.argumentsDelta!==""||e.name!==void 0;default:return!1}}function Pjt(e,t){let n=e.type==="tool-call-chunks"?e.args:e.texts,r=e.time0;for(let i=0;i<n.length;i+=1)if(i>0&&(r+=e.dt[i-1]),t(n[i]))return r}function Ojt(e){return e.type==="tool-call-chunks"&&e.name!==void 0?e.time0:Pjt(e,t=>t!=="")}function Hne(e){for(let t of e){let n=t.type==="chunk"?Cjt(t.chunk)?t.time:void 0:Ojt(t);if(n!==void 0)return n}}function xOe(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(r.type==="chunk"&&r.chunk.type===t)return r.chunk}}function bOe(e,t){let n=[];for(let r of e)r.type==="chunk"&&r.chunk.type===t&&n.push(r.chunk);return n}function wOe(e){let t=[];for(let n of e)n.type==="text-chunks"?t.push(n.texts.join("")):n.type==="chunk"&&n.chunk.type==="text-delta"&&t.push(n.chunk.text);return t.join("")}function kOe(e,t=new pw){for(let n of e)switch(n.type){case"chunk":t.push(n.chunk);break;case"text-chunks":t.push({type:"text-delta",index:n.index,text:n.texts.join("")});break;case"reasoning-chunks":t.push({type:"reasoning-delta",index:n.index,text:n.texts.join("")});break;case"tool-call-chunks":t.push({type:"tool-call-delta",index:n.index,id:n.id,...n.name===void 0?{}:{name:n.name},argumentsDelta:n.args.join("")});break;default:Ar(n,"assembleAssistantStream")}return t}function __(e,t,n){let r=Bne(e);if(r.ok)return r.value;throw new ht(r.reason==="empty"?`${t}: the API key resolved from ${n} is blank; set ${n} to the raw key (the web Models page writes it) or export it in the launching environment`:`${t}: the API key resolved from ${n} contains characters no HTTP header can carry; set ${n} to the raw key alone (the web Models page writes it)`,Wne)}function tOe(e,t){let n=ajt(e);return{type:"finish",reason:t?.aborted||n.code==="ABORTED"?{kind:"aborted",failure:n}:{kind:"error",failure:n}}}function nOe(e){let{nativeAuth:t}=e;return{...e,settingsPath:[...e.settingsPath],...e.baseURLEnv===void 0?{}:{baseURLEnv:[...e.baseURLEnv]},...t===void 0?{}:{nativeAuth:{...t,env:[...t.env]}}}}var ni,V$,sOe,qne,Wne,ZLt,ejt,tjt,uw,jne,oOe,aOe,lOe,Fne,cOe,njt,rjt,J$,ijt,sjt,ojt,uOe,mjt,Tjt,Cv,pw,S_,Mjt,Lne,ht,eL,SOe,Nr=F(()=>{Ua();ps();Cne();ol();vn();wh();a(Rv,"boundContextSummary");a(kh,"freezeMessage");a(lR,"createMessage");a(rOe,"createDeveloperMessage");a(Yn,"createUserMessage");a(H$,"createAssistantMessage");a(G$,"createSystemMessage");a(iOe,"createToolResultMessage");ni=class extends Error{static{a(this,"HarnessError")}code;constructor(e,t,n){super(e,n),this.code=t,this.name=new.target.name}},V$="CONTEXT_WINDOW_EXCEEDED",sOe="QUOTA",qne="EMPTY_RESPONSE",Wne="INVALID_CREDENTIAL",ZLt=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"),ejt=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"),tjt=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");a(K$,"isContextWindowExceededError");a(Q$,"isQuotaExceededError");a(Zc,"errorChain");uw="IMAGE_OFFLOAD_REQUIRED",jne=5,oOe=500,aOe=1e4,lOe=.1,Fne=Object.freeze([qne,"RATE_LIMIT","SERVER","TIMEOUT","TRANSPORT"]),cOe=L.object({initialDelayMs:L.number().max(ms).default(oOe),maxDelayMs:L.number().max(ms).default(aOe),jitterRatio:L.number().min(0).max(1).default(lOe)}),njt=L.object({mode:L.const("normal").required(),maxRetries:L.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(jne),retryableCodes:L.array(L.string()).default([...Fne]),backoff:cOe}),rjt=L.object({mode:L.const("always").required(),backoff:cOe}),J$=L.union([njt,rjt]),ijt=new Set(["mode","maxRetries","retryableCodes","backoff"]),sjt=new Set(["mode","maxRetries","retryableCodes","backoff"]),ojt=new Set(["initialDelayMs","maxDelayMs","jitterRatio"]);a(Une,"validateKeys");a(Dne,"resolveBackoff");a(cR,"resolveRetryPolicy");uOe=new WeakSet;a(aR,"callConfigEquals");a(dOe,"markAgentLoopRequest");a(pOe,"isAgentLoopRequest");a(ajt,"normalizeLlmFailure");a(ljt,"thrownMessage");a(cjt,"ownErrorCode");a(ujt,"ownFailureSnapshot");a(djt,"failureSnapshot");a(pjt,"errorMessage");a(hjt,"harnessErrorCode");mjt=/^[\x21-\x7E]+$/;a(Bne,"normalizeApiKey");a(k_,"resolveImageAttachmentAccess");a(z$,"quoted");a(hOe,"imageIdentity");a(fjt,"extension");a(mOe,"normalizedAccessText");a(zne,"textOnlyImageText");a(uR,"requestImageHandleText");a(dR,"offloadedImageText");a(Id,"contentHasImage");a(fOe,"contentHasFile");a(gOe,"fileHandleText");a(gjt,"replaceFilesWithHandles");a(yjt,"projectFilesToText");a(vjt,"base64Length");a(xjt,"visitImageBlocks");a(bjt,"replaceOffloadedImages");a(X$,"projectOffloadedImages");a(wjt,"offloadedImagePrefixCount");a(Y$,"requiredImageOffload");a(kjt,"replaceImagesForTextModel");a(Sjt,"projectImagesForTextModel");a($ne,"withoutDeveloperMessages");a(_jt,"toolDeclarations");a(Ejt,"projectToolUpdates");Tjt="0.2.1-rc.3",Cv={product:"deepseek-harness",version:Tjt,url:"https://github.com/deepseek-ai/deepseek-harness"};a(Ajt,"userAgent");a(dw,"attributionHeaders");a(Z$,"MessageId");a(pR,"ToolCallId");a(yOe,"ProviderRequestId");a(vOe,"LlmAttemptId");a(qa,"ReasoningEffortId");pw=class{static{a(this,"BlockAssembler")}partials=new Map;order=[];_usage;_finish;_replayState;push(e){switch(e.type){case"block-start":this.partials.has(e.index)||(this.order.push(e.index),this.partials.set(e.index,{blockType:e.blockType,text:"",toolCallArguments:""}));return;case"text-delta":case"reasoning-delta":{let t=this.ensure(e.index,e.type==="text-delta"?"text":"reasoning");if(t.block)return;t.text+=e.text;return}case"tool-call-delta":{let t=this.ensure(e.index,"tool-call");if(t.block)return;t.toolCallId=e.id,e.name&&(t.toolCallName=e.name),t.toolCallArguments+=e.argumentsDelta;return}case"block-end":{let t=this.ensure(e.index,e.block.type);if(t.block)return;t.block=e.block;return}case"usage":this._usage=e.usage;return;case"finish":this._finish=e.reason,this._replayState=e.replayState;return;default:return Ar(e,"BlockAssembler.push")}}ensure(e,t){let n=this.partials.get(e);return n||(n={blockType:t,text:"",toolCallArguments:""},this.partials.set(e,n),this.order.push(e)),n}assemble(e,t){if(e.block)return e.block;switch(e.blockType){case"text":return{type:"text",text:e.text};case"reasoning":return{type:"reasoning",text:e.text};case"tool-call":return{type:"tool-call",id:e.toolCallId??`call-${t}`,name:e.toolCallName??"",arguments:e.toolCallArguments};default:throw new Error(`cannot assemble incomplete block of type "${e.blockType}"`)}}mustGet(e){let t=this.partials.get(e);if(!t)throw new Error(`BlockAssembler invariant violated: no partial for index ${e}`);return t}assembled(){let e=this.order.map(i=>this.assemble(this.mustGet(i),i)),t=this.finish.kind==="max-tokens"?e.map(i=>i.type!=="tool-call"):void 0,n=t===void 0?e:e.filter((i,s)=>t[s]),r=this._replayState;return r?.blocks===void 0?{blocks:n,replay:r}:r.blocks.length!==e.length?{blocks:n,replay:void 0}:{blocks:n,replay:t===void 0||n.length===e.length?r:{response:r.response,blocks:r.blocks.filter((i,s)=>t[s])}}}blocks(){return this.assembled().blocks}interruptedBlocks(){return this.order.map(e=>{let t=this.mustGet(e),n=t.block?.type??t.blockType;if(!(n!=="text"&&n!=="reasoning"))return this.assemble(t,e)}).filter(e=>(e?.type==="text"||e?.type==="reasoning")&&e.text.trim()!=="")}get usage(){return this._usage}get finish(){return this._finish??{kind:"stop"}}get replayState(){return this.assembled().replay}message(e){return H$({content:this.blocks(),source:e})}};a(Ijt,"safeTime");a(ZPe,"safeIndex");a(Rjt,"snapshotChunk");a(eOe,"safeGap");S_=class{static{a(this,"AssistantStreamAccumulator")}records=[];push(e){let t=Ijt(e.time),n=Rjt(e.chunk),r=Ln({time:t,chunk:n}),i=this.records.at(-1);switch(n.type){case"text-delta":case"reasoning-delta":{if(ZPe(n.index,n.type),typeof n.text!="string")throw new TypeError(`${n.type} text must be a string`);let s=n.type==="text-delta"?"text-chunks":"reasoning-chunks",o=i!==void 0&&i.type===s?eOe(i.lastTime,t):void 0;return i!==void 0&&i.type===s&&i.index===n.index&&o!==void 0?(i.dt.push(o),i.texts.push(n.text),i.lastTime=t):this.records.push({type:s,time0:t,index:n.index,dt:[],texts:[n.text],lastTime:t}),r}case"tool-call-delta":{if(ZPe(n.index,n.type),typeof n.id!="string")throw new TypeError("tool-call-delta id must be a string");if(Object.hasOwn(n,"name")&&typeof n.name!="string")throw new TypeError("tool-call-delta name must be a string");if(typeof n.argumentsDelta!="string")throw new TypeError("tool-call-delta argumentsDelta must be a string");if(n.id.length===0||n.name==="")return this.records.push({type:"chunk",time:t,chunk:n}),r;let s=i?.type==="tool-call-chunks"?eOe(i.lastTime,t):void 0,o=i?.type==="tool-call-chunks"&&Object.hasOwn(i,"name")===Object.hasOwn(n,"name")&&i.name===n.name;return i?.type==="tool-call-chunks"&&i.index===n.index&&i.id===n.id&&o&&s!==void 0?(i.dt.push(s),i.args.push(n.argumentsDelta),i.lastTime=t):this.records.push({type:"tool-call-chunks",time0:t,index:n.index,dt:[],id:n.id,...Object.hasOwn(n,"name")?{name:n.name}:{},args:[n.argumentsDelta],lastTime:t}),r}case"block-start":case"block-end":case"usage":case"finish":return this.records.push({type:"chunk",time:t,chunk:n}),r;default:return Ar(n,"AssistantStreamAccumulator.push")}}snapshot(){return Ln(this.records.map(e=>{if(e.type==="chunk")return{...e};let{lastTime:t,...n}=e;return n.type==="tool-call-chunks"?{...n,dt:[...n.dt],args:[...n.args]}:{...n,dt:[...n.dt],texts:[...n.texts]}}))}};a(Cjt,"isTokenDelta");a(Pjt,"firstRunMemberTime");a(Ojt,"runFirstTokenTime");a(Hne,"assistantStreamFirstTokenTime");a(xOe,"lastAssistantStreamChunk");a(bOe,"assistantStreamChunks");a(wOe,"joinAssistantStreamText");a(kOe,"assembleAssistantStream");Mjt=a(function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},"__runInitializers"),Lne=a(function(e,t,n,r,i,s){function o(x){if(x!==void 0&&typeof x!="function")throw new TypeError("Function expected");return x}a(o,"accept");for(var l=r.kind,c=l==="getter"?"get":l==="setter"?"set":"value",u=!t&&e?r.static?e:e.prototype:null,d=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),p,h=!1,m=n.length-1;m>=0;m--){var g={};for(var y in r)g[y]=y==="access"?{}:r[y];for(var y in r.access)g.access[y]=r.access[y];g.addInitializer=function(x){if(h)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(x||null))};var v=(0,n[m])(l==="accessor"?{get:d.get,set:d.set}:d[c],g);if(l==="accessor"){if(v===void 0)continue;if(v===null||typeof v!="object")throw new TypeError("Object expected");(p=o(v.get))&&(d.get=p),(p=o(v.set))&&(d.set=p),(p=o(v.init))&&i.unshift(p)}else(p=o(v))&&(l==="field"?i.unshift(p):d[c]=p)}u&&Object.defineProperty(u,r.name,d),h=!0},"__esDecorate"),ht=class extends ni{static{a(this,"LlmError")}failure;constructor(e,t,n){if(typeof e!="string"||e.length===0)throw new Error("LlmError message must be a non-empty string");if(typeof t!="string"||t.length===0)throw new Error("LlmError code must be a non-empty string");if(n?.status!==void 0&&(!Number.isInteger(n.status)||n.status<100||n.status>599))throw new Error("LlmError status must be an integer from 100 through 599");if(n?.providerRetryAfterMs!==void 0&&(!Number.isFinite(n.providerRetryAfterMs)||n.providerRetryAfterMs<=0))throw new Error("LlmError providerRetryAfterMs must be a positive finite number");if(n?.requestId!==void 0&&(typeof n.requestId!="string"||n.requestId.length===0))throw new Error("LlmError requestId must be a non-empty string");super(e,t,n),this.name="LlmError",this.failure=Object.freeze({message:e,code:t,...n?.status===void 0?{}:{status:n.status},...n?.providerRetryAfterMs===void 0?{}:{providerRetryAfterMs:n.providerRetryAfterMs},...n?.requestId===void 0?{}:{requestId:n.requestId},...n?.offloadImages===void 0?{}:{offloadImages:n.offloadImages}})}};a(__,"assertUsableApiKey");eL=class{static{a(this,"LlmAdapter")}providerInfo(e){return{id:e,name:e}}providerRetryPolicy(e){}imageRequestPricing(e,t){}imageRequestTarget(e,t,n){return{width:n.width,height:n.height,maxBytes:n.bytes}}listModels(e){return Promise.resolve([])}resolveModel(e,t,n){return Promise.resolve({provider:e,id:t,name:t})}async prepareCall(e,t,n){return{model:await this.resolveModel(e,t,n),stream:a(r=>this.stream(r),"stream")}}},SOe=(()=>{let e=fi,t=[],n,r,i;return class extends e{static{a(this,"LlmRuntime")}static{let o=typeof Symbol=="function"&&Symbol.metadata?Object.create(e[Symbol.metadata]??null):void 0;n=[Ft],r=[Ft],i=[Ft("discoverModels")],Lne(this,null,n,{kind:"method",name:"listProviders",static:!1,private:!1,access:{has:a(l=>"listProviders"in l,"has"),get:a(l=>l.listProviders,"get")},metadata:o},null,t),Lne(this,null,r,{kind:"method",name:"listConfigurableProviders",static:!1,private:!1,access:{has:a(l=>"listConfigurableProviders"in l,"has"),get:a(l=>l.listConfigurableProviders,"get")},metadata:o},null,t),Lne(this,null,i,{kind:"method",name:"remoteDiscoverModels",static:!1,private:!1,access:{has:a(l=>"remoteDiscoverModels"in l,"has"),get:a(l=>l.remoteDiscoverModels,"get")},metadata:o},null,t),o&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})}adapters=(Mjt(this,t),new Map);directory=new Map;discoveries=new Map;constructor(o){super(o,"llm")}emitAdaptersUpdated(){for(let o of this.ctx.events.dispatch("emit",["llm/adapters-updated"]))try{let l=o();l!=null&&typeof l.then=="function"&&Promise.resolve(l).then(void 0,c=>{this.warnAdaptersListenerFailure(c)})}catch(l){this.warnAdaptersListenerFailure(l)}}warnAdaptersListenerFailure(o){this.ctx.logger.warn("llm: an llm/adapters-updated listener failed"),this.ctx.logger.warn(o)}registerAdapter(o,l){let c=new Set,u=!1,d=this.ctx.effect(function*(){if(o.length===0)throw new ht("an adapter must register at least one provider","INVALID_ADAPTER");this.commitRoutes(c,this.prepareRoutes(o,l,c)),yield()=>{u=!0;for(let h of c)this.adapters.delete(h);c.clear(),this.emitAdaptersUpdated()}}.bind(this),"llm.registerAdapter()"),p=a((()=>{d()}),"handle");return p.replace=h=>{if(u)throw new ht("a disposed adapter registration cannot replace its routes","REGISTRATION_DISPOSED");this.commitRoutes(c,this.prepareRoutes(h,l,c))},p}prepareRoutes(o,l,c){let u=new Set,d=[];for(let p of o){if(p.length===0)throw new ht("adapter provider names must be non-empty","INVALID_ADAPTER");if(u.has(p)||this.adapters.has(p)&&!c.has(p))throw new ht(`an adapter for provider "${p}" is already registered`,"DUPLICATE_ADAPTER");let h=l.providerInfo(p);if(typeof h.id!="string"||h.id!==p||typeof h.name!="string"||h.name.length===0)throw new ht(`adapter metadata for provider "${p}" must preserve its id and have a non-empty name`,"INVALID_ADAPTER");u.add(p);let m=l.providerRetryPolicy(p)??cR(void 0,`llm: provider "${p}" retryPolicy`);d.push({adapter:l,provider:{id:h.id,name:h.name},retryPolicy:m})}return d}commitRoutes(o,l){for(let c of o)this.adapters.delete(c);o.clear();for(let c of l)this.adapters.set(c.provider.id,c),o.add(c.provider.id);this.emitAdaptersUpdated()}listProviders(){return[...this.adapters.values()].map(({provider:o})=>({...o}))}registerConfigurableProviders(o){let l=[],c=!1,u=a(h=>{let m=[],g=new Set(l.map(y=>y.provider));for(let y of h){if(y.provider.length===0||y.displayName.length===0||y.settingsNs.length===0)throw new ht("configurable providers need a non-empty provider, displayName, and settingsNs","INVALID_DIRECTORY");if(y.settingsPath.some(v=>v.length===0))throw new ht(`configurable provider "${y.provider}" has an empty settingsPath segment`,"INVALID_DIRECTORY");if(this.directory.has(y.provider)&&!g.has(y.provider)||m.some(v=>v.provider===y.provider))throw new ht(`configurable provider "${y.provider}" is already declared`,"DUPLICATE_DIRECTORY");m.push(nOe(y))}for(let y of l)this.directory.delete(y.provider);for(let y of m)this.directory.set(y.provider,y);l=m,this.emitAdaptersUpdated()},"commit"),d=this.ctx.effect(function*(){if(o.length===0)throw new ht("a configurable-provider registration must declare at least one provider","INVALID_DIRECTORY");u(o),yield()=>{c=!0;for(let h of l)this.directory.delete(h.provider);l=[],this.emitAdaptersUpdated()}}.bind(this),"llm.registerConfigurableProviders()"),p=a((()=>{d()}),"handle");return p.replace=h=>{if(c)throw new ht("this configurable-provider registration was disposed","REGISTRATION_DISPOSED");u(h)},p}listConfigurableProviders(){return[...this.directory.values()].map(nOe)}registerModelDiscovery(o,l){let c=this.ctx.effect(function*(){if(o.length===0)throw new ht("model discovery needs a non-empty settings namespace","INVALID_DISCOVERY");if(this.discoveries.has(o))throw new ht(`model discovery for "${o}" is already registered`,"DUPLICATE_DISCOVERY");this.discoveries.set(o,l),yield()=>{this.discoveries.delete(o)}}.bind(this),"llm.registerModelDiscovery()");return()=>{c()}}async discoverModels(o,l,c){let u=this.discoveries.get(o);if(u===void 0)throw new ht(`no model discovery is registered for "${o}"`,"NO_DISCOVERY");if((l.provider??"").length===0&&(l.baseURL??"").length===0)throw new ht("model discovery needs a provider route or a baseURL","INVALID_DISCOVERY");let d=c===void 0?await u(l):await u(l,c),p=new Set,h=[];for(let m of d)typeof m.id!="string"||m.id.length===0||p.has(m.id)||(p.add(m.id),h.push({id:m.id,...m.name===void 0?{}:{name:m.name},...m.contextWindow===void 0?{}:{contextWindow:m.contextWindow},...m.maxTokens===void 0?{}:{maxTokens:m.maxTokens},...m.inputModalities===void 0?{}:{inputModalities:[...m.inputModalities]}}));return h}async remoteDiscoverModels(o,l,c){try{return await this.discoverModels(o,l,c)}catch(u){throw new qe("llm/model-discovery-rejected",u instanceof Error?u.message:String(u),{settingsNs:o,...l.baseURL===void 0?{}:{baseURL:l.baseURL}},{cause:u})}}providerRetryPolicy(o){return this.registration(o).retryPolicy}imageRequestPricing(o,l){return this.adapters.get(o)?.adapter.imageRequestPricing(o,l)}imageRequestTarget(o,l,c){return this.registration(o).adapter.imageRequestTarget(o,l,c)}fileRequestText(o){return gOe(o,this.fileReadPath(o))}detachedModalities(o){return o===void 0?void 0:[...o]}async listModels(o){let l=await this.registration(o).adapter.listModels(o),c=new Set;return l.map(u=>{if(typeof u.provider!="string"||u.provider!==o||typeof u.id!="string"||u.id.length===0||typeof u.name!="string"||u.name.length===0||u.description!==void 0&&typeof u.description!="string"||c.has(u.id))throw new ht(`adapter returned invalid or duplicate model metadata for provider "${o}"`,"INVALID_CATALOG");c.add(u.id);let d=this.detachedModalities(u.inputModalities);return{provider:u.provider,id:u.id,name:u.name,...u.description===void 0?{}:{description:u.description},...d===void 0?{}:{inputModalities:d}}})}async resolveModelInfo(o,l,c){return this.resolveModelInfoFor(this.registration(o),l,c)}async resolveModelInfoFor(o,l,c){let u=await o.adapter.resolveModel(o.provider.id,l,c);return this.normalizeModelInfo(o,l,u)}normalizeModelInfo(o,l,c){let u=o.provider.id;if(typeof c.provider!="string"||c.provider!==u||typeof c.id!="string"||c.id!==l||typeof c.name!="string"||c.name.length===0||c.description!==void 0&&typeof c.description!="string")throw new ht(`adapter returned invalid exact model metadata for provider "${u}" model "${l}"`,"INVALID_MODEL_INFO");let d=c.context;if(d!==void 0&&(!Number.isInteger(d.contextWindow)||d.contextWindow<=0))throw new ht(`adapter returned invalid context metadata for provider "${u}" model "${l}"`,"INVALID_MODEL_CONTEXT");let p=this.detachedModalities(c.inputModalities),h=c.systemPromptUpdate;if(h!==void 0&&h!=="in-history")throw new ht(`adapter returned invalid system prompt update mode for provider "${u}" model "${l}"`,"INVALID_MODEL_INFO");let m=c.toolUpdate;if(m!==void 0&&m!=="in-history"&&m!=="addition-only")throw new ht(`adapter returned invalid tool update mode for provider "${u}" model "${l}"`,"INVALID_MODEL_INFO");let g=c.defaultMaxTokens;if(g!==void 0&&(!Number.isSafeInteger(g)||g<=0))throw new ht(`adapter returned invalid default maxTokens for provider "${u}" model "${l}"`,"INVALID_MODEL_MAX_TOKENS");let y={provider:u,id:l,name:c.name,...c.description===void 0?{}:{description:c.description},...p===void 0?{}:{inputModalities:p},...d===void 0?{}:{context:{contextWindow:d.contextWindow}},...g===void 0?{}:{defaultMaxTokens:g},...c.systemPromptUpdate===void 0?{}:{systemPromptUpdate:c.systemPromptUpdate},...c.toolUpdate===void 0?{}:{toolUpdate:c.toolUpdate}},v=c.reasoning;if(v===void 0)return y;if(v.efforts.length===0)throw new ht(`adapter returned invalid reasoning metadata for provider "${u}" model "${l}"`,"INVALID_MODEL_REASONING");let x=new Set,b=v.efforts.map(_=>{if(typeof _.id!="string"||_.id.length===0||typeof _.name!="string"||_.name.length===0||_.description!==void 0&&typeof _.description!="string"||x.has(_.id))throw new ht(`adapter returned invalid or duplicate reasoning effort metadata for provider "${u}" model "${l}"`,"INVALID_MODEL_REASONING");return x.add(_.id),{id:_.id,name:_.name,..._.description===void 0?{}:{description:_.description}}});if(v.defaultEffort!==void 0&&!x.has(v.defaultEffort))throw new ht(`adapter returned an unknown default reasoning effort for provider "${u}" model "${l}"`,"INVALID_MODEL_REASONING");return{...y,reasoning:{efforts:b,...v.defaultEffort===void 0?{}:{defaultEffort:v.defaultEffort}}}}async resolveCallConfig(o,l){return(await this.resolveCallFor(this.registration(o.provider),o,l)).config}async resolveCallFor(o,l,c){let u=await this.resolveModelInfoFor(o,l.model,c);return this.resolveCallWithInfo(l,u)}resolveCallWithInfo(o,l){let c=o.maxTokens===void 0&&l.defaultMaxTokens!==void 0?{...o,maxTokens:l.defaultMaxTokens}:o,u=l.reasoning,d=c.reasoningEffort,p=c;if(u===void 0){if(d!==void 0)throw new ht(`provider "${o.provider}" model "${o.model}" does not support reasoning effort "${d}"`,"UNSUPPORTED_REASONING_EFFORT")}else{let h=d??u.defaultEffort;if(h!==void 0){if(!u.efforts.some(m=>m.id===h))throw new ht(`provider "${o.provider}" model "${o.model}" does not support reasoning effort "${h}"`,"UNSUPPORTED_REASONING_EFFORT");d!==h&&(p={...c,reasoningEffort:h})}}return{config:p,...l.context===void 0?{}:{context:l.context},modelInfo:l}}async prepareCall(o,l,c){l?.throwIfAborted();let{provider:u,model:d,...p}=o,h=this.registration(u),m=await h.adapter.prepareCall(u,d,l);l?.throwIfAborted();let g=this.normalizeModelInfo(h,d,m.model),y=c===void 0?o:{...c(Ln(structuredClone(p)),Ln(g)),provider:u,model:d};l?.throwIfAborted();let v=this.resolveCallWithInfo(y,g),x=Ln(structuredClone(v.config)),b=v.context===void 0?void 0:Ln(structuredClone(v.context)),_=Ln({...y.reasoningEffort===void 0&&x.reasoningEffort!==void 0?{reasoningEffort:!0}:{},...y.maxTokens===void 0&&x.maxTokens!==void 0?{maxTokens:!0}:{}}),S=!1;return Object.freeze({config:x,retryPolicy:h.retryPolicy,adapterDefaults:_,...b===void 0?{}:{context:b},...g.inputModalities===void 0?{}:{inputModalities:Object.freeze([...g.inputModalities])},...g.systemPromptUpdate===void 0?{}:{systemPromptUpdate:g.systemPromptUpdate},...g.toolUpdate===void 0?{}:{toolUpdate:g.toolUpdate},stream:a(T=>{if(S)throw new ht("a prepared LLM call can only be dispatched once","INVALID_PREPARED_CALL");if(!aR(T,x))throw new ht("prepared LLM call config changed before adapter dispatch","INVALID_PREPARED_CALL");return S=!0,this.streamWithRegistration(T,{registration:h,config:x,modelInfo:g,dispatch:a(A=>m.stream(A),"dispatch")})},"stream")})}registration(o){let l=this.adapters.get(o);if(!l)throw new ht(`no adapter registered for provider "${o}"`,"NO_ADAPTER");return l}forAdapter(o,l){let c=o.messages.map(d=>{if(d.role!=="assistant")return d;let p=d.source;return p.replayState===void 0||this.adapters.get(p.provider)?.adapter===l?d:kh({...d,source:{kind:"model",provider:p.provider,model:p.model}})});if(c.every((d,p)=>d===o.messages[p]))return o;let u={...o,messages:c};return Object.isFrozen(o)?Ln(u):u}fileReadPath(o){let l;try{l=this.ctx.get("attachments")?.fileHostPath(o)}catch{return}if(l!==void 0)return this.ctx.get("fs")?.processPathFromHostPath(l)}async*adapterStream(o,l){let c;try{let d=l?.registration??this.registration(o.provider),p=d.adapter,h,m,g;if(l===void 0){let _=await p.prepareCall(o.provider,o.model,o.signal);h=this.normalizeModelInfo(d,o.model,_.model),m=this.resolveCallWithInfo(o,h).config,g=a(S=>_.stream(S),"dispatch")}else h=l.modelInfo,m=l.config,g=l.dispatch;if(l!==void 0&&!aR(o,m))throw new ht("prepared LLM call config changed before adapter dispatch","INVALID_PREPARED_CALL");let y=aR(o,m)?o:Object.isFrozen(o)?Ln({...o,...m}):{...o,...m},v=y.messages;v.some(_=>fOe(_.content))&&(v=yjt(v,_=>this.fileReadPath(_))),h.inputModalities!==void 0&&!h.inputModalities.includes("image")&&v.some(_=>Id(_.content))&&(v=Sjt(v));let x=Ejt(v,y.tools,h.toolUpdate,y.toolHistory);v=x.messages;let b=y;(v!==y.messages||x.tools!==y.tools)&&(b={...y,messages:v,...x.tools===void 0?{}:{tools:x.tools}},Object.isFrozen(y)&&Ln(b)),c=g(this.forAdapter(b,p))[Symbol.asyncIterator]()}catch(d){yield tOe(d,o.signal);return}let u=!1;try{for(;;){let d;try{let p=await c.next();d=p.done?{done:!0}:{done:!1,value:p.value}}catch(p){u=!0,yield tOe(p,o.signal);return}if(d.done){u=!0;return}yield d.value}}finally{if(!u){let d=c.return?.bind(c);d&&await d()}}}stream(o){return this.streamWithRegistration(o)}streamWithRegistration(o,l){return this.ctx.waterfall(this,"llm/stream",o,()=>this.adapterStream(o,l))}}})();a(tOe,"adapterFailureChunk");a(nOe,"detachDirectoryEntry")});function _Oe(e,t){for(let n=t;n!==void 0;n=E_.get(n))if(n===e)throw new Error("dsh-scope: scope parent link would form a cycle");E_.set(e,t)}function Vne(e,t){if(E_.has(e))throw new Error("dsh-scope: scope key is already bound to a parent; re-linking requires the binding returned by the original bind");return _Oe(e,t),{rebind(n){_Oe(e,n)}}}function TOe(e){return E_.get(e)}function hR(e){let t=[];for(let n=e;n!==void 0;n=E_.get(n))t.push(n);return t}async function Njt(e){for(await Promise.resolve(e.dispose());e.inertia!==void 0;)await e.inertia}function Djt(){}function Pv(e,t,n){n?.parent!==void 0&&Vne(t,n.parent);let r=e.plugin(Djt),i=r.ctx.extend({[EOe]:t}),s;return{ctx:i,rawDispose:r.dispose,dispose:a(()=>s??=Njt(r),"dispose")}}function Il(e){return e[EOe]}function Rl(e,t){let n=e[Es.filter],r={[Es.filter](i){if(n!==void 0&&!n.call(e,i))return!1;let s=Il(i);if(s===void 0)return!0;for(let o=t;o!==void 0;o=E_.get(o))if(o===s)return!0;return!1}};return Gne.set(r,t),r}function $jt(e){return typeof e=="object"&&e!==null&&Gne.has(e)}function AOe(e){if($jt(e))return Gne.get(e)}var Sh,w1,_h,EOe,Gne,E_,vc=F(()=>{mr();Sh=class{static{a(this,"NamedEntries")}duplicateError;data=new Map;constructor(e){this.duplicateError=e}insert(e,t){let n=this.data;if(n.has(e))throw this.duplicateError(e);n.set(e,t);let r=!0;return()=>{r&&(r=!1,n.delete(e),n.size===0&&this.data===n&&(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}},w1=class{static{a(this,"AnonymousEntries")}data=new Map;append(e){let t=this.data,n=Symbol();t.set(n,e);let r=!0;return()=>{r&&(r=!1,t.delete(n),t.size===0&&this.data===t&&(this.data=new Map))}}values(){return this.data.values()}isEmpty(){return this.data.size===0}},_h=class{static{a(this,"ScopedLayers")}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 n of hR(e).reverse()){let r=this.scoped.get(n);r!==void 0&&t.push(r)}return t}merge(e,t){let n=new Map(t(this.global).entries());for(let r of this.chainLayers(e))for(let[i,s]of t(r).entries())n.set(i,s);return n}effect(e,t,n){let r=Il(e),i=n.notify??!0;return e.effect(function*(){let s,o=!1;if(r===void 0)s=this.global;else{let c=this.scoped.get(r);c===void 0?(s=this.createLayer(r),this.scoped.set(r,s),o=!0):s=c}let l;try{l=t(s)}catch(c){throw r!==void 0&&o&&s.isEmpty()&&this.scoped.delete(r),c}yield()=>{l(),r!==void 0&&s.isEmpty()&&this.scoped.delete(r),i&&this.onChange()},i&&this.onChange()}.bind(this),n.label)}},EOe=Symbol("dsh.scope"),Gne=new WeakMap,E_=new WeakMap;a(_Oe,"linkScopeParent");a(Vne,"bindScopeParent");a(TOe,"scopeParentOf");a(hR,"scopeChainOf");a(Njt,"quiesceFiber");a(Djt,"scope");a(Pv,"createScope");a(Il,"scopeOf");a(Rl,"scopeTarget");a($jt,"isScopeCarrier");a(AOe,"carrierKeyOf")});import{accessSync as kTr,constants as STr,realpathSync as _Tr,statSync as ETr}from"node:fs";import{tmpdir as ATr}from"node:os";function nL(e,t){if(e!==void 0&&t===void 0)throw new Error("invalid escalation: sandbox_permissions requires a justification");if(t!==void 0&&e===void 0)throw new Error("invalid escalation: justification is only valid together with sandbox_permissions");if(t!==void 0&&t.trim().length===0)throw new Error("invalid justification: expected a non-empty sentence")}function IOe(e){return`[sandbox: file access denied under ${e} mode]`}function ROe(e){return`[sandbox: escalation available \u2014 retry this exact ${e} once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]`}function COe(e){return`The narrowest wider sandbox mode for a one-shot retry of the exact ${e} the sandbox just denied; the retry asks the user for approval.`}async function rL(e,t){let{requestedMode:n,effectiveMode:r,justification:i,subject:s}=e;if(n===r)return r;if(!(Ljt[r]??[]).includes(n))throw new Error(`sandbox escalation to "${n}" is not strictly wider than this call's current "${r}" mode`);if(t.approver===void 0)throw new Error(`sandbox escalation to "${n}" requires approval, but no approval service is composed`);if(t.agent===void 0)throw new Error(`sandbox escalation to "${n}" requires approval, but the call has no agent to route it through`);let o=await t.approver.request({agent:t.agent,toolName:t.toolName,callId:t.callId,reason:`escalate sandbox to ${n}: ${i}`,displayReason:{en:`Allow this operation with ${n} permissions: ${i}`,zh:`\u5141\u8BB8\u672C\u6B21\u64CD\u4F5C\u4F7F\u7528 ${n} \u6743\u9650\uFF1A${i}`},...t.signal?{signal:t.signal}:{}});switch(o){case"allowed-once":return n;case"rejected":throw new Error(`the user rejected escalating this ${s} to "${n}"; it stays denied, so stop and explain instead of working around it`);case"cancelled":throw new Error(`approval for escalating to "${n}" was cancelled`);case"unavailable":throw new Error(`sandbox escalation to "${n}" requires approval, but no approval channel is available`);default:return Ar(o,"EscalationOutcome")}}var Ljt,tL,Kne=F(()=>{mr();Nr();ps();Ljt={"read-only":["workspace-write","danger-full-access"],"workspace-write":["danger-full-access"]},tL=["workspace-write","danger-full-access"];a(nL,"validateEscalationArgs");a(IOe,"sandboxDenialMarker");a(ROe,"escalationHintMarker");a(COe,"sandboxPermissionsDescription");a(rL,"approveEscalation")});function QOe(e,t){let n=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(typeof n!="function")return!1;try{return n.name===t&&n.prototype===e&&Function.prototype.toString.call(n)===`function ${t}() { [native code] }`}catch{return!1}}function JOe(e){return Object.getPrototypeOf(e)===null&&QOe(e,"Object")}function XOe(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&JOe(t)}catch{return!1}}function Ujt(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!QOe(t,"Array"))return!1;let n=Object.getPrototypeOf(t);return typeof n=="object"&&n!==null&&JOe(n)}function qjt(e){try{return Reflect.ownKeys(e).every(t=>typeof t=="string"&&Object.prototype.propertyIsEnumerable.call(e,t))}catch{return!1}}function mw(e){return XOe(e)&&qjt(e)}function vR(e){if(!Array.isArray(e))return!1;try{if(!Ujt(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 aL(e){return typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0)}function POe(e,t){switch(e){case"string":return typeof t=="string";case"number":return aL(t);case"integer":return aL(t)&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;default:return Ar(e,"JsonSchemaType")}}function Wjt(e,t,n,r){let i=Object.hasOwn(e,"required"),s=i?e.required:void 0;if(i)if(!vR(s)||s.some(o=>typeof o!="string"))r.push(`${t}.required must be an array of strings`);else{let o=mw(n)?n:{};for(let l of s)Object.hasOwn(o,l)||r.push(`${t}.required names "${l}" which is not in properties`)}Object.hasOwn(e,"additionalProperties")&&typeof e.additionalProperties!="boolean"&&r.push(`${t}.additionalProperties must be a boolean`)}function YOe(e,t,n,r){let i=[{kind:"enter",node:e,path:t}];for(let s=i.pop();s!==void 0;s=i.pop()){if(s.kind==="leave"){r.delete(s.node);continue}if(s.kind==="one-of-tail"){for(let h of OOe)Object.hasOwn(s.node,h)&&n.push(`${s.path}.${h} is not supported beside oneOf`);continue}if(s.kind==="object-tail"){Wjt(s.node,s.path,s.properties,n);continue}let{node:o,path:l}=s;if(!mw(o)){n.push(`${l} must be a schema object`);continue}if(r.has(o)){n.push(`${l} is circular`);continue}r.add(o),i.push({kind:"leave",node:o});for(let h of Object.keys(o))if(!jjt.has(h)){if(Fjt.has(h)){try{b1(o[h])||n.push(`${l}.${h} annotation must be lossless JSON data`)}catch{n.push(`${l}.${h} annotation must be lossless JSON data`)}continue}n.push(`${l}.${h} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`)}Object.hasOwn(o,"description")&&typeof o.description!="string"&&n.push(`${l}.description must be a string`),Object.hasOwn(o,"title")&&typeof o.title!="string"&&n.push(`${l}.title must be a string`);let c=Object.hasOwn(o,"type"),u=Object.hasOwn(o,"oneOf");if(c&&u){n.push(`${l} cannot declare both type and oneOf`);continue}if(!c&&!u){for(let h of OOe)Object.hasOwn(o,h)&&n.push(`${l}.${h} requires type or oneOf`);continue}if(u){let h=o.oneOf;if(i.push({kind:"one-of-tail",node:o,path:l}),!vR(h)||h.length<2)n.push(`${l}.oneOf must be an array of at least two schemas`);else for(let m=h.length-1;m>=0;m--)i.push({kind:"enter",node:h[m],path:`${l}.oneOf[${m}]`});continue}let d=o.type;if(typeof d!="string"||!tre.includes(d)){n.push(Array.isArray(d)?`${l}.type must be a single type string (type arrays are not supported)`:`${l}.type must be one of ${tre.join("/")}`);continue}let p=d;for(let[h,m]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(o,h)&&!m.includes(p)&&n.push(`${l}.${h} is not supported on type "${p}"`);switch(p){case"object":{let h=Object.hasOwn(o,"properties")?o.properties:void 0;if(i.push({kind:"object-tail",node:o,path:l,properties:h}),Object.hasOwn(o,"properties"))if(!mw(h))n.push(`${l}.properties must be an object of schemas`);else{let m=Object.entries(h);for(let g=m.length-1;g>=0;g--){let y=m[g];y!==void 0&&i.push({kind:"enter",node:y[1],path:`${l}.properties.${y[0]}`})}}break}case"array":Object.hasOwn(o,"items")&&i.push({kind:"enter",node:o.items,path:`${l}.items`});break;case"string":case"number":case"integer":case"boolean":case"null":{let h=Object.hasOwn(o,"enum"),m=h?o.enum:void 0,g=vR(m)&&m.length>0&&m.every(b=>POe(p,b));h&&!g&&n.push(`${l}.enum must be a non-empty array of ${p} values`);let y=Object.hasOwn(o,"const"),v=y?o.const:void 0,x=POe(p,v);y&&(x?g&&!m.includes(v)&&n.push(`${l}.const must be one of ${l}.enum when both are declared`):n.push(`${l}.const must be a ${p} value`));break}default:Ar(p,"JsonSchemaType")}}}function gw(e){let t=[];if(YOe(e,"schema",t,new Set),t.length>0)throw new wR(t)}function cL(e){let t=[];if(YOe(e,"schema",t,new Set),t.length===0&&(!mw(e)||!Object.hasOwn(e,"type")||e.type!=="object")&&t.push('schema.type must be "object" (structured output is object-rooted)'),t.length>0)throw new wR(t)}function Qne(e){try{return b1(e)}catch{return!1}}function Rd(e){return e===""?"arguments":e}function Jne(e,t){return e===""?t:`${e}.${t}`}function Xne(e){return[`"${Rd(e)}" must be a lossless JSON value`]}function MOe(e,t){for(let n of t)e.push(n)}function NOe(e,t,n){return{node:e,value:t,path:n,catches:!1,phase:"start",children:[],childIndex:0,violations:[],tailViolations:[],matches:0}}function mR(e,t,n){let r=Object.hasOwn(e,"enum")?e.enum:void 0;return r!==void 0&&!r.includes(t)?[`"${Rd(n)}" must be one of ${JSON.stringify(r)}`]:Object.hasOwn(e,"const")&&t!==e.const?[`"${Rd(n)}" must be ${JSON.stringify(e.const)}`]:[]}function Bjt(e,t,n){let r=[NOe(e,t,n)],i,s=a(l=>{let c=r.at(-1);if(c===void 0){i=l;return}c.kind==="oneOf"?l.length===0&&c.matches++:MOe(c.violations,l)},"receive"),o=a(l=>{r.pop(),s(l)},"finish");for(;r.length>0;){let l=r.at(-1);if(l===void 0)break;try{if(l.phase==="children"){if(l.childIndex<l.children.length){let d=l.children[l.childIndex];if(d===void 0)throw new Error("missing schema-value child frame");l.childIndex++,r.push(NOe(d.node,d.value,d.path));continue}if(l.kind==="oneOf"){o(l.matches===1?[]:[`"${Rd(l.path)}" must match exactly one oneOf branch (matched ${l.matches})`]);continue}MOe(l.violations,l.tailViolations),l.violations.length>0?o(l.violations):l.kind==="object"?o(Qne(l.value)?[]:[`"${Rd(l.path)}" must be a lossless JSON object`]):o(Qne(l.value)?[]:[`"${Rd(l.path)}" must be a dense lossless JSON array`]);continue}let c=Object.hasOwn(l.node,"type")?l.node.type:void 0;l.catches=!(c!==void 0&&!tre.includes(c));let u=Object.hasOwn(l.node,"oneOf")?l.node.oneOf:void 0;if(u!==void 0){l.kind="oneOf",l.children=Array.from(u,d=>({node:d,value:l.value,path:l.path})),l.childIndex=0,l.matches=0,l.phase="children";continue}if(c===void 0){o(Qne(l.value)?[]:Xne(l.path));continue}switch(c){case"object":{if(!XOe(l.value)){o([`"${Rd(l.path)}" must be an object`]);break}let d=Object.hasOwn(l.node,"properties")?l.node.properties??{}:{},p=[],h=Object.hasOwn(l.node,"required")?l.node.required??[]:[];for(let y of h)(!Object.hasOwn(l.value,y)||l.value[y]===void 0)&&p.push(`missing required property "${Jne(l.path,y)}"`);let m=[];for(let[y,v]of Object.entries(d))!Object.hasOwn(l.value,y)||l.value[y]===void 0||m.push({node:v,value:l.value[y],path:Jne(l.path,y)});let g=[];if(Object.hasOwn(l.node,"additionalProperties")&&l.node.additionalProperties===!1)for(let y of Object.keys(l.value))Object.hasOwn(d,y)||g.push(`"${Jne(l.path,y)}" is not a declared property (additionalProperties: false)`);l.kind="object",l.children=m,l.childIndex=0,l.violations=p,l.tailViolations=g,l.phase="children";break}case"array":{if(!Array.isArray(l.value)){o([`"${Rd(l.path)}" must be an array`]);break}let d=Object.hasOwn(l.node,"items")?l.node.items:void 0,p=d===void 0?[]:l.value.flatMap((h,m)=>[{node:d,value:h,path:`${l.path}[${m}]`}]);l.kind="array",l.children=p,l.childIndex=0,l.violations=[],l.phase="children";break}case"string":o(typeof l.value=="string"?mR(l.node,l.value,l.path):[`"${Rd(l.path)}" must be a string`]);break;case"number":o(typeof l.value!="number"?[`"${Rd(l.path)}" must be a number`]:aL(l.value)?mR(l.node,l.value,l.path):[`"${Rd(l.path)}" must be a finite JSON number`]);break;case"integer":o(!aL(l.value)||!Number.isInteger(l.value)?[`"${Rd(l.path)}" must be an integer`]:mR(l.node,l.value,l.path));break;case"boolean":o(typeof l.value=="boolean"?mR(l.node,l.value,l.path):[`"${Rd(l.path)}" must be a boolean`]);break;case"null":o(l.value===null?mR(l.node,l.value,l.path):[`"${Rd(l.path)}" must be null`]);break;default:o(Ar(c,"JsonSchemaType"))}}catch(c){let u=r.pop();for(;u!==void 0&&!u.catches;)u=r.pop();if(u===void 0)throw c;s(Xne(u.path))}}return i??Xne(n)}function uL(e,t,n="value"){return Bjt(e,t,n)}function Cd(e){throw new wR([e])}function fR(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 gR(e,t,n){for(let r of Object.keys(e))n.includes(r)||Cd(`${t}.${r} is not supported by the value schema DSL`)}function Hjt(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 Gjt(e,t){e.kind==="root"?e.holder.value=t:e.target.properties=t.properties}function ZOe(e){let t=new Set,n=[e];for(let r=n.pop();r!==void 0;r=n.pop()){if(r.kind==="leave"){t.delete(r.input);continue}if(r.kind==="property-map-tail"){r.required.length>0&&(r.compiled.required=r.required,r.destination.kind==="object"&&(r.destination.target.required=r.required));continue}if(r.kind==="property"){mw(r.property)||Cd(`${r.path} must be a value schema object`),Object.hasOwn(r.property,"required")&&r.property.required!==!0&&Cd(`${r.path}.required must be true when present`),Object.hasOwn(r.property,"required")&&r.property.required===!0&&r.required.push(r.key),n.push({kind:"value",input:r.property,path:r.path,allowRequired:!0,destination:{kind:"property",target:r.properties,key:r.key}});continue}if(r.kind==="property-map"){mw(r.input)||Cd(`${r.path} must be an object of value schemas`),t.has(r.input)&&Cd(`${r.path} is circular`),t.add(r.input);let u={properties:{}},d=[];Gjt(r.destination,u),n.push({kind:"leave",input:r.input}),n.push({kind:"property-map-tail",compiled:u,required:d,destination:r.destination});let p=Object.entries(r.input);for(let h=p.length-1;h>=0;h--){let m=p[h];m!==void 0&&n.push({kind:"property",property:m[1],path:`${r.path}.${m[0]}`,key:m[0],properties:u.properties,required:d})}continue}let{input:i,path:s}=r;mw(i)||Cd(`${s} must be a value schema object`),t.has(i)&&Cd(`${s} is circular`),t.add(i);let o=[...zjt,...r.allowRequired?["required"]:[]],l={};if(Hjt(r.destination,l),n.push({kind:"leave",input:i}),Object.hasOwn(i,"oneOf")){gR(i,s,[...o,"oneOf","type"]),Object.hasOwn(i,"type")&&Cd(`${s} cannot declare both type and oneOf`),vR(i.oneOf)||Cd(`${s}.oneOf must be an array of at least two value schemas`);let u=[];l.oneOf=u,fR(i,l);for(let d=i.oneOf.length-1;d>=0;d--)n.push({kind:"value",input:i.oneOf[d],path:`${s}.oneOf[${d}]`,allowRequired:!1,destination:{kind:"one-of",target:u,index:d}});continue}let c=Object.hasOwn(i,"type")?i.type:void 0;switch(c){case"json":gR(i,s,[...o,"type"]),fR(i,l);break;case"object":gR(i,s,[...o,"type","properties","additionalProperties"]),(!Object.hasOwn(i,"additionalProperties")||typeof i.additionalProperties!="boolean")&&Cd(`${s}.additionalProperties must be explicitly true or false`),l.type="object",fR(i,l),l.additionalProperties=i.additionalProperties,Object.hasOwn(i,"properties")&&n.push({kind:"property-map",input:i.properties,path:`${s}.properties`,destination:{kind:"object",target:l}});break;case"array":gR(i,s,[...o,"type","items"]),l.type="array",fR(i,l),Object.hasOwn(i,"items")&&n.push({kind:"value",input:i.items,path:`${s}.items`,allowRequired:!1,destination:{kind:"item",target:l}});break;case"string":case"number":case"integer":case"boolean":case"null":gR(i,s,[...o,"type","enum","const"]),l.type=c,fR(i,l),Object.hasOwn(i,"enum")&&(vR(i.enum)||Cd(`${s}.enum must be a non-empty array of scalar values`),l.enum=Array.from(i.enum,u=>u)),Object.hasOwn(i,"const")&&(l.const=i.const);break;default:Cd(`${s}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`)}}}function Vjt(e,t){let n={};return ZOe({kind:"property-map",input:e,path:t,destination:{kind:"root",holder:n}}),n.value??Cd(`${t} did not compile`)}function Kjt(e,t){let n={};return ZOe({kind:"value",input:e,path:t,allowRequired:!1,destination:{kind:"root",holder:n}}),n.value??Cd(`${t} did not compile`)}function Qjt(e){let t=Kjt(e,"schema");return gw(t),t}function eMe(e){let t=Vjt(e,"parameters"),n={type:"object",properties:t.properties,...t.required===void 0?{}:{required:t.required}};return gw(n),n}function Fn(e){let t=e.execute,n=e.finalizeContent,r=e.projectContent,i=e.output.render,s=e.output.presentationMeta,o=e.presentCall,l=e.presentResult,c=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 u=eMe(e.parameters),d=Qjt(e.output.schema),p=a(m=>uL(u,m,""),"validate"),h={name:e.name,description:e.description,parameters:u,output:{schema:d,render(m,g){return i(m,g)},...s!==void 0?{presentationMeta(m,g){return s(m,g)}}:{}},...e.deferLoading===!0?{deferLoading:e.deferLoading}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},async execute(m,g){let y=p(m);if(y.length>0)throw new ore(y);return t(m,g)}};return r&&(h.projectContent=(m,g)=>r(m,g)),n&&(h.finalizeContent=(m,g)=>n(m,g)),o&&(h.presentCall=m=>{if(!(p(m).length>0))return o(m)}),l&&(h.presentResult=(m,g)=>{if(!(p(m).length>0))return l(m,g)}),c&&(h.isConcurrencySafe=m=>p(m).length>0?!1:c(m)),h}function are(e,t={programDescription:"the program to execute",outputInstruction:"Curate the program output.",codeDescription:`The ${e} program to execute, following this tool's execution instructions.`}){return{description:`Execute a ${e} program against the available tools. Takes two required arguments: \`code\`, ${t.programDescription}, and \`description\`, a short summary of what the program does. Call tools as \`await tools.name(args)\` per the declarations in the system prompt. ${t.outputInstruction} Image-bearing subtool results are attached after the run.`,codeDescription:t.codeDescription}}function Yjt(e){return e===void 0?yR:{...e.timeout===void 0?{}:{timeoutMs:{...yR.timeoutMs,description:`Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default ${e.timeout.defaultMs}; capped at ${e.timeout.maxMs}. Zero does not disable the deadline.`}},...e.sandboxMode===void 0?{}:{sandbox_permissions:yR.sandbox_permissions,justification:yR.justification}}}function Zne(e){return e?.sandboxMode===void 0?"":" A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically."}function $Oe(e){let t=e();if(t===void 0)return lL;let n=Yne[t.language];if(!Object.hasOwn(Yne,t.language)||n===void 0){let r=Object.keys(Yne).map(i=>JSON.stringify(i)).join(", ");throw new Error(`dsh-tools: no run_code schema flavor registered for runtime language ${JSON.stringify(t.language)} (known: ${r})`)}return t.language==="typescript"&&t.programFormat==="function-body"?Xjt:n}function eFt(e){let t;try{t=js(e)}catch(r){throw new Error(`tool arguments must be lossless JSON: ${r instanceof Error?r.message:String(r)}`)}if(t===void 0)throw new Error("tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)");let n=js(t);if(n===void 0)throw new Error("tool arguments could not be detached for durable logging");return{dispatched:t,logged:n}}function nFt(e){let t=[],n=[{kind:"value",value:e,depth:0,compact:!1}];for(let r=n.pop();r!==void 0;r=n.pop()){if(r.kind==="text"){t.push(r.text);continue}let i=r.value;if(i===null||typeof i=="boolean"||typeof i=="number"){t.push(String(i));continue}if(typeof i=="string"){t.push(JSON.stringify(i));continue}let s=r.compact||(r.depth+1)*2>tFt,o=r.depth+1;if(Array.isArray(i)){if(t.push("["),i.length===0){t.push("]");continue}n.push({kind:"text",text:s?"]":`
14
+ `,r:"\r",t:" "},WPe=/[\\\u0000-\u001f]/u;a(Iv,"isWhitespace");a(VLt,"isHex");j6r=class b_{static{a(this,"PartialArguments")}static EMPTY=b_.fromObject({});static fromText(t){let n=new b_;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new b_;return n.object=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},n.sealed=!0,n}chunks=[];object;sealed=!1;#e=[];#n=0;#r=0;#t="root";#i=!1;#s=0;#o=!1;#u="";#l=null;#a=[];#p=!1;#m;#h=!1;#c=new Map;#f=[];#d=new Map;get isSealed(){return this.sealed}get invalid(){return this.scan(),this.#t==="invalid"||this.#h}append(t){if(this.sealed)throw new Error("PartialArguments: cannot append to a sealed view");t.length!==0&&(this.chunks.push(t),this.#n+=t.length,this.#e.push(this.#n))}settle(t){if(this.object!==void 0||t.length!==this.#n)return b_.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return b_.fromText(t);n+=r.length}return this.chunks=t.length===0?[]:[t],this.#e=t.length===0?[]:[t.length],this.sealed=!0,this}refresh(){if(this.#d.size===0)return!1;this.scan();let t=!1,n=!1;for(let r of this.#d.values()){if(r.completion){n=!0;continue}t=this.refreshRead(r)||t}if(n)for(let r of this.#d.values())r.completion&&(t=this.refreshRead(r)||t);return this.sealed&&this.#d.clear(),t}refreshRead(t){let n=t.answer();return Object.is(n,t.last)?!1:(t.last=n,!0)}closed(){return this.remember("closed","",()=>this.closedNow())}keys(){return this.remember("keys","",()=>this.keysNow(),t=>t.length)}has(t){return this.remember("has",t,()=>this.hasNow(t))}complete(t){return this.remember("complete",t,()=>this.completeNow(t))}stringLength(t,n){let r=Math.max(1,Math.floor(n?.step??1)),i=n?.offset??0;return this.remember(`length:${r}:${i}`,t,()=>this.lengthNow(t),s=>s===void 0?void 0:Math.ceil((s+i)/r))}stringExceeds(t,n){let r=Math.max(0,Math.floor(n));return this.remember(`exceeds:${r}`,t,()=>(this.lengthNow(t,r+1)??0)>r)}text(t){return this.remember("text",t,()=>this.textNow(t))}textPrefix(t,n){let r=Math.max(1,Math.floor(n));return this.remember(`prefix:${r}`,t,()=>this.textPrefixNow(t,r))}value(t){return this.remember("value",t,()=>this.valueNow(t))}remember(t,n,r,i){this.scan();let s=r();if(!this.sealed){let o=`${t}/${n}`;this.#d.has(o)||this.#d.set(o,{completion:t==="complete",answer:i===void 0?r:()=>i(r()),last:i===void 0?s:i(s)})}return s}closedNow(){return this.sealed||this.#t==="closed"||this.#t==="invalid"}keysNow(){return this.object===void 0?this.#f:Object.keys(this.object)}hasNow(t){return this.object===void 0?this.#c.has(t):Object.hasOwn(this.object,t)}completeNow(t){if(this.object!==void 0)return Object.hasOwn(this.object,t);let n=this.#c.get(t);return n!==void 0&&n.end>=0&&(n.kind==="string"?n.invalidAt===void 0:!n.invalid)}lengthNow(t,n=Number.POSITIVE_INFINITY){if(this.object!==void 0){let s=Object.hasOwn(this.object,t)?this.object[t]:void 0;return typeof s=="string"?s.length:void 0}let r=this.#c.get(t);if(r?.kind!=="string")return;if(r.text!==void 0&&r.text.at===r.end)return r.text.length;let i=r.length??={at:r.start,length:0,text:""};return this.readString(r,i,n,!1),i.length}textNow(t){if(this.object!==void 0){let i=Object.hasOwn(this.object,t)?this.object[t]:void 0;return typeof i=="string"?i:void 0}let n=this.#c.get(t);if(n?.kind!=="string")return;if(n.text===void 0&&n.end>=0&&n.needsDecoding&&n.invalidAt===void 0){let i;try{i=JSON.parse(`"${this.slice(n.start,n.end)}"`)}catch{}i!==void 0&&(n.text={at:n.end,length:i.length,text:i})}let r=n.text??={at:n.start,length:0,text:""};return this.readString(n,r,Number.POSITIVE_INFINITY,!0),r.text}textPrefixNow(t,n){if(this.object!==void 0){let o=Object.hasOwn(this.object,t)?this.object[t]:void 0;return typeof o=="string"?o.slice(0,n):void 0}let r=this.#c.get(t);if(r?.kind!=="string")return;let i=r.prefixes??=new Map,s=i.get(n);return s===void 0&&(s={at:r.start,length:0,text:""},i.set(n,s)),this.readString(r,s,n,!0),s.text}valueNow(t){if(this.object!==void 0){if(!Object.hasOwn(this.object,t))return;let r=this.object[t];return typeof r=="string"?void 0:r}let n=this.#c.get(t);if(!(n?.kind!=="value"||n.end<0||n.invalid)){if(n.parsed===void 0)try{n.parsed=JSON.parse(this.slice(n.start,n.end))}catch{n.invalid=!0,this.#h=!0}return n.parsed}}chunkAt(t){let n=0,r=this.#e.length;for(;n<r;){let i=n+r>>>1;this.#e[i]<=t?n=i+1:r=i}return n}slice(t,n){if(t>=n)return"";let r=this.chunkAt(t),i=this.chunkAt(n-1),s=r===0?0:this.#e[r-1];if(r===i)return this.chunks[r].slice(t-s,n-s);let o=[this.chunks[r].slice(t-s)];for(let l=r+1;l<i;l++)o.push(this.chunks[l]);return o.push(this.chunks[i].slice(0,n-this.#e[i-1])),o.join("")}readString(t,n,r,i){let s=Math.min(t.end<0?this.#r:t.end,t.invalidAt??Number.POSITIVE_INFINITY,this.#m??Number.POSITIVE_INFINITY);if(!t.needsDecoding){let l=Math.min(s-n.at,r-n.length);if(l<=0)return;i&&(n.text+=this.slice(n.at,n.at+l)),n.at+=l,n.length+=l;return}let o=this.chunkAt(n.at);for(;n.at<s&&n.length<r;){let l=o===0?0:this.#e[o-1],c=this.chunks[o],u=c.slice(n.at-l,Math.min(c.length,s-l)),d=u.search(WPe),p=Math.min(d<0?u.length:d,r-n.length);if(p>0){i&&(n.text+=u.slice(0,p)),n.at+=p,n.length+=p,n.at===l+c.length&&o++;continue}let h=u.length>1?u[1]:n.at+1<s?this.chunks[o+1][0]:void 0,m,g=2;if(u[0]==="\\"&&h===void 0&&t.end<0)return;if(u[0]==="\\"&&h==="u"){let y=this.slice(n.at+2,Math.min(s,n.at+6)),v=!0;for(let x=0;x<y.length;x++)VLt(y[x])||(v=!1);if(v){if(y.length<4&&t.end<0)return;y.length===4&&(m=String.fromCharCode(Number.parseInt(y,16)))}g=6}else u[0]==="\\"&&h!==void 0&&(m=GLt[h]);if(m===void 0){t.invalidAt=n.at,this.#h=!0;return}for(i&&(n.text+=m),n.length++,n.at+=g;o<this.chunks.length&&n.at>=this.#e[o];)o++}}scan(){if(!(this.object!==void 0||this.#r===this.#n))for(let t=this.chunkAt(this.#r);t<this.chunks.length&&this.#m===void 0;t++){let n=this.chunks[t],r=t===0?0:this.#e[t-1];for(let i=this.#r-r;i<n.length&&this.#t!=="invalid";i++){if(this.#t==="string"||this.#t==="nested"&&this.#p){let s=this.stringBoundary(n,i);if(this.#r+=s-i,i=s,i===n.length)break}this.step(n[i],this.#r),this.#r++}}}stringBoundary(t,n){let r=n;for(;;){let i=t.indexOf('"',r),s=i<0?t.length:i;if(this.#t==="string"){let c=this.#l;!c.needsDecoding&&WPe.test(t.slice(r,s))&&(c.needsDecoding=!0)}let o=s;for(;o>r&&t[o-1]==="\\";)o--;let l=(s-o)%2===1!==(o===r&&this.#i);if(this.#i=i<0&&l,i<0||!l)return s;r=i+1}}step(t,n){switch(this.#t){case"root":if(Iv(t))return;if(t==="{"){this.#t="key-or-end";return}this.fail();return;case"key-or-end":if(Iv(t))return;if(t==="}"){this.#t="closed";return}if(t==='"'){this.beginKey(n);return}this.fail();return;case"key-only":if(Iv(t))return;if(t==='"'){this.beginKey(n);return}this.fail();return;case"key":this.stepKey(t,n);return;case"colon":if(Iv(t))return;if(t===":"){this.#t="value";return}this.fail();return;case"value":this.beginValue(t,n);return;case"string":{let r=this.#l;r.end=n,this.#l=null,this.#t="comma-or-end";return}case"scalar":this.stepScalar(t,n);return;case"nested":this.stepNested(t,n);return;case"comma-or-end":if(Iv(t))return;if(t===","){this.#t="key-only";return}if(t==="}"){this.#t="closed";return}this.fail();return;case"closed":if(Iv(t))return;this.fail();return;case"invalid":return;default:Ar(this.#t)}}fail(){this.#m=this.#r,this.#t="invalid",this.#l=null}beginKey(t){this.#t="key",this.#s=t+1,this.#o=!1,this.#i=!1}stepKey(t,n){if(t<" "){this.fail();return}if(this.#i){this.#i=!1;return}if(t==="\\"){this.#i=!0,this.#o=!0;return}if(t!=='"')return;let r=this.slice(this.#s,n);if(this.#o)try{this.#u=JSON.parse(`"${r}"`)}catch{this.fail();return}else this.#u=r;this.#t="colon"}open(t){this.#c.has(this.#u)||this.#f.push(this.#u),this.#c.set(this.#u,t),this.#l=t}beginValue(t,n){if(!Iv(t)){if(t==='"'){this.open({kind:"string",start:n+1,end:-1,needsDecoding:!1,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0}),this.#i=!1,this.#t="string";return}if(t==="}"||t===","||t===":"||t==="]"){this.fail();return}if(this.open({kind:"value",start:n,end:-1,parsed:void 0,invalid:!1}),t==="{"||t==="["){this.#t="nested",this.#a=[t==="{"?"}":"]"],this.#p=!1,this.#i=!1;return}this.#t="scalar"}}stepScalar(t,n){t!==","&&t!=="}"&&!Iv(t)||(this.closeValue(n),this.#t=t===","?"key-only":t==="}"?"closed":"comma-or-end")}stepNested(t,n){if(this.#p){this.#p=!1;return}if(t==='"'){this.#p=!0;return}if(t==="{"||t==="["){this.#a.push(t==="{"?"}":"]");return}if(t==="}"||t==="]"){if(this.#a.pop()!==t){this.fail();return}this.#a.length===0&&(this.closeValue(n+1),this.#t="comma-or-end")}}closeValue(t){let n=this.#l;n.end=t,this.#l=null}};a(Ar,"assertNever");a(BPe,"hasIntrinsicConstructor");a(zPe,"isIntrinsicObjectPrototype");a(KLt,"hasPlainArrayPrototype");a(QLt,"hasPlainObjectPrototype");a(JLt,"enumerableStringKeys");a(HPe,"walkJsonValue");a(js,"snapshotJsonValue");a(b1,"isJsonValue");a(Al,"deepEqualJson");a(Ln,"deepFreeze")});function q$(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16)),t=Array.from(e,(n,r)=>(r===6?n&15|64:r===8?n&63|128:n).toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Cne=F(()=>{a(q$,"randomUUID")});var ol=F(()=>{});function XLt(e,t){let n=typeof e=="string"?{"":e}:{...e};for(let r in t){let i=t[r];i?.$description||i?.$desc?n[r]=i.$description||i.$desc:typeof i=="string"&&(n[r]=i)}return n}function sR(e){return e?.$value??e?.$inner}function GPe(e){return SPe(e??{},t=>!t.startsWith("$"))}function w_(e,t=[],n=!1,r=new Map){let i=r.get(e)??new Set;if(i.has(n))return;if(i.add(n),r.set(e,i),e.meta?.volatile&&n)throw new hs("volatile fields require a fixed object path without an enclosing volatile field",{path:t});let s=n||!!e.meta?.volatile;if(e.dict)for(let[o,l]of Object.entries(e.dict))w_(l,[...t,o],s,r);if(e.sKey&&w_(e.sKey,[...t,"<key>"],!0,r),e.inner&&(e.type!=="lazy"||e.inner[oR])&&w_(e.inner,[...t,"*"],!0,r),e.list)for(let o=0;o<e.list.length;o++)w_(e.list[o],[...t,String(o)],!0,r)}function Mne(e,t,n,r,i=!1){let{max:s=1/0,min:o=-1/0}=t;if(e>s)throw new hs(`expected ${n} <= ${s} but got ${e}`,r);if(e<o&&!i)throw new hs(`expected ${n} >= ${o} but got ${e}`,r)}function Pne(e,t){let n=e.toString();if(n.includes("e"))return e*Math.pow(10,t);let r=n.indexOf(".");if(r===-1)return e*Math.pow(10,t);let i=n.slice(r+1),s=n.slice(0,r);return i.length<=t?+(s+i.padEnd(t,"0")):+(s+i.slice(0,t)+"."+i.slice(t))}function YLt(e,t,n){if(n=Math.abs(n),!/^\d+\.\d+$/.test(n.toString()))return(e-t)%n===0;let r=n.toString().indexOf("."),i=n.toString().slice(r+1).length;return Math.abs(Pne(e,i)-Pne(t,i))%Pne(n,i)===0}function W$(e,t,n,r){try{let[i,s]=L.resolve(e[t],n,{...r,path:[...r.path||[],t]});return s!==void 0&&(e[t]=s),i}catch(i){if(!r?.autofix)throw i;return delete e[t],n.meta.volatile?yne(n.meta.default):n.meta.default}}function One(e,t){for(let n in t)n in e||(e[n]=t[n])}function Yc(e,t,n){JPe[e]=n,Object.assign(L,{[e](...r){let i=new L({type:e});return t.forEach((s,o)=>{switch(s){case"sKey":i.sKey=r[o]??L.string();break;case"inner":i.inner=L.from(r[o]);break;case"list":i.list=r[o].map(L.from);break;case"dict":i.dict=Vm(r[o],L.from);break;case"bits":i.bits={};for(let l in r[o])typeof r[o][l]=="number"&&(i.bits[l]=r[o][l]);break;case"callback":{let l=i.callback=r[o];l.toJSON||=()=>l.toString();break}case"constructor":{let l=i.constructor=r[o];typeof l=="function"&&(l.toJSON||=()=>l.name);break}default:i[s]=r[o]}}),e==="object"||e==="dict"?i.meta.default={}:e==="array"||e==="tuple"?i.meta.default=[]:e==="bitset"&&(i.meta.default=0),i}})}var oR,KPe,hs,L,QPe,VPe,JPe,vn=F(()=>{Av();oR=Symbol.for("schemastery"),KPe=Symbol.for("ValidationError");globalThis.__schemastery_index__??=0;globalThis.__schemastery_refs__=void 0;hs=class extends TypeError{static{a(this,"ValidationError")}options;name="ValidationError";constructor(e,t){let n="$";for(let r of t.path||[])typeof r=="string"?n+="."+r:typeof r=="number"?n+="["+r+"]":typeof r=="symbol"&&(n+=`[Symbol(${r.toString()})]`);n.startsWith(".")&&(n=n.slice(1)),super((n==="$"?"":`${n} `)+e),this.options=t}static is(e){return!!e?.[KPe]}};Object.defineProperty(hs.prototype,KPe,{value:!0});L=a(function(e){let t=a(function(n,r={}){return L.resolve(n,t,r)[0]},"schema");if(e.refs){let n=Vm(e.refs,i=>new L(i)),r=a(i=>n[i],"getRef");for(let i in n){let s=n[i];s.sKey=r(s.sKey),s.inner=r(s.inner),s.list=s.list&&s.list.map(r),s.dict=s.dict&&Vm(s.dict,r)}return n[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,L.prototype),t.meta||={},t.toString=t.toString.bind(t),t},"Schema");L.prototype=Object.create(Function.prototype);L.prototype[oR]=!0;Object.defineProperty(L.prototype,"~standard",{get(){return{version:1,vendor:"schemastery",validate:a(e=>{try{return{value:L.resolve(e,this,{})[0]}}catch(t){if(hs.is(t))return{issues:[{message:t.message,path:t.options.path}]};throw t}},"validate")}}});L.ValidationError=hs;L.prototype.toJSON=a(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 t={uid:this.uid,refs:globalThis.__schemastery_refs__};return globalThis.__schemastery_refs__=void 0,t},"toJSON");L.prototype.set=a(function(t,n){return this.dict[t]=n,this},"set");L.prototype.push=a(function(t){return this.list.push(t),this},"push");a(XLt,"mergeDesc");a(sR,"getInner");a(GPe,"extractKeys");L.prototype.i18n=a(function(t){let n=L(this),r=XLt(n.meta.description,t);return Object.keys(r).length&&(n.meta.description=r),n.dict&&(n.dict=Vm(n.dict,(i,s)=>i.i18n(Vm(t,o=>sR(o)?.[s]??o?.[s])))),n.list&&(n.list=n.list.map((i,s)=>i.i18n(Vm(t,(o={})=>Array.isArray(sR(o))?sR(o)[s]:Array.isArray(o)?o[s]:GPe(o))))),n.inner&&(n.inner=n.inner.i18n(Vm(t,i=>sR(i)?sR(i):GPe(i)))),n.sKey&&(n.sKey=n.sKey.i18n(Vm(t,i=>i?.$key))),n},"i18n");L.prototype.extra=a(function(t,n){let r=L(this);return r.meta={...r.meta,[t]:n},r},"extra");for(let e of["required","disabled","collapse","hidden","loose"])Object.assign(L.prototype,{[e](t=!0){let n=L(this);return n.meta={...n.meta,[e]:t},n}});L.prototype.deprecated=a(function(){let t=L(this);return t.meta.badges||=[],t.meta.badges.push({text:"deprecated",type:"danger"}),t},"deprecated");L.prototype.experimental=a(function(){let t=L(this);return t.meta.badges||=[],t.meta.badges.push({text:"experimental",type:"warning"}),t},"experimental");L.prototype.pattern=a(function(t){let n=L(this),r=_Pe(t,["source","flags"]);return n.meta={...n.meta,pattern:r},n},"pattern");L.prototype.simplify=a(function(t){if(xh(t)&&(t=t.get()),Ep(t,this.meta.default,this.type==="dict"))return null;if(la(t))return t;if(this.type==="object"||this.type==="dict"){let n={};for(let r in t){let i=(this.type==="object"?this.dict[r]:this.inner)?.simplify(t[r]);(this.type==="dict"||!la(i))&&(n[r]=i)}return Ep(n,this.meta.default,this.type==="dict")?null:n}else if(this.type==="array"||this.type==="tuple"){let n=[];return t.forEach((r,i)=>{let s=this.type==="array"?this.inner:this.list[i],o=s?s.simplify(r):r;n.push(o)}),n}else if(this.type==="intersect"){let n={};for(let r of this.list)Object.assign(n,r.simplify(t));return n}else if(this.type==="union")for(let n of this.list)try{return L.resolve(t,n,{}),n.simplify(t)}catch{}return t},"simplify");L.prototype.toString=a(function(t){return JPe[this.type]?.(this,t)??`Schema<${this.type}>`},"toString");L.prototype.role=a(function(e,t){let n=L(this);return n.meta={...n.meta,role:e,extra:t},n},"role");for(let e of["default","link","comment","description","max","min","step"])Object.assign(L.prototype,{[e](t){let n=L(this);return n.meta={...n.meta,[e]:t},n}});L.prototype.volatile=a(function(){if(this.meta.volatile)throw new TypeError("volatile schema is already wrapped");return this.extra("volatile",!0)},"volatile");QPe={},VPe=Symbol("checked-volatile-schema");a(w_,"validateVolatileSchema");L.extend=a(function(t,n){QPe[t]=n},"extend");L.resolve=a(function(t,n,r={},i=!1){if(!n)return[t];if(r[VPe]||(w_(n,r.path),r={...r,[VPe]:!0}),n.meta?.volatile){let o=L(n);o.meta={...n.meta,volatile:!1};let[l,c]=L.resolve(t,o,r,i);try{return[yne(l),c]}catch(u){throw new hs(u instanceof Error?u.message:String(u),r)}}if(r.ignore?.(t,n))return[t];if(la(t)&&n.type!=="lazy"){if(n.meta.required)throw new hs("missing required value",r);let o=n,l=n.meta.default;for(;o?.type==="intersect"&&la(l);)o=o.list[0],l=o?.meta.default;if(la(l))return[t];t=C$(l)}let s=QPe[n.type];if(!s)throw new hs(`unsupported type "${n.type}"`,r);try{return s(t,n,r,i)}catch(o){if(!n.meta.loose)throw o;return[n.meta.default]}},"resolve");L.from=a(function(t){if(la(t))return L.any();if(["string","number","boolean"].includes(typeof t))return L.const(t).required();if(t[oR])return t;if(typeof t=="function")switch(t){case String:return L.string().required();case Number:return L.number().required();case Boolean:return L.boolean().required();case Function:return L.function().required();default:return L.is(t).required()}else throw new TypeError(`cannot infer schema from ${t}`)},"from");L.lazy=a(function(t){let n=a(()=>(r.inner[oR]||(r.inner=r.builder(),r.inner.meta={...r.meta,...r.inner.meta}),r.inner.toJSON()),"toJSON"),r=new L({type:"lazy",builder:t,inner:{toJSON:n}});return r},"lazy");L.natural=a(function(){return L.number().step(1).min(0)},"natural");L.percent=a(function(){return L.number().step(.01).min(0).max(1).role("slider")},"percent");L.date=a(function(){return L.union([L.is(Date),L.transform(L.string().role("datetime"),(t,n)=>{let r=new Date(t);if(isNaN(+r))throw new hs(`invalid date "${t}"`,n);return r},!0)])},"date");L.regExp=a(function(t=""){return L.union([L.is(RegExp),L.transform(L.string().role("regexp",{flag:t}),(n,r)=>{try{return new RegExp(n,t)}catch(i){throw new hs(i.message,r)}},!0)])},"regExp");L.arrayBuffer=a(function(t){return L.union([L.is(ArrayBuffer),L.is(SharedArrayBuffer),L.transform(L.any(),(n,r)=>{if(Gm.isSource(n))return Gm.fromSource(n);throw new hs(`expected ArrayBufferSource but got ${n}`,r)},!0),...t?[L.transform(L.string(),(n,r)=>{try{return t==="base64"?Gm.fromBase64(n):Gm.fromHex(n)}catch(i){throw new hs(i.message,r)}},!0)]:[]])},"arrayBuffer");L.extend("lazy",(e,t,n,r)=>(t.inner[oR]||(t.inner=t.builder(),t.inner.meta={...t.meta,...t.inner.meta},w_(t.inner,n.path,!0)),L.resolve(e,t.inner,n,r)));L.extend("any",e=>[e]);L.extend("never",(e,t,n)=>{throw new hs(`expected nullable but got ${e}`,n)});L.extend("const",(e,{value:t},n)=>{if(Ep(e,t))return[t];throw new hs(`expected ${t} but got ${e}`,n)});a(Mne,"checkWithinRange");L.extend("string",(e,{meta:t},n)=>{if(typeof e!="string")throw new hs(`expected string but got ${e}`,n);if(t.pattern){let r=new RegExp(t.pattern.source,t.pattern.flags);if(!r.test(e))throw new hs(`expect string to match regexp ${r}`,n)}return Mne(e.length,t,"string length",n),[e]});a(Pne,"decimalShift");a(YLt,"isMultipleOf");L.extend("number",(e,{meta:t},n)=>{if(typeof e!="number")throw new hs(`expected number but got ${e}`,n);Mne(e,t,"number",n);let{step:r}=t;if(r&&!YLt(e,t.min??0,r))throw new hs(`expected number multiple of ${r} but got ${e}`,n);return[e]});L.extend("boolean",(e,t,n)=>{if(typeof e=="boolean")return[e];throw new hs(`expected boolean but got ${e}`,n)});L.extend("bitset",(e,{bits:t,meta:n},r)=>{let i=0,s=[];if(typeof e=="number"){i=e;for(let o in t)e&t[o]&&s.push(o)}else if(Array.isArray(e)){s=e;for(let o of s){if(typeof o!="string")throw new hs(`expected string but got ${o}`,r);o in t&&(i|=t[o])}}else throw new hs(`expected number or array but got ${e}`,r);return i===n.default?[i]:[i,s]});L.extend("function",(e,t,n)=>{if(typeof e=="function")return[e];throw new hs(`expected function but got ${e}`,n)});L.extend("is",(e,{constructor:t},n)=>{if(typeof t=="function"){if(e instanceof t)return[e];throw new hs(`expected ${t.name} but got ${e}`,n)}else{if(la(e))throw new hs(`expected ${t} but got ${e}`,n);let r=Object.getPrototypeOf(e);for(;r;){if(r.constructor?.name===t)return[e];r=Object.getPrototypeOf(r)}throw new hs(`expected ${t} but got ${e}`,n)}});a(W$,"property");L.extend("array",(e,{inner:t,meta:n},r)=>{if(!Array.isArray(e))throw new hs(`expected array but got ${e}`,r);return Mne(e.length,n,"array length",r,!la(t.meta.default)),[e.map((i,s)=>W$(e,s,t,r))]});L.extend("dict",(e,{inner:t,sKey:n},r,i)=>{if(!P$(e))throw new hs(`expected object but got ${e}`,r);let s={};for(let o in e){let l;try{l=L.resolve(o,n,r)[0]}catch(c){if(i)continue;throw c}s[l]=W$(e,o,t,r),e[l]=e[o],o!==l&&delete e[o]}return[s]});L.extend("tuple",(e,{list:t},n,r)=>{if(!Array.isArray(e))throw new hs(`expected array but got ${e}`,n);let i=t.map((s,o)=>W$(e,o,s,n));return r?[i]:(i.push(...e.slice(t.length)),[i])});a(One,"merge");L.extend("object",(e,{dict:t},n,r)=>{if(!P$(e))throw new hs(`expected object but got ${e}`,n);let i={};for(let s in t){let o=W$(e,s,t[s],n);(!la(o)||s in e)&&(i[s]=o)}return r||One(i,e),[i]});L.extend("union",(e,{list:t,toString:n},r,i)=>{let s=[];for(let o of t)try{return L.resolve(e,o,r,i)}catch(l){s.push(l)}throw new hs(`expected ${n()} but got ${JSON.stringify(e)}`,r)});L.extend("intersect",(e,{list:t,toString:n},r,i)=>{if(!t.length)return[e];let s;for(let o of t){let l=L.resolve(e,o,r,!0)[0];if(!la(l))if(la(s))s=l;else{if(typeof s!=typeof l)throw new hs(`expected ${n()} but got ${JSON.stringify(e)}`,r);if(typeof l=="object")One(s??={},l);else if(s!==l)throw new hs(`expected ${n()} but got ${JSON.stringify(e)}`,r)}}return!i&&P$(e)&&One(s,e),[s]});L.extend("transform",(e,{inner:t,callback:n,preserve:r},i)=>{let[s,o=e]=L.resolve(e,t,i,!0);return r?[n(s)]:[n(s),n(o)]});JPe={};a(Yc,"defineMethod");Yc("is",["constructor"],({constructor:e})=>typeof e=="function"?e.name:e);Yc("any",[],()=>"any");Yc("never",[],()=>"never");Yc("const",["value"],({value:e})=>typeof e=="string"?JSON.stringify(e):e);Yc("string",[],()=>"string");Yc("number",[],()=>"number");Yc("boolean",[],()=>"boolean");Yc("bitset",["bits"],()=>"bitset");Yc("function",[],()=>"function");Yc("array",["inner"],({inner:e})=>`${e.toString(!0)}[]`);Yc("dict",["inner","sKey"],({inner:e,sKey:t})=>`{ [key: ${t.toString()}]: ${e.toString()} }`);Yc("tuple",["list"],({list:e})=>`[${e.map(t=>t.toString()).join(", ")}]`);Yc("object",["dict"],({dict:e})=>Object.keys(e).length===0?"{}":`{ ${Object.entries(e).map(([t,n])=>`${t}${n.meta.required?"":"?"}: ${n.toString()}`).join(", ")} }`);Yc("union",["list"],({list:e},t)=>{let n=e.map(({toString:r})=>r()).join(" | ");return t?`(${n})`:n});Yc("intersect",["list"],({list:e})=>`${e.map(t=>t.toString(!0)).join(" & ")}`);Yc("transform",["inner","callback","preserve"],({inner:e},t)=>e.toString(t))});function XPe(e,t){if(!Number.isFinite(e)||e<=0||e>2147483647)throw new Error(`${t} must be a positive finite number no greater than ${ms}`)}function YPe(e,t,n,r="timeoutMs"){if(e!==void 0&&(!Number.isFinite(e)||e<=0))throw new Error(`${r} must be a positive finite number`);return Math.min(e??t,n)}function Km(e,t,n){if(t<=0)return{signal:e??new AbortController().signal,[Symbol.dispose](){}};XPe(t,"deadline timeoutMs");let r=new AbortController,i=setTimeout(()=>{r.abort(new Nne(n,t))},t);return{signal:e!==void 0?AbortSignal.any([e,r.signal]):r.signal,[Symbol.dispose](){clearTimeout(i)}}}function B$(e,t,n){XPe(t,"idleWatchdog timeoutMs");let r=new AbortController,i=e===void 0?r.signal:AbortSignal.any([e,r.signal]),s=new Nne(n,t),o,l=!1,c=!1,u=a(()=>{o!==void 0&&clearTimeout(o),o=setTimeout(()=>{r.abort(s)},t)},"arm");return{signal:i,async next(d){if(c)throw new Error("idleWatchdog is disposed");if(l)throw new Error("idleWatchdog next is already outstanding");l=!0,u();let p=Promise.withResolvers(),h=a(()=>{p.reject(s)},"onAbort");r.signal.addEventListener("abort",h,{once:!0});try{return await Promise.race([d.next().finally(()=>{r.signal.removeEventListener("abort",h)}),p.promise])}finally{clearTimeout(o),o=void 0,l=!1}},pulse(){c||!l||u()},[Symbol.dispose](){c||(c=!0,o!==void 0&&clearTimeout(o),o=void 0)}}}function Qm(e,t){let n=e.reason;if(n instanceof Nne)return t===void 0||n.code===t?n:void 0}var Nne,ms,wh=F(()=>{Nne=class extends Error{static{a(this,"TimeoutReason")}code;timeoutMs;name="TimeoutReason";constructor(e,t){super(`${e} after ${t}ms`),this.code=e,this.timeoutMs=t}},ms=2147483647;a(XPe,"assertTimerDelay");a(YPe,"clampTimeout");a(Km,"deadline");a(B$,"idleWatchdog");a(Qm,"timeoutOf")});function Rv(e){return e.length<=120?e:`${e.slice(0,119)}\u2026`}function kh(e){return Ln(structuredClone(e))}function lR(e){return Ln(structuredClone({...e,id:q$()}))}function rOe(e){return lR({...e,role:"developer"})}function Yn(e){return lR({...e,role:"user"})}function H$(e){return lR({role:"assistant",content:e.content,source:{kind:"model",...e.source}})}function G$(e){return lR({role:"system",content:e.length===0?[]:[{type:"text",text:e}],source:{kind:"system-prompt"}})}function iOe(e){return lR({role:"tool",source:{kind:"tool",callId:e.callId},toolCallId:e.callId,content:e.content,isError:e.isError})}function K$(e){return ZLt.test(e)||/\b(?:maximum|max)(?:\s+(?:allowed|supported))?\s+context\s+(?:length|window)\b/i.test(e)||ejt.test(e)||/\b(?:input|prompt|request)\s+(?:is\s+)?too\s+(?:long|large)\s+for\s+(?:this|the)\s+model\b/i.test(e)||tjt.test(e)}function Q$(e){return/\binsufficient[\s_-]+(?:quota|balance|credits?)\b/i.test(e)||/\b(?:quota|usage[\s_-]+limit)[\s_-]+(?:exceeded|exhausted|reached)\b/i.test(e)||/\bexceed(?:ed|s)?[\s_-]+(?:(?:your|the)[\s_-]+)?(?:current[\s_-]+)?quota\b/i.test(e)||/\b(?:balance|credits?)[\s_-]+(?:exhausted|depleted)\b/i.test(e)||/\bout[\s_-]+of[\s_-]+(?:credits?|budget)\b/i.test(e)}function Zc(e){let t=new Set,n=a(r=>{if(t.has(r))return"<circular cause>";t.add(r);try{if(!(r instanceof Error)){if(typeof r=="object"&&r!==null){let l=Object.getOwnPropertyDescriptor(r,"message");if(l!==void 0&&"value"in l&&typeof l.value=="string")return l.value}return String(r)}let i=r.message===""?r.name:r.message,s=r instanceof AggregateError&&r.errors.length>0?` [${r.errors.map(n).join("; ")}]`:"",o=r.cause===void 0||r.cause===null?"":n(r.cause);return`${i}${s}${o===""||o===i?"":`: ${o}`}`}catch{return"<unrenderable value>"}finally{t.delete(r)}},"render");return n(e)}function Une(e,t,n){for(let r of Object.keys(e))if(!t.has(r))throw new Error(`${n}: unknown key "${r}"`)}function Dne(e,t){e!==void 0&&Une(e,ojt,t);let n=e?.initialDelayMs??oOe,r=e?.maxDelayMs??aOe,i=e?.jitterRatio??lOe;if(!Number.isFinite(n)||n<=0||n>ms)throw new Error(`${t}.initialDelayMs must be a positive finite number no greater than ${ms}`);if(!Number.isFinite(r)||r<=0||r>ms)throw new Error(`${t}.maxDelayMs must be a positive finite number no greater than ${ms}`);if(n>r)throw new Error(`${t}.initialDelayMs must be less than or equal to maxDelayMs`);if(!Number.isFinite(i)||i<0||i>1)throw new Error(`${t}.jitterRatio must be between 0 and 1`);return Object.freeze({initialDelayMs:n,maxDelayMs:r,jitterRatio:i})}function cR(e,t){if(e===void 0)return Object.freeze({mode:"normal",maxRetries:jne,retryableCodes:Fne,...Dne(void 0,`${t}.backoff`)});switch(e.mode){case"normal":{Une(e,ijt,t);let n=e.maxRetries??jne,r=e.retryableCodes??[...Fne];if(!Number.isSafeInteger(n)||n<0)throw new Error(`${t}.maxRetries must be a non-negative safe integer`);if(r.length===0)throw new Error(`${t}.retryableCodes must not be empty`);if(r.some(i=>typeof i!="string"||i.length===0))throw new Error(`${t}.retryableCodes must contain only non-empty strings`);if(new Set(r).size!==r.length)throw new Error(`${t}.retryableCodes must not contain duplicates`);return Object.freeze({mode:"normal",maxRetries:n,retryableCodes:Object.freeze([...r]),...Dne(e.backoff,`${t}.backoff`)})}case"always":return Une(e,sjt,t),Object.freeze({mode:"always",...Dne(e.backoff,`${t}.backoff`)});default:throw new Error(`${t}.mode must be "normal" or "always"`)}}function aR(e,t){return e.provider!==t.provider||e.model!==t.model||e.reasoningEffort!==t.reasoningEffort||e.temperature!==t.temperature||e.maxTokens!==t.maxTokens?!1:e.stop===void 0||t.stop===void 0?e.stop===t.stop:e.stop.length===t.stop.length&&e.stop.every((n,r)=>n===t.stop?.[r])}function dOe(e){return uOe.add(e),e}function pOe(e){return uOe.has(e)}function ajt(e){let t=e instanceof Error?e:new ni(ljt(e),"UNKNOWN",{cause:e}),n=ujt(t);return n!==void 0&&n.code===cjt(t)?n:Object.freeze({message:pjt(t),code:hjt(t)})}function ljt(e){try{let t=String(e);return t.length>0?t:"LLM adapter failed"}catch{return"LLM adapter failed"}}function cjt(e){try{let t=Object.getOwnPropertyDescriptor(e,"code");return t!==void 0&&"value"in t?t.value:void 0}catch{return}}function ujt(e){try{let t=Object.getOwnPropertyDescriptor(e,"failure");return t!==void 0&&"value"in t?djt(t.value):void 0}catch{return}}function djt(e){if(!(typeof e!="object"||e===null))try{let t=e,n=t.message,r=t.code,i=t.status,s=t.providerRetryAfterMs,o=t.requestId,l=t.offloadImages;return typeof n!="string"||n.length===0||typeof r!="string"||r.length===0||i!==void 0&&(!Number.isInteger(i)||i<100||i>599)||s!==void 0&&(!Number.isFinite(s)||s<=0)||o!==void 0&&(typeof o!="string"||o.length===0)||l!==void 0&&(!Number.isSafeInteger(l)||l<=0)?void 0:Object.freeze({message:n,code:r,...i===void 0?{}:{status:i},...s===void 0?{}:{providerRetryAfterMs:s},...o===void 0?{}:{requestId:o},...l===void 0?{}:{offloadImages:l}})}catch{return}}function pjt(e){try{let t=e.message;if(typeof t=="string"&&t.length>0)return t}catch{}return"LLM adapter failed"}function hjt(e){return e instanceof ni?e.code:"UNKNOWN"}function Bne(e){let t=e.trim();return t.length===0?{ok:!1,reason:"empty"}:mjt.test(t)?{ok:!0,value:t}:{ok:!1,reason:"illegalCharacters"}}function k_(e,t,n){let r=e.imageHostPath(n);if(r===void 0)return;let i=t(r);return i===void 0?void 0:{readonlyPath:i}}function z$(e){return JSON.stringify(e)}function hOe(e){return e.name===void 0?String(e.attachmentId):`${z$(e.name)} (${e.attachmentId})`}function fjt(e){switch(e){case"image/png":return".png";case"image/jpeg":return".jpg";case"image/webp":return".webp";case"image/gif":return".gif";default:return Ar(e,"image extension")}}function mOe(e,t){return` Normalized copy (read-only; may be resized or re-encoded): ${z$(t.readonlyPath)} (${e.width}x${e.height}px, ${e.mediaType}). Source dimensions, format, and byte size may differ. Copy to a writable path ending in ${fjt(e.mediaType)} before editing.`}function zne(e){return`[image omitted because this model accepts text only; attachment sha256:${String(e.attachmentId).slice(7,15)}]`}function uR(e,t,n){let r=`Image ${hOe(e)}; request preview ${t.width}x${t.height}px.`;return n===void 0?`${r} It may be resized or re-encoded; source dimensions, format, and byte size may differ.`:r+mOe(e,n)}function dR(e,t){let n=`image omitted to fit request image limits; ${hOe(e)}.`;return t===void 0?`[${n} No local normalized image path is available; ask the user to attach it again if needed.]`:`[${n}${mOe(e,t)}]`}function Id(e){return e.some(t=>t.type==="image")}function fOe(e){for(let t of e)if(t.type==="file")return!0;return!1}function gOe(e,t){let n=String(e.attachmentId).slice(7,15),r=`File ${z$(e.name)} (${e.bytes} bytes, sha256:${n})`;return t===void 0?`[${r} was uploaded, but the current execution environment cannot access a readable path. Report that limitation if its contents are needed; do not claim to have read it.]`:`[${r}: verbatim read-only copy saved at ${z$(t)}. Read that path with your file tools when its contents are needed; copy it to a writable location before modifying it. When delegating file work, include this saved path in the delegation prompt; only subagents sharing this execution environment can read it.]`}function gjt(e,t){let n;for(let[r,i]of e.entries()){if(i.type==="file"){n??=e.slice(0,r),n.push({type:"text",text:gOe(i.attachment,t(i.attachment))});continue}n?.push(i)}return n??e}function yjt(e,t){return e.some(n=>fOe(n.content))?e.map(n=>{let r=gjt(n.content,t);return r===n.content?n:{...n,content:r}}):e}function vjt(e){return Math.ceil(e/3)*4}function xjt(e,t){for(let n of e)n.type==="image"&&t(n)}function bjt(e,t){let n;for(let[r,i]of e.entries()){if(i.type==="image"&&i.offloaded===!0){n??=e.slice(0,r),n.push({type:"text",text:t(i.attachment)});continue}n?.push(i)}return n??e}function X$(e,t){return e.map(n=>{let r=bjt(n.content,t);return r===n.content?n:{...n,content:r}})}function wjt(e,t){let n=e.reduce((p,h)=>p+h,0),r=t.maxImages===void 0?0:Math.max(0,e.length-t.maxImages),i=t.maxBytes===void 0?0:Math.max(0,n-t.maxBytes);if(r===0&&i===0)return 0;let s=t.countQuantum??1,o=t.byteQuantum??1,l=r===0?0:Math.ceil(r/s)*s,c=i===0?0:Math.ceil(i/o)*o,u=0,d=0;for(let p of e){if(u>=l&&(c===0||(o===1?d>=c:d>c)))break;d+=p,u+=1}return u}function Y$(e,t,n){let r=[];for(let i of e)xjt(i.content,s=>{if(s.offloaded===!0)return;let o=n(s);r.push(t.representation==="base64"?vjt(o):o)});return wjt(r,t)}function kjt(e){let t;for(let[n,r]of e.entries()){if(r.type==="image"){t??=e.slice(0,n),t.push({type:"text",text:zne(r.attachment)});continue}t?.push(r)}return t??e}function Sjt(e){return e.some(t=>Id(t.content))?e.map(t=>{let n=kjt(t.content);return n===t.content?t:{...t,content:n}}):e}function $ne(e){let t=e.filter(n=>n.role!=="developer");return t.length===e.length?e:t}function _jt(e,t,n){let r=new Map(n.tools.map(i=>[i.name,i]));for(let i of n.updates)for(let s of i.additions)r.has(s.name)||r.set(s.name,{...s,deferLoading:!0});switch(t){case"in-history":return r;case"addition-only":{let i=new Set(e?.map(s=>s.name));for(let s of r.keys())i.has(s)||r.delete(s);return r}default:return Ar(t)}}function Ejt(e,t,n,r){if(n===void 0){let u=t;return t?.some(d=>d.deferLoading===!0)&&(u=t.map(({deferLoading:d,...p})=>p)),{messages:$ne(e),tools:u}}if(r===void 0)return{messages:$ne(e),tools:t};let i=new Set(e.flatMap(u=>u.role==="developer"?[u.id]:[]));if(r.updates.some(u=>!i.has(u.messageId)))return{messages:$ne(e),tools:t};let s=_jt(t,n,r),o=new Set(r.updates.map(u=>u.messageId)),l=new Set(r.tools.filter(u=>!u.deferLoading).map(u=>u.name)),c=[];for(let u of e){if(u.role!=="developer"){c.push(u);continue}if(!o.has(u.id))continue;let d=u.content.filter(p=>{switch(p.type){case"tool-addition":return!s.has(p.toolName)||l.has(p.toolName)?!1:(l.add(p.toolName),!0);case"tool-removal":return n!=="in-history"?!1:l.delete(p.toolName);default:return!0}});d.length!==0&&(d.length===u.content.length?c.push(u):c.push({...u,content:d}))}return{messages:c.length===e.length&&c.every((u,d)=>u===e[d])?e:c,tools:[...s.values()]}}function Ajt(e=Cv){return`${e.product}/${e.version} (+${e.url})`}function dw(e=Cv){return{"user-agent":Ajt(e)}}function Z$(e){return e}function pR(e){return e}function yOe(e){return e}function vOe(e){return e}function qa(e){return e}function Ijt(e){if(!Number.isSafeInteger(e))throw new TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function ZPe(e,t){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw new TypeError(`${t} index must be a non-negative safe integer`);return e}function Rjt(e){let t=js(e);if(t===void 0)throw new TypeError("Assistant stream chunk must be losslessly JSON-serializable");return t}function eOe(e,t){let n=t-e;return Number.isSafeInteger(n)&&e+n===t?n:void 0}function Cjt(e){switch(e.type){case"text-delta":case"reasoning-delta":return e.text!=="";case"tool-call-delta":return e.argumentsDelta!==""||e.name!==void 0;default:return!1}}function Pjt(e,t){let n=e.type==="tool-call-chunks"?e.args:e.texts,r=e.time0;for(let i=0;i<n.length;i+=1)if(i>0&&(r+=e.dt[i-1]),t(n[i]))return r}function Ojt(e){return e.type==="tool-call-chunks"&&e.name!==void 0?e.time0:Pjt(e,t=>t!=="")}function Hne(e){for(let t of e){let n=t.type==="chunk"?Cjt(t.chunk)?t.time:void 0:Ojt(t);if(n!==void 0)return n}}function xOe(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(r.type==="chunk"&&r.chunk.type===t)return r.chunk}}function bOe(e,t){let n=[];for(let r of e)r.type==="chunk"&&r.chunk.type===t&&n.push(r.chunk);return n}function wOe(e){let t=[];for(let n of e)n.type==="text-chunks"?t.push(n.texts.join("")):n.type==="chunk"&&n.chunk.type==="text-delta"&&t.push(n.chunk.text);return t.join("")}function kOe(e,t=new pw){for(let n of e)switch(n.type){case"chunk":t.push(n.chunk);break;case"text-chunks":t.push({type:"text-delta",index:n.index,text:n.texts.join("")});break;case"reasoning-chunks":t.push({type:"reasoning-delta",index:n.index,text:n.texts.join("")});break;case"tool-call-chunks":t.push({type:"tool-call-delta",index:n.index,id:n.id,...n.name===void 0?{}:{name:n.name},argumentsDelta:n.args.join("")});break;default:Ar(n,"assembleAssistantStream")}return t}function __(e,t,n){let r=Bne(e);if(r.ok)return r.value;throw new ht(r.reason==="empty"?`${t}: the API key resolved from ${n} is blank; set ${n} to the raw key (the web Models page writes it) or export it in the launching environment`:`${t}: the API key resolved from ${n} contains characters no HTTP header can carry; set ${n} to the raw key alone (the web Models page writes it)`,Wne)}function tOe(e,t){let n=ajt(e);return{type:"finish",reason:t?.aborted||n.code==="ABORTED"?{kind:"aborted",failure:n}:{kind:"error",failure:n}}}function nOe(e){let{nativeAuth:t}=e;return{...e,settingsPath:[...e.settingsPath],...e.baseURLEnv===void 0?{}:{baseURLEnv:[...e.baseURLEnv]},...t===void 0?{}:{nativeAuth:{...t,env:[...t.env]}}}}var ni,V$,sOe,qne,Wne,ZLt,ejt,tjt,uw,jne,oOe,aOe,lOe,Fne,cOe,njt,rjt,J$,ijt,sjt,ojt,uOe,mjt,Tjt,Cv,pw,S_,Mjt,Lne,ht,eL,SOe,Nr=F(()=>{Ua();ps();Cne();ol();vn();wh();a(Rv,"boundContextSummary");a(kh,"freezeMessage");a(lR,"createMessage");a(rOe,"createDeveloperMessage");a(Yn,"createUserMessage");a(H$,"createAssistantMessage");a(G$,"createSystemMessage");a(iOe,"createToolResultMessage");ni=class extends Error{static{a(this,"HarnessError")}code;constructor(e,t,n){super(e,n),this.code=t,this.name=new.target.name}},V$="CONTEXT_WINDOW_EXCEEDED",sOe="QUOTA",qne="EMPTY_RESPONSE",Wne="INVALID_CREDENTIAL",ZLt=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"),ejt=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"),tjt=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");a(K$,"isContextWindowExceededError");a(Q$,"isQuotaExceededError");a(Zc,"errorChain");uw="IMAGE_OFFLOAD_REQUIRED",jne=5,oOe=500,aOe=1e4,lOe=.1,Fne=Object.freeze([qne,"RATE_LIMIT","SERVER","TIMEOUT","TRANSPORT"]),cOe=L.object({initialDelayMs:L.number().max(ms).default(oOe),maxDelayMs:L.number().max(ms).default(aOe),jitterRatio:L.number().min(0).max(1).default(lOe)}),njt=L.object({mode:L.const("normal").required(),maxRetries:L.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(jne),retryableCodes:L.array(L.string()).default([...Fne]),backoff:cOe}),rjt=L.object({mode:L.const("always").required(),backoff:cOe}),J$=L.union([njt,rjt]),ijt=new Set(["mode","maxRetries","retryableCodes","backoff"]),sjt=new Set(["mode","maxRetries","retryableCodes","backoff"]),ojt=new Set(["initialDelayMs","maxDelayMs","jitterRatio"]);a(Une,"validateKeys");a(Dne,"resolveBackoff");a(cR,"resolveRetryPolicy");uOe=new WeakSet;a(aR,"callConfigEquals");a(dOe,"markAgentLoopRequest");a(pOe,"isAgentLoopRequest");a(ajt,"normalizeLlmFailure");a(ljt,"thrownMessage");a(cjt,"ownErrorCode");a(ujt,"ownFailureSnapshot");a(djt,"failureSnapshot");a(pjt,"errorMessage");a(hjt,"harnessErrorCode");mjt=/^[\x21-\x7E]+$/;a(Bne,"normalizeApiKey");a(k_,"resolveImageAttachmentAccess");a(z$,"quoted");a(hOe,"imageIdentity");a(fjt,"extension");a(mOe,"normalizedAccessText");a(zne,"textOnlyImageText");a(uR,"requestImageHandleText");a(dR,"offloadedImageText");a(Id,"contentHasImage");a(fOe,"contentHasFile");a(gOe,"fileHandleText");a(gjt,"replaceFilesWithHandles");a(yjt,"projectFilesToText");a(vjt,"base64Length");a(xjt,"visitImageBlocks");a(bjt,"replaceOffloadedImages");a(X$,"projectOffloadedImages");a(wjt,"offloadedImagePrefixCount");a(Y$,"requiredImageOffload");a(kjt,"replaceImagesForTextModel");a(Sjt,"projectImagesForTextModel");a($ne,"withoutDeveloperMessages");a(_jt,"toolDeclarations");a(Ejt,"projectToolUpdates");Tjt="0.2.1-rc.4",Cv={product:"deepseek-harness",version:Tjt,url:"https://github.com/deepseek-ai/deepseek-harness"};a(Ajt,"userAgent");a(dw,"attributionHeaders");a(Z$,"MessageId");a(pR,"ToolCallId");a(yOe,"ProviderRequestId");a(vOe,"LlmAttemptId");a(qa,"ReasoningEffortId");pw=class{static{a(this,"BlockAssembler")}partials=new Map;order=[];_usage;_finish;_replayState;push(e){switch(e.type){case"block-start":this.partials.has(e.index)||(this.order.push(e.index),this.partials.set(e.index,{blockType:e.blockType,text:"",toolCallArguments:""}));return;case"text-delta":case"reasoning-delta":{let t=this.ensure(e.index,e.type==="text-delta"?"text":"reasoning");if(t.block)return;t.text+=e.text;return}case"tool-call-delta":{let t=this.ensure(e.index,"tool-call");if(t.block)return;t.toolCallId=e.id,e.name&&(t.toolCallName=e.name),t.toolCallArguments+=e.argumentsDelta;return}case"block-end":{let t=this.ensure(e.index,e.block.type);if(t.block)return;t.block=e.block;return}case"usage":this._usage=e.usage;return;case"finish":this._finish=e.reason,this._replayState=e.replayState;return;default:return Ar(e,"BlockAssembler.push")}}ensure(e,t){let n=this.partials.get(e);return n||(n={blockType:t,text:"",toolCallArguments:""},this.partials.set(e,n),this.order.push(e)),n}assemble(e,t){if(e.block)return e.block;switch(e.blockType){case"text":return{type:"text",text:e.text};case"reasoning":return{type:"reasoning",text:e.text};case"tool-call":return{type:"tool-call",id:e.toolCallId??`call-${t}`,name:e.toolCallName??"",arguments:e.toolCallArguments};default:throw new Error(`cannot assemble incomplete block of type "${e.blockType}"`)}}mustGet(e){let t=this.partials.get(e);if(!t)throw new Error(`BlockAssembler invariant violated: no partial for index ${e}`);return t}assembled(){let e=this.order.map(i=>this.assemble(this.mustGet(i),i)),t=this.finish.kind==="max-tokens"?e.map(i=>i.type!=="tool-call"):void 0,n=t===void 0?e:e.filter((i,s)=>t[s]),r=this._replayState;return r?.blocks===void 0?{blocks:n,replay:r}:r.blocks.length!==e.length?{blocks:n,replay:void 0}:{blocks:n,replay:t===void 0||n.length===e.length?r:{response:r.response,blocks:r.blocks.filter((i,s)=>t[s])}}}blocks(){return this.assembled().blocks}interruptedBlocks(){return this.order.map(e=>{let t=this.mustGet(e),n=t.block?.type??t.blockType;if(!(n!=="text"&&n!=="reasoning"))return this.assemble(t,e)}).filter(e=>(e?.type==="text"||e?.type==="reasoning")&&e.text.trim()!=="")}get usage(){return this._usage}get finish(){return this._finish??{kind:"stop"}}get replayState(){return this.assembled().replay}message(e){return H$({content:this.blocks(),source:e})}};a(Ijt,"safeTime");a(ZPe,"safeIndex");a(Rjt,"snapshotChunk");a(eOe,"safeGap");S_=class{static{a(this,"AssistantStreamAccumulator")}records=[];push(e){let t=Ijt(e.time),n=Rjt(e.chunk),r=Ln({time:t,chunk:n}),i=this.records.at(-1);switch(n.type){case"text-delta":case"reasoning-delta":{if(ZPe(n.index,n.type),typeof n.text!="string")throw new TypeError(`${n.type} text must be a string`);let s=n.type==="text-delta"?"text-chunks":"reasoning-chunks",o=i!==void 0&&i.type===s?eOe(i.lastTime,t):void 0;return i!==void 0&&i.type===s&&i.index===n.index&&o!==void 0?(i.dt.push(o),i.texts.push(n.text),i.lastTime=t):this.records.push({type:s,time0:t,index:n.index,dt:[],texts:[n.text],lastTime:t}),r}case"tool-call-delta":{if(ZPe(n.index,n.type),typeof n.id!="string")throw new TypeError("tool-call-delta id must be a string");if(Object.hasOwn(n,"name")&&typeof n.name!="string")throw new TypeError("tool-call-delta name must be a string");if(typeof n.argumentsDelta!="string")throw new TypeError("tool-call-delta argumentsDelta must be a string");if(n.id.length===0||n.name==="")return this.records.push({type:"chunk",time:t,chunk:n}),r;let s=i?.type==="tool-call-chunks"?eOe(i.lastTime,t):void 0,o=i?.type==="tool-call-chunks"&&Object.hasOwn(i,"name")===Object.hasOwn(n,"name")&&i.name===n.name;return i?.type==="tool-call-chunks"&&i.index===n.index&&i.id===n.id&&o&&s!==void 0?(i.dt.push(s),i.args.push(n.argumentsDelta),i.lastTime=t):this.records.push({type:"tool-call-chunks",time0:t,index:n.index,dt:[],id:n.id,...Object.hasOwn(n,"name")?{name:n.name}:{},args:[n.argumentsDelta],lastTime:t}),r}case"block-start":case"block-end":case"usage":case"finish":return this.records.push({type:"chunk",time:t,chunk:n}),r;default:return Ar(n,"AssistantStreamAccumulator.push")}}snapshot(){return Ln(this.records.map(e=>{if(e.type==="chunk")return{...e};let{lastTime:t,...n}=e;return n.type==="tool-call-chunks"?{...n,dt:[...n.dt],args:[...n.args]}:{...n,dt:[...n.dt],texts:[...n.texts]}}))}};a(Cjt,"isTokenDelta");a(Pjt,"firstRunMemberTime");a(Ojt,"runFirstTokenTime");a(Hne,"assistantStreamFirstTokenTime");a(xOe,"lastAssistantStreamChunk");a(bOe,"assistantStreamChunks");a(wOe,"joinAssistantStreamText");a(kOe,"assembleAssistantStream");Mjt=a(function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},"__runInitializers"),Lne=a(function(e,t,n,r,i,s){function o(x){if(x!==void 0&&typeof x!="function")throw new TypeError("Function expected");return x}a(o,"accept");for(var l=r.kind,c=l==="getter"?"get":l==="setter"?"set":"value",u=!t&&e?r.static?e:e.prototype:null,d=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),p,h=!1,m=n.length-1;m>=0;m--){var g={};for(var y in r)g[y]=y==="access"?{}:r[y];for(var y in r.access)g.access[y]=r.access[y];g.addInitializer=function(x){if(h)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(x||null))};var v=(0,n[m])(l==="accessor"?{get:d.get,set:d.set}:d[c],g);if(l==="accessor"){if(v===void 0)continue;if(v===null||typeof v!="object")throw new TypeError("Object expected");(p=o(v.get))&&(d.get=p),(p=o(v.set))&&(d.set=p),(p=o(v.init))&&i.unshift(p)}else(p=o(v))&&(l==="field"?i.unshift(p):d[c]=p)}u&&Object.defineProperty(u,r.name,d),h=!0},"__esDecorate"),ht=class extends ni{static{a(this,"LlmError")}failure;constructor(e,t,n){if(typeof e!="string"||e.length===0)throw new Error("LlmError message must be a non-empty string");if(typeof t!="string"||t.length===0)throw new Error("LlmError code must be a non-empty string");if(n?.status!==void 0&&(!Number.isInteger(n.status)||n.status<100||n.status>599))throw new Error("LlmError status must be an integer from 100 through 599");if(n?.providerRetryAfterMs!==void 0&&(!Number.isFinite(n.providerRetryAfterMs)||n.providerRetryAfterMs<=0))throw new Error("LlmError providerRetryAfterMs must be a positive finite number");if(n?.requestId!==void 0&&(typeof n.requestId!="string"||n.requestId.length===0))throw new Error("LlmError requestId must be a non-empty string");super(e,t,n),this.name="LlmError",this.failure=Object.freeze({message:e,code:t,...n?.status===void 0?{}:{status:n.status},...n?.providerRetryAfterMs===void 0?{}:{providerRetryAfterMs:n.providerRetryAfterMs},...n?.requestId===void 0?{}:{requestId:n.requestId},...n?.offloadImages===void 0?{}:{offloadImages:n.offloadImages}})}};a(__,"assertUsableApiKey");eL=class{static{a(this,"LlmAdapter")}providerInfo(e){return{id:e,name:e}}providerRetryPolicy(e){}imageRequestPricing(e,t){}imageRequestTarget(e,t,n){return{width:n.width,height:n.height,maxBytes:n.bytes}}listModels(e){return Promise.resolve([])}resolveModel(e,t,n){return Promise.resolve({provider:e,id:t,name:t})}async prepareCall(e,t,n){return{model:await this.resolveModel(e,t,n),stream:a(r=>this.stream(r),"stream")}}},SOe=(()=>{let e=fi,t=[],n,r,i;return class extends e{static{a(this,"LlmRuntime")}static{let o=typeof Symbol=="function"&&Symbol.metadata?Object.create(e[Symbol.metadata]??null):void 0;n=[Ft],r=[Ft],i=[Ft("discoverModels")],Lne(this,null,n,{kind:"method",name:"listProviders",static:!1,private:!1,access:{has:a(l=>"listProviders"in l,"has"),get:a(l=>l.listProviders,"get")},metadata:o},null,t),Lne(this,null,r,{kind:"method",name:"listConfigurableProviders",static:!1,private:!1,access:{has:a(l=>"listConfigurableProviders"in l,"has"),get:a(l=>l.listConfigurableProviders,"get")},metadata:o},null,t),Lne(this,null,i,{kind:"method",name:"remoteDiscoverModels",static:!1,private:!1,access:{has:a(l=>"remoteDiscoverModels"in l,"has"),get:a(l=>l.remoteDiscoverModels,"get")},metadata:o},null,t),o&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})}adapters=(Mjt(this,t),new Map);directory=new Map;discoveries=new Map;constructor(o){super(o,"llm")}emitAdaptersUpdated(){for(let o of this.ctx.events.dispatch("emit",["llm/adapters-updated"]))try{let l=o();l!=null&&typeof l.then=="function"&&Promise.resolve(l).then(void 0,c=>{this.warnAdaptersListenerFailure(c)})}catch(l){this.warnAdaptersListenerFailure(l)}}warnAdaptersListenerFailure(o){this.ctx.logger.warn("llm: an llm/adapters-updated listener failed"),this.ctx.logger.warn(o)}registerAdapter(o,l){let c=new Set,u=!1,d=this.ctx.effect(function*(){if(o.length===0)throw new ht("an adapter must register at least one provider","INVALID_ADAPTER");this.commitRoutes(c,this.prepareRoutes(o,l,c)),yield()=>{u=!0;for(let h of c)this.adapters.delete(h);c.clear(),this.emitAdaptersUpdated()}}.bind(this),"llm.registerAdapter()"),p=a((()=>{d()}),"handle");return p.replace=h=>{if(u)throw new ht("a disposed adapter registration cannot replace its routes","REGISTRATION_DISPOSED");this.commitRoutes(c,this.prepareRoutes(h,l,c))},p}prepareRoutes(o,l,c){let u=new Set,d=[];for(let p of o){if(p.length===0)throw new ht("adapter provider names must be non-empty","INVALID_ADAPTER");if(u.has(p)||this.adapters.has(p)&&!c.has(p))throw new ht(`an adapter for provider "${p}" is already registered`,"DUPLICATE_ADAPTER");let h=l.providerInfo(p);if(typeof h.id!="string"||h.id!==p||typeof h.name!="string"||h.name.length===0)throw new ht(`adapter metadata for provider "${p}" must preserve its id and have a non-empty name`,"INVALID_ADAPTER");u.add(p);let m=l.providerRetryPolicy(p)??cR(void 0,`llm: provider "${p}" retryPolicy`);d.push({adapter:l,provider:{id:h.id,name:h.name},retryPolicy:m})}return d}commitRoutes(o,l){for(let c of o)this.adapters.delete(c);o.clear();for(let c of l)this.adapters.set(c.provider.id,c),o.add(c.provider.id);this.emitAdaptersUpdated()}listProviders(){return[...this.adapters.values()].map(({provider:o})=>({...o}))}registerConfigurableProviders(o){let l=[],c=!1,u=a(h=>{let m=[],g=new Set(l.map(y=>y.provider));for(let y of h){if(y.provider.length===0||y.displayName.length===0||y.settingsNs.length===0)throw new ht("configurable providers need a non-empty provider, displayName, and settingsNs","INVALID_DIRECTORY");if(y.settingsPath.some(v=>v.length===0))throw new ht(`configurable provider "${y.provider}" has an empty settingsPath segment`,"INVALID_DIRECTORY");if(this.directory.has(y.provider)&&!g.has(y.provider)||m.some(v=>v.provider===y.provider))throw new ht(`configurable provider "${y.provider}" is already declared`,"DUPLICATE_DIRECTORY");m.push(nOe(y))}for(let y of l)this.directory.delete(y.provider);for(let y of m)this.directory.set(y.provider,y);l=m,this.emitAdaptersUpdated()},"commit"),d=this.ctx.effect(function*(){if(o.length===0)throw new ht("a configurable-provider registration must declare at least one provider","INVALID_DIRECTORY");u(o),yield()=>{c=!0;for(let h of l)this.directory.delete(h.provider);l=[],this.emitAdaptersUpdated()}}.bind(this),"llm.registerConfigurableProviders()"),p=a((()=>{d()}),"handle");return p.replace=h=>{if(c)throw new ht("this configurable-provider registration was disposed","REGISTRATION_DISPOSED");u(h)},p}listConfigurableProviders(){return[...this.directory.values()].map(nOe)}registerModelDiscovery(o,l){let c=this.ctx.effect(function*(){if(o.length===0)throw new ht("model discovery needs a non-empty settings namespace","INVALID_DISCOVERY");if(this.discoveries.has(o))throw new ht(`model discovery for "${o}" is already registered`,"DUPLICATE_DISCOVERY");this.discoveries.set(o,l),yield()=>{this.discoveries.delete(o)}}.bind(this),"llm.registerModelDiscovery()");return()=>{c()}}async discoverModels(o,l,c){let u=this.discoveries.get(o);if(u===void 0)throw new ht(`no model discovery is registered for "${o}"`,"NO_DISCOVERY");if((l.provider??"").length===0&&(l.baseURL??"").length===0)throw new ht("model discovery needs a provider route or a baseURL","INVALID_DISCOVERY");let d=c===void 0?await u(l):await u(l,c),p=new Set,h=[];for(let m of d)typeof m.id!="string"||m.id.length===0||p.has(m.id)||(p.add(m.id),h.push({id:m.id,...m.name===void 0?{}:{name:m.name},...m.contextWindow===void 0?{}:{contextWindow:m.contextWindow},...m.maxTokens===void 0?{}:{maxTokens:m.maxTokens},...m.inputModalities===void 0?{}:{inputModalities:[...m.inputModalities]}}));return h}async remoteDiscoverModels(o,l,c){try{return await this.discoverModels(o,l,c)}catch(u){throw new qe("llm/model-discovery-rejected",u instanceof Error?u.message:String(u),{settingsNs:o,...l.baseURL===void 0?{}:{baseURL:l.baseURL}},{cause:u})}}providerRetryPolicy(o){return this.registration(o).retryPolicy}imageRequestPricing(o,l){return this.adapters.get(o)?.adapter.imageRequestPricing(o,l)}imageRequestTarget(o,l,c){return this.registration(o).adapter.imageRequestTarget(o,l,c)}fileRequestText(o){return gOe(o,this.fileReadPath(o))}detachedModalities(o){return o===void 0?void 0:[...o]}async listModels(o){let l=await this.registration(o).adapter.listModels(o),c=new Set;return l.map(u=>{if(typeof u.provider!="string"||u.provider!==o||typeof u.id!="string"||u.id.length===0||typeof u.name!="string"||u.name.length===0||u.description!==void 0&&typeof u.description!="string"||c.has(u.id))throw new ht(`adapter returned invalid or duplicate model metadata for provider "${o}"`,"INVALID_CATALOG");c.add(u.id);let d=this.detachedModalities(u.inputModalities);return{provider:u.provider,id:u.id,name:u.name,...u.description===void 0?{}:{description:u.description},...d===void 0?{}:{inputModalities:d}}})}async resolveModelInfo(o,l,c){return this.resolveModelInfoFor(this.registration(o),l,c)}async resolveModelInfoFor(o,l,c){let u=await o.adapter.resolveModel(o.provider.id,l,c);return this.normalizeModelInfo(o,l,u)}normalizeModelInfo(o,l,c){let u=o.provider.id;if(typeof c.provider!="string"||c.provider!==u||typeof c.id!="string"||c.id!==l||typeof c.name!="string"||c.name.length===0||c.description!==void 0&&typeof c.description!="string")throw new ht(`adapter returned invalid exact model metadata for provider "${u}" model "${l}"`,"INVALID_MODEL_INFO");let d=c.context;if(d!==void 0&&(!Number.isInteger(d.contextWindow)||d.contextWindow<=0))throw new ht(`adapter returned invalid context metadata for provider "${u}" model "${l}"`,"INVALID_MODEL_CONTEXT");let p=this.detachedModalities(c.inputModalities),h=c.systemPromptUpdate;if(h!==void 0&&h!=="in-history")throw new ht(`adapter returned invalid system prompt update mode for provider "${u}" model "${l}"`,"INVALID_MODEL_INFO");let m=c.toolUpdate;if(m!==void 0&&m!=="in-history"&&m!=="addition-only")throw new ht(`adapter returned invalid tool update mode for provider "${u}" model "${l}"`,"INVALID_MODEL_INFO");let g=c.defaultMaxTokens;if(g!==void 0&&(!Number.isSafeInteger(g)||g<=0))throw new ht(`adapter returned invalid default maxTokens for provider "${u}" model "${l}"`,"INVALID_MODEL_MAX_TOKENS");let y={provider:u,id:l,name:c.name,...c.description===void 0?{}:{description:c.description},...p===void 0?{}:{inputModalities:p},...d===void 0?{}:{context:{contextWindow:d.contextWindow}},...g===void 0?{}:{defaultMaxTokens:g},...c.systemPromptUpdate===void 0?{}:{systemPromptUpdate:c.systemPromptUpdate},...c.toolUpdate===void 0?{}:{toolUpdate:c.toolUpdate}},v=c.reasoning;if(v===void 0)return y;if(v.efforts.length===0)throw new ht(`adapter returned invalid reasoning metadata for provider "${u}" model "${l}"`,"INVALID_MODEL_REASONING");let x=new Set,b=v.efforts.map(_=>{if(typeof _.id!="string"||_.id.length===0||typeof _.name!="string"||_.name.length===0||_.description!==void 0&&typeof _.description!="string"||x.has(_.id))throw new ht(`adapter returned invalid or duplicate reasoning effort metadata for provider "${u}" model "${l}"`,"INVALID_MODEL_REASONING");return x.add(_.id),{id:_.id,name:_.name,..._.description===void 0?{}:{description:_.description}}});if(v.defaultEffort!==void 0&&!x.has(v.defaultEffort))throw new ht(`adapter returned an unknown default reasoning effort for provider "${u}" model "${l}"`,"INVALID_MODEL_REASONING");return{...y,reasoning:{efforts:b,...v.defaultEffort===void 0?{}:{defaultEffort:v.defaultEffort}}}}async resolveCallConfig(o,l){return(await this.resolveCallFor(this.registration(o.provider),o,l)).config}async resolveCallFor(o,l,c){let u=await this.resolveModelInfoFor(o,l.model,c);return this.resolveCallWithInfo(l,u)}resolveCallWithInfo(o,l){let c=o.maxTokens===void 0&&l.defaultMaxTokens!==void 0?{...o,maxTokens:l.defaultMaxTokens}:o,u=l.reasoning,d=c.reasoningEffort,p=c;if(u===void 0){if(d!==void 0)throw new ht(`provider "${o.provider}" model "${o.model}" does not support reasoning effort "${d}"`,"UNSUPPORTED_REASONING_EFFORT")}else{let h=d??u.defaultEffort;if(h!==void 0){if(!u.efforts.some(m=>m.id===h))throw new ht(`provider "${o.provider}" model "${o.model}" does not support reasoning effort "${h}"`,"UNSUPPORTED_REASONING_EFFORT");d!==h&&(p={...c,reasoningEffort:h})}}return{config:p,...l.context===void 0?{}:{context:l.context},modelInfo:l}}async prepareCall(o,l,c){l?.throwIfAborted();let{provider:u,model:d,...p}=o,h=this.registration(u),m=await h.adapter.prepareCall(u,d,l);l?.throwIfAborted();let g=this.normalizeModelInfo(h,d,m.model),y=c===void 0?o:{...c(Ln(structuredClone(p)),Ln(g)),provider:u,model:d};l?.throwIfAborted();let v=this.resolveCallWithInfo(y,g),x=Ln(structuredClone(v.config)),b=v.context===void 0?void 0:Ln(structuredClone(v.context)),_=Ln({...y.reasoningEffort===void 0&&x.reasoningEffort!==void 0?{reasoningEffort:!0}:{},...y.maxTokens===void 0&&x.maxTokens!==void 0?{maxTokens:!0}:{}}),S=!1;return Object.freeze({config:x,retryPolicy:h.retryPolicy,adapterDefaults:_,...b===void 0?{}:{context:b},...g.inputModalities===void 0?{}:{inputModalities:Object.freeze([...g.inputModalities])},...g.systemPromptUpdate===void 0?{}:{systemPromptUpdate:g.systemPromptUpdate},...g.toolUpdate===void 0?{}:{toolUpdate:g.toolUpdate},stream:a(T=>{if(S)throw new ht("a prepared LLM call can only be dispatched once","INVALID_PREPARED_CALL");if(!aR(T,x))throw new ht("prepared LLM call config changed before adapter dispatch","INVALID_PREPARED_CALL");return S=!0,this.streamWithRegistration(T,{registration:h,config:x,modelInfo:g,dispatch:a(A=>m.stream(A),"dispatch")})},"stream")})}registration(o){let l=this.adapters.get(o);if(!l)throw new ht(`no adapter registered for provider "${o}"`,"NO_ADAPTER");return l}forAdapter(o,l){let c=o.messages.map(d=>{if(d.role!=="assistant")return d;let p=d.source;return p.replayState===void 0||this.adapters.get(p.provider)?.adapter===l?d:kh({...d,source:{kind:"model",provider:p.provider,model:p.model}})});if(c.every((d,p)=>d===o.messages[p]))return o;let u={...o,messages:c};return Object.isFrozen(o)?Ln(u):u}fileReadPath(o){let l;try{l=this.ctx.get("attachments")?.fileHostPath(o)}catch{return}if(l!==void 0)return this.ctx.get("fs")?.processPathFromHostPath(l)}async*adapterStream(o,l){let c;try{let d=l?.registration??this.registration(o.provider),p=d.adapter,h,m,g;if(l===void 0){let _=await p.prepareCall(o.provider,o.model,o.signal);h=this.normalizeModelInfo(d,o.model,_.model),m=this.resolveCallWithInfo(o,h).config,g=a(S=>_.stream(S),"dispatch")}else h=l.modelInfo,m=l.config,g=l.dispatch;if(l!==void 0&&!aR(o,m))throw new ht("prepared LLM call config changed before adapter dispatch","INVALID_PREPARED_CALL");let y=aR(o,m)?o:Object.isFrozen(o)?Ln({...o,...m}):{...o,...m},v=y.messages;v.some(_=>fOe(_.content))&&(v=yjt(v,_=>this.fileReadPath(_))),h.inputModalities!==void 0&&!h.inputModalities.includes("image")&&v.some(_=>Id(_.content))&&(v=Sjt(v));let x=Ejt(v,y.tools,h.toolUpdate,y.toolHistory);v=x.messages;let b=y;(v!==y.messages||x.tools!==y.tools)&&(b={...y,messages:v,...x.tools===void 0?{}:{tools:x.tools}},Object.isFrozen(y)&&Ln(b)),c=g(this.forAdapter(b,p))[Symbol.asyncIterator]()}catch(d){yield tOe(d,o.signal);return}let u=!1;try{for(;;){let d;try{let p=await c.next();d=p.done?{done:!0}:{done:!1,value:p.value}}catch(p){u=!0,yield tOe(p,o.signal);return}if(d.done){u=!0;return}yield d.value}}finally{if(!u){let d=c.return?.bind(c);d&&await d()}}}stream(o){return this.streamWithRegistration(o)}streamWithRegistration(o,l){return this.ctx.waterfall(this,"llm/stream",o,()=>this.adapterStream(o,l))}}})();a(tOe,"adapterFailureChunk");a(nOe,"detachDirectoryEntry")});function _Oe(e,t){for(let n=t;n!==void 0;n=E_.get(n))if(n===e)throw new Error("dsh-scope: scope parent link would form a cycle");E_.set(e,t)}function Vne(e,t){if(E_.has(e))throw new Error("dsh-scope: scope key is already bound to a parent; re-linking requires the binding returned by the original bind");return _Oe(e,t),{rebind(n){_Oe(e,n)}}}function TOe(e){return E_.get(e)}function hR(e){let t=[];for(let n=e;n!==void 0;n=E_.get(n))t.push(n);return t}async function Njt(e){for(await Promise.resolve(e.dispose());e.inertia!==void 0;)await e.inertia}function Djt(){}function Pv(e,t,n){n?.parent!==void 0&&Vne(t,n.parent);let r=e.plugin(Djt),i=r.ctx.extend({[EOe]:t}),s;return{ctx:i,rawDispose:r.dispose,dispose:a(()=>s??=Njt(r),"dispose")}}function Il(e){return e[EOe]}function Rl(e,t){let n=e[Es.filter],r={[Es.filter](i){if(n!==void 0&&!n.call(e,i))return!1;let s=Il(i);if(s===void 0)return!0;for(let o=t;o!==void 0;o=E_.get(o))if(o===s)return!0;return!1}};return Gne.set(r,t),r}function $jt(e){return typeof e=="object"&&e!==null&&Gne.has(e)}function AOe(e){if($jt(e))return Gne.get(e)}var Sh,w1,_h,EOe,Gne,E_,vc=F(()=>{mr();Sh=class{static{a(this,"NamedEntries")}duplicateError;data=new Map;constructor(e){this.duplicateError=e}insert(e,t){let n=this.data;if(n.has(e))throw this.duplicateError(e);n.set(e,t);let r=!0;return()=>{r&&(r=!1,n.delete(e),n.size===0&&this.data===n&&(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}},w1=class{static{a(this,"AnonymousEntries")}data=new Map;append(e){let t=this.data,n=Symbol();t.set(n,e);let r=!0;return()=>{r&&(r=!1,t.delete(n),t.size===0&&this.data===t&&(this.data=new Map))}}values(){return this.data.values()}isEmpty(){return this.data.size===0}},_h=class{static{a(this,"ScopedLayers")}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 n of hR(e).reverse()){let r=this.scoped.get(n);r!==void 0&&t.push(r)}return t}merge(e,t){let n=new Map(t(this.global).entries());for(let r of this.chainLayers(e))for(let[i,s]of t(r).entries())n.set(i,s);return n}effect(e,t,n){let r=Il(e),i=n.notify??!0;return e.effect(function*(){let s,o=!1;if(r===void 0)s=this.global;else{let c=this.scoped.get(r);c===void 0?(s=this.createLayer(r),this.scoped.set(r,s),o=!0):s=c}let l;try{l=t(s)}catch(c){throw r!==void 0&&o&&s.isEmpty()&&this.scoped.delete(r),c}yield()=>{l(),r!==void 0&&s.isEmpty()&&this.scoped.delete(r),i&&this.onChange()},i&&this.onChange()}.bind(this),n.label)}},EOe=Symbol("dsh.scope"),Gne=new WeakMap,E_=new WeakMap;a(_Oe,"linkScopeParent");a(Vne,"bindScopeParent");a(TOe,"scopeParentOf");a(hR,"scopeChainOf");a(Njt,"quiesceFiber");a(Djt,"scope");a(Pv,"createScope");a(Il,"scopeOf");a(Rl,"scopeTarget");a($jt,"isScopeCarrier");a(AOe,"carrierKeyOf")});import{accessSync as kTr,constants as STr,realpathSync as _Tr,statSync as ETr}from"node:fs";import{tmpdir as ATr}from"node:os";function nL(e,t){if(e!==void 0&&t===void 0)throw new Error("invalid escalation: sandbox_permissions requires a justification");if(t!==void 0&&e===void 0)throw new Error("invalid escalation: justification is only valid together with sandbox_permissions");if(t!==void 0&&t.trim().length===0)throw new Error("invalid justification: expected a non-empty sentence")}function IOe(e){return`[sandbox: file access denied under ${e} mode]`}function ROe(e){return`[sandbox: escalation available \u2014 retry this exact ${e} once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]`}function COe(e){return`The narrowest wider sandbox mode for a one-shot retry of the exact ${e} the sandbox just denied; the retry asks the user for approval.`}async function rL(e,t){let{requestedMode:n,effectiveMode:r,justification:i,subject:s}=e;if(n===r)return r;if(!(Ljt[r]??[]).includes(n))throw new Error(`sandbox escalation to "${n}" is not strictly wider than this call's current "${r}" mode`);if(t.approver===void 0)throw new Error(`sandbox escalation to "${n}" requires approval, but no approval service is composed`);if(t.agent===void 0)throw new Error(`sandbox escalation to "${n}" requires approval, but the call has no agent to route it through`);let o=await t.approver.request({agent:t.agent,toolName:t.toolName,callId:t.callId,reason:`escalate sandbox to ${n}: ${i}`,displayReason:{en:`Allow this operation with ${n} permissions: ${i}`,zh:`\u5141\u8BB8\u672C\u6B21\u64CD\u4F5C\u4F7F\u7528 ${n} \u6743\u9650\uFF1A${i}`},...t.signal?{signal:t.signal}:{}});switch(o){case"allowed-once":return n;case"rejected":throw new Error(`the user rejected escalating this ${s} to "${n}"; it stays denied, so stop and explain instead of working around it`);case"cancelled":throw new Error(`approval for escalating to "${n}" was cancelled`);case"unavailable":throw new Error(`sandbox escalation to "${n}" requires approval, but no approval channel is available`);default:return Ar(o,"EscalationOutcome")}}var Ljt,tL,Kne=F(()=>{mr();Nr();ps();Ljt={"read-only":["workspace-write","danger-full-access"],"workspace-write":["danger-full-access"]},tL=["workspace-write","danger-full-access"];a(nL,"validateEscalationArgs");a(IOe,"sandboxDenialMarker");a(ROe,"escalationHintMarker");a(COe,"sandboxPermissionsDescription");a(rL,"approveEscalation")});function QOe(e,t){let n=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(typeof n!="function")return!1;try{return n.name===t&&n.prototype===e&&Function.prototype.toString.call(n)===`function ${t}() { [native code] }`}catch{return!1}}function JOe(e){return Object.getPrototypeOf(e)===null&&QOe(e,"Object")}function XOe(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&JOe(t)}catch{return!1}}function Ujt(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!QOe(t,"Array"))return!1;let n=Object.getPrototypeOf(t);return typeof n=="object"&&n!==null&&JOe(n)}function qjt(e){try{return Reflect.ownKeys(e).every(t=>typeof t=="string"&&Object.prototype.propertyIsEnumerable.call(e,t))}catch{return!1}}function mw(e){return XOe(e)&&qjt(e)}function vR(e){if(!Array.isArray(e))return!1;try{if(!Ujt(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 aL(e){return typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0)}function POe(e,t){switch(e){case"string":return typeof t=="string";case"number":return aL(t);case"integer":return aL(t)&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;default:return Ar(e,"JsonSchemaType")}}function Wjt(e,t,n,r){let i=Object.hasOwn(e,"required"),s=i?e.required:void 0;if(i)if(!vR(s)||s.some(o=>typeof o!="string"))r.push(`${t}.required must be an array of strings`);else{let o=mw(n)?n:{};for(let l of s)Object.hasOwn(o,l)||r.push(`${t}.required names "${l}" which is not in properties`)}Object.hasOwn(e,"additionalProperties")&&typeof e.additionalProperties!="boolean"&&r.push(`${t}.additionalProperties must be a boolean`)}function YOe(e,t,n,r){let i=[{kind:"enter",node:e,path:t}];for(let s=i.pop();s!==void 0;s=i.pop()){if(s.kind==="leave"){r.delete(s.node);continue}if(s.kind==="one-of-tail"){for(let h of OOe)Object.hasOwn(s.node,h)&&n.push(`${s.path}.${h} is not supported beside oneOf`);continue}if(s.kind==="object-tail"){Wjt(s.node,s.path,s.properties,n);continue}let{node:o,path:l}=s;if(!mw(o)){n.push(`${l} must be a schema object`);continue}if(r.has(o)){n.push(`${l} is circular`);continue}r.add(o),i.push({kind:"leave",node:o});for(let h of Object.keys(o))if(!jjt.has(h)){if(Fjt.has(h)){try{b1(o[h])||n.push(`${l}.${h} annotation must be lossless JSON data`)}catch{n.push(`${l}.${h} annotation must be lossless JSON data`)}continue}n.push(`${l}.${h} is not a supported keyword (subset: type/oneOf/properties/required/additionalProperties/items/enum/const + annotations)`)}Object.hasOwn(o,"description")&&typeof o.description!="string"&&n.push(`${l}.description must be a string`),Object.hasOwn(o,"title")&&typeof o.title!="string"&&n.push(`${l}.title must be a string`);let c=Object.hasOwn(o,"type"),u=Object.hasOwn(o,"oneOf");if(c&&u){n.push(`${l} cannot declare both type and oneOf`);continue}if(!c&&!u){for(let h of OOe)Object.hasOwn(o,h)&&n.push(`${l}.${h} requires type or oneOf`);continue}if(u){let h=o.oneOf;if(i.push({kind:"one-of-tail",node:o,path:l}),!vR(h)||h.length<2)n.push(`${l}.oneOf must be an array of at least two schemas`);else for(let m=h.length-1;m>=0;m--)i.push({kind:"enter",node:h[m],path:`${l}.oneOf[${m}]`});continue}let d=o.type;if(typeof d!="string"||!tre.includes(d)){n.push(Array.isArray(d)?`${l}.type must be a single type string (type arrays are not supported)`:`${l}.type must be one of ${tre.join("/")}`);continue}let p=d;for(let[h,m]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(o,h)&&!m.includes(p)&&n.push(`${l}.${h} is not supported on type "${p}"`);switch(p){case"object":{let h=Object.hasOwn(o,"properties")?o.properties:void 0;if(i.push({kind:"object-tail",node:o,path:l,properties:h}),Object.hasOwn(o,"properties"))if(!mw(h))n.push(`${l}.properties must be an object of schemas`);else{let m=Object.entries(h);for(let g=m.length-1;g>=0;g--){let y=m[g];y!==void 0&&i.push({kind:"enter",node:y[1],path:`${l}.properties.${y[0]}`})}}break}case"array":Object.hasOwn(o,"items")&&i.push({kind:"enter",node:o.items,path:`${l}.items`});break;case"string":case"number":case"integer":case"boolean":case"null":{let h=Object.hasOwn(o,"enum"),m=h?o.enum:void 0,g=vR(m)&&m.length>0&&m.every(b=>POe(p,b));h&&!g&&n.push(`${l}.enum must be a non-empty array of ${p} values`);let y=Object.hasOwn(o,"const"),v=y?o.const:void 0,x=POe(p,v);y&&(x?g&&!m.includes(v)&&n.push(`${l}.const must be one of ${l}.enum when both are declared`):n.push(`${l}.const must be a ${p} value`));break}default:Ar(p,"JsonSchemaType")}}}function gw(e){let t=[];if(YOe(e,"schema",t,new Set),t.length>0)throw new wR(t)}function cL(e){let t=[];if(YOe(e,"schema",t,new Set),t.length===0&&(!mw(e)||!Object.hasOwn(e,"type")||e.type!=="object")&&t.push('schema.type must be "object" (structured output is object-rooted)'),t.length>0)throw new wR(t)}function Qne(e){try{return b1(e)}catch{return!1}}function Rd(e){return e===""?"arguments":e}function Jne(e,t){return e===""?t:`${e}.${t}`}function Xne(e){return[`"${Rd(e)}" must be a lossless JSON value`]}function MOe(e,t){for(let n of t)e.push(n)}function NOe(e,t,n){return{node:e,value:t,path:n,catches:!1,phase:"start",children:[],childIndex:0,violations:[],tailViolations:[],matches:0}}function mR(e,t,n){let r=Object.hasOwn(e,"enum")?e.enum:void 0;return r!==void 0&&!r.includes(t)?[`"${Rd(n)}" must be one of ${JSON.stringify(r)}`]:Object.hasOwn(e,"const")&&t!==e.const?[`"${Rd(n)}" must be ${JSON.stringify(e.const)}`]:[]}function Bjt(e,t,n){let r=[NOe(e,t,n)],i,s=a(l=>{let c=r.at(-1);if(c===void 0){i=l;return}c.kind==="oneOf"?l.length===0&&c.matches++:MOe(c.violations,l)},"receive"),o=a(l=>{r.pop(),s(l)},"finish");for(;r.length>0;){let l=r.at(-1);if(l===void 0)break;try{if(l.phase==="children"){if(l.childIndex<l.children.length){let d=l.children[l.childIndex];if(d===void 0)throw new Error("missing schema-value child frame");l.childIndex++,r.push(NOe(d.node,d.value,d.path));continue}if(l.kind==="oneOf"){o(l.matches===1?[]:[`"${Rd(l.path)}" must match exactly one oneOf branch (matched ${l.matches})`]);continue}MOe(l.violations,l.tailViolations),l.violations.length>0?o(l.violations):l.kind==="object"?o(Qne(l.value)?[]:[`"${Rd(l.path)}" must be a lossless JSON object`]):o(Qne(l.value)?[]:[`"${Rd(l.path)}" must be a dense lossless JSON array`]);continue}let c=Object.hasOwn(l.node,"type")?l.node.type:void 0;l.catches=!(c!==void 0&&!tre.includes(c));let u=Object.hasOwn(l.node,"oneOf")?l.node.oneOf:void 0;if(u!==void 0){l.kind="oneOf",l.children=Array.from(u,d=>({node:d,value:l.value,path:l.path})),l.childIndex=0,l.matches=0,l.phase="children";continue}if(c===void 0){o(Qne(l.value)?[]:Xne(l.path));continue}switch(c){case"object":{if(!XOe(l.value)){o([`"${Rd(l.path)}" must be an object`]);break}let d=Object.hasOwn(l.node,"properties")?l.node.properties??{}:{},p=[],h=Object.hasOwn(l.node,"required")?l.node.required??[]:[];for(let y of h)(!Object.hasOwn(l.value,y)||l.value[y]===void 0)&&p.push(`missing required property "${Jne(l.path,y)}"`);let m=[];for(let[y,v]of Object.entries(d))!Object.hasOwn(l.value,y)||l.value[y]===void 0||m.push({node:v,value:l.value[y],path:Jne(l.path,y)});let g=[];if(Object.hasOwn(l.node,"additionalProperties")&&l.node.additionalProperties===!1)for(let y of Object.keys(l.value))Object.hasOwn(d,y)||g.push(`"${Jne(l.path,y)}" is not a declared property (additionalProperties: false)`);l.kind="object",l.children=m,l.childIndex=0,l.violations=p,l.tailViolations=g,l.phase="children";break}case"array":{if(!Array.isArray(l.value)){o([`"${Rd(l.path)}" must be an array`]);break}let d=Object.hasOwn(l.node,"items")?l.node.items:void 0,p=d===void 0?[]:l.value.flatMap((h,m)=>[{node:d,value:h,path:`${l.path}[${m}]`}]);l.kind="array",l.children=p,l.childIndex=0,l.violations=[],l.phase="children";break}case"string":o(typeof l.value=="string"?mR(l.node,l.value,l.path):[`"${Rd(l.path)}" must be a string`]);break;case"number":o(typeof l.value!="number"?[`"${Rd(l.path)}" must be a number`]:aL(l.value)?mR(l.node,l.value,l.path):[`"${Rd(l.path)}" must be a finite JSON number`]);break;case"integer":o(!aL(l.value)||!Number.isInteger(l.value)?[`"${Rd(l.path)}" must be an integer`]:mR(l.node,l.value,l.path));break;case"boolean":o(typeof l.value=="boolean"?mR(l.node,l.value,l.path):[`"${Rd(l.path)}" must be a boolean`]);break;case"null":o(l.value===null?mR(l.node,l.value,l.path):[`"${Rd(l.path)}" must be null`]);break;default:o(Ar(c,"JsonSchemaType"))}}catch(c){let u=r.pop();for(;u!==void 0&&!u.catches;)u=r.pop();if(u===void 0)throw c;s(Xne(u.path))}}return i??Xne(n)}function uL(e,t,n="value"){return Bjt(e,t,n)}function Cd(e){throw new wR([e])}function fR(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 gR(e,t,n){for(let r of Object.keys(e))n.includes(r)||Cd(`${t}.${r} is not supported by the value schema DSL`)}function Hjt(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 Gjt(e,t){e.kind==="root"?e.holder.value=t:e.target.properties=t.properties}function ZOe(e){let t=new Set,n=[e];for(let r=n.pop();r!==void 0;r=n.pop()){if(r.kind==="leave"){t.delete(r.input);continue}if(r.kind==="property-map-tail"){r.required.length>0&&(r.compiled.required=r.required,r.destination.kind==="object"&&(r.destination.target.required=r.required));continue}if(r.kind==="property"){mw(r.property)||Cd(`${r.path} must be a value schema object`),Object.hasOwn(r.property,"required")&&r.property.required!==!0&&Cd(`${r.path}.required must be true when present`),Object.hasOwn(r.property,"required")&&r.property.required===!0&&r.required.push(r.key),n.push({kind:"value",input:r.property,path:r.path,allowRequired:!0,destination:{kind:"property",target:r.properties,key:r.key}});continue}if(r.kind==="property-map"){mw(r.input)||Cd(`${r.path} must be an object of value schemas`),t.has(r.input)&&Cd(`${r.path} is circular`),t.add(r.input);let u={properties:{}},d=[];Gjt(r.destination,u),n.push({kind:"leave",input:r.input}),n.push({kind:"property-map-tail",compiled:u,required:d,destination:r.destination});let p=Object.entries(r.input);for(let h=p.length-1;h>=0;h--){let m=p[h];m!==void 0&&n.push({kind:"property",property:m[1],path:`${r.path}.${m[0]}`,key:m[0],properties:u.properties,required:d})}continue}let{input:i,path:s}=r;mw(i)||Cd(`${s} must be a value schema object`),t.has(i)&&Cd(`${s} is circular`),t.add(i);let o=[...zjt,...r.allowRequired?["required"]:[]],l={};if(Hjt(r.destination,l),n.push({kind:"leave",input:i}),Object.hasOwn(i,"oneOf")){gR(i,s,[...o,"oneOf","type"]),Object.hasOwn(i,"type")&&Cd(`${s} cannot declare both type and oneOf`),vR(i.oneOf)||Cd(`${s}.oneOf must be an array of at least two value schemas`);let u=[];l.oneOf=u,fR(i,l);for(let d=i.oneOf.length-1;d>=0;d--)n.push({kind:"value",input:i.oneOf[d],path:`${s}.oneOf[${d}]`,allowRequired:!1,destination:{kind:"one-of",target:u,index:d}});continue}let c=Object.hasOwn(i,"type")?i.type:void 0;switch(c){case"json":gR(i,s,[...o,"type"]),fR(i,l);break;case"object":gR(i,s,[...o,"type","properties","additionalProperties"]),(!Object.hasOwn(i,"additionalProperties")||typeof i.additionalProperties!="boolean")&&Cd(`${s}.additionalProperties must be explicitly true or false`),l.type="object",fR(i,l),l.additionalProperties=i.additionalProperties,Object.hasOwn(i,"properties")&&n.push({kind:"property-map",input:i.properties,path:`${s}.properties`,destination:{kind:"object",target:l}});break;case"array":gR(i,s,[...o,"type","items"]),l.type="array",fR(i,l),Object.hasOwn(i,"items")&&n.push({kind:"value",input:i.items,path:`${s}.items`,allowRequired:!1,destination:{kind:"item",target:l}});break;case"string":case"number":case"integer":case"boolean":case"null":gR(i,s,[...o,"type","enum","const"]),l.type=c,fR(i,l),Object.hasOwn(i,"enum")&&(vR(i.enum)||Cd(`${s}.enum must be a non-empty array of scalar values`),l.enum=Array.from(i.enum,u=>u)),Object.hasOwn(i,"const")&&(l.const=i.const);break;default:Cd(`${s}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`)}}}function Vjt(e,t){let n={};return ZOe({kind:"property-map",input:e,path:t,destination:{kind:"root",holder:n}}),n.value??Cd(`${t} did not compile`)}function Kjt(e,t){let n={};return ZOe({kind:"value",input:e,path:t,allowRequired:!1,destination:{kind:"root",holder:n}}),n.value??Cd(`${t} did not compile`)}function Qjt(e){let t=Kjt(e,"schema");return gw(t),t}function eMe(e){let t=Vjt(e,"parameters"),n={type:"object",properties:t.properties,...t.required===void 0?{}:{required:t.required}};return gw(n),n}function Fn(e){let t=e.execute,n=e.finalizeContent,r=e.projectContent,i=e.output.render,s=e.output.presentationMeta,o=e.presentCall,l=e.presentResult,c=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 u=eMe(e.parameters),d=Qjt(e.output.schema),p=a(m=>uL(u,m,""),"validate"),h={name:e.name,description:e.description,parameters:u,output:{schema:d,render(m,g){return i(m,g)},...s!==void 0?{presentationMeta(m,g){return s(m,g)}}:{}},...e.deferLoading===!0?{deferLoading:e.deferLoading}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},async execute(m,g){let y=p(m);if(y.length>0)throw new ore(y);return t(m,g)}};return r&&(h.projectContent=(m,g)=>r(m,g)),n&&(h.finalizeContent=(m,g)=>n(m,g)),o&&(h.presentCall=m=>{if(!(p(m).length>0))return o(m)}),l&&(h.presentResult=(m,g)=>{if(!(p(m).length>0))return l(m,g)}),c&&(h.isConcurrencySafe=m=>p(m).length>0?!1:c(m)),h}function are(e,t={programDescription:"the program to execute",outputInstruction:"Curate the program output.",codeDescription:`The ${e} program to execute, following this tool's execution instructions.`}){return{description:`Execute a ${e} program against the available tools. Takes two required arguments: \`code\`, ${t.programDescription}, and \`description\`, a short summary of what the program does. Call tools as \`await tools.name(args)\` per the declarations in the system prompt. ${t.outputInstruction} Image-bearing subtool results are attached after the run.`,codeDescription:t.codeDescription}}function Yjt(e){return e===void 0?yR:{...e.timeout===void 0?{}:{timeoutMs:{...yR.timeoutMs,description:`Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default ${e.timeout.defaultMs}; capped at ${e.timeout.maxMs}. Zero does not disable the deadline.`}},...e.sandboxMode===void 0?{}:{sandbox_permissions:yR.sandbox_permissions,justification:yR.justification}}}function Zne(e){return e?.sandboxMode===void 0?"":" A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically."}function $Oe(e){let t=e();if(t===void 0)return lL;let n=Yne[t.language];if(!Object.hasOwn(Yne,t.language)||n===void 0){let r=Object.keys(Yne).map(i=>JSON.stringify(i)).join(", ");throw new Error(`dsh-tools: no run_code schema flavor registered for runtime language ${JSON.stringify(t.language)} (known: ${r})`)}return t.language==="typescript"&&t.programFormat==="function-body"?Xjt:n}function eFt(e){let t;try{t=js(e)}catch(r){throw new Error(`tool arguments must be lossless JSON: ${r instanceof Error?r.message:String(r)}`)}if(t===void 0)throw new Error("tool arguments must be lossless JSON (call the tool with an arguments object, e.g. `{}`)");let n=js(t);if(n===void 0)throw new Error("tool arguments could not be detached for durable logging");return{dispatched:t,logged:n}}function nFt(e){let t=[],n=[{kind:"value",value:e,depth:0,compact:!1}];for(let r=n.pop();r!==void 0;r=n.pop()){if(r.kind==="text"){t.push(r.text);continue}let i=r.value;if(i===null||typeof i=="boolean"||typeof i=="number"){t.push(String(i));continue}if(typeof i=="string"){t.push(JSON.stringify(i));continue}let s=r.compact||(r.depth+1)*2>tFt,o=r.depth+1;if(Array.isArray(i)){if(t.push("["),i.length===0){t.push("]");continue}n.push({kind:"text",text:s?"]":`
15
15
  ${iL.repeat(r.depth)}]`});for(let c=i.length-1;c>=0;c--){let u=i[c];if(u===void 0)throw new Error("cannot render a sparse JSON array");n.push({kind:"value",value:u,depth:o,compact:s}),n.push({kind:"text",text:s?c===0?"":",":`${c===0?`
16
16
  `:`,
17
17
  `}${iL.repeat(o)}`})}continue}let l=Object.keys(i);if(t.push("{"),l.length===0){t.push("}");continue}n.push({kind:"text",text:s?"}":`
@@ -164,7 +164,7 @@ Known schemas:
164
164
  - `)}`,new Error(ot)}let Ot=`${l}/$ref`,vt=Zo(e,Ve,n,r,i,s,o,Ot,c);if(vt.valid||Oe.push({instanceLocation:o,keyword:"$ref",keywordLocation:Ot,error:"A subschema had errors."},...vt.errors),n==="4"||n==="7")return{valid:Oe.length===0,errors:Oe}}if(Array.isArray(g)){let et=g.length,Ve=!1;for(let Ot=0;Ot<et;Ot++)if(d===g[Ot]||g[Ot]==="integer"&&d==="number"&&e%1===0&&e===e){Ve=!0;break}Ve||Oe.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${g.join('", "')}".`})}else g==="integer"?(d!=="number"||e%1||e!==e)&&Oe.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`}):g!==void 0&&d!==g&&Oe.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`});if(y!==void 0&&(d==="object"||d==="array"?m4(e,y)||Oe.push({instanceLocation:o,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&Oe.push({instanceLocation:o,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),v!==void 0&&(d==="object"||d==="array"?v.some(et=>m4(e,et))||Oe.push({instanceLocation:o,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(et=>e===et)||Oe.push({instanceLocation:o,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),b!==void 0){let et=`${l}/not`;Zo(e,b,n,r,i,s,o,et).valid&&Oe.push({instanceLocation:o,keyword:"not",keywordLocation:et,error:'Instance matched "not" schema.'})}let kt=[];if(_!==void 0){let et=`${l}/anyOf`,Ve=Oe.length,Ot=!1;for(let vt=0;vt<_.length;vt++){let ot=_[vt],Ct=Object.create(c),Ue=Zo(e,ot,n,r,i,m===!0?s:null,o,`${et}/${vt}`,Ct);Oe.push(...Ue.errors),Ot=Ot||Ue.valid,Ue.valid&&kt.push(Ct)}Ot?Oe.length=Ve:Oe.splice(Ve,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:et,error:"Instance does not match any subschemas."})}if(S!==void 0){let et=`${l}/allOf`,Ve=Oe.length,Ot=!0;for(let vt=0;vt<S.length;vt++){let ot=S[vt],Ct=Object.create(c),Ue=Zo(e,ot,n,r,i,m===!0?s:null,o,`${et}/${vt}`,Ct);Oe.push(...Ue.errors),Ot=Ot&&Ue.valid,Ue.valid&&kt.push(Ct)}Ot?Oe.length=Ve:Oe.splice(Ve,0,{instanceLocation:o,keyword:"allOf",keywordLocation:et,error:"Instance does not match every subschema."})}if(T!==void 0){let et=`${l}/oneOf`,Ve=Oe.length,Ot=T.filter((vt,ot)=>{let Ct=Object.create(c),Ue=Zo(e,vt,n,r,i,m===!0?s:null,o,`${et}/${ot}`,Ct);return Oe.push(...Ue.errors),Ue.valid&&kt.push(Ct),Ue.valid}).length;Ot===1?Oe.length=Ve:Oe.splice(Ve,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:et,error:`Instance does not match exactly one subschema (${Ot} matches).`})}if((d==="object"||d==="array")&&Object.assign(c,...kt),A!==void 0){let et=`${l}/if`;if(Zo(e,A,n,r,i,s,o,et,c).valid){if(R!==void 0){let Ot=Zo(e,R,n,r,i,s,o,`${l}/then`,c);Ot.valid||Oe.push({instanceLocation:o,keyword:"if",keywordLocation:et,error:'Instance does not match "then" schema.'},...Ot.errors)}}else if(M!==void 0){let Ot=Zo(e,M,n,r,i,s,o,`${l}/else`,c);Ot.valid||Oe.push({instanceLocation:o,keyword:"if",keywordLocation:et,error:'Instance does not match "else" schema.'},...Ot.errors)}}if(d==="object"){if(x!==void 0)for(let vt of x)vt in e||Oe.push({instanceLocation:o,keyword:"required",keywordLocation:`${l}/required`,error:`Instance does not have required property "${vt}".`});let et=Object.keys(e);if(I!==void 0&&et.length<I&&Oe.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${l}/minProperties`,error:`Instance does not have at least ${I} properties.`}),V!==void 0&&et.length>V&&Oe.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${l}/maxProperties`,error:`Instance does not have at least ${V} properties.`}),P!==void 0){let vt=`${l}/propertyNames`;for(let ot in e){let Ct=`${o}/${jp(ot)}`,Ue=Zo(ot,P,n,r,i,s,Ct,vt);Ue.valid||Oe.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:vt,error:`Property name "${ot}" does not match schema.`},...Ue.errors)}}if(O!==void 0){let vt=`${l}/dependantRequired`;for(let ot in O)if(ot in e){let Ct=O[ot];for(let Ue of Ct)Ue in e||Oe.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:vt,error:`Instance has "${ot}" but does not have "${Ue}".`})}}if(U!==void 0)for(let vt in U){let ot=`${l}/dependentSchemas`;if(vt in e){let Ct=Zo(e,U[vt],n,r,i,s,o,`${ot}/${jp(vt)}`,c);Ct.valid||Oe.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:ot,error:`Instance has "${vt}" but does not match dependant schema.`},...Ct.errors)}}if(D!==void 0){let vt=`${l}/dependencies`;for(let ot in D)if(ot in e){let Ct=D[ot];if(Array.isArray(Ct))for(let Ue of Ct)Ue in e||Oe.push({instanceLocation:o,keyword:"dependencies",keywordLocation:vt,error:`Instance has "${ot}" but does not have "${Ue}".`});else{let Ue=Zo(e,Ct,n,r,i,s,o,`${vt}/${jp(ot)}`);Ue.valid||Oe.push({instanceLocation:o,keyword:"dependencies",keywordLocation:vt,error:`Instance has "${ot}" but does not match dependant schema.`},...Ue.errors)}}}let Ve=Object.create(null),Ot=!1;if(j!==void 0){let vt=`${l}/properties`;for(let ot in j){if(!(ot in e))continue;let Ct=`${o}/${jp(ot)}`,Ue=Zo(e[ot],j[ot],n,r,i,s,Ct,`${vt}/${jp(ot)}`);if(Ue.valid)c[ot]=Ve[ot]=!0;else if(Ot=i,Oe.push({instanceLocation:o,keyword:"properties",keywordLocation:vt,error:`Property "${ot}" does not match schema.`},...Ue.errors),Ot)break}}if(!Ot&&$!==void 0){let vt=`${l}/patternProperties`;for(let ot in $){let Ct=new RegExp(ot,"u"),Ue=$[ot];for(let qt in e){if(!Ct.test(qt))continue;let hn=`${o}/${jp(qt)}`,Tt=Zo(e[qt],Ue,n,r,i,s,hn,`${vt}/${jp(ot)}`);Tt.valid?c[qt]=Ve[qt]=!0:(Ot=i,Oe.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:vt,error:`Property "${qt}" matches pattern "${ot}" but does not match associated schema.`},...Tt.errors))}}}if(!Ot&&H!==void 0){let vt=`${l}/additionalProperties`;for(let ot in e){if(Ve[ot])continue;let Ct=`${o}/${jp(ot)}`,Ue=Zo(e[ot],H,n,r,i,s,Ct,vt);Ue.valid?c[ot]=!0:(Ot=i,Oe.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:vt,error:`Property "${ot}" does not match additional properties schema.`},...Ue.errors))}}else if(!Ot&&ne!==void 0){let vt=`${l}/unevaluatedProperties`;for(let ot in e)if(!c[ot]){let Ct=`${o}/${jp(ot)}`,Ue=Zo(e[ot],ne,n,r,i,s,Ct,vt);Ue.valid?c[ot]=!0:Oe.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:vt,error:`Property "${ot}" does not match unevaluated properties schema.`},...Ue.errors)}}}else if(d==="array"){ce!==void 0&&e.length>ce&&Oe.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${l}/maxItems`,error:`Array has too many items (${e.length} > ${ce}).`}),he!==void 0&&e.length<he&&Oe.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${l}/minItems`,error:`Array has too few items (${e.length} < ${he}).`});let et=e.length,Ve=0,Ot=!1;if(q!==void 0){let vt=`${l}/prefixItems`,ot=Math.min(q.length,et);for(;Ve<ot;Ve++){let Ct=Zo(e[Ve],q[Ve],n,r,i,s,`${o}/${Ve}`,`${vt}/${Ve}`);if(c[Ve]=!0,!Ct.valid&&(Ot=i,Oe.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:vt,error:"Items did not match schema."},...Ct.errors),Ot))break}}if(Q!==void 0){let vt=`${l}/items`;if(Array.isArray(Q)){let ot=Math.min(Q.length,et);for(;Ve<ot;Ve++){let Ct=Zo(e[Ve],Q[Ve],n,r,i,s,`${o}/${Ve}`,`${vt}/${Ve}`);if(c[Ve]=!0,!Ct.valid&&(Ot=i,Oe.push({instanceLocation:o,keyword:"items",keywordLocation:vt,error:"Items did not match schema."},...Ct.errors),Ot))break}}else for(;Ve<et;Ve++){let ot=Zo(e[Ve],Q,n,r,i,s,`${o}/${Ve}`,vt);if(c[Ve]=!0,!ot.valid&&(Ot=i,Oe.push({instanceLocation:o,keyword:"items",keywordLocation:vt,error:"Items did not match schema."},...ot.errors),Ot))break}if(!Ot&&Y!==void 0){let ot=`${l}/additionalItems`;for(;Ve<et;Ve++){let Ct=Zo(e[Ve],Y,n,r,i,s,`${o}/${Ve}`,ot);c[Ve]=!0,Ct.valid||(Ot=i,Oe.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:ot,error:"Items did not match additional items schema."},...Ct.errors))}}}if(G!==void 0)if(et===0&&re===void 0)Oe.push({instanceLocation:o,keyword:"contains",keywordLocation:`${l}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(re!==void 0&&et<re)Oe.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array has less items (${et}) than minContains (${re}).`});else{let vt=`${l}/contains`,ot=Oe.length,Ct=0;for(let Ue=0;Ue<et;Ue++){let qt=Zo(e[Ue],G,n,r,i,s,`${o}/${Ue}`,vt);qt.valid?(c[Ue]=!0,Ct++):Oe.push(...qt.errors)}Ct>=(re||0)&&(Oe.length=ot),re===void 0&&be===void 0&&Ct===0?Oe.splice(ot,0,{instanceLocation:o,keyword:"contains",keywordLocation:vt,error:"Array does not contain item matching schema."}):re!==void 0&&Ct<re?Oe.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array must contain at least ${re} items matching schema. Only ${Ct} items were found.`}):be!==void 0&&Ct>be&&Oe.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${l}/maxContains`,error:`Array may contain at most ${be} items matching schema. ${Ct} items were found.`})}if(!Ot&&ee!==void 0){let vt=`${l}/unevaluatedItems`;for(Ve;Ve<et;Ve++){if(c[Ve])continue;let ot=Zo(e[Ve],ee,n,r,i,s,`${o}/${Ve}`,vt);c[Ve]=!0,ot.valid||Oe.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:vt,error:"Items did not match unevaluated items schema."},...ot.errors)}}if(Te)for(let vt=0;vt<et;vt++){let ot=e[vt],Ct=typeof ot=="object"&&ot!==null;for(let Ue=0;Ue<et;Ue++){if(vt===Ue)continue;let qt=e[Ue];(ot===qt||Ct&&(typeof qt=="object"&&qt!==null)&&m4(ot,qt))&&(Oe.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${l}/uniqueItems`,error:`Duplicate items at indexes ${vt} and ${Ue}.`}),vt=Number.MAX_SAFE_INTEGER,Ue=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(n==="4"?(Ie!==void 0&&(de===!0&&e<=Ie||e<Ie)&&Oe.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${de?"or equal to ":""} ${Ie}.`}),me!==void 0&&(Ze===!0&&e>=me||e>me)&&Oe.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${Ze?"or equal to ":""} ${me}.`})):(Ie!==void 0&&e<Ie&&Oe.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${Ie}.`}),me!==void 0&&e>me&&Oe.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${me}.`}),de!==void 0&&e<=de&&Oe.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${l}/exclusiveMinimum`,error:`${e} is less than ${de}.`}),Ze!==void 0&&e>=Ze&&Oe.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${l}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ze}.`})),Xe!==void 0){let et=e%Xe;Math.abs(0-et)>=11920929e-14&&Math.abs(Xe-et)>=11920929e-14&&Oe.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${l}/multipleOf`,error:`${e} is not a multiple of ${Xe}.`})}}else if(d==="string"){let et=gt===void 0&&je===void 0?0:qGe(e);gt!==void 0&&et<gt&&Oe.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${l}/minLength`,error:`String is too short (${et} < ${gt}).`}),je!==void 0&&et>je&&Oe.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${l}/maxLength`,error:`String is too long (${et} > ${je}).`}),Pe!==void 0&&!new RegExp(Pe,"u").test(e)&&Oe.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${l}/pattern`,error:"String does not match pattern."}),N!==void 0&&Afe[N]&&!Afe[N](e)&&Oe.push({instanceLocation:o,keyword:"format",keywordLocation:`${l}/format`,error:`String does not match format "${N}".`})}return{valid:Oe.length===0,errors:Oe}}var Cfe=F(()=>{Tfe();Eq();Ife();_q();Rfe();a(Zo,"validate")});var Tq,WGe=F(()=>{Eq();Cfe();Tq=class{static{a(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,n="2019-09",r=!0){this.schema=t,this.draft=n,this.shortCircuit=r,this.lookup=Z1(t)}validate(t){return Zo(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),Z1(t,this.lookup)}}});var BGe=F(()=>{Tfe();Eq();Ife();_q();UGe();Rfe();Cfe();WGe()});var Aq,zGe=F(()=>{BGe();Aq=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new Tq(t,this.draft,this.shortcircuit);return r=>{let i=n.validate(r);return i.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:i.errors.map(s=>`${s.instanceLocation}: ${s.error}`).join("; ")}}}}});var jo,Iq=F(()=>{"use strict";jo={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20,maxResourceResponseBytes:1048576}});import{createHash as zsn}from"node:crypto";function Gsn(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function Pfe(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":Hsn.some(i=>Gsn(i).test(e))?"allow":"ask"}function Fh(e){return e.replace(/Bearer\s+[^\s"']+/giu,"Bearer ***").replace(/(https?:\/\/[^\s"'?]+)\?[^\s"']*/giu,"$1?***").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/gu,"").slice(0,jo.maxErrorMessageChars)}function HGe(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=jo.maxPublicNameLength)return r;let i=Vsn(e,t),s=jo.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function Vsn(e,t){return zsn("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function GGe(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return gw(t),t}catch{return}}function Jsn(e){return Ksn.has(e)}function VGe(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!Jsn(e.mimeType)||!Qsn.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function KGe(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function j8(e){if(e.isError)return[{type:"text",text:e.content.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(`
165
165
  `)||"MCP tool returned an error."}];let t=[],n=[];for(let r of e.content)if(r.type==="text"&&typeof r.text=="string")n.push(r.text);else if(r.type==="resource_link"&&r.uri!==void 0)n.push(`Resource: ${r.name??"unnamed"} (${r.uri})`);else if(r.type==="image"&&r.data!==void 0)n.push(`![image](data:${r.mimeType??"image/png"};base64,${r.data})`);else if(r.type==="image")n.push(`[image: ${r.mimeType??"unknown type"}]`);else if(r.type==="audio")n.push("[audio result unsupported on Cloudflare Workers]");else if(r.type==="resource"&&r.resource?.text!==void 0){let i=r.resource.uri??"embedded resource";n.push(`--- ${i} ---
166
166
  ${r.resource.text}`)}else r.type==="resource"?n.push("[embedded resource: binary content not displayed]"):n.push(`[unsupported MCP content type: ${r.type}]`);return n.length>0&&t.push({type:"text",text:n.join(`
167
- `)}),t.length>0?t:[{type:"text",text:"(empty MCP result)"}]}var Hsn,Ksn,Qsn,Rq=F(()=>{"use strict";Zs();Iq();Hsn=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(Gsn,"globToRegExp");a(Pfe,"evaluateMcpToolPolicy");a(Fh,"scrubMcpErrorMessage");a(HGe,"publicToolName");a(Vsn,"hashSuffix");a(GGe,"supportedOutputSchema");Ksn=new Set(["image/png","image/jpeg"]),Qsn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Jsn,"isImageMediaType");a(VGe,"decodeImageBlock");a(KGe,"containsImage");a(j8,"mapMcpResultToContentBlocks")});var Ofe,QGe=F(()=>{Ofe={name:"dsh-edge",version:"0.33.0",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.1-rc.3"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","check:startup":"node scripts/check-startup.mjs","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0",yaml:"2.9.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.7.0","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.5","@deepseek-ai/cosmokit":"1.8.6","@deepseek-ai/dsh-agent":"0.2.1-rc.3","@deepseek-ai/dsh-agent-instructions":"0.2.1-rc.3","@deepseek-ai/dsh-agent-loop":"0.2.1-rc.3","@deepseek-ai/dsh-anonymous-user-id":"0.2.1-rc.3","@deepseek-ai/dsh-api-gateway":"0.2.1-rc.3","@deepseek-ai/dsh-api-job-controller":"0.2.1-rc.3","@deepseek-ai/dsh-api-remote-access":"0.2.1-rc.3","@deepseek-ai/dsh-api-remotes":"0.2.1-rc.3","@deepseek-ai/dsh-api-session-controller":"0.2.1-rc.3","@deepseek-ai/dsh-api-settings-controller":"0.2.1-rc.3","@deepseek-ai/dsh-api-workspace-controller":"0.2.1-rc.3","@deepseek-ai/dsh-api-workspace-files":"0.2.1-rc.3","@deepseek-ai/dsh-attachment":"0.2.1-rc.3","@deepseek-ai/dsh-brand":"0.2.1-rc.3","@deepseek-ai/dsh-client-connection":"0.2.1-rc.3","@deepseek-ai/dsh-client-file-upload":"0.2.1-rc.3","@deepseek-ai/dsh-client-locale":"0.2.1-rc.3","@deepseek-ai/dsh-client-store":"0.2.1-rc.3","@deepseek-ai/dsh-client-ui-chat":"0.2.1-rc.3","@deepseek-ai/dsh-client-ui-conversation":"0.2.1-rc.3","@deepseek-ai/dsh-client-ui-deliverables":"0.2.1-rc.3","@deepseek-ai/dsh-client-ui-settings":"0.2.1-rc.3","@deepseek-ai/dsh-client-ui-settings-general":"0.2.1-rc.3","@deepseek-ai/dsh-client-ui-theme":"0.2.1-rc.3","@deepseek-ai/dsh-command-compact":"0.2.1-rc.3","@deepseek-ai/dsh-command-feedback":"0.2.1-rc.3","@deepseek-ai/dsh-command-goal":"0.2.1-rc.3","@deepseek-ai/dsh-commands":"0.2.1-rc.3","@deepseek-ai/dsh-compaction":"0.2.1-rc.3","@deepseek-ai/dsh-compaction-basic":"0.2.1-rc.3","@deepseek-ai/dsh-compaction-image-offload":"0.2.1-rc.3","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.1-rc.3","@deepseek-ai/dsh-credentials":"0.2.1-rc.3","@deepseek-ai/dsh-file-reference":"0.2.1-rc.3","@deepseek-ai/dsh-fs":"0.2.1-rc.3","@deepseek-ai/dsh-fs-observation-policy":"0.2.1-rc.3","@deepseek-ai/dsh-goal":"0.2.1-rc.3","@deepseek-ai/dsh-goal-round-driver":"0.2.1-rc.3","@deepseek-ai/dsh-home-paths":"0.2.1-rc.3","@deepseek-ai/dsh-host-directory-picker":"0.2.1-rc.3","@deepseek-ai/dsh-host-plugin-inventory":"0.2.1-rc.3","@deepseek-ai/dsh-jobs":"0.2.1-rc.3","@deepseek-ai/dsh-jobs-local":"0.2.1-rc.3","@deepseek-ai/dsh-launch-environment":"0.2.1-rc.3","@deepseek-ai/dsh-llm":"0.2.1-rc.3","@deepseek-ai/dsh-mcp-resources":"0.2.1-rc.3","@deepseek-ai/dsh-llm-deepseek":"0.2.1-rc.3","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.1-rc.3","@deepseek-ai/dsh-llm-pi-ai":"0.2.1-rc.3","@deepseek-ai/dsh-llm-retry":"0.2.1-rc.3","@deepseek-ai/dsh-message-feedback":"0.2.1-rc.3","@deepseek-ai/dsh-output-retention":"0.2.1-rc.3","@deepseek-ai/dsh-plan-mode":"0.2.1-rc.3","@deepseek-ai/dsh-ptc-runtime":"0.2.1-rc.3","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.1-rc.3","@deepseek-ai/dsh-sandbox":"0.2.1-rc.3","@deepseek-ai/dsh-schedule":"0.2.1-rc.3","@deepseek-ai/dsh-scope":"0.2.1-rc.3","@deepseek-ai/dsh-session":"0.2.1-rc.3","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.1-rc.3","@deepseek-ai/dsh-session-log-export":"0.2.1-rc.3","@deepseek-ai/dsh-session-format":"0.2.1-rc.3","@deepseek-ai/dsh-session-format-catalog":"0.2.1-rc.3","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.1-rc.3","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.1-rc.3","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.1-rc.3","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.1-rc.3","@deepseek-ai/dsh-session-persistence":"0.2.1-rc.3","@deepseek-ai/dsh-session-projection":"0.2.1-rc.3","@deepseek-ai/dsh-session-projection-cache":"0.2.1-rc.3","@deepseek-ai/dsh-session-stats":"0.2.1-rc.3","@deepseek-ai/dsh-session-turn-outline":"0.2.1-rc.3","@deepseek-ai/dsh-session-query":"0.2.1-rc.3","@deepseek-ai/dsh-session-reference":"0.2.1-rc.3","@deepseek-ai/dsh-session-title":"0.2.1-rc.3","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.1-rc.3","@deepseek-ai/dsh-shell-env":"0.2.1-rc.3","@deepseek-ai/dsh-session-title-llm":"0.2.1-rc.3","@deepseek-ai/dsh-settings":"0.2.1-rc.3","@deepseek-ai/dsh-skill":"0.2.1-rc.3","@deepseek-ai/dsh-spill":"0.2.1-rc.3","@deepseek-ai/dsh-spill-policy":"0.2.1-rc.3","@deepseek-ai/dsh-storage":"0.2.1-rc.3","@deepseek-ai/dsh-storage-domain":"0.2.1-rc.3","@deepseek-ai/dsh-subagent":"0.2.1-rc.3","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.1-rc.3","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.1-rc.3","@deepseek-ai/dsh-system-prompt":"0.2.1-rc.3","@deepseek-ai/dsh-time-context":"0.2.1-rc.3","@deepseek-ai/dsh-timeout":"0.2.1-rc.3","@deepseek-ai/dsh-token-meter":"0.2.1-rc.3","@deepseek-ai/dsh-tool-ask-user":"0.2.1-rc.3","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.1-rc.3","@deepseek-ai/dsh-tool-fs":"0.2.1-rc.3","@deepseek-ai/dsh-tool-fs-search":"0.2.1-rc.3","@deepseek-ai/dsh-tool-goal":"0.2.1-rc.3","@deepseek-ai/dsh-tool-jobs":"0.2.1-rc.3","@deepseek-ai/dsh-tool-ralph":"0.2.1-rc.3","@deepseek-ai/dsh-tool-schedule":"0.2.1-rc.3","@deepseek-ai/dsh-tool-session-query":"0.2.1-rc.3","@deepseek-ai/dsh-tool-skill":"0.2.1-rc.3","@deepseek-ai/dsh-tool-subagent":"0.2.1-rc.3","@deepseek-ai/dsh-tool-subagent-control":"0.2.1-rc.3","@deepseek-ai/dsh-tool-present":"0.2.1-rc.3","@deepseek-ai/dsh-tool-todo":"0.2.1-rc.3","@deepseek-ai/dsh-tool-web":"0.2.1-rc.3","@deepseek-ai/dsh-tool-workflow":"0.2.1-rc.3","@deepseek-ai/dsh-tool-working-directory":"0.2.1-rc.3","@deepseek-ai/dsh-tools":"0.2.1-rc.3","@deepseek-ai/dsh-typert-protocol":"0.2.1-rc.3","@deepseek-ai/dsh-typert-registry":"0.2.1-rc.3","@deepseek-ai/dsh-user-approval":"0.2.1-rc.3","@deepseek-ai/dsh-user-questions":"0.2.1-rc.3","@deepseek-ai/dsh-util-values":"0.2.1-rc.3","@deepseek-ai/dsh-web":"0.2.1-rc.3","@deepseek-ai/dsh-web-deepseek-api":"0.2.1-rc.3","@deepseek-ai/dsh-web-fetch-http":"0.2.1-rc.3","@deepseek-ai/dsh-web-search-deepseek":"0.2.1-rc.3","@deepseek-ai/dsh-workflow":"0.2.1-rc.3","@deepseek-ai/dsh-working-directory":"0.2.1-rc.3","@deepseek-ai/dsh-workspace":"0.2.1-rc.3","@deepseek-ai/dsh-workspace-changes":"0.2.1-rc.3","@deepseek-ai/schemastery":"3.18.5","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0",diff:"9.0.0","fast-png":"8.0.0",fflate:"0.8.3","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var x3,JGe,XGe,F8=F(()=>{"use strict";QGe();x3=Ofe.version,JGe=Ofe.dshEdge.upstreamVersion,XGe=`npx dsh-edge@${x3.includes("-")?"next":"latest"} upgrade`});function ton(e){let t=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/iu.exec(e);if(t!==null)return t[1];let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/iu.exec(e);if(n!==null){let r=parseInt(n[1],16),i=parseInt(n[2],16);return`${String(r>>8)}.${String(r&255)}.${String(i>>8)}.${String(i&255)}`}}function non(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function ey(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("MCP server URL must use http: or https: protocol.");let n=t.hostname.toLowerCase(),r=n.endsWith(".")?n.slice(0,-1):n,i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(!(i==="localhost"||i==="127.0.0.1"||i==="::1")){for(let s of Ysn)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(non(i)){let s=ton(i),o=s??i;for(let l of Zsn)if(l.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let l of eon)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function ron(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}function son(e){return async(t,n)=>{let r=await E2(t,n);if(r.body===null)return r;let i=0,s=r.body.pipeThrough(new TransformStream({transform(o,l){if(i+=o.byteLength,i>e){l.error(new Error(`MCP server response is larger than ${String(e)} bytes.`));return}l.enqueue(o)}}));return new Response(s,{status:r.status,statusText:r.statusText,headers:r.headers})}}async function Mfe(e,t,n,r){ey(e);let i=new Sq(new URL(e),{requestInit:{headers:ron(t),signal:n},fetch:r===void 0?E2:son(r)}),s=new wq({name:"dsh-edge",version:x3},{capabilities:{},jsonSchemaValidator:ion});return await s.connect(i),{client:s,close:a(async()=>{await s.close().catch(()=>{})},"close")}}async function YGe(e,t,n){let r=AbortSignal.timeout(jo.probeTimeoutMs),i;try{i=await Mfe(t,n,r)}catch(l){throw new Error(Fh(l instanceof Error?l.message:String(l)))}let{client:s,close:o}=i;try{let l=[],c=new Set,u=new Set,d,p=s.getServerCapabilities?.()?.tools!==void 0;for(let y=0;p&&y<jo.maxCatalogPages;y++){let v=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let x of v.tools){if(l.length>=jo.maxToolsPerServer)break;let b=HGe(e,x.name);if(c.has(b))throw new Error(`Server listed tool "${x.name}" more than once`);c.add(b);let _=x.annotations?.readOnlyHint,S=GGe(x.outputSchema);l.push({name:x.name,publicName:b,description:x.description??"",inputSchema:x.inputSchema??{type:"object"},...S!==void 0?{outputSchema:S}:{},..._!==void 0?{annotations:{readOnlyHint:_}}:{}})}if(l.length>=jo.maxToolsPerServer||(d=v.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let h=s.getServerVersion?.(),m=s.getInstructions?.(),g=s.getServerCapabilities?.()?.resources!==void 0;return{tools:l,serverInfo:h?{name:h.name,version:h.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,jo.maxInstructionsLength):void 0,resources:g}}finally{await o()}}async function Cq(e,t,n,r,i,s){let o=s??jo.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),c;try{c=await Mfe(e,r,l)}catch(u){throw new Error(Fh(u instanceof Error?u.message:String(u)))}try{let u=await c.client.callTool({name:t,arguments:n},void 0,{signal:l});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(Fh(u instanceof Error?u.message:String(u)))}finally{await c.close()}}async function ZGe(e,t,n,r,i){let s=i??jo.callTimeoutMs,o=r?AbortSignal.any([r,AbortSignal.timeout(s)]):AbortSignal.timeout(s),l;try{l=await Mfe(e,n,o,jo.maxResourceResponseBytes)}catch(c){throw new Error(Fh(c instanceof Error?c.message:String(c)))}try{let{client:c}=l;if(t.method==="resources/read")return await c.readResource({uri:t.uri},{signal:o});let u=t.method==="resources/list"?"resources":"resourceTemplates",d=a(y=>t.method==="resources/list"?c.listResources(y===void 0?void 0:{cursor:y},{signal:o}):c.listResourceTemplates(y===void 0?void 0:{cursor:y},{signal:o}),"page");if(t.cursor!==void 0)return await d(t.cursor);let p=[],h=new Set,m=0,g;for(let y=0;y<jo.maxCatalogPages;y++){let v=await d(g),x=Array.isArray(v[u])?v[u]:[],b=new TextEncoder().encode(JSON.stringify(x)).byteLength;if(p.length>0&&m+b>jo.maxResourceResponseBytes)break;p.push(...x),m+=b;let _=typeof v.nextCursor=="string"?v.nextCursor:void 0;if(_===void 0){g=void 0;break}if(h.has(_))throw new Error(`Server repeated a ${t.method} continuation cursor`);h.add(_),g=_}return g===void 0?{[u]:p}:{[u]:p,nextCursor:g}}catch(c){throw new Error(Fh(c instanceof Error?c.message:String(c)))}finally{await l.close()}}var Ysn,Zsn,eon,ion,E2,U8=F(()=>{"use strict";rGe();$Ge();zGe();Rq();Iq();F8();Ysn=[".internal",".local",".localhost"],Zsn=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],eon=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(ton,"extractMappedIPv4");a(non,"isIpAddress");a(ey,"assertSafeUrl");a(ron,"buildHeaders");ion=new Aq,E2=a(async(e,t)=>{let n=await globalThis.fetch(e,{...t,redirect:"manual"});if(n.status>=300&&n.status<400)throw new Error(`MCP server returned HTTP ${String(n.status)} redirect; redirects are blocked for security.`);return n},"noRedirectFetch");a(son,"byteCappedFetch");a(Mfe,"connectClient");a(YGe,"probe");a(Cq,"callTool");a(ZGe,"requestResources")});var Oq={};Mt(Oq,{buildAuthorizationUrl:()=>mon,discoverEndpoints:()=>pon,exchangeCode:()=>fon,isTokenExpired:()=>yon,refreshToken:()=>gon,registerClient:()=>hon});function rVe(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,n=>n.toString(16).padStart(2,"0")).join("").slice(0,e)}async function don(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=/gu,"")}async function pon(e){let t=AbortSignal.timeout(Pq),n=new URL(e),r=n.pathname==="/"?"/.well-known/oauth-protected-resource":`/.well-known/oauth-protected-resource${n.pathname}`,i=new URL(r,n.origin);ey(i.href);let s=await E2(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let l=(await s.json()).authorization_servers?.[0];if(typeof l!="string")throw new Error("No authorization server in PRM");let c=new URL(l),u=c.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${c.pathname}`,d=new URL(u,c.origin);ey(d.href);let p=await E2(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let h=await p.json();if(typeof h.authorization_endpoint!="string"||typeof h.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:h.authorization_endpoint,token:h.token_endpoint,registration:h.registration_endpoint}}async function hon(e,t,n){let r=AbortSignal.timeout(Pq);ey(e);let i=await E2(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:n,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}),signal:r});if(!i.ok)throw new Error(`DCR failed: HTTP ${i.status}`);let s=await i.json();if(typeof s.client_id!="string")throw new Error("DCR response missing client_id");return{clientId:s.client_id,clientSecret:s.client_secret}}async function mon(e,t,n,r,i){let s=rVe(32),o=rVe(64),l=await don(o),c=new URL(e.authorization);for(let[u,d]of Object.entries({response_type:"code",client_id:t.clientId,redirect_uri:n,state:s,code_challenge:l,code_challenge_method:"S256",resource:i}))c.searchParams.set(u,d);return{authorizationUrl:c.href,pendingFlow:{state:s,codeVerifier:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function fon(e,t,n,r,i,s){let o=AbortSignal.timeout(Pq),l=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&l.set("resource",s),t.clientSecret!==void 0&&l.set("client_secret",t.clientSecret),ey(e);let c=await E2(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:o});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return iVe(await c.json())}async function gon(e,t,n,r){let i=AbortSignal.timeout(Pq),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n,client_id:t.clientId});r!==void 0&&s.set("resource",r),t.clientSecret!==void 0&&s.set("client_secret",t.clientSecret),ey(e);let o=await E2(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!o.ok)throw new Error(`Token refresh failed: HTTP ${o.status}`);return iVe(await o.json())}function iVe(e){let t=e;if(typeof t.access_token!="string")throw new Error("Missing access_token");let n=typeof t.expires_in=="number"?t.expires_in:void 0;return{accessToken:t.access_token,refreshToken:typeof t.refresh_token=="string"?t.refresh_token:void 0,expiresAt:n!==void 0?Date.now()+n*1e3:void 0,tokenType:typeof t.token_type=="string"?t.token_type:"Bearer",scope:typeof t.scope=="string"?t.scope:void 0}}function yon(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var Pq,Mq=F(()=>{"use strict";U8();Pq=1e4;a(rVe,"randomString");a(don,"sha256Base64Url");a(pon,"discoverEndpoints");a(hon,"registerClient");a(mon,"buildAuthorizationUrl");a(fon,"exchangeCode");a(gon,"refreshToken");a(iVe,"parseTokenResponse");a(yon,"isTokenExpired")});var ur,pVe,f4=F(()=>{mr();Nr();ur=class extends ni{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},pVe=class extends Nt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new ur("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function G8(e){return Gq.test(e)}function Vq(e){return e.invocation.modelInvocable}function Kq(e){return e.invocation.userInvocable}function tge(e){let t=fln(e);return[`<skill_content name="${gln(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
167
+ `)}),t.length>0?t:[{type:"text",text:"(empty MCP result)"}]}var Hsn,Ksn,Qsn,Rq=F(()=>{"use strict";Zs();Iq();Hsn=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(Gsn,"globToRegExp");a(Pfe,"evaluateMcpToolPolicy");a(Fh,"scrubMcpErrorMessage");a(HGe,"publicToolName");a(Vsn,"hashSuffix");a(GGe,"supportedOutputSchema");Ksn=new Set(["image/png","image/jpeg"]),Qsn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Jsn,"isImageMediaType");a(VGe,"decodeImageBlock");a(KGe,"containsImage");a(j8,"mapMcpResultToContentBlocks")});var Ofe,QGe=F(()=>{Ofe={name:"dsh-edge",version:"0.34.0",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.1-rc.4"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","check:startup":"node scripts/check-startup.mjs","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0",yaml:"2.9.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.7.0","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.5","@deepseek-ai/cosmokit":"1.8.6","@deepseek-ai/dsh-agent":"0.2.1-rc.4","@deepseek-ai/dsh-agent-instructions":"0.2.1-rc.4","@deepseek-ai/dsh-agent-loop":"0.2.1-rc.4","@deepseek-ai/dsh-anonymous-user-id":"0.2.1-rc.4","@deepseek-ai/dsh-api-gateway":"0.2.1-rc.4","@deepseek-ai/dsh-api-job-controller":"0.2.1-rc.4","@deepseek-ai/dsh-api-remote-access":"0.2.1-rc.4","@deepseek-ai/dsh-api-remotes":"0.2.1-rc.4","@deepseek-ai/dsh-api-session-controller":"0.2.1-rc.4","@deepseek-ai/dsh-api-settings-controller":"0.2.1-rc.4","@deepseek-ai/dsh-api-workspace-controller":"0.2.1-rc.4","@deepseek-ai/dsh-api-workspace-files":"0.2.1-rc.4","@deepseek-ai/dsh-attachment":"0.2.1-rc.4","@deepseek-ai/dsh-brand":"0.2.1-rc.4","@deepseek-ai/dsh-client-connection":"0.2.1-rc.4","@deepseek-ai/dsh-client-file-upload":"0.2.1-rc.4","@deepseek-ai/dsh-client-locale":"0.2.1-rc.4","@deepseek-ai/dsh-client-store":"0.2.1-rc.4","@deepseek-ai/dsh-client-ui-chat":"0.2.1-rc.4","@deepseek-ai/dsh-client-ui-conversation":"0.2.1-rc.4","@deepseek-ai/dsh-client-ui-deliverables":"0.2.1-rc.4","@deepseek-ai/dsh-client-ui-settings":"0.2.1-rc.4","@deepseek-ai/dsh-client-ui-settings-general":"0.2.1-rc.4","@deepseek-ai/dsh-client-ui-theme":"0.2.1-rc.4","@deepseek-ai/dsh-command-compact":"0.2.1-rc.4","@deepseek-ai/dsh-command-feedback":"0.2.1-rc.4","@deepseek-ai/dsh-command-goal":"0.2.1-rc.4","@deepseek-ai/dsh-commands":"0.2.1-rc.4","@deepseek-ai/dsh-compaction":"0.2.1-rc.4","@deepseek-ai/dsh-compaction-basic":"0.2.1-rc.4","@deepseek-ai/dsh-compaction-image-offload":"0.2.1-rc.4","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.1-rc.4","@deepseek-ai/dsh-credentials":"0.2.1-rc.4","@deepseek-ai/dsh-file-reference":"0.2.1-rc.4","@deepseek-ai/dsh-fs":"0.2.1-rc.4","@deepseek-ai/dsh-fs-observation-policy":"0.2.1-rc.4","@deepseek-ai/dsh-goal":"0.2.1-rc.4","@deepseek-ai/dsh-goal-round-driver":"0.2.1-rc.4","@deepseek-ai/dsh-home-paths":"0.2.1-rc.4","@deepseek-ai/dsh-host-directory-picker":"0.2.1-rc.4","@deepseek-ai/dsh-host-plugin-inventory":"0.2.1-rc.4","@deepseek-ai/dsh-jobs":"0.2.1-rc.4","@deepseek-ai/dsh-jobs-local":"0.2.1-rc.4","@deepseek-ai/dsh-launch-environment":"0.2.1-rc.4","@deepseek-ai/dsh-llm":"0.2.1-rc.4","@deepseek-ai/dsh-mcp-resources":"0.2.1-rc.4","@deepseek-ai/dsh-llm-deepseek":"0.2.1-rc.4","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.1-rc.4","@deepseek-ai/dsh-llm-pi-ai":"0.2.1-rc.4","@deepseek-ai/dsh-llm-retry":"0.2.1-rc.4","@deepseek-ai/dsh-message-feedback":"0.2.1-rc.4","@deepseek-ai/dsh-output-retention":"0.2.1-rc.4","@deepseek-ai/dsh-plan-mode":"0.2.1-rc.4","@deepseek-ai/dsh-ptc-runtime":"0.2.1-rc.4","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.1-rc.4","@deepseek-ai/dsh-sandbox":"0.2.1-rc.4","@deepseek-ai/dsh-schedule":"0.2.1-rc.4","@deepseek-ai/dsh-scope":"0.2.1-rc.4","@deepseek-ai/dsh-session":"0.2.1-rc.4","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.1-rc.4","@deepseek-ai/dsh-session-log-export":"0.2.1-rc.4","@deepseek-ai/dsh-session-format":"0.2.1-rc.4","@deepseek-ai/dsh-session-format-catalog":"0.2.1-rc.4","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.1-rc.4","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.1-rc.4","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.1-rc.4","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.1-rc.4","@deepseek-ai/dsh-session-persistence":"0.2.1-rc.4","@deepseek-ai/dsh-session-projection":"0.2.1-rc.4","@deepseek-ai/dsh-session-projection-cache":"0.2.1-rc.4","@deepseek-ai/dsh-session-stats":"0.2.1-rc.4","@deepseek-ai/dsh-session-turn-outline":"0.2.1-rc.4","@deepseek-ai/dsh-session-query":"0.2.1-rc.4","@deepseek-ai/dsh-session-reference":"0.2.1-rc.4","@deepseek-ai/dsh-session-title":"0.2.1-rc.4","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.1-rc.4","@deepseek-ai/dsh-shell-env":"0.2.1-rc.4","@deepseek-ai/dsh-session-title-llm":"0.2.1-rc.4","@deepseek-ai/dsh-settings":"0.2.1-rc.4","@deepseek-ai/dsh-skill":"0.2.1-rc.4","@deepseek-ai/dsh-spill":"0.2.1-rc.4","@deepseek-ai/dsh-spill-policy":"0.2.1-rc.4","@deepseek-ai/dsh-storage":"0.2.1-rc.4","@deepseek-ai/dsh-storage-domain":"0.2.1-rc.4","@deepseek-ai/dsh-subagent":"0.2.1-rc.4","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.1-rc.4","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.1-rc.4","@deepseek-ai/dsh-system-prompt":"0.2.1-rc.4","@deepseek-ai/dsh-time-context":"0.2.1-rc.4","@deepseek-ai/dsh-timeout":"0.2.1-rc.4","@deepseek-ai/dsh-token-meter":"0.2.1-rc.4","@deepseek-ai/dsh-tool-ask-user":"0.2.1-rc.4","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.1-rc.4","@deepseek-ai/dsh-tool-fs":"0.2.1-rc.4","@deepseek-ai/dsh-tool-fs-search":"0.2.1-rc.4","@deepseek-ai/dsh-tool-goal":"0.2.1-rc.4","@deepseek-ai/dsh-tool-jobs":"0.2.1-rc.4","@deepseek-ai/dsh-tool-ralph":"0.2.1-rc.4","@deepseek-ai/dsh-tool-schedule":"0.2.1-rc.4","@deepseek-ai/dsh-tool-session-query":"0.2.1-rc.4","@deepseek-ai/dsh-tool-skill":"0.2.1-rc.4","@deepseek-ai/dsh-tool-subagent":"0.2.1-rc.4","@deepseek-ai/dsh-tool-subagent-control":"0.2.1-rc.4","@deepseek-ai/dsh-tool-present":"0.2.1-rc.4","@deepseek-ai/dsh-tool-todo":"0.2.1-rc.4","@deepseek-ai/dsh-tool-web":"0.2.1-rc.4","@deepseek-ai/dsh-tool-workflow":"0.2.1-rc.4","@deepseek-ai/dsh-tool-working-directory":"0.2.1-rc.4","@deepseek-ai/dsh-tools":"0.2.1-rc.4","@deepseek-ai/dsh-typert-protocol":"0.2.1-rc.4","@deepseek-ai/dsh-typert-registry":"0.2.1-rc.4","@deepseek-ai/dsh-user-approval":"0.2.1-rc.4","@deepseek-ai/dsh-user-questions":"0.2.1-rc.4","@deepseek-ai/dsh-util-values":"0.2.1-rc.4","@deepseek-ai/dsh-web":"0.2.1-rc.4","@deepseek-ai/dsh-web-deepseek-api":"0.2.1-rc.4","@deepseek-ai/dsh-web-fetch-http":"0.2.1-rc.4","@deepseek-ai/dsh-web-search-deepseek":"0.2.1-rc.4","@deepseek-ai/dsh-workflow":"0.2.1-rc.4","@deepseek-ai/dsh-working-directory":"0.2.1-rc.4","@deepseek-ai/dsh-workspace":"0.2.1-rc.4","@deepseek-ai/dsh-workspace-changes":"0.2.1-rc.4","@deepseek-ai/schemastery":"3.18.5","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0",diff:"9.0.0","fast-png":"8.0.0",fflate:"0.8.3","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var x3,JGe,XGe,F8=F(()=>{"use strict";QGe();x3=Ofe.version,JGe=Ofe.dshEdge.upstreamVersion,XGe=`npx dsh-edge@${x3.includes("-")?"next":"latest"} upgrade`});function ton(e){let t=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/iu.exec(e);if(t!==null)return t[1];let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/iu.exec(e);if(n!==null){let r=parseInt(n[1],16),i=parseInt(n[2],16);return`${String(r>>8)}.${String(r&255)}.${String(i>>8)}.${String(i&255)}`}}function non(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function ey(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("MCP server URL must use http: or https: protocol.");let n=t.hostname.toLowerCase(),r=n.endsWith(".")?n.slice(0,-1):n,i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(!(i==="localhost"||i==="127.0.0.1"||i==="::1")){for(let s of Ysn)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(non(i)){let s=ton(i),o=s??i;for(let l of Zsn)if(l.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let l of eon)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function ron(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}function son(e){return async(t,n)=>{let r=await E2(t,n);if(r.body===null)return r;let i=0,s=r.body.pipeThrough(new TransformStream({transform(o,l){if(i+=o.byteLength,i>e){l.error(new Error(`MCP server response is larger than ${String(e)} bytes.`));return}l.enqueue(o)}}));return new Response(s,{status:r.status,statusText:r.statusText,headers:r.headers})}}async function Mfe(e,t,n,r){ey(e);let i=new Sq(new URL(e),{requestInit:{headers:ron(t),signal:n},fetch:r===void 0?E2:son(r)}),s=new wq({name:"dsh-edge",version:x3},{capabilities:{},jsonSchemaValidator:ion});return await s.connect(i),{client:s,close:a(async()=>{await s.close().catch(()=>{})},"close")}}async function YGe(e,t,n){let r=AbortSignal.timeout(jo.probeTimeoutMs),i;try{i=await Mfe(t,n,r)}catch(l){throw new Error(Fh(l instanceof Error?l.message:String(l)))}let{client:s,close:o}=i;try{let l=[],c=new Set,u=new Set,d,p=s.getServerCapabilities?.()?.tools!==void 0;for(let y=0;p&&y<jo.maxCatalogPages;y++){let v=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let x of v.tools){if(l.length>=jo.maxToolsPerServer)break;let b=HGe(e,x.name);if(c.has(b))throw new Error(`Server listed tool "${x.name}" more than once`);c.add(b);let _=x.annotations?.readOnlyHint,S=GGe(x.outputSchema);l.push({name:x.name,publicName:b,description:x.description??"",inputSchema:x.inputSchema??{type:"object"},...S!==void 0?{outputSchema:S}:{},..._!==void 0?{annotations:{readOnlyHint:_}}:{}})}if(l.length>=jo.maxToolsPerServer||(d=v.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let h=s.getServerVersion?.(),m=s.getInstructions?.(),g=s.getServerCapabilities?.()?.resources!==void 0;return{tools:l,serverInfo:h?{name:h.name,version:h.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,jo.maxInstructionsLength):void 0,resources:g}}finally{await o()}}async function Cq(e,t,n,r,i,s){let o=s??jo.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),c;try{c=await Mfe(e,r,l)}catch(u){throw new Error(Fh(u instanceof Error?u.message:String(u)))}try{let u=await c.client.callTool({name:t,arguments:n},void 0,{signal:l});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(Fh(u instanceof Error?u.message:String(u)))}finally{await c.close()}}async function ZGe(e,t,n,r,i){let s=i??jo.callTimeoutMs,o=r?AbortSignal.any([r,AbortSignal.timeout(s)]):AbortSignal.timeout(s),l;try{l=await Mfe(e,n,o,jo.maxResourceResponseBytes)}catch(c){throw new Error(Fh(c instanceof Error?c.message:String(c)))}try{let{client:c}=l;if(t.method==="resources/read")return await c.readResource({uri:t.uri},{signal:o});let u=t.method==="resources/list"?"resources":"resourceTemplates",d=a(y=>t.method==="resources/list"?c.listResources(y===void 0?void 0:{cursor:y},{signal:o}):c.listResourceTemplates(y===void 0?void 0:{cursor:y},{signal:o}),"page");if(t.cursor!==void 0)return await d(t.cursor);let p=[],h=new Set,m=0,g;for(let y=0;y<jo.maxCatalogPages;y++){let v=await d(g),x=Array.isArray(v[u])?v[u]:[],b=new TextEncoder().encode(JSON.stringify(x)).byteLength;if(p.length>0&&m+b>jo.maxResourceResponseBytes)break;p.push(...x),m+=b;let _=typeof v.nextCursor=="string"?v.nextCursor:void 0;if(_===void 0){g=void 0;break}if(h.has(_))throw new Error(`Server repeated a ${t.method} continuation cursor`);h.add(_),g=_}return g===void 0?{[u]:p}:{[u]:p,nextCursor:g}}catch(c){throw new Error(Fh(c instanceof Error?c.message:String(c)))}finally{await l.close()}}var Ysn,Zsn,eon,ion,E2,U8=F(()=>{"use strict";rGe();$Ge();zGe();Rq();Iq();F8();Ysn=[".internal",".local",".localhost"],Zsn=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],eon=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(ton,"extractMappedIPv4");a(non,"isIpAddress");a(ey,"assertSafeUrl");a(ron,"buildHeaders");ion=new Aq,E2=a(async(e,t)=>{let n=await globalThis.fetch(e,{...t,redirect:"manual"});if(n.status>=300&&n.status<400)throw new Error(`MCP server returned HTTP ${String(n.status)} redirect; redirects are blocked for security.`);return n},"noRedirectFetch");a(son,"byteCappedFetch");a(Mfe,"connectClient");a(YGe,"probe");a(Cq,"callTool");a(ZGe,"requestResources")});var Oq={};Mt(Oq,{buildAuthorizationUrl:()=>mon,discoverEndpoints:()=>pon,exchangeCode:()=>fon,isTokenExpired:()=>yon,refreshToken:()=>gon,registerClient:()=>hon});function rVe(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,n=>n.toString(16).padStart(2,"0")).join("").slice(0,e)}async function don(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=/gu,"")}async function pon(e){let t=AbortSignal.timeout(Pq),n=new URL(e),r=n.pathname==="/"?"/.well-known/oauth-protected-resource":`/.well-known/oauth-protected-resource${n.pathname}`,i=new URL(r,n.origin);ey(i.href);let s=await E2(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let l=(await s.json()).authorization_servers?.[0];if(typeof l!="string")throw new Error("No authorization server in PRM");let c=new URL(l),u=c.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${c.pathname}`,d=new URL(u,c.origin);ey(d.href);let p=await E2(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let h=await p.json();if(typeof h.authorization_endpoint!="string"||typeof h.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:h.authorization_endpoint,token:h.token_endpoint,registration:h.registration_endpoint}}async function hon(e,t,n){let r=AbortSignal.timeout(Pq);ey(e);let i=await E2(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:n,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}),signal:r});if(!i.ok)throw new Error(`DCR failed: HTTP ${i.status}`);let s=await i.json();if(typeof s.client_id!="string")throw new Error("DCR response missing client_id");return{clientId:s.client_id,clientSecret:s.client_secret}}async function mon(e,t,n,r,i){let s=rVe(32),o=rVe(64),l=await don(o),c=new URL(e.authorization);for(let[u,d]of Object.entries({response_type:"code",client_id:t.clientId,redirect_uri:n,state:s,code_challenge:l,code_challenge_method:"S256",resource:i}))c.searchParams.set(u,d);return{authorizationUrl:c.href,pendingFlow:{state:s,codeVerifier:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function fon(e,t,n,r,i,s){let o=AbortSignal.timeout(Pq),l=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&l.set("resource",s),t.clientSecret!==void 0&&l.set("client_secret",t.clientSecret),ey(e);let c=await E2(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:o});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return iVe(await c.json())}async function gon(e,t,n,r){let i=AbortSignal.timeout(Pq),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n,client_id:t.clientId});r!==void 0&&s.set("resource",r),t.clientSecret!==void 0&&s.set("client_secret",t.clientSecret),ey(e);let o=await E2(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!o.ok)throw new Error(`Token refresh failed: HTTP ${o.status}`);return iVe(await o.json())}function iVe(e){let t=e;if(typeof t.access_token!="string")throw new Error("Missing access_token");let n=typeof t.expires_in=="number"?t.expires_in:void 0;return{accessToken:t.access_token,refreshToken:typeof t.refresh_token=="string"?t.refresh_token:void 0,expiresAt:n!==void 0?Date.now()+n*1e3:void 0,tokenType:typeof t.token_type=="string"?t.token_type:"Bearer",scope:typeof t.scope=="string"?t.scope:void 0}}function yon(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var Pq,Mq=F(()=>{"use strict";U8();Pq=1e4;a(rVe,"randomString");a(don,"sha256Base64Url");a(pon,"discoverEndpoints");a(hon,"registerClient");a(mon,"buildAuthorizationUrl");a(fon,"exchangeCode");a(gon,"refreshToken");a(iVe,"parseTokenResponse");a(yon,"isTokenExpired")});var ur,pVe,f4=F(()=>{mr();Nr();ur=class extends ni{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},pVe=class extends Nt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new ur("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function G8(e){return Gq.test(e)}function Vq(e){return e.invocation.modelInvocable}function Kq(e){return e.invocation.userInvocable}function tge(e){let t=fln(e);return[`<skill_content name="${gln(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
168
168
  `)}function fln(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${g4(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${g4(t.path)}`,"Resolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed."];case"url":return[`Base URL for this skill: ${g4(t.url)}`,"Resolve relative URLs mentioned by this skill against the base URL before using them. Load referenced resources only as needed."];case"opaque":return[`Resources for this skill: ${g4(t.description)}`,"Load referenced resources only as needed."];default:return Ar(t,"SkillResourceBase.kind")}}function gln(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;")}function g4(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function vln(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw qVe(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw qVe(t);return n}function qVe(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function bln(e){return{name:e.name,description:e.description,...e.whenToUse!==void 0?{whenToUse:e.whenToUse}:{},invocation:e.invocation,source:e.source,provider:e.provider,...e.resourceBase!==void 0?{resourceBase:e.resourceBase}:{},rank:mln,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function wln(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!Gq.test(e.name))throw new Error(`skill provider "${t}" returned invalid skill name "${e.name}"`);if(typeof e.description!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string description`);if(e.description.length===0)throw new Error(`skill provider "${t}" returned skill "${e.name}" without a description`);if(nge(e.invocation,`skill provider "${t}" returned skill "${e.name}"`),e.whenToUse!==void 0&&typeof e.whenToUse!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string whenToUse`);if(typeof e.source!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string source`);if(typeof e.rank!="number"||!Number.isFinite(e.rank))throw new Error(`skill provider "${t}" returned skill "${e.name}" with an invalid rank`);if(typeof e.provider!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string provider`);if(e.provider!==t)throw new Error(`skill provider "${t}" returned skill "${e.name}" for provider "${e.provider}"`);if(e.path!==void 0&&typeof e.path!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string path`)}function kln(e){if(!Gq.test(e.name))throw new Error(`invalid skill name "${e.name}"`);if(e.description.length===0)throw new Error(`skill "${e.name}" requires a description`);nge(e.invocation,`runtime skill "${e.name}"`)}function Sln(e){let t=e.name,n=e.description,r=e.whenToUse,i=e.invocation,s=e.source,o=e.provider,l=e.content,c=e.path;if(typeof t!="string")throw new TypeError("loaded skill name must be a string");if(!Gq.test(t))throw new Error(`loaded skill has invalid name "${t}"`);if(typeof n!="string")throw new TypeError(`loaded skill "${t}" description must be a string`);if(n.length===0)throw new Error(`loaded skill "${t}" requires a description`);if(nge(i,`loaded skill "${t}"`),r!==void 0&&typeof r!="string")throw new TypeError(`loaded skill "${t}" whenToUse must be a string`);if(typeof s!="string")throw new TypeError(`loaded skill "${t}" source must be a string`);if(typeof o!="string")throw new TypeError(`loaded skill "${t}" provider must be a string`);if(typeof l!="string")throw new TypeError(`loaded skill "${t}" content must be a string`);if(c!==void 0&&typeof c!="string")throw new TypeError(`loaded skill "${t}" path must be a string`)}function _ln(e){let{name:t,description:n,whenToUse:r,invocation:i,source:s,provider:o,resourceBase:l}=e;return{name:t,...e.path===void 0?{}:{path:e.path},description:n,...r!==void 0?{whenToUse:r}:{},invocation:i,source:s,provider:o,...l!==void 0?{resourceBase:l}:{}}}function nge(e,t){if(e===void 0)return;if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError(`${t} with a non-object invocation policy`);let n=e;if(typeof n.modelInvocable!="boolean")throw new TypeError(`${t} with a non-boolean invocation.modelInvocable`);if(typeof n.userInvocable!="boolean")throw new TypeError(`${t} with a non-boolean invocation.userInvocable`)}function Eln(e,t){return HVe(e.name,t.name)}function HVe(e,t){return e<t?-1:e>t?1:0}function Tln(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function Aln(e,t,n=1){if(!Number.isInteger(t)||t<n)throw new Error(`skill: ${e} must be an integer greater than or equal to ${n}`)}function WVe(e,t){return t===void 0?e:(H8(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(Hq(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(Hq(o))})}))}function H8(e){if(e?.aborted===!0)throw Hq(e.reason)}function Hq(e){try{if(e instanceof Error)return e}catch{}return new Error(zq(e))}function zq(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var Gq,UVe,hln,Bq,mln,BVe,yln,zVe,xln,y4=F(()=>{mr();ps();vc();vn();Gq=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,UVe=128,hln=2,Bq="runtime",mln=250,BVe=600;a(G8,"isSkillName");a(Vq,"isModelInvocable");a(Kq,"isUserInvocable");a(tge,"renderSkillContent");a(fln,"renderResourceHint");a(gln,"escapeAttr");a(g4,"escapeText");yln=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new Sh(t=>new Error(e===void 0?`a skill provider named "${t}" is already registered`:`a skill provider named "${t}" is already registered in this scope`))}isEmpty(){return this.providers.isEmpty()&&this.runtime.size===0}},zVe=class extends Nt{static{a(this,"SkillRegistry")}static Config=L.object({collectCacheMaxEntries:L.number().default(UVe)});collectCacheMaxEntries;layers=new _h(e=>new yln(e),()=>{this.invalidateCache()});collectCache=new Map;revision=0;nextProviderOrder=0;scopeIds=new WeakMap;nextScopeId=1;constructor(e,t={}){super(e,"skills"),this.collectCacheMaxEntries=t.collectCacheMaxEntries??UVe,Aln("collectCacheMaxEntries",this.collectCacheMaxEntries)}registerProvider(e){let t=new AbortController,n,r,i={signal:t.signal,invalidate:a(()=>{let s=n;s!==void 0&&s.layer.providers.get(s.name)?.provider===r&&this.invalidateCache()},"invalidate")};try{r=e(i);let s=r.name;if(s===Bq)throw new Error(`"${Bq}" is reserved for runtime skill registrations`);let o=this.nextProviderOrder;return this.nextProviderOrder+=1,this.layers.effect(this.ctx,l=>{let c=l.providers.insert(s,{provider:r,order:o});return n={layer:l,name:s},()=>{n=void 0,c(),t.abort(new Error(`skill provider "${s}" disposed`))}},{label:"skills.registerProvider()"})}catch(s){throw t.abort(s),s}}register(e){kln(e);let t=Il(this.ctx),n=t===void 0?this.layers.global:this.layers.peek(t);if(n!==void 0&&n.runtime.has(e.name))return this.ctx.logger.warn(`runtime skill "${e.name}" ignored because it is already registered`),()=>{};let r={...e,invocation:e.invocation??{modelInvocable:!0,userInvocable:!0},provider:e.provider??Bq};return this.layers.effect(this.ctx,i=>(i.runtime.set(r.name,r),()=>{i.runtime.delete(r.name)}),{label:"skills.register()"})}async list(e={}){return(await this.snapshot(e)).skills}async snapshot(e={}){let t=await this.collect(e);return{skills:[...t.entries.values()].map(n=>_ln(n.candidate)).sort(Eln),complete:t.cacheable}}async get(e,t={}){if(!G8(e))return;let n=await this.collect(t);H8(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await WVe(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(Sln(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){H8(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,hR(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(H8(e.signal),n!==this.revision){if(t<hln){t+=1;continue}return{entries:s.entries,cacheable:!1}}if(s.cacheable&&(this.collectCache.set(r,s.entries),this.collectCache.size>this.collectCacheMaxEntries)){let o=this.collectCache.keys().next();this.collectCache.delete(o.value)}return s}}async collectFresh(e){let t=[this.layers.global,...this.layers.chainLayers(e.scope)],n=new Map,r=!0;for(let i of t){let s=await this.collectLayer(i,e);s.cacheable||(r=!1);for(let o of s.entries)n.set(o.candidate.name,o)}return{entries:n,cacheable:r}}async collectLayer(e,t){let n=await this.listLayerCandidates(e,t);n.entries.sort(Tln);let r=new Set,i=[];for(let s of n.entries){let o=s.candidate;if(r.has(o.name)){this.ctx.logger.warn(`skill "${o.name}" from ${o.source} ignored because a higher-priority skill already exists`);continue}r.add(o.name),i.push(s)}return{entries:i,cacheable:n.cacheable}}async listLayerCandidates(e,t){H8(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,l)=>HVe(o.name,l.name)))n.push({candidate:bln(s),provider:xln,providerOrder:-1,localOrder:i,layer:e}),i+=1;for(let{provider:s,order:o}of[...e.providers.values()]){let l=0,c;try{c=await WVe(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw Hq(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${zq(d)}`)}if(c===void 0)continue;let u=vln(c,s.name);u.complete||(r=!1);for(let d of u.candidates)wln(d,s.name),n.push({candidate:d,provider:s,providerOrder:o,localOrder:l,layer:e}),l+=1}return{entries:n,cacheable:r}}invalidateCache(){this.revision+=1,this.collectCache.clear(),this.notifyChange()}invalidateEntry(e){e.layer.providers.get(e.provider.name)?.provider===e.provider&&this.invalidateCache()}scopeId(e){let t=this.scopeIds.get(e);return t===void 0&&(t=this.nextScopeId,this.nextScopeId+=1,this.scopeIds.set(e,t)),t}collectCacheKey(e,t,n){return JSON.stringify({cwd:e,scopes:t.map(r=>this.scopeId(r)),revision:n})}notifyChange(){for(let e of this.ctx.events.dispatch("emit",["skills/change"]))try{let t=e();Promise.resolve(t).catch(n=>{this.ctx.logger.warn(`skills/change listener rejected: ${zq(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${zq(t)}`)}}};a(vln,"normalizeProviderObservation");a(qVe,"invalidProviderObservation");xln={name:Bq,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(bln,"runtimeCandidate");a(wln,"validateCandidate");a(kln,"validateRuntimeSkill");a(Sln,"validateDefinition");a(_ln,"toSummary");a(nge,"validateInvocation");a(Eln,"compareSkillSummary");a(HVe,"compareCodePoints");a(Tln,"compareIndexedCandidates");a(Aln,"assertPositiveInteger");a(WVe,"waitWithAbort");a(H8,"throwIfAborted");a(Hq,"toError");a(zq,"errorMessage")});var Uh,E4=F(()=>{Uh=class{static{a(this,"Deque")}buffer=new Array(16);head=0;count=0;get size(){return this.count}pushBack(e){this.ensureCapacity();let t=this.head+this.count;this.buffer[t<this.buffer.length?t:t-this.buffer.length]=e,this.count+=1}pushFront(e){this.ensureCapacity(),this.head=this.head===0?this.buffer.length-1:this.head-1,this.buffer[this.head]=e,this.count+=1}popFront(){if(this.count===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head+=1,this.head===this.buffer.length&&(this.head=0),this.count-=1,this.compact(),e}clear(){this.buffer=new Array(16),this.head=0,this.count=0}ensureCapacity(){this.count<this.buffer.length||this.resize(this.buffer.length*2)}compact(){if(this.count===0){this.head=0;return}this.buffer.length>16&&this.count<=this.buffer.length/4&&this.resize(Math.max(16,this.buffer.length/2))}resize(e){let t=new Array(e),n=this.head;for(let r=0;r<this.count;r+=1)t[r]=this.buffer[n],n+=1,n===this.buffer.length&&(n=0);this.buffer=t,this.head=0}}});var sy,bJe,d0e=F(()=>{mr();sy=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},bJe=class extends Nt{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var W4=le((Sti,zXe)=>{"use strict";var Xfn="2.0.0",Yfn=Number.MAX_SAFE_INTEGER||9007199254740991,Zfn=16,egn=250,tgn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];zXe.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Zfn,MAX_SAFE_BUILD_LENGTH:egn,MAX_SAFE_INTEGER:Yfn,RELEASE_TYPES:tgn,SEMVER_SPEC_VERSION:Xfn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var C9=le((_ti,HXe)=>{"use strict";var ngn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};HXe.exports=ngn});var B4=le((f0,GXe)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:r1e,MAX_SAFE_BUILD_LENGTH:rgn,MAX_LENGTH:ign}=W4(),sgn=C9();f0=GXe.exports={};var ogn=f0.re=[],agn=f0.safeRe=[],Rn=f0.src=[],lgn=f0.safeSrc=[],Cn=f0.t={},cgn=0,i1e="[a-zA-Z0-9-]",ugn=[["\\s",1],["\\d",ign],[i1e,rgn]],dgn=a(e=>{for(let[t,n]of ugn)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},"makeSafeRegex"),oi=a((e,t,n)=>{let r=dgn(t),i=cgn++;sgn(e,i,t),Cn[e]=i,Rn[i]=t,lgn[i]=r,ogn[i]=new RegExp(t,n?"g":void 0),agn[i]=new RegExp(r,n?"g":void 0)},"createToken");oi("NUMERICIDENTIFIER","0|[1-9]\\d*");oi("NUMERICIDENTIFIERLOOSE","\\d+");oi("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${i1e}*`);oi("MAINVERSION",`(${Rn[Cn.NUMERICIDENTIFIER]})\\.(${Rn[Cn.NUMERICIDENTIFIER]})\\.(${Rn[Cn.NUMERICIDENTIFIER]})`);oi("MAINVERSIONLOOSE",`(${Rn[Cn.NUMERICIDENTIFIERLOOSE]})\\.(${Rn[Cn.NUMERICIDENTIFIERLOOSE]})\\.(${Rn[Cn.NUMERICIDENTIFIERLOOSE]})`);oi("PRERELEASEIDENTIFIER",`(?:${Rn[Cn.NONNUMERICIDENTIFIER]}|${Rn[Cn.NUMERICIDENTIFIER]})`);oi("PRERELEASEIDENTIFIERLOOSE",`(?:${Rn[Cn.NONNUMERICIDENTIFIER]}|${Rn[Cn.NUMERICIDENTIFIERLOOSE]})`);oi("PRERELEASE",`(?:-(${Rn[Cn.PRERELEASEIDENTIFIER]}(?:\\.${Rn[Cn.PRERELEASEIDENTIFIER]})*))`);oi("PRERELEASELOOSE",`(?:-?(${Rn[Cn.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${Rn[Cn.PRERELEASEIDENTIFIERLOOSE]})*))`);oi("BUILDIDENTIFIER",`${i1e}+`);oi("BUILD",`(?:\\+(${Rn[Cn.BUILDIDENTIFIER]}(?:\\.${Rn[Cn.BUILDIDENTIFIER]})*))`);oi("FULLPLAIN",`v?${Rn[Cn.MAINVERSION]}${Rn[Cn.PRERELEASE]}?${Rn[Cn.BUILD]}?`);oi("FULL",`^${Rn[Cn.FULLPLAIN]}$`);oi("LOOSEPLAIN",`[v=\\s]*${Rn[Cn.MAINVERSIONLOOSE]}${Rn[Cn.PRERELEASELOOSE]}?${Rn[Cn.BUILD]}?`);oi("LOOSE",`^${Rn[Cn.LOOSEPLAIN]}$`);oi("GTLT","((?:<|>)?=?)");oi("XRANGEIDENTIFIERLOOSE",`${Rn[Cn.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);oi("XRANGEIDENTIFIER",`${Rn[Cn.NUMERICIDENTIFIER]}|x|X|\\*`);oi("XRANGEPLAIN",`[v=\\s]*(${Rn[Cn.XRANGEIDENTIFIER]})(?:\\.(${Rn[Cn.XRANGEIDENTIFIER]})(?:\\.(${Rn[Cn.XRANGEIDENTIFIER]})(?:${Rn[Cn.PRERELEASE]})?${Rn[Cn.BUILD]}?)?)?`);oi("XRANGEPLAINLOOSE",`[v=\\s]*(${Rn[Cn.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Rn[Cn.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Rn[Cn.XRANGEIDENTIFIERLOOSE]})(?:${Rn[Cn.PRERELEASELOOSE]})?${Rn[Cn.BUILD]}?)?)?`);oi("XRANGE",`^${Rn[Cn.GTLT]}\\s*${Rn[Cn.XRANGEPLAIN]}$`);oi("XRANGELOOSE",`^${Rn[Cn.GTLT]}\\s*${Rn[Cn.XRANGEPLAINLOOSE]}$`);oi("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r1e}})(?:\\.(\\d{1,${r1e}}))?(?:\\.(\\d{1,${r1e}}))?`);oi("COERCE",`${Rn[Cn.COERCEPLAIN]}(?:$|[^\\d])`);oi("COERCEFULL",Rn[Cn.COERCEPLAIN]+`(?:${Rn[Cn.PRERELEASE]})?(?:${Rn[Cn.BUILD]})?(?:$|[^\\d])`);oi("COERCERTL",Rn[Cn.COERCE],!0);oi("COERCERTLFULL",Rn[Cn.COERCEFULL],!0);oi("LONETILDE","(?:~>?)");oi("TILDETRIM",`(\\s*)${Rn[Cn.LONETILDE]}\\s+`,!0);f0.tildeTrimReplace="$1~";oi("TILDE",`^${Rn[Cn.LONETILDE]}${Rn[Cn.XRANGEPLAIN]}$`);oi("TILDELOOSE",`^${Rn[Cn.LONETILDE]}${Rn[Cn.XRANGEPLAINLOOSE]}$`);oi("LONECARET","(?:\\^)");oi("CARETTRIM",`(\\s*)${Rn[Cn.LONECARET]}\\s+`,!0);f0.caretTrimReplace="$1^";oi("CARET",`^${Rn[Cn.LONECARET]}${Rn[Cn.XRANGEPLAIN]}$`);oi("CARETLOOSE",`^${Rn[Cn.LONECARET]}${Rn[Cn.XRANGEPLAINLOOSE]}$`);oi("COMPARATORLOOSE",`^${Rn[Cn.GTLT]}\\s*(${Rn[Cn.LOOSEPLAIN]})$|^$`);oi("COMPARATOR",`^${Rn[Cn.GTLT]}\\s*(${Rn[Cn.FULLPLAIN]})$|^$`);oi("COMPARATORTRIM",`(\\s*)${Rn[Cn.GTLT]}\\s*(${Rn[Cn.LOOSEPLAIN]}|${Rn[Cn.XRANGEPLAIN]})`,!0);f0.comparatorTrimReplace="$1$2$3";oi("HYPHENRANGE",`^\\s*(${Rn[Cn.XRANGEPLAIN]})\\s+-\\s+(${Rn[Cn.XRANGEPLAIN]})\\s*$`);oi("HYPHENRANGELOOSE",`^\\s*(${Rn[Cn.XRANGEPLAINLOOSE]})\\s+-\\s+(${Rn[Cn.XRANGEPLAINLOOSE]})\\s*$`);oi("STAR","(<|>)?=?\\s*\\*");oi("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");oi("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var EB=le((Tti,VXe)=>{"use strict";var pgn=Object.freeze({loose:!0}),hgn=Object.freeze({}),mgn=a(e=>e?typeof e!="object"?pgn:e:hgn,"parseOptions");VXe.exports=mgn});var s1e=le((Iti,JXe)=>{"use strict";var KXe=/^[0-9]+$/,QXe=a((e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let n=KXe.test(e),r=KXe.test(t);return n&&r&&(e=+e,t=+t),e===t?0:n&&!r?-1:r&&!n?1:e<t?-1:1},"compareIdentifiers"),fgn=a((e,t)=>QXe(t,e),"rcompareIdentifiers");JXe.exports={compareIdentifiers:QXe,rcompareIdentifiers:fgn}});var Pc=le((Cti,YXe)=>{"use strict";var TB=C9(),{MAX_LENGTH:XXe,MAX_SAFE_INTEGER:AB}=W4(),{safeRe:IB,t:RB}=B4(),ggn=EB(),{compareIdentifiers:o1e}=s1e(),ygn=a((e,t)=>{let n=t.split(".");if(n.length>e.length)return!1;for(let r=0;r<n.length;r++)if(o1e(e[r],n[r])!==0)return!1;return!0},"isPrereleaseIdentifier"),a1e=class e{static{a(this,"SemVer")}constructor(t,n){if(n=ggn(n),t instanceof e){if(t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>XXe)throw new TypeError(`version is longer than ${XXe} characters`);TB("SemVer",t,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let r=t.trim().match(n.loose?IB[RB.LOOSE]:IB[RB.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>AB||this.major<0)throw new TypeError("Invalid major version");if(this.minor>AB||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>AB||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;if(s>=0&&s<AB)return s}return i}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(TB("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let n=0;do{let r=this.prerelease[n],i=t.prerelease[n];if(TB("prerelease compare",n,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r===i)continue;return o1e(r,i)}while(++n)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let n=0;do{let r=this.build[n],i=t.build[n];if(TB("build compare",n,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r===i)continue;return o1e(r,i)}while(++n)}inc(t,n,r){if(t.startsWith("pre")){if(!n&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(n){let i=`-${n}`.match(this.options.loose?IB[RB.PRERELEASELOOSE]:IB[RB.PRERELEASE]);if(!i||i[1]!==n)throw new Error(`invalid identifier: ${n}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,r),this.inc("pre",n,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",n,r),this.inc("pre",n,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(n===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(n){let s=[n,i];if(r===!1&&(s=[n]),ygn(this.prerelease,n)){let o=this.prerelease[n.split(".").length];isNaN(o)&&(this.prerelease=s)}else this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};YXe.exports=a1e});var W2=le((Oti,eYe)=>{"use strict";var ZXe=Pc(),vgn=a((e,t,n=!1)=>{if(e instanceof ZXe)return e;try{return new ZXe(e,t)}catch(r){if(!n)return null;throw r}},"parse");eYe.exports=vgn});var nYe=le((Nti,tYe)=>{"use strict";var xgn=W2(),bgn=a((e,t)=>{let n=xgn(e,t);return n?n.version:null},"valid");tYe.exports=bgn});var iYe=le(($ti,rYe)=>{"use strict";var wgn=W2(),kgn=a((e,t)=>{let n=wgn(e.trim().replace(/^[=v]+/,""),t);return n?n.version:null},"clean");rYe.exports=kgn});var aYe=le((jti,oYe)=>{"use strict";var sYe=Pc(),Sgn=a((e,t,n,r,i)=>{typeof n=="string"&&(i=r,r=n,n=void 0);try{return new sYe(e instanceof sYe?e.version:e,n).inc(t,r,i).version}catch{return null}},"inc");oYe.exports=Sgn});var uYe=le((Uti,cYe)=>{"use strict";var lYe=W2(),_gn=a((e,t)=>{let n=lYe(e,null,!0),r=lYe(t,null,!0),i=n.compare(r);if(i===0)return null;let s=i>0,o=s?n:r,l=s?r:n,c=!!o.prerelease.length;if(!!l.prerelease.length&&!c){if(!l.patch&&!l.minor)return"major";if(l.compareMain(o)===0)return l.minor&&!l.patch?"minor":"patch"}let d=c?"pre":"";return n.major!==r.major?d+"major":n.minor!==r.minor?d+"minor":n.patch!==r.patch?d+"patch":"prerelease"},"diff");cYe.exports=_gn});var pYe=le((Wti,dYe)=>{"use strict";var Egn=Pc(),Tgn=a((e,t)=>new Egn(e,t).major,"major");dYe.exports=Tgn});var mYe=le((zti,hYe)=>{"use strict";var Agn=Pc(),Ign=a((e,t)=>new Agn(e,t).minor,"minor");hYe.exports=Ign});var gYe=le((Gti,fYe)=>{"use strict";var Rgn=Pc(),Cgn=a((e,t)=>new Rgn(e,t).patch,"patch");fYe.exports=Cgn});var vYe=le((Kti,yYe)=>{"use strict";var Pgn=W2(),Ogn=a((e,t)=>{let n=Pgn(e,t);return n&&n.prerelease.length?n.prerelease:null},"prerelease");yYe.exports=Ogn});var Wh=le((Jti,bYe)=>{"use strict";var xYe=Pc(),Mgn=a((e,t,n)=>new xYe(e,n).compare(new xYe(t,n)),"compare");bYe.exports=Mgn});var kYe=le((Yti,wYe)=>{"use strict";var Ngn=Wh(),Dgn=a((e,t,n)=>Ngn(t,e,n),"rcompare");wYe.exports=Dgn});var _Ye=le((eni,SYe)=>{"use strict";var $gn=Wh(),Lgn=a((e,t)=>$gn(e,t,!0),"compareLoose");SYe.exports=Lgn});var CB=le((nni,TYe)=>{"use strict";var EYe=Pc(),jgn=a((e,t,n)=>{let r=new EYe(e,n),i=new EYe(t,n);return r.compare(i)||r.compareBuild(i)},"compareBuild");TYe.exports=jgn});var IYe=le((ini,AYe)=>{"use strict";var Fgn=CB(),Ugn=a((e,t)=>e.sort((n,r)=>Fgn(n,r,t)),"sort");AYe.exports=Ugn});var CYe=le((oni,RYe)=>{"use strict";var qgn=CB(),Wgn=a((e,t)=>e.sort((n,r)=>qgn(r,n,t)),"rsort");RYe.exports=Wgn});var P9=le((lni,PYe)=>{"use strict";var Bgn=Wh(),zgn=a((e,t,n)=>Bgn(e,t,n)>0,"gt");PYe.exports=zgn});var PB=le((uni,OYe)=>{"use strict";var Hgn=Wh(),Ggn=a((e,t,n)=>Hgn(e,t,n)<0,"lt");OYe.exports=Ggn});var l1e=le((pni,MYe)=>{"use strict";var Vgn=Wh(),Kgn=a((e,t,n)=>Vgn(e,t,n)===0,"eq");MYe.exports=Kgn});var c1e=le((mni,NYe)=>{"use strict";var Qgn=Wh(),Jgn=a((e,t,n)=>Qgn(e,t,n)!==0,"neq");NYe.exports=Jgn});var OB=le((gni,DYe)=>{"use strict";var Xgn=Wh(),Ygn=a((e,t,n)=>Xgn(e,t,n)>=0,"gte");DYe.exports=Ygn});var MB=le((vni,$Ye)=>{"use strict";var Zgn=Wh(),e0n=a((e,t,n)=>Zgn(e,t,n)<=0,"lte");$Ye.exports=e0n});var u1e=le((bni,LYe)=>{"use strict";var t0n=l1e(),n0n=c1e(),r0n=P9(),i0n=OB(),s0n=PB(),o0n=MB(),a0n=a((e,t,n,r)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof n=="object"&&(n=n.version),e===n;case"!==":return typeof e=="object"&&(e=e.version),typeof n=="object"&&(n=n.version),e!==n;case"":case"=":case"==":return t0n(e,n,r);case"!=":return n0n(e,n,r);case">":return r0n(e,n,r);case">=":return i0n(e,n,r);case"<":return s0n(e,n,r);case"<=":return o0n(e,n,r);default:throw new TypeError(`Invalid operator: ${t}`)}},"cmp");LYe.exports=a0n});var FYe=le((kni,jYe)=>{"use strict";var l0n=Pc(),c0n=W2(),{safeRe:NB,t:DB}=B4(),u0n=a((e,t)=>{if(e instanceof l0n)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let n=null;if(!t.rtl)n=e.match(t.includePrerelease?NB[DB.COERCEFULL]:NB[DB.COERCE]);else{let c=t.includePrerelease?NB[DB.COERCERTLFULL]:NB[DB.COERCERTL],u;for(;(u=c.exec(e))&&(!n||n.index+n[0].length!==e.length);)(!n||u.index+u[0].length!==n.index+n[0].length)&&(n=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(n===null)return null;let r=n[2],i=n[3]||"0",s=n[4]||"0",o=t.includePrerelease&&n[5]?`-${n[5]}`:"",l=t.includePrerelease&&n[6]?`+${n[6]}`:"";return c0n(`${r}.${i}.${s}${o}${l}`,t)},"coerce");jYe.exports=u0n});var qYe=le((_ni,UYe)=>{"use strict";var d0n=W2(),p0n=W4(),h0n=Pc(),m0n=a((e,t,n)=>{if(!p0n.RELEASE_TYPES.includes(t))return null;let r=f0n(e,n);return r&&g0n(r,t)},"truncate"),f0n=a((e,t)=>{let n=e instanceof h0n?e.version:e;return d0n(n,t)},"cloneInputVersion"),g0n=a((e,t)=>{if(y0n(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0;break}return e.format()},"doTruncation"),y0n=a(e=>e.startsWith("pre"),"isPrerelease");UYe.exports=m0n});var BYe=le((Tni,WYe)=>{"use strict";var d1e=class{static{a(this,"LRUCache")}constructor(){this.max=1e3,this.map=new Map}get(t){let n=this.map.get(t);if(n!==void 0)return this.map.delete(t),this.map.set(t,n),n}delete(t){return this.map.delete(t)}set(t,n){if(!this.delete(t)&&n!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(t,n)}return this}};WYe.exports=d1e});var Bh=le((Ini,VYe)=>{"use strict";var v0n=/\s+/g,p1e=class e{static{a(this,"Range")}constructor(t,n){if(n=b0n(n),t instanceof e)return t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease?t:new e(t.raw,n);if(t instanceof h1e)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=t.trim().replace(v0n," "),this.set=this.raw.split("||").map(r=>this.parseRange(r.trim())).filter(r=>r.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let r=this.set[0];if(this.set=this.set.filter(i=>!HYe(i[0])),this.set.length===0)this.set=[r];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&R0n(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let n=this.set[t];for(let r=0;r<n.length;r++)r>0&&(this.formatted+=" "),this.formatted+=n[r].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(I0n,"");let r=((this.options.includePrerelease&&T0n)|(this.options.loose&&A0n))+":"+t,i=zYe.get(r);if(i)return i;let s=this.options.loose,o=s?ad[Oc.HYPHENRANGELOOSE]:ad[Oc.HYPHENRANGE];t=t.replace(o,U0n(this.options.includePrerelease)),Uo("hyphen replace",t),t=t.replace(ad[Oc.COMPARATORTRIM],S0n),Uo("comparator trim",t),t=t.replace(ad[Oc.TILDETRIM],_0n),Uo("tilde trim",t),t=t.replace(ad[Oc.CARETTRIM],E0n),Uo("caret trim",t);let l=t.split(" ").map(p=>C0n(p,this.options)).join(" ").split(/\s+/).map(p=>F0n(p,this.options));s&&(l=l.filter(p=>(Uo("loose invalid filter",p,this.options),!!p.match(ad[Oc.COMPARATORLOOSE])))),Uo("range list",l);let c=new Map,u=l.map(p=>new h1e(p,this.options));for(let p of u){if(HYe(p))return[p];c.set(p.value,p)}c.size>1&&c.has("")&&c.delete("");let d=[...c.values()];return zYe.set(r,d),d}intersects(t,n){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(r=>GYe(r,n)&&t.set.some(i=>GYe(i,n)&&r.every(s=>i.every(o=>s.intersects(o,n)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new w0n(t,this.options)}catch{return!1}for(let n=0;n<this.set.length;n++)if(q0n(this.set[n],t,this.options))return!0;return!1}};VYe.exports=p1e;var x0n=BYe(),zYe=new x0n,b0n=EB(),h1e=O9(),Uo=C9(),w0n=Pc(),{safeRe:ad,src:k0n,t:Oc,comparatorTrimReplace:S0n,tildeTrimReplace:_0n,caretTrimReplace:E0n}=B4(),{FLAG_INCLUDE_PRERELEASE:T0n,FLAG_LOOSE:A0n}=W4(),I0n=new RegExp(k0n[Oc.BUILD],"g"),HYe=a(e=>e.value==="<0.0.0-0","isNullSet"),R0n=a(e=>e.value==="","isAny"),GYe=a((e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(s=>i.intersects(s,t)),i=r.pop();return n},"isSatisfiable"),C0n=a((e,t)=>(e=e.replace(ad[Oc.BUILD],""),Uo("comp",e,t),e=N0n(e,t),Uo("caret",e),e=O0n(e,t),Uo("tildes",e),e=$0n(e,t),Uo("xrange",e),e=j0n(e,t),Uo("stars",e),e),"parseComparator"),Nl=a(e=>!e||e.toLowerCase()==="x"||e==="*","isX"),P0n=a((e,t,n)=>Nl(e)&&!Nl(t)||Nl(t)&&n&&!Nl(n),"invalidXRangeOrder"),O0n=a((e,t)=>e.trim().split(/\s+/).map(n=>M0n(n,t)).join(" "),"replaceTildes"),M0n=a((e,t)=>{let n=t.loose?ad[Oc.TILDELOOSE]:ad[Oc.TILDE],r=t.includePrerelease?"-0":"";return e.replace(n,(i,s,o,l,c)=>{Uo("tilde",e,i,s,o,l,c);let u;return Nl(s)?u="":Nl(o)?u=`>=${s}.0.0${r} <${+s+1}.0.0-0`:Nl(l)?u=`>=${s}.${o}.0${r} <${s}.${+o+1}.0-0`:c?(Uo("replaceTilde pr",c),u=`>=${s}.${o}.${l}-${c} <${s}.${+o+1}.0-0`):u=`>=${s}.${o}.${l} <${s}.${+o+1}.0-0`,Uo("tilde return",u),u})},"replaceTilde"),N0n=a((e,t)=>e.trim().split(/\s+/).map(n=>D0n(n,t)).join(" "),"replaceCarets"),D0n=a((e,t)=>{Uo("caret",e,t);let n=t.loose?ad[Oc.CARETLOOSE]:ad[Oc.CARET],r=t.includePrerelease?"-0":"";return e.replace(n,(i,s,o,l,c)=>{Uo("caret",e,i,s,o,l,c);let u;return Nl(s)?u="":Nl(o)?u=`>=${s}.0.0${r} <${+s+1}.0.0-0`:Nl(l)?s==="0"?u=`>=${s}.${o}.0${r} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.0${r} <${+s+1}.0.0-0`:c?(Uo("replaceCaret pr",c),s==="0"?o==="0"?u=`>=${s}.${o}.${l}-${c} <${s}.${o}.${+l+1}-0`:u=`>=${s}.${o}.${l}-${c} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${l}-${c} <${+s+1}.0.0-0`):(Uo("no pr"),s==="0"?o==="0"?u=`>=${s}.${o}.${l} <${s}.${o}.${+l+1}-0`:u=`>=${s}.${o}.${l} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${l} <${+s+1}.0.0-0`),Uo("caret return",u),u})},"replaceCaret"),$0n=a((e,t)=>(Uo("replaceXRanges",e,t),e.split(/\s+/).map(n=>L0n(n,t)).join(" ")),"replaceXRanges"),L0n=a((e,t)=>{e=e.trim();let n=t.loose?ad[Oc.XRANGELOOSE]:ad[Oc.XRANGE];return e.replace(n,(r,i,s,o,l,c)=>{if(Uo("xRange",e,r,i,s,o,l,c),P0n(s,o,l))return e;let u=Nl(s),d=u||Nl(o),p=d||Nl(l),h=p;return i==="="&&h&&(i=""),c=t.includePrerelease?"-0":"",u?i===">"||i==="<"?r="<0.0.0-0":r="*":i&&h?(d&&(o=0),l=0,i===">"?(i=">=",d?(s=+s+1,o=0,l=0):(o=+o+1,l=0)):i==="<="&&(i="<",d?s=+s+1:o=+o+1),i==="<"&&(c="-0"),r=`${i+s}.${o}.${l}${c}`):d?r=`>=${s}.0.0${c} <${+s+1}.0.0-0`:p&&(r=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),Uo("xRange return",r),r})},"replaceXRange"),j0n=a((e,t)=>(Uo("replaceStars",e,t),e.trim().replace(ad[Oc.STAR],"")),"replaceStars"),F0n=a((e,t)=>(Uo("replaceGTE0",e,t),e.trim().replace(ad[t.includePrerelease?Oc.GTE0PRE:Oc.GTE0],"")),"replaceGTE0"),U0n=a(e=>(t,n,r,i,s,o,l,c,u,d,p,h)=>(Nl(r)?n="":Nl(i)?n=`>=${r}.0.0${e?"-0":""}`:Nl(s)?n=`>=${r}.${i}.0${e?"-0":""}`:o?n=`>=${n}`:n=`>=${n}${e?"-0":""}`,Nl(u)?c="":Nl(d)?c=`<${+u+1}.0.0-0`:Nl(p)?c=`<${u}.${+d+1}.0-0`:h?c=`<=${u}.${d}.${p}-${h}`:e?c=`<${u}.${d}.${+p+1}-0`:c=`<=${c}`,`${n} ${c}`.trim()),"hyphenReplace"),q0n=a((e,t,n)=>{for(let r=0;r<e.length;r++)if(!e[r].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let r=0;r<e.length;r++)if(Uo(e[r].semver),e[r].semver!==h1e.ANY&&e[r].semver.prerelease.length>0){let i=e[r].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0},"testSet")});var O9=le((Cni,ZYe)=>{"use strict";var M9=Symbol("SemVer ANY"),g1e=class e{static{a(this,"Comparator")}static get ANY(){return M9}constructor(t,n){if(n=KYe(n),t instanceof e){if(t.loose===!!n.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),f1e("comparator",t,n),this.options=n,this.loose=!!n.loose,this.parse(t),this.semver===M9?this.value="":this.value=this.operator+this.semver.version,f1e("comp",this)}parse(t){let n=this.options.loose?QYe[JYe.COMPARATORLOOSE]:QYe[JYe.COMPARATOR],r=t.match(n);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=r[1]!==void 0?r[1]:"",this.operator==="="&&(this.operator=""),r[2]?this.semver=new XYe(r[2],this.options.loose):this.semver=M9}toString(){return this.value}test(t){if(f1e("Comparator.test",t,this.options.loose),this.semver===M9||t===M9)return!0;if(typeof t=="string")try{t=new XYe(t,this.options)}catch{return!1}return m1e(t,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new YYe(t.value,n).test(this.value):t.operator===""?t.value===""?!0:new YYe(this.value,n).test(t.semver):(n=KYe(n),n.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!n.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||m1e(this.semver,"<",t.semver,n)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||m1e(this.semver,">",t.semver,n)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};ZYe.exports=g1e;var KYe=EB(),{safeRe:QYe,t:JYe}=B4(),m1e=u1e(),f1e=C9(),XYe=Pc(),YYe=Bh()});var N9=le((Oni,eZe)=>{"use strict";var W0n=Bh(),B0n=a((e,t,n)=>{try{t=new W0n(t,n)}catch{return!1}return t.test(e)},"satisfies");eZe.exports=B0n});var nZe=le((Nni,tZe)=>{"use strict";var z0n=Bh(),H0n=a((e,t)=>new z0n(e,t).set.map(n=>n.map(r=>r.value).join(" ").trim().split(" ")),"toComparators");tZe.exports=H0n});var iZe=le(($ni,rZe)=>{"use strict";var G0n=Pc(),V0n=Bh(),K0n=a((e,t,n)=>{let r=null,i=null,s=null;try{s=new V0n(t,n)}catch{return null}return e.forEach(o=>{s.test(o)&&(!r||i.compare(o)===-1)&&(r=o,i=new G0n(r,n))}),r},"maxSatisfying");rZe.exports=K0n});var oZe=le((jni,sZe)=>{"use strict";var Q0n=Pc(),J0n=Bh(),X0n=a((e,t,n)=>{let r=null,i=null,s=null;try{s=new J0n(t,n)}catch{return null}return e.forEach(o=>{s.test(o)&&(!r||i.compare(o)===1)&&(r=o,i=new Q0n(r,n))}),r},"minSatisfying");sZe.exports=X0n});var cZe=le((Uni,lZe)=>{"use strict";var y1e=Pc(),Y0n=Bh(),aZe=P9(),Z0n=a((e,t)=>{e=new Y0n(e,t);let n=new y1e("0.0.0");if(e.test(n)||(n=new y1e("0.0.0-0"),e.test(n)))return n;n=null;for(let r=0;r<e.set.length;++r){let i=e.set[r],s=null;i.forEach(o=>{let l=new y1e(o.semver.version);switch(o.operator){case">":l.prerelease.length===0?l.patch++:l.prerelease.push(0),l.raw=l.format();case"":case">=":(!s||aZe(l,s))&&(s=l);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!n||aZe(n,s))&&(n=s)}return n&&e.test(n)?n:null},"minVersion");lZe.exports=Z0n});var dZe=le((Wni,uZe)=>{"use strict";var e1n=Bh(),t1n=a((e,t)=>{try{return new e1n(e,t).range||"*"}catch{return null}},"validRange");uZe.exports=t1n});var $B=le((zni,fZe)=>{"use strict";var n1n=Pc(),mZe=O9(),{ANY:r1n}=mZe,i1n=Bh(),s1n=N9(),pZe=P9(),hZe=PB(),o1n=MB(),a1n=OB(),l1n=a((e,t,n,r)=>{e=new n1n(e,r),t=new i1n(t,r);let i,s,o,l,c;switch(n){case">":i=pZe,s=o1n,o=hZe,l=">",c=">=";break;case"<":i=hZe,s=a1n,o=pZe,l="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s1n(e,t,r))return!1;for(let u=0;u<t.set.length;++u){let d=t.set[u],p=null,h=null;if(d.forEach(m=>{m.semver===r1n&&(m=new mZe(">=0.0.0")),p=p||m,h=h||m,i(m.semver,p.semver,r)?p=m:o(m.semver,h.semver,r)&&(h=m)}),p.operator===l||p.operator===c||(!h.operator||h.operator===l)&&s(e,h.semver))return!1;if(h.operator===c&&o(e,h.semver))return!1}return!0},"outside");fZe.exports=l1n});var yZe=le((Gni,gZe)=>{"use strict";var c1n=$B(),u1n=a((e,t,n)=>c1n(e,t,">",n),"gtr");gZe.exports=u1n});var xZe=le((Kni,vZe)=>{"use strict";var d1n=$B(),p1n=a((e,t,n)=>d1n(e,t,"<",n),"ltr");vZe.exports=p1n});var kZe=le((Jni,wZe)=>{"use strict";var bZe=Bh(),h1n=a((e,t,n)=>(e=new bZe(e,n),t=new bZe(t,n),e.intersects(t,n)),"intersects");wZe.exports=h1n});var _Ze=le((Yni,SZe)=>{"use strict";var m1n=N9(),f1n=Wh();SZe.exports=(e,t,n)=>{let r=[],i=null,s=null,o=e.sort((d,p)=>f1n(d,p,n));for(let d of o)m1n(d,t,n)?(s=d,i||(i=d)):(s&&r.push([i,s]),s=null,i=null);i&&r.push([i,null]);let l=[];for(let[d,p]of r)d===p?l.push(d):!p&&d===o[0]?l.push("*"):p?d===o[0]?l.push(`<=${p}`):l.push(`${d} - ${p}`):l.push(`>=${d}`);let c=l.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return c.length<u.length?c:t}});var CZe=le((Zni,RZe)=>{"use strict";var EZe=Bh(),b1e=O9(),{ANY:v1e}=b1e,x1e=N9(),w1e=Wh(),g1n=a((e,t,n={})=>{if(e===t)return!0;e=new EZe(e,n),t=new EZe(t,n);let r=!1;e:for(let i of e.set){for(let s of t.set){let o=v1n(i,s,n);if(r=r||o!==null,o)continue e}if(r)return!1}return!0},"subset"),y1n=[new b1e(">=0.0.0-0")],TZe=[new b1e(">=0.0.0")],v1n=a((e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===v1e){if(t.length===1&&t[0].semver===v1e)return!0;n.includePrerelease?e=y1n:e=TZe}if(t.length===1&&t[0].semver===v1e){if(n.includePrerelease)return!0;t=TZe}let r=new Set,i,s;for(let m of e)m.operator===">"||m.operator===">="?i=AZe(i,m,n):m.operator==="<"||m.operator==="<="?s=IZe(s,m,n):r.add(m.semver);if(r.size>1)return null;let o;if(i&&s){if(o=w1e(i.semver,s.semver,n),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let m of r){if(i&&!x1e(m,String(i),n)||s&&!x1e(m,String(s),n))return null;for(let g of t)if(!x1e(m,String(g),n))return!1;return!0}let l,c,u,d,p=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1,h=i&&!n.includePrerelease&&i.semver.prerelease.length?i.semver:!1;p&&p.prerelease.length===1&&s.operator==="<"&&p.prerelease[0]===0&&(p=!1);for(let m of t){if(d=d||m.operator===">"||m.operator===">=",u=u||m.operator==="<"||m.operator==="<=",i){if(h&&m.semver.prerelease&&m.semver.prerelease.length&&m.semver.major===h.major&&m.semver.minor===h.minor&&m.semver.patch===h.patch&&(h=!1),m.operator===">"||m.operator===">="){if(l=AZe(i,m,n),l===m&&l!==i)return!1}else if(i.operator===">="&&!m.test(i.semver))return!1}if(s){if(p&&m.semver.prerelease&&m.semver.prerelease.length&&m.semver.major===p.major&&m.semver.minor===p.minor&&m.semver.patch===p.patch&&(p=!1),m.operator==="<"||m.operator==="<="){if(c=IZe(s,m,n),c===m&&c!==s)return!1}else if(s.operator==="<="&&!m.test(s.semver))return!1}if(!m.operator&&(s||i)&&o!==0)return!1}return!(i&&u&&!s&&o!==0||s&&d&&!i&&o!==0||h||p)},"simpleSubset"),AZe=a((e,t,n)=>{if(!e)return t;let r=w1e(e.semver,t.semver,n);return r>0?e:r<0||t.operator===">"&&e.operator===">="?t:e},"higherGT"),IZe=a((e,t,n)=>{if(!e)return t;let r=w1e(e.semver,t.semver,n);return r<0?e:r>0||t.operator==="<"&&e.operator==="<="?t:e},"lowerLT");RZe.exports=g1n});var NZe=le((tri,MZe)=>{"use strict";var k1e=B4(),PZe=W4(),x1n=Pc(),OZe=s1e(),b1n=W2(),w1n=nYe(),k1n=iYe(),S1n=aYe(),_1n=uYe(),E1n=pYe(),T1n=mYe(),A1n=gYe(),I1n=vYe(),R1n=Wh(),C1n=kYe(),P1n=_Ye(),O1n=CB(),M1n=IYe(),N1n=CYe(),D1n=P9(),$1n=PB(),L1n=l1e(),j1n=c1e(),F1n=OB(),U1n=MB(),q1n=u1e(),W1n=FYe(),B1n=qYe(),z1n=O9(),H1n=Bh(),G1n=N9(),V1n=nZe(),K1n=iZe(),Q1n=oZe(),J1n=cZe(),X1n=dZe(),Y1n=$B(),Z1n=yZe(),eyn=xZe(),tyn=kZe(),nyn=_Ze(),ryn=CZe();MZe.exports={parse:b1n,valid:w1n,clean:k1n,inc:S1n,diff:_1n,major:E1n,minor:T1n,patch:A1n,prerelease:I1n,compare:R1n,rcompare:C1n,compareLoose:P1n,compareBuild:O1n,sort:M1n,rsort:N1n,gt:D1n,lt:$1n,eq:L1n,neq:j1n,gte:F1n,lte:U1n,cmp:q1n,coerce:W1n,truncate:B1n,Comparator:z1n,Range:H1n,satisfies:G1n,toComparators:V1n,maxSatisfying:K1n,minSatisfying:Q1n,minVersion:J1n,validRange:X1n,outside:Y1n,gtr:Z1n,ltr:eyn,intersects:tyn,simplifyRange:nyn,subset:ryn,SemVer:x1n,re:k1e.re,src:k1e.src,tokens:k1e.t,SEMVER_SPEC_VERSION:PZe.SEMVER_SPEC_VERSION,RELEASE_TYPES:PZe.RELEASE_TYPES,compareIdentifiers:OZe.compareIdentifiers,rcompareIdentifiers:OZe.rcompareIdentifiers}});var SH,U1e,wa,Cf=F(()=>{SH=class{static{a(this,"FifoQueue")}incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(t){this.incoming.push(t)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},U1e=class{static{a(this,"EventStream")}queue=new SH;waiting=new SH;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(t,n){this.isComplete=t,this.extractResult=n,this.finalResultPromise=new Promise(r=>{this.resolveFinalResult=r})}push(t){if(this.done)return;this.isComplete(t)&&(this.done=!0,this.resolveFinalResult(this.extractResult(t)));let n=this.waiting.dequeue();n?n({value:t,done:!1}):this.queue.enqueue(t)}end(t){for(this.done=!0,t!==void 0&&this.resolveFinalResult(t);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let t=await new Promise(n=>this.waiting.enqueue(n));if(t.done)return;yield t.value}}}result(){return this.finalResultPromise}},wa=class extends U1e{static{a(this,"AssistantMessageEventStream")}#e=Date.now();#n=performance.now();constructor(){super(t=>t.type==="done"||t.type==="error",t=>{if(t.type==="done")return t.message;if(t.type==="error")return t.error;throw new Error("Unexpected event type for final result")})}push(t){t.type==="done"?this.#r(t.message):t.type==="error"&&this.#r(t.error),super.push(t)}end(t){t!==void 0&&this.#r(t),super.end(t)}#r(t){this.done||t.durationMs!==void 0||t.timestamp<this.#e||(t.durationMs=Math.max(0,Math.round(performance.now()-this.#n)))}}});function f2n(e,t,n){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:n}}function g2n(e){return typeof e.result=="function"}async function y2n(e,t){for await(let n of t)e.push(n);e.end(g2n(t)?await t.result():void 0)}function zh(e,t){let n=Date.now(),r=new wa;return t().then(i=>y2n(r,i)).catch(i=>{let s=f2n(e,i,n);r.push({type:"error",reason:"error",error:s}),r.end(s)}),r}function ll(e,t){let n={stream:a((r,i,s)=>zh(r,async()=>(await e()).stream(r,i,s)),"stream"),streamSimple:a((r,i,s)=>zh(r,async()=>(await e()).streamSimple(r,i,s)),"streamSimple")};return t?.fetchDeferred&&(n.fetchDeferred=(r,i,s)=>zh(r,async()=>{let o=await e();if(!o.fetchDeferred)throw new Error("API does not support deferred responses");return o.fetchDeferred(r,i,s)})),t?.cancelDeferred&&(n.cancelDeferred=async(r,i,s)=>{let o=await e();if(!o.cancelDeferred)throw new Error("API cannot cancel deferred responses");await o.cancelDeferred(r,i,s)}),n}var Bp=F(()=>{Cf();a(f2n,"createSetupErrorMessage");a(g2n,"hasResult");a(y2n,"forwardStream");a(zh,"lazyStream");a(ll,"lazyApi")});function x2n(){return globalThis.process?.env}function rnt(){return{async env(e){let t=x2n()?.[e];return typeof t=="string"&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await nnt("node:fs/promises"),n=e;return n.startsWith("~")&&(n=(await nnt("node:os")).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}var v2n,nnt,int=F(()=>{v2n=function(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,r,i,s,o){return r?t?".jsx":".js":i&&(!s||!o)?n:i+s+"."+o.toLowerCase()+"js"}):e},nnt=a(e=>import(v2n(e)),"importNodeModule");a(x2n,"getProcessEnv");a(rnt,"defaultProviderAuthContext")});function snt(e){if(e.reason!==void 0)return e.reason;let t=new Error("The operation was aborted");return t.name="AbortError",t}function Hh(e){return e??new AbortController().signal}function Gh(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(snt(t))):new Promise((n,r)=>{let i=!1,s=a(()=>t.removeEventListener("abort",o),"cleanup"),o=a(()=>{i||(i=!0,s(),r(snt(t)))},"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(l=>{i||(i=!0,s(),n(l))},l=>{i||(i=!0,s(),r(l))}),t.aborted&&o()})}var _H=F(()=>{a(snt,"abortReason");a(Hh,"operationSignal");a(Gh,"raceWithAbortSignal")});var EH,ont=F(()=>{_H();EH=class{static{a(this,"InMemoryCredentialStore")}credentials=new Map;chains=new Map;enqueue(t,n,r){let i=Hh(r?.signal),s=this.chains.get(t)??Promise.resolve(),o=(async()=>(await s.catch(()=>{}),i.throwIfAborted(),n()))(),l=o.catch(()=>{});return this.chains.set(t,l),l.then(()=>{this.chains.get(t)===l&&this.chains.delete(t)}),Gh(o,i)}async read(t,n){return n?.signal?.throwIfAborted(),this.credentials.get(t)}async list(t){return t?.signal?.throwIfAborted(),[...this.credentials].map(([n,r])=>({providerId:n,type:r.type}))}modify(t,n,r){return this.enqueue(t,async()=>{let i=this.credentials.get(t),s=await n(i);return r?.signal?.throwIfAborted(),s!==void 0&&this.credentials.set(t,s),s??i},r)}delete(t,n){return this.enqueue(t,async()=>{this.credentials.delete(t)},n)}}});function B2(e){return e instanceof Error?e.message||e.name:typeof e=="string"?e:String(e)}function b2n(e){if(!(e instanceof Error))return{name:"ThrownValue",message:B2(e)};let t=e.code;return{name:e.name||void 0,message:e.message||e.name,stack:e.stack,code:typeof t=="string"||typeof t=="number"?t:void 0}}function TH(e,t,n){return{type:e,timestamp:Date.now(),error:b2n(t),details:n}}function z2(e,t){e.diagnostics=[...e.diagnostics??[],t]}var F9=F(()=>{a(B2,"formatThrownValue");a(b2n,"extractDiagnosticError");a(TH,"createAssistantMessageDiagnostic");a(z2,"appendAssistantMessageDiagnostic")});function w2n(e,t){if(t==null)return e;let n=B2(t).trim();return!n||e.includes(n)?e:`${e}: ${n}`}var Zi,AH=F(()=>{F9();Zi=class extends Error{static{a(this,"ModelsError")}code;constructor(t,n,r){super(w2n(n,r?.cause),r),this.name="ModelsError",this.code=t}};a(w2n,"withCauseDetail")});function W1e(e,t,n,r){let i=Hh(r?.signal);return Gh(k2n(e,t,n,r,i),i)}async function k2n(e,t,n,r,i){i.throwIfAborted();let s=r?.env?S2n(n,r.env):n;if(r?.apiKey!==void 0&&e.auth.apiKey)return q1e(s,e.auth.apiKey,e.id,{type:"api_key",key:r.apiKey,env:r.env},i);let o=await A2n(t,e.id,i);if(o){if(o.type==="oauth"&&e.auth.oauth)return T2n(t,e.id,e.auth.oauth,o,i,r?.minOAuthValidityMs);if(o.type==="api_key"&&e.auth.apiKey){let l=r?.env?{...o,env:{...o.env,...r.env}}:o;return q1e(s,e.auth.apiKey,e.id,l,i)}return}return e.auth.apiKey?q1e(s,e.auth.apiKey,e.id,void 0,i):void 0}function S2n(e,t){return{env:a(async n=>t[n]||await e.env(n),"env"),fileExists:a(n=>e.fileExists(n),"fileExists")}}async function B1e(e,t,n,r,i){let s,o=new AbortController,l=a(()=>o.abort(i.reason),"cancelLockWait");i.addEventListener("abort",l,{once:!0}),i.aborted&&l();try{s=await e.modify(t,async c=>{if(i.removeEventListener("abort",l),i.throwIfAborted(),c?.type==="oauth"&&r(c))try{return await n.refresh(c,AbortSignal.timeout(E2n))}catch(u){throw new Zi("oauth",`OAuth refresh failed for ${t}`,{cause:u})}},{signal:o.signal})}catch(c){throw c instanceof Zi?c:(i.throwIfAborted(),new Zi("auth",`Credential store modify failed for ${t}`,{cause:c}))}finally{i.removeEventListener("abort",l)}return s?.type==="oauth"?s:void 0}async function T2n(e,t,n,r,i,s){let o=Math.max(_2n,s??0),l=a(u=>Date.now()+o>=u.expires,"expiresSoon"),c=r;if(l(c)){let u=await B1e(e,t,n,l,i);if(!u)return;if(c=u,s!==void 0&&l(c))throw new Zi("oauth",`OAuth refresh returned a token that expires too soon for ${t}`)}try{return{auth:await n.toAuth(c),source:"OAuth"}}catch(u){throw new Zi("oauth",`OAuth auth derivation failed for ${t}`,{cause:u})}}async function q1e(e,t,n,r,i){try{return await t.resolve({ctx:e,credential:r,signal:i})}catch(s){throw new Zi("auth",`API key auth failed for provider ${n}`,{cause:s})}}async function A2n(e,t,n){try{return await e.read(t,{signal:n})}catch(r){throw new Zi("auth",`Credential store read failed for ${t}`,{cause:r})}}var _2n,E2n,ant=F(()=>{_H();AH();AH();a(W1e,"resolveProviderAuth");a(k2n,"resolveProviderAuthWithSignal");a(S2n,"overlayEnvAuthContext");_2n=300*1e3,E2n=15e3;a(B1e,"refreshStoredOAuthCredential");a(T2n,"resolveStoredOAuth");a(q1e,"resolveApiKey");a(A2n,"readCredential")});var IH,lnt=F(()=>{IH=class{static{a(this,"InMemoryModelsStore")}entries=new Map;async read(t,n){n?.signal?.throwIfAborted();let r=this.entries.get(t);return r?structuredClone(r):void 0}async write(t,n,r){r?.signal?.throwIfAborted(),this.entries.set(t,structuredClone(n))}async delete(t,n){n?.signal?.throwIfAborted(),this.entries.delete(t)}}});function K4(e){return e.type??"chat"}function Pf(e,t){return K4(e)===t}function cnt(e){if(!Pf(e,"chat"))throw new Zi("provider",`Model ${e.provider}/${e.id} is not a chat model`)}function unt(e){if(!Pf(e,"image"))throw new Zi("provider",`Model ${e.provider}/${e.id} is not an image model`)}function dnt(e){if(!Pf(e,"classifier"))throw new Zi("provider",`Model ${e.provider}/${e.id} is not a classifier model`)}function pnt(e,t){if(t.images?.length&&!e.input.includes("image"))throw new Zi("provider",`Model ${e.provider}/${e.id} does not accept image input`)}function z1e(e,t,n=!1){return{api:e.api,provider:e.provider,model:e.id,output:[],stopReason:n?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function H1e(e,t,n=!1){return{api:e.api,provider:e.provider,model:e.id,answers:{},stopReason:n?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}var G1e=F(()=>{AH();a(K4,"getModelType");a(Pf,"isModelType");a(cnt,"assertChatModel");a(unt,"assertImageModel");a(dnt,"assertClassifierModel");a(pnt,"assertClassifierInputSupported");a(z1e,"imageErrorResult");a(H1e,"classifierErrorResult")});function RH(e,t=`
169
169
  `){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join(t)}function Mc(e){let t=[RH(e.content)];for(let n of Object.values(e.sections??{}))n!==null&&t.push(n);return t.filter(n=>n.length>0).join(`
170
170
 
@@ -8543,7 +8543,7 @@ The web request used endpoint ${JSON.stringify(e)}. Search endpoint configuratio
8543
8543
  .error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
8544
8544
  .hint { margin: 1.5rem 0 0; font-size: .875rem; }
8545
8545
  code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
8546
- `}a(OTt,"pageStyles");F8();var aRe="enabled",lRe=Object.freeze({id:"direct",capabilities:Object.freeze(["bash"]),plan:"free",shell:"just-bash-direct",probe:a(e=>e.LOADER===void 0?"available":"needs-binding","probe")}),uD=Object.freeze({id:"dynamic-worker",capabilities:Object.freeze(["bash","coding"]),plan:"paid",shell:"just-bash-isolated",probe:a(e=>e.LOADER===void 0?"needs-binding":"available","probe")}),cRe=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===aRe?"available":"needs-binding","probe")}),j1r=Object.freeze([cRe,uD,lRe]);function uRe(e,t=j1r){return t.filter(n=>n.probe(e)==="available")}a(uRe,"availableEdgeRuntimeProviders");function dRe(e){let t=a(r=>e.find(i=>i.capabilities.includes(r)),"first"),n=t("bash");if(n===void 0)throw new Error("No available runtime provider serves the bash layer.");return{bash:n.id,container:t("container")?.id??null}}a(dRe,"resolveEdgeRuntimeSelection");function GZ(e){let t=uRe(e),{bash:n,container:r}=dRe(t);return t.find(i=>i.id===(r??n)).shell}a(GZ,"resolveEdgeRuntimeShell");function F1r(){return"dsh-edge@0.33.0/isolated"}a(F1r,"resolveEdgeDeploymentId");function NS(e){return{baseURL:f_e(e.DEEPSEEK_BASE_URL),maxTokens:v_e(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Yk(e.DEEPSEEK_MODEL),reasoningEffort:g_e(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:wN(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:y_e(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Mb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(NS,"resolveEdgeDeploymentConfig");function U1r(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(U1r,"edgeDeploymentApiKeyConfigured");function q1r(e){let t=f_e(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(q1r,"projectedEdgeBaseURL");function pRe(e,t){return{shell:GZ(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:F1r(),apiKeyConfigured:U1r(e),baseURL:q1r(e.DEEPSEEK_BASE_URL),maxTokens:v_e(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Yk(e.DEEPSEEK_MODEL),reasoningEffort:g_e(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:wN(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:y_e(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Mb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(pRe,"resolveEdgeDeploymentProfile");function VZ(e){NS(e);let t=pRe(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:x3,upstreamVersion:JGe,status:"ready"}}a(VZ,"resolveEdgeDeploymentHealth");var hRe={scanned:1e3,deleted:200};function MTt(e,t,n){let r=e.sql,s=r.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'vfs_meta'").toArray().length>0?r.exec("SELECT v FROM vfs_meta WHERE k = 'schema_version'").toArray()[0]?.v:void 0;if(s===void 0)return{deleted:0,bytes:0,complete:!0,skipped:"no-vfs"};if(s!==10)return console.warn(`dsh-edge: workspace storage schema ${String(s)} is not ${String(10)}; not reclaiming deleted content.`),{deleted:0,bytes:0,complete:!0,skipped:"schema"};let o=n===void 0?new Uint8Array(0):B1r(n),l=r.exec(`SELECT b.hash, b.size, b.last_seen,
8546
+ `}a(OTt,"pageStyles");F8();var aRe="enabled",lRe=Object.freeze({id:"direct",capabilities:Object.freeze(["bash"]),plan:"free",shell:"just-bash-direct",probe:a(e=>e.LOADER===void 0?"available":"needs-binding","probe")}),uD=Object.freeze({id:"dynamic-worker",capabilities:Object.freeze(["bash","coding"]),plan:"paid",shell:"just-bash-isolated",probe:a(e=>e.LOADER===void 0?"needs-binding":"available","probe")}),cRe=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===aRe?"available":"needs-binding","probe")}),j1r=Object.freeze([cRe,uD,lRe]);function uRe(e,t=j1r){return t.filter(n=>n.probe(e)==="available")}a(uRe,"availableEdgeRuntimeProviders");function dRe(e){let t=a(r=>e.find(i=>i.capabilities.includes(r)),"first"),n=t("bash");if(n===void 0)throw new Error("No available runtime provider serves the bash layer.");return{bash:n.id,container:t("container")?.id??null}}a(dRe,"resolveEdgeRuntimeSelection");function GZ(e){let t=uRe(e),{bash:n,container:r}=dRe(t);return t.find(i=>i.id===(r??n)).shell}a(GZ,"resolveEdgeRuntimeShell");function F1r(){return"dsh-edge@0.34.0/isolated"}a(F1r,"resolveEdgeDeploymentId");function NS(e){return{baseURL:f_e(e.DEEPSEEK_BASE_URL),maxTokens:v_e(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Yk(e.DEEPSEEK_MODEL),reasoningEffort:g_e(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:wN(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:y_e(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Mb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(NS,"resolveEdgeDeploymentConfig");function U1r(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(U1r,"edgeDeploymentApiKeyConfigured");function q1r(e){let t=f_e(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(q1r,"projectedEdgeBaseURL");function pRe(e,t){return{shell:GZ(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:F1r(),apiKeyConfigured:U1r(e),baseURL:q1r(e.DEEPSEEK_BASE_URL),maxTokens:v_e(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Yk(e.DEEPSEEK_MODEL),reasoningEffort:g_e(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:wN(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:y_e(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Mb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(pRe,"resolveEdgeDeploymentProfile");function VZ(e){NS(e);let t=pRe(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:x3,upstreamVersion:JGe,status:"ready"}}a(VZ,"resolveEdgeDeploymentHealth");var hRe={scanned:1e3,deleted:200};function MTt(e,t,n){let r=e.sql,s=r.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'vfs_meta'").toArray().length>0?r.exec("SELECT v FROM vfs_meta WHERE k = 'schema_version'").toArray()[0]?.v:void 0;if(s===void 0)return{deleted:0,bytes:0,complete:!0,skipped:"no-vfs"};if(s!==10)return console.warn(`dsh-edge: workspace storage schema ${String(s)} is not ${String(10)}; not reclaiming deleted content.`),{deleted:0,bytes:0,complete:!0,skipped:"schema"};let o=n===void 0?new Uint8Array(0):B1r(n),l=r.exec(`SELECT b.hash, b.size, b.last_seen,
8547
8547
  EXISTS (SELECT 1 FROM vfs_chunks c WHERE c.hash = b.hash) AS used
8548
8548
  FROM vfs_blobs b
8549
8549
  WHERE b.hash > ?