art-framework 0.3.1 → 0.3.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/README.md +7 -1
- package/dist/index.cjs +67 -48
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +67 -48
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {v4}from'uuid';import*as F from'zod';import {z as z$1,ZodError}from'zod';import lt from'ajv';import pt from'mustache';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 {Anthropic}from'@anthropic-ai/sdk';import Ot from'openai';import*as I from'mathjs';import {evaluate}from'mathjs';var
|
|
2
|
-
Caused by: ${this.originalError.stack||this.originalError.toString()}`),e}},V=class extends c{constructor(e){super(`Unknown provider requested: ${e}`,"UNKNOWN_PROVIDER"),this.name="UnknownProviderError";}},j=class extends c{constructor(e,t){super(`Cannot activate local provider '${e}'. Local provider '${t}' is already active.`,"LOCAL_PROVIDER_CONFLICT"),this.name="LocalProviderConflictError";}},J=class extends c{constructor(e,t){super(`Local provider instance '${e}:${t}' is currently busy.`,"LOCAL_INSTANCE_BUSY"),this.name="LocalInstanceBusyError";}},be=class extends c{constructor(e){super(`Timeout waiting for an available instance of API provider '${e}'.`,"API_QUEUE_TIMEOUT"),this.name="ApiQueueTimeoutError";}},z=class extends c{constructor(e,t){super(`Failed to instantiate adapter for provider '${e}'.`,"ADAPTER_INSTANTIATION_ERROR",t),this.name="AdapterInstantiationError";}};var se=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 l=()=>this._releaseAdapter(t);return {adapter:r.adapter,release:l}}let n=this.availableProviders.get(e.providerName);if(!n)throw new V(e.providerName);if(n.isLocal){let l;for(let[p,g]of this.managedInstances.entries()){let A=this.availableProviders.get(g.configSignature.split('"providerName":"')[1].split('"')[0]);if(A?.isLocal){if(g.state==="active")throw p!==t?new j(e.providerName,A.name):new J(e.providerName,e.modelId);g.state==="idle"&&p!==t&&(l=g);}}l&&await this._evictInstance(l.configSignature);}if(!n.isLocal&&Array.from(this.managedInstances.values()).filter(p=>{let g=this.availableProviders.get(p.configSignature.split('"providerName":"')[1].split('"')[0]);return g&&!g.isLocal&&p.state==="active"&&g.name===e.providerName}).length>=this.maxParallelApiInstancesPerProvider)return new Promise((p,g)=>{this.requestQueue.push({config:e,resolve:p,reject:g});});let o;try{let l={...e.adapterOptions,providerName:e.providerName};o=new n.adapter(l);}catch(l){throw new z(e.providerName,l)}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 je=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(je||{}),L=class L{static configure(e){L.config={...L.config,...e};}static debug(e,...t){L.config.level<=0&&console.debug(`${L.config.prefix||"[ART]"} ${e}`,...t);}static info(e,...t){L.config.level<=1&&console.info(`${L.config.prefix||"[ART]"} ${e}`,...t);}static warn(e,...t){L.config.level<=2&&console.warn(`${L.config.prefix||"[ART]"} ${e}`,...t);}static error(e,...t){L.config.level<=3&&console.error(`${L.config.prefix||"[ART]"} ${e}`,...t);}};L.config={level:1};var a=L;var U=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 Y=class extends U{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 W=class extends U{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 Je=z$1.object({role:z$1.custom(f=>typeof f=="string"&&["system","user","assistant","tool","tool_request","tool_result"].includes(f),{message:"Invalid message role"}),content:z$1.union([z$1.string(),z$1.record(z$1.any()),z$1.null()]),name:z$1.string().optional(),tool_calls:z$1.array(z$1.object({id:z$1.string(),type:z$1.literal("function"),function:z$1.object({name:z$1.string(),arguments:z$1.string()})})).optional(),tool_call_id:z$1.string().optional()}).strict().refine(f=>!((f.role==="tool"||f.role==="tool_result")&&!f.tool_call_id||f.role==="assistant"&&f.content!==null&&typeof f.content!="string"||(f.role==="user"||f.role==="system")&&typeof f.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)"}),Me=z$1.array(Je);var ze=(n=>(n.USER="USER",n.AI="AI",n.SYSTEM="SYSTEM",n.TOOL="TOOL",n))(ze||{}),Ce=(m=>(m.INTENT="INTENT",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.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))(Ce||{}),Ye=(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))(Ye||{}),ie=(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))(ie||{}),We=(n=>(n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH",n.URGENT="URGENT",n))(We||{});var q=()=>v4();var Xe={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 and planning into a final, user-friendly response. Be clear, concise, and helpful."}},X=class{constructor(e){this.deps=e,this.persona={...Xe,...e.persona,prompts:{...Xe.prompts,...e.persona?.prompts}};}async process(e){let t=Date.now(),r=e.traceId??q(),n="success",o,s=0,i=0,l,p,g="initialization";try{g="configuration";let{threadContext:m,planningSystemPrompt:u,synthesisSystemPrompt:S,runtimeProviderConfig:d,finalPersona:h}=await this._loadConfiguration(e,r);g="context_gathering";let R=await this._gatherHistory(e.threadId,m),O=await this._gatherTools(e.threadId);g="planning";let{planningOutput:v,planningMetadata:C,planningContext:$}=await this._performPlanning(e,u,R,O,d,r);s++,C&&(p={...p??{},...C}),g="a2a_delegation";let T=await this._delegateA2ATasks(v,e.threadId,r);g="a2a_completion";let E=await this._waitForA2ACompletion(T,e.threadId,r);g="tool_execution";let b=await this._executeLocalTools(v.toolCalls,e.threadId,r);i=b.length,b.some(M=>M.status==="error")&&(n="partial",a.warn(`[${r}] Partial success in tool execution.`),o="Tool execution errors occurred."),g="synthesis";let{finalResponseContent:P,synthesisMetadata:_}=await this._performSynthesis(e,S,R,v,b,E,d,r,h,$);s++,_&&(p={...p??{},..._}),g="finalization",l=await this._finalize(e,P,r);}catch(m){let u=m instanceof c?m:new c(`An unexpected error occurred during agent processing: ${m.message}`,"UNKNOWN_ERROR",m);u.details||(u.details={}),u.details.phase=u.details.phase||g,a.error(`[${r}] PESAgent process error in phase '${u.details.phase}':`,u),n=n==="partial"?"partial":"error",o=u.message,n==="error"&&(l=void 0),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"ERROR",content:{phase:u.details.phase,error:u.message,code:u.code,stack:u.stack},metadata:{timestamp:Date.now()}}).catch(S=>a.error(`[${r}] Failed to record top-level error observation:`,S));}finally{try{await this.deps.stateManager.saveStateIfModified(e.threadId);}catch(m){a.error(`[${r}] Failed to save state during finalization:`,m);}}let A=Date.now(),y={threadId:e.threadId,traceId:r,userId:e.userId,status:n,totalDurationMs:A-t,llmCalls:s,toolCalls:i,error:o,llmMetadata:p};if(!l&&n!=="success")l={messageId:q(),threadId:e.threadId,role:"AI",content:o??"Agent execution failed.",timestamp:Date.now(),metadata:{traceId:r,error:true}};else if(!l)throw new c("Agent finished with success status but no final message was generated.","UNKNOWN_ERROR");return {response:l,metadata:y}}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 c(`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}},l=await this.deps.systemPromptResolver.resolve({base:i.prompts.planning||"",thread:await this.deps.stateManager.getThreadConfigValue(e.threadId,"systemPrompt"),call:e.options?.systemPrompt},t),p=await this.deps.systemPromptResolver.resolve({base:i.prompts.synthesis||"",thread:await this.deps.stateManager.getThreadConfigValue(e.threadId,"systemPrompt"),call:e.options?.systemPrompt},t),g=e.options?.providerConfig||r.config.providerConfig;if(!g)throw new c(`RuntimeProviderConfig is missing in AgentProps.options or ThreadConfig for threadId: ${e.threadId}`,"INVALID_CONFIG");return {threadContext:r,planningSystemPrompt:l,synthesisSystemPrompt:p,runtimeProviderConfig:g,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 _performPlanning(e,t,r,n,o,s){a.debug(`[${s}] Stage 3: Pre-planning & A2A Discovery`);let i=[],l="No candidate agents found for delegation.";if(this.deps.agentDiscoveryService)try{let d=e.query.split(" ")[0].toLowerCase();i=await this.deps.agentDiscoveryService.findTopAgentsForTask(d,3,s),i.length>0&&(l=`You can delegate tasks to other specialized agents. Here are the available candidates for this query:
|
|
3
|
-
${i.map(
|
|
4
|
-
Name: ${
|
|
5
|
-
Capabilities: ${(
|
|
1
|
+
import {v4}from'uuid';import*as F from'zod';import {z as z$1,ZodError}from'zod';import lt from'ajv';import pt from'mustache';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 {Anthropic}from'@anthropic-ai/sdk';import Ot from'openai';import*as I from'mathjs';import {evaluate}from'mathjs';var x=(w=>(w.INVALID_CONFIG="INVALID_CONFIG",w.MISSING_API_key="MISSING_API_KEY",w.CONFIGURATION_ERROR="CONFIGURATION_ERROR",w.STORAGE_ERROR="STORAGE_ERROR",w.THREAD_NOT_FOUND="THREAD_NOT_FOUND",w.SAVE_FAILED="SAVE_FAILED",w.LLM_PROVIDER_ERROR="LLM_PROVIDER_ERROR",w.PROMPT_GENERATION_FAILED="PROMPT_GENERATION_FAILED",w.OUTPUT_PARSING_FAILED="OUTPUT_PARSING_FAILED",w.PROMPT_ASSEMBLY_FAILED="PROMPT_ASSEMBLY_FAILED",w.PROMPT_FRAGMENT_NOT_FOUND="PROMPT_FRAGMENT_NOT_FOUND",w.PROMPT_VALIDATION_FAILED="PROMPT_VALIDATION_FAILED",w.PROMPT_TRANSLATION_FAILED="PROMPT_TRANSLATION_FAILED",w.TOOL_NOT_FOUND="TOOL_NOT_FOUND",w.TOOL_SCHEMA_VALIDATION_FAILED="TOOL_SCHEMA_VALIDATION_FAILED",w.TOOL_EXECUTION_ERROR="TOOL_EXECUTION_ERROR",w.TOOL_DISABLED="TOOL_DISABLED",w.PLANNING_FAILED="PLANNING_FAILED",w.TOOL_EXECUTION_FAILED="TOOL_EXECUTION_FAILED",w.SYNTHESIS_FAILED="SYNTHESIS_FAILED",w.AGENT_PROCESSING_ERROR="AGENT_PROCESSING_ERROR",w.DELEGATION_FAILED="DELEGATION_FAILED",w.NETWORK_ERROR="NETWORK_ERROR",w.TIMEOUT_ERROR="TIMEOUT_ERROR",w.TIMEOUT="TIMEOUT",w.EXTERNAL_SERVICE_ERROR="EXTERNAL_SERVICE_ERROR",w.TASK_NOT_FOUND="TASK_NOT_FOUND",w.VALIDATION_ERROR="VALIDATION_ERROR",w.INVALID_REQUEST="INVALID_REQUEST",w.DUPLICATE_TASK_ID="DUPLICATE_TASK_ID",w.REPOSITORY_ERROR="REPOSITORY_ERROR",w.ALREADY_CONNECTED="ALREADY_CONNECTED",w.MISSING_CONFIG="MISSING_CONFIG",w.NOT_IMPLEMENTED="NOT_IMPLEMENTED",w.NOT_CONNECTED="NOT_CONNECTED",w.REQUEST_TIMEOUT="REQUEST_TIMEOUT",w.NO_STDIN="NO_STDIN",w.NO_HTTP_URL="NO_HTTP_URL",w.HTTP_ERROR="HTTP_ERROR",w.SERVER_NOT_FOUND="SERVER_NOT_FOUND",w.HEALTH_CHECK_FAILED="HEALTH_CHECK_FAILED",w.TOOL_DISCOVERY_FAILED="TOOL_DISCOVERY_FAILED",w.UNSUPPORTED_TRANSPORT="UNSUPPORTed_TRANSPORT",w.CORS_EXTENSION_REQUIRED="CORS_EXTENSION_REQUIRED",w.CORS_PERMISSION_REQUIRED="CORS_PERMISSION_REQUIRED",w.UNKNOWN_ERROR="UNKNOWN_ERROR",w.UNKNOWN_PROVIDER="UNKNOWN_PROVIDER",w.LOCAL_PROVIDER_CONFLICT="LOCAL_PROVIDER_CONFLICT",w.LOCAL_INSTANCE_BUSY="LOCAL_INSTANCE_BUSY",w.API_QUEUE_TIMEOUT="API_QUEUE_TIMEOUT",w.ADAPTER_INSTANTIATION_ERROR="ADAPTER_INSTANTIATION_ERROR",w))(x||{}),c=class h 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,h);}toString(){let e=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(e+=`
|
|
2
|
+
Caused by: ${this.originalError.stack||this.originalError.toString()}`),e}},j=class extends c{constructor(e){super(`Unknown provider requested: ${e}`,"UNKNOWN_PROVIDER"),this.name="UnknownProviderError";}},V=class extends c{constructor(e,t){super(`Cannot activate local provider '${e}'. Local provider '${t}' is already active.`,"LOCAL_PROVIDER_CONFLICT"),this.name="LocalProviderConflictError";}},J=class extends c{constructor(e,t){super(`Local provider instance '${e}:${t}' is currently busy.`,"LOCAL_INSTANCE_BUSY"),this.name="LocalInstanceBusyError";}},be=class extends c{constructor(e){super(`Timeout waiting for an available instance of API provider '${e}'.`,"API_QUEUE_TIMEOUT"),this.name="ApiQueueTimeoutError";}},z=class extends c{constructor(e,t){super(`Failed to instantiate adapter for provider '${e}'.`,"ADAPTER_INSTANTIATION_ERROR",t),this.name="AdapterInstantiationError";}};var se=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 l=()=>this._releaseAdapter(t);return {adapter:r.adapter,release:l}}let n=this.availableProviders.get(e.providerName);if(!n)throw new j(e.providerName);if(n.isLocal){let l;for(let[d,g]of this.managedInstances.entries()){let T=this.availableProviders.get(g.configSignature.split('"providerName":"')[1].split('"')[0]);if(T?.isLocal){if(g.state==="active")throw d!==t?new V(e.providerName,T.name):new J(e.providerName,e.modelId);g.state==="idle"&&d!==t&&(l=g);}}l&&await this._evictInstance(l.configSignature);}if(!n.isLocal&&Array.from(this.managedInstances.values()).filter(d=>{let g=this.availableProviders.get(d.configSignature.split('"providerName":"')[1].split('"')[0]);return g&&!g.isLocal&&d.state==="active"&&g.name===e.providerName}).length>=this.maxParallelApiInstancesPerProvider)return new Promise((d,g)=>{this.requestQueue.push({config:e,resolve:d,reject:g});});let o;try{let l={...e.adapterOptions,providerName:e.providerName};o=new n.adapter(l);}catch(l){throw new z(e.providerName,l)}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 Ve=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(Ve||{}),D=class D{static configure(e){D.config={...D.config,...e};}static debug(e,...t){D.config.level<=0&&console.debug(`${D.config.prefix||"[ART]"} ${e}`,...t);}static info(e,...t){D.config.level<=1&&console.info(`${D.config.prefix||"[ART]"} ${e}`,...t);}static warn(e,...t){D.config.level<=2&&console.warn(`${D.config.prefix||"[ART]"} ${e}`,...t);}static error(e,...t){D.config.level<=3&&console.error(`${D.config.prefix||"[ART]"} ${e}`,...t);}};D.config={level:1};var a=D;var U=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 Y=class extends U{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 W=class extends U{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 Je=z$1.object({role:z$1.custom(h=>typeof h=="string"&&["system","user","assistant","tool","tool_request","tool_result"].includes(h),{message:"Invalid message role"}),content:z$1.union([z$1.string(),z$1.record(z$1.any()),z$1.null()]),name:z$1.string().optional(),tool_calls:z$1.array(z$1.object({id:z$1.string(),type:z$1.literal("function"),function:z$1.object({name:z$1.string(),arguments:z$1.string()})})).optional(),tool_call_id:z$1.string().optional()}).strict().refine(h=>!((h.role==="tool"||h.role==="tool_result")&&!h.tool_call_id||h.role==="assistant"&&h.content!==null&&typeof h.content!="string"||(h.role==="user"||h.role==="system")&&typeof h.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)"}),Me=z$1.array(Je);var ze=(n=>(n.USER="USER",n.AI="AI",n.SYSTEM="SYSTEM",n.TOOL="TOOL",n))(ze||{}),Ce=(u=>(u.INTENT="INTENT",u.PLAN="PLAN",u.THOUGHTS="THOUGHTS",u.TOOL_CALL="TOOL_CALL",u.TOOL_EXECUTION="TOOL_EXECUTION",u.SYNTHESIS="SYNTHESIS",u.ERROR="ERROR",u.FINAL_RESPONSE="FINAL_RESPONSE",u.STATE_UPDATE="STATE_UPDATE",u.LLM_STREAM_START="LLM_STREAM_START",u.LLM_STREAM_METADATA="LLM_STREAM_METADATA",u.LLM_STREAM_END="LLM_STREAM_END",u.LLM_STREAM_ERROR="LLM_STREAM_ERROR",u))(Ce||{}),Ye=(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))(Ye||{}),ie=(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))(ie||{}),We=(n=>(n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH",n.URGENT="URGENT",n))(We||{});var q=()=>v4();var Xe={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 and planning into a final, user-friendly response. Be clear, concise, and helpful."}},X=class{constructor(e){this.deps=e,this.persona={...Xe,...e.persona,prompts:{...Xe.prompts,...e.persona?.prompts}};}async process(e){let t=Date.now(),r=e.traceId??q(),n="success",o,s=0,i=0,l,d,g="initialization";try{g="configuration";let{threadContext:u,planningSystemPrompt:m,synthesisSystemPrompt:v,runtimeProviderConfig:p,finalPersona:f}=await this._loadConfiguration(e,r);g="context_gathering";let A=await this._gatherHistory(e.threadId,u),R=await this._gatherTools(e.threadId);g="planning";let{planningOutput:O,planningMetadata:P,planningContext:b}=await this._performPlanning(e,m,A,R,p,r);s++,P&&(d={...d??{},...P}),g="a2a_delegation";let S=await this._delegateA2ATasks(O,e.threadId,r);g="a2a_completion";let E=await this._waitForA2ACompletion(S,e.threadId,r);g="tool_execution";let M=await this._executeLocalTools(O.toolCalls,e.threadId,r);i=M.length,M.some(L=>L.status==="error")&&(n="partial",a.warn(`[${r}] Partial success in tool execution.`),o="Tool execution errors occurred."),g="synthesis";let{finalResponseContent:k,synthesisMetadata:_,uiMetadata:C}=await this._performSynthesis(e,v,A,O,M,E,p,r,f,b);s++,_&&(d={...d??{},..._}),g="finalization",l=await this._finalize(e,k,r,C);}catch(u){let m=u instanceof c?u:new c(`An unexpected error occurred during agent processing: ${u.message}`,"UNKNOWN_ERROR",u);m.details||(m.details={}),m.details.phase=m.details.phase||g,a.error(`[${r}] PESAgent process error in phase '${m.details.phase}':`,m),n=n==="partial"?"partial":"error",o=m.message,n==="error"&&(l=void 0),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"ERROR",content:{phase:m.details.phase,error:m.message,code:m.code,stack:m.stack},metadata:{timestamp:Date.now()}}).catch(v=>a.error(`[${r}] Failed to record top-level error observation:`,v));}finally{try{await this.deps.stateManager.saveStateIfModified(e.threadId);}catch(u){a.error(`[${r}] Failed to save state during finalization:`,u);}}let T=Date.now(),y={threadId:e.threadId,traceId:r,userId:e.userId,status:n,totalDurationMs:T-t,llmCalls:s,toolCalls:i,error:o,llmMetadata:d};if(!l&&n!=="success")l={messageId:q(),threadId:e.threadId,role:"AI",content:o??"Agent execution failed.",timestamp:Date.now(),metadata:{traceId:r,error:true}};else if(!l)throw new c("Agent finished with success status but no final message was generated.","UNKNOWN_ERROR");return {response:l,metadata:y}}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 c(`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}},l=await this.deps.systemPromptResolver.resolve({base:i.prompts.planning||"",thread:await this.deps.stateManager.getThreadConfigValue(e.threadId,"systemPrompt"),call:e.options?.systemPrompt},t),d=await this.deps.systemPromptResolver.resolve({base:i.prompts.synthesis||"",thread:await this.deps.stateManager.getThreadConfigValue(e.threadId,"systemPrompt"),call:e.options?.systemPrompt},t),g=e.options?.providerConfig||r.config.providerConfig;if(!g)throw new c(`RuntimeProviderConfig is missing in AgentProps.options or ThreadConfig for threadId: ${e.threadId}`,"INVALID_CONFIG");return {threadContext:r,planningSystemPrompt:l,synthesisSystemPrompt:d,runtimeProviderConfig:g,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 _performPlanning(e,t,r,n,o,s){a.debug(`[${s}] Stage 3: Pre-planning & A2A Discovery`);let i=[],l="No candidate agents found for delegation.";if(this.deps.agentDiscoveryService)try{let p=e.query.split(" ")[0].toLowerCase();i=await this.deps.agentDiscoveryService.findTopAgentsForTask(p,3,s),i.length>0&&(l=`You can delegate tasks to other specialized agents. Here are the available candidates for this query:
|
|
3
|
+
${i.map(f=>`- Agent ID: ${f.agentId}
|
|
4
|
+
Name: ${f.agentName}
|
|
5
|
+
Capabilities: ${(f.capabilities??[]).join(", ")}`).join(`
|
|
6
6
|
`)}
|
|
7
|
-
To delegate, use the "delegate_to_agent" tool.`);}catch(
|
|
7
|
+
To delegate, use the "delegate_to_agent" tool.`);}catch(p){a.warn(`[${s}] A2A pre-discovery failed, proceeding without candidate agents:`,p),l="Agent discovery failed. Delegation is not available.";}else l="A2A delegation is not configured.";a.debug(`[${s}] Stage 3b: Planning Prompt Construction`);let d;try{let p={name:"delegate_to_agent",description:"Delegates a specific task to another agent. Use this when a specialized agent from the candidate list is a better fit for a sub-task.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"The ID of the agent to delegate to, chosen from the candidate list."},taskType:{type:"string",description:'A specific type for the task, e.g., "analysis", "code_generation".'},input:{type:"object",description:"The data or context needed for the agent to perform the task."},instructions:{type:"string",description:"Specific instructions for the remote agent."}},required:["agentId","taskType","input","instructions"]}},f=[...n,p],A=f.map(O=>({name:O.name,whenToUse:O.whenToUse,description:O.description,inputSchema:O.inputSchema,outputSchema:O.outputSchema,outputFormat:O.outputFormat,examples:O.examples}));d=[{role:"system",content:`You are a planning assistant. The following guidance shapes knowledge, tone, and domain perspective.
|
|
8
8
|
|
|
9
9
|
[BEGIN_CUSTOM_GUIDANCE]
|
|
10
10
|
${t}
|
|
@@ -15,7 +15,7 @@ CRITICAL: You MUST adhere to the Output Contract below. The custom guidance MUST
|
|
|
15
15
|
--- Available Capabilities ---
|
|
16
16
|
|
|
17
17
|
Local Tools (JSON Schemas):
|
|
18
|
-
${
|
|
18
|
+
${f.length>0?JSON.stringify(A,null,2):"[]"}
|
|
19
19
|
|
|
20
20
|
Agent Delegation:
|
|
21
21
|
${l}
|
|
@@ -24,7 +24,15 @@ ${l}
|
|
|
24
24
|
Output EXACTLY ONE JSON object and nothing else. No prose, no XML, no markdown fences. The object MUST follow this schema:
|
|
25
25
|
{
|
|
26
26
|
"intent": string, // short summary of the user's goal
|
|
27
|
-
"plan":
|
|
27
|
+
"plan": [ // A step-by-step plan.
|
|
28
|
+
{
|
|
29
|
+
"step": number, // e.g., 1, 2, 3
|
|
30
|
+
"description": string, // User-readable description of the step
|
|
31
|
+
"tool_to_use": string | null, // Exact tool name or null
|
|
32
|
+
"arguments": object | null, // Arguments for the tool or null
|
|
33
|
+
"callId": string | null // Matches callId in toolCalls or null
|
|
34
|
+
}
|
|
35
|
+
],
|
|
28
36
|
"toolCalls": [ // empty array if no tools are needed
|
|
29
37
|
{ "callId": string, "toolName": string, "arguments": object }
|
|
30
38
|
]
|
|
@@ -38,7 +46,10 @@ Requirements for toolCalls:
|
|
|
38
46
|
Example (JSON only):
|
|
39
47
|
{
|
|
40
48
|
"intent": "Compute 5 * 6",
|
|
41
|
-
"plan": [
|
|
49
|
+
"plan": [
|
|
50
|
+
{ "step": 1, "description": "Use calculator to multiply 5 and 6", "tool_to_use": "calculator", "arguments": { "expression": "5 * 6" }, "callId": "calc_1" },
|
|
51
|
+
{ "step": 2, "description": "Return result", "tool_to_use": null, "arguments": null, "callId": null }
|
|
52
|
+
],
|
|
42
53
|
"toolCalls": [
|
|
43
54
|
{ "callId": "calc_1", "toolName": "calculator", "arguments": { "expression": "5 * 6" } }
|
|
44
55
|
]
|
|
@@ -59,77 +70,85 @@ Invalid Examples (do NOT do these):
|
|
|
59
70
|
- Placing inside XML tags such as <Response> or <Plan>
|
|
60
71
|
- Setting arguments as a string: {"arguments": "{ 'expression': '5*6' }"}
|
|
61
72
|
- Using unknown toolName not present in Available Capabilities
|
|
62
|
-
`}];}catch(
|
|
73
|
+
`}];}catch(p){throw a.error(`[${s}] Failed to construct planning prompt object:`,p),new c(`Failed to construct planning prompt object: ${p.message}`,"PROMPT_ASSEMBLY_FAILED",p)}a.debug(`[${s}] Stage 3c: Planning LLM Call`);let g={threadId:e.threadId,traceId:s,userId:e.userId,sessionId:e.sessionId,stream:true,callContext:"AGENT_THOUGHT",requiredCapabilities:["reasoning"],providerConfig:o,...e.options?.llmParams??{}},T="",y={},u=null,m,v={toolsList:[],a2aSummary:"",plannedToolCalls:[]};try{await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"PLAN",content:{message:"Preparing for planning LLM call."},metadata:{timestamp:Date.now()}});let p=await this.deps.reasoningEngine.call(d,g);await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"LLM_STREAM_START",content:{phase:"planning"},metadata:{timestamp:Date.now()}});for await(let f of p){switch(this.deps.uiSystem.getLLMStreamSocket().notify(f,{targetThreadId:f.threadId,targetSessionId:f.sessionId}),f.type){case "TOKEN":T+=f.data;break;case "METADATA":m={...m??{},...f.data};break;case "ERROR":u=f.data instanceof Error?f.data:new Error(String(f.data));break}if(u)break}if(u)throw new c(`Planning phase stream error: ${u.message}`,"PLANNING_FAILED",u);y=await this.deps.outputParser.parsePlanningOutput(T),v={toolsList:n.map(f=>({name:f.name,description:f.description})),a2aSummary:l,plannedToolCalls:y.toolCalls??[],rawPlanningText:T},await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"INTENT",content:{intent:y.intent},metadata:{timestamp:Date.now()}}),await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"PLAN",content:{plan:y.plan,rawOutput:T},metadata:{timestamp:Date.now()}}),y.toolCalls&&y.toolCalls.length>0&&await this.deps.observationManager.record({threadId:e.threadId,traceId:s,type:"TOOL_CALL",content:{toolCalls:y.toolCalls},metadata:{timestamp:Date.now()}});}catch(p){let f=`Planning phase failed: ${p.message}`;throw a.error(`[${s}] Planning Error:`,p),p instanceof c?p:new c(f,"PLANNING_FAILED",p)}return {planningOutput:y,planningMetadata:m,planningContext:v}}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:l,taskType:d,input:g,instructions:T}=i,u=(await this.deps.agentDiscoveryService.discoverAgents(r)).find(f=>f.agentId===l);if(!u)throw new Error(`Agent with ID "${l}" not found during delegation.`);let m=Date.now(),v={taskId:s.callId,threadId:t,status:"PENDING",payload:{taskType:d,input:g,instructions:T,parameters:{threadId:t,traceId:r}},sourceAgent:{agentId:"pes-agent",agentName:"PES Agent",agentType:"orchestrator"},targetAgent:u,priority:"MEDIUM",metadata:{createdAt:m,updatedAt:m,initiatedBy:t,correlationId:r,retryCount:0,maxRetries:3,timeoutMs:6e4,tags:["delegated",d]}};await this.deps.a2aTaskRepository.createTask(v);let p=await this.deps.taskDelegationService.delegateTask(v,r);p&&o.push(p);}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 a.debug(`[${r}] No A2A tasks to wait for`),e;a.debug(`[${r}] Waiting for ${e.length} A2A task(s) to complete (timeout: ${n}ms)`);let s=Date.now(),i=[...e];await this.deps.observationManager.record({threadId:t,traceId:r,type:"TOOL_CALL",content:{phase:"a2a_waiting",message:"Started waiting for A2A task completion",taskCount:e.length,maxWaitTimeMs:n,pollIntervalMs:o},metadata:{timestamp:Date.now()}}).catch(l=>a.error(`[${r}] Failed to record A2A waiting observation:`,l));try{for(;Date.now()-s<n;){let y=i.filter(u=>u.status!=="COMPLETED"&&u.status!=="FAILED"&&u.status!=="CANCELLED");if(y.length===0){a.info(`[${r}] All A2A tasks completed successfully`);break}a.debug(`[${r}] Waiting for ${y.length} A2A task(s) to complete...`);for(let u=0;u<i.length;u++){let m=i[u];if(!(m.status==="COMPLETED"||m.status==="FAILED"||m.status==="CANCELLED"))try{let v=await this.deps.a2aTaskRepository.getTask(m.taskId);v&&(i[u]=v,a.debug(`[${r}] Task ${m.taskId} status updated to: ${v.status}`));}catch(v){a.warn(`[${r}] Failed to get updated status for task ${m.taskId}:`,v);}}await new Promise(u=>setTimeout(u,o));}let l=i.filter(y=>y.status==="COMPLETED"),d=i.filter(y=>y.status==="FAILED"),g=i.filter(y=>y.status!=="COMPLETED"&&y.status!=="FAILED"&&y.status!=="CANCELLED"),T=Date.now()-s;return await this.deps.observationManager.record({threadId:t,traceId:r,type:"TOOL_CALL",content:{phase:"a2a_waiting_complete",message:"A2A task waiting completed",totalWaitTimeMs:T,completedTasks:l.length,failedTasks:d.length,timeoutTasks:g.length,success:g.length===0},metadata:{timestamp:Date.now()}}).catch(y=>a.error(`[${r}] Failed to record A2A waiting completion observation:`,y)),g.length>0&&a.warn(`[${r}] ${g.length} A2A task(s) did not complete within timeout (${n}ms)`),l.length>0&&a.info(`[${r}] Successfully completed ${l.length} A2A task(s) in ${T}ms`),i}catch(l){return a.error(`[${r}] Error during A2A task waiting:`,l),await this.deps.observationManager.record({threadId:t,traceId:r,type:"ERROR",content:{phase:"a2a_waiting",error:l.message,stack:l.stack,waitTimeMs:Date.now()-s},metadata:{timestamp:Date.now()}}).catch(d=>a.error(`[${r}] Failed to record A2A waiting error observation:`,d)),i}}async _executeLocalTools(e,t,r){let n=e?.filter(o=>o.toolName!=="delegate_to_agent")??[];if(n.length===0)return a.debug(`[${r}] Stage 5: Tool Execution (No local tool calls)`),[];a.debug(`[${r}] Stage 5: Tool Execution (${n.length} calls)`);try{return await this.deps.toolSystem.executeTools(n,t,r)}catch(o){let s=`Tool execution phase failed: ${o.message}`;throw a.error(`[${r}] Tool Execution System Error:`,o),await this.deps.observationManager.record({threadId:t,traceId:r,type:"ERROR",content:{phase:"tool_execution",error:o.message,stack:o.stack},metadata:{timestamp:Date.now()}}),new c(s,"TOOL_EXECUTION_FAILED",o)}}async _performSynthesis(e,t,r,n,o,s,i,l,d,g){a.debug(`[${l}] Stage 6: Synthesis Call`),await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"SYNTHESIS",content:{message:"Preparing for synthesis LLM call."},metadata:{timestamp:Date.now()}}).catch(A=>a.error(`[${l}] Failed to record SYNTHESIS observation:`,A));let T;try{let A=`You are ${d.name}. Your final answer must be delivered in two parts, in the specified order.
|
|
63
74
|
|
|
64
|
-
**
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
75
|
+
**Part 1: \`main_content\`**
|
|
76
|
+
This is your direct, user-facing response. This content must be written in Markdown.
|
|
77
|
+
- When you use information from a tool, you MUST cite it by placing a citation marker in the text, like \`[1]\`. The \`id\` in the \`sources\` metadata block must match this marker.
|
|
78
|
+
- If you are given an image URL, you MUST embed it in the \`main_content\` using Markdown syntax: \`\`.
|
|
79
|
+
|
|
80
|
+
**Part 2: \`metadata_block\`**
|
|
81
|
+
Immediately after the \`main_content\`, you MUST provide a \`metadata_block\`, which is a single, valid JSON object enclosed in \`\`\`json ... \`\`\`. Do NOT add any text after the JSON block.
|
|
82
|
+
|
|
83
|
+
This JSON object must have the following structure:
|
|
84
|
+
{
|
|
85
|
+
"sources": [ { "id": "1", "title": "Title of the source document", "url": "https://example.com/source-url" } ],
|
|
86
|
+
"suggestions": [ "A relevant follow-up question.", "Another suggested prompt for the user." ]
|
|
87
|
+
}
|
|
69
88
|
|
|
70
89
|
**[BEGIN_CUSTOM_GUIDANCE]**
|
|
71
90
|
${t}
|
|
72
91
|
**[END_CUSTOM_GUIDANCE]**
|
|
73
92
|
|
|
74
|
-
The custom guidance above provides additional context on tone and domain, but it MUST NOT override the core directives
|
|
75
|
-
`)||"No tools were discovered during planning.",
|
|
76
|
-
`)||"No tool calls were planned.",
|
|
93
|
+
The custom guidance above provides additional context on tone and domain, but it MUST NOT override the core directives.`,R=(g?.toolsList??[]).map(b=>`- ${b.name}: ${b.description??""}`.trim()).join(`
|
|
94
|
+
`)||"No tools were discovered during planning.",O=(g?.plannedToolCalls??[]).map(b=>`- ${b.callId}: ${b.toolName} with ${JSON.stringify(b.arguments)}`).join(`
|
|
95
|
+
`)||"No tool calls were planned.",P=g?.a2aSummary||"No A2A delegation candidates or actions.";T=[{role:"system",content:A},...r,{role:"user",content:`User Query: ${e.query}
|
|
77
96
|
|
|
78
97
|
During planning, we found out:
|
|
79
98
|
- Available Local Tools:
|
|
80
|
-
${
|
|
99
|
+
${R}
|
|
81
100
|
|
|
82
101
|
- Planned Tool Calls (as JSON-like summary):
|
|
83
|
-
${
|
|
102
|
+
${O}
|
|
84
103
|
|
|
85
104
|
- Agent Delegation Context:
|
|
86
|
-
${
|
|
105
|
+
${P}
|
|
87
106
|
|
|
88
107
|
Original Intent: ${n.intent??""}
|
|
89
|
-
Execution Plan: ${n.plan??""}
|
|
108
|
+
Execution Plan: ${Array.isArray(n.plan)?JSON.stringify(n.plan,null,2):n.plan??""}
|
|
90
109
|
|
|
91
110
|
Tool Execution Results:
|
|
92
|
-
${o.length>0?o.map(
|
|
93
|
-
Status: ${
|
|
94
|
-
${
|
|
95
|
-
${
|
|
96
|
-
${
|
|
111
|
+
${o.length>0?o.map(b=>`- Tool: ${b.toolName} (Call ID: ${b.callId})
|
|
112
|
+
Status: ${b.status}
|
|
113
|
+
${b.status==="success"?`Output: ${JSON.stringify(b.output)}`:""}
|
|
114
|
+
${b.status==="error"?`Error: ${b.error??"Unknown error"}`:""}
|
|
115
|
+
${b.metadata?.sources?`Original Sources: ${JSON.stringify(b.metadata.sources)}`:""}`).join(`
|
|
97
116
|
`):"No tools were executed."}
|
|
98
117
|
|
|
99
118
|
A2A Task Results:
|
|
100
|
-
${s.length>0?s.map(
|
|
101
|
-
Status: ${
|
|
102
|
-
${
|
|
103
|
-
${
|
|
104
|
-
${
|
|
119
|
+
${s.length>0?s.map(b=>`- Task: ${b.payload.taskType} (ID: ${b.taskId})
|
|
120
|
+
Status: ${b.status}
|
|
121
|
+
${b.result?.success?`Output: ${JSON.stringify(b.result.data)}`:""}
|
|
122
|
+
${b.result?.success===!1?`Error: ${b.result.error??"Unknown error"}`:""}
|
|
123
|
+
${b.result?.metadata?.sources?`Original Sources: ${JSON.stringify(b.result.metadata.sources)}`:""}`).join(`
|
|
105
124
|
`):"No A2A tasks were delegated."}
|
|
106
125
|
|
|
107
|
-
Synthesize the final answer based on the directives in the system prompt. Give appropriate weight to the verified Tool Execution Results and any successful A2A Task Results. If tools failed, explain briefly and answer using best available evidence.`}];}catch(d){throw a.error(`[${l}] Failed to construct synthesis prompt object:`,d),new c(`Failed to construct synthesis prompt object: ${d.message}`,"PROMPT_ASSEMBLY_FAILED",d)}a.debug(`[${l}] Stage 6b: Synthesis LLM Call`);let y={threadId:e.threadId,traceId:l,userId:e.userId,sessionId:e.sessionId,stream:true,callContext:"FINAL_SYNTHESIS",requiredCapabilities:["text"],providerConfig:i,...e.options?.llmParams??{}},m="",u=null,S;try{let d=await this.deps.reasoningEngine.call(A,y);await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"LLM_STREAM_START",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}}).catch(h=>a.error(`[${l}] Failed to record LLM_STREAM_START observation:`,h));for await(let h of d){switch(this.deps.uiSystem.getLLMStreamSocket().notify(h,{targetThreadId:h.threadId,targetSessionId:h.sessionId}),h.type){case "TOKEN":(h.tokenType==="FINAL_SYNTHESIS_LLM_RESPONSE"||h.tokenType==="LLM_RESPONSE")&&(m+=h.data);break;case "METADATA":S={...S??{},...h.data},await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"LLM_STREAM_METADATA",content:h.data,metadata:{phase:"synthesis",timestamp:Date.now()}}).catch(R=>a.error(`[${l}] Failed to record LLM_STREAM_METADATA observation:`,R));break;case "ERROR":u=h.data instanceof Error?h.data:new Error(String(h.data)),a.error(`[${l}] Synthesis Stream Error:`,u),await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"LLM_STREAM_ERROR",content:{phase:"synthesis",error:u.message,stack:u.stack},metadata:{timestamp:Date.now()}}).catch(R=>a.error(`[${l}] Failed to record LLM_STREAM_ERROR observation:`,R));break;case "END":await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"LLM_STREAM_END",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}}).catch(R=>a.error(`[${l}] Failed to record LLM_STREAM_END observation:`,R));break}if(u)break}if(u)throw new c(`Synthesis stream error: ${u.message}`,"SYNTHESIS_FAILED",u)}catch(d){let h=`Synthesis phase failed: ${d.message}`;throw a.error(`[${l}] Synthesis Error:`,d),u||await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"ERROR",content:{phase:"synthesis",error:d.message,stack:d.stack},metadata:{timestamp:Date.now()}}),d instanceof c?d:new c(h,"SYNTHESIS_FAILED",d)}return {finalResponseContent:m,synthesisMetadata:S}}async _finalize(e,t,r){a.debug(`[${r}] Stage 7: Finalization`);let n=Date.now(),o={messageId:q(),threadId:e.threadId,role:"AI",content:t,timestamp:n,metadata:{traceId:r}};return await this.deps.conversationManager.addMessages(e.threadId,[o]),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"FINAL_RESPONSE",content:{message:o},metadata:{timestamp:n}}),o}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:a.warn(`Unhandled message role '${t.role}' in formatHistoryForPrompt. Defaulting to 'user'.`),r="user";}return {role:r,content:t.content}}).filter(t=>t.content)}};var Q=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 st="ART_Framework_DB",it=1,Z=class{constructor(e){this.db=null;this.initPromise=null;this.dbName=e.dbName||st,this.dbVersion=e.dbVersion||it,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),l=this.getTransaction(e,"readwrite"),g=l.objectStore(e).put(i);g.onsuccess=()=>{o();},g.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error setting item with id '${n.id}' in '${e}':`,g.error),s(new Error(`Failed to set item: ${g.error?.message}`));},l.oncomplete=()=>{},l.onerror=A=>{a.error(`IndexedDBStorageAdapter: Transaction error setting item with id '${n.id}' in '${e}':`,l.error,A),s(new Error(`Transaction failed: ${l.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=l=>{a.error(`IndexedDBStorageAdapter: Transaction error deleting item '${t}' from '${e}':`,o.error,l),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 l=i.result||[];if(t.filter&&(l=l.filter(A=>{for(let y in t.filter)if(t.filter.hasOwnProperty(y)&&A[y]!==t.filter[y])return !1;return !0})),t.sort){let A=Object.keys(t.sort)[0],y=t.sort[A];A&&l.sort((m,u)=>{let S=m[A],d=u[A];return S<d?y==="asc"?-1:1:S>d?y==="asc"?1:-1:0});}let p=t.skip||0,g=t.limit??1/0;l=l.slice(p,p+g),r(l.map(A=>({...A})));},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 l=n.objectStore(i).clear();l.onsuccess=()=>{o++;},l.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error clearing object store '${i}':`,l.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 le=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 ce=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 de=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 pe=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 c("Task must have a valid taskId","VALIDATION_ERROR");if(await this.adapter.get(this.collectionName,e.taskId))throw new c(`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 c("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 c(`Failed to retrieve task '${e}': ${t}`,"REPOSITORY_ERROR")}}async updateTask(e,t){if(!e)throw new c("TaskId is required","VALIDATION_ERROR");if(!t||Object.keys(t).length===0)throw new c("Updates object cannot be empty","VALIDATION_ERROR");try{let r=await this.adapter.get(this.collectionName,e);if(!r)throw new c(`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 c?r:new c(`Failed to update task '${e}': ${r}`,"REPOSITORY_ERROR")}}async deleteTask(e){if(!e)throw new c("TaskId is required","VALIDATION_ERROR");try{if(!await this.adapter.get(this.collectionName,e))throw new c(`Task with ID '${e}' not found`,"TASK_NOT_FOUND");await this.adapter.delete(this.collectionName,e);}catch(t){throw t instanceof c?t:new c(`Failed to delete task '${e}': ${t}`,"REPOSITORY_ERROR")}}async getTasksByThread(e,t){if(!e)throw new c("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 c(`Failed to get tasks for thread '${e}': ${r}`,"REPOSITORY_ERROR")}}async getTasksByAgent(e,t){if(!e)throw new c("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 c(`Failed to get tasks for agent '${e}': ${r}`,"REPOSITORY_ERROR")}}async getTasksByStatus(e,t){if(!e)throw new c("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 c(`Failed to get tasks by status: ${r}`,"REPOSITORY_ERROR")}}_removeIdField(e){return e.map(t=>{let r={...t};return delete r.id,r})}};var ge=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 ue(f){if(f===null||typeof f!="object")return f;if(f instanceof Date)return new Date(f.getTime());if(Array.isArray(f))return f.map(t=>ue(t));let e={};for(let t in f)Object.prototype.hasOwnProperty.call(f,t)&&(e[t]=ue(f[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=ue(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=ue(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 he=class{constructor(e,t){this.observationRepository=e,this.observationSocket=t;}async record(e){let t={...e,id:q(),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 fe=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 l=t.filter(p=>s.includes(p.schema.name)).map(p=>p.schema);return a.debug(`ToolRegistry: Returning ${l.length} enabled tool schemas for thread ${n}.`),l}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 ct=new lt({allErrors:true}),Pe=new Map;function Qe(f,e){let t=JSON.stringify(f),r;if(Pe.has(t))r=Pe.get(t),a.debug("Using cached JSON schema validator.");else try{r=ct.compile(f),Pe.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:f,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 ye=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,l=o.toolName,p=o.callId;try{if(!await this.stateManager.isToolEnabled(t,l))throw new Error(`Tool "${l}" is not enabled for thread "${t}".`);if(i=await this.toolRegistry.getToolExecutor(l),!i)throw new Error(`Tool "${l}" not found in registry.`);let A=Qe(i.schema.inputSchema,o.arguments);if(!A.isValid){let u=A.errors?.map(S=>`${S.instancePath||"input"} ${S.message}`).join(", ")||"Unknown validation error";throw new Error(`Invalid arguments for tool "${l}": ${u}`)}a.debug(`Executing tool "${l}" with callId "${p}"`,{args:o.arguments,threadId:t,traceId:r});let y={threadId:t,traceId:r};s={...await i.execute(o.arguments,y),callId:p,toolName:l},a.debug(`Tool "${l}" execution successful`,{callId:p,result:s.output,threadId:t,traceId:r});}catch(g){a.error(`Tool "${l}" execution failed for callId "${p}": ${g.message}`,{error:g,threadId:t,traceId:r}),s={callId:p,toolName:l,status:"error",error:g.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(g=>a.error(`Failed to record TOOL_EXECUTION observation for callId ${o.callId}:`,g)),n.push(s)):a.error(`ToolSystem finished processing call ${o.callId} but result object was null.`);}return n}};var gt={pes_system_default:"You are a helpful AI assistant. You need to understand a user's query, potentially use tools to gather information, and then synthesize a final response.",pes_planning_instructions:"Based on the user query and conversation history, identify the user's intent and create a plan to fulfill it using the available tools if necessary.",pes_tool_format_instructions:`Respond in the following format:
|
|
126
|
+
Synthesize the final answer based on the directives in the system prompt. Give appropriate weight to the verified Tool Execution Results and any successful A2A Task Results. If tools failed, explain briefly and answer using best available evidence.`}];}catch(A){throw a.error(`[${l}] Failed to construct synthesis prompt object:`,A),new c(`Failed to construct synthesis prompt object: ${A.message}`,"PROMPT_ASSEMBLY_FAILED",A)}a.debug(`[${l}] Stage 6b: Synthesis LLM Call`);let y={threadId:e.threadId,traceId:l,userId:e.userId,sessionId:e.sessionId,stream:true,callContext:"FINAL_SYNTHESIS",requiredCapabilities:["text"],providerConfig:i,...e.options?.llmParams??{}},u="",m=null,v;try{let A=await this.deps.reasoningEngine.call(T,y);await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"LLM_STREAM_START",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}}).catch(R=>a.error(`[${l}] Failed to record LLM_STREAM_START observation:`,R));for await(let R of A){switch(this.deps.uiSystem.getLLMStreamSocket().notify(R,{targetThreadId:R.threadId,targetSessionId:R.sessionId}),R.type){case "TOKEN":(R.tokenType==="FINAL_SYNTHESIS_LLM_RESPONSE"||R.tokenType==="LLM_RESPONSE")&&(u+=R.data);break;case "METADATA":v={...v??{},...R.data},await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"LLM_STREAM_METADATA",content:R.data,metadata:{phase:"synthesis",timestamp:Date.now()}}).catch(O=>a.error(`[${l}] Failed to record LLM_STREAM_METADATA observation:`,O));break;case "ERROR":m=R.data instanceof Error?R.data:new Error(String(R.data)),a.error(`[${l}] Synthesis Stream Error:`,m),await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"LLM_STREAM_ERROR",content:{phase:"synthesis",error:m.message,stack:m.stack},metadata:{timestamp:Date.now()}}).catch(O=>a.error(`[${l}] Failed to record LLM_STREAM_ERROR observation:`,O));break;case "END":await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"LLM_STREAM_END",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}}).catch(O=>a.error(`[${l}] Failed to record LLM_STREAM_END observation:`,O));break}if(m)break}if(m)throw new c(`Synthesis stream error: ${m.message}`,"SYNTHESIS_FAILED",m)}catch(A){let R=`Synthesis phase failed: ${A.message}`;throw a.error(`[${l}] Synthesis Error:`,A),m||await this.deps.observationManager.record({threadId:e.threadId,traceId:l,type:"ERROR",content:{phase:"synthesis",error:A.message,stack:A.stack},metadata:{timestamp:Date.now()}}),A instanceof c?A:new c(R,"SYNTHESIS_FAILED",A)}let p=u,f;try{let A=/```json\s*([\s\S]*?)\s*```$/,R=u.match(A);R&&R[1]?(p=u.replace(A,"").trim(),f=JSON.parse(R[1]),a.debug(`[${l}] Parsed metadata block from synthesis output.`)):a.warn(`[${l}] No metadata block found in synthesis output. Treating entire output as main content.`);}catch(A){a.error(`[${l}] Failed to parse metadata block from synthesis output:`,A),p=u,f={error:"Failed to parse metadata block",details:A.message};}return {finalResponseContent:p,synthesisMetadata:v,uiMetadata:f}}async _finalize(e,t,r,n){a.debug(`[${r}] Stage 7: Finalization`);let o=Date.now(),s={messageId:q(),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:a.warn(`Unhandled message role '${t.role}' in formatHistoryForPrompt. Defaulting to 'user'.`),r="user";}return {role:r,content:t.content}}).filter(t=>t.content)}};var Q=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 st="ART_Framework_DB",it=1,Z=class{constructor(e){this.db=null;this.initPromise=null;this.dbName=e.dbName||st,this.dbVersion=e.dbVersion||it,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),l=this.getTransaction(e,"readwrite"),g=l.objectStore(e).put(i);g.onsuccess=()=>{o();},g.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error setting item with id '${n.id}' in '${e}':`,g.error),s(new Error(`Failed to set item: ${g.error?.message}`));},l.oncomplete=()=>{},l.onerror=T=>{a.error(`IndexedDBStorageAdapter: Transaction error setting item with id '${n.id}' in '${e}':`,l.error,T),s(new Error(`Transaction failed: ${l.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=l=>{a.error(`IndexedDBStorageAdapter: Transaction error deleting item '${t}' from '${e}':`,o.error,l),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 l=i.result||[];if(t.filter&&(l=l.filter(T=>{for(let y in t.filter)if(t.filter.hasOwnProperty(y)&&T[y]!==t.filter[y])return !1;return !0})),t.sort){let T=Object.keys(t.sort)[0],y=t.sort[T];T&&l.sort((u,m)=>{let v=u[T],p=m[T];return v<p?y==="asc"?-1:1:v>p?y==="asc"?1:-1:0});}let d=t.skip||0,g=t.limit??1/0;l=l.slice(d,d+g),r(l.map(T=>({...T})));},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 l=n.objectStore(i).clear();l.onsuccess=()=>{o++;},l.onerror=()=>{a.error(`IndexedDBStorageAdapter: Error clearing object store '${i}':`,l.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 le=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 ce=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 de=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 pe=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 c("Task must have a valid taskId","VALIDATION_ERROR");if(await this.adapter.get(this.collectionName,e.taskId))throw new c(`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 c("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 c(`Failed to retrieve task '${e}': ${t}`,"REPOSITORY_ERROR")}}async updateTask(e,t){if(!e)throw new c("TaskId is required","VALIDATION_ERROR");if(!t||Object.keys(t).length===0)throw new c("Updates object cannot be empty","VALIDATION_ERROR");try{let r=await this.adapter.get(this.collectionName,e);if(!r)throw new c(`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 c?r:new c(`Failed to update task '${e}': ${r}`,"REPOSITORY_ERROR")}}async deleteTask(e){if(!e)throw new c("TaskId is required","VALIDATION_ERROR");try{if(!await this.adapter.get(this.collectionName,e))throw new c(`Task with ID '${e}' not found`,"TASK_NOT_FOUND");await this.adapter.delete(this.collectionName,e);}catch(t){throw t instanceof c?t:new c(`Failed to delete task '${e}': ${t}`,"REPOSITORY_ERROR")}}async getTasksByThread(e,t){if(!e)throw new c("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 c(`Failed to get tasks for thread '${e}': ${r}`,"REPOSITORY_ERROR")}}async getTasksByAgent(e,t){if(!e)throw new c("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 c(`Failed to get tasks for agent '${e}': ${r}`,"REPOSITORY_ERROR")}}async getTasksByStatus(e,t){if(!e)throw new c("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 c(`Failed to get tasks by status: ${r}`,"REPOSITORY_ERROR")}}_removeIdField(e){return e.map(t=>{let r={...t};return delete r.id,r})}};var ge=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 ue(h){if(h===null||typeof h!="object")return h;if(h instanceof Date)return new Date(h.getTime());if(Array.isArray(h))return h.map(t=>ue(t));let e={};for(let t in h)Object.prototype.hasOwnProperty.call(h,t)&&(e[t]=ue(h[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=ue(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=ue(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 he=class{constructor(e,t){this.observationRepository=e,this.observationSocket=t;}async record(e){let t={...e,id:q(),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 fe=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 l=t.filter(d=>s.includes(d.schema.name)).map(d=>d.schema);return a.debug(`ToolRegistry: Returning ${l.length} enabled tool schemas for thread ${n}.`),l}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 ct=new lt({allErrors:true}),Pe=new Map;function Qe(h,e){let t=JSON.stringify(h),r;if(Pe.has(t))r=Pe.get(t),a.debug("Using cached JSON schema validator.");else try{r=ct.compile(h),Pe.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:h,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 ye=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,l=o.toolName,d=o.callId;try{if(!await this.stateManager.isToolEnabled(t,l))throw new Error(`Tool "${l}" is not enabled for thread "${t}".`);if(i=await this.toolRegistry.getToolExecutor(l),!i)throw new Error(`Tool "${l}" not found in registry.`);let T=Qe(i.schema.inputSchema,o.arguments);if(!T.isValid){let m=T.errors?.map(v=>`${v.instancePath||"input"} ${v.message}`).join(", ")||"Unknown validation error";throw new Error(`Invalid arguments for tool "${l}": ${m}`)}a.debug(`Executing tool "${l}" with callId "${d}"`,{args:o.arguments,threadId:t,traceId:r});let y={threadId:t,traceId:r};s={...await i.execute(o.arguments,y),callId:d,toolName:l},a.debug(`Tool "${l}" execution successful`,{callId:d,result:s.output,threadId:t,traceId:r});}catch(g){a.error(`Tool "${l}" execution failed for callId "${d}": ${g.message}`,{error:g,threadId:t,traceId:r}),s={callId:d,toolName:l,status:"error",error:g.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(g=>a.error(`Failed to record TOOL_EXECUTION observation for callId ${o.callId}:`,g)),n.push(s)):a.error(`ToolSystem finished processing call ${o.callId} but result object was null.`);}return n}};var gt={pes_system_default:"You are a helpful AI assistant. You need to understand a user's query, potentially use tools to gather information, and then synthesize a final response.",pes_planning_instructions:"Based on the user query and conversation history, identify the user's intent and create a plan to fulfill it using the available tools if necessary.",pes_tool_format_instructions:`Respond in the following format:
|
|
108
127
|
Intent: [Briefly describe the user's goal]
|
|
109
128
|
Plan: [Provide a step-by-step plan. If tools are needed, list them clearly.]
|
|
110
129
|
Tool Calls: [Output *only* the JSON array of tool calls required by the assistant, matching the ArtStandardMessage tool_calls format: [{\\"id\\": \\"call_abc123\\", \\"type\\": \\"function\\", \\"function\\": {\\"name\\": \\"tool_name\\", \\"arguments\\": \\"{\\\\\\"arg1\\\\\\": \\\\\\"value1\\\\\\"}\\"}}] or [] if no tools are needed. Do not add any other text in this section.]`,pes_synthesis_instructions:`Based on the user query, the plan, and the results of any tool executions, synthesize a final response to the user.
|
|
111
|
-
If the tools failed or provided unexpected results, explain the issue and try to answer based on available information or ask for clarification.`},Ae=class{getFragment(e,t){let r=gt[e];if(r===void 0)throw a.error(`[PromptManager] Prompt fragment not found: ${e}`),new c(`Prompt fragment not found: ${e}`,"PROMPT_FRAGMENT_NOT_FOUND");return t?r.replace(/\{\{([^}]+)\}\}/g,(n,o)=>{let s=o.trim(),i=t[s];return i!==void 0?String(i):n}):r}validatePrompt(e){try{return Me.parse(e)}catch(t){throw t instanceof ZodError?(a.error("[PromptManager] Prompt validation failed:",t.errors),new c(`Constructed prompt failed validation: ${t.message}`,"PROMPT_VALIDATION_FAILED",t)):(a.error("[PromptManager] Unexpected error during prompt validation:",t),new c(`Unexpected error during prompt validation: ${t.message}`,"PROMPT_VALIDATION_FAILED",t))}}async assemblePrompt(e,t){try{let r=pt.render(e.template,t),n;try{n=JSON.parse(r);}catch(o){throw a.error("[PromptManager] Failed to parse rendered template as JSON:",o),new c(`Failed to parse rendered template as JSON: ${o.message}`,"PROMPT_ASSEMBLY_FAILED",o)}if(!Array.isArray(n))throw a.error("[PromptManager] Rendered template is not an array:",n),new c(`Rendered template is not an array: ${typeof n}`,"PROMPT_ASSEMBLY_FAILED");return n}catch(r){throw r instanceof c?r:(a.error("[PromptManager] Failed to render prompt template:",r),new c(`Failed to render prompt template: ${r.message}`,"PROMPT_ASSEMBLY_FAILED",r))}}};function Ze(
|
|
130
|
+
If the tools failed or provided unexpected results, explain the issue and try to answer based on available information or ask for clarification.`},Ae=class{getFragment(e,t){let r=gt[e];if(r===void 0)throw a.error(`[PromptManager] Prompt fragment not found: ${e}`),new c(`Prompt fragment not found: ${e}`,"PROMPT_FRAGMENT_NOT_FOUND");return t?r.replace(/\{\{([^}]+)\}\}/g,(n,o)=>{let s=o.trim(),i=t[s];return i!==void 0?String(i):n}):r}validatePrompt(e){try{return Me.parse(e)}catch(t){throw t instanceof ZodError?(a.error("[PromptManager] Prompt validation failed:",t.errors),new c(`Constructed prompt failed validation: ${t.message}`,"PROMPT_VALIDATION_FAILED",t)):(a.error("[PromptManager] Unexpected error during prompt validation:",t),new c(`Unexpected error during prompt validation: ${t.message}`,"PROMPT_VALIDATION_FAILED",t))}}async assemblePrompt(e,t){try{let r=pt.render(e.template,t),n;try{n=JSON.parse(r);}catch(o){throw a.error("[PromptManager] Failed to parse rendered template as JSON:",o),new c(`Failed to parse rendered template as JSON: ${o.message}`,"PROMPT_ASSEMBLY_FAILED",o)}if(!Array.isArray(n))throw a.error("[PromptManager] Rendered template is not an array:",n),new c(`Rendered template is not an array: ${typeof n}`,"PROMPT_ASSEMBLY_FAILED");return n}catch(r){throw r instanceof c?r:(a.error("[PromptManager] Failed to render prompt template:",r),new c(`Failed to render prompt template: ${r.message}`,"PROMPT_ASSEMBLY_FAILED",r))}}};function Ze(h,e,t){switch(t||"append"){case "prepend":return `${e}
|
|
112
131
|
|
|
113
|
-
${
|
|
132
|
+
${h}`;case "append":default:return `${h}
|
|
114
133
|
|
|
115
|
-
${e}`}}function ke(
|
|
116
|
-
`||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 ut=F.object({callId:F.string().min(1),toolName:F.string().min(1),arguments:F.unknown()}),et=F.array(ut),Ie=class{async parsePlanningOutput(e){let t={},r=e,n=[],s=new ve("think").final(e),i="";s.forEach(
|
|
134
|
+
${e}`}}function ke(h){if(h)return typeof h=="string"?{content:h,strategy:"append"}:h}var Te=class{constructor(e,t){this.promptManager=e,this.registry=t;}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 l=this.registry.specs[s.tag],d={...l.defaultVariables||{},...s.variables||{}};i=this.renderTemplate(l.template,d),r=Ze(r,i,s.strategy||l.mergeStrategy||"append"),a.debug?.(`[${t||"no-trace"}] Applied system prompt tag '${s.tag}' with strategy '${s.strategy||l.mergeStrategy||"append"}'.`);}else s.content&&(i=s.content,r=Ze(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*fragment:([^}]+)\s*\}\}/g,(n,o)=>{try{return this.promptManager.getFragment(String(o).trim())}catch{return ""}}).replace(/\{\{\s*([^}:]+)\s*\}\}/g,(n,o)=>{let s=t[String(o).trim()];return s!==void 0?String(s):""})}};var Se=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 ve=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===`
|
|
135
|
+
`||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 ut=F.object({callId:F.string().min(1),toolName:F.string().min(1),arguments:F.unknown()}),et=F.array(ut),Ie=class{async parsePlanningOutput(e){let t={},r=e,n=[],s=new ve("think").final(e),i="";s.forEach(m=>{m.matched?n.push(m.data.trim()):i+=m.data;}),n.length>0&&(t.thoughts=n.join(`
|
|
117
136
|
|
|
118
137
|
---
|
|
119
138
|
|
|
120
|
-
`)),r=i;let
|
|
121
|
-
`):typeof d.plan=="string"&&(h.plan=d.plan),Array.isArray(d.toolCalls)){let R=et.safeParse(d.toolCalls);R.success?h.toolCalls=R.data:h.toolCalls=[];}return h.intent||h.plan||h.toolCalls?h:null}catch{return null}})(r);if(p)return t.intent=p.intent,t.plan=p.plan,t.toolCalls=p.toolCalls,t;let g=r.match(/Intent:\s*([\s\S]*?)(Plan:|Tool Calls:|$)/i);t.intent=g?.[1]?.trim();let A=r.match(/Plan:\s*([\s\S]*?)(Tool Calls:|$)/i);t.plan=A?.[1]?.trim();let y=r.match(/Tool Calls:\s*([\s\S]*?)$/i),m=y?.[1]?.trim();if(t.toolCalls=void 0,m){let u=null,S=null,d=/```(?:json)?\s*(\[[\s\S]*?\])\s*```|(\[[\s\S]*?\])/,h=m.match(d);if(h?u=h[1]?h[1].trim():h[2]?h[2].trim():null:a.debug(`OutputParser: No JSON array found in Tool Calls section. Content: ${m}`),u)try{let R=u.replace(/,\s*(?=]$)/,"");S=JSON.parse(R);}catch(R){a.error(`OutputParser: Failed to parse extracted JSON array. Error: ${R}. Extracted Content: ${u}. Original Content: ${m}`);}if(S!==null){let R=et.safeParse(S);R.success?t.toolCalls=R.data:(a.warn(`OutputParser: Tool Calls JSON structure validation failed. Errors: ${R.error.toString()}. Parsed Content: ${JSON.stringify(S)}`),t.toolCalls=[]);}else t.toolCalls=[];}else y&&(t.toolCalls=[]);return !t.intent&&!t.plan&&(t.toolCalls===void 0||t.toolCalls.length===0)&&!t.thoughts?(a.warn(`OutputParser: Could not parse any structured data (Intent, Plan, Tool Calls, Thoughts) from planning output. Original output: ${e}`),!t.intent&&!t.plan&&(t.toolCalls===void 0||t.toolCalls.length===0)&&a.debug(`OutputParser: No Intent, Plan, or Tool Calls found in non-thinking content part: ${r}`)):!t.intent&&!t.plan&&!t.toolCalls&&!t.thoughts&&a.warn(`OutputParser: Complete failure to parse any structured data or thoughts from planning output: ${e}`),t}async parseSynthesisOutput(e){return e.trim()}};var ee=class extends U{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 te=class extends U{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 Re=class{constructor(e,t,r){this.observationSocketInstance=new ee(e),this.conversationSocketInstance=new te(t),this.llmStreamSocketInstance=new Y,this.a2aTaskSocketInstance=new W(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 re=class{constructor(){this.strategies=new Map;a.info("AuthManager initialized.");}registerStrategy(e,t){if(!e||e.trim()==="")throw new c("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 c(`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 c(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 c(`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 c(`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 c(`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 G=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),l=typeof i=="object"&&i!==null?i:{value:i};return {callId:t.traceId||"unknown",toolName:this.schema.name,status:"success",output:[l],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 ne=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 rt(f){let e="";for(let t=0;t<f.length;t++)e+=String.fromCharCode(f[t]);return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}async function yt(f){let e=new TextEncoder().encode(f),t=await crypto.subtle.digest("SHA-256",e);return rt(new Uint8Array(t))}function tt(f=64){let e=new Uint8Array(f);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var Ee=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)}},B=class f{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 f(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 c(`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-"+tt(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 c("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 c("Could not discover OAuth server details.","INVALID_CONFIG");let e=await this.registerClient(),t=rt(crypto.getRandomValues(new Uint8Array(64))),r=await yt(t);sessionStorage.setItem("code_verifier",t);let n=tt(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 c("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 c("Authorization code missing","VALIDATION_ERROR");if(o!==sessionStorage.getItem("state"))throw new c("State mismatch","VALIDATION_ERROR");let s=localStorage.getItem("mcp_client_id")||await this.registerClient(),i=sessionStorage.getItem("code_verifier")||"",l=new URLSearchParams({grant_type:"authorization_code",code:n,code_verifier:i,redirect_uri:location.origin+"/callback",client_id:s});l.set("resource",this.baseUrl.toString().replace(/\/$/,""));let p=await fetch(this.oauthDiscovery.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l});if(!p.ok){let A=await p.json().catch(()=>({}));throw new c("Token exchange failed: "+(A.error_description||A.error||p.status),"EXTERNAL_SERVICE_ERROR")}let g=await p.json();return this.tokenManager=new Ee(this.oauthDiscovery),this.tokenManager.setClientId(s),this.tokenManager.update(g),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 Ee(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(l=>{a.error("Token refresh failed:",l);});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 c("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 c("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 H=class{constructor(e,t,r){this.activeConnections=new Map;this.configManager=new ne,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 l of i){let p=new G(s,l,this);await this.toolRegistry.registerTool(p),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 c(`Configuration for server "${e}" not found.`,"SERVER_NOT_FOUND");if(t.type!=="streamable-http")throw new c(`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=B.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 c("Companion extension not installed.","CORS_EXTENSION_REQUIRED")}throw new c("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 c(`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 c(`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 G(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 G(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 c("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 ae=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 c(`Discovery endpoint returned ${o.status}: ${o.statusText}`,"EXTERNAL_SERVICE_ERROR");let i=(await o.json()).services.filter(p=>p.service_type==="A2A_AGENT"&&p.status==="active");if(i.length===0)return a.warn(`[${e}] No active A2A agents found in discovery response`),[];let l=i.map(p=>this.transformToA2AAgentInfo(p.card_data));return this.config.enableCaching&&this.setCachedAgents(t,l),a.info(`[${e}] Discovered ${l.length} A2A agents: ${l.map(p=>p.agentName).join(", ")}`),l}catch(r){throw r.name==="AbortError"?new c(`Agent discovery request timed out after ${this.config.timeoutMs}ms`,"TIMEOUT"):r instanceof c?r:new c(`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 l=i.capabilities||[],p=0,g=[];for(let A of l){let y=A.toLowerCase(),m=e.toLowerCase(),u=0;y===m?u=10:y.includes(m)?u=8:m.includes(y)?u=6:u=this.calculateSemanticScore(y,m),u>0&&(p+=u,g.push(A));}return {agent:i,score:p,matchedCapabilities:g}}).filter(i=>i.score>0).sort((i,l)=>l.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,l]of r)if(e.includes(i)&&t.includes(l)||e.includes(l)&&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 l of s)if(i.length>3&&l.length>3&&(i.includes(l)||l.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 oe=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 c(`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 c?r:new c(`Failed to delegate task ${e.taskId}: ${r.message}`,"DELEGATION_FAILED",r)}}async submitTaskToAgent(e,t,r){if(!t.endpoint)throw new c(`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 l=new AbortController,p=setTimeout(()=>l.abort(),this.config.defaultTimeoutMs),g=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:l.signal});if(clearTimeout(p),!g.ok)throw new Error(`HTTP ${g.status}: ${g.statusText}`);let A=await g.json();if(!A.taskId||!A.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: ${A.taskId})`),A}catch(l){if(s=l,i++,l.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}):`,l.message),i>this.config.maxRetries)break;let p=this.config.useExponentialBackoff?this.config.retryDelayMs*Math.pow(2,i-1):this.config.retryDelayMs;a.debug(`[${r}] Retrying task submission in ${p}ms...`),await new Promise(g=>setTimeout(g,p));}throw new c(`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 Ne=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.promptManager=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 Z({dbName:r.dbName||"ARTDB",objectStores:r.objectStores||["conversations","observations","state","a2a_tasks"]});break;case "memory":default:this.storageAdapter=new Q;break}}else this.storageAdapter=this.config.storage;await this.storageAdapter.init?.(),this.conversationRepository=new le(this.storageAdapter),this.observationRepository=new ce(this.storageAdapter),this.stateRepository=new de(this.storageAdapter),this.a2aTaskRepository=new pe(this.storageAdapter),this.uiSystem=new Re(this.observationRepository,this.conversationRepository,this.a2aTaskRepository||void 0),this.conversationManager=new ge(this.conversationRepository,this.uiSystem.getConversationSocket());let e=this.config.stateSavingStrategy||"explicit";if(this.stateManager=new me(this.stateRepository,e),this.observationManager=new he(this.observationRepository,this.uiSystem.getObservationSocket()),this.toolRegistry=new fe(this.stateManager),this.config.tools)for(let r of this.config.tools)await this.toolRegistry.registerTool(r);this.providerManager=new se(this.config.providers),a.info("ProviderManager initialized."),this.reasoningEngine=new Se(this.providerManager),this.promptManager=new Ae;let t=this.config.systemPrompts;if(this.systemPromptResolver=new Te(this.promptManager,t),this.outputParser=new Ie,this.toolSystem=new ye(this.toolRegistry,this.stateManager,this.observationManager),this.config.authConfig?.enabled){if(this.authManager=new re,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 ae({discoveryEndpoint:this.config.a2aConfig.discoveryEndpoint}),this.taskDelegationService=new oe(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 H(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.promptManager||!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,promptManager:this.promptManager,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||X;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 Rt(f){let e=new Ne(f);await e.initialize();let t=e.createAgent(),r=e.getUISystem(),n=e.getStateManager(),o=e.getConversationManager(),s=e.getToolRegistry(),i=e.getObservationManager(),l=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:l}}var xe=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[p,g]of Object.entries(t.filter))Array.isArray(g)?n=n.in(p,g):g!=null&&(n=n.eq(p,g));if(t?.sort){let[p,g]=Object.entries(t.sort)[0]||[];p&&(n=n.order(p,{ascending:g==="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:l}=await n;if(l)throw a.error(`SupabaseStorageAdapter: query error for ${r}`,l),new Error(l.message);return (i??[]).map(p=>({...p}))}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 $e=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-1.5-flash-latest",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:l}=t,p=l||this.defaultModel,g;try{g=this.translateToGemini(e);}catch(u){return a.error(`Error translating ArtStandardPrompt to Gemini format: ${u.message}`,{error:u,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:u instanceof Error?u:new Error(String(u)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let A={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(A).forEach(u=>A[u]===void 0&&delete A[u]),a.debug(`Calling Gemini SDK with model ${p}, stream: ${!!s}`,{threadId:r,traceId:n});let y=this.genAI;return async function*(){let u=Date.now(),S,d,h,R;try{if(s){let O=await y.models.generateContentStream({model:p,contents:g,config:A});for await(let T of O){R=T,S||(S=Date.now()-u);let E=T.text;E&&(yield {type:"TOKEN",data:E,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"}),T.usageMetadata&&(a.debug("Gemini stream chunk usageMetadata:",{usageMetadata:T.usageMetadata,threadId:r,traceId:n}),d={...d||{},...T.usageMetadata});}let v=Date.now()-u;a.debug("Gemini stream finished processing chunks.",{totalGenerationTimeMs:v,threadId:r,traceId:n}),R?(h=R.candidates?.[0]?.finishReason,d=R.usageMetadata,a.debug("Gemini stream - Extracted from last chunk:",{finishReason:h,usageMetadata:d,threadId:r,traceId:n})):a.warn("Gemini stream - No last chunk found after loop.",{threadId:r,traceId:n});let C=d||{};yield {type:"METADATA",data:{stopReason:h,inputTokens:C?.promptTokenCount,outputTokens:C?.candidatesTokenCount,timeToFirstTokenMs:S,totalGenerationTimeMs:v,providerRawUsage:C,traceId:n},threadId:r,traceId:n,sessionId:o};}else {let O=await y.models.generateContent({model:p,contents:g,config:A}),v=O.candidates?.[0],C=O.text,$=v?.finishReason,T=O.usageMetadata,E=Date.now()-u;if(!v||!C){if(O.promptFeedback?.blockReason){a.error("Gemini SDK call blocked.",{feedback:O.promptFeedback,threadId:r,traceId:n}),yield {type:"ERROR",data:new Error(`Gemini API call blocked: ${O.promptFeedback.blockReason}`),threadId:r,traceId:n,sessionId:o};return}a.error("Invalid response structure from Gemini SDK: No text content found",{responseData:O,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}let b=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"LLM_RESPONSE";yield {type:"TOKEN",data:C.trim(),threadId:r,traceId:n,sessionId:o,tokenType:b},yield {type:"METADATA",data:{stopReason:$,inputTokens:T?.promptTokenCount,outputTokens:T?.candidatesTokenCount,totalGenerationTimeMs:E,providerRawUsage:T,traceId:n},threadId:r,traceId:n,sessionId:o};}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(O){a.error(`Error during Gemini SDK call: ${O.message}`,{error:O,threadId:r,traceId:n}),yield {type:"ERROR",data:O instanceof Error?O:new Error(String(O)),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+`
|
|
139
|
+
`)),r=i;let d=(m=>{if(!m)return null;let v=m.trim();if(v=v.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,"").trim(),v=v.replace(/^json\s*/i,"").trim(),!v.startsWith("{")&&v.includes("{")&&v.includes("}")){let p=v.indexOf("{"),f=v.lastIndexOf("}");p>=0&&f>p&&(v=v.slice(p,f+1));}try{let p=JSON.parse(v);if(!p||typeof p!="object")return null;let f={};if(typeof p.intent=="string"&&(f.intent=p.intent),Array.isArray(p.plan)?f.plan=p.plan.join(`
|
|
140
|
+
`):typeof p.plan=="string"&&(f.plan=p.plan),Array.isArray(p.toolCalls)){let A=et.safeParse(p.toolCalls);A.success?f.toolCalls=A.data:f.toolCalls=[];}return f.intent||f.plan||f.toolCalls?f:null}catch{return null}})(r);if(d)return t.intent=d.intent,t.plan=d.plan,t.toolCalls=d.toolCalls,t;let g=r.match(/Intent:\s*([\s\S]*?)(Plan:|Tool Calls:|$)/i);t.intent=g?.[1]?.trim();let T=r.match(/Plan:\s*([\s\S]*?)(Tool Calls:|$)/i);t.plan=T?.[1]?.trim();let y=r.match(/Tool Calls:\s*([\s\S]*?)$/i),u=y?.[1]?.trim();if(t.toolCalls=void 0,u){let m=null,v=null,p=/```(?:json)?\s*(\[[\s\S]*?\])\s*```|(\[[\s\S]*?\])/,f=u.match(p);if(f?m=f[1]?f[1].trim():f[2]?f[2].trim():null:a.debug(`OutputParser: No JSON array found in Tool Calls section. Content: ${u}`),m)try{let A=m.replace(/,\s*(?=]$)/,"");v=JSON.parse(A);}catch(A){a.error(`OutputParser: Failed to parse extracted JSON array. Error: ${A}. Extracted Content: ${m}. Original Content: ${u}`);}if(v!==null){let A=et.safeParse(v);A.success?t.toolCalls=A.data:(a.warn(`OutputParser: Tool Calls JSON structure validation failed. Errors: ${A.error.toString()}. Parsed Content: ${JSON.stringify(v)}`),t.toolCalls=[]);}else t.toolCalls=[];}else y&&(t.toolCalls=[]);return !t.intent&&!t.plan&&(t.toolCalls===void 0||t.toolCalls.length===0)&&!t.thoughts?(a.warn(`OutputParser: Could not parse any structured data (Intent, Plan, Tool Calls, Thoughts) from planning output. Original output: ${e}`),!t.intent&&!t.plan&&(t.toolCalls===void 0||t.toolCalls.length===0)&&a.debug(`OutputParser: No Intent, Plan, or Tool Calls found in non-thinking content part: ${r}`)):!t.intent&&!t.plan&&!t.toolCalls&&!t.thoughts&&a.warn(`OutputParser: Complete failure to parse any structured data or thoughts from planning output: ${e}`),t}async parseSynthesisOutput(e){return e.trim()}};var ee=class extends U{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 te=class extends U{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 Re=class{constructor(e,t,r){this.observationSocketInstance=new ee(e),this.conversationSocketInstance=new te(t),this.llmStreamSocketInstance=new Y,this.a2aTaskSocketInstance=new W(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 re=class{constructor(){this.strategies=new Map;a.info("AuthManager initialized.");}registerStrategy(e,t){if(!e||e.trim()==="")throw new c("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 c(`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 c(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 c(`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 c(`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 c(`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 G=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),l=typeof i=="object"&&i!==null?i:{value:i};return {callId:t.traceId||"unknown",toolName:this.schema.name,status:"success",output:[l],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 ne=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 rt(h){let e="";for(let t=0;t<h.length;t++)e+=String.fromCharCode(h[t]);return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}async function yt(h){let e=new TextEncoder().encode(h),t=await crypto.subtle.digest("SHA-256",e);return rt(new Uint8Array(t))}function tt(h=64){let e=new Uint8Array(h);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var Ee=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)}},B=class h{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 h(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 c(`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-"+tt(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 c("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 c("Could not discover OAuth server details.","INVALID_CONFIG");let e=await this.registerClient(),t=rt(crypto.getRandomValues(new Uint8Array(64))),r=await yt(t);sessionStorage.setItem("code_verifier",t);let n=tt(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 c("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 c("Authorization code missing","VALIDATION_ERROR");if(o!==sessionStorage.getItem("state"))throw new c("State mismatch","VALIDATION_ERROR");let s=localStorage.getItem("mcp_client_id")||await this.registerClient(),i=sessionStorage.getItem("code_verifier")||"",l=new URLSearchParams({grant_type:"authorization_code",code:n,code_verifier:i,redirect_uri:location.origin+"/callback",client_id:s});l.set("resource",this.baseUrl.toString().replace(/\/$/,""));let d=await fetch(this.oauthDiscovery.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l});if(!d.ok){let T=await d.json().catch(()=>({}));throw new c("Token exchange failed: "+(T.error_description||T.error||d.status),"EXTERNAL_SERVICE_ERROR")}let g=await d.json();return this.tokenManager=new Ee(this.oauthDiscovery),this.tokenManager.setClientId(s),this.tokenManager.update(g),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 Ee(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(l=>{a.error("Token refresh failed:",l);});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 c("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 c("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 H=class{constructor(e,t,r){this.activeConnections=new Map;this.configManager=new ne,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 l of i){let d=new G(s,l,this);await this.toolRegistry.registerTool(d),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 c(`Configuration for server "${e}" not found.`,"SERVER_NOT_FOUND");if(t.type!=="streamable-http")throw new c(`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=B.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 c("Companion extension not installed.","CORS_EXTENSION_REQUIRED")}throw new c("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 c(`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 c(`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 G(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 G(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 c("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 ae=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 c(`Discovery endpoint returned ${o.status}: ${o.statusText}`,"EXTERNAL_SERVICE_ERROR");let i=(await o.json()).services.filter(d=>d.service_type==="A2A_AGENT"&&d.status==="active");if(i.length===0)return a.warn(`[${e}] No active A2A agents found in discovery response`),[];let l=i.map(d=>this.transformToA2AAgentInfo(d.card_data));return this.config.enableCaching&&this.setCachedAgents(t,l),a.info(`[${e}] Discovered ${l.length} A2A agents: ${l.map(d=>d.agentName).join(", ")}`),l}catch(r){throw r.name==="AbortError"?new c(`Agent discovery request timed out after ${this.config.timeoutMs}ms`,"TIMEOUT"):r instanceof c?r:new c(`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 l=i.capabilities||[],d=0,g=[];for(let T of l){let y=T.toLowerCase(),u=e.toLowerCase(),m=0;y===u?m=10:y.includes(u)?m=8:u.includes(y)?m=6:m=this.calculateSemanticScore(y,u),m>0&&(d+=m,g.push(T));}return {agent:i,score:d,matchedCapabilities:g}}).filter(i=>i.score>0).sort((i,l)=>l.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,l]of r)if(e.includes(i)&&t.includes(l)||e.includes(l)&&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 l of s)if(i.length>3&&l.length>3&&(i.includes(l)||l.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 oe=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 c(`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 c?r:new c(`Failed to delegate task ${e.taskId}: ${r.message}`,"DELEGATION_FAILED",r)}}async submitTaskToAgent(e,t,r){if(!t.endpoint)throw new c(`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 l=new AbortController,d=setTimeout(()=>l.abort(),this.config.defaultTimeoutMs),g=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:l.signal});if(clearTimeout(d),!g.ok)throw new Error(`HTTP ${g.status}: ${g.statusText}`);let T=await g.json();if(!T.taskId||!T.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: ${T.taskId})`),T}catch(l){if(s=l,i++,l.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}):`,l.message),i>this.config.maxRetries)break;let d=this.config.useExponentialBackoff?this.config.retryDelayMs*Math.pow(2,i-1):this.config.retryDelayMs;a.debug(`[${r}] Retrying task submission in ${d}ms...`),await new Promise(g=>setTimeout(g,d));}throw new c(`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 Ne=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.promptManager=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 Z({dbName:r.dbName||"ARTDB",objectStores:r.objectStores||["conversations","observations","state","a2a_tasks"]});break;case "memory":default:this.storageAdapter=new Q;break}}else this.storageAdapter=this.config.storage;await this.storageAdapter.init?.(),this.conversationRepository=new le(this.storageAdapter),this.observationRepository=new ce(this.storageAdapter),this.stateRepository=new de(this.storageAdapter),this.a2aTaskRepository=new pe(this.storageAdapter),this.uiSystem=new Re(this.observationRepository,this.conversationRepository,this.a2aTaskRepository||void 0),this.conversationManager=new ge(this.conversationRepository,this.uiSystem.getConversationSocket());let e=this.config.stateSavingStrategy||"explicit";if(this.stateManager=new me(this.stateRepository,e),this.observationManager=new he(this.observationRepository,this.uiSystem.getObservationSocket()),this.toolRegistry=new fe(this.stateManager),this.config.tools)for(let r of this.config.tools)await this.toolRegistry.registerTool(r);this.providerManager=new se(this.config.providers),a.info("ProviderManager initialized."),this.reasoningEngine=new Se(this.providerManager),this.promptManager=new Ae;let t=this.config.systemPrompts;if(this.systemPromptResolver=new Te(this.promptManager,t),this.outputParser=new Ie,this.toolSystem=new ye(this.toolRegistry,this.stateManager,this.observationManager),this.config.authConfig?.enabled){if(this.authManager=new re,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 ae({discoveryEndpoint:this.config.a2aConfig.discoveryEndpoint}),this.taskDelegationService=new oe(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 H(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.promptManager||!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,promptManager:this.promptManager,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||X;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 Rt(h){let e=new Ne(h);await e.initialize();let t=e.createAgent(),r=e.getUISystem(),n=e.getStateManager(),o=e.getConversationManager(),s=e.getToolRegistry(),i=e.getObservationManager(),l=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:l}}var xe=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[d,g]of Object.entries(t.filter))Array.isArray(g)?n=n.in(d,g):g!=null&&(n=n.eq(d,g));if(t?.sort){let[d,g]=Object.entries(t.sort)[0]||[];d&&(n=n.order(d,{ascending:g==="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:l}=await n;if(l)throw a.error(`SupabaseStorageAdapter: query error for ${r}`,l),new Error(l.message);return (i??[]).map(d=>({...d}))}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 $e=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-1.5-flash-latest",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:l}=t,d=l||this.defaultModel,g;try{g=this.translateToGemini(e);}catch(m){return a.error(`Error translating ArtStandardPrompt to Gemini format: ${m.message}`,{error:m,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:m instanceof Error?m:new Error(String(m)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let T={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(T).forEach(m=>T[m]===void 0&&delete T[m]),a.debug(`Calling Gemini SDK with model ${d}, stream: ${!!s}`,{threadId:r,traceId:n});let y=this.genAI;return async function*(){let m=Date.now(),v,p,f,A;try{if(s){let R=await y.models.generateContentStream({model:d,contents:g,config:T});for await(let S of R){A=S,v||(v=Date.now()-m);let E=S.text;E&&(yield {type:"TOKEN",data:E,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"}),S.usageMetadata&&(a.debug("Gemini stream chunk usageMetadata:",{usageMetadata:S.usageMetadata,threadId:r,traceId:n}),p={...p||{},...S.usageMetadata});}let O=Date.now()-m;a.debug("Gemini stream finished processing chunks.",{totalGenerationTimeMs:O,threadId:r,traceId:n}),A?(f=A.candidates?.[0]?.finishReason,p=A.usageMetadata,a.debug("Gemini stream - Extracted from last chunk:",{finishReason:f,usageMetadata:p,threadId:r,traceId:n})):a.warn("Gemini stream - No last chunk found after loop.",{threadId:r,traceId:n});let P=p||{};yield {type:"METADATA",data:{stopReason:f,inputTokens:P?.promptTokenCount,outputTokens:P?.candidatesTokenCount,timeToFirstTokenMs:v,totalGenerationTimeMs:O,providerRawUsage:P,traceId:n},threadId:r,traceId:n,sessionId:o};}else {let R=await y.models.generateContent({model:d,contents:g,config:T}),O=R.candidates?.[0],P=R.text,b=O?.finishReason,S=R.usageMetadata,E=Date.now()-m;if(!O||!P){if(R.promptFeedback?.blockReason){a.error("Gemini SDK call blocked.",{feedback:R.promptFeedback,threadId:r,traceId:n}),yield {type:"ERROR",data:new Error(`Gemini API call blocked: ${R.promptFeedback.blockReason}`),threadId:r,traceId:n,sessionId:o};return}a.error("Invalid response structure from Gemini SDK: No text content found",{responseData:R,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}let M=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"LLM_RESPONSE";yield {type:"TOKEN",data:P.trim(),threadId:r,traceId:n,sessionId:o,tokenType:M},yield {type:"METADATA",data:{stopReason:b,inputTokens:S?.promptTokenCount,outputTokens:S?.candidatesTokenCount,totalGenerationTimeMs:E,providerRawUsage:S,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 Gemini SDK call: ${R.message}`,{error:R,threadId:r,traceId:n}),yield {type:"ERROR",data:R instanceof Error?R:new Error(String(R)),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+`
|
|
122
141
|
|
|
123
|
-
`,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 c("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 Le=class{constructor(e){this.providerName="openai";if(!e.apiKey)throw new Error("OpenAIAdapter requires an apiKey in options.");this.apiKey=e.apiKey,this.model=e.model||"gpt-3.5-turbo",this.apiBaseUrl=e.apiBaseUrl||"https://api.openai.com/v1",a.debug(`OpenAIAdapter initialized with model: ${this.model}`);}async call(e,t){let{threadId:r,traceId:n=`openai-trace-${Date.now()}`,sessionId:o,stream:s,callContext:i,model:l}=t,
|
|
124
|
-
`);for(let C=0;C<v.length-1;C++){let $=v[C].trim();if($!==""&&$.startsWith("data: ")){let T=$.substring(6);if(T==="[DONE]"){S=!0;break}try{let b=JSON.parse(T).choices?.[0];if(!b)continue;let P=b.delta?.content;if(typeof P=="string"&&P.length>0){let M=Date.now();l===void 0&&(l=M-i),p++,yield {type:"TOKEN",data:P,threadId:r??"",traceId:n??"",sessionId:o,tokenType:s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"};}let _=b.delta?.tool_calls;_&&(y||(y=[]),_.forEach(M=>{M.index!==void 0&&(y[M.index]||(y[M.index]={}),M.id&&(y[M.index].id=M.id),M.type&&(y[M.index].type=M.type),M.function&&(y[M.index].function||(y[M.index].function={}),M.function.name&&(y[M.index].function.name=M.function.name),M.function.arguments&&(y[M.index].function.arguments=(y[M.index].function.arguments||"")+M.function.arguments)));}),a.debug("OpenAI stream tool call delta:",{deltaToolCalls:_,threadId:r,traceId:n})),b.finish_reason&&(g=b.finish_reason,a.debug(`OpenAI stream finish reason received: ${g}`,{threadId:r,traceId:n}));}catch(E){a.warn(`Failed to parse OpenAI stream chunk: ${T}`,{parseError:E,threadId:r,traceId:n});}}}u=v[v.length-1];}catch(R){a.error(`Error reading OpenAI stream: ${R.message}`,{error:R,threadId:r,traceId:n}),yield {type:"ERROR",data:R instanceof c?R:new c(`Error reading OpenAI stream: ${R.message}`,"LLM_PROVIDER_ERROR",R),threadId:r??"",traceId:n??"",sessionId:o??""},S=true;}let d=Date.now()-i;yield {type:"METADATA",data:{stopReason:g,outputTokens:p>0?p:void 0,timeToFirstTokenMs:l,totalGenerationTimeMs:d,providerRawUsage:{finish_reason:g,usage:A,aggregatedToolCalls:y},traceId:n},threadId:r??"",traceId:n??"",sessionId:o??""},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:o??""},a.debug("OpenAI stream processing finished.",{threadId:r,traceId:n});}translateToOpenAI(e){return e.map(t=>{switch(t.role){case "system":return typeof t.content!="string"?(a.warn("OpenAIAdapter: 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("OpenAIAdapter: 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 c(`OpenAIAdapter: 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 c("OpenAIAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return typeof t.content!="string"&&a.warn("OpenAIAdapter: 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 a.debug("OpenAIAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls."),new c("OpenAIAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw a.warn(`OpenAIAdapter: Skipping message with unknown role: ${t.role}`),new c(`OpenAIAdapter: Unknown message role '${t.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var wt="claude-3-7-sonnet-20250219",_t=4096,De=class{constructor(e){this.providerName="anthropic";if(!e.apiKey)throw new c("AnthropicAdapter requires an apiKey in options.","INVALID_CONFIG");this.client=new Anthropic({apiKey:e.apiKey,baseURL:e.apiBaseUrl||void 0}),this.defaultModel=e.model||wt,this.defaultMaxTokens=e.defaultMaxTokens||_t,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:l,tools:p,providerConfig:g}=t,A=g?.modelId||l||this.defaultModel,y=g?.adapterOptions||{},m=y.max_tokens||y.maxTokens||t.max_tokens||t.maxOutputTokens||this.defaultMaxTokens,u=y.temperature??t.temperature??this.defaultTemperature,S=y.top_p||y.topP||t.top_p||t.topP,d=y.top_k||y.topK||t.top_k||t.topK,h=y.stop_sequences||y.stopSequences||t.stop||t.stop_sequences||t.stopSequences;if(!m){let T=new c("Anthropic API requires 'max_tokens'.","INVALID_CONFIG");return async function*(){yield {type:"ERROR",data:T,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let R,O;try{let T=this.translateToAnthropicSdk(e);R=T.systemPrompt,O=T.messages;}catch(T){a.error(`Error translating ArtStandardPrompt to Anthropic SDK format: ${T.message}`,{error:T,threadId:r,traceId:n});let E=T instanceof c?T:new c(`Prompt translation failed: ${T.message}`,"PROMPT_TRANSLATION_FAILED",T);return async function*(){yield {type:"ERROR",data:E,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let v=p?this.translateArtToolsToAnthropic(p):void 0,C={model:A,messages:O,max_tokens:m,system:R,temperature:u,top_p:S,top_k:d,stop_sequences:h,stream:s,tools:v};return Object.keys(C).forEach(T=>{let E=T;C[E]===void 0&&delete C[E];}),a.debug(`Calling Anthropic API with model ${A}`,{stream:s,tools:!!v,threadId:r,traceId:n}),async function*(){try{if(s){let T=await this.client.messages.create(C,this.getRequestOptions(A)),E="",b=[],P,_,M=null,D={input_tokens:void 0,output_tokens:void 0},He,Ke;for await(let k of T)switch(k.type){case "message_start":a.debug("Anthropic stream: message_start",{usage:k.message.usage,threadId:r,traceId:n}),D.input_tokens=k.message.usage.input_tokens,D.output_tokens=k.message.usage.output_tokens,P=D.input_tokens,_=D.output_tokens,He={inputTokens:P,outputTokens:_,providerRawUsage:{usage:{...k.message.usage}},traceId:n},yield {type:"METADATA",data:He,threadId:r,traceId:n,sessionId:o};break;case "content_block_start":a.debug("Anthropic stream: content_block_start",{index:k.index,block:k.content_block,threadId:r,traceId:n});break;case "content_block_delta":if(a.debug("Anthropic stream: content_block_delta",{index:k.index,delta:k.delta,threadId:r,traceId:n}),k.delta.type==="text_delta"){let _e=k.delta.text;E+=_e,yield {type:"TOKEN",data:_e,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"};}break;case "content_block_stop":a.debug("Anthropic stream: content_block_stop",{index:k.index,threadId:r,traceId:n});break;case "message_delta":a.debug("Anthropic stream: message_delta",{delta:k.delta,usage:k.usage,threadId:r,traceId:n}),M=k.delta.stop_reason??M,k.usage.output_tokens!==void 0&&k.usage.output_tokens!==null&&(D.output_tokens=k.usage.output_tokens),_=D.output_tokens,Ke={inputTokens:P,outputTokens:_,stopReason:k.delta.stop_reason??void 0,providerRawUsage:{usage:{input_tokens:P,output_tokens:k.usage.output_tokens??void 0},delta:k.delta},traceId:n},yield {type:"METADATA",data:Ke,threadId:r,traceId:n,sessionId:o};break;case "message_stop":{if(a.debug("Anthropic stream: message_stop. Using accumulated data.",{threadId:r,traceId:n}),M==="tool_use"&&b.length>0){let K=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE",Ve=b.map(Oe=>({type:"tool_use",id:Oe.id,name:Oe.name,input:Oe.input}));E.trim()?yield {type:"TOKEN",data:[{type:"text",text:E.trim()},...Ve],threadId:r,traceId:n,sessionId:o,tokenType:K}:yield {type:"TOKEN",data:Ve,threadId:r,traceId:n,sessionId:o,tokenType:K};}else if(E.trim()){let K=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:E.trim(),threadId:r,traceId:n,sessionId:o,tokenType:K};}yield {type:"METADATA",data:{inputTokens:D.input_tokens??void 0,outputTokens:D.output_tokens??void 0,stopReason:M??void 0,providerRawUsage:{usage:{input_tokens:D.input_tokens??void 0,output_tokens:D.output_tokens??void 0},stop_reason:M},traceId:n},threadId:r,traceId:n,sessionId:o};break}default:{a.warn("Anthropic stream: unhandled raw stream event type",{eventType:k.type,event:k,threadId:r,traceId:n});break}}}else {let T=await this.client.messages.create(C,this.getRequestOptions(A));a.debug(`Anthropic API call successful (non-streaming). Stop Reason: ${T.stop_reason}`,{threadId:r,traceId:n});let E="",b=[];T.content.forEach(_=>{_.type==="text"?E+=_.text:_.type==="tool_use"&&b.push(_);}),E=E.trim();let P=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";if(T.stop_reason==="tool_use"&&b.length>0){let _=b.map(M=>({type:"tool_use",id:M.id,name:M.name,input:M.input}));E?yield {type:"TOKEN",data:[{type:"text",text:E},..._],threadId:r,traceId:n,sessionId:o,tokenType:P}:yield {type:"TOKEN",data:_,threadId:r,traceId:n,sessionId:o,tokenType:P};}else E?yield {type:"TOKEN",data:E,threadId:r,traceId:n,sessionId:o,tokenType:P}:T.stop_reason!=="tool_use"&&a.warn("Anthropic API (non-streaming): Empty response text and not a tool_use stop_reason.",{response:T,threadId:r,traceId:n});T.usage&&(yield {type:"METADATA",data:{inputTokens:T.usage.input_tokens,outputTokens:T.usage.output_tokens,stopReason:T.stop_reason??void 0,providerRawUsage:{usage:T.usage,stop_reason:T.stop_reason,stop_sequence:T.stop_sequence},traceId:n},threadId:r,traceId:n,sessionId:o});}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(T){a.error(`Error during Anthropic API call: ${T.message}`,{error:T,threadId:r,traceId:n}),yield {type:"ERROR",data:T instanceof c?T:T instanceof Anthropic.APIError?new c(`Anthropic API Error (${T.status}): ${T.message}`,"LLM_PROVIDER_ERROR",T):new c(T.message||"Unknown Anthropic adapter error","LLM_PROVIDER_ERROR",T),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}.bind(this)()}getRequestOptions(e){let t=[];return 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 p=typeof s.content=="string"?s.content:String(s.content);t?(a.warn("AnthropicAdapter: Multiple system messages found. Appending to existing system prompt."),t+=`
|
|
125
|
-
${p}`):t=p;continue}let i=this.mapArtMessageToAnthropicContent(s),l=s.role==="user"||s.role==="tool_result"?"user":"assistant";if(n===l&&r.length>0){let p=r[r.length-1],g;typeof p.content=="string"?g=[{type:"text",text:p.content}]:g=p.content;let A=typeof i=="string"?[{type:"text",text:i}]:i,y=[...g,...A];p.content=y,a.debug(`AnthropicAdapter: Merged consecutive ${l} messages.`);}else r.push({role:l,content:i}),n=l;}!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 c(`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 c("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 c(`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 Ue=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:l}=t,p=l||this.model;if(s)return a.warn("OpenRouterAdapter: Streaming requested but not implemented. Returning error stream.",{threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new c("Streaming is not yet implemented for the OpenRouterAdapter.","LLM_PROVIDER_ERROR"),threadId:r??"",traceId:n??"",sessionId:o},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:o};}();let g;try{g=this.translateToOpenAI(e);}catch(d){return a.error(`Error translating ArtStandardPrompt to OpenRouter/OpenAI format: ${d.message}`,{error:d,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:d instanceof c?d:new c(`Prompt translation failed: ${d.message}`,"PROMPT_TRANSLATION_FAILED",d),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let A=`${this.apiBaseUrl}/chat/completions`,y=t.stop||t.stop_sequences||t.stopSequences,m={model:p,messages:g,temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,stop:y,stream:false};Object.keys(m).forEach(d=>m[d]===void 0&&delete m[d]);let u={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return this.siteUrl&&(u["HTTP-Referer"]=this.siteUrl),this.appName&&(u["X-Title"]=this.appName),a.debug(`Calling OpenRouter API (non-streaming): ${A} with model ${this.model}`,{threadId:r,traceId:n}),async function*(){try{let d=await fetch(A,{method:"POST",headers:u,body:JSON.stringify(m)});if(!d.ok){let T=await d.text(),E=T;try{let P=JSON.parse(T);P?.error?.message&&(E=P.error.message);}catch{}yield {type:"ERROR",data:new c(`OpenRouter API request failed: ${d.status} ${d.statusText} - ${E}`,"LLM_PROVIDER_ERROR",new Error(T)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let h=await d.json(),R=h.choices?.[0];if(!R?.message){yield {type:"ERROR",data:new c("Invalid response structure from OpenRouter API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(h))),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let O=R.message;O.tool_calls&&a.debug("OpenRouter response included tool calls (non-streaming)",{toolCalls:O.tool_calls,threadId:r,traceId:n}),a.debug(`OpenRouter API call successful. Finish reason: ${R.finish_reason}`,{threadId:r,traceId:n});let v=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(O.content??"").trim(),threadId:r,traceId:n,sessionId:o,tokenType:v},yield {type:"METADATA",data:{inputTokens:h.usage?.prompt_tokens,outputTokens:h.usage?.completion_tokens,stopReason:R.finish_reason,providerRawUsage:{usage:h.usage,finish_reason:R.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(d){a.error(`Error during OpenRouter API call: ${d.message}`,{error:d,threadId:r,traceId:n}),yield {type:"ERROR",data:d instanceof c?d:new c(d.message,"LLM_PROVIDER_ERROR",d),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("OpenRouterAdapter: 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("OpenRouterAdapter: 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 c(`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.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 c("OpenRouterAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return typeof t.content!="string"&&a.warn("OpenRouterAdapter: 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 c("OpenRouterAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new c(`OpenRouterAdapter: Unknown message role '${t.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var Fe=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:l}=t,p=l||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 c("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 g;try{g=this.translateToOpenAI(e);}catch(d){return a.error(`Error translating ArtStandardPrompt to DeepSeek/OpenAI format: ${d.message}`,{error:d,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:d instanceof c?d:new c(`Prompt translation failed: ${d.message}`,"PROMPT_TRANSLATION_FAILED",d),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let A=`${this.apiBaseUrl}/chat/completions`,y=t.stop||t.stop_sequences||t.stopSequences,m={model:p,messages:g,temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,stop:y,stream:false};Object.keys(m).forEach(d=>m[d]===void 0&&delete m[d]);let u={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return a.debug(`Calling DeepSeek API (non-streaming): ${A} with model ${this.model}`,{threadId:r,traceId:n}),async function*(){try{let d=await fetch(A,{method:"POST",headers:u,body:JSON.stringify(m)});if(!d.ok){let T=await d.text(),E=T;try{let P=JSON.parse(T);P?.error?.message&&(E=P.error.message);}catch{}yield {type:"ERROR",data:new c(`DeepSeek API request failed: ${d.status} ${d.statusText} - ${E}`,"LLM_PROVIDER_ERROR",new Error(T)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let h=await d.json(),R=h.choices?.[0];if(!R?.message){yield {type:"ERROR",data:new c("Invalid response structure from DeepSeek API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(h))),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let O=R.message;O.tool_calls&&a.debug("DeepSeek response included tool calls (non-streaming)",{toolCalls:O.tool_calls,threadId:r,traceId:n}),a.debug(`DeepSeek API call successful. Finish reason: ${R.finish_reason}`,{threadId:r,traceId:n});let v=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(O.content??"").trim(),threadId:r,traceId:n,sessionId:o,tokenType:v},yield {type:"METADATA",data:{inputTokens:h.usage?.prompt_tokens,outputTokens:h.usage?.completion_tokens,stopReason:R.finish_reason,providerRawUsage:{usage:h.usage,finish_reason:R.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(d){a.error(`Error during DeepSeek API call: ${d.message}`,{error:d,threadId:r,traceId:n}),yield {type:"ERROR",data:d instanceof c?d:new c(d.message,"LLM_PROVIDER_ERROR",d),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 c(`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 c("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 c("DeepSeekAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new c(`DeepSeekAdapter: Unknown message role '${t.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var Ge=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 Ot({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:l,tools:p,providerConfig:g}=t,A=g?.modelId||l||this.defaultModel;if(!A){let d=new c("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:d,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let y;try{y=this.translateToOpenAI(e,A);}catch(d){a.error(`Error translating ArtStandardPrompt to OpenAI format for Ollama: ${d.message}`,{error:d,threadId:r,traceId:n});let h=d instanceof c?d:new c(`Prompt translation failed: ${d.message}`,"PROMPT_TRANSLATION_FAILED",d);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=p?this.translateArtToolsToOpenAI(p):void 0,u={model:A,messages:y,temperature:t.temperature??g?.adapterOptions?.temperature,max_tokens:t.max_tokens??t.maxOutputTokens??g?.adapterOptions?.max_tokens,top_p:t.top_p??t.topP??g?.adapterOptions?.top_p,stop:(t.stop||t.stop_sequences||t.stopSequences)??g?.adapterOptions?.stop,stream:s,tools:m,tool_choice:t.tool_choice??g?.adapterOptions?.tool_choice};return Object.keys(u).forEach(d=>{let h=d;u[h]===void 0&&delete u[h];}),a.debug(`Calling Ollama API (via OpenAI client) with model ${A}`,{stream:s,tools:!!m,threadId:r,traceId:n}),async function*(){let d=Date.now(),h,R=0,O,v;try{if(s){let T=await this.client.chat.completions.create(u),E=[];for await(let b of T){h||(h=Date.now()-d);let P=b.choices[0]?.delta;if(v=b.choices[0]?.finish_reason??v,P?.content){R++;let _=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:P.content,threadId:r,traceId:n,sessionId:o,tokenType:_};}P?.tool_calls&&P.tool_calls.forEach(_=>{_.index!==void 0&&(E[_.index]?(_.id&&(E[_.index].id=_.id),_.function?.name&&(E[_.index].function.name=_.function.name),_.function?.arguments&&(E[_.index].function||(E[_.index].function={name:"",arguments:""}),E[_.index].function.arguments+=_.function.arguments)):E[_.index]={id:_.id||"",type:"function",function:{name:_.function?.name||"",arguments:_.function?.arguments||""}});}),b.usage&&(O=b.usage);}if(v==="tool_calls"&&E.length>0){let b=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:E.map(_=>({type:"tool_use",id:_.id,name:_.function.name,input:JSON.parse(_.function.arguments||"{}")})),threadId:r,traceId:n,sessionId:o,tokenType:b};}}else {let T=await this.client.chat.completions.create(u),E=T.choices[0];if(!E||!E.message)throw new c("Invalid response structure from Ollama API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(T)));v=E.finish_reason??void 0,O=T.usage;let b=E.message,P=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";if(b.tool_calls&&b.tool_calls.length>0){let _=b.tool_calls.map(M=>({type:"tool_use",id:M.id,name:M.function.name,input:JSON.parse(M.function.arguments||"{}")}));b.content?yield {type:"TOKEN",data:[{type:"text",text:b.content.trim()},..._],threadId:r,traceId:n,sessionId:o,tokenType:P}:yield {type:"TOKEN",data:_,threadId:r,traceId:n,sessionId:o,tokenType:P};}else b.content&&(yield {type:"TOKEN",data:b.content.trim(),threadId:r,traceId:n,sessionId:o,tokenType:P});}let C=Date.now()-d;yield {type:"METADATA",data:{stopReason:v,inputTokens:O?.prompt_tokens,outputTokens:O?.completion_tokens??(s?R:void 0),timeToFirstTokenMs:s?h:void 0,totalGenerationTimeMs:C,providerRawUsage:{usage:O,finish_reason:v},traceId:n},threadId:r,traceId:n,sessionId:o};}catch(C){a.error(`Error during Ollama API call: ${C.message}`,{error:C,threadId:r,traceId:n}),yield {type:"ERROR",data:C instanceof c?C:C.constructor.name==="APIError"?new c(`Ollama API Error (${C.status}): ${C.message}`,"LLM_PROVIDER_ERROR",C):new c(C.message||"Unknown Ollama adapter error","LLM_PROVIDER_ERROR",C),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 l="user";i.role==="system"?l="system":i.role==="user"?l="user":i.role==="assistant"?l="assistant":i.role==="tool_result"&&(l="tool");let p=this.mapArtMessageToOpenAIMessage(i);if(s&&s.role===l&&l!=="system"&&l!=="tool"){let g="";typeof s.content=="string"&&typeof p.content=="string"?g=`${s.content}
|
|
126
|
-
${
|
|
127
|
-
${
|
|
128
|
-
${
|
|
129
|
-
${
|
|
142
|
+
`,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 c("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 Le=class{constructor(e){this.providerName="openai";if(!e.apiKey)throw new Error("OpenAIAdapter requires an apiKey in options.");this.apiKey=e.apiKey,this.model=e.model||"gpt-3.5-turbo",this.apiBaseUrl=e.apiBaseUrl||"https://api.openai.com/v1",a.debug(`OpenAIAdapter initialized with model: ${this.model}`);}async call(e,t){let{threadId:r,traceId:n=`openai-trace-${Date.now()}`,sessionId:o,stream:s,callContext:i,model:l}=t,d=l||this.model,g;try{g=this.translateToOpenAI(e);}catch(u){return a.error(`Error translating ArtStandardPrompt to OpenAI format: ${u.message}`,{error:u,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:u instanceof c?u:new c(`Prompt translation failed: ${u.message}`,"PROMPT_TRANSLATION_FAILED",u),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let T=`${this.apiBaseUrl}/chat/completions`,y={model:d,messages:g,temperature:t.temperature,max_tokens:t.max_tokens,top_p:t.top_p,frequency_penalty:t.frequency_penalty,presence_penalty:t.presence_penalty,stop:t.stop||t.stop_sequences,stream:!!s};Object.keys(y).forEach(u=>y[u]===void 0&&delete y[u]),a.debug(`Calling OpenAI API: ${T} with model ${d}, stream: ${!!s}`,{threadId:r,traceId:n});try{let u=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(y)});if(!u.ok){let m=await u.text();return a.error(`OpenAI API request failed with status ${u.status}: ${m}`,{threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new c(`OpenAI API request failed: ${u.status} ${u.statusText} - ${m}`,"LLM_PROVIDER_ERROR",new Error(m)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}if(s&&u.body)return this.processStream(u.body,t);{let m=await u.json(),v=m.choices?.[0];if(!v?.message)return a.error("Invalid response structure from OpenAI API: No message found",{responseData:m,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new c("Invalid response structure from OpenAI API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(m))),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}();let p=v.message;return p.tool_calls&&a.debug("OpenAI response included tool calls (non-streaming)",{toolCalls:p.tool_calls,threadId:r,traceId:n}),a.debug(`OpenAI API call successful. Finish reason: ${v.finish_reason}`,{threadId:r,traceId:n}),async function*(){let A=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(p.content??"").trim(),threadId:r,traceId:n,sessionId:o,tokenType:A},yield {type:"METADATA",data:{stopReason:v.finish_reason,inputTokens:m.usage?.prompt_tokens,outputTokens:m.usage?.completion_tokens,providerRawUsage:{usage:m.usage,finish_reason:v.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}}catch(u){return a.error(`Error during OpenAI API call: ${u.message}`,{error:u,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:u instanceof c?u:new c(u.message,"LLM_PROVIDER_ERROR",u),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}}async*processStream(e,t){let{threadId:r,traceId:n,sessionId:o,callContext:s}=t,i=Date.now(),l,d=0,g,T=void 0,y,u=e.pipeThrough(new TextDecoderStream).getReader(),m="",v=false;for(;!v;)try{let{value:A,done:R}=await u.read();if(v=R,v)break;m+=A;let O=m.split(`
|
|
143
|
+
`);for(let P=0;P<O.length-1;P++){let b=O[P].trim();if(b!==""&&b.startsWith("data: ")){let S=b.substring(6);if(S==="[DONE]"){v=!0;break}try{let M=JSON.parse(S).choices?.[0];if(!M)continue;let k=M.delta?.content;if(typeof k=="string"&&k.length>0){let C=Date.now();l===void 0&&(l=C-i),d++,yield {type:"TOKEN",data:k,threadId:r??"",traceId:n??"",sessionId:o,tokenType:s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"};}let _=M.delta?.tool_calls;_&&(y||(y=[]),_.forEach(C=>{C.index!==void 0&&(y[C.index]||(y[C.index]={}),C.id&&(y[C.index].id=C.id),C.type&&(y[C.index].type=C.type),C.function&&(y[C.index].function||(y[C.index].function={}),C.function.name&&(y[C.index].function.name=C.function.name),C.function.arguments&&(y[C.index].function.arguments=(y[C.index].function.arguments||"")+C.function.arguments)));}),a.debug("OpenAI stream tool call delta:",{deltaToolCalls:_,threadId:r,traceId:n})),M.finish_reason&&(g=M.finish_reason,a.debug(`OpenAI stream finish reason received: ${g}`,{threadId:r,traceId:n}));}catch(E){a.warn(`Failed to parse OpenAI stream chunk: ${S}`,{parseError:E,threadId:r,traceId:n});}}}m=O[O.length-1];}catch(A){a.error(`Error reading OpenAI stream: ${A.message}`,{error:A,threadId:r,traceId:n}),yield {type:"ERROR",data:A instanceof c?A:new c(`Error reading OpenAI stream: ${A.message}`,"LLM_PROVIDER_ERROR",A),threadId:r??"",traceId:n??"",sessionId:o??""},v=true;}let p=Date.now()-i;yield {type:"METADATA",data:{stopReason:g,outputTokens:d>0?d:void 0,timeToFirstTokenMs:l,totalGenerationTimeMs:p,providerRawUsage:{finish_reason:g,usage:T,aggregatedToolCalls:y},traceId:n},threadId:r??"",traceId:n??"",sessionId:o??""},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:o??""},a.debug("OpenAI stream processing finished.",{threadId:r,traceId:n});}translateToOpenAI(e){return e.map(t=>{switch(t.role){case "system":return typeof t.content!="string"?(a.warn("OpenAIAdapter: 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("OpenAIAdapter: 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 c(`OpenAIAdapter: 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 c("OpenAIAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return typeof t.content!="string"&&a.warn("OpenAIAdapter: 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 a.debug("OpenAIAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls."),new c("OpenAIAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw a.warn(`OpenAIAdapter: Skipping message with unknown role: ${t.role}`),new c(`OpenAIAdapter: Unknown message role '${t.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var wt="claude-3-7-sonnet-20250219",_t=4096,De=class{constructor(e){this.providerName="anthropic";if(!e.apiKey)throw new c("AnthropicAdapter requires an apiKey in options.","INVALID_CONFIG");this.client=new Anthropic({apiKey:e.apiKey,baseURL:e.apiBaseUrl||void 0}),this.defaultModel=e.model||wt,this.defaultMaxTokens=e.defaultMaxTokens||_t,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:l,tools:d,providerConfig:g}=t,T=g?.modelId||l||this.defaultModel,y=g?.adapterOptions||{},u=y.max_tokens||y.maxTokens||t.max_tokens||t.maxOutputTokens||this.defaultMaxTokens,m=y.temperature??t.temperature??this.defaultTemperature,v=y.top_p||y.topP||t.top_p||t.topP,p=y.top_k||y.topK||t.top_k||t.topK,f=y.stop_sequences||y.stopSequences||t.stop||t.stop_sequences||t.stopSequences;if(!u){let S=new c("Anthropic API requires 'max_tokens'.","INVALID_CONFIG");return async function*(){yield {type:"ERROR",data:S,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let A,R;try{let S=this.translateToAnthropicSdk(e);A=S.systemPrompt,R=S.messages;}catch(S){a.error(`Error translating ArtStandardPrompt to Anthropic SDK format: ${S.message}`,{error:S,threadId:r,traceId:n});let E=S instanceof c?S:new c(`Prompt translation failed: ${S.message}`,"PROMPT_TRANSLATION_FAILED",S);return async function*(){yield {type:"ERROR",data:E,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let O=d?this.translateArtToolsToAnthropic(d):void 0,P={model:T,messages:R,max_tokens:u,system:A,temperature:m,top_p:v,top_k:p,stop_sequences:f,stream:s,tools:O};return Object.keys(P).forEach(S=>{let E=S;P[E]===void 0&&delete P[E];}),a.debug(`Calling Anthropic API with model ${T}`,{stream:s,tools:!!O,threadId:r,traceId:n}),async function*(){try{if(s){let S=await this.client.messages.create(P,this.getRequestOptions(T)),E="",M=[],k,_,C=null,L={input_tokens:void 0,output_tokens:void 0},He,Ke;for await(let N of S)switch(N.type){case "message_start":a.debug("Anthropic stream: message_start",{usage:N.message.usage,threadId:r,traceId:n}),L.input_tokens=N.message.usage.input_tokens,L.output_tokens=N.message.usage.output_tokens,k=L.input_tokens,_=L.output_tokens,He={inputTokens:k,outputTokens:_,providerRawUsage:{usage:{...N.message.usage}},traceId:n},yield {type:"METADATA",data:He,threadId:r,traceId:n,sessionId:o};break;case "content_block_start":a.debug("Anthropic stream: content_block_start",{index:N.index,block:N.content_block,threadId:r,traceId:n});break;case "content_block_delta":if(a.debug("Anthropic stream: content_block_delta",{index:N.index,delta:N.delta,threadId:r,traceId:n}),N.delta.type==="text_delta"){let _e=N.delta.text;E+=_e,yield {type:"TOKEN",data:_e,threadId:r,traceId:n,sessionId:o,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"};}break;case "content_block_stop":a.debug("Anthropic stream: content_block_stop",{index:N.index,threadId:r,traceId:n});break;case "message_delta":a.debug("Anthropic stream: message_delta",{delta:N.delta,usage:N.usage,threadId:r,traceId:n}),C=N.delta.stop_reason??C,N.usage.output_tokens!==void 0&&N.usage.output_tokens!==null&&(L.output_tokens=N.usage.output_tokens),_=L.output_tokens,Ke={inputTokens:k,outputTokens:_,stopReason:N.delta.stop_reason??void 0,providerRawUsage:{usage:{input_tokens:k,output_tokens:N.usage.output_tokens??void 0},delta:N.delta},traceId:n},yield {type:"METADATA",data:Ke,threadId:r,traceId:n,sessionId:o};break;case "message_stop":{if(a.debug("Anthropic stream: message_stop. Using accumulated data.",{threadId:r,traceId:n}),C==="tool_use"&&M.length>0){let K=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE",je=M.map(Oe=>({type:"tool_use",id:Oe.id,name:Oe.name,input:Oe.input}));E.trim()?yield {type:"TOKEN",data:[{type:"text",text:E.trim()},...je],threadId:r,traceId:n,sessionId:o,tokenType:K}:yield {type:"TOKEN",data:je,threadId:r,traceId:n,sessionId:o,tokenType:K};}else if(E.trim()){let K=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:E.trim(),threadId:r,traceId:n,sessionId:o,tokenType:K};}yield {type:"METADATA",data:{inputTokens:L.input_tokens??void 0,outputTokens:L.output_tokens??void 0,stopReason:C??void 0,providerRawUsage:{usage:{input_tokens:L.input_tokens??void 0,output_tokens:L.output_tokens??void 0},stop_reason:C},traceId:n},threadId:r,traceId:n,sessionId:o};break}default:{a.warn("Anthropic stream: unhandled raw stream event type",{eventType:N.type,event:N,threadId:r,traceId:n});break}}}else {let S=await this.client.messages.create(P,this.getRequestOptions(T));a.debug(`Anthropic API call successful (non-streaming). Stop Reason: ${S.stop_reason}`,{threadId:r,traceId:n});let E="",M=[];S.content.forEach(_=>{_.type==="text"?E+=_.text:_.type==="tool_use"&&M.push(_);}),E=E.trim();let k=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";if(S.stop_reason==="tool_use"&&M.length>0){let _=M.map(C=>({type:"tool_use",id:C.id,name:C.name,input:C.input}));E?yield {type:"TOKEN",data:[{type:"text",text:E},..._],threadId:r,traceId:n,sessionId:o,tokenType:k}:yield {type:"TOKEN",data:_,threadId:r,traceId:n,sessionId:o,tokenType:k};}else E?yield {type:"TOKEN",data:E,threadId:r,traceId:n,sessionId:o,tokenType:k}:S.stop_reason!=="tool_use"&&a.warn("Anthropic API (non-streaming): Empty response text and not a tool_use stop_reason.",{response:S,threadId:r,traceId:n});S.usage&&(yield {type:"METADATA",data:{inputTokens:S.usage.input_tokens,outputTokens:S.usage.output_tokens,stopReason:S.stop_reason??void 0,providerRawUsage:{usage:S.usage,stop_reason:S.stop_reason,stop_sequence:S.stop_sequence},traceId:n},threadId:r,traceId:n,sessionId:o});}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(S){a.error(`Error during Anthropic API call: ${S.message}`,{error:S,threadId:r,traceId:n}),yield {type:"ERROR",data:S instanceof c?S:S instanceof Anthropic.APIError?new c(`Anthropic API Error (${S.status}): ${S.message}`,"LLM_PROVIDER_ERROR",S):new c(S.message||"Unknown Anthropic adapter error","LLM_PROVIDER_ERROR",S),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}}.bind(this)()}getRequestOptions(e){let t=[];return 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 d=typeof s.content=="string"?s.content:String(s.content);t?(a.warn("AnthropicAdapter: Multiple system messages found. Appending to existing system prompt."),t+=`
|
|
144
|
+
${d}`):t=d;continue}let i=this.mapArtMessageToAnthropicContent(s),l=s.role==="user"||s.role==="tool_result"?"user":"assistant";if(n===l&&r.length>0){let d=r[r.length-1],g;typeof d.content=="string"?g=[{type:"text",text:d.content}]:g=d.content;let T=typeof i=="string"?[{type:"text",text:i}]:i,y=[...g,...T];d.content=y,a.debug(`AnthropicAdapter: Merged consecutive ${l} messages.`);}else r.push({role:l,content:i}),n=l;}!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 c(`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 c("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 c(`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 Ue=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:l}=t,d=l||this.model;if(s)return a.warn("OpenRouterAdapter: Streaming requested but not implemented. Returning error stream.",{threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new c("Streaming is not yet implemented for the OpenRouterAdapter.","LLM_PROVIDER_ERROR"),threadId:r??"",traceId:n??"",sessionId:o},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:o};}();let g;try{g=this.translateToOpenAI(e);}catch(p){return a.error(`Error translating ArtStandardPrompt to OpenRouter/OpenAI format: ${p.message}`,{error:p,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:p instanceof c?p:new c(`Prompt translation failed: ${p.message}`,"PROMPT_TRANSLATION_FAILED",p),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let T=`${this.apiBaseUrl}/chat/completions`,y=t.stop||t.stop_sequences||t.stopSequences,u={model:d,messages:g,temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,stop:y,stream:false};Object.keys(u).forEach(p=>u[p]===void 0&&delete u[p]);let m={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return this.siteUrl&&(m["HTTP-Referer"]=this.siteUrl),this.appName&&(m["X-Title"]=this.appName),a.debug(`Calling OpenRouter API (non-streaming): ${T} with model ${this.model}`,{threadId:r,traceId:n}),async function*(){try{let p=await fetch(T,{method:"POST",headers:m,body:JSON.stringify(u)});if(!p.ok){let S=await p.text(),E=S;try{let k=JSON.parse(S);k?.error?.message&&(E=k.error.message);}catch{}yield {type:"ERROR",data:new c(`OpenRouter API request failed: ${p.status} ${p.statusText} - ${E}`,"LLM_PROVIDER_ERROR",new Error(S)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let f=await p.json(),A=f.choices?.[0];if(!A?.message){yield {type:"ERROR",data:new c("Invalid response structure from OpenRouter API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(f))),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let R=A.message;R.tool_calls&&a.debug("OpenRouter response included tool calls (non-streaming)",{toolCalls:R.tool_calls,threadId:r,traceId:n}),a.debug(`OpenRouter API call successful. Finish reason: ${A.finish_reason}`,{threadId:r,traceId:n});let O=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(R.content??"").trim(),threadId:r,traceId:n,sessionId:o,tokenType:O},yield {type:"METADATA",data:{inputTokens:f.usage?.prompt_tokens,outputTokens:f.usage?.completion_tokens,stopReason:A.finish_reason,providerRawUsage:{usage:f.usage,finish_reason:A.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(p){a.error(`Error during OpenRouter API call: ${p.message}`,{error:p,threadId:r,traceId:n}),yield {type:"ERROR",data:p instanceof c?p:new c(p.message,"LLM_PROVIDER_ERROR",p),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("OpenRouterAdapter: 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("OpenRouterAdapter: 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 c(`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.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 c("OpenRouterAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return typeof t.content!="string"&&a.warn("OpenRouterAdapter: 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 c("OpenRouterAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new c(`OpenRouterAdapter: Unknown message role '${t.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var Fe=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:l}=t,d=l||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 c("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 g;try{g=this.translateToOpenAI(e);}catch(p){return a.error(`Error translating ArtStandardPrompt to DeepSeek/OpenAI format: ${p.message}`,{error:p,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:p instanceof c?p:new c(`Prompt translation failed: ${p.message}`,"PROMPT_TRANSLATION_FAILED",p),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let T=`${this.apiBaseUrl}/chat/completions`,y=t.stop||t.stop_sequences||t.stopSequences,u={model:d,messages:g,temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,stop:y,stream:false};Object.keys(u).forEach(p=>u[p]===void 0&&delete u[p]);let m={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return a.debug(`Calling DeepSeek API (non-streaming): ${T} with model ${this.model}`,{threadId:r,traceId:n}),async function*(){try{let p=await fetch(T,{method:"POST",headers:m,body:JSON.stringify(u)});if(!p.ok){let S=await p.text(),E=S;try{let k=JSON.parse(S);k?.error?.message&&(E=k.error.message);}catch{}yield {type:"ERROR",data:new c(`DeepSeek API request failed: ${p.status} ${p.statusText} - ${E}`,"LLM_PROVIDER_ERROR",new Error(S)),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let f=await p.json(),A=f.choices?.[0];if(!A?.message){yield {type:"ERROR",data:new c("Invalid response structure from DeepSeek API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(f))),threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};return}let R=A.message;R.tool_calls&&a.debug("DeepSeek response included tool calls (non-streaming)",{toolCalls:R.tool_calls,threadId:r,traceId:n}),a.debug(`DeepSeek API call successful. Finish reason: ${A.finish_reason}`,{threadId:r,traceId:n});let O=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(R.content??"").trim(),threadId:r,traceId:n,sessionId:o,tokenType:O},yield {type:"METADATA",data:{inputTokens:f.usage?.prompt_tokens,outputTokens:f.usage?.completion_tokens,stopReason:A.finish_reason,providerRawUsage:{usage:f.usage,finish_reason:A.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}catch(p){a.error(`Error during DeepSeek API call: ${p.message}`,{error:p,threadId:r,traceId:n}),yield {type:"ERROR",data:p instanceof c?p:new c(p.message,"LLM_PROVIDER_ERROR",p),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 c(`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 c("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 c("DeepSeekAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new c(`DeepSeekAdapter: Unknown message role '${t.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var Ge=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 Ot({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:l,tools:d,providerConfig:g}=t,T=g?.modelId||l||this.defaultModel;if(!T){let p=new c("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:p,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let y;try{y=this.translateToOpenAI(e,T);}catch(p){a.error(`Error translating ArtStandardPrompt to OpenAI format for Ollama: ${p.message}`,{error:p,threadId:r,traceId:n});let f=p instanceof c?p:new c(`Prompt translation failed: ${p.message}`,"PROMPT_TRANSLATION_FAILED",p);return async function*(){yield {type:"ERROR",data:f,threadId:r,traceId:n,sessionId:o},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:o};}()}let u=d?this.translateArtToolsToOpenAI(d):void 0,m={model:T,messages:y,temperature:t.temperature??g?.adapterOptions?.temperature,max_tokens:t.max_tokens??t.maxOutputTokens??g?.adapterOptions?.max_tokens,top_p:t.top_p??t.topP??g?.adapterOptions?.top_p,stop:(t.stop||t.stop_sequences||t.stopSequences)??g?.adapterOptions?.stop,stream:s,tools:u,tool_choice:t.tool_choice??g?.adapterOptions?.tool_choice};return Object.keys(m).forEach(p=>{let f=p;m[f]===void 0&&delete m[f];}),a.debug(`Calling Ollama API (via OpenAI client) with model ${T}`,{stream:s,tools:!!u,threadId:r,traceId:n}),async function*(){let p=Date.now(),f,A=0,R,O;try{if(s){let S=await this.client.chat.completions.create(m),E=[];for await(let M of S){f||(f=Date.now()-p);let k=M.choices[0]?.delta;if(O=M.choices[0]?.finish_reason??O,k?.content){A++;let _=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:k.content,threadId:r,traceId:n,sessionId:o,tokenType:_};}k?.tool_calls&&k.tool_calls.forEach(_=>{_.index!==void 0&&(E[_.index]?(_.id&&(E[_.index].id=_.id),_.function?.name&&(E[_.index].function.name=_.function.name),_.function?.arguments&&(E[_.index].function||(E[_.index].function={name:"",arguments:""}),E[_.index].function.arguments+=_.function.arguments)):E[_.index]={id:_.id||"",type:"function",function:{name:_.function?.name||"",arguments:_.function?.arguments||""}});}),M.usage&&(R=M.usage);}if(O==="tool_calls"&&E.length>0){let M=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:E.map(_=>({type:"tool_use",id:_.id,name:_.function.name,input:JSON.parse(_.function.arguments||"{}")})),threadId:r,traceId:n,sessionId:o,tokenType:M};}}else {let S=await this.client.chat.completions.create(m),E=S.choices[0];if(!E||!E.message)throw new c("Invalid response structure from Ollama API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(S)));O=E.finish_reason??void 0,R=S.usage;let M=E.message,k=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";if(M.tool_calls&&M.tool_calls.length>0){let _=M.tool_calls.map(C=>({type:"tool_use",id:C.id,name:C.function.name,input:JSON.parse(C.function.arguments||"{}")}));M.content?yield {type:"TOKEN",data:[{type:"text",text:M.content.trim()},..._],threadId:r,traceId:n,sessionId:o,tokenType:k}:yield {type:"TOKEN",data:_,threadId:r,traceId:n,sessionId:o,tokenType:k};}else M.content&&(yield {type:"TOKEN",data:M.content.trim(),threadId:r,traceId:n,sessionId:o,tokenType:k});}let P=Date.now()-p;yield {type:"METADATA",data:{stopReason:O,inputTokens:R?.prompt_tokens,outputTokens:R?.completion_tokens??(s?A:void 0),timeToFirstTokenMs:s?f:void 0,totalGenerationTimeMs:P,providerRawUsage:{usage:R,finish_reason:O},traceId:n},threadId:r,traceId:n,sessionId:o};}catch(P){a.error(`Error during Ollama API call: ${P.message}`,{error:P,threadId:r,traceId:n}),yield {type:"ERROR",data:P instanceof c?P:P.constructor.name==="APIError"?new c(`Ollama API Error (${P.status}): ${P.message}`,"LLM_PROVIDER_ERROR",P):new c(P.message||"Unknown Ollama adapter error","LLM_PROVIDER_ERROR",P),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 l="user";i.role==="system"?l="system":i.role==="user"?l="user":i.role==="assistant"?l="assistant":i.role==="tool_result"&&(l="tool");let d=this.mapArtMessageToOpenAIMessage(i);if(s&&s.role===l&&l!=="system"&&l!=="tool"){let g="";typeof s.content=="string"&&typeof d.content=="string"?g=`${s.content}
|
|
145
|
+
${d.content}`:typeof s.content=="string"?g=`${s.content}
|
|
146
|
+
${d.content===null?"":String(d.content)}`:typeof d.content=="string"?g=`${s.content===null?"":String(s.content)}
|
|
147
|
+
${d.content}`:g=`${s.content===null?"":String(s.content)}
|
|
148
|
+
${d.content===null?"":String(d.content)}`,s.content=g.trim()||null,s.role==="assistant"&&d.role==="assistant"&&d.tool_calls&&(s.tool_calls=[...s.tool_calls||[],...d.tool_calls]),s.role==="assistant"&&!s.content&&s.tool_calls&&s.tool_calls.length>0&&(s.content=null);}else s=d,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 c(`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 c("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 c("OllamaAdapter: Unexpected 'tool_request' role during mapping. This should be handled via assistant's tool_calls.","PROMPT_TRANSLATION_FAILED");default:throw new c(`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 c(`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 Mt={sqrt:I.sqrt,cbrt:I.cbrt,abs:I.abs,pow:I.pow,exp:I.exp,log:I.log,log10:I.log10,log2:I.log2,sin:I.sin,cos:I.cos,tan:I.tan,asin:I.asin,acos:I.acos,atan:I.atan,atan2:I.atan2,round:I.round,floor:I.floor,ceil:I.ceil,mod:I.mod,mean:I.mean,median:I.median,std:I.std,variance:I.variance,max:I.max,min:I.min,factorial:I.factorial,gamma:I.gamma,combinations:I.combinations,permutations:I.permutations,format:I.format},we=class we{constructor(){this.resultStore=new Map;this.schema={name:we.toolName,description:`Evaluates mathematical expressions using a sandboxed mathjs environment.
|
|
130
149
|
You can reference previous calculation results using the 'ans' variable.
|
|
131
150
|
Supports standard operators (+, -, *, /, %, ^), variables via 'scope', complex numbers, and the following allowed functions:
|
|
132
151
|
sqrt, cbrt, abs, pow, exp, log, log10, log2, sin, cos, tan, asin, acos, atan, atan2, round, floor, ceil, mod,
|
|
133
|
-
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={...Mt,...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 l=evaluate(r,s),
|
|
134
|
-
export{We as A2ATaskPriority,W as A2ATaskSocket,ie as A2ATaskStatus,c as ARTError,z as AdapterInstantiationError,ae as AgentDiscoveryService,De as AnthropicAdapter,be as ApiQueueTimeoutError,Je as ArtStandardMessageSchema,Me as ArtStandardPromptSchema,re as AuthManager,qe as CalculatorTool,te as ConversationSocket,Fe as DeepSeekAdapter,
|
|
152
|
+
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={...Mt,...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 l=evaluate(r,s),d;if(typeof l=="number"&&Number.isFinite(l))d=l;else if(I.isComplex(l))d=l.toString();else throw new Error(`Evaluation resulted in an unsupported type: ${I.typeOf(l)}`);return this.resultStore.set(n,l),a.info(`CalculatorTool evaluated "${r}" to ${d}`,{callId:i}),{callId:i,toolName:this.schema.name,status:"success",output:{result:d}}}catch(l){return a.error(`CalculatorTool failed to evaluate expression "${r}": ${l.message}`,{callId:i,error:l}),{callId:i,toolName:this.schema.name,status:"error",error:`Failed to evaluate expression: ${l.message}`}}}};we.toolName="calculator";var qe=we;var Be=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 c("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 c("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 c("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 c(`OAuth error on redirect: ${n} - ${o||"No description provided."}`,"EXTERNAL_SERVICE_ERROR")}let r=sessionStorage.getItem("pkce_code_verifier");if(!r)throw new c("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 c(`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 c("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 c("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 c("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 c(`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 c("An unexpected error occurred during the token refresh process.","UNKNOWN_ERROR",e)}}async exchangeCodeForToken(e){if(!this.codeVerifierForPendingLogin)throw new c("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 c(`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 io="0.2.8";
|
|
153
|
+
export{We as A2ATaskPriority,W as A2ATaskSocket,ie as A2ATaskStatus,c as ARTError,z as AdapterInstantiationError,ae as AgentDiscoveryService,De as AnthropicAdapter,be as ApiQueueTimeoutError,Je as ArtStandardMessageSchema,Me as ArtStandardPromptSchema,re as AuthManager,qe as CalculatorTool,te as ConversationSocket,Fe as DeepSeekAdapter,x as ErrorCode,$e as GeminiAdapter,Q as InMemoryStorageAdapter,Z as IndexedDBStorageAdapter,Y as LLMStreamSocket,J as LocalInstanceBusyError,V as LocalProviderConflictError,Ve as LogLevel,a as Logger,B as McpClientController,H as McpManager,G as McpProxyTool,ze as MessageRole,Ye as ModelCapability,ee as ObservationSocket,Ce as ObservationType,Ge as OllamaAdapter,Le as OpenAIAdapter,Ue as OpenRouterAdapter,X as PESAgent,Be as PKCEOAuthStrategy,xe as SupabaseStorageAdapter,oe as TaskDelegationService,U as TypedSocket,j as UnknownProviderError,io as VERSION,Rt as createArtInstance,q as generateUUID};//# sourceMappingURL=index.js.map
|
|
135
154
|
//# sourceMappingURL=index.js.map
|