jazz-ai 0.12.1 → 0.12.2
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/dist/main.js +3 -3
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -64,7 +64,7 @@ Expecting one of '${Z.join("', '")}'`);if(this._lifeCycleHooks[I])this._lifeCycl
|
|
|
64
64
|
`),this.outputHelp({error:!0});let Z=G||{},b=Z.exitCode||1,W=Z.code||"commander.error";this._exit(b,W,I)}_parseOptionsEnv(){this.options.forEach((I)=>{if(I.envVar&&I.envVar in Fl.env){let G=I.attributeName();if(this.getOptionValue(G)===void 0||["default","config","env"].includes(this.getOptionValueSource(G)))if(I.required||I.optional)this.emit(`optionEnv:${I.name()}`,Fl.env[I.envVar]);else this.emit(`optionEnv:${I.name()}`)}})}_parseOptionsImplied(){let I=new ikZ(this.options),G=(Z)=>{return this.getOptionValue(Z)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(Z))};this.options.filter((Z)=>Z.implied!==void 0&&G(Z.attributeName())&&I.valueFromOption(this.getOptionValue(Z.attributeName()),Z)).forEach((Z)=>{Object.keys(Z.implied).filter((b)=>!G(b)).forEach((b)=>{this.setOptionValueWithSource(b,Z.implied[b],"implied")})})}missingArgument(I){let G=`error: missing required argument '${I}'`;this.error(G,{code:"commander.missingArgument"})}optionMissingArgument(I){let G=`error: option '${I.flags}' argument missing`;this.error(G,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(I){let G=`error: required option '${I.flags}' not specified`;this.error(G,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(I,G){let Z=(l)=>{let Y=l.attributeName(),N=this.getOptionValue(Y),V=this.options.find((d)=>d.negate&&Y===d.attributeName()),X=this.options.find((d)=>!d.negate&&Y===d.attributeName());if(V&&(V.presetArg===void 0&&N===!1||V.presetArg!==void 0&&N===V.presetArg))return V;return X||l},b=(l)=>{let Y=Z(l),N=Y.attributeName();if(this.getOptionValueSource(N)==="env")return`environment variable '${Y.envVar}'`;return`option '${Y.flags}'`},W=`error: ${b(I)} cannot be used with ${b(G)}`;this.error(W,{code:"commander.conflictingOption"})}unknownOption(I){if(this._allowUnknownOption)return;let G="";if(I.startsWith("--")&&this._showSuggestionAfterError){let b=[],W=this;do{let l=W.createHelp().visibleOptions(W).filter((Y)=>Y.long).map((Y)=>Y.long);b=b.concat(l),W=W.parent}while(W&&!W._enablePositionalOptions);G=aeI(I,b)}let Z=`error: unknown option '${I}'${G}`;this.error(Z,{code:"commander.unknownOption"})}_excessArguments(I){if(this._allowExcessArguments)return;let G=this.registeredArguments.length,Z=G===1?"":"s",W=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${G} argument${Z} but got ${I.length}.`;this.error(W,{code:"commander.excessArguments"})}unknownCommand(){let I=this.args[0],G="";if(this._showSuggestionAfterError){let b=[];this.createHelp().visibleCommands(this).forEach((W)=>{if(b.push(W.name()),W.alias())b.push(W.alias())}),G=aeI(I,b)}let Z=`error: unknown command '${I}'${G}`;this.error(Z,{code:"commander.unknownCommand"})}version(I,G,Z){if(I===void 0)return this._version;this._version=I,G=G||"-V, --version",Z=Z||"output the version number";let b=this.createOption(G,Z);return this._versionOptionName=b.attributeName(),this._registerOption(b),this.on("option:"+b.name(),()=>{this._outputConfiguration.writeOut(`${I}
|
|
65
65
|
`),this._exit(0,"commander.version",I)}),this}description(I,G){if(I===void 0&&G===void 0)return this._description;if(this._description=I,G)this._argsDescription=G;return this}summary(I){if(I===void 0)return this._summary;return this._summary=I,this}alias(I){if(I===void 0)return this._aliases[0];let G=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)G=this.commands[this.commands.length-1];if(I===G._name)throw Error("Command alias can't be the same as its name");let Z=this.parent?._findCommand(I);if(Z){let b=[Z.name()].concat(Z.aliases()).join("|");throw Error(`cannot add alias '${I}' to command '${this.name()}' as already have command '${b}'`)}return G._aliases.push(I),this}aliases(I){if(I===void 0)return this._aliases;return I.forEach((G)=>this.alias(G)),this}usage(I){if(I===void 0){if(this._usage)return this._usage;let G=this.registeredArguments.map((Z)=>{return _kZ(Z)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?G:[]).join(" ")}return this._usage=I,this}name(I){if(I===void 0)return this._name;return this._name=I,this}helpGroup(I){if(I===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=I,this}commandsGroup(I){if(I===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=I,this}optionsGroup(I){if(I===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=I,this}_initOptionGroup(I){if(this._defaultOptionGroup&&!I.helpGroupHeading)I.helpGroup(this._defaultOptionGroup)}_initCommandGroup(I){if(this._defaultCommandGroup&&!I.helpGroup())I.helpGroup(this._defaultCommandGroup)}nameFromFilename(I){return this._name=qh.basename(I,qh.extname(I)),this}executableDir(I){if(I===void 0)return this._executableDir;return this._executableDir=I,this}helpInformation(I){let G=this.createHelp(),Z=this._getOutputContext(I);G.prepareContext({error:Z.error,helpWidth:Z.helpWidth,outputHasColors:Z.hasColors});let b=G.formatHelp(this,G);if(Z.hasColors)return b;return this._outputConfiguration.stripColor(b)}_getOutputContext(I){I=I||{};let G=!!I.error,Z,b,W;if(G)Z=(Y)=>this._outputConfiguration.writeErr(Y),b=this._outputConfiguration.getErrHasColors(),W=this._outputConfiguration.getErrHelpWidth();else Z=(Y)=>this._outputConfiguration.writeOut(Y),b=this._outputConfiguration.getOutHasColors(),W=this._outputConfiguration.getOutHelpWidth();return{error:G,write:(Y)=>{if(!b)Y=this._outputConfiguration.stripColor(Y);return Z(Y)},hasColors:b,helpWidth:W}}outputHelp(I){let G;if(typeof I==="function")G=I,I=void 0;let Z=this._getOutputContext(I),b={error:Z.error,write:Z.write,command:this};this._getCommandAndAncestors().reverse().forEach((l)=>l.emit("beforeAllHelp",b)),this.emit("beforeHelp",b);let W=this.helpInformation({error:Z.error});if(G){if(W=G(W),typeof W!=="string"&&!Buffer.isBuffer(W))throw Error("outputHelp callback must return a string or a Buffer")}if(Z.write(W),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",b),this._getCommandAndAncestors().forEach((l)=>l.emit("afterAllHelp",b))}helpOption(I,G){if(typeof I==="boolean"){if(I){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(I??"-h, --help",G??"display help for command"),I||G)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(I){return this._helpOption=I,this._initOptionGroup(I),this}help(I){this.outputHelp(I);let G=Number(Fl.exitCode??0);if(G===0&&I&&typeof I!=="function"&&I.error)G=1;this._exit(G,"commander.help","(outputHelp)")}addHelpText(I,G){let Z=["beforeAll","before","after","afterAll"];if(!Z.includes(I))throw Error(`Unexpected value for position to addHelpText.
|
|
66
66
|
Expecting one of '${Z.join("', '")}'`);let b=`${I}Help`;return this.on(b,(W)=>{let l;if(typeof G==="function")l=G({error:W.error,command:W.command});else l=G;if(l)W.write(`${l}
|
|
67
|
-
`)}),this}_outputHelpIfRequested(I){let G=this._getHelpOption();if(G&&I.find((b)=>G.is(b)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function xeI(I){return I.map((G)=>{if(!G.startsWith("--inspect"))return G;let Z,b="127.0.0.1",W="9229",l;if((l=G.match(/^(--inspect(-brk)?)$/))!==null)Z=l[1];else if((l=G.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Z=l[1],/^\d+$/.test(l[3]))W=l[3];else b=l[3];else if((l=G.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Z=l[1],b=l[3],W=l[4];if(Z&&W!=="0")return`${Z}=${b}:${parseInt(W)+1}`;return G})}function KmI(){if(Fl.env.NO_COLOR||Fl.env.FORCE_COLOR==="0"||Fl.env.FORCE_COLOR==="false")return!1;if(Fl.env.FORCE_COLOR||Fl.env.CLICOLOR_FORCE!==void 0)return!0;return}fkZ.Command=jmI;fkZ.useColor=KmI});var qeI=U((ekZ)=>{var{Argument:KeI}=Si(),{Command:DmI}=MeI(),{CommanderError:tkZ,InvalidArgumentError:jeI}=lK(),{Help:rkZ}=OmI(),{Option:DeI}=amI();ekZ.program=new DmI;ekZ.createCommand=(I)=>new DmI(I);ekZ.createOption=(I,G)=>new DeI(I,G);ekZ.createArgument=(I,G)=>new KeI(I,G);ekZ.Command=DmI;ekZ.Option=DeI;ekZ.Argument=KeI;ekZ.Help=rkZ;ekZ.CommanderError=tkZ;ekZ.InvalidArgumentError=jeI;ekZ.InvalidOptionArgumentError=jeI});var TeI,QRW,RRW,HRW,hRW,wRW,JRW,vRW,SeI,ERW,yRW,CRW;var neI=g(()=>{TeI=zZ(qeI(),1),{program:QRW,createCommand:RRW,createArgument:HRW,createOption:hRW,CommanderError:wRW,InvalidArgumentError:JRW,InvalidOptionArgumentError:vRW,Command:SeI,Argument:ERW,Option:yRW,Help:CRW}=TeI.default});var Id;var _i=g(()=>{Id={name:"jazz-ai",version:"0.12.
|
|
67
|
+
`)}),this}_outputHelpIfRequested(I){let G=this._getHelpOption();if(G&&I.find((b)=>G.is(b)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function xeI(I){return I.map((G)=>{if(!G.startsWith("--inspect"))return G;let Z,b="127.0.0.1",W="9229",l;if((l=G.match(/^(--inspect(-brk)?)$/))!==null)Z=l[1];else if((l=G.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Z=l[1],/^\d+$/.test(l[3]))W=l[3];else b=l[3];else if((l=G.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Z=l[1],b=l[3],W=l[4];if(Z&&W!=="0")return`${Z}=${b}:${parseInt(W)+1}`;return G})}function KmI(){if(Fl.env.NO_COLOR||Fl.env.FORCE_COLOR==="0"||Fl.env.FORCE_COLOR==="false")return!1;if(Fl.env.FORCE_COLOR||Fl.env.CLICOLOR_FORCE!==void 0)return!0;return}fkZ.Command=jmI;fkZ.useColor=KmI});var qeI=U((ekZ)=>{var{Argument:KeI}=Si(),{Command:DmI}=MeI(),{CommanderError:tkZ,InvalidArgumentError:jeI}=lK(),{Help:rkZ}=OmI(),{Option:DeI}=amI();ekZ.program=new DmI;ekZ.createCommand=(I)=>new DmI(I);ekZ.createOption=(I,G)=>new DeI(I,G);ekZ.createArgument=(I,G)=>new KeI(I,G);ekZ.Command=DmI;ekZ.Option=DeI;ekZ.Argument=KeI;ekZ.Help=rkZ;ekZ.CommanderError=tkZ;ekZ.InvalidArgumentError=jeI;ekZ.InvalidOptionArgumentError=jeI});var TeI,QRW,RRW,HRW,hRW,wRW,JRW,vRW,SeI,ERW,yRW,CRW;var neI=g(()=>{TeI=zZ(qeI(),1),{program:QRW,createCommand:RRW,createArgument:HRW,createOption:hRW,CommanderError:wRW,InvalidArgumentError:JRW,InvalidOptionArgumentError:vRW,Command:SeI,Argument:ERW,Option:yRW,Help:CRW}=TeI.default});var Id;var _i=g(()=>{Id={name:"jazz-ai",version:"0.12.2",description:"Your terminal. Your agent. Your rules.",license:"MIT",main:"dist/main.js",types:"dist/main.d.ts",type:"module",bin:{jazz:"./dist/main.js"},author:{name:"lvndry",email:"lvndry@proton.me",url:"https://github.com/lvndry"},homepage:"https://github.com/lvndry/jazz",repository:{type:"git",url:"https://github.com/lvndry/jazz.git"},bugs:{url:"https://github.com/lvndry/jazz/issues"},keywords:["cli","agents","automation","agentic","typescript","effect-ts","ai","llm","workflow","email","git","productivity","assistant","task-automation","developer-tools","ai-assistant","ai-agent","mcp","mcp-server","agent-skills"],scripts:{build:"bun run scripts/build.ts",typecheck:"bun run tsc --noEmit",dev:"bun --watch src/main.ts",start:"bun dist/main.js",cli:"bun src/main.ts",prepare:"git config core.hooksPath .githooks || true",lint:"bun eslint src --cache","lint:fix":"bun eslint src --fix --cache",format:"bun prettier --write src",test:"bun test","test:watch":"bun test --watch","test:typecheck":"bunx tsc --project tsconfig.test.json",clean:"rm -rf dist",prebuild:"bun run clean",prepublishOnly:"bun run build"},dependencies:{"@ai-sdk/alibaba":"^1.0.21","@ai-sdk/anthropic":"^3.0.74","@ai-sdk/cerebras":"^2.0.49","@ai-sdk/deepseek":"^2.0.32","@ai-sdk/fireworks":"^2.0.50","@ai-sdk/google":"^3.0.67","@ai-sdk/groq":"^3.0.38","@ai-sdk/mcp":"^1.0.39","@ai-sdk/mistral":"^3.0.33","@ai-sdk/moonshotai":"^2.0.20","@ai-sdk/openai":"^3.0.58","@ai-sdk/openai-compatible":"^2.0.45","@ai-sdk/togetherai":"^2.0.49","@ai-sdk/xai":"^3.0.87","@effect/cluster":"^0.58.2","@effect/platform":"^0.96.1","@effect/platform-node":"^0.106.0","@effect/rpc":"^0.75.1","@effect/sql":"^0.51.1","@modelcontextprotocol/sdk":"^1.29.0","@openrouter/ai-sdk-provider":"^2.9.0","@perplexity-ai/perplexity_ai":"^0.27.0","@tavily/core":"^0.7.3","@toon-format/toon":"^2.1.0",ai:"^6.0.174",chalk:"^4.1.2","cli-highlight":"^2.1.11",commander:"^14.0.3","cron-parser":"^5.5.0",cronstrue:"^3.14.0",diff:"^8.0.4",effect:"^3.21.2","exa-js":"^2.12.1","fast-glob":"^3.3.3","gpt-tokenizer":"^3.4.0","gray-matter":"^4.0.3",ink:"^6.8.0","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","linkup-sdk":"^3.2.0",marked:"^16.4.2","marked-terminal":"^7.3.0","node-emoji":"^2.2.0","ollama-ai-provider-v2":"^2.0.0","parallel-web":"^0.5.0","pdf-parse":"^2.4.5",plist:"^3.1.1",react:"^19.2.5",semver:"^7.7.4","short-uuid":"^5.2.0","vercel-minimax-ai-provider":"^0.0.2","wrap-ansi":"^9.0.2",zod:"^4.4.2"},devDependencies:{"@types/bun":"^1.3.13","@types/diff":"^8.0.0","@types/ink-big-text":"^1.2.4","@types/ink-gradient":"^2.0.4","@types/marked":"^6.0.0","@types/marked-terminal":"^6.1.1","@types/node":"^24.12.2","@types/node-notifier":"^8.0.5","@types/plist":"^3.0.5","@types/react":"^19.2.14",eslint:"^9.39.4","eslint-config-prettier":"^10.1.8","eslint-plugin-import":"^2.32.0","eslint-plugin-n":"^17.24.0","eslint-plugin-prettier":"^5.5.5",prettier:"^3.8.3",typescript:"^5.9.3","typescript-eslint":"^8.59.1"},engines:{node:">=22.16.0",npm:">=10.0.0"},files:["dist/","personas/","skills/","workflows/","README.md","LICENSE"]}});var _eI,PeI=()=>{return Object.assign((I)=>I,{[_eI]:_eI,option:(I)=>GI(I),either:(I)=>YG(I),is:(I)=>!0})};var $eI=g(()=>{_2();_Z();_eI=Symbol.for("effect/Brand/Refined")});var qmI,TmI,ieI;var feI=g(()=>{T4();qmI=gI,TmI=DG,ieI=UI});var seI,oeI,teI;var reI=g(()=>{i$();seI=dM,oeI=QM,teI=SfI});var SmI=(I,G)=>{switch(G._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(I);case"SymbolKeyword":return Object.getOwnPropertySymbols(I);case"Refinement":return SmI(I,G.from)}},YK=(I)=>{let G=!1,Z;return()=>{if(G)return Z;return Z=I(),G=!0,Z}},nmI=(I)=>Array.isArray(I),IIG=(I)=>!Array.isArray(I),eeI=(I)=>`[${AJ(I)}]`,Pi=(I)=>nmI(I)?I.map(eeI).join(""):eeI(I);var NK=g(()=>{FY()});var Wv=(I,G,Z,b)=>{let W=I;if(Z&&Jl(Z))W+=`
|
|
68
68
|
at path: ${Pi(Z)}`;if(G!==void 0)W+=`
|
|
69
69
|
details: ${G}`;if(b)W+=`
|
|
70
70
|
schema (${b._tag}): ${b}`;return W},_mI=(I,G,Z)=>Wv("Unsupported schema or overlapping types",`cannot extend ${I} with ${G}`,Z),GIG=(I)=>Wv("Unsupported key schema",void 0,void 0,I),ZIG=(I)=>Wv("Unsupported literal",`literal value: ${Sd(I)}`),PmI=(I)=>Wv("Duplicate index signature",`${I} index signature`),bIG,WIG,$mI=(I)=>Wv("Duplicate property signature transformation",`Duplicate key ${Sd(I)}`),ii=(I)=>Wv("Duplicate property signature",`Duplicate key ${Sd(I)}`);var imI=g(()=>{mY();FY();NK();bIG=Wv("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),WIG=Wv("Invalid element","A required element cannot follow an optional element. ts(1257)")});var YIG;var NIG=g(()=>{YIG=Symbol.for("effect/SchemaId/DateFromSelf")});class Ku{typeParameters;decodeUnknown;encodeUnknown;annotations;_tag="Declaration";constructor(I,G,Z,b={}){this.typeParameters=I,this.decodeUnknown=G,this.encodeUnknown=Z,this.annotations=b}toString(){return Yb(HH(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((I)=>I.toJSON()),annotations:EN(this.annotations)}}}class ju{literal;annotations;_tag="Literal";constructor(I,G={}){this.literal=I,this.annotations=G}toString(){return Yb(HH(this),()=>Sd(this.literal))}toJSON(){return{_tag:this._tag,literal:pJ(this.literal)?String(this.literal):this.literal,annotations:EN(this.annotations)}}}class si{symbol;annotations;_tag="UniqueSymbol";constructor(I,G={}){this.symbol=I,this.annotations=G}toString(){return Yb(HH(this),()=>Sd(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:EN(this.annotations)}}}class yIG{annotations;_tag="UndefinedKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class CIG{annotations;_tag="VoidKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class pIG{annotations;_tag="NeverKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class AIG{annotations;_tag="UnknownKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class LIG{annotations;_tag="AnyKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class zIG{annotations;_tag="StringKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class kIG{annotations;_tag="NumberKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class gIG{annotations;_tag="BooleanKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class UIG{annotations;_tag="BigIntKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class BIG{annotations;_tag="SymbolKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class aIG{annotations;_tag="ObjectKeyword";constructor(I={}){this.annotations=I}toString(){return YR(this)}toJSON(){return{_tag:this._tag,annotations:EN(this.annotations)}}}class dK{type;annotations;constructor(I,G={}){this.type=I,this.annotations=G}toJSON(){return{type:this.type.toJSON(),annotations:EN(this.annotations)}}toString(){return String(this.type)}}class Gf{elements;rest;isReadonly;annotations;_tag="TupleType";constructor(I,G,Z,b={}){this.elements=I,this.rest=G,this.isReadonly=Z,this.annotations=b;let W=!1,l=!1;for(let Y of I)if(Y.isOptional)W=!0;else if(W){l=!0;break}if(l||W&&G.length>1)throw Error(WIG)}toString(){return Yb(HH(this),()=>CgZ(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((I)=>I.toJSON()),rest:this.rest.map((I)=>I.toJSON()),isReadonly:this.isReadonly,annotations:EN(this.annotations)}}}class Du{type;isReadonly;parameter;constructor(I,G,Z){if(this.type=G,this.isReadonly=Z,MIG(I))this.parameter=I;else throw Error(bIG)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class lR{annotations;_tag="TypeLiteral";propertySignatures;indexSignatures;constructor(I,G,Z={}){this.annotations=Z;let b={};for(let l=0;l<I.length;l++){let Y=I[l].name;if(Object.prototype.hasOwnProperty.call(b,Y))throw Error(ii(Y));b[Y]=null}let W={string:!1,symbol:!1};for(let l=0;l<G.length;l++){let Y=CQI(G[l].parameter);if(ei(Y)){if(W.string)throw Error(PmI("string"));W.string=!0}else if(OIG(Y)){if(W.symbol)throw Error(PmI("symbol"));W.symbol=!0}}this.propertySignatures=I,this.indexSignatures=G}toString(){return Yb(HH(this),()=>pgZ(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((I)=>I.toJSON()),indexSignatures:this.indexSignatures.map((I)=>I.toJSON()),annotations:EN(this.annotations)}}}class c0{types;annotations;static make=(I,G)=>{return Zf(I)?new c0(I,G):I.length===1?I[0]:ti};static unify=(I,G)=>{return c0.make(ugZ(KIG(I)),G)};_tag="Union";constructor(I,G={}){this.types=I,this.annotations=G}toString(){return Yb(HH(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((I)=>I.toJSON()),annotations:EN(this.annotations)}}}class qu{f;annotations;_tag="Suspend";constructor(I,G={}){this.f=I,this.annotations=G,this.f=YK(I)}toString(){return HH(this).pipe(BX(()=>hN(j3(this.f)(),(I)=>HH(I))),Yb(()=>"<suspended schema>"))}toJSON(){let I=this.f(),G=fmI.get(I);if(G)return G;return fmI.set(I,{_tag:this._tag}),G={_tag:this._tag,ast:I.toJSON(),annotations:EN(this.annotations)},fmI.set(I,G),G}}class Tu{from;filter;annotations;_tag="Refinement";constructor(I,G,Z={}){this.from=I,this.filter=G,this.annotations=Z}toString(){return XK(this).pipe(Yb(()=>MG($IG(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(I)=>lv(this.from)?String(this.from)+" & "+I:I})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:EN(this.annotations)}}}class Yv{from;to;transformation;annotations;_tag="Transformation";constructor(I,G,Z,b={}){this.from=I,this.to=G,this.transformation=Z,this.annotations=b}toString(){return Yb(HH(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:EN(this.annotations)}}}class lf{decode;encode;_tag="FinalTransformation";constructor(I,G){this.decode=I,this.encode=G}}class qIG{_tag="ComposeTransformation"}class JQI{from;to;decode;encode;constructor(I,G,Z,b){this.from=I,this.to=G,this.decode=Z,this.encode=b}}class FK{propertySignatureTransformations;_tag="TypeLiteralTransformation";constructor(I){this.propertySignatureTransformations=I;let G={},Z={};for(let b of I){let W=b.from;if(G[W])throw Error($mI(W));G[W]=!0;let l=b.to;if(Z[l])throw Error($mI(l));Z[l]=!0}}}function Rm(I,G){let Z=!1,b=D3(I.length);for(let W=0;W<I.length;W++){let l=I[W],Y=G(l);if(Y!==l)Z=!0;b[W]=Y}return Z?b:I}function OgZ(I){return MG(QIG(I),{onNone:()=>"",onSome:(G)=>G.map((Z)=>` & Brand<${Sd(Z)}>`).join("")})}var VIG,XIG,dIG,omI,fi,cK,Gd,l9,Th,tmI,rmI,emI,IQI,GQI,ZQI,FIG,bQI,WQI,lQI,YQI,NQI,VK,mIG,V0,QIG,RIG,HIG,cQI,VQI,XK,XQI,hIG,wIG,JIG,vIG,EIG,dQI,HgZ,FQI=(I)=>UlI(HgZ(I),(G)=>G===!0),mQI,hgZ,wgZ=(I)=>BX(hgZ(I),()=>XK(I)),Sh=(I)=>(G)=>G._tag===I,Y9,oi,JgZ,ti,QQI,uIG,ri,ei,If,RQI,HQI,hQI,vgZ,EgZ,OIG,ygZ,N9,xIG=(I)=>I.map((G)=>G.type),CgZ=(I)=>{let G=I.elements.map(String).join(", ");return HOI(I.rest,{onEmpty:()=>`readonly [${G}]`,onNonEmpty:(Z,b)=>{let W=String(Z),l=W.includes(" | ")?`(${W})`:W;if(b.length>0){let Y=b.map(String).join(", ");if(I.elements.length>0)return`readonly [${G}, ...${l}[], ${Y}]`;else return`readonly [...${l}[], ${Y}]`}else if(I.elements.length>0)return`readonly [${G}, ...${l}[]]`;else return`ReadonlyArray<${W}>`}})},U2,MIG=(I)=>{switch(I._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return MIG(I.from)}return!1},cIG=(I)=>I.map(String).join("; "),pgZ=(I)=>{if(I.propertySignatures.length>0){let G=I.propertySignatures.map(String).join("; ");if(I.indexSignatures.length>0)return`{ ${G}; ${cIG(I.indexSignatures)} }`;else return`{ ${G} }`}else if(I.indexSignatures.length>0)return`{ ${cIG(I.indexSignatures)} }`;else return"{}"},wQI,AgZ,LgZ,KIG=(I)=>q3(I,(G)=>bf(G)?KIG(G.types):[G]),ugZ=(I)=>{let G=AgZ(I),Z=[],b={},W=[];for(let l of G)switch(l._tag){case"NeverKeyword":break;case"AnyKeyword":return[uIG];case"UnknownKeyword":return[QQI];case"ObjectKeyword":case"UndefinedKeyword":case"VoidKeyword":case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":{if(!b[l._tag])b[l._tag]=l,Z.push(l);break}case"Literal":{let Y=typeof l.literal;switch(Y){case"string":case"number":case"bigint":case"boolean":{let N=LgZ[Y];if(!b[N]&&!W.includes(l.literal))W.push(l.literal),Z.push(l);break}case"object":{if(!W.includes(l.literal))W.push(l.literal),Z.push(l);break}}break}case"UniqueSymbol":{if(!b.SymbolKeyword&&!W.includes(l.symbol))W.push(l.symbol),Z.push(l);break}case"TupleType":{if(!b.ObjectKeyword)Z.push(l);break}case"TypeLiteral":{if(l.propertySignatures.length===0&&l.indexSignatures.length===0){if(!b["{}"])b["{}"]=l,Z.push(l)}else if(!b.ObjectKeyword)Z.push(l);break}default:Z.push(l)}return Z},jIG=(I,G)=>I.map(G),Zf=(I)=>I.length>1,bf,fmI,lv,Wf,DIG,zgZ=(I)=>(G)=>G._tag===I,TIG,vQI,Yf=(I,G)=>{let Z=Object.getOwnPropertyDescriptors(I),b={...I.annotations};delete b[cK];let W={...b,...G},l=dQI(I);if($G(l))W[VK]=Yf(l.value,G);return Z.annotations.value=W,Object.create(Object.getPrototypeOf(I),Z)},kgZ="[\\s\\S]*?",ggZ="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",SIG=(I,G)=>{switch(I._tag){case"Literal":return QL(String(I.literal));case"StringKeyword":return kgZ;case"NumberKeyword":return ggZ;case"TemplateLiteral":return nIG(I,G,!1);case"Union":return I.types.map((Z)=>SIG(Z,G)).join("|")}},UgZ=(I,G,Z,b)=>{if(bf(I)){if(Z&&!b)return`(?:${G})`}else if(!Z||!b)return G;return`(${G})`},nIG=(I,G,Z)=>{let b="";if(I.head!==""){let W=QL(I.head);b+=G&&Z?`(${W})`:W}for(let W of I.spans){let l=SIG(W.type,G);if(b+=UgZ(W.type,l,G,Z),W.literal!==""){let Y=QL(W.literal);b+=G&&Z?`(${Y})`:Y}}return b},_IG=(I)=>new RegExp(`^${nIG(I,!1,!0)}$`),EQI=(I,G)=>{let Z=[],b=[],W=(l)=>{switch(l._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":b.push(new Du(l,G,!0));break;case"Literal":if(J2(l.literal)||B0(l.literal))Z.push(new U2(l.literal,G,!1,!0));else throw Error(ZIG(l.literal));break;case"Enums":{for(let[Y,N]of l.enums)Z.push(new U2(N,G,!1,!0));break}case"UniqueSymbol":Z.push(new U2(l.symbol,G,!1,!0));break;case"Union":l.types.forEach(W);break;default:throw Error(GIG(l))}};return W(I),{propertySignatures:Z,indexSignatures:b}},yQI=(I)=>(G)=>{let Z=void 0;for(let b of I)if(Object.prototype.hasOwnProperty.call(G.annotations,b)){if(Z===void 0)Z={};Z[b]=G.annotations[b]}return Z},PIG=(I)=>(G)=>{let Z={...G.annotations};for(let b of I)delete Z[b];return Z},BgZ,jN=(I)=>{switch(I._tag){case"Declaration":{let G=Rm(I.typeParameters,jN);return G===I.typeParameters?I:new Ku(G,I.decodeUnknown,I.encodeUnknown,I.annotations)}case"TupleType":{let G=Rm(I.elements,(W)=>{let l=jN(W.type);return l===W.type?W:new N9(l,W.isOptional)}),Z=xIG(I.rest),b=Rm(Z,jN);return G===I.elements&&b===Z?I:new Gf(G,b.map((W)=>new dK(W)),I.isReadonly,I.annotations)}case"TypeLiteral":{let G=Rm(I.propertySignatures,(b)=>{let W=jN(b.type);return W===b.type?b:new U2(b.name,W,b.isOptional,b.isReadonly)}),Z=Rm(I.indexSignatures,(b)=>{let W=jN(b.type);return W===b.type?b:new Du(b.parameter,W,b.isReadonly)});return G===I.propertySignatures&&Z===I.indexSignatures?I:new lR(G,Z,I.annotations)}case"Union":{let G=Rm(I.types,jN);return G===I.types?I:c0.make(G,I.annotations)}case"Suspend":return new qu(()=>jN(I.f()),I.annotations);case"Refinement":{let G=jN(I.from);return G===I.from?I:new Tu(G,I.filter,I.annotations)}case"Transformation":{let G=BgZ(I);return jN(G!==void 0?Yf(I.to,G):I.to)}}return I},smI=(I)=>{switch(I._tag){case"Transformation":return I.from;case"Refinement":return smI(I.from);case"Suspend":return smI(I.f())}},RH=(I,G)=>{switch(I._tag){case"Declaration":{let Z=Rm(I.typeParameters,(b)=>RH(b,G));return Z===I.typeParameters?I:new Ku(Z,I.decodeUnknown,I.encodeUnknown)}case"TupleType":{let Z=Rm(I.elements,(l)=>{let Y=RH(l.type,G);return Y===l.type?l:new N9(Y,l.isOptional)}),b=xIG(I.rest),W=Rm(b,(l)=>RH(l,G));return Z===I.elements&&W===b?I:new Gf(Z,W.map((l)=>new dK(l)),I.isReadonly)}case"TypeLiteral":{let Z=Rm(I.propertySignatures,(W)=>{let l=RH(W.type,G);return l===W.type?W:new U2(W.name,l,W.isOptional,W.isReadonly)}),b=Rm(I.indexSignatures,(W)=>{let l=RH(W.type,G);return l===W.type?W:new Du(W.parameter,l,W.isReadonly)});return Z===I.propertySignatures&&b===I.indexSignatures?I:new lR(Z,b)}case"Union":{let Z=Rm(I.types,(b)=>RH(b,G));return Z===I.types?I:c0.make(Z)}case"Suspend":{let Z=void 0,b=wgZ(I);if($G(b)){let W=G?"Bound":"";Z={[mQI]:`${b.value}Encoded${W}`}}return new qu(()=>RH(I.f(),G),Z)}case"Refinement":{let Z=RH(I.from,G);if(G){if(Z===I.from)return I;if(smI(I.from)===void 0&&FQI(I))return new Tu(Z,I.filter,I.annotations);return Z}else return Z}case"Transformation":return RH(I.from,G)}return I},mK=(I)=>RH(I,!1),EN=(I)=>{let G={};for(let Z of Object.getOwnPropertySymbols(I))G[String(Z)]=I[Z];return G},CQI=(I)=>{switch(I._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return I;case"Refinement":return CQI(I.from)}},YR=(I)=>Yb(HH(I),()=>I._tag),$IG=(I)=>cQI(I).pipe(BX(()=>XQI(I)),BX(()=>VQI(I)),gW((G)=>G+OgZ(I))),HH=(I)=>BX(XK(I),()=>$IG(I));var pQI=g(()=>{mY();$I();FY();imI();NK();F4();_Z();LJ();KZ();tNI();VIG=Symbol.for("effect/annotation/TypeConstructor"),XIG=Symbol.for("effect/annotation/Brand"),dIG=Symbol.for("effect/annotation/SchemaId"),omI=Symbol.for("effect/annotation/Message"),fi=Symbol.for("effect/annotation/MissingMessage"),cK=Symbol.for("effect/annotation/Identifier"),Gd=Symbol.for("effect/annotation/Title"),l9=Symbol.for("effect/annotation/AutoTitle"),Th=Symbol.for("effect/annotation/Description"),tmI=Symbol.for("effect/annotation/Examples"),rmI=Symbol.for("effect/annotation/Default"),emI=Symbol.for("effect/annotation/JSONSchema"),IQI=Symbol.for("effect/annotation/Arbitrary"),GQI=Symbol.for("effect/annotation/Pretty"),ZQI=Symbol.for("effect/annotation/Equivalence"),FIG=Symbol.for("effect/annotation/Documentation"),bQI=Symbol.for("effect/annotation/Concurrency"),WQI=Symbol.for("effect/annotation/Batching"),lQI=Symbol.for("effect/annotation/ParseIssueTitle"),YQI=Symbol.for("effect/annotation/ParseOptions"),NQI=Symbol.for("effect/annotation/DecodingFallback"),VK=Symbol.for("effect/annotation/Surrogate"),mIG=Symbol.for("effect/annotation/StableFilter"),V0=L(2,(I,G)=>Object.prototype.hasOwnProperty.call(I.annotations,G)?GI(I.annotations[G]):WI()),QIG=V0(XIG),RIG=V0(omI),HIG=V0(fi),cQI=V0(Gd),VQI=V0(l9),XK=V0(cK),XQI=V0(Th),hIG=V0(bQI),wIG=V0(WQI),JIG=V0(lQI),vIG=V0(YQI),EIG=V0(NQI),dQI=V0(VK),HgZ=V0(mIG),mQI=Symbol.for("effect/annotation/JSONIdentifier"),hgZ=V0(mQI);Y9=Sh("Literal");oi=new yIG({[Gd]:"undefined"});JgZ=new CIG({[Gd]:"void"});ti=new pIG({[Gd]:"never"});QQI=new AIG({[Gd]:"unknown"});uIG=new LIG({[Gd]:"any"});ri=new zIG({[Gd]:"string",[Th]:"a string"}),ei=Sh("StringKeyword");If=new kIG({[Gd]:"number",[Th]:"a number"}),RQI=Sh("NumberKeyword");HQI=new gIG({[Gd]:"boolean",[Th]:"a boolean"}),hQI=Sh("BooleanKeyword");vgZ=new UIG({[Gd]:"bigint",[Th]:"a bigint"});EgZ=new BIG({[Gd]:"symbol",[Th]:"a symbol"}),OIG=Sh("SymbolKeyword");ygZ=new aIG({[Gd]:"object",[Th]:"an object in the TypeScript meaning, i.e. the `object` type"});N9=class N9 extends dK{isOptional;constructor(I,G,Z={}){super(I,Z);this.isOptional=G}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:EN(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};U2=class U2 extends N9{name;isReadonly;constructor(I,G,Z,b,W){super(G,Z,W);this.name=I,this.isReadonly=b}toString(){return(this.isReadonly?"readonly ":"")+String(this.name)+(this.isOptional?"?":"")+": "+this.type}toJSON(){return{name:String(this.name),type:this.type.toJSON(),isOptional:this.isOptional,isReadonly:this.isReadonly,annotations:EN(this.annotations)}}};wQI=Sh("TypeLiteral"),AgZ=bV(x1(u2,(I)=>{switch(I._tag){case"AnyKeyword":return 0;case"UnknownKeyword":return 1;case"ObjectKeyword":return 2;case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":return 3}return 4})),LgZ={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};bf=Sh("Union"),fmI=WZ(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);lv=Sh("Refinement"),Wf={};DIG=Sh("Transformation");TIG=new qIG;vQI=zgZ("TypeLiteralTransformation"),BgZ=yQI([tmI,rmI,emI,IQI,GQI,ZQI])});class Wc{path;actual;issue;_tag="Pointer";constructor(I,G,Z){this.path=I,this.actual=G,this.issue=Z}}class uQI{actual;message;_tag="Unexpected";constructor(I,G){this.actual=I,this.message=G}}class Su{ast;message;_tag="Missing";actual=void 0;constructor(I,G){this.ast=I,this.message=G}}class yN{ast;actual;issues;output;_tag="Composite";constructor(I,G,Z,b){this.ast=I,this.actual=G,this.issues=Z,this.output=b}}class cf{ast;actual;kind;issue;_tag="Refinement";constructor(I,G,Z,b){this.ast=I,this.actual=G,this.kind=Z,this.issue=b}}class Vf{ast;actual;kind;issue;_tag="Transformation";constructor(I,G,Z,b){this.ast=I,this.actual=G,this.kind=Z,this.issue=b}}class WF{ast;actual;message;_tag="Type";constructor(I,G,Z){this.ast=I,this.actual=G,this.message=Z}}class zQI{ast;actual;message;_tag="Forbidden";constructor(I,G,Z){this.ast=I,this.actual=G,this.message=Z}}function NR(I){return I.sort(qgZ).map((G)=>G[1])}function $gZ(I){return XQI(I).pipe(BX(()=>cQI(I)),BX(()=>VQI(I)),BX(()=>XK(I)),Yb(()=>`{ ${I.from} | filter }`))}function igZ(I){if(I.message!==void 0)return I.message;return`Expected ${lv(I.ast)?$gZ(I.ast):String(I.ast)}, actual ${Sd(I.actual)}`}var fIG,tIG,rIG=(I)=>new tIG({issue:I}),_u,gQI,Zd,nh,bd,Xf,eIG,df=(I,G)=>{if(G===void 0||B0(G))return I;if(I===void 0)return G;return{...I,...G}},agZ=(I,G,Z)=>{let b=xc(I,G);return(W,l)=>b(W,df(Z,l))},xgZ=(I,G,Z)=>{let b=agZ(I,G,Z);return(W,l)=>gA(b(W,l),rIG)},MgZ=(I,G,Z)=>{let b=xc(I,G);return(W,l)=>b(W,{...df(Z,l),isEffectAllowed:!0})},IGG=(I,G)=>MgZ(I.ast,!1,G),Ff=(I,G)=>xgZ(jN(I.ast),!0,G),GGG=(I,G)=>{let Z=xc(jN(I.ast),!0);return(b,W)=>nV(Z(b,{exact:!0,...df(G,W)}))},KgZ,jgZ,xc=(I,G)=>{let Z=G?KgZ:jgZ,b=Z.get(I);if(b)return b;let W=DgZ(I,G),l=vIG(I),Y=$G(l)?(X,d)=>W(X,df(d,l.value)):W,N=EIG(I),V=G&&$G(N)?(X,d)=>RK(eIG(Y(X,d),N.value),I,X,d):Y;return Z.set(I,V),V},AQI=(I)=>DY(hIG(I)),LQI=(I)=>DY(wIG(I)),DgZ=(I,G)=>{switch(I._tag){case"Refinement":if(G){let Z=xc(I.from,!0);return(b,W)=>{W=W??Wf;let l=W?.errors==="all",Y=nh(eIG(Z(b,W),(N)=>{let V=new cf(I,b,"From",N);if(l&&FQI(I)&&YGG(N))return MG(I.filter(b,W,I),{onNone:()=>NG(V),onSome:(X)=>NG(new yN(I,b,[V,new cf(I,b,"Predicate",X)]))});return NG(V)}),(N)=>MG(I.filter(N,W,I),{onNone:()=>YG(N),onSome:(V)=>NG(new cf(I,b,"Predicate",V))}));return RK(Y,I,b,W)}}else{let Z=xc(jN(I),!0),b=xc(bGG(I.from),!1);return(W,l)=>RK(nh(Z(W,l),(Y)=>b(Y,l)),I,W,l)}case"Transformation":{let Z=TgZ(I.transformation,G),b=G?xc(I.from,!0):xc(I.to,!1),W=G?xc(I.to,!0):xc(I.from,!1);return(l,Y)=>RK(nh(Xf(b(l,Y),(N)=>new Vf(I,l,G?"Encoded":"Type",N)),(N)=>nh(Xf(Z(N,Y??Wf,I,l),(V)=>new Vf(I,l,"Transformation",V)),(V)=>Xf(W(V,Y),(X)=>new Vf(I,l,G?"Type":"Encoded",X)))),I,l,Y)}case"Declaration":{let Z=G?I.decodeUnknown(...I.typeParameters):I.encodeUnknown(...I.typeParameters);return(b,W)=>RK(Z(b,W??Wf,I),I,b,W)}case"Literal":return bF(I,(Z)=>Z===I.literal);case"UniqueSymbol":return bF(I,(Z)=>Z===I.symbol);case"UndefinedKeyword":return bF(I,zBI);case"NeverKeyword":return bF(I,kBI);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return YG;case"StringKeyword":return bF(I,J2);case"NumberKeyword":return bF(I,B0);case"BooleanKeyword":return bF(I,Dd);case"BigIntKeyword":return bF(I,pJ);case"SymbolKeyword":return bF(I,L3);case"ObjectKeyword":return bF(I,Ac);case"Enums":return bF(I,(Z)=>I.enums.some(([b,W])=>W===Z));case"TemplateLiteral":{let Z=_IG(I);return bF(I,(b)=>J2(b)&&Z.test(b))}case"TupleType":{let Z=I.elements.map((X)=>xc(X.type,G)),b=I.rest.map((X)=>xc(X.type,G)),W=I.elements.filter((X)=>!X.isOptional);if(I.rest.length>0)W=W.concat(I.rest.slice(1));let l=W.length,Y=I.elements.length>0?I.elements.map((X,d)=>d).join(" | "):"never",N=AQI(I),V=LQI(I);return(X,d)=>{if(!xlI(X))return NG(new WF(I,X));let F=d?.errors==="all",m=[],Q=0,R=[],H=X.length;for(let J=H;J<=l-1;J++){let C=new Wc(J,X,new Su(W[J-H]));if(F){m.push([Q++,C]);continue}else return NG(new yN(I,X,C,R))}if(I.rest.length===0)for(let J=I.elements.length;J<=H-1;J++){let C=new Wc(J,X,new uQI(X[J],`is unexpected, expected: ${Y}`));if(F){m.push([Q++,C]);continue}else return NG(new yN(I,X,C,R))}let w=0,v=void 0;for(;w<Z.length;w++)if(H<w+1){if(I.elements[w].isOptional)continue}else{let J=Z[w],C=J(X[w],d);if(Zd(C)){if(VW(C)){let E=new Wc(w,X,C.left);if(F){m.push([Q++,E]);continue}else return NG(new yN(I,X,E,NR(R)))}R.push([Q++,C.right])}else{let E=Q++,p=w;if(!v)v=[];v.push(({es:u,output:k})=>MI(x4(C),(A)=>{if(VW(A)){let B=new Wc(p,X,A.left);if(F)return u.push([E,B]),EZ;else return NG(new yN(I,X,B,NR(k)))}return k.push([E,A.right]),EZ}))}}if(Jl(b)){let[J,...C]=b;for(;w<H-C.length;w++){let E=J(X[w],d);if(Zd(E))if(VW(E)){let p=new Wc(w,X,E.left);if(F){m.push([Q++,p]);continue}else return NG(new yN(I,X,p,NR(R)))}else R.push([Q++,E.right]);else{let p=Q++,u=w;if(!v)v=[];v.push(({es:k,output:A})=>MI(x4(E),(B)=>{if(VW(B)){let O=new Wc(u,X,B.left);if(F)return k.push([p,O]),EZ;else return NG(new yN(I,X,O,NR(A)))}else return A.push([p,B.right]),EZ}))}}for(let E=0;E<C.length;E++){let p=w+E;if(H<p+1)continue;else{let u=C[E](X[p],d);if(Zd(u)){if(VW(u)){let k=new Wc(p,X,u.left);if(F){m.push([Q++,k]);continue}else return NG(new yN(I,X,k,NR(R)))}R.push([Q++,u.right])}else{let k=Q++;if(!v)v=[];v.push(({es:A,output:B})=>MI(x4(u),(O)=>{if(VW(O)){let M=new Wc(p,X,O.left);if(F)return A.push([k,M]),EZ;else return NG(new yN(I,X,M,NR(B)))}return B.push([k,O.right]),EZ}))}}}}let y=({es:J,output:C})=>K1(J)?NG(new yN(I,X,NR(J),NR(C))):YG(NR(C));if(v&&v.length>0){let J=v;return Cb(()=>{let C={es:BA(m),output:BA(R)};return MI(g2(J,(E)=>E(C),{concurrency:N,batching:V,discard:!0}),()=>y(C))})}return y({output:R,es:m})}}case"TypeLiteral":{if(I.propertySignatures.length===0&&I.indexSignatures.length===0)return bF(I,gBI);let Z=[],b={},W=[];for(let d of I.propertySignatures)Z.push([xc(d.type,G),d]),b[d.name]=null,W.push(d.name);let l=I.indexSignatures.map((d)=>[xc(d.parameter,G),xc(d.type,G),d.parameter]),Y=c0.make(I.indexSignatures.map((d)=>d.parameter).concat(W.map((d)=>L3(d)?new si(d):new ju(d)))),N=xc(Y,G),V=AQI(I),X=LQI(I);return(d,F)=>{if(!llI(d))return NG(new WF(I,d));let m=F?.errors==="all",Q=[],R=0,H=F?.onExcessProperty==="error",w=F?.onExcessProperty==="preserve",v={},y;if(H||w){y=Reflect.ownKeys(d);for(let p of y){let u=N(p,F);if(Zd(u)&&VW(u))if(H){let k=new Wc(p,d,new uQI(d[p],`is unexpected, expected: ${String(Y)}`));if(m){Q.push([R++,k]);continue}else return NG(new yN(I,d,k,v))}else v[p]=d[p]}}let J=void 0,C=F?.exact===!0;for(let p=0;p<Z.length;p++){let u=Z[p][1],k=u.name,A=Object.prototype.hasOwnProperty.call(d,k);if(!A){if(u.isOptional)continue;else if(C){let M=new Wc(k,d,new Su(u));if(m){Q.push([R++,M]);continue}else return NG(new yN(I,d,M,v))}}let B=Z[p][0],O=B(d[k],F);if(Zd(O)){if(VW(O)){let M=new Wc(k,d,A?O.left:new Su(u));if(m){Q.push([R++,M]);continue}else return NG(new yN(I,d,M,v))}v[k]=O.right}else{let M=R++,q=k;if(!J)J=[];J.push(({es:j,output:x})=>MI(x4(O),(D)=>{if(VW(D)){let P=new Wc(q,d,A?D.left:new Su(u));if(m)return j.push([M,P]),EZ;else return NG(new yN(I,d,P,x))}return x[q]=D.right,EZ}))}}for(let p=0;p<l.length;p++){let u=l[p],k=u[0],A=u[1],B=SmI(d,u[2]);for(let O of B){let M=k(O,F);if(Zd(M)&&nV(M)){let q=A(d[O],F);if(Zd(q)){if(VW(q)){let j=new Wc(O,d,q.left);if(m){Q.push([R++,j]);continue}else return NG(new yN(I,d,j,v))}else if(!Object.prototype.hasOwnProperty.call(b,O))v[O]=q.right}else{let j=R++,x=O;if(!J)J=[];J.push(({es:D,output:P})=>MI(x4(q),($)=>{if(VW($)){let e=new Wc(x,d,$.left);if(m)return D.push([j,e]),EZ;else return NG(new yN(I,d,e,P))}else{if(!Object.prototype.hasOwnProperty.call(b,O))P[O]=$.right;return EZ}}))}}}}let E=({es:p,output:u})=>{if(K1(p))return NG(new yN(I,d,NR(p),u));if(F?.propertyOrder==="original"){let k=y||Reflect.ownKeys(d);for(let B of W)if(k.indexOf(B)===-1)k.push(B);let A={};for(let B of k)if(Object.prototype.hasOwnProperty.call(u,B))A[B]=u[B];return YG(A)}return YG(u)};if(J&&J.length>0){let p=J;return Cb(()=>{let u={es:BA(Q),output:Object.assign({},v)};return MI(g2(p,(k)=>k(u),{concurrency:V,batching:X,discard:!0}),()=>E(u))})}return E({es:Q,output:v})}}case"Union":{let Z=ZGG(I.types,G),b=Reflect.ownKeys(Z.keys),W=b.length,l=I.types.length,Y=new Map;for(let X=0;X<l;X++)Y.set(I.types[X],xc(I.types[X],G));let N=AQI(I)??1,V=LQI(I);return(X,d)=>{let F=[],m=0,Q=[];if(W>0)if(rB(X))for(let w=0;w<W;w++){let v=b[w],y=Z.keys[v].buckets;if(Object.prototype.hasOwnProperty.call(X,v)){let J=String(X[v]);if(Object.prototype.hasOwnProperty.call(y,J))Q=Q.concat(y[J]);else{let{candidates:C,literals:E}=Z.keys[v],p=c0.make(E),u=C.length===l?new lR([new U2(v,p,!1,!0)],[]):c0.make(C);F.push([m++,new yN(u,X,new Wc(v,X,new WF(p,X[v])))])}}else{let{candidates:J,literals:C}=Z.keys[v],E=new U2(v,c0.make(C),!1,!0),p=J.length===l?new lR([E],[]):c0.make(J);F.push([m++,new yN(p,X,new Wc(v,X,new Su(E)))])}}else{let w=Z.candidates.length===l?I:c0.make(Z.candidates);F.push([m++,new WF(w,X)])}if(Z.otherwise.length>0)Q=Q.concat(Z.otherwise);let R=void 0;for(let w=0;w<Q.length;w++){let v=Q[w],y=Y.get(v)(X,d);if(Zd(y)&&(!R||R.length===0))if(nV(y))return y;else F.push([m++,y.left]);else{let J=m++;if(!R)R=[];R.push((C)=>Cb(()=>{if("finalResult"in C)return EZ;else return MI(x4(y),(E)=>{if(nV(E))C.finalResult=E;else C.es.push([J,E.left]);return EZ})}))}}let H=(w)=>K1(w)?w.length===1&&w[0][1]._tag==="Type"?NG(w[0][1]):NG(new yN(I,X,NR(w))):NG(new WF(I,X));if(R&&R.length>0){let w=R;return Cb(()=>{let v={es:BA(F)};return MI(g2(w,(y)=>y(v),{concurrency:N,batching:V,discard:!0}),()=>{if("finalResult"in v)return v.finalResult;return H(v.es)})})}return H(F)}}case"Suspend":{let Z=YK(()=>xc(I.f(),G));return(b,W)=>Z()(b,W)}}},bF=(I,G)=>(Z)=>G(Z)?YG(Z):NG(new WF(I,Z)),QK=(I,G)=>{switch(I._tag){case"Declaration":{let Z=dQI(I);if($G(Z))return QK(Z.value,G);break}case"TypeLiteral":{let Z=[];for(let b=0;b<I.propertySignatures.length;b++){let W=I.propertySignatures[b],l=G?mK(W.type):jN(W.type);if(Y9(l)&&!W.isOptional)Z.push([W.name,l])}return Z}case"TupleType":{let Z=[];for(let b=0;b<I.elements.length;b++){let W=I.elements[b],l=G?mK(W.type):jN(W.type);if(Y9(l)&&!W.isOptional)Z.push([b,l])}return Z}case"Refinement":return QK(I.from,G);case"Suspend":return QK(I.f(),G);case"Transformation":return QK(G?I.from:I.to,G)}return[]},ZGG=(I,G)=>{let Z={},b=[],W=[];for(let l=0;l<I.length;l++){let Y=I[l],N=QK(Y,G);if(N.length>0){W.push(Y);for(let V=0;V<N.length;V++){let[X,d]=N[V],F=String(d.literal);Z[X]=Z[X]||{buckets:{},literals:[],candidates:[]};let m=Z[X].buckets;if(Object.prototype.hasOwnProperty.call(m,F)){if(V<N.length-1)continue;m[F].push(Y),Z[X].literals.push(d),Z[X].candidates.push(Y)}else{m[F]=[Y],Z[X].literals.push(d),Z[X].candidates.push(Y);break}}}else b.push(Y)}return{keys:Z,otherwise:b,candidates:W}},bGG=(I)=>lv(I)?bGG(I.from):I,RK=(I,G,Z,b)=>{if(b?.isEffectAllowed===!0)return I;if(Zd(I))return I;let W=new ua,l=Tx(I,{scheduler:W});W.flush();let Y=l.unsafePoll();if(Y){if(Gm(Y))return YG(Y.value);let N=Y.cause;if(MNI(N))return NG(N.error);return NG(new zQI(G,Z,qNI(N)))}return NG(new zQI(G,Z,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},qgZ=([I],[G])=>I>G?1:I<G?-1:0,TgZ=(I,G)=>{switch(I._tag){case"FinalTransformation":return G?I.decode:I.encode;case"ComposeTransformation":return YG;case"TypeLiteralTransformation":return(Z)=>{let b=YG(Z);for(let W of I.propertySignatureTransformations){let[l,Y]=G?[W.from,W.to]:[W.to,W.from],N=G?W.decode:W.encode;b=bd(b,(X)=>{let d=N(Object.prototype.hasOwnProperty.call(X,l)?GI(X[l]):WI());if(delete X[l],$G(d))X[Y]=d.value;return X})}return b}}},o0=(I,G=[])=>({value:I,forest:G}),HK,SgZ=(I)=>I.value+WGG(`
|
|
@@ -7046,7 +7046,7 @@ Or update it in the interactive wizard: jazz wizard -> Update configuration`;W=n
|
|
|
7046
7046
|
`)}function l(V){let X=fZ(V.path),d=fZ(V.content),F=V.truncated===!0,m=[];if(X)m.push(X);if(d){if(m.length>0)m.push("");m.push(d)}if(F)m.push(""),m.push("[truncated]");return m.join(`
|
|
7047
7047
|
`)}function Y(V){let X=fZ(V.stdout),d=fZ(V.stderr),F=fZ(V.exitCode);if(!X&&!d)return F?`exitCode: ${F}`:"";let m=[];if(X)m.push(X);if(d){if(X)m.push("");m.push("stderr:"),m.push(d)}if(F&&F!=="0")m.push(""),m.push(`exitCode: ${F}`);return m.join(`
|
|
7048
7048
|
`)}function N(V){return JSON.stringify(V,null,2)}try{let V=JSON.parse(G);if(I==="load_skill"&&typeof V==="string")return WZb(V);if(I==="load_skill_section"&&typeof V==="string")return lZb(V);if(typeof V==="string"||typeof V==="number"||typeof V==="boolean")return Z(String(V));if(V===null)return"null";if(Array.isArray(V))return Z(JSON.stringify(V,null,2));let X=V;switch(I){case"list_todos":return Z(b(X));case"manage_todos":return Z(b(X)||fZ(X.message));case"context_info":return Z(W(X));case"load_skill":case"load_skill_section":{if(X.success===!0)return` ${uZ.default.dim("(loaded)")}`;return` ${uZ.default.red(`(error: ${fZ(X.error||X.result)})`)}`}case"spawn_subagent":{if(X.success===!0)return` ${uZ.default.dim("(sub-agent completed)")}`;return` ${uZ.default.red(`(error: ${fZ(X.error||X.result)})`)}`}case"git_status":{let d=fZ(X.branch),F=Array.isArray(X.modified)?X.modified.length:0,m=Array.isArray(X.staged)?X.staged.length:0,Q=[];if(d)Q.push(uZ.default.cyan(d));if(F>0)Q.push(uZ.default.yellow(`${F} modified`));if(m>0)Q.push(uZ.default.green(`${m} staged`));return Q.length>0?` ${uZ.default.dim("(")}${Q.join(uZ.default.dim(", "))}${uZ.default.dim(")")}`:""}case"git_log":{let d=X.commits||X,F=Array.isArray(d)?d.length:0;return F>0?` ${uZ.default.dim(`(${F} commit${F!==1?"s":""})`)}`:""}case"git_diff":{let d=[],F=X.paths,m=X.nameOnly===!0;if(Array.isArray(F)&&F.length>0){if(d.push(uZ.default.cyan(`${F.length} file${F.length!==1?"s":""}`)),m)d.push(uZ.default.dim("(names only)"))}if(X.truncated===!0)d.push(uZ.default.yellow("truncated"));if(X.hasChanges===!1&&!m)d.push(uZ.default.dim("no diff"));return d.length>0?` ${uZ.default.dim("(")}${d.join(uZ.default.dim(", "))}${uZ.default.dim(")")}`:""}case"grep":{let d=X.matches||X,F=Array.isArray(d)?d.length:0;return F>0?` ${uZ.default.dim(`(${F} match${F!==1?"es":""})`)}`:""}case"ls":{let d=X.items||X.files||X,F=Array.isArray(d)?d.length:0;return F>0?` ${uZ.default.dim(`(${F} item${F!==1?"s":""})`)}`:""}case"read_file":return Z(l(X));case"cd":{let d=fZ(X.path||X.currentDirectory);return d?` ${uZ.default.dim("→")} ${uZ.default.cyan(d)}`:""}case"execute_command":case"execute_execute_command":return Z(Y(X));case"http_request":{let d=X.statusCode;if(d!==void 0&&d!==null){let F=fZ(d);return F?` ${uZ.default.dim(`(${F})`)}`:""}return""}case"edit_file":case"execute_edit_file":case"write_file":case"execute_write_file":{let d=X.diff;if(typeof d==="string"&&d.length>0)return`
|
|
7049
|
-
${d}`;return""}case"read_pdf":{let{pageCount:d,pagesExtracted:F,truncated:m,path:Q,tables:R,totalLines:H}=X,w=[];if(Q)w.push(`file: ${fZ(Q)}`);if(Array.isArray(F)&&F.length>0)w.push(`pages: ${F.join(", ")}`);if(typeof d==="number")w.push(`total: ${d}`);if(typeof H==="number")w.push(`lines: ${H}`);if(Array.isArray(R))w.push(`tables: ${R.length}`);if(m)w.push(uZ.default.yellow("truncated"));return w.length>0?` ${uZ.default.dim("(")}${w.join(", ")}${uZ.default.dim(")")}`:""}default:return Z(N(X))}}catch{return Z(G)}}var uZ,bZb=12,v4G=1200;var Kj=g(()=>{pR();uZ=zZ(h0(),1)});var qk;var Er=g(()=>{zI();qk=tG.GenericTag("TelemetryService")});import{randomUUID as YZb}from"node:crypto";function E4G(I){let{agent:G,conversationId:Z,userId:b,provider:W,model:l,reasoningEffort:Y,maxIterations:N}=I;return{runId:YZb(),agentId:G.id,agentName:G.name,persona:G.config.persona,agentUpdatedAt:G.updatedAt,conversationId:Z,...b?{userId:b}:{},...W?{provider:W}:{},...l?{model:l}:{},...Y?{reasoningEffort:Y}:{},maxIterations:N,startedAt:new Date,totalPromptTokens:0,totalCompletionTokens:0,totalReasoningTokens:0,totalCacheReadTokens:0,totalCacheWriteTokens:0,llmRetryCount:0,toolCalls:0,toolErrors:0,toolsUsed:new Set,toolCallCounts:{},toolInvocationSequence:[],errors:[],iterationSummaries:[],currentIteration:void 0,firstTokenLatencyMs:void 0,totalToolDefinitionTokens:0,totalToolResultTokens:0,toolDefinitionsOffered:0}}function y4G(I,G){if(I.totalPromptTokens+=G.promptTokens,I.totalCompletionTokens+=G.completionTokens,G.reasoningTokens!=null)I.totalReasoningTokens+=G.reasoningTokens;if(G.cacheReadTokens!=null)I.totalCacheReadTokens+=G.cacheReadTokens;if(G.cacheWriteTokens!=null)I.totalCacheWriteTokens+=G.cacheWriteTokens}function C4G(I){uv.calibrate(I.authoritativePromptTokens,I.messagesAtCallTime,{provider:I.provider,modelId:I.modelId})}function jj(I,G){I.llmRetryCount+=1,I.lastError=B4G(I,G,"llm-retry")}function p4G(I,G){let Z={iteration:G,toolCalls:0,toolsUsed:new Set,toolCallCounts:{},errors:[],toolSequence:[],toolDefinitionTokens:0,toolResultTokens:0,toolResultSizes:{}};I.currentIteration=Z,I.iterationSummaries.push(Z)}function A4G(I){I.currentIteration=void 0}function L4G(I,G){I.toolCalls+=1,I.toolsUsed.add(G),I.toolCallCounts[G]=(I.toolCallCounts[G]??0)+1,I.toolInvocationSequence.push(G);let Z=I.currentIteration;if(Z)Z.toolCalls+=1,Z.toolsUsed.add(G),Z.toolCallCounts[G]=(Z.toolCallCounts[G]??0)+1,Z.toolSequence.push(G)}function u4G(I,G,Z){I.toolErrors+=1,I.lastError=B4G(I,Z,`tool:${G}`)}function a3I(I){return Math.ceil(I/4)}function z4G(I,G,Z){if(I.totalToolDefinitionTokens+=G,I.toolDefinitionsOffered+=Z,I.currentIteration)I.currentIteration.toolDefinitionTokens=G}function k4G(I,G,Z){let b=a3I(Z);if(I.totalToolResultTokens+=b,I.currentIteration)I.currentIteration.toolResultTokens+=b,I.currentIteration.toolResultSizes[G]=(I.currentIteration.toolResultSizes[G]??0)+b}function g4G(I,G){if(I.firstTokenLatencyMs===void 0)I.firstTokenLatencyMs=G}function U4G(I,G){let Z=new Date,b=Z.getTime()-I.startedAt.getTime(),W=I.totalPromptTokens+I.totalCompletionTokens,l=Array.from(I.toolsUsed.values()).sort(),Y=Object.fromEntries(Object.entries(I.toolCallCounts).sort(([X],[d])=>X.localeCompare(d))),N=I.lastError&&I.lastError.trim().length>0?I.lastError:void 0,V=I.iterationSummaries.map((X)=>({iteration:X.iteration,toolCalls:X.toolCalls,toolsUsed:Array.from(X.toolsUsed.values()).sort(),toolCallCounts:Object.fromEntries(Object.entries(X.toolCallCounts).sort(([d],[F])=>d.localeCompare(F))),errors:X.errors,toolSequence:X.toolSequence,toolDefinitionTokens:X.toolDefinitionTokens,toolResultTokens:X.toolResultTokens,toolResultSizes:X.toolResultSizes}));return h.gen(function*(){yield*NZb({runId:I.runId,agentId:I.agentId,agentName:I.agentName,persona:I.persona,agentUpdatedAt:I.agentUpdatedAt,conversationId:I.conversationId,...I.userId?{userId:I.userId}:{},...I.provider?{provider:I.provider}:{},...I.model?{model:I.model}:{},...I.reasoningEffort?{reasoningEffort:I.reasoningEffort}:{},promptTokens:I.totalPromptTokens,completionTokens:I.totalCompletionTokens,totalTokens:W,...I.totalReasoningTokens>0&&{reasoningTokens:I.totalReasoningTokens},...I.totalCacheReadTokens>0&&{cacheReadTokens:I.totalCacheReadTokens},...I.totalCacheWriteTokens>0&&{cacheWriteTokens:I.totalCacheWriteTokens},iterations:G.iterationsUsed,maxIterations:I.maxIterations,finished:G.finished,startedAt:I.startedAt,endedAt:Z,durationMs:b,retryCount:I.llmRetryCount,...N?{lastError:N}:{},toolCalls:I.toolCalls,toolsUsed:l,toolErrors:I.toolErrors,toolCallCounts:Y,toolInvocationSequence:I.toolInvocationSequence,errors:I.errors,iterationSummaries:V,...I.firstTokenLatencyMs!==void 0?{firstTokenLatencyMs:I.firstTokenLatencyMs}:{},toolDefinitionTokens:I.totalToolDefinitionTokens,toolResultTokens:I.totalToolResultTokens,toolDefinitionsOffered:I.toolDefinitionsOffered}),yield*VZb(I,W,b,G)})}function NZb(I){return h.gen(function*(){let G=yield*gG,Z={runId:I.runId,agentId:I.agentId,agentName:I.agentName,persona:I.persona,agentUpdatedAt:I.agentUpdatedAt.toISOString(),conversationId:I.conversationId,userId:I.userId??"anonymous",provider:I.provider??"unknown",model:I.model??"unknown",reasoningEffort:I.reasoningEffort??"disable",iterations:I.iterations,maxIterations:I.maxIterations,finished:I.finished,retryCount:I.retryCount,...I.lastError?{lastError:I.lastError}:{},promptTokens:I.promptTokens,completionTokens:I.completionTokens,totalTokens:I.totalTokens,...I.reasoningTokens!=null&&{reasoningTokens:I.reasoningTokens},...I.cacheReadTokens!=null&&{cacheReadTokens:I.cacheReadTokens},...I.cacheWriteTokens!=null&&{cacheWriteTokens:I.cacheWriteTokens},...I.firstTokenLatencyMs!==void 0?{firstTokenLatencyMs:I.firstTokenLatencyMs}:{},toolCalls:I.toolCalls,toolErrors:I.toolErrors,toolsUsed:I.toolsUsed,toolCallCounts:I.toolCallCounts,toolInvocationSequence:I.toolInvocationSequence,errors:I.errors,iterationSummaries:I.iterationSummaries,startedAt:I.startedAt.toISOString(),endedAt:I.endedAt.toISOString(),durationMs:I.durationMs,toolDefinitionTokens:I.toolDefinitionTokens,toolResultTokens:I.toolResultTokens,toolDefinitionsOffered:I.toolDefinitionsOffered};yield*G.info("Agent token usage",Z)})}function cZb(I,G,Z,b){let W={promptTokens:I.totalPromptTokens,completionTokens:I.totalCompletionTokens,totalTokens:G,...I.totalReasoningTokens>0&&{reasoningTokens:I.totalReasoningTokens},...I.totalCacheReadTokens>0&&{cacheReadTokens:I.totalCacheReadTokens},...I.totalCacheWriteTokens>0&&{cacheWriteTokens:I.totalCacheWriteTokens},...I.totalToolDefinitionTokens>0&&{toolDefinitionTokens:I.totalToolDefinitionTokens},...I.totalToolResultTokens>0&&{toolResultTokens:I.totalToolResultTokens},...I.toolDefinitionsOffered>0&&{toolDefinitionsOffered:I.toolDefinitionsOffered}};return{runId:I.runId,agentId:I.agentId,agentName:I.agentName,conversationId:I.conversationId,...I.provider&&{provider:I.provider},...I.model&&{model:I.model},durationMs:Z,iterationsUsed:b.iterationsUsed,finished:b.finished,usage:W,toolCalls:I.toolCalls,toolErrors:I.toolErrors}}function VZb(I,G,Z,b){return h.flatMap(h.context(),(W)=>{let l=tG.getOption(W,qk);if(l._tag==="None")return h.void;let Y=l.value,N=cZb(I,G,Z,b);return Y.recordAgentRunCompleted(N).pipe(h.catchAll(()=>h.void))}).pipe(h.catchAll(()=>h.void))}function XZb(I){return(I instanceof Error?I.message:String(I)).replace(/\s+/g," ").trim()}function B4G(I,G,Z){let b=XZb(G),W=Z?`${Z}: ${b}`:b;if(I.errors.push(W),I.currentIteration)I.currentIteration.errors.push(W);return W}var Tk=g(()=>{zI();sW();Er();Ps()});class FC{static executeTool(I,G,Z,b){return h.gen(function*(){let W=yield*xl,l=yield*gG,Y=b,N=Y===void 0?yield*W.getTool(I).pipe(h.catchAll(()=>h.succeed(void 0))):void 0;if(Y===void 0){if(Y=N?.timeoutMs,Y===void 0&&!N?.longRunning)Y=_WG}let V=W.executeTool(I,G,Z);return yield*Y!==void 0?V.pipe(h.timeoutFail({duration:Y,onTimeout:()=>{let d=Math.round(Y/60000);return Error(`Operation timed out after '${d}m'`)}}),h.catchAll((d)=>{let F=d instanceof Error?d.message:String(d);if(F.includes("timed out"))return l.warn(`Tool timeout: ${I}: ${F}`),h.succeed({success:!1,result:null,error:F});return h.fail(d)})):V})}static executeToolCall(I,G,Z,b,W,l,Y,N){return h.gen(function*(){let V=yield*oW,X=yield*gG;if(I.type!=="function")return{toolCallId:I.id,result:null,success:!1,name:"unknown"};let{name:d,arguments:F}=I.function;L4G(W,d);let m=Date.now();try{let Q;try{Q=JSON.parse(F)}catch(k){throw Error(`Invalid JSON in tool arguments: ${k instanceof Error?k.message:String(k)}`)}let R=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{};yield*X.logToolCall(d,R);let w=yield*(yield*xl).getTool(d).pipe(h.catchAll(()=>h.succeed(void 0))),v=w?.longRunning===!0,y=N.has(d);if(Z.showToolExecution&&!y){let k;if(d==="web_search")k={provider:(yield*(yield*ZZ).appConfig).web_search?.provider??"builtin"};if(b)yield*b.handleEvent({type:"tool_execution_start",toolName:d,toolCallId:I.id,arguments:R,...k?{metadata:k}:{},...v?{longRunning:!0}:{}});else{let A=yield*V.formatToolExecutionStart(d,R,k?{metadata:k}:void 0);yield*V.writeBlankLine(),yield*V.writeOutput(A)}}let J=yield*FC.executeTool(d,R,G,w?.timeoutMs),C=Date.now()-m,E=d;if(qJG(J.result)){let k=J.result,O=(yield*(yield*xl).getTool(d).pipe(h.catchAll(()=>h.succeed({riskLevel:"high-risk"})))).riskLevel,M=()=>G.getAutoApprovePolicy?.(),q=M(),j=()=>DJG(O,M())||FZb(d,G.autoApprovedTools)||dZb(d,k.executeArgs,G.autoApprovedCommands),x=j();if(x)yield*X.info("Tool auto-approved by policy",{toolName:d,executeToolName:k.executeToolName,riskLevel:O,autoApprovePolicy:q});else yield*X.debug("Tool requires approval, showing approval prompt",{toolName:d,executeToolName:k.executeToolName,riskLevel:O,autoApprovePolicy:q});let D=x?{approved:!0}:yield*V.requestApproval({toolName:d,message:k.message,executeToolName:k.executeToolName,executeArgs:k.executeArgs,...k.previewDiff?{previewDiff:k.previewDiff}:{},isAutoApproved:j});if(D.approved){if(D.alwaysApproveCommand&&G.onAutoApproveCommand)yield*G.onAutoApproveCommand(D.alwaysApproveCommand),yield*X.info("User chose to always approve command",{command:D.alwaysApproveCommand});if(D.alwaysApproveTool&&G.onAutoApproveTool)G.onAutoApproveTool(D.alwaysApproveTool),yield*X.info("User chose to always approve tool",{toolName:D.alwaysApproveTool});if(!x)yield*X.info("User approved tool execution",{toolName:d,executeToolName:k.executeToolName});let P=Date.now();if(Z.showToolExecution){let $;if(k.executeToolName==="web_search")$={provider:(yield*(yield*ZZ).appConfig).web_search?.provider??"builtin"};if(b)yield*b.handleEvent({type:"tool_execution_start",toolName:d,toolCallId:I.id,arguments:k.executeArgs,...$?{metadata:$}:{}});else{let e=yield*V.formatToolExecutionStart(d,k.executeArgs,$?{metadata:$}:void 0);yield*V.writeBlankLine(),yield*V.writeOutput(e)}}yield*V.signalToolExecutionStarted(),J=yield*FC.executeTool(k.executeToolName,k.executeArgs,G),C=Date.now()-P,E=k.executeToolName,yield*X.debug("Execution tool completed after approval",{executeToolName:k.executeToolName,success:J.success,durationMs:C,autoApproved:x})}else yield*X.info("User rejected tool execution",{toolName:d,userMessage:D.userMessage}),J={success:!1,result:{rejected:!0,message:D.userMessage?.trim()||"User rejected the operation. Please acknowledge this and ask if they'd like to try something different."},error:"User rejected the operation"}}let p=JSON.stringify(J.result);if(yield*X.debug("Tool execution succeeded",{agentId:l,conversationId:Y,toolName:E,toolCallId:I.id,durationMs:C,success:J.success,resultSize:p.length,resultPreview:p.substring(0,200)}),Z.showToolExecution)if(b)yield*b.handleEvent({type:"tool_execution_complete",toolCallId:I.id,result:p,durationMs:C});else if(J.success){let k=V.formatToolResult(E,p),A=yield*V.formatToolExecutionComplete(k,C);yield*V.writeOutput(A)}else{let k=J.error||"Tool execution failed",A=yield*V.formatToolExecutionError(k,C);yield*V.writeOutput(A)}let u=J.success?J.result:{error:J.error??"Tool execution failed",result:J.result};return{toolCallId:I.id,result:u,success:J.success,name:E}}catch(Q){let R=Date.now()-m,H=Q instanceof Error?Q.message:String(Q);if(Z.showToolExecution)if(b)yield*b.handleEvent({type:"tool_execution_complete",toolCallId:I.id,result:`Error: ${H}`,durationMs:R});else{let w=yield*V.formatToolExecutionError(H,R);yield*V.writeOutput(w)}return u4G(W,d,Q),yield*X.error("Tool execution failed",{agentId:l,conversationId:Y,toolName:d,toolCallId:I.id,error:H}),{toolCallId:I.id,result:{error:H},success:!1,name:d}}})}static executeToolCalls(I,G,Z,b,W,l,Y,N,V){return h.gen(function*(){let X=yield*oW,d=yield*gG,F=yield*xl,m=I.map((u)=>u.function.name),Q=Array.from(new Set(m)),R=yield*h.all(Q.map((u)=>h.either(F.getTool(u))),{concurrency:l1I}),H=new Set;for(let u=0;u<Q.length;u++){let k=Q[u],A=R[u];if(k&&A&&Z2.isRight(A)&&A.right.approvalExecuteToolName)H.add(k)}let w=m.filter((u)=>H.has(u));if(Z.showToolExecution)if(b)yield*b.handleEvent({type:"tools_detected",toolNames:m,toolsRequiringApproval:w,agentName:N});else{let u=yield*X.formatToolsDetected(N,m,w);yield*X.writeOutput(u)}let v=[];for(let u of I)if(u.type==="function"){let{name:k,arguments:A}=u.function;try{let B=JSON.parse(A),O=B&&typeof B==="object"&&!Array.isArray(B)?B:{},M=hw(k,O,{style:"plain"});v.push(M?`${k} ${M}`:k)}catch{v.push(k)}}let y=v.join(", ");yield*d.info(`${N} is using tools: ${y}`);let J=new Set(w),C=yield*h.all(I.map((u)=>h.fork(FC.executeToolCall(u,G,Z,b,W,l,Y,J))),{concurrency:l1I}),E=h.all(C.map((u)=>k2.join(u)),{concurrency:"unbounded"});if(!V)return yield*E;let p=yield*h.race(E.pipe(h.map((u)=>({type:"results",results:u}))),V.pipe(h.as({type:"interrupt"})));if(p.type==="interrupt")return yield*h.all(C.map((u)=>k2.interrupt(u)),{concurrency:"unbounded"}),yield*h.fail(new VRI({reason:"Tool execution interrupted by user"}));return p.results})}}function dZb(I,G,Z){if(!Z?.length)return!1;if(I!=="execute_command")return!1;let b=G.command;if(typeof b!=="string")return!1;let W=xk(b);return Z.some((l)=>W===l||W.startsWith(l+" "))}function FZb(I,G){if(!G?.length)return!1;return G.includes(I)}var x3I=g(()=>{zI();oY();sW();X0();Rv();bN();aj();Kj();Tk()});function mZb(I,G){let Z=I/G;if(Z>=0.9)return{role:"user",content:`[BUDGET CRITICAL: Iteration ${I}/${G} (${Math.round(Z*100)}%). Write your final output NOW. No further research or subagent spawning. Use what you have collected so far.]`};if(Z>=0.7)return{role:"user",content:`[BUDGET WARNING: Iteration ${I}/${G} (${Math.round(Z*100)}%). Begin consolidating results. Stop spawning new research subagents. Move to consolidation and output phases.]`};return null}function QZb(I,G=M3I){if(I.length<G)return!1;let b=I.slice(-G).map((l)=>`${l.name}:${l.arguments}`);return new Set(b).size/G<0.4}function yr(I,G,Z,b,W){return h.acquireUseRelease(h.gen(function*(){let l=yield*gG;yield*l.setSessionId(I.sessionId);let Y=yield*LZ.make(OI.none());return{logger:l,finalizeFiberRef:Y}}),({logger:l,finalizeFiberRef:Y})=>h.gen(function*(){let{agent:N,maxIterations:V}=I,X=V??y9,d=yield*oW,{actualConversationId:F,context:m,tools:Q,messages:R,runMetrics:H,provider:w,model:v}=G,y=yield*h.tryPromise({try:()=>cc(v,w),catch:()=>Error("Failed to fetch model metadata")}).pipe(h.catchAll(()=>h.succeed(void 0))),J=y?.contextWindow??Nc,C=Z6.getConfig().maxTokens,E=Z6.getConfig().protectedRecentTurns,p=new $s({maxTokens:C,...E!==void 0&&{protectedRecentTurns:E},modelHint:{provider:w,modelId:v}});yield*l.debug("Using model context window",{model:v,provider:w,contextWindow:J,source:y?"models.dev":"default"});let u=[R[0],...R.slice(1)],k={content:"",conversationId:F},A=!1,B=!1,O=0,M=[];for(let P=0;P<X;P++){yield*h.sync(()=>p4G(H,P+1));try{if(!I.internal&&b.shouldShowThinking)yield*d.presentThinking(N.name,P===0);u=yield*Zw.compactIfNeeded(u,N,I.sessionId,F,W,J);let $;for(let T=u.length-1;T>=0;T--)if(u[T]?.role==="user"){$=u[T]?.content;break}yield*l.debug("Sending LLM request",{agentId:N.id,conversationId:F,iteration:P+1,provider:w,model:v,messageCount:u.length,toolsAvailable:Q.length,reasoningEffort:N.config.reasoningEffort,lastUserMessage:$});let e=mZb(P+1,X),n=e?[...u,e]:u,S=yield*b.getCompletion(n,P);if(S.interrupted){let T=S.completion;if(k={...k,content:T.content,...T.toolCalls?{toolCalls:T.toolCalls}:{}},T.content.length>0)u.push({role:"assistant",content:T.content});yield*d.presentWarning(N.name,"generation stopped by user"),A=!0,B=!0,yield*l.debug("Interruption handled, breaking loop");break}let{completion:K}=S;if(yield*l.debug("LLM response received",{agentId:N.id,conversationId:F,iteration:P+1,contentLength:K.content.length,toolCallsCount:K.toolCalls?.length??0,tokenUsage:K.usage,contentPreview:K.content.substring(0,300)}),K.usage)y4G(H,K.usage),C4G({authoritativePromptTokens:K.usage.promptTokens,messagesAtCallTime:u,provider:w,modelId:v});if(K.toolDefinitionChars!=null)z4G(H,a3I(K.toolDefinitionChars),K.toolDefinitionCount??0);if(K.toolsDisabled)k={...k,toolsDisabled:!0};let _={role:"assistant",content:K.content,...K.toolCalls?{tool_calls:K.toolCalls.map((T)=>({id:T.id,type:T.type,function:{name:T.function.name,arguments:T.function.arguments},...T.thought_signature?{thought_signature:T.thought_signature}:{}}))}:{}};if(u.push(_),u=(yield*p.trim(u,l,N.id,F)).messages,K.toolCalls&&K.toolCalls.length>0){yield*l.info("Agent decided to use tools",{agentId:N.id,conversationId:F,iteration:P+1,toolsChosen:K.toolCalls.map((t)=>t.function.name),reasoning:K.content});for(let t of K.toolCalls)if(t.type==="function")M.push({name:t.function.name,arguments:t.function.arguments});if(M.length>M3I)M.splice(0,M.length-M3I);if(QZb(M))yield*l.warn("Meltdown detected — injecting recovery signal",{agentId:N.id,recentTools:M.slice(-10).map((t)=>t.name)}),u.push({role:"user",content:"[MELTDOWN DETECTED: You have been repeating the same tool calls without progress. Stop the current approach. Summarize what you have found so far, identify what is still missing, and either proceed directly to output or try a fundamentally different search strategy. Do not repeat your last action.]"}),M.length=0;let T={...m,tokenStats:{currentTokens:p.calculateTotalTokens(u),maxTokens:J},conversationMessages:u,parentAgent:N,parentMaxIterations:X,compactConversation:(t)=>{u=[u[0],...t.slice(1)]}},QI=yield*FC.executeToolCalls(K.toolCalls,T,Z,b.getRenderer(),H,N.id,F,N.name,b.getInterruptSignal?.()),FI=new Map(QI.map((t)=>[t.toolCallId,t.result])),i=[];for(let t of K.toolCalls)if(t.type==="function"&&!FI.has(t.id))i.push(t.id);if(i.length>0)return yield*l.error("Missing tool results for some tool calls",{agentId:N.id,conversationId:F,missingToolCallIds:i,expectedCount:K.toolCalls.length,actualCount:QI.length}),yield*h.fail(Error(`Missing tool results for ${i.length} tool call(s). This indicates a bug in tool execution.`));for(let t of K.toolCalls)if(t.type==="function"){let XI=FI.get(t.id);if(XI===void 0)yield*l.error("Tool result is undefined despite validation",{agentId:N.id,conversationId:F,toolCallId:t.id,toolName:t.function.name}),u.push({role:"tool",name:t.function.name,content:C3I(t.function.name,{error:"Tool execution result was undefined"}),tool_call_id:t.id});else{let dI=C3I(t.function.name,XI);u.push({role:"tool",name:t.function.name,content:dI,tool_call_id:t.id}),k4G(H,t.function.name,dI.length)}}k={...k,toolCalls:K.toolCalls,toolResults:Object.fromEntries(QI.map((t)=>[t.name,t.result]))};let o=I.checkQueuedMessage?.();if(o)u.push({role:"user",content:o});continue}yield*l.info("Agent provided final response",{agentId:N.id,conversationId:F,iteration:P+1,completionLength:K.content.length,totalToolsUsed:H.toolCalls});let YI=K.content?.trim().length?K.content:K.reasoning??K.content;k={...k,content:YI,...K.reasoning?{reasoning:K.reasoning}:{}},yield*b.presentResponse(N.name,YI,K),yield*d.presentCompletion(N.name),yield*b.onComplete(N.name,K),O=P+1,A=!0;break}finally{yield*h.sync(()=>A4G(H))}}if(!A)O=X,yield*d.presentWarning(N.name,`iteration limit reached (${X}) - type 'continue' to resume`);else if(!k.content?.trim()&&!k.reasoning?.trim()&&!k.toolCalls&&!B)yield*d.presentWarning(N.name,"model returned an empty response");yield*l.debug("Finalizing agent run",{interrupted:B,finished:A});let q=yield*U4G(H,{iterationsUsed:O,finished:A}).pipe(h.catchAll((P)=>l.warn("Failed to write agent token usage log",{error:P.message})),h.fork);yield*LZ.set(Y,OI.some(q));let j=y?.inputPricePerMillion??0,x=y?.outputPricePerMillion??0,D=j>0||x>0?parseFloat((H.totalPromptTokens/1e6*j+H.totalCompletionTokens/1e6*x).toFixed(8)):void 0;return{...k,messages:u,usage:{promptTokens:H.totalPromptTokens,completionTokens:H.totalCompletionTokens},...D!==void 0?{costUSD:D}:{}}}),({logger:l,finalizeFiberRef:Y})=>h.gen(function*(){let N=yield*LZ.get(Y);if(OI.isSome(N))yield*k2.await(N.value).pipe(h.asVoid,h.catchAll(()=>h.void));yield*l.clearSessionId()}))}var M3I=10;var K3I=g(()=>{zI();RR();sW();X0();HR();jJG();x3I();zHI();is();Tk()});function j3I(I,G,Z,b,W){return h.gen(function*(){let l=yield*Xd,Y=yield*gG,N=yield*oW,{agent:V}=I,{runMetrics:X,provider:d,model:F}=G,m=G.maxRetries??hz,Q=V.config.reasoningEffort??"disable",H={shouldShowThinking:Z.showThinking&&Q!=="disable",getCompletion(w,v){return h.gen(function*(){let y={model:F,messages:w,tools:G.tools,toolChoice:"auto",reasoning_effort:Q,...V.config.llmApiKeys?{providerApiKeys:V.config.llmApiKeys}:{}},J=(u,k)=>N.presentStatus(u,k),C=yield*LZ.make(0),E=Bj(m,V.name,J,C);return{completion:yield*h.retry(Uj(V.name,J,h.gen(function*(){try{return yield*l.createChatCompletion(d,y)}catch(u){throw jj(X,u),u}})),E).pipe(h.timeout(Ul.seconds(jK)),h.tapError((u)=>UY.isTimeoutException(u)?J(`${V.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):h.void)),interrupted:!1}})},presentResponse(w,v,y){return h.gen(function*(){let J=v;if(J&&Z.mode==="rendered")J=yield*N.renderMarkdown(J);if(J&&J.trim().length>0)yield*N.writeBlankLine(),yield*N.presentAgentResponse(V.name,J),yield*N.writeBlankLine();if(b&&y.usage){let C=[];if(y.usage.totalTokens)C.push(`Total: ${y.usage.totalTokens} tokens`);if(y.usage.promptTokens)C.push(`Prompt: ${y.usage.promptTokens}`);if(y.usage.completionTokens)C.push(`Completion: ${y.usage.completionTokens}`);if(C.length>0)yield*Y.info(`[${C.join(" | ")}]`)}})},onComplete(w,v){return h.void},getRenderer(){return null}};return yield*yr(I,G,Z,H,W)})}var O4G=g(()=>{zI();y3I();vv();sW();X0();K3I();Tk()});var Sk;var Cr=g(()=>{zI();Sk=tG.GenericTag("NotificationService")});function D3I(I,G,Z,b,W,l){return h.gen(function*(){let Y=yield*Xd,N=yield*gG,V=yield*oW,X=yield*h.serviceOption(Sk),{agent:d}=I,{runMetrics:F,provider:m,model:Q,actualConversationId:R}=G,H=G.maxRetries??hz,w=d.config.reasoningEffort??"disable",v=Z.showThinking&&w!=="disable",y={enabled:!0,...b.textBufferMs!==void 0&&{textBufferMs:b.textBufferMs}},J=yield*V.createStreamingRenderer({displayConfig:Z,streamingConfig:y,showMetrics:W,agentName:d.name,reasoningEffort:w,...I.ephemeralRegionId!==void 0&&{streamTarget:{kind:"ephemeral",regionId:I.ephemeralRegionId}}}),C=yield*_0.make(),E=()=>{h.runSync(_0.succeed(C,void 0))};yield*J.setInterruptHandler(E);let p=yield*LZ.make(void 0),u=yield*LZ.make("");return yield*yr(I,G,Z,{shouldShowThinking:v,getCompletion(B,O){return h.gen(function*(){yield*LZ.set(p,void 0),yield*LZ.set(u,"");let M={model:Q,messages:B,tools:G.tools,toolChoice:"auto",reasoning_effort:w,...d.config.llmApiKeys?{providerApiKeys:d.config.llmApiKeys}:{}},q=(K,_)=>V.presentStatus(K,_),j=yield*LZ.make(0),x=Bj(H,d.name,q,j),D=yield*h.retry(Uj(d.name,q,h.gen(function*(){try{return yield*Y.createStreamingChatCompletion(m,M)}catch(K){if(jj(F,K),K instanceof VR||K instanceof ih||K instanceof hm)yield*N.error("LLM request error",{provider:m,model:d.config.llmModel,errorType:K._tag,message:K.message,agentId:d.id,conversationId:R});throw K}})),x).pipe(h.timeout(Ul.seconds(jK)),h.tapError((K)=>UY.isTimeoutException(K)?q(`${d.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):h.void),h.catchIf((K)=>XC(K),(K)=>h.gen(function*(){yield*N.warn("Streaming failed, falling back to non-streaming mode",{provider:m,model:d.config.llmModel,errorType:K._tag,message:K.message,agentId:d.id,conversationId:R});let _=yield*LZ.make(0),s=Bj(H,d.name,q,_),YI=yield*h.retry(Uj(d.name,q,h.gen(function*(){try{return yield*Y.createChatCompletion(m,M)}catch(T){throw jj(F,T),T}})),s).pipe(h.timeout(Ul.seconds(jK)),h.tapError((T)=>UY.isTimeoutException(T)?q(`${d.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):h.void));return{stream:Dh.empty,response:h.succeed(YI),cancel:h.void}}))),P=yield*h.fork(Dh.runForEach(D.stream,(K)=>h.gen(function*(){if(yield*J.handleEvent(K),K.type==="text_chunk")yield*LZ.set(u,K.accumulated);if(K.type==="complete"){if(yield*LZ.set(p,K.response),K.metrics?.firstTokenLatencyMs)g4G(F,K.metrics.firstTokenLatencyMs)}if(K.type==="error"){let _=K.error;if(yield*N.error("Stream event error",{provider:m,model:d.config.llmModel,errorType:_._tag,message:_.message,recoverable:K.recoverable,agentId:d.id,conversationId:R}),!K.recoverable)yield*D.cancel}}))),$=yield*k2.await(P).pipe(h.raceFirst(_0.await(C)));if(yield*_0.isDone(C)){yield*D.cancel.pipe(h.catchAll((YI)=>N.debug(`Stream cancel error (safe to ignore): ${String(YI)}`))),yield*k2.interrupt(P).pipe(h.catchAll((YI)=>N.debug(`Fiber interrupt error (safe to ignore): ${String(YI)}`)));let K=yield*LZ.get(u);return yield*J.flush().pipe(h.catchAll((YI)=>N.debug(`Renderer flush error (safe to ignore): ${String(YI)}`))),{completion:(yield*LZ.get(p))??{id:"interrupted",model:Q,content:K},interrupted:!0}}let n,S=$;if(IN.isFailure(S)){yield*D.cancel;let K=UY.failureOption(S.cause);if(OI.isSome(K))return yield*N.error("Stream processing failed",{error:K.value instanceof Error?K.value.message:String(K.value)}),yield*h.fail(K.value);else{let _=UY.dieOption(S.cause);if(OI.isSome(_))return yield*h.die(_.value);let s=yield*LZ.get(p);if(s)n=s;else n=yield*D.response.pipe(h.timeout(a4G),h.catchAll(()=>h.gen(function*(){return yield*D.cancel,yield*Y.createChatCompletion(m,M)})))}}else{let K=yield*LZ.get(p);if(K)n=K;else n=yield*D.response.pipe(h.timeout(a4G),h.catchAll(()=>h.gen(function*(){return yield*D.cancel,yield*Y.createChatCompletion(m,M)})))}return{completion:n,interrupted:!1}})},presentResponse(B,O,M){return h.void},onComplete(B,O){return h.gen(function*(){if(OI.isSome(X))yield*X.value.notify(`${B} has completed the task.`,{title:"Jazz Task Complete",sound:!0}).pipe(h.catchAll(()=>h.void))})},getRenderer(){return J},getInterruptSignal(){return _0.await(C)}},l).pipe(h.ensuring(J.setInterruptHandler(null)))})}var a4G;var x4G=g(()=>{zI();y3I();vv();sW();Cr();X0();bN();gj();K3I();Tk();a4G=Ul.seconds(15)});var M4G=g(()=>{O4G();x4G();x3I()});function pr(I){return I.transport===void 0||I.transport==="stdio"}function Ar(I){return I.transport==="http"}var EV;var ww=g(()=>{zI();EV=tG.GenericTag("MCPServerManager")});function K4G(){return{name:"get_time",description:"Get current date and time. Use for scheduling, relative times (yesterday, next Monday), and timestamps.",parameters:c.object({}).strict(),riskLevel:"read-only",hidden:!1,createSummary:void 0,execute:()=>{let I=new Date,G=I.toISOString(),Z=RZb[I.getDay()],b=I.toLocaleDateString(),W=I.toLocaleTimeString(),l=Intl.DateTimeFormat().resolvedOptions().timeZone;return h.succeed({success:!0,result:{iso:G,timestamp:I.getTime(),dayOfWeek:Z,localDate:b,localTime:W,timezone:l}})}}}function j4G(){return{name:"context_info",description:"Get current context window token usage statistics.",parameters:c.object({}),riskLevel:"read-only",hidden:!1,createSummary:void 0,execute:(I,G)=>{let Z=G.tokenStats?.currentTokens??0,b=G.tokenStats?.maxTokens??50000,W=Math.round(Z/b*100),l=b-Z,Y;if(W<50)Y="Context budget is healthy. Proceed normally.";else if(W<80)Y="Context is moderately used. Consider being concise.";else Y="Context is limited. Complete current task or consider summarizing earlier context.";return h.succeed({success:!0,result:{estimatedTokensUsed:Z,maxTokens:b,remainingTokens:l,percentUsed:W,recommendation:Y}})}}}var RZb;var D4G=g(()=>{zI();bb();RZb=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]});var cG;var lW=g(()=>{zI();cG=tG.GenericTag("FileSystemContextService")});function kZ(I){let G=I.approvalExecuteToolName?"high-risk":"read-only";return{name:I.name,description:I.description,tags:I.tags??[],...I.aliases?{aliases:I.aliases}:{},parameters:I.parameters,hidden:I.hidden===!0,riskLevel:I.riskLevel??G,...I.approvalExecuteToolName?{approvalExecuteToolName:I.approvalExecuteToolName}:{},...I.longRunning?{longRunning:!0}:{},...I.timeoutMs!==void 0?{timeoutMs:I.timeoutMs}:{},createSummary:I.createSummary,execute(Z,b){if(I.validate){let W=I.validate(Z);if(!W.valid){let Y=(W.errors||["Invalid arguments"]).join("; ");return h.succeed({success:!1,result:null,error:Y})}let l=W.value;return I.handler(l,b)}return I.handler(Z,b)}}}function aG(I){return(G)=>{let Z=I.safeParse(G);if(!Z.success)return{valid:!1,errors:Z.error.issues.map((W)=>{let l=W.path.join(".");return l.length>0?`${l}: ${W.message}`:W.message})};return{valid:!0,value:Z.data}}}function HZb(I){return`⚠️ APPROVAL REQUIRED: ${I}`}function hZb(I){return`\uD83D\uDD27 EXECUTION TOOL: ${I}`}function Al(I){let G=`execute_${I.name}`,Z=I.riskLevel??"high-risk",b=I.validate??((N)=>{let V=I.parameters.safeParse(N);return V.success?{valid:!0,value:V.data}:{valid:!1,errors:V.error.issues.map((X)=>X.message)}}),W=I.approvalErrorMessage??`Approval required: ${I.name} requires user confirmation.`,l=kZ({name:I.name,description:HZb(I.description),...I.tags?{tags:I.tags}:{},parameters:I.parameters,riskLevel:Z,validate:b,approvalExecuteToolName:G,handler:(N,V)=>h.gen(function*(){let X=yield*I.approvalMessage(N,V);if(typeof X==="object"&&"skipApproval"in X)return X.toolResult;let d=typeof X==="string"?X:X.message,F=typeof X==="string"?void 0:X.previewDiff;return{success:!1,result:{approvalRequired:!0,message:d,previewDiff:F,executeToolName:G,executeArgs:N},error:W}})}),Y=kZ({name:G,description:hZb(`Performs the actual ${I.name} operation after user approval. This tool should only be called by the system after approval.`),hidden:!0,riskLevel:Z,parameters:I.parameters,validate:b,handler:I.handler,...I.createSummary?{createSummary:I.createSummary}:{},...I.timeoutMs!==void 0?{timeoutMs:I.timeoutMs}:{}});return{approval:l,execute:Y,all:()=>[l,Y]}}var nb=g(()=>{zI()});function aZ(I){return I.conversationId?{agentId:I.agentId,conversationId:I.conversationId}:{agentId:I.agentId}}function q4G(){let I=c.object({path:c.string().min(1).describe("Absolute or relative path to change to")}).strict();return kZ({name:"cd",description:"Change the working directory for this session. Persists across subsequent tool calls.",tags:["filesystem","navigation"],parameters:I,validate:aG(I),handler:(G,Z)=>h.gen(function*(){let b=yield*rI.FileSystem,W=yield*cG,l=yield*W.resolvePath(aZ(Z),G.path).pipe(h.catchAll(()=>h.succeed(null)));if(l===null)return{success:!1,result:null,error:`Path not found: ${G.path}`};try{if((yield*b.stat(l)).type!=="Directory")return{success:!1,result:null,error:`Not a directory: ${l}`};return yield*W.setCwd(aZ(Z),l),{success:!0,result:l}}catch(Y){return{success:!1,result:null,error:`cd failed: ${Y instanceof Error?Y.message:String(Y)}`}}})})}var T4G=g(()=>{Sb();zI();bb();lW();nb()});function n4G(){let I={name:"cp",description:"Copy a file or directory. Equivalent to shell cp/cp -r. Directories are copied recursively.",tags:["filesystem","write"],parameters:S4G,validate:aG(S4G),approvalMessage:(G,Z)=>h.gen(function*(){let b=yield*cG,W=yield*b.resolvePath(aZ(Z),G.source),l=yield*b.resolvePath(aZ(Z),G.destination,{skipExistenceCheck:!0}),Y=G.force===!0?" (will overwrite if exists)":"";return`About to copy: ${W}
|
|
7049
|
+
${d}`;return""}case"read_pdf":{let{pageCount:d,pagesExtracted:F,truncated:m,path:Q,tables:R,totalLines:H}=X,w=[];if(Q)w.push(`file: ${fZ(Q)}`);if(Array.isArray(F)&&F.length>0)w.push(`pages: ${F.join(", ")}`);if(typeof d==="number")w.push(`total: ${d}`);if(typeof H==="number")w.push(`lines: ${H}`);if(Array.isArray(R))w.push(`tables: ${R.length}`);if(m)w.push(uZ.default.yellow("truncated"));return w.length>0?` ${uZ.default.dim("(")}${w.join(", ")}${uZ.default.dim(")")}`:""}default:return Z(N(X))}}catch{return Z(G)}}var uZ,bZb=12,v4G=1200;var Kj=g(()=>{pR();uZ=zZ(h0(),1)});var qk;var Er=g(()=>{zI();qk=tG.GenericTag("TelemetryService")});import{randomUUID as YZb}from"node:crypto";function E4G(I){let{agent:G,conversationId:Z,userId:b,provider:W,model:l,reasoningEffort:Y,maxIterations:N}=I;return{runId:YZb(),agentId:G.id,agentName:G.name,persona:G.config.persona,agentUpdatedAt:G.updatedAt,conversationId:Z,...b?{userId:b}:{},...W?{provider:W}:{},...l?{model:l}:{},...Y?{reasoningEffort:Y}:{},maxIterations:N,startedAt:new Date,totalPromptTokens:0,totalCompletionTokens:0,totalReasoningTokens:0,totalCacheReadTokens:0,totalCacheWriteTokens:0,llmRetryCount:0,toolCalls:0,toolErrors:0,toolsUsed:new Set,toolCallCounts:{},toolInvocationSequence:[],errors:[],iterationSummaries:[],currentIteration:void 0,firstTokenLatencyMs:void 0,totalToolDefinitionTokens:0,totalToolResultTokens:0,toolDefinitionsOffered:0}}function y4G(I,G){if(I.totalPromptTokens+=G.promptTokens,I.totalCompletionTokens+=G.completionTokens,G.reasoningTokens!=null)I.totalReasoningTokens+=G.reasoningTokens;if(G.cacheReadTokens!=null)I.totalCacheReadTokens+=G.cacheReadTokens;if(G.cacheWriteTokens!=null)I.totalCacheWriteTokens+=G.cacheWriteTokens}function C4G(I){uv.calibrate(I.authoritativePromptTokens,I.messagesAtCallTime,{provider:I.provider,modelId:I.modelId})}function jj(I,G){I.llmRetryCount+=1,I.lastError=B4G(I,G,"llm-retry")}function p4G(I,G){let Z={iteration:G,toolCalls:0,toolsUsed:new Set,toolCallCounts:{},errors:[],toolSequence:[],toolDefinitionTokens:0,toolResultTokens:0,toolResultSizes:{}};I.currentIteration=Z,I.iterationSummaries.push(Z)}function A4G(I){I.currentIteration=void 0}function L4G(I,G){I.toolCalls+=1,I.toolsUsed.add(G),I.toolCallCounts[G]=(I.toolCallCounts[G]??0)+1,I.toolInvocationSequence.push(G);let Z=I.currentIteration;if(Z)Z.toolCalls+=1,Z.toolsUsed.add(G),Z.toolCallCounts[G]=(Z.toolCallCounts[G]??0)+1,Z.toolSequence.push(G)}function u4G(I,G,Z){I.toolErrors+=1,I.lastError=B4G(I,Z,`tool:${G}`)}function a3I(I){return Math.ceil(I/4)}function z4G(I,G,Z){if(I.totalToolDefinitionTokens+=G,I.toolDefinitionsOffered+=Z,I.currentIteration)I.currentIteration.toolDefinitionTokens=G}function k4G(I,G,Z){let b=a3I(Z);if(I.totalToolResultTokens+=b,I.currentIteration)I.currentIteration.toolResultTokens+=b,I.currentIteration.toolResultSizes[G]=(I.currentIteration.toolResultSizes[G]??0)+b}function g4G(I,G){if(I.firstTokenLatencyMs===void 0)I.firstTokenLatencyMs=G}function U4G(I,G){let Z=new Date,b=Z.getTime()-I.startedAt.getTime(),W=I.totalPromptTokens+I.totalCompletionTokens,l=Array.from(I.toolsUsed.values()).sort(),Y=Object.fromEntries(Object.entries(I.toolCallCounts).sort(([X],[d])=>X.localeCompare(d))),N=I.lastError&&I.lastError.trim().length>0?I.lastError:void 0,V=I.iterationSummaries.map((X)=>({iteration:X.iteration,toolCalls:X.toolCalls,toolsUsed:Array.from(X.toolsUsed.values()).sort(),toolCallCounts:Object.fromEntries(Object.entries(X.toolCallCounts).sort(([d],[F])=>d.localeCompare(F))),errors:X.errors,toolSequence:X.toolSequence,toolDefinitionTokens:X.toolDefinitionTokens,toolResultTokens:X.toolResultTokens,toolResultSizes:X.toolResultSizes}));return h.gen(function*(){yield*NZb({runId:I.runId,agentId:I.agentId,agentName:I.agentName,persona:I.persona,agentUpdatedAt:I.agentUpdatedAt,conversationId:I.conversationId,...I.userId?{userId:I.userId}:{},...I.provider?{provider:I.provider}:{},...I.model?{model:I.model}:{},...I.reasoningEffort?{reasoningEffort:I.reasoningEffort}:{},promptTokens:I.totalPromptTokens,completionTokens:I.totalCompletionTokens,totalTokens:W,...I.totalReasoningTokens>0&&{reasoningTokens:I.totalReasoningTokens},...I.totalCacheReadTokens>0&&{cacheReadTokens:I.totalCacheReadTokens},...I.totalCacheWriteTokens>0&&{cacheWriteTokens:I.totalCacheWriteTokens},iterations:G.iterationsUsed,maxIterations:I.maxIterations,finished:G.finished,startedAt:I.startedAt,endedAt:Z,durationMs:b,retryCount:I.llmRetryCount,...N?{lastError:N}:{},toolCalls:I.toolCalls,toolsUsed:l,toolErrors:I.toolErrors,toolCallCounts:Y,toolInvocationSequence:I.toolInvocationSequence,errors:I.errors,iterationSummaries:V,...I.firstTokenLatencyMs!==void 0?{firstTokenLatencyMs:I.firstTokenLatencyMs}:{},toolDefinitionTokens:I.totalToolDefinitionTokens,toolResultTokens:I.totalToolResultTokens,toolDefinitionsOffered:I.toolDefinitionsOffered}),yield*VZb(I,W,b,G)})}function NZb(I){return h.gen(function*(){let G=yield*gG,Z={runId:I.runId,agentId:I.agentId,agentName:I.agentName,persona:I.persona,agentUpdatedAt:I.agentUpdatedAt.toISOString(),conversationId:I.conversationId,userId:I.userId??"anonymous",provider:I.provider??"unknown",model:I.model??"unknown",reasoningEffort:I.reasoningEffort??"disable",iterations:I.iterations,maxIterations:I.maxIterations,finished:I.finished,retryCount:I.retryCount,...I.lastError?{lastError:I.lastError}:{},promptTokens:I.promptTokens,completionTokens:I.completionTokens,totalTokens:I.totalTokens,...I.reasoningTokens!=null&&{reasoningTokens:I.reasoningTokens},...I.cacheReadTokens!=null&&{cacheReadTokens:I.cacheReadTokens},...I.cacheWriteTokens!=null&&{cacheWriteTokens:I.cacheWriteTokens},...I.firstTokenLatencyMs!==void 0?{firstTokenLatencyMs:I.firstTokenLatencyMs}:{},toolCalls:I.toolCalls,toolErrors:I.toolErrors,toolsUsed:I.toolsUsed,toolCallCounts:I.toolCallCounts,toolInvocationSequence:I.toolInvocationSequence,errors:I.errors,iterationSummaries:I.iterationSummaries,startedAt:I.startedAt.toISOString(),endedAt:I.endedAt.toISOString(),durationMs:I.durationMs,toolDefinitionTokens:I.toolDefinitionTokens,toolResultTokens:I.toolResultTokens,toolDefinitionsOffered:I.toolDefinitionsOffered};yield*G.info("Agent token usage",Z)})}function cZb(I,G,Z,b){let W={promptTokens:I.totalPromptTokens,completionTokens:I.totalCompletionTokens,totalTokens:G,...I.totalReasoningTokens>0&&{reasoningTokens:I.totalReasoningTokens},...I.totalCacheReadTokens>0&&{cacheReadTokens:I.totalCacheReadTokens},...I.totalCacheWriteTokens>0&&{cacheWriteTokens:I.totalCacheWriteTokens},...I.totalToolDefinitionTokens>0&&{toolDefinitionTokens:I.totalToolDefinitionTokens},...I.totalToolResultTokens>0&&{toolResultTokens:I.totalToolResultTokens},...I.toolDefinitionsOffered>0&&{toolDefinitionsOffered:I.toolDefinitionsOffered}};return{runId:I.runId,agentId:I.agentId,agentName:I.agentName,conversationId:I.conversationId,...I.provider&&{provider:I.provider},...I.model&&{model:I.model},durationMs:Z,iterationsUsed:b.iterationsUsed,finished:b.finished,usage:W,toolCalls:I.toolCalls,toolErrors:I.toolErrors}}function VZb(I,G,Z,b){return h.flatMap(h.context(),(W)=>{let l=tG.getOption(W,qk);if(l._tag==="None")return h.void;let Y=l.value,N=cZb(I,G,Z,b);return Y.recordAgentRunCompleted(N).pipe(h.catchAll(()=>h.void))}).pipe(h.catchAll(()=>h.void))}function XZb(I){return(I instanceof Error?I.message:String(I)).replace(/\s+/g," ").trim()}function B4G(I,G,Z){let b=XZb(G),W=Z?`${Z}: ${b}`:b;if(I.errors.push(W),I.currentIteration)I.currentIteration.errors.push(W);return W}var Tk=g(()=>{zI();sW();Er();Ps()});class FC{static executeTool(I,G,Z,b){return h.gen(function*(){let W=yield*xl,l=yield*gG,Y=b,N=Y===void 0?yield*W.getTool(I).pipe(h.catchAll(()=>h.succeed(void 0))):void 0;if(Y===void 0){if(Y=N?.timeoutMs,Y===void 0&&!N?.longRunning)Y=_WG}let V=W.executeTool(I,G,Z);return yield*Y!==void 0?V.pipe(h.timeoutFail({duration:Y,onTimeout:()=>{let d=Math.round(Y/60000);return Error(`Operation timed out after '${d}m'`)}}),h.catchAll((d)=>{let F=d instanceof Error?d.message:String(d);if(F.includes("timed out"))return l.warn(`Tool timeout: ${I}: ${F}`),h.succeed({success:!1,result:null,error:F});return h.fail(d)})):V})}static executeToolCall(I,G,Z,b,W,l,Y,N){return h.gen(function*(){let V=yield*oW,X=yield*gG;if(I.type!=="function")return{toolCallId:I.id,result:null,success:!1,name:"unknown"};let{name:d,arguments:F}=I.function;L4G(W,d);let m=Date.now();try{let Q;try{Q=JSON.parse(F)}catch(k){throw Error(`Invalid JSON in tool arguments: ${k instanceof Error?k.message:String(k)}`)}let R=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{};yield*X.logToolCall(d,R);let w=yield*(yield*xl).getTool(d).pipe(h.catchAll(()=>h.succeed(void 0))),v=w?.longRunning===!0,y=N.has(d);if(Z.showToolExecution&&!y){let k;if(d==="web_search")k={provider:(yield*(yield*ZZ).appConfig).web_search?.provider??"builtin"};if(b)yield*b.handleEvent({type:"tool_execution_start",toolName:d,toolCallId:I.id,arguments:R,...k?{metadata:k}:{},...v?{longRunning:!0}:{}});else{let A=yield*V.formatToolExecutionStart(d,R,k?{metadata:k}:void 0);yield*V.writeBlankLine(),yield*V.writeOutput(A)}}let J=yield*FC.executeTool(d,R,G,w?.timeoutMs),C=Date.now()-m,E=d;if(qJG(J.result)){let k=J.result,O=(yield*(yield*xl).getTool(d).pipe(h.catchAll(()=>h.succeed({riskLevel:"high-risk"})))).riskLevel,M=()=>G.getAutoApprovePolicy?.(),q=M(),j=()=>DJG(O,M())||FZb(d,G.autoApprovedTools)||dZb(d,k.executeArgs,G.autoApprovedCommands),x=j();if(x)yield*X.info("Tool auto-approved by policy",{toolName:d,executeToolName:k.executeToolName,riskLevel:O,autoApprovePolicy:q});else yield*X.debug("Tool requires approval, showing approval prompt",{toolName:d,executeToolName:k.executeToolName,riskLevel:O,autoApprovePolicy:q});let D=x?{approved:!0}:yield*V.requestApproval({toolName:d,message:k.message,executeToolName:k.executeToolName,executeArgs:k.executeArgs,...k.previewDiff?{previewDiff:k.previewDiff}:{},isAutoApproved:j});if(D.approved){if(D.alwaysApproveCommand&&G.onAutoApproveCommand)yield*G.onAutoApproveCommand(D.alwaysApproveCommand),yield*X.info("User chose to always approve command",{command:D.alwaysApproveCommand});if(D.alwaysApproveTool&&G.onAutoApproveTool)G.onAutoApproveTool(D.alwaysApproveTool),yield*X.info("User chose to always approve tool",{toolName:D.alwaysApproveTool});if(!x)yield*X.info("User approved tool execution",{toolName:d,executeToolName:k.executeToolName});let P=Date.now();if(Z.showToolExecution){let $;if(k.executeToolName==="web_search")$={provider:(yield*(yield*ZZ).appConfig).web_search?.provider??"builtin"};if(b)yield*b.handleEvent({type:"tool_execution_start",toolName:d,toolCallId:I.id,arguments:k.executeArgs,...$?{metadata:$}:{}});else{let e=yield*V.formatToolExecutionStart(d,k.executeArgs,$?{metadata:$}:void 0);yield*V.writeBlankLine(),yield*V.writeOutput(e)}}yield*V.signalToolExecutionStarted(),J=yield*FC.executeTool(k.executeToolName,k.executeArgs,G),C=Date.now()-P,E=k.executeToolName,yield*X.debug("Execution tool completed after approval",{executeToolName:k.executeToolName,success:J.success,durationMs:C,autoApproved:x})}else yield*X.info("User rejected tool execution",{toolName:d,userMessage:D.userMessage}),J={success:!1,result:{rejected:!0,message:D.userMessage?.trim()||"User rejected the operation. Please acknowledge this and ask if they'd like to try something different."},error:"User rejected the operation"}}let p=JSON.stringify(J.result);if(yield*X.debug("Tool execution succeeded",{agentId:l,conversationId:Y,toolName:E,toolCallId:I.id,durationMs:C,success:J.success,resultSize:p.length,resultPreview:p.substring(0,200)}),Z.showToolExecution)if(b)yield*b.handleEvent({type:"tool_execution_complete",toolCallId:I.id,result:p,durationMs:C});else if(J.success){let k=V.formatToolResult(E,p),A=yield*V.formatToolExecutionComplete(k,C);yield*V.writeOutput(A)}else{let k=J.error||"Tool execution failed",A=yield*V.formatToolExecutionError(k,C);yield*V.writeOutput(A)}let u=J.success?J.result:{error:J.error??"Tool execution failed",result:J.result};return{toolCallId:I.id,result:u,success:J.success,name:E}}catch(Q){let R=Date.now()-m,H=Q instanceof Error?Q.message:String(Q);if(Z.showToolExecution)if(b)yield*b.handleEvent({type:"tool_execution_complete",toolCallId:I.id,result:`Error: ${H}`,durationMs:R});else{let w=yield*V.formatToolExecutionError(H,R);yield*V.writeOutput(w)}return u4G(W,d,Q),yield*X.error("Tool execution failed",{agentId:l,conversationId:Y,toolName:d,toolCallId:I.id,error:H}),{toolCallId:I.id,result:{error:H},success:!1,name:d}}})}static executeToolCalls(I,G,Z,b,W,l,Y,N,V){return h.gen(function*(){let X=yield*oW,d=yield*gG,F=yield*xl,m=I.map((u)=>u.function.name),Q=Array.from(new Set(m)),R=yield*h.all(Q.map((u)=>h.either(F.getTool(u))),{concurrency:l1I}),H=new Set;for(let u=0;u<Q.length;u++){let k=Q[u],A=R[u];if(k&&A&&Z2.isRight(A)&&A.right.approvalExecuteToolName)H.add(k)}let w=m.filter((u)=>H.has(u));if(Z.showToolExecution)if(b)yield*b.handleEvent({type:"tools_detected",toolNames:m,toolsRequiringApproval:w,agentName:N});else{let u=yield*X.formatToolsDetected(N,m,w);yield*X.writeOutput(u)}let v=[];for(let u of I)if(u.type==="function"){let{name:k,arguments:A}=u.function;try{let B=JSON.parse(A),O=B&&typeof B==="object"&&!Array.isArray(B)?B:{},M=hw(k,O,{style:"plain"});v.push(M?`${k} ${M}`:k)}catch{v.push(k)}}let y=v.join(", ");yield*d.info(`${N} is using tools: ${y}`);let J=new Set(w),C=yield*h.all(I.map((u)=>h.fork(FC.executeToolCall(u,G,Z,b,W,l,Y,J))),{concurrency:l1I}),E=h.all(C.map((u)=>k2.join(u)),{concurrency:"unbounded"});if(!V)return yield*E;let p=yield*h.race(E.pipe(h.map((u)=>({type:"results",results:u}))),V.pipe(h.as({type:"interrupt"})));if(p.type==="interrupt")return yield*h.all(C.map((u)=>k2.interrupt(u)),{concurrency:"unbounded"}),yield*h.fail(new VRI({reason:"Tool execution interrupted by user"}));return p.results})}}function dZb(I,G,Z){if(!Z?.length)return!1;if(I!=="execute_command")return!1;let b=G.command;if(typeof b!=="string")return!1;let W=xk(b);return Z.some((l)=>W===l||W.startsWith(l+" "))}function FZb(I,G){if(!G?.length)return!1;return G.includes(I)}var x3I=g(()=>{zI();oY();sW();X0();Rv();bN();aj();Kj();Tk()});function mZb(I,G){let Z=I/G;if(Z>=0.9)return{role:"user",content:`[BUDGET CRITICAL: Iteration ${I}/${G} (${Math.round(Z*100)}%). Write your final output NOW. No further research or subagent spawning. Use what you have collected so far.]`};if(Z>=0.7)return{role:"user",content:`[BUDGET WARNING: Iteration ${I}/${G} (${Math.round(Z*100)}%). Begin consolidating results. Stop spawning new research subagents. Move to consolidation and output phases.]`};return null}function QZb(I,G=M3I){if(I.length<G)return!1;let b=I.slice(-G).map((l)=>`${l.name}:${l.arguments}`);return new Set(b).size/G<0.4}function yr(I,G,Z,b,W){return h.acquireUseRelease(h.gen(function*(){let l=yield*gG;yield*l.setSessionId(I.sessionId);let Y=yield*LZ.make(OI.none());return{logger:l,finalizeFiberRef:Y}}),({logger:l,finalizeFiberRef:Y})=>h.gen(function*(){let{agent:N,maxIterations:V}=I,X=V??y9,d=yield*oW,{actualConversationId:F,context:m,tools:Q,messages:R,runMetrics:H,provider:w,model:v}=G,y=yield*h.tryPromise({try:()=>cc(v,w),catch:()=>Error("Failed to fetch model metadata")}).pipe(h.catchAll(()=>h.succeed(void 0))),J=y?.contextWindow??Nc,C=Z6.getConfig().maxTokens,E=Z6.getConfig().protectedRecentTurns,p=new $s({maxTokens:C,...E!==void 0&&{protectedRecentTurns:E},modelHint:{provider:w,modelId:v}});yield*l.debug("Using model context window",{model:v,provider:w,contextWindow:J,source:y?"models.dev":"default"});let u=[R[0],...R.slice(1)],k={content:"",conversationId:F},A=!1,B=!1,O=0,M=[];for(let P=0;P<X;P++){yield*h.sync(()=>p4G(H,P+1));try{if(!I.internal&&b.shouldShowThinking)yield*d.presentThinking(N.name,P===0);u=yield*Zw.compactIfNeeded(u,N,I.sessionId,F,W,J);let $;for(let T=u.length-1;T>=0;T--)if(u[T]?.role==="user"){$=u[T]?.content;break}yield*l.debug("Sending LLM request",{agentId:N.id,conversationId:F,iteration:P+1,provider:w,model:v,messageCount:u.length,toolsAvailable:Q.length,reasoningEffort:N.config.reasoningEffort,lastUserMessage:$});let e=mZb(P+1,X),n=e?[...u,e]:u,S=yield*b.getCompletion(n,P);if(S.interrupted){let T=S.completion;if(k={...k,content:T.content,...T.toolCalls?{toolCalls:T.toolCalls}:{}},T.content.length>0)u.push({role:"assistant",content:T.content});yield*d.presentWarning(N.name,"generation stopped by user"),A=!0,B=!0,yield*l.debug("Interruption handled, breaking loop");break}let{completion:K}=S;if(yield*l.debug("LLM response received",{agentId:N.id,conversationId:F,iteration:P+1,contentLength:K.content.length,toolCallsCount:K.toolCalls?.length??0,tokenUsage:K.usage,contentPreview:K.content.substring(0,300)}),K.usage)y4G(H,K.usage),C4G({authoritativePromptTokens:K.usage.promptTokens,messagesAtCallTime:u,provider:w,modelId:v});if(K.toolDefinitionChars!=null)z4G(H,a3I(K.toolDefinitionChars),K.toolDefinitionCount??0);if(K.toolsDisabled)k={...k,toolsDisabled:!0};let _={role:"assistant",content:K.content,...K.toolCalls?{tool_calls:K.toolCalls.map((T)=>({id:T.id,type:T.type,function:{name:T.function.name,arguments:T.function.arguments},...T.thought_signature?{thought_signature:T.thought_signature}:{}}))}:{}};if(u.push(_),u=(yield*p.trim(u,l,N.id,F)).messages,K.toolCalls&&K.toolCalls.length>0){yield*l.info("Agent decided to use tools",{agentId:N.id,conversationId:F,iteration:P+1,toolsChosen:K.toolCalls.map((t)=>t.function.name),reasoning:K.content});for(let t of K.toolCalls)if(t.type==="function")M.push({name:t.function.name,arguments:t.function.arguments});if(M.length>M3I)M.splice(0,M.length-M3I);if(QZb(M))yield*l.warn("Meltdown detected — injecting recovery signal",{agentId:N.id,recentTools:M.slice(-10).map((t)=>t.name)}),u.push({role:"user",content:"[MELTDOWN DETECTED: You have been repeating the same tool calls without progress. Stop the current approach. Summarize what you have found so far, identify what is still missing, and either proceed directly to output or try a fundamentally different search strategy. Do not repeat your last action.]"}),M.length=0;let T={...m,tokenStats:{currentTokens:p.calculateTotalTokens(u),maxTokens:J},conversationMessages:u,parentAgent:N,parentMaxIterations:X,compactConversation:(t)=>{u=[u[0],...t.slice(1)]}},QI=yield*FC.executeToolCalls(K.toolCalls,T,Z,b.getRenderer(),H,N.id,F,N.name,b.getInterruptSignal?.()),FI=new Map(QI.map((t)=>[t.toolCallId,t.result])),i=[];for(let t of K.toolCalls)if(t.type==="function"&&!FI.has(t.id))i.push(t.id);if(i.length>0)return yield*l.error("Missing tool results for some tool calls",{agentId:N.id,conversationId:F,missingToolCallIds:i,expectedCount:K.toolCalls.length,actualCount:QI.length}),yield*h.fail(Error(`Missing tool results for ${i.length} tool call(s). This indicates a bug in tool execution.`));for(let t of K.toolCalls)if(t.type==="function"){let XI=FI.get(t.id);if(XI===void 0)yield*l.error("Tool result is undefined despite validation",{agentId:N.id,conversationId:F,toolCallId:t.id,toolName:t.function.name}),u.push({role:"tool",name:t.function.name,content:C3I(t.function.name,{error:"Tool execution result was undefined"}),tool_call_id:t.id});else{let dI=C3I(t.function.name,XI);u.push({role:"tool",name:t.function.name,content:dI,tool_call_id:t.id}),k4G(H,t.function.name,dI.length)}}k={...k,toolCalls:K.toolCalls,toolResults:Object.fromEntries(QI.map((t)=>[t.name,t.result]))};let o=I.checkQueuedMessage?.();if(o)u.push({role:"user",content:o});continue}yield*l.info("Agent provided final response",{agentId:N.id,conversationId:F,iteration:P+1,completionLength:K.content.length,totalToolsUsed:H.toolCalls});let YI=K.content?.trim().length?K.content:K.reasoning??K.content;k={...k,content:YI,...K.reasoning?{reasoning:K.reasoning}:{}},yield*b.presentResponse(N.name,YI,K),yield*d.presentCompletion(N.name),yield*b.onComplete(N.name,K),O=P+1,A=!0;break}finally{yield*h.sync(()=>A4G(H))}}if(!A)O=X,yield*d.presentWarning(N.name,`iteration limit reached (${X}) - type 'continue' to resume`);else if(!k.content?.trim()&&!k.reasoning?.trim()&&!k.toolCalls&&!B)yield*d.presentWarning(N.name,"model returned an empty response");yield*l.debug("Finalizing agent run",{interrupted:B,finished:A});let q=yield*U4G(H,{iterationsUsed:O,finished:A}).pipe(h.catchAll((P)=>l.warn("Failed to write agent token usage log",{error:P.message})),h.fork);yield*LZ.set(Y,OI.some(q));let j=y?.inputPricePerMillion??0,x=y?.outputPricePerMillion??0,D=j>0||x>0?parseFloat((H.totalPromptTokens/1e6*j+H.totalCompletionTokens/1e6*x).toFixed(8)):void 0;return{...k,messages:u,usage:{promptTokens:H.totalPromptTokens,completionTokens:H.totalCompletionTokens},...D!==void 0?{costUSD:D}:{}}}),({logger:l,finalizeFiberRef:Y})=>h.gen(function*(){let N=yield*LZ.get(Y);if(OI.isSome(N))yield*k2.await(N.value).pipe(h.asVoid,h.catchAll(()=>h.void));yield*l.clearSessionId()}))}var M3I=10;var K3I=g(()=>{zI();RR();sW();X0();HR();jJG();x3I();zHI();is();Tk()});function j3I(I,G,Z,b,W){return h.gen(function*(){let l=yield*Xd,Y=yield*gG,N=yield*oW,{agent:V}=I,{runMetrics:X,provider:d,model:F}=G,m=G.maxRetries??hz,Q=V.config.reasoningEffort??"disable",R=Z.showThinking&&Q!=="disable",H=N.emitsToolEventsViaRenderer?.()===!0?yield*N.createStreamingRenderer({displayConfig:Z,streamingConfig:{enabled:!0},showMetrics:b,agentName:V.name,reasoningEffort:Q}):null;return yield*yr(I,G,Z,{shouldShowThinking:R,getCompletion(v,y){return h.gen(function*(){let J={model:F,messages:v,tools:G.tools,toolChoice:"auto",reasoning_effort:Q,...V.config.llmApiKeys?{providerApiKeys:V.config.llmApiKeys}:{}},C=(k,A)=>N.presentStatus(k,A),E=yield*LZ.make(0),p=Bj(m,V.name,C,E);return{completion:yield*h.retry(Uj(V.name,C,h.gen(function*(){try{return yield*l.createChatCompletion(d,J)}catch(k){throw jj(X,k),k}})),p).pipe(h.timeout(Ul.seconds(jK)),h.tapError((k)=>UY.isTimeoutException(k)?C(`${V.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):h.void)),interrupted:!1}})},presentResponse(v,y,J){return h.gen(function*(){let C=y;if(C&&Z.mode==="rendered")C=yield*N.renderMarkdown(C);if(C&&C.trim().length>0)yield*N.writeBlankLine(),yield*N.presentAgentResponse(V.name,C),yield*N.writeBlankLine();if(b&&J.usage){let E=[];if(J.usage.totalTokens)E.push(`Total: ${J.usage.totalTokens} tokens`);if(J.usage.promptTokens)E.push(`Prompt: ${J.usage.promptTokens}`);if(J.usage.completionTokens)E.push(`Completion: ${J.usage.completionTokens}`);if(E.length>0)yield*Y.info(`[${E.join(" | ")}]`)}})},onComplete(v,y){return h.void},getRenderer(){return H}},W)})}var O4G=g(()=>{zI();y3I();vv();sW();X0();K3I();Tk()});var Sk;var Cr=g(()=>{zI();Sk=tG.GenericTag("NotificationService")});function D3I(I,G,Z,b,W,l){return h.gen(function*(){let Y=yield*Xd,N=yield*gG,V=yield*oW,X=yield*h.serviceOption(Sk),{agent:d}=I,{runMetrics:F,provider:m,model:Q,actualConversationId:R}=G,H=G.maxRetries??hz,w=d.config.reasoningEffort??"disable",v=Z.showThinking&&w!=="disable",y={enabled:!0,...b.textBufferMs!==void 0&&{textBufferMs:b.textBufferMs}},J=yield*V.createStreamingRenderer({displayConfig:Z,streamingConfig:y,showMetrics:W,agentName:d.name,reasoningEffort:w,...I.ephemeralRegionId!==void 0&&{streamTarget:{kind:"ephemeral",regionId:I.ephemeralRegionId}}}),C=yield*_0.make(),E=()=>{h.runSync(_0.succeed(C,void 0))};yield*J.setInterruptHandler(E);let p=yield*LZ.make(void 0),u=yield*LZ.make("");return yield*yr(I,G,Z,{shouldShowThinking:v,getCompletion(B,O){return h.gen(function*(){yield*LZ.set(p,void 0),yield*LZ.set(u,"");let M={model:Q,messages:B,tools:G.tools,toolChoice:"auto",reasoning_effort:w,...d.config.llmApiKeys?{providerApiKeys:d.config.llmApiKeys}:{}},q=(K,_)=>V.presentStatus(K,_),j=yield*LZ.make(0),x=Bj(H,d.name,q,j),D=yield*h.retry(Uj(d.name,q,h.gen(function*(){try{return yield*Y.createStreamingChatCompletion(m,M)}catch(K){if(jj(F,K),K instanceof VR||K instanceof ih||K instanceof hm)yield*N.error("LLM request error",{provider:m,model:d.config.llmModel,errorType:K._tag,message:K.message,agentId:d.id,conversationId:R});throw K}})),x).pipe(h.timeout(Ul.seconds(jK)),h.tapError((K)=>UY.isTimeoutException(K)?q(`${d.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):h.void),h.catchIf((K)=>XC(K),(K)=>h.gen(function*(){yield*N.warn("Streaming failed, falling back to non-streaming mode",{provider:m,model:d.config.llmModel,errorType:K._tag,message:K.message,agentId:d.id,conversationId:R});let _=yield*LZ.make(0),s=Bj(H,d.name,q,_),YI=yield*h.retry(Uj(d.name,q,h.gen(function*(){try{return yield*Y.createChatCompletion(m,M)}catch(T){throw jj(F,T),T}})),s).pipe(h.timeout(Ul.seconds(jK)),h.tapError((T)=>UY.isTimeoutException(T)?q(`${d.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):h.void));return{stream:Dh.empty,response:h.succeed(YI),cancel:h.void}}))),P=yield*h.fork(Dh.runForEach(D.stream,(K)=>h.gen(function*(){if(yield*J.handleEvent(K),K.type==="text_chunk")yield*LZ.set(u,K.accumulated);if(K.type==="complete"){if(yield*LZ.set(p,K.response),K.metrics?.firstTokenLatencyMs)g4G(F,K.metrics.firstTokenLatencyMs)}if(K.type==="error"){let _=K.error;if(yield*N.error("Stream event error",{provider:m,model:d.config.llmModel,errorType:_._tag,message:_.message,recoverable:K.recoverable,agentId:d.id,conversationId:R}),!K.recoverable)yield*D.cancel}}))),$=yield*k2.await(P).pipe(h.raceFirst(_0.await(C)));if(yield*_0.isDone(C)){yield*D.cancel.pipe(h.catchAll((YI)=>N.debug(`Stream cancel error (safe to ignore): ${String(YI)}`))),yield*k2.interrupt(P).pipe(h.catchAll((YI)=>N.debug(`Fiber interrupt error (safe to ignore): ${String(YI)}`)));let K=yield*LZ.get(u);return yield*J.flush().pipe(h.catchAll((YI)=>N.debug(`Renderer flush error (safe to ignore): ${String(YI)}`))),{completion:(yield*LZ.get(p))??{id:"interrupted",model:Q,content:K},interrupted:!0}}let n,S=$;if(IN.isFailure(S)){yield*D.cancel;let K=UY.failureOption(S.cause);if(OI.isSome(K))return yield*N.error("Stream processing failed",{error:K.value instanceof Error?K.value.message:String(K.value)}),yield*h.fail(K.value);else{let _=UY.dieOption(S.cause);if(OI.isSome(_))return yield*h.die(_.value);let s=yield*LZ.get(p);if(s)n=s;else n=yield*D.response.pipe(h.timeout(a4G),h.catchAll(()=>h.gen(function*(){return yield*D.cancel,yield*Y.createChatCompletion(m,M)})))}}else{let K=yield*LZ.get(p);if(K)n=K;else n=yield*D.response.pipe(h.timeout(a4G),h.catchAll(()=>h.gen(function*(){return yield*D.cancel,yield*Y.createChatCompletion(m,M)})))}return{completion:n,interrupted:!1}})},presentResponse(B,O,M){return h.void},onComplete(B,O){return h.gen(function*(){if(OI.isSome(X))yield*X.value.notify(`${B} has completed the task.`,{title:"Jazz Task Complete",sound:!0}).pipe(h.catchAll(()=>h.void))})},getRenderer(){return J},getInterruptSignal(){return _0.await(C)}},l).pipe(h.ensuring(J.setInterruptHandler(null)))})}var a4G;var x4G=g(()=>{zI();y3I();vv();sW();Cr();X0();bN();gj();K3I();Tk();a4G=Ul.seconds(15)});var M4G=g(()=>{O4G();x4G();x3I()});function pr(I){return I.transport===void 0||I.transport==="stdio"}function Ar(I){return I.transport==="http"}var EV;var ww=g(()=>{zI();EV=tG.GenericTag("MCPServerManager")});function K4G(){return{name:"get_time",description:"Get current date and time. Use for scheduling, relative times (yesterday, next Monday), and timestamps.",parameters:c.object({}).strict(),riskLevel:"read-only",hidden:!1,createSummary:void 0,execute:()=>{let I=new Date,G=I.toISOString(),Z=RZb[I.getDay()],b=I.toLocaleDateString(),W=I.toLocaleTimeString(),l=Intl.DateTimeFormat().resolvedOptions().timeZone;return h.succeed({success:!0,result:{iso:G,timestamp:I.getTime(),dayOfWeek:Z,localDate:b,localTime:W,timezone:l}})}}}function j4G(){return{name:"context_info",description:"Get current context window token usage statistics.",parameters:c.object({}),riskLevel:"read-only",hidden:!1,createSummary:void 0,execute:(I,G)=>{let Z=G.tokenStats?.currentTokens??0,b=G.tokenStats?.maxTokens??50000,W=Math.round(Z/b*100),l=b-Z,Y;if(W<50)Y="Context budget is healthy. Proceed normally.";else if(W<80)Y="Context is moderately used. Consider being concise.";else Y="Context is limited. Complete current task or consider summarizing earlier context.";return h.succeed({success:!0,result:{estimatedTokensUsed:Z,maxTokens:b,remainingTokens:l,percentUsed:W,recommendation:Y}})}}}var RZb;var D4G=g(()=>{zI();bb();RZb=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]});var cG;var lW=g(()=>{zI();cG=tG.GenericTag("FileSystemContextService")});function kZ(I){let G=I.approvalExecuteToolName?"high-risk":"read-only";return{name:I.name,description:I.description,tags:I.tags??[],...I.aliases?{aliases:I.aliases}:{},parameters:I.parameters,hidden:I.hidden===!0,riskLevel:I.riskLevel??G,...I.approvalExecuteToolName?{approvalExecuteToolName:I.approvalExecuteToolName}:{},...I.longRunning?{longRunning:!0}:{},...I.timeoutMs!==void 0?{timeoutMs:I.timeoutMs}:{},createSummary:I.createSummary,execute(Z,b){if(I.validate){let W=I.validate(Z);if(!W.valid){let Y=(W.errors||["Invalid arguments"]).join("; ");return h.succeed({success:!1,result:null,error:Y})}let l=W.value;return I.handler(l,b)}return I.handler(Z,b)}}}function aG(I){return(G)=>{let Z=I.safeParse(G);if(!Z.success)return{valid:!1,errors:Z.error.issues.map((W)=>{let l=W.path.join(".");return l.length>0?`${l}: ${W.message}`:W.message})};return{valid:!0,value:Z.data}}}function HZb(I){return`⚠️ APPROVAL REQUIRED: ${I}`}function hZb(I){return`\uD83D\uDD27 EXECUTION TOOL: ${I}`}function Al(I){let G=`execute_${I.name}`,Z=I.riskLevel??"high-risk",b=I.validate??((N)=>{let V=I.parameters.safeParse(N);return V.success?{valid:!0,value:V.data}:{valid:!1,errors:V.error.issues.map((X)=>X.message)}}),W=I.approvalErrorMessage??`Approval required: ${I.name} requires user confirmation.`,l=kZ({name:I.name,description:HZb(I.description),...I.tags?{tags:I.tags}:{},parameters:I.parameters,riskLevel:Z,validate:b,approvalExecuteToolName:G,handler:(N,V)=>h.gen(function*(){let X=yield*I.approvalMessage(N,V);if(typeof X==="object"&&"skipApproval"in X)return X.toolResult;let d=typeof X==="string"?X:X.message,F=typeof X==="string"?void 0:X.previewDiff;return{success:!1,result:{approvalRequired:!0,message:d,previewDiff:F,executeToolName:G,executeArgs:N},error:W}})}),Y=kZ({name:G,description:hZb(`Performs the actual ${I.name} operation after user approval. This tool should only be called by the system after approval.`),hidden:!0,riskLevel:Z,parameters:I.parameters,validate:b,handler:I.handler,...I.createSummary?{createSummary:I.createSummary}:{},...I.timeoutMs!==void 0?{timeoutMs:I.timeoutMs}:{}});return{approval:l,execute:Y,all:()=>[l,Y]}}var nb=g(()=>{zI()});function aZ(I){return I.conversationId?{agentId:I.agentId,conversationId:I.conversationId}:{agentId:I.agentId}}function q4G(){let I=c.object({path:c.string().min(1).describe("Absolute or relative path to change to")}).strict();return kZ({name:"cd",description:"Change the working directory for this session. Persists across subsequent tool calls.",tags:["filesystem","navigation"],parameters:I,validate:aG(I),handler:(G,Z)=>h.gen(function*(){let b=yield*rI.FileSystem,W=yield*cG,l=yield*W.resolvePath(aZ(Z),G.path).pipe(h.catchAll(()=>h.succeed(null)));if(l===null)return{success:!1,result:null,error:`Path not found: ${G.path}`};try{if((yield*b.stat(l)).type!=="Directory")return{success:!1,result:null,error:`Not a directory: ${l}`};return yield*W.setCwd(aZ(Z),l),{success:!0,result:l}}catch(Y){return{success:!1,result:null,error:`cd failed: ${Y instanceof Error?Y.message:String(Y)}`}}})})}var T4G=g(()=>{Sb();zI();bb();lW();nb()});function n4G(){let I={name:"cp",description:"Copy a file or directory. Equivalent to shell cp/cp -r. Directories are copied recursively.",tags:["filesystem","write"],parameters:S4G,validate:aG(S4G),approvalMessage:(G,Z)=>h.gen(function*(){let b=yield*cG,W=yield*b.resolvePath(aZ(Z),G.source),l=yield*b.resolvePath(aZ(Z),G.destination,{skipExistenceCheck:!0}),Y=G.force===!0?" (will overwrite if exists)":"";return`About to copy: ${W}
|
|
7050
7050
|
to: ${l}${Y}`}),handler:(G,Z)=>h.gen(function*(){let b=yield*rI.FileSystem,W=yield*cG,l=yield*W.resolvePath(aZ(Z),G.source),Y=yield*W.resolvePath(aZ(Z),G.destination,{skipExistenceCheck:!0}),N=l.endsWith("/")?l:`${l}/`;if((Y.endsWith("/")?Y:`${Y}/`).startsWith(N))return{success:!1,result:null,error:`Destination must not be within source: ${Y}`};let X=yield*b.exists(Y).pipe(h.catchAll(()=>h.succeed(!1)));if(X&&G.force!==!0)return{success:!1,result:null,error:`Destination exists: ${Y}. Use force: true to overwrite.`};if(X&&G.force===!0)yield*b.remove(Y,{recursive:!0});return yield*b.copy(l,Y,{overwrite:G.force===!0}).pipe(h.map(()=>({success:!0,result:`Copied: ${l} → ${Y}`})),h.catchAll((d)=>h.succeed({success:!1,result:null,error:`cp failed: ${d instanceof Error?d.message:String(d)}`})))})};return Al(I)}var S4G;var _4G=g(()=>{Sb();zI();bb();lW();nb();S4G=c.object({source:c.string().min(1).describe("Path to copy (file or directory)"),destination:c.string().min(1).describe("Destination path"),force:c.boolean().optional().describe("Overwrite destination if it exists (default: false)")}).strict()});class Lr{diff(I,G,Z={}){let b;if(typeof Z==="function")b=Z,Z={};else if("callback"in Z)b=Z.callback;let W=this.castInput(I,Z),l=this.castInput(G,Z),Y=this.removeEmpty(this.tokenize(W,Z)),N=this.removeEmpty(this.tokenize(l,Z));return this.diffWithOptionsObj(Y,N,Z,b)}diffWithOptionsObj(I,G,Z,b){var W;let l=(v)=>{if(v=this.postProcess(v,Z),b){setTimeout(function(){b(v)},0);return}else return v},Y=G.length,N=I.length,V=1,X=Y+N;if(Z.maxEditLength!=null)X=Math.min(X,Z.maxEditLength);let d=(W=Z.timeout)!==null&&W!==void 0?W:1/0,F=Date.now()+d,m=[{oldPos:-1,lastComponent:void 0}],Q=this.extractCommon(m[0],G,I,0,Z);if(m[0].oldPos+1>=N&&Q+1>=Y)return l(this.buildValues(m[0].lastComponent,G,I));let R=-1/0,H=1/0,w=()=>{for(let v=Math.max(R,-V);v<=Math.min(H,V);v+=2){let y,J=m[v-1],C=m[v+1];if(J)m[v-1]=void 0;let E=!1;if(C){let u=C.oldPos-v;E=C&&0<=u&&u<Y}let p=J&&J.oldPos+1<N;if(!E&&!p){m[v]=void 0;continue}if(!p||E&&J.oldPos<C.oldPos)y=this.addToPath(C,!0,!1,0,Z);else y=this.addToPath(J,!1,!0,1,Z);if(Q=this.extractCommon(y,G,I,v,Z),y.oldPos+1>=N&&Q+1>=Y)return l(this.buildValues(y.lastComponent,G,I))||!0;else{if(m[v]=y,y.oldPos+1>=N)H=Math.min(H,v-1);if(Q+1>=Y)R=Math.max(R,v+1)}}V++};if(b)(function v(){setTimeout(function(){if(V>X||Date.now()>F)return b(void 0);if(!w())v()},0)})();else while(V<=X&&Date.now()<=F){let v=w();if(v)return v}}addToPath(I,G,Z,b,W){let l=I.lastComponent;if(l&&!W.oneChangePerToken&&l.added===G&&l.removed===Z)return{oldPos:I.oldPos+b,lastComponent:{count:l.count+1,added:G,removed:Z,previousComponent:l.previousComponent}};else return{oldPos:I.oldPos+b,lastComponent:{count:1,added:G,removed:Z,previousComponent:l}}}extractCommon(I,G,Z,b,W){let l=G.length,Y=Z.length,N=I.oldPos,V=N-b,X=0;while(V+1<l&&N+1<Y&&this.equals(Z[N+1],G[V+1],W))if(V++,N++,X++,W.oneChangePerToken)I.lastComponent={count:1,previousComponent:I.lastComponent,added:!1,removed:!1};if(X&&!W.oneChangePerToken)I.lastComponent={count:X,previousComponent:I.lastComponent,added:!1,removed:!1};return I.oldPos=N,V}equals(I,G,Z){if(Z.comparator)return Z.comparator(I,G);else return I===G||!!Z.ignoreCase&&I.toLowerCase()===G.toLowerCase()}removeEmpty(I){let G=[];for(let Z=0;Z<I.length;Z++)if(I[Z])G.push(I[Z]);return G}castInput(I,G){return I}tokenize(I,G){return Array.from(I)}join(I){return I.join("")}postProcess(I,G){return I}get useLongestToken(){return!1}buildValues(I,G,Z){let b=[],W;while(I)b.push(I),W=I.previousComponent,delete I.previousComponent,I=W;b.reverse();let l=b.length,Y=0,N=0,V=0;for(;Y<l;Y++){let X=b[Y];if(!X.removed){if(!X.added&&this.useLongestToken){let d=G.slice(N,N+X.count);d=d.map(function(F,m){let Q=Z[V+m];return Q.length>F.length?Q:F}),X.value=this.join(d)}else X.value=this.join(G.slice(N,N+X.count));if(N+=X.count,!X.added)V+=X.count}else X.value=this.join(Z.slice(V,V+X.count)),V+=X.count}return b}}function q3I(I,G,Z){return wZb.diff(I,G,Z)}function JZb(I,G){if(G.stripTrailingCr)I=I.replace(/\r\n/g,`
|
|
7051
7051
|
`);let Z=[],b=I.split(/(\n|\r\n)/);if(!b[b.length-1])b.pop();for(let W=0;W<b.length;W++){let l=b[W];if(W%2&&!G.newlineIsToken)Z[Z.length-1]+=l;else Z.push(l)}return Z}var P4G,wZb;var $4G=g(()=>{P4G=class P4G extends Lr{constructor(){super(...arguments);this.tokenize=JZb}equals(I,G,Z){if(Z.ignoreWhitespace){if(!Z.newlineIsToken||!I.includes(`
|
|
7052
7052
|
`))I=I.trim();if(!Z.newlineIsToken||!G.includes(`
|
|
@@ -7670,7 +7670,7 @@ ${N.join(`
|
|
|
7670
7670
|
}
|
|
7671
7671
|
}
|
|
7672
7672
|
`;yield*b.writeFileString(Y,N).pipe(h.catchAll(()=>h.void)),yield*Z.info(`Opening ${W} to edit MCP server configuration...`);try{hWW(`${W} "${Y}"`,{stdio:"inherit"})}catch{yield*b.remove(Y).pipe(h.catchAll(()=>h.void)),yield*Z.error(`Failed to open editor (${W}). Set $EDITOR or use --file instead.`);return}let V=yield*b.readFileString(Y).pipe(h.option);if(yield*b.remove(Y).pipe(h.catchAll(()=>h.void)),OI.isNone(V)){yield*Z.error("Could not read temp file after editing.");return}let X=V.value;if(X.trim()===""||X.trim()===N.trim()){yield*Z.warn("No changes made. Aborting.");return}return yield*iWI(X)})}function jNZ(){return h.gen(function*(){let I=yield*oG,Z=yield*(yield*ZZ).getOrElse("mcpServers",{}),b=Object.entries(Z);if(b.length===0){yield*I.info("No MCP servers configured.");return}yield*I.heading("MCP Servers");for(let[W,l]of b){let N=l.enabled!==!1?"enabled":"disabled",V="command"in l?`stdio: ${l.command}`:"http";yield*I.log(` ${W} (${V}) [${N}]`)}})}function DNZ(){return h.gen(function*(){let I=yield*oG,G=yield*ZZ,Z=yield*rI.FileSystem,b=yield*G.getOrElse("mcpServers",{}),W=Object.keys(b);if(W.length===0){yield*I.info("No MCP servers to remove.");return}let l=yield*I.select("Select a server to remove:",{choices:W.map((V)=>({name:V,value:V}))});if(!l){yield*I.info("Cancelled.");return}if(!(yield*I.confirm(`Remove server "${l}"?`,!1))){yield*I.info("Cancelled.");return}yield*HfG(Z,l);let N={};for(let[V,X]of Object.entries(b)){let d={};if(V===l)d.enabled=!1;else if(X.enabled!==void 0)d.enabled=X.enabled;if(Object.keys(d).length>0)N[V]=d}yield*G.set("mcpServers",N),yield*I.success(`Removed MCP server: ${l}`)})}function qNZ(){return h.gen(function*(){let I=yield*oG,G=yield*ZZ,Z=yield*G.getOrElse("mcpServers",{}),b=Object.entries(Z).filter(([,l])=>l.enabled===!1);if(b.length===0){yield*I.info("No disabled MCP servers to enable.");return}let W=yield*I.select("Select a server to enable:",{choices:b.map(([l])=>({name:l,value:l}))});if(!W){yield*I.info("Cancelled.");return}yield*G.set(`mcpServers.${W}`,{enabled:!0}),yield*I.success(`Enabled MCP server: ${W}`)})}function TNZ(){return h.gen(function*(){let I=yield*oG,G=yield*ZZ,Z=yield*G.getOrElse("mcpServers",{}),b=Object.entries(Z).filter(([,l])=>l.enabled!==!1);if(b.length===0){yield*I.info("No enabled MCP servers to disable.");return}let W=yield*I.select("Select a server to disable:",{choices:b.map(([l])=>({name:l,value:l}))});if(!W){yield*I.info("Cancelled.");return}yield*G.set(`mcpServers.${W}`,{enabled:!1}),yield*I.success(`Disabled MCP server: ${W}`)})}var vWW,EWW,yWW,CWW;var SNZ=g(()=>{Sb();zI();bb();oY();qN();nzI();vWW=c.object({command:c.string(),args:c.array(c.string()).optional(),env:c.record(c.string(),c.string()).optional(),enabled:c.boolean().optional()}),EWW=c.object({transport:c.literal("http"),url:c.string(),headers:c.record(c.string(),c.string()).optional(),enabled:c.boolean().optional()}),yWW=c.union([EWW,vWW]),CWW=c.record(c.string(),yWW)});function nNZ(){return h.gen(function*(){let I=yield*oG,G=yield*Nd;yield*I.heading("Create a new persona"),yield*I.log("A persona defines how an agent communicates — its tone, style, and behavioral rules."),yield*I.log("You can apply the same persona to different agents and models."),yield*I.log("");let Z=yield*I.ask("Persona name (e.g., hacker, therapist, pirate):",{validate:(V)=>{if(!V||V.trim().length===0)return"Name cannot be empty";if(V.length>100)return"Name cannot exceed 100 characters";if(!/^[a-zA-Z0-9_-]+$/.test(V))return"Only letters, numbers, underscores, and hyphens allowed";if(IT(V))return`"${V}" is a built-in persona name. Choose a different name.`;return!0},simple:!0});if(!Z||Z.trim().length===0){yield*I.info("Persona creation cancelled.");return}let b=yield*I.ask("Brief description (e.g., 'A sarcastic hacker who uses l33t speak'):",{validate:(V)=>{if(!V||V.trim().length===0)return"Description cannot be empty";if(V.length>500)return"Description cannot exceed 500 characters";return!0},simple:!0});if(!b||b.trim().length===0){yield*I.info("Persona creation cancelled.");return}yield*I.log(""),yield*I.info("Now write the system prompt. This is the core instruction that shapes how the agent behaves."),yield*I.info("Example: 'You are a cyberpunk hacker named Z3R0. Always use technical jargon, l33t speak, and reference the matrix. Be helpful but edgy.'"),yield*I.log("");let W=yield*I.ask("System prompt:",{validate:(V)=>{if(!V||V.trim().length===0)return"System prompt cannot be empty";if(V.length>1e4)return"System prompt cannot exceed 10,000 characters";return!0},simple:!0});if(!W||W.trim().length===0){yield*I.info("Persona creation cancelled.");return}let l=yield*I.ask("Tone (optional, e.g., sarcastic, formal, friendly):",{simple:!0}),Y=yield*I.ask("Style (optional, e.g., concise, verbose, technical):",{simple:!0}),N=yield*G.createPersona({name:Z.trim(),description:b.trim(),systemPrompt:W.trim(),...l&&l.trim().length>0?{tone:l.trim()}:{},...Y&&Y.trim().length>0?{style:Y.trim()}:{}});if(yield*I.log(""),yield*I.success(`Persona "${N.name}" created successfully!`),yield*I.log(` ID: ${N.id}`),yield*I.log(` Name: ${N.name}`),yield*I.log(` Description: ${N.description}`),N.tone)yield*I.log(` Tone: ${N.tone}`);if(N.style)yield*I.log(` Style: ${N.style}`);yield*I.log(""),yield*I.info("Apply this persona when creating an agent:"),yield*I.log(` jazz agent create (then select "${N.name}" as the persona)`)})}function _NZ(){return h.gen(function*(){let I=yield*Nd,G=yield*oG,Z=yield*I.listPersonas();if(Z.length===0){yield*G.info("No personas found. Create one with: jazz persona create");return}yield*G.heading(`Personas (${Z.length})`),yield*G.log("");for(let b of Z){let W=op(b.id),l=W?L1.default.dim(" (built-in)"):L1.default.green(" (custom)"),Y=L1.default.bold(b.name)+l;if(yield*G.log(` ${Y}`),yield*G.log(` ${L1.default.dim(b.description)}`),b.tone||b.style){let N=[b.tone?`tone: ${b.tone}`:"",b.style?`style: ${b.style}`:""].filter(Boolean).join(", ");yield*G.log(` ${L1.default.dim(N)}`)}if(!W)yield*G.log(` ${L1.default.dim(`id: ${b.id}`)}`);yield*G.log("")}yield*G.info("Create a new persona: jazz persona create")})}function PNZ(I){return h.gen(function*(){let G=yield*Nd,Z=yield*oG,b=yield*G.getPersonaByIdentifier(I),W=op(b.id);if(yield*Z.heading(`Persona: ${b.name}`),yield*Z.log(""),yield*Z.log(` ID: ${b.id}`),yield*Z.log(` Name: ${b.name}`),yield*Z.log(` Type: ${W?"built-in":"custom"}`),yield*Z.log(` Description: ${b.description}`),b.tone)yield*Z.log(` Tone: ${b.tone}`);if(b.style)yield*Z.log(` Style: ${b.style}`);if(yield*Z.log(` Created: ${b.createdAt.toISOString()}`),yield*Z.log(` Updated: ${b.updatedAt.toISOString()}`),!W&&b.systemPrompt){yield*Z.log(""),yield*Z.log(L1.default.bold(" System Prompt:"));let l=b.systemPrompt.length>500?b.systemPrompt.substring(0,500)+"...":b.systemPrompt;for(let Y of l.split(`
|
|
7673
|
-
`))yield*Z.log(` ${L1.default.dim(Y)}`)}})}function $NZ(I){return h.gen(function*(){let G=yield*Nd,Z=yield*oG,b=yield*G.getPersonaByIdentifier(I);if(op(b.id)){yield*Z.error("Built-in personas cannot be edited. Create a custom persona instead.");return}yield*Z.heading(`Edit persona: ${b.name}`),yield*Z.info("Press Enter to keep the current value, or type a new value."),yield*Z.log("");let W=yield*Z.select("What would you like to edit?",{choices:[{name:"Name",value:"name"},{name:"Description",value:"description"},{name:"System Prompt",value:"systemPrompt"},{name:"Tone",value:"tone"},{name:"Style",value:"style"}]});if(!W)return;let l,Y,N,V,X,d=!1;if(W==="name"){let m=yield*Z.ask(`New name (current: ${b.name}):`,{defaultValue:b.name,validate:(Q)=>{if(!Q||Q.trim().length===0)return"Name cannot be empty";if(!/^[a-zA-Z0-9_-]+$/.test(Q))return"Only letters, numbers, underscores, and hyphens allowed";if(IT(Q)&&Q.toLowerCase()!==b.name.toLowerCase())return`"${Q}" is a built-in persona name`;return!0},simple:!0});if(m)l=m.trim(),d=!0}else if(W==="description"){let m=yield*Z.ask(`New description (current: ${b.description}):`,{defaultValue:b.description,simple:!0});if(m)Y=m.trim(),d=!0}else if(W==="systemPrompt"){yield*Z.log(L1.default.dim("Current system prompt:"));let m=b.systemPrompt.length>200?b.systemPrompt.substring(0,200)+"...":b.systemPrompt;yield*Z.log(L1.default.dim(m)),yield*Z.log("");let Q=yield*Z.ask("New system prompt:",{simple:!0});if(Q&&Q.trim().length>0)N=Q.trim(),d=!0}else if(W==="tone"){let Q=(yield*Z.ask(`New tone (current: ${b.tone||"none"}):`,{defaultValue:b.tone||"",simple:!0}))?.trim()||void 0;if(Q!==(b.tone||void 0))V=Q,d=!0}else if(W==="style"){let Q=(yield*Z.ask(`New style (current: ${b.style||"none"}):`,{defaultValue:b.style||"",simple:!0}))?.trim()||void 0;if(Q!==(b.style||void 0))X=Q,d=!0}if(!d){yield*Z.info("No changes made.");return}let F=yield*G.updatePersona(b.id,{...l!==void 0&&{name:l},...Y!==void 0&&{description:Y},...N!==void 0&&{systemPrompt:N},...V!==void 0&&{tone:V},...X!==void 0&&{style:X}});yield*Z.success(`Persona "${F.name}" updated successfully!`)})}function iNZ(I){return h.gen(function*(){let G=yield*Nd,Z=yield*oG,b=yield*G.getPersonaByIdentifier(I);if(op(b.id)){yield*Z.error("Built-in personas cannot be deleted.");return}if(!(yield*Z.confirm(`Delete persona "${b.name}"? This cannot be undone.`,!1))){yield*Z.info("Deletion cancelled.");return}yield*G.deletePersona(b.id),yield*Z.success(`Persona "${b.name}" deleted.`)})}var L1;var fNZ=g(()=>{zI();wz();qN();pUI();L1=zZ(h0(),1)});function cBI(I){return I.length>sNZ?`${I.slice(0,sNZ)}…`:I}function oNZ(I,G){if(typeof G==="string")return cBI(G);if(G instanceof Error)return{name:G.name,message:cBI(G.message),...G.stack!==void 0?{stack:cBI(G.stack)}:{}};return G}class tNZ{emitEventTypes;constructor(I=Wd,G=new Set){this.emitEventTypes=G}presentThinking(I,G){return h.void}presentCompletion(I){return h.void}get eventsActive(){return this.emitEventTypes.size>0}emitNdjson(I){process.stderr.write(`${JSON.stringify(I,oNZ)}
|
|
7673
|
+
`))yield*Z.log(` ${L1.default.dim(Y)}`)}})}function $NZ(I){return h.gen(function*(){let G=yield*Nd,Z=yield*oG,b=yield*G.getPersonaByIdentifier(I);if(op(b.id)){yield*Z.error("Built-in personas cannot be edited. Create a custom persona instead.");return}yield*Z.heading(`Edit persona: ${b.name}`),yield*Z.info("Press Enter to keep the current value, or type a new value."),yield*Z.log("");let W=yield*Z.select("What would you like to edit?",{choices:[{name:"Name",value:"name"},{name:"Description",value:"description"},{name:"System Prompt",value:"systemPrompt"},{name:"Tone",value:"tone"},{name:"Style",value:"style"}]});if(!W)return;let l,Y,N,V,X,d=!1;if(W==="name"){let m=yield*Z.ask(`New name (current: ${b.name}):`,{defaultValue:b.name,validate:(Q)=>{if(!Q||Q.trim().length===0)return"Name cannot be empty";if(!/^[a-zA-Z0-9_-]+$/.test(Q))return"Only letters, numbers, underscores, and hyphens allowed";if(IT(Q)&&Q.toLowerCase()!==b.name.toLowerCase())return`"${Q}" is a built-in persona name`;return!0},simple:!0});if(m)l=m.trim(),d=!0}else if(W==="description"){let m=yield*Z.ask(`New description (current: ${b.description}):`,{defaultValue:b.description,simple:!0});if(m)Y=m.trim(),d=!0}else if(W==="systemPrompt"){yield*Z.log(L1.default.dim("Current system prompt:"));let m=b.systemPrompt.length>200?b.systemPrompt.substring(0,200)+"...":b.systemPrompt;yield*Z.log(L1.default.dim(m)),yield*Z.log("");let Q=yield*Z.ask("New system prompt:",{simple:!0});if(Q&&Q.trim().length>0)N=Q.trim(),d=!0}else if(W==="tone"){let Q=(yield*Z.ask(`New tone (current: ${b.tone||"none"}):`,{defaultValue:b.tone||"",simple:!0}))?.trim()||void 0;if(Q!==(b.tone||void 0))V=Q,d=!0}else if(W==="style"){let Q=(yield*Z.ask(`New style (current: ${b.style||"none"}):`,{defaultValue:b.style||"",simple:!0}))?.trim()||void 0;if(Q!==(b.style||void 0))X=Q,d=!0}if(!d){yield*Z.info("No changes made.");return}let F=yield*G.updatePersona(b.id,{...l!==void 0&&{name:l},...Y!==void 0&&{description:Y},...N!==void 0&&{systemPrompt:N},...V!==void 0&&{tone:V},...X!==void 0&&{style:X}});yield*Z.success(`Persona "${F.name}" updated successfully!`)})}function iNZ(I){return h.gen(function*(){let G=yield*Nd,Z=yield*oG,b=yield*G.getPersonaByIdentifier(I);if(op(b.id)){yield*Z.error("Built-in personas cannot be deleted.");return}if(!(yield*Z.confirm(`Delete persona "${b.name}"? This cannot be undone.`,!1))){yield*Z.info("Deletion cancelled.");return}yield*G.deletePersona(b.id),yield*Z.success(`Persona "${b.name}" deleted.`)})}var L1;var fNZ=g(()=>{zI();wz();qN();pUI();L1=zZ(h0(),1)});function cBI(I){return I.length>sNZ?`${I.slice(0,sNZ)}…`:I}function oNZ(I,G){if(typeof G==="string")return cBI(G);if(G instanceof Error)return{name:G.name,message:cBI(G.message),...G.stack!==void 0?{stack:cBI(G.stack)}:{}};return G}class tNZ{emitEventTypes;constructor(I=Wd,G=new Set){this.emitEventTypes=G}presentThinking(I,G){return h.void}presentCompletion(I){return h.void}get eventsActive(){return this.emitEventTypes.size>0}emitsToolEventsViaRenderer(){return this.eventsActive}emitNdjson(I){process.stderr.write(`${JSON.stringify(I,oNZ)}
|
|
7674
7674
|
`)}presentWarning(I,G){return h.sync(()=>{if(this.eventsActive){this.emitNdjson({type:"warning",agentName:I,message:G});return}process.stderr.write(`⚠ ${I}: ${G}
|
|
7675
7675
|
`)})}presentAgentResponse(I,G){return h.void}renderMarkdown(I){return h.succeed(I)}formatToolArguments(I,G){if(!G||Object.keys(G).length===0)return"";return` ${JSON.stringify(G)}`}formatToolResult(I,G){return G}formatToolExecutionStart(I,G,Z){return h.succeed("")}formatToolExecutionComplete(I,G){return h.succeed("")}formatToolExecutionError(I,G){return h.succeed("")}formatToolsDetected(I,G,Z){return h.succeed("")}createStreamingRenderer(I){if(this.emitEventTypes.size===0){let b={handleEvent:(W)=>h.void,setInterruptHandler:(W)=>h.void,reset:()=>h.void,flush:()=>h.void};return h.succeed(b)}let G=this.emitEventTypes,Z={handleEvent:(b)=>h.sync(()=>{if(G.has(b.type))process.stderr.write(`${JSON.stringify(b,oNZ)}
|
|
7676
7676
|
`)}),setInterruptHandler:(b)=>h.void,reset:()=>h.void,flush:()=>h.void};return h.succeed(Z)}writeOutput(I){return h.sync(()=>{if(this.eventsActive){this.emitNdjson({type:"output",message:I});return}process.stderr.write(I)})}writeBlankLine(){return h.void}presentStatus(I,G){return h.sync(()=>{if(this.eventsActive){this.emitNdjson({type:"status",level:G,message:I});return}let Z={info:"ℹ",success:"✓",warning:"⚠",error:"✗",progress:"⏳"};process.stderr.write(`${Z[G]} ${I}
|