@robota-sdk/agent-cli 3.0.0-beta.78 → 3.0.0-beta.79

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.
@@ -1,7 +1,7 @@
1
- import{createRequire as e}from"node:module";import{execFileSync as t,execSync as n,fork as r,spawn as i,spawnSync as a}from"node:child_process";import*as o from"node:readline";import{createHash as s,randomBytes as c,randomUUID as l}from"node:crypto";import u from"jssha";import d,{basename as f,dirname as p,isAbsolute as m,join as h,posix as g,relative as _,resolve as v,sep as y}from"node:path";import{constants as b,homedir as x,tmpdir as S}from"node:os";import{appendFileSync as C,constants as w,cpSync as ee,existsSync as T,lstatSync as E,mkdirSync as D,mkdtempSync as te,readFileSync as O,readdirSync as ne,renameSync as re,rmSync as ie,statSync as ae,unlinkSync as oe,writeFileSync as k}from"node:fs";import{access as se,chmod as ce,copyFile as le,mkdir as ue,readFile as de,readdir as fe,realpath as pe,rename as me,rm as he,stat as ge,writeFile as _e}from"node:fs/promises";import{Cron as ve}from"croner";import{z as A}from"zod";import ye from"fast-glob";import be from"p-limit";import{appendFileSync as j,existsSync as M,mkdirSync as xe,readFileSync as Se,readdirSync as Ce,renameSync as we,unlinkSync as Te,writeFileSync as Ee}from"fs";import{basename as De,dirname as Oe,join as N,resolve as ke}from"path";import{fileURLToPath as Ae}from"node:url";import{parseArgs as je}from"node:util";import Me from"@anthropic-ai/sdk";import Ne from"openai";import{FunctionCallingConfigMode as Pe,GoogleGenAI as Fe,Type as Ie}from"@google/genai";import{Box as P,Static as Le,Text as F,render as Re,useApp as ze,useInput as I,usePaste as Be,useStdout as Ve,useWindowSize as He}from"ink";import Ue,{createContext as We,useCallback as L,useContext as Ge,useEffect as R,useMemo as Ke,useRef as qe,useState as z}from"react";import{Fragment as Je,jsx as B,jsxs as V}from"react/jsx-runtime";import Ye from"chalk";import Xe from"string-width";import{marked as Ze}from"marked";import Qe from"marked-terminal";import{createServer as $e}from"node:http";import{WebSocket as et,WebSocketServer as tt}from"ws";import{createInterface as nt}from"node:readline/promises";import{createConnection as rt}from"node:net";import{zodToJsonSchema as it}from"zod-to-json-schema";function at(e){return{functionCalling:{supported:e},nativeWebTools:{webSearch:{supported:!1,enabled:!1,reason:`Provider does not declare native web search support.`},webFetch:{supported:!1,enabled:!1,reason:`Provider does not declare native web fetch support.`}}}}function ot(e){let t=typeof e.supportsTools==`function`?e.supportsTools():!1;return e.getCapabilities?.()??at(t)}function st(e,t,n){n?.webSearch===!0&&ct(e,`web search`,t.nativeWebTools.webSearch),n?.webFetch===!0&&ct(e,`web fetch`,t.nativeWebTools.webFetch)}function ct(e,t,n){if(!n.supported)throw Error(`Provider ${e} does not support native ${t}.${lt(n.reason)}`);if(!n.enabled)throw Error(`Provider ${e} supports native ${t} but it is not enabled.${lt(n.reason)}`)}function lt(e){return e?` ${e}`:``}function ut(e,t){return e.find(e=>e.type===t||e.aliases?.includes(t)===!0)}function dt(e){return e.map(e=>{if(!e.aliases||e.aliases.length===0)return e.type;let t=e.aliases.length===1?`alias`:`aliases`;return`${e.type} (${t}: ${e.aliases.join(`, `)})`}).join(`, `)}function ft(e){if(e?.credentialRequirement!==void 0)return e.credentialRequirement;if(e?.requiresApiKey===!0)return{anyOf:[`apiKey`]}}const pt=[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}];function mt(e,t,n){return{id:e,title:t,description:n?.description,options:pt,maxSelect:1,default:n?.defaultYes===void 0?void 0:{values:[n.defaultYes?`yes`:`no`]}}}function ht(e,t,n,r){return{id:e,title:t,options:n,maxSelect:1,description:r?.description,allowFreeText:r?.allowFreeText,maxVisible:r?.maxVisible,default:r?.default}}function gt(e,t,n){return{id:e,title:t,allowFreeText:!0,description:n?.description,masked:n?.masked,allowEmpty:n?.allowEmpty,placeholder:n?.placeholder,default:n?.default}}function _t(e){return e.type===`answer`&&e.values.includes(`yes`)}var vt=class{history=[];isInitialized=!1;config;async configure(e){this.config=e,await this.ensureInitialized()}getHistory(){return[...this.history]}clearHistory(){this.history=[]}addMessage(e){this.history.push(e)}validateInput(e){if(!e||typeof e!=`string`)throw Error(`Input must be a non-empty string`)}async ensureInitialized(){this.isInitialized||=(await this.initialize(),!0)}async dispose(){this.clearHistory(),this.isInitialized=!1}},yt=class{initialized=!1;async initialize(){this.initialized||=(await this.doInitialize(),!0)}async dispose(){await this.doDispose(),this.initialized=!1}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw Error(`${this.constructor.name} is not initialized`)}};function bt(e){if(!Array.isArray(e))throw Error(`Messages must be an array`);if(e.length===0)throw Error(`Messages array cannot be empty`);for(let t of e)if(!t.role||![`user`,`assistant`,`system`,`tool`].includes(t.role))throw Error(`Invalid message role: ${t.role}`)}function xt(e){if(e){if(!Array.isArray(e))throw Error(`Tools must be an array`);for(let t of e){if(!t.name||typeof t.name!=`string`)throw Error(`Tool must have a valid name`);if(!t.description||typeof t.description!=`string`)throw Error(`Tool must have a valid description`);if(!t.parameters||typeof t.parameters!=`object`||t.parameters===null||Array.isArray(t.parameters))throw Error(`Tool must have valid parameters`)}}}async function St(e,t,n,r){if(!e)throw Error(`Executor is required for ${t} provider. Configure an executor or use direct execution path.`);if(!r?.model)throw Error(`Model is required for executor execution in ${t} provider.`);return e.executeChat({messages:n,options:r,provider:t,model:r.model,...r.tools&&{tools:r.tools}})}async function*Ct(e,t,n,r){if(!e||!e.executeChatStream)throw Error(`Streaming executor is required for ${t} provider.`);if(!r?.model)throw Error(`Model is required for executor streaming in ${t} provider.`);let i=e.executeChatStream({messages:n,options:r,provider:t,model:r.model,stream:!0,...r.tools&&{tools:r.tools}});for await(let e of i)yield e}function wt(e){return e.category===`chat`}function Tt(e){let t=e.data;if(!t)throw Error(`Chat entry ${e.id} has no data`);return{...t,id:e.id,timestamp:e.timestamp}}function H(e){return{id:e.id,timestamp:e.timestamp,category:`chat`,type:e.role,data:{...e}}}function Et(e){return e.role===`assistant`}function Dt(e){return e.role===`system`}function Ot(e){return e.role===`tool`}const kt={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},log:()=>{},group:()=>{},groupEnd:()=>{}};var At=class e{static instance;globalLevel;constructor(){this.globalLevel=`warn`}static getInstance(){return e.instance||=new e,e.instance}getGlobalLevel(){return this.globalLevel}setGlobalLevel(e){this.globalLevel=e}},jt=class{level;packageName;sinkLogger;constructor(e,t){this.packageName=e,this.sinkLogger=t||kt}debug(...e){if(this.shouldLog(`debug`)){let[t,n]=e;this.forward(`debug`,String(t??``),Mt(n)?n:void 0)}}info(...e){if(this.shouldLog(`info`)){let[t,n]=e;this.forward(`info`,String(t??``),Mt(n)?n:void 0)}}warn(...e){if(this.shouldLog(`warn`)){let[t,n]=e;this.forward(`warn`,String(t??``),Mt(n)?n:void 0)}}error(...e){if(this.shouldLog(`error`)){let[t,n]=e;this.forward(`error`,String(t??``),Mt(n)?n:void 0)}}log(...e){this.info(...e)}getLevel(){return this.level||At.getInstance().getGlobalLevel()}shouldLog(e){let t=this.getLevel();if(t===`silent`)return!1;let n=[`debug`,`info`,`warn`,`error`,`silent`];return n.indexOf(e)>=n.indexOf(t)}forward(e,t,n){let r={timestamp:new Date().toISOString(),level:e,message:t,...n&&{context:n},packageName:this.packageName},i=`[${r.timestamp}] [${r.level.toUpperCase()}] [${r.packageName}] ${r.message}`;switch(e){case`debug`:this.sinkLogger.debug(i,n??{});return;case`info`:this.sinkLogger.info(i,n??{});return;case`warn`:this.sinkLogger.warn(i,n??{});return;case`error`:this.sinkLogger.error(i,n??{});return;case`silent`:return}}};function Mt(e){return typeof e==`object`&&!!e&&!(e instanceof Error)&&!(e instanceof Date)&&!Array.isArray(e)}function Nt(e,t){return new jt(e,t)}function Pt(e){At.getInstance().setGlobalLevel(e)}const U=Nt(`agents`);var Ft=class{config;executor;logger;constructor(e=kt){this.logger=e}async configure(e){this.config=e,this.hasExecutor(e)&&e.executor&&(this.executor=e.executor)}hasExecutor(e){return typeof e==`object`&&!!e&&`executor`in e}async*streamWithAbort(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await It(n,t);if(e.done||(await Lt(t),t?.aborted))break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async generateResponse(e){let t=await this.chat(e.messages,{...e.model!==void 0&&{model:e.model},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.tools!==void 0&&{tools:e.tools}});return{content:t.content??null,toolCalls:Et(t)?t.toolCalls:void 0,model:e.model,metadata:e.metadata}}async*generateStreamingResponse(e){if(!this.chatStream)throw Error(`[AI-PROVIDER] Streaming is not supported by provider "${this.name}"`);for await(let t of this.chatStream(e.messages,{...e.model!==void 0&&{model:e.model},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.tools!==void 0&&{tools:e.tools}}))yield{content:t.content??null,toolCalls:Et(t)?t.toolCalls:void 0,model:e.model,metadata:e.metadata}}supportsTools(){return!0}getCapabilities(){return at(this.supportsTools())}validateConfig(){return!0}validateMessages(e){bt(e)}validateTools(e){xt(e)}validateNativeWebTools(e){st(this.name,this.getCapabilities(),e)}async executeViaExecutorOrDirect(e,t){return St(this.executor,this.name,e,t)}async*executeStreamViaExecutorOrDirect(e,t){this.logger.debug?.(`🔍 [TOOL-FLOW] AbstractAIProvider.executeStreamViaExecutorOrDirect() - Executor request`,{provider:this.name,model:t?.model,hasTools:!!t?.tools,toolsCount:t?.tools?.length||0,toolNames:t?.tools?.map(e=>e.name)||[]}),yield*Ct(this.executor,this.name,e,t)}async dispose(){this.executor?.dispose&&await this.executor.dispose()}};async function It(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}async function Lt(e){e?.aborted||await new Promise(e=>setTimeout(e,0))}(function(e){return e.MONITORING=`monitoring`,e.LOGGING=`logging`,e.STORAGE=`storage`,e.NOTIFICATION=`notification`,e.SECURITY=`security`,e.PERFORMANCE=`performance`,e.ERROR_HANDLING=`error_handling`,e.LIMITS=`limits`,e.EVENT_PROCESSING=`event_processing`,e.CUSTOM=`custom`,e})({});let Rt=function(e){return e[e.CRITICAL=1e3]=`CRITICAL`,e[e.HIGH=800]=`HIGH`,e[e.NORMAL=500]=`NORMAL`,e[e.LOW=200]=`LOW`,e[e.MINIMAL=100]=`MINIMAL`,e}({});const zt={CREATED:`created`,EXECUTION_START:`execution_start`,EXECUTION_COMPLETE:`execution_complete`,EXECUTION_ERROR:`execution_error`,AGGREGATION_COMPLETE:`aggregation_complete`,CONFIG_UPDATED:`config_updated`},Bt=`agent`,Vt={START:`start`,COMPLETE:`complete`,ERROR:`error`,ASSISTANT_MESSAGE_START:`assistant_message_start`,ASSISTANT_MESSAGE_COMPLETE:`assistant_message_complete`,USER_MESSAGE:`user_message`,TOOL_RESULTS_TO_LLM:`tool_results_to_llm`,TOOL_RESULTS_READY:`tool_results_ready`},Ht=`execution`;function Ut(e){return`executionId`in e||`toolName`in e}function Wt(e){let t=0,n=!1;for(let r=0;r<e.length;r++){let i=e[r]===` `||e[r]===` `||e[r]===`
2
- `||e[r]===`\r`;!i&&!n?(t++,n=!0):i&&(n=!1)}return t}var Gt=class{listeners=new Set;subscribe(e){this.listeners.add(e)}unsubscribe(e){this.listeners.delete(e)}notifyListeners(e,t,n){for(let r of this.listeners)r(e,t,n)}},Kt=class extends Gt{emit(e,t,n){}};const qt=new Kt;function Jt(e){return e===qt||e instanceof Kt}function Yt(e,t){if(!e||e.trim().length===0)throw Error(`[EVENTS] ownerType is required to compose event names.`);if(e.includes(`.`))throw Error(`[EVENTS] ownerType must not contain '.': "${e}"`);if(!t||t.trim().length===0)throw Error(`[EVENTS] local event name is required.`);if(t.includes(`.`))throw Error(`[EVENTS] Local event name must not contain '.': "${t}"`);return`${e}.${t}`}function Xt(){return`span_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var Zt=class extends Gt{base;binding;constructor(e,t){super(),this.base=e,this.binding=t}emit(e,t,n){if(e.includes(`.`))throw Error(`[EVENTS] Local event name must not contain '.': "${e}"`);let r={...n,ownerType:this.binding.ownerType,ownerId:this.binding.ownerId,ownerPath:this.binding.ownerPath,depth:this.binding.ownerPath.length,spanId:n?.spanId??Xt()},i=Yt(this.binding.ownerType,e);this.base.emit(i,t,r)}subscribe(e){this.base.subscribe(e)}unsubscribe(e){this.base.unsubscribe(e)}};function Qt(e,t){return new Zt(e,t)}function $t(e,t,n,r,i,a,o){e.emitExecution(Vt.START,{parameters:{input:t,agentConfiguration:i.aiProviderInfo,availableTools:i.toolsInfo,toolCount:i.toolsInfo.length,hasTools:i.toolsInfo.length>0,systemMessage:n.systemMessage,provider:n.defaultModel.provider,model:n.defaultModel.model,temperature:n.defaultModel.temperature,maxTokens:n.defaultModel.maxTokens},metadata:{method:`execute`,inputLength:t.length,messageCount:r.length,aiProvider:i.aiProviderInfo.providerName,model:i.aiProviderInfo.model,toolsAvailable:i.toolsInfo.map(e=>e.name),agentCapabilities:{canUseTools:i.toolsInfo.length>0,supportedActions:i.toolsInfo.map(e=>e.name)}}},a,o)}function en(e,t,n,r){e.emitExecution(Vt.USER_MESSAGE,{parameters:{input:t,userPrompt:t,userMessageContent:t,messageLength:t.length,wordCount:Wt(t),characterCount:t.length},metadata:{messageRole:`user`,inputLength:t.length,messageType:`user_message`,hasQuestions:t.includes(`?`),containsUrgency:/urgent|asap|critical|emergency/i.test(t),estimatedComplexity:t.length>200?`high`:t.length>50?`medium`:`low`}},n,r)}function tn(e,t,n,r,i,a,o,s){if(typeof n.content!=`string`||n.content.length===0)throw Error(`[EXECUTION] assistant response must have content or tool calls`);if(!(n.timestamp instanceof Date))throw Error(`[EXECUTION] assistant response timestamp is required`);let c=n.content,l=n.timestamp,u=new Date().getTime()-l.getTime();e.emitWithContext(Vt.ASSISTANT_MESSAGE_COMPLETE,{parameters:{assistantMessage:c,responseLength:c.length,wordCount:Wt(c),responseTime:u,contentPreview:c.length>200?c.substring(0,200)+`...`:c},result:{success:!0,data:c.substring(0,100)+`...`,fullResponse:c,responseMetrics:{length:c.length,estimatedReadTime:Math.ceil(Wt(c)/200),hasCodeBlocks:/```/.test(c),hasLinks:/https?:\/\//.test(c),complexity:c.length>1e3?`high`:c.length>300?`medium`:`low`}},metadata:{executionId:r,round:i,completed:!0,reason:`no_tool_calls`,responseCharacteristics:{hasQuestions:c.includes(`?`),isError:/error|fail|wrong/i.test(c),isComplete:/complete|done|finish/i.test(c),containsNumbers:/\d/.test(c)}}},()=>e.buildResponseOwnerContext(a,r,o,s),e=>{if(!e.ownerType||!e.ownerId)throw Error(`[EXECUTION] Missing owner context for response event`);return Qt(t,{ownerType:e.ownerType,ownerId:e.ownerId,ownerPath:e.ownerPath})})}function nn(e,t,n,r,i,a,o,s,c,l){let u=n.map(e=>{if(!e.id||e.id.length===0)throw Error(`[EXECUTION] Tool call missing id for tool results ready payload`);return e.id});if(u.length===0)throw Error(`[EXECUTION] Tool results ready requires toolCallIds`);let d=()=>e.buildThinkingOwnerContext(a,o,c,l),f=e=>{if(!e.ownerType||!e.ownerId)throw Error(`[EXECUTION] Missing owner context for tool results event`);return Qt(t,{ownerType:e.ownerType,ownerId:e.ownerId,ownerPath:e.ownerPath})};e.emitWithContext(Vt.TOOL_RESULTS_READY,{parameters:{toolCallIds:u,round:s},metadata:{round:s}},d,f),e.emitWithContext(Vt.TOOL_RESULTS_TO_LLM,{parameters:{toolsExecuted:i.length,round:s},metadata:{toolsExecuted:r.results.map(e=>{if(!e.toolName||e.toolName.length===0)throw Error(`[EXECUTION] Tool result missing toolName`);return e.toolName}),round:s}},d,f)}var rn=class extends Error{context;constructor(e,t){super(e),this.context=t,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}},W=class extends rn{code=`CONFIGURATION_ERROR`;category=`user`;recoverable=!1;constructor(e,t){super(`Configuration Error: ${e}`,t)}},G=class extends rn{field;code=`VALIDATION_ERROR`;category=`user`;recoverable=!1;constructor(e,t,n){super(`Validation Error: ${e}`,n),this.field=t}},an=class extends rn{issues;attempts;code=`STRUCTURED_OUTPUT_ERROR`;category=`provider`;recoverable=!0;constructor(e,t,n,r){super(`Structured Output Error: ${e}`,r),this.issues=t,this.attempts=n}},on=class extends rn{provider;originalError;code=`PROVIDER_ERROR`;category=`provider`;recoverable=!0;constructor(e,t,n,r){super(`Provider Error (${t}): ${e}`,r),this.provider=t,this.originalError=n}},sn=class extends rn{provider;code=`AUTHENTICATION_ERROR`;category=`user`;recoverable=!1;constructor(e,t,n){super(`Authentication Error: ${e}`,n),this.provider=t}},cn=class extends rn{retryAfter;provider;code=`RATE_LIMIT_ERROR`;category=`provider`;recoverable=!0;constructor(e,t,n,r){super(`Rate Limit Error: ${e}`,r),this.retryAfter=t,this.provider=n}},ln=class extends rn{originalError;code=`NETWORK_ERROR`;category=`system`;recoverable=!0;constructor(e,t,n){super(`Network Error: ${e}`,n),this.originalError=t}},un=class extends rn{toolName;originalError;code=`TOOL_EXECUTION_ERROR`;category=`system`;recoverable=!1;constructor(e,t,n,r){super(`Tool Execution Error (${t}): ${e}`,r),this.toolName=t,this.originalError=n}},dn=class extends rn{pluginName;code=`PLUGIN_ERROR`;category=`system`;recoverable=!1;constructor(e,t,n){super(`Plugin Error (${t}): ${e}`,n),this.pluginName=t}},fn=class extends rn{code=`CACHE_INTEGRITY_ERROR`;category=`system`;recoverable=!1;constructor(e,t){super(`Cache Integrity Error: ${e}`,t)}};function pn(e){if(!e.executionId)throw new G(`[STRICT-POLICY][EMITTER-CONTRACT] Tool execution request missing executionId`);if(!e.ownerType)throw new G(`[STRICT-POLICY][EMITTER-CONTRACT] Tool execution request missing ownerType: executionId=${e.executionId}`);if(!e.ownerId)throw new G(`[STRICT-POLICY][EMITTER-CONTRACT] Tool execution request missing ownerId: executionId=${e.executionId}`);return{executionId:e.executionId,ownerType:e.ownerType,ownerId:e.ownerId}}function mn(e,t){let n=pn(e);return{toolName:e.toolName,parameters:e.parameters,...t?{signal:t}:{},executionId:n.executionId,ownerType:n.ownerType,ownerId:n.ownerId,ownerPath:e.ownerPath,metadata:e.metadata,eventService:e.eventService,baseEventService:e.baseEventService,...e.ask?{ask:e.ask}:{}}}function hn(e){return{toolName:e.toolName,executionId:e.executionId??``,success:!1,error:`Execution interrupted by user`,result:null}}function gn(e,t){return{toolName:e.toolName,result:null,success:!1,error:t.message,executionId:e.executionId}}function _n(e){return Error(`Tool execution failed: toolName=${String(e.toolName)} executionId=${String(e.executionId)} error=${String(e.error||`Unknown error`)}`)}function vn(e){return e!==void 0}function yn(e){return e!==void 0}function bn(e,t){if(e===0)return 0;if(t===void 0||!Number.isFinite(t))return e;let n=Math.floor(t);return n<1?1:Math.min(n,e)}async function xn(e,t,n,r){let i=e.requests[r];if(i)try{let a=e.signal?.aborted?hn(i):await t.executeTool(i.toolName,i.parameters,mn(i,e.signal));n.resultsByIndex[r]=a,a.success||(n.errorsByIndex[r]=_n(a))}catch(e){let t=e instanceof Error?e:Error(String(e));n.errorsByIndex[r]=t,n.resultsByIndex[r]=gn(i,t)}}async function Sn(e,t,n){for(;n.nextRequestIndex<e.requests.length;){let r=n.nextRequestIndex;n.nextRequestIndex+=1,await xn(e,t,n,r)}}async function Cn(e,t){let n={resultsByIndex:Array(e.requests.length),errorsByIndex:Array(e.requests.length),nextRequestIndex:0},r=bn(e.requests.length,e.maxConcurrency),i=Array.from({length:r},()=>Sn(e,t,n));await Promise.all(i);let a=n.resultsByIndex.filter(vn),o=n.errorsByIndex.filter(yn);if(o.length>0&&!e.continueOnError)throw o[0];return{results:a,errors:o}}async function wn(e,t){let n=[],r=[];for(let i of e.requests)try{let a=e.signal?.aborted?hn(i):await t.executeTool(i.toolName,i.parameters,mn(i,e.signal));if(n.push(a),a.success||r.push(_n(a)),!a.success&&!e.continueOnError)break}catch(t){let n=t instanceof Error?t:Error(String(t));if(r.push(n),!e.continueOnError)break}return{results:n,errors:r}}async function Tn(e,t,n){return n.debug(`Executing ${e.requests.length} tools in ${e.mode} mode`),e.mode===`parallel`?Cn(e,t):wn(e,t)}const En={CALL_START:`call_start`,CALL_COMPLETE:`call_complete`,CALL_ERROR:`call_error`,CALL_RESPONSE_READY:`call_response_ready`},Dn=`tool`,On=`unknown_tool`;var kn=class{tools;logger;askHandler;constructor(e,t=kt){this.tools=e,this.logger=t}setAskHandler(e){this.askHandler=e}async executeTool(e,t,n){this.logger.debug(`Executing tool: ${e}`);try{if(!n?.executionId)throw new G(`ToolExecutionService requires executionId (toolCallId) in ToolExecutionContext`);if(!this.tools.hasTool(e)){let t=this.tools.getTools().map(e=>e.name).sort(),r=An(e,t),i=n.eventService;if(i){let t={timestamp:new Date,toolName:e,error:r};i.emit(En.CALL_ERROR,t)}return this.logger.warn(`Tool call skipped because requested tool is not registered`,{toolName:e,availableTools:t}),{success:!1,error:r,toolName:e,executionId:n.executionId,metadata:{errorCode:On,requestedTool:e,availableTools:t}}}let r=n.eventService;if(r){let n={timestamp:new Date,toolName:e,parameters:t};r.emit(En.CALL_START,n)}let{toolName:i,parameters:a,...o}=n,s={...o,toolName:e,parameters:t,executionId:n.executionId},c=await this.tools.executeTool(e,t,s);if(this.logger.debug(`Tool execution completed: ${e}`),r){let t={timestamp:new Date,toolName:e,result:c};r.emit(En.CALL_COMPLETE,t),r.emit(En.CALL_RESPONSE_READY,t)}return{success:!0,result:c,toolName:e,executionId:s.executionId}}catch(t){this.logger.error(`Tool execution failed: ${e}`);let r=t instanceof Error?t:Error(String(t)),i=n?.eventService;if(i&&n?.executionId){let t={timestamp:new Date,toolName:e,error:r.message};i.emit(En.CALL_ERROR,t)}return{success:!1,error:r.message,toolName:e,executionId:n?.executionId}}}createExecutionRequestsWithContext(e,t){return e.map(e=>{let n;try{n=JSON.parse(e.function.arguments)}catch{throw new G(`Failed to parse arguments for tool "${e.function.name}" (call ${e.id}): invalid JSON`)}return{toolName:e.function.name,parameters:n,executionId:e.id,ownerType:`tool`,ownerId:e.id,ownerPath:[...t.ownerPathBase,{type:`tool`,id:e.id}],metadata:t.metadataFactory?t.metadataFactory(e):void 0,...this.askHandler?{ask:this.askHandler}:{}}})}async executeTools(e){return Tn(e,this,this.logger)}};function An(e,t){return`Tool "${e}" is not registered, so the tool call was not executed. Available tools: ${t.length>0?t.join(`, `):`no registered tools are available`}.`}function jn(e){return e?.ownerPath?.length?e.ownerPath.map(e=>({...e})):[]}function Mn(e,t,n,r){if(!n||n.length===0)throw Error(`[EXECUTION] Missing rootId for execution owner context`);if(!r||r.length===0)throw Error(`[EXECUTION] Missing executionId for execution owner context`);let i=[...e.length?e:t];return n&&!i.some(e=>e.type===`agent`&&e.id===n)&&i.push({type:`agent`,id:n}),i.push({type:`execution`,id:r}),{ownerType:Ht,ownerId:r,ownerPath:i}}function Nn(e,t,n,r,i,a){if(!i||i.length===0)throw Error(`[EXECUTION] Missing thinkingNodeId for thinking owner context`);let o=[...Mn(e,t,n,r).ownerPath];return a&&(o.push({type:`thinking`,id:a}),o.push({type:`tool_result`,id:`tool_result_${a}`})),o.push({type:`thinking`,id:i}),{ownerType:Ht,ownerId:r,ownerPath:o}}function Pn(e,t,n,r,i){if(!i||i.length===0)throw Error(`[EXECUTION] Missing toolCallId for tool owner context`);return{ownerType:Dn,ownerId:i,ownerPath:[...Mn(e,t,n,r).ownerPath,{type:`tool`,id:i}]}}function Fn(e,t,n,r,i,a){let o=Nn(e,t,n,r,i,a).ownerPath,s=`response_${i}`;return{ownerType:Ht,ownerId:r,ownerPath:[...o,{type:`response`,id:s}]}}var In=class{baseEventService;logger;ownerPathBase;toolEventServices;agentOwnerPathBase;constructor(e,t,n){this.baseEventService=e,this.logger=t,this.ownerPathBase=jn(n),this.toolEventServices=new Map,this.agentOwnerPathBase=[]}prepareOwnerPathBases(e){this.toolEventServices.clear();let t=[...this.ownerPathBase,{type:`agent`,id:e}];this.agentOwnerPathBase=t}resetOwnerPathBases(){this.toolEventServices.clear(),this.agentOwnerPathBase=[]}ensureToolEventService(e,t){if(Jt(this.baseEventService))return this.baseEventService;if(!e)throw Error(`[EVENT-SERVICE] Missing ownerId for tool event context`);if(!t||t.length===0)throw Error(`[EVENT-SERVICE] Missing ownerPath for tool event context`);if(this.toolEventServices.has(e))return this.toolEventServices.get(e);let n=Qt(this.baseEventService,{ownerType:Dn,ownerId:e,ownerPath:t.map(e=>({...e}))});return this.toolEventServices.set(e,n),n}clearToolEventServices(){this.toolEventServices.clear()}getBaseEventService(){return this.baseEventService}buildExecutionOwnerContext(e,t){return Mn(this.agentOwnerPathBase,this.ownerPathBase,e,t)}buildThinkingOwnerContext(e,t,n,r){return Nn(this.agentOwnerPathBase,this.ownerPathBase,e,t,n,r)}buildToolOwnerContext(e,t,n){return Pn(this.agentOwnerPathBase,this.ownerPathBase,e,t,n)}buildResponseOwnerContext(e,t,n,r){return Fn(this.agentOwnerPathBase,this.ownerPathBase,e,t,n,r)}emitExecution(e,t,n,r){this.emitWithContext(e,t,()=>this.buildExecutionOwnerContext(n,r),e=>{if(!e.ownerType||!e.ownerId)throw Error(`[EXECUTION] Missing owner context for execution event`);return Qt(this.baseEventService,{ownerType:e.ownerType,ownerId:e.ownerId,ownerPath:e.ownerPath})})}emitTool(e,t,n,r,i){this.emitWithContext(e,t,()=>this.buildToolOwnerContext(n,r,i),e=>this.ensureToolEventService(e.ownerId,e.ownerPath))}emitWithContext(e,t,n,r){if(Jt(this.baseEventService))return;let i=n(),a=r(i),o={timestamp:new Date,...t};a.emit(e,o,i)}emitExecutionStartEvent(e,t,n,r,i,a){$t(this,e,t,n,r,i,a)}emitUserMessageEvent(e,t,n){en(this,e,t,n)}emitAssistantMessageComplete(e,t,n,r,i,a){tn(this,this.baseEventService,e,t,n,r,i,a)}emitToolResultsEvents(e,t,n,r,i,a,o,s){nn(this,this.baseEventService,e,t,n,r,i,a,o,s)}};function Ln(e){let t=Rn(e.metadata),n=Bn(e.usage);return t??n}function Rn(e){if(!e)return;let t=Bn({inputTokens:Vn(e,`inputTokens`),outputTokens:Vn(e,`outputTokens`),promptTokens:Vn(e,`promptTokens`),completionTokens:Vn(e,`completionTokens`),totalTokens:Vn(e,`totalTokens`)});if(t)return t;let n=e.usage;if(typeof n==`string`)return zn(n);if(Un(n))return Bn(n)}function zn(e){try{return Bn(JSON.parse(e))}catch{return}}function Bn(e){if(!e)return;let t=Hn(e.inputTokens,e.promptTokens),n=Hn(e.outputTokens,e.completionTokens);if(t===void 0||n===void 0)return;let r=Hn(e.totalTokens);return{inputTokens:t,outputTokens:n,...r!==void 0&&{totalTokens:r}}}function Vn(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Hn(...e){return e.find(e=>typeof e==`number`&&Number.isFinite(e))}function Un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`number`&&Number.isFinite(e))}function Wn(e){return Math.ceil(JSON.stringify(e).length/4)}function Gn(e,t={}){let n=Wn(e),r=Kn(e),i=r?.tokens,a=qn(t.usageFloorTokens);return{usedTokens:r?.index===e.length-1?Math.max(i??0,a??0):Math.max(n,i??0,a??0),serializedTokens:n,...i!==void 0&&{providerTokens:i},...a!==void 0&&{usageFloorTokens:a}}}function Kn(e){for(let t=e.length-1;t>=0;t--){let n=Ln(e[t]);if(n)return{tokens:n.totalTokens??n.inputTokens+n.outputTokens,index:t}}}function qn(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.ceil(e)}const Jn={"claude-opus-4-6":{name:`Claude Opus 4.6`,id:`claude-opus-4-6`,contextWindow:1e6,maxOutput:128e3},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,id:`claude-sonnet-4-6`,contextWindow:1e6,maxOutput:64e3},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,id:`claude-haiku-4-5`,contextWindow:2e5,maxOutput:64e3},"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,id:`claude-haiku-4-5-20251001`,contextWindow:2e5,maxOutput:64e3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,id:`claude-sonnet-4-5`,contextWindow:2e5,maxOutput:64e3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,id:`claude-sonnet-4-5-20250929`,contextWindow:2e5,maxOutput:64e3},"claude-opus-4-5":{name:`Claude Opus 4.5`,id:`claude-opus-4-5`,contextWindow:2e5,maxOutput:64e3},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,id:`claude-opus-4-5-20251101`,contextWindow:2e5,maxOutput:64e3}};function Yn(e){return Jn[e]?.contextWindow??2e5}function Xn(e){return Jn[e]?.maxOutput??16384}function Zn(e){if(e>=1e6){let t=e/1e6;return Number.isInteger(t)?`${t}M`:`${parseFloat(t.toFixed(1))}M`}if(e<=0)return`0K`;if(e<1e3)return`<1K`;let t=e/1e3;return Number.isInteger(t)?`${t}K`:`${parseFloat(t.toFixed(1))}K`}const Qn=.95;function $n(e,t,n){let r=Gn(e,{usageFloorTokens:n}),i=Yn(t),a=i*Qn,o=i>0?Math.round(r.usedTokens/i*1e4)/100:100;return{shouldBlock:r.usedTokens>a,estimatedTokens:r.usedTokens,contextLimit:i,thresholdTokens:a,thresholdPercentage:Qn*100,usedPercentage:o,serializedTokens:r.serializedTokens,...r.providerTokens!==void 0&&{providerTokens:r.providerTokens},...r.usageFloorTokens!==void 0&&{usageFloorTokens:r.usageFloorTokens}}}function er(e,t,n,r,i,a){let o=$n(e,t.defaultModel.model,n.cumulativeInputTokens);return o.shouldBlock?(i.warn(`[ROUND] Context hard-capacity prevention before provider call`,{estimatedTokens:o.estimatedTokens,contextLimit:o.contextLimit,thresholdTokens:o.thresholdTokens,thresholdPercentage:o.thresholdPercentage,serializedTokens:o.serializedTokens,providerTokens:o.providerTokens??0,usageFloorTokens:o.usageFloorTokens??0,round:a}),r.addAssistantMessage(`Context window is near capacity. Cannot process further in this round. Estimated ${o.estimatedTokens.toLocaleString()} / ${o.contextLimit.toLocaleString()} tokens (${Math.round(o.usedPercentage)}%) exceeds the hard-block threshold ${Math.round(o.thresholdPercentage)}%. Run /compact and retry.`,[],{round:a,contextOverflow:!0,estimatedTokens:o.estimatedTokens,contextLimit:o.contextLimit,thresholdTokens:o.thresholdTokens,thresholdPercentage:o.thresholdPercentage,serializedTokens:o.serializedTokens,providerTokens:o.providerTokens??0,usageFloorTokens:o.usageFloorTokens??0,usedPercentage:o.usedPercentage}),!0):!1}const tr={beforeRun:async(e,t)=>{e.beforeRun&&t.input&&await e.beforeRun(t.input,t.metadata)},afterRun:async(e,t)=>{e.afterRun&&t.input&&t.response&&await e.afterRun(t.input,t.response,t.metadata)},beforeProviderCall:async(e,t)=>{e.beforeProviderCall&&t.messages&&await e.beforeProviderCall(t.messages)},afterProviderCall:async(e,t)=>{e.afterProviderCall&&t.messages&&t.responseMessage&&await e.afterProviderCall(t.messages,t.responseMessage)},onError:async(e,t)=>{if(e.onError&&t.error){let n={action:`${Ht}.${Vt.ERROR}`,metadata:{}},r=t.executionContext?.executionId;typeof r==`string`&&r.length>0&&(n.executionId=r);let i=t.executionContext?.sessionId;typeof i==`string`&&i.length>0&&(n.sessionId=i);let a=t.executionContext?.userId;typeof a==`string`&&a.length>0&&(n.userId=a),await e.onError(t.error,n)}}};async function nr(e,t,n,r){let i=tr[t];if(i)for(let a of e)try{await i(a,n)}catch(e){r.warn(`Plugin hook failed`,{pluginName:a.name,hookName:t,error:e instanceof Error?e.message:String(e)})}}function rr(e){if(e?.type){if(e.type===`json_schema`){if(!e.schema)throw Error(`responseFormat.schema is required when type is 'json_schema'.`);return{type:`json_schema`,schema:e.schema,...e.name&&{name:e.name}}}return{type:e.type}}}function ir(e,t){return e===void 0||t<=1?e:e===`required`||typeof e==`object`?`auto`:e}function ar(e,t){if(e===void 0||e===`auto`||e===`none`)return;let n=(t??[]).map(e=>e.name);if(e===`required`){if(n.length===0)throw Error(`toolChoice 'required' needs at least one tool, but the run has none.`);return}if(!n.includes(e.tool))throw Error(`toolChoice requests tool "${e.tool}" which is not available for this run. Available tools: ${n.length>0?n.join(`, `):`(none)`}`)}function or(e,t,n){let r=e.getCurrentProvider(),i=r?e.getProvider(r.provider):null;if(!r||!r.provider||!i)throw Error(`[EXECUTION] Provider is required`);let a=t.getTools();return{provider:i,currentInfo:r,aiProviderInfo:{providerName:r.provider,model:n.defaultModel.model,temperature:n.defaultModel.temperature,maxTokens:n.defaultModel.maxTokens},toolsInfo:a.map(e=>{let t=e.parameters?.properties;if(!e.description||e.description.length===0)throw Error(`[EXECUTION] Tool "${e.name}" is missing description`);return{name:e.name,description:e.description,parameters:t&&typeof t==`object`?Object.keys(t):[]}}),availableTools:a}}function sr(e){if(!e.currentInfo)throw Error(`No AI provider configured`);if(!e.provider)throw Error(`AI provider '${e.currentInfo.provider}' not found`);if(typeof e.provider.chat!=`function`)throw Error(`Provider must have chat method to support execution`)}function cr(e,t,n,r,i){let a=e.getConversationStore(t);if(!a.getMessages().some(e=>e.role!==`system`)&&n.length>0){for(let e of n)if(e.role===`user`)a.addUserMessage(e.content,e.metadata,e.parts);else if(e.role===`assistant`)a.addAssistantMessage(e.content,e.toolCalls,e.metadata,e.parts);else if(e.role===`tool`){let t=e.metadata?.toolName;if(typeof t!=`string`||t.length===0)throw Error(`[EXECUTION] Tool message missing toolName metadata`);a.addToolMessageWithId(e.content,e.toolCallId,t,e.metadata,e.parts)}}let o=a.getMessages().some(e=>e.role===`system`);return r.systemMessage&&!o&&a.setSystemPrompt(r.systemMessage,{executionId:i}),a}function lr(e,t,n,r){let i=e.getMessages(),a=i.filter(e=>e.role===`assistant`&&typeof e.content==`string`&&e.content.length>0).pop(),o=a?a.content:`No response received. The context window may be full.`,s=a?.metadata?.providerError===!0,c=Date.now()-n.getTime();return{response:o,messages:i.map(e=>{if(typeof e.content!=`string`)throw Error(`[EXECUTION] Message content is required`);return{role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata,...e.role===`assistant`&&`toolCalls`in e?{toolCalls:e.toolCalls}:{},...e.role===`tool`&&`toolCallId`in e?{toolCallId:e.toolCallId}:{}}}),executionId:t,duration:c,tokensUsed:i.filter(e=>e.metadata?.usage).reduce((e,t)=>{let n=t.metadata?.usage;if(n&&typeof n==`object`&&`totalTokens`in n){let t=Number(n.totalTokens);if(Number.isNaN(t))throw Error(`[EXECUTION] totalTokens must be a number`);return e+t}return e},0),toolsExecuted:r,success:!!a&&!s,...s?{error:Error(o)}:{}}}async function ur(e,t,n,r,i,a,o,s){let c=Date.now()-n.getTime();await nr(a,`onError`,{error:e instanceof Error?e:Error(String(e)),executionContext:mr(t)},o),o.error(`Execution pipeline failed`,{executionId:i,conversationId:r,duration:c,error:e instanceof Error?e.message:String(e)}),s.emitExecution(Vt.ERROR,{error:e instanceof Error?e.message:String(e),metadata:{method:`execute`,success:!1,duration:c}},r,i)}function dr(){return`exec_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function fr(e,t){if(!e?.conversationId||e.conversationId.length===0)throw Error(`[EXECUTION] conversationId is required for ${t}`);return e.conversationId}function pr(e,t,n,r,i,a){return{messages:e,config:t,startTime:n,executionId:r,conversationId:i,...a?.sessionId&&{sessionId:a.sessionId},...a?.userId&&{userId:a.userId},...a?.metadata&&{metadata:a.metadata},...a?.signal&&{signal:a.signal},...a?.onTextDelta&&{onTextDelta:a.onTextDelta},...a?.onExecutionEvent&&{onExecutionEvent:a.onExecutionEvent},...a?.maxExecutionRounds!==void 0&&{maxExecutionRounds:a.maxExecutionRounds},...a?.maxSameToolInputs!==void 0&&{maxSameToolInputs:a.maxSameToolInputs},...a?.allowToolOnlyCompletion!==void 0&&{allowToolOnlyCompletion:a.allowToolOnlyCompletion},...a?.maxTokens!==void 0&&{maxTokens:a.maxTokens},...a?.temperature!==void 0&&{temperature:a.temperature},...a?.toolChoice!==void 0&&{toolChoice:a.toolChoice}}}function mr(e){let t={conversationId:fr(e,`plugin-context`),executionId:e.executionId,startTime:e.startTime.toISOString(),messageCount:e.messages.length};return e.sessionId&&(t.sessionId=e.sessionId),e.userId&&(t.userId=e.userId),t}function hr(e,t){let n=Array.isArray(t.lastTrackedAssistantMessage?.toolCalls)&&t.lastTrackedAssistantMessage.toolCalls.length>0;return{thinkingNodeId:`thinking_${e}_round${t.runningAssistantCount+1}`,previousThinkingNodeId:n?`thinking_${e}_round${t.runningAssistantCount}`:void 0}}async function gr(e,t,n,r,i){if(!t.defaultModel?.model)throw Error(`Model is required in defaultModel configuration. Please specify a model.`);if(typeof t.defaultModel.model!=`string`||t.defaultModel.model.trim()===``)throw Error(`Model must be a non-empty string in defaultModel configuration.`);let a={model:t.defaultModel.model,effort:t.defaultModel.effort??`high`,...t.defaultModel.maxTokens!==void 0&&{maxTokens:t.defaultModel.maxTokens},...t.defaultModel.temperature!==void 0&&{temperature:t.defaultModel.temperature},...t.defaultModel.toolChoice!==void 0&&{toolChoice:t.defaultModel.toolChoice},...n.availableTools.length>0&&{tools:n.availableTools},...(()=>{let e=rr(t.responseFormat);return e?{responseFormat:e}:{}})(),...i};ar(a.toolChoice,a.tools);let o=n.provider.chat.bind(n.provider);if(r){let n=r.lookup(e,t.defaultModel.model,t.defaultModel.provider,{temperature:t.defaultModel.temperature,maxTokens:t.defaultModel.maxTokens});if(n)return{role:`assistant`,content:n,timestamp:new Date,id:l(),state:`complete`};let i=await _r(o,e,a,t.timeout);return typeof i.content==`string`&&r.store(e,t.defaultModel.model,t.defaultModel.provider,i.content,{temperature:t.defaultModel.temperature,maxTokens:t.defaultModel.maxTokens}),i}return _r(o,e,a,t.timeout)}async function _r(e,t,n,r){let i=vr(r),a=n.signal;if(i===void 0&&a===void 0)return e(t,n);if(a?.aborted)throw yr();let o=new AbortController,s,c=!1,l,u=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},d=e=>{c||(c=!0,l?.(e),o.abort(e))},f=()=>{i===void 0||c||(u(),s=setTimeout(()=>{d(Error(`Provider call idle timeout after ${i}ms`))},i))},p=()=>{d(yr())};a?.addEventListener(`abort`,p,{once:!0});let m=n.onTextDelta,h={...n,signal:o.signal,...m===void 0?{}:{onTextDelta:e=>{f(),m(e)}}};f();try{return await Promise.race([e(t,h),new Promise((e,t)=>{l=t})])}finally{c=!0,u(),a?.removeEventListener(`abort`,p)}}function vr(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return e}function yr(){let e=Error(`aborted`);return e.name=`AbortError`,e}function br(e,t,n,r,i){let a=e.role===`assistant`?e.toolCalls:void 0,o=Array.isArray(a)&&a.length>0;if(typeof e.content!=`string`&&!o)throw Error(`[EXECUTION] Provider response must have content or tool calls`);if(a&&!Array.isArray(a))throw Error(`[EXECUTION] assistant toolCalls must be an array`);let s=e.content??``;if(i.debug(`[ROUND-${r}] Provider response completed`,{executionId:t,conversationId:n,round:r,responseLength:s.length,hasToolCalls:Array.isArray(a)&&a.length>0,toolCallsCount:Array.isArray(a)?a.length:0}),e.role!==`assistant`)throw Error(`Unexpected response role: ${e.role}`);let c=e,l=c.toolCalls??[];if(!Array.isArray(l))throw Error(`[EXECUTION] assistantResponse.toolCalls must be an array`);return{assistantResponse:c,assistantToolCalls:l}}function xr(e,t,n,r){let i=0,a=0;return{wrappedOnTextDelta:a=>{e.onExecutionEvent?.(`provider_stream_raw_delta`,{executionId:n,conversationId:e.conversationId,round:r,sequence:i,delta:a}),i++,t.appendStreaming(a),e.onTextDelta?.(a)},wrappedOnProviderNativeRawPayload:t=>{let i=t.sequence??a;a=Math.max(a,i+1),e.onExecutionEvent?.(`provider_native_raw_payload`,{executionId:n,conversationId:e.conversationId,round:r,...t,sequence:i})}}}async function Sr(e,t,n,r,i,a,o,s,c,l,u){try{i.onExecutionEvent?.(`provider_request`,{executionId:s,conversationId:i.conversationId,round:o,provider:n.currentInfo.provider,model:t.defaultModel.model,messages:e,tools:n.availableTools});let a=await gr(e,t,n,r,{signal:i.signal,onTextDelta:l,onProviderNativeRawPayload:u,...i.maxTokens!==void 0&&{maxTokens:i.maxTokens},...i.temperature!==void 0&&{temperature:i.temperature},...(()=>{let e=ir(i.toolChoice??t.defaultModel.toolChoice,o);return e===void 0?{}:{toolChoice:e}})()});return i.onExecutionEvent?.(`provider_response_raw`,{executionId:s,conversationId:i.conversationId,round:o,response:a,responseKind:`provider-normalized-message`}),i.onExecutionEvent?.(`provider_response_normalized`,{executionId:s,conversationId:i.conversationId,round:o,response:a,toolCallsCount:a.role===`assistant`&&Array.isArray(a.toolCalls)?a.toolCalls.length:0}),a}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`)))throw a.commitAssistant(`interrupted`,{round:o}),e;a.discardPending();let t=e instanceof Error?e.message:String(e);return c.error(`[ROUND] Provider call failed`,{error:t,round:o}),a.addAssistantMessage(`Request failed: ${t}`,[],{round:o,providerError:!0}),null}}function Cr(e){return!e.success&&e.metadata?.errorCode===`unknown_tool`}function wr(e,t,n,r,i,a){let o=!1,s=0,c=0;for(let l of e){if(!l.id)throw Error(`Tool call missing ID: ${JSON.stringify(l)}`);let e=l.function?.name;if(!e||e.length===0)throw Error(`[EXECUTION] Tool call "${l.id}" missing function name`);if(o){i.warn(`[ROUND] Skipping tool result due to context overflow`,{toolCallId:l.id,toolName:e,round:r}),n.addToolMessageWithId(`Error: Context window near capacity. Tool execution result skipped. Respond with available results and re-request skipped tools if needed.`,l.id,e,{round:r,success:!1,error:`context_overflow`,toolName:e}),c++;continue}let u=t.results.find(e=>e.executionId===l.id),d=t.errors.find(e=>Ut(e)&&e.executionId===l.id),f,p={round:r};if(u&&u.success){if(u.result===void 0)throw Error(`[EXECUTION] Tool result missing result payload`);f=typeof u.result==`string`?u.result:JSON.stringify(u.result),p.success=!0,u.toolName&&(p.toolName=u.toolName)}else if(u&&!u.success){if(!u.error||u.error.length===0)throw Error(`[EXECUTION] Tool result missing error message`);f=`Error: ${u.error}`,p.success=!1,p.error=u.error,u.toolName&&(p.toolName=u.toolName),u.metadata?.errorCode===`unknown_tool`&&(p.errorCode=On,typeof u.metadata.requestedTool==`string`&&(p.requestedTool=u.metadata.requestedTool),Array.isArray(u.metadata.availableTools)&&(p.availableTools=u.metadata.availableTools.filter(e=>typeof e==`string`)))}else if(d){let e=d,t=e.error?.message?e.error.message:e.message?e.message:``;if(!t||t.length===0)throw Error(`[EXECUTION] Tool execution error missing message`);f=`Error: ${t}`,p.success=!1,p.error=t,e.toolName&&(p.toolName=e.toolName)}else throw Error(`No execution result found for tool call ID: ${l.id}`);if(i.debug(`Adding tool result to conversation`,{toolCallId:l.id,toolName:e,content:f.substring(0,100),round:r,currentHistoryLength:n.getMessages().length}),n.addToolMessageWithId(f,l.id,e,p),a){let e=Gn(n.getMessages(),{usageFloorTokens:a.cumulativeInputTokens}).usedTokens;e>a.contextLimit*.8&&(i.warn(`[ROUND] Context budget exceeded after tool result — skipping remaining tools`,{estimatedTokens:e,contextLimit:a.contextLimit,toolCallId:l.id,round:r}),o=!0)}s++,i.debug(`Tool result added to history`,{toolCallId:l.id,newHistoryLength:n.getMessages().length,round:r})}return{contextOverflowed:o,addedCount:s,skippedCount:c,unknownToolFailureCount:0,unknownToolNames:[]}}function Tr(e,t,n){for(let r of e){let e=r.function?.name??`unknown`,i=`${e}::${typeof r.function?.arguments==`string`?r.function.arguments:JSON.stringify(r.function?.arguments??{})}`,a=(t.sameToolInputCounts.get(i)??0)+1;if(t.sameToolInputCounts.set(i,a),a>n)throw Error(`[EXECUTION] Tool "${e}" called with identical input ${a} times — aborting to prevent infinite loop`)}}async function Er(e,t,n,r,i,a,o,s,c,l,u,d,f){let{toolExecutionService:p,logger:m,eventEmitter:h}=c,g=f??l?.maxSameToolInputs;g!==void 0&&Tr(e,s,g),m.debug(`Tool calls detected, executing tools`,{toolCallCount:e.length,round:i,toolCalls:e.map(e=>({id:e.id,name:e.function?.name}))});let _=h.buildThinkingOwnerContext(n,r,a,o).ownerPath,v=e.length,y=`${a}`,b=p.createExecutionRequestsWithContext(e,{ownerPathBase:_,metadataFactory:e=>({conversationId:n,round:i,directParentId:a,batchId:y,expectedCount:v,toolCallId:e.id})}).map(e=>{if(!e.ownerId)throw Error(`[EXECUTION] Tool request missing ownerId`);return{...e,eventService:h.ensureToolEventService(e.ownerId,e.ownerPath),baseEventService:h.getBaseEventService()}}),x={requests:b,mode:`parallel`,maxConcurrency:5,continueOnError:!0,signal:u};d?.(`tool_batch_started`,{executionId:r,conversationId:n,round:i,batchId:y,mode:x.mode,maxConcurrency:x.maxConcurrency,requestCount:b.length,tools:b.map(e=>e.toolName)}),b.forEach((e,t)=>{d?.(`tool_execution_request`,{executionId:r,conversationId:n,round:i,batchId:y,index:t,toolName:e.toolName,toolCallId:e.executionId,parameters:e.parameters,ownerPath:e.ownerPath})});let S=await p.executeTools(x),C=S.results.filter(Cr).map(e=>e.toolName).filter(e=>typeof e==`string`&&e.length>0);S.results.forEach((e,t)=>{d?.(`tool_execution_result`,{executionId:r,conversationId:n,round:i,batchId:y,index:t,toolName:e.toolName,toolCallId:e.executionId,success:e.success,result:e.result,error:e.error,metadata:e.metadata})}),s.toolsExecuted.push(...S.results.filter(e=>!Cr(e)).map(e=>{if(!e.toolName||e.toolName.length===0)throw Error(`[EXECUTION] Tool result missing toolName`);return e.toolName}));let w=Yn(l?.defaultModel?.model??``),ee=t.getMessages().length,T=wr(e,S,t,i,m,{contextLimit:w,cumulativeInputTokens:s.cumulativeInputTokens});return t.getMessages().slice(ee).forEach((e,t)=>{d?.(`tool_message_committed`,{executionId:r,conversationId:n,round:i,batchId:y,index:t,message:e}),d?.(`history_mutation`,{executionId:r,conversationId:n,round:i,batchId:y,mutation:`append_message`,index:ee+t,message:e})}),h.emitToolResultsEvents(e,S,s.toolsExecuted,n,r,i,a,o),h.clearToolEventServices(),{...T,unknownToolFailureCount:C.length,unknownToolNames:C}}function Dr(e){let t=0,n=0,r=!1;for(let i of e){if(!wt(i)||i.data===void 0)continue;let e=Tt(i);if(e.role!==`assistant`)continue;let a=Or(e);a&&(r=!0,t+=a.inputTokens,n+=a.outputTokens)}if(r)return{promptTokens:t,completionTokens:n,totalTokens:t+n}}function Or(e){let t=Ln(e);if(!t)return;let n=t.totalTokens??t.inputTokens+t.outputTokens;return{inputTokens:t.inputTokens,outputTokens:t.outputTokens,usage:{totalTokens:n,inputTokens:t.inputTokens,outputTokens:t.outputTokens}}}async function kr(e,t,n,r,i,a,o,s,c){let{plugins:l,logger:u,eventEmitter:d,cacheService:f}=c,p=e.currentRound;u.debug(`[ROUND-${p}] Starting execution round ${p}`,{executionId:i,conversationId:a.conversationId,round:p,maxRounds:t});let m=n.getMessages(),{thinkingNodeId:h,previousThinkingNodeId:g}=hr(r,e);if(await nr(l,`beforeProviderCall`,{messages:m},u),u.debug(`Sending messages to AI provider`,{round:p,messageCount:m.length,lastFewMessages:m.slice(-5).map(e=>({role:e.role,content:e.content?.substring(0,50),hasToolCalls:`toolCalls`in e?!!e.toolCalls?.length:!1,toolCallId:`toolCallId`in e?e.toolCallId:void 0}))}),d.emitWithContext(Vt.ASSISTANT_MESSAGE_START,{parameters:{round:p,messageCount:m.length},metadata:{round:p,thinkingNodeId:h}},()=>d.buildThinkingOwnerContext(r,i,h,g),e=>{if(!e.ownerType||!e.ownerId)throw Error(`[EXECUTION] Missing owner context for thinking event`);return Qt(d.getBaseEventService(),{ownerType:e.ownerType,ownerId:e.ownerId,ownerPath:e.ownerPath})}),er(m,o,e,n,u,p))return!0;p>1&&a.onTextDelta?.(`
1
+ import{createRequire as e}from"node:module";import{execFileSync as t,execSync as n,fork as r,spawn as i,spawnSync as a}from"node:child_process";import*as o from"node:readline";import{createHash as s,randomBytes as c,randomUUID as l}from"node:crypto";import u from"jssha";import d,{basename as f,dirname as p,isAbsolute as m,join as h,posix as g,relative as _,resolve as v,sep as y}from"node:path";import{constants as b,homedir as x,tmpdir as S}from"node:os";import{appendFileSync as C,constants as w,cpSync as T,existsSync as E,lstatSync as D,mkdirSync as O,mkdtempSync as k,readFileSync as A,readdirSync as ee,renameSync as te,rmSync as ne,statSync as re,unlinkSync as ie,writeFileSync as ae}from"node:fs";import{access as oe,chmod as se,copyFile as ce,mkdir as le,readFile as ue,readdir as de,realpath as fe,rename as pe,rm as me,stat as he,writeFile as ge}from"node:fs/promises";import{Cron as _e}from"croner";import{z as j}from"zod";import ve from"fast-glob";import ye from"p-limit";import{appendFileSync as M,existsSync as N,mkdirSync as be,readFileSync as xe,readdirSync as Se,renameSync as Ce,unlinkSync as we,writeFileSync as Te}from"fs";import{basename as Ee,dirname as De,join as P,resolve as Oe}from"path";import{fileURLToPath as ke}from"node:url";import{parseArgs as Ae}from"node:util";import je from"@anthropic-ai/sdk";import Me from"openai";import{FunctionCallingConfigMode as Ne,GoogleGenAI as Pe,Type as Fe}from"@google/genai";import{Box as F,Static as Ie,Text as I,render as Le,useApp as Re,useInput as L,usePaste as ze,useStdout as Be,useWindowSize as Ve}from"ink";import He,{createContext as Ue,useCallback as R,useContext as We,useEffect as Ge,useMemo as Ke,useRef as qe,useState as z}from"react";import{Fragment as Je,jsx as B,jsxs as V}from"react/jsx-runtime";import Ye from"chalk";import Xe from"string-width";import{marked as Ze}from"marked";import Qe from"marked-terminal";import{createServer as $e}from"node:http";import{WebSocket as et,WebSocketServer as tt}from"ws";import{createInterface as nt}from"node:readline/promises";import{createConnection as rt}from"node:net";import{zodToJsonSchema as it}from"zod-to-json-schema";function at(e){return{functionCalling:{supported:e},nativeWebTools:{webSearch:{supported:!1,enabled:!1,reason:`Provider does not declare native web search support.`},webFetch:{supported:!1,enabled:!1,reason:`Provider does not declare native web fetch support.`}}}}function ot(e){let t=typeof e.supportsTools==`function`?e.supportsTools():!1;return e.getCapabilities?.()??at(t)}function st(e,t,n){n?.webSearch===!0&&ct(e,`web search`,t.nativeWebTools.webSearch),n?.webFetch===!0&&ct(e,`web fetch`,t.nativeWebTools.webFetch)}function ct(e,t,n){if(!n.supported)throw Error(`Provider ${e} does not support native ${t}.${lt(n.reason)}`);if(!n.enabled)throw Error(`Provider ${e} supports native ${t} but it is not enabled.${lt(n.reason)}`)}function lt(e){return e?` ${e}`:``}function ut(e,t){return e.find(e=>e.type===t||e.aliases?.includes(t)===!0)}function dt(e){return e.map(e=>{if(!e.aliases||e.aliases.length===0)return e.type;let t=e.aliases.length===1?`alias`:`aliases`;return`${e.type} (${t}: ${e.aliases.join(`, `)})`}).join(`, `)}function ft(e){if(e?.credentialRequirement!==void 0)return e.credentialRequirement;if(e?.requiresApiKey===!0)return{anyOf:[`apiKey`]}}const pt=[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}];function mt(e,t,n){return{id:e,title:t,description:n?.description,options:pt,maxSelect:1,default:n?.defaultYes===void 0?void 0:{values:[n.defaultYes?`yes`:`no`]}}}function ht(e,t,n,r){return{id:e,title:t,options:n,maxSelect:1,description:r?.description,allowFreeText:r?.allowFreeText,maxVisible:r?.maxVisible,default:r?.default}}function gt(e,t,n){return{id:e,title:t,allowFreeText:!0,description:n?.description,masked:n?.masked,allowEmpty:n?.allowEmpty,placeholder:n?.placeholder,default:n?.default}}function _t(e){return e.type===`answer`&&e.values.includes(`yes`)}var vt=class{history=[];isInitialized=!1;config;async configure(e){this.config=e,await this.ensureInitialized()}getHistory(){return[...this.history]}clearHistory(){this.history=[]}addMessage(e){this.history.push(e)}validateInput(e){if(!e||typeof e!=`string`)throw Error(`Input must be a non-empty string`)}async ensureInitialized(){this.isInitialized||=(await this.initialize(),!0)}async dispose(){this.clearHistory(),this.isInitialized=!1}},yt=class{initialized=!1;async initialize(){this.initialized||=(await this.doInitialize(),!0)}async dispose(){await this.doDispose(),this.initialized=!1}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw Error(`${this.constructor.name} is not initialized`)}};function bt(e){if(!Array.isArray(e))throw Error(`Messages must be an array`);if(e.length===0)throw Error(`Messages array cannot be empty`);for(let t of e)if(!t.role||![`user`,`assistant`,`system`,`tool`].includes(t.role))throw Error(`Invalid message role: ${t.role}`)}function xt(e){if(e){if(!Array.isArray(e))throw Error(`Tools must be an array`);for(let t of e){if(!t.name||typeof t.name!=`string`)throw Error(`Tool must have a valid name`);if(!t.description||typeof t.description!=`string`)throw Error(`Tool must have a valid description`);if(!t.parameters||typeof t.parameters!=`object`||t.parameters===null||Array.isArray(t.parameters))throw Error(`Tool must have valid parameters`)}}}async function St(e,t,n,r){if(!e)throw Error(`Executor is required for ${t} provider. Configure an executor or use direct execution path.`);if(!r?.model)throw Error(`Model is required for executor execution in ${t} provider.`);return e.executeChat({messages:n,options:r,provider:t,model:r.model,...r.tools&&{tools:r.tools}})}async function*Ct(e,t,n,r){if(!e||!e.executeChatStream)throw Error(`Streaming executor is required for ${t} provider.`);if(!r?.model)throw Error(`Model is required for executor streaming in ${t} provider.`);let i=e.executeChatStream({messages:n,options:r,provider:t,model:r.model,stream:!0,...r.tools&&{tools:r.tools}});for await(let e of i)yield e}function wt(e){return e.category===`chat`}function Tt(e){let t=e.data;if(!t)throw Error(`Chat entry ${e.id} has no data`);return{...t,id:e.id,timestamp:e.timestamp}}function H(e){return{id:e.id,timestamp:e.timestamp,category:`chat`,type:e.role,data:{...e}}}function Et(e){return e.role===`assistant`}function Dt(e){return e.role===`system`}function Ot(e){return e.role===`tool`}const kt={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},log:()=>{},group:()=>{},groupEnd:()=>{}};var At=class e{static instance;globalLevel;constructor(){this.globalLevel=`warn`}static getInstance(){return e.instance||=new e,e.instance}getGlobalLevel(){return this.globalLevel}setGlobalLevel(e){this.globalLevel=e}},jt=class{level;packageName;sinkLogger;constructor(e,t){this.packageName=e,this.sinkLogger=t||kt}debug(...e){if(this.shouldLog(`debug`)){let[t,n]=e;this.forward(`debug`,String(t??``),Mt(n)?n:void 0)}}info(...e){if(this.shouldLog(`info`)){let[t,n]=e;this.forward(`info`,String(t??``),Mt(n)?n:void 0)}}warn(...e){if(this.shouldLog(`warn`)){let[t,n]=e;this.forward(`warn`,String(t??``),Mt(n)?n:void 0)}}error(...e){if(this.shouldLog(`error`)){let[t,n]=e;this.forward(`error`,String(t??``),Mt(n)?n:void 0)}}log(...e){this.info(...e)}getLevel(){return this.level||At.getInstance().getGlobalLevel()}shouldLog(e){let t=this.getLevel();if(t===`silent`)return!1;let n=[`debug`,`info`,`warn`,`error`,`silent`];return n.indexOf(e)>=n.indexOf(t)}forward(e,t,n){let r={timestamp:new Date().toISOString(),level:e,message:t,...n&&{context:n},packageName:this.packageName},i=`[${r.timestamp}] [${r.level.toUpperCase()}] [${r.packageName}] ${r.message}`;switch(e){case`debug`:this.sinkLogger.debug(i,n??{});return;case`info`:this.sinkLogger.info(i,n??{});return;case`warn`:this.sinkLogger.warn(i,n??{});return;case`error`:this.sinkLogger.error(i,n??{});return;case`silent`:return}}};function Mt(e){return typeof e==`object`&&!!e&&!(e instanceof Error)&&!(e instanceof Date)&&!Array.isArray(e)}function Nt(e,t){return new jt(e,t)}function Pt(e){At.getInstance().setGlobalLevel(e)}const U=Nt(`agents`);var Ft=class{config;executor;logger;constructor(e=kt){this.logger=e}async configure(e){this.config=e,this.hasExecutor(e)&&e.executor&&(this.executor=e.executor)}hasExecutor(e){return typeof e==`object`&&!!e&&`executor`in e}async*streamWithAbort(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await It(n,t);if(e.done||(await Lt(t),t?.aborted))break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async generateResponse(e){let t=await this.chat(e.messages,{...e.model!==void 0&&{model:e.model},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.tools!==void 0&&{tools:e.tools}});return{content:t.content??null,toolCalls:Et(t)?t.toolCalls:void 0,model:e.model,metadata:e.metadata}}async*generateStreamingResponse(e){if(!this.chatStream)throw Error(`[AI-PROVIDER] Streaming is not supported by provider "${this.name}"`);for await(let t of this.chatStream(e.messages,{...e.model!==void 0&&{model:e.model},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.tools!==void 0&&{tools:e.tools}}))yield{content:t.content??null,toolCalls:Et(t)?t.toolCalls:void 0,model:e.model,metadata:e.metadata}}supportsTools(){return!0}getCapabilities(){return at(this.supportsTools())}validateConfig(){return!0}validateMessages(e){bt(e)}validateTools(e){xt(e)}validateNativeWebTools(e){st(this.name,this.getCapabilities(),e)}async executeViaExecutorOrDirect(e,t){return St(this.executor,this.name,e,t)}async*executeStreamViaExecutorOrDirect(e,t){this.logger.debug?.(`🔍 [TOOL-FLOW] AbstractAIProvider.executeStreamViaExecutorOrDirect() - Executor request`,{provider:this.name,model:t?.model,hasTools:!!t?.tools,toolsCount:t?.tools?.length||0,toolNames:t?.tools?.map(e=>e.name)||[]}),yield*Ct(this.executor,this.name,e,t)}async dispose(){this.executor?.dispose&&await this.executor.dispose()}};async function It(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}async function Lt(e){e?.aborted||await new Promise(e=>setTimeout(e,0))}(function(e){return e.MONITORING=`monitoring`,e.LOGGING=`logging`,e.STORAGE=`storage`,e.NOTIFICATION=`notification`,e.SECURITY=`security`,e.PERFORMANCE=`performance`,e.ERROR_HANDLING=`error_handling`,e.LIMITS=`limits`,e.EVENT_PROCESSING=`event_processing`,e.CUSTOM=`custom`,e})({});let Rt=function(e){return e[e.CRITICAL=1e3]=`CRITICAL`,e[e.HIGH=800]=`HIGH`,e[e.NORMAL=500]=`NORMAL`,e[e.LOW=200]=`LOW`,e[e.MINIMAL=100]=`MINIMAL`,e}({});const zt={CREATED:`created`,EXECUTION_START:`execution_start`,EXECUTION_COMPLETE:`execution_complete`,EXECUTION_ERROR:`execution_error`,AGGREGATION_COMPLETE:`aggregation_complete`,CONFIG_UPDATED:`config_updated`},Bt=`agent`,Vt={START:`start`,COMPLETE:`complete`,ERROR:`error`,ASSISTANT_MESSAGE_START:`assistant_message_start`,ASSISTANT_MESSAGE_COMPLETE:`assistant_message_complete`,USER_MESSAGE:`user_message`,TOOL_RESULTS_TO_LLM:`tool_results_to_llm`,TOOL_RESULTS_READY:`tool_results_ready`},Ht=`execution`;function Ut(e){return`executionId`in e||`toolName`in e}function Wt(e){let t=0,n=!1;for(let r=0;r<e.length;r++){let i=e[r]===` `||e[r]===` `||e[r]===`
2
+ `||e[r]===`\r`;!i&&!n?(t++,n=!0):i&&(n=!1)}return t}var Gt=class{listeners=new Set;subscribe(e){this.listeners.add(e)}unsubscribe(e){this.listeners.delete(e)}notifyListeners(e,t,n){for(let r of this.listeners)r(e,t,n)}},Kt=class extends Gt{emit(e,t,n){}};const qt=new Kt;function Jt(e){return e===qt||e instanceof Kt}function Yt(e,t){if(!e||e.trim().length===0)throw Error(`[EVENTS] ownerType is required to compose event names.`);if(e.includes(`.`))throw Error(`[EVENTS] ownerType must not contain '.': "${e}"`);if(!t||t.trim().length===0)throw Error(`[EVENTS] local event name is required.`);if(t.includes(`.`))throw Error(`[EVENTS] Local event name must not contain '.': "${t}"`);return`${e}.${t}`}function Xt(){return`span_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var Zt=class extends Gt{base;binding;constructor(e,t){super(),this.base=e,this.binding=t}emit(e,t,n){if(e.includes(`.`))throw Error(`[EVENTS] Local event name must not contain '.': "${e}"`);let r={...n,ownerType:this.binding.ownerType,ownerId:this.binding.ownerId,ownerPath:this.binding.ownerPath,depth:this.binding.ownerPath.length,spanId:n?.spanId??Xt()},i=Yt(this.binding.ownerType,e);this.base.emit(i,t,r)}subscribe(e){this.base.subscribe(e)}unsubscribe(e){this.base.unsubscribe(e)}};function Qt(e,t){return new Zt(e,t)}function $t(e,t,n,r,i,a,o){e.emitExecution(Vt.START,{parameters:{input:t,agentConfiguration:i.aiProviderInfo,availableTools:i.toolsInfo,toolCount:i.toolsInfo.length,hasTools:i.toolsInfo.length>0,systemMessage:n.systemMessage,provider:n.defaultModel.provider,model:n.defaultModel.model,temperature:n.defaultModel.temperature,maxTokens:n.defaultModel.maxTokens},metadata:{method:`execute`,inputLength:t.length,messageCount:r.length,aiProvider:i.aiProviderInfo.providerName,model:i.aiProviderInfo.model,toolsAvailable:i.toolsInfo.map(e=>e.name),agentCapabilities:{canUseTools:i.toolsInfo.length>0,supportedActions:i.toolsInfo.map(e=>e.name)}}},a,o)}function en(e,t,n,r){e.emitExecution(Vt.USER_MESSAGE,{parameters:{input:t,userPrompt:t,userMessageContent:t,messageLength:t.length,wordCount:Wt(t),characterCount:t.length},metadata:{messageRole:`user`,inputLength:t.length,messageType:`user_message`,hasQuestions:t.includes(`?`),containsUrgency:/urgent|asap|critical|emergency/i.test(t),estimatedComplexity:t.length>200?`high`:t.length>50?`medium`:`low`}},n,r)}function tn(e,t,n,r,i,a,o,s){if(typeof n.content!=`string`||n.content.length===0)throw Error(`[EXECUTION] assistant response must have content or tool calls`);if(!(n.timestamp instanceof Date))throw Error(`[EXECUTION] assistant response timestamp is required`);let c=n.content,l=n.timestamp,u=new Date().getTime()-l.getTime();e.emitWithContext(Vt.ASSISTANT_MESSAGE_COMPLETE,{parameters:{assistantMessage:c,responseLength:c.length,wordCount:Wt(c),responseTime:u,contentPreview:c.length>200?c.substring(0,200)+`...`:c},result:{success:!0,data:c.substring(0,100)+`...`,fullResponse:c,responseMetrics:{length:c.length,estimatedReadTime:Math.ceil(Wt(c)/200),hasCodeBlocks:/```/.test(c),hasLinks:/https?:\/\//.test(c),complexity:c.length>1e3?`high`:c.length>300?`medium`:`low`}},metadata:{executionId:r,round:i,completed:!0,reason:`no_tool_calls`,responseCharacteristics:{hasQuestions:c.includes(`?`),isError:/error|fail|wrong/i.test(c),isComplete:/complete|done|finish/i.test(c),containsNumbers:/\d/.test(c)}}},()=>e.buildResponseOwnerContext(a,r,o,s),e=>{if(!e.ownerType||!e.ownerId)throw Error(`[EXECUTION] Missing owner context for response event`);return Qt(t,{ownerType:e.ownerType,ownerId:e.ownerId,ownerPath:e.ownerPath})})}function nn(e,t,n,r,i,a,o,s,c,l){let u=n.map(e=>{if(!e.id||e.id.length===0)throw Error(`[EXECUTION] Tool call missing id for tool results ready payload`);return e.id});if(u.length===0)throw Error(`[EXECUTION] Tool results ready requires toolCallIds`);let d=()=>e.buildThinkingOwnerContext(a,o,c,l),f=e=>{if(!e.ownerType||!e.ownerId)throw Error(`[EXECUTION] Missing owner context for tool results event`);return Qt(t,{ownerType:e.ownerType,ownerId:e.ownerId,ownerPath:e.ownerPath})};e.emitWithContext(Vt.TOOL_RESULTS_READY,{parameters:{toolCallIds:u,round:s},metadata:{round:s}},d,f),e.emitWithContext(Vt.TOOL_RESULTS_TO_LLM,{parameters:{toolsExecuted:i.length,round:s},metadata:{toolsExecuted:r.results.map(e=>{if(!e.toolName||e.toolName.length===0)throw Error(`[EXECUTION] Tool result missing toolName`);return e.toolName}),round:s}},d,f)}var rn=class extends Error{context;constructor(e,t){super(e),this.context=t,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}},W=class extends rn{code=`CONFIGURATION_ERROR`;category=`user`;recoverable=!1;constructor(e,t){super(`Configuration Error: ${e}`,t)}},G=class extends rn{field;code=`VALIDATION_ERROR`;category=`user`;recoverable=!1;constructor(e,t,n){super(`Validation Error: ${e}`,n),this.field=t}},an=class extends rn{issues;attempts;code=`STRUCTURED_OUTPUT_ERROR`;category=`provider`;recoverable=!0;constructor(e,t,n,r){super(`Structured Output Error: ${e}`,r),this.issues=t,this.attempts=n}},on=class extends rn{provider;originalError;code=`PROVIDER_ERROR`;category=`provider`;recoverable=!0;constructor(e,t,n,r){super(`Provider Error (${t}): ${e}`,r),this.provider=t,this.originalError=n}},sn=class extends rn{provider;code=`AUTHENTICATION_ERROR`;category=`user`;recoverable=!1;constructor(e,t,n){super(`Authentication Error: ${e}`,n),this.provider=t}},cn=class extends rn{retryAfter;provider;code=`RATE_LIMIT_ERROR`;category=`provider`;recoverable=!0;constructor(e,t,n,r){super(`Rate Limit Error: ${e}`,r),this.retryAfter=t,this.provider=n}},ln=class extends rn{originalError;code=`NETWORK_ERROR`;category=`system`;recoverable=!0;constructor(e,t,n){super(`Network Error: ${e}`,n),this.originalError=t}},un=class extends rn{toolName;originalError;code=`TOOL_EXECUTION_ERROR`;category=`system`;recoverable=!1;constructor(e,t,n,r){super(`Tool Execution Error (${t}): ${e}`,r),this.toolName=t,this.originalError=n}},dn=class extends rn{pluginName;code=`PLUGIN_ERROR`;category=`system`;recoverable=!1;constructor(e,t,n){super(`Plugin Error (${t}): ${e}`,n),this.pluginName=t}},fn=class extends rn{code=`CACHE_INTEGRITY_ERROR`;category=`system`;recoverable=!1;constructor(e,t){super(`Cache Integrity Error: ${e}`,t)}};function pn(e){if(!e.executionId)throw new G(`[STRICT-POLICY][EMITTER-CONTRACT] Tool execution request missing executionId`);if(!e.ownerType)throw new G(`[STRICT-POLICY][EMITTER-CONTRACT] Tool execution request missing ownerType: executionId=${e.executionId}`);if(!e.ownerId)throw new G(`[STRICT-POLICY][EMITTER-CONTRACT] Tool execution request missing ownerId: executionId=${e.executionId}`);return{executionId:e.executionId,ownerType:e.ownerType,ownerId:e.ownerId}}function mn(e,t){let n=pn(e);return{toolName:e.toolName,parameters:e.parameters,...t?{signal:t}:{},executionId:n.executionId,ownerType:n.ownerType,ownerId:n.ownerId,ownerPath:e.ownerPath,metadata:e.metadata,eventService:e.eventService,baseEventService:e.baseEventService,...e.ask?{ask:e.ask}:{}}}function hn(e){return{toolName:e.toolName,executionId:e.executionId??``,success:!1,error:`Execution interrupted by user`,result:null}}function gn(e,t){return{toolName:e.toolName,result:null,success:!1,error:t.message,executionId:e.executionId}}function _n(e){return Error(`Tool execution failed: toolName=${String(e.toolName)} executionId=${String(e.executionId)} error=${String(e.error||`Unknown error`)}`)}function vn(e){return e!==void 0}function yn(e){return e!==void 0}function bn(e,t){if(e===0)return 0;if(t===void 0||!Number.isFinite(t))return e;let n=Math.floor(t);return n<1?1:Math.min(n,e)}async function xn(e,t,n,r){let i=e.requests[r];if(i)try{let a=e.signal?.aborted?hn(i):await t.executeTool(i.toolName,i.parameters,mn(i,e.signal));n.resultsByIndex[r]=a,a.success||(n.errorsByIndex[r]=_n(a))}catch(e){let t=e instanceof Error?e:Error(String(e));n.errorsByIndex[r]=t,n.resultsByIndex[r]=gn(i,t)}}async function Sn(e,t,n){for(;n.nextRequestIndex<e.requests.length;){let r=n.nextRequestIndex;n.nextRequestIndex+=1,await xn(e,t,n,r)}}async function Cn(e,t){let n={resultsByIndex:Array(e.requests.length),errorsByIndex:Array(e.requests.length),nextRequestIndex:0},r=bn(e.requests.length,e.maxConcurrency),i=Array.from({length:r},()=>Sn(e,t,n));await Promise.all(i);let a=n.resultsByIndex.filter(vn),o=n.errorsByIndex.filter(yn);if(o.length>0&&!e.continueOnError)throw o[0];return{results:a,errors:o}}async function wn(e,t){let n=[],r=[];for(let i of e.requests)try{let a=e.signal?.aborted?hn(i):await t.executeTool(i.toolName,i.parameters,mn(i,e.signal));if(n.push(a),a.success||r.push(_n(a)),!a.success&&!e.continueOnError)break}catch(t){let n=t instanceof Error?t:Error(String(t));if(r.push(n),!e.continueOnError)break}return{results:n,errors:r}}async function Tn(e,t,n){return n.debug(`Executing ${e.requests.length} tools in ${e.mode} mode`),e.mode===`parallel`?Cn(e,t):wn(e,t)}const En={CALL_START:`call_start`,CALL_COMPLETE:`call_complete`,CALL_ERROR:`call_error`,CALL_RESPONSE_READY:`call_response_ready`},Dn=`tool`,On=`unknown_tool`;var kn=class{tools;logger;askHandler;constructor(e,t=kt){this.tools=e,this.logger=t}setAskHandler(e){this.askHandler=e}async executeTool(e,t,n){this.logger.debug(`Executing tool: ${e}`);try{if(!n?.executionId)throw new G(`ToolExecutionService requires executionId (toolCallId) in ToolExecutionContext`);if(!this.tools.hasTool(e)){let t=this.tools.getTools().map(e=>e.name).sort(),r=An(e,t),i=n.eventService;if(i){let t={timestamp:new Date,toolName:e,error:r};i.emit(En.CALL_ERROR,t)}return this.logger.warn(`Tool call skipped because requested tool is not registered`,{toolName:e,availableTools:t}),{success:!1,error:r,toolName:e,executionId:n.executionId,metadata:{errorCode:On,requestedTool:e,availableTools:t}}}let r=n.eventService;if(r){let n={timestamp:new Date,toolName:e,parameters:t};r.emit(En.CALL_START,n)}let{toolName:i,parameters:a,...o}=n,s={...o,toolName:e,parameters:t,executionId:n.executionId},c=await this.tools.executeTool(e,t,s);if(this.logger.debug(`Tool execution completed: ${e}`),r){let t={timestamp:new Date,toolName:e,result:c};r.emit(En.CALL_COMPLETE,t),r.emit(En.CALL_RESPONSE_READY,t)}return{success:!0,result:c,toolName:e,executionId:s.executionId}}catch(t){this.logger.error(`Tool execution failed: ${e}`);let r=t instanceof Error?t:Error(String(t)),i=n?.eventService;if(i&&n?.executionId){let t={timestamp:new Date,toolName:e,error:r.message};i.emit(En.CALL_ERROR,t)}return{success:!1,error:r.message,toolName:e,executionId:n?.executionId}}}createExecutionRequestsWithContext(e,t){return e.map(e=>{let n;try{n=JSON.parse(e.function.arguments)}catch{throw new G(`Failed to parse arguments for tool "${e.function.name}" (call ${e.id}): invalid JSON`)}return{toolName:e.function.name,parameters:n,executionId:e.id,ownerType:`tool`,ownerId:e.id,ownerPath:[...t.ownerPathBase,{type:`tool`,id:e.id}],metadata:t.metadataFactory?t.metadataFactory(e):void 0,...this.askHandler?{ask:this.askHandler}:{}}})}async executeTools(e){return Tn(e,this,this.logger)}};function An(e,t){return`Tool "${e}" is not registered, so the tool call was not executed. Available tools: ${t.length>0?t.join(`, `):`no registered tools are available`}.`}function jn(e){return e?.ownerPath?.length?e.ownerPath.map(e=>({...e})):[]}function Mn(e,t,n,r){if(!n||n.length===0)throw Error(`[EXECUTION] Missing rootId for execution owner context`);if(!r||r.length===0)throw Error(`[EXECUTION] Missing executionId for execution owner context`);let i=[...e.length?e:t];return n&&!i.some(e=>e.type===`agent`&&e.id===n)&&i.push({type:`agent`,id:n}),i.push({type:`execution`,id:r}),{ownerType:Ht,ownerId:r,ownerPath:i}}function Nn(e,t,n,r,i,a){if(!i||i.length===0)throw Error(`[EXECUTION] Missing thinkingNodeId for thinking owner context`);let o=[...Mn(e,t,n,r).ownerPath];return a&&(o.push({type:`thinking`,id:a}),o.push({type:`tool_result`,id:`tool_result_${a}`})),o.push({type:`thinking`,id:i}),{ownerType:Ht,ownerId:r,ownerPath:o}}function Pn(e,t,n,r,i){if(!i||i.length===0)throw Error(`[EXECUTION] Missing toolCallId for tool owner context`);return{ownerType:Dn,ownerId:i,ownerPath:[...Mn(e,t,n,r).ownerPath,{type:`tool`,id:i}]}}function Fn(e,t,n,r,i,a){let o=Nn(e,t,n,r,i,a).ownerPath,s=`response_${i}`;return{ownerType:Ht,ownerId:r,ownerPath:[...o,{type:`response`,id:s}]}}var In=class{baseEventService;logger;ownerPathBase;toolEventServices;agentOwnerPathBase;constructor(e,t,n){this.baseEventService=e,this.logger=t,this.ownerPathBase=jn(n),this.toolEventServices=new Map,this.agentOwnerPathBase=[]}prepareOwnerPathBases(e){this.toolEventServices.clear();let t=[...this.ownerPathBase,{type:`agent`,id:e}];this.agentOwnerPathBase=t}resetOwnerPathBases(){this.toolEventServices.clear(),this.agentOwnerPathBase=[]}ensureToolEventService(e,t){if(Jt(this.baseEventService))return this.baseEventService;if(!e)throw Error(`[EVENT-SERVICE] Missing ownerId for tool event context`);if(!t||t.length===0)throw Error(`[EVENT-SERVICE] Missing ownerPath for tool event context`);if(this.toolEventServices.has(e))return this.toolEventServices.get(e);let n=Qt(this.baseEventService,{ownerType:Dn,ownerId:e,ownerPath:t.map(e=>({...e}))});return this.toolEventServices.set(e,n),n}clearToolEventServices(){this.toolEventServices.clear()}getBaseEventService(){return this.baseEventService}buildExecutionOwnerContext(e,t){return Mn(this.agentOwnerPathBase,this.ownerPathBase,e,t)}buildThinkingOwnerContext(e,t,n,r){return Nn(this.agentOwnerPathBase,this.ownerPathBase,e,t,n,r)}buildToolOwnerContext(e,t,n){return Pn(this.agentOwnerPathBase,this.ownerPathBase,e,t,n)}buildResponseOwnerContext(e,t,n,r){return Fn(this.agentOwnerPathBase,this.ownerPathBase,e,t,n,r)}emitExecution(e,t,n,r){this.emitWithContext(e,t,()=>this.buildExecutionOwnerContext(n,r),e=>{if(!e.ownerType||!e.ownerId)throw Error(`[EXECUTION] Missing owner context for execution event`);return Qt(this.baseEventService,{ownerType:e.ownerType,ownerId:e.ownerId,ownerPath:e.ownerPath})})}emitTool(e,t,n,r,i){this.emitWithContext(e,t,()=>this.buildToolOwnerContext(n,r,i),e=>this.ensureToolEventService(e.ownerId,e.ownerPath))}emitWithContext(e,t,n,r){if(Jt(this.baseEventService))return;let i=n(),a=r(i),o={timestamp:new Date,...t};a.emit(e,o,i)}emitExecutionStartEvent(e,t,n,r,i,a){$t(this,e,t,n,r,i,a)}emitUserMessageEvent(e,t,n){en(this,e,t,n)}emitAssistantMessageComplete(e,t,n,r,i,a){tn(this,this.baseEventService,e,t,n,r,i,a)}emitToolResultsEvents(e,t,n,r,i,a,o,s){nn(this,this.baseEventService,e,t,n,r,i,a,o,s)}};function Ln(e){let t=Rn(e.metadata),n=Bn(e.usage);return t??n}function Rn(e){if(!e)return;let t=Bn({inputTokens:Vn(e,`inputTokens`),outputTokens:Vn(e,`outputTokens`),promptTokens:Vn(e,`promptTokens`),completionTokens:Vn(e,`completionTokens`),totalTokens:Vn(e,`totalTokens`)});if(t)return t;let n=e.usage;if(typeof n==`string`)return zn(n);if(Un(n))return Bn(n)}function zn(e){try{return Bn(JSON.parse(e))}catch{return}}function Bn(e){if(!e)return;let t=Hn(e.inputTokens,e.promptTokens),n=Hn(e.outputTokens,e.completionTokens);if(t===void 0||n===void 0)return;let r=Hn(e.totalTokens);return{inputTokens:t,outputTokens:n,...r!==void 0&&{totalTokens:r}}}function Vn(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Hn(...e){return e.find(e=>typeof e==`number`&&Number.isFinite(e))}function Un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`number`&&Number.isFinite(e))}function Wn(e){return Math.ceil(JSON.stringify(e).length/4)}function Gn(e,t={}){let n=Wn(e),r=Kn(e),i=r?.tokens,a=qn(t.usageFloorTokens);return{usedTokens:r?.index===e.length-1?Math.max(i??0,a??0):Math.max(n,i??0,a??0),serializedTokens:n,...i!==void 0&&{providerTokens:i},...a!==void 0&&{usageFloorTokens:a}}}function Kn(e){for(let t=e.length-1;t>=0;t--){let n=Ln(e[t]);if(n)return{tokens:n.totalTokens??n.inputTokens+n.outputTokens,index:t}}}function qn(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.ceil(e)}const Jn={"claude-opus-4-6":{name:`Claude Opus 4.6`,id:`claude-opus-4-6`,contextWindow:1e6,maxOutput:128e3},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,id:`claude-sonnet-4-6`,contextWindow:1e6,maxOutput:64e3},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,id:`claude-haiku-4-5`,contextWindow:2e5,maxOutput:64e3},"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,id:`claude-haiku-4-5-20251001`,contextWindow:2e5,maxOutput:64e3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,id:`claude-sonnet-4-5`,contextWindow:2e5,maxOutput:64e3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,id:`claude-sonnet-4-5-20250929`,contextWindow:2e5,maxOutput:64e3},"claude-opus-4-5":{name:`Claude Opus 4.5`,id:`claude-opus-4-5`,contextWindow:2e5,maxOutput:64e3},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,id:`claude-opus-4-5-20251101`,contextWindow:2e5,maxOutput:64e3}};function Yn(e){return Jn[e]?.contextWindow??2e5}function Xn(e){return Jn[e]?.maxOutput??16384}function Zn(e){if(e>=1e6){let t=e/1e6;return Number.isInteger(t)?`${t}M`:`${parseFloat(t.toFixed(1))}M`}if(e<=0)return`0K`;if(e<1e3)return`<1K`;let t=e/1e3;return Number.isInteger(t)?`${t}K`:`${parseFloat(t.toFixed(1))}K`}const Qn=.95;function $n(e,t,n){let r=Gn(e,{usageFloorTokens:n}),i=Yn(t),a=i*Qn,o=i>0?Math.round(r.usedTokens/i*1e4)/100:100;return{shouldBlock:r.usedTokens>a,estimatedTokens:r.usedTokens,contextLimit:i,thresholdTokens:a,thresholdPercentage:Qn*100,usedPercentage:o,serializedTokens:r.serializedTokens,...r.providerTokens!==void 0&&{providerTokens:r.providerTokens},...r.usageFloorTokens!==void 0&&{usageFloorTokens:r.usageFloorTokens}}}function er(e,t,n,r,i,a){let o=$n(e,t.defaultModel.model,n.cumulativeInputTokens);return o.shouldBlock?(i.warn(`[ROUND] Context hard-capacity prevention before provider call`,{estimatedTokens:o.estimatedTokens,contextLimit:o.contextLimit,thresholdTokens:o.thresholdTokens,thresholdPercentage:o.thresholdPercentage,serializedTokens:o.serializedTokens,providerTokens:o.providerTokens??0,usageFloorTokens:o.usageFloorTokens??0,round:a}),r.addAssistantMessage(`Context window is near capacity. Cannot process further in this round. Estimated ${o.estimatedTokens.toLocaleString()} / ${o.contextLimit.toLocaleString()} tokens (${Math.round(o.usedPercentage)}%) exceeds the hard-block threshold ${Math.round(o.thresholdPercentage)}%. Run /compact and retry.`,[],{round:a,contextOverflow:!0,estimatedTokens:o.estimatedTokens,contextLimit:o.contextLimit,thresholdTokens:o.thresholdTokens,thresholdPercentage:o.thresholdPercentage,serializedTokens:o.serializedTokens,providerTokens:o.providerTokens??0,usageFloorTokens:o.usageFloorTokens??0,usedPercentage:o.usedPercentage}),!0):!1}const tr={beforeRun:async(e,t)=>{e.beforeRun&&t.input&&await e.beforeRun(t.input,t.metadata)},afterRun:async(e,t)=>{e.afterRun&&t.input&&t.response&&await e.afterRun(t.input,t.response,t.metadata)},beforeProviderCall:async(e,t)=>{e.beforeProviderCall&&t.messages&&await e.beforeProviderCall(t.messages)},afterProviderCall:async(e,t)=>{e.afterProviderCall&&t.messages&&t.responseMessage&&await e.afterProviderCall(t.messages,t.responseMessage)},onError:async(e,t)=>{if(e.onError&&t.error){let n={action:`${Ht}.${Vt.ERROR}`,metadata:{}},r=t.executionContext?.executionId;typeof r==`string`&&r.length>0&&(n.executionId=r);let i=t.executionContext?.sessionId;typeof i==`string`&&i.length>0&&(n.sessionId=i);let a=t.executionContext?.userId;typeof a==`string`&&a.length>0&&(n.userId=a),await e.onError(t.error,n)}}};async function nr(e,t,n,r){let i=tr[t];if(i)for(let a of e)try{await i(a,n)}catch(e){r.warn(`Plugin hook failed`,{pluginName:a.name,hookName:t,error:e instanceof Error?e.message:String(e)})}}function rr(e){if(e?.type){if(e.type===`json_schema`){if(!e.schema)throw Error(`responseFormat.schema is required when type is 'json_schema'.`);return{type:`json_schema`,schema:e.schema,...e.name&&{name:e.name}}}return{type:e.type}}}function ir(e,t){return e===void 0||t<=1?e:e===`required`||typeof e==`object`?`auto`:e}function ar(e,t){if(e===void 0||e===`auto`||e===`none`)return;let n=(t??[]).map(e=>e.name);if(e===`required`){if(n.length===0)throw Error(`toolChoice 'required' needs at least one tool, but the run has none.`);return}if(!n.includes(e.tool))throw Error(`toolChoice requests tool "${e.tool}" which is not available for this run. Available tools: ${n.length>0?n.join(`, `):`(none)`}`)}function or(e,t,n){let r=e.getCurrentProvider(),i=r?e.getProvider(r.provider):null;if(!r||!r.provider||!i)throw Error(`[EXECUTION] Provider is required`);let a=t.getTools();return{provider:i,currentInfo:r,aiProviderInfo:{providerName:r.provider,model:n.defaultModel.model,temperature:n.defaultModel.temperature,maxTokens:n.defaultModel.maxTokens},toolsInfo:a.map(e=>{let t=e.parameters?.properties;if(!e.description||e.description.length===0)throw Error(`[EXECUTION] Tool "${e.name}" is missing description`);return{name:e.name,description:e.description,parameters:t&&typeof t==`object`?Object.keys(t):[]}}),availableTools:a}}function sr(e){if(!e.currentInfo)throw Error(`No AI provider configured`);if(!e.provider)throw Error(`AI provider '${e.currentInfo.provider}' not found`);if(typeof e.provider.chat!=`function`)throw Error(`Provider must have chat method to support execution`)}function cr(e,t,n,r,i){let a=e.getConversationStore(t);if(!a.getMessages().some(e=>e.role!==`system`)&&n.length>0){for(let e of n)if(e.role===`user`)a.addUserMessage(e.content,e.metadata,e.parts);else if(e.role===`assistant`)a.addAssistantMessage(e.content,e.toolCalls,e.metadata,e.parts);else if(e.role===`tool`){let t=e.metadata?.toolName;if(typeof t!=`string`||t.length===0)throw Error(`[EXECUTION] Tool message missing toolName metadata`);a.addToolMessageWithId(e.content,e.toolCallId,t,e.metadata,e.parts)}}let o=a.getMessages().some(e=>e.role===`system`);return r.systemMessage&&!o&&a.setSystemPrompt(r.systemMessage,{executionId:i}),a}function lr(e,t,n,r){let i=e.getMessages(),a=i.filter(e=>e.role===`assistant`&&typeof e.content==`string`&&e.content.length>0).pop(),o=a?a.content:`No response received. The context window may be full.`,s=a?.metadata?.providerError===!0,c=Date.now()-n.getTime();return{response:o,messages:i.map(e=>{if(typeof e.content!=`string`)throw Error(`[EXECUTION] Message content is required`);return{role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata,...e.role===`assistant`&&`toolCalls`in e?{toolCalls:e.toolCalls}:{},...e.role===`tool`&&`toolCallId`in e?{toolCallId:e.toolCallId}:{}}}),executionId:t,duration:c,tokensUsed:i.filter(e=>e.metadata?.usage).reduce((e,t)=>{let n=t.metadata?.usage;if(n&&typeof n==`object`&&`totalTokens`in n){let t=Number(n.totalTokens);if(Number.isNaN(t))throw Error(`[EXECUTION] totalTokens must be a number`);return e+t}return e},0),toolsExecuted:r,success:!!a&&!s,...s?{error:Error(o)}:{}}}async function ur(e,t,n,r,i,a,o,s){let c=Date.now()-n.getTime();await nr(a,`onError`,{error:e instanceof Error?e:Error(String(e)),executionContext:mr(t)},o),o.error(`Execution pipeline failed`,{executionId:i,conversationId:r,duration:c,error:e instanceof Error?e.message:String(e)}),s.emitExecution(Vt.ERROR,{error:e instanceof Error?e.message:String(e),metadata:{method:`execute`,success:!1,duration:c}},r,i)}function dr(){return`exec_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function fr(e,t){if(!e?.conversationId||e.conversationId.length===0)throw Error(`[EXECUTION] conversationId is required for ${t}`);return e.conversationId}function pr(e,t,n,r,i,a){return{messages:e,config:t,startTime:n,executionId:r,conversationId:i,...a?.sessionId&&{sessionId:a.sessionId},...a?.userId&&{userId:a.userId},...a?.metadata&&{metadata:a.metadata},...a?.signal&&{signal:a.signal},...a?.onTextDelta&&{onTextDelta:a.onTextDelta},...a?.onExecutionEvent&&{onExecutionEvent:a.onExecutionEvent},...a?.maxExecutionRounds!==void 0&&{maxExecutionRounds:a.maxExecutionRounds},...a?.maxSameToolInputs!==void 0&&{maxSameToolInputs:a.maxSameToolInputs},...a?.allowToolOnlyCompletion!==void 0&&{allowToolOnlyCompletion:a.allowToolOnlyCompletion},...a?.maxTokens!==void 0&&{maxTokens:a.maxTokens},...a?.temperature!==void 0&&{temperature:a.temperature},...a?.toolChoice!==void 0&&{toolChoice:a.toolChoice}}}function mr(e){let t={conversationId:fr(e,`plugin-context`),executionId:e.executionId,startTime:e.startTime.toISOString(),messageCount:e.messages.length};return e.sessionId&&(t.sessionId=e.sessionId),e.userId&&(t.userId=e.userId),t}function hr(e,t){let n=Array.isArray(t.lastTrackedAssistantMessage?.toolCalls)&&t.lastTrackedAssistantMessage.toolCalls.length>0;return{thinkingNodeId:`thinking_${e}_round${t.runningAssistantCount+1}`,previousThinkingNodeId:n?`thinking_${e}_round${t.runningAssistantCount}`:void 0}}async function gr(e,t,n,r,i){if(!t.defaultModel?.model)throw Error(`Model is required in defaultModel configuration. Please specify a model.`);if(typeof t.defaultModel.model!=`string`||t.defaultModel.model.trim()===``)throw Error(`Model must be a non-empty string in defaultModel configuration.`);let a={model:t.defaultModel.model,effort:t.defaultModel.effort??`high`,...t.defaultModel.maxTokens!==void 0&&{maxTokens:t.defaultModel.maxTokens},...t.defaultModel.temperature!==void 0&&{temperature:t.defaultModel.temperature},...t.defaultModel.toolChoice!==void 0&&{toolChoice:t.defaultModel.toolChoice},...n.availableTools.length>0&&{tools:n.availableTools},...(()=>{let e=rr(t.responseFormat);return e?{responseFormat:e}:{}})(),...i};ar(a.toolChoice,a.tools);let o=n.provider.chat.bind(n.provider);if(r){let n=r.lookup(e,t.defaultModel.model,t.defaultModel.provider,{temperature:t.defaultModel.temperature,maxTokens:t.defaultModel.maxTokens});if(n)return{role:`assistant`,content:n,timestamp:new Date,id:l(),state:`complete`};let i=await _r(o,e,a,t.timeout);return typeof i.content==`string`&&r.store(e,t.defaultModel.model,t.defaultModel.provider,i.content,{temperature:t.defaultModel.temperature,maxTokens:t.defaultModel.maxTokens}),i}return _r(o,e,a,t.timeout)}async function _r(e,t,n,r){let i=vr(r),a=n.signal;if(i===void 0&&a===void 0)return e(t,n);if(a?.aborted)throw yr();let o=new AbortController,s,c=!1,l,u=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},d=e=>{c||(c=!0,l?.(e),o.abort(e))},f=()=>{i===void 0||c||(u(),s=setTimeout(()=>{d(Error(`Provider call idle timeout after ${i}ms`))},i))},p=()=>{d(yr())};a?.addEventListener(`abort`,p,{once:!0});let m=n.onTextDelta,h={...n,signal:o.signal,...m===void 0?{}:{onTextDelta:e=>{f(),m(e)}}};f();try{return await Promise.race([e(t,h),new Promise((e,t)=>{l=t})])}finally{c=!0,u(),a?.removeEventListener(`abort`,p)}}function vr(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return e}function yr(){let e=Error(`aborted`);return e.name=`AbortError`,e}function br(e,t,n,r,i){let a=e.role===`assistant`?e.toolCalls:void 0,o=Array.isArray(a)&&a.length>0;if(typeof e.content!=`string`&&!o)throw Error(`[EXECUTION] Provider response must have content or tool calls`);if(a&&!Array.isArray(a))throw Error(`[EXECUTION] assistant toolCalls must be an array`);let s=e.content??``;if(i.debug(`[ROUND-${r}] Provider response completed`,{executionId:t,conversationId:n,round:r,responseLength:s.length,hasToolCalls:Array.isArray(a)&&a.length>0,toolCallsCount:Array.isArray(a)?a.length:0}),e.role!==`assistant`)throw Error(`Unexpected response role: ${e.role}`);let c=e,l=c.toolCalls??[];if(!Array.isArray(l))throw Error(`[EXECUTION] assistantResponse.toolCalls must be an array`);return{assistantResponse:c,assistantToolCalls:l}}function xr(e,t,n,r){let i=0,a=0;return{wrappedOnTextDelta:a=>{e.onExecutionEvent?.(`provider_stream_raw_delta`,{executionId:n,conversationId:e.conversationId,round:r,sequence:i,delta:a}),i++,t.appendStreaming(a),e.onTextDelta?.(a)},wrappedOnProviderNativeRawPayload:t=>{let i=t.sequence??a;a=Math.max(a,i+1),e.onExecutionEvent?.(`provider_native_raw_payload`,{executionId:n,conversationId:e.conversationId,round:r,...t,sequence:i})}}}async function Sr(e,t,n,r,i,a,o,s,c,l,u){try{i.onExecutionEvent?.(`provider_request`,{executionId:s,conversationId:i.conversationId,round:o,provider:n.currentInfo.provider,model:t.defaultModel.model,messages:e,tools:n.availableTools});let a=await gr(e,t,n,r,{signal:i.signal,onTextDelta:l,onProviderNativeRawPayload:u,...i.maxTokens!==void 0&&{maxTokens:i.maxTokens},...i.temperature!==void 0&&{temperature:i.temperature},...(()=>{let e=ir(i.toolChoice??t.defaultModel.toolChoice,o);return e===void 0?{}:{toolChoice:e}})()});return i.onExecutionEvent?.(`provider_response_raw`,{executionId:s,conversationId:i.conversationId,round:o,response:a,responseKind:`provider-normalized-message`}),i.onExecutionEvent?.(`provider_response_normalized`,{executionId:s,conversationId:i.conversationId,round:o,response:a,toolCallsCount:a.role===`assistant`&&Array.isArray(a.toolCalls)?a.toolCalls.length:0}),a}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`)))throw a.commitAssistant(`interrupted`,{round:o}),e;a.discardPending();let t=e instanceof Error?e.message:String(e);return c.error(`[ROUND] Provider call failed`,{error:t,round:o}),a.addAssistantMessage(`Request failed: ${t}`,[],{round:o,providerError:!0}),null}}function Cr(e){return!e.success&&e.metadata?.errorCode===`unknown_tool`}function wr(e,t,n,r,i,a){let o=!1,s=0,c=0;for(let l of e){if(!l.id)throw Error(`Tool call missing ID: ${JSON.stringify(l)}`);let e=l.function?.name;if(!e||e.length===0)throw Error(`[EXECUTION] Tool call "${l.id}" missing function name`);if(o){i.warn(`[ROUND] Skipping tool result due to context overflow`,{toolCallId:l.id,toolName:e,round:r}),n.addToolMessageWithId(`Error: Context window near capacity. Tool execution result skipped. Respond with available results and re-request skipped tools if needed.`,l.id,e,{round:r,success:!1,error:`context_overflow`,toolName:e}),c++;continue}let u=t.results.find(e=>e.executionId===l.id),d=t.errors.find(e=>Ut(e)&&e.executionId===l.id),f,p={round:r};if(u&&u.success){if(u.result===void 0)throw Error(`[EXECUTION] Tool result missing result payload`);f=typeof u.result==`string`?u.result:JSON.stringify(u.result),p.success=!0,u.toolName&&(p.toolName=u.toolName)}else if(u&&!u.success){if(!u.error||u.error.length===0)throw Error(`[EXECUTION] Tool result missing error message`);f=`Error: ${u.error}`,p.success=!1,p.error=u.error,u.toolName&&(p.toolName=u.toolName),u.metadata?.errorCode===`unknown_tool`&&(p.errorCode=On,typeof u.metadata.requestedTool==`string`&&(p.requestedTool=u.metadata.requestedTool),Array.isArray(u.metadata.availableTools)&&(p.availableTools=u.metadata.availableTools.filter(e=>typeof e==`string`)))}else if(d){let e=d,t=e.error?.message?e.error.message:e.message?e.message:``;if(!t||t.length===0)throw Error(`[EXECUTION] Tool execution error missing message`);f=`Error: ${t}`,p.success=!1,p.error=t,e.toolName&&(p.toolName=e.toolName)}else throw Error(`No execution result found for tool call ID: ${l.id}`);if(i.debug(`Adding tool result to conversation`,{toolCallId:l.id,toolName:e,content:f.substring(0,100),round:r,currentHistoryLength:n.getMessages().length}),n.addToolMessageWithId(f,l.id,e,p),a){let e=Gn(n.getMessages(),{usageFloorTokens:a.cumulativeInputTokens}).usedTokens;e>a.contextLimit*.8&&(i.warn(`[ROUND] Context budget exceeded after tool result — skipping remaining tools`,{estimatedTokens:e,contextLimit:a.contextLimit,toolCallId:l.id,round:r}),o=!0)}s++,i.debug(`Tool result added to history`,{toolCallId:l.id,newHistoryLength:n.getMessages().length,round:r})}return{contextOverflowed:o,addedCount:s,skippedCount:c,unknownToolFailureCount:0,unknownToolNames:[]}}function Tr(e,t,n){for(let r of e){let e=r.function?.name??`unknown`,i=`${e}::${typeof r.function?.arguments==`string`?r.function.arguments:JSON.stringify(r.function?.arguments??{})}`,a=(t.sameToolInputCounts.get(i)??0)+1;if(t.sameToolInputCounts.set(i,a),a>n)throw Error(`[EXECUTION] Tool "${e}" called with identical input ${a} times — aborting to prevent infinite loop`)}}async function Er(e,t,n,r,i,a,o,s,c,l,u,d,f){let{toolExecutionService:p,logger:m,eventEmitter:h}=c,g=f??l?.maxSameToolInputs;g!==void 0&&Tr(e,s,g),m.debug(`Tool calls detected, executing tools`,{toolCallCount:e.length,round:i,toolCalls:e.map(e=>({id:e.id,name:e.function?.name}))});let _=h.buildThinkingOwnerContext(n,r,a,o).ownerPath,v=e.length,y=`${a}`,b=p.createExecutionRequestsWithContext(e,{ownerPathBase:_,metadataFactory:e=>({conversationId:n,round:i,directParentId:a,batchId:y,expectedCount:v,toolCallId:e.id})}).map(e=>{if(!e.ownerId)throw Error(`[EXECUTION] Tool request missing ownerId`);return{...e,eventService:h.ensureToolEventService(e.ownerId,e.ownerPath),baseEventService:h.getBaseEventService()}}),x={requests:b,mode:`parallel`,maxConcurrency:5,continueOnError:!0,signal:u};d?.(`tool_batch_started`,{executionId:r,conversationId:n,round:i,batchId:y,mode:x.mode,maxConcurrency:x.maxConcurrency,requestCount:b.length,tools:b.map(e=>e.toolName)}),b.forEach((e,t)=>{d?.(`tool_execution_request`,{executionId:r,conversationId:n,round:i,batchId:y,index:t,toolName:e.toolName,toolCallId:e.executionId,parameters:e.parameters,ownerPath:e.ownerPath})});let S=await p.executeTools(x),C=S.results.filter(Cr).map(e=>e.toolName).filter(e=>typeof e==`string`&&e.length>0);S.results.forEach((e,t)=>{d?.(`tool_execution_result`,{executionId:r,conversationId:n,round:i,batchId:y,index:t,toolName:e.toolName,toolCallId:e.executionId,success:e.success,result:e.result,error:e.error,metadata:e.metadata})}),s.toolsExecuted.push(...S.results.filter(e=>!Cr(e)).map(e=>{if(!e.toolName||e.toolName.length===0)throw Error(`[EXECUTION] Tool result missing toolName`);return e.toolName}));let w=Yn(l?.defaultModel?.model??``),T=t.getMessages().length,E=wr(e,S,t,i,m,{contextLimit:w,cumulativeInputTokens:s.cumulativeInputTokens});return t.getMessages().slice(T).forEach((e,t)=>{d?.(`tool_message_committed`,{executionId:r,conversationId:n,round:i,batchId:y,index:t,message:e}),d?.(`history_mutation`,{executionId:r,conversationId:n,round:i,batchId:y,mutation:`append_message`,index:T+t,message:e})}),h.emitToolResultsEvents(e,S,s.toolsExecuted,n,r,i,a,o),h.clearToolEventServices(),{...E,unknownToolFailureCount:C.length,unknownToolNames:C}}function Dr(e){let t=0,n=0,r=!1;for(let i of e){if(!wt(i)||i.data===void 0)continue;let e=Tt(i);if(e.role!==`assistant`)continue;let a=Or(e);a&&(r=!0,t+=a.inputTokens,n+=a.outputTokens)}if(r)return{promptTokens:t,completionTokens:n,totalTokens:t+n}}function Or(e){let t=Ln(e);if(!t)return;let n=t.totalTokens??t.inputTokens+t.outputTokens;return{inputTokens:t.inputTokens,outputTokens:t.outputTokens,usage:{totalTokens:n,inputTokens:t.inputTokens,outputTokens:t.outputTokens}}}async function kr(e,t,n,r,i,a,o,s,c){let{plugins:l,logger:u,eventEmitter:d,cacheService:f}=c,p=e.currentRound;u.debug(`[ROUND-${p}] Starting execution round ${p}`,{executionId:i,conversationId:a.conversationId,round:p,maxRounds:t});let m=n.getMessages(),{thinkingNodeId:h,previousThinkingNodeId:g}=hr(r,e);if(await nr(l,`beforeProviderCall`,{messages:m},u),u.debug(`Sending messages to AI provider`,{round:p,messageCount:m.length,lastFewMessages:m.slice(-5).map(e=>({role:e.role,content:e.content?.substring(0,50),hasToolCalls:`toolCalls`in e?!!e.toolCalls?.length:!1,toolCallId:`toolCallId`in e?e.toolCallId:void 0}))}),d.emitWithContext(Vt.ASSISTANT_MESSAGE_START,{parameters:{round:p,messageCount:m.length},metadata:{round:p,thinkingNodeId:h}},()=>d.buildThinkingOwnerContext(r,i,h,g),e=>{if(!e.ownerType||!e.ownerId)throw Error(`[EXECUTION] Missing owner context for thinking event`);return Qt(d.getBaseEventService(),{ownerType:e.ownerType,ownerId:e.ownerId,ownerPath:e.ownerPath})}),er(m,o,e,n,u,p))return!0;p>1&&a.onTextDelta?.(`
3
3
 
4
- `),n.beginAssistant();let{wrappedOnTextDelta:_,wrappedOnProviderNativeRawPayload:v}=xr(a,n,i,p),y=await Sr(m,o,s,f,a,n,p,i,u,_,v);if(y===null)return!0;let{assistantResponse:b,assistantToolCalls:x}=br(y,i,a.conversationId,p,u);await nr(l,`afterProviderCall`,{messages:m,responseMessage:y},u);let S=typeof b.content==`string`&&b.content.trim().length>0;if(x.length===0&&!S)return u.warn(`[ROUND] Provider returned empty assistant response without tool calls`,{executionId:i,conversationId:a.conversationId,round:p}),n.discardPending(),!0;let C=Or(b),w=C?.inputTokens??0;w>0&&(e.cumulativeInputTokens=w),b.content&&!n.getPendingContent()&&n.appendStreaming(b.content);for(let e of x)n.appendToolCall(e);let ee=a.signal?.aborted?`interrupted`:`complete`;n.commitAssistant(ee,{round:p,...C??{}});let T=n.getMessages().at(-1);if(a.onExecutionEvent?.(`assistant_message_committed`,{executionId:i,conversationId:a.conversationId,round:p,message:b}),T&&a.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:a.conversationId,round:p,mutation:`append_message`,index:n.getMessages().length-1,message:T}),e.runningAssistantCount++,e.lastTrackedAssistantMessage=b,x.length===0)return u.debug(`[AGENT-FLOW-CONTROL] Round ${p} completed - no tool calls, execution finished for agent ${a.conversationId}`),d.emitAssistantMessageComplete(b,i,p,r,h,g),!0;let E=await Er(x,n,r,i,p,h,g,e,c,o,a.signal,a.onExecutionEvent,a.maxSameToolInputs??o.maxSameToolInputs);if(E.contextOverflowed&&u.warn(`[ROUND] Tool results partially skipped due to context overflow — continuing to let AI respond`,{added:E.addedCount,skipped:E.skippedCount,round:p}),E.unknownToolFailureCount>0?e.consecutiveUnknownToolFailureRounds+=1:e.consecutiveUnknownToolFailureRounds=0,e.consecutiveUnknownToolFailureRounds>=2){let t=[...new Set(E.unknownToolNames)].sort();return e.forcedSummaryInstruction=[`The model repeatedly requested unavailable tool(s): ${t.join(`, `)}.`,`Those tool calls were not executed because they are not registered tools.`,`Respond to the user now with that reason and use the available tool results already in the conversation history.`].join(` `),u.warn(`[ROUND] Stopping repeated unavailable tool-call loop`,{unavailableTools:t,consecutiveRounds:e.consecutiveUnknownToolFailureRounds,round:p}),!0}return u.debug(`Round ${p} completed - continuing to next round for agent ${a.conversationId}`),!1}function Ar(e,t){let n=t.maxExecutionRounds??e.maxExecutionRounds;if(n===void 0)return 10;if(!Number.isInteger(n)||n<0)throw Error(`[EXECUTION] maxExecutionRounds must be a non-negative integer`);return n}function jr(e,t){return t===0||e<t}async function Mr(e,t,n,r,i,a,o,s,c){let l=Ar(i,r);for(;jr(o.currentRound,l)&&!(s?.aborted||(o.currentRound++,await kr(o,l,e,t,n,r,i,a,c))||s?.aborted););let u=e.getMessages(),d=u.length>0?u[u.length-1]:void 0,f=d?.role===`assistant`&&typeof d.content==`string`&&d.content.length>0&&(!(`toolCalls`in d)||d.toolCalls.length===0);s?.aborted||r.allowToolOnlyCompletion!==!0&&(f||await Nr(e,a,i,n,o,t,r,c.logger,l))}async function Nr(e,t,n,r,i,a,o,s,c=10){s.warn(`No final text response — forcing summary call`,{maxRounds:c===0?`unlimited`:c,currentRound:i.currentRound,conversationId:a});try{let r=i.forcedSummaryInstruction??`Tool round limit reached. Provide your response based on the information gathered so far. If results are incomplete, let the user know what was covered and what remains — the user can request additional analysis in a follow-up message.`;e.addUserMessage(r);let a=e.getMessages(),s=n.systemMessage??``,c=a.some(e=>e.role===`system`&&e.content===s),u=s&&!c?[{id:l(),role:`system`,content:s,state:`complete`,timestamp:new Date},...a]:a,d={model:t.aiProviderInfo.model};o.onTextDelta&&(d.onTextDelta=o.onTextDelta);let f=await t.provider.chat(u,d),p=e.getMessages();if(p.findIndex(e=>e.role===`user`&&e.content===r)!==-1){let t=p.filter(e=>!(e.role===`user`&&e.content===r));e.clear();for(let n of t)e.addMessage(n)}let m=typeof f.content==`string`?f.content:``;m?e.addAssistantMessage(m,[],f.metadata):e.addAssistantMessage(`Maximum rounds reached. Partial results available in conversation history.`)}catch(e){s.warn(`Forced summary call failed`,{error:e instanceof Error?e.message:String(e)})}}async function Pr(e,t,n,r,i,a,o,s,c,l,u){let d={...lr(t,n,r,i.toolsExecuted),interrupted:o};return await nr(c,`afterRun`,{input:e,response:d.response,metadata:s?.metadata},l),l.debug(`Execution pipeline completed successfully`,{executionId:n,conversationId:a,duration:d.duration,tokensUsed:d.tokensUsed,toolsExecuted:d.toolsExecuted.length,rounds:i.currentRound}),u.emitExecution(Vt.COMPLETE,{result:{success:!0,data:d.response.substring(0,100)+`...`},metadata:{method:`execute`,success:!0,duration:d.duration,tokensUsed:d.tokensUsed,toolsExecuted:d.toolsExecuted}},a,n),d}async function*Fr(e,t,n,r,i,a,o,s){o.debug(`[EXECUTION-SERVICE-STREAM] Executing tools:`,{tools:e.map(e=>e.function.name)});let c=n,l=`thinking_${c}_${Date.now()}_${r}`,u=[...a.buildExecutionOwnerContext(c,r).ownerPath,{type:`thinking`,id:l}],d={requests:i.createExecutionRequestsWithContext(e,{ownerPathBase:u}),mode:`parallel`,maxConcurrency:5,continueOnError:!0,...s?{signal:s}:{}},f=await i.executeTools(d);for(let n of e){if(!n.id)throw Error(`[EXECUTION] Tool call missing id in streaming mode`);if(!n.function?.name||n.function.name.length===0)throw Error(`[EXECUTION] Tool call "${n.id}" missing function name in streaming mode`);let e=f.results.find(e=>e.executionId===n.id),i=f.errors.find(e=>Ut(e)&&e.executionId===n.id),a,o={executionId:r};if(e&&e.success){if(e.result===void 0)throw Error(`[EXECUTION] Tool result missing result payload in streaming mode`);a=typeof e.result==`string`?e.result:JSON.stringify(e.result),o.success=!0,e.toolName&&(o.toolName=e.toolName),yield{chunk:`\n[Tool: ${n.function.name} executed successfully]`,isComplete:!1}}else if(i){let e=i,t=e.error?.message?e.error.message:e.message?e.message:``;if(!t||t.length===0)throw Error(`[EXECUTION] Tool execution error missing message in streaming mode`);a=`Error: ${t}`,o.success=!1,o.error=t,e.toolName&&(o.toolName=e.toolName),yield{chunk:`\n[Tool: ${n.function.name} failed: ${t}]`,isComplete:!1}}else throw Error(`[EXECUTION] Missing tool result for tool call "${n.id}" in streaming mode`);t.addToolMessageWithId(a,n.id,n.function.name,o)}let p=e.map(e=>{if(!e.id||e.id.length===0)throw Error(`[EXECUTION] Tool call missing id for streaming tool results ready payload`);return e.id});if(p.length===0)throw Error(`[EXECUTION] Tool results ready requires toolCallIds in streaming mode`);a.emitExecution(Vt.TOOL_RESULTS_READY,{parameters:{toolCallIds:p,round:1},metadata:{toolsExecuted:f.results.map(e=>{if(!e.toolName||e.toolName.length===0)throw Error(`[EXECUTION] Tool result missing toolName`);return e.toolName}),round:1}},n,r)}async function*Ir(e,t,n,r,i){let{aiProviders:a,tools:o,conversationHistory:s,toolExecutionService:c,plugins:l,logger:u,eventEmitter:d}=i;u.debug(`ExecutionService.executeStream called`);let f=i.generateExecutionId(),p=Date.now();if(!r?.conversationId||r.conversationId.length===0)throw Error(`[EXECUTION] conversationId is required for streaming`);let m=r.conversationId;d.prepareOwnerPathBases(m);try{let t=s.getConversationStore(r.conversationId);e&&t.addUserMessage(e,{executionId:f}),await nr(l,`beforeRun`,{input:e,...r?.metadata?{metadata:r.metadata}:{}},u);let i=a.getCurrentProvider();if(!i)throw new W(`No AI provider configured`);let p=a.getProvider(i.provider);if(!p)throw new W(`AI provider '${i.provider}' not found`);if(typeof p.chatStream!=`function`)throw new W(`Provider must have chatStream method to support streaming execution`);u.debug(`ExecutionService calling provider.chatStream`);let h=t.getMessages(),g=Array.isArray(n.tools)?n.tools.length:void 0;u.debug(`[EXECUTION-SERVICE] config.tools:`,{length:g});let _=o.getTools(),v=Array.isArray(_)?_.length:void 0;u.debug(`[EXECUTION-SERVICE] this.tools.getTools():`,{length:v}),u.debug(`[EXECUTION-SERVICE] config.tools exists:`,{exists:!!n.tools}),u.debug(`[EXECUTION-SERVICE] config.tools.length > 0:`,{hasTools:n.tools&&n.tools.length>0});let y=r?.maxTokens??n.defaultModel.maxTokens,b=r?.temperature??n.defaultModel.temperature,x=r?.toolChoice??n.defaultModel.toolChoice,S={model:n.defaultModel.model,effort:n.defaultModel.effort??`high`,...r?.signal&&{signal:r.signal},...y!==void 0&&{maxTokens:y},...b!==void 0&&{temperature:b},...x!==void 0&&{toolChoice:x},...n.tools&&n.tools.length>0&&{tools:o.getTools()},...(()=>{let e=rr(n.responseFormat);return e?{responseFormat:e}:{}})()};ar(S.toolChoice,S.tools),u.debug(`[EXECUTION-SERVICE] Final chatOptions has tools:`,{hasTools:!!S.tools});let C=Array.isArray(S.tools)?S.tools.length:void 0;u.debug(`[EXECUTION-SERVICE] Final chatOptions.tools length:`,{length:C});let w=p.chatStream;if(!w)throw new W(`Provider does not support streaming`);let ee=w.call(p,h,S),T=``,E=!1,D=[],te=-1,O;for await(let e of ee){let t=Or(e);if(t&&(O=t),typeof e.content==`string`&&(E=!0),e.content&&(T+=e.content,yield{chunk:e.content,isComplete:!1}),e.role===`assistant`){let t=e;if(Array.isArray(t.toolCalls)&&t.toolCalls.length>0){for(let e of t.toolCalls)if(e.id&&e.id!==``){if(!e.type||e.type.length===0)throw Error(`[EXECUTION] Tool call "${e.id}" missing type in stream`);if(!e.function?.name||e.function.name.length===0)throw Error(`[EXECUTION] Tool call "${e.id}" missing function name in stream`);if(typeof e.function.arguments!=`string`)throw Error(`[EXECUTION] Tool call "${e.id}" missing arguments in stream`);te=D.length,D.push({id:e.id,type:e.type,function:{name:e.function.name,arguments:e.function.arguments}}),u.debug(`[TOOL-STREAM] New tool call started: ${e.id} (${e.function?.name})`)}else if(te>=0){let t=typeof e.function?.name==`string`&&e.function.name.length>0,n=typeof e.function?.arguments==`string`&&e.function.arguments.length>0;if(!t&&!n)throw Error(`[EXECUTION] Tool call fragment missing name/arguments for ${D[te].id}`);t&&(D[te].function.name+=e.function.name),n&&(D[te].function.arguments+=e.function.arguments);let r=n?e.function.arguments:e.function.name;u.debug(`[TOOL-STREAM] Adding fragment to tool ${D[te].id}: "${r}"`)}}}}if(u.debug(`[EXECUTION-SERVICE-STREAM] Stream completed, toolCalls detected:`,{count:D.length}),typeof T!=`string`)throw Error(`[EXECUTION] Streaming response content is required`);if(!E&&D.length===0)throw Error(`[EXECUTION] Provider response must have content or tool calls`);t.addAssistantMessage(T,D,{executionId:f,...O??{}}),D.length>0&&(yield*Fr(D,t,m,f,c,d,u,r?.signal)),await nr(l,`afterRun`,{input:e,response:T,...r?.metadata?{metadata:r.metadata}:{}},u),yield{chunk:``,isComplete:!0}}catch(t){throw u.error(`ExecutionService streaming execution failed`,{error:t instanceof Error?t.message:String(t),executionTime:Date.now()-p}),await nr(l,`onError`,{input:e,error:t instanceof Error?t:Error(String(t)),...r?.metadata?{metadata:r.metadata}:{}},u),t}finally{d.resetOwnerPathBases()}}var Lr=class{toolExecutionService;aiProviders;tools;conversationHistory;plugins=[];logger;eventEmitter;cacheService;constructor(e,t,n,r,i,a){if(this.toolExecutionService=new kn(t),this.aiProviders=e,this.tools=t,this.conversationHistory=n,this.plugins=[],this.logger=Nt(`ExecutionService`),!r)throw Error(`[EXECUTION] EventService is required`);this.eventEmitter=new In(r,this.logger,i),this.cacheService=a}setAskHandler(e){this.toolExecutionService.setAskHandler(e)}registerPlugin(e){let t=e.priority??0,n=this.plugins.findIndex(e=>(e.priority??0)<t);n===-1?this.plugins.push(e):this.plugins.splice(n,0,e),this.logger.debug(`Plugin registered`,{pluginName:e.name,priority:t})}removePlugin(e){let t=this.plugins.findIndex(t=>t.name===e);return t===-1?!1:(this.plugins.splice(t,1),this.logger.debug(`Plugin removed`,{pluginName:e}),!0)}getPlugin(e){return this.plugins.find(t=>t.name===e)}getPlugins(){return[...this.plugins]}async execute(e,t,n,r){let i=dr(),a=new Date,o=fr(r,`execute`),s=pr(t,n,a,i,o,r);this.eventEmitter.prepareOwnerPathBases(o),this.logger.debug(`Starting execution pipeline`,{executionId:i,conversationId:o,messageCount:t.length,hasContext:!!r});let c=or(this.aiProviders,this.tools,n);this.eventEmitter.emitExecutionStartEvent(e,n,t,c,o,i);let l=cr(this.conversationHistory,o,t,n,i);try{let t=l.getMessages().length;l.addUserMessage(e,{executionId:i});let u=l.getMessages()[t];u&&s.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:o,mutation:`append_message`,index:t,message:u}),this.eventEmitter.emitUserMessageEvent(e,o,i),await nr(this.plugins,`beforeRun`,{input:e,...r?.metadata?{metadata:r.metadata}:{}},this.logger),sr(c);let d={toolsExecuted:[],currentRound:0,runningAssistantCount:0,lastTrackedAssistantMessage:void 0,cumulativeInputTokens:0,consecutiveUnknownToolFailureRounds:0,sameToolInputCounts:new Map};for(let e of l.getMessages())e.role===`assistant`&&(d.runningAssistantCount++,d.lastTrackedAssistantMessage=e);return await Mr(l,o,i,s,n,c,d,r?.signal,{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService}),Pr(e,l,i,a,d,o,r?.signal?.aborted??!1,r,this.plugins,this.logger,this.eventEmitter)}catch(e){return e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`))?{response:``,messages:l.getMessages(),executionId:i,duration:Date.now()-a.getTime(),toolsExecuted:[],success:!0,interrupted:!0}:(await ur(e,s,a,o,i,this.plugins,this.logger,this.eventEmitter),{response:``,messages:[],tokensUsed:0,toolsExecuted:[],duration:Date.now()-a.getTime(),executionId:i,success:!1,error:e instanceof Error?e:Error(String(e))})}finally{this.eventEmitter.resetOwnerPathBases()}}async*executeStream(e,t,n,r){yield*Ir(e,t,n,r,{aiProviders:this.aiProviders,tools:this.tools,conversationHistory:this.conversationHistory,toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,generateExecutionId:()=>dr()})}async getStats(){return{pluginCount:this.plugins.length,pluginNames:this.plugins.map(e=>e.name),historyStats:this.conversationHistory.getStats()}}clearPlugins(){this.plugins=[],this.logger.debug(`All plugins cleared`)}};const Rr=(e,t)=>`${e}.${t}`,zr={START:Rr(Ht,Vt.START),COMPLETE:Rr(Ht,Vt.COMPLETE),ERROR:Rr(Ht,Vt.ERROR)},Br={CALL_START:Rr(Dn,En.CALL_START),CALL_COMPLETE:Rr(Dn,En.CALL_COMPLETE),CALL_ERROR:Rr(Dn,En.CALL_ERROR)},Vr={EXECUTION_START:Rr(Bt,zt.EXECUTION_START),EXECUTION_COMPLETE:Rr(Bt,zt.EXECUTION_COMPLETE),EXECUTION_ERROR:Rr(Bt,zt.EXECUTION_ERROR),CREATED:Rr(Bt,zt.CREATED)},K={EXECUTION_START:zr.START,EXECUTION_COMPLETE:zr.COMPLETE,EXECUTION_ERROR:zr.ERROR,TOOL_BEFORE_EXECUTE:`tool.beforeExecute`,TOOL_AFTER_EXECUTE:`tool.afterExecute`,TOOL_SUCCESS:`tool.success`,TOOL_ERROR:Br.CALL_ERROR,CONVERSATION_START:`conversation.start`,CONVERSATION_COMPLETE:`conversation.complete`,CONVERSATION_ERROR:`conversation.error`,AGENT_EXECUTION_START:Vr.EXECUTION_START,AGENT_EXECUTION_COMPLETE:Vr.EXECUTION_COMPLETE,AGENT_EXECUTION_ERROR:Vr.EXECUTION_ERROR,AGENT_CREATED:Vr.CREATED,AGENT_DESTROYED:`agent.destroyed`,PLUGIN_LOADED:`plugin.loaded`,PLUGIN_UNLOADED:`plugin.unloaded`,PLUGIN_ERROR:`plugin.error`,ERROR_OCCURRED:`error.occurred`,WARNING_OCCURRED:`warning.occurred`,MODULE_INITIALIZE_START:`module.initialize.start`,MODULE_INITIALIZE_COMPLETE:`module.initialize.complete`,MODULE_INITIALIZE_ERROR:`module.initialize.error`,MODULE_EXECUTION_START:`module.execution.start`,MODULE_EXECUTION_COMPLETE:`module.execution.complete`,MODULE_EXECUTION_ERROR:`module.execution.error`,MODULE_DISPOSE_START:`module.dispose.start`,MODULE_DISPOSE_COMPLETE:`module.dispose.complete`,MODULE_DISPOSE_ERROR:`module.dispose.error`,MODULE_REGISTERED:`module.registered`,MODULE_UNREGISTERED:`module.unregistered`,EXECUTION_HIERARCHY:`execution.hierarchy`,EXECUTION_REALTIME:`execution.realtime`,TOOL_REALTIME:`tool.realtime`,CUSTOM:`custom`};var Hr=class{enabled=!0;category=`custom`;priority=Rt.NORMAL;options;eventEmitter;subscribedEvents=[];eventHandlers=new Map;pluginLogger=Nt(`AbstractPlugin`);stats={calls:0,errors:0,moduleEventsReceived:0,lastActivity:void 0};async initialize(e){this.options=e,e&&`enabled`in e&&typeof e.enabled==`boolean`?this.enabled=e.enabled:this.enabled=!0,e?.category&&(this.category=e.category),e?.priority!==void 0&&(this.priority=(e.priority,e.priority))}async subscribeToModuleEvents(e){if(this.eventEmitter=e,!this.options)return;let t=[];this.options.subscribeToAllModuleEvents&&t.push(K.MODULE_INITIALIZE_START,K.MODULE_INITIALIZE_COMPLETE,K.MODULE_INITIALIZE_ERROR,K.MODULE_EXECUTION_START,K.MODULE_EXECUTION_COMPLETE,K.MODULE_EXECUTION_ERROR,K.MODULE_DISPOSE_START,K.MODULE_DISPOSE_COMPLETE,K.MODULE_DISPOSE_ERROR),this.options.moduleEvents&&t.push(...this.options.moduleEvents);for(let e of t){let t=this.eventEmitter.on(e,async t=>{try{this.stats.moduleEventsReceived++,this.stats.lastActivity=new Date,await this.onModuleEvent?.(e,t)}catch(t){this.stats.errors++;let n=t instanceof Error?t:Error(String(t));this.pluginLogger.error(`Plugin "${this.name}" failed to handle module event "${String(e)}"`,{plugin:this.name,eventType:String(e),error:n.message})}}),n=this.eventHandlers.get(e);n?n.push(t):this.eventHandlers.set(e,[t]),this.subscribedEvents.push(e)}}async unsubscribeFromModuleEvents(e){for(let[t,n]of this.eventHandlers.entries())for(let r of n)e.off(t,r);this.eventHandlers.clear(),this.subscribedEvents=[],this.eventEmitter=void 0}async dispose(){this.eventEmitter&&await this.unsubscribeFromModuleEvents(this.eventEmitter)}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}getConfig(){return{}}updateConfig(e){}getData(){return{name:this.name,version:this.version,enabled:this.enabled,category:this.category,priority:this.priority,subscribedEvents:[...this.subscribedEvents],metadata:{moduleEventsReceived:this.stats.moduleEventsReceived,totalCalls:this.stats.calls,totalErrors:this.stats.errors}}}getStatus(){return{name:this.name,version:this.version,enabled:this.enabled,initialized:!0,category:this.category,priority:this.priority,subscribedEventsCount:this.subscribedEvents.length,hasEventEmitter:!!this.eventEmitter}}getStats(){return{enabled:this.enabled,calls:this.stats.calls,errors:this.stats.errors,moduleEventsReceived:this.stats.moduleEventsReceived,...this.stats.lastActivity&&{lastActivity:this.stats.lastActivity}}}updateCallStats(){this.stats.calls++,this.stats.lastActivity=new Date}updateErrorStats(){this.stats.errors++,this.stats.lastActivity=new Date}},Ur=class{logger;eventService;constructor(e={}){this.eventService=e.eventService,this.logger=e.logger??kt}setEventService(e){this.eventService=e}getEventService(){return this.eventService}emitEvent(e,t){this.eventService&&this.eventService.emit(e,t)}async execute(e,t){return await this.executeImpl(e,t)}validate(e){return(this.schema.parameters.required||[]).every(t=>t in e)}validateParameters(e){let t=this.schema.parameters.required||[],n=[],r=e;for(let e of t)e in r||n.push(`Missing required parameter: ${e}`);return{isValid:n.length===0,errors:n}}getDescription(){return this.schema.description}getName(){return this.schema.name}},Wr=class{static validateAgentConfig(e){let t=[],n=[];return e.name||t.push(`name is required`),(!e.aiProviders||e.aiProviders.length===0)&&t.push(`aiProviders array is required and must have at least one provider`),e.defaultModel?(e.defaultModel.provider||t.push(`defaultModel.provider is required`),e.defaultModel.model||t.push(`defaultModel.model is required`)):t.push(`defaultModel is required`),e.aiProviders&&e.defaultModel?.provider&&(e.aiProviders.map(e=>e.name).includes(e.defaultModel.provider)||t.push(`defaultModel.provider "${e.defaultModel.provider}" is not found in aiProviders list`)),e.defaultModel?.temperature!==void 0&&(typeof e.defaultModel.temperature!=`number`||e.defaultModel.temperature<0||e.defaultModel.temperature>2)&&t.push(`defaultModel.temperature must be a number between 0 and 2`),e.defaultModel?.maxTokens!==void 0&&(typeof e.defaultModel.maxTokens!=`number`||e.defaultModel.maxTokens<=0)&&t.push(`defaultModel.maxTokens must be a positive number`),e.systemMessage&&e.systemMessage.length>1e3&&n.push(`systemMessage is quite long, consider keeping it concise for better performance`),e.tools&&e.tools.length>20&&n.push(`Large number of tools may impact performance, consider grouping related tools`),{isValid:t.length===0,errors:t,warnings:n}}static validateUserInput(e){let t=[],n=[];return!e||typeof e!=`string`?t.push(`Input must be a non-empty string`):(e.trim().length===0&&t.push(`Input cannot be only whitespace`),e.length>1e4&&n.push(`Very long input may be truncated by AI providers`)),{isValid:t.length===0,errors:t,warnings:n}}static validateProviderName(e){let t=[];return!e||typeof e!=`string`?t.push(`Provider name must be a non-empty string`):/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(e)||t.push(`Provider name must start with a letter and contain only letters, numbers, underscores, and hyphens`),{isValid:t.length===0,errors:t}}static validateModelName(e){let t=[];return!e||typeof e!=`string`?t.push(`Model name must be a non-empty string`):e.trim().length===0&&t.push(`Model name cannot be only whitespace`),{isValid:t.length===0,errors:t}}static validateApiKey(e){let t=[];return!e||typeof e!=`string`?(t.push(`API key must be a non-empty string`),{isValid:!1,errors:t}):(e.length<10&&t.push(`API key appears to be too short`),/\s/.test(e)&&t.push(`API key should not contain whitespace`),{isValid:t.length===0,errors:t,warnings:[]})}};const Gr=Wr.validateAgentConfig;Wr.validateUserInput,Wr.validateProviderName,Wr.validateModelName,Wr.validateApiKey;function Kr(e){return e===`darwin`?'Host OS: macOS (POSIX, BSD userland). Use BSD-flavored utilities: `sed -i ""` needs an empty backup arg, `date`/`grep`/`stat` flags differ from GNU. Prefer portable POSIX flags; avoid Linux/GNU-only options.':e===`linux`?"Host OS: Linux (POSIX, usually GNU coreutils, but distro/user setup varies). Prefer portable POSIX flags; do not assume a specific distro, and probe with `command -v` before relying on a non-standard tool.":`Host OS: ${e} (POSIX). Write portable POSIX sh/bash syntax; avoid OS-specific flags.`}function qr(e,t){let n=/(^|\/)bash$/.test(e)?`bash`:`sh`;return{command:e,kind:n,platform:t,commandArgs:e=>[`-c`,e],interactiveArgs:[],label:`${n} on ${t}`,syntaxHint:Kr(t)}}function Jr(e){return{command:e,kind:`powershell`,platform:`win32`,commandArgs:e=>[`-NoProfile`,`-Command`,e],interactiveArgs:[`-NoProfile`],label:`PowerShell (Windows)`,syntaxHint:"Write PowerShell syntax (not bash): e.g. `Get-ChildItem` not `ls -la`, `$env:VAR` not `$VAR`."}}function Yr(e=process.env,t=process.platform){let n=e.ROBOTA_SHELL?.trim();if(t===`win32`)return n!==void 0&&n.length>0?/(^|\\)cmd(\.exe)?$/i.test(n)?{command:n,kind:`cmd`,platform:t,commandArgs:e=>[`/d`,`/s`,`/c`,e],interactiveArgs:[],label:`cmd.exe (Windows)`,syntaxHint:`Write Windows cmd.exe syntax (not bash).`}:Jr(n):Jr(`powershell.exe`);if(n!==void 0&&n.length>0)return qr(n,t);let r=e.SHELL?.trim();return qr(r!==void 0&&r.length>0?r:`/bin/sh`,t)}function Xr(e,t={}){let n={},r=[],i=e._def;if(!i)throw Error(`Zod schema is missing _def; cannot convert to JSON schema.`);if(i.typeName===`ZodObject`&&i.shape){let e=typeof i.shape==`function`?i.shape():i.shape;for(let[t,i]of Object.entries(e))n[t]=Zr(i),Qr(i)&&r.push(t)}return{type:`object`,properties:n,required:r,...(t.allowAdditionalProperties||i.unknownKeys===`passthrough`)&&{additionalProperties:!0}}}function Zr(e){let t=e._def;if(!t)throw Error(`Zod type is missing _def; cannot convert to JSON schema.`);let n={};switch(t.description&&(n.description=t.description),t.typeName){case`ZodString`:return{type:`string`,...n};case`ZodNumber`:return{type:`number`,...n};case`ZodBoolean`:return{type:`boolean`,...n};case`ZodArray`:if(!t.type)throw Error(`ZodArray is missing item type; cannot convert to JSON schema.`);return{type:`array`,items:Zr(t.type),...n};case`ZodObject`:return{type:`object`,...n};case`ZodEnum`:{let e=t.values;if(!e||!Array.isArray(e))throw Error(`ZodEnum is missing enum values; cannot convert to JSON schema.`);return{type:`string`,enum:e,...n}}case`ZodOptional`:if(t.innerType)return{...Zr(t.innerType),...n};throw Error(`ZodOptional is missing innerType; cannot convert to JSON schema.`);case`ZodNullable`:if(t.innerType)return{...Zr(t.innerType),...n};throw Error(`ZodNullable is missing innerType; cannot convert to JSON schema.`);case`ZodDefault`:if(t.innerType)return{...Zr(t.innerType),...n};throw Error(`ZodDefault is missing innerType; cannot convert to JSON schema.`);case`ZodRecord`:return t.valueType?{type:`object`,additionalProperties:Zr(t.valueType),...n}:{type:`object`,additionalProperties:{type:`string`},...n};default:throw Error(`Unsupported Zod type: ${String(t.typeName)}`)}}function Qr(e){let t=e._def;if(!t)throw Error(`Zod schema is missing _def; cannot determine required fields.`);return t.typeName!==`ZodOptional`&&t.typeName!==`ZodNullable`&&t.typeName!==`ZodDefault`}function $r(e){return typeof e.safeParse==`function`&&typeof e.parse==`function`}function ei(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues;if(Array.isArray(t))return t.map(e=>{if(e&&typeof e==`object`&&`message`in e){let t=Array.isArray(e.path)?e.path.join(`.`):``,n=String(e.message);return t?`${t}: ${n}`:n}return String(e)})}return[String(e)]}function ti(e){if($r(e))return{name:`structured_output`,jsonSchema:Xr(e),validate:t=>{let n=e.safeParse(t);return n.success?{success:!0,value:n.data}:{success:!1,issues:ei(n.error)}}};let{jsonSchema:t,name:n}=e;return{name:n??`structured_output`,jsonSchema:t,validate:e=>{let n=ni(t,e,`$`);return n.length===0?{success:!0,value:e}:{success:!1,issues:n}}}}function ni(e,t,n){let r=[],i=e.type;switch(i){case`object`:{if(typeof t!=`object`||!t||Array.isArray(t))return[`${n}: expected object, got ${ri(t)}`];let i=t,a=`required`in e?e.required??[]:[];for(let e of a)e in i||r.push(`${n}.${e}: required property missing`);let o=e.properties??{};for(let[e,t]of Object.entries(o))e in i&&r.push(...ni(t,i[e],`${n}.${e}`));let s=e.additionalProperties;if(s===void 0||s===!1)for(let e of Object.keys(i))e in o||r.push(`${n}.${e}: unexpected additional property`);else if(typeof s==`object`)for(let[e,t]of Object.entries(i))e in o||r.push(...ni(s,t,`${n}.${e}`));return r}case`array`:{if(!Array.isArray(t))return[`${n}: expected array, got ${ri(t)}`];let i=`items`in e?e.items:void 0;return i&&t.forEach((e,t)=>{r.push(...ni(i,e,`${n}[${t}]`))}),r}case`string`:return typeof t==`string`?(`enum`in e&&e.enum&&!e.enum.some(e=>e===t)&&r.push(`${n}: value ${JSON.stringify(t)} is not one of the allowed enum values`),`pattern`in e&&e.pattern&&!new RegExp(e.pattern).test(t)&&r.push(`${n}: value does not match pattern ${e.pattern}`),r):[`${n}: expected string, got ${ri(t)}`];case`number`:case`integer`:return typeof t!=`number`||Number.isNaN(t)?[`${n}: expected number, got ${ri(t)}`]:(i===`integer`&&!Number.isInteger(t)&&r.push(`${n}: expected integer, got non-integer number`),`minimum`in e&&e.minimum!==void 0&&t<e.minimum&&r.push(`${n}: value ${t} is below minimum ${e.minimum}`),`maximum`in e&&e.maximum!==void 0&&t>e.maximum&&r.push(`${n}: value ${t} is above maximum ${e.maximum}`),`enum`in e&&e.enum&&!e.enum.some(e=>e===t)&&r.push(`${n}: value ${t} is not one of the allowed enum values`),r);case`boolean`:return typeof t==`boolean`?r:[`${n}: expected boolean, got ${ri(t)}`];case`null`:return t===null?r:[`${n}: expected null, got ${ri(t)}`];default:return[`${n}: unsupported schema type ${String(i)}`]}}function ri(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function ii(e){let t=e.trim(),n=/^```(?:json)?\s*\n([\s\S]*?)\n?```$/.exec(t),r=n?n[1]:t;try{return{success:!0,value:JSON.parse(r)}}catch(e){return{success:!1,issue:`response is not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}function ai(e,t){let n={id:l(),role:`user`,content:e,state:`complete`,timestamp:new Date};return t?.name&&(n.name=t.name),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function oi(e,t){let n={id:l(),role:`assistant`,content:e,state:t?.state??`complete`,timestamp:new Date};return t?.toolCalls&&(n.toolCalls=t.toolCalls),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function q(e,t){let n={id:l(),role:`system`,content:e,state:`complete`,timestamp:new Date};return t?.name&&(n.name=t.name),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function si(e,t){let n={id:l(),role:`tool`,content:e,toolCallId:t.toolCallId,state:`complete`,timestamp:new Date};return t.name&&(n.name=t.name),t.metadata&&(n.metadata=t.metadata),t.parts&&(n.parts=t.parts),n}var ci=class{maxMessages;entries=[];constructor(e){this.maxMessages=e?.maxMessages||0}addMessage(e){this.entries.push(H(e)),this.applyMessageLimit()}addEntry(e){this.entries.push(e)}getHistory(){return[...this.entries]}addUserMessage(e,t,n){this.addMessage(ai(e,{...t&&{metadata:t},...n&&{parts:n}}))}addAssistantMessage(e,t,n,r){this.addMessage(oi(e,{...t&&{toolCalls:t},...n&&{metadata:n},...r&&{parts:r}}))}addSystemMessage(e,t,n){this.addMessage(q(e,{...t&&{metadata:t},...n&&{parts:n}}))}setSystemPrompt(e,t,n){let r=e=>wt(e)&&Dt(Tt(e)),i=this.entries.filter(e=>!r(e)),a=H(q(e,{...t&&{metadata:t},...n&&{parts:n}}));i.unshift(a),this.entries=i}addToolMessageWithId(e,t,n,r,i){this.addMessage(si(e,{toolCallId:t,name:n,...r&&{metadata:r},...i&&{parts:i}}))}getMessages(){return this.entries.filter(wt).map(Tt)}getMessagesByRole(e){return this.getMessages().filter(t=>t.role===e)}getRecentMessages(e){return this.getMessages().slice(-e)}getMessageCount(){return this.entries.filter(wt).length}clear(){this.entries=[]}applyMessageLimit(){if(this.maxMessages<=0)return;let e=this.entries.filter(wt);if(e.length<=this.maxMessages)return;let t=e.map(Tt),n=t.filter(Dt),r=t.filter(e=>!Dt(e)),i=Math.max(0,this.maxMessages-n.length),a=[...n,...r.slice(-i)],o=new Set(a.map(e=>e.id));this.entries=this.entries.filter(e=>!wt(e)||o.has(e.id))}},li=class{history;pendingAssistant=null;constructor(e=0){this.history=new ci({maxMessages:e})}addMessage(e){this.history.addMessage(e)}addUserMessage(e,t,n){this.history.addUserMessage(e,t,n)}addAssistantMessage(e,t,n,r){this.history.addAssistantMessage(e,t,n,r)}addSystemMessage(e,t,n){this.history.addSystemMessage(e,t,n)}setSystemPrompt(e,t,n){this.history.setSystemPrompt(e,t,n)}addToolMessage(e,t,n,r,i){this.history.addToolMessageWithId(e,t,n||`unknown`,r,i)}addToolMessageWithId(e,t,n,r,i){this.history.addToolMessageWithId(e,t,n,r,i)}addEntry(e){this.history.addEntry(e)}getHistory(){return this.history.getHistory()}getMessages(){return this.history.getMessages()}getMessagesByRole(e){return this.history.getMessagesByRole(e)}getRecentMessages(e){return this.history.getRecentMessages(e)}getMessageCount(){return this.history.getMessageCount()}beginAssistant(){this.pendingAssistant||={id:l(),content:``,toolCalls:[]}}appendStreaming(e){this.pendingAssistant||={id:l(),content:``,toolCalls:[]},this.pendingAssistant.content+=e}appendToolCall(e){this.pendingAssistant||={id:l(),content:``,toolCalls:[]},this.pendingAssistant.toolCalls.some(t=>t.id===e.id)||this.pendingAssistant.toolCalls.push(e)}commitAssistant(e,t){if(!this.pendingAssistant)return;let n=this.pendingAssistant,r=n.toolCalls.length>0,i=n.content,a={id:n.id,role:`assistant`,content:i,state:e,timestamp:new Date,...r&&{toolCalls:n.toolCalls},...t&&{metadata:t}};this.history.addMessage(a),this.pendingAssistant=null}discardPending(){this.pendingAssistant=null}hasPendingAssistant(){return this.pendingAssistant!==null}getPendingContent(){return this.pendingAssistant?.content??``}getMessagesForAPI(){return this.history.getMessages().map(e=>{let t={role:e.role,content:e.content};return Et(e)&&e.state===`interrupted`&&(t.content=(t.content||``)+`
4
+ `),n.beginAssistant();let{wrappedOnTextDelta:_,wrappedOnProviderNativeRawPayload:v}=xr(a,n,i,p),y=await Sr(m,o,s,f,a,n,p,i,u,_,v);if(y===null)return!0;let{assistantResponse:b,assistantToolCalls:x}=br(y,i,a.conversationId,p,u);await nr(l,`afterProviderCall`,{messages:m,responseMessage:y},u);let S=typeof b.content==`string`&&b.content.trim().length>0;if(x.length===0&&!S)return u.warn(`[ROUND] Provider returned empty assistant response without tool calls`,{executionId:i,conversationId:a.conversationId,round:p}),n.discardPending(),!0;let C=Or(b),w=C?.inputTokens??0;w>0&&(e.cumulativeInputTokens=w),b.content&&!n.getPendingContent()&&n.appendStreaming(b.content);for(let e of x)n.appendToolCall(e);let T=a.signal?.aborted?`interrupted`:`complete`;n.commitAssistant(T,{round:p,...C??{}});let E=n.getMessages().at(-1);if(a.onExecutionEvent?.(`assistant_message_committed`,{executionId:i,conversationId:a.conversationId,round:p,message:b}),E&&a.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:a.conversationId,round:p,mutation:`append_message`,index:n.getMessages().length-1,message:E}),e.runningAssistantCount++,e.lastTrackedAssistantMessage=b,x.length===0)return u.debug(`[AGENT-FLOW-CONTROL] Round ${p} completed - no tool calls, execution finished for agent ${a.conversationId}`),d.emitAssistantMessageComplete(b,i,p,r,h,g),!0;let D=await Er(x,n,r,i,p,h,g,e,c,o,a.signal,a.onExecutionEvent,a.maxSameToolInputs??o.maxSameToolInputs);if(D.contextOverflowed&&u.warn(`[ROUND] Tool results partially skipped due to context overflow — continuing to let AI respond`,{added:D.addedCount,skipped:D.skippedCount,round:p}),D.unknownToolFailureCount>0?e.consecutiveUnknownToolFailureRounds+=1:e.consecutiveUnknownToolFailureRounds=0,e.consecutiveUnknownToolFailureRounds>=2){let t=[...new Set(D.unknownToolNames)].sort();return e.forcedSummaryInstruction=[`The model repeatedly requested unavailable tool(s): ${t.join(`, `)}.`,`Those tool calls were not executed because they are not registered tools.`,`Respond to the user now with that reason and use the available tool results already in the conversation history.`].join(` `),u.warn(`[ROUND] Stopping repeated unavailable tool-call loop`,{unavailableTools:t,consecutiveRounds:e.consecutiveUnknownToolFailureRounds,round:p}),!0}return u.debug(`Round ${p} completed - continuing to next round for agent ${a.conversationId}`),!1}function Ar(e,t){let n=t.maxExecutionRounds??e.maxExecutionRounds;if(n===void 0)return 10;if(!Number.isInteger(n)||n<0)throw Error(`[EXECUTION] maxExecutionRounds must be a non-negative integer`);return n}function jr(e,t){return t===0||e<t}async function Mr(e,t,n,r,i,a,o,s,c){let l=Ar(i,r);for(;jr(o.currentRound,l)&&!(s?.aborted||(o.currentRound++,await kr(o,l,e,t,n,r,i,a,c))||s?.aborted););let u=e.getMessages(),d=u.length>0?u[u.length-1]:void 0,f=d?.role===`assistant`&&typeof d.content==`string`&&d.content.length>0&&(!(`toolCalls`in d)||d.toolCalls.length===0);s?.aborted||r.allowToolOnlyCompletion!==!0&&(f||await Nr(e,a,i,n,o,t,r,c.logger,l))}async function Nr(e,t,n,r,i,a,o,s,c=10){s.warn(`No final text response — forcing summary call`,{maxRounds:c===0?`unlimited`:c,currentRound:i.currentRound,conversationId:a});try{let r=i.forcedSummaryInstruction??`Tool round limit reached. Provide your response based on the information gathered so far. If results are incomplete, let the user know what was covered and what remains — the user can request additional analysis in a follow-up message.`;e.addUserMessage(r);let a=e.getMessages(),s=n.systemMessage??``,c=a.some(e=>e.role===`system`&&e.content===s),u=s&&!c?[{id:l(),role:`system`,content:s,state:`complete`,timestamp:new Date},...a]:a,d={model:t.aiProviderInfo.model};o.onTextDelta&&(d.onTextDelta=o.onTextDelta);let f=await t.provider.chat(u,d),p=e.getMessages();if(p.findIndex(e=>e.role===`user`&&e.content===r)!==-1){let t=p.filter(e=>!(e.role===`user`&&e.content===r));e.clear();for(let n of t)e.addMessage(n)}let m=typeof f.content==`string`?f.content:``;m?e.addAssistantMessage(m,[],f.metadata):e.addAssistantMessage(`Maximum rounds reached. Partial results available in conversation history.`)}catch(e){s.warn(`Forced summary call failed`,{error:e instanceof Error?e.message:String(e)})}}async function Pr(e,t,n,r,i,a,o,s,c,l,u){let d={...lr(t,n,r,i.toolsExecuted),interrupted:o};return await nr(c,`afterRun`,{input:e,response:d.response,metadata:s?.metadata},l),l.debug(`Execution pipeline completed successfully`,{executionId:n,conversationId:a,duration:d.duration,tokensUsed:d.tokensUsed,toolsExecuted:d.toolsExecuted.length,rounds:i.currentRound}),u.emitExecution(Vt.COMPLETE,{result:{success:!0,data:d.response.substring(0,100)+`...`},metadata:{method:`execute`,success:!0,duration:d.duration,tokensUsed:d.tokensUsed,toolsExecuted:d.toolsExecuted}},a,n),d}async function*Fr(e,t,n,r,i,a,o,s){o.debug(`[EXECUTION-SERVICE-STREAM] Executing tools:`,{tools:e.map(e=>e.function.name)});let c=n,l=`thinking_${c}_${Date.now()}_${r}`,u=[...a.buildExecutionOwnerContext(c,r).ownerPath,{type:`thinking`,id:l}],d={requests:i.createExecutionRequestsWithContext(e,{ownerPathBase:u}),mode:`parallel`,maxConcurrency:5,continueOnError:!0,...s?{signal:s}:{}},f=await i.executeTools(d);for(let n of e){if(!n.id)throw Error(`[EXECUTION] Tool call missing id in streaming mode`);if(!n.function?.name||n.function.name.length===0)throw Error(`[EXECUTION] Tool call "${n.id}" missing function name in streaming mode`);let e=f.results.find(e=>e.executionId===n.id),i=f.errors.find(e=>Ut(e)&&e.executionId===n.id),a,o={executionId:r};if(e&&e.success){if(e.result===void 0)throw Error(`[EXECUTION] Tool result missing result payload in streaming mode`);a=typeof e.result==`string`?e.result:JSON.stringify(e.result),o.success=!0,e.toolName&&(o.toolName=e.toolName),yield{chunk:`\n[Tool: ${n.function.name} executed successfully]`,isComplete:!1}}else if(i){let e=i,t=e.error?.message?e.error.message:e.message?e.message:``;if(!t||t.length===0)throw Error(`[EXECUTION] Tool execution error missing message in streaming mode`);a=`Error: ${t}`,o.success=!1,o.error=t,e.toolName&&(o.toolName=e.toolName),yield{chunk:`\n[Tool: ${n.function.name} failed: ${t}]`,isComplete:!1}}else throw Error(`[EXECUTION] Missing tool result for tool call "${n.id}" in streaming mode`);t.addToolMessageWithId(a,n.id,n.function.name,o)}let p=e.map(e=>{if(!e.id||e.id.length===0)throw Error(`[EXECUTION] Tool call missing id for streaming tool results ready payload`);return e.id});if(p.length===0)throw Error(`[EXECUTION] Tool results ready requires toolCallIds in streaming mode`);a.emitExecution(Vt.TOOL_RESULTS_READY,{parameters:{toolCallIds:p,round:1},metadata:{toolsExecuted:f.results.map(e=>{if(!e.toolName||e.toolName.length===0)throw Error(`[EXECUTION] Tool result missing toolName`);return e.toolName}),round:1}},n,r)}async function*Ir(e,t,n,r,i){let{aiProviders:a,tools:o,conversationHistory:s,toolExecutionService:c,plugins:l,logger:u,eventEmitter:d}=i;u.debug(`ExecutionService.executeStream called`);let f=i.generateExecutionId(),p=Date.now();if(!r?.conversationId||r.conversationId.length===0)throw Error(`[EXECUTION] conversationId is required for streaming`);let m=r.conversationId;d.prepareOwnerPathBases(m);try{let t=s.getConversationStore(r.conversationId);e&&t.addUserMessage(e,{executionId:f}),await nr(l,`beforeRun`,{input:e,...r?.metadata?{metadata:r.metadata}:{}},u);let i=a.getCurrentProvider();if(!i)throw new W(`No AI provider configured`);let p=a.getProvider(i.provider);if(!p)throw new W(`AI provider '${i.provider}' not found`);if(typeof p.chatStream!=`function`)throw new W(`Provider must have chatStream method to support streaming execution`);u.debug(`ExecutionService calling provider.chatStream`);let h=t.getMessages(),g=Array.isArray(n.tools)?n.tools.length:void 0;u.debug(`[EXECUTION-SERVICE] config.tools:`,{length:g});let _=o.getTools(),v=Array.isArray(_)?_.length:void 0;u.debug(`[EXECUTION-SERVICE] this.tools.getTools():`,{length:v}),u.debug(`[EXECUTION-SERVICE] config.tools exists:`,{exists:!!n.tools}),u.debug(`[EXECUTION-SERVICE] config.tools.length > 0:`,{hasTools:n.tools&&n.tools.length>0});let y=r?.maxTokens??n.defaultModel.maxTokens,b=r?.temperature??n.defaultModel.temperature,x=r?.toolChoice??n.defaultModel.toolChoice,S={model:n.defaultModel.model,effort:n.defaultModel.effort??`high`,...r?.signal&&{signal:r.signal},...y!==void 0&&{maxTokens:y},...b!==void 0&&{temperature:b},...x!==void 0&&{toolChoice:x},...n.tools&&n.tools.length>0&&{tools:o.getTools()},...(()=>{let e=rr(n.responseFormat);return e?{responseFormat:e}:{}})()};ar(S.toolChoice,S.tools),u.debug(`[EXECUTION-SERVICE] Final chatOptions has tools:`,{hasTools:!!S.tools});let C=Array.isArray(S.tools)?S.tools.length:void 0;u.debug(`[EXECUTION-SERVICE] Final chatOptions.tools length:`,{length:C});let w=p.chatStream;if(!w)throw new W(`Provider does not support streaming`);let T=w.call(p,h,S),E=``,D=!1,O=[],k=-1,A;for await(let e of T){let t=Or(e);if(t&&(A=t),typeof e.content==`string`&&(D=!0),e.content&&(E+=e.content,yield{chunk:e.content,isComplete:!1}),e.role===`assistant`){let t=e;if(Array.isArray(t.toolCalls)&&t.toolCalls.length>0){for(let e of t.toolCalls)if(e.id&&e.id!==``){if(!e.type||e.type.length===0)throw Error(`[EXECUTION] Tool call "${e.id}" missing type in stream`);if(!e.function?.name||e.function.name.length===0)throw Error(`[EXECUTION] Tool call "${e.id}" missing function name in stream`);if(typeof e.function.arguments!=`string`)throw Error(`[EXECUTION] Tool call "${e.id}" missing arguments in stream`);k=O.length,O.push({id:e.id,type:e.type,function:{name:e.function.name,arguments:e.function.arguments}}),u.debug(`[TOOL-STREAM] New tool call started: ${e.id} (${e.function?.name})`)}else if(k>=0){let t=typeof e.function?.name==`string`&&e.function.name.length>0,n=typeof e.function?.arguments==`string`&&e.function.arguments.length>0;if(!t&&!n)throw Error(`[EXECUTION] Tool call fragment missing name/arguments for ${O[k].id}`);t&&(O[k].function.name+=e.function.name),n&&(O[k].function.arguments+=e.function.arguments);let r=n?e.function.arguments:e.function.name;u.debug(`[TOOL-STREAM] Adding fragment to tool ${O[k].id}: "${r}"`)}}}}if(u.debug(`[EXECUTION-SERVICE-STREAM] Stream completed, toolCalls detected:`,{count:O.length}),typeof E!=`string`)throw Error(`[EXECUTION] Streaming response content is required`);if(!D&&O.length===0)throw Error(`[EXECUTION] Provider response must have content or tool calls`);t.addAssistantMessage(E,O,{executionId:f,...A??{}}),O.length>0&&(yield*Fr(O,t,m,f,c,d,u,r?.signal)),await nr(l,`afterRun`,{input:e,response:E,...r?.metadata?{metadata:r.metadata}:{}},u),yield{chunk:``,isComplete:!0}}catch(t){throw u.error(`ExecutionService streaming execution failed`,{error:t instanceof Error?t.message:String(t),executionTime:Date.now()-p}),await nr(l,`onError`,{input:e,error:t instanceof Error?t:Error(String(t)),...r?.metadata?{metadata:r.metadata}:{}},u),t}finally{d.resetOwnerPathBases()}}var Lr=class{toolExecutionService;aiProviders;tools;conversationHistory;plugins=[];logger;eventEmitter;cacheService;constructor(e,t,n,r,i,a){if(this.toolExecutionService=new kn(t),this.aiProviders=e,this.tools=t,this.conversationHistory=n,this.plugins=[],this.logger=Nt(`ExecutionService`),!r)throw Error(`[EXECUTION] EventService is required`);this.eventEmitter=new In(r,this.logger,i),this.cacheService=a}setAskHandler(e){this.toolExecutionService.setAskHandler(e)}registerPlugin(e){let t=e.priority??0,n=this.plugins.findIndex(e=>(e.priority??0)<t);n===-1?this.plugins.push(e):this.plugins.splice(n,0,e),this.logger.debug(`Plugin registered`,{pluginName:e.name,priority:t})}removePlugin(e){let t=this.plugins.findIndex(t=>t.name===e);return t===-1?!1:(this.plugins.splice(t,1),this.logger.debug(`Plugin removed`,{pluginName:e}),!0)}getPlugin(e){return this.plugins.find(t=>t.name===e)}getPlugins(){return[...this.plugins]}async execute(e,t,n,r){let i=dr(),a=new Date,o=fr(r,`execute`),s=pr(t,n,a,i,o,r);this.eventEmitter.prepareOwnerPathBases(o),this.logger.debug(`Starting execution pipeline`,{executionId:i,conversationId:o,messageCount:t.length,hasContext:!!r});let c=or(this.aiProviders,this.tools,n);this.eventEmitter.emitExecutionStartEvent(e,n,t,c,o,i);let l=cr(this.conversationHistory,o,t,n,i);try{let t=l.getMessages().length;l.addUserMessage(e,{executionId:i});let u=l.getMessages()[t];u&&s.onExecutionEvent?.(`history_mutation`,{executionId:i,conversationId:o,mutation:`append_message`,index:t,message:u}),this.eventEmitter.emitUserMessageEvent(e,o,i),await nr(this.plugins,`beforeRun`,{input:e,...r?.metadata?{metadata:r.metadata}:{}},this.logger),sr(c);let d={toolsExecuted:[],currentRound:0,runningAssistantCount:0,lastTrackedAssistantMessage:void 0,cumulativeInputTokens:0,consecutiveUnknownToolFailureRounds:0,sameToolInputCounts:new Map};for(let e of l.getMessages())e.role===`assistant`&&(d.runningAssistantCount++,d.lastTrackedAssistantMessage=e);return await Mr(l,o,i,s,n,c,d,r?.signal,{toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,cacheService:this.cacheService}),Pr(e,l,i,a,d,o,r?.signal?.aborted??!1,r,this.plugins,this.logger,this.eventEmitter)}catch(e){return e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`))?{response:``,messages:l.getMessages(),executionId:i,duration:Date.now()-a.getTime(),toolsExecuted:[],success:!0,interrupted:!0}:(await ur(e,s,a,o,i,this.plugins,this.logger,this.eventEmitter),{response:``,messages:[],tokensUsed:0,toolsExecuted:[],duration:Date.now()-a.getTime(),executionId:i,success:!1,error:e instanceof Error?e:Error(String(e))})}finally{this.eventEmitter.resetOwnerPathBases()}}async*executeStream(e,t,n,r){yield*Ir(e,t,n,r,{aiProviders:this.aiProviders,tools:this.tools,conversationHistory:this.conversationHistory,toolExecutionService:this.toolExecutionService,plugins:this.plugins,logger:this.logger,eventEmitter:this.eventEmitter,generateExecutionId:()=>dr()})}async getStats(){return{pluginCount:this.plugins.length,pluginNames:this.plugins.map(e=>e.name),historyStats:this.conversationHistory.getStats()}}clearPlugins(){this.plugins=[],this.logger.debug(`All plugins cleared`)}};const Rr=(e,t)=>`${e}.${t}`,zr={START:Rr(Ht,Vt.START),COMPLETE:Rr(Ht,Vt.COMPLETE),ERROR:Rr(Ht,Vt.ERROR)},Br={CALL_START:Rr(Dn,En.CALL_START),CALL_COMPLETE:Rr(Dn,En.CALL_COMPLETE),CALL_ERROR:Rr(Dn,En.CALL_ERROR)},Vr={EXECUTION_START:Rr(Bt,zt.EXECUTION_START),EXECUTION_COMPLETE:Rr(Bt,zt.EXECUTION_COMPLETE),EXECUTION_ERROR:Rr(Bt,zt.EXECUTION_ERROR),CREATED:Rr(Bt,zt.CREATED)},K={EXECUTION_START:zr.START,EXECUTION_COMPLETE:zr.COMPLETE,EXECUTION_ERROR:zr.ERROR,TOOL_BEFORE_EXECUTE:`tool.beforeExecute`,TOOL_AFTER_EXECUTE:`tool.afterExecute`,TOOL_SUCCESS:`tool.success`,TOOL_ERROR:Br.CALL_ERROR,CONVERSATION_START:`conversation.start`,CONVERSATION_COMPLETE:`conversation.complete`,CONVERSATION_ERROR:`conversation.error`,AGENT_EXECUTION_START:Vr.EXECUTION_START,AGENT_EXECUTION_COMPLETE:Vr.EXECUTION_COMPLETE,AGENT_EXECUTION_ERROR:Vr.EXECUTION_ERROR,AGENT_CREATED:Vr.CREATED,AGENT_DESTROYED:`agent.destroyed`,PLUGIN_LOADED:`plugin.loaded`,PLUGIN_UNLOADED:`plugin.unloaded`,PLUGIN_ERROR:`plugin.error`,ERROR_OCCURRED:`error.occurred`,WARNING_OCCURRED:`warning.occurred`,MODULE_INITIALIZE_START:`module.initialize.start`,MODULE_INITIALIZE_COMPLETE:`module.initialize.complete`,MODULE_INITIALIZE_ERROR:`module.initialize.error`,MODULE_EXECUTION_START:`module.execution.start`,MODULE_EXECUTION_COMPLETE:`module.execution.complete`,MODULE_EXECUTION_ERROR:`module.execution.error`,MODULE_DISPOSE_START:`module.dispose.start`,MODULE_DISPOSE_COMPLETE:`module.dispose.complete`,MODULE_DISPOSE_ERROR:`module.dispose.error`,MODULE_REGISTERED:`module.registered`,MODULE_UNREGISTERED:`module.unregistered`,EXECUTION_HIERARCHY:`execution.hierarchy`,EXECUTION_REALTIME:`execution.realtime`,TOOL_REALTIME:`tool.realtime`,CUSTOM:`custom`};var Hr=class{enabled=!0;category=`custom`;priority=Rt.NORMAL;options;eventEmitter;subscribedEvents=[];eventHandlers=new Map;pluginLogger=Nt(`AbstractPlugin`);stats={calls:0,errors:0,moduleEventsReceived:0,lastActivity:void 0};async initialize(e){this.options=e,e&&`enabled`in e&&typeof e.enabled==`boolean`?this.enabled=e.enabled:this.enabled=!0,e?.category&&(this.category=e.category),e?.priority!==void 0&&(this.priority=(e.priority,e.priority))}async subscribeToModuleEvents(e){if(this.eventEmitter=e,!this.options)return;let t=[];this.options.subscribeToAllModuleEvents&&t.push(K.MODULE_INITIALIZE_START,K.MODULE_INITIALIZE_COMPLETE,K.MODULE_INITIALIZE_ERROR,K.MODULE_EXECUTION_START,K.MODULE_EXECUTION_COMPLETE,K.MODULE_EXECUTION_ERROR,K.MODULE_DISPOSE_START,K.MODULE_DISPOSE_COMPLETE,K.MODULE_DISPOSE_ERROR),this.options.moduleEvents&&t.push(...this.options.moduleEvents);for(let e of t){let t=this.eventEmitter.on(e,async t=>{try{this.stats.moduleEventsReceived++,this.stats.lastActivity=new Date,await this.onModuleEvent?.(e,t)}catch(t){this.stats.errors++;let n=t instanceof Error?t:Error(String(t));this.pluginLogger.error(`Plugin "${this.name}" failed to handle module event "${String(e)}"`,{plugin:this.name,eventType:String(e),error:n.message})}}),n=this.eventHandlers.get(e);n?n.push(t):this.eventHandlers.set(e,[t]),this.subscribedEvents.push(e)}}async unsubscribeFromModuleEvents(e){for(let[t,n]of this.eventHandlers.entries())for(let r of n)e.off(t,r);this.eventHandlers.clear(),this.subscribedEvents=[],this.eventEmitter=void 0}async dispose(){this.eventEmitter&&await this.unsubscribeFromModuleEvents(this.eventEmitter)}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}getConfig(){return{}}updateConfig(e){}getData(){return{name:this.name,version:this.version,enabled:this.enabled,category:this.category,priority:this.priority,subscribedEvents:[...this.subscribedEvents],metadata:{moduleEventsReceived:this.stats.moduleEventsReceived,totalCalls:this.stats.calls,totalErrors:this.stats.errors}}}getStatus(){return{name:this.name,version:this.version,enabled:this.enabled,initialized:!0,category:this.category,priority:this.priority,subscribedEventsCount:this.subscribedEvents.length,hasEventEmitter:!!this.eventEmitter}}getStats(){return{enabled:this.enabled,calls:this.stats.calls,errors:this.stats.errors,moduleEventsReceived:this.stats.moduleEventsReceived,...this.stats.lastActivity&&{lastActivity:this.stats.lastActivity}}}updateCallStats(){this.stats.calls++,this.stats.lastActivity=new Date}updateErrorStats(){this.stats.errors++,this.stats.lastActivity=new Date}},Ur=class{logger;eventService;constructor(e={}){this.eventService=e.eventService,this.logger=e.logger??kt}setEventService(e){this.eventService=e}getEventService(){return this.eventService}emitEvent(e,t){this.eventService&&this.eventService.emit(e,t)}async execute(e,t){return await this.executeImpl(e,t)}validate(e){return(this.schema.parameters.required||[]).every(t=>t in e)}validateParameters(e){let t=this.schema.parameters.required||[],n=[],r=e;for(let e of t)e in r||n.push(`Missing required parameter: ${e}`);return{isValid:n.length===0,errors:n}}getDescription(){return this.schema.description}getName(){return this.schema.name}},Wr=class{static validateAgentConfig(e){let t=[],n=[];return e.name||t.push(`name is required`),(!e.aiProviders||e.aiProviders.length===0)&&t.push(`aiProviders array is required and must have at least one provider`),e.defaultModel?(e.defaultModel.provider||t.push(`defaultModel.provider is required`),e.defaultModel.model||t.push(`defaultModel.model is required`)):t.push(`defaultModel is required`),e.aiProviders&&e.defaultModel?.provider&&(e.aiProviders.map(e=>e.name).includes(e.defaultModel.provider)||t.push(`defaultModel.provider "${e.defaultModel.provider}" is not found in aiProviders list`)),e.defaultModel?.temperature!==void 0&&(typeof e.defaultModel.temperature!=`number`||e.defaultModel.temperature<0||e.defaultModel.temperature>2)&&t.push(`defaultModel.temperature must be a number between 0 and 2`),e.defaultModel?.maxTokens!==void 0&&(typeof e.defaultModel.maxTokens!=`number`||e.defaultModel.maxTokens<=0)&&t.push(`defaultModel.maxTokens must be a positive number`),e.systemMessage&&e.systemMessage.length>1e3&&n.push(`systemMessage is quite long, consider keeping it concise for better performance`),e.tools&&e.tools.length>20&&n.push(`Large number of tools may impact performance, consider grouping related tools`),{isValid:t.length===0,errors:t,warnings:n}}static validateUserInput(e){let t=[],n=[];return!e||typeof e!=`string`?t.push(`Input must be a non-empty string`):(e.trim().length===0&&t.push(`Input cannot be only whitespace`),e.length>1e4&&n.push(`Very long input may be truncated by AI providers`)),{isValid:t.length===0,errors:t,warnings:n}}static validateProviderName(e){let t=[];return!e||typeof e!=`string`?t.push(`Provider name must be a non-empty string`):/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(e)||t.push(`Provider name must start with a letter and contain only letters, numbers, underscores, and hyphens`),{isValid:t.length===0,errors:t}}static validateModelName(e){let t=[];return!e||typeof e!=`string`?t.push(`Model name must be a non-empty string`):e.trim().length===0&&t.push(`Model name cannot be only whitespace`),{isValid:t.length===0,errors:t}}static validateApiKey(e){let t=[];return!e||typeof e!=`string`?(t.push(`API key must be a non-empty string`),{isValid:!1,errors:t}):(e.length<10&&t.push(`API key appears to be too short`),/\s/.test(e)&&t.push(`API key should not contain whitespace`),{isValid:t.length===0,errors:t,warnings:[]})}};const Gr=Wr.validateAgentConfig;Wr.validateUserInput,Wr.validateProviderName,Wr.validateModelName,Wr.validateApiKey;function Kr(e){return e===`darwin`?'Host OS: macOS (POSIX, BSD userland). Use BSD-flavored utilities: `sed -i ""` needs an empty backup arg, `date`/`grep`/`stat` flags differ from GNU. Prefer portable POSIX flags; avoid Linux/GNU-only options.':e===`linux`?"Host OS: Linux (POSIX, usually GNU coreutils, but distro/user setup varies). Prefer portable POSIX flags; do not assume a specific distro, and probe with `command -v` before relying on a non-standard tool.":`Host OS: ${e} (POSIX). Write portable POSIX sh/bash syntax; avoid OS-specific flags.`}function qr(e,t){let n=/(^|\/)bash$/.test(e)?`bash`:`sh`;return{command:e,kind:n,platform:t,commandArgs:e=>[`-c`,e],interactiveArgs:[],label:`${n} on ${t}`,syntaxHint:Kr(t)}}function Jr(e){return{command:e,kind:`powershell`,platform:`win32`,commandArgs:e=>[`-NoProfile`,`-Command`,e],interactiveArgs:[`-NoProfile`],label:`PowerShell (Windows)`,syntaxHint:"Write PowerShell syntax (not bash): e.g. `Get-ChildItem` not `ls -la`, `$env:VAR` not `$VAR`."}}function Yr(e=process.env,t=process.platform){let n=e.ROBOTA_SHELL?.trim();if(t===`win32`)return n!==void 0&&n.length>0?/(^|\\)cmd(\.exe)?$/i.test(n)?{command:n,kind:`cmd`,platform:t,commandArgs:e=>[`/d`,`/s`,`/c`,e],interactiveArgs:[],label:`cmd.exe (Windows)`,syntaxHint:`Write Windows cmd.exe syntax (not bash).`}:Jr(n):Jr(`powershell.exe`);if(n!==void 0&&n.length>0)return qr(n,t);let r=e.SHELL?.trim();return qr(r!==void 0&&r.length>0?r:`/bin/sh`,t)}function Xr(e,t={}){let n={},r=[],i=e._def;if(!i)throw Error(`Zod schema is missing _def; cannot convert to JSON schema.`);if(i.typeName===`ZodObject`&&i.shape){let e=typeof i.shape==`function`?i.shape():i.shape;for(let[t,i]of Object.entries(e))n[t]=Zr(i),Qr(i)&&r.push(t)}return{type:`object`,properties:n,required:r,...(t.allowAdditionalProperties||i.unknownKeys===`passthrough`)&&{additionalProperties:!0}}}function Zr(e){let t=e._def;if(!t)throw Error(`Zod type is missing _def; cannot convert to JSON schema.`);let n={};switch(t.description&&(n.description=t.description),t.typeName){case`ZodString`:return{type:`string`,...n};case`ZodNumber`:return{type:`number`,...n};case`ZodBoolean`:return{type:`boolean`,...n};case`ZodArray`:if(!t.type)throw Error(`ZodArray is missing item type; cannot convert to JSON schema.`);return{type:`array`,items:Zr(t.type),...n};case`ZodObject`:return{type:`object`,...n};case`ZodEnum`:{let e=t.values;if(!e||!Array.isArray(e))throw Error(`ZodEnum is missing enum values; cannot convert to JSON schema.`);return{type:`string`,enum:e,...n}}case`ZodOptional`:if(t.innerType)return{...Zr(t.innerType),...n};throw Error(`ZodOptional is missing innerType; cannot convert to JSON schema.`);case`ZodNullable`:if(t.innerType)return{...Zr(t.innerType),...n};throw Error(`ZodNullable is missing innerType; cannot convert to JSON schema.`);case`ZodDefault`:if(t.innerType)return{...Zr(t.innerType),...n};throw Error(`ZodDefault is missing innerType; cannot convert to JSON schema.`);case`ZodRecord`:return t.valueType?{type:`object`,additionalProperties:Zr(t.valueType),...n}:{type:`object`,additionalProperties:{type:`string`},...n};default:throw Error(`Unsupported Zod type: ${String(t.typeName)}`)}}function Qr(e){let t=e._def;if(!t)throw Error(`Zod schema is missing _def; cannot determine required fields.`);return t.typeName!==`ZodOptional`&&t.typeName!==`ZodNullable`&&t.typeName!==`ZodDefault`}function $r(e){return typeof e.safeParse==`function`&&typeof e.parse==`function`}function ei(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues;if(Array.isArray(t))return t.map(e=>{if(e&&typeof e==`object`&&`message`in e){let t=Array.isArray(e.path)?e.path.join(`.`):``,n=String(e.message);return t?`${t}: ${n}`:n}return String(e)})}return[String(e)]}function ti(e){if($r(e))return{name:`structured_output`,jsonSchema:Xr(e),validate:t=>{let n=e.safeParse(t);return n.success?{success:!0,value:n.data}:{success:!1,issues:ei(n.error)}}};let{jsonSchema:t,name:n}=e;return{name:n??`structured_output`,jsonSchema:t,validate:e=>{let n=ni(t,e,`$`);return n.length===0?{success:!0,value:e}:{success:!1,issues:n}}}}function ni(e,t,n){let r=[],i=e.type;switch(i){case`object`:{if(typeof t!=`object`||!t||Array.isArray(t))return[`${n}: expected object, got ${ri(t)}`];let i=t,a=`required`in e?e.required??[]:[];for(let e of a)e in i||r.push(`${n}.${e}: required property missing`);let o=e.properties??{};for(let[e,t]of Object.entries(o))e in i&&r.push(...ni(t,i[e],`${n}.${e}`));let s=e.additionalProperties;if(s===void 0||s===!1)for(let e of Object.keys(i))e in o||r.push(`${n}.${e}: unexpected additional property`);else if(typeof s==`object`)for(let[e,t]of Object.entries(i))e in o||r.push(...ni(s,t,`${n}.${e}`));return r}case`array`:{if(!Array.isArray(t))return[`${n}: expected array, got ${ri(t)}`];let i=`items`in e?e.items:void 0;return i&&t.forEach((e,t)=>{r.push(...ni(i,e,`${n}[${t}]`))}),r}case`string`:return typeof t==`string`?(`enum`in e&&e.enum&&!e.enum.some(e=>e===t)&&r.push(`${n}: value ${JSON.stringify(t)} is not one of the allowed enum values`),`pattern`in e&&e.pattern&&!new RegExp(e.pattern).test(t)&&r.push(`${n}: value does not match pattern ${e.pattern}`),r):[`${n}: expected string, got ${ri(t)}`];case`number`:case`integer`:return typeof t!=`number`||Number.isNaN(t)?[`${n}: expected number, got ${ri(t)}`]:(i===`integer`&&!Number.isInteger(t)&&r.push(`${n}: expected integer, got non-integer number`),`minimum`in e&&e.minimum!==void 0&&t<e.minimum&&r.push(`${n}: value ${t} is below minimum ${e.minimum}`),`maximum`in e&&e.maximum!==void 0&&t>e.maximum&&r.push(`${n}: value ${t} is above maximum ${e.maximum}`),`enum`in e&&e.enum&&!e.enum.some(e=>e===t)&&r.push(`${n}: value ${t} is not one of the allowed enum values`),r);case`boolean`:return typeof t==`boolean`?r:[`${n}: expected boolean, got ${ri(t)}`];case`null`:return t===null?r:[`${n}: expected null, got ${ri(t)}`];default:return[`${n}: unsupported schema type ${String(i)}`]}}function ri(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function ii(e){let t=e.trim(),n=/^```(?:json)?\s*\n([\s\S]*?)\n?```$/.exec(t),r=n?n[1]:t;try{return{success:!0,value:JSON.parse(r)}}catch(e){return{success:!1,issue:`response is not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}function ai(e,t){let n={id:l(),role:`user`,content:e,state:`complete`,timestamp:new Date};return t?.name&&(n.name=t.name),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function oi(e,t){let n={id:l(),role:`assistant`,content:e,state:t?.state??`complete`,timestamp:new Date};return t?.toolCalls&&(n.toolCalls=t.toolCalls),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function q(e,t){let n={id:l(),role:`system`,content:e,state:`complete`,timestamp:new Date};return t?.name&&(n.name=t.name),t?.metadata&&(n.metadata=t.metadata),t?.parts&&(n.parts=t.parts),n}function si(e,t){let n={id:l(),role:`tool`,content:e,toolCallId:t.toolCallId,state:`complete`,timestamp:new Date};return t.name&&(n.name=t.name),t.metadata&&(n.metadata=t.metadata),t.parts&&(n.parts=t.parts),n}var ci=class{maxMessages;entries=[];constructor(e){this.maxMessages=e?.maxMessages||0}addMessage(e){this.entries.push(H(e)),this.applyMessageLimit()}addEntry(e){this.entries.push(e)}getHistory(){return[...this.entries]}addUserMessage(e,t,n){this.addMessage(ai(e,{...t&&{metadata:t},...n&&{parts:n}}))}addAssistantMessage(e,t,n,r){this.addMessage(oi(e,{...t&&{toolCalls:t},...n&&{metadata:n},...r&&{parts:r}}))}addSystemMessage(e,t,n){this.addMessage(q(e,{...t&&{metadata:t},...n&&{parts:n}}))}setSystemPrompt(e,t,n){let r=e=>wt(e)&&Dt(Tt(e)),i=this.entries.filter(e=>!r(e)),a=H(q(e,{...t&&{metadata:t},...n&&{parts:n}}));i.unshift(a),this.entries=i}addToolMessageWithId(e,t,n,r,i){this.addMessage(si(e,{toolCallId:t,name:n,...r&&{metadata:r},...i&&{parts:i}}))}getMessages(){return this.entries.filter(wt).map(Tt)}getMessagesByRole(e){return this.getMessages().filter(t=>t.role===e)}getRecentMessages(e){return this.getMessages().slice(-e)}getMessageCount(){return this.entries.filter(wt).length}clear(){this.entries=[]}applyMessageLimit(){if(this.maxMessages<=0)return;let e=this.entries.filter(wt);if(e.length<=this.maxMessages)return;let t=e.map(Tt),n=t.filter(Dt),r=t.filter(e=>!Dt(e)),i=Math.max(0,this.maxMessages-n.length),a=[...n,...r.slice(-i)],o=new Set(a.map(e=>e.id));this.entries=this.entries.filter(e=>!wt(e)||o.has(e.id))}},li=class{history;pendingAssistant=null;constructor(e=0){this.history=new ci({maxMessages:e})}addMessage(e){this.history.addMessage(e)}addUserMessage(e,t,n){this.history.addUserMessage(e,t,n)}addAssistantMessage(e,t,n,r){this.history.addAssistantMessage(e,t,n,r)}addSystemMessage(e,t,n){this.history.addSystemMessage(e,t,n)}setSystemPrompt(e,t,n){this.history.setSystemPrompt(e,t,n)}addToolMessage(e,t,n,r,i){this.history.addToolMessageWithId(e,t,n||`unknown`,r,i)}addToolMessageWithId(e,t,n,r,i){this.history.addToolMessageWithId(e,t,n,r,i)}addEntry(e){this.history.addEntry(e)}getHistory(){return this.history.getHistory()}getMessages(){return this.history.getMessages()}getMessagesByRole(e){return this.history.getMessagesByRole(e)}getRecentMessages(e){return this.history.getRecentMessages(e)}getMessageCount(){return this.history.getMessageCount()}beginAssistant(){this.pendingAssistant||={id:l(),content:``,toolCalls:[]}}appendStreaming(e){this.pendingAssistant||={id:l(),content:``,toolCalls:[]},this.pendingAssistant.content+=e}appendToolCall(e){this.pendingAssistant||={id:l(),content:``,toolCalls:[]},this.pendingAssistant.toolCalls.some(t=>t.id===e.id)||this.pendingAssistant.toolCalls.push(e)}commitAssistant(e,t){if(!this.pendingAssistant)return;let n=this.pendingAssistant,r=n.toolCalls.length>0,i=n.content,a={id:n.id,role:`assistant`,content:i,state:e,timestamp:new Date,...r&&{toolCalls:n.toolCalls},...t&&{metadata:t}};this.history.addMessage(a),this.pendingAssistant=null}discardPending(){this.pendingAssistant=null}hasPendingAssistant(){return this.pendingAssistant!==null}getPendingContent(){return this.pendingAssistant?.content??``}getMessagesForAPI(){return this.history.getMessages().map(e=>{let t={role:e.role,content:e.content};return Et(e)&&e.state===`interrupted`&&(t.content=(t.content||``)+`
5
5
 
6
6
  [This response was interrupted by the user]`),Et(e)&&e.toolCalls&&(t.tool_calls=e.toolCalls),Ot(e)&&(t.tool_call_id=e.toolCallId),t})}clear(){this.history.clear()}},ui=class{conversations=new Map;logger;maxMessagesPerConversation;maxConversations;constructor(e={}){this.maxMessagesPerConversation=e.maxMessagesPerConversation||0,this.maxConversations=e.maxConversations||50,this.logger=Nt(`ConversationHistory`)}getConversationStore(e){return this.conversations.has(e)||(this.conversations.size>=this.maxConversations&&this.cleanupOldConversations(),this.conversations.set(e,new li(this.maxMessagesPerConversation))),this.conversations.get(e)}hasConversation(e){return this.conversations.has(e)}removeConversation(e){let t=this.conversations.delete(e);return t&&this.logger.debug(`Removed conversation`,{conversationId:e}),t}clearAll(){let e=this.conversations.size;this.conversations.clear(),this.logger.debug(`Cleared all conversations`,{removedCount:e})}getStats(){let e=Array.from(this.conversations.keys()),t=Array.from(this.conversations.values()).reduce((e,t)=>e+t.getMessageCount(),0);return{totalConversations:this.conversations.size,conversationIds:e,totalMessages:t}}cleanupOldConversations(){if(this.conversations.size===0)return;let e=this.conversations.keys().next().value;e&&this.conversations.delete(e)}};const di=`$ENV:`;function fi(e){return e.startsWith(di)}function pi(e){return`${di}${e}`}function mi(e){if(!fi(e))return e;let t=e.slice(5).trim();if(t.length!==0)return process.env[t]}function hi(e){return e===void 0||e.length===0?!1:mi(e)!==void 0}var gi=class{totalEmitted=0;totalErrors=0;incrementEmitted(){this.totalEmitted+=1}incrementErrors(){this.totalErrors+=1}getSnapshot(){return{totalEmitted:this.totalEmitted,totalErrors:this.totalErrors}}};function _i(e,t){if(e.maxListeners!==void 0&&e.maxListeners<0)throw new dn(`Invalid maxListeners option: ${e.maxListeners}. Must be a non-negative number.`,t,{maxListeners:e.maxListeners});if(e.buffer!==void 0&&e.buffer.maxSize!==void 0&&e.buffer.maxSize<0)throw new dn(`Invalid buffer.maxSize option: ${e.buffer.maxSize}. Must be a non-negative number.`,t,{bufferMaxSize:e.buffer.maxSize});if(e.buffer!==void 0&&e.buffer.flushInterval!==void 0&&e.buffer.flushInterval<0)throw new dn(`Invalid buffer.flushInterval option: ${e.buffer.flushInterval}. Must be a non-negative number.`,t,{bufferFlushInterval:e.buffer.flushInterval})}async function vi(e,t,n,r,i){try{await e.listener(t)}catch(a){if(n.incrementErrors(),!r)throw a instanceof Error?a:Error(String(a));i.error(`Event handler error`,{eventType:t.type,handlerId:e.id,error:a instanceof Error?a.message:String(a)})}}async function yi(e,t,n,r,i){let a=t.get(e.type);if(!a||a.length===0)return;let o=a.filter(t=>!t.filter||t.filter(e));if(o.length!==0){for(let t of o.filter(e=>e.once))r(e.type,t.id);if(n){await Promise.all(o.map(t=>i(t,e)));return}for(let t of o)await i(t,e)}}function bi(e){let t={},n=0;for(let[r,i]of e)t[r]=i.length,n+=i.length;return{listenerCounts:t,totalListeners:n}}function xi(e,t,n,r){let{listenerCounts:i,totalListeners:a}=bi(t),o=r.getSnapshot();return{enabled:e.enabled,calls:e.calls,errors:e.errors,eventTypes:Array.from(t.keys()),listenerCounts:i,totalListeners:a,bufferedEvents:n,totalEmitted:o.totalEmitted,totalErrors:o.totalErrors}}function Si(e,t,n,r,i,a,o){e.has(t)||e.set(t,[]);let s=e.get(t);if(s.length>=a)throw new dn(`Maximum listeners (${a}) exceeded for event type: ${t}`,o,{eventType:t,currentListeners:s.length});s.push({id:n,listener:r,once:i?.once??!1,...i?.filter&&{filter:i.filter}})}function Ci(e,t,n){let r=e.get(t);if(!r)return!1;let i=typeof n==`string`?r.findIndex(e=>e.id===n):r.findIndex(e=>e.listener===n);return i===-1?!1:(r.splice(i,1),!0)}function wi(e,t,n){let r=t.result!==null&&t.result!==void 0;return{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{toolName:t.name||``,toolId:t.id||``,toolResult:r?String(t.result):void 0,duration:n,success:r}}}var Ti=class extends Hr{name=`EventEmitterPlugin`;version=`1.0.0`;pluginOptions;logger;handlers=new Map;eventBuffer=[];nextHandlerId=1;bufferTimer;metrics;constructor(e={}){super(),this.logger=Nt(`EventEmitterPlugin`),this.metrics=e.metrics??new gi,_i(e,this.name),this.pluginOptions={enabled:e.enabled??!0,events:e.events??[K.AGENT_EXECUTION_START,K.AGENT_EXECUTION_COMPLETE,K.AGENT_EXECUTION_ERROR,K.TOOL_BEFORE_EXECUTE,K.TOOL_AFTER_EXECUTE,K.TOOL_SUCCESS,K.TOOL_ERROR],maxListeners:e.maxListeners??100,async:e.async??!0,catchErrors:e.catchErrors??!0,filters:e.filters??{},buffer:e.buffer??{enabled:!1,maxSize:1e3,flushInterval:5e3},category:e.category??`event_processing`,priority:e.priority??Rt.HIGH,moduleEvents:e.moduleEvents??[],subscribeToAllModuleEvents:e.subscribeToAllModuleEvents??!1},this.pluginOptions.buffer.enabled&&(this.bufferTimer=setInterval(()=>{this.flushBuffer().catch(e=>{this.logger.error(`Buffered flush failed`,{error:e instanceof Error?e.message:String(e)})})},this.pluginOptions.buffer.flushInterval))}async beforeExecution(e){await this.emit(K.AGENT_EXECUTION_START,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{messageCount:e.messages?.length||0,...e.config&&{config:e.config}}})}async afterExecution(e,t){await this.emit(K.AGENT_EXECUTION_COMPLETE,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{duration:t?.duration,tokensUsed:t?.tokensUsed,toolsExecuted:t?.toolsExecuted}})}async beforeConversation(e){await this.emit(K.CONVERSATION_START,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{messages:e.messages?.map(e=>({role:e.role,content:e.content||``,timestamp:e.timestamp?e.timestamp.toISOString():new Date().toISOString()})),config:e.config}})}async afterConversation(e,t){await this.emit(K.CONVERSATION_COMPLETE,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{response:t.content||t.response,tokensUsed:t.usage?.totalTokens||t.tokensUsed,toolCalls:t.toolCalls?.map(e=>({id:e.id||``,name:e.name||``,arguments:JSON.stringify(e.arguments||{}),result:String(e.result||``)}))}})}async beforeToolExecution(e,t){t&&await this.emit(K.TOOL_BEFORE_EXECUTE,{executionId:e.executionId,sessionId:e.sessionId,userId:e.userId,data:{toolName:t.toolName,toolId:t.executionId,arguments:JSON.stringify(t.parameters??{})}})}async afterToolExecution(e,t){if(!(!t.toolCalls||t.toolCalls.length===0))for(let n of t.toolCalls){let r=n.result===null?K.TOOL_ERROR:K.TOOL_SUCCESS,i=wi(e,n,t.duration);await this.emit(r,i),await this.emit(K.TOOL_AFTER_EXECUTE,{...i,data:{...i.data,toolResult:String(n.result||``)}})}}async onError(e,t){await this.emit(K.AGENT_EXECUTION_ERROR,{executionId:t?.executionId,sessionId:t?.sessionId,userId:t?.userId,error:e instanceof Error?e:Error(String(e)),data:{action:t?.action,tool:t?.tool,attempt:t?.attempt}})}on(e,t,n){let r=`handler_${this.nextHandlerId++}`;return Si(this.handlers,e,r,t,n,this.pluginOptions.maxListeners,this.name),r}once(e,t,n){return this.on(e,t,{once:!0,...n&&{filter:n}})}off(e,t){return Ci(this.handlers,e,t)}async emit(e,t={}){if(!this.pluginOptions.events.includes(e))return;let n={type:e,timestamp:new Date,...t},r=this.pluginOptions.filters[e];if(!(r&&!r(n))){if(this.metrics.incrementEmitted(),this.pluginOptions.buffer.enabled){this.eventBuffer.push(n),this.eventBuffer.length>=this.pluginOptions.buffer.maxSize&&await this.flushBuffer();return}await this.processEvent(n)}}async processEvent(e){await yi(e,this.handlers,this.pluginOptions.async,(e,t)=>this.off(e,t),(e,t)=>vi(e,t,this.metrics,this.pluginOptions.catchErrors,this.logger))}async flushBuffer(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];for(let t of e)await this.processEvent(t)}getStats(){return xi(super.getStats(),this.handlers,this.eventBuffer.length,this.metrics)}clearAllListeners(){this.handlers.clear()}async dispose(){this.bufferTimer&&clearInterval(this.bufferTimer),await this.flushBuffer(),this.clearAllListeners(),await super.dispose()}},Ei=class extends vt{moduleManager;pluginManager;addPlugin(e){this.pluginManager.addPlugin(e)}removePlugin(e){return this.pluginManager.removePlugin(e)}getPlugin(e){return this.pluginManager.getPlugin(e)}getPlugins(){return this.pluginManager.getPlugins()}getPluginNames(){return this.pluginManager.getPluginNames()}async registerModule(e,t){return this.moduleManager.registerModule(e,t)}async unregisterModule(e){return this.moduleManager.unregisterModule(e)}getModule(e){return this.moduleManager.getModule(e)}getModulesByType(e){return this.moduleManager.getModulesByType(e)}getModules(){return this.moduleManager.getModules()}getModuleNames(){return this.moduleManager.getModuleNames()}hasModule(e){return this.moduleManager.hasModule(e)}async executeModule(e,t){return this.moduleManager.executeModule(e,t)}getModuleStats(e){return this.moduleManager.getModuleStats(e)}};function Di(e){if(!e.name)throw new W(`Agent name is required`,{component:`Robota`});if(!e.aiProviders||e.aiProviders.length===0)throw new W(`At least one AI provider is required`,{component:`Robota`});if(!e.defaultModel)throw new W(`Default model configuration is required`,{component:`Robota`});if(!e.defaultModel.provider||!e.defaultModel.model)throw new W(`Default model must specify both provider and model`,{component:`Robota`});let t=e.aiProviders.map(e=>e.name),n=t.filter((e,n)=>t.indexOf(e)!==n);if(n.length>0)throw new W(`Duplicate AI provider names: ${n.join(`, `)}`,{component:`Robota`,duplicates:n});if(!t.includes(e.defaultModel.provider))throw new W(`Default provider '${e.defaultModel.provider}' not found in AI providers list. Available: ${t.join(`, `)}`,{component:`Robota`,defaultProvider:e.defaultModel.provider,availableProviders:t})}var Oi=class{logger;getAIProviders;getTools;getEventService;isReady;ensureReady;getConfig;setConfig;getConfigVersion;bumpConfigVersion;getConfigUpdatedAt;setConfigUpdatedAt;emitAgentEvent;constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){this.logger=e,this.getAIProviders=t,this.getTools=n,this.getEventService=r,this.isReady=i,this.ensureReady=a,this.getConfig=o,this.setConfig=s,this.getConfigVersion=c,this.bumpConfigVersion=l,this.getConfigUpdatedAt=u,this.setConfigUpdatedAt=d,this.emitAgentEvent=f}async updateTools(e){if(await this.ensureReady(),!Array.isArray(e))throw new W(`updateTools: next must be an array of tools`);this.getTools().getRegistry().clear();let t=[],n=this.getEventService();for(let r of e){n&&r.setEventService(n),this.getTools().addTool(r.schema,async(e,t)=>{if(!t)throw Error(`[ROBOTA] Missing ToolExecutionContext for tool execution`);return(await r.execute(e,t)).data});let e=r.schema.name;typeof e==`string`&&e.length>0&&t.push(e)}let r=this.getConfig();r.tools=e,this.setConfig(r);let i=this.bumpConfigVersion();return this.setConfigUpdatedAt(Date.now()),this.emitAgentEvent(zt.CONFIG_UPDATED,{parameters:{tools:t,systemMessage:r.systemMessage,provider:r.defaultModel.provider,model:r.defaultModel.model,temperature:r.defaultModel.temperature,maxTokens:r.defaultModel.maxTokens},metadata:{version:i}}),{version:i}}async updateConfiguration(e){if(e.tools)return this.updateTools(e.tools);throw new W(`updateConfiguration: only tools patch is supported at this time`)}async getConfiguration(){await this.ensureReady();let e=this.getTools().getTools().map(e=>({name:e.name,parameters:(()=>{let t=e.parameters?.properties;return t&&typeof t==`object`?Object.keys(t):void 0})()}));return{version:this.getConfigVersion(),tools:e,updatedAt:this.getConfigUpdatedAt(),metadata:void 0}}setModel(e){if(!e.provider||!e.model)throw new W(`Both provider and model are required`,{component:`Robota`});if(!this.isReady())throw new W(`Agent must be fully initialized before changing model configuration`,{component:`Robota`});let t=this.getAIProviders(),n=t.getProviderNames();if(!n.includes(e.provider))throw new W(`AI Provider '${e.provider}' not found. Available: ${n.join(`, `)}`,{component:`Robota`,provider:e.provider,availableProviders:n});t.setCurrentProvider(e.provider,e.model);let r=this.getConfig();this.setConfig({...r,defaultModel:{...r.defaultModel,provider:e.provider,model:e.model,...e.temperature!==void 0&&{temperature:e.temperature},...e.maxTokens!==void 0&&{maxTokens:e.maxTokens},...e.topP!==void 0&&{topP:e.topP},...e.effort!==void 0&&{effort:e.effort}}}),this.logger.debug(`Model configuration updated`,e)}getModel(){if(!this.isReady())throw new W(`Agent must be fully initialized before getting model configuration`,{component:`Robota`});let e=this.getAIProviders().getCurrentProvider();if(!e)throw new W(`No provider is currently set`,{component:`Robota`});let t=this.getConfig();return{provider:e.provider,model:e.model,...t.defaultModel.temperature!==void 0&&{temperature:t.defaultModel.temperature},...t.defaultModel.maxTokens!==void 0&&{maxTokens:t.defaultModel.maxTokens},...t.defaultModel.topP!==void 0&&{topP:t.defaultModel.topP}}}setSystemMessage(e){let t=this.getConfig();t.systemMessage=e,this.setConfig(t),this.setConfigUpdatedAt(Date.now())}getSystemMessage(){return this.getConfig().systemMessage}registerTool(e,t){if(t.hasTool(e.schema.name))throw Error(`[STRICT-POLICY][EMITTER-CONTRACT] Duplicate tool registration attempted: ${e.schema.name}. Tool registration flow must provide a single authoritative registration path.`);t.addTool(e.schema,async(t,n)=>{if(!n)throw Error(`[ROBOTA] Missing ToolExecutionContext for tool execution`);return(await e.execute(t,n)).data}),this.logger.debug(`Tool registered`,{toolName:e.schema.name})}},ki=class{agentName;moduleRegistry;logger;isReady;ensureReady;constructor(e,t,n,r,i){this.agentName=e,this.moduleRegistry=t,this.logger=n,this.isReady=r,this.ensureReady=i}async registerModule(e,t){await this.ensureReady(),await this.moduleRegistry.registerModule(e,{autoInitialize:t?.autoInitialize??!0,validateDependencies:t?.validateDependencies??!0}),this.logger.info(`Module registered`,{moduleName:e.name,moduleType:e.getModuleType().type})}async unregisterModule(e){if(!this.isReady())return!1;let t=await this.moduleRegistry.unregisterModule(e);return t&&this.logger.info(`Module unregistered`,{moduleName:e}),t}getModule(e){if(this.isReady())return this.moduleRegistry.getModule(e)}getModulesByType(e){return this.isReady()?this.moduleRegistry.getModulesByType(e):[]}getModules(){return this.isReady()?this.moduleRegistry.getAllModules():[]}getModuleNames(){return this.isReady()?this.moduleRegistry.getModuleNames():[]}hasModule(e){return this.isReady()?this.moduleRegistry.hasModule(e):!1}async executeModule(e,t){await this.ensureReady();let n={agentName:this.agentName,...t.executionId&&{executionId:t.executionId},...t.sessionId&&{sessionId:t.sessionId},...t.userId&&{userId:t.userId},...t.metadata&&{metadata:t.metadata}};return await this.moduleRegistry.executeModule(e,n)}getModuleStats(e){if(this.isReady())return this.moduleRegistry.getModuleStats(e)}},Ai=class{logger;isReady;getExecutionService;constructor(e,t,n){this.logger=e,this.isReady=t,this.getExecutionService=n}addPlugin(e){let t=this.getExecutionService();if(!this.isReady()||!t)throw new W(`Cannot add plugin before agent is fully initialized. Await an operation like run() first, or pass plugins via the constructor config.`,{pluginName:e.name});t.registerPlugin(e),this.logger.debug(`Plugin added`,{pluginName:e.name})}removePlugin(e){let t=this.getExecutionService();if(!t)return!1;let n=t.removePlugin(e);return n&&this.logger.debug(`Plugin removed`,{pluginName:e}),n}getPlugin(e){let t=this.getExecutionService();if(t)return t.getPlugin(e)}getPlugins(){let e=this.getExecutionService();return e?e.getPlugins():[]}getPluginNames(){let e=this.getExecutionService();return!this.isReady()||!e?[]:e.getPlugins().map(e=>e.name)}};function ji(e){return{moduleManager:new ki(e.getName(),e.getModuleRegistry(),e.getLogger(),e.getIsFullyInitialized,e.ensureFullyInitialized),pluginManager:new Ai(e.getLogger(),e.getIsFullyInitialized,e.getExecutionService),configManager:new Oi(e.getLogger(),e.getAiProviders,e.getTools,e.getEventService,e.getIsFullyInitialized,e.ensureFullyInitialized,e.getConfig,t=>e.setConfig(t),e.getConfigVersion,e.incrementConfigVersion,e.getConfigUpdatedAt,t=>e.setConfigUpdatedAt(t),(t,n)=>e.emitAgentEvent(t,n))}}function Mi(e,t){let n=Array.isArray(e.tools)?e.tools.map(e=>{let t=e?.schema?.name;if(typeof t==`string`&&t.length>0)return t;let n=e?.name;return typeof n==`string`&&n.length>0?n:``}).filter(e=>typeof e==`string`&&e.length>0):[];t(zt.CREATED,{parameters:{tools:n,systemMessage:e.systemMessage,provider:e.defaultModel.provider,model:e.defaultModel.model,temperature:e.defaultModel.temperature,maxTokens:e.defaultModel.maxTokens}})}function Ni(e,t,n,r,i){Jt(e)||e.emit(r,{timestamp:new Date,...i},{ownerType:Bt,ownerId:t,ownerPath:Fi(t,n)})}function Pi(){return new Ti({enabled:!0,events:[K.MODULE_INITIALIZE_START,K.MODULE_INITIALIZE_COMPLETE,K.MODULE_INITIALIZE_ERROR,K.MODULE_EXECUTION_START,K.MODULE_EXECUTION_COMPLETE,K.MODULE_EXECUTION_ERROR,K.MODULE_DISPOSE_START,K.MODULE_DISPOSE_COMPLETE,K.MODULE_DISPOSE_ERROR]})}function Fi(e,t){return[...t?.ownerPath?.length?t.ownerPath.map(e=>({...e})):[],{type:`agent`,id:e}]}function Ii(e,t){return{conversationId:e.conversationId,...t.sessionId&&{sessionId:t.sessionId},...t.userId&&{userId:t.userId},...t.metadata&&{metadata:t.metadata},...t.signal&&{signal:t.signal},...t.onTextDelta&&{onTextDelta:t.onTextDelta},...t.onExecutionEvent&&{onExecutionEvent:t.onExecutionEvent},...t.maxExecutionRounds!==void 0&&{maxExecutionRounds:t.maxExecutionRounds},...t.maxSameToolInputs!==void 0&&{maxSameToolInputs:t.maxSameToolInputs},...t.allowToolOnlyCompletion!==void 0&&{allowToolOnlyCompletion:t.allowToolOnlyCompletion},...t.maxTokens!==void 0&&{maxTokens:t.maxTokens},...t.temperature!==void 0&&{temperature:t.temperature},...t.toolChoice!==void 0&&{toolChoice:t.toolChoice}}}async function Li(e,t,n={},r){try{e.emitAgentEvent(zt.EXECUTION_START,{}),e.logger.debug(`Starting Robota execution`,{inputLength:t.length,conversationId:e.conversationId,sessionId:n.sessionId||`none`,userId:n.userId||`none`,hasMetadata:!!n.metadata});let i=e.getHistory(),a={...e.config,...r},o=await e.getExecutionService().execute(t,i,a,Ii(e,n));if(e.logger.debug(`Robota execution completed`,{success:o.success,duration:o.duration,tokensUsed:o.tokensUsed,toolsExecuted:o.toolsExecuted,interrupted:o.interrupted}),o.interrupted)return e.emitAgentEvent(zt.EXECUTION_COMPLETE,{}),o.response;if(!o.success)throw o.error??Error(`[STRICT-POLICY] Failed execution result missing error field — every success:false result must carry error`);return e.emitAgentEvent(zt.EXECUTION_COMPLETE,{}),o.response}catch(t){throw e.logger.error(`Robota execution failed`,{error:t instanceof Error?t.message:String(t),conversationId:e.conversationId}),e.emitAgentEvent(zt.EXECUTION_ERROR,{error:t instanceof Error?t.message:String(t)}),t}}async function*Ri(e,t,n={},r){try{e.emitAgentEvent(zt.EXECUTION_START,{}),e.logger.debug(`Starting Robota streaming execution`,{inputLength:t.length,conversationId:e.conversationId,sessionId:n.sessionId||`none`,userId:n.userId||`none`,hasMetadata:!!n.metadata});let i=e.getHistory(),a={...e.config,...r},o=e.getExecutionService().executeStream(t,i,a,Ii(e,n));for await(let e of o)yield e.chunk}catch(t){throw e.logger.error(`Robota streaming execution failed`,{error:t instanceof Error?t.message:String(t),conversationId:e.conversationId}),e.emitAgentEvent(zt.EXECUTION_ERROR,{error:t instanceof Error?t.message:String(t)}),t}finally{e.emitAgentEvent(zt.EXECUTION_COMPLETE,{})}}function zi(e){return{responseFormat:{type:`json_schema`,schema:e.jsonSchema,name:e.name}}}function Bi(e,t){return[`Your previous response did not match the required JSON schema.`,`Validation issues:`,...t.map(e=>`- ${e}`),``,`Respond with ONLY a JSON object (no prose, no code fences) matching this JSON schema:`,JSON.stringify(e.jsonSchema)].join(`
7
7
  `)}async function Vi(e,t,n,r){let i=(n.outputRetries??2)+1,a=zi(r),o=t,s=[];for(let t=1;t<=i;t++){let c=Ui(r,await Li(e,o,n,a));if(c.success)return c.value;s=c.issues,e.logger.debug(`Structured output validation failed`,{attempt:t,maxAttempts:i,issues:s}),t<i&&(o=Bi(r,s))}throw new an(`response failed schema validation after ${i} attempt(s)`,s,i)}async function*Hi(e,t,n,r){let i=(n.outputRetries??2)+1,a=zi(r),o=t,s=[];for(let t=1;t<=i;t++){let c=``;for await(let t of Ri(e,o,n,a))c+=t,yield t;let l=Ui(r,c);if(l.success)return l.value;s=l.issues,e.logger.debug(`Structured output validation failed (stream)`,{attempt:t,maxAttempts:i,issues:s}),t<i&&(o=Bi(r,s))}throw new an(`response failed schema validation after ${i} attempt(s)`,s,i)}function Ui(e,t){let n=ii(t);if(!n.success)return{success:!1,issues:[n.issue]};let r=e.validate(n.value);return r.success?{success:!0,value:r.value}:{success:!1,issues:r.issues}}function Wi(e,t){return e.getConversationStore(t).getMessages().map(e=>({id:e.id,role:e.role,content:e.content,state:e.state,timestamp:e.timestamp,metadata:e.metadata,...e.role===`assistant`&&`toolCalls`in e?{toolCalls:e.toolCalls}:{},...e.role===`tool`&&`toolCallId`in e?{toolCallId:e.toolCallId}:{},...e.role===`tool`&&`name`in e?{name:e.name}:{}}))}function Gi(e,t){return e.getConversationStore(t).getHistory()}function Ki(e,t,n){e.getConversationStore(t).addEntry(n)}function qi(e,t){e.getConversationStore(t).clear()}function Ji(e,t,n,r,i){let a=e.getConversationStore(t);n===`tool`&&i?.toolCallId?a.addToolMessageWithId(r,i.toolCallId,i.name??`unknown`):n===`assistant`?a.addAssistantMessage(r,[]):n===`system`?a.addSystemMessage(r):a.addUserMessage(r)}function Yi(e,t,n){e.getConversationStore(t).addMessage(n)}var Xi=class{build(e,t,n,r){let i=e.map(e=>({role:e.role,content:e.content})),a=JSON.stringify({messages:i,model:t,provider:n,temperature:r?.temperature,maxTokens:r?.maxTokens});return{hash:this.sha256(a),model:t,provider:n}}computeIntegrityHash(e){return this.sha256(e)}sha256(e){let t=new u(`SHA-256`,`TEXT`);return t.update(e),t.getHash(`HEX`)}},Zi=class{cache=new Map;accessOrder=[];maxEntries;ttlMs;keyBuilder=new Xi;hits=0;misses=0;constructor(e){this.maxEntries=e.maxEntries,this.ttlMs=e.ttlMs}get(e){let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>this.ttlMs){this.cache.delete(e),this.removeFromAccessOrder(e),this.misses++;return}let n=this.keyBuilder.computeIntegrityHash(t.response);if(t.integrityHash!==n)throw this.cache.delete(e),this.removeFromAccessOrder(e),new fn(`Integrity check failed for cache entry ${e}`,{hash:e,expected:n,actual:t.integrityHash});return this.touchAccessOrder(e),this.hits++,t}set(e){let t=e.key.hash;!this.cache.has(t)&&this.cache.size>=this.maxEntries&&this.evictLRU(),this.cache.set(t,e),this.touchAccessOrder(t)}delete(e){return this.cache.has(e)?(this.cache.delete(e),this.removeFromAccessOrder(e),!0):!1}clear(){this.cache.clear(),this.accessOrder.length=0,this.hits=0,this.misses=0}getStats(){let e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,entries:this.cache.size,hitRate:e===0?0:this.hits/e}}touchAccessOrder(e){this.removeFromAccessOrder(e),this.accessOrder.push(e)}removeFromAccessOrder(e){let t=this.accessOrder.indexOf(e);t!==-1&&this.accessOrder.splice(t,1)}evictLRU(){let e=this.accessOrder.shift();e&&this.cache.delete(e)}},Qi=class{storage;keyBuilder;constructor(e,t){this.storage=e,this.keyBuilder=t}lookup(e,t,n,r){let i=this.keyBuilder.build(e,t,n,r),a=this.storage.get(i.hash);return a?a.response:void 0}store(e,t,n,r,i){let a=this.keyBuilder.build(e,t,n,i);this.storage.set({key:a,response:r,timestamp:Date.now(),integrityHash:this.keyBuilder.computeIntegrityHash(r)})}getStats(){return this.storage.getStats()}};async function $i(e){let{config:t,aiProviders:n,tools:r,agentFactory:i,conversationHistory:a,moduleRegistry:o,eventEmitter:s,eventService:c,logger:l}=e;if(l.debug(`Starting Robota initialization with independent managers`),await Promise.all([n.initialize(),r.initialize(),i.initialize()]),t.aiProviders)for(let e of t.aiProviders)n.addProvider(e.name,e);if(t.defaultModel&&n.setCurrentProvider(t.defaultModel.provider,t.defaultModel.model),t.modules){for(let e of t.modules)await o.registerModule(e,{autoInitialize:!0,validateDependencies:!0});l.debug(`Modules registered and initialized`,{moduleCount:t.modules.length,moduleNames:t.modules.map(e=>e.name)})}if(t.tools)for(let e of t.tools)e instanceof Ur&&c&&e.setEventService(c),r.addTool(e.schema,async(t,n)=>{if(!n)throw Error(`[ROBOTA] Missing ToolExecutionContext for tool execution`);return(await e.execute(t,n)).data}),l.debug(`Tool registered during initialization`,{toolName:e.schema.name});let u;t.cache?.enabled&&(u=new Qi(new Zi({maxEntries:t.cache.maxEntries,ttlMs:t.cache.ttlMs}),new Xi));let d=new Lr(n,r,a,c,t.executionContext,u);if(t.ask&&d.setAskHandler(t.ask),t.plugins)for(let e of t.plugins)d.registerPlugin(e),e.subscribeToModuleEvents&&(await e.subscribeToModuleEvents(s),l.debug(`Plugin subscribed to module events`,{pluginName:e.name}));return l.debug(`Robota initialization completed successfully with independent managers`),d}async function ea(e){try{let t=await $i(e.ctx);e.setExecutionService(t),e.setFullyInitialized(!0)}catch(t){throw e.ctx.logger.error(`Robota initialization failed`,{error:t instanceof Error?t.message:String(t)}),t}}function ta(e){let t=e.isFullyInitialized?e.aiProviders.getProviderNames():[],n=e.isFullyInitialized?e.aiProviders.getCurrentProvider():null,r=n?n.provider:null,i=e.isFullyInitialized?e.tools.getTools().map(e=>e.name):[],a=e.getPluginNames(),o=e.getModuleNames(),s=e.getHistory(),c=Date.now()-e.startTime,l={user:0,assistant:0,system:0,tool:0};for(let e of s)e.role in l&&l[e.role]++;return{name:e.name,version:e.version,conversationId:e.conversationId,providers:t,currentProvider:r,tools:i,plugins:a,modules:o,historyLength:s.length,historyStats:{userMessages:l.user,assistantMessages:l.assistant,systemMessages:l.system,toolMessages:l.tool},uptime:c}}async function na(e){e.logger.debug(`Destroying Robota instance`,{name:e.name});let t=[],n=async(n,r)=>{try{await r(),e.logger.debug(n)}catch(r){let i=r instanceof Error?r:Error(String(r));t.push(i),e.logger.error(`Error during Robota destruction step`,{step:n,error:i.message})}};if(e.isFullyInitialized&&e.moduleRegistry&&await n(`All modules disposed`,()=>e.moduleRegistry.disposeAllModules()),e.executionService){let t=e.executionService.getPlugins();for(let e of t)await n(`Plugin disposed: ${e.name}`,()=>e.dispose());e.logger.debug(`ExecutionService plugins cleaned up`)}return e.moduleRegistry&&await n(`ModuleRegistry cleared`,()=>e.moduleRegistry.clearAllModules()),e.eventEmitter&&await n(`EventEmitter disposed`,()=>e.eventEmitter.dispose()),e.resetState(),t.length===0?e.logger.info(`Robota instance destroyed successfully`,{name:e.name}):e.logger.warn(`Robota instance destroyed with cleanup failures`,{name:e.name,failureCount:t.length}),{errors:t}}function ra(e){return{maxConcurrentAgents:e.maxConcurrentAgents||100,defaultSystemMessage:e.defaultSystemMessage||`You are a helpful AI assistant.`,strictValidation:e.strictValidation??!0,...e.defaultModel!==void 0&&{defaultModel:e.defaultModel},...e.defaultProvider!==void 0&&{defaultProvider:e.defaultProvider}}}function ia(e,t){if(!e.aiProviders||e.aiProviders.length===0)throw new W(`At least one AI provider must be specified in aiProviders array`);let n=e.defaultModel,r=n?.model??t.defaultModel;if(!r)throw new W(`No model specified: set config.defaultModel.model or the AgentFactory defaultModel option`);let i=n?.provider??e.aiProviders[0]?.name??t.defaultProvider;if(!i)throw new W(`No provider specified: set config.defaultModel.provider, an aiProviders entry, or the AgentFactory defaultProvider option`);return{id:e.id||aa(),name:e.name||`Unnamed Agent`,aiProviders:e.aiProviders,defaultModel:{provider:i,model:r,temperature:n?.temperature??.7,...n?.maxTokens!==void 0&&{maxTokens:n.maxTokens},...n?.topP!==void 0&&{topP:n.topP}},systemMessage:e.systemMessage||t.defaultSystemMessage,tools:e.tools||[],plugins:e.plugins||[],metadata:e.metadata||{},...e.logging&&{logging:e.logging},...e.conversationId&&{conversationId:e.conversationId},...e}}function aa(){return`agent_${Date.now()}_${Math.random().toString(36).substring(2,8)}`}function oa(e,t){return e.totalCreated++,e.activeCount++,t?e.fromTemplates++:e.customConfigured++,e.templateUsageRatio=e.totalCreated>0?e.fromTemplates/e.totalCreated:0,e}var sa=class{templates=new Map;logger;constructor(){this.logger=Nt(`AgentTemplates`),this.logger.info(`AgentTemplates initialized`)}registerTemplate(e){if(!e.id)throw Error(`Template must have an ID`);this.templates.has(e.id)&&this.logger.warn(`Template "${e.id}" is already registered, overriding`),this.templates.set(e.id,e),this.logger.info(`Template "${e.id}" registered successfully`,{templateId:e.id,category:e.category,tags:e.tags})}unregisterTemplate(e){let t=this.templates.delete(e);return t?this.logger.info(`Template "${e}" unregistered`):this.logger.warn(`Attempted to unregister non-existent template "${e}"`),t}getTemplates(){return Array.from(this.templates.values())}getTemplate(e){return this.templates.get(e)}findTemplates(e){return this.getTemplates().filter(t=>!(e.category&&t.category!==e.category||e.tags&&e.tags.length>0&&!e.tags.some(e=>t.tags?.includes(e))||e.provider&&t.config.defaultModel?.provider!==e.provider||e.model&&t.config.defaultModel?.model!==e.model))}applyTemplate(e,t={}){let n=[],r=!1,i={...e.config},a={...i,...t},o=e=>{e in t&&i[e]!==t[e]&&(r=!0,i[e]!==void 0&&n.push(`Override: ${e} changed from "${String(i[e])}" to "${String(t[e])}"`))};t.name!==void 0&&o(`name`),t.systemMessage!==void 0&&o(`systemMessage`);let s=a;return this.logger.debug(`Template applied`,{templateId:e.id,overridesCount:Object.keys(t).length,warningsCount:n.length,modified:r}),{config:s,template:e,warnings:n,modified:r}}hasTemplate(e){return this.templates.has(e)}getTemplateCount(){return this.templates.size}clearAll(){this.templates.clear(),this.logger.info(`All templates cleared`)}getStats(){let e=this.getTemplates(),t=[...new Set(e.map(e=>e.category).filter(e=>typeof e==`string`&&e.length>0))],n=[...new Set(e.flatMap(e=>e.tags||[]))],r=[...new Set(e.map(e=>e.config.defaultModel?.provider).filter(e=>typeof e==`string`&&e.length>0))],i=[...new Set(e.map(e=>e.config.defaultModel?.model).filter(e=>typeof e==`string`&&e.length>0))];return{totalTemplates:e.length,categories:t,tags:n,providers:r,models:i}}},ca=class{agentTemplates;initialized=!1;logger;options;activeAgents;creationStats;lifecycleEvents;constructor(e={},t={}){this.agentTemplates=new sa,this.logger=Nt(`AgentFactory`),this.options=ra(e),this.activeAgents=new Map,this.creationStats={totalCreated:0,activeCount:0,fromTemplates:0,customConfigured:0,templateUsageRatio:0},this.lifecycleEvents=t,this.logger.debug(`AgentFactory initialized`,{maxConcurrentAgents:this.options.maxConcurrentAgents,strictValidation:this.options.strictValidation,hasDefaultModel:!!this.options.defaultModel,hasDefaultProvider:!!this.options.defaultProvider,hasLifecycleEvents:this.lifecycleEvents!==null})}async initialize(){this.initialized||(this.logger.debug(`Initializing AgentFactory`),this.initialized=!0,this.logger.debug(`AgentFactory initialization completed`))}async createAgent(e,t,n=!1){let r;try{if(this.activeAgents.size>=this.options.maxConcurrentAgents)throw new W(`Maximum concurrent agents limit reached: ${this.options.maxConcurrentAgents}`);if(r=ia(t,this.options),this.options.strictValidation){let e=Gr(r);if(!e.isValid)throw new G(`Invalid agent configuration: ${e.errors.join(`, `)}`)}this.lifecycleEvents.beforeCreate&&await this.lifecycleEvents.beforeCreate(r);let i=new e(r),a=i;typeof a.initialize==`function`&&await a.initialize();let o=aa();return this.activeAgents.set(o,i),oa(this.creationStats,n),this.lifecycleEvents.afterCreate&&await this.lifecycleEvents.afterCreate(i,r),this.logger.info(`Agent created successfully`,{agentId:o,model:r.defaultModel.model,provider:r.defaultModel.provider}),i}catch(e){let n=e instanceof Error?e:Error(String(e));throw this.lifecycleEvents.onCreateError&&r&&await this.lifecycleEvents.onCreateError(n,r),this.logger.error(`Failed to create agent`,{error:n.message,model:t.defaultModel?.model,provider:t.defaultModel?.provider,hasTools:!!t.tools?.length}),n}}async createFromTemplate(e,t,n={}){let r=this.agentTemplates.getTemplate(t);if(!r)throw new W(`Template not found: ${t}`);let i=this.applyTemplate(r,n);i.warnings.length>0&&this.logger.warn(`Template application warnings`,{templateId:t,warnings:i.warnings});let a=await this.createAgent(e,i.config,!0);return this.logger.info(`Agent created from template`,{templateId:t,modified:i.modified,warnings:i.warnings.length}),a}registerTemplate(e){this.agentTemplates.registerTemplate(e)}unregisterTemplate(e){return this.agentTemplates.unregisterTemplate(e)}getTemplates(){return this.agentTemplates.getTemplates()}getTemplate(e){return this.agentTemplates.getTemplate(e)}findTemplates(e){return this.agentTemplates.findTemplates(e)}applyTemplate(e,t={}){return this.agentTemplates.applyTemplate(e,t)}async destroyAgent(e){let t=this.activeAgents.get(e);if(!t)return!1;try{let n=t;return typeof n.cleanup==`function`&&await n.cleanup(),this.activeAgents.delete(e),this.creationStats.activeCount--,this.lifecycleEvents.onDestroy&&await this.lifecycleEvents.onDestroy(e),this.logger.info(`Agent destroyed`,{agentId:e}),!0}catch(t){throw this.logger.error(`Error destroying agent`,{agentId:e,error:t instanceof Error?t.message:String(t)}),t}}getCreationStats(){return{...this.creationStats}}getActiveAgents(){return new Map(this.activeAgents)}validateConfiguration(e){return Gr(e)}},la=class extends yt{providers=new Map;currentProvider;currentModel;constructor(){super()}async doInitialize(){U.debug(`AIProviders initialized`)}async doDispose(){for(let[e,t]of this.providers)try{t.close&&await t.close(),U.debug(`Closed AI provider: ${e}`)}catch(t){U.warn(`Failed to close AI provider ${e}`,{error:t instanceof Error?t.message:String(t)})}this.providers.clear(),this.currentProvider=void 0,this.currentModel=void 0,U.debug(`AIProviders disposed`)}addProvider(e,t){this.ensureInitialized();let n=Wr.validateProviderName(e);if(!n.isValid)throw new G(`Invalid provider name: ${n.errors.join(`, `)}`);if(!t||typeof t!=`object`||!t||Array.isArray(t))throw new G(`Provider must be a valid object instance`);if(!t.name||typeof t.name!=`string`)throw new G(`Provider must have a valid name`);if(typeof t.chat!=`function`)throw new G(`Provider must have a chat method`);this.providers.has(e)&&U.warn(`Provider "${e}" is already registered, overriding`,{providerName:e,existingProvider:this.providers.get(e)?.name}),this.providers.set(e,t),U.debug(`AI provider "${e}" registered successfully`,{providerName:e,version:t.version,supportsStreaming:typeof t.chatStream==`function`})}removeProvider(e){if(this.ensureInitialized(),!this.providers.has(e)){U.warn(`Attempted to remove non-existent provider "${e}"`);return}let t=this.providers.get(e);t?.close&&t.close().catch(t=>{U.warn(`Failed to close provider ${e}`,{error:t.message})}),this.providers.delete(e),this.currentProvider===e&&(this.currentProvider=void 0,this.currentModel=void 0,U.debug(`Cleared current provider selection after removing "${e}"`)),U.debug(`AI provider "${e}" removed successfully`)}getProvider(e){return this.ensureInitialized(),this.providers.get(e)}getProviders(){return this.ensureInitialized(),Object.fromEntries(this.providers)}setCurrentProvider(e,t){if(this.ensureInitialized(),!this.providers.get(e))throw new W(`Provider "${e}" is not registered`);this.currentProvider=e,this.currentModel=t,U.debug(`Current AI provider set to "${e}" with model "${t}"`)}getCurrentProvider(){if(this.ensureInitialized(),!(!this.currentProvider||!this.currentModel))return{provider:this.currentProvider,model:this.currentModel}}isConfigured(){return this.ensureInitialized(),!!(this.currentProvider&&this.currentModel&&this.providers.has(this.currentProvider))}getCurrentProviderInstance(){if(!(!this.isConfigured()||!this.currentProvider))return this.providers.get(this.currentProvider)}getProviderNames(){return this.ensureInitialized(),Array.from(this.providers.keys())}getProvidersByPattern(e){this.ensureInitialized();let t=typeof e==`string`?new RegExp(e):e,n={};for(let[e,r]of this.providers)t.test(e)&&(n[e]=r);return n}supportsStreaming(e){this.ensureInitialized();let t=e||this.currentProvider;if(!t)return!1;let n=this.providers.get(t);return!!(n&&typeof n.chatStream==`function`)}getProviderCount(){return this.ensureInitialized(),this.providers.size}};function ua(e,t,n){if(!e.name||e.name.trim()===``)throw new W(`Module name is required`);if(!e.version||e.version.trim()===``)throw new W(`Module version is required`);let r=e.getModuleType(),i=t.validateTypeDescriptor(r);if(!i.valid)throw new W(`Invalid module type: ${i.errors.join(`, `)}`,{moduleName:e.name,errors:i.errors});i.warnings.length>0&&n.warn(`Module type validation warnings`,{moduleName:e.name,warnings:i.warnings})}async function da(e,t,n,r){let i=e.getModuleType();if(!i.dependencies||i.dependencies.length===0)return;for(let n of i.dependencies)if(!t.hasType(n))throw new W(`Module '${e.name}' depends on unregistered type '${n}'`,{moduleName:e.name,dependencyType:n});let a=new Set;for(let e of n.values())a.add(e.getModuleType().type);let o=[];for(let e of i.dependencies)a.has(e)||o.push(e);o.length>0&&r.warn(`Module has unmet dependencies`,{moduleName:e.name,missingDependencies:o})}function fa(e,t){let n=t.get(e);if(!n)return[];let r=n.getModuleType().type,i=[];for(let[n,a]of t.entries())n!==e&&a.getModuleType().dependencies?.includes(r)&&i.push(n);return i}function pa(e,t){let n={},r=0,i=0,a=0,o=0,s=0,c=0;for(let t of e.values()){let e=t.getModuleType().type;n[e]=(n[e]||0)+1,t.isInitialized()&&r++,t.isEnabled()&&i++}for(let e of t.values())a+=e.totalExecutions,o+=e.successfulExecutions,s+=e.failedExecutions,c+=e.totalExecutionTime;return{totalModules:e.size,initializedModules:r,enabledModules:i,modulesByType:n,totalExecutions:a,totalSuccessfulExecutions:o,totalFailedExecutions:s,averageExecutionTime:a>0?c/a:0}}function ma(){return[{type:`storage`,category:`storage`,layer:`infrastructure`,capabilities:[`data-persistence`,`data-retrieval`]},{type:`memory-storage`,category:`storage`,layer:`infrastructure`,dependencies:[`storage`],capabilities:[`in-memory-storage`,`fast-access`]},{type:`file-storage`,category:`storage`,layer:`infrastructure`,dependencies:[`storage`],capabilities:[`persistent-storage`,`file-system-access`]},{type:`text-processing`,category:`processing`,layer:`application`,capabilities:[`text-analysis`,`content-transformation`]},{type:`file-processing`,category:`processing`,layer:`application`,dependencies:[`storage`],capabilities:[`file-parsing`,`content-extraction`]},{type:`api-integration`,category:`integration`,layer:`application`,capabilities:[`external-api-access`,`data-synchronization`]},{type:`database-integration`,category:`integration`,layer:`infrastructure`,dependencies:[`storage`],capabilities:[`database-access`,`query-execution`]},{type:`rag`,category:`capability`,layer:`domain`,dependencies:[`storage`,`text-processing`],capabilities:[`document-search`,`context-retrieval`,`semantic-search`]},{type:`speech-processing`,category:`capability`,layer:`domain`,capabilities:[`speech-to-text`,`text-to-speech`,`audio-processing`]},{type:`image-analysis`,category:`capability`,layer:`domain`,capabilities:[`image-recognition`,`visual-analysis`,`content-extraction`]}]}function ha(e,t){let n=[],r=[];if((!e.type||e.type.trim()===``)&&n.push(`Module type is required and cannot be empty`),e.category||n.push(`Module category is required`),e.layer||n.push(`Module layer is required`),e.type&&!/^[a-zA-Z][a-zA-Z0-9-_]*$/.test(e.type)&&n.push(`Module type must start with a letter and contain only letters, numbers, hyphens, and underscores`),e.dependencies){for(let t of e.dependencies)(!t||t.trim()===``)&&n.push(`Dependencies cannot be empty`);e.dependencies.includes(e.type)&&n.push(`Module cannot depend on itself`)}if(e.capabilities)for(let t of e.capabilities)(!t||t.trim()===``)&&n.push(`Capabilities cannot be empty`);if(e.dependencies){let n=[`infrastructure`,`core`,`application`,`domain`,`presentation`],i=n.indexOf(e.layer);for(let a of e.dependencies){let o=t(a);o&&n.indexOf(o.layer)>i&&r.push(`Module '${e.type}' (${e.layer}) depends on '${a}' (${o.layer}) which is in a higher layer`)}}return{valid:n.length===0,errors:n,warnings:r}}function ga(e,t,n){let r=new Set,i=new Set,a=[],o=[],s=[];for(let r of e){let e=t(r);if(!e){s.push(r);continue}if(e.dependencies)for(let t of e.dependencies)!n(t)&&!s.includes(t)&&s.push(t)}let c=(s,l=[])=>{if(i.has(s)){let e=l.indexOf(s);o.push(l.slice(e).concat([s]));return}if(r.has(s))return;let u=t(s);if(!u)return;i.add(s);let d=[...l,s];if(u.dependencies)for(let t of u.dependencies)(e.includes(t)||n(t))&&c(t,d);i.delete(s),r.add(s),a.push(s)};for(let t of e)r.has(t)||c(t);return{resolved:s.length===0&&o.length===0,order:a,circularDependencies:o,missingDependencies:s}}function _a(e,t){let n=[],r=[],i=new Map;for(let n of e){let e=t(n);e&&(i.has(e.layer)||i.set(e.layer,[]),i.get(e.layer).push(n))}let a=new Map;for(let n of e){let e=t(n);if(e?.capabilities)for(let t of e.capabilities)a.has(t)||a.set(t,[]),a.get(t).push(n)}for(let[e,t]of Array.from(a.entries()))if(t.length>1)for(let r=0;r<t.length;r++)for(let i=r+1;i<t.length;i++){let a=t[r],o=t[i];a&&o&&n.push({module1:a,module2:o,reason:`Both modules provide capability '${e}'`})}return n.length>0&&(r.push(`Consider using only one module per capability`),r.push(`Check if modules can be configured to avoid conflicts`)),!i.has(`infrastructure`)&&e.length>1&&r.push(`Consider adding infrastructure modules for better foundation`),{compatible:n.length===0,conflicts:n,suggestions:r}}function va(e){let t={core:0,storage:0,processing:0,integration:0,interface:0,capability:0},n={infrastructure:0,core:0,application:0,domain:0,presentation:0},r=0,i=0;for(let a of e.values())t[a.category]++,n[a.layer]++,a.dependencies&&a.dependencies.length>0&&r++,a.capabilities&&a.capabilities.length>0&&i++;return{totalTypes:e.size,typesByCategory:t,typesByLayer:n,typesWithDependencies:r,typesWithCapabilities:i}}var ya=class{registeredTypes=new Map;logger;constructor(){this.logger=Nt(`ModuleDescriptorRegistry`),this.registerBuiltinTypes()}registerType(e){let t=this.validateTypeDescriptor(e);if(!t.valid)throw new W(`Invalid module type descriptor: ${t.errors.join(`, `)}`,{type:e.type,errors:t.errors});if(this.registeredTypes.has(e.type)){let t=this.registeredTypes.get(e.type);this.logger.warn(`Overriding existing module type`,{type:e.type,previousCategory:t?.category||`unknown`,newCategory:e.category})}this.registeredTypes.set(e.type,e),this.logger.info(`Module type registered`,{type:e.type,category:e.category,layer:e.layer,dependencies:e.dependencies?.length||0,capabilities:e.capabilities?.length||0})}unregisterType(e){if(!this.registeredTypes.has(e))return!1;let t=this.findDependentTypes(e);if(t.length>0)throw new W(`Cannot unregister module type '${e}' - it is required by: ${t.join(`, `)}`,{type:e,dependentTypes:t});return this.registeredTypes.delete(e),this.logger.info(`Module type unregistered`,{type:e}),!0}getType(e){return this.registeredTypes.get(e)}getAllTypes(){return Array.from(this.registeredTypes.values())}getTypesByCategory(e){return Array.from(this.registeredTypes.values()).filter(t=>t.category===e)}getTypesByLayer(e){return Array.from(this.registeredTypes.values()).filter(t=>t.layer===e)}hasType(e){return this.registeredTypes.has(e)}validateTypeDescriptor(e){return ha(e,e=>this.getType(e))}resolveDependencies(e){return ga(e,e=>this.getType(e),e=>this.hasType(e))}checkCompatibility(e){return _a(e,e=>this.getType(e))}findDependentTypes(e){let t=[];for(let[n,r]of this.registeredTypes)r.dependencies?.includes(e)&&t.push(n);return t}registerBuiltinTypes(){for(let e of ma())this.registerType(e);this.logger.info(`Built-in module types registered`,{totalTypes:this.registeredTypes.size})}clearAllTypes(){this.registeredTypes.clear(),this.logger.info(`All module types cleared`)}getStats(){return va(this.registeredTypes)}};const ba={REGISTERED:`module.registered`,UNREGISTERED:`module.unregistered`};var xa=class{modules=new Map;moduleOptions=new Map;moduleStatuses=new Map;moduleStats=new Map;registrationOrder=[];initializationOrder=[];typeRegistry;eventEmitter;logger;isDisposing=!1;constructor(e,t){this.eventEmitter=e,this.typeRegistry=t??new ya,this.logger=Nt(`ModuleRegistry`)}async registerModule(e,t={}){if(this.isDisposing)throw new W(`Cannot register modules during disposal`);if(ua(e,this.typeRegistry,this.logger),this.modules.has(e.name))throw new W(`Module with name '${e.name}' is already registered`,{moduleName:e.name});t.validateDependencies!==!1&&await da(e,this.typeRegistry,this.modules,this.logger),this.modules.set(e.name,e),this.moduleOptions.set(e.name,t.initOptions||{}),this.registrationOrder.push(e.name);let n=e.getModuleType();this.moduleStatuses.set(e.name,{name:e.name,type:n.type,enabled:e.isEnabled(),initialized:!1,hasEventEmitter:!!this.eventEmitter,registrationTime:new Date,dependencies:n.dependencies||[],dependents:[]}),this.moduleStats.set(e.name,{totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,totalExecutionTime:0}),t.autoInitialize&&await this.initializeModule(e.name,t.initTimeout),this.eventEmitter&&await this.eventEmitter.emit(ba.REGISTERED,{data:{moduleName:e.name,moduleType:n.type},timestamp:new Date})}async unregisterModule(e){let t=this.modules.get(e);if(!t)return!1;let n=fa(e,this.modules);if(n.length>0)throw new W(`Cannot unregister module '${e}' - it is required by: ${n.join(`, `)}`,{moduleName:e,dependents:n});t.isInitialized()&&t.dispose&&await t.dispose(),this.modules.delete(e),this.moduleOptions.delete(e),this.moduleStatuses.delete(e),this.moduleStats.delete(e);let r=this.registrationOrder.indexOf(e);r!==-1&&this.registrationOrder.splice(r,1);let i=this.initializationOrder.indexOf(e);return i!==-1&&this.initializationOrder.splice(i,1),this.eventEmitter&&await this.eventEmitter.emit(ba.UNREGISTERED,{data:{moduleName:e},timestamp:new Date}),!0}async initializeModule(e,t){let n=this.modules.get(e);if(!n)throw new W(`Module '${e}' not found`);if(n.isInitialized())return;let r=this.moduleOptions.get(e),i=n.initialize(r,this.eventEmitter);if(t&&t>0){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{i(Error(`Module '${e}' initialization timed out after ${t}ms`))},t)});await Promise.race([i.then(e=>(clearTimeout(n),e)),r])}else await i;let a=this.moduleStatuses.get(e);a&&(a.initialized=!0,a.initializationTime=new Date),this.initializationOrder.includes(e)||this.initializationOrder.push(e)}async initializeAllModules(e){let t=Array.from(this.modules.keys());if(t.length===0)return;let n=t.map(e=>this.modules.get(e).getModuleType().type),r=this.typeRegistry.resolveDependencies(n);if(!r.resolved){let e=[];throw r.missingDependencies.length>0&&e.push(`Missing dependencies: ${r.missingDependencies.join(`, `)}`),r.circularDependencies.length>0&&e.push(`Circular dependencies: ${r.circularDependencies.map(e=>e.join(` -> `)).join(`; `)}`),new W(`Cannot initialize modules: ${e.join(`; `)}`,{missingDependencies:r.missingDependencies,circularDependencies:r.circularDependencies.map(e=>e.join(` -> `))})}for(let n of r.order){let r=t.find(e=>this.modules.get(e).getModuleType().type===n);r&&await this.initializeModule(r,e)}}async executeModule(e,t){let n=this.modules.get(e);if(!n)throw new W(`Module '${e}' not found`);if(!n.isInitialized())throw new W(`Module '${e}' is not initialized`);if(!n.isEnabled())throw new W(`Module '${e}' is disabled`);let r=this.moduleStats.get(e),i=Date.now();try{if(!n.execute)throw new W(`Module '${e}' does not support execute()`);let a=await n.execute(t),o=Date.now()-i;r.totalExecutions++,r.successfulExecutions++,r.totalExecutionTime+=o,r.averageExecutionTime=r.totalExecutionTime/r.totalExecutions,r.lastExecutionTime=new Date;let s=this.moduleStatuses.get(e);return s&&(s.lastActivity=new Date),a}catch(e){let t=Date.now()-i;throw r.totalExecutions++,r.failedExecutions++,r.totalExecutionTime+=t,r.averageExecutionTime=r.totalExecutionTime/r.totalExecutions,r.lastExecutionTime=new Date,e}}getModule(e){return this.modules.get(e)}getModulesByType(e){return Array.from(this.modules.values()).filter(t=>t.getModuleType().type===e)}getAllModules(){return Array.from(this.modules.values())}getModuleNames(){return Array.from(this.modules.keys())}hasModule(e){return this.modules.has(e)}getModuleStatus(e){return this.moduleStatuses.get(e)}getAllModuleStatuses(){return Array.from(this.moduleStatuses.values())}getModuleStats(e){return this.moduleStats.get(e)}getAllModuleStats(){let e={};for(let[t,n]of this.moduleStats.entries())e[t]={...n};return e}async disposeAllModules(){this.isDisposing=!0;let e=[...this.initializationOrder].reverse();for(let t of e){let e=this.modules.get(t);if(e&&e.isInitialized())try{e.dispose&&await e.dispose();let n=this.moduleStatuses.get(t);n&&(n.initialized=!1)}catch(e){this.logger.error(`Failed to dispose module`,{name:t,error:e instanceof Error?e.message:String(e)})}}this.initializationOrder=[],this.isDisposing=!1}clearAllModules(){this.modules.clear(),this.moduleOptions.clear(),this.moduleStatuses.clear(),this.moduleStats.clear(),this.registrationOrder=[],this.initializationOrder=[],this.isDisposing=!1}getRegistryStats(){return pa(this.modules,this.moduleStats)}},Sa=class{tools=new Map;register(e){if(!e.schema?.name)throw new G(`Tool must have a valid schema with name`);let t=e.schema.name;this.validateToolSchema(e.schema),this.tools.has(t)&&U.warn(`Tool "${t}" is already registered, overriding`,{toolName:t,existingTool:this.tools.get(t)?.constructor.name}),this.tools.set(t,e),U.debug(`Tool "${t}" registered successfully`,{toolName:t,toolType:e.constructor.name,parameters:Object.keys(e.schema.parameters?.properties||{})})}unregister(e){if(!this.tools.has(e)){U.warn(`Attempted to unregister non-existent tool "${e}"`);return}this.tools.delete(e),U.debug(`Tool "${e}" unregistered successfully`)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSchemas(){let e=this.getAll();return U.debug(`[TOOL-FLOW] ToolRegistry.getSchemas() - Tools before schema extraction`,{count:e.length,tools:e.map(e=>({name:e.schema?.name??`unnamed`,hasSchema:!!e.schema,schemaType:typeof e.schema,toolType:e.constructor?.name||`unknown`}))}),this.getAll().map(e=>e.schema)}has(e){return this.tools.has(e)}clear(){let e=this.tools.size;this.tools.clear(),U.debug(`Cleared ${e} tools from registry`)}getToolNames(){return Array.from(this.tools.keys())}getToolsByPattern(e){let t=typeof e==`string`?new RegExp(e):e;return this.getAll().filter(e=>t.test(e.schema.name))}size(){return this.tools.size}validateToolSchema(e){if(!e.name||typeof e.name!=`string`)throw new G(`Tool schema must have a valid name`);if(!e.description||typeof e.description!=`string`)throw new G(`Tool schema must have a description`);if(!e.parameters||typeof e.parameters!=`object`||e.parameters===null||Array.isArray(e.parameters))throw new G(`Tool schema must have parameters object`);if(e.parameters.type!==`object`)throw new G(`Tool parameters type must be "object"`);if(e.parameters.properties)for(let t of Object.keys(e.parameters.properties)){let n=e.parameters.properties[t];if(!n?.type)throw new G(`Parameter "${t}" must have a type`);if(![`string`,`number`,`boolean`,`array`,`object`].includes(n.type))throw new G(`Parameter "${t}" has invalid type "${n.type}"`)}if(e.parameters.required){let t=e.parameters.properties||{};for(let n of e.parameters.required)if(!t[n])throw new G(`Required parameter "${n}" is not defined in properties`)}}},Ca=class{schema;fn;eventService;constructor(e,t){this.schema=e,this.fn=t,this.validateConstructorInputs()}getName(){return this.schema.name}setEventService(e){this.eventService=e}async execute(e,t){let n=this.schema.name;if(!this.validate(e))throw new G(`Invalid parameters for tool "${n}": ${this.getValidationErrors(e).join(`, `)}`);let r=Date.now(),i;try{i=await this.fn(e,t)}catch(r){throw r instanceof un||r instanceof G?r:new un(`Function tool execution failed: ${r instanceof Error?r.message:String(r)}`,n,r instanceof Error?r:Error(String(r)),{parameterCount:Object.keys(e||{}).length,hasContext:!!t})}let a=Date.now()-r;return{success:!0,data:i,metadata:{executionTime:a,toolName:n,parameters:e}}}validate(e){return this.getValidationErrors(e).length===0}validateParameters(e){let t=this.getValidationErrors(e);return{isValid:t.length===0,errors:t}}getDescription(){return this.schema.description}getValidationErrors(e){let t=[],n=this.schema.parameters.required||[],r=this.schema.parameters.properties||{};for(let r of n)r in e||t.push(`Missing required parameter: ${r}`);for(let[n,i]of Object.entries(e)){let e=r[n];if(!e){t.push(`Unknown parameter: ${n}`);continue}let a=this.validateParameterType(n,i,e);a&&t.push(a)}return t}validateParameterType(e,t,n){switch(n.type){case`string`:if(typeof t!=`string`)return`Parameter "${e}" must be a string, got ${typeof t}`;break;case`number`:if(typeof t!=`number`||isNaN(t))return`Parameter "${e}" must be a number, got ${typeof t}`;break;case`boolean`:if(typeof t!=`boolean`)return`Parameter "${e}" must be a boolean, got ${typeof t}`;break;case`array`:if(!Array.isArray(t))return`Parameter "${e}" must be an array, got ${typeof t}`;if(n.items)for(let r=0;r<t.length;r++){let i=this.validateParameterType(`${e}[${r}]`,t[r],n.items);if(i)return i}break;case`object`:if(typeof t!=`object`||!t||Array.isArray(t))return`Parameter "${e}" must be an object, got ${typeof t}`;break}if(n.enum&&n.enum.length>0){let r=n.enum,i=!1;for(let e of r)if(t===e){i=!0;break}if(!i)return`Parameter "${e}" must be one of: ${r.join(`, `)}, got ${t}`}}validateConstructorInputs(){if(!this.schema)throw new G(`Tool schema is required`);if(!this.fn||typeof this.fn!=`function`)throw new G(`Tool function is required and must be a function`);if(!this.schema.name)throw new G(`Tool schema must have a name`)}},wa=class extends yt{registry;allowedTools;constructor(){super(),this.registry=new Sa}async doInitialize(){U.debug(`Tools initialized`)}async doDispose(){this.registry.clear(),delete this.allowedTools,U.debug(`Tools disposed`)}addTool(e,t){this.ensureInitialized();let n=new Ca(e,t);this.registry.register(n),U.debug(`Tool "${e.name}" registered successfully`)}removeTool(e){this.ensureInitialized(),this.registry.unregister(e)}getTool(e){return this.ensureInitialized(),this.registry.get(e)}getToolSchema(e){return this.ensureInitialized(),this.registry.get(e)?.schema}getTools(){this.ensureInitialized();let e=this.registry.getSchemas();return this.allowedTools?e.filter(e=>this.allowedTools.includes(e.name)):e}async executeTool(e,t,n){if(this.ensureInitialized(),this.allowedTools&&!this.allowedTools.includes(e))throw new un(`Tool "${e}" is not in the allowed tools list`,e);let r=this.registry.get(e);if(!r)throw new un(`Tool "${e}" is not registered`,e);let i;try{i=await r.execute(t,n)}catch(t){throw t instanceof Error?new un(t.message,e,t):new un(String(t),e)}if(!i.success)throw new un(i.error||`Tool execution failed`,e,void 0,{parameters:JSON.stringify(t),result:JSON.stringify(i)});if(i.data===void 0)throw new un(`Tool execution succeeded but returned no data`,e);return i.data}hasTool(e){return this.ensureInitialized(),this.registry.has(e)}setAllowedTools(e){this.ensureInitialized(),this.allowedTools=[...e],U.debug(`Set allowed tools: ${e.join(`, `)}`)}getAllowedTools(){return this.ensureInitialized(),this.allowedTools?[...this.allowedTools]:void 0}getRegistry(){return this.ensureInitialized(),this.registry}getToolCount(){return this.ensureInitialized(),this.registry.size()}},Ta=class extends Ei{name;version=`1.0.0`;aiProviders;tools;agentFactory;conversationHistory;moduleRegistry;eventEmitter;executionService;eventService;agentEventService;config;conversationId;logger;initializationPromise;destroyed=!1;isFullyInitialized=!1;startTime;configVersion=1;configUpdatedAt=Date.now();configManager;constructor(e){super(),this.name=e.name,this.config=e,this.conversationId=e.conversationId||`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this.logger=Nt(`Robota`),this.startTime=Date.now(),e.logging&&(e.logging.level&&Pt(e.logging.level),e.logging.enabled===!1&&Pt(`silent`)),Di(e),this.aiProviders=new la,this.tools=new wa,this.agentFactory=new ca,this.conversationHistory=new ui,this.eventEmitter=Pi(),this.moduleRegistry=new xa(this.eventEmitter),this.eventService=e.eventService||qt,this.agentEventService=Qt(this.eventService,{ownerType:`agent`,ownerId:this.conversationId,ownerPath:Fi(this.conversationId,this.config.executionContext)});let t=ji({getName:()=>this.name,getModuleRegistry:()=>this.moduleRegistry,getLogger:()=>this.logger,getIsFullyInitialized:()=>this.isFullyInitialized,ensureFullyInitialized:()=>this.ensureFullyInitialized(),getExecutionService:()=>this.executionService,getAiProviders:()=>this.aiProviders,getTools:()=>this.tools,getEventService:()=>this.eventService,getConfig:()=>this.config,setConfig:e=>{this.config=e},getConfigVersion:()=>this.configVersion,incrementConfigVersion:()=>++this.configVersion,getConfigUpdatedAt:()=>this.configUpdatedAt,setConfigUpdatedAt:e=>{this.configUpdatedAt=e},emitAgentEvent:(e,t)=>this.emitAgentEvent(e,t)});this.moduleManager=t.moduleManager,this.pluginManager=t.pluginManager,this.configManager=t.configManager,Mi(this.config,(e,t)=>this.emitAgentEvent(e,t))}async ensureReady(){await this.ensureFullyInitialized()}async run(e,t={}){return this.assertNotDestroyed(),this.enqueueRun(t.signal,async()=>{await this.ensureFullyInitialized();try{if(t.output){let n=ti(t.output);return await Vi(this.executionDeps(),e,t,n)}return await Li(this.executionDeps(),e,t)}finally{this.resetEphemeralHistory()}})}async*runStream(e,t={}){this.assertNotDestroyed();let n=await this.acquireRunSlot(t.signal);try{if(await this.ensureFullyInitialized(),t.output){let n=ti(t.output);return yield*Hi(this.executionDeps(),e,t,n)}return yield*Ri(this.executionDeps(),e,t),void 0}finally{this.resetEphemeralHistory(),n()}}resetEphemeralHistory(){this.config.retainHistory===!1&&this.clearHistory()}runQueueTail=Promise.resolve();async acquireRunSlot(e){let t=this.runQueueTail,n=()=>{};if(this.runQueueTail=new Promise(e=>{n=e}),await t,e?.aborted)throw n(),Error(`Run aborted while queued behind another run on this instance`);return n}async enqueueRun(e,t){let n=await this.acquireRunSlot(e);try{return await t()}finally{n()}}executionDeps(){return{conversationId:this.conversationId,config:this.config,logger:this.logger,getHistory:()=>this.getHistory(),getExecutionService:()=>this.executionService,emitAgentEvent:(e,t)=>this.emitAgentEvent(e,t)}}getHistory(){return Wi(this.conversationHistory,this.conversationId)}getFullHistory(){return Gi(this.conversationHistory,this.conversationId)}addHistoryEntry(e){Ki(this.conversationHistory,this.conversationId,e)}clearHistory(){qi(this.conversationHistory,this.conversationId)}injectMessage(e,t,n){Ji(this.conversationHistory,this.conversationId,e,t,n)}injectRawMessage(e){Yi(this.conversationHistory,this.conversationId,e)}async updateTools(e){return this.configManager.updateTools(e)}async updateConfiguration(e){return this.configManager.updateConfiguration(e)}async getConfiguration(){return this.configManager.getConfiguration()}setModel(e){this.configManager.setModel(e)}getModel(){return this.configManager.getModel()}updateSystemPrompt(e){this.configManager.setSystemMessage(e),this.conversationHistory.getConversationStore(this.conversationId).setSystemPrompt(e)}getSystemPrompt(){return this.configManager.getSystemMessage()}registerTool(e){this.configManager.registerTool(e,this.tools)}unregisterTool(e){this.tools.removeTool(e)}getConfig(){return{...this.config}}swapDefaultProvider(e,t){this.aiProviders.addProvider(e.name,e),this.configManager.setModel({provider:e.name,model:t})}getStats(){return ta({name:this.name,version:this.version,conversationId:this.conversationId,startTime:this.startTime,isFullyInitialized:this.isFullyInitialized,aiProviders:this.aiProviders,tools:this.tools,getPluginNames:()=>this.getPluginNames(),getModuleNames:()=>this.getModuleNames(),getHistory:()=>this.getHistory()})}async destroy(){return this.destroyed?{errors:[]}:(this.destroyed=!0,await this.runQueueTail,na({name:this.name,isFullyInitialized:this.isFullyInitialized,moduleRegistry:this.moduleRegistry,eventEmitter:this.eventEmitter,executionService:this.executionService,logger:this.logger,resetState:()=>{this.isFullyInitialized=!1,this.initializationPromise=void 0}}))}assertNotDestroyed(){if(this.destroyed)throw Error(`[LIFECYCLE] Agent "${this.name}" has been destroyed — create a new instance`)}async initialize(){await this.ensureFullyInitialized()}async ensureFullyInitialized(){this.assertNotDestroyed(),!this.isFullyInitialized&&(this.initializationPromise||=this.doAsyncInit().catch(e=>{throw this.initializationPromise=void 0,e}),await this.initializationPromise)}doAsyncInit(){return ea({ctx:{config:this.config,aiProviders:this.aiProviders,tools:this.tools,agentFactory:this.agentFactory,conversationHistory:this.conversationHistory,moduleRegistry:this.moduleRegistry,eventEmitter:this.eventEmitter,eventService:this.eventService,logger:this.logger},setExecutionService:e=>{this.executionService=e},setFullyInitialized:e=>{this.isFullyInitialized=e}})}emitAgentEvent(e,t){Ni(this.agentEventService,this.conversationId,this.config.executionContext,e,t)}};const Ea={safe:`plan`,moderate:`default`,full:`acceptEdits`},Da={plan:{Shell:`deny`,Bash:`deny`,Read:`auto`,Write:`deny`,Edit:`deny`,Glob:`auto`,Grep:`auto`,WebFetch:`auto`,WebSearch:`auto`,AskUserQuestion:`auto`},default:{Shell:`approve`,Bash:`approve`,Read:`auto`,Write:`approve`,Edit:`approve`,Glob:`auto`,Grep:`auto`,WebFetch:`auto`,WebSearch:`auto`,AskUserQuestion:`auto`},acceptEdits:{Shell:`approve`,Bash:`approve`,Read:`auto`,Write:`auto`,Edit:`auto`,Glob:`auto`,Grep:`auto`,WebFetch:`auto`,WebSearch:`auto`,AskUserQuestion:`auto`},bypassPermissions:{Shell:`auto`,Bash:`auto`,Read:`auto`,Write:`auto`,Edit:`auto`,Glob:`auto`,Grep:`auto`,WebFetch:`auto`,WebSearch:`auto`,AskUserQuestion:`auto`}},Oa={plan:`deny`,default:`approve`,acceptEdits:`approve`,bypassPermissions:`auto`};function ka(e){let t=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Aa(e){let t=e.indexOf(`(`);return t===-1?{toolName:e.trim(),argPattern:void 0}:{toolName:e.slice(0,t).trim(),argPattern:e.slice(t+1,e.lastIndexOf(`)`)).trim()}}function ja(e,t){switch(e){case`Shell`:case`Bash`:return typeof t.command==`string`?t.command:void 0;case`Read`:case`Write`:case`Edit`:return typeof t.filePath==`string`?t.filePath:void 0;case`Glob`:case`Grep`:return typeof t.pattern==`string`?t.pattern:void 0;default:return}}function Ma(e,t,n){let r=Aa(n);if(r.toolName!==e)return!1;if(r.argPattern===void 0)return!0;let i=ja(e,t);return i===void 0?!1:ka(r.argPattern).test(i)}function Na(e,t,n,r={}){let{allow:i=[],deny:a=[]}=r;for(let n of a)if(Ma(e,t,n))return`deny`;for(let n of i)if(Ma(e,t,n))return`auto`;let o=Da[n][e];return o===void 0?Oa[n]:o}const Pa=1e6,Fa={"claude-opus-4-7":{inputPerMillion:15,outputPerMillion:75},"claude-opus-4-5":{inputPerMillion:15,outputPerMillion:75},"claude-sonnet-4-6":{inputPerMillion:3,outputPerMillion:15},"claude-sonnet-4-5":{inputPerMillion:3,outputPerMillion:15},"claude-haiku-4-5":{inputPerMillion:.8,outputPerMillion:4},"claude-3-5-sonnet-20241022":{inputPerMillion:3,outputPerMillion:15},"claude-3-5-haiku-20241022":{inputPerMillion:.8,outputPerMillion:4},"claude-3-opus-20240229":{inputPerMillion:15,outputPerMillion:75},"gpt-4o":{inputPerMillion:2.5,outputPerMillion:10},"gpt-4o-mini":{inputPerMillion:.15,outputPerMillion:.6},o1:{inputPerMillion:15,outputPerMillion:60},"o1-mini":{inputPerMillion:3,outputPerMillion:12},o3:{inputPerMillion:10,outputPerMillion:40},"o3-mini":{inputPerMillion:1.1,outputPerMillion:4.4},"deepseek-chat":{inputPerMillion:.14,outputPerMillion:.28},"deepseek-reasoner":{inputPerMillion:.55,outputPerMillion:2.19},"gemini-2.0-flash":{inputPerMillion:.1,outputPerMillion:.4},"gemini-2.0-flash-thinking":{inputPerMillion:.35,outputPerMillion:3.5},"gemini-1.5-pro":{inputPerMillion:1.25,outputPerMillion:5},"gemini-1.5-flash":{inputPerMillion:.075,outputPerMillion:.3}},Ia=[{pattern:/claude-opus/i,price:{inputPerMillion:15,outputPerMillion:75}},{pattern:/claude-sonnet/i,price:{inputPerMillion:3,outputPerMillion:15}},{pattern:/claude-haiku/i,price:{inputPerMillion:.8,outputPerMillion:4}},{pattern:/gpt-4o-mini/i,price:{inputPerMillion:.15,outputPerMillion:.6}},{pattern:/gpt-4/i,price:{inputPerMillion:2.5,outputPerMillion:10}},{pattern:/deepseek/i,price:{inputPerMillion:.14,outputPerMillion:.28}},{pattern:/gemini-2/i,price:{inputPerMillion:.1,outputPerMillion:.4}},{pattern:/gemini-1/i,price:{inputPerMillion:1.25,outputPerMillion:5}}];function La(e){let t=Fa[e];if(t)return t;for(let{pattern:t,price:n}of Ia)if(t.test(e))return n}function Ra(e,t,n){let r=La(e);if(r)return t/Pa*r.inputPerMillion+n/Pa*r.outputPerMillion}var za=class{type=`command`;execute(e,t){let n=(e.timeout??600)*1e3,r=JSON.stringify(t);return new Promise(a=>{let o=[],s=[],c=!1,l=Yr(),u=i(l.command,l.commandArgs(e.command),{cwd:t.cwd,env:{...process.env,...t.env}});u.stdout.on(`data`,e=>o.push(e)),u.stderr.on(`data`,e=>s.push(e)),u.stdin.on(`error`,()=>{}),u.stdin.write(r),u.stdin.end();let d=setTimeout(()=>{c||(c=!0,u.kill(`SIGTERM`),a({exitCode:1,stdout:``,stderr:`Hook timed out`}))},n);u.on(`close`,e=>{c||(c=!0,clearTimeout(d),a({exitCode:e??1,stdout:Buffer.concat(o).toString(`utf8`),stderr:Buffer.concat(s).toString(`utf8`)}))}),u.on(`error`,e=>{c||(c=!0,clearTimeout(d),a({exitCode:1,stdout:``,stderr:e.message}))})})}};function Ba(e){return e.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(e,t)=>{let n=process.env[t];return n===void 0?e:n})}var Va=class{type=`http`;async execute(e,t){let n=(e.timeout??10)*1e3,r={"Content-Type":`application/json`};if(e.headers)for(let[t,n]of Object.entries(e.headers))r[t]=Ba(n);try{let i=await fetch(e.url,{method:`POST`,headers:r,body:JSON.stringify(t),signal:AbortSignal.timeout(n)});if(!i.ok)return{exitCode:1,stdout:``,stderr:`HTTP ${i.status} ${i.statusText}`};let a=await i.json();return a.ok?{exitCode:0,stdout:JSON.stringify(a),stderr:``}:{exitCode:2,stdout:``,stderr:a.reason??`Blocked by HTTP hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};function Ha(){return[new za,new Va]}const Ua={deny:3,defer:2,ask:1,allow:0};function Wa(e){let t=e.trim();if(!t.startsWith(`{`))return null;try{return JSON.parse(t)}catch{return null}}function Ga(e,t){if(!e.matcher)return!0;if(!t)return!1;try{return new RegExp(e.matcher).test(t)}catch{return e.matcher===t}}function Ka(e){if(e.tool_name)return e.tool_name;if(e.hook_event_name===`SubagentStart`||e.hook_event_name===`SubagentStop`)return e.agent_type??e.agent_id;if(e.hook_event_name===`SessionEnd`)return e.reason}async function qa(e,t,n,r){if(!e)return{blocked:!1,stdout:``};let i=e[t];if(!i||i.length===0)return{blocked:!1,stdout:``};let a=r??Ha(),o=new Map;for(let e of a)o.set(e.type,e);let s=[],c=Ka(n),l=-1,u,d;for(let e of i){if(!Ga(e,c))continue;let r=e.env?{...n,env:{...n.env,...e.env}}:n;for(let n of e.hooks){let e=o.get(n.type);if(!e)continue;let i=await e.execute(n,r);if(i.exitCode===2)return{blocked:!0,reason:i.stderr||`Blocked by hook`,stdout:s.join(`
@@ -13,35 +13,35 @@ import{createRequire as e}from"node:module";import{execFileSync as t,execSync as
13
13
  `)};return u!==void 0&&(f.permissionDecision=u),d!==void 0&&(f.updatedInput=d),f}const Ja=process.platform===`win32`;function Ya(e){return e.exitCode!==null||e.signalCode!==null}function Xa(e,t,n){if(n&&!Ja&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function Za(e,t){if(Ja&&typeof e.pid==`number`){a(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}Xa(e,`SIGKILL`,t)}async function Qa(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!Ya(e)){if(typeof e.pid!=`number`)throw Error(`[agent-process] killProcessTree called with an unspawned child (no pid)`);if(t.preKill){try{await t.preKill()}catch{}if(Ya(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),Ya(e)){e.removeListener(`exit`,o),t();return}Xa(e,r,i),a=setTimeout(()=>{Ya(e)||Za(e,i)},n),a.unref?.()})}}var J=class extends Error{category;recoverable;constructor(e,t,n=!0){super(t),this.name=`BackgroundTaskError`,this.category=e,this.recoverable=n}};const $a=new Set([`idle`,`max_runtime`,`output_limit`,`repetition`,`stale_worker`]);function eo(){let e=()=>{},t=()=>{},n=new Promise((n,r)=>{e=n,t=r});return n.catch(()=>{}),{promise:n,resolve:e,reject:t}}function to(e){return new J(`runner`,e)}function no(e){return e instanceof J?{category:e.category,message:e.message,recoverable:e.recoverable}:{category:`runner`,message:e instanceof Error?e.message:e,recoverable:!0}}function ro(e){return e instanceof Error?e.message:e}function io(e,t){let n=t.metadata?.worktreePath;typeof n==`string`&&(e.worktreePath=n);let r=t.metadata?.branchName;typeof r==`string`&&(e.branchName=r);let i=t.metadata?.worktreeStatus;typeof i==`string`&&(e.worktreeStatus=i);let a=t.metadata?.worktreeNextAction;typeof a==`string`&&(e.worktreeNextAction=a);let o=t.metadata?.worktreeBaseRevision;typeof o==`string`&&(e.worktreeBaseRevision=o);let s=t.metadata?.parentWorktreeStatus;typeof s==`string`&&(e.parentWorktreeStatus=s);let c=t.metadata?.logPath;typeof c==`string`&&(e.logPath=c);let l=t.metadata?.transcriptPath;typeof l==`string`&&(e.transcriptPath=l);let u=t.metadata?.timeoutReason;ao(u)&&(e.timeoutReason=u)}function ao(e){return typeof e==`string`&&$a.has(e)}function oo(e){e.unref?.()}function so(e){return e.replace(/\s+/g,` `).trim()}function co(e,t){return e.length<=t?e:e.slice(e.length-t)}function lo(e,t){if(t<=1)return!1;let n=so(e);if(!n)return!1;let r=n.split(/(?<=[.!?。!?])\s+/).map(e=>e.trim()).filter(e=>e.length>=12);if(r.length<t)return!1;let i=``,a=0;for(let e of r)if(e===i?a+=1:(i=e,a=1),a>=t)return!0;return!1}function uo(e,t){if(e.kind===`agent`)return{promptPreview:e.prompt.slice(0,t)};if(e.kind===`process`)return{commandPreview:e.command.slice(0,t)};let n=e.command??e.agentInstruction;return n===void 0?{}:{commandPreview:n.slice(0,t)}}function fo(e,t,n,r){let i=uo(t,r),a=t.kind===`scheduled`?{schedule:{cronExpression:t.cronExpression,...t.agentInstruction===void 0?{}:{agentInstruction:t.agentInstruction},...t.command===void 0?{}:{command:t.command},...t.shell===void 0?{}:{shell:t.shell},...t.env===void 0?{}:{env:{...t.env}}}}:{};return{id:e,kind:t.kind,label:t.label,agentType:t.kind===`agent`?t.agentType:void 0,status:`queued`,mode:t.mode,parentSessionId:t.parentSessionId,parentTaskId:t.parentTaskId,depth:t.depth,cwd:t.cwd,updatedAt:n,unread:!1,isolation:t.kind===`agent`?t.isolation:void 0,...t.metadata?{metadata:{...t.metadata}}:{},...a,...i}}function po(e,t){return t?!(t.kind&&e.kind!==t.kind||t.status&&e.status!==t.status||t.mode&&e.mode!==t.mode):!0}function mo(e){let t=e.result?{...e.result,metadata:e.result.metadata?{...e.result.metadata}:void 0}:void 0;return{...e,metadata:e.metadata?{...e.metadata}:void 0,result:t,error:e.error?{...e.error}:void 0,schedule:e.schedule?{...e.schedule,env:e.schedule.env?{...e.schedule.env}:void 0}:void 0}}const ho=new Set([`completed`,`failed`,`cancelled`]),go=[{from:`queued`,event:`START`,to:`running`},{from:`queued`,event:`CANCEL`,to:`cancelled`},{from:`running`,event:`REQUEST_PERMISSION`,to:`waiting_permission`},{from:`running`,event:`COMPLETE`,to:`completed`},{from:`running`,event:`FAIL`,to:`failed`},{from:`running`,event:`CANCEL`,to:`cancelled`},{from:`running`,event:`SLEEP`,to:`sleeping`},{from:`waiting_permission`,event:`PERMISSION_ALLOWED`,to:`running`},{from:`waiting_permission`,event:`PERMISSION_DENIED`,to:`failed`},{from:`waiting_permission`,event:`CANCEL`,to:`cancelled`},{from:`sleeping`,event:`WAKE`,to:`running`},{from:`sleeping`,event:`CANCEL`,to:`cancelled`}];function _o(e){return ho.has(e)}function vo(e,t){let n=go.find(n=>n.from===e&&n.event===t);if(n)return n.to;throw new J(`validation`,`Invalid background task transition: ${e} + ${t} (${_o(e)?`terminal status`:`unsupported event`})`)}function yo(e,t){return e.state.status=vo(e.state.status,`START`),e.state.startedAt=t,e.state.updatedAt=t,e.state.lastActivityAt=t,mo(e.state)}function bo(e,t,n){if(e.depth>n)throw new J(`validation`,`Background task depth limit exceeded: depth=${e.depth} maxDepth=${n}`);if(!t.has(e.kind))throw to(`No background task runner registered for kind: ${e.kind}`)}function xo(e,t,n){if(e.handle=t,t.pid&&(e.state.pid=t.pid),t.logPath&&(e.state.logPath=t.logPath),t.transcriptPath&&(e.state.transcriptPath=t.transcriptPath),!t.pid&&!t.logPath&&!t.transcriptPath)return;let r=n();return e.state.updatedAt=r,e.state.lastActivityAt=r,mo(e.state)}function So(e,t,n){return e.state.status=vo(e.state.status,`COMPLETE`),e.state.result=t,io(e.state,t),e.state.unread=e.state.mode===`background`,e.state.completedAt=n,e.state.updatedAt=n,mo(e.state)}function Co(e,t,n){return e.state.status=vo(e.state.status,`FAIL`),e.state.error=no(t),e.state.completedAt=n,e.state.updatedAt=n,mo(e.state)}function wo(e,t,n){return e.state.status=vo(e.state.status,`CANCEL`),e.state.error={category:`runner`,message:t??`Background task cancelled`,recoverable:!0},e.state.completedAt=n,e.state.updatedAt=n,{task:mo(e.state)}}function To(e,t,n){if(e.state.lastActivityAt=n,t.type===`background_task_tool_start`)return e.state.currentAction=t.firstArg??t.toolName,e.state.updatedAt=n,mo(e.state);if(t.type===`background_task_tool_end`)return e.state.currentAction=t.success?void 0:t.error??t.toolName,e.state.updatedAt=n,mo(e.state);if(t.type===`background_task_sleeping`)return e.state.status=vo(e.state.status,`SLEEP`),e.state.nextFireAt=t.nextFireAt,e.state.updatedAt=n,mo(e.state);if(t.type===`background_task_waking`)return e.state.status===`sleeping`&&(e.state.status=vo(e.state.status,`WAKE`)),e.state.nextFireAt=void 0,e.state.updatedAt=n,mo(e.state)}function Eo(e){try{let t=e.runner.start({taskId:e.task.state.id,request:e.task.request,emit:e.onEvent}),n=xo(e.task,t,e.now);n&&e.onUpdated(n),e.onStarted(),t.result.then(t=>e.onCompleted(t),t=>e.onFailed(t instanceof Error?t:String(t)))}catch(t){e.onFailed(t instanceof Error?t:String(t))}}var Do=class{defaults;onTimeout;constructor(e,t){this.defaults=e,this.onTimeout=t}start(e){if(e.request.kind!==`agent`)return;this.resetIdleTimer(e);let t=e.request.maxRuntimeMs??this.defaults.agentMaxRuntimeMs;t>0&&(e.maxRuntimeTimer=setTimeout(()=>{this.onTimeout(e,`max_runtime`,`Background agent exceeded max runtime: ${t}ms`)},t),oo(e.maxRuntimeTimer))}recordActivity(e,t){e.state.status!==`running`&&e.state.status!==`waiting_permission`||(e.state.lastActivityAt=t,this.resetIdleTimer(e))}clear(e){e.idleTimer&&=(clearTimeout(e.idleTimer),void 0),e.maxRuntimeTimer&&=(clearTimeout(e.maxRuntimeTimer),void 0)}applyTextGuards(e,t){if(e.request.kind!==`agent`)return;e.outputBytes+=Buffer.byteLength(t,`utf8`),e.textDeltas+=1,e.recentText=co(`${e.recentText}${t}`,e.request.repetitionWindow??this.defaults.repetitionWindow);let n=e.request.outputLimitBytes??this.defaults.agentOutputLimitBytes;if(n>0&&e.outputBytes>n){this.onTimeout(e,`output_limit`,`Background agent exceeded output limit: ${n} bytes`);return}let r=e.request.maxTextDeltas??this.defaults.agentMaxTextDeltas;if(r>0&&e.textDeltas>r){this.onTimeout(e,`output_limit`,`Background agent exceeded text delta limit: ${r}`);return}this.isRepetitiveOutput(e,t)&&this.onTimeout(e,`repetition`,`Background agent produced repetitive output`)}resetIdleTimer(e){if(e.request.kind!==`agent`)return;e.idleTimer&&clearTimeout(e.idleTimer);let t=e.request.idleTimeoutMs??e.request.timeoutMs??this.defaults.agentIdleTimeoutMs;t<=0||(e.idleTimer=setTimeout(()=>{this.onTimeout(e,`idle`,`Background agent produced no activity for ${t}ms`)},t),oo(e.idleTimer))}isRepetitiveOutput(e,t){if(e.request.kind!==`agent`)return!1;let n=e.request.repetitionThreshold??this.defaults.repetitionThreshold;if(n<=1)return!1;let r=so(t);return r&&r===e.lastNormalizedDelta?e.repeatedDeltaCount+=1:(e.lastNormalizedDelta=r,e.repeatedDeltaCount=+!!r),e.repeatedDeltaCount>=n?!0:lo(e.recentText,n)}};function Oo(e,t){return new Do({agentIdleTimeoutMs:e.agentIdleTimeoutMs??24e4,agentMaxRuntimeMs:e.agentMaxRuntimeMs??0,agentOutputLimitBytes:e.agentOutputLimitBytes??256e3,agentMaxTextDeltas:e.agentMaxTextDeltas??2e4,repetitionWindow:e.repetitionWindow??800,repetitionThreshold:e.repetitionThreshold??8},t)}var ko=class{runners=new Map;maxConcurrent;maxDepth;now;idFactory;watchdogs;listeners=new Set;eventSink;tasks=new Map;queue=[];slotHolders=new Set;sequence=0;shuttingDown=!1;shutdownPromise;constructor(e){for(let t of e.runners)this.runners.set(t.kind,t);this.maxConcurrent=e.maxConcurrent??4,this.maxDepth=e.maxDepth??1,this.eventSink=e.eventSink,this.now=e.now??(()=>new Date().toISOString()),this.watchdogs=Oo(e,(e,t,n)=>{this.failForTimeout(e,t,n)}),this.idFactory=e.idFactory??(()=>(this.sequence+=1,`task_${this.sequence}`))}async spawn(e){if(this.shuttingDown)throw new J(`validation`,`Background task manager is shutting down`);bo(e,this.runners,this.maxDepth);let t=this.idFactory(e),n=eo();n.promise.catch(()=>void 0);let r=fo(t,e,this.now(),120);return this.tasks.set(t,{state:r,request:e,completion:n.promise,resolve:n.resolve,reject:n.reject,recentText:``,outputBytes:0,textDeltas:0,repeatedDeltaCount:0}),this.queue.push(t),this.emit({type:`background_task_created`,task:mo(r)}),this.drainQueue(),mo(r)}wait(e){return this.requireTask(e).completion}list(e){return[...this.tasks.values()].map(e=>e.state).filter(t=>po(t,e)).map(e=>mo(e))}get(e){let t=this.tasks.get(e);return t?mo(t.state):void 0}async cancel(e,t){let n=this.requireTask(e);if(_o(n.state.status))return;if(n.state.status===`queued`){this.removeFromQueue(e),this.cancelTask(n,t);return}let r=n.handle;this.cancelTask(n,t),await r?.cancel(t).catch(()=>void 0)}async close(e){if(!_o(this.requireTask(e).state.status))throw to(`Cannot close active background task: ${e}`);this.tasks.delete(e),this.emit({type:`background_task_closed`,taskId:e})}shutdown(e=`Background task manager shutdown`){return this.shutdownPromise?this.shutdownPromise:(this.shuttingDown=!0,this.shutdownPromise=Promise.all([...this.tasks.values()].filter(e=>!_o(e.state.status)).map(t=>this.cancel(t.state.id,e))).then(()=>void 0),this.shutdownPromise)}async send(e,t){let n=this.requireTask(e);if(!n.handle?.send)throw to(`Background task runner does not support input: ${e}`);await n.handle.send(t)}async readLog(e,t){let n=this.requireTask(e);if(!n.handle?.readLog)throw to(`Background task runner does not support log reads: ${e}`);return n.handle.readLog(t)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}acquireSlot(e){this.slotHolders.add(e)}releaseSlot(e){this.slotHolders.delete(e)}drainQueue(){for(;this.slotHolders.size<this.maxConcurrent;){let e=this.queue.shift();if(!e)return;let t=this.tasks.get(e);!t||t.state.status!==`queued`||this.startTask(t)}}startTask(e){let t=this.runners.get(e.request.kind);if(!t){this.failTask(e,to(`No runner for task kind: ${e.request.kind}`));return}let n=yo(e,this.now());this.acquireSlot(e.state.id),this.emit({type:`background_task_started`,task:n}),Eo({task:e,runner:t,now:this.now,onEvent:t=>this.handleRunnerEvent(e,t),onStarted:()=>this.watchdogs.start(e),onUpdated:e=>this.emit({type:`background_task_updated`,task:e}),onCompleted:t=>this.completeTask(e,t),onFailed:t=>this.failTask(e,t)})}completeTask(e,t){if(_o(e.state.status))return;this.watchdogs.clear(e);let n=So(e,t,this.now());this.releaseSlot(e.state.id),e.resolve(t),this.emit({type:`background_task_completed`,task:n}),this.shuttingDown||this.drainQueue()}failTask(e,t){if(_o(e.state.status))return;this.watchdogs.clear(e);let n=Co(e,t,this.now());this.releaseSlot(e.state.id),e.reject(to(ro(t))),this.emit({type:`background_task_failed`,task:n}),this.shuttingDown||this.drainQueue()}cancelTask(e,t){if(_o(e.state.status))return;this.watchdogs.clear(e);let n=wo(e,t,this.now());this.releaseSlot(e.state.id),e.reject(to(e.state.error?.message??`Background task cancelled`)),this.emit({type:`background_task_cancelled`,task:n.task}),this.shuttingDown||this.drainQueue()}handleRunnerEvent(e,t){if(!_o(e.state.status)){if(this.applyRunnerEventToState(e,t),t.type===`background_task_sleeping`){this.releaseSlot(e.state.id),this.shuttingDown||this.drainQueue();return}if(t.type===`background_task_waking`){this.acquireSlot(e.state.id),this.emit({type:`background_task_waking`,taskId:e.state.id,...t.instruction===void 0?{}:{instruction:t.instruction}});return}this.emit({...t,taskId:e.state.id}),t.type===`background_task_text_delta`&&this.watchdogs.applyTextGuards(e,t.delta)}}applyRunnerEventToState(e,t){let n=this.now();this.watchdogs.recordActivity(e,n);let r=To(e,t,n);r&&this.emit({type:`background_task_updated`,task:r})}async failForTimeout(e,t,n){if(_o(e.state.status))return;e.state.timeoutReason=t;let r=e.handle;this.failTask(e,new J(`timeout`,n));try{await r?.cancel(n)}catch{}}removeFromQueue(e){let t=this.queue.indexOf(e);t>=0&&this.queue.splice(t,1)}requireTask(e){let t=this.tasks.get(e);if(!t)throw to(`Unknown background task: ${e}`);return t}emit(e){this.eventSink?.(e);for(let t of this.listeners)t(e)}};const Ao=new TextEncoder;function jo(e){let t=[],n=0,r=!1,i=e.truncationMarker??`
14
14
  [output truncated]
15
15
  `;return{appendOutput(a){if(r)return;let o=e.limitBytes-n,s=Po(a);if(s<=o){t.push(a),n+=s;return}let c=Fo(a,Math.max(o,0));c.length>0&&t.push(c),t.push(i),r=!0},getOutput(){return t.join(``)}}}function Mo(e,t,n){for(let r of n.split(/\r?\n/))r.length>0&&e.push(`[${t}] ${r}`)}function No(e,t,n,r=200){let i=n?.offset??0,a=Math.min(i+r,t.length);return{taskId:e,cursor:n,nextCursor:a<t.length?{offset:a}:void 0,lines:t.slice(i,a)}}function Po(e){return Ao.encode(e).byteLength}function Fo(e,t){let n=0,r=0;for(let i of e){let e=Po(i);if(n+e>t)break;n+=e,r+=i.length}return e.slice(0,r)}function Io(e){let t=new RegExp(e.matchPattern),n=e.cooldownMs??1e3,r=e.now??(()=>Date.now()),i=``,a=-1/0;return{push(o){i+=o;let s=i.split(`
16
- `);i=s.pop()??``;for(let i of s){if(!t.test(i))continue;let o=r();o-a<n||(a=o,e.emit(`${e.agentInstruction}\n\nMatched output line: ${i.trim()}`))}}}}const Lo=process.platform!==`win32`;function Ro(e,t){if(!(e.matchPattern===void 0||e.agentInstruction===void 0||!t))return Io({matchPattern:e.matchPattern,agentInstruction:e.agentInstruction,emit:e=>t({type:`background_task_waking`,instruction:e})})}function zo(e){return{command:e.shell??`sh`,args:[`-c`,e.command]}}function Bo(e,t){return new Promise((n,r)=>{let i=t=>{e.stdin.off(`error`,i),r(t)};e.stdin.once(`error`,i),e.stdin.end(t,()=>{e.stdin.off(`error`,i),n()})})}function Vo(e={}){let t=e.killGraceMs??2e3;return{kind:`process`,start(e){if(e.request.kind!==`process`)throw new J(`runner`,`Invalid process task kind: ${e.request.kind}`);return Ho(e.taskId,e.request,t,e.emit)}}}function Ho(e,t,n,r){let a=zo(t),o=Ro(t,r),s={taskId:e,request:t,child:i(a.command,a.args,{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],detached:Lo}),logs:[],capture:jo({limitBytes:t.outputLimitBytes??3e4}),killGraceMs:n,...o?{wakeMatcher:o}:{}};return Wo(s,Uo(s))}function Uo(e){let t=!1;return new Promise((n,r)=>{let i=e.request.timeoutMs?setTimeout(()=>{Mo(e.logs,`system`,`timed out after ${e.request.timeoutMs}ms`),Qa(e.child,{processGroup:Lo,graceMs:e.killGraceMs}),s(new J(`timeout`,`Background process timed out`))},e.request.timeoutMs):void 0;function a(){i&&clearTimeout(i)}function o(r,i){t||(t=!0,a(),n({taskId:e.taskId,kind:`process`,output:e.capture.getOutput(),exitCode:r,signalCode:i}))}function s(e){t||(t=!0,a(),r(e))}Go(e),e.child.on(`error`,t=>{Mo(e.logs,`system`,t.message),s(new J(`process`,t.message))}),e.child.on(`close`,(e,t)=>{o(e??void 0,t??void 0)}),e.request.stdin!==void 0&&Bo(e.child,e.request.stdin).catch(t=>{Mo(e.logs,`system`,`stdin write failed: ${t.message}`)})})}function Wo(e,t){return{taskId:e.taskId,...e.child.pid===void 0?{}:{pid:e.child.pid},result:t,cancel:async t=>{await Ko(e,t)},send:async t=>{t.stdin&&await Bo(e.child,t.stdin)},readLog:t=>Promise.resolve(qo(e,t))}}function Go(e){e.child.stdout.on(`data`,t=>{let n=t.toString(`utf8`);e.capture.appendOutput(n),Mo(e.logs,`stdout`,n),e.wakeMatcher?.push(n)}),e.child.stderr.on(`data`,t=>{let n=t.toString(`utf8`);e.capture.appendOutput(n),Mo(e.logs,`stderr`,n),e.wakeMatcher?.push(n)})}async function Ko(e,t){Mo(e.logs,`system`,t?`cancel requested: ${t}`:`cancel requested`),await Qa(e.child,{processGroup:Lo,graceMs:e.killGraceMs})}function qo(e,t){return No(e.taskId,e.logs,t)}const Jo=process.platform!==`win32`,Yo=3e4;function Xo(e={}){return{kind:`scheduled`,start(t){if(t.request.kind!==`scheduled`)throw new J(`runner`,`Invalid scheduled task kind: ${t.request.kind}`);return Zo(t.taskId,t.request,t.emit??(()=>void 0),e)}}}function Zo(e,t,n,r){let i,a=new Promise(e=>{i=e}),o=[],s={protect:!0,...r.timezone===void 0?{}:{timezone:r.timezone}},c={taskId:e,request:t,logs:o,cancelled:!1,emit:n,resolve:i,job:new ve(t.cronExpression,s,()=>{c.cancelled||Qo(c)})};return $o(c),{taskId:e,result:a,cancel:async()=>{c.cancelled=!0,c.job.stop(),c.currentChild&&await Qa(c.currentChild,{processGroup:Jo}),i({taskId:e,kind:`scheduled`,output:jo({limitBytes:Yo}).getOutput()})},readLog:t=>Promise.resolve(No(e,o,t))}}function Qo(e){if(e.cancelled)return;e.emit(e.request.agentInstruction===void 0?{type:`background_task_waking`}:{type:`background_task_waking`,instruction:e.request.agentInstruction});let t=e.request.command;if(t===void 0){e.cancelled||$o(e);return}let n=jo({limitBytes:e.request.outputLimitBytes??Yo}),r=i(e.request.shell??`sh`,[`-c`,t],{cwd:e.request.cwd,env:{...process.env,...e.request.env??{}},stdio:[`ignore`,`pipe`,`pipe`],detached:Jo});e.currentChild=r;let a=e.request.timeoutMs===void 0?void 0:setTimeout(()=>{Mo(e.logs,`system`,`fire timed out after ${e.request.timeoutMs}ms — killing`),Qa(r,{processGroup:Jo})},e.request.timeoutMs),o=()=>{a&&clearTimeout(a)};r.stdout?.on(`data`,t=>{let r=t.toString(`utf8`);n.appendOutput(r),Mo(e.logs,`stdout`,r)}),r.stderr?.on(`data`,t=>{let r=t.toString(`utf8`);n.appendOutput(r),Mo(e.logs,`stderr`,r)}),r.on(`close`,()=>{o(),e.currentChild===r&&(e.currentChild=void 0),e.cancelled||$o(e)}),r.on(`error`,t=>{o(),e.currentChild===r&&(e.currentChild=void 0),Mo(e.logs,`system`,t.message),e.cancelled||$o(e)})}function $o(e){let t=e.job.nextRun();t!==null&&e.emit({type:`background_task_sleeping`,nextFireAt:t.toISOString()})}function es(){return[Vo(),Xo()]}function ts(e,t){let n=ut(t,e.name)?.defaults??{},r=e.model??n.model;if(!r)throw Error(`Provider ${e.name} requires model`);let i=e.apiKey??n.apiKey,a=e.options??n.options;return{name:e.name,model:r,apiKey:i===void 0?void 0:mi(i),baseURL:e.baseURL??n.baseURL,timeout:e.timeout,...a!==void 0&&{options:a}}}function ns(e,t){let n=ut(t,e.name);if(n===void 0)throw Error(`Unknown provider: ${e.name}. Currently supported: ${dt(t)}`);let r=ft(n);if(r!==void 0&&!rs(e,r))throw Error(`Provider ${e.name} requires ${as(r)}`);return n.createProvider(e)}function rs(e,t){return t.anyOf.some(t=>is(e,t))}function is(e,t){let n=e[t];return n!==void 0&&n.length>0}function as(e){return e.anyOf.join(` or `)}var os=class{backgroundTaskManager;sequence=0;processSequence=0;constructor(e){this.backgroundTaskManager=e.backgroundTaskManager??this.createBackgroundTaskManager(e)}async spawn(e){let t=await this.backgroundTaskManager.spawn(this.toBackgroundRequest(e));return this.toSubagentState(t)}async wait(e){let t=await this.backgroundTaskManager.wait(e);return{jobId:t.taskId,output:t.output,metadata:t.metadata}}list(){return this.backgroundTaskManager.list({kind:`agent`}).map(e=>this.toSubagentState(e))}get(e){let t=this.backgroundTaskManager.get(e);return t?.kind===`agent`?this.toSubagentState(t):void 0}async cancel(e,t){await this.backgroundTaskManager.cancel(e,t)}async close(e){await this.backgroundTaskManager.close(e)}async send(e,t){await this.backgroundTaskManager.send(e,{prompt:t})}async shutdown(e){await this.backgroundTaskManager.shutdown(e)}getBackgroundTaskManager(){return this.backgroundTaskManager}createBackgroundTaskManager(e){if(!e.runner)throw new J(`runner`,`SubagentManager requires a runner or backgroundTaskManager`);return new ko({runners:[ss(e.runner),...e.backgroundTaskRunners??[]],maxConcurrent:e.maxConcurrent,maxDepth:e.maxDepth,now:e.now,idFactory:e.idFactory??(e=>this.nextTaskId(e)),agentIdleTimeoutMs:e.agentIdleTimeoutMs,agentMaxRuntimeMs:e.agentMaxRuntimeMs,agentOutputLimitBytes:e.agentOutputLimitBytes,agentMaxTextDeltas:e.agentMaxTextDeltas,repetitionWindow:e.repetitionWindow,repetitionThreshold:e.repetitionThreshold})}nextTaskId(e){return e.kind===`agent`?(this.sequence+=1,`agent_${this.sequence}`):(this.processSequence+=1,`process_${this.processSequence}`)}toBackgroundRequest(e){return{kind:`agent`,agentType:e.type,label:e.label,parentSessionId:e.parentSessionId,mode:e.mode,depth:e.depth,cwd:e.cwd,prompt:e.prompt,model:e.model,isolation:e.isolation,allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,timeoutMs:e.timeoutMs,idleTimeoutMs:e.idleTimeoutMs,maxRuntimeMs:e.maxRuntimeMs,outputLimitBytes:e.outputLimitBytes,maxTextDeltas:e.maxTextDeltas,repetitionWindow:e.repetitionWindow,repetitionThreshold:e.repetitionThreshold,metadata:e.metadata,permissionPolicy:`inherit-allowlist`}}toSubagentState(e){return{id:e.id,type:e.agentType??e.label,label:e.label,parentSessionId:e.parentSessionId,status:e.status,mode:e.mode,depth:e.depth,pid:e.pid,cwd:e.cwd,isolation:e.isolation,worktreePath:e.worktreePath,branchName:e.branchName,worktreeStatus:e.worktreeStatus,worktreeNextAction:e.worktreeNextAction,worktreeBaseRevision:e.worktreeBaseRevision,parentWorktreeStatus:e.parentWorktreeStatus,promptPreview:e.promptPreview??``,currentTool:e.currentAction,logPath:e.logPath,transcriptPath:e.transcriptPath,startedAt:e.startedAt,updatedAt:e.updatedAt,completedAt:e.completedAt,timeoutReason:e.timeoutReason,result:e.result?.output,error:e.error?.message,metadata:e.metadata}}};function ss(e){return{kind:`agent`,start(t){if(t.request.kind!==`agent`)throw new J(`runner`,`Invalid subagent task kind: ${t.request.kind}`);let n=e.start({jobId:t.taskId,request:cs(t.request),emit:t.emit}),r={taskId:t.taskId,pid:n.pid,logPath:n.logPath,transcriptPath:n.transcriptPath,result:n.result.then(e=>ls(e)),cancel:e=>n.cancel(e)};if(n.send){let e=n.send;r.send=t=>e(t.prompt??``)}if(n.readLog){let e=n.readLog;r.readLog=t=>e(t)}return r}}}function cs(e){return{type:e.agentType,label:e.label,parentSessionId:e.parentSessionId,mode:e.mode,depth:e.depth,cwd:e.cwd,prompt:e.prompt,model:e.model,allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,timeoutMs:e.timeoutMs,idleTimeoutMs:e.idleTimeoutMs,maxRuntimeMs:e.maxRuntimeMs,outputLimitBytes:e.outputLimitBytes,maxTextDeltas:e.maxTextDeltas,repetitionWindow:e.repetitionWindow,repetitionThreshold:e.repetitionThreshold,isolation:e.isolation,metadata:e.metadata}}function ls(e){return{taskId:e.jobId,kind:`agent`,output:e.output,metadata:e.metadata,...e.usage?{usage:e.usage}:{}}}const us=/already exists|is already checked out|missing but already registered/i;function ds(e){return new fs(e)}var fs=class{worktreeDir;branchPrefix;idFactory;maxCreateAttempts;constructor(e={}){this.worktreeDir=e.worktreeDir??`.robota/worktrees`,this.branchPrefix=e.branchPrefix??`robota`,this.idFactory=e.idFactory??gs,this.maxCreateAttempts=e.maxCreateAttempts??5}prepare(e){if(this.maxCreateAttempts<1)throw new J(`runner`,`Git worktree creation attempts must be at least 1`);let t=hs(e.cwd),n=ps(t,[`rev-parse`,`HEAD`]).trim(),r=ps(t,[`status`,`--porcelain`]).trimEnd(),i=h(t,this.worktreeDir);D(i,{recursive:!0});let a;for(let o=0;o<this.maxCreateAttempts;o+=1){let o=_s(this.idFactory()),s=vs(e.jobId),c=`${this.branchPrefix}/${s}-${o}`,l=h(i,`${s}-${o}`);try{return ps(t,[`worktree`,`add`,`-b`,c,l,`HEAD`]),{repoRoot:t,worktreePath:l,branchName:c,baseRevision:n,parentStatus:r}}catch(e){if(a=ys(e),!bs(a))throw a}}throw new J(`runner`,`Unable to create Git worktree after ${this.maxCreateAttempts} attempts due to branch or path collisions. Last error: ${a?.message??`unknown error`}`)}isClean(e){return this.getStatus(e).trim().length===0}getStatus(e){return ps(e.worktreePath,[`status`,`--porcelain`])}remove(e){ps(e.repoRoot,[`worktree`,`remove`,`--force`,e.worktreePath]),ps(e.repoRoot,[`branch`,`-D`,e.branchName])}};function ps(e,n){try{return t(`git`,n,{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],env:ms()})}catch(e){let t=e instanceof Error?e.message:String(e);throw new J(`runner`,`git ${n.join(` `)} failed: ${t}`)}}function ms(){let e={...process.env};for(let t of Object.keys(e))t.startsWith(`GIT_`)&&delete e[t];return e}function hs(e){try{return ps(e,[`rev-parse`,`--show-toplevel`]).trim()}catch(e){throw new J(`runner`,`Worktree isolation requires a Git repository. Run from a Git worktree or request isolation "none". Details: ${e instanceof Error?e.message:String(e)}`)}}function gs(){return l().slice(0,8)}function _s(e){let t=vs(e).slice(0,8);return t.length>0?t:gs()}function vs(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``);return t.length>0?t:`agent`}function ys(e){return e instanceof Error?e:Error(String(e))}function bs(e){return us.test(e.message)}function xs(e){return new Ss(e)}var Ss=class{options;constructor(e){this.options=e}start(e){if(e.request.isolation!==`worktree`)return this.options.runner.start(e);let t=this.options.worktreeAdapter.prepare({jobId:e.jobId,cwd:e.request.cwd}),n=Ts(this.options,t,e);As(this.options,`WorktreeCreate`,e,t,!1);let r=this.startWrappedRunner(e,t,n);return this.createHandle(r,e,t,n)}startWrappedRunner(e,t,n){try{return this.options.runner.start(Cs(e,t))}catch(e){throw n.cleanupClean(),e}}createHandle(e,t,n,r){let i={jobId:e.jobId,...e.pid===void 0?{}:{pid:e.pid},result:e.result.then(e=>ws(e,this.options,n,r)).catch(e=>{throw r.cleanupClean(),e}),cancel:t=>{let n=e.cancel(t);return n.then(()=>r.cleanupClean()).catch(()=>void 0),n}},a=e.send;return a&&(i.send=e=>a(e)),i}};function Cs(e,t){return{...e,request:{...e.request,cwd:t.worktreePath,worktreePath:t.worktreePath,branchName:t.branchName}}}function ws(e,t,n,r){return r.cleanupClean()?{...e,metadata:Os(e.metadata,{isolation:`worktree`,worktreeRemoved:!0})}:{...e,metadata:Os(e.metadata,ks({isolation:`worktree`,worktreeRemoved:!1,worktreePath:n.worktreePath,branchName:n.branchName,worktreeBaseRevision:n.baseRevision,parentWorktreeStatus:n.parentStatus,worktreeStatus:Es(t,n),worktreeNextAction:Ds(n)}))}}function Ts(e,t,n){let r=!1;return{cleanupClean(){return r?!0:e.worktreeAdapter.isClean(t)?(e.worktreeAdapter.remove(t),r=!0,As(e,`WorktreeRemove`,n,t,!0),!0):!1}}}function Es(e,t){let n=e.worktreeAdapter.getStatus?.(t).trimEnd();return n&&n.length>0?n:`(dirty worktree)`}function Ds(e){let t=e.baseRevision?` based on ${e.baseRevision.slice(0,12)}`:``,n=e.parentStatus?.trim()?` Parent checkout had uncommitted changes when this worktree was created; review the base before merging.`:``;return`Review ${e.worktreePath}, then merge or delete branch ${e.branchName}${t}.${n}`}function Os(e,t){return{...e??{},...t}}function ks(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function As(e,t,n,r,i){let a={session_id:n.request.parentSessionId,cwd:r.repoRoot,hook_event_name:t,tool_name:`Agent`,tool_input:{jobId:n.jobId,agentType:n.request.type,worktreePath:r.worktreePath,branchName:r.branchName,removed:i}};qa(e.hooks,t,a,e.hookTypeExecutors).catch(()=>void 0)}const js=/^[A-Za-z]:[\\/]/,Ms=/'/g;async function Ns(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);let r=Gs(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=Ps(a),s=Ks(r,t);i.push(await Fs(e,t,s,r,o,n))}return{entries:i}}function Ps(e){if(e.length===0)throw Error(`workspace manifest path must not be empty`);if(e.includes(`\0`))throw Error(`workspace manifest path must not contain NUL bytes`);if(e.startsWith(`/`)||e.startsWith(`\\`)||js.test(e))throw Error(`workspace manifest path must be workspace-relative`);let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);if(t.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);if(t.some(e=>e===`..`))throw Error(`workspace manifest path cannot contain traversal segments`);let n=t.filter(e=>e!==`.`);if(n.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);return n.join(`/`)}async function Fs(e,t,n,r,i,a){switch(i.type){case`file`:return await Vs(e,n,r,i.content),Is(t,i.type);case`dir`:return await Hs(e,n),Is(t,i.type);case`localFile`:return await Ls(e,i.src,n,r,a),Is(t,i.type);case`localDir`:return await Rs(e,i.src,n,a),Is(t,i.type);case`gitRepo`:return await Bs(e,i,n),Is(t,i.type);case`s3Mount`:case`gcsMount`:case`r2Mount`:case`azureBlobMount`:return{path:t,type:i.type,status:`unsupported`,message:`${i.type} requires a provider-specific sandbox adapter.`};default:return Js(i)}}function Is(e,t){return{path:e,type:t,status:`applied`}}async function Ls(e,t,n,r,i){await Vs(e,n,r,await de(Ws(t,i.hostRoot),`utf8`))}async function Rs(e,t,n,r){await zs(e,Ws(t,r.hostRoot),n)}async function zs(e,t,n){await Hs(e,n);let r=await fe(t,{withFileTypes:!0});for(let i of r){let r=h(t,i.name),a=Ks(n,i.name);if(i.isDirectory()){await zs(e,r,a);continue}if(i.isFile()){let t=await de(r,`utf8`);await e.writeFile(a,t)}}}async function Bs(e,t,n){await Us(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${qs(t.ref)}`:``} ${qs(t.url)} ${qs(n)}`)}async function Vs(e,t,n,r){let i=g.dirname(t);i!==n&&await Hs(e,i),await e.writeFile(t,r)}async function Hs(e,t){await Us(e,`mkdir -p ${qs(t)}`)}async function Us(e,t){let n=await e.run(t);if(n.exitCode!==0)throw Error(`workspace manifest command failed: ${t}\n${n.stderr??n.stdout}`)}function Ws(e,t){return m(e)?v(e):v(t??process.cwd(),e)}function Gs(e){let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Ks(e,t){let n=Gs(e);return n===`/`?`/${t}`:`${n}/${t}`}function qs(e){return`'${e.replace(Ms,`'\\''`)}'`}function Js(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}function Ys(e,t,n){switch(n.type){case`string`:if(typeof t!=`string`)return`Parameter "${e}" must be a string, got ${typeof t}`;break;case`number`:if(typeof t!=`number`||isNaN(t))return`Parameter "${e}" must be a number, got ${typeof t}`;break;case`boolean`:if(typeof t!=`boolean`)return`Parameter "${e}" must be a boolean, got ${typeof t}`;break;case`array`:if(!Array.isArray(t))return`Parameter "${e}" must be an array, got ${typeof t}`;if(n.items)for(let r=0;r<t.length;r++){let i=Ys(`${e}[${r}]`,t[r],n.items);if(i)return i}break;case`object`:if(typeof t!=`object`||!t||Array.isArray(t))return`Parameter "${e}" must be an object, got ${typeof t}`;break}if(n.enum&&n.enum.length>0){let r=n.enum,i=!1;for(let e of r)if(t===e){i=!0;break}if(!i)return`Parameter "${e}" must be one of: ${r.join(`, `)}, got ${t}`}}function Xs(e,t,n,r){let i=[];for(let n of t)n in e||i.push(`Missing required parameter: ${n}`);for(let[t,a]of Object.entries(e)){let e=n[t];if(!e){if(r===!0)continue;if(r&&typeof r==`object`){let e=Ys(t,a,r);e&&i.push(e);continue}i.push(`Unknown parameter: ${t}`);continue}let o=Ys(t,a,e);o&&i.push(o)}return i}function Zs(e,t,n,r){let i=Xs(e,t,n,r);return{isValid:i.length===0,errors:i}}var Qs=class{schema;fn;eventService;constructor(e,t){this.schema=e,this.fn=t,this.validateConstructorInputs()}getName(){return this.schema.name}setEventService(e){this.eventService=e}async execute(e,t){let n=this.schema.name;if(!this.validate(e))throw new G(`Invalid parameters for tool "${n}": ${Xs(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties).join(`, `)}`);let r=Date.now(),i;try{i=await this.fn(e,t)}catch(r){throw r instanceof un||r instanceof G?r:new un(`Function tool execution failed: ${r instanceof Error?r.message:String(r)}`,n,r instanceof Error?r:Error(String(r)),{parameterCount:Object.keys(e||{}).length,hasContext:!!t})}let a=Date.now()-r;return{success:!0,data:i,metadata:{executionTime:a,toolName:n,parameters:e}}}validate(e){return Xs(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties).length===0}validateParameters(e){return Zs(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties)}getDescription(){return this.schema.description}validateConstructorInputs(){if(!this.schema)throw new G(`Tool schema is required`);if(!this.fn||typeof this.fn!=`function`)throw new G(`Tool function is required and must be a function`);if(!this.schema.name)throw new G(`Tool schema must have a name`)}};function $s(e,t,n,r){return new Qs({name:e,description:t,parameters:Xr(n)},async(e,t)=>{let i=n.safeParse(e);if(!i.success)throw new G(`Zod validation failed: ${i.error}`);let a=await r(i.data,t);return typeof a==`string`?a:JSON.stringify(a)})}const ec=process.platform!==`win32`,tc=A.object({command:A.string().describe(`The shell command to execute`),timeout:A.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:A.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});function nc(e){return[`Executes a command in the host shell and returns its output.`,``,`Active shell: ${e.label}. ${e.syntaxHint}`,``,`The working directory persists between commands, but shell state does not.`,``,"IMPORTANT: Avoid using this tool to run `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands. Instead, use the appropriate dedicated tool:",` - File search: Use Glob (NOT find or ls)`,` - Content search: Use Grep (NOT grep or rg)`,` - Read files: Use Read (NOT cat/head/tail)`,` - Edit files: Use Edit (NOT sed/awk)`,``,`For simple commands, keep the description brief (5-10 words). For complex commands, include enough context to clarify what the command does.`,``,`Output is limited to 30,000 characters. Longer output will be middle-truncated.`].join(`
17
- `)}async function rc(e,t,n,r){try{let i=await r.sandboxClient.run(e,{timeoutMs:t,workingDirectory:n}),a={success:!0,output:i.stderr?`${i.stdout}\nstderr:\n${i.stderr}`:i.stdout,exitCode:i.exitCode};return JSON.stringify(a)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}async function ic(e,t={},n){let{command:r,timeout:a=12e4,workingDirectory:o}=e,s=Math.min(a,6e5);if(t.sandboxClient)return rc(r,s,o,t);let c=Yr();return n?.aborted?JSON.stringify({success:!1,output:``,error:`Aborted before start`}):new Promise(e=>{let t=[],a=[],l=!1,u=!1,d=i(c.command,c.commandArgs(r),{cwd:o??process.cwd(),env:process.env,stdio:[`pipe`,`pipe`,`pipe`],detached:ec});d.stdin?.end(),d.stdout.on(`data`,e=>{t.push(e)}),d.stderr.on(`data`,e=>{a.push(e)});let f=setTimeout(()=>{l=!0,Qa(d,{processGroup:ec}),p({success:!1,output:Buffer.concat(t).toString(`utf8`),error:`Command timed out after ${s}ms`})},s);function p(t){u||(u=!0,clearTimeout(f),n?.removeEventListener(`abort`,m),e(JSON.stringify(t)))}function m(){Qa(d,{processGroup:ec}),p({success:!1,output:Buffer.concat(t).toString(`utf8`),error:`Aborted`})}n?.addEventListener(`abort`,m,{once:!0}),d.on(`error`,e=>{p({success:!1,output:``,error:e.message})}),d.on(`close`,e=>{if(l){p({success:!1,output:Buffer.concat(t).toString(`utf8`),error:`Command timed out after ${s}ms`,exitCode:e??void 0});return}let n=Buffer.concat(t).toString(`utf8`),r=Buffer.concat(a).toString(`utf8`),i=e??0;p({success:!0,output:r?`${n}\nstderr:\n${r}`:n,exitCode:i})})})}function ac(e,t){return $s(e,nc(Yr()),tc,async(e,n)=>ic(e,t,n?.signal))}function oc(e={}){return ac(`Shell`,e)}function sc(e={}){return ac(`Bash`,e)}oc(),sc();function cc(e,t){if(t===void 0)return;let n=v(e),r=v(t);if(n!==r&&!n.startsWith(r+y)){let t={success:!1,output:``,error:`Access denied: "${e}" is outside the working directory`};return JSON.stringify(t)}}const lc=2e3,uc=A.object({filePath:A.string().describe(`The absolute path to the file to read`),offset:A.number().optional().describe(`The line number to start reading from (1-based). Only provide if the file is too large to read at once`),limit:A.number().optional().describe(`The number of lines to read (default: ${lc}). Only provide if the file is too large to read at once`)});function dc(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}function fc(e,t){let n=t+e.length-1,r=String(n).length;return e.map((e,n)=>`${String(t+n).padStart(r,` `)}\t${e}`).join(`
16
+ `);i=s.pop()??``;for(let i of s){if(!t.test(i))continue;let o=r();o-a<n||(a=o,e.emit(`${e.agentInstruction}\n\nMatched output line: ${i.trim()}`))}}}}const Lo=process.platform!==`win32`;function Ro(e,t){if(!(e.matchPattern===void 0||e.agentInstruction===void 0||!t))return Io({matchPattern:e.matchPattern,agentInstruction:e.agentInstruction,emit:e=>t({type:`background_task_waking`,instruction:e})})}function zo(e){return{command:e.shell??`sh`,args:[`-c`,e.command]}}function Bo(e,t){return new Promise((n,r)=>{let i=t=>{e.stdin.off(`error`,i),r(t)};e.stdin.once(`error`,i),e.stdin.end(t,()=>{e.stdin.off(`error`,i),n()})})}function Vo(e={}){let t=e.killGraceMs??2e3;return{kind:`process`,start(e){if(e.request.kind!==`process`)throw new J(`runner`,`Invalid process task kind: ${e.request.kind}`);return Ho(e.taskId,e.request,t,e.emit)}}}function Ho(e,t,n,r){let a=zo(t),o=Ro(t,r),s={taskId:e,request:t,child:i(a.command,a.args,{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],detached:Lo}),logs:[],capture:jo({limitBytes:t.outputLimitBytes??3e4}),killGraceMs:n,...o?{wakeMatcher:o}:{}};return Wo(s,Uo(s))}function Uo(e){let t=!1;return new Promise((n,r)=>{let i=e.request.timeoutMs?setTimeout(()=>{Mo(e.logs,`system`,`timed out after ${e.request.timeoutMs}ms`),Qa(e.child,{processGroup:Lo,graceMs:e.killGraceMs}),s(new J(`timeout`,`Background process timed out`))},e.request.timeoutMs):void 0;function a(){i&&clearTimeout(i)}function o(r,i){t||(t=!0,a(),n({taskId:e.taskId,kind:`process`,output:e.capture.getOutput(),exitCode:r,signalCode:i}))}function s(e){t||(t=!0,a(),r(e))}Go(e),e.child.on(`error`,t=>{Mo(e.logs,`system`,t.message),s(new J(`process`,t.message))}),e.child.on(`close`,(e,t)=>{o(e??void 0,t??void 0)}),e.request.stdin!==void 0&&Bo(e.child,e.request.stdin).catch(t=>{Mo(e.logs,`system`,`stdin write failed: ${t.message}`)})})}function Wo(e,t){return{taskId:e.taskId,...e.child.pid===void 0?{}:{pid:e.child.pid},result:t,cancel:async t=>{await Ko(e,t)},send:async t=>{t.stdin&&await Bo(e.child,t.stdin)},readLog:t=>Promise.resolve(qo(e,t))}}function Go(e){e.child.stdout.on(`data`,t=>{let n=t.toString(`utf8`);e.capture.appendOutput(n),Mo(e.logs,`stdout`,n),e.wakeMatcher?.push(n)}),e.child.stderr.on(`data`,t=>{let n=t.toString(`utf8`);e.capture.appendOutput(n),Mo(e.logs,`stderr`,n),e.wakeMatcher?.push(n)})}async function Ko(e,t){Mo(e.logs,`system`,t?`cancel requested: ${t}`:`cancel requested`),await Qa(e.child,{processGroup:Lo,graceMs:e.killGraceMs})}function qo(e,t){return No(e.taskId,e.logs,t)}const Jo=process.platform!==`win32`,Yo=3e4;function Xo(e={}){return{kind:`scheduled`,start(t){if(t.request.kind!==`scheduled`)throw new J(`runner`,`Invalid scheduled task kind: ${t.request.kind}`);return Zo(t.taskId,t.request,t.emit??(()=>void 0),e)}}}function Zo(e,t,n,r){let i,a=new Promise(e=>{i=e}),o=[],s={protect:!0,...r.timezone===void 0?{}:{timezone:r.timezone}},c={taskId:e,request:t,logs:o,cancelled:!1,emit:n,resolve:i,job:new _e(t.cronExpression,s,()=>{c.cancelled||Qo(c)})};return $o(c),{taskId:e,result:a,cancel:async()=>{c.cancelled=!0,c.job.stop(),c.currentChild&&await Qa(c.currentChild,{processGroup:Jo}),i({taskId:e,kind:`scheduled`,output:jo({limitBytes:Yo}).getOutput()})},readLog:t=>Promise.resolve(No(e,o,t))}}function Qo(e){if(e.cancelled)return;e.emit(e.request.agentInstruction===void 0?{type:`background_task_waking`}:{type:`background_task_waking`,instruction:e.request.agentInstruction});let t=e.request.command;if(t===void 0){e.cancelled||$o(e);return}let n=jo({limitBytes:e.request.outputLimitBytes??Yo}),r=i(e.request.shell??`sh`,[`-c`,t],{cwd:e.request.cwd,env:{...process.env,...e.request.env??{}},stdio:[`ignore`,`pipe`,`pipe`],detached:Jo});e.currentChild=r;let a=e.request.timeoutMs===void 0?void 0:setTimeout(()=>{Mo(e.logs,`system`,`fire timed out after ${e.request.timeoutMs}ms — killing`),Qa(r,{processGroup:Jo})},e.request.timeoutMs),o=()=>{a&&clearTimeout(a)};r.stdout?.on(`data`,t=>{let r=t.toString(`utf8`);n.appendOutput(r),Mo(e.logs,`stdout`,r)}),r.stderr?.on(`data`,t=>{let r=t.toString(`utf8`);n.appendOutput(r),Mo(e.logs,`stderr`,r)}),r.on(`close`,()=>{o(),e.currentChild===r&&(e.currentChild=void 0),e.cancelled||$o(e)}),r.on(`error`,t=>{o(),e.currentChild===r&&(e.currentChild=void 0),Mo(e.logs,`system`,t.message),e.cancelled||$o(e)})}function $o(e){let t=e.job.nextRun();t!==null&&e.emit({type:`background_task_sleeping`,nextFireAt:t.toISOString()})}function es(){return[Vo(),Xo()]}function ts(e,t){let n=ut(t,e.name)?.defaults??{},r=e.model??n.model;if(!r)throw Error(`Provider ${e.name} requires model`);let i=e.apiKey??n.apiKey,a=e.options??n.options;return{name:e.name,model:r,apiKey:i===void 0?void 0:mi(i),baseURL:e.baseURL??n.baseURL,timeout:e.timeout,...a!==void 0&&{options:a}}}function ns(e,t){let n=ut(t,e.name);if(n===void 0)throw Error(`Unknown provider: ${e.name}. Currently supported: ${dt(t)}`);let r=ft(n);if(r!==void 0&&!rs(e,r))throw Error(`Provider ${e.name} requires ${as(r)}`);return n.createProvider(e)}function rs(e,t){return t.anyOf.some(t=>is(e,t))}function is(e,t){let n=e[t];return n!==void 0&&n.length>0}function as(e){return e.anyOf.join(` or `)}var os=class{backgroundTaskManager;sequence=0;processSequence=0;constructor(e){this.backgroundTaskManager=e.backgroundTaskManager??this.createBackgroundTaskManager(e)}async spawn(e){let t=await this.backgroundTaskManager.spawn(this.toBackgroundRequest(e));return this.toSubagentState(t)}async wait(e){let t=await this.backgroundTaskManager.wait(e);return{jobId:t.taskId,output:t.output,metadata:t.metadata}}list(){return this.backgroundTaskManager.list({kind:`agent`}).map(e=>this.toSubagentState(e))}get(e){let t=this.backgroundTaskManager.get(e);return t?.kind===`agent`?this.toSubagentState(t):void 0}async cancel(e,t){await this.backgroundTaskManager.cancel(e,t)}async close(e){await this.backgroundTaskManager.close(e)}async send(e,t){await this.backgroundTaskManager.send(e,{prompt:t})}async shutdown(e){await this.backgroundTaskManager.shutdown(e)}getBackgroundTaskManager(){return this.backgroundTaskManager}createBackgroundTaskManager(e){if(!e.runner)throw new J(`runner`,`SubagentManager requires a runner or backgroundTaskManager`);return new ko({runners:[ss(e.runner),...e.backgroundTaskRunners??[]],maxConcurrent:e.maxConcurrent,maxDepth:e.maxDepth,now:e.now,idFactory:e.idFactory??(e=>this.nextTaskId(e)),agentIdleTimeoutMs:e.agentIdleTimeoutMs,agentMaxRuntimeMs:e.agentMaxRuntimeMs,agentOutputLimitBytes:e.agentOutputLimitBytes,agentMaxTextDeltas:e.agentMaxTextDeltas,repetitionWindow:e.repetitionWindow,repetitionThreshold:e.repetitionThreshold})}nextTaskId(e){return e.kind===`agent`?(this.sequence+=1,`agent_${this.sequence}`):(this.processSequence+=1,`process_${this.processSequence}`)}toBackgroundRequest(e){return{kind:`agent`,agentType:e.type,label:e.label,parentSessionId:e.parentSessionId,mode:e.mode,depth:e.depth,cwd:e.cwd,prompt:e.prompt,model:e.model,isolation:e.isolation,allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,timeoutMs:e.timeoutMs,idleTimeoutMs:e.idleTimeoutMs,maxRuntimeMs:e.maxRuntimeMs,outputLimitBytes:e.outputLimitBytes,maxTextDeltas:e.maxTextDeltas,repetitionWindow:e.repetitionWindow,repetitionThreshold:e.repetitionThreshold,metadata:e.metadata,permissionPolicy:`inherit-allowlist`}}toSubagentState(e){return{id:e.id,type:e.agentType??e.label,label:e.label,parentSessionId:e.parentSessionId,status:e.status,mode:e.mode,depth:e.depth,pid:e.pid,cwd:e.cwd,isolation:e.isolation,worktreePath:e.worktreePath,branchName:e.branchName,worktreeStatus:e.worktreeStatus,worktreeNextAction:e.worktreeNextAction,worktreeBaseRevision:e.worktreeBaseRevision,parentWorktreeStatus:e.parentWorktreeStatus,promptPreview:e.promptPreview??``,currentTool:e.currentAction,logPath:e.logPath,transcriptPath:e.transcriptPath,startedAt:e.startedAt,updatedAt:e.updatedAt,completedAt:e.completedAt,timeoutReason:e.timeoutReason,result:e.result?.output,error:e.error?.message,metadata:e.metadata}}};function ss(e){return{kind:`agent`,start(t){if(t.request.kind!==`agent`)throw new J(`runner`,`Invalid subagent task kind: ${t.request.kind}`);let n=e.start({jobId:t.taskId,request:cs(t.request),emit:t.emit}),r={taskId:t.taskId,pid:n.pid,logPath:n.logPath,transcriptPath:n.transcriptPath,result:n.result.then(e=>ls(e)),cancel:e=>n.cancel(e)};if(n.send){let e=n.send;r.send=t=>e(t.prompt??``)}if(n.readLog){let e=n.readLog;r.readLog=t=>e(t)}return r}}}function cs(e){return{type:e.agentType,label:e.label,parentSessionId:e.parentSessionId,mode:e.mode,depth:e.depth,cwd:e.cwd,prompt:e.prompt,model:e.model,allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,timeoutMs:e.timeoutMs,idleTimeoutMs:e.idleTimeoutMs,maxRuntimeMs:e.maxRuntimeMs,outputLimitBytes:e.outputLimitBytes,maxTextDeltas:e.maxTextDeltas,repetitionWindow:e.repetitionWindow,repetitionThreshold:e.repetitionThreshold,isolation:e.isolation,metadata:e.metadata}}function ls(e){return{taskId:e.jobId,kind:`agent`,output:e.output,metadata:e.metadata,...e.usage?{usage:e.usage}:{}}}const us=/already exists|is already checked out|missing but already registered/i;function ds(e){return new fs(e)}var fs=class{worktreeDir;branchPrefix;idFactory;maxCreateAttempts;constructor(e={}){this.worktreeDir=e.worktreeDir??`.robota/worktrees`,this.branchPrefix=e.branchPrefix??`robota`,this.idFactory=e.idFactory??gs,this.maxCreateAttempts=e.maxCreateAttempts??5}prepare(e){if(this.maxCreateAttempts<1)throw new J(`runner`,`Git worktree creation attempts must be at least 1`);let t=hs(e.cwd),n=ps(t,[`rev-parse`,`HEAD`]).trim(),r=ps(t,[`status`,`--porcelain`]).trimEnd(),i=h(t,this.worktreeDir);O(i,{recursive:!0});let a;for(let o=0;o<this.maxCreateAttempts;o+=1){let o=_s(this.idFactory()),s=vs(e.jobId),c=`${this.branchPrefix}/${s}-${o}`,l=h(i,`${s}-${o}`);try{return ps(t,[`worktree`,`add`,`-b`,c,l,`HEAD`]),{repoRoot:t,worktreePath:l,branchName:c,baseRevision:n,parentStatus:r}}catch(e){if(a=ys(e),!bs(a))throw a}}throw new J(`runner`,`Unable to create Git worktree after ${this.maxCreateAttempts} attempts due to branch or path collisions. Last error: ${a?.message??`unknown error`}`)}isClean(e){return this.getStatus(e).trim().length===0}getStatus(e){return ps(e.worktreePath,[`status`,`--porcelain`])}remove(e){ps(e.repoRoot,[`worktree`,`remove`,`--force`,e.worktreePath]),ps(e.repoRoot,[`branch`,`-D`,e.branchName])}};function ps(e,n){try{return t(`git`,n,{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],env:ms()})}catch(e){let t=e instanceof Error?e.message:String(e);throw new J(`runner`,`git ${n.join(` `)} failed: ${t}`)}}function ms(){let e={...process.env};for(let t of Object.keys(e))t.startsWith(`GIT_`)&&delete e[t];return e}function hs(e){try{return ps(e,[`rev-parse`,`--show-toplevel`]).trim()}catch(e){throw new J(`runner`,`Worktree isolation requires a Git repository. Run from a Git worktree or request isolation "none". Details: ${e instanceof Error?e.message:String(e)}`)}}function gs(){return l().slice(0,8)}function _s(e){let t=vs(e).slice(0,8);return t.length>0?t:gs()}function vs(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``);return t.length>0?t:`agent`}function ys(e){return e instanceof Error?e:Error(String(e))}function bs(e){return us.test(e.message)}function xs(e){return new Ss(e)}var Ss=class{options;constructor(e){this.options=e}start(e){if(e.request.isolation!==`worktree`)return this.options.runner.start(e);let t=this.options.worktreeAdapter.prepare({jobId:e.jobId,cwd:e.request.cwd}),n=Ts(this.options,t,e);As(this.options,`WorktreeCreate`,e,t,!1);let r=this.startWrappedRunner(e,t,n);return this.createHandle(r,e,t,n)}startWrappedRunner(e,t,n){try{return this.options.runner.start(Cs(e,t))}catch(e){throw n.cleanupClean(),e}}createHandle(e,t,n,r){let i={jobId:e.jobId,...e.pid===void 0?{}:{pid:e.pid},result:e.result.then(e=>ws(e,this.options,n,r)).catch(e=>{throw r.cleanupClean(),e}),cancel:t=>{let n=e.cancel(t);return n.then(()=>r.cleanupClean()).catch(()=>void 0),n}},a=e.send;return a&&(i.send=e=>a(e)),i}};function Cs(e,t){return{...e,request:{...e.request,cwd:t.worktreePath,worktreePath:t.worktreePath,branchName:t.branchName}}}function ws(e,t,n,r){return r.cleanupClean()?{...e,metadata:Os(e.metadata,{isolation:`worktree`,worktreeRemoved:!0})}:{...e,metadata:Os(e.metadata,ks({isolation:`worktree`,worktreeRemoved:!1,worktreePath:n.worktreePath,branchName:n.branchName,worktreeBaseRevision:n.baseRevision,parentWorktreeStatus:n.parentStatus,worktreeStatus:Es(t,n),worktreeNextAction:Ds(n)}))}}function Ts(e,t,n){let r=!1;return{cleanupClean(){return r?!0:e.worktreeAdapter.isClean(t)?(e.worktreeAdapter.remove(t),r=!0,As(e,`WorktreeRemove`,n,t,!0),!0):!1}}}function Es(e,t){let n=e.worktreeAdapter.getStatus?.(t).trimEnd();return n&&n.length>0?n:`(dirty worktree)`}function Ds(e){let t=e.baseRevision?` based on ${e.baseRevision.slice(0,12)}`:``,n=e.parentStatus?.trim()?` Parent checkout had uncommitted changes when this worktree was created; review the base before merging.`:``;return`Review ${e.worktreePath}, then merge or delete branch ${e.branchName}${t}.${n}`}function Os(e,t){return{...e??{},...t}}function ks(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function As(e,t,n,r,i){let a={session_id:n.request.parentSessionId,cwd:r.repoRoot,hook_event_name:t,tool_name:`Agent`,tool_input:{jobId:n.jobId,agentType:n.request.type,worktreePath:r.worktreePath,branchName:r.branchName,removed:i}};qa(e.hooks,t,a,e.hookTypeExecutors).catch(()=>void 0)}const js=/^[A-Za-z]:[\\/]/,Ms=/'/g;async function Ns(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);let r=Gs(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=Ps(a),s=Ks(r,t);i.push(await Fs(e,t,s,r,o,n))}return{entries:i}}function Ps(e){if(e.length===0)throw Error(`workspace manifest path must not be empty`);if(e.includes(`\0`))throw Error(`workspace manifest path must not contain NUL bytes`);if(e.startsWith(`/`)||e.startsWith(`\\`)||js.test(e))throw Error(`workspace manifest path must be workspace-relative`);let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);if(t.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);if(t.some(e=>e===`..`))throw Error(`workspace manifest path cannot contain traversal segments`);let n=t.filter(e=>e!==`.`);if(n.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);return n.join(`/`)}async function Fs(e,t,n,r,i,a){switch(i.type){case`file`:return await Vs(e,n,r,i.content),Is(t,i.type);case`dir`:return await Hs(e,n),Is(t,i.type);case`localFile`:return await Ls(e,i.src,n,r,a),Is(t,i.type);case`localDir`:return await Rs(e,i.src,n,a),Is(t,i.type);case`gitRepo`:return await Bs(e,i,n),Is(t,i.type);case`s3Mount`:case`gcsMount`:case`r2Mount`:case`azureBlobMount`:return{path:t,type:i.type,status:`unsupported`,message:`${i.type} requires a provider-specific sandbox adapter.`};default:return Js(i)}}function Is(e,t){return{path:e,type:t,status:`applied`}}async function Ls(e,t,n,r,i){await Vs(e,n,r,await ue(Ws(t,i.hostRoot),`utf8`))}async function Rs(e,t,n,r){await zs(e,Ws(t,r.hostRoot),n)}async function zs(e,t,n){await Hs(e,n);let r=await de(t,{withFileTypes:!0});for(let i of r){let r=h(t,i.name),a=Ks(n,i.name);if(i.isDirectory()){await zs(e,r,a);continue}if(i.isFile()){let t=await ue(r,`utf8`);await e.writeFile(a,t)}}}async function Bs(e,t,n){await Us(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${qs(t.ref)}`:``} ${qs(t.url)} ${qs(n)}`)}async function Vs(e,t,n,r){let i=g.dirname(t);i!==n&&await Hs(e,i),await e.writeFile(t,r)}async function Hs(e,t){await Us(e,`mkdir -p ${qs(t)}`)}async function Us(e,t){let n=await e.run(t);if(n.exitCode!==0)throw Error(`workspace manifest command failed: ${t}\n${n.stderr??n.stdout}`)}function Ws(e,t){return m(e)?v(e):v(t??process.cwd(),e)}function Gs(e){let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Ks(e,t){let n=Gs(e);return n===`/`?`/${t}`:`${n}/${t}`}function qs(e){return`'${e.replace(Ms,`'\\''`)}'`}function Js(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}function Ys(e,t,n){switch(n.type){case`string`:if(typeof t!=`string`)return`Parameter "${e}" must be a string, got ${typeof t}`;break;case`number`:if(typeof t!=`number`||isNaN(t))return`Parameter "${e}" must be a number, got ${typeof t}`;break;case`boolean`:if(typeof t!=`boolean`)return`Parameter "${e}" must be a boolean, got ${typeof t}`;break;case`array`:if(!Array.isArray(t))return`Parameter "${e}" must be an array, got ${typeof t}`;if(n.items)for(let r=0;r<t.length;r++){let i=Ys(`${e}[${r}]`,t[r],n.items);if(i)return i}break;case`object`:if(typeof t!=`object`||!t||Array.isArray(t))return`Parameter "${e}" must be an object, got ${typeof t}`;break}if(n.enum&&n.enum.length>0){let r=n.enum,i=!1;for(let e of r)if(t===e){i=!0;break}if(!i)return`Parameter "${e}" must be one of: ${r.join(`, `)}, got ${t}`}}function Xs(e,t,n,r){let i=[];for(let n of t)n in e||i.push(`Missing required parameter: ${n}`);for(let[t,a]of Object.entries(e)){let e=n[t];if(!e){if(r===!0)continue;if(r&&typeof r==`object`){let e=Ys(t,a,r);e&&i.push(e);continue}i.push(`Unknown parameter: ${t}`);continue}let o=Ys(t,a,e);o&&i.push(o)}return i}function Zs(e,t,n,r){let i=Xs(e,t,n,r);return{isValid:i.length===0,errors:i}}var Qs=class{schema;fn;eventService;constructor(e,t){this.schema=e,this.fn=t,this.validateConstructorInputs()}getName(){return this.schema.name}setEventService(e){this.eventService=e}async execute(e,t){let n=this.schema.name;if(!this.validate(e))throw new G(`Invalid parameters for tool "${n}": ${Xs(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties).join(`, `)}`);let r=Date.now(),i;try{i=await this.fn(e,t)}catch(r){throw r instanceof un||r instanceof G?r:new un(`Function tool execution failed: ${r instanceof Error?r.message:String(r)}`,n,r instanceof Error?r:Error(String(r)),{parameterCount:Object.keys(e||{}).length,hasContext:!!t})}let a=Date.now()-r;return{success:!0,data:i,metadata:{executionTime:a,toolName:n,parameters:e}}}validate(e){return Xs(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties).length===0}validateParameters(e){return Zs(e,this.schema.parameters.required||[],this.schema.parameters.properties||{},this.schema.parameters.additionalProperties)}getDescription(){return this.schema.description}validateConstructorInputs(){if(!this.schema)throw new G(`Tool schema is required`);if(!this.fn||typeof this.fn!=`function`)throw new G(`Tool function is required and must be a function`);if(!this.schema.name)throw new G(`Tool schema must have a name`)}};function $s(e,t,n,r){return new Qs({name:e,description:t,parameters:Xr(n)},async(e,t)=>{let i=n.safeParse(e);if(!i.success)throw new G(`Zod validation failed: ${i.error}`);let a=await r(i.data,t);return typeof a==`string`?a:JSON.stringify(a)})}const ec=process.platform!==`win32`,tc=j.object({command:j.string().describe(`The shell command to execute`),timeout:j.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:j.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});function nc(e){return[`Executes a command in the host shell and returns its output.`,``,`Active shell: ${e.label}. ${e.syntaxHint}`,``,`The working directory persists between commands, but shell state does not.`,``,"IMPORTANT: Avoid using this tool to run `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands. Instead, use the appropriate dedicated tool:",` - File search: Use Glob (NOT find or ls)`,` - Content search: Use Grep (NOT grep or rg)`,` - Read files: Use Read (NOT cat/head/tail)`,` - Edit files: Use Edit (NOT sed/awk)`,``,`For simple commands, keep the description brief (5-10 words). For complex commands, include enough context to clarify what the command does.`,``,`Output is limited to 30,000 characters. Longer output will be middle-truncated.`].join(`
17
+ `)}async function rc(e,t,n,r){try{let i=await r.sandboxClient.run(e,{timeoutMs:t,workingDirectory:n}),a={success:!0,output:i.stderr?`${i.stdout}\nstderr:\n${i.stderr}`:i.stdout,exitCode:i.exitCode};return JSON.stringify(a)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}async function ic(e,t={},n){let{command:r,timeout:a=12e4,workingDirectory:o}=e,s=Math.min(a,6e5);if(t.sandboxClient)return rc(r,s,o,t);let c=Yr();return n?.aborted?JSON.stringify({success:!1,output:``,error:`Aborted before start`}):new Promise(e=>{let t=[],a=[],l=!1,u=!1,d=i(c.command,c.commandArgs(r),{cwd:o??process.cwd(),env:process.env,stdio:[`pipe`,`pipe`,`pipe`],detached:ec});d.stdin?.end(),d.stdout.on(`data`,e=>{t.push(e)}),d.stderr.on(`data`,e=>{a.push(e)});let f=setTimeout(()=>{l=!0,Qa(d,{processGroup:ec}),p({success:!1,output:Buffer.concat(t).toString(`utf8`),error:`Command timed out after ${s}ms`})},s);function p(t){u||(u=!0,clearTimeout(f),n?.removeEventListener(`abort`,m),e(JSON.stringify(t)))}function m(){Qa(d,{processGroup:ec}),p({success:!1,output:Buffer.concat(t).toString(`utf8`),error:`Aborted`})}n?.addEventListener(`abort`,m,{once:!0}),d.on(`error`,e=>{p({success:!1,output:``,error:e.message})}),d.on(`close`,e=>{if(l){p({success:!1,output:Buffer.concat(t).toString(`utf8`),error:`Command timed out after ${s}ms`,exitCode:e??void 0});return}let n=Buffer.concat(t).toString(`utf8`),r=Buffer.concat(a).toString(`utf8`),i=e??0;p({success:!0,output:r?`${n}\nstderr:\n${r}`:n,exitCode:i})})})}function ac(e,t){return $s(e,nc(Yr()),tc,async(e,n)=>ic(e,t,n?.signal))}function oc(e={}){return ac(`Shell`,e)}function sc(e={}){return ac(`Bash`,e)}oc(),sc();function cc(e,t){if(t===void 0)return;let n=v(e),r=v(t);if(n!==r&&!n.startsWith(r+y)){let t={success:!1,output:``,error:`Access denied: "${e}" is outside the working directory`};return JSON.stringify(t)}}const lc=2e3,uc=j.object({filePath:j.string().describe(`The absolute path to the file to read`),offset:j.number().optional().describe(`The line number to start reading from (1-based). Only provide if the file is too large to read at once`),limit:j.number().optional().describe(`The number of lines to read (default: ${lc}). Only provide if the file is too large to read at once`)});function dc(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}function fc(e,t){let n=t+e.length-1,r=String(n).length;return e.map((e,n)=>`${String(t+n).padStart(r,` `)}\t${e}`).join(`
18
18
  `)}function pc(e,t,n,r){let i=t.split(`
19
- `);i[i.length-1]===``&&i.pop();let a=n-1,o=i.slice(a,a+r),s=fc(o,n),c=i.length,l=o.length,u={success:!0,output:(l<c?`[File: ${e} (lines ${n}-${n+l-1} of ${c})]\n`:`[File: ${e} (${c} lines)]\n`)+s};return JSON.stringify(u)}async function mc(e,t={}){let{filePath:n,offset:r,limit:i=lc}=e,a=r!==void 0&&r>0?r:1;if(t.sandboxClient)try{return pc(n,await t.sandboxClient.readFile(n),a,i)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let o=cc(n,t.cwd);if(o!==void 0)return o;let s;try{s=await ge(n)}catch{let e={success:!1,output:``,error:`File not found: ${n}`};return JSON.stringify(e)}if(!s.isFile()){let e={success:!1,output:``,error:`Path is not a file: ${n}`};return JSON.stringify(e)}let c;try{c=await de(n)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}if(dc(c)){let e={success:!1,output:``,error:`Binary file not supported: ${n}`};return JSON.stringify(e)}return pc(n,c.toString(`utf8`),a,i)}function hc(e={}){return $s(`Read`,`Reads a file from the local filesystem.
19
+ `);i[i.length-1]===``&&i.pop();let a=n-1,o=i.slice(a,a+r),s=fc(o,n),c=i.length,l=o.length,u={success:!0,output:(l<c?`[File: ${e} (lines ${n}-${n+l-1} of ${c})]\n`:`[File: ${e} (${c} lines)]\n`)+s};return JSON.stringify(u)}async function mc(e,t={}){let{filePath:n,offset:r,limit:i=lc}=e,a=r!==void 0&&r>0?r:1;if(t.sandboxClient)try{return pc(n,await t.sandboxClient.readFile(n),a,i)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let o=cc(n,t.cwd);if(o!==void 0)return o;let s;try{s=await he(n)}catch{let e={success:!1,output:``,error:`File not found: ${n}`};return JSON.stringify(e)}if(!s.isFile()){let e={success:!1,output:``,error:`Path is not a file: ${n}`};return JSON.stringify(e)}let c;try{c=await ue(n)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}if(dc(c)){let e={success:!1,output:``,error:`Binary file not supported: ${n}`};return JSON.stringify(e)}return pc(n,c.toString(`utf8`),a,i)}function hc(e={}){return $s(`Read`,`Reads a file from the local filesystem.
20
20
 
21
21
  By default, reads up to 2000 lines from the beginning of the file. You can optionally specify offset and limit for partial reads.
22
22
 
23
23
  Results are returned using cat -n format, with line numbers starting at 1.
24
24
 
25
- The file_path parameter must be an absolute path, not a relative path.`,uc,async t=>mc(t,e))}hc();function gc(e){let t=p(e),n=f(e),r=c(6).toString(`hex`);return h(t,`.${n}.robota-tmp-${process.pid}-${Date.now()}-${r}`)}async function _c(e){try{return(await ge(e)).mode&4095}catch(e){if(e instanceof Error&&vc(e,`ENOENT`))return;throw e}}function vc(e,t){return`code`in e&&e.code===t}async function yc(e,t){await ue(p(e),{recursive:!0});let n=await _c(e),r=gc(e);try{await _e(r,t,`utf8`),n!==void 0&&await ce(r,n),await me(r,e)}catch(e){throw await he(r,{force:!0}).catch(()=>void 0),e}}const bc=A.object({filePath:A.string().describe(`The absolute path to the file to write`),content:A.string().describe(`The content to write to the file`)});async function xc(e,t={}){let{filePath:n,content:r}=e;if(!t.sandboxClient){let e=cc(n,t.cwd);if(e!==void 0)return e}try{t.sandboxClient?await t.sandboxClient.writeFile(n,r):await yc(n,r);let e={success:!0,output:`Written ${Buffer.byteLength(r,`utf8`)} bytes to ${n}`};return JSON.stringify(e)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}function Sc(e={}){return $s(`Write`,`Writes a file to the local filesystem. This will overwrite an existing file if one exists.
25
+ The file_path parameter must be an absolute path, not a relative path.`,uc,async t=>mc(t,e))}hc();function gc(e){let t=p(e),n=f(e),r=c(6).toString(`hex`);return h(t,`.${n}.robota-tmp-${process.pid}-${Date.now()}-${r}`)}async function _c(e){try{return(await he(e)).mode&4095}catch(e){if(e instanceof Error&&vc(e,`ENOENT`))return;throw e}}function vc(e,t){return`code`in e&&e.code===t}async function yc(e,t){await le(p(e),{recursive:!0});let n=await _c(e),r=gc(e);try{await ge(r,t,`utf8`),n!==void 0&&await se(r,n),await pe(r,e)}catch(e){throw await me(r,{force:!0}).catch(()=>void 0),e}}const bc=j.object({filePath:j.string().describe(`The absolute path to the file to write`),content:j.string().describe(`The content to write to the file`)});async function xc(e,t={}){let{filePath:n,content:r}=e;if(!t.sandboxClient){let e=cc(n,t.cwd);if(e!==void 0)return e}try{t.sandboxClient?await t.sandboxClient.writeFile(n,r):await yc(n,r);let e={success:!0,output:`Written ${Buffer.byteLength(r,`utf8`)} bytes to ${n}`};return JSON.stringify(e)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}function Sc(e={}){return $s(`Write`,`Writes a file to the local filesystem. This will overwrite an existing file if one exists.
26
26
 
27
27
  ALWAYS prefer the Edit tool for modifying existing files — it only sends the diff. Only use this tool to create new files or for complete rewrites.
28
28
 
29
- NEVER create documentation files (*.md) or README files unless explicitly requested by the user.`,bc,async t=>xc(t,e))}Sc();const Cc=A.object({filePath:A.string().describe(`The absolute path to the file to modify`),oldString:A.string().describe(`The text to replace (must be an exact match of existing content)`),newString:A.string().describe(`The text to replace it with (must be different from old_string)`),replaceAll:A.boolean().optional().describe(`Replace all occurrences of old_string (default: false). Useful for renaming variables`)});async function wc(e,t={}){let{filePath:n,oldString:r,newString:i,replaceAll:a=!1}=e;if(!t.sandboxClient){let e=cc(n,t.cwd);if(e!==void 0)return e}let o;try{o=t.sandboxClient?await t.sandboxClient.readFile(n):await de(n,`utf8`)}catch{let e={success:!1,output:``,error:`File not found: ${n}`};return JSON.stringify(e)}if(!o.includes(r)){let e={success:!1,output:``,error:`oldString not found in file: ${n}`};return JSON.stringify(e)}if(!a&&o.indexOf(r)!==o.lastIndexOf(r)){let e={success:!1,output:``,error:`oldString is not unique in file (found ${o.split(r).length-1} occurrences). Provide more context to make it unique, or use replaceAll:true.`};return JSON.stringify(e)}let s=a?o.split(r).join(i):o.slice(0,o.indexOf(r))+i+o.slice(o.indexOf(r)+r.length);try{t.sandboxClient?await t.sandboxClient.writeFile(n,s):await yc(n,s)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let c=a?o.split(r).length-1:1,l=o.indexOf(r),u=l>=0?o.substring(0,l).split(`
29
+ NEVER create documentation files (*.md) or README files unless explicitly requested by the user.`,bc,async t=>xc(t,e))}Sc();const Cc=j.object({filePath:j.string().describe(`The absolute path to the file to modify`),oldString:j.string().describe(`The text to replace (must be an exact match of existing content)`),newString:j.string().describe(`The text to replace it with (must be different from old_string)`),replaceAll:j.boolean().optional().describe(`Replace all occurrences of old_string (default: false). Useful for renaming variables`)});async function wc(e,t={}){let{filePath:n,oldString:r,newString:i,replaceAll:a=!1}=e;if(!t.sandboxClient){let e=cc(n,t.cwd);if(e!==void 0)return e}let o;try{o=t.sandboxClient?await t.sandboxClient.readFile(n):await ue(n,`utf8`)}catch{let e={success:!1,output:``,error:`File not found: ${n}`};return JSON.stringify(e)}if(!o.includes(r)){let e={success:!1,output:``,error:`oldString not found in file: ${n}`};return JSON.stringify(e)}if(!a&&o.indexOf(r)!==o.lastIndexOf(r)){let e={success:!1,output:``,error:`oldString is not unique in file (found ${o.split(r).length-1} occurrences). Provide more context to make it unique, or use replaceAll:true.`};return JSON.stringify(e)}let s=a?o.split(r).join(i):o.slice(0,o.indexOf(r))+i+o.slice(o.indexOf(r)+r.length);try{t.sandboxClient?await t.sandboxClient.writeFile(n,s):await yc(n,s)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let c=a?o.split(r).length-1:1,l=o.indexOf(r),u=l>=0?o.substring(0,l).split(`
30
30
  `).length:1,d={success:!0,output:`Replaced ${c} occurrence(s) in ${n}`,startLine:u};return JSON.stringify(d)}function Tc(e={}){return $s(`Edit`,`Performs exact string replacements in files.
31
31
 
32
32
  You must use the Read tool at least once before editing. When editing text from Read output, preserve the exact indentation.
33
33
 
34
34
  The edit will FAIL if old_string is not unique in the file. Either provide more surrounding context to make it unique, or use replace_all to change every instance.
35
35
 
36
- ALWAYS prefer editing existing files over creating new ones.`,Cc,async t=>wc(t,e))}Tc();const Ec=A.object({pattern:A.string().describe(`The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.tsx")`),path:A.string().optional().describe(`The directory to search in. Defaults to the current working directory. Must be a valid directory path if provided`),limit:A.number().optional().describe(`Maximum number of results to return (default: 1000). Use a smaller limit to save context space`)});async function Dc(e){let{pattern:t,path:n}=e,r=n?v(n):process.cwd(),i;try{i=await ye(t,{cwd:r,ignore:[`**/node_modules/**`,`**/.git/**`],dot:!0,absolute:!1})}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let a=be(100),o=await Promise.all(i.map(e=>a(async()=>{let t=v(r,e);try{return{path:e,mtime:(await ge(t)).mtimeMs}}catch{return{path:e,mtime:0}}})));o.sort((e,t)=>t.mtime-e.mtime);let s=e.limit??1e3,c=o.length,l=c>s,u=(l?o.slice(0,s):o).map(e=>e.path),d=u.length>0?u.join(`
36
+ ALWAYS prefer editing existing files over creating new ones.`,Cc,async t=>wc(t,e))}Tc();const Ec=j.object({pattern:j.string().describe(`The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.tsx")`),path:j.string().optional().describe(`The directory to search in. Defaults to the current working directory. Must be a valid directory path if provided`),limit:j.number().optional().describe(`Maximum number of results to return (default: 1000). Use a smaller limit to save context space`)});async function Dc(e){let{pattern:t,path:n}=e,r=n?v(n):process.cwd(),i;try{i=await ve(t,{cwd:r,ignore:[`**/node_modules/**`,`**/.git/**`],dot:!0,absolute:!1})}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let a=ye(100),o=await Promise.all(i.map(e=>a(async()=>{let t=v(r,e);try{return{path:e,mtime:(await he(t)).mtimeMs}}catch{return{path:e,mtime:0}}})));o.sort((e,t)=>t.mtime-e.mtime);let s=e.limit??1e3,c=o.length,l=c>s,u=(l?o.slice(0,s):o).map(e=>e.path),d=u.length>0?u.join(`
37
37
  `):`(no matches)`;return l&&(d+=`\n\n[Showing ${s} of ${c} matches. Use limit parameter to see more.]`),JSON.stringify({success:!0,output:d})}const Oc=$s(`Glob`,`Fast file pattern matching tool that works with any codebase size.
38
38
 
39
39
  Supports glob patterns like '**/*.js' or 'src/**/*.ts'. Returns matching file paths sorted by modification time.
40
40
 
41
41
  Use this tool when you need to find files by name patterns. When doing an open-ended search that may require multiple rounds, use the Agent tool instead.
42
42
 
43
- Default limit is 1000 results. Use the limit parameter if you need fewer results to save context space.`,Ec,async e=>Dc(e)),kc=A.object({pattern:A.string().describe(`The regular expression pattern to search for in file contents`),path:A.string().optional().describe(`File or directory to search in. Defaults to the current working directory`),glob:A.string().optional().describe(`Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}"). Only files matching this pattern will be searched`),contextLines:A.number().optional().describe(`Number of context lines to show before and after each match. Only applies when outputMode is "content". Default: 0`),outputMode:A.enum([`files_with_matches`,`content`,`count`]).optional().describe(`Output mode: "files_with_matches" shows only file paths (default), "content" shows matching lines with context, "count" shows per-file match counts`),headLimit:A.number().int().positive().optional().describe(`Maximum number of result lines (file paths, content lines, or count rows) to return. Excess results are truncated with a marker line`)});function Ac(e){let t=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`[^/]*`);return RegExp(`^${t}$`)}function jc(e,t){return t===void 0?!0:Ac(t).test(e)}async function Mc(e,t){let n=[];async function r(e){let i;try{i=await fe(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`.git`)continue;let i=h(e,a),o;try{o=await ge(i)}catch{continue}o.isDirectory()?await r(i):o.isFile()&&jc(a,t)&&n.push(i)}}return await r(e),n}function Nc(e,t,n,r,i){let a=e.split(`
44
- `),o=[];for(let e=0;e<a.length;e++)n.test(a[e])&&o.push(e);if(o.length===0)return[];if(i===`files_with_matches`)return[t];if(i===`count`)return[`${t}:${o.length}`];let s=new Set;for(let e of o)for(let t=Math.max(0,e-r);t<=Math.min(a.length-1,e+r);t++)s.add(t);let c=[],l=Array.from(s).sort((e,t)=>e-t),u;for(let e of l){u!==void 0&&e>u+1&&c.push(`--`);let n=e+1,r=o.includes(e)?`:`:`-`;c.push(`${t}:${n}${r}${a[e]}`),u=e}return c}async function Pc(e){let{pattern:t,path:n,glob:r,contextLines:i=0,outputMode:a=`files_with_matches`,headLimit:o}=e,s=n?v(n):process.cwd(),c;try{c=new RegExp(t)}catch{let e={success:!1,output:``,error:`Invalid regex pattern: ${t}`};return JSON.stringify(e)}let l;try{l=await ge(s)}catch{let e={success:!1,output:``,error:`Path not found: ${s}`};return JSON.stringify(e)}let u;u=l.isFile()?[s]:await Mc(s,r);let d=[];for(let e of u){let t;try{let n=await de(e),r=Math.min(n.length,8192),i=!1;for(let e=0;e<r;e++)if(n[e]===0){i=!0;break}if(i)continue;t=n.toString(`utf8`)}catch{continue}let n=Nc(t,e,c,i,a);d.push(...n)}let f=d;if(o!==void 0&&f.length>o){let e=f.length-o;f=[...f.slice(0,o),`(+${e} more results truncated by headLimit)`]}let p={success:!0,output:f.length>0?f.join(`
43
+ Default limit is 1000 results. Use the limit parameter if you need fewer results to save context space.`,Ec,async e=>Dc(e)),kc=j.object({pattern:j.string().describe(`The regular expression pattern to search for in file contents`),path:j.string().optional().describe(`File or directory to search in. Defaults to the current working directory`),glob:j.string().optional().describe(`Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}"). Only files matching this pattern will be searched`),contextLines:j.number().optional().describe(`Number of context lines to show before and after each match. Only applies when outputMode is "content". Default: 0`),outputMode:j.enum([`files_with_matches`,`content`,`count`]).optional().describe(`Output mode: "files_with_matches" shows only file paths (default), "content" shows matching lines with context, "count" shows per-file match counts`),headLimit:j.number().int().positive().optional().describe(`Maximum number of result lines (file paths, content lines, or count rows) to return. Excess results are truncated with a marker line`)});function Ac(e){let t=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`.+`).replace(/\*/g,`[^/]*`);return RegExp(`^${t}$`)}function jc(e,t){return t===void 0?!0:Ac(t).test(e)}async function Mc(e,t){let n=[];async function r(e){let i;try{i=await de(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`.git`)continue;let i=h(e,a),o;try{o=await he(i)}catch{continue}o.isDirectory()?await r(i):o.isFile()&&jc(a,t)&&n.push(i)}}return await r(e),n}function Nc(e,t,n,r,i){let a=e.split(`
44
+ `),o=[];for(let e=0;e<a.length;e++)n.test(a[e])&&o.push(e);if(o.length===0)return[];if(i===`files_with_matches`)return[t];if(i===`count`)return[`${t}:${o.length}`];let s=new Set;for(let e of o)for(let t=Math.max(0,e-r);t<=Math.min(a.length-1,e+r);t++)s.add(t);let c=[],l=Array.from(s).sort((e,t)=>e-t),u;for(let e of l){u!==void 0&&e>u+1&&c.push(`--`);let n=e+1,r=o.includes(e)?`:`:`-`;c.push(`${t}:${n}${r}${a[e]}`),u=e}return c}async function Pc(e){let{pattern:t,path:n,glob:r,contextLines:i=0,outputMode:a=`files_with_matches`,headLimit:o}=e,s=n?v(n):process.cwd(),c;try{c=new RegExp(t)}catch{let e={success:!1,output:``,error:`Invalid regex pattern: ${t}`};return JSON.stringify(e)}let l;try{l=await he(s)}catch{let e={success:!1,output:``,error:`Path not found: ${s}`};return JSON.stringify(e)}let u;u=l.isFile()?[s]:await Mc(s,r);let d=[];for(let e of u){let t;try{let n=await ue(e),r=Math.min(n.length,8192),i=!1;for(let e=0;e<r;e++)if(n[e]===0){i=!0;break}if(i)continue;t=n.toString(`utf8`)}catch{continue}let n=Nc(t,e,c,i,a);d.push(...n)}let f=d;if(o!==void 0&&f.length>o){let e=f.length-o;f=[...f.slice(0,o),`(+${e} more results truncated by headLimit)`]}let p={success:!0,output:f.length>0?f.join(`
45
45
  `):`(no matches)`};return JSON.stringify(p)}const Fc=$s(`Grep`,`A powerful search tool built on regex matching.
46
46
 
47
47
  Supports full regex syntax (e.g., 'log.*Error', 'function\\\\s+\\\\w+'). Filter files with glob parameter (e.g., '*.js', '**/*.tsx').
@@ -50,17 +50,17 @@ Output modes: 'content' shows matching lines with context, 'files_with_matches'
50
50
 
51
51
  Use this tool for ALL search tasks. NEVER invoke grep or rg as a Bash command.
52
52
 
53
- Use headLimit to control result size and save context space.`,kc,async e=>Pc(e)),Ic=3e4,Lc=5e6,Rc=A.object({url:A.string().describe(`The URL to fetch`),headers:A.record(A.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function zc(e){return e.replace(/<script[\s\S]*?<\/script>/gi,``).replace(/<style[\s\S]*?<\/style>/gi,``).replace(/<[^>]+>/g,` `).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&nbsp;/g,` `).replace(/\s+/g,` `).trim()}function Bc(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${Ic/1e3}s. The server did not respond in time.`;let t=e.code;return t===`ENOTFOUND`||t===`EAI_AGAIN`?`Network error: DNS resolution failed for this host. The URL may be incorrect or the host does not exist. Do not retry with the same URL.`:t===`ECONNREFUSED`?`Network error: Connection refused. The server is not accepting connections at this address. Do not retry with the same URL.`:t===`ECONNRESET`?`Network error: Connection was reset by the server. The server may be temporarily unavailable.`:t===`ETIMEDOUT`?`Network error: Connection timed out. The server is not reachable within the expected time.`:t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?`Network error: SSL certificate error (${t}). The server's certificate is invalid. Do not retry with the same URL.`:`Network error: ${e.message} Check that the URL is correct and the server is reachable.`}async function Vc(e,t){let{url:n,headers:r}=e;try{new URL(n)}catch{let e={success:!1,output:``,error:`Invalid URL: "${n}". Fix the URL format before retrying.`};return JSON.stringify(e)}try{let e=new AbortController,i=setTimeout(()=>e.abort(),Ic),a=t?AbortSignal.any([e.signal,t]):e.signal,o=await fetch(n,{headers:{"User-Agent":`Robota-CLI/3.0`,...r??{}},signal:a,redirect:`follow`});if(clearTimeout(i),!o.ok){let e=o.status>=500?` The server is temporarily unavailable — retrying may help.`:` Do not retry with the same URL.`,t={success:!1,output:``,error:`HTTP ${o.status} ${o.statusText}.${e}`};return JSON.stringify(t)}let s=o.headers.get(`content-type`)??``,c=await o.arrayBuffer();if(c.byteLength>Lc){let e={success:!1,output:``,error:`Response too large: ${c.byteLength} bytes (max ${Lc}). Consider fetching a more specific URL or a paginated endpoint.`};return JSON.stringify(e)}let l=new TextDecoder().decode(c);return s.includes(`html`)&&(l=zc(l)),JSON.stringify({success:!0,output:l})}catch(e){let t={success:!1,output:``,error:Bc(e)};return JSON.stringify(t)}}const Hc=$s(`WebFetch`,`Fetch a URL and return its content as text. HTML pages are converted to plain text.`,Rc,async(e,t)=>Vc(e,t?.signal)),Uc=A.object({query:A.string().describe(`The search query`),limit:A.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function Wc(e,t){let{query:n,limit:r=10}=e,i=process.env.BRAVE_API_KEY;if(!i)return JSON.stringify({success:!1,output:``,error:`Web search requires BRAVE_API_KEY environment variable. Get a free API key at https://brave.com/search/api/ (2,000 queries/month free).`});try{let e=new AbortController,a=setTimeout(()=>e.abort(),15e3),o=t?AbortSignal.any([e.signal,t]):e.signal,s=new URLSearchParams({q:n,count:String(Math.min(r,20))}),c=await fetch(`https://api.search.brave.com/res/v1/web/search?${s}`,{headers:{Accept:`application/json`,"Accept-Encoding":`gzip`,"X-Subscription-Token":i},signal:o});if(clearTimeout(a),!c.ok){let e={success:!1,output:``,error:`Brave Search API error: HTTP ${c.status} ${c.statusText}`};return JSON.stringify(e)}let l=((await c.json()).web?.results??[]).map(e=>({title:e.title,url:e.url,snippet:e.description})),u={success:!0,output:JSON.stringify(l,null,2)};return JSON.stringify(u)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}const Gc=$s(`WebSearch`,`Search the web and return results with title, URL, and snippet.`,Uc,async(e,t)=>Wc(e,t?.signal)),Kc=A.object({question:A.string().min(1).describe(`The complete question to ask the user.`),header:A.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:A.array(A.union([A.string().min(1).describe(`Display text of this choice.`),A.object({label:A.string().min(1).describe(`Display text of this choice.`),description:A.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:A.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:A.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),qc=A.object({questions:A.array(Kc).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),Jc=[`Ask the user one or more structured questions and wait for their answers.`,``,`Use this when you are blocked on a decision only the user can make — ambiguous requirements,`,`mutually exclusive approaches, or choices with real trade-offs. Do not use it for decisions with`,`a conventional default or facts you can verify yourself.`,``,`Provide 1-4 questions. Each question offers predefined options and/or free text:`,` - options + default: user picks one option (or types a custom answer unless allowFreeText: false)`,` - multiSelect: true: user may pick several options`,` - no options: pure free-text entry`,``,"The result is a JSON array with one entry per question: the selected option labels in `values`","and/or the typed answer in `text`, or `cancelled: true` if the user dismissed the question.","If no interactive user is attached (headless run), the result is `{ unavailable: true }` —",`continue autonomously with your best judgment and say what you assumed.`].join(`
53
+ Use headLimit to control result size and save context space.`,kc,async e=>Pc(e)),Ic=3e4,Lc=5e6,Rc=j.object({url:j.string().describe(`The URL to fetch`),headers:j.record(j.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function zc(e){return e.replace(/<script[\s\S]*?<\/script>/gi,``).replace(/<style[\s\S]*?<\/style>/gi,``).replace(/<[^>]+>/g,` `).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&nbsp;/g,` `).replace(/\s+/g,` `).trim()}function Bc(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${Ic/1e3}s. The server did not respond in time.`;let t=e.code;return t===`ENOTFOUND`||t===`EAI_AGAIN`?`Network error: DNS resolution failed for this host. The URL may be incorrect or the host does not exist. Do not retry with the same URL.`:t===`ECONNREFUSED`?`Network error: Connection refused. The server is not accepting connections at this address. Do not retry with the same URL.`:t===`ECONNRESET`?`Network error: Connection was reset by the server. The server may be temporarily unavailable.`:t===`ETIMEDOUT`?`Network error: Connection timed out. The server is not reachable within the expected time.`:t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?`Network error: SSL certificate error (${t}). The server's certificate is invalid. Do not retry with the same URL.`:`Network error: ${e.message} Check that the URL is correct and the server is reachable.`}async function Vc(e,t){let{url:n,headers:r}=e;try{new URL(n)}catch{let e={success:!1,output:``,error:`Invalid URL: "${n}". Fix the URL format before retrying.`};return JSON.stringify(e)}try{let e=new AbortController,i=setTimeout(()=>e.abort(),Ic),a=t?AbortSignal.any([e.signal,t]):e.signal,o=await fetch(n,{headers:{"User-Agent":`Robota-CLI/3.0`,...r??{}},signal:a,redirect:`follow`});if(clearTimeout(i),!o.ok){let e=o.status>=500?` The server is temporarily unavailable — retrying may help.`:` Do not retry with the same URL.`,t={success:!1,output:``,error:`HTTP ${o.status} ${o.statusText}.${e}`};return JSON.stringify(t)}let s=o.headers.get(`content-type`)??``,c=await o.arrayBuffer();if(c.byteLength>Lc){let e={success:!1,output:``,error:`Response too large: ${c.byteLength} bytes (max ${Lc}). Consider fetching a more specific URL or a paginated endpoint.`};return JSON.stringify(e)}let l=new TextDecoder().decode(c);return s.includes(`html`)&&(l=zc(l)),JSON.stringify({success:!0,output:l})}catch(e){let t={success:!1,output:``,error:Bc(e)};return JSON.stringify(t)}}const Hc=$s(`WebFetch`,`Fetch a URL and return its content as text. HTML pages are converted to plain text.`,Rc,async(e,t)=>Vc(e,t?.signal)),Uc=j.object({query:j.string().describe(`The search query`),limit:j.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function Wc(e,t){let{query:n,limit:r=10}=e,i=process.env.BRAVE_API_KEY;if(!i)return JSON.stringify({success:!1,output:``,error:`Web search requires BRAVE_API_KEY environment variable. Get a free API key at https://brave.com/search/api/ (2,000 queries/month free).`});try{let e=new AbortController,a=setTimeout(()=>e.abort(),15e3),o=t?AbortSignal.any([e.signal,t]):e.signal,s=new URLSearchParams({q:n,count:String(Math.min(r,20))}),c=await fetch(`https://api.search.brave.com/res/v1/web/search?${s}`,{headers:{Accept:`application/json`,"Accept-Encoding":`gzip`,"X-Subscription-Token":i},signal:o});if(clearTimeout(a),!c.ok){let e={success:!1,output:``,error:`Brave Search API error: HTTP ${c.status} ${c.statusText}`};return JSON.stringify(e)}let l=((await c.json()).web?.results??[]).map(e=>({title:e.title,url:e.url,snippet:e.description})),u={success:!0,output:JSON.stringify(l,null,2)};return JSON.stringify(u)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}const Gc=$s(`WebSearch`,`Search the web and return results with title, URL, and snippet.`,Uc,async(e,t)=>Wc(e,t?.signal)),Kc=j.object({question:j.string().min(1).describe(`The complete question to ask the user.`),header:j.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:j.array(j.union([j.string().min(1).describe(`Display text of this choice.`),j.object({label:j.string().min(1).describe(`Display text of this choice.`),description:j.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:j.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:j.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),qc=j.object({questions:j.array(Kc).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),Jc=[`Ask the user one or more structured questions and wait for their answers.`,``,`Use this when you are blocked on a decision only the user can make — ambiguous requirements,`,`mutually exclusive approaches, or choices with real trade-offs. Do not use it for decisions with`,`a conventional default or facts you can verify yourself.`,``,`Provide 1-4 questions. Each question offers predefined options and/or free text:`,` - options + default: user picks one option (or types a custom answer unless allowFreeText: false)`,` - multiSelect: true: user may pick several options`,` - no options: pure free-text entry`,``,"The result is a JSON array with one entry per question: the selected option labels in `values`","and/or the typed answer in `text`, or `cancelled: true` if the user dismissed the question.","If no interactive user is attached (headless run), the result is `{ unavailable: true }` —",`continue autonomously with your best judgment and say what you assumed.`].join(`
54
54
  `);function Yc(e){let t=(e.options??[]).map(e=>typeof e==`string`?{label:e}:e),n=e.multiSelect===!0&&t.length>1;return{id:`ask_${l()}`,title:e.question,...e.header===void 0?{}:{description:e.header},...t.length>0?{options:t.map(e=>({value:e.label,label:e.label,...e.description===void 0?{}:{description:e.description}}))}:{},minSelect:+(t.length>0),maxSelect:n?t.length:1,allowFreeText:e.allowFreeText!==!1||t.length===0}}async function Xc(e,t){let n=[],r=!1;for(let i of e.questions){if(r){n.push({question:i.question,cancelled:!0});continue}let e=await t(Yc(i));if(e.type===`cancelled`){r=!0,n.push({question:i.question,cancelled:!0});continue}n.push({question:i.question,values:[...e.values],...e.text===void 0?{}:{text:e.text}})}return{answers:n}}function Zc(){return $s(`AskUserQuestion`,Jc,qc,async(e,t)=>{let n=e,r=t?.ask,i=r?await Xc(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)})}Zc();var Qc=class{getPermissionMode(){return this.permissionMode}setPermissionMode(e){this.permissionMode=e}getActivePresetId(){return this.activePresetId}setActivePresetId(e){this.activePresetId=e}getParallelSubagentsEnabled(){return this.parallelSubagentsEnabled}setParallelSubagentsEnabled(e){this.parallelSubagentsEnabled=e}getSessionId(){return this.sessionId}getSystemMessage(){return this.systemMessage}updateSystemMessage(e){this.systemMessage=e,this.robota.updateSystemPrompt(e)}async applyModelOptions(e){await this.robota.ensureReady();let t=e.model??this.model;this.robota.setModel({provider:this.aiProvider.name,model:t,...e.effort!==void 0&&{effort:e.effort},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxOutputTokens!==void 0&&{maxTokens:e.maxOutputTokens}}),this.model=t}getToolSchemas(){return this.toolSchemas}getMessageCount(){return this.messageCount}getSessionAllowedTools(){return this.permissionEnforcer.getSessionAllowedTools()}clearSessionAllowedTools(){this.permissionEnforcer.clearSessionAllowedTools()}abort(){this.abortController&&=(this.abortController.abort(),null)}isRunning(){return this.abortController!==null}getContextState(){return this.contextTracker.getContextState()}syncContextFromHistory(){this.contextTracker.updateFromHistory(this.robota.getHistory())}getAutoCompactThreshold(){return this.contextTracker.getAutoCompactThreshold()}setAutoCompactThreshold(e){this.contextTracker.setAutoCompactThreshold(e)}getHistory(){return this.robota.getHistory()}getFullHistory(){return this.robota.getFullHistory()}getSessionTokenUsage(){let e=0,t=0,n=!1;for(let r of this.getFullHistory()){if(r.category!==`event`||r.type!==`usage-summary`)continue;let i=r.data;e+=i?.promptTokens??0,t+=i?.completionTokens??0,n=!0}return n?{inputTokens:e,outputTokens:t}:void 0}getModelId(){return this.model}addHistoryEntry(e){this.robota.addHistoryEntry(e)}injectMessage(e,t,n){this.robota.injectMessage(e,t,n)}injectRawMessage(e){this.robota.injectRawMessage(e)}clearHistory(){this.robota.clearHistory(),this.contextTracker.reset()}},$c=class extends Error{constructor(e){super(e),this.name=`CompactionError`}},el=class{sessionId;cwd;model;hooks;compactInstructions;hookTypeExecutors;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.model=e.model,this.hooks=e.hooks,this.compactInstructions=e.compactInstructions,this.hookTypeExecutors=e.hookTypeExecutors}async compact(e,t,n){if(t.length===0)return``;let r=n===void 0?`auto`:`manual`,i={session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PreCompact`,trigger:r};await qa(this.hooks,`PreCompact`,i,this.hookTypeExecutors);let a=this.buildCompactionPrompt(t,n),o=await e.chat([{id:l(),role:`user`,content:a,state:`complete`,timestamp:new Date}],{model:this.model});if(typeof o.content!=`string`||o.content.trim()===``)throw new $c(`Compaction produced an invalid summary (provider=${e.name}, content type=${typeof o.content}); conversation history preserved untouched`);return o.content}buildCompactionPrompt(e,t){let n=t??this.compactInstructions??``;return[`Summarize the following conversation concisely, preserving:`,`- User's original requests and goals`,`- Key decisions and conclusions`,`- Important code changes and file paths`,`- Current task status and next steps`,n?`\nAdditional focus:\n${n}\n`:``,`Drop verbose tool outputs, debugging steps, and exploratory work that didn't lead to results.`,``,`Conversation:`,e.map(e=>{let t=typeof e.content==`string`?e.content:JSON.stringify(e.content);return`${e.role}: ${t}`}).join(`
55
55
  `)].join(`
56
56
  `)}};const tl=.835;var nl=class{contextUsedTokens=0;contextMaxTokens;autoCompactThreshold;constructor(e,t,n){this.contextMaxTokens=t??Yn(e),this.autoCompactThreshold=rl(n)}getContextState(){let e=Math.min(100,this.contextUsedTokens/this.contextMaxTokens*100);return{maxTokens:this.contextMaxTokens,usedTokens:this.contextUsedTokens,usedPercentage:Math.round(e*100)/100,remainingPercentage:Math.round((100-e)*100)/100}}shouldAutoCompact(){return this.autoCompactThreshold===!1?!1:this.getContextState().usedPercentage>=this.autoCompactThreshold*100}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=rl(e)}updateFromHistory(e){this.contextUsedTokens=Gn(e).usedTokens}reset(){this.contextUsedTokens=0}};function rl(e){if(e===void 0)return tl;if(e===!1)return!1;if(!Number.isFinite(e)||e<=0||e>1)throw RangeError(`autoCompactThreshold must be a number greater than 0 and at most 1.`);return e}const il={success:!0,data:JSON.stringify({success:!1,output:``,error:`Permission denied. The user did not approve this action.`}),metadata:{}},al=Nt(`ToolHookHelpers`);function ol(e){if(typeof e.data!=`string`||e.data.length<=3e4)return e;let t=15e3,n=e.data.substring(0,t),r=e.data.substring(e.data.length-t),i=`${n}\n\n[... output truncated: ${e.data.length.toLocaleString()} chars total, showing first and last ${t.toLocaleString()} chars ...]\n\n${r}`;return{...e,data:i}}function sl(e,t,n,r,i,a){return{session_id:e,cwd:t,hook_event_name:`PreToolUse`,tool_name:n,tool_input:r,...i!==void 0&&{permission_mode:i},...a!==void 0&&{transcript_path:a}}}async function cl(e,t,n){let r=await qa(e,`PreToolUse`,t,n);return r.blocked?{success:!0,data:JSON.stringify({blocked:!0,reason:r.reason??`Blocked by hook`}),metadata:{}}:null}function ll(e,t,n,r){qa(e,`PostToolUse`,{...t,hook_event_name:`PostToolUse`,tool_output:typeof n.data==`string`?n.data:JSON.stringify(n.data)},r).catch(e=>al.warn(`hook failed`,{error:e}))}var ul=class{sessionId;cwd;getPermissionMode;config;terminal;permissionHandler;promptForApprovalFn;sessionLogger;onToolExecution;hookTypeExecutors;transcriptPath;sessionAllowedTools=new Set;onProjectAllowTool;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.getPermissionMode=e.getPermissionMode,this.config=e.config,this.terminal=e.terminal,this.permissionHandler=e.permissionHandler,this.promptForApprovalFn=e.promptForApprovalFn,this.sessionLogger=e.sessionLogger,this.onToolExecution=e.onToolExecution,this.hookTypeExecutors=e.hookTypeExecutors,this.transcriptPath=e.transcriptPath,this.onProjectAllowTool=e.onProjectAllowTool}wrapTools(e){return e.map(e=>this.wrapToolWithPermission(e))}getSessionAllowedTools(){return[...this.sessionAllowedTools]}clearSessionAllowedTools(){this.sessionAllowedTools.clear()}wrapToolWithPermission(e){let t=this,n=e.execute.bind(e),r=Object.create(e);return r.execute=async(r,i)=>{try{let a=e.getName();t.log(`tool_call`,{tool:a,args:r});let o=sl(t.sessionId,t.cwd,a,r,t.getPermissionMode(),t.transcriptPath),s=await cl(t.config.hooks,o,t.hookTypeExecutors);if(s)return t.log(`tool_blocked`,{tool:a,reason:`hook`}),s;if(!await t.checkPermission(a,r))return t.log(`tool_denied`,{tool:a,reason:`permission`}),t.onToolExecution?.({type:`end`,toolName:a,toolArgs:r,success:!1,denied:!0,executionId:i?.executionId}),il;t.onToolExecution?.({type:`start`,toolName:a,toolArgs:r,executionId:i?.executionId});let c=await n(r,i),l=ol(c);l!==c&&typeof c.data==`string`&&t.terminal.writeLine(` ⚠ Output truncated: ${c.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),t.onToolExecution?.({type:`end`,toolName:a,toolArgs:r,success:l.success,toolResultData:typeof l.data==`string`?l.data:JSON.stringify(l.data),executionId:i?.executionId});let u=typeof l.data==`string`?l.data.length:JSON.stringify(l.data).length;return t.log(`tool_result`,{tool:a,success:l.success,dataChars:u,truncated:l!==c}),ll(t.config.hooks,o,l,t.hookTypeExecutors),l}catch(e){let t=e instanceof Error?e.message:String(e);return{success:!0,data:JSON.stringify({success:!1,output:``,error:t}),metadata:{}}}},r}async checkPermission(e,t){let n=Na(e,t,this.getPermissionMode(),{allow:this.config.permissions.allow,deny:this.config.permissions.deny});if(n===`auto`)return!0;if(n===`deny`)return!1;if(this.sessionAllowedTools.has(e))return!0;if(this.permissionHandler){let n=await this.permissionHandler(e,t);return n===`allow-session`?(this.sessionAllowedTools.add(e),!0):n===`allow-project`?(this.sessionAllowedTools.add(e),this.onProjectAllowTool?.(e),!0):n}if(this.promptForApprovalFn){let n=await this.promptForApprovalFn(this.terminal,e,t);return n===`allow-session`?(this.sessionAllowedTools.add(e),!0):n===`allow-project`?(this.sessionAllowedTools.add(e),this.onProjectAllowTool?.(e),!0):n}return!1}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function dl(e,t,n,r,i){return new ul({sessionId:t,cwd:n,getPermissionMode:r,config:{permissions:e.permissions??{allow:[],deny:[]},hooks:e.hooks},terminal:e.terminal,permissionHandler:e.permissionHandler,promptForApprovalFn:e.promptForApproval,sessionLogger:e.sessionLogger,onToolExecution:e.onToolExecution,hookTypeExecutors:e.hookTypeExecutors,transcriptPath:i,onProjectAllowTool:e.onProjectAllowTool})}function fl(e,t,n,r){return{contextTracker:new nl(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new el({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,hookTypeExecutors:e.hookTypeExecutors})}}function pl(e,t,n,r,i,a){let o=t.wrapTools(n);return new Ta({name:e.agentName??`agent`,aiProviders:[r],defaultModel:{provider:r.name,model:i,...e.effort!==void 0&&{effort:e.effort}},systemMessage:a,tools:o,logging:{enabled:!1},...e.providerTimeout!==void 0&&{timeout:e.providerTimeout},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.ask?{ask:e.ask}:{}})}const ml=Nt(`SessionHistoryOps`);async function hl(e,t){let n=t.robota.getHistory();if(n.length===0)return;t.contextTracker.updateFromHistory(n);let r=t.contextTracker.getContextState(),i=n.filter(e=>e.role!==`system`),a=await t.compactionOrchestrator.compact(t.aiProvider,i,e);t.robota.clearHistory(),t.robota.injectMessage(`system`,t.systemMessage),t.robota.injectMessage(`assistant`,`[Context Summary]\n${a}`),t.contextTracker.updateFromHistory(t.robota.getHistory());let o={session_id:t.sessionId,cwd:t.cwd,hook_event_name:`PostCompact`,trigger:t.trigger,compact_summary:a};qa(t.hooks,`PostCompact`,o,t.hookTypeExecutors).catch(e=>ml.warn(`hook failed`,{error:e}));let s=t.contextTracker.getContextState();t.log(`context_compact`,{trigger:t.trigger,before:r,after:s}),t.onCompactEventCallback?.({trigger:t.trigger,before:r,after:s}),t.onCompactCallback&&t.onCompactCallback(a)}function gl(e){let t=e.robota.getHistory(),n=new Date().toISOString(),r=e.sessionStore.load(e.sessionId),i={id:e.sessionId,name:r?.name,cwd:e.cwd,createdAt:r?.createdAt??n,updatedAt:n,messages:t,history:e.getFullHistory(),systemPrompt:e.systemPrompt,toolSchemas:e.toolSchemas};e.sessionStore.save(i)}const _l=Nt(`SessionLifecycle`);function vl(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function yl(e,t,n,r,i,a,o){qa(n,`SessionStart`,{session_id:e,cwd:t,hook_event_name:`SessionStart`,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},r).then(e=>{e.stdout&&i(e.stdout)}).catch(e=>_l.warn(`SessionStart hook failed`,{error:e}))}async function bl(e,t,n,r,i,a,o){await qa(r,`SessionEnd`,{session_id:e,cwd:t,hook_event_name:`SessionEnd`,reason:n,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},i)}const xl=`unknown_tool`;function Sl(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function Cl(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){wl(e,n);return}t===`tool_execution_result`&&Tl(e,n)}}function wl(e,t){let n=Dl(t.toolName),r=Dl(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:El(t.parameters)}))}function Tl(e,t){let n=Dl(t.toolName),r=Dl(t.toolCallId);if(!n||!r)return;let i=Ol(t.metadata);if(!(e.unknownToolCallIds.has(r)||i?.errorCode===xl))return;e.unknownToolCallIds.delete(r);let a=Dl(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:a,errorCode:xl,requestedTool:Dl(i?.requestedTool)??n,availableTools:kl(i?.availableTools)})})}function El(e){let t=Ol(e);if(!t)return;let n={};for(let[e,r]of Object.entries(t))(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||typeof r==`object`&&r)&&(n[e]=r);return n}function Dl(e){return typeof e==`string`&&e.length>0?e:void 0}function Ol(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function kl(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const Al=Nt(`SessionRun`);async function jl(e,t,n,r){if(n.contextTracker.updateFromHistory(n.robota.getHistory()),n.contextTracker.shouldAutoCompact()){let e=n.aiProvider,t=e.onTextDelta;e.onTextDelta=void 0;try{await n.compact()}finally{e.onTextDelta=t}}n.log(`user`,{content:e});let i=await qa(n.hooks,`UserPromptSubmit`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`UserPromptSubmit`,user_message:t??e,prompt:t??e,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors),a=[n.sessionStartStdout,i.stdout].filter(Boolean).join(`
57
- `),o=a?`<system-reminder>\n${a}\n</system-reminder>\n${e}`:e;n.clearSessionStartStdout();let s=n.robota.getHistory(),c=JSON.stringify(s),l=ot(n.aiProvider);n.log(`pre_run`,{historyLength:s.length,historyChars:c.length,historyEstTokens:Math.ceil(c.length/4),input:o,history:s,model:n.model,provider:n.aiProvider.name,maxTokens:n.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:l.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:l.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:l.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:l.nativeWebTools.webFetch.enabled}),n.contextTracker.updateFromHistory([...s,ai(o)]),n.onContextUpdate?.(n.contextTracker.getContextState());let u;try{let e=Sl({knownToolNames:n.knownToolNames??[],...n.onToolExecution&&{onToolExecution:n.onToolExecution}}),t=n.onTextDelta?e=>{n.log(`text_delta`,{delta:e}),n.onTextDelta?.(e)}:void 0;if(u=await n.robota.run(o,{signal:r,maxExecutionRounds:n.maxTurns??0,onExecutionEvent:(t,r)=>{n.log(t,r),Cl(e,t,r),t===`assistant_message_committed`&&(n.contextTracker.updateFromHistory(n.robota.getHistory()),n.onContextUpdate?.(n.contextTracker.getContextState()))},...t&&{onTextDelta:t}}),r.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){throw n.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:n.robota.getHistory().length}),qa(n.hooks,`StopFailure`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors).catch(e=>Al.warn(`hook failed`,{error:e})),e}let d=n.robota.getHistory(),f=d.map(e=>{let t=`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0,n=t?e.toolCalls.map(e=>e.function.name):[];return{role:e.role,contentLength:typeof e.content==`string`?e.content.length:0,hasToolCalls:t,toolCallNames:n,...e.metadata?{metadata:e.metadata}:{}}});n.log(`assistant`,{content:u,historyLength:d.length,estimatedChars:JSON.stringify(d).length,history:d,historyStructure:f}),n.contextTracker.updateFromHistory(d);let p=n.contextTracker.getContextState();return n.onContextUpdate?.(p),n.log(`context`,{maxTokens:p.maxTokens,usedTokens:p.usedTokens,usedPercentage:p.usedPercentage,remainingPercentage:p.remainingPercentage}),qa(n.hooks,`Stop`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`Stop`,response:u.substring(0,500),last_assistant_message:u,stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors).catch(e=>Al.warn(`hook failed`,{error:e})),n.getSessionStore()&&n.persistSession(),u}var Ml=class extends Qc{robota;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;abortController=null;terminal;sessionStore;cwd;hooks;hookTypeExecutors;onTextDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(e){super();let{tools:t,provider:n,systemMessage:r}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.systemMessage=r,this.toolSchemas=t.map(e=>e.schema),this.cwd=process.cwd(),this.sessionLogger=e.sessionLogger,this.hooks=e.hooks,this.hookTypeExecutors=e.hookTypeExecutors,this.onTextDeltaCallback=e.onTextDelta,this.onContextUpdateCallback=e.onContextUpdate,this.onToolExecutionCallback=e.onToolExecution,this.onCompactCallback=e.onCompact,this.onCompactEventCallback=e.onCompactEvent,this.maxTurns=e.maxTurns,this.model=e.model??`claude-sonnet-4-5`,this.sessionId=e.sessionId??`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this.permissionMode=e.permissionMode??(e.defaultTrustLevel?Ea[e.defaultTrustLevel]:void 0)??`default`,this.activePresetId=e.activePresetId??`default`,this.parallelSubagentsEnabled=e.enableParallelSubagents??!0,this.transcriptPath=e.sessionStore?.getFilePath?.(this.sessionId),this.log(`session_init`,{cwd:this.cwd,systemPromptLength:r.length,systemPrompt:r,toolSchemas:this.toolSchemas,model:this.model,provider:n.name}),this.aiProvider=n,vl(n,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=dl(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath);let{contextTracker:i,compactionOrchestrator:a}=fl(e,this.model,this.sessionId,this.cwd);this.contextTracker=i,this.compactionOrchestrator=a,this.robota=pl(e,this.permissionEnforcer,t,n,this.model,r),yl(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t){this.abortController=new AbortController;let{signal:n}=this.abortController;try{let r=await jl(e,t,this.buildRunContext(),n);return this.messageCount+=1,r}finally{this.abortController=null}}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(){this.sessionStore&&gl({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,robota:this.robota,getFullHistory:()=>this.getFullHistory()})}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>bl(this.sessionId,this.cwd,t,this.hooks,this.hookTypeExecutors,this.permissionMode,this.transcriptPath)),await n(`destroy-agent`,async()=>{await this.robota.destroy()})})(),this.shutdownPromise}swapProvider(e,t){this.robota.swapDefaultProvider(e,t),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e}async compact(e,t=`manual`){await hl(e,{sessionId:this.sessionId,cwd:this.cwd,systemMessage:this.systemMessage,robota:this.robota,aiProvider:this.aiProvider,compactionOrchestrator:this.compactionOrchestrator,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,log:(e,t)=>this.log(e,t)})}buildRunContext(){return{sessionId:this.sessionId,cwd:this.cwd,model:this.model,robota:this.robota,aiProvider:this.aiProvider,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,sessionStartStdout:this.sessionStartStdout,log:(e,t)=>this.log(e,t),compact:()=>this.compact(void 0,`auto`),persistSession:()=>this.persistSessionInternal(),getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,knownToolNames:this.toolSchemas.map(e=>e.name)}}};const Nl=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;var Pl=class{logDir;options;constructor(e,t={}){this.logDir=e,this.options={externalPayloadThresholdBytes:t.externalPayloadThresholdBytes??32768,redactedValue:t.redactedValue??`[REDACTED]`};try{D(e,{recursive:!0})}catch{}}log(e,t,n){try{let r=Fl(e,this.logDir,n,this.options),i=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e,event:t,...r});C(h(this.logDir,`${e}.jsonl`),i+`
58
- `)}catch{}}};function Fl(e,t,n,r){let i={};for(let[a,o]of Object.entries(n))i[a]=Il(e,t,a,o,r);return i}function Il(e,t,n,r,i){if(Nl.test(n))return i.redactedValue;if(r==null||typeof r==`string`||typeof r==`number`)return Ll(e,t,r,i);if(typeof r==`boolean`)return r;if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return Ll(e,t,r.map(r=>Il(e,t,n,r,i)),i);if(typeof r==`object`){let n=r,a={};for(let[r,o]of Object.entries(n))a[r]=Il(e,t,r,o,i);return Ll(e,t,a,i)}return String(r)}function Ll(e,t,n,r){let i=JSON.stringify(n);if(i===void 0)return n;let a=Buffer.byteLength(i);if(a<=r.externalPayloadThresholdBytes)return n;let o=s(`sha256`).update(i).digest(`hex`),c=`${e}.payloads`,l=h(c,`${o}.json`),u=h(t,c),d=h(t,l);return D(u,{recursive:!0}),T(d)||k(d,i,`utf-8`),{kind:`external-payload`,encoding:`json`,sha256:o,byteLength:a,relativePath:l}}function Rl(e){let t=[],n=zl(),r=Bl();return e.forEach((e,i)=>{ql(e,i,t),Vl(n,e,i),Hl(r,e,i)}),Ul(n,t),Wl(r,t),{ok:t.length===0,issues:t}}function zl(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function Bl(){return{requests:new Map,results:new Set}}function Vl(e,t,n){let r=Gl(t);r&&(t.event===`provider_request`&&e.requests.set(r.key,{executionId:r.executionId,round:r.round,index:n}),t.event===`provider_response_raw`&&e.rawResponses.add(r.key),t.event===`provider_native_raw_payload`&&(t.payloadKind===`response`||t.payloadKind===`stream_event`)&&e.nativeRawPayloads.add(r.key),t.event===`provider_response_normalized`&&e.normalizedResponses.add(r.key))}function Hl(e,t,n){let r=Kl(t);r&&(t.event===`tool_execution_request`&&e.requests.set(r.key,{executionId:r.executionId,toolCallId:r.toolCallId,index:n}),t.event===`tool_execution_result`&&e.results.add(r.key))}function Ul(e,t){for(let[n,r]of e.requests)e.nativeRawPayloads.has(n)||t.push({code:`PROVIDER_NATIVE_RAW_PAYLOAD_MISSING`,message:`Provider request ${n} has no provider-native raw response or stream payload event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.rawResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_RAW_MISSING`,message:`Provider request ${n} has no raw response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.normalizedResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_NORMALIZED_MISSING`,message:`Provider request ${n} has no normalized response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round})}function Wl(e,t){for(let[n,r]of e.requests)e.results.has(n)||t.push({code:`TOOL_RESULT_MISSING`,message:`Tool request ${n} has no terminal result event.`,eventIndex:r.index,executionId:r.executionId,toolCallId:r.toolCallId})}function Gl(e){if(typeof e.executionId!=`string`)return;let t=typeof e.round==`number`?e.round:Number(e.round);if(Number.isFinite(t))return{key:`${e.executionId}:${t}`,executionId:e.executionId,round:t}}function Kl(e){if(typeof e.executionId!=`string`)return;let t=typeof e.toolCallId==`string`?e.toolCallId:typeof e.toolExecutionId==`string`?e.toolExecutionId:void 0;if(t)return{key:`${e.executionId}:${t}`,executionId:e.executionId,toolCallId:t}}function ql(e,t,n){if(Array.isArray(e)){e.forEach(e=>ql(e,t,n));return}if(Jl(e)){if(e.kind===`external-payload`){(e.encoding!==`json`||typeof e.sha256!=`string`||typeof e.relativePath!=`string`||typeof e.byteLength!=`number`)&&n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>ql(e,t,n))}}function Jl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yl(e){return T(e)?O(e,`utf-8`).split(`
59
- `).map(e=>e.trim()).filter(e=>e.length>0).map(e=>JSON.parse(e)):[]}function Xl(e){let t=[],n=[],r={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},i,a,o,s;for(let c of e){if(i??=c.sessionId,o??=c.timestamp,s=c.timestamp,c.event===`session_init`&&(a=typeof c.cwd==`string`?c.cwd:a),c.event===`history_mutation`&&c.mutation===`append_message`){let e=Ql(c.message);e&&(t.push(e),n.push(H(e)))}Zl(c,r)}return{sessionId:i,cwd:a,createdAt:o,updatedAt:s,messages:t,history:n,backgroundTaskEvents:r.backgroundTaskEvents,backgroundJobGroupEvents:r.backgroundJobGroupEvents,memoryEvents:r.memoryEvents}}function Zl(e,t){if(e.event===`background_task_event`){tu(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){tu(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&tu(t.memoryEvents,e,`memoryEvent`,`data`)}function Ql(e){if(!$l(e))return;let t=e.role;if(t!==`user`&&t!==`assistant`&&t!==`system`&&t!==`tool`)return;let n=typeof e.id==`string`?e.id:`${t}-${Date.now()}`,r=e.timestamp instanceof Date?e.timestamp:new Date(typeof e.timestamp==`string`?e.timestamp:Date.now());return{...e,id:n,role:t,timestamp:r}}function $l(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eu(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function tu(e,t,n,r){let i=eu(t,n)??eu(t,r);i&&e.push(i)}function nu(){return process.env.HOME??process.env.USERPROFILE??`/`}var ru=class{baseDir;constructor(e){this.baseDir=e??N(nu(),`.robota`,`sessions`)}ensureDir(){M(this.baseDir)||xe(this.baseDir,{recursive:!0})}filePath(e){return N(this.baseDir,`${e}.json`)}getFilePath(e){return this.filePath(e)}save(e){this.ensureDir();let t=this.filePath(e.id),n=`${t}.${process.pid}.tmp`;Ee(n,JSON.stringify(e,null,2),`utf-8`);try{we(n,t)}catch(e){throw Te(n),e}}load(e){let t=this.filePath(e);if(M(t))try{let e=Se(t,`utf-8`);return JSON.parse(e)}catch{return}}list(){if(!M(this.baseDir))return[];let e=Ce(this.baseDir).filter(e=>e.endsWith(`.json`)),t=[];for(let n of e)try{let e=Se(N(this.baseDir,n),`utf-8`),r=JSON.parse(e);t.push(r)}catch{}return t.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime())}delete(e){let t=this.filePath(e);M(t)&&Te(t)}};function iu(e,t,n,r=new Date().toISOString()){return{id:`${t}:${e.relativePath}`,sourcePath:e.sourcePath,relativePath:e.relativePath,originalReference:e.originalReference,loadType:t,status:n,byteLength:e.byteLength,loadedAt:r,lastUsedAt:r}}function au(e,t,n){let r=e.find(e=>e.sourcePath===t.sourcePath),i=e.filter(e=>e.sourcePath!==t.sourcePath),a=r?lu(r,t):t;return uu([...i,a],n)}function ou(e,t){let n=pu(t),r=e.find(e=>mu(e,n));return r?{references:e.filter(e=>e.sourcePath!==r.sourcePath),result:{removed:r}}:{references:[...e],result:{}}}function su(e){return{removed:[...e]}}function cu(e){return e.filter(e=>e.status===`active`)}function lu(e,t){return t.status===`active`?{...t,loadedAt:e.loadedAt}:{...e,byteLength:t.byteLength,originalReference:t.originalReference,lastUsedAt:t.lastUsedAt}}function uu(e,t){let n=t?.maxActiveReferences??8,r=t?.maxActiveBytes??262144,i=t?.maxObservedReferences??32,a=[],o=[...e];for(;du(o)>n||fu(o)>r;){let e=o.find(e=>e.status===`active`);if(!e)break;a.push(e),o=o.filter(t=>t.sourcePath!==e.sourcePath)}let s=o.filter(e=>e.status===`observed`);if(s.length>i){let e=s.slice(0,s.length-i);a.push(...e),o=o.filter(t=>t.status!==`observed`||!e.some(e=>e.sourcePath===t.sourcePath))}return{references:o,evicted:a}}function du(e){return e.filter(e=>e.status===`active`).length}function fu(e){return e.reduce((e,t)=>e+(t.status===`active`?t.byteLength:0),0)}function pu(e){return e.startsWith(`@`)?e.slice(1):e}function mu(e,t){return e.relativePath===t||e.sourcePath===t||e.originalReference===t||e.originalReference===`@${t}`}function hu(e,t){return t.length===0?e:[e,`<robota_file_references>`,...t.map(e=>{let t=e.content.replaceAll(`</file>`,`<\\/file>`);return[`<file path="${bu(e.relativePath)}" bytes="${e.byteLength}" reason="${e.reason}">`,t,`</file>`].join(`
57
+ `),o=a?`<system-reminder>\n${a}\n</system-reminder>\n${e}`:e;n.clearSessionStartStdout();let s=n.robota.getHistory(),c=JSON.stringify(s),l=ot(n.aiProvider);n.log(`pre_run`,{historyLength:s.length,historyChars:c.length,historyEstTokens:Math.ceil(c.length/4),input:o,history:s,model:n.model,provider:n.aiProvider.name,maxTokens:n.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:l.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:l.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:l.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:l.nativeWebTools.webFetch.enabled}),n.contextTracker.updateFromHistory([...s,ai(o)]),n.onContextUpdate?.(n.contextTracker.getContextState());let u;try{let e=Sl({knownToolNames:n.knownToolNames??[],...n.onToolExecution&&{onToolExecution:n.onToolExecution}}),t=n.onTextDelta?e=>{n.log(`text_delta`,{delta:e}),n.onTextDelta?.(e)}:void 0;if(u=await n.robota.run(o,{signal:r,maxExecutionRounds:n.maxTurns??0,onExecutionEvent:(t,r)=>{n.log(t,r),Cl(e,t,r),t===`assistant_message_committed`&&(n.contextTracker.updateFromHistory(n.robota.getHistory()),n.onContextUpdate?.(n.contextTracker.getContextState()))},...t&&{onTextDelta:t}}),r.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){throw n.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:n.robota.getHistory().length}),qa(n.hooks,`StopFailure`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors).catch(e=>Al.warn(`hook failed`,{error:e})),e}let d=n.robota.getHistory(),f=d.map(e=>{let t=`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0,n=t?e.toolCalls.map(e=>e.function.name):[];return{role:e.role,contentLength:typeof e.content==`string`?e.content.length:0,hasToolCalls:t,toolCallNames:n,...e.metadata?{metadata:e.metadata}:{}}});n.log(`assistant`,{content:u,historyLength:d.length,estimatedChars:JSON.stringify(d).length,history:d,historyStructure:f}),n.contextTracker.updateFromHistory(d);let p=n.contextTracker.getContextState();return n.onContextUpdate?.(p),n.log(`context`,{maxTokens:p.maxTokens,usedTokens:p.usedTokens,usedPercentage:p.usedPercentage,remainingPercentage:p.remainingPercentage}),qa(n.hooks,`Stop`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`Stop`,response:u.substring(0,500),last_assistant_message:u,stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors).catch(e=>Al.warn(`hook failed`,{error:e})),n.getSessionStore()&&n.persistSession(),u}var Ml=class extends Qc{robota;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;abortController=null;terminal;sessionStore;cwd;hooks;hookTypeExecutors;onTextDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(e){super();let{tools:t,provider:n,systemMessage:r}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.systemMessage=r,this.toolSchemas=t.map(e=>e.schema),this.cwd=process.cwd(),this.sessionLogger=e.sessionLogger,this.hooks=e.hooks,this.hookTypeExecutors=e.hookTypeExecutors,this.onTextDeltaCallback=e.onTextDelta,this.onContextUpdateCallback=e.onContextUpdate,this.onToolExecutionCallback=e.onToolExecution,this.onCompactCallback=e.onCompact,this.onCompactEventCallback=e.onCompactEvent,this.maxTurns=e.maxTurns,this.model=e.model??`claude-sonnet-4-5`,this.sessionId=e.sessionId??`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this.permissionMode=e.permissionMode??(e.defaultTrustLevel?Ea[e.defaultTrustLevel]:void 0)??`default`,this.activePresetId=e.activePresetId??`default`,this.parallelSubagentsEnabled=e.enableParallelSubagents??!0,this.transcriptPath=e.sessionStore?.getFilePath?.(this.sessionId),this.log(`session_init`,{cwd:this.cwd,systemPromptLength:r.length,systemPrompt:r,toolSchemas:this.toolSchemas,model:this.model,provider:n.name}),this.aiProvider=n,vl(n,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=dl(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath);let{contextTracker:i,compactionOrchestrator:a}=fl(e,this.model,this.sessionId,this.cwd);this.contextTracker=i,this.compactionOrchestrator=a,this.robota=pl(e,this.permissionEnforcer,t,n,this.model,r),yl(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t){this.abortController=new AbortController;let{signal:n}=this.abortController;try{let r=await jl(e,t,this.buildRunContext(),n);return this.messageCount+=1,r}finally{this.abortController=null}}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(){this.sessionStore&&gl({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,robota:this.robota,getFullHistory:()=>this.getFullHistory()})}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>bl(this.sessionId,this.cwd,t,this.hooks,this.hookTypeExecutors,this.permissionMode,this.transcriptPath)),await n(`destroy-agent`,async()=>{await this.robota.destroy()})})(),this.shutdownPromise}swapProvider(e,t){this.robota.swapDefaultProvider(e,t),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e}async compact(e,t=`manual`){await hl(e,{sessionId:this.sessionId,cwd:this.cwd,systemMessage:this.systemMessage,robota:this.robota,aiProvider:this.aiProvider,compactionOrchestrator:this.compactionOrchestrator,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,log:(e,t)=>this.log(e,t)})}buildRunContext(){return{sessionId:this.sessionId,cwd:this.cwd,model:this.model,robota:this.robota,aiProvider:this.aiProvider,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,sessionStartStdout:this.sessionStartStdout,log:(e,t)=>this.log(e,t),compact:()=>this.compact(void 0,`auto`),persistSession:()=>this.persistSessionInternal(),getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,knownToolNames:this.toolSchemas.map(e=>e.name)}}};const Nl=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;var Pl=class{logDir;options;constructor(e,t={}){this.logDir=e,this.options={externalPayloadThresholdBytes:t.externalPayloadThresholdBytes??32768,redactedValue:t.redactedValue??`[REDACTED]`};try{O(e,{recursive:!0})}catch{}}log(e,t,n){try{let r=Fl(e,this.logDir,n,this.options),i=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e,event:t,...r});C(h(this.logDir,`${e}.jsonl`),i+`
58
+ `)}catch{}}};function Fl(e,t,n,r){let i={};for(let[a,o]of Object.entries(n))i[a]=Il(e,t,a,o,r);return i}function Il(e,t,n,r,i){if(Nl.test(n))return i.redactedValue;if(r==null||typeof r==`string`||typeof r==`number`)return Ll(e,t,r,i);if(typeof r==`boolean`)return r;if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return Ll(e,t,r.map(r=>Il(e,t,n,r,i)),i);if(typeof r==`object`){let n=r,a={};for(let[r,o]of Object.entries(n))a[r]=Il(e,t,r,o,i);return Ll(e,t,a,i)}return String(r)}function Ll(e,t,n,r){let i=JSON.stringify(n);if(i===void 0)return n;let a=Buffer.byteLength(i);if(a<=r.externalPayloadThresholdBytes)return n;let o=s(`sha256`).update(i).digest(`hex`),c=`${e}.payloads`,l=h(c,`${o}.json`),u=h(t,c),d=h(t,l);return O(u,{recursive:!0}),E(d)||ae(d,i,`utf-8`),{kind:`external-payload`,encoding:`json`,sha256:o,byteLength:a,relativePath:l}}function Rl(e){let t=[],n=zl(),r=Bl();return e.forEach((e,i)=>{ql(e,i,t),Vl(n,e,i),Hl(r,e,i)}),Ul(n,t),Wl(r,t),{ok:t.length===0,issues:t}}function zl(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function Bl(){return{requests:new Map,results:new Set}}function Vl(e,t,n){let r=Gl(t);r&&(t.event===`provider_request`&&e.requests.set(r.key,{executionId:r.executionId,round:r.round,index:n}),t.event===`provider_response_raw`&&e.rawResponses.add(r.key),t.event===`provider_native_raw_payload`&&(t.payloadKind===`response`||t.payloadKind===`stream_event`)&&e.nativeRawPayloads.add(r.key),t.event===`provider_response_normalized`&&e.normalizedResponses.add(r.key))}function Hl(e,t,n){let r=Kl(t);r&&(t.event===`tool_execution_request`&&e.requests.set(r.key,{executionId:r.executionId,toolCallId:r.toolCallId,index:n}),t.event===`tool_execution_result`&&e.results.add(r.key))}function Ul(e,t){for(let[n,r]of e.requests)e.nativeRawPayloads.has(n)||t.push({code:`PROVIDER_NATIVE_RAW_PAYLOAD_MISSING`,message:`Provider request ${n} has no provider-native raw response or stream payload event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.rawResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_RAW_MISSING`,message:`Provider request ${n} has no raw response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.normalizedResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_NORMALIZED_MISSING`,message:`Provider request ${n} has no normalized response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round})}function Wl(e,t){for(let[n,r]of e.requests)e.results.has(n)||t.push({code:`TOOL_RESULT_MISSING`,message:`Tool request ${n} has no terminal result event.`,eventIndex:r.index,executionId:r.executionId,toolCallId:r.toolCallId})}function Gl(e){if(typeof e.executionId!=`string`)return;let t=typeof e.round==`number`?e.round:Number(e.round);if(Number.isFinite(t))return{key:`${e.executionId}:${t}`,executionId:e.executionId,round:t}}function Kl(e){if(typeof e.executionId!=`string`)return;let t=typeof e.toolCallId==`string`?e.toolCallId:typeof e.toolExecutionId==`string`?e.toolExecutionId:void 0;if(t)return{key:`${e.executionId}:${t}`,executionId:e.executionId,toolCallId:t}}function ql(e,t,n){if(Array.isArray(e)){e.forEach(e=>ql(e,t,n));return}if(Jl(e)){if(e.kind===`external-payload`){(e.encoding!==`json`||typeof e.sha256!=`string`||typeof e.relativePath!=`string`||typeof e.byteLength!=`number`)&&n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>ql(e,t,n))}}function Jl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yl(e){return E(e)?A(e,`utf-8`).split(`
59
+ `).map(e=>e.trim()).filter(e=>e.length>0).map(e=>JSON.parse(e)):[]}function Xl(e){let t=[],n=[],r={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},i,a,o,s;for(let c of e){if(i??=c.sessionId,o??=c.timestamp,s=c.timestamp,c.event===`session_init`&&(a=typeof c.cwd==`string`?c.cwd:a),c.event===`history_mutation`&&c.mutation===`append_message`){let e=Ql(c.message);e&&(t.push(e),n.push(H(e)))}Zl(c,r)}return{sessionId:i,cwd:a,createdAt:o,updatedAt:s,messages:t,history:n,backgroundTaskEvents:r.backgroundTaskEvents,backgroundJobGroupEvents:r.backgroundJobGroupEvents,memoryEvents:r.memoryEvents}}function Zl(e,t){if(e.event===`background_task_event`){tu(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){tu(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&tu(t.memoryEvents,e,`memoryEvent`,`data`)}function Ql(e){if(!$l(e))return;let t=e.role;if(t!==`user`&&t!==`assistant`&&t!==`system`&&t!==`tool`)return;let n=typeof e.id==`string`?e.id:`${t}-${Date.now()}`,r=e.timestamp instanceof Date?e.timestamp:new Date(typeof e.timestamp==`string`?e.timestamp:Date.now());return{...e,id:n,role:t,timestamp:r}}function $l(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eu(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function tu(e,t,n,r){let i=eu(t,n)??eu(t,r);i&&e.push(i)}function nu(){return process.env.HOME??process.env.USERPROFILE??`/`}var ru=class{baseDir;constructor(e){this.baseDir=e??P(nu(),`.robota`,`sessions`)}ensureDir(){N(this.baseDir)||be(this.baseDir,{recursive:!0})}filePath(e){return P(this.baseDir,`${e}.json`)}getFilePath(e){return this.filePath(e)}save(e){this.ensureDir();let t=this.filePath(e.id),n=`${t}.${process.pid}.tmp`;Te(n,JSON.stringify(e,null,2),`utf-8`);try{Ce(n,t)}catch(e){throw we(n),e}}load(e){let t=this.filePath(e);if(N(t))try{let e=xe(t,`utf-8`);return JSON.parse(e)}catch{return}}list(){if(!N(this.baseDir))return[];let e=Se(this.baseDir).filter(e=>e.endsWith(`.json`)),t=[];for(let n of e)try{let e=xe(P(this.baseDir,n),`utf-8`),r=JSON.parse(e);t.push(r)}catch{}return t.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime())}delete(e){let t=this.filePath(e);N(t)&&we(t)}};function iu(e,t,n,r=new Date().toISOString()){return{id:`${t}:${e.relativePath}`,sourcePath:e.sourcePath,relativePath:e.relativePath,originalReference:e.originalReference,loadType:t,status:n,byteLength:e.byteLength,loadedAt:r,lastUsedAt:r}}function au(e,t,n){let r=e.find(e=>e.sourcePath===t.sourcePath),i=e.filter(e=>e.sourcePath!==t.sourcePath),a=r?lu(r,t):t;return uu([...i,a],n)}function ou(e,t){let n=pu(t),r=e.find(e=>mu(e,n));return r?{references:e.filter(e=>e.sourcePath!==r.sourcePath),result:{removed:r}}:{references:[...e],result:{}}}function su(e){return{removed:[...e]}}function cu(e){return e.filter(e=>e.status===`active`)}function lu(e,t){return t.status===`active`?{...t,loadedAt:e.loadedAt}:{...e,byteLength:t.byteLength,originalReference:t.originalReference,lastUsedAt:t.lastUsedAt}}function uu(e,t){let n=t?.maxActiveReferences??8,r=t?.maxActiveBytes??262144,i=t?.maxObservedReferences??32,a=[],o=[...e];for(;du(o)>n||fu(o)>r;){let e=o.find(e=>e.status===`active`);if(!e)break;a.push(e),o=o.filter(t=>t.sourcePath!==e.sourcePath)}let s=o.filter(e=>e.status===`observed`);if(s.length>i){let e=s.slice(0,s.length-i);a.push(...e),o=o.filter(t=>t.status!==`observed`||!e.some(e=>e.sourcePath===t.sourcePath))}return{references:o,evicted:a}}function du(e){return e.filter(e=>e.status===`active`).length}function fu(e){return e.reduce((e,t)=>e+(t.status===`active`?t.byteLength:0),0)}function pu(e){return e.startsWith(`@`)?e.slice(1):e}function mu(e,t){return e.relativePath===t||e.sourcePath===t||e.originalReference===t||e.originalReference===`@${t}`}function hu(e,t){return t.length===0?e:[e,`<robota_file_references>`,...t.map(e=>{let t=e.content.replaceAll(`</file>`,`<\\/file>`);return[`<file path="${bu(e.relativePath)}" bytes="${e.byteLength}" reason="${e.reason}">`,t,`</file>`].join(`
60
60
  `)}),`</robota_file_references>`].join(`
61
61
 
62
62
  `)}function gu(e){return e.some(e=>e.severity===`error`)}function _u(e){return e.length===0?``:[`File reference error:`,...e.map(e=>`- ${e.reference}: ${e.message}`)].join(`
63
- `)}function vu(e){return e.map(({content:e,...t})=>t)}function yu(e){let t=vu(e);return{id:`prompt_file_reference_${l()}`,timestamp:new Date,category:`event`,type:`prompt-file-reference`,data:{message:xu(t),references:t}}}function bu(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function xu(e){return`Loaded file references: ${e.map(e=>`${e.relativePath} (${e.byteLength} B)`).join(`, `)}`}const Su=/(^|[\s([{])@([^\s)\]}>,;"'`]+)/g;function Cu(e){let t=[];for(let n of e.matchAll(Su)){let e=wu(n[2]??``);Tu(e)&&t.push({original:`@${e}`,path:e,index:n.index??0})}return t}function wu(e){let t=e.length;for(;t>0&&/[.,:;!?]/.test(e[t-1]??``);)--t;return e.slice(0,t)}function Tu(e){return e.length===0||e.includes(`://`)?!1:e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`~/`)||e.startsWith(`.`)||e.includes(`.`)}function Eu(e,t){return e.startsWith(`~/`)?v(x(),e.slice(2)):m(e)?v(e):v(t,e)}function Du(e,t){let n=_(t,e);return n===``||!n.startsWith(`..`)&&!m(n)}function Ou(e,t){return _(e,t).split(y).join(`/`)}var Y=class{existsSync(e){return T(e)}readFileSync(e,t){return O(e,t)}writeFileSync(e,t,n){k(e,t,n??`utf8`)}mkdirSync(e,t){D(e,t)}readdirSync(e,t){return t?.withFileTypes?ne(e,{withFileTypes:!0}):ne(e)}statSync(e){return ae(e)}rmSync(e,t){ie(e,t)}cpSync(e,t,n){ee(e,t,n)}renameSync(e,t){re(e,t)}get constants(){return w}},ku=class{async access(e,t){await se(e,t)}async copyFile(e,t,n){await le(e,t,n)}async mkdir(e,t){await ue(e,t)}async readFile(e,t){return de(e,t)}async readdir(e,t){return t?.withFileTypes?await fe(e,{withFileTypes:!0}):fe(e)}async realpath(e){return pe(e)}async rename(e,t){await me(e,t)}async rm(e,t){await he(e,t)}async stat(e){return ge(e)}async writeFile(e,t,n){await _e(e,t,n??`utf8`)}};async function Au(e,t){let n=await Mu(t);for(let t of Cu(e))await Iu(t,0,[],n);return Nu(n)}async function ju(e,t){let n=await Mu(t);for(let t of e)await Iu({original:`@${t}`,path:t,index:0},0,[],n);return Nu(n)}async function Mu(e){let t=e.fsAsync??new ku;return{rootPath:await Fu(e.cwd,t),limits:Pu(e.limits),reason:e.reason??`prompt-reference`,references:[],diagnostics:[],loadedPaths:new Set,totalBytes:0,fsAsync:t}}function Nu(e){return{references:e.references,diagnostics:e.diagnostics}}function Pu(e){return{maxDepth:e?.maxDepth??2,maxReferences:e?.maxReferences??8,maxFileBytes:e?.maxFileBytes??65536,maxTotalBytes:e?.maxTotalBytes??262144}}async function Fu(e,t){try{return await t.realpath(e)}catch{return v(e)}}async function Iu(e,t,n,r){if(!Lu(e,t,r))return;let i=await Ru(e,r);if(i===void 0||!zu(e,i,n,r))return;let a=await Bu(e,i,r);if(a===void 0)return;let o=await Vu(e,i,r);o!==void 0&&(r.loadedPaths.add(i),r.totalBytes+=a.byteLength,r.references.push(Hu(e,a,t,o,r)),await Uu(o,t,[...n,i],r))}function Lu(e,t,n){return n.references.length>=n.limits.maxReferences?(Wu(n,`too-many-references`,e,`Too many file references.`),!1):t>n.limits.maxDepth?(Wu(n,`max-depth`,e,`File reference nesting is too deep.`),!1):!0}async function Ru(e,t){let n=Eu(e.path,t.rootPath);if(!Du(n,t.rootPath)){Wu(t,`outside-root`,e,`Referenced path is outside the workspace.`);return}try{let r=await t.fsAsync.realpath(n);if(Du(r,t.rootPath))return r;Wu(t,`outside-root`,e,`Referenced path resolves outside the workspace.`)}catch{Wu(t,`not-found`,e,`Referenced file was not found.`)}}function zu(e,t,n,r){return n.includes(t)?(Wu(r,`circular-reference`,e,`Circular file reference detected.`),!1):!r.loadedPaths.has(t)}async function Bu(e,t,n){try{let r=await n.fsAsync.stat(t);if(r.isDirectory()){Wu(n,`directory-not-supported`,e,`Directory references are not supported.`);return}if(r.size>n.limits.maxFileBytes){Wu(n,`file-too-large`,e,`Referenced file exceeds the per-file size limit.`);return}if(n.totalBytes+r.size>n.limits.maxTotalBytes){Wu(n,`total-too-large`,e,`Referenced files exceed the total size limit.`);return}return{sourcePath:t,byteLength:r.size}}catch{Wu(n,`unreadable`,e,`Referenced file could not be inspected.`);return}}async function Vu(e,t,n){try{return await n.fsAsync.readFile(t,`utf8`)}catch{Wu(n,`unreadable`,e,`Referenced file could not be read.`);return}}function Hu(e,t,n,r,i){return{originalReference:e.original,sourcePath:t.sourcePath,relativePath:Ou(i.rootPath,t.sourcePath),reason:i.reason,depth:n,byteLength:t.byteLength,content:r}}async function Uu(e,t,n,r){for(let i of Cu(e))await Iu(i,t+1,n,r)}function Wu(e,t,n,r){e.diagnostics.push({code:t,severity:`error`,reference:n.original,message:r,path:n.path})}function Gu(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&(e.message.includes(`aborted`)||e.message.includes(`abort`))}function Ku(e,t){let n=[];for(let r=t;r<e.length;r++){let t=e[r];if(t?.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)n.push({name:e.function.name,args:e.function.arguments})}return n}function qu(e,t,n,r,i,a){let o=Ku(t,r),s=$u(t,r,i);return{response:e,history:n,toolSummaries:o,contextState:i,...s&&{usage:s},...a&&a.length>0?{promptFileReferences:[...a]}:{}}}function Ju(e,t,n,r){let i=Ku(e,n),a=[];for(let t=n;t<e.length;t++){let n=e[t];n?.role===`assistant`&&n.content&&a.push(n.content)}let o=$u(e,n,r);return{response:a.join(`
63
+ `)}function vu(e){return e.map(({content:e,...t})=>t)}function yu(e){let t=vu(e);return{id:`prompt_file_reference_${l()}`,timestamp:new Date,category:`event`,type:`prompt-file-reference`,data:{message:xu(t),references:t}}}function bu(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function xu(e){return`Loaded file references: ${e.map(e=>`${e.relativePath} (${e.byteLength} B)`).join(`, `)}`}const Su=/(^|[\s([{])@([^\s)\]}>,;"'`]+)/g;function Cu(e){let t=[];for(let n of e.matchAll(Su)){let e=wu(n[2]??``);Tu(e)&&t.push({original:`@${e}`,path:e,index:n.index??0})}return t}function wu(e){let t=e.length;for(;t>0&&/[.,:;!?]/.test(e[t-1]??``);)--t;return e.slice(0,t)}function Tu(e){return e.length===0||e.includes(`://`)?!1:e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`~/`)||e.startsWith(`.`)||e.includes(`.`)}function Eu(e,t){return e.startsWith(`~/`)?v(x(),e.slice(2)):m(e)?v(e):v(t,e)}function Du(e,t){let n=_(t,e);return n===``||!n.startsWith(`..`)&&!m(n)}function Ou(e,t){return _(e,t).split(y).join(`/`)}var Y=class{existsSync(e){return E(e)}readFileSync(e,t){return A(e,t)}writeFileSync(e,t,n){ae(e,t,n??`utf8`)}mkdirSync(e,t){O(e,t)}readdirSync(e,t){return t?.withFileTypes?ee(e,{withFileTypes:!0}):ee(e)}statSync(e){return re(e)}rmSync(e,t){ne(e,t)}cpSync(e,t,n){T(e,t,n)}renameSync(e,t){te(e,t)}get constants(){return w}},ku=class{async access(e,t){await oe(e,t)}async copyFile(e,t,n){await ce(e,t,n)}async mkdir(e,t){await le(e,t)}async readFile(e,t){return ue(e,t)}async readdir(e,t){return t?.withFileTypes?await de(e,{withFileTypes:!0}):de(e)}async realpath(e){return fe(e)}async rename(e,t){await pe(e,t)}async rm(e,t){await me(e,t)}async stat(e){return he(e)}async writeFile(e,t,n){await ge(e,t,n??`utf8`)}};async function Au(e,t){let n=await Mu(t);for(let t of Cu(e))await Iu(t,0,[],n);return Nu(n)}async function ju(e,t){let n=await Mu(t);for(let t of e)await Iu({original:`@${t}`,path:t,index:0},0,[],n);return Nu(n)}async function Mu(e){let t=e.fsAsync??new ku;return{rootPath:await Fu(e.cwd,t),limits:Pu(e.limits),reason:e.reason??`prompt-reference`,references:[],diagnostics:[],loadedPaths:new Set,totalBytes:0,fsAsync:t}}function Nu(e){return{references:e.references,diagnostics:e.diagnostics}}function Pu(e){return{maxDepth:e?.maxDepth??2,maxReferences:e?.maxReferences??8,maxFileBytes:e?.maxFileBytes??65536,maxTotalBytes:e?.maxTotalBytes??262144}}async function Fu(e,t){try{return await t.realpath(e)}catch{return v(e)}}async function Iu(e,t,n,r){if(!Lu(e,t,r))return;let i=await Ru(e,r);if(i===void 0||!zu(e,i,n,r))return;let a=await Bu(e,i,r);if(a===void 0)return;let o=await Vu(e,i,r);o!==void 0&&(r.loadedPaths.add(i),r.totalBytes+=a.byteLength,r.references.push(Hu(e,a,t,o,r)),await Uu(o,t,[...n,i],r))}function Lu(e,t,n){return n.references.length>=n.limits.maxReferences?(Wu(n,`too-many-references`,e,`Too many file references.`),!1):t>n.limits.maxDepth?(Wu(n,`max-depth`,e,`File reference nesting is too deep.`),!1):!0}async function Ru(e,t){let n=Eu(e.path,t.rootPath);if(!Du(n,t.rootPath)){Wu(t,`outside-root`,e,`Referenced path is outside the workspace.`);return}try{let r=await t.fsAsync.realpath(n);if(Du(r,t.rootPath))return r;Wu(t,`outside-root`,e,`Referenced path resolves outside the workspace.`)}catch{Wu(t,`not-found`,e,`Referenced file was not found.`)}}function zu(e,t,n,r){return n.includes(t)?(Wu(r,`circular-reference`,e,`Circular file reference detected.`),!1):!r.loadedPaths.has(t)}async function Bu(e,t,n){try{let r=await n.fsAsync.stat(t);if(r.isDirectory()){Wu(n,`directory-not-supported`,e,`Directory references are not supported.`);return}if(r.size>n.limits.maxFileBytes){Wu(n,`file-too-large`,e,`Referenced file exceeds the per-file size limit.`);return}if(n.totalBytes+r.size>n.limits.maxTotalBytes){Wu(n,`total-too-large`,e,`Referenced files exceed the total size limit.`);return}return{sourcePath:t,byteLength:r.size}}catch{Wu(n,`unreadable`,e,`Referenced file could not be inspected.`);return}}async function Vu(e,t,n){try{return await n.fsAsync.readFile(t,`utf8`)}catch{Wu(n,`unreadable`,e,`Referenced file could not be read.`);return}}function Hu(e,t,n,r,i){return{originalReference:e.original,sourcePath:t.sourcePath,relativePath:Ou(i.rootPath,t.sourcePath),reason:i.reason,depth:n,byteLength:t.byteLength,content:r}}async function Uu(e,t,n,r){for(let i of Cu(e))await Iu(i,t+1,n,r)}function Wu(e,t,n,r){e.diagnostics.push({code:t,severity:`error`,reference:n.original,message:r,path:n.path})}function Gu(e){return e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&(e.message.includes(`aborted`)||e.message.includes(`abort`))}function Ku(e,t){let n=[];for(let r=t;r<e.length;r++){let t=e[r];if(t?.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)n.push({name:e.function.name,args:e.function.arguments})}return n}function qu(e,t,n,r,i,a){let o=Ku(t,r),s=$u(t,r,i);return{response:e,history:n,toolSummaries:o,contextState:i,...s&&{usage:s},...a&&a.length>0?{promptFileReferences:[...a]}:{}}}function Ju(e,t,n,r){let i=Ku(e,n),a=[];for(let t=n;t<e.length;t++){let n=e[t];n?.role===`assistant`&&n.content&&a.push(n.content)}let o=$u(e,n,r);return{response:a.join(`
64
64
 
65
65
  `),history:t,toolSummaries:i,contextState:r,...o&&{usage:o}}}function Yu(e){return{id:`usage_${l()}`,timestamp:new Date,category:`event`,type:`usage-summary`,data:e}}function Xu(e,t){return Yu({kind:`exact`,scope:`turn`,totalTokens:e.totalTokens,promptTokens:e.promptTokens,completionTokens:e.completionTokens,contextUsedTokens:0,contextMaxTokens:0,contextUsedPercentage:0,costStatus:`exact`,source:t})}async function Zu(e,t,n,r=[]){let i=await ju(cu(r).map(e=>e.sourcePath),{cwd:t,reason:`manual`}),a=await Au(e,{cwd:t}),o=[...i.diagnostics,...a.diagnostics];if(gu(o))throw Error(_u(o));let s=hu(e,Qu([...i.references,...a.references])),c=n??(s===e?void 0:e),l=vu(i.references),u=vu(a.references),d=a.references.length>0?yu(a.references):void 0;return{modelInput:s,...c===void 0?{}:{hookInput:c},activeContextReferenceRecords:l,promptFileReferenceRecords:u,...d===void 0?{}:{promptFileReferenceEntry:d}}}function Qu(e){return[...new Map(e.map(e=>[e.sourcePath,e])).values()]}function $u(e,t,n){let r=e.slice(t),i=0,a=0,o=!1;for(let e of r){if(e.role!==`assistant`)continue;let t=Or(e);t&&(o=!0,i+=t.inputTokens,a+=t.outputTokens)}if(o)return{kind:`exact`,scope:`turn`,promptTokens:i,completionTokens:a,totalTokens:i+a,contextUsedTokens:n.usedTokens,contextMaxTokens:n.maxTokens,contextUsedPercentage:n.usedPercentage,costStatus:`unknown`}}const ed={write:()=>{},writeLine:()=>{},writeMarkdown:()=>{},writeError:()=>{},prompt:()=>Promise.resolve(``),select:()=>Promise.resolve(0),spinner:()=>({stop:()=>{},update:()=>{}})},td=1e3;var nd=class{manager;now;idFactory;unsubscribeManager;listeners=new Set;groups=new Map;sequence=0;constructor(e){this.manager=e.manager,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>this.nextGroupId()),this.sequence=e.initialGroups?.length??0;for(let t of e.initialGroups??[])this.restoreGroup(t);this.unsubscribeManager=this.manager.subscribe(e=>this.handleTaskEvent(e))}createGroup(e){let t=this.now(),n={id:this.idFactory(e),parentSessionId:e.parentSessionId,waitPolicy:e.waitPolicy,taskIds:[...e.taskIds],status:`running`,createdAt:t,updatedAt:t,results:[],...e.label?{label:e.label}:{}},r=this.createRecord(n);return this.groups.set(n.id,r),this.captureExistingTerminalTasks(r),this.emit({type:`background_job_group_created`,group:dd(r.state)}),this.evaluateCompletion(r),dd(r.state)}listGroups(){return[...this.groups.values()].map(e=>dd(e.state))}getGroup(e){let t=this.groups.get(e);return t?dd(t.state):void 0}waitGroup(e){let t=this.groups.get(e);return t?t.completion:Promise.reject(Error(`Unknown background job group: ${e}`))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.unsubscribeManager(),this.listeners.clear()}nextGroupId(){return this.sequence+=1,`group_${this.sequence}`}restoreGroup(e){let t=this.createRecord(dd(e));this.groups.set(e.id,t),e.status===`completed`&&t.resolve(dd(e))}createRecord(e){let t=()=>{};return{state:e,completion:new Promise(e=>{t=e}),resolve:t}}captureExistingTerminalTasks(e){for(let t of e.state.taskIds){let n=this.manager.get(t);n&&_o(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=rd(e);if(t)for(let e of this.groups.values())e.state.taskIds.includes(t.id)&&this.captureTask(e,t)&&(e.state.status===`running`?this.evaluateCompletion(e):this.emit({type:`background_job_group_updated`,group:dd(e.state)}))}captureTask(e,t){return e.state.results.some(e=>e.taskId===t.id)?!1:(e.state.results=[...e.state.results,ad(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!id(e.state)){this.emit({type:`background_job_group_updated`,group:dd(e.state)});return}let t=this.now();e.state.status=`completed`,e.state.completedAt=t,e.state.updatedAt=t;let n=dd(e.state);e.resolve(n),this.emit({type:`background_job_group_completed`,group:n})}emit(e){for(let t of this.listeners)t(e)}};function rd(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function id(e){return e.waitPolicy===`manual`?!1:e.waitPolicy===`wait_any`?e.results.length>0:e.taskIds.every(t=>e.results.some(e=>e.taskId===t))}function ad(e){return{taskId:e.id,label:e.label,status:e.status,...e.result?.output?{summary:od(e.result.output)}:{},...e.transcriptPath||e.logPath?{outputRef:e.transcriptPath??e.logPath}:{},...e.error?{error:{...e.error}}:{},...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}}function od(e){let t=e.trim();return t.length<=td?t:`${t.slice(0,td)}...`}function sd(e){let t=cd(e,`completed`),n=cd(e,`failed`),r=cd(e,`cancelled`);return{groupId:e.id,status:e.status,total:e.taskIds.length,completed:t,failed:n,cancelled:r,pending:Math.max(e.taskIds.length-e.results.length,0),lines:e.results.map(e=>ld(e))}}function cd(e,t){return e.results.filter(e=>e.status===t).length}function ld(e){let t=ud(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function ud(e){let t=(e.error?.message??e.summary??``).replace(/\s+/g,` `).trim();return t.length>0?t:`(no summary)`}function dd(e){return{...e,taskIds:[...e.taskIds],results:e.results.map(e=>({...e,...e.error?{error:{...e.error}}:{}}))}}const fd={kind:`executionOriginKind`,sessionId:`executionOriginSessionId`,turnId:`executionOriginTurnId`,commandName:`executionOriginCommandName`,toolCallId:`executionOriginToolCallId`,skillId:`executionOriginSkillId`,label:`executionOriginLabel`};function pd(e){return[`main`,e].join(`:`)}function md(e){return[`task`,e].join(`:`)}function hd(e){return[`group`,e].join(`:`)}function gd(e){let[t,n]=e.split(`:`,2);if(n){if(t===`main`)return{kind:`main_thread`,sourceId:n};if(t===`task`)return{kind:`background_task`,sourceId:n};if(t===`group`)return{kind:`background_group`,sourceId:n}}}function _d(e){return{[fd.kind]:e.kind,[fd.sessionId]:e.sessionId,...e.turnId?{[fd.turnId]:e.turnId}:{},...e.commandName?{[fd.commandName]:e.commandName}:{},...e.toolCallId?{[fd.toolCallId]:e.toolCallId}:{},...e.skillId?{[fd.skillId]:e.skillId}:{},...e.label?{[fd.label]:e.label}:{}}}function vd(e){let t=Cd(e.groups),n=[yd(e.mainThread),...Pd(e.groups).map(e=>xd(e)),...Nd(e.tasks).map(e=>bd(e,t.get(e.id)))].filter(t=>Md(t,e.filter));return{sessionId:e.sessionId,selectedEntryId:e.selectedEntryId??n.find(e=>e.kind===`main_thread`)?.id??pd(e.sessionId),updatedAt:n[0]?.updatedAt??e.mainThread.updatedAt,entries:n}}function yd(e){return{id:pd(e.sessionId),sourceId:e.sessionId,kind:`main_thread`,origin:{kind:`user_prompt`,sessionId:e.sessionId},status:e.isExecuting?`active`:`idle`,title:`Main thread`,subtitle:e.hasPendingPrompt?`prompt queued`:`${e.historyLength} history entries`,preview:Fd(e.preview),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`]}}function bd(e,t){return{id:md(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?md(e.parentTaskId):pd(e.parentSessionId),...t?{groupId:hd(t)}:{},origin:Sd(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:Td(e),preview:Od(e),currentAction:e.currentAction,unread:e.unread,attention:kd(e),visibility:Ad(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:wd(e)}}function xd(e){let t=Fd(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:hd(e.id),sourceId:e.id,kind:`background_group`,parentId:pd(e.parentSessionId),origin:{kind:`system`,sessionId:e.parentSessionId,label:e.label},status:e.status,title:e.label??e.id,subtitle:`${e.results.length}/${e.taskIds.length} tasks`,preview:t,unread:!1,attention:jd(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`]}}function Sd(e,t){let n=Ld(e?.[fd.kind]),r=Id(e?.[fd.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:Id(e?.[fd.turnId])??t.turnId,commandName:Id(e?.[fd.commandName])??t.commandName,toolCallId:Id(e?.[fd.toolCallId])??t.toolCallId,skillId:Id(e?.[fd.skillId])??t.skillId,label:Id(e?.[fd.label])??t.label}}function Cd(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function wd(e){let t=[`select`];return _o(e.status)?t.push(`close`):t.push(`cancel`),e.kind===`agent`&&e.status===`running`&&t.push(`send`),(e.logPath||e.transcriptPath)&&t.push(`read_log`),t}function Td(e){if(e.kind===`agent`)return e.agentType??e.cwd;let t=e.schedule?.agentInstruction;if(e.status===`sleeping`&&e.nextFireAt!==void 0){let n=`next: ${Dd(e.nextFireAt)}`;return t===void 0?n:`↻ wake "${Ed(t)}" · ${n}`}return e.cwd}function Ed(e){let t=e.trim();return t.length>32?`${t.slice(0,32)}…`:t}function Dd(e){let t=new Date(e),n=new Date,r=t.getTime()-n.getTime();if(r<=0)return`now`;let i=Math.round(r/1e3);if(i<60)return`${i}s`;let a=Math.round(i/60);return a<60?`${a}m`:`${Math.round(a/60)}h`}function Od(e){return e.status===`failed`?Fd(e.error?.message):e.status===`completed`?Fd(e.result?.output):Fd(e.promptPreview??e.commandPreview)}function kd(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function Ad(e){return e.status===`completed`&&!e.unread&&!e.error&&(e.result?.exitCode??0)===0&&!e.result?.signalCode&&!e.worktreePath&&!e.branchName?`collapsed`:`default`}function jd(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function Md(e,t){return t?!(t.includeMainThread===!1&&e.kind===`main_thread`||t.kinds&&!t.kinds.includes(e.kind)||t.visibility&&!t.visibility.includes(e.visibility)):!0}function Nd(e){return[...e].sort((e,t)=>{let n=e.startedAt??e.updatedAt,r=t.startedAt??t.updatedAt,i=n.localeCompare(r);return i===0?e.id.localeCompare(t.id):i})}function Pd(e){return[...e].sort((e,t)=>e.id.localeCompare(t.id))}function Fd(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function Id(e){return typeof e==`string`?e:void 0}function Ld(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function Rd(e){let t=Bd(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:Vd(e),timestamp:e.timestamp.toISOString(),sourceId:e.type}));return{entryId:e.entryId,...e.cursor?{cursor:e.cursor}:{},...t+n.length<e.history.length?{nextCursor:{offset:t+n.length}}:{},records:r}}function zd(e){let t=e.cursor?.offset??0,n=e.lines.map((n,r)=>({id:`${e.entryId}:${t}:${r}`,kind:e.kind??`process_output`,text:n}));return{entryId:e.entryId,...e.cursor?{cursor:e.cursor}:{},...e.nextCursor?{nextCursor:e.nextCursor}:{},records:n}}function Bd(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Vd(e){return typeof e.data==`string`?e.data:e.type}function Hd(e){return{spawnAgent:t=>e.manager.spawn(Ud(e,t)),spawnProcess:t=>e.manager.spawn(Wd(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function Ud(e,t){return{kind:`agent`,label:t.label,mode:t.mode??`background`,parentSessionId:e.sessionId,parentTaskId:t.parentTaskId,depth:t.depth??1,cwd:t.cwd??e.cwd,agentType:t.agentType,prompt:t.prompt,model:t.model,isolation:t.isolation,allowedTools:t.allowedTools?[...t.allowedTools]:void 0,disallowedTools:t.disallowedTools?[...t.disallowedTools]:void 0,permissionPolicy:t.permissionPolicy??`inherit-allowlist`,timeoutMs:t.timeoutMs,idleTimeoutMs:t.idleTimeoutMs,maxRuntimeMs:t.maxRuntimeMs,outputLimitBytes:t.outputLimitBytes,maxTextDeltas:t.maxTextDeltas,repetitionWindow:t.repetitionWindow,repetitionThreshold:t.repetitionThreshold,metadata:_d(e.origin)}}function Wd(e,t){return{kind:`process`,label:t.label??t.command,mode:t.mode??`background`,parentSessionId:e.sessionId,parentTaskId:t.parentTaskId,depth:t.depth??0,cwd:t.cwd??e.cwd,command:t.command,shell:t.shell,env:t.env,stdin:t.stdin,timeoutMs:t.timeoutMs,idleTimeoutMs:t.idleTimeoutMs,maxRuntimeMs:t.maxRuntimeMs,outputLimitBytes:t.outputLimitBytes,metadata:_d(e.origin)}}const Gd=new WeakMap;function Kd(e,t){Gd.set(e,t)}function qd(e){return Gd.get(e)}const Jd=[{name:`general-purpose`,description:`General-purpose task execution agent with full tool access.`,systemPrompt:`You are a general-purpose task execution agent. You have access to all tools available in the parent session and can perform any task delegated to you.
66
66
 
@@ -106,9 +106,9 @@ Do not use emojis.`}function Zd(){return`You are a worker subagent executing a s
106
106
  - Files changed: List of modifications
107
107
  - Issues: Any problems encountered`}function Qd(e){let t=[e.agentBody];e.claudeMd&&t.push(e.claudeMd),e.agentsMd&&t.push(e.agentsMd);let n=e.isForkWorker?Zd():Xd();return t.push(n),t.join(`
108
108
 
109
- `)}const $d=`robota_command_`,ef=/^[A-Za-z0-9_-]{1,64}$/;function tf(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function nf(e){let t=tf(e);if(!t)throw Error(`Model command descriptor name must not be empty.`);let n=t.replace(/[^A-Za-z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``);if(!n)throw Error(`Model command descriptor name cannot be projected safely: ${e}`);let r=`${$d}${n}`;if(ef.test(r))return r;let i=s(`sha256`).update(t).digest(`hex`).slice(0,8),a=`${$d}${n.slice(0,40).replace(/[_-]+$/g,``)||`command`}_${i}`;if(!ef.test(a))throw Error(`Projected model command tool name is not provider-safe: ${a}`);return a}function rf(e){let t=new Set,n=new Map,r=new Map,i=[];for(let a of e){let e=tf(a.name);if(!e)throw Error(`Model command descriptor name must not be empty.`);if(t.has(e))throw Error(`Duplicate model command descriptor: ${e}`);t.add(e);let o=nf(e),s=n.get(o);if(s!==void 0)throw Error(`Model command projection collision: ${s} and ${e} both map to ${o}`);n.set(o,e),r.set(e,o),i.push({commandName:e,toolName:o,description:lf(e,a),descriptor:a,requiresPermission:a.requiresPermission!==!1})}return{commandTools:i,toolNameToCommandName:n,commandNameToToolName:r}}function af(e){return`${e.toolName} — ${e.descriptor.description}`}function of(e,t){return JSON.stringify(t?{success:t.success,command:e,message:t.message,data:t.data}:{success:!1,command:e,error:`Unknown command: ${e}`})}function sf(e){return rf(e.commandDescriptors).commandTools.map(t=>{let n=cf(t.descriptor);return $s(t.toolName,t.description,n,async r=>{let i=n.parse(r);return e.isModelInvocable(t.commandName)?of(t.commandName,await e.execute(t.commandName,i.args??``)):JSON.stringify({success:!1,command:t.commandName,error:`Command is not model-invocable: ${t.commandName}`})})})}function cf(e){let t=e.argumentHint?`Arguments for the command. Expected grammar: ${e.argumentHint}`:`Arguments for the command as a single string.`;return A.object({args:A.string().optional().describe(t)})}function lf(e,t){let n=[t.description.trim(),`Robota command id: ${e}.`];return t.argumentHint&&n.push(`Argument grammar: ${t.argumentHint}`),n.filter(e=>e.length>0).join(`
109
+ `)}const $d=`robota_command_`,ef=/^[A-Za-z0-9_-]{1,64}$/;function tf(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function nf(e){let t=tf(e);if(!t)throw Error(`Model command descriptor name must not be empty.`);let n=t.replace(/[^A-Za-z0-9_-]/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``);if(!n)throw Error(`Model command descriptor name cannot be projected safely: ${e}`);let r=`${$d}${n}`;if(ef.test(r))return r;let i=s(`sha256`).update(t).digest(`hex`).slice(0,8),a=`${$d}${n.slice(0,40).replace(/[_-]+$/g,``)||`command`}_${i}`;if(!ef.test(a))throw Error(`Projected model command tool name is not provider-safe: ${a}`);return a}function rf(e){let t=new Set,n=new Map,r=new Map,i=[];for(let a of e){let e=tf(a.name);if(!e)throw Error(`Model command descriptor name must not be empty.`);if(t.has(e))throw Error(`Duplicate model command descriptor: ${e}`);t.add(e);let o=nf(e),s=n.get(o);if(s!==void 0)throw Error(`Model command projection collision: ${s} and ${e} both map to ${o}`);n.set(o,e),r.set(e,o),i.push({commandName:e,toolName:o,description:lf(e,a),descriptor:a,requiresPermission:a.requiresPermission!==!1})}return{commandTools:i,toolNameToCommandName:n,commandNameToToolName:r}}function af(e){return`${e.toolName} — ${e.descriptor.description}`}function of(e,t){return JSON.stringify(t?{success:t.success,command:e,message:t.message,data:t.data}:{success:!1,command:e,error:`Unknown command: ${e}`})}function sf(e){return rf(e.commandDescriptors).commandTools.map(t=>{let n=cf(t.descriptor);return $s(t.toolName,t.description,n,async r=>{let i=n.parse(r);return e.isModelInvocable(t.commandName)?of(t.commandName,await e.execute(t.commandName,i.args??``)):JSON.stringify({success:!1,command:t.commandName,error:`Command is not model-invocable: ${t.commandName}`})})})}function cf(e){let t=e.argumentHint?`Arguments for the command. Expected grammar: ${e.argumentHint}`:`Arguments for the command as a single string.`;return j.object({args:j.string().optional().describe(t)})}function lf(e,t){let n=[t.description.trim(),`Robota command id: ${e}.`];return t.argumentHint&&n.push(`Argument grammar: ${t.argumentHint}`),n.filter(e=>e.length>0).join(`
110
110
 
111
- `)}const uf={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},df=nf(`agent`);function ff(e,t){return uf[e]??e}function pf(e,t){let n=[...e];if(t.disallowedTools){let e=new Set(t.disallowedTools);n=n.filter(t=>!e.has(t.getName()))}if(t.tools){let e=new Set(t.tools);n=n.filter(t=>e.has(t.getName()))}return n=n.filter(e=>e.getName()!==`Agent`&&e.getName()!==df),n}function mf(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=pf(i,t),s=t.model?ff(t.model,n.provider.model):n.provider.model,c=Qd({agentBody:t.systemPrompt,claudeMd:r.claudeMd,agentsMd:r.agentsMd,isForkWorker:e.isForkWorker??!1}),l=e.provider;return new Ml({tools:o,provider:l,systemMessage:c,terminal:a,...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.sessionLogger===void 0?{}:{sessionLogger:e.sessionLogger},model:s,maxTurns:t.maxTurns,permissions:n.permissions,permissionMode:e.permissionMode,defaultTrustLevel:n.defaultTrustLevel,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution})}function hf(e,t){let n=t?.(e)??Yd(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function gf(e,t){return{...e,...t.request.model?{model:t.request.model}:{},...t.request.allowedTools?{tools:t.request.allowedTools}:{},...t.request.disallowedTools?{disallowedTools:t.request.disallowedTools}:{}}}function _f(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function vf(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function yf(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:_f(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function bf(e){try{return Dr(e.getFullHistory())}catch{return}}function xf(e){return{start(t){vf(t);let n=mf({agentDefinition:gf(hf(t.request.type,e.customAgentRegistry),t),parentConfig:e.config,parentContext:e.context,parentTools:e.tools,provider:e.provider,terminal:e.terminal,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:n=>{t.emit?.({type:`background_task_text_delta`,delta:n}),e.onTextDelta?.(n)},onToolExecution:n=>{yf(t,n),e.onToolExecution?.(n)}});return{jobId:t.jobId,result:n.run(t.request.prompt).then(e=>{let r=bf(n);return{jobId:t.jobId,output:e,...r?{usage:r}:{}}}),cancel:()=>(n.abort(),Promise.resolve())}}}}[`Creates delegated subagent jobs in isolated contexts.`,`Without jobs, one tool call creates one subagent job from prompt.`,`For explicit multi-agent or parallel-agent requests, use one Agent tool call with jobs containing one entry per requested role and a stable label for each role.`,`When the user explicitly asks to create, run, spawn, delegate to, or use agents/subagents, start the requested subagent job immediately.`,`Do not ask a follow-up question unless execution is impossible or unsafe.`,`Subagent jobs run as background tasks by default.`,`The tool waits for a terminal result and returns completed, failed, or timed-out outcome data with structured requested/started job counts.`,`After the tool returns, base user-facing claims on returned mode and counts; do not say parallel or multiple jobs started unless the result proves those jobs started.`,`Execution is represented by a real tool call and runtime background task event.`].join(` `),A.object({prompt:A.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:A.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:A.string().optional().describe(`Optional model override`),isolation:A.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:A.array(A.object({label:A.string().optional().describe(`Stable role label for this batch job`),prompt:A.string().describe(`The task for this subagent to perform`),subagent_type:A.string().optional().describe(`Agent type for this job`),model:A.string().optional().describe(`Optional model override for this job`),isolation:A.enum([`none`,`worktree`]).optional().describe(`Isolation for this job`)}).passthrough()).optional().describe(`Batch of subagent jobs to start in one Agent tool call`)}).passthrough();const Sf=new WeakMap;function Cf(e,t){Sf.set(e,t)}function wf(e){return Sf.get(e)}var Tf=class{getManager;onChanged;emitTaskEvent;emitGroupEvent;persistSession;onWake;appendSystemNote;appendHistoryEntry;backgroundTasks=[];backgroundTaskEvents=[];backgroundJobGroups=[];backgroundJobGroupEvents=[];backgroundTaskUnsubscribe=null;backgroundJobUnsubscribe=null;backgroundJobOrchestrator=null;constructor(e,t,n,r,i,a,o,s){this.getManager=e,this.onChanged=t,this.emitTaskEvent=n,this.emitGroupEvent=r,this.persistSession=i,this.onWake=a,this.appendSystemNote=o,this.appendHistoryEntry=s}subscribe(e){if(this.backgroundTaskUnsubscribe)return;let t=qd(e)??wf(e)?.backgroundTaskManager;t&&(this.backgroundTaskUnsubscribe=t.subscribe(e=>{this.recordTaskEvent(e),this.emitTaskEvent(e),e.type===`background_task_waking`&&e.instruction!==void 0&&this.onWake?.(e.instruction,e.taskId)}),this.reArmRestoredSchedules(t))}reArmRestoredSchedules(e){let t=Date.now();for(let n of this.backgroundTasks)n.kind!==`scheduled`||n.status!==`sleeping`||!n.schedule||(n.nextFireAt!==void 0&&new Date(n.nextFireAt).getTime()<t&&this.appendSystemNote?.(`Missed scheduled wake "${n.label}" (was due ${n.nextFireAt} while the session was closed); re-arming.`),e.spawn({kind:`scheduled`,cronExpression:n.schedule.cronExpression,label:n.label,mode:n.mode,parentSessionId:n.parentSessionId,depth:n.depth,cwd:n.cwd,...n.schedule.agentInstruction===void 0?{}:{agentInstruction:n.schedule.agentInstruction},...n.schedule.command===void 0?{}:{command:n.schedule.command},...n.schedule.shell===void 0?{}:{shell:n.schedule.shell},...n.schedule.env===void 0?{}:{env:{...n.schedule.env}}}))}dispose(){this.backgroundTaskUnsubscribe?.(),this.backgroundTaskUnsubscribe=null,this.backgroundJobUnsubscribe?.(),this.backgroundJobUnsubscribe=null,this.backgroundJobOrchestrator?.dispose(),this.backgroundJobOrchestrator=null}restoreState(e){this.backgroundTasks=e.tasks,this.backgroundTaskEvents=e.taskEvents,this.backgroundJobGroups=e.groups,this.backgroundJobGroupEvents=e.groupEvents}getState(){return{tasks:this.getTaskSnapshots(),taskEvents:this.backgroundTaskEvents,groups:this.getGroupSnapshots(),groupEvents:this.backgroundJobGroupEvents}}getManagerOrThrow(){let e=this.getManager();if(!e)throw Error(`Background task manager is not available for this session.`);return e}getOrchestratorOrThrow(e){if(this.backgroundJobOrchestrator)return this.backgroundJobOrchestrator;let t=this.getManagerOrThrow();return this.backgroundJobOrchestrator=new nd({manager:t,initialGroups:this.backgroundJobGroups}),this.subscribeGroupEvents(e),this.backgroundJobOrchestrator}async cancelTask(e,t){await this.getManagerOrThrow().cancel(e,t)}async closeTask(e){await this.getManagerOrThrow().close(e)}async sendTask(e,t){await this.getManagerOrThrow().send(e,t)}async readTaskLog(e,t){return this.getManagerOrThrow().readLog(e,t)}listTasks(e){return this.getManagerOrThrow().list(e)}getTask(e){return this.getManagerOrThrow().get(e)}createGroup(e,t){return this.getOrchestratorOrThrow(t).createGroup({...e,parentSessionId:t})}listGroups(e){return this.getOrchestratorOrThrow(e).listGroups()}getGroup(e,t){return this.getOrchestratorOrThrow(t).getGroup(e)}async waitGroup(e,t){return this.getOrchestratorOrThrow(t).waitGroup(e)}async readTaskDetail(e,t,n){let r=this.getManagerOrThrow().get(t);if(!r)throw Error(`Unknown background task: ${t}`);if(r.logPath||r.transcriptPath){let i=await this.getManagerOrThrow().readLog(t,n);return zd({entryId:e,lines:i.lines,cursor:i.cursor,nextCursor:i.nextCursor,kind:r.kind===`process`?`process_output`:`progress`})}let i=r.status===`failed`?`error`:r.status===`completed`?`result`:`progress`;return zd({entryId:e,lines:[r.error?.message??r.result?.output??r.currentAction??r.promptPreview??r.commandPreview??r.status],cursor:n,kind:i})}readGroupDetail(e,t,n){let r=this.getOrchestratorOrThrow(n).getGroup(t);if(!r)throw Error(`Unknown background job group: ${t}`);return zd({entryId:e,lines:sd(r).lines,kind:`group_summary`})}getTaskSnapshots(){try{return this.getManagerOrThrow().list()}catch{return this.backgroundTasks}}getGroupSnapshots(){try{return this.backgroundJobOrchestrator?.listGroups()??this.backgroundJobGroups}catch{return this.backgroundJobGroups}}subscribeGroupEvents(e){this.backgroundJobUnsubscribe||!this.backgroundJobOrchestrator||(this.backgroundJobUnsubscribe=this.backgroundJobOrchestrator.subscribe(t=>{this.recordGroupEvent(t,e),this.emitGroupEvent(t)}))}recordTaskEvent(e){this.backgroundTasks=this.getTaskSnapshots(),this.backgroundTaskEvents.push(e),this.recordCompletedTaskUsage(e),this.persistSession(),this.onChanged(`background_task`,Ef(e))}recordCompletedTaskUsage(e){if(e.type!==`background_task_completed`)return;let t=e.task.result?.usage;!t||t.totalTokens<=0||this.appendHistoryEntry?.(Xu(t,{scope:`background`,id:e.task.id,label:e.task.agentType??e.task.label}))}recordGroupEvent(e,t){this.backgroundJobGroups=this.getGroupSnapshots(),this.backgroundJobGroupEvents.push(e),this.persistSession(),this.onChanged(`background_group`,hd(e.group.id))}};function Ef(e){if(`task`in e)return md(e.task.id);if(`taskId`in e)return md(e.taskId)}function Df(e){let t=wf(e);if(!t)throw Error(`Agent runtime dependencies are not available for this session.`);if(!t.backgroundTaskManager)throw Error(`Background task manager is not available for this session.`);return t}function Of(e){let t=Df(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function kf(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Af(e){return(wf(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function jf(e,t,n,r){let i=Df(e),a=kf(t.agentType,i),o=e.getSessionId();return Of(e).spawn({type:t.agentType,label:t.label,parentSessionId:o,mode:t.mode,depth:(i.subagentDepth??0)+1,cwd:i.cwd??n??process.cwd(),prompt:t.prompt,model:t.model??a.model,isolation:t.isolation,allowedTools:a.tools,disallowedTools:a.disallowedTools,metadata:_d({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function Mf(e,t){return Of(e).wait(t)}async function Nf(e,t,n){await Of(e).send(t,n)}async function Pf(e,t,n){await Of(e).cancel(t,n)}async function Ff(e,t){await Of(e).close(t)}function If(e){return Of(e).list()}function Lf(e,t={}){let{sessionId:n,execCtrl:r,histTracker:i,bgTracker:a}=e,o=i.getHistory();return vd({sessionId:n,mainThread:{sessionId:n,isExecuting:r.executing,hasPendingPrompt:r.pendingPrompt!==null,historyLength:o.length,updatedAt:o.at(-1)?.timestamp.toISOString()??new Date(0).toISOString(),preview:r.streamingText.trim().length>0?r.streamingText:o.at(-1)?.type},tasks:a.getTaskSnapshots(),groups:a.getGroupSnapshots(),selectedEntryId:t.selectedEntryId,filter:t.filter})}async function Rf(e,t,n,r,i){let a=gd(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?Rd({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function zf(e,t,n,r){return Hd({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var Bf=class{isExecuting(){return this.execCtrl.executing}getPendingPrompt(){return this.execCtrl.pendingPrompt}getStreamingText(){return this.execCtrl.streamingText}getActiveTools(){return this.execCtrl.activeTools}cancelQueue(){this.execCtrl.clearPendingQueue()}async executeCommand(e,t){return await this.ensureInitialized(),this.execCtrl.executing?{success:!1,message:`Another prompt or command is already running. Wait for it to finish.`}:this.skillRouter.executeCommand(e,t)}async executeModelCommand(e,t){return await this.ensureInitialized(),this.skillRouter.executeModelCommand(e,t)}getCommandInvocationSource(){return this.skillRouter.getCommandInvocationSource()}async executeSkillCommandByName(e,t,n){return await this.ensureInitialized(),this.skillRouter.executeSkillCommandByName(e,t,n)}listCommands(){return this.skillRouter.listCommands()}listSkills(){return this.skillRouter.listSkills()}listModelInvocableCommands(){return this.skillRouter.listModelInvocableCommands()}getCommandHostAdapters(){return this.skillRouter.getCommandHostAdapters()}getSkillActivationEvents(){return this.histTracker.getSkillActivationEvents()}getContextState(){return this.getSessionOrThrow().getContextState()}async compactContext(e){await this.getSessionOrThrow().compact(e)}getFullHistory(){return this.histTracker.getHistory()}getMessages(){return this.histTracker.getHistory().filter(e=>e.category===`chat`).map(e=>e.data)}listEditCheckpoints(){return this.histTracker.listEditCheckpoints()}inspectEditCheckpoint(e){return this.histTracker.inspectEditCheckpoint(e)}async restoreEditCheckpoint(e){return await this.ensureInitialized(),this.histTracker.restoreEditCheckpoint(e)}async rollbackEditCheckpoint(e){return await this.ensureInitialized(),this.histTracker.rollbackEditCheckpoint(e)}getUsedMemoryReferences(){return this.histTracker.getUsedMemoryReferences()}recordMemoryEvent(e){this.histTracker.recordMemoryEvent(e)}listContextReferences(){return this.histTracker.listContextReferences()}async addContextReference(e){return this.histTracker.addContextReference(e)}removeContextReference(e){return this.histTracker.removeContextReference(e)}clearContextReferences(){return this.histTracker.clearContextReferences()}listBackgroundTasks(e){return this.bgTracker.listTasks(e)}getBackgroundTask(e){return this.bgTracker.getTask(e)}async cancelBackgroundTask(e,t){await this.ensureInitialized(),await this.bgTracker.cancelTask(e,t)}async closeBackgroundTask(e){await this.ensureInitialized(),await this.bgTracker.closeTask(e)}async sendBackgroundTask(e,t){await this.ensureInitialized(),await this.bgTracker.sendTask(e,t)}async readBackgroundTaskLog(e,t){return await this.ensureInitialized(),this.bgTracker.readTaskLog(e,t)}createBackgroundJobGroup(e){return this.bgTracker.createGroup(e,this.getSessionOrThrow().getSessionId())}listBackgroundJobGroups(){return this.bgTracker.listGroups(this.getSessionOrThrow().getSessionId())}getBackgroundJobGroup(e){return this.bgTracker.getGroup(e,this.getSessionOrThrow().getSessionId())}async waitBackgroundJobGroup(e){return await this.ensureInitialized(),this.bgTracker.waitGroup(e,this.getSessionOrThrow().getSessionId())}getExecutionWorkspaceSnapshot(e={}){return Lf({sessionId:this.getSessionOrThrow().getSessionId(),execCtrl:this.execCtrl,histTracker:this.histTracker,bgTracker:this.bgTracker},e)}listExecutionWorkspaceEntries(e){return[...this.getExecutionWorkspaceSnapshot({filter:e}).entries]}getExecutionWorkspaceEntry(e){return this.getExecutionWorkspaceSnapshot().entries.find(t=>t.id===e)}async readExecutionWorkspaceDetail(e,t){return await this.ensureInitialized(),Rf(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return zf(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return Af(this.getSessionOrThrow())}listAgentJobs(){return If(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),jf(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),Mf(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await Nf(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await Pf(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await Ff(this.getSessionOrThrow(),e)}async spawnScheduledWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`scheduled`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),cronExpression:e.cronExpression,agentInstruction:e.agentInstruction})}async spawnMonitorWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`process`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),command:e.command,matchPattern:e.matchPattern,agentInstruction:e.agentInstruction})}};function Vf(e){return s(`sha256`).update(e,`utf-8`).digest(`hex`)}function Hf(e,t=new Y){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:Vf(n)}}async function Uf(e,t=new Y){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}Vf(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function Wf(e,t=new Y){let{stale:n}=await Uf(e,t),r=new Set(n.map(e=>e.filePath)),i=[];return{updated:e.map(e=>{if(!r.has(e.filePath))return e;let n=t.readFileSync(e.filePath,`utf-8`);return i.push(e.filePath),{filePath:e.filePath,content:n,contentHash:Vf(n)}}),refreshed:i}}async function Gf(e,t,n,r,i,a){if(!n)return;let o=[...e,...t];if(o.length===0)return;let s=e.length,{updated:c,refreshed:l}=await Wf(o);if(l.length===0)return;let u=c.slice(0,s),d=c.slice(s);r(u,d);let f=n(u.map(e=>e.content).join(`
111
+ `)}const uf={sonnet:`claude-sonnet-4-6`,haiku:`claude-haiku-4-5`,opus:`claude-opus-4-6`},df=nf(`agent`);function ff(e,t){return uf[e]??e}function pf(e,t){let n=[...e];if(t.disallowedTools){let e=new Set(t.disallowedTools);n=n.filter(t=>!e.has(t.getName()))}if(t.tools){let e=new Set(t.tools);n=n.filter(t=>e.has(t.getName()))}return n=n.filter(e=>e.getName()!==`Agent`&&e.getName()!==df),n}function mf(e){let{agentDefinition:t,parentConfig:n,parentContext:r,parentTools:i,terminal:a}=e,o=pf(i,t),s=t.model?ff(t.model,n.provider.model):n.provider.model,c=Qd({agentBody:t.systemPrompt,claudeMd:r.claudeMd,agentsMd:r.agentsMd,isForkWorker:e.isForkWorker??!1}),l=e.provider;return new Ml({tools:o,provider:l,systemMessage:c,terminal:a,...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.sessionLogger===void 0?{}:{sessionLogger:e.sessionLogger},model:s,maxTurns:t.maxTurns,permissions:n.permissions,permissionMode:e.permissionMode,defaultTrustLevel:n.defaultTrustLevel,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution})}function hf(e,t){let n=t?.(e)??Yd(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function gf(e,t){return{...e,...t.request.model?{model:t.request.model}:{},...t.request.allowedTools?{tools:t.request.allowedTools}:{},...t.request.disallowedTools?{disallowedTools:t.request.disallowedTools}:{}}}function _f(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function vf(e){if(e.request.isolation===`worktree`)throw Error(`Worktree isolation requires a runtime shell subagent runner`)}function yf(e,t){if(t.type===`start`){e.emit?.({type:`background_task_tool_start`,toolName:t.toolName,firstArg:_f(t.toolArgs)});return}e.emit?.({type:`background_task_tool_end`,toolName:t.toolName,success:t.success??!0})}function bf(e){try{return Dr(e.getFullHistory())}catch{return}}function xf(e){return{start(t){vf(t);let n=mf({agentDefinition:gf(hf(t.request.type,e.customAgentRegistry),t),parentConfig:e.config,parentContext:e.context,parentTools:e.tools,provider:e.provider,terminal:e.terminal,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.hooks,hookTypeExecutors:e.hookTypeExecutors,onTextDelta:n=>{t.emit?.({type:`background_task_text_delta`,delta:n}),e.onTextDelta?.(n)},onToolExecution:n=>{yf(t,n),e.onToolExecution?.(n)}});return{jobId:t.jobId,result:n.run(t.request.prompt).then(e=>{let r=bf(n);return{jobId:t.jobId,output:e,...r?{usage:r}:{}}}),cancel:()=>(n.abort(),Promise.resolve())}}}}[`Creates delegated subagent jobs in isolated contexts.`,`Without jobs, one tool call creates one subagent job from prompt.`,`For explicit multi-agent or parallel-agent requests, use one Agent tool call with jobs containing one entry per requested role and a stable label for each role.`,`When the user explicitly asks to create, run, spawn, delegate to, or use agents/subagents, start the requested subagent job immediately.`,`Do not ask a follow-up question unless execution is impossible or unsafe.`,`Subagent jobs run as background tasks by default.`,`The tool waits for a terminal result and returns completed, failed, or timed-out outcome data with structured requested/started job counts.`,`After the tool returns, base user-facing claims on returned mode and counts; do not say parallel or multiple jobs started unless the result proves those jobs started.`,`Execution is represented by a real tool call and runtime background task event.`].join(` `),j.object({prompt:j.string().optional().describe(`The task for a single subagent to perform. Required when jobs is omitted.`),subagent_type:j.string().optional().describe(`Agent type: "general-purpose", "Explore", "Plan", or a custom agent name`),model:j.string().optional().describe(`Optional model override`),isolation:j.enum([`none`,`worktree`]).optional().describe(`Optional runtime isolation mode. "worktree" runs in a Git worktree.`),jobs:j.array(j.object({label:j.string().optional().describe(`Stable role label for this batch job`),prompt:j.string().describe(`The task for this subagent to perform`),subagent_type:j.string().optional().describe(`Agent type for this job`),model:j.string().optional().describe(`Optional model override for this job`),isolation:j.enum([`none`,`worktree`]).optional().describe(`Isolation for this job`)}).passthrough()).optional().describe(`Batch of subagent jobs to start in one Agent tool call`)}).passthrough();const Sf=new WeakMap;function Cf(e,t){Sf.set(e,t)}function wf(e){return Sf.get(e)}var Tf=class{getManager;onChanged;emitTaskEvent;emitGroupEvent;persistSession;onWake;appendSystemNote;appendHistoryEntry;backgroundTasks=[];backgroundTaskEvents=[];backgroundJobGroups=[];backgroundJobGroupEvents=[];backgroundTaskUnsubscribe=null;backgroundJobUnsubscribe=null;backgroundJobOrchestrator=null;constructor(e,t,n,r,i,a,o,s){this.getManager=e,this.onChanged=t,this.emitTaskEvent=n,this.emitGroupEvent=r,this.persistSession=i,this.onWake=a,this.appendSystemNote=o,this.appendHistoryEntry=s}subscribe(e){if(this.backgroundTaskUnsubscribe)return;let t=qd(e)??wf(e)?.backgroundTaskManager;t&&(this.backgroundTaskUnsubscribe=t.subscribe(e=>{this.recordTaskEvent(e),this.emitTaskEvent(e),e.type===`background_task_waking`&&e.instruction!==void 0&&this.onWake?.(e.instruction,e.taskId)}),this.reArmRestoredSchedules(t))}reArmRestoredSchedules(e){let t=Date.now();for(let n of this.backgroundTasks)n.kind!==`scheduled`||n.status!==`sleeping`||!n.schedule||(n.nextFireAt!==void 0&&new Date(n.nextFireAt).getTime()<t&&this.appendSystemNote?.(`Missed scheduled wake "${n.label}" (was due ${n.nextFireAt} while the session was closed); re-arming.`),e.spawn({kind:`scheduled`,cronExpression:n.schedule.cronExpression,label:n.label,mode:n.mode,parentSessionId:n.parentSessionId,depth:n.depth,cwd:n.cwd,...n.schedule.agentInstruction===void 0?{}:{agentInstruction:n.schedule.agentInstruction},...n.schedule.command===void 0?{}:{command:n.schedule.command},...n.schedule.shell===void 0?{}:{shell:n.schedule.shell},...n.schedule.env===void 0?{}:{env:{...n.schedule.env}}}))}dispose(){this.backgroundTaskUnsubscribe?.(),this.backgroundTaskUnsubscribe=null,this.backgroundJobUnsubscribe?.(),this.backgroundJobUnsubscribe=null,this.backgroundJobOrchestrator?.dispose(),this.backgroundJobOrchestrator=null}restoreState(e){this.backgroundTasks=e.tasks,this.backgroundTaskEvents=e.taskEvents,this.backgroundJobGroups=e.groups,this.backgroundJobGroupEvents=e.groupEvents}getState(){return{tasks:this.getTaskSnapshots(),taskEvents:this.backgroundTaskEvents,groups:this.getGroupSnapshots(),groupEvents:this.backgroundJobGroupEvents}}getManagerOrThrow(){let e=this.getManager();if(!e)throw Error(`Background task manager is not available for this session.`);return e}getOrchestratorOrThrow(e){if(this.backgroundJobOrchestrator)return this.backgroundJobOrchestrator;let t=this.getManagerOrThrow();return this.backgroundJobOrchestrator=new nd({manager:t,initialGroups:this.backgroundJobGroups}),this.subscribeGroupEvents(e),this.backgroundJobOrchestrator}async cancelTask(e,t){await this.getManagerOrThrow().cancel(e,t)}async closeTask(e){await this.getManagerOrThrow().close(e)}async sendTask(e,t){await this.getManagerOrThrow().send(e,t)}async readTaskLog(e,t){return this.getManagerOrThrow().readLog(e,t)}listTasks(e){return this.getManagerOrThrow().list(e)}getTask(e){return this.getManagerOrThrow().get(e)}createGroup(e,t){return this.getOrchestratorOrThrow(t).createGroup({...e,parentSessionId:t})}listGroups(e){return this.getOrchestratorOrThrow(e).listGroups()}getGroup(e,t){return this.getOrchestratorOrThrow(t).getGroup(e)}async waitGroup(e,t){return this.getOrchestratorOrThrow(t).waitGroup(e)}async readTaskDetail(e,t,n){let r=this.getManagerOrThrow().get(t);if(!r)throw Error(`Unknown background task: ${t}`);if(r.logPath||r.transcriptPath){let i=await this.getManagerOrThrow().readLog(t,n);return zd({entryId:e,lines:i.lines,cursor:i.cursor,nextCursor:i.nextCursor,kind:r.kind===`process`?`process_output`:`progress`})}let i=r.status===`failed`?`error`:r.status===`completed`?`result`:`progress`;return zd({entryId:e,lines:[r.error?.message??r.result?.output??r.currentAction??r.promptPreview??r.commandPreview??r.status],cursor:n,kind:i})}readGroupDetail(e,t,n){let r=this.getOrchestratorOrThrow(n).getGroup(t);if(!r)throw Error(`Unknown background job group: ${t}`);return zd({entryId:e,lines:sd(r).lines,kind:`group_summary`})}getTaskSnapshots(){try{return this.getManagerOrThrow().list()}catch{return this.backgroundTasks}}getGroupSnapshots(){try{return this.backgroundJobOrchestrator?.listGroups()??this.backgroundJobGroups}catch{return this.backgroundJobGroups}}subscribeGroupEvents(e){this.backgroundJobUnsubscribe||!this.backgroundJobOrchestrator||(this.backgroundJobUnsubscribe=this.backgroundJobOrchestrator.subscribe(t=>{this.recordGroupEvent(t,e),this.emitGroupEvent(t)}))}recordTaskEvent(e){this.backgroundTasks=this.getTaskSnapshots(),this.backgroundTaskEvents.push(e),this.recordCompletedTaskUsage(e),this.persistSession(),this.onChanged(`background_task`,Ef(e))}recordCompletedTaskUsage(e){if(e.type!==`background_task_completed`)return;let t=e.task.result?.usage;!t||t.totalTokens<=0||this.appendHistoryEntry?.(Xu(t,{scope:`background`,id:e.task.id,label:e.task.agentType??e.task.label}))}recordGroupEvent(e,t){this.backgroundJobGroups=this.getGroupSnapshots(),this.backgroundJobGroupEvents.push(e),this.persistSession(),this.onChanged(`background_group`,hd(e.group.id))}};function Ef(e){if(`task`in e)return md(e.task.id);if(`taskId`in e)return md(e.taskId)}function Df(e){let t=wf(e);if(!t)throw Error(`Agent runtime dependencies are not available for this session.`);if(!t.backgroundTaskManager)throw Error(`Background task manager is not available for this session.`);return t}function Of(e){let t=Df(e);if(!t.subagentManager)throw Error(`Subagent manager is not available for this session.`);return t.subagentManager}function kf(e,t){let n=t.customAgentRegistry?.(e);if(!n)throw Error(`Unknown agent type: ${e}`);return n}function Af(e){return(wf(e)?.agentDefinitions??[]).map(e=>({name:e.name,description:e.description}))}async function jf(e,t,n,r){let i=Df(e),a=kf(t.agentType,i),o=e.getSessionId();return Of(e).spawn({type:t.agentType,label:t.label,parentSessionId:o,mode:t.mode,depth:(i.subagentDepth??0)+1,cwd:i.cwd??n??process.cwd(),prompt:t.prompt,model:t.model??a.model,isolation:t.isolation,allowedTools:a.tools,disallowedTools:a.disallowedTools,metadata:_d({kind:r===`model`?`model_command`:`slash_command`,sessionId:o,commandName:`agent`,label:t.label})})}async function Mf(e,t){return Of(e).wait(t)}async function Nf(e,t,n){await Of(e).send(t,n)}async function Pf(e,t,n){await Of(e).cancel(t,n)}async function Ff(e,t){await Of(e).close(t)}function If(e){return Of(e).list()}function Lf(e,t={}){let{sessionId:n,execCtrl:r,histTracker:i,bgTracker:a}=e,o=i.getHistory();return vd({sessionId:n,mainThread:{sessionId:n,isExecuting:r.executing,hasPendingPrompt:r.pendingPrompt!==null,historyLength:o.length,updatedAt:o.at(-1)?.timestamp.toISOString()??new Date(0).toISOString(),preview:r.streamingText.trim().length>0?r.streamingText:o.at(-1)?.type},tasks:a.getTaskSnapshots(),groups:a.getGroupSnapshots(),selectedEntryId:t.selectedEntryId,filter:t.filter})}async function Rf(e,t,n,r,i){let a=gd(e);if(!a)throw Error(`Unknown execution workspace entry: ${e}`);return a.kind===`main_thread`?Rd({entryId:e,history:t(),cursor:i}):a.kind===`background_group`?n.readGroupDetail(e,a.sourceId,r):n.readTaskDetail(e,a.sourceId,i)}function zf(e,t,n,r){return Hd({manager:e.getManagerOrThrow(),groupOrchestrator:e.getOrchestratorOrThrow(t),sessionId:t,cwd:n,origin:{...r,sessionId:r.sessionId||t}})}var Bf=class{isExecuting(){return this.execCtrl.executing}getPendingPrompt(){return this.execCtrl.pendingPrompt}getStreamingText(){return this.execCtrl.streamingText}getActiveTools(){return this.execCtrl.activeTools}cancelQueue(){this.execCtrl.clearPendingQueue()}async executeCommand(e,t){return await this.ensureInitialized(),this.execCtrl.executing?{success:!1,message:`Another prompt or command is already running. Wait for it to finish.`}:this.skillRouter.executeCommand(e,t)}async executeModelCommand(e,t){return await this.ensureInitialized(),this.skillRouter.executeModelCommand(e,t)}getCommandInvocationSource(){return this.skillRouter.getCommandInvocationSource()}async executeSkillCommandByName(e,t,n){return await this.ensureInitialized(),this.skillRouter.executeSkillCommandByName(e,t,n)}listCommands(){return this.skillRouter.listCommands()}listSkills(){return this.skillRouter.listSkills()}listModelInvocableCommands(){return this.skillRouter.listModelInvocableCommands()}getCommandHostAdapters(){return this.skillRouter.getCommandHostAdapters()}getSkillActivationEvents(){return this.histTracker.getSkillActivationEvents()}getContextState(){return this.getSessionOrThrow().getContextState()}async compactContext(e){await this.getSessionOrThrow().compact(e)}getFullHistory(){return this.histTracker.getHistory()}getMessages(){return this.histTracker.getHistory().filter(e=>e.category===`chat`).map(e=>e.data)}listEditCheckpoints(){return this.histTracker.listEditCheckpoints()}inspectEditCheckpoint(e){return this.histTracker.inspectEditCheckpoint(e)}async restoreEditCheckpoint(e){return await this.ensureInitialized(),this.histTracker.restoreEditCheckpoint(e)}async rollbackEditCheckpoint(e){return await this.ensureInitialized(),this.histTracker.rollbackEditCheckpoint(e)}getUsedMemoryReferences(){return this.histTracker.getUsedMemoryReferences()}recordMemoryEvent(e){this.histTracker.recordMemoryEvent(e)}listContextReferences(){return this.histTracker.listContextReferences()}async addContextReference(e){return this.histTracker.addContextReference(e)}removeContextReference(e){return this.histTracker.removeContextReference(e)}clearContextReferences(){return this.histTracker.clearContextReferences()}listBackgroundTasks(e){return this.bgTracker.listTasks(e)}getBackgroundTask(e){return this.bgTracker.getTask(e)}async cancelBackgroundTask(e,t){await this.ensureInitialized(),await this.bgTracker.cancelTask(e,t)}async closeBackgroundTask(e){await this.ensureInitialized(),await this.bgTracker.closeTask(e)}async sendBackgroundTask(e,t){await this.ensureInitialized(),await this.bgTracker.sendTask(e,t)}async readBackgroundTaskLog(e,t){return await this.ensureInitialized(),this.bgTracker.readTaskLog(e,t)}createBackgroundJobGroup(e){return this.bgTracker.createGroup(e,this.getSessionOrThrow().getSessionId())}listBackgroundJobGroups(){return this.bgTracker.listGroups(this.getSessionOrThrow().getSessionId())}getBackgroundJobGroup(e){return this.bgTracker.getGroup(e,this.getSessionOrThrow().getSessionId())}async waitBackgroundJobGroup(e){return await this.ensureInitialized(),this.bgTracker.waitGroup(e,this.getSessionOrThrow().getSessionId())}getExecutionWorkspaceSnapshot(e={}){return Lf({sessionId:this.getSessionOrThrow().getSessionId(),execCtrl:this.execCtrl,histTracker:this.histTracker,bgTracker:this.bgTracker},e)}listExecutionWorkspaceEntries(e){return[...this.getExecutionWorkspaceSnapshot({filter:e}).entries]}getExecutionWorkspaceEntry(e){return this.getExecutionWorkspaceSnapshot().entries.find(t=>t.id===e)}async readExecutionWorkspaceDetail(e,t){return await this.ensureInitialized(),Rf(e,()=>this.histTracker.getHistory(),this.bgTracker,this.getSessionOrThrow().getSessionId(),t)}createExecutionWorkspaceTaskSpawner(e){return zf(this.bgTracker,this.getSessionOrThrow().getSessionId(),this.getCwd(),e)}listAgentDefinitions(){return Af(this.getSessionOrThrow())}listAgentJobs(){return If(this.getSessionOrThrow())}async spawnAgentJob(e){return await this.ensureInitialized(),jf(this.getSessionOrThrow(),e,this.getCwd(),this.skillRouter.getCommandInvocationSource())}async waitAgentJob(e){return await this.ensureInitialized(),Mf(this.getSessionOrThrow(),e)}async sendAgentJob(e,t){await this.ensureInitialized(),await Nf(this.getSessionOrThrow(),e,t)}async cancelAgentJob(e,t){await this.ensureInitialized(),await Pf(this.getSessionOrThrow(),e,t)}async closeAgentJob(e){await this.ensureInitialized(),await Ff(this.getSessionOrThrow(),e)}async spawnScheduledWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`scheduled`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),cronExpression:e.cronExpression,agentInstruction:e.agentInstruction})}async spawnMonitorWake(e){return await this.ensureInitialized(),this.bgTracker.getManagerOrThrow().spawn({kind:`process`,label:e.label,mode:`background`,parentSessionId:this.getSessionOrThrow().getSessionId(),depth:0,cwd:this.getCwd(),command:e.command,matchPattern:e.matchPattern,agentInstruction:e.agentInstruction})}};function Vf(e){return s(`sha256`).update(e,`utf-8`).digest(`hex`)}function Hf(e,t=new Y){let n=t.readFileSync(e,`utf-8`);return{filePath:e,content:n,contentHash:Vf(n)}}async function Uf(e,t=new Y){let n=[],r=[];for(let i of e){if(!t.existsSync(i.filePath)){r.push(i);continue}Vf(t.readFileSync(i.filePath,`utf-8`))===i.contentHash?r.push(i):n.push(i)}return{stale:n,fresh:r}}async function Wf(e,t=new Y){let{stale:n}=await Uf(e,t),r=new Set(n.map(e=>e.filePath)),i=[];return{updated:e.map(e=>{if(!r.has(e.filePath))return e;let n=t.readFileSync(e.filePath,`utf-8`);return i.push(e.filePath),{filePath:e.filePath,content:n,contentHash:Vf(n)}}),refreshed:i}}async function Gf(e,t,n,r,i,a){if(!n)return;let o=[...e,...t];if(o.length===0)return;let s=e.length,{updated:c,refreshed:l}=await Wf(o);if(l.length===0)return;let u=c.slice(0,s),d=c.slice(s);r(u,d);let f=n(u.map(e=>e.content).join(`
112
112
 
113
113
  `),d.map(e=>e.content).join(`
114
114
 
@@ -119,7 +119,7 @@ Do not use emojis.`}function Zd(){return`You are a worker subagent executing a s
119
119
  `).length;for(let e=u;e<u+3;e++)e<o.length&&l.push({type:`context`,text:o[e],lineNumber:e+1});let d=s[0]?.lineNumber??a[0]?.lineNumber??l[0]?.lineNumber??n,f=e.split(`
120
120
  `).length,p=t.split(`
121
121
  `).length;return[{type:`hunk`,text:`@@ -${d},${s.length+f+l.length} +${d},${s.length+p+l.length} @@`,lineNumber:d},...s,...a,...l]}function Qf(e){if(e.activeTools.length===0)return;let t=e.activeTools.map(e=>`${e.isRunning?`⟳`:e.result===`success`?`✓`:e.result===`error`?`✗`:`⊘`} ${e.toolName}${e.firstArg?`(${e.firstArg})`:``}`).join(`
122
- `);e.history.push({id:l(),timestamp:new Date,category:`event`,type:`tool-summary`,data:{tools:e.activeTools.map(e=>({toolName:e.toolName,firstArg:e.firstArg,isRunning:e.isRunning,result:e.result,diffFile:e.diffFile,diffLines:e.diffLines,toolResultData:e.toolResultData})),summary:t}})}function $f(e){let t=e.filter(e=>!e.isRunning);if(t.length<=50)return e;let n=t.length-50,r=0;return e.filter(e=>!e.isRunning&&r<n?(r++,!1):!0)}function ep(e,t){let n=Kf(t.toolArgs),r={toolName:t.toolName,firstArg:n,isRunning:!0,...t.executionId?{executionId:t.executionId}:{}};return e.activeTools.push(r),e.history.push({id:l(),timestamp:new Date,category:`event`,type:`tool-start`,data:{toolName:t.toolName,firstArg:n,isRunning:!0}}),r}function tp(e,t){let n=t.denied?`denied`:t.success===!1?`error`:`success`,r=e.activeTools.findIndex(e=>e.toolName===t.toolName&&e.isRunning);if(r===-1)return null;let i={...e.activeTools[r],...Yf(t),isRunning:!1,result:n,toolResultData:t.toolResultData};return e.activeTools[r]=i,e.activeTools=$f(e.activeTools),e.history.push({id:l(),timestamp:new Date,category:`event`,type:`tool-end`,data:{toolName:i.toolName,firstArg:i.firstArg,isRunning:!1,result:n,toolResultData:t.toolResultData}}),i}const np=[{pattern:/\b401\b|invalid.*api.?key|authentication.*fail|unauthorized/i,message:"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json)."},{pattern:/\b403\b|permission.*denied|forbidden/i,message:"Access denied. Your API key may lack permission for this model. Check your provider plan or run `/provider` to switch accounts."},{pattern:/\b429\b|rate.?limit|too many requests|quota.*exceeded/i,message:"Rate limit reached. Wait a moment and try again. Consider switching to a different model with `/model`."},{pattern:/\b500\b|internal server error/i,message:`The AI provider returned an internal error. This is usually temporary — try again.`},{pattern:/\b503\b|service.*unavailable|overloaded/i,message:`The AI provider is temporarily unavailable or overloaded. Try again in a few seconds.`},{pattern:/\b502\b|bad gateway/i,message:`The AI provider gateway is unreachable. Check your network or try again shortly.`},{pattern:/\btimeout\b|timed.?out|ETIMEDOUT/i,message:`The request timed out. Check your internet connection, or try a shorter prompt to reduce response time.`},{pattern:/ENOTFOUND|ECONNREFUSED|ECONNRESET|network.*error|fetch.*fail/i,message:`Network connection failed. Check your internet connection and verify your provider URL in settings.`}];function rp(e){if(e instanceof sn)return"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json).";if(e instanceof cn)return`Rate limit reached${e.retryAfter?` (retry after ${e.retryAfter}s)`:``}. Wait a moment and try again. Consider switching to a different model with \`/model\`.`;if(e instanceof ln)return`Network connection failed. Check your internet connection and verify your provider URL in settings.`;if(e instanceof on&&e.originalError)return rp(e.originalError);let t=e.message;for(let{pattern:e,message:n}of np)if(e.test(t))return n;return t}async function ip(e,t,n,r){let i=r.getHistory();i.push(H(ai(t??e))),r.onWorkspaceUpdated();let a=r.getSession().getHistory().length;r.resetUsedMemoryReferences();try{let o=await Zu(e,r.getCwd(),n,r.getContextReferences());o.promptFileReferenceEntry&&i.push(o.promptFileReferenceEntry),r.recordContextReferenceUsage(o.activeContextReferenceRecords),r.recordPromptContextReferences(o.promptFileReferenceRecords),await r.beginEditCheckpointTurn(t??e);let s=await r.getSession().run(o.modelInput,o.hookInput);r.flushStreaming(),Qf({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let c=qu(s||`(empty response)`,r.getSession().getHistory(),i,a,r.getSession().getContextState(),o.promptFileReferenceRecords);i.push(H(oi(c.response))),c.usage&&i.push(Yu(c.usage)),r.onComplete(c),r.onContextUpdate()}catch(e){if(r.flushStreaming(),Gu(e)){let e=Ju(r.getSession().getHistory(),i,a,r.getSession().getContextState());Qf({activeTools:r.getActiveTools(),history:i}),r.clearStreaming(),e.response&&i.push(H(oi(e.response))),e.usage&&i.push(Yu(e.usage)),i.push(H(q(`Interrupted by user.`))),r.onInterrupted(e)}else{Qf({activeTools:r.getActiveTools(),history:i});let t=r.getStreamingText();if(r.clearStreaming(),t.trim().length>0){let e=oi(t);e.state=`interrupted`,i.push(H(e))}let n=e instanceof Error?e:Error(String(e)),a=rp(n);i.push(H(q(`Error: ${a}`,{metadata:{kind:`error`}}))),r.onError(n)}}}var ap=class{histTracker;skillRouter;callbacks;executing=!1;streamingText=``;flushTimer=null;activeTools=[];pendingPrompt=null;pendingDisplayInput;pendingRawInput;pendingTurnOptions={};shuttingDown=!1;wakeTaskIds=new Set;constructor(e,t,n){this.histTracker=e,this.skillRouter=t,this.callbacks=n}clearPendingQueue(){this.pendingTurnOptions.wakeTaskId!==void 0&&this.wakeTaskIds.delete(this.pendingTurnOptions.wakeTaskId),this.pendingPrompt=null,this.pendingDisplayInput=void 0,this.pendingRawInput=void 0,this.pendingTurnOptions={}}clearStreaming(){this.streamingText=``,this.activeTools=[],this.flushTimer&&=(clearTimeout(this.flushTimer),null)}flushStreaming(){this.flushTimer&&=(clearTimeout(this.flushTimer),null)}handleTextDelta(e){this.streamingText+=e,this.callbacks.emit(`text_delta`,e),this.flushTimer||=setTimeout(()=>{this.flushTimer=null},16)}handleCompactEvent(e){e.trigger===`auto`&&this.histTracker.append(H(q(`Auto compacted context: ${Math.round(e.before.usedPercentage)}% -> ${Math.round(e.after.usedPercentage)}%`))),this.callbacks.emit(`compact`,e),this.callbacks.emit(`context_update`,e.after)}handleToolExecution(e){let t={activeTools:this.activeTools,history:this.histTracker.getHistory()};if(e.type===`start`){let n=ep(t,e);this.activeTools=t.activeTools,this.callbacks.emit(`tool_start`,n)}else{let n=tp(t,e);this.activeTools=t.activeTools,n&&this.callbacks.emit(`tool_end`,n)}}emitExecutionWorkspaceUpdated(e,t){this.callbacks.getSession()&&this.callbacks.emit(`execution_workspace_event`,{type:`execution_workspace_updated`,cause:e,...t?{entryId:t}:{},snapshot:this.callbacks.getExecutionWorkspaceSnapshot()})}drainPendingQueue(e){if(!this.shuttingDown&&this.pendingPrompt){let t=this.pendingPrompt,n=this.pendingDisplayInput,r=this.pendingRawInput,i=this.pendingTurnOptions;this.clearPendingQueue(),setTimeout(()=>void e(t,n,r,i),0)}}async executePrompt(e,t,n,r,i,a,o,s,c={}){await Gf(r,i,a,o,()=>this.callbacks.getSessionOrThrow(),(e,t)=>this.callbacks.emit(e,t)),this.executing=!0,this.clearStreaming(),this.callbacks.emit(`turn_source`,c.turnSource??`user`),this.callbacks.emit(`user_message`,t??e),this.callbacks.emit(`thinking`,!0);try{await ip(e,t,n,{getSession:()=>this.callbacks.getSessionOrThrow(),getCwd:()=>this.callbacks.getCwd(),getHistory:()=>this.histTracker.getHistory(),getContextReferences:()=>this.histTracker.listInjectionContextReferences(),getActiveTools:()=>this.activeTools,resetUsedMemoryReferences:()=>this.histTracker.resetUsedMemoryReferences(),recordContextReferenceUsage:e=>this.histTracker.recordContextReferenceUsage(e),recordPromptContextReferences:e=>this.histTracker.recordPromptContextReferences(e),beginEditCheckpointTurn:e=>this.histTracker.beginEditCheckpointTurn(e),flushStreaming:()=>this.flushStreaming(),clearStreaming:()=>this.clearStreaming(),getStreamingText:()=>this.streamingText,onWorkspaceUpdated:()=>this.emitExecutionWorkspaceUpdated(`main_thread`),onComplete:e=>{this.callbacks.emit(`complete`,e)},onInterrupted:e=>{this.callbacks.emit(`interrupted`,e)},onError:e=>{this.callbacks.emit(`error`,e)},onContextUpdate:()=>{this.callbacks.emit(`context_update`,this.callbacks.getContextState())}})}finally{try{await this.histTracker.finalizeEditCheckpointTurn()}catch(e){this.callbacks.emit(`error`,e instanceof Error?e:Error(String(e)))}this.executing=!1,this.callbacks.emit(`thinking`,!1),c.wakeTaskId!==void 0&&this.wakeTaskIds.delete(c.wakeTaskId),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(s)}}async executeForkSkillCommand(e,t,n,r,i,a){if(this.executing)throw Error(`Cannot execute fork skill while another prompt is running.`);this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.histTracker.append(H(ai(n??`/${e.name}`))),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let n=await this.skillRouter.executeSkillWithActivation(e,t,i,r);return await this.applyForkSkillResult(n.result??`(empty response)`),n}catch(e){let t=e instanceof Error?e:Error(String(e));return this.histTracker.append(H(q(`Error: ${rp(t)}`))),this.callbacks.emit(`error`,t),{mode:`fork`,result:``}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(a)}}async executeForegroundCommand(e,t){this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let t=await e();return this.callbacks.emit(`context_update`,this.callbacks.getContextState()),t}catch(e){return{success:!1,message:`Error: ${e instanceof Error?e.message:String(e)}`}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(t)}}async applyForkSkillResult(e){this.flushStreaming(),Qf({activeTools:this.activeTools,history:this.histTracker.getHistory()}),this.clearStreaming();let t={response:e,history:this.histTracker.getHistory(),toolSummaries:[],contextState:this.callbacks.getContextState()};this.histTracker.append(H(oi(e))),this.callbacks.emit(`complete`,t),this.callbacks.emit(`context_update`,this.callbacks.getContextState())}};function op(e,t,n){let r=wf(n)?.customAgentRegistry?.(e)??Yd(e);if(!r)throw Error(`Unknown agent type: ${e}`);return t.allowedTools?{...r,tools:t.allowedTools}:r}async function sp(e,t,n){let r=wf(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);return mf({agentDefinition:op(t.agent??`general-purpose`,t,n),parentConfig:r.config,parentContext:r.context,parentTools:r.tools,provider:r.provider,terminal:r.terminal,isForkWorker:!0,permissionMode:r.permissionMode,permissionHandler:r.permissionHandler,hooks:r.hooks,hookTypeExecutors:r.hookTypeExecutors,onTextDelta:r.onTextDelta,onToolExecution:r.onToolExecution}).run(e)}async function cp(e,t,n){let r=await ju([t],{cwd:n,reason:`manual`});if(gu(r.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[_u(r.diagnostics)]}};let i=r.references[0];if(!i)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let a=iu(vu([i])[0],`manual`,`active`),o=au(e,a);return{references:o.references,result:{reference:a,evicted:o.evicted,diagnostics:[]}}}function lp(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=iu(e,n.loadType,n.status,r);i=au(i,t).references}return i}function up(e,t){let n=new Date().toISOString();return e.map(e=>{let r=_(t,e.filePath);return{id:`system:${r}`,sourcePath:e.filePath,relativePath:r,originalReference:r,loadType:`system`,status:`active`,byteLength:Buffer.byteLength(e.content,`utf-8`),loadedAt:n,lastUsedAt:n}})}function dp(e){let t=h(e,`.robota`);return{settings:h(t,`settings.json`),settingsLocal:h(t,`settings.local.json`),logs:h(t,`logs`),sessions:h(t,`sessions`),memory:h(t,`memory`),checkpoints:h(t,`checkpoints`)}}function fp(){let e=h(x(),`.robota`);return{settings:h(e,`settings.json`),sessions:h(e,`sessions`),onboarded:h(e,`onboarded`)}}function pp(e){let t=e.fs??new Y,n=e.manifests.filter(t=>t.sequence>e.target.sequence),r=e.manifests.filter(t=>t.sequence>=e.target.sequence);return{target:mp(e.target),capturedFiles:e.target.files.map(n=>{let r=n.snapshotFile?h(e.checkpointDir(e.sessionId,e.target.id),n.snapshotFile):void 0,i=r?gp(r,t):void 0;return{originalPath:n.originalPath,relativePath:_(e.cwd,n.originalPath),existed:n.existed,restoreAction:n.existed?`restore-preimage`:`delete-created-file`,snapshotAvailable:n.existed?i!==void 0:!1,...i?{snapshotSizeBytes:i.size}:{}}}),restoreToCheckpoint:hp(n),rollbackThroughCheckpoint:hp(r)}}function mp(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function hp(e){return{checkpointIds:e.map(e=>e.id),fileCount:e.reduce((e,t)=>e+t.fileCount,0)}}function gp(e,t){try{return t.statSync(e)}catch{return}}const _p=`manifest.json`,vp=`files`;var yp=class{fs;fsAsync;cwd;rootDir;now;activeTurn=null;constructor(e,t=new Y,n=new ku){this.fs=t,this.fsAsync=n,this.cwd=v(e.cwd),this.rootDir=dp(this.cwd).checkpoints,this.now=e.now??(()=>new Date)}async beginTurn(e){this.activeTurn&&await this.finalizeTurn();let t=this.nextSequence(e.sessionId),n=`turn-${String(t).padStart(4,`0`)}`,r=h(this.sessionDir(e.sessionId),n);await this.fsAsync.mkdir(h(r,vp),{recursive:!0});let i={version:1,id:n,sessionId:e.sessionId,sequence:t,prompt:e.prompt,createdAt:this.now().toISOString(),fileCount:0,files:[]};return this.activeTurn={manifest:i,dir:r,capturedPaths:new Set},bp(i)}async captureFile(e){if(!this.activeTurn)return;let t=v(this.cwd,e);if(this.activeTurn.capturedPaths.has(t)||Sp(this.rootDir,t))return;let n=await this.createFileRecord(t,this.activeTurn);this.activeTurn.manifest.files.push(n),this.activeTurn.manifest.fileCount=this.activeTurn.manifest.files.length,this.activeTurn.capturedPaths.add(t)}async finalizeTurn(){if(!this.activeTurn)return;let e=this.activeTurn;return this.activeTurn=null,await this.writeManifest(e.dir,e.manifest),bp(e.manifest)}list(e){return this.loadManifests(e).map(bp)}inspect(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);return pp({cwd:this.cwd,sessionId:e,target:r,manifests:n,checkpointDir:(e,t)=>this.checkpointDir(e,t)})}async restoreToCheckpoint(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);let i=n.filter(e=>e.sequence>r.sequence).sort((e,t)=>t.sequence-e.sequence),a=0;for(let t of i)for(let n of t.files)await this.restoreFile(e,t.id,n),a+=1;for(let t of i)await this.fsAsync.rm(this.checkpointDir(e,t.id),{recursive:!0,force:!0});return{target:bp(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async rollbackThroughCheckpoint(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);let i=n.filter(e=>e.sequence>=r.sequence).sort((e,t)=>t.sequence-e.sequence),a=0;for(let t of i)for(let n of t.files)await this.restoreFile(e,t.id,n),a+=1;for(let t of i)await this.fsAsync.rm(this.checkpointDir(e,t.id),{recursive:!0,force:!0});return{target:bp(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async createFileRecord(e,t){if(!await Cp(this.fsAsync,this.fs,e))return{originalPath:e,existed:!1};let n=h(vp,`${String(t.manifest.files.length+1).padStart(6,`0`)}.content`);return await this.fsAsync.copyFile(e,h(t.dir,n)),{originalPath:e,existed:!0,snapshotFile:n}}async restoreFile(e,t,n){if(!n.existed){await this.fsAsync.rm(n.originalPath,{force:!0});return}if(!n.snapshotFile)throw Error(`Checkpoint file record is missing a snapshot: ${n.originalPath}`);await this.fsAsync.mkdir(p(n.originalPath),{recursive:!0}),await this.fsAsync.copyFile(h(this.checkpointDir(e,t),n.snapshotFile),n.originalPath)}loadManifests(e){let t=this.sessionDir(e);return wp(this.fs,t).map(e=>h(t,e,_p)).map(e=>Tp(this.fs,e)).filter(e=>e!==void 0).sort((e,t)=>e.sequence-t.sequence)}nextSequence(e){return(this.list(e).at(-1)?.sequence??0)+1}async writeManifest(e,t){await this.fsAsync.mkdir(e,{recursive:!0});let n=h(e,_p),r=`${n}.tmp`;await this.fsAsync.writeFile(r,JSON.stringify(t,null,2),`utf8`),await this.fsAsync.rename(r,n)}sessionDir(e){return h(this.rootDir,xp(e))}checkpointDir(e,t){return h(this.sessionDir(e),xp(t))}};function bp(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function xp(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function Sp(e,t){let n=_(e,t);return n.length===0||!n.startsWith(`..`)&&!n.startsWith(`/`)}async function Cp(e,t,n){try{return await e.access(n,t.constants.F_OK),!0}catch{return!1}}function wp(e,t){try{return e.readdirSync(t)}catch{return[]}}function Tp(e,t){try{let n=e.readFileSync(t,`utf8`);return JSON.parse(n)}catch{return}}function Ep(e){return e.source===`plugin`?`plugin`:`skill`}function Dp(e){return e.context===`fork`?`fork`:`inject`}function Op(e){return{type:`skill-activation`,skillName:e.skill.name,source:Ep(e.skill),invocation:e.invocation,mode:Dp(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function kp(e){let t=e.source===`plugin`?`plugin skill`:`skill`;return e.status===`failed`?`Skill failed: ${e.skillName}${e.error?` (${e.error})`:``}`:e.status===`completed`?`Skill completed: ${e.skillName}`:`Invoking ${t}: ${e.skillName}`}const Ap=new Set([`memory_candidate_saved`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`]);function jp(e){let t=e.topic?`: ${e.topic}`:``;switch(e.type){case`memory_candidate_saved`:return`Memory saved${t}`;case`memory_candidate_approved`:return`Memory approved${t}`;case`memory_candidate_rejected`:return`Memory rejected${t}${e.reason?` (${e.reason})`:``}`;case`memory_retrieved`:return`Memory recalled${t}`;case`memory_candidate_extracted`:return`Memory candidate extracted${t}`;case`memory_candidate_queued`:return`Memory candidate queued${t}`;case`memory_candidate_skipped`:return`Memory candidate skipped${t}${e.reason?` (${e.reason})`:``}`}}var Mp=class{cwd;getSessionId;getExecuting;persistSession;emitSkillActivation;emitMemoryEvent;history=[];editCheckpointStore=null;memoryEvents=[];usedMemoryReferences=[];contextReferences=[];systemContextReferences=[];skillActivationEvents=[];constructor(e,t,n,r,i,a,o=null){this.cwd=e,this.getSessionId=t,this.getExecuting=n,this.persistSession=r,this.emitSkillActivation=i,this.emitMemoryEvent=a,this.editCheckpointStore=o}restoreState(e){this.history=e.history,this.memoryEvents=e.memoryEvents,this.usedMemoryReferences=e.usedMemoryReferences,this.contextReferences=e.contextReferences,this.skillActivationEvents=e.skillActivationEvents}getState(){return{history:this.history,memoryEvents:this.memoryEvents,usedMemoryReferences:this.usedMemoryReferences,contextReferences:this.contextReferences,skillActivationEvents:this.skillActivationEvents}}append(e){this.history.push(e)}getHistory(){return this.history}clearHistory(){this.history=[],this.memoryEvents=[],this.usedMemoryReferences=[]}resetUsedMemoryReferences(){this.usedMemoryReferences=[]}recordContextReferenceUsage(e){this.contextReferences=lp(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=lp(this.contextReferences,e,{loadType:`prompt-reference`,status:`observed`}),this.persistSession()}listEditCheckpoints(){let e=this.getSessionId();return this.getCheckpointStore().list(e)}inspectEditCheckpoint(e){let t=this.getSessionId();return this.getCheckpointStore().inspect(t,e)}async restoreEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot restore edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push(H(q(`Restored edit checkpoint: ${e}`))),this.persistSession(),t}async rollbackEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot rollback edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().rollbackThroughCheckpoint(this.getSessionId(),e);return this.history.push(H(q(`Rolled back edit checkpoint: ${e}`))),this.persistSession(),t}async beginEditCheckpointTurn(e){this.editCheckpointStore&&await this.editCheckpointStore.beginTurn({sessionId:this.getSessionId(),prompt:e})}async finalizeEditCheckpointTurn(){if(this.editCheckpointStore)try{await this.editCheckpointStore.finalizeTurn()}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.history.push(H(q(`Checkpoint error: ${t.message}`))),t}}setEditCheckpointStore(e){this.editCheckpointStore=e}getUsedMemoryReferences(){return[...this.usedMemoryReferences]}recordMemoryEvent(e){this.memoryEvents.push(e),Ap.has(e.type)&&this.history.push({id:l(),timestamp:new Date(e.at),category:`event`,type:`memory-event`,data:{...e,message:jp(e)}}),this.emitMemoryEvent(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=up(e,this.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await cp(this.contextReferences,e,this.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=ou(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=su(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:l(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:kp(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){return this.editCheckpointStore||=new yp({cwd:this.cwd}),this.editCheckpointStore}};function Np(e){if(M(e))try{return JSON.parse(Se(e,`utf-8`))}catch{return}}function Pp(e){if(M(N(e,`pnpm-workspace.yaml`))||M(N(e,`pnpm-lock.yaml`)))return`pnpm`;if(M(N(e,`yarn.lock`)))return`yarn`;if(M(N(e,`bun.lockb`)))return`bun`;if(M(N(e,`package-lock.json`)))return`npm`}async function Fp(e){let t=N(e,`package.json`),n=N(e,`tsconfig.json`),r=N(e,`pyproject.toml`),i=N(e,`Cargo.toml`),a=N(e,`go.mod`);if(M(t)){let r=Np(t),i=M(n)?`typescript`:`javascript`,a=Pp(e);return{type:`node`,name:r?.name,packageManager:a,language:i}}return M(r)||M(N(e,`setup.py`))?{type:`python`,language:`python`}:M(i)?{type:`rust`,language:`rust`}:M(a)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}function Ip(e,t){e.injectRawMessage(t)}function Lp(e,t,n){let r=e.load(t);if(!r)return{history:[],sessionName:void 0,pendingRestoreMessages:null,backgroundTasks:[],backgroundTaskEvents:[],backgroundJobGroups:[],backgroundJobGroupEvents:[],skillActivationEvents:[],memoryEvents:[],usedMemoryReferences:[],contextReferences:[],sandboxSnapshotId:void 0,goal:void 0};let i=r.history??[],a=r.backgroundTasks??[],o=r.backgroundTaskEvents??[],s=r.backgroundJobGroups??[],c=r.backgroundJobGroupEvents??[],l=r.skillActivationEvents??[],u=r.memoryEvents??[],d=r.usedMemoryReferences??[],f=r.contextReferences??[],p=r.sandboxSnapshotId,{backgroundTasks:m,backgroundTaskEvents:h}=Rp(a,o),g=r.name,_=null;if(r.messages)if(n)for(let e of r.messages)Ip(n,e);else _=r.messages;return{history:i,sessionName:g,pendingRestoreMessages:_,backgroundTasks:m,backgroundTaskEvents:h,backgroundJobGroups:s,backgroundJobGroupEvents:c,skillActivationEvents:l,memoryEvents:u,usedMemoryReferences:d,contextReferences:f,sandboxSnapshotId:p,goal:r.goal}}function Rp(e,t){let n=new Date().toISOString(),r=[];return{backgroundTasks:e.map(e=>{if(zp(e.status)||Bp(e))return e;let t={...e,status:`failed`,timeoutReason:`stale_worker`,error:{category:`timeout`,message:`Restored background task is stale; worker cannot be reattached`,recoverable:!0},unread:!0,completedAt:n,updatedAt:n};return r.push({type:`background_task_failed`,task:t}),t}),backgroundTaskEvents:[...t,...r]}}function zp(e){return e===`completed`||e===`failed`||e===`cancelled`}function Bp(e){return e.kind===`scheduled`&&e.status===`sleeping`&&e.schedule!==void 0}function Vp(e){if(e.type===`background_task_started`&&e.task.kind===`agent`)return`SubagentStart`;if((e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)&&e.task.kind===`agent`)return`SubagentStop`}function Hp(e,t,n,r){let i=Vp(e);!i||!(`task`in e)||qa(n,i,{session_id:e.task.parentSessionId,cwd:t,hook_event_name:i,agent_id:e.task.id,agent_type:e.task.agentType??e.task.label,...e.task.transcriptPath?{agent_transcript_path:e.task.transcriptPath,transcript_path:e.task.transcriptPath}:{},...e.task.error?.message||e.task.timeoutReason?{reason:e.task.error?.message??e.task.timeoutReason}:{},...i===`SubagentStop`?{stop_hook_active:!1,...e.task.result?.output?{last_assistant_message:e.task.result.output}:{}}:{},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e.task.parentSessionId,ROBOTA_AGENT_ID:e.task.id,ROBOTA_AGENT_TYPE:e.task.agentType??e.task.label}},r).catch(()=>void 0)}const Up=[`Shell — execute host shell commands (OS-aware: bash/PowerShell)`,`Bash — alias of Shell (model-familiar name)`,`Read — read file contents with line numbers`,`Write — write content to a file`,`Edit — replace a string in a file`,`Glob — find files matching a pattern`,`Grep — search file contents with regex`,`WebFetch — fetch URL content as text`,`WebSearch — search the internet through the configured local tool`,`AskUserQuestion — ask the user structured questions (options/multi-select/free text) mid-task`];function Wp(e={}){return[oc(e),sc(e),hc(e),Sc(e),Tc(e),Oc,Fc,Hc,Gc,Zc()]}const Gp=new Set([`tools`,`disallowedTools`]),Kp=new Set([`maxTurns`]);function qp(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Jp(e){let t=e.split(`
122
+ `);e.history.push({id:l(),timestamp:new Date,category:`event`,type:`tool-summary`,data:{tools:e.activeTools.map(e=>({toolName:e.toolName,firstArg:e.firstArg,isRunning:e.isRunning,result:e.result,diffFile:e.diffFile,diffLines:e.diffLines,toolResultData:e.toolResultData})),summary:t}})}function $f(e){let t=e.filter(e=>!e.isRunning);if(t.length<=50)return e;let n=t.length-50,r=0;return e.filter(e=>!e.isRunning&&r<n?(r++,!1):!0)}function ep(e,t){let n=Kf(t.toolArgs),r={toolName:t.toolName,firstArg:n,isRunning:!0,...t.executionId?{executionId:t.executionId}:{}};return e.activeTools.push(r),e.history.push({id:l(),timestamp:new Date,category:`event`,type:`tool-start`,data:{toolName:t.toolName,firstArg:n,isRunning:!0}}),r}function tp(e,t){let n=t.denied?`denied`:t.success===!1?`error`:`success`,r=e.activeTools.findIndex(e=>e.toolName===t.toolName&&e.isRunning);if(r===-1)return null;let i={...e.activeTools[r],...Yf(t),isRunning:!1,result:n,toolResultData:t.toolResultData};return e.activeTools[r]=i,e.activeTools=$f(e.activeTools),e.history.push({id:l(),timestamp:new Date,category:`event`,type:`tool-end`,data:{toolName:i.toolName,firstArg:i.firstArg,isRunning:!1,result:n,toolResultData:t.toolResultData}}),i}const np=[{pattern:/\b401\b|invalid.*api.?key|authentication.*fail|unauthorized/i,message:"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json)."},{pattern:/\b403\b|permission.*denied|forbidden/i,message:"Access denied. Your API key may lack permission for this model. Check your provider plan or run `/provider` to switch accounts."},{pattern:/\b429\b|rate.?limit|too many requests|quota.*exceeded/i,message:"Rate limit reached. Wait a moment and try again. Consider switching to a different model with `/model`."},{pattern:/\b500\b|internal server error/i,message:`The AI provider returned an internal error. This is usually temporary — try again.`},{pattern:/\b503\b|service.*unavailable|overloaded/i,message:`The AI provider is temporarily unavailable or overloaded. Try again in a few seconds.`},{pattern:/\b502\b|bad gateway/i,message:`The AI provider gateway is unreachable. Check your network or try again shortly.`},{pattern:/\btimeout\b|timed.?out|ETIMEDOUT/i,message:`The request timed out. Check your internet connection, or try a shorter prompt to reduce response time.`},{pattern:/ENOTFOUND|ECONNREFUSED|ECONNRESET|network.*error|fetch.*fail/i,message:`Network connection failed. Check your internet connection and verify your provider URL in settings.`}];function rp(e){if(e instanceof sn)return"Invalid API key. Run `/provider` to reconfigure, or check your settings file (~/.robota/settings.json).";if(e instanceof cn)return`Rate limit reached${e.retryAfter?` (retry after ${e.retryAfter}s)`:``}. Wait a moment and try again. Consider switching to a different model with \`/model\`.`;if(e instanceof ln)return`Network connection failed. Check your internet connection and verify your provider URL in settings.`;if(e instanceof on&&e.originalError)return rp(e.originalError);let t=e.message;for(let{pattern:e,message:n}of np)if(e.test(t))return n;return t}async function ip(e,t,n,r){let i=r.getHistory();i.push(H(ai(t??e))),r.onWorkspaceUpdated();let a=r.getSession().getHistory().length;r.resetUsedMemoryReferences();try{let o=await Zu(e,r.getCwd(),n,r.getContextReferences());o.promptFileReferenceEntry&&i.push(o.promptFileReferenceEntry),r.recordContextReferenceUsage(o.activeContextReferenceRecords),r.recordPromptContextReferences(o.promptFileReferenceRecords),await r.beginEditCheckpointTurn(t??e);let s=await r.getSession().run(o.modelInput,o.hookInput);r.flushStreaming(),Qf({activeTools:r.getActiveTools(),history:i}),r.clearStreaming();let c=qu(s||`(empty response)`,r.getSession().getHistory(),i,a,r.getSession().getContextState(),o.promptFileReferenceRecords);i.push(H(oi(c.response))),c.usage&&i.push(Yu(c.usage)),r.onComplete(c),r.onContextUpdate()}catch(e){if(r.flushStreaming(),Gu(e)){let e=Ju(r.getSession().getHistory(),i,a,r.getSession().getContextState());Qf({activeTools:r.getActiveTools(),history:i}),r.clearStreaming(),e.response&&i.push(H(oi(e.response))),e.usage&&i.push(Yu(e.usage)),i.push(H(q(`Interrupted by user.`))),r.onInterrupted(e)}else{Qf({activeTools:r.getActiveTools(),history:i});let t=r.getStreamingText();if(r.clearStreaming(),t.trim().length>0){let e=oi(t);e.state=`interrupted`,i.push(H(e))}let n=e instanceof Error?e:Error(String(e)),a=rp(n);i.push(H(q(`Error: ${a}`,{metadata:{kind:`error`}}))),r.onError(n)}}}var ap=class{histTracker;skillRouter;callbacks;executing=!1;streamingText=``;flushTimer=null;activeTools=[];pendingPrompt=null;pendingDisplayInput;pendingRawInput;pendingTurnOptions={};shuttingDown=!1;wakeTaskIds=new Set;constructor(e,t,n){this.histTracker=e,this.skillRouter=t,this.callbacks=n}clearPendingQueue(){this.pendingTurnOptions.wakeTaskId!==void 0&&this.wakeTaskIds.delete(this.pendingTurnOptions.wakeTaskId),this.pendingPrompt=null,this.pendingDisplayInput=void 0,this.pendingRawInput=void 0,this.pendingTurnOptions={}}clearStreaming(){this.streamingText=``,this.activeTools=[],this.flushTimer&&=(clearTimeout(this.flushTimer),null)}flushStreaming(){this.flushTimer&&=(clearTimeout(this.flushTimer),null)}handleTextDelta(e){this.streamingText+=e,this.callbacks.emit(`text_delta`,e),this.flushTimer||=setTimeout(()=>{this.flushTimer=null},16)}handleCompactEvent(e){e.trigger===`auto`&&this.histTracker.append(H(q(`Auto compacted context: ${Math.round(e.before.usedPercentage)}% -> ${Math.round(e.after.usedPercentage)}%`))),this.callbacks.emit(`compact`,e),this.callbacks.emit(`context_update`,e.after)}handleToolExecution(e){let t={activeTools:this.activeTools,history:this.histTracker.getHistory()};if(e.type===`start`){let n=ep(t,e);this.activeTools=t.activeTools,this.callbacks.emit(`tool_start`,n)}else{let n=tp(t,e);this.activeTools=t.activeTools,n&&this.callbacks.emit(`tool_end`,n)}}emitExecutionWorkspaceUpdated(e,t){this.callbacks.getSession()&&this.callbacks.emit(`execution_workspace_event`,{type:`execution_workspace_updated`,cause:e,...t?{entryId:t}:{},snapshot:this.callbacks.getExecutionWorkspaceSnapshot()})}drainPendingQueue(e){if(!this.shuttingDown&&this.pendingPrompt){let t=this.pendingPrompt,n=this.pendingDisplayInput,r=this.pendingRawInput,i=this.pendingTurnOptions;this.clearPendingQueue(),setTimeout(()=>void e(t,n,r,i),0)}}async executePrompt(e,t,n,r,i,a,o,s,c={}){await Gf(r,i,a,o,()=>this.callbacks.getSessionOrThrow(),(e,t)=>this.callbacks.emit(e,t)),this.executing=!0,this.clearStreaming(),this.callbacks.emit(`turn_source`,c.turnSource??`user`),this.callbacks.emit(`user_message`,t??e),this.callbacks.emit(`thinking`,!0);try{await ip(e,t,n,{getSession:()=>this.callbacks.getSessionOrThrow(),getCwd:()=>this.callbacks.getCwd(),getHistory:()=>this.histTracker.getHistory(),getContextReferences:()=>this.histTracker.listInjectionContextReferences(),getActiveTools:()=>this.activeTools,resetUsedMemoryReferences:()=>this.histTracker.resetUsedMemoryReferences(),recordContextReferenceUsage:e=>this.histTracker.recordContextReferenceUsage(e),recordPromptContextReferences:e=>this.histTracker.recordPromptContextReferences(e),beginEditCheckpointTurn:e=>this.histTracker.beginEditCheckpointTurn(e),flushStreaming:()=>this.flushStreaming(),clearStreaming:()=>this.clearStreaming(),getStreamingText:()=>this.streamingText,onWorkspaceUpdated:()=>this.emitExecutionWorkspaceUpdated(`main_thread`),onComplete:e=>{this.callbacks.emit(`complete`,e)},onInterrupted:e=>{this.callbacks.emit(`interrupted`,e)},onError:e=>{this.callbacks.emit(`error`,e)},onContextUpdate:()=>{this.callbacks.emit(`context_update`,this.callbacks.getContextState())}})}finally{try{await this.histTracker.finalizeEditCheckpointTurn()}catch(e){this.callbacks.emit(`error`,e instanceof Error?e:Error(String(e)))}this.executing=!1,this.callbacks.emit(`thinking`,!1),c.wakeTaskId!==void 0&&this.wakeTaskIds.delete(c.wakeTaskId),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(s)}}async executeForkSkillCommand(e,t,n,r,i,a){if(this.executing)throw Error(`Cannot execute fork skill while another prompt is running.`);this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.histTracker.append(H(ai(n??`/${e.name}`))),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let n=await this.skillRouter.executeSkillWithActivation(e,t,i,r);return await this.applyForkSkillResult(n.result??`(empty response)`),n}catch(e){let t=e instanceof Error?e:Error(String(e));return this.histTracker.append(H(q(`Error: ${rp(t)}`))),this.callbacks.emit(`error`,t),{mode:`fork`,result:``}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(a)}}async executeForegroundCommand(e,t){this.executing=!0,this.clearStreaming(),this.callbacks.emit(`thinking`,!0),this.emitExecutionWorkspaceUpdated(`main_thread`);try{let t=await e();return this.callbacks.emit(`context_update`,this.callbacks.getContextState()),t}catch(e){return{success:!1,message:`Error: ${e instanceof Error?e.message:String(e)}`}}finally{this.executing=!1,this.callbacks.emit(`thinking`,!1),this.emitExecutionWorkspaceUpdated(`main_thread`),this.callbacks.persistSession(),this.drainPendingQueue(t)}}async applyForkSkillResult(e){this.flushStreaming(),Qf({activeTools:this.activeTools,history:this.histTracker.getHistory()}),this.clearStreaming();let t={response:e,history:this.histTracker.getHistory(),toolSummaries:[],contextState:this.callbacks.getContextState()};this.histTracker.append(H(oi(e))),this.callbacks.emit(`complete`,t),this.callbacks.emit(`context_update`,this.callbacks.getContextState())}};function op(e,t,n){let r=wf(n)?.customAgentRegistry?.(e)??Yd(e);if(!r)throw Error(`Unknown agent type: ${e}`);return t.allowedTools?{...r,tools:t.allowedTools}:r}async function sp(e,t,n){let r=wf(n);if(!r)throw Error(`Fork execution is not available. Agent runtime deps may not be initialized.`);return mf({agentDefinition:op(t.agent??`general-purpose`,t,n),parentConfig:r.config,parentContext:r.context,parentTools:r.tools,provider:r.provider,terminal:r.terminal,isForkWorker:!0,permissionMode:r.permissionMode,permissionHandler:r.permissionHandler,hooks:r.hooks,hookTypeExecutors:r.hookTypeExecutors,onTextDelta:r.onTextDelta,onToolExecution:r.onToolExecution}).run(e)}async function cp(e,t,n){let r=await ju([t],{cwd:n,reason:`manual`});if(gu(r.diagnostics))return{references:[...e],result:{evicted:[],diagnostics:[_u(r.diagnostics)]}};let i=r.references[0];if(!i)return{references:[...e],result:{evicted:[],diagnostics:[`No context reference was resolved.`]}};let a=iu(vu([i])[0],`manual`,`active`),o=au(e,a);return{references:o.references,result:{reference:a,evicted:o.evicted,diagnostics:[]}}}function lp(e,t,n){if(t.length===0)return[...e];let r=new Date().toISOString(),i=[...e];for(let e of t){let t=iu(e,n.loadType,n.status,r);i=au(i,t).references}return i}function up(e,t){let n=new Date().toISOString();return e.map(e=>{let r=_(t,e.filePath);return{id:`system:${r}`,sourcePath:e.filePath,relativePath:r,originalReference:r,loadType:`system`,status:`active`,byteLength:Buffer.byteLength(e.content,`utf-8`),loadedAt:n,lastUsedAt:n}})}function dp(e){let t=h(e,`.robota`);return{settings:h(t,`settings.json`),settingsLocal:h(t,`settings.local.json`),logs:h(t,`logs`),sessions:h(t,`sessions`),memory:h(t,`memory`),checkpoints:h(t,`checkpoints`)}}function fp(){let e=h(x(),`.robota`);return{settings:h(e,`settings.json`),sessions:h(e,`sessions`),onboarded:h(e,`onboarded`)}}function pp(e){let t=e.fs??new Y,n=e.manifests.filter(t=>t.sequence>e.target.sequence),r=e.manifests.filter(t=>t.sequence>=e.target.sequence);return{target:mp(e.target),capturedFiles:e.target.files.map(n=>{let r=n.snapshotFile?h(e.checkpointDir(e.sessionId,e.target.id),n.snapshotFile):void 0,i=r?gp(r,t):void 0;return{originalPath:n.originalPath,relativePath:_(e.cwd,n.originalPath),existed:n.existed,restoreAction:n.existed?`restore-preimage`:`delete-created-file`,snapshotAvailable:n.existed?i!==void 0:!1,...i?{snapshotSizeBytes:i.size}:{}}}),restoreToCheckpoint:hp(n),rollbackThroughCheckpoint:hp(r)}}function mp(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function hp(e){return{checkpointIds:e.map(e=>e.id),fileCount:e.reduce((e,t)=>e+t.fileCount,0)}}function gp(e,t){try{return t.statSync(e)}catch{return}}const _p=`manifest.json`,vp=`files`;var yp=class{fs;fsAsync;cwd;rootDir;now;activeTurn=null;constructor(e,t=new Y,n=new ku){this.fs=t,this.fsAsync=n,this.cwd=v(e.cwd),this.rootDir=dp(this.cwd).checkpoints,this.now=e.now??(()=>new Date)}async beginTurn(e){this.activeTurn&&await this.finalizeTurn();let t=this.nextSequence(e.sessionId),n=`turn-${String(t).padStart(4,`0`)}`,r=h(this.sessionDir(e.sessionId),n);await this.fsAsync.mkdir(h(r,vp),{recursive:!0});let i={version:1,id:n,sessionId:e.sessionId,sequence:t,prompt:e.prompt,createdAt:this.now().toISOString(),fileCount:0,files:[]};return this.activeTurn={manifest:i,dir:r,capturedPaths:new Set},bp(i)}async captureFile(e){if(!this.activeTurn)return;let t=v(this.cwd,e);if(this.activeTurn.capturedPaths.has(t)||Sp(this.rootDir,t))return;let n=await this.createFileRecord(t,this.activeTurn);this.activeTurn.manifest.files.push(n),this.activeTurn.manifest.fileCount=this.activeTurn.manifest.files.length,this.activeTurn.capturedPaths.add(t)}async finalizeTurn(){if(!this.activeTurn)return;let e=this.activeTurn;return this.activeTurn=null,await this.writeManifest(e.dir,e.manifest),bp(e.manifest)}list(e){return this.loadManifests(e).map(bp)}inspect(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);return pp({cwd:this.cwd,sessionId:e,target:r,manifests:n,checkpointDir:(e,t)=>this.checkpointDir(e,t)})}async restoreToCheckpoint(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);let i=n.filter(e=>e.sequence>r.sequence).sort((e,t)=>t.sequence-e.sequence),a=0;for(let t of i)for(let n of t.files)await this.restoreFile(e,t.id,n),a+=1;for(let t of i)await this.fsAsync.rm(this.checkpointDir(e,t.id),{recursive:!0,force:!0});return{target:bp(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async rollbackThroughCheckpoint(e,t){let n=this.loadManifests(e),r=n.find(e=>e.id===t);if(!r)throw Error(`Unknown edit checkpoint: ${t}`);let i=n.filter(e=>e.sequence>=r.sequence).sort((e,t)=>t.sequence-e.sequence),a=0;for(let t of i)for(let n of t.files)await this.restoreFile(e,t.id,n),a+=1;for(let t of i)await this.fsAsync.rm(this.checkpointDir(e,t.id),{recursive:!0,force:!0});return{target:bp(r),restoredCheckpointCount:i.length,restoredFileCount:a,removedCheckpointCount:i.length}}async createFileRecord(e,t){if(!await Cp(this.fsAsync,this.fs,e))return{originalPath:e,existed:!1};let n=h(vp,`${String(t.manifest.files.length+1).padStart(6,`0`)}.content`);return await this.fsAsync.copyFile(e,h(t.dir,n)),{originalPath:e,existed:!0,snapshotFile:n}}async restoreFile(e,t,n){if(!n.existed){await this.fsAsync.rm(n.originalPath,{force:!0});return}if(!n.snapshotFile)throw Error(`Checkpoint file record is missing a snapshot: ${n.originalPath}`);await this.fsAsync.mkdir(p(n.originalPath),{recursive:!0}),await this.fsAsync.copyFile(h(this.checkpointDir(e,t),n.snapshotFile),n.originalPath)}loadManifests(e){let t=this.sessionDir(e);return wp(this.fs,t).map(e=>h(t,e,_p)).map(e=>Tp(this.fs,e)).filter(e=>e!==void 0).sort((e,t)=>e.sequence-t.sequence)}nextSequence(e){return(this.list(e).at(-1)?.sequence??0)+1}async writeManifest(e,t){await this.fsAsync.mkdir(e,{recursive:!0});let n=h(e,_p),r=`${n}.tmp`;await this.fsAsync.writeFile(r,JSON.stringify(t,null,2),`utf8`),await this.fsAsync.rename(r,n)}sessionDir(e){return h(this.rootDir,xp(e))}checkpointDir(e,t){return h(this.sessionDir(e),xp(t))}};function bp(e){return{id:e.id,sessionId:e.sessionId,sequence:e.sequence,prompt:e.prompt,createdAt:e.createdAt,fileCount:e.fileCount}}function xp(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function Sp(e,t){let n=_(e,t);return n.length===0||!n.startsWith(`..`)&&!n.startsWith(`/`)}async function Cp(e,t,n){try{return await e.access(n,t.constants.F_OK),!0}catch{return!1}}function wp(e,t){try{return e.readdirSync(t)}catch{return[]}}function Tp(e,t){try{let n=e.readFileSync(t,`utf8`);return JSON.parse(n)}catch{return}}function Ep(e){return e.source===`plugin`?`plugin`:`skill`}function Dp(e){return e.context===`fork`?`fork`:`inject`}function Op(e){return{type:`skill-activation`,skillName:e.skill.name,source:Ep(e.skill),invocation:e.invocation,mode:Dp(e.skill),status:e.status,timestamp:new Date().toISOString(),...e.qualifiedName===void 0?{}:{qualifiedName:e.qualifiedName},...e.error===void 0?{}:{error:e.error}}}function kp(e){let t=e.source===`plugin`?`plugin skill`:`skill`;return e.status===`failed`?`Skill failed: ${e.skillName}${e.error?` (${e.error})`:``}`:e.status===`completed`?`Skill completed: ${e.skillName}`:`Invoking ${t}: ${e.skillName}`}const Ap=new Set([`memory_candidate_saved`,`memory_candidate_approved`,`memory_candidate_rejected`,`memory_retrieved`]);function jp(e){let t=e.topic?`: ${e.topic}`:``;switch(e.type){case`memory_candidate_saved`:return`Memory saved${t}`;case`memory_candidate_approved`:return`Memory approved${t}`;case`memory_candidate_rejected`:return`Memory rejected${t}${e.reason?` (${e.reason})`:``}`;case`memory_retrieved`:return`Memory recalled${t}`;case`memory_candidate_extracted`:return`Memory candidate extracted${t}`;case`memory_candidate_queued`:return`Memory candidate queued${t}`;case`memory_candidate_skipped`:return`Memory candidate skipped${t}${e.reason?` (${e.reason})`:``}`}}var Mp=class{cwd;getSessionId;getExecuting;persistSession;emitSkillActivation;emitMemoryEvent;history=[];editCheckpointStore=null;memoryEvents=[];usedMemoryReferences=[];contextReferences=[];systemContextReferences=[];skillActivationEvents=[];constructor(e,t,n,r,i,a,o=null){this.cwd=e,this.getSessionId=t,this.getExecuting=n,this.persistSession=r,this.emitSkillActivation=i,this.emitMemoryEvent=a,this.editCheckpointStore=o}restoreState(e){this.history=e.history,this.memoryEvents=e.memoryEvents,this.usedMemoryReferences=e.usedMemoryReferences,this.contextReferences=e.contextReferences,this.skillActivationEvents=e.skillActivationEvents}getState(){return{history:this.history,memoryEvents:this.memoryEvents,usedMemoryReferences:this.usedMemoryReferences,contextReferences:this.contextReferences,skillActivationEvents:this.skillActivationEvents}}append(e){this.history.push(e)}getHistory(){return this.history}clearHistory(){this.history=[],this.memoryEvents=[],this.usedMemoryReferences=[]}resetUsedMemoryReferences(){this.usedMemoryReferences=[]}recordContextReferenceUsage(e){this.contextReferences=lp(this.contextReferences,e,{loadType:`manual`,status:`active`}),this.persistSession()}recordPromptContextReferences(e){this.contextReferences=lp(this.contextReferences,e,{loadType:`prompt-reference`,status:`observed`}),this.persistSession()}listEditCheckpoints(){let e=this.getSessionId();return this.getCheckpointStore().list(e)}inspectEditCheckpoint(e){let t=this.getSessionId();return this.getCheckpointStore().inspect(t,e)}async restoreEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot restore edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().restoreToCheckpoint(this.getSessionId(),e);return this.history.push(H(q(`Restored edit checkpoint: ${e}`))),this.persistSession(),t}async rollbackEditCheckpoint(e){if(this.getExecuting())throw Error(`Cannot rollback edit checkpoint while a prompt is running.`);let t=await this.getCheckpointStore().rollbackThroughCheckpoint(this.getSessionId(),e);return this.history.push(H(q(`Rolled back edit checkpoint: ${e}`))),this.persistSession(),t}async beginEditCheckpointTurn(e){this.editCheckpointStore&&await this.editCheckpointStore.beginTurn({sessionId:this.getSessionId(),prompt:e})}async finalizeEditCheckpointTurn(){if(this.editCheckpointStore)try{await this.editCheckpointStore.finalizeTurn()}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.history.push(H(q(`Checkpoint error: ${t.message}`))),t}}setEditCheckpointStore(e){this.editCheckpointStore=e}getUsedMemoryReferences(){return[...this.usedMemoryReferences]}recordMemoryEvent(e){this.memoryEvents.push(e),Ap.has(e.type)&&this.history.push({id:l(),timestamp:new Date(e.at),category:`event`,type:`memory-event`,data:{...e,message:jp(e)}}),this.emitMemoryEvent(e),this.persistSession()}recordSystemContextFiles(e){this.systemContextReferences=up(e,this.cwd)}listContextReferences(){return[...this.systemContextReferences,...this.contextReferences]}listInjectionContextReferences(){return[...this.contextReferences]}async addContextReference(e){let{references:t,result:n}=await cp(this.contextReferences,e,this.cwd);return this.contextReferences=t,this.persistSession(),n}removeContextReference(e){let t=ou(this.contextReferences,e);return this.contextReferences=t.references,this.persistSession(),t.result}clearContextReferences(){let e=su(this.contextReferences);return this.contextReferences=[],this.persistSession(),e}getSkillActivationEvents(){return[...this.skillActivationEvents]}recordSkillActivationEvent(e,t){this.skillActivationEvents.push(e),t&&this.history.push({id:l(),timestamp:new Date(e.timestamp),category:`event`,type:`skill-activation`,data:{...e,message:kp(e)}}),this.emitSkillActivation(e),this.persistSession()}getCheckpointStore(){return this.editCheckpointStore||=new yp({cwd:this.cwd}),this.editCheckpointStore}};function Np(e){if(N(e))try{return JSON.parse(xe(e,`utf-8`))}catch{return}}function Pp(e){if(N(P(e,`pnpm-workspace.yaml`))||N(P(e,`pnpm-lock.yaml`)))return`pnpm`;if(N(P(e,`yarn.lock`)))return`yarn`;if(N(P(e,`bun.lockb`)))return`bun`;if(N(P(e,`package-lock.json`)))return`npm`}async function Fp(e){let t=P(e,`package.json`),n=P(e,`tsconfig.json`),r=P(e,`pyproject.toml`),i=P(e,`Cargo.toml`),a=P(e,`go.mod`);if(N(t)){let r=Np(t),i=N(n)?`typescript`:`javascript`,a=Pp(e);return{type:`node`,name:r?.name,packageManager:a,language:i}}return N(r)||N(P(e,`setup.py`))?{type:`python`,language:`python`}:N(i)?{type:`rust`,language:`rust`}:N(a)?{type:`go`,language:`go`}:{type:`unknown`,language:`unknown`}}function Ip(e,t){e.injectRawMessage(t)}function Lp(e,t,n){let r=e.load(t);if(!r)return{history:[],sessionName:void 0,pendingRestoreMessages:null,backgroundTasks:[],backgroundTaskEvents:[],backgroundJobGroups:[],backgroundJobGroupEvents:[],skillActivationEvents:[],memoryEvents:[],usedMemoryReferences:[],contextReferences:[],sandboxSnapshotId:void 0,goal:void 0};let i=r.history??[],a=r.backgroundTasks??[],o=r.backgroundTaskEvents??[],s=r.backgroundJobGroups??[],c=r.backgroundJobGroupEvents??[],l=r.skillActivationEvents??[],u=r.memoryEvents??[],d=r.usedMemoryReferences??[],f=r.contextReferences??[],p=r.sandboxSnapshotId,{backgroundTasks:m,backgroundTaskEvents:h}=Rp(a,o),g=r.name,_=null;if(r.messages)if(n)for(let e of r.messages)Ip(n,e);else _=r.messages;return{history:i,sessionName:g,pendingRestoreMessages:_,backgroundTasks:m,backgroundTaskEvents:h,backgroundJobGroups:s,backgroundJobGroupEvents:c,skillActivationEvents:l,memoryEvents:u,usedMemoryReferences:d,contextReferences:f,sandboxSnapshotId:p,goal:r.goal}}function Rp(e,t){let n=new Date().toISOString(),r=[];return{backgroundTasks:e.map(e=>{if(zp(e.status)||Bp(e))return e;let t={...e,status:`failed`,timeoutReason:`stale_worker`,error:{category:`timeout`,message:`Restored background task is stale; worker cannot be reattached`,recoverable:!0},unread:!0,completedAt:n,updatedAt:n};return r.push({type:`background_task_failed`,task:t}),t}),backgroundTaskEvents:[...t,...r]}}function zp(e){return e===`completed`||e===`failed`||e===`cancelled`}function Bp(e){return e.kind===`scheduled`&&e.status===`sleeping`&&e.schedule!==void 0}function Vp(e){if(e.type===`background_task_started`&&e.task.kind===`agent`)return`SubagentStart`;if((e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)&&e.task.kind===`agent`)return`SubagentStop`}function Hp(e,t,n,r){let i=Vp(e);!i||!(`task`in e)||qa(n,i,{session_id:e.task.parentSessionId,cwd:t,hook_event_name:i,agent_id:e.task.id,agent_type:e.task.agentType??e.task.label,...e.task.transcriptPath?{agent_transcript_path:e.task.transcriptPath,transcript_path:e.task.transcriptPath}:{},...e.task.error?.message||e.task.timeoutReason?{reason:e.task.error?.message??e.task.timeoutReason}:{},...i===`SubagentStop`?{stop_hook_active:!1,...e.task.result?.output?{last_assistant_message:e.task.result.output}:{}}:{},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e.task.parentSessionId,ROBOTA_AGENT_ID:e.task.id,ROBOTA_AGENT_TYPE:e.task.agentType??e.task.label}},r).catch(()=>void 0)}const Up=[`Shell — execute host shell commands (OS-aware: bash/PowerShell)`,`Bash — alias of Shell (model-familiar name)`,`Read — read file contents with line numbers`,`Write — write content to a file`,`Edit — replace a string in a file`,`Glob — find files matching a pattern`,`Grep — search file contents with regex`,`WebFetch — fetch URL content as text`,`WebSearch — search the internet through the configured local tool`,`AskUserQuestion — ask the user structured questions (options/multi-select/free text) mid-task`];function Wp(e={}){return[oc(e),sc(e),hc(e),Sc(e),Tc(e),Oc,Fc,Hc,Gc,Zc()]}const Gp=new Set([`tools`,`disallowedTools`]),Kp=new Set([`maxTurns`]);function qp(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Jp(e){let t=e.split(`
123
123
  `);if(t[0]?.trim()!==`---`)return{frontmatter:null,body:e};let n=-1;for(let e=1;e<t.length;e++)if(t[e]?.trim()===`---`){n=e;break}if(n===-1)return{frontmatter:null,body:e};let r={};for(let e=1;e<n;e++){let n=t[e].match(/^([a-zA-Z][a-zA-Z0-9]*(?:[A-Z][a-z]*)*):\s*(.+)/);if(!n)continue;let i=n[1],a=n[2].trim();Gp.has(i)?r[i]=qp(a):Kp.has(i)?r[i]=parseInt(a,10):r[i]=a}let i=t.slice(n+1).join(`
124
124
  `).trim();return{frontmatter:Object.keys(r).length>0?r:null,body:i}}function Yp(e,t){if(!t.existsSync(e))return[];let n=[],r;try{r=t.readdirSync(e,{withFileTypes:!0})}catch{return[]}for(let i of r){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let r=h(e,i.name),{frontmatter:a,body:o}=Jp(t.readFileSync(r,`utf-8`)),s=f(i.name,`.md`),c={name:a?.name??s,description:a?.description??``,systemPrompt:o};a?.model!==void 0&&(c.model=a.model),a?.maxTurns!==void 0&&(c.maxTurns=a.maxTurns),a?.tools!==void 0&&(c.tools=a.tools),a?.disallowedTools!==void 0&&(c.disallowedTools=a.disallowedTools),n.push(c)}return n}var Xp=class{cwd;home;fs;constructor(e,t,n=new Y){this.cwd=e,this.home=t??x(),this.fs=n}loadAll(){let e=[Yp(h(this.cwd,`.robota`,`agents`),this.fs),Yp(h(this.cwd,`.agents`,`agents`),this.fs),Yp(h(this.cwd,`.claude`,`agents`),this.fs),Yp(h(this.home,`.robota`,`agents`),this.fs),Yp(h(this.home,`.claude`,`agents`),this.fs)],t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.name)||(t.add(e.name),n.push(e));let r=[...n];for(let e of Jd)t.has(e.name)||r.push(e);return r}getAgent(e){return this.loadAll().find(t=>t.name===e)}};function Zp(e){let t=e.content.trim();return e.title?[`## ${e.title}`,t].join(`
125
125
  `):t}function Qp(e){return[...e].filter(e=>e.content.trim().length>0).sort((e,t)=>e.priority-t.priority||e.id.localeCompare(t.id)).map(e=>Zp(e)).join(`
@@ -127,18 +127,18 @@ Do not use emojis.`}function Zd(){return`You are a worker subagent executing a s
127
127
  `)}function $p(e,t,n,r,i){return{id:e,title:t,priority:n,content:r,source:i}}function em(e){return $p(`preset-persona`,void 0,5,e,`persona`)}function tm(){return $p(`preset-self-verification`,void 0,6,`Before you report a task complete, verify your work against this session's tool results — re-run the relevant checks and confirm the outcome matches what was asked. If something is not yet verified, say so plainly rather than implying it is done.`,`self-verification`)}function nm(e){if(e)return $p(`runtime-cwd`,`Working Directory`,30,`\`${e}\``,`runtime`)}function rm(e){let t=[];return e.name!==void 0&&t.push(`- **Name:** ${e.name}`),e.type!==`unknown`&&t.push(`- **Type:** ${e.type}`),e.language!==`unknown`&&t.push(`- **Language:** ${e.language}`),e.packageManager!==void 0&&t.push(`- **Package manager:** ${e.packageManager}`),$p(`runtime-project`,`Current Project`,40,t.join(`
128
128
  `),`runtime`)}function im(e){return $p(`permission-mode`,`Permission Mode`,50,`- **Permission mode:** ${e}`,`permissions`)}function am(e){if(!(e===void 0||e.trim().length===0))return $p(`runtime-response-language`,`Response Language`,45,e,`runtime`)}function om(e){if(e.trim().length!==0)return $p(`project-agents-md`,`Agent Instructions`,10,e,`project-instructions`)}function sm(e){if(e.trim().length!==0)return $p(`project-claude-md`,`Project Notes`,20,e,`project-instructions`)}function cm(e){if(!(e===void 0||e.trim().length===0))return $p(`project-memory`,`Project Memory`,25,e,`project-instructions`)}function lm(e){if(!(e===void 0||e.trim().length===0))return $p(`active-task-context`,`Active Task Context`,27,e,`project-instructions`)}function um(e){if(e.length!==0)return $p(`tool-descriptions`,`Available Tools`,60,e.map(e=>`- ${e}`).join(`
129
129
  `),`tool`)}function dm(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}`}function fm(e,t,n,r,i){let a=i.filter(t=>t.modelInvocable&&t.kind===e).map(dm);if(a.length!==0)return $p(`capability-${e}`,t,n,a.join(`
130
- `),r)}function pm(e){let t=[],n=fm(`builtin-command`,`Built-in Commands`,70,`command`,e),r=fm(`skill`,`Skills`,80,`skill`,e),i=fm(`agent`,`Agents`,90,`agent`,e),a=fm(`tool`,`Tools`,100,`tool`,e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),a&&t.push(a),t}function mm(e,t){t!==void 0&&e.push(t)}function hm(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function gm(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function _m(e){return[...e.commandDescriptors??[],...e.skills?hm(e.skills):[],...e.agents?gm(e.agents):[]]}function vm(e){let t=[];return mm(t,e.persona!==void 0&&e.persona.trim().length>0?em(e.persona):void 0),mm(t,e.selfVerification===!0?tm():void 0),mm(t,om(e.agentsMd)),mm(t,sm(e.claudeMd)),mm(t,cm(e.memoryMd)),mm(t,lm(e.taskContext)),mm(t,nm(e.cwd)),t.push(rm(e.projectInfo)),mm(t,am(e.language)),t.push(im(e.permissionMode)),mm(t,um(e.toolDescriptions)),t.push(...pm(_m(e))),Qp(t)}const ym=A.object({command:A.string().describe(`The shell command to start in the background`),timeout:A.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:A.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:A.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:A.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function bm(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function xm(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function Sm(e,t){try{let n=await t.backgroundTaskManager.spawn({kind:`process`,label:e.command,mode:`background`,parentSessionId:t.parentSessionId??`unknown-session`,depth:0,cwd:e.workingDirectory??t.cwd??process.cwd(),command:e.command,stdin:e.stdin,timeoutMs:e.timeout??12e4,outputLimitBytes:e.outputLimitBytes,metadata:t.metadata});return bm(n.id,n.status,e.command)}catch(e){return xm(e instanceof Error?e.message:String(e))}}function Cm(e){return $s(`BackgroundProcess`,`Start a shell command as a managed background task. Use this for long-running commands that should not block the current conversation. Use /background list, /background read <taskId>, /background cancel <taskId>, or /background close <taskId> to inspect or control it.`,ym,async t=>Sm(t,e))}function wm(e,t,n,r,i,a){let o,s=[],c;if(e.enableAgentRuntime||e.enableParallelSubagents){let l=new Xp(n);s=l.loadAll(),o={config:e.config,context:e.context,tools:i,terminal:e.terminal,provider:r,cwd:n,parentSessionId:t,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.config.hooks,hookTypeExecutors:a.length>0?a:void 0,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution,customAgentRegistry:e=>l.getAgent(e),agentDefinitions:s};let u=new os({runner:(e.subagentRunnerFactory??xf)(o),backgroundTaskRunners:e.backgroundTaskRunners});o.subagentManager=u,c=u.getBackgroundTaskManager(),o.backgroundTaskManager=c}else c=new ko({runners:e.backgroundTaskRunners??[]});let l=e.sessionLogger;return l&&c.subscribe(e=>km(l,t,e)),c.subscribe(t=>Hp(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:o,agentDefinitions:s,backgroundTaskManager:c}}function Tm(e,t,n,r,i){if(!e.backgroundTaskRunners?.some(e=>e.kind===`process`))return{backgroundProcessToolDeps:void 0};let a={backgroundTaskManager:t,cwd:r,parentSessionId:n,metadata:_d({kind:`tool_call`,sessionId:n,label:`BackgroundProcess`})};return i.push(Cm(a)),{backgroundProcessToolDeps:a}}function Em(e,t,n,r,i){return{agentsMd:e.context.agentsMd,claudeMd:e.context.claudeMd,memoryMd:e.context.memoryMd,taskContext:e.context.taskContext,toolDescriptions:n,permissionMode:e.permissionMode??Ea[e.config.defaultTrustLevel]??`default`,projectInfo:e.projectInfo??{type:`unknown`,language:`unknown`},cwd:t,language:e.config.language,skills:r.map(e=>({name:e.name,description:e.description,disableModelInvocation:e.disableModelInvocation})),...i.length>0?{agents:i.map(e=>({name:e.name,description:e.description}))}:{},commandDescriptors:e.commandDescriptors??[]}}function Dm(e,t,n,r,i,a,o){let s=e.systemPromptBuilder??vm,c=[...Up,...r?r.commandTools.map(af):[]],l=e.toolDescriptions??(i?[...c,`BackgroundProcess — start long-running shell commands as managed background tasks`]:c),u=e.persona,d=e.selfVerification,f=Em(e,t,l,a,o),p=s({...f,...u===void 0?{}:{persona:u},...d===void 0?{}:{selfVerification:d}});return{finalSystemMessage:e.appendSystemPrompt?`${p}\n\n${e.appendSystemPrompt}`:p,rebuildSystemMessage:(t,n,r)=>{r?.persona!==void 0&&(u=r.persona),r?.selfVerification!==void 0&&(d=r.selfVerification);let i=s({...f,...u===void 0?{}:{persona:u},...d===void 0?{}:{selfVerification:d},agentsMd:t,claudeMd:n});return e.appendSystemPrompt?`${i}\n\n${e.appendSystemPrompt}`:i}}}function Om(e,t,n,r){t&&(t.parentSessionId=e.getSessionId()),t&&(t.isParallelSubagentsEnabled=()=>e.getParallelSubagentsEnabled()),n&&(n.parentSessionId=e.getSessionId()),Kd(e,r),t&&Cf(e,t)}function km(e,t,n){let r={};if(n.type===`background_task_created`){r.taskId=n.task.id;let e=n.task.metadata?.executionOriginToolCallId;typeof e==`string`&&(r.originToolCallId=e)}e.log(t,`background_task_event`,{backgroundEventType:n.type,backgroundEvent:n,...r})}const Am=new Set([`Write`,`Edit`]);function jm(e,t){return e.map(e=>Am.has(e.getName())?new Mm(e,t):e)}var Mm=class{delegate;recorder;schema;constructor(e,t){this.delegate=e,this.recorder=t,this.schema=e.schema}setEventService(e){this.delegate.setEventService(e)}async execute(e,t){let n=Nm(e);return n&&await this.recorder.captureFile(n),this.delegate.execute(e,t)}validate(e){return this.delegate.validate(e)}validateParameters(e){return this.delegate.validateParameters(e)}getDescription(){return this.delegate.getDescription()}getName(){return this.delegate.getName()}};function Nm(e){if(!e||typeof e!=`object`)return;let t=e.filePath;return typeof t==`string`&&t.length>0?t:void 0}const Pm=new Set([`disable-model-invocation`,`user-invocable`]),Fm=new Set([`allowed-tools`]);function Im(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Lm(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Rm(e){let t=e.split(`
131
- `);if(t[0]?.trim()!==`---`)return null;let n={};for(let e=1;e<t.length;e++){let r=t[e];if(r.trim()===`---`)break;let i=r.match(/^([a-z][a-z0-9-]*):\s*(.+)/);if(!i)continue;let a=i[1],o=i[2].trim(),s=Im(a);Pm.has(a)?n[s]=o===`true`:Fm.has(a)?n[s]=Lm(o):n[s]=o}return Object.keys(n).length>0?n:null}function zm(e,t,n){let r={name:e?.name??n,description:e?.description??`Skill: ${n}`,source:`skill`,skillContent:t};return e?.argumentHint!==void 0&&(r.argumentHint=e.argumentHint),e?.disableModelInvocation!==void 0&&(r.disableModelInvocation=e.disableModelInvocation),e?.userInvocable!==void 0&&(r.userInvocable=e.userInvocable),e?.allowedTools!==void 0&&(r.allowedTools=e.allowedTools),e?.model!==void 0&&(r.model=e.model),e?.effort!==void 0&&(r.effort=e.effort),e?.context!==void 0&&(r.context=e.context),e?.agent!==void 0&&(r.agent=e.agent),r}function Bm(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isDirectory())continue;let r=h(e,i.name,`SKILL.md`);if(!t.existsSync(r))continue;let a=t.readFileSync(r,`utf-8`),o=Rm(a);n.push(zm(o,a,i.name))}return n}function Vm(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let r=h(e,i.name),a=t.readFileSync(r,`utf-8`),o=Rm(a),s=f(i.name,`.md`);n.push(zm(o,a,s))}return n}var Hm=class{name=`skill`;cwd;home;fs;cachedCommands=null;constructor(e,t,n=new Y){this.cwd=e,this.home=t??x(),this.fs=n}getCommands(){if(this.cachedCommands)return this.cachedCommands;let e=[Bm(h(this.cwd,`.claude`,`skills`),this.fs),Vm(h(this.cwd,`.claude`,`commands`),this.fs),Bm(h(this.home,`.robota`,`skills`),this.fs),Bm(h(this.cwd,`.agents`,`skills`),this.fs)],t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.name)||(t.add(e.name),n.push(e));return this.cachedCommands=n,this.cachedCommands}getModelInvocableSkills(){return this.getCommands().filter(e=>e.disableModelInvocation!==!0)}getUserInvocableSkills(){return this.getCommands().filter(e=>e.userInvocable!==!1)}},Um=class extends Error{filePath;constructor(e,t){super(`Settings file ${e} contains invalid JSON: ${t}. Fix or delete the file, or run robota diagnose.`),this.name=`SettingsParseError`,this.filePath=e}};function Wm(){return h(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function Gm(e,t){return t===void 0||t===`user`?Wm():h(e,`.robota`,`settings.local.json`)}function Km(e){if(!T(e))return{};let t=O(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new Um(e,t instanceof Error?t.message:String(t))}}function qm(e,t){D(p(e),{recursive:!0}),k(e,JSON.stringify(t,null,2)+`
132
- `,`utf8`)}function Jm(e){return T(e)?(oe(e),!0):!1}const Ym=`report_goal_status`,Xm=A.object({status:A.enum([`continue`,`satisfied`]).describe(`"satisfied" when the assigned goal is fully achieved; otherwise "continue".`),reason:A.string().describe(`A short justification for the status — what was achieved or what remains.`)});function Zm(){return $s(Ym,`Report progress toward the currently assigned autonomous goal. Call this only when you have an assigned goal: use status "satisfied" once it is fully achieved, or "continue" with the remaining work. Do not call it when no goal has been assigned.`,Xm,async e=>({acknowledged:!0,status:e.status===`satisfied`?`satisfied`:`continue`}))}const Qm=`When you have made as much progress as you can this turn, call \`${Ym}\`: use status "satisfied" once the goal is fully achieved, or status "continue" with a short reason describing the remaining work. Do the actual work with your tools first; the signal only reports your assessment.`;function $m(e){return[`You have been assigned an autonomous goal to pursue across multiple turns:`,``,`GOAL: ${e}`,``,`Work toward this goal now. ${Qm}`].join(`
130
+ `),r)}function pm(e){let t=[],n=fm(`builtin-command`,`Built-in Commands`,70,`command`,e),r=fm(`skill`,`Skills`,80,`skill`,e),i=fm(`agent`,`Agents`,90,`agent`,e),a=fm(`tool`,`Tools`,100,`tool`,e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),a&&t.push(a),t}function mm(e,t){t!==void 0&&e.push(t)}function hm(e){return e.map(e=>({name:e.name,kind:`skill`,description:e.description,userInvocable:!0,modelInvocable:e.disableModelInvocation!==!0}))}function gm(e){return e.map(e=>({name:e.name,kind:`agent`,description:e.description,userInvocable:!1,modelInvocable:!0,safety:`background-agent`}))}function _m(e){return[...e.commandDescriptors??[],...e.skills?hm(e.skills):[],...e.agents?gm(e.agents):[]]}function vm(e){let t=[];return mm(t,e.persona!==void 0&&e.persona.trim().length>0?em(e.persona):void 0),mm(t,e.selfVerification===!0?tm():void 0),mm(t,om(e.agentsMd)),mm(t,sm(e.claudeMd)),mm(t,cm(e.memoryMd)),mm(t,lm(e.taskContext)),mm(t,nm(e.cwd)),t.push(rm(e.projectInfo)),mm(t,am(e.language)),t.push(im(e.permissionMode)),mm(t,um(e.toolDescriptions)),t.push(...pm(_m(e))),Qp(t)}const ym=j.object({command:j.string().describe(`The shell command to start in the background`),timeout:j.number().optional().describe(`Optional timeout in milliseconds. Default is 120000.`),workingDirectory:j.string().optional().describe(`Working directory for the command. Defaults to the current project directory.`),stdin:j.string().optional().describe(`Optional stdin to write after the process starts.`),outputLimitBytes:j.number().optional().describe(`Maximum captured output bytes kept in the task result.`)});function bm(e,t,n){return JSON.stringify({success:!0,background:!0,output:``,taskId:e,status:t,command:n})}function xm(e){return JSON.stringify({success:!1,background:!0,output:``,error:`Background process error: ${e}`})}async function Sm(e,t){try{let n=await t.backgroundTaskManager.spawn({kind:`process`,label:e.command,mode:`background`,parentSessionId:t.parentSessionId??`unknown-session`,depth:0,cwd:e.workingDirectory??t.cwd??process.cwd(),command:e.command,stdin:e.stdin,timeoutMs:e.timeout??12e4,outputLimitBytes:e.outputLimitBytes,metadata:t.metadata});return bm(n.id,n.status,e.command)}catch(e){return xm(e instanceof Error?e.message:String(e))}}function Cm(e){return $s(`BackgroundProcess`,`Start a shell command as a managed background task. Use this for long-running commands that should not block the current conversation. Use /background list, /background read <taskId>, /background cancel <taskId>, or /background close <taskId> to inspect or control it.`,ym,async t=>Sm(t,e))}function wm(e,t,n,r,i,a){let o,s=[],c;if(e.enableAgentRuntime||e.enableParallelSubagents){let l=new Xp(n);s=l.loadAll(),o={config:e.config,context:e.context,tools:i,terminal:e.terminal,provider:r,cwd:n,parentSessionId:t,permissionMode:e.permissionMode,permissionHandler:e.permissionHandler,hooks:e.config.hooks,hookTypeExecutors:a.length>0?a:void 0,onTextDelta:e.onTextDelta,onToolExecution:e.onToolExecution,customAgentRegistry:e=>l.getAgent(e),agentDefinitions:s};let u=new os({runner:(e.subagentRunnerFactory??xf)(o),backgroundTaskRunners:e.backgroundTaskRunners});o.subagentManager=u,c=u.getBackgroundTaskManager(),o.backgroundTaskManager=c}else c=new ko({runners:e.backgroundTaskRunners??[]});let l=e.sessionLogger;return l&&c.subscribe(e=>km(l,t,e)),c.subscribe(t=>Hp(t,n,e.config.hooks,a.length>0?a:void 0)),{agentToolDeps:o,agentDefinitions:s,backgroundTaskManager:c}}function Tm(e,t,n,r,i){if(!e.backgroundTaskRunners?.some(e=>e.kind===`process`))return{backgroundProcessToolDeps:void 0};let a={backgroundTaskManager:t,cwd:r,parentSessionId:n,metadata:_d({kind:`tool_call`,sessionId:n,label:`BackgroundProcess`})};return i.push(Cm(a)),{backgroundProcessToolDeps:a}}function Em(e,t,n,r,i){return{agentsMd:e.context.agentsMd,claudeMd:e.context.claudeMd,memoryMd:e.context.memoryMd,taskContext:e.context.taskContext,toolDescriptions:n,permissionMode:e.permissionMode??Ea[e.config.defaultTrustLevel]??`default`,projectInfo:e.projectInfo??{type:`unknown`,language:`unknown`},cwd:t,language:e.config.language,skills:r.map(e=>({name:e.name,description:e.description,disableModelInvocation:e.disableModelInvocation})),...i.length>0?{agents:i.map(e=>({name:e.name,description:e.description}))}:{},commandDescriptors:e.commandDescriptors??[]}}function Dm(e,t,n,r,i,a,o){let s=e.systemPromptBuilder??vm,c=[...Up,...r?r.commandTools.map(af):[]],l=e.toolDescriptions??(i?[...c,`BackgroundProcess — start long-running shell commands as managed background tasks`]:c),u=e.persona,d=e.selfVerification,f=Em(e,t,l,a,o),p=s({...f,...u===void 0?{}:{persona:u},...d===void 0?{}:{selfVerification:d}});return{finalSystemMessage:e.appendSystemPrompt?`${p}\n\n${e.appendSystemPrompt}`:p,rebuildSystemMessage:(t,n,r)=>{r?.persona!==void 0&&(u=r.persona),r?.selfVerification!==void 0&&(d=r.selfVerification);let i=s({...f,...u===void 0?{}:{persona:u},...d===void 0?{}:{selfVerification:d},agentsMd:t,claudeMd:n});return e.appendSystemPrompt?`${i}\n\n${e.appendSystemPrompt}`:i}}}function Om(e,t,n,r){t&&(t.parentSessionId=e.getSessionId()),t&&(t.isParallelSubagentsEnabled=()=>e.getParallelSubagentsEnabled()),n&&(n.parentSessionId=e.getSessionId()),Kd(e,r),t&&Cf(e,t)}function km(e,t,n){let r={};if(n.type===`background_task_created`){r.taskId=n.task.id;let e=n.task.metadata?.executionOriginToolCallId;typeof e==`string`&&(r.originToolCallId=e)}e.log(t,`background_task_event`,{backgroundEventType:n.type,backgroundEvent:n,...r})}const Am=new Set([`Write`,`Edit`]);function jm(e,t){return e.map(e=>Am.has(e.getName())?new Mm(e,t):e)}var Mm=class{delegate;recorder;schema;constructor(e,t){this.delegate=e,this.recorder=t,this.schema=e.schema}setEventService(e){this.delegate.setEventService(e)}async execute(e,t){let n=Nm(e);return n&&await this.recorder.captureFile(n),this.delegate.execute(e,t)}validate(e){return this.delegate.validate(e)}validateParameters(e){return this.delegate.validateParameters(e)}getDescription(){return this.delegate.getDescription()}getName(){return this.delegate.getName()}};function Nm(e){if(!e||typeof e!=`object`)return;let t=e.filePath;return typeof t==`string`&&t.length>0?t:void 0}const Pm=new Set([`disable-model-invocation`,`user-invocable`]),Fm=new Set([`allowed-tools`]);function Im(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Lm(e){let t=e.includes(`,`)?/\s*,\s*/:/\s+/;return e.split(t).map(e=>e.trim()).filter(e=>e.length>0)}function Rm(e){let t=e.split(`
131
+ `);if(t[0]?.trim()!==`---`)return null;let n={};for(let e=1;e<t.length;e++){let r=t[e];if(r.trim()===`---`)break;let i=r.match(/^([a-z][a-z0-9-]*):\s*(.+)/);if(!i)continue;let a=i[1],o=i[2].trim(),s=Im(a);Pm.has(a)?n[s]=o===`true`:Fm.has(a)?n[s]=Lm(o):n[s]=o}return Object.keys(n).length>0?n:null}function zm(e,t,n){let r={name:e?.name??n,description:e?.description??`Skill: ${n}`,source:`skill`,skillContent:t};return e?.argumentHint!==void 0&&(r.argumentHint=e.argumentHint),e?.disableModelInvocation!==void 0&&(r.disableModelInvocation=e.disableModelInvocation),e?.userInvocable!==void 0&&(r.userInvocable=e.userInvocable),e?.allowedTools!==void 0&&(r.allowedTools=e.allowedTools),e?.model!==void 0&&(r.model=e.model),e?.effort!==void 0&&(r.effort=e.effort),e?.context!==void 0&&(r.context=e.context),e?.agent!==void 0&&(r.agent=e.agent),r}function Bm(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isDirectory())continue;let r=h(e,i.name,`SKILL.md`);if(!t.existsSync(r))continue;let a=t.readFileSync(r,`utf-8`),o=Rm(a);n.push(zm(o,a,i.name))}return n}function Vm(e,t){if(!t.existsSync(e))return[];let n=[],r=t.readdirSync(e,{withFileTypes:!0});for(let i of r){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let r=h(e,i.name),a=t.readFileSync(r,`utf-8`),o=Rm(a),s=f(i.name,`.md`);n.push(zm(o,a,s))}return n}var Hm=class{name=`skill`;cwd;home;fs;cachedCommands=null;constructor(e,t,n=new Y){this.cwd=e,this.home=t??x(),this.fs=n}getCommands(){if(this.cachedCommands)return this.cachedCommands;let e=[Bm(h(this.cwd,`.claude`,`skills`),this.fs),Vm(h(this.cwd,`.claude`,`commands`),this.fs),Bm(h(this.home,`.robota`,`skills`),this.fs),Bm(h(this.cwd,`.agents`,`skills`),this.fs)],t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.name)||(t.add(e.name),n.push(e));return this.cachedCommands=n,this.cachedCommands}getModelInvocableSkills(){return this.getCommands().filter(e=>e.disableModelInvocation!==!0)}getUserInvocableSkills(){return this.getCommands().filter(e=>e.userInvocable!==!1)}},Um=class extends Error{filePath;constructor(e,t){super(`Settings file ${e} contains invalid JSON: ${t}. Fix or delete the file, or run robota diagnose.`),this.name=`SettingsParseError`,this.filePath=e}};function Wm(){return h(process.env.HOME??process.env.USERPROFILE??`/`,`.robota`,`settings.json`)}function Gm(e,t){return t===void 0||t===`user`?Wm():h(e,`.robota`,`settings.local.json`)}function Km(e){if(!E(e))return{};let t=A(e,`utf8`);try{return JSON.parse(t)}catch(t){throw new Um(e,t instanceof Error?t.message:String(t))}}function qm(e,t){O(p(e),{recursive:!0}),ae(e,JSON.stringify(t,null,2)+`
132
+ `,`utf8`)}function Jm(e){return E(e)?(ie(e),!0):!1}const Ym=`report_goal_status`,Xm=j.object({status:j.enum([`continue`,`satisfied`]).describe(`"satisfied" when the assigned goal is fully achieved; otherwise "continue".`),reason:j.string().describe(`A short justification for the status — what was achieved or what remains.`)});function Zm(){return $s(Ym,`Report progress toward the currently assigned autonomous goal. Call this only when you have an assigned goal: use status "satisfied" once it is fully achieved, or "continue" with the remaining work. Do not call it when no goal has been assigned.`,Xm,async e=>({acknowledged:!0,status:e.status===`satisfied`?`satisfied`:`continue`}))}const Qm=`When you have made as much progress as you can this turn, call \`${Ym}\`: use status "satisfied" once the goal is fully achieved, or status "continue" with a short reason describing the remaining work. Do the actual work with your tools first; the signal only reports your assessment.`;function $m(e){return[`You have been assigned an autonomous goal to pursue across multiple turns:`,``,`GOAL: ${e}`,``,`Work toward this goal now. ${Qm}`].join(`
133
133
  `)}function eh(e){let t=e.progress[e.progress.length-1],n=t?.reason?`\nMost recent assessment: ${t.reason}`:``;return[`Continue pursuing the assigned goal (iteration ${e.iterations+1} of at most ${e.maxIterations}).`,``,`GOAL: ${e.objective}${n}`,``,`Keep going from where you left off. ${Qm}`].join(`
134
- `)}const th={now:()=>new Date().toISOString(),createId:()=>`goal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`};function nh(e){let t;try{t=JSON.parse(e)}catch{return null}return{status:t.status===`satisfied`?`satisfied`:`continue`,reason:typeof t.reason==`string`?t.reason:``}}function rh(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!(!n||n.name!==`report_goal_status`))return nh(n.args)}return null}function ih(e){return e.filter(e=>e.name!==Ym).length}var ah=class{deps;goal=null;consecutiveIdleTurns=0;noProgressLimit=2;constructor(e=th){this.deps=e}getState(){return this.goal}isActive(){return this.goal?.status===`active`}start(e,t={}){let n=e.trim();if(n.length===0)throw Error(`A goal objective must be a non-empty string.`);let r=t.maxIterations&&t.maxIterations>0?Math.floor(t.maxIterations):25;return this.noProgressLimit=t.noProgressLimit&&t.noProgressLimit>0?Math.floor(t.noProgressLimit):2,this.consecutiveIdleTurns=0,this.goal={id:this.deps.createId(),objective:n,status:`active`,iterations:0,maxIterations:r,startedAt:this.deps.now(),progress:[]},{goal:this.goal,prompt:$m(n)}}restore(e,t=2){this.goal=e.status===`active`?e:null,this.noProgressLimit=t,this.consecutiveIdleTurns=0}cancel(){return!this.goal||this.goal.status!==`active`?null:(this.goal={...this.goal,status:`stopped`,stopReason:`cancelled`},this.goal)}onTurnComplete(e){if(!this.goal||this.goal.status!==`active`)return null;let t=rh(e.toolSummaries),n=this.goal.iterations+1;if(this.goal={...this.goal,iterations:n,progress:[...this.goal.progress,{iteration:n,signal:t?.status??`continue`,reason:t?.reason??``}]},t?.status===`satisfied`)return this.stop(`satisfied`);let r=ih(e.toolSummaries)>0;return this.consecutiveIdleTurns=r?0:this.consecutiveIdleTurns+1,this.consecutiveIdleTurns>=this.noProgressLimit?this.stop(`no-progress`):n>=this.goal.maxIterations?this.stop(`max-iterations`):{action:`continue`,prompt:eh(this.goal),goal:this.goal}}stop(e){let t=e===`satisfied`?`satisfied`:`stopped`;return this.goal={...this.goal,status:t,stopReason:e},{action:`stop`,reason:e,goal:this.goal}}};function oh(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var sh=class{type=`agent`;sessionFactory;constructor(e){this.sessionFactory=e.sessionFactory}async execute(e,t){let n=e,r=n.maxTurns??50,i=n.timeout??60;try{let e=this.sessionFactory({maxTurns:r,timeout:i}),n=`Hook input:\n${JSON.stringify(t)}\n\nRespond with JSON: { "ok": boolean, "reason"?: string }`,a=await e.run(n),o=oh(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse agent response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by agent hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};function ch(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var lh=class{type=`prompt`;providerFactory;defaultModel;constructor(e){this.providerFactory=e.providerFactory,this.defaultModel=e.defaultModel}async execute(e,t){let n=e,r=n.model??this.defaultModel;try{let e=this.providerFactory(r),i=`${n.prompt}\n\nContext:\n${JSON.stringify(t)}\n\nRespond with JSON: { "ok": boolean, "reason"?: string }`,a=await e.complete(i),o=ch(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse AI response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by prompt hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};const uh=new Set([`Write`,`Edit`]),dh=new Set([`Shell`,`Bash`,`BackgroundProcess`]),fh=new Set([`Read`,`Glob`,`Grep`,`WebFetch`,`WebSearch`]);function ph(e){let t=e.toolName;return fh.has(t)?{toolName:t,reversible:!0,sideEffect:`none`,rollbackLayer:`none`,status:`read-only`,message:`${t} does not mutate the local workspace.`}:uh.has(t)?e.context.isolation===`worktree`||e.context.isolation===`provider-sandbox`?gh(t,`file-mutation`,e.context):e.context.checkpointAvailable?{toolName:t,reversible:!0,sideEffect:`file-mutation`,rollbackLayer:`edit-checkpoint`,status:`reversible`,message:`${t} is reversible through the active edit checkpoint.`}:{toolName:t,reversible:!1,sideEffect:`file-mutation`,rollbackLayer:`none`,status:`requires-checkpoint`,message:`${t} requires an edit checkpoint before file mutation.`}:dh.has(t)?gh(t,`shell-process`,e.context):t===`Agent`?_h(e.toolArgs,e.context):{toolName:t,reversible:!1,sideEffect:`unknown`,rollbackLayer:`none`,status:`unknown`,message:`${t} has no reversible execution contract.`}}function mh(e,t){let n={checkpointAvailable:t.checkpointAvailable,isolation:t.isolation??`none`},r=t.enforceUntrackedSideEffects??!0;return e.map(e=>new hh(e,{safetyContext:n,enforceUntrackedSideEffects:r}))}var hh=class{delegate;options;schema;constructor(e,t){this.delegate=e,this.options=t,this.schema=e.schema}setEventService(e){this.delegate.setEventService(e)}async execute(e,t){let n=ph({toolName:this.getName(),toolArgs:xh(e),context:this.options.safetyContext});return!n.reversible&&this.options.enforceUntrackedSideEffects?Sh(n):this.delegate.execute(e,t)}validate(e){return this.delegate.validate(e)}validateParameters(e){return this.delegate.validateParameters(e)}getDescription(){return this.delegate.getDescription()}getName(){return this.delegate.getName()}};function gh(e,t,n){return n.isolation===`worktree`?{toolName:e,reversible:!0,sideEffect:t,rollbackLayer:`worktree`,status:`reversible`,message:`${e} side effects are contained in an isolated Git worktree.`}:n.isolation===`provider-sandbox`?{toolName:e,reversible:!0,sideEffect:t,rollbackLayer:`provider-sandbox`,status:`reversible`,message:`${e} side effects are contained in a provider sandbox snapshot.`}:{toolName:e,reversible:!1,sideEffect:t,rollbackLayer:`none`,status:`requires-isolation`,message:`${e} can create host shell side effects that edit checkpoints cannot restore; use worktree or provider sandbox isolation.`}}function _h(e,t){return t.isolation===`worktree`||t.isolation===`provider-sandbox`?gh(`Agent`,`subagent`,t):vh(e)?{toolName:`Agent`,reversible:!0,sideEffect:`subagent`,rollbackLayer:`worktree`,status:`reversible`,message:`Agent jobs request worktree isolation, so shell side effects stay outside the parent workspace.`}:{toolName:`Agent`,reversible:!1,sideEffect:`subagent`,rollbackLayer:`none`,status:`requires-isolation`,message:`Agent jobs must request worktree isolation to be reversible in local-first mode.`}}function vh(e){if(!e)return!1;let t=e.jobs;return Array.isArray(t)?t.length>0&&t.every(e=>bh(e)?yh(e)===`worktree`:!1):yh(e)===`worktree`}function yh(e){let t=e.isolation;return typeof t==`string`?t:void 0}function bh(e){return e!==void 0&&typeof e==`object`&&!Array.isArray(e)}function xh(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function Sh(e){return{success:!0,data:{success:!1,output:``,error:e.message,reversibleSafety:{toolName:e.toolName,sideEffect:e.sideEffect,rollbackLayer:e.rollbackLayer,status:e.status}},metadata:{reversibleSafetyStatus:e.status,rollbackLayer:e.rollbackLayer}}}function Ch(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function wh(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Th(e,t){return e.some(e=>wh(e.name)===t)}function Eh(e){if(!e.provider)throw Error(`provider is required. SDK is provider-neutral — consumer must create and pass a provider instance.`);let t=e.provider,n=e.cwd??process.cwd(),r=e.sessionId??Dh(),i=new Hm(n),a=Ch(e.commandDescriptors),o=a.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,s=o?rf(a):void 0,c=Th(a,`skills`)?i.getModelInvocableSkills():[],l=Wp({sandboxClient:e.sandboxClient,cwd:n}),u=e.editCheckpointRecorder!==void 0&&e.sandboxClient===void 0,d=[...u&&e.editCheckpointRecorder?jm(l,e.editCheckpointRecorder):l,...e.additionalTools??[],...e.includeGoalTool?[Zm()]:[]],f=e.reversibleExecution?{...e.reversibleExecution,isolation:e.reversibleExecution.isolation??(e.sandboxClient?`provider-sandbox`:void 0)}:void 0,p=f?mh(d,{...f,checkpointAvailable:u}):d;o&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&p.push(...sf({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:a}));let m=[];e.providerFactory&&m.push(new lh({providerFactory:e.providerFactory,defaultModel:e.config.provider.model})),e.sessionFactory&&m.push(new sh({sessionFactory:e.sessionFactory})),e.additionalHookExecutors&&m.push(...e.additionalHookExecutors);let{agentToolDeps:g,agentDefinitions:_,backgroundTaskManager:v}=wm(e,r,n,t,p,m),{backgroundProcessToolDeps:y}=Tm(e,v,r,n,p),{finalSystemMessage:b,rebuildSystemMessage:x}=Dm(e,n,a,s,y,c,_),S=[`Read(.agents/**)`,`Read(.claude/**)`,`Read(.robota/**)`,`Glob(.agents/**)`,`Glob(.claude/**)`,`Glob(.robota/**)`],C=s?s.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],w=(e.allowedTools??[]).map(e=>`${e}(*)`),ee=(e.deniedTools??[]).map(e=>`${e}(*)`),T={allow:[...S,...C,...e.config.permissions.allow??[],...w],deny:[...e.config.permissions.deny??[],...ee]},E=h(n,`.robota`,`settings.local.json`);function D(e){let t=`${e}(*)`,n=Km(E),r=Array.isArray(n.permissions)?[]:n.permissions?.allow??[];r.includes(t)||qm(E,{...n,permissions:{...n.permissions??{},allow:[...r,t]}})}let te=new Ml({tools:p,provider:t,systemMessage:b,terminal:e.terminal,permissions:T,hooks:e.config.hooks,permissionMode:e.permissionMode,defaultTrustLevel:e.config.defaultTrustLevel,model:e.model??e.config.provider.model,providerTimeout:e.config.provider.timeout??12e4,maxTurns:e.maxTurns,sessionStore:e.sessionStore,sessionId:r,permissionHandler:e.permissionHandler,...e.ask?{ask:e.ask}:{},onProjectAllowTool:D,onTextDelta:e.onTextDelta,onContextUpdate:e.onContextUpdate,onToolExecution:e.onToolExecution,promptForApproval:e.promptForApproval,onCompact:e.onCompact,onCompactEvent:e.onCompactEvent,compactInstructions:e.compactInstructions??e.context.compactInstructions,autoCompactThreshold:e.autoCompactThreshold??e.config.autoCompactThreshold,sessionLogger:e.sessionLogger,hookTypeExecutors:m.length>0?m:void 0,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.effort===void 0?{}:{effort:e.effort}});return Om(te,g,y,v),{session:te,rebuildSystemMessage:x}}function Dh(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}const Oh=A.lazy(()=>A.union([A.string(),A.number(),A.boolean(),A.null(),A.undefined(),A.date(),A.array(Oh),A.record(Oh)])),kh=A.object({name:A.string().optional(),model:A.string().optional(),apiKey:A.string().optional(),baseURL:A.string().optional(),timeout:A.number().optional(),options:A.record(Oh).optional()}),Ah=A.object({type:A.string().optional(),model:A.string().optional(),apiKey:A.string().optional(),baseURL:A.string().optional(),timeout:A.number().optional(),options:A.record(Oh).optional()}),jh=A.object({allow:A.array(A.string()).optional(),deny:A.array(A.string()).optional()}),Mh=A.record(A.string()).optional(),Nh=A.object({type:A.literal(`command`),command:A.string(),timeout:A.number().optional()}),Ph=A.object({type:A.literal(`http`),url:A.string(),headers:A.record(A.string()).optional(),timeout:A.number().optional()}),Fh=A.object({type:A.literal(`prompt`),prompt:A.string(),model:A.string().optional()}),Ih=A.object({type:A.literal(`agent`),agent:A.string(),maxTurns:A.number().optional(),timeout:A.number().optional()}),Lh=A.discriminatedUnion(`type`,[Nh,Ph,Fh,Ih]),Rh=A.object({matcher:A.string(),hooks:A.array(Lh)}),zh=A.object({PreToolUse:A.array(Rh).optional(),PostToolUse:A.array(Rh).optional(),SessionStart:A.array(Rh).optional(),SessionEnd:A.array(Rh).optional(),Stop:A.array(Rh).optional(),StopFailure:A.array(Rh).optional(),PreCompact:A.array(Rh).optional(),PostCompact:A.array(Rh).optional(),UserPromptSubmit:A.array(Rh).optional(),SubagentStart:A.array(Rh).optional(),SubagentStop:A.array(Rh).optional(),WorktreeCreate:A.array(Rh).optional(),WorktreeRemove:A.array(Rh).optional()}).optional(),Bh=A.record(A.boolean()).optional(),Vh=A.object({source:A.object({type:A.enum([`github`,`git`,`local`,`url`]),repo:A.string().optional(),url:A.string().optional(),path:A.string().optional(),ref:A.string().optional()})}),Hh=A.record(Vh).optional().catch(void 0),Uh=A.union([A.number().gt(0).lte(1),A.literal(!1)]).optional(),Wh=A.object({enabled:A.boolean().optional(),options:A.record(Oh).optional()}),Gh=A.object({defaultTrustLevel:A.enum([`safe`,`moderate`,`full`]).optional(),language:A.string().optional(),preset:A.string().optional(),currentProvider:A.string().optional(),providers:A.record(Ah).optional(),provider:kh.optional(),permissions:jh.optional(),env:Mh,hooks:zh,enabledPlugins:Bh,extraKnownMarketplaces:Hh,autoCompactThreshold:Uh,transports:A.record(Wh).optional()});function Kh(){return process.env.HOME??process.env.USERPROFILE??`/`}const qh={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[]},env:{}};function Jh(e){if(!M(e))return;let t=Se(e,`utf-8`).trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function Yh(e){if(e.startsWith(`$ENV:`)){let t=e.slice(5);return process.env[t]??e}return e}function Xh(e){let t=e.provider?.apiKey===void 0?e.provider:Zh(e.provider);if(e.providers!==void 0){let n=Object.fromEntries(Object.entries(e.providers).map(([e,t])=>[e,Zh(t)]));return{...e,provider:t,providers:n}}return{...e,provider:t}}function Zh(e){return{...e,...e.apiKey!==void 0&&{apiKey:Yh(e.apiKey)}}}function Qh(e){return e.reduce((e,t)=>({...e,...t,provider:e.provider!==void 0||t.provider!==void 0?{...e.provider,...t.provider}:void 0,permissions:e.permissions!==void 0||t.permissions!==void 0?{allow:t.permissions?.allow??e.permissions?.allow,deny:t.permissions?.deny??e.permissions?.deny}:void 0,env:{...e.env??{},...t.env??{}},providers:e.providers!==void 0||t.providers!==void 0?$h(e.providers,t.providers):void 0,enabledPlugins:e.enabledPlugins!==void 0||t.enabledPlugins!==void 0?{...e.enabledPlugins??{},...t.enabledPlugins??{}}:void 0,extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold}),{})}function $h(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function eg(e){if(e.currentProvider!==void 0)return tg(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...qh.provider}}function tg(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??qh.provider.model,apiKey:n.apiKey??qh.provider.apiKey,...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function ng(e){return{defaultTrustLevel:e.defaultTrustLevel??qh.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:eg(e),permissions:{allow:e.permissions?.allow??qh.permissions.allow,deny:e.permissions?.deny??qh.permissions.deny},env:e.env??qh.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold}}function rg(e){let t=Kh();return[N(t,`.robota`,`settings.json`),N(t,`.claude`,`settings.json`),N(e,`.robota`,`settings.json`),N(e,`.robota`,`settings.local.json`),N(e,`.claude`,`settings.json`),N(e,`.claude`,`settings.local.json`)]}async function ig(e){let t=rg(e),n=[];for(let e of t){let t=Jh(e);t!==void 0&&n.push({raw:t,path:e})}return ng(Qh(n.map(({raw:e,path:t})=>{let n=Gh.safeParse(e);if(!n.success)throw Error(`Invalid settings in ${t}: ${n.error.message}`);return Xh(n.data)})))}const ag=h(`.agents`,`tasks`),og={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function sg(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function cg(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||f(t,`.md`)}function lg(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function ug(e,t){let n=e.split(/\r?\n/),r=RegExp(`^(#{2,6})\\s+${t}\\b`,`i`),i=n.findIndex(e=>r.test(e));if(i<0)return;let a=[];for(let e of n.slice(i+1)){if(/^##\s+/.test(e))break;a.push(e)}let o=a.join(`
134
+ `)}const th={now:()=>new Date().toISOString(),createId:()=>`goal_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`};function nh(e){let t;try{t=JSON.parse(e)}catch{return null}return{status:t.status===`satisfied`?`satisfied`:`continue`,reason:typeof t.reason==`string`?t.reason:``}}function rh(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!(!n||n.name!==`report_goal_status`))return nh(n.args)}return null}function ih(e){return e.filter(e=>e.name!==Ym).length}var ah=class{deps;goal=null;consecutiveIdleTurns=0;noProgressLimit=2;constructor(e=th){this.deps=e}getState(){return this.goal}isActive(){return this.goal?.status===`active`}start(e,t={}){let n=e.trim();if(n.length===0)throw Error(`A goal objective must be a non-empty string.`);let r=t.maxIterations&&t.maxIterations>0?Math.floor(t.maxIterations):25;return this.noProgressLimit=t.noProgressLimit&&t.noProgressLimit>0?Math.floor(t.noProgressLimit):2,this.consecutiveIdleTurns=0,this.goal={id:this.deps.createId(),objective:n,status:`active`,iterations:0,maxIterations:r,startedAt:this.deps.now(),progress:[]},{goal:this.goal,prompt:$m(n)}}restore(e,t=2){this.goal=e.status===`active`?e:null,this.noProgressLimit=t,this.consecutiveIdleTurns=0}cancel(){return!this.goal||this.goal.status!==`active`?null:(this.goal={...this.goal,status:`stopped`,stopReason:`cancelled`},this.goal)}onTurnComplete(e){if(!this.goal||this.goal.status!==`active`)return null;let t=rh(e.toolSummaries),n=this.goal.iterations+1;if(this.goal={...this.goal,iterations:n,progress:[...this.goal.progress,{iteration:n,signal:t?.status??`continue`,reason:t?.reason??``}]},t?.status===`satisfied`)return this.stop(`satisfied`);let r=ih(e.toolSummaries)>0;return this.consecutiveIdleTurns=r?0:this.consecutiveIdleTurns+1,this.consecutiveIdleTurns>=this.noProgressLimit?this.stop(`no-progress`):n>=this.goal.maxIterations?this.stop(`max-iterations`):{action:`continue`,prompt:eh(this.goal),goal:this.goal}}stop(e){let t=e===`satisfied`?`satisfied`:`stopped`;return this.goal={...this.goal,status:t,stopReason:e},{action:`stop`,reason:e,goal:this.goal}}};function oh(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var sh=class{type=`agent`;sessionFactory;constructor(e){this.sessionFactory=e.sessionFactory}async execute(e,t){let n=e,r=n.maxTurns??50,i=n.timeout??60;try{let e=this.sessionFactory({maxTurns:r,timeout:i}),n=`Hook input:\n${JSON.stringify(t)}\n\nRespond with JSON: { "ok": boolean, "reason"?: string }`,a=await e.run(n),o=oh(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse agent response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by agent hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};function ch(e){let t=/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(e);return t?t[1].trim():e.trim()}var lh=class{type=`prompt`;providerFactory;defaultModel;constructor(e){this.providerFactory=e.providerFactory,this.defaultModel=e.defaultModel}async execute(e,t){let n=e,r=n.model??this.defaultModel;try{let e=this.providerFactory(r),i=`${n.prompt}\n\nContext:\n${JSON.stringify(t)}\n\nRespond with JSON: { "ok": boolean, "reason"?: string }`,a=await e.complete(i),o=ch(a),s;try{s=JSON.parse(o)}catch{return{exitCode:1,stdout:``,stderr:`Failed to parse AI response as JSON: ${a}`}}return s.ok?{exitCode:0,stdout:JSON.stringify(s),stderr:``}:{exitCode:2,stdout:``,stderr:s.reason??`Blocked by prompt hook`}}catch(e){return{exitCode:1,stdout:``,stderr:e instanceof Error?e.message:String(e)}}}};const uh=new Set([`Write`,`Edit`]),dh=new Set([`Shell`,`Bash`,`BackgroundProcess`]),fh=new Set([`Read`,`Glob`,`Grep`,`WebFetch`,`WebSearch`]);function ph(e){let t=e.toolName;return fh.has(t)?{toolName:t,reversible:!0,sideEffect:`none`,rollbackLayer:`none`,status:`read-only`,message:`${t} does not mutate the local workspace.`}:uh.has(t)?e.context.isolation===`worktree`||e.context.isolation===`provider-sandbox`?gh(t,`file-mutation`,e.context):e.context.checkpointAvailable?{toolName:t,reversible:!0,sideEffect:`file-mutation`,rollbackLayer:`edit-checkpoint`,status:`reversible`,message:`${t} is reversible through the active edit checkpoint.`}:{toolName:t,reversible:!1,sideEffect:`file-mutation`,rollbackLayer:`none`,status:`requires-checkpoint`,message:`${t} requires an edit checkpoint before file mutation.`}:dh.has(t)?gh(t,`shell-process`,e.context):t===`Agent`?_h(e.toolArgs,e.context):{toolName:t,reversible:!1,sideEffect:`unknown`,rollbackLayer:`none`,status:`unknown`,message:`${t} has no reversible execution contract.`}}function mh(e,t){let n={checkpointAvailable:t.checkpointAvailable,isolation:t.isolation??`none`},r=t.enforceUntrackedSideEffects??!0;return e.map(e=>new hh(e,{safetyContext:n,enforceUntrackedSideEffects:r}))}var hh=class{delegate;options;schema;constructor(e,t){this.delegate=e,this.options=t,this.schema=e.schema}setEventService(e){this.delegate.setEventService(e)}async execute(e,t){let n=ph({toolName:this.getName(),toolArgs:xh(e),context:this.options.safetyContext});return!n.reversible&&this.options.enforceUntrackedSideEffects?Sh(n):this.delegate.execute(e,t)}validate(e){return this.delegate.validate(e)}validateParameters(e){return this.delegate.validateParameters(e)}getDescription(){return this.delegate.getDescription()}getName(){return this.delegate.getName()}};function gh(e,t,n){return n.isolation===`worktree`?{toolName:e,reversible:!0,sideEffect:t,rollbackLayer:`worktree`,status:`reversible`,message:`${e} side effects are contained in an isolated Git worktree.`}:n.isolation===`provider-sandbox`?{toolName:e,reversible:!0,sideEffect:t,rollbackLayer:`provider-sandbox`,status:`reversible`,message:`${e} side effects are contained in a provider sandbox snapshot.`}:{toolName:e,reversible:!1,sideEffect:t,rollbackLayer:`none`,status:`requires-isolation`,message:`${e} can create host shell side effects that edit checkpoints cannot restore; use worktree or provider sandbox isolation.`}}function _h(e,t){return t.isolation===`worktree`||t.isolation===`provider-sandbox`?gh(`Agent`,`subagent`,t):vh(e)?{toolName:`Agent`,reversible:!0,sideEffect:`subagent`,rollbackLayer:`worktree`,status:`reversible`,message:`Agent jobs request worktree isolation, so shell side effects stay outside the parent workspace.`}:{toolName:`Agent`,reversible:!1,sideEffect:`subagent`,rollbackLayer:`none`,status:`requires-isolation`,message:`Agent jobs must request worktree isolation to be reversible in local-first mode.`}}function vh(e){if(!e)return!1;let t=e.jobs;return Array.isArray(t)?t.length>0&&t.every(e=>bh(e)?yh(e)===`worktree`:!1):yh(e)===`worktree`}function yh(e){let t=e.isolation;return typeof t==`string`?t:void 0}function bh(e){return e!==void 0&&typeof e==`object`&&!Array.isArray(e)}function xh(e){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e}function Sh(e){return{success:!0,data:{success:!1,output:``,error:e.message,reversibleSafety:{toolName:e.toolName,sideEffect:e.sideEffect,rollbackLayer:e.rollbackLayer,status:e.status}},metadata:{reversibleSafetyStatus:e.status,rollbackLayer:e.rollbackLayer}}}function Ch(e){return(e??[]).filter(e=>e.modelInvocable&&e.kind===`builtin-command`)}function wh(e){return e.trim().replace(/^\/+/,``).split(/\s+/)[0]??``}function Th(e,t){return e.some(e=>wh(e.name)===t)}function Eh(e){if(!e.provider)throw Error(`provider is required. SDK is provider-neutral — consumer must create and pass a provider instance.`);let t=e.provider,n=e.cwd??process.cwd(),r=e.sessionId??Dh(),i=new Hm(n),a=Ch(e.commandDescriptors),o=a.length>0&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0,s=o?rf(a):void 0,c=Th(a,`skills`)?i.getModelInvocableSkills():[],l=Wp({sandboxClient:e.sandboxClient,cwd:n}),u=e.editCheckpointRecorder!==void 0&&e.sandboxClient===void 0,d=[...u&&e.editCheckpointRecorder?jm(l,e.editCheckpointRecorder):l,...e.additionalTools??[],...e.includeGoalTool?[Zm()]:[]],f=e.reversibleExecution?{...e.reversibleExecution,isolation:e.reversibleExecution.isolation??(e.sandboxClient?`provider-sandbox`:void 0)}:void 0,p=f?mh(d,{...f,checkpointAvailable:u}):d;o&&e.modelCommandExecutor!==void 0&&e.isModelCommandInvocable!==void 0&&p.push(...sf({execute:e.modelCommandExecutor,isModelInvocable:e.isModelCommandInvocable,commandDescriptors:a}));let m=[];e.providerFactory&&m.push(new lh({providerFactory:e.providerFactory,defaultModel:e.config.provider.model})),e.sessionFactory&&m.push(new sh({sessionFactory:e.sessionFactory})),e.additionalHookExecutors&&m.push(...e.additionalHookExecutors);let{agentToolDeps:g,agentDefinitions:_,backgroundTaskManager:v}=wm(e,r,n,t,p,m),{backgroundProcessToolDeps:y}=Tm(e,v,r,n,p),{finalSystemMessage:b,rebuildSystemMessage:x}=Dm(e,n,a,s,y,c,_),S=[`Read(.agents/**)`,`Read(.claude/**)`,`Read(.robota/**)`,`Glob(.agents/**)`,`Glob(.claude/**)`,`Glob(.robota/**)`],C=s?s.commandTools.filter(e=>!e.requiresPermission).map(e=>e.toolName):[],w=(e.allowedTools??[]).map(e=>`${e}(*)`),T=(e.deniedTools??[]).map(e=>`${e}(*)`),E={allow:[...S,...C,...e.config.permissions.allow??[],...w],deny:[...e.config.permissions.deny??[],...T]},D=h(n,`.robota`,`settings.local.json`);function O(e){let t=`${e}(*)`,n=Km(D),r=Array.isArray(n.permissions)?[]:n.permissions?.allow??[];r.includes(t)||qm(D,{...n,permissions:{...n.permissions??{},allow:[...r,t]}})}let k=new Ml({tools:p,provider:t,systemMessage:b,terminal:e.terminal,permissions:E,hooks:e.config.hooks,permissionMode:e.permissionMode,defaultTrustLevel:e.config.defaultTrustLevel,model:e.model??e.config.provider.model,providerTimeout:e.config.provider.timeout??12e4,maxTurns:e.maxTurns,sessionStore:e.sessionStore,sessionId:r,permissionHandler:e.permissionHandler,...e.ask?{ask:e.ask}:{},onProjectAllowTool:O,onTextDelta:e.onTextDelta,onContextUpdate:e.onContextUpdate,onToolExecution:e.onToolExecution,promptForApproval:e.promptForApproval,onCompact:e.onCompact,onCompactEvent:e.onCompactEvent,compactInstructions:e.compactInstructions??e.context.compactInstructions,autoCompactThreshold:e.autoCompactThreshold??e.config.autoCompactThreshold,sessionLogger:e.sessionLogger,hookTypeExecutors:m.length>0?m:void 0,agentName:e.agentName,...e.activePresetId===void 0?{}:{activePresetId:e.activePresetId},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.effort===void 0?{}:{effort:e.effort}});return Om(k,g,y,v),{session:k,rebuildSystemMessage:x}}function Dh(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}const Oh=j.lazy(()=>j.union([j.string(),j.number(),j.boolean(),j.null(),j.undefined(),j.date(),j.array(Oh),j.record(Oh)])),kh=j.object({name:j.string().optional(),model:j.string().optional(),apiKey:j.string().optional(),baseURL:j.string().optional(),timeout:j.number().optional(),options:j.record(Oh).optional()}),Ah=j.object({type:j.string().optional(),model:j.string().optional(),apiKey:j.string().optional(),baseURL:j.string().optional(),timeout:j.number().optional(),options:j.record(Oh).optional()}),jh=j.object({allow:j.array(j.string()).optional(),deny:j.array(j.string()).optional()}),Mh=j.record(j.string()).optional(),Nh=j.object({type:j.literal(`command`),command:j.string(),timeout:j.number().optional()}),Ph=j.object({type:j.literal(`http`),url:j.string(),headers:j.record(j.string()).optional(),timeout:j.number().optional()}),Fh=j.object({type:j.literal(`prompt`),prompt:j.string(),model:j.string().optional()}),Ih=j.object({type:j.literal(`agent`),agent:j.string(),maxTurns:j.number().optional(),timeout:j.number().optional()}),Lh=j.discriminatedUnion(`type`,[Nh,Ph,Fh,Ih]),Rh=j.object({matcher:j.string(),hooks:j.array(Lh)}),zh=j.object({PreToolUse:j.array(Rh).optional(),PostToolUse:j.array(Rh).optional(),SessionStart:j.array(Rh).optional(),SessionEnd:j.array(Rh).optional(),Stop:j.array(Rh).optional(),StopFailure:j.array(Rh).optional(),PreCompact:j.array(Rh).optional(),PostCompact:j.array(Rh).optional(),UserPromptSubmit:j.array(Rh).optional(),SubagentStart:j.array(Rh).optional(),SubagentStop:j.array(Rh).optional(),WorktreeCreate:j.array(Rh).optional(),WorktreeRemove:j.array(Rh).optional()}).optional(),Bh=j.record(j.boolean()).optional(),Vh=j.object({source:j.object({type:j.enum([`github`,`git`,`local`,`url`]),repo:j.string().optional(),url:j.string().optional(),path:j.string().optional(),ref:j.string().optional()})}),Hh=j.record(Vh).optional().catch(void 0),Uh=j.union([j.number().gt(0).lte(1),j.literal(!1)]).optional(),Wh=j.object({enabled:j.boolean().optional(),options:j.record(Oh).optional()}),Gh=j.object({defaultTrustLevel:j.enum([`safe`,`moderate`,`full`]).optional(),language:j.string().optional(),preset:j.string().optional(),currentProvider:j.string().optional(),providers:j.record(Ah).optional(),provider:kh.optional(),permissions:jh.optional(),env:Mh,hooks:zh,enabledPlugins:Bh,extraKnownMarketplaces:Hh,autoCompactThreshold:Uh,transports:j.record(Wh).optional()});function Kh(){return process.env.HOME??process.env.USERPROFILE??`/`}const qh={defaultTrustLevel:`moderate`,provider:{name:`anthropic`,model:`claude-opus-4-5`,apiKey:void 0},permissions:{allow:[],deny:[]},env:{}};function Jh(e){if(!N(e))return;let t=xe(e,`utf-8`).trim();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function Yh(e){if(e.startsWith(`$ENV:`)){let t=e.slice(5);return process.env[t]??e}return e}function Xh(e){let t=e.provider?.apiKey===void 0?e.provider:Zh(e.provider);if(e.providers!==void 0){let n=Object.fromEntries(Object.entries(e.providers).map(([e,t])=>[e,Zh(t)]));return{...e,provider:t,providers:n}}return{...e,provider:t}}function Zh(e){return{...e,...e.apiKey!==void 0&&{apiKey:Yh(e.apiKey)}}}function Qh(e){return e.reduce((e,t)=>({...e,...t,provider:e.provider!==void 0||t.provider!==void 0?{...e.provider,...t.provider}:void 0,permissions:e.permissions!==void 0||t.permissions!==void 0?{allow:t.permissions?.allow??e.permissions?.allow,deny:t.permissions?.deny??e.permissions?.deny}:void 0,env:{...e.env??{},...t.env??{}},providers:e.providers!==void 0||t.providers!==void 0?$h(e.providers,t.providers):void 0,enabledPlugins:e.enabledPlugins!==void 0||t.enabledPlugins!==void 0?{...e.enabledPlugins??{},...t.enabledPlugins??{}}:void 0,extraKnownMarketplaces:t.extraKnownMarketplaces??e.extraKnownMarketplaces,autoCompactThreshold:t.autoCompactThreshold??e.autoCompactThreshold}),{})}function $h(e,t){let n={...e??{}};for(let[e,r]of Object.entries(t??{}))n[e]={...n[e],...r};return n}function eg(e){if(e.currentProvider!==void 0)return tg(e);if(e.provider!==void 0)throw Error(`Legacy flat "provider" settings are not supported. Migrate to "currentProvider" + "providers" format.`);return{...qh.provider}}function tg(e){let t=e.currentProvider;if(t===void 0)throw Error(`currentProvider is required`);let n=e.providers?.[t];if(n===void 0)throw Error(`currentProvider "${t}" was not found in providers`);if(n.type===void 0)throw Error(`Provider profile "${t}" is missing type`);return{name:n.type,model:n.model??qh.provider.model,apiKey:n.apiKey??qh.provider.apiKey,...n.baseURL!==void 0&&{baseURL:n.baseURL},...n.timeout!==void 0&&{timeout:n.timeout},...n.options!==void 0&&{options:n.options}}}function ng(e){return{defaultTrustLevel:e.defaultTrustLevel??qh.defaultTrustLevel,language:e.language,currentProvider:e.currentProvider,provider:eg(e),permissions:{allow:e.permissions?.allow??qh.permissions.allow,deny:e.permissions?.deny??qh.permissions.deny},env:e.env??qh.env,hooks:e.hooks??void 0,enabledPlugins:e.enabledPlugins??void 0,extraKnownMarketplaces:e.extraKnownMarketplaces??void 0,autoCompactThreshold:e.autoCompactThreshold}}function rg(e){let t=Kh();return[P(t,`.robota`,`settings.json`),P(t,`.claude`,`settings.json`),P(e,`.robota`,`settings.json`),P(e,`.robota`,`settings.local.json`),P(e,`.claude`,`settings.json`),P(e,`.claude`,`settings.local.json`)]}async function ig(e){let t=rg(e),n=[];for(let e of t){let t=Jh(e);t!==void 0&&n.push({raw:t,path:e})}return ng(Qh(n.map(({raw:e,path:t})=>{let n=Gh.safeParse(e);if(!n.success)throw Error(`Invalid settings in ${t}: ${n.error.message}`);return Xh(n.data)})))}const ag=h(`.agents`,`tasks`),og={"in-progress":1,todo:2,blocked:3,unknown:4,completed:5};function sg(e){let t=e?.trim().toLowerCase();return t===`todo`||t===`in-progress`||t===`blocked`||t===`completed`?t:`unknown`}function cg(e,t){return e.split(/\r?\n/).find(e=>/^#\s+/.test(e))?.replace(/^#\s+/,``).trim()||f(t,`.md`)}function lg(e,t){return RegExp(`^- \\*\\*${t}\\*\\*:\\s*(.+)$`,`im`).exec(e)?.[1]?.trim()}function ug(e,t){let n=e.split(/\r?\n/),r=RegExp(`^(#{2,6})\\s+${t}\\b`,`i`),i=n.findIndex(e=>r.test(e));if(i<0)return;let a=[];for(let e of n.slice(i+1)){if(/^##\s+/.test(e))break;a.push(e)}let o=a.join(`
135
135
  `).trim();return o.length>0?o:void 0}function dg(e){return e.split(/\r?\n/).map(e=>/^- \[ \]\s+(.+)$/.exec(e)?.[1]?.trim()).filter(e=>e!==void 0&&e.length>0)}function fg(e,t){return t&&e.branch===t?0:og[e.status]}function pg(e){let t=[`### ${e.title}`,`- **Path:** \`${e.relativePath}\``];return t.push(`- **Status:** ${e.status}`),e.branch&&t.push(`- **Branch:** ${e.branch}`),e.scope&&t.push(`- **Scope:** ${e.scope}`),e.objective&&t.push(`- **Objective:** ${e.objective}`),e.openItems.length>0&&(t.push(`- **Open items:**`),t.push(...e.openItems.map(e=>` - ${e}`))),t.join(`
136
136
  `)}function mg(e,t){let n=v(e),r=!1;for(;!r;){let e=h(n,`.git`);if(t.existsSync(e)){if(t.statSync(e).isDirectory())return e;let r=t.readFileSync(e,`utf8`).trim().match(/^gitdir:\s*(.+)$/)?.[1];if(r)return m(r)?r:v(n,r)}let i=p(n);r=i===n,n=i}}function hg(e,t=new Y){let n=mg(e,t);if(!n)return;let r=h(n,`HEAD`);if(t.existsSync(r))return(t.readFileSync(r,`utf8`).trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1])?.trim()}function gg(e,t=new Y){let n=h(e,ag);return t.existsSync(n)?t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isFile()).map(e=>e.name).filter(e=>e!==`README.md`&&e.endsWith(`.md`)).sort((e,t)=>e.localeCompare(t)).map(e=>h(n,e)):[]}function _g(e,t,n=new Y){let r=n.readFileSync(e,`utf8`);return{path:e,relativePath:_(t,e),title:cg(r,e),status:sg(lg(r,`Status`)),branch:lg(r,`Branch`),scope:lg(r,`Scope`),objective:ug(r,`Objective`),openItems:dg(r)}}function vg(e,t={}){let n=t.maxTasks??3;return[...e].filter(e=>e.status!==`completed`).sort((e,n)=>fg(e,t.currentBranch)-fg(n,t.currentBranch)||e.relativePath.localeCompare(n.relativePath)).slice(0,n)}function yg(e){return e.map(pg).join(`
137
137
 
138
- `)}function bg(e,t={},n=new Y){let r=t.currentBranch??hg(e,n);return yg(vg(gg(e,n).map(t=>_g(t,e,n)),{...t,currentBranch:r}))}const xg=25600,Sg=[`user`,`feedback`,`project`,`reference`];function Cg(e){return Sg.includes(e)}function wg(e){return N(e,`.robota`,`memory`)}function Tg(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function Eg(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
139
- `).trimEnd(),truncated:n.length>t}}function Dg(e){return e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`general`}function Og(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function kg(e){return e.trim().replace(/\s+/g,` `)}var Ag=class{cwd;now;constructor(e,t=()=>new Date){this.cwd=e,this.now=t}getIndexPath(){return N(wg(this.cwd),`MEMORY.md`)}getTopicsPath(){return N(wg(this.cwd),`topics`)}loadStartupMemory(){let e=this.getIndexPath();if(!M(e))return{content:``,path:e,lineCount:0,truncated:!1};let t=Se(e,`utf8`),n=Tg(t,xg),r=Buffer.byteLength(t,`utf8`)>xg,i=Eg(n,200);return{content:i.content,path:e,lineCount:i.content.length===0?0:i.content.split(/\r?\n/).length,truncated:r||i.truncated}}list(){let e=this.getTopicsPath(),t=M(e)?Ce(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(t=>({name:De(t.name,`.md`),path:N(e,t.name)})).sort((e,t)=>e.name.localeCompare(t.name)):[];return{indexPath:this.getIndexPath(),topicsPath:e,topics:t}}readTopic(e){let t=Dg(e),n=N(this.getTopicsPath(),`${t}.md`);return M(n)?Se(n,`utf8`).trimEnd():``}append(e){let t=Dg(e.topic),n=wg(this.cwd),r=this.getTopicsPath();xe(r,{recursive:!0});let i=this.getIndexPath(),a=N(r,`${t}.md`),o=Og(this.now(),e,t),s=M(a)?``:`# ${t}\n\n`,c=kg(e.text);return M(a)&&Se(a,`utf8`).includes(`) ${c}`)?{indexPath:i,topicPath:a,topic:t,deduplicated:!0}:(M(i)||(xe(n,{recursive:!0}),Ee(i,`# Project Memory
138
+ `)}function bg(e,t={},n=new Y){let r=t.currentBranch??hg(e,n);return yg(vg(gg(e,n).map(t=>_g(t,e,n)),{...t,currentBranch:r}))}const xg=25600,Sg=[`user`,`feedback`,`project`,`reference`];function Cg(e){return Sg.includes(e)}function wg(e){return P(e,`.robota`,`memory`)}function Tg(e,t){let n=Buffer.from(e,`utf8`);return n.byteLength<=t?e:n.subarray(0,t).toString(`utf8`)}function Eg(e,t){let n=e.split(/\r?\n/);return{content:n.slice(0,t).join(`
139
+ `).trimEnd(),truncated:n.length>t}}function Dg(e){return e.trim().toLowerCase().replace(/[^a-z0-9가-힣_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`general`}function Og(e,t,n){let r=e.toISOString().slice(0,10),i=t.text.trim().replace(/\s+/g,` `);return`[${r}] (${t.type}/${n}) ${i}`}function kg(e){return e.trim().replace(/\s+/g,` `)}var Ag=class{cwd;now;constructor(e,t=()=>new Date){this.cwd=e,this.now=t}getIndexPath(){return P(wg(this.cwd),`MEMORY.md`)}getTopicsPath(){return P(wg(this.cwd),`topics`)}loadStartupMemory(){let e=this.getIndexPath();if(!N(e))return{content:``,path:e,lineCount:0,truncated:!1};let t=xe(e,`utf8`),n=Tg(t,xg),r=Buffer.byteLength(t,`utf8`)>xg,i=Eg(n,200);return{content:i.content,path:e,lineCount:i.content.length===0?0:i.content.split(/\r?\n/).length,truncated:r||i.truncated}}list(){let e=this.getTopicsPath(),t=N(e)?Se(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(t=>({name:Ee(t.name,`.md`),path:P(e,t.name)})).sort((e,t)=>e.name.localeCompare(t.name)):[];return{indexPath:this.getIndexPath(),topicsPath:e,topics:t}}readTopic(e){let t=Dg(e),n=P(this.getTopicsPath(),`${t}.md`);return N(n)?xe(n,`utf8`).trimEnd():``}append(e){let t=Dg(e.topic),n=wg(this.cwd),r=this.getTopicsPath();be(r,{recursive:!0});let i=this.getIndexPath(),a=P(r,`${t}.md`),o=Og(this.now(),e,t),s=N(a)?``:`# ${t}\n\n`,c=kg(e.text);return N(a)&&xe(a,`utf8`).includes(`) ${c}`)?{indexPath:i,topicPath:a,topic:t,deduplicated:!0}:(N(i)||(be(n,{recursive:!0}),Te(i,`# Project Memory
140
140
 
141
- `,`utf8`)),j(i,`- ${o}\n`,`utf8`),j(a,`${s}- ${o}\n`,`utf8`),{indexPath:i,topicPath:a,topic:t,deduplicated:!1})}};function jg(e,t){let n=[],r=ke(e),i=!1;for(;!i;){let e=N(r,t);M(e)&&n.push(e);let a=Oe(r);i=a===r,i||(r=a)}return n.reverse()}function Mg(e){let t=e.split(`
141
+ `,`utf8`)),M(i,`- ${o}\n`,`utf8`),M(a,`${s}- ${o}\n`,`utf8`),{indexPath:i,topicPath:a,topic:t,deduplicated:!1})}};function jg(e,t){let n=[],r=Oe(e),i=!1;for(;!i;){let e=P(r,t);N(e)&&n.push(e);let a=De(r);i=a===r,i||(r=a)}return n.reverse()}function Mg(e){let t=e.split(`
142
142
  `),n=!1,r=0,i=[];for(let e of t){let t=/^(#{1,6})\s+/.exec(e);if(t){if(n&&t[1].length<=r)break;if(/compact\s+instructions/i.test(e)){n=!0,r=t[1].length;continue}}n&&i.push(e)}return i.join(`
143
143
  `).trim()||void 0}async function Ng(e){let t=jg(e,`AGENTS.md`),n=jg(e,`CLAUDE.md`),r=t.map(e=>Hf(e)),i=n.map(e=>Hf(e)),a=r.map(e=>e.content).join(`
144
144
 
@@ -158,7 +158,7 @@ Do not use emojis.`}function Zd(){return`You are a worker subagent executing a s
158
158
 
159
159
  `),n=this.claudeFileEntries.map(e=>e.content).join(`
160
160
 
161
- `),r=this.rebuildSystemMessage(t,n,{selfVerification:e});this.getSessionOrThrow().updateSystemMessage(r)}applyCommandModuleSelection(e,t){this.skillRouter.reapplyCommandModuleSelection(e,t)}getAgentJobCapability(){return this}getUserInteraction(){return Ay(this.askHandler,()=>this.getCommandInvocationSource())}canHandoffTerminal(){return this.terminalHandoff?.canHandoffTerminal===!0}async runWithTerminal(e){if(!this.canHandoffTerminal()||this.terminalHandoff===void 0)throw Error(`Terminal handoff is unavailable: no interactive terminal (headless or non-TTY output).`);if(this.terminalHandoffActive)throw Error(`A terminal handoff is already in progress.`);this.terminalHandoffActive=!0;try{return await this.terminalHandoff.runWithTerminal(e)}finally{this.terminalHandoffActive=!1}}setAutoCompactThreshold(e,t=`session`){this.getSessionOrThrow().setAutoCompactThreshold(e),this.autoCompactThresholdSource=t,this.emit(`context_update`,this.getContextState()),this.persistCurrentSession()}clearConversationHistory(){this.getSessionOrThrow().clearHistory(),this.histTracker.clearHistory(),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState())}getName(){return this.sessionName}attachTransport(e){e.attach(this)}setName(e){if(this.sessionName=e,this.sessionStore&&this.session)try{let t=this.getSessionOrThrow().getSessionId(),n=this.sessionStore.load(t);n&&(n.name=e,n.updatedAt=new Date().toISOString(),this.sessionStore.save(n))}catch{}}getBackgroundTaskManager(){if(this.session)return qd(this.session)??wf(this.session)?.backgroundTaskManager}reportBackgroundError(e,t=`background`){let n=rp(e);this.histTracker.append(H(q(`Error: ${n}`,{metadata:{kind:`error`,source:t}}))),this.emit(`error`,e)}async captureSandboxSnapshot(){if(this.sandboxClient?.snapshot)try{this.sandboxSnapshotId=await this.sandboxClient.snapshot()}catch(e){let t=e instanceof Error?e:Error(String(e));this.histTracker.append(H(q(`Sandbox snapshot error: ${t.message}`))),this.emit(`error`,t)}}persistCurrentSession(){if(!this.sessionStore||!this.session)return;let e=this.bgTracker.getState(),t=this.histTracker.getState();Kg(this.sessionStore,this.session,this.sessionName,this.cwd??``,t.history,{tasks:e.tasks,events:e.taskEvents,groups:e.groups,groupEvents:e.groupEvents},{events:t.memoryEvents,usedReferences:t.usedMemoryReferences},{events:t.skillActivationEvents},{references:t.contextReferences},{snapshotId:this.sandboxSnapshotId},this.goalController.getState()??void 0)}async setGoal(e,t={}){await this.ensureInitialized();let{goal:n,prompt:r}=this.goalController.start(e,t);return this.emit(`goal_event`,{type:`goal_started`,goal:n}),this.persistCurrentSession(),this.scheduleGoalTurn(r,n),n}getGoalState(){return this.goalController.getState()}cancelGoal(){let e=this.goalController.cancel();return e&&(this.emit(`goal_event`,{type:`goal_stopped`,goal:e}),this.persistCurrentSession()),e}scheduleGoalTurn(e,t){if(this.execCtrl.shuttingDown)return;let n=`goal:${t.id}:${t.iterations}`;setTimeout(()=>this.requestWakeup(e,n),0)}handleGoalTurnComplete(e){if(!this.goalController.isActive()||this.currentTurnSource!==`agent-wakeup`)return;let t=this.goalController.onTurnComplete(e);t&&(this.persistCurrentSession(),t.action===`continue`?(this.emit(`goal_event`,{type:`goal_progress`,goal:t.goal}),this.scheduleGoalTurn(t.prompt,t.goal)):this.emit(`goal_event`,{type:`goal_stopped`,goal:t.goal}))}resumeGoalIfActive(){let e=this.goalController.getState();!e||e.status!==`active`||this.ensureInitialized().then(()=>{!this.goalController.isActive()||this.execCtrl.shuttingDown||this.scheduleGoalTurn(eh(e),e)})}async switchProvider(e){let t=this.getSessionOrThrow(),n=this.getCwd(),r=B_(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=V_(n,void 0,{providerOverride:e,providerDefinitions:this.providerDefinitions});t.swapProvider(i,r.model)}async executeCommand(e,t){if(this.orgPolicy?.blockedCommands?.includes(e))return{message:Oy(`Command /${e} is blocked by your organization policy.`,this.orgPolicy.adminContact),success:!1};let n=await super.executeCommand(e,t);if(n===null)return null;let r=n.effects?.find(e=>e.type===`provider-hot-swap-requested`);if(r){let{orgPolicy:e}=this;return e?.allowedProviders&&!e.allowedProviders.includes(r.profileName)?{message:Oy(`Provider "${r.profileName}" is not allowed by your organization policy. Allowed: ${e.allowedProviders.join(`, `)}.`,e.adminContact),success:!1}:(await this.switchProvider(r.profileName),{...n,effects:n.effects?.filter(e=>e.type!==`provider-hot-swap-requested`)})}return n}};function My(e,t=new Y){let n=dp(e);return new Ly(n.sessions,n.logs,t)}function Ny(e=new Y){return new Ly(fp().sessions,void 0,e)}function Py(e,t){return(e?.list()??[]).filter(e=>e.cwd===t).sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime()).map(e=>({id:e.id,...e.name===void 0?{}:{name:e.name},cwd:e.cwd,updatedAt:e.updatedAt,messageCount:e.messages.length,preview:Ry(e.messages)}))}function Fy(e,t){return Py(e,t)[0]?.id}function Iy(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var Ly=class{store;logsDir;fs;constructor(e,t,n=new Y){this.store=new ru(e),this.logsDir=t,this.fs=n}save(e){this.store.save(zy(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):By(t)}list(){let e=this.store.list().map(By),t=new Set(e.map(e=>e.id));for(let n of this.listReplayLogRecords())t.has(n.id)||e.push(n);return e.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime())}delete(e){this.store.delete(e)}loadFromReplayLog(e){if(!this.logsDir)return;let t=Xl(Yl(h(this.logsDir,`${e}.jsonl`)));if(!t.sessionId||t.messages.length===0)return;let n=t.backgroundTaskEvents,r=t.backgroundJobGroupEvents;return{id:t.sessionId,cwd:t.cwd??``,createdAt:t.createdAt??t.updatedAt??new Date(0).toISOString(),updatedAt:t.updatedAt??t.createdAt??new Date(0).toISOString(),messages:t.messages,history:t.history,backgroundTasks:Vy(n),backgroundTaskEvents:n,backgroundJobGroups:Uy(r),backgroundJobGroupEvents:r,skillActivationEvents:[],memoryEvents:t.memoryEvents}}listReplayLogRecords(){return!this.logsDir||!this.fs.existsSync(this.logsDir)?[]:this.fs.readdirSync(this.logsDir).filter(e=>e.endsWith(`.jsonl`)).map(e=>this.loadFromReplayLog(e.slice(0,-6))).filter(e=>e!==void 0)}};function Ry(e){for(let t of[...e].reverse())if(t.role===`assistant`&&typeof t.content==`string`)return t.content.replace(/[\n\r]+/g,` `).trim();return``}function zy(e){return{...e}}function By(e){return{id:e.id,...e.name===void 0?{}:{name:e.name},cwd:e.cwd,createdAt:e.createdAt,updatedAt:e.updatedAt,messages:e.messages,...e.history===void 0?{}:{history:e.history},...e.systemPrompt===void 0?{}:{systemPrompt:e.systemPrompt},...e.toolSchemas===void 0?{}:{toolSchemas:e.toolSchemas},...e.backgroundTasks===void 0?{}:{backgroundTasks:e.backgroundTasks},...e.backgroundTaskEvents===void 0?{}:{backgroundTaskEvents:e.backgroundTaskEvents},...e.backgroundJobGroups===void 0?{}:{backgroundJobGroups:e.backgroundJobGroups},...e.backgroundJobGroupEvents===void 0?{}:{backgroundJobGroupEvents:e.backgroundJobGroupEvents},...e.skillActivationEvents===void 0?{}:{skillActivationEvents:e.skillActivationEvents},...e.memoryEvents===void 0?{}:{memoryEvents:e.memoryEvents},...e.usedMemoryReferences===void 0?{}:{usedMemoryReferences:e.usedMemoryReferences},...e.contextReferences===void 0?{}:{contextReferences:e.contextReferences},...e.sandboxSnapshotId===void 0?{}:{sandboxSnapshotId:e.sandboxSnapshotId}}}function Vy(e){let t=new Map;for(let n of e){let e=Hy(n);e&&t.set(e.id,e)}return[...t.values()]}function Hy(e){switch(e.type){case`background_task_created`:case`background_task_started`:case`background_task_updated`:case`background_task_completed`:case`background_task_failed`:case`background_task_cancelled`:return e.task;default:return}}function Uy(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function Wy(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,``).trim().replace(/\s+/g,`-`).replace(/-+/g,`-`).slice(0,60)}async function Gy(e,t){let n=t.slice(0,200),r=await e.chat([q(`You generate short session titles. Respond with ONLY a 3-5 word lowercase-hyphenated title (e.g. refactor-auth-middleware). No explanation, no punctuation, no quotes.`),ai(n)],{maxTokens:20}),i=Wy(typeof r.content==`string`?r.content:``);return!i||i.length<3?Wy(t):i}var Ky=class{settingsPath;fs;constructor(e,t=new Y){this.settingsPath=e,this.fs=t}readAll(){if(!this.fs.existsSync(this.settingsPath))return{};try{let e=this.fs.readFileSync(this.settingsPath,`utf-8`),t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}writeAll(e){let t=p(this.settingsPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.settingsPath,JSON.stringify(e,null,2),`utf-8`)}getEnabledPlugins(){let e=this.readAll().enabledPlugins;return typeof e==`object`&&e?e:{}}setPluginEnabled(e,t){let n=this.readAll(),r=this.getEnabledPluginsFrom(n);r[e]=t,n.enabledPlugins=r,this.writeAll(n)}removePluginEntry(e){let t=this.readAll(),n=this.getEnabledPluginsFrom(t);delete n[e],t.enabledPlugins=n,this.writeAll(t)}getMarketplaceSources(){let e=this.readAll().extraKnownMarketplaces;return typeof e==`object`&&e?e:{}}setMarketplaceSource(e,t){let n=this.readAll(),r=this.getMarketplaceSourcesFrom(n);r[e]={source:t},n.extraKnownMarketplaces=r,this.writeAll(n)}removeMarketplaceSource(e){let t=this.readAll(),n=this.getMarketplaceSourcesFrom(t);delete n[e],t.extraKnownMarketplaces=n,this.writeAll(t)}getEnabledPluginsFrom(e){let t=e.enabledPlugins;return typeof t==`object`&&t?t:{}}getMarketplaceSourcesFrom(e){let t=e.extraKnownMarketplaces;return typeof t==`object`&&t?t:{}}},qy=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=h(this.pluginsDir,`cache`),this.registryPath=h(this.pluginsDir,`installed_plugins.json`),this.settingsStore=e.settingsStore,this.marketplaceClient=e.marketplaceClient,this.exec=e.exec,this.fs=e.fs??new Y}async install(e,t){let n=this.marketplaceClient.fetchManifest(t).plugins.find(t=>t.name===e);if(!n)throw Error(`Plugin "${e}" not found in marketplace "${t}"`);let r=this.resolveVersion(n,t),i=h(this.cacheDir,t,e,r);if(this.fs.existsSync(i))throw Error(`Plugin "${e}" version "${r}" is already installed from "${t}"`);this.resolveAndInstall(n.source,t,e,i);let a=`${e}@${t}`,o=this.readRegistry();o[a]={pluginName:e,marketplace:t,version:r,installPath:i,installedAt:new Date().toISOString()},this.writeRegistry(o)}async uninstall(e){let t=this.readRegistry(),n=t[e];if(!n)throw Error(`Plugin "${e}" is not installed`);this.fs.existsSync(n.installPath)&&this.fs.rmSync(n.installPath,{recursive:!0,force:!0}),delete t[e],this.writeRegistry(t),this.settingsStore.removePluginEntry(e)}async enable(e){this.settingsStore.setPluginEnabled(e,!0)}async disable(e){this.settingsStore.setPluginEnabled(e,!1)}getInstalledPlugins(){return this.readRegistry()}getPluginsByMarketplace(e){let t=this.readRegistry();return Object.values(t).filter(t=>t.marketplace===e)}resolveVersion(e,t){let n=e;return typeof n.version==`string`&&n.version?n.version:this.marketplaceClient.getMarketplaceSha(t)}normalizeSource(e){if(typeof e==`string`)return e;let t=e;return!t.type&&typeof t.source==`string`?{...t,type:t.source}:e}resolveAndInstall(e,t,n,r){this.fs.mkdirSync(r,{recursive:!0});let i=this.normalizeSource(e);try{if(typeof i==`string`){let e=h(this.marketplaceClient.getMarketplaceDir(t),i);if(!this.fs.existsSync(e))throw Error(`Plugin source path "${i}" not found in marketplace "${t}"`);this.fs.cpSync(e,r,{recursive:!0})}else if(i.type===`github`){let e=`https://github.com/${i.repo}.git`;this.cloneToDir(e,r,n)}else if(i.type===`url`&&typeof i.url==`string`&&i.url.endsWith(`.git`))this.cloneToDir(i.url,r,n);else if(i.type===`url`)throw Error(`URL source "${i.url}" is not a git repository (must end with .git)`);else throw Error(`Unknown source type: ${JSON.stringify(i)}`)}catch(e){throw this.fs.existsSync(r)&&this.fs.rmSync(r,{recursive:!0,force:!0}),e}}cloneToDir(e,t,n){this.fs.rmSync(t,{recursive:!0,force:!0});let r=`git clone --depth 1 ${e} ${t}`;try{this.exec(r,{timeout:6e4,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone plugin "${n}": ${t}`)}}readRegistry(){if(!this.fs.existsSync(this.registryPath))return{};try{let e=this.fs.readFileSync(this.registryPath,`utf-8`),t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}writeRegistry(e){let t=p(this.registryPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}};function Jy(e,t=new Y){if(!t.existsSync(e))return{};try{let n=t.readFileSync(e,`utf-8`),r=JSON.parse(n);return typeof r==`object`&&r?r:{}}catch{return{}}}function Yy(e,t,n=new Y){let r=p(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function Xy(e,t,n=new Y){let r=h(e,`installed_plugins.json`);if(!n.existsSync(r))return;let i;try{let e=n.readFileSync(r,`utf-8`),t=JSON.parse(e);if(typeof t!=`object`||!t)return;i=t}catch{return}let a=!1;for(let[e,r]of Object.entries(i))r.marketplace===t&&(r.installPath&&n.existsSync(r.installPath)&&n.rmSync(r.installPath,{recursive:!0,force:!0}),delete i[e],a=!0);if(a){let e=p(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const Zy=6e4;var Qy=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=h(this.pluginsDir,`marketplaces`),this.registryPath=h(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new Y}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=h(this.marketplacesDir,t);if(this.fs.mkdirSync(this.marketplacesDir,{recursive:!0}),e.type===`local`){if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.cpSync(e.path,n,{recursive:!0})}else{let t=`git clone --depth 1 ${this.resolveCloneUrl(e)} ${n}`;try{this.exec(t,{timeout:Zy,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=h(n,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(r))throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(e.type===`local`?`Local directory does not contain .claude-plugin/marketplace.json`:`Cloned repository does not contain .claude-plugin/marketplace.json`);let i=this.readManifestFromPath(r).name;if(!i)throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace manifest does not contain a "name" field`);let a=Jy(this.registryPath,this.fs);if(a[i])throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace "${i}" already exists`);let o=h(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},Yy(this.registryPath,a,this.fs),i}removeMarketplace(e){let t=Jy(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);Xy(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],Yy(this.registryPath,t,this.fs)}updateMarketplace(e){let t=Jy(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);if(!this.fs.existsSync(n.installLocation))throw Error(`Marketplace directory for "${e}" does not exist`);if(n.source.type===`local`){let e=n.source;if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),this.fs.cpSync(e.path,n.installLocation,{recursive:!0})}else{let t=`git -C ${n.installLocation} pull`;try{this.exec(t,{timeout:Zy,stdio:`pipe`})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Failed to update marketplace "${e}": ${n}`)}}n.lastUpdated=new Date().toISOString(),Yy(this.registryPath,t,this.fs)}listMarketplaces(){let e=Jy(this.registryPath,this.fs);return Object.entries(e).map(([e,t])=>({name:e,source:t.source,lastUpdated:t.lastUpdated}))}fetchManifest(e){let t=Jy(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);let n=h(t.installLocation,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(n))throw Error(`Marketplace "${e}" does not contain .claude-plugin/marketplace.json`);return this.readManifestFromPath(n)}getMarketplaceDir(e){let t=Jy(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);return t.installLocation}getMarketplaceSha(e){let t=this.getMarketplaceDir(e);try{return this.exec(`git -C ${t} rev-parse HEAD`,{timeout:Zy,stdio:`pipe`}).toString().trim().slice(0,12)}catch{return`unknown`}}listAvailablePlugins(){let e=[],t=this.listMarketplaces();for(let{name:n}of t)try{let t=this.fetchManifest(n);for(let r of t.plugins)e.push({...r,marketplace:n})}catch{}return e}resolveCloneUrl(e){switch(e.type){case`github`:return`https://github.com/${e.repo}.git`;case`git`:return e.url;case`local`:throw Error(`Local source type does not use git cloning`);case`url`:throw Error(`URL marketplace source is not yet supported`)}}readManifestFromPath(e){let t=this.fs.readFileSync(e,`utf-8`),n=JSON.parse(t);if(typeof n!=`object`||!n)throw Error(`Invalid marketplace manifest: not an object`);if(typeof n.name!=`string`)throw Error(`Invalid marketplace manifest: missing "name" field`);return n}};const $y=[{category:`preferences`,purpose:`User-local UI and display preferences.`,mayExecuteCommands:!1},{category:`view-state`,purpose:`Last selected panels, filters, and navigation state.`,mayExecuteCommands:!1},{category:`memory-projections`,purpose:`Inspectable local memory item projections and user choices.`,mayExecuteCommands:!1},{category:`task-associations`,purpose:`User-local associations between sessions, tasks, and background items.`,mayExecuteCommands:!1},{category:`workflow-metadata`,purpose:`Transparent workflow metadata that is not repo-owned.`,mayExecuteCommands:!1},{category:`inspection-index`,purpose:`Category and item summaries for user inspection and deletion.`,mayExecuteCommands:!1}];function eb(e){return e.toISOString()}function tb(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!d.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function nb(){return process.env.HOME??x()}function rb(e,t){let n=d.relative(e,t);return n===``||!n.startsWith(`..`)&&!d.isAbsolute(n)}async function ib(e,t){let n=e;for(;d.dirname(n)!==n;)try{let r=await t.realpath(n),i=d.relative(n,e);return d.resolve(r,i)}catch{n=d.dirname(n)}try{return await t.realpath(n)}catch{return d.resolve(e)}}async function ab(e){let t=e.fsAsync??new ku,n=d.resolve(e.activeRepositoryRoot);tb(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?d.join(e.homeDir??nb(),`.robota`):e.storageRoot;tb(`userLocalStorageRoot`,r);let i=d.resolve(r),a=await ib(i,t);if(rb(await ib(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function ob(e,t){return d.join(e,t)}async function sb(e,t,n){let r=ob(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=d.join(r,i.name),o=await n.stat(a),s=i.name;return{root:e,category:t,key:s,summary:`${t}/${s}`,source:`user-local-storage`,scope:`user`,storageLocation:a,createdAt:eb(new Date(o.birthtimeMs)),lastUsedAt:eb(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function cb(e){let t=e.fsAsync??new ku,n=await ab(e),r=d.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all($y.map(async e=>{let r=ob(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await sb(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:eb((e.now??(()=>new Date))())}}const lb=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],ub=`.json`,db=/^[a-z0-9][a-z0-9._-]*$/u,fb={"view-preference":`May affect UI panel, filter, density, or sorting display/navigation only.`,"last-visible-cwd":`May display or preselect an already visible workspace context only.`,"background-selection":`May restore the selected background entry in local UI only.`,"task-association":`May group visible tasks by a local association only.`,"display-preference":`May affect local text wrapping, compactness, or visibility only.`,"inspection-choice":`May affect inspection display choices only.`};function pb(e){return e.toISOString()}function mb(e){return lb.includes(e)}function hb(e){if(!mb(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function gb(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!db.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function _b(e,t,n){let r=t.trim().replace(/\s+/g,` `);if(r.length===0)throw Error(`${e} must not be empty.`);return r.length>n?r.slice(0,n):r}function vb(e){return _b(`value`,e,240)}function yb(e,t){return`${e}__${t}${ub}`}async function bb(e){let t=await ab(e);return{root:t,memoryRoot:d.join(t,`memory-projections`)}}function xb(e,t){let n=JSON.parse(e),r=Sb(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:hb(r),key:Sb(n,`key`),value:Sb(n,`value`),summary:Sb(n,`summary`),source:Sb(n,`source`),scope:Sb(n,`scope`),createdAt:Sb(n,`createdAt`),lastUsedAt:Sb(n,`lastUsedAt`),enabled:Cb(n,`enabled`)}}function Sb(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function Cb(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function wb(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:vb(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:fb[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function Tb(e,t,n){return wb(e,t,xb(await n.readFile(t,`utf8`),t))}async function Eb(e){let t=hb(e.category),n=gb(`key`,e.key),{root:r,memoryRoot:i}=await bb(e);return{root:r,storageLocation:d.join(i,yb(t,n))}}async function Db(e){let t=e.fsAsync??new ku,n=hb(e.category),r=gb(`key`,e.key),i=_b(`summary`,e.summary,240),a=_b(`source`,e.source,80),o=_b(`scope`,e.scope??`user`,120),s=vb(e.value),c=pb((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await bb(e),f=d.join(u,yb(n,r)),p=c;try{p=xb(await t.readFile(f,`utf8`),f).createdAt}catch(e){if(e instanceof Error&&e.message.includes(`ENOENT`))p=c;else throw e}let m={schemaVersion:1,category:n,key:r,value:s,summary:i,source:a,scope:o,createdAt:p,lastUsedAt:c,enabled:!0};return await t.mkdir(u,{recursive:!0}),await t.writeFile(f,`${JSON.stringify(m,null,2)}\n`,`utf8`),wb(l,f,m)}async function Ob(e){let t=e.fsAsync??new ku,{root:n,memoryRoot:r}=await bb(e),i;try{i=await t.readdir(r,{withFileTypes:!0})}catch{i=[]}let a=await Promise.all(i.filter(e=>e.isFile()&&e.name.endsWith(ub)).map(e=>Tb(n,d.join(r,e.name),t)));return{root:n,activeRepositoryRoot:d.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function kb(e){let t=e.fsAsync??new ku,{root:n,storageLocation:r}=await Eb(e);return Tb(n,r,t)}async function Ab(e){let t=e.fsAsync??new ku,{root:n,storageLocation:r}=await Eb(e),i={...xb(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:pb((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),wb(n,r,i)}async function jb(e){let t=e.fsAsync??new ku,{storageLocation:n}=await Eb(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}function Mb(e){return/^\/\S/.test(e)}function Nb(e){let t=e.slice(1).trim().split(/\s+/);return{name:t[0]??``,args:t.slice(1).filter(e=>e.length>0)}}function Pb(){let e=Wm();return{deleted:Jm(e),path:e}}function Fb(e){try{let t=Ib(e);if(!t)return;let n=O(h(t,`HEAD`),`utf8`).trim();if(!n)return;if(n.startsWith(`ref: `)){let e=n.slice(5).trim();return e.startsWith(`refs/heads/`)?e.slice(11):e}return n.slice(0,7)}catch{return}}function Ib(e){let t=v(e),n=p(t);for(;n!==t;){let e=Lb(h(t,`.git`),t);if(e)return e;t=n,n=p(t)}return Lb(h(t,`.git`),t)}function Lb(e,t){if(!T(e))return;let n=E(e);if(n.isDirectory())return e;if(!n.isFile())return;let r=O(e,`utf8`).trim();if(!r.startsWith(`gitdir:`))return;let i=r.slice(7).trim();return m(i)?i:v(t,i)}function Rb(e,t){let n=Bb(e),r=Bb(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=Hb(n.major,r.major)||Hb(n.minor,r.minor)||Hb(n.patch,r.patch);return i===0?Ub(n.prerelease,r.prerelease):i}function zb(e,t){return Rb(e,t)>0}function Bb(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=Vb(r),s=Vb(i),c=Vb(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function Vb(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function Hb(e,t){return Math.sign(e-t)}function Ub(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r],i=t[r];if(n===void 0)return-1;if(i===void 0)return 1;let a=Wb(n,i);if(a!==0)return a}return 0}function Wb(e,t){let n=Vb(e),r=Vb(t);return n!==void 0&&r!==void 0?Hb(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function Gb(e){let t=p(Ae(e)),n=[h(t,`..`,`..`,`package.json`),h(t,`..`,`package.json`)];for(let e of n)try{let t=O(e,`utf-8`),n=JSON.parse(t);if(n.version!==void 0&&n.name!==void 0)return n.version}catch{continue}return`0.0.0`}function Kb(e=process.env.HOME??process.env.USERPROFILE??`/`){return h(e,`.robota`,`update-check.json`)}function qb(e){if(T(e))try{return cx(JSON.parse(O(e,`utf8`)))}catch{return}}function Jb(e,t){D(p(e),{recursive:!0}),k(e,JSON.stringify(t,null,2)+`
161
+ `),r=this.rebuildSystemMessage(t,n,{selfVerification:e});this.getSessionOrThrow().updateSystemMessage(r)}applyCommandModuleSelection(e,t){this.skillRouter.reapplyCommandModuleSelection(e,t)}getAgentJobCapability(){return this}getUserInteraction(){return Ay(this.askHandler,()=>this.getCommandInvocationSource())}canHandoffTerminal(){return this.terminalHandoff?.canHandoffTerminal===!0}async runWithTerminal(e){if(!this.canHandoffTerminal()||this.terminalHandoff===void 0)throw Error(`Terminal handoff is unavailable: no interactive terminal (headless or non-TTY output).`);if(this.terminalHandoffActive)throw Error(`A terminal handoff is already in progress.`);this.terminalHandoffActive=!0;try{return await this.terminalHandoff.runWithTerminal(e)}finally{this.terminalHandoffActive=!1}}setAutoCompactThreshold(e,t=`session`){this.getSessionOrThrow().setAutoCompactThreshold(e),this.autoCompactThresholdSource=t,this.emit(`context_update`,this.getContextState()),this.persistCurrentSession()}clearConversationHistory(){this.getSessionOrThrow().clearHistory(),this.histTracker.clearHistory(),this.persistCurrentSession(),this.emit(`context_update`,this.getContextState())}getName(){return this.sessionName}attachTransport(e){e.attach(this)}setName(e){if(this.sessionName=e,this.sessionStore&&this.session)try{let t=this.getSessionOrThrow().getSessionId(),n=this.sessionStore.load(t);n&&(n.name=e,n.updatedAt=new Date().toISOString(),this.sessionStore.save(n))}catch{}}getBackgroundTaskManager(){if(this.session)return qd(this.session)??wf(this.session)?.backgroundTaskManager}reportBackgroundError(e,t=`background`){let n=rp(e);this.histTracker.append(H(q(`Error: ${n}`,{metadata:{kind:`error`,source:t}}))),this.emit(`error`,e)}async captureSandboxSnapshot(){if(this.sandboxClient?.snapshot)try{this.sandboxSnapshotId=await this.sandboxClient.snapshot()}catch(e){let t=e instanceof Error?e:Error(String(e));this.histTracker.append(H(q(`Sandbox snapshot error: ${t.message}`))),this.emit(`error`,t)}}persistCurrentSession(){if(!this.sessionStore||!this.session)return;let e=this.bgTracker.getState(),t=this.histTracker.getState();Kg(this.sessionStore,this.session,this.sessionName,this.cwd??``,t.history,{tasks:e.tasks,events:e.taskEvents,groups:e.groups,groupEvents:e.groupEvents},{events:t.memoryEvents,usedReferences:t.usedMemoryReferences},{events:t.skillActivationEvents},{references:t.contextReferences},{snapshotId:this.sandboxSnapshotId},this.goalController.getState()??void 0)}async setGoal(e,t={}){await this.ensureInitialized();let{goal:n,prompt:r}=this.goalController.start(e,t);return this.emit(`goal_event`,{type:`goal_started`,goal:n}),this.persistCurrentSession(),this.scheduleGoalTurn(r,n),n}getGoalState(){return this.goalController.getState()}cancelGoal(){let e=this.goalController.cancel();return e&&(this.emit(`goal_event`,{type:`goal_stopped`,goal:e}),this.persistCurrentSession()),e}scheduleGoalTurn(e,t){if(this.execCtrl.shuttingDown)return;let n=`goal:${t.id}:${t.iterations}`;setTimeout(()=>this.requestWakeup(e,n),0)}handleGoalTurnComplete(e){if(!this.goalController.isActive()||this.currentTurnSource!==`agent-wakeup`)return;let t=this.goalController.onTurnComplete(e);t&&(this.persistCurrentSession(),t.action===`continue`?(this.emit(`goal_event`,{type:`goal_progress`,goal:t.goal}),this.scheduleGoalTurn(t.prompt,t.goal)):this.emit(`goal_event`,{type:`goal_stopped`,goal:t.goal}))}resumeGoalIfActive(){let e=this.goalController.getState();!e||e.status!==`active`||this.ensureInitialized().then(()=>{!this.goalController.isActive()||this.execCtrl.shuttingDown||this.scheduleGoalTurn(eh(e),e)})}async switchProvider(e){let t=this.getSessionOrThrow(),n=this.getCwd(),r=B_(n,{providerOverride:e,providerDefinitions:this.providerDefinitions}),i=V_(n,void 0,{providerOverride:e,providerDefinitions:this.providerDefinitions});t.swapProvider(i,r.model)}async executeCommand(e,t){if(this.orgPolicy?.blockedCommands?.includes(e))return{message:Oy(`Command /${e} is blocked by your organization policy.`,this.orgPolicy.adminContact),success:!1};let n=await super.executeCommand(e,t);if(n===null)return null;let r=n.effects?.find(e=>e.type===`provider-hot-swap-requested`);if(r){let{orgPolicy:e}=this;return e?.allowedProviders&&!e.allowedProviders.includes(r.profileName)?{message:Oy(`Provider "${r.profileName}" is not allowed by your organization policy. Allowed: ${e.allowedProviders.join(`, `)}.`,e.adminContact),success:!1}:(await this.switchProvider(r.profileName),{...n,effects:n.effects?.filter(e=>e.type!==`provider-hot-swap-requested`)})}return n}};function My(e,t=new Y){let n=dp(e);return new Ly(n.sessions,n.logs,t)}function Ny(e=new Y){return new Ly(fp().sessions,void 0,e)}function Py(e,t){return(e?.list()??[]).filter(e=>e.cwd===t).sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime()).map(e=>({id:e.id,...e.name===void 0?{}:{name:e.name},cwd:e.cwd,updatedAt:e.updatedAt,messageCount:e.messages.length,preview:Ry(e.messages)}))}function Fy(e,t){return Py(e,t)[0]?.id}function Iy(e,t){return(e?.list()??[]).find(e=>e.id===t||e.name===t)?.id}var Ly=class{store;logsDir;fs;constructor(e,t,n=new Y){this.store=new ru(e),this.logsDir=t,this.fs=n}save(e){this.store.save(zy(e))}load(e){let t=this.store.load(e);return t===void 0?this.loadFromReplayLog(e):By(t)}list(){let e=this.store.list().map(By),t=new Set(e.map(e=>e.id));for(let n of this.listReplayLogRecords())t.has(n.id)||e.push(n);return e.sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime())}delete(e){this.store.delete(e)}loadFromReplayLog(e){if(!this.logsDir)return;let t=Xl(Yl(h(this.logsDir,`${e}.jsonl`)));if(!t.sessionId||t.messages.length===0)return;let n=t.backgroundTaskEvents,r=t.backgroundJobGroupEvents;return{id:t.sessionId,cwd:t.cwd??``,createdAt:t.createdAt??t.updatedAt??new Date(0).toISOString(),updatedAt:t.updatedAt??t.createdAt??new Date(0).toISOString(),messages:t.messages,history:t.history,backgroundTasks:Vy(n),backgroundTaskEvents:n,backgroundJobGroups:Uy(r),backgroundJobGroupEvents:r,skillActivationEvents:[],memoryEvents:t.memoryEvents}}listReplayLogRecords(){return!this.logsDir||!this.fs.existsSync(this.logsDir)?[]:this.fs.readdirSync(this.logsDir).filter(e=>e.endsWith(`.jsonl`)).map(e=>this.loadFromReplayLog(e.slice(0,-6))).filter(e=>e!==void 0)}};function Ry(e){for(let t of[...e].reverse())if(t.role===`assistant`&&typeof t.content==`string`)return t.content.replace(/[\n\r]+/g,` `).trim();return``}function zy(e){return{...e}}function By(e){return{id:e.id,...e.name===void 0?{}:{name:e.name},cwd:e.cwd,createdAt:e.createdAt,updatedAt:e.updatedAt,messages:e.messages,...e.history===void 0?{}:{history:e.history},...e.systemPrompt===void 0?{}:{systemPrompt:e.systemPrompt},...e.toolSchemas===void 0?{}:{toolSchemas:e.toolSchemas},...e.backgroundTasks===void 0?{}:{backgroundTasks:e.backgroundTasks},...e.backgroundTaskEvents===void 0?{}:{backgroundTaskEvents:e.backgroundTaskEvents},...e.backgroundJobGroups===void 0?{}:{backgroundJobGroups:e.backgroundJobGroups},...e.backgroundJobGroupEvents===void 0?{}:{backgroundJobGroupEvents:e.backgroundJobGroupEvents},...e.skillActivationEvents===void 0?{}:{skillActivationEvents:e.skillActivationEvents},...e.memoryEvents===void 0?{}:{memoryEvents:e.memoryEvents},...e.usedMemoryReferences===void 0?{}:{usedMemoryReferences:e.usedMemoryReferences},...e.contextReferences===void 0?{}:{contextReferences:e.contextReferences},...e.sandboxSnapshotId===void 0?{}:{sandboxSnapshotId:e.sandboxSnapshotId}}}function Vy(e){let t=new Map;for(let n of e){let e=Hy(n);e&&t.set(e.id,e)}return[...t.values()]}function Hy(e){switch(e.type){case`background_task_created`:case`background_task_started`:case`background_task_updated`:case`background_task_completed`:case`background_task_failed`:case`background_task_cancelled`:return e.task;default:return}}function Uy(e){let t=new Map;for(let n of e)t.set(n.group.id,n.group);return[...t.values()]}function Wy(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,``).trim().replace(/\s+/g,`-`).replace(/-+/g,`-`).slice(0,60)}async function Gy(e,t){let n=t.slice(0,200),r=await e.chat([q(`You generate short session titles. Respond with ONLY a 3-5 word lowercase-hyphenated title (e.g. refactor-auth-middleware). No explanation, no punctuation, no quotes.`),ai(n)],{maxTokens:20}),i=Wy(typeof r.content==`string`?r.content:``);return!i||i.length<3?Wy(t):i}var Ky=class{settingsPath;fs;constructor(e,t=new Y){this.settingsPath=e,this.fs=t}readAll(){if(!this.fs.existsSync(this.settingsPath))return{};try{let e=this.fs.readFileSync(this.settingsPath,`utf-8`),t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}writeAll(e){let t=p(this.settingsPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.settingsPath,JSON.stringify(e,null,2),`utf-8`)}getEnabledPlugins(){let e=this.readAll().enabledPlugins;return typeof e==`object`&&e?e:{}}setPluginEnabled(e,t){let n=this.readAll(),r=this.getEnabledPluginsFrom(n);r[e]=t,n.enabledPlugins=r,this.writeAll(n)}removePluginEntry(e){let t=this.readAll(),n=this.getEnabledPluginsFrom(t);delete n[e],t.enabledPlugins=n,this.writeAll(t)}getMarketplaceSources(){let e=this.readAll().extraKnownMarketplaces;return typeof e==`object`&&e?e:{}}setMarketplaceSource(e,t){let n=this.readAll(),r=this.getMarketplaceSourcesFrom(n);r[e]={source:t},n.extraKnownMarketplaces=r,this.writeAll(n)}removeMarketplaceSource(e){let t=this.readAll(),n=this.getMarketplaceSourcesFrom(t);delete n[e],t.extraKnownMarketplaces=n,this.writeAll(t)}getEnabledPluginsFrom(e){let t=e.enabledPlugins;return typeof t==`object`&&t?t:{}}getMarketplaceSourcesFrom(e){let t=e.extraKnownMarketplaces;return typeof t==`object`&&t?t:{}}},qy=class{pluginsDir;cacheDir;registryPath;settingsStore;marketplaceClient;exec;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.cacheDir=h(this.pluginsDir,`cache`),this.registryPath=h(this.pluginsDir,`installed_plugins.json`),this.settingsStore=e.settingsStore,this.marketplaceClient=e.marketplaceClient,this.exec=e.exec,this.fs=e.fs??new Y}async install(e,t){let n=this.marketplaceClient.fetchManifest(t).plugins.find(t=>t.name===e);if(!n)throw Error(`Plugin "${e}" not found in marketplace "${t}"`);let r=this.resolveVersion(n,t),i=h(this.cacheDir,t,e,r);if(this.fs.existsSync(i))throw Error(`Plugin "${e}" version "${r}" is already installed from "${t}"`);this.resolveAndInstall(n.source,t,e,i);let a=`${e}@${t}`,o=this.readRegistry();o[a]={pluginName:e,marketplace:t,version:r,installPath:i,installedAt:new Date().toISOString()},this.writeRegistry(o)}async uninstall(e){let t=this.readRegistry(),n=t[e];if(!n)throw Error(`Plugin "${e}" is not installed`);this.fs.existsSync(n.installPath)&&this.fs.rmSync(n.installPath,{recursive:!0,force:!0}),delete t[e],this.writeRegistry(t),this.settingsStore.removePluginEntry(e)}async enable(e){this.settingsStore.setPluginEnabled(e,!0)}async disable(e){this.settingsStore.setPluginEnabled(e,!1)}getInstalledPlugins(){return this.readRegistry()}getPluginsByMarketplace(e){let t=this.readRegistry();return Object.values(t).filter(t=>t.marketplace===e)}resolveVersion(e,t){let n=e;return typeof n.version==`string`&&n.version?n.version:this.marketplaceClient.getMarketplaceSha(t)}normalizeSource(e){if(typeof e==`string`)return e;let t=e;return!t.type&&typeof t.source==`string`?{...t,type:t.source}:e}resolveAndInstall(e,t,n,r){this.fs.mkdirSync(r,{recursive:!0});let i=this.normalizeSource(e);try{if(typeof i==`string`){let e=h(this.marketplaceClient.getMarketplaceDir(t),i);if(!this.fs.existsSync(e))throw Error(`Plugin source path "${i}" not found in marketplace "${t}"`);this.fs.cpSync(e,r,{recursive:!0})}else if(i.type===`github`){let e=`https://github.com/${i.repo}.git`;this.cloneToDir(e,r,n)}else if(i.type===`url`&&typeof i.url==`string`&&i.url.endsWith(`.git`))this.cloneToDir(i.url,r,n);else if(i.type===`url`)throw Error(`URL source "${i.url}" is not a git repository (must end with .git)`);else throw Error(`Unknown source type: ${JSON.stringify(i)}`)}catch(e){throw this.fs.existsSync(r)&&this.fs.rmSync(r,{recursive:!0,force:!0}),e}}cloneToDir(e,t,n){this.fs.rmSync(t,{recursive:!0,force:!0});let r=`git clone --depth 1 ${e} ${t}`;try{this.exec(r,{timeout:6e4,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone plugin "${n}": ${t}`)}}readRegistry(){if(!this.fs.existsSync(this.registryPath))return{};try{let e=this.fs.readFileSync(this.registryPath,`utf-8`),t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}writeRegistry(e){let t=p(this.registryPath);this.fs.existsSync(t)||this.fs.mkdirSync(t,{recursive:!0}),this.fs.writeFileSync(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}};function Jy(e,t=new Y){if(!t.existsSync(e))return{};try{let n=t.readFileSync(e,`utf-8`),r=JSON.parse(n);return typeof r==`object`&&r?r:{}}catch{return{}}}function Yy(e,t,n=new Y){let r=p(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(e,JSON.stringify(t,null,2),`utf-8`)}function Xy(e,t,n=new Y){let r=h(e,`installed_plugins.json`);if(!n.existsSync(r))return;let i;try{let e=n.readFileSync(r,`utf-8`),t=JSON.parse(e);if(typeof t!=`object`||!t)return;i=t}catch{return}let a=!1;for(let[e,r]of Object.entries(i))r.marketplace===t&&(r.installPath&&n.existsSync(r.installPath)&&n.rmSync(r.installPath,{recursive:!0,force:!0}),delete i[e],a=!0);if(a){let e=p(r);n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.writeFileSync(r,JSON.stringify(i,null,2),`utf-8`)}}const Zy=6e4;var Qy=class{pluginsDir;exec;marketplacesDir;registryPath;fs;constructor(e){this.pluginsDir=e.pluginsDir,this.exec=e.exec,this.marketplacesDir=h(this.pluginsDir,`marketplaces`),this.registryPath=h(this.pluginsDir,`known_marketplaces.json`),this.fs=e.fs??new Y}addMarketplace(e){let t=`temp-`+Date.now().toString(36),n=h(this.marketplacesDir,t);if(this.fs.mkdirSync(this.marketplacesDir,{recursive:!0}),e.type===`local`){if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.cpSync(e.path,n,{recursive:!0})}else{let t=`git clone --depth 1 ${this.resolveCloneUrl(e)} ${n}`;try{this.exec(t,{timeout:Zy,stdio:`pipe`})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to clone marketplace: ${t}`)}}let r=h(n,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(r))throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(e.type===`local`?`Local directory does not contain .claude-plugin/marketplace.json`:`Cloned repository does not contain .claude-plugin/marketplace.json`);let i=this.readManifestFromPath(r).name;if(!i)throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace manifest does not contain a "name" field`);let a=Jy(this.registryPath,this.fs);if(a[i])throw this.fs.rmSync(n,{recursive:!0,force:!0}),Error(`Marketplace "${i}" already exists`);let o=h(this.marketplacesDir,i);return this.fs.renameSync(n,o),a[i]={source:e,installLocation:o,lastUpdated:new Date().toISOString()},Yy(this.registryPath,a,this.fs),i}removeMarketplace(e){let t=Jy(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);Xy(this.pluginsDir,e,this.fs),this.fs.existsSync(n.installLocation)&&this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),delete t[e],Yy(this.registryPath,t,this.fs)}updateMarketplace(e){let t=Jy(this.registryPath,this.fs),n=t[e];if(!n)throw Error(`Marketplace "${e}" not found`);if(!this.fs.existsSync(n.installLocation))throw Error(`Marketplace directory for "${e}" does not exist`);if(n.source.type===`local`){let e=n.source;if(!this.fs.existsSync(e.path))throw Error(`Local marketplace path does not exist: ${e.path}`);this.fs.rmSync(n.installLocation,{recursive:!0,force:!0}),this.fs.cpSync(e.path,n.installLocation,{recursive:!0})}else{let t=`git -C ${n.installLocation} pull`;try{this.exec(t,{timeout:Zy,stdio:`pipe`})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Failed to update marketplace "${e}": ${n}`)}}n.lastUpdated=new Date().toISOString(),Yy(this.registryPath,t,this.fs)}listMarketplaces(){let e=Jy(this.registryPath,this.fs);return Object.entries(e).map(([e,t])=>({name:e,source:t.source,lastUpdated:t.lastUpdated}))}fetchManifest(e){let t=Jy(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);let n=h(t.installLocation,`.claude-plugin`,`marketplace.json`);if(!this.fs.existsSync(n))throw Error(`Marketplace "${e}" does not contain .claude-plugin/marketplace.json`);return this.readManifestFromPath(n)}getMarketplaceDir(e){let t=Jy(this.registryPath,this.fs)[e];if(!t)throw Error(`Marketplace "${e}" not found`);return t.installLocation}getMarketplaceSha(e){let t=this.getMarketplaceDir(e);try{return this.exec(`git -C ${t} rev-parse HEAD`,{timeout:Zy,stdio:`pipe`}).toString().trim().slice(0,12)}catch{return`unknown`}}listAvailablePlugins(){let e=[],t=this.listMarketplaces();for(let{name:n}of t)try{let t=this.fetchManifest(n);for(let r of t.plugins)e.push({...r,marketplace:n})}catch{}return e}resolveCloneUrl(e){switch(e.type){case`github`:return`https://github.com/${e.repo}.git`;case`git`:return e.url;case`local`:throw Error(`Local source type does not use git cloning`);case`url`:throw Error(`URL marketplace source is not yet supported`)}}readManifestFromPath(e){let t=this.fs.readFileSync(e,`utf-8`),n=JSON.parse(t);if(typeof n!=`object`||!n)throw Error(`Invalid marketplace manifest: not an object`);if(typeof n.name!=`string`)throw Error(`Invalid marketplace manifest: missing "name" field`);return n}};const $y=[{category:`preferences`,purpose:`User-local UI and display preferences.`,mayExecuteCommands:!1},{category:`view-state`,purpose:`Last selected panels, filters, and navigation state.`,mayExecuteCommands:!1},{category:`memory-projections`,purpose:`Inspectable local memory item projections and user choices.`,mayExecuteCommands:!1},{category:`task-associations`,purpose:`User-local associations between sessions, tasks, and background items.`,mayExecuteCommands:!1},{category:`workflow-metadata`,purpose:`Transparent workflow metadata that is not repo-owned.`,mayExecuteCommands:!1},{category:`inspection-index`,purpose:`Category and item summaries for user inspection and deletion.`,mayExecuteCommands:!1}];function eb(e){return e.toISOString()}function tb(e,t){if(t.trim().length===0)throw Error(`${e} must not be empty.`);if(!d.isAbsolute(t))throw Error(`${e} must be an absolute path: ${t}`)}function nb(){return process.env.HOME??x()}function rb(e,t){let n=d.relative(e,t);return n===``||!n.startsWith(`..`)&&!d.isAbsolute(n)}async function ib(e,t){let n=e;for(;d.dirname(n)!==n;)try{let r=await t.realpath(n),i=d.relative(n,e);return d.resolve(r,i)}catch{n=d.dirname(n)}try{return await t.realpath(n)}catch{return d.resolve(e)}}async function ab(e){let t=e.fsAsync??new ku,n=d.resolve(e.activeRepositoryRoot);tb(`activeRepositoryRoot`,n);let r=e.storageRoot===void 0?d.join(e.homeDir??nb(),`.robota`):e.storageRoot;tb(`userLocalStorageRoot`,r);let i=d.resolve(r),a=await ib(i,t);if(rb(await ib(n,t),a))throw Error(`User-local storage root must be outside the active repository: ${i}`);return i}function ob(e,t){return d.join(e,t)}async function sb(e,t,n){let r=ob(e,t),i;try{i=await n.readdir(r,{withFileTypes:!0})}catch{return[]}return(await Promise.all(i.map(async i=>{let a=d.join(r,i.name),o=await n.stat(a),s=i.name;return{root:e,category:t,key:s,summary:`${t}/${s}`,source:`user-local-storage`,scope:`user`,storageLocation:a,createdAt:eb(new Date(o.birthtimeMs)),lastUsedAt:eb(new Date(o.mtimeMs)),enabled:!0,deleteAvailable:!0,disableAvailable:!1}}))).sort((e,t)=>e.key.localeCompare(t.key))}async function cb(e){let t=e.fsAsync??new ku,n=await ab(e),r=d.resolve(e.activeRepositoryRoot),i=e.createDirectories??!0;return i&&await t.mkdir(n,{recursive:!0}),{root:n,activeRepositoryRoot:r,categories:await Promise.all($y.map(async e=>{let r=ob(n,e.category);i&&await t.mkdir(r,{recursive:!0});let a=await sb(n,e.category,t);return{category:e.category,purpose:e.purpose,mayExecuteCommands:e.mayExecuteCommands,storageLocation:r,itemCount:a.length,items:a}})),generatedAt:eb((e.now??(()=>new Date))())}}const lb=[`view-preference`,`last-visible-cwd`,`background-selection`,`task-association`,`display-preference`,`inspection-choice`],ub=`.json`,db=/^[a-z0-9][a-z0-9._-]*$/u,fb={"view-preference":`May affect UI panel, filter, density, or sorting display/navigation only.`,"last-visible-cwd":`May display or preselect an already visible workspace context only.`,"background-selection":`May restore the selected background entry in local UI only.`,"task-association":`May group visible tasks by a local association only.`,"display-preference":`May affect local text wrapping, compactness, or visibility only.`,"inspection-choice":`May affect inspection display choices only.`};function pb(e){return e.toISOString()}function mb(e){return lb.includes(e)}function hb(e){if(!mb(e))throw Error(`Unsupported user-local memory category: ${e}`);return e}function gb(e,t){let n=t.trim();if(n.length===0)throw Error(`${e} must not be empty.`);if(n.length>80||!db.test(n))throw Error(`${e} must use lowercase letters, numbers, dots, underscores, or hyphens: ${t}`);return n}function _b(e,t,n){let r=t.trim().replace(/\s+/g,` `);if(r.length===0)throw Error(`${e} must not be empty.`);return r.length>n?r.slice(0,n):r}function vb(e){return _b(`value`,e,240)}function yb(e,t){return`${e}__${t}${ub}`}async function bb(e){let t=await ab(e);return{root:t,memoryRoot:d.join(t,`memory-projections`)}}function xb(e,t){let n=JSON.parse(e),r=Sb(n,`category`);if(n.schemaVersion!==1)throw Error(`Unsupported user-local memory schema at ${t}`);return{schemaVersion:1,category:hb(r),key:Sb(n,`key`),value:Sb(n,`value`),summary:Sb(n,`summary`),source:Sb(n,`source`),scope:Sb(n,`scope`),createdAt:Sb(n,`createdAt`),lastUsedAt:Sb(n,`lastUsedAt`),enabled:Cb(n,`enabled`)}}function Sb(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Invalid user-local memory field: ${t}`);return n}function Cb(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Invalid user-local memory field: ${t}`);return n}function wb(e,t,n){return{root:e,category:n.category,key:n.key,summary:n.summary,valueSummary:vb(n.value),source:n.source,scope:n.scope,storageLocation:t,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,enabled:n.enabled,displayNavigationRule:fb[n.category],commandExecutionEffect:`none`,deleteAvailable:!0,disableAvailable:!0}}async function Tb(e,t,n){return wb(e,t,xb(await n.readFile(t,`utf8`),t))}async function Eb(e){let t=hb(e.category),n=gb(`key`,e.key),{root:r,memoryRoot:i}=await bb(e);return{root:r,storageLocation:d.join(i,yb(t,n))}}async function Db(e){let t=e.fsAsync??new ku,n=hb(e.category),r=gb(`key`,e.key),i=_b(`summary`,e.summary,240),a=_b(`source`,e.source,80),o=_b(`scope`,e.scope??`user`,120),s=vb(e.value),c=pb((e.now??(()=>new Date))()),{root:l,memoryRoot:u}=await bb(e),f=d.join(u,yb(n,r)),p=c;try{p=xb(await t.readFile(f,`utf8`),f).createdAt}catch(e){if(e instanceof Error&&e.message.includes(`ENOENT`))p=c;else throw e}let m={schemaVersion:1,category:n,key:r,value:s,summary:i,source:a,scope:o,createdAt:p,lastUsedAt:c,enabled:!0};return await t.mkdir(u,{recursive:!0}),await t.writeFile(f,`${JSON.stringify(m,null,2)}\n`,`utf8`),wb(l,f,m)}async function Ob(e){let t=e.fsAsync??new ku,{root:n,memoryRoot:r}=await bb(e),i;try{i=await t.readdir(r,{withFileTypes:!0})}catch{i=[]}let a=await Promise.all(i.filter(e=>e.isFile()&&e.name.endsWith(ub)).map(e=>Tb(n,d.join(r,e.name),t)));return{root:n,activeRepositoryRoot:d.resolve(e.activeRepositoryRoot),items:a.sort((e,t)=>`${e.category}/${e.key}`.localeCompare(`${t.category}/${t.key}`))}}async function kb(e){let t=e.fsAsync??new ku,{root:n,storageLocation:r}=await Eb(e);return Tb(n,r,t)}async function Ab(e){let t=e.fsAsync??new ku,{root:n,storageLocation:r}=await Eb(e),i={...xb(await t.readFile(r,`utf8`),r),enabled:!1,lastUsedAt:pb((e.now??(()=>new Date))())};return await t.writeFile(r,`${JSON.stringify(i,null,2)}\n`,`utf8`),wb(n,r,i)}async function jb(e){let t=e.fsAsync??new ku,{storageLocation:n}=await Eb(e);return await t.rm(n),{category:e.category,key:e.key,deleted:!0}}function Mb(e){return/^\/\S/.test(e)}function Nb(e){let t=e.slice(1).trim().split(/\s+/);return{name:t[0]??``,args:t.slice(1).filter(e=>e.length>0)}}function Pb(){let e=Wm();return{deleted:Jm(e),path:e}}function Fb(e){try{let t=Ib(e);if(!t)return;let n=A(h(t,`HEAD`),`utf8`).trim();if(!n)return;if(n.startsWith(`ref: `)){let e=n.slice(5).trim();return e.startsWith(`refs/heads/`)?e.slice(11):e}return n.slice(0,7)}catch{return}}function Ib(e){let t=v(e),n=p(t);for(;n!==t;){let e=Lb(h(t,`.git`),t);if(e)return e;t=n,n=p(t)}return Lb(h(t,`.git`),t)}function Lb(e,t){if(!E(e))return;let n=D(e);if(n.isDirectory())return e;if(!n.isFile())return;let r=A(e,`utf8`).trim();if(!r.startsWith(`gitdir:`))return;let i=r.slice(7).trim();return m(i)?i:v(t,i)}function Rb(e,t){let n=Bb(e),r=Bb(t);if(n===void 0||r===void 0)return Math.sign(e.localeCompare(t));let i=Hb(n.major,r.major)||Hb(n.minor,r.minor)||Hb(n.patch,r.patch);return i===0?Ub(n.prerelease,r.prerelease):i}function zb(e,t){return Rb(e,t)>0}function Bb(e){let[t,n]=(e.trim().replace(/^v/,``).split(`+`)[0]??``).split(`-`,2),[r,i,a]=t.split(`.`),o=Vb(r),s=Vb(i),c=Vb(a);if(!(o===void 0||s===void 0||c===void 0))return{major:o,minor:s,patch:c,prerelease:n?n.split(`.`):[]}}function Vb(e){if(!(e===void 0||!/^\d+$/.test(e)))return Number(e)}function Hb(e,t){return Math.sign(e-t)}function Ub(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1){let n=e[r],i=t[r];if(n===void 0)return-1;if(i===void 0)return 1;let a=Wb(n,i);if(a!==0)return a}return 0}function Wb(e,t){let n=Vb(e),r=Vb(t);return n!==void 0&&r!==void 0?Hb(n,r):n===void 0?r===void 0?Math.sign(e.localeCompare(t)):1:-1}function Gb(e){let t=p(ke(e)),n=[h(t,`..`,`..`,`package.json`),h(t,`..`,`package.json`)];for(let e of n)try{let t=A(e,`utf-8`),n=JSON.parse(t);if(n.version!==void 0&&n.name!==void 0)return n.version}catch{continue}return`0.0.0`}function Kb(e=process.env.HOME??process.env.USERPROFILE??`/`){return h(e,`.robota`,`update-check.json`)}function qb(e){if(E(e))try{return cx(JSON.parse(A(e,`utf8`)))}catch{return}}function Jb(e,t){O(p(e),{recursive:!0}),ae(e,JSON.stringify(t,null,2)+`
162
162
  `,`utf8`)}async function Yb(e){if(e.disabled===!0)return{status:`skipped`,reason:`disabled`};let t=e.packageName??`@robota-sdk/agent-cli`,n=e.cachePath??Kb(),r=e.now??new Date,i=e.ttlMs??864e5;if(e.force!==!0){let a=qb(n);if(a!==void 0&&ix(a,r,i,t))return nx(a,e.currentVersion)}let a=await Xb(e,t,n,r);return typeof a==`string`?rx(e.currentVersion,a):a}async function Xb(e,t,n,r){let i=await ax({fetchImpl:e.fetchImpl??fetch,packageName:t,registryUrl:e.registryUrl??`https://registry.npmjs.org`,timeoutMs:e.timeoutMs??1500});return i.ok?(Zb(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,latestVersion:i.version}),i.version):(Zb(n,{packageName:t,checkedAt:r.toISOString(),currentVersion:e.currentVersion,errorMessage:i.errorMessage}),{status:`error`,errorMessage:i.errorMessage})}function Zb(e,t){try{Jb(e,t)}catch{}}async function Qb(e){let t=await Yb(e);return t.status===`update_available`?t.notice:void 0}function $b(e){return e.printMode===!1&&e.disableUpdateCheck===!1}function ex(e){return[`Robota update available: ${e.currentVersion} -> ${e.latestVersion}.`,`Run ${e.installCommand}`].join(` `)}function tx(e){return e.status===`update_available`?ex(e.notice):e.status===`current`?`Robota is up to date (${e.currentVersion}).`:e.status===`skipped`?`Robota update check skipped.`:`Robota update check failed: ${e.errorMessage}`}function nx(e,t){return e.errorMessage===void 0?e.latestVersion===void 0?{status:`error`,errorMessage:`Cached update check has no latest version`}:rx(t,e.latestVersion):{status:`error`,errorMessage:e.errorMessage}}function rx(e,t){return zb(t,e)?{status:`update_available`,notice:{currentVersion:e,latestVersion:t,installCommand:`npm install -g '@robota-sdk/agent-cli@latest'`}}:{status:`current`,currentVersion:e,latestVersion:t}}function ix(e,t,n,r){if(e.packageName!==r)return!1;let i=Date.parse(e.checkedAt);return Number.isFinite(i)?t.getTime()-i<n:!1}async function ax(e){try{return{ok:!0,version:await ox(e)}}catch(e){return{ok:!1,errorMessage:e instanceof Error?e.message:String(e)}}}async function ox(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=sx(e.registryUrl,e.packageName),r=await e.fetchImpl(n,{headers:{accept:`application/json`},signal:t.signal});if(!r.ok)throw Error(`registry responded with HTTP ${r.status}`);let i=(await r.json())[`dist-tags`]?.latest;if(typeof i!=`string`||i.trim().length===0)throw Error(`registry metadata is missing dist-tags.latest`);return i}finally{clearTimeout(n)}}function sx(e,t){return`${e.replace(/\/+$/,``)}/${encodeURIComponent(t)}`}function cx(e){if(!lx(e))return;let t=e;if(typeof t.packageName==`string`&&typeof t.checkedAt==`string`&&typeof t.currentVersion==`string`&&(t.latestVersion===void 0||typeof t.latestVersion==`string`)&&(t.errorMessage===void 0||typeof t.errorMessage==`string`))return{packageName:t.packageName,checkedAt:t.checkedAt,currentVersion:t.currentVersion,...t.latestVersion!==void 0&&{latestVersion:t.latestVersion},...t.errorMessage!==void 0&&{errorMessage:t.errorMessage}}}function lx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ux=class{write(e){process.stdout.write(e)}writeLine(e){process.stdout.write(e+`
163
163
  `)}writeMarkdown(e){process.stdout.write(e)}writeError(e){process.stderr.write(e+`
164
164
  `)}prompt(e){return new Promise(t=>{let n=o.createInterface({input:process.stdin,output:process.stdout,terminal:!1,historySize:0});n.question(e,e=>{n.close(),t(e)})})}async select(e,t=0){for(let n=0;n<e.length;n++){let r=n===t?`>`:` `;process.stdout.write(` ${r} ${n+1}) ${e[n]}\n`)}let n=(await this.prompt(` Choose [1-${e.length}] (default: ${e[t]}): `)).trim().toLowerCase();if(n===``)return t;let r=parseInt(n,10);return!isNaN(r)&&r>=1&&r<=e.length?r-1:t}spinner(e){return{stop(){},update(){}}}};const dx=(e,t=!1)=>new Promise((n,r)=>{process.stdout.write(e);let i=``,a=process.stdin,o=a.isRaw;if(!a.isTTY){r(Error(`Cannot prompt for input: stdin is not a TTY.
@@ -222,15 +222,15 @@ Examples:
222
222
  robota --task-file task.md Run task from file (appended to system prompt)
223
223
  robota -p "Refactor the auth module" --dry-run Plan only, no execution
224
224
  robota --continue Resume the last session
225
- `}function kx(e){if(e===void 0)return;let t=e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:void 0}function Ax(e){if(e!==void 0){if(!Dx.includes(e))throw Error(`Invalid --output-format "${e}". Valid: ${Dx.join(` | `)}`);return e}}function jx(e){if(e!==void 0){if(!Ex.includes(e))throw Error(`Invalid --permission-mode "${e}". Valid: ${Ex.join(` | `)}`);return e}}function Mx(e){if(e===void 0)return;let t=parseInt(e,10);if(isNaN(t)||t<=0)throw Error(`Invalid --max-turns "${e}". Must be a positive integer.`);return t}const Nx={allowPositionals:!0,options:{help:{type:`boolean`,short:`h`,default:!1},p:{type:`boolean`,short:`p`,default:!1},continue:{type:`boolean`,short:`c`,default:!1},resume:{type:`string`,short:`r`},language:{type:`string`},"permission-mode":{type:`string`},"max-turns":{type:`string`},goal:{type:`string`},"goal-max-iterations":{type:`string`},"fork-session":{type:`boolean`,default:!1},name:{type:`string`,short:`n`},"output-format":{type:`string`},format:{type:`string`},summary:{type:`string`},source:{type:`string`},"system-prompt":{type:`string`},"append-system-prompt":{type:`string`},"task-file":{type:`string`},version:{type:`boolean`,default:!1},reset:{type:`boolean`,default:!1},bare:{type:`boolean`,default:!1},"allowed-tools":{type:`string`},"denied-tools":{type:`string`},model:{type:`string`},preset:{type:`string`},"no-session-persistence":{type:`boolean`,default:!1},"json-schema":{type:`string`},configure:{type:`boolean`,default:!1},"configure-provider":{type:`string`},provider:{type:`string`},"session-log":{type:`string`},type:{type:`string`},"base-url":{type:`string`},"api-key":{type:`string`},"api-key-env":{type:`string`},"set-current":{type:`boolean`,default:!1},"settings-scope":{type:`string`},"check-update":{type:`boolean`,default:!1},"disable-update-check":{type:`boolean`,default:!1},"dry-run":{type:`boolean`,default:!1},yes:{type:`boolean`,short:`y`,default:!1}}};function Px(e,t){return{positional:t,help:e.help??!1,printMode:e.p??!1,continueMode:e.continue??!1,resumeId:e.resume,language:e.language,permissionMode:jx(e[`permission-mode`]),maxTurns:Mx(e[`max-turns`]),goal:e.goal,goalMaxIterations:Mx(e[`goal-max-iterations`]),forkSession:e[`fork-session`]??!1,sessionName:e.name,outputFormat:Ax(e[`output-format`]),format:e.format,summary:e.summary,source:e.source,systemPrompt:e[`system-prompt`],appendSystemPrompt:e[`append-system-prompt`],taskFile:e[`task-file`],version:e.version??!1,reset:e.reset??!1,bare:e.bare??!1,allowedTools:e[`allowed-tools`],deniedTools:e[`denied-tools`],model:e.model,preset:e.preset,noSessionPersistence:e[`no-session-persistence`]??!1,jsonSchema:e[`json-schema`],configure:e.configure??!1,configureProvider:e[`configure-provider`],provider:e.provider,sessionLog:e[`session-log`],providerType:e.type,baseURL:e[`base-url`],apiKey:e[`api-key`],apiKeyEnv:e[`api-key-env`],setCurrent:e[`set-current`]??!1,settingsScope:e[`settings-scope`],checkUpdate:e[`check-update`]??!1,disableUpdateCheck:e[`disable-update-check`]??!1,dryRun:e[`dry-run`]??!1,yes:e.yes??!1}}function Fx(){let{values:e,positionals:t}=je(Nx),n=Px(e,t);if(n.printMode){if(n.resumeId===``)throw Error(`Print mode requires an explicit session id: -r <id|name> (the interactive session picker is TUI-only)`);if(n.noSessionPersistence&&(n.continueMode||n.resumeId!==void 0))throw Error(`--no-session-persistence conflicts with -c/-r (resume needs the session store)`)}if(n.dryRun){if(n.permissionMode!==void 0&&n.permissionMode!==`plan`)throw Error(`--dry-run is an alias for --permission-mode plan and conflicts with --permission-mode ${n.permissionMode}`);return{...n,permissionMode:`plan`}}return n}const Ix={id:`default`,title:`Default`,description:`Neutral baseline preset — no overrides; reproduces the standard agent behaviour.`},Lx={id:`autonomous-builder`,title:`Autonomous Builder`,description:`Proactive, self-verifying builder posture — high effort, acts first, dispatches parallel subagents (proactive autonomous-builder persona; original English wording).`,effort:`high`,autonomy:`act-first`,enableParallelSubagents:!0,selfVerification:!0,persona:[`You are a proactive, high-autonomy builder. When you have enough to proceed, proceed and`,`complete the task — act rather than stop to ask. Keep going through the points where a more`,`hesitant assistant would pause for confirmation, and only check in when something is genuinely`,`ambiguous or risky.`,``,`Stay inside the scope of the task. Do the simplest thing that works; do not refactor, add`,`abstractions, or expand scope beyond what was asked. Handle the adjacent detail that the task`,`plainly needs, but resist turning a focused change into a sweeping one.`,``,`After making changes, verify your own work — run the tests, re-read the goal, and confirm the`,`result actually matches what was requested before you call it done.`,``,`Ground your claims in evidence. Before reporting progress, check each claim against an actual`,`tool result from this session; if something is not yet verified, say so plainly rather than`,`implying it is finished.`,``,`Be warm and honest without being sycophantic — tell people what is useful, not just what they`,`want to hear. Stay even-handed and let your conclusions follow from the evidence. When you get`,`something wrong, own it directly, correct it, and move on.`,``,`Lead with the outcome. Report results plainly instead of narrating each step, keep formatting`,`light, and stay concise.`].join(`
225
+ `}function kx(e){if(e===void 0)return;let t=e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:void 0}function Ax(e){if(e!==void 0){if(!Dx.includes(e))throw Error(`Invalid --output-format "${e}". Valid: ${Dx.join(` | `)}`);return e}}function jx(e){if(e!==void 0){if(!Ex.includes(e))throw Error(`Invalid --permission-mode "${e}". Valid: ${Ex.join(` | `)}`);return e}}function Mx(e){if(e===void 0)return;let t=parseInt(e,10);if(isNaN(t)||t<=0)throw Error(`Invalid --max-turns "${e}". Must be a positive integer.`);return t}const Nx={allowPositionals:!0,options:{help:{type:`boolean`,short:`h`,default:!1},p:{type:`boolean`,short:`p`,default:!1},continue:{type:`boolean`,short:`c`,default:!1},resume:{type:`string`,short:`r`},language:{type:`string`},"permission-mode":{type:`string`},"max-turns":{type:`string`},goal:{type:`string`},"goal-max-iterations":{type:`string`},"fork-session":{type:`boolean`,default:!1},name:{type:`string`,short:`n`},"output-format":{type:`string`},format:{type:`string`},summary:{type:`string`},source:{type:`string`},"system-prompt":{type:`string`},"append-system-prompt":{type:`string`},"task-file":{type:`string`},version:{type:`boolean`,default:!1},reset:{type:`boolean`,default:!1},bare:{type:`boolean`,default:!1},"allowed-tools":{type:`string`},"denied-tools":{type:`string`},model:{type:`string`},preset:{type:`string`},"no-session-persistence":{type:`boolean`,default:!1},"json-schema":{type:`string`},configure:{type:`boolean`,default:!1},"configure-provider":{type:`string`},provider:{type:`string`},"session-log":{type:`string`},type:{type:`string`},"base-url":{type:`string`},"api-key":{type:`string`},"api-key-env":{type:`string`},"set-current":{type:`boolean`,default:!1},"settings-scope":{type:`string`},"check-update":{type:`boolean`,default:!1},"disable-update-check":{type:`boolean`,default:!1},"dry-run":{type:`boolean`,default:!1},yes:{type:`boolean`,short:`y`,default:!1}}};function Px(e,t){return{positional:t,help:e.help??!1,printMode:e.p??!1,continueMode:e.continue??!1,resumeId:e.resume,language:e.language,permissionMode:jx(e[`permission-mode`]),maxTurns:Mx(e[`max-turns`]),goal:e.goal,goalMaxIterations:Mx(e[`goal-max-iterations`]),forkSession:e[`fork-session`]??!1,sessionName:e.name,outputFormat:Ax(e[`output-format`]),format:e.format,summary:e.summary,source:e.source,systemPrompt:e[`system-prompt`],appendSystemPrompt:e[`append-system-prompt`],taskFile:e[`task-file`],version:e.version??!1,reset:e.reset??!1,bare:e.bare??!1,allowedTools:e[`allowed-tools`],deniedTools:e[`denied-tools`],model:e.model,preset:e.preset,noSessionPersistence:e[`no-session-persistence`]??!1,jsonSchema:e[`json-schema`],configure:e.configure??!1,configureProvider:e[`configure-provider`],provider:e.provider,sessionLog:e[`session-log`],providerType:e.type,baseURL:e[`base-url`],apiKey:e[`api-key`],apiKeyEnv:e[`api-key-env`],setCurrent:e[`set-current`]??!1,settingsScope:e[`settings-scope`],checkUpdate:e[`check-update`]??!1,disableUpdateCheck:e[`disable-update-check`]??!1,dryRun:e[`dry-run`]??!1,yes:e.yes??!1}}function Fx(){let{values:e,positionals:t}=Ae(Nx),n=Px(e,t);if(n.printMode){if(n.resumeId===``)throw Error(`Print mode requires an explicit session id: -r <id|name> (the interactive session picker is TUI-only)`);if(n.noSessionPersistence&&(n.continueMode||n.resumeId!==void 0))throw Error(`--no-session-persistence conflicts with -c/-r (resume needs the session store)`)}if(n.dryRun){if(n.permissionMode!==void 0&&n.permissionMode!==`plan`)throw Error(`--dry-run is an alias for --permission-mode plan and conflicts with --permission-mode ${n.permissionMode}`);return{...n,permissionMode:`plan`}}return n}const Ix={id:`default`,title:`Default`,description:`Neutral baseline preset — no overrides; reproduces the standard agent behaviour.`},Lx={id:`autonomous-builder`,title:`Autonomous Builder`,description:`Proactive, self-verifying builder posture — high effort, acts first, dispatches parallel subagents (proactive autonomous-builder persona; original English wording).`,effort:`high`,autonomy:`act-first`,enableParallelSubagents:!0,selfVerification:!0,persona:[`You are a proactive, high-autonomy builder. When you have enough to proceed, proceed and`,`complete the task — act rather than stop to ask. Keep going through the points where a more`,`hesitant assistant would pause for confirmation, and only check in when something is genuinely`,`ambiguous or risky.`,``,`Stay inside the scope of the task. Do the simplest thing that works; do not refactor, add`,`abstractions, or expand scope beyond what was asked. Handle the adjacent detail that the task`,`plainly needs, but resist turning a focused change into a sweeping one.`,``,`After making changes, verify your own work — run the tests, re-read the goal, and confirm the`,`result actually matches what was requested before you call it done.`,``,`Ground your claims in evidence. Before reporting progress, check each claim against an actual`,`tool result from this session; if something is not yet verified, say so plainly rather than`,`implying it is finished.`,``,`Be warm and honest without being sycophantic — tell people what is useful, not just what they`,`want to hear. Stay even-handed and let your conclusions follow from the evidence. When you get`,`something wrong, own it directly, correct it, and move on.`,``,`Lead with the outcome. Report results plainly instead of narrating each step, keep formatting`,`light, and stay concise.`].join(`
226
226
  `)},Rx={id:`careful-reviewer`,title:`Careful Reviewer`,description:`Conservative, ask-first reviewing posture — reads and plans before changing, prompts on write/exec, self-verifies, runs focused (no parallel subagents) at high effort.`,effort:`high`,autonomy:`ask-first`,enableParallelSubagents:!1,selfVerification:!0,persona:[`You are a careful, review-oriented assistant. Read and analyse before you change anything —`,`understand the surrounding code and context first, then lay out a short plan for the change and`,`wait for confirmation before you write or run things that have side effects.`,``,`When you propose a change, explain why — the reasoning behind it and the trade-offs against the`,`alternatives you considered, so the choice can be reviewed rather than taken on trust.`,``,`Stay conservative in scope. Make the change that was asked for and the detail it plainly needs;`,`do not widen the blast radius with unrequested refactors or rewrites.`,``,`Ground your claims in evidence. Before reporting progress or completion, check each claim against`,`an actual tool result from this session; if something is not yet verified, say so plainly rather`,`than implying it is done.`,``,`Be warm and honest without being sycophantic — tell people what is useful, not just what they`,`want to hear. Stay even-handed and let your conclusions follow from the evidence. When you get`,`something wrong, own it directly, correct it, and move on.`].join(`
227
227
  `)},zx={id:`neutral-executor`,title:`Neutral Executor`,description:`Thin, steerable executor — follows instructions literally, minimal editorialising, strict scope, terse output; balanced autonomy, no parallel subagents, no self-verification, medium effort for predictable scripted use (neutral-alignment work-style; original English wording).`,effort:`medium`,autonomy:`balanced`,enableParallelSubagents:!1,selfVerification:!1,persona:[`Follow the system and user instructions literally. Do what was asked, the way it was asked, and`,`defer to the given instructions over your own preferences.`,``,`Editorialise as little as possible. Skip unrequested commentary, caveats, and asides — give the`,`result, not a narration of it.`,``,`Stay strictly in scope. Make only the change that was requested and the detail it plainly needs;`,`do not add adjacent refactors, comments, or features that were not asked for.`,``,`Keep output terse. Prefer the shortest response that fully answers, so the result is predictable`,`and easy to consume in a script or pipeline.`].join(`
228
- `)},Bx={"ask-first":`default`,balanced:`default`,"act-first":`acceptEdits`},Vx=`robota-cli`,Hx=[Ix,Lx,Rx,zx],Ux=[];function Wx(){return[...Hx,...Ux]}function Gx(e){let t=new Set(Hx.map(e=>e.id)),n=[],r=[];for(let i of e){if(t.has(i.id)){r.push({id:i.id,reason:`collides with built-in preset`});continue}if(Ux.some(e=>e.id===i.id)){r.push({id:i.id,reason:`duplicate preset id`});continue}Ux.push(i),n.push(i.id)}return{registered:n,rejected:r}}function Kx(){return Wx().map(({id:e,title:t,description:n})=>({id:e,title:t,description:n}))}function qx(e){return Wx().find(t=>t.id===e)}function Jx(e){let{id:t,title:n,description:r,...i}=e;return i}function Yx(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Xx(e,t){return t?{...e,...Yx(t)}:e}function Zx(e,t={}){let n=qx(e);if(!n){let t=Wx().map(e=>e.id).join(`, `);throw Error(`Unknown preset: "${e}". Available presets: ${t}.`)}let r=Jx(n);return r=Xx(r,t.cliOverrides),r=Xx(r,t.explicit),Qx(r)}function Qx(e){return e.permissionMode===void 0?e.defaultPermissionMode===void 0?e.autonomy===void 0?e:{...e,permissionMode:Bx[e.autonomy]}:{...e,permissionMode:e.defaultPermissionMode}:e}const $x=[`low`,`medium`,`high`,`xhigh`,`max`],eS=[`ask-first`,`act-first`,`balanced`],tS=[`plan`,`default`,`acceptEdits`,`bypassPermissions`],nS=[`safe`,`moderate`,`full`];function rS(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iS(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function aS(e,t){let n=[[`persona`,e.persona,e=>t.persona=e],[`systemPrompt`,e.systemPrompt,e=>t.systemPrompt=e],[`appendSystemPrompt`,e.appendSystemPrompt,e=>t.appendSystemPrompt=e],[`agentName`,e.agentName,e=>t.agentName=e],[`model`,e.model,e=>t.model=e],[`language`,e.language,e=>t.language=e]];for(let[e,t,r]of n)if(t!==void 0){if(typeof t!=`string`)return`${e}: expected a string`;r(t)}}function oS(e,t){let n=[[`temperature`,e.temperature,e=>t.temperature=e],[`maxOutputTokens`,e.maxOutputTokens,e=>t.maxOutputTokens=e]];for(let[e,t,r]of n)if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))return`${e}: expected a number`;r(t)}let r=[[`enableParallelSubagents`,e.enableParallelSubagents,e=>t.enableParallelSubagents=e],[`selfVerification`,e.selfVerification,e=>t.selfVerification=e]];for(let[e,t,n]of r)if(t!==void 0){if(typeof t!=`boolean`)return`${e}: expected a boolean`;n(t)}}function sS(e,t){if(e.effort!==void 0){if(!$x.includes(e.effort))return`effort: expected one of ${$x.join(`, `)}`;t.effort=e.effort}if(e.autonomy!==void 0){if(!eS.includes(e.autonomy))return`autonomy: expected one of ${eS.join(`, `)}`;t.autonomy=e.autonomy}let n=[[`permissionMode`,e.permissionMode,e=>t.permissionMode=e],[`defaultPermissionMode`,e.defaultPermissionMode,e=>t.defaultPermissionMode=e]];for(let[e,t,r]of n)if(t!==void 0){if(!tS.includes(t))return`${e}: expected one of ${tS.join(`, `)}`;r(t)}if(e.defaultTrustLevel!==void 0){if(!nS.includes(e.defaultTrustLevel))return`defaultTrustLevel: expected one of ${nS.join(`, `)}`;t.defaultTrustLevel=e.defaultTrustLevel}}function cS(e,t){let n=[[`allowedTools`,e.allowedTools,e=>t.allowedTools=e],[`deniedTools`,e.deniedTools,e=>t.deniedTools=e],[`enabledCommandModules`,e.enabledCommandModules,e=>t.enabledCommandModules=e],[`disabledCommandModules`,e.disabledCommandModules,e=>t.disabledCommandModules=e]];for(let[e,t,r]of n)if(t!==void 0){if(!iS(t))return`${e}: expected an array of strings`;r(t)}}function lS(e){if(!rS(e))return{ok:!1,error:`preset: expected a non-null object`};let t=[[`id`,e.id],[`title`,e.title],[`description`,e.description]];for(let[e,n]of t)if(typeof n!=`string`||n.length===0)return{ok:!1,error:`${e}: expected a non-empty string`};let n={},r=aS(e,n)??oS(e,n)??sS(e,n)??cS(e,n);return r===void 0?{ok:!0,preset:{id:e.id,title:e.title,description:e.description,...n}}:{ok:!1,error:r}}function uS(){return h(x(),`.robota`,`presets`)}function dS(e){if(!T(e))return{loaded:[],errors:[]};let t=[],n=[],r=new Map,i=ne(e).filter(e=>e.endsWith(`.json`));for(let a of i){let i=h(e,a),o;try{o=JSON.parse(O(i,`utf8`))}catch(e){t.push({file:a,error:e instanceof Error?e.message:String(e)});continue}let s=lS(o);if(!s.ok){t.push({file:a,error:s.error});continue}n.push(s.preset),r.set(s.preset.id,a)}let a=Gx(n);for(let e of a.rejected)t.push({file:r.get(e.id)??e.id,error:e.reason});return{loaded:a.registered,errors:t}}function fS(e){return dS(e?.dir??uS())}function pS(e,t){return e.preset??t??`default`}function mS(e){return{...e.model===void 0?{}:{model:e.model},...e.systemPrompt===void 0?{}:{systemPrompt:e.systemPrompt},...e.appendSystemPrompt===void 0?{}:{appendSystemPrompt:e.appendSystemPrompt},...e.language===void 0?{}:{language:e.language},...e.permissionMode===void 0?{}:{permissionMode:e.permissionMode}}}function hS(e,t){return Zx(pS(e,t),{cliOverrides:mS(e)})}function gS(e){if(!e.parts||e.parts.length===0)return[{type:`text`,text:e.content||``}];let t=[];for(let n of e.parts)n.type===`text`?t.push({type:`text`,text:n.text}):n.type===`image_inline`?t.push({type:`image`,source:{type:`base64`,media_type:n.mimeType,data:n.data}}):n.type===`image_uri`&&t.push({type:`image`,source:{type:`url`,url:n.uri}});return t}function _S(e){return e.map(e=>{if(e.role===`user`){let t=e;return t.parts&&t.parts.length>0?{role:`user`,content:gS(t)}:{role:`user`,content:e.content||``}}else if(e.role===`assistant`){let t=e;if(t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:`text`,text:t.content});for(let n of t.toolCalls)e.push({type:`tool_use`,id:n.id,name:n.function.name,input:JSON.parse(n.function.arguments)});return{role:`assistant`,content:e}}return{role:`assistant`,content:t.content||``}}else if(e.role===`tool`)return{role:`user`,content:[{type:`tool_result`,tool_use_id:e.toolCallId??``,content:e.content||``}]};else return{role:`user`,content:e.content||``}})}function vS(e){if(!Array.isArray(e.content))return``;let t=e.content.filter(e=>e.type===`web_search_result`&&`title`in e&&`url`in e).map((e,t)=>`${t+1}. ${e.title}\n ${e.url}`).join(`
229
- `);return t?`[Web Search Results]\n${t}`:``}function yS(e){return e.map(e=>({name:e.name,description:e.description,input_schema:e.parameters}))}function bS(e){return e===`auto`?{type:`auto`}:e===`none`?{type:`none`}:e===`required`?{type:`any`}:{type:`tool`,name:e.tool}}async function xS(e,t,n,r,i,a){let o={...t,stream:!0};a?.({provider:`anthropic`,apiSurface:`anthropic-messages`,payloadKind:`request`,payload:o});let s=await e.messages.create(o,i?{signal:i}:void 0),c=[],u=[],d=``,f=``,p=``,m={input_tokens:0,output_tokens:0},h=``,g=null;try{let e=0;for await(let t of CS(s,i))switch(a?.({provider:`anthropic`,apiSurface:`anthropic-messages`,payloadKind:`stream_event`,sequence:e,payload:t}),e++,t.type){case`message_start`:m=t.message.usage,h=t.message.model;break;case`content_block_start`:if(t.content_block.type===`tool_use`)d=t.content_block.id,f=t.content_block.name,p=``;else if(t.content_block.type===`server_tool_use`){let e=t.content_block,i=e.input?.query??``,a=i?`\n🔍 Searching: "${i}"\n`:`\n🔍 [${e.name??`server_tool`}]\n`;c.push(a),n(a),r&&r(e.name??`server_tool`,{query:i})}else if(t.content_block.type===`web_search_tool_result`){let e=t.content_block,r=vS(e);r&&(c.push(`\n${r}\n\n`),n(`\n${r}\n\n`))}break;case`content_block_delta`:t.delta.type===`text_delta`?(c.push(t.delta.text),n(t.delta.text)):t.delta.type===`input_json_delta`&&(p+=t.delta.partial_json);break;case`content_block_stop`:d&&(u.push({id:d,type:`function`,function:{name:f,arguments:p||`{}`}}),d=``,f=``,p=``);break;case`message_delta`:t.usage&&(m.output_tokens=t.usage.output_tokens),g=t.delta.stop_reason;break}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return SS(c,u,m,h);throw e}if(i?.aborted)return SS(c,u,m,h);let _=c.join(``)||``,v={id:l(),role:`assistant`,content:_,state:`complete`,timestamp:new Date,...u.length>0&&{toolCalls:u}};return v.metadata={inputTokens:m.input_tokens,outputTokens:m.output_tokens,model:h},g&&(v.metadata.stopReason=g),v}function SS(e,t,n,r){let i=e.join(``)||``,a={id:l(),role:`assistant`,content:i,state:`complete`,timestamp:new Date,...t.length>0&&{toolCalls:t}};return a.metadata={inputTokens:n.input_tokens,outputTokens:n.output_tokens,model:r,stopReason:`aborted`},a}async function*CS(e,t){for await(let n of e){if(t?.aborted)break;yield n}}var wS=class extends Ft{name=`anthropic`;version=`1.0.0`;client;options;enableWebTools=!1;onTextDelta;onServerToolUse;constructor(e){if(super(),this.options=e,e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client;else if(e.apiKey)this.client=new Me({apiKey:e.apiKey,...e.timeout&&{timeout:e.timeout},...e.baseURL&&{baseURL:e.baseURL}});else throw new W(`Either Anthropic client, apiKey, or executor is required`)}async chat(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)return this.executeViaExecutorOrDirect(e,t);if(!this.client)throw Error(`Anthropic client not available. Either provide a client/apiKey or use an executor.`);let n=e.filter(e=>e.role===`system`),r=_S(e.filter(e=>e.role!==`system`)),i=n.map(e=>e.content||``).join(`
228
+ `)},Bx={"ask-first":`default`,balanced:`default`,"act-first":`acceptEdits`},Vx=`robota-cli`,Hx=[Ix,Lx,Rx,zx],Ux=[];function Wx(){return[...Hx,...Ux]}function Gx(e){let t=new Set(Hx.map(e=>e.id)),n=[],r=[];for(let i of e){if(t.has(i.id)){r.push({id:i.id,reason:`collides with built-in preset`});continue}if(Ux.some(e=>e.id===i.id)){r.push({id:i.id,reason:`duplicate preset id`});continue}Ux.push(i),n.push(i.id)}return{registered:n,rejected:r}}function Kx(){return Wx().map(({id:e,title:t,description:n})=>({id:e,title:t,description:n}))}function qx(e){return Wx().find(t=>t.id===e)}function Jx(e){let{id:t,title:n,description:r,...i}=e;return i}function Yx(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Xx(e,t){return t?{...e,...Yx(t)}:e}function Zx(e,t={}){let n=qx(e);if(!n){let t=Wx().map(e=>e.id).join(`, `);throw Error(`Unknown preset: "${e}". Available presets: ${t}.`)}let r=Jx(n);return r=Xx(r,t.cliOverrides),r=Xx(r,t.explicit),Qx(r)}function Qx(e){return e.permissionMode===void 0?e.defaultPermissionMode===void 0?e.autonomy===void 0?e:{...e,permissionMode:Bx[e.autonomy]}:{...e,permissionMode:e.defaultPermissionMode}:e}const $x=[`low`,`medium`,`high`,`xhigh`,`max`],eS=[`ask-first`,`act-first`,`balanced`],tS=[`plan`,`default`,`acceptEdits`,`bypassPermissions`],nS=[`safe`,`moderate`,`full`];function rS(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iS(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function aS(e,t){let n=[[`persona`,e.persona,e=>t.persona=e],[`systemPrompt`,e.systemPrompt,e=>t.systemPrompt=e],[`appendSystemPrompt`,e.appendSystemPrompt,e=>t.appendSystemPrompt=e],[`agentName`,e.agentName,e=>t.agentName=e],[`model`,e.model,e=>t.model=e],[`language`,e.language,e=>t.language=e]];for(let[e,t,r]of n)if(t!==void 0){if(typeof t!=`string`)return`${e}: expected a string`;r(t)}}function oS(e,t){let n=[[`temperature`,e.temperature,e=>t.temperature=e],[`maxOutputTokens`,e.maxOutputTokens,e=>t.maxOutputTokens=e]];for(let[e,t,r]of n)if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))return`${e}: expected a number`;r(t)}let r=[[`enableParallelSubagents`,e.enableParallelSubagents,e=>t.enableParallelSubagents=e],[`selfVerification`,e.selfVerification,e=>t.selfVerification=e]];for(let[e,t,n]of r)if(t!==void 0){if(typeof t!=`boolean`)return`${e}: expected a boolean`;n(t)}}function sS(e,t){if(e.effort!==void 0){if(!$x.includes(e.effort))return`effort: expected one of ${$x.join(`, `)}`;t.effort=e.effort}if(e.autonomy!==void 0){if(!eS.includes(e.autonomy))return`autonomy: expected one of ${eS.join(`, `)}`;t.autonomy=e.autonomy}let n=[[`permissionMode`,e.permissionMode,e=>t.permissionMode=e],[`defaultPermissionMode`,e.defaultPermissionMode,e=>t.defaultPermissionMode=e]];for(let[e,t,r]of n)if(t!==void 0){if(!tS.includes(t))return`${e}: expected one of ${tS.join(`, `)}`;r(t)}if(e.defaultTrustLevel!==void 0){if(!nS.includes(e.defaultTrustLevel))return`defaultTrustLevel: expected one of ${nS.join(`, `)}`;t.defaultTrustLevel=e.defaultTrustLevel}}function cS(e,t){let n=[[`allowedTools`,e.allowedTools,e=>t.allowedTools=e],[`deniedTools`,e.deniedTools,e=>t.deniedTools=e],[`enabledCommandModules`,e.enabledCommandModules,e=>t.enabledCommandModules=e],[`disabledCommandModules`,e.disabledCommandModules,e=>t.disabledCommandModules=e]];for(let[e,t,r]of n)if(t!==void 0){if(!iS(t))return`${e}: expected an array of strings`;r(t)}}function lS(e){if(!rS(e))return{ok:!1,error:`preset: expected a non-null object`};let t=[[`id`,e.id],[`title`,e.title],[`description`,e.description]];for(let[e,n]of t)if(typeof n!=`string`||n.length===0)return{ok:!1,error:`${e}: expected a non-empty string`};let n={},r=aS(e,n)??oS(e,n)??sS(e,n)??cS(e,n);return r===void 0?{ok:!0,preset:{id:e.id,title:e.title,description:e.description,...n}}:{ok:!1,error:r}}function uS(){return h(x(),`.robota`,`presets`)}function dS(e){if(!E(e))return{loaded:[],errors:[]};let t=[],n=[],r=new Map,i=ee(e).filter(e=>e.endsWith(`.json`));for(let a of i){let i=h(e,a),o;try{o=JSON.parse(A(i,`utf8`))}catch(e){t.push({file:a,error:e instanceof Error?e.message:String(e)});continue}let s=lS(o);if(!s.ok){t.push({file:a,error:s.error});continue}n.push(s.preset),r.set(s.preset.id,a)}let a=Gx(n);for(let e of a.rejected)t.push({file:r.get(e.id)??e.id,error:e.reason});return{loaded:a.registered,errors:t}}function fS(e){return dS(e?.dir??uS())}function pS(e,t){return e.preset??t??`default`}function mS(e){return{...e.model===void 0?{}:{model:e.model},...e.systemPrompt===void 0?{}:{systemPrompt:e.systemPrompt},...e.appendSystemPrompt===void 0?{}:{appendSystemPrompt:e.appendSystemPrompt},...e.language===void 0?{}:{language:e.language},...e.permissionMode===void 0?{}:{permissionMode:e.permissionMode}}}function hS(e,t){return Zx(pS(e,t),{cliOverrides:mS(e)})}function gS(e){if(!e.parts||e.parts.length===0)return[{type:`text`,text:e.content||``}];let t=[];for(let n of e.parts)n.type===`text`?t.push({type:`text`,text:n.text}):n.type===`image_inline`?t.push({type:`image`,source:{type:`base64`,media_type:n.mimeType,data:n.data}}):n.type===`image_uri`&&t.push({type:`image`,source:{type:`url`,url:n.uri}});return t}function _S(e){return e.map(e=>{if(e.role===`user`){let t=e;return t.parts&&t.parts.length>0?{role:`user`,content:gS(t)}:{role:`user`,content:e.content||``}}else if(e.role===`assistant`){let t=e;if(t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:`text`,text:t.content});for(let n of t.toolCalls)e.push({type:`tool_use`,id:n.id,name:n.function.name,input:JSON.parse(n.function.arguments)});return{role:`assistant`,content:e}}return{role:`assistant`,content:t.content||``}}else if(e.role===`tool`)return{role:`user`,content:[{type:`tool_result`,tool_use_id:e.toolCallId??``,content:e.content||``}]};else return{role:`user`,content:e.content||``}})}function vS(e){if(!Array.isArray(e.content))return``;let t=e.content.filter(e=>e.type===`web_search_result`&&`title`in e&&`url`in e).map((e,t)=>`${t+1}. ${e.title}\n ${e.url}`).join(`
229
+ `);return t?`[Web Search Results]\n${t}`:``}function yS(e){return e.map(e=>({name:e.name,description:e.description,input_schema:e.parameters}))}function bS(e){return e===`auto`?{type:`auto`}:e===`none`?{type:`none`}:e===`required`?{type:`any`}:{type:`tool`,name:e.tool}}async function xS(e,t,n,r,i,a){let o={...t,stream:!0};a?.({provider:`anthropic`,apiSurface:`anthropic-messages`,payloadKind:`request`,payload:o});let s=await e.messages.create(o,i?{signal:i}:void 0),c=[],u=[],d=``,f=``,p=``,m={input_tokens:0,output_tokens:0},h=``,g=null;try{let e=0;for await(let t of CS(s,i))switch(a?.({provider:`anthropic`,apiSurface:`anthropic-messages`,payloadKind:`stream_event`,sequence:e,payload:t}),e++,t.type){case`message_start`:m=t.message.usage,h=t.message.model;break;case`content_block_start`:if(t.content_block.type===`tool_use`)d=t.content_block.id,f=t.content_block.name,p=``;else if(t.content_block.type===`server_tool_use`){let e=t.content_block,i=e.input?.query??``,a=i?`\n🔍 Searching: "${i}"\n`:`\n🔍 [${e.name??`server_tool`}]\n`;c.push(a),n(a),r&&r(e.name??`server_tool`,{query:i})}else if(t.content_block.type===`web_search_tool_result`){let e=t.content_block,r=vS(e);r&&(c.push(`\n${r}\n\n`),n(`\n${r}\n\n`))}break;case`content_block_delta`:t.delta.type===`text_delta`?(c.push(t.delta.text),n(t.delta.text)):t.delta.type===`input_json_delta`&&(p+=t.delta.partial_json);break;case`content_block_stop`:d&&(u.push({id:d,type:`function`,function:{name:f,arguments:p||`{}`}}),d=``,f=``,p=``);break;case`message_delta`:t.usage&&(m.output_tokens=t.usage.output_tokens),g=t.delta.stop_reason;break}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return SS(c,u,m,h);throw e}if(i?.aborted)return SS(c,u,m,h);let _=c.join(``)||``,v={id:l(),role:`assistant`,content:_,state:`complete`,timestamp:new Date,...u.length>0&&{toolCalls:u}};return v.metadata={inputTokens:m.input_tokens,outputTokens:m.output_tokens,model:h},g&&(v.metadata.stopReason=g),v}function SS(e,t,n,r){let i=e.join(``)||``,a={id:l(),role:`assistant`,content:i,state:`complete`,timestamp:new Date,...t.length>0&&{toolCalls:t}};return a.metadata={inputTokens:n.input_tokens,outputTokens:n.output_tokens,model:r,stopReason:`aborted`},a}async function*CS(e,t){for await(let n of e){if(t?.aborted)break;yield n}}var wS=class extends Ft{name=`anthropic`;version=`1.0.0`;client;options;enableWebTools=!1;onTextDelta;onServerToolUse;constructor(e){if(super(),this.options=e,e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client;else if(e.apiKey)this.client=new je({apiKey:e.apiKey,...e.timeout&&{timeout:e.timeout},...e.baseURL&&{baseURL:e.baseURL}});else throw new W(`Either Anthropic client, apiKey, or executor is required`)}async chat(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)return this.executeViaExecutorOrDirect(e,t);if(!this.client)throw Error(`Anthropic client not available. Either provide a client/apiKey or use an executor.`);let n=e.filter(e=>e.role===`system`),r=_S(e.filter(e=>e.role!==`system`)),i=n.map(e=>e.content||``).join(`
230
230
 
231
- `)||void 0;if(!t?.model)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let a=t?.tools?yS(t.tools):[],o=this.enableWebTools?[{type:`web_search_20250305`,name:`web_search`}]:[],s=[...a,...o],c={model:t.model,messages:r,max_tokens:t?.maxTokens||Xn(t.model),...i&&{system:i},...t?.temperature!==void 0&&{temperature:t.temperature},...s.length>0&&{tools:s},...s.length>0&&t?.toolChoice!==void 0&&{tool_choice:bS(t.toolChoice)},...TS(t)},l=t?.onTextDelta??this.onTextDelta??(()=>{});try{return await xS(this.client,c,l,this.onServerToolUse,t?.signal,t?.onProviderNativeRawPayload)}catch(e){let t=e;throw t.status===429||t.error?.type===`rate_limit_error`?new cn(t.message??`Anthropic rate limit exceeded.`,void 0,`anthropic`):e}}async*chatStream(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor){yield*this.executeStreamViaExecutorOrDirect(e,t);return}if(!this.client)throw Error(`Anthropic client not available. Either provide a client/apiKey or use an executor.`);let n=_S(e);if(!t?.model)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let r={model:t.model,messages:n,max_tokens:t?.maxTokens||Xn(t.model),stream:!0,...TS(t)};t?.temperature!==void 0&&(r.temperature=t.temperature);let i=t?.tools?yS(t.tools):[],a=this.enableWebTools?[{type:`web_search_20250305`,name:`web_search`}]:[],o=[...i,...a];o.length>0&&(r.tools=o,t?.toolChoice!==void 0&&(r.tool_choice=bS(t.toolChoice))),t?.onProviderNativeRawPayload?.({provider:`anthropic`,apiSurface:`anthropic-messages`,payloadKind:`request`,payload:r});let s;try{s=await this.client.messages.create(r)}catch(e){let t=e;throw t.status===429||t.error?.type===`rate_limit_error`?new cn(t.message??`Anthropic rate limit exceeded.`,void 0,`anthropic`):e}let c=0;for await(let e of s)t?.onProviderNativeRawPayload?.({provider:`anthropic`,apiSurface:`anthropic-messages`,payloadKind:`stream_event`,sequence:c,payload:e}),c++,e.type===`content_block_delta`&&e.delta.type===`text_delta`&&(yield{id:l(),role:`assistant`,content:e.delta.text,state:`complete`,timestamp:new Date})}supportsTools(){return!0}getCapabilities(){return{functionCalling:{supported:!0},nativeWebTools:{webSearch:this.enableWebTools?{supported:!0,enabled:!0,source:`anthropic-messages`}:{supported:!0,enabled:!1,source:`anthropic-messages`,reason:`Call configureNativeWebTools({ webSearch: true }) or set enableWebTools.`},webFetch:{supported:!1,enabled:!1,source:`anthropic-messages`,reason:`Anthropic provider exposes server web search only.`}}}}configureNativeWebTools(e){return e.webSearch===!0&&(this.enableWebTools=!0),this.validateNativeWebTools(e),this.getCapabilities()}validateConfig(){return!!this.client&&!!this.options&&!!this.options.apiKey}async dispose(){}validateMessages(e){if(!Array.isArray(e))throw new G(`Messages must be an array`,`messages`);if(e.length===0)throw new G(`Messages array cannot be empty`,`messages`);for(let t of e)if(!t.role||![`user`,`assistant`,`system`,`tool`].includes(t.role))throw new G(`Invalid message role: ${t.role}`,`role`)}};function TS(e){return e?.responseFormat?.type===`json_schema`?{output_config:{format:{type:`json_schema`,schema:ES(e.responseFormat.schema)}}}:{}}function ES(e){if(Array.isArray(e))return e.map(ES);if(typeof e!=`object`||!e)return e;let t=e,n={...t};return t.properties&&typeof t.properties==`object`&&(n.properties=Object.fromEntries(Object.entries(t.properties).map(([e,t])=>[e,ES(t)]))),t.items&&typeof t.items==`object`&&(n.items=ES(t.items)),t.additionalProperties&&typeof t.additionalProperties==`object`?n.additionalProperties=ES(t.additionalProperties):t.type===`object`&&(n.additionalProperties=!1),n}async function DS(e,t=AS){return OS(e,t)}async function OS(e,t){let n=await t(`https://api.anthropic.com/v1/models`,kS(e.apiKey)).catch(e=>({ok:!1,status:0,json:()=>Promise.resolve({data:[]}),errorMessage:`Anthropic model refresh failed: ${e instanceof Error?e.message:String(e)}`}));if(`errorMessage`in n)return{status:`unavailable`,sourceUrl:NS,message:n.errorMessage};if(!n.ok)return{status:`unavailable`,sourceUrl:NS,message:`Anthropic model refresh failed: HTTP ${n.status}`};let r=await n.json(),i=new Date().toISOString(),a=(r.data??[]).filter(e=>typeof e.id==`string`&&e.id.length>0).map(e=>({id:e.id,displayName:e.display_name??e.id,lifecycle:`active`,sourceUrl:NS,lastVerifiedAt:i}));return{status:`live`,sourceUrl:NS,lastVerifiedAt:PS,entries:a,message:`Fetched ${a.length} models from Anthropic API`}}function kS(e){if(e)return{headers:{"x-api-key":e,"anthropic-version":`2023-06-01`}}}async function AS(e,t){let n=await fetch(e,{...t?.headers!==void 0&&{headers:t.headers}});return{ok:n.ok,status:n.status,json:()=>n.json()}}const jS=`claude-sonnet-4-6`,MS=`$ENV:ANTHROPIC_API_KEY`,NS=`https://platform.claude.com/docs/en/api/models/list`,PS=`2026-05-04`,FS=[{kind:`api-key`,label:`Anthropic API keys`,url:`https://platform.claude.com/settings/keys`,sourceUrl:`https://platform.claude.com/docs/en/api/overview`,lastVerifiedAt:`2026-05-08`}];function IS(){return{type:`anthropic`,displayName:`Anthropic`,description:`Claude series — strong at coding tasks. API key required.`,category:`cloud-paid`,defaults:{model:jS,apiKey:MS},modelCatalog:{status:`fallback`,sourceUrl:NS,lastVerifiedAt:PS,entries:LS()},setupHelpLinks:FS,setupSteps:[{key:`apiKey`,title:`Anthropic API key`,defaultValue:MS,masked:!0},{key:`model`,title:`Anthropic model`,defaultValue:jS}],refreshModelCatalog:({profile:e})=>DS(e),modelCatalogCacheTtlSeconds:86400,requiresApiKey:!0,createProvider:e=>new wS({apiKey:RS(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},defaultModel:e.model})}}function LS(){let e=new Set,t=[];for(let n of Object.values(Jn))e.has(n.name)||(e.add(n.name),t.push({id:n.id,displayName:n.name,contextWindow:n.contextWindow,capabilities:[`tools`,`vision`,`json_schema`,`reasoning`,`streaming`],lifecycle:`active`,sourceUrl:NS,lastVerifiedAt:PS}));return t}function RS(e){if(!e)throw Error(`Provider anthropic requires apiKey`);return e}function zS(e){return e.map(e=>HS(e))}function BS(e){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function VS(e){if(!e.parts||e.parts.length===0||!e.parts.some(e=>e.type===`image_inline`||e.type===`image_uri`))return e.content||``;let t=[];for(let n of e.parts)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`image_inline`){let e=n;t.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}else if(n.type===`image_uri`){let e=n;t.push({type:`image_url`,image_url:{url:e.uri}})}return t.length===0?e.content||``:t}function HS(e){if(e.role===`user`)return{role:`user`,content:VS(e)};if(e.role===`assistant`)return US(e);if(e.role===`system`)return{role:`system`,content:e.content||``};if(e.role===`tool`){if(!e.toolCallId||e.toolCallId.trim().length===0)throw Error(`Tool message missing toolCallId: ${JSON.stringify(e)}`);return{role:`tool`,content:e.content||``,tool_call_id:e.toolCallId}}throw Error(`Unsupported message role: ${JSON.stringify(e)}`)}function US(e){return e.toolCalls&&e.toolCalls.length>0?{role:`assistant`,content:e.content===``?null:e.content||null,tool_calls:e.toolCalls.map(e=>({id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments}}))}:{role:`assistant`,content:e.content===null?null:e.content||``}}var WS=class{logger;textProjector;toolCallTextProjector;constructor(e={}){this.logger=e.logger??kt,this.textProjector=e.textProjector,this.toolCallTextProjector=e.toolCallTextProjector}parseResponse(e){try{let t=e.choices?.[0];if(!t)throw Error(`No choices found in OpenAI-compatible response`);return this.parseChoice(t,e.usage)}catch(e){let t=e instanceof Error?e.message:`OpenAI-compatible response parsing failed`;throw this.logger.error(`Response parsing failed`,{error:t}),Error(`OpenAI-compatible response parsing failed: ${t}`)}}parseChoice(e,t){let n=e.message,r=this.projectToolCallText(n.content||``),i=this.toolCallTextProjector?.flush(),a=this.parseNativeToolCalls(n),o=[...r.toolCalls,...i?.toolCalls??[]],s=[...a,...o];return{id:l(),state:`complete`,role:`assistant`,content:this.projectText(r.visibleText+(i?.visibleText??``)),timestamp:new Date,...s.length>0&&{toolCalls:s},...t&&{usage:this.parseUsage(t)},metadata:{finishReason:e.finish_reason||void 0,...this.buildToolTextMetadata(r,i)}}}parseNativeToolCalls(e){return e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments}}))||[]}parseUsage(e){return{promptTokens:e.prompt_tokens,completionTokens:e.completion_tokens,totalTokens:e.total_tokens}}parseStreamingChunk(e){try{let t=e.usage?this.parseUsage(e.usage):void 0,n=e.choices?.[0];if(!n)return t?{id:l(),state:`complete`,role:`assistant`,content:``,timestamp:new Date,usage:t,metadata:{isStreamChunk:!0,isComplete:!0}}:null;let r=n.finish_reason,i=n.delta.tool_calls?.map(e=>({id:e.id||``,type:`function`,function:{name:e.function?.name||``,arguments:e.function?.arguments||``}}));return i?{id:l(),state:`complete`,role:`assistant`,content:``,timestamp:new Date,toolCalls:i,...t&&{usage:t},metadata:{isStreamChunk:!0,isComplete:r===`stop`||r===`tool_calls`}}:{id:l(),state:`complete`,role:`assistant`,content:this.projectText(n.delta.content||``),timestamp:new Date,...t&&{usage:t},metadata:{isStreamChunk:!0,isComplete:r===`stop`||r===`tool_calls`}}}catch(e){let t=e instanceof Error?e.message:`OpenAI-compatible chunk parsing failed`;throw this.logger.error(`Chunk parsing failed`,{error:t}),Error(`OpenAI-compatible chunk parsing failed: ${t}`)}}projectText(e){return this.textProjector?this.textProjector(e):e}projectToolCallText(e){return this.toolCallTextProjector?.project(e)??{visibleText:e,toolCalls:[],removedToolCallText:!1}}buildToolTextMetadata(e,t){let n=[e.rawToolCallText,t?.rawToolCallText].filter(e=>typeof e==`string`&&e.length>0).join(``);return{...(e.removedToolCallText||(t?.removedToolCallText??!1))&&{toolCallTextProjected:!0},...n.length>0&&{rawToolCallText:n}}}};async function GS(e){let t={textParts:[],toolCallParts:new Map,projectedToolCalls:[],rawToolCallTextParts:[],toolCallTextProjected:!1,model:``,finishReason:null};for await(let n of nC(e.stream,e.signal))KS(t,n,e);return YS(t,e),$S(t,e.metadata)}function KS(e,t,n){t.model&&(e.model=t.model),t.usage&&(e.usage={promptTokens:t.usage.prompt_tokens,completionTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens});let r=t.choices?.[0];r&&(e.finishReason=r.finish_reason??e.finishReason,qS(e,r.delta.content,n),QS(e,r.delta.tool_calls??[]))}function qS(e,t,n){if(!t)return;let r=XS(t,n.toolCallTextProjector);ZS(e,r);let i=JS(r.visibleText,n.textProjector);i.length!==0&&(e.textParts.push(i),n.onTextDelta?.(i))}function JS(e,t){return t?t(e):e}function YS(e,t){let n=t.toolCallTextProjector?.flush();if(n){ZS(e,n);let r=JS(n.visibleText,t.textProjector);r.length>0&&(e.textParts.push(r),t.onTextDelta?.(r))}let r=t.textProjectorFlush?.();r&&(e.textParts.push(r),t.onTextDelta?.(r))}function XS(e,t){return t?.project(e)??{visibleText:e,toolCalls:[],removedToolCallText:!1}}function ZS(e,t){t.toolCalls.length>0&&e.projectedToolCalls.push(...t.toolCalls),t.removedToolCallText&&(e.toolCallTextProjected=!0),t.rawToolCallText&&t.rawToolCallText.length>0&&e.rawToolCallTextParts.push(t.rawToolCallText)}function QS(e,t){for(let n of t){let t=n.index??0,r=e.toolCallParts.get(t)??{id:``,name:``,arguments:``},i=n.function?.name??r.name;e.toolCallParts.set(t,{id:n.id??r.id,name:i,arguments:r.arguments+(n.function?.arguments??``)})}}function $S(e,t={}){let n={...t};e.model&&(n.model=e.model),e.finishReason&&(n.finishReason=e.finishReason),e.toolCallTextProjected&&(n.toolCallTextProjected=!0),e.rawToolCallTextParts.length>0&&(n.rawToolCallText=e.rawToolCallTextParts.join(``));let r=eC(e);return{id:l(),role:`assistant`,content:e.textParts.join(``),state:`complete`,timestamp:new Date,...r.length>0&&{toolCalls:r},...e.usage&&{usage:e.usage},...Object.keys(n).length>0&&{metadata:n}}}function eC(e){return[...tC(e.toolCallParts),...e.projectedToolCalls]}function tC(e){return Array.from(e.entries()).sort(([e],[t])=>e-t).map(([e,t])=>({id:t.id||`call_${e}`,type:`function`,function:{name:t.name,arguments:t.arguments||`{}`}}))}async function*nC(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await rC(n,t);if(e.done||(await iC(t),t?.aborted))break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async function rC(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}async function iC(e){e?.aborted||await new Promise(e=>setTimeout(e,0))}async function*aC(e,t){let n=t.initialSequence??0;for await(let r of e)t.onProviderNativeRawPayload?.({provider:t.provider,...t.apiSurface!==void 0&&{apiSurface:t.apiSurface},payloadKind:`stream_event`,sequence:n,payload:r}),n++,yield r}async function oC(e,t=sC){if(!e.baseURL)return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`};try{let n=await t(`${e.baseURL.replace(/\/$/,``)}/models`);if(!n.ok)return{ok:!1,message:`HTTP ${n.status}`};let r=((await n.json()).data??[]).map(e=>e.id).filter(e=>!!e);return{ok:!0,message:`${r.length} model(s) discovered`,models:r}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}async function sC(e){let t=await fetch(e);return{ok:t.ok,status:t.status,json:()=>t.json()}}function cC(e){return e===void 0||e===`auto`?`auto`:e===`none`||e===`required`?e:{type:`function`,function:{name:e.tool}}}function lC(e){return e===void 0||e===`auto`?`auto`:e===`none`||e===`required`?e:{type:`function`,name:e.tool}}function uC(e){return zS(e)}function dC(e){return BS(e)}function fC(e,t){return t?.type===void 0?e:t.type===`json_schema`?{...e,responseFormat:`json_schema`,jsonSchema:{name:t.name??`structured_output`,schema:t.schema}}:{...e,responseFormat:t.type}}function pC(e){if(e.responseFormat===void 0||e.responseFormat===`text`)return;if(e.responseFormat===`json_object`)return{type:`json_object`};let t=hC(e);return{type:`json_schema`,json_schema:{name:t.name,schema:t.schema,...t.description!==void 0&&{description:t.description},...t.strict!==void 0&&{strict:t.strict}}}}function mC(e){if(e.responseFormat===void 0||e.responseFormat===`text`)return;if(e.responseFormat===`json_object`)return{format:{type:`json_object`}};let t=hC(e);return{format:{type:`json_schema`,name:t.name,schema:t.schema,...t.description!==void 0&&{description:t.description},...t.strict!==void 0&&{strict:t.strict}}}}function hC(e){let t=e.jsonSchema;if(e.responseFormat!==`json_schema`)throw Error(`Unsupported OpenAI response format: ${e.responseFormat}`);if(!t?.schema)throw Error(`OpenAI jsonSchema.schema is required when responseFormat is json_schema`);return{name:t.name,schema:t.schema,...t.description!==void 0&&{description:t.description},...t.strict!==void 0&&{strict:t.strict}}}async function gC(e){let t=SC(e.client);try{let n=yC(e);if(e.chatOptions?.onTextDelta??e.onTextDelta)return await bC(t,e,{...n,stream:!0,...vC(e)});await xC(e,n,`chat`),e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let r=await t.chat.completions.create(n);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`chat-completions`,payloadKind:`response`,payload:r}),e.responseParser.parseResponse(r)}catch(e){let t=e;if(t.status===429)throw new cn(t.message??`OpenAI rate limit exceeded.`,void 0,`openai`);let n=t.message||`OpenAI API request failed`;throw Error(`OpenAI chat failed: ${n}`)}}async function*_C(e){let t=SC(e.client);try{let n={...yC(e),stream:!0,...vC(e)};await xC(e,n,`stream`),e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let r=await t.chat.completions.create(n,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0);for await(let t of aC(r,{provider:`openai`,apiSurface:`chat-completions`,onProviderNativeRawPayload:e.chatOptions?.onProviderNativeRawPayload})){let n=e.responseParser.parseStreamingChunk(t);n&&(yield n)}}catch(e){let t=e;if(t.status===429)throw new cn(t.message??`OpenAI rate limit exceeded.`,void 0,`openai`);let n=t.message||`OpenAI API request failed`;throw Error(`OpenAI stream failed: ${n}`)}}function vC(e){return e.providerOptions.includeStreamUsage===!1?{}:{stream_options:{include_usage:!0}}}function yC(e){let t=uC(e.messages),n=e.chatOptions?.model??e.providerOptions.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let r=pC(fC(e.providerOptions,e.chatOptions?.responseFormat));return{model:n,messages:t,...e.chatOptions?.temperature!==void 0&&{temperature:e.chatOptions.temperature},...e.chatOptions?.maxTokens!==void 0&&{max_tokens:e.chatOptions.maxTokens},...e.chatOptions?.tools&&{tools:dC(e.chatOptions.tools),tool_choice:cC(e.chatOptions.toolChoice)},...r!==void 0&&{response_format:r}}}async function bC(e,t,n){try{return await xC(t,n,`stream`),t.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n}),GS({stream:aC(await e.chat.completions.create(n,t.chatOptions?.signal?{signal:t.chatOptions.signal}:void 0),{provider:`openai`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t.chatOptions?.onProviderNativeRawPayload}),onTextDelta:t.chatOptions?.onTextDelta??t.onTextDelta,signal:t.chatOptions?.signal})}catch(e){let t=e;if(t.status===429)throw new cn(t.message??`OpenAI rate limit exceeded.`,void 0,`openai`);let n=t.message||`OpenAI streaming request failed`;throw Error(`OpenAI stream failed: ${n}`)}}async function xC(e,t,n){if(!e.payloadLogger?.isEnabled())return;let r={model:t.model,messagesCount:t.messages.length,hasTools:!!t.tools,temperature:t.temperature??void 0,maxTokens:t.max_tokens??void 0,timestamp:new Date().toISOString()};await e.payloadLogger.logPayload(r,n)}function SC(e){if(!e)throw Error(`OpenAI client not available. Either provide a client/apiKey or use an executor.`);return e}var CC=class{parser;constructor(e){this.parser=new WS({logger:e})}parseResponse(e){try{return this.parser.parseResponse(e)}catch(e){let t=wC(e instanceof Error?e.message:`OpenAI response parsing failed`);throw Error(`OpenAI response parsing failed: ${t}`)}}parseStreamingChunk(e){try{return this.parser.parseStreamingChunk(e)}catch(e){let t=wC(e instanceof Error?e.message:`OpenAI chunk parsing failed`);throw Error(`OpenAI chunk parsing failed: ${t}`)}}};function wC(e){return e.replace(/^OpenAI-compatible response parsing failed: /,``).replace(/^OpenAI-compatible chunk parsing failed: /,``).replace(`OpenAI-compatible response`,`OpenAI response`)}function TC(e){switch(e){case`low`:return`low`;case`medium`:return`medium`;case`high`:case`xhigh`:case`max`:return`high`;default:return e}}function EC(e,t){return t===void 0?e:{...e,effort:TC(t)}}function DC(e){return e.flatMap(e=>kC(e))}function OC(e,t){let n=e?.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters,strict:t??!1}))??[];return n.length>0?n:void 0}function kC(e){if(e.role===`user`)return[NC(`user`,jC(e.content,e.parts))];if(e.role===`system`)return[NC(`system`,e.content)];if(e.role===`tool`){if(!e.toolCallId||e.toolCallId.trim().length===0)throw Error(`Tool message missing toolCallId: ${JSON.stringify(e)}`);return[{type:`function_call_output`,call_id:e.toolCallId,output:e.content||``}]}return AC(e)}function AC(e){let t=[];e.content&&e.content.length>0&&t.push(NC(`assistant`,e.content));for(let n of e.toolCalls??[])t.push({type:`function_call`,call_id:n.id,name:n.function.name,arguments:n.function.arguments});return t.length===0&&t.push(NC(`assistant`,``)),t}function jC(e,t){if(!t||t.length===0)return e;let n=t.map(e=>MC(e));return e.length>0&&!t.some(e=>e.type===`text`)?[{type:`input_text`,text:e},...n]:n}function MC(e){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_uri`?{type:`input_image`,image_url:e.uri}:{type:`input_image`,image_url:`data:${e.mimeType};base64,${e.data}`}}function NC(e,t){return{role:e,content:t}}async function*PC(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await FC(n,t);if(e.done||t?.aborted)break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async function FC(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}function IC(e){tw(e);let t=e.output??[];return VC({content:e.output_text??qC(t),toolCalls:WC(t),response:e,reasoning:XC(t)})}async function LC(e){let t={textParts:[],toolCalls:[],reasoning:QC()};for await(let n of PC(e.stream,e.signal))RC(t,n,e.onTextDelta);return t.completedResponse===void 0?VC({content:t.textParts.join(``),toolCalls:t.toolCalls,reasoning:t.reasoning}):BC(t)}function RC(e,t,n){if(t.type===`response.output_text.delta`){e.textParts.push(t.delta),n?.(t.delta);return}if(t.type===`response.completed`){e.completedResponse=t.response,$C(e.reasoning,XC(t.response.output??[]));return}if(t.type===`response.output_item.done`){zC(e,t.item);return}if(t.type===`response.error`||t.type===`response.failed`||t.type===`response.incomplete`)throw Error(`OpenAI Responses API failed: ${nw(t)}`)}function zC(e,t){if(GC(t)){e.toolCalls.push(KC(t));return}ZC(t)&&$C(e.reasoning,XC([t]))}function BC(e){let t=e.completedResponse;if(t===void 0)throw Error(`OpenAI Responses stream completed without response metadata`);tw(t);let n=t.output??[],r=WC(n),i=e.textParts.length>0?e.textParts.join(``):t.output_text??qC(n),a=XC(n);return $C(a,e.reasoning),VC({content:i,toolCalls:r.length>0?r:e.toolCalls,response:t,reasoning:a})}function VC(e){return{id:l(),role:`assistant`,content:e.content,state:`complete`,timestamp:new Date,...e.toolCalls.length>0&&{toolCalls:e.toolCalls},...e.response?.usage!==void 0&&{usage:UC(e.response.usage)},metadata:HC(e.response,e.reasoning)}}function HC(e,t){return{providerApiSurface:`responses`,...e?.id!==void 0&&{responseId:e.id},...e?.model!==void 0&&{model:e.model},...e?.status!==void 0&&{finishReason:e.status},...t.reasoningSummaryCount>0&&{reasoningSummaryCount:t.reasoningSummaryCount,reasoningSummaries:t.reasoningSummaries},...t.hasEncryptedReasoning&&{hasEncryptedReasoning:!0}}}function UC(e){return{promptTokens:e.input_tokens??0,completionTokens:e.output_tokens??0,totalTokens:e.total_tokens??0}}function WC(e){return e.filter(GC).map(e=>KC(e))}function GC(e){return e.type===`function_call`&&`call_id`in e&&`name`in e&&`arguments`in e}function KC(e){return{id:e.call_id,type:`function`,function:{name:e.name,arguments:e.arguments}}}function qC(e){return e.filter(YC).flatMap(e=>e.content).map(JC).join(``)}function JC(e){return e.type===`refusal`?e.refusal:e.text}function YC(e){return e.type===`message`&&`content`in e&&Array.isArray(e.content)}function XC(e){let t=QC();for(let n of e){if(!ZC(n))continue;let e=n.summary?.map(e=>e.text).filter(ew)??[];t.reasoningSummaryCount+=e.length,t.reasoningSummaries.push(...e),t.hasEncryptedReasoning=t.hasEncryptedReasoning||!!n.encrypted_content}return t}function ZC(e){return e.type===`reasoning`}function QC(){return{reasoningSummaryCount:0,reasoningSummaries:[],hasEncryptedReasoning:!1}}function $C(e,t){e.reasoningSummaryCount+=t.reasoningSummaryCount,e.reasoningSummaries.push(...t.reasoningSummaries),e.hasEncryptedReasoning=e.hasEncryptedReasoning||t.hasEncryptedReasoning}function ew(e){return e!==void 0}function tw(e){if(e.status===`failed`||e.status===`incomplete`)throw Error(`OpenAI Responses API failed: ${e.error?.message??e.status}`)}function nw(e){return e.message??e.error?.message??e.response?.error?.message??`unknown error`}async function rw(e){let t=e.chatOptions?.onTextDelta??e.onTextDelta;if(t)return aw({...e,chatOptions:{...e.chatOptions,onTextDelta:t}});if(!e.client)throw Error(`OpenAI Responses client not available.`);try{let t=ow(e);e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`responses`,payloadKind:`request`,payload:t});let n=await e.client.responses.create(t,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`responses`,payloadKind:`response`,payload:n}),IC(n)}catch(e){let t=e.message||`OpenAI Responses API request failed`;throw Error(`OpenAI responses failed: ${t}`)}}async function*iw(e){let t={deltas:[]},n=e.chatOptions?.onTextDelta??e.onTextDelta,r=aw({...e,chatOptions:{...e.chatOptions,onTextDelta:e=>{n?.(e),uw(t,cw(e))}}}).then(e=>dw(t,e)).catch(e=>fw(t,gw(e)));yield*lw(t),await r}async function aw(e){if(!e.client)throw Error(`OpenAI Responses client not available.`);try{let t=sw(e);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`responses`,payloadKind:`request`,payload:t}),LC({stream:aC(await e.client.responses.create(t,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0),{provider:`openai`,apiSurface:`responses`,onProviderNativeRawPayload:e.chatOptions?.onProviderNativeRawPayload}),onTextDelta:e.chatOptions?.onTextDelta,signal:e.chatOptions?.signal})}catch(e){let t=e.message||`OpenAI Responses streaming request failed`;throw Error(`OpenAI responses stream failed: ${t}`)}}function ow(e){let t=e.chatOptions?.model??e.providerOptions.defaultModel;if(!t)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let n=OC(e.chatOptions?.tools,e.providerOptions.strictTools),r=mC(e.providerOptions),i=EC(e.providerOptions.reasoning,e.chatOptions?.effort);return{model:t,input:DC(e.messages),...n!==void 0&&{tools:n,tool_choice:lC(e.chatOptions?.toolChoice)},...e.chatOptions?.temperature!==void 0&&{temperature:e.chatOptions.temperature},...e.chatOptions?.maxTokens!==void 0&&{max_output_tokens:e.chatOptions.maxTokens},...r!==void 0&&{text:r},...i!==void 0&&{reasoning:i},...e.providerOptions.includeEncryptedReasoning===!0&&{include:[`reasoning.encrypted_content`]},...e.providerOptions.store!==void 0&&{store:e.providerOptions.store}}}function sw(e){return{...ow(e),stream:!0}}function cw(e){return{id:l(),role:`assistant`,content:e,state:`complete`,timestamp:new Date,metadata:{providerApiSurface:`responses`,isStreamChunk:!0,isComplete:!1}}}async function*lw(e){for(;;){let t=e.deltas.shift();if(t!==void 0){yield t;continue}if(e.error!==void 0)throw e.error;if(e.finalMessage!==void 0){yield hw(e.finalMessage);return}await pw(e)}}function uw(e,t){e.deltas.push(t),mw(e)}function dw(e,t){e.finalMessage=t,mw(e)}function fw(e,t){e.error=t,mw(e)}function pw(e){return new Promise(t=>{e.wake=t})}function mw(e){e.wake?.(),e.wake=void 0}function hw(e){return{...e,content:``,metadata:{...e.metadata,isStreamChunk:!0,isComplete:!0}}}function gw(e){return e instanceof Error?e:Error(String(e))}var _w=class extends Ft{name=`openai`;version=`1.0.0`;client;options;apiSurface;payloadLogger;responseParser;onTextDelta;constructor(e){if(super(e.logger||kt),this.options=e,this.apiSurface=vw(e),bw(this.apiSurface,e.nativeWebTools),e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client;else if(e.apiKey)this.client=new Ne({apiKey:e.apiKey,...e.organization&&{organization:e.organization},...e.timeout&&{timeout:e.timeout},...e.baseURL&&{baseURL:e.baseURL}});else throw Error(`Either OpenAI client, apiKey, or executor is required`);this.responseParser=new CC(this.logger),this.payloadLogger=e.payloadLogger}async chat(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`OpenAI Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}return this.apiSurface===`responses`?rw({client:this.client,messages:e,chatOptions:t,providerOptions:this.options,onTextDelta:this.onTextDelta}):gC({client:this.client,messages:e,chatOptions:t,providerOptions:this.options,payloadLogger:this.payloadLogger,responseParser:this.responseParser,onTextDelta:this.onTextDelta})}async*chatStream(e,t){if(this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`OpenAI Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}if(this.apiSurface===`responses`){yield*iw({client:this.client,messages:e,chatOptions:t,providerOptions:this.options,onTextDelta:this.onTextDelta});return}yield*_C({client:this.client,messages:e,chatOptions:t,providerOptions:this.options,payloadLogger:this.payloadLogger,responseParser:this.responseParser,onTextDelta:this.onTextDelta})}supportsTools(){return!0}getCapabilities(){let e=this.apiSurface===`chat-completions`?`openai-compatible-chat-completions`:`openai-responses`;return{functionCalling:{supported:!0},nativeWebTools:{webSearch:{supported:!1,enabled:!1,source:e,reason:yw(this.apiSurface,`search`)},webFetch:{supported:!1,enabled:!1,source:e,reason:yw(this.apiSurface,`fetch`)}}}}validateConfig(){return!!this.client&&!!this.options}async dispose(){}validateMessages(e){super.validateMessages(e);for(let t of e)if(t.role===`assistant`){let e=t;if(e.toolCalls&&e.toolCalls.length>0&&e.content===``)continue}}};function vw(e){return e.apiSurface===void 0?e.baseURL?`chat-completions`:`responses`:e.apiSurface}function yw(e,t){return e===`chat-completions`?`OpenAI-compatible Chat Completions endpoints support declared function tools, not provider-native web ${t}.`:`OpenAI Responses native web ${t} is not wired in this Robota provider version.`}function bw(e,t){if(!(t?.webSearch!==!0&&t?.webFetch!==!0))throw Error(`Provider openai native web search/fetch is not supported for apiSurface ${e} in this Robota provider version.`)}const xw=`https://platform.openai.com/docs/api-reference/models/list`;async function Sw(e,t={}){if(!e.apiKey)return Ew(`OpenAI model catalog refresh requires apiKey.`);let n=t.fetcher??Dw,r=t.now??(()=>new Date),i=Cw(e.baseURL);try{let t=await n(i,{headers:{Authorization:`Bearer ${e.apiKey}`}});if(!t.ok)return Ew(Tw(t));let a=ww(await t.json());return{status:`live`,entries:a,lastVerifiedAt:r().toISOString(),sourceUrl:xw,message:`${a.length} OpenAI model(s) discovered.`}}catch(e){return Ew(e instanceof Error?e.message:String(e))}}function Cw(e){return e?`${e.replace(/\/$/,``)}/models`:`https://api.openai.com/v1/models`}function ww(e){return(e.data??[]).map(e=>e.id).filter(e=>e!==void 0&&e.trim().length>0).map(e=>({id:e,displayName:e,lifecycle:`active`}))}function Tw(e){let t=e.statusText?` ${e.statusText}`:``;return`OpenAI model catalog refresh failed: HTTP ${e.status}${t}`}function Ew(e){return{status:`unavailable`,sourceUrl:xw,message:e}}async function Dw(e,t){let n=await fetch(e,t);return{ok:n.ok,status:n.status,statusText:n.statusText,json:()=>n.json()}}const Ow=`$ENV:OPENAI_API_KEY`,kw=[{kind:`api-key`,label:`OpenAI API keys`,url:`https://platform.openai.com/api-keys`,sourceUrl:`https://developers.openai.com/api/reference/overview#authentication`,lastVerifiedAt:`2026-05-08`}];function Aw(){return{type:`openai`,displayName:`OpenAI`,description:`GPT series — general-purpose assistant. API key required.`,category:`cloud-paid`,defaults:{apiKey:Ow},modelCatalog:{status:`unavailable`,sourceUrl:`https://platform.openai.com/docs/api-reference/models/list`,message:`OpenAI model availability should be discovered live from GET /v1/models.`},setupHelpLinks:kw,setupSteps:[{key:`model`,title:`OpenAI model`,required:!0},{key:`apiKey`,title:`OpenAI API key`,defaultValue:Ow,masked:!0}],requiresApiKey:!0,probeProfile:oC,refreshModelCatalog:({profile:e})=>Sw(e),modelCatalogCacheTtlSeconds:86400,createProvider:e=>{let t=Mw(e.options),n=Nw(e.options);return Fw(e.baseURL,t,n),new _w({apiKey:jw(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},...t!==void 0&&{apiSurface:t},...n!==void 0&&{nativeWebTools:n},defaultModel:e.model})}}}function jw(e){if(!e)throw Error(`Provider openai requires apiKey`);return e}function Mw(e){let t=e?.apiSurface;if(t===`responses`||t===`chat-completions`)return t}function Nw(e){let t=Pw(e?.nativeWebTools)??Pw(e?.builtInWebTools);if(t!==void 0)return t}function Pw(e){if(e==null||e instanceof Date||Array.isArray(e)||typeof e!=`object`)return;let t=e.webSearch,n=e.webFetch;return{...typeof t==`boolean`&&{webSearch:t},...typeof n==`boolean`&&{webFetch:n}}}function Fw(e,t,n){if(!(n?.webSearch!==!0&&n?.webFetch!==!0))throw Error(e!==void 0||t===`chat-completions`?`Provider openai profile uses an OpenAI-compatible Chat Completions endpoint; native web search/fetch is not supported for this profile. Use Robota local WebSearch/WebFetch tools or a provider with documented hosted web support.`:`Provider openai native web search/fetch is not wired in this Robota provider version. Use Robota local WebSearch/WebFetch tools or a provider with documented hosted web support.`)}const Iw=`deepseek-v4-flash`,Lw=`$ENV:DEEPSEEK_API_KEY`,Rw=`https://api.deepseek.com`;var zw=class extends Ft{name=`deepseek`;version=`1.0.0`;client;options;responseParser;onTextDelta;constructor(e){if(super(e.logger||kt),this.options=e,e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client;else if(e.apiKey)this.client=new Ne({apiKey:e.apiKey,baseURL:e.baseURL??`https://api.deepseek.com`,...e.timeout!==void 0&&{timeout:e.timeout}});else throw Error(`Either DeepSeek client, apiKey, or executor is required`);this.responseParser=new WS({logger:this.logger})}async chat(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`DeepSeek Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}let n=this.getClient();try{let r=this.buildRequestParams(e,t),i=t?.onTextDelta??this.onTextDelta;if(i)return await this.chatWithStreamingAssembly({...r,stream:!0},{...t,onTextDelta:i});t?.onProviderNativeRawPayload?.({provider:`deepseek`,apiSurface:`chat-completions`,payloadKind:`request`,payload:r});let a=await n.chat.completions.create(r);return t?.onProviderNativeRawPayload?.({provider:`deepseek`,apiSurface:`chat-completions`,payloadKind:`response`,payload:a}),this.responseParser.parseResponse(a)}catch(e){let t=e.message||`DeepSeek API request failed`;throw Error(`DeepSeek chat failed: ${t}`)}}async*chatStream(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`DeepSeek Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}let n=this.getClient();try{let r=this.buildStreamingRequestParams(e,t);t?.onProviderNativeRawPayload?.({provider:`deepseek`,apiSurface:`chat-completions`,payloadKind:`request`,payload:r});let i=aC(await n.chat.completions.create(r),{provider:`deepseek`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t?.onProviderNativeRawPayload});for await(let e of this.streamWithAbort(i,t?.signal)){let t=this.responseParser.parseStreamingChunk(e);t&&(yield t)}}catch(e){let t=e.message||`DeepSeek API request failed`;throw Error(`DeepSeek stream failed: ${t}`)}}supportsTools(){return!0}getCapabilities(){return{functionCalling:{supported:!0},nativeWebTools:{webSearch:{supported:!1,enabled:!1,source:`openai-compatible-chat-completions`,reason:`DeepSeek OpenAI-compatible Chat Completions supports declared function tools, not provider-native web search.`},webFetch:{supported:!1,enabled:!1,source:`openai-compatible-chat-completions`,reason:`DeepSeek OpenAI-compatible Chat Completions supports declared function tools, not provider-native web fetch.`}}}}validateConfig(){return!!this.client&&!!this.options}async dispose(){}buildRequestParams(e,t){this.validateTools(t?.tools);let n=t?.model??this.options.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);return{model:n,messages:zS(e),...t?.temperature!==void 0&&{temperature:t.temperature},...t?.maxTokens!==void 0&&{max_tokens:t.maxTokens},...t?.tools&&{tools:BS(t.tools),tool_choice:cC(t.toolChoice)},...this.options.thinking!==void 0&&{thinking:{type:this.options.thinking}},...this.options.reasoningEffort!==void 0&&{reasoning_effort:this.options.reasoningEffort}}}buildStreamingRequestParams(e,t){return{...this.buildRequestParams(e,t),stream:!0}}getClient(){if(!this.client)throw Error(`DeepSeek client not available. Either provide a client/apiKey or use an executor.`);return this.client}async chatWithStreamingAssembly(e,t){let n=this.getClient();try{return t.onProviderNativeRawPayload?.({provider:`deepseek`,apiSurface:`chat-completions`,payloadKind:`request`,payload:e}),GS({stream:aC(await n.chat.completions.create(e,t.signal?{signal:t.signal}:void 0),{provider:`deepseek`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t.onProviderNativeRawPayload}),onTextDelta:t.onTextDelta,signal:t.signal})}catch(e){let t=e.message||`DeepSeek streaming request failed`;throw Error(`DeepSeek stream failed: ${t}`)}}};const Bw=`https://api-docs.deepseek.com/quick_start/pricing`,Vw=`2026-05-07`,Hw=`2026-07-24`,Uw=[{id:Iw,displayName:`DeepSeek V4 Flash`,contextWindow:1e6,capabilities:[`tools`,`reasoning`,`json_schema`,`streaming`],lifecycle:`active`,sourceUrl:Bw,lastVerifiedAt:Vw},{id:`deepseek-v4-pro`,displayName:`DeepSeek V4 Pro`,contextWindow:1e6,capabilities:[`tools`,`reasoning`,`json_schema`,`streaming`],lifecycle:`active`,sourceUrl:Bw,lastVerifiedAt:Vw},{id:`deepseek-chat`,displayName:`DeepSeek Chat compatibility alias, deprecated ${Hw}`,aliases:[Iw],contextWindow:1e6,capabilities:[`tools`,`json_schema`,`streaming`],lifecycle:`deprecated`,sourceUrl:Bw,lastVerifiedAt:Vw},{id:`deepseek-reasoner`,displayName:`DeepSeek Reasoner compatibility alias, deprecated ${Hw}`,aliases:[Iw],contextWindow:1e6,capabilities:[`reasoning`,`json_schema`,`streaming`],lifecycle:`deprecated`,sourceUrl:Bw,lastVerifiedAt:Vw}];function Ww(e){return Uw.find(t=>t.id===e)}async function Gw(e,t=Yw){let n=await t(`${Jw(e.baseURL??`https://api.deepseek.com`)}/models`,Kw(e.apiKey));return n.ok?{status:`live`,sourceUrl:Bw,lastVerifiedAt:Vw,entries:((await n.json()).data??[]).map(e=>e.id).filter(e=>typeof e==`string`&&e.length>0).map(qw)}:{status:`unavailable`,sourceUrl:Bw,message:`DeepSeek model refresh failed: HTTP ${n.status}`}}function Kw(e){if(e)return{headers:{Authorization:`Bearer ${e}`}}}function qw(e){return Ww(e)??{id:e,displayName:e,lifecycle:`active`,sourceUrl:`https://api-docs.deepseek.com/quick_start/pricing`,lastVerifiedAt:`2026-05-07`}}function Jw(e){return e.replace(/\/$/,``)}async function Yw(e,t){let n=await fetch(e,{...t?.headers!==void 0&&{headers:t.headers}});return{ok:n.ok,status:n.status,json:()=>n.json()}}const Xw={status:`fallback`,sourceUrl:Bw,lastVerifiedAt:Vw,entries:Uw},Zw=[{kind:`api-key`,label:`DeepSeek API keys`,url:`https://platform.deepseek.com/api_keys`,sourceUrl:`https://api-docs.deepseek.com/`,lastVerifiedAt:`2026-05-08`}];function Qw(){return{type:`deepseek`,displayName:`DeepSeek`,description:`High performance at low cost. API key required.`,category:`cloud-paid`,defaults:{model:Iw,apiKey:Lw,baseURL:Rw},modelCatalog:Xw,setupHelpLinks:Zw,setupSteps:[{key:`baseURL`,title:`DeepSeek OpenAI-compatible base URL`,defaultValue:Rw},{key:`model`,title:`DeepSeek model`,defaultValue:Iw},{key:`apiKey`,title:`DeepSeek API key`,defaultValue:Lw,masked:!0}],requiresApiKey:!0,probeProfile:oC,refreshModelCatalog:({profile:e})=>Gw(e),modelCatalogCacheTtlSeconds:86400,createProvider:e=>{let t=eT(e.options);return new zw({apiKey:$w(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},...t.thinking!==void 0&&{thinking:t.thinking},...t.reasoningEffort!==void 0&&{reasoningEffort:t.reasoningEffort},defaultModel:e.model})}}}function $w(e){if(!e)throw Error(`Provider deepseek requires apiKey`);return e}function eT(e){let t=tT(e?.thinking),n=nT(e?.reasoningEffort);return{...t!==void 0&&{thinking:t},...n!==void 0&&{reasoningEffort:n}}}function tT(e){if(e===!0)return`enabled`;if(e===!1)return`disabled`;if(e===`enabled`||e===`disabled`)return e;let t=rT(e)?.type;return t===`enabled`||t===`disabled`?t:void 0}function nT(e){if(e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`)return e}function rT(e){if(!(e==null||e instanceof Date||Array.isArray(e)))return typeof e==`object`?e:void 0}function iT(e){return e?e.some(e=>e.type===`image_inline`||e.type===`image_uri`):!1}function aT(e){if(!e)return[];let t=[];for(let n of e)n.type===`image_inline`&&t.push({kind:`uri`,uri:`data:${n.mimeType};base64,${n.data}`,mimeType:n.mimeType});return t}function oT(e){let t=e.indexOf(`,`);if(t<0)return;let n=e.slice(0,t),r=e.slice(t+1);if(!n.endsWith(`;base64`))return;let i=n.replace(`data:`,``).replace(`;base64`,``).trim();if(!(i.length===0||r.trim().length===0))return{mimeType:i,data:r}}function sT(e){if(e.kind===`inline`)return e.mimeType.trim().length===0||e.data.trim().length===0?{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Inline image source requires non-empty mimeType and data.`}}:{ok:!0,value:{type:`image_inline`,mimeType:e.mimeType,data:e.data}};if(!e.uri.startsWith(`data:`))return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Google image provider supports only inline or data URI input sources.`}};let t=oT(e.uri);return t?{ok:!0,value:{type:`image_inline`,mimeType:t.mimeType,data:t.data}}:{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Data URI source must use base64 payload.`}}}function cT(e,t,n){return n&&n.length>0?n:e.some(e=>iT(e.parts))?[`TEXT`,`IMAGE`]:t&&t.length>0?t:[`TEXT`]}function lT(e,t){return!t||t.length===0?!0:t.includes(e)}function uT(e,t,n){gT(t);let r=cT(e,t.defaultResponseModalities,n?.google?.responseModalities);dT(n?.model,r,t);let i={responseModalities:r};return fT(i,n),pT(i,t,n),mT(i,t),hT(i,t),i}function dT(e,t,n){if(!(!e||!t.includes(`IMAGE`))&&!lT(e,n.imageCapableModels))throw Error(`Selected model "${e}" is not configured as image-capable for Google provider.`)}function fT(e,t){typeof t?.temperature==`number`&&(e.temperature=t.temperature),typeof t?.maxTokens==`number`&&(e.maxOutputTokens=t.maxTokens),typeof t?.google?.topP==`number`&&(e.topP=t.google.topP),typeof t?.google?.topK==`number`&&(e.topK=t.google.topK),typeof t?.google?.candidateCount==`number`&&(e.candidateCount=t.google.candidateCount),t?.google?.stopSequences&&t.google.stopSequences.length>0&&(e.stopSequences=t.google.stopSequences),t?.signal&&(e.abortSignal=t.signal)}function pT(e,t,n){let r=n?.google?.safetySettings??t.safetySettings;r&&r.length>0&&(e.safetySettings=r)}function mT(e,t){t.responseMimeType&&(e.responseMimeType=t.responseMimeType),t.responseSchema&&(e.responseMimeType=t.responseMimeType??`application/json`,e.responseSchema=t.responseSchema),t.responseJsonSchema&&(e.responseMimeType=t.responseMimeType??`application/json`,e.responseJsonSchema=t.responseJsonSchema)}function hT(e,t){t.thinkingConfig&&(e.thinkingConfig=t.thinkingConfig),t.toolConfig&&(e.toolConfig=t.toolConfig)}function gT(e){if(e.responseSchema&&e.responseJsonSchema)throw Error(`Gemini structured output options responseSchema and responseJsonSchema are mutually exclusive.`)}function _T(e){let t=[],n=e.parts??[];for(let e of n){if(e.type===`text`){t.push({text:e.text});continue}if(e.type===`image_inline`){t.push({inlineData:{mimeType:e.mimeType,data:e.data}});continue}throw Error(`Google provider does not support image URI parts directly: ${e.uri}`)}return t.length===0&&typeof e.content==`string`&&e.content.length>0&&t.push({text:e.content}),t}function vT(e){let t=[],n=[];for(let r of e){if(r.role===`user`){t.push({role:`user`,parts:_T(r)});continue}if(r.role===`assistant`){t.push(yT(r));continue}if(r.role===`tool`){t.push(bT(r));continue}let e=xT(r);e.length>0&&n.push(e)}return{contents:t,...n.length>0&&{systemInstruction:n.join(`
231
+ `)||void 0;if(!t?.model)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let a=t?.tools?yS(t.tools):[],o=this.enableWebTools?[{type:`web_search_20250305`,name:`web_search`}]:[],s=[...a,...o],c={model:t.model,messages:r,max_tokens:t?.maxTokens||Xn(t.model),...i&&{system:i},...t?.temperature!==void 0&&{temperature:t.temperature},...s.length>0&&{tools:s},...s.length>0&&t?.toolChoice!==void 0&&{tool_choice:bS(t.toolChoice)},...TS(t)},l=t?.onTextDelta??this.onTextDelta??(()=>{});try{return await xS(this.client,c,l,this.onServerToolUse,t?.signal,t?.onProviderNativeRawPayload)}catch(e){let t=e;throw t.status===429||t.error?.type===`rate_limit_error`?new cn(t.message??`Anthropic rate limit exceeded.`,void 0,`anthropic`):e}}async*chatStream(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor){yield*this.executeStreamViaExecutorOrDirect(e,t);return}if(!this.client)throw Error(`Anthropic client not available. Either provide a client/apiKey or use an executor.`);let n=_S(e);if(!t?.model)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let r={model:t.model,messages:n,max_tokens:t?.maxTokens||Xn(t.model),stream:!0,...TS(t)};t?.temperature!==void 0&&(r.temperature=t.temperature);let i=t?.tools?yS(t.tools):[],a=this.enableWebTools?[{type:`web_search_20250305`,name:`web_search`}]:[],o=[...i,...a];o.length>0&&(r.tools=o,t?.toolChoice!==void 0&&(r.tool_choice=bS(t.toolChoice))),t?.onProviderNativeRawPayload?.({provider:`anthropic`,apiSurface:`anthropic-messages`,payloadKind:`request`,payload:r});let s;try{s=await this.client.messages.create(r)}catch(e){let t=e;throw t.status===429||t.error?.type===`rate_limit_error`?new cn(t.message??`Anthropic rate limit exceeded.`,void 0,`anthropic`):e}let c=0;for await(let e of s)t?.onProviderNativeRawPayload?.({provider:`anthropic`,apiSurface:`anthropic-messages`,payloadKind:`stream_event`,sequence:c,payload:e}),c++,e.type===`content_block_delta`&&e.delta.type===`text_delta`&&(yield{id:l(),role:`assistant`,content:e.delta.text,state:`complete`,timestamp:new Date})}supportsTools(){return!0}getCapabilities(){return{functionCalling:{supported:!0},nativeWebTools:{webSearch:this.enableWebTools?{supported:!0,enabled:!0,source:`anthropic-messages`}:{supported:!0,enabled:!1,source:`anthropic-messages`,reason:`Call configureNativeWebTools({ webSearch: true }) or set enableWebTools.`},webFetch:{supported:!1,enabled:!1,source:`anthropic-messages`,reason:`Anthropic provider exposes server web search only.`}}}}configureNativeWebTools(e){return e.webSearch===!0&&(this.enableWebTools=!0),this.validateNativeWebTools(e),this.getCapabilities()}validateConfig(){return!!this.client&&!!this.options&&!!this.options.apiKey}async dispose(){}validateMessages(e){if(!Array.isArray(e))throw new G(`Messages must be an array`,`messages`);if(e.length===0)throw new G(`Messages array cannot be empty`,`messages`);for(let t of e)if(!t.role||![`user`,`assistant`,`system`,`tool`].includes(t.role))throw new G(`Invalid message role: ${t.role}`,`role`)}};function TS(e){return e?.responseFormat?.type===`json_schema`?{output_config:{format:{type:`json_schema`,schema:ES(e.responseFormat.schema)}}}:{}}function ES(e){if(Array.isArray(e))return e.map(ES);if(typeof e!=`object`||!e)return e;let t=e,n={...t};return t.properties&&typeof t.properties==`object`&&(n.properties=Object.fromEntries(Object.entries(t.properties).map(([e,t])=>[e,ES(t)]))),t.items&&typeof t.items==`object`&&(n.items=ES(t.items)),t.additionalProperties&&typeof t.additionalProperties==`object`?n.additionalProperties=ES(t.additionalProperties):t.type===`object`&&(n.additionalProperties=!1),n}async function DS(e,t=AS){return OS(e,t)}async function OS(e,t){let n=await t(`https://api.anthropic.com/v1/models`,kS(e.apiKey)).catch(e=>({ok:!1,status:0,json:()=>Promise.resolve({data:[]}),errorMessage:`Anthropic model refresh failed: ${e instanceof Error?e.message:String(e)}`}));if(`errorMessage`in n)return{status:`unavailable`,sourceUrl:NS,message:n.errorMessage};if(!n.ok)return{status:`unavailable`,sourceUrl:NS,message:`Anthropic model refresh failed: HTTP ${n.status}`};let r=await n.json(),i=new Date().toISOString(),a=(r.data??[]).filter(e=>typeof e.id==`string`&&e.id.length>0).map(e=>({id:e.id,displayName:e.display_name??e.id,lifecycle:`active`,sourceUrl:NS,lastVerifiedAt:i}));return{status:`live`,sourceUrl:NS,lastVerifiedAt:PS,entries:a,message:`Fetched ${a.length} models from Anthropic API`}}function kS(e){if(e)return{headers:{"x-api-key":e,"anthropic-version":`2023-06-01`}}}async function AS(e,t){let n=await fetch(e,{...t?.headers!==void 0&&{headers:t.headers}});return{ok:n.ok,status:n.status,json:()=>n.json()}}const jS=`claude-sonnet-4-6`,MS=`$ENV:ANTHROPIC_API_KEY`,NS=`https://platform.claude.com/docs/en/api/models/list`,PS=`2026-05-04`,FS=[{kind:`api-key`,label:`Anthropic API keys`,url:`https://platform.claude.com/settings/keys`,sourceUrl:`https://platform.claude.com/docs/en/api/overview`,lastVerifiedAt:`2026-05-08`}];function IS(){return{type:`anthropic`,displayName:`Anthropic`,description:`Claude series — strong at coding tasks. API key required.`,category:`cloud-paid`,defaults:{model:jS,apiKey:MS},modelCatalog:{status:`fallback`,sourceUrl:NS,lastVerifiedAt:PS,entries:LS()},setupHelpLinks:FS,setupSteps:[{key:`apiKey`,title:`Anthropic API key`,defaultValue:MS,masked:!0},{key:`model`,title:`Anthropic model`,defaultValue:jS}],refreshModelCatalog:({profile:e})=>DS(e),modelCatalogCacheTtlSeconds:86400,requiresApiKey:!0,createProvider:e=>new wS({apiKey:RS(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},defaultModel:e.model})}}function LS(){let e=new Set,t=[];for(let n of Object.values(Jn))e.has(n.name)||(e.add(n.name),t.push({id:n.id,displayName:n.name,contextWindow:n.contextWindow,capabilities:[`tools`,`vision`,`json_schema`,`reasoning`,`streaming`],lifecycle:`active`,sourceUrl:NS,lastVerifiedAt:PS}));return t}function RS(e){if(!e)throw Error(`Provider anthropic requires apiKey`);return e}function zS(e){return e.map(e=>HS(e))}function BS(e){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function VS(e){if(!e.parts||e.parts.length===0||!e.parts.some(e=>e.type===`image_inline`||e.type===`image_uri`))return e.content||``;let t=[];for(let n of e.parts)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`image_inline`){let e=n;t.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}else if(n.type===`image_uri`){let e=n;t.push({type:`image_url`,image_url:{url:e.uri}})}return t.length===0?e.content||``:t}function HS(e){if(e.role===`user`)return{role:`user`,content:VS(e)};if(e.role===`assistant`)return US(e);if(e.role===`system`)return{role:`system`,content:e.content||``};if(e.role===`tool`){if(!e.toolCallId||e.toolCallId.trim().length===0)throw Error(`Tool message missing toolCallId: ${JSON.stringify(e)}`);return{role:`tool`,content:e.content||``,tool_call_id:e.toolCallId}}throw Error(`Unsupported message role: ${JSON.stringify(e)}`)}function US(e){return e.toolCalls&&e.toolCalls.length>0?{role:`assistant`,content:e.content===``?null:e.content||null,tool_calls:e.toolCalls.map(e=>({id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments}}))}:{role:`assistant`,content:e.content===null?null:e.content||``}}var WS=class{logger;textProjector;toolCallTextProjector;constructor(e={}){this.logger=e.logger??kt,this.textProjector=e.textProjector,this.toolCallTextProjector=e.toolCallTextProjector}parseResponse(e){try{let t=e.choices?.[0];if(!t)throw Error(`No choices found in OpenAI-compatible response`);return this.parseChoice(t,e.usage)}catch(e){let t=e instanceof Error?e.message:`OpenAI-compatible response parsing failed`;throw this.logger.error(`Response parsing failed`,{error:t}),Error(`OpenAI-compatible response parsing failed: ${t}`)}}parseChoice(e,t){let n=e.message,r=this.projectToolCallText(n.content||``),i=this.toolCallTextProjector?.flush(),a=this.parseNativeToolCalls(n),o=[...r.toolCalls,...i?.toolCalls??[]],s=[...a,...o];return{id:l(),state:`complete`,role:`assistant`,content:this.projectText(r.visibleText+(i?.visibleText??``)),timestamp:new Date,...s.length>0&&{toolCalls:s},...t&&{usage:this.parseUsage(t)},metadata:{finishReason:e.finish_reason||void 0,...this.buildToolTextMetadata(r,i)}}}parseNativeToolCalls(e){return e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments}}))||[]}parseUsage(e){return{promptTokens:e.prompt_tokens,completionTokens:e.completion_tokens,totalTokens:e.total_tokens}}parseStreamingChunk(e){try{let t=e.usage?this.parseUsage(e.usage):void 0,n=e.choices?.[0];if(!n)return t?{id:l(),state:`complete`,role:`assistant`,content:``,timestamp:new Date,usage:t,metadata:{isStreamChunk:!0,isComplete:!0}}:null;let r=n.finish_reason,i=n.delta.tool_calls?.map(e=>({id:e.id||``,type:`function`,function:{name:e.function?.name||``,arguments:e.function?.arguments||``}}));return i?{id:l(),state:`complete`,role:`assistant`,content:``,timestamp:new Date,toolCalls:i,...t&&{usage:t},metadata:{isStreamChunk:!0,isComplete:r===`stop`||r===`tool_calls`}}:{id:l(),state:`complete`,role:`assistant`,content:this.projectText(n.delta.content||``),timestamp:new Date,...t&&{usage:t},metadata:{isStreamChunk:!0,isComplete:r===`stop`||r===`tool_calls`}}}catch(e){let t=e instanceof Error?e.message:`OpenAI-compatible chunk parsing failed`;throw this.logger.error(`Chunk parsing failed`,{error:t}),Error(`OpenAI-compatible chunk parsing failed: ${t}`)}}projectText(e){return this.textProjector?this.textProjector(e):e}projectToolCallText(e){return this.toolCallTextProjector?.project(e)??{visibleText:e,toolCalls:[],removedToolCallText:!1}}buildToolTextMetadata(e,t){let n=[e.rawToolCallText,t?.rawToolCallText].filter(e=>typeof e==`string`&&e.length>0).join(``);return{...(e.removedToolCallText||(t?.removedToolCallText??!1))&&{toolCallTextProjected:!0},...n.length>0&&{rawToolCallText:n}}}};async function GS(e){let t={textParts:[],toolCallParts:new Map,projectedToolCalls:[],rawToolCallTextParts:[],toolCallTextProjected:!1,model:``,finishReason:null};for await(let n of nC(e.stream,e.signal))KS(t,n,e);return YS(t,e),$S(t,e.metadata)}function KS(e,t,n){t.model&&(e.model=t.model),t.usage&&(e.usage={promptTokens:t.usage.prompt_tokens,completionTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens});let r=t.choices?.[0];r&&(e.finishReason=r.finish_reason??e.finishReason,qS(e,r.delta.content,n),QS(e,r.delta.tool_calls??[]))}function qS(e,t,n){if(!t)return;let r=XS(t,n.toolCallTextProjector);ZS(e,r);let i=JS(r.visibleText,n.textProjector);i.length!==0&&(e.textParts.push(i),n.onTextDelta?.(i))}function JS(e,t){return t?t(e):e}function YS(e,t){let n=t.toolCallTextProjector?.flush();if(n){ZS(e,n);let r=JS(n.visibleText,t.textProjector);r.length>0&&(e.textParts.push(r),t.onTextDelta?.(r))}let r=t.textProjectorFlush?.();r&&(e.textParts.push(r),t.onTextDelta?.(r))}function XS(e,t){return t?.project(e)??{visibleText:e,toolCalls:[],removedToolCallText:!1}}function ZS(e,t){t.toolCalls.length>0&&e.projectedToolCalls.push(...t.toolCalls),t.removedToolCallText&&(e.toolCallTextProjected=!0),t.rawToolCallText&&t.rawToolCallText.length>0&&e.rawToolCallTextParts.push(t.rawToolCallText)}function QS(e,t){for(let n of t){let t=n.index??0,r=e.toolCallParts.get(t)??{id:``,name:``,arguments:``},i=n.function?.name??r.name;e.toolCallParts.set(t,{id:n.id??r.id,name:i,arguments:r.arguments+(n.function?.arguments??``)})}}function $S(e,t={}){let n={...t};e.model&&(n.model=e.model),e.finishReason&&(n.finishReason=e.finishReason),e.toolCallTextProjected&&(n.toolCallTextProjected=!0),e.rawToolCallTextParts.length>0&&(n.rawToolCallText=e.rawToolCallTextParts.join(``));let r=eC(e);return{id:l(),role:`assistant`,content:e.textParts.join(``),state:`complete`,timestamp:new Date,...r.length>0&&{toolCalls:r},...e.usage&&{usage:e.usage},...Object.keys(n).length>0&&{metadata:n}}}function eC(e){return[...tC(e.toolCallParts),...e.projectedToolCalls]}function tC(e){return Array.from(e.entries()).sort(([e],[t])=>e-t).map(([e,t])=>({id:t.id||`call_${e}`,type:`function`,function:{name:t.name,arguments:t.arguments||`{}`}}))}async function*nC(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await rC(n,t);if(e.done||(await iC(t),t?.aborted))break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async function rC(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}async function iC(e){e?.aborted||await new Promise(e=>setTimeout(e,0))}async function*aC(e,t){let n=t.initialSequence??0;for await(let r of e)t.onProviderNativeRawPayload?.({provider:t.provider,...t.apiSurface!==void 0&&{apiSurface:t.apiSurface},payloadKind:`stream_event`,sequence:n,payload:r}),n++,yield r}async function oC(e,t=sC){if(!e.baseURL)return{ok:!0,message:`Profile fields are valid; no endpoint probe configured.`};try{let n=await t(`${e.baseURL.replace(/\/$/,``)}/models`);if(!n.ok)return{ok:!1,message:`HTTP ${n.status}`};let r=((await n.json()).data??[]).map(e=>e.id).filter(e=>!!e);return{ok:!0,message:`${r.length} model(s) discovered`,models:r}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}async function sC(e){let t=await fetch(e);return{ok:t.ok,status:t.status,json:()=>t.json()}}function cC(e){return e===void 0||e===`auto`?`auto`:e===`none`||e===`required`?e:{type:`function`,function:{name:e.tool}}}function lC(e){return e===void 0||e===`auto`?`auto`:e===`none`||e===`required`?e:{type:`function`,name:e.tool}}function uC(e){return zS(e)}function dC(e){return BS(e)}function fC(e,t){return t?.type===void 0?e:t.type===`json_schema`?{...e,responseFormat:`json_schema`,jsonSchema:{name:t.name??`structured_output`,schema:t.schema}}:{...e,responseFormat:t.type}}function pC(e){if(e.responseFormat===void 0||e.responseFormat===`text`)return;if(e.responseFormat===`json_object`)return{type:`json_object`};let t=hC(e);return{type:`json_schema`,json_schema:{name:t.name,schema:t.schema,...t.description!==void 0&&{description:t.description},...t.strict!==void 0&&{strict:t.strict}}}}function mC(e){if(e.responseFormat===void 0||e.responseFormat===`text`)return;if(e.responseFormat===`json_object`)return{format:{type:`json_object`}};let t=hC(e);return{format:{type:`json_schema`,name:t.name,schema:t.schema,...t.description!==void 0&&{description:t.description},...t.strict!==void 0&&{strict:t.strict}}}}function hC(e){let t=e.jsonSchema;if(e.responseFormat!==`json_schema`)throw Error(`Unsupported OpenAI response format: ${e.responseFormat}`);if(!t?.schema)throw Error(`OpenAI jsonSchema.schema is required when responseFormat is json_schema`);return{name:t.name,schema:t.schema,...t.description!==void 0&&{description:t.description},...t.strict!==void 0&&{strict:t.strict}}}async function gC(e){let t=SC(e.client);try{let n=yC(e);if(e.chatOptions?.onTextDelta??e.onTextDelta)return await bC(t,e,{...n,stream:!0,...vC(e)});await xC(e,n,`chat`),e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let r=await t.chat.completions.create(n);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`chat-completions`,payloadKind:`response`,payload:r}),e.responseParser.parseResponse(r)}catch(e){let t=e;if(t.status===429)throw new cn(t.message??`OpenAI rate limit exceeded.`,void 0,`openai`);let n=t.message||`OpenAI API request failed`;throw Error(`OpenAI chat failed: ${n}`)}}async function*_C(e){let t=SC(e.client);try{let n={...yC(e),stream:!0,...vC(e)};await xC(e,n,`stream`),e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let r=await t.chat.completions.create(n,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0);for await(let t of aC(r,{provider:`openai`,apiSurface:`chat-completions`,onProviderNativeRawPayload:e.chatOptions?.onProviderNativeRawPayload})){let n=e.responseParser.parseStreamingChunk(t);n&&(yield n)}}catch(e){let t=e;if(t.status===429)throw new cn(t.message??`OpenAI rate limit exceeded.`,void 0,`openai`);let n=t.message||`OpenAI API request failed`;throw Error(`OpenAI stream failed: ${n}`)}}function vC(e){return e.providerOptions.includeStreamUsage===!1?{}:{stream_options:{include_usage:!0}}}function yC(e){let t=uC(e.messages),n=e.chatOptions?.model??e.providerOptions.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let r=pC(fC(e.providerOptions,e.chatOptions?.responseFormat));return{model:n,messages:t,...e.chatOptions?.temperature!==void 0&&{temperature:e.chatOptions.temperature},...e.chatOptions?.maxTokens!==void 0&&{max_tokens:e.chatOptions.maxTokens},...e.chatOptions?.tools&&{tools:dC(e.chatOptions.tools),tool_choice:cC(e.chatOptions.toolChoice)},...r!==void 0&&{response_format:r}}}async function bC(e,t,n){try{return await xC(t,n,`stream`),t.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n}),GS({stream:aC(await e.chat.completions.create(n,t.chatOptions?.signal?{signal:t.chatOptions.signal}:void 0),{provider:`openai`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t.chatOptions?.onProviderNativeRawPayload}),onTextDelta:t.chatOptions?.onTextDelta??t.onTextDelta,signal:t.chatOptions?.signal})}catch(e){let t=e;if(t.status===429)throw new cn(t.message??`OpenAI rate limit exceeded.`,void 0,`openai`);let n=t.message||`OpenAI streaming request failed`;throw Error(`OpenAI stream failed: ${n}`)}}async function xC(e,t,n){if(!e.payloadLogger?.isEnabled())return;let r={model:t.model,messagesCount:t.messages.length,hasTools:!!t.tools,temperature:t.temperature??void 0,maxTokens:t.max_tokens??void 0,timestamp:new Date().toISOString()};await e.payloadLogger.logPayload(r,n)}function SC(e){if(!e)throw Error(`OpenAI client not available. Either provide a client/apiKey or use an executor.`);return e}var CC=class{parser;constructor(e){this.parser=new WS({logger:e})}parseResponse(e){try{return this.parser.parseResponse(e)}catch(e){let t=wC(e instanceof Error?e.message:`OpenAI response parsing failed`);throw Error(`OpenAI response parsing failed: ${t}`)}}parseStreamingChunk(e){try{return this.parser.parseStreamingChunk(e)}catch(e){let t=wC(e instanceof Error?e.message:`OpenAI chunk parsing failed`);throw Error(`OpenAI chunk parsing failed: ${t}`)}}};function wC(e){return e.replace(/^OpenAI-compatible response parsing failed: /,``).replace(/^OpenAI-compatible chunk parsing failed: /,``).replace(`OpenAI-compatible response`,`OpenAI response`)}function TC(e){switch(e){case`low`:return`low`;case`medium`:return`medium`;case`high`:case`xhigh`:case`max`:return`high`;default:return e}}function EC(e,t){return t===void 0?e:{...e,effort:TC(t)}}function DC(e){return e.flatMap(e=>kC(e))}function OC(e,t){let n=e?.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters,strict:t??!1}))??[];return n.length>0?n:void 0}function kC(e){if(e.role===`user`)return[NC(`user`,jC(e.content,e.parts))];if(e.role===`system`)return[NC(`system`,e.content)];if(e.role===`tool`){if(!e.toolCallId||e.toolCallId.trim().length===0)throw Error(`Tool message missing toolCallId: ${JSON.stringify(e)}`);return[{type:`function_call_output`,call_id:e.toolCallId,output:e.content||``}]}return AC(e)}function AC(e){let t=[];e.content&&e.content.length>0&&t.push(NC(`assistant`,e.content));for(let n of e.toolCalls??[])t.push({type:`function_call`,call_id:n.id,name:n.function.name,arguments:n.function.arguments});return t.length===0&&t.push(NC(`assistant`,``)),t}function jC(e,t){if(!t||t.length===0)return e;let n=t.map(e=>MC(e));return e.length>0&&!t.some(e=>e.type===`text`)?[{type:`input_text`,text:e},...n]:n}function MC(e){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_uri`?{type:`input_image`,image_url:e.uri}:{type:`input_image`,image_url:`data:${e.mimeType};base64,${e.data}`}}function NC(e,t){return{role:e,content:t}}async function*PC(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await FC(n,t);if(e.done||t?.aborted)break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async function FC(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}function IC(e){tw(e);let t=e.output??[];return VC({content:e.output_text??qC(t),toolCalls:WC(t),response:e,reasoning:XC(t)})}async function LC(e){let t={textParts:[],toolCalls:[],reasoning:QC()};for await(let n of PC(e.stream,e.signal))RC(t,n,e.onTextDelta);return t.completedResponse===void 0?VC({content:t.textParts.join(``),toolCalls:t.toolCalls,reasoning:t.reasoning}):BC(t)}function RC(e,t,n){if(t.type===`response.output_text.delta`){e.textParts.push(t.delta),n?.(t.delta);return}if(t.type===`response.completed`){e.completedResponse=t.response,$C(e.reasoning,XC(t.response.output??[]));return}if(t.type===`response.output_item.done`){zC(e,t.item);return}if(t.type===`response.error`||t.type===`response.failed`||t.type===`response.incomplete`)throw Error(`OpenAI Responses API failed: ${nw(t)}`)}function zC(e,t){if(GC(t)){e.toolCalls.push(KC(t));return}ZC(t)&&$C(e.reasoning,XC([t]))}function BC(e){let t=e.completedResponse;if(t===void 0)throw Error(`OpenAI Responses stream completed without response metadata`);tw(t);let n=t.output??[],r=WC(n),i=e.textParts.length>0?e.textParts.join(``):t.output_text??qC(n),a=XC(n);return $C(a,e.reasoning),VC({content:i,toolCalls:r.length>0?r:e.toolCalls,response:t,reasoning:a})}function VC(e){return{id:l(),role:`assistant`,content:e.content,state:`complete`,timestamp:new Date,...e.toolCalls.length>0&&{toolCalls:e.toolCalls},...e.response?.usage!==void 0&&{usage:UC(e.response.usage)},metadata:HC(e.response,e.reasoning)}}function HC(e,t){return{providerApiSurface:`responses`,...e?.id!==void 0&&{responseId:e.id},...e?.model!==void 0&&{model:e.model},...e?.status!==void 0&&{finishReason:e.status},...t.reasoningSummaryCount>0&&{reasoningSummaryCount:t.reasoningSummaryCount,reasoningSummaries:t.reasoningSummaries},...t.hasEncryptedReasoning&&{hasEncryptedReasoning:!0}}}function UC(e){return{promptTokens:e.input_tokens??0,completionTokens:e.output_tokens??0,totalTokens:e.total_tokens??0}}function WC(e){return e.filter(GC).map(e=>KC(e))}function GC(e){return e.type===`function_call`&&`call_id`in e&&`name`in e&&`arguments`in e}function KC(e){return{id:e.call_id,type:`function`,function:{name:e.name,arguments:e.arguments}}}function qC(e){return e.filter(YC).flatMap(e=>e.content).map(JC).join(``)}function JC(e){return e.type===`refusal`?e.refusal:e.text}function YC(e){return e.type===`message`&&`content`in e&&Array.isArray(e.content)}function XC(e){let t=QC();for(let n of e){if(!ZC(n))continue;let e=n.summary?.map(e=>e.text).filter(ew)??[];t.reasoningSummaryCount+=e.length,t.reasoningSummaries.push(...e),t.hasEncryptedReasoning=t.hasEncryptedReasoning||!!n.encrypted_content}return t}function ZC(e){return e.type===`reasoning`}function QC(){return{reasoningSummaryCount:0,reasoningSummaries:[],hasEncryptedReasoning:!1}}function $C(e,t){e.reasoningSummaryCount+=t.reasoningSummaryCount,e.reasoningSummaries.push(...t.reasoningSummaries),e.hasEncryptedReasoning=e.hasEncryptedReasoning||t.hasEncryptedReasoning}function ew(e){return e!==void 0}function tw(e){if(e.status===`failed`||e.status===`incomplete`)throw Error(`OpenAI Responses API failed: ${e.error?.message??e.status}`)}function nw(e){return e.message??e.error?.message??e.response?.error?.message??`unknown error`}async function rw(e){let t=e.chatOptions?.onTextDelta??e.onTextDelta;if(t)return aw({...e,chatOptions:{...e.chatOptions,onTextDelta:t}});if(!e.client)throw Error(`OpenAI Responses client not available.`);try{let t=ow(e);e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`responses`,payloadKind:`request`,payload:t});let n=await e.client.responses.create(t,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`responses`,payloadKind:`response`,payload:n}),IC(n)}catch(e){let t=e.message||`OpenAI Responses API request failed`;throw Error(`OpenAI responses failed: ${t}`)}}async function*iw(e){let t={deltas:[]},n=e.chatOptions?.onTextDelta??e.onTextDelta,r=aw({...e,chatOptions:{...e.chatOptions,onTextDelta:e=>{n?.(e),uw(t,cw(e))}}}).then(e=>dw(t,e)).catch(e=>fw(t,gw(e)));yield*lw(t),await r}async function aw(e){if(!e.client)throw Error(`OpenAI Responses client not available.`);try{let t=sw(e);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`openai`,apiSurface:`responses`,payloadKind:`request`,payload:t}),LC({stream:aC(await e.client.responses.create(t,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0),{provider:`openai`,apiSurface:`responses`,onProviderNativeRawPayload:e.chatOptions?.onProviderNativeRawPayload}),onTextDelta:e.chatOptions?.onTextDelta,signal:e.chatOptions?.signal})}catch(e){let t=e.message||`OpenAI Responses streaming request failed`;throw Error(`OpenAI responses stream failed: ${t}`)}}function ow(e){let t=e.chatOptions?.model??e.providerOptions.defaultModel;if(!t)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let n=OC(e.chatOptions?.tools,e.providerOptions.strictTools),r=mC(e.providerOptions),i=EC(e.providerOptions.reasoning,e.chatOptions?.effort);return{model:t,input:DC(e.messages),...n!==void 0&&{tools:n,tool_choice:lC(e.chatOptions?.toolChoice)},...e.chatOptions?.temperature!==void 0&&{temperature:e.chatOptions.temperature},...e.chatOptions?.maxTokens!==void 0&&{max_output_tokens:e.chatOptions.maxTokens},...r!==void 0&&{text:r},...i!==void 0&&{reasoning:i},...e.providerOptions.includeEncryptedReasoning===!0&&{include:[`reasoning.encrypted_content`]},...e.providerOptions.store!==void 0&&{store:e.providerOptions.store}}}function sw(e){return{...ow(e),stream:!0}}function cw(e){return{id:l(),role:`assistant`,content:e,state:`complete`,timestamp:new Date,metadata:{providerApiSurface:`responses`,isStreamChunk:!0,isComplete:!1}}}async function*lw(e){for(;;){let t=e.deltas.shift();if(t!==void 0){yield t;continue}if(e.error!==void 0)throw e.error;if(e.finalMessage!==void 0){yield hw(e.finalMessage);return}await pw(e)}}function uw(e,t){e.deltas.push(t),mw(e)}function dw(e,t){e.finalMessage=t,mw(e)}function fw(e,t){e.error=t,mw(e)}function pw(e){return new Promise(t=>{e.wake=t})}function mw(e){e.wake?.(),e.wake=void 0}function hw(e){return{...e,content:``,metadata:{...e.metadata,isStreamChunk:!0,isComplete:!0}}}function gw(e){return e instanceof Error?e:Error(String(e))}var _w=class extends Ft{name=`openai`;version=`1.0.0`;client;options;apiSurface;payloadLogger;responseParser;onTextDelta;constructor(e){if(super(e.logger||kt),this.options=e,this.apiSurface=vw(e),bw(this.apiSurface,e.nativeWebTools),e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client;else if(e.apiKey)this.client=new Me({apiKey:e.apiKey,...e.organization&&{organization:e.organization},...e.timeout&&{timeout:e.timeout},...e.baseURL&&{baseURL:e.baseURL}});else throw Error(`Either OpenAI client, apiKey, or executor is required`);this.responseParser=new CC(this.logger),this.payloadLogger=e.payloadLogger}async chat(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`OpenAI Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}return this.apiSurface===`responses`?rw({client:this.client,messages:e,chatOptions:t,providerOptions:this.options,onTextDelta:this.onTextDelta}):gC({client:this.client,messages:e,chatOptions:t,providerOptions:this.options,payloadLogger:this.payloadLogger,responseParser:this.responseParser,onTextDelta:this.onTextDelta})}async*chatStream(e,t){if(this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`OpenAI Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}if(this.apiSurface===`responses`){yield*iw({client:this.client,messages:e,chatOptions:t,providerOptions:this.options,onTextDelta:this.onTextDelta});return}yield*_C({client:this.client,messages:e,chatOptions:t,providerOptions:this.options,payloadLogger:this.payloadLogger,responseParser:this.responseParser,onTextDelta:this.onTextDelta})}supportsTools(){return!0}getCapabilities(){let e=this.apiSurface===`chat-completions`?`openai-compatible-chat-completions`:`openai-responses`;return{functionCalling:{supported:!0},nativeWebTools:{webSearch:{supported:!1,enabled:!1,source:e,reason:yw(this.apiSurface,`search`)},webFetch:{supported:!1,enabled:!1,source:e,reason:yw(this.apiSurface,`fetch`)}}}}validateConfig(){return!!this.client&&!!this.options}async dispose(){}validateMessages(e){super.validateMessages(e);for(let t of e)if(t.role===`assistant`){let e=t;if(e.toolCalls&&e.toolCalls.length>0&&e.content===``)continue}}};function vw(e){return e.apiSurface===void 0?e.baseURL?`chat-completions`:`responses`:e.apiSurface}function yw(e,t){return e===`chat-completions`?`OpenAI-compatible Chat Completions endpoints support declared function tools, not provider-native web ${t}.`:`OpenAI Responses native web ${t} is not wired in this Robota provider version.`}function bw(e,t){if(!(t?.webSearch!==!0&&t?.webFetch!==!0))throw Error(`Provider openai native web search/fetch is not supported for apiSurface ${e} in this Robota provider version.`)}const xw=`https://platform.openai.com/docs/api-reference/models/list`;async function Sw(e,t={}){if(!e.apiKey)return Ew(`OpenAI model catalog refresh requires apiKey.`);let n=t.fetcher??Dw,r=t.now??(()=>new Date),i=Cw(e.baseURL);try{let t=await n(i,{headers:{Authorization:`Bearer ${e.apiKey}`}});if(!t.ok)return Ew(Tw(t));let a=ww(await t.json());return{status:`live`,entries:a,lastVerifiedAt:r().toISOString(),sourceUrl:xw,message:`${a.length} OpenAI model(s) discovered.`}}catch(e){return Ew(e instanceof Error?e.message:String(e))}}function Cw(e){return e?`${e.replace(/\/$/,``)}/models`:`https://api.openai.com/v1/models`}function ww(e){return(e.data??[]).map(e=>e.id).filter(e=>e!==void 0&&e.trim().length>0).map(e=>({id:e,displayName:e,lifecycle:`active`}))}function Tw(e){let t=e.statusText?` ${e.statusText}`:``;return`OpenAI model catalog refresh failed: HTTP ${e.status}${t}`}function Ew(e){return{status:`unavailable`,sourceUrl:xw,message:e}}async function Dw(e,t){let n=await fetch(e,t);return{ok:n.ok,status:n.status,statusText:n.statusText,json:()=>n.json()}}const Ow=`$ENV:OPENAI_API_KEY`,kw=[{kind:`api-key`,label:`OpenAI API keys`,url:`https://platform.openai.com/api-keys`,sourceUrl:`https://developers.openai.com/api/reference/overview#authentication`,lastVerifiedAt:`2026-05-08`}];function Aw(){return{type:`openai`,displayName:`OpenAI`,description:`GPT series — general-purpose assistant. API key required.`,category:`cloud-paid`,defaults:{apiKey:Ow},modelCatalog:{status:`unavailable`,sourceUrl:`https://platform.openai.com/docs/api-reference/models/list`,message:`OpenAI model availability should be discovered live from GET /v1/models.`},setupHelpLinks:kw,setupSteps:[{key:`model`,title:`OpenAI model`,required:!0},{key:`apiKey`,title:`OpenAI API key`,defaultValue:Ow,masked:!0}],requiresApiKey:!0,probeProfile:oC,refreshModelCatalog:({profile:e})=>Sw(e),modelCatalogCacheTtlSeconds:86400,createProvider:e=>{let t=Mw(e.options),n=Nw(e.options);return Fw(e.baseURL,t,n),new _w({apiKey:jw(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},...t!==void 0&&{apiSurface:t},...n!==void 0&&{nativeWebTools:n},defaultModel:e.model})}}}function jw(e){if(!e)throw Error(`Provider openai requires apiKey`);return e}function Mw(e){let t=e?.apiSurface;if(t===`responses`||t===`chat-completions`)return t}function Nw(e){let t=Pw(e?.nativeWebTools)??Pw(e?.builtInWebTools);if(t!==void 0)return t}function Pw(e){if(e==null||e instanceof Date||Array.isArray(e)||typeof e!=`object`)return;let t=e.webSearch,n=e.webFetch;return{...typeof t==`boolean`&&{webSearch:t},...typeof n==`boolean`&&{webFetch:n}}}function Fw(e,t,n){if(!(n?.webSearch!==!0&&n?.webFetch!==!0))throw Error(e!==void 0||t===`chat-completions`?`Provider openai profile uses an OpenAI-compatible Chat Completions endpoint; native web search/fetch is not supported for this profile. Use Robota local WebSearch/WebFetch tools or a provider with documented hosted web support.`:`Provider openai native web search/fetch is not wired in this Robota provider version. Use Robota local WebSearch/WebFetch tools or a provider with documented hosted web support.`)}const Iw=`deepseek-v4-flash`,Lw=`$ENV:DEEPSEEK_API_KEY`,Rw=`https://api.deepseek.com`;var zw=class extends Ft{name=`deepseek`;version=`1.0.0`;client;options;responseParser;onTextDelta;constructor(e){if(super(e.logger||kt),this.options=e,e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client;else if(e.apiKey)this.client=new Me({apiKey:e.apiKey,baseURL:e.baseURL??`https://api.deepseek.com`,...e.timeout!==void 0&&{timeout:e.timeout}});else throw Error(`Either DeepSeek client, apiKey, or executor is required`);this.responseParser=new WS({logger:this.logger})}async chat(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`DeepSeek Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}let n=this.getClient();try{let r=this.buildRequestParams(e,t),i=t?.onTextDelta??this.onTextDelta;if(i)return await this.chatWithStreamingAssembly({...r,stream:!0},{...t,onTextDelta:i});t?.onProviderNativeRawPayload?.({provider:`deepseek`,apiSurface:`chat-completions`,payloadKind:`request`,payload:r});let a=await n.chat.completions.create(r);return t?.onProviderNativeRawPayload?.({provider:`deepseek`,apiSurface:`chat-completions`,payloadKind:`response`,payload:a}),this.responseParser.parseResponse(a)}catch(e){let t=e.message||`DeepSeek API request failed`;throw Error(`DeepSeek chat failed: ${t}`)}}async*chatStream(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`DeepSeek Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}let n=this.getClient();try{let r=this.buildStreamingRequestParams(e,t);t?.onProviderNativeRawPayload?.({provider:`deepseek`,apiSurface:`chat-completions`,payloadKind:`request`,payload:r});let i=aC(await n.chat.completions.create(r),{provider:`deepseek`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t?.onProviderNativeRawPayload});for await(let e of this.streamWithAbort(i,t?.signal)){let t=this.responseParser.parseStreamingChunk(e);t&&(yield t)}}catch(e){let t=e.message||`DeepSeek API request failed`;throw Error(`DeepSeek stream failed: ${t}`)}}supportsTools(){return!0}getCapabilities(){return{functionCalling:{supported:!0},nativeWebTools:{webSearch:{supported:!1,enabled:!1,source:`openai-compatible-chat-completions`,reason:`DeepSeek OpenAI-compatible Chat Completions supports declared function tools, not provider-native web search.`},webFetch:{supported:!1,enabled:!1,source:`openai-compatible-chat-completions`,reason:`DeepSeek OpenAI-compatible Chat Completions supports declared function tools, not provider-native web fetch.`}}}}validateConfig(){return!!this.client&&!!this.options}async dispose(){}buildRequestParams(e,t){this.validateTools(t?.tools);let n=t?.model??this.options.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);return{model:n,messages:zS(e),...t?.temperature!==void 0&&{temperature:t.temperature},...t?.maxTokens!==void 0&&{max_tokens:t.maxTokens},...t?.tools&&{tools:BS(t.tools),tool_choice:cC(t.toolChoice)},...this.options.thinking!==void 0&&{thinking:{type:this.options.thinking}},...this.options.reasoningEffort!==void 0&&{reasoning_effort:this.options.reasoningEffort}}}buildStreamingRequestParams(e,t){return{...this.buildRequestParams(e,t),stream:!0}}getClient(){if(!this.client)throw Error(`DeepSeek client not available. Either provide a client/apiKey or use an executor.`);return this.client}async chatWithStreamingAssembly(e,t){let n=this.getClient();try{return t.onProviderNativeRawPayload?.({provider:`deepseek`,apiSurface:`chat-completions`,payloadKind:`request`,payload:e}),GS({stream:aC(await n.chat.completions.create(e,t.signal?{signal:t.signal}:void 0),{provider:`deepseek`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t.onProviderNativeRawPayload}),onTextDelta:t.onTextDelta,signal:t.signal})}catch(e){let t=e.message||`DeepSeek streaming request failed`;throw Error(`DeepSeek stream failed: ${t}`)}}};const Bw=`https://api-docs.deepseek.com/quick_start/pricing`,Vw=`2026-05-07`,Hw=`2026-07-24`,Uw=[{id:Iw,displayName:`DeepSeek V4 Flash`,contextWindow:1e6,capabilities:[`tools`,`reasoning`,`json_schema`,`streaming`],lifecycle:`active`,sourceUrl:Bw,lastVerifiedAt:Vw},{id:`deepseek-v4-pro`,displayName:`DeepSeek V4 Pro`,contextWindow:1e6,capabilities:[`tools`,`reasoning`,`json_schema`,`streaming`],lifecycle:`active`,sourceUrl:Bw,lastVerifiedAt:Vw},{id:`deepseek-chat`,displayName:`DeepSeek Chat compatibility alias, deprecated ${Hw}`,aliases:[Iw],contextWindow:1e6,capabilities:[`tools`,`json_schema`,`streaming`],lifecycle:`deprecated`,sourceUrl:Bw,lastVerifiedAt:Vw},{id:`deepseek-reasoner`,displayName:`DeepSeek Reasoner compatibility alias, deprecated ${Hw}`,aliases:[Iw],contextWindow:1e6,capabilities:[`reasoning`,`json_schema`,`streaming`],lifecycle:`deprecated`,sourceUrl:Bw,lastVerifiedAt:Vw}];function Ww(e){return Uw.find(t=>t.id===e)}async function Gw(e,t=Yw){let n=await t(`${Jw(e.baseURL??`https://api.deepseek.com`)}/models`,Kw(e.apiKey));return n.ok?{status:`live`,sourceUrl:Bw,lastVerifiedAt:Vw,entries:((await n.json()).data??[]).map(e=>e.id).filter(e=>typeof e==`string`&&e.length>0).map(qw)}:{status:`unavailable`,sourceUrl:Bw,message:`DeepSeek model refresh failed: HTTP ${n.status}`}}function Kw(e){if(e)return{headers:{Authorization:`Bearer ${e}`}}}function qw(e){return Ww(e)??{id:e,displayName:e,lifecycle:`active`,sourceUrl:`https://api-docs.deepseek.com/quick_start/pricing`,lastVerifiedAt:`2026-05-07`}}function Jw(e){return e.replace(/\/$/,``)}async function Yw(e,t){let n=await fetch(e,{...t?.headers!==void 0&&{headers:t.headers}});return{ok:n.ok,status:n.status,json:()=>n.json()}}const Xw={status:`fallback`,sourceUrl:Bw,lastVerifiedAt:Vw,entries:Uw},Zw=[{kind:`api-key`,label:`DeepSeek API keys`,url:`https://platform.deepseek.com/api_keys`,sourceUrl:`https://api-docs.deepseek.com/`,lastVerifiedAt:`2026-05-08`}];function Qw(){return{type:`deepseek`,displayName:`DeepSeek`,description:`High performance at low cost. API key required.`,category:`cloud-paid`,defaults:{model:Iw,apiKey:Lw,baseURL:Rw},modelCatalog:Xw,setupHelpLinks:Zw,setupSteps:[{key:`baseURL`,title:`DeepSeek OpenAI-compatible base URL`,defaultValue:Rw},{key:`model`,title:`DeepSeek model`,defaultValue:Iw},{key:`apiKey`,title:`DeepSeek API key`,defaultValue:Lw,masked:!0}],requiresApiKey:!0,probeProfile:oC,refreshModelCatalog:({profile:e})=>Gw(e),modelCatalogCacheTtlSeconds:86400,createProvider:e=>{let t=eT(e.options);return new zw({apiKey:$w(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},...t.thinking!==void 0&&{thinking:t.thinking},...t.reasoningEffort!==void 0&&{reasoningEffort:t.reasoningEffort},defaultModel:e.model})}}}function $w(e){if(!e)throw Error(`Provider deepseek requires apiKey`);return e}function eT(e){let t=tT(e?.thinking),n=nT(e?.reasoningEffort);return{...t!==void 0&&{thinking:t},...n!==void 0&&{reasoningEffort:n}}}function tT(e){if(e===!0)return`enabled`;if(e===!1)return`disabled`;if(e===`enabled`||e===`disabled`)return e;let t=rT(e)?.type;return t===`enabled`||t===`disabled`?t:void 0}function nT(e){if(e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`)return e}function rT(e){if(!(e==null||e instanceof Date||Array.isArray(e)))return typeof e==`object`?e:void 0}function iT(e){return e?e.some(e=>e.type===`image_inline`||e.type===`image_uri`):!1}function aT(e){if(!e)return[];let t=[];for(let n of e)n.type===`image_inline`&&t.push({kind:`uri`,uri:`data:${n.mimeType};base64,${n.data}`,mimeType:n.mimeType});return t}function oT(e){let t=e.indexOf(`,`);if(t<0)return;let n=e.slice(0,t),r=e.slice(t+1);if(!n.endsWith(`;base64`))return;let i=n.replace(`data:`,``).replace(`;base64`,``).trim();if(!(i.length===0||r.trim().length===0))return{mimeType:i,data:r}}function sT(e){if(e.kind===`inline`)return e.mimeType.trim().length===0||e.data.trim().length===0?{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Inline image source requires non-empty mimeType and data.`}}:{ok:!0,value:{type:`image_inline`,mimeType:e.mimeType,data:e.data}};if(!e.uri.startsWith(`data:`))return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Google image provider supports only inline or data URI input sources.`}};let t=oT(e.uri);return t?{ok:!0,value:{type:`image_inline`,mimeType:t.mimeType,data:t.data}}:{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Data URI source must use base64 payload.`}}}function cT(e,t,n){return n&&n.length>0?n:e.some(e=>iT(e.parts))?[`TEXT`,`IMAGE`]:t&&t.length>0?t:[`TEXT`]}function lT(e,t){return!t||t.length===0?!0:t.includes(e)}function uT(e,t,n){gT(t);let r=cT(e,t.defaultResponseModalities,n?.google?.responseModalities);dT(n?.model,r,t);let i={responseModalities:r};return fT(i,n),pT(i,t,n),mT(i,t),hT(i,t),i}function dT(e,t,n){if(!(!e||!t.includes(`IMAGE`))&&!lT(e,n.imageCapableModels))throw Error(`Selected model "${e}" is not configured as image-capable for Google provider.`)}function fT(e,t){typeof t?.temperature==`number`&&(e.temperature=t.temperature),typeof t?.maxTokens==`number`&&(e.maxOutputTokens=t.maxTokens),typeof t?.google?.topP==`number`&&(e.topP=t.google.topP),typeof t?.google?.topK==`number`&&(e.topK=t.google.topK),typeof t?.google?.candidateCount==`number`&&(e.candidateCount=t.google.candidateCount),t?.google?.stopSequences&&t.google.stopSequences.length>0&&(e.stopSequences=t.google.stopSequences),t?.signal&&(e.abortSignal=t.signal)}function pT(e,t,n){let r=n?.google?.safetySettings??t.safetySettings;r&&r.length>0&&(e.safetySettings=r)}function mT(e,t){t.responseMimeType&&(e.responseMimeType=t.responseMimeType),t.responseSchema&&(e.responseMimeType=t.responseMimeType??`application/json`,e.responseSchema=t.responseSchema),t.responseJsonSchema&&(e.responseMimeType=t.responseMimeType??`application/json`,e.responseJsonSchema=t.responseJsonSchema)}function hT(e,t){t.thinkingConfig&&(e.thinkingConfig=t.thinkingConfig),t.toolConfig&&(e.toolConfig=t.toolConfig)}function gT(e){if(e.responseSchema&&e.responseJsonSchema)throw Error(`Gemini structured output options responseSchema and responseJsonSchema are mutually exclusive.`)}function _T(e){let t=[],n=e.parts??[];for(let e of n){if(e.type===`text`){t.push({text:e.text});continue}if(e.type===`image_inline`){t.push({inlineData:{mimeType:e.mimeType,data:e.data}});continue}throw Error(`Google provider does not support image URI parts directly: ${e.uri}`)}return t.length===0&&typeof e.content==`string`&&e.content.length>0&&t.push({text:e.content}),t}function vT(e){let t=[],n=[];for(let r of e){if(r.role===`user`){t.push({role:`user`,parts:_T(r)});continue}if(r.role===`assistant`){t.push(yT(r));continue}if(r.role===`tool`){t.push(bT(r));continue}let e=xT(r);e.length>0&&n.push(e)}return{contents:t,...n.length>0&&{systemInstruction:n.join(`
232
232
  `)}}}function yT(e){let t=[],n=_T(e);for(let e of n)t.push(e);return t.length===0&&e.content&&t.push({text:e.content}),e.toolCalls&&e.toolCalls.length>0&&e.toolCalls.forEach(e=>{t.push({functionCall:{id:e.id,name:e.function.name,args:CT(e.function.arguments)}})}),{role:`model`,parts:t}}function bT(e){return{role:`user`,parts:[{functionResponse:{id:e.toolCallId,name:ST(e),response:wT(e.content)}}]}}function xT(e){let t=_T(e);if(t.length===0)return e.content;let n=[];for(let e of t){if(typeof e.text==`string`){n.push(e.text);continue}throw Error(`Google provider system instructions support only text parts.`)}return n.join(`
233
- `)}function ST(e){let t=e.name?.trim();if(!t)throw Error(`Google provider tool message requires a function name.`);return t}function CT(e){let t=JSON.parse(e);if(!TT(t))throw Error(`Google provider tool call arguments must be a JSON object.`);return t}function wT(e){let t=e.trim();if(t.length===0)return{output:null};try{let e=JSON.parse(t);return TT(e)?e:{output:e}}catch{return{output:e}}}function TT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const ET={string:Ie.STRING,number:Ie.NUMBER,integer:Ie.INTEGER,boolean:Ie.BOOLEAN,array:Ie.ARRAY,object:Ie.OBJECT};function DT(e){return e.map(e=>({name:e.name,description:e.description,parameters:{type:Ie.OBJECT,properties:kT(e.parameters.properties),required:e.parameters.required}}))}function OT(e){return e===`auto`?{mode:Pe.AUTO}:e===`none`?{mode:Pe.NONE}:e===`required`?{mode:Pe.ANY}:{mode:Pe.ANY,allowedFunctionNames:[e.tool]}}function kT(e){let t={};for(let[n,r]of Object.entries(e))t[n]=AT(r);return t}function AT(e){let t={},n=jT(e.type);return n&&(t.type=n),e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum.map(String)),e.items&&(t.items=AT(e.items)),e.properties&&(t.properties=kT(e.properties)),typeof e.minimum==`number`&&(t.minimum=e.minimum),typeof e.maximum==`number`&&(t.maximum=e.maximum),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.default!==void 0&&(t.default=e.default),t}function jT(e){if(e!==`null`)return ET[e]}function MT(){return`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function NT(e){let t=e.candidates?.[0];if(!t)throw Error(`No candidate in Gemini response`);let n=t.content;if(!n||!n.parts||n.parts.length===0)throw Error(`No content in Gemini response`);let r=PT(n.parts),i={id:l(),state:`complete`,role:`assistant`,content:r.textValues.length>0?r.textValues.join(``):null,parts:r.messageParts,timestamp:new Date};if(r.functionCalls.length>0){let e=i;e.toolCalls=r.functionCalls.map(e=>({id:e.id??MT(),type:`function`,function:{name:RT(e),arguments:JSON.stringify(e.args??{})}}))}let a=LT(e);return a&&(i.metadata=a),i}function PT(e){let t=[],n=[],r=[];for(let i of e)FT(i,t,n),IT(i,n),i.functionCall&&r.push(i.functionCall);return{textValues:t,messageParts:n,functionCalls:r}}function FT(e,t,n){typeof e.text==`string`&&(t.push(e.text),n.push({type:`text`,text:e.text}))}function IT(e,t){!e.inlineData||typeof e.inlineData.data!=`string`||typeof e.inlineData.mimeType!=`string`||t.push({type:`image_inline`,data:e.inlineData.data,mimeType:e.inlineData.mimeType})}function LT(e){if(!(!e.usageMetadata||typeof e.usageMetadata.promptTokenCount!=`number`||typeof e.usageMetadata.candidatesTokenCount!=`number`||typeof e.usageMetadata.totalTokenCount!=`number`))return{promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,totalTokens:e.usageMetadata.totalTokenCount}}function RT(e){if(!e.name||e.name.trim().length===0)throw Error(`Gemini function call is missing a function name.`);return e.name}async function zT(e,t,n,r,i=`gemini`){let a=HT(t,r),o=cT(n,t.defaultResponseModalities,r?.google?.responseModalities);if(r?.onTextDelta&&!o.includes(`IMAGE`))return UT(e,t,n,r,i);let s=vT(n),c=uT(n,t,{...r,model:a}),l=VT(a,s.contents,c,r,s.systemInstruction);WT(r,i,`request`,l);let u=await e.models.generateContent(l);WT(r,i,`response`,u);let d=NT(u);if(o.includes(`IMAGE`)&&!iT(d.parts))throw Error(`Gemini response did not include an image part while IMAGE modality was requested.`);return d}async function*BT(e,t,n,r,i=`gemini`){let a=HT(t,r);if(cT(n,t.defaultResponseModalities,r?.google?.responseModalities).includes(`IMAGE`))throw Error(`Google provider does not support streaming image modality responses.`);let o=vT(n),s=uT(n,t,{...r,model:a}),c=VT(a,o.contents,s,r,o.systemInstruction);WT(r,i,`request`,c);let u=await e.models.generateContentStream(c),d=0;for await(let e of u){WT(r,i,`stream_event`,e,d),d++;let t=GT(e);t&&(r?.onTextDelta?.(t),yield{id:l(),role:`assistant`,content:t,state:`complete`,timestamp:new Date})}}function VT(e,t,n,r,i){let a={...n};return r?.tools&&r.tools.length>0&&(a.tools=[{functionDeclarations:DT(r.tools)}],r.toolChoice!==void 0&&(a.toolConfig={functionCallingConfig:OT(r.toolChoice)})),i&&(a.systemInstruction=i),r?.responseFormat?.type===`json_schema`?(a.responseMimeType=`application/json`,a.responseSchema=r.responseFormat.schema):r?.responseFormat?.type===`json_object`&&(a.responseMimeType=`application/json`),{model:e,contents:t,config:a}}function HT(e,t){let n=t?.model??e.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);return n}async function UT(e,t,n,r,i=`gemini`){let a=[];for await(let o of BT(e,t,n,r,i))typeof o.content==`string`&&a.push(o.content);let o=a.join(``);return{id:l(),role:`assistant`,content:o,parts:o.length>0?[{type:`text`,text:o}]:[],state:`complete`,timestamp:new Date}}function WT(e,t,n,r,i){e?.onProviderNativeRawPayload?.({provider:t,apiSurface:`gemini-generate-content`,payloadKind:n,...i!==void 0&&{sequence:i},payload:r})}function GT(e){let t=e.text;return typeof t==`function`?t():t}async function KT(e,t,n){try{let r=aT((await e(t,{model:n,google:{responseModalities:[`TEXT`,`IMAGE`]}})).parts);return r.length===0?{ok:!1,error:{code:`PROVIDER_UPSTREAM_ERROR`,message:`Google image response did not include image output parts.`}}:{ok:!0,value:{outputs:r,model:n}}}catch(e){return{ok:!1,error:{code:`PROVIDER_UPSTREAM_ERROR`,message:e instanceof Error?e.message:`Google image request failed.`}}}}var qT=class extends Ft{name=`gemini`;version=`1.0.0`;onTextDelta;client;options;constructor(e){super(),this.options=e,e.executor&&(this.executor=e.executor),this.executor||(this.client=new Fe({apiKey:e.apiKey}))}async chat(e,t){if(this.validateMessages(e),this.executor)try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`Gemini Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Google client not available. Either provide apiKey or use an executor.`);try{return await zT(this.client,this.options,e,this.withProviderCallbacks(t),this.name)}catch(e){let t=e instanceof Error?e.message:`Google API request failed`;throw Error(`Google chat failed: ${t}`)}}async*chatStream(e,t){if(this.validateMessages(e),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`Gemini Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Google client not available. Either provide apiKey or use an executor.`);try{yield*BT(this.client,this.options,e,this.withProviderCallbacks(t),this.name)}catch(e){let t=e instanceof Error?e.message:`Google API request failed`;throw Error(`Google stream failed: ${t}`)}}async generateImage(e){if(e.prompt.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image generation requires a non-empty prompt.`}};if(e.model.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image generation requires a non-empty model.`}};let t={id:l(),role:`user`,content:e.prompt,state:`complete`,parts:[{type:`text`,text:e.prompt}],timestamp:new Date};return KT(this.chat.bind(this),[t],e.model)}async editImage(e){if(e.prompt.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image edit requires a non-empty prompt.`}};if(e.model.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image edit requires a non-empty model.`}};let t=sT(e.image);if(!t.ok)return t;let n={id:l(),role:`user`,content:e.prompt,state:`complete`,parts:[t.value,{type:`text`,text:e.prompt}],timestamp:new Date};return KT(this.chat.bind(this),[n],e.model)}async composeImage(e){if(e.prompt.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image compose requires a non-empty prompt.`}};if(e.model.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image compose requires a non-empty model.`}};if(e.images.length<2)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image compose requires at least two input images.`}};let t=[];for(let n of e.images){let e=sT(n);if(!e.ok)return e;t.push(e.value)}t.push({type:`text`,text:e.prompt});let n={id:l(),role:`user`,content:e.prompt,state:`complete`,parts:t,timestamp:new Date};return KT(this.chat.bind(this),[n],e.model)}supportsTools(){return!0}validateConfig(){return this.executor?this.executor.validateConfig():!!this.client&&!!this.options&&!!this.options.apiKey}async dispose(){}withProviderCallbacks(e){let t=e?.onTextDelta??this.onTextDelta;return t?{...e,onTextDelta:t}:e}};const JT=`$ENV:GEMINI_API_KEY`,YT=`gemini-3-flash-preview`,XT=`https://ai.google.dev/api/models`,ZT=`2026-05-04`,QT=[{kind:`api-key`,label:`Google AI Studio API keys`,url:`https://aistudio.google.com/apikey`,sourceUrl:`https://ai.google.dev/gemini-api/docs/api-key`,lastVerifiedAt:`2026-05-08`}];function $T(){return{type:`gemini`,aliases:[`google`],displayName:`Gemini`,description:`Google Gemini series — free tier available.`,category:`cloud-free`,defaults:{model:YT,apiKey:JT},modelCatalog:{status:`fallback`,sourceUrl:XT,lastVerifiedAt:ZT,entries:[{id:YT,displayName:`Gemini 3 Flash Preview`,capabilities:[`tools`,`vision`,`json_schema`,`reasoning`,`streaming`],lifecycle:`preview`,sourceUrl:XT,lastVerifiedAt:ZT}]},setupHelpLinks:QT,setupSteps:[{key:`model`,title:`Gemini model`,defaultValue:YT},{key:`apiKey`,title:`Gemini API key`,defaultValue:JT,masked:!0}],requiresApiKey:!0,refreshModelCatalog:({profile:e})=>nE(e),modelCatalogCacheTtlSeconds:86400,createProvider:e=>new qT({apiKey:eE(e.apiKey),defaultModel:e.model})}}function eE(e){if(!e)throw Error(`Provider gemini requires apiKey`);return e}const tE=`https://generativelanguage.googleapis.com/v1beta/models`;async function nE(e,t=aE){let n=await t(e.apiKey?`${tE}?key=${e.apiKey}`:tE);if(!n.ok)return{status:`unavailable`,sourceUrl:XT,message:`Gemini model refresh failed: HTTP ${n.status}`};let r=((await n.json()).models??[]).filter(rE).map(iE);return{status:`live`,sourceUrl:XT,lastVerifiedAt:new Date().toISOString(),entries:r,message:`Fetched ${r.length} Gemini models`}}function rE(e){return e.supportedGenerationMethods?.includes(`generateContent`)===!0}function iE(e){let t=e.name??``,n=t.startsWith(`models/`)?t.slice(7):t,r=t.includes(`preview`)?`preview`:`active`;return{id:n,displayName:e.displayName??n,lifecycle:r,sourceUrl:XT,lastVerifiedAt:ZT}}async function aE(e,t){let n=await fetch(e);return{ok:n.ok,status:n.status,json:()=>n.json()}}const oE=`<|channel>`;function sE(e){let t=lE(e,{final:!0});return{rawText:e,visibleText:t.visibleParts.join(``),removedReasoning:t.removedReasoning}}var cE=class{buffer=``;emittedVisibleText=``;hasRemovedReasoning=!1;get rawText(){return this.buffer}get removedReasoning(){return this.hasRemovedReasoning}project(e){return e.length===0?``:(this.buffer+=e,this.projectVisibleText({final:!1}))}flush(){return this.projectVisibleText({final:!0})}projectVisibleText(e){let t=lE(this.buffer,e);this.hasRemovedReasoning=this.hasRemovedReasoning||t.removedReasoning;let n=t.visibleParts.join(``),r=n.slice(this.emittedVisibleText.length);return this.emittedVisibleText=n,r}};function lE(e,t){let n={visibleParts:[],removedReasoning:!1},r=0;for(;r<e.length;){let i=e.indexOf(oE,r);if(i===-1){uE(n,e.slice(r),t);break}uE(n,e.slice(r,i),t);let a=i+10,o=e.indexOf(`<channel|>`,a);if(o===-1){t.final&&(n.removedReasoning=!0);break}n.removedReasoning=!0,r=dE(e,a,o)}return n}function uE(e,t,n){if(t.length===0)return;if(n.final){e.visibleParts.push(t);return}let r=fE(t);e.visibleParts.push(t.slice(0,t.length-r))}function dE(e,t,n){let r=e.slice(t,n),i=n+10;if(r.trim().length===0){let t=e.slice(i).match(/^thought(?:\r?\n)*/);return t&&(i+=t[0].length),i}return r.split(/\r?\n/,1)[0]?.trim(),i}function fE(e){let t=Math.min(e.length,9);for(let n=t;n>0;--n)if(oE.startsWith(e.slice(e.length-n)))return n;return 0}function pE(e){return[`<`]}function mE(e,t,n){return e.indexOf(`<`,t)}function hE(e,t){return+!!e.endsWith(`<`)}function gE(e,t){let n=e.indexOf(`>`,t+1);if(n===-1)return;let r=e.slice(t,n+1),i=r.match(/^<\s*([A-Za-z][\w:-]*)([\s/>][\s\S]*?|)>$/);if(!i)return;let a=i[1]??``;return{tagName:a,normalizedName:a.toLowerCase(),rawOpenTag:r,attributes:bE(i[2]??``),openEnd:n+1,selfClosing:/\/\s*>$/.test(r)}}function _E(e,t,n){if(t.selfClosing)return{innerText:``,end:t.openEnd,complete:!0};let r=CE(e,t.tagName,t.openEnd);if(r===-1)return{innerText:e.slice(t.openEnd),end:n.final?e.length:t.openEnd-t.rawOpenTag.length,complete:!1};let i=e.indexOf(`>`,r);return{innerText:e.slice(t.openEnd,r),end:i===-1?e.length:i+1,complete:!0}}function vE(e,t){if(t.selfClosing)return{rawText:t.rawOpenTag,end:t.openEnd};let n=CE(e,t.tagName,t.openEnd);if(n===-1)return{rawText:t.rawOpenTag,end:t.openEnd};let r=e.indexOf(`>`,n),i=r===-1?e.length:r+1;return{rawText:e.slice(t.openEnd-t.rawOpenTag.length,i),end:i}}function yE(e,t){let n=wE(e);return t.find(e=>wE(e)===n)}function bE(e){let t={},n=/([A-Za-z_][\w:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,r=n.exec(e);for(;r;){let i=r[1]??``;t[i]=xE(SE(r[2]??r[3]??``)),r=n.exec(e)}return t}function xE(e){return e===`true`?!0:e===`false`?!1:e===`null`?null:/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e)?Number(e):e}function SE(e){return e.replace(/&quot;/g,`"`).replace(/&apos;/g,`'`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`)}function CE(e,t,n){return e.toLowerCase().indexOf(`</${t.toLowerCase()}>`,n)}function wE(e){return e.replace(/[^a-z0-9]/gi,``).toLowerCase()}function TE(e,t){let n=EE(e,t);return n?[n]:[]}function EE(e,t){let n=e.indexOf(`>`),r=e.lastIndexOf(`</`);if(n===-1||r===-1||r<=n)return;let i=DE(e.slice(n+1,r).trim());if(!OE(i))return;let a=i.command,o=i.args;if(typeof a!=`string`||!OE(o))return;let s=yE(a,t);if(s)return{toolName:s,args:o}}function DE(e){try{return JSON.parse(e)}catch{return}}function OE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kE(e,t,n){let r=zE(),i=pE(t.toolNames),a=0;for(;a<e.length;){let o=mE(e,a,i);if(o===-1){FE(r,e.slice(a),n,i);break}FE(r,e.slice(a,o),n,i);let s=AE(e,o,r,t,n);if(!s.completed)break;a=s.cursor}return{visibleText:r.visibleParts.join(``),toolCalls:r.toolCalls,rawToolCallTextParts:r.rawToolCallTextParts,removedToolCallText:r.removedToolCallText}}function AE(e,t,n,r,i){let a=gE(e,t);if(!a)return jE(e,t,n,i);let o=yE(a.tagName,r.toolNames);return o?PE(e,a,o,n,r):ME(e,t,a,n,r,i)}function jE(e,t,n,r){return r.final?(n.visibleParts.push(e[t]??``),{cursor:t+1,completed:!0}):{cursor:t,completed:!1}}function ME(e,t,n,r,i,a){let o=_E(e,n,a);if(!o.complete&&!a.final)return{cursor:t,completed:!1};let s=e.slice(t,o.end),c=r.rawToolCallTextParts.length;return r.removedToolCallText=!0,LE(r,s,i),BE(r,NE(o,r,i)),r.rawToolCallTextParts.length===c&&r.rawToolCallTextParts.push(s),{cursor:o.end,completed:!0}}function NE(e,t,n){return kE(e.innerText,{...n,startCallIndex:VE(t,n)},{final:!0})}function PE(e,t,n,r,i){let a=vE(e,t);return IE(r,n,t.attributes,a.rawText,i),{cursor:a.end,completed:!0}}function FE(e,t,n,r){if(t.length===0)return;if(n.final){e.visibleParts.push(t);return}let i=hE(t,r);e.visibleParts.push(t.slice(0,t.length-i))}function IE(e,t,n,r,i){Object.keys(n).length!==0&&(e.toolCalls.push(RE(t,n,i,e)),e.rawToolCallTextParts.push(r),e.removedToolCallText=!0)}function LE(e,t,n){let r=TE(t,n.toolNames);for(let i of r)e.toolCalls.push(RE(i.toolName,i.args,n,e)),e.rawToolCallTextParts.push(t)}function RE(e,t,n,r){return{id:`${n.callIdPrefix??`gemma_call`}_${VE(r,n)}`,type:`function`,function:{name:e,arguments:JSON.stringify(t)}}}function zE(){return{visibleParts:[],toolCalls:[],rawToolCallTextParts:[],removedToolCallText:!1}}function BE(e,t){e.toolCalls.push(...t.toolCalls),e.rawToolCallTextParts.push(...t.rawToolCallTextParts),e.removedToolCallText=e.removedToolCallText||t.removedToolCallText}function VE(e,t){return(t.startCallIndex??0)+e.toolCalls.length}const HE=`<|"|>`;var UE=class{source;cursor=0;constructor(e){this.source=e}parse(){let e=this.parseObject();if(this.skipWhitespace(),this.cursor===this.source.length)return e}parseObject(){if(!this.consume(`{`))return;let e={};if(this.skipWhitespace(),this.consume(`}`))return e;for(;this.cursor<this.source.length;){let t=this.parseKey();if(!t||!this.consume(`:`))return;let n=this.parseValue();if(n===void 0)return;if(e[t]=n,this.skipWhitespace(),this.consume(`}`))return e;if(!this.consume(`,`))return}}parseArray(){if(!this.consume(`[`))return;let e=[];if(this.skipWhitespace(),this.consume(`]`))return e;for(;this.cursor<this.source.length;){let t=this.parseValue();if(t===void 0)return;if(e.push(t),this.skipWhitespace(),this.consume(`]`))return e;if(!this.consume(`,`))return}}parseValue(){return this.skipWhitespace(),this.source.startsWith(HE,this.cursor)?this.parseString():this.source.startsWith(`{`,this.cursor)?this.parseObject():this.source.startsWith(`[`,this.cursor)?this.parseArray():this.consumeLiteral(`true`)?!0:this.consumeLiteral(`false`)?!1:this.consumeLiteral(`null`)?null:this.parseNumber()}parseKey(){if(this.skipWhitespace(),this.source.startsWith(HE,this.cursor))return this.parseString();let e=/^[A-Za-z_][A-Za-z0-9_-]*/.exec(this.source.slice(this.cursor));if(e)return this.cursor+=e[0].length,this.skipWhitespace(),e[0]}parseString(){if(!this.consume(HE))return;let e=this.source.indexOf(HE,this.cursor);if(e===-1)return;let t=this.source.slice(this.cursor,e);return this.cursor=e+5,this.skipWhitespace(),t}parseNumber(){let e=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(this.source.slice(this.cursor));if(e)return this.cursor+=e[0].length,this.skipWhitespace(),Number(e[0])}consume(e){return this.skipWhitespace(),this.source.startsWith(e,this.cursor)?(this.cursor+=e.length,this.skipWhitespace(),!0):!1}consumeLiteral(e){return this.source.startsWith(e,this.cursor)?(this.cursor+=e.length,this.skipWhitespace(),!0):!1}skipWhitespace(){for(;/\s/.test(this.source[this.cursor]??``);)this.cursor+=1}};const WE=`<|tool_call>`,GE=`gemma_call`;function KE(e){if(!(!e||e.length===0))return new qE({toolNames:e.map(e=>e.name)})}var qE=class{options;buffer=``;emittedVisibleText=``;emittedRawToolCallText=``;emittedToolCallIds=new Set;constructor(e){this.options=e}project(e){return e.length===0?eD():(this.buffer+=e,this.projectVisibleText({final:!1}))}flush(){return this.projectVisibleText({final:!0})}projectVisibleText(e){let t=JE(this.buffer,this.options,e),n=t.visibleParts.join(``),r=n.slice(this.emittedVisibleText.length),i=t.rawToolCallTextParts.join(``),a=i.slice(this.emittedRawToolCallText.length);return this.emittedVisibleText=n,this.emittedRawToolCallText=i,{visibleText:r,toolCalls:t.toolCalls.filter(e=>this.emittedToolCallIds.has(e.id)?!1:(this.emittedToolCallIds.add(e.id),!0)),removedToolCallText:a.length>0,...a.length>0&&{rawToolCallText:a}}}};function JE(e,t,n){let r=YE(e,t,n),i=kE(r.visibleParts.join(``),{toolNames:t.toolNames,callIdPrefix:t.callIdPrefix??GE,startCallIndex:r.toolCalls.length},n);return{visibleParts:[i.visibleText],toolCalls:[...r.toolCalls,...i.toolCalls],rawToolCallTextParts:[...r.rawToolCallTextParts,...i.rawToolCallTextParts],removedToolCallText:r.removedToolCallText||i.removedToolCallText}}function YE(e,t,n){let r=ZE(),i=new Set(t.toolNames),a=0,o=0;for(;a<e.length;){let s=e.indexOf(WE,a);if(s===-1){QE(r,e.slice(a),n);break}QE(r,e.slice(a,s),n);let c=s+12,l=e.indexOf(`<tool_call|>`,c);if(l===-1){n.final&&r.visibleParts.push(e.slice(s));break}let u=e.slice(s,l+12),d=XE(e.slice(c,l),i,t,o);d?(r.toolCalls.push(d),r.rawToolCallTextParts.push(u),r.removedToolCallText=!0,o+=1):r.visibleParts.push(u),a=l+12}return r}function XE(e,t,n,r){let i=e.trim();if(!i.startsWith(`call:`))return;let a=i.slice(5).trimStart(),o=a.indexOf(`{`);if(o<=0)return;let s=a.slice(0,o).trim();if(!t.has(s))return;let c=new UE(a.slice(o)).parse();if(c)return{id:`${n.callIdPrefix??GE}_${r}`,type:`function`,function:{name:s,arguments:JSON.stringify(c)}}}function ZE(){return{visibleParts:[],toolCalls:[],rawToolCallTextParts:[],removedToolCallText:!1}}function QE(e,t,n){if(t.length===0)return;if(n.final){e.visibleParts.push(t);return}let r=$E(t);e.visibleParts.push(t.slice(0,t.length-r))}function $E(e){let t=Math.min(e.length,11);for(let n=t;n>0;--n)if(WE.startsWith(e.slice(e.length-n)))return n;return 0}function eD(){return{visibleText:``,toolCalls:[],removedToolCallText:!1}}function tD(e,t,n){let r=e.choices?.[0]?.message.content||``,i=new WS({logger:t,...n?.tools&&{toolCallTextProjector:KE(n.tools)}}).parseResponse(e),a=sE(i.content??``);return nD({...i,content:a.visibleText},r,a.removedReasoning)}function nD(e,t,n){return n?{...e,metadata:{...e.metadata??{},gemmaReasoningFiltered:!0,gemmaRawContent:t}}:e}function rD(e,t){return{id:l(),role:`assistant`,content:e,state:`complete`,timestamp:new Date,metadata:{isStreamChunk:!0,isComplete:t===`stop`||t===`tool_calls`}}}function iD(e,t){return{id:l(),role:`assistant`,content:``,toolCalls:e,state:`complete`,timestamp:new Date,metadata:{isStreamChunk:!0,isComplete:t===`stop`||t===`tool_calls`}}}function aD(e,t){return{reasoningProjector:new cE,responseParser:new WS({logger:e}),...t&&{toolCallProjector:KE(t)}}}function oD(e,t){let n=e.choices?.[0];if(!n)return[];let r=t.responseParser.parseStreamingChunk(e);return r&&Et(r)&&r.toolCalls?.length?[r]:cD(n.delta.content||``,n.finish_reason,t)}function sD(e){let t=cD(``,null,e,!0),n=e.reasoningProjector.flush();return n.length>0&&t.push(rD(n,null)),t}function cD(e,t,n,r=!1){let i=r?n.toolCallProjector?.flush():n.toolCallProjector?.project(e),a=[];i?.toolCalls.length&&a.push(iD(i.toolCalls,t));let o=i?.visibleText??e,s=n.reasoningProjector.project(o);return s.length>0&&a.push(rD(s,t)),a}var lD=class extends Ft{name=`gemma`;version=`1.0.0`;client;options;onTextDelta;constructor(e){if(super(e.logger||kt),this.options=e,e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client;else if(e.apiKey)this.client=new Ne({apiKey:e.apiKey,...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout}});else throw Error(`Either Gemma client, apiKey, or executor is required`)}async chat(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`Gemma Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Gemma client not available. Either provide a client/apiKey or use an executor.`);try{let n=this.buildRequestParams(e,t),r=t?.onTextDelta??this.onTextDelta;if(r)return await this.chatWithStreamingAssembly({...n,stream:!0},{...t,onTextDelta:r});t?.onProviderNativeRawPayload?.({provider:`gemma`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let i=await this.client.chat.completions.create(n);return t?.onProviderNativeRawPayload?.({provider:`gemma`,apiSurface:`chat-completions`,payloadKind:`response`,payload:i}),tD(i,this.logger,t)}catch(e){let t=e.message||`Gemma API request failed`;throw Error(`Gemma chat failed: ${t}`)}}async*chatStream(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`Gemma Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Gemma client not available. Either provide a client/apiKey or use an executor.`);try{let n=this.buildStreamingRequestParams(e,t);t?.onProviderNativeRawPayload?.({provider:`gemma`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let r=await this.client.chat.completions.create(n),i=aD(this.logger,t?.tools),a=aC(r,{provider:`gemma`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t?.onProviderNativeRawPayload});for await(let e of this.streamWithAbort(a,t?.signal))for(let t of oD(e,i))yield t;for(let e of sD(i))yield e}catch(e){let t=e.message||`Gemma API request failed`;throw Error(`Gemma stream failed: ${t}`)}}supportsTools(){return!0}getCapabilities(){return{functionCalling:{supported:!0},nativeWebTools:{webSearch:{supported:!1,enabled:!1,source:`openai-compatible-chat-completions`,reason:`Gemma OpenAI-compatible endpoints support declared function tools, not provider-native web search.`},webFetch:{supported:!1,enabled:!1,source:`openai-compatible-chat-completions`,reason:`Gemma OpenAI-compatible endpoints support declared function tools, not provider-native web fetch.`}}}}validateConfig(){return!!this.client&&!!this.options}async dispose(){}validateMessages(e){super.validateMessages(e);for(let t of e)if(t.role===`assistant`){let e=t;if(e.toolCalls&&e.toolCalls.length>0&&e.content===``)continue}}buildRequestParams(e,t){let n=t?.model??this.options.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);return{model:n,messages:zS(e),...t?.temperature!==void 0&&{temperature:t.temperature},...t?.maxTokens!==void 0&&{max_tokens:t.maxTokens},...t?.tools&&{tools:BS(t.tools),tool_choice:cC(t.toolChoice)}}}buildStreamingRequestParams(e,t){return{...this.buildRequestParams(e,t),stream:!0}}async chatWithStreamingAssembly(e,t){if(!this.client)throw Error(`Gemma client not available. Either provide a client/apiKey or use an executor.`);try{t.onProviderNativeRawPayload?.({provider:`gemma`,apiSurface:`chat-completions`,payloadKind:`request`,payload:e});let n=await this.client.chat.completions.create(e,t.signal?{signal:t.signal}:void 0),r=new cE;return nD(await GS({stream:aC(n,{provider:`gemma`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t.onProviderNativeRawPayload}),onTextDelta:t.onTextDelta,signal:t.signal,textProjector:e=>r.project(e),textProjectorFlush:()=>r.flush(),toolCallTextProjector:KE(t.tools)}),r.rawText,r.removedReasoning)}catch(e){let t=e.message||`Gemma streaming request failed`;throw Error(`Gemma stream failed: ${t}`)}}};const uD=`supergemma4-26b-uncensored-v2`,dD=`lm-studio`,fD=`http://localhost:1234/v1`,pD=`https://ai.google.dev/gemma`,mD=`2026-05-04`,hD=`https://lmstudio.ai/docs/developer`,gD=[{kind:`official`,label:`LM Studio local API documentation`,url:hD,sourceUrl:hD,lastVerifiedAt:`2026-05-08`}],_D={status:`fallback`,sourceUrl:pD,lastVerifiedAt:mD,entries:[{id:uD,displayName:`SuperGemma 4 26B`,capabilities:[`tools`,`streaming`],lifecycle:`active`,sourceUrl:pD,lastVerifiedAt:mD}]};function vD(){return{type:`gemma`,displayName:`Ollama / LM Studio / llama.cpp`,description:`Local models via LM Studio or Ollama. No API key needed.`,category:`local-free`,defaults:{model:uD,apiKey:dD,baseURL:fD},modelCatalog:_D,setupHelpLinks:gD,setupSteps:[{key:`baseURL`,title:`Gemma OpenAI-compatible base URL`,defaultValue:fD},{key:`model`,title:`Gemma model`,defaultValue:uD},{key:`apiKey`,title:`Gemma OpenAI-compatible API key`,defaultValue:dD,masked:!0}],requiresApiKey:!0,probeProfile:oC,createProvider:e=>new lD({apiKey:yD(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},defaultModel:e.model})}}function yD(e){if(!e)throw Error(`Provider gemma requires apiKey`);return e}const bD={singapore:`https://dashscope-intl.aliyuncs.com/compatible-mode/v1`,usVirginia:`https://dashscope-us.aliyuncs.com/compatible-mode/v1`,beijing:`https://dashscope.aliyuncs.com/compatible-mode/v1`,hongKong:`https://cn-hongkong.dashscope.aliyuncs.com/compatible-mode/v1`},xD={singapore:`https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1`,usVirginia:`https://dashscope-us.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1`,beijing:`https://dashscope.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1`},SD=`qwen-plus`,CD=`$ENV:DASHSCOPE_API_KEY`,wD=bD.singapore,TD=xD.singapore,ED=`https://www.alibabacloud.com/help/en/model-studio/compatibility-of-openai-with-dashscope`,DD=`2026-05-04`,OD=`qwen-responses`;function kD(e){let t=e.builtInWebTools,n=t?.webSearch===!0||t?.webFetch===!0,r=t?.webFetch===!0;return{functionCalling:{supported:!0},nativeWebTools:{webSearch:n?{supported:!0,enabled:!0,source:OD}:{supported:!0,enabled:!1,source:OD,reason:`Enable builtInWebTools.webSearch or builtInWebTools.webFetch.`},webFetch:r?{supported:!0,enabled:!0,source:OD}:{supported:!0,enabled:!1,source:OD,reason:`Enable builtInWebTools.webFetch.`}}}}async function AD(e,t,n){try{return n.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`chat-completions`,payloadKind:`request`,payload:t}),GS({stream:aC(await e.chat.completions.create(t,n.signal?{signal:n.signal}:void 0),{provider:`qwen`,apiSurface:`chat-completions`,onProviderNativeRawPayload:n.onProviderNativeRawPayload}),onTextDelta:n.onTextDelta,signal:n.signal})}catch(e){let t=e.message||`Qwen streaming request failed`;throw Error(`Qwen stream failed: ${t}`)}}function jD(e){let t=[];return(e?.webSearch===!0||e?.webFetch===!0)&&t.push(`web_search`),e?.webFetch===!0&&t.push(`web_extractor`),t}function MD(e){return jD(e).length>0}function ND(e){return e.flatMap(e=>ID(e))}function PD(e,t){let n=[...e.map(e=>({type:e})),...FD(t)];return n.length>0?n:void 0}function FD(e){return e?.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters}))??[]}function ID(e){return e.role===`user`?[RD(`user`,e.content)]:e.role===`system`?[RD(`system`,e.content)]:e.role===`tool`?[{type:`function_call_output`,call_id:e.toolCallId,output:e.content||``}]:LD(e)}function LD(e){let t=[];e.content&&e.content.length>0&&t.push(RD(`assistant`,e.content));for(let n of e.toolCalls??[])t.push({type:`function_call`,call_id:n.id,name:n.function.name,arguments:n.function.arguments});return t.length===0&&t.push(RD(`assistant`,``)),t}function RD(e,t){return{role:e,content:t??``}}async function*zD(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await BD(n,t);if(e.done||t?.aborted)break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async function BD(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}function VD(e,t){let n=e.output??[],r=YD(n,e.usage),i=eO(n);return KD({content:e.output_text??rO(n),toolCalls:i,response:e,usage:r,enabledBuiltInTools:t.enabledBuiltInTools})}async function HD(e){let t={textParts:[],toolCalls:[],usage:QD()};for await(let n of zD(e.stream,e.signal))UD(t,n,e.onTextDelta);return t.completedResponse===void 0?KD({content:t.textParts.join(``),toolCalls:t.toolCalls,usage:t.usage,enabledBuiltInTools:e.enabledBuiltInTools}):WD(t,e.enabledBuiltInTools)}function UD(e,t,n){if(t.type===`response.output_text.delta`){e.textParts.push(t.delta),n?.(t.delta);return}if(t.type===`response.completed`){e.completedResponse=t.response,ZD(e.usage,YD(t.response.output??[],t.response.usage));return}if(t.type===`response.output_item.done`){GD(e,t.item);return}if(t.type===`response.web_search_call.completed`){e.usage.webSearchCalls+=1;return}if(t.type===`response.error`||t.type===`response.failed`)throw Error(`Qwen Responses API failed: ${iO(t)}`)}function WD(e,t){let n=e.completedResponse;if(n===void 0)throw Error(`Qwen Responses stream completed without response metadata`);let r=n.output??[],i=eO(r),a=e.textParts.length>0?e.textParts.join(``):n.output_text??rO(r),o=YD(r,n.usage);return ZD(o,e.usage),KD({content:a,toolCalls:i.length>0?i:e.toolCalls,response:n,usage:o,enabledBuiltInTools:t})}function GD(e,t){if(t.type===`function_call`){tO(t)&&e.toolCalls.push(nO(t));return}ZD(e.usage,YD([t],void 0))}function KD(e){return{id:l(),role:`assistant`,content:e.content,state:`complete`,timestamp:new Date,...e.toolCalls.length>0&&{toolCalls:e.toolCalls},...e.response?.usage!==void 0&&{usage:{promptTokens:e.response.usage.input_tokens??0,completionTokens:e.response.usage.output_tokens??0,totalTokens:e.response.usage.total_tokens??0}},metadata:qD(e.enabledBuiltInTools,e.usage,e.response)}}function qD(e,t,n){let r=JD(t);return{providerToolMode:`qwen_responses`,providerBuiltInToolsEnabled:[...e],...r.length>0&&{providerBuiltInToolsUsed:r},qwenWebSearchCalls:t.webSearchCalls,qwenWebExtractorCalls:t.webExtractorCalls,...t.unsupportedToolTypes.size>0&&{qwenUnsupportedProviderToolTypes:[...t.unsupportedToolTypes].sort()},...n?.id!==void 0&&{responseId:n.id},...n?.model!==void 0&&{model:n.model},...n?.status!==void 0&&{finishReason:n.status}}}function JD(e){let t=[];return e.webSearchCalls>0&&t.push(`web_search`),e.webExtractorCalls>0&&t.push(`web_extractor`),t}function YD(e,t){let n=QD();for(let t of e)t.type===`web_search_call`?n.webSearchCalls+=1:t.type===`web_extractor_call`?n.webExtractorCalls+=1:$D(t.type)&&n.unsupportedToolTypes.add(t.type);return XD(n,t),n}function XD(e,t){let n=t?.x_tools;if(n!==void 0){e.webSearchCalls=Math.max(e.webSearchCalls,n.web_search?.count??0),e.webExtractorCalls=Math.max(e.webExtractorCalls,n.web_extractor?.count??0);for(let t of Object.keys(n))t!==`web_search`&&t!==`web_extractor`&&e.unsupportedToolTypes.add(t)}}function ZD(e,t){e.webSearchCalls=Math.max(e.webSearchCalls,t.webSearchCalls),e.webExtractorCalls=Math.max(e.webExtractorCalls,t.webExtractorCalls);for(let n of t.unsupportedToolTypes)e.unsupportedToolTypes.add(n)}function QD(){return{webSearchCalls:0,webExtractorCalls:0,unsupportedToolTypes:new Set}}function $D(e){return e.endsWith(`_call`)&&e!==`function_call`}function eO(e){return e.filter(tO).map(e=>nO(e))}function tO(e){return e.type===`function_call`&&`call_id`in e&&`name`in e&&`arguments`in e}function nO(e){return{id:e.call_id,type:`function`,function:{name:e.name,arguments:e.arguments}}}function rO(e){return e.filter(e=>e.type===`message`).flatMap(e=>e.content).map(e=>e.text).join(``)}function iO(e){return e.message??e.error?.message??e.response?.error?.message??`unknown error`}async function aO(e){let t=e.chatOptions?.onTextDelta??e.onTextDelta;if(t)return sO({...e,chatOptions:{...e.chatOptions,onTextDelta:t}});if(!e.client)throw Error(`Qwen Responses client not available for built-in web tools.`);try{let t=cO(e);e.chatOptions?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`responses`,payloadKind:`request`,payload:t});let n=await e.client.responses.create(t,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`responses`,payloadKind:`response`,payload:n}),VD(n,{enabledBuiltInTools:jD(e.builtInWebTools)})}catch(e){let t=e.message||`Qwen Responses API request failed`;throw Error(`Qwen responses failed: ${t}`)}}async function*oO(e){let t=[],n=await sO({...e,chatOptions:{...e.chatOptions,onTextDelta:n=>{e.chatOptions?.onTextDelta?.(n),t.push(uO(n))}}});for(let e of t)yield e;yield{...n,content:``,metadata:{...n.metadata,isStreamChunk:!0,isComplete:!0}}}async function sO(e){if(!e.client)throw Error(`Qwen Responses client not available for built-in web tools.`);try{let t=lO(e);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`responses`,payloadKind:`request`,payload:t}),HD({stream:aC(await e.client.responses.create(t,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0),{provider:`qwen`,apiSurface:`responses`,onProviderNativeRawPayload:e.chatOptions?.onProviderNativeRawPayload}),enabledBuiltInTools:jD(e.builtInWebTools),onTextDelta:e.chatOptions?.onTextDelta,signal:e.chatOptions?.signal})}catch(e){let t=e.message||`Qwen Responses streaming request failed`;throw Error(`Qwen responses stream failed: ${t}`)}}function cO(e){let t=e.chatOptions?.model??e.defaultModel;if(!t)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let n=PD(jD(e.builtInWebTools),e.chatOptions?.tools);return{model:t,input:ND(e.messages),...n!==void 0&&{tools:n},...n!==void 0&&e.chatOptions?.toolChoice!==void 0&&{tool_choice:lC(e.chatOptions.toolChoice)},...e.chatOptions?.temperature!==void 0&&{temperature:e.chatOptions.temperature},...e.chatOptions?.maxTokens!==void 0&&{max_output_tokens:e.chatOptions.maxTokens},...e.builtInWebTools?.enableThinking!==void 0&&{enable_thinking:e.builtInWebTools.enableThinking}}}function lO(e){return{...cO(e),stream:!0}}function uO(e){return{id:l(),role:`assistant`,content:e,state:`complete`,timestamp:new Date,metadata:{isStreamChunk:!0,isComplete:!1}}}var dO=class extends Ft{name=`qwen`;version=`1.0.0`;client;responsesClient;options;responseParser;onTextDelta;constructor(e){if(super(e.logger||kt),this.options=e,e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client,this.responsesClient=e.client;else if(e.apiKey)this.client=new Ne({apiKey:e.apiKey,baseURL:e.baseURL??wD,...e.timeout!==void 0&&{timeout:e.timeout}}),this.responsesClient=new Ne({apiKey:e.apiKey,baseURL:e.responsesBaseURL??TD,...e.timeout!==void 0&&{timeout:e.timeout}});else throw Error(`Either Qwen client, apiKey, or executor is required`);this.responseParser=new WS({logger:this.logger})}async chat(e,t){return this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor?this.chatViaExecutor(e,t):this.shouldUseResponsesApi()?this.chatViaResponsesApi(e,t,this.getResponsesClient()):this.chatViaChatCompletions(e,t,this.getClient())}async chatViaExecutor(e,t){try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`Qwen Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}}async chatViaResponsesApi(e,t,n){return this.validateTools(t?.tools),aO({client:n,messages:e,chatOptions:t,defaultModel:this.options.defaultModel,builtInWebTools:this.options.builtInWebTools,onTextDelta:this.onTextDelta})}async chatViaChatCompletions(e,t,n){try{let r=this.buildRequestParams(e,t),i=t?.onTextDelta??this.onTextDelta;if(i)return AD(n,{...r,stream:!0},{...t,onTextDelta:i});t?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`chat-completions`,payloadKind:`request`,payload:r});let a=await n.chat.completions.create(r);return t?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`chat-completions`,payloadKind:`response`,payload:a}),this.responseParser.parseResponse(a)}catch(e){let t=e.message||`Qwen API request failed`;throw Error(`Qwen chat failed: ${t}`)}}async*chatStream(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`Qwen Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Qwen client not available. Either provide a client/apiKey or use an executor.`);if(this.shouldUseResponsesApi()){this.validateTools(t?.tools),yield*oO({client:this.responsesClient,messages:e,chatOptions:t,defaultModel:this.options.defaultModel,builtInWebTools:this.options.builtInWebTools,onTextDelta:this.onTextDelta});return}try{let n=this.buildStreamingRequestParams(e,t);t?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let r=aC(await this.client.chat.completions.create(n),{provider:`qwen`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t?.onProviderNativeRawPayload});for await(let e of this.streamWithAbort(r,t?.signal)){let t=this.responseParser.parseStreamingChunk(e);t&&(yield t)}}catch(e){let t=e.message||`Qwen API request failed`;throw Error(`Qwen stream failed: ${t}`)}}supportsTools(){return!0}getCapabilities(){return kD(this.options)}validateConfig(){return!!this.client&&!!this.options&&(!this.shouldUseResponsesApi()||!!this.responsesClient)}async dispose(){}buildRequestParams(e,t){this.validateTools(t?.tools);let n=t?.model??this.options.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);return{model:n,messages:zS(e),...t?.temperature!==void 0&&{temperature:t.temperature},...t?.maxTokens!==void 0&&{max_tokens:t.maxTokens},...t?.tools&&{tools:BS(t.tools),tool_choice:cC(t.toolChoice)}}}buildStreamingRequestParams(e,t){return{...this.buildRequestParams(e,t),stream:!0}}shouldUseResponsesApi(){return MD(this.options.builtInWebTools)}getClient(){if(!this.client)throw Error(`Qwen client not available. Either provide a client/apiKey or use an executor.`);return this.client}getResponsesClient(){if(!this.responsesClient)throw Error(`Qwen Responses client not available for built-in web tools.`);return this.responsesClient}};async function fO(e,t=gO){let n=await t(`${hO(e.baseURL??wD)}/models`,pO(e.apiKey));if(!n.ok)return{status:`unavailable`,sourceUrl:ED,message:`Qwen model refresh failed: HTTP ${n.status}`};let r=((await n.json()).data??[]).map(e=>e.id).filter(e=>typeof e==`string`&&e.length>0).map(mO);return{status:`live`,sourceUrl:ED,lastVerifiedAt:DD,entries:r,message:`Loaded ${r.length} models from Qwen API`}}function pO(e){if(e)return{headers:{Authorization:`Bearer ${e}`}}}function mO(e){return{id:e,displayName:e,lifecycle:`active`,sourceUrl:ED,lastVerifiedAt:DD}}function hO(e){return e.replace(/\/$/,``)}async function gO(e,t){let n=await fetch(e,{...t?.headers!==void 0&&{headers:t.headers}});return{ok:n.ok,status:n.status,json:()=>n.json()}}const _O=[{kind:`api-key`,label:`Alibaba Cloud Model Studio API keys`,url:`https://modelstudio.console.alibabacloud.com/?tab=api#/api-key`,sourceUrl:`https://www.alibabacloud.com/help/en/model-studio/get-api-key`,lastVerifiedAt:`2026-05-08`}],vO={status:`fallback`,sourceUrl:ED,lastVerifiedAt:DD,entries:[{id:SD,displayName:`Qwen Plus`,capabilities:[`tools`,`reasoning`,`native_web`,`streaming`],lifecycle:`active`,sourceUrl:ED,lastVerifiedAt:DD},{id:`qwen-max`,displayName:`Qwen Max`,capabilities:[`tools`,`reasoning`,`native_web`,`streaming`],lifecycle:`active`,sourceUrl:ED,lastVerifiedAt:DD},{id:`qwen-flash`,displayName:`Qwen Flash`,capabilities:[`tools`,`native_web`,`streaming`],lifecycle:`active`,sourceUrl:ED,lastVerifiedAt:DD}]};function yO(){return{type:`qwen`,displayName:`Qwen`,description:`Alibaba Cloud Qwen series. API key required.`,category:`cloud-paid`,defaults:{model:SD,apiKey:CD,baseURL:wD},modelCatalog:vO,refreshModelCatalog:({profile:e})=>fO(e),modelCatalogCacheTtlSeconds:86400,setupHelpLinks:_O,setupSteps:[{key:`baseURL`,title:`Qwen OpenAI-compatible base URL`,defaultValue:wD},{key:`model`,title:`Qwen model`,defaultValue:SD},{key:`apiKey`,title:`Qwen Model Studio API key`,defaultValue:CD,masked:!0}],requiresApiKey:!0,probeProfile:oC,createProvider:e=>{let t=xO(e.options);return new dO({apiKey:bO(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...t.responsesBaseURL!==void 0&&{responsesBaseURL:t.responsesBaseURL},...e.timeout!==void 0&&{timeout:e.timeout},...t.builtInWebTools!==void 0&&{builtInWebTools:t.builtInWebTools},defaultModel:e.model})}}}function bO(e){if(!e)throw Error(`Provider qwen requires apiKey`);return e}function xO(e){let t=SO(CO(e?.builtInWebTools)),n=TO(e?.responsesBaseURL);return{...n!==void 0&&{responsesBaseURL:n},...t!==void 0&&{builtInWebTools:t}}}function SO(e){if(e!==void 0)return{...wO(e.webSearch)!==void 0&&{webSearch:wO(e.webSearch)},...wO(e.webFetch)!==void 0&&{webFetch:wO(e.webFetch)},...wO(e.enableThinking)!==void 0&&{enableThinking:wO(e.enableThinking)}}}function CO(e){if(!(e==null||e instanceof Date||Array.isArray(e)))return typeof e==`object`?e:void 0}function wO(e){return typeof e==`boolean`?e:void 0}function TO(e){return typeof e==`string`&&e.length>0?e:void 0}function EO(){return[IS(),Aw(),$T(),vD(),yO(),Qw()]}const DO=`general-purpose`;function OO(e){let t=[],n=``,r,i=!1;for(let a of e){if(i){n+=a,i=!1;continue}if(r&&a===`\\`){i=!0;continue}if(r){a===r?r=void 0:n+=a;continue}if(a===`"`||a===`'`){r=a;continue}if(/\s/.test(a)){n.length>0&&(t.push(n),n=``);continue}n+=a}return n.length>0&&t.push(n),t}function kO(e){let t=[],n,r,i;for(let a=0;a<e.length;a+=1){let o=e[a];if(o!==`--background`){if(o===`--agent`||o===`--type`||o===`-a`){n=e[a+1],a+=1;continue}if(o===`--model`){r=e[a+1],a+=1;continue}if(o===`--isolation`){let t=e[a+1];(t===`none`||t===`worktree`)&&(i=t),a+=1;continue}o!==void 0&&t.push(o)}}return{positional:t,...n?{agentType:n}:{},...r?{model:r}:{},...i?{isolation:i}:{}}}function AO(e,t,n,r){return{agentType:t,label:n,mode:`background`,prompt:r,...e.model?{model:e.model}:{},...e.isolation?{isolation:e.isolation}:{}}}function jO(e,t){let n=kO(e),[r,...i]=n.positional,a=n.agentType??DO,o=n.positional;!n.agentType&&r&&t.has(r)&&(a=r,o=i);let s=o.join(` `).trim();if(s)return AO(n,a,a,s)}function MO(e,t){let n=kO(e);return n.positional.map(e=>NO(e,n,t)).filter(e=>e!==void 0)}function NO(e,t,n){let r=e.indexOf(`=`);if(r>0)return PO(e.slice(0,r),e.slice(r+1),t,n);let i=e.indexOf(`:`);if(i<=0||i===e.length-1)return;let a=e.slice(0,i),o=e.slice(i+1);return AO(t,t.agentType??(n.has(a)?a:DO),a,o)}function PO(e,t,n,r){let i=t.indexOf(`:`);if(i===-1)return AO(n,n.agentType??(r.has(e)?e:DO),e,t);if(!(i===0||i===t.length-1))return AO(n,t.slice(0,i),e,t.slice(i+1))}function FO(e){return e instanceof Error?e.message:String(e)}function IO(e){return new Set(e.listAgentDefinitions().map(e=>e.name))}function LO(e,t){let n=e.listAgentDefinitions();if(!n.some(e=>e.name===t))return{message:`Unknown agent type: ${t}\nAvailable agents: ${n.map(e=>e.name).join(`, `)}`,success:!1}}async function RO(e,t){let n=LO(e,t.agentType);if(n)return n;try{return{state:await e.spawnAgentJob(t)}}catch(e){return{message:FO(e),success:!1}}}function zO(){return{message:``,effects:[{type:`agent-switcher-requested`}],success:!0}}async function BO(e){let t=e.listAgentDefinitions(),n=e.listAgentJobs();return{message:[`Available agents:`,...t.map(e=>` ${e.name} - ${e.description}`),``,n.length===0?`No active agent jobs.`:`Agent jobs:`,...n.map(e=>` ${VO(e)}`)].join(`
233
+ `)}function ST(e){let t=e.name?.trim();if(!t)throw Error(`Google provider tool message requires a function name.`);return t}function CT(e){let t=JSON.parse(e);if(!TT(t))throw Error(`Google provider tool call arguments must be a JSON object.`);return t}function wT(e){let t=e.trim();if(t.length===0)return{output:null};try{let e=JSON.parse(t);return TT(e)?e:{output:e}}catch{return{output:e}}}function TT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const ET={string:Fe.STRING,number:Fe.NUMBER,integer:Fe.INTEGER,boolean:Fe.BOOLEAN,array:Fe.ARRAY,object:Fe.OBJECT};function DT(e){return e.map(e=>({name:e.name,description:e.description,parameters:{type:Fe.OBJECT,properties:kT(e.parameters.properties),required:e.parameters.required}}))}function OT(e){return e===`auto`?{mode:Ne.AUTO}:e===`none`?{mode:Ne.NONE}:e===`required`?{mode:Ne.ANY}:{mode:Ne.ANY,allowedFunctionNames:[e.tool]}}function kT(e){let t={};for(let[n,r]of Object.entries(e))t[n]=AT(r);return t}function AT(e){let t={},n=jT(e.type);return n&&(t.type=n),e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum.map(String)),e.items&&(t.items=AT(e.items)),e.properties&&(t.properties=kT(e.properties)),typeof e.minimum==`number`&&(t.minimum=e.minimum),typeof e.maximum==`number`&&(t.maximum=e.maximum),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.default!==void 0&&(t.default=e.default),t}function jT(e){if(e!==`null`)return ET[e]}function MT(){return`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function NT(e){let t=e.candidates?.[0];if(!t)throw Error(`No candidate in Gemini response`);let n=t.content;if(!n||!n.parts||n.parts.length===0)throw Error(`No content in Gemini response`);let r=PT(n.parts),i={id:l(),state:`complete`,role:`assistant`,content:r.textValues.length>0?r.textValues.join(``):null,parts:r.messageParts,timestamp:new Date};if(r.functionCalls.length>0){let e=i;e.toolCalls=r.functionCalls.map(e=>({id:e.id??MT(),type:`function`,function:{name:RT(e),arguments:JSON.stringify(e.args??{})}}))}let a=LT(e);return a&&(i.metadata=a),i}function PT(e){let t=[],n=[],r=[];for(let i of e)FT(i,t,n),IT(i,n),i.functionCall&&r.push(i.functionCall);return{textValues:t,messageParts:n,functionCalls:r}}function FT(e,t,n){typeof e.text==`string`&&(t.push(e.text),n.push({type:`text`,text:e.text}))}function IT(e,t){!e.inlineData||typeof e.inlineData.data!=`string`||typeof e.inlineData.mimeType!=`string`||t.push({type:`image_inline`,data:e.inlineData.data,mimeType:e.inlineData.mimeType})}function LT(e){if(!(!e.usageMetadata||typeof e.usageMetadata.promptTokenCount!=`number`||typeof e.usageMetadata.candidatesTokenCount!=`number`||typeof e.usageMetadata.totalTokenCount!=`number`))return{promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,totalTokens:e.usageMetadata.totalTokenCount}}function RT(e){if(!e.name||e.name.trim().length===0)throw Error(`Gemini function call is missing a function name.`);return e.name}async function zT(e,t,n,r,i=`gemini`){let a=HT(t,r),o=cT(n,t.defaultResponseModalities,r?.google?.responseModalities);if(r?.onTextDelta&&!o.includes(`IMAGE`))return UT(e,t,n,r,i);let s=vT(n),c=uT(n,t,{...r,model:a}),l=VT(a,s.contents,c,r,s.systemInstruction);WT(r,i,`request`,l);let u=await e.models.generateContent(l);WT(r,i,`response`,u);let d=NT(u);if(o.includes(`IMAGE`)&&!iT(d.parts))throw Error(`Gemini response did not include an image part while IMAGE modality was requested.`);return d}async function*BT(e,t,n,r,i=`gemini`){let a=HT(t,r);if(cT(n,t.defaultResponseModalities,r?.google?.responseModalities).includes(`IMAGE`))throw Error(`Google provider does not support streaming image modality responses.`);let o=vT(n),s=uT(n,t,{...r,model:a}),c=VT(a,o.contents,s,r,o.systemInstruction);WT(r,i,`request`,c);let u=await e.models.generateContentStream(c),d=0;for await(let e of u){WT(r,i,`stream_event`,e,d),d++;let t=GT(e);t&&(r?.onTextDelta?.(t),yield{id:l(),role:`assistant`,content:t,state:`complete`,timestamp:new Date})}}function VT(e,t,n,r,i){let a={...n};return r?.tools&&r.tools.length>0&&(a.tools=[{functionDeclarations:DT(r.tools)}],r.toolChoice!==void 0&&(a.toolConfig={functionCallingConfig:OT(r.toolChoice)})),i&&(a.systemInstruction=i),r?.responseFormat?.type===`json_schema`?(a.responseMimeType=`application/json`,a.responseSchema=r.responseFormat.schema):r?.responseFormat?.type===`json_object`&&(a.responseMimeType=`application/json`),{model:e,contents:t,config:a}}function HT(e,t){let n=t?.model??e.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);return n}async function UT(e,t,n,r,i=`gemini`){let a=[];for await(let o of BT(e,t,n,r,i))typeof o.content==`string`&&a.push(o.content);let o=a.join(``);return{id:l(),role:`assistant`,content:o,parts:o.length>0?[{type:`text`,text:o}]:[],state:`complete`,timestamp:new Date}}function WT(e,t,n,r,i){e?.onProviderNativeRawPayload?.({provider:t,apiSurface:`gemini-generate-content`,payloadKind:n,...i!==void 0&&{sequence:i},payload:r})}function GT(e){let t=e.text;return typeof t==`function`?t():t}async function KT(e,t,n){try{let r=aT((await e(t,{model:n,google:{responseModalities:[`TEXT`,`IMAGE`]}})).parts);return r.length===0?{ok:!1,error:{code:`PROVIDER_UPSTREAM_ERROR`,message:`Google image response did not include image output parts.`}}:{ok:!0,value:{outputs:r,model:n}}}catch(e){return{ok:!1,error:{code:`PROVIDER_UPSTREAM_ERROR`,message:e instanceof Error?e.message:`Google image request failed.`}}}}var qT=class extends Ft{name=`gemini`;version=`1.0.0`;onTextDelta;client;options;constructor(e){super(),this.options=e,e.executor&&(this.executor=e.executor),this.executor||(this.client=new Pe({apiKey:e.apiKey}))}async chat(e,t){if(this.validateMessages(e),this.executor)try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`Gemini Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Google client not available. Either provide apiKey or use an executor.`);try{return await zT(this.client,this.options,e,this.withProviderCallbacks(t),this.name)}catch(e){let t=e instanceof Error?e.message:`Google API request failed`;throw Error(`Google chat failed: ${t}`)}}async*chatStream(e,t){if(this.validateMessages(e),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`Gemini Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Google client not available. Either provide apiKey or use an executor.`);try{yield*BT(this.client,this.options,e,this.withProviderCallbacks(t),this.name)}catch(e){let t=e instanceof Error?e.message:`Google API request failed`;throw Error(`Google stream failed: ${t}`)}}async generateImage(e){if(e.prompt.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image generation requires a non-empty prompt.`}};if(e.model.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image generation requires a non-empty model.`}};let t={id:l(),role:`user`,content:e.prompt,state:`complete`,parts:[{type:`text`,text:e.prompt}],timestamp:new Date};return KT(this.chat.bind(this),[t],e.model)}async editImage(e){if(e.prompt.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image edit requires a non-empty prompt.`}};if(e.model.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image edit requires a non-empty model.`}};let t=sT(e.image);if(!t.ok)return t;let n={id:l(),role:`user`,content:e.prompt,state:`complete`,parts:[t.value,{type:`text`,text:e.prompt}],timestamp:new Date};return KT(this.chat.bind(this),[n],e.model)}async composeImage(e){if(e.prompt.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image compose requires a non-empty prompt.`}};if(e.model.trim().length===0)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image compose requires a non-empty model.`}};if(e.images.length<2)return{ok:!1,error:{code:`PROVIDER_INVALID_REQUEST`,message:`Image compose requires at least two input images.`}};let t=[];for(let n of e.images){let e=sT(n);if(!e.ok)return e;t.push(e.value)}t.push({type:`text`,text:e.prompt});let n={id:l(),role:`user`,content:e.prompt,state:`complete`,parts:t,timestamp:new Date};return KT(this.chat.bind(this),[n],e.model)}supportsTools(){return!0}validateConfig(){return this.executor?this.executor.validateConfig():!!this.client&&!!this.options&&!!this.options.apiKey}async dispose(){}withProviderCallbacks(e){let t=e?.onTextDelta??this.onTextDelta;return t?{...e,onTextDelta:t}:e}};const JT=`$ENV:GEMINI_API_KEY`,YT=`gemini-3-flash-preview`,XT=`https://ai.google.dev/api/models`,ZT=`2026-05-04`,QT=[{kind:`api-key`,label:`Google AI Studio API keys`,url:`https://aistudio.google.com/apikey`,sourceUrl:`https://ai.google.dev/gemini-api/docs/api-key`,lastVerifiedAt:`2026-05-08`}];function $T(){return{type:`gemini`,aliases:[`google`],displayName:`Gemini`,description:`Google Gemini series — free tier available.`,category:`cloud-free`,defaults:{model:YT,apiKey:JT},modelCatalog:{status:`fallback`,sourceUrl:XT,lastVerifiedAt:ZT,entries:[{id:YT,displayName:`Gemini 3 Flash Preview`,capabilities:[`tools`,`vision`,`json_schema`,`reasoning`,`streaming`],lifecycle:`preview`,sourceUrl:XT,lastVerifiedAt:ZT}]},setupHelpLinks:QT,setupSteps:[{key:`model`,title:`Gemini model`,defaultValue:YT},{key:`apiKey`,title:`Gemini API key`,defaultValue:JT,masked:!0}],requiresApiKey:!0,refreshModelCatalog:({profile:e})=>nE(e),modelCatalogCacheTtlSeconds:86400,createProvider:e=>new qT({apiKey:eE(e.apiKey),defaultModel:e.model})}}function eE(e){if(!e)throw Error(`Provider gemini requires apiKey`);return e}const tE=`https://generativelanguage.googleapis.com/v1beta/models`;async function nE(e,t=aE){let n=await t(e.apiKey?`${tE}?key=${e.apiKey}`:tE);if(!n.ok)return{status:`unavailable`,sourceUrl:XT,message:`Gemini model refresh failed: HTTP ${n.status}`};let r=((await n.json()).models??[]).filter(rE).map(iE);return{status:`live`,sourceUrl:XT,lastVerifiedAt:new Date().toISOString(),entries:r,message:`Fetched ${r.length} Gemini models`}}function rE(e){return e.supportedGenerationMethods?.includes(`generateContent`)===!0}function iE(e){let t=e.name??``,n=t.startsWith(`models/`)?t.slice(7):t,r=t.includes(`preview`)?`preview`:`active`;return{id:n,displayName:e.displayName??n,lifecycle:r,sourceUrl:XT,lastVerifiedAt:ZT}}async function aE(e,t){let n=await fetch(e);return{ok:n.ok,status:n.status,json:()=>n.json()}}const oE=`<|channel>`;function sE(e){let t=lE(e,{final:!0});return{rawText:e,visibleText:t.visibleParts.join(``),removedReasoning:t.removedReasoning}}var cE=class{buffer=``;emittedVisibleText=``;hasRemovedReasoning=!1;get rawText(){return this.buffer}get removedReasoning(){return this.hasRemovedReasoning}project(e){return e.length===0?``:(this.buffer+=e,this.projectVisibleText({final:!1}))}flush(){return this.projectVisibleText({final:!0})}projectVisibleText(e){let t=lE(this.buffer,e);this.hasRemovedReasoning=this.hasRemovedReasoning||t.removedReasoning;let n=t.visibleParts.join(``),r=n.slice(this.emittedVisibleText.length);return this.emittedVisibleText=n,r}};function lE(e,t){let n={visibleParts:[],removedReasoning:!1},r=0;for(;r<e.length;){let i=e.indexOf(oE,r);if(i===-1){uE(n,e.slice(r),t);break}uE(n,e.slice(r,i),t);let a=i+10,o=e.indexOf(`<channel|>`,a);if(o===-1){t.final&&(n.removedReasoning=!0);break}n.removedReasoning=!0,r=dE(e,a,o)}return n}function uE(e,t,n){if(t.length===0)return;if(n.final){e.visibleParts.push(t);return}let r=fE(t);e.visibleParts.push(t.slice(0,t.length-r))}function dE(e,t,n){let r=e.slice(t,n),i=n+10;if(r.trim().length===0){let t=e.slice(i).match(/^thought(?:\r?\n)*/);return t&&(i+=t[0].length),i}return r.split(/\r?\n/,1)[0]?.trim(),i}function fE(e){let t=Math.min(e.length,9);for(let n=t;n>0;--n)if(oE.startsWith(e.slice(e.length-n)))return n;return 0}function pE(e){return[`<`]}function mE(e,t,n){return e.indexOf(`<`,t)}function hE(e,t){return+!!e.endsWith(`<`)}function gE(e,t){let n=e.indexOf(`>`,t+1);if(n===-1)return;let r=e.slice(t,n+1),i=r.match(/^<\s*([A-Za-z][\w:-]*)([\s/>][\s\S]*?|)>$/);if(!i)return;let a=i[1]??``;return{tagName:a,normalizedName:a.toLowerCase(),rawOpenTag:r,attributes:bE(i[2]??``),openEnd:n+1,selfClosing:/\/\s*>$/.test(r)}}function _E(e,t,n){if(t.selfClosing)return{innerText:``,end:t.openEnd,complete:!0};let r=CE(e,t.tagName,t.openEnd);if(r===-1)return{innerText:e.slice(t.openEnd),end:n.final?e.length:t.openEnd-t.rawOpenTag.length,complete:!1};let i=e.indexOf(`>`,r);return{innerText:e.slice(t.openEnd,r),end:i===-1?e.length:i+1,complete:!0}}function vE(e,t){if(t.selfClosing)return{rawText:t.rawOpenTag,end:t.openEnd};let n=CE(e,t.tagName,t.openEnd);if(n===-1)return{rawText:t.rawOpenTag,end:t.openEnd};let r=e.indexOf(`>`,n),i=r===-1?e.length:r+1;return{rawText:e.slice(t.openEnd-t.rawOpenTag.length,i),end:i}}function yE(e,t){let n=wE(e);return t.find(e=>wE(e)===n)}function bE(e){let t={},n=/([A-Za-z_][\w:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,r=n.exec(e);for(;r;){let i=r[1]??``;t[i]=xE(SE(r[2]??r[3]??``)),r=n.exec(e)}return t}function xE(e){return e===`true`?!0:e===`false`?!1:e===`null`?null:/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e)?Number(e):e}function SE(e){return e.replace(/&quot;/g,`"`).replace(/&apos;/g,`'`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`)}function CE(e,t,n){return e.toLowerCase().indexOf(`</${t.toLowerCase()}>`,n)}function wE(e){return e.replace(/[^a-z0-9]/gi,``).toLowerCase()}function TE(e,t){let n=EE(e,t);return n?[n]:[]}function EE(e,t){let n=e.indexOf(`>`),r=e.lastIndexOf(`</`);if(n===-1||r===-1||r<=n)return;let i=DE(e.slice(n+1,r).trim());if(!OE(i))return;let a=i.command,o=i.args;if(typeof a!=`string`||!OE(o))return;let s=yE(a,t);if(s)return{toolName:s,args:o}}function DE(e){try{return JSON.parse(e)}catch{return}}function OE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kE(e,t,n){let r=zE(),i=pE(t.toolNames),a=0;for(;a<e.length;){let o=mE(e,a,i);if(o===-1){FE(r,e.slice(a),n,i);break}FE(r,e.slice(a,o),n,i);let s=AE(e,o,r,t,n);if(!s.completed)break;a=s.cursor}return{visibleText:r.visibleParts.join(``),toolCalls:r.toolCalls,rawToolCallTextParts:r.rawToolCallTextParts,removedToolCallText:r.removedToolCallText}}function AE(e,t,n,r,i){let a=gE(e,t);if(!a)return jE(e,t,n,i);let o=yE(a.tagName,r.toolNames);return o?PE(e,a,o,n,r):ME(e,t,a,n,r,i)}function jE(e,t,n,r){return r.final?(n.visibleParts.push(e[t]??``),{cursor:t+1,completed:!0}):{cursor:t,completed:!1}}function ME(e,t,n,r,i,a){let o=_E(e,n,a);if(!o.complete&&!a.final)return{cursor:t,completed:!1};let s=e.slice(t,o.end),c=r.rawToolCallTextParts.length;return r.removedToolCallText=!0,LE(r,s,i),BE(r,NE(o,r,i)),r.rawToolCallTextParts.length===c&&r.rawToolCallTextParts.push(s),{cursor:o.end,completed:!0}}function NE(e,t,n){return kE(e.innerText,{...n,startCallIndex:VE(t,n)},{final:!0})}function PE(e,t,n,r,i){let a=vE(e,t);return IE(r,n,t.attributes,a.rawText,i),{cursor:a.end,completed:!0}}function FE(e,t,n,r){if(t.length===0)return;if(n.final){e.visibleParts.push(t);return}let i=hE(t,r);e.visibleParts.push(t.slice(0,t.length-i))}function IE(e,t,n,r,i){Object.keys(n).length!==0&&(e.toolCalls.push(RE(t,n,i,e)),e.rawToolCallTextParts.push(r),e.removedToolCallText=!0)}function LE(e,t,n){let r=TE(t,n.toolNames);for(let i of r)e.toolCalls.push(RE(i.toolName,i.args,n,e)),e.rawToolCallTextParts.push(t)}function RE(e,t,n,r){return{id:`${n.callIdPrefix??`gemma_call`}_${VE(r,n)}`,type:`function`,function:{name:e,arguments:JSON.stringify(t)}}}function zE(){return{visibleParts:[],toolCalls:[],rawToolCallTextParts:[],removedToolCallText:!1}}function BE(e,t){e.toolCalls.push(...t.toolCalls),e.rawToolCallTextParts.push(...t.rawToolCallTextParts),e.removedToolCallText=e.removedToolCallText||t.removedToolCallText}function VE(e,t){return(t.startCallIndex??0)+e.toolCalls.length}const HE=`<|"|>`;var UE=class{source;cursor=0;constructor(e){this.source=e}parse(){let e=this.parseObject();if(this.skipWhitespace(),this.cursor===this.source.length)return e}parseObject(){if(!this.consume(`{`))return;let e={};if(this.skipWhitespace(),this.consume(`}`))return e;for(;this.cursor<this.source.length;){let t=this.parseKey();if(!t||!this.consume(`:`))return;let n=this.parseValue();if(n===void 0)return;if(e[t]=n,this.skipWhitespace(),this.consume(`}`))return e;if(!this.consume(`,`))return}}parseArray(){if(!this.consume(`[`))return;let e=[];if(this.skipWhitespace(),this.consume(`]`))return e;for(;this.cursor<this.source.length;){let t=this.parseValue();if(t===void 0)return;if(e.push(t),this.skipWhitespace(),this.consume(`]`))return e;if(!this.consume(`,`))return}}parseValue(){return this.skipWhitespace(),this.source.startsWith(HE,this.cursor)?this.parseString():this.source.startsWith(`{`,this.cursor)?this.parseObject():this.source.startsWith(`[`,this.cursor)?this.parseArray():this.consumeLiteral(`true`)?!0:this.consumeLiteral(`false`)?!1:this.consumeLiteral(`null`)?null:this.parseNumber()}parseKey(){if(this.skipWhitespace(),this.source.startsWith(HE,this.cursor))return this.parseString();let e=/^[A-Za-z_][A-Za-z0-9_-]*/.exec(this.source.slice(this.cursor));if(e)return this.cursor+=e[0].length,this.skipWhitespace(),e[0]}parseString(){if(!this.consume(HE))return;let e=this.source.indexOf(HE,this.cursor);if(e===-1)return;let t=this.source.slice(this.cursor,e);return this.cursor=e+5,this.skipWhitespace(),t}parseNumber(){let e=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(this.source.slice(this.cursor));if(e)return this.cursor+=e[0].length,this.skipWhitespace(),Number(e[0])}consume(e){return this.skipWhitespace(),this.source.startsWith(e,this.cursor)?(this.cursor+=e.length,this.skipWhitespace(),!0):!1}consumeLiteral(e){return this.source.startsWith(e,this.cursor)?(this.cursor+=e.length,this.skipWhitespace(),!0):!1}skipWhitespace(){for(;/\s/.test(this.source[this.cursor]??``);)this.cursor+=1}};const WE=`<|tool_call>`,GE=`gemma_call`;function KE(e){if(!(!e||e.length===0))return new qE({toolNames:e.map(e=>e.name)})}var qE=class{options;buffer=``;emittedVisibleText=``;emittedRawToolCallText=``;emittedToolCallIds=new Set;constructor(e){this.options=e}project(e){return e.length===0?eD():(this.buffer+=e,this.projectVisibleText({final:!1}))}flush(){return this.projectVisibleText({final:!0})}projectVisibleText(e){let t=JE(this.buffer,this.options,e),n=t.visibleParts.join(``),r=n.slice(this.emittedVisibleText.length),i=t.rawToolCallTextParts.join(``),a=i.slice(this.emittedRawToolCallText.length);return this.emittedVisibleText=n,this.emittedRawToolCallText=i,{visibleText:r,toolCalls:t.toolCalls.filter(e=>this.emittedToolCallIds.has(e.id)?!1:(this.emittedToolCallIds.add(e.id),!0)),removedToolCallText:a.length>0,...a.length>0&&{rawToolCallText:a}}}};function JE(e,t,n){let r=YE(e,t,n),i=kE(r.visibleParts.join(``),{toolNames:t.toolNames,callIdPrefix:t.callIdPrefix??GE,startCallIndex:r.toolCalls.length},n);return{visibleParts:[i.visibleText],toolCalls:[...r.toolCalls,...i.toolCalls],rawToolCallTextParts:[...r.rawToolCallTextParts,...i.rawToolCallTextParts],removedToolCallText:r.removedToolCallText||i.removedToolCallText}}function YE(e,t,n){let r=ZE(),i=new Set(t.toolNames),a=0,o=0;for(;a<e.length;){let s=e.indexOf(WE,a);if(s===-1){QE(r,e.slice(a),n);break}QE(r,e.slice(a,s),n);let c=s+12,l=e.indexOf(`<tool_call|>`,c);if(l===-1){n.final&&r.visibleParts.push(e.slice(s));break}let u=e.slice(s,l+12),d=XE(e.slice(c,l),i,t,o);d?(r.toolCalls.push(d),r.rawToolCallTextParts.push(u),r.removedToolCallText=!0,o+=1):r.visibleParts.push(u),a=l+12}return r}function XE(e,t,n,r){let i=e.trim();if(!i.startsWith(`call:`))return;let a=i.slice(5).trimStart(),o=a.indexOf(`{`);if(o<=0)return;let s=a.slice(0,o).trim();if(!t.has(s))return;let c=new UE(a.slice(o)).parse();if(c)return{id:`${n.callIdPrefix??GE}_${r}`,type:`function`,function:{name:s,arguments:JSON.stringify(c)}}}function ZE(){return{visibleParts:[],toolCalls:[],rawToolCallTextParts:[],removedToolCallText:!1}}function QE(e,t,n){if(t.length===0)return;if(n.final){e.visibleParts.push(t);return}let r=$E(t);e.visibleParts.push(t.slice(0,t.length-r))}function $E(e){let t=Math.min(e.length,11);for(let n=t;n>0;--n)if(WE.startsWith(e.slice(e.length-n)))return n;return 0}function eD(){return{visibleText:``,toolCalls:[],removedToolCallText:!1}}function tD(e,t,n){let r=e.choices?.[0]?.message.content||``,i=new WS({logger:t,...n?.tools&&{toolCallTextProjector:KE(n.tools)}}).parseResponse(e),a=sE(i.content??``);return nD({...i,content:a.visibleText},r,a.removedReasoning)}function nD(e,t,n){return n?{...e,metadata:{...e.metadata??{},gemmaReasoningFiltered:!0,gemmaRawContent:t}}:e}function rD(e,t){return{id:l(),role:`assistant`,content:e,state:`complete`,timestamp:new Date,metadata:{isStreamChunk:!0,isComplete:t===`stop`||t===`tool_calls`}}}function iD(e,t){return{id:l(),role:`assistant`,content:``,toolCalls:e,state:`complete`,timestamp:new Date,metadata:{isStreamChunk:!0,isComplete:t===`stop`||t===`tool_calls`}}}function aD(e,t){return{reasoningProjector:new cE,responseParser:new WS({logger:e}),...t&&{toolCallProjector:KE(t)}}}function oD(e,t){let n=e.choices?.[0];if(!n)return[];let r=t.responseParser.parseStreamingChunk(e);return r&&Et(r)&&r.toolCalls?.length?[r]:cD(n.delta.content||``,n.finish_reason,t)}function sD(e){let t=cD(``,null,e,!0),n=e.reasoningProjector.flush();return n.length>0&&t.push(rD(n,null)),t}function cD(e,t,n,r=!1){let i=r?n.toolCallProjector?.flush():n.toolCallProjector?.project(e),a=[];i?.toolCalls.length&&a.push(iD(i.toolCalls,t));let o=i?.visibleText??e,s=n.reasoningProjector.project(o);return s.length>0&&a.push(rD(s,t)),a}var lD=class extends Ft{name=`gemma`;version=`1.0.0`;client;options;onTextDelta;constructor(e){if(super(e.logger||kt),this.options=e,e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client;else if(e.apiKey)this.client=new Me({apiKey:e.apiKey,...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout}});else throw Error(`Either Gemma client, apiKey, or executor is required`)}async chat(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`Gemma Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Gemma client not available. Either provide a client/apiKey or use an executor.`);try{let n=this.buildRequestParams(e,t),r=t?.onTextDelta??this.onTextDelta;if(r)return await this.chatWithStreamingAssembly({...n,stream:!0},{...t,onTextDelta:r});t?.onProviderNativeRawPayload?.({provider:`gemma`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let i=await this.client.chat.completions.create(n);return t?.onProviderNativeRawPayload?.({provider:`gemma`,apiSurface:`chat-completions`,payloadKind:`response`,payload:i}),tD(i,this.logger,t)}catch(e){let t=e.message||`Gemma API request failed`;throw Error(`Gemma chat failed: ${t}`)}}async*chatStream(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`Gemma Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Gemma client not available. Either provide a client/apiKey or use an executor.`);try{let n=this.buildStreamingRequestParams(e,t);t?.onProviderNativeRawPayload?.({provider:`gemma`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let r=await this.client.chat.completions.create(n),i=aD(this.logger,t?.tools),a=aC(r,{provider:`gemma`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t?.onProviderNativeRawPayload});for await(let e of this.streamWithAbort(a,t?.signal))for(let t of oD(e,i))yield t;for(let e of sD(i))yield e}catch(e){let t=e.message||`Gemma API request failed`;throw Error(`Gemma stream failed: ${t}`)}}supportsTools(){return!0}getCapabilities(){return{functionCalling:{supported:!0},nativeWebTools:{webSearch:{supported:!1,enabled:!1,source:`openai-compatible-chat-completions`,reason:`Gemma OpenAI-compatible endpoints support declared function tools, not provider-native web search.`},webFetch:{supported:!1,enabled:!1,source:`openai-compatible-chat-completions`,reason:`Gemma OpenAI-compatible endpoints support declared function tools, not provider-native web fetch.`}}}}validateConfig(){return!!this.client&&!!this.options}async dispose(){}validateMessages(e){super.validateMessages(e);for(let t of e)if(t.role===`assistant`){let e=t;if(e.toolCalls&&e.toolCalls.length>0&&e.content===``)continue}}buildRequestParams(e,t){let n=t?.model??this.options.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);return{model:n,messages:zS(e),...t?.temperature!==void 0&&{temperature:t.temperature},...t?.maxTokens!==void 0&&{max_tokens:t.maxTokens},...t?.tools&&{tools:BS(t.tools),tool_choice:cC(t.toolChoice)}}}buildStreamingRequestParams(e,t){return{...this.buildRequestParams(e,t),stream:!0}}async chatWithStreamingAssembly(e,t){if(!this.client)throw Error(`Gemma client not available. Either provide a client/apiKey or use an executor.`);try{t.onProviderNativeRawPayload?.({provider:`gemma`,apiSurface:`chat-completions`,payloadKind:`request`,payload:e});let n=await this.client.chat.completions.create(e,t.signal?{signal:t.signal}:void 0),r=new cE;return nD(await GS({stream:aC(n,{provider:`gemma`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t.onProviderNativeRawPayload}),onTextDelta:t.onTextDelta,signal:t.signal,textProjector:e=>r.project(e),textProjectorFlush:()=>r.flush(),toolCallTextProjector:KE(t.tools)}),r.rawText,r.removedReasoning)}catch(e){let t=e.message||`Gemma streaming request failed`;throw Error(`Gemma stream failed: ${t}`)}}};const uD=`supergemma4-26b-uncensored-v2`,dD=`lm-studio`,fD=`http://localhost:1234/v1`,pD=`https://ai.google.dev/gemma`,mD=`2026-05-04`,hD=`https://lmstudio.ai/docs/developer`,gD=[{kind:`official`,label:`LM Studio local API documentation`,url:hD,sourceUrl:hD,lastVerifiedAt:`2026-05-08`}],_D={status:`fallback`,sourceUrl:pD,lastVerifiedAt:mD,entries:[{id:uD,displayName:`SuperGemma 4 26B`,capabilities:[`tools`,`streaming`],lifecycle:`active`,sourceUrl:pD,lastVerifiedAt:mD}]};function vD(){return{type:`gemma`,displayName:`Ollama / LM Studio / llama.cpp`,description:`Local models via LM Studio or Ollama. No API key needed.`,category:`local-free`,defaults:{model:uD,apiKey:dD,baseURL:fD},modelCatalog:_D,setupHelpLinks:gD,setupSteps:[{key:`baseURL`,title:`Gemma OpenAI-compatible base URL`,defaultValue:fD},{key:`model`,title:`Gemma model`,defaultValue:uD},{key:`apiKey`,title:`Gemma OpenAI-compatible API key`,defaultValue:dD,masked:!0}],requiresApiKey:!0,probeProfile:oC,createProvider:e=>new lD({apiKey:yD(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...e.timeout!==void 0&&{timeout:e.timeout},defaultModel:e.model})}}function yD(e){if(!e)throw Error(`Provider gemma requires apiKey`);return e}const bD={singapore:`https://dashscope-intl.aliyuncs.com/compatible-mode/v1`,usVirginia:`https://dashscope-us.aliyuncs.com/compatible-mode/v1`,beijing:`https://dashscope.aliyuncs.com/compatible-mode/v1`,hongKong:`https://cn-hongkong.dashscope.aliyuncs.com/compatible-mode/v1`},xD={singapore:`https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1`,usVirginia:`https://dashscope-us.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1`,beijing:`https://dashscope.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1`},SD=`qwen-plus`,CD=`$ENV:DASHSCOPE_API_KEY`,wD=bD.singapore,TD=xD.singapore,ED=`https://www.alibabacloud.com/help/en/model-studio/compatibility-of-openai-with-dashscope`,DD=`2026-05-04`,OD=`qwen-responses`;function kD(e){let t=e.builtInWebTools,n=t?.webSearch===!0||t?.webFetch===!0,r=t?.webFetch===!0;return{functionCalling:{supported:!0},nativeWebTools:{webSearch:n?{supported:!0,enabled:!0,source:OD}:{supported:!0,enabled:!1,source:OD,reason:`Enable builtInWebTools.webSearch or builtInWebTools.webFetch.`},webFetch:r?{supported:!0,enabled:!0,source:OD}:{supported:!0,enabled:!1,source:OD,reason:`Enable builtInWebTools.webFetch.`}}}}async function AD(e,t,n){try{return n.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`chat-completions`,payloadKind:`request`,payload:t}),GS({stream:aC(await e.chat.completions.create(t,n.signal?{signal:n.signal}:void 0),{provider:`qwen`,apiSurface:`chat-completions`,onProviderNativeRawPayload:n.onProviderNativeRawPayload}),onTextDelta:n.onTextDelta,signal:n.signal})}catch(e){let t=e.message||`Qwen streaming request failed`;throw Error(`Qwen stream failed: ${t}`)}}function jD(e){let t=[];return(e?.webSearch===!0||e?.webFetch===!0)&&t.push(`web_search`),e?.webFetch===!0&&t.push(`web_extractor`),t}function MD(e){return jD(e).length>0}function ND(e){return e.flatMap(e=>ID(e))}function PD(e,t){let n=[...e.map(e=>({type:e})),...FD(t)];return n.length>0?n:void 0}function FD(e){return e?.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters}))??[]}function ID(e){return e.role===`user`?[RD(`user`,e.content)]:e.role===`system`?[RD(`system`,e.content)]:e.role===`tool`?[{type:`function_call_output`,call_id:e.toolCallId,output:e.content||``}]:LD(e)}function LD(e){let t=[];e.content&&e.content.length>0&&t.push(RD(`assistant`,e.content));for(let n of e.toolCalls??[])t.push({type:`function_call`,call_id:n.id,name:n.function.name,arguments:n.function.arguments});return t.length===0&&t.push(RD(`assistant`,``)),t}function RD(e,t){return{role:e,content:t??``}}async function*zD(e,t){let n=e[Symbol.asyncIterator]();try{for(;!t?.aborted;){let e=await BD(n,t);if(e.done||t?.aborted)break;yield e.value}}finally{t?.aborted&&await n.return?.()}}async function BD(e,t){if(!t)return e.next();if(t.aborted)return{done:!0,value:void 0};let n,r=new Promise(e=>{n=()=>e({done:!0,value:void 0}),t.addEventListener(`abort`,n,{once:!0})});try{return await Promise.race([e.next(),r])}finally{n&&t.removeEventListener(`abort`,n)}}function VD(e,t){let n=e.output??[],r=YD(n,e.usage),i=eO(n);return KD({content:e.output_text??rO(n),toolCalls:i,response:e,usage:r,enabledBuiltInTools:t.enabledBuiltInTools})}async function HD(e){let t={textParts:[],toolCalls:[],usage:QD()};for await(let n of zD(e.stream,e.signal))UD(t,n,e.onTextDelta);return t.completedResponse===void 0?KD({content:t.textParts.join(``),toolCalls:t.toolCalls,usage:t.usage,enabledBuiltInTools:e.enabledBuiltInTools}):WD(t,e.enabledBuiltInTools)}function UD(e,t,n){if(t.type===`response.output_text.delta`){e.textParts.push(t.delta),n?.(t.delta);return}if(t.type===`response.completed`){e.completedResponse=t.response,ZD(e.usage,YD(t.response.output??[],t.response.usage));return}if(t.type===`response.output_item.done`){GD(e,t.item);return}if(t.type===`response.web_search_call.completed`){e.usage.webSearchCalls+=1;return}if(t.type===`response.error`||t.type===`response.failed`)throw Error(`Qwen Responses API failed: ${iO(t)}`)}function WD(e,t){let n=e.completedResponse;if(n===void 0)throw Error(`Qwen Responses stream completed without response metadata`);let r=n.output??[],i=eO(r),a=e.textParts.length>0?e.textParts.join(``):n.output_text??rO(r),o=YD(r,n.usage);return ZD(o,e.usage),KD({content:a,toolCalls:i.length>0?i:e.toolCalls,response:n,usage:o,enabledBuiltInTools:t})}function GD(e,t){if(t.type===`function_call`){tO(t)&&e.toolCalls.push(nO(t));return}ZD(e.usage,YD([t],void 0))}function KD(e){return{id:l(),role:`assistant`,content:e.content,state:`complete`,timestamp:new Date,...e.toolCalls.length>0&&{toolCalls:e.toolCalls},...e.response?.usage!==void 0&&{usage:{promptTokens:e.response.usage.input_tokens??0,completionTokens:e.response.usage.output_tokens??0,totalTokens:e.response.usage.total_tokens??0}},metadata:qD(e.enabledBuiltInTools,e.usage,e.response)}}function qD(e,t,n){let r=JD(t);return{providerToolMode:`qwen_responses`,providerBuiltInToolsEnabled:[...e],...r.length>0&&{providerBuiltInToolsUsed:r},qwenWebSearchCalls:t.webSearchCalls,qwenWebExtractorCalls:t.webExtractorCalls,...t.unsupportedToolTypes.size>0&&{qwenUnsupportedProviderToolTypes:[...t.unsupportedToolTypes].sort()},...n?.id!==void 0&&{responseId:n.id},...n?.model!==void 0&&{model:n.model},...n?.status!==void 0&&{finishReason:n.status}}}function JD(e){let t=[];return e.webSearchCalls>0&&t.push(`web_search`),e.webExtractorCalls>0&&t.push(`web_extractor`),t}function YD(e,t){let n=QD();for(let t of e)t.type===`web_search_call`?n.webSearchCalls+=1:t.type===`web_extractor_call`?n.webExtractorCalls+=1:$D(t.type)&&n.unsupportedToolTypes.add(t.type);return XD(n,t),n}function XD(e,t){let n=t?.x_tools;if(n!==void 0){e.webSearchCalls=Math.max(e.webSearchCalls,n.web_search?.count??0),e.webExtractorCalls=Math.max(e.webExtractorCalls,n.web_extractor?.count??0);for(let t of Object.keys(n))t!==`web_search`&&t!==`web_extractor`&&e.unsupportedToolTypes.add(t)}}function ZD(e,t){e.webSearchCalls=Math.max(e.webSearchCalls,t.webSearchCalls),e.webExtractorCalls=Math.max(e.webExtractorCalls,t.webExtractorCalls);for(let n of t.unsupportedToolTypes)e.unsupportedToolTypes.add(n)}function QD(){return{webSearchCalls:0,webExtractorCalls:0,unsupportedToolTypes:new Set}}function $D(e){return e.endsWith(`_call`)&&e!==`function_call`}function eO(e){return e.filter(tO).map(e=>nO(e))}function tO(e){return e.type===`function_call`&&`call_id`in e&&`name`in e&&`arguments`in e}function nO(e){return{id:e.call_id,type:`function`,function:{name:e.name,arguments:e.arguments}}}function rO(e){return e.filter(e=>e.type===`message`).flatMap(e=>e.content).map(e=>e.text).join(``)}function iO(e){return e.message??e.error?.message??e.response?.error?.message??`unknown error`}async function aO(e){let t=e.chatOptions?.onTextDelta??e.onTextDelta;if(t)return sO({...e,chatOptions:{...e.chatOptions,onTextDelta:t}});if(!e.client)throw Error(`Qwen Responses client not available for built-in web tools.`);try{let t=cO(e);e.chatOptions?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`responses`,payloadKind:`request`,payload:t});let n=await e.client.responses.create(t,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`responses`,payloadKind:`response`,payload:n}),VD(n,{enabledBuiltInTools:jD(e.builtInWebTools)})}catch(e){let t=e.message||`Qwen Responses API request failed`;throw Error(`Qwen responses failed: ${t}`)}}async function*oO(e){let t=[],n=await sO({...e,chatOptions:{...e.chatOptions,onTextDelta:n=>{e.chatOptions?.onTextDelta?.(n),t.push(uO(n))}}});for(let e of t)yield e;yield{...n,content:``,metadata:{...n.metadata,isStreamChunk:!0,isComplete:!0}}}async function sO(e){if(!e.client)throw Error(`Qwen Responses client not available for built-in web tools.`);try{let t=lO(e);return e.chatOptions?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`responses`,payloadKind:`request`,payload:t}),HD({stream:aC(await e.client.responses.create(t,e.chatOptions?.signal?{signal:e.chatOptions.signal}:void 0),{provider:`qwen`,apiSurface:`responses`,onProviderNativeRawPayload:e.chatOptions?.onProviderNativeRawPayload}),enabledBuiltInTools:jD(e.builtInWebTools),onTextDelta:e.chatOptions?.onTextDelta,signal:e.chatOptions?.signal})}catch(e){let t=e.message||`Qwen Responses streaming request failed`;throw Error(`Qwen responses stream failed: ${t}`)}}function cO(e){let t=e.chatOptions?.model??e.defaultModel;if(!t)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);let n=PD(jD(e.builtInWebTools),e.chatOptions?.tools);return{model:t,input:ND(e.messages),...n!==void 0&&{tools:n},...n!==void 0&&e.chatOptions?.toolChoice!==void 0&&{tool_choice:lC(e.chatOptions.toolChoice)},...e.chatOptions?.temperature!==void 0&&{temperature:e.chatOptions.temperature},...e.chatOptions?.maxTokens!==void 0&&{max_output_tokens:e.chatOptions.maxTokens},...e.builtInWebTools?.enableThinking!==void 0&&{enable_thinking:e.builtInWebTools.enableThinking}}}function lO(e){return{...cO(e),stream:!0}}function uO(e){return{id:l(),role:`assistant`,content:e,state:`complete`,timestamp:new Date,metadata:{isStreamChunk:!0,isComplete:!1}}}var dO=class extends Ft{name=`qwen`;version=`1.0.0`;client;responsesClient;options;responseParser;onTextDelta;constructor(e){if(super(e.logger||kt),this.options=e,e.executor&&(this.executor=e.executor),!this.executor)if(e.client)this.client=e.client,this.responsesClient=e.client;else if(e.apiKey)this.client=new Me({apiKey:e.apiKey,baseURL:e.baseURL??wD,...e.timeout!==void 0&&{timeout:e.timeout}}),this.responsesClient=new Me({apiKey:e.apiKey,baseURL:e.responsesBaseURL??TD,...e.timeout!==void 0&&{timeout:e.timeout}});else throw Error(`Either Qwen client, apiKey, or executor is required`);this.responseParser=new WS({logger:this.logger})}async chat(e,t){return this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor?this.chatViaExecutor(e,t):this.shouldUseResponsesApi()?this.chatViaResponsesApi(e,t,this.getResponsesClient()):this.chatViaChatCompletions(e,t,this.getClient())}async chatViaExecutor(e,t){try{return await this.executeViaExecutorOrDirect(e,t)}catch(e){throw this.logger.error(`Qwen Provider executor chat error:`,e instanceof Error?e.message:String(e)),e}}async chatViaResponsesApi(e,t,n){return this.validateTools(t?.tools),aO({client:n,messages:e,chatOptions:t,defaultModel:this.options.defaultModel,builtInWebTools:this.options.builtInWebTools,onTextDelta:this.onTextDelta})}async chatViaChatCompletions(e,t,n){try{let r=this.buildRequestParams(e,t),i=t?.onTextDelta??this.onTextDelta;if(i)return AD(n,{...r,stream:!0},{...t,onTextDelta:i});t?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`chat-completions`,payloadKind:`request`,payload:r});let a=await n.chat.completions.create(r);return t?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`chat-completions`,payloadKind:`response`,payload:a}),this.responseParser.parseResponse(a)}catch(e){let t=e.message||`Qwen API request failed`;throw Error(`Qwen chat failed: ${t}`)}}async*chatStream(e,t){if(this.validateMessages(e),this.validateNativeWebTools(t?.nativeWebTools),this.executor)try{yield*this.executeStreamViaExecutorOrDirect(e,t);return}catch(e){throw this.logger.error(`Qwen Provider executor stream error:`,e instanceof Error?e.message:String(e)),e}if(!this.client)throw Error(`Qwen client not available. Either provide a client/apiKey or use an executor.`);if(this.shouldUseResponsesApi()){this.validateTools(t?.tools),yield*oO({client:this.responsesClient,messages:e,chatOptions:t,defaultModel:this.options.defaultModel,builtInWebTools:this.options.builtInWebTools,onTextDelta:this.onTextDelta});return}try{let n=this.buildStreamingRequestParams(e,t);t?.onProviderNativeRawPayload?.({provider:`qwen`,apiSurface:`chat-completions`,payloadKind:`request`,payload:n});let r=aC(await this.client.chat.completions.create(n),{provider:`qwen`,apiSurface:`chat-completions`,onProviderNativeRawPayload:t?.onProviderNativeRawPayload});for await(let e of this.streamWithAbort(r,t?.signal)){let t=this.responseParser.parseStreamingChunk(e);t&&(yield t)}}catch(e){let t=e.message||`Qwen API request failed`;throw Error(`Qwen stream failed: ${t}`)}}supportsTools(){return!0}getCapabilities(){return kD(this.options)}validateConfig(){return!!this.client&&!!this.options&&(!this.shouldUseResponsesApi()||!!this.responsesClient)}async dispose(){}buildRequestParams(e,t){this.validateTools(t?.tools);let n=t?.model??this.options.defaultModel;if(!n)throw Error(`Model is required in chat options. Please specify a model in defaultModel configuration.`);return{model:n,messages:zS(e),...t?.temperature!==void 0&&{temperature:t.temperature},...t?.maxTokens!==void 0&&{max_tokens:t.maxTokens},...t?.tools&&{tools:BS(t.tools),tool_choice:cC(t.toolChoice)}}}buildStreamingRequestParams(e,t){return{...this.buildRequestParams(e,t),stream:!0}}shouldUseResponsesApi(){return MD(this.options.builtInWebTools)}getClient(){if(!this.client)throw Error(`Qwen client not available. Either provide a client/apiKey or use an executor.`);return this.client}getResponsesClient(){if(!this.responsesClient)throw Error(`Qwen Responses client not available for built-in web tools.`);return this.responsesClient}};async function fO(e,t=gO){let n=await t(`${hO(e.baseURL??wD)}/models`,pO(e.apiKey));if(!n.ok)return{status:`unavailable`,sourceUrl:ED,message:`Qwen model refresh failed: HTTP ${n.status}`};let r=((await n.json()).data??[]).map(e=>e.id).filter(e=>typeof e==`string`&&e.length>0).map(mO);return{status:`live`,sourceUrl:ED,lastVerifiedAt:DD,entries:r,message:`Loaded ${r.length} models from Qwen API`}}function pO(e){if(e)return{headers:{Authorization:`Bearer ${e}`}}}function mO(e){return{id:e,displayName:e,lifecycle:`active`,sourceUrl:ED,lastVerifiedAt:DD}}function hO(e){return e.replace(/\/$/,``)}async function gO(e,t){let n=await fetch(e,{...t?.headers!==void 0&&{headers:t.headers}});return{ok:n.ok,status:n.status,json:()=>n.json()}}const _O=[{kind:`api-key`,label:`Alibaba Cloud Model Studio API keys`,url:`https://modelstudio.console.alibabacloud.com/?tab=api#/api-key`,sourceUrl:`https://www.alibabacloud.com/help/en/model-studio/get-api-key`,lastVerifiedAt:`2026-05-08`}],vO={status:`fallback`,sourceUrl:ED,lastVerifiedAt:DD,entries:[{id:SD,displayName:`Qwen Plus`,capabilities:[`tools`,`reasoning`,`native_web`,`streaming`],lifecycle:`active`,sourceUrl:ED,lastVerifiedAt:DD},{id:`qwen-max`,displayName:`Qwen Max`,capabilities:[`tools`,`reasoning`,`native_web`,`streaming`],lifecycle:`active`,sourceUrl:ED,lastVerifiedAt:DD},{id:`qwen-flash`,displayName:`Qwen Flash`,capabilities:[`tools`,`native_web`,`streaming`],lifecycle:`active`,sourceUrl:ED,lastVerifiedAt:DD}]};function yO(){return{type:`qwen`,displayName:`Qwen`,description:`Alibaba Cloud Qwen series. API key required.`,category:`cloud-paid`,defaults:{model:SD,apiKey:CD,baseURL:wD},modelCatalog:vO,refreshModelCatalog:({profile:e})=>fO(e),modelCatalogCacheTtlSeconds:86400,setupHelpLinks:_O,setupSteps:[{key:`baseURL`,title:`Qwen OpenAI-compatible base URL`,defaultValue:wD},{key:`model`,title:`Qwen model`,defaultValue:SD},{key:`apiKey`,title:`Qwen Model Studio API key`,defaultValue:CD,masked:!0}],requiresApiKey:!0,probeProfile:oC,createProvider:e=>{let t=xO(e.options);return new dO({apiKey:bO(e.apiKey),...e.baseURL!==void 0&&{baseURL:e.baseURL},...t.responsesBaseURL!==void 0&&{responsesBaseURL:t.responsesBaseURL},...e.timeout!==void 0&&{timeout:e.timeout},...t.builtInWebTools!==void 0&&{builtInWebTools:t.builtInWebTools},defaultModel:e.model})}}}function bO(e){if(!e)throw Error(`Provider qwen requires apiKey`);return e}function xO(e){let t=SO(CO(e?.builtInWebTools)),n=TO(e?.responsesBaseURL);return{...n!==void 0&&{responsesBaseURL:n},...t!==void 0&&{builtInWebTools:t}}}function SO(e){if(e!==void 0)return{...wO(e.webSearch)!==void 0&&{webSearch:wO(e.webSearch)},...wO(e.webFetch)!==void 0&&{webFetch:wO(e.webFetch)},...wO(e.enableThinking)!==void 0&&{enableThinking:wO(e.enableThinking)}}}function CO(e){if(!(e==null||e instanceof Date||Array.isArray(e)))return typeof e==`object`?e:void 0}function wO(e){return typeof e==`boolean`?e:void 0}function TO(e){return typeof e==`string`&&e.length>0?e:void 0}function EO(){return[IS(),Aw(),$T(),vD(),yO(),Qw()]}const DO=`general-purpose`;function OO(e){let t=[],n=``,r,i=!1;for(let a of e){if(i){n+=a,i=!1;continue}if(r&&a===`\\`){i=!0;continue}if(r){a===r?r=void 0:n+=a;continue}if(a===`"`||a===`'`){r=a;continue}if(/\s/.test(a)){n.length>0&&(t.push(n),n=``);continue}n+=a}return n.length>0&&t.push(n),t}function kO(e){let t=[],n,r,i;for(let a=0;a<e.length;a+=1){let o=e[a];if(o!==`--background`){if(o===`--agent`||o===`--type`||o===`-a`){n=e[a+1],a+=1;continue}if(o===`--model`){r=e[a+1],a+=1;continue}if(o===`--isolation`){let t=e[a+1];(t===`none`||t===`worktree`)&&(i=t),a+=1;continue}o!==void 0&&t.push(o)}}return{positional:t,...n?{agentType:n}:{},...r?{model:r}:{},...i?{isolation:i}:{}}}function AO(e,t,n,r){return{agentType:t,label:n,mode:`background`,prompt:r,...e.model?{model:e.model}:{},...e.isolation?{isolation:e.isolation}:{}}}function jO(e,t){let n=kO(e),[r,...i]=n.positional,a=n.agentType??DO,o=n.positional;!n.agentType&&r&&t.has(r)&&(a=r,o=i);let s=o.join(` `).trim();if(s)return AO(n,a,a,s)}function MO(e,t){let n=kO(e);return n.positional.map(e=>NO(e,n,t)).filter(e=>e!==void 0)}function NO(e,t,n){let r=e.indexOf(`=`);if(r>0)return PO(e.slice(0,r),e.slice(r+1),t,n);let i=e.indexOf(`:`);if(i<=0||i===e.length-1)return;let a=e.slice(0,i),o=e.slice(i+1);return AO(t,t.agentType??(n.has(a)?a:DO),a,o)}function PO(e,t,n,r){let i=t.indexOf(`:`);if(i===-1)return AO(n,n.agentType??(r.has(e)?e:DO),e,t);if(!(i===0||i===t.length-1))return AO(n,t.slice(0,i),e,t.slice(i+1))}function FO(e){return e instanceof Error?e.message:String(e)}function IO(e){return new Set(e.listAgentDefinitions().map(e=>e.name))}function LO(e,t){let n=e.listAgentDefinitions();if(!n.some(e=>e.name===t))return{message:`Unknown agent type: ${t}\nAvailable agents: ${n.map(e=>e.name).join(`, `)}`,success:!1}}async function RO(e,t){let n=LO(e,t.agentType);if(n)return n;try{return{state:await e.spawnAgentJob(t)}}catch(e){return{message:FO(e),success:!1}}}function zO(){return{message:``,effects:[{type:`agent-switcher-requested`}],success:!0}}async function BO(e){let t=e.listAgentDefinitions(),n=e.listAgentJobs();return{message:[`Available agents:`,...t.map(e=>` ${e.name} - ${e.description}`),``,n.length===0?`No active agent jobs.`:`Agent jobs:`,...n.map(e=>` ${VO(e)}`)].join(`
234
234
  `),success:!0,data:{agents:t.length,jobs:n.length}}}function VO(e){let t=[e.worktreePath?`worktree=${e.worktreePath}`:void 0,e.branchName?`branch=${e.branchName}`:void 0].filter(e=>e!==void 0),n=t.length>0?` ${t.join(` `)}`:``;return`${e.id} [${e.status}${n}] ${e.label} - ${e.promptPreview}`}async function HO(e,t){let n=jO(t,IO(e));if(!n)return{message:`Usage: agent run [AGENT_NAME] [--agent AGENT_NAME] PROMPT`,success:!1};let r=await RO(e,n);if(`success`in r)return r;let{state:i}=r;return{message:`Started agent job: ${i.id}`,success:!0,data:{agentId:i.id,status:i.status}}}async function UO(e,t){let n=t.includes(`--wait`)||!t.includes(`--detach`),r=MO(t.filter(e=>e!==`--wait`&&e!==`--detach`),IO(e));if(r.length===0)return{message:`Usage: agent parallel [--wait|--detach] LABEL:"PROMPT" [LABEL=AGENT_NAME:"PROMPT"]`,success:!1};let i=r.map(t=>LO(e,t.agentType)).find(e=>e!==void 0);if(i)return i;let a;try{a=await Promise.all(r.map(t=>e.spawnAgentJob(t)))}catch(e){return{message:FO(e),success:!1}}let o=e.createBackgroundJobGroup({waitPolicy:`wait_all`,taskIds:a.map(e=>e.id),label:`agent parallel`});if(n){let t=sd(await e.waitBackgroundJobGroup(o.id));return{message:XO(t),success:!0,data:{agentIds:a.map(e=>e.id),groupId:o.id,summary:t}}}return{message:[`Started agent jobs:`,...a.map(e=>`${e.label}: ${e.id}`)].join(`
235
235
  `),success:!0,data:{agentIds:a.map(e=>e.id),groupId:o.id}}}async function WO(e,t){let[n]=t;if(!n)return{message:`Usage: agent wait GROUP_ID`,success:!1};let r=sd(await e.waitBackgroundJobGroup(n));return{message:XO(r),success:!0,data:{groupId:n,summary:r}}}async function GO(e,t){let[n,r]=t;if(!n)return{message:`Usage: agent read AGENT_ID [OFFSET]`,success:!1};let i=r?{offset:Number.parseInt(r,10)}:void 0,a=await e.readBackgroundTaskLog(n,i),o=a.nextCursor?`\nNext offset: ${a.nextCursor.offset}`:``;return{message:a.lines.length>0?`${a.lines.join(`
236
236
  `)}${o}`:`No log lines: ${n}`,success:!0,data:{agentId:n,nextOffset:a.nextCursor?.offset}}}async function KO(e,t){let[n,...r]=t,i=r.join(` `).trim();return!n||!i?{message:`Usage: agent send AGENT_ID PROMPT`,success:!1}:(await e.sendAgentJob(n,i),{message:`Sent input to agent job: ${n}`,success:!0,data:{agentId:n}})}async function qO(e,t){let[n,...r]=t;return n?(await e.cancelAgentJob(n,r.join(` `)||void 0),{message:`Agent job stopped: ${n}`,success:!0,data:{agentId:n}}):{message:`Usage: agent stop AGENT_ID [REASON]`,success:!1}}async function JO(e,t){let[n]=t;return n?(await e.closeAgentJob(n),{message:`Agent job closed: ${n}`,success:!0,data:{agentId:n}}):{message:`Usage: agent close AGENT_ID`,success:!1}}async function YO(e,t){try{if(t.trim()===``)return zO();let[n=`list`,...r]=OO(t);return n===`list`&&r.length===0?BO(e):n===`run`?HO(e,r):n===`parallel`?UO(e,r):n===`wait`?WO(e,r):n===`read`||n===`open`?GO(e,r):n===`send`?KO(e,r):n===`stop`||n===`cancel`?qO(e,r):n===`close`?JO(e,r):HO(e,[n,...r])}catch(e){return{message:FO(e),success:!1}}}function XO(e){return[`Background job group ${e.groupId}: ${e.status} (${e.completed}/${e.total} completed, ${e.failed} failed, ${e.cancelled} cancelled, ${e.pending} pending)`,...e.lines].join(`
@@ -245,7 +245,7 @@ Examples:
245
245
  `)}function Fk(e){let t=K_(e),n=q_(e),r=J_(e),i=Mk(e.getSession().getHistory()),a=Nk(e.getSession().getFullHistory()),o=$_(e),s=o.filter(e=>e.loadType===`system`),c=o.filter(e=>e.loadType===`manual`),l=o.filter(e=>e.loadType===`prompt-reference`),u=s.reduce((e,t)=>e+Ok(t.byteLength),0),d=c.reduce((e,t)=>e+Ok(t.byteLength),0),f=l.reduce((e,t)=>e+Ok(t.byteLength),0),p=a.turnCount===0?`Conversation history — 0 turns`:`Conversation history — ${a.turnCount} turn${a.turnCount===1?``:`s`} | ~${i.totalTokens.toLocaleString()} tokens`,m=a.toolResults.map(e=>`${e.toolName}${e.displayArg?`: ${e.displayArg}`:``}`),h=a.toolResults.length,g=a.totalToolCallCount,_=g===0?`Tool results (0): (none)`:h<g?`Tool results (${h} unique / ${g} calls, ~${i.toolTokens.toLocaleString()} tokens):`:`Tool results (${h}, ~${i.toolTokens.toLocaleString()} tokens):`,v=a.turnCount===0?[]:[`User (${i.userCount}): ~${i.userTokens.toLocaleString()} tokens`,`Assistant (${i.assistantCount}): ~${i.assistantTokens.toLocaleString()} tokens`,...i.systemTokens>0?[`System messages: ~${i.systemTokens.toLocaleString()} tokens`]:[],g>0?[_,...m.map(e=>` ${e}`)].join(`
246
246
  `):_],y=a.turnCount===0?`${p}:\n (none)`:[`${p}:`,...v.map(e=>` ${e}`)].join(`
247
247
  `);return{success:!0,message:[`Context: ${t.usedTokens.toLocaleString()} / ${t.maxTokens.toLocaleString()} tokens (${Math.round(t.usedPercentage)}%)`,_k(n,r),``,Pk(`System prompt (active every turn)`,u,s.map(kk)),``,y,``,Pk(`Manually added`,d,c.map(kk)),``,Pk(`Prompt references (@-syntax)`,f,l.map(kk))].join(`
248
- `),data:{references:o,history:{turnCount:a.turnCount,toolResults:a.toolResults}}}}function Ik(){return{name:`context`,displayName:`Context References`,description:`Context window info, reference inventory, and auto-compact controls`,source:`context`,modelInvocable:!1,argumentHint:`list | add <path> | remove <path> | clear | auto ...`,subcommands:[{name:`list`,description:`List loaded context references`,source:`context`},{name:`add`,description:`Add a file to active context references`,source:`context`},{name:`remove`,description:`Remove a context reference`,source:`context`},{name:`clear`,description:`Clear context references`,source:`context`},{name:`auto`,description:`Inspect or change auto-compact policy`,source:`context`}]}}function Lk(){let e=Ik();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,execute:yk}}var Rk=class{name=`context`;getCommands(){return[Ik()]}};function zk(){return{name:`agent-command-context`,commandSources:[new Rk],systemCommands:[Lk()]}}function Bk(){let e=process.env.VISUAL?.trim(),t=process.env.EDITOR?.trim(),n=(e!==void 0&&e.length>0?e:t!==void 0&&t.length>0?t:`vi`).split(/\s+/).filter(e=>e.length>0);return{command:n[0]??`vi`,args:n.slice(1)}}function Vk(e,t,n){return new Promise((r,a)=>{let o=i(e,[...t],{cwd:n,stdio:`inherit`,env:process.env});o.on(`error`,a),o.on(`exit`,(e,t)=>{if(e!==null){r(e);return}if(t){let e=b.signals[t];r(128+(e??0));return}r(0)})})}async function Hk(e,t){if(e.canHandoffTerminal?.()!==!0||e.runWithTerminal===void 0)return{message:`An editor is unavailable here (no interactive terminal).`,success:!1};let n=Bk(),r=te(h(S(),`robota-editor-`)),i=h(r,`message.md`);k(i,t??``,`utf8`);try{let t=await e.runWithTerminal(async()=>Vk(n.command,[...n.args,i],e.getCwd()));if(t!==0)return{message:`Editor exited without saving (code ${t}).`,success:!1,data:{exitCode:t}};let r=O(i,`utf8`).replace(/\s+$/u,``);return r.length===0?{message:`Editor closed with empty content; nothing composed.`,success:!1}:{message:r,success:!0,data:{content:r}}}finally{ie(r,{recursive:!0,force:!0,maxRetries:3,retryDelay:20})}}function Uk(){return{name:`editor`,displayName:`Editor`,description:"Compose a message in $EDITOR (optionally pre-filled with `/editor <text>`), then return it.",source:`editor`,modelInvocable:!1}}function Wk(){let e=Uk();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Hk}}var Gk=class{name=`editor`;getCommands(){return[Uk()]}};function Kk(){return{name:`agent-command-editor`,commandSources:[new Gk],systemCommands:[Wk()]}}async function qk(e,t){let n=e.getUserInteraction?.();return n&&!_t(await n.ask(mt(`exit`,`Exit the session?`)))?{success:!0,message:`Exit cancelled.`}:{success:!0,message:`Exit requested.`,effects:[Yv()]}}function Jk(){return{name:`exit`,displayName:`Exit Session`,description:`Exit CLI`,source:`exit`,modelInvocable:!1}}function Yk(){let e=Jk();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:qk}}var Xk=class{name=`exit`;getCommands(){return[Jk()]}};function Zk(){return{name:`agent-command-exit`,commandSources:[new Xk],systemCommands:[Yk()]}}function Qk(e){let t=[`Goal: ${e.objective}`,`Status: ${e.status}${e.stopReason?` (${e.stopReason})`:``}`,`Iterations: ${e.iterations} / ${e.maxIterations}`],n=e.progress[e.progress.length-1];return n?.reason&&t.push(`Latest: ${n.reason}`),t.join(`
248
+ `),data:{references:o,history:{turnCount:a.turnCount,toolResults:a.toolResults}}}}function Ik(){return{name:`context`,displayName:`Context References`,description:`Context window info, reference inventory, and auto-compact controls`,source:`context`,modelInvocable:!1,argumentHint:`list | add <path> | remove <path> | clear | auto ...`,subcommands:[{name:`list`,description:`List loaded context references`,source:`context`},{name:`add`,description:`Add a file to active context references`,source:`context`},{name:`remove`,description:`Remove a context reference`,source:`context`},{name:`clear`,description:`Clear context references`,source:`context`},{name:`auto`,description:`Inspect or change auto-compact policy`,source:`context`}]}}function Lk(){let e=Ik();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,execute:yk}}var Rk=class{name=`context`;getCommands(){return[Ik()]}};function zk(){return{name:`agent-command-context`,commandSources:[new Rk],systemCommands:[Lk()]}}function Bk(){let e=process.env.VISUAL?.trim(),t=process.env.EDITOR?.trim(),n=(e!==void 0&&e.length>0?e:t!==void 0&&t.length>0?t:`vi`).split(/\s+/).filter(e=>e.length>0);return{command:n[0]??`vi`,args:n.slice(1)}}function Vk(e,t,n){return new Promise((r,a)=>{let o=i(e,[...t],{cwd:n,stdio:`inherit`,env:process.env});o.on(`error`,a),o.on(`exit`,(e,t)=>{if(e!==null){r(e);return}if(t){let e=b.signals[t];r(128+(e??0));return}r(0)})})}async function Hk(e,t){if(e.canHandoffTerminal?.()!==!0||e.runWithTerminal===void 0)return{message:`An editor is unavailable here (no interactive terminal).`,success:!1};let n=Bk(),r=k(h(S(),`robota-editor-`)),i=h(r,`message.md`);ae(i,t??``,`utf8`);try{let t=await e.runWithTerminal(async()=>Vk(n.command,[...n.args,i],e.getCwd()));if(t!==0)return{message:`Editor exited without saving (code ${t}).`,success:!1,data:{exitCode:t}};let r=A(i,`utf8`).replace(/\s+$/u,``);return r.length===0?{message:`Editor closed with empty content; nothing composed.`,success:!1}:{message:r,success:!0,data:{content:r}}}finally{ne(r,{recursive:!0,force:!0,maxRetries:3,retryDelay:20})}}function Uk(){return{name:`editor`,displayName:`Editor`,description:"Compose a message in $EDITOR (optionally pre-filled with `/editor <text>`), then return it.",source:`editor`,modelInvocable:!1}}function Wk(){let e=Uk();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:Hk}}var Gk=class{name=`editor`;getCommands(){return[Uk()]}};function Kk(){return{name:`agent-command-editor`,commandSources:[new Gk],systemCommands:[Wk()]}}async function qk(e,t){let n=e.getUserInteraction?.();return n&&!_t(await n.ask(mt(`exit`,`Exit the session?`)))?{success:!0,message:`Exit cancelled.`}:{success:!0,message:`Exit requested.`,effects:[Yv()]}}function Jk(){return{name:`exit`,displayName:`Exit Session`,description:`Exit CLI`,source:`exit`,modelInvocable:!1}}function Yk(){let e=Jk();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:qk}}var Xk=class{name=`exit`;getCommands(){return[Jk()]}};function Zk(){return{name:`agent-command-exit`,commandSources:[new Xk],systemCommands:[Yk()]}}function Qk(e){let t=[`Goal: ${e.objective}`,`Status: ${e.status}${e.stopReason?` (${e.stopReason})`:``}`,`Iterations: ${e.iterations} / ${e.maxIterations}`],n=e.progress[e.progress.length-1];return n?.reason&&t.push(`Latest: ${n.reason}`),t.join(`
249
249
  `)}async function $k(e,t){let n=t.trim(),r=n.split(/\s+/)[0]?.toLowerCase()??``;if(n.length===0||r===`help`)return{message:`Usage:
250
250
  /goal <objective> assign a goal and pursue it autonomously
251
251
  /goal status show the current goal and progress
@@ -291,37 +291,37 @@ Examples:
291
291
  `),success:!0,data:{count:e.length,checkpoints:[...e]}}}function NM(e){return e.length>0?e.join(`, `):`(none)`}function PM(e){let t=e.capturedFiles.length>0?e.capturedFiles.map(e=>{let t=e.snapshotSizeBytes===void 0?``:` size=${e.snapshotSizeBytes}B`;return`- ${e.relativePath} action=${e.restoreAction} snapshot=${String(e.snapshotAvailable)}${t}`}):[`(no files captured)`];return{message:[`Checkpoint ${e.target.id}`,`Prompt: ${jM(e.target.prompt)}`,`Captured files:`,...t,`Restore later checkpoints: files=${e.restoreToCheckpoint.fileCount} checkpoints=${NM(e.restoreToCheckpoint.checkpointIds)}`,`Rollback through checkpoint: files=${e.rollbackThroughCheckpoint.fileCount} checkpoints=${NM(e.rollbackThroughCheckpoint.checkpointIds)}`].join(`
292
292
  `),success:!0,data:{inspection:e}}}function FM(e){return{message:[`Restored code to ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Rolled back checkpoints: ${e.restoredCheckpointCount}`].join(`
293
293
  `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function IM(e){return{message:[`Rolled back code through ${e.target.id}.`,`Restored files: ${e.restoredFileCount}`,`Removed checkpoints: ${e.removedCheckpointCount}`].join(`
294
- `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function LM(e){return{message:e instanceof Error?e.message:String(e),success:!1}}function RM(e,t){if(!t)return AM();try{return PM(ny(e,t))}catch(e){return LM(e instanceof Error?e:String(e))}}async function zM(e,t){if(!t)return AM();try{return FM(await ry(e,t))}catch(e){return LM(e instanceof Error?e:String(e))}}async function BM(e,t){if(!t)return AM();try{return IM(await iy(e,t))}catch(e){return LM(e instanceof Error?e:String(e))}}async function VM(e,t){let n=t.trim().split(/\s+/).filter(Boolean),r=n[0]??`list`;return r===`list`?MM(ty(e)):r===`inspect`?RM(e,n[1]):r===`restore`||r===`code`?zM(e,n[1]):r===`rollback`?BM(e,n[1]):AM()}function HM(){return{name:`rewind`,displayName:`Rewind History`,description:`List, inspect, restore, or rollback edit checkpoints.`,source:`rewind`,argumentHint:`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`,modelInvocable:!1,safety:`write`,subcommands:ey()}}function UM(){let e=HM();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,argumentHint:e.argumentHint,userInvocable:!0,modelInvocable:!1,safety:`write`,subcommands:e.subcommands,execute:VM}}var WM=class{name=`rewind`;getCommands(){return[HM()]}};function GM(){return{name:`agent-command-rewind`,commandSources:[new WM],systemCommands:[UM()]}}const KM={s:1e3,m:6e4,h:36e5,d:864e5},qM=`Usage: /schedule in <N><s|m|h|d> <instruction> | /schedule cron "<expr>" <instruction>`;function JM(e,t){let n=e.trim();if(n.length===0)return{ok:!1,error:qM};if(n.startsWith(`in `)){let e=n.slice(3).trim(),r=e.indexOf(` `);if(r===-1)return{ok:!1,error:`Missing instruction. ${qM}`};let i=e.slice(0,r),a=e.slice(r+1).trim(),o=/^(\d+)(s|m|h|d)$/.exec(i);if(!o)return{ok:!1,error:`Invalid duration "${i}". ${qM}`};if(a.length===0)return{ok:!1,error:`Missing instruction. ${qM}`};let s=parseInt(o[1],10)*KM[o[2]];return{ok:!0,spec:{cronExpression:new Date(t+s).toISOString(),instruction:a,recurring:!1}}}if(n.startsWith(`cron `)){let e=n.slice(5).trim(),t=/^["']([^"']+)["']\s+(.+)$/.exec(e);if(!t)return{ok:!1,error:`cron form needs a quoted expression. ${qM}`};let r=t[2].trim();return r.length===0?{ok:!1,error:`Missing instruction. ${qM}`}:{ok:!0,spec:{cronExpression:t[1].trim(),instruction:r,recurring:!0}}}return{ok:!1,error:qM}}function YM(e,t){return`${e}: ${t.slice(0,48)}${t.length>48?`…`:``}`}async function XM(e,t,n=Date.now()){let r=JM(t,n);if(!r.ok)return{message:r.error,success:!1};let{cronExpression:i,instruction:a,recurring:o}=r.spec,s=await e.spawnScheduledWake({label:YM(`Scheduled`,a),cronExpression:i,agentInstruction:a});return{message:`Scheduled wake (${o?`cron \`${i}\``:`once at ${i}`}): "${a}" — task ${s.id}.`,success:!0,data:{taskId:s.id,cronExpression:i,recurring:o}}}function ZM(e){let t=/^["']([^"']+)["']\s+["']([^"']+)["']\s+(.+)$/.exec(e.trim());if(!t)return null;let n=t[3].trim();return n.length===0?null:{command:t[1],matchPattern:t[2],instruction:n}}async function QM(e,t){let n=ZM(t);if(!n)return{message:`Usage: /monitor "<command>" "<pattern>" <instruction>`,success:!1};let r=await e.spawnMonitorWake({label:YM(`Monitor`,n.instruction),command:n.command,matchPattern:n.matchPattern,agentInstruction:n.instruction});return{message:`Monitoring \`${n.command}\` for /${n.matchPattern}/ — task ${r.id}.`,success:!0,data:{taskId:r.id,matchPattern:n.matchPattern}}}function $M(e){let t=e.getAgentJobCapability?.();if(!t)throw Error(`Scheduling requires an active agent runtime.`);return t}function eN(){return{name:`schedule`,displayName:`Schedule Wake`,description:`Schedule the agent to wake and run an instruction on a timer (one-shot or cron).`,source:`schedule`,argumentHint:`in <N><s|m|h|d> <instruction> | cron "<expr>" <instruction>`,modelInvocable:!0}}function tN(){return{name:`monitor`,displayName:`Monitor Process`,description:`Watch a process’s output and wake the agent when a line matches a pattern.`,source:`schedule`,argumentHint:`"<command>" "<pattern>" <instruction>`,modelInvocable:!0}}function nN(){let e=eN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>XM($M(e),t)}}function rN(){let e=tN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>QM($M(e),t)}}var iN=class{name=`schedule`;getCommands(){return[eN(),tN()]}};function aN(){return{name:`agent-command-schedule`,commandSources:[new iN],systemCommands:[nN(),rN()],sessionRequirements:[`agent-runtime`]}}function oN(e,t,n){return Ra(e,t,n)}function sN(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function cN(e){return e.toLocaleString(`en-US`)}async function lN(e,t){let n=e.getUserInteraction?.();return n&&!_t(await n.ask(mt(`clear`,`Clear conversation history?`)))?{success:!0,message:`Clear cancelled.`}:(Gv(e),{success:!0,message:`Conversation cleared.`,effects:[{type:`conversation-history-cleared`}]})}function uN(e,t){let n=Kv(t);return n===void 0?{success:!1,message:`Usage: rename <name>`}:{success:!0,message:`Session renamed to "${n}".`,data:{name:n},effects:[qv(n)]}}function dN(e,t){return{success:!0,message:`Opening session picker...`,data:{triggerResumePicker:!0},effects:[Jv()]}}const fN=`.robota/budget.json`;function pN(e){let t=h(e,fN);if(!T(t))return;let n;try{n=O(t,`utf-8`)}catch{return}try{return JSON.parse(n)}catch{return}}function mN(e,t){D(h(e,`.robota`),{recursive:!0}),k(h(e,fN),JSON.stringify(t,null,2))}function hN(e){let t=h(e,fN);T(t)&&k(t,`{}`)}function gN(e){let t=e.getSession(),n=Xv(e),r=t.getSessionTokenUsage?.(),i=t.getModelId?.(),a=[`Session: ${n.sessionId}`,`Messages: ${n.messageCount}`],o={sessionId:n.sessionId,messageCount:n.messageCount};if(r){if(a.push(`Tokens: ${cN(r.inputTokens)} input / ${cN(r.outputTokens)} output`),o.inputTokens=r.inputTokens,o.outputTokens=r.outputTokens,i){let t=oN(i,r.inputTokens,r.outputTokens);if(t!==void 0){a.push(`Cost: ${sN(t)} (${i})`),o.estimatedCostUsd=t;let n=pN(e.getCwd());if(n?.monthly){let e=n.monthly-t,r=Math.min(100,Math.round(t/n.monthly*100));a.push(`Budget: ${sN(e)} remaining of ${sN(n.monthly)}/mo (${r}% used)`),o.budgetMonthly=n.monthly,o.budgetRemainingUsd=e}}}}else a.push(`Tokens: not yet available (no turns completed)`);return{lines:a,data:o}}function _N(e,t){let n=t.trim();if(n.startsWith(`budget`)){let t=n.slice(6).trim();if(t===`clear`)return hN(e.getCwd()),{success:!0,message:`Monthly budget cleared.`};if(t===``){let t=pN(e.getCwd());return t?.monthly?{success:!0,message:`Monthly budget: ${sN(t.monthly)}`}:{success:!0,message:`No budget set. Use: /cost budget <amount>`}}let r=parseFloat(t);return!Number.isFinite(r)||r<=0?{success:!1,message:`Usage: /cost budget <amount> (e.g. /cost budget 5.00)`}:(mN(e.getCwd(),{monthly:r}),{success:!0,message:`Monthly budget set to ${sN(r)}.`})}let{lines:r,data:i}=gN(e);return{success:!0,message:r.join(`
294
+ `),success:!0,data:{target:e.target,restoredCheckpointCount:e.restoredCheckpointCount,restoredFileCount:e.restoredFileCount,removedCheckpointCount:e.removedCheckpointCount}}}function LM(e){return{message:e instanceof Error?e.message:String(e),success:!1}}function RM(e,t){if(!t)return AM();try{return PM(ny(e,t))}catch(e){return LM(e instanceof Error?e:String(e))}}async function zM(e,t){if(!t)return AM();try{return FM(await ry(e,t))}catch(e){return LM(e instanceof Error?e:String(e))}}async function BM(e,t){if(!t)return AM();try{return IM(await iy(e,t))}catch(e){return LM(e instanceof Error?e:String(e))}}async function VM(e,t){let n=t.trim().split(/\s+/).filter(Boolean),r=n[0]??`list`;return r===`list`?MM(ty(e)):r===`inspect`?RM(e,n[1]):r===`restore`||r===`code`?zM(e,n[1]):r===`rollback`?BM(e,n[1]):AM()}function HM(){return{name:`rewind`,displayName:`Rewind History`,description:`List, inspect, restore, or rollback edit checkpoints.`,source:`rewind`,argumentHint:`list | inspect CHECKPOINT_ID | restore CHECKPOINT_ID | code CHECKPOINT_ID | rollback CHECKPOINT_ID`,modelInvocable:!1,safety:`write`,subcommands:ey()}}function UM(){let e=HM();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,argumentHint:e.argumentHint,userInvocable:!0,modelInvocable:!1,safety:`write`,subcommands:e.subcommands,execute:VM}}var WM=class{name=`rewind`;getCommands(){return[HM()]}};function GM(){return{name:`agent-command-rewind`,commandSources:[new WM],systemCommands:[UM()]}}const KM={s:1e3,m:6e4,h:36e5,d:864e5},qM=`Usage: /schedule in <N><s|m|h|d> <instruction> | /schedule cron "<expr>" <instruction>`;function JM(e,t){let n=e.trim();if(n.length===0)return{ok:!1,error:qM};if(n.startsWith(`in `)){let e=n.slice(3).trim(),r=e.indexOf(` `);if(r===-1)return{ok:!1,error:`Missing instruction. ${qM}`};let i=e.slice(0,r),a=e.slice(r+1).trim(),o=/^(\d+)(s|m|h|d)$/.exec(i);if(!o)return{ok:!1,error:`Invalid duration "${i}". ${qM}`};if(a.length===0)return{ok:!1,error:`Missing instruction. ${qM}`};let s=parseInt(o[1],10)*KM[o[2]];return{ok:!0,spec:{cronExpression:new Date(t+s).toISOString(),instruction:a,recurring:!1}}}if(n.startsWith(`cron `)){let e=n.slice(5).trim(),t=/^["']([^"']+)["']\s+(.+)$/.exec(e);if(!t)return{ok:!1,error:`cron form needs a quoted expression. ${qM}`};let r=t[2].trim();return r.length===0?{ok:!1,error:`Missing instruction. ${qM}`}:{ok:!0,spec:{cronExpression:t[1].trim(),instruction:r,recurring:!0}}}return{ok:!1,error:qM}}function YM(e,t){return`${e}: ${t.slice(0,48)}${t.length>48?`…`:``}`}async function XM(e,t,n=Date.now()){let r=JM(t,n);if(!r.ok)return{message:r.error,success:!1};let{cronExpression:i,instruction:a,recurring:o}=r.spec,s=await e.spawnScheduledWake({label:YM(`Scheduled`,a),cronExpression:i,agentInstruction:a});return{message:`Scheduled wake (${o?`cron \`${i}\``:`once at ${i}`}): "${a}" — task ${s.id}.`,success:!0,data:{taskId:s.id,cronExpression:i,recurring:o}}}function ZM(e){let t=/^["']([^"']+)["']\s+["']([^"']+)["']\s+(.+)$/.exec(e.trim());if(!t)return null;let n=t[3].trim();return n.length===0?null:{command:t[1],matchPattern:t[2],instruction:n}}async function QM(e,t){let n=ZM(t);if(!n)return{message:`Usage: /monitor "<command>" "<pattern>" <instruction>`,success:!1};let r=await e.spawnMonitorWake({label:YM(`Monitor`,n.instruction),command:n.command,matchPattern:n.matchPattern,agentInstruction:n.instruction});return{message:`Monitoring \`${n.command}\` for /${n.matchPattern}/ — task ${r.id}.`,success:!0,data:{taskId:r.id,matchPattern:n.matchPattern}}}function $M(e){let t=e.getAgentJobCapability?.();if(!t)throw Error(`Scheduling requires an active agent runtime.`);return t}function eN(){return{name:`schedule`,displayName:`Schedule Wake`,description:`Schedule the agent to wake and run an instruction on a timer (one-shot or cron).`,source:`schedule`,argumentHint:`in <N><s|m|h|d> <instruction> | cron "<expr>" <instruction>`,modelInvocable:!0}}function tN(){return{name:`monitor`,displayName:`Monitor Process`,description:`Watch a process’s output and wake the agent when a line matches a pattern.`,source:`schedule`,argumentHint:`"<command>" "<pattern>" <instruction>`,modelInvocable:!0}}function nN(){let e=eN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>XM($M(e),t)}}function rN(){let e=tN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,lifecycle:`inline`,execute:(e,t)=>QM($M(e),t)}}var iN=class{name=`schedule`;getCommands(){return[eN(),tN()]}};function aN(){return{name:`agent-command-schedule`,commandSources:[new iN],systemCommands:[nN(),rN()],sessionRequirements:[`agent-runtime`]}}function oN(e,t,n){return Ra(e,t,n)}function sN(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function cN(e){return e.toLocaleString(`en-US`)}async function lN(e,t){let n=e.getUserInteraction?.();return n&&!_t(await n.ask(mt(`clear`,`Clear conversation history?`)))?{success:!0,message:`Clear cancelled.`}:(Gv(e),{success:!0,message:`Conversation cleared.`,effects:[{type:`conversation-history-cleared`}]})}function uN(e,t){let n=Kv(t);return n===void 0?{success:!1,message:`Usage: rename <name>`}:{success:!0,message:`Session renamed to "${n}".`,data:{name:n},effects:[qv(n)]}}function dN(e,t){return{success:!0,message:`Opening session picker...`,data:{triggerResumePicker:!0},effects:[Jv()]}}const fN=`.robota/budget.json`;function pN(e){let t=h(e,fN);if(!E(t))return;let n;try{n=A(t,`utf-8`)}catch{return}try{return JSON.parse(n)}catch{return}}function mN(e,t){O(h(e,`.robota`),{recursive:!0}),ae(h(e,fN),JSON.stringify(t,null,2))}function hN(e){let t=h(e,fN);E(t)&&ae(t,`{}`)}function gN(e){let t=e.getSession(),n=Xv(e),r=t.getSessionTokenUsage?.(),i=t.getModelId?.(),a=[`Session: ${n.sessionId}`,`Messages: ${n.messageCount}`],o={sessionId:n.sessionId,messageCount:n.messageCount};if(r){if(a.push(`Tokens: ${cN(r.inputTokens)} input / ${cN(r.outputTokens)} output`),o.inputTokens=r.inputTokens,o.outputTokens=r.outputTokens,i){let t=oN(i,r.inputTokens,r.outputTokens);if(t!==void 0){a.push(`Cost: ${sN(t)} (${i})`),o.estimatedCostUsd=t;let n=pN(e.getCwd());if(n?.monthly){let e=n.monthly-t,r=Math.min(100,Math.round(t/n.monthly*100));a.push(`Budget: ${sN(e)} remaining of ${sN(n.monthly)}/mo (${r}% used)`),o.budgetMonthly=n.monthly,o.budgetRemainingUsd=e}}}}else a.push(`Tokens: not yet available (no turns completed)`);return{lines:a,data:o}}function _N(e,t){let n=t.trim();if(n.startsWith(`budget`)){let t=n.slice(6).trim();if(t===`clear`)return hN(e.getCwd()),{success:!0,message:`Monthly budget cleared.`};if(t===``){let t=pN(e.getCwd());return t?.monthly?{success:!0,message:`Monthly budget: ${sN(t.monthly)}`}:{success:!0,message:`No budget set. Use: /cost budget <amount>`}}let r=parseFloat(t);return!Number.isFinite(r)||r<=0?{success:!1,message:`Usage: /cost budget <amount> (e.g. /cost budget 5.00)`}:(mN(e.getCwd(),{monthly:r}),{success:!0,message:`Monthly budget set to ${sN(r)}.`})}let{lines:r,data:i}=gN(e);return{success:!0,message:r.join(`
295
295
  `),data:i}}function vN(e,t){let n=Zv(e);return{success:n.validation.ok,message:Qv(n),data:{logFile:n.logFile,entryCount:n.entryCount,issueCount:n.validation.issues.length,ok:n.validation.ok}}}function yN(){return{name:`clear`,displayName:`Clear History`,description:`Clear conversation history`,source:`session`,modelInvocable:!1}}function bN(){return{name:`rename`,displayName:`Rename Session`,description:`Rename the current session`,source:`session`,modelInvocable:!1}}function xN(){return{name:`resume`,displayName:`Resume Session`,description:`Resume a previous session`,source:`session`,modelInvocable:!1}}function SN(){return{name:`cost`,displayName:`Session Cost`,description:`Show session token usage and estimated cost. /cost budget <amount> sets a monthly budget.`,source:`session`,modelInvocable:!1}}function CN(){return{name:`validate-session`,displayName:`Validate Session`,description:`Validate current session replay log`,source:`session`,modelInvocable:!1}}function wN(){let e=yN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:lN}}function TN(){let e=bN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:uN}}function EN(){let e=xN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:dN}}function DN(){let e=SN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:_N}}function ON(){let e=CN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:vN}}var kN=class{name=`session`;getCommands(){return[yN(),bN(),xN(),SN(),CN()]}};function AN(){return{name:`agent-command-session`,commandSources:[new kN],systemCommands:[wN(),TN(),EN(),DN(),ON()]}}function jN(){return{name:`settings`,displayName:`Settings`,description:`Open transport settings — enable/disable transports and configure options`,source:`settings`,modelInvocable:!1}}function MN(){let e=jN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:async()=>({success:!0,message:`Opening settings...`,effects:[{type:`settings-tui-requested`}]})}}var NN=class{name=`settings`;getCommands(){return[jN()]}};function PN(){return{name:`agent-command-settings`,commandSources:[new NN],systemCommands:[MN()]}}function FN(){let e=Yr();return{command:e.command,interactiveArgs:e.interactiveArgs,commandArgs:t=>e.commandArgs(t)}}async function IN(e,t){if(e.canHandoffTerminal?.()!==!0||e.runWithTerminal===void 0)return{message:`An interactive shell is unavailable here (no interactive terminal).`,success:!1};let n=FN(),r=e.getCwd(),i=t.trim(),a=await e.runWithTerminal(async()=>i.length>0?Vk(n.command,n.commandArgs(i),r):Vk(n.command,n.interactiveArgs,r));return{message:i.length>0?`Command exited (code ${a}).`:`Shell session ended (code ${a}).`,success:a===0,data:{exitCode:a}}}function LN(){return{name:`shell`,displayName:`Shell`,description:"Drop to an interactive shell (or run `/shell <command>` interactively), then return to the agent.",source:`shell`,modelInvocable:!1}}function RN(){let e=LN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!0,userInvocable:!0,modelInvocable:!1,lifecycle:`inline`,execute:IN}}var zN=class{name=`shell`;getCommands(){return[LN()]}};function BN(){return{name:`agent-command-shell`,commandSources:[new zN],systemCommands:[RN()]}}function VN(e){let t=[];return e.modelInvocable||t.push(`model-disabled`),e.userInvocable||t.push(`model-only`),e.context&&t.push(`context:${e.context}`),e.agent&&t.push(`agent:${e.agent}`),t.length>0?` [${t.join(`, `)}]`:``}function HN(e){let t=e.argumentHint?` ${e.argumentHint}`:``;return`- ${e.name}${t}: ${e.description}${VN(e)}`}function UN(e){return e.length===0?[`No skills are registered for this session.`,``,`Skills are metadata until activated. Do not invent or imitate a skill workflow when no matching registered skill exists.`].join(`
296
296
  `):[`Registered skills:`,...e.map(HN),``,`Activation contract:`,`- Use /skills <skill-name> [args] to activate a matching skill.`,`- Treat /<skill-name> as a virtual alias for /skills <skill-name>.`,`- The system prompt Skills section is skill selection metadata.`,`- Treat descriptions as selection metadata only, not as loaded SKILL.md content.`,`- Do not answer by merely naming, recommending, or imitating a matching skill.`,`- If no listed skill matches the task, continue without claiming a skill was activated.`].join(`
297
297
  `)}function WN(e){let t=e.trim();if(t.length===0||t===`list`)return{action:`list`,skillArgs:``};let[n=``,...r]=t.split(/\s+/);return n.length===0?{action:`list`,skillArgs:``}:{action:`activate`,skillName:n,skillArgs:r.join(` `)}}async function GN(e,t=``){let n=WN(t);if(n.action===`activate`&&n.skillName!==void 0){if(!e.executeSkillCommandByName)return{success:!1,message:`Skill activation is not available in this session.`};let t=`/${n.skillName}${n.skillArgs?` ${n.skillArgs}`:``}`;return await e.executeSkillCommandByName(n.skillName,n.skillArgs,{invocationSource:e.getCommandInvocationSource?.()??`user`,displayInput:t,rawInput:t})??{success:!1,message:`Unknown skill: ${n.skillName}`}}let r=e.listSkills?.()??[];return{success:!0,message:UN(r),data:{skills:r,activationContract:{activateWith:`/skills <skill-name> [args]`,activationRequiredBeforeWorkflow:!0,metadataIsNotSkillContent:!0}}}}function KN(){return{name:`skills`,displayName:`Skills`,description:`Skill command. Before following a matching registered skill from the system prompt Skills section, invoke the projected skills command tool with args "<skill-name> [args]". Without arguments, list registered skills. With a skill name, activate that skill. Slash syntax is a UI input/display concern; the SDK command identity is "skills".`,source:`skills`,modelInvocable:!0,userInvocable:!0,argumentHint:`[list | <skill-name> [args]]`,safety:`read-only`}}function qN(){let e=KN();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:e.argumentHint,safety:e.safety,lifecycle:`inline`,execute:GN}}var JN=class{name=`skills`;getCommands(){return[KN()]}};function YN(e){let t=[new JN];return t.push(new Hm(e.cwd)),{name:`agent-command-skills`,commandSources:t,systemCommands:[qN()]}}const XN=[`Usage: /statusline on | off | reset | git on | git off`,`Fields: model, context, permission mode, message count, session name, thinking state, git branch.`].join(`
298
298
  `);function ZN(e){let t=e.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0),[n,r]=t;return n===`on`&&r===void 0?{success:!0,message:`Status line enabled.`,patch:{enabled:!0}}:n===`off`&&r===void 0?{success:!0,message:`Status line disabled.`,patch:{enabled:!1}}:n===`reset`&&r===void 0?{success:!0,message:`Status line settings reset.`,patch:{...Fv}}:n===`git`&&r===`on`&&t.length===2?{success:!0,message:`Status line git branch shown.`,patch:{gitBranch:!0}}:n===`git`&&r===`off`&&t.length===2?{success:!0,message:`Status line git branch hidden.`,patch:{gitBranch:!1}}:{success:!1,message:XN}}function QN(e,t){let n=ZN(t);return n.success?{success:!0,message:n.message,effects:[{type:`statusline-settings-patch`,patch:n.patch}]}:{success:!1,message:n.message}}function $N(){return{name:`statusline`,displayName:`Status Line`,description:`Configure TUI status-line visibility and fields such as model, context, tokens, session, and git branch.`,source:`statusline`,argumentHint:`on | off | reset | git on | git off`,subcommands:Iv(`statusline`),modelInvocable:!1}}function eP(){let e=$N();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:QN}}var tP=class{name=`statusline`;getCommands(){return[$N()]}};function nP(){return{name:`agent-command-statusline`,commandSources:[new tP],systemCommands:[eP()]}}const rP=`Usage: user-local storage list [--format json] | user-local memory set <category> <key> <value> --summary <summary> --source <source> | user-local memory list [--format json] | user-local memory inspect <category> <key> [--format json] | user-local memory disable <category> <key> | user-local memory delete <category> <key>`;function iP(e){return e.length===0?`No user-local memory items.`:e.map(e=>`- ${e.category}/${e.key} (${e.enabled?`enabled`:`disabled`})`).join(`
299
299
  `)}function aP(e){if(e===void 0)throw Error(`User-local memory category is required.`);return e}async function oP(e,t){let n=await Ob({activeRepositoryRoot:e});return{message:t.format===`json`?JSON.stringify(n,null,2):iP(n.items),success:!0,data:{list:n}}}async function sP(e,t){let[n,r,i]=t.positional,a=await Db({activeRepositoryRoot:e,category:aP(n),key:r??``,value:i??``,summary:t.summary??``,source:t.source??``});return{message:`Stored user-local memory item ${a.category}/${a.key} at ${a.storageLocation}`,success:!0,data:{item:a}}}async function cP(e,t){let[n,r]=t.positional,i=await kb({activeRepositoryRoot:e,category:aP(n),key:r??``});return{message:t.format===`json`?JSON.stringify(i,null,2):`${i.category}/${i.key}: ${i.summary}`,success:!0,data:{item:i}}}async function lP(e,t){let[n,r]=t.positional,i=await Ab({activeRepositoryRoot:e,category:aP(n),key:r??``});return{message:`Disabled user-local memory item ${i.category}/${i.key}`,success:!0,data:{item:i}}}async function uP(e,t){let[n,r]=t.positional,i=await jb({activeRepositoryRoot:e,category:aP(n),key:r??``});return{message:`Deleted user-local memory item ${i.category}/${i.key}`,success:!0,data:{result:i}}}async function dP(e,t){return(t.action??`list`)===`list`?oP(e,t):t.action===`set`?sP(e,t):t.action===`inspect`?cP(e,t):t.action===`disable`?lP(e,t):t.action===`delete`?uP(e,t):{message:rP,success:!1}}function fP(e){if(e===void 0||e===`text`)return`text`;if(e===`json`)return`json`;throw Error(`Unsupported user-local output format: ${e}`)}function pP(e,t,n){return e===`--format`?{format:t[n+1],nextIndex:n+1}:e.startsWith(`--format=`)?{format:e.slice(9),nextIndex:n}:e===`--summary`?{summary:t[n+1],nextIndex:n+1}:e.startsWith(`--summary=`)?{summary:e.slice(10),nextIndex:n}:e===`--source`?{source:t[n+1],nextIndex:n+1}:e.startsWith(`--source=`)?{source:e.slice(9),nextIndex:n}:null}function mP(e,t={}){let n=t.format,r=t.summary,i=t.source,a=[];for(let t=0;t<e.length;t+=1){let o=e[t],s=pP(o,e,t);if(s!==null){n=s.format??n,r=s.summary??r,i=s.source??i,t=s.nextIndex;continue}a.push(o)}return{target:a[0],action:a[1],positional:a.slice(2),format:fP(n),summary:r,source:i}}function hP(e){return e.trim().split(/\s+/).filter(Boolean)}function gP(e,t){let n=t.map(e=>`- ${e.category}`);return[`User-local storage root: ${e}`,`Categories:`,...n].join(`
300
300
  `)}async function _P(e,t){if((t.action??`list`)!==`list`)return{message:rP,success:!1};let n=await cb({activeRepositoryRoot:e});return{message:t.format===`json`?JSON.stringify(n,null,2):gP(n.root,n.categories),success:!0,data:{root:n.root,categories:n.categories,inspection:n}}}async function vP(e,t){return t.target===`storage`?_P(e,t):t.target===`memory`?dP(e,t):{message:rP,success:!1}}function yP(e){return e.includes(`ENOENT`)?`User-local memory item not found.`:e}async function bP(e){try{return await vP(e.cwd,mP(e.argv,{format:e.format,summary:e.summary,source:e.source}))}catch(e){return{message:yP(e instanceof Error?e.message:String(e)),success:!1}}}async function xP(e,t){try{return await vP(e.getCwd(),mP(hP(t)))}catch(e){return{message:yP(e instanceof Error?e.message:String(e)),success:!1}}}function SP(){return{name:`user-local`,displayName:`User Config`,description:`Inspect Robota user-local storage and memory state.`,source:`user-local`,argumentHint:`storage list [--format json] | memory set/list/inspect/disable/delete`,modelInvocable:!1,safety:`read-only`,subcommands:[{name:`storage`,description:`Inspect user-local storage categories`,source:`user-local`},{name:`memory`,description:`Inspect and manage user-local memory items`,source:`user-local`}]}}function CP(){let e=SP();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,safety:e.safety,subcommands:e.subcommands,execute:xP}}var wP=class{name=`user-local`;getCommands(){return[SP()]}};function TP(){return{name:`agent-command-user-local`,commandSources:[new wP],systemCommands:[CP()]}}function EP(e,t,n){let r=e;if(t!==void 0){let e=new Set(t);r=r.filter(t=>e.has(t.name))}if(n!==void 0){let e=new Set(n);r=r.filter(t=>!e.has(t.name))}return r}function DP({cwd:e,providerDefinitions:t,providerSettingsAdapter:n,enabledCommandModules:r,disabledCommandModules:i}){return EP([YN({cwd:e}),cA(),nk(),BA(),FA(),gj(),mA(),ck(),rA(),BN(),Kk(),kA(),TP(),mk(),zk(),Zk(),AN(),kM(),GM(),aN(),nP(),aj(),PN(),yM({providerDefinitions:t,settings:n})],r,i)}function OP(e){let t=x(),r=h(t,`.robota`,`plugins`),i=h(t,`.robota`,`settings.json`),a=(e,t)=>n(e,{timeout:t.timeout,stdio:t.stdio??`pipe`}),o=new Ky(i),s=new Qy({pluginsDir:r,exec:a});return{cwd:e,marketplace:s,installer:new qy({pluginsDir:r,settingsStore:o,marketplaceClient:s,exec:a}),loader:new Lg(r),settingsStore:o}}async function kP(e){let t=await e.loader.loadAll(),n=e.settingsStore.getEnabledPlugins();return t.map(e=>{let t=e.pluginDir.split(`/`),r=t.indexOf(`cache`),i=r>=0?t[r+1]??``:``,a=i?`${e.manifest.name}@${i}`:e.manifest.name;return{name:a,description:e.manifest.description,enabled:n[a]!==!1&&n[e.manifest.name]!==!1}})}async function AP(e,t){let n;try{n=e.marketplace.fetchManifest(t)}catch{return[]}let r=e.installer.getInstalledPlugins(),i=new Set(Object.values(r).map(e=>e.pluginName));return n.plugins.map(e=>({name:e.name,description:e.description,installed:i.has(e.name)}))}async function jP(e,t,r){let[i,a]=t.split(`@`);if(!i||!a)throw Error(`Plugin ID must be in format: name@marketplace`);if(r===`project`){await new qy({pluginsDir:h(e.cwd,`.robota`,`plugins`),settingsStore:e.settingsStore,marketplaceClient:e.marketplace,exec:(e,t)=>n(e,{timeout:t.timeout,stdio:t.stdio??`pipe`})}).install(i,a);return}await e.installer.install(i,a)}async function MP(e,t){let n=e.installer.getPluginsByMarketplace(t);for(let t of n)await e.installer.uninstall(`${t.pluginName}@${t.marketplace}`);e.marketplace.removeMarketplace(t)}function NP(e){return e.marketplace.listMarketplaces().map(e=>({name:e.name,type:e.source.type}))}function PP(e){let t=OP(e);return{listInstalled:()=>kP(t),listAvailablePlugins:e=>AP(t,e),install:(e,n)=>jP(t,e,n),uninstall:async e=>t.installer.uninstall(e),enable:async e=>t.installer.enable(e),disable:async e=>t.installer.disable(e),marketplaceAdd:async e=>e.includes(`/`)&&!e.includes(`:`)?t.marketplace.addMarketplace({type:`github`,repo:e}):t.marketplace.addMarketplace({type:`git`,url:e}),marketplaceRemove:e=>MP(t,e),marketplaceUpdate:async e=>t.marketplace.updateMarketplace(e),marketplaceList:async()=>NP(t),reloadPlugins:async()=>({loadedPluginCount:(await t.loader.loadAll()).length})}}const FP=`plugin`;function IP(){return process.env.HOME??x()}function LP(e){let t=new Lg(h(IP(),`.robota`,`plugins`));try{let n=t.loadPluginsSync();return n.length===0?(e.replaceSource(FP),0):(e.replaceSource(FP,new H_(n)),n.length)}catch{return e.replaceSource(FP),0}}function RP(e){if(e===void 0||e===`user`||e===`project-local`)return e;throw Error(`Invalid --settings-scope "${e}". Valid: user | project-local`)}function zP(e,t,n,r=EO()){let i=Gm(e,RP(t.settingsScope));return t.configureProvider?(j_(i,HP(t),{providerDefinitions:r}),n.writeLine(`Provider profile saved to ${i}`),!t.printMode&&t.positional.length===0):t.provider&&t.setCurrent?(M_(t.settingsScope===void 0?k_(e):i,t.provider,{knownProviders:R_(e).providers}),n.writeLine(`Current provider set to ${t.provider}`),!t.printMode&&t.positional.length===0):!1}async function BP(e,t,n,r,i=EO(),a){await SM(e,{provider:t.provider,settingsScope:RP(t.settingsScope)},n,r,i,{formatError:UP,isInteractive:a===void 0?()=>process.stdin.isTTY===!0&&process.stdout.isTTY===!0:()=>a})}async function VP(e,t,n,r,i=EO()){await xM(e,{settingsScope:RP(t.settingsScope)},n,r,i)}function HP(e){let t=e.providerType??e.configureProvider;if(!e.configureProvider||!t)throw Error(`--configure-provider requires a provider profile and --type`);return{profile:e.configureProvider,type:t,...e.model!==void 0&&{model:e.model},...e.apiKey!==void 0&&{apiKey:e.apiKey},...e.apiKeyEnv!==void 0&&{apiKeyEnv:e.apiKeyEnv},...e.baseURL!==void 0&&{baseURL:e.baseURL},setCurrent:e.setCurrent}}function UP(e=EO()){return[`No provider configuration found.`,"Run `robota --configure` in an interactive terminal, or configure a provider:",`Supported providers: ${dt(e)}`,...e.map(WP)].join(`
301
- `)}function WP(e){return` ${[`robota --configure-provider ${e.type}`,`--type ${e.type}`,...e.defaults?.baseURL===void 0?[]:[`--base-url <url>`],`--model <model>`,...e.requiresApiKey===!0?[`--api-key-env <ENV_NAME>`]:[],`--set-current`].join(` `)}`}const GP={running:{symbol:`⟳`,color:`yellow`},success:{symbol:`✓`,color:`green`},error:{symbol:`✗`,color:`red`},denied:{symbol:`⊘`,color:`yellowBright`},waiting:{symbol:`◴`,color:`yellow`},cancelled:{symbol:`⊗`,color:`yellow`},idle:{symbol:`·`,color:`gray`}};function KP(e){return e.isRunning?`running`:e.result===`error`?`error`:e.result===`denied`?`denied`:`success`}const qP=[`active`,`queued`,`running`,`sleeping`];function JP(e,t){return t===`failed`||e===`failed`?`error`:t===`permission`||e===`waiting_permission`?`waiting`:e===`completed`?`success`:e===`cancelled`?`cancelled`:qP.includes(e)?`running`:`idle`}const YP=[`active`,`queued`,`running`,`waiting_permission`,`sleeping`],XP=/\s+/g;function ZP(e){return(e?.entries??[]).filter(e=>e.kind===`background_task`&&e.visibility==="default")}function QP(e){return ZP(e).filter(e=>YP.includes(e.status)).length}function $P(e,t={}){let n=e.id===t.selectedEntryId,r={id:e.id,radio:n?`●`:`○`,title:tF(e),subtitle:nF(e),statusLabel:rF(e.status),preview:aF(e.preview??e.currentAction),color:iF(e),isSelected:n};return{...r,accessibleText:oF(r)}}function eF(e){let t=e.text.trim().replace(XP,` `);return t?t.length>160?`${t.slice(0,160)}...`:t:e.kind}function tF(e){return e.kind===`main_thread`?e.title:e.kind===`background_group`?`${e.title} group`:e.taskKind===`agent`?`${e.title} agent`:e.taskKind===`process`?e.title||`Process`:e.taskKind===`scheduled`?e.title||`Scheduled`:e.title}function nF(e){return e.kind===`main_thread`?e.subtitle:[e.taskKind,e.subtitle,e.attention===`none`?void 0:e.attention].filter(e=>typeof e==`string`&&e.length>0).join(` · `)||void 0}function rF(e){return e.replace(/_/g,` `)}function iF(e){return GP[JP(e.status,e.attention)].color}function aF(e){return e?.trim().replace(XP,` `)||void 0}function oF(e){return[e.radio,e.title,e.statusLabel,e.subtitle,e.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}function sF(e,t={}){let n=$P(e),r=GP[JP(e.status,e.attention)].symbol,i=[n.statusLabel,n.subtitle].filter(e=>typeof e==`string`&&e.length>0);return{connector:t.isLast===!1?`├`:`└`,marker:r,color:n.color,label:n.title,segments:i,preview:n.preview,accessibleText:[`${t.isLast===!1?`├`:`└`} ${r} ${n.title}`,...i,n.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}}function cF({entries:e,focusedIndex:t=null}){return e.length===0?null:V(P,{flexDirection:`column`,marginBottom:1,children:[V(P,{children:[B(F,{color:`cyan`,bold:!0,children:`Background work`}),B(F,{dimColor:!0,children:t===null?` · ↓ select · Ctrl+B all`:` · ↑↓ select · Enter open · Esc back`})]}),e.map((n,r)=>{let i=sF(n,{isLast:r===e.length-1});return V(F,{wrap:`truncate-end`,inverse:r===t,children:[`${i.connector} `,B(F,{color:i.color,children:i.marker}),` ${i.label}`,i.segments.map((e,t)=>B(F,{dimColor:!0,children:` · ${e}`},`${e}-${t}`)),i.preview?B(F,{dimColor:!0,children:` · ${i.preview}`}):null]},n.id)})]})}function lF({percentage:e}){return e>=90?B(P,{borderStyle:`single`,borderColor:`red`,paddingX:1,children:V(F,{color:`red`,bold:!0,children:[`⚠ Context at `,Math.round(e),`% — window nearly full. Run /compact to summarize the conversation.`]})}):e>=70?B(P,{paddingX:1,children:V(F,{color:`yellow`,children:[`Context at `,Math.round(e),`% — consider running /compact to free up space.`]})}):null}function uF({entry:e,page:t,loading:n,error:r}){let i=$P(e,{selectedEntryId:e.id}),a=t?.records.slice(-12)??[];return V(P,{flexDirection:`column`,marginBottom:1,children:[B(F,{color:`cyan`,bold:!0,children:`Viewing ${i.title}`}),V(F,{dimColor:!0,children:[i.statusLabel,i.subtitle?` · ${i.subtitle}`:``,i.preview?` · ${i.preview}`:``]}),n?B(F,{dimColor:!0,children:`Loading workspace detail...`}):null,r?B(F,{color:`red`,children:r}):null,!n&&!r&&a.length===0?B(F,{dimColor:!0,children:`No detail yet`}):null,!n&&!r&&a.map(e=>{let{symbol:t,color:n}=dF(e.kind);return V(F,{color:n,children:[t?`${t} `:``,eF(e)]},e.id)}),t?.nextCursor?B(F,{dimColor:!0,children:`... more detail available`}):null]})}function dF(e){return e===`error`?{symbol:GP.error.symbol,color:GP.error.color}:e===`result`?{symbol:GP.success.symbol,color:GP.success.color}:e===`group_summary`?{symbol:`▸`,color:`cyan`}:e===`process_output`?{symbol:`·`,color:`white`}:{symbol:``,color:void 0}}function fF(){return{selectedIndex:0,scrollOffset:0,resolved:!1}}function pF(e){if(e.escape===!0)return`cancel`;if(e.upArrow===!0)return`previous`;if(e.downArrow===!0)return`next`;if(e.return===!0)return`select`}function mF(e){if(e.escape===!0)return`cancel`;if(e.leftArrow===!0||e.upArrow===!0)return`previous`;if(e.rightArrow===!0||e.downArrow===!0)return`next`;if(e.return===!0)return`select`}function hF(e,t,n){if(e.resolved)return{state:e,effect:{type:`none`}};if(t===`cancel`)return{state:{...e,resolved:!0},effect:{type:`cancel`}};if(n.enabled===!1||n.itemCount===0)return{state:e,effect:{type:`none`}};if(t===`select`){let t=yF(e.selectedIndex,n.itemCount);return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`select`,index:t}}}let r=_F(e.selectedIndex,t,n),i=vF(r,e.scrollOffset,n);return{state:{...e,selectedIndex:r,scrollOffset:i},effect:{type:`none`}}}function gF(e,t){if(t.itemCount===0)return{...e,selectedIndex:0,scrollOffset:0};let n=yF(e.selectedIndex,t.itemCount),r=vF(n,e.scrollOffset,t);return n===e.selectedIndex&&r===e.scrollOffset?e:{...e,selectedIndex:n,scrollOffset:r}}function _F(e,t,n){return t===`previous`?n.wrap===!0&&e===0?n.itemCount-1:Math.max(0,e-1):n.wrap===!0&&e===n.itemCount-1?0:Math.min(n.itemCount-1,e+1)}function vF(e,t,n){let r=n.maxVisible??n.itemCount;return r<=0?0:e<t?e:e>=t+r?e-r+1:Math.max(0,t)}function yF(e,t){return Math.min(Math.max(e,0),t-1)}function bF({snapshot:e,selectedEntryId:t,onSelect:n,onClose:r}){let{normalized:i,visibleEntries:a,applyAction:o}=xF({entries:[...e?.entries??[]],selectedEntryId:t,onSelect:n,onClose:r});return I((e,t)=>{let n=pF(t);n!==void 0&&o(n)}),V(P,{flexDirection:`column`,borderStyle:`round`,borderColor:`cyan`,paddingX:1,children:[B(F,{color:`cyan`,bold:!0,children:`Execution workspace`}),B(P,{flexDirection:`column`,marginTop:1,children:a.length===0?B(F,{dimColor:!0,children:`No workspace entries`}):a.map((e,n)=>B(wF,{entry:e,isFocused:i.scrollOffset+n===i.selectedIndex,selectedEntryId:t},e.id))}),B(F,{dimColor:!0,children:`Ctrl+B Close ↑↓ Navigate Enter Switch Esc Close`})]})}function xF({entries:e,selectedEntryId:t,onSelect:n,onClose:r}){let[i,a]=z(()=>fF()),o=qe(i);R(()=>{let n=CF({selectedIndex:Math.max(0,e.findIndex(e=>e.id===t)),itemCount:e.length});o.current=n,a(n)},[e.length,t]);let s=CF({selectedIndex:i.selectedIndex,scrollOffset:i.scrollOffset,itemCount:e.length});return s!==i&&(o.current=s),{normalized:s,visibleEntries:e.slice(s.scrollOffset,s.scrollOffset+8),applyAction:SF({entries:e,stateRef:o,setState:a,onSelect:n,onClose:r})}}function SF({entries:e,stateRef:t,setState:n,onSelect:r,onClose:i}){return a=>{let o=hF(t.current,a,{itemCount:e.length,maxVisible:8}),s=o.effect.type===`select`||o.effect.type===`cancel`?{...o.state,resolved:!1}:o.state;if(t.current=s,n(s),o.effect.type===`cancel`)i();else if(o.effect.type===`select`){let t=e[o.effect.index];t&&r(t.id)}}}function CF(e){return gF({selectedIndex:e.selectedIndex,scrollOffset:e.scrollOffset??0,resolved:!1},{itemCount:e.itemCount,maxVisible:8})}function wF({entry:e,isFocused:t,selectedEntryId:n}){let r=$P(e,{selectedEntryId:n});return V(F,{children:[B(F,{color:t?`cyan`:void 0,bold:t,children:t?`> `:` `}),B(F,{color:r.color,children:r.radio}),B(F,{color:t?`cyan`:void 0,bold:t,children:` ${r.title}`}),B(F,{dimColor:!0,children:` · ${r.statusLabel}`}),r.subtitle?B(F,{dimColor:!0,children:` · ${r.subtitle}`}):null,r.preview?B(F,{dimColor:!0,children:` · ${r.preview}`}):null]})}function TF(e,t,n){return t<=0?{type:`exit`}:n.upArrow?{type:`move`,index:e>0?e-1:null}:n.downArrow?{type:`move`,index:e<t-1?e+1:e}:n.return?{type:`open`,index:Math.min(Math.max(e,0),t-1)}:n.escape?{type:`exit`}:{type:`none`}}function EF(){return{listInstalled:async()=>[],listAvailablePlugins:async()=>[],install:async()=>void 0,uninstall:async()=>void 0,enable:async()=>void 0,disable:async()=>void 0,marketplaceAdd:async()=>``,marketplaceRemove:async()=>void 0,marketplaceUpdate:async()=>void 0,marketplaceList:async()=>[],reloadPlugins:async()=>({loadedPluginCount:0})}}function DF(e){return Ke(()=>EF(),[])}function OF(e,t){for(let n of e){if(n.type===`language-change-requested`)return kF(n.language,t),!0;if(n.type===`settings-reset-requested`)return AF(t),!0;if(n.type===`session-exit-requested`)return t.requestShutdown(n.reason??`prompt_input_exit`,n.message??`User requested exit`),!0;if(n.type===`session-restart-requested`)return t.requestShutdown(n.reason,n.message),!0;if(n.type===`plugin-tui-requested`)return t.openPluginTUI(),!0;if(n.type===`settings-tui-requested`)return t.openTransportTUI(),!0;if(n.type===`agent-switcher-requested`)return t.openAgentSwitcher(),!0;if(n.type===`session-picker-requested`)return t.openSessionPicker(),!0;if(n.type===`session-renamed`)return t.renameSession(n.name),!0;if(n.type===`statusline-settings-patch`&&Lv(n.patch))return t.applyStatusLinePatch(n.patch)}return!1}function kF(e,t){let n=t.cliAdapter.getUserSettingsPath(),r=t.cliAdapter.readSettings(n);r.language=e,t.cliAdapter.writeSettings(n,r),t.addEntry(H(q(`Language set to "${e}". Restarting...`))),t.requestShutdown(`other`,`Language change restart`)}function AF(e){let t=e.cliAdapter.getUserSettingsPath();e.cliAdapter.deleteSettings(t)?e.addEntry(H(q(`Deleted ${t}. Exiting...`))):e.addEntry(H(q(`No user settings found.`))),e.requestShutdown(`other`,`Reset settings restart`)}const jF=We(null),MF=jF.Provider;function NF(){let e=Ge(jF);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function PF({cwd:e,providerOverride:t,interactiveSession:n,commandEffectQueue:r,addEntry:i,baseHandleSubmit:a,setSessionName:o,setStatusLineSettings:s,showSessionPickerOnStart:c,openAgentSwitcher:l}){let{exit:u}=ze(),d=NF(),[f,p]=z(!1),[m,h]=z(c??!1),[g,_]=z(!1),v=L((e,t)=>{i(H(q(`Shutting down...`))),setTimeout(()=>{n.shutdown({reason:e,message:t}).finally(()=>u())},500)},[n,i,u]),y=L(e=>OF(e,{addEntry:i,requestShutdown:v,openPluginTUI:()=>p(!0),openSessionPicker:()=>h(!0),openTransportTUI:()=>_(!0),openAgentSwitcher:()=>l?.(),renameSession:e=>{n.setName(e),o(e)},applyStatusLinePatch:e=>(s(d.applyStatusLineSettings(d.getUserSettingsPath(),e)),!0),cliAdapter:d}),[i,d,n,v,o,s]),b=L(()=>{let e=r.drain();return e===void 0?!1:y(e.effects)},[y,r]);return{handleSubmit:L(async e=>{await a(e),b()},[a,b]),showPluginTUI:f,showSessionPicker:m,showTransportTUI:g,setShowPluginTUI:p,setShowSessionPicker:h,setShowTransportTUI:_}}function FF(e){let t={...Fv},n=e.statusline;return IF(n)?{enabled:typeof n.enabled==`boolean`?n.enabled:t.enabled,gitBranch:typeof n.gitBranch==`boolean`?n.gitBranch:t.gitBranch}:t}function IF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function LF(){let e=NF();return z(()=>FF(e.readSettings(e.getUserSettingsPath())))}function RF(e){let[t,n]=z(!1);return R(()=>{if(e)return e.registerSuspendHooks({suspend:async()=>{n(!0),await new Promise(e=>setTimeout(e,50))},resume:()=>n(!1)})},[e]),t}function zF(e){let[,t]=z(0);R(()=>(e.onChange=()=>t(e=>e+1),()=>{e.onChange=null}),[e]);let n=e.stateManager,r=L(t=>e.selectExecutionWorkspaceEntry(t),[e]),i=L(t=>e.readExecutionWorkspaceDetail(t),[e]);return{interactiveSession:e.getSession(),registry:e.getRegistry(),commandEffectQueue:e.getCommandEffectQueue(),history:n.history,addEntry:e=>n.addEntry(e),streamingText:n.streamingText,activeTools:n.activeTools,isThinking:n.isThinking,isAborting:n.isAborting,lastErrorMessage:n.lastErrorMessage,isStalled:n.isStalled,isShuttingDown:e.isShuttingDown,pendingPrompt:n.pendingPrompt,executionWorkspaceSnapshot:n.executionWorkspaceSnapshot,selectedExecutionEntryId:n.selectedExecutionEntryId,permissionRequest:e.permissionRequest,pendingUserAction:e.pendingUserAction??null,contextState:n.contextState,handleSubmit:t=>e.handleInput(t),handleAbort:()=>e.abort(),handleCancelQueue:()=>e.cancelQueue(),handleShutdown:t=>e.shutdown({reason:t}),selectExecutionWorkspaceEntry:r,readExecutionWorkspaceDetail:i}}const BF=`[200~`,VF=`[201~`;function HF(e){return{value:e,cursor:e.length,isPasting:!1,pasteBuffer:``}}function UF(e,t,n){return t===e.value?e:{...e,value:t,cursor:n==null?t.length:Math.min(n,t.length)}}function WF(e,t,n,r){let i=KF(e,t,r);if(i!==void 0)return i;let a=qF(e,t,n,r);if(a!==void 0)return a;let o=JF(e,n,r);return o===void 0?iI(e,t):o}function GF(e,t,n){let r=t.replace(/\r\n?/g,`
301
+ `)}function WP(e){return` ${[`robota --configure-provider ${e.type}`,`--type ${e.type}`,...e.defaults?.baseURL===void 0?[]:[`--base-url <url>`],`--model <model>`,...e.requiresApiKey===!0?[`--api-key-env <ENV_NAME>`]:[],`--set-current`].join(` `)}`}const GP={running:{symbol:`⟳`,color:`yellow`},success:{symbol:`✓`,color:`green`},error:{symbol:`✗`,color:`red`},denied:{symbol:`⊘`,color:`yellowBright`},waiting:{symbol:`◴`,color:`yellow`},cancelled:{symbol:`⊗`,color:`yellow`},idle:{symbol:`·`,color:`gray`}};function KP(e){return e.isRunning?`running`:e.result===`error`?`error`:e.result===`denied`?`denied`:`success`}const qP=[`active`,`queued`,`running`,`sleeping`];function JP(e,t){return t===`failed`||e===`failed`?`error`:t===`permission`||e===`waiting_permission`?`waiting`:e===`completed`?`success`:e===`cancelled`?`cancelled`:qP.includes(e)?`running`:`idle`}const YP=[`active`,`queued`,`running`,`waiting_permission`,`sleeping`],XP=/\s+/g;function ZP(e){return(e?.entries??[]).filter(e=>e.kind===`background_task`&&e.visibility==="default")}function QP(e){return ZP(e).filter(e=>YP.includes(e.status)).length}function $P(e,t={}){let n=e.id===t.selectedEntryId,r={id:e.id,radio:n?`●`:`○`,title:tF(e),subtitle:nF(e),statusLabel:rF(e.status),preview:aF(e.preview??e.currentAction),color:iF(e),isSelected:n};return{...r,accessibleText:oF(r)}}function eF(e){let t=e.text.trim().replace(XP,` `);return t?t.length>160?`${t.slice(0,160)}...`:t:e.kind}function tF(e){return e.kind===`main_thread`?e.title:e.kind===`background_group`?`${e.title} group`:e.taskKind===`agent`?`${e.title} agent`:e.taskKind===`process`?e.title||`Process`:e.taskKind===`scheduled`?e.title||`Scheduled`:e.title}function nF(e){return e.kind===`main_thread`?e.subtitle:[e.taskKind,e.subtitle,e.attention===`none`?void 0:e.attention].filter(e=>typeof e==`string`&&e.length>0).join(` · `)||void 0}function rF(e){return e.replace(/_/g,` `)}function iF(e){return GP[JP(e.status,e.attention)].color}function aF(e){return e?.trim().replace(XP,` `)||void 0}function oF(e){return[e.radio,e.title,e.statusLabel,e.subtitle,e.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}function sF(e,t={}){let n=$P(e),r=GP[JP(e.status,e.attention)].symbol,i=[n.statusLabel,n.subtitle].filter(e=>typeof e==`string`&&e.length>0);return{connector:t.isLast===!1?`├`:`└`,marker:r,color:n.color,label:n.title,segments:i,preview:n.preview,accessibleText:[`${t.isLast===!1?`├`:`└`} ${r} ${n.title}`,...i,n.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}}function cF({entries:e,focusedIndex:t=null}){return e.length===0?null:V(F,{flexDirection:`column`,marginBottom:1,children:[V(F,{children:[B(I,{color:`cyan`,bold:!0,children:`Background work`}),B(I,{dimColor:!0,children:t===null?` · ↓ select · Ctrl+B all`:` · ↑↓ select · Enter open · Esc back`})]}),e.map((n,r)=>{let i=sF(n,{isLast:r===e.length-1});return V(I,{wrap:`truncate-end`,inverse:r===t,children:[`${i.connector} `,B(I,{color:i.color,children:i.marker}),` ${i.label}`,i.segments.map((e,t)=>B(I,{dimColor:!0,children:` · ${e}`},`${e}-${t}`)),i.preview?B(I,{dimColor:!0,children:` · ${i.preview}`}):null]},n.id)})]})}function lF({percentage:e}){return e>=90?B(F,{borderStyle:`single`,borderColor:`red`,paddingX:1,children:V(I,{color:`red`,bold:!0,children:[`⚠ Context at `,Math.round(e),`% — window nearly full. Run /compact to summarize the conversation.`]})}):e>=70?B(F,{paddingX:1,children:V(I,{color:`yellow`,children:[`Context at `,Math.round(e),`% — consider running /compact to free up space.`]})}):null}function uF({entry:e,page:t,loading:n,error:r}){let i=$P(e,{selectedEntryId:e.id}),a=t?.records.slice(-12)??[];return V(F,{flexDirection:`column`,marginBottom:1,children:[B(I,{color:`cyan`,bold:!0,children:`Viewing ${i.title}`}),V(I,{dimColor:!0,children:[i.statusLabel,i.subtitle?` · ${i.subtitle}`:``,i.preview?` · ${i.preview}`:``]}),n?B(I,{dimColor:!0,children:`Loading workspace detail...`}):null,r?B(I,{color:`red`,children:r}):null,!n&&!r&&a.length===0?B(I,{dimColor:!0,children:`No detail yet`}):null,!n&&!r&&a.map(e=>{let{symbol:t,color:n}=dF(e.kind);return V(I,{color:n,children:[t?`${t} `:``,eF(e)]},e.id)}),t?.nextCursor?B(I,{dimColor:!0,children:`... more detail available`}):null]})}function dF(e){return e===`error`?{symbol:GP.error.symbol,color:GP.error.color}:e===`result`?{symbol:GP.success.symbol,color:GP.success.color}:e===`group_summary`?{symbol:`▸`,color:`cyan`}:e===`process_output`?{symbol:`·`,color:`white`}:{symbol:``,color:void 0}}function fF(){return{selectedIndex:0,scrollOffset:0,resolved:!1}}function pF(e){if(e.escape===!0)return`cancel`;if(e.upArrow===!0)return`previous`;if(e.downArrow===!0)return`next`;if(e.return===!0)return`select`}function mF(e){if(e.escape===!0)return`cancel`;if(e.leftArrow===!0||e.upArrow===!0)return`previous`;if(e.rightArrow===!0||e.downArrow===!0)return`next`;if(e.return===!0)return`select`}function hF(e,t,n){if(e.resolved)return{state:e,effect:{type:`none`}};if(t===`cancel`)return{state:{...e,resolved:!0},effect:{type:`cancel`}};if(n.enabled===!1||n.itemCount===0)return{state:e,effect:{type:`none`}};if(t===`select`){let t=yF(e.selectedIndex,n.itemCount);return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`select`,index:t}}}let r=_F(e.selectedIndex,t,n),i=vF(r,e.scrollOffset,n);return{state:{...e,selectedIndex:r,scrollOffset:i},effect:{type:`none`}}}function gF(e,t){if(t.itemCount===0)return{...e,selectedIndex:0,scrollOffset:0};let n=yF(e.selectedIndex,t.itemCount),r=vF(n,e.scrollOffset,t);return n===e.selectedIndex&&r===e.scrollOffset?e:{...e,selectedIndex:n,scrollOffset:r}}function _F(e,t,n){return t===`previous`?n.wrap===!0&&e===0?n.itemCount-1:Math.max(0,e-1):n.wrap===!0&&e===n.itemCount-1?0:Math.min(n.itemCount-1,e+1)}function vF(e,t,n){let r=n.maxVisible??n.itemCount;return r<=0?0:e<t?e:e>=t+r?e-r+1:Math.max(0,t)}function yF(e,t){return Math.min(Math.max(e,0),t-1)}function bF({snapshot:e,selectedEntryId:t,onSelect:n,onClose:r}){let{normalized:i,visibleEntries:a,applyAction:o}=xF({entries:[...e?.entries??[]],selectedEntryId:t,onSelect:n,onClose:r});return L((e,t)=>{let n=pF(t);n!==void 0&&o(n)}),V(F,{flexDirection:`column`,borderStyle:`round`,borderColor:`cyan`,paddingX:1,children:[B(I,{color:`cyan`,bold:!0,children:`Execution workspace`}),B(F,{flexDirection:`column`,marginTop:1,children:a.length===0?B(I,{dimColor:!0,children:`No workspace entries`}):a.map((e,n)=>B(wF,{entry:e,isFocused:i.scrollOffset+n===i.selectedIndex,selectedEntryId:t},e.id))}),B(I,{dimColor:!0,children:`Ctrl+B Close ↑↓ Navigate Enter Switch Esc Close`})]})}function xF({entries:e,selectedEntryId:t,onSelect:n,onClose:r}){let[i,a]=z(()=>fF()),o=qe(i);Ge(()=>{let n=CF({selectedIndex:Math.max(0,e.findIndex(e=>e.id===t)),itemCount:e.length});o.current=n,a(n)},[e.length,t]);let s=CF({selectedIndex:i.selectedIndex,scrollOffset:i.scrollOffset,itemCount:e.length});return s!==i&&(o.current=s),{normalized:s,visibleEntries:e.slice(s.scrollOffset,s.scrollOffset+8),applyAction:SF({entries:e,stateRef:o,setState:a,onSelect:n,onClose:r})}}function SF({entries:e,stateRef:t,setState:n,onSelect:r,onClose:i}){return a=>{let o=hF(t.current,a,{itemCount:e.length,maxVisible:8}),s=o.effect.type===`select`||o.effect.type===`cancel`?{...o.state,resolved:!1}:o.state;if(t.current=s,n(s),o.effect.type===`cancel`)i();else if(o.effect.type===`select`){let t=e[o.effect.index];t&&r(t.id)}}}function CF(e){return gF({selectedIndex:e.selectedIndex,scrollOffset:e.scrollOffset??0,resolved:!1},{itemCount:e.itemCount,maxVisible:8})}function wF({entry:e,isFocused:t,selectedEntryId:n}){let r=$P(e,{selectedEntryId:n});return V(I,{children:[B(I,{color:t?`cyan`:void 0,bold:t,children:t?`> `:` `}),B(I,{color:r.color,children:r.radio}),B(I,{color:t?`cyan`:void 0,bold:t,children:` ${r.title}`}),B(I,{dimColor:!0,children:` · ${r.statusLabel}`}),r.subtitle?B(I,{dimColor:!0,children:` · ${r.subtitle}`}):null,r.preview?B(I,{dimColor:!0,children:` · ${r.preview}`}):null]})}function TF(e,t,n){return t<=0?{type:`exit`}:n.upArrow?{type:`move`,index:e>0?e-1:null}:n.downArrow?{type:`move`,index:e<t-1?e+1:e}:n.return?{type:`open`,index:Math.min(Math.max(e,0),t-1)}:n.escape?{type:`exit`}:{type:`none`}}function EF(){return{listInstalled:async()=>[],listAvailablePlugins:async()=>[],install:async()=>void 0,uninstall:async()=>void 0,enable:async()=>void 0,disable:async()=>void 0,marketplaceAdd:async()=>``,marketplaceRemove:async()=>void 0,marketplaceUpdate:async()=>void 0,marketplaceList:async()=>[],reloadPlugins:async()=>({loadedPluginCount:0})}}function DF(e){return Ke(()=>EF(),[])}function OF(e,t){for(let n of e){if(n.type===`language-change-requested`)return kF(n.language,t),!0;if(n.type===`settings-reset-requested`)return AF(t),!0;if(n.type===`session-exit-requested`)return t.requestShutdown(n.reason??`prompt_input_exit`,n.message??`User requested exit`),!0;if(n.type===`session-restart-requested`)return t.requestShutdown(n.reason,n.message),!0;if(n.type===`plugin-tui-requested`)return t.openPluginTUI(),!0;if(n.type===`settings-tui-requested`)return t.openTransportTUI(),!0;if(n.type===`agent-switcher-requested`)return t.openAgentSwitcher(),!0;if(n.type===`session-picker-requested`)return t.openSessionPicker(),!0;if(n.type===`session-renamed`)return t.renameSession(n.name),!0;if(n.type===`statusline-settings-patch`&&Lv(n.patch))return t.applyStatusLinePatch(n.patch)}return!1}function kF(e,t){let n=t.cliAdapter.getUserSettingsPath(),r=t.cliAdapter.readSettings(n);r.language=e,t.cliAdapter.writeSettings(n,r),t.addEntry(H(q(`Language set to "${e}". Restarting...`))),t.requestShutdown(`other`,`Language change restart`)}function AF(e){let t=e.cliAdapter.getUserSettingsPath();e.cliAdapter.deleteSettings(t)?e.addEntry(H(q(`Deleted ${t}. Exiting...`))):e.addEntry(H(q(`No user settings found.`))),e.requestShutdown(`other`,`Reset settings restart`)}const jF=Ue(null),MF=jF.Provider;function NF(){let e=We(jF);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function PF({cwd:e,providerOverride:t,interactiveSession:n,commandEffectQueue:r,addEntry:i,baseHandleSubmit:a,setSessionName:o,setStatusLineSettings:s,showSessionPickerOnStart:c,openAgentSwitcher:l}){let{exit:u}=Re(),d=NF(),[f,p]=z(!1),[m,h]=z(c??!1),[g,_]=z(!1),v=R((e,t)=>{i(H(q(`Shutting down...`))),setTimeout(()=>{n.shutdown({reason:e,message:t}).finally(()=>u())},500)},[n,i,u]),y=R(e=>OF(e,{addEntry:i,requestShutdown:v,openPluginTUI:()=>p(!0),openSessionPicker:()=>h(!0),openTransportTUI:()=>_(!0),openAgentSwitcher:()=>l?.(),renameSession:e=>{n.setName(e),o(e)},applyStatusLinePatch:e=>(s(d.applyStatusLineSettings(d.getUserSettingsPath(),e)),!0),cliAdapter:d}),[i,d,n,v,o,s]),b=R(()=>{let e=r.drain();return e===void 0?!1:y(e.effects)},[y,r]);return{handleSubmit:R(async e=>{await a(e),b()},[a,b]),showPluginTUI:f,showSessionPicker:m,showTransportTUI:g,setShowPluginTUI:p,setShowSessionPicker:h,setShowTransportTUI:_}}function FF(e){let t={...Fv},n=e.statusline;return IF(n)?{enabled:typeof n.enabled==`boolean`?n.enabled:t.enabled,gitBranch:typeof n.gitBranch==`boolean`?n.gitBranch:t.gitBranch}:t}function IF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function LF(){let e=NF();return z(()=>FF(e.readSettings(e.getUserSettingsPath())))}function RF(e){let[t,n]=z(!1);return Ge(()=>{if(e)return e.registerSuspendHooks({suspend:async()=>{n(!0),await new Promise(e=>setTimeout(e,50))},resume:()=>n(!1)})},[e]),t}function zF(e){let[,t]=z(0);Ge(()=>(e.onChange=()=>t(e=>e+1),()=>{e.onChange=null}),[e]);let n=e.stateManager,r=R(t=>e.selectExecutionWorkspaceEntry(t),[e]),i=R(t=>e.readExecutionWorkspaceDetail(t),[e]);return{interactiveSession:e.getSession(),registry:e.getRegistry(),commandEffectQueue:e.getCommandEffectQueue(),history:n.history,addEntry:e=>n.addEntry(e),streamingText:n.streamingText,activeTools:n.activeTools,isThinking:n.isThinking,isAborting:n.isAborting,lastErrorMessage:n.lastErrorMessage,isStalled:n.isStalled,isShuttingDown:e.isShuttingDown,pendingPrompt:n.pendingPrompt,executionWorkspaceSnapshot:n.executionWorkspaceSnapshot,selectedExecutionEntryId:n.selectedExecutionEntryId,permissionRequest:e.permissionRequest,pendingUserAction:e.pendingUserAction??null,contextState:n.contextState,handleSubmit:t=>e.handleInput(t),handleAbort:()=>e.abort(),handleCancelQueue:()=>e.cancelQueue(),handleShutdown:t=>e.shutdown({reason:t}),selectExecutionWorkspaceEntry:r,readExecutionWorkspaceDetail:i}}const BF=`[200~`,VF=`[201~`;function HF(e){return{value:e,cursor:e.length,isPasting:!1,pasteBuffer:``}}function UF(e,t,n){return t===e.value?e:{...e,value:t,cursor:n==null?t.length:Math.min(n,t.length)}}function WF(e,t,n,r){let i=KF(e,t,r);if(i!==void 0)return i;let a=qF(e,t,n,r);if(a!==void 0)return a;let o=JF(e,n,r);return o===void 0?iI(e,t):o}function GF(e,t,n){let r=t.replace(/\r\n?/g,`
302
302
  `);return r.length===0?{state:e,effect:{type:`none`}}:r.includes(`
303
303
  `)&&n.canPaste?{state:e,effect:{type:`paste`,text:r,cursor:e.cursor}}:iI(e,r)}function KF(e,t,n){if(t===BF||t.startsWith(BF))return $F(e,t);if(e.isPasting)return eI(e,t,n)}function qF(e,t,n,r){if(n.ctrl===!0&&t===`c`||n.tab===!0)return{state:e,effect:{type:`none`}};if(n.return===!0)return{state:e,effect:{type:`submit`,value:e.value}};if(t.length>1&&(t.includes(`
304
304
  `)||t.includes(`\r`))&&r.canPaste)return{state:e,effect:{type:`paste`,text:t.replace(/\r\n?/g,`
305
- `),cursor:e.cursor}}}function JF(e,t,n){if(t.upArrow===!0||t.downArrow===!0)return n.enableVerticalNavigation===!1?{state:e,effect:{type:`none`}}:tI(e,t.upArrow===!0?`up`:`down`,n.availableWidth);if(t.leftArrow===!0)return nI(e,`left`);if(t.rightArrow===!0)return nI(e,`right`);if(t.backspace===!0||t.delete===!0)return rI(e)}function YF(e){if(!e||e.length===0)return``;let t=``;for(let n of e){let e=n.charCodeAt(0);e>31&&e!==127&&(t+=n)}return t}function XF(e,t,n){return{value:e.slice(0,t)+n+e.slice(t),cursor:t+n.length}}function ZF(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++){let t=Xe(e[i]),a=r%n;a+t>n&&(r+=n-a),r+=t}return r}function QF(e,t,n){let r=0;for(let i=0;i<e.length;i++){if(r>=t)return i;let a=Xe(e[i]),o=r%n;o+a>n&&(r+=n-o),r+=a}return e.length}function $F(e,t){return{state:{...e,isPasting:!0,pasteBuffer:t.slice(5)},effect:{type:`none`}}}function eI(e,t,n){if(t!==VF&&!t.includes(VF))return{state:{...e,pasteBuffer:e.pasteBuffer+t},effect:{type:`none`}};let r=t.split(VF)[0]??``;return GF({...e,isPasting:!1,pasteBuffer:``},e.pasteBuffer+r,n)}function tI(e,t,n){if(!n||n<=0)return{state:e,effect:{type:`none`}};let r=[...e.value],i=ZF(r,e.cursor,n),a=t===`up`?i-n:i+n;if(a<0)return{state:e,effect:{type:`none`}};let o=QF(r,a,n);return o===e.cursor?{state:e,effect:{type:`none`}}:{state:{...e,cursor:o},effect:{type:`render`}}}function nI(e,t){return t===`left`&&e.cursor>0?{state:{...e,cursor:e.cursor-1},effect:{type:`render`}}:t===`right`&&e.cursor<e.value.length?{state:{...e,cursor:e.cursor+1},effect:{type:`render`}}:{state:e,effect:{type:`none`}}}function rI(e){if(e.cursor===0)return{state:e,effect:{type:`none`}};let t=e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor);return{state:{...e,value:t,cursor:e.cursor-1},effect:{type:`change`,value:t}}}function iI(e,t){let n=YF(t);if(n.length===0)return{state:e,effect:{type:`none`}};let r=XF(e.value,e.cursor,n);return{state:{...e,value:r.value,cursor:r.cursor},effect:{type:`change`,value:r.value}}}function aI({value:e,onChange:t,onSubmit:n,onPaste:r,placeholder:i=``,focus:a=!0,showCursor:o=!0,availableWidth:s,cursorHint:c=null,enableVerticalNavigation:l=!0}){let u=qe(HF(e)),[,d]=z(0);return u.current=UF(u.current,e,c),oI({stateRef:u,onChange:t,onSubmit:n,onPaste:r,availableWidth:s,focus:a,enableVerticalNavigation:l,forceRender:d}),B(F,{children:uI(u.current.value,u.current.cursor,i,o&&a)})}function oI(e){Be(t=>{cI(e,()=>GF(e.stateRef.current,t,sI(e)))},{isActive:e.focus}),I((t,n)=>{cI(e,()=>WF(e.stateRef.current,t,n,sI(e)))},{isActive:e.focus})}function sI(e){return{availableWidth:e.availableWidth,canPaste:e.onPaste!==void 0,enableVerticalNavigation:e.enableVerticalNavigation}}function cI(e,t){try{let n=t();e.stateRef.current=n.state,lI(n.effect,e.onChange,e.onSubmit,e.onPaste,e.forceRender)}catch{}}function lI(e,t,n,r,i){e.type===`change`?t(e.value):e.type===`submit`?n?.(e.value):e.type===`paste`?r?.(e.text,e.cursor):e.type===`render`&&i(e=>e+1)}function uI(e,t,n,r){if(!r)return e.length>0?e:n?Ye.gray(n):``;if(e.length===0)return n.length>0?Ye.inverse(n[0])+Ye.gray(n.slice(1)):Ye.inverse(` `);let i=[...e],a=``;for(let e=0;e<i.length;e++){let n=i[e]??``;a+=e===t?Ye.inverse(n):n}return t>=i.length&&(a+=Ye.inverse(` `)),a}function dI(e){if(e.upArrow===!0)return`previous`;if(e.downArrow===!0)return`next`;if(e.escape===!0)return`close`;if(e.tab===!0)return`complete`}function fI(e){if(e.backspace===!0||e.delete===!0)return`cancelQueue`}function pI(e){if(e.upArrow===!0)return`previous`;if(e.downArrow===!0)return`next`}function mI(){return{selectedIndex:null,draft:``}}function hI(e,t,n,r){if(t.length===0)return{value:e,cursorHint:e.length,state:n};if(r===`previous`){let r=n.selectedIndex===null?t.length-1:Math.max(0,n.selectedIndex-1),i=t[r]??e;return{value:i,cursorHint:i.length,state:{selectedIndex:r,draft:n.selectedIndex===null?e:n.draft}}}if(n.selectedIndex===null)return{value:e,cursorHint:e.length,state:n};if(n.selectedIndex<t.length-1){let r=n.selectedIndex+1,i=t[r]??e;return{value:i,cursorHint:i.length,state:{...n,selectedIndex:r}}}return{value:n.draft,cursorHint:n.draft.length,state:mI()}}function gI(e,t){let n=t.trim();return n.length===0||e[e.length-1]===n?[...e]:[...e,n]}function _I(e){let t=[];for(let n of e){if(n.category!==`chat`||n.type!==`user`)continue;let e=n.data;typeof e?.content==`string`&&(t=gI(t,e.content))}return t}function vI(e,t,n){return t===0?0:n===`previous`?e>0?e-1:t-1:e<t-1?e+1:0}function yI(e,t){if(Mb(e)&&e.slice(1).includes(` `)){let{name:n}=Nb(e);return{type:`insert`,value:`/${n} ${t.name} `}}return t.subcommands&&t.subcommands.length>0?{type:`insert`,value:`/${t.name} `,selectedIndex:0}:{type:`insert`,value:`/${t.name} `}}function bI(e,t){if(Mb(e)&&e.slice(1).includes(` `)){let{name:n}=Nb(e);return{type:`submit`,value:`/${n} ${t.name}`}}return t.subcommands&&t.subcommands.length>0?{type:`insert`,value:`/${t.name} `,selectedIndex:0}:{type:`submit`,value:`/${t.name}`}}function xI(e,t,n,r){let i=r.split(`
306
- `).length,a=`[Pasted text #${n} +${i} lines]`;return{value:e.slice(0,t)+a+e.slice(t),cursorHint:t+a.length,label:a,lineCount:i}}function SI(e){return e.trim().length>0}function CI(e){if(!e.startsWith(`/`))return{isSlash:!1,parentCommand:``,filter:``};let t=e.slice(1),n=t.indexOf(` `);return n===-1?{isSlash:!0,parentCommand:``,filter:t}:{isSlash:!0,parentCommand:t.slice(0,n),filter:t.slice(n+1)}}function wI(e,t){let[n,r]=z(0),[i,a]=z(!1),o=Ue.useRef(e);o.current!==e&&(o.current=e,i&&a(!1));let s=CI(e),c=s.isSlash&&s.parentCommand.length>0,l=Ke(()=>{if(!t||!s.isSlash||i)return[];if(c){let e=t.getSubcommands(s.parentCommand);if(e.length===0)return[];if(!s.filter)return e;let n=s.filter.toLowerCase();return e.filter(e=>e.name.toLowerCase().startsWith(n))}return t.getCommands(s.filter)},[t,s.isSlash,s.parentCommand,s.filter,i,c]),u=s.isSlash&&l.length>0&&!i;return n>=l.length&&l.length>0&&r(l.length-1),{showPopup:u,filteredCommands:l,selectedIndex:n,setSelectedIndex:r,isSubcommandMode:c,setShowPopup:e=>{a(typeof e==`function`?t=>!e(!t):!e)}}}function TI(){let{stdout:e}=Ve(),t=()=>Math.max(40,(e.columns??80)-4),[n,r]=z(t);return R(()=>{let n=()=>r(t());return e.on(`resize`,n),()=>{e.off(`resize`,n)}},[e]),n}function EI(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e.padEnd(t)}function DI(e){let{cmd:t,isSelected:n,showSlash:r,rowWidth:i,nameColWidth:a}=e,o=n?`> `:` `,s=n?`cyan`:void 0,c=!n,l=EI(t.name,a);return B(P,{width:i,children:B(F,{color:s,dimColor:c,wrap:`truncate-end`,children:r?`${o}/${l} ${t.description??``}`:`${o}${l} ${t.description??``}`})})}function OI({commands:e,selectedIndex:t,visible:n,isSubcommandMode:r}){let i=TI();if(!n||e.length===0)return null;let a=kI(t,e.length),o=e.slice(a,a+8),s=Math.min(20,Math.max(...o.map(e=>e.name.length)));return V(P,{flexDirection:`column`,borderStyle:`round`,borderColor:`gray`,paddingX:1,children:[o.map((e,n)=>B(DI,{cmd:e,isSelected:a+n===t,showSlash:!r,rowWidth:i,nameColWidth:s},e.name)),B(F,{dimColor:!0,children:` ↑↓ Navigate Tab Complete Enter Select Esc Close`})]})}function kI(e,t){if(t<=8||e<8)return 0;let n=t-8;return Math.min(e-8+1,n)}const AI=/\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;function jI(e,t){return e.replace(AI,(e,n)=>t.get(Number(n))??``)}function MI(){if(`NO_COLOR`in process.env)return!1;let e=process.env.FORCE_COLOR;return e===`0`?!1:e!==void 0&&e!==``?!0:!!process.stdout.isTTY}const NI=[`#666666`,`#888888`,`#aaaaaa`,`#888888`];function PI({text:e}){let t=MI(),[n,r]=z(0);return R(()=>{if(!t)return;let e=setInterval(()=>{r(e=>e+1)},400);return()=>clearInterval(e)},[t]),t?B(F,{children:[...e].map((e,t)=>B(F,{color:NI[(n+Math.floor(t/4))%NI.length],children:e},t))}):B(F,{color:NI[2],children:e})}function FI({onSubmit:e,onCancelQueue:t,isDisabled:n,isAborting:r,pendingPrompt:i,registry:a,sessionName:o,history:s,onRequestFocusBackgroundList:c}){let[l,u]=z(``),[d,f]=z(null),[p,m]=z(mI),[h,g]=z([]),_=Ke(()=>_I(s??[]),[s]),v=Ke(()=>h.reduce((e,t)=>gI(e,t),_),[_,h]),y=qe(new Map),{columns:b}=He(),x=b>0?b:80,S=Math.max(1,x-3),C=qe(0),{showPopup:w,filteredCommands:ee,selectedIndex:T,setSelectedIndex:E,isSubcommandMode:D,setShowPopup:te}=wI(l,a),O=L((e,t)=>{C.current+=1;let n=C.current;y.current.set(n,e),u(r=>{let i=xI(r,t,n,e);return f(i.cursorHint),i.value})},[]),ne=L(()=>{m(mI())},[]),re=L(e=>{g(t=>gI(t,e))},[]),ie=L(t=>{re(t),ne(),e(t)},[e,re,ne]),ae=L(e=>{let t=yI(l,e);t.type===`insert`&&(u(t.value),t.selectedIndex!==void 0&&E(t.selectedIndex))},[l,E]),oe=L(e=>{let t=bI(l,e);if(t.type===`insert`){u(t.value),t.selectedIndex!==void 0&&E(t.selectedIndex);return}t.type===`submit`&&(u(``),ie(t.value))},[l,ie,E]),k=L(e=>{if(!SI(e))return;if(w&&ee[T]){oe(ee[T]);return}let t=jI(e.trim(),y.current);u(``),y.current.clear(),C.current=0,ie(t)},[w,ee,T,oe,ie]);I((e,t)=>{if(!w)return;let n=dI(t);if(n===`previous`||n===`next`)E(e=>vI(e,ee.length,n));else if(n===`close`)te(!1);else if(n===`complete`){let e=ee[T];e&&ae(e)}},{isActive:w&&!n}),I((e,t)=>{let n=pI(t);if(!n)return;if(n===`next`&&p.selectedIndex===null&&l.length===0){c?.();return}let r=hI(l,v,p,n);u(r.value),f(r.cursorHint),m(r.state)},{isActive:!w&&!n&&!i}),I((e,n)=>{fI(n)===`cancelQueue`&&i&&t?.()},{isActive:!!i});let se=r?`yellow`:i?`cyan`:n?`gray`:`green`,ce=Math.max(1,x-0),le=(()=>{if(o){let e=` "${o}" `,t=Math.max(0,ce-e.length-2);return{left:`─`.repeat(t),label:e,right:`─`.repeat(2)}}return{left:`─`.repeat(ce),label:``,right:``}})();return V(P,{flexDirection:`column`,children:[w&&B(OI,{commands:ee,selectedIndex:T,visible:w,isSubcommandMode:D}),V(F,{color:se,children:[le.left,le.label?B(F,{backgroundColor:se,color:`black`,bold:!0,children:le.label}):null,le.right]}),B(P,{borderStyle:`single`,borderTop:!1,borderLeft:!1,borderRight:!1,borderColor:se,paddingLeft:1,children:r?B(F,{color:`yellow`,children:` Interrupting...`}):i?V(F,{color:`cyan`,children:[` `,`Queued:`,` `,i.length>50?i.slice(0,47)+`...`:i,` `,B(F,{dimColor:!0,children:`(Backspace to cancel)`})]}):n?B(PI,{text:` Waiting for response... (ESC to interrupt)`}):V(P,{children:[B(F,{color:`green`,bold:!0,children:`> `}),B(aI,{value:l,onChange:e=>{u(e),ne(),f(null)},onSubmit:k,onPaste:O,placeholder:`Type a message or /help`,availableWidth:S,cursorHint:d,enableVerticalNavigation:!1})]})})]})}const II=new Set([`Shell`,`Bash`,`BackgroundProcess`]);function LI(e){if(!II.has(e.toolName)||!e.toolResultData)return;let t=RI(e.toolResultData),n=KI(t,`exitCode`),r=qI(t,`success`),i=HI(VI(zI(e.toolResultData,t))),a=i.slice(0,4),o=Math.max(0,i.length-a.length),s=e.result===`error`||r===!1||n!==void 0&&n!==0;return{status:s?`error`:`success`,statusLabel:BI(s,n),previewLines:a,omittedLineCount:o,transcriptHint:o>0?`... +${o} lines (full output in session transcript)`:void 0}}function RI(e){try{return JSON.parse(e)}catch{return e}}function zI(e,t){if(!WI(t))return e;let n=GI(t,`output`);if(n!==void 0)return n;let r=GI(t,`stdout`),i=GI(t,`stderr`),a=GI(t,`error`),o=[];return r&&o.push(r),i&&o.push(UI(i,`[stderr] `)),!r&&!i&&a&&o.push(a),o.join(`
305
+ `),cursor:e.cursor}}}function JF(e,t,n){if(t.upArrow===!0||t.downArrow===!0)return n.enableVerticalNavigation===!1?{state:e,effect:{type:`none`}}:tI(e,t.upArrow===!0?`up`:`down`,n.availableWidth);if(t.leftArrow===!0)return nI(e,`left`);if(t.rightArrow===!0)return nI(e,`right`);if(t.backspace===!0||t.delete===!0)return rI(e)}function YF(e){if(!e||e.length===0)return``;let t=``;for(let n of e){let e=n.charCodeAt(0);e>31&&e!==127&&(t+=n)}return t}function XF(e,t,n){return{value:e.slice(0,t)+n+e.slice(t),cursor:t+n.length}}function ZF(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++){let t=Xe(e[i]),a=r%n;a+t>n&&(r+=n-a),r+=t}return r}function QF(e,t,n){let r=0;for(let i=0;i<e.length;i++){if(r>=t)return i;let a=Xe(e[i]),o=r%n;o+a>n&&(r+=n-o),r+=a}return e.length}function $F(e,t){return{state:{...e,isPasting:!0,pasteBuffer:t.slice(5)},effect:{type:`none`}}}function eI(e,t,n){if(t!==VF&&!t.includes(VF))return{state:{...e,pasteBuffer:e.pasteBuffer+t},effect:{type:`none`}};let r=t.split(VF)[0]??``;return GF({...e,isPasting:!1,pasteBuffer:``},e.pasteBuffer+r,n)}function tI(e,t,n){if(!n||n<=0)return{state:e,effect:{type:`none`}};let r=[...e.value],i=ZF(r,e.cursor,n),a=t===`up`?i-n:i+n;if(a<0)return{state:e,effect:{type:`none`}};let o=QF(r,a,n);return o===e.cursor?{state:e,effect:{type:`none`}}:{state:{...e,cursor:o},effect:{type:`render`}}}function nI(e,t){return t===`left`&&e.cursor>0?{state:{...e,cursor:e.cursor-1},effect:{type:`render`}}:t===`right`&&e.cursor<e.value.length?{state:{...e,cursor:e.cursor+1},effect:{type:`render`}}:{state:e,effect:{type:`none`}}}function rI(e){if(e.cursor===0)return{state:e,effect:{type:`none`}};let t=e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor);return{state:{...e,value:t,cursor:e.cursor-1},effect:{type:`change`,value:t}}}function iI(e,t){let n=YF(t);if(n.length===0)return{state:e,effect:{type:`none`}};let r=XF(e.value,e.cursor,n);return{state:{...e,value:r.value,cursor:r.cursor},effect:{type:`change`,value:r.value}}}function aI({value:e,onChange:t,onSubmit:n,onPaste:r,placeholder:i=``,focus:a=!0,showCursor:o=!0,availableWidth:s,cursorHint:c=null,enableVerticalNavigation:l=!0}){let u=qe(HF(e)),[,d]=z(0);return u.current=UF(u.current,e,c),oI({stateRef:u,onChange:t,onSubmit:n,onPaste:r,availableWidth:s,focus:a,enableVerticalNavigation:l,forceRender:d}),B(I,{children:uI(u.current.value,u.current.cursor,i,o&&a)})}function oI(e){ze(t=>{cI(e,()=>GF(e.stateRef.current,t,sI(e)))},{isActive:e.focus}),L((t,n)=>{cI(e,()=>WF(e.stateRef.current,t,n,sI(e)))},{isActive:e.focus})}function sI(e){return{availableWidth:e.availableWidth,canPaste:e.onPaste!==void 0,enableVerticalNavigation:e.enableVerticalNavigation}}function cI(e,t){try{let n=t();e.stateRef.current=n.state,lI(n.effect,e.onChange,e.onSubmit,e.onPaste,e.forceRender)}catch{}}function lI(e,t,n,r,i){e.type===`change`?t(e.value):e.type===`submit`?n?.(e.value):e.type===`paste`?r?.(e.text,e.cursor):e.type===`render`&&i(e=>e+1)}function uI(e,t,n,r){if(!r)return e.length>0?e:n?Ye.gray(n):``;if(e.length===0)return n.length>0?Ye.inverse(n[0])+Ye.gray(n.slice(1)):Ye.inverse(` `);let i=[...e],a=``;for(let e=0;e<i.length;e++){let n=i[e]??``;a+=e===t?Ye.inverse(n):n}return t>=i.length&&(a+=Ye.inverse(` `)),a}function dI(e){if(e.upArrow===!0)return`previous`;if(e.downArrow===!0)return`next`;if(e.escape===!0)return`close`;if(e.tab===!0)return`complete`}function fI(e){if(e.backspace===!0||e.delete===!0)return`cancelQueue`}function pI(e){if(e.upArrow===!0)return`previous`;if(e.downArrow===!0)return`next`}function mI(){return{selectedIndex:null,draft:``}}function hI(e,t,n,r){if(t.length===0)return{value:e,cursorHint:e.length,state:n};if(r===`previous`){let r=n.selectedIndex===null?t.length-1:Math.max(0,n.selectedIndex-1),i=t[r]??e;return{value:i,cursorHint:i.length,state:{selectedIndex:r,draft:n.selectedIndex===null?e:n.draft}}}if(n.selectedIndex===null)return{value:e,cursorHint:e.length,state:n};if(n.selectedIndex<t.length-1){let r=n.selectedIndex+1,i=t[r]??e;return{value:i,cursorHint:i.length,state:{...n,selectedIndex:r}}}return{value:n.draft,cursorHint:n.draft.length,state:mI()}}function gI(e,t){let n=t.trim();return n.length===0||e[e.length-1]===n?[...e]:[...e,n]}function _I(e){let t=[];for(let n of e){if(n.category!==`chat`||n.type!==`user`)continue;let e=n.data;typeof e?.content==`string`&&(t=gI(t,e.content))}return t}function vI(e,t,n){return t===0?0:n===`previous`?e>0?e-1:t-1:e<t-1?e+1:0}function yI(e,t){if(Mb(e)&&e.slice(1).includes(` `)){let{name:n}=Nb(e);return{type:`insert`,value:`/${n} ${t.name} `}}return t.subcommands&&t.subcommands.length>0?{type:`insert`,value:`/${t.name} `,selectedIndex:0}:{type:`insert`,value:`/${t.name} `}}function bI(e,t){if(Mb(e)&&e.slice(1).includes(` `)){let{name:n}=Nb(e);return{type:`submit`,value:`/${n} ${t.name}`}}return t.subcommands&&t.subcommands.length>0?{type:`insert`,value:`/${t.name} `,selectedIndex:0}:{type:`submit`,value:`/${t.name}`}}function xI(e,t,n,r){let i=r.split(`
306
+ `).length,a=`[Pasted text #${n} +${i} lines]`;return{value:e.slice(0,t)+a+e.slice(t),cursorHint:t+a.length,label:a,lineCount:i}}function SI(e){return e.trim().length>0}function CI(e){if(!e.startsWith(`/`))return{isSlash:!1,parentCommand:``,filter:``};let t=e.slice(1),n=t.indexOf(` `);return n===-1?{isSlash:!0,parentCommand:``,filter:t}:{isSlash:!0,parentCommand:t.slice(0,n),filter:t.slice(n+1)}}function wI(e,t){let[n,r]=z(0),[i,a]=z(!1),o=He.useRef(e);o.current!==e&&(o.current=e,i&&a(!1));let s=CI(e),c=s.isSlash&&s.parentCommand.length>0,l=Ke(()=>{if(!t||!s.isSlash||i)return[];if(c){let e=t.getSubcommands(s.parentCommand);if(e.length===0)return[];if(!s.filter)return e;let n=s.filter.toLowerCase();return e.filter(e=>e.name.toLowerCase().startsWith(n))}return t.getCommands(s.filter)},[t,s.isSlash,s.parentCommand,s.filter,i,c]),u=s.isSlash&&l.length>0&&!i;return n>=l.length&&l.length>0&&r(l.length-1),{showPopup:u,filteredCommands:l,selectedIndex:n,setSelectedIndex:r,isSubcommandMode:c,setShowPopup:e=>{a(typeof e==`function`?t=>!e(!t):!e)}}}function TI(){let{stdout:e}=Be(),t=()=>Math.max(40,(e.columns??80)-4),[n,r]=z(t);return Ge(()=>{let n=()=>r(t());return e.on(`resize`,n),()=>{e.off(`resize`,n)}},[e]),n}function EI(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e.padEnd(t)}function DI(e){let{cmd:t,isSelected:n,showSlash:r,rowWidth:i,nameColWidth:a}=e,o=n?`> `:` `,s=n?`cyan`:void 0,c=!n,l=EI(t.name,a);return B(F,{width:i,children:B(I,{color:s,dimColor:c,wrap:`truncate-end`,children:r?`${o}/${l} ${t.description??``}`:`${o}${l} ${t.description??``}`})})}function OI({commands:e,selectedIndex:t,visible:n,isSubcommandMode:r}){let i=TI();if(!n||e.length===0)return null;let a=kI(t,e.length),o=e.slice(a,a+8),s=Math.min(20,Math.max(...o.map(e=>e.name.length)));return V(F,{flexDirection:`column`,borderStyle:`round`,borderColor:`gray`,paddingX:1,children:[o.map((e,n)=>B(DI,{cmd:e,isSelected:a+n===t,showSlash:!r,rowWidth:i,nameColWidth:s},e.name)),B(I,{dimColor:!0,children:` ↑↓ Navigate Tab Complete Enter Select Esc Close`})]})}function kI(e,t){if(t<=8||e<8)return 0;let n=t-8;return Math.min(e-8+1,n)}const AI=/\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;function jI(e,t){return e.replace(AI,(e,n)=>t.get(Number(n))??``)}function MI(){if(`NO_COLOR`in process.env)return!1;let e=process.env.FORCE_COLOR;return e===`0`?!1:e!==void 0&&e!==``?!0:!!process.stdout.isTTY}const NI=[`#666666`,`#888888`,`#aaaaaa`,`#888888`];function PI({text:e}){let t=MI(),[n,r]=z(0);return Ge(()=>{if(!t)return;let e=setInterval(()=>{r(e=>e+1)},400);return()=>clearInterval(e)},[t]),t?B(I,{children:[...e].map((e,t)=>B(I,{color:NI[(n+Math.floor(t/4))%NI.length],children:e},t))}):B(I,{color:NI[2],children:e})}function FI({onSubmit:e,onCancelQueue:t,isDisabled:n,isAborting:r,pendingPrompt:i,registry:a,sessionName:o,history:s,onRequestFocusBackgroundList:c}){let[l,u]=z(``),[d,f]=z(null),[p,m]=z(mI),[h,g]=z([]),_=Ke(()=>_I(s??[]),[s]),v=Ke(()=>h.reduce((e,t)=>gI(e,t),_),[_,h]),y=qe(new Map),{columns:b}=Ve(),x=b>0?b:80,S=Math.max(1,x-3),C=qe(0),{showPopup:w,filteredCommands:T,selectedIndex:E,setSelectedIndex:D,isSubcommandMode:O,setShowPopup:k}=wI(l,a),A=R((e,t)=>{C.current+=1;let n=C.current;y.current.set(n,e),u(r=>{let i=xI(r,t,n,e);return f(i.cursorHint),i.value})},[]),ee=R(()=>{m(mI())},[]),te=R(e=>{g(t=>gI(t,e))},[]),ne=R(t=>{te(t),ee(),e(t)},[e,te,ee]),re=R(e=>{let t=yI(l,e);t.type===`insert`&&(u(t.value),t.selectedIndex!==void 0&&D(t.selectedIndex))},[l,D]),ie=R(e=>{let t=bI(l,e);if(t.type===`insert`){u(t.value),t.selectedIndex!==void 0&&D(t.selectedIndex);return}t.type===`submit`&&(u(``),ne(t.value))},[l,ne,D]),ae=R(e=>{if(!SI(e))return;if(w&&T[E]){ie(T[E]);return}let t=jI(e.trim(),y.current);u(``),y.current.clear(),C.current=0,ne(t)},[w,T,E,ie,ne]);L((e,t)=>{if(!w)return;let n=dI(t);if(n===`previous`||n===`next`)D(e=>vI(e,T.length,n));else if(n===`close`)k(!1);else if(n===`complete`){let e=T[E];e&&re(e)}},{isActive:w&&!n}),L((e,t)=>{let n=pI(t);if(!n)return;if(n===`next`&&p.selectedIndex===null&&l.length===0){c?.();return}let r=hI(l,v,p,n);u(r.value),f(r.cursorHint),m(r.state)},{isActive:!w&&!n&&!i}),L((e,n)=>{fI(n)===`cancelQueue`&&i&&t?.()},{isActive:!!i});let oe=r?`yellow`:i?`cyan`:n?`gray`:`green`,se=Math.max(1,x-0),ce=(()=>{if(o){let e=` "${o}" `,t=Math.max(0,se-e.length-2);return{left:`─`.repeat(t),label:e,right:`─`.repeat(2)}}return{left:`─`.repeat(se),label:``,right:``}})();return V(F,{flexDirection:`column`,children:[w&&B(OI,{commands:T,selectedIndex:E,visible:w,isSubcommandMode:O}),V(I,{color:oe,children:[ce.left,ce.label?B(I,{backgroundColor:oe,color:`black`,bold:!0,children:ce.label}):null,ce.right]}),B(F,{borderStyle:`single`,borderTop:!1,borderLeft:!1,borderRight:!1,borderColor:oe,paddingLeft:1,children:r?B(I,{color:`yellow`,children:` Interrupting...`}):i?V(I,{color:`cyan`,children:[` `,`Queued:`,` `,i.length>50?i.slice(0,47)+`...`:i,` `,B(I,{dimColor:!0,children:`(Backspace to cancel)`})]}):n?B(PI,{text:` Waiting for response... (ESC to interrupt)`}):V(F,{children:[B(I,{color:`green`,bold:!0,children:`> `}),B(aI,{value:l,onChange:e=>{u(e),ee(),f(null)},onSubmit:ae,onPaste:A,placeholder:`Type a message or /help`,availableWidth:S,cursorHint:d,enableVerticalNavigation:!1})]})})]})}const II=new Set([`Shell`,`Bash`,`BackgroundProcess`]);function LI(e){if(!II.has(e.toolName)||!e.toolResultData)return;let t=RI(e.toolResultData),n=KI(t,`exitCode`),r=qI(t,`success`),i=HI(VI(zI(e.toolResultData,t))),a=i.slice(0,4),o=Math.max(0,i.length-a.length),s=e.result===`error`||r===!1||n!==void 0&&n!==0;return{status:s?`error`:`success`,statusLabel:BI(s,n),previewLines:a,omittedLineCount:o,transcriptHint:o>0?`... +${o} lines (full output in session transcript)`:void 0}}function RI(e){try{return JSON.parse(e)}catch{return e}}function zI(e,t){if(!WI(t))return e;let n=GI(t,`output`);if(n!==void 0)return n;let r=GI(t,`stdout`),i=GI(t,`stderr`),a=GI(t,`error`),o=[];return r&&o.push(r),i&&o.push(UI(i,`[stderr] `)),!r&&!i&&a&&o.push(a),o.join(`
307
307
  `)}function BI(e,t){return t!==void 0&&t!==0?`exit ${t}`:e?`error`:`ok`}function VI(e){return e?e.replace(/\r\n/g,`
308
308
  `).split(`
309
309
  `):[]}function HI(e){let t=e.length;for(;t>0&&e[t-1].trim().length===0;)--t;return e.slice(0,t)}function UI(e,t){return VI(e).map(e=>`${t}${e}`).join(`
310
310
  `)}function WI(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function GI(e,t){if(!WI(e))return;let n=e[t];return typeof n==`string`?n:void 0}function KI(e,t){if(!WI(e))return;let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function qI(e,t){if(!WI(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}const JI=/_[0-9a-f]{8}$/;function YI(e){if(!e.startsWith($d))return e;let t=e.slice(15).replace(JI,``);return t.length>0?t:e}const XI={reset:`\x1B[0m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,lightRed:`\x1B[38;5;210m`,lightGreen:`\x1B[38;5;120m`,darkRedBackground:`\x1B[48;5;52m`,darkGreenBackground:`\x1B[48;5;22m`},ZI=` `,QI=Qe;function $I(e){return e===void 0?MI():e}function eL(e){return e?.trim().toLowerCase()===`diff`}function tL(e,t,n){let r=`${ZI}${e}`.padEnd(t);return n?e.startsWith(`+`)?`${XI.darkGreenBackground}${XI.lightGreen}${r}${XI.reset}`:e.startsWith(`-`)?`${XI.darkRedBackground}${XI.lightRed}${r}${XI.reset}`:r.trimEnd():r.trimEnd()}function nL(e,t,n){if(e.startsWith(`+`)||e.startsWith(`-`))return tL(e,n,t);let r=`${ZI}${e}`;return t?e.startsWith(`@@`)?`${XI.cyan}${r}${XI.reset}`:e.startsWith(`diff `)||e.startsWith(`index `)?`${XI.dim}${r}${XI.reset}`:r:r}function rL(e,t){let n=e.reduce((e,t)=>Math.max(e,4+t.length),0);return t===void 0?n:Math.max(n,t)}function iL(e,t,n){let r=e.split(`
311
311
  `),i=rL(r,n);return`${r.map(e=>nL(e,t,i)).join(`
312
- `)}\n\n`}function aL(e,t){let n=new QI(void 0,{ignoreIllegals:!0}),r=n.code.bind(n);return n.code=(n,i,a)=>eL(i)?iL(n,e,t):r(n,i,a),n}function oL(e,t={}){let n=Ze.parse(e,{renderer:aL($I(t.color),t.codeBlockWidth)});return typeof n==`string`?n.trimEnd():e}function sL({tool:e}){let t=LI(e);if(!t||t.statusLabel===`ok`&&t.previewLines.length===0&&!t.transcriptHint)return null;let n=t.status===`error`?GP.error.color:`white`;return V(P,{flexDirection:`column`,marginLeft:4,children:[t.statusLabel!==`ok`&&B(F,{color:n,dimColor:!0,children:t.statusLabel}),t.previewLines.map((e,t)=>B(F,{color:n,dimColor:!0,children:e},`${e}-${t}`)),t.transcriptHint&&B(F,{dimColor:!0,children:t.transcriptHint})]})}function cL(e){let t=e.lines.length>12?uL(e.lines):e.lines,n=Math.max(...t.map(e=>e.lineNumber),0).toString().length,r=t.map(e=>lL(e,n)),i=e.lines.length>12;return{file:e.file,markdown:["```diff",...r,"```"].join(`
313
- `),truncated:i,remainingLineCount:i?e.lines.length-t.length:0}}function lL(e,t){if(e.type===`hunk`)return e.text;let n=e.lineNumber.toString().padStart(t,` `);return e.type===`remove`?`- ${n} | ${e.text}`:e.type===`add`?`+ ${n} | ${e.text}`:` ${n} | ${e.text}`}function uL(e){let t=dL(e),n=[];for(let e of t){if(n.length===0&&e.length>10)return e.slice(0,10);if(n.length+e.length>10)break;n.push(...e)}return n.length>0?n:e.slice(0,10)}function dL(e){let t=[],n=[];for(let r of e){if(r.type===`hunk`&&n.length>0){t.push(n),n=[r];continue}n.push(r)}return n.length>0&&t.push(n),t}function fL({file:e,lines:t}){let n=cL({file:e,lines:t});return V(P,{flexDirection:`column`,marginLeft:4,children:[n.file&&V(F,{color:`white`,dimColor:!0,children:[`│ `,n.file]}),B(F,{children:oL(n.markdown)}),n.truncated&&V(F,{color:`white`,dimColor:!0,children:[`│ ... and `,n.remainingLineCount,` more lines`]})]})}function pL({entry:e}){let t=e.data;if(!t)return B(Je,{});let n=t.promptTokens===void 0?`?`:mL(t.promptTokens),r=t.completionTokens===void 0?`?`:mL(t.completionTokens),i=mL(t.totalTokens),a=`${Math.round(t.contextUsedPercentage)}% (${Zn(t.contextUsedTokens)}/${Zn(t.contextMaxTokens)})`,o=t.costStatus===`unknown`?`cost unknown`:`cost ${t.costStatus}`;return B(P,{flexDirection:`column`,marginBottom:1,children:V(P,{children:[V(F,{color:`white`,bold:!0,children:[`Usage:`,` `]}),V(F,{dimColor:!0,children:[t.kind,` `,i,` tokens (in `,n,` / out `,r,`) · Context `,a,` ·`,` `,o]})]})})}function mL(e){return e<1e3?e.toLocaleString():Zn(e)}function hL(e){return LI(e)?.status===`error`?`✗`:e.isRunning?`⟳`:e.result===`error`?`✗`:e.result===`denied`?`⊘`:`✓`}function gL(e){return LI(e)?.status===`error`||e.result===`error`?`red`:e.isRunning||e.result===`denied`?`yellow`:`green`}function _L(e){return`${hL(e)} ${YI(e.toolName)}${e.firstArg?`(${e.firstArg})`:``}`}function vL({role:e}){switch(e){case`user`:return V(F,{color:`green`,bold:!0,children:[`You:`,` `]});case`assistant`:return V(F,{color:`cyan`,bold:!0,children:[`Robota:`,` `]});case`system`:return V(F,{color:`yellow`,bold:!0,children:[`System:`,` `]});case`tool`:return V(F,{color:`white`,bold:!0,children:[`Tool:`,` `]})}}function yL({message:e}){if(!Ot(e))return B(Je,{});let t=e.name,n=e.content,r=null;try{let e=JSON.parse(n);Array.isArray(e)&&e.length>0&&typeof e[0].line==`string`&&(r=e)}catch{}if(r)return V(P,{flexDirection:`column`,marginBottom:1,children:[V(P,{children:[V(F,{color:`white`,bold:!0,children:[`Tool:`,` `]}),t&&V(F,{color:`white`,dimColor:!0,children:[`[`,YI(t),`]`]})]}),B(F,{children:` `}),r.map((e,t)=>V(P,{flexDirection:`column`,children:[V(F,{color:`green`,children:[` `,`✓`,` `,e.line]}),e.diffLines&&e.diffLines.length>0&&B(fL,{file:e.diffFile,lines:e.diffLines})]},t))]});let i=n.split(`
314
- `).filter(e=>e.trim());return V(P,{flexDirection:`column`,marginBottom:1,children:[V(P,{children:[V(F,{color:`white`,bold:!0,children:[`Tool:`,` `]}),t&&V(F,{color:`white`,dimColor:!0,children:[`[`,t,`]`]})]}),B(F,{children:` `}),i.map((e,t)=>V(F,{color:`green`,children:[` `,`✓`,` `,e]},t))]})}function bL({message:e}){let t=(e.content??``).replace(/^Error:\s*/,``);return V(P,{flexDirection:`column`,marginBottom:1,children:[B(P,{children:V(F,{color:`red`,bold:!0,children:[`✖ Error:`,` `]})}),V(P,{marginLeft:2,flexDirection:`column`,children:[B(F,{color:`red`,wrap:`wrap`,children:t}),B(F,{dimColor:!0,wrap:`wrap`,children:`The session is still alive — type your next prompt when ready.`})]})]})}const xL=Ue.memo(function({message:e}){if(Ot(e))return B(yL,{message:e});if(e.role===`system`&&e.metadata?.kind===`error`)return B(bL,{message:e});let t=e.content??``,n=e.state===`interrupted`;return V(P,{flexDirection:`column`,marginBottom:1,children:[B(P,{children:B(vL,{role:e.role})}),B(F,{children:` `}),B(P,{marginLeft:2,children:B(F,{wrap:`wrap`,children:Et(e)?oL(t+(n?`
312
+ `)}\n\n`}function aL(e,t){let n=new QI(void 0,{ignoreIllegals:!0}),r=n.code.bind(n);return n.code=(n,i,a)=>eL(i)?iL(n,e,t):r(n,i,a),n}function oL(e,t={}){let n=Ze.parse(e,{renderer:aL($I(t.color),t.codeBlockWidth)});return typeof n==`string`?n.trimEnd():e}function sL({tool:e}){let t=LI(e);if(!t||t.statusLabel===`ok`&&t.previewLines.length===0&&!t.transcriptHint)return null;let n=t.status===`error`?GP.error.color:`white`;return V(F,{flexDirection:`column`,marginLeft:4,children:[t.statusLabel!==`ok`&&B(I,{color:n,dimColor:!0,children:t.statusLabel}),t.previewLines.map((e,t)=>B(I,{color:n,dimColor:!0,children:e},`${e}-${t}`)),t.transcriptHint&&B(I,{dimColor:!0,children:t.transcriptHint})]})}function cL(e){let t=e.lines.length>12?uL(e.lines):e.lines,n=Math.max(...t.map(e=>e.lineNumber),0).toString().length,r=t.map(e=>lL(e,n)),i=e.lines.length>12;return{file:e.file,markdown:["```diff",...r,"```"].join(`
313
+ `),truncated:i,remainingLineCount:i?e.lines.length-t.length:0}}function lL(e,t){if(e.type===`hunk`)return e.text;let n=e.lineNumber.toString().padStart(t,` `);return e.type===`remove`?`- ${n} | ${e.text}`:e.type===`add`?`+ ${n} | ${e.text}`:` ${n} | ${e.text}`}function uL(e){let t=dL(e),n=[];for(let e of t){if(n.length===0&&e.length>10)return e.slice(0,10);if(n.length+e.length>10)break;n.push(...e)}return n.length>0?n:e.slice(0,10)}function dL(e){let t=[],n=[];for(let r of e){if(r.type===`hunk`&&n.length>0){t.push(n),n=[r];continue}n.push(r)}return n.length>0&&t.push(n),t}function fL({file:e,lines:t}){let n=cL({file:e,lines:t});return V(F,{flexDirection:`column`,marginLeft:4,children:[n.file&&V(I,{color:`white`,dimColor:!0,children:[`│ `,n.file]}),B(I,{children:oL(n.markdown)}),n.truncated&&V(I,{color:`white`,dimColor:!0,children:[`│ ... and `,n.remainingLineCount,` more lines`]})]})}function pL({entry:e}){let t=e.data;if(!t)return B(Je,{});let n=t.promptTokens===void 0?`?`:mL(t.promptTokens),r=t.completionTokens===void 0?`?`:mL(t.completionTokens),i=mL(t.totalTokens),a=`${Math.round(t.contextUsedPercentage)}% (${Zn(t.contextUsedTokens)}/${Zn(t.contextMaxTokens)})`,o=t.costStatus===`unknown`?`cost unknown`:`cost ${t.costStatus}`;return B(F,{flexDirection:`column`,marginBottom:1,children:V(F,{children:[V(I,{color:`white`,bold:!0,children:[`Usage:`,` `]}),V(I,{dimColor:!0,children:[t.kind,` `,i,` tokens (in `,n,` / out `,r,`) · Context `,a,` ·`,` `,o]})]})})}function mL(e){return e<1e3?e.toLocaleString():Zn(e)}function hL(e){return LI(e)?.status===`error`?`✗`:e.isRunning?`⟳`:e.result===`error`?`✗`:e.result===`denied`?`⊘`:`✓`}function gL(e){return LI(e)?.status===`error`||e.result===`error`?`red`:e.isRunning||e.result===`denied`?`yellow`:`green`}function _L(e){return`${hL(e)} ${YI(e.toolName)}${e.firstArg?`(${e.firstArg})`:``}`}function vL({role:e}){switch(e){case`user`:return V(I,{color:`green`,bold:!0,children:[`You:`,` `]});case`assistant`:return V(I,{color:`cyan`,bold:!0,children:[`Robota:`,` `]});case`system`:return V(I,{color:`yellow`,bold:!0,children:[`System:`,` `]});case`tool`:return V(I,{color:`white`,bold:!0,children:[`Tool:`,` `]})}}function yL({message:e}){if(!Ot(e))return B(Je,{});let t=e.name,n=e.content,r=null;try{let e=JSON.parse(n);Array.isArray(e)&&e.length>0&&typeof e[0].line==`string`&&(r=e)}catch{}if(r)return V(F,{flexDirection:`column`,marginBottom:1,children:[V(F,{children:[V(I,{color:`white`,bold:!0,children:[`Tool:`,` `]}),t&&V(I,{color:`white`,dimColor:!0,children:[`[`,YI(t),`]`]})]}),B(I,{children:` `}),r.map((e,t)=>V(F,{flexDirection:`column`,children:[V(I,{color:`green`,children:[` `,`✓`,` `,e.line]}),e.diffLines&&e.diffLines.length>0&&B(fL,{file:e.diffFile,lines:e.diffLines})]},t))]});let i=n.split(`
314
+ `).filter(e=>e.trim());return V(F,{flexDirection:`column`,marginBottom:1,children:[V(F,{children:[V(I,{color:`white`,bold:!0,children:[`Tool:`,` `]}),t&&V(I,{color:`white`,dimColor:!0,children:[`[`,t,`]`]})]}),B(I,{children:` `}),i.map((e,t)=>V(I,{color:`green`,children:[` `,`✓`,` `,e]},t))]})}function bL({message:e}){let t=(e.content??``).replace(/^Error:\s*/,``);return V(F,{flexDirection:`column`,marginBottom:1,children:[B(F,{children:V(I,{color:`red`,bold:!0,children:[`✖ Error:`,` `]})}),V(F,{marginLeft:2,flexDirection:`column`,children:[B(I,{color:`red`,wrap:`wrap`,children:t}),B(I,{dimColor:!0,wrap:`wrap`,children:`The session is still alive — type your next prompt when ready.`})]})]})}const xL=He.memo(function({message:e}){if(Ot(e))return B(yL,{message:e});if(e.role===`system`&&e.metadata?.kind===`error`)return B(bL,{message:e});let t=e.content??``,n=e.state===`interrupted`;return V(F,{flexDirection:`column`,marginBottom:1,children:[B(F,{children:B(vL,{role:e.role})}),B(I,{children:` `}),B(F,{marginLeft:2,children:B(I,{wrap:`wrap`,children:Et(e)?oL(t+(n?`
315
315
 
316
316
  _(interrupted)_`:``)):t})})]})});function SL({entry:e}){let t=e.data,n=t?.tools,r=t?.summary?.split(`
317
- `)??[];return n&&n.length>0?V(P,{flexDirection:`column`,marginBottom:1,children:[B(P,{children:V(F,{color:`white`,bold:!0,children:[`Tool:`,` `]})}),B(F,{children:` `}),n.map((e,t)=>V(P,{flexDirection:`column`,children:[V(F,{color:gL(e),children:[` `,_L(e)]}),B(sL,{tool:e}),e.diffLines&&e.diffLines.length>0&&B(fL,{file:e.diffFile,lines:e.diffLines})]},t))]}):V(P,{flexDirection:`column`,marginBottom:1,children:[B(P,{children:V(F,{color:`white`,bold:!0,children:[`Tool:`,` `]})}),B(F,{children:` `}),r.map((e,t)=>V(F,{color:`green`,children:[` `,e]},t))]})}function CL({entry:e}){let t=e.data,n=typeof t?.message==`string`?t.message:typeof t?.content==`string`?t.content:e.type;return V(P,{flexDirection:`column`,marginBottom:1,children:[B(P,{children:V(F,{color:`yellow`,bold:!0,children:[`System:`,` `]})}),B(F,{children:` `}),B(P,{marginLeft:2,children:B(F,{wrap:`wrap`,children:n})})]})}function wL({entry:e}){if(e.category===`chat`){let t=e.data;return B(xL,{message:t})}return e.type===`tool-summary`?B(SL,{entry:e}):e.type===`usage-summary`?B(pL,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?B(Je,{}):B(CL,{entry:e})}function TL({items:e,renderItem:t,onSelect:n,onCancel:r,maxVisible:i=3,footerHint:a=` ↑↓ Navigate Enter Select Esc Cancel`}){let[o,s]=z(()=>fF()),c=qe(o),l=L(t=>{let a=hF(c.current,t,{itemCount:e.length,maxVisible:i});if(c.current=a.state,s(a.state),a.effect.type===`cancel`)r();else if(a.effect.type===`select`){let t=e[a.effect.index];t!==void 0&&n(t)}},[e,i,r,n]);if(I((e,t)=>{let n=pF(t);n!==void 0&&l(n)}),e.length===0)return B(P,{});let u=gF(o,{itemCount:e.length,maxVisible:i});u!==o&&(c.current=u);let{selectedIndex:d,scrollOffset:f}=u,p=e.slice(f,f+i),m=f+i<e.length;return V(P,{flexDirection:`column`,children:[f>0&&V(F,{dimColor:!0,children:[` ↑ `,f,` more above`]}),p.map((e,n)=>B(P,{marginBottom:1,children:t(e,f+n===d)},f+n)),m&&V(F,{dimColor:!0,children:[` ↓ `,e.length-f-i,` more below`]}),a!==``&&B(F,{dimColor:!0,children:a})]})}function EL({title:e,description:t,options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o,onCancel:s}){let[c,l]=z(0),[u,d]=z(()=>new Set(a??[])),f=e=>{d(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.size<i&&n.add(e),n})};I((e,t)=>{if(t.upArrow)l(e=>e<=0?n.length-1:e-1);else if(t.downArrow)l(e=>e>=n.length-1?0:e+1);else if(e===` `){let e=n[c];e!==void 0&&f(e.value)}else t.return?u.size>=r&&o([...u]):t.escape&&s()});let p=u.size>=r;return V(P,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(F,{color:`yellow`,bold:!0,children:e}),t!==void 0&&t.length>0&&B(F,{dimColor:!0,children:t}),n.map((e,t)=>{let n=t===c,r=u.has(e.value);return V(F,{color:n?`cyan`:void 0,children:[n?`> `:` `,r?`[x] `:`[ ] `,e.label]},e.value)}),V(F,{dimColor:!0,children:[` ↑↓ Navigate Space Toggle Enter Confirm`,p?``:` (min ${r})`,` Esc Cancel`]})]})}function DL(){return{value:``,resolved:!1}}function OL(e,t){if(t.escape===!0)return{type:`cancel`};if(t.return===!0)return{type:`submit`};if(t.backspace===!0||t.delete===!0)return{type:`delete`};if(e&&t.ctrl!==!0&&t.meta!==!0)return{type:`insert`,value:e}}function kL(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:t.type===`cancel`?{state:{...e,resolved:!0},effect:{type:`cancel`}}:t.type===`delete`?{state:{...e,value:e.value.slice(0,-1),error:void 0},effect:{type:`none`}}:t.type===`insert`?{state:{...e,value:e.value+t.value,error:void 0},effect:{type:`none`}}:AL(e,n)}function AL(e,t){let n=e.value.trim();if(!n&&!t.allowEmpty){let r=t.validate?.(n);return{state:r?{...e,error:r}:e,effect:{type:`none`}}}let r=t.validate?.(n);return r===void 0?{state:{...e,resolved:!0},effect:{type:`submit`,value:n}}:{state:{...e,error:r},effect:{type:`none`}}}function jL({title:e,description:t,placeholder:n,onSubmit:r,onCancel:i,validate:a,allowEmpty:o=!1,masked:s=!1}){let[c,l]=z(()=>DL()),u=qe(c),d=L(e=>{let t=kL(u.current,e,{allowEmpty:o,validate:a});u.current=t.state,l(t.state),t.effect.type===`cancel`?i():t.effect.type===`submit`&&r(t.effect.value)},[o,a,i,r]);return I((e,t)=>{let n=OL(e,t);n!==void 0&&d(n)}),V(P,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(F,{color:`yellow`,bold:!0,children:e}),B(ML,{description:t}),V(P,{marginTop:1,children:[B(F,{color:`cyan`,children:`> `}),c.value?B(F,{children:s?`*`.repeat(c.value.length):c.value}):n?B(F,{dimColor:!0,children:n}):null,B(F,{color:`cyan`,children:`█`})]}),c.error&&B(F,{color:`red`,children:c.error}),B(F,{dimColor:!0,children:` Enter Submit Esc Cancel`})]})}function ML({description:e}){return e===void 0||e.length===0?null:B(F,{dimColor:!0,children:e})}const NL={value:``,label:`Type a custom answer…`};function PL({request:e,onAnswer:t}){let[n,r]=z(!1),i=e.options??[],a=i.length>0,o=e.maxSelect??1,s=()=>t({type:`cancelled`});if(!a||n)return B(jL,{title:e.title,description:e.description,placeholder:e.placeholder,allowEmpty:e.allowEmpty,masked:e.masked,onSubmit:e=>t({type:`answer`,values:[],text:e}),onCancel:n?()=>r(!1):s},`text:${e.id}`);if(o>1)return B(EL,{title:e.title,description:e.description,options:i,minSelect:e.minSelect??1,maxSelect:o,defaultValues:e.default?.values,onConfirm:e=>t({type:`answer`,values:e}),onCancel:s});let c=e.allowFreeText?[...i,NL]:[...i];return V(P,{flexDirection:`column`,children:[B(F,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&B(F,{dimColor:!0,children:e.description}),B(TL,{items:c,maxVisible:e.maxVisible,renderItem:(e,t)=>V(F,{color:t?`cyan`:void 0,children:[t?`> `:` `,e.label]}),onSelect:e=>{e===NL?r(!0):t({type:`answer`,values:[e.value]})},onCancel:s})]})}const FL=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function IL(e,t){let n=mF({...t,escape:!1});if(n!==void 0)return n;if(e===`y`||e===`1`)return{type:`shortcut`,index:0};if(e===`s`||e===`a`||e===`2`)return{type:`shortcut`,index:1};if(e===`p`||e===`3`)return{type:`shortcut`,index:2};if(e===`n`||e===`d`||e===`4`)return{type:`shortcut`,index:3}}function LL(e,t){if(e.resolved)return{state:e,effect:{type:`none`}};if(typeof t!=`string`)return zL(e,t.index);let n=hF(e,t,{itemCount:FL.length});return n.effect.type===`select`?{state:n.state,effect:{type:`resolve`,decision:RL(n.effect.index)}}:{state:n.state,effect:{type:`none`}}}function RL(e){return e===0?!0:e===1?`allow-session`:e===2?`allow-project`:!1}function zL(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:RL(t)}}}function BL(e){let t=Object.entries(e);return t.length===0?`(no arguments)`:t.map(([e,t])=>`${e}: ${typeof t==`string`?t:JSON.stringify(t)}`).join(`, `)}function VL({request:e}){let[t,n]=Ue.useState(()=>fF()),r=Ue.useRef(t),i=Ue.useRef(e);if(i.current!==e){i.current=e;let t=fF();r.current=t,n(t)}let a=Ue.useCallback(t=>{let i=LL(r.current,t);r.current=i.state,n(i.state),i.effect.type===`resolve`&&e.resolve(i.effect.decision)},[e]);return I((e,t)=>{let n=IL(e,t);n!==void 0&&a(n)}),V(P,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(F,{color:`yellow`,bold:!0,children:`[Permission Required]`}),V(F,{children:[`Tool:`,` `,B(F,{color:`cyan`,bold:!0,children:e.toolName})]}),V(F,{dimColor:!0,children:[` `,BL(e.toolArgs)]}),B(P,{marginTop:1,children:FL.map((e,n)=>B(P,{marginRight:2,children:V(F,{color:n===t.selectedIndex?`cyan`:void 0,bold:n===t.selectedIndex,children:[n===t.selectedIndex?`> `:` `,e]})},e))}),B(F,{dimColor:!0,children:` left/right to select, Enter to confirm`})]})}function HL(e,t,n){let r=mF({...t,escape:!1});if(r!==void 0)return r;if(n===2&&e===`y`)return{type:`shortcut`,index:0};if(n===2&&e===`n`)return{type:`shortcut`,index:1}}function UL(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?hF(e,t,{itemCount:n}):{state:{...e,selectedIndex:t.index,resolved:!0},effect:{type:`select`,index:t.index}}}function WL({message:e,options:t=[`Yes`,`No`],onSelect:n}){let[r,i]=z(()=>fF()),a=qe(r),o=L(e=>{let r=UL(a.current,e,t.length);a.current=r.state,i(r.state),r.effect.type===`select`&&n(r.effect.index)},[n,t.length]);return I((e,n)=>{let r=HL(e,n,t.length);r!==void 0&&o(r)}),V(P,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(F,{color:`yellow`,children:e}),B(P,{marginTop:1,children:t.map((e,t)=>B(P,{marginRight:2,children:V(F,{color:t===r.selectedIndex?`cyan`:void 0,bold:t===r.selectedIndex,children:[t===r.selectedIndex?`> `:` `,e]})},e))}),B(F,{dimColor:!0,children:` arrow keys to select, Enter to confirm`})]})}function GL(e,t,n,r,i){let[a,o]=z([]),[s,c]=z(!1),[l,u]=z();return R(()=>{if(o([]),u(void 0),e===`marketplace-list`)c(!0),n.marketplaceList().then(e=>{let t=[{label:`Add Marketplace`,value:`__add__`}],n=e.map(e=>({label:e.name,value:e.name,hint:e.type}));o([...t,...n]),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)});else if(e===`marketplace-browse`){let e=t??``;c(!0),n.listAvailablePlugins(e).then(e=>{o(e.map(e=>({label:e.name,value:e.name,hint:e.installed?`installed`:e.description}))),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)})}else e===`installed-list`&&(c(!0),n.listInstalled().then(e=>{o(e.map(e=>({label:e.name,value:e.name,hint:e.description}))),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)}))},[i,e,t,n,r]),{items:a,loading:s,error:l}}function KL({title:e,items:t,onSelect:n,onBack:r,loading:i,error:a}){let[o,s]=z(()=>fF()),c=qe(o),l=!i&&!a,u=L(e=>{let i=hF(c.current,e,{itemCount:t.length,enabled:l});if(c.current=i.state,s(i.state),i.effect.type===`cancel`)r();else if(i.effect.type===`select`){let e=t[i.effect.index];e!==void 0&&n(e.value)}},[l,t,r,n]);I((e,t)=>{let n=pF(t);n!==void 0&&u(n)});let d=gF(o,{itemCount:t.length});d!==o&&(c.current=d);let f=d.selectedIndex;return V(P,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(F,{color:`yellow`,bold:!0,children:e}),i&&B(P,{marginTop:1,children:B(F,{dimColor:!0,children:`Loading...`})}),a&&V(P,{marginTop:1,flexDirection:`column`,children:[B(F,{color:`red`,children:a}),B(F,{dimColor:!0,children:`Press Esc to go back`})]}),!i&&!a&&B(P,{flexDirection:`column`,marginTop:1,children:t.map((e,t)=>V(P,{children:[V(F,{color:t===f?`cyan`:void 0,bold:t===f,children:[t===f?`> `:` `,e.label]}),e.hint&&V(F,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),B(F,{dimColor:!0,children:i||a?``:` ↑↓ Navigate Enter Select Esc Back`})]})}function qL(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function JL(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function YL(e,t,n,r){e===`browse`?r.push({screen:`marketplace-browse`,context:{marketplace:t}}):e===`update`?n.marketplaceUpdate(t).then(()=>{r.notify(`Updated marketplace "${t}".`),r.pop()}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)}):e===`remove`&&r.setConfirm({message:`Remove marketplace "${t}" and all its plugins?`,onConfirm:()=>{r.setConfirm(void 0),n.marketplaceRemove(t).then(()=>{r.notify(`Removed marketplace "${t}".`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>r.setConfirm(void 0)})}function XL(e,t,n,r){let i=`${e}@${t}`;n.find(t=>t.value===e)?.hint===`installed`?r.push({screen:`installed-action`,context:{pluginId:i}}):r.push({screen:`marketplace-install-scope`,context:{marketplace:t,pluginId:i}})}function ZL(e,t,n,r){let i=e;n.install(t,i).then(()=>{r.notify(`Installed plugin "${t}" (${i} scope).`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})}function QL(e,t,n){n.setConfirm({message:`Uninstall plugin "${e}"?`,onConfirm:()=>{n.setConfirm(void 0),t.uninstall(e).then(()=>{n.notify(`Uninstalled plugin "${e}".`),n.refresh()}).catch(e=>{n.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>n.setConfirm(void 0)})}function $L(e,t,n,r){e===`uninstall`&&r.setConfirm({message:`Uninstall plugin "${t}"?`,onConfirm:()=>{r.setConfirm(void 0),n.uninstall(t).then(()=>{r.notify(`Uninstalled plugin "${t}".`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>r.setConfirm(void 0)})}function eR({callbacks:e,onClose:t,addMessage:n}){let[r,i]=z([{screen:`main`}]),[a,o]=z(),[s,c]=z(0),l=r[r.length-1]??{screen:`main`},u=L(e=>{i(t=>[...t,e])},[]),d=L(()=>{i(e=>e.length<=1?(t(),e):e.slice(0,-1))},[t]),f=L(e=>{i(n=>{let r=n.slice(0,Math.max(1,n.length-e));return r.length===0?(t(),n):r})},[t]),p=L(e=>{n?.({role:`system`,content:e})},[n]),m=L(()=>{c(e=>e+1)},[]),h=L(e=>o(e),[o]),g={push:L(e=>u({screen:e.screen,context:e.context}),[u]),pop:d,popN:f,notify:p,setConfirm:h,refresh:m},{items:_,loading:v,error:y}=GL(l.screen,l.context?.marketplace,e,s,r.length),b=L(t=>{let n=l.screen,r=l.context;n===`main`?qL(t,g):n===`marketplace-list`?JL(t,g):n===`marketplace-action`?YL(t,r?.marketplace??``,e,g):n===`marketplace-browse`?XL(t,r?.marketplace??``,_,g):n===`marketplace-install-scope`?ZL(t,r?.pluginId??``,e,g):n===`installed-list`?QL(t,e,g):n===`installed-action`&&$L(t,r?.pluginId??``,e,g)},[l,_,e,u,d,f,p,o,m]),x=L(t=>{l.screen===`marketplace-add`&&e.marketplaceAdd(t).then(e=>{p(`Added marketplace "${e}" from ${t}.`),d()}).catch(e=>{p(`Error: ${e instanceof Error?e.message:String(e)}`),d()})},[l.screen,e,p,d]);if(a)return B(WL,{message:a.message,onSelect:e=>{e===0?a.onConfirm():a.onCancel()}});let S=l.screen;return S===`marketplace-add`?B(jL,{title:`Add Marketplace Source`,placeholder:`owner/repo or git URL`,onSubmit:x,onCancel:d,validate:e=>e.includes(`/`)?void 0:`Must be owner/repo or a git URL`}):S===`marketplace-action`?B(KL,{title:`Marketplace: ${l.context?.marketplace??``}`,items:[{label:`Browse plugins`,value:`browse`},{label:`Update`,value:`update`},{label:`Remove`,value:`remove`}],onSelect:b,onBack:d},r.length):S===`marketplace-install-scope`?B(KL,{title:`Install scope for "${l.context?.pluginId??``}"`,items:[{label:`User scope`,value:`user`},{label:`Project scope`,value:`project`}],onSelect:b,onBack:d},r.length):S===`installed-action`?B(KL,{title:`Plugin: ${l.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:b,onBack:d},r.length):B(KL,{title:{main:`Plugin Management`,"marketplace-list":`Marketplace`,"marketplace-browse":`Browse: ${l.context?.marketplace??``}`,"installed-list":`Installed Plugins`}[S]??`Plugin Management`,items:{main:[{label:`Marketplace`,value:`marketplace`},{label:`Installed Plugins`,value:`installed`}]}[S]??_,onSelect:b,onBack:d,loading:v,error:y},`${S}-${r.length}-${s}`)}function tR({sessions:e,onSelect:t,onCancel:n}){return V(P,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[B(F,{bold:!0,color:`cyan`,children:`Select a session to resume:`}),B(TL,{items:[...e],renderItem:(e,t)=>{let n=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return V(F,{children:[t?`> `:` `,B(F,{bold:!0,children:e.name??e.id.slice(0,8)}),` `,B(F,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,V(F,{dimColor:!0,children:[`msgs: `,e.messageCount]}),n?V(Je,{children:[`
318
- `,B(F,{color:`gray`,children:n})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function nR(e){let t=rR(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function rR(e){return e.activeToolCount>0?{kind:`tools`,label:`Tools (${e.activeToolCount})`,color:`cyan`}:e.isThinking?{kind:`thinking`,label:`Thinking`,color:`yellow`}:e.activeBackgroundTaskCount>0?{kind:`background`,label:`Background (${e.activeBackgroundTaskCount})`,color:`cyan`}:e.hasPendingPrompt?{kind:`queued`,label:`Queued`,color:`yellow`}:{kind:`idle`,label:`Idle`,color:`gray`}}function iR(e){return e>=90?`red`:e>=70?`yellow`:`green`}function aR({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=nR({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return B(F,{color:i.color,bold:i.kind!==`idle`,children:i.text})}function oR({percentage:e,usedTokens:t,maxTokens:n}){return V(F,{color:iR(e),children:[`Context: `,Math.round(e),`% (`,Zn(t),`/`,Zn(n),` tokens)`]})}function sR({permissionMode:e}){return V(Je,{children:[B(F,{color:`cyan`,bold:!0,children:`Mode:`}),` `,B(F,{children:e})]})}function cR(e){return e!=="default"}function lR({activePresetId:e}){return V(Je,{children:[B(F,{color:`cyan`,bold:!0,children:`Preset:`}),` `,B(F,{children:e})]})}function uR(e){return e!==void 0&&e!=="default"}function dR({modelName:e,providerDisplayName:t}){return t===void 0?B(F,{dimColor:!0,children:e}):V(F,{dimColor:!0,children:[t,` `,e]})}function fR(e){let t=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,n=cR(e.permissionMode),r=e.activePresetId,i=uR(r);return V(F,{children:[B(aR,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),n&&V(Je,{children:[` | `,B(sR,{permissionMode:e.permissionMode})]}),i&&V(Je,{children:[` | `,B(lR,{activePresetId:r})]}),e.sessionName&&V(Je,{children:[` | `,B(F,{color:`magenta`,children:e.sessionName})]}),t&&V(Je,{children:[` | `,V(F,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),` | `,B(dR,{modelName:e.modelName,providerDisplayName:e.providerDisplayName}),` | `,B(oR,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})}function pR({permissionMode:e,modelName:t,providerDisplayName:n,sessionId:r,isThinking:i,activeToolCount:a=0,activeBackgroundTaskCount:o=0,hasPendingPrompt:s=!1,contextPercentage:c,contextUsedTokens:l,contextMaxTokens:u,sessionName:d,gitBranch:f,showGitBranch:p=!0,activeAgentLabel:m,activePresetId:h}){return V(P,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[B(fR,{permissionMode:e,modelName:t,providerDisplayName:n,isThinking:i,activeToolCount:a,activeBackgroundTaskCount:o,hasPendingPrompt:s,contextPercentage:c,contextUsedTokens:l,contextMaxTokens:u,sessionName:d,gitBranch:f,showGitBranch:p,activePresetId:h}),m!==void 0&&V(F,{color:`yellow`,bold:!0,children:[`[`,m,`]`]})]})}function mR({cwd:e,permissionMode:t,modelId:n,providerType:r,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextState:l,sessionName:u,settings:d,activeAgentLabel:f,activePresetId:p,gitRefreshToken:m}){let h=NF(),g=Ke(()=>h.getGitBranch(e),[h,e,m]),_=Ke(()=>r===void 0?void 0:h.getProviderDisplayName(r),[h,r]);return d.enabled?B(pR,{permissionMode:t,modelName:n??``,providerDisplayName:_,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l.percentage,contextUsedTokens:l.usedTokens,contextMaxTokens:l.maxTokens,sessionName:u,gitBranch:g,showGitBranch:d.gitBranch,activeAgentLabel:f,activePresetId:p}):null}function hR(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function gR(e){let t=KP(e),{color:n,symbol:r}=GP[t];return{color:n,icon:r,strikethrough:t===`error`||t===`denied`}}function _R(e){return e?B(P,{marginBottom:1,children:B(F,{color:`yellow`,children:`Thinking...`})}):B(Je,{})}function vR(e){return V(P,{flexDirection:`column`,marginBottom:1,children:[B(F,{color:`white`,bold:!0,children:`Tools:`}),B(F,{children:` `}),e.map((e,t)=>{let{color:n,icon:r,strikethrough:i}=gR(e);return V(P,{flexDirection:`column`,children:[V(F,{color:n,strikethrough:i,children:[` `,r,` `,YI(e.toolName),`(`,e.firstArg,`)`]}),e.diffLines&&e.diffLines.length>0&&B(fL,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${t}`)})]})}function yR({text:e,activeTools:t,isThinking:n=!1}){let r=t.length>0,i=e.length>0;return!r&&!i?_R(n):V(P,{flexDirection:`column`,children:[r&&vR(t),i&&V(P,{flexDirection:`column`,marginBottom:1,children:[B(F,{color:`cyan`,bold:!0,children:`Robota:`}),B(F,{children:` `}),B(P,{marginLeft:2,children:B(F,{wrap:`wrap`,children:oL(e)})})]})]})}function bR({entry:e,selected:t}){let n=e.config.enabled,r=n?`●`:`○`,i=n?`[enabled] `:`[disabled]`,a=e.config.options?.port,o=typeof a==`number`?`port: ${a}`:``;return B(P,{children:B(F,{color:t?`cyan`:void 0,bold:t,children:`${r} ${e.transport.name.padEnd(18)} ${i} ${o}`})})}function xR(e,t,n,r,i,a,o,s){I(L((c,l)=>{if(!n){if(l.upArrow){i(e=>Math.max(0,e-1));return}if(l.downArrow){i(t=>Math.min(e.length-1,t+1));return}if(l.escape||l.return){o();return}if(c===` `){let n=e[t];if(!n)return;a(!0),r.setEnabled(n.transport.name,!n.config.enabled).then(()=>{s(),a(!1)}).catch(()=>a(!1))}}},[n,e,t,r,o,s,i,a]))}function SR({registry:e,onClose:t}){let[n,r]=z(()=>e.getAll()),[i,a]=z(0),[o,s]=z(!1);return xR(n,i,o,e,a,s,t,L(()=>{r(e.getAll())},[e])),V(P,{flexDirection:`column`,paddingX:2,paddingY:1,children:[B(F,{bold:!0,children:`Settings › Transports`}),B(P,{marginTop:1,flexDirection:`column`,children:n.map((e,t)=>B(bR,{entry:e,selected:t===i},e.transport.name))}),B(P,{marginTop:1,children:B(F,{dimColor:!0,children:`↑↓ select space toggle enter/esc close`})}),o&&B(P,{marginTop:1,children:B(F,{color:`yellow`,children:`Saving…`})})]})}function CR({message:e}){return B(P,{paddingX:1,marginBottom:1,children:B(F,{color:`yellow`,children:e})})}function wR(e){let[t,n]=z(()=>({channel:e.createChannel(e.resumeSessionId),sessionId:e.resumeSessionId})),[r,i]=z(e.showSessionPickerOnStart??!1);return B(MF,{value:e.cliAdapter,children:B(TR,{...e,channel:t.channel,showSessionPickerOnStart:r,resumeSessionId:t.sessionId,onSessionSwitch:r=>{i(!1),t.channel.stop(),n({channel:e.createChannel(r),sessionId:r})}},t.sessionId??`__new__`)})}function TR(e){let t=e.cwd,{channel:n}=e,r=RF(n.terminalHandoffController),{interactiveSession:i,registry:a,commandEffectQueue:o,history:s,addEntry:c,streamingText:l,activeTools:u,isThinking:d,lastErrorMessage:f,isStalled:p,isAborting:m,isShuttingDown:h,pendingPrompt:g,executionWorkspaceSnapshot:_,selectedExecutionEntryId:v,selectExecutionWorkspaceEntry:y,readExecutionWorkspaceDetail:b,permissionRequest:x,pendingUserAction:S,contextState:C,handleSubmit:w,handleAbort:ee,handleCancelQueue:T,handleShutdown:E}=zF(n),[D,te]=z(n.sessionName),O=DF(t),ne=i?void 0:O,{exit:re}=ze(),[ie,ae]=z(),[oe,k]=z(!1),[se,ce]=z(null),[le,ue]=z(),[de,fe]=z(!1),[pe,me]=LF(),[he,ge]=z(0),[_e,ve]=z(null),A=Ke(()=>ZP(_),[_]),ye=_e!==null;R(()=>{ve(e=>e===null||A.length===0?null:Math.min(e,A.length-1))},[A.length]);let be=QP(_),j=Ke(()=>_?.entries.find(e=>e.id===v),[_,v]),{handleSubmit:M,showPluginTUI:xe,showSessionPicker:Se,showTransportTUI:Ce,setShowPluginTUI:we,setShowSessionPicker:Te,setShowTransportTUI:Ee}=PF({cwd:t,providerOverride:e.providerOverride,interactiveSession:i,commandEffectQueue:o,addEntry:c,baseHandleSubmit:w,setSessionName:te,setStatusLineSettings:me,showSessionPickerOnStart:e.showSessionPickerOnStart,openAgentSwitcher:()=>k(!0)});R(()=>(n.start(),()=>{n.stop()}),[n]);let De=!j||j.kind===`main_thread`||j.controls.includes(`send`),Oe=j&&j.kind!==`main_thread`?j.title:void 0,N=Ke(()=>_?.entries.find(e=>e.kind===`main_thread`)?.id,[_]),ke=L(async e=>{j&&j.kind!==`main_thread`&&j.controls.includes(`send`)?await i.sendAgentJob(j.sourceId,e):await M(e)},[j,M,i]),Ae=L(async e=>{ge(e=>e+1),await ke(e)},[ke]),je=qe(!1);R(()=>{je.current&&!d&&ge(e=>e+1),je.current=d},[d]),R(()=>{let e=i?.getName?.();e&&!D&&te(e)},[i,D]),R(()=>{let t=!0;return e.startupUpdateNotice?.then(e=>{t&&e!==void 0&&ae(e)}).catch(()=>{}),()=>{t=!1}},[e.startupUpdateNotice]),R(()=>{let e=D?`Robota — ${D}`:`Robota`;process.stdout.write(`\x1b]0;${e}\x07`)},[D]),I((e,t)=>{!t.escape||!d||x||S||xe||Ce||Se||oe||ee()}),I((e,t)=>{!t.ctrl||e!==`b`||x||S||xe||Se||h||k(e=>!e)}),I((e,t)=>{!t.escape||d||x||S||xe||Ce||Se||oe||j&&j.kind!==`main_thread`&&N!==void 0&&y(N)}),I((e,t)=>{if(_e===null)return;let n=A,r=TF(_e,n.length,t);if(r.type===`move`)ve(r.index);else if(r.type===`open`){let e=n[r.index];e&&y(e.id),ve(null)}else r.type===`exit`&&ve(null)},{isActive:ye&&!x&&!S&&!xe&&!Ce&&!Se&&!oe}),I((e,t)=>{!t.ctrl||e!==`c`||hR({isShuttingDown:h,graceful:()=>void E(`prompt_input_exit`).finally(()=>re())})}),R(()=>{let e=()=>{hR({isShuttingDown:h,graceful:()=>void E(`other`).finally(()=>re())})};return process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}},[E,re,h]),R(()=>{if(!j||j.kind===`main_thread`){ce(null),ue(void 0),fe(!1);return}let e=!0;return fe(!0),ue(void 0),b(j.id).then(t=>{e&&(ce(t),fe(!1))}).catch(t=>{e&&(ue(t.message),fe(!1))}),()=>{e=!1}},[_,b,j]);let Me=e.permissionMode??`default`,Ne=``,Pe;try{let e=i.getSession();Me=e.getPermissionMode(),Pe=e.getActivePresetId?.(),Ne=e.getSessionId()}catch{}return V(P,{flexDirection:`column`,children:[B(Le,{items:Ke(()=>[{kind:`banner`,version:e.version??`0.0.0`},...s.map(e=>({kind:`entry`,entry:e}))],[s,e.version]),children:e=>e.kind===`banner`?V(P,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[B(F,{color:`cyan`,bold:!0,children:`
317
+ `)??[];return n&&n.length>0?V(F,{flexDirection:`column`,marginBottom:1,children:[B(F,{children:V(I,{color:`white`,bold:!0,children:[`Tool:`,` `]})}),B(I,{children:` `}),n.map((e,t)=>V(F,{flexDirection:`column`,children:[V(I,{color:gL(e),children:[` `,_L(e)]}),B(sL,{tool:e}),e.diffLines&&e.diffLines.length>0&&B(fL,{file:e.diffFile,lines:e.diffLines})]},t))]}):V(F,{flexDirection:`column`,marginBottom:1,children:[B(F,{children:V(I,{color:`white`,bold:!0,children:[`Tool:`,` `]})}),B(I,{children:` `}),r.map((e,t)=>V(I,{color:`green`,children:[` `,e]},t))]})}function CL({entry:e}){let t=e.data,n=typeof t?.message==`string`?t.message:typeof t?.content==`string`?t.content:e.type;return V(F,{flexDirection:`column`,marginBottom:1,children:[B(F,{children:V(I,{color:`yellow`,bold:!0,children:[`System:`,` `]})}),B(I,{children:` `}),B(F,{marginLeft:2,children:B(I,{wrap:`wrap`,children:n})})]})}function wL({entry:e}){if(e.category===`chat`){let t=e.data;return B(xL,{message:t})}return e.type===`tool-summary`?B(SL,{entry:e}):e.type===`usage-summary`?B(pL,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?B(Je,{}):B(CL,{entry:e})}function TL({items:e,renderItem:t,onSelect:n,onCancel:r,maxVisible:i=3,footerHint:a=` ↑↓ Navigate Enter Select Esc Cancel`}){let[o,s]=z(()=>fF()),c=qe(o),l=R(t=>{let a=hF(c.current,t,{itemCount:e.length,maxVisible:i});if(c.current=a.state,s(a.state),a.effect.type===`cancel`)r();else if(a.effect.type===`select`){let t=e[a.effect.index];t!==void 0&&n(t)}},[e,i,r,n]);if(L((e,t)=>{let n=pF(t);n!==void 0&&l(n)}),e.length===0)return B(F,{});let u=gF(o,{itemCount:e.length,maxVisible:i});u!==o&&(c.current=u);let{selectedIndex:d,scrollOffset:f}=u,p=e.slice(f,f+i),m=f+i<e.length;return V(F,{flexDirection:`column`,children:[f>0&&V(I,{dimColor:!0,children:[` ↑ `,f,` more above`]}),p.map((e,n)=>B(F,{marginBottom:1,children:t(e,f+n===d)},f+n)),m&&V(I,{dimColor:!0,children:[` ↓ `,e.length-f-i,` more below`]}),a!==``&&B(I,{dimColor:!0,children:a})]})}function EL({title:e,description:t,options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o,onCancel:s}){let[c,l]=z(0),[u,d]=z(()=>new Set(a??[])),f=e=>{d(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.size<i&&n.add(e),n})};L((e,t)=>{if(t.upArrow)l(e=>e<=0?n.length-1:e-1);else if(t.downArrow)l(e=>e>=n.length-1?0:e+1);else if(e===` `){let e=n[c];e!==void 0&&f(e.value)}else t.return?u.size>=r&&o([...u]):t.escape&&s()});let p=u.size>=r;return V(F,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(I,{color:`yellow`,bold:!0,children:e}),t!==void 0&&t.length>0&&B(I,{dimColor:!0,children:t}),n.map((e,t)=>{let n=t===c,r=u.has(e.value);return V(I,{color:n?`cyan`:void 0,children:[n?`> `:` `,r?`[x] `:`[ ] `,e.label]},e.value)}),V(I,{dimColor:!0,children:[` ↑↓ Navigate Space Toggle Enter Confirm`,p?``:` (min ${r})`,` Esc Cancel`]})]})}function DL(){return{value:``,resolved:!1}}function OL(e,t){if(t.escape===!0)return{type:`cancel`};if(t.return===!0)return{type:`submit`};if(t.backspace===!0||t.delete===!0)return{type:`delete`};if(e&&t.ctrl!==!0&&t.meta!==!0)return{type:`insert`,value:e}}function kL(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:t.type===`cancel`?{state:{...e,resolved:!0},effect:{type:`cancel`}}:t.type===`delete`?{state:{...e,value:e.value.slice(0,-1),error:void 0},effect:{type:`none`}}:t.type===`insert`?{state:{...e,value:e.value+t.value,error:void 0},effect:{type:`none`}}:AL(e,n)}function AL(e,t){let n=e.value.trim();if(!n&&!t.allowEmpty){let r=t.validate?.(n);return{state:r?{...e,error:r}:e,effect:{type:`none`}}}let r=t.validate?.(n);return r===void 0?{state:{...e,resolved:!0},effect:{type:`submit`,value:n}}:{state:{...e,error:r},effect:{type:`none`}}}function jL({title:e,description:t,placeholder:n,onSubmit:r,onCancel:i,validate:a,allowEmpty:o=!1,masked:s=!1}){let[c,l]=z(()=>DL()),u=qe(c),d=R(e=>{let t=kL(u.current,e,{allowEmpty:o,validate:a});u.current=t.state,l(t.state),t.effect.type===`cancel`?i():t.effect.type===`submit`&&r(t.effect.value)},[o,a,i,r]);return L((e,t)=>{let n=OL(e,t);n!==void 0&&d(n)}),V(F,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(I,{color:`yellow`,bold:!0,children:e}),B(ML,{description:t}),V(F,{marginTop:1,children:[B(I,{color:`cyan`,children:`> `}),c.value?B(I,{children:s?`*`.repeat(c.value.length):c.value}):n?B(I,{dimColor:!0,children:n}):null,B(I,{color:`cyan`,children:`█`})]}),c.error&&B(I,{color:`red`,children:c.error}),B(I,{dimColor:!0,children:` Enter Submit Esc Cancel`})]})}function ML({description:e}){return e===void 0||e.length===0?null:B(I,{dimColor:!0,children:e})}const NL={value:``,label:`Type a custom answer…`};function PL({request:e,onAnswer:t}){let[n,r]=z(!1),i=e.options??[],a=i.length>0,o=e.maxSelect??1,s=()=>t({type:`cancelled`});if(!a||n)return B(jL,{title:e.title,description:e.description,placeholder:e.placeholder,allowEmpty:e.allowEmpty,masked:e.masked,onSubmit:e=>t({type:`answer`,values:[],text:e}),onCancel:n?()=>r(!1):s},`text:${e.id}`);if(o>1)return B(EL,{title:e.title,description:e.description,options:i,minSelect:e.minSelect??1,maxSelect:o,defaultValues:e.default?.values,onConfirm:e=>t({type:`answer`,values:e}),onCancel:s});let c=e.allowFreeText?[...i,NL]:[...i];return V(F,{flexDirection:`column`,children:[B(I,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&B(I,{dimColor:!0,children:e.description}),B(TL,{items:c,maxVisible:e.maxVisible,renderItem:(e,t)=>V(I,{color:t?`cyan`:void 0,children:[t?`> `:` `,e.label]}),onSelect:e=>{e===NL?r(!0):t({type:`answer`,values:[e.value]})},onCancel:s})]})}const FL=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function IL(e,t){let n=mF({...t,escape:!1});if(n!==void 0)return n;if(e===`y`||e===`1`)return{type:`shortcut`,index:0};if(e===`s`||e===`a`||e===`2`)return{type:`shortcut`,index:1};if(e===`p`||e===`3`)return{type:`shortcut`,index:2};if(e===`n`||e===`d`||e===`4`)return{type:`shortcut`,index:3}}function LL(e,t){if(e.resolved)return{state:e,effect:{type:`none`}};if(typeof t!=`string`)return zL(e,t.index);let n=hF(e,t,{itemCount:FL.length});return n.effect.type===`select`?{state:n.state,effect:{type:`resolve`,decision:RL(n.effect.index)}}:{state:n.state,effect:{type:`none`}}}function RL(e){return e===0?!0:e===1?`allow-session`:e===2?`allow-project`:!1}function zL(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:RL(t)}}}function BL(e){let t=Object.entries(e);return t.length===0?`(no arguments)`:t.map(([e,t])=>`${e}: ${typeof t==`string`?t:JSON.stringify(t)}`).join(`, `)}function VL({request:e}){let[t,n]=He.useState(()=>fF()),r=He.useRef(t),i=He.useRef(e);if(i.current!==e){i.current=e;let t=fF();r.current=t,n(t)}let a=He.useCallback(t=>{let i=LL(r.current,t);r.current=i.state,n(i.state),i.effect.type===`resolve`&&e.resolve(i.effect.decision)},[e]);return L((e,t)=>{let n=IL(e,t);n!==void 0&&a(n)}),V(F,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(I,{color:`yellow`,bold:!0,children:`[Permission Required]`}),V(I,{children:[`Tool:`,` `,B(I,{color:`cyan`,bold:!0,children:e.toolName})]}),V(I,{dimColor:!0,children:[` `,BL(e.toolArgs)]}),B(F,{marginTop:1,children:FL.map((e,n)=>B(F,{marginRight:2,children:V(I,{color:n===t.selectedIndex?`cyan`:void 0,bold:n===t.selectedIndex,children:[n===t.selectedIndex?`> `:` `,e]})},e))}),B(I,{dimColor:!0,children:` left/right to select, Enter to confirm`})]})}function HL(e,t,n){let r=mF({...t,escape:!1});if(r!==void 0)return r;if(n===2&&e===`y`)return{type:`shortcut`,index:0};if(n===2&&e===`n`)return{type:`shortcut`,index:1}}function UL(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?hF(e,t,{itemCount:n}):{state:{...e,selectedIndex:t.index,resolved:!0},effect:{type:`select`,index:t.index}}}function WL({message:e,options:t=[`Yes`,`No`],onSelect:n}){let[r,i]=z(()=>fF()),a=qe(r),o=R(e=>{let r=UL(a.current,e,t.length);a.current=r.state,i(r.state),r.effect.type===`select`&&n(r.effect.index)},[n,t.length]);return L((e,n)=>{let r=HL(e,n,t.length);r!==void 0&&o(r)}),V(F,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(I,{color:`yellow`,children:e}),B(F,{marginTop:1,children:t.map((e,t)=>B(F,{marginRight:2,children:V(I,{color:t===r.selectedIndex?`cyan`:void 0,bold:t===r.selectedIndex,children:[t===r.selectedIndex?`> `:` `,e]})},e))}),B(I,{dimColor:!0,children:` arrow keys to select, Enter to confirm`})]})}function GL(e,t,n,r,i){let[a,o]=z([]),[s,c]=z(!1),[l,u]=z();return Ge(()=>{if(o([]),u(void 0),e===`marketplace-list`)c(!0),n.marketplaceList().then(e=>{let t=[{label:`Add Marketplace`,value:`__add__`}],n=e.map(e=>({label:e.name,value:e.name,hint:e.type}));o([...t,...n]),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)});else if(e===`marketplace-browse`){let e=t??``;c(!0),n.listAvailablePlugins(e).then(e=>{o(e.map(e=>({label:e.name,value:e.name,hint:e.installed?`installed`:e.description}))),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)})}else e===`installed-list`&&(c(!0),n.listInstalled().then(e=>{o(e.map(e=>({label:e.name,value:e.name,hint:e.description}))),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)}))},[i,e,t,n,r]),{items:a,loading:s,error:l}}function KL({title:e,items:t,onSelect:n,onBack:r,loading:i,error:a}){let[o,s]=z(()=>fF()),c=qe(o),l=!i&&!a,u=R(e=>{let i=hF(c.current,e,{itemCount:t.length,enabled:l});if(c.current=i.state,s(i.state),i.effect.type===`cancel`)r();else if(i.effect.type===`select`){let e=t[i.effect.index];e!==void 0&&n(e.value)}},[l,t,r,n]);L((e,t)=>{let n=pF(t);n!==void 0&&u(n)});let d=gF(o,{itemCount:t.length});d!==o&&(c.current=d);let f=d.selectedIndex;return V(F,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[B(I,{color:`yellow`,bold:!0,children:e}),i&&B(F,{marginTop:1,children:B(I,{dimColor:!0,children:`Loading...`})}),a&&V(F,{marginTop:1,flexDirection:`column`,children:[B(I,{color:`red`,children:a}),B(I,{dimColor:!0,children:`Press Esc to go back`})]}),!i&&!a&&B(F,{flexDirection:`column`,marginTop:1,children:t.map((e,t)=>V(F,{children:[V(I,{color:t===f?`cyan`:void 0,bold:t===f,children:[t===f?`> `:` `,e.label]}),e.hint&&V(I,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),B(I,{dimColor:!0,children:i||a?``:` ↑↓ Navigate Enter Select Esc Back`})]})}function qL(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function JL(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function YL(e,t,n,r){e===`browse`?r.push({screen:`marketplace-browse`,context:{marketplace:t}}):e===`update`?n.marketplaceUpdate(t).then(()=>{r.notify(`Updated marketplace "${t}".`),r.pop()}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)}):e===`remove`&&r.setConfirm({message:`Remove marketplace "${t}" and all its plugins?`,onConfirm:()=>{r.setConfirm(void 0),n.marketplaceRemove(t).then(()=>{r.notify(`Removed marketplace "${t}".`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>r.setConfirm(void 0)})}function XL(e,t,n,r){let i=`${e}@${t}`;n.find(t=>t.value===e)?.hint===`installed`?r.push({screen:`installed-action`,context:{pluginId:i}}):r.push({screen:`marketplace-install-scope`,context:{marketplace:t,pluginId:i}})}function ZL(e,t,n,r){let i=e;n.install(t,i).then(()=>{r.notify(`Installed plugin "${t}" (${i} scope).`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})}function QL(e,t,n){n.setConfirm({message:`Uninstall plugin "${e}"?`,onConfirm:()=>{n.setConfirm(void 0),t.uninstall(e).then(()=>{n.notify(`Uninstalled plugin "${e}".`),n.refresh()}).catch(e=>{n.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>n.setConfirm(void 0)})}function $L(e,t,n,r){e===`uninstall`&&r.setConfirm({message:`Uninstall plugin "${t}"?`,onConfirm:()=>{r.setConfirm(void 0),n.uninstall(t).then(()=>{r.notify(`Uninstalled plugin "${t}".`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>r.setConfirm(void 0)})}function eR({callbacks:e,onClose:t,addMessage:n}){let[r,i]=z([{screen:`main`}]),[a,o]=z(),[s,c]=z(0),l=r[r.length-1]??{screen:`main`},u=R(e=>{i(t=>[...t,e])},[]),d=R(()=>{i(e=>e.length<=1?(t(),e):e.slice(0,-1))},[t]),f=R(e=>{i(n=>{let r=n.slice(0,Math.max(1,n.length-e));return r.length===0?(t(),n):r})},[t]),p=R(e=>{n?.({role:`system`,content:e})},[n]),m=R(()=>{c(e=>e+1)},[]),h=R(e=>o(e),[o]),g={push:R(e=>u({screen:e.screen,context:e.context}),[u]),pop:d,popN:f,notify:p,setConfirm:h,refresh:m},{items:_,loading:v,error:y}=GL(l.screen,l.context?.marketplace,e,s,r.length),b=R(t=>{let n=l.screen,r=l.context;n===`main`?qL(t,g):n===`marketplace-list`?JL(t,g):n===`marketplace-action`?YL(t,r?.marketplace??``,e,g):n===`marketplace-browse`?XL(t,r?.marketplace??``,_,g):n===`marketplace-install-scope`?ZL(t,r?.pluginId??``,e,g):n===`installed-list`?QL(t,e,g):n===`installed-action`&&$L(t,r?.pluginId??``,e,g)},[l,_,e,u,d,f,p,o,m]),x=R(t=>{l.screen===`marketplace-add`&&e.marketplaceAdd(t).then(e=>{p(`Added marketplace "${e}" from ${t}.`),d()}).catch(e=>{p(`Error: ${e instanceof Error?e.message:String(e)}`),d()})},[l.screen,e,p,d]);if(a)return B(WL,{message:a.message,onSelect:e=>{e===0?a.onConfirm():a.onCancel()}});let S=l.screen;return S===`marketplace-add`?B(jL,{title:`Add Marketplace Source`,placeholder:`owner/repo or git URL`,onSubmit:x,onCancel:d,validate:e=>e.includes(`/`)?void 0:`Must be owner/repo or a git URL`}):S===`marketplace-action`?B(KL,{title:`Marketplace: ${l.context?.marketplace??``}`,items:[{label:`Browse plugins`,value:`browse`},{label:`Update`,value:`update`},{label:`Remove`,value:`remove`}],onSelect:b,onBack:d},r.length):S===`marketplace-install-scope`?B(KL,{title:`Install scope for "${l.context?.pluginId??``}"`,items:[{label:`User scope`,value:`user`},{label:`Project scope`,value:`project`}],onSelect:b,onBack:d},r.length):S===`installed-action`?B(KL,{title:`Plugin: ${l.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:b,onBack:d},r.length):B(KL,{title:{main:`Plugin Management`,"marketplace-list":`Marketplace`,"marketplace-browse":`Browse: ${l.context?.marketplace??``}`,"installed-list":`Installed Plugins`}[S]??`Plugin Management`,items:{main:[{label:`Marketplace`,value:`marketplace`},{label:`Installed Plugins`,value:`installed`}]}[S]??_,onSelect:b,onBack:d,loading:v,error:y},`${S}-${r.length}-${s}`)}function tR({sessions:e,onSelect:t,onCancel:n}){return V(F,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[B(I,{bold:!0,color:`cyan`,children:`Select a session to resume:`}),B(TL,{items:[...e],renderItem:(e,t)=>{let n=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return V(I,{children:[t?`> `:` `,B(I,{bold:!0,children:e.name??e.id.slice(0,8)}),` `,B(I,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,V(I,{dimColor:!0,children:[`msgs: `,e.messageCount]}),n?V(Je,{children:[`
318
+ `,B(I,{color:`gray`,children:n})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function nR(e){let t=rR(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function rR(e){return e.activeToolCount>0?{kind:`tools`,label:`Tools (${e.activeToolCount})`,color:`cyan`}:e.isThinking?{kind:`thinking`,label:`Thinking`,color:`yellow`}:e.activeBackgroundTaskCount>0?{kind:`background`,label:`Background (${e.activeBackgroundTaskCount})`,color:`cyan`}:e.hasPendingPrompt?{kind:`queued`,label:`Queued`,color:`yellow`}:{kind:`idle`,label:`Idle`,color:`gray`}}function iR(e){return e>=90?`red`:e>=70?`yellow`:`green`}function aR({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=nR({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return B(I,{color:i.color,bold:i.kind!==`idle`,children:i.text})}function oR({percentage:e,usedTokens:t,maxTokens:n}){return V(I,{color:iR(e),children:[`Context: `,Math.round(e),`% (`,Zn(t),`/`,Zn(n),` tokens)`]})}function sR({permissionMode:e}){return V(Je,{children:[B(I,{color:`cyan`,bold:!0,children:`Mode:`}),` `,B(I,{children:e})]})}function cR(e){return e!=="default"}function lR({activePresetId:e}){return V(Je,{children:[B(I,{color:`cyan`,bold:!0,children:`Preset:`}),` `,B(I,{children:e})]})}function uR(e){return e!==void 0&&e!=="default"}function dR({modelName:e,providerDisplayName:t}){return t===void 0?B(I,{dimColor:!0,children:e}):V(I,{dimColor:!0,children:[t,` `,e]})}function fR(e){let t=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,n=cR(e.permissionMode),r=e.activePresetId,i=uR(r);return V(I,{children:[B(aR,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),n&&V(Je,{children:[` | `,B(sR,{permissionMode:e.permissionMode})]}),i&&V(Je,{children:[` | `,B(lR,{activePresetId:r})]}),e.sessionName&&V(Je,{children:[` | `,B(I,{color:`magenta`,children:e.sessionName})]}),t&&V(Je,{children:[` | `,V(I,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),` | `,B(dR,{modelName:e.modelName,providerDisplayName:e.providerDisplayName}),` | `,B(oR,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})}function pR({permissionMode:e,modelName:t,providerDisplayName:n,sessionId:r,isThinking:i,activeToolCount:a=0,activeBackgroundTaskCount:o=0,hasPendingPrompt:s=!1,contextPercentage:c,contextUsedTokens:l,contextMaxTokens:u,sessionName:d,gitBranch:f,showGitBranch:p=!0,activeAgentLabel:m,activePresetId:h}){return V(F,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[B(fR,{permissionMode:e,modelName:t,providerDisplayName:n,isThinking:i,activeToolCount:a,activeBackgroundTaskCount:o,hasPendingPrompt:s,contextPercentage:c,contextUsedTokens:l,contextMaxTokens:u,sessionName:d,gitBranch:f,showGitBranch:p,activePresetId:h}),m!==void 0&&V(I,{color:`yellow`,bold:!0,children:[`[`,m,`]`]})]})}function mR({cwd:e,permissionMode:t,modelId:n,providerType:r,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextState:l,sessionName:u,settings:d,activeAgentLabel:f,activePresetId:p,gitRefreshToken:m}){let h=NF(),g=Ke(()=>h.getGitBranch(e),[h,e,m]),_=Ke(()=>r===void 0?void 0:h.getProviderDisplayName(r),[h,r]);return d.enabled?B(pR,{permissionMode:t,modelName:n??``,providerDisplayName:_,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l.percentage,contextUsedTokens:l.usedTokens,contextMaxTokens:l.maxTokens,sessionName:u,gitBranch:g,showGitBranch:d.gitBranch,activeAgentLabel:f,activePresetId:p}):null}function hR(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function gR(e){let t=KP(e),{color:n,symbol:r}=GP[t];return{color:n,icon:r,strikethrough:t===`error`||t===`denied`}}function _R(e){return e?B(F,{marginBottom:1,children:B(I,{color:`yellow`,children:`Thinking...`})}):B(Je,{})}function vR(e){return V(F,{flexDirection:`column`,marginBottom:1,children:[B(I,{color:`white`,bold:!0,children:`Tools:`}),B(I,{children:` `}),e.map((e,t)=>{let{color:n,icon:r,strikethrough:i}=gR(e);return V(F,{flexDirection:`column`,children:[V(I,{color:n,strikethrough:i,children:[` `,r,` `,YI(e.toolName),`(`,e.firstArg,`)`]}),e.diffLines&&e.diffLines.length>0&&B(fL,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${t}`)})]})}function yR({text:e,activeTools:t,isThinking:n=!1}){let r=t.length>0,i=e.length>0;return!r&&!i?_R(n):V(F,{flexDirection:`column`,children:[r&&vR(t),i&&V(F,{flexDirection:`column`,marginBottom:1,children:[B(I,{color:`cyan`,bold:!0,children:`Robota:`}),B(I,{children:` `}),B(F,{marginLeft:2,children:B(I,{wrap:`wrap`,children:oL(e)})})]})]})}function bR({entry:e,selected:t}){let n=e.config.enabled,r=n?`●`:`○`,i=n?`[enabled] `:`[disabled]`,a=e.config.options?.port,o=typeof a==`number`?`port: ${a}`:``;return B(F,{children:B(I,{color:t?`cyan`:void 0,bold:t,children:`${r} ${e.transport.name.padEnd(18)} ${i} ${o}`})})}function xR(e,t,n,r,i,a,o,s){L(R((c,l)=>{if(!n){if(l.upArrow){i(e=>Math.max(0,e-1));return}if(l.downArrow){i(t=>Math.min(e.length-1,t+1));return}if(l.escape||l.return){o();return}if(c===` `){let n=e[t];if(!n)return;a(!0),r.setEnabled(n.transport.name,!n.config.enabled).then(()=>{s(),a(!1)}).catch(()=>a(!1))}}},[n,e,t,r,o,s,i,a]))}function SR({registry:e,onClose:t}){let[n,r]=z(()=>e.getAll()),[i,a]=z(0),[o,s]=z(!1);return xR(n,i,o,e,a,s,t,R(()=>{r(e.getAll())},[e])),V(F,{flexDirection:`column`,paddingX:2,paddingY:1,children:[B(I,{bold:!0,children:`Settings › Transports`}),B(F,{marginTop:1,flexDirection:`column`,children:n.map((e,t)=>B(bR,{entry:e,selected:t===i},e.transport.name))}),B(F,{marginTop:1,children:B(I,{dimColor:!0,children:`↑↓ select space toggle enter/esc close`})}),o&&B(F,{marginTop:1,children:B(I,{color:`yellow`,children:`Saving…`})})]})}function CR({message:e}){return B(F,{paddingX:1,marginBottom:1,children:B(I,{color:`yellow`,children:e})})}function wR(e){let[t,n]=z(()=>({channel:e.createChannel(e.resumeSessionId),sessionId:e.resumeSessionId})),[r,i]=z(e.showSessionPickerOnStart??!1);return B(MF,{value:e.cliAdapter,children:B(TR,{...e,channel:t.channel,showSessionPickerOnStart:r,resumeSessionId:t.sessionId,onSessionSwitch:r=>{i(!1),t.channel.stop(),n({channel:e.createChannel(r),sessionId:r})}},t.sessionId??`__new__`)})}function TR(e){let t=e.cwd,{channel:n}=e,r=RF(n.terminalHandoffController),{interactiveSession:i,registry:a,commandEffectQueue:o,history:s,addEntry:c,streamingText:l,activeTools:u,isThinking:d,lastErrorMessage:f,isStalled:p,isAborting:m,isShuttingDown:h,pendingPrompt:g,executionWorkspaceSnapshot:_,selectedExecutionEntryId:v,selectExecutionWorkspaceEntry:y,readExecutionWorkspaceDetail:b,permissionRequest:x,pendingUserAction:S,contextState:C,handleSubmit:w,handleAbort:T,handleCancelQueue:E,handleShutdown:D}=zF(n),[O,k]=z(n.sessionName),A=DF(t),ee=i?void 0:A,{exit:te}=Re(),[ne,re]=z(),[ie,ae]=z(!1),[oe,se]=z(null),[ce,le]=z(),[ue,de]=z(!1),[fe,pe]=LF(),[me,he]=z(0),[ge,_e]=z(null),j=Ke(()=>ZP(_),[_]),ve=ge!==null;Ge(()=>{_e(e=>e===null||j.length===0?null:Math.min(e,j.length-1))},[j.length]);let ye=QP(_),M=Ke(()=>_?.entries.find(e=>e.id===v),[_,v]),{handleSubmit:N,showPluginTUI:be,showSessionPicker:xe,showTransportTUI:Se,setShowPluginTUI:Ce,setShowSessionPicker:we,setShowTransportTUI:Te}=PF({cwd:t,providerOverride:e.providerOverride,interactiveSession:i,commandEffectQueue:o,addEntry:c,baseHandleSubmit:w,setSessionName:k,setStatusLineSettings:pe,showSessionPickerOnStart:e.showSessionPickerOnStart,openAgentSwitcher:()=>ae(!0)});Ge(()=>(n.start(),()=>{n.stop()}),[n]);let Ee=!M||M.kind===`main_thread`||M.controls.includes(`send`),De=M&&M.kind!==`main_thread`?M.title:void 0,P=Ke(()=>_?.entries.find(e=>e.kind===`main_thread`)?.id,[_]),Oe=R(async e=>{M&&M.kind!==`main_thread`&&M.controls.includes(`send`)?await i.sendAgentJob(M.sourceId,e):await N(e)},[M,N,i]),ke=R(async e=>{he(e=>e+1),await Oe(e)},[Oe]),Ae=qe(!1);Ge(()=>{Ae.current&&!d&&he(e=>e+1),Ae.current=d},[d]),Ge(()=>{let e=i?.getName?.();e&&!O&&k(e)},[i,O]),Ge(()=>{let t=!0;return e.startupUpdateNotice?.then(e=>{t&&e!==void 0&&re(e)}).catch(()=>{}),()=>{t=!1}},[e.startupUpdateNotice]),Ge(()=>{let e=O?`Robota — ${O}`:`Robota`;process.stdout.write(`\x1b]0;${e}\x07`)},[O]),L((e,t)=>{!t.escape||!d||x||S||be||Se||xe||ie||T()}),L((e,t)=>{!t.ctrl||e!==`b`||x||S||be||xe||h||ae(e=>!e)}),L((e,t)=>{!t.escape||d||x||S||be||Se||xe||ie||M&&M.kind!==`main_thread`&&P!==void 0&&y(P)}),L((e,t)=>{if(ge===null)return;let n=j,r=TF(ge,n.length,t);if(r.type===`move`)_e(r.index);else if(r.type===`open`){let e=n[r.index];e&&y(e.id),_e(null)}else r.type===`exit`&&_e(null)},{isActive:ve&&!x&&!S&&!be&&!Se&&!xe&&!ie}),L((e,t)=>{!t.ctrl||e!==`c`||hR({isShuttingDown:h,graceful:()=>void D(`prompt_input_exit`).finally(()=>te())})}),Ge(()=>{let e=()=>{hR({isShuttingDown:h,graceful:()=>void D(`other`).finally(()=>te())})};return process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}},[D,te,h]),Ge(()=>{if(!M||M.kind===`main_thread`){se(null),le(void 0),de(!1);return}let e=!0;return de(!0),le(void 0),b(M.id).then(t=>{e&&(se(t),de(!1))}).catch(t=>{e&&(le(t.message),de(!1))}),()=>{e=!1}},[_,b,M]);let je=e.permissionMode??`default`,Me=``,Ne;try{let e=i.getSession();je=e.getPermissionMode(),Ne=e.getActivePresetId?.(),Me=e.getSessionId()}catch{}return V(F,{flexDirection:`column`,children:[B(Ie,{items:Ke(()=>[{kind:`banner`,version:e.version??`0.0.0`},...s.map(e=>({kind:`entry`,entry:e}))],[s,e.version]),children:e=>e.kind===`banner`?V(F,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[B(I,{color:`cyan`,bold:!0,children:`
319
319
  ____ ___ ____ ___ _____ _
320
320
  | _ \\ / _ \\| __ ) / _ \\_ _|/ \\
321
321
  | |_) | | | | _ \\| | | || | / _ \\
322
322
  | _ <| |_| | |_) | |_| || |/ ___ \\
323
323
  |_| \\_\\\\___/|____/ \\___/ |_/_/ \\_\\
324
- `}),V(F,{dimColor:!0,children:[` v`,e.version]})]},`logo`):B(wL,{entry:e.entry},e.entry.id)}),!r&&V(Je,{children:[ie&&B(CR,{message:ie}),V(P,{flexDirection:`column`,paddingX:1,flexGrow:1,children:[j&&j.kind!==`main_thread`&&B(uF,{entry:j,page:se,loading:de,error:le}),h&&B(P,{marginBottom:1,children:B(F,{color:`yellow`,children:`Shutting down...`})}),(d||u.length>0)&&V(P,{flexDirection:`column`,marginBottom:1,children:[B(yR,{text:l,activeTools:u,isThinking:d}),p&&B(F,{color:`yellow`,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!d&&f&&B(P,{marginBottom:1,children:B(F,{color:`red`,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`})}),B(cF,{entries:A,focusedIndex:_e})]}),oe&&B(bF,{snapshot:_,selectedEntryId:v,onSelect:y,onClose:()=>k(!1)}),x&&B(VL,{request:x}),S&&B(PL,{request:S,onAnswer:e=>n.resolveUserAction(e)}),xe&&B(eR,{callbacks:ne,onClose:()=>we(!1),addMessage:e=>c(H(q(e.content)))}),Ce&&e.transportRegistry&&B(SR,{registry:e.transportRegistry,onClose:()=>Ee(!1)}),Se&&B(tR,{sessions:Py(e.sessionStore,e.cwd),onSelect:t=>{Te(!1),e.onSessionSwitch(t)},onCancel:()=>{Te(!1),c(H(q(`Session resume cancelled.`)))}}),B(lF,{percentage:C.percentage}),B(FI,{onSubmit:Ae,onCancelQueue:T,isDisabled:!!x||!!S||xe||Ce||Se||oe||h||d&&!!g||!De||ye,isAborting:m,pendingPrompt:g,registry:a,sessionName:D,history:s,onRequestFocusBackgroundList:()=>{A.length>0&&ve(0)}}),B(mR,{cwd:t,permissionMode:Me,modelId:e.modelId,providerType:e.providerType,sessionId:Ne,isThinking:d,activeToolCount:u.length,activeBackgroundTaskCount:be,hasPendingPrompt:g!==null,contextState:C,sessionName:D,settings:pe,activeAgentLabel:Oe,activePresetId:Pe,gitRefreshToken:he})]})]})}var ER=class{hooks;instance;registerSuspendHooks(e){return this.hooks=e,()=>{this.hooks===e&&(this.hooks=void 0)}}setInkInstance(e){this.instance=e}get canHandoffTerminal(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&this.hooks!==void 0}async runWithTerminal(e){let t=this.hooks;if(!this.canHandoffTerminal||t===void 0)throw Error(`TUI terminal handoff unavailable: no interactive TTY, or the App is not mounted.`);await t.suspend(),this.instance?.clear();let n=process.stdin;n.isTTY&&typeof n.setRawMode==`function`&&n.setRawMode(!1),n.pause();try{return await e()}finally{t.resume()}}};function DR(e){return/not initialized/i.test(e.message)}function OR(e){let t=e.isBenignError??DR,n=null,r=0,i;function a(){n!==null&&(clearInterval(n),n=null)}function o(){r+=e.intervalMs;try{e.check()}catch(n){let o=n instanceof Error?n:Error(String(n));if(!t(o)){a(),e.onFailure({kind:`error`,error:o});return}i=o,r>=e.timeoutMs&&(a(),e.onFailure({kind:`timeout`,lastError:i}));return}a(),e.onReady()}return{start(){n===null&&(r=0,n=setInterval(o,e.intervalMs))},stop:a}}var kR=class{queue=[];enqueueEffects(e){e.length!==0&&this.queue.push({effects:[...e]})}drain(){return this.queue.shift()}clear(){this.queue.length=0}};function AR(e,t,n,r,i,a){let o=jR(e.effects,n,r,a);if(r.addEntry(H(q(e.message))),o.length>0&&i.enqueueEffects(o),t.isInitialized){let e=t.getContextState();r.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})}}function jR(e,t,n,r){if(e===void 0||e.length===0)return[];let i=[];for(let a of e){if(a.type===`conversation-history-cleared`){n.clearHistory();continue}if(a.type===`plugin-registry-reload-requested`){r?.(t);continue}i.push(a)}return i}function MR(e,t){let n=null;return{schedule(){n||=setTimeout(()=>{n=null,e()},t)},flush(){n&&=(clearTimeout(n),null)}}}var NR=class{history=[];streamingText=``;activeTools=[];isThinking=!1;isAborting=!1;pendingPrompt=null;contextState={percentage:0,usedTokens:0,maxTokens:0};executionWorkspaceSnapshot=null;selectedExecutionEntryId;lastErrorMessage=null;isStalled=!1;onChange=null;streamBuf=``;debouncedStreamNotify=MR(()=>this.notify(),300);stallTimer=null;armStallTimer(){this.clearStallTimer(),this.stallTimer=setTimeout(()=>{this.stallTimer=null,this.isStalled=!0,this.notify()},15e3)}clearStallTimer(){this.stallTimer&&=(clearTimeout(this.stallTimer),null),this.isStalled&&=!1}notify(){this.onChange?.()}onTextDelta=e=>{this.isThinking&&this.armStallTimer(),this.streamBuf+=e,this.streamingText=this.streamBuf,this.debouncedStreamNotify.schedule()};onToolStart=e=>{this.clearStallTimer(),this.activeTools=[...this.activeTools,e],this.notify()};onToolEnd=e=>{let t=this.activeTools.findLastIndex(t=>t.toolName===e.toolName&&t.isRunning);if(t!==-1){let n=[...this.activeTools];n[t]=e,this.activeTools=n}this.isThinking&&!this.activeTools.some(e=>e.isRunning)&&this.armStallTimer(),this.notify()};onThinking=e=>{this.isThinking=e,e?(this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.lastErrorMessage=null,this.armStallTimer()):(this.isAborting=!1,this.activeTools=[],this.clearStallTimer()),this.notify()};onComplete=e=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.contextState={percentage:e.contextState.usedPercentage,usedTokens:e.contextState.usedTokens,maxTokens:e.contextState.maxTokens},this.notify()};onInterrupted=()=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onError=e=>{this.clearStallTimer(),this.lastErrorMessage=e?.message??`Unknown error`,this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onContextUpdate=e=>{this.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})};syncHistory(e){e.length!==0&&(this.history=[...e],this.notify())}addEntry(e){this.history=[...this.history,e],this.notify()}clearHistory(){this.history=[],this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()}setPendingPrompt(e){this.pendingPrompt=e,this.notify()}setAborting(e){this.isAborting=e,this.notify()}setContextState(e){this.contextState=e,this.notify()}syncExecutionWorkspaceSnapshot(e){let t=this.selectedExecutionEntryId,n=t!==void 0&&e.entries.some(e=>e.id===t)?t:e.selectedEntryId??e.entries[0]?.id;this.executionWorkspaceSnapshot={...e,...n?{selectedEntryId:n}:{}},this.selectedExecutionEntryId=n,this.notify()}selectExecutionWorkspaceEntry(e){this.executionWorkspaceSnapshot?.entries.some(t=>t.id===e)&&(this.selectedExecutionEntryId=e,this.executionWorkspaceSnapshot={...this.executionWorkspaceSnapshot,selectedEntryId:e},this.notify())}dispose(){this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.onChange=null}};const PR=15e3,FR=5e3;var IR=class{stateManager;interactiveSession;registry;commandEffectQueue;opts;submitHandler=null;userActionQueue=[];processingUserAction=!1;permissionRequest=null;pendingUserAction=null;availableCommands=[];isShuttingDown=!1;sessionName;autoNameTriggered=!1;sessionStarted=!1;initPoller=null;get terminalHandoffController(){return this.opts.terminalHandoff}permissionQueue=[];processingPermission=!1;sessionEventBindings=[];stopped=!1;onChange=null;constructor(e){this.opts=e,this.sessionName=e.sessionName,this.stateManager=new NR,this.stateManager.onChange=()=>this.onChange?.(),this.interactiveSession=this.createSession(),this.registry=this.createRegistry(),this.commandEffectQueue=new kR}createSession(){let e=this.opts;return new jy({cwd:e.cwd,provider:e.provider,permissionMode:e.permissionMode,maxTurns:e.maxTurns,permissionHandler:(e,t)=>this.handlePermissionRequest(e,t),askHandler:e=>this.askUser(e),sessionStore:e.sessionStore,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,sessionName:e.sessionName,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,language:e.language,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,systemPrompt:e.systemPrompt,appendSystemPrompt:e.appendSystemPrompt,allowedTools:e.allowedTools,deniedTools:e.deniedTools,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,terminalHandoff:e.terminalHandoff})}createRegistry(){let e=new e_;for(let t of this.opts.commandModules??[])e.addModule(t);return this.opts.reloadPluginCommandSource?.(e),e}onSubmit(e){this.submitHandler=e}write(e){}setAvailableCommands(e){this.availableCommands=e,this.onChange?.()}setBusy(e){this.stateManager.onThinking(e)}async start(){this.sessionStarted||(this.sessionStarted=!0,this.wireSessionEvents(),this.syncRestoredHistory(),this.startInitCheck(),this.opts.transportRegistry&&await this.opts.transportRegistry.startAll(this.interactiveSession))}async stop(){this.stopped||(this.stopped=!0,this.sessionStarted=!1,this.unwireSessionEvents(),this.cancelAllPermissions(),this.cancelAllUserActions(),this.stopInitCheck(),this.onChange=null,this.stateManager.dispose(),this.opts.transportRegistry&&await this.opts.transportRegistry.stopAll(),this.isShuttingDown||await this.shutdownSessionBounded(`other`,`channel stopped`,FR))}getSession(){return this.interactiveSession}getRegistry(){return this.registry}getCommandEffectQueue(){return this.commandEffectQueue}abort(){this.stateManager.setAborting(!0),this.cancelAllUserActions(),this.cancelAllPermissions(),this.interactiveSession.abort()}cancelQueue(){this.interactiveSession.cancelQueue(),this.cancelAllUserActions(),this.cancelAllPermissions(),this.stateManager.setPendingPrompt(null)}async shutdown(e){this.isShuttingDown||(this.isShuttingDown=!0,this.cancelAllUserActions(),this.cancelAllPermissions(),this.stateManager.addEntry(H(q(`Shutting down...`))),this.onChange?.(),await this.shutdownSessionBounded(e?.reason??`prompt_input_exit`,`CLI shutdown`,e?.timeoutMs??FR))}async shutdownSessionBounded(e,t,n){let r,i=new Promise(e=>{r=setTimeout(e,n),r.unref?.()});await Promise.race([this.interactiveSession.shutdown({reason:e,message:t}).catch(()=>void 0),i]),r&&clearTimeout(r)}selectExecutionWorkspaceEntry(e){this.stateManager.selectExecutionWorkspaceEntry(e)}async readExecutionWorkspaceDetail(e){return this.interactiveSession.readExecutionWorkspaceDetail(e)}async sendAgentJob(e,t){await this.interactiveSession.sendAgentJob(e,t)}setSessionName(e){this.sessionName=e,this.interactiveSession.setName(e),this.onChange?.()}async askUser(e){return new Promise(t=>{this.userActionQueue.push({request:e,resolve:t}),this.processNextUserAction()})}resolveUserAction(e){let t=this.userActionQueue[0];t&&(this.userActionQueue.shift(),this.processingUserAction=!1,this.pendingUserAction=null,this.onChange?.(),t.resolve(e),this.processNextUserAction())}processNextUserAction(){if(this.processingUserAction)return;let e=this.userActionQueue[0];if(!e){this.pendingUserAction=null,this.onChange?.();return}this.processingUserAction=!0,this.pendingUserAction=e.request,this.onChange?.()}cancelAllUserActions(){let e=this.userActionQueue;this.userActionQueue=[],this.processingUserAction=!1,this.pendingUserAction=null;for(let t of e)t.resolve({type:`cancelled`});this.onChange?.()}async handleInput(e){if(!e.startsWith(`/`)){await this.interactiveSession.submit(e),this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}await this.handleSlashCommand(e)}async handleSlashCommand(e){let t=e.slice(1).split(/\s+/),n=t[0]?.toLowerCase()??``,r=t.slice(1).join(` `),i=await this.interactiveSession.executeCommand(n,r);if(i){if(i.effects?.some(e=>e.type===`session-execution-started`)){this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}AR(i,this.interactiveSession,this.registry,this.stateManager,this.commandEffectQueue,this.opts.reloadPluginCommandSource);return}this.stateManager.addEntry(H(q(`Unknown command "/${n}". Type /help for help.`)))}handlePermissionRequest(e,t){return new Promise(n=>{this.permissionQueue.push({toolName:e,toolArgs:t,resolve:n}),this.processNextPermission()})}processNextPermission(){if(this.processingPermission)return;let e=this.permissionQueue[0];if(!e){this.permissionRequest=null,this.onChange?.();return}this.processingPermission=!0,this.permissionRequest={toolName:e.toolName,toolArgs:e.toolArgs,resolve:t=>{this.permissionQueue.shift(),this.processingPermission=!1,this.permissionRequest=null,e.resolve(t),setTimeout(()=>this.processNextPermission(),0)}},this.onChange?.()}cancelAllPermissions(){let e=this.permissionQueue;this.permissionQueue=[],this.processingPermission=!1,this.permissionRequest=null;for(let t of e)t.resolve(!1);this.onChange?.()}wireSessionEvents(){let e=this.interactiveSession,t=this.stateManager;this.bindSession(`user_message`,e=>{this.handleAutoNaming(e),t.addEntry(H(ai(e)))}),this.bindSession(`text_delta`,t.onTextDelta),this.bindSession(`tool_start`,t.onToolStart),this.bindSession(`tool_end`,t.onToolEnd),this.bindSession(`thinking`,t.onThinking),this.bindSession(`complete`,n=>{t.onComplete(n),t.syncHistory(e.getFullHistory())}),this.bindSession(`interrupted`,t.onInterrupted),this.bindSession(`error`,n=>{t.onError(n),t.syncHistory(e.getFullHistory())}),this.bindSession(`context_update`,t.onContextUpdate),this.bindSession(`compact`,()=>{t.syncHistory(e.getFullHistory())}),this.bindSession(`skill_activation`,()=>{t.syncHistory(e.getFullHistory())}),this.bindSession(`memory_event`,()=>{t.syncHistory(e.getFullHistory())}),this.bindSession(`execution_workspace_event`,e=>{t.syncExecutionWorkspaceSnapshot(e.snapshot)})}bindSession(e,t){this.interactiveSession.on(e,t),this.sessionEventBindings.push({event:e,handler:t})}unwireSessionEvents(){for(let{event:e,handler:t}of this.sessionEventBindings)this.interactiveSession.off(e,t);this.sessionEventBindings=[]}handleAutoNaming(e){this.autoNameTriggered||this.opts.sessionName||this.interactiveSession.getName()||(this.autoNameTriggered=!0,Gy(this.opts.provider,e).then(e=>{this.interactiveSession.setName(e),this.sessionName=e,this.opts.onAutoNamed?.(e),this.onChange?.()}).catch(()=>{this.autoNameTriggered=!1}))}syncRestoredHistory(){if(this.stateManager.history.length===0){let e=this.interactiveSession.getFullHistory();e.length>0&&this.stateManager.syncHistory(e)}}startInitCheck(){this.initPoller=OR({check:()=>this.runInitCheck(),intervalMs:200,timeoutMs:PR,onReady:()=>void 0,onFailure:e=>this.onInitFailure(e)}),this.initPoller.start()}runInitCheck(){let e=this.interactiveSession.getContextState();this.stateManager.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens});let t=this.interactiveSession.getFullHistory();t.length>0&&this.stateManager.syncHistory(t),this.syncExecutionWorkspace()}onInitFailure(e){let t=e.kind===`timeout`?`Session initialization timed out after ${PR/1e3}s${e.lastError?` (last error: ${e.lastError.message})`:``}`:`Session initialization failed: ${e.error.message}`;this.stateManager.onError(),this.stateManager.addEntry({id:`session-init-error-${Date.now()}`,timestamp:new Date,category:`event`,type:`session-init-error`,data:{message:t}})}stopInitCheck(){this.initPoller?.stop(),this.initPoller=null}syncExecutionWorkspace(){try{this.stateManager.syncExecutionWorkspaceSnapshot(this.interactiveSession.getExecutionWorkspaceSnapshot({selectedEntryId:this.stateManager.selectedExecutionEntryId}))}catch{}}};function LR(e,t){return{cwd:e.cwd,provider:e.provider,permissionMode:e.permissionMode,maxTurns:e.maxTurns,allowedTools:e.allowedTools,deniedTools:e.deniedTools,sessionStore:e.sessionStore,resumeSessionId:t,forkSession:e.forkSession,sessionName:e.sessionName,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,transportRegistry:e.transportRegistry,language:e.language,reloadPluginCommandSource:e.reloadPluginCommandSource,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification}}async function RR(e){let t=new ER,n=Re(B(wR,{cwd:e.cwd,createChannel:n=>{let r=new IR({...LR(e,n),terminalHandoff:t});return e.onChannelReady?.(r),r},providerOverride:e.providerOverride,providerType:e.providerType,modelId:e.modelId,permissionMode:e.permissionMode,version:e.version,sessionStore:e.sessionStore,resumeSessionId:e.resumeSessionId,showSessionPickerOnStart:e.showSessionPickerOnStart,startupUpdateNotice:e.startupUpdateNotice,transportRegistry:e.transportRegistry,cliAdapter:e.cliAdapter}),{exitOnCtrlC:!1});t.setInkInstance(n),await n.waitUntilExit()}function zR({providerDefinitions:e,reloadPluginCommandSource:t}){return{getUserSettingsPath:()=>Wm(),readSettings:e=>Km(e),writeSettings:(e,t)=>qm(e,t),deleteSettings:e=>Jm(e),applyStatusLineSettings:(e,t)=>zv(e,t),reloadPluginCommandSource:e=>{t(e)},applyActiveModelChange:(e,t,n)=>(N_(e,t,n),{applied:!0}),getGitBranch:e=>Fb(e),getProviderDisplayName:t=>ut(e,t)?.displayName??t}}let BR=null,VR=!1;function HR(e){BR=e}function UR(e,t){try{if(BR){BR.getSession().reportBackgroundError(e,t);return}}catch{}process.stderr.write(`\n[robota] ${t}: ${e.message}\n`)}function WR(){VR||(VR=!0,process.on(`unhandledRejection`,e=>{UR(e instanceof Error?e:Error(String(e)),`unhandled rejection`)}),process.on(`uncaughtException`,e=>{UR(e instanceof Error?e:Error(String(e)),`uncaught exception`)}))}var GR=class{entries=new Map;settingsPath;constructor(e){this.settingsPath=e}register(e){this.entries.set(e.name,e)}getAll(){let e=this.readTransportSettings();return Array.from(this.entries.values()).map(t=>({transport:t,config:this.resolveConfig(t,e[t.name])}))}getEnabled(){return this.getAll().filter(e=>e.config.enabled).map(e=>e.transport)}async setEnabled(e,t){let n=Km(this.settingsPath),r=n.transports??{};r[e]={...r[e]??{},enabled:t},n.transports=r,qm(this.settingsPath,n)}async setOptions(e,t){let n=Km(this.settingsPath),r=n.transports??{};r[e]={...r[e]??{},options:t},n.transports=r,qm(this.settingsPath,n)}async startAll(e){let t=this.getEnabled();for(let n of t)n.attach(e),await n.start()}async stopAll(){let e=[];for(let t of this.entries.values())try{await t.stop()}catch(t){e.push(t instanceof Error?t:Error(String(t)))}return{errors:e}}resolveConfig(e,t){return{enabled:t?.enabled??e.defaultEnabled,options:t?.options??{}}}readTransportSettings(){let e=Km(this.settingsPath).transports;return!e||typeof e!=`object`||Array.isArray(e)?{}:e}};function KR(e,t,n){if(n.type===`get-background-tasks`){t({type:`background_tasks`,tasks:e.listBackgroundTasks(n.filter)});return}if(n.type===`get-background-task`){JR(e,t,n);return}if(n.type===`get-background-job-groups`){t({type:`background_job_groups`,groups:e.listBackgroundJobGroups()});return}if(n.type===`get-background-job-group`){XR(e,t,n);return}if(n.type===`wait-background-job-group`){ZR(e,t,n);return}YR(e,t,n)}function qR(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}if(n.type===`cancel-background-task`){$R(t,`cancel`,n.taskId,e.cancelBackgroundTask(n.taskId,n.reason));return}if(n.type===`close-background-task`){$R(t,`close`,n.taskId,e.closeBackgroundTask(n.taskId));return}QR(e,t,n)}function JR(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}t({type:`background_task`,taskId:n.taskId,task:e.getBackgroundTask(n.taskId)??null})}function YR(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}e.readBackgroundTaskLog(n.taskId,n.cursor).then(e=>t({type:`background_task_log`,taskId:n.taskId,page:e}),e=>t({type:`protocol_error`,message:e.message}))}function XR(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}t({type:`background_job_group`,groupId:n.groupId,group:e.getBackgroundJobGroup(n.groupId)??null})}function ZR(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}e.waitBackgroundJobGroup(n.groupId).then(e=>t({type:`background_job_group`,groupId:n.groupId,group:e}),e=>t({type:`protocol_error`,message:e.message}))}function QR(e,t,n){if(!n.input){t({type:`protocol_error`,message:`input is required`});return}$R(t,`send`,n.taskId,e.sendBackgroundTask(n.taskId,n.input))}function $R(e,t,n,r){r.then(()=>e({type:`background_task_control_result`,action:t,taskId:n,success:!0}),r=>e({type:`background_task_control_result`,action:t,taskId:n,success:!1,message:r.message}))}function ez(e){let t=tz(e.session,e.send);return{onMessage:nz(e.session,e.send),cleanup:t}}function tz(e,t){let n=e=>t({type:`user_message`,content:e}),r=e=>t({type:`text_delta`,delta:e}),i=e=>t({type:`tool_start`,state:e}),a=e=>t({type:`tool_end`,state:e}),o=e=>t({type:`thinking`,isThinking:e}),s=e=>t({type:`complete`,result:e}),c=e=>t({type:`interrupted`,result:e}),l=e=>t({type:`error`,message:e.message}),u=e=>t({type:`background_task_event`,event:e}),d=e=>t({type:`background_job_group_event`,event:e}),f=e=>t({type:`execution_workspace_event`,snapshot:e.snapshot});return e.on(`user_message`,n),e.on(`text_delta`,r),e.on(`tool_start`,i),e.on(`tool_end`,a),e.on(`thinking`,o),e.on(`complete`,s),e.on(`interrupted`,c),e.on(`error`,l),e.on(`background_task_event`,u),e.on(`background_job_group_event`,d),e.on(`execution_workspace_event`,f),()=>{e.off(`user_message`,n),e.off(`text_delta`,r),e.off(`tool_start`,i),e.off(`tool_end`,a),e.off(`thinking`,o),e.off(`complete`,s),e.off(`interrupted`,c),e.off(`error`,l),e.off(`background_task_event`,u),e.off(`background_job_group_event`,d),e.off(`execution_workspace_event`,f)}}function nz(e,t){return n=>{let r=rz(n,t);r&&iz(e,t,r)}}function rz(e,t){try{return JSON.parse(e)}catch{return t({type:`protocol_error`,message:`Invalid JSON`}),null}}function iz(e,t,n){if(oz(n)){uz(e,t,n);return}if(sz(n)){dz(e,t,n);return}if(cz(n)){KR(e,t,n);return}if(lz(n)){qR(e,t,n);return}t({type:`protocol_error`,message:`Unknown message type: ${az(n)}`})}function az(e){return e.type}function oz(e){return e.type===`submit`||e.type===`command`||e.type===`abort`||e.type===`cancel-queue`}function sz(e){return e.type===`get-messages`||e.type===`get-context`||e.type===`get-executing`||e.type===`get-pending`||e.type===`get-execution-workspace`}function cz(e){return e.type===`get-background-tasks`||e.type===`get-background-task`||e.type===`read-background-task-log`||e.type===`get-background-job-groups`||e.type===`get-background-job-group`||e.type===`wait-background-job-group`}function lz(e){return e.type===`cancel-background-task`||e.type===`close-background-task`||e.type===`send-background-task`}function uz(e,t,n){if(n.type===`submit`){if(!n.prompt){t({type:`protocol_error`,message:`prompt is required`});return}e.submit(n.prompt).catch(e=>{t({type:`protocol_error`,message:e.message})})}else if(n.type===`command`){if(!n.name){t({type:`protocol_error`,message:`name is required`});return}e.executeCommand(n.name,n.args??``).then(e=>{t({type:`command_result`,name:n.name,message:e?.message??`Unknown command: ${n.name}`,success:e?.success??!1,data:e?.data})},e=>{t({type:`protocol_error`,message:e.message})})}else n.type===`abort`?e.abort():e.cancelQueue()}function dz(e,t,n){n.type===`get-messages`?t({type:`messages`,messages:e.getMessages()}):n.type===`get-context`?t({type:`context`,state:e.getContextState()}):n.type===`get-executing`?t({type:`executing`,executing:e.isExecuting()}):n.type===`get-execution-workspace`?t({type:`execution_workspace_event`,snapshot:e.getExecutionWorkspaceSnapshot()}):t({type:`pending`,pending:e.getPendingPrompt()})}const fz=7070;var pz=class{name=`ws`;defaultEnabled=!0;optionsSchema={port:{type:`number`,description:`WebSocket server port`,default:fz},maxRetries:{type:`number`,description:`Port retry attempts when port is occupied`,default:20}};session=null;stopFn=null;port;maxRetries;constructor(e={}){this.port=e.port??fz,this.maxRetries=e.maxRetries??20}attach(e){this.session=e}async start(){if(!this.session)throw Error(`WsTransport: attach() must be called before start()`);let e=await this.bindWithRetry(this.session,this.port,this.maxRetries);this.stopFn=e.stop}async stop(){await this.stopFn?.(),this.stopFn=null}validateOptions(e){let{port:t,maxRetries:n}=e;return!(t!==void 0&&(typeof t!=`number`||t<1||t>65535)||n!==void 0&&(typeof n!=`number`||n<0))}bindWithRetry(e,t,n){return this.tryBind(e,t).catch(r=>{if(r.code===`EADDRINUSE`&&n>0)return this.bindWithRetry(e,t+1,n-1);throw r})}tryBind(e,t){return new Promise((n,r)=>{let i=$e((e,t)=>{t.writeHead(400).end(`WebSocket endpoint`)});i.on(`error`,e=>{i.close(),r(e)}),i.listen(t,`127.0.0.1`,()=>{let t=new tt({server:i});t.on(`connection`,t=>{let n=e=>{t.readyState===et.OPEN&&t.send(JSON.stringify(e))},{onMessage:r,cleanup:i}=ez({session:e,send:n});t.on(`message`,e=>r(String(e))),t.on(`close`,i),t.on(`error`,i),n({type:`messages`,messages:e.getMessages()}),n({type:`execution_workspace_event`,snapshot:e.getExecutionWorkspaceSnapshot()})}),n({stop:()=>new Promise(e=>{t.close(()=>i.close(()=>e()))})})})})}};function mz(e){return typeof e==`object`&&!!e}function hz(e,t){return typeof e[t]==`string`}function gz(e){if(e.usage===void 0)return!0;let t=e.usage;return mz(t)?typeof t.promptTokens==`number`&&typeof t.completionTokens==`number`&&typeof t.totalTokens==`number`:!1}function _z(e){if(!mz(e)||!hz(e,`type`))return!1;switch(e.type){case`ready`:return!0;case`text_delta`:return hz(e,`delta`);case`tool_start`:return hz(e,`toolName`);case`tool_end`:return hz(e,`toolName`)&&typeof e.success==`boolean`;case`result`:return hz(e,`output`)&&gz(e);case`error`:return hz(e,`message`);case`cancelled`:return e.reason===void 0||typeof e.reason==`string`;default:return!1}}const vz=process.platform!==`win32`;function yz(e,t){return new Promise(n=>{if(e.exitCode!==null||e.signalCode!==null){n();return}let r=setTimeout(()=>{e.removeListener(`exit`,i),n()},t);r.unref?.();let i=()=>{clearTimeout(r),n()};e.once(`exit`,i)})}function bz(e,t,n,r,i){switch(e.type){case`ready`:t();break;case`result`:n(e);break;case`error`:r(new J(`runner`,e.message));break;case`cancelled`:r(new J(`runner`,e.reason??`Subagent worker cancelled`));break;case`text_delta`:i?.({type:`background_task_text_delta`,delta:e.delta});break;case`tool_start`:i?.({type:`background_task_tool_start`,toolName:e.toolName,firstArg:xz(e.toolArgs)});break;case`tool_end`:i?.({type:`background_task_tool_end`,toolName:e.toolName,success:e.success});break;default:r(new J(`runner`,`Unhandled subagent worker message`))}}function xz(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function Sz(e,t){return new Promise((n,r)=>{if(!e.connected){r(new J(`crash`,`Subagent worker IPC channel is closed`));return}e.send(t,e=>{if(e){r(e);return}n()})})}async function Cz(e,t){await Qa(e.child,{graceMs:e.killGraceMs,processGroup:vz,preKill:async()=>{e.child.connected&&(await Sz(e.child,{type:`cancel`,reason:t}).catch(()=>void 0),await yz(e.child,e.killGraceMs))}})}function wz(e){return new Promise((t,n)=>{new Tz(e,t,n).start()})}var Tz=class{options;resolve;reject;settled=!1;started=!1;timeoutTimer;constructor(e,t,n){this.options=e,this.resolve=t,this.reject=n,this.timeoutTimer=Dz(this.options.runtime,e=>this.rejectOnce(e))}start(){let{child:e}=this.options.runtime;e.on(`message`,this.onMessage),e.on(`error`,this.onError),e.on(`exit`,this.onExit),e.once(`spawn`,()=>{setImmediate(this.startWorker)})}startWorker=()=>{if(this.started)return;this.started=!0;let{child:e}=this.options.runtime;Sz(e,{type:`start`,payload:this.options.payload}).catch(e=>{this.rejectOnce(e instanceof Error?e:Error(String(e)))})};onMessage=e=>{if(!_z(e)){this.rejectOnce(new J(`runner`,`Received malformed subagent worker message`));return}let{job:t}=this.options.runtime;bz(e,this.startWorker,this.resolveOnce,this.rejectOnce,t.emit)};onError=e=>{this.rejectOnce(new J(`crash`,e.message))};onExit=(e,t)=>{this.settled||this.rejectOnce(new J(`crash`,kz(e,t)))};resolveOnce=e=>{if(this.settled)return;this.settled=!0,this.clearTimers(),this.cleanup();let{runtime:t,resolveTranscriptPath:n}=this.options;this.resolve(Oz(t.job,e,n))};rejectOnce=e=>{this.settled||(this.settled=!0,this.clearTimers(),this.cleanup(),this.reject(e))};clearTimers(){this.timeoutTimer&&clearTimeout(this.timeoutTimer)}cleanup(){let{child:e}=this.options.runtime;e.off(`message`,this.onMessage),e.off(`error`,this.onError),e.off(`exit`,this.onExit)}};function Ez(e){let t=!1,n=()=>{};return{promise:new Promise((e,t)=>{n=t}),reject(r){t||(t=!0,n(new J(`runner`,r??`Subagent job cancelled: ${e}`)))}}}function Dz(e,t){if(e.job.request.timeoutMs)return setTimeout(()=>{Cz(e,`Subagent worker timed out`),t(new J(`timeout`,`Subagent worker timed out`))},e.job.request.timeoutMs)}function Oz(e,t,n){let r=n(e);return{jobId:e.jobId,output:t.output,...r?{metadata:{transcriptPath:r,logPath:r}}:{},...t.usage?{usage:t.usage}:{}}}function kz(e,t){return`Subagent worker exited before result: ${t===null?`exit code ${e===null?`unknown`:e}`:`signal ${t}`}`}const Az=process.platform!==`win32`;function jz(e){return t=>{let n=new Mz(t,e);return e.worktreeIsolation===!1?n:xs({runner:n,worktreeAdapter:e.worktreeAdapter??ds(),hooks:t.config.hooks,hookTypeExecutors:t.hookTypeExecutors})}}var Mz=class{deps;workerPath;execArgv;killGraceMs;providerConfig;env;logsDir;constructor(e,t){this.deps=e,this.workerPath=t.workerPath,this.execArgv=t.execArgv,this.killGraceMs=t.killGraceMs??2e3,this.providerConfig=t.providerConfig,this.env=t.env,this.logsDir=t.logsDir}start(e){let t=r(this.workerPath,[],{cwd:e.request.cwd,env:{...process.env,...this.env??{}},execArgv:this.execArgv??Iz(this.workerPath),stdio:[`ignore`,`ignore`,`ignore`,`ipc`],detached:Az}),n={job:e,child:t,killGraceMs:this.killGraceMs},i=wz({runtime:n,payload:this.createStartPayload(e),resolveTranscriptPath:e=>this.resolveTranscriptPath(e)}),a=Ez(e.jobId);i.catch(()=>void 0);let o=Promise.race([i,a.promise]);o.catch(()=>void 0);let s=this.resolveTranscriptPath(e);return{jobId:e.jobId,...t.pid!==void 0&&{pid:t.pid},...s!==void 0&&{transcriptPath:s,logPath:s},result:o,cancel:async e=>{a.reject(e),await Cz(n,e)},send:async e=>{await Sz(t,{type:`send`,prompt:e})},...s!==void 0&&{readLog:async t=>Lz(e.jobId,s,t)}}}createStartPayload(e){let t=Nz(e.request.type,this.deps.customAgentRegistry);return{jobId:e.jobId,request:e.request,agentDefinition:Pz(t,e),parentConfig:this.deps.config,parentContext:this.deps.context,providerProfile:Fz(this.providerConfig,this.deps,e),permissionMode:this.deps.permissionMode,...this.logsDir?{logsDir:this.logsDir}:{}}}resolveTranscriptPath(e){if(this.logsDir)return h(this.logsDir,e.request.parentSessionId,`subagents`,`${e.jobId}.jsonl`)}};function Nz(e,t){let n=t?.(e)??Yd(e);if(!n)throw new J(`validation`,`Unknown agent type: ${e}`);return n}function Pz(e,t){return{...e,...t.request.model?{model:t.request.model}:{},...t.request.allowedTools?{tools:t.request.allowedTools}:{},...t.request.disallowedTools?{disallowedTools:t.request.disallowedTools}:{}}}function Fz(e,t,n){let r=e??t.config.provider;return{profileName:t.config.currentProvider,type:r.name,model:n.request.model??r.model,apiKey:r.apiKey,baseURL:r.baseURL,timeout:r.timeout,options:r.options}}function Iz(e){return!e.endsWith(`.ts`)||process.execArgv.some(e=>e.includes(`tsx`))?process.execArgv:[...process.execArgv,`--import`,`tsx`]}function Lz(e,t,n){return T(t)?No(e,O(t,`utf8`).split(/\r?\n/).filter(Boolean),n):{taskId:e,cursor:n,lines:[]}}function Rz(){return h(p(Ae(import.meta.url)),`child-process-subagent-worker.js`)}async function zz(e,t,n){if(e.positional[0]!==`user-local`)return!1;let r=await bP({cwd:t,argv:e.positional.slice(1),format:e.format,summary:e.summary,source:e.source}),i=r.message.trimEnd();if(!r.success)throw Error(i);return n.writeLine(i),!0}function Bz(e,t){return new Date(t).getTime()-new Date(e).getTime()}function Vz(e){return new Date(e).toISOString()}function Hz(e,t,n,r,i,a){return{kind:e,fromType:t,toType:n,fromTimestamp:Vz(r),toTimestamp:Vz(i),durationMs:Bz(r,i),turnIndex:a}}function Uz(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];if(!i){r++;continue}if(i.category===`chat`&&i.type===`user`){n++;let a=i.timestamp,o=!1,s=null,c=r+1;for(;c<e.length;){let r=e[c];if(!r){c++;continue}if(r.category===`chat`&&r.type===`user`)break;if(r.category===`event`&&r.type===`tool-start`){o?s!==null&&t.push(Hz(`llm_between_tools`,`tool-end`,`tool-start`,s,r.timestamp,n)):(t.push(Hz(`user_to_first_tool`,`user`,`tool-start`,a,r.timestamp,n)),o=!0),s=null,c++;continue}if(r.category===`event`&&r.type===`tool-end`){let i=e[c-1];i&&i.category===`event`&&i.type===`tool-start`&&t.push(Hz(`tool_exec`,`tool-start`,`tool-end`,i.timestamp,r.timestamp,n)),s=r.timestamp,c++;continue}if(r.category===`event`&&r.type===`tool-summary`){s!==null&&t.push(Hz(`llm_final_response`,`tool-end`,`tool-summary`,s,r.timestamp,n)),c++;continue}if(r.category===`chat`&&r.type===`assistant`){o?s!==null&&t.push(Hz(`llm_final_response`,`tool-end`,`assistant`,s,r.timestamp,n)):t.push(Hz(`user_to_assistant`,`user`,`assistant`,a,r.timestamp,n)),c++;break}c++}r=c}else r++}return t}function Wz(e){let t=e.filter(e=>e.kind===`user_to_first_tool`||e.kind===`user_to_assistant`||e.kind===`llm_between_tools`||e.kind===`llm_final_response`),n=e.filter(e=>e.kind===`tool_exec`),r=e.filter(e=>e.kind===`user_to_assistant`),i=e=>e.length?Math.round(e.reduce((e,t)=>e+t.durationMs,0)/e.length):0,a=e=>e.length?Math.max(...e.map(e=>e.durationMs)):0;return{llmWaitMs:{avg:i(t),max:a(t),total:t.reduce((e,t)=>e+t.durationMs,0),count:t.length},toolExecMs:{avg:i(n),max:a(n),median:(e=>{if(!e.length)return 0;let t=[...e].sort((e,t)=>e.durationMs-t.durationMs),n=Math.floor(t.length/2);return t.length%2==0?Math.round(((t[n-1]?.durationMs??0)+(t[n]?.durationMs??0))/2):t[n]?.durationMs??0})(n),count:n.length},userToAssistantMs:{avg:i(r),max:a(r),count:r.length}}}function Gz(e){let t=Uz(e.history??[]),n=t.filter(e=>e.durationMs>=1e4);return{sessionId:e.id,cwd:e.cwd,createdAt:e.createdAt,totalIntervals:t.length,intervals:t,slowIntervals:n,stats:Wz(t)}}function Kz(e){let t=e.flatMap(e=>e.intervals.filter(e=>e.kind===`user_to_first_tool`||e.kind===`user_to_assistant`||e.kind===`llm_between_tools`||e.kind===`llm_final_response`)),n=e.flatMap(e=>e.intervals.filter(e=>e.kind===`tool_exec`)),r=t.length?Math.round(t.reduce((e,t)=>e+t.durationMs,0)/t.length):0,i=n.length?Math.round(n.reduce((e,t)=>e+t.durationMs,0)/n.length):0,a=0,o=``,s=0,c=``;for(let t of e)for(let e of t.intervals)e.durationMs>a&&(a=e.durationMs,o=t.sessionId,s=e.turnIndex,c=e.kind);let l=e.map(e=>e.createdAt).sort();return{sessionCount:e.length,fromDate:l[0]??``,toDate:l[l.length-1]??``,avgLlmResponseMs:r,avgToolExecMs:i,maxSingleDelayMs:a,maxSingleDelaySession:o,maxSingleDelayTurn:s,maxSingleDelayKind:c}}function qz(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:`${e}`}function Jz(e){let t=[];if(t.push(`Token usage — session ${e.sessionId}`),t.push(` total ${qz(e.totalTokens)} (prompt ${qz(e.promptTokens)} · completion ${qz(e.completionTokens)})`),e.bySource.length===0)return t.push(` (no usage recorded)`),t.join(`
324
+ `}),V(I,{dimColor:!0,children:[` v`,e.version]})]},`logo`):B(wL,{entry:e.entry},e.entry.id)}),!r&&V(Je,{children:[ne&&B(CR,{message:ne}),V(F,{flexDirection:`column`,paddingX:1,flexGrow:1,children:[M&&M.kind!==`main_thread`&&B(uF,{entry:M,page:oe,loading:ue,error:ce}),h&&B(F,{marginBottom:1,children:B(I,{color:`yellow`,children:`Shutting down...`})}),(d||u.length>0)&&V(F,{flexDirection:`column`,marginBottom:1,children:[B(yR,{text:l,activeTools:u,isThinking:d}),p&&B(I,{color:`yellow`,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!d&&f&&B(F,{marginBottom:1,children:B(I,{color:`red`,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`})}),B(cF,{entries:j,focusedIndex:ge})]}),ie&&B(bF,{snapshot:_,selectedEntryId:v,onSelect:y,onClose:()=>ae(!1)}),x&&B(VL,{request:x}),S&&B(PL,{request:S,onAnswer:e=>n.resolveUserAction(e)}),be&&B(eR,{callbacks:ee,onClose:()=>Ce(!1),addMessage:e=>c(H(q(e.content)))}),Se&&e.transportRegistry&&B(SR,{registry:e.transportRegistry,onClose:()=>Te(!1)}),xe&&B(tR,{sessions:Py(e.sessionStore,e.cwd),onSelect:t=>{we(!1),e.onSessionSwitch(t)},onCancel:()=>{we(!1),c(H(q(`Session resume cancelled.`)))}}),B(lF,{percentage:C.percentage}),B(FI,{onSubmit:ke,onCancelQueue:E,isDisabled:!!x||!!S||be||Se||xe||ie||h||d&&!!g||!Ee||ve,isAborting:m,pendingPrompt:g,registry:a,sessionName:O,history:s,onRequestFocusBackgroundList:()=>{j.length>0&&_e(0)}}),B(mR,{cwd:t,permissionMode:je,modelId:e.modelId,providerType:e.providerType,sessionId:Me,isThinking:d,activeToolCount:u.length,activeBackgroundTaskCount:ye,hasPendingPrompt:g!==null,contextState:C,sessionName:O,settings:fe,activeAgentLabel:De,activePresetId:Ne,gitRefreshToken:me})]})]})}var ER=class{hooks;instance;registerSuspendHooks(e){return this.hooks=e,()=>{this.hooks===e&&(this.hooks=void 0)}}setInkInstance(e){this.instance=e}get canHandoffTerminal(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&this.hooks!==void 0}async runWithTerminal(e){let t=this.hooks;if(!this.canHandoffTerminal||t===void 0)throw Error(`TUI terminal handoff unavailable: no interactive TTY, or the App is not mounted.`);await t.suspend(),this.instance?.clear();let n=process.stdin;n.isTTY&&typeof n.setRawMode==`function`&&n.setRawMode(!1),n.pause();try{return await e()}finally{t.resume()}}};function DR(e){return/not initialized/i.test(e.message)}function OR(e){let t=e.isBenignError??DR,n=null,r=0,i;function a(){n!==null&&(clearInterval(n),n=null)}function o(){r+=e.intervalMs;try{e.check()}catch(n){let o=n instanceof Error?n:Error(String(n));if(!t(o)){a(),e.onFailure({kind:`error`,error:o});return}i=o,r>=e.timeoutMs&&(a(),e.onFailure({kind:`timeout`,lastError:i}));return}a(),e.onReady()}return{start(){n===null&&(r=0,n=setInterval(o,e.intervalMs))},stop:a}}var kR=class{queue=[];enqueueEffects(e){e.length!==0&&this.queue.push({effects:[...e]})}drain(){return this.queue.shift()}clear(){this.queue.length=0}};function AR(e,t,n,r,i,a){let o=jR(e.effects,n,r,a);if(r.addEntry(H(q(e.message))),o.length>0&&i.enqueueEffects(o),t.isInitialized){let e=t.getContextState();r.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})}}function jR(e,t,n,r){if(e===void 0||e.length===0)return[];let i=[];for(let a of e){if(a.type===`conversation-history-cleared`){n.clearHistory();continue}if(a.type===`plugin-registry-reload-requested`){r?.(t);continue}i.push(a)}return i}function MR(e,t){let n=null;return{schedule(){n||=setTimeout(()=>{n=null,e()},t)},flush(){n&&=(clearTimeout(n),null)}}}var NR=class{history=[];streamingText=``;activeTools=[];isThinking=!1;isAborting=!1;pendingPrompt=null;contextState={percentage:0,usedTokens:0,maxTokens:0};executionWorkspaceSnapshot=null;selectedExecutionEntryId;lastErrorMessage=null;isStalled=!1;onChange=null;streamBuf=``;debouncedStreamNotify=MR(()=>this.notify(),300);stallTimer=null;armStallTimer(){this.clearStallTimer(),this.stallTimer=setTimeout(()=>{this.stallTimer=null,this.isStalled=!0,this.notify()},15e3)}clearStallTimer(){this.stallTimer&&=(clearTimeout(this.stallTimer),null),this.isStalled&&=!1}notify(){this.onChange?.()}onTextDelta=e=>{this.isThinking&&this.armStallTimer(),this.streamBuf+=e,this.streamingText=this.streamBuf,this.debouncedStreamNotify.schedule()};onToolStart=e=>{this.clearStallTimer(),this.activeTools=[...this.activeTools,e],this.notify()};onToolEnd=e=>{let t=this.activeTools.findLastIndex(t=>t.toolName===e.toolName&&t.isRunning);if(t!==-1){let n=[...this.activeTools];n[t]=e,this.activeTools=n}this.isThinking&&!this.activeTools.some(e=>e.isRunning)&&this.armStallTimer(),this.notify()};onThinking=e=>{this.isThinking=e,e?(this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.lastErrorMessage=null,this.armStallTimer()):(this.isAborting=!1,this.activeTools=[],this.clearStallTimer()),this.notify()};onComplete=e=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.contextState={percentage:e.contextState.usedPercentage,usedTokens:e.contextState.usedTokens,maxTokens:e.contextState.maxTokens},this.notify()};onInterrupted=()=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onError=e=>{this.clearStallTimer(),this.lastErrorMessage=e?.message??`Unknown error`,this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onContextUpdate=e=>{this.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})};syncHistory(e){e.length!==0&&(this.history=[...e],this.notify())}addEntry(e){this.history=[...this.history,e],this.notify()}clearHistory(){this.history=[],this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()}setPendingPrompt(e){this.pendingPrompt=e,this.notify()}setAborting(e){this.isAborting=e,this.notify()}setContextState(e){this.contextState=e,this.notify()}syncExecutionWorkspaceSnapshot(e){let t=this.selectedExecutionEntryId,n=t!==void 0&&e.entries.some(e=>e.id===t)?t:e.selectedEntryId??e.entries[0]?.id;this.executionWorkspaceSnapshot={...e,...n?{selectedEntryId:n}:{}},this.selectedExecutionEntryId=n,this.notify()}selectExecutionWorkspaceEntry(e){this.executionWorkspaceSnapshot?.entries.some(t=>t.id===e)&&(this.selectedExecutionEntryId=e,this.executionWorkspaceSnapshot={...this.executionWorkspaceSnapshot,selectedEntryId:e},this.notify())}dispose(){this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.onChange=null}};const PR=15e3,FR=5e3;var IR=class{stateManager;interactiveSession;registry;commandEffectQueue;opts;submitHandler=null;userActionQueue=[];processingUserAction=!1;permissionRequest=null;pendingUserAction=null;availableCommands=[];isShuttingDown=!1;sessionName;autoNameTriggered=!1;sessionStarted=!1;initPoller=null;get terminalHandoffController(){return this.opts.terminalHandoff}permissionQueue=[];processingPermission=!1;sessionEventBindings=[];stopped=!1;onChange=null;constructor(e){this.opts=e,this.sessionName=e.sessionName,this.stateManager=new NR,this.stateManager.onChange=()=>this.onChange?.(),this.interactiveSession=this.createSession(),this.registry=this.createRegistry(),this.commandEffectQueue=new kR}createSession(){let e=this.opts;return new jy({cwd:e.cwd,provider:e.provider,permissionMode:e.permissionMode,maxTurns:e.maxTurns,permissionHandler:(e,t)=>this.handlePermissionRequest(e,t),askHandler:e=>this.askUser(e),sessionStore:e.sessionStore,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,sessionName:e.sessionName,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,language:e.language,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,systemPrompt:e.systemPrompt,appendSystemPrompt:e.appendSystemPrompt,allowedTools:e.allowedTools,deniedTools:e.deniedTools,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,terminalHandoff:e.terminalHandoff})}createRegistry(){let e=new e_;for(let t of this.opts.commandModules??[])e.addModule(t);return this.opts.reloadPluginCommandSource?.(e),e}onSubmit(e){this.submitHandler=e}write(e){}setAvailableCommands(e){this.availableCommands=e,this.onChange?.()}setBusy(e){this.stateManager.onThinking(e)}async start(){this.sessionStarted||(this.sessionStarted=!0,this.wireSessionEvents(),this.syncRestoredHistory(),this.startInitCheck(),this.opts.transportRegistry&&await this.opts.transportRegistry.startAll(this.interactiveSession))}async stop(){this.stopped||(this.stopped=!0,this.sessionStarted=!1,this.unwireSessionEvents(),this.cancelAllPermissions(),this.cancelAllUserActions(),this.stopInitCheck(),this.onChange=null,this.stateManager.dispose(),this.opts.transportRegistry&&await this.opts.transportRegistry.stopAll(),this.isShuttingDown||await this.shutdownSessionBounded(`other`,`channel stopped`,FR))}getSession(){return this.interactiveSession}getRegistry(){return this.registry}getCommandEffectQueue(){return this.commandEffectQueue}abort(){this.stateManager.setAborting(!0),this.cancelAllUserActions(),this.cancelAllPermissions(),this.interactiveSession.abort()}cancelQueue(){this.interactiveSession.cancelQueue(),this.cancelAllUserActions(),this.cancelAllPermissions(),this.stateManager.setPendingPrompt(null)}async shutdown(e){this.isShuttingDown||(this.isShuttingDown=!0,this.cancelAllUserActions(),this.cancelAllPermissions(),this.stateManager.addEntry(H(q(`Shutting down...`))),this.onChange?.(),await this.shutdownSessionBounded(e?.reason??`prompt_input_exit`,`CLI shutdown`,e?.timeoutMs??FR))}async shutdownSessionBounded(e,t,n){let r,i=new Promise(e=>{r=setTimeout(e,n),r.unref?.()});await Promise.race([this.interactiveSession.shutdown({reason:e,message:t}).catch(()=>void 0),i]),r&&clearTimeout(r)}selectExecutionWorkspaceEntry(e){this.stateManager.selectExecutionWorkspaceEntry(e)}async readExecutionWorkspaceDetail(e){return this.interactiveSession.readExecutionWorkspaceDetail(e)}async sendAgentJob(e,t){await this.interactiveSession.sendAgentJob(e,t)}setSessionName(e){this.sessionName=e,this.interactiveSession.setName(e),this.onChange?.()}async askUser(e){return new Promise(t=>{this.userActionQueue.push({request:e,resolve:t}),this.processNextUserAction()})}resolveUserAction(e){let t=this.userActionQueue[0];t&&(this.userActionQueue.shift(),this.processingUserAction=!1,this.pendingUserAction=null,this.onChange?.(),t.resolve(e),this.processNextUserAction())}processNextUserAction(){if(this.processingUserAction)return;let e=this.userActionQueue[0];if(!e){this.pendingUserAction=null,this.onChange?.();return}this.processingUserAction=!0,this.pendingUserAction=e.request,this.onChange?.()}cancelAllUserActions(){let e=this.userActionQueue;this.userActionQueue=[],this.processingUserAction=!1,this.pendingUserAction=null;for(let t of e)t.resolve({type:`cancelled`});this.onChange?.()}async handleInput(e){if(!e.startsWith(`/`)){await this.interactiveSession.submit(e),this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}await this.handleSlashCommand(e)}async handleSlashCommand(e){let t=e.slice(1).split(/\s+/),n=t[0]?.toLowerCase()??``,r=t.slice(1).join(` `),i=await this.interactiveSession.executeCommand(n,r);if(i){if(i.effects?.some(e=>e.type===`session-execution-started`)){this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}AR(i,this.interactiveSession,this.registry,this.stateManager,this.commandEffectQueue,this.opts.reloadPluginCommandSource);return}this.stateManager.addEntry(H(q(`Unknown command "/${n}". Type /help for help.`)))}handlePermissionRequest(e,t){return new Promise(n=>{this.permissionQueue.push({toolName:e,toolArgs:t,resolve:n}),this.processNextPermission()})}processNextPermission(){if(this.processingPermission)return;let e=this.permissionQueue[0];if(!e){this.permissionRequest=null,this.onChange?.();return}this.processingPermission=!0,this.permissionRequest={toolName:e.toolName,toolArgs:e.toolArgs,resolve:t=>{this.permissionQueue.shift(),this.processingPermission=!1,this.permissionRequest=null,e.resolve(t),setTimeout(()=>this.processNextPermission(),0)}},this.onChange?.()}cancelAllPermissions(){let e=this.permissionQueue;this.permissionQueue=[],this.processingPermission=!1,this.permissionRequest=null;for(let t of e)t.resolve(!1);this.onChange?.()}wireSessionEvents(){let e=this.interactiveSession,t=this.stateManager;this.bindSession(`user_message`,e=>{this.handleAutoNaming(e),t.addEntry(H(ai(e)))}),this.bindSession(`text_delta`,t.onTextDelta),this.bindSession(`tool_start`,t.onToolStart),this.bindSession(`tool_end`,t.onToolEnd),this.bindSession(`thinking`,t.onThinking),this.bindSession(`complete`,n=>{t.onComplete(n),t.syncHistory(e.getFullHistory())}),this.bindSession(`interrupted`,t.onInterrupted),this.bindSession(`error`,n=>{t.onError(n),t.syncHistory(e.getFullHistory())}),this.bindSession(`context_update`,t.onContextUpdate),this.bindSession(`compact`,()=>{t.syncHistory(e.getFullHistory())}),this.bindSession(`skill_activation`,()=>{t.syncHistory(e.getFullHistory())}),this.bindSession(`memory_event`,()=>{t.syncHistory(e.getFullHistory())}),this.bindSession(`execution_workspace_event`,e=>{t.syncExecutionWorkspaceSnapshot(e.snapshot)})}bindSession(e,t){this.interactiveSession.on(e,t),this.sessionEventBindings.push({event:e,handler:t})}unwireSessionEvents(){for(let{event:e,handler:t}of this.sessionEventBindings)this.interactiveSession.off(e,t);this.sessionEventBindings=[]}handleAutoNaming(e){this.autoNameTriggered||this.opts.sessionName||this.interactiveSession.getName()||(this.autoNameTriggered=!0,Gy(this.opts.provider,e).then(e=>{this.interactiveSession.setName(e),this.sessionName=e,this.opts.onAutoNamed?.(e),this.onChange?.()}).catch(()=>{this.autoNameTriggered=!1}))}syncRestoredHistory(){if(this.stateManager.history.length===0){let e=this.interactiveSession.getFullHistory();e.length>0&&this.stateManager.syncHistory(e)}}startInitCheck(){this.initPoller=OR({check:()=>this.runInitCheck(),intervalMs:200,timeoutMs:PR,onReady:()=>void 0,onFailure:e=>this.onInitFailure(e)}),this.initPoller.start()}runInitCheck(){let e=this.interactiveSession.getContextState();this.stateManager.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens});let t=this.interactiveSession.getFullHistory();t.length>0&&this.stateManager.syncHistory(t),this.syncExecutionWorkspace()}onInitFailure(e){let t=e.kind===`timeout`?`Session initialization timed out after ${PR/1e3}s${e.lastError?` (last error: ${e.lastError.message})`:``}`:`Session initialization failed: ${e.error.message}`;this.stateManager.onError(),this.stateManager.addEntry({id:`session-init-error-${Date.now()}`,timestamp:new Date,category:`event`,type:`session-init-error`,data:{message:t}})}stopInitCheck(){this.initPoller?.stop(),this.initPoller=null}syncExecutionWorkspace(){try{this.stateManager.syncExecutionWorkspaceSnapshot(this.interactiveSession.getExecutionWorkspaceSnapshot({selectedEntryId:this.stateManager.selectedExecutionEntryId}))}catch{}}};function LR(e,t){return{cwd:e.cwd,provider:e.provider,permissionMode:e.permissionMode,maxTurns:e.maxTurns,allowedTools:e.allowedTools,deniedTools:e.deniedTools,sessionStore:e.sessionStore,resumeSessionId:t,forkSession:e.forkSession,sessionName:e.sessionName,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,transportRegistry:e.transportRegistry,language:e.language,reloadPluginCommandSource:e.reloadPluginCommandSource,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification}}async function RR(e){let t=new ER,n=Le(B(wR,{cwd:e.cwd,createChannel:n=>{let r=new IR({...LR(e,n),terminalHandoff:t});return e.onChannelReady?.(r),r},providerOverride:e.providerOverride,providerType:e.providerType,modelId:e.modelId,permissionMode:e.permissionMode,version:e.version,sessionStore:e.sessionStore,resumeSessionId:e.resumeSessionId,showSessionPickerOnStart:e.showSessionPickerOnStart,startupUpdateNotice:e.startupUpdateNotice,transportRegistry:e.transportRegistry,cliAdapter:e.cliAdapter}),{exitOnCtrlC:!1});t.setInkInstance(n),await n.waitUntilExit()}function zR({providerDefinitions:e,reloadPluginCommandSource:t}){return{getUserSettingsPath:()=>Wm(),readSettings:e=>Km(e),writeSettings:(e,t)=>qm(e,t),deleteSettings:e=>Jm(e),applyStatusLineSettings:(e,t)=>zv(e,t),reloadPluginCommandSource:e=>{t(e)},applyActiveModelChange:(e,t,n)=>(N_(e,t,n),{applied:!0}),getGitBranch:e=>Fb(e),getProviderDisplayName:t=>ut(e,t)?.displayName??t}}let BR=null,VR=!1;function HR(e){BR=e}function UR(e,t){try{if(BR){BR.getSession().reportBackgroundError(e,t);return}}catch{}process.stderr.write(`\n[robota] ${t}: ${e.message}\n`)}function WR(){VR||(VR=!0,process.on(`unhandledRejection`,e=>{UR(e instanceof Error?e:Error(String(e)),`unhandled rejection`)}),process.on(`uncaughtException`,e=>{UR(e instanceof Error?e:Error(String(e)),`uncaught exception`)}))}var GR=class{entries=new Map;settingsPath;constructor(e){this.settingsPath=e}register(e){this.entries.set(e.name,e)}getAll(){let e=this.readTransportSettings();return Array.from(this.entries.values()).map(t=>({transport:t,config:this.resolveConfig(t,e[t.name])}))}getEnabled(){return this.getAll().filter(e=>e.config.enabled).map(e=>e.transport)}async setEnabled(e,t){let n=Km(this.settingsPath),r=n.transports??{};r[e]={...r[e]??{},enabled:t},n.transports=r,qm(this.settingsPath,n)}async setOptions(e,t){let n=Km(this.settingsPath),r=n.transports??{};r[e]={...r[e]??{},options:t},n.transports=r,qm(this.settingsPath,n)}async startAll(e){let t=this.getEnabled();for(let n of t)n.attach(e),await n.start()}async stopAll(){let e=[];for(let t of this.entries.values())try{await t.stop()}catch(t){e.push(t instanceof Error?t:Error(String(t)))}return{errors:e}}resolveConfig(e,t){return{enabled:t?.enabled??e.defaultEnabled,options:t?.options??{}}}readTransportSettings(){let e=Km(this.settingsPath).transports;return!e||typeof e!=`object`||Array.isArray(e)?{}:e}};function KR(e,t,n){if(n.type===`get-background-tasks`){t({type:`background_tasks`,tasks:e.listBackgroundTasks(n.filter)});return}if(n.type===`get-background-task`){JR(e,t,n);return}if(n.type===`get-background-job-groups`){t({type:`background_job_groups`,groups:e.listBackgroundJobGroups()});return}if(n.type===`get-background-job-group`){XR(e,t,n);return}if(n.type===`wait-background-job-group`){ZR(e,t,n);return}YR(e,t,n)}function qR(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}if(n.type===`cancel-background-task`){$R(t,`cancel`,n.taskId,e.cancelBackgroundTask(n.taskId,n.reason));return}if(n.type===`close-background-task`){$R(t,`close`,n.taskId,e.closeBackgroundTask(n.taskId));return}QR(e,t,n)}function JR(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}t({type:`background_task`,taskId:n.taskId,task:e.getBackgroundTask(n.taskId)??null})}function YR(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}e.readBackgroundTaskLog(n.taskId,n.cursor).then(e=>t({type:`background_task_log`,taskId:n.taskId,page:e}),e=>t({type:`protocol_error`,message:e.message}))}function XR(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}t({type:`background_job_group`,groupId:n.groupId,group:e.getBackgroundJobGroup(n.groupId)??null})}function ZR(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}e.waitBackgroundJobGroup(n.groupId).then(e=>t({type:`background_job_group`,groupId:n.groupId,group:e}),e=>t({type:`protocol_error`,message:e.message}))}function QR(e,t,n){if(!n.input){t({type:`protocol_error`,message:`input is required`});return}$R(t,`send`,n.taskId,e.sendBackgroundTask(n.taskId,n.input))}function $R(e,t,n,r){r.then(()=>e({type:`background_task_control_result`,action:t,taskId:n,success:!0}),r=>e({type:`background_task_control_result`,action:t,taskId:n,success:!1,message:r.message}))}function ez(e){let t=tz(e.session,e.send);return{onMessage:nz(e.session,e.send),cleanup:t}}function tz(e,t){let n=e=>t({type:`user_message`,content:e}),r=e=>t({type:`text_delta`,delta:e}),i=e=>t({type:`tool_start`,state:e}),a=e=>t({type:`tool_end`,state:e}),o=e=>t({type:`thinking`,isThinking:e}),s=e=>t({type:`complete`,result:e}),c=e=>t({type:`interrupted`,result:e}),l=e=>t({type:`error`,message:e.message}),u=e=>t({type:`background_task_event`,event:e}),d=e=>t({type:`background_job_group_event`,event:e}),f=e=>t({type:`execution_workspace_event`,snapshot:e.snapshot});return e.on(`user_message`,n),e.on(`text_delta`,r),e.on(`tool_start`,i),e.on(`tool_end`,a),e.on(`thinking`,o),e.on(`complete`,s),e.on(`interrupted`,c),e.on(`error`,l),e.on(`background_task_event`,u),e.on(`background_job_group_event`,d),e.on(`execution_workspace_event`,f),()=>{e.off(`user_message`,n),e.off(`text_delta`,r),e.off(`tool_start`,i),e.off(`tool_end`,a),e.off(`thinking`,o),e.off(`complete`,s),e.off(`interrupted`,c),e.off(`error`,l),e.off(`background_task_event`,u),e.off(`background_job_group_event`,d),e.off(`execution_workspace_event`,f)}}function nz(e,t){return n=>{let r=rz(n,t);r&&iz(e,t,r)}}function rz(e,t){try{return JSON.parse(e)}catch{return t({type:`protocol_error`,message:`Invalid JSON`}),null}}function iz(e,t,n){if(oz(n)){uz(e,t,n);return}if(sz(n)){dz(e,t,n);return}if(cz(n)){KR(e,t,n);return}if(lz(n)){qR(e,t,n);return}t({type:`protocol_error`,message:`Unknown message type: ${az(n)}`})}function az(e){return e.type}function oz(e){return e.type===`submit`||e.type===`command`||e.type===`abort`||e.type===`cancel-queue`}function sz(e){return e.type===`get-messages`||e.type===`get-context`||e.type===`get-executing`||e.type===`get-pending`||e.type===`get-execution-workspace`}function cz(e){return e.type===`get-background-tasks`||e.type===`get-background-task`||e.type===`read-background-task-log`||e.type===`get-background-job-groups`||e.type===`get-background-job-group`||e.type===`wait-background-job-group`}function lz(e){return e.type===`cancel-background-task`||e.type===`close-background-task`||e.type===`send-background-task`}function uz(e,t,n){if(n.type===`submit`){if(!n.prompt){t({type:`protocol_error`,message:`prompt is required`});return}e.submit(n.prompt).catch(e=>{t({type:`protocol_error`,message:e.message})})}else if(n.type===`command`){if(!n.name){t({type:`protocol_error`,message:`name is required`});return}e.executeCommand(n.name,n.args??``).then(e=>{t({type:`command_result`,name:n.name,message:e?.message??`Unknown command: ${n.name}`,success:e?.success??!1,data:e?.data})},e=>{t({type:`protocol_error`,message:e.message})})}else n.type===`abort`?e.abort():e.cancelQueue()}function dz(e,t,n){n.type===`get-messages`?t({type:`messages`,messages:e.getMessages()}):n.type===`get-context`?t({type:`context`,state:e.getContextState()}):n.type===`get-executing`?t({type:`executing`,executing:e.isExecuting()}):n.type===`get-execution-workspace`?t({type:`execution_workspace_event`,snapshot:e.getExecutionWorkspaceSnapshot()}):t({type:`pending`,pending:e.getPendingPrompt()})}const fz=7070;var pz=class{name=`ws`;defaultEnabled=!0;optionsSchema={port:{type:`number`,description:`WebSocket server port`,default:fz},maxRetries:{type:`number`,description:`Port retry attempts when port is occupied`,default:20}};session=null;stopFn=null;port;maxRetries;constructor(e={}){this.port=e.port??fz,this.maxRetries=e.maxRetries??20}attach(e){this.session=e}async start(){if(!this.session)throw Error(`WsTransport: attach() must be called before start()`);let e=await this.bindWithRetry(this.session,this.port,this.maxRetries);this.stopFn=e.stop}async stop(){await this.stopFn?.(),this.stopFn=null}validateOptions(e){let{port:t,maxRetries:n}=e;return!(t!==void 0&&(typeof t!=`number`||t<1||t>65535)||n!==void 0&&(typeof n!=`number`||n<0))}bindWithRetry(e,t,n){return this.tryBind(e,t).catch(r=>{if(r.code===`EADDRINUSE`&&n>0)return this.bindWithRetry(e,t+1,n-1);throw r})}tryBind(e,t){return new Promise((n,r)=>{let i=$e((e,t)=>{t.writeHead(400).end(`WebSocket endpoint`)});i.on(`error`,e=>{i.close(),r(e)}),i.listen(t,`127.0.0.1`,()=>{let t=new tt({server:i});t.on(`connection`,t=>{let n=e=>{t.readyState===et.OPEN&&t.send(JSON.stringify(e))},{onMessage:r,cleanup:i}=ez({session:e,send:n});t.on(`message`,e=>r(String(e))),t.on(`close`,i),t.on(`error`,i),n({type:`messages`,messages:e.getMessages()}),n({type:`execution_workspace_event`,snapshot:e.getExecutionWorkspaceSnapshot()})}),n({stop:()=>new Promise(e=>{t.close(()=>i.close(()=>e()))})})})})}};function mz(e){return typeof e==`object`&&!!e}function hz(e,t){return typeof e[t]==`string`}function gz(e){if(e.usage===void 0)return!0;let t=e.usage;return mz(t)?typeof t.promptTokens==`number`&&typeof t.completionTokens==`number`&&typeof t.totalTokens==`number`:!1}function _z(e){if(!mz(e)||!hz(e,`type`))return!1;switch(e.type){case`ready`:return!0;case`text_delta`:return hz(e,`delta`);case`tool_start`:return hz(e,`toolName`);case`tool_end`:return hz(e,`toolName`)&&typeof e.success==`boolean`;case`result`:return hz(e,`output`)&&gz(e);case`error`:return hz(e,`message`);case`cancelled`:return e.reason===void 0||typeof e.reason==`string`;default:return!1}}const vz=process.platform!==`win32`;function yz(e,t){return new Promise(n=>{if(e.exitCode!==null||e.signalCode!==null){n();return}let r=setTimeout(()=>{e.removeListener(`exit`,i),n()},t);r.unref?.();let i=()=>{clearTimeout(r),n()};e.once(`exit`,i)})}function bz(e,t,n,r,i){switch(e.type){case`ready`:t();break;case`result`:n(e);break;case`error`:r(new J(`runner`,e.message));break;case`cancelled`:r(new J(`runner`,e.reason??`Subagent worker cancelled`));break;case`text_delta`:i?.({type:`background_task_text_delta`,delta:e.delta});break;case`tool_start`:i?.({type:`background_task_tool_start`,toolName:e.toolName,firstArg:xz(e.toolArgs)});break;case`tool_end`:i?.({type:`background_task_tool_end`,toolName:e.toolName,success:e.success});break;default:r(new J(`runner`,`Unhandled subagent worker message`))}}function xz(e){if(!e)return;let t=Object.values(e)[0];if(t!==void 0)return typeof t==`object`?JSON.stringify(t):String(t)}function Sz(e,t){return new Promise((n,r)=>{if(!e.connected){r(new J(`crash`,`Subagent worker IPC channel is closed`));return}e.send(t,e=>{if(e){r(e);return}n()})})}async function Cz(e,t){await Qa(e.child,{graceMs:e.killGraceMs,processGroup:vz,preKill:async()=>{e.child.connected&&(await Sz(e.child,{type:`cancel`,reason:t}).catch(()=>void 0),await yz(e.child,e.killGraceMs))}})}function wz(e){return new Promise((t,n)=>{new Tz(e,t,n).start()})}var Tz=class{options;resolve;reject;settled=!1;started=!1;timeoutTimer;constructor(e,t,n){this.options=e,this.resolve=t,this.reject=n,this.timeoutTimer=Dz(this.options.runtime,e=>this.rejectOnce(e))}start(){let{child:e}=this.options.runtime;e.on(`message`,this.onMessage),e.on(`error`,this.onError),e.on(`exit`,this.onExit),e.once(`spawn`,()=>{setImmediate(this.startWorker)})}startWorker=()=>{if(this.started)return;this.started=!0;let{child:e}=this.options.runtime;Sz(e,{type:`start`,payload:this.options.payload}).catch(e=>{this.rejectOnce(e instanceof Error?e:Error(String(e)))})};onMessage=e=>{if(!_z(e)){this.rejectOnce(new J(`runner`,`Received malformed subagent worker message`));return}let{job:t}=this.options.runtime;bz(e,this.startWorker,this.resolveOnce,this.rejectOnce,t.emit)};onError=e=>{this.rejectOnce(new J(`crash`,e.message))};onExit=(e,t)=>{this.settled||this.rejectOnce(new J(`crash`,kz(e,t)))};resolveOnce=e=>{if(this.settled)return;this.settled=!0,this.clearTimers(),this.cleanup();let{runtime:t,resolveTranscriptPath:n}=this.options;this.resolve(Oz(t.job,e,n))};rejectOnce=e=>{this.settled||(this.settled=!0,this.clearTimers(),this.cleanup(),this.reject(e))};clearTimers(){this.timeoutTimer&&clearTimeout(this.timeoutTimer)}cleanup(){let{child:e}=this.options.runtime;e.off(`message`,this.onMessage),e.off(`error`,this.onError),e.off(`exit`,this.onExit)}};function Ez(e){let t=!1,n=()=>{};return{promise:new Promise((e,t)=>{n=t}),reject(r){t||(t=!0,n(new J(`runner`,r??`Subagent job cancelled: ${e}`)))}}}function Dz(e,t){if(e.job.request.timeoutMs)return setTimeout(()=>{Cz(e,`Subagent worker timed out`),t(new J(`timeout`,`Subagent worker timed out`))},e.job.request.timeoutMs)}function Oz(e,t,n){let r=n(e);return{jobId:e.jobId,output:t.output,...r?{metadata:{transcriptPath:r,logPath:r}}:{},...t.usage?{usage:t.usage}:{}}}function kz(e,t){return`Subagent worker exited before result: ${t===null?`exit code ${e===null?`unknown`:e}`:`signal ${t}`}`}const Az=process.platform!==`win32`;function jz(e){return t=>{let n=new Mz(t,e);return e.worktreeIsolation===!1?n:xs({runner:n,worktreeAdapter:e.worktreeAdapter??ds(),hooks:t.config.hooks,hookTypeExecutors:t.hookTypeExecutors})}}var Mz=class{deps;workerPath;execArgv;killGraceMs;providerConfig;env;logsDir;constructor(e,t){this.deps=e,this.workerPath=t.workerPath,this.execArgv=t.execArgv,this.killGraceMs=t.killGraceMs??2e3,this.providerConfig=t.providerConfig,this.env=t.env,this.logsDir=t.logsDir}start(e){let t=r(this.workerPath,[],{cwd:e.request.cwd,env:{...process.env,...this.env??{}},execArgv:this.execArgv??Iz(this.workerPath),stdio:[`ignore`,`ignore`,`ignore`,`ipc`],detached:Az}),n={job:e,child:t,killGraceMs:this.killGraceMs},i=wz({runtime:n,payload:this.createStartPayload(e),resolveTranscriptPath:e=>this.resolveTranscriptPath(e)}),a=Ez(e.jobId);i.catch(()=>void 0);let o=Promise.race([i,a.promise]);o.catch(()=>void 0);let s=this.resolveTranscriptPath(e);return{jobId:e.jobId,...t.pid!==void 0&&{pid:t.pid},...s!==void 0&&{transcriptPath:s,logPath:s},result:o,cancel:async e=>{a.reject(e),await Cz(n,e)},send:async e=>{await Sz(t,{type:`send`,prompt:e})},...s!==void 0&&{readLog:async t=>Lz(e.jobId,s,t)}}}createStartPayload(e){let t=Nz(e.request.type,this.deps.customAgentRegistry);return{jobId:e.jobId,request:e.request,agentDefinition:Pz(t,e),parentConfig:this.deps.config,parentContext:this.deps.context,providerProfile:Fz(this.providerConfig,this.deps,e),permissionMode:this.deps.permissionMode,...this.logsDir?{logsDir:this.logsDir}:{}}}resolveTranscriptPath(e){if(this.logsDir)return h(this.logsDir,e.request.parentSessionId,`subagents`,`${e.jobId}.jsonl`)}};function Nz(e,t){let n=t?.(e)??Yd(e);if(!n)throw new J(`validation`,`Unknown agent type: ${e}`);return n}function Pz(e,t){return{...e,...t.request.model?{model:t.request.model}:{},...t.request.allowedTools?{tools:t.request.allowedTools}:{},...t.request.disallowedTools?{disallowedTools:t.request.disallowedTools}:{}}}function Fz(e,t,n){let r=e??t.config.provider;return{profileName:t.config.currentProvider,type:r.name,model:n.request.model??r.model,apiKey:r.apiKey,baseURL:r.baseURL,timeout:r.timeout,options:r.options}}function Iz(e){return!e.endsWith(`.ts`)||process.execArgv.some(e=>e.includes(`tsx`))?process.execArgv:[...process.execArgv,`--import`,`tsx`]}function Lz(e,t,n){return E(t)?No(e,A(t,`utf8`).split(/\r?\n/).filter(Boolean),n):{taskId:e,cursor:n,lines:[]}}function Rz(){return h(p(ke(import.meta.url)),`child-process-subagent-worker.js`)}async function zz(e,t,n){if(e.positional[0]!==`user-local`)return!1;let r=await bP({cwd:t,argv:e.positional.slice(1),format:e.format,summary:e.summary,source:e.source}),i=r.message.trimEnd();if(!r.success)throw Error(i);return n.writeLine(i),!0}function Bz(e,t){return new Date(t).getTime()-new Date(e).getTime()}function Vz(e){return new Date(e).toISOString()}function Hz(e,t,n,r,i,a){return{kind:e,fromType:t,toType:n,fromTimestamp:Vz(r),toTimestamp:Vz(i),durationMs:Bz(r,i),turnIndex:a}}function Uz(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];if(!i){r++;continue}if(i.category===`chat`&&i.type===`user`){n++;let a=i.timestamp,o=!1,s=null,c=r+1;for(;c<e.length;){let r=e[c];if(!r){c++;continue}if(r.category===`chat`&&r.type===`user`)break;if(r.category===`event`&&r.type===`tool-start`){o?s!==null&&t.push(Hz(`llm_between_tools`,`tool-end`,`tool-start`,s,r.timestamp,n)):(t.push(Hz(`user_to_first_tool`,`user`,`tool-start`,a,r.timestamp,n)),o=!0),s=null,c++;continue}if(r.category===`event`&&r.type===`tool-end`){let i=e[c-1];i&&i.category===`event`&&i.type===`tool-start`&&t.push(Hz(`tool_exec`,`tool-start`,`tool-end`,i.timestamp,r.timestamp,n)),s=r.timestamp,c++;continue}if(r.category===`event`&&r.type===`tool-summary`){s!==null&&t.push(Hz(`llm_final_response`,`tool-end`,`tool-summary`,s,r.timestamp,n)),c++;continue}if(r.category===`chat`&&r.type===`assistant`){o?s!==null&&t.push(Hz(`llm_final_response`,`tool-end`,`assistant`,s,r.timestamp,n)):t.push(Hz(`user_to_assistant`,`user`,`assistant`,a,r.timestamp,n)),c++;break}c++}r=c}else r++}return t}function Wz(e){let t=e.filter(e=>e.kind===`user_to_first_tool`||e.kind===`user_to_assistant`||e.kind===`llm_between_tools`||e.kind===`llm_final_response`),n=e.filter(e=>e.kind===`tool_exec`),r=e.filter(e=>e.kind===`user_to_assistant`),i=e=>e.length?Math.round(e.reduce((e,t)=>e+t.durationMs,0)/e.length):0,a=e=>e.length?Math.max(...e.map(e=>e.durationMs)):0;return{llmWaitMs:{avg:i(t),max:a(t),total:t.reduce((e,t)=>e+t.durationMs,0),count:t.length},toolExecMs:{avg:i(n),max:a(n),median:(e=>{if(!e.length)return 0;let t=[...e].sort((e,t)=>e.durationMs-t.durationMs),n=Math.floor(t.length/2);return t.length%2==0?Math.round(((t[n-1]?.durationMs??0)+(t[n]?.durationMs??0))/2):t[n]?.durationMs??0})(n),count:n.length},userToAssistantMs:{avg:i(r),max:a(r),count:r.length}}}function Gz(e){let t=Uz(e.history??[]),n=t.filter(e=>e.durationMs>=1e4);return{sessionId:e.id,cwd:e.cwd,createdAt:e.createdAt,totalIntervals:t.length,intervals:t,slowIntervals:n,stats:Wz(t)}}function Kz(e){let t=e.flatMap(e=>e.intervals.filter(e=>e.kind===`user_to_first_tool`||e.kind===`user_to_assistant`||e.kind===`llm_between_tools`||e.kind===`llm_final_response`)),n=e.flatMap(e=>e.intervals.filter(e=>e.kind===`tool_exec`)),r=t.length?Math.round(t.reduce((e,t)=>e+t.durationMs,0)/t.length):0,i=n.length?Math.round(n.reduce((e,t)=>e+t.durationMs,0)/n.length):0,a=0,o=``,s=0,c=``;for(let t of e)for(let e of t.intervals)e.durationMs>a&&(a=e.durationMs,o=t.sessionId,s=e.turnIndex,c=e.kind);let l=e.map(e=>e.createdAt).sort();return{sessionCount:e.length,fromDate:l[0]??``,toDate:l[l.length-1]??``,avgLlmResponseMs:r,avgToolExecMs:i,maxSingleDelayMs:a,maxSingleDelaySession:o,maxSingleDelayTurn:s,maxSingleDelayKind:c}}function qz(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:`${e}`}function Jz(e){let t=[];if(t.push(`Token usage — session ${e.sessionId}`),t.push(` total ${qz(e.totalTokens)} (prompt ${qz(e.promptTokens)} · completion ${qz(e.completionTokens)})`),e.bySource.length===0)return t.push(` (no usage recorded)`),t.join(`
325
325
  `);t.push(` by source (most tokens first):`);for(let n of e.bySource)t.push(` ${n.label.padEnd(24)} ${String(n.percentage).padStart(5)}% ${qz(n.totalTokens).padStart(7)} (${n.turns} turn${n.turns===1?``:`s`})`);return e.topConsumer&&t.push(` top consumer: ${e.topConsumer.label} (${e.topConsumer.percentage}%)`),t.join(`
326
326
  `)}function Yz(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`}function Xz(e){return new Date(e).toLocaleString(`sv-SE`,{timeZoneName:`short`}).slice(0,16)}function Zz(e){return{user_to_first_tool:`user → tool-start`,user_to_assistant:`user → assistant`,tool_exec:`tool-start → tool-end`,llm_between_tools:`tool-end → tool-start`,llm_final_response:`tool-end → assistant/summary`}[e.kind]??e.kind}function Qz(e){let{stats:t}=e,n=t.llmWaitMs.total+t.toolExecMs.avg*t.toolExecMs.count;if(n===0)return`Verdict: No timing data available.`;let r=Math.round(t.llmWaitMs.total/n*100);return`Verdict: LLM API wait ${r}% | Code processing ${100-r}%`}function $z(e){let t=[],{stats:n}=e;if(t.push(`Session: ${e.sessionId}`),t.push(`Created: ${Xz(e.createdAt)} | cwd: ${e.cwd}`),t.push(``),t.push(`Timing Summary:`),n.llmWaitMs.count>0&&t.push(` LLM API wait ${Yz(n.llmWaitMs.avg).padStart(8)} avg | ${Yz(n.llmWaitMs.max).padStart(8)} max`),n.toolExecMs.count>0&&t.push(` Tool execution ${Yz(n.toolExecMs.avg).padStart(8)} avg | ${Yz(n.toolExecMs.median).padStart(8)} median`),n.userToAssistantMs.count>0&&t.push(` user → assistant ${Yz(n.userToAssistantMs.avg).padStart(8)} avg`),n.llmWaitMs.count===0&&n.toolExecMs.count===0&&t.push(` (no intervals computed — session may have no history)`),e.slowIntervals.length>0){t.push(``),t.push(`Slow intervals (>10s):`);for(let n of e.slowIntervals)t.push(` turn ${n.turnIndex} ${Zz(n).padEnd(32)} ${Yz(n.durationMs).padStart(8)}`)}return t.push(``),t.push(Qz(e)),t.join(`
327
327
  `)}function eB(e){let t=[];return t.push(`Analyzed ${e.sessionCount} sessions (${Xz(e.fromDate)} ~ ${Xz(e.toDate)})`),t.push(` Avg LLM response: ${Yz(e.avgLlmResponseMs)}`),t.push(` Avg tool exec: ${Yz(e.avgToolExecMs)}`),e.maxSingleDelayMs>0&&t.push(` Max single delay: ${Yz(e.maxSingleDelayMs)} (${e.maxSingleDelaySession}, turn ${e.maxSingleDelayTurn}, ${e.maxSingleDelayKind})`),t.join(`
@@ -331,12 +331,12 @@ _(interrupted)_`:``)):t})})]})});function SL({entry:e}){let t=e.data,n=t?.tools,
331
331
  `),process.exit(1)),process.stdout.write(eB(Kz(e))+`
332
332
  `);return}let i=r[r.length-1];i||(process.stderr.write(`No sessions found.
333
333
  `),process.exit(1)),process.stdout.write($z(Gz(i))+`
334
- `)}const uB=()=>Gb(import.meta.url);async function dB(e){let t=nt({input:process.stdin,output:process.stdout});try{let n=(await t.question(e)).trim().toLowerCase();return n===`y`||n===`yes`}finally{t.close()}}async function fB(e,t){let n=Wm();if(!T(n))return e.writeLine(`No user settings found.`),0;if(!t.yes){if(!t.isTTY)return e.writeError(`--reset deletes ${n}. Refusing without confirmation in non-interactive mode — pass --yes to proceed.`),1;if(!await(t.confirm??dB)(`Delete ${n}? [y/N] `))return e.writeLine(`Reset cancelled.`),1}let r=Pb();return r.deleted?e.writeLine(`Deleted ${r.path}`):e.writeLine(`No user settings found.`),0}const pB={anthropic:{host:`api.anthropic.com`,port:443},openai:{host:`api.openai.com`,port:443},gemini:{host:`generativelanguage.googleapis.com`,port:443},deepseek:{host:`api.deepseek.com`,port:443},qwen:{host:`dashscope.aliyuncs.com`,port:443}};function mB(){let[e]=process.versions.node.split(`.`).map(Number);return e!==void 0&&e>=22?{label:`Node.js version`,status:`ok`,message:`v${process.versions.node}`}:{label:`Node.js version`,status:`fail`,message:`v${process.versions.node} (requires >=22)\n nvm: nvm install 22 && nvm use 22\n Volta: volta install node@22`}}function hB(e){return{label:`robota version`,status:`ok`,message:e}}function gB(e,t,n){try{let r=B_(e,{providerDefinitions:t,env:n}),i=r.source===`env-default`?`env-default via ${r.sourceEnvVar??`environment`}`:`settings profile`,a=r.model===void 0?``:` (${r.model})`;return{label:`API key`,status:`ok`,message:`${r.name}${a} — ${i}`}}catch(e){return{label:`API key`,status:`fail`,message:`${e instanceof Error?e.message:String(e)}\n Set ANTHROPIC_API_KEY or run: robota --configure\n Get key: https://console.anthropic.com/settings/keys`}}}function _B(e){try{return JSON.parse(O(e,`utf-8`)),`ok`}catch{return`corrupt`}}function vB(e){let t=O_(e).filter(e=>T(e));return t.length===0?[{label:`Settings file`,status:`warn`,message:`Not found — run: robota --configure`}]:t.map(e=>_B(e)===`corrupt`?{label:`Settings file`,status:`fail`,message:`${e} — invalid JSON\n Fix or delete the file, or run: robota --configure`}:{label:`Settings file`,status:`ok`,message:e})}function yB(e){try{let t=JSON.parse(O(e,`utf-8`));return typeof t.currentProvider==`string`?t.currentProvider:void 0}catch{return}}function bB(e){let t=h(e,`.robota`,`settings.json`),n=h(process.env.HOME??``,`.robota`,`settings.json`),r=T(t)?t:T(n)?n:void 0;if(r!==void 0){let e=(yB(r)??``).toLowerCase(),t=Object.entries(pB).find(([t])=>e.startsWith(t));if(t)return t[1]}return pB.anthropic}function xB(){let e=process.env.TERM_PROGRAM??`unknown`;return process.platform===`darwin`&&e===`Apple_Terminal`?{label:`Terminal`,status:`warn`,message:`macOS Terminal.app — CJK/IME input may be unstable
334
+ `)}const uB=()=>Gb(import.meta.url);async function dB(e){let t=nt({input:process.stdin,output:process.stdout});try{let n=(await t.question(e)).trim().toLowerCase();return n===`y`||n===`yes`}finally{t.close()}}async function fB(e,t){let n=Wm();if(!E(n))return e.writeLine(`No user settings found.`),0;if(!t.yes){if(!t.isTTY)return e.writeError(`--reset deletes ${n}. Refusing without confirmation in non-interactive mode — pass --yes to proceed.`),1;if(!await(t.confirm??dB)(`Delete ${n}? [y/N] `))return e.writeLine(`Reset cancelled.`),1}let r=Pb();return r.deleted?e.writeLine(`Deleted ${r.path}`):e.writeLine(`No user settings found.`),0}const pB={anthropic:{host:`api.anthropic.com`,port:443},openai:{host:`api.openai.com`,port:443},gemini:{host:`generativelanguage.googleapis.com`,port:443},deepseek:{host:`api.deepseek.com`,port:443},qwen:{host:`dashscope.aliyuncs.com`,port:443}};function mB(){let[e]=process.versions.node.split(`.`).map(Number);return e!==void 0&&e>=22?{label:`Node.js version`,status:`ok`,message:`v${process.versions.node}`}:{label:`Node.js version`,status:`fail`,message:`v${process.versions.node} (requires >=22)\n nvm: nvm install 22 && nvm use 22\n Volta: volta install node@22`}}function hB(e){return{label:`robota version`,status:`ok`,message:e}}function gB(e,t,n){try{let r=B_(e,{providerDefinitions:t,env:n}),i=r.source===`env-default`?`env-default via ${r.sourceEnvVar??`environment`}`:`settings profile`,a=r.model===void 0?``:` (${r.model})`;return{label:`API key`,status:`ok`,message:`${r.name}${a} — ${i}`}}catch(e){return{label:`API key`,status:`fail`,message:`${e instanceof Error?e.message:String(e)}\n Set ANTHROPIC_API_KEY or run: robota --configure\n Get key: https://console.anthropic.com/settings/keys`}}}function _B(e){try{return JSON.parse(A(e,`utf-8`)),`ok`}catch{return`corrupt`}}function vB(e){let t=O_(e).filter(e=>E(e));return t.length===0?[{label:`Settings file`,status:`warn`,message:`Not found — run: robota --configure`}]:t.map(e=>_B(e)===`corrupt`?{label:`Settings file`,status:`fail`,message:`${e} — invalid JSON\n Fix or delete the file, or run: robota --configure`}:{label:`Settings file`,status:`ok`,message:e})}function yB(e){try{let t=JSON.parse(A(e,`utf-8`));return typeof t.currentProvider==`string`?t.currentProvider:void 0}catch{return}}function bB(e){let t=h(e,`.robota`,`settings.json`),n=h(process.env.HOME??``,`.robota`,`settings.json`),r=E(t)?t:E(n)?n:void 0;if(r!==void 0){let e=(yB(r)??``).toLowerCase(),t=Object.entries(pB).find(([t])=>e.startsWith(t));if(t)return t[1]}return pB.anthropic}function xB(){let e=process.env.TERM_PROGRAM??`unknown`;return process.platform===`darwin`&&e===`Apple_Terminal`?{label:`Terminal`,status:`warn`,message:`macOS Terminal.app — CJK/IME input may be unstable
335
335
  Recommendation: use iTerm2 (https://iterm2.com)`}:{label:`Terminal`,status:`ok`,message:e}}function SB(e){let t=`Network (${e.host})`;return new Promise(n=>{let r=Date.now(),i=rt({host:e.host,port:e.port}),a=setTimeout(()=>{i.destroy(),n({label:t,status:`fail`,message:`timeout (3s)`})},3e3);i.on(`connect`,()=>{clearTimeout(a),i.destroy(),n({label:t,status:`ok`,message:`reachable (${Date.now()-r}ms)`})}),i.on(`error`,e=>{clearTimeout(a),n({label:t,status:`warn`,message:`${e.message}\n Check proxy settings or firewall`})})})}async function CB(e,t={checkNetwork:SB}){e.terminal.writeLine(`
336
336
  robota diagnose
337
337
  `);let n=bB(e.cwd),r=t.providerDefinitions??EO(),i=t.env??process.env,a=[mB(),hB(e.version),gB(e.cwd,r,i),...vB(e.cwd),xB(),await t.checkNetwork(n)],o=0,s=0;for(let t of a){let n=t.status===`ok`?`✓`:t.status===`warn`?`⚠`:`✗`,r=t.message.split(`
338
- `);e.terminal.writeLine(` ${n} ${t.label}: ${r[0]}`);for(let t of r.slice(1))e.terminal.writeLine(` ${t}`);t.status===`fail`&&o++,t.status===`warn`&&s++}return e.terminal.writeLine(``),o===0&&s===0?e.terminal.writeLine(`✓ All checks passed. robota is ready to use.`):o>0?e.terminal.writeLine(`✗ ${o} issue(s) found. Fix the items above to use robota.`):e.terminal.writeLine(`⚠ ${s} warning(s). robota may work but check the items above.`),e.terminal.writeLine(``),o}const wB=`robota`,TB={permissions:{allow:[`Read(.robota/**)`,`Read(.claude/**)`,`Read(.agents/**)`],deny:[]}};function EB(e){let t=h(e,`settings.json`);if(!T(t))return{};let n=O(t,`utf8`);try{return JSON.parse(n)}catch{return null}}var DB=class extends Error{constructor(e){super(`Cannot ask "${e}" in a non-interactive shell. Re-run with --yes to accept the defaults.`),this.name=`InitPromptUnavailableError`}};async function OB(e,t,n){if(n.yes||n.ci)return n.terminal.writeLine(`${e} → ${t?`Y`:`N`} (${n.yes?`--yes`:`CI`}: using default)`),t;if(!n.isTTY)throw new DB(e);let r=await n.promptFn(`${e} [y/N] `);return r.toLowerCase()===`y`||r.toLowerCase()===`yes`}async function kB(e,t,n={}){t.writeLine(``),t.writeLine(`${wB} project initialization`),t.writeLine(`─`.repeat(40));let r={yes:n.yes===!0,ci:n.ci??process.env.CI===`true`,isTTY:n.isTTY??process.stdin.isTTY===!0,promptFn:n.promptFn??dx,terminal:t},i=dp(e).settings,a=p(i),o=h(e,`AGENTS.md`),s=h(e,`.claude`),c=T(s),l=T(i),u=T(o);if(l&&u&&(t.writeLine(``),t.writeLine(`Both AGENTS.md and .robota/settings.json already exist.`),!await OB(`Overwrite existing files?`,!1,r))){t.writeLine(`Init cancelled.`);return}let d={...TB};if(c&&(t.writeLine(``),t.writeLine(`Detected .claude/ directory (Claude Code configuration).`),await OB(`Migrate Claude Code settings to .robota/?`,!1,r))){let e=EB(s);if(e===null)t.writeLine(`Warning: .claude/settings.json could not be parsed — skipping migration.`);else{let n=e.permissions;d={...e,permissions:{...typeof e.permissions==`object`&&e.permissions!==null?e.permissions:{},allow:[...TB.permissions.allow,...n?.allow??[]],deny:n?.deny??[]}},t.writeLine(`Settings imported from .claude/settings.json.`)}}D(a,{recursive:!0}),k(i,JSON.stringify(d,null,2)+`
339
- `,`utf8`),t.writeLine(``),t.writeLine(`Created: .robota/settings.json`),k(o,`# AGENTS.md — Project Agent Guidelines
338
+ `);e.terminal.writeLine(` ${n} ${t.label}: ${r[0]}`);for(let t of r.slice(1))e.terminal.writeLine(` ${t}`);t.status===`fail`&&o++,t.status===`warn`&&s++}return e.terminal.writeLine(``),o===0&&s===0?e.terminal.writeLine(`✓ All checks passed. robota is ready to use.`):o>0?e.terminal.writeLine(`✗ ${o} issue(s) found. Fix the items above to use robota.`):e.terminal.writeLine(`⚠ ${s} warning(s). robota may work but check the items above.`),e.terminal.writeLine(``),o}const wB=`robota`,TB={permissions:{allow:[`Read(.robota/**)`,`Read(.claude/**)`,`Read(.agents/**)`],deny:[]}};function EB(e){let t=h(e,`settings.json`);if(!E(t))return{};let n=A(t,`utf8`);try{return JSON.parse(n)}catch{return null}}var DB=class extends Error{constructor(e){super(`Cannot ask "${e}" in a non-interactive shell. Re-run with --yes to accept the defaults.`),this.name=`InitPromptUnavailableError`}};async function OB(e,t,n){if(n.yes||n.ci)return n.terminal.writeLine(`${e} → ${t?`Y`:`N`} (${n.yes?`--yes`:`CI`}: using default)`),t;if(!n.isTTY)throw new DB(e);let r=await n.promptFn(`${e} [y/N] `);return r.toLowerCase()===`y`||r.toLowerCase()===`yes`}async function kB(e,t,n={}){t.writeLine(``),t.writeLine(`${wB} project initialization`),t.writeLine(`─`.repeat(40));let r={yes:n.yes===!0,ci:n.ci??process.env.CI===`true`,isTTY:n.isTTY??process.stdin.isTTY===!0,promptFn:n.promptFn??dx,terminal:t},i=dp(e).settings,a=p(i),o=h(e,`AGENTS.md`),s=h(e,`.claude`),c=E(s),l=E(i),u=E(o);if(l&&u&&(t.writeLine(``),t.writeLine(`Both AGENTS.md and .robota/settings.json already exist.`),!await OB(`Overwrite existing files?`,!1,r))){t.writeLine(`Init cancelled.`);return}let d={...TB};if(c&&(t.writeLine(``),t.writeLine(`Detected .claude/ directory (Claude Code configuration).`),await OB(`Migrate Claude Code settings to .robota/?`,!1,r))){let e=EB(s);if(e===null)t.writeLine(`Warning: .claude/settings.json could not be parsed — skipping migration.`);else{let n=e.permissions;d={...e,permissions:{...typeof e.permissions==`object`&&e.permissions!==null?e.permissions:{},allow:[...TB.permissions.allow,...n?.allow??[]],deny:n?.deny??[]}},t.writeLine(`Settings imported from .claude/settings.json.`)}}O(a,{recursive:!0}),ae(i,JSON.stringify(d,null,2)+`
339
+ `,`utf8`),t.writeLine(``),t.writeLine(`Created: .robota/settings.json`),ae(o,`# AGENTS.md — Project Agent Guidelines
340
340
 
341
341
  This file guides the AI agent working in this project. Customize it for your project.
342
342
 
@@ -366,7 +366,7 @@ npm run build
366
366
  ## Important Notes
367
367
 
368
368
  <!-- Anything the agent should know before making changes -->
369
- `,`utf8`),t.writeLine(`Created: AGENTS.md`),t.writeLine(``),t.writeLine(`Initialization complete.`),t.writeLine(``),t.writeLine(`Next steps:`),t.writeLine(` 1. Edit AGENTS.md to describe your project conventions`),t.writeLine(` 2. Run \`${wB} --configure\` to set up your AI provider`),t.writeLine(` 3. Run \`${wB}\` to start the assistant`),t.writeLine(``),n.onProviderSetup!==void 0&&(r.isTTY||r.yes||r.ci)&&await OB(`Would you like to set up a provider now?`,!1,r)&&await n.onProviderSetup()}function AB(e=fp().onboarded){return!T(e)}function jB(e=fp().onboarded){D(p(e),{recursive:!0}),k(e,new Date().toISOString())}const MB=`
369
+ `,`utf8`),t.writeLine(`Created: AGENTS.md`),t.writeLine(``),t.writeLine(`Initialization complete.`),t.writeLine(``),t.writeLine(`Next steps:`),t.writeLine(` 1. Edit AGENTS.md to describe your project conventions`),t.writeLine(` 2. Run \`${wB} --configure\` to set up your AI provider`),t.writeLine(` 3. Run \`${wB}\` to start the assistant`),t.writeLine(``),n.onProviderSetup!==void 0&&(r.isTTY||r.yes||r.ci)&&await OB(`Would you like to set up a provider now?`,!1,r)&&await n.onProviderSetup()}function AB(e=fp().onboarded){return!E(e)}function jB(e=fp().onboarded){O(p(e),{recursive:!0}),ae(e,new Date().toISOString())}const MB=`
370
370
  ╭─────────────────────────────────────────────────────────────╮
371
371
  │ Welcome to ${wB}! — AI coding assistant │
372
372
  │ │
@@ -387,16 +387,18 @@ npm run build
387
387
  ⚠ macOS Terminal.app detected: CJK/IME input may be unstable.
388
388
  Recommended: use iTerm2 (https://iterm2.com) for Korean/Japanese/Chinese input.
389
389
  Or use headless mode: robota -p "your prompt"
390
- `)}function FB(e){let t=e.lastIndexOf(`[`);if(t<=0||!e.endsWith(`]`))return;let n=e.slice(0,t),r=e.slice(t+1,e.length-1);if(/^\d+$/.test(r))return{portKey:n,index:Number.parseInt(r,10)}}const IB={CREATED:`created`,QUEUED:`queued`,RUNNING:`running`,SUCCESS:`success`,FAILED:`failed`,CANCELLED:`cancelled`},X={CREATED:`created`,QUEUED:`queued`,RUNNING:`running`,SUCCESS:`success`,FAILED:`failed`,UPSTREAM_FAILED:`upstream_failed`,SKIPPED:`skipped`,CANCELLED:`cancelled`},LB={STARTED:`execution.started`,COMPLETED:`execution.completed`,FAILED:`execution.failed`},RB={STARTED:`task.started`,COMPLETED:`task.completed`,FAILED:`task.failed`},zB={[`${IB.CREATED}:QUEUE`]:IB.QUEUED,[`${IB.CREATED}:CANCEL`]:IB.CANCELLED,[`${IB.QUEUED}:START`]:IB.RUNNING,[`${IB.QUEUED}:CANCEL`]:IB.CANCELLED,[`${IB.RUNNING}:COMPLETE_SUCCESS`]:IB.SUCCESS,[`${IB.RUNNING}:COMPLETE_FAILURE`]:IB.FAILED,[`${IB.RUNNING}:CANCEL`]:IB.CANCELLED};function BB(e,t){return{code:`DAG_STATE_TRANSITION_INVALID`,category:`state_transition`,message:`DagRun transition is not allowed: ${e} -> ${t}`,retryable:!1,context:{currentStatus:e,event:t}}}function VB(e){return`run.${e}`}var HB=class{static transition(e,t){let n=zB[`${e}:${t}`];return n?{ok:!0,value:{nextStatus:n,domainEvents:[VB(n)]}}:{ok:!1,error:BB(e,t)}}};const UB={[`${X.CREATED}:QUEUE`]:X.QUEUED,[`${X.CREATED}:CANCEL`]:X.CANCELLED,[`${X.QUEUED}:START`]:X.RUNNING,[`${X.QUEUED}:UPSTREAM_FAIL`]:X.UPSTREAM_FAILED,[`${X.QUEUED}:SKIP`]:X.SKIPPED,[`${X.QUEUED}:CANCEL`]:X.CANCELLED,[`${X.RUNNING}:COMPLETE_SUCCESS`]:X.SUCCESS,[`${X.RUNNING}:COMPLETE_FAILURE`]:X.FAILED,[`${X.RUNNING}:CANCEL`]:X.CANCELLED,[`${X.FAILED}:RETRY`]:X.QUEUED};function WB(e,t){return{code:`DAG_STATE_TRANSITION_INVALID`,category:`state_transition`,message:`TaskRun transition is not allowed: ${e} -> ${t}`,retryable:!1,context:{currentStatus:e,event:t}}}function GB(e){return`task.${e}`}var KB=class{static transition(e,t){let n=UB[`${e}:${t}`];return n?{ok:!0,value:{nextStatus:n,domainEvents:[GB(n)]}}:{ok:!1,error:WB(e,t)}}};function qB(e,t,n,r,i,a,o){return{code:t,category:e,message:n,retryable:r,context:i,fix:a,agentHint:o}}function Z(e,t,n,r,i){return qB(`validation`,e,t,!1,n,r,i)}function JB(e,t,n,r,i){return qB(`dispatch`,e,t,!0,n,r,i)}function YB(e,t,n,r,i,a){return qB(`task_execution`,e,t,n,r,i,a)}function XB(e){let t=Date.parse(e);return Number.isNaN(t)?{ok:!1,error:Z(`DAG_VALIDATION_INVALID_LOGICAL_DATE`,`logicalDate must be a valid ISO-8601 datetime string`,{logicalDate:e})}:{ok:!0,value:new Date(t).toISOString()}}var ZB=class{clock;constructor(e){this.clock=e}resolve(e,t){let n=this.clock.nowIso();if(e===`scheduled`){if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_MISSING_LOGICAL_DATE`,`scheduled trigger requires logicalDate`,{trigger:e})};let r=XB(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}if(!t)return{ok:!0,value:{trigger:e,logicalDate:n,requestedAt:n}};let r=XB(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}},QB=class{assertWithinBudget(e,t,n){if(t<0)return{ok:!1,error:Z(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be zero or positive`,{nextEstimatedCredits:t})};let r=e+t;return typeof n==`number`&&r>n?{ok:!1,error:Z(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds runCreditLimit`,{nextTotalCredits:r,runCreditLimit:n})}:{ok:!0,value:r}}},$B=class{lifecycleFactory;costPolicyEvaluator;constructor(e,t){this.lifecycleFactory=e,this.costPolicyEvaluator=t}async runNode(e){let t=this.lifecycleFactory.create(e.context.nodeDefinition.nodeType);if(!t.ok)return t;let n=await t.value.initialize(e.context);if(!n.ok)return n;let r=await t.value.validateInput(e.input,e.context);if(!r.ok)return await t.value.dispose(e.context),r;let i=await t.value.estimateCost(e.input,e.context);if(!i.ok)return await t.value.dispose(e.context),i;let a=this.costPolicyEvaluator.assertWithinBudget(e.context.currentTotalCredits,i.value.estimatedCredits,e.context.runCreditLimit);if(!a.ok)return await t.value.dispose(e.context),a;let o=await t.value.execute(e.input,e.context);if(!o.ok)return await t.value.dispose(e.context),o;let s=await t.value.validateOutput(o.value,e.context);return s.ok?(await t.value.dispose(e.context)).ok?{ok:!0,value:{output:o.value,estimatedCredits:i.value.estimatedCredits,totalCredits:a.value}}:{ok:!1,error:YB(`DAG_TASK_EXECUTION_DISPOSE_FAILED`,`Node dispose step failed after execution`,!1,{nodeType:e.context.nodeDefinition.nodeType,taskRunId:e.context.taskRunId})}:(await t.value.dispose(e.context),s)}},eV=class{create(e){return{ok:!1,error:Z(`DAG_VALIDATION_NODE_LIFECYCLE_NOT_REGISTERED`,`Node lifecycle is not registered for nodeType`,{nodeType:e})}}},tV=class{nodeManifestRegistry;lifecycleFactory;runner;constructor(e,t){this.nodeManifestRegistry=e,this.lifecycleFactory=t??new eV,this.runner=new $B(this.lifecycleFactory,new QB)}async execute(e){if(!e.nodeDefinition)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_DEFINITION_MISSING`,`Task execution requires nodeDefinition in execution input`,{nodeId:e.nodeId})};let t=this.nodeManifestRegistry.getManifest(e.nodeDefinition.nodeType);if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_MANIFEST_NOT_FOUND`,`Node manifest is not registered for nodeType`,{nodeType:e.nodeDefinition.nodeType})};let n=await this.runner.runNode({input:e.input,context:{dagId:e.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeDefinition:e.nodeDefinition,nodeManifest:t,attempt:e.attempt,executionPath:e.executionPath,runCreditLimit:e.costPolicy?.runCreditLimit,currentTotalCredits:e.currentTotalCredits??0}});return n.ok?{ok:!0,output:n.value.output,estimatedCredits:n.value.estimatedCredits,totalCredits:n.value.totalCredits}:n}};function nV(e,t){return`${e}:${t}`}var rV=class{definitions=new Map;latestPublishedVersionByDagId=new Map;dagRuns=new Map;taskRuns=new Map;async saveDefinition(e){let t=`${e.dagId}:${e.version}`;if(this.definitions.set(t,e),e.status===`published`){let t=this.latestPublishedVersionByDagId.get(e.dagId)??0;e.version>t&&this.latestPublishedVersionByDagId.set(e.dagId,e.version)}}async getDefinition(e,t){let n=`${e}:${t}`;return this.definitions.get(n)}async listDefinitions(){return[...this.definitions.values()].sort((e,t)=>e.dagId.localeCompare(t.dagId)||e.version-t.version)}async listDefinitionsByDagId(e){return[...this.definitions.values()].filter(t=>t.dagId===e).sort((e,t)=>e.version-t.version)}async getLatestPublishedDefinition(e){let t=this.latestPublishedVersionByDagId.get(e);if(t)return this.definitions.get(`${e}:${t}`)}async deleteDefinition(e,t){this.definitions.delete(`${e}:${t}`);let n=[...this.definitions.values()].filter(t=>t.dagId===e&&t.status===`published`).sort((e,t)=>e.version-t.version);if(n.length===0){this.latestPublishedVersionByDagId.delete(e);return}this.latestPublishedVersionByDagId.set(e,n[n.length-1].version)}async createDagRun(e){this.dagRuns.set(e.dagRunId,e)}async getDagRun(e){return this.dagRuns.get(e)}async listDagRuns(){return[...this.dagRuns.values()].sort((e,t)=>e.dagRunId.localeCompare(t.dagRunId))}async getDagRunByRunKey(e){for(let t of this.dagRuns.values())if(t.runKey===e)return t}async updateDagRunStatus(e,t,n){let r=this.dagRuns.get(e);if(!r)return;let i={...r,status:t,endedAt:n};this.dagRuns.set(e,i)}async deleteDagRun(e){this.dagRuns.delete(e)}async createTaskRun(e){let t=nV(e.dagRunId,e.taskRunId);this.taskRuns.set(t,e)}async getTaskRun(e){for(let t of this.taskRuns.values())if(t.taskRunId===e)return t}async listTaskRunsByDagRunId(e){let t=[];for(let n of this.taskRuns.values())n.dagRunId===e&&t.push(n);return t}async deleteTaskRunsByDagRunId(e){for(let[t,n]of this.taskRuns.entries())n.dagRunId===e&&this.taskRuns.delete(t)}async updateTaskRunStatus(e,t,n){for(let[r,i]of this.taskRuns.entries()){if(i.taskRunId!==e)continue;let a={...i,status:t,errorCode:n?.code,errorMessage:n?.message};this.taskRuns.set(r,a);return}}async saveTaskRunSnapshots(e,t,n,r,i){for(let[a,o]of this.taskRuns.entries()){if(o.taskRunId!==e)continue;let s={...o,inputSnapshot:typeof t==`string`?t:o.inputSnapshot,outputSnapshot:typeof n==`string`?n:o.outputSnapshot,estimatedCredits:typeof r==`number`?r:o.estimatedCredits,totalCredits:typeof i==`number`?i:o.totalCredits};this.taskRuns.set(a,s);return}}async incrementTaskAttempt(e){for(let[t,n]of this.taskRuns.entries()){if(n.taskRunId!==e)continue;let r={...n,attempt:n.attempt+1};this.taskRuns.set(t,r);return}}},iV=class{pendingQueue=[];inFlight=new Map;waiters=[];async enqueue(e){this.pendingQueue.push(e),this.notifyNextWaiter()}async dequeue(e,t,n=0){let r=this.tryDequeue(e,t);return r||n<=0?r:(await this.waitForMessage(n),this.tryDequeue(e,t))}async ack(e){this.inFlight.delete(e)}async nack(e){let t=this.inFlight.get(e);t&&(this.inFlight.delete(e),this.pendingQueue.unshift(t.message),this.notifyNextWaiter())}tryDequeue(e,t){this.requeueExpiredMessages();let n=this.pendingQueue.shift();if(!n)return;let r=Date.now();return this.inFlight.set(n.messageId,{message:n,ownerId:e,visibleAtEpochMs:r+t}),n}requeueExpiredMessages(){let e=Date.now();for(let[t,n]of this.inFlight.entries())n.visibleAtEpochMs>e||(this.inFlight.delete(t),this.pendingQueue.push(n.message))}async waitForMessage(e){return new Promise(t=>{let n={resolve:()=>{clearTimeout(n.timeout),this.removeWaiter(n),t()},timeout:setTimeout(()=>{n.resolve()},e)};this.waiters.push(n)})}notifyNextWaiter(){this.waiters.shift()?.resolve()}removeWaiter(e){let t=this.waiters.indexOf(e);t>=0&&this.waiters.splice(t,1)}},aV=class{records=new Map;async acquire(e,t,n){let r=new Date().toISOString(),i=Date.now(),a=this.records.get(e);if(a&&Date.parse(a.leaseUntil)>i)return;let o={leaseKey:e,ownerId:t,acquiredAt:r,leaseUntil:new Date(i+n).toISOString()};return this.records.set(e,o),o}async renew(e,t,n){let r=this.records.get(e);if(!r||r.ownerId!==t)return;let i=Date.now(),a={leaseKey:e,ownerId:t,acquiredAt:r.acquiredAt,leaseUntil:new Date(i+n).toISOString()};return this.records.set(e,a),a}async release(e,t){let n=this.records.get(e);!n||n.ownerId!==t||this.records.delete(e)}async get(e){return this.records.get(e)}},oV=class{nowIso(){return new Date().toISOString()}nowEpochMs(){return Date.now()}};function sV(e,t,n){let r=n.issues[0];return Z(`DAG_VALIDATION_NODE_CONFIG_SCHEMA_INVALID`,`Node config does not satisfy schema: ${r?.path.join(`.`)??`config`} ${r?.message??`Invalid config`}`,{nodeId:t.nodeDefinition.nodeId,nodeType:e,issueCount:n.issues.length})}var Q=class{defaultInputPort;defaultOutputPort;taskHandler;constructor(){this.taskHandler={initialize:async e=>{let t=this.parseNodeConfig(e);return t.ok?this.initializeWithConfig(e,t.value):t},validateInput:async(e,t)=>{let n=this.parseNodeConfig(t);return n.ok?this.validateInputWithConfig(e,t,n.value):n},estimateCost:async(e,t)=>{let n=this.parseNodeConfig(t);return n.ok?this.estimateCostWithConfig(e,t,n.value):n},execute:async(e,t)=>{let n=this.parseNodeConfig(t);return n.ok?this.executeWithConfig(e,t,n.value):n},validateOutput:async(e,t)=>{let n=this.parseNodeConfig(t);return n.ok?this.validateOutputWithConfig(e,t,n.value):n},dispose:async e=>{let t=this.parseNodeConfig(e);return t.ok?this.disposeWithConfig(e,t.value):t}}}parseNodeConfig(e){let t=this.configSchemaDefinition.safeParse(e.nodeDefinition.config);return t.success?{ok:!0,value:t.data}:{ok:!1,error:sV(this.nodeType,e,t.error)}}async initializeWithConfig(e,t){return{ok:!0,value:void 0}}async validateInputWithConfig(e,t,n){return{ok:!0,value:void 0}}async validateOutputWithConfig(e,t,n){return{ok:!0,value:void 0}}async disposeWithConfig(e,t){return{ok:!0,value:void 0}}};const cV=`asset://`;var lV=class e{value;constructor(e){this.value=e}static fromAssetReference(t){return t.referenceType===`asset`?new e({referenceType:`asset`,assetId:t.assetId,mediaType:t.mediaType,name:t.name,sizeBytes:t.sizeBytes}):new e({referenceType:`uri`,uri:t.uri,mediaType:t.mediaType,name:t.name,sizeBytes:t.sizeBytes})}static fromBinary(t){if(typeof t.assetId==`string`&&t.assetId.trim().length>0)return{ok:!0,value:new e({referenceType:`asset`,assetId:t.assetId.trim(),mediaType:t.mimeType,sizeBytes:t.sizeBytes})};if(t.uri.startsWith(cV)){let n=t.uri.slice(8).trim();return n.length===0?{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_INVALID`,`Binary asset URI must include non-empty assetId`)}:{ok:!0,value:new e({referenceType:`asset`,assetId:n,mediaType:t.mimeType,sizeBytes:t.sizeBytes})}}return{ok:!0,value:new e({referenceType:`uri`,uri:t.uri,mediaType:t.mimeType,sizeBytes:t.sizeBytes})}}static fromCandidate(e,t){let n=typeof e.assetId==`string`&&(t?.allowEmptyAssetId===!0||e.assetId.trim().length>0),r=typeof e.uri==`string`&&(t?.allowEmptyUri===!0||e.uri.trim().length>0);return n===r?{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_XOR_REQUIRED`,`Exactly one of assetId or uri must be provided`)}:e.referenceType===`asset`&&!n?{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_TYPE_MISMATCH`,`referenceType asset requires assetId`)}:e.referenceType===`uri`&&!r?{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_TYPE_MISMATCH`,`referenceType uri requires uri`)}:this.buildFromValidatedCandidate(e,n)}static buildFromValidatedCandidate(t,n){return n&&typeof t.assetId==`string`?{ok:!0,value:new e({referenceType:`asset`,assetId:t.assetId.trim(),mediaType:t.mediaType,name:t.name,sizeBytes:t.sizeBytes})}:typeof t.uri==`string`?{ok:!0,value:new e({referenceType:`uri`,uri:t.uri,mediaType:t.mediaType,name:t.name,sizeBytes:t.sizeBytes})}:{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_INVALID`,`uri must be a string when referenceType is uri`)}}isAsset(){return this.value.referenceType===`asset`}isUri(){return this.value.referenceType===`uri`}assetId(){return this.value.assetId}uri(){return this.value.uri}mediaType(){return this.value.mediaType}toAssetIdOrUri(){return this.value.referenceType===`asset`&&typeof this.value.assetId==`string`?{referenceType:`asset`,assetId:this.value.assetId}:{referenceType:`uri`,uri:this.value.uri??``}}toAssetContentUrl(e){if(!(!this.isAsset()||typeof this.value.assetId!=`string`))return`${e.replace(/\/$/,``)}/view?filename=${encodeURIComponent(this.value.assetId)}`}toBinary(e,t){let n=typeof this.value.mediaType==`string`&&this.value.mediaType.trim().length>0?this.value.mediaType:t;return this.value.referenceType===`asset`&&typeof this.value.assetId==`string`?{kind:e,mimeType:n,uri:`${cV}${this.value.assetId}`,referenceType:`asset`,assetId:this.value.assetId,sizeBytes:this.value.sizeBytes}:{kind:e,mimeType:n,uri:this.value.uri??``,referenceType:`uri`,sizeBytes:this.value.sizeBytes}}};function uV(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))return{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be binary payload object`,{nodeId:t,key:n,expectedType:`binary`})};let i=e;if(!(i.kind===`image`||i.kind===`video`||i.kind===`audio`||i.kind===`file`)||typeof i.mimeType!=`string`||typeof i.uri!=`string`)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be valid binary payload`,{nodeId:t,key:n,expectedType:`binary`})};let a=i.kind;return r&&a!==r?{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input binary kind does not match expected kind`,{nodeId:t,key:n,expectedKind:r,actualKind:a})}:{ok:!0,value:{kind:a,mimeType:i.mimeType,uri:i.uri,referenceType:i.referenceType===`asset`||i.referenceType===`uri`?i.referenceType:void 0,assetId:typeof i.assetId==`string`?i.assetId:void 0,sizeBytes:typeof i.sizeBytes==`number`?i.sizeBytes:void 0}}}var $=class{input;nodeId;output={};constructor(e,t){this.input=e,this.nodeId=t}getInput(e){return this.input[e]}requireInput(e){let t=this.getInput(e);return t===void 0?{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_MISSING`,`Node input key is missing`,{nodeId:this.nodeId,key:e})}:{ok:!0,value:t}}requireInputString(e){let t=this.requireInput(e);return t.ok?typeof t.value==`string`?{ok:!0,value:t.value}:{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be string`,{nodeId:this.nodeId,key:e,expectedType:`string`})}:t}requireInputArray(e){let t=this.getInput(e);if(Array.isArray(t))return{ok:!0,value:t};let n=this.collectListHandleValues(e);return n?{ok:!0,value:n}:t===void 0?{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_MISSING`,`Node input key is missing`,{nodeId:this.nodeId,key:e})}:{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be array`,{nodeId:this.nodeId,key:e,expectedType:`array`})}}requireInputBinary(e,t){let n=this.requireInput(e);return n.ok?uV(n.value,this.nodeId,e,t):n}requireInputBinaryList(e,t,n){let r=this.requireInputArray(e);if(!r.ok)return r;let i=r.value;if(typeof n?.minItems==`number`&&i.length<n.minItems)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_MIN_ITEMS_NOT_SATISFIED`,`Node input list does not satisfy minItems`,{nodeId:this.nodeId,key:e,minItems:n.minItems,actualItems:i.length})};if(typeof n?.maxItems==`number`&&i.length>n.maxItems)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_MAX_ITEMS_EXCEEDED`,`Node input list exceeds maxItems`,{nodeId:this.nodeId,key:e,maxItems:n.maxItems,actualItems:i.length})};let a=[];for(let[n,r]of i.entries()){let i=uV(r,this.nodeId,`${e}[${n}]`,t);if(!i.ok)return i;a.push(i.value)}return{ok:!0,value:a}}requireInputMediaReference(e,t){let n=this.requireInput(e);return n.ok?this.parseMediaReferenceValue(n.value,e,t):n}requireInputBinaryReference(e,t){let n=this.requireInputBinary(e,t);if(!n.ok)return n;let r=lV.fromBinary(n.value);return r.ok?r:{ok:!1,error:Z(r.error.code,r.error.message,{nodeId:this.nodeId,key:e,...r.error.context??{}})}}setOutput(e,t){this.output[e]=t}toOutput(){return{...this.output}}collectListHandleValues(e){let t=new Map;for(let[n,r]of Object.entries(this.input)){let i=FB(n);!i||i.portKey!==e||t.set(i.index,r)}if(t.size===0)return;let n=[...t.keys()].sort((e,t)=>e-t),r=n[n.length-1]+1;if(n.length!==r)return;let i=[];for(let e=0;e<r;e+=1){let n=t.get(e);if(n===void 0)return;i.push(n)}return i}parseMediaReferenceValue(e,t,n){if(typeof e==`string`){if(n?.allowStringAssetUri===!0&&e.startsWith(`asset://`))return this.wrapMediaReferenceError(lV.fromCandidate({referenceType:`asset`,assetId:e.slice(8)}),t);if(n?.allowStringUri===!0)return this.wrapMediaReferenceError(lV.fromCandidate({referenceType:`uri`,uri:e}),t)}return typeof e!=`object`||!e||Array.isArray(e)?{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be media reference object`,{nodeId:this.nodeId,key:t,expectedType:`media-reference`})}:this.wrapMediaReferenceError(lV.fromCandidate(e),t)}wrapMediaReferenceError(e,t){return e.ok?e:{ok:!1,error:Z(e.error.code,e.error.message,{nodeId:this.nodeId,key:t,...e.error.context??{}})}}};function dV(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.kind==`string`&&typeof t.mimeType==`string`&&typeof t.uri==`string`}function fV(e,t){if(e.isList)return Array.isArray(t)?t.every(t=>fV({...e,isList:!1},t)):!1;switch(e.type){case`string`:return typeof t==`string`;case`number`:return typeof t==`number`;case`boolean`:return typeof t==`boolean`;case`object`:return typeof t==`object`&&!!t&&!Array.isArray(t)&&!dV(t);case`array`:return Array.isArray(t);case`binary`:return!(!dV(t)||e.binaryKind&&t.kind!==e.binaryKind||e.mimeTypes&&e.mimeTypes.length>0&&!e.mimeTypes.includes(t.mimeType));default:return!1}}function pV(e,t,n,r){for(let i of t){let t=e[i.key];if(t===void 0){if(i.required)return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_REQUIRED_INPUT_MISSING`:`DAG_VALIDATION_NODE_REQUIRED_OUTPUT_MISSING`,n===`input`?`Required input port "${i.key}" (${i.type}) is missing on node "${r}"`:`Required output port "${i.key}" (${i.type}) was not set by node "${r}"`,{nodeId:r,key:i.key,type:i.type},n===`input`?{action:`connect_port`,suggestion:`Connect a "${i.type}" output to the "${i.key}" input of node "${r}"`}:void 0)};continue}if(i.isList){if(!Array.isArray(t))return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`:`DAG_VALIDATION_NODE_OUTPUT_TYPE_MISMATCH`,n===`input`?`List input port must receive array payload`:`List output port must emit array payload`,{nodeId:r,key:i.key,type:i.type})};if(typeof i.minItems==`number`&&t.length<i.minItems)return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_INPUT_MIN_ITEMS_NOT_SATISFIED`:`DAG_VALIDATION_NODE_OUTPUT_MIN_ITEMS_NOT_SATISFIED`,n===`input`?`List input port does not satisfy minItems`:`List output port does not satisfy minItems`,{nodeId:r,key:i.key,minItems:i.minItems,actualItems:t.length})};if(typeof i.maxItems==`number`&&t.length>i.maxItems)return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_INPUT_MAX_ITEMS_EXCEEDED`:`DAG_VALIDATION_NODE_OUTPUT_MAX_ITEMS_EXCEEDED`,n===`input`?`List input port exceeds maxItems`:`List output port exceeds maxItems`,{nodeId:r,key:i.key,maxItems:i.maxItems,actualItems:t.length})}}if(!fV(i,t))return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`:`DAG_VALIDATION_NODE_OUTPUT_TYPE_MISMATCH`,n===`input`?`Input port "${i.key}" on node "${r}" expects type "${i.type}" but received incompatible value`:`Output port "${i.key}" on node "${r}" emitted value incompatible with type "${i.type}"`,{nodeId:r,key:i.key,type:i.type},n===`input`?{action:`check_port_type`,suggestion:`Ensure the upstream output connected to "${i.key}" produces a "${i.type}" value`}:void 0)}}return{ok:!0,value:void 0}}var mV=class{handler;constructor(e){this.handler=e}async initialize(e){return this.handler.initialize?this.handler.initialize(e):{ok:!0,value:void 0}}async validateInput(e,t){let n=pV(e,t.nodeManifest.inputs,`input`,t.nodeDefinition.nodeId);return n.ok?this.handler.validateInput?this.handler.validateInput(e,t):{ok:!0,value:void 0}:n}async estimateCost(e,t){return this.handler.estimateCost?this.handler.estimateCost(e,t):{ok:!0,value:{estimatedCredits:0}}}async execute(e,t){return this.handler.execute(e,t)}async validateOutput(e,t){let n=pV(e,t.nodeManifest.outputs,`output`,t.nodeDefinition.nodeId);return n.ok?this.handler.validateOutput?this.handler.validateOutput(e,t):{ok:!0,value:void 0}:n}async dispose(e){return this.handler.dispose?this.handler.dispose(e):{ok:!0,value:void 0}}},hV=class{handlersByType;constructor(e){this.handlersByType=e}getHandler(e){return this.handlersByType[e]}listNodeTypes(){return Object.keys(this.handlersByType)}},gV=class{taskHandlerRegistry;constructor(e){this.taskHandlerRegistry=e}create(e){let t=this.taskHandlerRegistry.getHandler(e);return t?{ok:!0,value:new mV(t)}:{ok:!1,error:Z(`DAG_VALIDATION_NODE_LIFECYCLE_NOT_REGISTERED`,`Node lifecycle is not registered for nodeType`,{nodeType:e})}}},_V=class{manifestByType=new Map;constructor(e){for(let t of e)this.manifestByType.set(t.nodeType,t)}getManifest(e){return this.manifestByType.get(e)}listManifests(){return[...this.manifestByType.values()]}};const vV=A.string().trim().min(1);A.enum([`asset`,`uri`]);const yV=A.object({referenceType:A.literal(`asset`),assetId:vV,mediaType:A.string().optional(),name:A.string().optional(),sizeBytes:A.number().int().nonnegative().optional()}),bV=A.object({referenceType:A.literal(`uri`),uri:vV,mediaType:A.string().optional(),name:A.string().optional(),sizeBytes:A.number().int().nonnegative().optional()}),xV=A.union([yV,bV]);function SV(){return A.object({asset:xV})}function CV(e){return typeof e!=`object`||!e?!1:e instanceof A.ZodType}function wV(e){return e==null?{ok:!0,value:{}}:CV(e)?{ok:!0,value:it(e,{target:`jsonSchema7`})}:{ok:!1,error:Z(`DAG_VALIDATION_CONFIG_SCHEMA_INVALID`,`configSchemaDefinition must be a Zod schema instance.`)}}function TV(e){let t=[],n={};for(let r of e){let e=wV(r.configSchemaDefinition);if(!e.ok)return e;let i={nodeType:r.nodeType,displayName:r.displayName,category:r.category,inputs:r.inputs,outputs:r.outputs,configSchema:e.value,...r.defaultInputPort===void 0?{}:{defaultInputPort:r.defaultInputPort},...r.defaultOutputPort===void 0?{}:{defaultOutputPort:r.defaultOutputPort}};t.push(i),n[i.nodeType]=r.taskHandler}return{ok:!0,value:{manifests:t,handlersByType:n}}}const EV={IMAGE_PNG:{binaryKind:`image`,mimeTypes:[`image/png`]},IMAGE_COMMON:{binaryKind:`image`,mimeTypes:[`image/png`,`image/jpeg`,`image/webp`]},VIDEO_MP4:{binaryKind:`video`,mimeTypes:[`video/mp4`]},AUDIO_MPEG:{binaryKind:`audio`,mimeTypes:[`audio/mpeg`]},FILE_GENERIC:{binaryKind:`file`,mimeTypes:[]}};function DV(e){return{key:e.key,label:e.label,order:e.order,type:`binary`,required:e.required,description:e.description,binaryKind:e.preset.binaryKind,mimeTypes:[...e.preset.mimeTypes],isList:e.isList,minItems:e.minItems,maxItems:e.maxItems}}var OV=class{listeners=new Set;logger;constructor(e){this.logger=e}publish(e){let t=[];for(let n of[...this.listeners])try{n(e)}catch(n){t.push(n),this.logger&&this.logger.error(`RunProgressEventBus listener threw an error`,{eventType:e.eventType,error:n instanceof Error?n.message:String(n)})}if(t.length>0&&!this.logger)throw t[0]instanceof Error?t[0]:Error(String(t[0]))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function kV(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t||Array.isArray(t)?{ok:!1,error:Z(`DAG_VALIDATION_PAYLOAD_INVALID`,`Payload must be a JSON object`)}:{ok:!0,value:t}}catch{return{ok:!1,error:Z(`DAG_VALIDATION_PAYLOAD_PARSE_FAILED`,`Failed to parse payload JSON`)}}}function AV(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t||Array.isArray(t)||!(`dagId`in t)||!(`version`in t)||!(`nodes`in t)||!(`edges`in t)||!(`status`in t)||typeof t.dagId!=`string`||typeof t.version!=`number`||!Array.isArray(t.nodes)||!Array.isArray(t.edges)||typeof t.status!=`string`?{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`Definition snapshot must be a valid DAG definition object`)}:{ok:!0,value:t}}catch{return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse definition snapshot JSON`)}}}async function jV(e,t,n,r,i){let{dagRunId:a,definition:o,input:s}=e,c=o.nodes.filter(e=>e.dependsOn.length===0);if(c.length===0)return{ok:!1,error:Z(`DAG_VALIDATION_NO_ENTRY_NODE`,`DAG must include at least one entry node (dependsOn = [])`,{dagId:o.dagId,version:o.version})};let l=HB.transition(`created`,`QUEUE`);if(!l.ok)return l;await t.updateDagRunStatus(a,l.value.nextStatus);let u=HB.transition(`queued`,`START`);if(!u.ok)return u;await t.updateDagRunStatus(a,u.value.nextStatus),i?.publish({dagRunId:a,eventType:LB.STARTED,occurredAt:r.nowIso(),dagId:o.dagId,version:o.version});let d=[];for(let e of c){let c=`${a}:${e.nodeId}:attempt:1`;d.push(c),await t.createTaskRun({taskRunId:c,dagRunId:a,nodeId:e.nodeId,status:`queued`,attempt:1});let l={messageId:`${c}:message`,dagRunId:a,taskRunId:c,nodeId:e.nodeId,attempt:1,executionPath:[`dagId:${o.dagId}`,`dagRunId:${a}`,`nodeId:${e.nodeId}`,`taskRunId:${c}`,`attempt:1`],payload:s,createdAt:r.nowIso()};try{await n.enqueue(l)}catch(n){return MV(a,c,e.nodeId,d,n,t,r,i)}}return{ok:!0,value:{taskRunIds:d}}}async function MV(e,t,n,r,i,a,o,s){let c=JB(`DAG_DISPATCH_ENQUEUE_FAILED`,`Failed to enqueue entry task`,{dagRunId:e,taskRunId:t,nodeId:n,errorMessage:i instanceof Error&&i.message.trim().length>0?i.message:`Unknown error`}),l=KB.transition(`queued`,`CANCEL`);if(l.ok){await a.updateTaskRunStatus(t,l.value.nextStatus,c);for(let e of r)e!==t&&await a.updateTaskRunStatus(e,l.value.nextStatus,c)}let u=HB.transition(`running`,`COMPLETE_FAILURE`);return u.ok&&(await a.updateDagRunStatus(e,u.value.nextStatus,o.nowIso()),s?.publish({dagRunId:e,eventType:LB.FAILED,occurredAt:o.nowIso(),error:c})),{ok:!1,error:c}}var NV=class{storage;queue;clock;runProgressEventReporter;timeSemanticsService;constructor(e,t,n,r){this.storage=e,this.queue=t,this.clock=n,this.runProgressEventReporter=r,this.timeSemanticsService=new ZB(n)}async createRun(e){let t=e.version?await this.storage.getDefinition(e.dagId,e.version):await this.storage.getLatestPublishedDefinition(e.dagId);if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_NOT_FOUND`,`Published DAG definition was not found`,{dagId:e.dagId,hasVersion:!!e.version})};if(t.status!==`published`)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_NOT_PUBLISHED`,`Only published definitions can be executed`,{dagId:t.dagId,version:t.version,status:t.status})};let n=this.timeSemanticsService.resolve(e.trigger,e.logicalDate);if(!n.ok)return n;let r=e.rerunKey?`${t.dagId}:${n.value.logicalDate}:rerun:${e.rerunKey}`:`${t.dagId}:${n.value.logicalDate}`,i=await this.storage.getDagRunByRunKey(r);if(i)return{ok:!0,value:{dagRunId:i.dagRunId,dagId:i.dagId,version:i.version,logicalDate:i.logicalDate,status:i.status}};let a=this.generateDagRunId(t.dagId,n.value.logicalDate,e.rerunKey);try{await this.storage.createDagRun({dagRunId:a,dagId:t.dagId,version:t.version,status:`created`,definitionSnapshot:JSON.stringify(t),inputSnapshot:JSON.stringify(e.input),runKey:r,logicalDate:n.value.logicalDate,trigger:e.trigger,startedAt:this.clock.nowIso()})}catch(e){return{ok:!1,error:JB(`DAG_DISPATCH_DAG_RUN_CREATE_FAILED`,`Failed to create DagRun`,{dagId:t.dagId,version:t.version,runKey:r,errorMessage:this.resolveErrorMessage(e instanceof Error?e:void 0)})}}return{ok:!0,value:{dagRunId:a,dagId:t.dagId,version:t.version,logicalDate:n.value.logicalDate,status:`created`}}}async startCreatedRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};if(t.status!==`created`){let n=await this.storage.listTaskRunsByDagRunId(e);return{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}if(typeof t.definitionSnapshot!=`string`||t.definitionSnapshot.trim().length===0)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:e})};let n=AV(t.definitionSnapshot);if(!n.ok)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot is invalid`,{dagRunId:e})};let r=kV(t.inputSnapshot??`{}`);if(!r.ok)return{ok:!1,error:Z(`DAG_VALIDATION_RUN_INPUT_SNAPSHOT_INVALID`,`DagRun input snapshot is invalid`,{dagRunId:e})};let i=await jV({dagRunId:e,definition:n.value,input:r.value},this.storage,this.queue,this.clock,this.runProgressEventReporter);return i.ok?{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:i.value.taskRunIds}}:i}async startRun(e){let t=await this.createRun(e);if(!t.ok)return t;if(t.value.status===`created`)return this.startCreatedRun(t.value.dagRunId);let n=await this.storage.listTaskRunsByDagRunId(t.value.dagRunId);return{ok:!0,value:{dagRunId:t.value.dagRunId,dagId:t.value.dagId,version:t.value.version,logicalDate:t.value.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}generateDagRunId(e,t,n){let r=Date.parse(t);return n?`${e}:run:${r}:rerun:${n}`:`${e}:run:${r}`}resolveErrorMessage(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}},PV=class{storage;constructor(e){this.storage=e}async getRun(e){let t=await this.storage.getDagRun(e);return t?{ok:!0,value:{dagRun:t,taskRuns:await this.storage.listTaskRunsByDagRunId(e)}}:{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}},FV=class{storage;clock;constructor(e,t){this.storage=e,this.clock=t}async cancelRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};let n=HB.transition(t.status,`CANCEL`);return n.ok?(await this.storage.updateDagRunStatus(e,n.value.nextStatus,this.clock.nowIso()),{ok:!0,value:{dagRunId:e,status:`cancelled`}}):n}};function IV(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function LV(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function RV(e,t,n){let r=e.nodes.find(e=>e.nodeId===n);if(!r)return{ok:!1,error:Z(`DAG_VALIDATION_DOWNSTREAM_NODE_NOT_FOUND`,`Downstream node was not found while building payload`,{downstreamNodeId:n})};let i=e.edges.filter(e=>e.to===n);if(i.length===0)return{ok:!0,value:{}};let a={};for(let e of i){let n=zV(a,e,r,t);if(!n.ok)return n}return WV(a,r.inputs??[]),{ok:!0,value:a}}function zV(e,t,n,r){if(!t.bindings||t.bindings.length===0)return{ok:!1,error:Z(`DAG_VALIDATION_BINDING_REQUIRED`,`Incoming edge must define at least one binding`,{from:t.from,to:t.to})};let i=BV(t.from,t.to,r);if(!i.ok)return i;let a=i.value;for(let r of t.bindings){let i=VV(e,r,a,t,n);if(!i.ok)return i}return{ok:!0,value:void 0}}function BV(e,t,n){let r=n.find(t=>t.nodeId===e&&t.status===`success`);if(!r||!r.outputSnapshot)return{ok:!1,error:Z(`DAG_VALIDATION_UPSTREAM_OUTPUT_MISSING`,`Upstream output snapshot is missing for binding dispatch`,{from:e,to:t})};try{let n=JSON.parse(r.outputSnapshot);return LV(n)?{ok:!0,value:n}:{ok:!1,error:Z(`DAG_VALIDATION_UPSTREAM_OUTPUT_INVALID`,`Upstream output snapshot has invalid payload shape`,{from:e,to:t})}}catch(n){return{ok:!1,error:Z(`DAG_VALIDATION_UPSTREAM_OUTPUT_PARSE_FAILED`,`Failed to parse upstream output snapshot`,{from:e,to:t,errorMessage:IV(n)})}}}function VV(e,t,n,r,i){let a=n[t.outputKey];if(a===void 0)return{ok:!1,error:Z(`DAG_VALIDATION_BINDING_OUTPUT_KEY_MISSING`,`Binding outputKey was not found in upstream output`,{from:r.from,outputKey:t.outputKey})};if((i.inputs??[]).find(e=>e.key===t.inputKey)?.isList)return HV(e,t.inputKey,a,r.to);let o=FB(t.inputKey);return o?UV(e,o,a,t.inputKey,r.to,i):e[t.inputKey]===void 0?(e[t.inputKey]=a,{ok:!0,value:void 0}):{ok:!1,error:Z(`DAG_VALIDATION_BINDING_INPUT_KEY_CONFLICT`,`Multiple bindings target the same input key`,{to:r.to,inputKey:t.inputKey})}}function HV(e,t,n,r){Array.isArray(e[t])||(e[t]=[]);let i=e[t];return Array.isArray(i)?(i.push(n),{ok:!0,value:void 0}):{ok:!1,error:Z(`DAG_VALIDATION_BINDING_LIST_PAYLOAD_INVALID`,`List payload container is invalid`,{to:r,inputKey:t})}}function UV(e,t,n,r,i,a){if(!(a.inputs??[]).find(e=>e.key===t.portKey)?.isList)return{ok:!1,error:Z(`DAG_VALIDATION_BINDING_INPUT_KEY_MISSING`,`Binding inputKey does not resolve to a valid list input port`,{to:i,inputKey:r})};let o=e[t.portKey],s=Array.isArray(o)?o:[];return s[t.index]=n,e[t.portKey]=s,{ok:!0,value:void 0}}function WV(e,t){for(let n of t){if(!n.isList)continue;let t=e[n.key];Array.isArray(t)&&(e[n.key]=t.filter(e=>e!==void 0))}}function GV(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function KV(e,t,n,r,i,a,o){let s=t.nodes.filter(e=>e.dependsOn.includes(n));if(s.length===0)return{ok:!0,value:void 0};let c=await i.listTaskRunsByDagRunId(e.dagRunId);for(let n of s){let r=await qV(e,t,n,c,i,a,o);if(!r.ok)return r}return{ok:!0,value:void 0}}async function qV(e,t,n,r,i,a,o){if(r.some(e=>e.nodeId===n.nodeId)||!n.dependsOn.every(e=>r.some(t=>t.nodeId===e&&t.status===`success`)))return{ok:!0,value:void 0};let s=`${e.dagRunId}:${n.nodeId}:attempt:1`;await i.createTaskRun({taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1});let c=RV(t,r,n.nodeId);if(!c.ok)return c;let l=n.timeoutMs?{...c.value,timeoutMs:n.timeoutMs}:c.value,u={messageId:`${s}:message:1`,dagRunId:e.dagRunId,taskRunId:s,nodeId:n.nodeId,attempt:1,executionPath:[`dagId:${e.dagId}`,`dagRunId:${e.dagRunId}`,`nodeId:${n.nodeId}`,`taskRunId:${s}`,`attempt:1`],payload:l,createdAt:o.nowIso()};try{await a.enqueue(u)}catch(t){let r=KB.transition(`queued`,`CANCEL`);return r.ok&&await i.updateTaskRunStatus(s,r.value.nextStatus),{ok:!1,error:JB(`DAG_DISPATCH_ENQUEUE_DOWNSTREAM_FAILED`,`Failed to enqueue downstream task`,{dagRunId:e.dagRunId,nodeId:n.nodeId,errorMessage:GV(t)})}}return r.push({taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}),{ok:!0,value:void 0}}const JV=new Set([`created`,`queued`,`running`]),YV=new Set([`failed`]);async function XV(e,t,n,r){let i=await t.getDagRun(e);if(!i)return{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found while finalizing run status`,{dagRunId:e})};if(i.status!==`running`)return{ok:!0,value:void 0};let a=await t.listTaskRunsByDagRunId(e);if(a.some(e=>JV.has(e.status)))return{ok:!0,value:void 0};let o=a.some(e=>YV.has(e.status)),s=HB.transition(i.status,o?`COMPLETE_FAILURE`:`COMPLETE_SUCCESS`);return s.ok?(await t.updateDagRunStatus(e,s.value.nextStatus,n.nowIso()),o?ZV(e,a,n,r):r?.publish({dagRunId:e,eventType:LB.COMPLETED,occurredAt:n.nowIso()}),{ok:!0,value:void 0}):s}function ZV(e,t,n,r){let i=t.find(e=>YV.has(e.status)),a=typeof i?.errorCode==`string`&&typeof i.errorMessage==`string`?YB(i.errorCode,i.errorMessage,!1,{dagRunId:e,taskRunId:i.taskRunId,nodeId:i.nodeId}):YB(`DAG_TASK_EXECUTION_FAILED`,`Run completed with failure.`,!1,{dagRunId:e});r?.publish({dagRunId:e,eventType:LB.FAILED,occurredAt:n.nowIso(),error:a})}function QV(e,t){return YB(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${t}ms`,!0,{taskRunId:e,timeoutMs:t})}function $V(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function eH(e,t,n,r){return new Promise(i=>{let a=!1,o=setTimeout(()=>{a||(a=!0,i({ok:!1,error:QV(r,n)}))},n);e.execute(t).then(e=>{a||(a=!0,clearTimeout(o),i(e))}).catch(e=>{a||(a=!0,clearTimeout(o),i({ok:!1,error:YB(`DAG_TASK_EXECUTION_EXCEPTION`,`Task executor threw an exception`,!0,{taskRunId:r,errorMessage:$V(e)})}))})})}function tH(e){let t=0;for(let n of e)typeof n.totalCredits==`number`&&n.totalCredits>t&&(t=n.totalCredits);return t}function nH(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function rH(e,t){if(typeof e.definitionSnapshot!=`string`||e.definitionSnapshot.trim().length===0)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:t})};try{let n=JSON.parse(e.definitionSnapshot);return iH(n)?{ok:!0,value:n}:{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot has invalid shape`,{dagRunId:t})}}catch(e){return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse DagRun definition snapshot`,{dagRunId:t,errorMessage:nH(e)})}}}function iH(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.dagId==`string`&&typeof e.version==`number`&&Array.isArray(e.nodes)&&Array.isArray(e.edges)&&typeof e.status==`string`}async function aH(e,t){let n=await e.getDagRun(t.dagRunId);if(!n)return{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found for dequeued message`,{dagRunId:t.dagRunId})};let r=rH(n,t.dagRunId);if(!r.ok)return r;let i=r.value,a=i.nodes.find(e=>e.nodeId===t.nodeId);return a?{ok:!0,value:{dagRun:n,definition:i,nodeDefinition:a}}:{ok:!1,error:Z(`DAG_VALIDATION_NODE_NOT_FOUND`,`Node definition not found for task execution`,{nodeId:t.nodeId,dagId:n.dagId,version:n.version})}}function oH(e,t){let n=e.map(e=>e.startsWith(`attempt:`)?`attempt:${t}`:e);return n.some(e=>e.startsWith(`attempt:`))||n.push(`attempt:${t}`),n}function sH(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function cH(e,t,n,r,i,a,o,s){if(r.deadLetterEnabled){let t=await uH(e,n,r,o);if(!t.ok)return dH(a,e.messageId,t.error)}let c=await XV(e.dagRunId,i,o,s);return c.ok?fH(a,e.messageId,t,!1):dH(a,e.messageId,c.error)}async function lH(e,t,n,r,i){let a=KB.transition(`failed`,`RETRY`);if(!a.ok)return dH(r,e.messageId,a.error);await n.incrementTaskAttempt(t),await n.updateTaskRunStatus(t,a.value.nextStatus);let o=e.attempt+1,s={...e,messageId:`${e.taskRunId}:message:${o}`,attempt:o,executionPath:oH(e.executionPath,o),createdAt:i.nowIso()};try{await r.enqueue(s)}catch(n){return dH(r,e.messageId,JB(`DAG_DISPATCH_ENQUEUE_RETRY_FAILED`,`Failed to enqueue retry message`,{taskRunId:t,attempt:o,errorMessage:sH(n)}))}return fH(r,e.messageId,t,!0)}async function uH(e,t,n,r){if(!n.deadLetterQueue)return{ok:!1,error:Z(`DAG_VALIDATION_DEAD_LETTER_QUEUE_NOT_CONFIGURED`,`deadLetterEnabled requires deadLetterQueue to be configured`,{taskRunId:e.taskRunId})};let i={...e,messageId:`${e.taskRunId}:dlq:${r.nowEpochMs()}`,payload:{...e.payload,dlqReasonCode:t.code,dlqReasonMessage:t.message,dlqSourceMessageId:e.messageId},createdAt:r.nowIso()};try{return await n.deadLetterQueue.enqueue(i),{ok:!0,value:void 0}}catch(t){return{ok:!1,error:JB(`DAG_DISPATCH_DEAD_LETTER_ENQUEUE_FAILED`,`Failed to enqueue dead letter message`,{taskRunId:e.taskRunId,originalMessageId:e.messageId,errorMessage:sH(t)})}}}async function dH(e,t,n){return await e.ack(t),{ok:!1,error:n}}async function fH(e,t,n,r){return await e.ack(t),{ok:!0,value:{processed:!0,taskRunId:n,retried:r}}}var pH=class{storage;queue;lease;executor;clock;options;runProgressEventReporter;constructor(e,t,n,r,i,a,o){this.storage=e,this.queue=t,this.lease=n,this.executor=r,this.clock=i,this.options=a,this.runProgressEventReporter=o}async processOnce(){let e=await this.queue.dequeue(this.options.workerId,this.options.visibilityTimeoutMs,this.options.idleWaitMs);if(!e)return{ok:!0,value:{processed:!1}};let t=`taskRun:${e.taskRunId}`;if(!await this.lease.acquire(t,this.options.workerId,this.options.leaseDurationMs))return await this.queue.nack(e.messageId),{ok:!0,value:{processed:!1}};try{return this.processAcquiredMessage(e)}finally{await this.lease.release(t,this.options.workerId)}}async processAcquiredMessage(e){let t=await this.storage.getTaskRun(e.taskRunId);if(!t)return dH(this.queue,e.messageId,Z(`DAG_VALIDATION_TASK_RUN_NOT_FOUND`,`TaskRun not found for dequeued message`,{taskRunId:e.taskRunId}));let n=await this.transitionToRunning(e,t);if(!n.ok)return dH(this.queue,e.messageId,n.error);let r=await aH(this.storage,e);if(!r.ok)return dH(this.queue,e.messageId,r.error);let{dagRun:i,definition:a,nodeDefinition:o}=r.value,s=await this.buildExecutionInput(e,i,a,o),c=this.resolveTimeoutMs(e),l=await eH(this.executor,s,c,e.taskRunId);return l.ok?this.handleSuccessPath(e,t.taskRunId,i,a,l.output,l.estimatedCredits,l.totalCredits):this.handleFailurePath(e,t.taskRunId,l.error)}async transitionToRunning(e,t){let n=KB.transition(t.status,`START`);return n.ok?(await this.storage.updateTaskRunStatus(t.taskRunId,n.value.nextStatus),this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:RB.STARTED,occurredAt:this.clock.nowIso(),taskRunId:t.taskRunId,nodeId:e.nodeId,input:e.payload}),await this.storage.saveTaskRunSnapshots(t.taskRunId,JSON.stringify(e.payload)),{ok:!0,value:void 0}):n}async buildExecutionInput(e,t,n,r){let i=tH(await this.storage.listTaskRunsByDagRunId(e.dagRunId));return{dagId:t.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:e.attempt,executionPath:e.executionPath,input:e.payload,nodeDefinition:r,costPolicy:n.costPolicy,currentTotalCredits:i}}async handleSuccessPath(e,t,n,r,i,a,o){let s=KB.transition(`running`,`COMPLETE_SUCCESS`);if(!s.ok)return dH(this.queue,e.messageId,s.error);await this.completeTaskRun(e,t,s.value.nextStatus,i,a,o);let c=await KV(n,r,e.nodeId,i,this.storage,this.queue,this.clock);if(!c.ok)return dH(this.queue,e.messageId,c.error);let l=await XV(e.dagRunId,this.storage,this.clock,this.runProgressEventReporter);return l.ok?fH(this.queue,e.messageId,t,!1):dH(this.queue,e.messageId,l.error)}async handleFailurePath(e,t,n){let r=KB.transition(`running`,`COMPLETE_FAILURE`);return r.ok?(await this.storage.updateTaskRunStatus(t,r.value.nextStatus,n),this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:RB.FAILED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,error:n}),this.options.retryEnabled&&n.retryable&&e.attempt<this.options.maxAttempts?lH(e,t,this.storage,this.queue,this.clock):cH(e,t,n,this.options,this.storage,this.queue,this.clock,this.runProgressEventReporter)):dH(this.queue,e.messageId,r.error)}async completeTaskRun(e,t,n,r,i,a){await this.storage.updateTaskRunStatus(t,n),await this.storage.saveTaskRunSnapshots(t,void 0,JSON.stringify(r),i,a),this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:RB.COMPLETED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,output:r})}resolveTimeoutMs(e){let t=e.payload.timeoutMs;return typeof t==`number`&&t>0?t:this.options.defaultTimeoutMs}};function mH(e,t){let n={...t,retryEnabled:t.retryEnabled??!1,deadLetterEnabled:t.deadLetterEnabled??!1,deadLetterQueue:e.deadLetterQueue};return new pH(e.storage,e.queue,e.lease,e.executor,e.clock,n,e.runProgressEventReporter)}function hH(e){return(e.startsWith(`Robota`)?e.slice(6):e).replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`).replace(/^-/,``)}function gH(e,t){let n=new Map;for(let t of e.links)n.set(t[0],t);let r=t?.nodes??{},i=e.nodes.map(e=>{let t=r[String(e.id)],n={nodeId:t?.nodeId??`node-${e.id}`,nodeType:hH(e.type),dependsOn:[],config:e.properties?.robota_config??{},position:e.pos[0]!==0||e.pos[1]!==0?{x:e.pos[0],y:e.pos[1]}:void 0};return t?.retryPolicy&&(n.retryPolicy=t.retryPolicy),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),t?.costPolicy&&(n.costPolicy=t.costPolicy),n}),a=new Map;e.nodes.forEach((e,t)=>{a.set(e.id,i[t])});let o=new Map,s=new Map;for(let t of e.links){let[,n,,r]=t,i=a.get(n),c=a.get(r);if(!i||!c)continue;let l=e.nodes.find(e=>e.id===n),u=e.nodes.find(e=>e.id===r),d=t[2],f=t[4],p=l?.outputs?.[d]?.name??`out${d}`,m=u?.inputs?.[f]?.name??`in${f}`,h=`${i.nodeId}:${c.nodeId}`;o.has(h)||o.set(h,[]),o.get(h).push({outputKey:p,inputKey:m}),s.has(c.nodeId)||s.set(c.nodeId,new Set),s.get(c.nodeId).add(i.nodeId)}for(let e of i){let t=s.get(e.nodeId);t&&(e.dependsOn=[...t])}let c=[];for(let[e,t]of o){let[n,r]=e.split(`:`);c.push({from:n,to:r,bindings:t})}return{dagId:t?.dagId??`unknown`,version:t?.version??1,status:t?.status??`active`,nodes:i,edges:c,...t?.costPolicy?{costPolicy:t.costPolicy}:{},...t?.inputSchema?{inputSchema:t.inputSchema}:{},...t?.outputSchema?{outputSchema:t.outputSchema}:{}}}function _H(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.links)&&typeof t.version==`number`&&!(`dagId`in t)}function vH(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.dagId==`string`&&Array.isArray(t.nodes)}const yH=A.object({text:A.string().default(``)});var bH=class extends Q{nodeType=`input`;displayName=`Input`;category=`Core`;defaultOutputPort=`text`;inputs=[];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=yH;async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,`input`),i=typeof e.text==`string`?e.text:n.text;return r.setOutput(`text`,i),r.setOutput(`_agentSummary`,`Input: ${i.length} chars.`),{ok:!0,value:r.toOutput()}}};const xH=A.object({ports:A.array(A.string()).default([]),values:A.record(A.string()).default({})});var SH=class extends Q{nodeType=`multi-input`;displayName=`Multi-Input`;category=`Core`;inputs=[];outputs=[];configSchemaDefinition=xH;async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,`multi-input`),i=n.ports.length>0?n.ports:Object.keys({...n.values,...e});for(let t of i){if(t===`_agentSummary`)continue;let i=typeof e[t]==`string`?e[t]:n.values[t]??``;r.setOutput(t,i)}return r.setOutput(`_agentSummary`,`Multi-input: emitted ${i.length} port(s): ${i.join(`, `)}.`),{ok:!0,value:r.toOutput()}}};const CH=A.object({prefix:A.string().default(``)});var wH=class extends Q{nodeType=`transform`;displayName=`Transform`;category=`Core`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!1},{key:`data`,label:`Data`,order:1,type:`object`,required:!1}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!1},{key:`data`,label:`Data`,order:1,type:`object`,required:!1}];configSchemaDefinition=CH;async validateInputWithConfig(e,t,n){return Object.keys(e).length===0?{ok:!1,error:Z(`DAG_VALIDATION_TRANSFORM_INPUT_REQUIRED`,`Transform node requires at least one input value`,{nodeId:t.nodeDefinition.nodeId})}:{ok:!0,value:void 0}}async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:1e-4}}}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.getInput(`text`);if(typeof i==`string`){let e=`${n.prefix}${i}`;r.setOutput(`text`,e),r.setOutput(`_agentSummary`,`Transformed input. Output length: ${e.length} chars.`)}else{for(let[t,n]of Object.entries(e))r.setOutput(t,n);r.setOutput(`_agentSummary`,`Passed through ${Object.keys(e).length} port(s).`)}return{ok:!0,value:r.toOutput()}}};const TH=`__ROBOTA_TEXT_TEMPLATE_ESCAPED_PERCENT_S__`,EH=A.object({template:A.string().default(`%s`).describe(`Template string. Supports two syntaxes: {{text}} (Handlebars-style) or %s (printf-style). Both replace input text. Use %%s for a literal %s.`)});var DH=class extends Q{nodeType=`text-template`;displayName=`Text Template`;category=`Core`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=EH;async validateInputWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId).requireInputString(`text`);return r.ok?{ok:!0,value:void 0}:r}async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=i.value,o=n.template.split(`%%s`).join(TH).replaceAll(`{{text}}`,a).split(`%s`).join(a).split(TH).join(`%s`);return r.setOutput(`text`,o),r.setOutput(`_agentSummary`,`Template rendered. Output length: ${o.length} chars.`),{ok:!0,value:r.toOutput()}}};const OH=A.object({});var kH=class extends Q{nodeType=`text-output`;displayName=`Text Output`;category=`Core`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=OH;async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,`text-output`),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,i.value),r.setOutput(`_agentSummary`,`Output: ${i.value.length} chars.`),{ok:!0,value:r.toOutput()}):i}};const AH=A.object({});var jH=class extends Q{nodeType=`image-loader`;displayName=`Image Loader`;category=`Media`;defaultInputPort=`asset`;defaultOutputPort=`image`;inputs=[{key:`asset`,label:`Media Reference`,order:0,type:`object`,required:!0}];outputs=[DV({key:`image`,label:`Image`,order:0,required:!0,preset:EV.IMAGE_COMMON})];configSchemaDefinition=AH;async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputMediaReference(`asset`);return i.ok?(r.setOutput(`image`,i.value.toBinary(`image`,`image/png`)),r.setOutput(`_agentSummary`,`Asset loaded as image binary.`),{ok:!0,value:r.toOutput()}):i}};const MH=SV().extend({mimeType:A.string().optional()});var NH=class extends Q{nodeType=`image-source`;displayName=`Image Source`;category=`Test`;defaultOutputPort=`image`;inputs=[];outputs=[DV({key:`image`,label:`Image`,order:0,required:!0,description:`Test image output`,preset:EV.IMAGE_COMMON})];configSchemaDefinition=MH;async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=lV.fromAssetReference(n.asset),i=typeof n.mimeType==`string`?n.mimeType:r.mediaType(),a=typeof i==`string`&&i.trim().length>0?i:`image/png`;return{ok:!0,value:{image:r.toBinary(`image`,a),_agentSummary:`Image source resolved. Type: ${a}.`}}}};function PH(e){let t=e.image;return typeof t!=`object`||!t||!(`kind`in t)||!(`mimeType`in t)||!(`uri`in t)?!1:t.kind===`image`&&typeof t.mimeType==`string`&&typeof t.uri==`string`}const FH=A.object({});var IH=class extends Q{nodeType=`ok-emitter`;displayName=`OK Emitter`;category=`Test`;defaultInputPort=`image`;inputs=[DV({key:`image`,label:`Image Input`,order:0,required:!0,description:`Binary image from upstream`,preset:EV.IMAGE_COMMON})];outputs=[{key:`status`,label:`Status`,order:0,type:`string`,required:!0,description:`Execution status`}];configSchemaDefinition=FH;async validateInputWithConfig(e,t,n){return PH(e)?{ok:!0,value:void 0}:{ok:!1,error:Z(`DAG_VALIDATION_OK_EMITTER_IMAGE_REQUIRED`,`OK emitter node requires an image binary input`,{nodeId:t.nodeDefinition.nodeId})}}async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,`ok-emitter`),i=r.requireInput(`image`);return i.ok?PH({image:i.value})?(r.setOutput(`status`,`ok`),r.setOutput(`_agentSummary`,`Image validated. Status: ok.`),{ok:!0,value:r.toOutput()}):{ok:!1,error:YB(`DAG_TASK_EXECUTION_OK_EMITTER_IMAGE_INVALID`,`OK emitter execution requires image binary input`,!1)}:i}};const LH={read:e=>hc(e),write:e=>Sc(e),edit:e=>Tc(e),shell:e=>oc(e),bash:e=>sc(e),glob:()=>Oc,grep:()=>Fc,"web-fetch":()=>Hc,"web-search":()=>Gc},RH=Object.freeze(Object.keys(LH)),zH=A.object({toolName:A.string().min(1),params:A.record(A.unknown()).default({}),cwd:A.string().optional(),baseCredits:A.number().nonnegative().default(0)}),BH=[{key:`params`,label:`Tool Parameters (JSON string)`,order:0,type:`string`,required:!1}],VH=[{key:`output`,label:`Output`,order:0,type:`string`,required:!0},{key:`isError`,label:`Is Error`,order:1,type:`boolean`,required:!0}];function HH(e){let t=typeof e==`string`?e:JSON.stringify(e??``);try{let e=JSON.parse(t);if(typeof e==`object`&&e&&typeof e.success==`boolean`){let t=e.success?e.output:e.error??e.output;return{output:typeof t==`string`?t:String(t??``),isError:!e.success}}}catch{}return{output:t,isError:!1}}function UH(e,t,n){return Z(`DAG_VALIDATION_TOOL_INVALID_PARAMS`,t,{toolName:e},{action:`set_input`,suggestion:n})}function WH(e,t){if(typeof e==`string`&&e.trim()!==``){let n;try{n=JSON.parse(e)}catch{return{ok:!1,error:UH(t,"The `params` input port must be a JSON object string.",`Provide a valid JSON object as the params input`)}}return typeof n!=`object`||!n||Array.isArray(n)?{ok:!1,error:UH(t,"The `params` input port must decode to a JSON object.",`Provide a JSON object (not an array or primitive)`)}:{ok:!0,value:n}}return typeof e==`object`&&e&&!Array.isArray(e)?{ok:!0,value:e}:{ok:!0,value:{}}}async function GH(e,t,n,r){try{let{output:i,isError:a}=HH((await e.execute(t)).data),o=new $({},r);return o.setOutput(`output`,i),o.setOutput(`isError`,a),o.setOutput(`_agentSummary`,`Tool "${n}" ran. ${a?`Reported an error.`:`Output: ${i.length} chars.`}`),{ok:!0,value:o.toOutput()}}catch(e){return{ok:!1,error:YB(`DAG_TASK_EXECUTION_TOOL_CALL_FAILED`,`Tool "${n}" failed: ${e instanceof Error?e.message:String(e)}`,!0,{toolName:n})}}}var KH=class extends Q{nodeType=`tool`;displayName=`Tool`;category=`Integration`;inputs=BH;outputs=VH;configSchemaDefinition=zH;defaultInputPort=`params`;defaultOutputPort=`output`;constructor(){super()}async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:n.baseCredits}}}async executeWithConfig(e,t,n){let r=LH[n.toolName];if(!r)return{ok:!1,error:Z(`DAG_VALIDATION_TOOL_UNKNOWN_TOOL`,`Unknown toolName "${n.toolName}". Choose one of the supported in-process builtins.`,{toolName:n.toolName},{action:`set_config`,suggestion:`Set toolName to a supported builtin`,options:[...RH]})};let i=WH(new $(e,t.nodeDefinition.nodeId).getInput(`params`),n.toolName);if(!i.ok)return i;let a={...n.params,...i.value};return GH(r(n.cwd===void 0?{}:{cwd:n.cwd}),a,n.toolName,t.nodeDefinition.nodeId)}};const qH={ok:!0,value:{estimatedCredits:0}},JH=A.object({});var YH=class extends Q{nodeType=`string-to-number`;displayName=`String → Number`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`number`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`number`,label:`Number`,order:0,type:`string`,required:!0}];configSchemaDefinition=JH;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=Number(i.value);return isNaN(a)?{ok:!1,error:Z(`DAG_VALIDATION_STRING_TO_NUMBER_INVALID`,`Cannot convert "${i.value}" to a number`,{nodeId:t.nodeDefinition.nodeId})}:(r.setOutput(`number`,String(a)),{ok:!0,value:r.toOutput()})}},XH=class extends Q{nodeType=`number-to-string`;displayName=`Number → String`;category=`Utility`;defaultInputPort=`number`;defaultOutputPort=`text`;inputs=[{key:`number`,label:`Number`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=JH;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`number`);return i.ok?(r.setOutput(`text`,i.value),{ok:!0,value:r.toOutput()}):i}};const ZH=A.object({separator:A.string().default(`, `)});var QH=class extends Q{nodeType=`text-join`;displayName=`Text Join`;category=`Utility`;defaultInputPort=`items`;defaultOutputPort=`text`;inputs=[{key:`items`,label:`Items (newline-separated)`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=ZH;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`items`);if(!i.ok)return i;let a=i.value.split(`
391
- `).filter(e=>e.trim()!==``);return r.setOutput(`text`,a.join(n.separator)),{ok:!0,value:r.toOutput()}}};const $H=A.object({separator:A.string().default(`
392
- `),trim:A.boolean().default(!0)});var eU=class extends Q{nodeType=`text-split`;displayName=`Text Split`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`items`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`items`,label:`Items (newline-separated)`,order:0,type:`string`,required:!0}];configSchemaDefinition=$H;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=i.value.split(n.separator),o=n.trim?a.map(e=>e.trim()).filter(e=>e!==``):a;return r.setOutput(`items`,o.join(`
393
- `)),{ok:!0,value:r.toOutput()}}};const tU=A.object({search:A.string().default(``),replacement:A.string().default(``),useRegex:A.boolean().default(!1),flags:A.string().default(`g`)});var nU=class extends Q{nodeType=`text-replace`;displayName=`Text Replace`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=tU;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a;if(n.useRegex)try{let e=new RegExp(n.search,n.flags);a=i.value.replace(e,n.replacement)}catch{return{ok:!1,error:Z(`DAG_VALIDATION_TEXT_REPLACE_INVALID_REGEX`,`Invalid regex: "${n.search}"`,{nodeId:t.nodeDefinition.nodeId})}}else a=i.value.split(n.search).join(n.replacement);return r.setOutput(`text`,a),{ok:!0,value:r.toOutput()}}},rU=class extends Q{nodeType=`text-length`;displayName=`Text Length`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Length`,order:0,type:`string`,required:!0}];configSchemaDefinition=JH;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t){let n=new $(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);return r.ok?(n.setOutput(`text`,String(r.value.length)),{ok:!0,value:n.toOutput()}):r}},iU=class extends Q{nodeType=`text-upper`;displayName=`Text Uppercase`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=JH;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t){let n=new $(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);return r.ok?(n.setOutput(`text`,r.value.toUpperCase()),{ok:!0,value:n.toOutput()}):r}},aU=class extends Q{nodeType=`text-lower`;displayName=`Text Lowercase`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=JH;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t){let n=new $(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);return r.ok?(n.setOutput(`text`,r.value.toLowerCase()),{ok:!0,value:n.toOutput()}):r}};const oU=A.object({mode:A.enum([`both`,`start`,`end`]).default(`both`)});var sU=class extends Q{nodeType=`text-trim`;displayName=`Text Trim`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=oU;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=n.mode===`start`?i.value.trimStart():n.mode===`end`?i.value.trimEnd():i.value.trim();return r.setOutput(`text`,a),{ok:!0,value:r.toOutput()}}};const cU=A.object({path:A.string().default(``),fallback:A.string().default(``)});var lU=class extends Q{nodeType=`json-extract`;displayName=`JSON Extract`;category=`Utility`;defaultInputPort=`json`;defaultOutputPort=`text`;inputs=[{key:`json`,label:`JSON`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Value`,order:0,type:`string`,required:!0}];configSchemaDefinition=cU;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`json`);if(!i.ok)return i;let a;try{a=JSON.parse(i.value)}catch{return{ok:!1,error:Z(`DAG_VALIDATION_JSON_EXTRACT_INVALID_JSON`,`Input is not valid JSON`,{nodeId:t.nodeDefinition.nodeId})}}let o=n.path?n.path.split(`.`):[],s=a;for(let e of o){if(typeof s!=`object`||!s){s=void 0;break}s=s[e]}let c=s===void 0?n.fallback:String(s);return r.setOutput(`text`,c),{ok:!0,value:r.toOutput()}}};const uU=A.object({operator:A.enum([`non-empty`,`equals`,`contains`,`starts-with`,`ends-with`]).default(`non-empty`),operand:A.string().default(``)});var dU=class extends Q{nodeType=`conditional-text`;displayName=`Conditional Text`;category=`Utility`;defaultInputPort=`condition`;defaultOutputPort=`text`;inputs=[{key:`condition`,label:`Condition`,order:0,type:`string`,required:!0},{key:`text_true`,label:`If True`,order:1,type:`string`,required:!0},{key:`text_false`,label:`If False`,order:2,type:`string`,required:!1}];outputs=[{key:`text`,label:`Result`,order:0,type:`string`,required:!0}];configSchemaDefinition=uU;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`condition`);if(!i.ok)return i;let a=r.requireInputString(`text_true`);if(!a.ok)return a;let o=r.getInput(`text_false`),s=i.value,c=n.operand,l;switch(n.operator){case`non-empty`:l=s.trim().length>0;break;case`equals`:l=s===c;break;case`contains`:l=s.includes(c);break;case`starts-with`:l=s.startsWith(c);break;case`ends-with`:l=s.endsWith(c);break}let u=l?a.value:typeof o==`string`?o:``;return r.setOutput(`text`,u),{ok:!0,value:r.toOutput()}}};const fU=A.object({skipEmpty:A.boolean().default(!1)});var pU=class extends Q{nodeType=`text-count-lines`;displayName=`Text Count Lines`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Line Count`,order:0,type:`string`,required:!0}];configSchemaDefinition=fU;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=i.value.split(`
394
- `),o=n.skipEmpty?a.filter(e=>e.trim()!==``).length:a.length;return r.setOutput(`text`,String(o)),{ok:!0,value:r.toOutput()}}};const mU=A.object({times:A.number().int().min(0).default(2),separator:A.string().default(``)});var hU=class extends Q{nodeType=`text-repeat`;displayName=`Text Repeat`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Repeated Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=mU;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=Array.from({length:n.times},()=>i.value);return r.setOutput(`text`,a.join(n.separator)),{ok:!0,value:r.toOutput()}}};const gU=A.object({start:A.number().int().default(0),end:A.number().int().optional()});var _U=class extends Q{nodeType=`text-slice`;displayName=`Text Slice`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Sliced Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=gU;async estimateCostWithConfig(){return qH}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,i.value.slice(n.start,n.end)),{ok:!0,value:r.toOutput()}):i}};function vU(e,t){let n=new OV;return{runOrchestrator:new NV(e.storage,e.queue,e.clock,n),runQuery:new PV(e.storage),runCancel:new FV(e.storage,e.clock),workerLoop:mH({storage:e.storage,queue:e.queue,deadLetterQueue:e.deadLetterQueue,lease:e.lease,executor:e.executor,clock:e.clock,runProgressEventReporter:n},{...t.worker,retryEnabled:t.worker.retryEnabled??!1}),runProgressEventBus:n}}function yU(){return[new bH,new SH,new wH,new DH,new kH,new jH,new NH,new IH,new KH,new YH,new XH,new QH,new eU,new nU,new rU,new iU,new aU,new sU,new lU,new dU,new pU,new hU,new _U]}const bU=new Set([`success`,`failed`,`cancelled`]);function xU(e){return bU.has(e)}function SU(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{return{}}return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}function CU(e){let t={};for(let n of e){let e=SU(n.outputSnapshot);for(let[r,i]of Object.entries(e))t[`${n.nodeId}.${r}`]=i}return t}function wU(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.status!==`success`)continue;let r=SU(n.outputSnapshot);for(let e of Object.values(r))if(typeof e==`string`)return e}}function TU(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n&&n.status===`failed`&&n.errorMessage)return`${n.nodeId}: ${n.errorMessage}`}}const EU=1e4;function DU(e){return new Promise(t=>{setTimeout(t,e)})}var OU=class{options;providerId=`local`;displayName=`Local (in-process)`;constructor(e={}){this.options=e}async listNodes(){return this.buildNodeRegistry().map(AU)}async execute(e,t,n){let r=this.buildNodeRegistry(),i=gH(e,void 0),a=Date.now(),o=!1,s=()=>{o=!0};n?.signal?.addEventListener(`abort`,s);try{let e=await kU(i,r,t,n?.onProgress,()=>o),s=Date.now()-a,c=CU(e.taskRuns),l=e.dagRun.status===`success`,u=l?void 0:TU(e.taskRuns);return n?.onProgress?.({type:`dag_complete`,nodeId:``,durationMs:s,finalOutput:l?wU(e.taskRuns):void 0,error:l?void 0:u??`DAG run did not succeed`}),{ok:l,outputs:c,durationMs:s,...l?{}:{error:u??`DAG run did not succeed`}}}catch(e){let t=Date.now()-a,r=e instanceof Error?e.message:String(e);return n?.onProgress?.({type:`dag_complete`,nodeId:``,durationMs:t,error:r}),{ok:!1,outputs:{},durationMs:t,error:r}}finally{n?.signal?.removeEventListener(`abort`,s)}}buildNodeRegistry(){let e=this.options.nodeRegistry??yU(),t=this.options.instantNodes??[],n=this.options.extraNodes??[],r=new Set([...t.map(e=>e.nodeType),...n.map(e=>e.nodeType)]);return[...e.filter(e=>!r.has(e.nodeType)),...n,...t]}};async function kU(e,t,n,r,i){let a=TV(t);if(!a.ok)throw Error(`Node definition assembly failed: ${a.error.code}`);let o=a.value,s=new tV(new _V(o.manifests),new gV(new hV(o.handlersByType))),c=new rV,l=vU({storage:c,queue:new iV,deadLetterQueue:new iV,lease:new aV,executor:s,clock:new oV},{worker:{workerId:`local-dag-runtime-provider`,leaseDurationMs:6e4,visibilityTimeoutMs:6e4,maxAttempts:1,defaultTimeoutMs:3e5,retryEnabled:!1}}),u=new Map(e.nodes.map(e=>[e.nodeId,e.nodeType])),d=new Map,f=l.runProgressEventBus.subscribe(e=>{if(r){if(e.eventType===`task.started`)d.set(e.nodeId,Date.now()),r({type:`node_start`,nodeId:e.nodeId,nodeType:u.get(e.nodeId)});else if(e.eventType===`task.completed`){let t=d.get(e.nodeId);r({type:`node_complete`,nodeId:e.nodeId,nodeType:u.get(e.nodeId),durationMs:t===void 0?void 0:Date.now()-t})}else if(e.eventType===`task.failed`){let t=d.get(e.nodeId);r({type:`node_error`,nodeId:e.nodeId,nodeType:u.get(e.nodeId),durationMs:t===void 0?void 0:Date.now()-t,error:e.error.message??e.error.code})}}});try{let t={...e,status:`published`};await c.saveDefinition(t);let r=await l.runOrchestrator.startRun({dagId:e.dagId,version:e.version,trigger:`manual`,input:n});if(!r.ok)throw Error(`startRun failed: ${r.error.code}`);let{dagRunId:a}=r.value;for(let e=0;e<EU;e++){i()&&await l.runCancel.cancelRun(a);let e=await l.workerLoop.processOnce();if(!e.ok)throw Error(`Worker step failed: ${e.error.code}`);let t=await l.runQuery.getRun(a);if(!t.ok)throw Error(`Run query failed: ${t.error.code}`);let{dagRun:n,taskRuns:r}=t.value;if(xU(n.status))return{dagRun:n,taskRuns:r};e.value.processed||await DU(10)}throw Error(`Run ${a} did not reach terminal state after ${EU} iterations`)}finally{f()}}function AU(e){let t={},n={};for(let r of e.inputs??[]){let e=MU(r.type),i={},a=r;a.default!==void 0&&(i.default=a.default);let o=Object.keys(i).length>0?[e,i]:[e];r.required===!1?n[r.key]=o:t[r.key]=o}let r=e.outputs??[],i={nodeType:e.nodeType,input:{required:t},output:r.map(e=>MU(e.type)),output_name:r.map(e=>e.key),category:e.category??`robota`,source:`local`};return Object.keys(n).length>0&&(i.input.optional=n),i}const jU={string:`STRING`,object:`JSON`,binary:`IMAGE`,number:`FLOAT`,boolean:`BOOLEAN`,integer:`INT`};function MU(e){return jU[e]??e.toUpperCase()}async function NU(e,t=`.dag/workflows`){let n=v(e,t),r=await fe(n).catch(()=>null);if(r===null)return{success:!0,message:`No workflow catalog at ${t} (build or save a workflow to populate it).`};let i=r.filter(e=>e.endsWith(`.dag.json`)).sort();if(i.length===0)return{success:!0,message:`No workflow files (*.dag.json) in ${t}.`};let a=[];for(let e of i){let t=await de(h(n,e),`utf-8`).then(e=>JSON.parse(e)).then(e=>`${e.nodes?.length??0} node(s), ${e.links?.length??0} link(s)`).catch(()=>`unreadable`);a.push(` ${e} — ${t}`)}return{success:!0,message:`Workflows in ${t} (${i.length}):\n${a.join(`
395
- `)}`}}async function PU(){let e=await new OU().listNodes(),t=[...e].sort((e,t)=>e.nodeType.localeCompare(t.nodeType)).map(e=>` ${e.nodeType}${e.description?` — ${e.description}`:``}`);return{success:!0,message:`Available workflow nodes (${e.length}):\n${t.join(`
396
- `)}`}}async function FU(e){let t=await de(e,`utf-8`);return JSON.parse(t)}async function IU(e,t){if(!e)return{success:!1,message:`Usage: /workflows run <file.dag.json>`};let n=await FU(v(t,e)).catch(t=>{let n=t instanceof Error?t.message:String(t);return Error(`Failed to read DAG file "${e}": ${n}`)});if(n instanceof Error)return{success:!1,message:n.message};let r=await new OU().execute(n,{});return r.ok?{success:!0,message:`Workflow completed in ${r.durationMs}ms.\nOutputs: ${JSON.stringify(r.outputs,null,2)}`}:{success:!1,message:`Workflow failed (${r.durationMs}ms): ${r.error??`unknown error`}`}}async function LU(e,t){if(!e)return{success:!1,message:`Usage: /workflows validate <file.dag.json>`};let n=await de(v(t,e),`utf-8`).then(e=>JSON.parse(e)).catch(t=>{let n=t instanceof Error?t.message:String(t);return Error(`Failed to read DAG file "${e}": ${n}`)});if(n instanceof Error)return{success:!1,message:n.message};let r;if(_H(n))r=gH(n);else if(vH(n))r=n;else return{success:!1,message:`"${e}" is not a recognized DAG workflow file (expected a .dag.json node-graph or a DAG definition).`};let i=await new OU().listNodes(),a=new Set(i.map(e=>e.nodeType)),o=new Set(r.nodes.map(e=>e.nodeId)),s=[];r.nodes.length===0&&s.push(`workflow has no nodes`);for(let e of r.nodes)a.has(e.nodeType)||s.push(`node "${e.nodeId}": unknown node type "${e.nodeType}"`);for(let e of r.edges)o.has(e.from)||s.push(`edge references unknown source node "${e.from}"`),o.has(e.to)||s.push(`edge references unknown target node "${e.to}"`);if(s.length>0){let t=s.length===1?``:`s`;return{success:!1,message:`Invalid workflow "${e}" (${s.length} issue${t}):\n${s.map(e=>` - ${e}`).join(`
397
- `)}`}}return{success:!0,message:`Valid workflow "${e}": ${r.nodes.length} node(s), ${r.edges.length} edge(s).`}}const RU=[{name:`list`,description:`List available workflow nodes`,source:`workflows`,modelInvocable:!1},{name:`catalog`,description:`List workflow files in the local .dag/workflows catalog`,source:`workflows`,modelInvocable:!1},{name:`validate`,description:`Validate a .dag.json workflow file against the node catalog`,source:`workflows`,argumentHint:`<file.dag.json>`,modelInvocable:!1},{name:`run`,description:`Run a .dag.json workflow file`,source:`workflows`,argumentHint:`<file.dag.json>`,modelInvocable:!1}],zU=[`Usage: /workflows <list|catalog|validate|run>`,` list List available workflow nodes`,` catalog List workflow files in .dag/workflows`,` validate <file> Validate a .dag.json workflow file`,` run <file> Run a .dag.json workflow file`].join(`
398
- `);function BU(e){let t=e.trim();if(t===``)return{sub:``,rest:``};let n=t.indexOf(` `);return n===-1?{sub:t,rest:``}:{sub:t.slice(0,n),rest:t.slice(n+1).trim()}}async function VU(e,t){let{sub:n,rest:r}=BU(t);switch(n){case``:return{success:!0,message:zU};case`list`:return PU();case`catalog`:return NU(process.cwd());case`validate`:return LU(r,process.cwd());case`run`:return IU(r,process.cwd());default:return{success:!1,message:`Unknown subcommand "${n}".\n${zU}`}}}function HU(){return{name:`workflows`,displayName:`Workflows`,description:`List, validate, and run DAG workflows on the in-process runtime`,source:`workflows`,argumentHint:`<list|catalog|validate|run> [args]`,subcommands:RU,modelInvocable:!1}}function UU(){let e=HU();return{name:e.name,displayName:e.displayName,description:e.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!1,argumentHint:e.argumentHint,subcommands:e.subcommands,lifecycle:`inline`,execute:VU}}var WU=class{name=`workflows`;getCommands(){return[HU()]}};function GU(){return{name:`agent-command-workflows`,commandSources:[new WU],systemCommands:[UU()]}}function KU(){return GU()}function qU(e,t,n,r,i={}){let a={settings:{read:()=>Km(Wm()),write:e=>qm(Wm(),e)},plugin:PP(e)},o=n.providerDefinitions??EO(),s={readMergedSettings:()=>R_(e),readTargetSettings:()=>Km(k_(e)),writeTargetSettings:t=>qm(k_(e),t)},c=KU();return{commandHostAdapters:a,providerDefinitions:o,commandModules:[...DP({cwd:e,providerDefinitions:o,providerSettingsAdapter:s,...i.enabledCommandModules===void 0?{}:{enabledCommandModules:i.enabledCommandModules},...i.disabledCommandModules===void 0?{}:{disabledCommandModules:i.disabledCommandModules}}),c,...n.commandModules??[]],startupUpdateNoticePromise:$b(t)?Qb({currentVersion:r}):void 0}}function JU(e,t){let n=O(v(e,t),`utf8`).trim();if(n.length===0)throw Error(`Task file is empty: ${t}`);return`Task file (${t}):\n${n}`}function YU(e,t){let n=[];if(t.appendSystemPrompt&&n.push(t.appendSystemPrompt),t.taskFile)try{n.push(JU(e,t.taskFile))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}return t.jsonSchema&&n.push(`Respond with valid JSON only, matching this JSON schema:\n${t.jsonSchema}`),n.length>0?n.join(`
399
-
400
- `):void 0}async function XU(e,t,n,r,i,a,o,s,c={},l={}){let u=t.goal?.trim(),d=t.positional.join(` `).trim();if(!u&&!d&&!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);d=Buffer.concat(e).toString(`utf-8`).trim()}!u&&!d&&(process.stderr.write(`Print mode (-p) requires a prompt argument (or --goal <objective>).
401
- `),process.exit(1));let f=YU(e,t),p=new Tx({cwd:e,provider:n,outputFormat:t.outputFormat??`text`,permissionMode:t.permissionMode??l.permissionMode??`bypassPermissions`,maxTurns:t.maxTurns,sessionStore:t.noSessionPersistence?void 0:r,resumeSessionId:c.resumeSessionId,forkSession:c.forkSession,sessionName:t.sessionName,bare:t.bare||void 0,allowedTools:kx(t.allowedTools),deniedTools:kx(t.deniedTools),appendSystemPrompt:f,...l.persona===void 0?{}:{persona:l.persona},...l.agentName===void 0?{}:{agentName:l.agentName},...l.activePresetId===void 0?{}:{activePresetId:l.activePresetId},...l.enableParallelSubagents===void 0?{}:{enableParallelSubagents:l.enableParallelSubagents},...l.selfVerification===void 0?{}:{selfVerification:l.selfVerification},...t.systemPrompt?{systemPrompt:t.systemPrompt}:{},backgroundTaskRunners:i,subagentRunnerFactory:a,commandModules:o,commandHostAdapters:s});u?await p.runGoal(u,t.goalMaxIterations?{maxIterations:t.goalMaxIterations}:{}):await p.run(d),process.exit(p.getExitCode())}function ZU(t){let n;try{n=e(import.meta.url)(`@robota-sdk/agent-provider-replay`)}catch{throw Error(`--session-log replay requires @robota-sdk/agent-provider-replay, a dev-only package that is not bundled in the published CLI.`)}return n.createReplayProviderFromLogFile(t)}function QU(){let e=new GR(Wm());return e.register(new pz),e}async function $U(e={}){if(process.argv[2]===`session`&&process.argv[3]===`analyze`){await lB(process.argv.slice(4),process.cwd());return}let t;try{t=Fx()}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let r=uB();if(t.help){process.stdout.write(Ox());return}if(t.version){process.stdout.write(`robota ${r}\n`);return}if(t.checkUpdate){let e=await Yb({currentVersion:r,force:!0}),t=tx(e);e.status===`error`&&(process.stderr.write(`${t}\n`),process.exit(1)),process.stdout.write(`${t}\n`);return}let i=process.cwd(),a=new ux;if(t.reset){process.exitCode=await fB(a,{yes:t.yes,isTTY:process.stdin.isTTY===!0});return}if(t.positional[0]===`diagnose`){let e=await CB({version:r,terminal:a,cwd:i});process.exitCode=+(e>0);return}if(t.positional[0]===`session`&&t.positional[1]===`analyze`){await lB(process.argv.slice(4),i);return}try{if(await zz(t,i,a))return}catch(e){a.writeError(e instanceof Error?e.message:String(e)),process.exit(1)}let o=Km(Wm()),s=typeof o.preset==`string`?o.preset:void 0,c=fS();for(let{file:e,error:t}of c.errors)a.writeError(`Skipped external preset "${e}": ${t}`);let l;try{l=hS(t,s)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let u=pS(t,s),{commandHostAdapters:d,providerDefinitions:f,commandModules:p,startupUpdateNoticePromise:m}=qU(i,t,e,r,{...l.enabledCommandModules===void 0?{}:{enabledCommandModules:l.enabledCommandModules},...l.disabledCommandModules===void 0?{}:{disabledCommandModules:l.disabledCommandModules}});if(t.positional[0]===`init`){try{await kB(i,a,{yes:t.yes,onProviderSetup:async()=>{await VP(i,t,dx,a,f)}})}catch(e){a.writeError(e instanceof Error?e.message:String(e)),process.exit(1)}return}if(t.configure){await VP(i,t,dx,a,f);return}if(zP(i,t,a,f))return;try{await BP(i,t,dx,a,f)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(e instanceof L_&&t.printMode?3:1)}let h=t.provider?{providerOverride:t.provider,providerDefinitions:f}:{providerDefinitions:f},g=B_(i,h),_=l.model??g.model;if(g.source===`env-default`&&g.sourceEnvVar!==void 0){let e=`Using ${g.name} (${_}) via ${g.sourceEnvVar} — run \`robota --configure\` to persist a profile.\n`;t.printMode?process.stderr.write(e):a.writeLine(e.trimEnd())}let v=t.sessionLog?ZU(t.sessionLog):V_(i,l.model,h),y=es(),b=dp(i),x=jz({workerPath:Rz(),providerConfig:{...g,model:_},logsDir:b.logs}),S=My(i),C,w=!1;if(t.continueMode?C=Fy(S,i):t.resumeId!==void 0&&(t.resumeId===``?w=!0:(C=Iy(S,t.resumeId),C===void 0&&(process.stderr.write(`Session not found: ${t.resumeId}\n`),process.exit(1)))),t.printMode||t.goal){await XU(i,t,v,S,y,x,p,d,{resumeSessionId:C,forkSession:t.forkSession},{agentName:l.agentName??Vx,activePresetId:u,persona:l.persona,...l.permissionMode===void 0?{}:{permissionMode:l.permissionMode},...l.enableParallelSubagents===void 0?{}:{enableParallelSubagents:l.enableParallelSubagents},...l.selfVerification===void 0?{}:{selfVerification:l.selfVerification}});return}PB(a),WR(),AB()&&(NB(a),jB()),await RR({onChannelReady:e=>HR(e),cwd:i,provider:v,providerOverride:t.provider,providerType:g.name,modelId:_,language:t.language,permissionMode:t.permissionMode??l.permissionMode,maxTurns:t.maxTurns,allowedTools:kx(t.allowedTools),deniedTools:kx(t.deniedTools),version:r,sessionStore:t.noSessionPersistence?void 0:S,resumeSessionId:C,showSessionPickerOnStart:w,forkSession:t.forkSession,sessionName:t.sessionName,backgroundTaskRunners:y,subagentRunnerFactory:x,commandModules:p,commandHostAdapters:d,shellExec:e=>n(e,{timeout:5e3,encoding:`utf-8`,stdio:`pipe`}).trimEnd(),startupUpdateNotice:m?m.then(e=>e?ex(e):void 0):void 0,transportRegistry:QU(),cliAdapter:zR({providerDefinitions:f,reloadPluginCommandSource:LP}),reloadPluginCommandSource:LP,agentName:l.agentName??Vx,activePresetId:u,persona:l.persona,...l.enableParallelSubagents===void 0?{}:{enableParallelSubagents:l.enableParallelSubagents},...l.selfVerification===void 0?{}:{selfVerification:l.selfVerification}}),process.exit(0)}export{$U as startCli};
390
+ `)}function FB(e){let t=e.lastIndexOf(`[`);if(t<=0||!e.endsWith(`]`))return;let n=e.slice(0,t),r=e.slice(t+1,e.length-1);if(/^\d+$/.test(r))return{portKey:n,index:Number.parseInt(r,10)}}const IB={CREATED:`created`,QUEUED:`queued`,RUNNING:`running`,SUCCESS:`success`,FAILED:`failed`,CANCELLED:`cancelled`},X={CREATED:`created`,QUEUED:`queued`,RUNNING:`running`,SUCCESS:`success`,FAILED:`failed`,UPSTREAM_FAILED:`upstream_failed`,SKIPPED:`skipped`,CANCELLED:`cancelled`},LB={STARTED:`execution.started`,COMPLETED:`execution.completed`,FAILED:`execution.failed`},RB={STARTED:`task.started`,COMPLETED:`task.completed`,FAILED:`task.failed`},zB={[`${IB.CREATED}:QUEUE`]:IB.QUEUED,[`${IB.CREATED}:CANCEL`]:IB.CANCELLED,[`${IB.QUEUED}:START`]:IB.RUNNING,[`${IB.QUEUED}:CANCEL`]:IB.CANCELLED,[`${IB.RUNNING}:COMPLETE_SUCCESS`]:IB.SUCCESS,[`${IB.RUNNING}:COMPLETE_FAILURE`]:IB.FAILED,[`${IB.RUNNING}:CANCEL`]:IB.CANCELLED};function BB(e,t){return{code:`DAG_STATE_TRANSITION_INVALID`,category:`state_transition`,message:`DagRun transition is not allowed: ${e} -> ${t}`,retryable:!1,context:{currentStatus:e,event:t}}}function VB(e){return`run.${e}`}var HB=class{static transition(e,t){let n=zB[`${e}:${t}`];return n?{ok:!0,value:{nextStatus:n,domainEvents:[VB(n)]}}:{ok:!1,error:BB(e,t)}}};const UB={[`${X.CREATED}:QUEUE`]:X.QUEUED,[`${X.CREATED}:CANCEL`]:X.CANCELLED,[`${X.QUEUED}:START`]:X.RUNNING,[`${X.QUEUED}:UPSTREAM_FAIL`]:X.UPSTREAM_FAILED,[`${X.QUEUED}:SKIP`]:X.SKIPPED,[`${X.QUEUED}:CANCEL`]:X.CANCELLED,[`${X.RUNNING}:COMPLETE_SUCCESS`]:X.SUCCESS,[`${X.RUNNING}:COMPLETE_FAILURE`]:X.FAILED,[`${X.RUNNING}:CANCEL`]:X.CANCELLED,[`${X.FAILED}:RETRY`]:X.QUEUED};function WB(e,t){return{code:`DAG_STATE_TRANSITION_INVALID`,category:`state_transition`,message:`TaskRun transition is not allowed: ${e} -> ${t}`,retryable:!1,context:{currentStatus:e,event:t}}}function GB(e){return`task.${e}`}var KB=class{static transition(e,t){let n=UB[`${e}:${t}`];return n?{ok:!0,value:{nextStatus:n,domainEvents:[GB(n)]}}:{ok:!1,error:WB(e,t)}}};function qB(e,t,n,r,i,a,o){return{code:t,category:e,message:n,retryable:r,context:i,fix:a,agentHint:o}}function Z(e,t,n,r,i){return qB(`validation`,e,t,!1,n,r,i)}function JB(e,t,n,r,i){return qB(`dispatch`,e,t,!0,n,r,i)}function YB(e,t,n,r,i,a){return qB(`task_execution`,e,t,n,r,i,a)}function XB(e){let t=Date.parse(e);return Number.isNaN(t)?{ok:!1,error:Z(`DAG_VALIDATION_INVALID_LOGICAL_DATE`,`logicalDate must be a valid ISO-8601 datetime string`,{logicalDate:e})}:{ok:!0,value:new Date(t).toISOString()}}var ZB=class{clock;constructor(e){this.clock=e}resolve(e,t){let n=this.clock.nowIso();if(e===`scheduled`){if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_MISSING_LOGICAL_DATE`,`scheduled trigger requires logicalDate`,{trigger:e})};let r=XB(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}if(!t)return{ok:!0,value:{trigger:e,logicalDate:n,requestedAt:n}};let r=XB(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}},QB=class{assertWithinBudget(e,t,n){if(t<0)return{ok:!1,error:Z(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be zero or positive`,{nextEstimatedCredits:t})};let r=e+t;return typeof n==`number`&&r>n?{ok:!1,error:Z(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds runCreditLimit`,{nextTotalCredits:r,runCreditLimit:n})}:{ok:!0,value:r}}},$B=class{lifecycleFactory;costPolicyEvaluator;constructor(e,t){this.lifecycleFactory=e,this.costPolicyEvaluator=t}async runNode(e){let t=this.lifecycleFactory.create(e.context.nodeDefinition.nodeType);if(!t.ok)return t;let n=await t.value.initialize(e.context);if(!n.ok)return n;let r=await t.value.validateInput(e.input,e.context);if(!r.ok)return await t.value.dispose(e.context),r;let i=await t.value.estimateCost(e.input,e.context);if(!i.ok)return await t.value.dispose(e.context),i;let a=this.costPolicyEvaluator.assertWithinBudget(e.context.currentTotalCredits,i.value.estimatedCredits,e.context.runCreditLimit);if(!a.ok)return await t.value.dispose(e.context),a;let o=await t.value.execute(e.input,e.context);if(!o.ok)return await t.value.dispose(e.context),o;let s=await t.value.validateOutput(o.value,e.context);return s.ok?(await t.value.dispose(e.context)).ok?{ok:!0,value:{output:o.value,estimatedCredits:i.value.estimatedCredits,totalCredits:a.value}}:{ok:!1,error:YB(`DAG_TASK_EXECUTION_DISPOSE_FAILED`,`Node dispose step failed after execution`,!1,{nodeType:e.context.nodeDefinition.nodeType,taskRunId:e.context.taskRunId})}:(await t.value.dispose(e.context),s)}},eV=class{create(e){return{ok:!1,error:Z(`DAG_VALIDATION_NODE_LIFECYCLE_NOT_REGISTERED`,`Node lifecycle is not registered for nodeType`,{nodeType:e})}}},tV=class{nodeManifestRegistry;lifecycleFactory;runner;constructor(e,t){this.nodeManifestRegistry=e,this.lifecycleFactory=t??new eV,this.runner=new $B(this.lifecycleFactory,new QB)}async execute(e){if(!e.nodeDefinition)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_DEFINITION_MISSING`,`Task execution requires nodeDefinition in execution input`,{nodeId:e.nodeId})};let t=this.nodeManifestRegistry.getManifest(e.nodeDefinition.nodeType);if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_MANIFEST_NOT_FOUND`,`Node manifest is not registered for nodeType`,{nodeType:e.nodeDefinition.nodeType})};let n=await this.runner.runNode({input:e.input,context:{dagId:e.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeDefinition:e.nodeDefinition,nodeManifest:t,attempt:e.attempt,executionPath:e.executionPath,runCreditLimit:e.costPolicy?.runCreditLimit,currentTotalCredits:e.currentTotalCredits??0}});return n.ok?{ok:!0,output:n.value.output,estimatedCredits:n.value.estimatedCredits,totalCredits:n.value.totalCredits}:n}};const nV={root:`.workflows`,workflowExt:`.json`};function rV(e,t){return`${e}:${t}`}var iV=class{definitions=new Map;latestPublishedVersionByDagId=new Map;dagRuns=new Map;taskRuns=new Map;async saveDefinition(e){let t=`${e.dagId}:${e.version}`;if(this.definitions.set(t,e),e.status===`published`){let t=this.latestPublishedVersionByDagId.get(e.dagId)??0;e.version>t&&this.latestPublishedVersionByDagId.set(e.dagId,e.version)}}async getDefinition(e,t){let n=`${e}:${t}`;return this.definitions.get(n)}async listDefinitions(){return[...this.definitions.values()].sort((e,t)=>e.dagId.localeCompare(t.dagId)||e.version-t.version)}async listDefinitionsByDagId(e){return[...this.definitions.values()].filter(t=>t.dagId===e).sort((e,t)=>e.version-t.version)}async getLatestPublishedDefinition(e){let t=this.latestPublishedVersionByDagId.get(e);if(t)return this.definitions.get(`${e}:${t}`)}async deleteDefinition(e,t){this.definitions.delete(`${e}:${t}`);let n=[...this.definitions.values()].filter(t=>t.dagId===e&&t.status===`published`).sort((e,t)=>e.version-t.version);if(n.length===0){this.latestPublishedVersionByDagId.delete(e);return}this.latestPublishedVersionByDagId.set(e,n[n.length-1].version)}async createDagRun(e){this.dagRuns.set(e.dagRunId,e)}async getDagRun(e){return this.dagRuns.get(e)}async listDagRuns(){return[...this.dagRuns.values()].sort((e,t)=>e.dagRunId.localeCompare(t.dagRunId))}async getDagRunByRunKey(e){for(let t of this.dagRuns.values())if(t.runKey===e)return t}async updateDagRunStatus(e,t,n){let r=this.dagRuns.get(e);if(!r)return;let i={...r,status:t,endedAt:n};this.dagRuns.set(e,i)}async deleteDagRun(e){this.dagRuns.delete(e)}async createTaskRun(e){let t=rV(e.dagRunId,e.taskRunId);this.taskRuns.set(t,e)}async getTaskRun(e){for(let t of this.taskRuns.values())if(t.taskRunId===e)return t}async listTaskRunsByDagRunId(e){let t=[];for(let n of this.taskRuns.values())n.dagRunId===e&&t.push(n);return t}async deleteTaskRunsByDagRunId(e){for(let[t,n]of this.taskRuns.entries())n.dagRunId===e&&this.taskRuns.delete(t)}async updateTaskRunStatus(e,t,n){for(let[r,i]of this.taskRuns.entries()){if(i.taskRunId!==e)continue;let a={...i,status:t,errorCode:n?.code,errorMessage:n?.message};this.taskRuns.set(r,a);return}}async saveTaskRunSnapshots(e,t,n,r,i){for(let[a,o]of this.taskRuns.entries()){if(o.taskRunId!==e)continue;let s={...o,inputSnapshot:typeof t==`string`?t:o.inputSnapshot,outputSnapshot:typeof n==`string`?n:o.outputSnapshot,estimatedCredits:typeof r==`number`?r:o.estimatedCredits,totalCredits:typeof i==`number`?i:o.totalCredits};this.taskRuns.set(a,s);return}}async incrementTaskAttempt(e){for(let[t,n]of this.taskRuns.entries()){if(n.taskRunId!==e)continue;let r={...n,attempt:n.attempt+1};this.taskRuns.set(t,r);return}}},aV=class{pendingQueue=[];inFlight=new Map;waiters=[];async enqueue(e){this.pendingQueue.push(e),this.notifyNextWaiter()}async dequeue(e,t,n=0){let r=this.tryDequeue(e,t);return r||n<=0?r:(await this.waitForMessage(n),this.tryDequeue(e,t))}async ack(e){this.inFlight.delete(e)}async nack(e){let t=this.inFlight.get(e);t&&(this.inFlight.delete(e),this.pendingQueue.unshift(t.message),this.notifyNextWaiter())}tryDequeue(e,t){this.requeueExpiredMessages();let n=this.pendingQueue.shift();if(!n)return;let r=Date.now();return this.inFlight.set(n.messageId,{message:n,ownerId:e,visibleAtEpochMs:r+t}),n}requeueExpiredMessages(){let e=Date.now();for(let[t,n]of this.inFlight.entries())n.visibleAtEpochMs>e||(this.inFlight.delete(t),this.pendingQueue.push(n.message))}async waitForMessage(e){return new Promise(t=>{let n={resolve:()=>{clearTimeout(n.timeout),this.removeWaiter(n),t()},timeout:setTimeout(()=>{n.resolve()},e)};this.waiters.push(n)})}notifyNextWaiter(){this.waiters.shift()?.resolve()}removeWaiter(e){let t=this.waiters.indexOf(e);t>=0&&this.waiters.splice(t,1)}},oV=class{records=new Map;async acquire(e,t,n){let r=new Date().toISOString(),i=Date.now(),a=this.records.get(e);if(a&&Date.parse(a.leaseUntil)>i)return;let o={leaseKey:e,ownerId:t,acquiredAt:r,leaseUntil:new Date(i+n).toISOString()};return this.records.set(e,o),o}async renew(e,t,n){let r=this.records.get(e);if(!r||r.ownerId!==t)return;let i=Date.now(),a={leaseKey:e,ownerId:t,acquiredAt:r.acquiredAt,leaseUntil:new Date(i+n).toISOString()};return this.records.set(e,a),a}async release(e,t){let n=this.records.get(e);!n||n.ownerId!==t||this.records.delete(e)}async get(e){return this.records.get(e)}},sV=class{nowIso(){return new Date().toISOString()}nowEpochMs(){return Date.now()}};function cV(e,t,n){let r=n.issues[0];return Z(`DAG_VALIDATION_NODE_CONFIG_SCHEMA_INVALID`,`Node config does not satisfy schema: ${r?.path.join(`.`)??`config`} ${r?.message??`Invalid config`}`,{nodeId:t.nodeDefinition.nodeId,nodeType:e,issueCount:n.issues.length})}var Q=class{defaultInputPort;defaultOutputPort;taskHandler;constructor(){this.taskHandler={initialize:async e=>{let t=this.parseNodeConfig(e);return t.ok?this.initializeWithConfig(e,t.value):t},validateInput:async(e,t)=>{let n=this.parseNodeConfig(t);return n.ok?this.validateInputWithConfig(e,t,n.value):n},estimateCost:async(e,t)=>{let n=this.parseNodeConfig(t);return n.ok?this.estimateCostWithConfig(e,t,n.value):n},execute:async(e,t)=>{let n=this.parseNodeConfig(t);return n.ok?this.executeWithConfig(e,t,n.value):n},validateOutput:async(e,t)=>{let n=this.parseNodeConfig(t);return n.ok?this.validateOutputWithConfig(e,t,n.value):n},dispose:async e=>{let t=this.parseNodeConfig(e);return t.ok?this.disposeWithConfig(e,t.value):t}}}parseNodeConfig(e){let t=this.configSchemaDefinition.safeParse(e.nodeDefinition.config);return t.success?{ok:!0,value:t.data}:{ok:!1,error:cV(this.nodeType,e,t.error)}}async initializeWithConfig(e,t){return{ok:!0,value:void 0}}async validateInputWithConfig(e,t,n){return{ok:!0,value:void 0}}async validateOutputWithConfig(e,t,n){return{ok:!0,value:void 0}}async disposeWithConfig(e,t){return{ok:!0,value:void 0}}};const lV=`asset://`;var uV=class e{value;constructor(e){this.value=e}static fromAssetReference(t){return t.referenceType===`asset`?new e({referenceType:`asset`,assetId:t.assetId,mediaType:t.mediaType,name:t.name,sizeBytes:t.sizeBytes}):new e({referenceType:`uri`,uri:t.uri,mediaType:t.mediaType,name:t.name,sizeBytes:t.sizeBytes})}static fromBinary(t){if(typeof t.assetId==`string`&&t.assetId.trim().length>0)return{ok:!0,value:new e({referenceType:`asset`,assetId:t.assetId.trim(),mediaType:t.mimeType,sizeBytes:t.sizeBytes})};if(t.uri.startsWith(lV)){let n=t.uri.slice(8).trim();return n.length===0?{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_INVALID`,`Binary asset URI must include non-empty assetId`)}:{ok:!0,value:new e({referenceType:`asset`,assetId:n,mediaType:t.mimeType,sizeBytes:t.sizeBytes})}}return{ok:!0,value:new e({referenceType:`uri`,uri:t.uri,mediaType:t.mimeType,sizeBytes:t.sizeBytes})}}static fromCandidate(e,t){let n=typeof e.assetId==`string`&&(t?.allowEmptyAssetId===!0||e.assetId.trim().length>0),r=typeof e.uri==`string`&&(t?.allowEmptyUri===!0||e.uri.trim().length>0);return n===r?{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_XOR_REQUIRED`,`Exactly one of assetId or uri must be provided`)}:e.referenceType===`asset`&&!n?{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_TYPE_MISMATCH`,`referenceType asset requires assetId`)}:e.referenceType===`uri`&&!r?{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_TYPE_MISMATCH`,`referenceType uri requires uri`)}:this.buildFromValidatedCandidate(e,n)}static buildFromValidatedCandidate(t,n){return n&&typeof t.assetId==`string`?{ok:!0,value:new e({referenceType:`asset`,assetId:t.assetId.trim(),mediaType:t.mediaType,name:t.name,sizeBytes:t.sizeBytes})}:typeof t.uri==`string`?{ok:!0,value:new e({referenceType:`uri`,uri:t.uri,mediaType:t.mediaType,name:t.name,sizeBytes:t.sizeBytes})}:{ok:!1,error:Z(`DAG_VALIDATION_MEDIA_REFERENCE_INVALID`,`uri must be a string when referenceType is uri`)}}isAsset(){return this.value.referenceType===`asset`}isUri(){return this.value.referenceType===`uri`}assetId(){return this.value.assetId}uri(){return this.value.uri}mediaType(){return this.value.mediaType}toAssetIdOrUri(){return this.value.referenceType===`asset`&&typeof this.value.assetId==`string`?{referenceType:`asset`,assetId:this.value.assetId}:{referenceType:`uri`,uri:this.value.uri??``}}toAssetContentUrl(e){if(!(!this.isAsset()||typeof this.value.assetId!=`string`))return`${e.replace(/\/$/,``)}/view?filename=${encodeURIComponent(this.value.assetId)}`}toBinary(e,t){let n=typeof this.value.mediaType==`string`&&this.value.mediaType.trim().length>0?this.value.mediaType:t;return this.value.referenceType===`asset`&&typeof this.value.assetId==`string`?{kind:e,mimeType:n,uri:`${lV}${this.value.assetId}`,referenceType:`asset`,assetId:this.value.assetId,sizeBytes:this.value.sizeBytes}:{kind:e,mimeType:n,uri:this.value.uri??``,referenceType:`uri`,sizeBytes:this.value.sizeBytes}}};function dV(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))return{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be binary payload object`,{nodeId:t,key:n,expectedType:`binary`})};let i=e;if(!(i.kind===`image`||i.kind===`video`||i.kind===`audio`||i.kind===`file`)||typeof i.mimeType!=`string`||typeof i.uri!=`string`)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be valid binary payload`,{nodeId:t,key:n,expectedType:`binary`})};let a=i.kind;return r&&a!==r?{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input binary kind does not match expected kind`,{nodeId:t,key:n,expectedKind:r,actualKind:a})}:{ok:!0,value:{kind:a,mimeType:i.mimeType,uri:i.uri,referenceType:i.referenceType===`asset`||i.referenceType===`uri`?i.referenceType:void 0,assetId:typeof i.assetId==`string`?i.assetId:void 0,sizeBytes:typeof i.sizeBytes==`number`?i.sizeBytes:void 0}}}var $=class{input;nodeId;output={};constructor(e,t){this.input=e,this.nodeId=t}getInput(e){return this.input[e]}requireInput(e){let t=this.getInput(e);return t===void 0?{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_MISSING`,`Node input key is missing`,{nodeId:this.nodeId,key:e})}:{ok:!0,value:t}}requireInputString(e){let t=this.requireInput(e);return t.ok?typeof t.value==`string`?{ok:!0,value:t.value}:{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be string`,{nodeId:this.nodeId,key:e,expectedType:`string`})}:t}requireInputArray(e){let t=this.getInput(e);if(Array.isArray(t))return{ok:!0,value:t};let n=this.collectListHandleValues(e);return n?{ok:!0,value:n}:t===void 0?{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_MISSING`,`Node input key is missing`,{nodeId:this.nodeId,key:e})}:{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be array`,{nodeId:this.nodeId,key:e,expectedType:`array`})}}requireInputBinary(e,t){let n=this.requireInput(e);return n.ok?dV(n.value,this.nodeId,e,t):n}requireInputBinaryList(e,t,n){let r=this.requireInputArray(e);if(!r.ok)return r;let i=r.value;if(typeof n?.minItems==`number`&&i.length<n.minItems)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_MIN_ITEMS_NOT_SATISFIED`,`Node input list does not satisfy minItems`,{nodeId:this.nodeId,key:e,minItems:n.minItems,actualItems:i.length})};if(typeof n?.maxItems==`number`&&i.length>n.maxItems)return{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_MAX_ITEMS_EXCEEDED`,`Node input list exceeds maxItems`,{nodeId:this.nodeId,key:e,maxItems:n.maxItems,actualItems:i.length})};let a=[];for(let[n,r]of i.entries()){let i=dV(r,this.nodeId,`${e}[${n}]`,t);if(!i.ok)return i;a.push(i.value)}return{ok:!0,value:a}}requireInputMediaReference(e,t){let n=this.requireInput(e);return n.ok?this.parseMediaReferenceValue(n.value,e,t):n}requireInputBinaryReference(e,t){let n=this.requireInputBinary(e,t);if(!n.ok)return n;let r=uV.fromBinary(n.value);return r.ok?r:{ok:!1,error:Z(r.error.code,r.error.message,{nodeId:this.nodeId,key:e,...r.error.context??{}})}}setOutput(e,t){this.output[e]=t}toOutput(){return{...this.output}}collectListHandleValues(e){let t=new Map;for(let[n,r]of Object.entries(this.input)){let i=FB(n);!i||i.portKey!==e||t.set(i.index,r)}if(t.size===0)return;let n=[...t.keys()].sort((e,t)=>e-t),r=n[n.length-1]+1;if(n.length!==r)return;let i=[];for(let e=0;e<r;e+=1){let n=t.get(e);if(n===void 0)return;i.push(n)}return i}parseMediaReferenceValue(e,t,n){if(typeof e==`string`){if(n?.allowStringAssetUri===!0&&e.startsWith(`asset://`))return this.wrapMediaReferenceError(uV.fromCandidate({referenceType:`asset`,assetId:e.slice(8)}),t);if(n?.allowStringUri===!0)return this.wrapMediaReferenceError(uV.fromCandidate({referenceType:`uri`,uri:e}),t)}return typeof e!=`object`||!e||Array.isArray(e)?{ok:!1,error:Z(`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`,`Node input key must be media reference object`,{nodeId:this.nodeId,key:t,expectedType:`media-reference`})}:this.wrapMediaReferenceError(uV.fromCandidate(e),t)}wrapMediaReferenceError(e,t){return e.ok?e:{ok:!1,error:Z(e.error.code,e.error.message,{nodeId:this.nodeId,key:t,...e.error.context??{}})}}};function fV(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.kind==`string`&&typeof t.mimeType==`string`&&typeof t.uri==`string`}function pV(e,t){if(e.isList)return Array.isArray(t)?t.every(t=>pV({...e,isList:!1},t)):!1;switch(e.type){case`string`:return typeof t==`string`;case`number`:return typeof t==`number`;case`boolean`:return typeof t==`boolean`;case`object`:return typeof t==`object`&&!!t&&!Array.isArray(t)&&!fV(t);case`array`:return Array.isArray(t);case`binary`:return!(!fV(t)||e.binaryKind&&t.kind!==e.binaryKind||e.mimeTypes&&e.mimeTypes.length>0&&!e.mimeTypes.includes(t.mimeType));default:return!1}}function mV(e,t,n,r){for(let i of t){let t=e[i.key];if(t===void 0){if(i.required)return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_REQUIRED_INPUT_MISSING`:`DAG_VALIDATION_NODE_REQUIRED_OUTPUT_MISSING`,n===`input`?`Required input port "${i.key}" (${i.type}) is missing on node "${r}"`:`Required output port "${i.key}" (${i.type}) was not set by node "${r}"`,{nodeId:r,key:i.key,type:i.type},n===`input`?{action:`connect_port`,suggestion:`Connect a "${i.type}" output to the "${i.key}" input of node "${r}"`}:void 0)};continue}if(i.isList){if(!Array.isArray(t))return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`:`DAG_VALIDATION_NODE_OUTPUT_TYPE_MISMATCH`,n===`input`?`List input port must receive array payload`:`List output port must emit array payload`,{nodeId:r,key:i.key,type:i.type})};if(typeof i.minItems==`number`&&t.length<i.minItems)return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_INPUT_MIN_ITEMS_NOT_SATISFIED`:`DAG_VALIDATION_NODE_OUTPUT_MIN_ITEMS_NOT_SATISFIED`,n===`input`?`List input port does not satisfy minItems`:`List output port does not satisfy minItems`,{nodeId:r,key:i.key,minItems:i.minItems,actualItems:t.length})};if(typeof i.maxItems==`number`&&t.length>i.maxItems)return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_INPUT_MAX_ITEMS_EXCEEDED`:`DAG_VALIDATION_NODE_OUTPUT_MAX_ITEMS_EXCEEDED`,n===`input`?`List input port exceeds maxItems`:`List output port exceeds maxItems`,{nodeId:r,key:i.key,maxItems:i.maxItems,actualItems:t.length})}}if(!pV(i,t))return{ok:!1,error:Z(n===`input`?`DAG_VALIDATION_NODE_INPUT_TYPE_MISMATCH`:`DAG_VALIDATION_NODE_OUTPUT_TYPE_MISMATCH`,n===`input`?`Input port "${i.key}" on node "${r}" expects type "${i.type}" but received incompatible value`:`Output port "${i.key}" on node "${r}" emitted value incompatible with type "${i.type}"`,{nodeId:r,key:i.key,type:i.type},n===`input`?{action:`check_port_type`,suggestion:`Ensure the upstream output connected to "${i.key}" produces a "${i.type}" value`}:void 0)}}return{ok:!0,value:void 0}}var hV=class{handler;constructor(e){this.handler=e}async initialize(e){return this.handler.initialize?this.handler.initialize(e):{ok:!0,value:void 0}}async validateInput(e,t){let n=mV(e,t.nodeManifest.inputs,`input`,t.nodeDefinition.nodeId);return n.ok?this.handler.validateInput?this.handler.validateInput(e,t):{ok:!0,value:void 0}:n}async estimateCost(e,t){return this.handler.estimateCost?this.handler.estimateCost(e,t):{ok:!0,value:{estimatedCredits:0}}}async execute(e,t){return this.handler.execute(e,t)}async validateOutput(e,t){let n=mV(e,t.nodeManifest.outputs,`output`,t.nodeDefinition.nodeId);return n.ok?this.handler.validateOutput?this.handler.validateOutput(e,t):{ok:!0,value:void 0}:n}async dispose(e){return this.handler.dispose?this.handler.dispose(e):{ok:!0,value:void 0}}},gV=class{handlersByType;constructor(e){this.handlersByType=e}getHandler(e){return this.handlersByType[e]}listNodeTypes(){return Object.keys(this.handlersByType)}},_V=class{taskHandlerRegistry;constructor(e){this.taskHandlerRegistry=e}create(e){let t=this.taskHandlerRegistry.getHandler(e);return t?{ok:!0,value:new hV(t)}:{ok:!1,error:Z(`DAG_VALIDATION_NODE_LIFECYCLE_NOT_REGISTERED`,`Node lifecycle is not registered for nodeType`,{nodeType:e})}}},vV=class{manifestByType=new Map;constructor(e){for(let t of e)this.manifestByType.set(t.nodeType,t)}getManifest(e){return this.manifestByType.get(e)}listManifests(){return[...this.manifestByType.values()]}};const yV=j.string().trim().min(1);j.enum([`asset`,`uri`]);const bV=j.object({referenceType:j.literal(`asset`),assetId:yV,mediaType:j.string().optional(),name:j.string().optional(),sizeBytes:j.number().int().nonnegative().optional()}),xV=j.object({referenceType:j.literal(`uri`),uri:yV,mediaType:j.string().optional(),name:j.string().optional(),sizeBytes:j.number().int().nonnegative().optional()}),SV=j.union([bV,xV]);function CV(){return j.object({asset:SV})}function wV(e){return typeof e!=`object`||!e?!1:e instanceof j.ZodType}function TV(e){return e==null?{ok:!0,value:{}}:wV(e)?{ok:!0,value:it(e,{target:`jsonSchema7`})}:{ok:!1,error:Z(`DAG_VALIDATION_CONFIG_SCHEMA_INVALID`,`configSchemaDefinition must be a Zod schema instance.`)}}function EV(e){let t=[],n={};for(let r of e){let e=TV(r.configSchemaDefinition);if(!e.ok)return e;let i={nodeType:r.nodeType,displayName:r.displayName,category:r.category,inputs:r.inputs,outputs:r.outputs,configSchema:e.value,...r.defaultInputPort===void 0?{}:{defaultInputPort:r.defaultInputPort},...r.defaultOutputPort===void 0?{}:{defaultOutputPort:r.defaultOutputPort}};t.push(i),n[i.nodeType]=r.taskHandler}return{ok:!0,value:{manifests:t,handlersByType:n}}}const DV={IMAGE_PNG:{binaryKind:`image`,mimeTypes:[`image/png`]},IMAGE_COMMON:{binaryKind:`image`,mimeTypes:[`image/png`,`image/jpeg`,`image/webp`]},VIDEO_MP4:{binaryKind:`video`,mimeTypes:[`video/mp4`]},AUDIO_MPEG:{binaryKind:`audio`,mimeTypes:[`audio/mpeg`]},FILE_GENERIC:{binaryKind:`file`,mimeTypes:[]}};function OV(e){return{key:e.key,label:e.label,order:e.order,type:`binary`,required:e.required,description:e.description,binaryKind:e.preset.binaryKind,mimeTypes:[...e.preset.mimeTypes],isList:e.isList,minItems:e.minItems,maxItems:e.maxItems}}var kV=class{listeners=new Set;logger;constructor(e){this.logger=e}publish(e){let t=[];for(let n of[...this.listeners])try{n(e)}catch(n){t.push(n),this.logger&&this.logger.error(`RunProgressEventBus listener threw an error`,{eventType:e.eventType,error:n instanceof Error?n.message:String(n)})}if(t.length>0&&!this.logger)throw t[0]instanceof Error?t[0]:Error(String(t[0]))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function AV(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t||Array.isArray(t)?{ok:!1,error:Z(`DAG_VALIDATION_PAYLOAD_INVALID`,`Payload must be a JSON object`)}:{ok:!0,value:t}}catch{return{ok:!1,error:Z(`DAG_VALIDATION_PAYLOAD_PARSE_FAILED`,`Failed to parse payload JSON`)}}}function jV(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t||Array.isArray(t)||!(`dagId`in t)||!(`version`in t)||!(`nodes`in t)||!(`edges`in t)||!(`status`in t)||typeof t.dagId!=`string`||typeof t.version!=`number`||!Array.isArray(t.nodes)||!Array.isArray(t.edges)||typeof t.status!=`string`?{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`Definition snapshot must be a valid DAG definition object`)}:{ok:!0,value:t}}catch{return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse definition snapshot JSON`)}}}async function MV(e,t,n,r,i){let{dagRunId:a,definition:o,input:s}=e,c=o.nodes.filter(e=>e.dependsOn.length===0);if(c.length===0)return{ok:!1,error:Z(`DAG_VALIDATION_NO_ENTRY_NODE`,`DAG must include at least one entry node (dependsOn = [])`,{dagId:o.dagId,version:o.version})};let l=HB.transition(`created`,`QUEUE`);if(!l.ok)return l;await t.updateDagRunStatus(a,l.value.nextStatus);let u=HB.transition(`queued`,`START`);if(!u.ok)return u;await t.updateDagRunStatus(a,u.value.nextStatus),i?.publish({dagRunId:a,eventType:LB.STARTED,occurredAt:r.nowIso(),dagId:o.dagId,version:o.version});let d=[];for(let e of c){let c=`${a}:${e.nodeId}:attempt:1`;d.push(c),await t.createTaskRun({taskRunId:c,dagRunId:a,nodeId:e.nodeId,status:`queued`,attempt:1});let l={messageId:`${c}:message`,dagRunId:a,taskRunId:c,nodeId:e.nodeId,attempt:1,executionPath:[`dagId:${o.dagId}`,`dagRunId:${a}`,`nodeId:${e.nodeId}`,`taskRunId:${c}`,`attempt:1`],payload:s,createdAt:r.nowIso()};try{await n.enqueue(l)}catch(n){return NV(a,c,e.nodeId,d,n,t,r,i)}}return{ok:!0,value:{taskRunIds:d}}}async function NV(e,t,n,r,i,a,o,s){let c=JB(`DAG_DISPATCH_ENQUEUE_FAILED`,`Failed to enqueue entry task`,{dagRunId:e,taskRunId:t,nodeId:n,errorMessage:i instanceof Error&&i.message.trim().length>0?i.message:`Unknown error`}),l=KB.transition(`queued`,`CANCEL`);if(l.ok){await a.updateTaskRunStatus(t,l.value.nextStatus,c);for(let e of r)e!==t&&await a.updateTaskRunStatus(e,l.value.nextStatus,c)}let u=HB.transition(`running`,`COMPLETE_FAILURE`);return u.ok&&(await a.updateDagRunStatus(e,u.value.nextStatus,o.nowIso()),s?.publish({dagRunId:e,eventType:LB.FAILED,occurredAt:o.nowIso(),error:c})),{ok:!1,error:c}}var PV=class{storage;queue;clock;runProgressEventReporter;timeSemanticsService;constructor(e,t,n,r){this.storage=e,this.queue=t,this.clock=n,this.runProgressEventReporter=r,this.timeSemanticsService=new ZB(n)}async createRun(e){let t=e.version?await this.storage.getDefinition(e.dagId,e.version):await this.storage.getLatestPublishedDefinition(e.dagId);if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_NOT_FOUND`,`Published DAG definition was not found`,{dagId:e.dagId,hasVersion:!!e.version})};if(t.status!==`published`)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_NOT_PUBLISHED`,`Only published definitions can be executed`,{dagId:t.dagId,version:t.version,status:t.status})};let n=this.timeSemanticsService.resolve(e.trigger,e.logicalDate);if(!n.ok)return n;let r=e.rerunKey?`${t.dagId}:${n.value.logicalDate}:rerun:${e.rerunKey}`:`${t.dagId}:${n.value.logicalDate}`,i=await this.storage.getDagRunByRunKey(r);if(i)return{ok:!0,value:{dagRunId:i.dagRunId,dagId:i.dagId,version:i.version,logicalDate:i.logicalDate,status:i.status}};let a=this.generateDagRunId(t.dagId,n.value.logicalDate,e.rerunKey);try{await this.storage.createDagRun({dagRunId:a,dagId:t.dagId,version:t.version,status:`created`,definitionSnapshot:JSON.stringify(t),inputSnapshot:JSON.stringify(e.input),runKey:r,logicalDate:n.value.logicalDate,trigger:e.trigger,startedAt:this.clock.nowIso()})}catch(e){return{ok:!1,error:JB(`DAG_DISPATCH_DAG_RUN_CREATE_FAILED`,`Failed to create DagRun`,{dagId:t.dagId,version:t.version,runKey:r,errorMessage:this.resolveErrorMessage(e instanceof Error?e:void 0)})}}return{ok:!0,value:{dagRunId:a,dagId:t.dagId,version:t.version,logicalDate:n.value.logicalDate,status:`created`}}}async startCreatedRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};if(t.status!==`created`){let n=await this.storage.listTaskRunsByDagRunId(e);return{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}if(typeof t.definitionSnapshot!=`string`||t.definitionSnapshot.trim().length===0)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:e})};let n=jV(t.definitionSnapshot);if(!n.ok)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot is invalid`,{dagRunId:e})};let r=AV(t.inputSnapshot??`{}`);if(!r.ok)return{ok:!1,error:Z(`DAG_VALIDATION_RUN_INPUT_SNAPSHOT_INVALID`,`DagRun input snapshot is invalid`,{dagRunId:e})};let i=await MV({dagRunId:e,definition:n.value,input:r.value},this.storage,this.queue,this.clock,this.runProgressEventReporter);return i.ok?{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:i.value.taskRunIds}}:i}async startRun(e){let t=await this.createRun(e);if(!t.ok)return t;if(t.value.status===`created`)return this.startCreatedRun(t.value.dagRunId);let n=await this.storage.listTaskRunsByDagRunId(t.value.dagRunId);return{ok:!0,value:{dagRunId:t.value.dagRunId,dagId:t.value.dagId,version:t.value.version,logicalDate:t.value.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}generateDagRunId(e,t,n){let r=Date.parse(t);return n?`${e}:run:${r}:rerun:${n}`:`${e}:run:${r}`}resolveErrorMessage(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}},FV=class{storage;constructor(e){this.storage=e}async getRun(e){let t=await this.storage.getDagRun(e);return t?{ok:!0,value:{dagRun:t,taskRuns:await this.storage.listTaskRunsByDagRunId(e)}}:{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}},IV=class{storage;clock;constructor(e,t){this.storage=e,this.clock=t}async cancelRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};let n=HB.transition(t.status,`CANCEL`);return n.ok?(await this.storage.updateDagRunStatus(e,n.value.nextStatus,this.clock.nowIso()),{ok:!0,value:{dagRunId:e,status:`cancelled`}}):n}};function LV(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function RV(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zV(e,t,n){let r=e.nodes.find(e=>e.nodeId===n);if(!r)return{ok:!1,error:Z(`DAG_VALIDATION_DOWNSTREAM_NODE_NOT_FOUND`,`Downstream node was not found while building payload`,{downstreamNodeId:n})};let i=e.edges.filter(e=>e.to===n);if(i.length===0)return{ok:!0,value:{}};let a={};for(let e of i){let n=BV(a,e,r,t);if(!n.ok)return n}return GV(a,r.inputs??[]),{ok:!0,value:a}}function BV(e,t,n,r){if(!t.bindings||t.bindings.length===0)return{ok:!1,error:Z(`DAG_VALIDATION_BINDING_REQUIRED`,`Incoming edge must define at least one binding`,{from:t.from,to:t.to})};let i=VV(t.from,t.to,r);if(!i.ok)return i;let a=i.value;for(let r of t.bindings){let i=HV(e,r,a,t,n);if(!i.ok)return i}return{ok:!0,value:void 0}}function VV(e,t,n){let r=n.find(t=>t.nodeId===e&&t.status===`success`);if(!r||!r.outputSnapshot)return{ok:!1,error:Z(`DAG_VALIDATION_UPSTREAM_OUTPUT_MISSING`,`Upstream output snapshot is missing for binding dispatch`,{from:e,to:t})};try{let n=JSON.parse(r.outputSnapshot);return RV(n)?{ok:!0,value:n}:{ok:!1,error:Z(`DAG_VALIDATION_UPSTREAM_OUTPUT_INVALID`,`Upstream output snapshot has invalid payload shape`,{from:e,to:t})}}catch(n){return{ok:!1,error:Z(`DAG_VALIDATION_UPSTREAM_OUTPUT_PARSE_FAILED`,`Failed to parse upstream output snapshot`,{from:e,to:t,errorMessage:LV(n)})}}}function HV(e,t,n,r,i){let a=n[t.outputKey];if(a===void 0)return{ok:!1,error:Z(`DAG_VALIDATION_BINDING_OUTPUT_KEY_MISSING`,`Binding outputKey was not found in upstream output`,{from:r.from,outputKey:t.outputKey})};if((i.inputs??[]).find(e=>e.key===t.inputKey)?.isList)return UV(e,t.inputKey,a,r.to);let o=FB(t.inputKey);return o?WV(e,o,a,t.inputKey,r.to,i):e[t.inputKey]===void 0?(e[t.inputKey]=a,{ok:!0,value:void 0}):{ok:!1,error:Z(`DAG_VALIDATION_BINDING_INPUT_KEY_CONFLICT`,`Multiple bindings target the same input key`,{to:r.to,inputKey:t.inputKey})}}function UV(e,t,n,r){Array.isArray(e[t])||(e[t]=[]);let i=e[t];return Array.isArray(i)?(i.push(n),{ok:!0,value:void 0}):{ok:!1,error:Z(`DAG_VALIDATION_BINDING_LIST_PAYLOAD_INVALID`,`List payload container is invalid`,{to:r,inputKey:t})}}function WV(e,t,n,r,i,a){if(!(a.inputs??[]).find(e=>e.key===t.portKey)?.isList)return{ok:!1,error:Z(`DAG_VALIDATION_BINDING_INPUT_KEY_MISSING`,`Binding inputKey does not resolve to a valid list input port`,{to:i,inputKey:r})};let o=e[t.portKey],s=Array.isArray(o)?o:[];return s[t.index]=n,e[t.portKey]=s,{ok:!0,value:void 0}}function GV(e,t){for(let n of t){if(!n.isList)continue;let t=e[n.key];Array.isArray(t)&&(e[n.key]=t.filter(e=>e!==void 0))}}function KV(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function qV(e,t,n,r,i,a,o){let s=t.nodes.filter(e=>e.dependsOn.includes(n));if(s.length===0)return{ok:!0,value:void 0};let c=await i.listTaskRunsByDagRunId(e.dagRunId);for(let n of s){let r=await JV(e,t,n,c,i,a,o);if(!r.ok)return r}return{ok:!0,value:void 0}}async function JV(e,t,n,r,i,a,o){if(r.some(e=>e.nodeId===n.nodeId)||!n.dependsOn.every(e=>r.some(t=>t.nodeId===e&&t.status===`success`)))return{ok:!0,value:void 0};let s=`${e.dagRunId}:${n.nodeId}:attempt:1`;await i.createTaskRun({taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1});let c=zV(t,r,n.nodeId);if(!c.ok)return c;let l=n.timeoutMs?{...c.value,timeoutMs:n.timeoutMs}:c.value,u={messageId:`${s}:message:1`,dagRunId:e.dagRunId,taskRunId:s,nodeId:n.nodeId,attempt:1,executionPath:[`dagId:${e.dagId}`,`dagRunId:${e.dagRunId}`,`nodeId:${n.nodeId}`,`taskRunId:${s}`,`attempt:1`],payload:l,createdAt:o.nowIso()};try{await a.enqueue(u)}catch(t){let r=KB.transition(`queued`,`CANCEL`);return r.ok&&await i.updateTaskRunStatus(s,r.value.nextStatus),{ok:!1,error:JB(`DAG_DISPATCH_ENQUEUE_DOWNSTREAM_FAILED`,`Failed to enqueue downstream task`,{dagRunId:e.dagRunId,nodeId:n.nodeId,errorMessage:KV(t)})}}return r.push({taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}),{ok:!0,value:void 0}}const YV=new Set([`created`,`queued`,`running`]),XV=new Set([`failed`]);async function ZV(e,t,n,r){let i=await t.getDagRun(e);if(!i)return{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found while finalizing run status`,{dagRunId:e})};if(i.status!==`running`)return{ok:!0,value:void 0};let a=await t.listTaskRunsByDagRunId(e);if(a.some(e=>YV.has(e.status)))return{ok:!0,value:void 0};let o=a.some(e=>XV.has(e.status)),s=HB.transition(i.status,o?`COMPLETE_FAILURE`:`COMPLETE_SUCCESS`);return s.ok?(await t.updateDagRunStatus(e,s.value.nextStatus,n.nowIso()),o?QV(e,a,n,r):r?.publish({dagRunId:e,eventType:LB.COMPLETED,occurredAt:n.nowIso()}),{ok:!0,value:void 0}):s}function QV(e,t,n,r){let i=t.find(e=>XV.has(e.status)),a=typeof i?.errorCode==`string`&&typeof i.errorMessage==`string`?YB(i.errorCode,i.errorMessage,!1,{dagRunId:e,taskRunId:i.taskRunId,nodeId:i.nodeId}):YB(`DAG_TASK_EXECUTION_FAILED`,`Run completed with failure.`,!1,{dagRunId:e});r?.publish({dagRunId:e,eventType:LB.FAILED,occurredAt:n.nowIso(),error:a})}function $V(e,t){return YB(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${t}ms`,!0,{taskRunId:e,timeoutMs:t})}function eH(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function tH(e,t,n,r){return new Promise(i=>{let a=!1,o=setTimeout(()=>{a||(a=!0,i({ok:!1,error:$V(r,n)}))},n);e.execute(t).then(e=>{a||(a=!0,clearTimeout(o),i(e))}).catch(e=>{a||(a=!0,clearTimeout(o),i({ok:!1,error:YB(`DAG_TASK_EXECUTION_EXCEPTION`,`Task executor threw an exception`,!0,{taskRunId:r,errorMessage:eH(e)})}))})})}function nH(e){let t=0;for(let n of e)typeof n.totalCredits==`number`&&n.totalCredits>t&&(t=n.totalCredits);return t}function rH(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function iH(e,t){if(typeof e.definitionSnapshot!=`string`||e.definitionSnapshot.trim().length===0)return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:t})};try{let n=JSON.parse(e.definitionSnapshot);return aH(n)?{ok:!0,value:n}:{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot has invalid shape`,{dagRunId:t})}}catch(e){return{ok:!1,error:Z(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse DagRun definition snapshot`,{dagRunId:t,errorMessage:rH(e)})}}}function aH(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.dagId==`string`&&typeof e.version==`number`&&Array.isArray(e.nodes)&&Array.isArray(e.edges)&&typeof e.status==`string`}async function oH(e,t){let n=await e.getDagRun(t.dagRunId);if(!n)return{ok:!1,error:Z(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found for dequeued message`,{dagRunId:t.dagRunId})};let r=iH(n,t.dagRunId);if(!r.ok)return r;let i=r.value,a=i.nodes.find(e=>e.nodeId===t.nodeId);return a?{ok:!0,value:{dagRun:n,definition:i,nodeDefinition:a}}:{ok:!1,error:Z(`DAG_VALIDATION_NODE_NOT_FOUND`,`Node definition not found for task execution`,{nodeId:t.nodeId,dagId:n.dagId,version:n.version})}}function sH(e,t){let n=e.map(e=>e.startsWith(`attempt:`)?`attempt:${t}`:e);return n.some(e=>e.startsWith(`attempt:`))||n.push(`attempt:${t}`),n}function cH(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function lH(e,t,n,r,i,a,o,s){if(r.deadLetterEnabled){let t=await dH(e,n,r,o);if(!t.ok)return fH(a,e.messageId,t.error)}let c=await ZV(e.dagRunId,i,o,s);return c.ok?pH(a,e.messageId,t,!1):fH(a,e.messageId,c.error)}async function uH(e,t,n,r,i){let a=KB.transition(`failed`,`RETRY`);if(!a.ok)return fH(r,e.messageId,a.error);await n.incrementTaskAttempt(t),await n.updateTaskRunStatus(t,a.value.nextStatus);let o=e.attempt+1,s={...e,messageId:`${e.taskRunId}:message:${o}`,attempt:o,executionPath:sH(e.executionPath,o),createdAt:i.nowIso()};try{await r.enqueue(s)}catch(n){return fH(r,e.messageId,JB(`DAG_DISPATCH_ENQUEUE_RETRY_FAILED`,`Failed to enqueue retry message`,{taskRunId:t,attempt:o,errorMessage:cH(n)}))}return pH(r,e.messageId,t,!0)}async function dH(e,t,n,r){if(!n.deadLetterQueue)return{ok:!1,error:Z(`DAG_VALIDATION_DEAD_LETTER_QUEUE_NOT_CONFIGURED`,`deadLetterEnabled requires deadLetterQueue to be configured`,{taskRunId:e.taskRunId})};let i={...e,messageId:`${e.taskRunId}:dlq:${r.nowEpochMs()}`,payload:{...e.payload,dlqReasonCode:t.code,dlqReasonMessage:t.message,dlqSourceMessageId:e.messageId},createdAt:r.nowIso()};try{return await n.deadLetterQueue.enqueue(i),{ok:!0,value:void 0}}catch(t){return{ok:!1,error:JB(`DAG_DISPATCH_DEAD_LETTER_ENQUEUE_FAILED`,`Failed to enqueue dead letter message`,{taskRunId:e.taskRunId,originalMessageId:e.messageId,errorMessage:cH(t)})}}}async function fH(e,t,n){return await e.ack(t),{ok:!1,error:n}}async function pH(e,t,n,r){return await e.ack(t),{ok:!0,value:{processed:!0,taskRunId:n,retried:r}}}var mH=class{storage;queue;lease;executor;clock;options;runProgressEventReporter;constructor(e,t,n,r,i,a,o){this.storage=e,this.queue=t,this.lease=n,this.executor=r,this.clock=i,this.options=a,this.runProgressEventReporter=o}async processOnce(){let e=await this.queue.dequeue(this.options.workerId,this.options.visibilityTimeoutMs,this.options.idleWaitMs);if(!e)return{ok:!0,value:{processed:!1}};let t=`taskRun:${e.taskRunId}`;if(!await this.lease.acquire(t,this.options.workerId,this.options.leaseDurationMs))return await this.queue.nack(e.messageId),{ok:!0,value:{processed:!1}};try{return this.processAcquiredMessage(e)}finally{await this.lease.release(t,this.options.workerId)}}async processAcquiredMessage(e){let t=await this.storage.getTaskRun(e.taskRunId);if(!t)return fH(this.queue,e.messageId,Z(`DAG_VALIDATION_TASK_RUN_NOT_FOUND`,`TaskRun not found for dequeued message`,{taskRunId:e.taskRunId}));let n=await this.transitionToRunning(e,t);if(!n.ok)return fH(this.queue,e.messageId,n.error);let r=await oH(this.storage,e);if(!r.ok)return fH(this.queue,e.messageId,r.error);let{dagRun:i,definition:a,nodeDefinition:o}=r.value,s=await this.buildExecutionInput(e,i,a,o),c=this.resolveTimeoutMs(e),l=await tH(this.executor,s,c,e.taskRunId);return l.ok?this.handleSuccessPath(e,t.taskRunId,i,a,l.output,l.estimatedCredits,l.totalCredits):this.handleFailurePath(e,t.taskRunId,l.error)}async transitionToRunning(e,t){let n=KB.transition(t.status,`START`);return n.ok?(await this.storage.updateTaskRunStatus(t.taskRunId,n.value.nextStatus),this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:RB.STARTED,occurredAt:this.clock.nowIso(),taskRunId:t.taskRunId,nodeId:e.nodeId,input:e.payload}),await this.storage.saveTaskRunSnapshots(t.taskRunId,JSON.stringify(e.payload)),{ok:!0,value:void 0}):n}async buildExecutionInput(e,t,n,r){let i=nH(await this.storage.listTaskRunsByDagRunId(e.dagRunId));return{dagId:t.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:e.attempt,executionPath:e.executionPath,input:e.payload,nodeDefinition:r,costPolicy:n.costPolicy,currentTotalCredits:i}}async handleSuccessPath(e,t,n,r,i,a,o){let s=KB.transition(`running`,`COMPLETE_SUCCESS`);if(!s.ok)return fH(this.queue,e.messageId,s.error);await this.completeTaskRun(e,t,s.value.nextStatus,i,a,o);let c=await qV(n,r,e.nodeId,i,this.storage,this.queue,this.clock);if(!c.ok)return fH(this.queue,e.messageId,c.error);let l=await ZV(e.dagRunId,this.storage,this.clock,this.runProgressEventReporter);return l.ok?pH(this.queue,e.messageId,t,!1):fH(this.queue,e.messageId,l.error)}async handleFailurePath(e,t,n){let r=KB.transition(`running`,`COMPLETE_FAILURE`);return r.ok?(await this.storage.updateTaskRunStatus(t,r.value.nextStatus,n),this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:RB.FAILED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,error:n}),this.options.retryEnabled&&n.retryable&&e.attempt<this.options.maxAttempts?uH(e,t,this.storage,this.queue,this.clock):lH(e,t,n,this.options,this.storage,this.queue,this.clock,this.runProgressEventReporter)):fH(this.queue,e.messageId,r.error)}async completeTaskRun(e,t,n,r,i,a){await this.storage.updateTaskRunStatus(t,n),await this.storage.saveTaskRunSnapshots(t,void 0,JSON.stringify(r),i,a),this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:RB.COMPLETED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,output:r})}resolveTimeoutMs(e){let t=e.payload.timeoutMs;return typeof t==`number`&&t>0?t:this.options.defaultTimeoutMs}};function hH(e,t){let n={...t,retryEnabled:t.retryEnabled??!1,deadLetterEnabled:t.deadLetterEnabled??!1,deadLetterQueue:e.deadLetterQueue};return new mH(e.storage,e.queue,e.lease,e.executor,e.clock,n,e.runProgressEventReporter)}function gH(e){return`parallel`in e}function _H(e,t){return e.id??`${e.nodeType}-${t}`}function vH(e,t){return e.find(e=>e.nodeType===t)}function yH(e,t){let n=t.map(e=>e.nodeType),r={action:`replace_node_type`,suggestion:n[0],options:n};return Z(`UNKNOWN_NODE_TYPE`,`Node type "${e}" is not registered`,{requestedType:e},r)}function bH(e,t){let n=[],r=[],i=[],a=[],o=0;for(let s of e.pipeline)if(gH(s)){let e=[];for(let c of s.parallel){let l=_H(c,o);o+=1;let u=vH(t,c.nodeType);if(!u)return{ok:!1,error:yH(c.nodeType,t),warnings:n};let d=a.map(e=>e.nodeId);r.push({nodeId:l,nodeType:c.nodeType,dependsOn:d,config:c.config??{}});for(let e of a){let t=c.toPort??u.defaultInputPort;if(!t){n.push({message:`Node "${l}" (${c.nodeType}) has no defaultInputPort; edge from "${e.nodeId}" requires explicit toPort`});continue}i.push({from:e.nodeId,to:l,bindings:[{outputKey:e.portKey,inputKey:t}]})}let f=s.fromPort??c.fromPort??u.defaultOutputPort;f?e.push({nodeId:l,portKey:f}):n.push({message:`Node "${l}" (${c.nodeType}) has no defaultOutputPort; downstream connections require explicit fromPort`})}a=e}else{let e=_H(s,o);o+=1;let c=vH(t,s.nodeType);if(!c)return{ok:!1,error:yH(s.nodeType,t),warnings:n};let l=a.map(e=>e.nodeId);r.push({nodeId:e,nodeType:s.nodeType,dependsOn:l,config:s.config??{}});for(let t of a){let r=s.toPort??c.defaultInputPort;if(!r){n.push({message:`Node "${e}" (${s.nodeType}) has no defaultInputPort; edge from "${t.nodeId}" requires explicit toPort`});continue}i.push({from:t.nodeId,to:e,bindings:[{outputKey:t.portKey,inputKey:r}]})}let u=s.fromPort??c.defaultOutputPort;a=u?[{nodeId:e,portKey:u}]:[]}return r.length===0?{ok:!1,error:Z(`EMPTY_PIPELINE`,`pipeline must contain at least one node`,void 0,{action:`add_node`,suggestion:`Add at least one node spec to the pipeline array`}),warnings:n}:{ok:!0,definition:{dagId:e.dagId??`dag-build-result`,version:1,status:`draft`,nodes:r,edges:i},warnings:n,nodeCount:r.length,edgeCount:i.length}}const xH=`Robota`,SH=`robota_config`;function CH(e){return`${xH}${e.split(`-`).map(e=>e.length>0?e[0].toUpperCase()+e.slice(1):``).join(``)}`}function wH(e){return(e.startsWith(xH)?e.slice(6):e).replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`).replace(/^-/,``)}function TH(e){let t=new Map;e.nodes.forEach((e,n)=>{t.set(e.nodeId,n+1)});let n=new Map,r=new Map;for(let t of e.edges)for(let e of t.bindings??[]){n.has(t.from)||n.set(t.from,new Map);let i=n.get(t.from);i.has(e.outputKey)||i.set(e.outputKey,i.size),r.has(t.to)||r.set(t.to,new Map);let a=r.get(t.to);a.has(e.inputKey)||a.set(e.inputKey,a.size)}let i=[],a=1,o=new Map,s=new Map;for(let n of e.nodes){let e=t.get(n.nodeId);o.set(e,[]),s.set(e,[])}for(let c of e.edges){let e=t.get(c.from),l=t.get(c.to);if(!(e===void 0||l===void 0))for(let t of c.bindings??[]){let u=a++,d=n.get(c.from)?.get(t.outputKey)??0,f=r.get(c.to)?.get(t.inputKey)??0,p=`STRING`;i.push([u,e,d,l,f,p]);let m=s.get(e),h=m.find(e=>e.name===t.outputKey);h||(h={name:t.outputKey,type:p,links:[]},m.push(h)),h.links.push(u);let g=o.get(l);g.find(e=>e.name===t.inputKey)||g.push({name:t.inputKey,type:p,link:u})}}let c=e.nodes.map(e=>{let n=t.get(e.nodeId),r=o.get(n),i=s.get(n),a={id:n,type:CH(e.nodeType),pos:[e.position?.x??0,e.position?.y??0],properties:{[SH]:e.config},widgets_values:Object.values(e.config)};return r.length>0&&(a.inputs=r),i.length>0&&(a.outputs=i),a}),l={last_node_id:e.nodes.length,last_link_id:a-1,nodes:c,links:i,version:.4},u={};for(let n of e.nodes){let e=t.get(n.nodeId),r={nodeId:n.nodeId};n.retryPolicy&&(r.retryPolicy=n.retryPolicy),n.timeoutMs!==void 0&&(r.timeoutMs=n.timeoutMs),n.costPolicy&&(r.costPolicy=n.costPolicy),u[String(e)]=r}let d={dagId:e.dagId,version:e.version,status:e.status,nodes:u};return e.costPolicy&&(d.costPolicy=e.costPolicy),e.inputSchema&&(d.inputSchema=e.inputSchema),e.outputSchema&&(d.outputSchema=e.outputSchema),{workflowFile:l,companion:d}}function EH(e,t){let n=new Map;for(let t of e.links)n.set(t[0],t);let r=t?.nodes??{},i=e.nodes.map(e=>{let t=r[String(e.id)],n={nodeId:t?.nodeId??`node-${e.id}`,nodeType:wH(e.type),dependsOn:[],config:e.properties?.[SH]??{},position:e.pos[0]!==0||e.pos[1]!==0?{x:e.pos[0],y:e.pos[1]}:void 0};return t?.retryPolicy&&(n.retryPolicy=t.retryPolicy),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),t?.costPolicy&&(n.costPolicy=t.costPolicy),n}),a=new Map;e.nodes.forEach((e,t)=>{a.set(e.id,i[t])});let o=new Map,s=new Map;for(let t of e.links){let[,n,,r]=t,i=a.get(n),c=a.get(r);if(!i||!c)continue;let l=e.nodes.find(e=>e.id===n),u=e.nodes.find(e=>e.id===r),d=t[2],f=t[4],p=l?.outputs?.[d]?.name??`out${d}`,m=u?.inputs?.[f]?.name??`in${f}`,h=`${i.nodeId}:${c.nodeId}`;o.has(h)||o.set(h,[]),o.get(h).push({outputKey:p,inputKey:m}),s.has(c.nodeId)||s.set(c.nodeId,new Set),s.get(c.nodeId).add(i.nodeId)}for(let e of i){let t=s.get(e.nodeId);t&&(e.dependsOn=[...t])}let c=[];for(let[e,t]of o){let[n,r]=e.split(`:`);c.push({from:n,to:r,bindings:t})}return{dagId:t?.dagId??`unknown`,version:t?.version??1,status:t?.status??`active`,nodes:i,edges:c,...t?.costPolicy?{costPolicy:t.costPolicy}:{},...t?.inputSchema?{inputSchema:t.inputSchema}:{},...t?.outputSchema?{outputSchema:t.outputSchema}:{}}}function DH(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.links)&&typeof t.version==`number`&&!(`dagId`in t)}function OH(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.dagId==`string`&&Array.isArray(t.nodes)}const kH=j.object({text:j.string().default(``)});var AH=class extends Q{nodeType=`input`;displayName=`Input`;category=`Core`;defaultOutputPort=`text`;inputs=[];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=kH;async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,`input`),i=typeof e.text==`string`?e.text:n.text;return r.setOutput(`text`,i),r.setOutput(`_agentSummary`,`Input: ${i.length} chars.`),{ok:!0,value:r.toOutput()}}};const jH=j.object({ports:j.array(j.string()).default([]),values:j.record(j.string()).default({})});var MH=class extends Q{nodeType=`multi-input`;displayName=`Multi-Input`;category=`Core`;inputs=[];outputs=[];configSchemaDefinition=jH;async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,`multi-input`),i=n.ports.length>0?n.ports:Object.keys({...n.values,...e});for(let t of i){if(t===`_agentSummary`)continue;let i=typeof e[t]==`string`?e[t]:n.values[t]??``;r.setOutput(t,i)}return r.setOutput(`_agentSummary`,`Multi-input: emitted ${i.length} port(s): ${i.join(`, `)}.`),{ok:!0,value:r.toOutput()}}};const NH=j.object({prefix:j.string().default(``)});var PH=class extends Q{nodeType=`transform`;displayName=`Transform`;category=`Core`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!1},{key:`data`,label:`Data`,order:1,type:`object`,required:!1}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!1},{key:`data`,label:`Data`,order:1,type:`object`,required:!1}];configSchemaDefinition=NH;async validateInputWithConfig(e,t,n){return Object.keys(e).length===0?{ok:!1,error:Z(`DAG_VALIDATION_TRANSFORM_INPUT_REQUIRED`,`Transform node requires at least one input value`,{nodeId:t.nodeDefinition.nodeId})}:{ok:!0,value:void 0}}async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:1e-4}}}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.getInput(`text`);if(typeof i==`string`){let e=`${n.prefix}${i}`;r.setOutput(`text`,e),r.setOutput(`_agentSummary`,`Transformed input. Output length: ${e.length} chars.`)}else{for(let[t,n]of Object.entries(e))r.setOutput(t,n);r.setOutput(`_agentSummary`,`Passed through ${Object.keys(e).length} port(s).`)}return{ok:!0,value:r.toOutput()}}};const FH=`__ROBOTA_TEXT_TEMPLATE_ESCAPED_PERCENT_S__`,IH=j.object({template:j.string().default(`%s`).describe(`Template string. Supports two syntaxes: {{text}} (Handlebars-style) or %s (printf-style). Both replace input text. Use %%s for a literal %s.`)});var LH=class extends Q{nodeType=`text-template`;displayName=`Text Template`;category=`Core`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=IH;async validateInputWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId).requireInputString(`text`);return r.ok?{ok:!0,value:void 0}:r}async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=i.value,o=n.template.split(`%%s`).join(FH).replaceAll(`{{text}}`,a).split(`%s`).join(a).split(FH).join(`%s`);return r.setOutput(`text`,o),r.setOutput(`_agentSummary`,`Template rendered. Output length: ${o.length} chars.`),{ok:!0,value:r.toOutput()}}};const RH=j.object({});var zH=class extends Q{nodeType=`text-output`;displayName=`Text Output`;category=`Core`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=RH;async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,`text-output`),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,i.value),r.setOutput(`_agentSummary`,`Output: ${i.value.length} chars.`),{ok:!0,value:r.toOutput()}):i}};const BH=j.object({});var VH=class extends Q{nodeType=`image-loader`;displayName=`Image Loader`;category=`Media`;defaultInputPort=`asset`;defaultOutputPort=`image`;inputs=[{key:`asset`,label:`Media Reference`,order:0,type:`object`,required:!0}];outputs=[OV({key:`image`,label:`Image`,order:0,required:!0,preset:DV.IMAGE_COMMON})];configSchemaDefinition=BH;async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputMediaReference(`asset`);return i.ok?(r.setOutput(`image`,i.value.toBinary(`image`,`image/png`)),r.setOutput(`_agentSummary`,`Asset loaded as image binary.`),{ok:!0,value:r.toOutput()}):i}};const HH=CV().extend({mimeType:j.string().optional()});var UH=class extends Q{nodeType=`image-source`;displayName=`Image Source`;category=`Test`;defaultOutputPort=`image`;inputs=[];outputs=[OV({key:`image`,label:`Image`,order:0,required:!0,description:`Test image output`,preset:DV.IMAGE_COMMON})];configSchemaDefinition=HH;async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=uV.fromAssetReference(n.asset),i=typeof n.mimeType==`string`?n.mimeType:r.mediaType(),a=typeof i==`string`&&i.trim().length>0?i:`image/png`;return{ok:!0,value:{image:r.toBinary(`image`,a),_agentSummary:`Image source resolved. Type: ${a}.`}}}};function WH(e){let t=e.image;return typeof t!=`object`||!t||!(`kind`in t)||!(`mimeType`in t)||!(`uri`in t)?!1:t.kind===`image`&&typeof t.mimeType==`string`&&typeof t.uri==`string`}const GH=j.object({});var KH=class extends Q{nodeType=`ok-emitter`;displayName=`OK Emitter`;category=`Test`;defaultInputPort=`image`;inputs=[OV({key:`image`,label:`Image Input`,order:0,required:!0,description:`Binary image from upstream`,preset:DV.IMAGE_COMMON})];outputs=[{key:`status`,label:`Status`,order:0,type:`string`,required:!0,description:`Execution status`}];configSchemaDefinition=GH;async validateInputWithConfig(e,t,n){return WH(e)?{ok:!0,value:void 0}:{ok:!1,error:Z(`DAG_VALIDATION_OK_EMITTER_IMAGE_REQUIRED`,`OK emitter node requires an image binary input`,{nodeId:t.nodeDefinition.nodeId})}}async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,`ok-emitter`),i=r.requireInput(`image`);return i.ok?WH({image:i.value})?(r.setOutput(`status`,`ok`),r.setOutput(`_agentSummary`,`Image validated. Status: ok.`),{ok:!0,value:r.toOutput()}):{ok:!1,error:YB(`DAG_TASK_EXECUTION_OK_EMITTER_IMAGE_INVALID`,`OK emitter execution requires image binary input`,!1)}:i}};const qH={read:e=>hc(e),write:e=>Sc(e),edit:e=>Tc(e),shell:e=>oc(e),bash:e=>sc(e),glob:()=>Oc,grep:()=>Fc,"web-fetch":()=>Hc,"web-search":()=>Gc},JH=Object.freeze(Object.keys(qH)),YH=j.object({toolName:j.string().min(1),params:j.record(j.unknown()).default({}),cwd:j.string().optional(),baseCredits:j.number().nonnegative().default(0)}),XH=[{key:`params`,label:`Tool Parameters (JSON string)`,order:0,type:`string`,required:!1}],ZH=[{key:`output`,label:`Output`,order:0,type:`string`,required:!0},{key:`isError`,label:`Is Error`,order:1,type:`boolean`,required:!0}];function QH(e){let t=typeof e==`string`?e:JSON.stringify(e??``);try{let e=JSON.parse(t);if(typeof e==`object`&&e&&typeof e.success==`boolean`){let t=e.success?e.output:e.error??e.output;return{output:typeof t==`string`?t:String(t??``),isError:!e.success}}}catch{}return{output:t,isError:!1}}function $H(e,t,n){return Z(`DAG_VALIDATION_TOOL_INVALID_PARAMS`,t,{toolName:e},{action:`set_input`,suggestion:n})}function eU(e,t){if(typeof e==`string`&&e.trim()!==``){let n;try{n=JSON.parse(e)}catch{return{ok:!1,error:$H(t,"The `params` input port must be a JSON object string.",`Provide a valid JSON object as the params input`)}}return typeof n!=`object`||!n||Array.isArray(n)?{ok:!1,error:$H(t,"The `params` input port must decode to a JSON object.",`Provide a JSON object (not an array or primitive)`)}:{ok:!0,value:n}}return typeof e==`object`&&e&&!Array.isArray(e)?{ok:!0,value:e}:{ok:!0,value:{}}}async function tU(e,t,n,r){try{let{output:i,isError:a}=QH((await e.execute(t)).data),o=new $({},r);return o.setOutput(`output`,i),o.setOutput(`isError`,a),o.setOutput(`_agentSummary`,`Tool "${n}" ran. ${a?`Reported an error.`:`Output: ${i.length} chars.`}`),{ok:!0,value:o.toOutput()}}catch(e){return{ok:!1,error:YB(`DAG_TASK_EXECUTION_TOOL_CALL_FAILED`,`Tool "${n}" failed: ${e instanceof Error?e.message:String(e)}`,!0,{toolName:n})}}}var nU=class extends Q{nodeType=`tool`;displayName=`Tool`;category=`Integration`;inputs=XH;outputs=ZH;configSchemaDefinition=YH;defaultInputPort=`params`;defaultOutputPort=`output`;constructor(){super()}async estimateCostWithConfig(e,t,n){return{ok:!0,value:{estimatedCredits:n.baseCredits}}}async executeWithConfig(e,t,n){let r=qH[n.toolName];if(!r)return{ok:!1,error:Z(`DAG_VALIDATION_TOOL_UNKNOWN_TOOL`,`Unknown toolName "${n.toolName}". Choose one of the supported in-process builtins.`,{toolName:n.toolName},{action:`set_config`,suggestion:`Set toolName to a supported builtin`,options:[...JH]})};let i=eU(new $(e,t.nodeDefinition.nodeId).getInput(`params`),n.toolName);if(!i.ok)return i;let a={...n.params,...i.value};return tU(r(n.cwd===void 0?{}:{cwd:n.cwd}),a,n.toolName,t.nodeDefinition.nodeId)}};const rU={ok:!0,value:{estimatedCredits:0}},iU=j.object({});var aU=class extends Q{nodeType=`string-to-number`;displayName=`String → Number`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`number`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`number`,label:`Number`,order:0,type:`string`,required:!0}];configSchemaDefinition=iU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=Number(i.value);return isNaN(a)?{ok:!1,error:Z(`DAG_VALIDATION_STRING_TO_NUMBER_INVALID`,`Cannot convert "${i.value}" to a number`,{nodeId:t.nodeDefinition.nodeId})}:(r.setOutput(`number`,String(a)),{ok:!0,value:r.toOutput()})}},oU=class extends Q{nodeType=`number-to-string`;displayName=`Number → String`;category=`Utility`;defaultInputPort=`number`;defaultOutputPort=`text`;inputs=[{key:`number`,label:`Number`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=iU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`number`);return i.ok?(r.setOutput(`text`,i.value),{ok:!0,value:r.toOutput()}):i}};const sU=j.object({separator:j.string().default(`, `)});var cU=class extends Q{nodeType=`text-join`;displayName=`Text Join`;category=`Utility`;defaultInputPort=`items`;defaultOutputPort=`text`;inputs=[{key:`items`,label:`Items (newline-separated)`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=sU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`items`);if(!i.ok)return i;let a=i.value.split(`
391
+ `).filter(e=>e.trim()!==``);return r.setOutput(`text`,a.join(n.separator)),{ok:!0,value:r.toOutput()}}};const lU=j.object({separator:j.string().default(`
392
+ `),trim:j.boolean().default(!0)});var uU=class extends Q{nodeType=`text-split`;displayName=`Text Split`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`items`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`items`,label:`Items (newline-separated)`,order:0,type:`string`,required:!0}];configSchemaDefinition=lU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=i.value.split(n.separator),o=n.trim?a.map(e=>e.trim()).filter(e=>e!==``):a;return r.setOutput(`items`,o.join(`
393
+ `)),{ok:!0,value:r.toOutput()}}};const dU=j.object({search:j.string().default(``),replacement:j.string().default(``),useRegex:j.boolean().default(!1),flags:j.string().default(`g`)});var fU=class extends Q{nodeType=`text-replace`;displayName=`Text Replace`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=dU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a;if(n.useRegex)try{let e=new RegExp(n.search,n.flags);a=i.value.replace(e,n.replacement)}catch{return{ok:!1,error:Z(`DAG_VALIDATION_TEXT_REPLACE_INVALID_REGEX`,`Invalid regex: "${n.search}"`,{nodeId:t.nodeDefinition.nodeId})}}else a=i.value.split(n.search).join(n.replacement);return r.setOutput(`text`,a),{ok:!0,value:r.toOutput()}}},pU=class extends Q{nodeType=`text-length`;displayName=`Text Length`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Length`,order:0,type:`string`,required:!0}];configSchemaDefinition=iU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t){let n=new $(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);return r.ok?(n.setOutput(`text`,String(r.value.length)),{ok:!0,value:n.toOutput()}):r}},mU=class extends Q{nodeType=`text-upper`;displayName=`Text Uppercase`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=iU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t){let n=new $(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);return r.ok?(n.setOutput(`text`,r.value.toUpperCase()),{ok:!0,value:n.toOutput()}):r}},hU=class extends Q{nodeType=`text-lower`;displayName=`Text Lowercase`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=iU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t){let n=new $(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);return r.ok?(n.setOutput(`text`,r.value.toLowerCase()),{ok:!0,value:n.toOutput()}):r}};const gU=j.object({mode:j.enum([`both`,`start`,`end`]).default(`both`)});var _U=class extends Q{nodeType=`text-trim`;displayName=`Text Trim`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=gU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=n.mode===`start`?i.value.trimStart():n.mode===`end`?i.value.trimEnd():i.value.trim();return r.setOutput(`text`,a),{ok:!0,value:r.toOutput()}}};const vU=j.object({path:j.string().default(``),fallback:j.string().default(``)});var yU=class extends Q{nodeType=`json-extract`;displayName=`JSON Extract`;category=`Utility`;defaultInputPort=`json`;defaultOutputPort=`text`;inputs=[{key:`json`,label:`JSON`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Value`,order:0,type:`string`,required:!0}];configSchemaDefinition=vU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`json`);if(!i.ok)return i;let a;try{a=JSON.parse(i.value)}catch{return{ok:!1,error:Z(`DAG_VALIDATION_JSON_EXTRACT_INVALID_JSON`,`Input is not valid JSON`,{nodeId:t.nodeDefinition.nodeId})}}let o=n.path?n.path.split(`.`):[],s=a;for(let e of o){if(typeof s!=`object`||!s){s=void 0;break}s=s[e]}let c=s===void 0?n.fallback:String(s);return r.setOutput(`text`,c),{ok:!0,value:r.toOutput()}}};const bU=j.object({operator:j.enum([`non-empty`,`equals`,`contains`,`starts-with`,`ends-with`]).default(`non-empty`),operand:j.string().default(``)});var xU=class extends Q{nodeType=`conditional-text`;displayName=`Conditional Text`;category=`Utility`;defaultInputPort=`condition`;defaultOutputPort=`text`;inputs=[{key:`condition`,label:`Condition`,order:0,type:`string`,required:!0},{key:`text_true`,label:`If True`,order:1,type:`string`,required:!0},{key:`text_false`,label:`If False`,order:2,type:`string`,required:!1}];outputs=[{key:`text`,label:`Result`,order:0,type:`string`,required:!0}];configSchemaDefinition=bU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`condition`);if(!i.ok)return i;let a=r.requireInputString(`text_true`);if(!a.ok)return a;let o=r.getInput(`text_false`),s=i.value,c=n.operand,l;switch(n.operator){case`non-empty`:l=s.trim().length>0;break;case`equals`:l=s===c;break;case`contains`:l=s.includes(c);break;case`starts-with`:l=s.startsWith(c);break;case`ends-with`:l=s.endsWith(c);break}let u=l?a.value:typeof o==`string`?o:``;return r.setOutput(`text`,u),{ok:!0,value:r.toOutput()}}};const SU=j.object({skipEmpty:j.boolean().default(!1)});var CU=class extends Q{nodeType=`text-count-lines`;displayName=`Text Count Lines`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Line Count`,order:0,type:`string`,required:!0}];configSchemaDefinition=SU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=i.value.split(`
394
+ `),o=n.skipEmpty?a.filter(e=>e.trim()!==``).length:a.length;return r.setOutput(`text`,String(o)),{ok:!0,value:r.toOutput()}}};const wU=j.object({times:j.number().int().min(0).default(2),separator:j.string().default(``)});var TU=class extends Q{nodeType=`text-repeat`;displayName=`Text Repeat`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Repeated Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=wU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=Array.from({length:n.times},()=>i.value);return r.setOutput(`text`,a.join(n.separator)),{ok:!0,value:r.toOutput()}}};const EU=j.object({start:j.number().int().default(0),end:j.number().int().optional()});var DU=class extends Q{nodeType=`text-slice`;displayName=`Text Slice`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Sliced Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=EU;async estimateCostWithConfig(){return rU}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,i.value.slice(n.start,n.end)),{ok:!0,value:r.toOutput()}):i}};function OU(e,t){let n=new kV;return{runOrchestrator:new PV(e.storage,e.queue,e.clock,n),runQuery:new FV(e.storage),runCancel:new IV(e.storage,e.clock),workerLoop:hH({storage:e.storage,queue:e.queue,deadLetterQueue:e.deadLetterQueue,lease:e.lease,executor:e.executor,clock:e.clock,runProgressEventReporter:n},{...t.worker,retryEnabled:t.worker.retryEnabled??!1}),runProgressEventBus:n}}function kU(){return[new AH,new MH,new PH,new LH,new zH,new VH,new UH,new KH,new nU,new aU,new oU,new cU,new uU,new fU,new pU,new mU,new hU,new _U,new yU,new xU,new CU,new TU,new DU]}const AU=new Set([`success`,`failed`,`cancelled`]);function jU(e){return AU.has(e)}function MU(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{return{}}return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}function NU(e){let t={};for(let n of e){let e=MU(n.outputSnapshot);for(let[r,i]of Object.entries(e))t[`${n.nodeId}.${r}`]=i}return t}function PU(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.status!==`success`)continue;let r=MU(n.outputSnapshot);for(let e of Object.values(r))if(typeof e==`string`)return e}}function FU(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n&&n.status===`failed`&&n.errorMessage)return`${n.nodeId}: ${n.errorMessage}`}}const IU=1e4;function LU(e){return new Promise(t=>{setTimeout(t,e)})}var RU=class{options;providerId=`local`;displayName=`Local (in-process)`;constructor(e={}){this.options=e}async listNodes(){return this.buildNodeRegistry().map(BU)}async execute(e,t,n){let r=this.buildNodeRegistry(),i=EH(e,void 0),a=Date.now(),o=!1,s=()=>{o=!0};n?.signal?.addEventListener(`abort`,s);try{let e=await zU(i,r,t,n?.onProgress,()=>o),s=Date.now()-a,c=NU(e.taskRuns),l=e.dagRun.status===`success`,u=l?void 0:FU(e.taskRuns);return n?.onProgress?.({type:`dag_complete`,nodeId:``,durationMs:s,finalOutput:l?PU(e.taskRuns):void 0,error:l?void 0:u??`DAG run did not succeed`}),{ok:l,outputs:c,durationMs:s,...l?{}:{error:u??`DAG run did not succeed`}}}catch(e){let t=Date.now()-a,r=e instanceof Error?e.message:String(e);return n?.onProgress?.({type:`dag_complete`,nodeId:``,durationMs:t,error:r}),{ok:!1,outputs:{},durationMs:t,error:r}}finally{n?.signal?.removeEventListener(`abort`,s)}}buildNodeRegistry(){let e=this.options.nodeRegistry??kU(),t=this.options.instantNodes??[],n=this.options.extraNodes??[],r=new Set([...t.map(e=>e.nodeType),...n.map(e=>e.nodeType)]);return[...e.filter(e=>!r.has(e.nodeType)),...n,...t]}};async function zU(e,t,n,r,i){let a=EV(t);if(!a.ok)throw Error(`Node definition assembly failed: ${a.error.code}`);let o=a.value,s=new tV(new vV(o.manifests),new _V(new gV(o.handlersByType))),c=new iV,l=OU({storage:c,queue:new aV,deadLetterQueue:new aV,lease:new oV,executor:s,clock:new sV},{worker:{workerId:`local-dag-runtime-provider`,leaseDurationMs:6e4,visibilityTimeoutMs:6e4,maxAttempts:1,defaultTimeoutMs:3e5,retryEnabled:!1}}),u=new Map(e.nodes.map(e=>[e.nodeId,e.nodeType])),d=new Map,f=l.runProgressEventBus.subscribe(e=>{if(r){if(e.eventType===`task.started`)d.set(e.nodeId,Date.now()),r({type:`node_start`,nodeId:e.nodeId,nodeType:u.get(e.nodeId)});else if(e.eventType===`task.completed`){let t=d.get(e.nodeId);r({type:`node_complete`,nodeId:e.nodeId,nodeType:u.get(e.nodeId),durationMs:t===void 0?void 0:Date.now()-t})}else if(e.eventType===`task.failed`){let t=d.get(e.nodeId);r({type:`node_error`,nodeId:e.nodeId,nodeType:u.get(e.nodeId),durationMs:t===void 0?void 0:Date.now()-t,error:e.error.message??e.error.code})}}});try{let t={...e,status:`published`};await c.saveDefinition(t);let r=await l.runOrchestrator.startRun({dagId:e.dagId,version:e.version,trigger:`manual`,input:n});if(!r.ok)throw Error(`startRun failed: ${r.error.code}`);let{dagRunId:a}=r.value;for(let e=0;e<IU;e++){i()&&await l.runCancel.cancelRun(a);let e=await l.workerLoop.processOnce();if(!e.ok)throw Error(`Worker step failed: ${e.error.code}`);let t=await l.runQuery.getRun(a);if(!t.ok)throw Error(`Run query failed: ${t.error.code}`);let{dagRun:n,taskRuns:r}=t.value;if(jU(n.status))return{dagRun:n,taskRuns:r};e.value.processed||await LU(10)}throw Error(`Run ${a} did not reach terminal state after ${IU} iterations`)}finally{f()}}function BU(e){let t={},n={};for(let r of e.inputs??[]){let e=HU(r.type),i={},a=r;a.default!==void 0&&(i.default=a.default);let o=Object.keys(i).length>0?[e,i]:[e];r.required===!1?n[r.key]=o:t[r.key]=o}let r=e.outputs??[],i={nodeType:e.nodeType,input:{required:t},output:r.map(e=>HU(e.type)),output_name:r.map(e=>e.key),category:e.category??`robota`,source:`local`};return Object.keys(n).length>0&&(i.input.optional=n),i}const VU={string:`STRING`,object:`JSON`,binary:`IMAGE`,number:`FLOAT`,boolean:`BOOLEAN`,integer:`INT`};function HU(e){return VU[e]??e.toUpperCase()}function UU(e){let t=e.meta;if(typeof t!=`object`||!t||Array.isArray(t))return{};let n=t;return{description:typeof n.description==`string`?n.description:void 0,displayName:typeof n.displayName==`string`?n.displayName:void 0,tags:Array.isArray(n.tags)?n.tags.filter(e=>typeof e==`string`):void 0}}function WU(e){return Array.isArray(e.nodes)||typeof e.dagId==`string`}async function GU(e,t=nV){let n;try{n=await de(e)}catch{return[]}let r=t.workflowExt,i=[];for(let t of n){if(t.endsWith(`.node.json`)||!t.endsWith(r))continue;let n=h(e,t),a;try{let e=JSON.parse(await ue(n,`utf8`));if(typeof e!=`object`||!e||Array.isArray(e))continue;a=e}catch{continue}WU(a)&&i.push({id:t.slice(0,-r.length),filePath:n,definition:a,meta:UU(a)})}return i.sort((e,t)=>e.id.localeCompare(t.id))}var KU=class extends qT{name=`google`;constructor(e){super(e)}};const qU=[`anthropic`,`openai`,`gemini`,`deepseek`,`qwen`];function JU(e){return typeof e==`string`&&qU.includes(e)}const YU=j.object({model:j.string().optional()}),XU={anthropic:{model:`claude-sonnet-4-6`,envVar:`ANTHROPIC_API_KEY`},openai:{model:`gpt-4o-mini`,envVar:`OPENAI_API_KEY`},gemini:{model:`gemini-2.0-flash`,envVar:`GEMINI_API_KEY`},deepseek:{model:`deepseek-chat`,envVar:`DEEPSEEK_API_KEY`},qwen:{model:`qwen-turbo`,envVar:`DASHSCOPE_API_KEY`}};function ZU(e,t){return Object.entries(t).reduce((e,[t,n])=>e.replaceAll(`{{${t}}}`,n),e)}function QU(e,t){let n=XU[e],r=process.env[n.envVar];if(typeof r!=`string`||r.trim().length===0){let t=Object.entries(XU).filter(([t])=>t!==e&&process.env[XU[t].envVar]).map(([e])=>e);return{error:Z(`DAG_VALIDATION_INSTANT_NODE_API_KEY_REQUIRED`,`${n.envVar} is required for instant node provider "${e}" but is not set`,{provider:e,envVar:n.envVar},{action:`add_api_key`,suggestion:`Set ${n.envVar} in your environment or .env file`,options:t.length>0?t.map(e=>`Use provider "${e}" instead (API key already set)`):[`Set ${n.envVar}=<your-api-key> in your environment`]})}}let i=`InstantNode_${e}`,a;switch(e){case`anthropic`:a=new Ta({name:i,aiProviders:[new wS({apiKey:r.trim()})],defaultModel:{provider:`anthropic`,model:t}});break;case`openai`:a=new Ta({name:i,aiProviders:[new _w({apiKey:r.trim()})],defaultModel:{provider:`openai`,model:t}});break;case`gemini`:a=new Ta({name:i,aiProviders:[new KU({apiKey:r.trim()})],defaultModel:{provider:`google`,model:t}});break;case`deepseek`:a=new Ta({name:i,aiProviders:[new zw({apiKey:r.trim()})],defaultModel:{provider:`deepseek`,model:t}});break;case`qwen`:a=new Ta({name:i,aiProviders:[new dO({apiKey:r.trim()})],defaultModel:{provider:`qwen`,model:t}});break}return{agent:a}}var $U=class extends Q{nodeType;displayName;category=`Instant`;inputs;outputs;defaultInputPort;defaultOutputPort;configSchemaDefinition=YU;spec;constructor(e){super(),this.spec=e,this.nodeType=e.nodeType,this.displayName=e.displayName,this.inputs=e.inputPorts.map((e,t)=>({key:e.key,label:e.key,order:t,type:`string`,required:!0,description:e.description})),this.outputs=[{key:e.outputPort.key,label:e.outputPort.key,order:0,type:`string`,required:!0,description:e.outputPort.description}],this.defaultInputPort=e.inputPorts[0]?.key,this.defaultOutputPort=e.outputPort.key}toPersisted(){return{kind:`prompt`,nodeType:this.spec.nodeType,displayName:this.spec.displayName,systemPromptTemplate:this.spec.systemPromptTemplate,inputPorts:this.spec.inputPorts,outputPort:this.spec.outputPort,...this.spec.provider===void 0?{}:{provider:this.spec.provider},...this.spec.model===void 0?{}:{model:this.spec.model}}}async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i={};for(let e of this.spec.inputPorts){let t=r.requireInputString(e.key);if(!t.ok)return t;i[e.key]=t.value}let a=this.spec.provider??`anthropic`,o=XU[a],s=n.model??this.spec.model??o.model,c=QU(a,s);if(`error`in c)return{ok:!1,error:c.error};let l=ZU(this.spec.systemPromptTemplate,i);try{let e=await c.agent.run(l);r.setOutput(this.spec.outputPort.key,e);let t=typeof e==`string`?e.split(` `).length:0;return r.setOutput(`_agentSummary`,`Generated ${t} words. Model: ${s}.`),{ok:!0,value:r.toOutput()}}catch(e){return{ok:!1,error:YB(`DAG_TASK_EXECUTION_LLM_GENERATION_FAILED`,e instanceof Error?e.message:`LLM generation failed`,!0,{provider:a,model:s,nodeType:this.nodeType})}}}};function eW(e){return new $U(e)}var tW=class extends Q{nodeType;displayName;category=`Instant`;inputs;outputs;defaultInputPort;defaultOutputPort;configSchemaDefinition=YU;spec;constructor(e){if(super(),(e.maxDepth??0)>=3)throw Error(`Composite node nesting limit (3) exceeded for "${e.nodeType}"`);this.spec=e,this.nodeType=e.nodeType,this.displayName=e.displayName,this.inputs=[{key:e.exposedInputPort.key,label:e.exposedInputPort.key,order:0,type:`string`,required:!0,description:e.exposedInputPort.description}],this.outputs=e.exposedOutputPorts.map((e,t)=>({key:e.key,label:e.key,order:t,type:`string`,required:!0,description:e.description})),this.defaultInputPort=e.exposedInputPort.key,this.defaultOutputPort=e.exposedOutputPorts[0]?.key??`output`}toPersisted(){return{kind:`composite`,nodeType:this.spec.nodeType,displayName:this.spec.displayName,innerDag:this.spec.innerDag,exposedInputPort:this.spec.exposedInputPort,exposedOutputPorts:this.spec.exposedOutputPorts,...this.spec.maxDepth===void 0?{}:{maxDepth:this.spec.maxDepth}}}async estimateCostWithConfig(){return{ok:!0,value:{estimatedCredits:0}}}async executeWithConfig(e,t,n){let r=new $(e,t.nodeDefinition.nodeId),i=r.requireInputString(this.spec.exposedInputPort.key);if(!i.ok)return i;let a={[this.spec.exposedInputPort.mapsTo.nodeId]:{[this.spec.exposedInputPort.mapsTo.portKey]:i.value}};try{let e=await this.spec.runner.run(this.spec.innerDag,a);if(!e.ok)return{ok:!1,error:YB(`DAG_TASK_EXECUTION_COMPOSITE_FAILED`,e.error??`Composite sub-DAG execution failed`,!0,{nodeType:this.nodeType})};for(let t of this.spec.exposedOutputPorts){let n=e.outputs[t.mapsTo.nodeId]?.[t.mapsTo.portKey];n!==void 0&&r.setOutput(t.key,n)}return r.setOutput(`_agentSummary`,`Composite sub-DAG completed: ${this.spec.innerDag.nodes.length} nodes.`),{ok:!0,value:r.toOutput()}}catch(e){return{ok:!1,error:YB(`DAG_TASK_EXECUTION_COMPOSITE_FAILED`,e instanceof Error?e.message:`Composite sub-DAG execution failed`,!0,{nodeType:this.nodeType})}}}};function nW(e){return new tW(e)}function rW(e){return typeof e==`object`&&!!e&&typeof e.toPersisted==`function`}function iW(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function aW(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){let e=iW(n);if(!e||typeof e.key!=`string`)return null;t.push(typeof e.description==`string`?{key:e.key,description:e.description}:{key:e.key})}return t.length>0?t:null}function oW(e){let t=iW(e);if(!t||typeof t.nodeType!=`string`)return null;let n=t.nodeType,r=typeof t.displayName==`string`?t.displayName:n;if(t.kind===`composite`){let e=iW(t.innerDag),i=iW(t.exposedInputPort);return!e||!i||typeof i.key!=`string`||!Array.isArray(t.exposedOutputPorts)||t.exposedOutputPorts.length===0?null:{kind:`composite`,nodeType:n,displayName:r,innerDag:e,exposedInputPort:i,exposedOutputPorts:t.exposedOutputPorts,...typeof t.maxDepth==`number`?{maxDepth:t.maxDepth}:{}}}if(typeof t.systemPromptTemplate!=`string`)return null;let i=aW(t.inputPorts),a=iW(t.outputPort);return!i||!a||typeof a.key!=`string`?null:{kind:`prompt`,nodeType:n,displayName:r,systemPromptTemplate:t.systemPromptTemplate,inputPorts:i,outputPort:typeof a.description==`string`?{key:a.key,description:a.description}:{key:a.key},...JU(t.provider)?{provider:t.provider}:{},...typeof t.model==`string`?{model:t.model}:{}}}function sW(e,t={}){if(e.kind===`composite`){if(!t.compositeRunner)throw Error(`rehydrateInstantNode: composite node "${e.nodeType}" requires a compositeRunner (its runner is not serialized).`);return nW({nodeType:e.nodeType,displayName:e.displayName,innerDag:e.innerDag,exposedInputPort:e.exposedInputPort,exposedOutputPorts:e.exposedOutputPorts,runner:t.compositeRunner,...e.maxDepth===void 0?{}:{maxDepth:e.maxDepth}})}return eW({nodeType:e.nodeType,displayName:e.displayName,systemPromptTemplate:e.systemPromptTemplate,inputPorts:e.inputPorts,outputPort:e.outputPort,...e.provider===void 0?{}:{provider:e.provider},...e.model===void 0?{}:{model:e.model}})}async function cW(e,t=nV){let n=t.root,r=t.workflowExt,i=await GU(v(e,n),t);if(i.length===0)return{success:!0,message:`No workflow files (*${r}) in ${n}.`};let a=i.map(e=>{let t=e.definition,n=t.nodes?.length??0,i=t.edges?.length??t.links?.length??0;return` ${e.id}${r} — ${n} node(s), ${i} link(s)`});return{success:!0,message:`Workflows in ${n} (${i.length}):\n${a.join(`
395
+ `)}`}}async function lW(){let e=await new RU().listNodes(),t=[...e].sort((e,t)=>e.nodeType.localeCompare(t.nodeType)).map(e=>` ${e.nodeType}${e.description?` — ${e.description}`:``}`);return{success:!0,message:`Available workflow nodes (${e.length}):\n${t.join(`
396
+ `)}`}}async function uW(e,t=nV){let n=v(e,h(t.root,`nodes`)),r;try{r=await de(n)}catch{return[]}let i=[];for(let e of r.filter(e=>e.endsWith(`.node.json`))){let t;try{t=oW(JSON.parse(await ue(h(n,e),`utf-8`)))}catch{continue}if(t){if(t.kind===`composite`){process.stderr.write(`[instant-node-loader] skipping composite node "${t.nodeType}" — composite reload is not supported in this workspace\n`);continue}i.push(sW(t))}}return i}async function dW(e){let t=await ue(e,`utf-8`),n=JSON.parse(t);return OH(n)?TH(n).workflowFile:n}async function fW(e,t,n=nV){if(!e)return{success:!1,message:`Usage: /workflows run <file.json>`};let r=await dW(v(t,e)).catch(t=>{let n=t instanceof Error?t.message:String(t);return Error(`Failed to read DAG file "${e}": ${n}`)});if(r instanceof Error)return{success:!1,message:r.message};let i=await uW(t,n),a=await new RU({workspace:n,projectDir:t,...i.length>0?{instantNodes:i}:{}}).execute(r,{});return a.ok?{success:!0,message:`Workflow completed in ${a.durationMs}ms.\nOutputs: ${JSON.stringify(a.outputs,null,2)}`}:{success:!1,message:`Workflow failed (${a.durationMs}ms): ${a.error??`unknown error`}`}}async function pW(e,t){if(!e)return{success:!1,message:`Usage: /workflows validate <file.dag.json>`};let n=await ue(v(t,e),`utf-8`).then(e=>JSON.parse(e)).catch(t=>{let n=t instanceof Error?t.message:String(t);return Error(`Failed to read DAG file "${e}": ${n}`)});if(n instanceof Error)return{success:!1,message:n.message};let r;if(DH(n))r=EH(n);else if(OH(n))r=n;else return{success:!1,message:`"${e}" is not a recognized DAG workflow file (expected a .dag.json node-graph or a DAG definition).`};let i=await new RU().listNodes(),a=new Set(i.map(e=>e.nodeType)),o=new Set(r.nodes.map(e=>e.nodeId)),s=[];r.nodes.length===0&&s.push(`workflow has no nodes`);for(let e of r.nodes)a.has(e.nodeType)||s.push(`node "${e.nodeId}": unknown node type "${e.nodeType}"`);for(let e of r.edges)o.has(e.from)||s.push(`edge references unknown source node "${e.from}"`),o.has(e.to)||s.push(`edge references unknown target node "${e.to}"`);if(s.length>0){let t=s.length===1?``:`s`;return{success:!1,message:`Invalid workflow "${e}" (${s.length} issue${t}):\n${s.map(e=>` - ${e}`).join(`
397
+ `)}`}}return{success:!0,message:`Valid workflow "${e}": ${r.nodes.length} node(s), ${r.edges.length} edge(s).`}}function mW(e){let t=EV(e);return t.ok?{ok:!0,manifests:t.value.manifests}:{ok:!1,error:`failed to build node registry: ${t.error.message}`}}function hW(e){return e.length===0?`—`:e.map(e=>e.key).join(`, `)}function gW(e){return[...e].sort((e,t)=>e.nodeType.localeCompare(t.nodeType)).map(e=>{let t=e.defaultInputPort??hW(e.inputs),n=e.defaultOutputPort??hW(e.outputs);return`- ${e.nodeType} (in: ${t}; out: ${n})`}).join(`
398
+ `)}function _W(e){return[`You are a workflow author. Given a natural-language request, design a linear DAG workflow and`,`return ONLY a JSON object (no prose, no code fences) matching this shape:`,`{`,` "name": "kebab-or-snake identifier (letters, digits, - and _ only)",`,` "description": "one short line",`,` "pipeline": [ { "nodeType": "<type>", "config": { ... optional } }, ... ],`,` "newNodes": [ { "nodeType", "displayName", "systemPromptTemplate", "inputPorts":[{"key"}], "outputPort":{"key"} } ],`,` "sampleInput": { "text": "an example input to run with" }`,`}`,``,`Rules:`,`- The pipeline is executed left-to-right; adjacent nodes are auto-wired by their default ports.`,`- Start from an "input" node and end with a "text-output" node unless the request says otherwise.`,`- Prefer the existing nodes below. Only define a "newNodes" prompt-backed node when NO existing`,` node fits; reference it by its nodeType in the pipeline. Omit "newNodes" entirely if unused.`,`- "systemPromptTemplate" may reference an input port with {{key}}.`,``,`Available nodes:`,e].join(`
399
+ `)}async function vW(e,t,n,r){let i;try{i=await e.chat([q(_W(n)),ai(t)],{maxTokens:2048,responseFormat:{type:`json_object`},...r?{model:r}:{}})}catch(e){return{ok:!1,error:`provider call failed: ${e instanceof Error?e.message:String(e)}`}}let a=typeof i.content==`string`?i.content.trim():``;return a===``?{ok:!1,error:`provider returned an empty response`}:{ok:!0,raw:a}}const yW=/^[a-zA-Z0-9_-]+$/;function bW(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function xW(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){let e=bW(n);if(!e||typeof e.key!=`string`)return null;t.push(typeof e.description==`string`?{key:e.key,description:e.description}:{key:e.key})}return t}function SW(e){let t=bW(e);if(!t)return{error:`newNodes entry is not an object`};if(typeof t.nodeType!=`string`||!yW.test(t.nodeType))return{error:`newNodes entry has an invalid nodeType: ${JSON.stringify(t.nodeType)}`};if(typeof t.systemPromptTemplate!=`string`||t.systemPromptTemplate.trim()===``)return{error:`newNodes "${t.nodeType}" is missing systemPromptTemplate`};let n=xW(t.inputPorts);if(!n||n.length===0)return{error:`newNodes "${t.nodeType}" has no valid inputPorts`};let r=bW(t.outputPort);return!r||typeof r.key!=`string`?{error:`newNodes "${t.nodeType}" has no valid outputPort`}:{nodeType:t.nodeType,...typeof t.displayName==`string`?{displayName:t.displayName}:{},systemPromptTemplate:t.systemPromptTemplate,inputPorts:n,outputPort:typeof r.description==`string`?{key:r.key,description:r.description}:{key:r.key},...typeof t.provider==`string`?{provider:t.provider}:{},...typeof t.model==`string`?{model:t.model}:{}}}function CW(e){let t=bW(e);if(!t)return;let n={};for(let[e,r]of Object.entries(t))typeof r==`string`&&(n[e]=r);return Object.keys(n).length>0?n:void 0}function wW(e){let t=e.trim();return t.startsWith("```")?t.replace(/^```[a-zA-Z0-9]*\s*\n?/,``).replace(/\n?```\s*$/,``).trim():t}function TW(e){let t;try{t=JSON.parse(wW(e))}catch(e){return{ok:!1,error:`provider did not return valid JSON: ${e instanceof Error?e.message:String(e)}`}}let n=bW(t);if(!n)return{ok:!1,error:`authoring spec is not a JSON object`};if(typeof n.name!=`string`||!yW.test(n.name))return{ok:!1,error:`authoring spec "name" must match ${yW.source}; got ${JSON.stringify(n.name)}`};let r=n.name;if(!Array.isArray(n.pipeline)||n.pipeline.length===0)return{ok:!1,error:`authoring spec "pipeline" must be a non-empty array`};let i=[];for(let e of n.pipeline){let t=bW(e);if(!t||typeof t.nodeType!=`string`)return{ok:!1,error:`each pipeline stage must be an object with a string nodeType`};let n=bW(t.config);i.push(n?{nodeType:t.nodeType,config:n}:{nodeType:t.nodeType})}let a;if(n.newNodes!==void 0){if(!Array.isArray(n.newNodes))return{ok:!1,error:`authoring spec "newNodes" must be an array when present`};a=[];for(let e of n.newNodes){let t=SW(e);if(`error`in t)return{ok:!1,error:t.error};a.push(t)}}let o=CW(n.sampleInput);return{ok:!0,spec:{name:r,...typeof n.description==`string`?{description:n.description}:{},pipeline:i,...a&&a.length>0?{newNodes:a}:{},...o?{sampleInput:o}:{}}}}function EW(e,t){let n=e.pipeline.map(e=>e.config?{nodeType:e.nodeType,config:e.config}:{nodeType:e.nodeType}),r=bH({dagId:e.name,pipeline:n},t);return r.ok?{ok:!0,definition:r.definition}:{ok:!1,error:r.error.message}}async function DW(e,t,n,r,i){let a=new RU({workspace:n,projectDir:t,...r.length>0?{instantNodes:r}:{}}),{workflowFile:o}=TH(e),s=await a.execute(o,i);return{ok:s.ok,outputs:s.outputs,durationMs:s.durationMs,...s.ok?{}:{error:s.error??`unknown error`}}}async function OW(e,t,n,r=nV){let i=v(e,r.root);await le(i,{recursive:!0});let a=h(i,`${t}${r.workflowExt}`);return await ge(a,`${JSON.stringify(n,null,2)}\n`,`utf-8`),a}async function kW(e,t,n,r=nV){if(!rW(t))return null;let i={...t.toPersisted(),createdAt:n};if(i.kind===`composite`)return null;let a=v(e,h(r.root,`nodes`));await le(a,{recursive:!0});let o=h(a,`${t.nodeType}.node.json`);return await ge(o,`${JSON.stringify(i,null,2)}\n`,`utf-8`),o}function AW(e){let t=[],n=``,r=!1,i=null;for(let a of e)i===null?a===`"`||a===`'`?(i=a,r=!0):/\s/.test(a)?r&&=(t.push(n),n=``,!1):(n+=a,r=!0):a===i?i=null:n+=a;return r&&t.push(n),t}function jW(e){let t=AW(e.trim()),n=[],r={},i,a=0;for(;a<t.length&&!t[a].startsWith(`--`);)n.push(t[a]),a+=1;for(;a<t.length;){let e=t[a];if(e===`--input`){let e=t[a+1];if(e===void 0||e.startsWith(`--`))return{ok:!1,error:`--input requires a key=value argument.`};let n=e.indexOf(`=`);if(n<=0)return{ok:!1,error:`--input must be key=value, got "${e}".`};r[e.slice(0,n)]=e.slice(n+1),a+=2}else if(e===`--name`){let e=t[a+1];if(e===void 0||e.startsWith(`--`))return{ok:!1,error:`--name requires a value.`};i=e,a+=2}else return{ok:!1,error:`create received unexpected flag: ${e}`}}let o=n.join(` `).trim();return o===``?{ok:!1,error:`A natural-language description is required.`}:{ok:!0,value:{description:o,...i?{nameOverride:i}:{},inputs:r}}}function MW(e,t){let n=JU(e.provider)?e.provider:t;return eW({nodeType:e.nodeType,displayName:e.displayName??e.nodeType,systemPromptTemplate:e.systemPromptTemplate,inputPorts:e.inputPorts,outputPort:e.outputPort,...n?{provider:n}:{},...e.model?{model:e.model}:{}})}function NW(e){return JSON.stringify(e,null,2)}function PW(e,t){if(Object.keys(t).length===0)return e;let n=!1,r=e.nodes.map(e=>n||e.nodeType!==`input`?e:(n=!0,{...e,config:{...e.config,...t}}));return{...e,nodes:r}}async function FW(e,t,n={}){let r=n.workspace??nV,i=n.now??(()=>new Date().toISOString()),a=jW(e);if(!a.ok)return{success:!1,message:`${a.error}\nUsage: /workflows create "<description>" [--input key=value] [--name <name>]`};let{description:o,nameOverride:s,inputs:c}=a.value,l=n.providerDefinitions??[],u,d=n.model,f;try{if(n.resolveProvider)u=n.resolveProvider(t);else{u=V_(t,void 0,{providerDefinitions:l});let e=B_(t,{providerDefinitions:l});d??=e.model,f=JU(e.name)?e.name:void 0}}catch(e){return{success:!1,message:`No active LLM provider is configured. Configure one (e.g. \`/provider\` or set the provider API key) and retry.\nDetail: ${e instanceof L_||e instanceof Error?e.message:String(e)}`}}let p=await uW(t,r),m=[...kU(),...p],h=mW(m);if(!h.ok)return{success:!1,message:`Failed to build node catalog: ${h.error}`};let g=await vW(u,o,gW(h.manifests),d);if(!g.ok)return{success:!1,message:`Authoring failed: ${g.error}`};let _=TW(g.raw);if(!_.ok)return{success:!1,message:`Authoring produced an invalid spec: ${_.error}`};let v=_.spec,y=s??v.name,b=[],x=new Set(m.map(e=>e.nodeType));for(let e of v.newNodes??[])x.has(e.nodeType)||(b.push(MW(e,f)),x.add(e.nodeType));let S=mW([...m,...b]);if(!S.ok)return{success:!1,message:`Failed to build node catalog: ${S.error}`};let C=S.manifests,w=EW({...v,name:y},C);if(!w.ok)return{success:!1,message:`Could not assemble workflow: ${w.error}`};let T=Object.keys(c).length>0?c:v.sampleInput??{},E=PW(w.definition,T),D=i(),O=[];for(let e of b){let n=await kW(t,e,D,r);n&&O.push(n)}let k=await OW(t,y,E,r),A=await DW(E,t,r,[...p,...b],T),ee=O.length>0?`\nNew nodes: ${O.join(`, `)}`:``;return A.ok?{success:!0,message:`Created and ran "${y}".\nSaved: ${k}${ee}\nCompleted in ${A.durationMs}ms.\nOutputs: ${NW(A.outputs)}\nRe-run: /workflows run ${k}`}:{success:!1,message:`Saved ${k}${ee}\nBut the run failed (${A.durationMs}ms): ${A.error}\nInspect or edit the saved artifact and re-run with: /workflows run ${k}`}}const IW=[{name:`create`,description:`Author a workflow from a natural-language description and run it immediately`,source:`workflows`,argumentHint:`"<description>" [--input key=value] [--name <name>]`,modelInvocable:!0},{name:`list`,description:`List available workflow nodes`,source:`workflows`,modelInvocable:!1},{name:`catalog`,description:`List workflow files in the local .workflows catalog`,source:`workflows`,modelInvocable:!1},{name:`validate`,description:`Validate a workflow file against the node catalog`,source:`workflows`,argumentHint:`<file.json>`,modelInvocable:!1},{name:`run`,description:`Run a workflow file`,source:`workflows`,argumentHint:`<file.json>`,modelInvocable:!1}],LW=[`Usage: /workflows <create|list|catalog|validate|run>`,` create "<desc>" Author a workflow from natural language and run it`,` list List available workflow nodes`,` catalog List workflow files in .workflows`,` validate <file> Validate a workflow file`,` run <file> Run a workflow file`].join(`
400
+ `);function RW(e){let t=e.trim();if(t===``)return{sub:``,rest:``};let n=t.indexOf(` `);return n===-1?{sub:t,rest:``}:{sub:t.slice(0,n),rest:t.slice(n+1).trim()}}async function zW(e,t,n,r){let{sub:i,rest:a}=RW(t),o=e.getCwd();switch(i){case``:return{success:!0,message:LW};case`create`:return FW(a,o,{workspace:n,providerDefinitions:r});case`list`:return lW();case`catalog`:return cW(o,n);case`validate`:return pW(a,o);case`run`:return fW(a,o,n);default:return{success:!1,message:`Unknown subcommand "${i}".\n${LW}`}}}function BW(){return{name:`workflows`,displayName:`Workflows`,description:`Author (from natural language), list, validate, and run DAG workflows on the in-process runtime`,source:`workflows`,argumentHint:`<create|list|catalog|validate|run> [args]`,subcommands:IW,modelInvocable:!0}}function VW(e,t){let n=BW();return{name:n.name,displayName:n.displayName,description:n.description,requiresPermission:!1,userInvocable:!0,modelInvocable:!0,argumentHint:n.argumentHint,subcommands:n.subcommands,lifecycle:`inline`,execute:(n,r)=>zW(n,r,e,t)}}var HW=class{name=`workflows`;getCommands(){return[BW()]}};function UW(e={}){let t=e.workspace??nV,n=e.providerDefinitions??[];return{name:`agent-command-workflows`,commandSources:[new HW],systemCommands:[VW(t,n)]}}function WW(e){return UW({providerDefinitions:e})}function GW(e,t,n,r,i={}){let a={settings:{read:()=>Km(Wm()),write:e=>qm(Wm(),e)},plugin:PP(e)},o=n.providerDefinitions??EO(),s={readMergedSettings:()=>R_(e),readTargetSettings:()=>Km(k_(e)),writeTargetSettings:t=>qm(k_(e),t)},c=WW(o);return{commandHostAdapters:a,providerDefinitions:o,commandModules:[...DP({cwd:e,providerDefinitions:o,providerSettingsAdapter:s,...i.enabledCommandModules===void 0?{}:{enabledCommandModules:i.enabledCommandModules},...i.disabledCommandModules===void 0?{}:{disabledCommandModules:i.disabledCommandModules}}),c,...n.commandModules??[]],startupUpdateNoticePromise:$b(t)?Qb({currentVersion:r}):void 0}}function KW(e,t){let n=A(v(e,t),`utf8`).trim();if(n.length===0)throw Error(`Task file is empty: ${t}`);return`Task file (${t}):\n${n}`}function qW(e,t){let n=[];if(t.appendSystemPrompt&&n.push(t.appendSystemPrompt),t.taskFile)try{n.push(KW(e,t.taskFile))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}return t.jsonSchema&&n.push(`Respond with valid JSON only, matching this JSON schema:\n${t.jsonSchema}`),n.length>0?n.join(`
401
+
402
+ `):void 0}async function JW(e,t,n,r,i,a,o,s,c={},l={}){let u=t.goal?.trim(),d=t.positional.join(` `).trim();if(!u&&!d&&!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);d=Buffer.concat(e).toString(`utf-8`).trim()}!u&&!d&&(process.stderr.write(`Print mode (-p) requires a prompt argument (or --goal <objective>).
403
+ `),process.exit(1));let f=qW(e,t),p=new Tx({cwd:e,provider:n,outputFormat:t.outputFormat??`text`,permissionMode:t.permissionMode??l.permissionMode??`bypassPermissions`,maxTurns:t.maxTurns,sessionStore:t.noSessionPersistence?void 0:r,resumeSessionId:c.resumeSessionId,forkSession:c.forkSession,sessionName:t.sessionName,bare:t.bare||void 0,allowedTools:kx(t.allowedTools),deniedTools:kx(t.deniedTools),appendSystemPrompt:f,...l.persona===void 0?{}:{persona:l.persona},...l.agentName===void 0?{}:{agentName:l.agentName},...l.activePresetId===void 0?{}:{activePresetId:l.activePresetId},...l.enableParallelSubagents===void 0?{}:{enableParallelSubagents:l.enableParallelSubagents},...l.selfVerification===void 0?{}:{selfVerification:l.selfVerification},...t.systemPrompt?{systemPrompt:t.systemPrompt}:{},backgroundTaskRunners:i,subagentRunnerFactory:a,commandModules:o,commandHostAdapters:s});u?await p.runGoal(u,t.goalMaxIterations?{maxIterations:t.goalMaxIterations}:{}):await p.run(d),process.exit(p.getExitCode())}function YW(t){let n;try{n=e(import.meta.url)(`@robota-sdk/agent-provider-replay`)}catch{throw Error(`--session-log replay requires @robota-sdk/agent-provider-replay, a dev-only package that is not bundled in the published CLI.`)}return n.createReplayProviderFromLogFile(t)}function XW(){let e=new GR(Wm());return e.register(new pz),e}async function ZW(e={}){if(process.argv[2]===`session`&&process.argv[3]===`analyze`){await lB(process.argv.slice(4),process.cwd());return}let t;try{t=Fx()}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let r=uB();if(t.help){process.stdout.write(Ox());return}if(t.version){process.stdout.write(`robota ${r}\n`);return}if(t.checkUpdate){let e=await Yb({currentVersion:r,force:!0}),t=tx(e);e.status===`error`&&(process.stderr.write(`${t}\n`),process.exit(1)),process.stdout.write(`${t}\n`);return}let i=process.cwd(),a=new ux;if(t.reset){process.exitCode=await fB(a,{yes:t.yes,isTTY:process.stdin.isTTY===!0});return}if(t.positional[0]===`diagnose`){let e=await CB({version:r,terminal:a,cwd:i});process.exitCode=+(e>0);return}if(t.positional[0]===`session`&&t.positional[1]===`analyze`){await lB(process.argv.slice(4),i);return}try{if(await zz(t,i,a))return}catch(e){a.writeError(e instanceof Error?e.message:String(e)),process.exit(1)}let o=Km(Wm()),s=typeof o.preset==`string`?o.preset:void 0,c=fS();for(let{file:e,error:t}of c.errors)a.writeError(`Skipped external preset "${e}": ${t}`);let l;try{l=hS(t,s)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let u=pS(t,s),{commandHostAdapters:d,providerDefinitions:f,commandModules:p,startupUpdateNoticePromise:m}=GW(i,t,e,r,{...l.enabledCommandModules===void 0?{}:{enabledCommandModules:l.enabledCommandModules},...l.disabledCommandModules===void 0?{}:{disabledCommandModules:l.disabledCommandModules}});if(t.positional[0]===`init`){try{await kB(i,a,{yes:t.yes,onProviderSetup:async()=>{await VP(i,t,dx,a,f)}})}catch(e){a.writeError(e instanceof Error?e.message:String(e)),process.exit(1)}return}if(t.configure){await VP(i,t,dx,a,f);return}if(zP(i,t,a,f))return;try{await BP(i,t,dx,a,f)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(e instanceof L_&&t.printMode?3:1)}let h=t.provider?{providerOverride:t.provider,providerDefinitions:f}:{providerDefinitions:f},g=B_(i,h),_=l.model??g.model;if(g.source===`env-default`&&g.sourceEnvVar!==void 0){let e=`Using ${g.name} (${_}) via ${g.sourceEnvVar} — run \`robota --configure\` to persist a profile.\n`;t.printMode?process.stderr.write(e):a.writeLine(e.trimEnd())}let v=t.sessionLog?YW(t.sessionLog):V_(i,l.model,h),y=es(),b=dp(i),x=jz({workerPath:Rz(),providerConfig:{...g,model:_},logsDir:b.logs}),S=My(i),C,w=!1;if(t.continueMode?C=Fy(S,i):t.resumeId!==void 0&&(t.resumeId===``?w=!0:(C=Iy(S,t.resumeId),C===void 0&&(process.stderr.write(`Session not found: ${t.resumeId}\n`),process.exit(1)))),t.printMode||t.goal){await JW(i,t,v,S,y,x,p,d,{resumeSessionId:C,forkSession:t.forkSession},{agentName:l.agentName??Vx,activePresetId:u,persona:l.persona,...l.permissionMode===void 0?{}:{permissionMode:l.permissionMode},...l.enableParallelSubagents===void 0?{}:{enableParallelSubagents:l.enableParallelSubagents},...l.selfVerification===void 0?{}:{selfVerification:l.selfVerification}});return}PB(a),WR(),AB()&&(NB(a),jB()),await RR({onChannelReady:e=>HR(e),cwd:i,provider:v,providerOverride:t.provider,providerType:g.name,modelId:_,language:t.language,permissionMode:t.permissionMode??l.permissionMode,maxTurns:t.maxTurns,allowedTools:kx(t.allowedTools),deniedTools:kx(t.deniedTools),version:r,sessionStore:t.noSessionPersistence?void 0:S,resumeSessionId:C,showSessionPickerOnStart:w,forkSession:t.forkSession,sessionName:t.sessionName,backgroundTaskRunners:y,subagentRunnerFactory:x,commandModules:p,commandHostAdapters:d,shellExec:e=>n(e,{timeout:5e3,encoding:`utf-8`,stdio:`pipe`}).trimEnd(),startupUpdateNotice:m?m.then(e=>e?ex(e):void 0):void 0,transportRegistry:XW(),cliAdapter:zR({providerDefinitions:f,reloadPluginCommandSource:LP}),reloadPluginCommandSource:LP,agentName:l.agentName??Vx,activePresetId:u,persona:l.persona,...l.enableParallelSubagents===void 0?{}:{enableParallelSubagents:l.enableParallelSubagents},...l.selfVerification===void 0?{}:{selfVerification:l.selfVerification}}),process.exit(0)}export{ZW as startCli};
402
404
  //# sourceMappingURL=index.js.map