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.
- package/THIRD_PARTY_NOTICES.md +513 -513
- package/dist/index.html +1 -1
- package/dist/plugins/@deepseek-ai/dsh-client-ui-conversation/client.js +26 -11
- package/dist/plugins/@deepseek-ai/dsh-client-ui-settings-general/client.js +1 -1
- package/dist/plugins/@deepseek-ai/dsh-client-ui-sidebar/client.js +1 -1
- package/package.json +124 -124
- package/worker/direct/index.js +4 -4
- package/worker/isolated/index.js +3 -3
package/worker/direct/index.js
CHANGED
|
@@ -11,7 +11,7 @@ var Xqt=Object.create;var AU=Object.defineProperty;var Zqt=Object.getOwnProperty
|
|
|
11
11
|
`+e.map(t=>t.path?` - ${t.message} (at ${t.path.join(".")})`:` - ${t.message}`).join(`
|
|
12
12
|
`))}};Object.defineProperty($De.prototype,aVt,{value:!0});a(pF,"resolveConfig");UDe=new WeakMap;a(jse,"runDisposable");a(cVt,"emitPluginDisposed");dF=class FDe extends Error{static{a(this,"CordisError")}code;constructor(t,n){super(n??FDe.Code[t]),this.code=t}};(function(e){e.Code={INACTIVE_EFFECT:"cannot create effect on inactive context"}})(dF||(dF={}));C0="__INACTIVE__",jDe=class{static{a(this,"Fiber")}parent;inject;runtime;uid;ctx;config;_config;state=0;dispose;store;inertia;_hooks=Object.create(null);_disposables=new zse;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[Ns.intercept]=Object.create(e[Ns.intercept]);for(let[c,l]of o)Pa(l)||(this.ctx[Ns.intercept][c]=l)}this._runner={epoch:C0,getOuterStack:i,execute:a(function(){if(XGt(r.callback)){let c=new r.callback(this.ctx,this.config);for(let l of c?.[vn.initHooks]??[])l();return c?.[vn.init]?.()}else return r.callback(this.ctx,this.config)},"execute"),collect:s},this.dispose=e.fiber.effect(()=>{let c=r.fibers.push(this);return async()=>{for(this.uid=null,cVt(this.context,this),this.ctx.registry.has(r.callback)&&(c(),r.fibers.length||this.ctx.registry.delete(r.callback)),this._setEpoch(C0),this.inertia||this._updateState(()=>(this.inertia=this._unload(),5));this.inertia;)await this.inertia}},"ctx.plugin()");try{this.context.emit("internal/plugin",this)}catch(c){throw Promise.resolve(this.dispose()).catch(l=>this.ctx.logger.error(l)),c}if(this.uid!==null&&e.fiber.state!==5){for(let c of Object.keys(this.inject))this._checkImpl(c);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 dF("INACTIVE_EFFECT")}_execute(e){let t=e.epoch;return uF(n=>{let r=a(s=>{if(typeof s=="function")e.collect(s);else if(!Pa(s))throw new TypeError("Invalid effect")},"safeCollect"),i=e.execute.call(this);if(typeof i=="function")return e.collect(i);if(!Pa(i))if(tA(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 dF("INACTIVE_EFFECT");let n=[],r=!1,i,s=a(()=>{if(r)return i;r=!0;let E;for(let A of n.splice(0).reverse())if(E)E=E.then(()=>jse(A));else{let I=jse(A);tA(I)&&"then"in I&&(E=I)}return i=E},"dispose"),o={label:t,children:[]},c={execute:e,epoch:!0,collect:a(E=>{n.push(E),this._disposables.delete(E),E[vn.effect]&&o.children.push(E[vn.effect])},"collect"),getOuterStack:Vse()},l,u=!0,d,p,h,m=!1,f,g=a(()=>!1,"removeWrapper"),v=a(()=>(h??=new Promise((E,A)=>{d=E,p=A}),h),"waitForSetup"),x=a(E=>Promise.resolve(E).then(()=>s(),async A=>{throw await s(),A}),"disposeAfter"),b=a(E=>{let A;try{A=E()}catch(I){throw g(),I}if(tA(A)&&"then"in A){let I=Promise.resolve(A).finally(()=>{g(),f===I&&(f=void 0)});return f=I}return g(),A},"finalizeDisposal"),w=dm(()=>c.epoch?(c.epoch=!1,b(()=>u?x(v()):l?x(l):s())):m?f:void 0,vn.effect,o);UDe.set(w,()=>f),g=this._disposables.push(w);try{l=this._execute(c)}catch(E){u=!1,m=!0,c.epoch=!1;let A;try{A=b(s)}finally{p?.(E)}throw tA(A)&&"then"in A&&A.catch(I=>this.ctx.logger.error(I)),E}u=!1,h&&Promise.resolve(l).then(d,p),l?.catch(()=>c.epoch?b(s):s()).catch(E=>this.ctx.logger.error(E));let k=a(()=>{if(c.epoch)return c.epoch=!1,b(s)},"disposeAsync");return w.then=async(E,A)=>Promise.resolve(l).then(()=>k).then(E,A),w}getEffects(){return[...this._disposables].map(e=>e[vn.effect]).filter(Boolean)}_getState(){return this.uid===null?4:this._error?3:this._runner.epoch!==C0?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(P0(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=C0;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!==C0&&t===C0?(this.inertia=this._reload(),1):(this.inertia=this._unload(),5)))}_resolveConfig(e){return e=this.context.waterfall(this,"internal/config",e,()=>e),this.runtime?pF(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=C0}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 uF(async t=>{await Promise.resolve(),t.error=new Error,await jse(e)},this._runner.getOuterStack)}catch(t){this.ctx.logger.error(t)}})),this.store=void 0,this._updateState(()=>{if(this._runner.epoch===C0)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(C0),this._refresh(),await this.await()}update(e,t=!1){if(this.assertActive(),this._config=e,this.state!==2){this._error=void 0,this._setEpoch(C0),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(lVt,"isApplicable");a(pP,"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,vn.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})(pP||(pP={}));uVt=class{static{a(this,"RegistryService")}ctx;_counter=0;_internal=new Map;constructor(e){this.ctx=e,dm(this,vn.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(lVt(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=Vse()){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 c=e.name;c==="apply"&&(c=void 0),i={name:c,callback:r,fibers:new zse,Config:e.Config},this._internal.set(r,i)}let s=new jDe(this.ctx,t,pP.resolve(e.inject),i,n),o=Object.create(s);return o.then=(c,l)=>s.await().then(c,l),o}},Ns=class dP{static{a(this,"Context")}static effect=vn.effect;static filter=vn.filter;static isolate=vn.isolate;static intercept=vn.intercept;static is(t){return!!t?.[dP.is]}static{dP.is[Symbol.toPrimitive]=()=>Symbol.for("cordis.is"),dP.prototype[dP.is]=!0}constructor(){this[vn.isolate]=Object.create(null),this[vn.intercept]=Object.create(null);let t=new Proxy(this,NDe.handler);return this.root=t,this.baseUrl=void 0,this.fiber=new jDe(t,{},Object.create(null),null,()=>[]),this.reflect=new NDe(t),this.registry=new uVt(t),this.events=new tVt(t),this.logger=new sVt(t),this.fiber._disposables.clear(),t}[Symbol.for("nodejs.util.inspect.custom")](){return`Context <${this.fiber.name}>`}extend(t={}){let n=Reflect.getOwnPropertyDescriptor(this,vn.shadow)?.value,r=Object.create(P0(this,this));for(let i of Reflect.ownKeys(t))Object.defineProperty(r,i,Reflect.getOwnPropertyDescriptor(t,i));return n?Object.assign(Object.create(r),{[vn.shadow]:n}):r}isolate(t,n){let r=Object.create(this[vn.isolate]);return r[t]=n??Symbol(t),this.extend({[vn.isolate]:r})}intercept(t,n){let r=Object.create(this[vn.intercept]);return r[t]=n,this.extend({[vn.intercept]:r})}},Dt=class qDe{static{a(this,"Service")}ctx;static init=vn.init;static check=vn.check;static config=vn.config;static invoke=vn.invoke;static extend=vn.extend;static tracker=vn.tracker;static resolveConfig=vn.resolveConfig;name;constructor(t,n){this.ctx=t,n??=this.constructor.provide;let r=this,i={associate:n,property:"ctx"};return r[vn.invoke]&&(r=Wse(n,Hse(Object.getPrototypeOf(this),Function.prototype),i)),r.ctx=t,r.name=n,dm(r,vn.tracker,i),r.ctx.reflect.provide(n,r,this[vn.check]),r}[vn.filter](t){return t[vn.isolate][this.name]===this.ctx[vn.isolate][this.name]}[vn.extend](t){let n;return this[qDe.invoke]?n=Wse(this.name,this,this[vn.tracker]):n=Object.create(this),Object.assign(n,t)}[vn.resolveConfig](t,n){let r=this.ctx[Ns.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 Ql(e){if(typeof e=="object"&&e!==null&&e.isDSHRemoteError===!0&&typeof e.code=="string")return e}function nA(e){return Kse(e,new Set)}function Kse(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)||!Kse(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||!Kse(Reflect.get(e,r),t))return!1;return!0}finally{t.delete(e)}}function MS(e){let t=e?.peer.principal;return t?.kind==="owner"?void 0:t}function pVt(e){return e!=="."&&e!==".."&&dVt.test(e)}function hVt(e,t,n={}){hF("service key",t);let r=n.namespace??t;hF("namespace",r);let i=Reflect.get(e,"ctx");return Ns.is(i)&&mVt(i),Object.freeze({service:e,serviceKey:t,namespace:r})}function mVt(e){Object.hasOwn(e.root.reflect.props,"invocation")||e.root.accessor("invocation",{get:a(()=>{},"get")})}function qt(e,t){if(typeof e=="string")return hF("Remote export name",e),WDe({kind:"direct"},{exportName:e});if(typeof e=="object")return WDe({kind:"direct"},gVt(e,fVt,'Remote options require name, mode: "stream", or resources'));if(t===void 0)throw new TypeError("typert-protocol: Remote decorator context is missing");HDe(t,{kind:"direct"})}function gVt(e,t,n){let r=Reflect.ownKeys(e);if(r.length===0||r.some(c=>typeof c!="string"||!t.has(c))||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&&hF("Remote export name",s),{...i===void 0?{}:{mode:i},...s===void 0?{}:{exportName:s},...o===void 0?{}:{resources:yVt(o)}}}function yVt(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 WDe(e,t={}){return function(n,r){HDe(r,e,t)}}function mF(e){let t=Object.getPrototypeOf(e);return t===null?[]:(zDe(t)?.methods??[]).map(n=>({...n}))}function zDe(e){let t=Object.getOwnPropertyDescriptor(e,BDe);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 HDe(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`);vVt(i,r,t,n)})}function vVt(e,t,n,{mode:r,exportName:i,resources:s}){let o=zDe(e),c=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}}),l=o?.methods.find(u=>u.method===t);if(l!==void 0){if(l.exportName===c.exportName&&l.mode===c.mode&&l.resources===c.resources&&xVt(l.invocation,n))return;throw new Error(`typert-protocol: Remote method "${t}" has conflicting invocation markers`)}Object.defineProperty(e,BDe,{configurable:!0,value:Object.freeze({version:1,methods:Object.freeze([...o?.methods??[],c])})})}function xVt(e,t){return e.kind==="direct"?t.kind==="direct":t.kind==="direct"?!1:e.context===t.context}function hF(e,t){if(!pVt(t))throw new TypeError(`typert-protocol: ${e} must contain only RPC endpoint segment characters`)}var We,dVt,BDe,wi,fVt,dc=q(()=>{yr();We=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(Ql,"remoteErrorOf");a(nA,"isRemoteJsonValue");a(Kse,"visitJsonValue");a(MS,"principalOf");dVt=/^[A-Za-z0-9_$.-]+$/;a(pVt,"isTypertRemoteSegment");BDe="@deepseek-ai/dsh-typert-protocol/remote-methods";a(hVt,"bindTypertRemote");wi=class extends Dt{static{a(this,"TypertRemoteService")}typertRemote;constructor(e,t,n={}){super(e,t),this.typertRemote=hVt(this,this.name,n)}};a(mVt,"provideInvocationAccessor");a(qt,"Remote");fVt=new Set(["name","mode","resources"]);a(gVt,"markerOptions");a(yVt,"resourceReaders");a(WDe,"remoteDecorator");a(mF,"remoteMethods");a(zDe,"readRemoteMethodDescriptor");a(HDe,"addMarkerInitializer");a(vVt,"mark");a(xVt,"sameInvocation");a(hF,"validateName")});function Vx(e){return e===" "||e===`
|
|
13
13
|
`||e==="\r"||e===" "}function wVt(e){return e>="0"&&e<="9"||e>="a"&&e<="f"||e>="A"&&e<="F"}function Pr(e,t){let n=JSON.stringify(e)??String(e);throw new Error(`unreachable variant${t?` in ${t}`:""}: ${n}`)}function VDe(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 KDe(e){return Object.getPrototypeOf(e)===null&&VDe(e,"Object")}function kVt(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!VDe(t,"Array"))return!1;let n=Object.getPrototypeOf(t);return typeof n=="object"&&n!==null&&KDe(n)}function SVt(e){let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&KDe(t)}function _Vt(e){let t=Reflect.ownKeys(e);if(!t.some(n=>typeof n!="string"||!Object.prototype.propertyIsEnumerable.call(e,n)))return t}function QDe(e,t){let n=new Set,r,i=a((o,c)=>{o!==void 0&&(o.kind==="root"?r=c:o.kind==="array"?o.target[o.index]=c:Object.defineProperty(o.target,o.key,{value:c,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 c=o.value;if(c===null){i(o.destination,null);continue}if(typeof c=="boolean"||typeof c=="string"){i(o.destination,c);continue}if(typeof c=="number"){if(!Number.isFinite(c)||Object.is(c,-0))return;i(o.destination,c);continue}if(typeof c!="object"||n.has(c))return;if(Array.isArray(c)){if(!kVt(c))return;let d=c.length;if(Reflect.ownKeys(c).length!==d+1)return;let p=t?[]:void 0;p!==void 0&&i(o.destination,p),n.add(c),s.push({kind:"leave",source:c});for(let h=d-1;h>=0;h--)s.push({kind:"array-item",source:c,index:h,...p===void 0?{}:{target:p}});continue}if(!SVt(c))return;let l=_Vt(c);if(l===void 0)return;let u=t?{}:void 0;u!==void 0&&i(o.destination,u),n.add(c),s.push({kind:"leave",source:c});for(let d=l.length-1;d>=0;d--){let p=l[d];if(p===void 0)return;s.push({kind:"object-property",source:c,key:p,...u===void 0?{}:{target:u}})}}return t?r:!0}function Qs(e){return QDe(e,!0)}function R1(e){return QDe(e,!1)===!0}function tl(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)=>tl(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&&tl(n[s],r[s]))}function jn(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 c=s[o];c!==void 0&&n.push({kind:"property",source:i,key:c})}}return e}var bVt,GDe,tUr,ws=q(()=>{bVt={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
14
|
-
`,r:"\r",t:" "},GDe=/[\\\u0000-\u001f]/u;a(Vx,"isWhitespace");a(wVt,"isHex");tUr=class rA{static{a(this,"PartialArguments")}static EMPTY=rA.fromObject({});static fromText(t){let n=new rA;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new rA;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="";#c=null;#a=[];#p=!1;#m;#h=!1;#l=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 rA.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return rA.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.#l.has(t):Object.hasOwn(this.object,t)}completeNow(t){if(this.object!==void 0)return Object.hasOwn(this.object,t);let n=this.#l.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.#l.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.#l.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.#l.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.#l.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 c=r+1;c<i;c++)o.push(this.chunks[c]);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 c=Math.min(s-n.at,r-n.length);if(c<=0)return;i&&(n.text+=this.slice(n.at,n.at+c)),n.at+=c,n.length+=c;return}let o=this.chunkAt(n.at);for(;n.at<s&&n.length<r;){let c=o===0?0:this.#e[o-1],l=this.chunks[o],u=l.slice(n.at-c,Math.min(l.length,s-c)),d=u.search(GDe),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===c+l.length&&o++;continue}let h=u.length>1?u[1]:n.at+1<s?this.chunks[o+1][0]:void 0,m,f=2;if(u[0]==="\\"&&h===void 0&&t.end<0)return;if(u[0]==="\\"&&h==="u"){let g=this.slice(n.at+2,Math.min(s,n.at+6)),v=!0;for(let x=0;x<g.length;x++)wVt(g[x])||(v=!1);if(v){if(g.length<4&&t.end<0)return;g.length===4&&(m=String.fromCharCode(Number.parseInt(g,16)))}f=6}else u[0]==="\\"&&h!==void 0&&(m=bVt[h]);if(m===void 0){t.invalidAt=n.at,this.#h=!0;return}for(i&&(n.text+=m),n.length++,n.at+=f;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 l=this.#c;!l.needsDecoding&&GDe.test(t.slice(r,s))&&(l.needsDecoding=!0)}let o=s;for(;o>r&&t[o-1]==="\\";)o--;let c=(s-o)%2===1!==(o===r&&this.#i);if(this.#i=i<0&&c,i<0||!c)return s;r=i+1}}step(t,n){switch(this.#t){case"root":if(Vx(t))return;if(t==="{"){this.#t="key-or-end";return}this.fail();return;case"key-or-end":if(Vx(t))return;if(t==="}"){this.#t="closed";return}if(t==='"'){this.beginKey(n);return}this.fail();return;case"key-only":if(Vx(t))return;if(t==='"'){this.beginKey(n);return}this.fail();return;case"key":this.stepKey(t,n);return;case"colon":if(Vx(t))return;if(t===":"){this.#t="value";return}this.fail();return;case"value":this.beginValue(t,n);return;case"string":{let r=this.#c;r.end=n,this.#c=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(Vx(t))return;if(t===","){this.#t="key-only";return}if(t==="}"){this.#t="closed";return}this.fail();return;case"closed":if(Vx(t))return;this.fail();return;case"invalid":return;default:Pr(this.#t)}}fail(){this.#m=this.#r,this.#t="invalid",this.#c=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.#l.has(this.#u)||this.#f.push(this.#u),this.#l.set(this.#u,t),this.#c=t}beginValue(t,n){if(!Vx(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!=="}"&&!Vx(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.#c;n.end=t,this.#c=null}};a(Pr,"assertNever");a(VDe,"hasIntrinsicConstructor");a(KDe,"isIntrinsicObjectPrototype");a(kVt,"hasPlainArrayPrototype");a(SVt,"hasPlainObjectPrototype");a(_Vt,"enumerableStringKeys");a(QDe,"walkJsonValue");a(Qs,"snapshotJsonValue");a(R1,"isJsonValue");a(tl,"deepEqualJson");a(jn,"deepFreeze")});function fF(){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 Qse=q(()=>{a(fF,"randomUUID")});var Nc=q(()=>{});function EVt(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 hP(e){return e?.$value??e?.$inner}function JDe(e){return ADe(e??{},t=>!t.startsWith("$"))}function iA(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 ks("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,c]of Object.entries(e.dict))iA(c,[...t,o],s,r);if(e.sKey&&iA(e.sKey,[...t,"<key>"],!0,r),e.inner&&(e.type!=="lazy"||e.inner[mP])&&iA(e.inner,[...t,"*"],!0,r),e.list)for(let o=0;o<e.list.length;o++)iA(e.list[o],[...t,String(o)],!0,r)}function Xse(e,t,n,r,i=!1){let{max:s=1/0,min:o=-1/0}=t;if(e>s)throw new ks(`expected ${n} <= ${s} but got ${e}`,r);if(e<o&&!i)throw new ks(`expected ${n} >= ${o} but got ${e}`,r)}function Jse(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 TVt(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(Jse(e,i)-Jse(t,i))%Jse(n,i)===0}function gF(e,t,n,r){try{let[i,s]=j.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?Dse(n.meta.default):n.meta.default}}function Yse(e,t){for(let n in t)n in e||(e[n]=t[n])}function Pu(e,t,n){e$e[e]=n,Object.assign(j,{[e](...r){let i=new j({type:e});return t.forEach((s,o)=>{switch(s){case"sKey":i.sKey=r[o]??j.string();break;case"inner":i.inner=j.from(r[o]);break;case"list":i.list=r[o].map(j.from);break;case"dict":i.dict=Hf(r[o],j.from);break;case"bits":i.bits={};for(let c in r[o])typeof r[o][c]=="number"&&(i.bits[c]=r[o][c]);break;case"callback":{let c=i.callback=r[o];c.toJSON||=()=>c.toString();break}case"constructor":{let c=i.constructor=r[o];typeof c=="function"&&(c.toJSON||=()=>c.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 mP,XDe,ks,j,ZDe,YDe,e$e,kn=q(()=>{Gx();mP=Symbol.for("schemastery"),XDe=Symbol.for("ValidationError");globalThis.__schemastery_index__??=0;globalThis.__schemastery_refs__=void 0;ks=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?.[XDe]}};Object.defineProperty(ks.prototype,XDe,{value:!0});j=a(function(e){let t=a(function(n,r={}){return j.resolve(n,t,r)[0]},"schema");if(e.refs){let n=Hf(e.refs,i=>new j(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&&Hf(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,j.prototype),t.meta||={},t.toString=t.toString.bind(t),t},"Schema");j.prototype=Object.create(Function.prototype);j.prototype[mP]=!0;Object.defineProperty(j.prototype,"~standard",{get(){return{version:1,vendor:"schemastery",validate:a(e=>{try{return{value:j.resolve(e,this,{})[0]}}catch(t){if(ks.is(t))return{issues:[{message:t.message,path:t.options.path}]};throw t}},"validate")}}});j.ValidationError=ks;j.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");j.prototype.set=a(function(t,n){return this.dict[t]=n,this},"set");j.prototype.push=a(function(t){return this.list.push(t),this},"push");a(EVt,"mergeDesc");a(hP,"getInner");a(JDe,"extractKeys");j.prototype.i18n=a(function(t){let n=j(this),r=EVt(n.meta.description,t);return Object.keys(r).length&&(n.meta.description=r),n.dict&&(n.dict=Hf(n.dict,(i,s)=>i.i18n(Hf(t,o=>hP(o)?.[s]??o?.[s])))),n.list&&(n.list=n.list.map((i,s)=>i.i18n(Hf(t,(o={})=>Array.isArray(hP(o))?hP(o)[s]:Array.isArray(o)?o[s]:JDe(o))))),n.inner&&(n.inner=n.inner.i18n(Hf(t,i=>hP(i)?hP(i):JDe(i)))),n.sKey&&(n.sKey=n.sKey.i18n(Hf(t,i=>i?.$key))),n},"i18n");j.prototype.extra=a(function(t,n){let r=j(this);return r.meta={...r.meta,[t]:n},r},"extra");for(let e of["required","disabled","collapse","hidden","loose"])Object.assign(j.prototype,{[e](t=!0){let n=j(this);return n.meta={...n.meta,[e]:t},n}});j.prototype.deprecated=a(function(){let t=j(this);return t.meta.badges||=[],t.meta.badges.push({text:"deprecated",type:"danger"}),t},"deprecated");j.prototype.experimental=a(function(){let t=j(this);return t.meta.badges||=[],t.meta.badges.push({text:"experimental",type:"warning"}),t},"experimental");j.prototype.pattern=a(function(t){let n=j(this),r=IDe(t,["source","flags"]);return n.meta={...n.meta,pattern:r},n},"pattern");j.prototype.simplify=a(function(t){if(um(t)&&(t=t.get()),ph(t,this.meta.default,this.type==="dict"))return null;if(Pa(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"||!Pa(i))&&(n[r]=i)}return ph(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 j.resolve(t,n,{}),n.simplify(t)}catch{}return t},"simplify");j.prototype.toString=a(function(t){return e$e[this.type]?.(this,t)??`Schema<${this.type}>`},"toString");j.prototype.role=a(function(e,t){let n=j(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(j.prototype,{[e](t){let n=j(this);return n.meta={...n.meta,[e]:t},n}});j.prototype.volatile=a(function(){if(this.meta.volatile)throw new TypeError("volatile schema is already wrapped");return this.extra("volatile",!0)},"volatile");ZDe={},YDe=Symbol("checked-volatile-schema");a(iA,"validateVolatileSchema");j.extend=a(function(t,n){ZDe[t]=n},"extend");j.resolve=a(function(t,n,r={},i=!1){if(!n)return[t];if(r[YDe]||(iA(n,r.path),r={...r,[YDe]:!0}),n.meta?.volatile){let o=j(n);o.meta={...n.meta,volatile:!1};let[c,l]=j.resolve(t,o,r,i);try{return[Dse(c),l]}catch(u){throw new ks(u instanceof Error?u.message:String(u),r)}}if(r.ignore?.(t,n))return[t];if(Pa(t)&&n.type!=="lazy"){if(n.meta.required)throw new ks("missing required value",r);let o=n,c=n.meta.default;for(;o?.type==="intersect"&&Pa(c);)o=o.list[0],c=o?.meta.default;if(Pa(c))return[t];t=iF(c)}let s=ZDe[n.type];if(!s)throw new ks(`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");j.from=a(function(t){if(Pa(t))return j.any();if(["string","number","boolean"].includes(typeof t))return j.const(t).required();if(t[mP])return t;if(typeof t=="function")switch(t){case String:return j.string().required();case Number:return j.number().required();case Boolean:return j.boolean().required();case Function:return j.function().required();default:return j.is(t).required()}else throw new TypeError(`cannot infer schema from ${t}`)},"from");j.lazy=a(function(t){let n=a(()=>(r.inner[mP]||(r.inner=r.builder(),r.inner.meta={...r.meta,...r.inner.meta}),r.inner.toJSON()),"toJSON"),r=new j({type:"lazy",builder:t,inner:{toJSON:n}});return r},"lazy");j.natural=a(function(){return j.number().step(1).min(0)},"natural");j.percent=a(function(){return j.number().step(.01).min(0).max(1).role("slider")},"percent");j.date=a(function(){return j.union([j.is(Date),j.transform(j.string().role("datetime"),(t,n)=>{let r=new Date(t);if(isNaN(+r))throw new ks(`invalid date "${t}"`,n);return r},!0)])},"date");j.regExp=a(function(t=""){return j.union([j.is(RegExp),j.transform(j.string().role("regexp",{flag:t}),(n,r)=>{try{return new RegExp(n,t)}catch(i){throw new ks(i.message,r)}},!0)])},"regExp");j.arrayBuffer=a(function(t){return j.union([j.is(ArrayBuffer),j.is(SharedArrayBuffer),j.transform(j.any(),(n,r)=>{if(zf.isSource(n))return zf.fromSource(n);throw new ks(`expected ArrayBufferSource but got ${n}`,r)},!0),...t?[j.transform(j.string(),(n,r)=>{try{return t==="base64"?zf.fromBase64(n):zf.fromHex(n)}catch(i){throw new ks(i.message,r)}},!0)]:[]])},"arrayBuffer");j.extend("lazy",(e,t,n,r)=>(t.inner[mP]||(t.inner=t.builder(),t.inner.meta={...t.meta,...t.inner.meta},iA(t.inner,n.path,!0)),j.resolve(e,t.inner,n,r)));j.extend("any",e=>[e]);j.extend("never",(e,t,n)=>{throw new ks(`expected nullable but got ${e}`,n)});j.extend("const",(e,{value:t},n)=>{if(ph(e,t))return[t];throw new ks(`expected ${t} but got ${e}`,n)});a(Xse,"checkWithinRange");j.extend("string",(e,{meta:t},n)=>{if(typeof e!="string")throw new ks(`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 ks(`expect string to match regexp ${r}`,n)}return Xse(e.length,t,"string length",n),[e]});a(Jse,"decimalShift");a(TVt,"isMultipleOf");j.extend("number",(e,{meta:t},n)=>{if(typeof e!="number")throw new ks(`expected number but got ${e}`,n);Xse(e,t,"number",n);let{step:r}=t;if(r&&!TVt(e,t.min??0,r))throw new ks(`expected number multiple of ${r} but got ${e}`,n);return[e]});j.extend("boolean",(e,t,n)=>{if(typeof e=="boolean")return[e];throw new ks(`expected boolean but got ${e}`,n)});j.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 ks(`expected string but got ${o}`,r);o in t&&(i|=t[o])}}else throw new ks(`expected number or array but got ${e}`,r);return i===n.default?[i]:[i,s]});j.extend("function",(e,t,n)=>{if(typeof e=="function")return[e];throw new ks(`expected function but got ${e}`,n)});j.extend("is",(e,{constructor:t},n)=>{if(typeof t=="function"){if(e instanceof t)return[e];throw new ks(`expected ${t.name} but got ${e}`,n)}else{if(Pa(e))throw new ks(`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 ks(`expected ${t} but got ${e}`,n)}});a(gF,"property");j.extend("array",(e,{inner:t,meta:n},r)=>{if(!Array.isArray(e))throw new ks(`expected array but got ${e}`,r);return Xse(e.length,n,"array length",r,!Pa(t.meta.default)),[e.map((i,s)=>gF(e,s,t,r))]});j.extend("dict",(e,{inner:t,sKey:n},r,i)=>{if(!sF(e))throw new ks(`expected object but got ${e}`,r);let s={};for(let o in e){let c;try{c=j.resolve(o,n,r)[0]}catch(l){if(i)continue;throw l}s[c]=gF(e,o,t,r),e[c]=e[o],o!==c&&delete e[o]}return[s]});j.extend("tuple",(e,{list:t},n,r)=>{if(!Array.isArray(e))throw new ks(`expected array but got ${e}`,n);let i=t.map((s,o)=>gF(e,o,s,n));return r?[i]:(i.push(...e.slice(t.length)),[i])});a(Yse,"merge");j.extend("object",(e,{dict:t},n,r)=>{if(!sF(e))throw new ks(`expected object but got ${e}`,n);let i={};for(let s in t){let o=gF(e,s,t[s],n);(!Pa(o)||s in e)&&(i[s]=o)}return r||Yse(i,e),[i]});j.extend("union",(e,{list:t,toString:n},r,i)=>{let s=[];for(let o of t)try{return j.resolve(e,o,r,i)}catch(c){s.push(c)}throw new ks(`expected ${n()} but got ${JSON.stringify(e)}`,r)});j.extend("intersect",(e,{list:t,toString:n},r,i)=>{if(!t.length)return[e];let s;for(let o of t){let c=j.resolve(e,o,r,!0)[0];if(!Pa(c))if(Pa(s))s=c;else{if(typeof s!=typeof c)throw new ks(`expected ${n()} but got ${JSON.stringify(e)}`,r);if(typeof c=="object")Yse(s??={},c);else if(s!==c)throw new ks(`expected ${n()} but got ${JSON.stringify(e)}`,r)}}return!i&&sF(e)&&Yse(s,e),[s]});j.extend("transform",(e,{inner:t,callback:n,preserve:r},i)=>{let[s,o=e]=j.resolve(e,t,i,!0);return r?[n(s)]:[n(s),n(o)]});e$e={};a(Pu,"defineMethod");Pu("is",["constructor"],({constructor:e})=>typeof e=="function"?e.name:e);Pu("any",[],()=>"any");Pu("never",[],()=>"never");Pu("const",["value"],({value:e})=>typeof e=="string"?JSON.stringify(e):e);Pu("string",[],()=>"string");Pu("number",[],()=>"number");Pu("boolean",[],()=>"boolean");Pu("bitset",["bits"],()=>"bitset");Pu("function",[],()=>"function");Pu("array",["inner"],({inner:e})=>`${e.toString(!0)}[]`);Pu("dict",["inner","sKey"],({inner:e,sKey:t})=>`{ [key: ${t.toString()}]: ${e.toString()} }`);Pu("tuple",["list"],({list:e})=>`[${e.map(t=>t.toString()).join(", ")}]`);Pu("object",["dict"],({dict:e})=>Object.keys(e).length===0?"{}":`{ ${Object.entries(e).map(([t,n])=>`${t}${n.meta.required?"":"?"}: ${n.toString()}`).join(", ")} }`);Pu("union",["list"],({list:e},t)=>{let n=e.map(({toString:r})=>r()).join(" | ");return t?`(${n})`:n});Pu("intersect",["list"],({list:e})=>`${e.map(t=>t.toString(!0)).join(" & ")}`);Pu("transform",["inner","callback","preserve"],({inner:e},t)=>e.toString(t))});function t$e(e,t){if(!Number.isFinite(e)||e<=0||e>2147483647)throw new Error(`${t} must be a positive finite number no greater than ${Ss}`)}function n$e(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 Gf(e,t,n){if(t<=0)return{signal:e??new AbortController().signal,[Symbol.dispose](){}};t$e(t,"deadline timeoutMs");let r=new AbortController,i=setTimeout(()=>{r.abort(new Zse(n,t))},t);return{signal:e!==void 0?AbortSignal.any([e,r.signal]):r.signal,[Symbol.dispose](){clearTimeout(i)}}}function yF(e,t,n){t$e(t,"idleWatchdog timeoutMs");let r=new AbortController,i=e===void 0?r.signal:AbortSignal.any([e,r.signal]),s=new Zse(n,t),o,c=!1,l=!1,u=a(()=>{o!==void 0&&clearTimeout(o),o=setTimeout(()=>{r.abort(s)},t)},"arm");return{signal:i,async next(d){if(l)throw new Error("idleWatchdog is disposed");if(c)throw new Error("idleWatchdog next is already outstanding");c=!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,c=!1}},pulse(){l||!c||u()},[Symbol.dispose](){l||(l=!0,o!==void 0&&clearTimeout(o),o=void 0)}}}function Vf(e,t){let n=e.reason;if(n instanceof Zse)return t===void 0||n.code===t?n:void 0}var Zse,Ss,pm=q(()=>{Zse=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}},Ss=2147483647;a(t$e,"assertTimerDelay");a(n$e,"clampTimeout");a(Gf,"deadline");a(yF,"idleWatchdog");a(Vf,"timeoutOf")});function Kx(e){return e.length<=120?e:`${e.slice(0,119)}\u2026`}function hm(e){return jn(structuredClone(e))}function gP(e){return jn(structuredClone({...e,id:fF()}))}function a$e(e){return gP({...e,role:"developer"})}function tr(e){return gP({...e,role:"user"})}function xF(e){return gP({role:"assistant",content:e.content,source:{kind:"model",...e.source}})}function bF(e){return gP({role:"system",content:e.length===0?[]:[{type:"text",text:e}],source:{kind:"system-prompt"}})}function c$e(e){return gP({role:"tool",source:{kind:"tool",callId:e.callId},toolCallId:e.callId,content:e.content,isError:e.isError})}function kF(e){return AVt.test(e)||/\b(?:maximum|max)(?:\s+(?:allowed|supported))?\s+context\s+(?:length|window)\b/i.test(e)||IVt.test(e)||/\b(?:input|prompt|request)\s+(?:is\s+)?too\s+(?:long|large)\s+for\s+(?:this|the)\s+model\b/i.test(e)||RVt.test(e)}function SF(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 Ou(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 c=Object.getOwnPropertyDescriptor(r,"message");if(c!==void 0&&"value"in c&&typeof c.value=="string")return c.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 soe(e,t,n){for(let r of Object.keys(e))if(!t.has(r))throw new Error(`${n}: unknown key "${r}"`)}function eoe(e,t){e!==void 0&&soe(e,NVt,t);let n=e?.initialDelayMs??u$e,r=e?.maxDelayMs??d$e,i=e?.jitterRatio??p$e;if(!Number.isFinite(n)||n<=0||n>Ss)throw new Error(`${t}.initialDelayMs must be a positive finite number no greater than ${Ss}`);if(!Number.isFinite(r)||r<=0||r>Ss)throw new Error(`${t}.maxDelayMs must be a positive finite number no greater than ${Ss}`);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 yP(e,t){if(e===void 0)return Object.freeze({mode:"normal",maxRetries:roe,retryableCodes:ioe,...eoe(void 0,`${t}.backoff`)});switch(e.mode){case"normal":{soe(e,OVt,t);let n=e.maxRetries??roe,r=e.retryableCodes??[...ioe];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]),...eoe(e.backoff,`${t}.backoff`)})}case"always":return soe(e,MVt,t),Object.freeze({mode:"always",...eoe(e.backoff,`${t}.backoff`)});default:throw new Error(`${t}.mode must be "normal" or "always"`)}}function fP(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 f$e(e){return m$e.add(e),e}function g$e(e){return m$e.has(e)}function LVt(e){let t=e instanceof Error?e:new oi(DVt(e),"UNKNOWN",{cause:e}),n=UVt(t);return n!==void 0&&n.code===$Vt(t)?n:Object.freeze({message:jVt(t),code:qVt(t)})}function DVt(e){try{let t=String(e);return t.length>0?t:"LLM adapter failed"}catch{return"LLM adapter failed"}}function $Vt(e){try{let t=Object.getOwnPropertyDescriptor(e,"code");return t!==void 0&&"value"in t?t.value:void 0}catch{return}}function UVt(e){try{let t=Object.getOwnPropertyDescriptor(e,"failure");return t!==void 0&&"value"in t?FVt(t.value):void 0}catch{return}}function FVt(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,c=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)||c!==void 0&&(!Number.isSafeInteger(c)||c<=0)?void 0:Object.freeze({message:n,code:r,...i===void 0?{}:{status:i},...s===void 0?{}:{providerRetryAfterMs:s},...o===void 0?{}:{requestId:o},...c===void 0?{}:{offloadImages:c}})}catch{return}}function jVt(e){try{let t=e.message;if(typeof t=="string"&&t.length>0)return t}catch{}return"LLM adapter failed"}function qVt(e){return e instanceof oi?e.code:"UNKNOWN"}function coe(e){let t=e.trim();return t.length===0?{ok:!1,reason:"empty"}:WVt.test(t)?{ok:!0,value:t}:{ok:!1,reason:"illegalCharacters"}}function sA(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 vF(e){return JSON.stringify(e)}function y$e(e){return e.name===void 0?String(e.attachmentId):`${vF(e.name)} (${e.attachmentId})`}function BVt(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 Pr(e,"image extension")}}function v$e(e,t){return` Normalized copy (read-only; may be resized or re-encoded): ${vF(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 ${BVt(e.mediaType)} before editing.`}function loe(e){return`[image omitted because this model accepts text only; attachment sha256:${String(e.attachmentId).slice(7,15)}]`}function vP(e,t,n){let r=`Image ${y$e(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+v$e(e,n)}function xP(e,t){let n=`image omitted to fit request image limits; ${y$e(e)}.`;return t===void 0?`[${n} No local normalized image path is available; ask the user to attach it again if needed.]`:`[${n}${v$e(e,t)}]`}function lp(e){return e.some(t=>t.type==="image")}function x$e(e){for(let t of e)if(t.type==="file")return!0;return!1}function b$e(e,t){let n=String(e.attachmentId).slice(7,15),r=`File ${vF(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 ${vF(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 zVt(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:b$e(i.attachment,t(i.attachment))});continue}n?.push(i)}return n??e}function HVt(e,t){return e.some(n=>x$e(n.content))?e.map(n=>{let r=zVt(n.content,t);return r===n.content?n:{...n,content:r}}):e}function GVt(e){return Math.ceil(e/3)*4}function VVt(e,t){for(let n of e)n.type==="image"&&t(n)}function KVt(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 EF(e,t){return e.map(n=>{let r=KVt(n.content,t);return r===n.content?n:{...n,content:r}})}function QVt(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,c=r===0?0:Math.ceil(r/s)*s,l=i===0?0:Math.ceil(i/o)*o,u=0,d=0;for(let p of e){if(u>=c&&(l===0||(o===1?d>=l:d>l)))break;d+=p,u+=1}return u}function TF(e,t,n){let r=[];for(let i of e)VVt(i.content,s=>{if(s.offloaded===!0)return;let o=n(s);r.push(t.representation==="base64"?GVt(o):o)});return QVt(r,t)}function JVt(e){let t;for(let[n,r]of e.entries()){if(r.type==="image"){t??=e.slice(0,n),t.push({type:"text",text:loe(r.attachment)});continue}t?.push(r)}return t??e}function YVt(e){return e.some(t=>lp(t.content))?e.map(t=>{let n=JVt(t.content);return n===t.content?t:{...t,content:n}}):e}function toe(e){let t=e.filter(n=>n.role!=="developer");return t.length===e.length?e:t}function XVt(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 Pr(t)}}function ZVt(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:toe(e),tools:u}}if(r===void 0)return{messages:toe(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:toe(e),tools:t};let s=XVt(t,n,r),o=new Set(r.updates.map(u=>u.messageId)),c=new Set(r.tools.filter(u=>!u.deferLoading).map(u=>u.name)),l=[];for(let u of e){if(u.role!=="developer"){l.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)||c.has(p.toolName)?!1:(c.add(p.toolName),!0);case"tool-removal":return n!=="in-history"?!1:c.delete(p.toolName);default:return!0}});d.length!==0&&(d.length===u.content.length?l.push(u):l.push({...u,content:d}))}return{messages:l.length===e.length&&l.every((u,d)=>u===e[d])?e:l,tools:[...s.values()]}}function tKt(e=Qx){return`${e.product}/${e.version} (+${e.url})`}function LS(e=Qx){return{"user-agent":tKt(e)}}function AF(e){return e}function bP(e){return e}function w$e(e){return e}function k$e(e){return e}function pc(e){return e}function nKt(e){if(!Number.isSafeInteger(e))throw new TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function r$e(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 rKt(e){let t=Qs(e);if(t===void 0)throw new TypeError("Assistant stream chunk must be losslessly JSON-serializable");return t}function i$e(e,t){let n=t-e;return Number.isSafeInteger(n)&&e+n===t?n:void 0}function iKt(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 sKt(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 oKt(e){return e.type==="tool-call-chunks"&&e.name!==void 0?e.time0:sKt(e,t=>t!=="")}function uoe(e){for(let t of e){let n=t.type==="chunk"?iKt(t.chunk)?t.time:void 0:oKt(t);if(n!==void 0)return n}}function S$e(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 _$e(e,t){let n=[];for(let r of e)r.type==="chunk"&&r.chunk.type===t&&n.push(r.chunk);return n}function E$e(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 T$e(e,t=new DS){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:Pr(n,"assembleAssistantStream")}return t}function aA(e,t,n){let r=coe(e);if(r.ok)return r.value;throw new mt(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)`,aoe)}function s$e(e,t){let n=LVt(e);return{type:"finish",reason:t?.aborted||n.code==="ABORTED"?{kind:"aborted",failure:n}:{kind:"error",failure:n}}}function o$e(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 oi,wF,l$e,ooe,aoe,AVt,IVt,RVt,NS,roe,u$e,d$e,p$e,ioe,h$e,CVt,PVt,_F,OVt,MVt,NVt,m$e,WVt,eKt,Qx,DS,oA,aKt,noe,mt,IF,A$e,Ur=q(()=>{dc();ws();Qse();Nc();kn();pm();a(Kx,"boundContextSummary");a(hm,"freezeMessage");a(gP,"createMessage");a(a$e,"createDeveloperMessage");a(tr,"createUserMessage");a(xF,"createAssistantMessage");a(bF,"createSystemMessage");a(c$e,"createToolResultMessage");oi=class extends Error{static{a(this,"HarnessError")}code;constructor(e,t,n){super(e,n),this.code=t,this.name=new.target.name}},wF="CONTEXT_WINDOW_EXCEEDED",l$e="QUOTA",ooe="EMPTY_RESPONSE",aoe="INVALID_CREDENTIAL",AVt=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"),IVt=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"),RVt=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(kF,"isContextWindowExceededError");a(SF,"isQuotaExceededError");a(Ou,"errorChain");NS="IMAGE_OFFLOAD_REQUIRED",roe=5,u$e=500,d$e=1e4,p$e=.1,ioe=Object.freeze([ooe,"RATE_LIMIT","SERVER","TIMEOUT","TRANSPORT"]),h$e=j.object({initialDelayMs:j.number().max(Ss).default(u$e),maxDelayMs:j.number().max(Ss).default(d$e),jitterRatio:j.number().min(0).max(1).default(p$e)}),CVt=j.object({mode:j.const("normal").required(),maxRetries:j.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(roe),retryableCodes:j.array(j.string()).default([...ioe]),backoff:h$e}),PVt=j.object({mode:j.const("always").required(),backoff:h$e}),_F=j.union([CVt,PVt]),OVt=new Set(["mode","maxRetries","retryableCodes","backoff"]),MVt=new Set(["mode","maxRetries","retryableCodes","backoff"]),NVt=new Set(["initialDelayMs","maxDelayMs","jitterRatio"]);a(soe,"validateKeys");a(eoe,"resolveBackoff");a(yP,"resolveRetryPolicy");m$e=new WeakSet;a(fP,"callConfigEquals");a(f$e,"markAgentLoopRequest");a(g$e,"isAgentLoopRequest");a(LVt,"normalizeLlmFailure");a(DVt,"thrownMessage");a($Vt,"ownErrorCode");a(UVt,"ownFailureSnapshot");a(FVt,"failureSnapshot");a(jVt,"errorMessage");a(qVt,"harnessErrorCode");WVt=/^[\x21-\x7E]+$/;a(coe,"normalizeApiKey");a(sA,"resolveImageAttachmentAccess");a(vF,"quoted");a(y$e,"imageIdentity");a(BVt,"extension");a(v$e,"normalizedAccessText");a(loe,"textOnlyImageText");a(vP,"requestImageHandleText");a(xP,"offloadedImageText");a(lp,"contentHasImage");a(x$e,"contentHasFile");a(b$e,"fileHandleText");a(zVt,"replaceFilesWithHandles");a(HVt,"projectFilesToText");a(GVt,"base64Length");a(VVt,"visitImageBlocks");a(KVt,"replaceOffloadedImages");a(EF,"projectOffloadedImages");a(QVt,"offloadedImagePrefixCount");a(TF,"requiredImageOffload");a(JVt,"replaceImagesForTextModel");a(YVt,"projectImagesForTextModel");a(toe,"withoutDeveloperMessages");a(XVt,"toolDeclarations");a(ZVt,"projectToolUpdates");eKt="0.2.1-rc.3",Qx={product:"deepseek-harness",version:eKt,url:"https://github.com/deepseek-ai/deepseek-harness"};a(tKt,"userAgent");a(LS,"attributionHeaders");a(AF,"MessageId");a(bP,"ToolCallId");a(w$e,"ProviderRequestId");a(k$e,"LlmAttemptId");a(pc,"ReasoningEffortId");DS=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 Pr(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 xF({content:this.blocks(),source:e})}};a(nKt,"safeTime");a(r$e,"safeIndex");a(rKt,"snapshotChunk");a(i$e,"safeGap");oA=class{static{a(this,"AssistantStreamAccumulator")}records=[];push(e){let t=nKt(e.time),n=rKt(e.chunk),r=jn({time:t,chunk:n}),i=this.records.at(-1);switch(n.type){case"text-delta":case"reasoning-delta":{if(r$e(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?i$e(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(r$e(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"?i$e(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 Pr(n,"AssistantStreamAccumulator.push")}}snapshot(){return jn(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(iKt,"isTokenDelta");a(sKt,"firstRunMemberTime");a(oKt,"runFirstTokenTime");a(uoe,"assistantStreamFirstTokenTime");a(S$e,"lastAssistantStreamChunk");a(_$e,"assistantStreamChunks");a(E$e,"joinAssistantStreamText");a(T$e,"assembleAssistantStream");aKt=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"),noe=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 c=r.kind,l=c==="getter"?"get":c==="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 f={};for(var g in r)f[g]=g==="access"?{}:r[g];for(var g in r.access)f.access[g]=r.access[g];f.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])(c==="accessor"?{get:d.get,set:d.set}:d[l],f);if(c==="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))&&(c==="field"?i.unshift(p):d[l]=p)}u&&Object.defineProperty(u,r.name,d),h=!0},"__esDecorate"),mt=class extends oi{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(aA,"assertUsableApiKey");IF=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")}}},A$e=(()=>{let e=wi,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=[qt],r=[qt],i=[qt("discoverModels")],noe(this,null,n,{kind:"method",name:"listProviders",static:!1,private:!1,access:{has:a(c=>"listProviders"in c,"has"),get:a(c=>c.listProviders,"get")},metadata:o},null,t),noe(this,null,r,{kind:"method",name:"listConfigurableProviders",static:!1,private:!1,access:{has:a(c=>"listConfigurableProviders"in c,"has"),get:a(c=>c.listConfigurableProviders,"get")},metadata:o},null,t),noe(this,null,i,{kind:"method",name:"remoteDiscoverModels",static:!1,private:!1,access:{has:a(c=>"remoteDiscoverModels"in c,"has"),get:a(c=>c.remoteDiscoverModels,"get")},metadata:o},null,t),o&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})}adapters=(aKt(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 c=o();c!=null&&typeof c.then=="function"&&Promise.resolve(c).then(void 0,l=>{this.warnAdaptersListenerFailure(l)})}catch(c){this.warnAdaptersListenerFailure(c)}}warnAdaptersListenerFailure(o){this.ctx.logger.warn("llm: an llm/adapters-updated listener failed"),this.ctx.logger.warn(o)}registerAdapter(o,c){let l=new Set,u=!1,d=this.ctx.effect(function*(){if(o.length===0)throw new mt("an adapter must register at least one provider","INVALID_ADAPTER");this.commitRoutes(l,this.prepareRoutes(o,c,l)),yield()=>{u=!0;for(let h of l)this.adapters.delete(h);l.clear(),this.emitAdaptersUpdated()}}.bind(this),"llm.registerAdapter()"),p=a((()=>{d()}),"handle");return p.replace=h=>{if(u)throw new mt("a disposed adapter registration cannot replace its routes","REGISTRATION_DISPOSED");this.commitRoutes(l,this.prepareRoutes(h,c,l))},p}prepareRoutes(o,c,l){let u=new Set,d=[];for(let p of o){if(p.length===0)throw new mt("adapter provider names must be non-empty","INVALID_ADAPTER");if(u.has(p)||this.adapters.has(p)&&!l.has(p))throw new mt(`an adapter for provider "${p}" is already registered`,"DUPLICATE_ADAPTER");let h=c.providerInfo(p);if(typeof h.id!="string"||h.id!==p||typeof h.name!="string"||h.name.length===0)throw new mt(`adapter metadata for provider "${p}" must preserve its id and have a non-empty name`,"INVALID_ADAPTER");u.add(p);let m=c.providerRetryPolicy(p)??yP(void 0,`llm: provider "${p}" retryPolicy`);d.push({adapter:c,provider:{id:h.id,name:h.name},retryPolicy:m})}return d}commitRoutes(o,c){for(let l of o)this.adapters.delete(l);o.clear();for(let l of c)this.adapters.set(l.provider.id,l),o.add(l.provider.id);this.emitAdaptersUpdated()}listProviders(){return[...this.adapters.values()].map(({provider:o})=>({...o}))}registerConfigurableProviders(o){let c=[],l=!1,u=a(h=>{let m=[],f=new Set(c.map(g=>g.provider));for(let g of h){if(g.provider.length===0||g.displayName.length===0||g.settingsNs.length===0)throw new mt("configurable providers need a non-empty provider, displayName, and settingsNs","INVALID_DIRECTORY");if(g.settingsPath.some(v=>v.length===0))throw new mt(`configurable provider "${g.provider}" has an empty settingsPath segment`,"INVALID_DIRECTORY");if(this.directory.has(g.provider)&&!f.has(g.provider)||m.some(v=>v.provider===g.provider))throw new mt(`configurable provider "${g.provider}" is already declared`,"DUPLICATE_DIRECTORY");m.push(o$e(g))}for(let g of c)this.directory.delete(g.provider);for(let g of m)this.directory.set(g.provider,g);c=m,this.emitAdaptersUpdated()},"commit"),d=this.ctx.effect(function*(){if(o.length===0)throw new mt("a configurable-provider registration must declare at least one provider","INVALID_DIRECTORY");u(o),yield()=>{l=!0;for(let h of c)this.directory.delete(h.provider);c=[],this.emitAdaptersUpdated()}}.bind(this),"llm.registerConfigurableProviders()"),p=a((()=>{d()}),"handle");return p.replace=h=>{if(l)throw new mt("this configurable-provider registration was disposed","REGISTRATION_DISPOSED");u(h)},p}listConfigurableProviders(){return[...this.directory.values()].map(o$e)}registerModelDiscovery(o,c){let l=this.ctx.effect(function*(){if(o.length===0)throw new mt("model discovery needs a non-empty settings namespace","INVALID_DISCOVERY");if(this.discoveries.has(o))throw new mt(`model discovery for "${o}" is already registered`,"DUPLICATE_DISCOVERY");this.discoveries.set(o,c),yield()=>{this.discoveries.delete(o)}}.bind(this),"llm.registerModelDiscovery()");return()=>{l()}}async discoverModels(o,c,l){let u=this.discoveries.get(o);if(u===void 0)throw new mt(`no model discovery is registered for "${o}"`,"NO_DISCOVERY");if((c.provider??"").length===0&&(c.baseURL??"").length===0)throw new mt("model discovery needs a provider route or a baseURL","INVALID_DISCOVERY");let d=l===void 0?await u(c):await u(c,l),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,c,l){try{return await this.discoverModels(o,c,l)}catch(u){throw new We("llm/model-discovery-rejected",u instanceof Error?u.message:String(u),{settingsNs:o,...c.baseURL===void 0?{}:{baseURL:c.baseURL}},{cause:u})}}providerRetryPolicy(o){return this.registration(o).retryPolicy}imageRequestPricing(o,c){return this.adapters.get(o)?.adapter.imageRequestPricing(o,c)}imageRequestTarget(o,c,l){return this.registration(o).adapter.imageRequestTarget(o,c,l)}fileRequestText(o){return b$e(o,this.fileReadPath(o))}detachedModalities(o){return o===void 0?void 0:[...o]}async listModels(o){let c=await this.registration(o).adapter.listModels(o),l=new Set;return c.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"||l.has(u.id))throw new mt(`adapter returned invalid or duplicate model metadata for provider "${o}"`,"INVALID_CATALOG");l.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,c,l){return this.resolveModelInfoFor(this.registration(o),c,l)}async resolveModelInfoFor(o,c,l){let u=await o.adapter.resolveModel(o.provider.id,c,l);return this.normalizeModelInfo(o,c,u)}normalizeModelInfo(o,c,l){let u=o.provider.id;if(typeof l.provider!="string"||l.provider!==u||typeof l.id!="string"||l.id!==c||typeof l.name!="string"||l.name.length===0||l.description!==void 0&&typeof l.description!="string")throw new mt(`adapter returned invalid exact model metadata for provider "${u}" model "${c}"`,"INVALID_MODEL_INFO");let d=l.context;if(d!==void 0&&(!Number.isInteger(d.contextWindow)||d.contextWindow<=0))throw new mt(`adapter returned invalid context metadata for provider "${u}" model "${c}"`,"INVALID_MODEL_CONTEXT");let p=this.detachedModalities(l.inputModalities),h=l.systemPromptUpdate;if(h!==void 0&&h!=="in-history")throw new mt(`adapter returned invalid system prompt update mode for provider "${u}" model "${c}"`,"INVALID_MODEL_INFO");let m=l.toolUpdate;if(m!==void 0&&m!=="in-history"&&m!=="addition-only")throw new mt(`adapter returned invalid tool update mode for provider "${u}" model "${c}"`,"INVALID_MODEL_INFO");let f=l.defaultMaxTokens;if(f!==void 0&&(!Number.isSafeInteger(f)||f<=0))throw new mt(`adapter returned invalid default maxTokens for provider "${u}" model "${c}"`,"INVALID_MODEL_MAX_TOKENS");let g={provider:u,id:c,name:l.name,...l.description===void 0?{}:{description:l.description},...p===void 0?{}:{inputModalities:p},...d===void 0?{}:{context:{contextWindow:d.contextWindow}},...f===void 0?{}:{defaultMaxTokens:f},...l.systemPromptUpdate===void 0?{}:{systemPromptUpdate:l.systemPromptUpdate},...l.toolUpdate===void 0?{}:{toolUpdate:l.toolUpdate}},v=l.reasoning;if(v===void 0)return g;if(v.efforts.length===0)throw new mt(`adapter returned invalid reasoning metadata for provider "${u}" model "${c}"`,"INVALID_MODEL_REASONING");let x=new Set,b=v.efforts.map(w=>{if(typeof w.id!="string"||w.id.length===0||typeof w.name!="string"||w.name.length===0||w.description!==void 0&&typeof w.description!="string"||x.has(w.id))throw new mt(`adapter returned invalid or duplicate reasoning effort metadata for provider "${u}" model "${c}"`,"INVALID_MODEL_REASONING");return x.add(w.id),{id:w.id,name:w.name,...w.description===void 0?{}:{description:w.description}}});if(v.defaultEffort!==void 0&&!x.has(v.defaultEffort))throw new mt(`adapter returned an unknown default reasoning effort for provider "${u}" model "${c}"`,"INVALID_MODEL_REASONING");return{...g,reasoning:{efforts:b,...v.defaultEffort===void 0?{}:{defaultEffort:v.defaultEffort}}}}async resolveCallConfig(o,c){return(await this.resolveCallFor(this.registration(o.provider),o,c)).config}async resolveCallFor(o,c,l){let u=await this.resolveModelInfoFor(o,c.model,l);return this.resolveCallWithInfo(c,u)}resolveCallWithInfo(o,c){let l=o.maxTokens===void 0&&c.defaultMaxTokens!==void 0?{...o,maxTokens:c.defaultMaxTokens}:o,u=c.reasoning,d=l.reasoningEffort,p=l;if(u===void 0){if(d!==void 0)throw new mt(`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 mt(`provider "${o.provider}" model "${o.model}" does not support reasoning effort "${h}"`,"UNSUPPORTED_REASONING_EFFORT");d!==h&&(p={...l,reasoningEffort:h})}}return{config:p,...c.context===void 0?{}:{context:c.context},modelInfo:c}}async prepareCall(o,c,l){c?.throwIfAborted();let{provider:u,model:d,...p}=o,h=this.registration(u),m=await h.adapter.prepareCall(u,d,c);c?.throwIfAborted();let f=this.normalizeModelInfo(h,d,m.model),g=l===void 0?o:{...l(jn(structuredClone(p)),jn(f)),provider:u,model:d};c?.throwIfAborted();let v=this.resolveCallWithInfo(g,f),x=jn(structuredClone(v.config)),b=v.context===void 0?void 0:jn(structuredClone(v.context)),w=jn({...g.reasoningEffort===void 0&&x.reasoningEffort!==void 0?{reasoningEffort:!0}:{},...g.maxTokens===void 0&&x.maxTokens!==void 0?{maxTokens:!0}:{}}),k=!1;return Object.freeze({config:x,retryPolicy:h.retryPolicy,adapterDefaults:w,...b===void 0?{}:{context:b},...f.inputModalities===void 0?{}:{inputModalities:Object.freeze([...f.inputModalities])},...f.systemPromptUpdate===void 0?{}:{systemPromptUpdate:f.systemPromptUpdate},...f.toolUpdate===void 0?{}:{toolUpdate:f.toolUpdate},stream:a(E=>{if(k)throw new mt("a prepared LLM call can only be dispatched once","INVALID_PREPARED_CALL");if(!fP(E,x))throw new mt("prepared LLM call config changed before adapter dispatch","INVALID_PREPARED_CALL");return k=!0,this.streamWithRegistration(E,{registration:h,config:x,modelInfo:f,dispatch:a(A=>m.stream(A),"dispatch")})},"stream")})}registration(o){let c=this.adapters.get(o);if(!c)throw new mt(`no adapter registered for provider "${o}"`,"NO_ADAPTER");return c}forAdapter(o,c){let l=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===c?d:hm({...d,source:{kind:"model",provider:p.provider,model:p.model}})});if(l.every((d,p)=>d===o.messages[p]))return o;let u={...o,messages:l};return Object.isFrozen(o)?jn(u):u}fileReadPath(o){let c;try{c=this.ctx.get("attachments")?.fileHostPath(o)}catch{return}if(c!==void 0)return this.ctx.get("fs")?.processPathFromHostPath(c)}async*adapterStream(o,c){let l;try{let d=c?.registration??this.registration(o.provider),p=d.adapter,h,m,f;if(c===void 0){let w=await p.prepareCall(o.provider,o.model,o.signal);h=this.normalizeModelInfo(d,o.model,w.model),m=this.resolveCallWithInfo(o,h).config,f=a(k=>w.stream(k),"dispatch")}else h=c.modelInfo,m=c.config,f=c.dispatch;if(c!==void 0&&!fP(o,m))throw new mt("prepared LLM call config changed before adapter dispatch","INVALID_PREPARED_CALL");let g=fP(o,m)?o:Object.isFrozen(o)?jn({...o,...m}):{...o,...m},v=g.messages;v.some(w=>x$e(w.content))&&(v=HVt(v,w=>this.fileReadPath(w))),h.inputModalities!==void 0&&!h.inputModalities.includes("image")&&v.some(w=>lp(w.content))&&(v=YVt(v));let x=ZVt(v,g.tools,h.toolUpdate,g.toolHistory);v=x.messages;let b=g;(v!==g.messages||x.tools!==g.tools)&&(b={...g,messages:v,...x.tools===void 0?{}:{tools:x.tools}},Object.isFrozen(g)&&jn(b)),l=f(this.forAdapter(b,p))[Symbol.asyncIterator]()}catch(d){yield s$e(d,o.signal);return}let u=!1;try{for(;;){let d;try{let p=await l.next();d=p.done?{done:!0}:{done:!1,value:p.value}}catch(p){u=!0,yield s$e(p,o.signal);return}if(d.done){u=!0;return}yield d.value}}finally{if(!u){let d=l.return?.bind(l);d&&await d()}}}stream(o){return this.streamWithRegistration(o)}streamWithRegistration(o,c){return this.ctx.waterfall(this,"llm/stream",o,()=>this.adapterStream(o,c))}}})();a(s$e,"adapterFailureChunk");a(o$e,"detachDirectoryEntry")});function I$e(e,t){for(let n=t;n!==void 0;n=cA.get(n))if(n===e)throw new Error("dsh-scope: scope parent link would form a cycle");cA.set(e,t)}function poe(e,t){if(cA.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 I$e(e,t),{rebind(n){I$e(e,n)}}}function C$e(e){return cA.get(e)}function wP(e){let t=[];for(let n=e;n!==void 0;n=cA.get(n))t.push(n);return t}async function cKt(e){for(await Promise.resolve(e.dispose());e.inertia!==void 0;)await e.inertia}function lKt(){}function Jx(e,t,n){n?.parent!==void 0&&poe(t,n.parent);let r=e.plugin(lKt),i=r.ctx.extend({[R$e]:t}),s;return{ctx:i,rawDispose:r.dispose,dispose:a(()=>s??=cKt(r),"dispose")}}function nl(e){return e[R$e]}function rl(e,t){let n=e[Ns.filter],r={[Ns.filter](i){if(n!==void 0&&!n.call(e,i))return!1;let s=nl(i);if(s===void 0)return!0;for(let o=t;o!==void 0;o=cA.get(o))if(o===s)return!0;return!1}};return doe.set(r,t),r}function uKt(e){return typeof e=="object"&&e!==null&&doe.has(e)}function P$e(e){if(uKt(e))return doe.get(e)}var mm,C1,fm,R$e,doe,cA,Jl=q(()=>{yr();mm=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}},C1=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}},fm=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 wP(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=nl(e),i=n.notify??!0;return e.effect(function*(){let s,o=!1;if(r===void 0)s=this.global;else{let l=this.scoped.get(r);l===void 0?(s=this.createLayer(r),this.scoped.set(r,s),o=!0):s=l}let c;try{c=t(s)}catch(l){throw r!==void 0&&o&&s.isEmpty()&&this.scoped.delete(r),l}yield()=>{c(),r!==void 0&&s.isEmpty()&&this.scoped.delete(r),i&&this.onChange()},i&&this.onChange()}.bind(this),n.label)}},R$e=Symbol("dsh.scope"),doe=new WeakMap,cA=new WeakMap;a(I$e,"linkScopeParent");a(poe,"bindScopeParent");a(C$e,"scopeParentOf");a(wP,"scopeChainOf");a(cKt,"quiesceFiber");a(lKt,"scope");a(Jx,"createScope");a(nl,"scopeOf");a(rl,"scopeTarget");a(uKt,"isScopeCarrier");a(P$e,"carrierKeyOf")});import{accessSync as FUr,constants as jUr,realpathSync as qUr,statSync as WUr}from"node:fs";import{tmpdir as zUr}from"node:os";function CF(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 O$e(e){return`[sandbox: file access denied under ${e} mode]`}function M$e(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 N$e(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 PF(e,t){let{requestedMode:n,effectiveMode:r,justification:i,subject:s}=e;if(n===r)return r;if(!(dKt[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 Pr(o,"EscalationOutcome")}}var dKt,RF,hoe=q(()=>{yr();Ur();ws();dKt={"read-only":["workspace-write","danger-full-access"],"workspace-write":["danger-full-access"]},RF=["workspace-write","danger-full-access"];a(CF,"validateEscalationArgs");a(O$e,"sandboxDenialMarker");a(M$e,"escalationHintMarker");a(N$e,"sandboxPermissionsDescription");a(PF,"approveEscalation")});function Z$e(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 eUe(e){return Object.getPrototypeOf(e)===null&&Z$e(e,"Object")}function tUe(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&eUe(t)}catch{return!1}}function mKt(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Z$e(t,"Array"))return!1;let n=Object.getPrototypeOf(t);return typeof n=="object"&&n!==null&&eUe(n)}function fKt(e){try{return Reflect.ownKeys(e).every(t=>typeof t=="string"&&Object.prototype.propertyIsEnumerable.call(e,t))}catch{return!1}}function US(e){return tUe(e)&&fKt(e)}function TP(e){if(!Array.isArray(e))return!1;try{if(!mKt(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 LF(e){return typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0)}function L$e(e,t){switch(e){case"string":return typeof t=="string";case"number":return LF(t);case"integer":return LF(t)&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;default:return Pr(e,"JsonSchemaType")}}function gKt(e,t,n,r){let i=Object.hasOwn(e,"required"),s=i?e.required:void 0;if(i)if(!TP(s)||s.some(o=>typeof o!="string"))r.push(`${t}.required must be an array of strings`);else{let o=US(n)?n:{};for(let c of s)Object.hasOwn(o,c)||r.push(`${t}.required names "${c}" which is not in properties`)}Object.hasOwn(e,"additionalProperties")&&typeof e.additionalProperties!="boolean"&&r.push(`${t}.additionalProperties must be a boolean`)}function nUe(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 D$e)Object.hasOwn(s.node,h)&&n.push(`${s.path}.${h} is not supported beside oneOf`);continue}if(s.kind==="object-tail"){gKt(s.node,s.path,s.properties,n);continue}let{node:o,path:c}=s;if(!US(o)){n.push(`${c} must be a schema object`);continue}if(r.has(o)){n.push(`${c} is circular`);continue}r.add(o),i.push({kind:"leave",node:o});for(let h of Object.keys(o))if(!pKt.has(h)){if(hKt.has(h)){try{R1(o[h])||n.push(`${c}.${h} annotation must be lossless JSON data`)}catch{n.push(`${c}.${h} annotation must be lossless JSON data`)}continue}n.push(`${c}.${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(`${c}.description must be a string`),Object.hasOwn(o,"title")&&typeof o.title!="string"&&n.push(`${c}.title must be a string`);let l=Object.hasOwn(o,"type"),u=Object.hasOwn(o,"oneOf");if(l&&u){n.push(`${c} cannot declare both type and oneOf`);continue}if(!l&&!u){for(let h of D$e)Object.hasOwn(o,h)&&n.push(`${c}.${h} requires type or oneOf`);continue}if(u){let h=o.oneOf;if(i.push({kind:"one-of-tail",node:o,path:c}),!TP(h)||h.length<2)n.push(`${c}.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:`${c}.oneOf[${m}]`});continue}let d=o.type;if(typeof d!="string"||!boe.includes(d)){n.push(Array.isArray(d)?`${c}.type must be a single type string (type arrays are not supported)`:`${c}.type must be one of ${boe.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(`${c}.${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:c,properties:h}),Object.hasOwn(o,"properties"))if(!US(h))n.push(`${c}.properties must be an object of schemas`);else{let m=Object.entries(h);for(let f=m.length-1;f>=0;f--){let g=m[f];g!==void 0&&i.push({kind:"enter",node:g[1],path:`${c}.properties.${g[0]}`})}}break}case"array":Object.hasOwn(o,"items")&&i.push({kind:"enter",node:o.items,path:`${c}.items`});break;case"string":case"number":case"integer":case"boolean":case"null":{let h=Object.hasOwn(o,"enum"),m=h?o.enum:void 0,f=TP(m)&&m.length>0&&m.every(b=>L$e(p,b));h&&!f&&n.push(`${c}.enum must be a non-empty array of ${p} values`);let g=Object.hasOwn(o,"const"),v=g?o.const:void 0,x=L$e(p,v);g&&(x?f&&!m.includes(v)&&n.push(`${c}.const must be one of ${c}.enum when both are declared`):n.push(`${c}.const must be a ${p} value`));break}default:Pr(p,"JsonSchemaType")}}}function jS(e){let t=[];if(nUe(e,"schema",t,new Set),t.length>0)throw new RP(t)}function $F(e){let t=[];if(nUe(e,"schema",t,new Set),t.length===0&&(!US(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 RP(t)}function moe(e){try{return R1(e)}catch{return!1}}function up(e){return e===""?"arguments":e}function foe(e,t){return e===""?t:`${e}.${t}`}function goe(e){return[`"${up(e)}" must be a lossless JSON value`]}function $$e(e,t){for(let n of t)e.push(n)}function U$e(e,t,n){return{node:e,value:t,path:n,catches:!1,phase:"start",children:[],childIndex:0,violations:[],tailViolations:[],matches:0}}function kP(e,t,n){let r=Object.hasOwn(e,"enum")?e.enum:void 0;return r!==void 0&&!r.includes(t)?[`"${up(n)}" must be one of ${JSON.stringify(r)}`]:Object.hasOwn(e,"const")&&t!==e.const?[`"${up(n)}" must be ${JSON.stringify(e.const)}`]:[]}function yKt(e,t,n){let r=[U$e(e,t,n)],i,s=a(c=>{let l=r.at(-1);if(l===void 0){i=c;return}l.kind==="oneOf"?c.length===0&&l.matches++:$$e(l.violations,c)},"receive"),o=a(c=>{r.pop(),s(c)},"finish");for(;r.length>0;){let c=r.at(-1);if(c===void 0)break;try{if(c.phase==="children"){if(c.childIndex<c.children.length){let d=c.children[c.childIndex];if(d===void 0)throw new Error("missing schema-value child frame");c.childIndex++,r.push(U$e(d.node,d.value,d.path));continue}if(c.kind==="oneOf"){o(c.matches===1?[]:[`"${up(c.path)}" must match exactly one oneOf branch (matched ${c.matches})`]);continue}$$e(c.violations,c.tailViolations),c.violations.length>0?o(c.violations):c.kind==="object"?o(moe(c.value)?[]:[`"${up(c.path)}" must be a lossless JSON object`]):o(moe(c.value)?[]:[`"${up(c.path)}" must be a dense lossless JSON array`]);continue}let l=Object.hasOwn(c.node,"type")?c.node.type:void 0;c.catches=!(l!==void 0&&!boe.includes(l));let u=Object.hasOwn(c.node,"oneOf")?c.node.oneOf:void 0;if(u!==void 0){c.kind="oneOf",c.children=Array.from(u,d=>({node:d,value:c.value,path:c.path})),c.childIndex=0,c.matches=0,c.phase="children";continue}if(l===void 0){o(moe(c.value)?[]:goe(c.path));continue}switch(l){case"object":{if(!tUe(c.value)){o([`"${up(c.path)}" must be an object`]);break}let d=Object.hasOwn(c.node,"properties")?c.node.properties??{}:{},p=[],h=Object.hasOwn(c.node,"required")?c.node.required??[]:[];for(let g of h)(!Object.hasOwn(c.value,g)||c.value[g]===void 0)&&p.push(`missing required property "${foe(c.path,g)}"`);let m=[];for(let[g,v]of Object.entries(d))!Object.hasOwn(c.value,g)||c.value[g]===void 0||m.push({node:v,value:c.value[g],path:foe(c.path,g)});let f=[];if(Object.hasOwn(c.node,"additionalProperties")&&c.node.additionalProperties===!1)for(let g of Object.keys(c.value))Object.hasOwn(d,g)||f.push(`"${foe(c.path,g)}" is not a declared property (additionalProperties: false)`);c.kind="object",c.children=m,c.childIndex=0,c.violations=p,c.tailViolations=f,c.phase="children";break}case"array":{if(!Array.isArray(c.value)){o([`"${up(c.path)}" must be an array`]);break}let d=Object.hasOwn(c.node,"items")?c.node.items:void 0,p=d===void 0?[]:c.value.flatMap((h,m)=>[{node:d,value:h,path:`${c.path}[${m}]`}]);c.kind="array",c.children=p,c.childIndex=0,c.violations=[],c.phase="children";break}case"string":o(typeof c.value=="string"?kP(c.node,c.value,c.path):[`"${up(c.path)}" must be a string`]);break;case"number":o(typeof c.value!="number"?[`"${up(c.path)}" must be a number`]:LF(c.value)?kP(c.node,c.value,c.path):[`"${up(c.path)}" must be a finite JSON number`]);break;case"integer":o(!LF(c.value)||!Number.isInteger(c.value)?[`"${up(c.path)}" must be an integer`]:kP(c.node,c.value,c.path));break;case"boolean":o(typeof c.value=="boolean"?kP(c.node,c.value,c.path):[`"${up(c.path)}" must be a boolean`]);break;case"null":o(c.value===null?kP(c.node,c.value,c.path):[`"${up(c.path)}" must be null`]);break;default:o(Pr(l,"JsonSchemaType"))}}catch(l){let u=r.pop();for(;u!==void 0&&!u.catches;)u=r.pop();if(u===void 0)throw l;s(goe(u.path))}}return i??goe(n)}function UF(e,t,n="value"){return yKt(e,t,n)}function dp(e){throw new RP([e])}function SP(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 _P(e,t,n){for(let r of Object.keys(e))n.includes(r)||dp(`${t}.${r} is not supported by the value schema DSL`)}function xKt(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 bKt(e,t){e.kind==="root"?e.holder.value=t:e.target.properties=t.properties}function rUe(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"){US(r.property)||dp(`${r.path} must be a value schema object`),Object.hasOwn(r.property,"required")&&r.property.required!==!0&&dp(`${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"){US(r.input)||dp(`${r.path} must be an object of value schemas`),t.has(r.input)&&dp(`${r.path} is circular`),t.add(r.input);let u={properties:{}},d=[];bKt(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;US(i)||dp(`${s} must be a value schema object`),t.has(i)&&dp(`${s} is circular`),t.add(i);let o=[...vKt,...r.allowRequired?["required"]:[]],c={};if(xKt(r.destination,c),n.push({kind:"leave",input:i}),Object.hasOwn(i,"oneOf")){_P(i,s,[...o,"oneOf","type"]),Object.hasOwn(i,"type")&&dp(`${s} cannot declare both type and oneOf`),TP(i.oneOf)||dp(`${s}.oneOf must be an array of at least two value schemas`);let u=[];c.oneOf=u,SP(i,c);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 l=Object.hasOwn(i,"type")?i.type:void 0;switch(l){case"json":_P(i,s,[...o,"type"]),SP(i,c);break;case"object":_P(i,s,[...o,"type","properties","additionalProperties"]),(!Object.hasOwn(i,"additionalProperties")||typeof i.additionalProperties!="boolean")&&dp(`${s}.additionalProperties must be explicitly true or false`),c.type="object",SP(i,c),c.additionalProperties=i.additionalProperties,Object.hasOwn(i,"properties")&&n.push({kind:"property-map",input:i.properties,path:`${s}.properties`,destination:{kind:"object",target:c}});break;case"array":_P(i,s,[...o,"type","items"]),c.type="array",SP(i,c),Object.hasOwn(i,"items")&&n.push({kind:"value",input:i.items,path:`${s}.items`,allowRequired:!1,destination:{kind:"item",target:c}});break;case"string":case"number":case"integer":case"boolean":case"null":_P(i,s,[...o,"type","enum","const"]),c.type=l,SP(i,c),Object.hasOwn(i,"enum")&&(TP(i.enum)||dp(`${s}.enum must be a non-empty array of scalar values`),c.enum=Array.from(i.enum,u=>u)),Object.hasOwn(i,"const")&&(c.const=i.const);break;default:dp(`${s}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`)}}}function wKt(e,t){let n={};return rUe({kind:"property-map",input:e,path:t,destination:{kind:"root",holder:n}}),n.value??dp(`${t} did not compile`)}function kKt(e,t){let n={};return rUe({kind:"value",input:e,path:t,allowRequired:!1,destination:{kind:"root",holder:n}}),n.value??dp(`${t} did not compile`)}function SKt(e){let t=kKt(e,"schema");return jS(t),t}function iUe(e){let t=wKt(e,"parameters"),n={type:"object",properties:t.properties,...t.required===void 0?{}:{required:t.required}};return jS(n),n}function Wn(e){let t=e.execute,n=e.finalizeContent,r=e.projectContent,i=e.output.render,s=e.output.presentationMeta,o=e.presentCall,c=e.presentResult,l=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=iUe(e.parameters),d=SKt(e.output.schema),p=a(m=>UF(u,m,""),"validate"),h={name:e.name,description:e.description,parameters:u,output:{schema:d,render(m,f){return i(m,f)},...s!==void 0?{presentationMeta(m,f){return s(m,f)}}:{}},...e.deferLoading===!0?{deferLoading:e.deferLoading}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},async execute(m,f){let g=p(m);if(g.length>0)throw new Eoe(g);return t(m,f)}};return r&&(h.projectContent=(m,f)=>r(m,f)),n&&(h.finalizeContent=(m,f)=>n(m,f)),o&&(h.presentCall=m=>{if(!(p(m).length>0))return o(m)}),c&&(h.presentResult=(m,f)=>{if(!(p(m).length>0))return c(m,f)}),l&&(h.isConcurrencySafe=m=>p(m).length>0?!1:l(m)),h}function Toe(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 TKt(e){return e===void 0?EP:{...e.timeout===void 0?{}:{timeoutMs:{...EP.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:EP.sandbox_permissions,justification:EP.justification}}}function voe(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 j$e(e){let t=e();if(t===void 0)return DF;let n=yoe[t.language];if(!Object.hasOwn(yoe,t.language)||n===void 0){let r=Object.keys(yoe).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"?EKt:n}function IKt(e){let t;try{t=Qs(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=Qs(t);if(n===void 0)throw new Error("tool arguments could not be detached for durable logging");return{dispatched:t,logged:n}}function CKt(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>RKt,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:" "},GDe=/[\\\u0000-\u001f]/u;a(Vx,"isWhitespace");a(wVt,"isHex");tUr=class rA{static{a(this,"PartialArguments")}static EMPTY=rA.fromObject({});static fromText(t){let n=new rA;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new rA;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="";#c=null;#a=[];#p=!1;#m;#h=!1;#l=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 rA.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return rA.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.#l.has(t):Object.hasOwn(this.object,t)}completeNow(t){if(this.object!==void 0)return Object.hasOwn(this.object,t);let n=this.#l.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.#l.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.#l.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.#l.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.#l.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 c=r+1;c<i;c++)o.push(this.chunks[c]);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 c=Math.min(s-n.at,r-n.length);if(c<=0)return;i&&(n.text+=this.slice(n.at,n.at+c)),n.at+=c,n.length+=c;return}let o=this.chunkAt(n.at);for(;n.at<s&&n.length<r;){let c=o===0?0:this.#e[o-1],l=this.chunks[o],u=l.slice(n.at-c,Math.min(l.length,s-c)),d=u.search(GDe),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===c+l.length&&o++;continue}let h=u.length>1?u[1]:n.at+1<s?this.chunks[o+1][0]:void 0,m,f=2;if(u[0]==="\\"&&h===void 0&&t.end<0)return;if(u[0]==="\\"&&h==="u"){let g=this.slice(n.at+2,Math.min(s,n.at+6)),v=!0;for(let x=0;x<g.length;x++)wVt(g[x])||(v=!1);if(v){if(g.length<4&&t.end<0)return;g.length===4&&(m=String.fromCharCode(Number.parseInt(g,16)))}f=6}else u[0]==="\\"&&h!==void 0&&(m=bVt[h]);if(m===void 0){t.invalidAt=n.at,this.#h=!0;return}for(i&&(n.text+=m),n.length++,n.at+=f;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 l=this.#c;!l.needsDecoding&&GDe.test(t.slice(r,s))&&(l.needsDecoding=!0)}let o=s;for(;o>r&&t[o-1]==="\\";)o--;let c=(s-o)%2===1!==(o===r&&this.#i);if(this.#i=i<0&&c,i<0||!c)return s;r=i+1}}step(t,n){switch(this.#t){case"root":if(Vx(t))return;if(t==="{"){this.#t="key-or-end";return}this.fail();return;case"key-or-end":if(Vx(t))return;if(t==="}"){this.#t="closed";return}if(t==='"'){this.beginKey(n);return}this.fail();return;case"key-only":if(Vx(t))return;if(t==='"'){this.beginKey(n);return}this.fail();return;case"key":this.stepKey(t,n);return;case"colon":if(Vx(t))return;if(t===":"){this.#t="value";return}this.fail();return;case"value":this.beginValue(t,n);return;case"string":{let r=this.#c;r.end=n,this.#c=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(Vx(t))return;if(t===","){this.#t="key-only";return}if(t==="}"){this.#t="closed";return}this.fail();return;case"closed":if(Vx(t))return;this.fail();return;case"invalid":return;default:Pr(this.#t)}}fail(){this.#m=this.#r,this.#t="invalid",this.#c=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.#l.has(this.#u)||this.#f.push(this.#u),this.#l.set(this.#u,t),this.#c=t}beginValue(t,n){if(!Vx(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!=="}"&&!Vx(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.#c;n.end=t,this.#c=null}};a(Pr,"assertNever");a(VDe,"hasIntrinsicConstructor");a(KDe,"isIntrinsicObjectPrototype");a(kVt,"hasPlainArrayPrototype");a(SVt,"hasPlainObjectPrototype");a(_Vt,"enumerableStringKeys");a(QDe,"walkJsonValue");a(Qs,"snapshotJsonValue");a(R1,"isJsonValue");a(tl,"deepEqualJson");a(jn,"deepFreeze")});function fF(){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 Qse=q(()=>{a(fF,"randomUUID")});var Nc=q(()=>{});function EVt(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 hP(e){return e?.$value??e?.$inner}function JDe(e){return ADe(e??{},t=>!t.startsWith("$"))}function iA(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 ks("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,c]of Object.entries(e.dict))iA(c,[...t,o],s,r);if(e.sKey&&iA(e.sKey,[...t,"<key>"],!0,r),e.inner&&(e.type!=="lazy"||e.inner[mP])&&iA(e.inner,[...t,"*"],!0,r),e.list)for(let o=0;o<e.list.length;o++)iA(e.list[o],[...t,String(o)],!0,r)}function Xse(e,t,n,r,i=!1){let{max:s=1/0,min:o=-1/0}=t;if(e>s)throw new ks(`expected ${n} <= ${s} but got ${e}`,r);if(e<o&&!i)throw new ks(`expected ${n} >= ${o} but got ${e}`,r)}function Jse(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 TVt(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(Jse(e,i)-Jse(t,i))%Jse(n,i)===0}function gF(e,t,n,r){try{let[i,s]=j.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?Dse(n.meta.default):n.meta.default}}function Yse(e,t){for(let n in t)n in e||(e[n]=t[n])}function Pu(e,t,n){e$e[e]=n,Object.assign(j,{[e](...r){let i=new j({type:e});return t.forEach((s,o)=>{switch(s){case"sKey":i.sKey=r[o]??j.string();break;case"inner":i.inner=j.from(r[o]);break;case"list":i.list=r[o].map(j.from);break;case"dict":i.dict=Hf(r[o],j.from);break;case"bits":i.bits={};for(let c in r[o])typeof r[o][c]=="number"&&(i.bits[c]=r[o][c]);break;case"callback":{let c=i.callback=r[o];c.toJSON||=()=>c.toString();break}case"constructor":{let c=i.constructor=r[o];typeof c=="function"&&(c.toJSON||=()=>c.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 mP,XDe,ks,j,ZDe,YDe,e$e,kn=q(()=>{Gx();mP=Symbol.for("schemastery"),XDe=Symbol.for("ValidationError");globalThis.__schemastery_index__??=0;globalThis.__schemastery_refs__=void 0;ks=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?.[XDe]}};Object.defineProperty(ks.prototype,XDe,{value:!0});j=a(function(e){let t=a(function(n,r={}){return j.resolve(n,t,r)[0]},"schema");if(e.refs){let n=Hf(e.refs,i=>new j(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&&Hf(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,j.prototype),t.meta||={},t.toString=t.toString.bind(t),t},"Schema");j.prototype=Object.create(Function.prototype);j.prototype[mP]=!0;Object.defineProperty(j.prototype,"~standard",{get(){return{version:1,vendor:"schemastery",validate:a(e=>{try{return{value:j.resolve(e,this,{})[0]}}catch(t){if(ks.is(t))return{issues:[{message:t.message,path:t.options.path}]};throw t}},"validate")}}});j.ValidationError=ks;j.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");j.prototype.set=a(function(t,n){return this.dict[t]=n,this},"set");j.prototype.push=a(function(t){return this.list.push(t),this},"push");a(EVt,"mergeDesc");a(hP,"getInner");a(JDe,"extractKeys");j.prototype.i18n=a(function(t){let n=j(this),r=EVt(n.meta.description,t);return Object.keys(r).length&&(n.meta.description=r),n.dict&&(n.dict=Hf(n.dict,(i,s)=>i.i18n(Hf(t,o=>hP(o)?.[s]??o?.[s])))),n.list&&(n.list=n.list.map((i,s)=>i.i18n(Hf(t,(o={})=>Array.isArray(hP(o))?hP(o)[s]:Array.isArray(o)?o[s]:JDe(o))))),n.inner&&(n.inner=n.inner.i18n(Hf(t,i=>hP(i)?hP(i):JDe(i)))),n.sKey&&(n.sKey=n.sKey.i18n(Hf(t,i=>i?.$key))),n},"i18n");j.prototype.extra=a(function(t,n){let r=j(this);return r.meta={...r.meta,[t]:n},r},"extra");for(let e of["required","disabled","collapse","hidden","loose"])Object.assign(j.prototype,{[e](t=!0){let n=j(this);return n.meta={...n.meta,[e]:t},n}});j.prototype.deprecated=a(function(){let t=j(this);return t.meta.badges||=[],t.meta.badges.push({text:"deprecated",type:"danger"}),t},"deprecated");j.prototype.experimental=a(function(){let t=j(this);return t.meta.badges||=[],t.meta.badges.push({text:"experimental",type:"warning"}),t},"experimental");j.prototype.pattern=a(function(t){let n=j(this),r=IDe(t,["source","flags"]);return n.meta={...n.meta,pattern:r},n},"pattern");j.prototype.simplify=a(function(t){if(um(t)&&(t=t.get()),ph(t,this.meta.default,this.type==="dict"))return null;if(Pa(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"||!Pa(i))&&(n[r]=i)}return ph(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 j.resolve(t,n,{}),n.simplify(t)}catch{}return t},"simplify");j.prototype.toString=a(function(t){return e$e[this.type]?.(this,t)??`Schema<${this.type}>`},"toString");j.prototype.role=a(function(e,t){let n=j(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(j.prototype,{[e](t){let n=j(this);return n.meta={...n.meta,[e]:t},n}});j.prototype.volatile=a(function(){if(this.meta.volatile)throw new TypeError("volatile schema is already wrapped");return this.extra("volatile",!0)},"volatile");ZDe={},YDe=Symbol("checked-volatile-schema");a(iA,"validateVolatileSchema");j.extend=a(function(t,n){ZDe[t]=n},"extend");j.resolve=a(function(t,n,r={},i=!1){if(!n)return[t];if(r[YDe]||(iA(n,r.path),r={...r,[YDe]:!0}),n.meta?.volatile){let o=j(n);o.meta={...n.meta,volatile:!1};let[c,l]=j.resolve(t,o,r,i);try{return[Dse(c),l]}catch(u){throw new ks(u instanceof Error?u.message:String(u),r)}}if(r.ignore?.(t,n))return[t];if(Pa(t)&&n.type!=="lazy"){if(n.meta.required)throw new ks("missing required value",r);let o=n,c=n.meta.default;for(;o?.type==="intersect"&&Pa(c);)o=o.list[0],c=o?.meta.default;if(Pa(c))return[t];t=iF(c)}let s=ZDe[n.type];if(!s)throw new ks(`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");j.from=a(function(t){if(Pa(t))return j.any();if(["string","number","boolean"].includes(typeof t))return j.const(t).required();if(t[mP])return t;if(typeof t=="function")switch(t){case String:return j.string().required();case Number:return j.number().required();case Boolean:return j.boolean().required();case Function:return j.function().required();default:return j.is(t).required()}else throw new TypeError(`cannot infer schema from ${t}`)},"from");j.lazy=a(function(t){let n=a(()=>(r.inner[mP]||(r.inner=r.builder(),r.inner.meta={...r.meta,...r.inner.meta}),r.inner.toJSON()),"toJSON"),r=new j({type:"lazy",builder:t,inner:{toJSON:n}});return r},"lazy");j.natural=a(function(){return j.number().step(1).min(0)},"natural");j.percent=a(function(){return j.number().step(.01).min(0).max(1).role("slider")},"percent");j.date=a(function(){return j.union([j.is(Date),j.transform(j.string().role("datetime"),(t,n)=>{let r=new Date(t);if(isNaN(+r))throw new ks(`invalid date "${t}"`,n);return r},!0)])},"date");j.regExp=a(function(t=""){return j.union([j.is(RegExp),j.transform(j.string().role("regexp",{flag:t}),(n,r)=>{try{return new RegExp(n,t)}catch(i){throw new ks(i.message,r)}},!0)])},"regExp");j.arrayBuffer=a(function(t){return j.union([j.is(ArrayBuffer),j.is(SharedArrayBuffer),j.transform(j.any(),(n,r)=>{if(zf.isSource(n))return zf.fromSource(n);throw new ks(`expected ArrayBufferSource but got ${n}`,r)},!0),...t?[j.transform(j.string(),(n,r)=>{try{return t==="base64"?zf.fromBase64(n):zf.fromHex(n)}catch(i){throw new ks(i.message,r)}},!0)]:[]])},"arrayBuffer");j.extend("lazy",(e,t,n,r)=>(t.inner[mP]||(t.inner=t.builder(),t.inner.meta={...t.meta,...t.inner.meta},iA(t.inner,n.path,!0)),j.resolve(e,t.inner,n,r)));j.extend("any",e=>[e]);j.extend("never",(e,t,n)=>{throw new ks(`expected nullable but got ${e}`,n)});j.extend("const",(e,{value:t},n)=>{if(ph(e,t))return[t];throw new ks(`expected ${t} but got ${e}`,n)});a(Xse,"checkWithinRange");j.extend("string",(e,{meta:t},n)=>{if(typeof e!="string")throw new ks(`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 ks(`expect string to match regexp ${r}`,n)}return Xse(e.length,t,"string length",n),[e]});a(Jse,"decimalShift");a(TVt,"isMultipleOf");j.extend("number",(e,{meta:t},n)=>{if(typeof e!="number")throw new ks(`expected number but got ${e}`,n);Xse(e,t,"number",n);let{step:r}=t;if(r&&!TVt(e,t.min??0,r))throw new ks(`expected number multiple of ${r} but got ${e}`,n);return[e]});j.extend("boolean",(e,t,n)=>{if(typeof e=="boolean")return[e];throw new ks(`expected boolean but got ${e}`,n)});j.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 ks(`expected string but got ${o}`,r);o in t&&(i|=t[o])}}else throw new ks(`expected number or array but got ${e}`,r);return i===n.default?[i]:[i,s]});j.extend("function",(e,t,n)=>{if(typeof e=="function")return[e];throw new ks(`expected function but got ${e}`,n)});j.extend("is",(e,{constructor:t},n)=>{if(typeof t=="function"){if(e instanceof t)return[e];throw new ks(`expected ${t.name} but got ${e}`,n)}else{if(Pa(e))throw new ks(`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 ks(`expected ${t} but got ${e}`,n)}});a(gF,"property");j.extend("array",(e,{inner:t,meta:n},r)=>{if(!Array.isArray(e))throw new ks(`expected array but got ${e}`,r);return Xse(e.length,n,"array length",r,!Pa(t.meta.default)),[e.map((i,s)=>gF(e,s,t,r))]});j.extend("dict",(e,{inner:t,sKey:n},r,i)=>{if(!sF(e))throw new ks(`expected object but got ${e}`,r);let s={};for(let o in e){let c;try{c=j.resolve(o,n,r)[0]}catch(l){if(i)continue;throw l}s[c]=gF(e,o,t,r),e[c]=e[o],o!==c&&delete e[o]}return[s]});j.extend("tuple",(e,{list:t},n,r)=>{if(!Array.isArray(e))throw new ks(`expected array but got ${e}`,n);let i=t.map((s,o)=>gF(e,o,s,n));return r?[i]:(i.push(...e.slice(t.length)),[i])});a(Yse,"merge");j.extend("object",(e,{dict:t},n,r)=>{if(!sF(e))throw new ks(`expected object but got ${e}`,n);let i={};for(let s in t){let o=gF(e,s,t[s],n);(!Pa(o)||s in e)&&(i[s]=o)}return r||Yse(i,e),[i]});j.extend("union",(e,{list:t,toString:n},r,i)=>{let s=[];for(let o of t)try{return j.resolve(e,o,r,i)}catch(c){s.push(c)}throw new ks(`expected ${n()} but got ${JSON.stringify(e)}`,r)});j.extend("intersect",(e,{list:t,toString:n},r,i)=>{if(!t.length)return[e];let s;for(let o of t){let c=j.resolve(e,o,r,!0)[0];if(!Pa(c))if(Pa(s))s=c;else{if(typeof s!=typeof c)throw new ks(`expected ${n()} but got ${JSON.stringify(e)}`,r);if(typeof c=="object")Yse(s??={},c);else if(s!==c)throw new ks(`expected ${n()} but got ${JSON.stringify(e)}`,r)}}return!i&&sF(e)&&Yse(s,e),[s]});j.extend("transform",(e,{inner:t,callback:n,preserve:r},i)=>{let[s,o=e]=j.resolve(e,t,i,!0);return r?[n(s)]:[n(s),n(o)]});e$e={};a(Pu,"defineMethod");Pu("is",["constructor"],({constructor:e})=>typeof e=="function"?e.name:e);Pu("any",[],()=>"any");Pu("never",[],()=>"never");Pu("const",["value"],({value:e})=>typeof e=="string"?JSON.stringify(e):e);Pu("string",[],()=>"string");Pu("number",[],()=>"number");Pu("boolean",[],()=>"boolean");Pu("bitset",["bits"],()=>"bitset");Pu("function",[],()=>"function");Pu("array",["inner"],({inner:e})=>`${e.toString(!0)}[]`);Pu("dict",["inner","sKey"],({inner:e,sKey:t})=>`{ [key: ${t.toString()}]: ${e.toString()} }`);Pu("tuple",["list"],({list:e})=>`[${e.map(t=>t.toString()).join(", ")}]`);Pu("object",["dict"],({dict:e})=>Object.keys(e).length===0?"{}":`{ ${Object.entries(e).map(([t,n])=>`${t}${n.meta.required?"":"?"}: ${n.toString()}`).join(", ")} }`);Pu("union",["list"],({list:e},t)=>{let n=e.map(({toString:r})=>r()).join(" | ");return t?`(${n})`:n});Pu("intersect",["list"],({list:e})=>`${e.map(t=>t.toString(!0)).join(" & ")}`);Pu("transform",["inner","callback","preserve"],({inner:e},t)=>e.toString(t))});function t$e(e,t){if(!Number.isFinite(e)||e<=0||e>2147483647)throw new Error(`${t} must be a positive finite number no greater than ${Ss}`)}function n$e(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 Gf(e,t,n){if(t<=0)return{signal:e??new AbortController().signal,[Symbol.dispose](){}};t$e(t,"deadline timeoutMs");let r=new AbortController,i=setTimeout(()=>{r.abort(new Zse(n,t))},t);return{signal:e!==void 0?AbortSignal.any([e,r.signal]):r.signal,[Symbol.dispose](){clearTimeout(i)}}}function yF(e,t,n){t$e(t,"idleWatchdog timeoutMs");let r=new AbortController,i=e===void 0?r.signal:AbortSignal.any([e,r.signal]),s=new Zse(n,t),o,c=!1,l=!1,u=a(()=>{o!==void 0&&clearTimeout(o),o=setTimeout(()=>{r.abort(s)},t)},"arm");return{signal:i,async next(d){if(l)throw new Error("idleWatchdog is disposed");if(c)throw new Error("idleWatchdog next is already outstanding");c=!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,c=!1}},pulse(){l||!c||u()},[Symbol.dispose](){l||(l=!0,o!==void 0&&clearTimeout(o),o=void 0)}}}function Vf(e,t){let n=e.reason;if(n instanceof Zse)return t===void 0||n.code===t?n:void 0}var Zse,Ss,pm=q(()=>{Zse=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}},Ss=2147483647;a(t$e,"assertTimerDelay");a(n$e,"clampTimeout");a(Gf,"deadline");a(yF,"idleWatchdog");a(Vf,"timeoutOf")});function Kx(e){return e.length<=120?e:`${e.slice(0,119)}\u2026`}function hm(e){return jn(structuredClone(e))}function gP(e){return jn(structuredClone({...e,id:fF()}))}function a$e(e){return gP({...e,role:"developer"})}function tr(e){return gP({...e,role:"user"})}function xF(e){return gP({role:"assistant",content:e.content,source:{kind:"model",...e.source}})}function bF(e){return gP({role:"system",content:e.length===0?[]:[{type:"text",text:e}],source:{kind:"system-prompt"}})}function c$e(e){return gP({role:"tool",source:{kind:"tool",callId:e.callId},toolCallId:e.callId,content:e.content,isError:e.isError})}function kF(e){return AVt.test(e)||/\b(?:maximum|max)(?:\s+(?:allowed|supported))?\s+context\s+(?:length|window)\b/i.test(e)||IVt.test(e)||/\b(?:input|prompt|request)\s+(?:is\s+)?too\s+(?:long|large)\s+for\s+(?:this|the)\s+model\b/i.test(e)||RVt.test(e)}function SF(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 Ou(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 c=Object.getOwnPropertyDescriptor(r,"message");if(c!==void 0&&"value"in c&&typeof c.value=="string")return c.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 soe(e,t,n){for(let r of Object.keys(e))if(!t.has(r))throw new Error(`${n}: unknown key "${r}"`)}function eoe(e,t){e!==void 0&&soe(e,NVt,t);let n=e?.initialDelayMs??u$e,r=e?.maxDelayMs??d$e,i=e?.jitterRatio??p$e;if(!Number.isFinite(n)||n<=0||n>Ss)throw new Error(`${t}.initialDelayMs must be a positive finite number no greater than ${Ss}`);if(!Number.isFinite(r)||r<=0||r>Ss)throw new Error(`${t}.maxDelayMs must be a positive finite number no greater than ${Ss}`);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 yP(e,t){if(e===void 0)return Object.freeze({mode:"normal",maxRetries:roe,retryableCodes:ioe,...eoe(void 0,`${t}.backoff`)});switch(e.mode){case"normal":{soe(e,OVt,t);let n=e.maxRetries??roe,r=e.retryableCodes??[...ioe];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]),...eoe(e.backoff,`${t}.backoff`)})}case"always":return soe(e,MVt,t),Object.freeze({mode:"always",...eoe(e.backoff,`${t}.backoff`)});default:throw new Error(`${t}.mode must be "normal" or "always"`)}}function fP(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 f$e(e){return m$e.add(e),e}function g$e(e){return m$e.has(e)}function LVt(e){let t=e instanceof Error?e:new oi(DVt(e),"UNKNOWN",{cause:e}),n=UVt(t);return n!==void 0&&n.code===$Vt(t)?n:Object.freeze({message:jVt(t),code:qVt(t)})}function DVt(e){try{let t=String(e);return t.length>0?t:"LLM adapter failed"}catch{return"LLM adapter failed"}}function $Vt(e){try{let t=Object.getOwnPropertyDescriptor(e,"code");return t!==void 0&&"value"in t?t.value:void 0}catch{return}}function UVt(e){try{let t=Object.getOwnPropertyDescriptor(e,"failure");return t!==void 0&&"value"in t?FVt(t.value):void 0}catch{return}}function FVt(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,c=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)||c!==void 0&&(!Number.isSafeInteger(c)||c<=0)?void 0:Object.freeze({message:n,code:r,...i===void 0?{}:{status:i},...s===void 0?{}:{providerRetryAfterMs:s},...o===void 0?{}:{requestId:o},...c===void 0?{}:{offloadImages:c}})}catch{return}}function jVt(e){try{let t=e.message;if(typeof t=="string"&&t.length>0)return t}catch{}return"LLM adapter failed"}function qVt(e){return e instanceof oi?e.code:"UNKNOWN"}function coe(e){let t=e.trim();return t.length===0?{ok:!1,reason:"empty"}:WVt.test(t)?{ok:!0,value:t}:{ok:!1,reason:"illegalCharacters"}}function sA(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 vF(e){return JSON.stringify(e)}function y$e(e){return e.name===void 0?String(e.attachmentId):`${vF(e.name)} (${e.attachmentId})`}function BVt(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 Pr(e,"image extension")}}function v$e(e,t){return` Normalized copy (read-only; may be resized or re-encoded): ${vF(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 ${BVt(e.mediaType)} before editing.`}function loe(e){return`[image omitted because this model accepts text only; attachment sha256:${String(e.attachmentId).slice(7,15)}]`}function vP(e,t,n){let r=`Image ${y$e(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+v$e(e,n)}function xP(e,t){let n=`image omitted to fit request image limits; ${y$e(e)}.`;return t===void 0?`[${n} No local normalized image path is available; ask the user to attach it again if needed.]`:`[${n}${v$e(e,t)}]`}function lp(e){return e.some(t=>t.type==="image")}function x$e(e){for(let t of e)if(t.type==="file")return!0;return!1}function b$e(e,t){let n=String(e.attachmentId).slice(7,15),r=`File ${vF(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 ${vF(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 zVt(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:b$e(i.attachment,t(i.attachment))});continue}n?.push(i)}return n??e}function HVt(e,t){return e.some(n=>x$e(n.content))?e.map(n=>{let r=zVt(n.content,t);return r===n.content?n:{...n,content:r}}):e}function GVt(e){return Math.ceil(e/3)*4}function VVt(e,t){for(let n of e)n.type==="image"&&t(n)}function KVt(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 EF(e,t){return e.map(n=>{let r=KVt(n.content,t);return r===n.content?n:{...n,content:r}})}function QVt(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,c=r===0?0:Math.ceil(r/s)*s,l=i===0?0:Math.ceil(i/o)*o,u=0,d=0;for(let p of e){if(u>=c&&(l===0||(o===1?d>=l:d>l)))break;d+=p,u+=1}return u}function TF(e,t,n){let r=[];for(let i of e)VVt(i.content,s=>{if(s.offloaded===!0)return;let o=n(s);r.push(t.representation==="base64"?GVt(o):o)});return QVt(r,t)}function JVt(e){let t;for(let[n,r]of e.entries()){if(r.type==="image"){t??=e.slice(0,n),t.push({type:"text",text:loe(r.attachment)});continue}t?.push(r)}return t??e}function YVt(e){return e.some(t=>lp(t.content))?e.map(t=>{let n=JVt(t.content);return n===t.content?t:{...t,content:n}}):e}function toe(e){let t=e.filter(n=>n.role!=="developer");return t.length===e.length?e:t}function XVt(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 Pr(t)}}function ZVt(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:toe(e),tools:u}}if(r===void 0)return{messages:toe(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:toe(e),tools:t};let s=XVt(t,n,r),o=new Set(r.updates.map(u=>u.messageId)),c=new Set(r.tools.filter(u=>!u.deferLoading).map(u=>u.name)),l=[];for(let u of e){if(u.role!=="developer"){l.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)||c.has(p.toolName)?!1:(c.add(p.toolName),!0);case"tool-removal":return n!=="in-history"?!1:c.delete(p.toolName);default:return!0}});d.length!==0&&(d.length===u.content.length?l.push(u):l.push({...u,content:d}))}return{messages:l.length===e.length&&l.every((u,d)=>u===e[d])?e:l,tools:[...s.values()]}}function tKt(e=Qx){return`${e.product}/${e.version} (+${e.url})`}function LS(e=Qx){return{"user-agent":tKt(e)}}function AF(e){return e}function bP(e){return e}function w$e(e){return e}function k$e(e){return e}function pc(e){return e}function nKt(e){if(!Number.isSafeInteger(e))throw new TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function r$e(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 rKt(e){let t=Qs(e);if(t===void 0)throw new TypeError("Assistant stream chunk must be losslessly JSON-serializable");return t}function i$e(e,t){let n=t-e;return Number.isSafeInteger(n)&&e+n===t?n:void 0}function iKt(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 sKt(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 oKt(e){return e.type==="tool-call-chunks"&&e.name!==void 0?e.time0:sKt(e,t=>t!=="")}function uoe(e){for(let t of e){let n=t.type==="chunk"?iKt(t.chunk)?t.time:void 0:oKt(t);if(n!==void 0)return n}}function S$e(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 _$e(e,t){let n=[];for(let r of e)r.type==="chunk"&&r.chunk.type===t&&n.push(r.chunk);return n}function E$e(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 T$e(e,t=new DS){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:Pr(n,"assembleAssistantStream")}return t}function aA(e,t,n){let r=coe(e);if(r.ok)return r.value;throw new mt(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)`,aoe)}function s$e(e,t){let n=LVt(e);return{type:"finish",reason:t?.aborted||n.code==="ABORTED"?{kind:"aborted",failure:n}:{kind:"error",failure:n}}}function o$e(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 oi,wF,l$e,ooe,aoe,AVt,IVt,RVt,NS,roe,u$e,d$e,p$e,ioe,h$e,CVt,PVt,_F,OVt,MVt,NVt,m$e,WVt,eKt,Qx,DS,oA,aKt,noe,mt,IF,A$e,Ur=q(()=>{dc();ws();Qse();Nc();kn();pm();a(Kx,"boundContextSummary");a(hm,"freezeMessage");a(gP,"createMessage");a(a$e,"createDeveloperMessage");a(tr,"createUserMessage");a(xF,"createAssistantMessage");a(bF,"createSystemMessage");a(c$e,"createToolResultMessage");oi=class extends Error{static{a(this,"HarnessError")}code;constructor(e,t,n){super(e,n),this.code=t,this.name=new.target.name}},wF="CONTEXT_WINDOW_EXCEEDED",l$e="QUOTA",ooe="EMPTY_RESPONSE",aoe="INVALID_CREDENTIAL",AVt=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"),IVt=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"),RVt=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(kF,"isContextWindowExceededError");a(SF,"isQuotaExceededError");a(Ou,"errorChain");NS="IMAGE_OFFLOAD_REQUIRED",roe=5,u$e=500,d$e=1e4,p$e=.1,ioe=Object.freeze([ooe,"RATE_LIMIT","SERVER","TIMEOUT","TRANSPORT"]),h$e=j.object({initialDelayMs:j.number().max(Ss).default(u$e),maxDelayMs:j.number().max(Ss).default(d$e),jitterRatio:j.number().min(0).max(1).default(p$e)}),CVt=j.object({mode:j.const("normal").required(),maxRetries:j.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(roe),retryableCodes:j.array(j.string()).default([...ioe]),backoff:h$e}),PVt=j.object({mode:j.const("always").required(),backoff:h$e}),_F=j.union([CVt,PVt]),OVt=new Set(["mode","maxRetries","retryableCodes","backoff"]),MVt=new Set(["mode","maxRetries","retryableCodes","backoff"]),NVt=new Set(["initialDelayMs","maxDelayMs","jitterRatio"]);a(soe,"validateKeys");a(eoe,"resolveBackoff");a(yP,"resolveRetryPolicy");m$e=new WeakSet;a(fP,"callConfigEquals");a(f$e,"markAgentLoopRequest");a(g$e,"isAgentLoopRequest");a(LVt,"normalizeLlmFailure");a(DVt,"thrownMessage");a($Vt,"ownErrorCode");a(UVt,"ownFailureSnapshot");a(FVt,"failureSnapshot");a(jVt,"errorMessage");a(qVt,"harnessErrorCode");WVt=/^[\x21-\x7E]+$/;a(coe,"normalizeApiKey");a(sA,"resolveImageAttachmentAccess");a(vF,"quoted");a(y$e,"imageIdentity");a(BVt,"extension");a(v$e,"normalizedAccessText");a(loe,"textOnlyImageText");a(vP,"requestImageHandleText");a(xP,"offloadedImageText");a(lp,"contentHasImage");a(x$e,"contentHasFile");a(b$e,"fileHandleText");a(zVt,"replaceFilesWithHandles");a(HVt,"projectFilesToText");a(GVt,"base64Length");a(VVt,"visitImageBlocks");a(KVt,"replaceOffloadedImages");a(EF,"projectOffloadedImages");a(QVt,"offloadedImagePrefixCount");a(TF,"requiredImageOffload");a(JVt,"replaceImagesForTextModel");a(YVt,"projectImagesForTextModel");a(toe,"withoutDeveloperMessages");a(XVt,"toolDeclarations");a(ZVt,"projectToolUpdates");eKt="0.2.1-rc.4",Qx={product:"deepseek-harness",version:eKt,url:"https://github.com/deepseek-ai/deepseek-harness"};a(tKt,"userAgent");a(LS,"attributionHeaders");a(AF,"MessageId");a(bP,"ToolCallId");a(w$e,"ProviderRequestId");a(k$e,"LlmAttemptId");a(pc,"ReasoningEffortId");DS=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 Pr(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 xF({content:this.blocks(),source:e})}};a(nKt,"safeTime");a(r$e,"safeIndex");a(rKt,"snapshotChunk");a(i$e,"safeGap");oA=class{static{a(this,"AssistantStreamAccumulator")}records=[];push(e){let t=nKt(e.time),n=rKt(e.chunk),r=jn({time:t,chunk:n}),i=this.records.at(-1);switch(n.type){case"text-delta":case"reasoning-delta":{if(r$e(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?i$e(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(r$e(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"?i$e(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 Pr(n,"AssistantStreamAccumulator.push")}}snapshot(){return jn(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(iKt,"isTokenDelta");a(sKt,"firstRunMemberTime");a(oKt,"runFirstTokenTime");a(uoe,"assistantStreamFirstTokenTime");a(S$e,"lastAssistantStreamChunk");a(_$e,"assistantStreamChunks");a(E$e,"joinAssistantStreamText");a(T$e,"assembleAssistantStream");aKt=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"),noe=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 c=r.kind,l=c==="getter"?"get":c==="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 f={};for(var g in r)f[g]=g==="access"?{}:r[g];for(var g in r.access)f.access[g]=r.access[g];f.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])(c==="accessor"?{get:d.get,set:d.set}:d[l],f);if(c==="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))&&(c==="field"?i.unshift(p):d[l]=p)}u&&Object.defineProperty(u,r.name,d),h=!0},"__esDecorate"),mt=class extends oi{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(aA,"assertUsableApiKey");IF=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")}}},A$e=(()=>{let e=wi,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=[qt],r=[qt],i=[qt("discoverModels")],noe(this,null,n,{kind:"method",name:"listProviders",static:!1,private:!1,access:{has:a(c=>"listProviders"in c,"has"),get:a(c=>c.listProviders,"get")},metadata:o},null,t),noe(this,null,r,{kind:"method",name:"listConfigurableProviders",static:!1,private:!1,access:{has:a(c=>"listConfigurableProviders"in c,"has"),get:a(c=>c.listConfigurableProviders,"get")},metadata:o},null,t),noe(this,null,i,{kind:"method",name:"remoteDiscoverModels",static:!1,private:!1,access:{has:a(c=>"remoteDiscoverModels"in c,"has"),get:a(c=>c.remoteDiscoverModels,"get")},metadata:o},null,t),o&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})}adapters=(aKt(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 c=o();c!=null&&typeof c.then=="function"&&Promise.resolve(c).then(void 0,l=>{this.warnAdaptersListenerFailure(l)})}catch(c){this.warnAdaptersListenerFailure(c)}}warnAdaptersListenerFailure(o){this.ctx.logger.warn("llm: an llm/adapters-updated listener failed"),this.ctx.logger.warn(o)}registerAdapter(o,c){let l=new Set,u=!1,d=this.ctx.effect(function*(){if(o.length===0)throw new mt("an adapter must register at least one provider","INVALID_ADAPTER");this.commitRoutes(l,this.prepareRoutes(o,c,l)),yield()=>{u=!0;for(let h of l)this.adapters.delete(h);l.clear(),this.emitAdaptersUpdated()}}.bind(this),"llm.registerAdapter()"),p=a((()=>{d()}),"handle");return p.replace=h=>{if(u)throw new mt("a disposed adapter registration cannot replace its routes","REGISTRATION_DISPOSED");this.commitRoutes(l,this.prepareRoutes(h,c,l))},p}prepareRoutes(o,c,l){let u=new Set,d=[];for(let p of o){if(p.length===0)throw new mt("adapter provider names must be non-empty","INVALID_ADAPTER");if(u.has(p)||this.adapters.has(p)&&!l.has(p))throw new mt(`an adapter for provider "${p}" is already registered`,"DUPLICATE_ADAPTER");let h=c.providerInfo(p);if(typeof h.id!="string"||h.id!==p||typeof h.name!="string"||h.name.length===0)throw new mt(`adapter metadata for provider "${p}" must preserve its id and have a non-empty name`,"INVALID_ADAPTER");u.add(p);let m=c.providerRetryPolicy(p)??yP(void 0,`llm: provider "${p}" retryPolicy`);d.push({adapter:c,provider:{id:h.id,name:h.name},retryPolicy:m})}return d}commitRoutes(o,c){for(let l of o)this.adapters.delete(l);o.clear();for(let l of c)this.adapters.set(l.provider.id,l),o.add(l.provider.id);this.emitAdaptersUpdated()}listProviders(){return[...this.adapters.values()].map(({provider:o})=>({...o}))}registerConfigurableProviders(o){let c=[],l=!1,u=a(h=>{let m=[],f=new Set(c.map(g=>g.provider));for(let g of h){if(g.provider.length===0||g.displayName.length===0||g.settingsNs.length===0)throw new mt("configurable providers need a non-empty provider, displayName, and settingsNs","INVALID_DIRECTORY");if(g.settingsPath.some(v=>v.length===0))throw new mt(`configurable provider "${g.provider}" has an empty settingsPath segment`,"INVALID_DIRECTORY");if(this.directory.has(g.provider)&&!f.has(g.provider)||m.some(v=>v.provider===g.provider))throw new mt(`configurable provider "${g.provider}" is already declared`,"DUPLICATE_DIRECTORY");m.push(o$e(g))}for(let g of c)this.directory.delete(g.provider);for(let g of m)this.directory.set(g.provider,g);c=m,this.emitAdaptersUpdated()},"commit"),d=this.ctx.effect(function*(){if(o.length===0)throw new mt("a configurable-provider registration must declare at least one provider","INVALID_DIRECTORY");u(o),yield()=>{l=!0;for(let h of c)this.directory.delete(h.provider);c=[],this.emitAdaptersUpdated()}}.bind(this),"llm.registerConfigurableProviders()"),p=a((()=>{d()}),"handle");return p.replace=h=>{if(l)throw new mt("this configurable-provider registration was disposed","REGISTRATION_DISPOSED");u(h)},p}listConfigurableProviders(){return[...this.directory.values()].map(o$e)}registerModelDiscovery(o,c){let l=this.ctx.effect(function*(){if(o.length===0)throw new mt("model discovery needs a non-empty settings namespace","INVALID_DISCOVERY");if(this.discoveries.has(o))throw new mt(`model discovery for "${o}" is already registered`,"DUPLICATE_DISCOVERY");this.discoveries.set(o,c),yield()=>{this.discoveries.delete(o)}}.bind(this),"llm.registerModelDiscovery()");return()=>{l()}}async discoverModels(o,c,l){let u=this.discoveries.get(o);if(u===void 0)throw new mt(`no model discovery is registered for "${o}"`,"NO_DISCOVERY");if((c.provider??"").length===0&&(c.baseURL??"").length===0)throw new mt("model discovery needs a provider route or a baseURL","INVALID_DISCOVERY");let d=l===void 0?await u(c):await u(c,l),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,c,l){try{return await this.discoverModels(o,c,l)}catch(u){throw new We("llm/model-discovery-rejected",u instanceof Error?u.message:String(u),{settingsNs:o,...c.baseURL===void 0?{}:{baseURL:c.baseURL}},{cause:u})}}providerRetryPolicy(o){return this.registration(o).retryPolicy}imageRequestPricing(o,c){return this.adapters.get(o)?.adapter.imageRequestPricing(o,c)}imageRequestTarget(o,c,l){return this.registration(o).adapter.imageRequestTarget(o,c,l)}fileRequestText(o){return b$e(o,this.fileReadPath(o))}detachedModalities(o){return o===void 0?void 0:[...o]}async listModels(o){let c=await this.registration(o).adapter.listModels(o),l=new Set;return c.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"||l.has(u.id))throw new mt(`adapter returned invalid or duplicate model metadata for provider "${o}"`,"INVALID_CATALOG");l.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,c,l){return this.resolveModelInfoFor(this.registration(o),c,l)}async resolveModelInfoFor(o,c,l){let u=await o.adapter.resolveModel(o.provider.id,c,l);return this.normalizeModelInfo(o,c,u)}normalizeModelInfo(o,c,l){let u=o.provider.id;if(typeof l.provider!="string"||l.provider!==u||typeof l.id!="string"||l.id!==c||typeof l.name!="string"||l.name.length===0||l.description!==void 0&&typeof l.description!="string")throw new mt(`adapter returned invalid exact model metadata for provider "${u}" model "${c}"`,"INVALID_MODEL_INFO");let d=l.context;if(d!==void 0&&(!Number.isInteger(d.contextWindow)||d.contextWindow<=0))throw new mt(`adapter returned invalid context metadata for provider "${u}" model "${c}"`,"INVALID_MODEL_CONTEXT");let p=this.detachedModalities(l.inputModalities),h=l.systemPromptUpdate;if(h!==void 0&&h!=="in-history")throw new mt(`adapter returned invalid system prompt update mode for provider "${u}" model "${c}"`,"INVALID_MODEL_INFO");let m=l.toolUpdate;if(m!==void 0&&m!=="in-history"&&m!=="addition-only")throw new mt(`adapter returned invalid tool update mode for provider "${u}" model "${c}"`,"INVALID_MODEL_INFO");let f=l.defaultMaxTokens;if(f!==void 0&&(!Number.isSafeInteger(f)||f<=0))throw new mt(`adapter returned invalid default maxTokens for provider "${u}" model "${c}"`,"INVALID_MODEL_MAX_TOKENS");let g={provider:u,id:c,name:l.name,...l.description===void 0?{}:{description:l.description},...p===void 0?{}:{inputModalities:p},...d===void 0?{}:{context:{contextWindow:d.contextWindow}},...f===void 0?{}:{defaultMaxTokens:f},...l.systemPromptUpdate===void 0?{}:{systemPromptUpdate:l.systemPromptUpdate},...l.toolUpdate===void 0?{}:{toolUpdate:l.toolUpdate}},v=l.reasoning;if(v===void 0)return g;if(v.efforts.length===0)throw new mt(`adapter returned invalid reasoning metadata for provider "${u}" model "${c}"`,"INVALID_MODEL_REASONING");let x=new Set,b=v.efforts.map(w=>{if(typeof w.id!="string"||w.id.length===0||typeof w.name!="string"||w.name.length===0||w.description!==void 0&&typeof w.description!="string"||x.has(w.id))throw new mt(`adapter returned invalid or duplicate reasoning effort metadata for provider "${u}" model "${c}"`,"INVALID_MODEL_REASONING");return x.add(w.id),{id:w.id,name:w.name,...w.description===void 0?{}:{description:w.description}}});if(v.defaultEffort!==void 0&&!x.has(v.defaultEffort))throw new mt(`adapter returned an unknown default reasoning effort for provider "${u}" model "${c}"`,"INVALID_MODEL_REASONING");return{...g,reasoning:{efforts:b,...v.defaultEffort===void 0?{}:{defaultEffort:v.defaultEffort}}}}async resolveCallConfig(o,c){return(await this.resolveCallFor(this.registration(o.provider),o,c)).config}async resolveCallFor(o,c,l){let u=await this.resolveModelInfoFor(o,c.model,l);return this.resolveCallWithInfo(c,u)}resolveCallWithInfo(o,c){let l=o.maxTokens===void 0&&c.defaultMaxTokens!==void 0?{...o,maxTokens:c.defaultMaxTokens}:o,u=c.reasoning,d=l.reasoningEffort,p=l;if(u===void 0){if(d!==void 0)throw new mt(`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 mt(`provider "${o.provider}" model "${o.model}" does not support reasoning effort "${h}"`,"UNSUPPORTED_REASONING_EFFORT");d!==h&&(p={...l,reasoningEffort:h})}}return{config:p,...c.context===void 0?{}:{context:c.context},modelInfo:c}}async prepareCall(o,c,l){c?.throwIfAborted();let{provider:u,model:d,...p}=o,h=this.registration(u),m=await h.adapter.prepareCall(u,d,c);c?.throwIfAborted();let f=this.normalizeModelInfo(h,d,m.model),g=l===void 0?o:{...l(jn(structuredClone(p)),jn(f)),provider:u,model:d};c?.throwIfAborted();let v=this.resolveCallWithInfo(g,f),x=jn(structuredClone(v.config)),b=v.context===void 0?void 0:jn(structuredClone(v.context)),w=jn({...g.reasoningEffort===void 0&&x.reasoningEffort!==void 0?{reasoningEffort:!0}:{},...g.maxTokens===void 0&&x.maxTokens!==void 0?{maxTokens:!0}:{}}),k=!1;return Object.freeze({config:x,retryPolicy:h.retryPolicy,adapterDefaults:w,...b===void 0?{}:{context:b},...f.inputModalities===void 0?{}:{inputModalities:Object.freeze([...f.inputModalities])},...f.systemPromptUpdate===void 0?{}:{systemPromptUpdate:f.systemPromptUpdate},...f.toolUpdate===void 0?{}:{toolUpdate:f.toolUpdate},stream:a(E=>{if(k)throw new mt("a prepared LLM call can only be dispatched once","INVALID_PREPARED_CALL");if(!fP(E,x))throw new mt("prepared LLM call config changed before adapter dispatch","INVALID_PREPARED_CALL");return k=!0,this.streamWithRegistration(E,{registration:h,config:x,modelInfo:f,dispatch:a(A=>m.stream(A),"dispatch")})},"stream")})}registration(o){let c=this.adapters.get(o);if(!c)throw new mt(`no adapter registered for provider "${o}"`,"NO_ADAPTER");return c}forAdapter(o,c){let l=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===c?d:hm({...d,source:{kind:"model",provider:p.provider,model:p.model}})});if(l.every((d,p)=>d===o.messages[p]))return o;let u={...o,messages:l};return Object.isFrozen(o)?jn(u):u}fileReadPath(o){let c;try{c=this.ctx.get("attachments")?.fileHostPath(o)}catch{return}if(c!==void 0)return this.ctx.get("fs")?.processPathFromHostPath(c)}async*adapterStream(o,c){let l;try{let d=c?.registration??this.registration(o.provider),p=d.adapter,h,m,f;if(c===void 0){let w=await p.prepareCall(o.provider,o.model,o.signal);h=this.normalizeModelInfo(d,o.model,w.model),m=this.resolveCallWithInfo(o,h).config,f=a(k=>w.stream(k),"dispatch")}else h=c.modelInfo,m=c.config,f=c.dispatch;if(c!==void 0&&!fP(o,m))throw new mt("prepared LLM call config changed before adapter dispatch","INVALID_PREPARED_CALL");let g=fP(o,m)?o:Object.isFrozen(o)?jn({...o,...m}):{...o,...m},v=g.messages;v.some(w=>x$e(w.content))&&(v=HVt(v,w=>this.fileReadPath(w))),h.inputModalities!==void 0&&!h.inputModalities.includes("image")&&v.some(w=>lp(w.content))&&(v=YVt(v));let x=ZVt(v,g.tools,h.toolUpdate,g.toolHistory);v=x.messages;let b=g;(v!==g.messages||x.tools!==g.tools)&&(b={...g,messages:v,...x.tools===void 0?{}:{tools:x.tools}},Object.isFrozen(g)&&jn(b)),l=f(this.forAdapter(b,p))[Symbol.asyncIterator]()}catch(d){yield s$e(d,o.signal);return}let u=!1;try{for(;;){let d;try{let p=await l.next();d=p.done?{done:!0}:{done:!1,value:p.value}}catch(p){u=!0,yield s$e(p,o.signal);return}if(d.done){u=!0;return}yield d.value}}finally{if(!u){let d=l.return?.bind(l);d&&await d()}}}stream(o){return this.streamWithRegistration(o)}streamWithRegistration(o,c){return this.ctx.waterfall(this,"llm/stream",o,()=>this.adapterStream(o,c))}}})();a(s$e,"adapterFailureChunk");a(o$e,"detachDirectoryEntry")});function I$e(e,t){for(let n=t;n!==void 0;n=cA.get(n))if(n===e)throw new Error("dsh-scope: scope parent link would form a cycle");cA.set(e,t)}function poe(e,t){if(cA.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 I$e(e,t),{rebind(n){I$e(e,n)}}}function C$e(e){return cA.get(e)}function wP(e){let t=[];for(let n=e;n!==void 0;n=cA.get(n))t.push(n);return t}async function cKt(e){for(await Promise.resolve(e.dispose());e.inertia!==void 0;)await e.inertia}function lKt(){}function Jx(e,t,n){n?.parent!==void 0&&poe(t,n.parent);let r=e.plugin(lKt),i=r.ctx.extend({[R$e]:t}),s;return{ctx:i,rawDispose:r.dispose,dispose:a(()=>s??=cKt(r),"dispose")}}function nl(e){return e[R$e]}function rl(e,t){let n=e[Ns.filter],r={[Ns.filter](i){if(n!==void 0&&!n.call(e,i))return!1;let s=nl(i);if(s===void 0)return!0;for(let o=t;o!==void 0;o=cA.get(o))if(o===s)return!0;return!1}};return doe.set(r,t),r}function uKt(e){return typeof e=="object"&&e!==null&&doe.has(e)}function P$e(e){if(uKt(e))return doe.get(e)}var mm,C1,fm,R$e,doe,cA,Jl=q(()=>{yr();mm=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}},C1=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}},fm=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 wP(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=nl(e),i=n.notify??!0;return e.effect(function*(){let s,o=!1;if(r===void 0)s=this.global;else{let l=this.scoped.get(r);l===void 0?(s=this.createLayer(r),this.scoped.set(r,s),o=!0):s=l}let c;try{c=t(s)}catch(l){throw r!==void 0&&o&&s.isEmpty()&&this.scoped.delete(r),l}yield()=>{c(),r!==void 0&&s.isEmpty()&&this.scoped.delete(r),i&&this.onChange()},i&&this.onChange()}.bind(this),n.label)}},R$e=Symbol("dsh.scope"),doe=new WeakMap,cA=new WeakMap;a(I$e,"linkScopeParent");a(poe,"bindScopeParent");a(C$e,"scopeParentOf");a(wP,"scopeChainOf");a(cKt,"quiesceFiber");a(lKt,"scope");a(Jx,"createScope");a(nl,"scopeOf");a(rl,"scopeTarget");a(uKt,"isScopeCarrier");a(P$e,"carrierKeyOf")});import{accessSync as FUr,constants as jUr,realpathSync as qUr,statSync as WUr}from"node:fs";import{tmpdir as zUr}from"node:os";function CF(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 O$e(e){return`[sandbox: file access denied under ${e} mode]`}function M$e(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 N$e(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 PF(e,t){let{requestedMode:n,effectiveMode:r,justification:i,subject:s}=e;if(n===r)return r;if(!(dKt[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 Pr(o,"EscalationOutcome")}}var dKt,RF,hoe=q(()=>{yr();Ur();ws();dKt={"read-only":["workspace-write","danger-full-access"],"workspace-write":["danger-full-access"]},RF=["workspace-write","danger-full-access"];a(CF,"validateEscalationArgs");a(O$e,"sandboxDenialMarker");a(M$e,"escalationHintMarker");a(N$e,"sandboxPermissionsDescription");a(PF,"approveEscalation")});function Z$e(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 eUe(e){return Object.getPrototypeOf(e)===null&&Z$e(e,"Object")}function tUe(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;try{let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&eUe(t)}catch{return!1}}function mKt(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Z$e(t,"Array"))return!1;let n=Object.getPrototypeOf(t);return typeof n=="object"&&n!==null&&eUe(n)}function fKt(e){try{return Reflect.ownKeys(e).every(t=>typeof t=="string"&&Object.prototype.propertyIsEnumerable.call(e,t))}catch{return!1}}function US(e){return tUe(e)&&fKt(e)}function TP(e){if(!Array.isArray(e))return!1;try{if(!mKt(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 LF(e){return typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0)}function L$e(e,t){switch(e){case"string":return typeof t=="string";case"number":return LF(t);case"integer":return LF(t)&&Number.isInteger(t);case"boolean":return typeof t=="boolean";case"null":return t===null;default:return Pr(e,"JsonSchemaType")}}function gKt(e,t,n,r){let i=Object.hasOwn(e,"required"),s=i?e.required:void 0;if(i)if(!TP(s)||s.some(o=>typeof o!="string"))r.push(`${t}.required must be an array of strings`);else{let o=US(n)?n:{};for(let c of s)Object.hasOwn(o,c)||r.push(`${t}.required names "${c}" which is not in properties`)}Object.hasOwn(e,"additionalProperties")&&typeof e.additionalProperties!="boolean"&&r.push(`${t}.additionalProperties must be a boolean`)}function nUe(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 D$e)Object.hasOwn(s.node,h)&&n.push(`${s.path}.${h} is not supported beside oneOf`);continue}if(s.kind==="object-tail"){gKt(s.node,s.path,s.properties,n);continue}let{node:o,path:c}=s;if(!US(o)){n.push(`${c} must be a schema object`);continue}if(r.has(o)){n.push(`${c} is circular`);continue}r.add(o),i.push({kind:"leave",node:o});for(let h of Object.keys(o))if(!pKt.has(h)){if(hKt.has(h)){try{R1(o[h])||n.push(`${c}.${h} annotation must be lossless JSON data`)}catch{n.push(`${c}.${h} annotation must be lossless JSON data`)}continue}n.push(`${c}.${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(`${c}.description must be a string`),Object.hasOwn(o,"title")&&typeof o.title!="string"&&n.push(`${c}.title must be a string`);let l=Object.hasOwn(o,"type"),u=Object.hasOwn(o,"oneOf");if(l&&u){n.push(`${c} cannot declare both type and oneOf`);continue}if(!l&&!u){for(let h of D$e)Object.hasOwn(o,h)&&n.push(`${c}.${h} requires type or oneOf`);continue}if(u){let h=o.oneOf;if(i.push({kind:"one-of-tail",node:o,path:c}),!TP(h)||h.length<2)n.push(`${c}.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:`${c}.oneOf[${m}]`});continue}let d=o.type;if(typeof d!="string"||!boe.includes(d)){n.push(Array.isArray(d)?`${c}.type must be a single type string (type arrays are not supported)`:`${c}.type must be one of ${boe.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(`${c}.${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:c,properties:h}),Object.hasOwn(o,"properties"))if(!US(h))n.push(`${c}.properties must be an object of schemas`);else{let m=Object.entries(h);for(let f=m.length-1;f>=0;f--){let g=m[f];g!==void 0&&i.push({kind:"enter",node:g[1],path:`${c}.properties.${g[0]}`})}}break}case"array":Object.hasOwn(o,"items")&&i.push({kind:"enter",node:o.items,path:`${c}.items`});break;case"string":case"number":case"integer":case"boolean":case"null":{let h=Object.hasOwn(o,"enum"),m=h?o.enum:void 0,f=TP(m)&&m.length>0&&m.every(b=>L$e(p,b));h&&!f&&n.push(`${c}.enum must be a non-empty array of ${p} values`);let g=Object.hasOwn(o,"const"),v=g?o.const:void 0,x=L$e(p,v);g&&(x?f&&!m.includes(v)&&n.push(`${c}.const must be one of ${c}.enum when both are declared`):n.push(`${c}.const must be a ${p} value`));break}default:Pr(p,"JsonSchemaType")}}}function jS(e){let t=[];if(nUe(e,"schema",t,new Set),t.length>0)throw new RP(t)}function $F(e){let t=[];if(nUe(e,"schema",t,new Set),t.length===0&&(!US(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 RP(t)}function moe(e){try{return R1(e)}catch{return!1}}function up(e){return e===""?"arguments":e}function foe(e,t){return e===""?t:`${e}.${t}`}function goe(e){return[`"${up(e)}" must be a lossless JSON value`]}function $$e(e,t){for(let n of t)e.push(n)}function U$e(e,t,n){return{node:e,value:t,path:n,catches:!1,phase:"start",children:[],childIndex:0,violations:[],tailViolations:[],matches:0}}function kP(e,t,n){let r=Object.hasOwn(e,"enum")?e.enum:void 0;return r!==void 0&&!r.includes(t)?[`"${up(n)}" must be one of ${JSON.stringify(r)}`]:Object.hasOwn(e,"const")&&t!==e.const?[`"${up(n)}" must be ${JSON.stringify(e.const)}`]:[]}function yKt(e,t,n){let r=[U$e(e,t,n)],i,s=a(c=>{let l=r.at(-1);if(l===void 0){i=c;return}l.kind==="oneOf"?c.length===0&&l.matches++:$$e(l.violations,c)},"receive"),o=a(c=>{r.pop(),s(c)},"finish");for(;r.length>0;){let c=r.at(-1);if(c===void 0)break;try{if(c.phase==="children"){if(c.childIndex<c.children.length){let d=c.children[c.childIndex];if(d===void 0)throw new Error("missing schema-value child frame");c.childIndex++,r.push(U$e(d.node,d.value,d.path));continue}if(c.kind==="oneOf"){o(c.matches===1?[]:[`"${up(c.path)}" must match exactly one oneOf branch (matched ${c.matches})`]);continue}$$e(c.violations,c.tailViolations),c.violations.length>0?o(c.violations):c.kind==="object"?o(moe(c.value)?[]:[`"${up(c.path)}" must be a lossless JSON object`]):o(moe(c.value)?[]:[`"${up(c.path)}" must be a dense lossless JSON array`]);continue}let l=Object.hasOwn(c.node,"type")?c.node.type:void 0;c.catches=!(l!==void 0&&!boe.includes(l));let u=Object.hasOwn(c.node,"oneOf")?c.node.oneOf:void 0;if(u!==void 0){c.kind="oneOf",c.children=Array.from(u,d=>({node:d,value:c.value,path:c.path})),c.childIndex=0,c.matches=0,c.phase="children";continue}if(l===void 0){o(moe(c.value)?[]:goe(c.path));continue}switch(l){case"object":{if(!tUe(c.value)){o([`"${up(c.path)}" must be an object`]);break}let d=Object.hasOwn(c.node,"properties")?c.node.properties??{}:{},p=[],h=Object.hasOwn(c.node,"required")?c.node.required??[]:[];for(let g of h)(!Object.hasOwn(c.value,g)||c.value[g]===void 0)&&p.push(`missing required property "${foe(c.path,g)}"`);let m=[];for(let[g,v]of Object.entries(d))!Object.hasOwn(c.value,g)||c.value[g]===void 0||m.push({node:v,value:c.value[g],path:foe(c.path,g)});let f=[];if(Object.hasOwn(c.node,"additionalProperties")&&c.node.additionalProperties===!1)for(let g of Object.keys(c.value))Object.hasOwn(d,g)||f.push(`"${foe(c.path,g)}" is not a declared property (additionalProperties: false)`);c.kind="object",c.children=m,c.childIndex=0,c.violations=p,c.tailViolations=f,c.phase="children";break}case"array":{if(!Array.isArray(c.value)){o([`"${up(c.path)}" must be an array`]);break}let d=Object.hasOwn(c.node,"items")?c.node.items:void 0,p=d===void 0?[]:c.value.flatMap((h,m)=>[{node:d,value:h,path:`${c.path}[${m}]`}]);c.kind="array",c.children=p,c.childIndex=0,c.violations=[],c.phase="children";break}case"string":o(typeof c.value=="string"?kP(c.node,c.value,c.path):[`"${up(c.path)}" must be a string`]);break;case"number":o(typeof c.value!="number"?[`"${up(c.path)}" must be a number`]:LF(c.value)?kP(c.node,c.value,c.path):[`"${up(c.path)}" must be a finite JSON number`]);break;case"integer":o(!LF(c.value)||!Number.isInteger(c.value)?[`"${up(c.path)}" must be an integer`]:kP(c.node,c.value,c.path));break;case"boolean":o(typeof c.value=="boolean"?kP(c.node,c.value,c.path):[`"${up(c.path)}" must be a boolean`]);break;case"null":o(c.value===null?kP(c.node,c.value,c.path):[`"${up(c.path)}" must be null`]);break;default:o(Pr(l,"JsonSchemaType"))}}catch(l){let u=r.pop();for(;u!==void 0&&!u.catches;)u=r.pop();if(u===void 0)throw l;s(goe(u.path))}}return i??goe(n)}function UF(e,t,n="value"){return yKt(e,t,n)}function dp(e){throw new RP([e])}function SP(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 _P(e,t,n){for(let r of Object.keys(e))n.includes(r)||dp(`${t}.${r} is not supported by the value schema DSL`)}function xKt(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 bKt(e,t){e.kind==="root"?e.holder.value=t:e.target.properties=t.properties}function rUe(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"){US(r.property)||dp(`${r.path} must be a value schema object`),Object.hasOwn(r.property,"required")&&r.property.required!==!0&&dp(`${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"){US(r.input)||dp(`${r.path} must be an object of value schemas`),t.has(r.input)&&dp(`${r.path} is circular`),t.add(r.input);let u={properties:{}},d=[];bKt(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;US(i)||dp(`${s} must be a value schema object`),t.has(i)&&dp(`${s} is circular`),t.add(i);let o=[...vKt,...r.allowRequired?["required"]:[]],c={};if(xKt(r.destination,c),n.push({kind:"leave",input:i}),Object.hasOwn(i,"oneOf")){_P(i,s,[...o,"oneOf","type"]),Object.hasOwn(i,"type")&&dp(`${s} cannot declare both type and oneOf`),TP(i.oneOf)||dp(`${s}.oneOf must be an array of at least two value schemas`);let u=[];c.oneOf=u,SP(i,c);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 l=Object.hasOwn(i,"type")?i.type:void 0;switch(l){case"json":_P(i,s,[...o,"type"]),SP(i,c);break;case"object":_P(i,s,[...o,"type","properties","additionalProperties"]),(!Object.hasOwn(i,"additionalProperties")||typeof i.additionalProperties!="boolean")&&dp(`${s}.additionalProperties must be explicitly true or false`),c.type="object",SP(i,c),c.additionalProperties=i.additionalProperties,Object.hasOwn(i,"properties")&&n.push({kind:"property-map",input:i.properties,path:`${s}.properties`,destination:{kind:"object",target:c}});break;case"array":_P(i,s,[...o,"type","items"]),c.type="array",SP(i,c),Object.hasOwn(i,"items")&&n.push({kind:"value",input:i.items,path:`${s}.items`,allowRequired:!1,destination:{kind:"item",target:c}});break;case"string":case"number":case"integer":case"boolean":case"null":_P(i,s,[...o,"type","enum","const"]),c.type=l,SP(i,c),Object.hasOwn(i,"enum")&&(TP(i.enum)||dp(`${s}.enum must be a non-empty array of scalar values`),c.enum=Array.from(i.enum,u=>u)),Object.hasOwn(i,"const")&&(c.const=i.const);break;default:dp(`${s}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`)}}}function wKt(e,t){let n={};return rUe({kind:"property-map",input:e,path:t,destination:{kind:"root",holder:n}}),n.value??dp(`${t} did not compile`)}function kKt(e,t){let n={};return rUe({kind:"value",input:e,path:t,allowRequired:!1,destination:{kind:"root",holder:n}}),n.value??dp(`${t} did not compile`)}function SKt(e){let t=kKt(e,"schema");return jS(t),t}function iUe(e){let t=wKt(e,"parameters"),n={type:"object",properties:t.properties,...t.required===void 0?{}:{required:t.required}};return jS(n),n}function Wn(e){let t=e.execute,n=e.finalizeContent,r=e.projectContent,i=e.output.render,s=e.output.presentationMeta,o=e.presentCall,c=e.presentResult,l=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=iUe(e.parameters),d=SKt(e.output.schema),p=a(m=>UF(u,m,""),"validate"),h={name:e.name,description:e.description,parameters:u,output:{schema:d,render(m,f){return i(m,f)},...s!==void 0?{presentationMeta(m,f){return s(m,f)}}:{}},...e.deferLoading===!0?{deferLoading:e.deferLoading}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},async execute(m,f){let g=p(m);if(g.length>0)throw new Eoe(g);return t(m,f)}};return r&&(h.projectContent=(m,f)=>r(m,f)),n&&(h.finalizeContent=(m,f)=>n(m,f)),o&&(h.presentCall=m=>{if(!(p(m).length>0))return o(m)}),c&&(h.presentResult=(m,f)=>{if(!(p(m).length>0))return c(m,f)}),l&&(h.isConcurrencySafe=m=>p(m).length>0?!1:l(m)),h}function Toe(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 TKt(e){return e===void 0?EP:{...e.timeout===void 0?{}:{timeoutMs:{...EP.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:EP.sandbox_permissions,justification:EP.justification}}}function voe(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 j$e(e){let t=e();if(t===void 0)return DF;let n=yoe[t.language];if(!Object.hasOwn(yoe,t.language)||n===void 0){let r=Object.keys(yoe).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"?EKt:n}function IKt(e){let t;try{t=Qs(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=Qs(t);if(n===void 0)throw new Error("tool arguments could not be detached for durable logging");return{dispatched:t,logged:n}}function CKt(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>RKt,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
|
${OF.repeat(r.depth)}]`});for(let l=i.length-1;l>=0;l--){let u=i[l];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?l===0?"":",":`${l===0?`
|
|
16
16
|
`:`,
|
|
17
17
|
`}${OF.repeat(o)}`})}continue}let c=Object.keys(i);if(t.push("{"),c.length===0){t.push("}");continue}n.push({kind:"text",text:s?"}":`
|
|
@@ -164,7 +164,7 @@ Known schemas:
|
|
|
164
164
|
- `)}`,new Error(at)}let Nt=`${c}/$ref`,xt=ba(e,Ke,n,r,i,s,o,Nt,l);if(xt.valid||Me.push({instanceLocation:o,keyword:"$ref",keywordLocation:Nt,error:"A subschema had errors."},...xt.errors),n==="4"||n==="7")return{valid:Me.length===0,errors:Me}}if(Array.isArray(f)){let tt=f.length,Ke=!1;for(let Nt=0;Nt<tt;Nt++)if(d===f[Nt]||f[Nt]==="integer"&&d==="number"&&e%1===0&&e===e){Ke=!0;break}Ke||Me.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${f.join('", "')}".`})}else f==="integer"?(d!=="number"||e%1||e!==e)&&Me.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${f}".`}):f!==void 0&&d!==f&&Me.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${f}".`});if(g!==void 0&&(d==="object"||d==="array"?YI(e,g)||Me.push({instanceLocation:o,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):e!==g&&Me.push({instanceLocation:o,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(g)}.`})),v!==void 0&&(d==="object"||d==="array"?v.some(tt=>YI(e,tt))||Me.push({instanceLocation:o,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(tt=>e===tt)||Me.push({instanceLocation:o,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),b!==void 0){let tt=`${c}/not`;ba(e,b,n,r,i,s,o,tt).valid&&Me.push({instanceLocation:o,keyword:"not",keywordLocation:tt,error:'Instance matched "not" schema.'})}let _t=[];if(w!==void 0){let tt=`${c}/anyOf`,Ke=Me.length,Nt=!1;for(let xt=0;xt<w.length;xt++){let at=w[xt],Ot=Object.create(l),qe=ba(e,at,n,r,i,m===!0?s:null,o,`${tt}/${xt}`,Ot);Me.push(...qe.errors),Nt=Nt||qe.valid,qe.valid&&_t.push(Ot)}Nt?Me.length=Ke:Me.splice(Ke,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:tt,error:"Instance does not match any subschemas."})}if(k!==void 0){let tt=`${c}/allOf`,Ke=Me.length,Nt=!0;for(let xt=0;xt<k.length;xt++){let at=k[xt],Ot=Object.create(l),qe=ba(e,at,n,r,i,m===!0?s:null,o,`${tt}/${xt}`,Ot);Me.push(...qe.errors),Nt=Nt&&qe.valid,qe.valid&&_t.push(Ot)}Nt?Me.length=Ke:Me.splice(Ke,0,{instanceLocation:o,keyword:"allOf",keywordLocation:tt,error:"Instance does not match every subschema."})}if(E!==void 0){let tt=`${c}/oneOf`,Ke=Me.length,Nt=E.filter((xt,at)=>{let Ot=Object.create(l),qe=ba(e,xt,n,r,i,m===!0?s:null,o,`${tt}/${at}`,Ot);return Me.push(...qe.errors),qe.valid&&_t.push(Ot),qe.valid}).length;Nt===1?Me.length=Ke:Me.splice(Ke,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:tt,error:`Instance does not match exactly one subschema (${Nt} matches).`})}if((d==="object"||d==="array")&&Object.assign(l,..._t),A!==void 0){let tt=`${c}/if`;if(ba(e,A,n,r,i,s,o,tt,l).valid){if(I!==void 0){let Nt=ba(e,I,n,r,i,s,o,`${c}/then`,l);Nt.valid||Me.push({instanceLocation:o,keyword:"if",keywordLocation:tt,error:'Instance does not match "then" schema.'},...Nt.errors)}}else if(M!==void 0){let Nt=ba(e,M,n,r,i,s,o,`${c}/else`,l);Nt.valid||Me.push({instanceLocation:o,keyword:"if",keywordLocation:tt,error:'Instance does not match "else" schema.'},...Nt.errors)}}if(d==="object"){if(x!==void 0)for(let xt of x)xt in e||Me.push({instanceLocation:o,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${xt}".`});let tt=Object.keys(e);if(R!==void 0&&tt.length<R&&Me.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${R} properties.`}),B!==void 0&&tt.length>B&&Me.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${B} properties.`}),C!==void 0){let xt=`${c}/propertyNames`;for(let at in e){let Ot=`${o}/${Eh(at)}`,qe=ba(at,C,n,r,i,s,Ot,xt);qe.valid||Me.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:xt,error:`Property name "${at}" does not match schema.`},...qe.errors)}}if(N!==void 0){let xt=`${c}/dependantRequired`;for(let at in N)if(at in e){let Ot=N[at];for(let qe of Ot)qe in e||Me.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:xt,error:`Instance has "${at}" but does not have "${qe}".`})}}if(U!==void 0)for(let xt in U){let at=`${c}/dependentSchemas`;if(xt in e){let Ot=ba(e,U[xt],n,r,i,s,o,`${at}/${Eh(xt)}`,l);Ot.valid||Me.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:at,error:`Instance has "${xt}" but does not match dependant schema.`},...Ot.errors)}}if(L!==void 0){let xt=`${c}/dependencies`;for(let at in L)if(at in e){let Ot=L[at];if(Array.isArray(Ot))for(let qe of Ot)qe in e||Me.push({instanceLocation:o,keyword:"dependencies",keywordLocation:xt,error:`Instance has "${at}" but does not have "${qe}".`});else{let qe=ba(e,Ot,n,r,i,s,o,`${xt}/${Eh(at)}`);qe.valid||Me.push({instanceLocation:o,keyword:"dependencies",keywordLocation:xt,error:`Instance has "${at}" but does not match dependant schema.`},...qe.errors)}}}let Ke=Object.create(null),Nt=!1;if($!==void 0){let xt=`${c}/properties`;for(let at in $){if(!(at in e))continue;let Ot=`${o}/${Eh(at)}`,qe=ba(e[at],$[at],n,r,i,s,Ot,`${xt}/${Eh(at)}`);if(qe.valid)l[at]=Ke[at]=!0;else if(Nt=i,Me.push({instanceLocation:o,keyword:"properties",keywordLocation:xt,error:`Property "${at}" does not match schema.`},...qe.errors),Nt)break}}if(!Nt&&D!==void 0){let xt=`${c}/patternProperties`;for(let at in D){let Ot=new RegExp(at,"u"),qe=D[at];for(let Bt in e){if(!Ot.test(Bt))continue;let yn=`${o}/${Eh(Bt)}`,It=ba(e[Bt],qe,n,r,i,s,yn,`${xt}/${Eh(at)}`);It.valid?l[Bt]=Ke[Bt]=!0:(Nt=i,Me.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:xt,error:`Property "${Bt}" matches pattern "${at}" but does not match associated schema.`},...It.errors))}}}if(!Nt&&W!==void 0){let xt=`${c}/additionalProperties`;for(let at in e){if(Ke[at])continue;let Ot=`${o}/${Eh(at)}`,qe=ba(e[at],W,n,r,i,s,Ot,xt);qe.valid?l[at]=!0:(Nt=i,Me.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:xt,error:`Property "${at}" does not match additional properties schema.`},...qe.errors))}}else if(!Nt&&ee!==void 0){let xt=`${c}/unevaluatedProperties`;for(let at in e)if(!l[at]){let Ot=`${o}/${Eh(at)}`,qe=ba(e[at],ee,n,r,i,s,Ot,xt);qe.valid?l[at]=!0:Me.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:xt,error:`Property "${at}" does not match unevaluated properties schema.`},...qe.errors)}}}else if(d==="array"){de!==void 0&&e.length>de&&Me.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${de}).`}),fe!==void 0&&e.length<fe&&Me.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${fe}).`});let tt=e.length,Ke=0,Nt=!1;if(F!==void 0){let xt=`${c}/prefixItems`,at=Math.min(F.length,tt);for(;Ke<at;Ke++){let Ot=ba(e[Ke],F[Ke],n,r,i,s,`${o}/${Ke}`,`${xt}/${Ke}`);if(l[Ke]=!0,!Ot.valid&&(Nt=i,Me.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:xt,error:"Items did not match schema."},...Ot.errors),Nt))break}}if(K!==void 0){let xt=`${c}/items`;if(Array.isArray(K)){let at=Math.min(K.length,tt);for(;Ke<at;Ke++){let Ot=ba(e[Ke],K[Ke],n,r,i,s,`${o}/${Ke}`,`${xt}/${Ke}`);if(l[Ke]=!0,!Ot.valid&&(Nt=i,Me.push({instanceLocation:o,keyword:"items",keywordLocation:xt,error:"Items did not match schema."},...Ot.errors),Nt))break}}else for(;Ke<tt;Ke++){let at=ba(e[Ke],K,n,r,i,s,`${o}/${Ke}`,xt);if(l[Ke]=!0,!at.valid&&(Nt=i,Me.push({instanceLocation:o,keyword:"items",keywordLocation:xt,error:"Items did not match schema."},...at.errors),Nt))break}if(!Nt&&Z!==void 0){let at=`${c}/additionalItems`;for(;Ke<tt;Ke++){let Ot=ba(e[Ke],Z,n,r,i,s,`${o}/${Ke}`,at);l[Ke]=!0,Ot.valid||(Nt=i,Me.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:at,error:"Items did not match additional items schema."},...Ot.errors))}}}if(V!==void 0)if(tt===0&&se===void 0)Me.push({instanceLocation:o,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(se!==void 0&&tt<se)Me.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${tt}) than minContains (${se}).`});else{let xt=`${c}/contains`,at=Me.length,Ot=0;for(let qe=0;qe<tt;qe++){let Bt=ba(e[qe],V,n,r,i,s,`${o}/${qe}`,xt);Bt.valid?(l[qe]=!0,Ot++):Me.push(...Bt.errors)}Ot>=(se||0)&&(Me.length=at),se===void 0&&xe===void 0&&Ot===0?Me.splice(at,0,{instanceLocation:o,keyword:"contains",keywordLocation:xt,error:"Array does not contain item matching schema."}):se!==void 0&&Ot<se?Me.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${se} items matching schema. Only ${Ot} items were found.`}):xe!==void 0&&Ot>xe&&Me.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${xe} items matching schema. ${Ot} items were found.`})}if(!Nt&&ne!==void 0){let xt=`${c}/unevaluatedItems`;for(Ke;Ke<tt;Ke++){if(l[Ke])continue;let at=ba(e[Ke],ne,n,r,i,s,`${o}/${Ke}`,xt);l[Ke]=!0,at.valid||Me.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:xt,error:"Items did not match unevaluated items schema."},...at.errors)}}if(Ae)for(let xt=0;xt<tt;xt++){let at=e[xt],Ot=typeof at=="object"&&at!==null;for(let qe=0;qe<tt;qe++){if(xt===qe)continue;let Bt=e[qe];(at===Bt||Ot&&(typeof Bt=="object"&&Bt!==null)&&YI(at,Bt))&&(Me.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${xt} and ${qe}.`}),xt=Number.MAX_SAFE_INTEGER,qe=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(n==="4"?(Re!==void 0&&(he===!0&&e<=Re||e<Re)&&Me.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${he?"or equal to ":""} ${Re}.`}),ge!==void 0&&(et===!0&&e>=ge||e>ge)&&Me.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${et?"or equal to ":""} ${ge}.`})):(Re!==void 0&&e<Re&&Me.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Re}.`}),ge!==void 0&&e>ge&&Me.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${ge}.`}),he!==void 0&&e<=he&&Me.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${he}.`}),et!==void 0&&e>=et&&Me.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${et}.`})),Xe!==void 0){let tt=e%Xe;Math.abs(0-tt)>=11920929e-14&&Math.abs(Xe-tt)>=11920929e-14&&Me.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Xe}.`})}}else if(d==="string"){let tt=yt===void 0&&Fe===void 0?0:HYe(e);yt!==void 0&&tt<yt&&Me.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${tt} < ${yt}).`}),Fe!==void 0&&tt>Fe&&Me.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${tt} > ${Fe}).`}),Oe!==void 0&&!new RegExp(Oe,"u").test(e)&&Me.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),O!==void 0&&Gye[O]&&!Gye[O](e)&&Me.push({instanceLocation:o,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${O}".`})}return{valid:Me.length===0,errors:Me}}var Qye=q(()=>{Hye();ZB();Vye();XB();Kye();a(ba,"validate")});var ez,GYe=q(()=>{ZB();Qye();ez=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=cv(t)}validate(t){return ba(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),cv(t,this.lookup)}}});var VYe=q(()=>{Hye();ZB();Vye();XB();zYe();Kye();Qye();GYe()});var tz,KYe=q(()=>{VYe();tz=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new ez(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 ia,nz=q(()=>{"use strict";ia={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 vfn}from"node:crypto";function bfn(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function Jye(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":xfn.some(i=>bfn(i).test(e))?"allow":"ask"}function Cm(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,ia.maxErrorMessageChars)}function QYe(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=ia.maxPublicNameLength)return r;let i=wfn(e,t),s=ia.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function wfn(e,t){return vfn("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function JYe(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return jS(t),t}catch{return}}function _fn(e){return kfn.has(e)}function YYe(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!_fn(e.mimeType)||!Sfn.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function XYe(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function GO(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(``);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 xfn,kfn,Sfn,rz=q(()=>{"use strict";ho();nz();xfn=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(bfn,"globToRegExp");a(Jye,"evaluateMcpToolPolicy");a(Cm,"scrubMcpErrorMessage");a(QYe,"publicToolName");a(wfn,"hashSuffix");a(JYe,"supportedOutputSchema");kfn=new Set(["image/png","image/jpeg"]),Sfn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(_fn,"isImageMediaType");a(YYe,"decodeImageBlock");a(XYe,"containsImage");a(GO,"mapMcpResultToContentBlocks")});var Yye,ZYe=q(()=>{Yye={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 B2,eXe,tXe,VO=q(()=>{"use strict";ZYe();B2=Yye.version,eXe=Yye.dshEdge.upstreamVersion,tXe=`npx dsh-edge@${B2.includes("-")?"next":"latest"} upgrade`});function Rfn(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 Cfn(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function lv(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 Tfn)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Cfn(i)){let s=Rfn(i),o=s??i;for(let c of Afn)if(c.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let c of Ifn)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Pfn(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}function Mfn(e){return async(t,n)=>{let r=await zb(t,n);if(r.body===null)return r;let i=0,s=r.body.pipeThrough(new TransformStream({transform(o,c){if(i+=o.byteLength,i>e){c.error(new Error(`MCP server response is larger than ${String(e)} bytes.`));return}c.enqueue(o)}}));return new Response(s,{status:r.status,statusText:r.statusText,headers:r.headers})}}async function Xye(e,t,n,r){lv(e);let i=new YB(new URL(e),{requestInit:{headers:Pfn(t),signal:n},fetch:r===void 0?zb:Mfn(r)}),s=new QB({name:"dsh-edge",version:B2},{capabilities:{},jsonSchemaValidator:Ofn});return await s.connect(i),{client:s,close:a(async()=>{await s.close().catch(()=>{})},"close")}}async function nXe(e,t,n){let r=AbortSignal.timeout(ia.probeTimeoutMs),i;try{i=await Xye(t,n,r)}catch(c){throw new Error(Cm(c instanceof Error?c.message:String(c)))}let{client:s,close:o}=i;try{let c=[],l=new Set,u=new Set,d,p=s.getServerCapabilities?.()?.tools!==void 0;for(let g=0;p&&g<ia.maxCatalogPages;g++){let v=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let x of v.tools){if(c.length>=ia.maxToolsPerServer)break;let b=QYe(e,x.name);if(l.has(b))throw new Error(`Server listed tool "${x.name}" more than once`);l.add(b);let w=x.annotations?.readOnlyHint,k=JYe(x.outputSchema);c.push({name:x.name,publicName:b,description:x.description??"",inputSchema:x.inputSchema??{type:"object"},...k!==void 0?{outputSchema:k}:{},...w!==void 0?{annotations:{readOnlyHint:w}}:{}})}if(c.length>=ia.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?.(),f=s.getServerCapabilities?.()?.resources!==void 0;return{tools:c,serverInfo:h?{name:h.name,version:h.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,ia.maxInstructionsLength):void 0,resources:f}}finally{await o()}}async function iz(e,t,n,r,i,s){let o=s??ia.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await Xye(e,r,c)}catch(u){throw new Error(Cm(u instanceof Error?u.message:String(u)))}try{let u=await l.client.callTool({name:t,arguments:n},void 0,{signal:c});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(Cm(u instanceof Error?u.message:String(u)))}finally{await l.close()}}async function rXe(e,t,n,r,i){let s=i??ia.callTimeoutMs,o=r?AbortSignal.any([r,AbortSignal.timeout(s)]):AbortSignal.timeout(s),c;try{c=await Xye(e,n,o,ia.maxResourceResponseBytes)}catch(l){throw new Error(Cm(l instanceof Error?l.message:String(l)))}try{let{client:l}=c;if(t.method==="resources/read")return await l.readResource({uri:t.uri},{signal:o});let u=t.method==="resources/list"?"resources":"resourceTemplates",d=a(g=>t.method==="resources/list"?l.listResources(g===void 0?void 0:{cursor:g},{signal:o}):l.listResourceTemplates(g===void 0?void 0:{cursor:g},{signal:o}),"page");if(t.cursor!==void 0)return await d(t.cursor);let p=[],h=new Set,m=0,f;for(let g=0;g<ia.maxCatalogPages;g++){let v=await d(f),x=Array.isArray(v[u])?v[u]:[],b=new TextEncoder().encode(JSON.stringify(x)).byteLength;if(p.length>0&&m+b>ia.maxResourceResponseBytes)break;p.push(...x),m+=b;let w=typeof v.nextCursor=="string"?v.nextCursor:void 0;if(w===void 0){f=void 0;break}if(h.has(w))throw new Error(`Server repeated a ${t.method} continuation cursor`);h.add(w),f=w}return f===void 0?{[u]:p}:{[u]:p,nextCursor:f}}catch(l){throw new Error(Cm(l instanceof Error?l.message:String(l)))}finally{await c.close()}}var Tfn,Afn,Ifn,Ofn,zb,KO=q(()=>{"use strict";aYe();jYe();KYe();rz();nz();VO();Tfn=[".internal",".local",".localhost"],Afn=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Ifn=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Rfn,"extractMappedIPv4");a(Cfn,"isIpAddress");a(lv,"assertSafeUrl");a(Pfn,"buildHeaders");Ofn=new tz,zb=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(Mfn,"byteCappedFetch");a(Xye,"connectClient");a(nXe,"probe");a(iz,"callTool");a(rXe,"requestResources")});var oz={};Lt(oz,{buildAuthorizationUrl:()=>Wfn,discoverEndpoints:()=>jfn,exchangeCode:()=>Bfn,isTokenExpired:()=>Hfn,refreshToken:()=>zfn,registerClient:()=>qfn});function aXe(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 Ffn(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 jfn(e){let t=AbortSignal.timeout(sz),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);lv(i.href);let s=await zb(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let c=(await s.json()).authorization_servers?.[0];if(typeof c!="string")throw new Error("No authorization server in PRM");let l=new URL(c),u=l.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${l.pathname}`,d=new URL(u,l.origin);lv(d.href);let p=await zb(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 qfn(e,t,n){let r=AbortSignal.timeout(sz);lv(e);let i=await zb(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 Wfn(e,t,n,r,i){let s=aXe(32),o=aXe(64),c=await Ffn(o),l=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:c,code_challenge_method:"S256",resource:i}))l.searchParams.set(u,d);return{authorizationUrl:l.href,pendingFlow:{state:s,codeVerifier:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function Bfn(e,t,n,r,i,s){let o=AbortSignal.timeout(sz),c=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&c.set("resource",s),t.clientSecret!==void 0&&c.set("client_secret",t.clientSecret),lv(e);let l=await zb(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c.toString(),signal:o});if(!l.ok)throw new Error(`Token exchange failed: HTTP ${l.status}`);return cXe(await l.json())}async function zfn(e,t,n,r){let i=AbortSignal.timeout(sz),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),lv(e);let o=await zb(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 cXe(await o.json())}function cXe(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 Hfn(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var sz,az=q(()=>{"use strict";KO();sz=1e4;a(aXe,"randomString");a(Ffn,"sha256Base64Url");a(jfn,"discoverEndpoints");a(qfn,"registerClient");a(Wfn,"buildAuthorizationUrl");a(Bfn,"exchangeCode");a(zfn,"refreshToken");a(cXe,"parseTokenResponse");a(Hfn,"isTokenExpired")});var hr,gXe,XI=q(()=>{yr();Ur();hr=class extends oi{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},gXe=class extends Dt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new hr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function eM(e){return bz.test(e)}function wz(e){return e.invocation.modelInvocable}function kz(e){return e.invocation.userInvocable}function b1e(e){let t=B0n(e);return[`<skill_content name="${z0n(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 xfn,kfn,Sfn,rz=q(()=>{"use strict";ho();nz();xfn=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(bfn,"globToRegExp");a(Jye,"evaluateMcpToolPolicy");a(Cm,"scrubMcpErrorMessage");a(QYe,"publicToolName");a(wfn,"hashSuffix");a(JYe,"supportedOutputSchema");kfn=new Set(["image/png","image/jpeg"]),Sfn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(_fn,"isImageMediaType");a(YYe,"decodeImageBlock");a(XYe,"containsImage");a(GO,"mapMcpResultToContentBlocks")});var Yye,ZYe=q(()=>{Yye={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 B2,eXe,tXe,VO=q(()=>{"use strict";ZYe();B2=Yye.version,eXe=Yye.dshEdge.upstreamVersion,tXe=`npx dsh-edge@${B2.includes("-")?"next":"latest"} upgrade`});function Rfn(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 Cfn(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function lv(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 Tfn)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Cfn(i)){let s=Rfn(i),o=s??i;for(let c of Afn)if(c.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let c of Ifn)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Pfn(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}function Mfn(e){return async(t,n)=>{let r=await zb(t,n);if(r.body===null)return r;let i=0,s=r.body.pipeThrough(new TransformStream({transform(o,c){if(i+=o.byteLength,i>e){c.error(new Error(`MCP server response is larger than ${String(e)} bytes.`));return}c.enqueue(o)}}));return new Response(s,{status:r.status,statusText:r.statusText,headers:r.headers})}}async function Xye(e,t,n,r){lv(e);let i=new YB(new URL(e),{requestInit:{headers:Pfn(t),signal:n},fetch:r===void 0?zb:Mfn(r)}),s=new QB({name:"dsh-edge",version:B2},{capabilities:{},jsonSchemaValidator:Ofn});return await s.connect(i),{client:s,close:a(async()=>{await s.close().catch(()=>{})},"close")}}async function nXe(e,t,n){let r=AbortSignal.timeout(ia.probeTimeoutMs),i;try{i=await Xye(t,n,r)}catch(c){throw new Error(Cm(c instanceof Error?c.message:String(c)))}let{client:s,close:o}=i;try{let c=[],l=new Set,u=new Set,d,p=s.getServerCapabilities?.()?.tools!==void 0;for(let g=0;p&&g<ia.maxCatalogPages;g++){let v=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let x of v.tools){if(c.length>=ia.maxToolsPerServer)break;let b=QYe(e,x.name);if(l.has(b))throw new Error(`Server listed tool "${x.name}" more than once`);l.add(b);let w=x.annotations?.readOnlyHint,k=JYe(x.outputSchema);c.push({name:x.name,publicName:b,description:x.description??"",inputSchema:x.inputSchema??{type:"object"},...k!==void 0?{outputSchema:k}:{},...w!==void 0?{annotations:{readOnlyHint:w}}:{}})}if(c.length>=ia.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?.(),f=s.getServerCapabilities?.()?.resources!==void 0;return{tools:c,serverInfo:h?{name:h.name,version:h.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,ia.maxInstructionsLength):void 0,resources:f}}finally{await o()}}async function iz(e,t,n,r,i,s){let o=s??ia.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await Xye(e,r,c)}catch(u){throw new Error(Cm(u instanceof Error?u.message:String(u)))}try{let u=await l.client.callTool({name:t,arguments:n},void 0,{signal:c});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(Cm(u instanceof Error?u.message:String(u)))}finally{await l.close()}}async function rXe(e,t,n,r,i){let s=i??ia.callTimeoutMs,o=r?AbortSignal.any([r,AbortSignal.timeout(s)]):AbortSignal.timeout(s),c;try{c=await Xye(e,n,o,ia.maxResourceResponseBytes)}catch(l){throw new Error(Cm(l instanceof Error?l.message:String(l)))}try{let{client:l}=c;if(t.method==="resources/read")return await l.readResource({uri:t.uri},{signal:o});let u=t.method==="resources/list"?"resources":"resourceTemplates",d=a(g=>t.method==="resources/list"?l.listResources(g===void 0?void 0:{cursor:g},{signal:o}):l.listResourceTemplates(g===void 0?void 0:{cursor:g},{signal:o}),"page");if(t.cursor!==void 0)return await d(t.cursor);let p=[],h=new Set,m=0,f;for(let g=0;g<ia.maxCatalogPages;g++){let v=await d(f),x=Array.isArray(v[u])?v[u]:[],b=new TextEncoder().encode(JSON.stringify(x)).byteLength;if(p.length>0&&m+b>ia.maxResourceResponseBytes)break;p.push(...x),m+=b;let w=typeof v.nextCursor=="string"?v.nextCursor:void 0;if(w===void 0){f=void 0;break}if(h.has(w))throw new Error(`Server repeated a ${t.method} continuation cursor`);h.add(w),f=w}return f===void 0?{[u]:p}:{[u]:p,nextCursor:f}}catch(l){throw new Error(Cm(l instanceof Error?l.message:String(l)))}finally{await c.close()}}var Tfn,Afn,Ifn,Ofn,zb,KO=q(()=>{"use strict";aYe();jYe();KYe();rz();nz();VO();Tfn=[".internal",".local",".localhost"],Afn=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Ifn=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Rfn,"extractMappedIPv4");a(Cfn,"isIpAddress");a(lv,"assertSafeUrl");a(Pfn,"buildHeaders");Ofn=new tz,zb=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(Mfn,"byteCappedFetch");a(Xye,"connectClient");a(nXe,"probe");a(iz,"callTool");a(rXe,"requestResources")});var oz={};Lt(oz,{buildAuthorizationUrl:()=>Wfn,discoverEndpoints:()=>jfn,exchangeCode:()=>Bfn,isTokenExpired:()=>Hfn,refreshToken:()=>zfn,registerClient:()=>qfn});function aXe(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 Ffn(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 jfn(e){let t=AbortSignal.timeout(sz),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);lv(i.href);let s=await zb(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let c=(await s.json()).authorization_servers?.[0];if(typeof c!="string")throw new Error("No authorization server in PRM");let l=new URL(c),u=l.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${l.pathname}`,d=new URL(u,l.origin);lv(d.href);let p=await zb(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 qfn(e,t,n){let r=AbortSignal.timeout(sz);lv(e);let i=await zb(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 Wfn(e,t,n,r,i){let s=aXe(32),o=aXe(64),c=await Ffn(o),l=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:c,code_challenge_method:"S256",resource:i}))l.searchParams.set(u,d);return{authorizationUrl:l.href,pendingFlow:{state:s,codeVerifier:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function Bfn(e,t,n,r,i,s){let o=AbortSignal.timeout(sz),c=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&c.set("resource",s),t.clientSecret!==void 0&&c.set("client_secret",t.clientSecret),lv(e);let l=await zb(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c.toString(),signal:o});if(!l.ok)throw new Error(`Token exchange failed: HTTP ${l.status}`);return cXe(await l.json())}async function zfn(e,t,n,r){let i=AbortSignal.timeout(sz),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),lv(e);let o=await zb(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 cXe(await o.json())}function cXe(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 Hfn(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var sz,az=q(()=>{"use strict";KO();sz=1e4;a(aXe,"randomString");a(Ffn,"sha256Base64Url");a(jfn,"discoverEndpoints");a(qfn,"registerClient");a(Wfn,"buildAuthorizationUrl");a(Bfn,"exchangeCode");a(zfn,"refreshToken");a(cXe,"parseTokenResponse");a(Hfn,"isTokenExpired")});var hr,gXe,XI=q(()=>{yr();Ur();hr=class extends oi{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},gXe=class extends Dt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new hr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function eM(e){return bz.test(e)}function wz(e){return e.invocation.modelInvocable}function kz(e){return e.invocation.userInvocable}function b1e(e){let t=B0n(e);return[`<skill_content name="${z0n(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
168
168
|
`)}function B0n(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${ZI(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${ZI(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: ${ZI(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: ${ZI(t.description)}`,"Load referenced resources only as needed."];default:return Pr(t,"SkillResourceBase.kind")}}function z0n(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function ZI(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function G0n(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw HXe(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw HXe(t);return n}function HXe(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function K0n(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:W0n,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function Q0n(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!bz.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(w1e(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 J0n(e){if(!bz.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`);w1e(e.invocation,`runtime skill "${e.name}"`)}function Y0n(e){let t=e.name,n=e.description,r=e.whenToUse,i=e.invocation,s=e.source,o=e.provider,c=e.content,l=e.path;if(typeof t!="string")throw new TypeError("loaded skill name must be a string");if(!bz.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(w1e(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 c!="string")throw new TypeError(`loaded skill "${t}" content must be a string`);if(l!==void 0&&typeof l!="string")throw new TypeError(`loaded skill "${t}" path must be a string`)}function X0n(e){let{name:t,description:n,whenToUse:r,invocation:i,source:s,provider:o,resourceBase:c}=e;return{name:t,...e.path===void 0?{}:{path:e.path},description:n,...r!==void 0?{whenToUse:r}:{},invocation:i,source:s,provider:o,...c!==void 0?{resourceBase:c}:{}}}function w1e(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 Z0n(e,t){return QXe(e.name,t.name)}function QXe(e,t){return e<t?-1:e>t?1:0}function eyn(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function tyn(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 GXe(e,t){return t===void 0?e:(ZO(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(xz(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(xz(o))})}))}function ZO(e){if(e?.aborted===!0)throw xz(e.reason)}function xz(e){try{if(e instanceof Error)return e}catch{}return new Error(vz(e))}function vz(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var bz,zXe,q0n,yz,W0n,VXe,H0n,KXe,V0n,eR=q(()=>{yr();ws();Jl();kn();bz=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,zXe=128,q0n=2,yz="runtime",W0n=250,VXe=600;a(eM,"isSkillName");a(wz,"isModelInvocable");a(kz,"isUserInvocable");a(b1e,"renderSkillContent");a(B0n,"renderResourceHint");a(z0n,"escapeAttr");a(ZI,"escapeText");H0n=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new mm(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}},KXe=class extends Dt{static{a(this,"SkillRegistry")}static Config=j.object({collectCacheMaxEntries:j.number().default(zXe)});collectCacheMaxEntries;layers=new fm(e=>new H0n(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??zXe,tyn("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===yz)throw new Error(`"${yz}" is reserved for runtime skill registrations`);let o=this.nextProviderOrder;return this.nextProviderOrder+=1,this.layers.effect(this.ctx,c=>{let l=c.providers.insert(s,{provider:r,order:o});return n={layer:c,name:s},()=>{n=void 0,l(),t.abort(new Error(`skill provider "${s}" disposed`))}},{label:"skills.registerProvider()"})}catch(s){throw t.abort(s),s}}register(e){J0n(e);let t=nl(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??yz};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=>X0n(n.candidate)).sort(Z0n),complete:t.cacheable}}async get(e,t={}){if(!eM(e))return;let n=await this.collect(t);ZO(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await GXe(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(Y0n(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){ZO(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,wP(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(ZO(e.signal),n!==this.revision){if(t<q0n){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(eyn);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){ZO(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,c)=>QXe(o.name,c.name)))n.push({candidate:K0n(s),provider:V0n,providerOrder:-1,localOrder:i,layer:e}),i+=1;for(let{provider:s,order:o}of[...e.providers.values()]){let c=0,l;try{l=await GXe(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw xz(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${vz(d)}`)}if(l===void 0)continue;let u=G0n(l,s.name);u.complete||(r=!1);for(let d of u.candidates)Q0n(d,s.name),n.push({candidate:d,provider:s,providerOrder:o,localOrder:c,layer:e}),c+=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: ${vz(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${vz(t)}`)}}};a(G0n,"normalizeProviderObservation");a(HXe,"invalidProviderObservation");V0n={name:yz,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(K0n,"runtimeCandidate");a(Q0n,"validateCandidate");a(J0n,"validateRuntimeSkill");a(Y0n,"validateDefinition");a(X0n,"toSummary");a(w1e,"validateInvocation");a(Z0n,"compareSkillSummary");a(QXe,"compareCodePoints");a(eyn,"compareIndexedCandidates");a(tyn,"assertPositiveInteger");a(GXe,"waitWithAbort");a(ZO,"throwIfAborted");a(xz,"toError");a(vz,"errorMessage")});var Pm,cR=q(()=>{Pm=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 mv,Ttt,Cve=q(()=>{yr();mv=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},Ttt=class extends Dt{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var ER=ue((j0i,Qnt)=>{"use strict";var _Sn="2.0.0",ESn=Number.MAX_SAFE_INTEGER||9007199254740991,TSn=16,ASn=250,ISn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Qnt.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:TSn,MAX_SAFE_BUILD_LENGTH:ASn,MAX_SAFE_INTEGER:ESn,RELEASE_TYPES:ISn,SEMVER_SPEC_VERSION:_Sn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var FM=ue((q0i,Jnt)=>{"use strict";var RSn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};Jnt.exports=RSn});var TR=ue((yy,Ynt)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:kxe,MAX_SAFE_BUILD_LENGTH:CSn,MAX_LENGTH:PSn}=ER(),OSn=FM();yy=Ynt.exports={};var MSn=yy.re=[],NSn=yy.safeRe=[],Mn=yy.src=[],LSn=yy.safeSrc=[],Nn=yy.t={},DSn=0,Sxe="[a-zA-Z0-9-]",$Sn=[["\\s",1],["\\d",PSn],[Sxe,CSn]],USn=a(e=>{for(let[t,n]of $Sn)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},"makeSafeRegex"),di=a((e,t,n)=>{let r=USn(t),i=DSn++;OSn(e,i,t),Nn[e]=i,Mn[i]=t,LSn[i]=r,MSn[i]=new RegExp(t,n?"g":void 0),NSn[i]=new RegExp(r,n?"g":void 0)},"createToken");di("NUMERICIDENTIFIER","0|[1-9]\\d*");di("NUMERICIDENTIFIERLOOSE","\\d+");di("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Sxe}*`);di("MAINVERSION",`(${Mn[Nn.NUMERICIDENTIFIER]})\\.(${Mn[Nn.NUMERICIDENTIFIER]})\\.(${Mn[Nn.NUMERICIDENTIFIER]})`);di("MAINVERSIONLOOSE",`(${Mn[Nn.NUMERICIDENTIFIERLOOSE]})\\.(${Mn[Nn.NUMERICIDENTIFIERLOOSE]})\\.(${Mn[Nn.NUMERICIDENTIFIERLOOSE]})`);di("PRERELEASEIDENTIFIER",`(?:${Mn[Nn.NONNUMERICIDENTIFIER]}|${Mn[Nn.NUMERICIDENTIFIER]})`);di("PRERELEASEIDENTIFIERLOOSE",`(?:${Mn[Nn.NONNUMERICIDENTIFIER]}|${Mn[Nn.NUMERICIDENTIFIERLOOSE]})`);di("PRERELEASE",`(?:-(${Mn[Nn.PRERELEASEIDENTIFIER]}(?:\\.${Mn[Nn.PRERELEASEIDENTIFIER]})*))`);di("PRERELEASELOOSE",`(?:-?(${Mn[Nn.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${Mn[Nn.PRERELEASEIDENTIFIERLOOSE]})*))`);di("BUILDIDENTIFIER",`${Sxe}+`);di("BUILD",`(?:\\+(${Mn[Nn.BUILDIDENTIFIER]}(?:\\.${Mn[Nn.BUILDIDENTIFIER]})*))`);di("FULLPLAIN",`v?${Mn[Nn.MAINVERSION]}${Mn[Nn.PRERELEASE]}?${Mn[Nn.BUILD]}?`);di("FULL",`^${Mn[Nn.FULLPLAIN]}$`);di("LOOSEPLAIN",`[v=\\s]*${Mn[Nn.MAINVERSIONLOOSE]}${Mn[Nn.PRERELEASELOOSE]}?${Mn[Nn.BUILD]}?`);di("LOOSE",`^${Mn[Nn.LOOSEPLAIN]}$`);di("GTLT","((?:<|>)?=?)");di("XRANGEIDENTIFIERLOOSE",`${Mn[Nn.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);di("XRANGEIDENTIFIER",`${Mn[Nn.NUMERICIDENTIFIER]}|x|X|\\*`);di("XRANGEPLAIN",`[v=\\s]*(${Mn[Nn.XRANGEIDENTIFIER]})(?:\\.(${Mn[Nn.XRANGEIDENTIFIER]})(?:\\.(${Mn[Nn.XRANGEIDENTIFIER]})(?:${Mn[Nn.PRERELEASE]})?${Mn[Nn.BUILD]}?)?)?`);di("XRANGEPLAINLOOSE",`[v=\\s]*(${Mn[Nn.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Mn[Nn.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Mn[Nn.XRANGEIDENTIFIERLOOSE]})(?:${Mn[Nn.PRERELEASELOOSE]})?${Mn[Nn.BUILD]}?)?)?`);di("XRANGE",`^${Mn[Nn.GTLT]}\\s*${Mn[Nn.XRANGEPLAIN]}$`);di("XRANGELOOSE",`^${Mn[Nn.GTLT]}\\s*${Mn[Nn.XRANGEPLAINLOOSE]}$`);di("COERCEPLAIN",`(^|[^\\d])(\\d{1,${kxe}})(?:\\.(\\d{1,${kxe}}))?(?:\\.(\\d{1,${kxe}}))?`);di("COERCE",`${Mn[Nn.COERCEPLAIN]}(?:$|[^\\d])`);di("COERCEFULL",Mn[Nn.COERCEPLAIN]+`(?:${Mn[Nn.PRERELEASE]})?(?:${Mn[Nn.BUILD]})?(?:$|[^\\d])`);di("COERCERTL",Mn[Nn.COERCE],!0);di("COERCERTLFULL",Mn[Nn.COERCEFULL],!0);di("LONETILDE","(?:~>?)");di("TILDETRIM",`(\\s*)${Mn[Nn.LONETILDE]}\\s+`,!0);yy.tildeTrimReplace="$1~";di("TILDE",`^${Mn[Nn.LONETILDE]}${Mn[Nn.XRANGEPLAIN]}$`);di("TILDELOOSE",`^${Mn[Nn.LONETILDE]}${Mn[Nn.XRANGEPLAINLOOSE]}$`);di("LONECARET","(?:\\^)");di("CARETTRIM",`(\\s*)${Mn[Nn.LONECARET]}\\s+`,!0);yy.caretTrimReplace="$1^";di("CARET",`^${Mn[Nn.LONECARET]}${Mn[Nn.XRANGEPLAIN]}$`);di("CARETLOOSE",`^${Mn[Nn.LONECARET]}${Mn[Nn.XRANGEPLAINLOOSE]}$`);di("COMPARATORLOOSE",`^${Mn[Nn.GTLT]}\\s*(${Mn[Nn.LOOSEPLAIN]})$|^$`);di("COMPARATOR",`^${Mn[Nn.GTLT]}\\s*(${Mn[Nn.FULLPLAIN]})$|^$`);di("COMPARATORTRIM",`(\\s*)${Mn[Nn.GTLT]}\\s*(${Mn[Nn.LOOSEPLAIN]}|${Mn[Nn.XRANGEPLAIN]})`,!0);yy.comparatorTrimReplace="$1$2$3";di("HYPHENRANGE",`^\\s*(${Mn[Nn.XRANGEPLAIN]})\\s+-\\s+(${Mn[Nn.XRANGEPLAIN]})\\s*$`);di("HYPHENRANGELOOSE",`^\\s*(${Mn[Nn.XRANGEPLAINLOOSE]})\\s+-\\s+(${Mn[Nn.XRANGEPLAINLOOSE]})\\s*$`);di("STAR","(<|>)?=?\\s*\\*");di("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");di("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var eG=ue((B0i,Xnt)=>{"use strict";var FSn=Object.freeze({loose:!0}),jSn=Object.freeze({}),qSn=a(e=>e?typeof e!="object"?FSn:e:jSn,"parseOptions");Xnt.exports=qSn});var _xe=ue((H0i,trt)=>{"use strict";var Znt=/^[0-9]+$/,ert=a((e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let n=Znt.test(e),r=Znt.test(t);return n&&r&&(e=+e,t=+t),e===t?0:n&&!r?-1:r&&!n?1:e<t?-1:1},"compareIdentifiers"),WSn=a((e,t)=>ert(t,e),"rcompareIdentifiers");trt.exports={compareIdentifiers:ert,rcompareIdentifiers:WSn}});var lu=ue((V0i,rrt)=>{"use strict";var tG=FM(),{MAX_LENGTH:nrt,MAX_SAFE_INTEGER:nG}=ER(),{safeRe:rG,t:iG}=TR(),BSn=eG(),{compareIdentifiers:Exe}=_xe(),zSn=a((e,t)=>{let n=t.split(".");if(n.length>e.length)return!1;for(let r=0;r<n.length;r++)if(Exe(e[r],n[r])!==0)return!1;return!0},"isPrereleaseIdentifier"),Txe=class e{static{a(this,"SemVer")}constructor(t,n){if(n=BSn(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>nrt)throw new TypeError(`version is longer than ${nrt} characters`);tG("SemVer",t,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let r=t.trim().match(n.loose?rG[iG.LOOSE]:rG[iG.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>nG||this.major<0)throw new TypeError("Invalid major version");if(this.minor>nG||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>nG||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<nG)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(tG("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(tG("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 Exe(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(tG("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 Exe(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?rG[iG.PRERELEASELOOSE]:rG[iG.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]),zSn(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}};rrt.exports=Txe});var aw=ue((Q0i,srt)=>{"use strict";var irt=lu(),HSn=a((e,t,n=!1)=>{if(e instanceof irt)return e;try{return new irt(e,t)}catch(r){if(!n)return null;throw r}},"parse");srt.exports=HSn});var art=ue((Y0i,ort)=>{"use strict";var GSn=aw(),VSn=a((e,t)=>{let n=GSn(e,t);return n?n.version:null},"valid");ort.exports=VSn});var lrt=ue((Z0i,crt)=>{"use strict";var KSn=aw(),QSn=a((e,t)=>{let n=KSn(e.trim().replace(/^[=v]+/,""),t);return n?n.version:null},"clean");crt.exports=QSn});var prt=ue((tyi,drt)=>{"use strict";var urt=lu(),JSn=a((e,t,n,r,i)=>{typeof n=="string"&&(i=r,r=n,n=void 0);try{return new urt(e instanceof urt?e.version:e,n).inc(t,r,i).version}catch{return null}},"inc");drt.exports=JSn});var frt=ue((ryi,mrt)=>{"use strict";var hrt=aw(),YSn=a((e,t)=>{let n=hrt(e,null,!0),r=hrt(t,null,!0),i=n.compare(r);if(i===0)return null;let s=i>0,o=s?n:r,c=s?r:n,l=!!o.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(o)===0)return c.minor&&!c.patch?"minor":"patch"}let d=l?"pre":"";return n.major!==r.major?d+"major":n.minor!==r.minor?d+"minor":n.patch!==r.patch?d+"patch":"prerelease"},"diff");mrt.exports=YSn});var yrt=ue((syi,grt)=>{"use strict";var XSn=lu(),ZSn=a((e,t)=>new XSn(e,t).major,"major");grt.exports=ZSn});var xrt=ue((ayi,vrt)=>{"use strict";var e2n=lu(),t2n=a((e,t)=>new e2n(e,t).minor,"minor");vrt.exports=t2n});var wrt=ue((lyi,brt)=>{"use strict";var n2n=lu(),r2n=a((e,t)=>new n2n(e,t).patch,"patch");brt.exports=r2n});var Srt=ue((dyi,krt)=>{"use strict";var i2n=aw(),s2n=a((e,t)=>{let n=i2n(e,t);return n&&n.prerelease.length?n.prerelease:null},"prerelease");krt.exports=s2n});var Mm=ue((hyi,Ert)=>{"use strict";var _rt=lu(),o2n=a((e,t,n)=>new _rt(e,n).compare(new _rt(t,n)),"compare");Ert.exports=o2n});var Art=ue((fyi,Trt)=>{"use strict";var a2n=Mm(),c2n=a((e,t,n)=>a2n(t,e,n),"rcompare");Trt.exports=c2n});var Rrt=ue((yyi,Irt)=>{"use strict";var l2n=Mm(),u2n=a((e,t)=>l2n(e,t,!0),"compareLoose");Irt.exports=u2n});var sG=ue((xyi,Prt)=>{"use strict";var Crt=lu(),d2n=a((e,t,n)=>{let r=new Crt(e,n),i=new Crt(t,n);return r.compare(i)||r.compareBuild(i)},"compareBuild");Prt.exports=d2n});var Mrt=ue((wyi,Ort)=>{"use strict";var p2n=sG(),h2n=a((e,t)=>e.sort((n,r)=>p2n(n,r,t)),"sort");Ort.exports=h2n});var Lrt=ue((Syi,Nrt)=>{"use strict";var m2n=sG(),f2n=a((e,t)=>e.sort((n,r)=>m2n(r,n,t)),"rsort");Nrt.exports=f2n});var jM=ue((Eyi,Drt)=>{"use strict";var g2n=Mm(),y2n=a((e,t,n)=>g2n(e,t,n)>0,"gt");Drt.exports=y2n});var oG=ue((Ayi,$rt)=>{"use strict";var v2n=Mm(),x2n=a((e,t,n)=>v2n(e,t,n)<0,"lt");$rt.exports=x2n});var Axe=ue((Ryi,Urt)=>{"use strict";var b2n=Mm(),w2n=a((e,t,n)=>b2n(e,t,n)===0,"eq");Urt.exports=w2n});var Ixe=ue((Pyi,Frt)=>{"use strict";var k2n=Mm(),S2n=a((e,t,n)=>k2n(e,t,n)!==0,"neq");Frt.exports=S2n});var aG=ue((Myi,jrt)=>{"use strict";var _2n=Mm(),E2n=a((e,t,n)=>_2n(e,t,n)>=0,"gte");jrt.exports=E2n});var cG=ue((Lyi,qrt)=>{"use strict";var T2n=Mm(),A2n=a((e,t,n)=>T2n(e,t,n)<=0,"lte");qrt.exports=A2n});var Rxe=ue(($yi,Wrt)=>{"use strict";var I2n=Axe(),R2n=Ixe(),C2n=jM(),P2n=aG(),O2n=oG(),M2n=cG(),N2n=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 I2n(e,n,r);case"!=":return R2n(e,n,r);case">":return C2n(e,n,r);case">=":return P2n(e,n,r);case"<":return O2n(e,n,r);case"<=":return M2n(e,n,r);default:throw new TypeError(`Invalid operator: ${t}`)}},"cmp");Wrt.exports=N2n});var zrt=ue((Fyi,Brt)=>{"use strict";var L2n=lu(),D2n=aw(),{safeRe:lG,t:uG}=TR(),$2n=a((e,t)=>{if(e instanceof L2n)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?lG[uG.COERCEFULL]:lG[uG.COERCE]);else{let l=t.includePrerelease?lG[uG.COERCERTLFULL]:lG[uG.COERCERTL],u;for(;(u=l.exec(e))&&(!n||n.index+n[0].length!==e.length);)(!n||u.index+u[0].length!==n.index+n[0].length)&&(n=u),l.lastIndex=u.index+u[1].length+u[2].length;l.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]}`:"",c=t.includePrerelease&&n[6]?`+${n[6]}`:"";return D2n(`${r}.${i}.${s}${o}${c}`,t)},"coerce");Brt.exports=$2n});var Grt=ue((qyi,Hrt)=>{"use strict";var U2n=aw(),F2n=ER(),j2n=lu(),q2n=a((e,t,n)=>{if(!F2n.RELEASE_TYPES.includes(t))return null;let r=W2n(e,n);return r&&B2n(r,t)},"truncate"),W2n=a((e,t)=>{let n=e instanceof j2n?e.version:e;return U2n(n,t)},"cloneInputVersion"),B2n=a((e,t)=>{if(z2n(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"),z2n=a(e=>e.startsWith("pre"),"isPrerelease");Hrt.exports=q2n});var Krt=ue((Byi,Vrt)=>{"use strict";var Cxe=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}};Vrt.exports=Cxe});var Nm=ue((Hyi,Xrt)=>{"use strict";var H2n=/\s+/g,Pxe=class e{static{a(this,"Range")}constructor(t,n){if(n=V2n(n),t instanceof e)return t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease?t:new e(t.raw,n);if(t instanceof Oxe)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(H2n," "),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=>!Jrt(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&&n_n(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(t_n,"");let r=((this.options.includePrerelease&&Z2n)|(this.options.loose&&e_n))+":"+t,i=Qrt.get(r);if(i)return i;let s=this.options.loose,o=s?qd[uu.HYPHENRANGELOOSE]:qd[uu.HYPHENRANGE];t=t.replace(o,h_n(this.options.includePrerelease)),oa("hyphen replace",t),t=t.replace(qd[uu.COMPARATORTRIM],J2n),oa("comparator trim",t),t=t.replace(qd[uu.TILDETRIM],Y2n),oa("tilde trim",t),t=t.replace(qd[uu.CARETTRIM],X2n),oa("caret trim",t);let c=t.split(" ").map(p=>r_n(p,this.options)).join(" ").split(/\s+/).map(p=>p_n(p,this.options));s&&(c=c.filter(p=>(oa("loose invalid filter",p,this.options),!!p.match(qd[uu.COMPARATORLOOSE])))),oa("range list",c);let l=new Map,u=c.map(p=>new Oxe(p,this.options));for(let p of u){if(Jrt(p))return[p];l.set(p.value,p)}l.size>1&&l.has("")&&l.delete("");let d=[...l.values()];return Qrt.set(r,d),d}intersects(t,n){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(r=>Yrt(r,n)&&t.set.some(i=>Yrt(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 K2n(t,this.options)}catch{return!1}for(let n=0;n<this.set.length;n++)if(m_n(this.set[n],t,this.options))return!0;return!1}};Xrt.exports=Pxe;var G2n=Krt(),Qrt=new G2n,V2n=eG(),Oxe=qM(),oa=FM(),K2n=lu(),{safeRe:qd,src:Q2n,t:uu,comparatorTrimReplace:J2n,tildeTrimReplace:Y2n,caretTrimReplace:X2n}=TR(),{FLAG_INCLUDE_PRERELEASE:Z2n,FLAG_LOOSE:e_n}=ER(),t_n=new RegExp(Q2n[uu.BUILD],"g"),Jrt=a(e=>e.value==="<0.0.0-0","isNullSet"),n_n=a(e=>e.value==="","isAny"),Yrt=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"),r_n=a((e,t)=>(e=e.replace(qd[uu.BUILD],""),oa("comp",e,t),e=a_n(e,t),oa("caret",e),e=s_n(e,t),oa("tildes",e),e=l_n(e,t),oa("xrange",e),e=d_n(e,t),oa("stars",e),e),"parseComparator"),cl=a(e=>!e||e.toLowerCase()==="x"||e==="*","isX"),i_n=a((e,t,n)=>cl(e)&&!cl(t)||cl(t)&&n&&!cl(n),"invalidXRangeOrder"),s_n=a((e,t)=>e.trim().split(/\s+/).map(n=>o_n(n,t)).join(" "),"replaceTildes"),o_n=a((e,t)=>{let n=t.loose?qd[uu.TILDELOOSE]:qd[uu.TILDE],r=t.includePrerelease?"-0":"";return e.replace(n,(i,s,o,c,l)=>{oa("tilde",e,i,s,o,c,l);let u;return cl(s)?u="":cl(o)?u=`>=${s}.0.0${r} <${+s+1}.0.0-0`:cl(c)?u=`>=${s}.${o}.0${r} <${s}.${+o+1}.0-0`:l?(oa("replaceTilde pr",l),u=`>=${s}.${o}.${c}-${l} <${s}.${+o+1}.0-0`):u=`>=${s}.${o}.${c} <${s}.${+o+1}.0-0`,oa("tilde return",u),u})},"replaceTilde"),a_n=a((e,t)=>e.trim().split(/\s+/).map(n=>c_n(n,t)).join(" "),"replaceCarets"),c_n=a((e,t)=>{oa("caret",e,t);let n=t.loose?qd[uu.CARETLOOSE]:qd[uu.CARET],r=t.includePrerelease?"-0":"";return e.replace(n,(i,s,o,c,l)=>{oa("caret",e,i,s,o,c,l);let u;return cl(s)?u="":cl(o)?u=`>=${s}.0.0${r} <${+s+1}.0.0-0`:cl(c)?s==="0"?u=`>=${s}.${o}.0${r} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.0${r} <${+s+1}.0.0-0`:l?(oa("replaceCaret pr",l),s==="0"?o==="0"?u=`>=${s}.${o}.${c}-${l} <${s}.${o}.${+c+1}-0`:u=`>=${s}.${o}.${c}-${l} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${c}-${l} <${+s+1}.0.0-0`):(oa("no pr"),s==="0"?o==="0"?u=`>=${s}.${o}.${c} <${s}.${o}.${+c+1}-0`:u=`>=${s}.${o}.${c} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${c} <${+s+1}.0.0-0`),oa("caret return",u),u})},"replaceCaret"),l_n=a((e,t)=>(oa("replaceXRanges",e,t),e.split(/\s+/).map(n=>u_n(n,t)).join(" ")),"replaceXRanges"),u_n=a((e,t)=>{e=e.trim();let n=t.loose?qd[uu.XRANGELOOSE]:qd[uu.XRANGE];return e.replace(n,(r,i,s,o,c,l)=>{if(oa("xRange",e,r,i,s,o,c,l),i_n(s,o,c))return e;let u=cl(s),d=u||cl(o),p=d||cl(c),h=p;return i==="="&&h&&(i=""),l=t.includePrerelease?"-0":"",u?i===">"||i==="<"?r="<0.0.0-0":r="*":i&&h?(d&&(o=0),c=0,i===">"?(i=">=",d?(s=+s+1,o=0,c=0):(o=+o+1,c=0)):i==="<="&&(i="<",d?s=+s+1:o=+o+1),i==="<"&&(l="-0"),r=`${i+s}.${o}.${c}${l}`):d?r=`>=${s}.0.0${l} <${+s+1}.0.0-0`:p&&(r=`>=${s}.${o}.0${l} <${s}.${+o+1}.0-0`),oa("xRange return",r),r})},"replaceXRange"),d_n=a((e,t)=>(oa("replaceStars",e,t),e.trim().replace(qd[uu.STAR],"")),"replaceStars"),p_n=a((e,t)=>(oa("replaceGTE0",e,t),e.trim().replace(qd[t.includePrerelease?uu.GTE0PRE:uu.GTE0],"")),"replaceGTE0"),h_n=a(e=>(t,n,r,i,s,o,c,l,u,d,p,h)=>(cl(r)?n="":cl(i)?n=`>=${r}.0.0${e?"-0":""}`:cl(s)?n=`>=${r}.${i}.0${e?"-0":""}`:o?n=`>=${n}`:n=`>=${n}${e?"-0":""}`,cl(u)?l="":cl(d)?l=`<${+u+1}.0.0-0`:cl(p)?l=`<${u}.${+d+1}.0-0`:h?l=`<=${u}.${d}.${p}-${h}`:e?l=`<${u}.${d}.${+p+1}-0`:l=`<=${l}`,`${n} ${l}`.trim()),"hyphenReplace"),m_n=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(oa(e[r].semver),e[r].semver!==Oxe.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 qM=ue((Vyi,iit)=>{"use strict";var WM=Symbol("SemVer ANY"),Lxe=class e{static{a(this,"Comparator")}static get ANY(){return WM}constructor(t,n){if(n=Zrt(n),t instanceof e){if(t.loose===!!n.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Nxe("comparator",t,n),this.options=n,this.loose=!!n.loose,this.parse(t),this.semver===WM?this.value="":this.value=this.operator+this.semver.version,Nxe("comp",this)}parse(t){let n=this.options.loose?eit[tit.COMPARATORLOOSE]:eit[tit.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 nit(r[2],this.options.loose):this.semver=WM}toString(){return this.value}test(t){if(Nxe("Comparator.test",t,this.options.loose),this.semver===WM||t===WM)return!0;if(typeof t=="string")try{t=new nit(t,this.options)}catch{return!1}return Mxe(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 rit(t.value,n).test(this.value):t.operator===""?t.value===""?!0:new rit(this.value,n).test(t.semver):(n=Zrt(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("=")||Mxe(this.semver,"<",t.semver,n)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Mxe(this.semver,">",t.semver,n)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};iit.exports=Lxe;var Zrt=eG(),{safeRe:eit,t:tit}=TR(),Mxe=Rxe(),Nxe=FM(),nit=lu(),rit=Nm()});var BM=ue((Qyi,sit)=>{"use strict";var f_n=Nm(),g_n=a((e,t,n)=>{try{t=new f_n(t,n)}catch{return!1}return t.test(e)},"satisfies");sit.exports=g_n});var ait=ue((Yyi,oit)=>{"use strict";var y_n=Nm(),v_n=a((e,t)=>new y_n(e,t).set.map(n=>n.map(r=>r.value).join(" ").trim().split(" ")),"toComparators");oit.exports=v_n});var lit=ue((Zyi,cit)=>{"use strict";var x_n=lu(),b_n=Nm(),w_n=a((e,t,n)=>{let r=null,i=null,s=null;try{s=new b_n(t,n)}catch{return null}return e.forEach(o=>{s.test(o)&&(!r||i.compare(o)===-1)&&(r=o,i=new x_n(r,n))}),r},"maxSatisfying");cit.exports=w_n});var dit=ue((t1i,uit)=>{"use strict";var k_n=lu(),S_n=Nm(),__n=a((e,t,n)=>{let r=null,i=null,s=null;try{s=new S_n(t,n)}catch{return null}return e.forEach(o=>{s.test(o)&&(!r||i.compare(o)===1)&&(r=o,i=new k_n(r,n))}),r},"minSatisfying");uit.exports=__n});var mit=ue((r1i,hit)=>{"use strict";var Dxe=lu(),E_n=Nm(),pit=jM(),T_n=a((e,t)=>{e=new E_n(e,t);let n=new Dxe("0.0.0");if(e.test(n)||(n=new Dxe("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 c=new Dxe(o.semver.version);switch(o.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!s||pit(c,s))&&(s=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!n||pit(n,s))&&(n=s)}return n&&e.test(n)?n:null},"minVersion");hit.exports=T_n});var git=ue((s1i,fit)=>{"use strict";var A_n=Nm(),I_n=a((e,t)=>{try{return new A_n(e,t).range||"*"}catch{return null}},"validRange");fit.exports=I_n});var dG=ue((a1i,bit)=>{"use strict";var R_n=lu(),xit=qM(),{ANY:C_n}=xit,P_n=Nm(),O_n=BM(),yit=jM(),vit=oG(),M_n=cG(),N_n=aG(),L_n=a((e,t,n,r)=>{e=new R_n(e,r),t=new P_n(t,r);let i,s,o,c,l;switch(n){case">":i=yit,s=M_n,o=vit,c=">",l=">=";break;case"<":i=vit,s=N_n,o=yit,c="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(O_n(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===C_n&&(m=new xit(">=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===c||p.operator===l||(!h.operator||h.operator===c)&&s(e,h.semver))return!1;if(h.operator===l&&o(e,h.semver))return!1}return!0},"outside");bit.exports=L_n});var kit=ue((l1i,wit)=>{"use strict";var D_n=dG(),$_n=a((e,t,n)=>D_n(e,t,">",n),"gtr");wit.exports=$_n});var _it=ue((d1i,Sit)=>{"use strict";var U_n=dG(),F_n=a((e,t,n)=>U_n(e,t,"<",n),"ltr");Sit.exports=F_n});var Ait=ue((h1i,Tit)=>{"use strict";var Eit=Nm(),j_n=a((e,t,n)=>(e=new Eit(e,n),t=new Eit(t,n),e.intersects(t,n)),"intersects");Tit.exports=j_n});var Rit=ue((f1i,Iit)=>{"use strict";var q_n=BM(),W_n=Mm();Iit.exports=(e,t,n)=>{let r=[],i=null,s=null,o=e.sort((d,p)=>W_n(d,p,n));for(let d of o)q_n(d,t,n)?(s=d,i||(i=d)):(s&&r.push([i,s]),s=null,i=null);i&&r.push([i,null]);let c=[];for(let[d,p]of r)d===p?c.push(d):!p&&d===o[0]?c.push("*"):p?d===o[0]?c.push(`<=${p}`):c.push(`${d} - ${p}`):c.push(`>=${d}`);let l=c.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return l.length<u.length?l:t}});var Lit=ue((g1i,Nit)=>{"use strict";var Cit=Nm(),Fxe=qM(),{ANY:$xe}=Fxe,Uxe=BM(),jxe=Mm(),B_n=a((e,t,n={})=>{if(e===t)return!0;e=new Cit(e,n),t=new Cit(t,n);let r=!1;e:for(let i of e.set){for(let s of t.set){let o=H_n(i,s,n);if(r=r||o!==null,o)continue e}if(r)return!1}return!0},"subset"),z_n=[new Fxe(">=0.0.0-0")],Pit=[new Fxe(">=0.0.0")],H_n=a((e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===$xe){if(t.length===1&&t[0].semver===$xe)return!0;n.includePrerelease?e=z_n:e=Pit}if(t.length===1&&t[0].semver===$xe){if(n.includePrerelease)return!0;t=Pit}let r=new Set,i,s;for(let m of e)m.operator===">"||m.operator===">="?i=Oit(i,m,n):m.operator==="<"||m.operator==="<="?s=Mit(s,m,n):r.add(m.semver);if(r.size>1)return null;let o;if(i&&s){if(o=jxe(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&&!Uxe(m,String(i),n)||s&&!Uxe(m,String(s),n))return null;for(let f of t)if(!Uxe(m,String(f),n))return!1;return!0}let c,l,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(c=Oit(i,m,n),c===m&&c!==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(l=Mit(s,m,n),l===m&&l!==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"),Oit=a((e,t,n)=>{if(!e)return t;let r=jxe(e.semver,t.semver,n);return r>0?e:r<0||t.operator===">"&&e.operator===">="?t:e},"higherGT"),Mit=a((e,t,n)=>{if(!e)return t;let r=jxe(e.semver,t.semver,n);return r<0?e:r>0||t.operator==="<"&&e.operator==="<="?t:e},"lowerLT");Nit.exports=B_n});var Fit=ue((v1i,Uit)=>{"use strict";var qxe=TR(),Dit=ER(),G_n=lu(),$it=_xe(),V_n=aw(),K_n=art(),Q_n=lrt(),J_n=prt(),Y_n=frt(),X_n=yrt(),Z_n=xrt(),eEn=wrt(),tEn=Srt(),nEn=Mm(),rEn=Art(),iEn=Rrt(),sEn=sG(),oEn=Mrt(),aEn=Lrt(),cEn=jM(),lEn=oG(),uEn=Axe(),dEn=Ixe(),pEn=aG(),hEn=cG(),mEn=Rxe(),fEn=zrt(),gEn=Grt(),yEn=qM(),vEn=Nm(),xEn=BM(),bEn=ait(),wEn=lit(),kEn=dit(),SEn=mit(),_En=git(),EEn=dG(),TEn=kit(),AEn=_it(),IEn=Ait(),REn=Rit(),CEn=Lit();Uit.exports={parse:V_n,valid:K_n,clean:Q_n,inc:J_n,diff:Y_n,major:X_n,minor:Z_n,patch:eEn,prerelease:tEn,compare:nEn,rcompare:rEn,compareLoose:iEn,compareBuild:sEn,sort:oEn,rsort:aEn,gt:cEn,lt:lEn,eq:uEn,neq:dEn,gte:pEn,lte:hEn,cmp:mEn,coerce:fEn,truncate:gEn,Comparator:yEn,Range:vEn,satisfies:xEn,toComparators:bEn,maxSatisfying:wEn,minSatisfying:kEn,minVersion:SEn,validRange:_En,outside:EEn,gtr:TEn,ltr:AEn,intersects:IEn,simplifyRange:REn,subset:CEn,SemVer:G_n,re:qxe.re,src:qxe.src,tokens:qxe.t,SEMVER_SPEC_VERSION:Dit.SEMVER_SPEC_VERSION,RELEASE_TYPES:Dit.RELEASE_TYPES,compareIdentifiers:$it.compareIdentifiers,rcompareIdentifiers:$it.rcompareIdentifiers}});var XV,sbe,Ha,Ag=q(()=>{XV=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()}},sbe=class{static{a(this,"EventStream")}queue=new XV;waiting=new XV;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}},Ha=class extends sbe{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 WAn(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 BAn(e){return typeof e.result=="function"}async function zAn(e,t){for await(let n of t)e.push(n);e.end(BAn(t)?await t.result():void 0)}function Lm(e,t){let n=Date.now(),r=new Ha;return t().then(i=>zAn(r,i)).catch(i=>{let s=WAn(e,i,n);r.push({type:"error",reason:"error",error:s}),r.end(s)}),r}function Dc(e,t){let n={stream:a((r,i,s)=>Lm(r,async()=>(await e()).stream(r,i,s)),"stream"),streamSimple:a((r,i,s)=>Lm(r,async()=>(await e()).streamSimple(r,i,s)),"streamSimple")};return t?.fetchDeferred&&(n.fetchDeferred=(r,i,s)=>Lm(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 Ch=q(()=>{Ag();a(WAn,"createSetupErrorMessage");a(BAn,"hasResult");a(zAn,"forwardStream");a(Lm,"lazyStream");a(Dc,"lazyApi")});function GAn(){return globalThis.process?.env}function oat(){return{async env(e){let t=GAn()?.[e];return typeof t=="string"&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await sat("node:fs/promises"),n=e;return n.startsWith("~")&&(n=(await sat("node:os")).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}var HAn,sat,aat=q(()=>{HAn=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},sat=a(e=>import(HAn(e)),"importNodeModule");a(GAn,"getProcessEnv");a(oat,"defaultProviderAuthContext")});function cat(e){if(e.reason!==void 0)return e.reason;let t=new Error("The operation was aborted");return t.name="AbortError",t}function Dm(e){return e??new AbortController().signal}function $m(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(cat(t))):new Promise((n,r)=>{let i=!1,s=a(()=>t.removeEventListener("abort",o),"cleanup"),o=a(()=>{i||(i=!0,s(),r(cat(t)))},"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(c=>{i||(i=!0,s(),n(c))},c=>{i||(i=!0,s(),r(c))}),t.aborted&&o()})}var ZV=q(()=>{a(cat,"abortReason");a(Dm,"operationSignal");a($m,"raceWithAbortSignal")});var eK,lat=q(()=>{ZV();eK=class{static{a(this,"InMemoryCredentialStore")}credentials=new Map;chains=new Map;enqueue(t,n,r){let i=Dm(r?.signal),s=this.chains.get(t)??Promise.resolve(),o=(async()=>(await s.catch(()=>{}),i.throwIfAborted(),n()))(),c=o.catch(()=>{});return this.chains.set(t,c),c.then(()=>{this.chains.get(t)===c&&this.chains.delete(t)}),$m(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 cw(e){return e instanceof Error?e.message||e.name:typeof e=="string"?e:String(e)}function VAn(e){if(!(e instanceof Error))return{name:"ThrownValue",message:cw(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 tK(e,t,n){return{type:e,timestamp:Date.now(),error:VAn(t),details:n}}function lw(e,t){e.diagnostics=[...e.diagnostics??[],t]}var KM=q(()=>{a(cw,"formatThrownValue");a(VAn,"extractDiagnosticError");a(tK,"createAssistantMessageDiagnostic");a(lw,"appendAssistantMessageDiagnostic")});function KAn(e,t){if(t==null)return e;let n=cw(t).trim();return!n||e.includes(n)?e:`${e}: ${n}`}var as,nK=q(()=>{KM();as=class extends Error{static{a(this,"ModelsError")}code;constructor(t,n,r){super(KAn(n,r?.cause),r),this.name="ModelsError",this.code=t}};a(KAn,"withCauseDetail")});function abe(e,t,n,r){let i=Dm(r?.signal);return $m(QAn(e,t,n,r,i),i)}async function QAn(e,t,n,r,i){i.throwIfAborted();let s=r?.env?JAn(n,r.env):n;if(r?.apiKey!==void 0&&e.auth.apiKey)return obe(s,e.auth.apiKey,e.id,{type:"api_key",key:r.apiKey,env:r.env},i);let o=await eIn(t,e.id,i);if(o){if(o.type==="oauth"&&e.auth.oauth)return ZAn(t,e.id,e.auth.oauth,o,i,r?.minOAuthValidityMs);if(o.type==="api_key"&&e.auth.apiKey){let c=r?.env?{...o,env:{...o.env,...r.env}}:o;return obe(s,e.auth.apiKey,e.id,c,i)}return}return e.auth.apiKey?obe(s,e.auth.apiKey,e.id,void 0,i):void 0}function JAn(e,t){return{env:a(async n=>t[n]||await e.env(n),"env"),fileExists:a(n=>e.fileExists(n),"fileExists")}}async function cbe(e,t,n,r,i){let s,o=new AbortController,c=a(()=>o.abort(i.reason),"cancelLockWait");i.addEventListener("abort",c,{once:!0}),i.aborted&&c();try{s=await e.modify(t,async l=>{if(i.removeEventListener("abort",c),i.throwIfAborted(),l?.type==="oauth"&&r(l))try{return await n.refresh(l,AbortSignal.timeout(XAn))}catch(u){throw new as("oauth",`OAuth refresh failed for ${t}`,{cause:u})}},{signal:o.signal})}catch(l){throw l instanceof as?l:(i.throwIfAborted(),new as("auth",`Credential store modify failed for ${t}`,{cause:l}))}finally{i.removeEventListener("abort",c)}return s?.type==="oauth"?s:void 0}async function ZAn(e,t,n,r,i,s){let o=Math.max(YAn,s??0),c=a(u=>Date.now()+o>=u.expires,"expiresSoon"),l=r;if(c(l)){let u=await cbe(e,t,n,c,i);if(!u)return;if(l=u,s!==void 0&&c(l))throw new as("oauth",`OAuth refresh returned a token that expires too soon for ${t}`)}try{return{auth:await n.toAuth(l),source:"OAuth"}}catch(u){throw new as("oauth",`OAuth auth derivation failed for ${t}`,{cause:u})}}async function obe(e,t,n,r,i){try{return await t.resolve({ctx:e,credential:r,signal:i})}catch(s){throw new as("auth",`API key auth failed for provider ${n}`,{cause:s})}}async function eIn(e,t,n){try{return await e.read(t,{signal:n})}catch(r){throw new as("auth",`Credential store read failed for ${t}`,{cause:r})}}var YAn,XAn,uat=q(()=>{ZV();nK();nK();a(abe,"resolveProviderAuth");a(QAn,"resolveProviderAuthWithSignal");a(JAn,"overlayEnvAuthContext");YAn=300*1e3,XAn=15e3;a(cbe,"refreshStoredOAuthCredential");a(ZAn,"resolveStoredOAuth");a(obe,"resolveApiKey");a(eIn,"readCredential")});var rK,dat=q(()=>{rK=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 PR(e){return e.type??"chat"}function Ig(e,t){return PR(e)===t}function pat(e){if(!Ig(e,"chat"))throw new as("provider",`Model ${e.provider}/${e.id} is not a chat model`)}function hat(e){if(!Ig(e,"image"))throw new as("provider",`Model ${e.provider}/${e.id} is not an image model`)}function mat(e){if(!Ig(e,"classifier"))throw new as("provider",`Model ${e.provider}/${e.id} is not a classifier model`)}function fat(e,t){if(t.images?.length&&!e.input.includes("image"))throw new as("provider",`Model ${e.provider}/${e.id} does not accept image input`)}function lbe(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 ube(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 dbe=q(()=>{nK();a(PR,"getModelType");a(Ig,"isModelType");a(pat,"assertChatModel");a(hat,"assertImageModel");a(mat,"assertClassifierModel");a(fat,"assertClassifierInputSupported");a(lbe,"imageErrorResult");a(ube,"classifierErrorResult")});function iK(e,t=`
|
|
169
169
|
`){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join(t)}function du(e){let t=[iK(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,12 +8543,12 @@ 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(L3t,"pageStyles");VO();var T8e="enabled",A8e=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")}),x$=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")}),I8e=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===T8e?"available":"needs-binding","probe")}),dEr=Object.freeze([I8e,x$,A8e]);function R8e(e,t=dEr){return t.filter(n=>n.probe(e)==="available")}a(R8e,"availableEdgeRuntimeProviders");function C8e(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(C8e,"resolveEdgeRuntimeSelection");function wne(e){let t=R8e(e),{bash:n,container:r}=C8e(t);return t.find(i=>i.id===(r??n)).shell}a(wne,"resolveEdgeRuntimeShell");function pEr(){return"dsh-edge@0.
|
|
8546
|
+
`}a(L3t,"pageStyles");VO();var T8e="enabled",A8e=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")}),x$=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")}),I8e=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===T8e?"available":"needs-binding","probe")}),dEr=Object.freeze([I8e,x$,A8e]);function R8e(e,t=dEr){return t.filter(n=>n.probe(e)==="available")}a(R8e,"availableEdgeRuntimeProviders");function C8e(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(C8e,"resolveEdgeRuntimeSelection");function wne(e){let t=R8e(e),{bash:n,container:r}=C8e(t);return t.find(i=>i.id===(r??n)).shell}a(wne,"resolveEdgeRuntimeShell");function pEr(){return"dsh-edge@0.34.0/direct"}a(pEr,"resolveEdgeDeploymentId");function iT(e){return{baseURL:NIe(e.DEEPSEEK_BASE_URL),maxTokens:$Ie(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:kE(e.DEEPSEEK_MODEL),reasoningEffort:LIe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:CD(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:DIe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Xk(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(iT,"resolveEdgeDeploymentConfig");function hEr(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(hEr,"edgeDeploymentApiKeyConfigured");function mEr(e){let t=NIe(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(mEr,"projectedEdgeBaseURL");function P8e(e,t){return{shell:wne(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:pEr(),apiKeyConfigured:hEr(e),baseURL:mEr(e.DEEPSEEK_BASE_URL),maxTokens:$Ie(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:kE(e.DEEPSEEK_MODEL),reasoningEffort:LIe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:CD(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:DIe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Xk(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(P8e,"resolveEdgeDeploymentProfile");function kne(e){iT(e);let t=P8e(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:B2,upstreamVersion:eXe,status:"ready"}}a(kne,"resolveEdgeDeploymentHealth");var O8e={scanned:1e3,deleted:200};function D3t(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):gEr(n),c=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 > ?
|
|
8550
8550
|
ORDER BY b.hash
|
|
8551
|
-
LIMIT ?`,o,O8e.scanned).toArray(),l=t-864e5,u=0,d=0,p=0;for(let m of c){let f=m.used===0&&m.last_seen<l;if(f&&u>=O8e.deleted)break;p++,f&&(e.transactionSync(()=>{r.exec("DELETE FROM vfs_blob_bytes WHERE hash = ?",m.hash),r.exec("DELETE FROM vfs_blobs WHERE hash = ?",m.hash)}),u++,d+=m.size)}return c.length<O8e.scanned&&p===c.length?{deleted:u,bytes:d,complete:!0}:{deleted:u,bytes:d,cursor:fEr(c[p-1].hash),complete:!1}}a(D3t,"reclaimUnreferencedBlobs");function fEr(e){return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}a(fEr,"bytesToHex");function gEr(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return t}a(gEr,"hexToBytes");import{AsyncLocalStorage as wLr}from"node:async_hooks";function $3t(e){let{intervalMs:t,ping:n,onFailure:r}=e,i=!1,s=setInterval(()=>{i||n().catch(o=>{i||(i=!0,clearInterval(s),r(o instanceof Error?o:new Error(String(o))))})},t);return()=>{i||(i=!0,clearInterval(s))}}a($3t,"startHeartbeat");import{RpcTarget as yEr}from"cloudflare:workers";async function vEr(e,t){let n=AbortSignal.timeout(t.timeoutMs),r=await e.fetchPort(t.port,`http://container${t.path}`,{method:"HEAD",signal:n});if(r.body?.cancel(),!r.ok)throw new Error(`computerd health returned ${r.status}`)}a(vEr,"probeComputerdHealth");var xEr="computer.internal",bEr="/health",M8e="/api",wEr=8080,kEr=3e4,SEr=2e4,_Er=1,EEr=2e3,TEr=250,AEr=2e3;function IEr(e,t){if(t===void 0||e===null)return!1;let n=e.indexOf(" ");if(n===-1||e.slice(0,n).toLowerCase()!=="bearer")return!1;let r=e.slice(n+1).trim();if(r.length!==t.length)return!1;let i=0;for(let s=0;s<t.length;s+=1)i|=r.charCodeAt(s)^t.charCodeAt(s);return i===0}a(IEr,"bearerMatches");var _ne=class{static{a(this,"LegacyContainerBackend")}type="cloudflare-container";id;#e;#n;#r;#t;#i;#s;#o;#u;constructor(e){this.id=e.id??"container-shell",this.#n=e.egress??{mode:"none"},this.#r=this.#n.mode==="http-gateway"?crypto.randomUUID():void 0,this.#e={container:e.container,workspace:e.workspace,containerEnv:e.containerEnv,egressHost:e.egressHost??xEr,containerPort:e.containerPort??wEr,connectTimeoutMs:e.connectTimeoutMs??kEr,heartbeatIntervalMs:e.heartbeatIntervalMs??SEr,restartAttempts:e.restartAttempts??_Er,healthProbeTimeoutMs:e.healthProbeTimeoutMs??EEr,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??TEr,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??AEr}}async connect(){if(this.#u)return this.#u;let e=Date.now()+this.#e.connectTimeoutMs,t=await(await this.#e.container()).getWorkspaceContainer(),n=await t.exitInfo().catch(()=>null),r={PORT:String(this.#e.containerPort),MOUNT_POINT:wNe,...this.#e.containerEnv},i,s;try{({runtimeId:i,clientSecret:s}=await t.start({env:r,enableInternet:this.#n.mode==="direct"}))}catch(p){throw new fd(this.#h("start",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}try{await t.interceptOutboundHttp(this.#e.egressHost,this.#e.workspace),this.#n.mode==="http-gateway"&&this.#r!==void 0&&await t.interceptAllOutboundHttp(this.#e.workspace,this.#r)}catch(p){throw new fd(this.#h("egress",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}this.#t=s,this.#c(),i=await this.#p(t,r,e,n,i),await this.#l(t,e),await this.#f(t,e,s);let o=await this.#d(e),c=Kie(o),l,u=new Promise(p=>{let h=!1,m=a(()=>{h||(h=!0,l?.(),p(),this.#u=void 0)},"onClose");o.addEventListener("close",m,{once:!0}),o.addEventListener("error",m,{once:!0}),c.onRpcBroken(m)});this.#e.heartbeatIntervalMs>0&&(l=$3t({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>c.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:c,runtimeId:i,closed:u,close:a(async()=>{l?.();try{c[Symbol.dispose]?.()}catch{}try{o.close()}catch{}this.#u=void 0},"close")};return this.#u=d,d}async handleFetch(e){if(this.#n.mode==="http-gateway"&&this.#r!==void 0&&e.headers.get("x-workspace-egress-token")===this.#r){let i=new Headers(e.headers),s=i.get(B3),o;try{o=new URL(s??"")}catch{return new Response("invalid egress URL",{status:400})}if(o.protocol!=="http:"&&o.protocol!=="https:")return new Response("invalid egress URL",{status:400});i.delete(OU),i.delete(B3);let c=new Request(e,{headers:i});return this.#n.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==M8e)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${M8e} requires a websocket upgrade`,{status:400});if(!IEr(e.headers.get("authorization"),this.#t))return new Response("unauthorized",{status:401,headers:{"www-authenticate":"Bearer"}});let t=new WebSocketPair,[n,r]=[t[0],t[1]];if(r.accept(),this.#s)this.#s(r);else return r.close(1011,"no pending connect"),new Response("no pending connect",{status:409});return new Response(null,{status:101,webSocket:n})}#c(){this.#i=new Promise((e,t)=>{this.#s=e,this.#o=t}),this.#i.catch(()=>{})}#a(){this.#i=void 0,this.#s=void 0,this.#o=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,o=Math.max(0,n-Date.now()),c=Math.max(250,Math.floor(o/s)),l=0,u=0,d,p=i;for(;l<s;){l++;let h=Math.min(n,Date.now()+c);if(await this.#m(e,h).then(()=>!0,m=>(d=m,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#n.mode==="direct"})),u++}catch(m){throw this.#o?.(m),this.#a(),new fd(this.#h("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:m}),{cause:m})}}throw this.#o?.(new Error("computerd never became healthy")),this.#a(),new fd(this.#h("health",{attempt:l,maxAttempts:s,restarts:u,lastError:d,priorExit:r}),d instanceof Error?{cause:d}:void 0)}async#m(e,t){let n=this.#e.healthRetryInitialDelayMs,r;for(;Date.now()<t;)try{await vEr(e,{port:this.#e.containerPort,path:"/health",timeoutMs:Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now()))});return}catch(i){r=i;let s=t-Date.now();if(s<=0)break;await REr(Math.min(n,s)),n=Math.min(n*2,this.#e.healthRetryMaxDelayMs)}throw r??new Error("computerd health probe timed out")}#h(e,t){let n=t.priorExit?` priorExit=${JSON.stringify(t.priorExit.reason)}`:"";return`LegacyContainerBackend(${this.id}): connect failed at stage=${e} port=${this.#e.containerPort} attempt=${t.attempt}/${t.maxAttempts} restarts=${t.restarts} timeoutMs=${this.#e.connectTimeoutMs}${n} lastError=${U3t(t.lastError)}`}async#l(e,t){let n;try{let r=await e.fetchPort(this.#e.containerPort,"http://container/api",{signal:AbortSignal.timeout(Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now())))});n=r.status,await r.text().catch(()=>"")}catch{return}if(n!==401)throw this.#o?.(new Error("container is not enforcing RPC_CLIENT_SECRET")),this.#a(),new fd(`LegacyContainerBackend(${this.id}) [stage=auth]: container served an unauthenticated request to /api with ${n}, so this workspace would run without authorization. A container or image predating RPC_CLIENT_SECRET has to be recycled.`)}async#f(e,t,n){let r=Math.max(0,t-Date.now()),i;try{i=await e.fetchPort(this.#e.containerPort,"http://container/connect",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({base:`http://${this.#e.egressHost}`,health:bEr,api:M8e,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new fd(`LegacyContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${U3t(s)}`,{cause:s})}if(!i.ok){let s=await i.text().catch(()=>""),o=new Error(`/connect ${i.status}`);throw this.#o?.(o),this.#a(),new fd(`LegacyContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#d(e){let t=this.#i;if(!t)throw new Error("LegacyContainerBackend: upgrade promise missing");let n=Math.max(0,e-Date.now()),r;try{return await Promise.race([t,new Promise((i,s)=>{r=setTimeout(()=>s(new fd(`LegacyContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#a()}}};function REr(e){return new Promise(t=>setTimeout(t,e))}a(REr,"sleep");function U3t(e){return e instanceof Error?e.message:String(e)}a(U3t,"describeError");var F3t="computer:container-client-secret",CEr=16;function PEr(){let e=crypto.getRandomValues(new Uint8Array(CEr));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(PEr,"generate");var OEr=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(F3t);if(typeof e=="string"&&e.length>0)return e;let t=PEr();return await this.storage.put(F3t,t),t}},j3t="computer:container-launch-record";async function q3t(e){return{enableInternet:e.enableInternet,envDigest:await NEr(e.env)}}a(q3t,"launchRecordFor");function MEr(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(MEr,"sameLaunch");async function NEr(e){let t=Object.keys(e).sort().map(r=>`${r.length}:${r}=${e[r]?.length??0}:${e[r]??""}`).join(";"),n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}a(NEr,"digestEnv");var LEr=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(j3t)??null}async set(e){await this.storage.put(j3t,e)}},W3t=new WeakMap;function D8e(e){let t=W3t.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},W3t.set(e,t)),t}a(D8e,"getContainerLifecycle");function Sne(e){return D8e(e).exit}a(Sne,"containerExitInfo");function B3t(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(B3t,"formatExitReason");function z3t(e,t,n){let r=D8e(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>H3t(r,i,void 0,n),s=>H3t(r,i,s,n))}a(z3t,"installContainerMonitor");async function N8e(e,t){let n=D8e(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(N8e,"destroyContainerExpectingExit");async function H3t(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=B3t(n),o=Date.now();e.exit={reason:s,exitedAt:o},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!1});try{await r?.()}catch(c){console.error({message:"workspace.container.exit_cleanup_failed",reason:B3t(c),exitedAt:Date.now()})}}a(H3t,"recordExit");var L8e="computer:container-runtime-identity",DEr=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(L8e)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(L8e,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(L8e)}},$Er=class extends yEr{static{a(this,"LegacyWorkspaceContainerAPI")}#e;#n;#r;#t;#i;constructor(e){if(super(),!e.container)throw new Error("LegacyWorkspaceContainerAPI: DO is not container-enabled (check wrangler.jsonc)");this.#e=e.container,this.#n=e,this.#r=new DEr(e.storage),this.#t=new OEr(e.storage),this.#i=new LEr(e.storage)}async start(e){let t=Sne(this.#n),n=await this.#t.ensure(),r=await q3t(e);if(t!==null){try{await N8e(this.#n,this.#e)}catch{}return this.#s(e,n,r,"launched")}if(!this.#e.running)return this.#s(e,n,r,"launched");let i=await this.#i.get();if(i===null||!MEr(i,r)){console.warn({message:i===null?"container was started outside LegacyWorkspaceContainerAPI; relaunching so the requested environment applies":"running container was launched with a different spec; relaunching",component:"workspace-container",requested:r,actual:i});try{await N8e(this.#n,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return z3t(this.#n,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await N8e(this.#n,this.#e)}catch{}let t=await this.#t.ensure();return this.#s(e,t,await q3t(e),"launched")}async setInactivityTimeout(e){await this.#e.setInactivityTimeout(e)}async#s(e,t,n,r){let i=await this.#r.markStarted();try{this.#e.start({enableInternet:e.enableInternet,env:{...e.env,RPC_CLIENT_SECRET:t}})}catch(s){throw await this.#r.clear(i),s}return await this.#i.set(n),z3t(this.#n,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:Sne(this.#n)}}async exitInfo(){return Sne(this.#n)}async interceptAllOutboundHttp(e,t){let n=this.#n.exports.WorkspaceProxy({props:{...W3(e,this.#n),egressToken:t}});await Promise.all([this.#e.interceptAllOutboundHttp(n),this.#e.interceptOutboundHttps("*",n)])}async interceptOutboundHttp(e,t){let n=this.#n.exports;await this.#e.interceptOutboundHttp(e,n.WorkspaceProxy({props:W3(t,this.#n)}))}fetchPort(e,t,n){let r=Sne(this.#n);if(r!==null)throw new fd(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function G3t(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new $Er(this.ctx)}}return t}a(G3t,"withLegacyWorkspaceContainer");var UEr={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function K3t(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),o=t.slice(i+1),c=UEr[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(K3t,"resolve");function FEr(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(FEr,"errorResponse");async function $8e(e,t,n,r,i){let s=K3t(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a($8e,"callEdgeApi");async function Q3t(e,t){let r=new URL(t.url).pathname;if(t.method!=="POST"||!r.startsWith("/api/"))return new Response("not found",{status:404});if(r==="/api/respond")return Response.json({accepted:!1,reason:"not-pending"});let i=r.slice(5);if(K3t(e,i)===void 0)return new Response("not found",{status:404});let s;try{s=await t.json()}catch{return new Response("body is not JSON",{status:400})}let o=typeof s.rpcId=="string"?s.rpcId:"invalid-request",c=s.payload??{};try{let l=await $8e(e,i,o,c,t.signal);return l===void 0?new Response("not found",{status:404}):Response.json({type:"server-response",rpcId:l.rpcId,result:l.result})}catch(l){return FEr(o,{code:"gateway/internal",message:String(l),details:{}})}}a(Q3t,"dispatchEdgeApi");Ur();vo();ev();import{DurableObject as kLr}from"cloudflare:workers";var Ene=class{constructor(t,n=Date.now,r=2){this.sleepAfterMs=t;this.now=n;this.maxConcurrent=r}sleepAfterMs;now;maxConcurrent;static{a(this,"ContainerActivity")}inFlight=0;lastActivity;stopping;waiters=[];async admit(t){let n=this.now();for(;this.stopping!==void 0||this.inFlight>=this.maxConcurrent;){if(t?.throwIfAborted(),this.stopping!==void 0){await jEr(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let c=this.waiters.indexOf(s);c!==-1&&this.waiters.splice(c,1),i(t.reason)},"abort");this.waiters.push(s),t?.addEventListener("abort",o,{once:!0})})}return t?.aborted===!0&&(this.waiters.shift()?.(),t.throwIfAborted()),{release:this.begin(),queuedMs:this.now()-n}}begin(){this.inFlight+=1,this.lastActivity=this.now();let t=!1;return()=>{t||(t=!0,this.inFlight-=1,this.lastActivity=this.now(),this.waiters.shift()?.())}}async stopIfIdle(t){return this.idle()?await this.stop(t):"busy"}async stopNow(t){return this.inFlight===0?await this.stop(t):"busy"}snapshot(){return{runningCommands:this.inFlight,lastActivityAt:this.lastActivity??null}}async stop(t){if(this.stopping!==void 0)return"busy";let n="stopped",r=t().catch(i=>{n="failed",this.lastActivity=this.now(),console.error("dsh-edge container stop failed.",i)});this.stopping=r;try{await r}finally{this.stopping=void 0}return n}deadline(){return this.inFlight>0?this.now()+this.sleepAfterMs():this.lastActivity===void 0?this.now():this.lastActivity+this.sleepAfterMs()}idle(){return this.inFlight===0&&(this.lastActivity===void 0||this.now()>=this.lastActivity+this.sleepAfterMs())}};function jEr(e,t){return t===void 0?e:new Promise((n,r)=>{let i=a(()=>r(t.reason),"abort");t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",i))})}a(jEr,"untilAborted");import{WorkerEntrypoint as Kxs}from"cloudflare:workers";var LT=el(J3t());import{gunzipSync as qAr}from"node:zlib";import{constants as L7e,gunzipSync as C5r,gzipSync as P5r}from"node:zlib";var qEr=Object.create,mMe=Object.defineProperty,WEr=Object.getOwnPropertyDescriptor,BEr=Object.getOwnPropertyNames,zEr=Object.getPrototypeOf,HEr=Object.prototype.hasOwnProperty,De=a((e,t)=>()=>(e&&(t=e(e=0)),t),"L"),Fre=a((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"Jo"),En=a((e,t)=>{for(var n in t)mMe(e,n,{get:t[n],enumerable:!0})},"ae"),GEr=a((e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of BEr(t))!HEr.call(e,i)&&i!==n&&mMe(e,i,{get:a(()=>t[i],"get"),enumerable:!(r=WEr(t,i))||r.enumerable});return e},"_3"),GMt=a((e,t,n)=>(n=e!=null?qEr(zEr(e)):{},GEr(t||!e||!e.__esModule?mMe(n,"default",{value:e,enumerable:!0}):n,e)),"Vp"),VMt={};En(VMt,{AsyncLocalStorage:a(()=>QMt,"AsyncLocalStorage"),Module:a(()=>JMt,"Module"),lookup:a(()=>KMt,"lookup")});function KMt(){throw new Error("node:dns is not available in browser environments")}a(KMt,"kc");var QMt,JMt,tOe=De(()=>{"use strict";QMt=void 0,JMt=void 0});function VEr(){return nOe||YMt(),nOe}a(VEr,"Gp");function YMt(){let e=[{prop:"Function",target:globalThis,violationType:"function_constructor",strategy:"throw",reason:"Function constructor allows arbitrary code execution"},{prop:"eval",target:globalThis,violationType:"eval",strategy:"throw",reason:"eval() allows arbitrary code execution"},{prop:"setTimeout",target:globalThis,violationType:"setTimeout",strategy:"throw",reason:"setTimeout with string argument allows code execution"},{prop:"setInterval",target:globalThis,violationType:"setInterval",strategy:"throw",reason:"setInterval with string argument allows code execution"},{prop:"setImmediate",target:globalThis,violationType:"setImmediate",strategy:"throw",reason:"setImmediate could be used to escape sandbox context"},{prop:"env",target:process,violationType:"process_env",strategy:"throw",reason:"process.env could leak sensitive environment variables",allowedKeys:new Set(["NODE_V8_COVERAGE","NODE_DEBUG","NODE_DEBUG_NATIVE","NODE_COMPILE_CACHE","NODE_ENV","WATCH_REPORT_DEPENDENCIES","FORCE_COLOR","DEBUG","UNDICI_NO_FG","JEST_WORKER_ID","__MINIMATCH_TESTING_PLATFORM__","LOG_TOKENS","LOG_STREAM"])},{prop:"binding",target:process,violationType:"process_binding",strategy:"throw",reason:"process.binding provides access to native Node.js modules"},{prop:"_linkedBinding",target:process,violationType:"process_binding",strategy:"throw",reason:"process._linkedBinding provides access to native Node.js modules"},{prop:"dlopen",target:process,violationType:"process_dlopen",strategy:"throw",reason:"process.dlopen allows loading native addons"},{prop:"getBuiltinModule",target:process,violationType:"process_get_builtin_module",strategy:"throw",reason:"process.getBuiltinModule allows loading native Node.js modules (fs, child_process, vm)"},{prop:"exit",target:process,violationType:"process_exit",strategy:"throw",reason:"process.exit could terminate the interpreter"},{prop:"abort",target:process,violationType:"process_exit",strategy:"throw",reason:"process.abort could crash the interpreter"},{prop:"kill",target:process,violationType:"process_kill",strategy:"throw",reason:"process.kill could signal other processes"},{prop:"setuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setuid could escalate privileges"},{prop:"setgid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgid could escalate privileges"},{prop:"seteuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.seteuid could escalate effective user privileges"},{prop:"setegid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setegid could escalate effective group privileges"},{prop:"initgroups",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.initgroups could modify supplementary group IDs"},{prop:"setgroups",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgroups could modify supplementary group IDs"},{prop:"umask",target:process,violationType:"process_umask",strategy:"throw",reason:"process.umask could modify file creation permissions"},{prop:"argv",target:process,violationType:"process_argv",strategy:"throw",reason:"process.argv may contain secrets in CLI arguments"},{prop:"cwd",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.cwd could disclose real host working directory path"},{prop:"chdir",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.chdir could confuse the interpreter's CWD tracking"},{prop:"report",target:process,violationType:"process_report",strategy:"throw",reason:"process.report could disclose full environment, host paths, and system info"},{prop:"loadEnvFile",target:process,violationType:"process_env",strategy:"throw",reason:"process.loadEnvFile could load env files bypassing env proxy"},{prop:"setUncaughtExceptionCaptureCallback",target:process,violationType:"process_exception_handler",strategy:"throw",reason:"setUncaughtExceptionCaptureCallback could intercept security errors"},...["on","once","addListener","prependListener","prependOnceListener"].map(n=>({prop:n,target:process,violationType:"process_exception_handler",strategy:"throw",reason:"process-global listeners can outlive the sandbox and lose its security context"})),{prop:"send",target:process,violationType:"process_send",strategy:"throw",reason:"process.send could communicate with parent process in IPC contexts"},{prop:"channel",target:process,violationType:"process_channel",strategy:"throw",reason:"process.channel could access IPC channel to parent process"},{prop:"cpuUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.cpuUsage could enable timing side-channel attacks"},{prop:"memoryUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.memoryUsage could enable timing side-channel attacks"},{prop:"hrtime",target:process,violationType:"process_timing",strategy:"throw",reason:"process.hrtime could enable timing side-channel attacks"},{prop:"WeakRef",target:globalThis,violationType:"weak_ref",strategy:"throw",reason:"WeakRef could be used to leak references outside sandbox"},{prop:"FinalizationRegistry",target:globalThis,violationType:"finalization_registry",strategy:"throw",reason:"FinalizationRegistry could be used to leak references outside sandbox"},{prop:"Reflect",target:globalThis,violationType:"reflect",strategy:"freeze",reason:"Reflect provides introspection capabilities"},{prop:"Proxy",target:globalThis,violationType:"proxy",strategy:"throw",reason:"Proxy allows intercepting and modifying object behavior"},{prop:"WebAssembly",target:globalThis,violationType:"webassembly",strategy:"throw",reason:"WebAssembly allows executing arbitrary compiled code"},{prop:"SharedArrayBuffer",target:globalThis,violationType:"shared_array_buffer",strategy:"throw",reason:"SharedArrayBuffer could enable side-channel communication or timing attacks"},{prop:"Atomics",target:globalThis,violationType:"atomics",strategy:"throw",reason:"Atomics could enable side-channel communication or timing attacks"},{prop:"performance",target:globalThis,violationType:"performance_timing",strategy:"throw",reason:"performance.now() provides sub-millisecond timing for side-channel attacks"},{prop:"stdout",target:process,violationType:"process_stdout",strategy:"throw",reason:"process.stdout could bypass interpreter output to write to host stdout"},{prop:"stderr",target:process,violationType:"process_stderr",strategy:"throw",reason:"process.stderr could bypass interpreter output to write to host stderr"},{prop:"__defineGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineGetter__ allows prototype pollution via getter injection"},{prop:"__defineSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineSetter__ allows prototype pollution via setter injection"},{prop:"__lookupGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupGetter__ enables introspection for prototype pollution attacks"},{prop:"__lookupSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupSetter__ enables introspection for prototype pollution attacks"},{prop:"JSON",target:globalThis,violationType:"json_mutation",strategy:"freeze",reason:"Freeze JSON to prevent mutation of parsing/serialization"},{prop:"Math",target:globalThis,violationType:"math_mutation",strategy:"freeze",reason:"Freeze Math to prevent mutation of math utilities"}];try{let n=Object.getPrototypeOf(async()=>{}).constructor;n&&n!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(async()=>{}),violationType:"async_function_constructor",strategy:"throw",reason:"AsyncFunction constructor allows arbitrary async code execution"})}catch{}try{let n=Object.getPrototypeOf(function*(){}).constructor;n&&n!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(function*(){}),violationType:"generator_function_constructor",strategy:"throw",reason:"GeneratorFunction constructor allows arbitrary generator code execution"})}catch{}try{let n=Object.getPrototypeOf(async function*(){}).constructor;n&&n!==Function&&n!==Object.getPrototypeOf(async()=>{}).constructor&&e.push({prop:"constructor",target:Object.getPrototypeOf(async function*(){}),violationType:"async_generator_function_constructor",strategy:"throw",reason:"AsyncGeneratorFunction constructor allows arbitrary async generator code execution"})}catch{}let t=e.filter(n=>{try{return n.target[n.prop]!==void 0}catch{return!1}});return nOe??=new Set(t.map(({violationType:n})=>n)),t}a(YMt,"Ic");var nOe,KEr=De(()=>{"use strict"});function QEr(){return Math.floor(XMt+ZMt())}a(QEr,"Zp");var XMt,ZMt,JEr=De(()=>{"use strict";XMt=performance.timeOrigin,ZMt=performance.now.bind(performance)});function YEr(e){let t=e?.find(n=>fMe.has(n));if(t)throw new RangeError(`defenseInDepth.excludeViolationTypes cannot disable the non-excludable "${t}" protection`)}a(YEr,"Xp");function XEr(e,t,n){let r=n&&!fMe.has(t)?`
|
|
8551
|
+
LIMIT ?`,o,O8e.scanned).toArray(),l=t-864e5,u=0,d=0,p=0;for(let m of c){let f=m.used===0&&m.last_seen<l;if(f&&u>=O8e.deleted)break;p++,f&&(e.transactionSync(()=>{r.exec("DELETE FROM vfs_blob_bytes WHERE hash = ?",m.hash),r.exec("DELETE FROM vfs_blobs WHERE hash = ?",m.hash)}),u++,d+=m.size)}return c.length<O8e.scanned&&p===c.length?{deleted:u,bytes:d,complete:!0}:{deleted:u,bytes:d,cursor:fEr(c[p-1].hash),complete:!1}}a(D3t,"reclaimUnreferencedBlobs");function fEr(e){return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}a(fEr,"bytesToHex");function gEr(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return t}a(gEr,"hexToBytes");import{AsyncLocalStorage as wLr}from"node:async_hooks";function $3t(e){let{intervalMs:t,ping:n,onFailure:r}=e,i=!1,s=setInterval(()=>{i||n().catch(o=>{i||(i=!0,clearInterval(s),r(o instanceof Error?o:new Error(String(o))))})},t);return()=>{i||(i=!0,clearInterval(s))}}a($3t,"startHeartbeat");import{RpcTarget as yEr}from"cloudflare:workers";async function vEr(e,t){let n=AbortSignal.timeout(t.timeoutMs),r=await e.fetchPort(t.port,`http://container${t.path}`,{method:"HEAD",signal:n});if(r.body?.cancel(),!r.ok)throw new Error(`computerd health returned ${r.status}`)}a(vEr,"probeComputerdHealth");var xEr="computer.internal",bEr="/health",M8e="/api",wEr=8080,kEr=3e4,SEr=2e4,_Er=1,EEr=2e3,TEr=250,AEr=2e3;function IEr(e,t){if(t===void 0||e===null)return!1;let n=e.indexOf(" ");if(n===-1||e.slice(0,n).toLowerCase()!=="bearer")return!1;let r=e.slice(n+1).trim();if(r.length!==t.length)return!1;let i=0;for(let s=0;s<t.length;s+=1)i|=r.charCodeAt(s)^t.charCodeAt(s);return i===0}a(IEr,"bearerMatches");var _ne=class{static{a(this,"LegacyContainerBackend")}type="cloudflare-container";id;#e;#n;#r;#t;#i;#s;#o;#u;constructor(e){this.id=e.id??"container-shell",this.#n=e.egress??{mode:"none"},this.#r=this.#n.mode==="http-gateway"?crypto.randomUUID():void 0,this.#e={container:e.container,workspace:e.workspace,containerEnv:e.containerEnv,egressHost:e.egressHost??xEr,containerPort:e.containerPort??wEr,connectTimeoutMs:e.connectTimeoutMs??kEr,heartbeatIntervalMs:e.heartbeatIntervalMs??SEr,restartAttempts:e.restartAttempts??_Er,healthProbeTimeoutMs:e.healthProbeTimeoutMs??EEr,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??TEr,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??AEr}}async connect(){if(this.#u)return this.#u;let e=Date.now()+this.#e.connectTimeoutMs,t=await(await this.#e.container()).getWorkspaceContainer(),n=await t.exitInfo().catch(()=>null),r={PORT:String(this.#e.containerPort),MOUNT_POINT:wNe,...this.#e.containerEnv},i,s;try{({runtimeId:i,clientSecret:s}=await t.start({env:r,enableInternet:this.#n.mode==="direct"}))}catch(p){throw new fd(this.#h("start",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}try{await t.interceptOutboundHttp(this.#e.egressHost,this.#e.workspace),this.#n.mode==="http-gateway"&&this.#r!==void 0&&await t.interceptAllOutboundHttp(this.#e.workspace,this.#r)}catch(p){throw new fd(this.#h("egress",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}this.#t=s,this.#c(),i=await this.#p(t,r,e,n,i),await this.#l(t,e),await this.#f(t,e,s);let o=await this.#d(e),c=Kie(o),l,u=new Promise(p=>{let h=!1,m=a(()=>{h||(h=!0,l?.(),p(),this.#u=void 0)},"onClose");o.addEventListener("close",m,{once:!0}),o.addEventListener("error",m,{once:!0}),c.onRpcBroken(m)});this.#e.heartbeatIntervalMs>0&&(l=$3t({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>c.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:c,runtimeId:i,closed:u,close:a(async()=>{l?.();try{c[Symbol.dispose]?.()}catch{}try{o.close()}catch{}this.#u=void 0},"close")};return this.#u=d,d}async handleFetch(e){if(this.#n.mode==="http-gateway"&&this.#r!==void 0&&e.headers.get("x-workspace-egress-token")===this.#r){let i=new Headers(e.headers),s=i.get(B3),o;try{o=new URL(s??"")}catch{return new Response("invalid egress URL",{status:400})}if(o.protocol!=="http:"&&o.protocol!=="https:")return new Response("invalid egress URL",{status:400});i.delete(OU),i.delete(B3);let c=new Request(e,{headers:i});return this.#n.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==M8e)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${M8e} requires a websocket upgrade`,{status:400});if(!IEr(e.headers.get("authorization"),this.#t))return new Response("unauthorized",{status:401,headers:{"www-authenticate":"Bearer"}});let t=new WebSocketPair,[n,r]=[t[0],t[1]];if(r.accept(),this.#s)this.#s(r);else return r.close(1011,"no pending connect"),new Response("no pending connect",{status:409});return new Response(null,{status:101,webSocket:n})}#c(){this.#i=new Promise((e,t)=>{this.#s=e,this.#o=t}),this.#i.catch(()=>{})}#a(){this.#i=void 0,this.#s=void 0,this.#o=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,o=Math.max(0,n-Date.now()),c=Math.max(250,Math.floor(o/s)),l=0,u=0,d,p=i;for(;l<s;){l++;let h=Math.min(n,Date.now()+c);if(await this.#m(e,h).then(()=>!0,m=>(d=m,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#n.mode==="direct"})),u++}catch(m){throw this.#o?.(m),this.#a(),new fd(this.#h("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:m}),{cause:m})}}throw this.#o?.(new Error("computerd never became healthy")),this.#a(),new fd(this.#h("health",{attempt:l,maxAttempts:s,restarts:u,lastError:d,priorExit:r}),d instanceof Error?{cause:d}:void 0)}async#m(e,t){let n=this.#e.healthRetryInitialDelayMs,r;for(;Date.now()<t;)try{await vEr(e,{port:this.#e.containerPort,path:"/health",timeoutMs:Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now()))});return}catch(i){r=i;let s=t-Date.now();if(s<=0)break;await REr(Math.min(n,s)),n=Math.min(n*2,this.#e.healthRetryMaxDelayMs)}throw r??new Error("computerd health probe timed out")}#h(e,t){let n=t.priorExit?` priorExit=${JSON.stringify(t.priorExit.reason)}`:"";return`LegacyContainerBackend(${this.id}): connect failed at stage=${e} port=${this.#e.containerPort} attempt=${t.attempt}/${t.maxAttempts} restarts=${t.restarts} timeoutMs=${this.#e.connectTimeoutMs}${n} lastError=${U3t(t.lastError)}`}async#l(e,t){let n;try{let r=await e.fetchPort(this.#e.containerPort,"http://container/api",{signal:AbortSignal.timeout(Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now())))});n=r.status,await r.text().catch(()=>"")}catch{return}if(n!==401)throw this.#o?.(new Error("container is not enforcing RPC_CLIENT_SECRET")),this.#a(),new fd(`LegacyContainerBackend(${this.id}) [stage=auth]: container served an unauthenticated request to /api with ${n}, so this workspace would run without authorization. A container or image predating RPC_CLIENT_SECRET has to be recycled.`)}async#f(e,t,n){let r=Math.max(0,t-Date.now()),i;try{i=await e.fetchPort(this.#e.containerPort,"http://container/connect",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({base:`http://${this.#e.egressHost}`,health:bEr,api:M8e,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new fd(`LegacyContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${U3t(s)}`,{cause:s})}if(!i.ok){let s=await i.text().catch(()=>""),o=new Error(`/connect ${i.status}`);throw this.#o?.(o),this.#a(),new fd(`LegacyContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#d(e){let t=this.#i;if(!t)throw new Error("LegacyContainerBackend: upgrade promise missing");let n=Math.max(0,e-Date.now()),r;try{return await Promise.race([t,new Promise((i,s)=>{r=setTimeout(()=>s(new fd(`LegacyContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#a()}}};function REr(e){return new Promise(t=>setTimeout(t,e))}a(REr,"sleep");function U3t(e){return e instanceof Error?e.message:String(e)}a(U3t,"describeError");var F3t="computer:container-client-secret",CEr=16;function PEr(){let e=crypto.getRandomValues(new Uint8Array(CEr));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(PEr,"generate");var OEr=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(F3t);if(typeof e=="string"&&e.length>0)return e;let t=PEr();return await this.storage.put(F3t,t),t}},j3t="computer:container-launch-record";async function q3t(e){return{enableInternet:e.enableInternet,envDigest:await NEr(e.env)}}a(q3t,"launchRecordFor");function MEr(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(MEr,"sameLaunch");async function NEr(e){let t=Object.keys(e).sort().map(r=>`${r.length}:${r}=${e[r]?.length??0}:${e[r]??""}`).join(";"),n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}a(NEr,"digestEnv");var LEr=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(j3t)??null}async set(e){await this.storage.put(j3t,e)}},W3t=new WeakMap;function D8e(e){let t=W3t.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},W3t.set(e,t)),t}a(D8e,"getContainerLifecycle");function Sne(e){return D8e(e).exit}a(Sne,"containerExitInfo");function B3t(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(B3t,"formatExitReason");function z3t(e,t,n){let r=D8e(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>H3t(r,i,void 0,n),s=>H3t(r,i,s,n))}a(z3t,"installContainerMonitor");async function N8e(e,t){let n=D8e(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(N8e,"destroyContainerExpectingExit");async function H3t(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=B3t(n),o=Date.now();e.exit={reason:s,exitedAt:o},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!1});try{await r?.()}catch(c){console.error({message:"workspace.container.exit_cleanup_failed",reason:B3t(c),exitedAt:Date.now()})}}a(H3t,"recordExit");var L8e="computer:container-runtime-identity",DEr=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(L8e)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(L8e,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(L8e)}},$Er=class extends yEr{static{a(this,"LegacyWorkspaceContainerAPI")}#e;#n;#r;#t;#i;constructor(e){if(super(),!e.container)throw new Error("LegacyWorkspaceContainerAPI: DO is not container-enabled (check wrangler.jsonc)");this.#e=e.container,this.#n=e,this.#r=new DEr(e.storage),this.#t=new OEr(e.storage),this.#i=new LEr(e.storage)}async start(e){let t=Sne(this.#n),n=await this.#t.ensure(),r=await q3t(e);if(t!==null){try{await N8e(this.#n,this.#e)}catch{}return this.#s(e,n,r,"launched")}if(!this.#e.running)return this.#s(e,n,r,"launched");let i=await this.#i.get();if(i===null||!MEr(i,r)){console.warn({message:i===null?"container was started outside LegacyWorkspaceContainerAPI; relaunching so the requested environment applies":"running container was launched with a different spec; relaunching",component:"workspace-container",requested:r,actual:i});try{await N8e(this.#n,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return z3t(this.#n,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await N8e(this.#n,this.#e)}catch{}let t=await this.#t.ensure();return this.#s(e,t,await q3t(e),"launched")}async setInactivityTimeout(e){await this.#e.setInactivityTimeout(e)}async#s(e,t,n,r){let i=await this.#r.markStarted();try{this.#e.start({enableInternet:e.enableInternet,env:{...e.env,RPC_CLIENT_SECRET:t}})}catch(s){throw await this.#r.clear(i),s}return await this.#i.set(n),z3t(this.#n,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:Sne(this.#n)}}async exitInfo(){return Sne(this.#n)}async interceptAllOutboundHttp(e,t){let n=this.#n.exports.WorkspaceProxy({props:{...W3(e,this.#n),egressToken:t}});await Promise.all([this.#e.interceptAllOutboundHttp(n),this.#e.interceptOutboundHttps("*",n)])}async interceptOutboundHttp(e,t){let n=this.#n.exports;await this.#e.interceptOutboundHttp(e,n.WorkspaceProxy({props:W3(t,this.#n)}))}fetchPort(e,t,n){let r=Sne(this.#n);if(r!==null)throw new fd(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function G3t(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new $Er(this.ctx)}}return t}a(G3t,"withLegacyWorkspaceContainer");var UEr={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function K3t(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),o=t.slice(i+1),c=UEr[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(K3t,"resolve");function FEr(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(FEr,"errorResponse");async function $8e(e,t,n,r,i){let s=K3t(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a($8e,"callEdgeApi");async function Q3t(e,t){let r=new URL(t.url).pathname;if(t.method!=="POST"||!r.startsWith("/api/"))return new Response("not found",{status:404});if(r==="/api/respond")return Response.json({accepted:!1,reason:"not-pending"});let i=r.slice(5);if(K3t(e,i)===void 0)return new Response("not found",{status:404});let s;try{s=await t.json()}catch{return new Response("body is not JSON",{status:400})}let o=typeof s.rpcId=="string"?s.rpcId:"invalid-request",c=s.payload??{};try{let l=await $8e(e,i,o,c,t.signal);return l===void 0?new Response("not found",{status:404}):Response.json({type:"server-response",rpcId:l.rpcId,result:l.result})}catch(l){return FEr(o,{code:"gateway/internal",message:String(l),details:{}})}}a(Q3t,"dispatchEdgeApi");Ur();vo();ev();import{DurableObject as kLr}from"cloudflare:workers";var Ene=class{constructor(t,n=Date.now,r=2){this.sleepAfterMs=t;this.now=n;this.maxConcurrent=r}sleepAfterMs;now;maxConcurrent;static{a(this,"ContainerActivity")}inFlight=0;lastActivity;stopping;waiters=[];async admit(t){let n=this.now();for(;this.stopping!==void 0||this.inFlight>=this.maxConcurrent;){if(t?.throwIfAborted(),this.stopping!==void 0){await jEr(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let c=this.waiters.indexOf(s);c!==-1&&this.waiters.splice(c,1),i(t.reason)},"abort");this.waiters.push(s),t?.addEventListener("abort",o,{once:!0})})}return t?.aborted===!0&&(this.waiters.shift()?.(),t.throwIfAborted()),{release:this.begin(),queuedMs:this.now()-n}}begin(){this.inFlight+=1,this.lastActivity=this.now();let t=!1;return()=>{t||(t=!0,this.inFlight-=1,this.lastActivity=this.now(),this.waiters.shift()?.())}}async stopIfIdle(t){return this.idle()?await this.stop(t):"busy"}async stopNow(t){return this.inFlight===0?await this.stop(t):"busy"}snapshot(){return{runningCommands:this.inFlight,lastActivityAt:this.lastActivity??null}}async stop(t){if(this.stopping!==void 0)return"busy";let n="stopped",r=t().catch(i=>{n="failed",this.lastActivity=this.now(),console.error("dsh-edge container stop failed.",i)});this.stopping=r;try{await r}finally{this.stopping=void 0}return n}deadline(){return this.inFlight>0?this.now()+this.sleepAfterMs():this.lastActivity===void 0?this.now():this.lastActivity+this.sleepAfterMs()}idle(){return this.inFlight===0&&(this.lastActivity===void 0||this.now()>=this.lastActivity+this.sleepAfterMs())}};function jEr(e,t){return t===void 0?e:new Promise((n,r)=>{let i=a(()=>r(t.reason),"abort");t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",i))})}a(jEr,"untilAborted");import{WorkerEntrypoint as Kxs}from"cloudflare:workers";var LT=el(J3t(),1);import{gunzipSync as qAr}from"node:zlib";import{constants as L7e,gunzipSync as C5r,gzipSync as P5r}from"node:zlib";var qEr=Object.create,mMe=Object.defineProperty,WEr=Object.getOwnPropertyDescriptor,BEr=Object.getOwnPropertyNames,zEr=Object.getPrototypeOf,HEr=Object.prototype.hasOwnProperty,De=a((e,t)=>()=>(e&&(t=e(e=0)),t),"L"),Fre=a((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"Jo"),En=a((e,t)=>{for(var n in t)mMe(e,n,{get:t[n],enumerable:!0})},"ae"),GEr=a((e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of BEr(t))!HEr.call(e,i)&&i!==n&&mMe(e,i,{get:a(()=>t[i],"get"),enumerable:!(r=WEr(t,i))||r.enumerable});return e},"_3"),GMt=a((e,t,n)=>(n=e!=null?qEr(zEr(e)):{},GEr(t||!e||!e.__esModule?mMe(n,"default",{value:e,enumerable:!0}):n,e)),"Vp"),VMt={};En(VMt,{AsyncLocalStorage:a(()=>QMt,"AsyncLocalStorage"),Module:a(()=>JMt,"Module"),lookup:a(()=>KMt,"lookup")});function KMt(){throw new Error("node:dns is not available in browser environments")}a(KMt,"kc");var QMt,JMt,tOe=De(()=>{"use strict";QMt=void 0,JMt=void 0});function VEr(){return nOe||YMt(),nOe}a(VEr,"Gp");function YMt(){let e=[{prop:"Function",target:globalThis,violationType:"function_constructor",strategy:"throw",reason:"Function constructor allows arbitrary code execution"},{prop:"eval",target:globalThis,violationType:"eval",strategy:"throw",reason:"eval() allows arbitrary code execution"},{prop:"setTimeout",target:globalThis,violationType:"setTimeout",strategy:"throw",reason:"setTimeout with string argument allows code execution"},{prop:"setInterval",target:globalThis,violationType:"setInterval",strategy:"throw",reason:"setInterval with string argument allows code execution"},{prop:"setImmediate",target:globalThis,violationType:"setImmediate",strategy:"throw",reason:"setImmediate could be used to escape sandbox context"},{prop:"env",target:process,violationType:"process_env",strategy:"throw",reason:"process.env could leak sensitive environment variables",allowedKeys:new Set(["NODE_V8_COVERAGE","NODE_DEBUG","NODE_DEBUG_NATIVE","NODE_COMPILE_CACHE","NODE_ENV","WATCH_REPORT_DEPENDENCIES","FORCE_COLOR","DEBUG","UNDICI_NO_FG","JEST_WORKER_ID","__MINIMATCH_TESTING_PLATFORM__","LOG_TOKENS","LOG_STREAM"])},{prop:"binding",target:process,violationType:"process_binding",strategy:"throw",reason:"process.binding provides access to native Node.js modules"},{prop:"_linkedBinding",target:process,violationType:"process_binding",strategy:"throw",reason:"process._linkedBinding provides access to native Node.js modules"},{prop:"dlopen",target:process,violationType:"process_dlopen",strategy:"throw",reason:"process.dlopen allows loading native addons"},{prop:"getBuiltinModule",target:process,violationType:"process_get_builtin_module",strategy:"throw",reason:"process.getBuiltinModule allows loading native Node.js modules (fs, child_process, vm)"},{prop:"exit",target:process,violationType:"process_exit",strategy:"throw",reason:"process.exit could terminate the interpreter"},{prop:"abort",target:process,violationType:"process_exit",strategy:"throw",reason:"process.abort could crash the interpreter"},{prop:"kill",target:process,violationType:"process_kill",strategy:"throw",reason:"process.kill could signal other processes"},{prop:"setuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setuid could escalate privileges"},{prop:"setgid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgid could escalate privileges"},{prop:"seteuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.seteuid could escalate effective user privileges"},{prop:"setegid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setegid could escalate effective group privileges"},{prop:"initgroups",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.initgroups could modify supplementary group IDs"},{prop:"setgroups",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgroups could modify supplementary group IDs"},{prop:"umask",target:process,violationType:"process_umask",strategy:"throw",reason:"process.umask could modify file creation permissions"},{prop:"argv",target:process,violationType:"process_argv",strategy:"throw",reason:"process.argv may contain secrets in CLI arguments"},{prop:"cwd",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.cwd could disclose real host working directory path"},{prop:"chdir",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.chdir could confuse the interpreter's CWD tracking"},{prop:"report",target:process,violationType:"process_report",strategy:"throw",reason:"process.report could disclose full environment, host paths, and system info"},{prop:"loadEnvFile",target:process,violationType:"process_env",strategy:"throw",reason:"process.loadEnvFile could load env files bypassing env proxy"},{prop:"setUncaughtExceptionCaptureCallback",target:process,violationType:"process_exception_handler",strategy:"throw",reason:"setUncaughtExceptionCaptureCallback could intercept security errors"},...["on","once","addListener","prependListener","prependOnceListener"].map(n=>({prop:n,target:process,violationType:"process_exception_handler",strategy:"throw",reason:"process-global listeners can outlive the sandbox and lose its security context"})),{prop:"send",target:process,violationType:"process_send",strategy:"throw",reason:"process.send could communicate with parent process in IPC contexts"},{prop:"channel",target:process,violationType:"process_channel",strategy:"throw",reason:"process.channel could access IPC channel to parent process"},{prop:"cpuUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.cpuUsage could enable timing side-channel attacks"},{prop:"memoryUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.memoryUsage could enable timing side-channel attacks"},{prop:"hrtime",target:process,violationType:"process_timing",strategy:"throw",reason:"process.hrtime could enable timing side-channel attacks"},{prop:"WeakRef",target:globalThis,violationType:"weak_ref",strategy:"throw",reason:"WeakRef could be used to leak references outside sandbox"},{prop:"FinalizationRegistry",target:globalThis,violationType:"finalization_registry",strategy:"throw",reason:"FinalizationRegistry could be used to leak references outside sandbox"},{prop:"Reflect",target:globalThis,violationType:"reflect",strategy:"freeze",reason:"Reflect provides introspection capabilities"},{prop:"Proxy",target:globalThis,violationType:"proxy",strategy:"throw",reason:"Proxy allows intercepting and modifying object behavior"},{prop:"WebAssembly",target:globalThis,violationType:"webassembly",strategy:"throw",reason:"WebAssembly allows executing arbitrary compiled code"},{prop:"SharedArrayBuffer",target:globalThis,violationType:"shared_array_buffer",strategy:"throw",reason:"SharedArrayBuffer could enable side-channel communication or timing attacks"},{prop:"Atomics",target:globalThis,violationType:"atomics",strategy:"throw",reason:"Atomics could enable side-channel communication or timing attacks"},{prop:"performance",target:globalThis,violationType:"performance_timing",strategy:"throw",reason:"performance.now() provides sub-millisecond timing for side-channel attacks"},{prop:"stdout",target:process,violationType:"process_stdout",strategy:"throw",reason:"process.stdout could bypass interpreter output to write to host stdout"},{prop:"stderr",target:process,violationType:"process_stderr",strategy:"throw",reason:"process.stderr could bypass interpreter output to write to host stderr"},{prop:"__defineGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineGetter__ allows prototype pollution via getter injection"},{prop:"__defineSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineSetter__ allows prototype pollution via setter injection"},{prop:"__lookupGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupGetter__ enables introspection for prototype pollution attacks"},{prop:"__lookupSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupSetter__ enables introspection for prototype pollution attacks"},{prop:"JSON",target:globalThis,violationType:"json_mutation",strategy:"freeze",reason:"Freeze JSON to prevent mutation of parsing/serialization"},{prop:"Math",target:globalThis,violationType:"math_mutation",strategy:"freeze",reason:"Freeze Math to prevent mutation of math utilities"}];try{let n=Object.getPrototypeOf(async()=>{}).constructor;n&&n!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(async()=>{}),violationType:"async_function_constructor",strategy:"throw",reason:"AsyncFunction constructor allows arbitrary async code execution"})}catch{}try{let n=Object.getPrototypeOf(function*(){}).constructor;n&&n!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(function*(){}),violationType:"generator_function_constructor",strategy:"throw",reason:"GeneratorFunction constructor allows arbitrary generator code execution"})}catch{}try{let n=Object.getPrototypeOf(async function*(){}).constructor;n&&n!==Function&&n!==Object.getPrototypeOf(async()=>{}).constructor&&e.push({prop:"constructor",target:Object.getPrototypeOf(async function*(){}),violationType:"async_generator_function_constructor",strategy:"throw",reason:"AsyncGeneratorFunction constructor allows arbitrary async generator code execution"})}catch{}let t=e.filter(n=>{try{return n.target[n.prop]!==void 0}catch{return!1}});return nOe??=new Set(t.map(({violationType:n})=>n)),t}a(YMt,"Ic");var nOe,KEr=De(()=>{"use strict"});function QEr(){return Math.floor(XMt+ZMt())}a(QEr,"Zp");var XMt,ZMt,JEr=De(()=>{"use strict";XMt=performance.timeOrigin,ZMt=performance.now.bind(performance)});function YEr(e){let t=e?.find(n=>fMe.has(n));if(t)throw new RangeError(`defenseInDepth.excludeViolationTypes cannot disable the non-excludable "${t}" protection`)}a(YEr,"Xp");function XEr(e,t,n){let r=n&&!fMe.has(t)?`
|
|
8552
8552
|
|
|
8553
8553
|
If this access is required by trusted host-runtime code, add "${t}" to defenseInDepth.excludeViolationTypes.`:"";return e+e9t+r}a(XEr,"Yp");var fMe,e9t,ZEr=De(()=>{"use strict";fMe=new Set(["function_constructor","async_function_constructor","generator_function_constructor","async_generator_function_constructor"]),e9t=`
|
|
8554
8554
|
|