jazz-ai 0.13.1 → 0.13.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.
Files changed (2) hide show
  1. package/dist/main.js +7 -7
  2. 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 vl.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()}`,vl.env[I.envVar]);else this.emit(`optionEnv:${I.name()}`)}})}_parseOptionsImplied(){let I=new ARI(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),c=this.options.find((F)=>F.negate&&Y===F.attributeName()),X=this.options.find((F)=>!F.negate&&Y===F.attributeName());if(c&&(c.presetArg===void 0&&N===!1||c.presetArg!==void 0&&N===c.presetArg))return c;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=pRI(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",b=I.length,W=this.parent?` for '${this.name()}'`:"",l=I.join(", "),Y=`error: too many arguments${W}. Expected ${G} argument${Z} but got ${b}: ${l}.`;this.error(Y,{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=pRI(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 bs(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=ch.basename(I,ch.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(vl.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)")}}});var qEW;var bbG=g(()=>{Ws();ZbG();i6();CRI();LRI();qEW=new rz});var F0;var s6=g(()=>{F0={name:"jazz-ai",version:"0.13.1",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 && bun run tsc -p tsconfig.build.json","typecheck:evals":"tsc -p evals/tsconfig.json",evals:"bun run evals/cli.ts",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 scripts --cache","lint:fix":"bun eslint src scripts --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.29","@ai-sdk/anthropic":"^3.0.85","@ai-sdk/cerebras":"^2.0.57","@ai-sdk/deepseek":"^2.0.39","@ai-sdk/fireworks":"^2.0.57","@ai-sdk/google":"^3.0.83","@ai-sdk/groq":"^3.0.42","@ai-sdk/mcp":"^1.0.52","@ai-sdk/mistral":"^3.0.40","@ai-sdk/moonshotai":"^2.0.26","@ai-sdk/openai":"^3.0.73","@ai-sdk/openai-compatible":"^2.0.51","@ai-sdk/togetherai":"^2.0.56","@ai-sdk/xai":"^3.0.96","@effect/cluster":"^0.59.0","@effect/platform":"^0.96.2","@effect/platform-node":"^0.107.0","@effect/rpc":"^0.75.1","@effect/sql":"^0.51.1","@modelcontextprotocol/sdk":"^1.29.0","@openrouter/ai-sdk-provider":"^2.9.1","@perplexity-ai/perplexity_ai":"^0.33.0","@tavily/core":"^0.7.6","@toon-format/toon":"^2.3.0",ai:"^6.0.208",chalk:"^5.6.2","cli-highlight":"^2.1.11",commander:"^15.0.0","cron-parser":"^5.5.0",cronstrue:"^3.20.0",diff:"^9.0.0",effect:"^3.21.4","exa-js":"^2.14.0","fast-glob":"^3.3.3","gpt-tokenizer":"^3.4.0","gray-matter":"^4.0.3",ink:"^7.1.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","linkup-sdk":"^3.2.5",marked:"^18.0.5","marked-terminal":"^7.3.0","node-emoji":"^2.2.0","ollama-ai-provider-v2":"^3.6.0","parallel-web":"^1.1.0","pdf-parse":"^2.4.5",plist:"^5.0.0",react:"^19.2.7",semver:"^7.8.4","short-uuid":"^6.0.3","vercel-minimax-ai-provider":"^0.0.2","wrap-ansi":"^10.0.0",zod:"^4.4.3"},devDependencies:{"@eslint/js":"^10.0.1","@types/bun":"^1.3.14","@types/marked":"^6.0.0","@types/marked-terminal":"^6.1.1","@types/node":"^26.0.0","@types/react":"^19.2.17",eslint:"^10.5.0","eslint-config-prettier":"^10.1.8","eslint-plugin-import-x":"^4.16.2","eslint-plugin-n":"^18.1.0","eslint-plugin-prettier":"^5.5.6",prettier:"^3.8.4",typescript:"^6.0.3","typescript-eslint":"^8.61.1"},engines:{node:">=22.16.0",npm:">=10.0.0"},files:["dist/","vendor/terminal-notifier/","personas/","skills/","workflows/","README.md","LICENSE"]}});var WbG,lbG=()=>{return Object.assign((I)=>I,{[WbG]:WbG,option:(I)=>lI(I),either:(I)=>dG(I),is:(I)=>!0})};var YbG=g(()=>{WV();nZ();WbG=Symbol.for("effect/Brand/Refined")});var kRI,uRI,NbG;var VbG=g(()=>{lv();kRI=xI,uRI=nG,NbG=MI});var cbG,XbG,FbG;var dbG=g(()=>{Yf();cbG=eK,XbG=Z6,FbG=HtI});var gRI=(I,G)=>{switch(G._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(I);case"SymbolKeyword":return Object.getOwnPropertySymbols(I);case"Refinement":return gRI(I,G.from)}},o6=(I)=>{let G=!1,Z;return()=>{if(G)return Z;return Z=I(),G=!0,Z}},URI=(I)=>Array.isArray(I),mbG=(I)=>!Array.isArray(I),QbG=(I)=>`[${_J(I)}]`,Ns=(I)=>URI(I)?I.map(QbG).join(""):QbG(I);var r6=g(()=>{cY()});var yv=(I,G,Z,b)=>{let W=I;if(Z&&zl(Z))W+=`
67
+ `)}),this}_outputHelpIfRequested(I){let G=this._getHelpOption();if(G&&I.find((b)=>G.is(b)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}});var qEW;var bbG=g(()=>{Ws();ZbG();i6();CRI();LRI();qEW=new rz});var F0;var s6=g(()=>{F0={name:"jazz-ai",version:"0.13.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 && bun run tsc -p tsconfig.build.json","typecheck:evals":"tsc -p evals/tsconfig.json",evals:"bun run evals/cli.ts",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 scripts --cache","lint:fix":"bun eslint src scripts --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.29","@ai-sdk/anthropic":"^3.0.85","@ai-sdk/cerebras":"^2.0.57","@ai-sdk/deepseek":"^2.0.39","@ai-sdk/fireworks":"^2.0.57","@ai-sdk/google":"^3.0.83","@ai-sdk/groq":"^3.0.42","@ai-sdk/mcp":"^1.0.52","@ai-sdk/mistral":"^3.0.40","@ai-sdk/moonshotai":"^2.0.26","@ai-sdk/openai":"^3.0.73","@ai-sdk/openai-compatible":"^2.0.51","@ai-sdk/togetherai":"^2.0.56","@ai-sdk/xai":"^3.0.96","@effect/cluster":"^0.59.0","@effect/platform":"^0.96.2","@effect/platform-node":"^0.107.0","@effect/rpc":"^0.75.1","@effect/sql":"^0.51.1","@modelcontextprotocol/sdk":"^1.29.0","@openrouter/ai-sdk-provider":"^2.9.1","@perplexity-ai/perplexity_ai":"^0.33.0","@tavily/core":"^0.7.6","@toon-format/toon":"^2.3.0",ai:"^6.0.208",chalk:"^5.6.2","cli-highlight":"^2.1.11",commander:"^15.0.0","cron-parser":"^5.5.0",cronstrue:"^3.20.0",diff:"^9.0.0",effect:"^3.21.4","exa-js":"^2.14.0","fast-glob":"^3.3.3","gpt-tokenizer":"^3.4.0","gray-matter":"^4.0.3",ink:"^7.1.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","linkup-sdk":"^3.2.5",marked:"^18.0.5","marked-terminal":"^7.3.0","node-emoji":"^2.2.0","ollama-ai-provider-v2":"^3.6.0","parallel-web":"^1.1.0","pdf-parse":"^2.4.5",plist:"^5.0.0",react:"^19.2.7",semver:"^7.8.4","short-uuid":"^6.0.3","vercel-minimax-ai-provider":"^0.0.2","wrap-ansi":"^10.0.0",zod:"^4.4.3"},devDependencies:{"@eslint/js":"^10.0.1","@types/bun":"^1.3.14","@types/marked":"^6.0.0","@types/marked-terminal":"^6.1.1","@types/node":"^26.0.0","@types/react":"^19.2.17",eslint:"^10.5.0","eslint-config-prettier":"^10.1.8","eslint-plugin-import-x":"^4.16.2","eslint-plugin-n":"^18.1.0","eslint-plugin-prettier":"^5.5.6",prettier:"^3.8.4",typescript:"^6.0.3","typescript-eslint":"^8.61.1"},engines:{node:">=22.16.0",npm:">=10.0.0"},files:["dist/","vendor/terminal-notifier/","personas/","skills/","workflows/","README.md","LICENSE"]}});var WbG,lbG=()=>{return Object.assign((I)=>I,{[WbG]:WbG,option:(I)=>lI(I),either:(I)=>dG(I),is:(I)=>!0})};var YbG=g(()=>{WV();nZ();WbG=Symbol.for("effect/Brand/Refined")});var kRI,uRI,NbG;var VbG=g(()=>{lv();kRI=xI,uRI=nG,NbG=MI});var cbG,XbG,FbG;var dbG=g(()=>{Yf();cbG=eK,XbG=Z6,FbG=HtI});var gRI=(I,G)=>{switch(G._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(I);case"SymbolKeyword":return Object.getOwnPropertySymbols(I);case"Refinement":return gRI(I,G.from)}},o6=(I)=>{let G=!1,Z;return()=>{if(G)return Z;return Z=I(),G=!0,Z}},URI=(I)=>Array.isArray(I),mbG=(I)=>!Array.isArray(I),QbG=(I)=>`[${_J(I)}]`,Ns=(I)=>URI(I)?I.map(QbG).join(""):QbG(I);var r6=g(()=>{cY()});var yv=(I,G,Z,b)=>{let W=I;if(Z&&zl(Z))W+=`
68
68
  at path: ${Ns(Z)}`;if(G!==void 0)W+=`
69
69
  details: ${G}`;if(b)W+=`
