art-framework 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import {v4}from'uuid';import*as K from'zod';import {z}from'zod';import It from'ajv';import {CallToolResultSchema}from'@modelcontextprotocol/sdk/types.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {hasInstall,install,getInstallUrl,getAllowedInfo,requestHosts}from'art-mcp-permission-manager';import {GoogleGenAI}from'@google/genai';import qt from'openai';import {Anthropic}from'@anthropic-ai/sdk';import*as _ from'mathjs';import {evaluate}from'mathjs';var H=(b=>(b.INVALID_CONFIG="INVALID_CONFIG",b.MISSING_API_key="MISSING_API_KEY",b.CONFIGURATION_ERROR="CONFIGURATION_ERROR",b.STORAGE_ERROR="STORAGE_ERROR",b.THREAD_NOT_FOUND="THREAD_NOT_FOUND",b.SAVE_FAILED="SAVE_FAILED",b.LLM_PROVIDER_ERROR="LLM_PROVIDER_ERROR",b.PROMPT_GENERATION_FAILED="PROMPT_GENERATION_FAILED",b.OUTPUT_PARSING_FAILED="OUTPUT_PARSING_FAILED",b.PROMPT_ASSEMBLY_FAILED="PROMPT_ASSEMBLY_FAILED",b.PROMPT_FRAGMENT_NOT_FOUND="PROMPT_FRAGMENT_NOT_FOUND",b.PROMPT_VALIDATION_FAILED="PROMPT_VALIDATION_FAILED",b.PROMPT_TRANSLATION_FAILED="PROMPT_TRANSLATION_FAILED",b.TOOL_NOT_FOUND="TOOL_NOT_FOUND",b.TOOL_SCHEMA_VALIDATION_FAILED="TOOL_SCHEMA_VALIDATION_FAILED",b.TOOL_EXECUTION_ERROR="TOOL_EXECUTION_ERROR",b.TOOL_DISABLED="TOOL_DISABLED",b.PLANNING_FAILED="PLANNING_FAILED",b.TOOL_EXECUTION_FAILED="TOOL_EXECUTION_FAILED",b.SYNTHESIS_FAILED="SYNTHESIS_FAILED",b.AGENT_PROCESSING_ERROR="AGENT_PROCESSING_ERROR",b.DELEGATION_FAILED="DELEGATION_FAILED",b.NETWORK_ERROR="NETWORK_ERROR",b.TIMEOUT_ERROR="TIMEOUT_ERROR",b.TIMEOUT="TIMEOUT",b.EXTERNAL_SERVICE_ERROR="EXTERNAL_SERVICE_ERROR",b.TASK_NOT_FOUND="TASK_NOT_FOUND",b.VALIDATION_ERROR="VALIDATION_ERROR",b.INVALID_REQUEST="INVALID_REQUEST",b.DUPLICATE_TASK_ID="DUPLICATE_TASK_ID",b.REPOSITORY_ERROR="REPOSITORY_ERROR",b.ALREADY_CONNECTED="ALREADY_CONNECTED",b.MISSING_CONFIG="MISSING_CONFIG",b.NOT_IMPLEMENTED="NOT_IMPLEMENTED",b.NOT_CONNECTED="NOT_CONNECTED",b.REQUEST_TIMEOUT="REQUEST_TIMEOUT",b.NO_STDIN="NO_STDIN",b.NO_HTTP_URL="NO_HTTP_URL",b.HTTP_ERROR="HTTP_ERROR",b.SERVER_NOT_FOUND="SERVER_NOT_FOUND",b.HEALTH_CHECK_FAILED="HEALTH_CHECK_FAILED",b.TOOL_DISCOVERY_FAILED="TOOL_DISCOVERY_FAILED",b.UNSUPPORTED_TRANSPORT="UNSUPPORTed_TRANSPORT",b.CORS_EXTENSION_REQUIRED="CORS_EXTENSION_REQUIRED",b.CORS_PERMISSION_REQUIRED="CORS_PERMISSION_REQUIRED",b.UNKNOWN_ERROR="UNKNOWN_ERROR",b.UNKNOWN_PROVIDER="UNKNOWN_PROVIDER",b.LOCAL_PROVIDER_CONFLICT="LOCAL_PROVIDER_CONFLICT",b.LOCAL_INSTANCE_BUSY="LOCAL_INSTANCE_BUSY",b.API_QUEUE_TIMEOUT="API_QUEUE_TIMEOUT",b.ADAPTER_INSTANTIATION_ERROR="ADAPTER_INSTANTIATION_ERROR",b))(H||{}),d=class g extends Error{constructor(e,t,r,n={}){super(e),this.name="ARTError",this.code=t,this.originalError=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,g);}toString(){let e=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(e+=`
2
- Caused by: ${this.originalError.stack||this.originalError.toString()}`),e}},ne=class extends d{constructor(e){super(`Unknown provider requested: ${e}`,"UNKNOWN_PROVIDER"),this.name="UnknownProviderError";}},oe=class extends d{constructor(e,t){super(`Cannot activate local provider '${e}'. Local provider '${t}' is already active.`,"LOCAL_PROVIDER_CONFLICT"),this.name="LocalProviderConflictError";}},ae=class extends d{constructor(e,t){super(`Local provider instance '${e}:${t}' is currently busy.`,"LOCAL_INSTANCE_BUSY"),this.name="LocalInstanceBusyError";}},Ge=class extends d{constructor(e){super(`Timeout waiting for an available instance of API provider '${e}'.`,"API_QUEUE_TIMEOUT"),this.name="ApiQueueTimeoutError";}},se=class extends d{constructor(e,t){super(`Failed to instantiate adapter for provider '${e}'.`,"ADAPTER_INSTANTIATION_ERROR",t),this.name="AdapterInstantiationError";}};var ie=class{constructor(e){this.availableProviders=new Map(e.availableProviders.map(t=>[t.name,t])),this.maxParallelApiInstancesPerProvider=e.maxParallelApiInstancesPerProvider??5,this.apiInstanceIdleTimeoutMs=(e.apiInstanceIdleTimeoutSeconds??300)*1e3,this.managedInstances=new Map,this.requestQueue=[];}_getConfigSignature(e){let t=e.adapterOptions?Object.keys(e.adapterOptions).sort().reduce((r,n)=>(r[n]=n.toLowerCase().includes("key")?"***":e.adapterOptions[n],r),{}):{};return JSON.stringify({providerName:e.providerName,modelId:e.modelId,adapterOptions:t})}getAvailableProviders(){return Array.from(this.availableProviders.keys())}async getAdapter(e){let t=this._getConfigSignature(e),r=this.managedInstances.get(t);if(r&&r.state==="idle"){r.state="active",r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0);let c=()=>this._releaseAdapter(t);return {adapter:r.adapter,release:c}}let n=this.availableProviders.get(e.providerName);if(!n)throw new ne(e.providerName);if(n.isLocal){let c;for(let[l,p]of this.managedInstances.entries()){let u=this.availableProviders.get(p.configSignature.split('"providerName":"')[1].split('"')[0]);if(u?.isLocal){if(p.state==="active")throw l!==t?new oe(e.providerName,u.name):new ae(e.providerName,e.modelId);p.state==="idle"&&l!==t&&(c=p);}}c&&await this._evictInstance(c.configSignature);}if(!n.isLocal&&Array.from(this.managedInstances.values()).filter(l=>{let p=this.availableProviders.get(l.configSignature.split('"providerName":"')[1].split('"')[0]);return p&&!p.isLocal&&l.state==="active"&&p.name===e.providerName}).length>=this.maxParallelApiInstancesPerProvider)return new Promise((l,p)=>{this.requestQueue.push({config:e,resolve:l,reject:p});});let o;try{let c={...n.baseOptions,...e.adapterOptions,providerName:e.providerName};o=new n.adapter(c);}catch(c){throw new se(e.providerName,c)}let s={adapter:o,configSignature:t,state:"active"};this.managedInstances.set(t,s);let i=()=>this._releaseAdapter(t);return {adapter:s.adapter,release:i}}_releaseAdapter(e){let t=this.managedInstances.get(e);if(!t)return;t.state="idle",t.lastUsedTimestamp=Date.now();let r=this.availableProviders.get(t.configSignature.split('"providerName":"')[1].split('"')[0]);if(r&&!r.isLocal&&(t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this._evictInstance(e);},this.apiInstanceIdleTimeoutMs)),this.requestQueue.length>0){let n=this.requestQueue.shift();n&&this.getAdapter(n.config).then(n.resolve).catch(n.reject);}}async _evictInstance(e){let t=this.managedInstances.get(e);if(t&&t.state==="idle"){if(t.adapter.shutdown)try{await t.adapter.shutdown();}catch{}this.managedInstances.delete(e),t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0);}}};var nt=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(nt||{}),B=class B{static configure(e){B.config={...B.config,...e};}static debug(e,...t){B.config.level<=0&&console.debug(`${B.config.prefix||"[ART]"} ${e}`,...t);}static info(e,...t){B.config.level<=1&&console.info(`${B.config.prefix||"[ART]"} ${e}`,...t);}static warn(e,...t){B.config.level<=2&&console.warn(`${B.config.prefix||"[ART]"} ${e}`,...t);}static error(e,...t){B.config.level<=3&&console.error(`${B.config.prefix||"[ART]"} ${e}`,...t);}};B.config={level:1};var a=B;var V=class{constructor(){this.subscriptions=new Map;}subscribe(e,t,r){let n=v4(),o={id:n,callback:e,filter:t,options:r};return this.subscriptions.set(n,o),a.debug(`New subscription added: ${n}, Filter: ${JSON.stringify(t)}, Options: ${JSON.stringify(r)}`),()=>{this.subscriptions.delete(n),a.debug(`Subscription removed: ${n}`);}}notify(e,t,r){let n=this.constructor.name;a.debug(`[${n}] notify() called. Data type: ${typeof e}, Sub count: ${this.subscriptions.size}, Options: ${JSON.stringify(t)}`),a.debug(`Notifying ${this.subscriptions.size} subscribers. Data: ${JSON.stringify(e).substring(0,100)}..., Options: ${JSON.stringify(t)}`),this.subscriptions.forEach(o=>{try{if(o.options?.threadId&&t?.targetThreadId&&o.options.threadId!==t.targetThreadId||r&&o.filter!==void 0&&!r(e,o.filter))return;a.debug(`Checks passed for sub ${o.id}. Invoking callback.`),o.callback(e);}catch(s){a.error(`Error executing subscription callback ${o.id}:`,s);}});}async getHistory(e,t){return a.warn("getHistory is not implemented in the base TypedSocket."),[]}clearAllSubscriptions(){this.subscriptions.clear(),a.debug("All subscriptions cleared.");}};var Q=class extends V{constructor(){super(),a.debug("LLMStreamSocket initialized.");}notifyStreamEvent(e){a.debug(`Notifying LLMStreamEvent: ${e.type} for thread ${e.threadId}, trace ${e.traceId}`),super.notify(e,{targetThreadId:e.threadId,targetSessionId:e.sessionId},(t,r)=>r?Array.isArray(r)?r.includes(t.type):t.type===r:true);}};var ee=class extends V{constructor(e){super(),this.taskRepository=e,a.debug("A2ATaskSocket initialized.");}notifyTaskEvent(e){a.debug(`Notifying A2A Task Event: ${e.task.taskId} (${e.eventType}) status: ${e.task.status}`),super.notify(e,{targetThreadId:e.task.metadata.correlationId,targetSessionId:e.task.sourceAgent.agentId},(t,r)=>this.matchesFilter(t,r));}notifyTaskCreated(e,t){this.notifyTaskEvent({task:e,eventType:"created",timestamp:Date.now(),metadata:t});}notifyTaskUpdated(e,t,r){let n="updated";t&&t!==e.status&&(n="status_changed",e.status==="COMPLETED"?n="completed":e.status==="FAILED"?n="failed":e.status==="CANCELLED"?n="cancelled":e.targetAgent&&t==="PENDING"&&(n="delegated")),this.notifyTaskEvent({task:e,eventType:n,timestamp:Date.now(),previousStatus:t,metadata:r});}notifyTaskDelegated(e,t){this.notifyTaskEvent({task:e,eventType:"delegated",timestamp:Date.now(),metadata:t});}notifyTaskCompleted(e,t){this.notifyTaskEvent({task:e,eventType:"completed",timestamp:Date.now(),metadata:t});}notifyTaskFailed(e,t){this.notifyTaskEvent({task:e,eventType:"failed",timestamp:Date.now(),metadata:t});}async getHistory(e,t){if(!this.taskRepository)return a.warn("Cannot getHistory for A2ATaskSocket: IA2ATaskRepository not configured."),[];a.debug(`Getting history for A2ATaskSocket: Thread ${t?.threadId}, Filter: ${JSON.stringify(e)}, Limit: ${t?.limit}`);try{let r=[];t?.threadId?r=await this.taskRepository.getTasksByThread(t.threadId):e?.status?r=await this.taskRepository.getTasksByStatus(e.status,{limit:t?.limit}):r=await this.taskRepository.getTasksByStatus(["PENDING","IN_PROGRESS","COMPLETED","FAILED","WAITING","REVIEW"],{limit:t?.limit});let n=r.map(o=>this.taskToEvent(o)).filter(o=>this.matchesFilter(o,e));return n.sort((o,s)=>s.timestamp-o.timestamp),t?.limit&&(!e?.status||t.threadId)&&(n=n.slice(0,t.limit)),n}catch(r){return a.error("Error fetching A2A task history:",r),[]}}taskToEvent(e){let t="updated";return e.status==="COMPLETED"?t="completed":e.status==="FAILED"?t="failed":e.status==="CANCELLED"?t="cancelled":e.targetAgent?t="delegated":e.metadata.createdAt===e.metadata.updatedAt&&(t="created"),{task:e,eventType:t,timestamp:e.metadata.updatedAt||e.metadata.createdAt,metadata:{automatic:true,source:"history",context:{taskType:e.payload.taskType,priority:e.priority,hasTargetAgent:!!e.targetAgent}}}}matchesFilter(e,t){if(!t)return true;let r=e.task;return !(t.status&&!(Array.isArray(t.status)?t.status:[t.status]).includes(r.status)||t.taskType&&!(Array.isArray(t.taskType)?t.taskType:[t.taskType]).includes(r.payload.taskType)||t.sourceAgentId&&r.sourceAgent.agentId!==t.sourceAgentId||t.targetAgentId&&(!r.targetAgent||r.targetAgent.agentId!==t.targetAgentId)||t.priority&&r.priority!==t.priority||t.threadId&&r.metadata.correlationId!==t.threadId)}};var le=(s=>(s.PENDING="pending",s.IN_PROGRESS="in_progress",s.COMPLETED="completed",s.FAILED="failed",s.CANCELLED="cancelled",s.WAITING="waiting",s))(le||{});var ot=z.object({role:z.custom(g=>typeof g=="string"&&["system","user","assistant","tool","tool_request","tool_result"].includes(g),{message:"Invalid message role"}),content:z.union([z.string(),z.record(z.any()),z.null()]),name:z.string().optional(),tool_calls:z.array(z.object({id:z.string(),type:z.literal("function"),function:z.object({name:z.string(),arguments:z.string()})})).optional(),tool_call_id:z.string().optional()}).strict().refine(g=>!((g.role==="tool"||g.role==="tool_result")&&!g.tool_call_id||g.role==="assistant"&&g.content!==null&&typeof g.content!="string"||(g.role==="user"||g.role==="system")&&typeof g.content!="string"),{message:"Invalid message structure based on role (e.g., tool_call_id missing for tool role, invalid content type for user/system, assistant content not string/null)"}),yt=z.array(ot);var at=(n=>(n.USER="USER",n.AI="AI",n.SYSTEM="SYSTEM",n.TOOL="TOOL",n))(at||{}),Fe=(m=>(m.INTENT="INTENT",m.TITLE="TITLE",m.PLAN="PLAN",m.THOUGHTS="THOUGHTS",m.TOOL_CALL="TOOL_CALL",m.TOOL_EXECUTION="TOOL_EXECUTION",m.SYNTHESIS="SYNTHESIS",m.ERROR="ERROR",m.FINAL_RESPONSE="FINAL_RESPONSE",m.STATE_UPDATE="STATE_UPDATE",m.PLAN_UPDATE="PLAN_UPDATE",m.ITEM_STATUS_CHANGE="ITEM_STATUS_CHANGE",m.LLM_STREAM_START="LLM_STREAM_START",m.LLM_STREAM_METADATA="LLM_STREAM_METADATA",m.LLM_STREAM_END="LLM_STREAM_END",m.LLM_STREAM_ERROR="LLM_STREAM_ERROR",m))(Fe||{}),st=(i=>(i.TEXT="text",i.VISION="vision",i.STREAMING="streaming",i.TOOL_USE="tool_use",i.RAG="rag",i.CODE="code",i.REASONING="reasoning",i))(st||{}),ve=(i=>(i.PENDING="PENDING",i.IN_PROGRESS="IN_PROGRESS",i.COMPLETED="COMPLETED",i.FAILED="FAILED",i.CANCELLED="CANCELLED",i.WAITING="WAITING",i.REVIEW="REVIEW",i))(ve||{}),it=(n=>(n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH",n.URGENT="URGENT",n))(it||{});var X=()=>v4();var lt={name:"Zoi",prompts:{planning:"You are a helpful AI assistant. Your primary goal is to understand a user's query, determine the intent, and create a clear plan to provide an accurate and helpful response. You can use tools to gather information if necessary.",synthesis:"You are a helpful AI assistant named Art. Your primary goal is to synthesize the information gathered from tools, outcomes of each todo list task and planning into a final, user-friendly response. Be clear, concise, and helpful. If any ui components are defined, you should use those to display your outputs."}},ce=class{constructor(e){this.deps=e,this.persona={...lt,...e.persona,prompts:{...lt.prompts,...e.persona?.prompts}};}async process(e){let t=Date.now(),r=e.traceId??X(),n="success",o,s=0,i=0,c,l,p="initialization";try{p="configuration";let{threadContext:A,planningSystemPrompt:E,synthesisSystemPrompt:M,runtimeProviderConfig:m,finalPersona:w}=await this._loadConfiguration(e,r);p="context_gathering";let S=await this._gatherHistory(e.threadId,A),N=await this._gatherTools(e.threadId);p="state_loading";let C=A.state?.data;if(!!C&&C.todoList&&C.todoList.length>0){if(a.debug(`[${r}] Existing plan found. Processing follow-up/refinement.`),p="planning_refinement",e.query&&e.query.trim().length>0){let h=await this._performPlanRefinement(e,E,S,C,N,m,r);s++,h.metadata&&(l={...l??{},...h.metadata}),h.output.todoList&&(C.intent=h.output.intent||C.intent,C.plan=h.output.plan||C.plan,C.todoList=h.output.todoList,await this._saveState(e.threadId,C),await this._recordPlanObservations(e.threadId,r,h.output,h.rawText));}}else {a.debug(`[${r}] No existing plan found. Initiating Planning Phase.`),p="planning";let h=await this._performPlanning(e,E,S,N,m,r);s++,h.metadata&&(l={...l??{},...h.metadata}),C={threadId:e.threadId,intent:h.output.intent||"Unknown Intent",title:h.output.title||"New Conversation",plan:h.output.plan||"",todoList:h.output.todoList||[],currentStepId:null,isPaused:!1},await this._saveState(e.threadId,C),await this._recordPlanObservations(e.threadId,r,h.output,h.rawText);}p="execution_loop";let L=await this._executeTodoList(e,C,N,m,r);s+=L.llmCalls,i+=L.toolCalls,L.llmMetadata&&(l={...l??{},...L.llmMetadata}),p="synthesis";let{finalResponseContent:R,synthesisMetadata:y,uiMetadata:O}=await this._performSynthesis(e,M,S,C,m,r,w);s++,y&&(l={...l??{},...y}),p="finalization",c=await this._finalize(e,R,r,O);}catch(A){let E=A instanceof d?A:new d(`An unexpected error occurred during agent processing: ${A.message}`,"UNKNOWN_ERROR",A);E.details=E.details||{},E.details.phase=p,a.error(`[${r}] PESAgent process error in phase '${p}':`,E),n="error",o=E.message,await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"ERROR",content:{phase:p,error:E.message,stack:E.stack},metadata:{timestamp:Date.now()}});}finally{try{await this.deps.stateManager.saveStateIfModified(e.threadId);}catch(A){a.error(`[${r}] Failed to save state during finalization:`,A);}}let u=Date.now(),f={threadId:e.threadId,traceId:r,userId:e.userId,status:n,totalDurationMs:u-t,llmCalls:s,toolCalls:i,error:o,llmMetadata:l};return !c&&n!=="success"&&(c={messageId:X(),threadId:e.threadId,role:"AI",content:o??"Agent execution failed.",timestamp:Date.now(),metadata:{traceId:r,error:true}}),{response:c,metadata:f}}async _saveState(e,t){await this.deps.stateManager.setAgentState(e,{data:t,version:1,modified:Date.now()});}async _recordPlanObservations(e,t,r,n){await this.deps.observationManager.record({threadId:e,traceId:t,type:"INTENT",content:{intent:r.intent},metadata:{timestamp:Date.now()}}),r.title&&await this.deps.observationManager.record({threadId:e,traceId:t,type:"TITLE",content:{title:r.title},metadata:{timestamp:Date.now()}}),await this.deps.observationManager.record({threadId:e,traceId:t,type:"PLAN",content:{plan:r.plan,todoList:r.todoList,rawOutput:n},metadata:{timestamp:Date.now()}}),await this.deps.observationManager.record({threadId:e,traceId:t,type:"PLAN_UPDATE",content:{todoList:r.todoList},metadata:{timestamp:Date.now()}});}async _performPlanning(e,t,r,n,o,s){a.debug(`[${s}] Stage 3: Planning`);let i=n.map(p=>({name:p.name,description:p.description,inputSchema:p.inputSchema})),l=[{role:"system",content:`You are a planning assistant.
1
+ import {v4}from'uuid';import*as q from'zod';import {z}from'zod';import It from'ajv';import {CallToolResultSchema}from'@modelcontextprotocol/sdk/types.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {hasInstall,install,getInstallUrl,getAllowedInfo,requestHosts}from'art-mcp-permission-manager';import {GoogleGenAI}from'@google/genai';import qt from'openai';import {Anthropic}from'@anthropic-ai/sdk';import*as E from'mathjs';import {evaluate}from'mathjs';var F=(b=>(b.INVALID_CONFIG="INVALID_CONFIG",b.MISSING_API_key="MISSING_API_KEY",b.CONFIGURATION_ERROR="CONFIGURATION_ERROR",b.STORAGE_ERROR="STORAGE_ERROR",b.THREAD_NOT_FOUND="THREAD_NOT_FOUND",b.SAVE_FAILED="SAVE_FAILED",b.LLM_PROVIDER_ERROR="LLM_PROVIDER_ERROR",b.PROMPT_GENERATION_FAILED="PROMPT_GENERATION_FAILED",b.OUTPUT_PARSING_FAILED="OUTPUT_PARSING_FAILED",b.PROMPT_ASSEMBLY_FAILED="PROMPT_ASSEMBLY_FAILED",b.PROMPT_FRAGMENT_NOT_FOUND="PROMPT_FRAGMENT_NOT_FOUND",b.PROMPT_VALIDATION_FAILED="PROMPT_VALIDATION_FAILED",b.PROMPT_TRANSLATION_FAILED="PROMPT_TRANSLATION_FAILED",b.TOOL_NOT_FOUND="TOOL_NOT_FOUND",b.TOOL_SCHEMA_VALIDATION_FAILED="TOOL_SCHEMA_VALIDATION_FAILED",b.TOOL_EXECUTION_ERROR="TOOL_EXECUTION_ERROR",b.TOOL_DISABLED="TOOL_DISABLED",b.PLANNING_FAILED="PLANNING_FAILED",b.TOOL_EXECUTION_FAILED="TOOL_EXECUTION_FAILED",b.SYNTHESIS_FAILED="SYNTHESIS_FAILED",b.AGENT_PROCESSING_ERROR="AGENT_PROCESSING_ERROR",b.DELEGATION_FAILED="DELEGATION_FAILED",b.NETWORK_ERROR="NETWORK_ERROR",b.TIMEOUT_ERROR="TIMEOUT_ERROR",b.TIMEOUT="TIMEOUT",b.EXTERNAL_SERVICE_ERROR="EXTERNAL_SERVICE_ERROR",b.TASK_NOT_FOUND="TASK_NOT_FOUND",b.VALIDATION_ERROR="VALIDATION_ERROR",b.INVALID_REQUEST="INVALID_REQUEST",b.DUPLICATE_TASK_ID="DUPLICATE_TASK_ID",b.REPOSITORY_ERROR="REPOSITORY_ERROR",b.ALREADY_CONNECTED="ALREADY_CONNECTED",b.MISSING_CONFIG="MISSING_CONFIG",b.NOT_IMPLEMENTED="NOT_IMPLEMENTED",b.NOT_CONNECTED="NOT_CONNECTED",b.REQUEST_TIMEOUT="REQUEST_TIMEOUT",b.NO_STDIN="NO_STDIN",b.NO_HTTP_URL="NO_HTTP_URL",b.HTTP_ERROR="HTTP_ERROR",b.SERVER_NOT_FOUND="SERVER_NOT_FOUND",b.HEALTH_CHECK_FAILED="HEALTH_CHECK_FAILED",b.TOOL_DISCOVERY_FAILED="TOOL_DISCOVERY_FAILED",b.UNSUPPORTED_TRANSPORT="UNSUPPORTed_TRANSPORT",b.CORS_EXTENSION_REQUIRED="CORS_EXTENSION_REQUIRED",b.CORS_PERMISSION_REQUIRED="CORS_PERMISSION_REQUIRED",b.UNKNOWN_ERROR="UNKNOWN_ERROR",b.UNKNOWN_PROVIDER="UNKNOWN_PROVIDER",b.LOCAL_PROVIDER_CONFLICT="LOCAL_PROVIDER_CONFLICT",b.LOCAL_INSTANCE_BUSY="LOCAL_INSTANCE_BUSY",b.API_QUEUE_TIMEOUT="API_QUEUE_TIMEOUT",b.ADAPTER_INSTANTIATION_ERROR="ADAPTER_INSTANTIATION_ERROR",b))(F||{}),d=class g extends Error{constructor(e,t,r,n={}){super(e),this.name="ARTError",this.code=t,this.originalError=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,g);}toString(){let e=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(e+=`
2
+ Caused by: ${this.originalError.stack||this.originalError.toString()}`),e}},ae=class extends d{constructor(e){super(`Unknown provider requested: ${e}`,"UNKNOWN_PROVIDER"),this.name="UnknownProviderError";}},se=class extends d{constructor(e,t){super(`Cannot activate local provider '${e}'. Local provider '${t}' is already active.`,"LOCAL_PROVIDER_CONFLICT"),this.name="LocalProviderConflictError";}},ie=class extends d{constructor(e,t){super(`Local provider instance '${e}:${t}' is currently busy.`,"LOCAL_INSTANCE_BUSY"),this.name="LocalInstanceBusyError";}},Fe=class extends d{constructor(e){super(`Timeout waiting for an available instance of API provider '${e}'.`,"API_QUEUE_TIMEOUT"),this.name="ApiQueueTimeoutError";}},le=class extends d{constructor(e,t){super(`Failed to instantiate adapter for provider '${e}'.`,"ADAPTER_INSTANTIATION_ERROR",t),this.name="AdapterInstantiationError";}};var ce=class{constructor(e){this.availableProviders=new Map(e.availableProviders.map(t=>[t.name,t])),this.maxParallelApiInstancesPerProvider=e.maxParallelApiInstancesPerProvider??5,this.apiInstanceIdleTimeoutMs=(e.apiInstanceIdleTimeoutSeconds??300)*1e3,this.managedInstances=new Map,this.requestQueue=[];}_getConfigSignature(e){let t=e.adapterOptions?Object.keys(e.adapterOptions).sort().reduce((r,n)=>(r[n]=n.toLowerCase().includes("key")?"***":e.adapterOptions[n],r),{}):{};return JSON.stringify({providerName:e.providerName,modelId:e.modelId,adapterOptions:t})}getAvailableProviders(){return Array.from(this.availableProviders.keys())}async getAdapter(e){let t=this._getConfigSignature(e),r=this.managedInstances.get(t);if(r&&r.state==="idle"){r.state="active",r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0);let c=()=>this._releaseAdapter(t);return {adapter:r.adapter,release:c}}let n=this.availableProviders.get(e.providerName);if(!n)throw new ae(e.providerName);if(n.isLocal){let c;for(let[l,p]of this.managedInstances.entries()){let u=this.availableProviders.get(p.configSignature.split('"providerName":"')[1].split('"')[0]);if(u?.isLocal){if(p.state==="active")throw l!==t?new se(e.providerName,u.name):new ie(e.providerName,e.modelId);p.state==="idle"&&l!==t&&(c=p);}}c&&await this._evictInstance(c.configSignature);}if(!n.isLocal&&Array.from(this.managedInstances.values()).filter(l=>{let p=this.availableProviders.get(l.configSignature.split('"providerName":"')[1].split('"')[0]);return p&&!p.isLocal&&l.state==="active"&&p.name===e.providerName}).length>=this.maxParallelApiInstancesPerProvider)return new Promise((l,p)=>{this.requestQueue.push({config:e,resolve:l,reject:p});});let o;try{let c={...n.baseOptions,...e.adapterOptions,providerName:e.providerName};o=new n.adapter(c);}catch(c){throw new le(e.providerName,c)}let s={adapter:o,configSignature:t,state:"active"};this.managedInstances.set(t,s);let i=()=>this._releaseAdapter(t);return {adapter:s.adapter,release:i}}_releaseAdapter(e){let t=this.managedInstances.get(e);if(!t)return;t.state="idle",t.lastUsedTimestamp=Date.now();let r=this.availableProviders.get(t.configSignature.split('"providerName":"')[1].split('"')[0]);if(r&&!r.isLocal&&(t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this._evictInstance(e);},this.apiInstanceIdleTimeoutMs)),this.requestQueue.length>0){let n=this.requestQueue.shift();n&&this.getAdapter(n.config).then(n.resolve).catch(n.reject);}}async _evictInstance(e){let t=this.managedInstances.get(e);if(t&&t.state==="idle"){if(t.adapter.shutdown)try{await t.adapter.shutdown();}catch{}this.managedInstances.delete(e),t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0);}}};var nt=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(nt||{}),B=class B{static configure(e){B.config={...B.config,...e};}static debug(e,...t){B.config.level<=0&&console.debug(`${B.config.prefix||"[ART]"} ${e}`,...t);}static info(e,...t){B.config.level<=1&&console.info(`${B.config.prefix||"[ART]"} ${e}`,...t);}static warn(e,...t){B.config.level<=2&&console.warn(`${B.config.prefix||"[ART]"} ${e}`,...t);}static error(e,...t){B.config.level<=3&&console.error(`${B.config.prefix||"[ART]"} ${e}`,...t);}};B.config={level:1};var a=B;var V=class{constructor(){this.subscriptions=new Map;}subscribe(e,t,r){let n=v4(),o={id:n,callback:e,filter:t,options:r};return this.subscriptions.set(n,o),a.debug(`New subscription added: ${n}, Filter: ${JSON.stringify(t)}, Options: ${JSON.stringify(r)}`),()=>{this.subscriptions.delete(n),a.debug(`Subscription removed: ${n}`);}}notify(e,t,r){let n=this.constructor.name;a.debug(`[${n}] notify() called. Data type: ${typeof e}, Sub count: ${this.subscriptions.size}, Options: ${JSON.stringify(t)}`),a.debug(`Notifying ${this.subscriptions.size} subscribers. Data: ${(JSON.stringify(e)??"null").substring(0,100)}..., Options: ${JSON.stringify(t)}`),this.subscriptions.forEach(o=>{try{if(o.options?.threadId&&t?.targetThreadId&&o.options.threadId!==t.targetThreadId||r&&o.filter!==void 0&&!r(e,o.filter))return;a.debug(`Checks passed for sub ${o.id}. Invoking callback.`),o.callback(e);}catch(s){a.error(`Error executing subscription callback ${o.id}:`,s);}});}async getHistory(e,t){return a.warn("getHistory is not implemented in the base TypedSocket."),[]}clearAllSubscriptions(){this.subscriptions.clear(),a.debug("All subscriptions cleared.");}};var te=class extends V{constructor(){super(),a.debug("LLMStreamSocket initialized.");}notifyStreamEvent(e){a.debug(`Notifying LLMStreamEvent: ${e.type} for thread ${e.threadId}, trace ${e.traceId}`),super.notify(e,{targetThreadId:e.threadId,targetSessionId:e.sessionId},(t,r)=>r?Array.isArray(r)?r.includes(t.type):t.type===r:true);}};var re=class extends V{constructor(e){super(),this.taskRepository=e,a.debug("A2ATaskSocket initialized.");}notifyTaskEvent(e){a.debug(`Notifying A2A Task Event: ${e.task.taskId} (${e.eventType}) status: ${e.task.status}`),super.notify(e,{targetThreadId:e.task.metadata.correlationId,targetSessionId:e.task.sourceAgent.agentId},(t,r)=>this.matchesFilter(t,r));}notifyTaskCreated(e,t){this.notifyTaskEvent({task:e,eventType:"created",timestamp:Date.now(),metadata:t});}notifyTaskUpdated(e,t,r){let n="updated";t&&t!==e.status&&(n="status_changed",e.status==="COMPLETED"?n="completed":e.status==="FAILED"?n="failed":e.status==="CANCELLED"?n="cancelled":e.targetAgent&&t==="PENDING"&&(n="delegated")),this.notifyTaskEvent({task:e,eventType:n,timestamp:Date.now(),previousStatus:t,metadata:r});}notifyTaskDelegated(e,t){this.notifyTaskEvent({task:e,eventType:"delegated",timestamp:Date.now(),metadata:t});}notifyTaskCompleted(e,t){this.notifyTaskEvent({task:e,eventType:"completed",timestamp:Date.now(),metadata:t});}notifyTaskFailed(e,t){this.notifyTaskEvent({task:e,eventType:"failed",timestamp:Date.now(),metadata:t});}async getHistory(e,t){if(!this.taskRepository)return a.warn("Cannot getHistory for A2ATaskSocket: IA2ATaskRepository not configured."),[];a.debug(`Getting history for A2ATaskSocket: Thread ${t?.threadId}, Filter: ${JSON.stringify(e)}, Limit: ${t?.limit}`);try{let r=[];t?.threadId?r=await this.taskRepository.getTasksByThread(t.threadId):e?.status?r=await this.taskRepository.getTasksByStatus(e.status,{limit:t?.limit}):r=await this.taskRepository.getTasksByStatus(["PENDING","IN_PROGRESS","COMPLETED","FAILED","WAITING","REVIEW"],{limit:t?.limit});let n=r.map(o=>this.taskToEvent(o)).filter(o=>this.matchesFilter(o,e));return n.sort((o,s)=>s.timestamp-o.timestamp),t?.limit&&(!e?.status||t.threadId)&&(n=n.slice(0,t.limit)),n}catch(r){return a.error("Error fetching A2A task history:",r),[]}}taskToEvent(e){let t="updated";return e.status==="COMPLETED"?t="completed":e.status==="FAILED"?t="failed":e.status==="CANCELLED"?t="cancelled":e.targetAgent?t="delegated":e.metadata.createdAt===e.metadata.updatedAt&&(t="created"),{task:e,eventType:t,timestamp:e.metadata.updatedAt||e.metadata.createdAt,metadata:{automatic:true,source:"history",context:{taskType:e.payload.taskType,priority:e.priority,hasTargetAgent:!!e.targetAgent}}}}matchesFilter(e,t){if(!t)return true;let r=e.task;return !(t.status&&!(Array.isArray(t.status)?t.status:[t.status]).includes(r.status)||t.taskType&&!(Array.isArray(t.taskType)?t.taskType:[t.taskType]).includes(r.payload.taskType)||t.sourceAgentId&&r.sourceAgent.agentId!==t.sourceAgentId||t.targetAgentId&&(!r.targetAgent||r.targetAgent.agentId!==t.targetAgentId)||t.priority&&r.priority!==t.priority||t.threadId&&r.metadata.correlationId!==t.threadId)}};var de=(s=>(s.PENDING="pending",s.IN_PROGRESS="in_progress",s.COMPLETED="completed",s.FAILED="failed",s.CANCELLED="cancelled",s.WAITING="waiting",s))(de||{});var ot=z.object({role:z.custom(g=>typeof g=="string"&&["system","user","assistant","tool","tool_request","tool_result"].includes(g),{message:"Invalid message role"}),content:z.union([z.string(),z.record(z.any()),z.null()]),name:z.string().optional(),tool_calls:z.array(z.object({id:z.string(),type:z.literal("function"),function:z.object({name:z.string(),arguments:z.string()})})).optional(),tool_call_id:z.string().optional()}).strict().refine(g=>!((g.role==="tool"||g.role==="tool_result")&&!g.tool_call_id||g.role==="assistant"&&g.content!==null&&typeof g.content!="string"||(g.role==="user"||g.role==="system")&&typeof g.content!="string"),{message:"Invalid message structure based on role (e.g., tool_call_id missing for tool role, invalid content type for user/system, assistant content not string/null)"}),yt=z.array(ot);var at=(n=>(n.USER="USER",n.AI="AI",n.SYSTEM="SYSTEM",n.TOOL="TOOL",n))(at||{}),He=(h=>(h.INTENT="INTENT",h.TITLE="TITLE",h.PLAN="PLAN",h.THOUGHTS="THOUGHTS",h.TOOL_CALL="TOOL_CALL",h.TOOL_EXECUTION="TOOL_EXECUTION",h.SYNTHESIS="SYNTHESIS",h.ERROR="ERROR",h.FINAL_RESPONSE="FINAL_RESPONSE",h.STATE_UPDATE="STATE_UPDATE",h.PLAN_UPDATE="PLAN_UPDATE",h.ITEM_STATUS_CHANGE="ITEM_STATUS_CHANGE",h.LLM_STREAM_START="LLM_STREAM_START",h.LLM_STREAM_METADATA="LLM_STREAM_METADATA",h.LLM_STREAM_END="LLM_STREAM_END",h.LLM_STREAM_ERROR="LLM_STREAM_ERROR",h))(He||{}),st=(i=>(i.TEXT="text",i.VISION="vision",i.STREAMING="streaming",i.TOOL_USE="tool_use",i.RAG="rag",i.CODE="code",i.REASONING="reasoning",i))(st||{}),Re=(i=>(i.PENDING="PENDING",i.IN_PROGRESS="IN_PROGRESS",i.COMPLETED="COMPLETED",i.FAILED="FAILED",i.CANCELLED="CANCELLED",i.WAITING="WAITING",i.REVIEW="REVIEW",i))(Re||{}),it=(n=>(n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH",n.URGENT="URGENT",n))(it||{});var Z=()=>v4();var lt={name:"Zoi",prompts:{planning:"You are a helpful AI assistant. Your primary goal is to understand a user's query, determine the intent, and create a clear plan to provide an accurate and helpful response. You can use tools to gather information if necessary.",synthesis:"You are a helpful AI assistant named Art. Your primary goal is to synthesize the information gathered from tools, outcomes of each todo list task and planning into a final, user-friendly response. Be clear, concise, and helpful. If any ui components are defined, you should use those to display your outputs."}},pe=class{constructor(e){this.deps=e,this.persona={...lt,...e.persona,prompts:{...lt.prompts,...e.persona?.prompts}};}async process(e){let t=Date.now(),r=e.traceId??Z(),n="success",o,s=0,i=0,c,l,p="initialization";try{p="configuration";let{threadContext:I,planningSystemPrompt:v,synthesisSystemPrompt:C,runtimeProviderConfig:h,finalPersona:R}=await this._loadConfiguration(e,r);p="context_gathering";let O=await this._gatherHistory(e.threadId,I),x=await this._gatherTools(e.threadId);p="state_loading";let P=I.state?.data;if(!!P&&P.todoList&&P.todoList.length>0){if(a.debug(`[${r}] Existing plan found. Processing follow-up/refinement.`),p="planning_refinement",e.query&&e.query.trim().length>0){let f=await this._performPlanRefinement(e,v,O,P,x,h,r);s++,f.metadata&&(l={...l??{},...f.metadata}),f.output.todoList&&(P.intent=f.output.intent||P.intent,P.plan=f.output.plan||P.plan,P.todoList=f.output.todoList,await this._saveState(e.threadId,P),await this._recordPlanObservations(e.threadId,r,f.output,f.rawText));}}else {a.debug(`[${r}] No existing plan found. Initiating Planning Phase.`),p="planning";let f=await this._performPlanning(e,v,O,x,h,r);s++,f.metadata&&(l={...l??{},...f.metadata}),P={threadId:e.threadId,intent:f.output.intent||"Unknown Intent",title:f.output.title||"New Conversation",plan:f.output.plan||"",todoList:f.output.todoList||[],currentStepId:null,isPaused:!1},await this._saveState(e.threadId,P),await this._recordPlanObservations(e.threadId,r,f.output,f.rawText);}p="execution_loop";let D=await this._executeTodoList(e,P,x,h,r);s+=D.llmCalls,i+=D.toolCalls,D.llmMetadata&&(l={...l??{},...D.llmMetadata}),p="synthesis";let{finalResponseContent:k,synthesisMetadata:_,uiMetadata:w}=await this._performSynthesis(e,C,O,P,h,r,R);s++,_&&(l={...l??{},..._}),p="finalization",c=await this._finalize(e,k,r,w);}catch(I){let v=I instanceof d?I:new d(`An unexpected error occurred during agent processing: ${I.message}`,"UNKNOWN_ERROR",I);v.details=v.details||{},v.details.phase=p,a.error(`[${r}] PESAgent process error in phase '${p}':`,v),n="error",o=v.message,await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"ERROR",content:{phase:p,error:v.message,stack:v.stack},metadata:{timestamp:Date.now()}});}finally{try{await this.deps.stateManager.saveStateIfModified(e.threadId);}catch(I){a.error(`[${r}] Failed to save state during finalization:`,I);}}let u=Date.now(),m={threadId:e.threadId,traceId:r,userId:e.userId,status:n,totalDurationMs:u-t,llmCalls:s,toolCalls:i,error:o,llmMetadata:l};return !c&&n!=="success"&&(c={messageId:Z(),threadId:e.threadId,role:"AI",content:o??"Agent execution failed.",timestamp:Date.now(),metadata:{traceId:r,error:true}}),{response:c,metadata:m}}async _saveState(e,t){await this.deps.stateManager.setAgentState(e,{data:t,version:1,modified:Date.now()});}async _recordPlanObservations(e,t,r,n){await this.deps.observationManager.record({threadId:e,traceId:t,type:"INTENT",content:{intent:r.intent},metadata:{timestamp:Date.now()}}),r.title&&await this.deps.observationManager.record({threadId:e,traceId:t,type:"TITLE",content:{title:r.title},metadata:{timestamp:Date.now()}}),await this.deps.observationManager.record({threadId:e,traceId:t,type:"PLAN",content:{plan:r.plan,todoList:r.todoList,rawOutput:n},metadata:{timestamp:Date.now()}}),await this.deps.observationManager.record({threadId:e,traceId:t,type:"PLAN_UPDATE",content:{todoList:r.todoList},metadata:{timestamp:Date.now()}});}async _performPlanning(e,t,r,n,o,s){a.debug(`[${s}] Stage 3: Planning`);let i=n.map(p=>({name:p.name,description:p.description,inputSchema:p.inputSchema})),l=[{role:"system",content:`You are a planning assistant.
3
3
  [BEGIN_CUSTOM_GUIDANCE]
4
4
  ${t}
5
5
  [END_CUSTOM_GUIDANCE]
@@ -34,14 +34,14 @@ Output the updated JSON object (title, intent, plan, todoList). Ensure you prese
34
34
  `},...r,{role:"user",content:`User Query: ${e.query}
35
35
 
36
36
  Available Tools:
37
- ${JSON.stringify(c,null,2)}`}];return this._callPlanningLLM(p,e,s,i)}async _callPlanningLLM(e,t,r,n){let o={threadId:t.threadId,traceId:n,userId:t.userId,sessionId:t.sessionId,stream:true,callContext:"AGENT_THOUGHT",requiredCapabilities:["reasoning"],providerConfig:r,...t.options?.llmParams??{}},s="",i,c=null;try{await this.deps.observationManager.record({threadId:t.threadId,traceId:n,type:"PLAN",content:{message:"Generating/Refining Plan..."},metadata:{timestamp:Date.now()}});let l=await this.deps.reasoningEngine.call(e,o);await this.deps.observationManager.record({threadId:t.threadId,traceId:n,type:"LLM_STREAM_START",content:{phase:"planning"},metadata:{timestamp:Date.now()}});for await(let u of l)this.deps.uiSystem.getLLMStreamSocket().notify(u,{targetThreadId:u.threadId,targetSessionId:u.sessionId}),u.type==="TOKEN"?s+=u.data:u.type==="METADATA"?i=u.data:u.type==="ERROR"&&(c=u.data);if(c)throw c;return {output:await this.deps.outputParser.parsePlanningOutput(s),metadata:i,rawText:s}}catch(l){throw new d(`Planning failed: ${l.message}`,"PLANNING_FAILED",l)}}async _executeTodoList(e,t,r,n,o){a.debug(`[${o}] Starting Execution Loop`);let s=0,i=0,c={},l=true,p=20,u=0;for(;l&&u<p;){u++;let f=t.todoList.find(A=>A.status!=="pending"?false:!A.dependencies||A.dependencies.length===0?true:A.dependencies.every(E=>{let M=t.todoList.find(m=>m.id===E);return M&&M.status==="completed"}));if(!f){a.debug(`[${o}] No runnable pending items found.`),l=false;break}a.debug(`[${o}] Executing Item: ${f.id}`),t.currentStepId=f.id,f.status="in_progress",f.updatedTimestamp=Date.now(),await this._saveState(e.threadId,t),await this.deps.observationManager.record({threadId:e.threadId,traceId:o,type:"ITEM_STATUS_CHANGE",content:{itemId:f.id,status:"in_progress"},parentId:f.id,metadata:{timestamp:Date.now()}});try{let A=await this._processTodoItem(e,f,t,r,n,o);s+=A.llmCalls,i+=A.toolCalls,A.metadata&&(c={...c,...A.metadata}),A.status==="success"?(f.status="completed",f.result=A.output):A.status==="wait"?f.status="waiting":(f.status="failed",l=!1);}catch(A){a.error(`[${o}] Error executing item ${f.id}:`,A),f.status="failed",l=false;}f.updatedTimestamp=Date.now(),await this._saveState(e.threadId,t),await this.deps.observationManager.record({threadId:e.threadId,traceId:o,type:"ITEM_STATUS_CHANGE",content:{itemId:f.id,status:f.status},parentId:f.id,metadata:{timestamp:Date.now()}});}return {llmCalls:s,toolCalls:i,llmMetadata:c}}async _processTodoItem(e,t,r,n,o,s){let i=0,c=0,l={},p=n.map(I=>({name:I.name,description:I.description,inputSchema:I.inputSchema})),u={name:"delegate_to_agent",description:"Delegates a specific task to another agent.",inputSchema:{type:"object",properties:{agentId:{type:"string"},taskType:{type:"string"},input:{type:"object"},instructions:{type:"string"}},required:["agentId","taskType","input","instructions"]}},f=[...p,u],A=r.todoList.filter(I=>I.status==="completed").map(I=>`Item ${I.id}: ${I.description}
38
- Result: ${JSON.stringify(I.result)}`).join(`
37
+ ${JSON.stringify(c,null,2)}`}];return this._callPlanningLLM(p,e,s,i)}async _callPlanningLLM(e,t,r,n){let o={threadId:t.threadId,traceId:n,userId:t.userId,sessionId:t.sessionId,stream:true,callContext:"AGENT_THOUGHT",requiredCapabilities:["reasoning"],providerConfig:r,...t.options?.llmParams??{}},s="",i,c=null;try{await this.deps.observationManager.record({threadId:t.threadId,traceId:n,type:"PLAN",content:{message:"Generating/Refining Plan..."},metadata:{timestamp:Date.now()}});let l=await this.deps.reasoningEngine.call(e,o);await this.deps.observationManager.record({threadId:t.threadId,traceId:n,type:"LLM_STREAM_START",content:{phase:"planning"},metadata:{timestamp:Date.now()}});for await(let u of l)this.deps.uiSystem.getLLMStreamSocket().notify(u,{targetThreadId:u.threadId,targetSessionId:u.sessionId}),u.type==="TOKEN"?s+=u.data:u.type==="METADATA"?i=u.data:u.type==="ERROR"&&(c=u.data);if(c)throw c;return {output:await this.deps.outputParser.parsePlanningOutput(s),metadata:i,rawText:s}}catch(l){throw new d(`Planning failed: ${l.message}`,"PLANNING_FAILED",l)}}async _executeTodoList(e,t,r,n,o){a.debug(`[${o}] Starting Execution Loop`);let s=0,i=0,c={},l=true,p=20,u=0;for(;l&&u<p;){u++;let m=t.todoList.find(I=>I.status!=="pending"?false:!I.dependencies||I.dependencies.length===0?true:I.dependencies.every(v=>{let C=t.todoList.find(h=>h.id===v);return C&&C.status==="completed"}));if(!m){a.debug(`[${o}] No runnable pending items found.`),l=false;break}a.debug(`[${o}] Executing Item: ${m.id}`),t.currentStepId=m.id,m.status="in_progress",m.updatedTimestamp=Date.now(),await this._saveState(e.threadId,t),await this.deps.observationManager.record({threadId:e.threadId,traceId:o,type:"ITEM_STATUS_CHANGE",content:{itemId:m.id,status:"in_progress"},parentId:m.id,metadata:{timestamp:Date.now()}});try{let I=await this._processTodoItem(e,m,t,r,n,o);s+=I.llmCalls,i+=I.toolCalls,I.metadata&&(c={...c,...I.metadata}),I.status==="success"?(m.status="completed",m.result=I.output):I.status==="wait"?m.status="waiting":(m.status="failed",l=!1);}catch(I){a.error(`[${o}] Error executing item ${m.id}:`,I),m.status="failed",l=false;}m.updatedTimestamp=Date.now(),await this._saveState(e.threadId,t),await this.deps.observationManager.record({threadId:e.threadId,traceId:o,type:"ITEM_STATUS_CHANGE",content:{itemId:m.id,status:m.status},parentId:m.id,metadata:{timestamp:Date.now()}});}return {llmCalls:s,toolCalls:i,llmMetadata:c}}async _processTodoItem(e,t,r,n,o,s){let i=0,c=0,l={},p=n.map(T=>({name:T.name,description:T.description,inputSchema:T.inputSchema})),u={name:"delegate_to_agent",description:"Delegates a specific task to another agent.",inputSchema:{type:"object",properties:{agentId:{type:"string"},taskType:{type:"string"},input:{type:"object"},instructions:{type:"string"}},required:["agentId","taskType","input","instructions"]}},m=[...p,u],I=r.todoList.filter(T=>T.status==="completed").map(T=>`Item ${T.id}: ${T.description}
38
+ Result: ${JSON.stringify(T.result)}`).join(`
39
39
 
40
- `),M=[{role:"system",content:`You are executing a step in a larger plan.
40
+ `),C=[{role:"system",content:`You are executing a step in a larger plan.
41
41
  Current Task: ${t.description}
42
42
  Context: ${e.query}
43
43
  Previous Steps Results:
44
- ${A}
44
+ ${I}
45
45
  Instructions:
46
46
  1. Use tools if necessary.
47
47
  2. If you need to delegate to another agent, use 'delegate_to_agent'.
@@ -50,15 +50,15 @@ Instructions:
50
50
  `},{role:"user",content:`Execute the task: ${t.description}
51
51
 
52
52
  Available Tools:
53
- ${JSON.stringify(f)}`}],m=5,w=0,S=false,N,C="success";for(;!S&&w<m;){w++;let I={threadId:e.threadId,traceId:s,userId:e.userId,sessionId:e.sessionId,stream:true,callContext:"AGENT_THOUGHT",requiredCapabilities:["reasoning"],providerConfig:o,...e.options?.llmParams??{}},L="",R=null,y;await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"LLM_STREAM_START",content:{phase:`execution_item_${t.id}_iter_${w}`},parentId:t.id,metadata:{timestamp:Date.now()}});let O=await this.deps.reasoningEngine.call(M,I);i++;for await(let T of O)this.deps.uiSystem.getLLMStreamSocket().notify(T,{targetThreadId:T.threadId,targetSessionId:T.sessionId}),T.type==="TOKEN"?(L+=T.data,T.tokenType&&String(T.tokenType).includes("THINKING")&&await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"THOUGHTS",content:{text:T.data},parentId:t.id,metadata:{phase:"execution",tokenType:T.tokenType,timestamp:Date.now()}}).catch(D=>a.error(`[${s}] Failed to record THOUGHTS observation:`,D))):T.type==="METADATA"?y=T.data:T.type==="ERROR"&&(R=T.data);if(R)throw R;y&&(l={...l,...y});let h=await this.deps.outputParser.parseExecutionOutput(L);if(M.push({role:"assistant",content:L}),h.updatedPlan&&h.updatedPlan.todoList&&(a.info(`[${s}] Plan update received from execution step.`),r.todoList=h.updatedPlan.todoList,h.updatedPlan.intent&&(r.intent=h.updatedPlan.intent),h.updatedPlan.plan&&(r.plan=h.updatedPlan.plan),await this._saveState(e.threadId,r),await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"PLAN_UPDATE",content:{todoList:r.todoList},metadata:{timestamp:Date.now()}})),h.toolCalls&&h.toolCalls.length>0){let T=h.toolCalls.filter(x=>x.toolName==="delegate_to_agent"),D=h.toolCalls.filter(x=>x.toolName!=="delegate_to_agent"),k=[];if(T.length>0&&(k=await this._delegateA2ATasks({toolCalls:T},e.threadId,s),(await this._waitForA2ACompletion(k,e.threadId,s)).forEach(v=>{M.push({role:"tool_result",content:JSON.stringify(v.result||{error:"Task failed"}),name:"delegate_to_agent",tool_call_id:v.taskId});})),D.length>0){let x=await this.deps.toolSystem.executeTools(D,e.threadId,s);c+=x.length,await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"TOOL_EXECUTION",content:{toolResults:x},parentId:t.id,metadata:{timestamp:Date.now()}}),x.forEach(v=>{M.push({role:"tool_result",content:JSON.stringify(v.output||v.error),name:v.toolName,tool_call_id:v.callId});});}}else S=true,N=h.content;}return {status:C,output:N,llmCalls:i,toolCalls:c,metadata:l}}async _performSynthesis(e,t,r,n,o,s,i){a.debug(`[${s}] Stage 6: Synthesis`);let c=n.todoList.filter(I=>I.status==="completed"),l=n.todoList.filter(I=>I.status==="failed"),p=`
53
+ ${JSON.stringify(m)}`}],h=5,R=0,O=false,x,P="success";for(;!O&&R<h;){R++;let T={threadId:e.threadId,traceId:s,userId:e.userId,sessionId:e.sessionId,stream:true,callContext:"AGENT_THOUGHT",requiredCapabilities:["reasoning"],providerConfig:o,...e.options?.llmParams??{}},D="",k=null,_;await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"LLM_STREAM_START",content:{phase:`execution_item_${t.id}_iter_${R}`},parentId:t.id,metadata:{timestamp:Date.now()}});let w=await this.deps.reasoningEngine.call(C,T);i++;for await(let A of w)this.deps.uiSystem.getLLMStreamSocket().notify(A,{targetThreadId:A.threadId,targetSessionId:A.sessionId}),A.type==="TOKEN"?(D+=A.data,A.tokenType&&String(A.tokenType).includes("THINKING")&&await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"THOUGHTS",content:{text:A.data},parentId:t.id,metadata:{phase:"execution",tokenType:A.tokenType,timestamp:Date.now()}}).catch(M=>a.error(`[${s}] Failed to record THOUGHTS observation:`,M))):A.type==="METADATA"?_=A.data:A.type==="ERROR"&&(k=A.data);if(k)throw k;_&&(l={...l,..._});let f=await this.deps.outputParser.parseExecutionOutput(D);if(C.push({role:"assistant",content:D}),f.updatedPlan&&f.updatedPlan.todoList&&(a.info(`[${s}] Plan update received from execution step.`),r.todoList=f.updatedPlan.todoList,f.updatedPlan.intent&&(r.intent=f.updatedPlan.intent),f.updatedPlan.plan&&(r.plan=f.updatedPlan.plan),await this._saveState(e.threadId,r),await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"PLAN_UPDATE",content:{todoList:r.todoList},metadata:{timestamp:Date.now()}})),f.toolCalls&&f.toolCalls.length>0){let A=f.toolCalls.filter(y=>y.toolName==="delegate_to_agent"),M=f.toolCalls.filter(y=>y.toolName!=="delegate_to_agent"),N=[];if(A.length>0&&(N=await this._delegateA2ATasks({toolCalls:A},e.threadId,s),(await this._waitForA2ACompletion(N,e.threadId,s)).forEach(S=>{C.push({role:"tool_result",content:JSON.stringify(S.result||{error:"Task failed"}),name:"delegate_to_agent",tool_call_id:S.taskId});})),M.length>0){let y=await this.deps.toolSystem.executeTools(M,e.threadId,s);c+=y.length,await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"TOOL_EXECUTION",content:{toolResults:y},parentId:t.id,metadata:{timestamp:Date.now()}}),y.forEach(S=>{C.push({role:"tool_result",content:JSON.stringify(S.output||S.error),name:S.toolName,tool_call_id:S.callId});});}}else O=true,x=f.content;}return {status:P,output:x,llmCalls:i,toolCalls:c,metadata:l}}async _performSynthesis(e,t,r,n,o,s,i){a.debug(`[${s}] Stage 6: Synthesis`);let c=n.todoList.filter(T=>T.status==="completed"),l=n.todoList.filter(T=>T.status==="failed"),p=`
54
54
  Completed Tasks:
55
- ${c.map(I=>`- ${I.description}: ${JSON.stringify(I.result).substring(0,200)}...`).join(`
55
+ ${c.map(T=>`- ${T.description}: ${(JSON.stringify(T.result)??"null").substring(0,200)}...`).join(`
56
56
  `)}
57
57
 
58
58
  Failed Tasks:
59
- ${l.map(I=>`- ${I.description}`).join(`
59
+ ${l.map(T=>`- ${T.description}`).join(`
60
60
  `)}
61
- `,f=[{role:"system",content:`You are ${i.name}.
61
+ `,m=[{role:"system",content:`You are ${i.name}.
62
62
  [BEGIN_CUSTOM_GUIDANCE]
63
63
  ${t}
64
64
  [END_CUSTOM_GUIDANCE]
@@ -68,36 +68,36 @@ Format your response with <mainContent>...</mainContent> for the user message an
68
68
  `},...r,{role:"user",content:`User Query: ${e.query}
69
69
 
70
70
  Work Summary:
71
- ${p}`}],A={threadId:e.threadId,traceId:s,userId:e.userId,sessionId:e.sessionId,stream:true,callContext:"FINAL_SYNTHESIS",requiredCapabilities:["text"],providerConfig:o,...e.options?.llmParams??{}},E="",M,m=await this.deps.reasoningEngine.call(f,A);await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"LLM_STREAM_START",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}});for await(let I of m)this.deps.uiSystem.getLLMStreamSocket().notify(I,{targetThreadId:I.threadId,targetSessionId:I.sessionId}),I.type==="TOKEN"?(I.tokenType==="FINAL_SYNTHESIS_LLM_RESPONSE"||I.tokenType==="LLM_RESPONSE")&&(E+=I.data):I.type==="METADATA"&&(M=I.data);let w=E,S,N=/```json\s*([\s\S]*?)\s*```$/,C=E.match(N);if(C&&C[1]){w=E.replace(N,"").trim();try{S=JSON.parse(C[1]);}catch{}}return {finalResponseContent:w,synthesisMetadata:M,uiMetadata:S}}async _loadConfiguration(e,t){a.debug(`[${t}] Stage 1: Initiation & Config`);let r=await this.deps.stateManager.loadThreadContext(e.threadId,e.userId);if(!r)throw new d(`Thread context not found for threadId: ${e.threadId}`,"THREAD_NOT_FOUND");let n=e.options?.persona,o=await this.deps.stateManager.getThreadConfigValue(e.threadId,"persona"),s=this.persona,i={name:n?.name||o?.name||s.name,prompts:{planning:n?.prompts?.planning||o?.prompts?.planning||s.prompts.planning,synthesis:n?.prompts?.synthesis||o?.prompts?.synthesis||s.prompts.synthesis}},c=await this.deps.systemPromptResolver.resolve({base:i.prompts.planning||"",thread:await this.deps.stateManager.getThreadConfigValue(e.threadId,"systemPrompt"),call:e.options?.systemPrompt},t),l=await this.deps.systemPromptResolver.resolve({base:i.prompts.synthesis||"",thread:await this.deps.stateManager.getThreadConfigValue(e.threadId,"systemPrompt"),call:e.options?.systemPrompt},t),p=e.options?.providerConfig||r.config.providerConfig;if(!p)throw new d(`RuntimeProviderConfig is missing in AgentProps.options or ThreadConfig for threadId: ${e.threadId}`,"INVALID_CONFIG");return {threadContext:r,planningSystemPrompt:c,synthesisSystemPrompt:l,runtimeProviderConfig:p,finalPersona:i}}async _gatherHistory(e,t){a.debug(`[${t.threadId||e}] Stage 2: Gathering History`);let r={limit:t.config.historyLimit},n=await this.deps.conversationManager.getMessages(e,r);return this.formatHistoryForPrompt(n)}async _gatherTools(e){return a.debug(`[${e}] Stage 2: Gathering Tools`),await this.deps.toolRegistry.getAvailableTools({enabledForThreadId:e})}async _delegateA2ATasks(e,t,r){a.debug(`[${r}] Stage 4: A2A Task Delegation`);let n=e.toolCalls?.filter(s=>s.toolName==="delegate_to_agent")??[];if(n.length===0)return a.debug(`[${r}] No A2A delegation calls in the plan.`),[];if(!this.deps.taskDelegationService||!this.deps.agentDiscoveryService)return a.warn(`[${r}] A2A services not available. Skipping delegation.`),[];let o=[];for(let s of n)try{let i=s.arguments,{agentId:c,taskType:l,input:p,instructions:u}=i,A=(await this.deps.agentDiscoveryService.discoverAgents(r)).find(w=>w.agentId===c);if(!A)throw new Error(`Agent with ID "${c}" not found during delegation.`);let E=Date.now(),M={taskId:s.callId,threadId:t,status:"PENDING",payload:{taskType:l,input:p,instructions:u,parameters:{threadId:t,traceId:r}},sourceAgent:{agentId:"pes-agent",agentName:"PES Agent",agentType:"orchestrator"},targetAgent:A,priority:"MEDIUM",metadata:{createdAt:E,updatedAt:E,initiatedBy:t,correlationId:r,retryCount:0,maxRetries:3,timeoutMs:6e4,tags:["delegated",l]}};await this.deps.a2aTaskRepository.createTask(M);let m=await this.deps.taskDelegationService.delegateTask(M,r);m&&o.push(m);}catch(i){a.error(`[${r}] Failed to process and delegate A2A task for call ${s.callId}:`,i),await this.deps.observationManager.record({threadId:t,traceId:r,type:"ERROR",content:{phase:"a2a_delegation",error:`Delegation for call ${s.callId} failed: ${i.message}`},metadata:{timestamp:Date.now()}});}return a.info(`[${r}] Successfully initiated delegation for ${o.length}/${n.length} A2A task(s).`),o}async _waitForA2ACompletion(e,t,r,n=3e4,o=2e3){if(e.length===0)return e;a.debug(`[${r}] Waiting for ${e.length} A2A task(s) to complete (timeout: ${n}ms)`);let s=Date.now(),i=[...e];try{for(;Date.now()-s<n;){let c=i.filter(l=>l.status!=="COMPLETED"&&l.status!=="FAILED"&&l.status!=="CANCELLED");if(c.length===0){a.info(`[${r}] All A2A tasks completed successfully`);break}a.debug(`[${r}] Waiting for ${c.length} A2A task(s) to complete...`);for(let l=0;l<i.length;l++){let p=i[l];if(!(p.status==="COMPLETED"||p.status==="FAILED"||p.status==="CANCELLED"))try{let u=await this.deps.a2aTaskRepository.getTask(p.taskId);u&&(i[l]=u);}catch(u){a.warn(`[${r}] Failed to get updated status for task ${p.taskId}:`,u);}}await new Promise(l=>setTimeout(l,o));}return i}catch(c){return a.error(`[${r}] Error during A2A task waiting:`,c),i}}async _finalize(e,t,r,n){a.debug(`[${r}] Stage 7: Finalization`);let o=Date.now(),s={messageId:X(),threadId:e.threadId,role:"AI",content:t,timestamp:o,metadata:{traceId:r}};return await this.deps.conversationManager.addMessages(e.threadId,[s]),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"FINAL_RESPONSE",content:{message:s,uiMetadata:n},metadata:{timestamp:o}}),s}formatHistoryForPrompt(e){return e.map(t=>{let r;switch(t.role){case "USER":r="user";break;case "AI":r="assistant";break;case "SYSTEM":r="system";break;case "TOOL":r="tool";break;default:r="user";}return {role:r,content:t.content}}).filter(t=>t.content)}};var de=class{constructor(){this.storage=new Map;}async init(e){return Promise.resolve()}async get(e,t){let r=this.storage.get(e);if(!r)return null;let n=r.get(t);return n?JSON.parse(JSON.stringify(n)):null}async set(e,t,r){return this.storage.has(e)||this.storage.set(e,new Map),this.storage.get(e).set(t,JSON.parse(JSON.stringify(r))),Promise.resolve()}async delete(e,t){let r=this.storage.get(e);return r&&r.delete(t),Promise.resolve()}async query(e,t){let r=this.storage.get(e);if(!r)return [];let n=Array.from(r.values());return t.filter&&(n=n.filter(o=>{for(let s in t.filter)if(t.filter.hasOwnProperty(s)&&o[s]!==t.filter[s])return false;return true})),typeof t.limit=="number"&&t.limit>=0&&(n=n.slice(0,t.limit)),JSON.parse(JSON.stringify(n))}async clearCollection(e){return this.storage.delete(e),Promise.resolve()}async clearAll(){return this.storage.clear(),Promise.resolve()}};var At="ART_Framework_DB",St=1,pe=class{constructor(e){this.db=null;this.initPromise=null;this.dbName=e.dbName||At,this.dbVersion=e.dbVersion||St,this.requiredObjectStores=new Set(["conversations","observations","state","a2a_tasks",...e.objectStores||[]]);}async init(){return this.initPromise?this.initPromise:(this.initPromise=new Promise((e,t)=>{if(!("indexedDB"in window))return a.error("IndexedDBStorageAdapter: IndexedDB not supported in this browser."),t(new Error("IndexedDB not supported"));let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=n=>{a.error(`IndexedDBStorageAdapter: Database error: ${r.error}`,n),t(new Error(`IndexedDB error: ${r.error?.message}`));},r.onsuccess=n=>{this.db=n.target.result,a.info(`IndexedDBStorageAdapter: Database '${this.dbName}' opened successfully (Version: ${this.db.version}).`);let o=new Set(Array.from(this.db.objectStoreNames)),s=[...this.requiredObjectStores].filter(i=>!o.has(i));s.length>0&&a.warn(`IndexedDBStorageAdapter: The following required object stores were not found after opening DB version ${this.db.version}: ${s.join(", ")}. This might happen if the DB version wasn't incremented after adding stores.`),this.db.onerror=i=>{a.error("IndexedDBStorageAdapter: Generic database error:",i);},e();},r.onupgradeneeded=n=>{if(a.info(`IndexedDBStorageAdapter: Upgrading database '${this.dbName}' from version ${n.oldVersion} to ${n.newVersion}...`),this.db=n.target.result,!n.target.transaction){a.error("IndexedDBStorageAdapter: Upgrade transaction is null!"),t(new Error("Upgrade transaction failed"));return}let s=new Set(Array.from(this.db.objectStoreNames));this.requiredObjectStores.forEach(i=>{s.has(i)||(a.info(`IndexedDBStorageAdapter: Creating object store '${i}'...`),this.db?.createObjectStore(i,{keyPath:"id"}));}),a.info("IndexedDBStorageAdapter: Database upgrade complete.");},r.onblocked=n=>{a.warn(`IndexedDBStorageAdapter: Database open request blocked for '${this.dbName}'. Please close other tabs/connections using an older version of this database.`,n),t(new Error(`IndexedDB open blocked for ${this.dbName}. Close other connections.`));};}),this.initPromise)}getTransaction(e,t){if(!this.db)throw new Error("IndexedDBStorageAdapter: Database not initialized. Ensure init() was called and awaited.");return (Array.isArray(e)?e:[e]).forEach(n=>{if(!this.db?.objectStoreNames.contains(n))throw new Error(`IndexedDBStorageAdapter: Object store "${n}" does not exist in the database.`)}),this.db.transaction(e,t)}async get(e,t){return await this.init(),new Promise((r,n)=>{try{let i=this.getTransaction(e,"readonly").objectStore(e).get(t);i.onsuccess=()=>{r(i.result?{...i.result}:null);},i.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error getting item '${t}' from '${e}':`,i.error),n(new Error(`Failed to get item: ${i.error?.message}`));};}catch(o){n(o);}})}async set(e,t,r){let n=r;return typeof n.id>"u"?Promise.reject(new Error(`IndexedDBStorageAdapter: Data for collection '${e}' must have an 'id' property matching the keyPath.`)):(n.id!==t&&a.warn(`IndexedDBStorageAdapter: Provided id ('${t}') and data.id ('${n.id}') mismatch for collection '${e}'. Using data.id as the key.`),await this.init(),new Promise((o,s)=>{try{let i=structuredClone(r),c=this.getTransaction(e,"readwrite"),p=c.objectStore(e).put(i);p.onsuccess=()=>{o();},p.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error setting item with id '${n.id}' in '${e}':`,p.error),s(new Error(`Failed to set item: ${p.error?.message}`));},c.oncomplete=()=>{},c.onerror=u=>{a.error(`IndexedDBStorageAdapter: Transaction error setting item with id '${n.id}' in '${e}':`,c.error,u),s(new Error(`Transaction failed: ${c.error?.message}`));};}catch(i){s(i);}}))}async delete(e,t){return await this.init(),new Promise((r,n)=>{try{let o=this.getTransaction(e,"readwrite"),i=o.objectStore(e).delete(t);i.onsuccess=()=>{r();},i.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error deleting item '${t}' from '${e}':`,i.error),n(new Error(`Failed to delete item: ${i.error?.message}`));},o.onerror=c=>{a.error(`IndexedDBStorageAdapter: Transaction error deleting item '${t}' from '${e}':`,o.error,c),n(new Error(`Transaction failed: ${o.error?.message}`));};}catch(o){n(o);}})}async query(e,t){return await this.init(),new Promise((r,n)=>{try{let i=this.getTransaction(e,"readonly").objectStore(e).getAll();i.onsuccess=()=>{let c=i.result||[];if(t.filter&&(c=c.filter(u=>{for(let f in t.filter)if(t.filter.hasOwnProperty(f)&&u[f]!==t.filter[f])return !1;return !0})),t.sort){let u=Object.keys(t.sort)[0],f=t.sort[u];u&&c.sort((A,E)=>{let M=A[u],m=E[u];return M<m?f==="asc"?-1:1:M>m?f==="asc"?1:-1:0});}let l=t.skip||0,p=t.limit??1/0;c=c.slice(l,l+p),r(c.map(u=>({...u})));},i.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error querying collection '${e}':`,i.error),n(new Error(`Failed to query collection: ${i.error?.message}`));};}catch(o){n(o);}})}async clearCollection(e){return await this.init(),new Promise((t,r)=>{try{let n=this.getTransaction(e,"readwrite"),s=n.objectStore(e).clear();s.onsuccess=()=>{t();},s.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error clearing collection '${e}':`,s.error),r(new Error(`Failed to clear collection: ${s.error?.message}`));},n.onerror=i=>{a.error(`IndexedDBStorageAdapter: Transaction error clearing collection '${e}':`,n.error,i),r(new Error(`Transaction failed: ${n.error?.message}`));};}catch(n){r(n);}})}async clearAll(){if(await this.init(),!this.db)throw new Error("Database not initialized.");let e=Array.from(this.db.objectStoreNames);return e.length===0?Promise.resolve():new Promise((t,r)=>{try{let n=this.getTransaction(e,"readwrite"),o=0,s=e.length;e.forEach(i=>{let c=n.objectStore(i).clear();c.onsuccess=()=>{o++;},c.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error clearing object store '${i}':`,c.error);};}),n.oncomplete=()=>{a.info("IndexedDBStorageAdapter: All object stores cleared successfully."),t();},n.onerror=i=>{a.error("IndexedDBStorageAdapter: Transaction error during clearAll:",n.error,i),r(new Error(`Failed to clear all stores: ${n.error?.message}`));};}catch(n){r(n);}})}};var Re=class{constructor(e){this.collectionName="conversations";if(!e)throw new Error("ConversationRepository requires a valid StorageAdapter instance.");this.adapter=e;}async addMessages(e,t){if(!t||t.length===0)return Promise.resolve();let r=t.map(n=>{n.threadId!==e&&console.warn(`ConversationRepository: Message ${n.messageId} has mismatching threadId (${n.threadId}) for repository operation on thread ${e}.`);let o={...n,id:n.messageId};return this.adapter.set(this.collectionName,o.id,o)});await Promise.all(r);}async getMessages(e,t){let n=await this.adapter.query(this.collectionName,{filter:{threadId:e}});return n.sort((s,i)=>s.timestamp-i.timestamp),t?.beforeTimestamp!==void 0&&(n=n.filter(s=>s.timestamp<t.beforeTimestamp)),t?.afterTimestamp!==void 0&&(n=n.filter(s=>s.timestamp>t.afterTimestamp)),t?.limit!==void 0&&t.limit>0&&(n=n.slice(-t.limit)),n.map(({id:s,...i})=>i)}};var Oe=class{constructor(e){this.collectionName="observations";if(!e)throw new Error("ObservationRepository requires a valid StorageAdapter instance.");this.adapter=e;}async addObservation(e){if(typeof e.id>"u")return Promise.reject(new Error("ObservationRepository: Observation must have an 'id' property."));await this.adapter.set(this.collectionName,e.id,e);}async getObservations(e,t){let n=await this.adapter.query(this.collectionName,{filter:{threadId:e}});if(n.sort((o,s)=>o.timestamp-s.timestamp),t?.types&&t.types.length>0){let o=new Set(t.types);n=n.filter(s=>o.has(s.type));}return t?.beforeTimestamp!==void 0&&(n=n.filter(o=>o.timestamp<t.beforeTimestamp)),t?.afterTimestamp!==void 0&&(n=n.filter(o=>o.timestamp>t.afterTimestamp)),n}};var we=class{constructor(e){this.collectionName="state";if(!e)throw new Error("StateRepository requires a valid StorageAdapter instance.");this.adapter=e;}async getThreadContext(e){let t=await this.adapter.get(this.collectionName,e);if(!t)return null;let r={...t};return delete r.id,r}async setThreadContext(e,t){if(!t||typeof t.config>"u")return Promise.reject(new Error("StateRepository: ThreadContext must contain a 'config' property."));let r={...t,id:e};await this.adapter.set(this.collectionName,e,r);}async getThreadConfig(e){return (await this.getThreadContext(e))?.config??null}async setThreadConfig(e,t){let r=await this.getThreadContext(e),n={config:t,state:r?.state??null};await this.setThreadContext(e,n);}async getAgentState(e){return (await this.getThreadContext(e))?.state??null}async setAgentState(e,t){let r=await this.getThreadContext(e);if(!r||!r.config)return Promise.reject(new Error(`StateRepository: Cannot set AgentState for thread '${e}' because no ThreadConfig exists. Set config first.`));let n={config:r.config,state:t};await this.setThreadContext(e,n);}};var ke=class{constructor(e){this.collectionName="a2a_tasks";if(!e)throw new Error("TaskStatusRepository requires a valid StorageAdapter instance.");this.adapter=e;}async createTask(e){if(!e||!e.taskId)throw new d("Task must have a valid taskId","VALIDATION_ERROR");if(await this.adapter.get(this.collectionName,e.taskId))throw new d(`Task with ID '${e.taskId}' already exists`,"DUPLICATE_TASK_ID");let r={...e,id:e.taskId};await this.adapter.set(this.collectionName,e.taskId,r);}async getTask(e){if(!e)throw new d("TaskId is required","VALIDATION_ERROR");try{let t=await this.adapter.get(this.collectionName,e);if(!t)return null;let r={...t};return delete r.id,r}catch(t){throw new d(`Failed to retrieve task '${e}': ${t}`,"REPOSITORY_ERROR")}}async updateTask(e,t){if(!e)throw new d("TaskId is required","VALIDATION_ERROR");if(!t||Object.keys(t).length===0)throw new d("Updates object cannot be empty","VALIDATION_ERROR");try{let r=await this.adapter.get(this.collectionName,e);if(!r)throw new d(`Task with ID '${e}' not found`,"TASK_NOT_FOUND");let n={...r,...t,taskId:e,id:e};t.metadata&&(n.metadata={...r.metadata,...t.metadata,lastUpdated:Date.now()}),await this.adapter.set(this.collectionName,e,n);}catch(r){throw r instanceof d?r:new d(`Failed to update task '${e}': ${r}`,"REPOSITORY_ERROR")}}async deleteTask(e){if(!e)throw new d("TaskId is required","VALIDATION_ERROR");try{if(!await this.adapter.get(this.collectionName,e))throw new d(`Task with ID '${e}' not found`,"TASK_NOT_FOUND");await this.adapter.delete(this.collectionName,e);}catch(t){throw t instanceof d?t:new d(`Failed to delete task '${e}': ${t}`,"REPOSITORY_ERROR")}}async getTasksByThread(e,t){if(!e)throw new d("ThreadId is required","VALIDATION_ERROR");try{let n=await this.adapter.query(this.collectionName,{filter:{threadId:e}});if(t){if(t.status){let o=Array.isArray(t.status)?t.status:[t.status];n=n.filter(s=>o.includes(s.status));}t.priority&&(n=n.filter(o=>o.priority===t.priority)),t.assignedAgentId&&(n=n.filter(o=>o.targetAgent?.agentId===t.assignedAgentId));}return n.sort((o,s)=>(s.metadata?.createdAt||0)-(o.metadata?.createdAt||0)),this._removeIdField(n)}catch(r){throw new d(`Failed to get tasks for thread '${e}': ${r}`,"REPOSITORY_ERROR")}}async getTasksByAgent(e,t){if(!e)throw new d("AgentId is required","VALIDATION_ERROR");try{let n=(await this.adapter.query(this.collectionName,{filter:{}})).filter(o=>o.targetAgent?.agentId===e);if(t){if(t.status){let o=Array.isArray(t.status)?t.status:[t.status];n=n.filter(s=>o.includes(s.status));}t.priority&&(n=n.filter(o=>o.priority===t.priority));}return n.sort((o,s)=>(s.metadata?.createdAt||0)-(o.metadata?.createdAt||0)),this._removeIdField(n)}catch(r){throw new d(`Failed to get tasks for agent '${e}': ${r}`,"REPOSITORY_ERROR")}}async getTasksByStatus(e,t){if(!e)throw new d("Status is required","VALIDATION_ERROR");try{let r=await this.adapter.query(this.collectionName,{filter:{}}),n=Array.isArray(e)?e:[e],o=r.filter(s=>n.includes(s.status));if(o.sort((s,i)=>(i.metadata?.createdAt||0)-(s.metadata?.createdAt||0)),t){let s=t.offset||0,i=t.limit;s>0&&(o=o.slice(s)),i&&i>0&&(o=o.slice(0,i));}return this._removeIdField(o)}catch(r){throw new d(`Failed to get tasks by status: ${r}`,"REPOSITORY_ERROR")}}_removeIdField(e){return e.map(t=>{let r={...t};return delete r.id,r})}};var be=class{constructor(e,t){this.repository=e,this.conversationSocket=t;}async addMessages(e,t){if(!e)return Promise.reject(new Error("ConversationManager: threadId cannot be empty."));if(!t||t.length===0)return Promise.resolve();await this.repository.addMessages(e,t),t.forEach(r=>{try{this.conversationSocket.notify(r,{targetThreadId:e});}catch(n){console.error(`ConversationManager: Failed to notify message ${r.messageId} via socket for thread ${e}`,n);}});}async getMessages(e,t){return e?await this.repository.getMessages(e,t):Promise.reject(new Error("ConversationManager: threadId cannot be empty."))}};function Me(g){if(g===null||typeof g!="object")return g;if(g instanceof Date)return new Date(g.getTime());if(Array.isArray(g))return g.map(t=>Me(t));let e={};for(let t in g)Object.prototype.hasOwnProperty.call(g,t)&&(e[t]=Me(g[t]));return e}var ue=class{constructor(e,t="explicit"){this.repository=e,this.strategy=t,this.contextCache=new Map;}async loadThreadContext(e,t){if(!e)throw new Error("StateManager: threadId cannot be empty for loadThreadContext.");if(this.strategy==="implicit"&&this.contextCache.has(e))return this.contextCache.get(e).context;let r=await this.repository.getThreadContext(e);if(!r)throw new Error(`StateManager: Thread context not found for threadId '${e}'. Application should call setThreadConfig first for new threads.`);if(this.strategy==="implicit"){let n=Me(r),o=n.state?JSON.stringify(n.state):null;return this.contextCache.set(e,{originalStateSnapshot:o,context:n}),n}else return r}async isToolEnabled(e,t){try{return (await this.loadThreadContext(e)).config?.enabledTools?.includes(t)??!1}catch(r){return console.warn(`StateManager: Could not check if tool '${t}' is enabled for thread '${e}' because context failed to load: ${r}`),false}}async getThreadConfigValue(e,t){let r=await this.loadThreadContext(e);if(r.config&&t in r.config)return r.config[t]}async saveStateIfModified(e){if(!e)throw new Error("StateManager: threadId cannot be empty for saveStateIfModified.");if(this.strategy==="explicit")return console.warn(`StateManager (explicit): saveStateIfModified called for thread ${e}. AgentState must be saved explicitly using setAgentState(). This method is a no-op for AgentState in explicit mode.`),Promise.resolve();let t=this.contextCache.get(e);if(!t)return console.warn(`StateManager (implicit): saveStateIfModified called for thread ${e}, but context was not loaded or cached in this StateManager instance for this cycle. State will not be saved implicitly.`),Promise.resolve();let r=t.context.state,n=r?JSON.stringify(r):null;return n!==t.originalStateSnapshot&&(r===null&&console.warn(`StateManager (implicit): AgentState for thread ${e} became null. Attempting to save null state.`),r!==null?(await this.repository.setAgentState(e,r),t.originalStateSnapshot=n):console.warn(`StateManager (implicit): AgentState for thread ${e} is null. Implicit save will not persist null state due to setAgentState constraints. Use setAgentState with a valid object to clear or update.`)),Promise.resolve()}async setThreadConfig(e,t){if(!e||!t)throw new Error("StateManager: threadId and config are required for setThreadConfig.");await this.repository.setThreadConfig(e,t),this.contextCache.has(e)&&this.contextCache.delete(e);}async setAgentState(e,t){if(!e)throw new Error("StateManager: threadId cannot be empty for setAgentState.");if(typeof t>"u"||t===null)throw new Error("StateManager: state cannot be undefined or null for setAgentState.");if(await this.repository.setAgentState(e,t),this.strategy==="implicit"){let r=this.contextCache.get(e);r&&(r.context.state=Me(t),r.originalStateSnapshot=JSON.stringify(t));}}async enableToolsForThread(e,t){if(!e)throw new Error("StateManager: threadId cannot be empty for enableToolsForThread.");if(!t||t.length===0)throw new Error("StateManager: toolNames cannot be empty for enableToolsForThread.");let r=await this.loadThreadContext(e);if(!r.config)throw new Error(`StateManager: No ThreadConfig found for threadId '${e}'. Cannot enable tools without existing configuration.`);let n=r.config.enabledTools||[],o=[...new Set([...n,...t])],s={...r.config,enabledTools:o};await this.setThreadConfig(e,s);}async disableToolsForThread(e,t){if(!e)throw new Error("StateManager: threadId cannot be empty for disableToolsForThread.");if(!t||t.length===0)throw new Error("StateManager: toolNames cannot be empty for disableToolsForThread.");let r=await this.loadThreadContext(e);if(!r.config)throw new Error(`StateManager: No ThreadConfig found for threadId '${e}'. Cannot disable tools without existing configuration.`);let o=(r.config.enabledTools||[]).filter(i=>!t.includes(i)),s={...r.config,enabledTools:o};await this.setThreadConfig(e,s);}async getEnabledToolsForThread(e){if(!e)throw new Error("StateManager: threadId cannot be empty for getEnabledToolsForThread.");return (await this.loadThreadContext(e)).config?.enabledTools||[]}clearCache(){this.contextCache.clear();}};var Ce=class{constructor(e,t){this.observationRepository=e,this.observationSocket=t;}async record(e){let t={...e,id:X(),timestamp:Date.now(),title:`${e.type} Recorded`};try{await this.observationRepository.addObservation(t),a.debug(`[ObservationManager] Notifying ObservationSocket for obsId: ${t.id}, type: ${t.type}`),this.observationSocket.notify(t,{targetThreadId:t.threadId}),a.debug(`[ObservationManager] ObservationSocket notified for obsId: ${t.id}`);}catch(r){throw console.error("Error recording observation:",r),r}}async getObservations(e,t){try{return await this.observationRepository.getObservations(e,t)}catch(r){throw console.error(`Error retrieving observations for thread ${e}:`,r),r}}};var ge=class{constructor(e){this.executors=new Map;this.stateManager=e,a.debug(`ToolRegistry initialized ${e?"with":"without"} StateManager.`);}async registerTool(e){if(!e||!e.schema||!e.schema.name)throw a.error("ToolRegistry: Attempted to register an invalid tool executor."),new Error("Invalid tool executor provided for registration.");let t=e.schema.name;this.executors.has(t)&&a.warn(`ToolRegistry: Overwriting existing tool registration for "${t}".`),this.executors.set(t,e),a.debug(`ToolRegistry: Registered tool "${t}".`);}async getToolExecutor(e){let t=this.executors.get(e);return t||a.debug(`ToolRegistry: Tool "${e}" not found.`),t}async getAvailableTools(e){let t=Array.from(this.executors.values()),r=t.map(n=>n.schema);if(e?.enabledForThreadId&&this.stateManager){let n=e.enabledForThreadId;a.debug(`ToolRegistry: Attempting to filter tools for threadId: ${n}`);try{let s=(await this.stateManager.loadThreadContext(n))?.config?.enabledTools;if(s&&Array.isArray(s)){a.debug(`ToolRegistry: Found enabled tools for thread ${n}: ${s.join(", ")}`);let c=t.filter(l=>s.includes(l.schema.name)).map(l=>l.schema);return a.debug(`ToolRegistry: Returning ${c.length} enabled tool schemas for thread ${n}.`),c}else a.warn(`ToolRegistry: No specific enabledTools found for thread ${n} or config missing. Returning all tools.`);}catch(o){a.error(`ToolRegistry: Error loading thread config for ${n}: ${o.message}. Returning all tools.`);}}else e?.enabledForThreadId&&!this.stateManager&&a.warn("ToolRegistry: Filtering by enabledForThreadId requested, but StateManager was not provided. Returning all tools.");return a.debug(`ToolRegistry: Returning all ${r.length} registered tool schemas.`),r}async clearAllTools(){this.executors.clear(),a.debug("ToolRegistry: Cleared all registered tools.");}async unregisterTool(e){this.executors.delete(e)&&a.debug(`ToolRegistry: Unregistered tool "${e}".`);}async unregisterTools(e){let t=0;for(let[r,n]of Array.from(this.executors.entries()))try{e(n.schema)&&(this.executors.delete(r),t++);}catch{}return t>0&&a.debug(`ToolRegistry: Unregistered ${t} tool(s) via predicate.`),t}};var _t=new It({allErrors:true}),He=new Map;function ct(g,e){let t=JSON.stringify(g),r;if(He.has(t))r=He.get(t),a.debug("Using cached JSON schema validator.");else try{r=_t.compile(g),He.set(t,r),a.debug("Compiled and cached new JSON schema validator.");}catch(o){return a.error(`Failed to compile JSON schema: ${o.message}`,{schema:g,error:o}),{isValid:false,errors:[{keyword:"compilation",instancePath:"",schemaPath:"",params:{},message:`Schema compilation failed: ${o.message}`}]}}return r(e)?{isValid:true,errors:null}:(a.warn("JSON schema validation failed.",{errors:r.errors,data:e}),{isValid:false,errors:r.errors||[]})}var Ne=class{constructor(e,t,r){if(!e)throw new Error("ToolSystem constructor requires a ToolRegistry instance.");if(!t)throw new Error("ToolSystem constructor requires a StateManager instance.");if(!r)throw new Error("ToolSystem constructor requires an ObservationManager instance.");this.toolRegistry=e,this.stateManager=t,this.observationManager=r,a.info("ToolSystem initialized.");}async executeTools(e,t,r){let n=[];a.debug(`ToolSystem executing ${e.length} tool calls for thread ${t}`,{traceId:r});for(let o of e){let s=null,i,c=o.toolName,l=o.callId;try{if(!await this.stateManager.isToolEnabled(t,c))throw new Error(`Tool "${c}" is not enabled for thread "${t}".`);if(i=await this.toolRegistry.getToolExecutor(c),!i)throw new Error(`Tool "${c}" not found in registry.`);let u=ct(i.schema.inputSchema,o.arguments);if(!u.isValid){let E=u.errors?.map(M=>`${M.instancePath||"input"} ${M.message}`).join(", ")||"Unknown validation error";throw new Error(`Invalid arguments for tool "${c}": ${E}`)}a.debug(`Executing tool "${c}" with callId "${l}"`,{args:o.arguments,threadId:t,traceId:r});let f={threadId:t,traceId:r};s={...await i.execute(o.arguments,f),callId:l,toolName:c},a.debug(`Tool "${c}" execution successful`,{callId:l,result:s.output,threadId:t,traceId:r});}catch(p){a.error(`Tool "${c}" execution failed for callId "${l}": ${p.message}`,{error:p,threadId:t,traceId:r}),s={callId:l,toolName:c,status:"error",error:p.message||"Unknown execution error"};}s?(this.observationManager.record({threadId:t,traceId:r,type:"TOOL_EXECUTION",content:s,metadata:{timestamp:Date.now(),callId:o.callId}}).catch(p=>a.error(`Failed to record TOOL_EXECUTION observation for callId ${o.callId}:`,p)),n.push(s)):a.error(`ToolSystem finished processing call ${o.callId} but result object was null.`);}return n}};function dt(g,e,t){switch(t||"append"){case "prepend":return `${e}
71
+ ${p}`}],I={threadId:e.threadId,traceId:s,userId:e.userId,sessionId:e.sessionId,stream:true,callContext:"FINAL_SYNTHESIS",requiredCapabilities:["text"],providerConfig:o,...e.options?.llmParams??{}},v="",C,h=await this.deps.reasoningEngine.call(m,I);await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"LLM_STREAM_START",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}});for await(let T of h)this.deps.uiSystem.getLLMStreamSocket().notify(T,{targetThreadId:T.threadId,targetSessionId:T.sessionId}),T.type==="TOKEN"?(T.tokenType==="FINAL_SYNTHESIS_LLM_RESPONSE"||T.tokenType==="LLM_RESPONSE")&&(v+=T.data):T.type==="METADATA"&&(C=T.data);let R=v,O,x=/```json\s*([\s\S]*?)\s*```$/,P=v.match(x);if(P&&P[1]){R=v.replace(x,"").trim();try{O=JSON.parse(P[1]);}catch{}}return {finalResponseContent:R,synthesisMetadata:C,uiMetadata:O}}async _loadConfiguration(e,t){a.debug(`[${t}] Stage 1: Initiation & Config`);let r=await this.deps.stateManager.loadThreadContext(e.threadId,e.userId);if(!r)throw new d(`Thread context not found for threadId: ${e.threadId}`,"THREAD_NOT_FOUND");let n=e.options?.persona,o=await this.deps.stateManager.getThreadConfigValue(e.threadId,"persona"),s=this.persona,i={name:n?.name||o?.name||s.name,prompts:{planning:n?.prompts?.planning||o?.prompts?.planning||s.prompts.planning,synthesis:n?.prompts?.synthesis||o?.prompts?.synthesis||s.prompts.synthesis}},c=await this.deps.systemPromptResolver.resolve({base:i.prompts.planning||"",thread:await this.deps.stateManager.getThreadConfigValue(e.threadId,"systemPrompt"),call:e.options?.systemPrompt},t),l=await this.deps.systemPromptResolver.resolve({base:i.prompts.synthesis||"",thread:await this.deps.stateManager.getThreadConfigValue(e.threadId,"systemPrompt"),call:e.options?.systemPrompt},t),p=e.options?.providerConfig||r.config.providerConfig;if(!p)throw new d(`RuntimeProviderConfig is missing in AgentProps.options or ThreadConfig for threadId: ${e.threadId}`,"INVALID_CONFIG");return {threadContext:r,planningSystemPrompt:c,synthesisSystemPrompt:l,runtimeProviderConfig:p,finalPersona:i}}async _gatherHistory(e,t){a.debug(`[${t.threadId||e}] Stage 2: Gathering History`);let r={limit:t.config.historyLimit},n=await this.deps.conversationManager.getMessages(e,r);return this.formatHistoryForPrompt(n)}async _gatherTools(e){return a.debug(`[${e}] Stage 2: Gathering Tools`),await this.deps.toolRegistry.getAvailableTools({enabledForThreadId:e})}async _delegateA2ATasks(e,t,r){a.debug(`[${r}] Stage 4: A2A Task Delegation`);let n=e.toolCalls?.filter(s=>s.toolName==="delegate_to_agent")??[];if(n.length===0)return a.debug(`[${r}] No A2A delegation calls in the plan.`),[];if(!this.deps.taskDelegationService||!this.deps.agentDiscoveryService)return a.warn(`[${r}] A2A services not available. Skipping delegation.`),[];let o=[];for(let s of n)try{let i=s.arguments,{agentId:c,taskType:l,input:p,instructions:u}=i,I=(await this.deps.agentDiscoveryService.discoverAgents(r)).find(R=>R.agentId===c);if(!I)throw new Error(`Agent with ID "${c}" not found during delegation.`);let v=Date.now(),C={taskId:s.callId,threadId:t,status:"PENDING",payload:{taskType:l,input:p,instructions:u,parameters:{threadId:t,traceId:r}},sourceAgent:{agentId:"pes-agent",agentName:"PES Agent",agentType:"orchestrator"},targetAgent:I,priority:"MEDIUM",metadata:{createdAt:v,updatedAt:v,initiatedBy:t,correlationId:r,retryCount:0,maxRetries:3,timeoutMs:6e4,tags:["delegated",l]}};await this.deps.a2aTaskRepository.createTask(C);let h=await this.deps.taskDelegationService.delegateTask(C,r);h&&o.push(h);}catch(i){a.error(`[${r}] Failed to process and delegate A2A task for call ${s.callId}:`,i),await this.deps.observationManager.record({threadId:t,traceId:r,type:"ERROR",content:{phase:"a2a_delegation",error:`Delegation for call ${s.callId} failed: ${i.message}`},metadata:{timestamp:Date.now()}});}return a.info(`[${r}] Successfully initiated delegation for ${o.length}/${n.length} A2A task(s).`),o}async _waitForA2ACompletion(e,t,r,n=3e4,o=2e3){if(e.length===0)return e;a.debug(`[${r}] Waiting for ${e.length} A2A task(s) to complete (timeout: ${n}ms)`);let s=Date.now(),i=[...e];try{for(;Date.now()-s<n;){let c=i.filter(l=>l.status!=="COMPLETED"&&l.status!=="FAILED"&&l.status!=="CANCELLED");if(c.length===0){a.info(`[${r}] All A2A tasks completed successfully`);break}a.debug(`[${r}] Waiting for ${c.length} A2A task(s) to complete...`);for(let l=0;l<i.length;l++){let p=i[l];if(!(p.status==="COMPLETED"||p.status==="FAILED"||p.status==="CANCELLED"))try{let u=await this.deps.a2aTaskRepository.getTask(p.taskId);u&&(i[l]=u);}catch(u){a.warn(`[${r}] Failed to get updated status for task ${p.taskId}:`,u);}}await new Promise(l=>setTimeout(l,o));}return i}catch(c){return a.error(`[${r}] Error during A2A task waiting:`,c),i}}async _finalize(e,t,r,n){a.debug(`[${r}] Stage 7: Finalization`);let o=Date.now(),s={messageId:Z(),threadId:e.threadId,role:"AI",content:t,timestamp:o,metadata:{traceId:r}};return await this.deps.conversationManager.addMessages(e.threadId,[s]),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"FINAL_RESPONSE",content:{message:s,uiMetadata:n},metadata:{timestamp:o}}),s}formatHistoryForPrompt(e){return e.map(t=>{let r;switch(t.role){case "USER":r="user";break;case "AI":r="assistant";break;case "SYSTEM":r="system";break;case "TOOL":r="tool";break;default:r="user";}return {role:r,content:t.content}}).filter(t=>t.content)}};var ue=class{constructor(){this.storage=new Map;}async init(e){return Promise.resolve()}async get(e,t){let r=this.storage.get(e);if(!r)return null;let n=r.get(t);return n?JSON.parse(JSON.stringify(n)):null}async set(e,t,r){return this.storage.has(e)||this.storage.set(e,new Map),this.storage.get(e).set(t,JSON.parse(JSON.stringify(r))),Promise.resolve()}async delete(e,t){let r=this.storage.get(e);return r&&r.delete(t),Promise.resolve()}async query(e,t){let r=this.storage.get(e);if(!r)return [];let n=Array.from(r.values());return t.filter&&(n=n.filter(o=>{for(let s in t.filter)if(t.filter.hasOwnProperty(s)&&o[s]!==t.filter[s])return false;return true})),typeof t.limit=="number"&&t.limit>=0&&(n=n.slice(0,t.limit)),JSON.parse(JSON.stringify(n))}async clearCollection(e){return this.storage.delete(e),Promise.resolve()}async clearAll(){return this.storage.clear(),Promise.resolve()}};var At="ART_Framework_DB",St=1,ge=class{constructor(e){this.db=null;this.initPromise=null;this.dbName=e.dbName||At,this.dbVersion=e.dbVersion||St,this.requiredObjectStores=new Set(["conversations","observations","state","a2a_tasks",...e.objectStores||[]]);}async init(){return this.initPromise?this.initPromise:(this.initPromise=new Promise((e,t)=>{if(!("indexedDB"in window))return a.error("IndexedDBStorageAdapter: IndexedDB not supported in this browser."),t(new Error("IndexedDB not supported"));let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=n=>{a.error(`IndexedDBStorageAdapter: Database error: ${r.error}`,n),t(new Error(`IndexedDB error: ${r.error?.message}`));},r.onsuccess=n=>{this.db=n.target.result,a.info(`IndexedDBStorageAdapter: Database '${this.dbName}' opened successfully (Version: ${this.db.version}).`);let o=new Set(Array.from(this.db.objectStoreNames)),s=[...this.requiredObjectStores].filter(i=>!o.has(i));s.length>0&&a.warn(`IndexedDBStorageAdapter: The following required object stores were not found after opening DB version ${this.db.version}: ${s.join(", ")}. This might happen if the DB version wasn't incremented after adding stores.`),this.db.onerror=i=>{a.error("IndexedDBStorageAdapter: Generic database error:",i);},e();},r.onupgradeneeded=n=>{if(a.info(`IndexedDBStorageAdapter: Upgrading database '${this.dbName}' from version ${n.oldVersion} to ${n.newVersion}...`),this.db=n.target.result,!n.target.transaction){a.error("IndexedDBStorageAdapter: Upgrade transaction is null!"),t(new Error("Upgrade transaction failed"));return}let s=new Set(Array.from(this.db.objectStoreNames));this.requiredObjectStores.forEach(i=>{s.has(i)||(a.info(`IndexedDBStorageAdapter: Creating object store '${i}'...`),this.db?.createObjectStore(i,{keyPath:"id"}));}),a.info("IndexedDBStorageAdapter: Database upgrade complete.");},r.onblocked=n=>{a.warn(`IndexedDBStorageAdapter: Database open request blocked for '${this.dbName}'. Please close other tabs/connections using an older version of this database.`,n),t(new Error(`IndexedDB open blocked for ${this.dbName}. Close other connections.`));};}),this.initPromise)}getTransaction(e,t){if(!this.db)throw new Error("IndexedDBStorageAdapter: Database not initialized. Ensure init() was called and awaited.");return (Array.isArray(e)?e:[e]).forEach(n=>{if(!this.db?.objectStoreNames.contains(n))throw new Error(`IndexedDBStorageAdapter: Object store "${n}" does not exist in the database.`)}),this.db.transaction(e,t)}async get(e,t){return await this.init(),new Promise((r,n)=>{try{let i=this.getTransaction(e,"readonly").objectStore(e).get(t);i.onsuccess=()=>{r(i.result?{...i.result}:null);},i.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error getting item '${t}' from '${e}':`,i.error),n(new Error(`Failed to get item: ${i.error?.message}`));};}catch(o){n(o);}})}async set(e,t,r){let n=r;return typeof n.id>"u"?Promise.reject(new Error(`IndexedDBStorageAdapter: Data for collection '${e}' must have an 'id' property matching the keyPath.`)):(n.id!==t&&a.warn(`IndexedDBStorageAdapter: Provided id ('${t}') and data.id ('${n.id}') mismatch for collection '${e}'. Using data.id as the key.`),await this.init(),new Promise((o,s)=>{try{let i=structuredClone(r),c=this.getTransaction(e,"readwrite"),p=c.objectStore(e).put(i);p.onsuccess=()=>{o();},p.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error setting item with id '${n.id}' in '${e}':`,p.error),s(new Error(`Failed to set item: ${p.error?.message}`));},c.oncomplete=()=>{},c.onerror=u=>{a.error(`IndexedDBStorageAdapter: Transaction error setting item with id '${n.id}' in '${e}':`,c.error,u),s(new Error(`Transaction failed: ${c.error?.message}`));};}catch(i){s(i);}}))}async delete(e,t){return await this.init(),new Promise((r,n)=>{try{let o=this.getTransaction(e,"readwrite"),i=o.objectStore(e).delete(t);i.onsuccess=()=>{r();},i.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error deleting item '${t}' from '${e}':`,i.error),n(new Error(`Failed to delete item: ${i.error?.message}`));},o.onerror=c=>{a.error(`IndexedDBStorageAdapter: Transaction error deleting item '${t}' from '${e}':`,o.error,c),n(new Error(`Transaction failed: ${o.error?.message}`));};}catch(o){n(o);}})}async query(e,t){return await this.init(),new Promise((r,n)=>{try{let i=this.getTransaction(e,"readonly").objectStore(e).getAll();i.onsuccess=()=>{let c=i.result||[];if(t.filter&&(c=c.filter(u=>{for(let m in t.filter)if(t.filter.hasOwnProperty(m)&&u[m]!==t.filter[m])return !1;return !0})),t.sort){let u=Object.keys(t.sort)[0],m=t.sort[u];u&&c.sort((I,v)=>{let C=I[u],h=v[u];return C<h?m==="asc"?-1:1:C>h?m==="asc"?1:-1:0});}let l=t.skip||0,p=t.limit??1/0;c=c.slice(l,l+p),r(c.map(u=>({...u})));},i.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error querying collection '${e}':`,i.error),n(new Error(`Failed to query collection: ${i.error?.message}`));};}catch(o){n(o);}})}async clearCollection(e){return await this.init(),new Promise((t,r)=>{try{let n=this.getTransaction(e,"readwrite"),s=n.objectStore(e).clear();s.onsuccess=()=>{t();},s.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error clearing collection '${e}':`,s.error),r(new Error(`Failed to clear collection: ${s.error?.message}`));},n.onerror=i=>{a.error(`IndexedDBStorageAdapter: Transaction error clearing collection '${e}':`,n.error,i),r(new Error(`Transaction failed: ${n.error?.message}`));};}catch(n){r(n);}})}async clearAll(){if(await this.init(),!this.db)throw new Error("Database not initialized.");let e=Array.from(this.db.objectStoreNames);return e.length===0?Promise.resolve():new Promise((t,r)=>{try{let n=this.getTransaction(e,"readwrite"),o=0,s=e.length;e.forEach(i=>{let c=n.objectStore(i).clear();c.onsuccess=()=>{o++;},c.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error clearing object store '${i}':`,c.error);};}),n.oncomplete=()=>{a.info("IndexedDBStorageAdapter: All object stores cleared successfully."),t();},n.onerror=i=>{a.error("IndexedDBStorageAdapter: Transaction error during clearAll:",n.error,i),r(new Error(`Failed to clear all stores: ${n.error?.message}`));};}catch(n){r(n);}})}};var Oe=class{constructor(e){this.collectionName="conversations";if(!e)throw new Error("ConversationRepository requires a valid StorageAdapter instance.");this.adapter=e;}async addMessages(e,t){if(!t||t.length===0)return Promise.resolve();let r=t.map(n=>{n.threadId!==e&&console.warn(`ConversationRepository: Message ${n.messageId} has mismatching threadId (${n.threadId}) for repository operation on thread ${e}.`);let o={...n,id:n.messageId};return this.adapter.set(this.collectionName,o.id,o)});await Promise.all(r);}async getMessages(e,t){let n=await this.adapter.query(this.collectionName,{filter:{threadId:e}});return n.sort((s,i)=>s.timestamp-i.timestamp),t?.beforeTimestamp!==void 0&&(n=n.filter(s=>s.timestamp<t.beforeTimestamp)),t?.afterTimestamp!==void 0&&(n=n.filter(s=>s.timestamp>t.afterTimestamp)),t?.limit!==void 0&&t.limit>0&&(n=n.slice(-t.limit)),n.map(({id:s,...i})=>i)}};var we=class{constructor(e){this.collectionName="observations";if(!e)throw new Error("ObservationRepository requires a valid StorageAdapter instance.");this.adapter=e;}async addObservation(e){if(typeof e.id>"u")return Promise.reject(new Error("ObservationRepository: Observation must have an 'id' property."));await this.adapter.set(this.collectionName,e.id,e);}async getObservations(e,t){let n=await this.adapter.query(this.collectionName,{filter:{threadId:e}});if(n.sort((o,s)=>o.timestamp-s.timestamp),t?.types&&t.types.length>0){let o=new Set(t.types);n=n.filter(s=>o.has(s.type));}return t?.beforeTimestamp!==void 0&&(n=n.filter(o=>o.timestamp<t.beforeTimestamp)),t?.afterTimestamp!==void 0&&(n=n.filter(o=>o.timestamp>t.afterTimestamp)),n}};var ke=class{constructor(e){this.collectionName="state";if(!e)throw new Error("StateRepository requires a valid StorageAdapter instance.");this.adapter=e;}async getThreadContext(e){let t=await this.adapter.get(this.collectionName,e);if(!t)return null;let r={...t};return delete r.id,r}async setThreadContext(e,t){if(!t||typeof t.config>"u")return Promise.reject(new Error("StateRepository: ThreadContext must contain a 'config' property."));let r={...t,id:e};await this.adapter.set(this.collectionName,e,r);}async getThreadConfig(e){return (await this.getThreadContext(e))?.config??null}async setThreadConfig(e,t){let r=await this.getThreadContext(e),n={config:t,state:r?.state??null};await this.setThreadContext(e,n);}async getAgentState(e){return (await this.getThreadContext(e))?.state??null}async setAgentState(e,t){let r=await this.getThreadContext(e);if(!r||!r.config)return Promise.reject(new Error(`StateRepository: Cannot set AgentState for thread '${e}' because no ThreadConfig exists. Set config first.`));let n={config:r.config,state:t};await this.setThreadContext(e,n);}};var be=class{constructor(e){this.collectionName="a2a_tasks";if(!e)throw new Error("TaskStatusRepository requires a valid StorageAdapter instance.");this.adapter=e;}async createTask(e){if(!e||!e.taskId)throw new d("Task must have a valid taskId","VALIDATION_ERROR");if(await this.adapter.get(this.collectionName,e.taskId))throw new d(`Task with ID '${e.taskId}' already exists`,"DUPLICATE_TASK_ID");let r={...e,id:e.taskId};await this.adapter.set(this.collectionName,e.taskId,r);}async getTask(e){if(!e)throw new d("TaskId is required","VALIDATION_ERROR");try{let t=await this.adapter.get(this.collectionName,e);if(!t)return null;let r={...t};return delete r.id,r}catch(t){throw new d(`Failed to retrieve task '${e}': ${t}`,"REPOSITORY_ERROR")}}async updateTask(e,t){if(!e)throw new d("TaskId is required","VALIDATION_ERROR");if(!t||Object.keys(t).length===0)throw new d("Updates object cannot be empty","VALIDATION_ERROR");try{let r=await this.adapter.get(this.collectionName,e);if(!r)throw new d(`Task with ID '${e}' not found`,"TASK_NOT_FOUND");let n={...r,...t,taskId:e,id:e};t.metadata&&(n.metadata={...r.metadata,...t.metadata,lastUpdated:Date.now()}),await this.adapter.set(this.collectionName,e,n);}catch(r){throw r instanceof d?r:new d(`Failed to update task '${e}': ${r}`,"REPOSITORY_ERROR")}}async deleteTask(e){if(!e)throw new d("TaskId is required","VALIDATION_ERROR");try{if(!await this.adapter.get(this.collectionName,e))throw new d(`Task with ID '${e}' not found`,"TASK_NOT_FOUND");await this.adapter.delete(this.collectionName,e);}catch(t){throw t instanceof d?t:new d(`Failed to delete task '${e}': ${t}`,"REPOSITORY_ERROR")}}async getTasksByThread(e,t){if(!e)throw new d("ThreadId is required","VALIDATION_ERROR");try{let n=await this.adapter.query(this.collectionName,{filter:{threadId:e}});if(t){if(t.status){let o=Array.isArray(t.status)?t.status:[t.status];n=n.filter(s=>o.includes(s.status));}t.priority&&(n=n.filter(o=>o.priority===t.priority)),t.assignedAgentId&&(n=n.filter(o=>o.targetAgent?.agentId===t.assignedAgentId));}return n.sort((o,s)=>(s.metadata?.createdAt||0)-(o.metadata?.createdAt||0)),this._removeIdField(n)}catch(r){throw new d(`Failed to get tasks for thread '${e}': ${r}`,"REPOSITORY_ERROR")}}async getTasksByAgent(e,t){if(!e)throw new d("AgentId is required","VALIDATION_ERROR");try{let n=(await this.adapter.query(this.collectionName,{filter:{}})).filter(o=>o.targetAgent?.agentId===e);if(t){if(t.status){let o=Array.isArray(t.status)?t.status:[t.status];n=n.filter(s=>o.includes(s.status));}t.priority&&(n=n.filter(o=>o.priority===t.priority));}return n.sort((o,s)=>(s.metadata?.createdAt||0)-(o.metadata?.createdAt||0)),this._removeIdField(n)}catch(r){throw new d(`Failed to get tasks for agent '${e}': ${r}`,"REPOSITORY_ERROR")}}async getTasksByStatus(e,t){if(!e)throw new d("Status is required","VALIDATION_ERROR");try{let r=await this.adapter.query(this.collectionName,{filter:{}}),n=Array.isArray(e)?e:[e],o=r.filter(s=>n.includes(s.status));if(o.sort((s,i)=>(i.metadata?.createdAt||0)-(s.metadata?.createdAt||0)),t){let s=t.offset||0,i=t.limit;s>0&&(o=o.slice(s)),i&&i>0&&(o=o.slice(0,i));}return this._removeIdField(o)}catch(r){throw new d(`Failed to get tasks by status: ${r}`,"REPOSITORY_ERROR")}}_removeIdField(e){return e.map(t=>{let r={...t};return delete r.id,r})}};var Me=class{constructor(e,t){this.repository=e,this.conversationSocket=t;}async addMessages(e,t){if(!e)return Promise.reject(new Error("ConversationManager: threadId cannot be empty."));if(!t||t.length===0)return Promise.resolve();await this.repository.addMessages(e,t),t.forEach(r=>{try{this.conversationSocket.notify(r,{targetThreadId:e});}catch(n){console.error(`ConversationManager: Failed to notify message ${r.messageId} via socket for thread ${e}`,n);}});}async getMessages(e,t){return e?await this.repository.getMessages(e,t):Promise.reject(new Error("ConversationManager: threadId cannot be empty."))}};function Ce(g){if(g===null||typeof g!="object")return g;if(g instanceof Date)return new Date(g.getTime());if(Array.isArray(g))return g.map(t=>Ce(t));let e={};for(let t in g)Object.prototype.hasOwnProperty.call(g,t)&&(e[t]=Ce(g[t]));return e}var me=class{constructor(e,t="explicit"){this.repository=e,this.strategy=t,this.contextCache=new Map;}async loadThreadContext(e,t){if(!e)throw new Error("StateManager: threadId cannot be empty for loadThreadContext.");if(this.strategy==="implicit"&&this.contextCache.has(e))return this.contextCache.get(e).context;let r=await this.repository.getThreadContext(e);if(!r)throw new Error(`StateManager: Thread context not found for threadId '${e}'. Application should call setThreadConfig first for new threads.`);if(this.strategy==="implicit"){let n=Ce(r),o=n.state?JSON.stringify(n.state):null;return this.contextCache.set(e,{originalStateSnapshot:o,context:n}),n}else return r}async isToolEnabled(e,t){try{return (await this.loadThreadContext(e)).config?.enabledTools?.includes(t)??!1}catch(r){return console.warn(`StateManager: Could not check if tool '${t}' is enabled for thread '${e}' because context failed to load: ${r}`),false}}async getThreadConfigValue(e,t){let r=await this.loadThreadContext(e);if(r.config&&t in r.config)return r.config[t]}async saveStateIfModified(e){if(!e)throw new Error("StateManager: threadId cannot be empty for saveStateIfModified.");if(this.strategy==="explicit")return console.warn(`StateManager (explicit): saveStateIfModified called for thread ${e}. AgentState must be saved explicitly using setAgentState(). This method is a no-op for AgentState in explicit mode.`),Promise.resolve();let t=this.contextCache.get(e);if(!t)return console.warn(`StateManager (implicit): saveStateIfModified called for thread ${e}, but context was not loaded or cached in this StateManager instance for this cycle. State will not be saved implicitly.`),Promise.resolve();let r=t.context.state,n=r?JSON.stringify(r):null;return n!==t.originalStateSnapshot&&(r===null&&console.warn(`StateManager (implicit): AgentState for thread ${e} became null. Attempting to save null state.`),r!==null?(await this.repository.setAgentState(e,r),t.originalStateSnapshot=n):console.warn(`StateManager (implicit): AgentState for thread ${e} is null. Implicit save will not persist null state due to setAgentState constraints. Use setAgentState with a valid object to clear or update.`)),Promise.resolve()}async setThreadConfig(e,t){if(!e||!t)throw new Error("StateManager: threadId and config are required for setThreadConfig.");await this.repository.setThreadConfig(e,t),this.contextCache.has(e)&&this.contextCache.delete(e);}async setAgentState(e,t){if(!e)throw new Error("StateManager: threadId cannot be empty for setAgentState.");if(typeof t>"u"||t===null)throw new Error("StateManager: state cannot be undefined or null for setAgentState.");if(await this.repository.setAgentState(e,t),this.strategy==="implicit"){let r=this.contextCache.get(e);r&&(r.context.state=Ce(t),r.originalStateSnapshot=JSON.stringify(t));}}async enableToolsForThread(e,t){if(!e)throw new Error("StateManager: threadId cannot be empty for enableToolsForThread.");if(!t||t.length===0)throw new Error("StateManager: toolNames cannot be empty for enableToolsForThread.");let r=await this.loadThreadContext(e);if(!r.config)throw new Error(`StateManager: No ThreadConfig found for threadId '${e}'. Cannot enable tools without existing configuration.`);let n=r.config.enabledTools||[],o=[...new Set([...n,...t])],s={...r.config,enabledTools:o};await this.setThreadConfig(e,s);}async disableToolsForThread(e,t){if(!e)throw new Error("StateManager: threadId cannot be empty for disableToolsForThread.");if(!t||t.length===0)throw new Error("StateManager: toolNames cannot be empty for disableToolsForThread.");let r=await this.loadThreadContext(e);if(!r.config)throw new Error(`StateManager: No ThreadConfig found for threadId '${e}'. Cannot disable tools without existing configuration.`);let o=(r.config.enabledTools||[]).filter(i=>!t.includes(i)),s={...r.config,enabledTools:o};await this.setThreadConfig(e,s);}async getEnabledToolsForThread(e){if(!e)throw new Error("StateManager: threadId cannot be empty for getEnabledToolsForThread.");return (await this.loadThreadContext(e)).config?.enabledTools||[]}clearCache(){this.contextCache.clear();}};var Ne=class{constructor(e,t){this.observationRepository=e,this.observationSocket=t;}async record(e){let t={...e,id:Z(),timestamp:Date.now(),title:`${e.type} Recorded`};try{await this.observationRepository.addObservation(t),a.debug(`[ObservationManager] Notifying ObservationSocket for obsId: ${t.id}, type: ${t.type}`),this.observationSocket.notify(t,{targetThreadId:t.threadId}),a.debug(`[ObservationManager] ObservationSocket notified for obsId: ${t.id}`);}catch(r){throw console.error("Error recording observation:",r),r}}async getObservations(e,t){try{return await this.observationRepository.getObservations(e,t)}catch(r){throw console.error(`Error retrieving observations for thread ${e}:`,r),r}}};var he=class{constructor(e){this.executors=new Map;this.stateManager=e,a.debug(`ToolRegistry initialized ${e?"with":"without"} StateManager.`);}async registerTool(e){if(!e||!e.schema||!e.schema.name)throw a.error("ToolRegistry: Attempted to register an invalid tool executor."),new Error("Invalid tool executor provided for registration.");let t=e.schema.name;this.executors.has(t)&&a.warn(`ToolRegistry: Overwriting existing tool registration for "${t}".`),this.executors.set(t,e),a.debug(`ToolRegistry: Registered tool "${t}".`);}async getToolExecutor(e){let t=this.executors.get(e);return t||a.debug(`ToolRegistry: Tool "${e}" not found.`),t}async getAvailableTools(e){let t=Array.from(this.executors.values()),r=t.map(n=>n.schema);if(e?.enabledForThreadId&&this.stateManager){let n=e.enabledForThreadId;a.debug(`ToolRegistry: Attempting to filter tools for threadId: ${n}`);try{let s=(await this.stateManager.loadThreadContext(n))?.config?.enabledTools;if(s&&Array.isArray(s)){a.debug(`ToolRegistry: Found enabled tools for thread ${n}: ${s.join(", ")}`);let c=t.filter(l=>s.includes(l.schema.name)).map(l=>l.schema);return a.debug(`ToolRegistry: Returning ${c.length} enabled tool schemas for thread ${n}.`),c}else a.warn(`ToolRegistry: No specific enabledTools found for thread ${n} or config missing. Returning all tools.`);}catch(o){a.error(`ToolRegistry: Error loading thread config for ${n}: ${o.message}. Returning all tools.`);}}else e?.enabledForThreadId&&!this.stateManager&&a.warn("ToolRegistry: Filtering by enabledForThreadId requested, but StateManager was not provided. Returning all tools.");return a.debug(`ToolRegistry: Returning all ${r.length} registered tool schemas.`),r}async clearAllTools(){this.executors.clear(),a.debug("ToolRegistry: Cleared all registered tools.");}async unregisterTool(e){this.executors.delete(e)&&a.debug(`ToolRegistry: Unregistered tool "${e}".`);}async unregisterTools(e){let t=0;for(let[r,n]of Array.from(this.executors.entries()))try{e(n.schema)&&(this.executors.delete(r),t++);}catch{}return t>0&&a.debug(`ToolRegistry: Unregistered ${t} tool(s) via predicate.`),t}};var _t=new It({allErrors:true}),qe=new Map;function ct(g,e){let t=JSON.stringify(g),r;if(qe.has(t))r=qe.get(t),a.debug("Using cached JSON schema validator.");else try{r=_t.compile(g),qe.set(t,r),a.debug("Compiled and cached new JSON schema validator.");}catch(o){return a.error(`Failed to compile JSON schema: ${o.message}`,{schema:g,error:o}),{isValid:false,errors:[{keyword:"compilation",instancePath:"",schemaPath:"",params:{},message:`Schema compilation failed: ${o.message}`}]}}return r(e)?{isValid:true,errors:null}:(a.warn("JSON schema validation failed.",{errors:r.errors,data:e}),{isValid:false,errors:r.errors||[]})}var Pe=class{constructor(e,t,r){if(!e)throw new Error("ToolSystem constructor requires a ToolRegistry instance.");if(!t)throw new Error("ToolSystem constructor requires a StateManager instance.");if(!r)throw new Error("ToolSystem constructor requires an ObservationManager instance.");this.toolRegistry=e,this.stateManager=t,this.observationManager=r,a.info("ToolSystem initialized.");}async executeTools(e,t,r){let n=[];a.debug(`ToolSystem executing ${e.length} tool calls for thread ${t}`,{traceId:r});for(let o of e){let s=null,i,c=o.toolName,l=o.callId;try{if(!await this.stateManager.isToolEnabled(t,c))throw new Error(`Tool "${c}" is not enabled for thread "${t}".`);if(i=await this.toolRegistry.getToolExecutor(c),!i)throw new Error(`Tool "${c}" not found in registry.`);let u=ct(i.schema.inputSchema,o.arguments);if(!u.isValid){let v=u.errors?.map(C=>`${C.instancePath||"input"} ${C.message}`).join(", ")||"Unknown validation error";throw new Error(`Invalid arguments for tool "${c}": ${v}`)}a.debug(`Executing tool "${c}" with callId "${l}"`,{args:o.arguments,threadId:t,traceId:r});let m={threadId:t,traceId:r};s={...await i.execute(o.arguments,m),callId:l,toolName:c},a.debug(`Tool "${c}" execution successful`,{callId:l,result:s.output,threadId:t,traceId:r});}catch(p){a.error(`Tool "${c}" execution failed for callId "${l}": ${p.message}`,{error:p,threadId:t,traceId:r}),s={callId:l,toolName:c,status:"error",error:p.message||"Unknown execution error"};}s?(this.observationManager.record({threadId:t,traceId:r,type:"TOOL_EXECUTION",content:s,metadata:{timestamp:Date.now(),callId:o.callId}}).catch(p=>a.error(`Failed to record TOOL_EXECUTION observation for callId ${o.callId}:`,p)),n.push(s)):a.error(`ToolSystem finished processing call ${o.callId} but result object was null.`);}return n}};function dt(g,e,t){switch(t||"append"){case "prepend":return `${e}
72
72
 
73
73
  ${g}`;case "append":default:return `${g}
74
74
 
75
- ${e}`}}function qe(g){if(g)return typeof g=="string"?{content:g,strategy:"append"}:g}var Pe=class{constructor(e){this.registry=e;}async resolve(e,t){let r=e.base,n=[{src:"instance",ov:qe(e.instance)},{src:"thread",ov:qe(e.thread)},{src:"call",ov:qe(e.call)}];for(let o of n){let s=o.ov;if(!s)continue;let i="";if(s.tag&&this.registry?.specs?.[s.tag]){let c=this.registry.specs[s.tag],l={...c.defaultVariables||{},...s.variables||{}};i=this.renderTemplate(c.template,l),r=dt(r,i,s.strategy||c.mergeStrategy||"append"),a.debug?.(`[${t||"no-trace"}] Applied system prompt tag '${s.tag}' with strategy '${s.strategy||c.mergeStrategy||"append"}'.`);}else s.content&&(i=s.content,r=dt(r,i,s.strategy||"append"),a.debug?.(`[${t||"no-trace"}] Applied freeform system prompt with strategy '${s.strategy||"append"}'.`));}return r}renderTemplate(e,t){return e.replace(/\{\{\s*([^}:]+)\s*\}\}/g,(r,n)=>{let o=t[String(n).trim()];return o!==void 0?String(o):""})}};var xe=class{constructor(e){this.providerManager=e,a.info("ReasoningEngine initialized with ProviderManager");}async call(e,t){let r=t.providerConfig;if(!r)throw new Error("CallOptions must include 'providerConfig' for multi-provider architecture.");a.debug(`ReasoningEngine requesting adapter for provider: ${r.providerName}, model: ${r.modelId}`,{threadId:t.threadId,traceId:t.traceId,stream:t.stream});let n;try{n=await this.providerManager.getAdapter(r),a.debug(`ReasoningEngine obtained adapter for signature: ${n.adapter.providerName}`,{threadId:t.threadId,traceId:t.traceId});}catch(o){throw a.error(`ReasoningEngine failed to get adapter: ${o.message}`,{error:o,threadId:t.threadId,traceId:t.traceId}),o}try{let o=await n.adapter.call(e,t);return (async function*(){try{for await(let i of o)yield i;}finally{n.release(),a.debug(`ReasoningEngine released adapter for signature: ${n.adapter.providerName}`,{threadId:t.threadId,traceId:t.traceId});}})()}catch(o){throw a.error(`ReasoningEngine encountered an error during adapter call or stream processing: ${o.message}`,{error:o,threadId:t.threadId,traceId:t.traceId}),n.release(),a.debug(`ReasoningEngine released adapter after error for signature: ${n.adapter.providerName}`,{threadId:t.threadId,traceId:t.traceId}),o}}};var me=class{constructor(e,t,r=0){this.tagName=e;this.transform=t;this.position=r;this.index=0;this.currentChunks=[];this.cachedBuffer=[];this.isCurrentlyMatched=false;this.tagDepth=0;this.pointer=0;this.S_TEXT=0;this.S_TAG_OPEN=1;this.S_TAG_NAME=2;this.S_TAG_CLOSING_SLASH=3;this.S_IGNORE_UNTIL_GT=4;this.state=this.S_TEXT;}collectCurrentCache(e){if(this.cachedBuffer.length===0){e!==void 0&&this.currentChunks.length>0;return}let t=this.cachedBuffer.join("");this.cachedBuffer=[];let r=e===void 0?this.isCurrentlyMatched:!e,n=this.currentChunks.length>0?this.currentChunks[this.currentChunks.length-1]:null;n&&n.matched===r?n.data+=t:this.currentChunks.push({matched:r,data:t});}flushProcessedChunks(){let e=this.currentChunks;return this.currentChunks=[],this.transform?e.map(this.transform):e}update(e){for(let t=0;t<e.length;t++){let r=e[t];this.pointer++,this.state===this.S_TEXT?r==="<"&&(this.pointer>this.position||this.isCurrentlyMatched||this.tagDepth>0)?(this.collectCurrentCache(),this.state=this.S_TAG_OPEN,this.cachedBuffer.push(r)):this.cachedBuffer.push(r):this.state===this.S_TAG_OPEN?(this.cachedBuffer.push(r),r==="/"?(this.state=this.S_TAG_CLOSING_SLASH,this.index=0):r.match(/[a-zA-Z]/)?(this.state=this.S_TAG_NAME,this.index=0,this.cachedBuffer.pop(),t--):this.state=this.S_TEXT):this.state===this.S_TAG_NAME?this.index<this.tagName.length&&r===this.tagName[this.index]?(this.cachedBuffer.push(r),this.index++):r===">"&&this.index===this.tagName.length?(this.cachedBuffer.push(r),this.collectCurrentCache(true),this.isCurrentlyMatched=true,this.tagDepth++,this.state=this.S_TEXT,this.cachedBuffer=[]):(r===" "||r===" "||r===`
76
- `||r==="\r"||r===">")&&this.index===this.tagName.length?(this.cachedBuffer.push(r),r===">"?(this.collectCurrentCache(true),this.isCurrentlyMatched=true,this.tagDepth++,this.state=this.S_TEXT,this.cachedBuffer=[]):this.state=this.S_IGNORE_UNTIL_GT):(this.state=this.S_IGNORE_UNTIL_GT,this.cachedBuffer.push(r)):this.state===this.S_TAG_CLOSING_SLASH?(this.cachedBuffer.push(r),this.index<this.tagName.length&&r===this.tagName[this.index]?this.index++:r===">"&&this.index===this.tagName.length?(this.collectCurrentCache(false),this.tagDepth--,this.isCurrentlyMatched=this.tagDepth>0,this.state=this.S_TEXT,this.cachedBuffer=[]):this.state=this.S_IGNORE_UNTIL_GT):this.state===this.S_IGNORE_UNTIL_GT&&(this.cachedBuffer.push(r),r===">"&&(this.state=this.S_TEXT));}return this.flushProcessedChunks()}final(e){return e&&this.update(e),this.collectCurrentCache(),this.flushProcessedChunks()}};var Et=K.object({callId:K.string().min(1),toolName:K.string().min(1),arguments:K.unknown()}),Ke=K.array(Et),vt=K.object({id:K.string(),description:K.string(),status:K.nativeEnum(le).optional().default("pending"),dependencies:K.array(K.string()).optional()}),Rt=K.array(vt),Le=class{async parsePlanningOutput(e){let t={},r=e,n=[],s=new me("think").final(e),i="";s.forEach(p=>{p.matched?n.push(p.data.trim()):i+=p.data;}),n.length>0&&(t.thoughts=n.join(`
75
+ ${e}`}}function Ke(g){if(g)return typeof g=="string"?{content:g,strategy:"append"}:g}var xe=class{constructor(e){this.registry=e;}async resolve(e,t){let r=e.base,n=[{src:"instance",ov:Ke(e.instance)},{src:"thread",ov:Ke(e.thread)},{src:"call",ov:Ke(e.call)}];for(let o of n){let s=o.ov;if(!s)continue;let i="";if(s.tag&&this.registry?.specs?.[s.tag]){let c=this.registry.specs[s.tag],l={...c.defaultVariables||{},...s.variables||{}};i=this.renderTemplate(c.template,l),r=dt(r,i,s.strategy||c.mergeStrategy||"append"),a.debug?.(`[${t||"no-trace"}] Applied system prompt tag '${s.tag}' with strategy '${s.strategy||c.mergeStrategy||"append"}'.`);}else s.content&&(i=s.content,r=dt(r,i,s.strategy||"append"),a.debug?.(`[${t||"no-trace"}] Applied freeform system prompt with strategy '${s.strategy||"append"}'.`));}return r}renderTemplate(e,t){return e.replace(/\{\{\s*([^}:]+)\s*\}\}/g,(r,n)=>{let o=t[String(n).trim()];return o!==void 0?String(o):""})}};var Le=class{constructor(e){this.providerManager=e,a.info("ReasoningEngine initialized with ProviderManager");}async call(e,t){let r=t.providerConfig;if(!r)throw new Error("CallOptions must include 'providerConfig' for multi-provider architecture.");a.debug(`ReasoningEngine requesting adapter for provider: ${r.providerName}, model: ${r.modelId}`,{threadId:t.threadId,traceId:t.traceId,stream:t.stream});let n;try{n=await this.providerManager.getAdapter(r),a.debug(`ReasoningEngine obtained adapter for signature: ${n.adapter.providerName}`,{threadId:t.threadId,traceId:t.traceId});}catch(o){throw a.error(`ReasoningEngine failed to get adapter: ${o.message}`,{error:o,threadId:t.threadId,traceId:t.traceId}),o}try{let o=await n.adapter.call(e,t);return (async function*(){try{for await(let i of o)yield i;}finally{n.release(),a.debug(`ReasoningEngine released adapter for signature: ${n.adapter.providerName}`,{threadId:t.threadId,traceId:t.traceId});}})()}catch(o){throw a.error(`ReasoningEngine encountered an error during adapter call or stream processing: ${o.message}`,{error:o,threadId:t.threadId,traceId:t.traceId}),n.release(),a.debug(`ReasoningEngine released adapter after error for signature: ${n.adapter.providerName}`,{threadId:t.threadId,traceId:t.traceId}),o}}};var fe=class{constructor(e,t,r=0){this.tagName=e;this.transform=t;this.position=r;this.index=0;this.currentChunks=[];this.cachedBuffer=[];this.isCurrentlyMatched=false;this.tagDepth=0;this.pointer=0;this.S_TEXT=0;this.S_TAG_OPEN=1;this.S_TAG_NAME=2;this.S_TAG_CLOSING_SLASH=3;this.S_IGNORE_UNTIL_GT=4;this.state=this.S_TEXT;}collectCurrentCache(e){if(this.cachedBuffer.length===0){e!==void 0&&this.currentChunks.length>0;return}let t=this.cachedBuffer.join("");this.cachedBuffer=[];let r=e===void 0?this.isCurrentlyMatched:!e,n=this.currentChunks.length>0?this.currentChunks[this.currentChunks.length-1]:null;n&&n.matched===r?n.data+=t:this.currentChunks.push({matched:r,data:t});}flushProcessedChunks(){let e=this.currentChunks;return this.currentChunks=[],this.transform?e.map(this.transform):e}update(e){for(let t=0;t<e.length;t++){let r=e[t];this.pointer++,this.state===this.S_TEXT?r==="<"&&(this.pointer>this.position||this.isCurrentlyMatched||this.tagDepth>0)?(this.collectCurrentCache(),this.state=this.S_TAG_OPEN,this.cachedBuffer.push(r)):this.cachedBuffer.push(r):this.state===this.S_TAG_OPEN?(this.cachedBuffer.push(r),r==="/"?(this.state=this.S_TAG_CLOSING_SLASH,this.index=0):r.match(/[a-zA-Z]/)?(this.state=this.S_TAG_NAME,this.index=0,this.cachedBuffer.pop(),t--):this.state=this.S_TEXT):this.state===this.S_TAG_NAME?this.index<this.tagName.length&&r===this.tagName[this.index]?(this.cachedBuffer.push(r),this.index++):r===">"&&this.index===this.tagName.length?(this.cachedBuffer.push(r),this.collectCurrentCache(true),this.isCurrentlyMatched=true,this.tagDepth++,this.state=this.S_TEXT,this.cachedBuffer=[]):(r===" "||r===" "||r===`
76
+ `||r==="\r"||r===">")&&this.index===this.tagName.length?(this.cachedBuffer.push(r),r===">"?(this.collectCurrentCache(true),this.isCurrentlyMatched=true,this.tagDepth++,this.state=this.S_TEXT,this.cachedBuffer=[]):this.state=this.S_IGNORE_UNTIL_GT):(this.state=this.S_IGNORE_UNTIL_GT,this.cachedBuffer.push(r)):this.state===this.S_TAG_CLOSING_SLASH?(this.cachedBuffer.push(r),this.index<this.tagName.length&&r===this.tagName[this.index]?this.index++:r===">"&&this.index===this.tagName.length?(this.collectCurrentCache(false),this.tagDepth--,this.isCurrentlyMatched=this.tagDepth>0,this.state=this.S_TEXT,this.cachedBuffer=[]):this.state=this.S_IGNORE_UNTIL_GT):this.state===this.S_IGNORE_UNTIL_GT&&(this.cachedBuffer.push(r),r===">"&&(this.state=this.S_TEXT));}return this.flushProcessedChunks()}final(e){return e&&this.update(e),this.collectCurrentCache(),this.flushProcessedChunks()}};var Et=q.object({callId:q.string().min(1),toolName:q.string().min(1),arguments:q.unknown()}),Be=q.array(Et),vt=q.object({id:q.string(),description:q.string(),status:q.nativeEnum(de).optional().default("pending"),dependencies:q.array(q.string()).optional()}),Rt=q.array(vt),De=class{async parsePlanningOutput(e){let t={},r=e,n=[],s=new fe("think").final(e),i="";s.forEach(p=>{p.matched?n.push(p.data.trim()):i+=p.data;}),n.length>0&&(t.thoughts=n.join(`
77
77
 
78
78
  ---
79
79
 
80
- `)),r=i;let l=(p=>{if(!p)return null;let u=p.trim();if(u=u.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,"").trim(),!u.startsWith("{")&&u.includes("{")&&u.includes("}")){let f=u.indexOf("{"),A=u.lastIndexOf("}");f>=0&&A>f&&(u=u.slice(f,A+1));}try{return JSON.parse(u)}catch{return null}})(r);if(l&&typeof l=="object"){if(typeof l.title=="string"&&(t.title=l.title),typeof l.intent=="string"&&(t.intent=l.intent),Array.isArray(l.plan)?t.plan=l.plan.map(p=>typeof p=="string"?p:JSON.stringify(p)).join(`
81
- `):typeof l.plan=="string"&&(t.plan=l.plan),Array.isArray(l.toolCalls)){let p=Ke.safeParse(l.toolCalls);p.success?t.toolCalls=p.data:t.toolCalls=[];}if(Array.isArray(l.todoList)){let p=Rt.safeParse(l.todoList);p.success?t.todoList=p.data.map(u=>({...u,createdTimestamp:Date.now(),updatedTimestamp:Date.now()})):a.warn(`OutputParser: TodoList validation failed: ${p.error}`);}}else {let p=r.match(/Title:\s*([\s\S]*?)(Intent:|Plan:|Tool Calls:|Todo List:|$)/i);p&&(t.title=p[1].trim());let u=r.match(/Intent:\s*([\s\S]*?)(Plan:|Tool Calls:|Todo List:|$)/i);u&&(t.intent=u[1].trim());let f=r.match(/Plan:\s*([\s\S]*?)(Tool Calls:|Todo List:|$)/i);f&&(t.plan=f[1].trim());}return t}async parseExecutionOutput(e){let t={},r=e,n=[],s=new me("think").final(e),i="";s.forEach(l=>{l.matched?n.push(l.data.trim()):i+=l.data;}),n.length>0&&(t.thoughts=n.join(`
80
+ `)),r=i;let l=(p=>{if(!p)return null;let u=p.trim();if(u=u.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,"").trim(),!u.startsWith("{")&&u.includes("{")&&u.includes("}")){let m=u.indexOf("{"),I=u.lastIndexOf("}");m>=0&&I>m&&(u=u.slice(m,I+1));}try{return JSON.parse(u)}catch{return null}})(r);if(l&&typeof l=="object"){if(typeof l.title=="string"&&(t.title=l.title),typeof l.intent=="string"&&(t.intent=l.intent),Array.isArray(l.plan)?t.plan=l.plan.map(p=>typeof p=="string"?p:JSON.stringify(p)).join(`
81
+ `):typeof l.plan=="string"&&(t.plan=l.plan),Array.isArray(l.toolCalls)){let p=Be.safeParse(l.toolCalls);p.success?t.toolCalls=p.data:t.toolCalls=[];}if(Array.isArray(l.todoList)){let p=Rt.safeParse(l.todoList);p.success?t.todoList=p.data.map(u=>({...u,createdTimestamp:Date.now(),updatedTimestamp:Date.now()})):a.warn(`OutputParser: TodoList validation failed: ${p.error}`);}}else {let p=r.match(/Title:\s*([\s\S]*?)(Intent:|Plan:|Tool Calls:|Todo List:|$)/i);p&&(t.title=p[1].trim());let u=r.match(/Intent:\s*([\s\S]*?)(Plan:|Tool Calls:|Todo List:|$)/i);u&&(t.intent=u[1].trim());let m=r.match(/Plan:\s*([\s\S]*?)(Tool Calls:|Todo List:|$)/i);m&&(t.plan=m[1].trim());}return t}async parseExecutionOutput(e){let t={},r=e,n=[],s=new fe("think").final(e),i="";s.forEach(l=>{l.matched?n.push(l.data.trim()):i+=l.data;}),n.length>0&&(t.thoughts=n.join(`
82
82
 
83
83
  ---
84
84
 
85
- `)),r=i.trim();let c=r.match(/```json\s*([\s\S]*?)\s*```/);if(c)try{let l=JSON.parse(c[1]);if(Array.isArray(l.toolCalls)){let p=Ke.safeParse(l.toolCalls);p.success&&(t.toolCalls=p.data);}else if(Array.isArray(l)){let p=Ke.safeParse(l);p.success&&(t.toolCalls=p.data);}l.nextStepDecision&&(t.nextStepDecision=l.nextStepDecision),l.updatedPlan&&(t.updatedPlan=l.updatedPlan),l.content?t.content=l.content:t.content=r.replace(c[0],"").trim();}catch(l){a.warn(`Failed to parse JSON block in execution output: ${l}`),t.content=r;}else t.content=r;return t}async parseSynthesisOutput(e){return e.trim()}};var he=class extends V{constructor(e){super(),this.observationRepository=e,a.debug("ObservationSocket initialized.");}notifyObservation(e){a.debug(`Notifying Observation: ${e.id} (${e.type}) for thread ${e.threadId}`),super.notify(e,{targetThreadId:e.threadId},(t,r)=>r?Array.isArray(r)?r.includes(t.type):t.type===r:true);}async getHistory(e,t){if(!this.observationRepository)return a.warn("Cannot getHistory for ObservationSocket: ObservationRepository not configured."),[];if(!t?.threadId)return a.warn("Cannot getHistory for ObservationSocket: threadId is required."),[];a.debug(`Getting history for ObservationSocket: Thread ${t.threadId}, Filter: ${JSON.stringify(e)}, Limit: ${t.limit}`);let r={};e&&(r.types=Array.isArray(e)?e:[e]),t.limit!==void 0&&a.debug(`Limit requested: ${t.limit}. Repository implementation must handle this.`);try{return await this.observationRepository.getObservations(t.threadId,r)}catch(n){return a.error(`Error fetching observation history for thread ${t.threadId} with filter ${JSON.stringify(r)}:`,n),[]}}};var fe=class extends V{constructor(e){super(),this.conversationRepository=e,a.debug("ConversationSocket initialized.");}notifyMessage(e){a.debug(`Notifying Message: ${e.messageId} (${e.role}) for thread ${e.threadId}`),super.notify(e,{targetThreadId:e.threadId},(t,r)=>r?Array.isArray(r)?r.includes(t.role):t.role===r:true);}async getHistory(e,t){if(!this.conversationRepository)return a.warn("Cannot getHistory for ConversationSocket: ConversationRepository not configured."),[];if(!t?.threadId)return a.warn("Cannot getHistory for ConversationSocket: threadId is required."),[];a.debug(`Getting history for ConversationSocket: Thread ${t.threadId}, Filter: ${JSON.stringify(e)}, Limit: ${t.limit}`);let r={};t.limit!==void 0&&(r.limit=t.limit),e&&a.warn("Role filtering requested for ConversationSocket.getHistory, but not directly supported by IConversationRepository.getMessages. Fetching all roles up to limit.");try{return await this.conversationRepository.getMessages(t.threadId,r)}catch(n){return a.error(`Error fetching message history for thread ${t.threadId}:`,n),[]}}};var ye=class{constructor(e,t,r){this.observationSocketInstance=new he(e),this.conversationSocketInstance=new fe(t),this.llmStreamSocketInstance=new Q,this.a2aTaskSocketInstance=new ee(r),a.debug("UISystem initialized with Observation, Conversation, LLM Stream, and A2A Task sockets.");}getObservationSocket(){return this.observationSocketInstance}getConversationSocket(){return this.conversationSocketInstance}getLLMStreamSocket(){return this.llmStreamSocketInstance}getA2ATaskSocket(){return this.a2aTaskSocketInstance}};var Te=class{constructor(){this.strategies=new Map;a.info("AuthManager initialized.");}registerStrategy(e,t){if(!e||e.trim()==="")throw new d("Strategy ID cannot be empty or null","INVALID_CONFIG");this.strategies.has(e)&&a.warn(`AuthManager: Overwriting existing auth strategy with ID: ${e}`),this.strategies.set(e,t),a.debug(`AuthManager: Registered strategy '${e}'.`);}async getHeaders(e){let t=this.strategies.get(e);if(!t)throw e.includes("zyntopia")&&a.error(`AuthManager: Strategy '${e}' not found. Did you register a ZyntopiaOAuthStrategy with the ID 'default_zyntopia_auth'?`),new d(`Authentication strategy with ID '${e}' not found.`,"INVALID_CONFIG");try{return await t.getAuthHeaders()}catch(r){let n=`Failed to get authentication headers from strategy '${e}'`;throw a.error(n,r),new d(n,"LLM_PROVIDER_ERROR",r instanceof Error?r:new Error(String(r)))}}hasStrategy(e){return this.strategies.has(e)}getRegisteredStrategyIds(){return Array.from(this.strategies.keys())}removeStrategy(e){let t=this.strategies.delete(e);return t&&a.debug(`AuthManager: Removed strategy '${e}'.`),t}clearAllStrategies(){let e=this.strategies.size;this.strategies.clear(),a.debug(`AuthManager: Cleared ${e} strategies.`);}async login(e){let t=this.strategies.get(e);if(!t||!t.login)throw new d(`Login not supported for strategy '${e}'.`,"INVALID_CONFIG");await t.login();}async handleRedirect(e){let t=this.strategies.get(e);if(!t||!t.handleRedirect)throw new d(`handleRedirect not supported for strategy '${e}'.`,"INVALID_CONFIG");await t.handleRedirect();}logout(e){let t=this.strategies.get(e);if(!t||!t.logout)throw new d(`Logout not supported for strategy '${e}'.`,"INVALID_CONFIG");t.logout();}async isAuthenticated(e){let t=this.strategies.get(e);return !t||!t.isAuthenticated?false:await t.isAuthenticated()}};var Y=class{constructor(e,t,r){this.card=e,this.toolDefinition=t,this.mcpManager=r,this.schema={name:`mcp_${e.id}_${t.name}`,description:t.description||`Tool ${t.name} from ${e.displayName||e.id}`,inputSchema:t.inputSchema,outputSchema:t.outputSchema},a.debug(`McpProxyTool: Created proxy for tool "${t.name}" from server "${e.displayName}"`);}async execute(e,t){let r=Date.now();try{a.debug(`McpProxyTool: Execution requested for "${this.schema.name}". Getting or creating connection...`);let n=await this.mcpManager.getOrCreateConnection(this.card.id);a.debug(`McpProxyTool: Connection ready. Executing tool "${this.toolDefinition.name}" on server "${this.card.displayName}"`);let o=await n.callTool(this.toolDefinition.name,e),s=Date.now()-r,i=CallToolResultSchema.parse(o),c=typeof i=="object"&&i!==null?i:{value:i};return {callId:t.traceId||"unknown",toolName:this.schema.name,status:"success",output:[c],metadata:{executionTime:s,mcpServer:{id:this.card.id,name:this.card.displayName},rawResponse:o}}}catch(n){let o=Date.now()-r;return a.error(`McpProxyTool: Failed to execute tool "${this.toolDefinition.name}": ${n.message}`),{callId:t.traceId||"unknown",toolName:this.schema.name,status:"error",error:`MCP execution failed: ${n.message}`,metadata:{executionTime:o,mcpServer:{id:this.card.id,name:this.card.displayName},originalError:n instanceof Error?n.stack:String(n)}}}}getOriginalToolName(){return this.toolDefinition.name}getServerConfig(){return {...this.card}}getToolDefinition(){return {...this.toolDefinition}}};var Ae=class{constructor(){this.configKey="art_mcp_config";this.config=this.loadConfig();}loadConfig(){try{let t=localStorage.getItem(this.configKey);if(t){let r=JSON.parse(t),n=this.validateAndFixConfig(r);return JSON.stringify(n)!==JSON.stringify(r)&&(a.info("ConfigManager: Config was automatically validated and fixed"),this.writeConfig(n)),n}}catch(t){a.error(`ConfigManager: Error reading or parsing config from localStorage: ${t.message}`);}a.info("ConfigManager: Configuration not found in localStorage. Creating a new default config.");let e=this.createDefaultConfig();return this.writeConfig(e),e}validateAndFixConfig(e){let t={mcpServers:{}};for(let[r,n]of Object.entries(e.mcpServers)){if(r==="[object Object]"||typeof n!="object"||!n){a.warn(`ConfigManager: Removing corrupted entry: "${r}"`);continue}let o={id:n.id||r,type:n.type||"streamable-http",enabled:n.enabled!==false,displayName:n.displayName||r,description:n.description||`MCP server: ${r}`,connection:n.connection,installation:n.installation,timeout:n.timeout||3e4,tools:n.tools||[],resources:n.resources||[],resourceTemplates:n.resourceTemplates||[]};r==="tavily_search_stdio"&&(!o.tools||o.tools.length===0)&&(o.tools=[{name:"tavily-search",description:"A powerful web search tool that provides comprehensive, real-time results using Tavily's AI search engine.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},search_depth:{type:"string",enum:["basic","advanced"],description:"The depth of the search. It can be 'basic' or 'advanced'",default:"basic"},topic:{type:"string",enum:["general","news"],description:"The category of the search",default:"general"},max_results:{type:"number",description:"The maximum number of search results to return",default:10,minimum:5,maximum:20},include_raw_content:{type:"boolean",description:"Include the cleaned and parsed HTML content of each search result",default:false}},required:["query"]}},{name:"tavily-extract",description:"A powerful web content extraction tool that retrieves and processes raw content from specified URLs.",inputSchema:{type:"object",properties:{urls:{type:"array",items:{type:"string"},description:"List of URLs to extract content from"},extract_depth:{type:"string",enum:["basic","advanced"],description:"Depth of extraction - 'basic' or 'advanced'",default:"basic"},include_images:{type:"boolean",description:"Include a list of images extracted from the urls in the response",default:false}},required:["urls"]}}],a.info("ConfigManager: Added tools definition for Tavily server")),t.mcpServers[r]=o;}return t}createDefaultConfig(){return {mcpServers:{tavily_search_remote:{id:"tavily_search_remote",type:"streamable-http",enabled:true,displayName:"Tavily Search (Remote)",description:"Provides AI-powered search and web content extraction tools via a remote server.",connection:{url:"https://mcp.tavily.com/v1/stream",authStrategyId:"tavily_api_key"},tools:[{name:"tavily-search",description:"A powerful web search tool...",inputSchema:{}},{name:"tavily-extract",description:"A powerful web content extraction tool...",inputSchema:{}}],resources:[],resourceTemplates:[]}}}}writeConfig(e){try{localStorage.setItem(this.configKey,JSON.stringify(e,null,2)),a.debug("ConfigManager: Configuration saved to localStorage.");}catch(t){a.error(`ConfigManager: Failed to write to localStorage: ${t.message}`);}}getConfig(){return this.config}setServerConfig(e,t){this.config.mcpServers[e]=t,this.writeConfig(this.config),a.info(`ConfigManager: Updated configuration for server "${e}"`);}removeServerConfig(e){this.config.mcpServers[e]?(delete this.config.mcpServers[e],this.writeConfig(this.config),a.info(`ConfigManager: Removed configuration for server "${e}"`)):a.warn(`ConfigManager: Attempted to remove non-existent server config "${e}"`);}};function ut(g){let e="";for(let t=0;t<g.length;t++)e+=String.fromCharCode(g[t]);return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}async function bt(g){let e=new TextEncoder().encode(g),t=await crypto.subtle.digest("SHA-256",e);return ut(new Uint8Array(t))}function pt(g=64){let e=new Uint8Array(g);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var De=class{constructor(e){this.oauthConfig=e;this.accessToken=null;this.refreshToken=null;this.expiresAt=null;this.clientId=null;}load(){this.accessToken=sessionStorage.getItem("access_token"),this.refreshToken=sessionStorage.getItem("refresh_token");let e=sessionStorage.getItem("token_expires_at");e&&(this.expiresAt=parseInt(e,10)),this.clientId=localStorage.getItem("mcp_client_id");}setClientId(e){this.clientId=e;}update(e){this.accessToken=e.access_token,e.refresh_token&&(this.refreshToken=e.refresh_token),e.expires_in&&(this.expiresAt=Date.now()+e.expires_in*1e3),sessionStorage.setItem("access_token",this.accessToken||""),this.refreshToken&&sessionStorage.setItem("refresh_token",this.refreshToken),this.expiresAt&&sessionStorage.setItem("token_expires_at",String(this.expiresAt));}clear(){this.accessToken=null,this.refreshToken=null,this.expiresAt=null,sessionStorage.removeItem("access_token"),sessionStorage.removeItem("refresh_token"),sessionStorage.removeItem("token_expires_at");}getAccessToken(){return this.accessToken}needsRefresh(){return this.expiresAt?Date.now()>=this.expiresAt-300*1e3:false}async refresh(){if(!this.refreshToken)throw new Error("No refresh token available");if(!this.oauthConfig.token_endpoint)throw new Error("Missing token endpoint");let e=new URLSearchParams({grant_type:"refresh_token",refresh_token:this.refreshToken});this.clientId&&e.set("client_id",this.clientId);let t=await fetch(this.oauthConfig.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e});if(!t.ok)throw this.clear(),new Error("Token refresh failed");let r=await t.json();this.update(r);}isAuthenticated(){return !!this.accessToken&&(this.expiresAt?this.expiresAt>Date.now():true)}},te=class g{constructor(e,t){this.client=null;this.transport=null;this.oauthDiscovery=null;this.tokenManager=null;this.sessionId=null;this.protocolVersion="2025-06-18";this.baseUrl=new URL(e),this.scopes=t??["read","write"];}static create(e,t){return new g(e,t)}async discoverAuthorizationServer(){if(this.oauthDiscovery)return;let e=new URL("/.well-known/oauth-authorization-server",this.baseUrl).toString(),t=await fetch(e);if(!t.ok)throw new d(`Failed to fetch authorization server metadata from ${e}`,"NETWORK_ERROR");this.oauthDiscovery=await t.json(),sessionStorage.setItem("mcp_oauth_discovery",JSON.stringify(this.oauthDiscovery));}async registerClient(){if(!this.oauthDiscovery?.registration_endpoint){let n=localStorage.getItem("mcp_client_id");if(n)return n;let o="public-"+pt(16);return localStorage.setItem("mcp_client_id",o),o}let e={client_name:"MCP Browser Demo",redirect_uris:[location.origin+"/callback"],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",application_type:"web"},t=await fetch(this.oauthDiscovery.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new d("Client registration failed","EXTERNAL_SERVICE_ERROR");let r=await t.json();return localStorage.setItem("mcp_client_id",r.client_id),r.client_id}async startOAuth(){if(await this.discoverAuthorizationServer(),!this.oauthDiscovery)throw new d("Could not discover OAuth server details.","INVALID_CONFIG");let e=await this.registerClient(),t=ut(crypto.getRandomValues(new Uint8Array(64))),r=await bt(t);sessionStorage.setItem("code_verifier",t);let n=pt(16);sessionStorage.setItem("state",n);let o=new URL(this.oauthDiscovery.authorization_endpoint);o.searchParams.set("response_type","code"),o.searchParams.set("client_id",e),o.searchParams.set("redirect_uri",location.origin+"/callback"),o.searchParams.set("scope",this.scopes.join(" ")),o.searchParams.set("code_challenge",r),o.searchParams.set("code_challenge_method","S256"),o.searchParams.set("state",n),o.searchParams.set("resource",this.baseUrl.toString().replace(/\/$/,"")),window.location.href=o.toString();}async maybeHandleCallback(){let e=new URL(window.location.href);if(!(e.pathname==="/callback"&&(e.searchParams.get("code")||e.searchParams.get("error"))))return false;let r=sessionStorage.getItem("mcp_oauth_discovery");if(r?this.oauthDiscovery=JSON.parse(r):await this.discoverAuthorizationServer(),!this.oauthDiscovery)throw new d("Could not determine OAuth server details for callback.","INVALID_CONFIG");let n=e.searchParams.get("code"),o=e.searchParams.get("state");if(!n)throw new d("Authorization code missing","VALIDATION_ERROR");if(o!==sessionStorage.getItem("state"))throw new d("State mismatch","VALIDATION_ERROR");let s=localStorage.getItem("mcp_client_id")||await this.registerClient(),i=sessionStorage.getItem("code_verifier")||"",c=new URLSearchParams({grant_type:"authorization_code",code:n,code_verifier:i,redirect_uri:location.origin+"/callback",client_id:s});c.set("resource",this.baseUrl.toString().replace(/\/$/,""));let l=await fetch(this.oauthDiscovery.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c});if(!l.ok){let u=await l.json().catch(()=>({}));throw new d("Token exchange failed: "+(u.error_description||u.error||l.status),"EXTERNAL_SERVICE_ERROR")}let p=await l.json();return this.tokenManager=new De(this.oauthDiscovery),this.tokenManager.setClientId(s),this.tokenManager.update(p),sessionStorage.removeItem("code_verifier"),sessionStorage.removeItem("state"),history.replaceState({},"","/"),true}loadExistingSession(){let e=sessionStorage.getItem("mcp_oauth_discovery");e&&(this.oauthDiscovery=JSON.parse(e)),this.tokenManager=new De(this.oauthDiscovery||{}),this.tokenManager.load(),this.sessionId=sessionStorage.getItem("mcp_session_id");}isAuthenticated(){return this.tokenManager?this.tokenManager.isAuthenticated():false}async connect(){if(!this.client){let e=async(t,r)=>{this.tokenManager?.load(),this.tokenManager?.needsRefresh()&&await this.tokenManager.refresh().catch(c=>{a.error("Token refresh failed:",c);});let n=new Headers(r?.headers);n.set("Authorization",`Bearer ${this.tokenManager?.getAccessToken()||""}`),n.set("Accept","application/json, text/event-stream"),n.set("MCP-Protocol-Version",this.protocolVersion),this.sessionId&&n.set("Mcp-Session-Id",this.sessionId);let o={...r,headers:n},s=await fetch(t,o),i=s.headers.get("Mcp-Session-Id");return i&&(this.sessionId=i,sessionStorage.setItem("mcp_session_id",i)),s};this.transport=new StreamableHTTPClientTransport(this.baseUrl,{fetch:e}),this.client=new Client({name:"mcp-browser-demo",version:"1.0.0"}),await this.client.connect(this.transport);}}async ensureConnected(){this.client||await this.connect();}async listTools(){if(!this.client)throw new d("Not connected","NOT_CONNECTED");return (await this.client.listTools()).tools?.map(t=>({name:t.name,description:t.description}))??[]}async callTool(e,t){if(!this.client)throw new d("Not connected","NOT_CONNECTED");try{return await this.client.callTool({name:e,arguments:t})}catch(r){if(String(r?.message||"").includes("401")&&this.tokenManager)return await this.tokenManager.refresh().catch(o=>{throw a.error("Token refresh failed during tool call:",o),r}),await this.client.callTool({name:e,arguments:t});throw r}}async logout(){try{if(this.transport){let e={},t=this.tokenManager?.getAccessToken();t&&(e.Authorization=`Bearer ${t}`),this.sessionId&&(e["Mcp-Session-Id"]=this.sessionId),await fetch(this.baseUrl.toString(),{method:"DELETE",headers:e}).catch(()=>{});}}finally{this.client=null,this.transport=null,this.tokenManager?.clear(),this.sessionId=null,sessionStorage.removeItem("mcp_session_id"),sessionStorage.removeItem("mcp_oauth_discovery");}}};var re=class{constructor(e,t,r){this.activeConnections=new Map;this.configManager=new Ae,this.toolRegistry=e,this.authManager=r,a.info("McpManager: Hub initialized. Will load tools from config catalog.");}async initialize(e){if(!e?.enabled){a.info("McpManager: MCP is disabled. Skipping initialization.");return}a.info("McpManager: Initializing from multiple sources...");let t=this.configManager.getConfig().mcpServers;a.info(`McpManager: Found ${Object.keys(t).length} servers in local config`);let r=[];try{r=await this.discoverAvailableServers(e.discoveryEndpoint),a.info(`McpManager: Discovered ${r.length} servers from discovery API`);}catch(s){a.warn(`McpManager: Discovery API failed, continuing with local config only: ${s.message}`);}let n=new Map;for(let[s,i]of Object.entries(t))n.set(s,i);for(let s of r)n.has(s.id)?a.info(`McpManager: Server "${s.id}" exists in both local config and discovery API. Using local config.`):(n.set(s.id,s),a.info(`McpManager: Added discovered server "${s.id}" to available servers`));let o=0;for(let[,s]of n){if(!s.enabled)continue;let i=s.tools||[];if(Array.isArray(i))for(let c of i){let l=new Y(s,c,this);await this.toolRegistry.registerTool(l),o++;}}a.info(`McpManager: Initialization complete. Registered ${o} proxy tools from ${n.size} total servers.`);}async shutdown(){a.info("McpManager: Shutting down all active connections...");let e=Array.from(this.activeConnections.values()).map(t=>t.logout());await Promise.allSettled(e),this.activeConnections.clear(),a.info("McpManager: Shutdown complete.");}async getOrCreateConnection(e){if(this.activeConnections.has(e)){let i=this.activeConnections.get(e);if(i.isAuthenticated())return await i.ensureConnected(),i}a.info(`McpManager: No active connection for "${e}". Creating one on-demand...`);let t=this.configManager.getConfig().mcpServers[e];if(!t)throw new d(`Configuration for server "${e}" not found.`,"SERVER_NOT_FOUND");if(t.type!=="streamable-http")throw new d(`Unsupported transport type "${t.type}" for server "${e}". Only 'streamable-http' is supported in the browser.`,"UNSUPPORTed_TRANSPORT");let r=t.connection;await this.ensureCorsAccess(r.url);let n=r.oauth?.scopes,o=te.create(r.url,Array.isArray(n)?n:n?[n]:void 0);return await o.maybeHandleCallback()&&a.info(`McpManager: OAuth callback for server "${e}" handled successfully.`),o.loadExistingSession(),o.isAuthenticated()||(await o.startOAuth(),await this.waitForAuth(o,18e4)),await o.connect(),this.activeConnections.set(e,o),a.info(`McpManager: On-demand connection for "${e}" established successfully.`),o}async ensureCorsAccess(e){if(!hasInstall()){if(!install({browser:"auto"})){let o=getInstallUrl();throw alert("ART MCP requires a companion browser extension for CORS. Please install it: "+o),new d("Companion extension not installed.","CORS_EXTENSION_REQUIRED")}throw new d("Companion extension installation started. Please complete it and retry.","CORS_EXTENSION_REQUIRED")}let{hostname:t}=new URL(e),r=await getAllowedInfo();if((!r.enabled||r.type==="specific"&&!r.hosts?.includes(t))&&await requestHosts({hosts:[t]})!=="accept")throw new d(`User did not grant permission for ${t}.`,"CORS_PERMISSION_REQUIRED")}async discoverAvailableServers(e){let t=e||"http://localhost:4200/api/services";a.info(`McpManager: Discovering servers from ${t}...`);try{await this.ensureCorsAccess(t);let r=await fetch(t,{method:"GET",headers:{Accept:"application/json","User-Agent":"ART-Framework-MCP/2.0"},signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Discovery API returned ${r.status}: ${r.statusText}`);let n=await r.json(),s=(Array.isArray(n)?n:n.services||[]).filter(i=>i.service_type==="MCP_SERVICE").map(i=>this.convertServiceToMcpCard(i)).filter(i=>i!==null);return a.info(`McpManager: Successfully discovered ${s.length} MCP servers from discovery API`),s}catch(r){throw a.error(`McpManager: Failed to discover servers from ${t}: ${r.message}`),new d(`Discovery API failed: ${r.message}`,"NETWORK_ERROR")}}convertServiceToMcpCard(e){try{if(!e.id||!e.name||!e.connection)return a.warn("McpManager: Skipping invalid service entry: missing required fields"),null;let t={id:e.id,type:e.connection.type==="sse"?"streamable-http":e.connection.type,enabled:e.enabled!==!1,displayName:e.name,description:e.description||`MCP service: ${e.name}`,connection:e.connection,timeout:e.timeout||1e4,tools:e.tools||[],resources:e.resources||[],resourceTemplates:e.resourceTemplates||[],installation:e.installation};return a.debug(`McpManager: Converted service "${e.id}" to MCPCard`),t}catch(t){return a.warn(`McpManager: Failed to convert service to MCPCard: ${t.message}`),null}}async installServer(e){this.configManager.setServerConfig(e.id,e);try{let t=e.connection;await this.ensureCorsAccess(t.url);let r;try{r=await this.getOrCreateConnection(e.id);}catch(i){return a.warn(`McpManager: Could not connect during install for "${e.id}": ${i?.message||i}. The user may need to complete authentication and retry.`),e}let o=(await r.listTools()||[]).map(i=>({name:i.name,description:i.description})),s={...e,tools:o};this.configManager.setServerConfig(e.id,s);for(let i of o)await this.toolRegistry.registerTool(new Y(s,i,this));return a.info(`McpManager: Installed server "${e.id}" with ${o.length} discovered tool(s).`),s}catch(t){a.warn(`McpManager: Could not complete live discovery during install for "${e.id}": ${t?.message||t}. Falling back to provided tools.`);let r=e.tools||[];for(let n of r)await this.toolRegistry.registerTool(new Y(e,n,this));return e}}async waitForAuth(e,t){let r=Date.now();for(;Date.now()-r<t;){if(e.isAuthenticated())return;await new Promise(n=>setTimeout(n,1e3));}throw new d("Authentication window timed out.","TIMEOUT")}async uninstallServer(e){try{let t=`mcp_${e}_`;this.toolRegistry.unregisterTools&&await this.toolRegistry.unregisterTools(n=>typeof n?.name=="string"&&n.name.startsWith(t));let r=this.activeConnections.get(e);r&&(await r.logout(),this.activeConnections.delete(e)),this.configManager.removeServerConfig(e),a.info(`McpManager: Server "${e}" uninstalled.`);}catch(t){a.warn(`McpManager: Uninstall encountered issues for "${e}": ${t?.message||t}`),this.configManager.removeServerConfig(e);}}};var Se=class{constructor(e){this.agentCache=new Map;this.config={discoveryEndpoint:"https://api.zyntopia.com/a2a/discover",timeoutMs:1e4,enableCaching:true,cacheTtlMs:3e5,...e},a.debug(`AgentDiscoveryService initialized with endpoint: ${this.config.discoveryEndpoint}`);}async discoverAgents(e){let t="all_agents";if(this.config.enableCaching){let r=this.getCachedAgents(t);if(r)return a.debug(`[${e}] Returning ${r.length} cached A2A agents`),r}try{a.debug(`[${e}] Discovering A2A agents from: ${this.config.discoveryEndpoint}`);let r=new AbortController,n=setTimeout(()=>r.abort(),this.config.timeoutMs),o=await fetch(this.config.discoveryEndpoint,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"},signal:r.signal});if(clearTimeout(n),!o.ok)throw new d(`Discovery endpoint returned ${o.status}: ${o.statusText}`,"EXTERNAL_SERVICE_ERROR");let i=(await o.json()).services.filter(l=>l.service_type==="A2A_AGENT"&&l.status==="active");if(i.length===0)return a.warn(`[${e}] No active A2A agents found in discovery response`),[];let c=i.map(l=>this.transformToA2AAgentInfo(l.card_data));return this.config.enableCaching&&this.setCachedAgents(t,c),a.info(`[${e}] Discovered ${c.length} A2A agents: ${c.map(l=>l.agentName).join(", ")}`),c}catch(r){throw r.name==="AbortError"?new d(`Agent discovery request timed out after ${this.config.timeoutMs}ms`,"TIMEOUT"):r instanceof d?r:new d(`Failed to discover A2A agents: ${r.message}`,"EXTERNAL_SERVICE_ERROR",r)}}async findTopAgentsForTask(e,t=3,r){let n=await this.discoverAgents(r);if(n.length===0)return a.warn(`[${r}] No A2A agents available for task type: ${e}`),[];let s=n.map(i=>{let c=i.capabilities||[],l=0,p=[];for(let u of c){let f=u.toLowerCase(),A=e.toLowerCase(),E=0;f===A?E=10:f.includes(A)?E=8:A.includes(f)?E=6:E=this.calculateSemanticScore(f,A),E>0&&(l+=E,p.push(u));}return {agent:i,score:l,matchedCapabilities:p}}).filter(i=>i.score>0).sort((i,c)=>c.score-i.score).slice(0,t);return s.length===0?(a.warn(`[${r}] No suitable A2A agent found for task type: ${e}`),[]):(a.debug(`[${r}] Found ${s.length} candidate agents for task type "${e}":`),s.forEach(i=>{a.debug(` - ${i.agent.agentName} (Score: ${i.score}, Matched: ${i.matchedCapabilities.join(", ")})`);}),s.map(i=>i.agent))}calculateSemanticScore(e,t){let r=[["analysis","analyze"],["analysis","examine"],["analysis","evaluate"],["statistical","statistics"],["data","information"],["research","investigate"],["research","study"],["research","explore"],["medical","health"],["web","online"],["literature","document"],["generation","generate"],["generation","create"],["generation","produce"],["report","document"],["visualization","visual"],["chart","graph"],["computation","compute"],["computation","calculate"],["computation","process"],["mathematical","math"],["algorithm","algorithmic"],["transformation","transform"],["conversion","convert"],["translation","translate"],["validation","validate"],["verification","verify"],["testing","test"]];for(let[i,c]of r)if(e.includes(i)&&t.includes(c)||e.includes(c)&&t.includes(i))return 4;let n=i=>i.replace(/ing$|ed$|er$|tion$|sion$|ment$|ness$|ly$|al$/,""),o=e.split(/[_\s-]/).map(n),s=t.split(/[_\s-]/).map(n);for(let i of o)for(let c of s)if(i.length>3&&c.length>3&&(i.includes(c)||c.includes(i)))return 3;return 0}async findAgentsByCapabilities(e,t){let n=(await this.discoverAgents(t)).filter(o=>e.every(s=>o.capabilities?.some(i=>i.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(i.toLowerCase()))));return a.debug(`[${t}] Found ${n.length} agents matching capabilities: ${e.join(", ")}`),n}clearCache(){this.agentCache.clear(),a.debug("Agent discovery cache cleared");}getCachedAgents(e){let t=this.agentCache.get(e);return t?Date.now()-t.timestamp>this.config.cacheTtlMs?(this.agentCache.delete(e),null):t.agents:null}setCachedAgents(e,t){this.agentCache.set(e,{agents:t,timestamp:Date.now()});}transformToA2AAgentInfo(e){return {agentId:e.id,agentName:e.name,agentType:e.category||"unknown",endpoint:e.endpoint,capabilities:e.capabilities||[],status:"available"}}};var Ie=class{constructor(e,t={}){this.taskRepository=e,this.config={defaultTimeoutMs:t.defaultTimeoutMs??3e4,maxRetries:t.maxRetries??3,retryDelayMs:t.retryDelayMs??1e3,useExponentialBackoff:t.useExponentialBackoff??true,callbackUrl:t.callbackUrl??"http://localhost:3000/api/a2a/callback"},a.debug("TaskDelegationService initialized with config:",this.config);}async delegateTasks(e,t){if(e.length===0)return a.debug(`[${t}] No tasks to delegate`),[];a.info(`[${t}] Starting delegation of ${e.length} A2A task(s)`);let r=[];for(let n of e)try{let o=await this.delegateTask(n,t);o&&r.push(o);}catch(o){a.error(`[${t}] Failed to delegate task ${n.taskId}:`,o);}return a.info(`[${t}] Successfully delegated ${r.length}/${e.length} task(s)`),r}async delegateTask(e,t){a.debug(`[${t}] Delegating task ${e.taskId} of type "${e.payload.taskType}"`);try{let r=e.targetAgent;if(!r)throw new d(`Task ${e.taskId} cannot be delegated without a targetAgent.`,"VALIDATION_ERROR");a.debug(`[${t}] Confirmed target agent "${r.agentName}" for task ${e.taskId}`);let n=await this.submitTaskToAgent(e,r,t),o=Date.now(),s={...e,status:n.status,metadata:{...e.metadata,updatedAt:o,startedAt:n.status==="IN_PROGRESS"?o:e.metadata.startedAt,tags:[...e.metadata.tags||[],"delegated"],delegatedAt:o,estimatedCompletionMs:n.estimatedCompletionMs}};return await this.taskRepository.updateTask(s.taskId,s),a.info(`[${t}] Successfully delegated task ${e.taskId} to agent "${r.agentName}" (status: ${n.status})`),s}catch(r){a.error(`[${t}] Task delegation failed for ${e.taskId}:`,r);try{await this.taskRepository.updateTask(e.taskId,{status:"FAILED",metadata:{...e.metadata,updatedAt:Date.now(),completedAt:Date.now(),tags:[...e.metadata.tags||[],"delegation_failed"]},result:{success:!1,error:`Delegation failed: ${r.message}`,metadata:{errorType:"delegation_error",timestamp:Date.now()}}});}catch(n){a.error(`[${t}] Failed to persist task failure for ${e.taskId}:`,n);}throw r instanceof d?r:new d(`Failed to delegate task ${e.taskId}: ${r.message}`,"DELEGATION_FAILED",r)}}async submitTaskToAgent(e,t,r){if(!t.endpoint)throw new d(`Target agent "${t.agentName}" has no endpoint configured`,"VALIDATION_ERROR");let n=`${t.endpoint.replace(/\/$/,"")}/tasks`,o={taskId:e.taskId,taskType:e.payload.taskType,input:e.payload.input,instructions:e.payload.instructions,parameters:e.payload.parameters,priority:e.priority,sourceAgent:e.sourceAgent,timeoutMs:e.metadata.timeoutMs,maxRetries:e.metadata.maxRetries,callbackUrl:this.generateCallbackUrl(e.taskId),metadata:{traceId:r,submittedAt:Date.now(),sourceTimestamp:e.metadata.createdAt}};a.debug(`[${r}] Submitting task ${e.taskId} to ${n}`);let s=new Error("Unknown error"),i=0;for(;i<=this.config.maxRetries;)try{let c=new AbortController,l=setTimeout(()=>c.abort(),this.config.defaultTimeoutMs),p=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"ART-Framework-A2A/1.0.0","X-Trace-ID":r||"",...t.authentication?.type==="bearer"&&t.authentication.token?{Authorization:`Bearer ${t.authentication.token}`}:{},...t.authentication?.type==="api_key"&&t.authentication.apiKey?{"X-API-Key":t.authentication.apiKey}:{}},body:JSON.stringify(o),signal:c.signal});if(clearTimeout(l),!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);let u=await p.json();if(!u.taskId||!u.status)throw new Error("Invalid response format from remote agent");return a.debug(`[${r}] Task ${e.taskId} submitted successfully to "${t.agentName}" (remote task ID: ${u.taskId})`),u}catch(c){if(s=c,i++,c.name==="AbortError"?a.warn(`[${r}] Task submission timed out for ${e.taskId} (attempt ${i}/${this.config.maxRetries+1})`):a.warn(`[${r}] Task submission failed for ${e.taskId} (attempt ${i}/${this.config.maxRetries+1}):`,c.message),i>this.config.maxRetries)break;let l=this.config.useExponentialBackoff?this.config.retryDelayMs*Math.pow(2,i-1):this.config.retryDelayMs;a.debug(`[${r}] Retrying task submission in ${l}ms...`),await new Promise(p=>setTimeout(p,l));}throw new d(`Failed to submit task ${e.taskId} to agent "${t.agentName}" after ${this.config.maxRetries+1} attempts: ${s.message}`,"EXTERNAL_SERVICE_ERROR",s)}async checkTaskStatus(e,t){if(!e.targetAgent?.endpoint)return a.warn(`[${t}] Cannot check status for task ${e.taskId}: no target agent endpoint`),null;let r=`${e.targetAgent.endpoint.replace(/\/$/,"")}/tasks/${e.taskId}`;try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.config.defaultTimeoutMs),s=await fetch(r,{method:"GET",headers:{"User-Agent":"ART-Framework-A2A/1.0.0","X-Trace-ID":t||"",...e.targetAgent.authentication?.type==="bearer"&&e.targetAgent.authentication.token?{Authorization:`Bearer ${e.targetAgent.authentication.token}`}:{},...e.targetAgent.authentication?.type==="api_key"&&e.targetAgent.authentication.apiKey?{"X-API-Key":e.targetAgent.authentication.apiKey}:{}},signal:n.signal});if(clearTimeout(o),!s.ok){if(s.status===404)return a.warn(`[${t}] Task ${e.taskId} not found on remote agent`),null;throw new Error(`HTTP ${s.status}: ${s.statusText}`)}let i=await s.json();return a.debug(`[${t}] Task ${e.taskId} status: ${i.status}`),i}catch(n){return a.error(`[${t}] Failed to check status for task ${e.taskId}:`,n),null}}async updateTaskFromRemoteStatus(e,t,r){let n=Date.now(),o={...e.metadata,updatedAt:n},s={status:t.status,metadata:o};return t.status==="COMPLETED"&&t.result&&(s.result=t.result,o.completedAt=n),t.status==="FAILED"&&t.error&&(s.result={success:false,error:t.error,metadata:{remoteError:true,timestamp:n}},o.completedAt=n),t.metadata&&Object.assign(o,t.metadata),s.metadata=o,await this.taskRepository.updateTask(e.taskId,s),a.debug(`[${r}] Updated task ${e.taskId} with remote status: ${t.status}`),{...e,...s}}generateCallbackUrl(e){return `${this.config.callbackUrl.replace(/\/$/,"")}/${e}`}async cancelTask(e,t){if(!e.targetAgent?.endpoint)return a.warn(`[${t}] Cannot cancel task ${e.taskId}: no target agent endpoint`),false;let r=`${e.targetAgent.endpoint.replace(/\/$/,"")}/tasks/${e.taskId}`;try{let n=await fetch(r,{method:"DELETE",headers:{"User-Agent":"ART-Framework-A2A/1.0.0","X-Trace-ID":t||"",...e.targetAgent.authentication?.type==="bearer"&&e.targetAgent.authentication.token?{Authorization:`Bearer ${e.targetAgent.authentication.token}`}:{},...e.targetAgent.authentication?.type==="api_key"&&e.targetAgent.authentication.apiKey?{"X-API-Key":e.targetAgent.authentication.apiKey}:{}}});return n.ok?(await this.taskRepository.updateTask(e.taskId,{status:"CANCELLED",metadata:{...e.metadata,updatedAt:Date.now(),completedAt:Date.now()}}),a.info(`[${t}] Successfully cancelled task ${e.taskId}`),!0):(a.warn(`[${t}] Failed to cancel task ${e.taskId}: HTTP ${n.status}`),!1)}catch(n){return a.error(`[${t}] Error cancelling task ${e.taskId}:`,n),false}}};var $e=class{constructor(e){this.storageAdapter=null;this.uiSystem=null;this.conversationRepository=null;this.observationRepository=null;this.stateRepository=null;this.a2aTaskRepository=null;this.conversationManager=null;this.stateManager=null;this.observationManager=null;this.toolRegistry=null;this.providerManager=null;this.reasoningEngine=null;this.outputParser=null;this.systemPromptResolver=null;this.toolSystem=null;this.authManager=null;this.mcpManager=null;this.agentDiscoveryService=null;this.taskDelegationService=null;if(this.config=e,!e.storage)throw new Error("ArtInstanceConfig requires 'storage' configuration.");if(!e.providers)throw new Error("ArtInstanceConfig requires 'providers' configuration.")}async initialize(){if("type"in this.config.storage){let r=this.config.storage;switch(r.type){case "indexedDB":this.storageAdapter=new pe({dbName:r.dbName||"ARTDB",objectStores:r.objectStores||["conversations","observations","state","a2a_tasks"]});break;case "memory":default:this.storageAdapter=new de;break}}else this.storageAdapter=this.config.storage;await this.storageAdapter.init?.(),this.conversationRepository=new Re(this.storageAdapter),this.observationRepository=new Oe(this.storageAdapter),this.stateRepository=new we(this.storageAdapter),this.a2aTaskRepository=new ke(this.storageAdapter),this.uiSystem=new ye(this.observationRepository,this.conversationRepository,this.a2aTaskRepository||void 0),this.conversationManager=new be(this.conversationRepository,this.uiSystem.getConversationSocket());let e=this.config.stateSavingStrategy||"explicit";if(this.stateManager=new ue(this.stateRepository,e),this.observationManager=new Ce(this.observationRepository,this.uiSystem.getObservationSocket()),this.toolRegistry=new ge(this.stateManager),this.config.tools)for(let r of this.config.tools)await this.toolRegistry.registerTool(r);this.providerManager=new ie(this.config.providers),a.info("ProviderManager initialized."),this.reasoningEngine=new xe(this.providerManager);let t=this.config.systemPrompts;if(this.systemPromptResolver=new Pe(t),this.outputParser=new Le,this.toolSystem=new Ne(this.toolRegistry,this.stateManager,this.observationManager),this.config.authConfig?.enabled){if(this.authManager=new Te,this.config.authConfig.strategies)for(let{id:r,strategy:n}of this.config.authConfig.strategies)this.authManager.registerStrategy(r,n);a.info("AuthManager initialized.");}if(this.config.a2aConfig&&(this.agentDiscoveryService=new Se({discoveryEndpoint:this.config.a2aConfig.discoveryEndpoint}),this.taskDelegationService=new Ie(this.a2aTaskRepository,{callbackUrl:this.config.a2aConfig.callbackUrl}),a.info("A2A Services (Discovery, Delegation) initialized.")),this.config.mcpConfig){if(!this.toolRegistry||!this.stateManager)throw new Error("MCP Manager requires ToolRegistry and StateManager to be initialized first.");this.mcpManager=new re(this.toolRegistry,this.stateManager,this.authManager||void 0),await this.mcpManager.initialize(this.config.mcpConfig),a.info("McpManager Hub initialized with local config and Zyntopia discovery.");}}createAgent(){if(!this.stateManager||!this.conversationManager||!this.toolRegistry||!this.reasoningEngine||!this.outputParser||!this.observationManager||!this.toolSystem||!this.providerManager||!this.a2aTaskRepository)throw new Error("AgentFactory not fully initialized. Call initialize() before creating an agent.");let e={stateManager:this.stateManager,conversationManager:this.conversationManager,toolRegistry:this.toolRegistry,reasoningEngine:this.reasoningEngine,outputParser:this.outputParser,observationManager:this.observationManager,toolSystem:this.toolSystem,uiSystem:this.uiSystem,systemPromptResolver:this.systemPromptResolver,a2aTaskRepository:this.a2aTaskRepository,authManager:this.authManager,mcpManager:this.mcpManager,agentDiscoveryService:this.agentDiscoveryService,taskDelegationService:this.taskDelegationService,persona:this.config.persona},t=this.config.agentCore||ce;return new t(e)}getStorageAdapter(){return this.storageAdapter}getUISystem(){return this.uiSystem}getToolRegistry(){return this.toolRegistry}getStateManager(){return this.stateManager}getConversationManager(){return this.conversationManager}getObservationManager(){return this.observationManager}getAuthManager(){return this.authManager}getMcpManager(){return this.mcpManager}};async function Lt(g){let e=new $e(g);await e.initialize();let t=e.createAgent(),r=e.getUISystem(),n=e.getStateManager(),o=e.getConversationManager(),s=e.getToolRegistry(),i=e.getObservationManager(),c=e.getAuthManager();if(!r||!n||!o||!s||!i)throw new Error("Failed to initialize one or more core components within AgentFactory.");return {process:t.process.bind(t),uiSystem:r,stateManager:n,conversationManager:o,toolRegistry:s,observationManager:i,authManager:c}}var Be=class{constructor(e){this.client=null;this.schema="public";this.tables={conversations:"conversations",observations:"observations",state:"state",a2a_tasks:"a2a_tasks"};this.configure(e);}configure(e){this.config=e,e.schema&&(this.schema=e.schema),e.tables&&(this.tables={...this.tables,...e.tables}),this.client=e.client??null;}async init(){if(!this.client)try{let{createClient:e}=await import('@supabase/supabase-js');this.client=e(this.config.url,this.config.apiKey,{db:{schema:this.schema},auth:{persistSession:!1}}),a.info("SupabaseStorageAdapter: Client initialized.");}catch(e){throw a.error("SupabaseStorageAdapter: Failed to initialize client",e),e}}tableForCollection(e){switch(e){case "conversations":return this.tables.conversations;case "observations":return this.tables.observations;case "state":return this.tables.state;case "a2a_tasks":return this.tables.a2a_tasks;default:return e}}async get(e,t){await this.init();let r=this.tableForCollection(e),{data:n,error:o}=await this.client.from(r).select("*").eq("id",t).limit(1).maybeSingle();if(o)throw a.error(`SupabaseStorageAdapter: get error for ${r}/${t}`,o),new Error(o.message);return n?{...n}:null}async set(e,t,r){await this.init();let n=this.tableForCollection(e),o={...r};if(typeof o.id>"u")throw new Error(`SupabaseStorageAdapter: Data for collection '${e}' must have an 'id' property.`);let{error:s}=await this.client.from(n).upsert(o,{onConflict:"id"});if(s)throw a.error(`SupabaseStorageAdapter: set error for ${n}/${t}`,s),new Error(s.message)}async delete(e,t){await this.init();let r=this.tableForCollection(e),{error:n}=await this.client.from(r).delete().eq("id",t);if(n)throw a.error(`SupabaseStorageAdapter: delete error for ${r}/${t}`,n),new Error(n.message)}async query(e,t){await this.init();let r=this.tableForCollection(e),n=this.client.from(r).select("*");if(t?.filter)for(let[l,p]of Object.entries(t.filter))Array.isArray(p)?n=n.in(l,p):p!=null&&(n=n.eq(l,p));if(t?.sort){let[l,p]=Object.entries(t.sort)[0]||[];l&&(n=n.order(l,{ascending:p==="asc"}));}let o=t?.skip||0,s=t?.limit??null;s!==null&&s>=0?n=n.range(o,o+Math.max(0,s)-1):o>0&&(n=n.range(o,o+9999));let{data:i,error:c}=await n;if(c)throw a.error(`SupabaseStorageAdapter: query error for ${r}`,c),new Error(c.message);return (i??[]).map(l=>({...l}))}async clearCollection(e){await this.init();let t=this.tableForCollection(e),{error:r}=await this.client.from(t).delete().neq("id",null);if(r)throw a.error(`SupabaseStorageAdapter: clearCollection error for ${t}`,r),new Error(r.message)}async clearAll(){await this.init();let e=Object.values(this.tables);for(let t of e){let{error:r}=await this.client.from(t).delete().neq("id",null);if(r)throw a.error(`SupabaseStorageAdapter: clearAll error for ${t}`,r),new Error(r.message)}}};var $t=3,Ut=1e3,Gt=3e4,Ft=[503,429,500,502,504];function Ht(g){let e=g?.code||g?.status||g?.error?.code;if(e&&Ft.includes(Number(e)))return true;let t=String(g?.message||g?.error?.message||"").toLowerCase();return t.includes("overloaded")||t.includes("rate limit")||t.includes("temporarily unavailable")||t.includes("503")||t.includes("429")}async function gt(g,e={}){let t=e.maxRetries??$t,r=e.initialDelayMs??Ut,n=e.maxDelayMs??Gt,o;for(let s=0;s<=t;s++)try{return await g()}catch(i){if(o=i,s===t||!Ht(i))throw i;let c=r*Math.pow(2,s),l=Math.random()*.3*c,p=Math.min(c+l,n);e.onRetry&&e.onRetry(i,s+1,p),a.warn(`Gemini API call failed (attempt ${s+1}/${t+1}), retrying in ${Math.round(p)}ms...`,{error:i?.message||i,statusCode:i?.code||i?.status||i?.error?.code}),await new Promise(u=>setTimeout(u,p));}throw o}var Ve=class{constructor(e){this.providerName="gemini";if(!e.apiKey)throw new Error("GeminiAdapter requires an apiKey in options.");this.apiKey=e.apiKey,this.defaultModel=e.model||"gemini-2.5-flash",this.genAI=new GoogleGenAI({apiKey:this.apiKey}),a.debug(`GeminiAdapter initialized with default model: ${this.defaultModel}`);}async call(e,t){let{threadId:r,traceId:n=`gemini-trace-${Date.now()}`,sessionId:o,stream:s,callContext:i,model:c}=t,l=c||this.defaultModel,p;try{p=this.translateToGemini(e);}catch(w){return a.error(`Error translating ArtStandardPrompt to Gemini format: ${w.message}`,{error:w,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:w instanceof Error?w:new Error(String(w)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let u={temperature:t.temperature,maxOutputTokens:t.max_tokens||t.maxOutputTokens,topP:t.top_p||t.topP,topK:t.top_k||t.topK,stopSequences:t.stop||t.stop_sequences||t.stopSequences};Object.keys(u).forEach(w=>u[w]===void 0&&delete u[w]);let f=!!t?.gemini?.thinking?.includeThoughts,A=t?.gemini?.thinking?.thinkingBudget,E=f?{...u,thinkingConfig:{includeThoughts:true,...A!==void 0?{thinkingBudget:A}:{}}}:{...u};a.debug(`Calling Gemini SDK with model ${l}, stream: ${!!s}`,{threadId:r,traceId:n});let M=this.genAI;return async function*(){let w=Date.now(),S,N,C,I;try{if(s){let L=await gt(()=>M.models.generateContentStream({model:l,contents:p,config:E}),{onRetry:(h,T,D)=>{a.info(`Retrying Gemini stream call (attempt ${T})`,{threadId:r,traceId:n,delayMs:D});}});for await(let h of L){I=h,S||(S=Date.now()-w);let D=h?.candidates?.[0]?.content?.parts;if(Array.isArray(D)&&D.length>0)for(let k of D){let x=k?.text;if(!x)continue;let v=!!(k?.thought||k?.metadata?.thought||k?.inlineMetadata?.thought);yield {type:"TOKEN",data:x,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?v?"AGENT_THOUGHT_LLM_THINKING":"AGENT_THOUGHT_LLM_RESPONSE":v?"FINAL_SYNTHESIS_LLM_THINKING":"FINAL_SYNTHESIS_LLM_RESPONSE"};}else {let k=h.text;k&&(yield {type:"TOKEN",data:k,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"});}h.usageMetadata&&(a.debug("Gemini stream chunk usageMetadata:",{usageMetadata:h.usageMetadata,threadId:r,traceId:n}),N={...N||{},...h.usageMetadata});}let R=Date.now()-w;a.debug("Gemini stream finished processing chunks.",{totalGenerationTimeMs:R,threadId:r,traceId:n}),I?(C=I.candidates?.[0]?.finishReason,N=I.usageMetadata,a.debug("Gemini stream - Extracted from last chunk:",{finishReason:C,usageMetadata:N,threadId:r,traceId:n})):a.warn("Gemini stream - No last chunk found after loop.",{threadId:r,traceId:n});let y=N||{};yield {type:"METADATA",data:{stopReason:C,inputTokens:y?.promptTokenCount,outputTokens:y?.candidatesTokenCount,thinkingTokens:y?.thinkingTokenCount??y?.thoughtTokens,timeToFirstTokenMs:S,totalGenerationTimeMs:R,providerRawUsage:y,traceId:n},threadId:r,traceId:n,sessionId:o};}else {let L=await gt(()=>M.models.generateContent({model:l,contents:p,config:E}),{onRetry:(x,v,F)=>{a.info(`Retrying Gemini call (attempt ${v})`,{threadId:r,traceId:n,delayMs:F});}}),R=L.candidates?.[0],y=L.text,O=R?.finishReason,h=L.usageMetadata,T=Date.now()-w,D=R?.content?.parts;if(Array.isArray(D)&&D.length>0)for(let x of D){let v=x?.text;if(!v)continue;let F=!!(x?.thought||x?.metadata?.thought||x?.inlineMetadata?.thought),P=i==="AGENT_THOUGHT"?F?"AGENT_THOUGHT_LLM_THINKING":"AGENT_THOUGHT_LLM_RESPONSE":F?"FINAL_SYNTHESIS_LLM_THINKING":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:v.trim(),threadId:r,traceId:n,sessionId:o,tokenType:P};}else if(!R||!y){if(L.promptFeedback?.blockReason){a.error("Gemini SDK call blocked.",{feedback:L.promptFeedback,threadId:r,traceId:n}),yield {type:"ERROR",data:new Error(`Gemini API call blocked: ${L.promptFeedback.blockReason}`),threadId:r,traceId:n,sessionId:o};return}a.error("Invalid response structure from Gemini SDK: No text content found",{responseData:L,threadId:r,traceId:n}),yield {type:"ERROR",data:new Error("Invalid response structure from Gemini SDK: No text content found."),threadId:r,traceId:n,sessionId:o};return}else {let x=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"LLM_RESPONSE";yield {type:"TOKEN",data:y.trim(),threadId:r,traceId:n,sessionId:o,tokenType:x};}yield {type:"METADATA",data:{stopReason:O,inputTokens:h?.promptTokenCount,outputTokens:h?.candidatesTokenCount,thinkingTokens:h?.thinkingTokenCount??h?.thoughtTokens,totalGenerationTimeMs:T,providerRawUsage:h,traceId:n},threadId:r,traceId:n,sessionId:o};}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(L){a.error(`Error during Gemini SDK call: ${L.message}`,{error:L,threadId:r,traceId:n}),yield {type:"ERROR",data:L instanceof Error?L:new Error(String(L)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}()}translateToGemini(e){let t=[],r=null;for(let n of e){let o,s=[];switch(n.role){case "system":typeof n.content=="string"?r=n.content:a.warn("GeminiAdapter: Ignoring non-string system prompt content.",{content:n.content});continue;case "user":{o="user";let i="";r&&(i+=r+`
85
+ `)),r=i.trim();let c=r.match(/```json\s*([\s\S]*?)\s*```/);if(c)try{let l=JSON.parse(c[1]);if(Array.isArray(l.toolCalls)){let p=Be.safeParse(l.toolCalls);p.success&&(t.toolCalls=p.data);}else if(Array.isArray(l)){let p=Be.safeParse(l);p.success&&(t.toolCalls=p.data);}l.nextStepDecision&&(t.nextStepDecision=l.nextStepDecision),l.updatedPlan&&(t.updatedPlan=l.updatedPlan),l.content?t.content=l.content:t.content=r.replace(c[0],"").trim();}catch(l){a.warn(`Failed to parse JSON block in execution output: ${l}`),t.content=r;}else t.content=r;return t}async parseSynthesisOutput(e){return e.trim()}};var ye=class extends V{constructor(e){super(),this.observationRepository=e,a.debug("ObservationSocket initialized.");}notifyObservation(e){a.debug(`Notifying Observation: ${e.id} (${e.type}) for thread ${e.threadId}`),super.notify(e,{targetThreadId:e.threadId},(t,r)=>r?Array.isArray(r)?r.includes(t.type):t.type===r:true);}async getHistory(e,t){if(!this.observationRepository)return a.warn("Cannot getHistory for ObservationSocket: ObservationRepository not configured."),[];if(!t?.threadId)return a.warn("Cannot getHistory for ObservationSocket: threadId is required."),[];a.debug(`Getting history for ObservationSocket: Thread ${t.threadId}, Filter: ${JSON.stringify(e)}, Limit: ${t.limit}`);let r={};e&&(r.types=Array.isArray(e)?e:[e]),t.limit!==void 0&&a.debug(`Limit requested: ${t.limit}. Repository implementation logic applies.`);try{return await this.observationRepository.getObservations(t.threadId,r)}catch(n){return a.error(`Error fetching observation history for thread ${t.threadId} with filter ${JSON.stringify(r)}:`,n),[]}}};var Te=class extends V{constructor(e){super(),this.conversationRepository=e,a.debug("ConversationSocket initialized.");}notifyMessage(e){a.debug(`Notifying Message: ${e.messageId} (${e.role}) for thread ${e.threadId}`),super.notify(e,{targetThreadId:e.threadId},(t,r)=>r?Array.isArray(r)?r.includes(t.role):t.role===r:true);}async getHistory(e,t){if(!this.conversationRepository)return a.warn("Cannot getHistory for ConversationSocket: ConversationRepository not configured."),[];if(!t?.threadId)return a.warn("Cannot getHistory for ConversationSocket: threadId is required."),[];a.debug(`Getting history for ConversationSocket: Thread ${t.threadId}, Filter: ${JSON.stringify(e)}, Limit: ${t.limit}`);let r={};t.limit!==void 0&&(r.limit=t.limit),e&&a.warn("Role filtering requested for ConversationSocket.getHistory, but not directly supported by IConversationRepository.getMessages. Fetching all roles up to limit.");try{return await this.conversationRepository.getMessages(t.threadId,r)}catch(n){return a.error(`Error fetching message history for thread ${t.threadId}:`,n),[]}}};var Ae=class{constructor(e,t,r){this.observationSocketInstance=new ye(e),this.conversationSocketInstance=new Te(t),this.llmStreamSocketInstance=new te,this.a2aTaskSocketInstance=new re(r),a.debug("UISystem initialized with Observation, Conversation, LLM Stream, and A2A Task sockets.");}getObservationSocket(){return this.observationSocketInstance}getConversationSocket(){return this.conversationSocketInstance}getLLMStreamSocket(){return this.llmStreamSocketInstance}getA2ATaskSocket(){return this.a2aTaskSocketInstance}};var Se=class{constructor(){this.strategies=new Map;a.info("AuthManager initialized.");}registerStrategy(e,t){if(!e||e.trim()==="")throw new d("Strategy ID cannot be empty or null","INVALID_CONFIG");this.strategies.has(e)&&a.warn(`AuthManager: Overwriting existing auth strategy with ID: ${e}`),this.strategies.set(e,t),a.debug(`AuthManager: Registered strategy '${e}'.`);}async getHeaders(e){let t=this.strategies.get(e);if(!t)throw e.includes("zyntopia")&&a.error(`AuthManager: Strategy '${e}' not found. Did you register a ZyntopiaOAuthStrategy with the ID 'default_zyntopia_auth'?`),new d(`Authentication strategy with ID '${e}' not found.`,"INVALID_CONFIG");try{return await t.getAuthHeaders()}catch(r){let n=`Failed to get authentication headers from strategy '${e}'`;throw a.error(n,r),new d(n,"LLM_PROVIDER_ERROR",r instanceof Error?r:new Error(String(r)))}}hasStrategy(e){return this.strategies.has(e)}getRegisteredStrategyIds(){return Array.from(this.strategies.keys())}removeStrategy(e){let t=this.strategies.delete(e);return t&&a.debug(`AuthManager: Removed strategy '${e}'.`),t}clearAllStrategies(){let e=this.strategies.size;this.strategies.clear(),a.debug(`AuthManager: Cleared ${e} strategies.`);}async login(e){let t=this.strategies.get(e);if(!t||!t.login)throw new d(`Login not supported for strategy '${e}'.`,"INVALID_CONFIG");await t.login();}async handleRedirect(e){let t=this.strategies.get(e);if(!t||!t.handleRedirect)throw new d(`handleRedirect not supported for strategy '${e}'.`,"INVALID_CONFIG");await t.handleRedirect();}logout(e){let t=this.strategies.get(e);if(!t||!t.logout)throw new d(`Logout not supported for strategy '${e}'.`,"INVALID_CONFIG");t.logout();}async isAuthenticated(e){let t=this.strategies.get(e);return !t||!t.isAuthenticated?false:await t.isAuthenticated()}};var W=class{constructor(e,t,r){this.card=e,this.toolDefinition=t,this.mcpManager=r,this.schema={name:`mcp_${e.id}_${t.name}`,description:t.description||`Tool ${t.name} from ${e.displayName||e.id}`,inputSchema:t.inputSchema,outputSchema:t.outputSchema},a.debug(`McpProxyTool: Created proxy for tool "${t.name}" from server "${e.displayName}"`);}async execute(e,t){let r=Date.now();try{a.debug(`McpProxyTool: Execution requested for "${this.schema.name}". Getting or creating connection...`);let n=await this.mcpManager.getOrCreateConnection(this.card.id);a.debug(`McpProxyTool: Connection ready. Executing tool "${this.toolDefinition.name}" on server "${this.card.displayName}"`);let o=await n.callTool(this.toolDefinition.name,e),s=Date.now()-r,i=CallToolResultSchema.parse(o),c=typeof i=="object"&&i!==null?i:{value:i};return {callId:t.traceId||"unknown",toolName:this.schema.name,status:"success",output:[c],metadata:{executionTime:s,mcpServer:{id:this.card.id,name:this.card.displayName},rawResponse:o}}}catch(n){let o=Date.now()-r;return a.error(`McpProxyTool: Failed to execute tool "${this.toolDefinition.name}": ${n.message}`),{callId:t.traceId||"unknown",toolName:this.schema.name,status:"error",error:`MCP execution failed: ${n.message}`,metadata:{executionTime:o,mcpServer:{id:this.card.id,name:this.card.displayName},originalError:n instanceof Error?n.stack:String(n)}}}}getOriginalToolName(){return this.toolDefinition.name}getServerConfig(){return {...this.card}}getToolDefinition(){return {...this.toolDefinition}}};var Ie=class{constructor(){this.configKey="art_mcp_config";this.config=this.loadConfig();}loadConfig(){try{let t=localStorage.getItem(this.configKey);if(t){let r=JSON.parse(t),n=this.validateAndFixConfig(r);return JSON.stringify(n)!==JSON.stringify(r)&&(a.info("ConfigManager: Config was automatically validated and fixed"),this.writeConfig(n)),n}}catch(t){a.error(`ConfigManager: Error reading or parsing config from localStorage: ${t.message}`);}a.info("ConfigManager: Configuration not found in localStorage. Creating a new default config.");let e=this.createDefaultConfig();return this.writeConfig(e),e}validateAndFixConfig(e){let t={mcpServers:{}};for(let[r,n]of Object.entries(e.mcpServers)){if(r==="[object Object]"||typeof n!="object"||!n){a.warn(`ConfigManager: Removing corrupted entry: "${r}"`);continue}let o={id:n.id||r,type:n.type||"streamable-http",enabled:n.enabled!==false,displayName:n.displayName||r,description:n.description||`MCP server: ${r}`,connection:n.connection,installation:n.installation,timeout:n.timeout||3e4,tools:n.tools||[],resources:n.resources||[],resourceTemplates:n.resourceTemplates||[]};r==="tavily_search_stdio"&&(!o.tools||o.tools.length===0)&&(o.tools=[{name:"tavily-search",description:"A powerful web search tool that provides comprehensive, real-time results using Tavily's AI search engine.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},search_depth:{type:"string",enum:["basic","advanced"],description:"The depth of the search. It can be 'basic' or 'advanced'",default:"basic"},topic:{type:"string",enum:["general","news"],description:"The category of the search",default:"general"},max_results:{type:"number",description:"The maximum number of search results to return",default:10,minimum:5,maximum:20},include_raw_content:{type:"boolean",description:"Include the cleaned and parsed HTML content of each search result",default:false}},required:["query"]}},{name:"tavily-extract",description:"A powerful web content extraction tool that retrieves and processes raw content from specified URLs.",inputSchema:{type:"object",properties:{urls:{type:"array",items:{type:"string"},description:"List of URLs to extract content from"},extract_depth:{type:"string",enum:["basic","advanced"],description:"Depth of extraction - 'basic' or 'advanced'",default:"basic"},include_images:{type:"boolean",description:"Include a list of images extracted from the urls in the response",default:false}},required:["urls"]}}],a.info("ConfigManager: Added tools definition for Tavily server")),t.mcpServers[r]=o;}return t}createDefaultConfig(){return {mcpServers:{tavily_search_remote:{id:"tavily_search_remote",type:"streamable-http",enabled:true,displayName:"Tavily Search (Remote)",description:"Provides AI-powered search and web content extraction tools via a remote server.",connection:{url:"https://mcp.tavily.com/v1/stream",authStrategyId:"tavily_api_key"},tools:[{name:"tavily-search",description:"A powerful web search tool...",inputSchema:{}},{name:"tavily-extract",description:"A powerful web content extraction tool...",inputSchema:{}}],resources:[],resourceTemplates:[]}}}}writeConfig(e){try{localStorage.setItem(this.configKey,JSON.stringify(e,null,2)),a.debug("ConfigManager: Configuration saved to localStorage.");}catch(t){a.error(`ConfigManager: Failed to write to localStorage: ${t.message}`);}}getConfig(){return this.config}setServerConfig(e,t){this.config.mcpServers[e]=t,this.writeConfig(this.config),a.info(`ConfigManager: Updated configuration for server "${e}"`);}removeServerConfig(e){this.config.mcpServers[e]?(delete this.config.mcpServers[e],this.writeConfig(this.config),a.info(`ConfigManager: Removed configuration for server "${e}"`)):a.warn(`ConfigManager: Attempted to remove non-existent server config "${e}"`);}};function ut(g){let e="";for(let t=0;t<g.length;t++)e+=String.fromCharCode(g[t]);return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}async function bt(g){let e=new TextEncoder().encode(g),t=await crypto.subtle.digest("SHA-256",e);return ut(new Uint8Array(t))}function pt(g=64){let e=new Uint8Array(g);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var $e=class{constructor(e){this.oauthConfig=e;this.accessToken=null;this.refreshToken=null;this.expiresAt=null;this.clientId=null;}load(){this.accessToken=sessionStorage.getItem("access_token"),this.refreshToken=sessionStorage.getItem("refresh_token");let e=sessionStorage.getItem("token_expires_at");e&&(this.expiresAt=parseInt(e,10)),this.clientId=localStorage.getItem("mcp_client_id");}setClientId(e){this.clientId=e;}update(e){this.accessToken=e.access_token,e.refresh_token&&(this.refreshToken=e.refresh_token),e.expires_in&&(this.expiresAt=Date.now()+e.expires_in*1e3),sessionStorage.setItem("access_token",this.accessToken||""),this.refreshToken&&sessionStorage.setItem("refresh_token",this.refreshToken),this.expiresAt&&sessionStorage.setItem("token_expires_at",String(this.expiresAt));}clear(){this.accessToken=null,this.refreshToken=null,this.expiresAt=null,sessionStorage.removeItem("access_token"),sessionStorage.removeItem("refresh_token"),sessionStorage.removeItem("token_expires_at");}getAccessToken(){return this.accessToken}needsRefresh(){return this.expiresAt?Date.now()>=this.expiresAt-300*1e3:false}async refresh(){if(!this.refreshToken)throw new Error("No refresh token available");if(!this.oauthConfig.token_endpoint)throw new Error("Missing token endpoint");let e=new URLSearchParams({grant_type:"refresh_token",refresh_token:this.refreshToken});this.clientId&&e.set("client_id",this.clientId);let t=await fetch(this.oauthConfig.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e});if(!t.ok)throw this.clear(),new Error("Token refresh failed");let r=await t.json();this.update(r);}isAuthenticated(){return !!this.accessToken&&(this.expiresAt?this.expiresAt>Date.now():true)}},ne=class g{constructor(e,t){this.client=null;this.transport=null;this.oauthDiscovery=null;this.tokenManager=null;this.sessionId=null;this.protocolVersion="2025-06-18";this.baseUrl=new URL(e),this.scopes=t??["read","write"];}static create(e,t){return new g(e,t)}async discoverAuthorizationServer(){if(this.oauthDiscovery)return;let e=new URL("/.well-known/oauth-authorization-server",this.baseUrl).toString(),t=await fetch(e);if(!t.ok)throw new d(`Failed to fetch authorization server metadata from ${e}`,"NETWORK_ERROR");this.oauthDiscovery=await t.json(),sessionStorage.setItem("mcp_oauth_discovery",JSON.stringify(this.oauthDiscovery));}async registerClient(){if(!this.oauthDiscovery?.registration_endpoint){let n=localStorage.getItem("mcp_client_id");if(n)return n;let o="public-"+pt(16);return localStorage.setItem("mcp_client_id",o),o}let e={client_name:"MCP Browser Demo",redirect_uris:[location.origin+"/callback"],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",application_type:"web"},t=await fetch(this.oauthDiscovery.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new d("Client registration failed","EXTERNAL_SERVICE_ERROR");let r=await t.json();return localStorage.setItem("mcp_client_id",r.client_id),r.client_id}async startOAuth(){if(await this.discoverAuthorizationServer(),!this.oauthDiscovery)throw new d("Could not discover OAuth server details.","INVALID_CONFIG");let e=await this.registerClient(),t=ut(crypto.getRandomValues(new Uint8Array(64))),r=await bt(t);sessionStorage.setItem("code_verifier",t);let n=pt(16);sessionStorage.setItem("state",n);let o=new URL(this.oauthDiscovery.authorization_endpoint);o.searchParams.set("response_type","code"),o.searchParams.set("client_id",e),o.searchParams.set("redirect_uri",location.origin+"/callback"),o.searchParams.set("scope",this.scopes.join(" ")),o.searchParams.set("code_challenge",r),o.searchParams.set("code_challenge_method","S256"),o.searchParams.set("state",n),o.searchParams.set("resource",this.baseUrl.toString().replace(/\/$/,"")),window.location.href=o.toString();}async maybeHandleCallback(){let e=new URL(window.location.href);if(!(e.pathname==="/callback"&&(e.searchParams.get("code")||e.searchParams.get("error"))))return false;let r=sessionStorage.getItem("mcp_oauth_discovery");if(r?this.oauthDiscovery=JSON.parse(r):await this.discoverAuthorizationServer(),!this.oauthDiscovery)throw new d("Could not determine OAuth server details for callback.","INVALID_CONFIG");let n=e.searchParams.get("code"),o=e.searchParams.get("state");if(!n)throw new d("Authorization code missing","VALIDATION_ERROR");if(o!==sessionStorage.getItem("state"))throw new d("State mismatch","VALIDATION_ERROR");let s=localStorage.getItem("mcp_client_id")||await this.registerClient(),i=sessionStorage.getItem("code_verifier")||"",c=new URLSearchParams({grant_type:"authorization_code",code:n,code_verifier:i,redirect_uri:location.origin+"/callback",client_id:s});c.set("resource",this.baseUrl.toString().replace(/\/$/,""));let l=await fetch(this.oauthDiscovery.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c});if(!l.ok){let u=await l.json().catch(()=>({}));throw new d("Token exchange failed: "+(u.error_description||u.error||l.status),"EXTERNAL_SERVICE_ERROR")}let p=await l.json();return this.tokenManager=new $e(this.oauthDiscovery),this.tokenManager.setClientId(s),this.tokenManager.update(p),sessionStorage.removeItem("code_verifier"),sessionStorage.removeItem("state"),history.replaceState({},"","/"),true}loadExistingSession(){let e=sessionStorage.getItem("mcp_oauth_discovery");e&&(this.oauthDiscovery=JSON.parse(e)),this.tokenManager=new $e(this.oauthDiscovery||{}),this.tokenManager.load(),this.sessionId=sessionStorage.getItem("mcp_session_id");}isAuthenticated(){return this.tokenManager?this.tokenManager.isAuthenticated():false}async connect(){if(!this.client){let e=async(t,r)=>{this.tokenManager?.load(),this.tokenManager?.needsRefresh()&&await this.tokenManager.refresh().catch(c=>{a.error("Token refresh failed:",c);});let n=new Headers(r?.headers);n.set("Authorization",`Bearer ${this.tokenManager?.getAccessToken()||""}`),n.set("Accept","application/json, text/event-stream"),n.set("MCP-Protocol-Version",this.protocolVersion),this.sessionId&&n.set("Mcp-Session-Id",this.sessionId);let o={...r,headers:n},s=await fetch(t,o),i=s.headers.get("Mcp-Session-Id");return i&&(this.sessionId=i,sessionStorage.setItem("mcp_session_id",i)),s};this.transport=new StreamableHTTPClientTransport(this.baseUrl,{fetch:e}),this.client=new Client({name:"mcp-browser-demo",version:"1.0.0"}),await this.client.connect(this.transport);}}async ensureConnected(){this.client||await this.connect();}async listTools(){if(!this.client)throw new d("Not connected","NOT_CONNECTED");return (await this.client.listTools()).tools?.map(t=>({name:t.name,description:t.description}))??[]}async callTool(e,t){if(!this.client)throw new d("Not connected","NOT_CONNECTED");try{return await this.client.callTool({name:e,arguments:t})}catch(r){if(String(r?.message||"").includes("401")&&this.tokenManager)return await this.tokenManager.refresh().catch(o=>{throw a.error("Token refresh failed during tool call:",o),r}),await this.client.callTool({name:e,arguments:t});throw r}}async logout(){try{if(this.transport){let e={},t=this.tokenManager?.getAccessToken();t&&(e.Authorization=`Bearer ${t}`),this.sessionId&&(e["Mcp-Session-Id"]=this.sessionId),await fetch(this.baseUrl.toString(),{method:"DELETE",headers:e}).catch(()=>{});}}finally{this.client=null,this.transport=null,this.tokenManager?.clear(),this.sessionId=null,sessionStorage.removeItem("mcp_session_id"),sessionStorage.removeItem("mcp_oauth_discovery");}}};var oe=class{constructor(e,t,r){this.activeConnections=new Map;this.configManager=new Ie,this.toolRegistry=e,this.authManager=r,a.info("McpManager: Hub initialized. Will load tools from config catalog.");}async initialize(e){if(!e?.enabled){a.info("McpManager: MCP is disabled. Skipping initialization.");return}a.info("McpManager: Initializing from multiple sources...");let t=this.configManager.getConfig().mcpServers;a.info(`McpManager: Found ${Object.keys(t).length} servers in local config`);let r=[];try{r=await this.discoverAvailableServers(e.discoveryEndpoint),a.info(`McpManager: Discovered ${r.length} servers from discovery API`);}catch(s){a.warn(`McpManager: Discovery API failed, continuing with local config only: ${s.message}`);}let n=new Map;for(let[s,i]of Object.entries(t))n.set(s,i);for(let s of r)n.has(s.id)?a.info(`McpManager: Server "${s.id}" exists in both local config and discovery API. Using local config.`):(n.set(s.id,s),a.info(`McpManager: Added discovered server "${s.id}" to available servers`));let o=0;for(let[,s]of n){if(!s.enabled)continue;let i=s.tools||[];if(Array.isArray(i))for(let c of i){let l=new W(s,c,this);await this.toolRegistry.registerTool(l),o++;}}a.info(`McpManager: Initialization complete. Registered ${o} proxy tools from ${n.size} total servers.`);}async shutdown(){a.info("McpManager: Shutting down all active connections...");let e=Array.from(this.activeConnections.values()).map(t=>t.logout());await Promise.allSettled(e),this.activeConnections.clear(),a.info("McpManager: Shutdown complete.");}async getOrCreateConnection(e){if(this.activeConnections.has(e)){let i=this.activeConnections.get(e);if(i.isAuthenticated())return await i.ensureConnected(),i}a.info(`McpManager: No active connection for "${e}". Creating one on-demand...`);let t=this.configManager.getConfig().mcpServers[e];if(!t)throw new d(`Configuration for server "${e}" not found.`,"SERVER_NOT_FOUND");if(t.type!=="streamable-http")throw new d(`Unsupported transport type "${t.type}" for server "${e}". Only 'streamable-http' is supported in the browser.`,"UNSUPPORTed_TRANSPORT");let r=t.connection;await this.ensureCorsAccess(r.url);let n=r.oauth?.scopes,o=ne.create(r.url,Array.isArray(n)?n:n?[n]:void 0);return await o.maybeHandleCallback()&&a.info(`McpManager: OAuth callback for server "${e}" handled successfully.`),o.loadExistingSession(),o.isAuthenticated()||(await o.startOAuth(),await this.waitForAuth(o,18e4)),await o.connect(),this.activeConnections.set(e,o),a.info(`McpManager: On-demand connection for "${e}" established successfully.`),o}async ensureCorsAccess(e){if(!hasInstall()){if(!install({browser:"auto"})){let o=getInstallUrl();throw alert("ART MCP requires a companion browser extension for CORS. Please install it: "+o),new d("Companion extension not installed.","CORS_EXTENSION_REQUIRED")}throw new d("Companion extension installation started. Please complete it and retry.","CORS_EXTENSION_REQUIRED")}let{hostname:t}=new URL(e),r=await getAllowedInfo();if((!r.enabled||r.type==="specific"&&!r.hosts?.includes(t))&&await requestHosts({hosts:[t]})!=="accept")throw new d(`User did not grant permission for ${t}.`,"CORS_PERMISSION_REQUIRED")}async discoverAvailableServers(e){let t=e||"http://localhost:4200/api/services";a.info(`McpManager: Discovering servers from ${t}...`);try{await this.ensureCorsAccess(t);let r=await fetch(t,{method:"GET",headers:{Accept:"application/json","User-Agent":"ART-Framework-MCP/2.0"},signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Discovery API returned ${r.status}: ${r.statusText}`);let n=await r.json(),s=(Array.isArray(n)?n:n.services||[]).filter(i=>i.service_type==="MCP_SERVICE").map(i=>this.convertServiceToMcpCard(i)).filter(i=>i!==null);return a.info(`McpManager: Successfully discovered ${s.length} MCP servers from discovery API`),s}catch(r){throw a.error(`McpManager: Failed to discover servers from ${t}: ${r.message}`),new d(`Discovery API failed: ${r.message}`,"NETWORK_ERROR")}}convertServiceToMcpCard(e){try{if(!e.id||!e.name||!e.connection)return a.warn("McpManager: Skipping invalid service entry: missing required fields"),null;let t={id:e.id,type:e.connection.type==="sse"?"streamable-http":e.connection.type,enabled:e.enabled!==!1,displayName:e.name,description:e.description||`MCP service: ${e.name}`,connection:e.connection,timeout:e.timeout||1e4,tools:e.tools||[],resources:e.resources||[],resourceTemplates:e.resourceTemplates||[],installation:e.installation};return a.debug(`McpManager: Converted service "${e.id}" to MCPCard`),t}catch(t){return a.warn(`McpManager: Failed to convert service to MCPCard: ${t.message}`),null}}async installServer(e){this.configManager.setServerConfig(e.id,e);try{let t=e.connection;await this.ensureCorsAccess(t.url);let r;try{r=await this.getOrCreateConnection(e.id);}catch(i){return a.warn(`McpManager: Could not connect during install for "${e.id}": ${i?.message||i}. The user may need to complete authentication and retry.`),e}let o=(await r.listTools()||[]).map(i=>({name:i.name,description:i.description})),s={...e,tools:o};this.configManager.setServerConfig(e.id,s);for(let i of o)await this.toolRegistry.registerTool(new W(s,i,this));return a.info(`McpManager: Installed server "${e.id}" with ${o.length} discovered tool(s).`),s}catch(t){a.warn(`McpManager: Could not complete live discovery during install for "${e.id}": ${t?.message||t}. Falling back to provided tools.`);let r=e.tools||[];for(let n of r)await this.toolRegistry.registerTool(new W(e,n,this));return e}}async waitForAuth(e,t){let r=Date.now();for(;Date.now()-r<t;){if(e.isAuthenticated())return;await new Promise(n=>setTimeout(n,1e3));}throw new d("Authentication window timed out.","TIMEOUT")}async uninstallServer(e){try{let t=`mcp_${e}_`;this.toolRegistry.unregisterTools&&await this.toolRegistry.unregisterTools(n=>typeof n?.name=="string"&&n.name.startsWith(t));let r=this.activeConnections.get(e);r&&(await r.logout(),this.activeConnections.delete(e)),this.configManager.removeServerConfig(e),a.info(`McpManager: Server "${e}" uninstalled.`);}catch(t){a.warn(`McpManager: Uninstall encountered issues for "${e}": ${t?.message||t}`),this.configManager.removeServerConfig(e);}}};var _e=class{constructor(e){this.agentCache=new Map;this.config={discoveryEndpoint:"https://api.zyntopia.com/a2a/discover",timeoutMs:1e4,enableCaching:true,cacheTtlMs:3e5,...e},a.debug(`AgentDiscoveryService initialized with endpoint: ${this.config.discoveryEndpoint}`);}async discoverAgents(e){let t="all_agents";if(this.config.enableCaching){let r=this.getCachedAgents(t);if(r)return a.debug(`[${e}] Returning ${r.length} cached A2A agents`),r}try{a.debug(`[${e}] Discovering A2A agents from: ${this.config.discoveryEndpoint}`);let r=new AbortController,n=setTimeout(()=>r.abort(),this.config.timeoutMs),o=await fetch(this.config.discoveryEndpoint,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"},signal:r.signal});if(clearTimeout(n),!o.ok)throw new d(`Discovery endpoint returned ${o.status}: ${o.statusText}`,"EXTERNAL_SERVICE_ERROR");let i=(await o.json()).services.filter(l=>l.service_type==="A2A_AGENT"&&l.status==="active");if(i.length===0)return a.warn(`[${e}] No active A2A agents found in discovery response`),[];let c=i.map(l=>this.transformToA2AAgentInfo(l.card_data));return this.config.enableCaching&&this.setCachedAgents(t,c),a.info(`[${e}] Discovered ${c.length} A2A agents: ${c.map(l=>l.agentName).join(", ")}`),c}catch(r){throw r.name==="AbortError"?new d(`Agent discovery request timed out after ${this.config.timeoutMs}ms`,"TIMEOUT"):r instanceof d?r:new d(`Failed to discover A2A agents: ${r.message}`,"EXTERNAL_SERVICE_ERROR",r)}}async findTopAgentsForTask(e,t=3,r){let n=await this.discoverAgents(r);if(n.length===0)return a.warn(`[${r}] No A2A agents available for task type: ${e}`),[];let s=n.map(i=>{let c=i.capabilities||[],l=0,p=[];for(let u of c){let m=u.toLowerCase(),I=e.toLowerCase(),v=0;m===I?v=10:m.includes(I)?v=8:I.includes(m)?v=6:v=this.calculateSemanticScore(m,I),v>0&&(l+=v,p.push(u));}return {agent:i,score:l,matchedCapabilities:p}}).filter(i=>i.score>0).sort((i,c)=>c.score-i.score).slice(0,t);return s.length===0?(a.warn(`[${r}] No suitable A2A agent found for task type: ${e}`),[]):(a.debug(`[${r}] Found ${s.length} candidate agents for task type "${e}":`),s.forEach(i=>{a.debug(` - ${i.agent.agentName} (Score: ${i.score}, Matched: ${i.matchedCapabilities.join(", ")})`);}),s.map(i=>i.agent))}calculateSemanticScore(e,t){let r=[["analysis","analyze"],["analysis","examine"],["analysis","evaluate"],["statistical","statistics"],["data","information"],["research","investigate"],["research","study"],["research","explore"],["medical","health"],["web","online"],["literature","document"],["generation","generate"],["generation","create"],["generation","produce"],["report","document"],["visualization","visual"],["chart","graph"],["computation","compute"],["computation","calculate"],["computation","process"],["mathematical","math"],["algorithm","algorithmic"],["transformation","transform"],["conversion","convert"],["translation","translate"],["validation","validate"],["verification","verify"],["testing","test"]];for(let[i,c]of r)if(e.includes(i)&&t.includes(c)||e.includes(c)&&t.includes(i))return 4;let n=i=>i.replace(/ing$|ed$|er$|tion$|sion$|ment$|ness$|ly$|al$/,""),o=e.split(/[_\s-]/).map(n),s=t.split(/[_\s-]/).map(n);for(let i of o)for(let c of s)if(i.length>3&&c.length>3&&(i.includes(c)||c.includes(i)))return 3;return 0}async findAgentsByCapabilities(e,t){let n=(await this.discoverAgents(t)).filter(o=>e.every(s=>o.capabilities?.some(i=>i.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(i.toLowerCase()))));return a.debug(`[${t}] Found ${n.length} agents matching capabilities: ${e.join(", ")}`),n}clearCache(){this.agentCache.clear(),a.debug("Agent discovery cache cleared");}getCachedAgents(e){let t=this.agentCache.get(e);return t?Date.now()-t.timestamp>this.config.cacheTtlMs?(this.agentCache.delete(e),null):t.agents:null}setCachedAgents(e,t){this.agentCache.set(e,{agents:t,timestamp:Date.now()});}transformToA2AAgentInfo(e){return {agentId:e.id,agentName:e.name,agentType:e.category||"unknown",endpoint:e.endpoint,capabilities:e.capabilities||[],status:"available"}}};var Ee=class{constructor(e,t={}){this.taskRepository=e,this.config={defaultTimeoutMs:t.defaultTimeoutMs??3e4,maxRetries:t.maxRetries??3,retryDelayMs:t.retryDelayMs??1e3,useExponentialBackoff:t.useExponentialBackoff??true,callbackUrl:t.callbackUrl??"http://localhost:3000/api/a2a/callback"},a.debug("TaskDelegationService initialized with config:",this.config);}async delegateTasks(e,t){if(e.length===0)return a.debug(`[${t}] No tasks to delegate`),[];a.info(`[${t}] Starting delegation of ${e.length} A2A task(s)`);let r=[];for(let n of e)try{let o=await this.delegateTask(n,t);o&&r.push(o);}catch(o){a.error(`[${t}] Failed to delegate task ${n.taskId}:`,o);}return a.info(`[${t}] Successfully delegated ${r.length}/${e.length} task(s)`),r}async delegateTask(e,t){a.debug(`[${t}] Delegating task ${e.taskId} of type "${e.payload.taskType}"`);try{let r=e.targetAgent;if(!r)throw new d(`Task ${e.taskId} cannot be delegated without a targetAgent.`,"VALIDATION_ERROR");a.debug(`[${t}] Confirmed target agent "${r.agentName}" for task ${e.taskId}`);let n=await this.submitTaskToAgent(e,r,t),o=Date.now(),s={...e,status:n.status,metadata:{...e.metadata,updatedAt:o,startedAt:n.status==="IN_PROGRESS"?o:e.metadata.startedAt,tags:[...e.metadata.tags||[],"delegated"],delegatedAt:o,estimatedCompletionMs:n.estimatedCompletionMs}};return await this.taskRepository.updateTask(s.taskId,s),a.info(`[${t}] Successfully delegated task ${e.taskId} to agent "${r.agentName}" (status: ${n.status})`),s}catch(r){a.error(`[${t}] Task delegation failed for ${e.taskId}:`,r);try{await this.taskRepository.updateTask(e.taskId,{status:"FAILED",metadata:{...e.metadata,updatedAt:Date.now(),completedAt:Date.now(),tags:[...e.metadata.tags||[],"delegation_failed"]},result:{success:!1,error:`Delegation failed: ${r.message}`,metadata:{errorType:"delegation_error",timestamp:Date.now()}}});}catch(n){a.error(`[${t}] Failed to persist task failure for ${e.taskId}:`,n);}throw r instanceof d?r:new d(`Failed to delegate task ${e.taskId}: ${r.message}`,"DELEGATION_FAILED",r)}}async submitTaskToAgent(e,t,r){if(!t.endpoint)throw new d(`Target agent "${t.agentName}" has no endpoint configured`,"VALIDATION_ERROR");let n=`${t.endpoint.replace(/\/$/,"")}/tasks`,o={taskId:e.taskId,taskType:e.payload.taskType,input:e.payload.input,instructions:e.payload.instructions,parameters:e.payload.parameters,priority:e.priority,sourceAgent:e.sourceAgent,timeoutMs:e.metadata.timeoutMs,maxRetries:e.metadata.maxRetries,callbackUrl:this.generateCallbackUrl(e.taskId),metadata:{traceId:r,submittedAt:Date.now(),sourceTimestamp:e.metadata.createdAt}};a.debug(`[${r}] Submitting task ${e.taskId} to ${n}`);let s=new Error("Unknown error"),i=0;for(;i<=this.config.maxRetries;)try{let c=new AbortController,l=setTimeout(()=>c.abort(),this.config.defaultTimeoutMs),p=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"ART-Framework-A2A/1.0.0","X-Trace-ID":r||"",...t.authentication?.type==="bearer"&&t.authentication.token?{Authorization:`Bearer ${t.authentication.token}`}:{},...t.authentication?.type==="api_key"&&t.authentication.apiKey?{"X-API-Key":t.authentication.apiKey}:{}},body:JSON.stringify(o),signal:c.signal});if(clearTimeout(l),!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);let u=await p.json();if(!u.taskId||!u.status)throw new Error("Invalid response format from remote agent");return a.debug(`[${r}] Task ${e.taskId} submitted successfully to "${t.agentName}" (remote task ID: ${u.taskId})`),u}catch(c){if(s=c,i++,c.name==="AbortError"?a.warn(`[${r}] Task submission timed out for ${e.taskId} (attempt ${i}/${this.config.maxRetries+1})`):a.warn(`[${r}] Task submission failed for ${e.taskId} (attempt ${i}/${this.config.maxRetries+1}):`,c.message),i>this.config.maxRetries)break;let l=this.config.useExponentialBackoff?this.config.retryDelayMs*Math.pow(2,i-1):this.config.retryDelayMs;a.debug(`[${r}] Retrying task submission in ${l}ms...`),await new Promise(p=>setTimeout(p,l));}throw new d(`Failed to submit task ${e.taskId} to agent "${t.agentName}" after ${this.config.maxRetries+1} attempts: ${s.message}`,"EXTERNAL_SERVICE_ERROR",s)}async checkTaskStatus(e,t){if(!e.targetAgent?.endpoint)return a.warn(`[${t}] Cannot check status for task ${e.taskId}: no target agent endpoint`),null;let r=`${e.targetAgent.endpoint.replace(/\/$/,"")}/tasks/${e.taskId}`;try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.config.defaultTimeoutMs),s=await fetch(r,{method:"GET",headers:{"User-Agent":"ART-Framework-A2A/1.0.0","X-Trace-ID":t||"",...e.targetAgent.authentication?.type==="bearer"&&e.targetAgent.authentication.token?{Authorization:`Bearer ${e.targetAgent.authentication.token}`}:{},...e.targetAgent.authentication?.type==="api_key"&&e.targetAgent.authentication.apiKey?{"X-API-Key":e.targetAgent.authentication.apiKey}:{}},signal:n.signal});if(clearTimeout(o),!s.ok){if(s.status===404)return a.warn(`[${t}] Task ${e.taskId} not found on remote agent`),null;throw new Error(`HTTP ${s.status}: ${s.statusText}`)}let i=await s.json();return a.debug(`[${t}] Task ${e.taskId} status: ${i.status}`),i}catch(n){return a.error(`[${t}] Failed to check status for task ${e.taskId}:`,n),null}}async updateTaskFromRemoteStatus(e,t,r){let n=Date.now(),o={...e.metadata,updatedAt:n},s={status:t.status,metadata:o};return t.status==="COMPLETED"&&t.result&&(s.result=t.result,o.completedAt=n),t.status==="FAILED"&&t.error&&(s.result={success:false,error:t.error,metadata:{remoteError:true,timestamp:n}},o.completedAt=n),t.metadata&&Object.assign(o,t.metadata),s.metadata=o,await this.taskRepository.updateTask(e.taskId,s),a.debug(`[${r}] Updated task ${e.taskId} with remote status: ${t.status}`),{...e,...s}}generateCallbackUrl(e){return `${this.config.callbackUrl.replace(/\/$/,"")}/${e}`}async cancelTask(e,t){if(!e.targetAgent?.endpoint)return a.warn(`[${t}] Cannot cancel task ${e.taskId}: no target agent endpoint`),false;let r=`${e.targetAgent.endpoint.replace(/\/$/,"")}/tasks/${e.taskId}`;try{let n=await fetch(r,{method:"DELETE",headers:{"User-Agent":"ART-Framework-A2A/1.0.0","X-Trace-ID":t||"",...e.targetAgent.authentication?.type==="bearer"&&e.targetAgent.authentication.token?{Authorization:`Bearer ${e.targetAgent.authentication.token}`}:{},...e.targetAgent.authentication?.type==="api_key"&&e.targetAgent.authentication.apiKey?{"X-API-Key":e.targetAgent.authentication.apiKey}:{}}});return n.ok?(await this.taskRepository.updateTask(e.taskId,{status:"CANCELLED",metadata:{...e.metadata,updatedAt:Date.now(),completedAt:Date.now()}}),a.info(`[${t}] Successfully cancelled task ${e.taskId}`),!0):(a.warn(`[${t}] Failed to cancel task ${e.taskId}: HTTP ${n.status}`),!1)}catch(n){return a.error(`[${t}] Error cancelling task ${e.taskId}:`,n),false}}};var Ue=class{constructor(e){this.storageAdapter=null;this.uiSystem=null;this.conversationRepository=null;this.observationRepository=null;this.stateRepository=null;this.a2aTaskRepository=null;this.conversationManager=null;this.stateManager=null;this.observationManager=null;this.toolRegistry=null;this.providerManager=null;this.reasoningEngine=null;this.outputParser=null;this.systemPromptResolver=null;this.toolSystem=null;this.authManager=null;this.mcpManager=null;this.agentDiscoveryService=null;this.taskDelegationService=null;if(this.config=e,!e.storage)throw new Error("ArtInstanceConfig requires 'storage' configuration.");if(!e.providers)throw new Error("ArtInstanceConfig requires 'providers' configuration.")}async initialize(){if("type"in this.config.storage){let r=this.config.storage;switch(r.type){case "indexedDB":this.storageAdapter=new ge({dbName:r.dbName||"ARTDB",objectStores:r.objectStores||["conversations","observations","state","a2a_tasks"]});break;case "memory":default:this.storageAdapter=new ue;break}}else this.storageAdapter=this.config.storage;await this.storageAdapter.init?.(),this.conversationRepository=new Oe(this.storageAdapter),this.observationRepository=new we(this.storageAdapter),this.stateRepository=new ke(this.storageAdapter),this.a2aTaskRepository=new be(this.storageAdapter),this.uiSystem=new Ae(this.observationRepository,this.conversationRepository,this.a2aTaskRepository||void 0),this.conversationManager=new Me(this.conversationRepository,this.uiSystem.getConversationSocket());let e=this.config.stateSavingStrategy||"explicit";if(this.stateManager=new me(this.stateRepository,e),this.observationManager=new Ne(this.observationRepository,this.uiSystem.getObservationSocket()),this.toolRegistry=new he(this.stateManager),this.config.tools)for(let r of this.config.tools)await this.toolRegistry.registerTool(r);this.providerManager=new ce(this.config.providers),a.info("ProviderManager initialized."),this.reasoningEngine=new Le(this.providerManager);let t=this.config.systemPrompts;if(this.systemPromptResolver=new xe(t),this.outputParser=new De,this.toolSystem=new Pe(this.toolRegistry,this.stateManager,this.observationManager),this.config.authConfig?.enabled){if(this.authManager=new Se,this.config.authConfig.strategies)for(let{id:r,strategy:n}of this.config.authConfig.strategies)this.authManager.registerStrategy(r,n);a.info("AuthManager initialized.");}if(this.config.a2aConfig&&(this.agentDiscoveryService=new _e({discoveryEndpoint:this.config.a2aConfig.discoveryEndpoint}),this.taskDelegationService=new Ee(this.a2aTaskRepository,{callbackUrl:this.config.a2aConfig.callbackUrl}),a.info("A2A Services (Discovery, Delegation) initialized.")),this.config.mcpConfig){if(!this.toolRegistry||!this.stateManager)throw new Error("MCP Manager requires ToolRegistry and StateManager to be initialized first.");this.mcpManager=new oe(this.toolRegistry,this.stateManager,this.authManager||void 0),await this.mcpManager.initialize(this.config.mcpConfig),a.info("McpManager Hub initialized with local config and Zyntopia discovery.");}}createAgent(){if(!this.stateManager||!this.conversationManager||!this.toolRegistry||!this.reasoningEngine||!this.outputParser||!this.observationManager||!this.toolSystem||!this.providerManager||!this.a2aTaskRepository)throw new Error("AgentFactory not fully initialized. Call initialize() before creating an agent.");let e={stateManager:this.stateManager,conversationManager:this.conversationManager,toolRegistry:this.toolRegistry,reasoningEngine:this.reasoningEngine,outputParser:this.outputParser,observationManager:this.observationManager,toolSystem:this.toolSystem,uiSystem:this.uiSystem,systemPromptResolver:this.systemPromptResolver,a2aTaskRepository:this.a2aTaskRepository,authManager:this.authManager,mcpManager:this.mcpManager,agentDiscoveryService:this.agentDiscoveryService,taskDelegationService:this.taskDelegationService,persona:this.config.persona},t=this.config.agentCore||pe;return new t(e)}getStorageAdapter(){return this.storageAdapter}getUISystem(){return this.uiSystem}getToolRegistry(){return this.toolRegistry}getStateManager(){return this.stateManager}getConversationManager(){return this.conversationManager}getObservationManager(){return this.observationManager}getAuthManager(){return this.authManager}getMcpManager(){return this.mcpManager}};async function Lt(g){let e=new Ue(g);await e.initialize();let t=e.createAgent(),r=e.getUISystem(),n=e.getStateManager(),o=e.getConversationManager(),s=e.getToolRegistry(),i=e.getObservationManager(),c=e.getAuthManager();if(!r||!n||!o||!s||!i)throw new Error("Failed to initialize one or more core components within AgentFactory.");return {process:t.process.bind(t),uiSystem:r,stateManager:n,conversationManager:o,toolRegistry:s,observationManager:i,authManager:c}}var Ve=class{constructor(e){this.client=null;this.schema="public";this.tables={conversations:"conversations",observations:"observations",state:"state",a2a_tasks:"a2a_tasks"};this.configure(e);}configure(e){this.config=e,e.schema&&(this.schema=e.schema),e.tables&&(this.tables={...this.tables,...e.tables}),this.client=e.client??null;}async init(){if(!this.client)try{let{createClient:e}=await import('@supabase/supabase-js');this.client=e(this.config.url,this.config.apiKey,{db:{schema:this.schema},auth:{persistSession:!1}}),a.info("SupabaseStorageAdapter: Client initialized.");}catch(e){throw a.error("SupabaseStorageAdapter: Failed to initialize client",e),e}}tableForCollection(e){switch(e){case "conversations":return this.tables.conversations;case "observations":return this.tables.observations;case "state":return this.tables.state;case "a2a_tasks":return this.tables.a2a_tasks;default:return e}}async get(e,t){await this.init();let r=this.tableForCollection(e),{data:n,error:o}=await this.client.from(r).select("*").eq("id",t).limit(1).maybeSingle();if(o)throw a.error(`SupabaseStorageAdapter: get error for ${r}/${t}`,o),new Error(o.message);return n?{...n}:null}async set(e,t,r){await this.init();let n=this.tableForCollection(e),o={...r};if(typeof o.id>"u")throw new Error(`SupabaseStorageAdapter: Data for collection '${e}' must have an 'id' property.`);let{error:s}=await this.client.from(n).upsert(o,{onConflict:"id"});if(s)throw a.error(`SupabaseStorageAdapter: set error for ${n}/${t}`,s),new Error(s.message)}async delete(e,t){await this.init();let r=this.tableForCollection(e),{error:n}=await this.client.from(r).delete().eq("id",t);if(n)throw a.error(`SupabaseStorageAdapter: delete error for ${r}/${t}`,n),new Error(n.message)}async query(e,t){await this.init();let r=this.tableForCollection(e),n=this.client.from(r).select("*");if(t?.filter)for(let[l,p]of Object.entries(t.filter))Array.isArray(p)?n=n.in(l,p):p!=null&&(n=n.eq(l,p));if(t?.sort){let[l,p]=Object.entries(t.sort)[0]||[];l&&(n=n.order(l,{ascending:p==="asc"}));}let o=t?.skip||0,s=t?.limit??null;s!==null&&s>=0?n=n.range(o,o+Math.max(0,s)-1):o>0&&(n=n.range(o,o+9999));let{data:i,error:c}=await n;if(c)throw a.error(`SupabaseStorageAdapter: query error for ${r}`,c),new Error(c.message);return (i??[]).map(l=>({...l}))}async clearCollection(e){await this.init();let t=this.tableForCollection(e),{error:r}=await this.client.from(t).delete().neq("id",null);if(r)throw a.error(`SupabaseStorageAdapter: clearCollection error for ${t}`,r),new Error(r.message)}async clearAll(){await this.init();let e=Object.values(this.tables);for(let t of e){let{error:r}=await this.client.from(t).delete().neq("id",null);if(r)throw a.error(`SupabaseStorageAdapter: clearAll error for ${t}`,r),new Error(r.message)}}};var $t=3,Ut=1e3,Gt=3e4,Ft=[503,429,500,502,504];function Ht(g){let e=g?.code||g?.status||g?.error?.code;if(e&&Ft.includes(Number(e)))return true;let t=String(g?.message||g?.error?.message||"").toLowerCase();return t.includes("overloaded")||t.includes("rate limit")||t.includes("temporarily unavailable")||t.includes("503")||t.includes("429")}async function gt(g,e={}){let t=e.maxRetries??$t,r=e.initialDelayMs??Ut,n=e.maxDelayMs??Gt,o;for(let s=0;s<=t;s++)try{return await g()}catch(i){if(o=i,s===t||!Ht(i))throw i;let c=r*Math.pow(2,s),l=Math.random()*.3*c,p=Math.min(c+l,n);e.onRetry&&e.onRetry(i,s+1,p),a.warn(`Gemini API call failed (attempt ${s+1}/${t+1}), retrying in ${Math.round(p)}ms...`,{error:i?.message||i,statusCode:i?.code||i?.status||i?.error?.code}),await new Promise(u=>setTimeout(u,p));}throw o}var je=class{constructor(e){this.providerName="gemini";if(!e.apiKey)throw new Error("GeminiAdapter requires an apiKey in options.");this.apiKey=e.apiKey,this.defaultModel=e.model||"gemini-3-flash",this.genAI=new GoogleGenAI({apiKey:this.apiKey,apiVersion:e.apiVersion}),a.debug(`GeminiAdapter initialized with default model: ${this.defaultModel}`);}async call(e,t){let{threadId:r,traceId:n=`gemini-trace-${Date.now()}`,sessionId:o,stream:s,callContext:i,model:c}=t,l=c||this.defaultModel,p,u;try{let T=this.translateToGemini(e);p=T.contents,u=T.systemInstruction;}catch(T){return a.error(`Error translating ArtStandardPrompt to Gemini format: ${T.message}`,{error:T,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:T instanceof Error?T:new Error(String(T)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let m={temperature:t.temperature,maxOutputTokens:t.max_tokens||t.maxOutputTokens,topP:t.top_p||t.topP,topK:t.top_k||t.topK,stopSequences:t.stop||t.stop_sequences||t.stopSequences};Object.keys(m).forEach(T=>m[T]===void 0&&delete m[T]);let I=t?.gemini?.thinking,v=!!I?.includeThoughts,C=I?.thinkingBudget,h=I?.thinkingLevel,R=v?{...m,thinkingConfig:{includeThoughts:true,...C!==void 0?{thinkingBudget:C}:{},...h!==void 0?{thinkingLevel:h}:{}}}:{...m},O={model:l,contents:p,config:R};u&&(O.systemInstruction=u),a.debug(`Calling Gemini SDK with model ${l}, stream: ${!!s}`,{threadId:r,traceId:n});let x=this.genAI;return async function*(){let T=Date.now(),D,k,_,w;try{if(s){let f=await gt(()=>x.models.generateContentStream(O),{onRetry:(y,S,$)=>{a.info(`Retrying Gemini stream call (attempt ${S})`,{threadId:r,traceId:n,delayMs:$});}});for await(let y of f){w=y,D||(D=Date.now()-T);let $=y?.candidates?.[0]?.content?.parts;if(Array.isArray($)&&$.length>0)for(let K of $){let U=K?.text;if(!U)continue;let z=!!(K?.thought||K?.metadata?.thought||K?.inlineMetadata?.thought);yield {type:"TOKEN",data:U,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?z?"AGENT_THOUGHT_LLM_THINKING":"AGENT_THOUGHT_LLM_RESPONSE":z?"FINAL_SYNTHESIS_LLM_THINKING":"FINAL_SYNTHESIS_LLM_RESPONSE"};}else {let K=y.text;K&&(yield {type:"TOKEN",data:K,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"});}y.usageMetadata&&(a.debug("Gemini stream chunk usageMetadata:",{usageMetadata:y.usageMetadata,threadId:r,traceId:n}),k={...k||{},...y.usageMetadata});}let A=Date.now()-T;a.debug("Gemini stream finished processing chunks.",{totalGenerationTimeMs:A,threadId:r,traceId:n}),w?(_=w.candidates?.[0]?.finishReason,k=w.usageMetadata,a.debug("Gemini stream - Extracted from last chunk:",{finishReason:_,usageMetadata:k,threadId:r,traceId:n})):a.warn("Gemini stream - No last chunk found after loop.",{threadId:r,traceId:n});let M=k||{};yield {type:"METADATA",data:{stopReason:_,inputTokens:M?.promptTokenCount,outputTokens:M?.candidatesTokenCount,thinkingTokens:M?.thinkingTokenCount??M?.thoughtTokens,timeToFirstTokenMs:D,totalGenerationTimeMs:A,providerRawUsage:M,traceId:n},threadId:r,traceId:n,sessionId:o};}else {let f=await gt(()=>x.models.generateContent(O),{onRetry:(U,z,X)=>{a.info(`Retrying Gemini call (attempt ${z})`,{threadId:r,traceId:n,delayMs:X});}}),A=f.candidates?.[0],M=f.text,N=A?.finishReason,y=f.usageMetadata,S=Date.now()-T,$=A?.content?.parts;if(Array.isArray($)&&$.length>0)for(let U of $){let z=U?.text;if(!z)continue;let X=!!(U?.thought||U?.metadata?.thought||U?.inlineMetadata?.thought),L=i==="AGENT_THOUGHT"?X?"AGENT_THOUGHT_LLM_THINKING":"AGENT_THOUGHT_LLM_RESPONSE":X?"FINAL_SYNTHESIS_LLM_THINKING":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:z.trim(),threadId:r,traceId:n,sessionId:o,tokenType:L};}else if(!A||!M){if(f.promptFeedback?.blockReason){a.error("Gemini SDK call blocked.",{feedback:f.promptFeedback,threadId:r,traceId:n}),yield {type:"ERROR",data:new Error(`Gemini API call blocked: ${f.promptFeedback.blockReason}`),threadId:r,traceId:n,sessionId:o};return}a.error("Invalid response structure from Gemini SDK: No text content found",{responseData:f,threadId:r,traceId:n}),yield {type:"ERROR",data:new Error("Invalid response structure from Gemini SDK: No text content found."),threadId:r,traceId:n,sessionId:o};return}else {let U=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"LLM_RESPONSE";yield {type:"TOKEN",data:M.trim(),threadId:r,traceId:n,sessionId:o,tokenType:U};}yield {type:"METADATA",data:{stopReason:N,inputTokens:y?.promptTokenCount,outputTokens:y?.candidatesTokenCount,thinkingTokens:y?.thinkingTokenCount??y?.thoughtTokens,totalGenerationTimeMs:S,providerRawUsage:y,traceId:n},threadId:r,traceId:n,sessionId:o};}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(f){a.error(`Error during Gemini SDK call: ${f.message}`,{error:f,threadId:r,traceId:n}),yield {type:"ERROR",data:f instanceof Error?f:new Error(String(f)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}()}translateToGemini(e){let t=[],r;for(let n of e){let o,s=[];switch(n.role){case "system":typeof n.content=="string"?r=(r?r+`
86
86
 
87
- `,r=null),typeof n.content=="string"?i+=n.content:(a.warn("GeminiAdapter: Stringifying non-string user content.",{content:n.content}),i+=JSON.stringify(n.content)),s.push({text:i});break}case "assistant":o="model",typeof n.content=="string"&&n.content.trim()!==""&&s.push({text:n.content}),n.tool_calls&&n.tool_calls.length>0&&n.tool_calls.forEach(i=>{i.type==="function"?s.push({functionCall:{name:i.function.name,args:JSON.parse(i.function.arguments||"{}")}}):a.warn(`GeminiAdapter: Skipping unsupported tool call type: ${i.type}`);}),s.length===0&&s.push({text:""});break;case "tool_result":if(o="user",!n.tool_call_id||!n.name)throw new d("GeminiAdapter: 'tool_result' message missing required 'tool_call_id' or 'name'.","PROMPT_TRANSLATION_FAILED");s.push({functionResponse:{name:n.name,response:{content:n.content}}});break;case "tool_request":a.debug("GeminiAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls.");continue;default:a.warn(`GeminiAdapter: Skipping message with unhandled role: ${n.role}`);continue}t.push({role:o,parts:s});}return r&&(a.warn("GeminiAdapter: System prompt provided but no user message found to merge it into. Adding as a separate initial user message."),t.unshift({role:"user",parts:[{text:r}]})),t.length>0&&t[0].role==="model"&&(a.warn("Gemini conversation history starts with 'model' role. Prepending a dummy 'user' turn.",{firstRole:t[0].role}),t.unshift({role:"user",parts:[{text:"(Initial context)"}]})),t}};var Kt="gpt-4o",Bt=4096,Vt=.7,je=class{constructor(e){this.providerName="openai";if(!e.apiKey)throw new d("OpenAIAdapter requires an apiKey in options.","INVALID_CONFIG");this.client=new qt({apiKey:e.apiKey,baseURL:e.apiBaseUrl||void 0}),this.defaultModel=e.model||Kt,this.defaultMaxTokens=e.defaultMaxTokens||Bt,this.defaultTemperature=e.defaultTemperature||Vt,a.debug(`OpenAIAdapter initialized with model: ${this.defaultModel}`);}async call(e,t){let{threadId:r,traceId:n=`openai-trace-${Date.now()}`,sessionId:o,stream:s=false,callContext:i,model:c,tools:l,providerConfig:p}=t,u=p?.modelId||c||this.defaultModel,f=p?.adapterOptions||{},A=f.max_tokens||f.maxTokens||t.max_tokens||t.maxOutputTokens||this.defaultMaxTokens,E=f.temperature??t.temperature??this.defaultTemperature,M=t.openai||{},m=M.reasoning?.effort||"medium",w=M.reasoning?.summary||"auto",S,N;try{let R=this.translateToResponsesFormat(e);S=R.systemPrompt,N=R.input;}catch(R){a.error(`Error translating ArtStandardPrompt to OpenAI Responses format: ${R.message}`,{error:R,threadId:r,traceId:n});let y=R instanceof d?R:new d(`Prompt translation failed: ${R.message}`,"PROMPT_TRANSLATION_FAILED",R);return async function*(){yield {type:"ERROR",data:y,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let C=l?this.translateArtToolsToOpenAI(l):void 0,I={model:u,input:N,instructions:S,temperature:E,max_output_tokens:A,stream:s,store:true,reasoning:{effort:m,summary:w},tools:C};return Object.keys(I).forEach(R=>{let y=R;I[y]===void 0&&delete I[y];}),a.debug(`Calling OpenAI Responses API with model ${u}`,{stream:s,tools:!!C,threadId:r,traceId:n}),async function*(){try{let R=Date.now(),y;if(s){let O=await this.client.responses.create({...I,stream:!0}),h="",T="",D,k,x=[];for await(let P of O)if(y===void 0&&(y=Date.now()-R),P.type==="response.reasoning.delta"||P.type==="response.reasoning_text.delta"){if(P.delta){T+=P.delta;let U=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:P.delta,threadId:r,traceId:n,sessionId:o,tokenType:U};}}else if(P.type==="response.reasoning_summary.delta"||P.type==="response.reasoning_summary_text.delta"){if(P.delta){let U=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:P.delta,threadId:r,traceId:n,sessionId:o,tokenType:U};}}else if(P.type==="response.text.delta"||P.type==="response.output_text.delta"){if(P.delta){h+=P.delta;let U=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:P.delta,threadId:r,traceId:n,sessionId:o,tokenType:U};}}else if(P.type==="response.output_item.added"){if(P.item){if(P.item.type==="text"&&P.item.text){let U=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:P.item.text,threadId:r,traceId:n,sessionId:o,tokenType:U};}else if(P.item.type==="reasoning"&&P.item.text){let U=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:P.item.text,threadId:r,traceId:n,sessionId:o,tokenType:U};}else if(P.item.type==="message"&&P.item.content){for(let U of P.item.content)if(U.type==="output_text"&&U.text){let Ee=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:U.text,threadId:r,traceId:n,sessionId:o,tokenType:Ee};}}}}else if(P.type==="response.done"||P.type==="response.completed")P.response?.usage&&(k=P.response.usage),P.response?.status&&(D=P.response.status==="completed"?"stop":P.response.status);else if(P.type==="response.error"||P.type==="error"){let U=P.error?.message||P.message||"Unknown OpenAI Responses API error";throw new d(`OpenAI Responses API Error: ${U}`,"LLM_PROVIDER_ERROR",new Error(U))}let v=Date.now()-R;yield {type:"METADATA",data:{inputTokens:k?.input_tokens,outputTokens:k?.output_tokens,thinkingTokens:k?.output_tokens_details?.reasoning_tokens,stopReason:D,timeToFirstTokenMs:y,totalGenerationTimeMs:v,providerRawUsage:k,traceId:n},threadId:r,traceId:n,sessionId:o};}else {let O=await this.client.responses.create({...I,stream:!1});a.debug(`OpenAI Responses API call successful (non-streaming). Status: ${O.status}`,{threadId:r,traceId:n});let h="",T="",D=[];if(O.output&&Array.isArray(O.output)){for(let k of O.output)if(k.type==="message"&&k.content)for(let x of k.content)x.type==="output_text"&&(h+=x.text);else if(k.type==="reasoning"&&k.summary)for(let x of k.summary)x.type==="summary_text"&&(T+=x.text);}if(T.trim()){let k=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:T.trim(),threadId:r,traceId:n,sessionId:o,tokenType:k};}if(h.trim()){let k=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:h.trim(),threadId:r,traceId:n,sessionId:o,tokenType:k};}if(D.length>0&&(yield {type:"TOKEN",data:D.map(v=>({type:"tool_use",id:v.id,name:v.name,input:v.input})),threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"}),O.usage){let k=Date.now()-R;yield {type:"METADATA",data:{inputTokens:O.usage.input_tokens,outputTokens:O.usage.output_tokens,thinkingTokens:O.usage.output_tokens_details?.reasoning_tokens,stopReason:O.status==="completed"?"stop":O.status,totalGenerationTimeMs:k,providerRawUsage:{usage:O.usage,status:O.status},traceId:n},threadId:r,traceId:n,sessionId:o};}}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(R){a.error(`Error during OpenAI Responses API call: ${R.message}`,{error:R,threadId:r,traceId:n}),yield {type:"ERROR",data:R instanceof d?R:R instanceof Error&&R.message.includes("OpenAI")?new d(`OpenAI API Error: ${R.message}`,"LLM_PROVIDER_ERROR",R):new d(R.message||"Unknown OpenAI adapter error","LLM_PROVIDER_ERROR",R),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}.bind(this)()}async shutdown(){a.debug("OpenAIAdapter shutdown called.");}translateToResponsesFormat(e){let t,r=[];for(let n of e){if(n.role==="system"){let s=typeof n.content=="string"?n.content:String(n.content);t?(a.warn("OpenAIAdapter: Multiple system messages found. Appending to existing system prompt."),t+=`
87
+ `:"")+n.content:a.warn("GeminiAdapter: Ignoring non-string system prompt content.",{content:n.content});continue;case "user":{o="user";let i="";typeof n.content=="string"?i=n.content:(a.warn("GeminiAdapter: Stringifying non-string user content.",{content:n.content}),i=JSON.stringify(n.content)),s.push({text:i});break}case "assistant":o="model",typeof n.content=="string"&&n.content.trim()!==""&&s.push({text:n.content}),n.tool_calls&&n.tool_calls.length>0&&n.tool_calls.forEach(i=>{i.type==="function"?s.push({functionCall:{name:i.function.name,args:JSON.parse(i.function.arguments||"{}")}}):a.warn(`GeminiAdapter: Skipping unsupported tool call type: ${i.type}`);}),s.length===0&&s.push({text:""});break;case "tool_result":if(o="user",!n.tool_call_id||!n.name)throw new d("GeminiAdapter: 'tool_result' message missing required 'tool_call_id' or 'name'.","PROMPT_TRANSLATION_FAILED");s.push({functionResponse:{name:n.name,response:{content:n.content}}});break;case "tool_request":a.debug("GeminiAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls.");continue;default:a.warn(`GeminiAdapter: Skipping message with unhandled role: ${n.role}`);continue}t.push({role:o,parts:s});}return t.length>0&&t[0].role==="model"&&(a.warn("Gemini conversation history starts with 'model' role. Prepending a dummy 'user' turn.",{firstRole:t[0].role}),t.unshift({role:"user",parts:[{text:"(Initial context)"}]})),{contents:t,systemInstruction:r}}};var Kt="gpt-5.2-instant",Bt=4096,Vt=.7,ze=class{constructor(e){this.providerName="openai";if(!e.apiKey)throw new d("OpenAIAdapter requires an apiKey in options.","INVALID_CONFIG");this.client=new qt({apiKey:e.apiKey,baseURL:e.apiBaseUrl||void 0}),this.defaultModel=e.model||Kt,this.defaultMaxTokens=e.defaultMaxTokens||Bt,this.defaultTemperature=e.defaultTemperature||Vt,a.debug(`OpenAIAdapter initialized with model: ${this.defaultModel}`);}async call(e,t){let{threadId:r,traceId:n=`openai-trace-${Date.now()}`,sessionId:o,stream:s=false,callContext:i,model:c,tools:l,providerConfig:p}=t,u=p?.modelId||c||this.defaultModel,m=p?.adapterOptions||{},I=m.max_tokens||m.maxTokens||t.max_tokens||t.maxOutputTokens||this.defaultMaxTokens,v=m.temperature??t.temperature??this.defaultTemperature,C=t.openai||{},h=C.reasoning?.effort||"medium",R=C.reasoning?.summary||"auto",O,x;try{let k=this.translateToResponsesFormat(e);O=k.systemPrompt,x=k.input;}catch(k){a.error(`Error translating ArtStandardPrompt to OpenAI Responses format: ${k.message}`,{error:k,threadId:r,traceId:n});let _=k instanceof d?k:new d(`Prompt translation failed: ${k.message}`,"PROMPT_TRANSLATION_FAILED",k);return async function*(){yield {type:"ERROR",data:_,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let P=l?this.translateArtToolsToOpenAI(l):void 0,T={model:u,input:x,instructions:O,temperature:v,max_output_tokens:I,stream:s,store:true,reasoning:{effort:h,summary:R},tools:P};return Object.keys(T).forEach(k=>{let _=k;T[_]===void 0&&delete T[_];}),a.debug(`Calling OpenAI Responses API with model ${u}`,{stream:s,tools:!!P,threadId:r,traceId:n}),async function*(){try{let k=Date.now(),_;if(s){let w=await this.client.responses.create({...T,stream:!0}),f,A;for await(let y of w)if(_===void 0&&(_=Date.now()-k),y.type==="response.reasoning.delta"||y.type==="response.reasoning_text.delta"){if(y.delta){let S=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:y.delta,threadId:r,traceId:n,sessionId:o,tokenType:S};}}else if(y.type==="response.reasoning_summary.delta"||y.type==="response.reasoning_summary_text.delta"){if(y.delta){let S=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:y.delta,threadId:r,traceId:n,sessionId:o,tokenType:S};}}else if(y.type==="response.text.delta"||y.type==="response.output_text.delta"){if(y.delta){let S=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:y.delta,threadId:r,traceId:n,sessionId:o,tokenType:S};}}else if(y.type==="response.output_item.added"){if(y.item){if(y.item.type==="text"&&y.item.text){let S=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:y.item.text,threadId:r,traceId:n,sessionId:o,tokenType:S};}else if(y.item.type==="reasoning"&&y.item.text){let S=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:y.item.text,threadId:r,traceId:n,sessionId:o,tokenType:S};}else if(y.item.type==="message"&&y.item.content){for(let S of y.item.content)if(S.type==="output_text"&&S.text){let $=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:S.text,threadId:r,traceId:n,sessionId:o,tokenType:$};}}}}else if(y.type==="response.done"||y.type==="response.completed")y.response?.usage&&(A=y.response.usage),y.response?.status&&(f=y.response.status==="completed"?"stop":y.response.status);else if(y.type==="response.error"||y.type==="error"){let S=y.error?.message||y.message||"Unknown OpenAI Responses API error";throw new d(`OpenAI Responses API Error: ${S}`,"LLM_PROVIDER_ERROR",new Error(S))}let M=Date.now()-k;yield {type:"METADATA",data:{inputTokens:A?.input_tokens,outputTokens:A?.output_tokens,thinkingTokens:A?.output_tokens_details?.reasoning_tokens,stopReason:f,timeToFirstTokenMs:_,totalGenerationTimeMs:M,providerRawUsage:A,traceId:n},threadId:r,traceId:n,sessionId:o};}else {let w=await this.client.responses.create({...T,stream:!1});a.debug(`OpenAI Responses API call successful (non-streaming). Status: ${w.status}`,{threadId:r,traceId:n});let f="",A="",M=[];if(w.output&&Array.isArray(w.output)){for(let N of w.output)if(N.type==="message"&&N.content)for(let y of N.content)y.type==="output_text"&&(f+=y.text);else if(N.type==="reasoning"&&N.summary)for(let y of N.summary)y.type==="summary_text"&&(A+=y.text);}if(A.trim()){let N=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:A.trim(),threadId:r,traceId:n,sessionId:o,tokenType:N};}if(f.trim()){let N=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:f.trim(),threadId:r,traceId:n,sessionId:o,tokenType:N};}if(M.length>0&&(yield {type:"TOKEN",data:M.map(S=>({type:"tool_use",id:S.id,name:S.name,input:S.input})),threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"}),w.usage){let N=Date.now()-k;yield {type:"METADATA",data:{inputTokens:w.usage.input_tokens,outputTokens:w.usage.output_tokens,thinkingTokens:w.usage.output_tokens_details?.reasoning_tokens,stopReason:w.status==="completed"?"stop":w.status,totalGenerationTimeMs:N,providerRawUsage:{usage:w.usage,status:w.status},traceId:n},threadId:r,traceId:n,sessionId:o};}}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(k){a.error(`Error during OpenAI Responses API call: ${k.message}`,{error:k,threadId:r,traceId:n}),yield {type:"ERROR",data:k instanceof d?k:k instanceof Error&&k.message.includes("OpenAI")?new d(`OpenAI API Error: ${k.message}`,"LLM_PROVIDER_ERROR",k):new d(k.message||"Unknown OpenAI adapter error","LLM_PROVIDER_ERROR",k),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}.bind(this)()}async shutdown(){a.debug("OpenAIAdapter shutdown called.");}translateToResponsesFormat(e){let t,r=[];for(let n of e){if(n.role==="system"){let s=typeof n.content=="string"?n.content:String(n.content);t?(a.warn("OpenAIAdapter: Multiple system messages found. Appending to existing system prompt."),t+=`
88
88
  ${s}`):t=s;continue}let o=this.mapArtMessageToResponsesContent(n);o&&r.push(o);}return {systemPrompt:t,input:r}}mapArtMessageToResponsesContent(e){switch(e.role){case "user":case "tool_result":{let t=[];if(e.role==="tool_result"){let r=`Tool result for ${e.name||"unknown tool"}: ${String(e.content)}`;t.push({type:"input_text",text:r});}else {let r=typeof e.content=="string"?e.content:String(e.content);t.push({type:"input_text",text:r});}return {role:"user",content:t}}case "assistant":{let t=[];if(typeof e.content=="string"&&e.content.trim()!==""&&t.push({type:"output_text",text:e.content}),e.tool_calls&&e.tool_calls.length>0){let r=e.tool_calls.map(n=>{try{let o=JSON.parse(n.function.arguments||"{}");return `Called tool ${n.function.name} with arguments: ${JSON.stringify(o)}`}catch(o){throw new d(`OpenAIAdapter: Failed to parse tool call arguments for tool ${n.function.name} (ID: ${n.id}). Arguments must be valid JSON. Error: ${o.message}`,"PROMPT_TRANSLATION_FAILED",o)}}).join(`
89
89
  `);t.length>0?t[0].text+=`
90
90
 
91
- `+r:t.push({type:"output_text",text:r});}return t.length===0&&t.push({type:"output_text",text:""}),{role:"assistant",content:t}}case "tool_request":return a.debug("OpenAIAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls."),null;default:return a.warn(`OpenAIAdapter: Skipping message with unhandled role: ${e.role}`),null}}translateArtToolsToOpenAI(e){return e.map(t=>{if(!t.inputSchema||typeof t.inputSchema!="object")throw new d(`Invalid inputSchema definition for tool '${t.name}'. Expected a JSON schema object.`,"INVALID_CONFIG");return {type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}})}};var jt="claude-3-7-sonnet-20250219",zt=4096,ze=class{constructor(e){this.providerName="anthropic";if(!e.apiKey)throw new d("AnthropicAdapter requires an apiKey in options.","INVALID_CONFIG");this.client=new Anthropic({apiKey:e.apiKey,baseURL:e.apiBaseUrl||void 0}),this.defaultModel=e.model||jt,this.defaultMaxTokens=e.defaultMaxTokens||zt,this.defaultTemperature=e.defaultTemperature,a.debug(`AnthropicAdapter initialized with model: ${this.defaultModel}`);}async call(e,t){let{threadId:r,traceId:n=`anthropic-trace-${Date.now()}`,sessionId:o,stream:s=false,callContext:i,model:c,tools:l,providerConfig:p}=t,u=p?.modelId||c||this.defaultModel,f=p?.adapterOptions||{},A=f.max_tokens||f.maxTokens||t.max_tokens||t.maxOutputTokens||this.defaultMaxTokens,E=f.temperature??t.temperature??this.defaultTemperature,M=f.top_p||f.topP||t.top_p||t.topP,m=f.top_k||f.topK||t.top_k||t.topK,w=f.stop_sequences||f.stopSequences||t.stop||t.stop_sequences||t.stopSequences,S=f.thinking||t.thinking;if(!A){let y=new d("Anthropic API requires 'max_tokens'.","INVALID_CONFIG");return async function*(){yield {type:"ERROR",data:y,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let N,C;try{let y=this.translateToAnthropicSdk(e);N=y.systemPrompt,C=y.messages;}catch(y){a.error(`Error translating ArtStandardPrompt to Anthropic SDK format: ${y.message}`,{error:y,threadId:r,traceId:n});let O=y instanceof d?y:new d(`Prompt translation failed: ${y.message}`,"PROMPT_TRANSLATION_FAILED",y);return async function*(){yield {type:"ERROR",data:O,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let I=l?this.translateArtToolsToAnthropic(l):void 0,L={model:u,messages:C,max_tokens:A,system:N,temperature:E,top_p:M,top_k:m,stop_sequences:w,thinking:S,stream:s,tools:I};return Object.keys(L).forEach(y=>{let O=y;L[O]===void 0&&delete L[O];}),a.debug(`Calling Anthropic API with model ${u}`,{stream:s,tools:!!I,threadId:r,traceId:n}),async function*(){try{let y=Date.now(),O;if(s){let h=await this.client.messages.create(L,this.getRequestOptions(u)),T="",D=[],k=new Map,x=new Set,v,F,P=null,U={input_tokens:void 0,output_tokens:void 0},Ee,tt;for await(let $ of h)switch($.type){case "message_start":a.debug("Anthropic stream: message_start",{usage:$.message.usage,threadId:r,traceId:n}),U.input_tokens=$.message.usage.input_tokens,U.output_tokens=$.message.usage.output_tokens,v=U.input_tokens,F=U.output_tokens,Ee={inputTokens:v,outputTokens:F,providerRawUsage:{usage:{...$.message.usage}},traceId:n},yield {type:"METADATA",data:Ee,threadId:r,traceId:n,sessionId:o};break;case "content_block_start":if(a.debug("Anthropic stream: content_block_start",{index:$.index,block:$.content_block,threadId:r,traceId:n}),$.content_block?.type==="thinking"){x.add($.index);let G=$.content_block.thinking||"";G&&(O===void 0&&(O=Date.now()-y),yield {type:"TOKEN",data:G,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING"});}if($.content_block?.type==="tool_use"){let G=$.content_block;k.set($.index,{id:G.id,name:G.name,chunks:[]});}break;case "content_block_delta":if(a.debug("Anthropic stream: content_block_delta",{index:$.index,delta:$.delta,threadId:r,traceId:n}),$.delta.type==="text_delta"){let G=$.delta.text;T+=G,O===void 0&&(O=Date.now()-y),yield {type:"TOKEN",data:G,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"};}else if($.delta.type==="thinking_delta"){let G=$.delta.thinking||"";G&&(O===void 0&&(O=Date.now()-y),yield {type:"TOKEN",data:G,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING"});}else if($.delta.type==="input_json_delta"){let G=k.get($.index);if(G){let z=$.delta.partial_json??"";z&&G.chunks.push(z);}}break;case "content_block_stop":if(a.debug("Anthropic stream: content_block_stop",{index:$.index,threadId:r,traceId:n}),k.has($.index)){let G=k.get($.index),z=G.chunks.join(""),J={};try{J=z?JSON.parse(z):{};}catch{}D.push({id:G.id,name:G.name,input:J}),k.delete($.index);}break;case "message_delta":a.debug("Anthropic stream: message_delta",{delta:$.delta,usage:$.usage,threadId:r,traceId:n}),P=$.delta.stop_reason??P,$.usage.output_tokens!==void 0&&$.usage.output_tokens!==null&&(U.output_tokens=$.usage.output_tokens),F=U.output_tokens,tt={inputTokens:v,outputTokens:F,stopReason:$.delta.stop_reason??void 0,providerRawUsage:{usage:{input_tokens:v,output_tokens:$.usage.output_tokens??void 0},delta:$.delta},traceId:n},yield {type:"METADATA",data:tt,threadId:r,traceId:n,sessionId:o};break;case "message_stop":{a.debug("Anthropic stream: message_stop. Using accumulated data.",{threadId:r,traceId:n});for(let[J,W]of k.entries()){let Z=W.chunks.join(""),rt={};try{rt=Z?JSON.parse(Z):{};}catch(ht){a.warn("AnthropicAdapter: Failed to parse tool_use input JSON in final flush.",{error:ht,threadId:r,traceId:n});}D.push({id:W.id,name:W.name,input:rt}),k.delete(J);}if(P==="tool_use"&&D.length>0){let J=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE",W=D.map(Z=>({type:"tool_use",id:Z.id,name:Z.name,input:Z.input}));T.trim()?yield {type:"TOKEN",data:[{type:"text",text:T.trim()},...W],threadId:r,traceId:n,sessionId:o,tokenType:J}:yield {type:"TOKEN",data:W,threadId:r,traceId:n,sessionId:o,tokenType:J};}else if(T.trim()){let J=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:T.trim(),threadId:r,traceId:n,sessionId:o,tokenType:J};}let G=Date.now()-y;yield {type:"METADATA",data:{inputTokens:U.input_tokens??void 0,outputTokens:U.output_tokens??void 0,stopReason:P??void 0,timeToFirstTokenMs:O,totalGenerationTimeMs:G,providerRawUsage:{usage:{input_tokens:U.input_tokens??void 0,output_tokens:U.output_tokens??void 0},stop_reason:P},traceId:n},threadId:r,traceId:n,sessionId:o};break}default:{a.warn("Anthropic stream: unhandled raw stream event type",{eventType:$.type,event:$,threadId:r,traceId:n});break}}}else {let h=await this.client.messages.create(L,this.getRequestOptions(u));a.debug(`Anthropic API call successful (non-streaming). Stop Reason: ${h.stop_reason}`,{threadId:r,traceId:n});let T="",D=[];h.content.forEach(x=>{x.type==="text"?T+=x.text:x.type==="tool_use"&&D.push(x);}),T=T.trim();let k=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";if(h.stop_reason==="tool_use"&&D.length>0){let x=D.map(v=>({type:"tool_use",id:v.id,name:v.name,input:v.input}));T?yield {type:"TOKEN",data:[{type:"text",text:T},...x],threadId:r,traceId:n,sessionId:o,tokenType:k}:yield {type:"TOKEN",data:x,threadId:r,traceId:n,sessionId:o,tokenType:k};}else T?yield {type:"TOKEN",data:T,threadId:r,traceId:n,sessionId:o,tokenType:k}:h.stop_reason!=="tool_use"&&a.warn("Anthropic API (non-streaming): Empty response text and not a tool_use stop_reason.",{response:h,threadId:r,traceId:n});h.usage&&(yield {type:"METADATA",data:{inputTokens:h.usage.input_tokens,outputTokens:h.usage.output_tokens,stopReason:h.stop_reason??void 0,totalGenerationTimeMs:Date.now()-y,providerRawUsage:{usage:h.usage,stop_reason:h.stop_reason,stop_sequence:h.stop_sequence},traceId:n},threadId:r,traceId:n,sessionId:o});}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(y){a.error(`Error during Anthropic API call: ${y.message}`,{error:y,threadId:r,traceId:n}),yield {type:"ERROR",data:y instanceof d?y:y instanceof Anthropic.APIError?new d(`Anthropic API Error (${y.status}): ${y.message}`,"LLM_PROVIDER_ERROR",y):new d(y.message||"Unknown Anthropic adapter error","LLM_PROVIDER_ERROR",y),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}.bind(this)()}async shutdown(){a.debug("AnthropicAdapter shutdown called.");}getRequestOptions(e){let t=[];return e.startsWith("claude-3-5-sonnet")||e.startsWith("claude-3-opus"),t.length>0?{headers:{"anthropic-beta":t.join(",")}}:{}}translateToAnthropicSdk(e){let t,r=[],n=null;for(let s of e){if(s.role==="system"){let l=typeof s.content=="string"?s.content:String(s.content);t?(a.warn("AnthropicAdapter: Multiple system messages found. Appending to existing system prompt."),t+=`
92
- ${l}`):t=l;continue}let i=this.mapArtMessageToAnthropicContent(s),c=s.role==="user"||s.role==="tool_result"?"user":"assistant";if(n===c&&r.length>0){let l=r[r.length-1],p;typeof l.content=="string"?p=[{type:"text",text:l.content}]:p=l.content;let u=typeof i=="string"?[{type:"text",text:i}]:i,f=[...p,...u];l.content=f,a.debug(`AnthropicAdapter: Merged consecutive ${c} messages.`);}else r.push({role:c,content:i}),n=c;}!t&&r.length>0&&r[0].role!=="user"&&(a.warn("AnthropicAdapter: Prompt does not start with user message and has no system prompt. Prepending an empty user message for compatibility."),r.unshift({role:"user",content:"(Previous turn context)"}));let o=e[e.length-1];return o?.role==="assistant"&&o.tool_calls&&o.tool_calls.length>0&&a.debug("AnthropicAdapter: Prompt ends with assistant requesting tool calls."),{systemPrompt:t,messages:r}}mapArtMessageToAnthropicContent(e){let t=[];if(e.content&&typeof e.content=="string"&&e.content.trim()!==""?t.push({type:"text",text:e.content}):e.content&&typeof e.content!="string"&&e.role!=="tool_result"&&(!e.tool_calls||e.tool_calls.length===0)&&(a.warn(`AnthropicAdapter: Non-string, non-tool_result, non-tool_call-only content for role ${e.role}, stringifying.`,{content:e.content}),t.push({type:"text",text:JSON.stringify(e.content)})),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0&&e.tool_calls.forEach(r=>{if(r.type==="function")try{t.push({type:"tool_use",id:r.id,name:r.function.name,input:JSON.parse(r.function.arguments||"{}")});}catch(n){throw new d(`AnthropicAdapter: Failed to parse tool call arguments for tool ${r.function.name} (ID: ${r.id}). Arguments must be valid JSON. Error: ${n.message}`,"PROMPT_TRANSLATION_FAILED",n)}else a.warn(`AnthropicAdapter: Skipping non-function tool_call type: ${r.type}`);}),e.role==="tool_result"){if(!e.tool_call_id)throw new d("AnthropicAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");let r={type:"tool_result",tool_use_id:e.tool_call_id};typeof e.content=="string"?r.content=e.content:Array.isArray(e.content)&&e.content.every(n=>typeof n=="object"&&n.type==="text"&&typeof n.text=="string")?r.content=e.content.map(n=>({type:"text",text:n.text})):e.content!==null&&e.content!==void 0&&(r.content=JSON.stringify(e.content)),t.push(r);}return t.length===1&&t[0].type==="text"?t[0].text:t.length===0?"":t}translateArtToolsToAnthropic(e){return e.map(t=>{if(!t.inputSchema||typeof t.inputSchema!="object")throw new d(`Invalid inputSchema definition for tool '${t.name}'. Expected a JSON schema object.`,"INVALID_CONFIG");return {name:t.name,description:t.description,input_schema:t.inputSchema}})}};var Je=class{constructor(e){this.providerName="openrouter";if(!e.apiKey)throw new Error("OpenRouterAdapter requires an apiKey in options.");if(!e.model)throw new Error("OpenRouterAdapter requires a model identifier in options (e.g., 'google/gemini-pro').");this.apiKey=e.apiKey,this.model=e.model,this.apiBaseUrl=e.apiBaseUrl||"https://openrouter.ai/api/v1",this.siteUrl=e.siteUrl,this.appName=e.appName,a.debug(`OpenRouterAdapter initialized for model: ${this.model}`);}async call(e,t){let{threadId:r,traceId:n=`openrouter-trace-${Date.now()}`,sessionId:o,stream:s,callContext:i,model:c,tools:l}=t,p=c||this.model,u,f;try{u=this.translateToOpenAI(e),l&&l.length>0&&(f=this.translateArtToolsToOpenAI(l));}catch(S){return a.error(`Error translating prompt/tools for OpenRouter: ${S.message}`,{error:S,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:S instanceof d?S:new d(`Prompt translation failed: ${S.message}`,"PROMPT_TRANSLATION_FAILED",S),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let A=t.openrouter||{},E=typeof A?.include_reasoning=="boolean"?A.include_reasoning:A?.reasoning?A.reasoning.exclude!==true:void 0,M={model:p,messages:u,temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,stop:t.stop||t.stop_sequences||t.stopSequences,stream:!!s,...s?{stream_options:{include_usage:true}}:{},tools:f,tool_choice:t.tool_choice,provider:A.provider,transforms:A.useMiddleOutTransform===false?void 0:["middle-out"],reasoning:A.reasoning,...E!==void 0?{include_reasoning:E}:{}};Object.keys(M).forEach(S=>M[S]===void 0&&delete M[S]);let m={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};this.siteUrl&&(m["HTTP-Referer"]=this.siteUrl),this.appName&&(m["X-Title"]=this.appName);let w=`${this.apiBaseUrl}/chat/completions`;a.debug(`Calling OpenRouter API: ${w} with model ${p}, stream: ${!!s}`,{threadId:r,traceId:n});try{let S=await fetch(w,{method:"POST",headers:m,body:JSON.stringify(M)});if(!S.ok){let N=await S.text(),C=new d(`OpenRouter API request failed: ${S.status} ${S.statusText} - ${N}`,"LLM_PROVIDER_ERROR",new Error(N));return async function*(){yield {type:"ERROR",data:C,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}if(s&&S.body)return this.processStream(S.body,t);{let N=await S.json();return this.processNonStreamingResponse(N,t)}}catch(S){a.error(`Error during OpenRouter API call: ${S.message}`,{error:S,threadId:r,traceId:n});let N=S instanceof d?S:new d(S.message,"LLM_PROVIDER_ERROR",S);return async function*(){yield {type:"ERROR",data:N,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}}async*processStream(e,t){var C;let{threadId:r,traceId:n,sessionId:o,callContext:s}=t,i=r||"",c=n||"",l=o||"",p=Date.now(),u,f,A,E=[],M=e.getReader(),m=new TextDecoder,w="";for(;;)try{let{value:I,done:L}=await M.read();if(L)break;w+=m.decode(I,{stream:!0});let R=w.split(`
93
- `);w=R.pop()||"";for(let y of R){let O=y.trim();if(!O||!O.startsWith("data: "))continue;let h=O.substring(6);if(h==="[DONE]")break;let T=JSON.parse(h);if(T?.error)throw new d(`OpenRouter stream error: ${T.error?.message??"unknown"}`,"LLM_PROVIDER_ERROR",new Error(JSON.stringify(T.error)));let D=T.choices?.[0];if(!D)continue;u===void 0&&(u=Date.now()-p);let k=D.delta??{};if(typeof k.reasoning=="string"&&k.reasoning.length>0){let v=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:k.reasoning,threadId:i,traceId:c,sessionId:l,tokenType:v};}let x=k.reasoning_details;if(Array.isArray(x)){for(let v of x)if(v?.type==="reasoning.text"&&typeof v.text=="string"&&v.text.length>0){let F=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:v.text,threadId:i,traceId:c,sessionId:l,tokenType:F};}else if(v?.type==="reasoning.summary"&&typeof v.summary=="string"&&v.summary.length>0){let F=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:v.summary,threadId:i,traceId:c,sessionId:l,tokenType:F};}}if(typeof k.content=="string"&&k.content.length>0){let v=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:k.content,threadId:i,traceId:c,sessionId:l,tokenType:v};}if(Array.isArray(k.tool_calls)){for(let v of k.tool_calls)if(typeof v?.index=="number"&&(E[v.index]||(E[v.index]={}),v.id&&(E[v.index].id=v.id),v.type&&(E[v.index].type=v.type),v.function)){let F=(C=E[v.index]).function||(C.function={});v.function.name&&(F.name=v.function.name),typeof v.function.arguments=="string"&&(F.arguments=(F.arguments||"")+v.function.arguments);}}D.finish_reason&&(f=D.finish_reason),T.usage&&(A=T.usage);}}catch(I){yield {type:"ERROR",data:I instanceof d?I:new d(`Error reading OpenRouter stream: ${I.message}`,"LLM_PROVIDER_ERROR",I),threadId:i,traceId:c,sessionId:l};return}f==="tool_calls"&&E.length>0&&(yield {type:"TOKEN",data:E.map(R=>({type:"tool_use",id:String(R?.id??""),name:String(R?.function?.name??""),input:JSON.parse(R?.function?.arguments??"{}")})),threadId:i,traceId:c,sessionId:l,tokenType:s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"});let S=Date.now()-p;yield {type:"METADATA",data:{stopReason:f,inputTokens:A?.prompt_tokens,outputTokens:A?.completion_tokens,thinkingTokens:A?.completion_tokens_details?.reasoning_tokens,timeToFirstTokenMs:u,totalGenerationTimeMs:S,providerRawUsage:{...A,finish_reason:f},traceId:c},threadId:i,traceId:c,sessionId:l},yield {type:"END",data:null,threadId:i,traceId:c,sessionId:l};}async*processNonStreamingResponse(e,t){let{threadId:r,traceId:n,sessionId:o,callContext:s}=t,i=r||"",c=n||"",l=o||"",p=e.choices?.[0];if(!p?.message){yield {type:"ERROR",data:new d("Invalid response structure from OpenRouter API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(e))),threadId:i,traceId:c,sessionId:l},yield {type:"END",data:null,threadId:i,traceId:c,sessionId:l};return}let u=p.message;if(typeof u.reasoning=="string"&&u.reasoning.length>0){let S=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:u.reasoning,threadId:i,traceId:c,sessionId:l,tokenType:S};}if(Array.isArray(u.reasoning_details)){for(let S of u.reasoning_details)if(S?.type==="reasoning.text"&&typeof S.text=="string"&&S.text.length>0){let N=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:S.text,threadId:i,traceId:c,sessionId:l,tokenType:N};}else if(S?.type==="reasoning.summary"&&typeof S.summary=="string"&&S.summary.length>0){let N=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:S.summary,threadId:i,traceId:c,sessionId:l,tokenType:N};}}let f=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE",A=u.tool_calls?.map(S=>({type:"tool_use",id:String(S?.id??""),name:String(S?.function?.name??""),input:JSON.parse(S?.function?.arguments??"{}")}))||[],E=u.content??"",M=[];E.trim()&&M.push({type:"text",text:E.trim()}),M.push(...A),M.length>0&&(yield {type:"TOKEN",data:M.length===1&&M[0].type==="text"?M[0].text:M,threadId:i,traceId:c,sessionId:l,tokenType:f});let m=e.usage;yield {type:"METADATA",data:{stopReason:p.finish_reason,inputTokens:m?.prompt_tokens,outputTokens:m?.completion_tokens,thinkingTokens:m?.completion_tokens_details?.reasoning_tokens,providerRawUsage:{...m,finish_reason:p.finish_reason},traceId:c},threadId:i,traceId:c,sessionId:l},yield {type:"END",data:null,threadId:i,traceId:c,sessionId:l};}translateArtToolsToOpenAI(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}))}translateToOpenAI(e){return e.map(t=>{switch(t.role){case "system":return {role:"system",content:String(t.content)};case "user":return {role:"user",content:String(t.content)};case "assistant":{let r={role:"assistant",content:typeof t.content=="string"?t.content:null};return t.tool_calls&&t.tool_calls.length>0&&(r.tool_calls=t.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new d(`OpenRouterAdapter: Invalid tool_call structure in assistant message. ID: ${n.id}`,"PROMPT_TRANSLATION_FAILED");return {id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}})),r.content===""&&r.tool_calls&&(r.content=null),r}case "tool_result":{if(!t.tool_call_id)throw new d("OpenRouterAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return {role:"tool",tool_call_id:t.tool_call_id,content:String(t.content)}}case "tool_request":throw new d("OpenRouterAdapter: Unexpected 'tool_request' role. This should be handled by 'tool_calls' in an assistant message.","PROMPT_TRANSLATION_FAILED");default:throw new d(`OpenRouterAdapter: Unknown message role '${t.role}' encountered.`,"PROMPT_TRANSLATION_FAILED")}})}};var Ye=class{constructor(e){this.providerName="deepseek";if(!e.apiKey)throw new Error("DeepSeekAdapter requires an apiKey in options.");this.apiKey=e.apiKey,this.model=e.model||"deepseek-chat",this.apiBaseUrl=e.apiBaseUrl||"https://api.deepseek.com/v1",a.debug(`DeepSeekAdapter initialized with model: ${this.model}`);}async call(e,t){let{threadId:r,traceId:n=`deepseek-trace-${Date.now()}`,sessionId:o,stream:s,callContext:i,model:c}=t,l=c||this.model;if(s)return a.warn("DeepSeekAdapter: Streaming requested but not implemented. Returning error stream.",{threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new d("Streaming is not yet implemented for the DeepSeekAdapter.","LLM_PROVIDER_ERROR"),threadId:r??"",traceId:n??"",sessionId:o},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:o};}();let p;try{p=this.translateToOpenAI(e);}catch(m){return a.error(`Error translating ArtStandardPrompt to DeepSeek/OpenAI format: ${m.message}`,{error:m,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:m instanceof d?m:new d(`Prompt translation failed: ${m.message}`,"PROMPT_TRANSLATION_FAILED",m),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let u=`${this.apiBaseUrl}/chat/completions`,f=t.stop||t.stop_sequences||t.stopSequences,A={model:l,messages:p,temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,stop:f,stream:false};Object.keys(A).forEach(m=>A[m]===void 0&&delete A[m]);let E={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return a.debug(`Calling DeepSeek API (non-streaming): ${u} with model ${this.model}`,{threadId:r,traceId:n}),async function*(){try{let m=await fetch(u,{method:"POST",headers:E,body:JSON.stringify(A)});if(!m.ok){let R=await m.text(),y=R;try{let h=JSON.parse(R);h?.error?.message&&(y=h.error.message);}catch{}yield {type:"ERROR",data:new d(`DeepSeek API request failed: ${m.status} ${m.statusText} - ${y}`,"LLM_PROVIDER_ERROR",new Error(R)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let w=await m.json(),S=w.choices?.[0];if(!S?.message){yield {type:"ERROR",data:new d("Invalid response structure from DeepSeek API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(w))),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let N=S.message;N.tool_calls&&a.debug("DeepSeek response included tool calls (non-streaming)",{toolCalls:N.tool_calls,threadId:r,traceId:n}),a.debug(`DeepSeek API call successful. Finish reason: ${S.finish_reason}`,{threadId:r,traceId:n});let C=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(N.content??"").trim(),threadId:r,traceId:n,sessionId:o,tokenType:C},yield {type:"METADATA",data:{inputTokens:w.usage?.prompt_tokens,outputTokens:w.usage?.completion_tokens,stopReason:S.finish_reason,providerRawUsage:{usage:w.usage,finish_reason:S.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(m){a.error(`Error during DeepSeek API call: ${m.message}`,{error:m,threadId:r,traceId:n}),yield {type:"ERROR",data:m instanceof d?m:new d(m.message,"LLM_PROVIDER_ERROR",m),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}()}translateToOpenAI(e){return e.map(t=>{switch(t.role){case "system":return typeof t.content!="string"?(a.warn("DeepSeekAdapter: System message content is not a string. Stringifying.",{content:t.content}),{role:"system",content:String(t.content)}):{role:"system",content:t.content};case "user":return typeof t.content!="string"?(a.warn("DeepSeekAdapter: User message content is not a string. Stringifying.",{content:t.content}),{role:"user",content:String(t.content)}):{role:"user",content:t.content};case "assistant":{let r={role:"assistant",content:typeof t.content=="string"?t.content:null};return t.tool_calls&&t.tool_calls.length>0&&(r.tool_calls=t.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new d(`DeepSeekAdapter: Invalid tool_call structure in assistant message. ID: ${n.id}`,"PROMPT_TRANSLATION_FAILED");return {id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}})),r.content===""&&!r.tool_calls&&(r.content=null),r.content===""&&r.tool_calls&&(r.content=null),typeof r.content!="string"&&r.content!==null&&(r.content=null),r}case "tool_result":{if(!t.tool_call_id)throw new d("DeepSeekAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return typeof t.content!="string"&&a.warn("DeepSeekAdapter: Tool result content is not a string. Stringifying.",{content:t.content}),{role:"tool",tool_call_id:t.tool_call_id,content:String(t.content)}}case "tool_request":throw new d("DeepSeekAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new d(`DeepSeekAdapter: Unknown message role '${t.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var Xe=class{constructor(e){this.providerName="ollama";this.ollamaBaseUrl=e.ollamaBaseUrl||"http://localhost:11434",this.defaultModel=e.defaultModel;let t=this.ollamaBaseUrl.replace(/\/v1$/,"").replace(/\/$/,"");this.client=new qt({baseURL:`${t}/v1`,apiKey:e.apiKey||"ollama",dangerouslyAllowBrowser:true}),a.debug(`OllamaAdapter initialized. Base URL: ${t}/v1, Default Model: ${this.defaultModel||"Not set"}`);}async call(e,t){let{threadId:r,traceId:n=`ollama-trace-${Date.now()}`,sessionId:o,stream:s=false,callContext:i,model:c,tools:l,providerConfig:p}=t,u=p?.modelId||c||this.defaultModel;if(!u){let m=new d("Ollama model ID is not specified. Provide it in adapter options, runtime config, or call options.","INVALID_CONFIG");return async function*(){yield {type:"ERROR",data:m,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let f;try{f=this.translateToOpenAI(e,u);}catch(m){a.error(`Error translating ArtStandardPrompt to OpenAI format for Ollama: ${m.message}`,{error:m,threadId:r,traceId:n});let w=m instanceof d?m:new d(`Prompt translation failed: ${m.message}`,"PROMPT_TRANSLATION_FAILED",m);return async function*(){yield {type:"ERROR",data:w,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let A=l?this.translateArtToolsToOpenAI(l):void 0,E={model:u,messages:f,temperature:t.temperature??p?.adapterOptions?.temperature,max_tokens:t.max_tokens??t.maxOutputTokens??p?.adapterOptions?.max_tokens,top_p:t.top_p??t.topP??p?.adapterOptions?.top_p,stop:(t.stop||t.stop_sequences||t.stopSequences)??p?.adapterOptions?.stop,stream:s,tools:A,tool_choice:t.tool_choice??p?.adapterOptions?.tool_choice};return Object.keys(E).forEach(m=>{let w=m;E[w]===void 0&&delete E[w];}),a.debug(`Calling Ollama API (via OpenAI client) with model ${u}`,{stream:s,tools:!!A,threadId:r,traceId:n}),async function*(){let m=Date.now(),w,S=0,N,C;try{if(s){let R=await this.client.chat.completions.create(E),y=[];for await(let O of R){w||(w=Date.now()-m);let h=O.choices[0]?.delta;if(C=O.choices[0]?.finish_reason??C,h?.content){S++;let T=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:h.content,threadId:r,traceId:n,sessionId:o,tokenType:T};}h?.tool_calls&&h.tool_calls.forEach(T=>{T.index!==void 0&&(y[T.index]?(T.id&&(y[T.index].id=T.id),T.function?.name&&(y[T.index].function.name=T.function.name),T.function?.arguments&&(y[T.index].function||(y[T.index].function={name:"",arguments:""}),y[T.index].function.arguments+=T.function.arguments)):y[T.index]={id:T.id||"",type:"function",function:{name:T.function?.name||"",arguments:T.function?.arguments||""}});}),O.usage&&(N=O.usage);}if(C==="tool_calls"&&y.length>0){let O=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:y.map(T=>({type:"tool_use",id:T.id,name:T.function.name,input:JSON.parse(T.function.arguments||"{}")})),threadId:r,traceId:n,sessionId:o,tokenType:O};}}else {let R=await this.client.chat.completions.create(E),y=R.choices[0];if(!y||!y.message)throw new d("Invalid response structure from Ollama API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(R)));C=y.finish_reason??void 0,N=R.usage;let O=y.message,h=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";if(O.tool_calls&&O.tool_calls.length>0){let T=O.tool_calls.map(D=>({type:"tool_use",id:D.id,name:D.function.name,input:JSON.parse(D.function.arguments||"{}")}));O.content?yield {type:"TOKEN",data:[{type:"text",text:O.content.trim()},...T],threadId:r,traceId:n,sessionId:o,tokenType:h}:yield {type:"TOKEN",data:T,threadId:r,traceId:n,sessionId:o,tokenType:h};}else O.content&&(yield {type:"TOKEN",data:O.content.trim(),threadId:r,traceId:n,sessionId:o,tokenType:h});}let I=Date.now()-m;yield {type:"METADATA",data:{stopReason:C,inputTokens:N?.prompt_tokens,outputTokens:N?.completion_tokens??(s?S:void 0),timeToFirstTokenMs:s?w:void 0,totalGenerationTimeMs:I,providerRawUsage:{usage:N,finish_reason:C},traceId:n},threadId:r,traceId:n,sessionId:o};}catch(I){a.error(`Error during Ollama API call: ${I.message}`,{error:I,threadId:r,traceId:n}),yield {type:"ERROR",data:I instanceof d?I:I.constructor.name==="APIError"?new d(`Ollama API Error (${I.status}): ${I.message}`,"LLM_PROVIDER_ERROR",I):new d(I.message||"Unknown Ollama adapter error","LLM_PROVIDER_ERROR",I),threadId:r,traceId:n,sessionId:o};}finally{yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}.bind(this)()}translateToOpenAI(e,t){let r=[...e],n=[];if(t?.toLowerCase().includes("deepseek-r1")){a.debug(`OllamaAdapter: Applying R1-style message merging for model: ${t}`);let s=null;for(let i of r){let c="user";i.role==="system"?c="system":i.role==="user"?c="user":i.role==="assistant"?c="assistant":i.role==="tool_result"&&(c="tool");let l=this.mapArtMessageToOpenAIMessage(i);if(s&&s.role===c&&c!=="system"&&c!=="tool"){let p="";typeof s.content=="string"&&typeof l.content=="string"?p=`${s.content}
91
+ `+r:t.push({type:"output_text",text:r});}return t.length===0&&t.push({type:"output_text",text:""}),{role:"assistant",content:t}}case "tool_request":return a.debug("OpenAIAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls."),null;default:return a.warn(`OpenAIAdapter: Skipping message with unhandled role: ${e.role}`),null}}translateArtToolsToOpenAI(e){return e.map(t=>{if(!t.inputSchema||typeof t.inputSchema!="object")throw new d(`Invalid inputSchema definition for tool '${t.name}'. Expected a JSON schema object.`,"INVALID_CONFIG");return {type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}})}};var jt="claude-4.5-sonnet",zt=4096,Je=class{constructor(e){this.providerName="anthropic";if(!e.apiKey)throw new d("AnthropicAdapter requires an apiKey in options.","INVALID_CONFIG");this.client=new Anthropic({apiKey:e.apiKey,baseURL:e.apiBaseUrl||void 0}),this.defaultModel=e.model||jt,this.defaultMaxTokens=e.defaultMaxTokens||zt,this.defaultTemperature=e.defaultTemperature,a.debug(`AnthropicAdapter initialized with model: ${this.defaultModel}`);}async call(e,t){let{threadId:r,traceId:n=`anthropic-trace-${Date.now()}`,sessionId:o,stream:s=false,callContext:i,model:c,tools:l,providerConfig:p}=t,u=p?.modelId||c||this.defaultModel,m=p?.adapterOptions||{},I=m.max_tokens||m.maxTokens||t.max_tokens||t.maxOutputTokens||this.defaultMaxTokens,v=m.temperature??t.temperature??this.defaultTemperature,C=m.top_p||m.topP||t.top_p||t.topP,h=m.top_k||m.topK||t.top_k||t.topK,R=m.stop_sequences||m.stopSequences||t.stop||t.stop_sequences||t.stopSequences,O=m.thinking||t.thinking;if(!I){let _=new d("Anthropic API requires 'max_tokens'.","INVALID_CONFIG");return async function*(){yield {type:"ERROR",data:_,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let x,P;try{let _=this.translateToAnthropicSdk(e);x=_.systemPrompt,P=_.messages;}catch(_){a.error(`Error translating ArtStandardPrompt to Anthropic SDK format: ${_.message}`,{error:_,threadId:r,traceId:n});let w=_ instanceof d?_:new d(`Prompt translation failed: ${_.message}`,"PROMPT_TRANSLATION_FAILED",_);return async function*(){yield {type:"ERROR",data:w,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let T=l?this.translateArtToolsToAnthropic(l):void 0,D={model:u,messages:P,max_tokens:I,system:x,temperature:v,top_p:C,top_k:h,stop_sequences:R,thinking:O,stream:s,tools:T};return Object.keys(D).forEach(_=>{let w=_;D[w]===void 0&&delete D[w];}),a.debug(`Calling Anthropic API with model ${u}`,{stream:s,tools:!!T,threadId:r,traceId:n}),async function*(){try{let _=Date.now(),w;if(s){let f=await this.client.messages.create(D,this.getRequestOptions(u)),A="",M=[],N=new Map,y=new Set,S,$,K=null,U={input_tokens:void 0,output_tokens:void 0},z,X;for await(let L of f)switch(L.type){case "message_start":a.debug("Anthropic stream: message_start",{usage:L.message.usage,threadId:r,traceId:n}),U.input_tokens=L.message.usage.input_tokens,U.output_tokens=L.message.usage.output_tokens,S=U.input_tokens,$=U.output_tokens,z={inputTokens:S,outputTokens:$,providerRawUsage:{usage:{...L.message.usage}},traceId:n},yield {type:"METADATA",data:z,threadId:r,traceId:n,sessionId:o};break;case "content_block_start":if(a.debug("Anthropic stream: content_block_start",{index:L.index,block:L.content_block,threadId:r,traceId:n}),L.content_block?.type==="thinking"){y.add(L.index);let G=L.content_block.thinking||"";G&&(w===void 0&&(w=Date.now()-_),yield {type:"TOKEN",data:G,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING"});}if(L.content_block?.type==="tool_use"){let G=L.content_block;N.set(L.index,{id:G.id,name:G.name,chunks:[]});}break;case "content_block_delta":if(a.debug("Anthropic stream: content_block_delta",{index:L.index,delta:L.delta,threadId:r,traceId:n}),L.delta.type==="text_delta"){let G=L.delta.text;A+=G,w===void 0&&(w=Date.now()-_),yield {type:"TOKEN",data:G,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"};}else if(L.delta.type==="thinking_delta"){let G=L.delta.thinking||"";G&&(w===void 0&&(w=Date.now()-_),yield {type:"TOKEN",data:G,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING"});}else if(L.delta.type==="input_json_delta"){let G=N.get(L.index);if(G){let J=L.delta.partial_json??"";J&&G.chunks.push(J);}}break;case "content_block_stop":if(a.debug("Anthropic stream: content_block_stop",{index:L.index,threadId:r,traceId:n}),N.has(L.index)){let G=N.get(L.index),J=G.chunks.join(""),Y={};try{Y=J?JSON.parse(J):{};}catch{}M.push({id:G.id,name:G.name,input:Y}),N.delete(L.index);}break;case "message_delta":a.debug("Anthropic stream: message_delta",{delta:L.delta,usage:L.usage,threadId:r,traceId:n}),K=L.delta.stop_reason??K,L.usage.output_tokens!==void 0&&L.usage.output_tokens!==null&&(U.output_tokens=L.usage.output_tokens),$=U.output_tokens,X={inputTokens:S,outputTokens:$,stopReason:L.delta.stop_reason??void 0,providerRawUsage:{usage:{input_tokens:S,output_tokens:L.usage.output_tokens??void 0},delta:L.delta},traceId:n},yield {type:"METADATA",data:X,threadId:r,traceId:n,sessionId:o};break;case "message_stop":{a.debug("Anthropic stream: message_stop. Using accumulated data.",{threadId:r,traceId:n});for(let[Y,Q]of N.entries()){let ee=Q.chunks.join(""),rt={};try{rt=ee?JSON.parse(ee):{};}catch(ht){a.warn("AnthropicAdapter: Failed to parse tool_use input JSON in final flush.",{error:ht,threadId:r,traceId:n});}M.push({id:Q.id,name:Q.name,input:rt}),N.delete(Y);}if(K==="tool_use"&&M.length>0){let Y=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE",Q=M.map(ee=>({type:"tool_use",id:ee.id,name:ee.name,input:ee.input}));A.trim()?yield {type:"TOKEN",data:[{type:"text",text:A.trim()},...Q],threadId:r,traceId:n,sessionId:o,tokenType:Y}:yield {type:"TOKEN",data:Q,threadId:r,traceId:n,sessionId:o,tokenType:Y};}else if(A.trim()){let Y=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:A.trim(),threadId:r,traceId:n,sessionId:o,tokenType:Y};}let G=Date.now()-_;yield {type:"METADATA",data:{inputTokens:U.input_tokens??void 0,outputTokens:U.output_tokens??void 0,stopReason:K??void 0,timeToFirstTokenMs:w,totalGenerationTimeMs:G,providerRawUsage:{usage:{input_tokens:U.input_tokens??void 0,output_tokens:U.output_tokens??void 0},stop_reason:K},traceId:n},threadId:r,traceId:n,sessionId:o};break}default:{a.warn("Anthropic stream: unhandled raw stream event type",{eventType:L.type,event:L,threadId:r,traceId:n});break}}}else {let f=await this.client.messages.create(D,this.getRequestOptions(u));a.debug(`Anthropic API call successful (non-streaming). Stop Reason: ${f.stop_reason}`,{threadId:r,traceId:n});let A="",M=[];f.content.forEach(y=>{y.type==="text"?A+=y.text:y.type==="tool_use"&&M.push(y);}),A=A.trim();let N=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";if(f.stop_reason==="tool_use"&&M.length>0){let y=M.map(S=>({type:"tool_use",id:S.id,name:S.name,input:S.input}));A?yield {type:"TOKEN",data:[{type:"text",text:A},...y],threadId:r,traceId:n,sessionId:o,tokenType:N}:yield {type:"TOKEN",data:y,threadId:r,traceId:n,sessionId:o,tokenType:N};}else A?yield {type:"TOKEN",data:A,threadId:r,traceId:n,sessionId:o,tokenType:N}:f.stop_reason!=="tool_use"&&a.warn("Anthropic API (non-streaming): Empty response text and not a tool_use stop_reason.",{response:f,threadId:r,traceId:n});f.usage&&(yield {type:"METADATA",data:{inputTokens:f.usage.input_tokens,outputTokens:f.usage.output_tokens,stopReason:f.stop_reason??void 0,totalGenerationTimeMs:Date.now()-_,providerRawUsage:{usage:f.usage,stop_reason:f.stop_reason,stop_sequence:f.stop_sequence},traceId:n},threadId:r,traceId:n,sessionId:o});}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(_){a.error(`Error during Anthropic API call: ${_.message}`,{error:_,threadId:r,traceId:n}),yield {type:"ERROR",data:_ instanceof d?_:_ instanceof Anthropic.APIError?new d(`Anthropic API Error (${_.status}): ${_.message}`,"LLM_PROVIDER_ERROR",_):new d(_.message||"Unknown Anthropic adapter error","LLM_PROVIDER_ERROR",_),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}.bind(this)()}async shutdown(){a.debug("AnthropicAdapter shutdown called.");}getRequestOptions(e){let t=[];return e.startsWith("claude-3-5-sonnet")||e.startsWith("claude-3-opus"),t.length>0?{headers:{"anthropic-beta":t.join(",")}}:{}}translateToAnthropicSdk(e){let t,r=[],n=null;for(let s of e){if(s.role==="system"){let l=typeof s.content=="string"?s.content:String(s.content);t?(a.warn("AnthropicAdapter: Multiple system messages found. Appending to existing system prompt."),t+=`
92
+ ${l}`):t=l;continue}let i=this.mapArtMessageToAnthropicContent(s),c=s.role==="user"||s.role==="tool_result"?"user":"assistant";if(n===c&&r.length>0){let l=r[r.length-1],p;typeof l.content=="string"?p=[{type:"text",text:l.content}]:p=l.content;let u=typeof i=="string"?[{type:"text",text:i}]:i,m=[...p,...u];l.content=m,a.debug(`AnthropicAdapter: Merged consecutive ${c} messages.`);}else r.push({role:c,content:i}),n=c;}!t&&r.length>0&&r[0].role!=="user"&&(a.warn("AnthropicAdapter: Prompt does not start with user message and has no system prompt. Prepending an empty user message for compatibility."),r.unshift({role:"user",content:"(Previous turn context)"}));let o=e[e.length-1];return o?.role==="assistant"&&o.tool_calls&&o.tool_calls.length>0&&a.debug("AnthropicAdapter: Prompt ends with assistant requesting tool calls."),{systemPrompt:t,messages:r}}mapArtMessageToAnthropicContent(e){let t=[];if(e.content&&typeof e.content=="string"&&e.content.trim()!==""?t.push({type:"text",text:e.content}):e.content&&typeof e.content!="string"&&e.role!=="tool_result"&&(!e.tool_calls||e.tool_calls.length===0)&&(a.warn(`AnthropicAdapter: Non-string, non-tool_result, non-tool_call-only content for role ${e.role}, stringifying.`,{content:e.content}),t.push({type:"text",text:JSON.stringify(e.content)})),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0&&e.tool_calls.forEach(r=>{if(r.type==="function")try{t.push({type:"tool_use",id:r.id,name:r.function.name,input:JSON.parse(r.function.arguments||"{}")});}catch(n){throw new d(`AnthropicAdapter: Failed to parse tool call arguments for tool ${r.function.name} (ID: ${r.id}). Arguments must be valid JSON. Error: ${n.message}`,"PROMPT_TRANSLATION_FAILED",n)}else a.warn(`AnthropicAdapter: Skipping non-function tool_call type: ${r.type}`);}),e.role==="tool_result"){if(!e.tool_call_id)throw new d("AnthropicAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");let r={type:"tool_result",tool_use_id:e.tool_call_id};typeof e.content=="string"?r.content=e.content:Array.isArray(e.content)&&e.content.every(n=>typeof n=="object"&&n.type==="text"&&typeof n.text=="string")?r.content=e.content.map(n=>({type:"text",text:n.text})):e.content!==null&&e.content!==void 0&&(r.content=JSON.stringify(e.content)),t.push(r);}return t.length===1&&t[0].type==="text"?t[0].text:t.length===0?"":t}translateArtToolsToAnthropic(e){return e.map(t=>{if(!t.inputSchema||typeof t.inputSchema!="object")throw new d(`Invalid inputSchema definition for tool '${t.name}'. Expected a JSON schema object.`,"INVALID_CONFIG");return {name:t.name,description:t.description,input_schema:t.inputSchema}})}};var Jt=3,Yt=1e3,Xt=3e4,Wt=[503,429,500,502,504];function Zt(g){let e=g?.code||g?.status||g?.error?.code;if(e&&Wt.includes(Number(e)))return true;let t=String(g?.message||g?.error?.message||"").toLowerCase();return t.includes("overloaded")||t.includes("rate limit")||t.includes("temporarily unavailable")||t.includes("503")||t.includes("429")}async function Qt(g,e={}){let t=e.maxRetries??Jt,r=e.initialDelayMs??Yt,n=e.maxDelayMs??Xt,o;for(let s=0;s<=t;s++)try{return await g()}catch(i){if(o=i,s===t||!Zt(i))throw i;let c=r*Math.pow(2,s),l=Math.random()*.3*c,p=Math.min(c+l,n);e.onRetry&&e.onRetry(i,s+1,p),a.warn(`OpenRouter API call failed (attempt ${s+1}/${t+1}), retrying in ${Math.round(p)}ms...`,{error:i?.message||i,statusCode:i?.code||i?.status||i?.error?.code}),await new Promise(u=>setTimeout(u,p));}throw o}var Ye=class{constructor(e){this.providerName="openrouter";if(!e.apiKey)throw new Error("OpenRouterAdapter requires an apiKey in options.");if(!e.model)throw new Error("OpenRouterAdapter requires a model identifier in options (e.g., 'google/gemini-pro').");this.apiKey=e.apiKey,this.model=e.model,this.apiBaseUrl=e.apiBaseUrl||"https://openrouter.ai/api/v1",this.siteUrl=e.siteUrl,this.appName=e.appName,a.debug(`OpenRouterAdapter initialized for model: ${this.model}`);}async call(e,t){let{threadId:r,traceId:n=`openrouter-trace-${Date.now()}`,sessionId:o,stream:s,model:i,tools:c}=t,l=i||this.model,p,u;try{p=this.translateToOpenAI(e),c&&c.length>0&&(u=this.translateArtToolsToOpenAI(c));}catch(R){return a.error(`Error translating prompt/tools for OpenRouter: ${R.message}`,{error:R,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:R instanceof d?R:new d(`Prompt translation failed: ${R.message}`,"PROMPT_TRANSLATION_FAILED",R),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let m=t.openrouter||{},I=typeof m?.include_reasoning=="boolean"?m.include_reasoning:m?.reasoning?m.reasoning.exclude!==true:void 0,v={model:l,messages:p,temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,stop:t.stop||t.stop_sequences||t.stopSequences,stream:!!s,...s?{stream_options:{include_usage:true}}:{},tools:u,tool_choice:t.tool_choice,response_format:t.response_format,provider:m.provider,transforms:m.useMiddleOutTransform===false?void 0:["middle-out"],reasoning:m.reasoning,...I!==void 0?{include_reasoning:I}:{}};Object.keys(v).forEach(R=>v[R]===void 0&&delete v[R]);let C={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};this.siteUrl&&(C["HTTP-Referer"]=this.siteUrl),this.appName&&(C["X-Title"]=this.appName);let h=`${this.apiBaseUrl}/chat/completions`;a.debug(`Calling OpenRouter API: ${h} with model ${l}, stream: ${!!s}`,{threadId:r,traceId:n});try{let R=await Qt(async()=>{let O=await fetch(h,{method:"POST",headers:C,body:JSON.stringify(v)});if(!O.ok){let x=await O.text(),P=new Error(`OpenRouter API request failed: ${O.status} ${O.statusText} - ${x}`);throw P.status=O.status,P}return O},{onRetry:(O,x,P)=>{a.info(`Retrying OpenRouter call (attempt ${x})`,{threadId:r,traceId:n,delayMs:P});}});if(s&&R.body)return this.processStream(R.body,t);{let O=await R.json();return this.processNonStreamingResponse(O,t)}}catch(R){a.error(`Error during OpenRouter API call: ${R.message}`,{error:R,threadId:r,traceId:n});let O=R instanceof d?R:new d(R.message,"LLM_PROVIDER_ERROR",R);return async function*(){yield {type:"ERROR",data:O,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}}async*processStream(e,t){var P;let{threadId:r,traceId:n,sessionId:o,callContext:s}=t,i=r||"",c=n||"",l=o||"",p=Date.now(),u,m,I,v=[],C=e.getReader(),h=new TextDecoder,R="";for(;;)try{let{value:T,done:D}=await C.read();if(D)break;R+=h.decode(T,{stream:!0});let k=R.split(`
93
+ `);R=k.pop()||"";for(let _ of k){let w=_.trim();if(!w||!w.startsWith("data: "))continue;let f=w.substring(6);if(f==="[DONE]")break;let A=JSON.parse(f);if(A?.error)throw new d(`OpenRouter stream error: ${A.error?.message??"unknown"}`,"LLM_PROVIDER_ERROR",new Error(JSON.stringify(A.error)));let M=A.choices?.[0];if(!M)continue;u===void 0&&(u=Date.now()-p);let N=M.delta??{};if(typeof N.reasoning=="string"&&N.reasoning.length>0){let S=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:N.reasoning,threadId:i,traceId:c,sessionId:l,tokenType:S};}let y=N.reasoning_details;if(Array.isArray(y)){for(let S of y)if(S?.type==="reasoning.text"&&typeof S.text=="string"&&S.text.length>0){let $=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:S.text,threadId:i,traceId:c,sessionId:l,tokenType:$};}else if(S?.type==="reasoning.summary"&&typeof S.summary=="string"&&S.summary.length>0){let $=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:S.summary,threadId:i,traceId:c,sessionId:l,tokenType:$};}}if(typeof N.content=="string"&&N.content.length>0){let S=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:N.content,threadId:i,traceId:c,sessionId:l,tokenType:S};}if(Array.isArray(N.tool_calls)){for(let S of N.tool_calls)if(typeof S?.index=="number"&&(v[S.index]||(v[S.index]={}),S.id&&(v[S.index].id=S.id),S.type&&(v[S.index].type=S.type),S.function)){let $=(P=v[S.index]).function||(P.function={});S.function.name&&($.name=S.function.name),typeof S.function.arguments=="string"&&($.arguments=($.arguments||"")+S.function.arguments);}}M.finish_reason&&(m=M.finish_reason),A.usage&&(I=A.usage);}}catch(T){yield {type:"ERROR",data:T instanceof d?T:new d(`Error reading OpenRouter stream: ${T.message}`,"LLM_PROVIDER_ERROR",T),threadId:i,traceId:c,sessionId:l};return}m==="tool_calls"&&v.length>0&&(yield {type:"TOKEN",data:v.map(k=>({type:"tool_use",id:String(k?.id??""),name:String(k?.function?.name??""),input:JSON.parse(k?.function?.arguments??"{}")})),threadId:i,traceId:c,sessionId:l,tokenType:s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"});let O=Date.now()-p;yield {type:"METADATA",data:{stopReason:m,inputTokens:I?.prompt_tokens,outputTokens:I?.completion_tokens,thinkingTokens:I?.completion_tokens_details?.reasoning_tokens,timeToFirstTokenMs:u,totalGenerationTimeMs:O,providerRawUsage:{...I,finish_reason:m},traceId:c},threadId:i,traceId:c,sessionId:l},yield {type:"END",data:null,threadId:i,traceId:c,sessionId:l};}async*processNonStreamingResponse(e,t){let{threadId:r,traceId:n,sessionId:o,callContext:s}=t,i=r||"",c=n||"",l=o||"",p=e.choices?.[0];if(!p?.message){yield {type:"ERROR",data:new d("Invalid response structure from OpenRouter API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(e))),threadId:i,traceId:c,sessionId:l},yield {type:"END",data:null,threadId:i,traceId:c,sessionId:l};return}let u=p.message;if(typeof u.reasoning=="string"&&u.reasoning.length>0){let O=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:u.reasoning,threadId:i,traceId:c,sessionId:l,tokenType:O};}if(Array.isArray(u.reasoning_details)){for(let O of u.reasoning_details)if(O?.type==="reasoning.text"&&typeof O.text=="string"&&O.text.length>0){let x=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:O.text,threadId:i,traceId:c,sessionId:l,tokenType:x};}else if(O?.type==="reasoning.summary"&&typeof O.summary=="string"&&O.summary.length>0){let x=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_THINKING":"FINAL_SYNTHESIS_LLM_THINKING";yield {type:"TOKEN",data:O.summary,threadId:i,traceId:c,sessionId:l,tokenType:x};}}let m=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE",I=u.tool_calls?.map(O=>({type:"tool_use",id:String(O?.id??""),name:String(O?.function?.name??""),input:JSON.parse(O?.function?.arguments??"{}")}))||[],v=u.content??"",C=[];v.trim()&&C.push({type:"text",text:v.trim()}),C.push(...I),C.length>0&&(yield {type:"TOKEN",data:C.length===1&&C[0].type==="text"?C[0].text:C,threadId:i,traceId:c,sessionId:l,tokenType:m});let h=e.usage;yield {type:"METADATA",data:{stopReason:p.finish_reason,inputTokens:h?.prompt_tokens,outputTokens:h?.completion_tokens,thinkingTokens:h?.completion_tokens_details?.reasoning_tokens,providerRawUsage:{...h,finish_reason:p.finish_reason},traceId:c},threadId:i,traceId:c,sessionId:l},yield {type:"END",data:null,threadId:i,traceId:c,sessionId:l};}translateArtToolsToOpenAI(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}))}translateToOpenAI(e){return e.map(t=>{switch(t.role){case "system":return {role:"system",content:String(t.content)};case "user":return {role:"user",content:String(t.content)};case "assistant":{let r={role:"assistant",content:typeof t.content=="string"?t.content:null};return t.tool_calls&&t.tool_calls.length>0&&(r.tool_calls=t.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new d(`OpenRouterAdapter: Invalid tool_call structure in assistant message. ID: ${n.id}`,"PROMPT_TRANSLATION_FAILED");return {id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}})),r.content===""&&r.tool_calls&&(r.content=null),r}case "tool_result":{if(!t.tool_call_id)throw new d("OpenRouterAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return {role:"tool",tool_call_id:t.tool_call_id,content:String(t.content)}}case "tool_request":throw new d("OpenRouterAdapter: Unexpected 'tool_request' role. This should be handled by 'tool_calls' in an assistant message.","PROMPT_TRANSLATION_FAILED");default:throw new d(`OpenRouterAdapter: Unknown message role '${t.role}' encountered.`,"PROMPT_TRANSLATION_FAILED")}})}};var Xe=class{constructor(e){this.providerName="deepseek";if(!e.apiKey)throw new Error("DeepSeekAdapter requires an apiKey in options.");this.apiKey=e.apiKey,this.model=e.model||"deepseek-chat",this.apiBaseUrl=e.apiBaseUrl||"https://api.deepseek.com/v1",a.debug(`DeepSeekAdapter initialized with model: ${this.model}`);}async call(e,t){let{threadId:r,traceId:n=`deepseek-trace-${Date.now()}`,sessionId:o,stream:s,callContext:i,model:c}=t,l=c||this.model;if(s)return a.warn("DeepSeekAdapter: Streaming requested but not implemented. Returning error stream.",{threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new d("Streaming is not yet implemented for the DeepSeekAdapter.","LLM_PROVIDER_ERROR"),threadId:r??"",traceId:n??"",sessionId:o},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:o};}();let p;try{p=this.translateToOpenAI(e);}catch(h){return a.error(`Error translating ArtStandardPrompt to DeepSeek/OpenAI format: ${h.message}`,{error:h,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:h instanceof d?h:new d(`Prompt translation failed: ${h.message}`,"PROMPT_TRANSLATION_FAILED",h),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let u=`${this.apiBaseUrl}/chat/completions`,m=t.stop||t.stop_sequences||t.stopSequences,I={model:l,messages:p,temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,stop:m,stream:false};Object.keys(I).forEach(h=>I[h]===void 0&&delete I[h]);let v={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return a.debug(`Calling DeepSeek API (non-streaming): ${u} with model ${this.model}`,{threadId:r,traceId:n}),async function*(){try{let h=await fetch(u,{method:"POST",headers:v,body:JSON.stringify(I)});if(!h.ok){let k=await h.text(),_=k;try{let f=JSON.parse(k);f?.error?.message&&(_=f.error.message);}catch{}yield {type:"ERROR",data:new d(`DeepSeek API request failed: ${h.status} ${h.statusText} - ${_}`,"LLM_PROVIDER_ERROR",new Error(k)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let R=await h.json(),O=R.choices?.[0];if(!O?.message){yield {type:"ERROR",data:new d("Invalid response structure from DeepSeek API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(R))),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let x=O.message;x.tool_calls&&a.debug("DeepSeek response included tool calls (non-streaming)",{toolCalls:x.tool_calls,threadId:r,traceId:n}),a.debug(`DeepSeek API call successful. Finish reason: ${O.finish_reason}`,{threadId:r,traceId:n});let P=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(x.content??"").trim(),threadId:r,traceId:n,sessionId:o,tokenType:P},yield {type:"METADATA",data:{inputTokens:R.usage?.prompt_tokens,outputTokens:R.usage?.completion_tokens,stopReason:O.finish_reason,providerRawUsage:{usage:R.usage,finish_reason:O.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(h){a.error(`Error during DeepSeek API call: ${h.message}`,{error:h,threadId:r,traceId:n}),yield {type:"ERROR",data:h instanceof d?h:new d(h.message,"LLM_PROVIDER_ERROR",h),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}()}translateToOpenAI(e){return e.map(t=>{switch(t.role){case "system":return typeof t.content!="string"?(a.warn("DeepSeekAdapter: System message content is not a string. Stringifying.",{content:t.content}),{role:"system",content:String(t.content)}):{role:"system",content:t.content};case "user":return typeof t.content!="string"?(a.warn("DeepSeekAdapter: User message content is not a string. Stringifying.",{content:t.content}),{role:"user",content:String(t.content)}):{role:"user",content:t.content};case "assistant":{let r={role:"assistant",content:typeof t.content=="string"?t.content:null};return t.tool_calls&&t.tool_calls.length>0&&(r.tool_calls=t.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new d(`DeepSeekAdapter: Invalid tool_call structure in assistant message. ID: ${n.id}`,"PROMPT_TRANSLATION_FAILED");return {id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}})),r.content===""&&!r.tool_calls&&(r.content=null),r.content===""&&r.tool_calls&&(r.content=null),typeof r.content!="string"&&r.content!==null&&(r.content=null),r}case "tool_result":{if(!t.tool_call_id)throw new d("DeepSeekAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return typeof t.content!="string"&&a.warn("DeepSeekAdapter: Tool result content is not a string. Stringifying.",{content:t.content}),{role:"tool",tool_call_id:t.tool_call_id,content:String(t.content)}}case "tool_request":throw new d("DeepSeekAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new d(`DeepSeekAdapter: Unknown message role '${t.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var We=class{constructor(e){this.providerName="ollama";this.ollamaBaseUrl=e.ollamaBaseUrl||"http://localhost:11434",this.defaultModel=e.defaultModel;let t=this.ollamaBaseUrl.replace(/\/v1$/,"").replace(/\/$/,"");this.client=new qt({baseURL:`${t}/v1`,apiKey:e.apiKey||"ollama",dangerouslyAllowBrowser:true}),a.debug(`OllamaAdapter initialized. Base URL: ${t}/v1, Default Model: ${this.defaultModel||"Not set"}`);}async call(e,t){let{threadId:r,traceId:n=`ollama-trace-${Date.now()}`,sessionId:o,stream:s=false,callContext:i,model:c,tools:l,providerConfig:p}=t,u=p?.modelId||c||this.defaultModel;if(!u){let h=new d("Ollama model ID is not specified. Provide it in adapter options, runtime config, or call options.","INVALID_CONFIG");return async function*(){yield {type:"ERROR",data:h,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let m;try{m=this.translateToOpenAI(e,u);}catch(h){a.error(`Error translating ArtStandardPrompt to OpenAI format for Ollama: ${h.message}`,{error:h,threadId:r,traceId:n});let R=h instanceof d?h:new d(`Prompt translation failed: ${h.message}`,"PROMPT_TRANSLATION_FAILED",h);return async function*(){yield {type:"ERROR",data:R,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let I=l?this.translateArtToolsToOpenAI(l):void 0,v={model:u,messages:m,temperature:t.temperature??p?.adapterOptions?.temperature,max_tokens:t.max_tokens??t.maxOutputTokens??p?.adapterOptions?.max_tokens,top_p:t.top_p??t.topP??p?.adapterOptions?.top_p,stop:(t.stop||t.stop_sequences||t.stopSequences)??p?.adapterOptions?.stop,stream:s,tools:I,tool_choice:t.tool_choice??p?.adapterOptions?.tool_choice};return Object.keys(v).forEach(h=>{let R=h;v[R]===void 0&&delete v[R];}),a.debug(`Calling Ollama API (via OpenAI client) with model ${u}`,{stream:s,tools:!!I,threadId:r,traceId:n}),async function*(){let h=Date.now(),R,O=0,x,P;try{if(s){let k=await this.client.chat.completions.create(v),_=[];for await(let w of k){R||(R=Date.now()-h);let f=w.choices[0]?.delta;if(P=w.choices[0]?.finish_reason??P,f?.content){O++;let A=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:f.content,threadId:r,traceId:n,sessionId:o,tokenType:A};}f?.tool_calls&&f.tool_calls.forEach(A=>{if(A.index!==void 0)if(!_[A.index])_[A.index]={id:A.id||"",type:"function",function:{name:A.function?.name||"",arguments:A.function?.arguments||""}};else {let M=_[A.index];M.type==="function"&&(A.id&&(M.id=A.id),A.function?.name&&(M.function.name=A.function.name),A.function?.arguments&&(M.function||(M.function={name:"",arguments:""}),M.function.arguments+=A.function.arguments));}}),w.usage&&(x=w.usage);}if(P==="tool_calls"&&_.length>0){let w=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:_.filter(A=>A.type==="function").map(A=>{let M=A;return {type:"tool_use",id:M.id,name:M.function.name,input:JSON.parse(M.function.arguments||"{}")}}),threadId:r,traceId:n,sessionId:o,tokenType:w};}}else {let k=await this.client.chat.completions.create(v),_=k.choices[0];if(!_||!_.message)throw new d("Invalid response structure from Ollama API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(k)));P=_.finish_reason??void 0,x=k.usage;let w=_.message,f=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";if(w.tool_calls&&w.tool_calls.length>0){let A=w.tool_calls.filter(M=>M.type==="function").map(M=>{let N=M;return {type:"tool_use",id:N.id,name:N.function.name,input:JSON.parse(N.function.arguments||"{}")}});w.content?yield {type:"TOKEN",data:[{type:"text",text:w.content.trim()},...A],threadId:r,traceId:n,sessionId:o,tokenType:f}:yield {type:"TOKEN",data:A,threadId:r,traceId:n,sessionId:o,tokenType:f};}else w.content&&(yield {type:"TOKEN",data:w.content.trim(),threadId:r,traceId:n,sessionId:o,tokenType:f});}let T=Date.now()-h;yield {type:"METADATA",data:{stopReason:P,inputTokens:x?.prompt_tokens,outputTokens:x?.completion_tokens??(s?O:void 0),timeToFirstTokenMs:s?R:void 0,totalGenerationTimeMs:T,providerRawUsage:{usage:x,finish_reason:P},traceId:n},threadId:r,traceId:n,sessionId:o};}catch(T){a.error(`Error during Ollama API call: ${T.message}`,{error:T,threadId:r,traceId:n}),yield {type:"ERROR",data:T instanceof d?T:T.constructor.name==="APIError"?new d(`Ollama API Error (${T.status}): ${T.message}`,"LLM_PROVIDER_ERROR",T):new d(T.message||"Unknown Ollama adapter error","LLM_PROVIDER_ERROR",T),threadId:r,traceId:n,sessionId:o};}finally{yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}.bind(this)()}translateToOpenAI(e,t){let r=[...e],n=[];if(t?.toLowerCase().includes("deepseek-r1")){a.debug(`OllamaAdapter: Applying R1-style message merging for model: ${t}`);let s=null;for(let i of r){let c="user";i.role==="system"?c="system":i.role==="user"?c="user":i.role==="assistant"?c="assistant":i.role==="tool_result"&&(c="tool");let l=this.mapArtMessageToOpenAIMessage(i);if(s&&s.role===c&&c!=="system"&&c!=="tool"){let p="";typeof s.content=="string"&&typeof l.content=="string"?p=`${s.content}
94
94
  ${l.content}`:typeof s.content=="string"?p=`${s.content}
95
95
  ${l.content===null?"":String(l.content)}`:typeof l.content=="string"?p=`${s.content===null?"":String(s.content)}
96
96
  ${l.content}`:p=`${s.content===null?"":String(s.content)}
97
- ${l.content===null?"":String(l.content)}`,s.content=p.trim()||null,s.role==="assistant"&&l.role==="assistant"&&l.tool_calls&&(s.tool_calls=[...s.tool_calls||[],...l.tool_calls]),s.role==="assistant"&&!s.content&&s.tool_calls&&s.tool_calls.length>0&&(s.content=null);}else s=l,n.push(s);}}else for(let s of r)n.push(this.mapArtMessageToOpenAIMessage(s));return n}mapArtMessageToOpenAIMessage(e){switch(e.role){case "system":return {role:"system",content:typeof e.content=="string"?e.content:String(e.content)};case "user":return {role:"user",content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};case "assistant":{let t={role:"assistant",content:typeof e.content=="string"?e.content:null};return e.tool_calls&&e.tool_calls.length>0&&(t.tool_calls=e.tool_calls.map(r=>{if(r.type!=="function"||!r.function?.name||typeof r.function?.arguments!="string")throw new d(`OllamaAdapter: Invalid tool_call structure in assistant message. ID: ${r.id}`,"PROMPT_TRANSLATION_FAILED");return {id:r.id,type:r.type,function:{name:r.function.name,arguments:r.function.arguments}}})),(t.content===""&&t.tool_calls&&t.tool_calls.length>0||t.content===""&&(!t.tool_calls||t.tool_calls.length===0)&&typeof e.content!="string")&&(t.content=null),typeof t.content!="string"&&t.content!==null&&(t.content=null),t}case "tool_result":{if(!e.tool_call_id)throw new d("OllamaAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return {role:"tool",tool_call_id:e.tool_call_id,content:String(e.content)}}case "tool_request":throw new d("OllamaAdapter: Unexpected 'tool_request' role during mapping. This should be handled via assistant's tool_calls.","PROMPT_TRANSLATION_FAILED");default:throw new d(`OllamaAdapter: Unknown message role '${e.role}' encountered during mapping.`,"PROMPT_TRANSLATION_FAILED")}}translateArtToolsToOpenAI(e){return e.map(t=>{if(!t.name||!t.inputSchema)throw new d(`Invalid ART ToolSchema for tool '${t.name||"unknown"}'. Must include name and inputSchema.`,"INVALID_CONFIG");return {type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}})}async shutdown(){return a.debug(`OllamaAdapter shutdown called. No specific resources to release for model ${this.defaultModel||"not set"}.`),Promise.resolve()}};var Xt={sqrt:_.sqrt,cbrt:_.cbrt,abs:_.abs,pow:_.pow,exp:_.exp,log:_.log,log10:_.log10,log2:_.log2,sin:_.sin,cos:_.cos,tan:_.tan,asin:_.asin,acos:_.acos,atan:_.atan,atan2:_.atan2,round:_.round,floor:_.floor,ceil:_.ceil,mod:_.mod,mean:_.mean,median:_.median,std:_.std,variance:_.variance,max:_.max,min:_.min,factorial:_.factorial,gamma:_.gamma,combinations:_.combinations,permutations:_.permutations,format:_.format},Ue=class Ue{constructor(){this.resultStore=new Map;this.schema={name:Ue.toolName,description:`Evaluates mathematical expressions using a sandboxed mathjs environment.
97
+ ${l.content===null?"":String(l.content)}`,s.content=p.trim()||null,s.role==="assistant"&&l.role==="assistant"&&l.tool_calls&&(s.tool_calls=[...s.tool_calls||[],...l.tool_calls]),s.role==="assistant"&&!s.content&&s.tool_calls&&s.tool_calls.length>0&&(s.content=null);}else s=l,n.push(s);}}else for(let s of r)n.push(this.mapArtMessageToOpenAIMessage(s));return n}mapArtMessageToOpenAIMessage(e){switch(e.role){case "system":return {role:"system",content:typeof e.content=="string"?e.content:String(e.content)};case "user":return {role:"user",content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};case "assistant":{let t={role:"assistant",content:typeof e.content=="string"?e.content:null};return e.tool_calls&&e.tool_calls.length>0&&(t.tool_calls=e.tool_calls.map(r=>{if(r.type!=="function"||!r.function?.name||typeof r.function?.arguments!="string")throw new d(`OllamaAdapter: Invalid tool_call structure in assistant message. ID: ${r.id}`,"PROMPT_TRANSLATION_FAILED");return {id:r.id,type:r.type,function:{name:r.function.name,arguments:r.function.arguments}}})),(t.content===""&&t.tool_calls&&t.tool_calls.length>0||t.content===""&&(!t.tool_calls||t.tool_calls.length===0)&&typeof e.content!="string")&&(t.content=null),typeof t.content!="string"&&t.content!==null&&(t.content=null),t}case "tool_result":{if(!e.tool_call_id)throw new d("OllamaAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return {role:"tool",tool_call_id:e.tool_call_id,content:String(e.content)}}case "tool_request":throw new d("OllamaAdapter: Unexpected 'tool_request' role during mapping. This should be handled via assistant's tool_calls.","PROMPT_TRANSLATION_FAILED");default:throw new d(`OllamaAdapter: Unknown message role '${e.role}' encountered during mapping.`,"PROMPT_TRANSLATION_FAILED")}}translateArtToolsToOpenAI(e){return e.map(t=>{if(!t.name||!t.inputSchema)throw new d(`Invalid ART ToolSchema for tool '${t.name||"unknown"}'. Must include name and inputSchema.`,"INVALID_CONFIG");return {type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}}})}async shutdown(){return a.debug(`OllamaAdapter shutdown called. No specific resources to release for model ${this.defaultModel||"not set"}.`),Promise.resolve()}};var rr={sqrt:E.sqrt,cbrt:E.cbrt,abs:E.abs,pow:E.pow,exp:E.exp,log:E.log,log10:E.log10,log2:E.log2,sin:E.sin,cos:E.cos,tan:E.tan,asin:E.asin,acos:E.acos,atan:E.atan,atan2:E.atan2,round:E.round,floor:E.floor,ceil:E.ceil,mod:E.mod,mean:E.mean,median:E.median,std:E.std,variance:E.variance,max:E.max,min:E.min,factorial:E.factorial,gamma:E.gamma,combinations:E.combinations,permutations:E.permutations,format:E.format},Ge=class Ge{constructor(){this.resultStore=new Map;this.schema={name:Ge.toolName,description:`Evaluates mathematical expressions using a sandboxed mathjs environment.
98
98
  You can reference previous calculation results using the 'ans' variable.
99
99
  Supports standard operators (+, -, *, /, %, ^), variables via 'scope', complex numbers, and the following allowed functions:
100
100
  sqrt, cbrt, abs, pow, exp, log, log10, log2, sin, cos, tan, asin, acos, atan, atan2, round, floor, ceil, mod,
101
- mean, median, std, variance, max, min, factorial, gamma, combinations, permutations, format.`,inputSchema:{type:"object",properties:{expression:{type:"string",description:'The mathematical expression to evaluate (e.g., "2 + 2", "sqrt(a)", "a * b", "sqrt(-4)", "factorial(5)", "ans + 10").'},scope:{type:"object",description:'An optional object containing variables and their values (numbers only) to be used in the expression (e.g., {"a": 16, "b": 3}).',additionalProperties:{type:"number"},default:{}}},required:["expression"]},examples:[{input:{expression:"2 + 2"},output:{result:4},description:"Simple addition"},{input:{expression:"12 % 5"},output:{result:2},description:"Modulo operation"},{input:{expression:"sqrt(16)"},output:{result:4},description:"Square root function"},{input:{expression:"a + b",scope:{a:7,b:3}},output:{result:10},description:"Expression with variables"},{input:{expression:"result % 13",scope:{result:347}},output:{result:9},description:"Modulo with variable"},{input:{expression:"sqrt(-4)"},output:{result:"2i"},description:"Square root of negative (complex result)"},{input:{expression:"pow(i, 2)"},output:{result:-1},description:"Complex number calculation (i^2)"},{input:{expression:"log(10)"},output:{result:2.302585092994046},description:"Natural logarithm"},{input:{expression:"factorial(5)"},output:{result:120},description:"Factorial function"},{input:{expression:"ans + 10"},output:{result:130},description:"Using previous result with 'ans'"},{input:{expression:"mean([1, 2, 3, 4, 5])"},output:{result:3},description:"Statistical function"}]};}async execute(e,t){let r=e.expression,n=t.threadId||"default-thread",o=this.resultStore.get(n),s={...Xt,...e.scope||{},...o!==void 0?{ans:o}:{}},i=t.traceId||"calculator-call";a.debug(`CalculatorTool executing with expression: "${r}" and combined scope keys: ${Object.keys(s).join(", ")}`,{callId:i,context:t});try{let c=evaluate(r,s),l;if(typeof c=="number"&&Number.isFinite(c))l=c;else if(_.isComplex(c))l=c.toString();else throw new Error(`Evaluation resulted in an unsupported type: ${_.typeOf(c)}`);return this.resultStore.set(n,c),a.info(`CalculatorTool evaluated "${r}" to ${l}`,{callId:i}),{callId:i,toolName:this.schema.name,status:"success",output:{result:l}}}catch(c){return a.error(`CalculatorTool failed to evaluate expression "${r}": ${c.message}`,{callId:i,error:c}),{callId:i,toolName:this.schema.name,status:"error",error:`Failed to evaluate expression: ${c.message}`}}}};Ue.toolName="calculator";var We=Ue;var Ze=class{constructor(e){this.cachedToken=null;this.codeVerifierForPendingLogin=null;this.loginWaiter=null;if(!e.authorizationEndpoint||!e.tokenEndpoint||!e.clientId||!e.redirectUri||!e.scopes)throw new d("PKCEOAuthStrategy requires authorizationEndpoint, tokenEndpoint, clientId, redirectUri, and scopes.","INVALID_CONFIG");this.config={openInNewTab:true,channelName:"art-auth",...e};try{this.channel=new BroadcastChannel(this.config.channelName),this.channel.onmessage=async t=>{let r=t.data||{};if(r?.type==="art-auth-code"&&typeof r?.code=="string")try{await this.exchangeCodeForToken(r.code),this.loginWaiter&&this.loginWaiter.resolve();}catch(n){this.loginWaiter&&this.loginWaiter.reject(n);}finally{this.loginWaiter=null;}};}catch{}}async login(){let e=this.generateCodeVerifier(),t=await this.generateCodeChallenge(e);sessionStorage.setItem("pkce_code_verifier",e),this.codeVerifierForPendingLogin=e;let r=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,scope:this.config.scopes,response_type:"code",code_challenge:t,code_challenge_method:"S256"});this.config.resource&&r.append("resource",this.config.resource);try{let o={ch:this.config.channelName},s=btoa(unescape(encodeURIComponent(JSON.stringify(o)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");r.append("state",s);}catch{}let n=`${this.config.authorizationEndpoint}?${r.toString()}`;if(a.info("Starting PKCE login at authorization endpoint."),this.config.openInNewTab){if(!window.open(n,"_blank","noopener,noreferrer"))throw new d("Popup blocked. Please allow popups to continue login.","INVALID_CONFIG");await new Promise((s,i)=>{this.loginWaiter={resolve:s,reject:i},setTimeout(()=>{this.loginWaiter&&(this.loginWaiter=null,i(new d("Login timed out. Please try again.","TIMEOUT")));},18e4);});return}window.location.assign(n);}async handleRedirect(){let e=new URLSearchParams(window.location.search),t=e.get("code");if(!t){let n=e.get("error"),o=e.get("error_description");throw new d(`OAuth error on redirect: ${n} - ${o||"No description provided."}`,"EXTERNAL_SERVICE_ERROR")}let r=sessionStorage.getItem("pkce_code_verifier");if(!r)throw new d("No PKCE code verifier found in session storage. Please initiate login again.","INVALID_CONFIG");try{let n=await fetch(this.config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,code:t,code_verifier:r})});if(!n.ok){let s=await n.text();throw new d(`Failed to exchange authorization code for token: ${s}`,"NETWORK_ERROR")}let o=await n.json();this.cachedToken={accessToken:o.access_token,refreshToken:o.refresh_token,expiresAt:Date.now()+(o.expires_in||3600)*1e3},a.info("Successfully obtained access token.");}catch(n){throw a.error("Error during token exchange:",n),new d("An unexpected error occurred during the token exchange process.","UNKNOWN_ERROR",n)}finally{sessionStorage.removeItem("pkce_code_verifier");}}async getAuthHeaders(){if(!this.cachedToken)throw new d("No cached token available. Please login first.","INVALID_CONFIG");return Date.now()>=this.cachedToken.expiresAt&&(a.info("Access token expired, attempting to refresh."),await this.refreshToken()),{Authorization:`Bearer ${this.cachedToken.accessToken}`}}logout(){this.cachedToken=null,sessionStorage.removeItem("pkce_code_verifier"),a.info("Cached token and PKCE code verifier cleared.");}async isAuthenticated(){if(!this.cachedToken)return false;if(Date.now()>=this.cachedToken.expiresAt)try{return await this.refreshToken(),!0}catch{return false}return true}generateCodeVerifier(){let e=new Uint8Array(32);return window.crypto.getRandomValues(e),this.base64UrlEncode(e)}async generateCodeChallenge(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return this.base64UrlEncode(new Uint8Array(n))}base64UrlEncode(e){return btoa(String.fromCharCode.apply(null,Array.from(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async refreshToken(){if(!this.cachedToken?.refreshToken)throw this.logout(),new d("No refresh token available. User must re-authenticate.","INVALID_CONFIG");try{let e=await fetch(this.config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:this.config.clientId,refresh_token:this.cachedToken.refreshToken})});if(!e.ok){let r=await e.text();throw this.logout(),new d(`Failed to refresh token: ${r}`,"NETWORK_ERROR")}let t=await e.json();this.cachedToken={accessToken:t.access_token,refreshToken:t.refresh_token||this.cachedToken.refreshToken,expiresAt:Date.now()+(t.expires_in||3600)*1e3},a.info("Successfully refreshed access token.");}catch(e){throw this.logout(),a.error("Error during token refresh:",e),new d("An unexpected error occurred during the token refresh process.","UNKNOWN_ERROR",e)}}async exchangeCodeForToken(e){if(!this.codeVerifierForPendingLogin)throw new d("Missing code verifier for PKCE exchange.","INVALID_CONFIG");let t=await fetch(this.config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,code:e,code_verifier:this.codeVerifierForPendingLogin})});if(!t.ok){let n=await t.text();throw new d(`Failed to exchange authorization code for token: ${n}`,"NETWORK_ERROR")}let r=await t.json();this.cachedToken={accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:Date.now()+(r.expires_in||3600)*1e3},this.codeVerifierForPendingLogin=null,sessionStorage.removeItem("pkce_code_verifier");}};var Qe=class{constructor(e,t="Authorization"){this.apiKey=e;this.headerName=t;if(!e||e.trim()==="")throw new Error("API key cannot be empty or null");if(!t||t.trim()==="")throw new Error("Header name cannot be empty or null")}async getAuthHeaders(){let e=this.headerName==="Authorization"?`Bearer ${this.apiKey}`:this.apiKey;return {[this.headerName]:e}}getHeaderName(){return this.headerName}isUsingAuthorizationHeader(){return this.headerName==="Authorization"}};var _e=class{constructor(e){this.cachedToken=null;this.refreshPromise=null;this.validateConfig(e),this.config={grantType:"client_credentials",tokenTimeoutMs:3e4,tokenRefreshBufferMs:3e5,...e},a.debug(`GenericOAuthStrategy: Initialized with endpoint ${e.tokenEndpoint} and grant type ${this.config.grantType}`);}validateConfig(e){if(!e.clientId||e.clientId.trim()==="")throw new d("OAuth client ID cannot be empty","VALIDATION_ERROR");if(!e.clientSecret||e.clientSecret.trim()==="")throw new d("OAuth client secret cannot be empty","VALIDATION_ERROR");if(!e.tokenEndpoint||e.tokenEndpoint.trim()==="")throw new d("OAuth token endpoint cannot be empty","VALIDATION_ERROR");try{new URL(e.tokenEndpoint);}catch(t){throw new d("Invalid OAuth token endpoint URL","VALIDATION_ERROR",t instanceof Error?t:new Error(String(t)))}}async getAuthHeaders(){try{let e=await this.getValidToken();return {Authorization:`${e.tokenType} ${e.accessToken}`}}catch(e){let t="Failed to get OAuth authentication headers";throw a.error(t,e),new d(t,"LLM_PROVIDER_ERROR",e instanceof Error?e:new Error(String(e)))}}async getValidToken(){if(this.cachedToken&&this.isTokenValid(this.cachedToken))return a.debug("GenericOAuthStrategy: Using cached token"),this.cachedToken;if(this.refreshPromise)return a.debug("GenericOAuthStrategy: Waiting for ongoing token refresh"),await this.refreshPromise;this.refreshPromise=this.acquireNewToken();try{let e=await this.refreshPromise;return this.cachedToken=e,e}finally{this.refreshPromise=null;}}isTokenValid(e){let t=Date.now(),r=this.config.tokenRefreshBufferMs;return e.expiresAt>t+r}async acquireNewToken(){a.debug(`GenericOAuthStrategy: Acquiring new token from ${this.config.tokenEndpoint}`);let e=this.buildTokenRequest();try{let t=new AbortController,r=setTimeout(()=>t.abort(),this.config.tokenTimeoutMs),n=await fetch(this.config.tokenEndpoint,{...e,signal:t.signal});if(clearTimeout(r),!n.ok){let s=await n.text().catch(()=>"Unknown error");throw new d(`OAuth token request failed: ${n.status} ${n.statusText}: ${s}`,"EXTERNAL_SERVICE_ERROR")}let o=await n.json();return this.processTokenResponse(o)}catch(t){if(t instanceof d)throw t;let r=`Failed to acquire OAuth token: ${t instanceof Error?t.message:String(t)}`;throw a.error(r,t),new d(r,"EXTERNAL_SERVICE_ERROR",t instanceof Error?t:new Error(String(t)))}}buildTokenRequest(){let e={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",...this.config.tokenRequestHeaders},t;if(this.config.grantType==="client_credentials"){let r=new URLSearchParams({grant_type:"client_credentials",client_id:this.config.clientId,client_secret:this.config.clientSecret});this.config.scopes&&r.append("scope",this.config.scopes),t=r.toString();}else if(this.config.grantType==="refresh_token"&&this.cachedToken?.refreshToken)t=new URLSearchParams({grant_type:"refresh_token",refresh_token:this.cachedToken.refreshToken,client_id:this.config.clientId,client_secret:this.config.clientSecret}).toString();else throw new d(`Unsupported grant type: ${this.config.grantType}`,"NOT_IMPLEMENTED");return {method:"POST",headers:e,body:t}}processTokenResponse(e){if(!e.access_token)throw new d("OAuth token response missing access_token","EXTERNAL_SERVICE_ERROR");let t=Date.now(),r=e.expires_in||3600,n=t+r*1e3,o={accessToken:e.access_token,tokenType:e.token_type||"Bearer",expiresAt:n,refreshToken:e.refresh_token,scope:e.scope};return a.debug(`GenericOAuthStrategy: Token acquired, expires at ${new Date(n).toISOString()}`),o}async refreshToken(){return a.debug("GenericOAuthStrategy: Manual token refresh requested"),this.cachedToken=null,this.refreshPromise=null,await this.getAuthHeaders()}clearTokenCache(){a.debug("GenericOAuthStrategy: Clearing token cache"),this.cachedToken=null,this.refreshPromise=null;}getTokenInfo(){return this.cachedToken?{expiresAt:new Date(this.cachedToken.expiresAt),scope:this.cachedToken.scope,hasRefreshToken:!!this.cachedToken.refreshToken}:null}getConfig(){return {clientId:this.config.clientId,tokenEndpoint:this.config.tokenEndpoint,scopes:this.config.scopes,grantType:this.config.grantType,tokenRequestHeaders:this.config.tokenRequestHeaders,tokenTimeoutMs:this.config.tokenTimeoutMs,tokenRefreshBufferMs:this.config.tokenRefreshBufferMs}}};var j=class j extends _e{constructor(e){let t=e.environment||"production",r=j.ZYNTOPIA_ENDPOINTS[t],n=j.ZYNTOPIA_DEFAULT_SCOPES[t],o={clientId:e.clientId,clientSecret:e.clientSecret,tokenEndpoint:e.tokenEndpoint||r,scopes:e.scopes||n,environment:t,tokenTimeoutMs:e.tokenTimeoutMs||3e4,tokenRefreshBufferMs:e.tokenRefreshBufferMs||3e5,customHeaders:e.customHeaders||{}},s={clientId:o.clientId,clientSecret:o.clientSecret,tokenEndpoint:o.tokenEndpoint,scopes:o.scopes,grantType:"client_credentials",tokenTimeoutMs:o.tokenTimeoutMs,tokenRefreshBufferMs:o.tokenRefreshBufferMs,tokenRequestHeaders:{"User-Agent":"ART-Framework-Zyntopia/1.0","X-Zyntopia-Client":"art-framework","X-Zyntopia-Environment":t,...o.customHeaders}};super(s),this.zyntopiaConfig=o,a.debug(`ZyntopiaOAuthStrategy: Initialized for ${t} environment with endpoint ${o.tokenEndpoint}`);}getZyntopiaConfig(){return {clientId:this.zyntopiaConfig.clientId,tokenEndpoint:this.zyntopiaConfig.tokenEndpoint,scopes:this.zyntopiaConfig.scopes,environment:this.zyntopiaConfig.environment,tokenTimeoutMs:this.zyntopiaConfig.tokenTimeoutMs,tokenRefreshBufferMs:this.zyntopiaConfig.tokenRefreshBufferMs,customHeaders:this.zyntopiaConfig.customHeaders}}getEnvironment(){return this.zyntopiaConfig.environment}isProduction(){return this.zyntopiaConfig.environment==="production"}isDevelopment(){return this.zyntopiaConfig.environment!=="production"}static forProduction(e,t,r){return new j({clientId:e,clientSecret:t,environment:"production",scopes:r})}static forStaging(e,t,r){return new j({clientId:e,clientSecret:t,environment:"staging",scopes:r})}static forDevelopment(e,t,r){return new j({clientId:e,clientSecret:t,environment:"development",scopes:r})}static getDefaultScopes(e){return j.ZYNTOPIA_DEFAULT_SCOPES[e]}static getTokenEndpoint(e){return j.ZYNTOPIA_ENDPOINTS[e]}static validateZyntopiaConfig(e){if(!e.clientId||e.clientId.trim()==="")throw new Error("Zyntopia client ID is required");if(!e.clientSecret||e.clientSecret.trim()==="")throw new Error("Zyntopia client secret is required");if(e.environment&&!["production","staging","development"].includes(e.environment))throw new Error("Zyntopia environment must be one of: production, staging, development");if(e.tokenTimeoutMs&&(e.tokenTimeoutMs<1e3||e.tokenTimeoutMs>6e4))throw new Error("Zyntopia token timeout must be between 1000ms and 60000ms");if(e.tokenRefreshBufferMs&&(e.tokenRefreshBufferMs<3e4||e.tokenRefreshBufferMs>6e5))throw new Error("Zyntopia token refresh buffer must be between 30000ms and 600000ms")}};j.ZYNTOPIA_ENDPOINTS={production:"https://auth.zyntopia.com/oauth/token",staging:"https://staging-auth.zyntopia.com/oauth/token",development:"https://dev-auth.zyntopia.com/oauth/token"},j.ZYNTOPIA_DEFAULT_SCOPES={production:"zyntopia:read zyntopia:write zyntopia:admin",staging:"zyntopia:read zyntopia:write zyntopia:admin zyntopia:debug",development:"zyntopia:read zyntopia:write zyntopia:admin zyntopia:debug zyntopia:test"};var et=j;var Ka="0.3.8";
102
- export{it as A2ATaskPriority,ee as A2ATaskSocket,ve as A2ATaskStatus,d as ARTError,se as AdapterInstantiationError,Se as AgentDiscoveryService,$e as AgentFactory,ze as AnthropicAdapter,Qe as ApiKeyStrategy,Ge as ApiQueueTimeoutError,ot as ArtStandardMessageSchema,yt as ArtStandardPromptSchema,Te as AuthManager,We as CalculatorTool,fe as ConversationSocket,Ye as DeepSeekAdapter,H as ErrorCode,Ve as GeminiAdapter,_e as GenericOAuthStrategy,de as InMemoryStorageAdapter,pe as IndexedDBStorageAdapter,Q as LLMStreamSocket,ae as LocalInstanceBusyError,oe as LocalProviderConflictError,nt as LogLevel,a as Logger,te as McpClientController,re as McpManager,Y as McpProxyTool,at as MessageRole,st as ModelCapability,he as ObservationSocket,Fe as ObservationType,Xe as OllamaAdapter,je as OpenAIAdapter,Je as OpenRouterAdapter,ce as PESAgent,Ze as PKCEOAuthStrategy,ie as ProviderManagerImpl,ue as StateManager,Be as SupabaseStorageAdapter,Ie as TaskDelegationService,le as TodoItemStatus,ge as ToolRegistry,V as TypedSocket,ye as UISystem,ne as UnknownProviderError,Ka as VERSION,et as ZyntopiaOAuthStrategy,Lt as createArtInstance,X as generateUUID};//# sourceMappingURL=index.js.map
101
+ mean, median, std, variance, max, min, factorial, gamma, combinations, permutations, format.`,inputSchema:{type:"object",properties:{expression:{type:"string",description:'The mathematical expression to evaluate (e.g., "2 + 2", "sqrt(a)", "a * b", "sqrt(-4)", "factorial(5)", "ans + 10").'},scope:{type:"object",description:'An optional object containing variables and their values (numbers only) to be used in the expression (e.g., {"a": 16, "b": 3}).',additionalProperties:{type:"number"},default:{}}},required:["expression"]},examples:[{input:{expression:"2 + 2"},output:{result:4},description:"Simple addition"},{input:{expression:"12 % 5"},output:{result:2},description:"Modulo operation"},{input:{expression:"sqrt(16)"},output:{result:4},description:"Square root function"},{input:{expression:"a + b",scope:{a:7,b:3}},output:{result:10},description:"Expression with variables"},{input:{expression:"result % 13",scope:{result:347}},output:{result:9},description:"Modulo with variable"},{input:{expression:"sqrt(-4)"},output:{result:"2i"},description:"Square root of negative (complex result)"},{input:{expression:"pow(i, 2)"},output:{result:-1},description:"Complex number calculation (i^2)"},{input:{expression:"log(10)"},output:{result:2.302585092994046},description:"Natural logarithm"},{input:{expression:"factorial(5)"},output:{result:120},description:"Factorial function"},{input:{expression:"ans + 10"},output:{result:130},description:"Using previous result with 'ans'"},{input:{expression:"mean([1, 2, 3, 4, 5])"},output:{result:3},description:"Statistical function"}]};}async execute(e,t){let r=e.expression,n=t.threadId||"default-thread",o=this.resultStore.get(n),s={...rr,...e.scope||{},...o!==void 0?{ans:o}:{}},i=t.traceId||"calculator-call";a.debug(`CalculatorTool executing with expression: "${r}" and combined scope keys: ${Object.keys(s).join(", ")}`,{callId:i,context:t});try{let c=evaluate(r,s),l;if(typeof c=="number"&&Number.isFinite(c))l=c;else if(E.isComplex(c))l=c.toString();else throw new Error(`Evaluation resulted in an unsupported type: ${E.typeOf(c)}`);return this.resultStore.set(n,c),a.info(`CalculatorTool evaluated "${r}" to ${l}`,{callId:i}),{callId:i,toolName:this.schema.name,status:"success",output:{result:l}}}catch(c){return a.error(`CalculatorTool failed to evaluate expression "${r}": ${c.message}`,{callId:i,error:c}),{callId:i,toolName:this.schema.name,status:"error",error:`Failed to evaluate expression: ${c.message}`}}}};Ge.toolName="calculator";var Ze=Ge;var Qe=class{constructor(e){this.cachedToken=null;this.codeVerifierForPendingLogin=null;this.loginWaiter=null;if(!e.authorizationEndpoint||!e.tokenEndpoint||!e.clientId||!e.redirectUri||!e.scopes)throw new d("PKCEOAuthStrategy requires authorizationEndpoint, tokenEndpoint, clientId, redirectUri, and scopes.","INVALID_CONFIG");this.config={openInNewTab:true,channelName:"art-auth",...e};try{this.channel=new BroadcastChannel(this.config.channelName),this.channel.onmessage=async t=>{let r=t.data||{};if(r?.type==="art-auth-code"&&typeof r?.code=="string")try{await this.exchangeCodeForToken(r.code),this.loginWaiter&&this.loginWaiter.resolve();}catch(n){this.loginWaiter&&this.loginWaiter.reject(n);}finally{this.loginWaiter=null;}};}catch{}}async login(){let e=this.generateCodeVerifier(),t=await this.generateCodeChallenge(e);sessionStorage.setItem("pkce_code_verifier",e),this.codeVerifierForPendingLogin=e;let r=new URLSearchParams({client_id:this.config.clientId,redirect_uri:this.config.redirectUri,scope:this.config.scopes,response_type:"code",code_challenge:t,code_challenge_method:"S256"});this.config.resource&&r.append("resource",this.config.resource);try{let o={ch:this.config.channelName},s=btoa(unescape(encodeURIComponent(JSON.stringify(o)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");r.append("state",s);}catch{}let n=`${this.config.authorizationEndpoint}?${r.toString()}`;if(a.info("Starting PKCE login at authorization endpoint."),this.config.openInNewTab){if(!window.open(n,"_blank","noopener,noreferrer"))throw new d("Popup blocked. Please allow popups to continue login.","INVALID_CONFIG");await new Promise((s,i)=>{this.loginWaiter={resolve:s,reject:i},setTimeout(()=>{this.loginWaiter&&(this.loginWaiter=null,i(new d("Login timed out. Please try again.","TIMEOUT")));},18e4);});return}window.location.assign(n);}async handleRedirect(){let e=new URLSearchParams(window.location.search),t=e.get("code");if(!t){let n=e.get("error"),o=e.get("error_description");throw new d(`OAuth error on redirect: ${n} - ${o||"No description provided."}`,"EXTERNAL_SERVICE_ERROR")}let r=sessionStorage.getItem("pkce_code_verifier");if(!r)throw new d("No PKCE code verifier found in session storage. Please initiate login again.","INVALID_CONFIG");try{let n=await fetch(this.config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,code:t,code_verifier:r})});if(!n.ok){let s=await n.text();throw new d(`Failed to exchange authorization code for token: ${s}`,"NETWORK_ERROR")}let o=await n.json();this.cachedToken={accessToken:o.access_token,refreshToken:o.refresh_token,expiresAt:Date.now()+(o.expires_in||3600)*1e3},a.info("Successfully obtained access token.");}catch(n){throw a.error("Error during token exchange:",n),new d("An unexpected error occurred during the token exchange process.","UNKNOWN_ERROR",n)}finally{sessionStorage.removeItem("pkce_code_verifier");}}async getAuthHeaders(){if(!this.cachedToken)throw new d("No cached token available. Please login first.","INVALID_CONFIG");return Date.now()>=this.cachedToken.expiresAt&&(a.info("Access token expired, attempting to refresh."),await this.refreshToken()),{Authorization:`Bearer ${this.cachedToken.accessToken}`}}logout(){this.cachedToken=null,sessionStorage.removeItem("pkce_code_verifier"),a.info("Cached token and PKCE code verifier cleared.");}async isAuthenticated(){if(!this.cachedToken)return false;if(Date.now()>=this.cachedToken.expiresAt)try{return await this.refreshToken(),!0}catch{return false}return true}generateCodeVerifier(){let e=new Uint8Array(32);return window.crypto.getRandomValues(e),this.base64UrlEncode(e)}async generateCodeChallenge(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return this.base64UrlEncode(new Uint8Array(n))}base64UrlEncode(e){return btoa(String.fromCharCode.apply(null,Array.from(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async refreshToken(){if(!this.cachedToken?.refreshToken)throw this.logout(),new d("No refresh token available. User must re-authenticate.","INVALID_CONFIG");try{let e=await fetch(this.config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:this.config.clientId,refresh_token:this.cachedToken.refreshToken})});if(!e.ok){let r=await e.text();throw this.logout(),new d(`Failed to refresh token: ${r}`,"NETWORK_ERROR")}let t=await e.json();this.cachedToken={accessToken:t.access_token,refreshToken:t.refresh_token||this.cachedToken.refreshToken,expiresAt:Date.now()+(t.expires_in||3600)*1e3},a.info("Successfully refreshed access token.");}catch(e){throw this.logout(),a.error("Error during token refresh:",e),new d("An unexpected error occurred during the token refresh process.","UNKNOWN_ERROR",e)}}async exchangeCodeForToken(e){if(!this.codeVerifierForPendingLogin)throw new d("Missing code verifier for PKCE exchange.","INVALID_CONFIG");let t=await fetch(this.config.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:this.config.clientId,redirect_uri:this.config.redirectUri,code:e,code_verifier:this.codeVerifierForPendingLogin})});if(!t.ok){let n=await t.text();throw new d(`Failed to exchange authorization code for token: ${n}`,"NETWORK_ERROR")}let r=await t.json();this.cachedToken={accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:Date.now()+(r.expires_in||3600)*1e3},this.codeVerifierForPendingLogin=null,sessionStorage.removeItem("pkce_code_verifier");}};var et=class{constructor(e,t="Authorization"){this.apiKey=e;this.headerName=t;if(!e||e.trim()==="")throw new Error("API key cannot be empty or null");if(!t||t.trim()==="")throw new Error("Header name cannot be empty or null")}async getAuthHeaders(){let e=this.headerName==="Authorization"?`Bearer ${this.apiKey}`:this.apiKey;return {[this.headerName]:e}}getHeaderName(){return this.headerName}isUsingAuthorizationHeader(){return this.headerName==="Authorization"}};var ve=class{constructor(e){this.cachedToken=null;this.refreshPromise=null;this.validateConfig(e),this.config={grantType:"client_credentials",tokenTimeoutMs:3e4,tokenRefreshBufferMs:3e5,...e},a.debug(`GenericOAuthStrategy: Initialized with endpoint ${e.tokenEndpoint} and grant type ${this.config.grantType}`);}validateConfig(e){if(!e.clientId||e.clientId.trim()==="")throw new d("OAuth client ID cannot be empty","VALIDATION_ERROR");if(!e.clientSecret||e.clientSecret.trim()==="")throw new d("OAuth client secret cannot be empty","VALIDATION_ERROR");if(!e.tokenEndpoint||e.tokenEndpoint.trim()==="")throw new d("OAuth token endpoint cannot be empty","VALIDATION_ERROR");try{new URL(e.tokenEndpoint);}catch(t){throw new d("Invalid OAuth token endpoint URL","VALIDATION_ERROR",t instanceof Error?t:new Error(String(t)))}}async getAuthHeaders(){try{let e=await this.getValidToken();return {Authorization:`${e.tokenType} ${e.accessToken}`}}catch(e){let t="Failed to get OAuth authentication headers";throw a.error(t,e),new d(t,"LLM_PROVIDER_ERROR",e instanceof Error?e:new Error(String(e)))}}async getValidToken(){if(this.cachedToken&&this.isTokenValid(this.cachedToken))return a.debug("GenericOAuthStrategy: Using cached token"),this.cachedToken;if(this.refreshPromise)return a.debug("GenericOAuthStrategy: Waiting for ongoing token refresh"),await this.refreshPromise;this.refreshPromise=this.acquireNewToken();try{let e=await this.refreshPromise;return this.cachedToken=e,e}finally{this.refreshPromise=null;}}isTokenValid(e){let t=Date.now(),r=this.config.tokenRefreshBufferMs;return e.expiresAt>t+r}async acquireNewToken(){a.debug(`GenericOAuthStrategy: Acquiring new token from ${this.config.tokenEndpoint}`);let e=this.buildTokenRequest();try{let t=new AbortController,r=setTimeout(()=>t.abort(),this.config.tokenTimeoutMs),n=await fetch(this.config.tokenEndpoint,{...e,signal:t.signal});if(clearTimeout(r),!n.ok){let s=await n.text().catch(()=>"Unknown error");throw new d(`OAuth token request failed: ${n.status} ${n.statusText}: ${s}`,"EXTERNAL_SERVICE_ERROR")}let o=await n.json();return this.processTokenResponse(o)}catch(t){if(t instanceof d)throw t;let r=`Failed to acquire OAuth token: ${t instanceof Error?t.message:String(t)}`;throw a.error(r,t),new d(r,"EXTERNAL_SERVICE_ERROR",t instanceof Error?t:new Error(String(t)))}}buildTokenRequest(){let e={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",...this.config.tokenRequestHeaders},t;if(this.config.grantType==="client_credentials"){let r=new URLSearchParams({grant_type:"client_credentials",client_id:this.config.clientId,client_secret:this.config.clientSecret});this.config.scopes&&r.append("scope",this.config.scopes),t=r.toString();}else if(this.config.grantType==="refresh_token"&&this.cachedToken?.refreshToken)t=new URLSearchParams({grant_type:"refresh_token",refresh_token:this.cachedToken.refreshToken,client_id:this.config.clientId,client_secret:this.config.clientSecret}).toString();else throw new d(`Unsupported grant type: ${this.config.grantType}`,"NOT_IMPLEMENTED");return {method:"POST",headers:e,body:t}}processTokenResponse(e){if(!e.access_token)throw new d("OAuth token response missing access_token","EXTERNAL_SERVICE_ERROR");let t=Date.now(),r=e.expires_in||3600,n=t+r*1e3,o={accessToken:e.access_token,tokenType:e.token_type||"Bearer",expiresAt:n,refreshToken:e.refresh_token,scope:e.scope};return a.debug(`GenericOAuthStrategy: Token acquired, expires at ${new Date(n).toISOString()}`),o}async refreshToken(){return a.debug("GenericOAuthStrategy: Manual token refresh requested"),this.cachedToken=null,this.refreshPromise=null,await this.getAuthHeaders()}clearTokenCache(){a.debug("GenericOAuthStrategy: Clearing token cache"),this.cachedToken=null,this.refreshPromise=null;}getTokenInfo(){return this.cachedToken?{expiresAt:new Date(this.cachedToken.expiresAt),scope:this.cachedToken.scope,hasRefreshToken:!!this.cachedToken.refreshToken}:null}getConfig(){return {clientId:this.config.clientId,tokenEndpoint:this.config.tokenEndpoint,scopes:this.config.scopes,grantType:this.config.grantType,tokenRequestHeaders:this.config.tokenRequestHeaders,tokenTimeoutMs:this.config.tokenTimeoutMs,tokenRefreshBufferMs:this.config.tokenRefreshBufferMs}}};var j=class j extends ve{constructor(e){let t=e.environment||"production",r=j.ZYNTOPIA_ENDPOINTS[t],n=j.ZYNTOPIA_DEFAULT_SCOPES[t],o={clientId:e.clientId,clientSecret:e.clientSecret,tokenEndpoint:e.tokenEndpoint||r,scopes:e.scopes||n,environment:t,tokenTimeoutMs:e.tokenTimeoutMs||3e4,tokenRefreshBufferMs:e.tokenRefreshBufferMs||3e5,customHeaders:e.customHeaders||{}},s={clientId:o.clientId,clientSecret:o.clientSecret,tokenEndpoint:o.tokenEndpoint,scopes:o.scopes,grantType:"client_credentials",tokenTimeoutMs:o.tokenTimeoutMs,tokenRefreshBufferMs:o.tokenRefreshBufferMs,tokenRequestHeaders:{"User-Agent":"ART-Framework-Zyntopia/1.0","X-Zyntopia-Client":"art-framework","X-Zyntopia-Environment":t,...o.customHeaders}};super(s),this.zyntopiaConfig=o,a.debug(`ZyntopiaOAuthStrategy: Initialized for ${t} environment with endpoint ${o.tokenEndpoint}`);}getZyntopiaConfig(){return {clientId:this.zyntopiaConfig.clientId,tokenEndpoint:this.zyntopiaConfig.tokenEndpoint,scopes:this.zyntopiaConfig.scopes,environment:this.zyntopiaConfig.environment,tokenTimeoutMs:this.zyntopiaConfig.tokenTimeoutMs,tokenRefreshBufferMs:this.zyntopiaConfig.tokenRefreshBufferMs,customHeaders:this.zyntopiaConfig.customHeaders}}getEnvironment(){return this.zyntopiaConfig.environment}isProduction(){return this.zyntopiaConfig.environment==="production"}isDevelopment(){return this.zyntopiaConfig.environment!=="production"}static forProduction(e,t,r){return new j({clientId:e,clientSecret:t,environment:"production",scopes:r})}static forStaging(e,t,r){return new j({clientId:e,clientSecret:t,environment:"staging",scopes:r})}static forDevelopment(e,t,r){return new j({clientId:e,clientSecret:t,environment:"development",scopes:r})}static getDefaultScopes(e){return j.ZYNTOPIA_DEFAULT_SCOPES[e]}static getTokenEndpoint(e){return j.ZYNTOPIA_ENDPOINTS[e]}static validateZyntopiaConfig(e){if(!e.clientId||e.clientId.trim()==="")throw new Error("Zyntopia client ID is required");if(!e.clientSecret||e.clientSecret.trim()==="")throw new Error("Zyntopia client secret is required");if(e.environment&&!["production","staging","development"].includes(e.environment))throw new Error("Zyntopia environment must be one of: production, staging, development");if(e.tokenTimeoutMs&&(e.tokenTimeoutMs<1e3||e.tokenTimeoutMs>6e4))throw new Error("Zyntopia token timeout must be between 1000ms and 60000ms");if(e.tokenRefreshBufferMs&&(e.tokenRefreshBufferMs<3e4||e.tokenRefreshBufferMs>6e5))throw new Error("Zyntopia token refresh buffer must be between 30000ms and 600000ms")}};j.ZYNTOPIA_ENDPOINTS={production:"https://auth.zyntopia.com/oauth/token",staging:"https://staging-auth.zyntopia.com/oauth/token",development:"https://dev-auth.zyntopia.com/oauth/token"},j.ZYNTOPIA_DEFAULT_SCOPES={production:"zyntopia:read zyntopia:write zyntopia:admin",staging:"zyntopia:read zyntopia:write zyntopia:admin zyntopia:debug",development:"zyntopia:read zyntopia:write zyntopia:admin zyntopia:debug zyntopia:test"};var tt=j;var za="0.4.2";
102
+ export{it as A2ATaskPriority,re as A2ATaskSocket,Re as A2ATaskStatus,d as ARTError,le as AdapterInstantiationError,_e as AgentDiscoveryService,Ue as AgentFactory,Je as AnthropicAdapter,et as ApiKeyStrategy,Fe as ApiQueueTimeoutError,ot as ArtStandardMessageSchema,yt as ArtStandardPromptSchema,Se as AuthManager,Ze as CalculatorTool,Te as ConversationSocket,Xe as DeepSeekAdapter,F as ErrorCode,je as GeminiAdapter,ve as GenericOAuthStrategy,ue as InMemoryStorageAdapter,ge as IndexedDBStorageAdapter,te as LLMStreamSocket,ie as LocalInstanceBusyError,se as LocalProviderConflictError,nt as LogLevel,a as Logger,ne as McpClientController,oe as McpManager,W as McpProxyTool,at as MessageRole,st as ModelCapability,ye as ObservationSocket,He as ObservationType,We as OllamaAdapter,ze as OpenAIAdapter,Ye as OpenRouterAdapter,pe as PESAgent,Qe as PKCEOAuthStrategy,ce as ProviderManagerImpl,me as StateManager,Ve as SupabaseStorageAdapter,Ee as TaskDelegationService,de as TodoItemStatus,he as ToolRegistry,V as TypedSocket,Ae as UISystem,ae as UnknownProviderError,za as VERSION,tt as ZyntopiaOAuthStrategy,Lt as createArtInstance,Z as generateUUID};//# sourceMappingURL=index.js.map
103
103
  //# sourceMappingURL=index.js.map