@anthropic-ai/claude-agent-sdk 0.2.97 → 0.2.98

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/browser-sdk.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // (c) Anthropic PBC. All rights reserved. Use is subject to the Legal Agreements outlined here: https://code.claude.com/docs/en/legal-and-compliance.
2
2
 
3
- // Version: 0.2.97
3
+ // Version: 0.2.98
4
4
  var xB=Object.create;var{getPrototypeOf:TB,defineProperty:QY,getOwnPropertyNames:fB}=Object;var gB=Object.prototype.hasOwnProperty;function yB($){return this[$]}var hB,uB,xU=($,X,J)=>{var Y=$!=null&&typeof $==="object";if(Y){var z=X?hB??=new WeakMap:uB??=new WeakMap,W=z.get($);if(W)return W}J=$!=null?xB(TB($)):{};let Q=X||!$||!$.__esModule?QY(J,"default",{value:$,enumerable:!0}):J;for(let G of fB($))if(!gB.call(Q,G))QY(Q,G,{get:yB.bind($,G),enumerable:!0});if(Y)z.set($,Q);return Q};var k=($,X)=>()=>(X||$((X={exports:{}}).exports,X),X.exports);var lB=($)=>$;function mB($,X){this[$]=lB.bind(null,X)}var x6=($,X)=>{for(var J in X)QY($,J,{get:X[J],enumerable:!0,configurable:!0,set:mB.bind(X,J)})};var cB=Symbol.dispose||Symbol.for("Symbol.dispose"),iB=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),D$=($,X,J)=>{if(X!=null){if(typeof X!=="object"&&typeof X!=="function")throw TypeError('Object expected to be assigned to "using" declaration');var Y;if(J)Y=X[iB];if(Y===void 0)Y=X[cB];if(typeof Y!=="function")throw TypeError("Object not disposable");$.push([J,Y,X])}else if(J)$.push([J]);return X},B$=($,X,J)=>{var Y=typeof SuppressedError==="function"?SuppressedError:function(Q,G,U,w){return w=Error(U),w.name="SuppressedError",w.error=Q,w.suppressed=G,w},z=(Q)=>X=J?new Y(Q,X,"An error was suppressed during disposal"):(J=!0,Q),W=(Q)=>{while(Q=$.pop())try{var G=Q[1]&&Q[1].call(Q[2]);if(Q[0])return Promise.resolve(G).then(W,(U)=>(z(U),W()))}catch(U){z(U)}if(J)throw X};return W()};var fJ=k((cH)=>{Object.defineProperty(cH,"__esModule",{value:!0});cH.regexpCode=cH.getEsmExportName=cH.getProperty=cH.safeStringify=cH.stringify=cH.strConcat=cH.addCodeArg=cH.str=cH._=cH.nil=cH._Code=cH.Name=cH.IDENTIFIER=cH._CodeOrName=void 0;class b7{}cH._CodeOrName=b7;cH.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class z0 extends b7{constructor($){super();if(!cH.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}cH.Name=z0;class M4 extends b7{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((X,J)=>`${X}${J}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((X,J)=>{if(J instanceof z0)X[J.str]=(X[J.str]||0)+1;return X},{})}}cH._Code=M4;cH.nil=new M4("");function lH($,...X){let J=[$[0]],Y=0;while(Y<X.length)AG(J,X[Y]),J.push($[++Y]);return new M4(J)}cH._=lH;var bG=new M4("+");function mH($,...X){let J=[TJ($[0])],Y=0;while(Y<X.length)J.push(bG),AG(J,X[Y]),J.push(bG,TJ($[++Y]));return vM(J),new M4(J)}cH.str=mH;function AG($,X){if(X instanceof M4)$.push(...X._items);else if(X instanceof z0)$.push(X);else $.push(CM(X))}cH.addCodeArg=AG;function vM($){let X=1;while(X<$.length-1){if($[X]===bG){let J=RM($[X-1],$[X+1]);if(J!==void 0){$.splice(X-1,3,J);continue}$[X++]="+"}X++}}function RM($,X){if(X==='""')return $;if($==='""')return X;if(typeof $=="string"){if(X instanceof z0||$[$.length-1]!=='"')return;if(typeof X!="string")return`${$.slice(0,-1)}${X}"`;if(X[0]==='"')return $.slice(0,-1)+X.slice(1);return}if(typeof X=="string"&&X[0]==='"'&&!($ instanceof z0))return`"${$}${X.slice(1)}`;return}function ZM($,X){return X.emptyStr()?$:$.emptyStr()?X:mH`${$}${X}`}cH.strConcat=ZM;function CM($){return typeof $=="number"||typeof $=="boolean"||$===null?$:TJ(Array.isArray($)?$.join(","):$)}function kM($){return new M4(TJ($))}cH.stringify=kM;function TJ($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}cH.safeStringify=TJ;function _M($){return typeof $=="string"&&cH.IDENTIFIER.test($)?new M4(`.${$}`):lH`[${$}]`}cH.getProperty=_M;function xM($){if(typeof $=="string"&&cH.IDENTIFIER.test($))return new M4(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}cH.getEsmExportName=xM;function TM($){return new M4($.toString())}cH.regexpCode=TM});var EG=k((dH)=>{Object.defineProperty(dH,"__esModule",{value:!0});dH.ValueScope=dH.ValueScopeName=dH.Scope=dH.varKinds=dH.UsedValueState=void 0;var o$=fJ();class nH extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var M7;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(M7||(dH.UsedValueState=M7={}));dH.varKinds={const:new o$.Name("const"),let:new o$.Name("let"),var:new o$.Name("var")};class PG{constructor({prefixes:$,parent:X}={}){this._names={},this._prefixes=$,this._parent=X}toName($){return $ instanceof o$.Name?$:this.name($)}name($){return new o$.Name(this._newName($))}_newName($){let X=this._names[$]||this._nameGroup($);return`${$}${X.index++}`}_nameGroup($){var X,J;if(((J=(X=this._parent)===null||X===void 0?void 0:X._prefixes)===null||J===void 0?void 0:J.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}dH.Scope=PG;class SG extends o$.Name{constructor($,X){super(X);this.prefix=$}setValue($,{property:X,itemIndex:J}){this.value=$,this.scopePath=o$._`.${new o$.Name(X)}[${J}]`}}dH.ValueScopeName=SG;var rM=o$._`\n`;class pH extends PG{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?rM:o$.nil}}get(){return this._scope}name($){return new SG($,this._newName($))}value($,X){var J;if(X.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Y=this.toName($),{prefix:z}=Y,W=(J=X.key)!==null&&J!==void 0?J:X.ref,Q=this._values[z];if(Q){let w=Q.get(W);if(w)return w}else Q=this._values[z]=new Map;Q.set(W,Y);let G=this._scope[z]||(this._scope[z]=[]),U=G.length;return G[U]=X.ref,Y.setValue(X,{property:z,itemIndex:U}),Y}getValue($,X){let J=this._values[$];if(!J)return;return J.get(X)}scopeRefs($,X=this._values){return this._reduceValues(X,(J)=>{if(J.scopePath===void 0)throw Error(`CodeGen: name "${J}" has no value`);return o$._`${$}${J.scopePath}`})}scopeCode($=this._values,X,J){return this._reduceValues($,(Y)=>{if(Y.value===void 0)throw Error(`CodeGen: name "${Y}" has no value`);return Y.value.code},X,J)}_reduceValues($,X,J={},Y){let z=o$.nil;for(let W in $){let Q=$[W];if(!Q)continue;let G=J[W]=J[W]||new Map;Q.forEach((U)=>{if(G.has(U))return;G.set(U,M7.Started);let w=X(U);if(w){let N=this.opts.es5?dH.varKinds.var:dH.varKinds.const;z=o$._`${z}${N} ${U} = ${w};${this.opts._n}`}else if(w=Y===null||Y===void 0?void 0:Y(U))z=o$._`${z}${w}${this.opts._n}`;else throw new nH(U);G.set(U,M7.Completed)})}return z}}dH.ValueScope=pH});var t=k((t$)=>{Object.defineProperty(t$,"__esModule",{value:!0});t$.or=t$.and=t$.not=t$.CodeGen=t$.operators=t$.varKinds=t$.ValueScopeName=t$.ValueScope=t$.Scope=t$.Name=t$.regexpCode=t$.stringify=t$.getProperty=t$.nil=t$.strConcat=t$.str=t$._=void 0;var J$=fJ(),P4=EG(),S6=fJ();Object.defineProperty(t$,"_",{enumerable:!0,get:function(){return S6._}});Object.defineProperty(t$,"str",{enumerable:!0,get:function(){return S6.str}});Object.defineProperty(t$,"strConcat",{enumerable:!0,get:function(){return S6.strConcat}});Object.defineProperty(t$,"nil",{enumerable:!0,get:function(){return S6.nil}});Object.defineProperty(t$,"getProperty",{enumerable:!0,get:function(){return S6.getProperty}});Object.defineProperty(t$,"stringify",{enumerable:!0,get:function(){return S6.stringify}});Object.defineProperty(t$,"regexpCode",{enumerable:!0,get:function(){return S6.regexpCode}});Object.defineProperty(t$,"Name",{enumerable:!0,get:function(){return S6.Name}});var Z7=EG();Object.defineProperty(t$,"Scope",{enumerable:!0,get:function(){return Z7.Scope}});Object.defineProperty(t$,"ValueScope",{enumerable:!0,get:function(){return Z7.ValueScope}});Object.defineProperty(t$,"ValueScopeName",{enumerable:!0,get:function(){return Z7.ValueScopeName}});Object.defineProperty(t$,"varKinds",{enumerable:!0,get:function(){return Z7.varKinds}});t$.operators={GT:new J$._Code(">"),GTE:new J$._Code(">="),LT:new J$._Code("<"),LTE:new J$._Code("<="),EQ:new J$._Code("==="),NEQ:new J$._Code("!=="),NOT:new J$._Code("!"),OR:new J$._Code("||"),AND:new J$._Code("&&"),ADD:new J$._Code("+")};class E6{optimizeNodes(){return this}optimizeNames($,X){return this}}class oH extends E6{constructor($,X,J){super();this.varKind=$,this.name=X,this.rhs=J}render({es5:$,_n:X}){let J=$?P4.varKinds.var:this.varKind,Y=this.rhs===void 0?"":` = ${this.rhs}`;return`${J} ${this.name}${Y};`+X}optimizeNames($,X){if(!$[this.name.str])return;if(this.rhs)this.rhs=W0(this.rhs,$,X);return this}get names(){return this.rhs instanceof J$._CodeOrName?this.rhs.names:{}}}class ZG extends E6{constructor($,X,J){super();this.lhs=$,this.rhs=X,this.sideEffects=J}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,X){if(this.lhs instanceof J$.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=W0(this.rhs,$,X),this}get names(){let $=this.lhs instanceof J$.Name?{}:{...this.lhs.names};return R7($,this.rhs)}}class tH extends ZG{constructor($,X,J,Y){super($,J,Y);this.op=X}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class aH extends E6{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class sH extends E6{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class eH extends E6{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class $K extends E6{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,X){return this.code=W0(this.code,$,X),this}get names(){return this.code instanceof J$._CodeOrName?this.code.names:{}}}class C7 extends E6{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((X,J)=>X+J.render($),"")}optimizeNodes(){let{nodes:$}=this,X=$.length;while(X--){let J=$[X].optimizeNodes();if(Array.isArray(J))$.splice(X,1,...J);else if(J)$[X]=J;else $.splice(X,1)}return $.length>0?this:void 0}optimizeNames($,X){let{nodes:J}=this,Y=J.length;while(Y--){let z=J[Y];if(z.optimizeNames($,X))continue;sM($,z.names),J.splice(Y,1)}return J.length>0?this:void 0}get names(){return this.nodes.reduce(($,X)=>Y1($,X.names),{})}}class v6 extends C7{render($){return"{"+$._n+super.render($)+"}"+$._n}}class XK extends C7{}class gJ extends v6{}gJ.kind="else";class $6 extends v6{constructor($,X){super(X);this.condition=$}render($){let X=`if(${this.condition})`+super.render($);if(this.else)X+="else "+this.else.render($);return X}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let X=this.else;if(X){let J=X.optimizeNodes();X=this.else=Array.isArray(J)?new gJ(J):J}if(X){if($===!1)return X instanceof $6?X:X.nodes;if(this.nodes.length)return this;return new $6(QK($),X instanceof $6?[X]:X.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,X){var J;if(this.else=(J=this.else)===null||J===void 0?void 0:J.optimizeNames($,X),!(super.optimizeNames($,X)||this.else))return;return this.condition=W0(this.condition,$,X),this}get names(){let $=super.names;if(R7($,this.condition),this.else)Y1($,this.else.names);return $}}$6.kind="if";class Y0 extends v6{}Y0.kind="for";class JK extends Y0{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,X){if(!super.optimizeNames($,X))return;return this.iteration=W0(this.iteration,$,X),this}get names(){return Y1(super.names,this.iteration.names)}}class zK extends Y0{constructor($,X,J,Y){super();this.varKind=$,this.name=X,this.from=J,this.to=Y}render($){let X=$.es5?P4.varKinds.var:this.varKind,{name:J,from:Y,to:z}=this;return`for(${X} ${J}=${Y}; ${J}<${z}; ${J}++)`+super.render($)}get names(){let $=R7(super.names,this.from);return R7($,this.to)}}class vG extends Y0{constructor($,X,J,Y){super();this.loop=$,this.varKind=X,this.name=J,this.iterable=Y}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,X){if(!super.optimizeNames($,X))return;return this.iterable=W0(this.iterable,$,X),this}get names(){return Y1(super.names,this.iterable.names)}}class P7 extends v6{constructor($,X,J){super();this.name=$,this.args=X,this.async=J}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}P7.kind="func";class S7 extends C7{render($){return"return "+super.render($)}}S7.kind="return";class YK extends v6{render($){let X="try"+super.render($);if(this.catch)X+=this.catch.render($);if(this.finally)X+=this.finally.render($);return X}optimizeNodes(){var $,X;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(X=this.finally)===null||X===void 0||X.optimizeNodes(),this}optimizeNames($,X){var J,Y;return super.optimizeNames($,X),(J=this.catch)===null||J===void 0||J.optimizeNames($,X),(Y=this.finally)===null||Y===void 0||Y.optimizeNames($,X),this}get names(){let $=super.names;if(this.catch)Y1($,this.catch.names);if(this.finally)Y1($,this.finally.names);return $}}class E7 extends v6{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}E7.kind="catch";class v7 extends v6{render($){return"finally"+super.render($)}}v7.kind="finally";class WK{constructor($,X={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...X,_n:X.lines?`
5
5
  `:""},this._extScope=$,this._scope=new P4.Scope({parent:$}),this._nodes=[new XK]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,X){let J=this._extScope.value($,X);return(this._values[J.prefix]||(this._values[J.prefix]=new Set)).add(J),J}getScopeValue($,X){return this._extScope.getValue($,X)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,X,J,Y){let z=this._scope.toName(X);if(J!==void 0&&Y)this._constants[z.str]=J;return this._leafNode(new oH($,z,J)),z}const($,X,J){return this._def(P4.varKinds.const,$,X,J)}let($,X,J){return this._def(P4.varKinds.let,$,X,J)}var($,X,J){return this._def(P4.varKinds.var,$,X,J)}assign($,X,J){return this._leafNode(new ZG($,X,J))}add($,X){return this._leafNode(new tH($,t$.operators.ADD,X))}code($){if(typeof $=="function")$();else if($!==J$.nil)this._leafNode(new $K($));return this}object(...$){let X=["{"];for(let[J,Y]of $){if(X.length>1)X.push(",");if(X.push(J),J!==Y||this.opts.es5)X.push(":"),(0,J$.addCodeArg)(X,Y)}return X.push("}"),new J$._Code(X)}if($,X,J){if(this._blockNode(new $6($)),X&&J)this.code(X).else().code(J).endIf();else if(X)this.code(X).endIf();else if(J)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new $6($))}else(){return this._elseNode(new gJ)}endIf(){return this._endBlockNode($6,gJ)}_for($,X){if(this._blockNode($),X)this.code(X).endFor();return this}for($,X){return this._for(new JK($),X)}forRange($,X,J,Y,z=this.opts.es5?P4.varKinds.var:P4.varKinds.let){let W=this._scope.toName($);return this._for(new zK(z,W,X,J),()=>Y(W))}forOf($,X,J,Y=P4.varKinds.const){let z=this._scope.toName($);if(this.opts.es5){let W=X instanceof J$.Name?X:this.var("_arr",X);return this.forRange("_i",0,J$._`${W}.length`,(Q)=>{this.var(z,J$._`${W}[${Q}]`),J(z)})}return this._for(new vG("of",Y,z,X),()=>J(z))}forIn($,X,J,Y=this.opts.es5?P4.varKinds.var:P4.varKinds.const){if(this.opts.ownProperties)return this.forOf($,J$._`Object.keys(${X})`,J);let z=this._scope.toName($);return this._for(new vG("in",Y,z,X),()=>J(z))}endFor(){return this._endBlockNode(Y0)}label($){return this._leafNode(new aH($))}break($){return this._leafNode(new sH($))}return($){let X=new S7;if(this._blockNode(X),this.code($),X.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(S7)}try($,X,J){if(!X&&!J)throw Error('CodeGen: "try" without "catch" and "finally"');let Y=new YK;if(this._blockNode(Y),this.code($),X){let z=this.name("e");this._currNode=Y.catch=new E7(z),X(z)}if(J)this._currNode=Y.finally=new v7,this.code(J);return this._endBlockNode(E7,v7)}throw($){return this._leafNode(new eH($))}block($,X){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(X);return this}endBlock($){let X=this._blockStarts.pop();if(X===void 0)throw Error("CodeGen: not in self-balancing block");let J=this._nodes.length-X;if(J<0||$!==void 0&&J!==$)throw Error(`CodeGen: wrong number of nodes: ${J} vs ${$} expected`);return this._nodes.length=X,this}func($,X=J$.nil,J,Y){if(this._blockNode(new P7($,X,J)),Y)this.code(Y).endFunc();return this}endFunc(){return this._endBlockNode(P7)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,X){let J=this._currNode;if(J instanceof $||X&&J instanceof X)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${X?`${$.kind}/${X.kind}`:$.kind}"`)}_elseNode($){let X=this._currNode;if(!(X instanceof $6))throw Error('CodeGen: "else" without "if"');return this._currNode=X.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let X=this._nodes;X[X.length-1]=$}}t$.CodeGen=WK;function Y1($,X){for(let J in X)$[J]=($[J]||0)+(X[J]||0);return $}function R7($,X){return X instanceof J$._CodeOrName?Y1($,X.names):$}function W0($,X,J){if($ instanceof J$.Name)return Y($);if(!z($))return $;return new J$._Code($._items.reduce((W,Q)=>{if(Q instanceof J$.Name)Q=Y(Q);if(Q instanceof J$._Code)W.push(...Q._items);else W.push(Q);return W},[]));function Y(W){let Q=J[W.str];if(Q===void 0||X[W.str]!==1)return W;return delete X[W.str],Q}function z(W){return W instanceof J$._Code&&W._items.some((Q)=>Q instanceof J$.Name&&X[Q.str]===1&&J[Q.str]!==void 0)}}function sM($,X){for(let J in X)$[J]=($[J]||0)-(X[J]||0)}function QK($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:J$._`!${RG($)}`}t$.not=QK;var eM=GK(t$.operators.AND);function $2(...$){return $.reduce(eM)}t$.and=$2;var X2=GK(t$.operators.OR);function J2(...$){return $.reduce(X2)}t$.or=J2;function GK($){return(X,J)=>X===J$.nil?J:J===J$.nil?X:J$._`${RG(X)} ${$} ${RG(J)}`}function RG($){return $ instanceof J$.Name?$:J$._`(${$})`}});var z$=k((BK)=>{Object.defineProperty(BK,"__esModule",{value:!0});BK.checkStrictMode=BK.getErrorPath=BK.Type=BK.useFunc=BK.setEvaluated=BK.evaluatedPropsToName=BK.mergeEvaluated=BK.eachItem=BK.unescapeJsonPointer=BK.escapeJsonPointer=BK.escapeFragment=BK.unescapeFragment=BK.schemaRefOrVal=BK.schemaHasRulesButRef=BK.schemaHasRules=BK.checkUnknownRules=BK.alwaysValidSchema=BK.toHash=void 0;var w$=t(),Q2=fJ();function G2($){let X={};for(let J of $)X[J]=!0;return X}BK.toHash=G2;function U2($,X){if(typeof X=="boolean")return X;if(Object.keys(X).length===0)return!0;return HK($,X),!KK(X,$.self.RULES.all)}BK.alwaysValidSchema=U2;function HK($,X=$.schema){let{opts:J,self:Y}=$;if(!J.strictSchema)return;if(typeof X==="boolean")return;let z=Y.RULES.keywords;for(let W in X)if(!z[W])DK($,`unknown keyword: "${W}"`)}BK.checkUnknownRules=HK;function KK($,X){if(typeof $=="boolean")return!$;for(let J in $)if(X[J])return!0;return!1}BK.schemaHasRules=KK;function w2($,X){if(typeof $=="boolean")return!$;for(let J in $)if(J!=="$ref"&&X.all[J])return!0;return!1}BK.schemaHasRulesButRef=w2;function N2({topSchemaRef:$,schemaPath:X},J,Y,z){if(!z){if(typeof J=="number"||typeof J=="boolean")return J;if(typeof J=="string")return w$._`${J}`}return w$._`${$}${X}${(0,w$.getProperty)(Y)}`}BK.schemaRefOrVal=N2;function H2($){return VK(decodeURIComponent($))}BK.unescapeFragment=H2;function K2($){return encodeURIComponent(kG($))}BK.escapeFragment=K2;function kG($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}BK.escapeJsonPointer=kG;function VK($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}BK.unescapeJsonPointer=VK;function V2($,X){if(Array.isArray($))for(let J of $)X(J);else X($)}BK.eachItem=V2;function wK({mergeNames:$,mergeToName:X,mergeValues:J,resultToName:Y}){return(z,W,Q,G)=>{let U=Q===void 0?W:Q instanceof w$.Name?(W instanceof w$.Name?$(z,W,Q):X(z,W,Q),Q):W instanceof w$.Name?(X(z,Q,W),W):J(W,Q);return G===w$.Name&&!(U instanceof w$.Name)?Y(z,U):U}}BK.mergeEvaluated={props:wK({mergeNames:($,X,J)=>$.if(w$._`${J} !== true && ${X} !== undefined`,()=>{$.if(w$._`${X} === true`,()=>$.assign(J,!0),()=>$.assign(J,w$._`${J} || {}`).code(w$._`Object.assign(${J}, ${X})`))}),mergeToName:($,X,J)=>$.if(w$._`${J} !== true`,()=>{if(X===!0)$.assign(J,!0);else $.assign(J,w$._`${J} || {}`),_G($,J,X)}),mergeValues:($,X)=>$===!0?!0:{...$,...X},resultToName:OK}),items:wK({mergeNames:($,X,J)=>$.if(w$._`${J} !== true && ${X} !== undefined`,()=>$.assign(J,w$._`${X} === true ? true : ${J} > ${X} ? ${J} : ${X}`)),mergeToName:($,X,J)=>$.if(w$._`${J} !== true`,()=>$.assign(J,X===!0?!0:w$._`${J} > ${X} ? ${J} : ${X}`)),mergeValues:($,X)=>$===!0?!0:Math.max($,X),resultToName:($,X)=>$.var("items",X)})};function OK($,X){if(X===!0)return $.var("props",!0);let J=$.var("props",w$._`{}`);if(X!==void 0)_G($,J,X);return J}BK.evaluatedPropsToName=OK;function _G($,X,J){Object.keys(J).forEach((Y)=>$.assign(w$._`${X}${(0,w$.getProperty)(Y)}`,!0))}BK.setEvaluated=_G;var NK={};function O2($,X){return $.scopeValue("func",{ref:X,code:NK[X.code]||(NK[X.code]=new Q2._Code(X.code))})}BK.useFunc=O2;var CG;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(CG||(BK.Type=CG={}));function D2($,X,J){if($ instanceof w$.Name){let Y=X===CG.Num;return J?Y?w$._`"[" + ${$} + "]"`:w$._`"['" + ${$} + "']"`:Y?w$._`"/" + ${$}`:w$._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return J?(0,w$.getProperty)($).toString():"/"+kG($)}BK.getErrorPath=D2;function DK($,X,J=$.opts.strictSchema){if(!J)return;if(X=`strict mode: ${X}`,J===!0)throw Error(X);$.self.logger.warn(X)}BK.checkStrictMode=DK});var X6=k((qK)=>{Object.defineProperty(qK,"__esModule",{value:!0});var u$=t(),_2={data:new u$.Name("data"),valCxt:new u$.Name("valCxt"),instancePath:new u$.Name("instancePath"),parentData:new u$.Name("parentData"),parentDataProperty:new u$.Name("parentDataProperty"),rootData:new u$.Name("rootData"),dynamicAnchors:new u$.Name("dynamicAnchors"),vErrors:new u$.Name("vErrors"),errors:new u$.Name("errors"),this:new u$.Name("this"),self:new u$.Name("self"),scope:new u$.Name("scope"),json:new u$.Name("json"),jsonPos:new u$.Name("jsonPos"),jsonLen:new u$.Name("jsonLen"),jsonPart:new u$.Name("jsonPart")};qK.default=_2});var yJ=k((bK)=>{Object.defineProperty(bK,"__esModule",{value:!0});bK.extendErrors=bK.resetErrorsCount=bK.reportExtraError=bK.reportError=bK.keyword$DataError=bK.keywordError=void 0;var Y$=t(),_7=z$(),i$=X6();bK.keywordError={message:({keyword:$})=>Y$.str`must pass "${$}" keyword validation`};bK.keyword$DataError={message:({keyword:$,schemaType:X})=>X?Y$.str`"${$}" keyword must be ${X} ($data)`:Y$.str`"${$}" keyword is invalid ($data)`};function T2($,X=bK.keywordError,J,Y){let{it:z}=$,{gen:W,compositeRule:Q,allErrors:G}=z,U=IK($,X,J);if(Y!==null&&Y!==void 0?Y:Q||G)LK(W,U);else FK(z,Y$._`[${U}]`)}bK.reportError=T2;function f2($,X=bK.keywordError,J){let{it:Y}=$,{gen:z,compositeRule:W,allErrors:Q}=Y,G=IK($,X,J);if(LK(z,G),!(W||Q))FK(Y,i$.default.vErrors)}bK.reportExtraError=f2;function g2($,X){$.assign(i$.default.errors,X),$.if(Y$._`${i$.default.vErrors} !== null`,()=>$.if(X,()=>$.assign(Y$._`${i$.default.vErrors}.length`,X),()=>$.assign(i$.default.vErrors,null)))}bK.resetErrorsCount=g2;function y2({gen:$,keyword:X,schemaValue:J,data:Y,errsCount:z,it:W}){if(z===void 0)throw Error("ajv implementation error");let Q=$.name("err");$.forRange("i",z,i$.default.errors,(G)=>{if($.const(Q,Y$._`${i$.default.vErrors}[${G}]`),$.if(Y$._`${Q}.instancePath === undefined`,()=>$.assign(Y$._`${Q}.instancePath`,(0,Y$.strConcat)(i$.default.instancePath,W.errorPath))),$.assign(Y$._`${Q}.schemaPath`,Y$.str`${W.errSchemaPath}/${X}`),W.opts.verbose)$.assign(Y$._`${Q}.schema`,J),$.assign(Y$._`${Q}.data`,Y)})}bK.extendErrors=y2;function LK($,X){let J=$.const("err",X);$.if(Y$._`${i$.default.vErrors} === null`,()=>$.assign(i$.default.vErrors,Y$._`[${J}]`),Y$._`${i$.default.vErrors}.push(${J})`),$.code(Y$._`${i$.default.errors}++`)}function FK($,X){let{gen:J,validateName:Y,schemaEnv:z}=$;if(z.$async)J.throw(Y$._`new ${$.ValidationError}(${X})`);else J.assign(Y$._`${Y}.errors`,X),J.return(!1)}var W1={keyword:new Y$.Name("keyword"),schemaPath:new Y$.Name("schemaPath"),params:new Y$.Name("params"),propertyName:new Y$.Name("propertyName"),message:new Y$.Name("message"),schema:new Y$.Name("schema"),parentSchema:new Y$.Name("parentSchema")};function IK($,X,J){let{createErrors:Y}=$.it;if(Y===!1)return Y$._`{}`;return h2($,X,J)}function h2($,X,J={}){let{gen:Y,it:z}=$,W=[u2(z,J),l2($,J)];return m2($,X,W),Y.object(...W)}function u2({errorPath:$},{instancePath:X}){let J=X?Y$.str`${$}${(0,_7.getErrorPath)(X,_7.Type.Str)}`:$;return[i$.default.instancePath,(0,Y$.strConcat)(i$.default.instancePath,J)]}function l2({keyword:$,it:{errSchemaPath:X}},{schemaPath:J,parentSchema:Y}){let z=Y?X:Y$.str`${X}/${$}`;if(J)z=Y$.str`${z}${(0,_7.getErrorPath)(J,_7.Type.Str)}`;return[W1.schemaPath,z]}function m2($,{params:X,message:J},Y){let{keyword:z,data:W,schemaValue:Q,it:G}=$,{opts:U,propertyName:w,topSchemaRef:N,schemaPath:K}=G;if(Y.push([W1.keyword,z],[W1.params,typeof X=="function"?X($):X||Y$._`{}`]),U.messages)Y.push([W1.message,typeof J=="function"?J($):J]);if(U.verbose)Y.push([W1.schema,Q],[W1.parentSchema,Y$._`${N}${K}`],[i$.default.data,W]);if(w)Y.push([W1.propertyName,w])}});var EK=k((PK)=>{Object.defineProperty(PK,"__esModule",{value:!0});PK.boolOrEmptySchema=PK.topBoolOrEmptySchema=void 0;var d2=yJ(),r2=t(),o2=X6(),t2={message:"boolean schema is false"};function a2($){let{gen:X,schema:J,validateName:Y}=$;if(J===!1)MK($,!1);else if(typeof J=="object"&&J.$async===!0)X.return(o2.default.data);else X.assign(r2._`${Y}.errors`,null),X.return(!0)}PK.topBoolOrEmptySchema=a2;function s2($,X){let{gen:J,schema:Y}=$;if(Y===!1)J.var(X,!1),MK($);else J.var(X,!0)}PK.boolOrEmptySchema=s2;function MK($,X){let{gen:J,data:Y}=$,z={gen:J,keyword:"false schema",data:Y,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,d2.reportError)(z,t2,void 0,X)}});var TG=k((vK)=>{Object.defineProperty(vK,"__esModule",{value:!0});vK.getRules=vK.isJSONType=void 0;var $P=["string","number","integer","boolean","null","object","array"],XP=new Set($P);function JP($){return typeof $=="string"&&XP.has($)}vK.isJSONType=JP;function zP(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}vK.getRules=zP});var fG=k((kK)=>{Object.defineProperty(kK,"__esModule",{value:!0});kK.shouldUseRule=kK.shouldUseGroup=kK.schemaHasRulesForType=void 0;function WP({schema:$,self:X},J){let Y=X.RULES.types[J];return Y&&Y!==!0&&ZK($,Y)}kK.schemaHasRulesForType=WP;function ZK($,X){return X.rules.some((J)=>CK($,J))}kK.shouldUseGroup=ZK;function CK($,X){var J;return $[X.keyword]!==void 0||((J=X.definition.implements)===null||J===void 0?void 0:J.some((Y)=>$[Y]!==void 0))}kK.shouldUseRule=CK});var hJ=k((gK)=>{Object.defineProperty(gK,"__esModule",{value:!0});gK.reportTypeError=gK.checkDataTypes=gK.checkDataType=gK.coerceAndCheckDataType=gK.getJSONTypes=gK.getSchemaTypes=gK.DataType=void 0;var UP=TG(),wP=fG(),NP=yJ(),o=t(),xK=z$(),Q0;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(Q0||(gK.DataType=Q0={}));function HP($){let X=TK($.type);if(X.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!X.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)X.push("null")}return X}gK.getSchemaTypes=HP;function TK($){let X=Array.isArray($)?$:$?[$]:[];if(X.every(UP.isJSONType))return X;throw Error("type must be JSONType or JSONType[]: "+X.join(","))}gK.getJSONTypes=TK;function KP($,X){let{gen:J,data:Y,opts:z}=$,W=VP(X,z.coerceTypes),Q=X.length>0&&!(W.length===0&&X.length===1&&(0,wP.schemaHasRulesForType)($,X[0]));if(Q){let G=yG(X,Y,z.strictNumbers,Q0.Wrong);J.if(G,()=>{if(W.length)OP($,X,W);else hG($)})}return Q}gK.coerceAndCheckDataType=KP;var fK=new Set(["string","number","integer","boolean","null"]);function VP($,X){return X?$.filter((J)=>fK.has(J)||X==="array"&&J==="array"):[]}function OP($,X,J){let{gen:Y,data:z,opts:W}=$,Q=Y.let("dataType",o._`typeof ${z}`),G=Y.let("coerced",o._`undefined`);if(W.coerceTypes==="array")Y.if(o._`${Q} == 'object' && Array.isArray(${z}) && ${z}.length == 1`,()=>Y.assign(z,o._`${z}[0]`).assign(Q,o._`typeof ${z}`).if(yG(X,z,W.strictNumbers),()=>Y.assign(G,z)));Y.if(o._`${G} !== undefined`);for(let w of J)if(fK.has(w)||w==="array"&&W.coerceTypes==="array")U(w);Y.else(),hG($),Y.endIf(),Y.if(o._`${G} !== undefined`,()=>{Y.assign(z,G),DP($,G)});function U(w){switch(w){case"string":Y.elseIf(o._`${Q} == "number" || ${Q} == "boolean"`).assign(G,o._`"" + ${z}`).elseIf(o._`${z} === null`).assign(G,o._`""`);return;case"number":Y.elseIf(o._`${Q} == "boolean" || ${z} === null
6
6
  || (${Q} == "string" && ${z} && ${z} == +${z})`).assign(G,o._`+${z}`);return;case"integer":Y.elseIf(o._`${Q} === "boolean" || ${z} === null
@@ -51,7 +51,7 @@ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
51
51
  `))$=L4($);let Y=`${new Date().toISOString()} [${X.toUpperCase()}] ${$.trim()}
52
52
  `;if(Fw()){Lw(Y);return}bL().write(Y)}function bw(){return Iw()??process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??f6(M3(),"debug",`${O3()}.txt`)}var Aw=j4(async()=>{try{let $=bw(),X=j0($),J=f6(X,"latest");await OL(J).catch(()=>{}),await VL($,J)}catch{}});var wy=(()=>{let $=process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;if($!==void 0){let X=Number($);if(!Number.isNaN(X)&&X>=0)return X}return 1/0})();var AL={[Symbol.dispose](){}};function ML(){return AL}var I$=ML;function L4($,X,J){let z=[];try{const Y=D$(z,I$`JSON.stringify(${$})`,0);return JSON.stringify($,X,J)}catch(W){var Q=W,G=1}finally{B$(z,Q,G)}}var Mw=($,X)=>{let Y=[];try{const J=D$(Y,I$`JSON.parse(${$})`,0);return typeof X>"u"?JSON.parse($):JSON.parse($,X)}catch(z){var W=z,Q=1}finally{B$(Y,W,Q)}};class QX{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor($){this.returned=$}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){if(this.queue.length>0)return Promise.resolve({done:!1,value:this.queue.shift()});if(this.isDone)return Promise.resolve({done:!0,value:void 0});if(this.hasError)return Promise.reject(this.hasError);return new Promise(($,X)=>{this.readResolve=$,this.readReject=X})}enqueue($){if(this.readResolve){let X=this.readResolve;this.readResolve=void 0,this.readReject=void 0,X({done:!1,value:$})}else this.queue.push($)}done(){if(this.isDone=!0,this.readResolve){let $=this.readResolve;this.readResolve=void 0,this.readReject=void 0,$({done:!0,value:void 0})}}error($){if(this.hasError=$,this.readReject){let X=this.readReject;this.readResolve=void 0,this.readReject=void 0,X($)}}return(){if(this.isDone=!0,this.returned)this.returned();return Promise.resolve({done:!0,value:void 0})}}class dY{sendMcpMessage;isClosed=!1;constructor($){this.sendMcpMessage=$}onclose;onerror;onmessage;async start(){}async send($){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage($)}async close(){if(this.isClosed)return;this.isClosed=!0,this.onclose?.()}}class rY{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;pendingControlResponses=new Map;cleanupPerformed=!1;sdkMessages;inputStream=new QX;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;sdkMcpTransports=new Map;sdkMcpServerInstances=new Map;pendingMcpResponses=new Map;firstResultReceivedResolve;firstResultReceived=!1;lastErrorResultText;transcriptMirrorBatcher;setIsSingleUserTurn($){this.isSingleUserTurn=$}setTranscriptMirrorBatcher($){this.transcriptMirrorBatcher=$}hasBidirectionalNeeds(){return this.sdkMcpTransports.size>0||this.hooks!==void 0&&Object.keys(this.hooks).length>0||this.canUseTool!==void 0||this.onElicitation!==void 0}constructor($,X,J,Y,z,W=new Map,Q,G,U){this.transport=$;this.isSingleUserTurn=X;this.canUseTool=J;this.hooks=Y;this.abortController=z;this.jsonSchema=Q;this.initConfig=G;this.onElicitation=U;for(let[w,N]of W)this.connectSdkMcpServer(w,N);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initialization=this.initialize(),this.initialization.catch(()=>{})}setError($){this.inputStream.error($)}async stopTask($){await this.request({subtype:"stop_task",task_id:$})}close(){this.cleanup()}cleanup($){if(this.cleanupPerformed)return;this.cleanupPerformed=!0;try{for(let J of this.cancelControllers.values())J.abort();this.cancelControllers.clear(),this.transport.close();let X=Error("Query closed before response received");for(let{reject:J}of this.pendingControlResponses.values())J(X);this.pendingControlResponses.clear();for(let{reject:J}of this.pendingMcpResponses.values())J(X);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let J of this.sdkMcpTransports.values())J.close().catch(()=>{});if(this.sdkMcpTransports.clear(),$)this.inputStream.error($);else this.inputStream.done()}catch(X){}}next(...[$]){return this.sdkMessages.next(...[$])}return($){return this.sdkMessages.return($)}throw($){return this.sdkMessages.throw($)}[Symbol.asyncIterator](){return this.sdkMessages}[Symbol.asyncDispose](){return this.sdkMessages[Symbol.asyncDispose]()}async readMessages(){try{for await(let $ of this.transport.readMessages()){if($.type==="control_response"){let X=this.pendingControlResponses.get($.response.request_id);if(X)X.handler($.response);continue}else if($.type==="control_request"){this.handleControlRequest($);continue}else if($.type==="control_cancel_request"){this.handleControlCancelRequest($);continue}else if($.type==="keep_alive")continue;else if($.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue($.filePath,$.entries);continue}if($.type==="system"&&$.subtype==="post_turn_summary")continue;if($.type==="result"){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();if(this.lastErrorResultText=$.is_error?$.subtype==="success"?$.result:$.errors.join("; "):void 0,this.firstResultReceived=!0,this.firstResultReceivedResolve)this.firstResultReceivedResolve();if(this.isSingleUserTurn)z4("[Query.readMessages] First result received for single-turn query, closing stdin"),this.transport.endInput()}else if(!($.type==="system"&&$.subtype==="session_state_changed"))this.lastErrorResultText=void 0;this.inputStream.enqueue($)}if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();if(this.firstResultReceivedResolve)this.firstResultReceivedResolve();this.inputStream.done(),this.cleanup()}catch($){if(this.transcriptMirrorBatcher)await this.transcriptMirrorBatcher.flush();if(this.firstResultReceivedResolve)this.firstResultReceivedResolve();if(this.lastErrorResultText!==void 0&&!($ instanceof T6)){let X=Error(`Claude Code returned an error result: ${this.lastErrorResultText}`);z4(`[Query.readMessages] Replacing exit error with result text. Original: ${gz($)}`),this.inputStream.error(X),this.cleanup(X);return}this.inputStream.error($),this.cleanup($)}}async handleControlRequest($){let X=new AbortController;this.cancelControllers.set($.request_id,X);try{let J=await this.processControlRequest($,X.signal);if(this.cleanupPerformed)return;let Y={type:"control_response",response:{subtype:"success",request_id:$.request_id,response:J}};await Promise.resolve(this.transport.write(L4(Y)+`
53
53
  `))}catch(J){if(this.cleanupPerformed)return;let Y={type:"control_response",response:{subtype:"error",request_id:$.request_id,error:gz(J)}};try{await Promise.resolve(this.transport.write(L4(Y)+`
54
- `))}catch(z){z4(`[Query.handleControlRequest] Error-response write failed: ${gz(z)}`,{level:"error"})}}finally{this.cancelControllers.delete($.request_id)}}handleControlCancelRequest($){let X=this.cancelControllers.get($.request_id);if(X)X.abort(),this.cancelControllers.delete($.request_id)}async processControlRequest($,X){if($.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");return{...await this.canUseTool($.request.tool_name,$.request.input,{signal:X,suggestions:$.request.permission_suggestions,blockedPath:$.request.blocked_path,decisionReason:$.request.decision_reason,title:$.request.title,displayName:$.request.display_name,description:$.request.description,toolUseID:$.request.tool_use_id,agentID:$.request.agent_id}),toolUseID:$.request.tool_use_id}}else if($.request.subtype==="hook_callback")return await this.handleHookCallbacks($.request.callback_id,$.request.input,$.request.tool_use_id,X);else if($.request.subtype==="mcp_message"){let J=$.request,Y=this.sdkMcpTransports.get(J.server_name);if(!Y)throw Error(`SDK MCP server not found: ${J.server_name}`);if("method"in J.message&&"id"in J.message&&J.message.id!==null)return{mcp_response:await this.handleMcpControlRequest(J.server_name,J,Y)};else{if(Y.onmessage)Y.onmessage(J.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if($.request.subtype==="elicitation"){let J=$.request;if(this.onElicitation)return await this.onElicitation({serverName:J.mcp_server_name,message:J.message,mode:J.mode,url:J.url,elicitationId:J.elicitation_id,requestedSchema:J.requested_schema,title:J.title,displayName:J.display_name,description:J.description},{signal:X});return{action:"decline"}}throw Error("Unsupported control request subtype: "+$.request.subtype)}async*readSdkMessages(){for await(let $ of this.inputStream)yield $}async initialize(){let $;if(this.hooks){$={};for(let[z,W]of Object.entries(this.hooks))if(W.length>0)$[z]=W.map((Q)=>{let G=[];for(let U of Q.hooks){let w=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(w,U),G.push(w)}return{matcher:Q.matcher,hookCallbackIds:G,timeout:Q.timeout}})}let X=this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,J={subtype:"initialize",hooks:$,sdkMcpServers:X,jsonSchema:this.jsonSchema,systemPrompt:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries};return(await this.request(J)).response}async interrupt(){await this.request({subtype:"interrupt"})}async setPermissionMode($){await this.request({subtype:"set_permission_mode",mode:$})}async setModel($){await this.request({subtype:"set_model",model:$})}async setMaxThinkingTokens($){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:$})}async applyFlagSettings($){await this.request({subtype:"apply_flag_settings",settings:$})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async rewindFiles($,X){return(await this.request({subtype:"rewind_files",user_message_id:$,dry_run:X?.dryRun})).response}async cancelAsyncMessage($){return(await this.request({subtype:"cancel_async_message",message_uuid:$})).response.cancelled}async seedReadState($,X){await this.request({subtype:"seed_read_state",path:$,mtime:X})}async enableRemoteControl($){return(await this.request({subtype:"remote_control",enabled:$})).response}async setProactive($){await this.request({subtype:"set_proactive",enabled:$})}async generateSessionTitle($,X){return(await this.request({subtype:"generate_session_title",description:$,persist:X?.persist})).response.title}async askSideQuestion($){return(await this.request({subtype:"side_question",question:$})).response.response}processPendingPermissionRequests($){for(let X of $)if(X.request.subtype==="can_use_tool")this.handleControlRequest(X).catch(()=>{})}request($){let X=Math.random().toString(36).substring(2,15),J={request_id:X,type:"control_request",request:$};return new Promise((Y,z)=>{this.pendingControlResponses.set(X,{handler:(W)=>{if(this.pendingControlResponses.delete(X),W.subtype==="success")Y(W);else if(z(Error(W.error)),W.pending_permission_requests)this.processPendingPermissionRequests(W.pending_permission_requests)},reject:z}),Promise.resolve(this.transport.write(L4(J)+`
54
+ `))}catch(z){z4(`[Query.handleControlRequest] Error-response write failed: ${gz(z)}`,{level:"error"})}}finally{this.cancelControllers.delete($.request_id)}}handleControlCancelRequest($){let X=this.cancelControllers.get($.request_id);if(X)X.abort(),this.cancelControllers.delete($.request_id)}async processControlRequest($,X){if($.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");return{...await this.canUseTool($.request.tool_name,$.request.input,{signal:X,suggestions:$.request.permission_suggestions,blockedPath:$.request.blocked_path,decisionReason:$.request.decision_reason,title:$.request.title,displayName:$.request.display_name,description:$.request.description,toolUseID:$.request.tool_use_id,agentID:$.request.agent_id}),toolUseID:$.request.tool_use_id}}else if($.request.subtype==="hook_callback")return await this.handleHookCallbacks($.request.callback_id,$.request.input,$.request.tool_use_id,X);else if($.request.subtype==="mcp_message"){let J=$.request,Y=this.sdkMcpTransports.get(J.server_name);if(!Y)throw Error(`SDK MCP server not found: ${J.server_name}`);if("method"in J.message&&"id"in J.message&&J.message.id!==null)return{mcp_response:await this.handleMcpControlRequest(J.server_name,J,Y)};else{if(Y.onmessage)Y.onmessage(J.message);return{mcp_response:{jsonrpc:"2.0",result:{},id:0}}}}else if($.request.subtype==="elicitation"){let J=$.request;if(this.onElicitation)return await this.onElicitation({serverName:J.mcp_server_name,message:J.message,mode:J.mode,url:J.url,elicitationId:J.elicitation_id,requestedSchema:J.requested_schema,title:J.title,displayName:J.display_name,description:J.description},{signal:X});return{action:"decline"}}throw Error("Unsupported control request subtype: "+$.request.subtype)}async*readSdkMessages(){for await(let $ of this.inputStream)yield $}async initialize(){let $;if(this.hooks){$={};for(let[z,W]of Object.entries(this.hooks))if(W.length>0)$[z]=W.map((Q)=>{let G=[];for(let U of Q.hooks){let w=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(w,U),G.push(w)}return{matcher:Q.matcher,hookCallbackIds:G,timeout:Q.timeout}})}let X=this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,J={subtype:"initialize",hooks:$,sdkMcpServers:X,jsonSchema:this.jsonSchema,systemPrompt:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries};return(await this.request(J)).response}async interrupt(){await this.request({subtype:"interrupt"})}async setPermissionMode($){await this.request({subtype:"set_permission_mode",mode:$})}async setModel($){await this.request({subtype:"set_model",model:$})}async setMaxThinkingTokens($){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:$})}async applyFlagSettings($){await this.request({subtype:"apply_flag_settings",settings:$})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async rewindFiles($,X){return(await this.request({subtype:"rewind_files",user_message_id:$,dry_run:X?.dryRun})).response}async cancelAsyncMessage($){return(await this.request({subtype:"cancel_async_message",message_uuid:$})).response.cancelled}async seedReadState($,X){await this.request({subtype:"seed_read_state",path:$,mtime:X})}async enableRemoteControl($,X){return(await this.request({subtype:"remote_control",enabled:$,...X!==void 0&&{name:X}})).response}async setProactive($){await this.request({subtype:"set_proactive",enabled:$})}async generateSessionTitle($,X){return(await this.request({subtype:"generate_session_title",description:$,persist:X?.persist})).response.title}async askSideQuestion($){return(await this.request({subtype:"side_question",question:$})).response.response}processPendingPermissionRequests($){for(let X of $)if(X.request.subtype==="can_use_tool")this.handleControlRequest(X).catch(()=>{})}request($){let X=Math.random().toString(36).substring(2,15),J={request_id:X,type:"control_request",request:$};return new Promise((Y,z)=>{this.pendingControlResponses.set(X,{handler:(W)=>{if(this.pendingControlResponses.delete(X),W.subtype==="success")Y(W);else if(z(Error(W.error)),W.pending_permission_requests)this.processPendingPermissionRequests(W.pending_permission_requests)},reject:z}),Promise.resolve(this.transport.write(L4(J)+`
55
55
  `)).catch((W)=>{this.pendingControlResponses.delete(X),z(W)})})}initializationResult(){return this.initialization}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer($){await this.request({subtype:"mcp_reconnect",serverName:$})}async toggleMcpServer($,X){await this.request({subtype:"mcp_toggle",serverName:$,enabled:X})}async enableChannel($){await this.request({subtype:"channel_enable",serverName:$})}async mcpAuthenticate($){return(await this.request({subtype:"mcp_authenticate",serverName:$})).response}async mcpClearAuth($){return(await this.request({subtype:"mcp_clear_auth",serverName:$})).response}async mcpSubmitOAuthCallbackUrl($,X){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:$,callbackUrl:X})).response}async claudeAuthenticate($){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:$})).response}async claudeOAuthCallback($,X){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:$,state:X})).response}async claudeOAuthWaitForCompletion(){return(await this.request({subtype:"claude_oauth_wait_for_completion"})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async getContextUsage(){return(await this.request({subtype:"get_context_usage"})).response}async reloadPlugins(){return(await this.request({subtype:"reload_plugins"})).response}async setMcpServers($){let X={},J={};for(let[G,U]of Object.entries($))if(U.type==="sdk"&&"instance"in U)X[G]=U.instance;else J[G]=U;let Y=new Set(this.sdkMcpServerInstances.keys()),z=new Set(Object.keys(X));for(let G of Y)if(!z.has(G))await this.disconnectSdkMcpServer(G);for(let[G,U]of Object.entries(X))if(!Y.has(G))this.connectSdkMcpServer(G,U);let W={};for(let G of Object.keys(X))W[G]={type:"sdk",name:G};return(await this.request({subtype:"mcp_set_servers",servers:{...J,...W}})).response}async accountInfo(){return(await this.initialization).account}async streamInput($){z4("[Query.streamInput] Starting to process input stream");try{let X=0;for await(let J of $){if(X++,z4(`[Query.streamInput] Processing message ${X}: ${J.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(L4(J)+`
56
56
  `))}if(z4(`[Query.streamInput] Finished processing ${X} messages from input stream`),X>0&&this.hasBidirectionalNeeds())z4("[Query.streamInput] Has bidirectional needs, waiting for first result"),await this.waitForFirstResult();z4("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(X){if(!(X instanceof T6))throw X}}waitForFirstResult(){if(this.firstResultReceived)return z4("[Query.waitForFirstResult] Result already received, returning immediately"),Promise.resolve();return new Promise(($)=>{if(this.abortController?.signal.aborted){$();return}this.abortController?.signal.addEventListener("abort",()=>$(),{once:!0}),this.firstResultReceivedResolve=$})}handleHookCallbacks($,X,J,Y){let z=this.hookCallbacks.get($);if(!z)throw Error(`No hook callback found for ID: ${$}`);return z(X,J,{signal:Y})}connectSdkMcpServer($,X){let J=new dY((Y)=>this.sendMcpServerMessageToCli($,Y));this.sdkMcpTransports.set($,J),this.sdkMcpServerInstances.set($,X),X.connect(J).catch((Y)=>{if(this.sdkMcpTransports.get($)===J)this.sdkMcpTransports.delete($);if(this.sdkMcpServerInstances.get($)===X)this.sdkMcpServerInstances.delete($);z4(`[Query.connectSdkMcpServer] Failed to connect MCP server '${$}': ${Y}`,{level:"error"})})}async disconnectSdkMcpServer($){let X=this.sdkMcpTransports.get($);if(X)await X.close(),this.sdkMcpTransports.delete($);this.sdkMcpServerInstances.delete($)}sendMcpServerMessageToCli($,X){if("id"in X&&X.id!==null&&X.id!==void 0){let Y=`${$}:${X.id}`,z=this.pendingMcpResponses.get(Y);if(z){z.resolve(X),this.pendingMcpResponses.delete(Y);return}}let J={type:"control_request",request_id:Uz(),request:{subtype:"mcp_message",server_name:$,message:X}};Promise.resolve(this.transport.write(L4(J)+`
57
57
  `)).catch((Y)=>{z4(`[Query.sendMcpServerMessageToCli] Transport write failed: ${Y}`,{level:"error"})})}handleMcpControlRequest($,X,J){let Y="id"in X.message?X.message.id:null,z=`${$}:${Y}`;return new Promise((W,Q)=>{let G=()=>{this.pendingMcpResponses.delete(z)},U=(N)=>{G(),W(N)},w=(N)=>{G(),Q(N)};if(this.pendingMcpResponses.set(z,{resolve:U,reject:w}),J.onmessage)J.onmessage(X.message);else{G(),Q(Error("No message handler registered"));return}})}}var Pw=15000,PL=50000;class oY{options;ws;ready=!1;abortController;messages=new QX;exitError;readyPromise;readyResolve;readyReject;abortHandler;keepAliveTimer;partialLine="";constructor($){this.options=$;this.abortController=$.abortController||new AbortController,this.readyPromise=new Promise((X,J)=>{this.readyResolve=X,this.readyReject=J}),this.readyPromise.catch(()=>{}),this.initialize()}initialize(){try{let{url:$}=this.options,X=new URL($);if(!X.protocol.startsWith("ws"))throw Error("WebSocket URL must use ws:// or wss:// protocol");this.ws=new globalThis.WebSocket(X.toString());let J=setTimeout(()=>{if(!this.ready){this.ws?.close();let Y=Error(`WebSocket connection timeout after ${Pw}ms`);if(this.exitError=Y,this.readyReject)this.readyReject(Y)}},Pw);if(this.ws.onopen=()=>{if(clearTimeout(J),this.ready=!0,this.readyResolve)this.readyResolve();if(this.options.authMessage&&this.ws)try{this.ws.send(L4(this.options.authMessage)+`