70
70
  schema (${b._tag}): ${b}`;return W},BRI=(I,G,Z)=>yv("Unsupported schema or overlapping types",`cannot extend ${I} with ${G}`,Z),RbG=(I)=>yv("Unsupported key schema",void 0,void 0,I),HbG=(I)=>yv("Unsupported literal",`literal value: ${$F(I)}`),ORI=(I)=>yv("Duplicate index signature",`${I} index signature`),wbG,hbG,xRI=(I)=>yv("Duplicate property signature transformation",`Duplicate key ${$F(I)}`),cs=(I)=>yv("Duplicate property signature",`Duplicate key ${$F(I)}`);var MRI=g(()=>{XY();cY();r6();wbG=yv("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),hbG=yv("Invalid element","A required element cannot follow an optional element. ts(1257)")});var vbG;var EbG=g(()=>{vbG=Symbol.for("effect/SchemaId/DateFromSelf")});class tz{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 Xb(zH(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((I)=>I.toJSON()),annotations:pN(this.annotations)}}}class ez{literal;annotations;_tag="Literal";constructor(I,G={}){this.literal=I,this.annotations=G}toString(){return Xb(zH(this),()=>$F(this.literal))}toJSON(){return{_tag:this._tag,literal:TJ(this.literal)?String(this.literal):this.literal,annotations:pN(this.annotations)}}}class Fs{symbol;annotations;_tag="UniqueSymbol";constructor(I,G={}){this.symbol=I,this.annotations=G}toString(){return Xb(zH(this),()=>$F(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:pN(this.annotations)}}}class KbG{annotations;_tag="UndefinedKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class abG{annotations;_tag="VoidKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class jbG{annotations;_tag="NeverKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class DbG{annotations;_tag="UnknownKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class qbG{annotations;_tag="AnyKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class TbG{annotations;_tag="StringKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class _bG{annotations;_tag="NumberKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class PbG{annotations;_tag="BooleanKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class nbG{annotations;_tag="BigIntKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class $bG{annotations;_tag="SymbolKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class fbG{annotations;_tag="ObjectKeyword";constructor(I={}){this.annotations=I}toString(){return JR(this)}toJSON(){return{_tag:this._tag,annotations:pN(this.annotations)}}}class Ga{type;annotations;constructor(I,G={}){this.type=I,this.annotations=G}toJSON(){return{type:this.type.toJSON(),annotations:pN(this.annotations)}}toString(){return String(this.type)}}class ws{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(hbG)}toString(){return Xb(zH(this),()=>B6Z(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((I)=>I.toJSON()),rest:this.rest.map((I)=>I.toJSON()),isReadonly:this.isReadonly,annotations:pN(this.annotations)}}}class Ik{type;isReadonly;parameter;constructor(I,G,Z){if(this.type=G,this.isReadonly=Z,obG(I))this.parameter=I;else throw Error(wbG)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class hR{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(cs(Y));b[Y]=null}let W={string:!1,symbol:!1};for(let l=0;l<G.length;l++){let Y=F1I(G[l].parameter);if(Rs(Y)){if(W.string)throw Error(ORI("string"));W.string=!0}else if(ibG(Y)){if(W.symbol)throw Error(ORI("symbol"));W.symbol=!0}}this.propertySignatures=I,this.indexSignatures=G}toString(){return Xb(zH(this),()=>O6Z(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((I)=>I.toJSON()),indexSignatures:this.indexSignatures.map((I)=>I.toJSON()),annotations:pN(this.annotations)}}}class d0{types;annotations;static make=(I,G)=>{return hs(I)?new d0(I,G):I.length===1?I[0]:Qs};static unify=(I,G)=>{return d0.make(K6Z(rbG(I)),G)};_tag="Union";constructor(I,G={}){this.types=I,this.annotations=G}toString(){return Xb(zH(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((I)=>I.toJSON()),annotations:pN(this.annotations)}}}class Gk{f;annotations;_tag="Suspend";constructor(I,G={}){this.f=I,this.annotations=G,this.f=o6(I)}toString(){return zH(this).pipe(BX(()=>yN(I9(this.f)(),(I)=>zH(I))),Xb(()=>"<suspended schema>"))}toJSON(){let I=this.f(),G=KRI.get(I);if(G)return G;return KRI.set(I,{_tag:this._tag}),G={_tag:this._tag,ast:I.toJSON(),annotations:pN(this.annotations)},KRI.set(I,G),G}}class Zk{from;filter;annotations;_tag="Refinement";constructor(I,G,Z={}){this.from=I,this.filter=G,this.annotations=Z}toString(){return Ia(this).pipe(Xb(()=>TG(YWG(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(I)=>Cv(this.from)?String(this.from)+" & "+I:I})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:pN(this.annotations)}}}class Av{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 Xb(zH(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:pN(this.annotations)}}}class Es{decode;encode;_tag="FinalTransformation";constructor(I,G){this.decode=I,this.encode=G}}class IWG{_tag="ComposeTransformation"}class N1I{from;to;decode;encode;constructor(I,G,Z,b){this.from=I,this.to=G,this.decode=Z,this.encode=b}}class Za{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(xRI(W));G[W]=!0;let l=b.to;if(Z[l])throw Error(xRI(l));Z[l]=!0}}}function yQ(I,G){let Z=!1,b=G9(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 T6Z(I){return TG(kbG(I),{onNone:()=>"",onSome:(G)=>G.map((Z)=>` & Brand<${$F(Z)}>`).join("")})}var CbG,AbG,LbG,jRI,Xs,t6,IF,yy,Xh,DRI,qRI,SRI,TRI,_RI,PRI,pbG,nRI,$RI,iRI,fRI,sRI,e6,zbG,Q0,kbG,ubG,gbG,oRI,rRI,Ia,tRI,UbG,BbG,ObG,xbG,MbG,eRI,L6Z,I1I=(I)=>yNI(L6Z(I),(G)=>G===!0),G1I,p6Z,z6Z=(I)=>BX(p6Z(I),()=>Ia(I)),Fh=(I)=>(G)=>G._tag===I,Cy,ds,k6Z,Qs,Z1I,SbG,ms,Rs,Hs,b1I,W1I,l1I,u6Z,g6Z,ibG,U6Z,Ay,sbG=(I)=>I.map((G)=>G.type),B6Z=(I)=>{let G=I.elements.map(String).join(", ");return PKI(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}>`}})},D2,obG=(I)=>{switch(I._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return obG(I.from)}return!1},ybG=(I)=>I.map(String).join("; "),O6Z=(I)=>{if(I.propertySignatures.length>0){let G=I.propertySignatures.map(String).join("; ");if(I.indexSignatures.length>0)return`{ ${G}; ${ybG(I.indexSignatures)} }`;else return`{ ${G} }`}else if(I.indexSignatures.length>0)return`{ ${ybG(I.indexSignatures)} }`;else return"{}"},Y1I,x6Z,M6Z,rbG=(I)=>Z9(I,(G)=>Js(G)?rbG(G.types):[G]),K6Z=(I)=>{let G=x6Z(I),Z=[],b={},W=[];for(let l of G)switch(l._tag){case"NeverKeyword":break;case"AnyKeyword":return[SbG];case"UnknownKeyword":return[Z1I];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=M6Z[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},tbG=(I,G)=>I.map(G),hs=(I)=>I.length>1,Js,KRI,Cv,vs,ebG,a6Z=(I)=>(G)=>G._tag===I,GWG,V1I,ys=(I,G)=>{let Z=Object.getOwnPropertyDescriptors(I),b={...I.annotations};delete b[t6];let W={...b,...G},l=eRI(I);if(tG(l))W[e6]=ys(l.value,G);return Z.annotations.value=W,Object.create(Object.getPrototypeOf(I),Z)},j6Z="[\\s\\S]*?",D6Z="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",ZWG=(I,G)=>{switch(I._tag){case"Literal":return zp(String(I.literal));case"StringKeyword":return j6Z;case"NumberKeyword":return D6Z;case"TemplateLiteral":return bWG(I,G,!1);case"Union":return I.types.map((Z)=>ZWG(Z,G)).join("|")}},q6Z=(I,G,Z,b)=>{if(Js(I)){if(Z&&!b)return`(?:${G})`}else if(!Z||!b)return G;return`(${G})`},bWG=(I,G,Z)=>{let b="";if(I.head!==""){let W=zp(I.head);b+=G&&Z?`(${W})`:W}for(let W of I.spans){let l=ZWG(W.type,G);if(b+=q6Z(W.type,l,G,Z),W.literal!==""){let Y=zp(W.literal);b+=G&&Z?`(${Y})`:Y}}return b},WWG=(I)=>new RegExp(`^${bWG(I,!1,!0)}$`),c1I=(I,G)=>{let Z=[],b=[],W=(l)=>{switch(l._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":b.push(new Ik(l,G,!0));break;case"Literal":if(z2(l.literal)||a0(l.literal))Z.push(new D2(l.literal,G,!1,!0));else throw Error(HbG(l.literal));break;case"Enums":{for(let[Y,N]of l.enums)Z.push(new D2(N,G,!1,!0));break}case"UniqueSymbol":Z.push(new D2(l.symbol,G,!1,!0));break;case"Union":l.types.forEach(W);break;default:throw Error(RbG(l))}};return W(I),{propertySignatures:Z,indexSignatures:b}},X1I=(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},lWG=(I)=>(G)=>{let Z={...G.annotations};for(let b of I)delete Z[b];return Z},S6Z,_N=(I)=>{switch(I._tag){case"Declaration":{let G=yQ(I.typeParameters,_N);return G===I.typeParameters?I:new tz(G,I.decodeUnknown,I.encodeUnknown,I.annotations)}case"TupleType":{let G=yQ(I.elements,(W)=>{let l=_N(W.type);return l===W.type?W:new Ay(l,W.isOptional)}),Z=sbG(I.rest),b=yQ(Z,_N);return G===I.elements&&b===Z?I:new ws(G,b.map((W)=>new Ga(W)),I.isReadonly,I.annotations)}case"TypeLiteral":{let G=yQ(I.propertySignatures,(b)=>{let W=_N(b.type);return W===b.type?b:new D2(b.name,W,b.isOptional,b.isReadonly)}),Z=yQ(I.indexSignatures,(b)=>{let W=_N(b.type);return W===b.type?b:new Ik(b.parameter,W,b.isReadonly)});return G===I.propertySignatures&&Z===I.indexSignatures?I:new hR(G,Z,I.annotations)}case"Union":{let G=yQ(I.types,_N);return G===I.types?I:d0.make(G,I.annotations)}case"Suspend":return new Gk(()=>_N(I.f()),I.annotations);case"Refinement":{let G=_N(I.from);return G===I.from?I:new Zk(G,I.filter,I.annotations)}case"Transformation":{let G=S6Z(I);return _N(G!==void 0?ys(I.to,G):I.to)}}return I},aRI=(I)=>{switch(I._tag){case"Transformation":return I.from;case"Refinement":return aRI(I.from);case"Suspend":return aRI(I.f())}},pH=(I,G)=>{switch(I._tag){case"Declaration":{let Z=yQ(I.typeParameters,(b)=>pH(b,G));return Z===I.typeParameters?I:new tz(Z,I.decodeUnknown,I.encodeUnknown)}case"TupleType":{let Z=yQ(I.elements,(l)=>{let Y=pH(l.type,G);return Y===l.type?l:new Ay(Y,l.isOptional)}),b=sbG(I.rest),W=yQ(b,(l)=>pH(l,G));return Z===I.elements&&W===b?I:new ws(Z,W.map((l)=>new Ga(l)),I.isReadonly)}case"TypeLiteral":{let Z=yQ(I.propertySignatures,(W)=>{let l=pH(W.type,G);return l===W.type?W:new D2(W.name,l,W.isOptional,W.isReadonly)}),b=yQ(I.indexSignatures,(W)=>{let l=pH(W.type,G);return l===W.type?W:new Ik(W.parameter,l,W.isReadonly)});return Z===I.propertySignatures&&b===I.indexSignatures?I:new hR(Z,b)}case"Union":{let Z=yQ(I.types,(b)=>pH(b,G));return Z===I.types?I:d0.make(Z)}case"Suspend":{let Z=void 0,b=z6Z(I);if(tG(b)){let W=G?"Bound":"";Z={[G1I]:`${b.value}Encoded${W}`}}return new Gk(()=>pH(I.f(),G),Z)}case"Refinement":{let Z=pH(I.from,G);if(G){if(Z===I.from)return I;if(aRI(I.from)===void 0&&I1I(I))return new Zk(Z,I.filter,I.annotations);return Z}else return Z}case"Transformation":return pH(I.from,G)}return I},ba=(I)=>pH(I,!1),pN=(I)=>{let G={};for(let Z of Object.getOwnPropertySymbols(I))G[String(Z)]=I[Z];return G},F1I=(I)=>{switch(I._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return I;case"Refinement":return F1I(I.from)}},JR=(I)=>Xb(zH(I),()=>I._tag),YWG=(I)=>oRI(I).pipe(BX(()=>tRI(I)),BX(()=>rRI(I)),xW((G)=>G+T6Z(I))),zH=(I)=>BX(Ia(I),()=>YWG(I));var d1I=g(()=>{XY();sI();cY();MRI();r6();g4();nZ();PJ();qZ();TVI();CbG=Symbol.for("effect/annotation/TypeConstructor"),AbG=Symbol.for("effect/annotation/Brand"),LbG=Symbol.for("effect/annotation/SchemaId"),jRI=Symbol.for("effect/annotation/Message"),Xs=Symbol.for("effect/annotation/MissingMessage"),t6=Symbol.for("effect/annotation/Identifier"),IF=Symbol.for("effect/annotation/Title"),yy=Symbol.for("effect/annotation/AutoTitle"),Xh=Symbol.for("effect/annotation/Description"),DRI=Symbol.for("effect/annotation/Examples"),qRI=Symbol.for("effect/annotation/Default"),SRI=Symbol.for("effect/annotation/JSONSchema"),TRI=Symbol.for("effect/annotation/Arbitrary"),_RI=Symbol.for("effect/annotation/Pretty"),PRI=Symbol.for("effect/annotation/Equivalence"),pbG=Symbol.for("effect/annotation/Documentation"),nRI=Symbol.for("effect/annotation/Concurrency"),$RI=Symbol.for("effect/annotation/Batching"),iRI=Symbol.for("effect/annotation/ParseIssueTitle"),fRI=Symbol.for("effect/annotation/ParseOptions"),sRI=Symbol.for("effect/annotation/DecodingFallback"),e6=Symbol.for("effect/annotation/Surrogate"),zbG=Symbol.for("effect/annotation/StableFilter"),Q0=z(2,(I,G)=>Object.prototype.hasOwnProperty.call(I.annotations,G)?lI(I.annotations[G]):FI()),kbG=Q0(AbG),ubG=Q0(jRI),gbG=Q0(Xs),oRI=Q0(IF),rRI=Q0(yy),Ia=Q0(t6),tRI=Q0(Xh),UbG=Q0(nRI),BbG=Q0($RI),ObG=Q0(iRI),xbG=Q0(fRI),MbG=Q0(sRI),eRI=Q0(e6),L6Z=Q0(zbG),G1I=Symbol.for("effect/annotation/JSONIdentifier"),p6Z=Q0(G1I);Cy=Fh("Literal");ds=new KbG({[IF]:"undefined"});k6Z=new abG({[IF]:"void"});Qs=new jbG({[IF]:"never"});Z1I=new DbG({[IF]:"unknown"});SbG=new qbG({[IF]:"any"});ms=new TbG({[IF]:"string",[Xh]:"a string"}),Rs=Fh("StringKeyword");Hs=new _bG({[IF]:"number",[Xh]:"a number"}),b1I=Fh("NumberKeyword");W1I=new PbG({[IF]:"boolean",[Xh]:"a boolean"}),l1I=Fh("BooleanKeyword");u6Z=new nbG({[IF]:"bigint",[Xh]:"a bigint"});g6Z=new $bG({[IF]:"symbol",[Xh]:"a symbol"}),ibG=Fh("SymbolKeyword");U6Z=new fbG({[IF]:"object",[Xh]:"an object in the TypeScript meaning, i.e. the `object` type"});Ay=class Ay extends Ga{isOptional;constructor(I,G,Z={}){super(I,Z);this.isOptional=G}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:pN(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};D2=class D2 extends Ay{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:pN(this.annotations)}}};Y1I=Fh("TypeLiteral"),x6Z=Vc($1(M2,(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})),M6Z={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};Js=Fh("Union"),KRI=cZ(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);Cv=Fh("Refinement"),vs={};ebG=Fh("Transformation");GWG=new IWG;V1I=a6Z("TypeLiteralTransformation"),S6Z=X1I([DRI,qRI,SRI,TRI,_RI,PRI])});class hV{path;actual;issue;_tag="Pointer";constructor(I,G,Z){this.path=I,this.actual=G,this.issue=Z}}class R1I{actual;message;_tag="Unexpected";constructor(I,G){this.actual=I,this.message=G}}class bk{ast;message;_tag="Missing";actual=void 0;constructor(I,G){this.ast=I,this.message=G}}class zN{ast;actual;issues;output;_tag="Composite";constructor(I,G,Z,b){this.ast=I,this.actual=G,this.issues=Z,this.output=b}}class As{ast;actual;kind;issue;_tag="Refinement";constructor(I,G,Z,b){this.ast=I,this.actual=G,this.kind=Z,this.issue=b}}class Ls{ast;actual;kind;issue;_tag="Transformation";constructor(I,G,Z,b){this.ast=I,this.actual=G,this.kind=Z,this.issue=b}}class Vd{ast;actual;message;_tag="Type";constructor(I,G,Z){this.ast=I,this.actual=G,this.message=Z}}class H1I{ast;actual;message;_tag="Forbidden";constructor(I,G,Z){this.ast=I,this.actual=G,this.message=Z}}function vR(I){return I.sort(s6Z).map((G)=>G[1])}function GaZ(I){return tRI(I).pipe(BX(()=>oRI(I)),BX(()=>rRI(I)),BX(()=>Ia(I)),Xb(()=>`{ ${I.from} | filter }`))}function ZaZ(I){if(I.message!==void 0)return I.message;return`Expected ${Cv(I.ast)?GaZ(I.ast):String(I.ast)}, actual ${$F(I.actual)}`}var VWG,FWG,dWG=(I)=>new FWG({issue:I}),lk,h1I,GF,dh,ZF,ps,QWG,zs=(I,G)=>{if(G===void 0||a0(G))return I;if(I===void 0)return G;return{...I,...G}},_6Z=(I,G,Z)=>{let b=nV(I,G);return(W,l)=>b(W,zs(Z,l))},P6Z=(I,G,Z)=>{let b=_6Z(I,G,Z);return(W,l)=>_L(b(W,l),dWG)},n6Z=(I,G,Z)=>{let b=nV(I,G);return(W,l)=>b(W,{...zs(Z,l),isEffectAllowed:!0})},mWG=(I,G)=>n6Z(I.ast,!1,G),ks=(I,G)=>P6Z(_N(I.ast),!0,G),RWG=(I,G)=>{let Z=nV(_N(I.ast),!0);return(b,W)=>$c(Z(b,{exact:!0,...zs(G,W)}))},$6Z,i6Z,nV=(I,G)=>{let Z=G?$6Z:i6Z,b=Z.get(I);if(b)return b;let W=f6Z(I,G),l=xbG(I),Y=tG(l)?(X,F)=>W(X,zs(F,l.value)):W,N=MbG(I),c=G&&tG(N)?(X,F)=>la(QWG(Y(X,F),N.value),I,X,F):Y;return Z.set(I,c),c},Q1I=(I)=>jY(UbG(I)),m1I=(I)=>jY(BbG(I)),f6Z=(I,G)=>{switch(I._tag){case"Refinement":if(G){let Z=nV(I.from,!0);return(b,W)=>{W=W??vs;let l=W?.errors==="all",Y=dh(QWG(Z(b,W),(N)=>{let c=new As(I,b,"From",N);if(l&&I1I(I)&&vWG(N))return TG(I.filter(b,W,I),{onNone:()=>QG(c),onSome:(X)=>QG(new zN(I,b,[c,new As(I,b,"Predicate",X)]))});return QG(c)}),(N)=>TG(I.filter(N,W,I),{onNone:()=>dG(N),onSome:(c)=>QG(new As(I,b,"Predicate",c))}));return la(Y,I,b,W)}}else{let Z=nV(_N(I),!0),b=nV(wWG(I.from),!1);return(W,l)=>la(dh(Z(W,l),(Y)=>b(Y,l)),I,W,l)}case"Transformation":{let Z=o6Z(I.transformation,G),b=G?nV(I.from,!0):nV(I.to,!1),W=G?nV(I.to,!0):nV(I.from,!1);return(l,Y)=>la(dh(ps(b(l,Y),(N)=>new Ls(I,l,G?"Encoded":"Type",N)),(N)=>dh(ps(Z(N,Y??vs,I,l),(c)=>new Ls(I,l,"Transformation",c)),(c)=>ps(W(c,Y),(X)=>new Ls(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)=>la(Z(b,W??vs,I),I,b,W)}case"Literal":return Nd(I,(Z)=>Z===I.literal);case"UniqueSymbol":return Nd(I,(Z)=>Z===I.symbol);case"UndefinedKeyword":return Nd(I,ZKI);case"NeverKeyword":return Nd(I,bKI);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return dG;case"StringKeyword":return Nd(I,z2);case"NumberKeyword":return Nd(I,a0);case"BooleanKeyword":return Nd(I,_F);case"BigIntKeyword":return Nd(I,TJ);case"SymbolKeyword":return Nd(I,T3);case"ObjectKeyword":return Nd(I,MV);case"Enums":return Nd(I,(Z)=>I.enums.some(([b,W])=>W===Z));case"TemplateLiteral":{let Z=WWG(I);return Nd(I,(b)=>z2(b)&&Z.test(b))}case"TupleType":{let Z=I.elements.map((X)=>nV(X.type,G)),b=I.rest.map((X)=>nV(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,F)=>F).join(" | "):"never",N=Q1I(I),c=m1I(I);return(X,F)=>{if(!pNI(X))return QG(new Vd(I,X));let d=F?.errors==="all",Q=[],m=0,R=[],H=X.length;for(let J=H;J<=l-1;J++){let y=new hV(J,X,new bk(W[J-H]));if(d){Q.push([m++,y]);continue}else return QG(new zN(I,X,y,R))}if(I.rest.length===0)for(let J=I.elements.length;J<=H-1;J++){let y=new hV(J,X,new R1I(X[J],`is unexpected, expected: ${Y}`));if(d){Q.push([m++,y]);continue}else return QG(new zN(I,X,y,R))}let h=0,E=void 0;for(;h<Z.length;h++)if(H<h+1){if(I.elements[h].isOptional)continue}else{let J=Z[h],y=J(X[h],F);if(GF(y)){if(FW(y)){let v=new hV(h,X,y.left);if(d){Q.push([m++,v]);continue}else return QG(new zN(I,X,v,vR(R)))}R.push([m++,y.right])}else{let v=m++,A=h;if(!E)E=[];E.push(({es:k,output:L})=>jI(e4(y),(p)=>{if(FW(p)){let x=new hV(A,X,p.left);if(d)return k.push([v,x]),AZ;else return QG(new zN(I,X,x,vR(L)))}return L.push([v,p.right]),AZ}))}}if(zl(b)){let[J,...y]=b;for(;h<H-y.length;h++){let v=J(X[h],F);if(GF(v))if(FW(v)){let A=new hV(h,X,v.left);if(d){Q.push([m++,A]);continue}else return QG(new zN(I,X,A,vR(R)))}else R.push([m++,v.right]);else{let A=m++,k=h;if(!E)E=[];E.push(({es:L,output:p})=>jI(e4(v),(x)=>{if(FW(x)){let U=new hV(k,X,x.left);if(d)return L.push([A,U]),AZ;else return QG(new zN(I,X,U,vR(p)))}else return p.push([A,x.right]),AZ}))}}for(let v=0;v<y.length;v++){let A=h+v;if(H<A+1)continue;else{let k=y[v](X[A],F);if(GF(k)){if(FW(k)){let L=new hV(A,X,k.left);if(d){Q.push([m++,L]);continue}else return QG(new zN(I,X,L,vR(R)))}R.push([m++,k.right])}else{let L=m++;if(!E)E=[];E.push(({es:p,output:x})=>jI(e4(k),(U)=>{if(FW(U)){let O=new hV(A,X,U.left);if(d)return p.push([L,O]),AZ;else return QG(new zN(I,X,O,vR(x)))}return x.push([L,U.right]),AZ}))}}}}let C=({es:J,output:y})=>f1(J)?QG(new zN(I,X,vR(J),vR(y))):dG(vR(y));if(E&&E.length>0){let J=E;return ub(()=>{let y={es:nL(Q),output:nL(R)};return jI(j2(J,(v)=>v(y),{concurrency:N,batching:c,discard:!0}),()=>C(y))})}return C({output:R,es:Q})}}case"TypeLiteral":{if(I.propertySignatures.length===0&&I.indexSignatures.length===0)return Nd(I,WKI);let Z=[],b={},W=[];for(let F of I.propertySignatures)Z.push([nV(F.type,G),F]),b[F.name]=null,W.push(F.name);let l=I.indexSignatures.map((F)=>[nV(F.parameter,G),nV(F.type,G),F.parameter]),Y=d0.make(I.indexSignatures.map((F)=>F.parameter).concat(W.map((F)=>T3(F)?new Fs(F):new ez(F)))),N=nV(Y,G),c=Q1I(I),X=m1I(I);return(F,d)=>{if(!oYI(F))return QG(new Vd(I,F));let Q=d?.errors==="all",m=[],R=0,H=d?.onExcessProperty==="error",h=d?.onExcessProperty==="preserve",E={},C;if(H||h){C=Reflect.ownKeys(F);for(let A of C){let k=N(A,d);if(GF(k)&&FW(k))if(H){let L=new hV(A,F,new R1I(F[A],`is unexpected, expected: ${String(Y)}`));if(Q){m.push([R++,L]);continue}else return QG(new zN(I,F,L,E))}else E[A]=F[A]}}let J=void 0,y=d?.exact===!0;for(let A=0;A<Z.length;A++){let k=Z[A][1],L=k.name,p=Object.prototype.hasOwnProperty.call(F,L);if(!p){if(k.isOptional)continue;else if(y){let O=new hV(L,F,new bk(k));if(Q){m.push([R++,O]);continue}else return QG(new zN(I,F,O,E))}}let x=Z[A][0],U=x(F[L],d);if(GF(U)){if(FW(U)){let O=new hV(L,F,p?U.left:new bk(k));if(Q){m.push([R++,O]);continue}else return QG(new zN(I,F,O,E))}E[L]=U.right}else{let O=R++,D=L;if(!J)J=[];J.push(({es:K,output:a})=>jI(e4(U),(j)=>{if(FW(j)){let r=new hV(D,F,p?j.left:new bk(k));if(Q)return K.push([O,r]),AZ;else return QG(new zN(I,F,r,a))}return a[D]=j.right,AZ}))}}for(let A=0;A<l.length;A++){let k=l[A],L=k[0],p=k[1],x=gRI(F,k[2]);for(let U of x){let O=L(U,d);if(GF(O)&&$c(O)){let D=p(F[U],d);if(GF(D)){if(FW(D)){let K=new hV(U,F,D.left);if(Q){m.push([R++,K]);continue}else return QG(new zN(I,F,K,E))}else if(!Object.prototype.hasOwnProperty.call(b,U))E[U]=D.right}else{let K=R++,a=U;if(!J)J=[];J.push(({es:j,output:r})=>jI(e4(D),(T)=>{if(FW(T)){let i=new hV(a,F,T.left);if(Q)return j.push([K,i]),AZ;else return QG(new zN(I,F,i,r))}else{if(!Object.prototype.hasOwnProperty.call(b,U))r[U]=T.right;return AZ}}))}}}}let v=({es:A,output:k})=>{if(f1(A))return QG(new zN(I,F,vR(A),k));if(d?.propertyOrder==="original"){let L=C||Reflect.ownKeys(F);for(let x of W)if(L.indexOf(x)===-1)L.push(x);let p={};for(let x of L)if(Object.prototype.hasOwnProperty.call(k,x))p[x]=k[x];return dG(p)}return dG(k)};if(J&&J.length>0){let A=J;return ub(()=>{let k={es:nL(m),output:Object.assign({},E)};return jI(j2(A,(L)=>L(k),{concurrency:c,batching:X,discard:!0}),()=>v(k))})}return v({es:m,output:E})}}case"Union":{let Z=HWG(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],nV(I.types[X],G));let N=Q1I(I)??1,c=m1I(I);return(X,F)=>{let d=[],Q=0,m=[];if(W>0)if(qO(X))for(let h=0;h<W;h++){let E=b[h],C=Z.keys[E].buckets;if(Object.prototype.hasOwnProperty.call(X,E)){let J=String(X[E]);if(Object.prototype.hasOwnProperty.call(C,J))m=m.concat(C[J]);else{let{candidates:y,literals:v}=Z.keys[E],A=d0.make(v),k=y.length===l?new hR([new D2(E,A,!1,!0)],[]):d0.make(y);d.push([Q++,new zN(k,X,new hV(E,X,new Vd(A,X[E])))])}}else{let{candidates:J,literals:y}=Z.keys[E],v=new D2(E,d0.make(y),!1,!0),A=J.length===l?new hR([v],[]):d0.make(J);d.push([Q++,new zN(A,X,new hV(E,X,new bk(v)))])}}else{let h=Z.candidates.length===l?I:d0.make(Z.candidates);d.push([Q++,new Vd(h,X)])}if(Z.otherwise.length>0)m=m.concat(Z.otherwise);let R=void 0;for(let h=0;h<m.length;h++){let E=m[h],C=Y.get(E)(X,F);if(GF(C)&&(!R||R.length===0))if($c(C))return C;else d.push([Q++,C.left]);else{let J=Q++;if(!R)R=[];R.push((y)=>ub(()=>{if("finalResult"in y)return AZ;else return jI(e4(C),(v)=>{if($c(v))y.finalResult=v;else y.es.push([J,v.left]);return AZ})}))}}let H=(h)=>f1(h)?h.length===1&&h[0][1]._tag==="Type"?QG(h[0][1]):QG(new zN(I,X,vR(h))):QG(new Vd(I,X));if(R&&R.length>0){let h=R;return ub(()=>{let E={es:nL(d)};return jI(j2(h,(C)=>C(E),{concurrency:N,batching:c,discard:!0}),()=>{if("finalResult"in E)return E.finalResult;return H(E.es)})})}return H(d)}}case"Suspend":{let Z=o6(()=>nV(I.f(),G));return(b,W)=>Z()(b,W)}}},Nd=(I,G)=>(Z)=>G(Z)?dG(Z):QG(new Vd(I,Z)),Wa=(I,G)=>{switch(I._tag){case"Declaration":{let Z=eRI(I);if(tG(Z))return Wa(Z.value,G);break}case"TypeLiteral":{let Z=[];for(let b=0;b<I.propertySignatures.length;b++){let W=I.propertySignatures[b],l=G?ba(W.type):_N(W.type);if(Cy(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?ba(W.type):_N(W.type);if(Cy(l)&&!W.isOptional)Z.push([b,l])}return Z}case"Refinement":return Wa(I.from,G);case"Suspend":return Wa(I.f(),G);case"Transformation":return Wa(G?I.from:I.to,G)}return[]},HWG=(I,G)=>{let Z={},b=[],W=[];for(let l=0;l<I.length;l++){let Y=I[l],N=Wa(Y,G);if(N.length>0){W.push(Y);for(let c=0;c<N.length;c++){let[X,F]=N[c],d=String(F.literal);Z[X]=Z[X]||{buckets:{},literals:[],candidates:[]};let Q=Z[X].buckets;if(Object.prototype.hasOwnProperty.call(Q,d)){if(c<N.length-1)continue;Q[d].push(Y),Z[X].literals.push(F),Z[X].candidates.push(Y)}else{Q[d]=[Y],Z[X].literals.push(F),Z[X].candidates.push(Y);break}}}else b.push(Y)}return{keys:Z,otherwise:b,candidates:W}},wWG=(I)=>Cv(I)?wWG(I.from):I,la=(I,G,Z,b)=>{if(b?.isEffectAllowed===!0)return I;if(GF(I))return I;let W=new RM,l=uK(I,{scheduler:W});W.flush();let Y=l.unsafePoll();if(Y){if(VQ(Y))return dG(Y.value);let N=Y.cause;if(zVI(N))return QG(N.error);return QG(new H1I(G,Z,UVI(N)))}return QG(new H1I(G,Z,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},s6Z=([I],[G])=>I>G?1:I<G?-1:0,o6Z=(I,G)=>{switch(I._tag){case"FinalTransformation":return G?I.decode:I.encode;case"ComposeTransformation":return dG;case"TypeLiteralTransformation":return(Z)=>{let b=dG(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=ZF(b,(X)=>{let F=N(Object.prototype.hasOwnProperty.call(X,l)?lI(X[l]):FI());if(delete X[l],tG(F))X[Y]=F.value;return X})}return b}}},GX=(I,G=[])=>({value:I,forest:G}),Ya,r6Z=(I)=>I.value+hWG(`
@@ -6822,7 +6822,7 @@ Or update it in the interactive wizard: jazz wizard -> Update configuration`;W=n
6822
6822
  `)}function l(c){let X=fZ(c.path),F=fZ(c.content),d=c.truncated===!0,Q=[];if(X)Q.push(X);if(F){if(Q.length>0)Q.push("");Q.push(F)}if(d)Q.push(""),Q.push("[truncated]");return Q.join(`
6823
6823
  `)}function Y(c){let X=fZ(c.stdout),F=fZ(c.stderr),d=fZ(c.exitCode);if(!X&&!F)return d?`exitCode: ${d}`:"";let Q=[];if(X)Q.push(X);if(F){if(X)Q.push("");Q.push("stderr:"),Q.push(F)}if(d&&d!=="0")Q.push(""),Q.push(`exitCode: ${d}`);return Q.join(`
6824
6824
  `)}function N(c){return JSON.stringify(c,null,2)}try{let c=JSON.parse(G);if(I==="load_skill"&&typeof c==="string")return AVb(c);if(I==="load_skill_section"&&typeof c==="string")return LVb(c);if(typeof c==="string"||typeof c==="number"||typeof c==="boolean")return Z(String(c));if(c===null)return"null";if(Array.isArray(c))return Z(JSON.stringify(c,null,2));let X=c;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` ${bI.dim("(loaded)")}`;return` ${bI.red(`(error: ${fZ(X.error||X.result)})`)}`}case"spawn_subagent":{if(X.success===!0)return` ${bI.dim("(sub-agent completed)")}`;return` ${bI.red(`(error: ${fZ(X.error||X.result)})`)}`}case"git_status":{let F=fZ(X.branch),d=Array.isArray(X.modified)?X.modified.length:0,Q=Array.isArray(X.staged)?X.staged.length:0,m=[];if(F)m.push(bI.cyan(F));if(d>0)m.push(bI.yellow(`${d} modified`));if(Q>0)m.push(bI.green(`${Q} staged`));return m.length>0?` ${bI.dim("(")}${m.join(bI.dim(", "))}${bI.dim(")")}`:""}case"git_log":{let F=X.commits||X,d=Array.isArray(F)?F.length:0;return d>0?` ${bI.dim(`(${d} commit${d!==1?"s":""})`)}`:""}case"git_diff":{let F=[],d=X.paths,Q=X.nameOnly===!0;if(Array.isArray(d)&&d.length>0){if(F.push(bI.cyan(`${d.length} file${d.length!==1?"s":""}`)),Q)F.push(bI.dim("(names only)"))}if(X.truncated===!0)F.push(bI.yellow("truncated"));if(X.hasChanges===!1&&!Q)F.push(bI.dim("no diff"));return F.length>0?` ${bI.dim("(")}${F.join(bI.dim(", "))}${bI.dim(")")}`:""}case"grep":{let F=X.matches||X,d=Array.isArray(F)?F.length:0;return d>0?` ${bI.dim(`(${d} match${d!==1?"es":""})`)}`:""}case"ls":{let F=X.items||X.files||X,d=Array.isArray(F)?F.length:0;return d>0?` ${bI.dim(`(${d} item${d!==1?"s":""})`)}`:""}case"read_file":return Z(l(X));case"cd":{let F=fZ(X.path||X.currentDirectory);return F?` ${bI.dim("→")} ${bI.cyan(F)}`:""}case"execute_command":case"execute_execute_command":return Z(Y(X));case"http_request":{let F=X.statusCode;if(F!==void 0&&F!==null){let d=fZ(F);return d?` ${bI.dim(`(${d})`)}`:""}return""}case"edit_file":case"execute_edit_file":case"write_file":case"execute_write_file":{let F=X.diff;if(typeof F==="string"&&F.length>0)return`
6825
- ${F}`;return""}case"read_pdf":{let{pageCount:F,pagesExtracted:d,truncated:Q,path:m,tables:R,totalLines:H}=X,h=[];if(m)h.push(`file: ${fZ(m)}`);if(Array.isArray(d)&&d.length>0)h.push(`pages: ${d.join(", ")}`);if(typeof F==="number")h.push(`total: ${F}`);if(typeof H==="number")h.push(`lines: ${H}`);if(Array.isArray(R))h.push(`tables: ${R.length}`);if(Q)h.push(bI.yellow("truncated"));return h.length>0?` ${bI.dim("(")}${h.join(", ")}${bI.dim(")")}`:""}default:return Z(N(X))}}catch{return Z(G)}}var q3G=12,kyI=1200,D3G=1e5;var Zg=g(()=>{y0();MR()});var bg;var Me=g(()=>{UI();bg=ZZ.GenericTag("TelemetryService")});import{randomUUID as pVb}from"node:crypto";function T3G(I){let{agent:G,conversationId:Z,userId:b,provider:W,model:l,reasoningEffort:Y,maxIterations:N}=I;return{runId:pVb(),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,childCostUSD: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 _3G(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 P3G(I){_v.calibrate(I.authoritativePromptTokens,I.messagesAtCallTime,{provider:I.provider,modelId:I.modelId})}function gD(I,G){I.llmRetryCount+=1,I.lastError=e3G(I,G,"llm-retry")}function n3G(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 $3G(I){I.currentIteration=void 0}function i3G(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 f3G(I,G,Z){I.toolErrors+=1,I.lastError=e3G(I,Z,`tool:${G}`)}function uyI(I){return Math.ceil(I/4)}function s3G(I,G,Z){if(I.totalToolDefinitionTokens+=G,I.toolDefinitionsOffered+=Z,I.currentIteration)I.currentIteration.toolDefinitionTokens=G}function o3G(I,G,Z){let b=uyI(Z);if(I.totalToolResultTokens+=b,I.currentIteration)I.currentIteration.toolResultTokens+=b,I.currentIteration.toolResultSizes[G]=(I.currentIteration.toolResultSizes[G]??0)+b}function r3G(I,G){if(I.firstTokenLatencyMs===void 0)I.firstTokenLatencyMs=G}function t3G(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],[F])=>X.localeCompare(F))),N=I.lastError&&I.lastError.trim().length>0?I.lastError:void 0,c=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(([F],[d])=>F.localeCompare(d))),errors:X.errors,toolSequence:X.toolSequence,toolDefinitionTokens:X.toolDefinitionTokens,toolResultTokens:X.toolResultTokens,toolResultSizes:X.toolResultSizes}));return w.gen(function*(){yield*zVb({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:c,...I.firstTokenLatencyMs!==void 0?{firstTokenLatencyMs:I.firstTokenLatencyMs}:{},toolDefinitionTokens:I.totalToolDefinitionTokens,toolResultTokens:I.totalToolResultTokens,toolDefinitionsOffered:I.toolDefinitionsOffered}),yield*uVb(I,W,b,G)})}function zVb(I){return w.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 kVb(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 uVb(I,G,Z,b){return w.flatMap(w.context(),(W)=>{let l=ZZ.getOption(W,bg);if(l._tag==="None")return w.void;let Y=l.value,N=kVb(I,G,Z,b);return Y.recordAgentRunCompleted(N).pipe(w.catchAll(()=>w.void))}).pipe(w.catchAll(()=>w.void))}function gVb(I){return(I instanceof Error?I.message:String(I)).replace(/\s+/g," ").trim()}function e3G(I,G,Z){let b=gVb(G),W=Z?`${Z}: ${b}`:b;if(I.errors.push(W),I.currentIteration)I.currentIteration.errors.push(W);return W}var Wg=g(()=>{UI();$W();Me();Nr()});class kC{static executeTool(I,G,Z,b){return w.gen(function*(){let W=yield*yl,l=yield*gG,Y=b,N=Y===void 0?yield*W.getTool(I).pipe(w.catchAll(()=>w.succeed(void 0))):void 0;if(Y===void 0){if(Y=N?.timeoutMs,Y===void 0&&!N?.longRunning)Y=Z2G}let c=W.executeTool(I,G,Z);return yield*Y!==void 0?c.pipe(w.timeoutFail({duration:Y,onTimeout:()=>{let F=Math.round(Y/60000);return Error(`Operation timed out after '${F}m'`)}}),w.catchAll((F)=>{let d=F instanceof Error?F.message:String(F);if(d.includes("timed out"))return l.warn(`Tool timeout: ${I}: ${d}`),w.succeed({success:!1,result:null,error:d});return w.fail(F)})):c})}static executeToolCall(I,G,Z,b,W,l,Y,N){return w.gen(function*(){let c=yield*ul,X=yield*gG;if(I.type!=="function")return{toolCallId:I.id,result:null,success:!1,name:"unknown"};let{name:F,arguments:d}=I.function;i3G(W,F);let Q=Date.now();try{let m;try{m=JSON.parse(d)}catch(L){throw Error(`Invalid JSON in tool arguments: ${L instanceof Error?L.message:String(L)}`,{cause:L})}let R=m&&typeof m==="object"&&!Array.isArray(m)?m:{};yield*X.logToolCall(F,R);let h=yield*(yield*yl).getTool(F).pipe(w.catchAll(()=>w.succeed(void 0))),E=h?.longRunning===!0,C=N.has(F);if(Z.showToolExecution&&!C){let L;if(F==="web_search")L={provider:(yield*(yield*pZ).appConfig).web_search?.provider??"builtin"};if(b)yield*b.handleEvent({type:"tool_execution_start",toolName:F,toolCallId:I.id,arguments:R,...L?{metadata:L}:{},...E?{longRunning:!0}:{}});else{let p=yield*c.formatToolExecutionStart(F,R,L?{metadata:L}:void 0);yield*c.writeBlankLine(),yield*c.writeOutput(p)}}let J=yield*kC.executeTool(F,R,G,h?.timeoutMs),y=Date.now()-Q,v=F;if(C3G(J.result)){let L=J.result,U=(yield*(yield*yl).getTool(F).pipe(w.catchAll(()=>w.succeed({riskLevel:"high-risk"})))).riskLevel,O=()=>G.getAutoApprovePolicy?.(),D=O(),K=()=>y3G(U,O())||BVb(F,G.autoApprovedTools)||UVb(F,L.executeArgs,G.autoApprovedCommands),a=K();if(a)yield*X.info("Tool auto-approved by policy",{toolName:F,executeToolName:L.executeToolName,riskLevel:U,autoApprovePolicy:D});else yield*X.debug("Tool requires approval, showing approval prompt",{toolName:F,executeToolName:L.executeToolName,riskLevel:U,autoApprovePolicy:D});let j=a?{approved:!0}:yield*c.requestApproval({toolName:F,message:L.message,executeToolName:L.executeToolName,executeArgs:L.executeArgs,...L.previewDiff?{previewDiff:L.previewDiff}:{},isAutoApproved:K});if(j.approved){if(j.alwaysApproveCommand&&G.onAutoApproveCommand)yield*G.onAutoApproveCommand(j.alwaysApproveCommand),yield*X.info("User chose to always approve command",{command:j.alwaysApproveCommand});if(j.alwaysApproveTool&&G.onAutoApproveTool)G.onAutoApproveTool(j.alwaysApproveTool),yield*X.info("User chose to always approve tool",{toolName:j.alwaysApproveTool});if(!a)yield*X.info("User approved tool execution",{toolName:F,executeToolName:L.executeToolName});let r=Date.now();if(Z.showToolExecution){let T;if(L.executeToolName==="web_search")T={provider:(yield*(yield*pZ).appConfig).web_search?.provider??"builtin"};if(b)yield*b.handleEvent({type:"tool_execution_start",toolName:F,toolCallId:I.id,arguments:L.executeArgs,...T?{metadata:T}:{}});else{let i=yield*c.formatToolExecutionStart(F,L.executeArgs,T?{metadata:T}:void 0);yield*c.writeBlankLine(),yield*c.writeOutput(i)}}J=yield*kC.executeTool(L.executeToolName,L.executeArgs,G),y=Date.now()-r,v=L.executeToolName,yield*X.debug("Execution tool completed after approval",{executeToolName:L.executeToolName,success:J.success,durationMs:y,autoApproved:a})}else yield*X.info("User rejected tool execution",{toolName:F,userMessage:j.userMessage}),J={success:!1,result:{rejected:!0,message:j.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 A=JSON.stringify(J.result);if(yield*X.debug("Tool execution succeeded",{agentId:l,conversationId:Y,toolName:v,toolCallId:I.id,durationMs:y,success:J.success,resultSize:A.length,resultPreview:A.substring(0,200)}),Z.showToolExecution)if(b)yield*b.handleEvent({type:"tool_execution_complete",toolCallId:I.id,result:A,durationMs:y});else if(J.success){let L=c.formatToolResult(v,A),p=yield*c.formatToolExecutionComplete(L,y);yield*c.writeOutput(p)}else{let L=J.error||"Tool execution failed",p=yield*c.formatToolExecutionError(L,y);yield*c.writeOutput(p)}yield*c.signalToolExecutionStarted();let k=J.success?J.result:{error:J.error??"Tool execution failed",result:J.result};return{toolCallId:I.id,result:k,success:J.success,name:v}}catch(m){let R=Date.now()-Q,H=m instanceof Error?m.message:String(m);if(Z.showToolExecution)if(b)yield*b.handleEvent({type:"tool_execution_complete",toolCallId:I.id,result:`Error: ${H}`,durationMs:R});else{let h=yield*c.formatToolExecutionError(H,R);yield*c.writeOutput(h)}return f3G(W,F,m),yield*X.error("Tool execution failed",{agentId:l,conversationId:Y,toolName:F,toolCallId:I.id,error:H}),yield*c.signalToolExecutionStarted(),{toolCallId:I.id,result:{error:H},success:!1,name:F}}})}static executeToolCalls(I,G,Z,b,W,l,Y,N,c){return w.gen(function*(){let X=yield*ul,F=yield*gG,d=yield*yl,Q=I.map((k)=>k.function.name),m=Array.from(new Set(Q)),R=yield*w.all(m.map((k)=>w.either(d.getTool(k))),{concurrency:iHI}),H=new Set;for(let k=0;k<m.length;k++){let L=m[k],p=R[k];if(L&&p&&V2.isRight(p)&&p.right.approvalExecuteToolName)H.add(L)}let h=Q.filter((k)=>H.has(k));if(Z.showToolExecution)if(b)yield*b.handleEvent({type:"tools_detected",toolNames:Q,toolsRequiringApproval:h,agentName:N});else{let k=yield*X.formatToolsDetected(N,Q,h);yield*X.writeOutput(k)}let E=[];for(let k of I)if(k.type==="function"){let{name:L,arguments:p}=k.function;try{let x=JSON.parse(p),U=x&&typeof x==="object"&&!Array.isArray(x)?x:{},O=Kh(L,U,{style:"plain"});E.push(O?`${L} ${O}`:L)}catch{E.push(L)}}let C=E.join(", ");yield*F.info(`${N} is using tools: ${C}`);let J=new Set(h),y=yield*w.all(I.map((k)=>w.fork(kC.executeToolCall(k,G,Z,b,W,l,Y,J))),{concurrency:iHI}),v=w.all(y.map((k)=>a2.join(k)),{concurrency:"unbounded"});if(!c)return yield*v;let A=yield*w.race(v.pipe(w.map((k)=>({type:"results",results:k}))),c.pipe(w.as({type:"interrupt"})));if(A.type==="interrupt")return yield*w.all(y.map((k)=>a2.interrupt(k)),{concurrency:"unbounded"}),yield*w.fail(new o1I({reason:"Tool execution interrupted by user"}));return A.results})}}function UVb(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=eu(b);return Z.some((l)=>W===l||W.startsWith(l+" "))}function BVb(I,G){if(!G?.length)return!1;return G.includes(I)}var gyI=g(()=>{UI();uN();$W();bX();hh();OY();zD();Zg();Wg()});function OVb(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 xVb(I,G=UyI){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 MVb(I,G,Z,b,W,l){return w.gen(function*(){let{response:Y,currentMessages:N,runMetrics:c,modelMetadata:X,finished:F,interrupted:d}=I,Q=I.iterationsUsed;if(!F)Q=W,yield*G.onIterationLimit(b,W);else if(!Y.content?.trim()&&!Y.reasoning?.trim()&&!Y.toolCalls&&!d)yield*G.onEmptyResponse(b);yield*Z.debug("Finalizing agent run",{interrupted:d,finished:F});let m=yield*t3G(c,{iterationsUsed:Q,finished:F}).pipe(w.catchAll((C)=>Z.warn("Failed to write agent token usage log",{error:C.message})),w.fork);yield*gZ.set(l,KI.some(m));let R=X?.inputPricePerMillion??0,H=X?.outputPricePerMillion??0,h=R>0||H>0?c.totalPromptTokens/1e6*R+c.totalCompletionTokens/1e6*H:void 0,E=h!==void 0||c.childCostUSD>0?parseFloat(((h??0)+c.childCostUSD).toFixed(8)):void 0;return{...Y,messages:N,usage:{promptTokens:c.totalPromptTokens,completionTokens:c.totalCompletionTokens},...E!==void 0?{costUSD:E}:{}}})}function KVb(I,G,Z,b,W){let{agent:l,actualConversationId:Y,context:N,contextWindowMaxTokens:c,runContextWindowManager:X,displayConfig:F,strategy:d,runMetrics:Q,maxIterations:m,options:R,logger:H}=W;return w.gen(function*(){yield*H.info("Agent decided to use tools",{agentId:l.id,conversationId:Y,iteration:b+1,toolsChosen:G.map((v)=>v.function.name),reasoning:Z});for(let v of G)if(v.type==="function")I.recentToolCalls.push({name:v.function.name,arguments:v.function.arguments});if(I.recentToolCalls.length>UyI)I.recentToolCalls.splice(0,I.recentToolCalls.length-UyI);if(xVb(I.recentToolCalls))yield*H.warn("Meltdown detected — injecting recovery signal",{agentId:l.id,recentTools:I.recentToolCalls.slice(-10).map((v)=>v.name)}),I.currentMessages.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.]"}),I.recentToolCalls.length=0;let h={...N,tokenStats:{currentTokens:X.calculateTotalTokens(I.currentMessages),maxTokens:c},conversationMessages:I.currentMessages,parentAgent:l,parentMaxIterations:m,compactConversation:(v)=>{I.currentMessages=[I.currentMessages[0],...v.slice(1)]},recordChildCost:(v)=>{Q.childCostUSD+=v}},E=yield*kC.executeToolCalls(G,h,F,d.getRenderer(),Q,l.id,Y,l.name,d.getInterruptSignal?.()),C=new Map(E.map((v)=>[v.toolCallId,v.result])),J=[];for(let v of G)if(v.type==="function"&&!C.has(v.id))J.push(v.id);if(J.length>0)return yield*H.error("Missing tool results for some tool calls",{agentId:l.id,conversationId:Y,missingToolCallIds:J,expectedCount:G.length,actualCount:E.length}),yield*w.fail(Error(`Missing tool results for ${J.length} tool call(s). This indicates a bug in tool execution.`));for(let v of G)if(v.type==="function"){let A=C.get(v.id);if(A===void 0)yield*H.error("Tool result is undefined despite validation",{agentId:l.id,conversationId:Y,toolCallId:v.id,toolName:v.function.name}),I.currentMessages.push({role:"tool",name:v.function.name,content:CyI(v.function.name,{error:"Tool execution result was undefined"}),tool_call_id:v.id});else{let k=CyI(v.function.name,A);I.currentMessages.push({role:"tool",name:v.function.name,content:k,tool_call_id:v.id}),o3G(Q,v.function.name,k.length)}}I.response={...I.response,toolCalls:[...I.response.toolCalls??[],...G],toolResults:{...I.response.toolResults,...Object.fromEntries(E.map((v)=>[v.name,v.result]))}};let y=R.checkQueuedMessage?.();if(y)I.currentMessages.push({role:"user",content:y})})}function aVb(I,G,Z){let{agent:b,options:W,actualConversationId:l,tools:Y,provider:N,model:c,runMetrics:X,contextWindowMaxTokens:F,runContextWindowManager:d,strategy:Q,observer:m,logger:R,maxIterations:H,runRecursive:h}=Z;return w.gen(function*(){if(!W.internal&&Q.shouldShowThinking)yield*m.onThinking(b.name,G===0);I.currentMessages=yield*yh.compactIfNeeded(I.currentMessages,b,W.sessionId,l,h,F);let E;for(let p=I.currentMessages.length-1;p>=0;p--)if(I.currentMessages[p]?.role==="user"){E=I.currentMessages[p]?.content;break}yield*R.debug("Sending LLM request",{agentId:b.id,conversationId:l,iteration:G+1,provider:N,model:c,messageCount:I.currentMessages.length,toolsAvailable:Y.length,reasoningEffort:b.config.reasoningEffort,lastUserMessage:E});let C=OVb(G+1,H),J=C?[...I.currentMessages,C]:I.currentMessages,y=yield*Q.getCompletion(J,G);if(y.interrupted){let p=y.completion;if(I.response={...I.response,content:p.content,...p.toolCalls?{toolCalls:p.toolCalls}:{}},p.content.length>0)I.currentMessages.push({role:"assistant",content:p.content});return yield*m.onInterrupted(b.name),yield*R.debug("Interruption handled, breaking loop"),{kind:"interrupted"}}let{completion:v}=y;if(yield*R.debug("LLM response received",{agentId:b.id,conversationId:l,iteration:G+1,contentLength:v.content.length,toolCallsCount:v.toolCalls?.length??0,tokenUsage:v.usage,contentPreview:v.content.substring(0,300)}),v.usage)_3G(X,v.usage),P3G({authoritativePromptTokens:v.usage.promptTokens,messagesAtCallTime:I.currentMessages,provider:N,modelId:c});if(v.toolDefinitionChars!=null)s3G(X,uyI(v.toolDefinitionChars),v.toolDefinitionCount??0);if(v.toolsDisabled)I.response={...I.response,toolsDisabled:!0};let A={role:"assistant",content:v.content,...v.reasoningParts&&v.reasoningParts.length>0?{reasoning_parts:v.reasoningParts}:{},...v.toolCalls?{tool_calls:v.toolCalls.map((p)=>({id:p.id,type:p.type,function:{name:p.function.name,arguments:p.function.arguments},...p.thought_signature?{thought_signature:p.thought_signature}:{}}))}:{}};I.currentMessages.push(A);let k=yield*d.trim(I.currentMessages,R,b.id,l);if(I.currentMessages=k.messages,v.toolCalls&&v.toolCalls.length>0)return yield*KVb(I,v.toolCalls,v.content,G,Z),{kind:"continue"};yield*R.info("Agent provided final response",{agentId:b.id,conversationId:l,iteration:G+1,completionLength:v.content.length,totalToolsUsed:X.toolCalls});let L=v.content?.trim().length?v.content:v.reasoning??v.content;return I.response={...I.response,content:L,...v.reasoning?{reasoning:v.reasoning}:{}},yield*Q.presentResponse(b.name,L,v),yield*m.onCompletion(b.name),yield*Q.onComplete(b.name,v),I.iterationsUsed=G+1,{kind:"final"}})}function Ke(I,G,Z,b,W,l){return w.acquireUseRelease(w.gen(function*(){let Y=yield*gG;yield*Y.setSessionId(I.sessionId);let N=yield*gZ.make(KI.none());return{logger:Y,finalizeFiberRef:N}}),({logger:Y,finalizeFiberRef:N})=>w.gen(function*(){let{agent:c,maxIterations:X}=I,F=X??ay,{actualConversationId:d,context:Q,tools:m,messages:R,runMetrics:H,provider:h,model:E}=G,C=yield*w.tryPromise({try:()=>n2(E,h),catch:()=>Error("Failed to fetch model metadata")}).pipe(w.catchAll(()=>w.succeed(void 0))),J=C?.contextWindow??Cc,y=$a.getConfig().maxTokens,v=$a.getConfig().protectedRecentTurns,A=new Vr({maxTokens:y,...v!==void 0&&{protectedRecentTurns:v},modelHint:{provider:h,modelId:E}});yield*Y.debug("Using model context window",{model:E,provider:h,contextWindow:J,source:C?"models.dev":"default"});let k={currentMessages:[R[0],...R.slice(1)],response:{content:"",conversationId:d},recentToolCalls:[],iterationsUsed:0},L=!1,p=!1,x={agent:c,options:I,actualConversationId:d,context:Q,tools:m,provider:h,model:E,runMetrics:H,contextWindowMaxTokens:J,runContextWindowManager:A,displayConfig:Z,strategy:b,observer:W,logger:Y,maxIterations:F,runRecursive:l};for(let U=0;U<F;U++){yield*w.sync(()=>n3G(H,U+1));try{let O=yield*aVb(k,U,x);if(O.kind==="interrupted"){L=!0,p=!0;break}if(O.kind==="final"){L=!0;break}}finally{yield*w.sync(()=>$3G(H))}}return yield*MVb({response:k.response,currentMessages:k.currentMessages,runMetrics:H,modelMetadata:C,iterationsUsed:k.iterationsUsed,finished:L,interrupted:p},W,Y,c.name,F,N)}),({logger:Y,finalizeFiberRef:N})=>w.gen(function*(){let c=yield*gZ.get(N);if(KI.isSome(c))yield*a2.await(c.value).pipe(w.asVoid,w.catchAll(()=>w.void));yield*Y.clearSessionId()}))}var UyI=10;var ByI=g(()=>{UI();KH();$W();xh();E3G();gyI();wwI();cr();Wg()});function ae(I){return{onThinking:(G,Z)=>I.presentThinking(G,Z),onInterrupted:(G)=>I.presentWarning(G,"generation stopped by user"),onIterationLimit:(G,Z)=>I.presentWarning(G,`iteration limit reached (${Z}) - type 'continue' to resume`),onEmptyResponse:(G)=>I.presentWarning(G,"model returned an empty response"),onCompletion:(G)=>I.presentCompletion(G)}}function OyI(I,G,Z,b,W){return w.gen(function*(){let l=yield*TQ,Y=yield*gG,N=yield*ul,{agent:c}=I,{runMetrics:X,provider:F,model:d}=G,Q=G.maxRetries??Ok,m=c.config.reasoningEffort??"disable",R=Z.showThinking&&m!=="disable",H=N.emitsToolEventsViaRenderer?.()===!0?yield*N.createStreamingRenderer({displayConfig:Z,streamingConfig:{enabled:!0},showMetrics:b,agentName:c.name,reasoningEffort:m}):null,h={shouldShowThinking:R,getCompletion(C,J){return w.gen(function*(){let y={model:d,messages:C,tools:G.tools,toolChoice:"auto",reasoning_effort:m,...typeof c.config.temperature==="number"?{temperature:c.config.temperature}:{},...c.config.llmApiKeys?{providerApiKeys:c.config.llmApiKeys}:{}},v=(p,x)=>N.presentStatus(p,x),A=yield*gZ.make(0),k=yD(Q,c.name,v,A);return{completion:yield*w.retry(ED(c.name,v,w.gen(function*(){try{return yield*l.createChatCompletion(F,y)}catch(p){throw gD(X,p),p}})),k).pipe(w.timeout(Hl.seconds(ua)),w.tapError((p)=>kY.isTimeoutException(p)?v(`${c.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):w.void)),interrupted:!1}})},presentResponse(C,J,y){return w.gen(function*(){let v=J;if(v&&Z.mode==="rendered")v=yield*N.renderMarkdown(v);if(v&&v.trim().length>0)yield*N.writeBlankLine(),yield*N.presentAgentResponse(c.name,v),yield*N.writeBlankLine();if(b&&y.usage){let A=[];if(y.usage.totalTokens)A.push(`Total: ${y.usage.totalTokens} tokens`);if(y.usage.promptTokens)A.push(`Prompt: ${y.usage.promptTokens}`);if(y.usage.completionTokens)A.push(`Completion: ${y.usage.completionTokens}`);if(A.length>0)yield*Y.info(`[${A.join(" | ")}]`)}})},onComplete(C,J){return w.void},getRenderer(){return H}},E=ae(N);return yield*Ke(I,G,Z,h,E,W)})}var I9G=g(()=>{UI();EyI();pC();$W();bX();ByI();Wg()});var lg;var je=g(()=>{UI();lg=ZZ.GenericTag("NotificationService")});function xyI(I,G,Z,b,W,l){return w.gen(function*(){let Y=yield*TQ,N=yield*gG,c=yield*ul,X=yield*w.serviceOption(lg),{agent:F}=I,{runMetrics:d,provider:Q,model:m,actualConversationId:R}=G,H=G.maxRetries??Ok,h=F.config.reasoningEffort??"disable",E=Z.showThinking&&h!=="disable",C={enabled:!0,...b.textBufferMs!==void 0&&{textBufferMs:b.textBufferMs}},J=yield*c.createStreamingRenderer({displayConfig:Z,streamingConfig:C,showMetrics:W,agentName:F.name,reasoningEffort:h,...I.ephemeralRegionId!==void 0&&{streamTarget:{kind:"ephemeral",regionId:I.ephemeralRegionId}}}),y=yield*s0.make(),v=()=>{w.runSync(s0.succeed(y,void 0))};yield*J.setInterruptHandler(v);let A=yield*gZ.make(void 0),k=yield*gZ.make(""),L={shouldShowThinking:E,getCompletion(U,O){return w.gen(function*(){yield*gZ.set(A,void 0),yield*gZ.set(k,"");let D={model:m,messages:U,tools:G.tools,toolChoice:"auto",reasoning_effort:h,...typeof F.config.temperature==="number"?{temperature:F.config.temperature}:{},...F.config.llmApiKeys?{providerApiKeys:F.config.llmApiKeys}:{}},K=(_,$)=>c.presentStatus(_,$),a=yield*gZ.make(0),j=yD(H,F.name,K,a),r=yield*w.retry(ED(F.name,K,w.gen(function*(){try{return yield*Y.createStreamingChatCompletion(Q,D)}catch(_){if(gD(d,_),_ instanceof LQ||_ instanceof UH||_ instanceof AQ)yield*N.error("LLM request error",{provider:Q,model:F.config.llmModel,errorType:_._tag,message:_.message,agentId:F.id,conversationId:R});throw _}})),j).pipe(w.timeout(Hl.seconds(ua)),w.tapError((_)=>kY.isTimeoutException(_)?K(`${F.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):w.void),w.catchIf((_)=>LC(_),(_)=>w.gen(function*(){yield*N.warn("Streaming failed, falling back to non-streaming mode",{provider:Q,model:F.config.llmModel,errorType:_._tag,message:_.message,agentId:F.id,conversationId:R});let $=yield*gZ.make(0),II=yD(H,F.name,K,$),n=yield*w.retry(ED(F.name,K,w.gen(function*(){try{return yield*Y.createChatCompletion(Q,D)}catch(t){throw gD(d,t),t}})),II).pipe(w.timeout(Hl.seconds(ua)),w.tapError((t)=>kY.isTimeoutException(t)?K(`${F.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):w.void));return{stream:Vh.empty,response:w.succeed(n),cancel:w.void}}))),T=yield*w.fork(Vh.runForEach(r.stream,(_)=>w.gen(function*(){if(yield*J.handleEvent(_),_.type==="text_chunk")yield*gZ.set(k,_.accumulated);if(_.type==="complete"){if(yield*gZ.set(A,_.response),_.metrics?.firstTokenLatencyMs)r3G(d,_.metrics.firstTokenLatencyMs)}if(_.type==="error"){let $=_.error;if(yield*N.error("Stream event error",{provider:Q,model:F.config.llmModel,errorType:$._tag,message:$.message,recoverable:_.recoverable,agentId:F.id,conversationId:R}),!_.recoverable)yield*r.cancel}}))),i=yield*a2.await(T).pipe(w.raceFirst(s0.await(y)));if(yield*s0.isDone(y)){yield*r.cancel.pipe(w.catchAll((n)=>N.debug(`Stream cancel error (safe to ignore): ${String(n)}`))),yield*a2.interrupt(T).pipe(w.catchAll((n)=>N.debug(`Fiber interrupt error (safe to ignore): ${String(n)}`)));let _=yield*gZ.get(k);return yield*J.flush().pipe(w.catchAll((n)=>N.debug(`Renderer flush error (safe to ignore): ${String(n)}`))),{completion:(yield*gZ.get(A))??{id:"interrupted",model:m,content:_},interrupted:!0}}let q,S=i;if(lN.isFailure(S)){yield*r.cancel;let _=kY.failureOption(S.cause);if(KI.isSome(_))return yield*N.error("Stream processing failed",{error:_.value instanceof Error?_.value.message:String(_.value)}),yield*w.fail(_.value);else{let $=kY.dieOption(S.cause);if(KI.isSome($))return yield*w.die($.value);let II=yield*gZ.get(A);if(II)q=II;else q=yield*r.response.pipe(w.timeout(G9G),w.catchAll(()=>w.gen(function*(){return yield*r.cancel,yield*Y.createChatCompletion(Q,D)})))}}else{let _=yield*gZ.get(A);if(_)q=_;else q=yield*r.response.pipe(w.timeout(G9G),w.catchAll(()=>w.gen(function*(){return yield*r.cancel,yield*Y.createChatCompletion(Q,D)})))}return{completion:q,interrupted:!1}})},presentResponse(U,O,D){return w.void},onComplete(U,O){return w.gen(function*(){if(KI.isSome(X))yield*X.value.notify(`${U} has completed the task.`,{title:"Jazz Task Complete",sound:!0}).pipe(w.catchAll(()=>w.void))})},getRenderer(){return J},getInterruptSignal(){return s0.await(y)}},p=ae(c);return yield*Ke(I,G,Z,L,p,l).pipe(w.ensuring(J.setInterruptHandler(null)))})}var G9G;var Z9G=g(()=>{UI();EyI();pC();$W();je();bX();OY();vD();ByI();Wg();G9G=Hl.seconds(15)});var b9G=g(()=>{I9G();Z9G();gyI()});var XG;var GW=g(()=>{UI();XG=ZZ.GenericTag("FileSystemContextService")});function PQ(I={},G=[]){let Z={PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME??process.env.USER??"jazz",SHELL:process.env.SHELL??"/bin/sh",LANG:process.env.LANG??"en_US.UTF-8",LC_ALL:process.env.LC_ALL??"C",LC_CTYPE:process.env.LC_CTYPE??"UTF-8",TERM:process.env.TERM??"xterm-256color",PWD:process.cwd(),TMPDIR:process.env.TMPDIR??"/tmp",XDG_RUNTIME_DIR:process.env.XDG_RUNTIME_DIR,GIT_PAGER:process.env.GIT_PAGER??"cat",GIT_TERMINAL_PROMPT:"0",...I};for(let[b,W]of Object.entries(process.env??{})){if(W===void 0)continue;if(!G.includes(b)&&/API|KEY|SECRET|TOKEN|PASSWORD|CREDENTIAL|AUTH/i.test(b)||b in Z||b.startsWith("SSH_"))continue;Z[b]=W}return Z}function jVb(I){switch(I){case"string":return V.string();case"number":case"integer":return V.number();case"boolean":return V.boolean();case"null":return V.null();default:return V.object({})}}function DVb(I){if(I.every((b)=>typeof b==="string"))return V.enum(I);let G=I.filter((b)=>b===null||typeof b==="string"||typeof b==="number"||typeof b==="boolean");if(G.length===0)return V.unknown();if(G.length===1)return V.literal(G[0]);let Z=G.map((b)=>V.literal(b));return V.union([Z[0],Z[1],...Z.slice(2)])}function qVb(I,G){if(!I.properties)return V.object({}).passthrough();let Z={},b=new Set(I.required||[]);for(let[l,Y]of Object.entries(I.properties)){let N=G(Y),c=b.has(l);Z[l]=c?N:N.optional()}let W=V.object(Z);if(I.additionalProperties===!1)return W.strict();else if(I.additionalProperties===!0||I.additionalProperties!==void 0)return W.passthrough();return W}function SVb(I,G){if(I.items){let Z=G(I.items);return V.array(Z)}return V.array(V.unknown())}function W9G(I,G){if(I.length===0)return V.unknown();let Z=I.map(G),b=Z[0];if(!b)return V.unknown();if(I.length===1)return b;let W=Z[1];if(!W)return b;if(I.length===2)return V.union([b,W]);return V.union([b,W,...Z.slice(2)])}function TVb(I,G){return I.map(G).reduce((b,W)=>b.and(W),V.object({}))}function _Vb(I){if(I==="object")return!0;if(Array.isArray(I))return I.includes("object");return!1}function PVb(I){if(I==="array")return!0;if(Array.isArray(I))return I.includes("array");return!1}function aR(I,G){if(typeof I!=="object"||I===null)return V.object({});let b=I.jsonSchema;if(b!==void 0&&typeof b==="object"&&b!==null)return aR(b,G);let W=I;if("const"in W&&W.const!==void 0){let N=W.const;if(typeof N==="string"||typeof N==="number"||typeof N==="boolean"||N===null)return V.literal(N);return V.unknown()}if(W.$ref)return console.warn(`[MCP Schema Converter] $ref not supported: ${W.$ref}${G?` (tool: ${G})`:""}`),V.unknown();if(_Vb(W.type))return qVb(W,(N)=>aR(N,G));if(PVb(W.type))return SVb(W,(N)=>aR(N,G));if(W.enum&&W.enum.length>0)return DVb(W.enum);if(W.oneOf&&Array.isArray(W.oneOf)&&W.oneOf.length>0)return W9G(W.oneOf,(N)=>aR(N,G));if(W.anyOf&&Array.isArray(W.anyOf)&&W.anyOf.length>0)return W9G(W.anyOf,(N)=>aR(N,G));if(W.allOf&&Array.isArray(W.allOf)&&W.allOf.length>0)return TVb(W.allOf,(N)=>aR(N,G));let l;if(Array.isArray(W.type))l=W.type.length>0?W.type[0]:void 0;else if(typeof W.type==="string")l=W.type;else l=void 0;let Y=jVb(l);if(W.description){let N=W.format,c=N?` (format: ${N})`:"";Y=Y.describe(`${W.description}${c}`)}return Y}var MyI=g(()=>{Nb()});function zZ(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 w.succeed({success:!1,result:null,error:Y})}let l=W.value;return I.handler(l,b)}return I.handler(Z,b)}}}function MG(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 nVb(I){return`⚠️ APPROVAL REQUIRED: ${I}`}function $Vb(I){return`\uD83D\uDD27 EXECUTION TOOL: ${I}`}function Bl(I){let G=`execute_${I.name}`,Z=I.riskLevel??"high-risk",b=I.validate??((N)=>{let c=I.parameters.safeParse(N);return c.success?{valid:!0,value:c.data}:{valid:!1,errors:c.error.issues.map((X)=>X.message)}}),W=I.approvalErrorMessage??`Approval required: ${I.name} requires user confirmation.`,l=zZ({name:I.name,description:nVb(I.description),...I.tags?{tags:I.tags}:{},parameters:I.parameters,riskLevel:Z,validate:b,approvalExecuteToolName:G,handler:(N,c)=>w.gen(function*(){let X=yield*I.approvalMessage(N,c);if(typeof X==="object"&&"skipApproval"in X)return X.toolResult;let F=typeof X==="string"?X:X.message,d=typeof X==="string"?void 0:X.previewDiff;return{success:!1,result:{approvalRequired:!0,message:F,previewDiff:d,executeToolName:G,executeArgs:N},error:W}})}),Y=zZ({name:G,description:$Vb(`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 Sb=g(()=>{UI()});function OZ(I){return I.conversationId?{agentId:I.agentId,conversationId:I.conversationId}:{agentId:I.agentId}}function De(I){let{name:G,description:Z,parameters:b,handler:W}=I;if(typeof G!=="string"||!/^[a-z][a-z0-9_]{1,63}$/.test(G))return{message:`Invalid custom tool name "${String(G)}"`,suggestion:"Use lowercase letters, digits, and underscores only, starting with a letter, 2-64 characters (e.g. list_files)."};if(G.startsWith("mcp_"))return{message:`Custom tool name "${G}" cannot start with the reserved "mcp_" prefix`,suggestion:"Choose a name that does not start with mcp_."};if(typeof Z!=="string"||Z.length<1||Z.length>1024)return{message:`Custom tool "${G}" description must be a string between 1 and 1024 characters`,suggestion:"Provide a short, non-empty description of what the tool does."};if(typeof b!=="object"||b===null||Array.isArray(b)||b.type!=="object")return{message:`Custom tool "${G}" parameters must be a JSON Schema object with "type": "object"`,suggestion:'Set parameters to an object schema, e.g. { type: "object", properties: {} }.'};if(typeof W!=="object"||W===null||W.type!=="record"&&W.type!=="command"){let l=typeof W==="object"&&W!==null&&"type"in W?String(W.type):typeof W;return{message:`Custom tool "${G}" handler.type must be "record" or "command" (got "${l}")`,suggestion:'Set handler.type to "record" or "command".'}}if(W.type==="record"){if(W.response!==void 0&&(typeof W.response!=="string"||W.response.length>1024))return{message:`Custom tool "${G}" handler.response must be a string of at most 1024 characters`,suggestion:"Shorten the fixed response or remove it."};return null}if(!Array.isArray(W.command)||W.command.length===0||W.command.some((l)=>typeof l!=="string"||l.length===0))return{message:`Custom tool "${G}" handler.command must be a non-empty array of non-empty strings`,suggestion:'Provide a command like ["ls", "-la"].'};if(W.timeoutMs!==void 0&&(!Number.isInteger(W.timeoutMs)||W.timeoutMs<=0||W.timeoutMs>300000))return{message:`Custom tool "${G}" handler.timeoutMs must be a positive integer of at most 300000`,suggestion:"Set timeoutMs between 1 and 300000 milliseconds, or omit it."};return null}import{spawn as iVb}from"child_process";function N9G(I,G,Z){if(I.bytes>=Z)return I;let b=Z-I.bytes,W=G.subarray(0,b);return{chunks:[...I.chunks,W],bytes:I.bytes+W.byteLength}}function V9G(I){return Buffer.concat(I.chunks).toString("utf8")}function oVb(I,G,Z,b,W){return new Promise((l)=>{let[Y,...N]=I;if(!Y){l({ok:!1,error:"Custom tool command is empty"});return}let c=!1,X=Y9G,F=Y9G,d;try{d=iVb(Y,N,{cwd:Z,stdio:["pipe","pipe","pipe"],env:b,detached:!1})}catch(R){l({ok:!1,error:R instanceof Error?R.message:String(R)});return}let Q=(R)=>{if(c)return;c=!0,clearTimeout(m),l(R)},m=setTimeout(()=>{d.kill("SIGKILL"),Q({ok:!1,error:`Command timed out after ${W}ms`})},W);d.stdout?.on("data",(R)=>{X=N9G(X,R,l9G)}),d.stderr?.on("data",(R)=>{F=N9G(F,R,l9G)}),d.on("error",(R)=>{Q({ok:!1,error:R instanceof Error?R.message:String(R)})}),d.on("close",(R)=>{Q({ok:!0,exitCode:R??0,stdout:V9G(X),stderr:V9G(F)})}),d.stdin?.on("error",()=>{}),d.stdin?.write(G),d.stdin?.end()})}function rVb(I){let G=aR(I.parameters,I.name),Z=MG(G),b=I.handler.response??"Recorded.";return{...zZ({name:I.name,description:I.description,parameters:G,validate:Z,riskLevel:"read-only",handler:()=>w.succeed({success:!0,result:b})}),sourceCustomToolDefinition:I}}function tVb(I,G){let Z=aR(I.parameters,I.name),b=MG(Z),W=I.handler.command,l=I.handler.timeoutMs??fVb;return{...zZ({name:I.name,description:I.description,parameters:Z,validate:b,riskLevel:"high-risk",timeoutMs:l+sVb,handler:(Y,N)=>w.gen(function*(){let c=yield*XG,X=yield*gG,F=yield*c.getCwd(OZ(N)),d=PQ({},G),Q=JSON.stringify(Y),m=yield*w.promise(()=>oVb(W,Q,F,d,l));if(!m.ok)return yield*X.debug(`Custom tool "${I.name}" command execution failed: ${m.error}`),{success:!1,result:null,error:m.error};if(m.exitCode!==0)return{success:!1,result:null,error:`Command exited with code ${m.exitCode}${m.stderr?`: ${m.stderr}`:""}`};return{success:!0,result:m.stdout}})}),sourceCustomToolDefinition:I}}function KyI(I,G){if(I===G)return!0;if(typeof I!=="object"||typeof G!=="object"||I===null||G===null)return!1;if(Array.isArray(I)||Array.isArray(G)){if(!Array.isArray(I)||!Array.isArray(G)||I.length!==G.length)return!1;return I.every((W,l)=>KyI(W,G[l]))}let Z=Object.entries(I),b=G;if(Z.length!==Object.keys(b).length)return!1;return Z.every(([W,l])=>KyI(l,b[W]))}function X9G(I,G){return w.gen(function*(){let Z=yield*yl,b=yield*gG,W=I.config.customTools??[];if(W.length===0)return;let l=new Set(G),Y=W.filter((c)=>l.has(c.name));if(Y.length===0){yield*b.debug("Agent declares custom tools but none are referenced in its tool list, skipping registration");return}let N=I.config.envAllowlist??[];for(let c of Y){let X=De(c);if(X)yield*w.fail(new kN({agentId:I.id,field:"config.customTools",message:X.message,suggestion:X.suggestion}));let F=yield*Z.getTool(c.name).pipe(w.option);if(KI.isSome(F)){let Q=KI.fromNullable(F.value.sourceCustomToolDefinition);if(KI.isSome(Q)&&KyI(Q.value,c)){yield*b.debug(`Custom tool "${c.name}" is already registered with an identical definition, skipping re-registration`);continue}if(KI.isSome(Q))yield*w.fail(new kN({agentId:I.id,field:"config.customTools",message:`Custom tool "${c.name}" is already registered with a different definition than before (definition changed — restart the session or revert the config).`,suggestion:`Restart the session, or revert the "${c.name}" custom tool definition to match what was registered earlier.`}));else yield*w.fail(new kN({agentId:I.id,field:"config.customTools",message:`Custom tool "${c.name}" collides with an existing builtin or MCP tool (or one of its aliases). Rename yours.`,suggestion:`Choose a unique name for the "${c.name}" custom tool.`}))}if(c.handler.type==="command"){let Q=tVb(c,N);yield*Z.registerTool(Q,c9G),yield*b.debug(`Registered custom tool "${c.name}" (command handler)`);continue}let d=rVb(c);yield*Z.registerTool(d,c9G),yield*b.debug(`Registered custom tool "${c.name}" (record handler)`)}})}var l9G=16384,fVb=30000,sVb=5000,Y9G,c9G;var F9G=g(()=>{UI();GW();$W();hh();OY();MyI();Sb();Y9G={chunks:[],bytes:0};c9G={id:"custom_tools",displayName:"Custom Tools"}});function qe(I){return I.transport===void 0||I.transport==="stdio"}function Se(I){return I.transport==="http"}var pc;var ah=g(()=>{UI();pc=ZZ.GenericTag("MCPServerManager")});function d9G(){return{name:"get_time",description:"Get current date and time. Use for scheduling, relative times (yesterday, next Monday), and timestamps.",parameters:V.object({}).strict(),riskLevel:"read-only",hidden:!1,createSummary:void 0,execute:()=>{let I=new Date,G=I.toISOString(),Z=eVb[I.getDay()],b=I.toLocaleDateString(),W=I.toLocaleTimeString(),l=Intl.DateTimeFormat().resolvedOptions().timeZone;return w.succeed({success:!0,result:{iso:G,timestamp:I.getTime(),dayOfWeek:Z,localDate:b,localTime:W,timezone:l}})}}}function Q9G(){return{name:"context_info",description:"Get current context window token usage statistics.",parameters:V.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 w.succeed({success:!0,result:{estimatedTokensUsed:Z,maxTokens:b,remainingTokens:l,percentUsed:W,recommendation:Y}})}}}var eVb;var m9G=g(()=>{UI();Nb();eVb=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]});function R9G(){let I=V.object({path:V.string().min(1).describe("Absolute or relative path to change to")}).strict();return zZ({name:"cd",description:"Change the working directory for this session. Persists across subsequent tool calls.",tags:["filesystem","navigation"],parameters:I,validate:MG(I),handler:(G,Z)=>w.gen(function*(){let b=yield*oI.FileSystem,W=yield*XG,l=yield*W.resolvePath(OZ(Z),G.path).pipe(w.catchAll(()=>w.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(OZ(Z),l),{success:!0,result:l}}catch(Y){return{success:!1,result:null,error:`cd failed: ${Y instanceof Error?Y.message:String(Y)}`}}})})}var H9G=g(()=>{gb();UI();Nb();GW();Sb()});function h9G(){let I={name:"cp",description:"Copy a file or directory. Equivalent to shell cp/cp -r. Directories are copied recursively.",tags:["filesystem","write"],parameters:w9G,validate:MG(w9G),approvalMessage:(G,Z)=>w.gen(function*(){let b=yield*XG,W=yield*b.resolvePath(OZ(Z),G.source),l=yield*b.resolvePath(OZ(Z),G.destination,{skipExistenceCheck:!0}),Y=G.force===!0?" (will overwrite if exists)":"";return`About to copy: ${W}
6825
+ ${F}`;return""}case"read_pdf":{let{pageCount:F,pagesExtracted:d,truncated:Q,path:m,tables:R,totalLines:H}=X,h=[];if(m)h.push(`file: ${fZ(m)}`);if(Array.isArray(d)&&d.length>0)h.push(`pages: ${d.join(", ")}`);if(typeof F==="number")h.push(`total: ${F}`);if(typeof H==="number")h.push(`lines: ${H}`);if(Array.isArray(R))h.push(`tables: ${R.length}`);if(Q)h.push(bI.yellow("truncated"));return h.length>0?` ${bI.dim("(")}${h.join(", ")}${bI.dim(")")}`:""}default:return Z(N(X))}}catch{return Z(G)}}var q3G=12,kyI=1200,D3G=1e5;var Zg=g(()=>{y0();MR()});var bg;var Me=g(()=>{UI();bg=ZZ.GenericTag("TelemetryService")});import{randomUUID as pVb}from"node:crypto";function T3G(I){let{agent:G,conversationId:Z,userId:b,provider:W,model:l,reasoningEffort:Y,maxIterations:N}=I;return{runId:pVb(),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,childCostUSD: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 _3G(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 P3G(I){_v.calibrate(I.authoritativePromptTokens,I.messagesAtCallTime,{provider:I.provider,modelId:I.modelId})}function gD(I,G){I.llmRetryCount+=1,I.lastError=e3G(I,G,"llm-retry")}function n3G(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 $3G(I){I.currentIteration=void 0}function i3G(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 f3G(I,G,Z){I.toolErrors+=1,I.lastError=e3G(I,Z,`tool:${G}`)}function uyI(I){return Math.ceil(I/4)}function s3G(I,G,Z){if(I.totalToolDefinitionTokens+=G,I.toolDefinitionsOffered+=Z,I.currentIteration)I.currentIteration.toolDefinitionTokens=G}function o3G(I,G,Z){let b=uyI(Z);if(I.totalToolResultTokens+=b,I.currentIteration)I.currentIteration.toolResultTokens+=b,I.currentIteration.toolResultSizes[G]=(I.currentIteration.toolResultSizes[G]??0)+b}function r3G(I,G){if(I.firstTokenLatencyMs===void 0)I.firstTokenLatencyMs=G}function t3G(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],[F])=>X.localeCompare(F))),N=I.lastError&&I.lastError.trim().length>0?I.lastError:void 0,c=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(([F],[d])=>F.localeCompare(d))),errors:X.errors,toolSequence:X.toolSequence,toolDefinitionTokens:X.toolDefinitionTokens,toolResultTokens:X.toolResultTokens,toolResultSizes:X.toolResultSizes}));return w.gen(function*(){yield*zVb({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:c,...I.firstTokenLatencyMs!==void 0?{firstTokenLatencyMs:I.firstTokenLatencyMs}:{},toolDefinitionTokens:I.totalToolDefinitionTokens,toolResultTokens:I.totalToolResultTokens,toolDefinitionsOffered:I.toolDefinitionsOffered}),yield*uVb(I,W,b,G)})}function zVb(I){return w.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 kVb(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 uVb(I,G,Z,b){return w.flatMap(w.context(),(W)=>{let l=ZZ.getOption(W,bg);if(l._tag==="None")return w.void;let Y=l.value,N=kVb(I,G,Z,b);return Y.recordAgentRunCompleted(N).pipe(w.catchAll(()=>w.void))}).pipe(w.catchAll(()=>w.void))}function gVb(I){return(I instanceof Error?I.message:String(I)).replace(/\s+/g," ").trim()}function e3G(I,G,Z){let b=gVb(G),W=Z?`${Z}: ${b}`:b;if(I.errors.push(W),I.currentIteration)I.currentIteration.errors.push(W);return W}var Wg=g(()=>{UI();$W();Me();Nr()});class kC{static executeTool(I,G,Z,b){return w.gen(function*(){let W=yield*yl,l=yield*gG,Y=b,N=Y===void 0?yield*W.getTool(I).pipe(w.catchAll(()=>w.succeed(void 0))):void 0;if(Y===void 0){if(Y=N?.timeoutMs,Y===void 0&&!N?.longRunning)Y=Z2G}let c=W.executeTool(I,G,Z);return yield*Y!==void 0?c.pipe(w.timeoutFail({duration:Y,onTimeout:()=>{let F=Math.round(Y/60000);return Error(`Operation timed out after '${F}m'`)}}),w.catchAll((F)=>{let d=F instanceof Error?F.message:String(F);if(d.includes("timed out"))return l.warn(`Tool timeout: ${I}: ${d}`),w.succeed({success:!1,result:null,error:d});return w.fail(F)})):c})}static executeToolCall(I,G,Z,b,W,l,Y,N){return w.gen(function*(){let c=yield*ul,X=yield*gG;if(I.type!=="function")return{toolCallId:I.id,result:null,success:!1,name:"unknown"};let{name:F,arguments:d}=I.function;i3G(W,F);let Q=Date.now();try{let m;try{m=JSON.parse(d)}catch(L){throw Error(`Invalid JSON in tool arguments: ${L instanceof Error?L.message:String(L)}`,{cause:L})}let R=m&&typeof m==="object"&&!Array.isArray(m)?m:{};yield*X.logToolCall(F,R);let h=yield*(yield*yl).getTool(F).pipe(w.catchAll(()=>w.succeed(void 0))),E=h?.longRunning===!0,C=N.has(F);if(Z.showToolExecution&&!C){let L;if(F==="web_search")L={provider:(yield*(yield*pZ).appConfig).web_search?.provider??"builtin"};if(b)yield*b.handleEvent({type:"tool_execution_start",toolName:F,toolCallId:I.id,arguments:R,...L?{metadata:L}:{},...E?{longRunning:!0}:{}});else{let p=yield*c.formatToolExecutionStart(F,R,L?{metadata:L}:void 0);yield*c.writeBlankLine(),yield*c.writeOutput(p)}}let J=yield*kC.executeTool(F,R,G,h?.timeoutMs),y=Date.now()-Q,v=F;if(C3G(J.result)){let L=J.result,U=(yield*(yield*yl).getTool(F).pipe(w.catchAll(()=>w.succeed({riskLevel:"high-risk"})))).riskLevel,O=()=>G.getAutoApprovePolicy?.(),D=O(),K=()=>y3G(U,O())||BVb(F,G.autoApprovedTools)||UVb(F,L.executeArgs,G.autoApprovedCommands),a=K();if(b)yield*b.handleEvent({type:"approval_required",toolName:F,riskLevel:U,...D!==void 0?{autoApprovePolicy:String(D)}:{}});if(a)yield*X.info("Tool auto-approved by policy",{toolName:F,executeToolName:L.executeToolName,riskLevel:U,autoApprovePolicy:D});else yield*X.debug("Tool requires approval, showing approval prompt",{toolName:F,executeToolName:L.executeToolName,riskLevel:U,autoApprovePolicy:D});let j=a?{approved:!0}:yield*c.requestApproval({toolName:F,message:L.message,executeToolName:L.executeToolName,executeArgs:L.executeArgs,...L.previewDiff?{previewDiff:L.previewDiff}:{},isAutoApproved:K});if(b)yield*b.handleEvent({type:"approval_resolved",toolName:F,approved:j.approved,auto:a});if(j.approved){if(j.alwaysApproveCommand&&G.onAutoApproveCommand)yield*G.onAutoApproveCommand(j.alwaysApproveCommand),yield*X.info("User chose to always approve command",{command:j.alwaysApproveCommand});if(j.alwaysApproveTool&&G.onAutoApproveTool)G.onAutoApproveTool(j.alwaysApproveTool),yield*X.info("User chose to always approve tool",{toolName:j.alwaysApproveTool});if(!a)yield*X.info("User approved tool execution",{toolName:F,executeToolName:L.executeToolName});let r=Date.now();if(Z.showToolExecution){let T;if(L.executeToolName==="web_search")T={provider:(yield*(yield*pZ).appConfig).web_search?.provider??"builtin"};if(b)yield*b.handleEvent({type:"tool_execution_start",toolName:F,toolCallId:I.id,arguments:L.executeArgs,...T?{metadata:T}:{}});else{let i=yield*c.formatToolExecutionStart(F,L.executeArgs,T?{metadata:T}:void 0);yield*c.writeBlankLine(),yield*c.writeOutput(i)}}J=yield*kC.executeTool(L.executeToolName,L.executeArgs,G),y=Date.now()-r,v=L.executeToolName,yield*X.debug("Execution tool completed after approval",{executeToolName:L.executeToolName,success:J.success,durationMs:y,autoApproved:a})}else yield*X.info("User rejected tool execution",{toolName:F,userMessage:j.userMessage}),J={success:!1,result:{rejected:!0,message:j.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 A=JSON.stringify(J.result);if(yield*X.debug("Tool execution succeeded",{agentId:l,conversationId:Y,toolName:v,toolCallId:I.id,durationMs:y,success:J.success,resultSize:A.length,resultPreview:A.substring(0,200)}),Z.showToolExecution)if(b)yield*b.handleEvent({type:"tool_execution_complete",toolCallId:I.id,result:A,durationMs:y});else if(J.success){let L=c.formatToolResult(v,A),p=yield*c.formatToolExecutionComplete(L,y);yield*c.writeOutput(p)}else{let L=J.error||"Tool execution failed",p=yield*c.formatToolExecutionError(L,y);yield*c.writeOutput(p)}yield*c.signalToolExecutionStarted();let k=J.success?J.result:{error:J.error??"Tool execution failed",result:J.result};return{toolCallId:I.id,result:k,success:J.success,name:v}}catch(m){let R=Date.now()-Q,H=m instanceof Error?m.message:String(m);if(Z.showToolExecution)if(b)yield*b.handleEvent({type:"tool_execution_complete",toolCallId:I.id,result:`Error: ${H}`,durationMs:R});else{let h=yield*c.formatToolExecutionError(H,R);yield*c.writeOutput(h)}return f3G(W,F,m),yield*X.error("Tool execution failed",{agentId:l,conversationId:Y,toolName:F,toolCallId:I.id,error:H}),yield*c.signalToolExecutionStarted(),{toolCallId:I.id,result:{error:H},success:!1,name:F}}})}static executeToolCalls(I,G,Z,b,W,l,Y,N,c){return w.gen(function*(){let X=yield*ul,F=yield*gG,d=yield*yl,Q=I.map((k)=>k.function.name),m=Array.from(new Set(Q)),R=yield*w.all(m.map((k)=>w.either(d.getTool(k))),{concurrency:iHI}),H=new Set;for(let k=0;k<m.length;k++){let L=m[k],p=R[k];if(L&&p&&V2.isRight(p)&&p.right.approvalExecuteToolName)H.add(L)}let h=Q.filter((k)=>H.has(k));if(Z.showToolExecution)if(b)yield*b.handleEvent({type:"tools_detected",toolNames:Q,toolsRequiringApproval:h,agentName:N});else{let k=yield*X.formatToolsDetected(N,Q,h);yield*X.writeOutput(k)}let E=[];for(let k of I)if(k.type==="function"){let{name:L,arguments:p}=k.function;try{let x=JSON.parse(p),U=x&&typeof x==="object"&&!Array.isArray(x)?x:{},O=Kh(L,U,{style:"plain"});E.push(O?`${L} ${O}`:L)}catch{E.push(L)}}let C=E.join(", ");yield*F.info(`${N} is using tools: ${C}`);let J=new Set(h),y=yield*w.all(I.map((k)=>w.fork(kC.executeToolCall(k,G,Z,b,W,l,Y,J))),{concurrency:iHI}),v=w.all(y.map((k)=>a2.join(k)),{concurrency:"unbounded"});if(!c)return yield*v;let A=yield*w.race(v.pipe(w.map((k)=>({type:"results",results:k}))),c.pipe(w.as({type:"interrupt"})));if(A.type==="interrupt")return yield*w.all(y.map((k)=>a2.interrupt(k)),{concurrency:"unbounded"}),yield*w.fail(new o1I({reason:"Tool execution interrupted by user"}));return A.results})}}function UVb(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=eu(b);return Z.some((l)=>W===l||W.startsWith(l+" "))}function BVb(I,G){if(!G?.length)return!1;return G.includes(I)}var gyI=g(()=>{UI();uN();$W();bX();hh();OY();zD();Zg();Wg()});function OVb(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 xVb(I,G=UyI){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 MVb(I,G,Z,b,W,l){return w.gen(function*(){let{response:Y,currentMessages:N,runMetrics:c,modelMetadata:X,finished:F,interrupted:d}=I,Q=I.iterationsUsed;if(!F)Q=W,yield*G.onIterationLimit(b,W);else if(!Y.content?.trim()&&!Y.reasoning?.trim()&&!Y.toolCalls&&!d)yield*G.onEmptyResponse(b);yield*Z.debug("Finalizing agent run",{interrupted:d,finished:F});let m=yield*t3G(c,{iterationsUsed:Q,finished:F}).pipe(w.catchAll((C)=>Z.warn("Failed to write agent token usage log",{error:C.message})),w.fork);yield*gZ.set(l,KI.some(m));let R=X?.inputPricePerMillion??0,H=X?.outputPricePerMillion??0,h=R>0||H>0?c.totalPromptTokens/1e6*R+c.totalCompletionTokens/1e6*H:void 0,E=h!==void 0||c.childCostUSD>0?parseFloat(((h??0)+c.childCostUSD).toFixed(8)):void 0;return{...Y,messages:N,usage:{promptTokens:c.totalPromptTokens,completionTokens:c.totalCompletionTokens},...E!==void 0?{costUSD:E}:{}}})}function KVb(I,G,Z,b,W){let{agent:l,actualConversationId:Y,context:N,contextWindowMaxTokens:c,runContextWindowManager:X,displayConfig:F,strategy:d,runMetrics:Q,maxIterations:m,options:R,logger:H}=W;return w.gen(function*(){yield*H.info("Agent decided to use tools",{agentId:l.id,conversationId:Y,iteration:b+1,toolsChosen:G.map((A)=>A.function.name),reasoning:Z});for(let A of G)if(A.type==="function")I.recentToolCalls.push({name:A.function.name,arguments:A.function.arguments});if(I.recentToolCalls.length>UyI)I.recentToolCalls.splice(0,I.recentToolCalls.length-UyI);if(xVb(I.recentToolCalls))yield*H.warn("Meltdown detected — injecting recovery signal",{agentId:l.id,recentTools:I.recentToolCalls.slice(-10).map((A)=>A.name)}),I.currentMessages.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.]"}),I.recentToolCalls.length=0;let h=d.getRenderer(),E={...N,tokenStats:{currentTokens:X.calculateTotalTokens(I.currentMessages),maxTokens:c},conversationMessages:I.currentMessages,parentAgent:l,parentMaxIterations:m,compactConversation:(A)=>{I.currentMessages=[I.currentMessages[0],...A.slice(1)]},recordChildCost:(A)=>{Q.childCostUSD+=A},...h?{emitEvent:(A)=>h.handleEvent(A)}:{}},C=yield*kC.executeToolCalls(G,E,F,h,Q,l.id,Y,l.name,d.getInterruptSignal?.()),J=new Map(C.map((A)=>[A.toolCallId,A.result])),y=[];for(let A of G)if(A.type==="function"&&!J.has(A.id))y.push(A.id);if(y.length>0)return yield*H.error("Missing tool results for some tool calls",{agentId:l.id,conversationId:Y,missingToolCallIds:y,expectedCount:G.length,actualCount:C.length}),yield*w.fail(Error(`Missing tool results for ${y.length} tool call(s). This indicates a bug in tool execution.`));for(let A of G)if(A.type==="function"){let k=J.get(A.id);if(k===void 0)yield*H.error("Tool result is undefined despite validation",{agentId:l.id,conversationId:Y,toolCallId:A.id,toolName:A.function.name}),I.currentMessages.push({role:"tool",name:A.function.name,content:CyI(A.function.name,{error:"Tool execution result was undefined"}),tool_call_id:A.id});else{let L=CyI(A.function.name,k);I.currentMessages.push({role:"tool",name:A.function.name,content:L,tool_call_id:A.id}),o3G(Q,A.function.name,L.length)}}I.response={...I.response,toolCalls:[...I.response.toolCalls??[],...G],toolResults:{...I.response.toolResults,...Object.fromEntries(C.map((A)=>[A.name,A.result]))}};let v=R.checkQueuedMessage?.();if(v)I.currentMessages.push({role:"user",content:v})})}function aVb(I,G,Z){let{agent:b,options:W,actualConversationId:l,tools:Y,provider:N,model:c,runMetrics:X,contextWindowMaxTokens:F,runContextWindowManager:d,strategy:Q,observer:m,logger:R,maxIterations:H,runRecursive:h}=Z;return w.gen(function*(){if(!W.internal&&Q.shouldShowThinking)yield*m.onThinking(b.name,G===0);I.currentMessages=yield*yh.compactIfNeeded(I.currentMessages,b,W.sessionId,l,h,F);let E;for(let p=I.currentMessages.length-1;p>=0;p--)if(I.currentMessages[p]?.role==="user"){E=I.currentMessages[p]?.content;break}yield*R.debug("Sending LLM request",{agentId:b.id,conversationId:l,iteration:G+1,provider:N,model:c,messageCount:I.currentMessages.length,toolsAvailable:Y.length,reasoningEffort:b.config.reasoningEffort,lastUserMessage:E});let C=OVb(G+1,H),J=C?[...I.currentMessages,C]:I.currentMessages,y=yield*Q.getCompletion(J,G);if(y.interrupted){let p=y.completion;if(I.response={...I.response,content:p.content,...p.toolCalls?{toolCalls:p.toolCalls}:{}},p.content.length>0)I.currentMessages.push({role:"assistant",content:p.content});return yield*m.onInterrupted(b.name),yield*R.debug("Interruption handled, breaking loop"),{kind:"interrupted"}}let{completion:v}=y;if(yield*R.debug("LLM response received",{agentId:b.id,conversationId:l,iteration:G+1,contentLength:v.content.length,toolCallsCount:v.toolCalls?.length??0,tokenUsage:v.usage,contentPreview:v.content.substring(0,300)}),v.usage)_3G(X,v.usage),P3G({authoritativePromptTokens:v.usage.promptTokens,messagesAtCallTime:I.currentMessages,provider:N,modelId:c});if(v.toolDefinitionChars!=null)s3G(X,uyI(v.toolDefinitionChars),v.toolDefinitionCount??0);if(v.toolsDisabled)I.response={...I.response,toolsDisabled:!0};let A={role:"assistant",content:v.content,...v.reasoningParts&&v.reasoningParts.length>0?{reasoning_parts:v.reasoningParts}:{},...v.toolCalls?{tool_calls:v.toolCalls.map((p)=>({id:p.id,type:p.type,function:{name:p.function.name,arguments:p.function.arguments},...p.thought_signature?{thought_signature:p.thought_signature}:{}}))}:{}};I.currentMessages.push(A);let k=yield*d.trim(I.currentMessages,R,b.id,l);if(I.currentMessages=k.messages,v.toolCalls&&v.toolCalls.length>0)return yield*KVb(I,v.toolCalls,v.content,G,Z),{kind:"continue"};yield*R.info("Agent provided final response",{agentId:b.id,conversationId:l,iteration:G+1,completionLength:v.content.length,totalToolsUsed:X.toolCalls});let L=v.content?.trim().length?v.content:v.reasoning??v.content;return I.response={...I.response,content:L,...v.reasoning?{reasoning:v.reasoning}:{}},yield*Q.presentResponse(b.name,L,v),yield*m.onCompletion(b.name),yield*Q.onComplete(b.name,v),I.iterationsUsed=G+1,{kind:"final"}})}function Ke(I,G,Z,b,W,l){return w.acquireUseRelease(w.gen(function*(){let Y=yield*gG;yield*Y.setSessionId(I.sessionId);let N=yield*gZ.make(KI.none());return{logger:Y,finalizeFiberRef:N}}),({logger:Y,finalizeFiberRef:N})=>w.gen(function*(){let{agent:c,maxIterations:X}=I,F=X??ay,{actualConversationId:d,context:Q,tools:m,messages:R,runMetrics:H,provider:h,model:E}=G,C=yield*w.tryPromise({try:()=>n2(E,h),catch:()=>Error("Failed to fetch model metadata")}).pipe(w.catchAll(()=>w.succeed(void 0))),J=C?.contextWindow??Cc,y=$a.getConfig().maxTokens,v=$a.getConfig().protectedRecentTurns,A=new Vr({maxTokens:y,...v!==void 0&&{protectedRecentTurns:v},modelHint:{provider:h,modelId:E}});yield*Y.debug("Using model context window",{model:E,provider:h,contextWindow:J,source:C?"models.dev":"default"});let k={currentMessages:[R[0],...R.slice(1)],response:{content:"",conversationId:d},recentToolCalls:[],iterationsUsed:0},L=!1,p=!1,x={agent:c,options:I,actualConversationId:d,context:Q,tools:m,provider:h,model:E,runMetrics:H,contextWindowMaxTokens:J,runContextWindowManager:A,displayConfig:Z,strategy:b,observer:W,logger:Y,maxIterations:F,runRecursive:l};for(let U=0;U<F;U++){yield*w.sync(()=>n3G(H,U+1));try{let O=yield*aVb(k,U,x);if(O.kind==="interrupted"){L=!0,p=!0;break}if(O.kind==="final"){L=!0;break}}finally{yield*w.sync(()=>$3G(H))}}return yield*MVb({response:k.response,currentMessages:k.currentMessages,runMetrics:H,modelMetadata:C,iterationsUsed:k.iterationsUsed,finished:L,interrupted:p},W,Y,c.name,F,N)}),({logger:Y,finalizeFiberRef:N})=>w.gen(function*(){let c=yield*gZ.get(N);if(KI.isSome(c))yield*a2.await(c.value).pipe(w.asVoid,w.catchAll(()=>w.void));yield*Y.clearSessionId()}))}var UyI=10;var ByI=g(()=>{UI();KH();$W();xh();E3G();gyI();wwI();cr();Wg()});function ae(I){return{onThinking:(G,Z)=>I.presentThinking(G,Z),onInterrupted:(G)=>I.presentWarning(G,"generation stopped by user"),onIterationLimit:(G,Z)=>I.presentWarning(G,`iteration limit reached (${Z}) - type 'continue' to resume`),onEmptyResponse:(G)=>I.presentWarning(G,"model returned an empty response"),onCompletion:(G)=>I.presentCompletion(G)}}function OyI(I,G,Z,b,W){return w.gen(function*(){let l=yield*TQ,Y=yield*gG,N=yield*ul,{agent:c}=I,{runMetrics:X,provider:F,model:d}=G,Q=G.maxRetries??Ok,m=c.config.reasoningEffort??"disable",R=Z.showThinking&&m!=="disable",H=N.emitsToolEventsViaRenderer?.()===!0?yield*N.createStreamingRenderer({displayConfig:Z,streamingConfig:{enabled:!0},showMetrics:b,agentName:c.name,reasoningEffort:m}):null,h={shouldShowThinking:R,getCompletion(C,J){return w.gen(function*(){let y={model:d,messages:C,tools:G.tools,toolChoice:"auto",reasoning_effort:m,...typeof c.config.temperature==="number"?{temperature:c.config.temperature}:{},...c.config.llmApiKeys?{providerApiKeys:c.config.llmApiKeys}:{}},v=(p,x)=>N.presentStatus(p,x),A=yield*gZ.make(0),k=yD(Q,c.name,v,A);return{completion:yield*w.retry(ED(c.name,v,w.gen(function*(){try{return yield*l.createChatCompletion(F,y)}catch(p){throw gD(X,p),p}})),k).pipe(w.timeout(Hl.seconds(ua)),w.tapError((p)=>kY.isTimeoutException(p)?v(`${c.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):w.void)),interrupted:!1}})},presentResponse(C,J,y){return w.gen(function*(){let v=J;if(v&&Z.mode==="rendered")v=yield*N.renderMarkdown(v);if(v&&v.trim().length>0)yield*N.writeBlankLine(),yield*N.presentAgentResponse(c.name,v),yield*N.writeBlankLine();if(b&&y.usage){let A=[];if(y.usage.totalTokens)A.push(`Total: ${y.usage.totalTokens} tokens`);if(y.usage.promptTokens)A.push(`Prompt: ${y.usage.promptTokens}`);if(y.usage.completionTokens)A.push(`Completion: ${y.usage.completionTokens}`);if(A.length>0)yield*Y.info(`[${A.join(" | ")}]`)}})},onComplete(C,J){return w.void},getRenderer(){return H}},E=ae(N);return yield*Ke(I,G,Z,h,E,W)})}var I9G=g(()=>{UI();EyI();pC();$W();bX();ByI();Wg()});var lg;var je=g(()=>{UI();lg=ZZ.GenericTag("NotificationService")});function xyI(I,G,Z,b,W,l){return w.gen(function*(){let Y=yield*TQ,N=yield*gG,c=yield*ul,X=yield*w.serviceOption(lg),{agent:F}=I,{runMetrics:d,provider:Q,model:m,actualConversationId:R}=G,H=G.maxRetries??Ok,h=F.config.reasoningEffort??"disable",E=Z.showThinking&&h!=="disable",C={enabled:!0,...b.textBufferMs!==void 0&&{textBufferMs:b.textBufferMs}},J=yield*c.createStreamingRenderer({displayConfig:Z,streamingConfig:C,showMetrics:W,agentName:F.name,reasoningEffort:h,...I.ephemeralRegionId!==void 0&&{streamTarget:{kind:"ephemeral",regionId:I.ephemeralRegionId}}}),y=yield*s0.make(),v=()=>{w.runSync(s0.succeed(y,void 0))};yield*J.setInterruptHandler(v);let A=yield*gZ.make(void 0),k=yield*gZ.make(""),L={shouldShowThinking:E,getCompletion(U,O){return w.gen(function*(){yield*gZ.set(A,void 0),yield*gZ.set(k,"");let D={model:m,messages:U,tools:G.tools,toolChoice:"auto",reasoning_effort:h,...typeof F.config.temperature==="number"?{temperature:F.config.temperature}:{},...F.config.llmApiKeys?{providerApiKeys:F.config.llmApiKeys}:{}},K=(_,$)=>c.presentStatus(_,$),a=yield*gZ.make(0),j=yD(H,F.name,K,a),r=yield*w.retry(ED(F.name,K,w.gen(function*(){try{return yield*Y.createStreamingChatCompletion(Q,D)}catch(_){if(gD(d,_),_ instanceof LQ||_ instanceof UH||_ instanceof AQ)yield*N.error("LLM request error",{provider:Q,model:F.config.llmModel,errorType:_._tag,message:_.message,agentId:F.id,conversationId:R});throw _}})),j).pipe(w.timeout(Hl.seconds(ua)),w.tapError((_)=>kY.isTimeoutException(_)?K(`${F.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):w.void),w.catchIf((_)=>LC(_),(_)=>w.gen(function*(){yield*N.warn("Streaming failed, falling back to non-streaming mode",{provider:Q,model:F.config.llmModel,errorType:_._tag,message:_.message,agentId:F.id,conversationId:R});let $=yield*gZ.make(0),II=yD(H,F.name,K,$),n=yield*w.retry(ED(F.name,K,w.gen(function*(){try{return yield*Y.createChatCompletion(Q,D)}catch(t){throw gD(d,t),t}})),II).pipe(w.timeout(Hl.seconds(ua)),w.tapError((t)=>kY.isTimeoutException(t)?K(`${F.name} exceeded the maximum wait time for this step (including retries). Check connectivity or try again.`,"warning"):w.void));return{stream:Vh.empty,response:w.succeed(n),cancel:w.void}}))),T=yield*w.fork(Vh.runForEach(r.stream,(_)=>w.gen(function*(){if(yield*J.handleEvent(_),_.type==="text_chunk")yield*gZ.set(k,_.accumulated);if(_.type==="complete"){if(yield*gZ.set(A,_.response),_.metrics?.firstTokenLatencyMs)r3G(d,_.metrics.firstTokenLatencyMs)}if(_.type==="error"){let $=_.error;if(yield*N.error("Stream event error",{provider:Q,model:F.config.llmModel,errorType:$._tag,message:$.message,recoverable:_.recoverable,agentId:F.id,conversationId:R}),!_.recoverable)yield*r.cancel}}))),i=yield*a2.await(T).pipe(w.raceFirst(s0.await(y)));if(yield*s0.isDone(y)){yield*r.cancel.pipe(w.catchAll((n)=>N.debug(`Stream cancel error (safe to ignore): ${String(n)}`))),yield*a2.interrupt(T).pipe(w.catchAll((n)=>N.debug(`Fiber interrupt error (safe to ignore): ${String(n)}`)));let _=yield*gZ.get(k);return yield*J.flush().pipe(w.catchAll((n)=>N.debug(`Renderer flush error (safe to ignore): ${String(n)}`))),{completion:(yield*gZ.get(A))??{id:"interrupted",model:m,content:_},interrupted:!0}}let q,S=i;if(lN.isFailure(S)){yield*r.cancel;let _=kY.failureOption(S.cause);if(KI.isSome(_))return yield*N.error("Stream processing failed",{error:_.value instanceof Error?_.value.message:String(_.value)}),yield*w.fail(_.value);else{let $=kY.dieOption(S.cause);if(KI.isSome($))return yield*w.die($.value);let II=yield*gZ.get(A);if(II)q=II;else q=yield*r.response.pipe(w.timeout(G9G),w.catchAll(()=>w.gen(function*(){return yield*r.cancel,yield*Y.createChatCompletion(Q,D)})))}}else{let _=yield*gZ.get(A);if(_)q=_;else q=yield*r.response.pipe(w.timeout(G9G),w.catchAll(()=>w.gen(function*(){return yield*r.cancel,yield*Y.createChatCompletion(Q,D)})))}return{completion:q,interrupted:!1}})},presentResponse(U,O,D){return w.void},onComplete(U,O){return w.gen(function*(){if(KI.isSome(X))yield*X.value.notify(`${U} has completed the task.`,{title:"Jazz Task Complete",sound:!0}).pipe(w.catchAll(()=>w.void))})},getRenderer(){return J},getInterruptSignal(){return s0.await(y)}},p=ae(c);return yield*Ke(I,G,Z,L,p,l).pipe(w.ensuring(J.setInterruptHandler(null)))})}var G9G;var Z9G=g(()=>{UI();EyI();pC();$W();je();bX();OY();vD();ByI();Wg();G9G=Hl.seconds(15)});var b9G=g(()=>{I9G();Z9G();gyI()});var XG;var GW=g(()=>{UI();XG=ZZ.GenericTag("FileSystemContextService")});function PQ(I={},G=[]){let Z={PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin",HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME??process.env.USER??"jazz",SHELL:process.env.SHELL??"/bin/sh",LANG:process.env.LANG??"en_US.UTF-8",LC_ALL:process.env.LC_ALL??"C",LC_CTYPE:process.env.LC_CTYPE??"UTF-8",TERM:process.env.TERM??"xterm-256color",PWD:process.cwd(),TMPDIR:process.env.TMPDIR??"/tmp",XDG_RUNTIME_DIR:process.env.XDG_RUNTIME_DIR,GIT_PAGER:process.env.GIT_PAGER??"cat",GIT_TERMINAL_PROMPT:"0",...I};for(let[b,W]of Object.entries(process.env??{})){if(W===void 0)continue;if(!G.includes(b)&&/API|KEY|SECRET|TOKEN|PASSWORD|CREDENTIAL|AUTH/i.test(b)||b in Z||b.startsWith("SSH_"))continue;Z[b]=W}return Z}function jVb(I){switch(I){case"string":return V.string();case"number":case"integer":return V.number();case"boolean":return V.boolean();case"null":return V.null();default:return V.object({})}}function DVb(I){if(I.every((b)=>typeof b==="string"))return V.enum(I);let G=I.filter((b)=>b===null||typeof b==="string"||typeof b==="number"||typeof b==="boolean");if(G.length===0)return V.unknown();if(G.length===1)return V.literal(G[0]);let Z=G.map((b)=>V.literal(b));return V.union([Z[0],Z[1],...Z.slice(2)])}function qVb(I,G){if(!I.properties)return V.object({}).passthrough();let Z={},b=new Set(I.required||[]);for(let[l,Y]of Object.entries(I.properties)){let N=G(Y),c=b.has(l);Z[l]=c?N:N.optional()}let W=V.object(Z);if(I.additionalProperties===!1)return W.strict();else if(I.additionalProperties===!0||I.additionalProperties!==void 0)return W.passthrough();return W}function SVb(I,G){if(I.items){let Z=G(I.items);return V.array(Z)}return V.array(V.unknown())}function W9G(I,G){if(I.length===0)return V.unknown();let Z=I.map(G),b=Z[0];if(!b)return V.unknown();if(I.length===1)return b;let W=Z[1];if(!W)return b;if(I.length===2)return V.union([b,W]);return V.union([b,W,...Z.slice(2)])}function TVb(I,G){return I.map(G).reduce((b,W)=>b.and(W),V.object({}))}function _Vb(I){if(I==="object")return!0;if(Array.isArray(I))return I.includes("object");return!1}function PVb(I){if(I==="array")return!0;if(Array.isArray(I))return I.includes("array");return!1}function aR(I,G){if(typeof I!=="object"||I===null)return V.object({});let b=I.jsonSchema;if(b!==void 0&&typeof b==="object"&&b!==null)return aR(b,G);let W=I;if("const"in W&&W.const!==void 0){let N=W.const;if(typeof N==="string"||typeof N==="number"||typeof N==="boolean"||N===null)return V.literal(N);return V.unknown()}if(W.$ref)return console.warn(`[MCP Schema Converter] $ref not supported: ${W.$ref}${G?` (tool: ${G})`:""}`),V.unknown();if(_Vb(W.type))return qVb(W,(N)=>aR(N,G));if(PVb(W.type))return SVb(W,(N)=>aR(N,G));if(W.enum&&W.enum.length>0)return DVb(W.enum);if(W.oneOf&&Array.isArray(W.oneOf)&&W.oneOf.length>0)return W9G(W.oneOf,(N)=>aR(N,G));if(W.anyOf&&Array.isArray(W.anyOf)&&W.anyOf.length>0)return W9G(W.anyOf,(N)=>aR(N,G));if(W.allOf&&Array.isArray(W.allOf)&&W.allOf.length>0)return TVb(W.allOf,(N)=>aR(N,G));let l;if(Array.isArray(W.type))l=W.type.length>0?W.type[0]:void 0;else if(typeof W.type==="string")l=W.type;else l=void 0;let Y=jVb(l);if(W.description){let N=W.format,c=N?` (format: ${N})`:"";Y=Y.describe(`${W.description}${c}`)}return Y}var MyI=g(()=>{Nb()});function zZ(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 w.succeed({success:!1,result:null,error:Y})}let l=W.value;return I.handler(l,b)}return I.handler(Z,b)}}}function MG(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 nVb(I){return`⚠️ APPROVAL REQUIRED: ${I}`}function $Vb(I){return`\uD83D\uDD27 EXECUTION TOOL: ${I}`}function Bl(I){let G=`execute_${I.name}`,Z=I.riskLevel??"high-risk",b=I.validate??((N)=>{let c=I.parameters.safeParse(N);return c.success?{valid:!0,value:c.data}:{valid:!1,errors:c.error.issues.map((X)=>X.message)}}),W=I.approvalErrorMessage??`Approval required: ${I.name} requires user confirmation.`,l=zZ({name:I.name,description:nVb(I.description),...I.tags?{tags:I.tags}:{},parameters:I.parameters,riskLevel:Z,validate:b,approvalExecuteToolName:G,handler:(N,c)=>w.gen(function*(){let X=yield*I.approvalMessage(N,c);if(typeof X==="object"&&"skipApproval"in X)return X.toolResult;let F=typeof X==="string"?X:X.message,d=typeof X==="string"?void 0:X.previewDiff;return{success:!1,result:{approvalRequired:!0,message:F,previewDiff:d,executeToolName:G,executeArgs:N},error:W}})}),Y=zZ({name:G,description:$Vb(`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 Sb=g(()=>{UI()});function OZ(I){return I.conversationId?{agentId:I.agentId,conversationId:I.conversationId}:{agentId:I.agentId}}function De(I){let{name:G,description:Z,parameters:b,handler:W}=I;if(typeof G!=="string"||!/^[a-z][a-z0-9_]{1,63}$/.test(G))return{message:`Invalid custom tool name "${String(G)}"`,suggestion:"Use lowercase letters, digits, and underscores only, starting with a letter, 2-64 characters (e.g. list_files)."};if(G.startsWith("mcp_"))return{message:`Custom tool name "${G}" cannot start with the reserved "mcp_" prefix`,suggestion:"Choose a name that does not start with mcp_."};if(typeof Z!=="string"||Z.length<1||Z.length>1024)return{message:`Custom tool "${G}" description must be a string between 1 and 1024 characters`,suggestion:"Provide a short, non-empty description of what the tool does."};if(typeof b!=="object"||b===null||Array.isArray(b)||b.type!=="object")return{message:`Custom tool "${G}" parameters must be a JSON Schema object with "type": "object"`,suggestion:'Set parameters to an object schema, e.g. { type: "object", properties: {} }.'};if(typeof W!=="object"||W===null||W.type!=="record"&&W.type!=="command"){let l=typeof W==="object"&&W!==null&&"type"in W?String(W.type):typeof W;return{message:`Custom tool "${G}" handler.type must be "record" or "command" (got "${l}")`,suggestion:'Set handler.type to "record" or "command".'}}if(W.type==="record"){if(W.response!==void 0&&(typeof W.response!=="string"||W.response.length>1024))return{message:`Custom tool "${G}" handler.response must be a string of at most 1024 characters`,suggestion:"Shorten the fixed response or remove it."};return null}if(!Array.isArray(W.command)||W.command.length===0||W.command.some((l)=>typeof l!=="string"||l.length===0))return{message:`Custom tool "${G}" handler.command must be a non-empty array of non-empty strings`,suggestion:'Provide a command like ["ls", "-la"].'};if(W.timeoutMs!==void 0&&(!Number.isInteger(W.timeoutMs)||W.timeoutMs<=0||W.timeoutMs>300000))return{message:`Custom tool "${G}" handler.timeoutMs must be a positive integer of at most 300000`,suggestion:"Set timeoutMs between 1 and 300000 milliseconds, or omit it."};return null}import{spawn as iVb}from"child_process";function N9G(I,G,Z){if(I.bytes>=Z)return I;let b=Z-I.bytes,W=G.subarray(0,b);return{chunks:[...I.chunks,W],bytes:I.bytes+W.byteLength}}function V9G(I){return Buffer.concat(I.chunks).toString("utf8")}function oVb(I,G,Z,b,W){return new Promise((l)=>{let[Y,...N]=I;if(!Y){l({ok:!1,error:"Custom tool command is empty"});return}let c=!1,X=Y9G,F=Y9G,d;try{d=iVb(Y,N,{cwd:Z,stdio:["pipe","pipe","pipe"],env:b,detached:!1})}catch(R){l({ok:!1,error:R instanceof Error?R.message:String(R)});return}let Q=(R)=>{if(c)return;c=!0,clearTimeout(m),l(R)},m=setTimeout(()=>{d.kill("SIGKILL"),Q({ok:!1,error:`Command timed out after ${W}ms`})},W);d.stdout?.on("data",(R)=>{X=N9G(X,R,l9G)}),d.stderr?.on("data",(R)=>{F=N9G(F,R,l9G)}),d.on("error",(R)=>{Q({ok:!1,error:R instanceof Error?R.message:String(R)})}),d.on("close",(R)=>{Q({ok:!0,exitCode:R??0,stdout:V9G(X),stderr:V9G(F)})}),d.stdin?.on("error",()=>{}),d.stdin?.write(G),d.stdin?.end()})}function rVb(I){let G=aR(I.parameters,I.name),Z=MG(G),b=I.handler.response??"Recorded.";return{...zZ({name:I.name,description:I.description,parameters:G,validate:Z,riskLevel:"read-only",handler:()=>w.succeed({success:!0,result:b})}),sourceCustomToolDefinition:I}}function tVb(I,G){let Z=aR(I.parameters,I.name),b=MG(Z),W=I.handler.command,l=I.handler.timeoutMs??fVb;return{...zZ({name:I.name,description:I.description,parameters:Z,validate:b,riskLevel:"high-risk",timeoutMs:l+sVb,handler:(Y,N)=>w.gen(function*(){let c=yield*XG,X=yield*gG,F=yield*c.getCwd(OZ(N)),d=PQ({},G),Q=JSON.stringify(Y),m=yield*w.promise(()=>oVb(W,Q,F,d,l));if(!m.ok)return yield*X.debug(`Custom tool "${I.name}" command execution failed: ${m.error}`),{success:!1,result:null,error:m.error};if(m.exitCode!==0)return{success:!1,result:null,error:`Command exited with code ${m.exitCode}${m.stderr?`: ${m.stderr}`:""}`};return{success:!0,result:m.stdout}})}),sourceCustomToolDefinition:I}}function KyI(I,G){if(I===G)return!0;if(typeof I!=="object"||typeof G!=="object"||I===null||G===null)return!1;if(Array.isArray(I)||Array.isArray(G)){if(!Array.isArray(I)||!Array.isArray(G)||I.length!==G.length)return!1;return I.every((W,l)=>KyI(W,G[l]))}let Z=Object.entries(I),b=G;if(Z.length!==Object.keys(b).length)return!1;return Z.every(([W,l])=>KyI(l,b[W]))}function X9G(I,G){return w.gen(function*(){let Z=yield*yl,b=yield*gG,W=I.config.customTools??[];if(W.length===0)return;let l=new Set(G),Y=W.filter((c)=>l.has(c.name));if(Y.length===0){yield*b.debug("Agent declares custom tools but none are referenced in its tool list, skipping registration");return}let N=I.config.envAllowlist??[];for(let c of Y){let X=De(c);if(X)yield*w.fail(new kN({agentId:I.id,field:"config.customTools",message:X.message,suggestion:X.suggestion}));let F=yield*Z.getTool(c.name).pipe(w.option);if(KI.isSome(F)){let Q=KI.fromNullable(F.value.sourceCustomToolDefinition);if(KI.isSome(Q)&&KyI(Q.value,c)){yield*b.debug(`Custom tool "${c.name}" is already registered with an identical definition, skipping re-registration`);continue}if(KI.isSome(Q))yield*w.fail(new kN({agentId:I.id,field:"config.customTools",message:`Custom tool "${c.name}" is already registered with a different definition than before (definition changed — restart the session or revert the config).`,suggestion:`Restart the session, or revert the "${c.name}" custom tool definition to match what was registered earlier.`}));else yield*w.fail(new kN({agentId:I.id,field:"config.customTools",message:`Custom tool "${c.name}" collides with an existing builtin or MCP tool (or one of its aliases). Rename yours.`,suggestion:`Choose a unique name for the "${c.name}" custom tool.`}))}if(c.handler.type==="command"){let Q=tVb(c,N);yield*Z.registerTool(Q,c9G),yield*b.debug(`Registered custom tool "${c.name}" (command handler)`);continue}let d=rVb(c);yield*Z.registerTool(d,c9G),yield*b.debug(`Registered custom tool "${c.name}" (record handler)`)}})}var l9G=16384,fVb=30000,sVb=5000,Y9G,c9G;var F9G=g(()=>{UI();GW();$W();hh();OY();MyI();Sb();Y9G={chunks:[],bytes:0};c9G={id:"custom_tools",displayName:"Custom Tools"}});function qe(I){return I.transport===void 0||I.transport==="stdio"}function Se(I){return I.transport==="http"}var pc;var ah=g(()=>{UI();pc=ZZ.GenericTag("MCPServerManager")});function d9G(){return{name:"get_time",description:"Get current date and time. Use for scheduling, relative times (yesterday, next Monday), and timestamps.",parameters:V.object({}).strict(),riskLevel:"read-only",hidden:!1,createSummary:void 0,execute:()=>{let I=new Date,G=I.toISOString(),Z=eVb[I.getDay()],b=I.toLocaleDateString(),W=I.toLocaleTimeString(),l=Intl.DateTimeFormat().resolvedOptions().timeZone;return w.succeed({success:!0,result:{iso:G,timestamp:I.getTime(),dayOfWeek:Z,localDate:b,localTime:W,timezone:l}})}}}function Q9G(){return{name:"context_info",description:"Get current context window token usage statistics.",parameters:V.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 w.succeed({success:!0,result:{estimatedTokensUsed:Z,maxTokens:b,remainingTokens:l,percentUsed:W,recommendation:Y}})}}}var eVb;var m9G=g(()=>{UI();Nb();eVb=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]});function R9G(){let I=V.object({path:V.string().min(1).describe("Absolute or relative path to change to")}).strict();return zZ({name:"cd",description:"Change the working directory for this session. Persists across subsequent tool calls.",tags:["filesystem","navigation"],parameters:I,validate:MG(I),handler:(G,Z)=>w.gen(function*(){let b=yield*oI.FileSystem,W=yield*XG,l=yield*W.resolvePath(OZ(Z),G.path).pipe(w.catchAll(()=>w.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(OZ(Z),l),{success:!0,result:l}}catch(Y){return{success:!1,result:null,error:`cd failed: ${Y instanceof Error?Y.message:String(Y)}`}}})})}var H9G=g(()=>{gb();UI();Nb();GW();Sb()});function h9G(){let I={name:"cp",description:"Copy a file or directory. Equivalent to shell cp/cp -r. Directories are copied recursively.",tags:["filesystem","write"],parameters:w9G,validate:MG(w9G),approvalMessage:(G,Z)=>w.gen(function*(){let b=yield*XG,W=yield*b.resolvePath(OZ(Z),G.source),l=yield*b.resolvePath(OZ(Z),G.destination,{skipExistenceCheck:!0}),Y=G.force===!0?" (will overwrite if exists)":"";return`About to copy: ${W}
6826
6826
  to: ${l}${Y}`}),handler:(G,Z)=>w.gen(function*(){let b=yield*oI.FileSystem,W=yield*XG,l=yield*W.resolvePath(OZ(Z),G.source),Y=yield*W.resolvePath(OZ(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(w.catchAll(()=>w.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(w.map(()=>({success:!0,result:`Copied: ${l} → ${Y}`})),w.catchAll((F)=>w.succeed({success:!1,result:null,error:`cp failed: ${F instanceof Error?F.message:String(F)}`})))})};return Bl(I)}var w9G;var J9G=g(()=>{gb();UI();Nb();GW();Sb();w9G=V.object({source:V.string().min(1).describe("Path to copy (file or directory)"),destination:V.string().min(1).describe("Destination path"),force:V.boolean().optional().describe("Overwrite destination if it exists (default: false)")}).strict()});class Te{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=(E)=>{if(E=this.postProcess(E,Z),b){setTimeout(function(){b(E)},0);return}else return E},Y=G.length,N=I.length,c=1,X=Y+N;if(Z.maxEditLength!=null)X=Math.min(X,Z.maxEditLength);let F=(W=Z.timeout)!==null&&W!==void 0?W:1/0,d=Date.now()+F,Q=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(Q[0],G,I,0,Z);if(Q[0].oldPos+1>=N&&m+1>=Y)return l(this.buildValues(Q[0].lastComponent,G,I));let R=-1/0,H=1/0,h=()=>{for(let E=Math.max(R,-c);E<=Math.min(H,c);E+=2){let C,J=Q[E-1],y=Q[E+1];if(J)Q[E-1]=void 0;let v=!1;if(y){let k=y.oldPos-E;v=y&&0<=k&&k<Y}let A=J&&J.oldPos+1<N;if(!v&&!A){Q[E]=void 0;continue}if(!A||v&&J.oldPos<y.oldPos)C=this.addToPath(y,!0,!1,0,Z);else C=this.addToPath(J,!1,!0,1,Z);if(m=this.extractCommon(C,G,I,E,Z),C.oldPos+1>=N&&m+1>=Y)return l(this.buildValues(C.lastComponent,G,I))||!0;else{if(Q[E]=C,C.oldPos+1>=N)H=Math.min(H,E-1);if(m+1>=Y)R=Math.max(R,E+1)}}c++};if(b)(function E(){setTimeout(function(){if(c>X||Date.now()>d)return b(void 0);if(!h())E()},0)})();else while(c<=X&&Date.now()<=d){let E=h();if(E)return E}}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,c=N-b,X=0;while(c+1<l&&N+1<Y&&this.equals(Z[N+1],G[c+1],W))if(c++,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,c}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,c=0;for(;Y<l;Y++){let X=b[Y];if(!X.removed){if(!X.added&&this.useLongestToken){let F=G.slice(N,N+X.count);F=F.map(function(d,Q){let m=Z[c+Q];return m.length>d.length?m:d}),X.value=this.join(F)}else X.value=this.join(G.slice(N,N+X.count));if(N+=X.count,!X.added)c+=X.count}else X.value=this.join(Z.slice(c,c+X.count)),c+=X.count}return b}}function ayI(I,G,Z){return Icb.diff(I,G,Z)}function Gcb(I,G){if(G.stripTrailingCr)I=I.replace(/\r\n/g,`
6827
6827
  `);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 v9G,Icb;var E9G=g(()=>{v9G=class v9G extends Te{constructor(){super(...arguments);this.tokenize=Gcb}equals(I,G,Z){if(Z.ignoreWhitespace){if(!Z.newlineIsToken||!I.includes(`
6828
6828
  `))I=I.trim();if(!Z.newlineIsToken||!G.includes(`
@@ -6944,7 +6944,7 @@ Rules:
6944
6944
  - Your response will be returned directly to the parent agent
6945
6945
 
6946
6946
  TASK:
6947
- ${I.task}`,m=yield*kc.runRecursive({agent:X,userInput:Q,sessionId:G.sessionId??G.conversationId??`session-${Date.now()}`,conversationId:`subagent-conv-${++XCG}-${Date.now()}`,maxIterations:G.parentMaxIterations??ay,ephemeralRegionId:c,...G.getAutoApprovePolicy?{autoApprovePolicy:G.getAutoApprovePolicy}:{},...G.autoApprovedCommands?{autoApprovedCommands:G.autoApprovedCommands}:{},...G.autoApprovedTools?{autoApprovedTools:G.autoApprovedTools}:{},...G.onAutoApproveCommand?{onAutoApproveCommand:G.onAutoApproveCommand}:{},...G.onAutoApproveTool?{onAutoApproveTool:G.onAutoApproveTool}:{}}).pipe(w.tapError(()=>w.sync(()=>JI.collapseEphemeral(c,{line:bI.dim(bI.italic(`${YZ().error} ${Y} failed`)),durationMs:Date.now()-N}))),w.onInterrupt(()=>w.sync(()=>JI.collapseEphemeral(c,{line:bI.dim(bI.italic(`${YZ().error} ${Y} interrupted`)),durationMs:Date.now()-N}))));if(m.costUSD&&G.recordChildCost)G.recordChildCost(m.costUSD);let R=m.content;if(!R?.trim()&&m.messages?.length){let A=[];for(let k of m.messages)if(k.role==="assistant"&&typeof k.content==="string"&&k.content.trim())A.push(k.content.trim());if(A.length>0)R=`[Sub-agent reached iteration limit. Partial results below]
6947
+ ${I.task}`;if(G.emitEvent)yield*G.emitEvent({type:"subagent_start",task:l,agentName:Y});let m=yield*kc.runRecursive({agent:X,userInput:Q,sessionId:G.sessionId??G.conversationId??`session-${Date.now()}`,conversationId:`subagent-conv-${++XCG}-${Date.now()}`,maxIterations:G.parentMaxIterations??ay,ephemeralRegionId:c,...G.getAutoApprovePolicy?{autoApprovePolicy:G.getAutoApprovePolicy}:{},...G.autoApprovedCommands?{autoApprovedCommands:G.autoApprovedCommands}:{},...G.autoApprovedTools?{autoApprovedTools:G.autoApprovedTools}:{},...G.onAutoApproveCommand?{onAutoApproveCommand:G.onAutoApproveCommand}:{},...G.onAutoApproveTool?{onAutoApproveTool:G.onAutoApproveTool}:{}}).pipe(w.tapError(()=>w.sync(()=>JI.collapseEphemeral(c,{line:bI.dim(bI.italic(`${YZ().error} ${Y} failed`)),durationMs:Date.now()-N}))),w.onInterrupt(()=>w.sync(()=>JI.collapseEphemeral(c,{line:bI.dim(bI.italic(`${YZ().error} ${Y} interrupted`)),durationMs:Date.now()-N}))),w.ensuring(G.emitEvent?G.emitEvent({type:"subagent_complete"}):w.void));if(m.costUSD&&G.recordChildCost)G.recordChildCost(m.costUSD);let R=m.content;if(!R?.trim()&&m.messages?.length){let A=[];for(let k of m.messages)if(k.role==="assistant"&&typeof k.content==="string"&&k.content.trim())A.push(k.content.trim());if(A.length>0)R=`[Sub-agent reached iteration limit. Partial results below]
6948
6948
 
6949
6949
  ${A.join(`
6950
6950
 
@@ -7242,7 +7242,7 @@ ${yG.warning(YZ().arrow)} ${yG.warning(I)} is using tools: ${yG.primary(W)}
7242
7242
  `)}function EoG(I,G,Z){let b=[];switch(G.type){case"stream_start":return I.lastAgentHeaderWritten=!0,I.currentProvider=G.provider,I.currentModel=G.model,I.lastAppliedTextSequence=-1,I.isThinking=!1,b.push({type:"log",message:Z(Dc.createElement(gB,null,Dc.createElement(H1,{color:LI.agent},`${YZ().note} `),Dc.createElement(H1,{color:LI.agent,bold:!0},I.agentName),Dc.createElement(H1,{dimColor:!0},` · ${G.provider}/${G.model}`))),timestamp:new Date}),{activity:{phase:"awaiting",agentName:I.agentName,provider:G.provider,model:G.model,label:sSb()},outputs:b};case"thinking_start":return I.isThinking=!0,{activity:HWI(I),outputs:b};case"thinking_chunk":return{activity:HWI(I),outputs:b};case"thinking_complete":return I.isThinking=!1,{activity:HWI(I),outputs:b};case"text_start":return I.lastAppliedTextSequence=-1,{activity:{phase:"streaming",agentName:I.agentName,text:""},outputs:b};case"text_chunk":{if(G.sequence>I.lastAppliedTextSequence)I.lastAppliedTextSequence=G.sequence;return{activity:HWI(I),outputs:b}}case"tools_detected":{let W=new Set(G.toolsRequiringApproval),l=new Map;for(let N of G.toolNames)l.set(N,(l.get(N)??0)+1);let Y=Array.from(l.entries()).map(([N,c])=>{let X=c>1?`${N} ×${c}`:N;return W.has(N)?`${X} (requires approval)`:X}).join(", ");return b.push({type:"log",message:"",timestamp:new Date}),b.push({type:"info",message:Z(oSb(`Tools: ${Y}`)),timestamp:new Date}),{activity:null,outputs:b}}case"tool_call":return{activity:null,outputs:b};case"tool_execution_start":{let W=G.toolName==="manage_todos"?rSb(G.arguments):void 0,l=sq(G.toolName,G.arguments,G.metadata!==void 0?{metadata:G.metadata}:void 0);if(W)I.activeTools.set(G.toolCallId,{toolName:G.toolName,startedAt:Date.now(),todoSnapshot:W});else I.activeTools.set(G.toolCallId,{toolName:G.toolName,startedAt:Date.now()});return b.push({type:"info",message:`${G.toolName}${l.length>0?` ${l}`:""}`,timestamp:new Date}),{activity:JoG(I),outputs:b}}case"tool_execution_complete":{let W=I.activeTools.get(G.toolCallId),l=W?.toolName;I.activeTools.delete(G.toolCallId);let Y=G.summary?.trim();if(l==="manage_todos"&&W?.todoSnapshot&&W.todoSnapshot.length>0)Y=`Todo list
7243
7243
  ${eSb(W.todoSnapshot)}`;if(!Y&&l&&G.result)Y=RWI(l,G.result);let c=(Y&&Y.length>0?Y:l??"Tool").includes(`
7244
7244
  `);if(Y&&Y.length>0&&c){let F=Y.split(`
7245
- `),d=(F[0]??"").trim().length>0?(F[0]??"").trim():l??"Tool",Q=F.slice(1);b.push({type:"log",message:Z(Dc.createElement(gB,{paddingLeft:WW.content,flexDirection:"column",borderStyle:"round",borderColor:LI.toolBorder,paddingX:1},Dc.createElement(gB,null,Dc.createElement(H1,{color:LI.success},`${YZ().success} `),Dc.createElement(H1,{color:LI.agent},d),Dc.createElement(H1,{dimColor:!0},` (${G.durationMs}ms)`)),...Q.map((m,R)=>Dc.createElement(gB,{key:`tool-result-line-${R}`},Dc.createElement(H1,m.includes("\x1B[")?{}:{dimColor:!0},m))))),timestamp:new Date})}else{let F=Y&&Y.length>0?Y:l??"Tool";b.push({type:"log",message:Z(Dc.createElement(gB,{paddingLeft:WW.content},Dc.createElement(H1,{color:LI.success},`${YZ().success} `),Dc.createElement(H1,{color:LI.agent},F),Dc.createElement(H1,{dimColor:!0},` (${G.durationMs}ms)`))),timestamp:new Date})}return b.push({type:"log",message:"",timestamp:new Date}),{activity:I.activeTools.size>0?JoG(I):{phase:"idle"},outputs:b}}case"usage_update":return{activity:null,outputs:b};case"error":return b.push({type:"error",message:`Error: ${G.error.message}`,timestamp:new Date}),{activity:{phase:"error",message:G.error.message},outputs:b};case"complete":return{activity:{phase:"complete"},outputs:b}}}var hoG;var yoG=g(()=>{uB();VN();fW();hoG=["is tuning up","is counting in","is riffing","is finding the groove","is warming up the horns","is setting the tempo","is taking it from the top","is improvising","is reading the charts","is picking up the rhythm","is working out the changes","is in the woodshed"]});function CoG(I){if(I.length===0)return 0;let G=ITb(I),Z=G<I.length,b=Z?G:Math.max(0,I.length-256);if(b<=0)return mgI(I);let W=[ZTb(I,b),bTb(I,b),WTb(I,b),lTb(I,b),YTb(I,b)].filter((Y)=>Y!==null);if(Z)W.push(b);if(W.length===0)return mgI(I);let l=Math.max(...W);if(VTb(I,l))return mgI(I);return l}function AoG(I){if(LoG(I)!==null)return!0;let G=I.lastIndexOf(`
7245
+ `),d=(F[0]??"").trim().length>0?(F[0]??"").trim():l??"Tool",Q=F.slice(1);b.push({type:"log",message:Z(Dc.createElement(gB,{paddingLeft:WW.content,flexDirection:"column",borderStyle:"round",borderColor:LI.toolBorder,paddingX:1},Dc.createElement(gB,null,Dc.createElement(H1,{color:LI.success},`${YZ().success} `),Dc.createElement(H1,{color:LI.agent},d),Dc.createElement(H1,{dimColor:!0},` (${G.durationMs}ms)`)),...Q.map((m,R)=>Dc.createElement(gB,{key:`tool-result-line-${R}`},Dc.createElement(H1,m.includes("\x1B[")?{}:{dimColor:!0},m))))),timestamp:new Date})}else{let F=Y&&Y.length>0?Y:l??"Tool";b.push({type:"log",message:Z(Dc.createElement(gB,{paddingLeft:WW.content},Dc.createElement(H1,{color:LI.success},`${YZ().success} `),Dc.createElement(H1,{color:LI.agent},F),Dc.createElement(H1,{dimColor:!0},` (${G.durationMs}ms)`))),timestamp:new Date})}return b.push({type:"log",message:"",timestamp:new Date}),{activity:I.activeTools.size>0?JoG(I):{phase:"idle"},outputs:b}}case"usage_update":case"approval_required":case"approval_resolved":case"subagent_start":case"subagent_complete":return{activity:null,outputs:b};case"error":return b.push({type:"error",message:`Error: ${G.error.message}`,timestamp:new Date}),{activity:{phase:"error",message:G.error.message},outputs:b};case"complete":return{activity:{phase:"complete"},outputs:b}}}var hoG;var yoG=g(()=>{uB();VN();fW();hoG=["is tuning up","is counting in","is riffing","is finding the groove","is warming up the horns","is setting the tempo","is taking it from the top","is improvising","is reading the charts","is picking up the rhythm","is working out the changes","is in the woodshed"]});function CoG(I){if(I.length===0)return 0;let G=ITb(I),Z=G<I.length,b=Z?G:Math.max(0,I.length-256);if(b<=0)return mgI(I);let W=[ZTb(I,b),bTb(I,b),WTb(I,b),lTb(I,b),YTb(I,b)].filter((Y)=>Y!==null);if(Z)W.push(b);if(W.length===0)return mgI(I);let l=Math.max(...W);if(VTb(I,l))return mgI(I);return l}function AoG(I){if(LoG(I)!==null)return!0;let G=I.lastIndexOf(`
7246
7246
  `);if((G===-1?I:I.slice(G+1)).trimStart().startsWith("|"))return!0;return!1}function ITb(I){let G=LoG(I);if(G!==null)return G;let Z=GTb(I);if(Z!==null)return Z;return I.length}function LoG(I){let G=/^(```|~~~)/gm,Z=null,b=null,W;while((W=G.exec(I))!==null)if(Z===null)Z=W[1],b=W.index;else if(W[1]===Z)Z=null,b=null;return b}function wWI(I){return/^\s*([-*+]\s|\d+\.\s)/.test(I)}function GTb(I){let G=I.split(`
7247
7247
  `),Z=[],b=0;for(let c of G)Z.push(b),b+=c.length+1;let W=null,l=-1,Y=G.length-1;while(Y>=0)if(wWI(G[Y])){let c=Y;while(c>0&&wWI(G[c-1]))c-=1;if(W===null)W=c,l=Y+1;Y=c-1}else Y-=1;if(W===null)return null;if(Z[l-1]+G[l-1].length>=I.length-256)return Z[W]??null;return null}function ZTb(I,G){let Z=I.slice(0,G),b=-1;for(let W of["```\n",`~~~
7248
7248
  `]){let l=Z.lastIndexOf(W);if(l!==-1){let Y=l+W.length;if(Y<=G)b=Math.max(b,Y)}}return b===-1?null:b}function bTb(I,G){let Z=I.lastIndexOf(`
@@ -7545,13 +7545,13 @@ ${N.join(`
7545
7545
  `;return`${JSON.stringify({ok:!0,answer:I.answer,costUSD:I.costUSD,tokenUsage:I.tokenUsage,toolCalls:I.toolCalls})}
7546
7546
  `}function aMI(I,G,Z=0){return G.json?`${JSON.stringify({ok:!1,error:I,costUSD:Z})}
7547
7547
  `:`${I}
7548
- `}function jMI(I){return gFW.includes(I)}function DMI(I){return UFW.includes(I)}function BFW(I){let G=I.responseMessages&&I.responseMessages.length>0?I.responseMessages:[...I.priorRecord?.messages??[],{role:"user",content:I.prompt},{role:"assistant",content:I.responseContent}];return{conversationId:I.conversationId,title:I.priorRecord?.title??I.prompt.trim().slice(0,80),agentId:I.agentId,startedAt:I.priorRecord?.startedAt??I.now,endedAt:I.now,messageCount:G.length,messages:G}}function OFW(I){return Object.prototype.hasOwnProperty.call(MMI,I)}function qMI(I){let G=new Set(["error"]),Z=I.split(",").map((b)=>b.trim().toLowerCase()).filter((b)=>b.length>0);for(let b of Z){if(b==="all"){for(let W of Object.values(MMI))for(let l of W)G.add(l);continue}if(!OFW(b))return{ok:!1,error:`Invalid --events category "${b}". Expected: tools, reasoning, text, usage, all.`};for(let W of MMI[b])G.add(W)}return{ok:!0,types:G}}function xFW(){if(process.stdin.readableEnded)return Promise.resolve("");return new Promise((I,G)=>{let Z=[];process.stdin.on("data",(b)=>Z.push(b)),process.stdin.on("end",()=>I(Buffer.concat(Z).toString("utf-8"))),process.stdin.on("error",G)})}function $QZ(I,G,Z){let b={json:Z.json};return w.gen(function*(){let W=I.trim();if(W.length===0)return yield*DYI("No agent specified. Use --agent <agentId>.",b);let l=G??"";if(l.trim().length===0&&!process.stdin.isTTY)l=yield*w.tryPromise({try:()=>xFW(),catch:()=>Error("Failed to read prompt from stdin.")}).pipe(w.catchAll(()=>w.succeed("")));if(l.trim().length===0)return yield*DYI("No prompt provided. Pass it as an argument or pipe it via stdin.",b);let Y=yield*g0(W).pipe(w.catchTag("StorageNotFoundError",()=>w.fail(new Qk({agentId:W,suggestion:Y3.checkAgentExists(W)})))),N=Z.reasoningEffort!==void 0?{...Y,config:{...Y.config,reasoningEffort:Z.reasoningEffort}}:Y,c=Z.conversationId?.trim();if(c!==void 0&&c.length===0)return yield*DYI("Invalid --conversation id: must be non-empty.",b);let X=c!==void 0?yield*LrG(Y.id,c):null,F=Z.approvalPolicy,d=`run-${Y.id}-${Date.now()}`,Q=kc.run({agent:N,userInput:l,sessionId:d,conversationId:c??d,...X!==null?{conversationHistory:X.messages}:{},...F!==void 0?{autoApprovePolicy:F}:{},...Z.maxIterations!=null?{maxIterations:Z.maxIterations}:{}}),m=yield*Z.timeoutMs!=null?Q.pipe(w.timeoutFail({duration:Hl.millis(Z.timeoutMs),onTimeout:()=>Error(`Run exceeded the ${Z.timeoutMs}ms timeout.`)})):Q;if(c!==void 0){let E=BFW({agentId:Y.id,conversationId:c,prompt:l,priorRecord:X,responseContent:m.content,responseMessages:m.messages,now:new Date().toISOString()});yield*ZS(E).pipe(w.catchAll((C)=>w.sync(()=>{process.stderr.write(`Warning: failed to save conversation "${c}": ${eq(C)}
7549
- `)})))}let R=m.usage?.promptTokens??0,H=m.usage?.completionTokens??0,h=(m.toolCalls??[]).map((E)=>({id:E.id,name:E.function?.name??"",arguments:E.function?.arguments??""}));yield*MFW(KMI({answer:m.content,costUSD:m.costUSD??0,tokenUsage:{promptTokens:R,completionTokens:H,totalTokens:R+H},toolCalls:h},b))}).pipe(w.catchAll((W)=>DYI(eq(W),b)),w.provide(CT(Z.eventTypes??new Set)))}var gFW,UFW,MMI,MFW=(I)=>w.sync(()=>{process.stdout.write(I)}),DYI=(I,G,Z=0)=>w.sync(()=>{let b=aMI(I,G,Z);if(G.json)process.stdout.write(b);else process.stderr.write(b);process.exitCode=1});var SMI=g(()=>{UI();OC();aE();xMI();OY();BB();WS();gFW=["read-only","low-risk","high-risk"];UFW=["disable","low","medium","high"];MMI={tools:["tools_detected","tool_call","tool_execution_start","tool_execution_complete"],reasoning:["thinking_start","thinking_chunk","thinking_complete"],text:["text_start","text_chunk"],usage:["stream_start","usage_update","complete"]}});import iQZ from"node:process";function TMI(){let{env:I}=iQZ,{TERM:G,TERM_PROGRAM:Z}=I;if(iQZ.platform!=="win32")return G!=="linux";return Boolean(I.WT_SESSION)||Boolean(I.TERMINUS_SUBLIME)||I.ConEmuTask==="{cmd::Cmder}"||Z==="Terminus-Sublime"||Z==="vscode"||G==="xterm-256color"||G==="alacritty"||G==="rxvt-unicode"||G==="rxvt-unicode-256color"||I.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var fQZ=()=>{};var sQZ,oQZ,KFW,aFW,jFW,DFW,qFW,rQZ,sMl;var tQZ=g(()=>{fQZ();sQZ={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"█",squareDarkShade:"▓",squareMediumShade:"▒",squareLightShade:"░",squareTop:"▀",squareBottom:"▄",squareLeft:"▌",squareRight:"▐",squareCenter:"■",bullet:"●",dot:"․",ellipsis:"…",pointerSmall:"›",triangleUp:"▲",triangleUpSmall:"▴",triangleDown:"▼",triangleDownSmall:"▾",triangleLeftSmall:"◂",triangleRightSmall:"▸",home:"⌂",heart:"♥",musicNote:"♪",musicNoteBeamed:"♫",arrowUp:"↑",arrowDown:"↓",arrowLeft:"←",arrowRight:"→",arrowLeftRight:"↔",arrowUpDown:"↕",almostEqual:"≈",notEqual:"≠",lessOrEqual:"≤",greaterOrEqual:"≥",identical:"≡",infinity:"∞",subscriptZero:"₀",subscriptOne:"₁",subscriptTwo:"₂",subscriptThree:"₃",subscriptFour:"₄",subscriptFive:"₅",subscriptSix:"₆",subscriptSeven:"₇",subscriptEight:"₈",subscriptNine:"₉",oneHalf:"½",oneThird:"⅓",oneQuarter:"¼",oneFifth:"⅕",oneSixth:"⅙",oneEighth:"⅛",twoThirds:"⅔",twoFifths:"⅖",threeQuarters:"¾",threeFifths:"⅗",threeEighths:"⅜",fourFifths:"⅘",fiveSixths:"⅚",fiveEighths:"⅝",sevenEighths:"⅞",line:"─",lineBold:"━",lineDouble:"═",lineDashed0:"┄",lineDashed1:"┅",lineDashed2:"┈",lineDashed3:"┉",lineDashed4:"╌",lineDashed5:"╍",lineDashed6:"╴",lineDashed7:"╶",lineDashed8:"╸",lineDashed9:"╺",lineDashed10:"╼",lineDashed11:"╾",lineDashed12:"−",lineDashed13:"–",lineDashed14:"‐",lineDashed15:"⁃",lineVertical:"│",lineVerticalBold:"┃",lineVerticalDouble:"║",lineVerticalDashed0:"┆",lineVerticalDashed1:"┇",lineVerticalDashed2:"┊",lineVerticalDashed3:"┋",lineVerticalDashed4:"╎",lineVerticalDashed5:"╏",lineVerticalDashed6:"╵",lineVerticalDashed7:"╷",lineVerticalDashed8:"╹",lineVerticalDashed9:"╻",lineVerticalDashed10:"╽",lineVerticalDashed11:"╿",lineDownLeft:"┐",lineDownLeftArc:"╮",lineDownBoldLeftBold:"┓",lineDownBoldLeft:"┒",lineDownLeftBold:"┑",lineDownDoubleLeftDouble:"╗",lineDownDoubleLeft:"╖",lineDownLeftDouble:"╕",lineDownRight:"┌",lineDownRightArc:"╭",lineDownBoldRightBold:"┏",lineDownBoldRight:"┎",lineDownRightBold:"┍",lineDownDoubleRightDouble:"╔",lineDownDoubleRight:"╓",lineDownRightDouble:"╒",lineUpLeft:"┘",lineUpLeftArc:"╯",lineUpBoldLeftBold:"┛",lineUpBoldLeft:"┚",lineUpLeftBold:"┙",lineUpDoubleLeftDouble:"╝",lineUpDoubleLeft:"╜",lineUpLeftDouble:"╛",lineUpRight:"└",lineUpRightArc:"╰",lineUpBoldRightBold:"┗",lineUpBoldRight:"┖",lineUpRightBold:"┕",lineUpDoubleRightDouble:"╚",lineUpDoubleRight:"╙",lineUpRightDouble:"╘",lineUpDownLeft:"┤",lineUpBoldDownBoldLeftBold:"┫",lineUpBoldDownBoldLeft:"┨",lineUpDownLeftBold:"┥",lineUpBoldDownLeftBold:"┩",lineUpDownBoldLeftBold:"┪",lineUpDownBoldLeft:"┧",lineUpBoldDownLeft:"┦",lineUpDoubleDownDoubleLeftDouble:"╣",lineUpDoubleDownDoubleLeft:"╢",lineUpDownLeftDouble:"╡",lineUpDownRight:"├",lineUpBoldDownBoldRightBold:"┣",lineUpBoldDownBoldRight:"┠",lineUpDownRightBold:"┝",lineUpBoldDownRightBold:"┡",lineUpDownBoldRightBold:"┢",lineUpDownBoldRight:"┟",lineUpBoldDownRight:"┞",lineUpDoubleDownDoubleRightDouble:"╠",lineUpDoubleDownDoubleRight:"╟",lineUpDownRightDouble:"╞",lineDownLeftRight:"┬",lineDownBoldLeftBoldRightBold:"┳",lineDownLeftBoldRightBold:"┯",lineDownBoldLeftRight:"┰",lineDownBoldLeftBoldRight:"┱",lineDownBoldLeftRightBold:"┲",lineDownLeftRightBold:"┮",lineDownLeftBoldRight:"┭",lineDownDoubleLeftDoubleRightDouble:"╦",lineDownDoubleLeftRight:"╥",lineDownLeftDoubleRightDouble:"╤",lineUpLeftRight:"┴",lineUpBoldLeftBoldRightBold:"┻",lineUpLeftBoldRightBold:"┷",lineUpBoldLeftRight:"┸",lineUpBoldLeftBoldRight:"┹",lineUpBoldLeftRightBold:"┺",lineUpLeftRightBold:"┶",lineUpLeftBoldRight:"┵",lineUpDoubleLeftDoubleRightDouble:"╩",lineUpDoubleLeftRight:"╨",lineUpLeftDoubleRightDouble:"╧",lineUpDownLeftRight:"┼",lineUpBoldDownBoldLeftBoldRightBold:"╋",lineUpDownBoldLeftBoldRightBold:"╈",lineUpBoldDownLeftBoldRightBold:"╇",lineUpBoldDownBoldLeftRightBold:"╊",lineUpBoldDownBoldLeftBoldRight:"╉",lineUpBoldDownLeftRight:"╀",lineUpDownBoldLeftRight:"╁",lineUpDownLeftBoldRight:"┽",lineUpDownLeftRightBold:"┾",lineUpBoldDownBoldLeftRight:"╂",lineUpDownLeftBoldRightBold:"┿",lineUpBoldDownLeftBoldRight:"╃",lineUpBoldDownLeftRightBold:"╄",lineUpDownBoldLeftBoldRight:"╅",lineUpDownBoldLeftRightBold:"╆",lineUpDoubleDownDoubleLeftDoubleRightDouble:"╬",lineUpDoubleDownDoubleLeftRight:"╫",lineUpDownLeftDoubleRightDouble:"╪",lineCross:"╳",lineBackslash:"╲",lineSlash:"╱"},oQZ={tick:"✔",info:"ℹ",warning:"⚠",cross:"✘",squareSmall:"◻",squareSmallFilled:"◼",circle:"◯",circleFilled:"◉",circleDotted:"◌",circleDouble:"◎",circleCircle:"ⓞ",circleCross:"ⓧ",circlePipe:"Ⓘ",radioOn:"◉",radioOff:"◯",checkboxOn:"☒",checkboxOff:"☐",checkboxCircleOn:"ⓧ",checkboxCircleOff:"Ⓘ",pointer:"❯",triangleUpOutline:"△",triangleLeft:"◀",triangleRight:"▶",lozenge:"◆",lozengeOutline:"◇",hamburger:"☰",smiley:"㋡",mustache:"෴",star:"★",play:"▶",nodejs:"⬢",oneSeventh:"⅐",oneNinth:"⅑",oneTenth:"⅒"},KFW={tick:"√",info:"i",warning:"‼",cross:"×",squareSmall:"□",squareSmallFilled:"■",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(○)",circleCross:"(×)",circlePipe:"(│)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[×]",checkboxOff:"[ ]",checkboxCircleOn:"(×)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"∆",triangleLeft:"◄",triangleRight:"►",lozenge:"♦",lozengeOutline:"◊",hamburger:"≡",smiley:"☺",mustache:"┌─┐",star:"✶",play:"►",nodejs:"♦",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},aFW={...sQZ,...oQZ},jFW={...sQZ,...KFW},DFW=TMI(),qFW=DFW?aFW:jFW,rQZ=qFW,sMl=Object.entries(oQZ)});import _MI from"react";import{Box as SFW,Text as eQZ}from"ink";function TFW({isSelected:I=!1}){return _MI.createElement(SFW,{marginRight:1},I?_MI.createElement(eQZ,{color:"blue"},rQZ.pointer):_MI.createElement(eQZ,null," "))}var PMI;var nMI=g(()=>{tQZ();PMI=TFW});import*as ImZ from"react";import{Text as _FW}from"ink";function PFW({isSelected:I=!1,label:G}){return ImZ.createElement(_FW,{color:I?"blue":void 0},G)}var $MI;var iMI=g(()=>{$MI=PFW});function LL(I,G){if(!Array.isArray(I))throw TypeError(`Expected an array, got \`${typeof I}\`.`);if(!Number.isSafeInteger(G))throw TypeError(`The \`steps\` parameter must be an integer, got ${G}.`);let{length:Z}=I;if(Z===0)return[...I];let b=(G%Z+Z)%Z;if(b===0)return[...I];return[...I.slice(-b),...I.slice(0,-b)]}import{isDeepStrictEqual as nFW}from"node:util";import qYI,{useState as GmZ,useEffect as $FW,useRef as iFW,useCallback as fFW}from"react";import{Box as ZmZ,useInput as sFW}from"ink";function oFW({items:I=[],isFocused:G=!0,initialIndex:Z=0,indicatorComponent:b=PMI,itemComponent:W=$MI,limit:l,onSelect:Y,onHighlight:N}){let c=typeof l==="number"&&I.length>l,X=c?Math.min(l,I.length):I.length,F=X-1,[d,Q]=GmZ(Z>F?F-Z:0),[m,R]=GmZ(Z?Z>F?F:Z:0),H=iFW(I);$FW(()=>{if(!nFW(H.current.map((E)=>E.value),I.map((E)=>E.value)))Q(0),R(0);H.current=I},[I]),sFW(fFW((E,C)=>{if(E==="k"||C.upArrow){let J=(c?X:I.length)-1,y=m===0,v=c?m:J,A=y?d+1:d,k=y?v:m-1;Q(A),R(k);let L=c?LL(I,A).slice(0,X):I;if(typeof N==="function")N(L[k])}if(E==="j"||C.downArrow){let J=m===(c?X:I.length)-1,y=c?m:0,v=J?d-1:d,A=J?y:m+1;Q(v),R(A);let k=c?LL(I,v).slice(0,X):I;if(typeof N==="function")N(k[A])}if(/^[1-9]$/.test(E)){let J=Number.parseInt(E,10)-1,y=c?LL(I,d).slice(0,X):I;if(J>=0&&J<y.length){let v=y[J];if(v)Y?.(v)}}if(C.return){let J=c?LL(I,d).slice(0,X):I;if(typeof Y==="function")Y(J[m])}},[c,X,d,m,I,Y,N]),{isActive:G});let h=c?LL(I,d).slice(0,X):I;return qYI.createElement(ZmZ,{flexDirection:"column"},h.map((E,C)=>{let J=C===m;return qYI.createElement(ZmZ,{key:E.key??E.value},qYI.createElement(b,{isSelected:J}),qYI.createElement(W,{...E,isSelected:J}))}))}var fMI;var bmZ=g(()=>{nMI();iMI();fMI=oFW});var WmZ=g(()=>{nMI();iMI();bmZ()});import{Box as k3,Text as OJ,useInput as rFW}from"ink";import{useState as tFW,useEffect as eFW}from"react";import{jsx as M1,jsxs as pL}from"react/jsx-runtime";function SYI({options:I,onSelect:G,onExit:Z,title:b}){let[W,l]=tFW(0);eFW(()=>{l(Math.floor(Math.random()*lmZ.length))},[]),rFW((N,c)=>{if(c.escape)Z();if(N==="q")Z()});let Y=I.map((N)=>({label:N.label,value:N.value}));return pL(k3,{flexDirection:"column",paddingX:2,paddingY:1,children:[pL(k3,{flexDirection:"column",marginBottom:1,children:[pL(OJ,{bold:!0,color:LI.primary,children:[sMI.note," Jazz"]}),pL(OJ,{dimColor:!0,children:["v",F0.version," · your everyday agentic CLI"]})]}),pL(k3,{flexDirection:"column",marginTop:1,paddingY:0,children:[M1(k3,{marginBottom:1,children:M1(OJ,{bold:!0,color:LI.selected,children:b||"What would you like to do?"})}),M1(fMI,{items:Y,onSelect:(N)=>G(N.value),indicatorComponent:IdW,itemComponent:GdW})]}),pL(k3,{marginTop:1,children:[pL(OJ,{color:LI.primary,children:[sMI.note," "]}),M1(OJ,{dimColor:!0,italic:!0,wrap:"wrap",children:lmZ[W]})]}),M1(k3,{marginTop:1,children:M1(OJ,{dimColor:!0,children:"↑↓ move · enter select · q quit"})})]})}function IdW({isSelected:I=!1}){return M1(k3,{marginRight:1,children:I?M1(OJ,{color:LI.primary,bold:!0,children:sMI.rail}):M1(OJ,{children:" "})})}function GdW({isSelected:I=!1,label:G}){return M1(k3,{children:M1(OJ,{color:I?LI.selected:LI.secondary,bold:I,children:G})})}var sMI,lmZ;var oMI=g(()=>{WmZ();VN();fW();s6();sMI=YZ(),lmZ=["Type '/help' in chat to see every command and keyboard shortcut","Use Arrow Up in chat to recall your previous messages","Press Alt+Enter in chat to write multi-line messages","Press Ctrl+R after a response to expand the agent's reasoning","Run 'jazz agent list' to see all your active agents","Agents work best with specific, focused descriptions","Delete unused agents to keep your workspace clean","Use the email skill (Himalaya) to let agents read, send, and manage your inbox","Use the calendar skill (khal) to let agents view and manage your schedule","The 'fs' tools allow agents to read and write files in your project","Enable Web Search to give your agent up-to-date knowledge","Agents can use 'grep' to search your codebase instantly","Use /tools to see which tools are available","Jazz supports MCP! Connect to Notion, GitHub, and 100+ other services","Use Agent Skills to teach complex workflows to your agents","Switch LLM models mid-chat if you need more intelligence or speed","Local models via Ollama are supported for offline privacy","Ask agents to 'plan first' for complex coding tasks","Agents can read PDFs! Just give them the file path","Ask an agent to 'summarize this conversation' to catch up","Chain commands: 'Find TODOs then create a summary file'","Use '/new' to clear the context and start a new conversation","Use 'jazz config show' to see your configuration","Check 'jazz update' regularly for new features","You can have multiple agents running in different terminal tabs","Agents can write their own tests before writing code","Try asking an agent to 'optimize your system prompt'","Jazz agents never execute dangerous commands without approval","The 'shell' tool is sandboxed but powerful - use with care!"]});import ZdW from"react";function YmZ(){return w.gen(function*(){let I=!0;while(I)switch(yield*bdW([{label:"LLM Providers (API Keys)",value:"llm-providers"},{label:"Web Search Providers",value:"web-search"},{label:"Output & Display",value:"output-display"},{label:"Logging",value:"logging"},{label:"Notifications",value:"notifications"},{label:"Back to Main Menu",value:"back"}])){case"llm-providers":{yield*WdW();break}case"web-search":{yield*ldW();break}case"output-display":{yield*YdW();break}case"logging":{yield*VdW();break}case"notifications":{yield*NdW();break}case"back":{I=!1;break}}})}function bdW(I){return w.async((G)=>{JI.setCustomView(ZdW.createElement(SYI,{options:I,title:"Configuration",onSelect:(Z)=>{JI.setCustomView(null),G(w.succeed(Z))},onExit:()=>{JI.setCustomView(null),G(w.succeed("back"))}}))})}function WdW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ;while(!0){let Z=yield*G.appConfig,b=dd.map((c)=>{let X=!!Z.llm?.[c]?.api_key;return{name:`${yV(c)} ${X?"(configured)":""}`,value:c}});b.push({name:"Back",value:"back"});let W=yield*I.select("Select provider to configure:",{choices:b});if(!W||W==="back")break;let l=W,Y=yV(l);yield*I.info(`Configuring ${Y}...`);let N=yield*I.password(`Enter API Key for ${Y} (leave empty to keep current):`);if(N.trim())yield*G.set(`llm.${l}.api_key`,N),yield*I.success(`Configuration for ${Y} updated.`);else yield*I.info("No changes made.");yield*I.log("")}})}function ldW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ;while(!0){let Z=yield*G.appConfig,l=[{name:`Select external provider (current: ${Z.web_search?.provider??"Built-in (if available)"})`,value:"select-provider"},...Y1.map((N)=>{let c=!!Z.web_search?.[N.value]?.api_key;return{name:`${N.name} API Key ${c?"(configured)":""}`,value:N.value}}),{name:"Back",value:"back"}],Y=yield*I.select("Web Search Configuration:",{choices:l});if(!Y||Y==="back")break;if(Y==="select-provider"){let N=[{name:"None (use built-in if available)",value:"none"},...Y1.map((X)=>({name:X.name,value:X.value}))],c=yield*I.select("Select provider:",{choices:N});if(c==="none")yield*G.set("web_search.provider",void 0),yield*I.success("External provider disabled. Built-in provider web search will be used if available.");else if(c)yield*G.set("web_search.provider",c),yield*I.success(`External provider set to ${c}.`)}else{let N=Y;yield*I.info(`Configuring ${N}...`);let c=yield*I.password(`Enter API Key for ${N} (leave empty to keep current):`);if(c.trim())yield*G.set(`web_search.${N}.api_key`,c),yield*I.success(`Configuration for ${N} updated.`);else yield*I.info("No changes made.")}yield*I.log("")}})}function YdW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ,Z=function*(b){let W=yield*I.confirm(b.prompt,b.currentValue);yield*G.set(b.configKey,W),yield*I.success(`${b.label} ${W?"enabled":"disabled"}.`)};while(!0){let b=yield*G.appConfig,W=pQ(b),l=b.output?.showMetrics??!0,Y=b.output?.colorProfile??"auto",N=yield*I.select("Output & display settings:",{choices:[{name:`Output mode (${W.mode})`,value:"mode"},{name:`Color profile (${Y})`,value:"color-profile"},{name:`Show thinking (${W.showThinking?"on":"off"})`,value:"show-thinking"},{name:`Show tool execution (${W.showToolExecution?"on":"off"})`,value:"show-tool-execution"},{name:`Show metrics (${l?"on":"off"})`,value:"show-metrics"},{name:"Back",value:"back"}]});if(!N||N==="back")break;switch(N){case"mode":{let c=yield*I.select("Select output mode:",{choices:[{name:"Hybrid (styled, copy-paste friendly)",value:"hybrid"},{name:"Raw (plain text)",value:"raw"},{name:"Rendered (styled)",value:"rendered"},{name:"Quiet (suppress output, for cron/background)",value:"quiet"}]});if(c)yield*G.set("output.mode",c),yield*I.success(`Output mode set to ${c}.`);break}case"color-profile":{let c=yield*I.select("Select color profile:",{choices:[{name:"Auto (default)",value:"auto"},{name:"Full",value:"full"},{name:"Basic",value:"basic"},{name:"None",value:"none"}]});if(c)if(c==="auto")yield*G.set("output.colorProfile",void 0),yield*I.success("Color profile set to auto.");else yield*G.set("output.colorProfile",c),yield*I.success(`Color profile set to ${c}.`);break}case"show-thinking":{yield*Z({prompt:"Show thinking output?",currentValue:W.showThinking,configKey:"output.showThinking",label:"Show thinking"});break}case"show-tool-execution":{yield*Z({prompt:"Show tool execution?",currentValue:W.showToolExecution,configKey:"output.showToolExecution",label:"Show tool execution"});break}case"show-metrics":{yield*Z({prompt:"Show performance metrics?",currentValue:l,configKey:"output.showMetrics",label:"Show metrics"});break}}yield*I.log("")}})}function NdW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ;while(!0){let Z=yield*G.appConfig,b=Z.notifications?.enabled??!0,W=Z.notifications?.sound??!0,l=yield*I.select("Notification settings:",{choices:[{name:`System notifications (${b?"on":"off"})`,value:"enabled"},{name:`Notification sound (${W?"on":"off"})`,value:"sound"},{name:"Back",value:"back"}]});if(!l||l==="back")break;switch(l){case"enabled":{let Y=yield*I.confirm("Enable system notifications?",b);yield*G.set("notifications.enabled",Y),yield*I.success(`System notifications ${Y?"enabled":"disabled"}.`);break}case"sound":{let Y=yield*I.confirm("Enable notification sound?",W);yield*G.set("notifications.sound",Y),yield*I.success(`Notification sound ${Y?"enabled":"disabled"}.`);break}}yield*I.log("")}})}function VdW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ;while(!0){let b=(yield*G.appConfig).logging?.format??"plain",W=yield*I.select("Logging settings:",{choices:[{name:`Log format (${b})`,value:"format"},{name:"Back",value:"back"}]});if(!W||W==="back")break;if(W==="format"){let l=yield*I.select("Select log format:",{choices:[{name:"Plain (human readable)",value:"plain"},{name:"JSON (structured for log processors)",value:"json"},{name:"TOON (token-efficient for LLM analysis)",value:"toon"}]});if(l)yield*G.set("logging.format",l),yield*I.success(`Log format set to ${l}.`)}yield*I.log("")}})}var NmZ=g(()=>{UI();kU();KH();uN();nN();gy();MR();nQ();oMI()});import cdW from"react";function VmZ(){return w.gen(function*(){let I=yield*bc,G=yield*pZ,Z=yield*bZ;yield*Z.setTitle("\uD83C\uDFB7 Jazz"),yield*ddW(G,Z);let b=!1;while(!b){let W=yield*I.listAgents(),Y=yield*(yield*HJ).get("wizard.lastUsedAgentId").pipe(w.map((d)=>typeof d==="string"?d:null),w.catchAll(()=>w.succeed(null))),N=null;if(Y){let d=yield*w.either(I.getAgent(Y));if(d._tag==="Right")N=d.right}let c=!1;for(let d of W)if((yield*bS(d.id).pipe(w.catchAll(()=>w.succeed({agentId:d.id,conversations:[]})))).conversations.length>0){c=!0;break}let X=[];if(N)X.push({label:`Resume: ${N.name}`,value:"continue"});if(W.length>0)X.push({label:"New conversation",value:"new-conversation"});if(c)X.push({label:"Resume conversation",value:"resume-conversation"});if(X.push({label:"Create agent",value:"create-agent"}),W.length>0)X.push({label:"List agents",value:"list-agents"},{label:"Edit agent",value:"edit-agent"},{label:"Delete agent",value:"delete-agent"},{label:"Update configuration",value:"config"});else X.push({label:"Update configuration",value:"config"});switch(X.push({label:"Exit",value:"exit"}),yield*XdW(X)){case"continue":{if(N)yield*TYI(N),yield*Z.clear();break}case"new-conversation":{let d=yield*rMI(W,Z,"Select an agent to chat with:",Y);if(d)yield*TYI(d),yield*Z.clear();break}case"resume-conversation":{yield*FdW(W,Z),yield*Z.clear();break}case"create-agent":{let d=W.length,Q=yield*MYI().pipe(w.either);if(Q._tag==="Left"){yield*Z.error(`Failed to create agent: ${String(Q.left)}`),yield*Z.clear();break}let m=yield*I.listAgents().pipe(w.catchAll((H)=>w.gen(function*(){return yield*Z.error(`Failed to retrieve agents: ${String(H)}`),[]})));if(m.length===0||m.length<=d){yield*Z.clear();break}let R=m.reduce((H,h)=>H.createdAt.getTime()>h.createdAt.getTime()?H:h);yield*TYI(R).pipe(w.catchAll((H)=>w.gen(function*(){yield*Z.error(`Failed to start chat with created agent: ${String(H)}`)}))),yield*Z.clear();break}case"edit-agent":{let d=yield*rMI(W,Z,"Select an agent to edit:",Y);if(d)yield*aYI(d.id).pipe(w.catchAll((Q)=>w.gen(function*(){yield*Z.error(`Failed to edit agent: ${String(Q)}`)}))),yield*Z.clear();break}case"list-agents":{yield*uYI().pipe(w.catchAll((d)=>w.gen(function*(){yield*Z.error(`Failed to list agents: ${String(d)}`)}))),yield*Z.ask("Press Enter to continue...",{hidden:!0}),yield*Z.clear();break}case"delete-agent":{let d=yield*rMI(W,Z,"Select an agent to delete:",Y);if(d){if(!(yield*Z.confirm(`Delete agent "${d.name}" (${d.config.llmProvider}/${d.config.llmModel})? This cannot be undone.`,!1))){yield*Z.info("Deletion cancelled."),yield*Z.ask("Press Enter to continue...",{hidden:!0}),yield*Z.clear();break}yield*gYI(d.id).pipe(w.catchAll((m)=>w.gen(function*(){yield*Z.error(`Failed to delete agent: ${String(m)}`)}))),yield*Z.ask("Press Enter to continue...",{hidden:!0}),yield*Z.clear()}break}case"config":{yield*YmZ(),yield*Z.clear();break}case"exit":default:b=!0;break}}yield*Z.log(""),yield*w.sync(()=>process.exit(0))}).pipe(w.catchAll((I)=>w.fail(I instanceof Error?I:Error(String(I)))))}function XdW(I){return w.async((G)=>{let Z=!1,b=(W)=>{if(Z)return;Z=!0,JI.setCustomView(null),G(w.succeed(W))};JI.setCustomView(cdW.createElement(SYI,{options:I,onSelect:(W)=>b(W),onExit:()=>b("exit")}))})}function rMI(I,G,Z,b){return w.gen(function*(){if(I.length===0)return yield*G.warn("No agents available."),null;let l=fA(I,b).map((N)=>{let c=N.description&&N.description!==N.name?` · ${N.description}`:"";return{name:`${N.name} · ${N.config.llmModel}${c}`,value:N.id}}),Y=yield*G.search(Z,{choices:l,placeholder:"Type to filter agents…"});if(!Y)return null;return I.find((N)=>N.id===Y)??null})}function TYI(I,G){return w.gen(function*(){let Z=yield*bZ;if(yield*(yield*HJ).set("wizard.lastUsedAgentId",I.id).pipe(w.catchAll(()=>w.void)),yield*Z.clear(),yield*Z.heading(`Starting chat with: ${I.name}`),yield*Z.log(`${I.model} - Reasoning: ${I.config.reasoningEffort??"disabled"}`),I.description)yield*Z.log(` Description: ${I.description}`);yield*Z.log(""),yield*Z.info("Type '/help' to see available special commands."),yield*Z.info("Type '/exit' to end the conversation."),yield*Z.log(""),yield*(yield*xB).startChatSession(I,G).pipe(w.catchAll((l)=>w.gen(function*(){yield*Z.error(`Chat session error: ${String(l)}`)})))})}function FdW(I,G){return w.gen(function*(){let Z=[];for(let Y of I){let N=yield*bS(Y.id).pipe(w.catchAll(()=>w.succeed({agentId:Y.id,conversations:[]})));for(let c of N.conversations)Z.push({agent:Y,conversationId:c.conversationId,title:c.title,startedAt:c.startedAt,messageCount:c.messageCount,messages:c.messages})}if(Z.length===0){yield*G.warn("No saved conversations found.");return}Z.sort((Y,N)=>new Date(N.startedAt).getTime()-new Date(Y.startedAt).getTime());let b=Z.map((Y,N)=>({name:`${Y.title} · ${Y.agent.model}`,value:String(N)})),W=yield*G.search("Select a conversation to resume:",{choices:b,placeholder:"Type to filter conversations…"});if(W===null||W===void 0)return;let l=Z[Number(W)];if(!l)return;yield*TYI(l.agent,{initialHistory:l.messages,initialConversationTitle:l.title})})}function ddW(I,G){return w.gen(function*(){if(yield*I.has("notifications.enabled"))return;yield*G.log(""),yield*G.heading("\uD83C\uDFB7 Welcome to Jazz! Let's get you set up."),yield*G.log("");let b={OPENAI_API_KEY:"openai",ANTHROPIC_API_KEY:"anthropic",GOOGLE_GENERATIVE_AI_API_KEY:"google",MISTRAL_API_KEY:"mistral",XAI_API_KEY:"xai",DEEPSEEK_API_KEY:"deepseek",GROQ_API_KEY:"groq",OPENROUTER_API_KEY:"openrouter"},W=[];for(let[Y,N]of Object.entries(b))if(process.env[Y])W.push(`${N} (${Y})`);if(W.length>0){yield*G.success("Detected API keys from environment:");for(let Y of W)yield*G.log(` • ${Y}`);yield*G.log("")}else yield*G.info("No API keys detected from environment."),yield*G.log(" Set up a key via 'Update configuration' or export OPENAI_API_KEY"),yield*G.log("");yield*G.info("Jazz can send desktop notifications for completions and approvals.");let l=yield*G.confirm("Enable desktop notifications?",!0);if(yield*I.set("notifications.enabled",l),l){let Y=yield*G.confirm("Play a sound with notifications?",!0);yield*I.set("notifications.sound",Y),yield*G.success("Notifications enabled! Change anytime in Settings.")}else yield*G.info("Notifications disabled. Enable anytime in Settings.");yield*G.log("")})}var cmZ=g(()=>{UI();uN();KE();pWI();GS();nN();WS();zMI();NmZ();gMI();BMI();nQ();oMI()});import{Box as XmZ,Text as QdW}from"ink";import _YI from"react";function dmZ(){return w.gen(function*(){let I=yield*bZ,G=yield*V1,Z=yield*N1;yield*I.heading("\uD83D\uDCCB Available Workflows"),yield*I.log("");let b=yield*G.listWorkflows();if(b.length===0){yield*I.info("No workflows found."),yield*I.log(""),yield*I.info("Create a workflow by adding a WORKFLOW.md file to:"),yield*I.log(" • ./workflows/<name>/WORKFLOW.md (local)"),yield*I.log(" • ~/.jazz/workflows/<name>/WORKFLOW.md (global)");return}let W=yield*Z.listScheduled().pipe(w.map((Q)=>new Set(Q.map((m)=>m.workflowName))),w.catchAll(()=>w.succeed(new Set))),l=14400000,{runningNames:Y,staleNames:N}=yield*w5().pipe(w.map((Q)=>{let m=new Set,R=new Set;for(let H of Q)if(H.status==="running"){let h=Date.parse(H.startedAt);if(!Number.isFinite(h))continue;if(Date.now()-h>l)R.add(H.workflowName);else m.add(H.workflowName)}return{runningNames:m,staleNames:R}}),w.catchAll(()=>w.succeed({runningNames:new Set,staleNames:new Set}))),{local:c,global:X,builtin:F}=uWI(b);function d(Q){if(Y.has(Q.name))return" ● running";if(N.has(Q.name))return" ✗ failed (stale)";if(W.has(Q.name))return" ○ scheduled";if(Q.schedule)return" — not scheduled";return""}if(c.length>0){yield*I.log("Local workflows:");for(let Q of c)yield*I.log(gWI(Q,{statusBadge:d(Q)}));yield*I.log("")}if(X.length>0){yield*I.log("Global workflows (~/.jazz/workflows):");for(let Q of X)yield*I.log(gWI(Q,{statusBadge:d(Q)}));yield*I.log("")}if(F.length>0){yield*I.log("Built-in workflows:");for(let Q of F)yield*I.log(gWI(Q,{statusBadge:d(Q)}));yield*I.log("")}yield*I.info(`Total: ${b.length} workflow(s)`)})}function QmZ(I){return w.gen(function*(){let G=yield*bZ,b=yield*(yield*V1).loadWorkflow(I).pipe(w.catchAll((W)=>w.gen(function*(){return yield*G.error(`Workflow not found: ${I}`),yield*G.info("Run 'jazz workflow list' to see available workflows."),yield*w.fail(W)})));if(yield*G.heading(`\uD83D\uDCCB Workflow: ${b.metadata.name}`),yield*G.log(""),yield*G.log(`Description: ${b.metadata.description}`),yield*G.log(`Path: ${b.metadata.path}`),b.metadata.agent)yield*G.log(`Agent: ${b.metadata.agent}`);if(b.metadata.schedule){let W=jE(b.metadata.schedule),l=W?`${W} (${b.metadata.schedule})`:b.metadata.schedule;yield*G.log(`Schedule: ${l}`)}if(b.metadata.autoApprove!==void 0)yield*G.log(`Auto-approve: ${b.metadata.autoApprove}`);if(b.metadata.skills&&b.metadata.skills.length>0)yield*G.log(`Skills: ${b.metadata.skills.join(", ")}`);if(b.metadata.catchUpOnStartup!==void 0)yield*G.log(`Catch-up on startup: ${b.metadata.catchUpOnStartup}`);if(b.metadata.maxCatchUpAge!==void 0)yield*G.log(`Max catch-up age (seconds): ${b.metadata.maxCatchUpAge}`);yield*G.log(""),yield*G.log(y5(60)),yield*G.log("Prompt:"),yield*G.log(y5(60)),yield*G.log(b.prompt)})}function mmZ(I,G){let Z=G?.json===!0,b=(l)=>Z?w.void:w.suspend(l),W=w.gen(function*(){let l=yield*bZ,Y=yield*V1,N=yield*gG,c=G?.autoApprove===!0||Z,X=G?.scheduled===!0;if(X){let k=(yield*(yield*N1).listScheduled().pipe(w.catchAll(()=>w.succeed([])))).find((L)=>L.workflowName===I);if(k?.scheduledAt){let L=new Date(k.scheduledAt).getTime(),p=Date.now(),x=60000;if(!Number.isNaN(L)&&p-L<60000){yield*N.info("Scheduler-triggered run skipped: workflow was just scheduled",{workflow:I,scheduledAt:k.scheduledAt,elapsedMs:p-L});return}}}yield*b(()=>l.heading(`\uD83D\uDE80 Running workflow: ${I}`)),yield*b(()=>l.log(""));let F=new Date().toISOString();yield*zA({workflowName:I,startedAt:F,status:"running",triggeredBy:X?"scheduled":"manual"}).pipe(w.catchAll(()=>w.void));let Q=(v)=>DE(I,{completedAt:new Date().toISOString(),status:"failed",error:v}).pipe(w.catchAll(()=>w.void)),m=yield*Y.loadWorkflow(I).pipe(w.catchAll((v)=>w.gen(function*(){return yield*Q(`Workflow not found: ${I}`),yield*b(()=>l.error(`Workflow not found: ${I}`)),yield*b(()=>l.info("Run 'jazz workflow list' to see available workflows.")),yield*w.fail(v)}))),R=G?.agent||m.metadata.agent||"default",H,h=yield*g0(R).pipe(w.either);if(h._tag==="Right")H=h.right,yield*b(()=>l.info(`Using agent: ${H.name} (${H.model})`));else{if(c){let k=`Agent '${R}' not found. Scheduled workflows require a valid agent — update the workflow or re-schedule with an existing agent.`;return yield*Q(k),yield*b(()=>l.error(`Agent '${R}' not found.`)),yield*b(()=>l.info("Scheduled workflows require a valid agent. Update the workflow or create the agent.")),yield*w.fail(Error(k))}let v=yield*f7();if(v.length===0)return yield*Q("No agents available. Create an agent first with: jazz agent create"),yield*l.error("No agents available."),yield*l.info("Create an agent first with: jazz agent create"),yield*w.fail(Error("No agents available. Create an agent first with: jazz agent create"));if(R!=="default")yield*l.warn(`Agent '${R}' not found.`);else yield*l.info("No default agent configured.");yield*l.log("");let A=yield*vmZ(v,"Select an agent to run this workflow:");if(!A){yield*DE(I,{completedAt:new Date().toISOString(),status:"skipped"}).pipe(w.catchAll(()=>w.void)),yield*l.info("Workflow cancelled.");return}H=A,yield*l.info(`Using agent: ${H.name} (${H.model})`)}let E=G?.autoApprove===!0?m.metadata.autoApprove??!0:m.metadata.autoApprove;if(E)yield*b(()=>l.info(`Auto-approve policy: ${E}`));yield*b(()=>l.log("")),yield*N.info("Starting workflow execution",{workflow:I,agent:H.name,autoApprove:E});let C=G?.maxIterations??m.metadata.maxIterations,J=kc.run({agent:H,userInput:m.prompt,sessionId:`workflow-${I}-${Date.now()}`,conversationId:`workflow-${I}-${Date.now()}`,...C!=null?{maxIterations:C}:{},...E!==void 0?{autoApprovePolicy:E}:{}}),y=yield*(G?.timeoutMs!=null?J.pipe(w.timeoutFail({duration:Hl.millis(G.timeoutMs),onTimeout:()=>Error(`Run exceeded the ${G.timeoutMs}ms timeout.`)})):J).pipe(w.tap((v)=>DE(I,{completedAt:new Date().toISOString(),status:"completed",...FmZ(v)}).pipe(w.catchAll(()=>w.void))),w.tapError((v)=>DE(I,{completedAt:new Date().toISOString(),status:"failed",error:v instanceof Error?v.message:String(v)}).pipe(w.catchAll(()=>w.void))),w.tapError(()=>w.sync(()=>{process.exitCode=1})));if(Z){let v=y.usage?.promptTokens??0,A=y.usage?.completionTokens??0,k=(y.toolCalls??[]).map((L)=>({id:L.id,name:L.function?.name??"",arguments:L.function?.arguments??""}));yield*w.sync(()=>{process.stdout.write(KMI({answer:y.content,costUSD:y.costUSD??0,tokenUsage:{promptTokens:v,completionTokens:A,totalTokens:v+A},toolCalls:k},{json:!0}))});return}if(yield*l.log(""),yield*l.success(`Workflow completed: ${I}`),c){let v={workflow:I,...FmZ(y)};yield*l.log(`[JAZZ_SUMMARY] ${JSON.stringify(v)}`)}});if(!Z)return W;return W.pipe(w.catchAll((l)=>w.sync(()=>{process.stdout.write(aMI(eq(l),{json:!0})),process.exitCode=1})),w.provide(CT(G?.eventTypes??new Set)))}function RmZ(I){return w.gen(function*(){let G=yield*bZ,Z=yield*V1,b=yield*N1;yield*G.heading(`⏰ Scheduling workflow: ${I}`),yield*G.log("");let W=yield*Z.loadWorkflow(I).pipe(w.catchAll((Q)=>w.gen(function*(){return yield*G.error(`Workflow not found: ${I}`),yield*G.info("Run 'jazz workflow list' to see available workflows."),yield*w.fail(Q)})));if(!W.metadata.schedule){yield*G.error(`Workflow '${I}' has no schedule defined.`),yield*G.info("Add a 'schedule' field to the workflow's WORKFLOW.md frontmatter."),yield*G.log(""),yield*G.log("Example:"),yield*G.log(" ---"),yield*G.log(" name: my-workflow"),yield*G.log(' schedule: "0 * * * *" # Every hour'),yield*G.log(" ---");return}let l=b.getSchedulerType();if(l==="unsupported"){yield*G.error("Scheduling is not supported on this platform."),yield*G.info("Supported platforms: macOS (launchd), Linux (cron)");return}if(yield*b.isScheduled(I))yield*G.info(`Workflow '${I}' is already scheduled. Updating...`);let N,c,X=W.metadata.agent||"default",F=yield*g0(X).pipe(w.either);if(F._tag==="Right")N=X,c=F.right.name,yield*G.info(`Using agent: ${c}`);else{let Q=yield*f7();if(Q.length===0)return yield*G.error("No agents available."),yield*G.info("Create an agent first with: jazz agent create"),yield*w.fail(Error("No agents available. Create an agent first with: jazz agent create"));if(X!=="default")yield*G.warn(`Agent '${X}' specified in workflow not found.`);else yield*G.info("No agent specified in workflow. Please select an agent:");yield*G.log("");let m=yield*vmZ(Q,"Select an agent to run this scheduled workflow:");if(!m){yield*G.info("Scheduling cancelled.");return}N=m.id,c=m.name,yield*G.info(`Using agent: ${c}`)}yield*G.log("");let d=!1;if(l==="launchd")d=yield*G.confirm("Run on login? (catches missed runs when your Mac was asleep)",!1),yield*G.log("");if(yield*b.schedule(W.metadata,N,{runAtLoad:d}),yield*G.success(`Workflow '${I}' scheduled successfully!`),yield*G.log(""),yield*G.log(` Schedule: ${W.metadata.schedule}`),yield*G.log(` Agent: ${c}`),yield*G.log(` Scheduler: ${l}`),d)yield*G.log(" Run on login: yes");if(yield*G.log(""),W.metadata.autoApprove)yield*G.info(`Auto-approve policy: ${W.metadata.autoApprove}`);else yield*G.warn("No auto-approve policy set. The workflow may pause for approval during scheduled runs."),yield*G.info("Add 'autoApprove: true' or 'autoApprove: low-risk' to the workflow.");yield*G.log(""),yield*G.info("Logs will be written to: ~/.jazz/logs/"),yield*G.info(`To unschedule: jazz workflow unschedule ${I}`)})}function HmZ(I){return w.gen(function*(){let G=yield*bZ,Z=yield*N1;if(yield*G.heading(`\uD83D\uDED1 Unscheduling workflow: ${I}`),yield*G.log(""),Z.getSchedulerType()==="unsupported"){yield*G.error("Scheduling is not supported on this platform.");return}if(!(yield*Z.isScheduled(I))){yield*G.info(`Workflow '${I}' is not currently scheduled.`);return}yield*Z.unschedule(I),yield*G.success(`Workflow '${I}' unscheduled successfully.`)})}function wmZ(){return w.gen(function*(){let I=yield*bZ;yield*I.heading("\uD83D\uDD04 Workflow catch-up"),yield*I.log(""),yield*I.info("Scheduled runs only fire when the machine is awake. If your Mac was asleep or off at the scheduled time, those runs were missed. Here you can run them now."),yield*I.log("");let G=yield*WbI().pipe(w.catchAll(()=>w.succeed([])));if(G.length===0){yield*I.info("No workflows need catch-up right now."),yield*I.log(""),yield*I.info("Workflows must be scheduled, have catchUpOnStartup: true, and have missed their last run within the max catch-up window.");return}yield*I.log("Workflows that missed a scheduled run:"),yield*I.log("");for(let l of G){let Y=l.decision.scheduledAt?.toISOString()??"—",N=jE(l.entry.schedule)??l.entry.schedule;yield*I.log(` • ${l.entry.workflowName} (${N}) — missed at ${Y}`)}yield*I.log("");let Z=G.map((l)=>({name:`${l.entry.workflowName} (${l.decision.scheduledAt?.toISOString()??"—"})`,value:l.entry.workflowName})),b=yield*I.checkbox("Select workflows to run now (Space to toggle, Enter to confirm):",{choices:Z,default:[]});if(b.length===0){yield*I.info("No workflows selected. Exiting.");return}let W=G.filter((l)=>b.includes(l.entry.workflowName)).map((l)=>l.entry);yield*I.log(""),yield*I.info(`Running catch-up for ${W.length} workflow(s)...`),yield*I.log(""),yield*lbI(W),yield*I.log(""),yield*I.success("Catch-up finished.")})}function hmZ(){return w.gen(function*(){let I=yield*bZ,G=yield*N1;yield*I.heading("⏰ Scheduled Workflows"),yield*I.log("");let Z=G.getSchedulerType();if(Z==="unsupported"){yield*I.error("Scheduling is not supported on this platform."),yield*I.info("Supported platforms: macOS (launchd), Linux (cron)");return}yield*I.info(`Scheduler: ${Z}`),yield*I.log("");let b=yield*G.listScheduled();if(b.length===0){yield*I.info("No workflows are currently scheduled."),yield*I.log(""),yield*I.info("To schedule a workflow: jazz workflow schedule <name>");return}for(let W of b){let l=W.enabled?"✓ enabled":"✗ disabled",Y=jE(W.schedule)??W.schedule;yield*I.log(` ${W.workflowName} (${Y}) agent: ${W.agent} ${l}`)}yield*I.log(""),yield*I.info(`Total: ${b.length} scheduled workflow(s)`)})}function JmZ(I){return w.gen(function*(){let G=yield*bZ;if(I)yield*G.heading(`\uD83D\uDCDC Run History: ${I}`);else yield*G.heading("\uD83D\uDCDC Recent Workflow Runs");yield*G.log("");let Z=yield*bKG(20),b=I?Z.filter((l)=>l.workflowName===I):Z;if(b.length===0){yield*G.info("No run history found."),yield*G.log(` History file: ${LZI()}`);return}let W=14400000;for(let l of b){let Y=Date.parse(l.startedAt),N=l.status==="running"&&Number.isFinite(Y)&&Date.now()-Y>W,c=N?"failed":l.status,X=c==="completed"?"✓":c==="failed"?"✗":c==="skipped"?"⊘":"…",F=l.completedAt?`${Math.round((new Date(l.completedAt).getTime()-new Date(l.startedAt).getTime())/1000)}s`:N?"failed (stale — process exited without updating)":"in progress",d=l.triggeredBy==="scheduled"?" (scheduled)":"";if(yield*G.log(` ${X} ${l.workflowName}${d} - ${c} (${F})`),yield*G.log(` Started: ${l.startedAt}`),l.error)yield*G.log(` Error: ${l.error}`);yield*G.log("")}yield*G.info(`Showing ${b.length} most recent run(s)`)})}function FmZ(I){return{...I.costUSD!==void 0?{costUSD:I.costUSD}:{},...I.usage!==void 0?{tokenUsage:I.usage}:{}}}function vmZ(I,G){return w.async((Z)=>{let b=I.map((W)=>({label:`${W.name} (${W.config.llmModel})`,value:W.id}));JI.setCustomView(_YI.createElement(XmZ,{flexDirection:"column",padding:1},_YI.createElement(QdW,{bold:!0,color:LI.primary},G),_YI.createElement(XmZ,{marginTop:1},_YI.createElement(pYI,{options:b,pageSize:10,placeholder:"Type to filter agents…",onSelect:(W)=>{JI.setCustomView(null),Z(w.succeed(I.find((l)=>l.id===W)??null))},onCancel:()=>{JI.setCustomView(null),Z(w.succeed(null))}}))))})}var EmZ=g(()=>{UI();HMI();nQ();fW();cJ();OC();aE();$W();nN();xMI();OU();BB();JkI();s7();Rq();wq();KgI();SMI()});function OO(I){return(G)=>{if(!/^\d+$/.test(G))throw Error(`${I} must be a positive integer (got "${G}").`);let Z=Number.parseInt(G,10);if(Z<=0)throw Error(`${I} must be a positive integer (got "${G}").`);return Z}}function mdW(I){I.command("run [prompt]").description("Run an agent once non-interactively (for scripts/webhooks). Prompt comes from the argument or piped stdin; the answer goes to stdout, all chatter to stderr.").requiredOption("--agent <agentId>","Agent ID or name to run").option("--json","Emit a single JSON envelope { ok, answer, costUSD, tokenUsage, toolCalls }").option("--approval-policy <policy>","Auto-approve tools up to a risk level: read-only | low-risk | high-risk (high-risk approves everything). Tools above the level are declined.").option("--timeout <ms>","Abort the run after this many milliseconds",OO("--timeout")).option("--max-iterations <n>","Maximum agent reasoning iterations for this run",OO("--max-iterations")).option("--events <categories>","Emit selected event categories as NDJSON to stderr during the run (comma-separated: tools,reasoning,text,usage,all). stdout stays the clean payload.").option("--reasoning <effort>","Reasoning effort for this run: low | medium | high | disable (overrides the agent's config)").option("--conversation <id>","Stable conversation key (e.g. a Telegram chat id). Loads prior history for this key before the run and saves the updated transcript after, giving repeated invocations shared memory. Omit for a stateless one-shot run.").action((G,Z)=>{let b=I.opts(),W=Z.json===!0;if(Z.approvalPolicy!==void 0&&!jMI(Z.approvalPolicy)){let Y=`Invalid --approval-policy "${Z.approvalPolicy}". Expected read-only, low-risk, or high-risk.`;if(W)process.stdout.write(`${JSON.stringify({ok:!1,error:Y,costUSD:0})}
7548
+ `}function jMI(I){return gFW.includes(I)}function DMI(I){return UFW.includes(I)}function BFW(I){let G=I.responseMessages&&I.responseMessages.length>0?I.responseMessages:[...I.priorRecord?.messages??[],{role:"user",content:I.prompt},{role:"assistant",content:I.responseContent}];return{conversationId:I.conversationId,title:I.priorRecord?.title??I.prompt.trim().slice(0,80),agentId:I.agentId,startedAt:I.priorRecord?.startedAt??I.now,endedAt:I.now,messageCount:G.length,messages:G}}function OFW(I){return Object.prototype.hasOwnProperty.call(MMI,I)}function qMI(I){let G=new Set(["error"]),Z=I.split(",").map((b)=>b.trim().toLowerCase()).filter((b)=>b.length>0);for(let b of Z){if(b==="all"){for(let W of Object.values(MMI))for(let l of W)G.add(l);continue}if(!OFW(b))return{ok:!1,error:`Invalid --events category "${b}". Expected: tools, reasoning, text, usage, approval, subagent, all.`};for(let W of MMI[b])G.add(W)}return{ok:!0,types:G}}function xFW(){if(process.stdin.readableEnded)return Promise.resolve("");return new Promise((I,G)=>{let Z=[];process.stdin.on("data",(b)=>Z.push(b)),process.stdin.on("end",()=>I(Buffer.concat(Z).toString("utf-8"))),process.stdin.on("error",G)})}function $QZ(I,G,Z){let b={json:Z.json};return w.gen(function*(){let W=I.trim();if(W.length===0)return yield*DYI("No agent specified. Use --agent <agentId>.",b);let l=G??"";if(l.trim().length===0&&!process.stdin.isTTY)l=yield*w.tryPromise({try:()=>xFW(),catch:()=>Error("Failed to read prompt from stdin.")}).pipe(w.catchAll(()=>w.succeed("")));if(l.trim().length===0)return yield*DYI("No prompt provided. Pass it as an argument or pipe it via stdin.",b);let Y=yield*g0(W).pipe(w.catchTag("StorageNotFoundError",()=>w.fail(new Qk({agentId:W,suggestion:Y3.checkAgentExists(W)})))),N=Z.reasoningEffort!==void 0?{...Y,config:{...Y.config,reasoningEffort:Z.reasoningEffort}}:Y,c=Z.conversationId?.trim();if(c!==void 0&&c.length===0)return yield*DYI("Invalid --conversation id: must be non-empty.",b);let X=c!==void 0?yield*LrG(Y.id,c):null,F=Z.approvalPolicy,d=`run-${Y.id}-${Date.now()}`,Q=kc.run({agent:N,userInput:l,sessionId:d,conversationId:c??d,...X!==null?{conversationHistory:X.messages}:{},...F!==void 0?{autoApprovePolicy:F}:{},...Z.maxIterations!=null?{maxIterations:Z.maxIterations}:{},...Z.stream!==void 0?{stream:Z.stream}:{}}),m=yield*Z.timeoutMs!=null?Q.pipe(w.timeoutFail({duration:Hl.millis(Z.timeoutMs),onTimeout:()=>Error(`Run exceeded the ${Z.timeoutMs}ms timeout.`)})):Q;if(c!==void 0){let E=BFW({agentId:Y.id,conversationId:c,prompt:l,priorRecord:X,responseContent:m.content,responseMessages:m.messages,now:new Date().toISOString()});yield*ZS(E).pipe(w.catchAll((C)=>w.sync(()=>{process.stderr.write(`Warning: failed to save conversation "${c}": ${eq(C)}
7549
+ `)})))}let R=m.usage?.promptTokens??0,H=m.usage?.completionTokens??0,h=(m.toolCalls??[]).map((E)=>({id:E.id,name:E.function?.name??"",arguments:E.function?.arguments??""}));yield*MFW(KMI({answer:m.content,costUSD:m.costUSD??0,tokenUsage:{promptTokens:R,completionTokens:H,totalTokens:R+H},toolCalls:h},b))}).pipe(w.catchAll((W)=>DYI(eq(W),b)),w.provide(CT(Z.eventTypes??new Set)))}var gFW,UFW,MMI,MFW=(I)=>w.sync(()=>{process.stdout.write(I)}),DYI=(I,G,Z=0)=>w.sync(()=>{let b=aMI(I,G,Z);if(G.json)process.stdout.write(b);else process.stderr.write(b);process.exitCode=1});var SMI=g(()=>{UI();OC();aE();xMI();OY();BB();WS();gFW=["read-only","low-risk","high-risk"];UFW=["disable","low","medium","high"];MMI={tools:["tools_detected","tool_call","tool_execution_start","tool_execution_complete"],reasoning:["thinking_start","thinking_chunk","thinking_complete"],text:["text_start","text_chunk"],usage:["stream_start","usage_update","complete"],approval:["approval_required","approval_resolved"],subagent:["subagent_start","subagent_complete"]}});import iQZ from"node:process";function TMI(){let{env:I}=iQZ,{TERM:G,TERM_PROGRAM:Z}=I;if(iQZ.platform!=="win32")return G!=="linux";return Boolean(I.WT_SESSION)||Boolean(I.TERMINUS_SUBLIME)||I.ConEmuTask==="{cmd::Cmder}"||Z==="Terminus-Sublime"||Z==="vscode"||G==="xterm-256color"||G==="alacritty"||G==="rxvt-unicode"||G==="rxvt-unicode-256color"||I.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var fQZ=()=>{};var sQZ,oQZ,KFW,aFW,jFW,DFW,qFW,rQZ,sMl;var tQZ=g(()=>{fQZ();sQZ={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"█",squareDarkShade:"▓",squareMediumShade:"▒",squareLightShade:"░",squareTop:"▀",squareBottom:"▄",squareLeft:"▌",squareRight:"▐",squareCenter:"■",bullet:"●",dot:"․",ellipsis:"…",pointerSmall:"›",triangleUp:"▲",triangleUpSmall:"▴",triangleDown:"▼",triangleDownSmall:"▾",triangleLeftSmall:"◂",triangleRightSmall:"▸",home:"⌂",heart:"♥",musicNote:"♪",musicNoteBeamed:"♫",arrowUp:"↑",arrowDown:"↓",arrowLeft:"←",arrowRight:"→",arrowLeftRight:"↔",arrowUpDown:"↕",almostEqual:"≈",notEqual:"≠",lessOrEqual:"≤",greaterOrEqual:"≥",identical:"≡",infinity:"∞",subscriptZero:"₀",subscriptOne:"₁",subscriptTwo:"₂",subscriptThree:"₃",subscriptFour:"₄",subscriptFive:"₅",subscriptSix:"₆",subscriptSeven:"₇",subscriptEight:"₈",subscriptNine:"₉",oneHalf:"½",oneThird:"⅓",oneQuarter:"¼",oneFifth:"⅕",oneSixth:"⅙",oneEighth:"⅛",twoThirds:"⅔",twoFifths:"⅖",threeQuarters:"¾",threeFifths:"⅗",threeEighths:"⅜",fourFifths:"⅘",fiveSixths:"⅚",fiveEighths:"⅝",sevenEighths:"⅞",line:"─",lineBold:"━",lineDouble:"═",lineDashed0:"┄",lineDashed1:"┅",lineDashed2:"┈",lineDashed3:"┉",lineDashed4:"╌",lineDashed5:"╍",lineDashed6:"╴",lineDashed7:"╶",lineDashed8:"╸",lineDashed9:"╺",lineDashed10:"╼",lineDashed11:"╾",lineDashed12:"−",lineDashed13:"–",lineDashed14:"‐",lineDashed15:"⁃",lineVertical:"│",lineVerticalBold:"┃",lineVerticalDouble:"║",lineVerticalDashed0:"┆",lineVerticalDashed1:"┇",lineVerticalDashed2:"┊",lineVerticalDashed3:"┋",lineVerticalDashed4:"╎",lineVerticalDashed5:"╏",lineVerticalDashed6:"╵",lineVerticalDashed7:"╷",lineVerticalDashed8:"╹",lineVerticalDashed9:"╻",lineVerticalDashed10:"╽",lineVerticalDashed11:"╿",lineDownLeft:"┐",lineDownLeftArc:"╮",lineDownBoldLeftBold:"┓",lineDownBoldLeft:"┒",lineDownLeftBold:"┑",lineDownDoubleLeftDouble:"╗",lineDownDoubleLeft:"╖",lineDownLeftDouble:"╕",lineDownRight:"┌",lineDownRightArc:"╭",lineDownBoldRightBold:"┏",lineDownBoldRight:"┎",lineDownRightBold:"┍",lineDownDoubleRightDouble:"╔",lineDownDoubleRight:"╓",lineDownRightDouble:"╒",lineUpLeft:"┘",lineUpLeftArc:"╯",lineUpBoldLeftBold:"┛",lineUpBoldLeft:"┚",lineUpLeftBold:"┙",lineUpDoubleLeftDouble:"╝",lineUpDoubleLeft:"╜",lineUpLeftDouble:"╛",lineUpRight:"└",lineUpRightArc:"╰",lineUpBoldRightBold:"┗",lineUpBoldRight:"┖",lineUpRightBold:"┕",lineUpDoubleRightDouble:"╚",lineUpDoubleRight:"╙",lineUpRightDouble:"╘",lineUpDownLeft:"┤",lineUpBoldDownBoldLeftBold:"┫",lineUpBoldDownBoldLeft:"┨",lineUpDownLeftBold:"┥",lineUpBoldDownLeftBold:"┩",lineUpDownBoldLeftBold:"┪",lineUpDownBoldLeft:"┧",lineUpBoldDownLeft:"┦",lineUpDoubleDownDoubleLeftDouble:"╣",lineUpDoubleDownDoubleLeft:"╢",lineUpDownLeftDouble:"╡",lineUpDownRight:"├",lineUpBoldDownBoldRightBold:"┣",lineUpBoldDownBoldRight:"┠",lineUpDownRightBold:"┝",lineUpBoldDownRightBold:"┡",lineUpDownBoldRightBold:"┢",lineUpDownBoldRight:"┟",lineUpBoldDownRight:"┞",lineUpDoubleDownDoubleRightDouble:"╠",lineUpDoubleDownDoubleRight:"╟",lineUpDownRightDouble:"╞",lineDownLeftRight:"┬",lineDownBoldLeftBoldRightBold:"┳",lineDownLeftBoldRightBold:"┯",lineDownBoldLeftRight:"┰",lineDownBoldLeftBoldRight:"┱",lineDownBoldLeftRightBold:"┲",lineDownLeftRightBold:"┮",lineDownLeftBoldRight:"┭",lineDownDoubleLeftDoubleRightDouble:"╦",lineDownDoubleLeftRight:"╥",lineDownLeftDoubleRightDouble:"╤",lineUpLeftRight:"┴",lineUpBoldLeftBoldRightBold:"┻",lineUpLeftBoldRightBold:"┷",lineUpBoldLeftRight:"┸",lineUpBoldLeftBoldRight:"┹",lineUpBoldLeftRightBold:"┺",lineUpLeftRightBold:"┶",lineUpLeftBoldRight:"┵",lineUpDoubleLeftDoubleRightDouble:"╩",lineUpDoubleLeftRight:"╨",lineUpLeftDoubleRightDouble:"╧",lineUpDownLeftRight:"┼",lineUpBoldDownBoldLeftBoldRightBold:"╋",lineUpDownBoldLeftBoldRightBold:"╈",lineUpBoldDownLeftBoldRightBold:"╇",lineUpBoldDownBoldLeftRightBold:"╊",lineUpBoldDownBoldLeftBoldRight:"╉",lineUpBoldDownLeftRight:"╀",lineUpDownBoldLeftRight:"╁",lineUpDownLeftBoldRight:"┽",lineUpDownLeftRightBold:"┾",lineUpBoldDownBoldLeftRight:"╂",lineUpDownLeftBoldRightBold:"┿",lineUpBoldDownLeftBoldRight:"╃",lineUpBoldDownLeftRightBold:"╄",lineUpDownBoldLeftBoldRight:"╅",lineUpDownBoldLeftRightBold:"╆",lineUpDoubleDownDoubleLeftDoubleRightDouble:"╬",lineUpDoubleDownDoubleLeftRight:"╫",lineUpDownLeftDoubleRightDouble:"╪",lineCross:"╳",lineBackslash:"╲",lineSlash:"╱"},oQZ={tick:"✔",info:"ℹ",warning:"⚠",cross:"✘",squareSmall:"◻",squareSmallFilled:"◼",circle:"◯",circleFilled:"◉",circleDotted:"◌",circleDouble:"◎",circleCircle:"ⓞ",circleCross:"ⓧ",circlePipe:"Ⓘ",radioOn:"◉",radioOff:"◯",checkboxOn:"☒",checkboxOff:"☐",checkboxCircleOn:"ⓧ",checkboxCircleOff:"Ⓘ",pointer:"❯",triangleUpOutline:"△",triangleLeft:"◀",triangleRight:"▶",lozenge:"◆",lozengeOutline:"◇",hamburger:"☰",smiley:"㋡",mustache:"෴",star:"★",play:"▶",nodejs:"⬢",oneSeventh:"⅐",oneNinth:"⅑",oneTenth:"⅒"},KFW={tick:"√",info:"i",warning:"‼",cross:"×",squareSmall:"□",squareSmallFilled:"■",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(○)",circleCross:"(×)",circlePipe:"(│)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[×]",checkboxOff:"[ ]",checkboxCircleOn:"(×)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"∆",triangleLeft:"◄",triangleRight:"►",lozenge:"♦",lozengeOutline:"◊",hamburger:"≡",smiley:"☺",mustache:"┌─┐",star:"✶",play:"►",nodejs:"♦",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},aFW={...sQZ,...oQZ},jFW={...sQZ,...KFW},DFW=TMI(),qFW=DFW?aFW:jFW,rQZ=qFW,sMl=Object.entries(oQZ)});import _MI from"react";import{Box as SFW,Text as eQZ}from"ink";function TFW({isSelected:I=!1}){return _MI.createElement(SFW,{marginRight:1},I?_MI.createElement(eQZ,{color:"blue"},rQZ.pointer):_MI.createElement(eQZ,null," "))}var PMI;var nMI=g(()=>{tQZ();PMI=TFW});import*as ImZ from"react";import{Text as _FW}from"ink";function PFW({isSelected:I=!1,label:G}){return ImZ.createElement(_FW,{color:I?"blue":void 0},G)}var $MI;var iMI=g(()=>{$MI=PFW});function LL(I,G){if(!Array.isArray(I))throw TypeError(`Expected an array, got \`${typeof I}\`.`);if(!Number.isSafeInteger(G))throw TypeError(`The \`steps\` parameter must be an integer, got ${G}.`);let{length:Z}=I;if(Z===0)return[...I];let b=(G%Z+Z)%Z;if(b===0)return[...I];return[...I.slice(-b),...I.slice(0,-b)]}import{isDeepStrictEqual as nFW}from"node:util";import qYI,{useState as GmZ,useEffect as $FW,useRef as iFW,useCallback as fFW}from"react";import{Box as ZmZ,useInput as sFW}from"ink";function oFW({items:I=[],isFocused:G=!0,initialIndex:Z=0,indicatorComponent:b=PMI,itemComponent:W=$MI,limit:l,onSelect:Y,onHighlight:N}){let c=typeof l==="number"&&I.length>l,X=c?Math.min(l,I.length):I.length,F=X-1,[d,Q]=GmZ(Z>F?F-Z:0),[m,R]=GmZ(Z?Z>F?F:Z:0),H=iFW(I);$FW(()=>{if(!nFW(H.current.map((E)=>E.value),I.map((E)=>E.value)))Q(0),R(0);H.current=I},[I]),sFW(fFW((E,C)=>{if(E==="k"||C.upArrow){let J=(c?X:I.length)-1,y=m===0,v=c?m:J,A=y?d+1:d,k=y?v:m-1;Q(A),R(k);let L=c?LL(I,A).slice(0,X):I;if(typeof N==="function")N(L[k])}if(E==="j"||C.downArrow){let J=m===(c?X:I.length)-1,y=c?m:0,v=J?d-1:d,A=J?y:m+1;Q(v),R(A);let k=c?LL(I,v).slice(0,X):I;if(typeof N==="function")N(k[A])}if(/^[1-9]$/.test(E)){let J=Number.parseInt(E,10)-1,y=c?LL(I,d).slice(0,X):I;if(J>=0&&J<y.length){let v=y[J];if(v)Y?.(v)}}if(C.return){let J=c?LL(I,d).slice(0,X):I;if(typeof Y==="function")Y(J[m])}},[c,X,d,m,I,Y,N]),{isActive:G});let h=c?LL(I,d).slice(0,X):I;return qYI.createElement(ZmZ,{flexDirection:"column"},h.map((E,C)=>{let J=C===m;return qYI.createElement(ZmZ,{key:E.key??E.value},qYI.createElement(b,{isSelected:J}),qYI.createElement(W,{...E,isSelected:J}))}))}var fMI;var bmZ=g(()=>{nMI();iMI();fMI=oFW});var WmZ=g(()=>{nMI();iMI();bmZ()});import{Box as k3,Text as OJ,useInput as rFW}from"ink";import{useState as tFW,useEffect as eFW}from"react";import{jsx as M1,jsxs as pL}from"react/jsx-runtime";function SYI({options:I,onSelect:G,onExit:Z,title:b}){let[W,l]=tFW(0);eFW(()=>{l(Math.floor(Math.random()*lmZ.length))},[]),rFW((N,c)=>{if(c.escape)Z();if(N==="q")Z()});let Y=I.map((N)=>({label:N.label,value:N.value}));return pL(k3,{flexDirection:"column",paddingX:2,paddingY:1,children:[pL(k3,{flexDirection:"column",marginBottom:1,children:[pL(OJ,{bold:!0,color:LI.primary,children:[sMI.note," Jazz"]}),pL(OJ,{dimColor:!0,children:["v",F0.version," · your everyday agentic CLI"]})]}),pL(k3,{flexDirection:"column",marginTop:1,paddingY:0,children:[M1(k3,{marginBottom:1,children:M1(OJ,{bold:!0,color:LI.selected,children:b||"What would you like to do?"})}),M1(fMI,{items:Y,onSelect:(N)=>G(N.value),indicatorComponent:IdW,itemComponent:GdW})]}),pL(k3,{marginTop:1,children:[pL(OJ,{color:LI.primary,children:[sMI.note," "]}),M1(OJ,{dimColor:!0,italic:!0,wrap:"wrap",children:lmZ[W]})]}),M1(k3,{marginTop:1,children:M1(OJ,{dimColor:!0,children:"↑↓ move · enter select · q quit"})})]})}function IdW({isSelected:I=!1}){return M1(k3,{marginRight:1,children:I?M1(OJ,{color:LI.primary,bold:!0,children:sMI.rail}):M1(OJ,{children:" "})})}function GdW({isSelected:I=!1,label:G}){return M1(k3,{children:M1(OJ,{color:I?LI.selected:LI.secondary,bold:I,children:G})})}var sMI,lmZ;var oMI=g(()=>{WmZ();VN();fW();s6();sMI=YZ(),lmZ=["Type '/help' in chat to see every command and keyboard shortcut","Use Arrow Up in chat to recall your previous messages","Press Alt+Enter in chat to write multi-line messages","Press Ctrl+R after a response to expand the agent's reasoning","Run 'jazz agent list' to see all your active agents","Agents work best with specific, focused descriptions","Delete unused agents to keep your workspace clean","Use the email skill (Himalaya) to let agents read, send, and manage your inbox","Use the calendar skill (khal) to let agents view and manage your schedule","The 'fs' tools allow agents to read and write files in your project","Enable Web Search to give your agent up-to-date knowledge","Agents can use 'grep' to search your codebase instantly","Use /tools to see which tools are available","Jazz supports MCP! Connect to Notion, GitHub, and 100+ other services","Use Agent Skills to teach complex workflows to your agents","Switch LLM models mid-chat if you need more intelligence or speed","Local models via Ollama are supported for offline privacy","Ask agents to 'plan first' for complex coding tasks","Agents can read PDFs! Just give them the file path","Ask an agent to 'summarize this conversation' to catch up","Chain commands: 'Find TODOs then create a summary file'","Use '/new' to clear the context and start a new conversation","Use 'jazz config show' to see your configuration","Check 'jazz update' regularly for new features","You can have multiple agents running in different terminal tabs","Agents can write their own tests before writing code","Try asking an agent to 'optimize your system prompt'","Jazz agents never execute dangerous commands without approval","The 'shell' tool is sandboxed but powerful - use with care!"]});import ZdW from"react";function YmZ(){return w.gen(function*(){let I=!0;while(I)switch(yield*bdW([{label:"LLM Providers (API Keys)",value:"llm-providers"},{label:"Web Search Providers",value:"web-search"},{label:"Output & Display",value:"output-display"},{label:"Logging",value:"logging"},{label:"Notifications",value:"notifications"},{label:"Back to Main Menu",value:"back"}])){case"llm-providers":{yield*WdW();break}case"web-search":{yield*ldW();break}case"output-display":{yield*YdW();break}case"logging":{yield*VdW();break}case"notifications":{yield*NdW();break}case"back":{I=!1;break}}})}function bdW(I){return w.async((G)=>{JI.setCustomView(ZdW.createElement(SYI,{options:I,title:"Configuration",onSelect:(Z)=>{JI.setCustomView(null),G(w.succeed(Z))},onExit:()=>{JI.setCustomView(null),G(w.succeed("back"))}}))})}function WdW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ;while(!0){let Z=yield*G.appConfig,b=dd.map((c)=>{let X=!!Z.llm?.[c]?.api_key;return{name:`${yV(c)} ${X?"(configured)":""}`,value:c}});b.push({name:"Back",value:"back"});let W=yield*I.select("Select provider to configure:",{choices:b});if(!W||W==="back")break;let l=W,Y=yV(l);yield*I.info(`Configuring ${Y}...`);let N=yield*I.password(`Enter API Key for ${Y} (leave empty to keep current):`);if(N.trim())yield*G.set(`llm.${l}.api_key`,N),yield*I.success(`Configuration for ${Y} updated.`);else yield*I.info("No changes made.");yield*I.log("")}})}function ldW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ;while(!0){let Z=yield*G.appConfig,l=[{name:`Select external provider (current: ${Z.web_search?.provider??"Built-in (if available)"})`,value:"select-provider"},...Y1.map((N)=>{let c=!!Z.web_search?.[N.value]?.api_key;return{name:`${N.name} API Key ${c?"(configured)":""}`,value:N.value}}),{name:"Back",value:"back"}],Y=yield*I.select("Web Search Configuration:",{choices:l});if(!Y||Y==="back")break;if(Y==="select-provider"){let N=[{name:"None (use built-in if available)",value:"none"},...Y1.map((X)=>({name:X.name,value:X.value}))],c=yield*I.select("Select provider:",{choices:N});if(c==="none")yield*G.set("web_search.provider",void 0),yield*I.success("External provider disabled. Built-in provider web search will be used if available.");else if(c)yield*G.set("web_search.provider",c),yield*I.success(`External provider set to ${c}.`)}else{let N=Y;yield*I.info(`Configuring ${N}...`);let c=yield*I.password(`Enter API Key for ${N} (leave empty to keep current):`);if(c.trim())yield*G.set(`web_search.${N}.api_key`,c),yield*I.success(`Configuration for ${N} updated.`);else yield*I.info("No changes made.")}yield*I.log("")}})}function YdW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ,Z=function*(b){let W=yield*I.confirm(b.prompt,b.currentValue);yield*G.set(b.configKey,W),yield*I.success(`${b.label} ${W?"enabled":"disabled"}.`)};while(!0){let b=yield*G.appConfig,W=pQ(b),l=b.output?.showMetrics??!0,Y=b.output?.colorProfile??"auto",N=yield*I.select("Output & display settings:",{choices:[{name:`Output mode (${W.mode})`,value:"mode"},{name:`Color profile (${Y})`,value:"color-profile"},{name:`Show thinking (${W.showThinking?"on":"off"})`,value:"show-thinking"},{name:`Show tool execution (${W.showToolExecution?"on":"off"})`,value:"show-tool-execution"},{name:`Show metrics (${l?"on":"off"})`,value:"show-metrics"},{name:"Back",value:"back"}]});if(!N||N==="back")break;switch(N){case"mode":{let c=yield*I.select("Select output mode:",{choices:[{name:"Hybrid (styled, copy-paste friendly)",value:"hybrid"},{name:"Raw (plain text)",value:"raw"},{name:"Rendered (styled)",value:"rendered"},{name:"Quiet (suppress output, for cron/background)",value:"quiet"}]});if(c)yield*G.set("output.mode",c),yield*I.success(`Output mode set to ${c}.`);break}case"color-profile":{let c=yield*I.select("Select color profile:",{choices:[{name:"Auto (default)",value:"auto"},{name:"Full",value:"full"},{name:"Basic",value:"basic"},{name:"None",value:"none"}]});if(c)if(c==="auto")yield*G.set("output.colorProfile",void 0),yield*I.success("Color profile set to auto.");else yield*G.set("output.colorProfile",c),yield*I.success(`Color profile set to ${c}.`);break}case"show-thinking":{yield*Z({prompt:"Show thinking output?",currentValue:W.showThinking,configKey:"output.showThinking",label:"Show thinking"});break}case"show-tool-execution":{yield*Z({prompt:"Show tool execution?",currentValue:W.showToolExecution,configKey:"output.showToolExecution",label:"Show tool execution"});break}case"show-metrics":{yield*Z({prompt:"Show performance metrics?",currentValue:l,configKey:"output.showMetrics",label:"Show metrics"});break}}yield*I.log("")}})}function NdW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ;while(!0){let Z=yield*G.appConfig,b=Z.notifications?.enabled??!0,W=Z.notifications?.sound??!0,l=yield*I.select("Notification settings:",{choices:[{name:`System notifications (${b?"on":"off"})`,value:"enabled"},{name:`Notification sound (${W?"on":"off"})`,value:"sound"},{name:"Back",value:"back"}]});if(!l||l==="back")break;switch(l){case"enabled":{let Y=yield*I.confirm("Enable system notifications?",b);yield*G.set("notifications.enabled",Y),yield*I.success(`System notifications ${Y?"enabled":"disabled"}.`);break}case"sound":{let Y=yield*I.confirm("Enable notification sound?",W);yield*G.set("notifications.sound",Y),yield*I.success(`Notification sound ${Y?"enabled":"disabled"}.`);break}}yield*I.log("")}})}function VdW(){return w.gen(function*(){let I=yield*bZ,G=yield*pZ;while(!0){let b=(yield*G.appConfig).logging?.format??"plain",W=yield*I.select("Logging settings:",{choices:[{name:`Log format (${b})`,value:"format"},{name:"Back",value:"back"}]});if(!W||W==="back")break;if(W==="format"){let l=yield*I.select("Select log format:",{choices:[{name:"Plain (human readable)",value:"plain"},{name:"JSON (structured for log processors)",value:"json"},{name:"TOON (token-efficient for LLM analysis)",value:"toon"}]});if(l)yield*G.set("logging.format",l),yield*I.success(`Log format set to ${l}.`)}yield*I.log("")}})}var NmZ=g(()=>{UI();kU();KH();uN();nN();gy();MR();nQ();oMI()});import cdW from"react";function VmZ(){return w.gen(function*(){let I=yield*bc,G=yield*pZ,Z=yield*bZ;yield*Z.setTitle("\uD83C\uDFB7 Jazz"),yield*ddW(G,Z);let b=!1;while(!b){let W=yield*I.listAgents(),Y=yield*(yield*HJ).get("wizard.lastUsedAgentId").pipe(w.map((d)=>typeof d==="string"?d:null),w.catchAll(()=>w.succeed(null))),N=null;if(Y){let d=yield*w.either(I.getAgent(Y));if(d._tag==="Right")N=d.right}let c=!1;for(let d of W)if((yield*bS(d.id).pipe(w.catchAll(()=>w.succeed({agentId:d.id,conversations:[]})))).conversations.length>0){c=!0;break}let X=[];if(N)X.push({label:`Resume: ${N.name}`,value:"continue"});if(W.length>0)X.push({label:"New conversation",value:"new-conversation"});if(c)X.push({label:"Resume conversation",value:"resume-conversation"});if(X.push({label:"Create agent",value:"create-agent"}),W.length>0)X.push({label:"List agents",value:"list-agents"},{label:"Edit agent",value:"edit-agent"},{label:"Delete agent",value:"delete-agent"},{label:"Update configuration",value:"config"});else X.push({label:"Update configuration",value:"config"});switch(X.push({label:"Exit",value:"exit"}),yield*XdW(X)){case"continue":{if(N)yield*TYI(N),yield*Z.clear();break}case"new-conversation":{let d=yield*rMI(W,Z,"Select an agent to chat with:",Y);if(d)yield*TYI(d),yield*Z.clear();break}case"resume-conversation":{yield*FdW(W,Z),yield*Z.clear();break}case"create-agent":{let d=W.length,Q=yield*MYI().pipe(w.either);if(Q._tag==="Left"){yield*Z.error(`Failed to create agent: ${String(Q.left)}`),yield*Z.clear();break}let m=yield*I.listAgents().pipe(w.catchAll((H)=>w.gen(function*(){return yield*Z.error(`Failed to retrieve agents: ${String(H)}`),[]})));if(m.length===0||m.length<=d){yield*Z.clear();break}let R=m.reduce((H,h)=>H.createdAt.getTime()>h.createdAt.getTime()?H:h);yield*TYI(R).pipe(w.catchAll((H)=>w.gen(function*(){yield*Z.error(`Failed to start chat with created agent: ${String(H)}`)}))),yield*Z.clear();break}case"edit-agent":{let d=yield*rMI(W,Z,"Select an agent to edit:",Y);if(d)yield*aYI(d.id).pipe(w.catchAll((Q)=>w.gen(function*(){yield*Z.error(`Failed to edit agent: ${String(Q)}`)}))),yield*Z.clear();break}case"list-agents":{yield*uYI().pipe(w.catchAll((d)=>w.gen(function*(){yield*Z.error(`Failed to list agents: ${String(d)}`)}))),yield*Z.ask("Press Enter to continue...",{hidden:!0}),yield*Z.clear();break}case"delete-agent":{let d=yield*rMI(W,Z,"Select an agent to delete:",Y);if(d){if(!(yield*Z.confirm(`Delete agent "${d.name}" (${d.config.llmProvider}/${d.config.llmModel})? This cannot be undone.`,!1))){yield*Z.info("Deletion cancelled."),yield*Z.ask("Press Enter to continue...",{hidden:!0}),yield*Z.clear();break}yield*gYI(d.id).pipe(w.catchAll((m)=>w.gen(function*(){yield*Z.error(`Failed to delete agent: ${String(m)}`)}))),yield*Z.ask("Press Enter to continue...",{hidden:!0}),yield*Z.clear()}break}case"config":{yield*YmZ(),yield*Z.clear();break}case"exit":default:b=!0;break}}yield*Z.log(""),yield*w.sync(()=>process.exit(0))}).pipe(w.catchAll((I)=>w.fail(I instanceof Error?I:Error(String(I)))))}function XdW(I){return w.async((G)=>{let Z=!1,b=(W)=>{if(Z)return;Z=!0,JI.setCustomView(null),G(w.succeed(W))};JI.setCustomView(cdW.createElement(SYI,{options:I,onSelect:(W)=>b(W),onExit:()=>b("exit")}))})}function rMI(I,G,Z,b){return w.gen(function*(){if(I.length===0)return yield*G.warn("No agents available."),null;let l=fA(I,b).map((N)=>{let c=N.description&&N.description!==N.name?` · ${N.description}`:"";return{name:`${N.name} · ${N.config.llmModel}${c}`,value:N.id}}),Y=yield*G.search(Z,{choices:l,placeholder:"Type to filter agents…"});if(!Y)return null;return I.find((N)=>N.id===Y)??null})}function TYI(I,G){return w.gen(function*(){let Z=yield*bZ;if(yield*(yield*HJ).set("wizard.lastUsedAgentId",I.id).pipe(w.catchAll(()=>w.void)),yield*Z.clear(),yield*Z.heading(`Starting chat with: ${I.name}`),yield*Z.log(`${I.model} - Reasoning: ${I.config.reasoningEffort??"disabled"}`),I.description)yield*Z.log(` Description: ${I.description}`);yield*Z.log(""),yield*Z.info("Type '/help' to see available special commands."),yield*Z.info("Type '/exit' to end the conversation."),yield*Z.log(""),yield*(yield*xB).startChatSession(I,G).pipe(w.catchAll((l)=>w.gen(function*(){yield*Z.error(`Chat session error: ${String(l)}`)})))})}function FdW(I,G){return w.gen(function*(){let Z=[];for(let Y of I){let N=yield*bS(Y.id).pipe(w.catchAll(()=>w.succeed({agentId:Y.id,conversations:[]})));for(let c of N.conversations)Z.push({agent:Y,conversationId:c.conversationId,title:c.title,startedAt:c.startedAt,messageCount:c.messageCount,messages:c.messages})}if(Z.length===0){yield*G.warn("No saved conversations found.");return}Z.sort((Y,N)=>new Date(N.startedAt).getTime()-new Date(Y.startedAt).getTime());let b=Z.map((Y,N)=>({name:`${Y.title} · ${Y.agent.model}`,value:String(N)})),W=yield*G.search("Select a conversation to resume:",{choices:b,placeholder:"Type to filter conversations…"});if(W===null||W===void 0)return;let l=Z[Number(W)];if(!l)return;yield*TYI(l.agent,{initialHistory:l.messages,initialConversationTitle:l.title})})}function ddW(I,G){return w.gen(function*(){if(yield*I.has("notifications.enabled"))return;yield*G.log(""),yield*G.heading("\uD83C\uDFB7 Welcome to Jazz! Let's get you set up."),yield*G.log("");let b={OPENAI_API_KEY:"openai",ANTHROPIC_API_KEY:"anthropic",GOOGLE_GENERATIVE_AI_API_KEY:"google",MISTRAL_API_KEY:"mistral",XAI_API_KEY:"xai",DEEPSEEK_API_KEY:"deepseek",GROQ_API_KEY:"groq",OPENROUTER_API_KEY:"openrouter"},W=[];for(let[Y,N]of Object.entries(b))if(process.env[Y])W.push(`${N} (${Y})`);if(W.length>0){yield*G.success("Detected API keys from environment:");for(let Y of W)yield*G.log(` • ${Y}`);yield*G.log("")}else yield*G.info("No API keys detected from environment."),yield*G.log(" Set up a key via 'Update configuration' or export OPENAI_API_KEY"),yield*G.log("");yield*G.info("Jazz can send desktop notifications for completions and approvals.");let l=yield*G.confirm("Enable desktop notifications?",!0);if(yield*I.set("notifications.enabled",l),l){let Y=yield*G.confirm("Play a sound with notifications?",!0);yield*I.set("notifications.sound",Y),yield*G.success("Notifications enabled! Change anytime in Settings.")}else yield*G.info("Notifications disabled. Enable anytime in Settings.");yield*G.log("")})}var cmZ=g(()=>{UI();uN();KE();pWI();GS();nN();WS();zMI();NmZ();gMI();BMI();nQ();oMI()});import{Box as XmZ,Text as QdW}from"ink";import _YI from"react";function dmZ(){return w.gen(function*(){let I=yield*bZ,G=yield*V1,Z=yield*N1;yield*I.heading("\uD83D\uDCCB Available Workflows"),yield*I.log("");let b=yield*G.listWorkflows();if(b.length===0){yield*I.info("No workflows found."),yield*I.log(""),yield*I.info("Create a workflow by adding a WORKFLOW.md file to:"),yield*I.log(" • ./workflows/<name>/WORKFLOW.md (local)"),yield*I.log(" • ~/.jazz/workflows/<name>/WORKFLOW.md (global)");return}let W=yield*Z.listScheduled().pipe(w.map((Q)=>new Set(Q.map((m)=>m.workflowName))),w.catchAll(()=>w.succeed(new Set))),l=14400000,{runningNames:Y,staleNames:N}=yield*w5().pipe(w.map((Q)=>{let m=new Set,R=new Set;for(let H of Q)if(H.status==="running"){let h=Date.parse(H.startedAt);if(!Number.isFinite(h))continue;if(Date.now()-h>l)R.add(H.workflowName);else m.add(H.workflowName)}return{runningNames:m,staleNames:R}}),w.catchAll(()=>w.succeed({runningNames:new Set,staleNames:new Set}))),{local:c,global:X,builtin:F}=uWI(b);function d(Q){if(Y.has(Q.name))return" ● running";if(N.has(Q.name))return" ✗ failed (stale)";if(W.has(Q.name))return" ○ scheduled";if(Q.schedule)return" — not scheduled";return""}if(c.length>0){yield*I.log("Local workflows:");for(let Q of c)yield*I.log(gWI(Q,{statusBadge:d(Q)}));yield*I.log("")}if(X.length>0){yield*I.log("Global workflows (~/.jazz/workflows):");for(let Q of X)yield*I.log(gWI(Q,{statusBadge:d(Q)}));yield*I.log("")}if(F.length>0){yield*I.log("Built-in workflows:");for(let Q of F)yield*I.log(gWI(Q,{statusBadge:d(Q)}));yield*I.log("")}yield*I.info(`Total: ${b.length} workflow(s)`)})}function QmZ(I){return w.gen(function*(){let G=yield*bZ,b=yield*(yield*V1).loadWorkflow(I).pipe(w.catchAll((W)=>w.gen(function*(){return yield*G.error(`Workflow not found: ${I}`),yield*G.info("Run 'jazz workflow list' to see available workflows."),yield*w.fail(W)})));if(yield*G.heading(`\uD83D\uDCCB Workflow: ${b.metadata.name}`),yield*G.log(""),yield*G.log(`Description: ${b.metadata.description}`),yield*G.log(`Path: ${b.metadata.path}`),b.metadata.agent)yield*G.log(`Agent: ${b.metadata.agent}`);if(b.metadata.schedule){let W=jE(b.metadata.schedule),l=W?`${W} (${b.metadata.schedule})`:b.metadata.schedule;yield*G.log(`Schedule: ${l}`)}if(b.metadata.autoApprove!==void 0)yield*G.log(`Auto-approve: ${b.metadata.autoApprove}`);if(b.metadata.skills&&b.metadata.skills.length>0)yield*G.log(`Skills: ${b.metadata.skills.join(", ")}`);if(b.metadata.catchUpOnStartup!==void 0)yield*G.log(`Catch-up on startup: ${b.metadata.catchUpOnStartup}`);if(b.metadata.maxCatchUpAge!==void 0)yield*G.log(`Max catch-up age (seconds): ${b.metadata.maxCatchUpAge}`);yield*G.log(""),yield*G.log(y5(60)),yield*G.log("Prompt:"),yield*G.log(y5(60)),yield*G.log(b.prompt)})}function mmZ(I,G){let Z=G?.json===!0,b=(l)=>Z?w.void:w.suspend(l),W=w.gen(function*(){let l=yield*bZ,Y=yield*V1,N=yield*gG,c=G?.autoApprove===!0||Z,X=G?.scheduled===!0;if(X){let k=(yield*(yield*N1).listScheduled().pipe(w.catchAll(()=>w.succeed([])))).find((L)=>L.workflowName===I);if(k?.scheduledAt){let L=new Date(k.scheduledAt).getTime(),p=Date.now(),x=60000;if(!Number.isNaN(L)&&p-L<60000){yield*N.info("Scheduler-triggered run skipped: workflow was just scheduled",{workflow:I,scheduledAt:k.scheduledAt,elapsedMs:p-L});return}}}yield*b(()=>l.heading(`\uD83D\uDE80 Running workflow: ${I}`)),yield*b(()=>l.log(""));let F=new Date().toISOString();yield*zA({workflowName:I,startedAt:F,status:"running",triggeredBy:X?"scheduled":"manual"}).pipe(w.catchAll(()=>w.void));let Q=(v)=>DE(I,{completedAt:new Date().toISOString(),status:"failed",error:v}).pipe(w.catchAll(()=>w.void)),m=yield*Y.loadWorkflow(I).pipe(w.catchAll((v)=>w.gen(function*(){return yield*Q(`Workflow not found: ${I}`),yield*b(()=>l.error(`Workflow not found: ${I}`)),yield*b(()=>l.info("Run 'jazz workflow list' to see available workflows.")),yield*w.fail(v)}))),R=G?.agent||m.metadata.agent||"default",H,h=yield*g0(R).pipe(w.either);if(h._tag==="Right")H=h.right,yield*b(()=>l.info(`Using agent: ${H.name} (${H.model})`));else{if(c){let k=`Agent '${R}' not found. Scheduled workflows require a valid agent — update the workflow or re-schedule with an existing agent.`;return yield*Q(k),yield*b(()=>l.error(`Agent '${R}' not found.`)),yield*b(()=>l.info("Scheduled workflows require a valid agent. Update the workflow or create the agent.")),yield*w.fail(Error(k))}let v=yield*f7();if(v.length===0)return yield*Q("No agents available. Create an agent first with: jazz agent create"),yield*l.error("No agents available."),yield*l.info("Create an agent first with: jazz agent create"),yield*w.fail(Error("No agents available. Create an agent first with: jazz agent create"));if(R!=="default")yield*l.warn(`Agent '${R}' not found.`);else yield*l.info("No default agent configured.");yield*l.log("");let A=yield*vmZ(v,"Select an agent to run this workflow:");if(!A){yield*DE(I,{completedAt:new Date().toISOString(),status:"skipped"}).pipe(w.catchAll(()=>w.void)),yield*l.info("Workflow cancelled.");return}H=A,yield*l.info(`Using agent: ${H.name} (${H.model})`)}let E=G?.autoApprove===!0?m.metadata.autoApprove??!0:m.metadata.autoApprove;if(E)yield*b(()=>l.info(`Auto-approve policy: ${E}`));yield*b(()=>l.log("")),yield*N.info("Starting workflow execution",{workflow:I,agent:H.name,autoApprove:E});let C=G?.maxIterations??m.metadata.maxIterations,J=kc.run({agent:H,userInput:m.prompt,sessionId:`workflow-${I}-${Date.now()}`,conversationId:`workflow-${I}-${Date.now()}`,...C!=null?{maxIterations:C}:{},...E!==void 0?{autoApprovePolicy:E}:{}}),y=yield*(G?.timeoutMs!=null?J.pipe(w.timeoutFail({duration:Hl.millis(G.timeoutMs),onTimeout:()=>Error(`Run exceeded the ${G.timeoutMs}ms timeout.`)})):J).pipe(w.tap((v)=>DE(I,{completedAt:new Date().toISOString(),status:"completed",...FmZ(v)}).pipe(w.catchAll(()=>w.void))),w.tapError((v)=>DE(I,{completedAt:new Date().toISOString(),status:"failed",error:v instanceof Error?v.message:String(v)}).pipe(w.catchAll(()=>w.void))),w.tapError(()=>w.sync(()=>{process.exitCode=1})));if(Z){let v=y.usage?.promptTokens??0,A=y.usage?.completionTokens??0,k=(y.toolCalls??[]).map((L)=>({id:L.id,name:L.function?.name??"",arguments:L.function?.arguments??""}));yield*w.sync(()=>{process.stdout.write(KMI({answer:y.content,costUSD:y.costUSD??0,tokenUsage:{promptTokens:v,completionTokens:A,totalTokens:v+A},toolCalls:k},{json:!0}))});return}if(yield*l.log(""),yield*l.success(`Workflow completed: ${I}`),c){let v={workflow:I,...FmZ(y)};yield*l.log(`[JAZZ_SUMMARY] ${JSON.stringify(v)}`)}});if(!Z)return W;return W.pipe(w.catchAll((l)=>w.sync(()=>{process.stdout.write(aMI(eq(l),{json:!0})),process.exitCode=1})),w.provide(CT(G?.eventTypes??new Set)))}function RmZ(I){return w.gen(function*(){let G=yield*bZ,Z=yield*V1,b=yield*N1;yield*G.heading(`⏰ Scheduling workflow: ${I}`),yield*G.log("");let W=yield*Z.loadWorkflow(I).pipe(w.catchAll((Q)=>w.gen(function*(){return yield*G.error(`Workflow not found: ${I}`),yield*G.info("Run 'jazz workflow list' to see available workflows."),yield*w.fail(Q)})));if(!W.metadata.schedule){yield*G.error(`Workflow '${I}' has no schedule defined.`),yield*G.info("Add a 'schedule' field to the workflow's WORKFLOW.md frontmatter."),yield*G.log(""),yield*G.log("Example:"),yield*G.log(" ---"),yield*G.log(" name: my-workflow"),yield*G.log(' schedule: "0 * * * *" # Every hour'),yield*G.log(" ---");return}let l=b.getSchedulerType();if(l==="unsupported"){yield*G.error("Scheduling is not supported on this platform."),yield*G.info("Supported platforms: macOS (launchd), Linux (cron)");return}if(yield*b.isScheduled(I))yield*G.info(`Workflow '${I}' is already scheduled. Updating...`);let N,c,X=W.metadata.agent||"default",F=yield*g0(X).pipe(w.either);if(F._tag==="Right")N=X,c=F.right.name,yield*G.info(`Using agent: ${c}`);else{let Q=yield*f7();if(Q.length===0)return yield*G.error("No agents available."),yield*G.info("Create an agent first with: jazz agent create"),yield*w.fail(Error("No agents available. Create an agent first with: jazz agent create"));if(X!=="default")yield*G.warn(`Agent '${X}' specified in workflow not found.`);else yield*G.info("No agent specified in workflow. Please select an agent:");yield*G.log("");let m=yield*vmZ(Q,"Select an agent to run this scheduled workflow:");if(!m){yield*G.info("Scheduling cancelled.");return}N=m.id,c=m.name,yield*G.info(`Using agent: ${c}`)}yield*G.log("");let d=!1;if(l==="launchd")d=yield*G.confirm("Run on login? (catches missed runs when your Mac was asleep)",!1),yield*G.log("");if(yield*b.schedule(W.metadata,N,{runAtLoad:d}),yield*G.success(`Workflow '${I}' scheduled successfully!`),yield*G.log(""),yield*G.log(` Schedule: ${W.metadata.schedule}`),yield*G.log(` Agent: ${c}`),yield*G.log(` Scheduler: ${l}`),d)yield*G.log(" Run on login: yes");if(yield*G.log(""),W.metadata.autoApprove)yield*G.info(`Auto-approve policy: ${W.metadata.autoApprove}`);else yield*G.warn("No auto-approve policy set. The workflow may pause for approval during scheduled runs."),yield*G.info("Add 'autoApprove: true' or 'autoApprove: low-risk' to the workflow.");yield*G.log(""),yield*G.info("Logs will be written to: ~/.jazz/logs/"),yield*G.info(`To unschedule: jazz workflow unschedule ${I}`)})}function HmZ(I){return w.gen(function*(){let G=yield*bZ,Z=yield*N1;if(yield*G.heading(`\uD83D\uDED1 Unscheduling workflow: ${I}`),yield*G.log(""),Z.getSchedulerType()==="unsupported"){yield*G.error("Scheduling is not supported on this platform.");return}if(!(yield*Z.isScheduled(I))){yield*G.info(`Workflow '${I}' is not currently scheduled.`);return}yield*Z.unschedule(I),yield*G.success(`Workflow '${I}' unscheduled successfully.`)})}function wmZ(){return w.gen(function*(){let I=yield*bZ;yield*I.heading("\uD83D\uDD04 Workflow catch-up"),yield*I.log(""),yield*I.info("Scheduled runs only fire when the machine is awake. If your Mac was asleep or off at the scheduled time, those runs were missed. Here you can run them now."),yield*I.log("");let G=yield*WbI().pipe(w.catchAll(()=>w.succeed([])));if(G.length===0){yield*I.info("No workflows need catch-up right now."),yield*I.log(""),yield*I.info("Workflows must be scheduled, have catchUpOnStartup: true, and have missed their last run within the max catch-up window.");return}yield*I.log("Workflows that missed a scheduled run:"),yield*I.log("");for(let l of G){let Y=l.decision.scheduledAt?.toISOString()??"—",N=jE(l.entry.schedule)??l.entry.schedule;yield*I.log(` • ${l.entry.workflowName} (${N}) — missed at ${Y}`)}yield*I.log("");let Z=G.map((l)=>({name:`${l.entry.workflowName} (${l.decision.scheduledAt?.toISOString()??"—"})`,value:l.entry.workflowName})),b=yield*I.checkbox("Select workflows to run now (Space to toggle, Enter to confirm):",{choices:Z,default:[]});if(b.length===0){yield*I.info("No workflows selected. Exiting.");return}let W=G.filter((l)=>b.includes(l.entry.workflowName)).map((l)=>l.entry);yield*I.log(""),yield*I.info(`Running catch-up for ${W.length} workflow(s)...`),yield*I.log(""),yield*lbI(W),yield*I.log(""),yield*I.success("Catch-up finished.")})}function hmZ(){return w.gen(function*(){let I=yield*bZ,G=yield*N1;yield*I.heading("⏰ Scheduled Workflows"),yield*I.log("");let Z=G.getSchedulerType();if(Z==="unsupported"){yield*I.error("Scheduling is not supported on this platform."),yield*I.info("Supported platforms: macOS (launchd), Linux (cron)");return}yield*I.info(`Scheduler: ${Z}`),yield*I.log("");let b=yield*G.listScheduled();if(b.length===0){yield*I.info("No workflows are currently scheduled."),yield*I.log(""),yield*I.info("To schedule a workflow: jazz workflow schedule <name>");return}for(let W of b){let l=W.enabled?"✓ enabled":"✗ disabled",Y=jE(W.schedule)??W.schedule;yield*I.log(` ${W.workflowName} (${Y}) agent: ${W.agent} ${l}`)}yield*I.log(""),yield*I.info(`Total: ${b.length} scheduled workflow(s)`)})}function JmZ(I){return w.gen(function*(){let G=yield*bZ;if(I)yield*G.heading(`\uD83D\uDCDC Run History: ${I}`);else yield*G.heading("\uD83D\uDCDC Recent Workflow Runs");yield*G.log("");let Z=yield*bKG(20),b=I?Z.filter((l)=>l.workflowName===I):Z;if(b.length===0){yield*G.info("No run history found."),yield*G.log(` History file: ${LZI()}`);return}let W=14400000;for(let l of b){let Y=Date.parse(l.startedAt),N=l.status==="running"&&Number.isFinite(Y)&&Date.now()-Y>W,c=N?"failed":l.status,X=c==="completed"?"✓":c==="failed"?"✗":c==="skipped"?"⊘":"…",F=l.completedAt?`${Math.round((new Date(l.completedAt).getTime()-new Date(l.startedAt).getTime())/1000)}s`:N?"failed (stale — process exited without updating)":"in progress",d=l.triggeredBy==="scheduled"?" (scheduled)":"";if(yield*G.log(` ${X} ${l.workflowName}${d} - ${c} (${F})`),yield*G.log(` Started: ${l.startedAt}`),l.error)yield*G.log(` Error: ${l.error}`);yield*G.log("")}yield*G.info(`Showing ${b.length} most recent run(s)`)})}function FmZ(I){return{...I.costUSD!==void 0?{costUSD:I.costUSD}:{},...I.usage!==void 0?{tokenUsage:I.usage}:{}}}function vmZ(I,G){return w.async((Z)=>{let b=I.map((W)=>({label:`${W.name} (${W.config.llmModel})`,value:W.id}));JI.setCustomView(_YI.createElement(XmZ,{flexDirection:"column",padding:1},_YI.createElement(QdW,{bold:!0,color:LI.primary},G),_YI.createElement(XmZ,{marginTop:1},_YI.createElement(pYI,{options:b,pageSize:10,placeholder:"Type to filter agents…",onSelect:(W)=>{JI.setCustomView(null),Z(w.succeed(I.find((l)=>l.id===W)??null))},onCancel:()=>{JI.setCustomView(null),Z(w.succeed(null))}}))))})}var EmZ=g(()=>{UI();HMI();nQ();fW();cJ();OC();aE();$W();nN();xMI();OU();BB();JkI();s7();Rq();wq();KgI();SMI()});function OO(I){return(G)=>{if(!/^\d+$/.test(G))throw Error(`${I} must be a positive integer (got "${G}").`);let Z=Number.parseInt(G,10);if(Z<=0)throw Error(`${I} must be a positive integer (got "${G}").`);return Z}}function mdW(I){I.command("run [prompt]").description("Run an agent once non-interactively (for scripts/webhooks). Prompt comes from the argument or piped stdin; the answer goes to stdout, all chatter to stderr.").requiredOption("--agent <agentId>","Agent ID or name to run").option("--json","Emit a single JSON envelope { ok, answer, costUSD, tokenUsage, toolCalls }").option("--approval-policy <policy>","Auto-approve tools up to a risk level: read-only | low-risk | high-risk (high-risk approves everything). Tools above the level are declined.").option("--timeout <ms>","Abort the run after this many milliseconds",OO("--timeout")).option("--max-iterations <n>","Maximum agent reasoning iterations for this run",OO("--max-iterations")).option("--events <categories>","Emit selected event categories as NDJSON to stderr during the run (comma-separated: tools,reasoning,text,usage,approval,subagent,all). stdout stays the clean payload.").option("--reasoning <effort>","Reasoning effort for this run: low | medium | high | disable (overrides the agent's config)").option("--conversation <id>","Stable conversation key (e.g. a Telegram chat id). Loads prior history for this key before the run and saves the updated transcript after, giving repeated invocations shared memory. Omit for a stateless one-shot run.").option("--stream","Force streaming mode. Required for --events to emit in non-TTY contexts (scripts, webhooks), where streaming is otherwise auto-disabled.").option("--no-stream","Disable streaming mode").action((G,Z)=>{let b=I.opts(),W=Z.json===!0;if(Z.approvalPolicy!==void 0&&!jMI(Z.approvalPolicy)){let Y=`Invalid --approval-policy "${Z.approvalPolicy}". Expected read-only, low-risk, or high-risk.`;if(W)process.stdout.write(`${JSON.stringify({ok:!1,error:Y,costUSD:0})}
7550
7550
  `);else process.stderr.write(`${Y}
7551
7551
  `);process.exitCode=1;return}let l=Z.events!==void 0?qMI(Z.events):void 0;if(l!==void 0&&!l.ok){if(W)process.stdout.write(`${JSON.stringify({ok:!1,error:l.error,costUSD:0})}
7552
7552
  `);else process.stderr.write(`${l.error}
7553
7553
  `);process.exitCode=1;return}if(Z.reasoning!==void 0&&!DMI(Z.reasoning)){let Y=`Invalid --reasoning "${Z.reasoning}". Expected low, medium, high, or disable.`;if(W)process.stdout.write(`${JSON.stringify({ok:!1,error:Y,costUSD:0})}
7554
7554
  `);else process.stderr.write(`${Y}
7555
- `);process.exitCode=1;return}process.env.JAZZ_NO_TUI="1",aN($QZ(Z.agent,G,{json:W,...Z.approvalPolicy!==void 0&&jMI(Z.approvalPolicy)?{approvalPolicy:Z.approvalPolicy}:{},...Z.reasoning!==void 0&&DMI(Z.reasoning)?{reasoningEffort:Z.reasoning}:{},...Z.timeout!==void 0?{timeoutMs:Z.timeout}:{},...Z.maxIterations!==void 0?{maxIterations:Z.maxIterations}:{},...l?.ok?{eventTypes:l.types}:{},...Z.conversation!==void 0?{conversationId:Z.conversation}:{}}),{verbose:b.verbose,debug:b.debug,configPath:b.config},{skipCatchUp:!0,skipUpdateCheck:!0})})}function RdW(I){let G=I.command("agent").description("Manage agents");G.command("list").alias("ls").description("List all agents").action(()=>{let Z=I.opts();aN(uYI(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})}),G.command("create").description("Create a new agent (interactive mode)").action(()=>{let Z=I.opts();aN(MYI(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})}),G.command("show <agentId>").description("Get an agent details").action((Z)=>{let b=I.opts();aN(dQZ(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("edit <agentId>").description("Edit an existing agent").action((Z)=>{let b=I.opts();aN(aYI(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("delete <agentId>").alias("remove").alias("rm").description("Delete an agent").option("-y, --yes","Delete without asking for confirmation").option("-f, --force","Alias for --yes").action((Z,b)=>{let W=I.opts();aN(gYI(Z,{skipConfirmation:b.yes===!0||b.force===!0}),{verbose:W.verbose,debug:W.debug,configPath:W.config})}),G.command("chat <agentIdentifier>").description("Start a chat with an AI agent by ID or name").option("--stream","Force streaming mode (real-time output)").option("--no-stream","Disable streaming mode").option("--max-iterations <n>","Maximum agent reasoning iterations per turn (default 80)",OO("--max-iterations")).action((Z,b)=>{let W=I.opts(),l=b.noStream===!0?!1:b.stream===!0?!0:void 0;aN(QQZ(Z,{...l!==void 0?{stream:l}:{},...b.maxIterations!==void 0?{maxIterations:b.maxIterations}:{}}),{verbose:W.verbose,debug:W.debug,configPath:W.config})})}function HdW(I){let G=I.command("config").description("Manage configuration");G.command("get <key>").description("Get a configuration value").action((Z)=>{let b=I.opts();aN(vQZ(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("set <key> [value]").description("Set a configuration value").action((Z,b)=>{let W=I.opts();aN(EQZ(Z,b),{verbose:W.verbose,debug:W.debug,configPath:W.config})}),G.command("show").description("Show all configuration values").action(()=>{let Z=I.opts();aN(JQZ(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})})}function wdW(I){let G=I.command("mcp").description("Manage MCP servers"),Z=(b)=>{let W=I.opts();aN(b,{verbose:W.verbose,debug:W.debug,configPath:W.config})};G.command("add [json]").description("Add an MCP server from JSON (inline, --file, or interactive)").option("-f, --file <path>","Read MCP server JSON from a file").action((b,W)=>{Z(UQZ(b,W?.file))}),G.command("list").alias("ls").description("List all configured MCP servers").action(()=>Z(BQZ())),G.command("remove").alias("rm").description("Remove an MCP server").action(()=>Z(OQZ())),G.command("enable").description("Enable a disabled MCP server").action(()=>Z(xQZ())),G.command("disable").description("Disable an enabled MCP server").action(()=>Z(MQZ()))}function hdW(I){let G=I.command("persona").description("Manage personas"),Z=(b)=>{let W=I.opts();aN(b,{verbose:W.verbose,debug:W.debug,configPath:W.config})};G.command("create").description("Create a new custom persona (interactive)").action(()=>Z(aQZ())),G.command("list").alias("ls").description("List all personas (built-in + custom)").action(()=>Z(jQZ())),G.command("show <identifier>").description("Show details of a persona by name or ID").action((b)=>Z(DQZ(b))),G.command("edit <identifier>").description("Edit an existing custom persona").action((b)=>Z(qQZ(b))),G.command("delete <identifier>").alias("rm").description("Delete a custom persona").action((b)=>Z(SQZ(b)))}function JdW(I){I.command("update").alias("upgrade").description("Update Jazz to the latest version").option("--check","Check for updates without installing").action((G)=>{let Z=I.opts();aN(klG(G),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})})}function vdW(I){let G=I.command("workflow").description("Manage and run workflows");G.command("list").alias("ls").description("List all available workflows").action(()=>{let Z=I.opts();aN(dmZ(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})}),G.command("show <name>").description("Show details of a workflow").action((Z)=>{let b=I.opts();aN(QmZ(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("run <name>").description("Run a workflow once").option("--auto-approve","Auto-approve tool executions based on workflow policy").option("--agent <agentId>","Agent ID or name to use for this workflow run").option("--max-iterations <n>","Maximum agent reasoning iterations (overrides the workflow's own setting)",OO("--max-iterations")).option("--scheduled","Indicates this run was triggered by the system scheduler (launchd/cron)").option("--json","Emit a single JSON envelope { ok, answer, costUSD, tokenUsage, toolCalls } on stdout (for scripts/gateways); all chatter is suppressed").option("--timeout <ms>","Abort the run after this many milliseconds",OO("--timeout")).option("--events <categories>","With --json: emit selected event categories as NDJSON to stderr during the run (comma-separated: tools,reasoning,text,usage,all). stdout stays the clean payload.").action((Z,b,W)=>{let l=I.opts(),Y=b.json===!0,N=W.name()==="run"&&W.parent?.name()==="workflow";if(b.events!==void 0&&!Y){process.stderr.write(`--events requires --json.
7555
+ `);process.exitCode=1;return}process.env.JAZZ_NO_TUI="1",aN($QZ(Z.agent,G,{json:W,...Z.approvalPolicy!==void 0&&jMI(Z.approvalPolicy)?{approvalPolicy:Z.approvalPolicy}:{},...Z.reasoning!==void 0&&DMI(Z.reasoning)?{reasoningEffort:Z.reasoning}:{},...Z.timeout!==void 0?{timeoutMs:Z.timeout}:{},...Z.maxIterations!==void 0?{maxIterations:Z.maxIterations}:{},...l?.ok?{eventTypes:l.types}:{},...Z.conversation!==void 0?{conversationId:Z.conversation}:{},...Z.noStream===!0?{stream:!1}:Z.stream===!0?{stream:!0}:{}}),{verbose:b.verbose,debug:b.debug,configPath:b.config},{skipCatchUp:!0,skipUpdateCheck:!0})})}function RdW(I){let G=I.command("agent").description("Manage agents");G.command("list").alias("ls").description("List all agents").action(()=>{let Z=I.opts();aN(uYI(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})}),G.command("create").description("Create a new agent (interactive mode)").action(()=>{let Z=I.opts();aN(MYI(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})}),G.command("show <agentId>").description("Get an agent details").action((Z)=>{let b=I.opts();aN(dQZ(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("edit <agentId>").description("Edit an existing agent").action((Z)=>{let b=I.opts();aN(aYI(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("delete <agentId>").alias("remove").alias("rm").description("Delete an agent").option("-y, --yes","Delete without asking for confirmation").option("-f, --force","Alias for --yes").action((Z,b)=>{let W=I.opts();aN(gYI(Z,{skipConfirmation:b.yes===!0||b.force===!0}),{verbose:W.verbose,debug:W.debug,configPath:W.config})}),G.command("chat <agentIdentifier>").description("Start a chat with an AI agent by ID or name").option("--stream","Force streaming mode (real-time output)").option("--no-stream","Disable streaming mode").option("--max-iterations <n>","Maximum agent reasoning iterations per turn (default 80)",OO("--max-iterations")).action((Z,b)=>{let W=I.opts(),l=b.noStream===!0?!1:b.stream===!0?!0:void 0;aN(QQZ(Z,{...l!==void 0?{stream:l}:{},...b.maxIterations!==void 0?{maxIterations:b.maxIterations}:{}}),{verbose:W.verbose,debug:W.debug,configPath:W.config})})}function HdW(I){let G=I.command("config").description("Manage configuration");G.command("get <key>").description("Get a configuration value").action((Z)=>{let b=I.opts();aN(vQZ(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("set <key> [value]").description("Set a configuration value").action((Z,b)=>{let W=I.opts();aN(EQZ(Z,b),{verbose:W.verbose,debug:W.debug,configPath:W.config})}),G.command("show").description("Show all configuration values").action(()=>{let Z=I.opts();aN(JQZ(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})})}function wdW(I){let G=I.command("mcp").description("Manage MCP servers"),Z=(b)=>{let W=I.opts();aN(b,{verbose:W.verbose,debug:W.debug,configPath:W.config})};G.command("add [json]").description("Add an MCP server from JSON (inline, --file, or interactive)").option("-f, --file <path>","Read MCP server JSON from a file").action((b,W)=>{Z(UQZ(b,W?.file))}),G.command("list").alias("ls").description("List all configured MCP servers").action(()=>Z(BQZ())),G.command("remove").alias("rm").description("Remove an MCP server").action(()=>Z(OQZ())),G.command("enable").description("Enable a disabled MCP server").action(()=>Z(xQZ())),G.command("disable").description("Disable an enabled MCP server").action(()=>Z(MQZ()))}function hdW(I){let G=I.command("persona").description("Manage personas"),Z=(b)=>{let W=I.opts();aN(b,{verbose:W.verbose,debug:W.debug,configPath:W.config})};G.command("create").description("Create a new custom persona (interactive)").action(()=>Z(aQZ())),G.command("list").alias("ls").description("List all personas (built-in + custom)").action(()=>Z(jQZ())),G.command("show <identifier>").description("Show details of a persona by name or ID").action((b)=>Z(DQZ(b))),G.command("edit <identifier>").description("Edit an existing custom persona").action((b)=>Z(qQZ(b))),G.command("delete <identifier>").alias("rm").description("Delete a custom persona").action((b)=>Z(SQZ(b)))}function JdW(I){I.command("update").alias("upgrade").description("Update Jazz to the latest version").option("--check","Check for updates without installing").action((G)=>{let Z=I.opts();aN(klG(G),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})})}function vdW(I){let G=I.command("workflow").description("Manage and run workflows");G.command("list").alias("ls").description("List all available workflows").action(()=>{let Z=I.opts();aN(dmZ(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})}),G.command("show <name>").description("Show details of a workflow").action((Z)=>{let b=I.opts();aN(QmZ(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("run <name>").description("Run a workflow once").option("--auto-approve","Auto-approve tool executions based on workflow policy").option("--agent <agentId>","Agent ID or name to use for this workflow run").option("--max-iterations <n>","Maximum agent reasoning iterations (overrides the workflow's own setting)",OO("--max-iterations")).option("--scheduled","Indicates this run was triggered by the system scheduler (launchd/cron)").option("--json","Emit a single JSON envelope { ok, answer, costUSD, tokenUsage, toolCalls } on stdout (for scripts/gateways); all chatter is suppressed").option("--timeout <ms>","Abort the run after this many milliseconds",OO("--timeout")).option("--events <categories>","With --json: emit selected event categories as NDJSON to stderr during the run (comma-separated: tools,reasoning,text,usage,approval,subagent,all). stdout stays the clean payload.").action((Z,b,W)=>{let l=I.opts(),Y=b.json===!0,N=W.name()==="run"&&W.parent?.name()==="workflow";if(b.events!==void 0&&!Y){process.stderr.write(`--events requires --json.
7556
7556
  `),process.exitCode=1;return}let c=b.events!==void 0?qMI(b.events):void 0;if(c!==void 0&&!c.ok){process.stdout.write(`${JSON.stringify({ok:!1,error:c.error,costUSD:0})}
7557
7557
  `),process.exitCode=1;return}if(Y)process.env.JAZZ_NO_TUI="1";aN(mmZ(Z,{...b,...b.timeout!==void 0?{timeoutMs:b.timeout}:{},...c?.ok?{eventTypes:c.types}:{}}),{verbose:l.verbose,debug:l.debug,configPath:l.config},{skipCatchUp:N,skipUpdateCheck:Y})}),G.command("schedule <name>").description("Enable scheduled execution for a workflow").action((Z)=>{let b=I.opts();aN(RmZ(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("unschedule <name>").description("Disable scheduled execution for a workflow").action((Z)=>{let b=I.opts();aN(HmZ(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})}),G.command("scheduled").description("List all scheduled workflows").action(()=>{let Z=I.opts();aN(hmZ(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})}),G.command("catchup").description("List workflows that missed a scheduled run, select which to run, then run them").action(()=>{let Z=I.opts();aN(wmZ(),{verbose:Z.verbose,debug:Z.debug,configPath:Z.config})}),G.command("history [name]").description("Show workflow run history").action((Z)=>{let b=I.opts();aN(JmZ(Z),{verbose:b.verbose,debug:b.debug,configPath:b.config})})}function ymZ(){return w.sync(()=>{let I=new rz;if(I.name("jazz").description("Create and manage autonomous AI agents that execute real-world tasks (email, git, web, shell, and more)").version(F0.version),I.option("-v, --verbose","Enable verbose logging").option("--debug","Enable debug level logging").option("--config <path>","Path to configuration file").option("--no-tui","Disable TUI; use plain terminal output (for CI, scripts, small terminals)").option("--output <mode>","Output mode: rendered, hybrid (default), raw (no formatting), or quiet (suppress output)"),I.hook("preAction",(G)=>{let Z=G.optsWithGlobals();if(Z.tui===!1)process.env.JAZZ_NO_TUI="1";if(Z.output)process.env.JAZZ_OUTPUT_MODE=Z.output}),mdW(I),RdW(I),hdW(I),HdW(I),wdW(I),JdW(I),vdW(I),process.argv.length<=2)I.action(()=>{let G=I.opts();aN(VmZ(),{verbose:G.verbose,debug:G.debug,configPath:G.config})});return I})}var CmZ=g(()=>{bbG();UI();s6();bQZ();zMI();mQZ();yQZ();gMI();BMI();KQZ();TQZ();SMI();lHI();cmZ();EmZ()});var pmZ={};SW(pmZ,{requestKey:()=>AmZ,isBypassHost:()=>LmZ,installWebCassette:()=>LdW});import{existsSync as EdW,readFileSync as ydW,writeFileSync as CdW}from"node:fs";function AmZ(I,G){let Z=typeof I==="string"?I:I instanceof URL?I.href:I.url,b=(G?.method??"GET").toUpperCase(),W="";if(typeof G?.body==="string")W=G.body;else if(G?.body instanceof URLSearchParams)W=G.body.toString();return`${b} ${Z} ${W}`}function LmZ(I){let G=typeof I==="string"?I:I instanceof URL?I.href:I.url,Z;try{Z=new URL(G).hostname}catch{return!1}return AdW.some((b)=>Z.includes(b))}function LdW(I,G){let Z=globalThis.fetch.bind(globalThis),b=EdW(I)?JSON.parse(ydW(I,"utf-8")):{};globalThis.fetch=async(W,l)=>{if(LmZ(W))return Z(W,l);let Y=AmZ(W,l);if(G==="replay"){let F=b[Y];if(!F)throw Error(`web-cassette replay miss: ${Y}`);return new Response(F.body,{status:F.status,headers:F.headers})}let N=await Z(W,l),c=await N.clone().text(),X={};return N.headers.forEach((F,d)=>X[d]=F),b[Y]={status:N.status,body:c,headers:X},CdW(I,JSON.stringify(b,null,2)),N}}var AdW;var zmZ=g(()=>{AdW=["openai.com","openrouter.ai","anthropic.com","googleapis.com","mistral.ai","groq.com","x.ai","together.xyz","together.ai","cohere.com","fireworks.ai","deepseek.com","moonshot","minimax","cerebras","dashscope","models.dev","localhost","127.0.0.1"]});var zdW={};function pdW(){return w.gen(function*(){if(process.env.JAZZ_WEB_CASSETTE){let{installWebCassette:G}=yield*w.promise(()=>Promise.resolve().then(() => (zmZ(),pmZ)));G(process.env.JAZZ_WEB_CASSETTE,process.env.JAZZ_WEB_MODE==="record"?"record":"replay")}(yield*ymZ()).parse()})}var kmZ=g(()=>{UI();CmZ();w.runPromise(pdW()).catch((I)=>{throw console.error("Fatal error:",I),I})});process.noDeprecation=!0;Promise.resolve().then(() => (kmZ(),zdW)).catch((I)=>{throw console.error("Fatal error:",I),I});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jazz-ai",
3
- "version": "0.13.1",
3
+ "version": "0.13.2",
4
4
  "description": "Your terminal. Your agent. Your rules.",
5
5
  "license": "MIT",
6
6
  "main": "dist/main.js",