@sourcegraph/amp 0.0.1759608074-g34c1da → 0.0.1759636906-gf9ec5f

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.
Files changed (2) hide show
  1. package/dist/main.js +8 -8
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4488,7 +4488,7 @@ ${A}`;return V.pop(),`{${I}}`}case"number":return isFinite(M)?String(M):Q?Q(M):"
4488
4488
  `),stack:Q&&Q.stack,exception:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(Q)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:_96.loadavg(),uptime:_96.uptime()}}getTrace(Q){return(Q?b96.parse(Q):b96.get()).map((X)=>{return{column:X.getColumnNumber(),file:X.getFileName(),function:X.getFunctionName(),line:X.getLineNumber(),method:X.getMethodName(),native:X.isNative()}})}_addHandler(Q){if(!this.handlers.has(Q)){Q.handleExceptions=!0;let Z=new qr8(Q);this.handlers.set(Q,Z),this.logger.pipe(Z)}}_uncaughtException(Q){let Z=this.getAllInfo(Q),X=this._getExceptionHandlers(),Y=typeof this.logger.exitOnError==="function"?this.logger.exitOnError(Q):this.logger.exitOnError,K;if(!X.length&&Y)console.warn("winston: exitOnError cannot be true with no exception handlers."),console.warn("winston: not exiting process."),Y=!1;function q(){if(L_1("doExit",Y),L_1("process._exiting",process._exiting),Y&&!process._exiting){if(K)clearTimeout(K);process.exit(1)}}if(!X||X.length===0)return process.nextTick(q);if(Yr8(X,(G,z)=>{let U=Kr8(z),W=G.transport||G;function F(H){return()=>{L_1(H),U()}}W._ending=!0,W.once("finish",F("finished")),W.once("error",F("error"))},()=>Y&&q()),this.logger.log(Z),Y)K=setTimeout(q,3000)}_getExceptionHandlers(){return this.logger.transports.filter((Q)=>{return(Q.transport||Q).handleExceptions})}}});var f96=t((M22,y96)=>{var{Writable:Gr8}=iA();y96.exports=class extends Gr8{constructor(Q){super({objectMode:!0});if(!Q)throw Error("RejectionStream requires a TransportStream instance.");this.handleRejections=!0,this.transport=Q}_write(Q,Z,X){if(Q.rejection)return this.transport.log(Q,X);return X(),!0}}});var j_1=t((V22,m96)=>{var h96=s1("os"),zr8=f21(),O_1=ng()("winston:rejection"),Ur8=V_1(),g96=N_1(),Wr8=f96();m96.exports=class{constructor(Q){if(!Q)throw Error("Logger is required to handle rejections");this.logger=Q,this.handlers=new Map}handle(...Q){if(Q.forEach((Z)=>{if(Array.isArray(Z))return Z.forEach((X)=>this._addHandler(X));this._addHandler(Z)}),!this.catcher)this.catcher=this._unhandledRejection.bind(this),process.on("unhandledRejection",this.catcher)}unhandle(){if(this.catcher)process.removeListener("unhandledRejection",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach((Q)=>this.logger.unpipe(Q))}getAllInfo(Q){let Z=null;if(Q)Z=typeof Q==="string"?Q:Q.message;return{error:Q,level:"error",message:[`unhandledRejection: ${Z||"(no error message)"}`,Q&&Q.stack||" No stack trace"].join(`
4489
4489
  `),stack:Q&&Q.stack,rejection:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(Q)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:h96.loadavg(),uptime:h96.uptime()}}getTrace(Q){return(Q?g96.parse(Q):g96.get()).map((X)=>{return{column:X.getColumnNumber(),file:X.getFileName(),function:X.getFunctionName(),line:X.getLineNumber(),method:X.getMethodName(),native:X.isNative()}})}_addHandler(Q){if(!this.handlers.has(Q)){Q.handleRejections=!0;let Z=new Wr8(Q);this.handlers.set(Q,Z),this.logger.pipe(Z)}}_unhandledRejection(Q){let Z=this.getAllInfo(Q),X=this._getRejectionHandlers(),Y=typeof this.logger.exitOnError==="function"?this.logger.exitOnError(Q):this.logger.exitOnError,K;if(!X.length&&Y)console.warn("winston: exitOnError cannot be true with no rejection handlers."),console.warn("winston: not exiting process."),Y=!1;function q(){if(O_1("doExit",Y),O_1("process._exiting",process._exiting),Y&&!process._exiting){if(K)clearTimeout(K);process.exit(1)}}if(!X||X.length===0)return process.nextTick(q);if(zr8(X,(G,z)=>{let U=Ur8(z),W=G.transport||G;function F(H){return()=>{O_1(H),U()}}W._ending=!0,W.once("finish",F("finished")),W.once("error",F("error"))},()=>Y&&q()),this.logger.log(Z),Y)K=setTimeout(q,3000)}_getRejectionHandlers(){return this.logger.transports.filter((Q)=>{return(Q.transport||Q).handleRejections})}}});var d96=t((N22,p96)=>{class u96{constructor(J){let Q=h21();if(typeof J!=="object"||Array.isArray(J)||!(J instanceof Q))throw Error("Logger is required for profiling");else this.logger=J,this.start=Date.now()}done(...J){if(typeof J[J.length-1]==="function")console.warn("Callback function no longer supported as of winston@3.0.0"),J.pop();let Q=typeof J[J.length-1]==="object"?J.pop():{};return Q.level=Q.level||"info",Q.durationMs=Date.now()-this.start,this.logger.write(Q)}}p96.exports=u96});var h21=t((L22,a96)=>{var{Stream:Fr8,Transform:Hr8}=iA(),c96=f21(),{LEVEL:VU,SPLAT:l96}=y7(),i96=sl(),Br8=A_1(),Dr8=j_1(),Mr8=xk1(),Vr8=d96(),{warn:Nr8}=Uk1(),Lr8=x21(),Ar8=/%[scdjifoO%]/g;class w_1 extends Hr8{constructor(J){super({objectMode:!0});this.configure(J)}child(J){let Q=this;return Object.create(Q,{write:{value:function(Z){let X=Object.assign({},J,Z);if(Z instanceof Error)X.stack=Z.stack,X.message=Z.message;Q.write(X)}}})}configure({silent:J,format:Q,defaultMeta:Z,levels:X,level:Y="info",exitOnError:K=!0,transports:q,colors:G,emitErrs:z,formatters:U,padLevels:W,rewriters:F,stripColors:H,exceptionHandlers:B,rejectionHandlers:M}={}){if(this.transports.length)this.clear();if(this.silent=J,this.format=Q||this.format||Xk1()(),this.defaultMeta=Z||null,this.levels=X||this.levels||Lr8.npm.levels,this.level=Y,this.exceptions)this.exceptions.unhandle();if(this.rejections)this.rejections.unhandle();if(this.exceptions=new Br8(this),this.rejections=new Dr8(this),this.profilers={},this.exitOnError=K,q)q=Array.isArray(q)?q:[q],q.forEach((V)=>this.add(V));if(G||z||U||W||F||H)throw Error(["{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.","Use a custom winston.format(function) instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join(`
4490
4490
  `));if(B)this.exceptions.handle(B);if(M)this.rejections.handle(M)}isLevelEnabled(J){let Q=R_1(this.levels,J);if(Q===null)return!1;let Z=R_1(this.levels,this.level);if(Z===null)return!1;if(!this.transports||this.transports.length===0)return Z>=Q;return this.transports.findIndex((Y)=>{let K=R_1(this.levels,Y.level);if(K===null)K=Z;return K>=Q})!==-1}log(J,Q,...Z){if(arguments.length===1)return J[VU]=J.level,this._addDefaultMeta(J),this.write(J),this;if(arguments.length===2){if(Q&&typeof Q==="object")return Q[VU]=Q.level=J,this._addDefaultMeta(Q),this.write(Q),this;return Q={[VU]:J,level:J,message:Q},this._addDefaultMeta(Q),this.write(Q),this}let[X]=Z;if(typeof X==="object"&&X!==null){if(!(Q&&Q.match&&Q.match(Ar8))){let K=Object.assign({},this.defaultMeta,X,{[VU]:J,[l96]:Z,level:J,message:Q});if(X.message)K.message=`${K.message} ${X.message}`;if(X.stack)K.stack=X.stack;if(X.cause)K.cause=X.cause;return this.write(K),this}}return this.write(Object.assign({},this.defaultMeta,{[VU]:J,[l96]:Z,level:J,message:Q})),this}_transform(J,Q,Z){if(this.silent)return Z();if(!J[VU])J[VU]=J.level;if(!this.levels[J[VU]]&&this.levels[J[VU]]!==0)console.error("[winston] Unknown logger level: %s",J[VU]);if(!this._readableState.pipes)console.error("[winston] Attempt to write logs with no transports, which can increase memory usage: %j",J);try{this.push(this.format.transform(J,this.format.options))}finally{this._writableState.sync=!1,Z()}}_final(J){let Q=this.transports.slice();c96(Q,(Z,X)=>{if(!Z||Z.finished)return setImmediate(X);Z.once("finish",X),Z.end()},J)}add(J){let Q=!i96(J)||J.log.length>2?new Mr8({transport:J}):J;if(!Q._writableState||!Q._writableState.objectMode)throw Error("Transports must WritableStreams in objectMode. Set { objectMode: true }.");if(this._onEvent("error",Q),this._onEvent("warn",Q),this.pipe(Q),J.handleExceptions)this.exceptions.handle();if(J.handleRejections)this.rejections.handle();return this}remove(J){if(!J)return this;let Q=J;if(!i96(J)||J.log.length>2)Q=this.transports.filter((Z)=>Z.transport===J)[0];if(Q)this.unpipe(Q);return this}clear(){return this.unpipe(),this}close(){return this.exceptions.unhandle(),this.rejections.unhandle(),this.clear(),this.emit("close"),this}setLevels(){Nr8.deprecated("setLevels")}query(J,Q){if(typeof J==="function")Q=J,J={};J=J||{};let Z={},X=Object.assign({},J.query||{});function Y(q,G){if(J.query&&typeof q.formatQuery==="function")J.query=q.formatQuery(X);q.query(J,(z,U)=>{if(z)return G(z);if(typeof q.formatResults==="function")U=q.formatResults(U,J.format);G(null,U)})}function K(q,G){Y(q,(z,U)=>{if(G){if(U=z||U,U)Z[q.name]=U;G()}G=null})}c96(this.transports.filter((q)=>!!q.query),K,()=>Q(null,Z))}stream(J={}){let Q=new Fr8,Z=[];return Q._streams=Z,Q.destroy=()=>{let X=Z.length;while(X--)Z[X].destroy()},this.transports.filter((X)=>!!X.stream).forEach((X)=>{let Y=X.stream(J);if(!Y)return;Z.push(Y),Y.on("log",(K)=>{K.transport=K.transport||[],K.transport.push(X.name),Q.emit("log",K)}),Y.on("error",(K)=>{K.transport=K.transport||[],K.transport.push(X.name),Q.emit("error",K)})}),Q}startTimer(){return new Vr8(this)}profile(J,...Q){let Z=Date.now();if(this.profilers[J]){let X=this.profilers[J];if(delete this.profilers[J],typeof Q[Q.length-2]==="function")console.warn("Callback function no longer supported as of winston@3.0.0"),Q.pop();let Y=typeof Q[Q.length-1]==="object"?Q.pop():{};return Y.level=Y.level||"info",Y.durationMs=Z-X,Y.message=Y.message||J,this.write(Y)}return this.profilers[J]=Z,this}handleExceptions(...J){console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()"),this.exceptions.handle(...J)}unhandleExceptions(...J){console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()"),this.exceptions.unhandle(...J)}cli(){throw Error(["Logger.cli() was removed in winston@3.0.0","Use a custom winston.formats.cli() instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join(`
4491
- `))}_onEvent(J,Q){function Z(X){if(J==="error"&&!this.transports.includes(Q))this.add(Q);this.emit(J,X,Q)}if(!Q["__winston"+J])Q["__winston"+J]=Z.bind(this),Q.on(J,Q["__winston"+J])}_addDefaultMeta(J){if(this.defaultMeta)Object.assign(J,this.defaultMeta)}}function R_1(J,Q){let Z=J[Q];if(!Z&&Z!==0)return null;return Z}Object.defineProperty(w_1.prototype,"transports",{configurable:!1,enumerable:!0,get(){let{pipes:J}=this._readableState;return!Array.isArray(J)?[J].filter(Boolean):J}});a96.exports=w_1});var I_1=t((A22,n96)=>{var{LEVEL:Or8}=y7(),jr8=x21(),Rr8=h21(),wr8=ng()("winston:create-logger");function Ir8(J){return"is"+J.charAt(0).toUpperCase()+J.slice(1)+"Enabled"}n96.exports=function(J={}){J.levels=J.levels||jr8.npm.levels;class Q extends Rr8{constructor(X){super(X)}}let Z=new Q(J);return Object.keys(J.levels).forEach(function(X){if(wr8('Define prototype method for "%s"',X),X==="log"){console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');return}Q.prototype[X]=function(...Y){let K=this||Z;if(Y.length===1){let[q]=Y,G=q&&q.message&&q||{message:q};return G.level=G[Or8]=X,K._addDefaultMeta(G),K.write(G),this||Z}if(Y.length===0)return K.log(X,""),K;return K.log(X,...Y)},Q.prototype[Ir8(X)]=function(){return(this||Z).isLevelEnabled(X)}}),Z}});var s96=t((O22,r96)=>{var Er8=I_1();r96.exports=class{constructor(Q={}){this.loggers=new Map,this.options=Q}add(Q,Z){if(!this.loggers.has(Q)){Z=Object.assign({},Z||this.options);let X=Z.transports||this.options.transports;if(X)Z.transports=Array.isArray(X)?X.slice():[X];else Z.transports=[];let Y=Er8(Z);Y.on("close",()=>this._delete(Q)),this.loggers.set(Q,Y)}return this.loggers.get(Q)}get(Q,Z){return this.add(Q,Z)}has(Q){return!!this.loggers.has(Q)}close(Q){if(Q)return this._removeLogger(Q);this.loggers.forEach((Z,X)=>this._removeLogger(X))}_removeLogger(Q){if(!this.loggers.has(Q))return;this.loggers.get(Q).close(),this._delete(Q)}_delete(Q){this.loggers.delete(Q)}}});var Q26=t((OK)=>{var o96=Gk1(),{warn:og}=Uk1();OK.version=D66().version;OK.transports=j96();OK.config=x21();OK.addColors=o96.levels;OK.format=o96.format;OK.createLogger=I_1();OK.Logger=h21();OK.ExceptionHandler=A_1();OK.RejectionHandler=j_1();OK.Container=s96();OK.Transport=cP();OK.loggers=new OK.Container;var NU=OK.createLogger();Object.keys(OK.config.npm.levels).concat(["log","query","stream","add","remove","clear","profile","startTimer","handleExceptions","unhandleExceptions","handleRejections","unhandleRejections","configure","child"]).forEach((J)=>OK[J]=(...Q)=>NU[J](...Q));Object.defineProperty(OK,"level",{get(){return NU.level},set(J){NU.level=J}});Object.defineProperty(OK,"exceptions",{get(){return NU.exceptions}});Object.defineProperty(OK,"rejections",{get(){return NU.rejections}});["exitOnError"].forEach((J)=>{Object.defineProperty(OK,J,{get(){return NU[J]},set(Q){NU[J]=Q}})});Object.defineProperty(OK,"default",{get(){return{exceptionHandlers:NU.exceptionHandlers,rejectionHandlers:NU.rejectionHandlers,transports:NU.transports}}});og.deprecated(OK,"setLevels");og.forFunctions(OK,"useFormat",["cli"]);og.forProperties(OK,"useFormat",["padLevels","stripColors"]);og.forFunctions(OK,"deprecated",["addRewriter","addFilter","clone","extend"]);og.forProperties(OK,"deprecated",["emitErrs","levelLength"])});class m21{threadID;v;n;constructor(J,Q,Z){this.threadID=J;this.v=Q;this.n=Z}toJSON(){return this.toString()}toString(){return`${this.threadID}@${this.v}.${this.n}`}equals(J){return this.toString()===J.toString()}static of(J){let Q=J.match(/^(.+)@(\d+)\.(\d+)$/);if(!Q)throw Error(`Invalid MessageID format: ${J}`);let[,Z,X,Y]=Q;if(!Z||!X||!Y)throw Error(`Invalid MessageID format: ${J}`);let K=parseInt(X,10),q=parseInt(Y,10);if(isNaN(K)||isNaN(q))throw Error(`Invalid MessageID format: ${J}`);return new m21(Z,K,q)}}class N6{widget;context;_mounted=!1;get mounted(){return this._mounted}initState(){}didUpdateWidget(J){}dispose(){}setState(J){if(!this._mounted)throw Error("setState() called after dispose()");if(J)J();this._markNeedsBuild()}_mount(J,Q){this.widget=J,this.context=Q,this._mounted=!0,this.initState()}_update(J){let Q=this.widget;this.widget=J,this.didUpdateWidget(Q)}_unmount(){this._mounted=!1,this.dispose()}_markNeedsBuild(){let J=this.context.element;if("markNeedsBuild"in J&&typeof J.markNeedsBuild==="function")J.markNeedsBuild()}}function U26(){try{if(process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1003l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1016l"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?2031l"),process.stdout.write("\x1B[?2048l"),process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[0 q"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[999;1H"),process.stdout.write("\x1B[0m"),!process.env.TERM_PROGRAM?.startsWith("iTerm"))process.stdout.write("\x1B]9;4;0\x1B\\")}catch(J){}}function G8(J,...Q){if(!J){let Z=Q.join(" "),X=Error(Z);l.error("TUI Assert failed",{assertion:Z,stackTrace:X.stack,meta:Q});let Y=process.env.AMP_DEBUG,K=process.env.VITEST;if(Y||K){if(K)throw X;U26(),console.error("FATAL TUI ERROR:",Z),console.error("Stack trace:",X.stack),console.error("Context:",{meta:Q}),process.exit(1)}}}var j4=B1(()=>{F0()});function W26(J,Q){C_1=J,S_1=Q}function F26(){return typeof process<"u"&&(process.env.BUN_TEST==="1"||globalThis.Bun?.jest!==void 0||typeof globalThis.test==="function")}function H26(){if(!C_1){if(F26())return{scheduleBuildFor:()=>{}};throw Error("Build scheduler not initialized. Make sure WidgetsBinding is created.")}return C_1}function u21(){if(!S_1){if(F26())return{requestLayout:()=>{},requestPaint:()=>{},removeFromQueues:()=>{}};throw Error("Paint scheduler not initialized. Make sure WidgetsBinding is created.")}return S_1}var C_1=null,S_1=null;class rM{_parent;_children=[];_needsLayout=!1;_needsPaint=!1;_cachedDepth;_attached=!1;_debugData={};allowHitTestOutsideBounds=!1;parentData;sendDebugData(J){this._debugData={...this._debugData,...J}}get debugData(){return this._debugData}get parent(){return this._parent}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Q=this._parent;while(Q)J++,Q=Q._parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get needsLayout(){return this._needsLayout}get needsPaint(){return this._needsPaint}get attached(){return this._attached}adoptChild(J){if(J._parent=this,J._invalidateDepth(),this._children.push(J),"setupParentData"in this&&typeof this.setupParentData==="function")this.setupParentData(J);if(this._attached)J.attach();this.markNeedsLayout()}dropChild(J){let Q=this._children.indexOf(J);if(Q!==-1){if(J._attached)J.detach();this._children.splice(Q,1),J._parent=void 0,J._invalidateDepth(),this.markNeedsLayout()}}removeAllChildren(){for(let J of this._children){if(J._attached)J.detach();J._parent=void 0,J._invalidateDepth()}this._children.length=0,this.markNeedsLayout()}replaceChildren(J){for(let Q of J)Q._parent=this,Q._invalidateDepth();this._children=J,this.markNeedsLayout()}attach(){if(this._attached)return;this._attached=!0;for(let J of this._children)J.attach()}detach(){if(!this._attached)return;this._attached=!1;for(let J of this._children)J.detach()}markNeedsLayout(){if(this._needsLayout)return;if(!this._attached)return;if(this._needsLayout=!0,this.parent)this.parent.markNeedsLayout();else u21().requestLayout(this)}markNeedsPaint(){if(this._needsPaint)return;if(!this._attached)return;this._needsPaint=!0,u21().requestPaint(this)}performLayout(){}paint(J,Q=0,Z=0){this._needsPaint=!1;for(let X of this.children)if("offset"in X){let Y=X,K=Q+Y.offset.x,q=Z+Y.offset.y;X.paint(J,K,q)}else X.paint(J,Q,Z)}visitChildren(J){for(let Q of this._children)J(Q)}dispose(){u21().removeFromQueues(this),this._cachedDepth=void 0,this._parent=void 0,this._children.length=0}}function Qm(J,Q=0){return Number.isFinite(J)?J:Q}class u6{minWidth;maxWidth;minHeight;maxHeight;constructor(J,Q,Z,X){if(typeof J==="object")this.minWidth=J.minWidth??0,this.maxWidth=J.maxWidth??1/0,this.minHeight=J.minHeight??0,this.maxHeight=J.maxHeight??1/0;else this.minWidth=J??0,this.maxWidth=Q??1/0,this.minHeight=Z??0,this.maxHeight=X??1/0}static tight(J,Q){return new u6(J,J,Q,Q)}static loose(J,Q){return new u6(0,J,0,Q)}get hasBoundedWidth(){return this.maxWidth!==1/0}get hasBoundedHeight(){return this.maxHeight!==1/0}get hasTightWidth(){return this.minWidth>=this.maxWidth}get hasTightHeight(){return this.minHeight>=this.maxHeight}constrain(J,Q){return G8(isFinite(J),`BoxConstraints.constrain received infinite width: ${J}. This indicates a layout bug where a widget is not properly calculating its desired size.`),G8(isFinite(Q),`BoxConstraints.constrain received infinite height: ${Q}. This indicates a layout bug where a widget is not properly calculating its desired size.`),{width:Math.max(this.minWidth,Math.min(this.maxWidth,J)),height:Math.max(this.minHeight,Math.min(this.maxHeight,Q))}}enforce(J){let Q=(Z,X,Y)=>Math.max(X,Math.min(Y,Z));return new u6(Q(J.minWidth,this.minWidth,this.maxWidth),Q(J.maxWidth,this.minWidth,this.maxWidth),Q(J.minHeight,this.minHeight,this.maxHeight),Q(J.maxHeight,this.minHeight,this.maxHeight))}get biggest(){return{width:this.maxWidth,height:this.maxHeight}}get smallest(){return{width:this.minWidth,height:this.minHeight}}loosen(){return new u6(0,this.maxWidth,0,this.maxHeight)}tighten({width:J,height:Q}={}){return new u6(J===void 0?this.minWidth:Math.max(this.minWidth,Math.min(this.maxWidth,J)),J===void 0?this.maxWidth:Math.max(this.minWidth,Math.min(this.maxWidth,J)),Q===void 0?this.minHeight:Math.max(this.minHeight,Math.min(this.maxHeight,Q)),Q===void 0?this.maxHeight:Math.max(this.minHeight,Math.min(this.maxHeight,Q)))}static tightFor({width:J,height:Q}={}){return new u6(J??0,J??1/0,Q??0,Q??1/0)}equals(J){return this.minWidth===J.minWidth&&this.maxWidth===J.maxWidth&&this.minHeight===J.minHeight&&this.maxHeight===J.maxHeight}}var Z8;var p9=B1(()=>{j4();Z8=class Z8 extends rM{_size={width:0,height:0};get size(){return{...this._size}}setSize(J,Q){G8(Number.isFinite(J)&&Number.isFinite(Q),`RenderBox.setSize received non-finite dimension: ${J}x${Q}`),this._size.width=J,this._size.height=Q}_offset={x:0,y:0};get offset(){return{...this._offset}}setOffset(J,Q){let Z=Number.isFinite(J)?Math.round(J):0,X=Number.isFinite(Q)?Math.round(Q):0;this._offset.x=Z,this._offset.y=X}localToGlobal(J){let{x:Q,y:Z}=J,X=this;while(X)if(Q+=X._offset.x,Z+=X._offset.y,X=X.parent,X&&!("_offset"in X))break;return{x:Q,y:Z}}globalToLocal(J){let Q=this.localToGlobal({x:0,y:0});return{x:J.x-Q.x,y:J.y-Q.y}}_lastConstraints;layout(J){let Q=!this._lastConstraints||!J.equals(this._lastConstraints);if(!this._needsLayout&&!Q)return;this._lastConstraints=J,this._needsLayout=!1,this.performLayout()}getMinIntrinsicWidth(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMinIntrinsicWidth(J));return Z}getMaxIntrinsicWidth(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMaxIntrinsicWidth(J));return Z}getMinIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMinIntrinsicHeight(J));return Z}getMaxIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMaxIntrinsicHeight(J));return Z}paint(J,Q=0,Z=0){let X=J.getSize(),Y=X.width,K=X.height;for(let q of this.children)if(q instanceof Z8){let G=Q+this.offset.x+q.offset.x,z=Z+this.offset.y+q.offset.y,U=G+q.size.width,W=z+q.size.height;if(!(G>=Y||z>=K||U<=0||W<=0))q.paint(J,Q+this.offset.x,Z+this.offset.y)}}hitTest(J,Q,Z=0,X=0){let Y=Z+this.offset.x,K=X+this.offset.y,q=Q.x>=Y&&Q.x<Y+this.size.width,G=Q.y>=K&&Q.y<K+this.size.height;if(q&&G){J.addWithPaintOffset(this,{x:Y,y:K},Q);let z=!0;for(let U=this.children.length-1;U>=0;U--)if(this.children[U].hitTest(J,Q,Y,K))z=!0;return z}if(this.allowHitTestOutsideBounds){let z=!1;for(let U=this.children.length-1;U>=0;U--)if(this.children[U].hitTest(J,Q,Y,K))z=!0;return z}return!1}}});class JH{element;widget;mediaQuery;parent;constructor(J,Q,Z=void 0,X=null){this.element=J;this.widget=Q;this.mediaQuery=Z;this.parent=X}findAncestorElementOfType(J){let Q=this.element.parent;while(Q){if(Q instanceof J)return Q;Q=Q.parent}return null}findAncestorWidgetOfType(J){return this.element.findAncestorWidgetOfType(J)}dependOnInheritedWidgetOfExactType(J){return this.element.dependOnInheritedWidgetOfExactType(J)}findAncestorStateOfType(J){let Q=this.element.parent;while(Q){if("state"in Q&&Q.state instanceof J)return Q.state;Q=Q.parent}return null}findRenderObject(){if("renderObject"in this.element){let J=this.element.renderObject;return J instanceof rM?J:void 0}return}}var Zm=B1(()=>{p9()});class JQ{key;_debugData={};constructor({key:J}={}){if(this.constructor===JQ)throw Error("Widget is abstract and cannot be instantiated directly");this.key=J}sendDebugData(J){this._debugData={...this._debugData,...J}}get debugData(){return this._debugData}canUpdate(J){if(this.constructor!==J.constructor)return!1;if(this.key===void 0&&J.key===void 0)return!0;if(this.key===void 0||J.key===void 0)return!1;return this.key.equals(J.key)}}class rX{widget;parent;_children=[];_inheritedDependencies=new Set;_dirty=!1;_cachedDepth;_mounted=!1;constructor(J){this.widget=J}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Q=this.parent;while(Q)J++,Q=Q.parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get dirty(){return this._dirty}get mounted(){return this._mounted}get renderObject(){return}update(J){this.widget=J}addChild(J){J.parent=this,J._invalidateDepth(),this._children.push(J)}removeChild(J){let Q=this._children.indexOf(J);if(Q!==-1)this._children.splice(Q,1),J.parent=void 0,J._invalidateDepth()}removeAllChildren(){for(let J of this._children)J.parent=void 0,J._invalidateDepth();this._children.length=0}markMounted(){this._mounted=!0}unmount(){this._mounted=!1,this._dirty=!1,this._cachedDepth=void 0;for(let J of this._inheritedDependencies)if("removeDependent"in J)J.removeDependent(this);this._inheritedDependencies.clear()}markNeedsRebuild(){if(!this._mounted)return;this._dirty=!0,H26().scheduleBuildFor(this)}dependOnInheritedWidgetOfExactType(J){let Q=this.parent;while(Q){if(Q.widget.constructor===J){if("addDependent"in Q)Q.addDependent(this),this._inheritedDependencies.add(Q);return Q}Q=Q.parent}return null}findAncestorElementOfType(J){let Q=this.parent;while(Q){if(Q instanceof J)return Q;Q=Q.parent}return null}findAncestorWidgetOfType(J){let Q=this.parent;while(Q){if(Q.widget instanceof J)return Q.widget;Q=Q.parent}return null}}var QH=()=>{};var L6,v_1;var F2=B1(()=>{Zm();QH();L6=class L6 extends JQ{createElement(){return new v_1(this)}};v_1=class v_1 extends rX{_state;_child;_context;constructor(J){super(J)}get statefulWidget(){return this.widget}get state(){return this._state}get child(){return this._child}mount(){this._context=new JH(this,this.widget),this._state=this.statefulWidget.createState(),this._state._mount(this.statefulWidget,this._context),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;if(this._state)this._state._unmount(),this._state=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._state)this._state._update(this.statefulWidget);if(this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context||!this._state)throw Error("Cannot rebuild unmounted element");let J=this._state.build(this._context);if(this._child)if(this._child.widget.canUpdate(J))this._child.update(J);else{let Q=this._child,Z=this.findNearestRenderObjectAncestor();if(Z&&Q.renderObject)Z.dropChild(Q.renderObject);else if(!Z&&Q.renderObject)Q.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount(),Z&&this._child.renderObject)Z.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!Z&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}markNeedsBuild(){this.markNeedsRebuild()}findNearestRenderObjectAncestor(){let J=this.parent;while(J){if(J.renderObject){if(this._child?.renderObject&&J.renderObject===this._child.renderObject){J=J.parent;continue}return J.renderObject}J=J.parent}return}get renderObject(){return this._child?.renderObject}}});function pr8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Z,subthread:X}=Q,Y=dr8(Z),K=new Set(Y.map((F)=>F.toolUse.id)),q=J.subagents[X.threadID];if(!q){if(q={subThreadID:Z.id,parentToolID:X.toolUse.id,taskDescription:X.toolUse.input?.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let F=WQ(J.mainThread);q.isCompleted=D26(F,X.toolUse.id)}}let G=cr8(Z,Y,q.agentState),z=q.agentState===G?q:{...q,agentState:G},U={...J.tools},W=B26([],Z).items.filter((F)=>F.type==="toolResult");for(let F of W)U[F.id]={id:F.id,subthreadID:Z.id,toolRun:F.toolResult.run,toolUse:F.toolUse};return Y.forEach(({toolUse:F,toolRun:H})=>{U[F.id]={id:F.id,subthreadID:Z.id,toolRun:H,toolUse:F}}),{subagents:{...J.subagents,[X.threadID]:z},tools:U,items:J.items,activeTools:J.activeTools,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Z,subthreads:X,workerStatus:Y}=Q,K=WQ(Z),q={...J.subagents};for(let H of X){let B=q[H.threadID];if(!B)continue;let M=D26(K,H.toolUse.id);q[H.threadID]={...B,isCompleted:M}}let{items:G,activeTools:z}=B26(J.items,Z),U=L_(Z,Y),W=Gp({messages:Z.messages}),F=Array.isArray(W)?W:[];return{...J,subagents:q,items:G,activeTools:z,viewState:U,todosList:F,mainThread:Z}}case"worker-status-change":{if(!J.mainThread)return J;let Z=L_(J.mainThread,Q.workerStatus);if(Z===J.viewState)return J;return{...J,viewState:Z}}default:return J}}function B26(J,Q){let Z=[],X=[],Y=new Map;for(let q of J)Y.set(q.id,q);let K=new Set;for(let[q,G]of Q.messages.entries()){let z=`${G.role}-${q}`;switch(G.role){case"assistant":{if(G.state.type==="streaming"){for(let F of G.content)if(F.type==="tool_use")K.add(F.id)}if(G.content.some((F)=>F.type==="text"&&F.text.trim()||F.type==="thinking"))X.push({type:"message",id:z,message:G});break}case"info":X.push({type:"message",id:z,message:G});break;case"user":{if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="image"))X.push({type:"message",id:z,message:G});for(let W of G.content)if(W.type==="tool_result"){let F=JZ(Q,W.toolUseID);if(!F)throw Error(`(bug) tool use ${W.toolUseID} not found`);if(K.has(W.toolUseID)||!O5(W.run)){Z.push({toolUse:F,toolRun:W.run});continue}X.push({type:"toolResult",id:W.toolUseID,toolUse:F,toolResult:W})}break}}}for(let q of K){let G=JZ(Q,q);if(!G)continue;if(!Z.some((U)=>U.toolUse.id===q))Z.push({toolUse:G,toolRun:{status:"in-progress"}})}return{items:X,activeTools:Z}}function D26(J,Q){let Z=J.get(Q);return(Z&&O5(Z.run))??!1}function dr8(J){let Q=[],Z=new Map,X=new Set;for(let Y of J.messages){if(Y.role==="assistant"&&Y.state.type==="streaming"){for(let K of Y.content)if(K.type==="tool_use")X.add(K.id),Z.set(K.id,K)}for(let K of Y.content)if(K.type==="tool_use")Z.set(K.id,K);else if(K.type==="tool_result"){let q=Z.get(K.toolUseID);if(q&&!O5(K.run))Q.push({toolUse:q,toolRun:K.run})}}for(let Y of X){let K=Z.get(Y);if(!K)continue;if(!Q.some((G)=>G.toolUse.id===Y))Q.push({toolUse:K,toolRun:{status:"in-progress"}})}return Q}function cr8(J,Q,Z){let X=J.messages.at(-1);if(X?.content.some((Y)=>Y.type==="tool_result"&&Y.run.status==="blocked-on-user"))return l.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(Q.filter((Y)=>Y.toolRun.status==="in-progress").length>0){let Y=Z?.type==="running-tools"?Z.startTime:Date.now();return l.info("Subagent status: running-tools",{threadID:J.id,startTime:Y,hasStartTime:!!Y}),{type:"running-tools",startTime:Y}}if(X&&X.role==="assistant"&&X.state.type==="streaming")switch(X.content.at(-1)?.type){case"text":return l.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return l.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let K=Z?.type==="running-tools"?Z.startTime:Date.now();return l.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:K,hasStartTime:!!K}),{type:"running-tools",startTime:K}}default:return l.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return l.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}function lr8(J){k_1=J}function sM(){return M26}function p21(){return k_1}function d21(J){M26=J,k_1?.switchWorker(J)}var k_1=null,M26=null,__1,V26;var c21=B1(()=>{F0();u2();j2();F2();__1=class __1 extends L6{props;constructor(J){super();this.props=J}createState(){return new V26}};V26=class V26 extends N6{state={subagents:{},tools:{},items:[],activeTools:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};subscriptions=[];subthreadSubs=new Map;currentSubthreads=[];currentWorkerStatus={state:"initial"};initState(){this.setupSubscriptions(),lr8(this)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions()}setupSubscriptions(){let{threadService:J,worker:Q}=this.widget.props,Z=J.observePatches(Q.thread.id).pipe(cV()).subscribe((K)=>{this.dispatch({type:"main-thread-patch",thread:K,subthreads:this.currentSubthreads,workerStatus:this.currentWorkerStatus})});this.subscriptions.push(Z);let X=Q.status.subscribe((K)=>{this.currentWorkerStatus=K,this.dispatch({type:"worker-status-change",workerStatus:K})});this.subscriptions.push(X);let Y=Q.subthreads.subscribe((K)=>{this.currentSubthreads=K;for(let q of K){if(this.subthreadSubs.has(q.toolUse.id))continue;let G=J.observePatches(q.threadID).pipe(cV()).subscribe((z)=>{this.dispatch({type:"subthread-patch",thread:z,subthread:q})});this.subthreadSubs.set(q.toolUse.id,G)}});this.subscriptions.push(Y)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[],this.subthreadSubs.forEach((J)=>J.unsubscribe()),this.subthreadSubs.clear()}switchWorker(J){this.cleanup(),this.setState(()=>{this.state={subagents:{},tools:{},items:[],activeTools:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null},this.currentSubthreads=[],this.currentWorkerStatus={state:"initial"}});let{threadService:Q}=this.widget.props,Z=sM()||J,X=Q.observePatches(Z.thread.id).pipe(cV()).subscribe((q)=>{this.dispatch({type:"main-thread-patch",thread:q,subthreads:this.currentSubthreads,workerStatus:this.currentWorkerStatus})});this.subscriptions.push(X);let Y=J.status.subscribe((q)=>{this.currentWorkerStatus=q,this.dispatch({type:"worker-status-change",workerStatus:q})});this.subscriptions.push(Y);let K=J.subthreads.subscribe((q)=>{this.currentSubthreads=q;for(let G of q){if(this.subthreadSubs.has(G.toolUse.id))continue;let z=Q.observePatches(G.threadID).pipe(cV()).subscribe((U)=>{this.dispatch({type:"subthread-patch",thread:U,subthread:G})});this.subthreadSubs.set(G.toolUse.id,z)}});this.subscriptions.push(K)}dispatch(J){this.setState(()=>{this.state=pr8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((Y)=>({toolUse:Y.toolUse,toolRun:Y.toolRun,subthreadID:Y.subthreadID})),Q={};for(let Y of Object.values(this.state.subagents)){let K=J.filter((q)=>q.subthreadID===Y.subThreadID);Q[Y.parentToolID]=K}let Z=(Y)=>Y==="oracle"||Y==="finder"||Y==="fast_finder"||Y==="xai_finder"||Y==="kimiK2_finder"||Y==="gossip_finder"||Y==="sonoma_finder",X=[];for(let Y of this.state.activeTools)if(Z(Y.toolUse.name))X.push({toolUseId:Y.toolUse.id,toolName:Y.toolUse.name,toolRun:Y.toolRun});for(let Y of this.state.items)if(Y.type==="toolResult"&&Z(Y.toolUse.name))X.push({toolUseId:Y.toolUse.id,toolName:Y.toolUse.name,toolRun:Y.toolResult.run});for(let{toolUseId:Y,toolName:K,toolRun:q}of X){let G=[],z;if(q.status==="in-progress"||q.status==="done"||q.status==="error"||q.status==="cancelled")z=q.progress;if(z){let U=0;for(let W of z)if(W.tool_uses)for(let F of W.tool_uses){let H=`${Y}:progress:${U++}`;G.push({toolUse:{type:"tool_use",id:H,name:F.tool_name,input:F.input},toolRun:{status:F.status}})}}Q[Y]=G}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q)}}});var L26={};V6(L26,{startSSEConnection:()=>y_1,generateClientID:()=>x_1,connectCommand:()=>f_1,connectBackground:()=>nr8});import*as N26 from"node:https";function x_1(J){let{generateClientID:Q}=(rJ1(),vX6(fd1));return Q(J)}async function b_1(J,Q){let Z=await d8(),X=await Z.secrets.getToken("apiKey",Z.settings.url);if(!X)throw Error("API key not found");let Y=Z.settings.url;if(!Y)throw Error("amp.url is not set");let K=await fetch(new URL(`/api/clients/${J}/receipt`,Y),{method:"POST",headers:{...KY(),"Content-Type":"application/json",Authorization:`Bearer ${X}`},body:JSON.stringify({messageID:Q.toString()})});if(!K.ok){let q=await K.text();throw Error(`Failed to confirm receipt: ${K.status} ${q}`)}}async function ir8(J,Q,Z,X){try{let Y=sM()||J.worker,q=Y.thread.v,G=X.v;if(G<q){l.debug(`Skipping stale message v${G} < current v${q}`),await b_1(Z,X);return}await Y.handle({type:"user:message",message:{content:Q.content,fileMentions:Q.fileMentions,userState:Q.userState,agentMode:Q.agentMode,meta:Q.meta,source:Q.source}}),await b_1(Z,X),l.debug(`Successfully processed message ${X.toString()}`)}catch(Y){l.error("Error processing received message:",Y),await b_1(Z,X)}}async function ar8(J,Q,Z={}){let X=await d8(Z.signal),Y=await X.secrets.getToken("apiKey",X.settings.url);if(!Y)throw Error("API key not found");let K=X.settings.url;if(!K)throw Error("amp.url is not set");let q=new URL(`/api/clients/${Q}/subscription`,K),G=Z.timeout||55000;return new Promise((z,U)=>{let W=Z.lastEventId,F=!1,B={method:"POST",headers:{Authorization:`Bearer ${Y}`,Accept:"text/event-stream","Cache-Control":"no-cache","Content-Type":"application/json",...W&&{"Last-Event-ID":W},...Z.currentThreadID&&{"X-Current-Thread-ID":Z.currentThreadID}},rejectUnauthorized:!1},M=!1,V=setTimeout(()=>{l.debug(`Connection timeout after ${G}ms, closing to reconnect`),M=!0,N.destroy(),z({lastEventId:W})},G),N=N26.request(q,B,(L)=>{if(L.statusCode!==200){if(clearTimeout(V),L.statusCode===409){let O="";L.on("data",(j)=>{O+=j.toString()}),L.on("end",()=>{try{let I=(JSON.parse(O).message||"Client already subscribed to another thread").match(/Client (\S+) is already subscribed/),w=I?I[1]:"another client";U(Error(`Another client is connected with ${w}.
4491
+ `))}_onEvent(J,Q){function Z(X){if(J==="error"&&!this.transports.includes(Q))this.add(Q);this.emit(J,X,Q)}if(!Q["__winston"+J])Q["__winston"+J]=Z.bind(this),Q.on(J,Q["__winston"+J])}_addDefaultMeta(J){if(this.defaultMeta)Object.assign(J,this.defaultMeta)}}function R_1(J,Q){let Z=J[Q];if(!Z&&Z!==0)return null;return Z}Object.defineProperty(w_1.prototype,"transports",{configurable:!1,enumerable:!0,get(){let{pipes:J}=this._readableState;return!Array.isArray(J)?[J].filter(Boolean):J}});a96.exports=w_1});var I_1=t((A22,n96)=>{var{LEVEL:Or8}=y7(),jr8=x21(),Rr8=h21(),wr8=ng()("winston:create-logger");function Ir8(J){return"is"+J.charAt(0).toUpperCase()+J.slice(1)+"Enabled"}n96.exports=function(J={}){J.levels=J.levels||jr8.npm.levels;class Q extends Rr8{constructor(X){super(X)}}let Z=new Q(J);return Object.keys(J.levels).forEach(function(X){if(wr8('Define prototype method for "%s"',X),X==="log"){console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');return}Q.prototype[X]=function(...Y){let K=this||Z;if(Y.length===1){let[q]=Y,G=q&&q.message&&q||{message:q};return G.level=G[Or8]=X,K._addDefaultMeta(G),K.write(G),this||Z}if(Y.length===0)return K.log(X,""),K;return K.log(X,...Y)},Q.prototype[Ir8(X)]=function(){return(this||Z).isLevelEnabled(X)}}),Z}});var s96=t((O22,r96)=>{var Er8=I_1();r96.exports=class{constructor(Q={}){this.loggers=new Map,this.options=Q}add(Q,Z){if(!this.loggers.has(Q)){Z=Object.assign({},Z||this.options);let X=Z.transports||this.options.transports;if(X)Z.transports=Array.isArray(X)?X.slice():[X];else Z.transports=[];let Y=Er8(Z);Y.on("close",()=>this._delete(Q)),this.loggers.set(Q,Y)}return this.loggers.get(Q)}get(Q,Z){return this.add(Q,Z)}has(Q){return!!this.loggers.has(Q)}close(Q){if(Q)return this._removeLogger(Q);this.loggers.forEach((Z,X)=>this._removeLogger(X))}_removeLogger(Q){if(!this.loggers.has(Q))return;this.loggers.get(Q).close(),this._delete(Q)}_delete(Q){this.loggers.delete(Q)}}});var Q26=t((OK)=>{var o96=Gk1(),{warn:og}=Uk1();OK.version=D66().version;OK.transports=j96();OK.config=x21();OK.addColors=o96.levels;OK.format=o96.format;OK.createLogger=I_1();OK.Logger=h21();OK.ExceptionHandler=A_1();OK.RejectionHandler=j_1();OK.Container=s96();OK.Transport=cP();OK.loggers=new OK.Container;var NU=OK.createLogger();Object.keys(OK.config.npm.levels).concat(["log","query","stream","add","remove","clear","profile","startTimer","handleExceptions","unhandleExceptions","handleRejections","unhandleRejections","configure","child"]).forEach((J)=>OK[J]=(...Q)=>NU[J](...Q));Object.defineProperty(OK,"level",{get(){return NU.level},set(J){NU.level=J}});Object.defineProperty(OK,"exceptions",{get(){return NU.exceptions}});Object.defineProperty(OK,"rejections",{get(){return NU.rejections}});["exitOnError"].forEach((J)=>{Object.defineProperty(OK,J,{get(){return NU[J]},set(Q){NU[J]=Q}})});Object.defineProperty(OK,"default",{get(){return{exceptionHandlers:NU.exceptionHandlers,rejectionHandlers:NU.rejectionHandlers,transports:NU.transports}}});og.deprecated(OK,"setLevels");og.forFunctions(OK,"useFormat",["cli"]);og.forProperties(OK,"useFormat",["padLevels","stripColors"]);og.forFunctions(OK,"deprecated",["addRewriter","addFilter","clone","extend"]);og.forProperties(OK,"deprecated",["emitErrs","levelLength"])});class m21{threadID;v;n;constructor(J,Q,Z){this.threadID=J;this.v=Q;this.n=Z}toJSON(){return this.toString()}toString(){return`${this.threadID}@${this.v}.${this.n}`}equals(J){return this.toString()===J.toString()}static of(J){let Q=J.match(/^(.+)@(\d+)\.(\d+)$/);if(!Q)throw Error(`Invalid MessageID format: ${J}`);let[,Z,X,Y]=Q;if(!Z||!X||!Y)throw Error(`Invalid MessageID format: ${J}`);let K=parseInt(X,10),q=parseInt(Y,10);if(isNaN(K)||isNaN(q))throw Error(`Invalid MessageID format: ${J}`);return new m21(Z,K,q)}}class N6{widget;context;_mounted=!1;get mounted(){return this._mounted}initState(){}didUpdateWidget(J){}dispose(){}setState(J){if(!this._mounted)throw Error("setState() called after dispose()");if(J)J();this._markNeedsBuild()}_mount(J,Q){this.widget=J,this.context=Q,this._mounted=!0,this.initState()}_update(J){let Q=this.widget;this.widget=J,this.didUpdateWidget(Q)}_unmount(){this._mounted=!1,this.dispose()}_markNeedsBuild(){let J=this.context.element;if("markNeedsBuild"in J&&typeof J.markNeedsBuild==="function")J.markNeedsBuild()}}function U26(){try{if(process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1003l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1016l"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?2031l"),process.stdout.write("\x1B[?2048l"),process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[0 q"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[999;1H"),process.stdout.write("\x1B[0m"),!process.env.TERM_PROGRAM?.startsWith("iTerm"))process.stdout.write("\x1B]9;4;0\x1B\\")}catch(J){}}function G8(J,...Q){if(!J){let Z=Q.join(" "),X=Error(Z);l.error("TUI Assert failed",{assertion:Z,stackTrace:X.stack,meta:Q});let Y=process.env.AMP_DEBUG,K=process.env.VITEST;if(Y||K){if(K)throw X;U26(),console.error("FATAL TUI ERROR:",Z),console.error("Stack trace:",X.stack),console.error("Context:",{meta:Q}),process.exit(1)}}}var j4=B1(()=>{F0()});function W26(J,Q){C_1=J,S_1=Q}function F26(){return typeof process<"u"&&(process.env.BUN_TEST==="1"||globalThis.Bun?.jest!==void 0||typeof globalThis.test==="function")}function H26(){if(!C_1){if(F26())return{scheduleBuildFor:()=>{}};throw Error("Build scheduler not initialized. Make sure WidgetsBinding is created.")}return C_1}function u21(){if(!S_1){if(F26())return{requestLayout:()=>{},requestPaint:()=>{},removeFromQueues:()=>{}};throw Error("Paint scheduler not initialized. Make sure WidgetsBinding is created.")}return S_1}var C_1=null,S_1=null;class rM{_parent;_children=[];_needsLayout=!1;_needsPaint=!1;_cachedDepth;_attached=!1;_debugData={};allowHitTestOutsideBounds=!1;parentData;sendDebugData(J){this._debugData={...this._debugData,...J}}get debugData(){return this._debugData}get parent(){return this._parent}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Q=this._parent;while(Q)J++,Q=Q._parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get needsLayout(){return this._needsLayout}get needsPaint(){return this._needsPaint}get attached(){return this._attached}adoptChild(J){if(J._parent=this,J._invalidateDepth(),this._children.push(J),"setupParentData"in this&&typeof this.setupParentData==="function")this.setupParentData(J);if(this._attached)J.attach();this.markNeedsLayout()}dropChild(J){let Q=this._children.indexOf(J);if(Q!==-1){if(J._attached)J.detach();this._children.splice(Q,1),J._parent=void 0,J._invalidateDepth(),this.markNeedsLayout()}}removeAllChildren(){for(let J of this._children){if(J._attached)J.detach();J._parent=void 0,J._invalidateDepth()}this._children.length=0,this.markNeedsLayout()}replaceChildren(J){for(let Q of J)Q._parent=this,Q._invalidateDepth();this._children=J,this.markNeedsLayout()}attach(){if(this._attached)return;this._attached=!0;for(let J of this._children)J.attach()}detach(){if(!this._attached)return;this._attached=!1;for(let J of this._children)J.detach()}markNeedsLayout(){if(this._needsLayout)return;if(!this._attached)return;if(this._needsLayout=!0,this.parent)this.parent.markNeedsLayout();else u21().requestLayout(this)}markNeedsPaint(){if(this._needsPaint)return;if(!this._attached)return;this._needsPaint=!0,u21().requestPaint(this)}performLayout(){}paint(J,Q=0,Z=0){this._needsPaint=!1;for(let X of this.children)if("offset"in X){let Y=X,K=Q+Y.offset.x,q=Z+Y.offset.y;X.paint(J,K,q)}else X.paint(J,Q,Z)}visitChildren(J){for(let Q of this._children)J(Q)}dispose(){u21().removeFromQueues(this),this._cachedDepth=void 0,this._parent=void 0,this._children.length=0}}function Qm(J,Q=0){return Number.isFinite(J)?J:Q}class u6{minWidth;maxWidth;minHeight;maxHeight;constructor(J,Q,Z,X){if(typeof J==="object")this.minWidth=J.minWidth??0,this.maxWidth=J.maxWidth??1/0,this.minHeight=J.minHeight??0,this.maxHeight=J.maxHeight??1/0;else this.minWidth=J??0,this.maxWidth=Q??1/0,this.minHeight=Z??0,this.maxHeight=X??1/0}static tight(J,Q){return new u6(J,J,Q,Q)}static loose(J,Q){return new u6(0,J,0,Q)}get hasBoundedWidth(){return this.maxWidth!==1/0}get hasBoundedHeight(){return this.maxHeight!==1/0}get hasTightWidth(){return this.minWidth>=this.maxWidth}get hasTightHeight(){return this.minHeight>=this.maxHeight}constrain(J,Q){return G8(isFinite(J),`BoxConstraints.constrain received infinite width: ${J}. This indicates a layout bug where a widget is not properly calculating its desired size.`),G8(isFinite(Q),`BoxConstraints.constrain received infinite height: ${Q}. This indicates a layout bug where a widget is not properly calculating its desired size.`),{width:Math.max(this.minWidth,Math.min(this.maxWidth,J)),height:Math.max(this.minHeight,Math.min(this.maxHeight,Q))}}enforce(J){let Q=(Z,X,Y)=>Math.max(X,Math.min(Y,Z));return new u6(Q(J.minWidth,this.minWidth,this.maxWidth),Q(J.maxWidth,this.minWidth,this.maxWidth),Q(J.minHeight,this.minHeight,this.maxHeight),Q(J.maxHeight,this.minHeight,this.maxHeight))}get biggest(){return{width:this.maxWidth,height:this.maxHeight}}get smallest(){return{width:this.minWidth,height:this.minHeight}}loosen(){return new u6(0,this.maxWidth,0,this.maxHeight)}tighten({width:J,height:Q}={}){return new u6(J===void 0?this.minWidth:Math.max(this.minWidth,Math.min(this.maxWidth,J)),J===void 0?this.maxWidth:Math.max(this.minWidth,Math.min(this.maxWidth,J)),Q===void 0?this.minHeight:Math.max(this.minHeight,Math.min(this.maxHeight,Q)),Q===void 0?this.maxHeight:Math.max(this.minHeight,Math.min(this.maxHeight,Q)))}static tightFor({width:J,height:Q}={}){return new u6(J??0,J??1/0,Q??0,Q??1/0)}equals(J){return this.minWidth===J.minWidth&&this.maxWidth===J.maxWidth&&this.minHeight===J.minHeight&&this.maxHeight===J.maxHeight}}var Z8;var p9=B1(()=>{j4();Z8=class Z8 extends rM{_size={width:0,height:0};get size(){return{...this._size}}setSize(J,Q){G8(Number.isFinite(J)&&Number.isFinite(Q),`RenderBox.setSize received non-finite dimension: ${J}x${Q}`),this._size.width=J,this._size.height=Q}_offset={x:0,y:0};get offset(){return{...this._offset}}setOffset(J,Q){let Z=Number.isFinite(J)?Math.round(J):0,X=Number.isFinite(Q)?Math.round(Q):0;this._offset.x=Z,this._offset.y=X}localToGlobal(J){let{x:Q,y:Z}=J,X=this;while(X)if(Q+=X._offset.x,Z+=X._offset.y,X=X.parent,X&&!("_offset"in X))break;return{x:Q,y:Z}}globalToLocal(J){let Q=this.localToGlobal({x:0,y:0});return{x:J.x-Q.x,y:J.y-Q.y}}_lastConstraints;layout(J){let Q=!this._lastConstraints||!J.equals(this._lastConstraints);if(!this._needsLayout&&!Q)return;this._lastConstraints=J,this._needsLayout=!1,this.performLayout()}getMinIntrinsicWidth(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMinIntrinsicWidth(J));return Z}getMaxIntrinsicWidth(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMaxIntrinsicWidth(J));return Z}getMinIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMinIntrinsicHeight(J));return Z}getMaxIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 0;let Z=0;for(let X of Q)Z=Math.max(Z,X.getMaxIntrinsicHeight(J));return Z}paint(J,Q=0,Z=0){let X=J.getSize(),Y=X.width,K=X.height;for(let q of this.children)if(q instanceof Z8){let G=Q+this.offset.x+q.offset.x,z=Z+this.offset.y+q.offset.y,U=G+q.size.width,W=z+q.size.height;if(!(G>=Y||z>=K||U<=0||W<=0))q.paint(J,Q+this.offset.x,Z+this.offset.y)}}hitTest(J,Q,Z=0,X=0){let Y=Z+this.offset.x,K=X+this.offset.y,q=Q.x>=Y&&Q.x<Y+this.size.width,G=Q.y>=K&&Q.y<K+this.size.height;if(q&&G){J.addWithPaintOffset(this,{x:Y,y:K},Q);let z=!0;for(let U=this.children.length-1;U>=0;U--)if(this.children[U].hitTest(J,Q,Y,K))z=!0;return z}if(this.allowHitTestOutsideBounds){let z=!1;for(let U=this.children.length-1;U>=0;U--)if(this.children[U].hitTest(J,Q,Y,K))z=!0;return z}return!1}}});class JH{element;widget;mediaQuery;parent;constructor(J,Q,Z=void 0,X=null){this.element=J;this.widget=Q;this.mediaQuery=Z;this.parent=X}findAncestorElementOfType(J){let Q=this.element.parent;while(Q){if(Q instanceof J)return Q;Q=Q.parent}return null}findAncestorWidgetOfType(J){return this.element.findAncestorWidgetOfType(J)}dependOnInheritedWidgetOfExactType(J){return this.element.dependOnInheritedWidgetOfExactType(J)}findAncestorStateOfType(J){let Q=this.element.parent;while(Q){if("state"in Q&&Q.state instanceof J)return Q.state;Q=Q.parent}return null}findRenderObject(){if("renderObject"in this.element){let J=this.element.renderObject;return J instanceof rM?J:void 0}return}}var Zm=B1(()=>{p9()});class JQ{key;_debugData={};constructor({key:J}={}){if(this.constructor===JQ)throw Error("Widget is abstract and cannot be instantiated directly");this.key=J}sendDebugData(J){this._debugData={...this._debugData,...J}}get debugData(){return this._debugData}canUpdate(J){if(this.constructor!==J.constructor)return!1;if(this.key===void 0&&J.key===void 0)return!0;if(this.key===void 0||J.key===void 0)return!1;return this.key.equals(J.key)}}class rX{widget;parent;_children=[];_inheritedDependencies=new Set;_dirty=!1;_cachedDepth;_mounted=!1;constructor(J){this.widget=J}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Q=this.parent;while(Q)J++,Q=Q.parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get dirty(){return this._dirty}get mounted(){return this._mounted}get renderObject(){return}update(J){this.widget=J}addChild(J){J.parent=this,J._invalidateDepth(),this._children.push(J)}removeChild(J){let Q=this._children.indexOf(J);if(Q!==-1)this._children.splice(Q,1),J.parent=void 0,J._invalidateDepth()}removeAllChildren(){for(let J of this._children)J.parent=void 0,J._invalidateDepth();this._children.length=0}markMounted(){this._mounted=!0}unmount(){this._mounted=!1,this._dirty=!1,this._cachedDepth=void 0;for(let J of this._inheritedDependencies)if("removeDependent"in J)J.removeDependent(this);this._inheritedDependencies.clear()}markNeedsRebuild(){if(!this._mounted)return;this._dirty=!0,H26().scheduleBuildFor(this)}dependOnInheritedWidgetOfExactType(J){let Q=this.parent;while(Q){if(Q.widget.constructor===J){if("addDependent"in Q)Q.addDependent(this),this._inheritedDependencies.add(Q);return Q}Q=Q.parent}return null}findAncestorElementOfType(J){let Q=this.parent;while(Q){if(Q instanceof J)return Q;Q=Q.parent}return null}findAncestorWidgetOfType(J){let Q=this.parent;while(Q){if(Q.widget instanceof J)return Q.widget;Q=Q.parent}return null}}var QH=()=>{};var L6,v_1;var F2=B1(()=>{Zm();QH();L6=class L6 extends JQ{createElement(){return new v_1(this)}};v_1=class v_1 extends rX{_state;_child;_context;constructor(J){super(J)}get statefulWidget(){return this.widget}get state(){return this._state}get child(){return this._child}mount(){this._context=new JH(this,this.widget),this._state=this.statefulWidget.createState(),this._state._mount(this.statefulWidget,this._context),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;if(this._state)this._state._unmount(),this._state=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._state)this._state._update(this.statefulWidget);if(this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context||!this._state)throw Error("Cannot rebuild unmounted element");let J=this._state.build(this._context);if(this._child)if(this._child.widget.canUpdate(J))this._child.update(J);else{let Q=this._child,Z=this.findNearestRenderObjectAncestor();if(Z&&Q.renderObject)Z.dropChild(Q.renderObject);else if(!Z&&Q.renderObject)Q.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount(),Z&&this._child.renderObject)Z.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!Z&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}markNeedsBuild(){this.markNeedsRebuild()}findNearestRenderObjectAncestor(){let J=this.parent;while(J){if(J.renderObject){if(this._child?.renderObject&&J.renderObject===this._child.renderObject){J=J.parent;continue}return J.renderObject}J=J.parent}return}get renderObject(){return this._child?.renderObject}}});function pr8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Z,subthread:X}=Q,Y=dr8(Z),K=new Set(Y.map((F)=>F.toolUse.id)),q=J.subagents[X.threadID];if(!q){if(q={subThreadID:Z.id,parentToolID:X.toolUse.id,taskDescription:X.toolUse.input?.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let F=WQ(J.mainThread);q.isCompleted=D26(F,X.toolUse.id)}}let G=cr8(Z,Y,q.agentState),z=q.agentState===G?q:{...q,agentState:G},U={...J.tools},W=B26([],Z).items.filter((F)=>F.type==="toolResult");for(let F of W)U[F.id]={id:F.id,subthreadID:Z.id,toolRun:F.toolResult.run,toolUse:F.toolUse};return Y.forEach(({toolUse:F,toolRun:H})=>{U[F.id]={id:F.id,subthreadID:Z.id,toolRun:H,toolUse:F}}),{subagents:{...J.subagents,[X.threadID]:z},tools:U,items:J.items,activeTools:J.activeTools,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Z,subthreads:X,workerStatus:Y}=Q,K=WQ(Z),q={...J.subagents};for(let H of X){let B=q[H.threadID];if(!B)continue;let M=D26(K,H.toolUse.id);q[H.threadID]={...B,isCompleted:M}}let{items:G,activeTools:z}=B26(J.items,Z),U=L_(Z,Y),W=Gp({messages:Z.messages}),F=Array.isArray(W)?W:[];return{...J,subagents:q,items:G,activeTools:z,viewState:U,todosList:F,mainThread:Z}}case"worker-status-change":{if(!J.mainThread)return J;let Z=L_(J.mainThread,Q.workerStatus);if(Z===J.viewState)return J;return{...J,viewState:Z}}default:return J}}function B26(J,Q){let Z=[],X=[],Y=new Map;for(let G of J)Y.set(G.id,G);let K=new Map,q=new Set;for(let[G,z]of Q.messages.entries()){let U=`${z.role}-${G}`;switch(z.role){case"assistant":{let W=z.state.type==="streaming";for(let H of z.content)if(H.type==="tool_use"){if(K.set(H.id,H),W)q.add(H.id)}if(z.content.some((H)=>H.type==="text"&&H.text.trim()||H.type==="thinking"))X.push({type:"message",id:U,message:z});break}case"info":X.push({type:"message",id:U,message:z});break;case"user":{if(z.content.some((F)=>F.type==="text"&&F.text.trim()||F.type==="image"))X.push({type:"message",id:U,message:z});for(let F of z.content)if(F.type==="tool_result"){let H=K.get(F.toolUseID)??JZ(Q,F.toolUseID);if(!H)throw Error(`(bug) tool use ${F.toolUseID} not found`);if(q.has(F.toolUseID)||!O5(F.run)){Z.push({toolUse:H,toolRun:F.run});continue}X.push({type:"toolResult",id:F.toolUseID,toolUse:H,toolResult:F})}break}}}for(let G of q){let z=K.get(G)??JZ(Q,G);if(!z)continue;if(!Z.some((W)=>W.toolUse.id===G))Z.push({toolUse:z,toolRun:{status:"in-progress"}})}return{items:X,activeTools:Z}}function D26(J,Q){let Z=J.get(Q);return(Z&&O5(Z.run))??!1}function dr8(J){let Q=[],Z=new Map,X=new Set;for(let Y of J.messages){if(Y.role==="assistant"&&Y.state.type==="streaming"){for(let K of Y.content)if(K.type==="tool_use")X.add(K.id),Z.set(K.id,K)}for(let K of Y.content)if(K.type==="tool_use")Z.set(K.id,K);else if(K.type==="tool_result"){let q=Z.get(K.toolUseID);if(q&&!O5(K.run))Q.push({toolUse:q,toolRun:K.run})}}for(let Y of X){let K=Z.get(Y);if(!K)continue;if(!Q.some((G)=>G.toolUse.id===Y))Q.push({toolUse:K,toolRun:{status:"in-progress"}})}return Q}function cr8(J,Q,Z){let X=J.messages.at(-1);if(X?.content.some((Y)=>Y.type==="tool_result"&&Y.run.status==="blocked-on-user"))return l.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(Q.filter((Y)=>Y.toolRun.status==="in-progress").length>0){let Y=Z?.type==="running-tools"?Z.startTime:Date.now();return l.info("Subagent status: running-tools",{threadID:J.id,startTime:Y,hasStartTime:!!Y}),{type:"running-tools",startTime:Y}}if(X&&X.role==="assistant"&&X.state.type==="streaming")switch(X.content.at(-1)?.type){case"text":return l.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return l.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let K=Z?.type==="running-tools"?Z.startTime:Date.now();return l.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:K,hasStartTime:!!K}),{type:"running-tools",startTime:K}}default:return l.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return l.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}function lr8(J){k_1=J}function sM(){return M26}function p21(){return k_1}function d21(J){M26=J,k_1?.switchWorker(J)}var k_1=null,M26=null,__1,V26;var c21=B1(()=>{F0();u2();j2();F2();__1=class __1 extends L6{props;constructor(J){super();this.props=J}createState(){return new V26}};V26=class V26 extends N6{state={subagents:{},tools:{},items:[],activeTools:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};subscriptions=[];subthreadSubs=new Map;currentSubthreads=[];currentWorkerStatus={state:"initial"};initState(){this.setupSubscriptions(),lr8(this)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions()}setupSubscriptions(){let{threadService:J,worker:Q}=this.widget.props,Z=J.observePatches(Q.thread.id).pipe(cV()).subscribe((K)=>{this.dispatch({type:"main-thread-patch",thread:K,subthreads:this.currentSubthreads,workerStatus:this.currentWorkerStatus})});this.subscriptions.push(Z);let X=Q.status.subscribe((K)=>{this.currentWorkerStatus=K,this.dispatch({type:"worker-status-change",workerStatus:K})});this.subscriptions.push(X);let Y=Q.subthreads.subscribe((K)=>{this.currentSubthreads=K;for(let q of K){if(this.subthreadSubs.has(q.toolUse.id))continue;let G=J.observePatches(q.threadID).pipe(cV()).subscribe((z)=>{this.dispatch({type:"subthread-patch",thread:z,subthread:q})});this.subthreadSubs.set(q.toolUse.id,G)}});this.subscriptions.push(Y)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[],this.subthreadSubs.forEach((J)=>J.unsubscribe()),this.subthreadSubs.clear()}switchWorker(J){this.cleanup(),this.setState(()=>{this.state={subagents:{},tools:{},items:[],activeTools:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null},this.currentSubthreads=[],this.currentWorkerStatus={state:"initial"}});let{threadService:Q}=this.widget.props,Z=sM()||J,X=Q.observePatches(Z.thread.id).pipe(cV()).subscribe((q)=>{this.dispatch({type:"main-thread-patch",thread:q,subthreads:this.currentSubthreads,workerStatus:this.currentWorkerStatus})});this.subscriptions.push(X);let Y=J.status.subscribe((q)=>{this.currentWorkerStatus=q,this.dispatch({type:"worker-status-change",workerStatus:q})});this.subscriptions.push(Y);let K=J.subthreads.subscribe((q)=>{this.currentSubthreads=q;for(let G of q){if(this.subthreadSubs.has(G.toolUse.id))continue;let z=Q.observePatches(G.threadID).pipe(cV()).subscribe((U)=>{this.dispatch({type:"subthread-patch",thread:U,subthread:G})});this.subthreadSubs.set(G.toolUse.id,z)}});this.subscriptions.push(K)}dispatch(J){this.setState(()=>{this.state=pr8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((K)=>({toolUse:K.toolUse,toolRun:K.toolRun,subthreadID:K.subthreadID})),Q={};for(let K of Object.values(this.state.subagents)){let q=J.filter((G)=>G.subthreadID===K.subThreadID);Q[K.parentToolID]=q}let Z=(K)=>K==="oracle"||K==="finder"||K==="fast_finder"||K==="xai_finder"||K==="kimiK2_finder"||K==="gossip_finder"||K==="sonoma_finder",X=new Map;for(let K of this.state.activeTools)if(Z(K.toolUse.name))X.set(K.toolUse.id,{toolUseId:K.toolUse.id,toolName:K.toolUse.name,toolRun:K.toolRun});for(let K of this.state.items)if(K.type==="toolResult"&&Z(K.toolUse.name))X.set(K.toolUse.id,{toolUseId:K.toolUse.id,toolName:K.toolUse.name,toolRun:K.toolResult.run});let Y=Array.from(X.values());for(let{toolUseId:K,toolName:q,toolRun:G}of Y){let z=[],U;if(G.status==="in-progress"||G.status==="done"||G.status==="error"||G.status==="cancelled")U=G.progress;if(U){let W=0;for(let F of U)if(F.tool_uses)for(let H of F.tool_uses){let B=`${K}:progress:${W++}`;z.push({toolUse:{type:"tool_use",id:B,name:H.tool_name,input:H.input},toolRun:{status:H.status}})}}Q[K]=z}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q)}}});var L26={};V6(L26,{startSSEConnection:()=>y_1,generateClientID:()=>x_1,connectCommand:()=>f_1,connectBackground:()=>nr8});import*as N26 from"node:https";function x_1(J){let{generateClientID:Q}=(rJ1(),vX6(fd1));return Q(J)}async function b_1(J,Q){let Z=await d8(),X=await Z.secrets.getToken("apiKey",Z.settings.url);if(!X)throw Error("API key not found");let Y=Z.settings.url;if(!Y)throw Error("amp.url is not set");let K=await fetch(new URL(`/api/clients/${J}/receipt`,Y),{method:"POST",headers:{...KY(),"Content-Type":"application/json",Authorization:`Bearer ${X}`},body:JSON.stringify({messageID:Q.toString()})});if(!K.ok){let q=await K.text();throw Error(`Failed to confirm receipt: ${K.status} ${q}`)}}async function ir8(J,Q,Z,X){try{let Y=sM()||J.worker,q=Y.thread.v,G=X.v;if(G<q){l.debug(`Skipping stale message v${G} < current v${q}`),await b_1(Z,X);return}await Y.handle({type:"user:message",message:{content:Q.content,fileMentions:Q.fileMentions,userState:Q.userState,agentMode:Q.agentMode,meta:Q.meta,source:Q.source}}),await b_1(Z,X),l.debug(`Successfully processed message ${X.toString()}`)}catch(Y){l.error("Error processing received message:",Y),await b_1(Z,X)}}async function ar8(J,Q,Z={}){let X=await d8(Z.signal),Y=await X.secrets.getToken("apiKey",X.settings.url);if(!Y)throw Error("API key not found");let K=X.settings.url;if(!K)throw Error("amp.url is not set");let q=new URL(`/api/clients/${Q}/subscription`,K),G=Z.timeout||55000;return new Promise((z,U)=>{let W=Z.lastEventId,F=!1,B={method:"POST",headers:{Authorization:`Bearer ${Y}`,Accept:"text/event-stream","Cache-Control":"no-cache","Content-Type":"application/json",...W&&{"Last-Event-ID":W},...Z.currentThreadID&&{"X-Current-Thread-ID":Z.currentThreadID}},rejectUnauthorized:!1},M=!1,V=setTimeout(()=>{l.debug(`Connection timeout after ${G}ms, closing to reconnect`),M=!0,N.destroy(),z({lastEventId:W})},G),N=N26.request(q,B,(L)=>{if(L.statusCode!==200){if(clearTimeout(V),L.statusCode===409){let O="";L.on("data",(j)=>{O+=j.toString()}),L.on("end",()=>{try{let I=(JSON.parse(O).message||"Client already subscribed to another thread").match(/Client (\S+) is already subscribed/),w=I?I[1]:"another client";U(Error(`Another client is connected with ${w}.
4492
4492
  Disconnect that client first.`))}catch{U(Error(`Another client is connected with this client ID.
4493
4493
  Disconnect that client first.`))}});return}U(Error(`Connection failed: ${L.statusCode} ${L.statusMessage}`));return}l.debug(`SSE connection established${W?` with Last-Event-ID: ${W}`:""}`);let A=gj({onEvent(O){if(O.id)W=O.id;if(O.data)try{let j=JSON.parse(O.data);if(j.action?.type==="disconnect"){if(l.info("Received disconnect action from server - user disconnected via web interface"),F=!0,Z.onDisconnectAction)Z.onDisconnectAction();N.destroy();return}if(O.event==="user-message"&&j.content){let R=j,I=m21.of(O.id||"");ir8(J,R,Q,I).catch((w)=>l.error("Error processing message in background:",w))}}catch(j){l.error("Failed to parse SSE message:",j)}}});L.on("data",(O)=>{A.feed(O.toString())}),L.on("end",()=>{clearTimeout(V),l.debug("SSE connection ended normally"),z({lastEventId:W})}),L.on("error",(O)=>{if(clearTimeout(V),!M&&!F)l.error("SSE response error:",O);if(!F)U(O);else z({lastEventId:W})})});if(N.on("error",(L)=>{if(clearTimeout(V),!M&&!F)l.error("SSE request error:",L);if(!F)U(L);else z({lastEventId:W})}),Z.signal)Z.signal.addEventListener("abort",()=>{clearTimeout(V),N.destroy(),z({lastEventId:W})});N.end()})}async function y_1(J,Q,Z={}){let X=(await d8()).settings.url;l.info(`Connecting to Amp server at ${X}`),l.info(`Client ID: ${Q}`);let Y,K=0,q=3,G=!1;while(!Z.signal?.aborted&&!G)try{if(l.info(`${K===0?"Connected":"Reconnected"} to Amp Connect - ready to receive messages from web interface`),Y=(await ar8(J,Q,{signal:Z.signal,lastEventId:Y,timeout:55000,currentThreadID:Z.currentThreadID,onDisconnectAction:()=>{G=!0}})).lastEventId,K=0,G){if(l.info("Connection closed by user via web interface"),Z.onUserDisconnect)Z.onUserDisconnect();break}if(!Z.signal?.aborted)l.debug("Connection ended, reconnecting in 1 second..."),await new Promise((U)=>setTimeout(U,1000))}catch(z){if(z.name==="AbortError"||Z.signal?.aborted){l.debug("Connection aborted");break}if(z.message.includes("Already connected:"))throw l.error("Connection failed - client already subscribed:",z.message),z;if(K++,K>=q)throw l.error(`Connection failed after ${q} retries:`,z),z;let U=Math.min(1000*Math.pow(2,K-1),1e4);l.warn(`Connection attempt ${K} failed, retrying in ${U}ms:`,z.message),await new Promise((W)=>setTimeout(W,U))}}async function f_1(J,Q={}){if(Q.skipServerConnection){l.info("Skipping server connection (test mode)");return}let Z=x_1(Q.clientId),X=new AbortController,Y=()=>{l.info("Disconnecting from Amp Connect..."),X.abort()};process.on("SIGINT",Y),process.on("SIGTERM",Y);try{await y_1(J,Z,{signal:X.signal})}catch(K){if(K.name==="AbortError")l.info("Connection aborted");else throw l.error("Connection failed:",K),K}finally{process.off("SIGINT",Y),process.off("SIGTERM",Y)}}async function nr8(J,Q={}){if(Q.skipServerConnection)return l.info("Skipping server connection (test mode)"),Promise.resolve();let Z=x_1(Q.clientId),X=new AbortController,Y;if("worker"in J&&J.worker?.thread?.id)Y=J.worker.thread.id,l.info(`Connecting with active thread: ${Y}`);let K=y_1(J,Z,{signal:X.signal,currentThreadID:Y,onUserDisconnect:Q.onUserDisconnect}).catch((q)=>{if(q.name!=="AbortError")l.error("Background connection failed:",q);throw q});return{clientID:Z,disconnect:()=>{l.info("Disconnecting background connection..."),X.abort()},promise:K}}var h_1=B1(()=>{F0();O2();CG();Xc();c21()});var W76=t((U76)=>{Object.defineProperty(U76,"__esModule",{value:!0});var vt8=DL1(),kt8=NL1(),_t8=IL1(),bt8=TL1(),z76=CL1(),xt8=[vt8.default,kt8.default,(0,_t8.default)(),bt8.default,z76.metadataVocabulary,z76.contentVocabulary];U76.default=xt8});var F76=t((tX2,ft8)=>{ft8.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var B76=t((sZ,Mb1)=>{Object.defineProperty(sZ,"__esModule",{value:!0});sZ.MissingRefError=sZ.ValidationError=sZ.CodeGen=sZ.Name=sZ.nil=sZ.stringify=sZ.str=sZ._=sZ.KeywordCxt=sZ.Ajv=void 0;var ht8=BL1(),gt8=W76(),mt8=vL1(),H76=F76(),ut8=["/properties"],D41="http://json-schema.org/draft-07/schema";class Vm extends ht8.default{_addVocabularies(){if(super._addVocabularies(),gt8.default.forEach((J)=>this.addVocabulary(J)),this.opts.discriminator)this.addKeyword(mt8.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let J=this.opts.$data?this.$dataMetaSchema(H76,ut8):H76;this.addMetaSchema(J,D41,!1),this.refs["http://json-schema.org/schema"]=D41}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(D41)?D41:void 0)}}sZ.Ajv=Vm;Mb1.exports=sZ=Vm;Mb1.exports.Ajv=Vm;Object.defineProperty(sZ,"__esModule",{value:!0});sZ.default=Vm;var pt8=pI();Object.defineProperty(sZ,"KeywordCxt",{enumerable:!0,get:function(){return pt8.KeywordCxt}});var UT=x8();Object.defineProperty(sZ,"_",{enumerable:!0,get:function(){return UT._}});Object.defineProperty(sZ,"str",{enumerable:!0,get:function(){return UT.str}});Object.defineProperty(sZ,"stringify",{enumerable:!0,get:function(){return UT.stringify}});Object.defineProperty(sZ,"nil",{enumerable:!0,get:function(){return UT.nil}});Object.defineProperty(sZ,"Name",{enumerable:!0,get:function(){return UT.Name}});Object.defineProperty(sZ,"CodeGen",{enumerable:!0,get:function(){return UT.CodeGen}});var dt8=eb();Object.defineProperty(sZ,"ValidationError",{enumerable:!0,get:function(){return dt8.default}});var ct8=dI();Object.defineProperty(sZ,"MissingRefError",{enumerable:!0,get:function(){return ct8.default}})});var Ob1=t((YK2,k76)=>{k76.exports=(J,Q=process.argv)=>{let Z=J.startsWith("-")?"":J.length===1?"-":"--",X=Q.indexOf(Z+J),Y=Q.indexOf("--");return X!==-1&&(Y===-1||X<Y)}});var x76=t((KK2,b76)=>{var ue8=s1("os"),_76=s1("tty"),wK=Ob1(),{env:p5}=process,eM;if(wK("no-color")||wK("no-colors")||wK("color=false")||wK("color=never"))eM=0;else if(wK("color")||wK("colors")||wK("color=true")||wK("color=always"))eM=1;if("FORCE_COLOR"in p5)if(p5.FORCE_COLOR==="true")eM=1;else if(p5.FORCE_COLOR==="false")eM=0;else eM=p5.FORCE_COLOR.length===0?1:Math.min(parseInt(p5.FORCE_COLOR,10),3);function jb1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function Rb1(J,Q){if(eM===0)return 0;if(wK("color=16m")||wK("color=full")||wK("color=truecolor"))return 3;if(wK("color=256"))return 2;if(J&&!Q&&eM===void 0)return 0;let Z=eM||0;if(p5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=ue8.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in p5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in p5))||p5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in p5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(p5.TEAMCITY_VERSION)?1:0;if(p5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in p5){let X=parseInt((p5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(p5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(p5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(p5.TERM))return 1;if("COLORTERM"in p5)return 1;return Z}function pe8(J){let Q=Rb1(J,J&&J.isTTY);return jb1(Q)}b76.exports={supportsColor:pe8,stdout:jb1(Rb1(!0,_76.isatty(1))),stderr:jb1(Rb1(!0,_76.isatty(2)))}});var h76=t((qK2,f76)=>{var de8=x76(),FT=Ob1();function y76(J){if(/^\d{3,4}$/.test(J)){let Z=/(\d{1,2})(\d{2})/.exec(J)||[];return{major:0,minor:parseInt(Z[1],10),patch:parseInt(Z[2],10)}}let Q=(J||"").split(".").map((Z)=>parseInt(Z,10));return{major:Q[0],minor:Q[1],patch:Q[2]}}function wb1(J){let{CI:Q,FORCE_HYPERLINK:Z,NETLIFY:X,TEAMCITY_VERSION:Y,TERM_PROGRAM:K,TERM_PROGRAM_VERSION:q,VTE_VERSION:G,TERM:z}=process.env;if(Z)return!(Z.length>0&&parseInt(Z,10)===0);if(FT("no-hyperlink")||FT("no-hyperlinks")||FT("hyperlink=false")||FT("hyperlink=never"))return!1;if(FT("hyperlink=true")||FT("hyperlink=always"))return!0;if(X)return!0;if(!de8.supportsColor(J))return!1;if(J&&!J.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if(process.platform==="win32")return!1;if(Q)return!1;if(Y)return!1;if(K){let U=y76(q||"");switch(K){case"iTerm.app":if(U.major===3)return U.minor>=1;return U.major>3;case"WezTerm":return U.major>=20200620;case"vscode":return U.major>1||U.major===1&&U.minor>=72;case"ghostty":return!0}}if(G){if(G==="0.50.0")return!1;let U=y76(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}f76.exports={supportsHyperlink:wb1,stdout:wb1(process.stdout),stderr:wb1(process.stderr)}});var A56={};V6(A56,{setTerminalFocused:()=>J09,initFocusTracking:()=>e19,getTerminalFocused:()=>cb1});function e19(J){let Q=(Z)=>{if(Z.type==="focus")db1=Z.focused};J.onFocus(Q)}function cb1(){return db1}function J09(J){db1=J}var db1=!0;var j56={};V6(j56,{initIdleTracking:()=>Q09,getIsIdle:()=>lb1});function Q09(J,Q=300000){O56=Q,$41=Date.now(),J.onKey(()=>{$41=Date.now()}),J.onMouse(()=>{$41=Date.now()})}function lb1(){return Date.now()-$41>=O56}var $41,O56=300000;var ib1=B1(()=>{$41=Date.now()});var c41=t((o56)=>{Object.defineProperty(o56,"__esModule",{value:!0});function W09(J){var Q=new Uint32Array(1);return Q[0]=J[0]*1664525+1013904223,Q}o56.default=W09});var ZJ6=t((JJ6)=>{Object.defineProperty(JJ6,"__esModule",{value:!0});JJ6.makeNoise2D=void 0;var l41=c41(),H09=0.02127659574468085,jx1=(Math.sqrt(3)-1)/2,B09=(1/Math.sqrt(3)-1)/2;function t56(J,Q,Z){return{dx:-Q-J*jx1,dy:-Z-J*jx1,xsb:Q,ysb:Z}}function D09(J){var Q=[];for(var Z=0;Z<pm.length;Z+=4){var X=M09[pm[Z]],Y=null,K=null;for(var q=0;q<X.length;q+=3){if(K=t56(X[q],X[q+1],X[q+2]),Y===null)Q[Z/4]=K;else Y.next=K;Y=K}K.next=t56(pm[Z+1],pm[Z+2],pm[Z+3])}var G=[];for(var Z=0;Z<Ox1.length;Z+=2)G[Ox1[Z]]=Q[Ox1[Z+1]];var z=new Uint8Array(256),U=new Uint8Array(256),W=new Uint8Array(256);for(var Z=0;Z<256;Z++)W[Z]=Z;var F=new Uint32Array(1);F[0]=J,F=l41.default(l41.default(l41.default(F)));for(var Z=255;Z>=0;Z--){F=l41.default(F);var H=new Uint32Array(1);if(H[0]=(F[0]+31)%(Z+1),H[0]<0)H[0]+=Z+1;z[Z]=W[H[0]],U[Z]=z[Z]&14,W[H[0]]=W[Z]}return function(B,M){var V=(B+M)*B09,N=B+V,L=M+V,A=Math.floor(N),O=Math.floor(L),j=(A+O)*jx1,R=B-(A+j),I=M-(O+j),w=N-A,E=L-O,$=w+E,P=w-E+1|$<<1|$+E<<2|$+w<<4,C=0;for(var k=G[P];k!==void 0;k=k.next){var g=R+k.dx,T=I+k.dy,v=2-g*g-T*T;if(v>0){var f=A+k.xsb,h=O+k.ysb,S=z[f&255],x=U[S+h&255],b=e56[x]*g+e56[x+1]*T;C+=v*v*v*v*b}}return C*H09}}JJ6.makeNoise2D=D09;var M09=[[1,1,0,1,0,1,0,0,0],[1,1,0,1,0,1,2,1,1]],e56=[5,2,2,5,-5,2,-2,5,5,-2,2,-5,-5,-2,-2,-5],Ox1=[0,1,1,0,4,1,17,0,20,2,21,2,22,5,23,5,26,4,39,3,42,4,43,3],pm=[0,0,1,-1,0,0,-1,1,0,2,1,1,1,2,2,0,1,2,0,2,1,0,0,0]});var KJ6=t((XJ6)=>{Object.defineProperty(XJ6,"__esModule",{value:!0});XJ6.makeNoise3D=void 0;var i41=c41(),V09=0.009708737864077669,a41=(Math.sqrt(4)-1)/3,N09=(1/Math.sqrt(4)-1)/3;function Rx1(J,Q,Z,X){return{dx:-Q-J*a41,dy:-Z-J*a41,dz:-X-J*a41,xsb:Q,ysb:Z,zsb:X}}function L09(J){var Q=[];for(var Z=0;Z<AU.length;Z+=9){var X=A09[AU[Z]],Y=null,K=null;for(var q=0;q<X.length;q+=4){if(K=Rx1(X[q],X[q+1],X[q+2],X[q+3]),Y===null)Q[Z/9]=K;else Y.next=K;Y=K}K.next=Rx1(AU[Z+1],AU[Z+2],AU[Z+3],AU[Z+4]),K.next.next=Rx1(AU[Z+5],AU[Z+6],AU[Z+7],AU[Z+8])}var G=[];for(var Z=0;Z<Ix1.length;Z+=2)G[Ix1[Z]]=Q[Ix1[Z+1]];var z=new Uint8Array(256),U=new Uint8Array(256),W=new Uint8Array(256);for(var Z=0;Z<256;Z++)W[Z]=Z;var F=new Uint32Array(1);F[0]=J,F=i41.default(i41.default(i41.default(F)));for(var Z=255;Z>=0;Z--){F=i41.default(F);var H=new Uint32Array(1);if(H[0]=(F[0]+31)%(Z+1),H[0]<0)H[0]+=Z+1;z[Z]=W[H[0]],U[Z]=z[Z]%24*3,W[H[0]]=W[Z]}return function(B,M,V){var N=(B+M+V)*N09,L=B+N,A=M+N,O=V+N,j=Math.floor(L),R=Math.floor(A),I=Math.floor(O),w=(j+R+I)*a41,E=B-(j+w),$=M-(R+w),P=V-(I+w),C=L-j,k=A-R,g=O-I,T=C+k+g,v=k-g+1|C-k+1<<1|C-g+1<<2|T<<3|T+g<<5|T+k<<7|T+C<<9,f=0;for(var h=G[v];h!==void 0;h=h.next){var S=E+h.dx,x=$+h.dy,b=P+h.dz,m=2-S*S-x*x-b*b;if(m>0){var a=j+h.xsb,u=R+h.ysb,J1=I+h.zsb,G1=z[a&255],W1=z[G1+u&255],Z1=U[W1+J1&255],F1=wx1[Z1]*S+wx1[Z1+1]*x+wx1[Z1+2]*b;f+=m*m*m*m*F1}}return f*V09}}XJ6.makeNoise3D=L09;var A09=[[0,0,0,0,1,1,0,0,1,0,1,0,1,0,0,1],[2,1,1,0,2,1,0,1,2,0,1,1,3,1,1,1],[1,1,0,0,1,0,1,0,1,0,0,1,2,1,1,0,2,1,0,1,2,0,1,1]],wx1=[-11,4,4,-4,11,4,-4,4,11,11,4,4,4,11,4,4,4,11,-11,-4,4,-4,-11,4,-4,-4,11,11,-4,4,4,-11,4,4,-4,11,-11,4,-4,-4,11,-4,-4,4,-11,11,4,-4,4,11,-4,4,4,-11,-11,-4,-4,-4,-11,-4,-4,-4,-11,11,-4,-4,4,-11,-4,4,-4,-11],Ix1=[0,2,1,1,2,2,5,1,6,0,7,0,32,2,34,2,129,1,133,1,160,5,161,5,518,0,519,0,546,4,550,4,645,3,647,3,672,5,673,5,674,4,677,3,678,4,679,3,680,13,681,13,682,12,685,14,686,12,687,14,712,20,714,18,809,21,813,23,840,20,841,21,1198,19,1199,22,1226,18,1230,19,1325,23,1327,22,1352,15,1353,17,1354,15,1357,17,1358,16,1359,16,1360,11,1361,10,1362,11,1365,10,1366,9,1367,9,1392,11,1394,11,1489,10,1493,10,1520,8,1521,8,1878,9,1879,9,1906,7,1910,7,2005,6,2007,6,2032,8,2033,8,2034,7,2037,6,2038,7,2039,6],AU=[0,0,1,-1,0,0,1,0,-1,0,0,-1,1,0,0,0,1,-1,0,0,-1,0,1,0,0,-1,1,0,2,1,1,0,1,1,1,-1,0,2,1,0,1,1,1,-1,1,0,2,0,1,1,1,-1,1,1,1,3,2,1,0,3,1,2,0,1,3,2,0,1,3,1,0,2,1,3,0,2,1,3,0,1,2,1,1,1,0,0,2,2,0,0,1,1,0,1,0,2,0,2,0,1,1,0,0,1,2,0,0,2,2,0,0,0,0,1,1,-1,1,2,0,0,0,0,1,-1,1,1,2,0,0,0,0,1,1,1,-1,2,3,1,1,1,2,0,0,2,2,3,1,1,1,2,2,0,0,2,3,1,1,1,2,0,2,0,2,1,1,-1,1,2,0,0,2,2,1,1,-1,1,2,2,0,0,2,1,-1,1,1,2,0,0,2,2,1,-1,1,1,2,0,2,0,2,1,1,1,-1,2,2,0,0,2,1,1,1,-1,2,0,2,0]});var zJ6=t((qJ6)=>{Object.defineProperty(qJ6,"__esModule",{value:!0});qJ6.makeNoise4D=void 0;var n41=c41(),O09=0.03333333333333333,dm=(Math.sqrt(5)-1)/4,j09=(1/Math.sqrt(5)-1)/4;function r41(J,Q,Z,X,Y){return{dx:-Q-J*dm,dy:-Z-J*dm,dz:-X-J*dm,dw:-Y-J*dm,xsb:Q,ysb:Z,zsb:X,wsb:Y}}function R09(J){var Q=[];for(var Z=0;Z<VJ.length;Z+=16){var X=w09[VJ[Z]],Y=null,K=null;for(var q=0;q<X.length;q+=5){if(K=r41(X[q],X[q+1],X[q+2],X[q+3],X[q+4]),Y===null)Q[Z/16]=K;else Y.next=K;Y=K}K.next=r41(VJ[Z+1],VJ[Z+2],VJ[Z+3],VJ[Z+4],VJ[Z+5]),K.next.next=r41(VJ[Z+6],VJ[Z+7],VJ[Z+8],VJ[Z+9],VJ[Z+10]),K.next.next.next=r41(VJ[Z+11],VJ[Z+12],VJ[Z+13],VJ[Z+14],VJ[Z+15])}var G=[];for(var Z=0;Z<Ex1.length;Z+=2)G[Ex1[Z]]=Q[Ex1[Z+1]];var z=new Uint8Array(256),U=new Uint8Array(256),W=new Uint8Array(256);for(var Z=0;Z<256;Z++)W[Z]=Z;var F=new Uint32Array(1);F[0]=J,F=n41.default(n41.default(n41.default(F)));for(var Z=255;Z>=0;Z--){F=n41.default(F);var H=new Uint32Array(1);if(H[0]=(F[0]+31)%(Z+1),H[0]<0)H[0]+=Z+1;z[Z]=W[H[0]],U[Z]=z[Z]&252,W[H[0]]=W[Z]}return function(B,M,V,N){var L=(B+M+V+N)*j09,A=B+L,O=M+L,j=V+L,R=N+L,I=Math.floor(A),w=Math.floor(O),E=Math.floor(j),$=Math.floor(R),P=(I+w+E+$)*dm,C=B-(I+P),k=M-(w+P),g=V-(E+P),T=N-($+P),v=A-I,f=O-w,h=j-E,S=R-$,x=v+f+h+S,b=h-S+1|f-h+1<<1|f-S+1<<2|v-f+1<<3|v-h+1<<4|v-S+1<<5|x<<6|x+S<<8|x+h<<11|x+f<<14|x+v<<17,m=0;for(var a=G[b];a!==void 0;a=a.next){var u=C+a.dx,J1=k+a.dy,G1=g+a.dz,W1=T+a.dw,Z1=2-u*u-J1*J1-G1*G1-W1*W1;if(Z1>0){var F1=I+a.xsb,d=w+a.ysb,p=E+a.zsb,i=$+a.wsb,n=z[F1&255],s=z[n+d&255],Y1=z[s+p&255],Q1=U[Y1+i&255],H1=s41[Q1]*u+s41[Q1+1]*J1+s41[Q1+2]*G1+s41[Q1+3]*W1;m+=Z1*Z1*Z1*Z1*H1}}return m*O09}}qJ6.makeNoise4D=R09;var w09=[[0,0,0,0,0,1,1,0,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1],[3,1,1,1,0,3,1,1,0,1,3,1,0,1,1,3,0,1,1,1,4,1,1,1,1],[1,1,0,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,2,1,1,0,0,2,1,0,1,0,2,1,0,0,1,2,0,1,1,0,2,0,1,0,1,2,0,0,1,1],[3,1,1,1,0,3,1,1,0,1,3,1,0,1,1,3,0,1,1,1,2,1,1,0,0,2,1,0,1,0,2,1,0,0,1,2,0,1,1,0,2,0,1,0,1,2,0,0,1,1]],s41=[3,1,1,1,1,3,1,1,1,1,3,1,1,1,1,3,-3,1,1,1,-1,3,1,1,-1,1,3,1,-1,1,1,3,3,-1,1,1,1,-3,1,1,1,-1,3,1,1,-1,1,3,-3,-1,1,1,-1,-3,1,1,-1,-1,3,1,-1,-1,1,3,3,1,-1,1,1,3,-1,1,1,1,-3,1,1,1,-1,3,-3,1,-1,1,-1,3,-1,1,-1,1,-3,1,-1,1,-1,3,3,-1,-1,1,1,-3,-1,1,1,-1,-3,1,1,-1,-1,3,-3,-1,-1,1,-1,-3,-1,1,-1,-1,-3,1,-1,-1,-1,3,3,1,1,-1,1,3,1,-1,1,1,3,-1,1,1,1,-3,-3,1,1,-1,-1,3,1,-1,-1,1,3,-1,-1,1,1,-3,3,-1,1,-1,1,-3,1,-1,1,-1,3,-1,1,-1,1,-3,-3,-1,1,-1,-1,-3,1,-1,-1,-1,3,-1,-1,-1,1,-3,3,1,-1,-1,1,3,-1,-1,1,1,-3,-1,1,1,-1,-3,-3,1,-1,-1,-1,3,-1,-1,-1,1,-3,-1,-1,1,-1,-3,3,-1,-1,-1,1,-3,-1,-1,1,-1,-3,-1,1,-1,-1,-3,-3,-1,-1,-1,-1,-3,-1,-1,-1,-1,-3,-1,-1,-1,-1,-3],Ex1=[0,3,1,2,2,3,5,2,6,1,7,1,8,3,9,2,10,3,13,2,16,3,18,3,22,1,23,1,24,3,26,3,33,2,37,2,38,1,39,1,41,2,45,2,54,1,55,1,56,0,57,0,58,0,59,0,60,0,61,0,62,0,63,0,256,3,258,3,264,3,266,3,272,3,274,3,280,3,282,3,2049,2,2053,2,2057,2,2061,2,2081,2,2085,2,2089,2,2093,2,2304,9,2305,9,2312,9,2313,9,16390,1,16391,1,16406,1,16407,1,16422,1,16423,1,16438,1,16439,1,16642,8,16646,8,16658,8,16662,8,18437,6,18439,6,18469,6,18471,6,18688,9,18689,9,18690,8,18693,6,18694,8,18695,6,18696,9,18697,9,18706,8,18710,8,18725,6,18727,6,131128,0,131129,0,131130,0,131131,0,131132,0,131133,0,131134,0,131135,0,131352,7,131354,7,131384,7,131386,7,133161,5,133165,5,133177,5,133181,5,133376,9,133377,9,133384,9,133385,9,133400,7,133402,7,133417,5,133421,5,133432,7,133433,5,133434,7,133437,5,147510,4,147511,4,147518,4,147519,4,147714,8,147718,8,147730,8,147734,8,147736,7,147738,7,147766,4,147767,4,147768,7,147770,7,147774,4,147775,4,149509,6,149511,6,149541,6,149543,6,149545,5,149549,5,149558,4,149559,4,149561,5,149565,5,149566,4,149567,4,149760,9,149761,9,149762,8,149765,6,149766,8,149767,6,149768,9,149769,9,149778,8,149782,8,149784,7,149786,7,149797,6,149799,6,149801,5,149805,5,149814,4,149815,4,149816,7,149817,5,149818,7,149821,5,149822,4,149823,4,149824,37,149825,37,149826,36,149829,34,149830,36,149831,34,149832,37,149833,37,149842,36,149846,36,149848,35,149850,35,149861,34,149863,34,149865,33,149869,33,149878,32,149879,32,149880,35,149881,33,149882,35,149885,33,149886,32,149887,32,150080,49,150082,48,150088,49,150098,48,150104,47,150106,47,151873,46,151877,45,151881,46,151909,45,151913,44,151917,44,152128,49,152129,46,152136,49,152137,46,166214,43,166215,42,166230,43,166247,42,166262,41,166263,41,166466,48,166470,43,166482,48,166486,43,168261,45,168263,42,168293,45,168295,42,168512,31,168513,28,168514,31,168517,28,168518,25,168519,25,280952,40,280953,39,280954,40,280957,39,280958,38,280959,38,281176,47,281178,47,281208,40,281210,40,282985,44,282989,44,283001,39,283005,39,283208,30,283209,27,283224,30,283241,27,283256,22,283257,22,297334,41,297335,41,297342,38,297343,38,297554,29,297558,24,297562,29,297590,24,297594,21,297598,21,299365,26,299367,23,299373,26,299383,23,299389,20,299391,20,299584,31,299585,28,299586,31,299589,28,299590,25,299591,25,299592,30,299593,27,299602,29,299606,24,299608,30,299610,29,299621,26,299623,23,299625,27,299629,26,299638,24,299639,23,299640,22,299641,22,299642,21,299645,20,299646,21,299647,20,299648,61,299649,60,299650,61,299653,60,299654,59,299655,59,299656,58,299657,57,299666,55,299670,54,299672,58,299674,55,299685,52,299687,51,299689,57,299693,52,299702,54,299703,51,299704,56,299705,56,299706,53,299709,50,299710,53,299711,50,299904,61,299906,61,299912,58,299922,55,299928,58,299930,55,301697,60,301701,60,301705,57,301733,52,301737,57,301741,52,301952,79,301953,79,301960,76,301961,76,316038,59,316039,59,316054,54,316071,51,316086,54,316087,51,316290,78,316294,78,316306,73,316310,73,318085,77,318087,77,318117,70,318119,70,318336,79,318337,79,318338,78,318341,77,318342,78,318343,77,430776,56,430777,56,430778,53,430781,50,430782,53,430783,50,431000,75,431002,72,431032,75,431034,72,432809,74,432813,69,432825,74,432829,69,433032,76,433033,76,433048,75,433065,74,433080,75,433081,74,447158,71,447159,68,447166,71,447167,68,447378,73,447382,73,447386,72,447414,71,447418,72,447422,71,449189,70,449191,70,449197,69,449207,68,449213,69,449215,68,449408,67,449409,67,449410,66,449413,64,449414,66,449415,64,449416,67,449417,67,449426,66,449430,66,449432,65,449434,65,449445,64,449447,64,449449,63,449453,63,449462,62,449463,62,449464,65,449465,63,449466,65,449469,63,449470,62,449471,62,449472,19,449473,19,449474,18,449477,16,449478,18,449479,16,449480,19,449481,19,449490,18,449494,18,449496,17,449498,17,449509,16,449511,16,449513,15,449517,15,449526,14,449527,14,449528,17,449529,15,449530,17,449533,15,449534,14,449535,14,449728,19,449729,19,449730,18,449734,18,449736,19,449737,19,449746,18,449750,18,449752,17,449754,17,449784,17,449786,17,451520,19,451521,19,451525,16,451527,16,451528,19,451529,19,451557,16,451559,16,451561,15,451565,15,451577,15,451581,15,451776,19,451777,19,451784,19,451785,19,465858,18,465861,16,465862,18,465863,16,465874,18,465878,18,465893,16,465895,16,465910,14,465911,14,465918,14,465919,14,466114,18,466118,18,466130,18,466134,18,467909,16,467911,16,467941,16,467943,16,468160,13,468161,13,468162,13,468163,13,468164,13,468165,13,468166,13,468167,13,580568,17,580570,17,580585,15,580589,15,580598,14,580599,14,580600,17,580601,15,580602,17,580605,15,580606,14,580607,14,580824,17,580826,17,580856,17,580858,17,582633,15,582637,15,582649,15,582653,15,582856,12,582857,12,582872,12,582873,12,582888,12,582889,12,582904,12,582905,12,596982,14,596983,14,596990,14,596991,14,597202,11,597206,11,597210,11,597214,11,597234,11,597238,11,597242,11,597246,11,599013,10,599015,10,599021,10,599023,10,599029,10,599031,10,599037,10,599039,10,599232,13,599233,13,599234,13,599235,13,599236,13,599237,13,599238,13,599239,13,599240,12,599241,12,599250,11,599254,11,599256,12,599257,12,599258,11,599262,11,599269,10,599271,10,599272,12,599273,12,599277,10,599279,10,599282,11,599285,10,599286,11,599287,10,599288,12,599289,12,599290,11,599293,10,599294,11,599295,10],VJ=[0,0,1,-1,0,0,0,1,0,-1,0,0,1,0,0,-1,0,0,-1,1,0,0,0,0,1,-1,0,0,0,1,0,-1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,-1,0,0,-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,2,1,1,0,0,1,1,1,-1,0,1,1,1,0,-1,0,2,1,0,1,0,1,1,-1,1,0,1,1,0,1,-1,0,2,0,1,1,0,1,-1,1,1,0,1,0,1,1,-1,0,2,1,0,0,1,1,1,-1,0,1,1,1,0,-1,1,0,2,0,1,0,1,1,-1,1,0,1,1,0,1,-1,1,0,2,0,0,1,1,1,-1,0,1,1,1,0,-1,1,1,1,4,2,1,1,0,4,1,2,1,0,4,1,1,2,0,1,4,2,1,0,1,4,1,2,0,1,4,1,1,0,2,1,4,2,0,1,1,4,1,0,2,1,4,1,0,1,2,1,4,0,2,1,1,4,0,1,2,1,4,0,1,1,2,1,2,1,1,0,0,3,2,1,0,0,3,1,2,0,0,1,2,1,0,1,0,3,2,0,1,0,3,1,0,2,0,1,2,0,1,1,0,3,0,2,1,0,3,0,1,2,0,1,2,1,0,0,1,3,2,0,0,1,3,1,0,0,2,1,2,0,1,0,1,3,0,2,0,1,3,0,1,0,2,1,2,0,0,1,1,3,0,0,2,1,3,0,0,1,2,2,3,1,1,1,0,2,1,1,1,-1,2,2,0,0,0,2,3,1,1,0,1,2,1,1,-1,1,2,2,0,0,0,2,3,1,0,1,1,2,1,-1,1,1,2,2,0,0,0,2,3,1,1,1,0,2,1,1,1,-1,2,0,2,0,0,2,3,1,1,0,1,2,1,1,-1,1,2,0,2,0,0,2,3,0,1,1,1,2,-1,1,1,1,2,0,2,0,0,2,3,1,1,1,0,2,1,1,1,-1,2,0,0,2,0,2,3,1,0,1,1,2,1,-1,1,1,2,0,0,2,0,2,3,0,1,1,1,2,-1,1,1,1,2,0,0,2,0,2,3,1,1,0,1,2,1,1,-1,1,2,0,0,0,2,2,3,1,0,1,1,2,1,-1,1,1,2,0,0,0,2,2,3,0,1,1,1,2,-1,1,1,1,2,0,0,0,2,2,1,1,1,-1,0,1,1,1,0,-1,0,0,0,0,0,2,1,1,-1,1,0,1,1,0,1,-1,0,0,0,0,0,2,1,-1,1,1,0,1,0,1,1,-1,0,0,0,0,0,2,1,1,-1,0,1,1,1,0,-1,1,0,0,0,0,0,2,1,-1,1,0,1,1,0,1,-1,1,0,0,0,0,0,2,1,-1,0,1,1,1,0,-1,1,1,0,0,0,0,0,2,1,1,1,-1,0,1,1,1,0,-1,2,2,0,0,0,2,1,1,-1,1,0,1,1,0,1,-1,2,2,0,0,0,2,1,1,-1,0,1,1,1,0,-1,1,2,2,0,0,0,2,1,1,1,-1,0,1,1,1,0,-1,2,0,2,0,0,2,1,-1,1,1,0,1,0,1,1,-1,2,0,2,0,0,2,1,-1,1,0,1,1,0,1,-1,1,2,0,2,0,0,2,1,1,-1,1,0,1,1,0,1,-1,2,0,0,2,0,2,1,-1,1,1,0,1,0,1,1,-1,2,0,0,2,0,2,1,-1,0,1,1,1,0,-1,1,1,2,0,0,2,0,2,1,1,-1,0,1,1,1,0,-1,1,2,0,0,0,2,2,1,-1,1,0,1,1,0,1,-1,1,2,0,0,0,2,2,1,-1,0,1,1,1,0,-1,1,1,2,0,0,0,2,3,1,1,0,0,0,2,2,0,0,0,2,1,1,1,-1,3,1,0,1,0,0,2,0,2,0,0,2,1,1,1,-1,3,1,0,0,1,0,2,0,0,2,0,2,1,1,1,-1,3,1,1,0,0,0,2,2,0,0,0,2,1,1,-1,1,3,1,0,1,0,0,2,0,2,0,0,2,1,1,-1,1,3,1,0,0,0,1,2,0,0,0,2,2,1,1,-1,1,3,1,1,0,0,0,2,2,0,0,0,2,1,-1,1,1,3,1,0,0,1,0,2,0,0,2,0,2,1,-1,1,1,3,1,0,0,0,1,2,0,0,0,2,2,1,-1,1,1,3,1,0,1,0,0,2,0,2,0,0,2,-1,1,1,1,3,1,0,0,1,0,2,0,0,2,0,2,-1,1,1,1,3,1,0,0,0,1,2,0,0,0,2,2,-1,1,1,1,3,3,2,1,0,0,3,1,2,0,0,4,1,1,1,1,3,3,2,0,1,0,3,1,0,2,0,4,1,1,1,1,3,3,0,2,1,0,3,0,1,2,0,4,1,1,1,1,3,3,2,0,0,1,3,1,0,0,2,4,1,1,1,1,3,3,0,2,0,1,3,0,1,0,2,4,1,1,1,1,3,3,0,0,2,1,3,0,0,1,2,4,1,1,1,1,3,3,2,1,0,0,3,1,2,0,0,2,1,1,1,-1,3,3,2,0,1,0,3,1,0,2,0,2,1,1,1,-1,3,3,0,2,1,0,3,0,1,2,0,2,1,1,1,-1,3,3,2,1,0,0,3,1,2,0,0,2,1,1,-1,1,3,3,2,0,0,1,3,1,0,0,2,2,1,1,-1,1,3,3,0,2,0,1,3,0,1,0,2,2,1,1,-1,1,3,3,2,0,1,0,3,1,0,2,0,2,1,-1,1,1,3,3,2,0,0,1,3,1,0,0,2,2,1,-1,1,1,3,3,0,0,2,1,3,0,0,1,2,2,1,-1,1,1,3,3,0,2,1,0,3,0,1,2,0,2,-1,1,1,1,3,3,0,2,0,1,3,0,1,0,2,2,-1,1,1,1,3,3,0,0,2,1,3,0,0,1,2,2,-1,1,1,1]});var UJ6=t((cm)=>{Object.defineProperty(cm,"__esModule",{value:!0});cm.makeNoise4D=cm.makeNoise3D=cm.makeNoise2D=void 0;var I09=ZJ6();Object.defineProperty(cm,"makeNoise2D",{enumerable:!0,get:function(){return I09.makeNoise2D}});var E09=KJ6();Object.defineProperty(cm,"makeNoise3D",{enumerable:!0,get:function(){return E09.makeNoise3D}});var $09=zJ6();Object.defineProperty(cm,"makeNoise4D",{enumerable:!0,get:function(){return $09.makeNoise4D}})});var zZ6=t((mR2,$71)=>{var Q29=typeof window<"u"?window:typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?self:{},v6=function(J){var Q=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,Z=0,X={},Y={manual:J.Prism&&J.Prism.manual,disableWorkerMessageHandler:J.Prism&&J.Prism.disableWorkerMessageHandler,util:{encode:function V(N){if(N instanceof K)return new K(N.type,V(N.content),N.alias);else if(Array.isArray(N))return N.map(V);else return N.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/\u00a0/g," ")},type:function(V){return Object.prototype.toString.call(V).slice(8,-1)},objId:function(V){if(!V.__id)Object.defineProperty(V,"__id",{value:++Z});return V.__id},clone:function V(N,L){L=L||{};var A,O;switch(Y.util.type(N)){case"Object":if(O=Y.util.objId(N),L[O])return L[O];A={},L[O]=A;for(var j in N)if(N.hasOwnProperty(j))A[j]=V(N[j],L);return A;case"Array":if(O=Y.util.objId(N),L[O])return L[O];return A=[],L[O]=A,N.forEach(function(R,I){A[I]=V(R,L)}),A;default:return N}},getLanguage:function(V){while(V){var N=Q.exec(V.className);if(N)return N[1].toLowerCase();V=V.parentElement}return"none"},setLanguage:function(V,N){V.className=V.className.replace(RegExp(Q,"gi"),""),V.classList.add("language-"+N)},currentScript:function(){if(typeof document>"u")return null;if(document.currentScript&&document.currentScript.tagName==="SCRIPT")return document.currentScript;try{throw Error()}catch(A){var V=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(A.stack)||[])[1];if(V){var N=document.getElementsByTagName("script");for(var L in N)if(N[L].src==V)return N[L]}return null}},isActive:function(V,N,L){var A="no-"+N;while(V){var O=V.classList;if(O.contains(N))return!0;if(O.contains(A))return!1;V=V.parentElement}return!!L}},languages:{plain:X,plaintext:X,text:X,txt:X,extend:function(V,N){var L=Y.util.clone(Y.languages[V]);for(var A in N)L[A]=N[A];return L},insertBefore:function(V,N,L,A){A=A||Y.languages;var O=A[V],j={};for(var R in O)if(O.hasOwnProperty(R)){if(R==N){for(var I in L)if(L.hasOwnProperty(I))j[I]=L[I]}if(!L.hasOwnProperty(R))j[R]=O[R]}var w=A[V];return A[V]=j,Y.languages.DFS(Y.languages,function(E,$){if($===w&&E!=V)this[E]=j}),j},DFS:function V(N,L,A,O){O=O||{};var j=Y.util.objId;for(var R in N)if(N.hasOwnProperty(R)){L.call(N,R,N[R],A||R);var I=N[R],w=Y.util.type(I);if(w==="Object"&&!O[j(I)])O[j(I)]=!0,V(I,L,null,O);else if(w==="Array"&&!O[j(I)])O[j(I)]=!0,V(I,L,R,O)}}},plugins:{},highlightAll:function(V,N){Y.highlightAllUnder(document,V,N)},highlightAllUnder:function(V,N,L){var A={callback:L,container:V,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};Y.hooks.run("before-highlightall",A),A.elements=Array.prototype.slice.apply(A.container.querySelectorAll(A.selector)),Y.hooks.run("before-all-elements-highlight",A);for(var O=0,j;j=A.elements[O++];)Y.highlightElement(j,N===!0,A.callback)},highlightElement:function(V,N,L){var A=Y.util.getLanguage(V),O=Y.languages[A];Y.util.setLanguage(V,A);var j=V.parentElement;if(j&&j.nodeName.toLowerCase()==="pre")Y.util.setLanguage(j,A);var R=V.textContent,I={element:V,language:A,grammar:O,code:R};function w($){I.highlightedCode=$,Y.hooks.run("before-insert",I),I.element.innerHTML=I.highlightedCode,Y.hooks.run("after-highlight",I),Y.hooks.run("complete",I),L&&L.call(I.element)}if(Y.hooks.run("before-sanity-check",I),j=I.element.parentElement,j&&j.nodeName.toLowerCase()==="pre"&&!j.hasAttribute("tabindex"))j.setAttribute("tabindex","0");if(!I.code){Y.hooks.run("complete",I),L&&L.call(I.element);return}if(Y.hooks.run("before-highlight",I),!I.grammar){w(Y.util.encode(I.code));return}if(N&&J.Worker){var E=new Worker(Y.filename);E.onmessage=function($){w($.data)},E.postMessage(JSON.stringify({language:I.language,code:I.code,immediateClose:!0}))}else w(Y.highlight(I.code,I.grammar,I.language))},highlight:function(V,N,L){var A={code:V,grammar:N,language:L};if(Y.hooks.run("before-tokenize",A),!A.grammar)throw Error('The language "'+A.language+'" has no grammar.');return A.tokens=Y.tokenize(A.code,A.grammar),Y.hooks.run("after-tokenize",A),K.stringify(Y.util.encode(A.tokens),A.language)},tokenize:function(V,N){var L=N.rest;if(L){for(var A in L)N[A]=L[A];delete N.rest}var O=new z;return U(O,O.head,V),G(V,O,N,O.head,0),F(O)},hooks:{all:{},add:function(V,N){var L=Y.hooks.all;L[V]=L[V]||[],L[V].push(N)},run:function(V,N){var L=Y.hooks.all[V];if(!L||!L.length)return;for(var A=0,O;O=L[A++];)O(N)}},Token:K};J.Prism=Y;function K(V,N,L,A){this.type=V,this.content=N,this.alias=L,this.length=(A||"").length|0}K.stringify=function V(N,L){if(typeof N=="string")return N;if(Array.isArray(N)){var A="";return N.forEach(function(w){A+=V(w,L)}),A}var O={type:N.type,content:V(N.content,L),tag:"span",classes:["token",N.type],attributes:{},language:L},j=N.alias;if(j)if(Array.isArray(j))Array.prototype.push.apply(O.classes,j);else O.classes.push(j);Y.hooks.run("wrap",O);var R="";for(var I in O.attributes)R+=" "+I+'="'+(O.attributes[I]||"").replace(/"/g,"&quot;")+'"';return"<"+O.tag+' class="'+O.classes.join(" ")+'"'+R+">"+O.content+"</"+O.tag+">"};function q(V,N,L,A){V.lastIndex=N;var O=V.exec(L);if(O&&A&&O[1]){var j=O[1].length;O.index+=j,O[0]=O[0].slice(j)}return O}function G(V,N,L,A,O,j){for(var R in L){if(!L.hasOwnProperty(R)||!L[R])continue;var I=L[R];I=Array.isArray(I)?I:[I];for(var w=0;w<I.length;++w){if(j&&j.cause==R+","+w)return;var E=I[w],$=E.inside,P=!!E.lookbehind,C=!!E.greedy,k=E.alias;if(C&&!E.pattern.global){var g=E.pattern.toString().match(/[imsuy]*$/)[0];E.pattern=RegExp(E.pattern.source,g+"g")}var T=E.pattern||E;for(var v=A.next,f=O;v!==N.tail;f+=v.value.length,v=v.next){if(j&&f>=j.reach)break;var h=v.value;if(N.length>V.length)return;if(h instanceof K)continue;var S=1,x;if(C){if(x=q(T,f,V,P),!x||x.index>=V.length)break;var u=x.index,b=x.index+x[0].length,m=f;m+=v.value.length;while(u>=m)v=v.next,m+=v.value.length;if(m-=v.value.length,f=m,v.value instanceof K)continue;for(var a=v;a!==N.tail&&(m<b||typeof a.value==="string");a=a.next)S++,m+=a.value.length;S--,h=V.slice(f,m),x.index-=f}else if(x=q(T,0,h,P),!x)continue;var u=x.index,J1=x[0],G1=h.slice(0,u),W1=h.slice(u+J1.length),Z1=f+h.length;if(j&&Z1>j.reach)j.reach=Z1;var F1=v.prev;if(G1)F1=U(N,F1,G1),f+=G1.length;W(N,F1,S);var d=new K(R,$?Y.tokenize(J1,$):J1,k,J1);if(v=U(N,F1,d),W1)U(N,v,W1);if(S>1){var p={cause:R+","+w,reach:Z1};if(G(V,N,L,v.prev,f,p),j&&p.reach>j.reach)j.reach=p.reach}}}}}function z(){var V={value:null,prev:null,next:null},N={value:null,prev:V,next:null};V.next=N,this.head=V,this.tail=N,this.length=0}function U(V,N,L){var A=N.next,O={value:L,prev:N,next:A};return N.next=O,A.prev=O,V.length++,O}function W(V,N,L){var A=N.next;for(var O=0;O<L&&A!==V.tail;O++)A=A.next;N.next=A,A.prev=N,V.length-=O}function F(V){var N=[],L=V.head.next;while(L!==V.tail)N.push(L.value),L=L.next;return N}if(!J.document){if(!J.addEventListener)return Y;if(!Y.disableWorkerMessageHandler)J.addEventListener("message",function(V){var N=JSON.parse(V.data),L=N.language,A=N.code,O=N.immediateClose;if(J.postMessage(Y.highlight(A,Y.languages[L],L)),O)J.close()},!1);return Y}var H=Y.util.currentScript();if(H){if(Y.filename=H.src,H.hasAttribute("data-manual"))Y.manual=!0}function B(){if(!Y.manual)Y.highlightAll()}if(!Y.manual){var M=document.readyState;if(M==="loading"||M==="interactive"&&H&&H.defer)document.addEventListener("DOMContentLoaded",B);else if(window.requestAnimationFrame)window.requestAnimationFrame(B);else window.setTimeout(B,16)}return Y}(Q29);if(typeof $71<"u"&&$71.exports)$71.exports=v6;if(typeof global<"u")global.Prism=v6;v6.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]};v6.languages.markup.tag.inside["attr-value"].inside.entity=v6.languages.markup.entity;v6.languages.markup.doctype.inside["internal-subset"].inside=v6.languages.markup;v6.hooks.add("wrap",function(J){if(J.type==="entity")J.attributes.title=J.content.replace(/&amp;/,"&")});Object.defineProperty(v6.languages.markup.tag,"addInlined",{value:function(Q,Z){var X={};X["language-"+Z]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:v6.languages[Z]},X.cdata=/^<!\[CDATA\[|\]\]>$/i;var Y={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:X}};Y["language-"+Z]={pattern:/[\s\S]+/,inside:v6.languages[Z]};var K={};K[Q]={pattern:RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return Q}),"i"),lookbehind:!0,greedy:!0,inside:Y},v6.languages.insertBefore("markup","cdata",K)}});Object.defineProperty(v6.languages.markup.tag,"addAttribute",{value:function(J,Q){v6.languages.markup.tag.inside["special-attr"].push({pattern:RegExp(/(^|["'\s])/.source+"(?:"+J+")"+/\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,"i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[Q,"language-"+Q],inside:v6.languages[Q]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}});v6.languages.html=v6.languages.markup;v6.languages.mathml=v6.languages.markup;v6.languages.svg=v6.languages.markup;v6.languages.xml=v6.languages.extend("markup",{});v6.languages.ssml=v6.languages.xml;v6.languages.atom=v6.languages.xml;v6.languages.rss=v6.languages.xml;(function(J){var Q=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;J.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+Q.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+Q.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+Q.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+Q.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:Q,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},J.languages.css.atrule.inside.rest=J.languages.css;var Z=J.languages.markup;if(Z)Z.tag.addInlined("style","css"),Z.tag.addAttribute("style","css")})(v6);v6.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/};v6.languages.javascript=v6.languages.extend("clike",{"class-name":[v6.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(/(^|[^\w$])/.source+"(?:"+(/NaN|Infinity/.source+"|"+/0[bB][01]+(?:_[01]+)*n?/.source+"|"+/0[oO][0-7]+(?:_[0-7]+)*n?/.source+"|"+/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source+"|"+/\d+(?:_\d+)*n/.source+"|"+/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source)+")"+/(?![\w$])/.source),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/});v6.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;v6.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp(/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source+/\//.source+"(?:"+/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source+"|"+/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source+")"+/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:v6.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:v6.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:v6.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:v6.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:v6.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/});v6.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:v6.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}});v6.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}});if(v6.languages.markup)v6.languages.markup.tag.addInlined("script","javascript"),v6.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,"javascript");v6.languages.js=v6.languages.javascript;(function(){if(typeof v6>"u"||typeof document>"u")return;if(!Element.prototype.matches)Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector;var J="Loading…",Q=function(H,B){return"✖ Error "+H+" while fetching file: "+B},Z="✖ Error: File does not exist or is empty",X={js:"javascript",py:"python",rb:"ruby",ps1:"powershell",psm1:"powershell",sh:"bash",bat:"batch",h:"c",tex:"latex"},Y="data-src-status",K="loading",q="loaded",G="failed",z="pre[data-src]:not(["+Y+'="'+q+'"]):not(['+Y+'="'+K+'"])';function U(H,B,M){var V=new XMLHttpRequest;V.open("GET",H,!0),V.onreadystatechange=function(){if(V.readyState==4)if(V.status<400&&V.responseText)B(V.responseText);else if(V.status>=400)M(Q(V.status,V.statusText));else M(Z)},V.send(null)}function W(H){var B=/^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(H||"");if(B){var M=Number(B[1]),V=B[2],N=B[3];if(!V)return[M,M];if(!N)return[M,void 0];return[M,Number(N)]}return}v6.hooks.add("before-highlightall",function(H){H.selector+=", "+z}),v6.hooks.add("before-sanity-check",function(H){var B=H.element;if(B.matches(z)){H.code="",B.setAttribute(Y,K);var M=B.appendChild(document.createElement("CODE"));M.textContent=J;var V=B.getAttribute("data-src"),N=H.language;if(N==="none"){var L=(/\.(\w+)$/.exec(V)||[,"none"])[1];N=X[L]||L}v6.util.setLanguage(M,N),v6.util.setLanguage(B,N);var A=v6.plugins.autoloader;if(A)A.loadLanguages(N);U(V,function(O){B.setAttribute(Y,q);var j=W(B.getAttribute("data-range"));if(j){var R=O.split(/\r\n?|\n/g),I=j[0],w=j[1]==null?R.length:j[1];if(I<0)I+=R.length;if(I=Math.max(0,Math.min(I-1,R.length)),w<0)w+=R.length;if(w=Math.max(0,Math.min(w,R.length)),O=R.slice(I,w).join(`
4494
4494
  `),!B.hasAttribute("data-start"))B.setAttribute("data-start",String(I+1))}M.textContent=O,v6.highlightElement(M)},function(O){B.setAttribute(Y,G),M.textContent=O})}}),v6.plugins.fileHighlight={highlight:function(B){var M=(B||document).querySelectorAll(z);for(var V=0,N;N=M[V++];)v6.highlightElement(N)}};var F=!1;v6.fileHighlight=function(){if(!F)console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead."),F=!0;v6.plugins.fileHighlight.highlight.apply(this,arguments)}})()});var uZ6=t((sP2,mZ6)=>{mZ6.exports=C71;function C71(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}C71.prototype.go=function(J){if(this.pending<this.max)gZ6(this,J);else this.waiting.push(J)};C71.prototype.wait=function(J){if(this.pending===0)J(this.error);else this.listeners.push(J)};C71.prototype.hold=function(){return hZ6(this)};function hZ6(J){J.pending+=1;var Q=!1;return Z;function Z(Y){if(Q)throw Error("callback called twice");if(Q=!0,J.error=J.error||Y,J.pending-=1,J.waiting.length>0&&J.pending<J.max)gZ6(J,J.waiting.shift());else if(J.pending===0){var K=J.listeners;J.listeners=[],K.forEach(X)}}function X(Y){Y(J.error)}}function gZ6(J,Q){Q(hZ6(J))}});var dZ6=t((C29)=>{var Yu=s1("fs"),S71=s1("util"),wf1=s1("stream"),pZ6=wf1.Readable,If1=wf1.Writable,E29=wf1.PassThrough,$29=uZ6(),v71=s1("events").EventEmitter;C29.createFromBuffer=P29;C29.createFromFd=T29;C29.BufferSlicer=VH;C29.FdSlicer=MH;S71.inherits(MH,v71);function MH(J,Q){Q=Q||{},v71.call(this),this.fd=J,this.pend=new $29,this.pend.max=1,this.refCount=0,this.autoClose=!!Q.autoClose}MH.prototype.read=function(J,Q,Z,X,Y){var K=this;K.pend.go(function(q){Yu.read(K.fd,J,Q,Z,X,function(G,z,U){q(),Y(G,z,U)})})};MH.prototype.write=function(J,Q,Z,X,Y){var K=this;K.pend.go(function(q){Yu.write(K.fd,J,Q,Z,X,function(G,z,U){q(),Y(G,z,U)})})};MH.prototype.createReadStream=function(J){return new k71(this,J)};MH.prototype.createWriteStream=function(J){return new _71(this,J)};MH.prototype.ref=function(){this.refCount+=1};MH.prototype.unref=function(){var J=this;if(J.refCount-=1,J.refCount>0)return;if(J.refCount<0)throw Error("invalid unref");if(J.autoClose)Yu.close(J.fd,Q);function Q(Z){if(Z)J.emit("error",Z);else J.emit("close")}};S71.inherits(k71,pZ6);function k71(J,Q){Q=Q||{},pZ6.call(this,Q),this.context=J,this.context.ref(),this.start=Q.start||0,this.endOffset=Q.end,this.pos=this.start,this.destroyed=!1}k71.prototype._read=function(J){var Q=this;if(Q.destroyed)return;var Z=Math.min(Q._readableState.highWaterMark,J);if(Q.endOffset!=null)Z=Math.min(Z,Q.endOffset-Q.pos);if(Z<=0){Q.destroyed=!0,Q.push(null),Q.context.unref();return}Q.context.pend.go(function(X){if(Q.destroyed)return X();var Y=Buffer.allocUnsafe(Z);Yu.read(Q.context.fd,Y,0,Z,Q.pos,function(K,q){if(K)Q.destroy(K);else if(q===0)Q.destroyed=!0,Q.push(null),Q.context.unref();else Q.pos+=q,Q.push(Y.slice(0,q));X()})})};k71.prototype.destroy=function(J){if(this.destroyed)return;J=J||Error("stream destroyed"),this.destroyed=!0,this.emit("error",J),this.context.unref()};S71.inherits(_71,If1);function _71(J,Q){Q=Q||{},If1.call(this,Q),this.context=J,this.context.ref(),this.start=Q.start||0,this.endOffset=Q.end==null?1/0:+Q.end,this.bytesWritten=0,this.pos=this.start,this.destroyed=!1,this.on("finish",this.destroy.bind(this))}_71.prototype._write=function(J,Q,Z){var X=this;if(X.destroyed)return;if(X.pos+J.length>X.endOffset){var Y=Error("maximum file length exceeded");Y.code="ETOOBIG",X.destroy(),Z(Y);return}X.context.pend.go(function(K){if(X.destroyed)return K();Yu.write(X.context.fd,J,0,J.length,X.pos,function(q,G){if(q)X.destroy(),K(),Z(q);else X.bytesWritten+=G,X.pos+=G,X.emit("progress"),K(),Z()})})};_71.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=!0,this.context.unref()};S71.inherits(VH,v71);function VH(J,Q){v71.call(this),Q=Q||{},this.refCount=0,this.buffer=J,this.maxChunkSize=Q.maxChunkSize||Number.MAX_SAFE_INTEGER}VH.prototype.read=function(J,Q,Z,X,Y){if(!(0<=Q&&Q<=J.length))throw RangeError("offset outside buffer: 0 <= "+Q+" <= "+J.length);if(X<0)throw RangeError("position is negative: "+X);if(Q+Z>J.length)Z=J.length-Q;if(X+Z>this.buffer.length)Z=this.buffer.length-X;if(Z<=0){setImmediate(function(){Y(null,0)});return}this.buffer.copy(J,Q,X,X+Z),setImmediate(function(){Y(null,Z)})};VH.prototype.write=function(J,Q,Z,X,Y){J.copy(this.buffer,X,Q,Q+Z),setImmediate(function(){Y(null,Z,J)})};VH.prototype.createReadStream=function(J){J=J||{};var Q=new E29(J);Q.destroyed=!1,Q.start=J.start||0,Q.endOffset=J.end,Q.pos=Q.endOffset||this.buffer.length;var Z=this.buffer.slice(Q.start,Q.pos),X=0;while(!0){var Y=X+this.maxChunkSize;if(Y>=Z.length){if(X<Z.length)Q.write(Z.slice(X,Z.length));break}Q.write(Z.slice(X,Y)),X=Y}return Q.end(),Q.destroy=function(){Q.destroyed=!0},Q};VH.prototype.createWriteStream=function(J){var Q=this;J=J||{};var Z=new If1(J);return Z.start=J.start||0,Z.endOffset=J.end==null?this.buffer.length:+J.end,Z.bytesWritten=0,Z.pos=Z.start,Z.destroyed=!1,Z._write=function(X,Y,K){if(Z.destroyed)return;var q=Z.pos+X.length;if(q>Z.endOffset){var G=Error("maximum file length exceeded");G.code="ETOOBIG",Z.destroyed=!0,K(G);return}X.copy(Q.buffer,Z.pos,0,X.length),Z.bytesWritten+=X.length,Z.pos=q,Z.emit("progress"),K()},Z.destroy=function(){Z.destroyed=!0},Z};VH.prototype.ref=function(){this.refCount+=1};VH.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")};function P29(J,Q){return new VH(J,Q)}function T29(J,Q){return new MH(J,Q)}});var iZ6=t((tP2,lZ6)=>{var BV=s1("buffer").Buffer,Ef1=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918000,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array<"u")Ef1=new Int32Array(Ef1);function cZ6(J){if(BV.isBuffer(J))return J;var Q=typeof BV.alloc==="function"&&typeof BV.from==="function";if(typeof J==="number")return Q?BV.alloc(J):new BV(J);else if(typeof J==="string")return Q?BV.from(J):new BV(J);else throw Error("input must be buffer, number, or string, received "+typeof J)}function b29(J){var Q=cZ6(4);return Q.writeInt32BE(J,0),Q}function $f1(J,Q){if(J=cZ6(J),BV.isBuffer(Q))Q=Q.readUInt32BE(0);var Z=~~Q^-1;for(var X=0;X<J.length;X++)Z=Ef1[(Z^J[X])&255]^Z>>>8;return Z^-1}function Pf1(){return b29($f1.apply(null,arguments))}Pf1.signed=function(){return $f1.apply(null,arguments)};Pf1.unsigned=function(){return $f1.apply(null,arguments)>>>0};lZ6.exports=Pf1});import{randomBytes as k49}from"node:crypto";import{mkdir as _49,readFile as wX6,writeFile as b49}from"node:fs/promises";import x49 from"node:os";import df1 from"node:path";import{stderr as o2,stdout as g2}from"node:process";k0();F0();var _u1={workspacePaths:[".agents/commands"],globalPaths:["~/.config/amp/commands"],enableWatching:!0};function Oq6(J,Q){if(J.length!==Q.length)return!1;for(let Z=0;Z<J.length;Z++){let X=J[Z],Y=Q[Z];if(!X||!Y)return!1;if(X.name!==Y.name||X.available!==Y.available||X.lastModified!==Y.lastModified)return!1}return!0}function uT(J=_u1,Q=null){let Z=new m2([]),X=!1,Y=null,K,q=Z.pipe(P8(Oq6),CK((H)=>{return l.warn("Command stream error, using fallback",{error:H}),J0.of([])}),v9());async function G(){if(Y)return;let H=await q6(Q);if(!H)return;let{CommandDiscovery:B}=await Promise.resolve().then(() => (ku1(),vu1));Y=new B(J,H),K={dispose:Y.commandChanges.subscribe((M)=>{if(!X)Z.next(M)}).unsubscribe}}async function z(){if(await G(),!Y)return l.debug("No workspace roots available, skipping command discovery"),[];return await Y.discoverCommands()}async function U(){if(X)return;try{let H=await z();Z.next(H)}catch(H){l.warn("Failed to refresh commands",{error:H})}}async function W(H){let M=(await q6(q)).find((A)=>A.name===H);if(!M)return;let{available:V,unavailableReason:N,...L}=M;return L}async function F(H){return(await q6(q)).find((V)=>V.name===H)?.available??!1}return U(),{commands:q,getCommand:W,refreshCommands:U,isCommandAvailable:F,dispose(){X=!0,K?.dispose(),Y?.dispose()}}}fO();F0();import hO from"node:diagnostics_channel";import{mkdirSync as Iq6}from"node:fs";import{writeFile as Eq6}from"node:fs/promises";import $q6 from"node:path";var fu1=!1;function gu1(){if(fu1)return;fu1=!0;try{Iq6(YJ1,{recursive:!0})}catch(X){l.error("Failed to create HTTP logs directory",{error:X})}let J=new WeakMap,Q=new WeakMap,Z=new WeakMap;hO.channel("undici:request:create").subscribe((X)=>{let{request:Y}=X,K=`${Y.origin}${Y.path}`,q={};if(Array.isArray(Y.headers))for(let z=0;z<Y.headers.length;z+=2)q[Y.headers[z]||""]=Y.headers[z+1]||"";else if(Y.headers)q=Y.headers;let G={timestamp:new Date().toISOString(),method:Y.method||"UNKNOWN",url:K,headers:q};Z.set(Y,G),J.set(Y,[])}),hO.channel("undici:request:bodyChunkSent").subscribe((X)=>{let{request:Y,chunk:K}=X;if(K&&Y){let q=J.get(Y)||[],G=typeof K==="string"?Buffer.from(K,"utf-8"):K;q.push(G),J.set(Y,q)}}),hO.channel("undici:request:headers").subscribe((X)=>{let{request:Y,response:K}=X,q=Z.get(Y);if(q){q.responseStatus=K.statusCode;let G={};if(Array.isArray(K.headers))for(let z=0;z<K.headers.length;z+=2){let U=K.headers[z],W=K.headers[z+1];if(U&&W){let F=Buffer.isBuffer(U)?U.toString("utf-8"):String(U),H=Buffer.isBuffer(W)?W.toString("utf-8"):String(W);G[F]=H}}q.responseHeaders=G}}),hO.channel("undici:request:bodyChunkReceived").subscribe((X)=>{let{request:Y,chunk:K}=X;if(K&&Y){let q=Q.get(Y)||[];q.push(K),Q.set(Y,q)}}),hO.channel("undici:request:trailers").subscribe((X)=>{let{request:Y}=X,K=Z.get(Y);if(!K)return;hu1(K).catch((q)=>{l.error("Failed to write HTTP request log",{error:q})}),J.delete(Y),Q.delete(Y),Z.delete(Y)}),hO.channel("undici:request:error").subscribe((X)=>{let{request:Y,error:K}=X,q=Z.get(Y);if(q){let G=J.get(Y),z=Q.get(Y);if(G&&G.length>0)q.requestBody=Buffer.concat(G.map((W)=>Buffer.from(W))).toString("utf-8");if(z&&z.length>0)q.responseBody=Buffer.concat(z).toString("utf-8");let U={...q,error:{message:K.message,stack:K.stack}};hu1(U).catch((W)=>{l.error("Failed to write HTTP error log",{error:W})})}J.delete(Y),Q.delete(Y),Z.delete(Y)}),l.info("HTTP request/response logging initialized")}async function hu1(J){let Z=new URL(J.url).pathname.replace(/^\//,"").replace(/\//g,"_")||"root",Y=`${new Date(J.timestamp).getTime()}_${Z}_${J.method}.json`,K=$q6.join(YJ1,Y),q=JSON.stringify(J,null,2);await Eq6(K,q,"utf-8")}F0();k0();import Sq6 from"node:fs";import vq6 from"node:os";var Pq6=/("(?:\\?[^])*?")|(\/\/.*)|(\/\*[^]*?\*\/)/g,Tq6=/("(?:\\?[^])*?")|(,\s*)(?=]|})/g,Cq6={parse:(J)=>{J=String(J);try{return JSON.parse(J)}catch{return JSON.parse(J.replace(Pq6,"$1").replace(Tq6,"$1"))}}},mu1=Cq6;F0();k0();F0();class KJ1{options;value;lastError;lastUpdated=0;pendingPromise;eventsSubject=new y8;events=this.eventsSubject;constructor(J){this.options=J}async get(){if(this.lastError)return this.recompute();let Q=Date.now()-this.lastUpdated;if(this.value===void 0||Q>=this.options.hardTTL)return this.recompute();if(Q>=this.options.softTTL&&!this.pendingPromise)this.recompute().catch(()=>{});return this.value}getCached(){return this.value}async refresh(){return this.recompute()}recompute(){if(this.pendingPromise)return this.pendingPromise;return this.pendingPromise=this.performRecomputation(),this.pendingPromise.finally(()=>{this.pendingPromise=void 0}),this.pendingPromise}async performRecomputation(){try{let J=await this.options.compute(),Q=this.value;this.lastError=void 0,this.value=J,this.lastUpdated=Date.now();let Z=this.options.changes(Q,J);if(Z!==void 0)try{this.eventsSubject.next(Z)}catch(X){l.error("Uncaught error for GlobalCachedValue.events subscriber",X)}return J}catch(J){let Q=J instanceof Error?J:Error(String(J));this.lastError=Q;let Z=this.value;this.value=void 0;let X=this.options.changes(Z,void 0);if(X!==void 0)try{this.eventsSubject.next(X)}catch(Y){l.error("Uncaught error for GlobalCachedValue.events subscriber",Y)}throw Q}}}function kq6(J){if(!/^\d{4}-\d{2}-\d{2}$/.test(J))throw Error(`Invalid compatibility date format "${J}". Expected format: YYYY-MM-DD (e.g., "2024-01-15")`);let Z=new Date(J+"T00:00:00.000Z");if(Number.isNaN(Z.getTime()))throw Error(`Invalid compatibility date "${J}". Date could not be parsed.`);let X=J.split("-").map(Number),[Y,K,q]=X;if(X.length!==3||Y===void 0||K===void 0||q===void 0)throw Error(`Invalid compatibility date "${J}". Could not parse date components.`);if(Z.getUTCFullYear()!==Y||Z.getUTCMonth()!==K-1||Z.getUTCDate()!==q)throw Error(`Invalid compatibility date "${J}". Date components are invalid.`);return Z}var uu1=new KJ1({compute:async()=>{try{let J=await xq6(),Q;try{Q=mu1.parse(J)}catch(X){throw Error(`Invalid JSON in admin settings: ${X} (content: "${J}")`)}l.debug("Admin settings loaded",{rawConfig:Q});let Z={};for(let[X,Y]of Object.entries(Q))if(X.startsWith("amp.")){let K=X.substring(4);if(K==="admin.compatibilityDate")try{Z.compatibilityDate=kq6(Y)}catch(q){l.warn(`Invalid admin compatibility date: ${q instanceof Error?q.message:String(q)}`)}else Z[K]=Y}return Z}catch(J){if(J.code==="ENOENT")return{};return l.error("Failed to read admin settings",{error:J}),{}}},softTTL:30000,hardTTL:120000,changes:(J,Q)=>{let Z=_q6(J,Q);return Z.length>0?Z:void 0}});function pu1(J,Q={fetch:()=>uu1.get(),changes:uu1.events}){return{...J,async get(Z,X){let Y=await Q.fetch();if(X==="admin"||!X&&Z in Y)return Y[Z];return J.get(Z,X)},async keys(){let Z=await J.keys(),X=await Q.fetch(),Y=Object.keys(X),K=new Set([...Z,...Y]);return Array.from(K)},get changes(){if(Q.changes)return kT(J.changes,Q.changes);return J.changes}}}function _q6(J,Q){let Z=J??{},X=Q??{},Y=JSON.stringify(Z,Object.keys(Z).sort()),K=JSON.stringify(X,Object.keys(X).sort());if(Y===K)return[];let q=new Set([...Object.keys(Z),...Object.keys(X)]);return Array.from(q)}function bq6(){switch(vq6.platform()){case"darwin":return"/Library/Application Support/ampcode/managed-settings.json";case"linux":return"/etc/ampcode/managed-settings.json";case"win32":return"C:\\ProgramData\\ampcode\\managed-settings.json";default:return null}}async function xq6(){let J=bq6();if(!J)return"{}";try{return await Sq6.promises.readFile(J,"utf-8")}catch(Q){if(Q.code==="ENOENT")return"{}";throw Q}}O2();k0();var bu=new m2({});function PH(J,Q){let Z=bu.getValue();bu.next({...Z,[J]:Q})}n6();k0();$H();Qj();fV();zp();O2();Up();function nJ1({storage:J,secretStorage:Q,workspaceRoots:Z,defaultAmpURL:X=oQ,defaultCacheDirectory:Y,preferThreadEnv:K,homeDir:q,userConfigDir:G}){let z=_8(async()=>{let H=await J.keys();return Object.fromEntries(await Promise.all(H.map(async(M)=>[M,await J.get(M)])))}).pipe(A9((H)=>_T(J0.of(H),J.changes.pipe(EU(async(B)=>{return await Promise.all(B.map(async(M)=>{let V=await J.get(M);H[M]=V})),H})))),S0((H)=>{let B={...H,url:H.url||X,"todos.enabled":H["todos.enabled"]??!0,cacheDirectory:H.cacheDirectory||Y};if(B.permissions)B.permissions=uu(B.permissions);return B}),v9(),P8()),U=$2(Q.changes.pipe(Q7(void 0)),z.pipe(S0(({url:H})=>H),P8())).pipe(EU(async([,H])=>({getToken:async(B,M)=>{return Q.get(B,M)},isSet:{[H]:Object.fromEntries(await Promise.all(kd1.map(async(B)=>[B,!!await Q.get(B,H)])))}})));cu1($2(z,U,bu).pipe(S0(([H,B,M])=>({settings:{...H,...M},secrets:B}))));let W=Z.pipe(S0((H)=>({workspaceFolders:H?.map(K8)??null,isWindows:Hj().os==="windows",homeDir:typeof process==="object"&&process.env.HOME?K8(b0.file(process.env.HOME)):void 0,preferThreadEnv:K}))),F=W.subscribe((H)=>{du(H)});return{get(H,B){return J.get(H,B)},updateSettings(H,B,M){return J.set(H,B,M)},async appendSettings(H,B,M){let V=await J.get(H,M);if(V===void 0)return J.set(H,B,M);else if(!Array.isArray(V))throw Error(`Cannot append to non-array setting: ${H}`);else if(V.length===0)return J.set(H,B,M);else{let N=[...V,...B];return J.set(H,N,M)}},async prependSettings(H,B,M){let V=await J.get(H,M);if(V===void 0)return J.set(H,B,M);else if(!Array.isArray(V))throw Error(`Cannot prepend to non-array setting: ${H}`);else if(V.length===0)return J.set(H,B,M);else{let N=[...B,...V];return J.set(H,N,M)}},updateSecret(H,B,M){return Q.set(H,B,M)},workspaceRoots:Z,displayPathEnvInfo:W,homeDir:q,userConfigDir:G,unsubscribe(){F.unsubscribe()}}}rJ1();$H();yj();Ld();Y7();n6();k0();F0();O2();var Pa1=100;j2();pU();var bD6=60000;class wq1{constructor(J){this._options=J,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(bd,(Q)=>{let Z=this._requestHandlerAbortControllers.get(Q.params.requestId);Z===null||Z===void 0||Z.abort(Q.params.reason)}),this.setNotificationHandler(yd,(Q)=>{this._onprogress(Q)}),this.setRequestHandler(xd,(Q)=>({}))}_setupTimeout(J,Q,Z,X,Y=!1){this._timeoutInfo.set(J,{timeoutId:setTimeout(X,Q),startTime:Date.now(),timeout:Q,maxTotalTimeout:Z,resetTimeoutOnProgress:Y,onTimeout:X})}_resetTimeout(J){let Q=this._timeoutInfo.get(J);if(!Q)return!1;let Z=Date.now()-Q.startTime;if(Q.maxTotalTimeout&&Z>=Q.maxTotalTimeout)throw this._timeoutInfo.delete(J),new hK(zY.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Q.maxTotalTimeout,totalElapsed:Z});return clearTimeout(Q.timeoutId),Q.timeoutId=setTimeout(Q.onTimeout,Q.timeout),!0}_cleanupTimeout(J){let Q=this._timeoutInfo.get(J);if(Q)clearTimeout(Q.timeoutId),this._timeoutInfo.delete(J)}async connect(J){var Q,Z,X;this._transport=J;let Y=(Q=this.transport)===null||Q===void 0?void 0:Q.onclose;this._transport.onclose=()=>{Y===null||Y===void 0||Y(),this._onclose()};let K=(Z=this.transport)===null||Z===void 0?void 0:Z.onerror;this._transport.onerror=(G)=>{K===null||K===void 0||K(G),this._onerror(G)};let q=(X=this._transport)===null||X===void 0?void 0:X.onmessage;this._transport.onmessage=(G,z)=>{if(q===null||q===void 0||q(G,z),FS(G)||ya1(G))this._onresponse(G);else if(_d(G))this._onrequest(G,z);else if(_a1(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){var J;let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(J=this.onclose)===null||J===void 0||J.call(this);let Z=new hK(zY.ConnectionClosed,"Connection closed");for(let X of Q.values())X(Z)}_onerror(J){var Q;(Q=this.onerror)===null||Q===void 0||Q.call(this,J)}_onnotification(J){var Q;let Z=(Q=this._notificationHandlers.get(J.method))!==null&&Q!==void 0?Q:this.fallbackNotificationHandler;if(Z===void 0)return;Promise.resolve().then(()=>Z(J)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(J,Q){var Z,X;let Y=(Z=this._requestHandlers.get(J.method))!==null&&Z!==void 0?Z:this.fallbackRequestHandler,K=this._transport;if(Y===void 0){K===null||K===void 0||K.send({jsonrpc:"2.0",id:J.id,error:{code:zY.MethodNotFound,message:"Method not found"}}).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let q=new AbortController;this._requestHandlerAbortControllers.set(J.id,q);let G={signal:q.signal,sessionId:K===null||K===void 0?void 0:K.sessionId,_meta:(X=J.params)===null||X===void 0?void 0:X._meta,sendNotification:(z)=>this.notification(z,{relatedRequestId:J.id}),sendRequest:(z,U,W)=>this.request(z,U,{...W,relatedRequestId:J.id}),authInfo:Q===null||Q===void 0?void 0:Q.authInfo,requestId:J.id,requestInfo:Q===null||Q===void 0?void 0:Q.requestInfo};Promise.resolve().then(()=>Y(J,G)).then((z)=>{if(q.signal.aborted)return;return K===null||K===void 0?void 0:K.send({result:z,jsonrpc:"2.0",id:J.id})},(z)=>{var U;if(q.signal.aborted)return;return K===null||K===void 0?void 0:K.send({jsonrpc:"2.0",id:J.id,error:{code:Number.isSafeInteger(z.code)?z.code:zY.InternalError,message:(U=z.message)!==null&&U!==void 0?U:"Internal error"}})}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{this._requestHandlerAbortControllers.delete(J.id)})}_onprogress(J){let{progressToken:Q,...Z}=J.params,X=Number(Q),Y=this._progressHandlers.get(X);if(!Y){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(J)}`));return}let K=this._responseHandlers.get(X),q=this._timeoutInfo.get(X);if(q&&K&&q.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(G){K(G);return}Y(Z)}_onresponse(J){let Q=Number(J.id),Z=this._responseHandlers.get(Q);if(Z===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(J)}`));return}if(this._responseHandlers.delete(Q),this._progressHandlers.delete(Q),this._cleanupTimeout(Q),FS(J))Z(J);else{let X=new hK(J.error.code,J.error.message,J.error.data);Z(X)}}get transport(){return this._transport}async close(){var J;await((J=this._transport)===null||J===void 0?void 0:J.close())}request(J,Q,Z){let{relatedRequestId:X,resumptionToken:Y,onresumptiontoken:K}=Z!==null&&Z!==void 0?Z:{};return new Promise((q,G)=>{var z,U,W,F,H,B;if(!this._transport){G(Error("Not connected"));return}if(((z=this._options)===null||z===void 0?void 0:z.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod(J.method);(U=Z===null||Z===void 0?void 0:Z.signal)===null||U===void 0||U.throwIfAborted();let M=this._requestMessageId++,V={...J,jsonrpc:"2.0",id:M};if(Z===null||Z===void 0?void 0:Z.onprogress)this._progressHandlers.set(M,Z.onprogress),V.params={...J.params,_meta:{...((W=J.params)===null||W===void 0?void 0:W._meta)||{},progressToken:M}};let N=(O)=>{var j;this._responseHandlers.delete(M),this._progressHandlers.delete(M),this._cleanupTimeout(M),(j=this._transport)===null||j===void 0||j.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:M,reason:String(O)}},{relatedRequestId:X,resumptionToken:Y,onresumptiontoken:K}).catch((R)=>this._onerror(Error(`Failed to send cancellation: ${R}`))),G(O)};this._responseHandlers.set(M,(O)=>{var j;if((j=Z===null||Z===void 0?void 0:Z.signal)===null||j===void 0?void 0:j.aborted)return;if(O instanceof Error)return G(O);try{let R=Q.parse(O.result);q(R)}catch(R){G(R)}}),(F=Z===null||Z===void 0?void 0:Z.signal)===null||F===void 0||F.addEventListener("abort",()=>{var O;N((O=Z===null||Z===void 0?void 0:Z.signal)===null||O===void 0?void 0:O.reason)});let L=(H=Z===null||Z===void 0?void 0:Z.timeout)!==null&&H!==void 0?H:bD6,A=()=>N(new hK(zY.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(M,L,Z===null||Z===void 0?void 0:Z.maxTotalTimeout,A,(B=Z===null||Z===void 0?void 0:Z.resetTimeoutOnProgress)!==null&&B!==void 0?B:!1),this._transport.send(V,{relatedRequestId:X,resumptionToken:Y,onresumptiontoken:K}).catch((O)=>{this._cleanupTimeout(M),G(O)})})}async notification(J,Q){var Z,X;if(!this._transport)throw Error("Not connected");if(this.assertNotificationCapability(J.method),((X=(Z=this._options)===null||Z===void 0?void 0:Z.debouncedNotificationMethods)!==null&&X!==void 0?X:[]).includes(J.method)&&!J.params&&!(Q===null||Q===void 0?void 0:Q.relatedRequestId)){if(this._pendingDebouncedNotifications.has(J.method))return;this._pendingDebouncedNotifications.add(J.method),Promise.resolve().then(()=>{var G;if(this._pendingDebouncedNotifications.delete(J.method),!this._transport)return;let z={...J,jsonrpc:"2.0"};(G=this._transport)===null||G===void 0||G.send(z,Q).catch((U)=>this._onerror(U))});return}let q={...J,jsonrpc:"2.0"};await this._transport.send(q,Q)}setRequestHandler(J,Q){let Z=J.shape.method.value;this.assertRequestHandlerCapability(Z),this._requestHandlers.set(Z,(X,Y)=>{return Promise.resolve(Q(J.parse(X),Y))})}removeRequestHandler(J){this._requestHandlers.delete(J)}assertCanSetRequestHandler(J){if(this._requestHandlers.has(J))throw Error(`A request handler for ${J} already exists, which would be overridden`)}setNotificationHandler(J,Q){this._notificationHandlers.set(J.shape.method.value,(Z)=>Promise.resolve(Q(J.parse(Z))))}removeNotificationHandler(J){this._notificationHandlers.delete(J)}}function ia1(J,Q){return Object.entries(Q).reduce((Z,[X,Y])=>{if(Y&&typeof Y==="object")Z[X]=Z[X]?{...Z[X],...Y}:Y;else Z[X]=Y;return Z},{...J})}pU();var nr1=Y8(ar1(),1);class DS extends wq1{constructor(J,Q){var Z;super(Q);this._clientInfo=J,this._cachedToolOutputValidators=new Map,this._capabilities=(Z=Q===null||Q===void 0?void 0:Q.capabilities)!==null&&Z!==void 0?Z:{},this._ajv=new nr1.default}registerCapabilities(J){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=ia1(this._capabilities,J)}assertCapability(J,Q){var Z;if(!((Z=this._serverCapabilities)===null||Z===void 0?void 0:Z[J]))throw Error(`Server does not support ${J} (required for ${Q})`)}async connect(J,Q){if(await super.connect(J),J.sessionId!==void 0)return;try{let Z=await this.request({method:"initialize",params:{protocolVersion:fj,capabilities:this._capabilities,clientInfo:this._clientInfo}},Gq1,Q);if(Z===void 0)throw Error(`Server sent invalid initialize result: ${Z}`);if(!Ta1.includes(Z.protocolVersion))throw Error(`Server's protocol version is not supported: ${Z.protocolVersion}`);if(this._serverCapabilities=Z.capabilities,this._serverVersion=Z.serverInfo,J.setProtocolVersion)J.setProtocolVersion(Z.protocolVersion);this._instructions=Z.instructions,await this.notification({method:"notifications/initialized"})}catch(Z){throw this.close(),Z}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(J){var Q,Z,X,Y,K;switch(J){case"logging/setLevel":if(!((Q=this._serverCapabilities)===null||Q===void 0?void 0:Q.logging))throw Error(`Server does not support logging (required for ${J})`);break;case"prompts/get":case"prompts/list":if(!((Z=this._serverCapabilities)===null||Z===void 0?void 0:Z.prompts))throw Error(`Server does not support prompts (required for ${J})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!((X=this._serverCapabilities)===null||X===void 0?void 0:X.resources))throw Error(`Server does not support resources (required for ${J})`);if(J==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${J})`);break;case"tools/call":case"tools/list":if(!((Y=this._serverCapabilities)===null||Y===void 0?void 0:Y.tools))throw Error(`Server does not support tools (required for ${J})`);break;case"completion/complete":if(!((K=this._serverCapabilities)===null||K===void 0?void 0:K.completions))throw Error(`Server does not support completions (required for ${J})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(J){var Q;switch(J){case"notifications/roots/list_changed":if(!((Q=this._capabilities.roots)===null||Q===void 0?void 0:Q.listChanged))throw Error(`Client does not support roots list changed notifications (required for ${J})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(J){switch(J){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${J})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${J})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${J})`);break;case"ping":break}}async ping(J){return this.request({method:"ping"},XN,J)}async complete(J,Q){return this.request({method:"completion/complete",params:J},Rq1,Q)}async setLoggingLevel(J,Q){return this.request({method:"logging/setLevel",params:{level:J}},XN,Q)}async getPrompt(J,Q){return this.request({method:"prompts/get",params:J},Nq1,Q)}async listPrompts(J,Q){return this.request({method:"prompts/list",params:J},Bq1,Q)}async listResources(J,Q){return this.request({method:"resources/list",params:J},Uq1,Q)}async listResourceTemplates(J,Q){return this.request({method:"resources/templates/list",params:J},Wq1,Q)}async readResource(J,Q){return this.request({method:"resources/read",params:J},Fq1,Q)}async subscribeResource(J,Q){return this.request({method:"resources/subscribe",params:J},XN,Q)}async unsubscribeResource(J,Q){return this.request({method:"resources/unsubscribe",params:J},XN,Q)}async callTool(J,Q=gd,Z){let X=await this.request({method:"tools/call",params:J},Q,Z),Y=this.getToolOutputValidator(J.name);if(Y){if(!X.structuredContent&&!X.isError)throw new hK(zY.InvalidRequest,`Tool ${J.name} has an output schema but did not return structured content`);if(X.structuredContent)try{if(!Y(X.structuredContent))throw new hK(zY.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(Y.errors)}`)}catch(K){if(K instanceof hK)throw K;throw new hK(zY.InvalidParams,`Failed to validate structured content: ${K instanceof Error?K.message:String(K)}`)}}return X}cacheToolOutputSchemas(J){this._cachedToolOutputValidators.clear();for(let Q of J)if(Q.outputSchema)try{let Z=this._ajv.compile(Q.outputSchema);this._cachedToolOutputValidators.set(Q.name,Z)}catch(Z){}}getToolOutputValidator(J){return this._cachedToolOutputValidators.get(J)}async listTools(J,Q){let Z=await this.request({method:"tools/list",params:J},Aq1,Q);return this.cacheToolOutputSchemas(Z.tools),Z}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}Xc();class sq1 extends Event{constructor(J,Q){var Z,X;super(J),this.code=(Z=Q==null?void 0:Q.code)!=null?Z:void 0,this.message=(X=Q==null?void 0:Q.message)!=null?X:void 0}[Symbol.for("nodejs.util.inspect.custom")](J,Q,Z){return Z(rr1(this),Q)}[Symbol.for("Deno.customInspect")](J,Q){return J(rr1(this),Q)}}function DV6(J){let Q=globalThis.DOMException;return typeof Q=="function"?new Q(J,"SyntaxError"):SyntaxError(J)}function oq1(J){return J instanceof Error?"errors"in J&&Array.isArray(J.errors)?J.errors.map(oq1).join(", "):("cause"in J)&&J.cause instanceof Error?`${J}: ${oq1(J.cause)}`:J.message:`${J}`}function rr1(J){return{type:J.type,message:J.message,code:J.code,defaultPrevented:J.defaultPrevented,cancelable:J.cancelable,timeStamp:J.timeStamp}}var or1=(J)=>{throw TypeError(J)},KG1=(J,Q,Z)=>Q.has(J)||or1("Cannot "+Z),W9=(J,Q,Z)=>(KG1(J,Q,"read from private field"),Z?Z.call(J):Q.get(J)),m7=(J,Q,Z)=>Q.has(J)?or1("Cannot add the same private member more than once"):Q instanceof WeakSet?Q.add(J):Q.set(J,Z),H4=(J,Q,Z,X)=>(KG1(J,Q,"write to private field"),Q.set(J,Z),Z),dU=(J,Q,Z)=>(KG1(J,Q,"access private method"),Z),KZ,qN,mj,Yc,Kc,NS,dj,LS,aH,uj,cj,pj,MS,gK,tq1,eq1,JG1,sr1,QG1,ZG1,VS,XG1,YG1;class lj extends EventTarget{constructor(J,Q){var Z,X;super(),m7(this,gK),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,m7(this,KZ),m7(this,qN),m7(this,mj),m7(this,Yc),m7(this,Kc),m7(this,NS),m7(this,dj),m7(this,LS,null),m7(this,aH),m7(this,uj),m7(this,cj,null),m7(this,pj,null),m7(this,MS,null),m7(this,eq1,async(Y)=>{var K;W9(this,uj).reset();let{body:q,redirected:G,status:z,headers:U}=Y;if(z===204){dU(this,gK,VS).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(G?H4(this,mj,new URL(Y.url)):H4(this,mj,void 0),z!==200){dU(this,gK,VS).call(this,`Non-200 status code (${z})`,z);return}if(!(U.get("content-type")||"").startsWith("text/event-stream")){dU(this,gK,VS).call(this,'Invalid content type, expected "text/event-stream"',z);return}if(W9(this,KZ)===this.CLOSED)return;H4(this,KZ,this.OPEN);let W=new Event("open");if((K=W9(this,MS))==null||K.call(this,W),this.dispatchEvent(W),typeof q!="object"||!q||!("getReader"in q)){dU(this,gK,VS).call(this,"Invalid response body, expected a web ReadableStream",z),this.close();return}let F=new TextDecoder,H=q.getReader(),B=!0;do{let{done:M,value:V}=await H.read();V&&W9(this,uj).feed(F.decode(V,{stream:!M})),M&&(B=!1,W9(this,uj).reset(),dU(this,gK,XG1).call(this))}while(B)}),m7(this,JG1,(Y)=>{H4(this,aH,void 0),!(Y.name==="AbortError"||Y.type==="aborted")&&dU(this,gK,XG1).call(this,oq1(Y))}),m7(this,QG1,(Y)=>{typeof Y.id=="string"&&H4(this,LS,Y.id);let K=new MessageEvent(Y.event||"message",{data:Y.data,origin:W9(this,mj)?W9(this,mj).origin:W9(this,qN).origin,lastEventId:Y.id||""});W9(this,pj)&&(!Y.event||Y.event==="message")&&W9(this,pj).call(this,K),this.dispatchEvent(K)}),m7(this,ZG1,(Y)=>{H4(this,NS,Y)}),m7(this,YG1,()=>{H4(this,dj,void 0),W9(this,KZ)===this.CONNECTING&&dU(this,gK,tq1).call(this)});try{if(J instanceof URL)H4(this,qN,J);else if(typeof J=="string")H4(this,qN,new URL(J,MV6()));else throw Error("Invalid URL")}catch{throw DV6("An invalid or illegal string was specified")}H4(this,uj,gj({onEvent:W9(this,QG1),onRetry:W9(this,ZG1)})),H4(this,KZ,this.CONNECTING),H4(this,NS,3000),H4(this,Kc,(Z=Q==null?void 0:Q.fetch)!=null?Z:globalThis.fetch),H4(this,Yc,(X=Q==null?void 0:Q.withCredentials)!=null?X:!1),dU(this,gK,tq1).call(this)}get readyState(){return W9(this,KZ)}get url(){return W9(this,qN).href}get withCredentials(){return W9(this,Yc)}get onerror(){return W9(this,cj)}set onerror(J){H4(this,cj,J)}get onmessage(){return W9(this,pj)}set onmessage(J){H4(this,pj,J)}get onopen(){return W9(this,MS)}set onopen(J){H4(this,MS,J)}addEventListener(J,Q,Z){let X=Q;super.addEventListener(J,X,Z)}removeEventListener(J,Q,Z){let X=Q;super.removeEventListener(J,X,Z)}close(){W9(this,dj)&&clearTimeout(W9(this,dj)),W9(this,KZ)!==this.CLOSED&&(W9(this,aH)&&W9(this,aH).abort(),H4(this,KZ,this.CLOSED),H4(this,aH,void 0))}}KZ=new WeakMap,qN=new WeakMap,mj=new WeakMap,Yc=new WeakMap,Kc=new WeakMap,NS=new WeakMap,dj=new WeakMap,LS=new WeakMap,aH=new WeakMap,uj=new WeakMap,cj=new WeakMap,pj=new WeakMap,MS=new WeakMap,gK=new WeakSet,tq1=function(){H4(this,KZ,this.CONNECTING),H4(this,aH,new AbortController),W9(this,Kc)(W9(this,qN),dU(this,gK,sr1).call(this)).then(W9(this,eq1)).catch(W9(this,JG1))},eq1=new WeakMap,JG1=new WeakMap,sr1=function(){var J;let Q={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...W9(this,LS)?{"Last-Event-ID":W9(this,LS)}:void 0},cache:"no-store",signal:(J=W9(this,aH))==null?void 0:J.signal};return"window"in globalThis&&(Q.credentials=this.withCredentials?"include":"same-origin"),Q},QG1=new WeakMap,ZG1=new WeakMap,VS=function(J,Q){var Z;W9(this,KZ)!==this.CLOSED&&H4(this,KZ,this.CLOSED);let X=new sq1("error",{code:Q,message:J});(Z=W9(this,cj))==null||Z.call(this,X),this.dispatchEvent(X)},XG1=function(J,Q){var Z;if(W9(this,KZ)===this.CLOSED)return;H4(this,KZ,this.CONNECTING);let X=new sq1("error",{code:Q,message:J});(Z=W9(this,cj))==null||Z.call(this,X),this.dispatchEvent(X),H4(this,dj,setTimeout(W9(this,YG1),W9(this,NS)))},YG1=new WeakMap,lj.CONNECTING=0,lj.OPEN=1,lj.CLOSED=2;function MV6(){let J="document"in globalThis?globalThis.document:void 0;return J&&typeof J=="object"&&"baseURI"in J&&typeof J.baseURI=="string"?J.baseURI:void 0}pU();var qG1;qG1=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((J)=>J.webcrypto);async function VV6(J){return(await qG1).getRandomValues(new Uint8Array(J))}async function NV6(J){let Z="",X=await VV6(J);for(let Y=0;Y<J;Y++){let K=X[Y]%66;Z+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[K]}return Z}async function LV6(J){return await NV6(J)}async function AV6(J){let Q=await(await qG1).subtle.digest("SHA-256",new TextEncoder().encode(J));return btoa(String.fromCharCode(...new Uint8Array(Q))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function GG1(J){if(!J)J=43;if(J<43||J>128)throw`Expected a length between 43 and 128. Received ${J}.`;let Q=await LV6(J),Z=await AV6(Q);return{code_verifier:Q,code_challenge:Z}}pU();EG();var tr1=e.object({resource:e.string().url(),authorization_servers:e.array(e.string().url()).optional(),jwks_uri:e.string().url().optional(),scopes_supported:e.array(e.string()).optional(),bearer_methods_supported:e.array(e.string()).optional(),resource_signing_alg_values_supported:e.array(e.string()).optional(),resource_name:e.string().optional(),resource_documentation:e.string().optional(),resource_policy_uri:e.string().url().optional(),resource_tos_uri:e.string().url().optional(),tls_client_certificate_bound_access_tokens:e.boolean().optional(),authorization_details_types_supported:e.array(e.string()).optional(),dpop_signing_alg_values_supported:e.array(e.string()).optional(),dpop_bound_access_tokens_required:e.boolean().optional()}).passthrough(),zG1=e.object({issuer:e.string(),authorization_endpoint:e.string(),token_endpoint:e.string(),registration_endpoint:e.string().optional(),scopes_supported:e.array(e.string()).optional(),response_types_supported:e.array(e.string()),response_modes_supported:e.array(e.string()).optional(),grant_types_supported:e.array(e.string()).optional(),token_endpoint_auth_methods_supported:e.array(e.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e.array(e.string()).optional(),service_documentation:e.string().optional(),revocation_endpoint:e.string().optional(),revocation_endpoint_auth_methods_supported:e.array(e.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:e.array(e.string()).optional(),introspection_endpoint:e.string().optional(),introspection_endpoint_auth_methods_supported:e.array(e.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:e.array(e.string()).optional(),code_challenge_methods_supported:e.array(e.string()).optional()}).passthrough(),OV6=e.object({issuer:e.string(),authorization_endpoint:e.string(),token_endpoint:e.string(),userinfo_endpoint:e.string().optional(),jwks_uri:e.string(),registration_endpoint:e.string().optional(),scopes_supported:e.array(e.string()).optional(),response_types_supported:e.array(e.string()),response_modes_supported:e.array(e.string()).optional(),grant_types_supported:e.array(e.string()).optional(),acr_values_supported:e.array(e.string()).optional(),subject_types_supported:e.array(e.string()),id_token_signing_alg_values_supported:e.array(e.string()),id_token_encryption_alg_values_supported:e.array(e.string()).optional(),id_token_encryption_enc_values_supported:e.array(e.string()).optional(),userinfo_signing_alg_values_supported:e.array(e.string()).optional(),userinfo_encryption_alg_values_supported:e.array(e.string()).optional(),userinfo_encryption_enc_values_supported:e.array(e.string()).optional(),request_object_signing_alg_values_supported:e.array(e.string()).optional(),request_object_encryption_alg_values_supported:e.array(e.string()).optional(),request_object_encryption_enc_values_supported:e.array(e.string()).optional(),token_endpoint_auth_methods_supported:e.array(e.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e.array(e.string()).optional(),display_values_supported:e.array(e.string()).optional(),claim_types_supported:e.array(e.string()).optional(),claims_supported:e.array(e.string()).optional(),service_documentation:e.string().optional(),claims_locales_supported:e.array(e.string()).optional(),ui_locales_supported:e.array(e.string()).optional(),claims_parameter_supported:e.boolean().optional(),request_parameter_supported:e.boolean().optional(),request_uri_parameter_supported:e.boolean().optional(),require_request_uri_registration:e.boolean().optional(),op_policy_uri:e.string().optional(),op_tos_uri:e.string().optional()}).passthrough(),er1=OV6.merge(zG1.pick({code_challenge_methods_supported:!0})),UG1=e.object({access_token:e.string(),id_token:e.string().optional(),token_type:e.string(),expires_in:e.number().optional(),scope:e.string().optional(),refresh_token:e.string().optional()}).strip(),Js1=e.object({error:e.string(),error_description:e.string().optional(),error_uri:e.string().optional()}),jV6=e.object({redirect_uris:e.array(e.string()).refine((J)=>J.every((Q)=>URL.canParse(Q)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:e.string().optional(),grant_types:e.array(e.string()).optional(),response_types:e.array(e.string()).optional(),client_name:e.string().optional(),client_uri:e.string().optional(),logo_uri:e.string().optional(),scope:e.string().optional(),contacts:e.array(e.string()).optional(),tos_uri:e.string().optional(),policy_uri:e.string().optional(),jwks_uri:e.string().optional(),jwks:e.any().optional(),software_id:e.string().optional(),software_version:e.string().optional(),software_statement:e.string().optional()}).strip(),RV6=e.object({client_id:e.string(),client_secret:e.string().optional(),client_id_issued_at:e.number().optional(),client_secret_expires_at:e.number().optional()}).strip(),Qs1=jV6.merge(RV6),UG9=e.object({error:e.string(),error_description:e.string().optional()}).strip(),WG9=e.object({token:e.string(),token_type_hint:e.string().optional()}).strip();function Zs1(J){let Q=typeof J==="string"?new URL(J):new URL(J.href);return Q.hash="",Q}function Xs1({requestedResource:J,configuredResource:Q}){let Z=typeof J==="string"?new URL(J):new URL(J.href),X=typeof Q==="string"?new URL(Q):new URL(Q.href);if(Z.origin!==X.origin)return!1;if(Z.pathname.length<X.pathname.length)return!1;let Y=Z.pathname.endsWith("/")?Z.pathname:Z.pathname+"/",K=X.pathname.endsWith("/")?X.pathname:X.pathname+"/";return Y.startsWith(K)}class u7 extends Error{constructor(J,Q){super(J);this.errorUri=Q,this.name=this.constructor.name}toResponseObject(){let J={error:this.errorCode,error_description:this.message};if(this.errorUri)J.error_uri=this.errorUri;return J}get errorCode(){return this.constructor.errorCode}}class qc extends u7{}qc.errorCode="invalid_request";class ij extends u7{}ij.errorCode="invalid_client";class aj extends u7{}aj.errorCode="invalid_grant";class nj extends u7{}nj.errorCode="unauthorized_client";class Gc extends u7{}Gc.errorCode="unsupported_grant_type";class zc extends u7{}zc.errorCode="invalid_scope";class Uc extends u7{}Uc.errorCode="access_denied";class nH extends u7{}nH.errorCode="server_error";class Wc extends u7{}Wc.errorCode="temporarily_unavailable";class Fc extends u7{}Fc.errorCode="unsupported_response_type";class Hc extends u7{}Hc.errorCode="unsupported_token_type";class Bc extends u7{}Bc.errorCode="invalid_token";class Dc extends u7{}Dc.errorCode="method_not_allowed";class Mc extends u7{}Mc.errorCode="too_many_requests";class Vc extends u7{}Vc.errorCode="invalid_client_metadata";class Nc extends u7{}Nc.errorCode="insufficient_scope";var Ys1={[qc.errorCode]:qc,[ij.errorCode]:ij,[aj.errorCode]:aj,[nj.errorCode]:nj,[Gc.errorCode]:Gc,[zc.errorCode]:zc,[Uc.errorCode]:Uc,[nH.errorCode]:nH,[Wc.errorCode]:Wc,[Fc.errorCode]:Fc,[Hc.errorCode]:Hc,[Bc.errorCode]:Bc,[Dc.errorCode]:Dc,[Mc.errorCode]:Mc,[Vc.errorCode]:Vc,[Nc.errorCode]:Nc};class HX extends Error{constructor(J){super(J!==null&&J!==void 0?J:"Unauthorized")}}function qs1(J,Q){let Z=J.client_secret!==void 0;if(Q.length===0)return Z?"client_secret_post":"none";if(Z&&Q.includes("client_secret_basic"))return"client_secret_basic";if(Z&&Q.includes("client_secret_post"))return"client_secret_post";if(Q.includes("none"))return"none";return Z?"client_secret_post":"none"}function Gs1(J,Q,Z,X){let{client_id:Y,client_secret:K}=Q;switch(J){case"client_secret_basic":wV6(Y,K,Z);return;case"client_secret_post":IV6(Y,K,X);return;case"none":EV6(Y,X);return;default:throw Error(`Unsupported client authentication method: ${J}`)}}function wV6(J,Q,Z){if(!Q)throw Error("client_secret_basic authentication requires a client_secret");let X=btoa(`${J}:${Q}`);Z.set("Authorization",`Basic ${X}`)}function IV6(J,Q,Z){if(Z.set("client_id",J),Q)Z.set("client_secret",Q)}function EV6(J,Q){Q.set("client_id",J)}async function FG1(J){let Q=J instanceof Response?J.status:void 0,Z=J instanceof Response?await J.text():J;try{let X=Js1.parse(JSON.parse(Z)),{error:Y,error_description:K,error_uri:q}=X;return new(Ys1[Y]||nH)(K||"",q)}catch(X){let Y=`${Q?`HTTP ${Q}: `:""}Invalid OAuth error response: ${X}. Raw body: ${Z}`;return new nH(Y)}}async function rH(J,Q){var Z,X;try{return await WG1(J,Q)}catch(Y){if(Y instanceof ij||Y instanceof nj)return await((Z=J.invalidateCredentials)===null||Z===void 0?void 0:Z.call(J,"all")),await WG1(J,Q);else if(Y instanceof aj)return await((X=J.invalidateCredentials)===null||X===void 0?void 0:X.call(J,"tokens")),await WG1(J,Q);throw Y}}async function WG1(J,{serverUrl:Q,authorizationCode:Z,scope:X,resourceMetadataUrl:Y,fetchFn:K}){let q,G;try{if(q=await PV6(Q,{resourceMetadataUrl:Y},K),q.authorization_servers&&q.authorization_servers.length>0)G=q.authorization_servers[0]}catch(V){}if(!G)G=Q;let z=await $V6(Q,J,q),U=await kV6(G,{fetchFn:K}),W=await Promise.resolve(J.clientInformation());if(!W){if(Z!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");if(!J.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let V=await yV6(G,{metadata:U,clientMetadata:J.clientMetadata});await J.saveClientInformation(V),W=V}if(Z!==void 0){let V=await J.codeVerifier(),N=await bV6(G,{metadata:U,clientInformation:W,authorizationCode:Z,codeVerifier:V,redirectUri:J.redirectUrl,resource:z,addClientAuthentication:J.addClientAuthentication,fetchFn:K});return await J.saveTokens(N),"AUTHORIZED"}let F=await J.tokens();if(F===null||F===void 0?void 0:F.refresh_token)try{let V=await xV6(G,{metadata:U,clientInformation:W,refreshToken:F.refresh_token,resource:z,addClientAuthentication:J.addClientAuthentication});return await J.saveTokens(V),"AUTHORIZED"}catch(V){if(!(V instanceof u7)||V instanceof nH);else throw V}let H=J.state?await J.state():void 0,{authorizationUrl:B,codeVerifier:M}=await _V6(G,{metadata:U,clientInformation:W,state:H,redirectUrl:J.redirectUrl,scope:X||J.clientMetadata.scope,resource:z});return await J.saveCodeVerifier(M),await J.redirectToAuthorization(B),"REDIRECT"}async function $V6(J,Q,Z){let X=Zs1(J);if(Q.validateResourceURL)return await Q.validateResourceURL(X,Z===null||Z===void 0?void 0:Z.resource);if(!Z)return;if(!Xs1({requestedResource:X,configuredResource:Z.resource}))throw Error(`Protected resource ${Z.resource} does not match expected ${X} (or origin)`);return new URL(Z.resource)}function AS(J){let Q=J.headers.get("WWW-Authenticate");if(!Q)return;let[Z,X]=Q.split(" ");if(Z.toLowerCase()!=="bearer"||!X)return;let K=/resource_metadata="([^"]*)"/.exec(Q);if(!K)return;try{return new URL(K[1])}catch(q){return}}async function PV6(J,Q,Z=fetch){let X=await SV6(J,"oauth-protected-resource",Z,{protocolVersion:Q===null||Q===void 0?void 0:Q.protocolVersion,metadataUrl:Q===null||Q===void 0?void 0:Q.resourceMetadataUrl});if(!X||X.status===404)throw Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!X.ok)throw Error(`HTTP ${X.status} trying to load well-known OAuth protected resource metadata.`);return tr1.parse(await X.json())}async function HG1(J,Q,Z=fetch){try{return await Z(J,{headers:Q})}catch(X){if(X instanceof TypeError)if(Q)return HG1(J,void 0,Z);else return;throw X}}function TV6(J,Q="",Z={}){if(Q.endsWith("/"))Q=Q.slice(0,-1);return Z.prependPathname?`${Q}/.well-known/${J}`:`/.well-known/${J}${Q}`}async function Ks1(J,Q,Z=fetch){return await HG1(J,{"MCP-Protocol-Version":Q},Z)}function CV6(J,Q){return!J||J.status===404&&Q!=="/"}async function SV6(J,Q,Z,X){var Y,K;let q=new URL(J),G=(Y=X===null||X===void 0?void 0:X.protocolVersion)!==null&&Y!==void 0?Y:fj,z;if(X===null||X===void 0?void 0:X.metadataUrl)z=new URL(X.metadataUrl);else{let W=TV6(Q,q.pathname);z=new URL(W,(K=X===null||X===void 0?void 0:X.metadataServerUrl)!==null&&K!==void 0?K:q),z.search=q.search}let U=await Ks1(z,G,Z);if(!(X===null||X===void 0?void 0:X.metadataUrl)&&CV6(U,q.pathname)){let W=new URL(`/.well-known/${Q}`,q);U=await Ks1(W,G,Z)}return U}function vV6(J){let Q=typeof J==="string"?new URL(J):J,Z=Q.pathname!=="/",X=[];if(!Z)return X.push({url:new URL("/.well-known/oauth-authorization-server",Q.origin),type:"oauth"}),X.push({url:new URL("/.well-known/openid-configuration",Q.origin),type:"oidc"}),X;let Y=Q.pathname;if(Y.endsWith("/"))Y=Y.slice(0,-1);return X.push({url:new URL(`/.well-known/oauth-authorization-server${Y}`,Q.origin),type:"oauth"}),X.push({url:new URL("/.well-known/oauth-authorization-server",Q.origin),type:"oauth"}),X.push({url:new URL(`/.well-known/openid-configuration${Y}`,Q.origin),type:"oidc"}),X.push({url:new URL(`${Y}/.well-known/openid-configuration`,Q.origin),type:"oidc"}),X}async function kV6(J,{fetchFn:Q=fetch,protocolVersion:Z=fj}={}){var X;let Y={"MCP-Protocol-Version":Z},K=vV6(J);for(let{url:q,type:G}of K){let z=await HG1(q,Y,Q);if(!z)continue;if(!z.ok){if(z.status>=400&&z.status<500)continue;throw Error(`HTTP ${z.status} trying to load ${G==="oauth"?"OAuth":"OpenID provider"} metadata from ${q}`)}if(G==="oauth")return zG1.parse(await z.json());else{let U=er1.parse(await z.json());if(!((X=U.code_challenge_methods_supported)===null||X===void 0?void 0:X.includes("S256")))throw Error(`Incompatible OIDC provider at ${q}: does not support S256 code challenge method required by MCP specification`);return U}}return}async function _V6(J,{metadata:Q,clientInformation:Z,redirectUrl:X,scope:Y,state:K,resource:q}){let U;if(Q){if(U=new URL(Q.authorization_endpoint),!Q.response_types_supported.includes("code"))throw Error("Incompatible auth server: does not support response type code");if(!Q.code_challenge_methods_supported||!Q.code_challenge_methods_supported.includes("S256"))throw Error("Incompatible auth server: does not support code challenge method S256")}else U=new URL("/authorize",J);let W=await GG1(),F=W.code_verifier,H=W.code_challenge;if(U.searchParams.set("response_type","code"),U.searchParams.set("client_id",Z.client_id),U.searchParams.set("code_challenge",H),U.searchParams.set("code_challenge_method","S256"),U.searchParams.set("redirect_uri",String(X)),K)U.searchParams.set("state",K);if(Y)U.searchParams.set("scope",Y);if(Y===null||Y===void 0?void 0:Y.includes("offline_access"))U.searchParams.append("prompt","consent");if(q)U.searchParams.set("resource",q.href);return{authorizationUrl:U,codeVerifier:F}}async function bV6(J,{metadata:Q,clientInformation:Z,authorizationCode:X,codeVerifier:Y,redirectUri:K,resource:q,addClientAuthentication:G,fetchFn:z}){var U;let W="authorization_code",F=(Q===null||Q===void 0?void 0:Q.token_endpoint)?new URL(Q.token_endpoint):new URL("/token",J);if((Q===null||Q===void 0?void 0:Q.grant_types_supported)&&!Q.grant_types_supported.includes("authorization_code"))throw Error("Incompatible auth server: does not support grant type authorization_code");let H=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),B=new URLSearchParams({grant_type:"authorization_code",code:X,code_verifier:Y,redirect_uri:String(K)});if(G)G(H,B,J,Q);else{let V=(U=Q===null||Q===void 0?void 0:Q.token_endpoint_auth_methods_supported)!==null&&U!==void 0?U:[],N=qs1(Z,V);Gs1(N,Z,H,B)}if(q)B.set("resource",q.href);let M=await(z!==null&&z!==void 0?z:fetch)(F,{method:"POST",headers:H,body:B});if(!M.ok)throw await FG1(M);return UG1.parse(await M.json())}async function xV6(J,{metadata:Q,clientInformation:Z,refreshToken:X,resource:Y,addClientAuthentication:K,fetchFn:q}){var G;let z="refresh_token",U;if(Q){if(U=new URL(Q.token_endpoint),Q.grant_types_supported&&!Q.grant_types_supported.includes("refresh_token"))throw Error("Incompatible auth server: does not support grant type refresh_token")}else U=new URL("/token",J);let W=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),F=new URLSearchParams({grant_type:"refresh_token",refresh_token:X});if(K)K(W,F,J,Q);else{let B=(G=Q===null||Q===void 0?void 0:Q.token_endpoint_auth_methods_supported)!==null&&G!==void 0?G:[],M=qs1(Z,B);Gs1(M,Z,W,F)}if(Y)F.set("resource",Y.href);let H=await(q!==null&&q!==void 0?q:fetch)(U,{method:"POST",headers:W,body:F});if(!H.ok)throw await FG1(H);return UG1.parse({refresh_token:X,...await H.json()})}async function yV6(J,{metadata:Q,clientMetadata:Z,fetchFn:X}){let Y;if(Q){if(!Q.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");Y=new URL(Q.registration_endpoint)}else Y=new URL("/register",J);let K=await(X!==null&&X!==void 0?X:fetch)(Y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!K.ok)throw await FG1(K);return Qs1.parse(await K.json())}class zs1 extends Error{constructor(J,Q,Z){super(`SSE error: ${Q}`);this.code=J,this.event=Z}}class BG1{constructor(J,Q){this._url=J,this._resourceMetadataUrl=void 0,this._eventSourceInit=Q===null||Q===void 0?void 0:Q.eventSourceInit,this._requestInit=Q===null||Q===void 0?void 0:Q.requestInit,this._authProvider=Q===null||Q===void 0?void 0:Q.authProvider,this._fetch=Q===null||Q===void 0?void 0:Q.fetch}async _authThenStart(){var J;if(!this._authProvider)throw new HX("No auth provider");let Q;try{Q=await rH(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(Z){throw(J=this.onerror)===null||J===void 0||J.call(this,Z),Z}if(Q!=="AUTHORIZED")throw new HX;return await this._startOrAuth()}async _commonHeaders(){var J;let Q={};if(this._authProvider){let Z=await this._authProvider.tokens();if(Z)Q.Authorization=`Bearer ${Z.access_token}`}if(this._protocolVersion)Q["mcp-protocol-version"]=this._protocolVersion;return new Headers({...Q,...(J=this._requestInit)===null||J===void 0?void 0:J.headers})}_startOrAuth(){var J,Q,Z;let X=(Z=(Q=(J=this===null||this===void 0?void 0:this._eventSourceInit)===null||J===void 0?void 0:J.fetch)!==null&&Q!==void 0?Q:this._fetch)!==null&&Z!==void 0?Z:fetch;return new Promise((Y,K)=>{this._eventSource=new lj(this._url.href,{...this._eventSourceInit,fetch:async(q,G)=>{let z=await this._commonHeaders();z.set("Accept","text/event-stream");let U=await X(q,{...G,headers:z});if(U.status===401&&U.headers.has("www-authenticate"))this._resourceMetadataUrl=AS(U);return U}}),this._abortController=new AbortController,this._eventSource.onerror=(q)=>{var G;if(q.code===401&&this._authProvider){this._authThenStart().then(Y,K);return}let z=new zs1(q.code,q.message,q);K(z),(G=this.onerror)===null||G===void 0||G.call(this,z)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(q)=>{var G;let z=q;try{if(this._endpoint=new URL(z.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(U){K(U),(G=this.onerror)===null||G===void 0||G.call(this,U),this.close();return}Y()}),this._eventSource.onmessage=(q)=>{var G,z;let U=q,W;try{W=dH.parse(JSON.parse(U.data))}catch(F){(G=this.onerror)===null||G===void 0||G.call(this,F);return}(z=this.onmessage)===null||z===void 0||z.call(this,W)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(J){if(!this._authProvider)throw new HX("No auth provider");if(await rH(this._authProvider,{serverUrl:this._url,authorizationCode:J,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new HX("Failed to authorize")}async close(){var J,Q,Z;(J=this._abortController)===null||J===void 0||J.abort(),(Q=this._eventSource)===null||Q===void 0||Q.close(),(Z=this.onclose)===null||Z===void 0||Z.call(this)}async send(J){var Q,Z,X;if(!this._endpoint)throw Error("Not connected");try{let Y=await this._commonHeaders();Y.set("content-type","application/json");let K={...this._requestInit,method:"POST",headers:Y,body:JSON.stringify(J),signal:(Q=this._abortController)===null||Q===void 0?void 0:Q.signal},q=await((Z=this._fetch)!==null&&Z!==void 0?Z:fetch)(this._endpoint,K);if(!q.ok){if(q.status===401&&this._authProvider){if(this._resourceMetadataUrl=AS(q),await rH(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new HX;return this.send(J)}let G=await q.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${q.status}): ${G}`)}}catch(Y){throw(X=this.onerror)===null||X===void 0||X.call(this,Y),Y}}setProtocolVersion(J){this._protocolVersion=J}}pU();Xc();class DG1 extends TransformStream{constructor({onError:J,onRetry:Q,onComment:Z}={}){let X;super({start(Y){X=gj({onEvent:(K)=>{Y.enqueue(K)},onError(K){J==="terminate"?Y.error(K):typeof J=="function"&&J(K)},onRetry:Q,onComment:Z})},transform(Y){X.feed(Y)}})}}var fV6={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Lc extends Error{constructor(J,Q){super(`Streamable HTTP error: ${Q}`);this.code=J}}class MG1{constructor(J,Q){var Z;this._url=J,this._resourceMetadataUrl=void 0,this._requestInit=Q===null||Q===void 0?void 0:Q.requestInit,this._authProvider=Q===null||Q===void 0?void 0:Q.authProvider,this._fetch=Q===null||Q===void 0?void 0:Q.fetch,this._sessionId=Q===null||Q===void 0?void 0:Q.sessionId,this._reconnectionOptions=(Z=Q===null||Q===void 0?void 0:Q.reconnectionOptions)!==null&&Z!==void 0?Z:fV6}async _authThenStart(){var J;if(!this._authProvider)throw new HX("No auth provider");let Q;try{Q=await rH(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(Z){throw(J=this.onerror)===null||J===void 0||J.call(this,Z),Z}if(Q!=="AUTHORIZED")throw new HX;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var J;let Q={};if(this._authProvider){let X=await this._authProvider.tokens();if(X)Q.Authorization=`Bearer ${X.access_token}`}if(this._sessionId)Q["mcp-session-id"]=this._sessionId;if(this._protocolVersion)Q["mcp-protocol-version"]=this._protocolVersion;let Z=this._normalizeHeaders((J=this._requestInit)===null||J===void 0?void 0:J.headers);return new Headers({...Q,...Z})}async _startOrAuthSse(J){var Q,Z,X;let{resumptionToken:Y}=J;try{let K=await this._commonHeaders();if(K.set("Accept","text/event-stream"),Y)K.set("last-event-id",Y);let q=await((Q=this._fetch)!==null&&Q!==void 0?Q:fetch)(this._url,{method:"GET",headers:K,signal:(Z=this._abortController)===null||Z===void 0?void 0:Z.signal});if(!q.ok){if(q.status===401&&this._authProvider)return await this._authThenStart();if(q.status===405)return;throw new Lc(q.status,`Failed to open SSE stream: ${q.statusText}`)}this._handleSseStream(q.body,J,!0)}catch(K){throw(X=this.onerror)===null||X===void 0||X.call(this,K),K}}_getNextReconnectionDelay(J){let Q=this._reconnectionOptions.initialReconnectionDelay,Z=this._reconnectionOptions.reconnectionDelayGrowFactor,X=this._reconnectionOptions.maxReconnectionDelay;return Math.min(Q*Math.pow(Z,J),X)}_normalizeHeaders(J){if(!J)return{};if(J instanceof Headers)return Object.fromEntries(J.entries());if(Array.isArray(J))return Object.fromEntries(J);return{...J}}_scheduleReconnection(J,Q=0){var Z;let X=this._reconnectionOptions.maxRetries;if(X>0&&Q>=X){(Z=this.onerror)===null||Z===void 0||Z.call(this,Error(`Maximum reconnection attempts (${X}) exceeded.`));return}let Y=this._getNextReconnectionDelay(Q);setTimeout(()=>{this._startOrAuthSse(J).catch((K)=>{var q;(q=this.onerror)===null||q===void 0||q.call(this,Error(`Failed to reconnect SSE stream: ${K instanceof Error?K.message:String(K)}`)),this._scheduleReconnection(J,Q+1)})},Y)}_handleSseStream(J,Q,Z){if(!J)return;let{onresumptiontoken:X,replayMessageId:Y}=Q,K;(async()=>{var G,z,U,W;try{let F=J.pipeThrough(new TextDecoderStream).pipeThrough(new DG1).getReader();while(!0){let{value:H,done:B}=await F.read();if(B)break;if(H.id)K=H.id,X===null||X===void 0||X(H.id);if(!H.event||H.event==="message")try{let M=dH.parse(JSON.parse(H.data));if(Y!==void 0&&FS(M))M.id=Y;(G=this.onmessage)===null||G===void 0||G.call(this,M)}catch(M){(z=this.onerror)===null||z===void 0||z.call(this,M)}}}catch(F){if((U=this.onerror)===null||U===void 0||U.call(this,Error(`SSE stream disconnected: ${F}`)),Z&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:K,onresumptiontoken:X,replayMessageId:Y},0)}catch(H){(W=this.onerror)===null||W===void 0||W.call(this,Error(`Failed to reconnect: ${H instanceof Error?H.message:String(H)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(J){if(!this._authProvider)throw new HX("No auth provider");if(await rH(this._authProvider,{serverUrl:this._url,authorizationCode:J,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new HX("Failed to authorize")}async close(){var J,Q;(J=this._abortController)===null||J===void 0||J.abort(),(Q=this.onclose)===null||Q===void 0||Q.call(this)}async send(J,Q){var Z,X,Y,K;try{let{resumptionToken:q,onresumptiontoken:G}=Q||{};if(q){this._startOrAuthSse({resumptionToken:q,replayMessageId:_d(J)?J.id:void 0}).catch((V)=>{var N;return(N=this.onerror)===null||N===void 0?void 0:N.call(this,V)});return}let z=await this._commonHeaders();z.set("content-type","application/json"),z.set("accept","application/json, text/event-stream");let U={...this._requestInit,method:"POST",headers:z,body:JSON.stringify(J),signal:(Z=this._abortController)===null||Z===void 0?void 0:Z.signal},W=await((X=this._fetch)!==null&&X!==void 0?X:fetch)(this._url,U),F=W.headers.get("mcp-session-id");if(F)this._sessionId=F;if(!W.ok){if(W.status===401&&this._authProvider){if(this._resourceMetadataUrl=AS(W),await rH(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new HX;return this.send(J)}let V=await W.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${W.status}): ${V}`)}if(W.status===202){if(ga1(J))this._startOrAuthSse({resumptionToken:void 0}).catch((V)=>{var N;return(N=this.onerror)===null||N===void 0?void 0:N.call(this,V)});return}let B=(Array.isArray(J)?J:[J]).filter((V)=>("method"in V)&&("id"in V)&&V.id!==void 0).length>0,M=W.headers.get("content-type");if(B)if(M===null||M===void 0?void 0:M.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:G},!1);else if(M===null||M===void 0?void 0:M.includes("application/json")){let V=await W.json(),N=Array.isArray(V)?V.map((L)=>dH.parse(L)):[dH.parse(V)];for(let L of N)(Y=this.onmessage)===null||Y===void 0||Y.call(this,L)}else throw new Lc(-1,`Unexpected content type: ${M}`)}catch(q){throw(K=this.onerror)===null||K===void 0||K.call(this,q),q}}get sessionId(){return this._sessionId}async terminateSession(){var J,Q,Z;if(!this._sessionId)return;try{let X=await this._commonHeaders(),Y={...this._requestInit,method:"DELETE",headers:X,signal:(J=this._abortController)===null||J===void 0?void 0:J.signal},K=await((Q=this._fetch)!==null&&Q!==void 0?Q:fetch)(this._url,Y);if(!K.ok&&K.status!==405)throw new Lc(K.status,`Failed to terminate session: ${K.statusText}`);this._sessionId=void 0}catch(X){throw(Z=this.onerror)===null||Z===void 0||Z.call(this,X),X}}setProtocolVersion(J){this._protocolVersion=J}get protocolVersion(){return this._protocolVersion}}pU();n6();k0();F0();OS();DX();Tc();function Cc(J,Q){for(let Z of J??[])if(Pc(XN6(Q),Z.matches))return Z.action==="allow";return!0}function XN6(J){if("command"in J)return{command:J.command,args:J.args?.join(" "),env:J.env};return J}pU();F0();$5();Y7();var So1=h7.CLAUDE_3_5_SONNET.name;function vo1(J,Q){J.setRequestHandler(jq1,async(Z,X)=>{try{l.info("MCP sampling request:",Z,X);let Y=Z.params.messages.map((q)=>({role:q.role,content:[{type:"text",text:String(q.content.text||"")}]})),K=await XB(Y,[],Z.params.systemPrompt?[{type:"text",text:Z.params.systemPrompt}]:[],Q,void 0,void 0);if(K.message){let q=K.message.content.find((G)=>G.type==="text");if(q&&q.type==="text")return{content:{type:"text",text:q.text},model:K.message.model,role:"assistant"}}return l.error("MCP sampling missing result"),{content:{type:"text",text:"No response generated"},model:So1,role:"assistant"}}catch(Y){return l.error("MCP sampling failed:",Y),{content:{type:"text",text:"Error generating response"},model:So1,role:"assistant"}}})}var kz1=wc;function c36(J){return J.map((Q)=>{if(Q.type==="text"){let Z=D2.bufferByteLengthCompat(Q.text);if(Z>kz1){let X=D2.utf8Clamp(Q.text,kz1),Y=Math.round(Z/1024);return{type:"text",text:`${X}
@@ -5802,7 +5802,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||yO}function O76(J,Q){let
5802
5802
  `);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let q=K.optsWithGlobals(),G=await Q(K,q),z=0;await G.mcpService.initialized;let U=K.args.slice(1),W;if(L76()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await V76({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:G,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await G.asyncDispose(),G.cleanupTerminal(),process.exit(z)})}F0();Ew();O2();import{homedir as C49}from"node:os";import zu from"node:path";Iw();Y7();zN();u2();G3();n6();k0();function j76(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}F0();zN();import Xe8 from"node:fs";import R76 from"node:path";function w76(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!R76.isAbsolute(Q))return null;return l.debug("Extracted image path",{original:J,extracted:Q}),Q}function I76(J){try{let Q=R76.extname(J).toLowerCase(),Z=Bs1(Q);if(!Z)return l.warn("Unsupported image file extension",{ext:Q}),null;try{let X=Xe8.readFileSync(J);return Ye8(X,Z)}catch(X){l.error(`Failed to read image file ${J}:`,X)}}catch(Q){l.error("Error handling image file path",{imagePath:J,error:Q})}return null}function Ye8(J,Q){if(J.length>tj)return l.warn(`Image file too large: ${J.length} bytes (max: ${tj})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as m76}from"node:child_process";import{rmdir as ce8}from"node:fs/promises";import{tmpdir as le8}from"node:os";import u76 from"node:path";sj();F0();import{spawn as Ke8}from"node:child_process";import{promises as qe8}from"node:fs";function E76(J){return J.kind==="executable"}function $76(J){return J.kind==="markdown"}var XH=50000,P76=300000;async function Nb1(J,Q,Z,X={}){let{timeoutMs:Y=P76,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(l.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),$76(q))return await Ge8(q,Q);else if(E76(q))return await ze8(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return l.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function Ge8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await qe8.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>XH?Z.slice(0,XH)+`
5803
5803
  ... (output truncated at ${XH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function ze8(J,Q,Z=P76,X){return new Promise((Y)=>{let[K,q]=Ue8(J,Q);l.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=Us1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),l.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=Ke8(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=XH)F.push(V);else{let N=XH-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=XH)H.push(V);else{let N=XH-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
5804
5804
  ${L}`:L;if(B>XH)A+=`
5805
- ... (output truncated at ${XH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function Ue8(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Fe8(Z,X?[...X]:null,Y,Q);else return We8(Z,X?[...X]:null,Y,Q)}function We8(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Fe8(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}F0();Ew();O2();Iw();Y7();fV();dG();fB();n6();k0();import{mkdtemp as ie8,readFile as ae8,unlink as ne8,writeFile as _K2}from"fs/promises";var V41={};V6(V41,{scrollUp:()=>ve8,scrollDown:()=>ke8,link:()=>he8,image:()=>ge8,iTerm:()=>me8,exitAlternativeScreen:()=>ye8,eraseUp:()=>Se8,eraseStartLine:()=>Te8,eraseScreen:()=>Lb1,eraseLines:()=>$e8,eraseLine:()=>v76,eraseEndLine:()=>Pe8,eraseDown:()=>Ce8,enterAlternativeScreen:()=>xe8,cursorUp:()=>C76,cursorTo:()=>De8,cursorShow:()=>Ee8,cursorSavePosition:()=>Ae8,cursorRestorePosition:()=>Oe8,cursorPrevLine:()=>we8,cursorNextLine:()=>Re8,cursorMove:()=>Me8,cursorLeft:()=>S76,cursorHide:()=>Ie8,cursorGetPosition:()=>je8,cursorForward:()=>Ne8,cursorDown:()=>Ve8,cursorBackward:()=>Le8,clearTerminal:()=>be8,clearScreen:()=>_e8,beep:()=>fe8});import Ab1 from"node:process";var M41=globalThis.window?.document!==void 0,gY2=globalThis.process?.versions?.node!==void 0,mY2=globalThis.process?.versions?.bun!==void 0,uY2=globalThis.Deno?.version?.deno!==void 0,pY2=globalThis.process?.versions?.electron!==void 0,dY2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,cY2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,lY2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,iY2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,aY2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Nm=globalThis.navigator?.userAgentData?.platform,nY2=Nm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",rY2=Nm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",sY2=Nm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",oY2=Nm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),tY2=Nm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var q2="\x1B[",Am="\x1B]",WT="\x07",Lm=";",T76=!M41&&Ab1.env.TERM_PROGRAM==="Apple_Terminal",He8=!M41&&Ab1.platform==="win32",Be8=M41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Ab1.cwd,De8=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return q2+(J+1)+"G";return q2+(Q+1)+Lm+(J+1)+"H"},Me8=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=q2+-J+"D";else if(J>0)Z+=q2+J+"C";if(Q<0)Z+=q2+-Q+"A";else if(Q>0)Z+=q2+Q+"B";return Z},C76=(J=1)=>q2+J+"A",Ve8=(J=1)=>q2+J+"B",Ne8=(J=1)=>q2+J+"C",Le8=(J=1)=>q2+J+"D",S76=q2+"G",Ae8=T76?"\x1B7":q2+"s",Oe8=T76?"\x1B8":q2+"u",je8=q2+"6n",Re8=q2+"E",we8=q2+"F",Ie8=q2+"?25l",Ee8=q2+"?25h",$e8=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=v76+(Z<J-1?C76():"");if(J)Q+=S76;return Q},Pe8=q2+"K",Te8=q2+"1K",v76=q2+"2K",Ce8=q2+"J",Se8=q2+"1J",Lb1=q2+"2J",ve8=q2+"S",ke8=q2+"T",_e8="\x1Bc",be8=He8?`${Lb1}${q2}0f`:`${Lb1}${q2}3J${q2}H`,xe8=q2+"?1049h",ye8=q2+"?1049l",fe8=WT,he8=(J,Q)=>[Am,"8",Lm,Lm,Q,WT,J,Am,"8",Lm,Lm,WT].join(""),ge8=(J,Q={})=>{let Z=`${Am}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+WT},me8={setCwd:(J=Be8())=>`${Am}50;CurrentDir=${J}${WT}`,annotation(J,Q={}){let Z=`${Am}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+WT}};var N41=Y8(h76(),1);function JV(J,Q,{target:Z="stdout",...X}={}){if(!N41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return V41.link(J,Q)}JV.isSupported=N41.default.stdout;JV.stderr=(J,Q,Z={})=>JV(J,Q,{target:"stderr",...Z});JV.stderr.isSupported=N41.default.stderr;F0();dG();class Ib1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759608074-g34c1da"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Ze1(Q)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}F0();class L41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class oZ{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function g76(J){if(J instanceof L41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof oZ)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var re8={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (h_1(),L26));return(await K({worker:J.worker},{clientId:J.clientId,onUserDisconnect:()=>{Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}})).promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((G)=>{Z.sendStatus({connected:!1,errorMessage:G.message})}),new oZ(`Started connecting to Amp web interface
5805
+ ... (output truncated at ${XH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function Ue8(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Fe8(Z,X?[...X]:null,Y,Q);else return We8(Z,X?[...X]:null,Y,Q)}function We8(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Fe8(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}F0();Ew();O2();Iw();Y7();fV();dG();fB();n6();k0();import{mkdtemp as ie8,readFile as ae8,unlink as ne8,writeFile as _K2}from"fs/promises";var V41={};V6(V41,{scrollUp:()=>ve8,scrollDown:()=>ke8,link:()=>he8,image:()=>ge8,iTerm:()=>me8,exitAlternativeScreen:()=>ye8,eraseUp:()=>Se8,eraseStartLine:()=>Te8,eraseScreen:()=>Lb1,eraseLines:()=>$e8,eraseLine:()=>v76,eraseEndLine:()=>Pe8,eraseDown:()=>Ce8,enterAlternativeScreen:()=>xe8,cursorUp:()=>C76,cursorTo:()=>De8,cursorShow:()=>Ee8,cursorSavePosition:()=>Ae8,cursorRestorePosition:()=>Oe8,cursorPrevLine:()=>we8,cursorNextLine:()=>Re8,cursorMove:()=>Me8,cursorLeft:()=>S76,cursorHide:()=>Ie8,cursorGetPosition:()=>je8,cursorForward:()=>Ne8,cursorDown:()=>Ve8,cursorBackward:()=>Le8,clearTerminal:()=>be8,clearScreen:()=>_e8,beep:()=>fe8});import Ab1 from"node:process";var M41=globalThis.window?.document!==void 0,gY2=globalThis.process?.versions?.node!==void 0,mY2=globalThis.process?.versions?.bun!==void 0,uY2=globalThis.Deno?.version?.deno!==void 0,pY2=globalThis.process?.versions?.electron!==void 0,dY2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,cY2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,lY2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,iY2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,aY2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Nm=globalThis.navigator?.userAgentData?.platform,nY2=Nm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",rY2=Nm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",sY2=Nm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",oY2=Nm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),tY2=Nm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var q2="\x1B[",Am="\x1B]",WT="\x07",Lm=";",T76=!M41&&Ab1.env.TERM_PROGRAM==="Apple_Terminal",He8=!M41&&Ab1.platform==="win32",Be8=M41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Ab1.cwd,De8=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return q2+(J+1)+"G";return q2+(Q+1)+Lm+(J+1)+"H"},Me8=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=q2+-J+"D";else if(J>0)Z+=q2+J+"C";if(Q<0)Z+=q2+-Q+"A";else if(Q>0)Z+=q2+Q+"B";return Z},C76=(J=1)=>q2+J+"A",Ve8=(J=1)=>q2+J+"B",Ne8=(J=1)=>q2+J+"C",Le8=(J=1)=>q2+J+"D",S76=q2+"G",Ae8=T76?"\x1B7":q2+"s",Oe8=T76?"\x1B8":q2+"u",je8=q2+"6n",Re8=q2+"E",we8=q2+"F",Ie8=q2+"?25l",Ee8=q2+"?25h",$e8=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=v76+(Z<J-1?C76():"");if(J)Q+=S76;return Q},Pe8=q2+"K",Te8=q2+"1K",v76=q2+"2K",Ce8=q2+"J",Se8=q2+"1J",Lb1=q2+"2J",ve8=q2+"S",ke8=q2+"T",_e8="\x1Bc",be8=He8?`${Lb1}${q2}0f`:`${Lb1}${q2}3J${q2}H`,xe8=q2+"?1049h",ye8=q2+"?1049l",fe8=WT,he8=(J,Q)=>[Am,"8",Lm,Lm,Q,WT,J,Am,"8",Lm,Lm,WT].join(""),ge8=(J,Q={})=>{let Z=`${Am}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+WT},me8={setCwd:(J=Be8())=>`${Am}50;CurrentDir=${J}${WT}`,annotation(J,Q={}){let Z=`${Am}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+WT}};var N41=Y8(h76(),1);function JV(J,Q,{target:Z="stdout",...X}={}){if(!N41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return V41.link(J,Q)}JV.isSupported=N41.default.stdout;JV.stderr=(J,Q,Z={})=>JV(J,Q,{target:"stderr",...Z});JV.stderr.isSupported=N41.default.stderr;F0();dG();class Ib1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759636906-gf9ec5f"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Ze1(Q)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}F0();class L41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class oZ{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function g76(J){if(J instanceof L41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof oZ)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var re8={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (h_1(),L26));return(await K({worker:J.worker},{clientId:J.clientId,onUserDisconnect:()=>{Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}})).promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((G)=>{Z.sendStatus({connected:!1,errorMessage:G.message})}),new oZ(`Started connecting to Amp web interface
5806
5806
  Client ID: ${Y}
5807
5807
  You can now send messages from the web interface to this thread`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}}};class Eb1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=uT()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new Ib1(async()=>{try{return(await d8()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),j9.pipe(S0((Q)=>Q.settings["internal.modes"]),P8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...se8},process.env.AMP_CONNECT==="1")Object.assign(this.commands,re8);if(J)Object.assign(this.commands,oe8)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{l.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await Nb1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var se8={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${JJ} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:UX0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new L41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await ie8(u76.join(le8(),"amp-edit-")),Y=u76.join(X,"message.amp.md");m76(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await ae8(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return l.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await ne8(Y),await ce8(X)}catch(K){l.warn("Failed to clean up temporary file",K)}return}catch(Z){return l.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return PH("dangerouslyAllowAll",!1),new oZ("Amp is now following permissions rules for this session")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return PH("dangerouslyAllowAll",!0),new oZ("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await zT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw l.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:zT};await B41(Y);return}catch(Y){l.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return l.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new oZ(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return l.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
5808
5808
  `).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=Rv(new URL(Y),Z.id).toString(),G=`Thread URL: ${JV(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new oZ(`${G}
@@ -5996,7 +5996,7 @@ ${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTr
5996
5996
  `),J.stdout.write(`Thread: ${F}
5997
5997
  `),J.stdout.write(`Continue this thread with: amp threads continue ${U}
5998
5998
  `)}}function v49(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return h1.index(Z[X])}ib1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){o2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
5999
- `)}var cf1=df1.join(Ou1||df1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function y49(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function MV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")PH("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new N2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${e6.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")PH("experimental.agentMode",Q.agentMode)}var f49=P0.union([P0.object({command:P0.string(),args:P0.array(P0.string()).optional(),env:P0.record(P0.string(),P0.string()).optional()}).strict(),P0.object({url:P0.string()}).strict()]),h49=P0.record(P0.string(),f49);async function if1(J){try{await _49(df1.dirname(cf1),{recursive:!0}),await b49(cf1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function g49(){try{return(await wX6(cf1,"utf-8")).trim()}catch(J){return null}}async function m49(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return h49.parse(Q)}catch(Z){if(Z instanceof P0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function u49(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var OX6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??qG,description:`Custom settings file path (overrides the default location ${qG})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${P_1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:GG(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:qb1(),hidden:!0,description:(J)=>J?"Enable IDE connection. When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:Dj}],jX6=(J)=>("deprecated"in J)&&J.deprecated===!0,p49=(J)=>("hidden"in J)&&J.hidden===!0,d49=(J)=>("default"in J),c49=(J)=>("default"in J)?J.default:void 0;function l49(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new N2(jK.unknownCommand(Z),1,q)}}var IX6=null;function zk2(){return IX6}function i71(J){return{...J,getThreadEnvironment:g21,vfs:et1({os:J.fileSystem}),fileChangeTrackerStorage:new Iv(J.fileSystem),generateThreadTitle:ia,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var af1=b0.file(x49.homedir()),EX6=process.env.XDG_CONFIG_HOME?b0.file(process.env.XDG_CONFIG_HOME):p0.joinPath(af1,".config");async function VV(J,Q){Ed1("0.0.1759608074-g34c1da");let Z=nJ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([b0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:$_1,homeDir:af1,userConfigDir:EX6}),X=await d8();l.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=Ol(zj()),K=_t1({configService:Z,toolService:Y}),q=L30(Y,b9,ro).catch((L)=>{l.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{l.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)$d1(!0);if(Q.ide&&qb1())Pd1(!0);if(N16(Y),Q.jetbrains)Y.registerTool(Nn);else if(Q.ide)Y.registerTool(GY0);let z;if(!J.executeMode)z=new e21(process.cwd(),{},!0);else z=new class extends e21{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(g2.write(`No API key found. Starting login flow...
5999
+ `)}var cf1=df1.join(Ou1||df1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function y49(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function MV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")PH("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new N2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${e6.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")PH("experimental.agentMode",Q.agentMode)}var f49=P0.union([P0.object({command:P0.string(),args:P0.array(P0.string()).optional(),env:P0.record(P0.string(),P0.string()).optional()}).strict(),P0.object({url:P0.string()}).strict()]),h49=P0.record(P0.string(),f49);async function if1(J){try{await _49(df1.dirname(cf1),{recursive:!0}),await b49(cf1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function g49(){try{return(await wX6(cf1,"utf-8")).trim()}catch(J){return null}}async function m49(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return h49.parse(Q)}catch(Z){if(Z instanceof P0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function u49(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var OX6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??qG,description:`Custom settings file path (overrides the default location ${qG})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${P_1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:GG(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:qb1(),hidden:!0,description:(J)=>J?"Enable IDE connection. When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:Dj}],jX6=(J)=>("deprecated"in J)&&J.deprecated===!0,p49=(J)=>("hidden"in J)&&J.hidden===!0,d49=(J)=>("default"in J),c49=(J)=>("default"in J)?J.default:void 0;function l49(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new N2(jK.unknownCommand(Z),1,q)}}var IX6=null;function zk2(){return IX6}function i71(J){return{...J,getThreadEnvironment:g21,vfs:et1({os:J.fileSystem}),fileChangeTrackerStorage:new Iv(J.fileSystem),generateThreadTitle:ia,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var af1=b0.file(x49.homedir()),EX6=process.env.XDG_CONFIG_HOME?b0.file(process.env.XDG_CONFIG_HOME):p0.joinPath(af1,".config");async function VV(J,Q){Ed1("0.0.1759636906-gf9ec5f");let Z=nJ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([b0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:$_1,homeDir:af1,userConfigDir:EX6}),X=await d8();l.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=Ol(zj()),K=_t1({configService:Z,toolService:Y}),q=L30(Y,b9,ro).catch((L)=>{l.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{l.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)$d1(!0);if(Q.ide&&qb1())Pd1(!0);if(N16(Y),Q.jetbrains)Y.registerTool(Nn);else if(Q.ide)Y.registerTool(GY0);let z;if(!J.executeMode)z=new e21(process.cwd(),{},!0);else z=new class extends e21{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(g2.write(`No API key found. Starting login flow...
6000
6000
  `),!await i49(J))await nA(),process.exit(1)}let U=await Ge1({isDevelopment:!1}),W=new ZU1(U),F=new JU1(U,{lazy:!0}),H=new aB1(W),B=Q.notifications!==void 0?Q.notifications:!J.executeMode,M=A16({playNotificationSound:async(L)=>{if(B){L16(L);let A=cb1(),O=lb1();if((!A||O)&&X.settings["notifications.system.enabled"]!==!1){if(L==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(L==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:W});l.info("Starting Amp background services");let V=VX0({threadService:W,threadHistoryService:F,isExtensionDevelopment:!1}),N={configService:Z,toolService:Y,mcpService:K,threadService:W,threadHistoryService:F,threadSummaryService:H,threadSyncService:V,threadStorage:U,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:z,notificationService:M,fileSystem:Q.jetbrains||Q.ide?st1:b9};return{...N,async asyncDispose(){await N.mcpService.dispose(),await N.threadService.asyncDispose(),N.configService.unsubscribe(),N.toolService.dispose(),N.fuzzyServer.dispose(),N.threadSyncService.dispose(),N.settingsStorage[Symbol.dispose]()}}}async function i49(J){if(!J.executeMode){if(!await Bb1("Would you like to log in to Amp? [(y)es, (n)o]: "))return g2.write(`Login cancelled. Run the command again to retry.
6001
6001
  `),!1}return await $X6(J)}async function $X6(J){let Q=k49(32).toString("hex"),Z=await Hb1(J.ampURL,Q);try{await GT(Z)}catch(Y){l.error("Failed to open browser",{error:Y})}let X=await Hb1(J.ampURL,Q,!1);g2.write(`If your browser did not open automatically, visit:
6002
6002
 
@@ -6006,12 +6006,12 @@ ${e6.blue.bold(X)}
6006
6006
  Login successful! You can now use the Amp CLI.
6007
6007
  `),!0}catch(Y){return l.error("Login failed",{error:Y}),o2.write(`
6008
6008
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6009
- `),!1}}function a49(){let J=new Pg().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)sA(),process.exit(0);let H=F.originalError??F;j26(H)}),J.option("-V, --version","output the version number",()=>{g2.write(`0.0.1759608074-g34c1da (released 2025-10-04T20:05:53.134Z)
6010
- `),process.exit(0)}),J.addHelpText("after",R46()),J.configureHelp({formatHelp:w46}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await o49(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await s49(M,await Jb1(B,M.settings))});let Q=async(F,H,B)=>{nJ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:J0.of([b0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:af1,userConfigDir:EX6});let M={...H,executeMode:!1};await lf1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await RX6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await Y79(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await JY(M);if(H.pick)await Q(M,V,B);else await X79(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await JY(M);await Z79(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await RX6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await JY(M);await Q79(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await JY(M);await J79(M,V,F,B)}),O76(J,async(F,H)=>{let B=await JY(H);MV(F,H);let M=await VV(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:sA,asyncDispose:M.asyncDispose.bind(M)}}),n46(J),u46(J,async(F)=>{return(await JY(F)).settings}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);MV(H,B);let V=await VV(M,B);try{await f_1(V,{})}finally{await V.asyncDispose(),await sA()}});let X=new Pg().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(F)=>{await zb1(F.force||!1,F.verbose||!1,"0.0.1759608074-g34c1da"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,B){let V=typeof F.description==="string"?F.description:B===void 0?F.description(!0):F.description(B),N=new pM(H,V),L=c49(F);if(L)N.default(L);if(N.hidden=p49(F)||jX6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of OX6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new pM("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new pM("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new pM("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new pM("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new pM("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let F=new pM("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(F)}J.action(async(F,H)=>{let B=F,M=await JY(B);if(Object.keys(B).forEach((V)=>{let N=OX6.find((L)=>L.name===V);if(N&&jX6(N)&&!d49(N))o2.write(e6.yellow(`Warning: '--${V}' flag is deprecated
6009
+ `),!1}}function a49(){let J=new Pg().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)sA(),process.exit(0);let H=F.originalError??F;j26(H)}),J.option("-V, --version","output the version number",()=>{g2.write(`0.0.1759636906-gf9ec5f (released 2025-10-05T04:07:23.174Z)
6010
+ `),process.exit(0)}),J.addHelpText("after",R46()),J.configureHelp({formatHelp:w46}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await o49(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await s49(M,await Jb1(B,M.settings))});let Q=async(F,H,B)=>{nJ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:J0.of([b0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:af1,userConfigDir:EX6});let M={...H,executeMode:!1};await lf1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await RX6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await Y79(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await JY(M);if(H.pick)await Q(M,V,B);else await X79(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await JY(M);await Z79(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);await RX6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await JY(M);await Q79(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await JY(M);await J79(M,V,F,B)}),O76(J,async(F,H)=>{let B=await JY(H);MV(F,H);let M=await VV(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:sA,asyncDispose:M.asyncDispose.bind(M)}}),n46(J),u46(J,async(F)=>{return(await JY(F)).settings}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await JY(B);MV(H,B);let V=await VV(M,B);try{await f_1(V,{})}finally{await V.asyncDispose(),await sA()}});let X=new Pg().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(F)=>{await zb1(F.force||!1,F.verbose||!1,"0.0.1759636906-gf9ec5f"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,B){let V=typeof F.description==="string"?F.description:B===void 0?F.description(!0):F.description(B),N=new pM(H,V),L=c49(F);if(L)N.default(L);if(N.hidden=p49(F)||jX6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of OX6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new pM("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new pM("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new pM("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new pM("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new pM("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let F=new pM("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(F)}J.action(async(F,H)=>{let B=F,M=await JY(B);if(Object.keys(B).forEach((V)=>{let N=OX6.find((L)=>L.name===V);if(N&&jX6(N)&&!d49(N))o2.write(e6.yellow(`Warning: '--${V}' flag is deprecated
6011
6011
  `))}),H.args.length>0)l49(M,H);await lf1(M,B,H)});let U=new Pg("doctor").summary("Generate support bundle").description("Generate a support bundle for troubleshooting issues. This collects logs, configuration, and system information into a file that can be shared with Amp support for debugging.").option("--output-dir <path>","Directory to save the support bundle",process.cwd()).option("--include-full-logs","Include full log history",!1).allowUnknownOption(!1).action(async(F)=>{await e49(F.outputDir,F.includeFullLogs)});J.addCommand(U);let W=new Pg("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(F)=>{await t49(F.version)});return J.addCommand(W),J}async function l71(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??yK(),K=i71(J);if(Z)await J.threadStorage.set(Y,Z);let q=await vJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,F41(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(X7(z,"assistant"))await if1(Y),G.unsubscribe()});return await q.resume(),q}async function lf1(J,Q,Z){let X=process.stdin,Y=W41(Q);if(Y instanceof Error)tZ(Y.message);let K,q=null;if(Q.streamJsonInput)K="";else if(typeof Q.execute==="string"){K=Q.execute;let j=(await Db1()).trimEnd();if(j)q=j}else K=(await Db1()).trimEnd();if(Q.remote&&!J.executeMode)throw new N2("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new N2("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new N2("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new N2("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new N2("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new N2("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&K===""&&!Q.streamJsonInput)throw new N2("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
6012
6012
  Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMode&&!J.streamJsonMode&&typeof Q.execute!=="string")X=await J76();MV(Z,Q);let G=await VV(J,Q);IX6=G;let z=i71(G),U=async(j)=>{let R=await wX6(j,"utf-8"),I=JSON.parse(R);if(!SU(I.id))throw new N2(jK.invalidThreadId);return l71(G,{visibility:Y,thread:I})},W=async(j)=>{if(!SU(j))throw new N2(jK.invalidThreadId);let R=await G.threadService.get(j)??void 0;return l71(G,{visibility:Y,thread:R})},F=async()=>{try{if(Q.threadId)return W(Q.threadId);else return l71(G,{visibility:Y})}catch(j){if(j instanceof N2)throw j;throw await l21(j,Q.threadId),Error("handleError should have called process.exit()")}},H=async()=>{return l71(G,{visibility:Y})};if(Q.format==="jsonl")o2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6013
- `),await nA(),process.exit(1);if(J.executeMode&&Q.remote)await r46(K,q),await G.asyncDispose(),process.exit(0);let B=await F();if(J.executeMode)await k26(B,B.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1;if(Q.jetbrains||Q.ide){await nl1();let j=await Tj({jetbrainsOnly:Q.jetbrains});if(j.length===0)if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall");else a5.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(j.length===1){let R=j[0];if(R)a5.selectConfig(R)}else M=!0}let N=Wb1("0.0.1759608074-g34c1da",G.settingsStorage),L=J0.of([b0.file(process.cwd())]),A=uT(void 0,L);if(K)B.handle({type:"user:message",message:{content:[{type:"text",text:K}]}});let O=await d8();await AX6({stdin:X,stdout:process.stdout,history:new u_1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:B.threadID,worker:B,workerDeps:z,configService:G.configService,internalAPIClient:EJ,ampURL:J.ampURL,useGpt5:O.settings.gpt5??!1,startNewThread:H,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:a5,connectedClientsService:new Wp,commandRegistry:A,showJetBrainsInstaller:V,showIdePicker:M,startWithPicker:Q.startWithPicker,updateService:N,debugWidgetTree:Q.debugWidgetTree,jetbrainsMode:Q.jetbrains,clientId:Q.clientId}),await G.asyncDispose(),process.exit(0)}async function JY(J){if(J.interactive)o2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6014
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=LU({...J,getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(await o46(Y),await t46(Y),J.mcpConfig){let G=await m49(J.mcpConfig);Y=u49(Y,G)}let K=await Y.get("url","global");if(!K)K=oQ;if(!EH(K))l.info("Targeting custom Amp server",{ampURL:K});if(Y=pu1(Y),await Y.get("debug.httpLogging"))gu1();return{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:s46(await Jb1(J,Y))}}function n49(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function r49(){let J=n49(process.argv);if(X26({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),y49(l),l.info("Starting Amp CLI.",{version:"0.0.1759608074-g34c1da",buildTimestamp:"2025-10-04T20:05:53.134Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new N2(jK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await a49().parseAsync(process.argv)}r49().catch(l21);async function s49(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),g2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6013
+ `),await nA(),process.exit(1);if(J.executeMode&&Q.remote)await r46(K,q),await G.asyncDispose(),process.exit(0);let B=await F();if(J.executeMode)await k26(B,B.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1;if(Q.jetbrains||Q.ide){await nl1();let j=await Tj({jetbrainsOnly:Q.jetbrains});if(j.length===0)if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall");else a5.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(j.length===1){let R=j[0];if(R)a5.selectConfig(R)}else M=!0}let N=Wb1("0.0.1759636906-gf9ec5f",G.settingsStorage),L=J0.of([b0.file(process.cwd())]),A=uT(void 0,L);if(K)B.handle({type:"user:message",message:{content:[{type:"text",text:K}]}});let O=await d8();await AX6({stdin:X,stdout:process.stdout,history:new u_1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:B.threadID,worker:B,workerDeps:z,configService:G.configService,internalAPIClient:EJ,ampURL:J.ampURL,useGpt5:O.settings.gpt5??!1,startNewThread:H,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:a5,connectedClientsService:new Wp,commandRegistry:A,showJetBrainsInstaller:V,showIdePicker:M,startWithPicker:Q.startWithPicker,updateService:N,debugWidgetTree:Q.debugWidgetTree,jetbrainsMode:Q.jetbrains,clientId:Q.clientId}),await G.asyncDispose(),process.exit(0)}async function JY(J){if(J.interactive)o2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6014
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=LU({...J,getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(await o46(Y),await t46(Y),J.mcpConfig){let G=await m49(J.mcpConfig);Y=u49(Y,G)}let K=await Y.get("url","global");if(!K)K=oQ;if(!EH(K))l.info("Targeting custom Amp server",{ampURL:K});if(Y=pu1(Y),await Y.get("debug.httpLogging"))gu1();return{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:s46(await Jb1(J,Y))}}function n49(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function r49(){let J=n49(process.argv);if(X26({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),y49(l),l.info("Starting Amp CLI.",{version:"0.0.1759636906-gf9ec5f",buildTimestamp:"2025-10-05T04:07:23.174Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new N2(jK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await a49().parseAsync(process.argv)}r49().catch(l21);async function s49(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),g2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6015
6015
  `);else if(!EH(J.ampURL))g2.write(`Logging in to ${new URL(J.ampURL).hostname}
6016
6016
  `);let Z=process.env.AMP_API_KEY;if(Z)g2.write(`API key found in environment variable, storing...
6017
6017
  `),await Q.set("apiKey",Z,J.ampURL),g2.write(`API key successfully stored.
@@ -6027,7 +6027,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMo
6027
6027
  `));try{let Q;if(J)Q=J,o2.write(e6.blue(`Updating to version ${J}...
6028
6028
  `)),await KT(J),o2.write(e6.green(`✓ Successfully updated to version ${J}
6029
6029
  `));else{o2.write(e6.blue(`Checking for updates...
6030
- `));let{hasUpdate:X,latestVersion:Y}=await AR("0.0.1759608074-g34c1da");if(!X)o2.write(e6.green(`✓ Amp CLI is already up to date.
6030
+ `));let{hasUpdate:X,latestVersion:Y}=await AR("0.0.1759636906-gf9ec5f");if(!X)o2.write(e6.green(`✓ Amp CLI is already up to date.
6031
6031
  `)),process.exit(0);if(!Y)o2.write(e6.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,o2.write(e6.blue(`Updating to version ${Y}...
6032
6032
  `)),await KT(Y),o2.write(e6.green(`✓ Successfully updated to version ${Y}
6033
6033
  `))}let Z=await QO(Q);if(Z.warning)o2.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1759608074-g34c1da",
3
+ "version": "0.0.1759636906-gf9ec5f",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {