art-framework 0.2.4 → 0.2.5

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 CHANGED
Binary file
package/dist/index.cjs CHANGED
@@ -1,47 +1,39 @@
1
- 'use strict';var uuid=require('uuid'),ge=require('ajv'),I=require('zod'),g=require('mathjs');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ge__default=/*#__PURE__*/_interopDefault(ge);var I__namespace=/*#__PURE__*/_interopNamespace(I);var g__namespace=/*#__PURE__*/_interopNamespace(g);var W=(o=>(o.USER="USER",o.AI="AI",o.SYSTEM="SYSTEM",o.TOOL="TOOL",o))(W||{}),Q=(p=>(p.INTENT="INTENT",p.PLAN="PLAN",p.THOUGHTS="THOUGHTS",p.TOOL_CALL="TOOL_CALL",p.TOOL_EXECUTION="TOOL_EXECUTION",p.SYNTHESIS="SYNTHESIS",p.ERROR="ERROR",p.FINAL_RESPONSE="FINAL_RESPONSE",p.STATE_UPDATE="STATE_UPDATE",p))(Q||{});var S=()=>uuid.v4();var y=class c extends Error{code;originalError;constructor(e,t,r){super(e),this.name="ARTError",this.code=t,this.originalError=r,Error.captureStackTrace&&Error.captureStackTrace(this,c);}toString(){let e=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(e+=`
2
- Caused by: ${this.originalError.stack||this.originalError.toString()}`),e}};var A=class{deps;constructor(e){this.deps=e;}async process(e){let t=Date.now(),r=e.traceId??S(),o="success",a,i=0,n=0,l;try{console.log(`[${r}] Stage 1: Initiation & Config`);let d=await this.deps.stateManager.loadThreadContext(e.threadId,e.userId);if(!d)throw new y(`Thread context not found for threadId: ${e.threadId}`,"THREAD_NOT_FOUND");let u=d.config.systemPrompt;console.log(`[${r}] Stage 2: Planning Context`);let M={limit:d.config.historyLimit},T=await this.deps.conversationManager.getMessages(e.threadId,M),v=await this.deps.toolRegistry.getAvailableTools({enabledForThreadId:e.threadId});console.log(`[${r}] Stage 3: Planning Call`);let N=await this.deps.promptManager.createPlanningPrompt(e.query,T,u,v,d),se={threadId:e.threadId,traceId:r,userId:e.userId,onThought:h=>{this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"THOUGHTS",content:{phase:"planning",thought:h},metadata:{timestamp:Date.now()}}).catch(b=>console.error(`[${r}] Failed to record planning thought observation:`,b));},...d.config.reasoning.parameters??{},...e.options?.llmParams??{}},Y,f={};try{i++,Y=await this.deps.reasoningEngine.call(N,se),f=await this.deps.outputParser.parsePlanningOutput(Y),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"INTENT",content:{intent:f.intent},metadata:{timestamp:Date.now()}}),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"PLAN",content:{plan:f.plan,rawOutput:Y},metadata:{timestamp:Date.now()}}),f.toolCalls&&f.toolCalls.length>0&&await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"TOOL_CALL",content:{toolCalls:f.toolCalls},metadata:{timestamp:Date.now()}});}catch(h){throw o="error",a=`Planning phase failed: ${h.message}`,console.error(`[${r}] Planning Error:`,h),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"ERROR",content:{phase:"planning",error:h.message,stack:h.stack},metadata:{timestamp:Date.now()}}),new y(a,"PLANNING_FAILED",h)}let k=[];if(f.toolCalls&&f.toolCalls.length>0){console.log(`[${r}] Stage 4: Tool Execution (${f.toolCalls.length} calls)`);try{k=await this.deps.toolSystem.executeTools(f.toolCalls,e.threadId,r),n=k.length,k.some(h=>h.status==="error")&&(o="partial",console.warn(`[${r}] Partial success in tool execution.`),a=a?`${a}; Tool execution errors occurred.`:"Tool execution errors occurred.");}catch(h){throw o="error",a=`Tool execution phase failed: ${h.message}`,console.error(`[${r}] Tool Execution System Error:`,h),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"ERROR",content:{phase:"tool_execution",error:h.message,stack:h.stack},metadata:{timestamp:Date.now()}}),new y(a,"TOOL_EXECUTION_FAILED",h)}}else console.log(`[${r}] Stage 4: Tool Execution (No tool calls)`);console.log(`[${r}] Stage 5: Synthesis Call`);let ie=await this.deps.promptManager.createSynthesisPrompt(e.query,f.intent,f.plan,k,T,u,d),le={threadId:e.threadId,traceId:r,userId:e.userId,onThought:h=>{this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"THOUGHTS",content:{phase:"synthesis",thought:h},metadata:{timestamp:Date.now()}}).catch(b=>console.error(`[${r}] Failed to record synthesis thought observation:`,b));},...d.config.reasoning.parameters??{},...e.options?.llmParams??{}},X;try{i++;let h=await this.deps.reasoningEngine.call(ie,le);await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"SYNTHESIS",content:{rawOutput:h},metadata:{timestamp:Date.now()}}),X=await this.deps.outputParser.parseSynthesisOutput(h);}catch(h){o=o==="partial"?"partial":"error";let b=`Synthesis phase failed: ${h.message}`;if(a=a?`${a}; ${b}`:b,console.error(`[${r}] Synthesis Error:`,h),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"ERROR",content:{phase:"synthesis",error:h.message,stack:h.stack},metadata:{timestamp:Date.now()}}),o!=="partial")throw new y(b,"SYNTHESIS_FAILED",h);X=a;}console.log(`[${r}] Stage 6: Finalization`);let re=Date.now();l={messageId:S(),threadId:e.threadId,role:"AI",content:X,timestamp:re,metadata:{traceId:r}},await this.deps.conversationManager.addMessages(e.threadId,[l]),await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"FINAL_RESPONSE",content:{message:l},metadata:{timestamp:re}}),await this.deps.stateManager.saveStateIfModified(e.threadId);}catch(d){console.error(`[${r}] PESAgent process error:`,d),o=o==="partial"?"partial":"error",a=a??(d instanceof y?d.message:"An unexpected error occurred."),o==="error"&&(l=void 0),d instanceof y&&(d.code==="PLANNING_FAILED"||d.code==="TOOL_EXECUTION_FAILED"||d.code==="SYNTHESIS_FAILED")||await this.deps.observationManager.record({threadId:e.threadId,traceId:r,type:"ERROR",content:{phase:"agent_process",error:d.message,stack:d.stack},metadata:{timestamp:Date.now()}}).catch(u=>console.error(`[${r}] Failed to record top-level error observation:`,u));}finally{try{await this.deps.stateManager.saveStateIfModified(e.threadId);}catch(d){console.error(`[${r}] Failed to save state during finalization:`,d);}}let p=Date.now(),m={threadId:e.threadId,traceId:r,userId:e.userId,status:o,totalDurationMs:p-t,llmCalls:i,toolCalls:n,error:a};if(!l&&o!=="success")l={messageId:S(),threadId:e.threadId,role:"AI",content:a??"Agent execution failed.",timestamp:Date.now(),metadata:{traceId:r,error:true}};else if(!l)throw new y("Agent finished with success status but no final message was generated.","UNKNOWN_ERROR");return {response:l,metadata:m}}};var x=class{storage=new Map;async init(e){return Promise.resolve()}async get(e,t){let r=this.storage.get(e);if(!r)return null;let o=r.get(t);return o?JSON.parse(JSON.stringify(o)):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 o=Array.from(r.values());return t.filter&&(o=o.filter(a=>{for(let i in t.filter)if(t.filter.hasOwnProperty(i)&&a[i]!==t.filter[i])return false;return true})),typeof t.limit=="number"&&t.limit>=0&&(o=o.slice(0,t.limit)),JSON.parse(JSON.stringify(o))}async clearCollection(e){return this.storage.delete(e),Promise.resolve()}async clearAll(){return this.storage.clear(),Promise.resolve()}};var ce="ART_Framework_DB",pe=1,w=class{db=null;dbName;dbVersion;requiredObjectStores;initPromise=null;constructor(e){this.dbName=e.dbName||ce,this.dbVersion=e.dbVersion||pe,this.requiredObjectStores=new Set(["conversations","observations","state",...e.objectStores]);}async init(){return this.initPromise?this.initPromise:(this.initPromise=new Promise((e,t)=>{if(!("indexedDB"in window))return console.error("IndexedDBStorageAdapter: IndexedDB not supported in this browser."),t(new Error("IndexedDB not supported"));let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=o=>{console.error(`IndexedDBStorageAdapter: Database error: ${r.error}`,o),t(new Error(`IndexedDB error: ${r.error?.message}`));},r.onsuccess=o=>{this.db=o.target.result,console.log(`IndexedDBStorageAdapter: Database '${this.dbName}' opened successfully (Version: ${this.db.version}).`);let a=new Set(Array.from(this.db.objectStoreNames)),i=[...this.requiredObjectStores].filter(n=>!a.has(n));i.length>0&&console.warn(`IndexedDBStorageAdapter: The following required object stores were not found after opening DB version ${this.db.version}: ${i.join(", ")}. This might happen if the DB version wasn't incremented after adding stores.`),this.db.onerror=n=>{console.error("IndexedDBStorageAdapter: Generic database error:",n);},e();},r.onupgradeneeded=o=>{if(console.log(`IndexedDBStorageAdapter: Upgrading database '${this.dbName}' from version ${o.oldVersion} to ${o.newVersion}...`),this.db=o.target.result,!o.target.transaction){console.error("IndexedDBStorageAdapter: Upgrade transaction is null!"),t(new Error("Upgrade transaction failed"));return}let i=new Set(Array.from(this.db.objectStoreNames));this.requiredObjectStores.forEach(n=>{i.has(n)||(console.log(`IndexedDBStorageAdapter: Creating object store '${n}'...`),this.db?.createObjectStore(n,{keyPath:"id"}));}),console.log("IndexedDBStorageAdapter: Database upgrade complete.");},r.onblocked=o=>{console.warn(`IndexedDBStorageAdapter: Database open request blocked for '${this.dbName}'. Please close other tabs/connections using an older version of this database.`,o),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. Call init() first.");return (Array.isArray(e)?e:[e]).forEach(o=>{if(!this.db?.objectStoreNames.contains(o))throw new Error(`IndexedDBStorageAdapter: Object store "${o}" does not exist in the database.`)}),this.db.transaction(e,t)}async get(e,t){return await this.init(),new Promise((r,o)=>{try{let n=this.getTransaction(e,"readonly").objectStore(e).get(t);n.onsuccess=()=>{r(n.result?{...n.result}:null);},n.onerror=()=>{console.error(`IndexedDBStorageAdapter: Error getting item '${t}' from '${e}':`,n.error),o(new Error(`Failed to get item: ${n.error?.message}`));};}catch(a){o(a);}})}async set(e,t,r){let o=r;return typeof o.id>"u"?Promise.reject(new Error(`IndexedDBStorageAdapter: Data for collection '${e}' must have an 'id' property matching the keyPath.`)):(o.id!==t&&console.warn(`IndexedDBStorageAdapter: Provided id ('${t}') and data.id ('${o.id}') mismatch for collection '${e}'. Using data.id as the key.`),await this.init(),new Promise((a,i)=>{try{let n=structuredClone(r),l=this.getTransaction(e,"readwrite"),m=l.objectStore(e).put(n);m.onsuccess=()=>{a();},m.onerror=()=>{console.error(`IndexedDBStorageAdapter: Error setting item with id '${o.id}' in '${e}':`,m.error),i(new Error(`Failed to set item: ${m.error?.message}`));},l.oncomplete=()=>{},l.onerror=d=>{console.error(`IndexedDBStorageAdapter: Transaction error setting item with id '${o.id}' in '${e}':`,l.error,d),i(new Error(`Transaction failed: ${l.error?.message}`));};}catch(n){i(n);}}))}async delete(e,t){return await this.init(),new Promise((r,o)=>{try{let a=this.getTransaction(e,"readwrite"),n=a.objectStore(e).delete(t);n.onsuccess=()=>{r();},n.onerror=()=>{console.error(`IndexedDBStorageAdapter: Error deleting item '${t}' from '${e}':`,n.error),o(new Error(`Failed to delete item: ${n.error?.message}`));},a.onerror=l=>{console.error(`IndexedDBStorageAdapter: Transaction error deleting item '${t}' from '${e}':`,a.error,l),o(new Error(`Transaction failed: ${a.error?.message}`));};}catch(a){o(a);}})}async query(e,t){return await this.init(),new Promise((r,o)=>{try{let n=this.getTransaction(e,"readonly").objectStore(e).getAll();n.onsuccess=()=>{let l=n.result||[];if(t.filter&&(l=l.filter(d=>{for(let u in t.filter)if(t.filter.hasOwnProperty(u)&&d[u]!==t.filter[u])return !1;return !0})),t.sort){let d=Object.keys(t.sort)[0],u=t.sort[d];d&&l.sort((M,T)=>{let v=M[d],N=T[d];return v<N?u==="asc"?-1:1:v>N?u==="asc"?1:-1:0});}let p=t.skip||0,m=t.limit??1/0;l=l.slice(p,p+m),r(l.map(d=>({...d})));},n.onerror=()=>{console.error(`IndexedDBStorageAdapter: Error querying collection '${e}':`,n.error),o(new Error(`Failed to query collection: ${n.error?.message}`));};}catch(a){o(a);}})}async clearCollection(e){return await this.init(),new Promise((t,r)=>{try{let o=this.getTransaction(e,"readwrite"),i=o.objectStore(e).clear();i.onsuccess=()=>{t();},i.onerror=()=>{console.error(`IndexedDBStorageAdapter: Error clearing collection '${e}':`,i.error),r(new Error(`Failed to clear collection: ${i.error?.message}`));},o.onerror=n=>{console.error(`IndexedDBStorageAdapter: Transaction error clearing collection '${e}':`,o.error,n),r(new Error(`Transaction failed: ${o.error?.message}`));};}catch(o){r(o);}})}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 o=this.getTransaction(e,"readwrite"),a=0,i=e.length;e.forEach(n=>{let l=o.objectStore(n).clear();l.onsuccess=()=>{a++;},l.onerror=()=>{console.error(`IndexedDBStorageAdapter: Error clearing object store '${n}':`,l.error);};}),o.oncomplete=()=>{console.log("IndexedDBStorageAdapter: All object stores cleared successfully."),t();},o.onerror=n=>{console.error("IndexedDBStorageAdapter: Transaction error during clearAll:",o.error,n),r(new Error(`Failed to clear all stores: ${o.error?.message}`));};}catch(o){r(o);}})}};var D=class{adapter;collectionName="conversations";constructor(e){this.adapter=e;}async addMessages(e,t){if(!t||t.length===0)return Promise.resolve();let r=t.map(o=>{o.threadId!==e&&console.warn(`ConversationRepository: Message ${o.messageId} has mismatching threadId (${o.threadId}) for repository operation on thread ${e}.`);let a={...o,id:o.messageId};return this.adapter.set(this.collectionName,a.id,a)});await Promise.all(r);}async getMessages(e,t){let o=await this.adapter.query(this.collectionName,{filter:{threadId:e}});return o.sort((i,n)=>i.timestamp-n.timestamp),t?.beforeTimestamp!==void 0&&(o=o.filter(i=>i.timestamp<t.beforeTimestamp)),t?.afterTimestamp!==void 0&&(o=o.filter(i=>i.timestamp>t.afterTimestamp)),t?.limit!==void 0&&t.limit>0&&(o=o.slice(-t.limit)),o.map(({id:i,...n})=>n)}};var _=class{adapter;collectionName="observations";constructor(e){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 o=await this.adapter.query(this.collectionName,{filter:{threadId:e}});if(o.sort((a,i)=>a.timestamp-i.timestamp),t?.types&&t.types.length>0){let a=new Set(t.types);o=o.filter(i=>a.has(i.type));}return t?.beforeTimestamp!==void 0&&(o=o.filter(a=>a.timestamp<t.beforeTimestamp)),t?.afterTimestamp!==void 0&&(o=o.filter(a=>a.timestamp>t.afterTimestamp)),o}};var F=class{adapter;collectionName="state";constructor(e){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),o={config:t,state:r?.state??null};await this.setThreadContext(e,o);}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 o={config:r.config,state:t};await this.setThreadContext(e,o);}};var U=class{repository;conversationSocket;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.notifyMessage(r);}catch(o){console.error(`ConversationManager: Failed to notify message ${r.messageId} via socket`,o);}});}async getMessages(e,t){return e?await this.repository.getMessages(e,t):Promise.reject(new Error("ConversationManager: threadId cannot be empty."))}};var B=class{repository;constructor(e){this.repository=e;}async loadThreadContext(e,t){if(!e)throw new Error("StateManager: threadId cannot be empty.");let r=await this.repository.getThreadContext(e);if(!r)throw new Error(`StateManager: Thread context not found for threadId '${e}'.`);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){return e?(console.warn(`StateManager: saveStateIfModified called for thread ${e}, but state modification tracking/saving is not implemented in this version. State must be saved explicitly via repository methods.`),Promise.resolve()):Promise.reject(new Error("StateManager: threadId cannot be empty for saveStateIfModified."))}async setThreadConfig(e,t){if(!e||!t)throw new Error("StateManager: threadId and config are required for setThreadConfig.");await this.repository.setThreadConfig(e,t);}};var L=class{observationRepository;observationSocket;constructor(e,t){this.observationRepository=e,this.observationSocket=t;}async record(e){let t={...e,id:S(),timestamp:Date.now(),title:`${e.type} Recorded`};try{await this.observationRepository.addObservation(t),this.observationSocket.notifyObservation(t);}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 oe=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o))(oe||{}),s=class c{static config={level:1};static configure(e){c.config={...c.config,...e};}static debug(e,...t){c.config.level<=0&&console.debug(`${c.config.prefix||"[ART]"} ${e}`,...t);}static info(e,...t){c.config.level<=1&&console.info(`${c.config.prefix||"[ART]"} ${e}`,...t);}static warn(e,...t){c.config.level<=2&&console.warn(`${c.config.prefix||"[ART]"} ${e}`,...t);}static error(e,...t){c.config.level<=3&&console.error(`${c.config.prefix||"[ART]"} ${e}`,...t);}};var q=class{executors=new Map;async registerTool(e){if(!e||!e.schema||!e.schema.name)throw s.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)&&s.warn(`ToolRegistry: Overwriting existing tool registration for "${t}".`),this.executors.set(t,e),s.debug(`ToolRegistry: Registered tool "${t}".`);}async getToolExecutor(e){let t=this.executors.get(e);return t||s.debug(`ToolRegistry: Tool "${e}" not found.`),t}async getAvailableTools(e){e?.enabledForThreadId&&s.warn("ToolRegistry: Filtering by enabledForThreadId is not implemented in the basic ToolRegistry. Returning all tools.");let t=Array.from(this.executors.values()).map(r=>r.schema);return s.debug(`ToolRegistry: Returning ${t.length} available tool schemas.`),t}async clearAllTools(){this.executors.clear(),s.debug("ToolRegistry: Cleared all registered tools.");}};var me=new ge__default.default({allErrors:true}),Z=new Map;function ae(c,e){let t=JSON.stringify(c),r;if(Z.has(t))r=Z.get(t),s.debug("Using cached JSON schema validator.");else try{r=me.compile(c),Z.set(t,r),s.debug("Compiled and cached new JSON schema validator.");}catch(a){return s.error(`Failed to compile JSON schema: ${a.message}`,{schema:c,error:a}),{isValid:false,errors:[{keyword:"compilation",instancePath:"",schemaPath:"",params:{},message:`Schema compilation failed: ${a.message}`}]}}return r(e)?{isValid:true,errors:null}:(s.warn("JSON schema validation failed.",{errors:r.errors,data:e}),{isValid:false,errors:r.errors||[]})}var j=class{toolRegistry;stateManager;observationManager;constructor(e,t,r){if(!e)throw new Error("ToolSystem requires a ToolRegistry.");if(!t)throw new Error("ToolSystem requires a StateManager.");if(!r)throw new Error("ToolSystem requires an ObservationManager.");this.toolRegistry=e,this.stateManager=t,this.observationManager=r,s.info("ToolSystem initialized.");}async executeTools(e,t,r){let o=[];s.debug(`ToolSystem executing ${e.length} tool calls for thread ${t}`,{traceId:r});for(let a of e){let i=null,n,l=a.toolName,p=a.callId;try{if(!await this.stateManager.isToolEnabled(t,l))throw new Error(`Tool "${l}" is not enabled for thread "${t}".`);if(n=await this.toolRegistry.getToolExecutor(l),!n)throw new Error(`Tool "${l}" not found in registry.`);let d=ae(n.schema.inputSchema,a.arguments);if(!d.isValid){let T=d.errors?.map(v=>`${v.instancePath||"input"} ${v.message}`).join(", ")||"Unknown validation error";throw new Error(`Invalid arguments for tool "${l}": ${T}`)}s.debug(`Executing tool "${l}" with callId "${p}"`,{args:a.arguments,threadId:t,traceId:r});let u={threadId:t,traceId:r};i={...await n.execute(a.arguments,u),callId:p,toolName:l},s.debug(`Tool "${l}" execution successful`,{callId:p,result:i.output,threadId:t,traceId:r});}catch(m){s.error(`Tool "${l}" execution failed for callId "${p}": ${m.message}`,{error:m,threadId:t,traceId:r}),i={callId:p,toolName:l,status:"error",error:m.message||"Unknown execution error"};}i?(this.observationManager.record({threadId:t,traceId:r,type:"TOOL_EXECUTION",content:i,metadata:{timestamp:Date.now(),callId:a.callId}}).catch(m=>s.error(`Failed to record TOOL_EXECUTION observation for callId ${a.callId}:`,m)),o.push(i)):s.error(`ToolSystem finished processing call ${a.callId} but result object was null.`);}return o}};function ne(c,e){return c.replace(/\{\{(\w+)\}\}/g,(t,r)=>e[r]!==void 0?String(e[r]):t)}var K=class{defaultSystemPrompt="You are a helpful AI assistant. Respond concisely and accurately.";defaultPlanningPromptTemplate=`System Prompt:
3
- {{systemPrompt}}
4
-
5
- Conversation History:
6
- {{history}}
7
-
8
- User Query:
9
- {{query}}
1
+ 'use strict';var uuid=require('uuid'),Me=require('ajv'),k=require('zod'),genai=require('@google/genai'),m=require('mathjs');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Me__default=/*#__PURE__*/_interopDefault(Me);var k__namespace=/*#__PURE__*/_interopNamespace(k);var m__namespace=/*#__PURE__*/_interopNamespace(m);var d=class u extends Error{code;originalError;constructor(t,e,r){super(t),this.name="ARTError",this.code=e,this.originalError=r,Error.captureStackTrace&&Error.captureStackTrace(this,u);}toString(){let t=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(t+=`
2
+ Caused by: ${this.originalError.stack||this.originalError.toString()}`),t}},H=class extends d{constructor(t){super(`Unknown provider requested: ${t}`,"UNKNOWN_PROVIDER"),this.name="UnknownProviderError";}},j=class extends d{constructor(t,e){super(`Cannot activate local provider '${t}'. Local provider '${e}' is already active.`,"LOCAL_PROVIDER_CONFLICT"),this.name="LocalProviderConflictError";}},K=class extends d{constructor(t,e){super(`Local provider instance '${t}:${e}' is currently busy.`,"LOCAL_INSTANCE_BUSY"),this.name="LocalInstanceBusyError";}};var V=class extends d{constructor(t,e){super(`Failed to instantiate adapter for provider '${t}'.`,"ADAPTER_INSTANTIATION_ERROR",e),this.name="AdapterInstantiationError";}};var J=class{availableProviders;maxParallelApiInstancesPerProvider;apiInstanceIdleTimeoutMs;managedInstances;requestQueue;constructor(t){this.availableProviders=new Map(t.availableProviders.map(e=>[e.name,e])),this.maxParallelApiInstancesPerProvider=t.maxParallelApiInstancesPerProvider??5,this.apiInstanceIdleTimeoutMs=(t.apiInstanceIdleTimeoutSeconds??300)*1e3,this.managedInstances=new Map,this.requestQueue=[];}_getConfigSignature(t){let e=t.adapterOptions?Object.keys(t.adapterOptions).sort().reduce((r,n)=>(r[n]=t.adapterOptions[n],r),{}):{};return JSON.stringify({providerName:t.providerName,modelId:t.modelId,adapterOptions:e})}getAvailableProviders(){return Array.from(this.availableProviders.keys())}async getAdapter(t){let e=this._getConfigSignature(t),r=this.managedInstances.get(e);if(r&&r.state==="idle"){r.state="active",r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0),console.log(`Reusing idle instance for signature: ${e}`);let s=()=>this._releaseAdapter(e);return {adapter:r.adapter,release:s}}let n=this.availableProviders.get(t.providerName);if(!n)throw new H(t.providerName);if(n.isLocal){let s;for(let[c,g]of this.managedInstances.entries()){let y=this.availableProviders.get(g.configSignature.split('"providerName":"')[1].split('"')[0]);if(y?.isLocal){if(g.state==="active")throw c!==e?new j(t.providerName,y.name):new K(t.providerName,t.modelId);g.state==="idle"&&c!==e&&(s=g);}}s&&(console.log(`Evicting idle local instance with different signature: ${s.configSignature}`),await this._evictInstance(s.configSignature));}if(!n.isLocal&&Array.from(this.managedInstances.values()).filter(c=>{let g=this.availableProviders.get(c.configSignature.split('"providerName":"')[1].split('"')[0]);return g&&!g.isLocal&&c.state==="active"&&g.name===t.providerName}).length>=this.maxParallelApiInstancesPerProvider)return console.log(`API limit reached for ${t.providerName}. Queueing request.`),new Promise((c,g)=>{this.requestQueue.push({config:t,resolve:c,reject:g});});let a;try{a=new n.adapter(t.adapterOptions);}catch(s){throw new V(t.providerName,s)}let l={adapter:a,configSignature:e,state:"active"};this.managedInstances.set(e,l),console.log(`Created new instance for signature: ${e}`);let i=()=>this._releaseAdapter(e);return {adapter:l.adapter,release:i}}_releaseAdapter(t){console.log(`Release called for signature: ${t}`);let e=this.managedInstances.get(t);if(!e){console.warn(`Attempted to release unknown instance with signature: ${t}`);return}e.state="idle",e.lastUsedTimestamp=Date.now();let r=this.availableProviders.get(e.configSignature.split('"providerName":"')[1].split('"')[0]);if(r&&!r.isLocal&&(e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this._evictInstance(t);},this.apiInstanceIdleTimeoutMs)),this.requestQueue.length>0){let n=this.requestQueue.shift();n&&(console.log(`Dequeuing request for provider: ${n.config.providerName}`),this.getAdapter(n.config).then(n.resolve).catch(n.reject));}}async _evictInstance(t){console.log(`Attempting to evict instance with signature: ${t}`);let e=this.managedInstances.get(t);if(e&&e.state==="idle"){if(console.log(`Evicting idle instance with signature: ${t}`),e.adapter.shutdown)try{await e.adapter.shutdown(),console.log(`Adapter shutdown successful for ${t}`);}catch(r){console.error(`Error during adapter shutdown for ${t}:`,r);}this.managedInstances.delete(t),e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=void 0);}else e&&e.state==="active"?console.log(`Instance with signature ${t} is active, not evicting.`):console.log(`Instance with signature ${t} not found, cannot evict.`);}};var Ie=(n=>(n.USER="USER",n.AI="AI",n.SYSTEM="SYSTEM",n.TOOL="TOOL",n))(Ie||{}),ce=(f=>(f.INTENT="INTENT",f.PLAN="PLAN",f.THOUGHTS="THOUGHTS",f.TOOL_CALL="TOOL_CALL",f.TOOL_EXECUTION="TOOL_EXECUTION",f.SYNTHESIS="SYNTHESIS",f.ERROR="ERROR",f.FINAL_RESPONSE="FINAL_RESPONSE",f.STATE_UPDATE="STATE_UPDATE",f.LLM_STREAM_START="LLM_STREAM_START",f.LLM_STREAM_METADATA="LLM_STREAM_METADATA",f.LLM_STREAM_END="LLM_STREAM_END",f.LLM_STREAM_ERROR="LLM_STREAM_ERROR",f))(ce||{}),Se=(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))(Se||{});var F=()=>uuid.v4();var Te=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(Te||{}),o=class u{static config={level:1};static configure(t){u.config={...u.config,...t};}static debug(t,...e){u.config.level<=0&&console.debug(`${u.config.prefix||"[ART]"} ${t}`,...e);}static info(t,...e){u.config.level<=1&&console.info(`${u.config.prefix||"[ART]"} ${t}`,...e);}static warn(t,...e){u.config.level<=2&&console.warn(`${u.config.prefix||"[ART]"} ${t}`,...e);}static error(t,...e){u.config.level<=3&&console.error(`${u.config.prefix||"[ART]"} ${t}`,...e);}};var Oe="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.",q=class{deps;defaultSystemPrompt=Oe;constructor(t){this.deps=t;}async process(t){let e=Date.now(),r=t.traceId??F(),n="success",a,l=0,i=0,s,c;try{o.debug(`[${r}] Stage 1: Initiation & Config`);let A=await this.deps.stateManager.loadThreadContext(t.threadId,t.userId);if(!A)throw new d(`Thread context not found for threadId: ${t.threadId}`,"THREAD_NOT_FOUND");let f=await this.deps.stateManager.getThreadConfigValue(t.threadId,"systemPrompt")||this.defaultSystemPrompt,T=t.options?.providerConfig||A.config.providerConfig;if(!T)throw new d(`RuntimeProviderConfig is missing in AgentProps.options or ThreadConfig for threadId: ${t.threadId}`,"INVALID_CONFIG");o.debug(`[${r}] Stage 2: Planning Context Assembly`);let O={limit:A.config.historyLimit},p=await this.deps.conversationManager.getMessages(t.threadId,O),b=await this.deps.toolRegistry.getAvailableTools({enabledForThreadId:t.threadId}),h=this.formatHistoryForPrompt(p);o.debug(`[${r}] Stage 3: Planning Prompt Construction`);let I;try{I=[{role:"system",content:f},...h,{role:"user",content:`User Query: ${t.query}
10
3
 
11
4
  Available Tools:
12
- {{tools}}
5
+ ${b.length>0?b.map(S=>`- ${S.name}: ${S.description}
6
+ Input Schema: ${JSON.stringify(S.inputSchema)}`).join(`
7
+ `):"No tools available."}
13
8
 
14
9
  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.
15
10
  Respond in the following format:
16
11
  Intent: [Briefly describe the user's goal]
17
12
  Plan: [Provide a step-by-step plan. If tools are needed, list them clearly.]
18
- Tool Calls: [Output *only* the JSON array of tool calls required: [{"callId": "call_1", "toolName": "tool_name", "arguments": {"arg1": "value1"}}] or [] if no tools are needed. Do not add any other text in this section.]`;defaultSynthesisPromptTemplate=`System Prompt:
19
- {{systemPrompt}}
20
-
21
- Conversation History:
22
- {{history}}
23
-
24
- User Query:
25
- {{query}}
13
+ 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.]`}];}catch(S){throw o.error(`[${r}] Failed to construct planning prompt object:`,S),new d(`Failed to construct planning prompt object: ${S.message}`,"PROMPT_ASSEMBLY_FAILED",S)}o.debug(`[${r}] Stage 3b: Planning LLM Call`);let w={threadId:t.threadId,traceId:r,userId:t.userId,sessionId:t.sessionId,stream:!0,callContext:"AGENT_THOUGHT",requiredCapabilities:["reasoning"],providerConfig:T,...t.options?.llmParams??{}},N="",_={},R=null;try{await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"PLAN",content:{message:"Preparing for planning LLM call."},metadata:{timestamp:Date.now()}}).catch(E=>o.error(`[${r}] Failed to record PLAN observation:`,E)),l++;let S=await this.deps.reasoningEngine.call(I,w);await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"LLM_STREAM_START",content:{phase:"planning"},metadata:{timestamp:Date.now()}}).catch(E=>o.error(`[${r}] Failed to record LLM_STREAM_START observation:`,E));for await(let E of S){switch(this.deps.uiSystem.getLLMStreamSocket().notify(E,{targetThreadId:E.threadId,targetSessionId:E.sessionId}),E.type){case "TOKEN":N+=E.data;break;case "METADATA":await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"LLM_STREAM_METADATA",content:E.data,metadata:{phase:"planning",timestamp:Date.now()}}).catch(L=>o.error(`[${r}] Failed to record LLM_STREAM_METADATA observation:`,L)),c={...c??{},...E.data};break;case "ERROR":R=E.data instanceof Error?E.data:new Error(String(E.data)),n="error",a=`Planning phase stream error: ${R.message}`,o.error(`[${r}] Planning Stream Error:`,R),await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"LLM_STREAM_ERROR",content:{phase:"planning",error:R.message,stack:R.stack},metadata:{timestamp:Date.now()}}).catch(L=>o.error(`[${r}] Failed to record LLM_STREAM_ERROR observation:`,L));break;case "END":await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"LLM_STREAM_END",content:{phase:"planning"},metadata:{timestamp:Date.now()}}).catch(L=>o.error(`[${r}] Failed to record LLM_STREAM_END observation:`,L));break}if(R)break}if(R)throw new d(a,"PLANNING_FAILED",R);_=await this.deps.outputParser.parsePlanningOutput(N),await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"INTENT",content:{intent:_.intent},metadata:{timestamp:Date.now()}}),await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"PLAN",content:{plan:_.plan,rawOutput:N},metadata:{timestamp:Date.now()}}),_.toolCalls&&_.toolCalls.length>0&&await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"TOOL_CALL",content:{toolCalls:_.toolCalls},metadata:{timestamp:Date.now()}});}catch(S){throw n="error",a=a??`Planning phase failed: ${S.message}`,o.error(`[${r}] Planning Error:`,S),R||await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"ERROR",content:{phase:"planning",error:S.message,stack:S.stack},metadata:{timestamp:Date.now()}}),S instanceof d?S:new d(a,"PLANNING_FAILED",S)}let P=[];if(_.toolCalls&&_.toolCalls.length>0){o.debug(`[${r}] Stage 4: Tool Execution (${_.toolCalls.length} calls)`);try{P=await this.deps.toolSystem.executeTools(_.toolCalls,t.threadId,r),i=P.length,P.some(S=>S.status==="error")&&(n="partial",o.warn(`[${r}] Partial success in tool execution.`),a=a?`${a}; Tool execution errors occurred.`:"Tool execution errors occurred.");}catch(S){throw n="error",a=`Tool execution phase failed: ${S.message}`,o.error(`[${r}] Tool Execution System Error:`,S),await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"ERROR",content:{phase:"tool_execution",error:S.message,stack:S.stack},metadata:{timestamp:Date.now()}}),new d(a,"TOOL_EXECUTION_FAILED",S)}}else o.debug(`[${r}] Stage 4: Tool Execution (No tool calls)`);o.debug(`[${r}] Stage 5: Synthesis Call`),await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"SYNTHESIS",content:{message:"Preparing for synthesis LLM call."},metadata:{timestamp:Date.now()}}).catch(S=>o.error(`[${r}] Failed to record SYNTHESIS observation:`,S)),o.debug(`[${r}] Stage 5: Synthesis Prompt Construction`);let M;try{M=[{role:"system",content:f},...h,{role:"user",content:`User Query: ${t.query}
26
14
 
27
- Original Intent:
28
- {{intent}}
29
-
30
- Execution Plan:
31
- {{plan}}
15
+ Original Intent: ${_.intent??""}
16
+ Execution Plan: ${_.plan??""}
32
17
 
33
18
  Tool Execution Results:
34
- {{toolResults}}
19
+ ${P.length>0?P.map(S=>`- Tool: ${S.toolName} (Call ID: ${S.callId})
20
+ Status: ${S.status}
21
+ ${S.status==="success"?`Output: ${JSON.stringify(S.output)}`:""}
22
+ ${S.status==="error"?`Error: ${S.error??"Unknown error"}`:""}`).join(`
23
+ `):"No tools were executed."}
35
24
 
36
25
  Based on the user query, the plan, and the results of any tool executions, synthesize a final response to the user.
37
- If the tools failed or provided unexpected results, explain the issue and try to answer based on available information or ask for clarification.`;async createPlanningPrompt(e,t,r,o,a){let i=t.map(p=>`${p.role==="USER"?"User":"AI"}: ${p.content}`).join(`
38
- `),n=o.length>0?o.map(p=>`- ${p.name}: ${p.description}
39
- Input Schema: ${JSON.stringify(p.inputSchema)}`).join(`
40
- `):"No tools available.",l={systemPrompt:r||this.defaultSystemPrompt,history:i||"No history yet.",query:e,tools:n};return Promise.resolve(ne(this.defaultPlanningPromptTemplate,l))}async createSynthesisPrompt(e,t,r,o,a,i,n){let l=a.map(d=>`${d.role==="USER"?"User":"AI"}: ${d.content}`).join(`
41
- `),p=o.length>0?o.map(d=>{let u=d.status==="success"?`Output: ${JSON.stringify(d.output)}`:`Error: ${d.error}`;return `- Tool: ${d.toolName} (Call ID: ${d.callId})
42
- Status: ${d.status}
43
- ${u}`}).join(`
44
- `):"No tools were executed.",m={systemPrompt:i||this.defaultSystemPrompt,history:l||"No history yet.",query:e,intent:t,plan:r,toolResults:p};return Promise.resolve(ne(this.defaultSynthesisPromptTemplate,m))}};var G=class{adapter;constructor(e){if(!e)throw new Error("ReasoningEngine requires a valid ProviderAdapter.");this.adapter=e,s.info(`ReasoningEngine initialized with adapter: ${e.providerName}`);}async call(e,t){s.debug(`ReasoningEngine delegating call to adapter: ${this.adapter.providerName}`,{threadId:t.threadId,traceId:t.traceId});try{return await this.adapter.call(e,t)}catch(r){throw s.error(`ReasoningEngine encountered an error during adapter call: ${r.message}`,{error:r,threadId:t.threadId,traceId:t.traceId}),r}}};var ue=I__namespace.object({callId:I__namespace.string().min(1),toolName:I__namespace.string().min(1),arguments:I__namespace.unknown()}),he=I__namespace.array(ue),J=class{async parsePlanningOutput(e){let t={},r=e.match(/Intent:\s*([\s\S]*?)(Plan:|Tool Calls:|$)/i);t.intent=r?.[1]?.trim();let o=e.match(/Plan:\s*([\s\S]*?)(Tool Calls:|$)/i);t.plan=o?.[1]?.trim();let a=e.match(/Tool Calls:\s*([\s\S]*?)$/i),i=a?.[1]?.trim();if(t.toolCalls=void 0,i){let n=null,l=null,p=/```(?:json)?\s*(\[[\s\S]*?\])\s*```|(\[[\s\S]*?\])/,m=i.match(p);if(m?n=m[1]?m[1].trim():m[2]?m[2].trim():null:s.debug(`OutputParser: No JSON array found in Tool Calls section. Content: ${i}`),n)try{let d=n.replace(/,\s*(?=]$)/,"");l=JSON.parse(d);}catch(d){s.error(`OutputParser: Failed to parse extracted JSON array. Error: ${d}. Extracted Content: ${n}. Original Content: ${i}`);}if(l!==null){let d=he.safeParse(l);d.success?t.toolCalls=d.data:(s.warn(`OutputParser: Tool Calls JSON structure validation failed. Errors: ${d.error.toString()}. Parsed Content: ${JSON.stringify(l)}`),t.toolCalls=[]);}else t.toolCalls=[];}else a&&(t.toolCalls=[]);return !t.intent&&!t.plan&&!t.toolCalls&&s.warn(`OutputParser: Could not parse any structured data (Intent, Plan, Tool Calls) from planning output: ${e}`),t}async parseSynthesisOutput(e){return e.trim()}};var P=class{providerName="openai";apiKey;model;apiBaseUrl;constructor(e){if(!e.apiKey)throw new Error("OpenAI API key is required.");this.apiKey=e.apiKey,this.model=e.model||"gpt-3.5-turbo",this.apiBaseUrl=e.apiBaseUrl||"https://api.openai.com/v1",s.debug(`OpenAIAdapter initialized with model: ${this.model}`);}async call(e,t){typeof e!="string"&&(s.warn("OpenAIAdapter received non-string prompt. Treating as string."),e=String(e));let r=`${this.apiBaseUrl}/chat/completions`,o={model:this.model,messages:[{role:"user",content:e}],temperature:t.temperature,max_tokens:t.max_tokens};Object.keys(o).forEach(a=>o[a]===void 0&&delete o[a]),s.debug(`Calling OpenAI API: ${r} with model ${this.model}`,{threadId:t.threadId,traceId:t.traceId});try{let a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(o)});if(!a.ok){let l=await a.text();throw s.error(`OpenAI API request failed with status ${a.status}: ${l}`,{threadId:t.threadId,traceId:t.traceId}),new Error(`OpenAI API request failed: ${a.status} ${a.statusText} - ${l}`)}let i=await a.json();if(!i.choices||i.choices.length===0||!i.choices[0].message?.content)throw s.error("Invalid response structure from OpenAI API",{responseData:i,threadId:t.threadId,traceId:t.traceId}),new Error("Invalid response structure from OpenAI API: No content found.");let n=i.choices[0].message.content.trim();return s.debug(`OpenAI API call successful. Response length: ${n.length}`,{threadId:t.threadId,traceId:t.traceId}),n}catch(a){throw s.error(`Error during OpenAI API call: ${a.message}`,{error:a,threadId:t.threadId,traceId:t.traceId}),a}}};var C=class{providerName="gemini";apiKey;model;apiBaseUrl;apiVersion;constructor(e){if(!e.apiKey)throw new Error("Gemini API key is required.");this.apiKey=e.apiKey,this.model=e.model||"gemini-1.5-flash",this.apiVersion=e.apiVersion||"v1beta",this.apiBaseUrl=e.apiBaseUrl||"https://generativelanguage.googleapis.com",s.debug(`GeminiAdapter initialized with model: ${this.model}, version: ${this.apiVersion}`);}async call(e,t){typeof e!="string"&&(s.warn("GeminiAdapter received non-string prompt. Treating as string."),e=String(e));let r=`${this.apiBaseUrl}/${this.apiVersion}/models/${this.model}:generateContent?key=${this.apiKey}`,o={contents:[{parts:[{text:e}]}],generationConfig:{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}};o.generationConfig&&(Object.keys(o.generationConfig).forEach(a=>o.generationConfig[a]===void 0&&delete o.generationConfig[a]),Object.keys(o.generationConfig).length===0&&delete o.generationConfig),s.debug(`Calling Gemini API: ${r.split("?")[0]} with model ${this.model}`,{threadId:t.threadId,traceId:t.traceId});try{let a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok){let p=await a.text();throw s.error(`Gemini API request failed with status ${a.status}: ${p}`,{threadId:t.threadId,traceId:t.traceId}),new Error(`Gemini API request failed: ${a.status} ${a.statusText} - ${p}`)}let i=await a.json(),n=i.candidates?.[0]?.content?.parts?.map(p=>p.text).join("");if(n==null)throw i.promptFeedback?(s.error("Gemini API call blocked or failed to generate content.",{responseData:i,threadId:t.threadId,traceId:t.traceId}),new Error("Gemini API call blocked or failed to generate content. Check prompt feedback in logs or API documentation.")):(s.error("Invalid response structure from Gemini API: No text content found",{responseData:i,threadId:t.threadId,traceId:t.traceId}),new Error("Invalid response structure from Gemini API: No text content found."));let l=n.trim();return s.debug(`Gemini API call successful. Response length: ${l.length}`,{threadId:t.threadId,traceId:t.traceId}),l}catch(a){throw s.error(`Error during Gemini API call: ${a.message}`,{error:a,threadId:t.threadId,traceId:t.traceId}),a}}};var R=class{providerName="anthropic";apiKey;model;apiVersion;apiBaseUrl;defaultMaxTokens=1024;constructor(e){if(!e.apiKey)throw new Error("Anthropic API key is required.");this.apiKey=e.apiKey,this.model=e.model||"claude-3-haiku-20240307",this.apiVersion=e.apiVersion||"2023-06-01",this.apiBaseUrl=e.apiBaseUrl||"https://api.anthropic.com/v1",s.debug(`AnthropicAdapter initialized with model: ${this.model}, version: ${this.apiVersion}`);}async call(e,t){typeof e!="string"&&(s.warn("AnthropicAdapter received non-string prompt. Treating as string."),e=String(e));let r=`${this.apiBaseUrl}/messages`,o=t.max_tokens||t.maxOutputTokens||t.max_tokens_to_sample||this.defaultMaxTokens,a={model:this.model,messages:[{role:"user",content:e}],system:t.system_prompt||t.system,max_tokens:o,temperature:t.temperature,top_p:t.top_p||t.topP,top_k:t.top_k||t.topK,stop_sequences:t.stop||t.stop_sequences||t.stopSequences};Object.keys(a).forEach(i=>{let n=i;n!=="max_tokens"&&a[n]===void 0&&delete a[n];}),s.debug(`Calling Anthropic API: ${r} with model ${this.model}`,{threadId:t.threadId,traceId:t.traceId});try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion},body:JSON.stringify(a)});if(!i.ok){let m=await i.text();s.error(`Anthropic API request failed with status ${i.status}: ${m}`,{threadId:t.threadId,traceId:t.traceId});let d=m;try{let u=JSON.parse(m);u?.error?.message&&(d=u.error.message);}catch{}throw new Error(`Anthropic API request failed: ${i.status} ${i.statusText} - ${d}`)}let n=await i.json(),l=n.content?.find(m=>m.type==="text")?.text;if(l==null)throw s.error("Invalid response structure from Anthropic API: No text content found",{responseData:n,threadId:t.threadId,traceId:t.traceId}),new Error("Invalid response structure from Anthropic API: No text content found.");let p=l.trim();return s.debug(`Anthropic API call successful. Response length: ${p.length}`,{threadId:t.threadId,traceId:t.traceId}),p}catch(i){throw s.error(`Error during Anthropic API call: ${i.message}`,{error:i,threadId:t.threadId,traceId:t.traceId}),i}}};var E=class{providerName="openrouter";apiKey;model;apiBaseUrl;siteUrl;appName;constructor(e){if(!e.apiKey)throw new Error("OpenRouter API key is required.");if(!e.model)throw new Error("OpenRouter model identifier is required (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,s.debug(`OpenRouterAdapter initialized for model: ${this.model}`);}async call(e,t){typeof e!="string"&&(s.warn("OpenRouterAdapter received non-string prompt. Treating as string."),e=String(e));let r=`${this.apiBaseUrl}/chat/completions`,o=t.stop||t.stop_sequences||t.stopSequences,a={model:this.model,messages:[{role:"user",content:e}],temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,top_k:t.top_k||t.topK,stop:o};Object.keys(a).forEach(n=>a[n]===void 0&&delete a[n]);let i={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};this.siteUrl&&(i["HTTP-Referer"]=this.siteUrl),this.appName&&(i["X-Title"]=this.appName),s.debug(`Calling OpenRouter API: ${r} with model ${this.model}`,{threadId:t.threadId,traceId:t.traceId});try{let n=await fetch(r,{method:"POST",headers:i,body:JSON.stringify(a)});if(!n.ok){let m=await n.text();s.error(`OpenRouter API request failed with status ${n.status}: ${m}`,{threadId:t.threadId,traceId:t.traceId});let d=m;try{let u=JSON.parse(m);u?.error?.message&&(d=u.error.message);}catch{}throw new Error(`OpenRouter API request failed: ${n.status} ${n.statusText} - ${d}`)}let l=await n.json();if(!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw s.error("Invalid response structure from OpenRouter API",{responseData:l,threadId:t.threadId,traceId:t.traceId}),new Error("Invalid response structure from OpenRouter API: No content found.");let p=l.choices[0].message.content.trim();return s.debug(`OpenRouter API call successful. Response length: ${p.length}`,{threadId:t.threadId,traceId:t.traceId}),p}catch(n){throw s.error(`Error during OpenRouter API call: ${n.message}`,{error:n,threadId:t.threadId,traceId:t.traceId}),n}}};var $=class{providerName="deepseek";apiKey;model;apiBaseUrl;constructor(e){if(!e.apiKey)throw new Error("DeepSeek API key is required.");this.apiKey=e.apiKey,this.model=e.model||"deepseek-chat",this.apiBaseUrl=e.apiBaseUrl||"https://api.deepseek.com/v1",s.debug(`DeepSeekAdapter initialized with model: ${this.model}`);}async call(e,t){typeof e!="string"&&(s.warn("DeepSeekAdapter received non-string prompt. Treating as string."),e=String(e));let r=`${this.apiBaseUrl}/chat/completions`,o=t.stop||t.stop_sequences||t.stopSequences,a={model:this.model,messages:[{role:"user",content:e}],temperature:t.temperature,max_tokens:t.max_tokens||t.maxOutputTokens,top_p:t.top_p||t.topP,stop:o};Object.keys(a).forEach(n=>a[n]===void 0&&delete a[n]);let i={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};s.debug(`Calling DeepSeek API: ${r} with model ${this.model}`,{threadId:t.threadId,traceId:t.traceId});try{let n=await fetch(r,{method:"POST",headers:i,body:JSON.stringify(a)});if(!n.ok){let m=await n.text();s.error(`DeepSeek API request failed with status ${n.status}: ${m}`,{threadId:t.threadId,traceId:t.traceId});let d=m;try{let u=JSON.parse(m);u?.error?.message&&(d=u.error.message);}catch{}throw new Error(`DeepSeek API request failed: ${n.status} ${n.statusText} - ${d}`)}let l=await n.json();if(!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw s.error("Invalid response structure from DeepSeek API",{responseData:l,threadId:t.threadId,traceId:t.traceId}),new Error("Invalid response structure from DeepSeek API: No content found.");let p=l.choices[0].message.content.trim();return s.debug(`DeepSeek API call successful. Response length: ${p.length}`,{threadId:t.threadId,traceId:t.traceId}),p}catch(n){throw s.error(`Error during DeepSeek API call: ${n.message}`,{error:n,threadId:t.threadId,traceId:t.traceId}),n}}};var O=class{subscriptions=new Map;constructor(){}subscribe(e,t,r){let o=uuid.v4(),a={id:o,callback:e,filter:t,options:r};return this.subscriptions.set(o,a),s.debug(`New subscription added: ${o}, Filter: ${JSON.stringify(t)}, Options: ${JSON.stringify(r)}`),()=>{this.subscriptions.delete(o),s.debug(`Subscription removed: ${o}`);}}notify(e,t,r){s.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;o.callback(e);}catch(a){s.error(`Error executing subscription callback ${o.id}:`,a);}});}async getHistory(e,t){return s.warn("getHistory is not implemented in the base TypedSocket."),[]}clearAllSubscriptions(){this.subscriptions.clear(),s.debug("All subscriptions cleared.");}};var V=class extends O{observationRepository;constructor(e){super(),this.observationRepository=e,s.debug("ObservationSocket initialized.");}notifyObservation(e){s.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 s.warn("Cannot getHistory for ObservationSocket: ObservationRepository not configured."),[];if(!t?.threadId)return s.warn("Cannot getHistory for ObservationSocket: threadId is required."),[];s.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&&s.debug(`Limit requested: ${t.limit}. Repository implementation must handle this.`);try{return await this.observationRepository.getObservations(t.threadId,r)}catch(o){return s.error(`Error fetching observation history for thread ${t.threadId} with filter ${JSON.stringify(r)}:`,o),[]}}};var H=class extends O{conversationRepository;constructor(e){super(),this.conversationRepository=e,s.debug("ConversationSocket initialized.");}notifyMessage(e){s.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 s.warn("Cannot getHistory for ConversationSocket: ConversationRepository not configured."),[];if(!t?.threadId)return s.warn("Cannot getHistory for ConversationSocket: threadId is required."),[];s.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&&s.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(o){return s.error(`Error fetching message history for thread ${t.threadId}:`,o),[]}}};var z=class{observationSocketInstance;conversationSocketInstance;constructor(e,t){this.observationSocketInstance=new V(e),this.conversationSocketInstance=new H(t),s.debug("UISystem initialized with Observation and Conversation sockets.");}getObservationSocket(){return this.observationSocketInstance}getConversationSocket(){return this.conversationSocketInstance}};var ee=class{config;storageAdapter=null;uiSystem=null;conversationRepository=null;observationRepository=null;stateRepository=null;conversationManager=null;stateManager=null;observationManager=null;toolRegistry=null;providerAdapter=null;reasoningEngine=null;promptManager=null;outputParser=null;toolSystem=null;constructor(e){if(this.config=e,!e.storage)throw new Error("Storage configuration is required.");if(!e.reasoning)throw new Error("Reasoning configuration is required.")}async initialize(){switch(this.config.storage.type){case "indexedDB":this.storageAdapter=new w({dbName:this.config.storage.dbName||"ARTDB",objectStores:["conversations","observations","state"]});break;case "memory":default:this.storageAdapter=new x;break}if(await this.storageAdapter.init?.(),this.conversationRepository=new D(this.storageAdapter),this.observationRepository=new _(this.storageAdapter),this.stateRepository=new F(this.storageAdapter),this.uiSystem=new z(this.observationRepository,this.conversationRepository),this.conversationManager=new U(this.conversationRepository,this.uiSystem.getConversationSocket()),this.stateManager=new B(this.stateRepository),this.observationManager=new L(this.observationRepository,this.uiSystem.getObservationSocket()),this.toolRegistry=new q,this.config.tools)for(let t of this.config.tools)await this.toolRegistry.registerTool(t);let e=this.config.reasoning;switch(e.provider){case "openai":this.providerAdapter=new P({apiKey:e.apiKey,model:e.model});break;case "gemini":this.providerAdapter=new C({apiKey:e.apiKey,model:e.model});break;case "anthropic":this.providerAdapter=new R({apiKey:e.apiKey,model:e.model});break;case "openrouter":this.providerAdapter=new E({apiKey:e.apiKey,model:e.model});break;case "deepseek":this.providerAdapter=new $({apiKey:e.apiKey,model:e.model});break;default:throw new Error(`Unsupported reasoning provider: ${e.provider}`)}this.reasoningEngine=new G(this.providerAdapter),this.promptManager=new K,this.outputParser=new J,this.toolSystem=new j(this.toolRegistry,this.stateManager,this.observationManager);}createAgent(){if(!this.stateManager||!this.conversationManager||!this.toolRegistry||!this.promptManager||!this.reasoningEngine||!this.outputParser||!this.observationManager||!this.toolSystem||!this.providerAdapter)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},t=this.config.agentCore||A;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}};async function ye(c){let e=new ee(c);await e.initialize();let t=e.createAgent(),r=e.getUISystem(),o=e.getStateManager(),a=e.getConversationManager(),i=e.getToolRegistry(),n=e.getObservationManager();if(!r||!o||!a||!i||!n)throw new Error("Failed to initialize one or more core components within AgentFactory.");return {process:t.process.bind(t),uiSystem:r,stateManager:o,conversationManager:a,toolRegistry:i,observationManager:n}}var ve={sqrt:g__namespace.sqrt,cbrt:g__namespace.cbrt,abs:g__namespace.abs,pow:g__namespace.pow,exp:g__namespace.exp,log:g__namespace.log,log10:g__namespace.log10,log2:g__namespace.log2,sin:g__namespace.sin,cos:g__namespace.cos,tan:g__namespace.tan,asin:g__namespace.asin,acos:g__namespace.acos,atan:g__namespace.atan,atan2:g__namespace.atan2,round:g__namespace.round,floor:g__namespace.floor,ceil:g__namespace.ceil,mod:g__namespace.mod},te=class c{static toolName="calculator";schema={name:c.toolName,description:`Evaluates mathematical expressions using a sandboxed mathjs environment. IMPORTANT LIMITATIONS: Each expression is evaluated independently; there is no memory of previous results (e.g., no 'ans' variable). Only a specific list of functions is supported.
26
+ If the tools failed or provided unexpected results, explain the issue and try to answer based on available information or ask for clarification.`}];}catch(S){throw o.error(`[${r}] Failed to construct synthesis prompt object:`,S),new d(`Failed to construct synthesis prompt object: ${S.message}`,"PROMPT_ASSEMBLY_FAILED",S)}o.debug(`[${r}] Stage 5b: Synthesis LLM Call`);let x={threadId:t.threadId,traceId:r,userId:t.userId,sessionId:t.sessionId,stream:!0,callContext:"FINAL_SYNTHESIS",requiredCapabilities:["text"],providerConfig:T,...t.options?.llmParams??{}},$="",v=null;try{l++;let S=await this.deps.reasoningEngine.call(M,x);await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"LLM_STREAM_START",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}}).catch(E=>o.error(`[${r}] Failed to record LLM_STREAM_START observation:`,E));for await(let E of S){switch(this.deps.uiSystem.getLLMStreamSocket().notify(E,{targetThreadId:E.threadId,targetSessionId:E.sessionId}),E.type){case "TOKEN":(E.tokenType==="FINAL_SYNTHESIS_LLM_RESPONSE"||E.tokenType==="LLM_RESPONSE")&&($+=E.data);break;case "METADATA":c={...c??{},...E.data},await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"LLM_STREAM_METADATA",content:E.data,metadata:{phase:"synthesis",timestamp:Date.now()}}).catch(L=>o.error(`[${r}] Failed to record LLM_STREAM_METADATA observation:`,L));break;case "ERROR":v=E.data instanceof Error?E.data:new Error(String(E.data)),n=n==="partial"?"partial":"error",a=a?`${a}; Synthesis stream error: ${v.message}`:`Synthesis stream error: ${v.message}`,o.error(`[${r}] Synthesis Stream Error:`,v),await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"LLM_STREAM_ERROR",content:{phase:"synthesis",error:v.message,stack:v.stack},metadata:{timestamp:Date.now()}}).catch(L=>o.error(`[${r}] Failed to record LLM_STREAM_ERROR observation:`,L));break;case "END":await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"LLM_STREAM_END",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}}).catch(L=>o.error(`[${r}] Failed to record LLM_STREAM_END observation:`,L));break}if(v)break}if(v){if(n!=="partial")throw new d(a,"SYNTHESIS_FAILED",v);$=a;}}catch(S){n=n==="partial"?"partial":"error";let E=`Synthesis phase failed: ${S.message}`;if(a=a?`${a}; ${E}`:E,o.error(`[${r}] Synthesis Error:`,S),v||await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"ERROR",content:{phase:"synthesis",error:S.message,stack:S.stack},metadata:{timestamp:Date.now()}}),n!=="partial")throw S instanceof d?S:new d(E,"SYNTHESIS_FAILED",S);$=a;}o.debug(`[${r}] Stage 6: Finalization`);let de=Date.now();s={messageId:F(),threadId:t.threadId,role:"AI",content:$,timestamp:de,metadata:{traceId:r}},await this.deps.conversationManager.addMessages(t.threadId,[s]),await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"FINAL_RESPONSE",content:{message:s},metadata:{timestamp:de}}),await this.deps.stateManager.saveStateIfModified(t.threadId);}catch(A){o.error(`[${r}] PESAgent process error:`,A),n=n==="partial"?"partial":"error",a=a??(A instanceof d?A.message:"An unexpected error occurred."),n==="error"&&(s=void 0),A instanceof d&&(A.code==="PLANNING_FAILED"||A.code==="TOOL_EXECUTION_FAILED"||A.code==="SYNTHESIS_FAILED")||await this.deps.observationManager.record({threadId:t.threadId,traceId:r,type:"ERROR",content:{phase:"agent_process",error:A.message,stack:A.stack},metadata:{timestamp:Date.now()}}).catch(f=>o.error(`[${r}] Failed to record top-level error observation:`,f));}finally{try{await this.deps.stateManager.saveStateIfModified(t.threadId);}catch(A){o.error(`[${r}] Failed to save state during finalization:`,A);}}let g=Date.now(),y={threadId:t.threadId,traceId:r,userId:t.userId,status:n,totalDurationMs:g-e,llmCalls:l,toolCalls:i,error:a,llmMetadata:c};if(!s&&n!=="success")s={messageId:F(),threadId:t.threadId,role:"AI",content:a??"Agent execution failed.",timestamp:Date.now(),metadata:{traceId:r,error:true}};else if(!s)throw new d("Agent finished with success status but no final message was generated.","UNKNOWN_ERROR");return {response:s,metadata:y}}formatHistoryForPrompt(t){return t.map(e=>{let r;switch(e.role){case "USER":r="user";break;case "AI":r="assistant";break;case "SYSTEM":r="system";break;case "TOOL":r="tool";break;default:o.warn(`Unhandled message role '${e.role}' in formatHistoryForPrompt. Defaulting to 'user'.`),r="user";}return {role:r,content:e.content}}).filter(e=>e.content)}};var G=class{storage=new Map;async init(t){return Promise.resolve()}async get(t,e){let r=this.storage.get(t);if(!r)return null;let n=r.get(e);return n?JSON.parse(JSON.stringify(n)):null}async set(t,e,r){return this.storage.has(t)||this.storage.set(t,new Map),this.storage.get(t).set(e,JSON.parse(JSON.stringify(r))),Promise.resolve()}async delete(t,e){let r=this.storage.get(t);return r&&r.delete(e),Promise.resolve()}async query(t,e){let r=this.storage.get(t);if(!r)return [];let n=Array.from(r.values());return e.filter&&(n=n.filter(a=>{for(let l in e.filter)if(e.filter.hasOwnProperty(l)&&a[l]!==e.filter[l])return false;return true})),typeof e.limit=="number"&&e.limit>=0&&(n=n.slice(0,e.limit)),JSON.parse(JSON.stringify(n))}async clearCollection(t){return this.storage.delete(t),Promise.resolve()}async clearAll(){return this.storage.clear(),Promise.resolve()}};var be="ART_Framework_DB",_e=1,B=class{db=null;dbName;dbVersion;requiredObjectStores;initPromise=null;constructor(t){this.dbName=t.dbName||be,this.dbVersion=t.dbVersion||_e,this.requiredObjectStores=new Set(["conversations","observations","state",...t.objectStores||[]]);}async init(){return this.initPromise?this.initPromise:(this.initPromise=new Promise((t,e)=>{if(!("indexedDB"in window))return o.error("IndexedDBStorageAdapter: IndexedDB not supported in this browser."),e(new Error("IndexedDB not supported"));let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=n=>{o.error(`IndexedDBStorageAdapter: Database error: ${r.error}`,n),e(new Error(`IndexedDB error: ${r.error?.message}`));},r.onsuccess=n=>{this.db=n.target.result,o.info(`IndexedDBStorageAdapter: Database '${this.dbName}' opened successfully (Version: ${this.db.version}).`);let a=new Set(Array.from(this.db.objectStoreNames)),l=[...this.requiredObjectStores].filter(i=>!a.has(i));l.length>0&&o.warn(`IndexedDBStorageAdapter: The following required object stores were not found after opening DB version ${this.db.version}: ${l.join(", ")}. This might happen if the DB version wasn't incremented after adding stores.`),this.db.onerror=i=>{o.error("IndexedDBStorageAdapter: Generic database error:",i);},t();},r.onupgradeneeded=n=>{if(o.info(`IndexedDBStorageAdapter: Upgrading database '${this.dbName}' from version ${n.oldVersion} to ${n.newVersion}...`),this.db=n.target.result,!n.target.transaction){o.error("IndexedDBStorageAdapter: Upgrade transaction is null!"),e(new Error("Upgrade transaction failed"));return}let l=new Set(Array.from(this.db.objectStoreNames));this.requiredObjectStores.forEach(i=>{l.has(i)||(o.info(`IndexedDBStorageAdapter: Creating object store '${i}'...`),this.db?.createObjectStore(i,{keyPath:"id"}));}),o.info("IndexedDBStorageAdapter: Database upgrade complete.");},r.onblocked=n=>{o.warn(`IndexedDBStorageAdapter: Database open request blocked for '${this.dbName}'. Please close other tabs/connections using an older version of this database.`,n),e(new Error(`IndexedDB open blocked for ${this.dbName}. Close other connections.`));};}),this.initPromise)}getTransaction(t,e){if(!this.db)throw new Error("IndexedDBStorageAdapter: Database not initialized. Ensure init() was called and awaited.");return (Array.isArray(t)?t:[t]).forEach(n=>{if(!this.db?.objectStoreNames.contains(n))throw new Error(`IndexedDBStorageAdapter: Object store "${n}" does not exist in the database.`)}),this.db.transaction(t,e)}async get(t,e){return await this.init(),new Promise((r,n)=>{try{let i=this.getTransaction(t,"readonly").objectStore(t).get(e);i.onsuccess=()=>{r(i.result?{...i.result}:null);},i.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error getting item '${e}' from '${t}':`,i.error),n(new Error(`Failed to get item: ${i.error?.message}`));};}catch(a){n(a);}})}async set(t,e,r){let n=r;return typeof n.id>"u"?Promise.reject(new Error(`IndexedDBStorageAdapter: Data for collection '${t}' must have an 'id' property matching the keyPath.`)):(n.id!==e&&o.warn(`IndexedDBStorageAdapter: Provided id ('${e}') and data.id ('${n.id}') mismatch for collection '${t}'. Using data.id as the key.`),await this.init(),new Promise((a,l)=>{try{let i=structuredClone(r),s=this.getTransaction(t,"readwrite"),g=s.objectStore(t).put(i);g.onsuccess=()=>{a();},g.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error setting item with id '${n.id}' in '${t}':`,g.error),l(new Error(`Failed to set item: ${g.error?.message}`));},s.oncomplete=()=>{},s.onerror=y=>{o.error(`IndexedDBStorageAdapter: Transaction error setting item with id '${n.id}' in '${t}':`,s.error,y),l(new Error(`Transaction failed: ${s.error?.message}`));};}catch(i){l(i);}}))}async delete(t,e){return await this.init(),new Promise((r,n)=>{try{let a=this.getTransaction(t,"readwrite"),i=a.objectStore(t).delete(e);i.onsuccess=()=>{r();},i.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error deleting item '${e}' from '${t}':`,i.error),n(new Error(`Failed to delete item: ${i.error?.message}`));},a.onerror=s=>{o.error(`IndexedDBStorageAdapter: Transaction error deleting item '${e}' from '${t}':`,a.error,s),n(new Error(`Transaction failed: ${a.error?.message}`));};}catch(a){n(a);}})}async query(t,e){return await this.init(),new Promise((r,n)=>{try{let i=this.getTransaction(t,"readonly").objectStore(t).getAll();i.onsuccess=()=>{let s=i.result||[];if(e.filter&&(s=s.filter(y=>{for(let A in e.filter)if(e.filter.hasOwnProperty(A)&&y[A]!==e.filter[A])return !1;return !0})),e.sort){let y=Object.keys(e.sort)[0],A=e.sort[y];y&&s.sort((f,T)=>{let O=f[y],p=T[y];return O<p?A==="asc"?-1:1:O>p?A==="asc"?1:-1:0});}let c=e.skip||0,g=e.limit??1/0;s=s.slice(c,c+g),r(s.map(y=>({...y})));},i.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error querying collection '${t}':`,i.error),n(new Error(`Failed to query collection: ${i.error?.message}`));};}catch(a){n(a);}})}async clearCollection(t){return await this.init(),new Promise((e,r)=>{try{let n=this.getTransaction(t,"readwrite"),l=n.objectStore(t).clear();l.onsuccess=()=>{e();},l.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error clearing collection '${t}':`,l.error),r(new Error(`Failed to clear collection: ${l.error?.message}`));},n.onerror=i=>{o.error(`IndexedDBStorageAdapter: Transaction error clearing collection '${t}':`,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 t=Array.from(this.db.objectStoreNames);return t.length===0?Promise.resolve():new Promise((e,r)=>{try{let n=this.getTransaction(t,"readwrite"),a=0,l=t.length;t.forEach(i=>{let s=n.objectStore(i).clear();s.onsuccess=()=>{a++;},s.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error clearing object store '${i}':`,s.error);};}),n.oncomplete=()=>{o.info("IndexedDBStorageAdapter: All object stores cleared successfully."),e();},n.onerror=i=>{o.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 z=class{adapter;collectionName="conversations";constructor(t){if(!t)throw new Error("ConversationRepository requires a valid StorageAdapter instance.");this.adapter=t;}async addMessages(t,e){if(!e||e.length===0)return Promise.resolve();let r=e.map(n=>{n.threadId!==t&&console.warn(`ConversationRepository: Message ${n.messageId} has mismatching threadId (${n.threadId}) for repository operation on thread ${t}.`);let a={...n,id:n.messageId};return this.adapter.set(this.collectionName,a.id,a)});await Promise.all(r);}async getMessages(t,e){let n=await this.adapter.query(this.collectionName,{filter:{threadId:t}});return n.sort((l,i)=>l.timestamp-i.timestamp),e?.beforeTimestamp!==void 0&&(n=n.filter(l=>l.timestamp<e.beforeTimestamp)),e?.afterTimestamp!==void 0&&(n=n.filter(l=>l.timestamp>e.afterTimestamp)),e?.limit!==void 0&&e.limit>0&&(n=n.slice(-e.limit)),n.map(({id:l,...i})=>i)}};var Y=class{adapter;collectionName="observations";constructor(t){if(!t)throw new Error("ObservationRepository requires a valid StorageAdapter instance.");this.adapter=t;}async addObservation(t){if(typeof t.id>"u")return Promise.reject(new Error("ObservationRepository: Observation must have an 'id' property."));await this.adapter.set(this.collectionName,t.id,t);}async getObservations(t,e){let n=await this.adapter.query(this.collectionName,{filter:{threadId:t}});if(n.sort((a,l)=>a.timestamp-l.timestamp),e?.types&&e.types.length>0){let a=new Set(e.types);n=n.filter(l=>a.has(l.type));}return e?.beforeTimestamp!==void 0&&(n=n.filter(a=>a.timestamp<e.beforeTimestamp)),e?.afterTimestamp!==void 0&&(n=n.filter(a=>a.timestamp>e.afterTimestamp)),n}};var Q=class{adapter;collectionName="state";constructor(t){if(!t)throw new Error("StateRepository requires a valid StorageAdapter instance.");this.adapter=t;}async getThreadContext(t){let e=await this.adapter.get(this.collectionName,t);if(!e)return null;let r={...e};return delete r.id,r}async setThreadContext(t,e){if(!e||typeof e.config>"u")return Promise.reject(new Error("StateRepository: ThreadContext must contain a 'config' property."));let r={...e,id:t};await this.adapter.set(this.collectionName,t,r);}async getThreadConfig(t){return (await this.getThreadContext(t))?.config??null}async setThreadConfig(t,e){let r=await this.getThreadContext(t),n={config:e,state:r?.state??null};await this.setThreadContext(t,n);}async getAgentState(t){return (await this.getThreadContext(t))?.state??null}async setAgentState(t,e){let r=await this.getThreadContext(t);if(!r||!r.config)return Promise.reject(new Error(`StateRepository: Cannot set AgentState for thread '${t}' because no ThreadConfig exists. Set config first.`));let n={config:r.config,state:e};await this.setThreadContext(t,n);}};var X=class{repository;conversationSocket;constructor(t,e){this.repository=t,this.conversationSocket=e;}async addMessages(t,e){if(!t)return Promise.reject(new Error("ConversationManager: threadId cannot be empty."));if(!e||e.length===0)return Promise.resolve();await this.repository.addMessages(t,e),e.forEach(r=>{try{this.conversationSocket.notify(r,{targetThreadId:t});}catch(n){console.error(`ConversationManager: Failed to notify message ${r.messageId} via socket for thread ${t}`,n);}});}async getMessages(t,e){return t?await this.repository.getMessages(t,e):Promise.reject(new Error("ConversationManager: threadId cannot be empty."))}};var W=class{repository;constructor(t){this.repository=t;}async loadThreadContext(t,e){if(!t)throw new Error("StateManager: threadId cannot be empty.");let r=await this.repository.getThreadContext(t);if(!r)throw new Error(`StateManager: Thread context not found for threadId '${t}'.`);return r}async isToolEnabled(t,e){try{return (await this.loadThreadContext(t)).config?.enabledTools?.includes(e)??!1}catch(r){return console.warn(`StateManager: Could not check if tool '${e}' is enabled for thread '${t}' because context failed to load: ${r}`),false}}async getThreadConfigValue(t,e){let r=await this.loadThreadContext(t);if(r.config&&e in r.config)return r.config[e]}async saveStateIfModified(t){return t?(console.warn(`StateManager: saveStateIfModified called for thread ${t}, but state modification tracking/saving is not implemented in this version. State must be saved explicitly via repository methods.`),Promise.resolve()):Promise.reject(new Error("StateManager: threadId cannot be empty for saveStateIfModified."))}async setThreadConfig(t,e){if(!t||!e)throw new Error("StateManager: threadId and config are required for setThreadConfig.");await this.repository.setThreadConfig(t,e);}};var Z=class{observationRepository;observationSocket;constructor(t,e){this.observationRepository=t,this.observationSocket=e;}async record(t){let e={...t,id:F(),timestamp:Date.now(),title:`${t.type} Recorded`};try{await this.observationRepository.addObservation(e),o.debug(`[ObservationManager] Notifying ObservationSocket for obsId: ${e.id}, type: ${e.type}`),this.observationSocket.notify(e,{targetThreadId:e.threadId}),o.debug(`[ObservationManager] ObservationSocket notified for obsId: ${e.id}`);}catch(r){throw console.error("Error recording observation:",r),r}}async getObservations(t,e){try{return await this.observationRepository.getObservations(t,e)}catch(r){throw console.error(`Error retrieving observations for thread ${t}:`,r),r}}};var ee=class{executors=new Map;stateManager;constructor(t){this.stateManager=t,o.debug(`ToolRegistry initialized ${t?"with":"without"} StateManager.`);}async registerTool(t){if(!t||!t.schema||!t.schema.name)throw o.error("ToolRegistry: Attempted to register an invalid tool executor."),new Error("Invalid tool executor provided for registration.");let e=t.schema.name;this.executors.has(e)&&o.warn(`ToolRegistry: Overwriting existing tool registration for "${e}".`),this.executors.set(e,t),o.debug(`ToolRegistry: Registered tool "${e}".`);}async getToolExecutor(t){let e=this.executors.get(t);return e||o.debug(`ToolRegistry: Tool "${t}" not found.`),e}async getAvailableTools(t){let e=Array.from(this.executors.values()),r=e.map(n=>n.schema);if(t?.enabledForThreadId&&this.stateManager){let n=t.enabledForThreadId;o.debug(`ToolRegistry: Attempting to filter tools for threadId: ${n}`);try{let l=(await this.stateManager.loadThreadContext(n))?.config?.enabledTools;if(l&&Array.isArray(l)){o.debug(`ToolRegistry: Found enabled tools for thread ${n}: ${l.join(", ")}`);let s=e.filter(c=>l.includes(c.schema.name)).map(c=>c.schema);return o.debug(`ToolRegistry: Returning ${s.length} enabled tool schemas for thread ${n}.`),s}else o.warn(`ToolRegistry: No specific enabledTools found for thread ${n} or config missing. Returning all tools.`);}catch(a){o.error(`ToolRegistry: Error loading thread config for ${n}: ${a.message}. Returning all tools.`);}}else t?.enabledForThreadId&&!this.stateManager&&o.warn("ToolRegistry: Filtering by enabledForThreadId requested, but StateManager was not provided. Returning all tools.");return o.debug(`ToolRegistry: Returning all ${r.length} registered tool schemas.`),r}async clearAllTools(){this.executors.clear(),o.debug("ToolRegistry: Cleared all registered tools.");}};var Pe=new Me__default.default({allErrors:true}),pe=new Map;function ve(u,t){let e=JSON.stringify(u),r;if(pe.has(e))r=pe.get(e),o.debug("Using cached JSON schema validator.");else try{r=Pe.compile(u),pe.set(e,r),o.debug("Compiled and cached new JSON schema validator.");}catch(a){return o.error(`Failed to compile JSON schema: ${a.message}`,{schema:u,error:a}),{isValid:false,errors:[{keyword:"compilation",instancePath:"",schemaPath:"",params:{},message:`Schema compilation failed: ${a.message}`}]}}return r(t)?{isValid:true,errors:null}:(o.warn("JSON schema validation failed.",{errors:r.errors,data:t}),{isValid:false,errors:r.errors||[]})}var te=class{toolRegistry;stateManager;observationManager;constructor(t,e,r){if(!t)throw new Error("ToolSystem constructor requires a ToolRegistry instance.");if(!e)throw new Error("ToolSystem constructor requires a StateManager instance.");if(!r)throw new Error("ToolSystem constructor requires an ObservationManager instance.");this.toolRegistry=t,this.stateManager=e,this.observationManager=r,o.info("ToolSystem initialized.");}async executeTools(t,e,r){let n=[];o.debug(`ToolSystem executing ${t.length} tool calls for thread ${e}`,{traceId:r});for(let a of t){let l=null,i,s=a.toolName,c=a.callId;try{if(!await this.stateManager.isToolEnabled(e,s))throw new Error(`Tool "${s}" is not enabled for thread "${e}".`);if(i=await this.toolRegistry.getToolExecutor(s),!i)throw new Error(`Tool "${s}" not found in registry.`);let y=ve(i.schema.inputSchema,a.arguments);if(!y.isValid){let T=y.errors?.map(O=>`${O.instancePath||"input"} ${O.message}`).join(", ")||"Unknown validation error";throw new Error(`Invalid arguments for tool "${s}": ${T}`)}o.debug(`Executing tool "${s}" with callId "${c}"`,{args:a.arguments,threadId:e,traceId:r});let A={threadId:e,traceId:r};l={...await i.execute(a.arguments,A),callId:c,toolName:s},o.debug(`Tool "${s}" execution successful`,{callId:c,result:l.output,threadId:e,traceId:r});}catch(g){o.error(`Tool "${s}" execution failed for callId "${c}": ${g.message}`,{error:g,threadId:e,traceId:r}),l={callId:c,toolName:s,status:"error",error:g.message||"Unknown execution error"};}l?(this.observationManager.record({threadId:e,traceId:r,type:"TOOL_EXECUTION",content:l,metadata:{timestamp:Date.now(),callId:a.callId}}).catch(g=>o.error(`Failed to record TOOL_EXECUTION observation for callId ${a.callId}:`,g)),n.push(l)):o.error(`ToolSystem finished processing call ${a.callId} but result object was null.`);}return n}};var we=k.z.object({role:k.z.custom(u=>typeof u=="string"&&["system","user","assistant","tool","tool_request","tool_result"].includes(u),{message:"Invalid message role"}),content:k.z.union([k.z.string(),k.z.record(k.z.any()),k.z.null()]),name:k.z.string().optional(),tool_calls:k.z.array(k.z.object({id:k.z.string(),type:k.z.literal("function"),function:k.z.object({name:k.z.string(),arguments:k.z.string()})})).optional(),tool_call_id:k.z.string().optional()}).strict().refine(u=>!((u.role==="tool"||u.role==="tool_result")&&!u.tool_call_id||u.role==="assistant"&&u.content!==null&&typeof u.content!="string"||(u.role==="user"||u.role==="system")&&typeof u.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)"}),Re=k.z.array(we);var xe={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:
27
+ Intent: [Briefly describe the user's goal]
28
+ Plan: [Provide a step-by-step plan. If tools are needed, list them clearly.]
29
+ 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.
30
+ If the tools failed or provided unexpected results, explain the issue and try to answer based on available information or ask for clarification.`},re=class{getFragment(t,e){let r=xe[t];if(r===void 0)throw o.error(`[PromptManager] Prompt fragment not found: ${t}`),new d(`Prompt fragment not found: ${t}`,"PROMPT_FRAGMENT_NOT_FOUND");return e?r.replace(/\{\{([^}]+)\}\}/g,(n,a)=>{let l=a.trim(),i=e[l];return i!==void 0?String(i):n}):r}validatePrompt(t){try{return Re.parse(t)}catch(e){throw e instanceof k.ZodError?(o.error("[PromptManager] Prompt validation failed:",e.errors),new d(`Constructed prompt failed validation: ${e.message}`,"PROMPT_VALIDATION_FAILED",e)):(o.error("[PromptManager] Unexpected error during prompt validation:",e),new d(`Unexpected error during prompt validation: ${e.message}`,"PROMPT_VALIDATION_FAILED",e))}}};var ne=class{providerManager;constructor(t){this.providerManager=t,o.info("ReasoningEngine initialized with ProviderManager");}async call(t,e){let r=e.providerConfig;if(!r)throw new Error("CallOptions must include 'providerConfig' for multi-provider architecture.");o.debug(`ReasoningEngine requesting adapter for provider: ${r.providerName}, model: ${r.modelId}`,{threadId:e.threadId,traceId:e.traceId,stream:e.stream});let n;try{n=await this.providerManager.getAdapter(r),o.debug(`ReasoningEngine obtained adapter for signature: ${n.adapter.providerName}`,{threadId:e.threadId,traceId:e.traceId});}catch(a){throw o.error(`ReasoningEngine failed to get adapter: ${a.message}`,{error:a,threadId:e.threadId,traceId:e.traceId}),a}try{let a=await n.adapter.call(t,e);return async function*(){try{for await(let i of a)yield i;}finally{n.release(),o.debug(`ReasoningEngine released adapter for signature: ${n.adapter.providerName}`,{threadId:e.threadId,traceId:e.traceId});}}()}catch(a){throw o.error(`ReasoningEngine encountered an error during adapter call or stream processing: ${a.message}`,{error:a,threadId:e.threadId,traceId:e.traceId}),n.release(),o.debug(`ReasoningEngine released adapter after error for signature: ${n.adapter.providerName}`,{threadId:e.threadId,traceId:e.traceId}),a}}};var Ce=k__namespace.object({callId:k__namespace.string().min(1),toolName:k__namespace.string().min(1),arguments:k__namespace.unknown()}),Le=k__namespace.array(Ce),oe=class{async parsePlanningOutput(t){let e={},r=t.match(/Intent:\s*([\s\S]*?)(Plan:|Tool Calls:|$)/i);e.intent=r?.[1]?.trim();let n=t.match(/Plan:\s*([\s\S]*?)(Tool Calls:|$)/i);e.plan=n?.[1]?.trim();let a=t.match(/Tool Calls:\s*([\s\S]*?)$/i),l=a?.[1]?.trim();if(e.toolCalls=void 0,l){let i=null,s=null,c=/```(?:json)?\s*(\[[\s\S]*?\])\s*```|(\[[\s\S]*?\])/,g=l.match(c);if(g?i=g[1]?g[1].trim():g[2]?g[2].trim():null:o.debug(`OutputParser: No JSON array found in Tool Calls section. Content: ${l}`),i)try{let y=i.replace(/,\s*(?=]$)/,"");s=JSON.parse(y);}catch(y){o.error(`OutputParser: Failed to parse extracted JSON array. Error: ${y}. Extracted Content: ${i}. Original Content: ${l}`);}if(s!==null){let y=Le.safeParse(s);y.success?e.toolCalls=y.data:(o.warn(`OutputParser: Tool Calls JSON structure validation failed. Errors: ${y.error.toString()}. Parsed Content: ${JSON.stringify(s)}`),e.toolCalls=[]);}else e.toolCalls=[];}else a&&(e.toolCalls=[]);return !e.intent&&!e.plan&&!e.toolCalls&&o.warn(`OutputParser: Could not parse any structured data (Intent, Plan, Tool Calls) from planning output: ${t}`),e}async parseSynthesisOutput(t){return t.trim()}};var D=class{subscriptions=new Map;constructor(){}subscribe(t,e,r){let n=uuid.v4(),a={id:n,callback:t,filter:e,options:r};return this.subscriptions.set(n,a),o.debug(`New subscription added: ${n}, Filter: ${JSON.stringify(e)}, Options: ${JSON.stringify(r)}`),()=>{this.subscriptions.delete(n),o.debug(`Subscription removed: ${n}`);}}notify(t,e,r){let n=this.constructor.name;o.debug(`[${n}] notify() called. Data type: ${typeof t}, Sub count: ${this.subscriptions.size}, Options: ${JSON.stringify(e)}`),o.debug(`Notifying ${this.subscriptions.size} subscribers. Data: ${JSON.stringify(t).substring(0,100)}..., Options: ${JSON.stringify(e)}`),this.subscriptions.forEach(a=>{try{if(a.options?.threadId&&e?.targetThreadId&&a.options.threadId!==e.targetThreadId||r&&a.filter!==void 0&&!r(t,a.filter))return;o.debug(`Checks passed for sub ${a.id}. Invoking callback.`),a.callback(t);}catch(l){o.error(`Error executing subscription callback ${a.id}:`,l);}});}async getHistory(t,e){return o.warn("getHistory is not implemented in the base TypedSocket."),[]}clearAllSubscriptions(){this.subscriptions.clear(),o.debug("All subscriptions cleared.");}};var ae=class extends D{observationRepository;constructor(t){super(),this.observationRepository=t,o.debug("ObservationSocket initialized.");}notifyObservation(t){o.debug(`Notifying Observation: ${t.id} (${t.type}) for thread ${t.threadId}`),super.notify(t,{targetThreadId:t.threadId},(e,r)=>r?Array.isArray(r)?r.includes(e.type):e.type===r:true);}async getHistory(t,e){if(!this.observationRepository)return o.warn("Cannot getHistory for ObservationSocket: ObservationRepository not configured."),[];if(!e?.threadId)return o.warn("Cannot getHistory for ObservationSocket: threadId is required."),[];o.debug(`Getting history for ObservationSocket: Thread ${e.threadId}, Filter: ${JSON.stringify(t)}, Limit: ${e.limit}`);let r={};t&&(r.types=Array.isArray(t)?t:[t]),e.limit!==void 0&&o.debug(`Limit requested: ${e.limit}. Repository implementation must handle this.`);try{return await this.observationRepository.getObservations(e.threadId,r)}catch(n){return o.error(`Error fetching observation history for thread ${e.threadId} with filter ${JSON.stringify(r)}:`,n),[]}}};var se=class extends D{conversationRepository;constructor(t){super(),this.conversationRepository=t,o.debug("ConversationSocket initialized.");}notifyMessage(t){o.debug(`Notifying Message: ${t.messageId} (${t.role}) for thread ${t.threadId}`),super.notify(t,{targetThreadId:t.threadId},(e,r)=>r?Array.isArray(r)?r.includes(e.role):e.role===r:true);}async getHistory(t,e){if(!this.conversationRepository)return o.warn("Cannot getHistory for ConversationSocket: ConversationRepository not configured."),[];if(!e?.threadId)return o.warn("Cannot getHistory for ConversationSocket: threadId is required."),[];o.debug(`Getting history for ConversationSocket: Thread ${e.threadId}, Filter: ${JSON.stringify(t)}, Limit: ${e.limit}`);let r={};e.limit!==void 0&&(r.limit=e.limit),t&&o.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(e.threadId,r)}catch(n){return o.error(`Error fetching message history for thread ${e.threadId}:`,n),[]}}};var ie=class extends D{constructor(){super(),o.debug("LLMStreamSocket initialized.");}notifyStreamEvent(t){o.debug(`Notifying LLMStreamEvent: ${t.type} for thread ${t.threadId}, trace ${t.traceId}`),super.notify(t,{targetThreadId:t.threadId,targetSessionId:t.sessionId},(e,r)=>r?Array.isArray(r)?r.includes(e.type):e.type===r:true);}};var le=class{observationSocketInstance;conversationSocketInstance;llmStreamSocketInstance;constructor(t,e){this.observationSocketInstance=new ae(t),this.conversationSocketInstance=new se(e),this.llmStreamSocketInstance=new ie,o.debug("UISystem initialized with Observation, Conversation, and LLM Stream sockets.");}getObservationSocket(){return this.observationSocketInstance}getConversationSocket(){return this.conversationSocketInstance}getLLMStreamSocket(){return this.llmStreamSocketInstance}};var ge=class{config;storageAdapter=null;uiSystem=null;conversationRepository=null;observationRepository=null;stateRepository=null;conversationManager=null;stateManager=null;observationManager=null;toolRegistry=null;providerManager=null;reasoningEngine=null;promptManager=null;outputParser=null;toolSystem=null;constructor(t){if(this.config=t,!t.storage)throw new Error("AgentFactoryConfig requires 'storage' configuration.");if(!t.providers)throw new Error("AgentFactoryConfig requires 'providers' configuration.")}async initialize(){switch(this.config.storage.type){case "indexedDB":this.storageAdapter=new B({dbName:this.config.storage.dbName||"ARTDB",objectStores:["conversations","observations","state"]});break;case "memory":default:this.storageAdapter=new G;break}if(await this.storageAdapter.init?.(),this.conversationRepository=new z(this.storageAdapter),this.observationRepository=new Y(this.storageAdapter),this.stateRepository=new Q(this.storageAdapter),this.uiSystem=new le(this.observationRepository,this.conversationRepository),this.conversationManager=new X(this.conversationRepository,this.uiSystem.getConversationSocket()),this.stateManager=new W(this.stateRepository),this.observationManager=new Z(this.observationRepository,this.uiSystem.getObservationSocket()),this.toolRegistry=new ee(this.stateManager),this.config.tools)for(let t of this.config.tools)await this.toolRegistry.registerTool(t);this.providerManager=new J(this.config.providers),o.info("ProviderManager initialized."),this.reasoningEngine=new ne(this.providerManager),this.promptManager=new re,this.outputParser=new oe,this.toolSystem=new te(this.toolRegistry,this.stateManager,this.observationManager);}createAgent(){if(!this.stateManager||!this.conversationManager||!this.toolRegistry||!this.promptManager||!this.reasoningEngine||!this.outputParser||!this.observationManager||!this.toolSystem||!this.providerManager)throw new Error("AgentFactory not fully initialized. Call initialize() before creating an agent.");let t={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},e=this.config.agentCore||q;return new e(t)}getStorageAdapter(){return this.storageAdapter}getUISystem(){return this.uiSystem}getToolRegistry(){return this.toolRegistry}getStateManager(){return this.stateManager}getConversationManager(){return this.conversationManager}getObservationManager(){return this.observationManager}};async function ke(u){let t=new ge(u);await t.initialize();let e=t.createAgent(),r=t.getUISystem(),n=t.getStateManager(),a=t.getConversationManager(),l=t.getToolRegistry(),i=t.getObservationManager();if(!r||!n||!a||!l||!i)throw new Error("Failed to initialize one or more core components within AgentFactory.");return {process:e.process.bind(e),uiSystem:r,stateManager:n,conversationManager:a,toolRegistry:l,observationManager:i}}var me=class{providerName="gemini";apiKey;defaultModel;genAI;constructor(t){if(!t.apiKey)throw new Error("GeminiAdapter requires an apiKey in options.");this.apiKey=t.apiKey,this.defaultModel=t.model||"gemini-1.5-flash-latest",this.genAI=new genai.GoogleGenAI({apiKey:this.apiKey}),o.debug(`GeminiAdapter initialized with default model: ${this.defaultModel}`);}async call(t,e){let{threadId:r,traceId:n=`gemini-trace-${Date.now()}`,sessionId:a,stream:l,callContext:i,model:s}=e,c=s||this.defaultModel,g;try{g=this.translateToGemini(t);}catch(T){return o.error(`Error translating ArtStandardPrompt to Gemini format: ${T.message}`,{error:T,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:T instanceof Error?T:new Error(String(T)),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}()}let y={temperature:e.temperature,maxOutputTokens:e.max_tokens||e.maxOutputTokens,topP:e.top_p||e.topP,topK:e.top_k||e.topK,stopSequences:e.stop||e.stop_sequences||e.stopSequences};Object.keys(y).forEach(T=>y[T]===void 0&&delete y[T]),o.debug(`Calling Gemini SDK with model ${c}, stream: ${!!l}`,{threadId:r,traceId:n});let A=this.genAI;return async function*(){let T=Date.now(),O,p,b,h;try{if(l){let I=await A.models.generateContentStream({model:c,contents:g,config:y});for await(let R of I){h=R,O||(O=Date.now()-T);let P=R.text;P&&(yield {type:"TOKEN",data:P,threadId:r,traceId:n,sessionId:a,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"}),R.usageMetadata&&(o.debug("Gemini stream chunk usageMetadata:",{usageMetadata:R.usageMetadata,threadId:r,traceId:n}),p={...p||{},...R.usageMetadata});}let w=Date.now()-T;o.debug("Gemini stream finished processing chunks.",{totalGenerationTimeMs:w,threadId:r,traceId:n}),h?(b=h.candidates?.[0]?.finishReason,p=h.usageMetadata,o.debug("Gemini stream - Extracted from last chunk:",{finishReason:b,usageMetadata:p,threadId:r,traceId:n})):o.warn("Gemini stream - No last chunk found after loop.",{threadId:r,traceId:n});let N=p||{};yield {type:"METADATA",data:{stopReason:b,inputTokens:N?.promptTokenCount,outputTokens:N?.candidatesTokenCount,timeToFirstTokenMs:O,totalGenerationTimeMs:w,providerRawUsage:N,traceId:n},threadId:r,traceId:n,sessionId:a};}else {let I=await A.models.generateContent({model:c,contents:g,config:y}),w=I.candidates?.[0],N=I.text,_=w?.finishReason,R=I.usageMetadata,P=Date.now()-T;if(!w||!N){if(I.promptFeedback?.blockReason){o.error("Gemini SDK call blocked.",{feedback:I.promptFeedback,threadId:r,traceId:n}),yield {type:"ERROR",data:new Error(`Gemini API call blocked: ${I.promptFeedback.blockReason}`),threadId:r,traceId:n,sessionId:a};return}o.error("Invalid response structure from Gemini SDK: No text content found",{responseData:I,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:a};return}let M=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"LLM_RESPONSE";yield {type:"TOKEN",data:N.trim(),threadId:r,traceId:n,sessionId:a,tokenType:M},yield {type:"METADATA",data:{stopReason:_,inputTokens:R?.promptTokenCount,outputTokens:R?.candidatesTokenCount,totalGenerationTimeMs:P,providerRawUsage:R,traceId:n},threadId:r,traceId:n,sessionId:a};}yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}catch(I){o.error(`Error during Gemini SDK call: ${I.message}`,{error:I,threadId:r,traceId:n}),yield {type:"ERROR",data:I instanceof Error?I:new Error(String(I)),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}}()}translateToGemini(t){let e=[],r=null;for(let n of t){let a,l=[];switch(n.role){case "system":typeof n.content=="string"?r=n.content:o.warn("GeminiAdapter: Ignoring non-string system prompt content.",{content:n.content});continue;case "user":{a="user";let i="";r&&(i+=r+`
31
+
32
+ `,r=null),typeof n.content=="string"?i+=n.content:(o.warn("GeminiAdapter: Stringifying non-string user content.",{content:n.content}),i+=JSON.stringify(n.content)),l.push({text:i});break}case "assistant":a="model",typeof n.content=="string"&&n.content.trim()!==""&&l.push({text:n.content}),n.tool_calls&&n.tool_calls.length>0&&n.tool_calls.forEach(i=>{i.type==="function"?l.push({functionCall:{name:i.function.name,args:JSON.parse(i.function.arguments||"{}")}}):o.warn(`GeminiAdapter: Skipping unsupported tool call type: ${i.type}`);}),l.length===0&&l.push({text:""});break;case "tool_result":if(a="user",!n.tool_call_id||!n.name)throw new d("GeminiAdapter: 'tool_result' message missing required 'tool_call_id' or 'name'.","PROMPT_TRANSLATION_FAILED");l.push({functionResponse:{name:n.name,response:{content:n.content}}});break;case "tool_request":o.debug("GeminiAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls.");continue;default:o.warn(`GeminiAdapter: Skipping message with unhandled role: ${n.role}`);continue}e.push({role:a,parts:l});}return r&&(o.warn("GeminiAdapter: System prompt provided but no user message found to merge it into. Adding as a separate initial user message."),e.unshift({role:"user",parts:[{text:r}]})),e.length>0&&e[0].role==="model"&&(o.warn("Gemini conversation history starts with 'model' role. Prepending a dummy 'user' turn.",{firstRole:e[0].role}),e.unshift({role:"user",parts:[{text:"(Initial context)"}]})),e}};var ue=class{providerName="openai";apiKey;model;apiBaseUrl;constructor(t){if(!t.apiKey)throw new Error("OpenAIAdapter requires an apiKey in options.");this.apiKey=t.apiKey,this.model=t.model||"gpt-3.5-turbo",this.apiBaseUrl=t.apiBaseUrl||"https://api.openai.com/v1",o.debug(`OpenAIAdapter initialized with model: ${this.model}`);}async call(t,e){let{threadId:r,traceId:n=`openai-trace-${Date.now()}`,sessionId:a,stream:l,callContext:i,model:s}=e,c=s||this.model,g;try{g=this.translateToOpenAI(t);}catch(f){return o.error(`Error translating ArtStandardPrompt to OpenAI format: ${f.message}`,{error:f,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:f instanceof d?f:new d(`Prompt translation failed: ${f.message}`,"PROMPT_TRANSLATION_FAILED",f),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}()}let y=`${this.apiBaseUrl}/chat/completions`,A={model:c,messages:g,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,frequency_penalty:e.frequency_penalty,presence_penalty:e.presence_penalty,stop:e.stop||e.stop_sequences,stream:!!l};Object.keys(A).forEach(f=>A[f]===void 0&&delete A[f]),o.debug(`Calling OpenAI API: ${y} with model ${c}, stream: ${!!l}`,{threadId:r,traceId:n});try{let f=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(A)});if(!f.ok){let T=await f.text();return o.error(`OpenAI API request failed with status ${f.status}: ${T}`,{threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new d(`OpenAI API request failed: ${f.status} ${f.statusText} - ${T}`,"LLM_PROVIDER_ERROR",new Error(T)),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}()}if(l&&f.body)return this.processStream(f.body,e);{let T=await f.json(),O=T.choices?.[0];if(!O?.message)return o.error("Invalid response structure from OpenAI API: No message found",{responseData:T,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new d("Invalid response structure from OpenAI API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(T))),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}();let p=O.message;return p.tool_calls&&o.debug("OpenAI response included tool calls (non-streaming)",{toolCalls:p.tool_calls,threadId:r,traceId:n}),o.debug(`OpenAI API call successful. Finish reason: ${O.finish_reason}`,{threadId:r,traceId:n}),async function*(){let h=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(p.content??"").trim(),threadId:r,traceId:n,sessionId:a,tokenType:h},yield {type:"METADATA",data:{stopReason:O.finish_reason,inputTokens:T.usage?.prompt_tokens,outputTokens:T.usage?.completion_tokens,providerRawUsage:{usage:T.usage,finish_reason:O.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}()}}catch(f){return o.error(`Error during OpenAI API call: ${f.message}`,{error:f,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:f instanceof d?f:new d(f.message,"LLM_PROVIDER_ERROR",f),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}()}}async*processStream(t,e){let{threadId:r,traceId:n,sessionId:a,callContext:l}=e,i=Date.now(),s,c=0,g,y=void 0,A,f=t.pipeThrough(new TextDecoderStream).getReader(),T="",O=false;for(;!O;)try{let{value:h,done:I}=await f.read();if(O=I,O)break;T+=h;let w=T.split(`
33
+ `);for(let N=0;N<w.length-1;N++){let _=w[N].trim();if(_!==""&&_.startsWith("data: ")){let R=_.substring(6);if(R==="[DONE]"){O=!0;break}try{let M=JSON.parse(R).choices?.[0];if(!M)continue;let x=M.delta?.content;if(typeof x=="string"&&x.length>0){let v=Date.now();s===void 0&&(s=v-i),c++,yield {type:"TOKEN",data:x,threadId:r??"",traceId:n??"",sessionId:a,tokenType:l==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"};}let $=M.delta?.tool_calls;$&&(A||(A=[]),$.forEach(v=>{v.index!==void 0&&(A[v.index]||(A[v.index]={}),v.id&&(A[v.index].id=v.id),v.type&&(A[v.index].type=v.type),v.function&&(A[v.index].function||(A[v.index].function={}),v.function.name&&(A[v.index].function.name=v.function.name),v.function.arguments&&(A[v.index].function.arguments=(A[v.index].function.arguments||"")+v.function.arguments)));}),o.debug("OpenAI stream tool call delta:",{deltaToolCalls:$,threadId:r,traceId:n})),M.finish_reason&&(g=M.finish_reason,o.debug(`OpenAI stream finish reason received: ${g}`,{threadId:r,traceId:n}));}catch(P){o.warn(`Failed to parse OpenAI stream chunk: ${R}`,{parseError:P,threadId:r,traceId:n});}}}T=w[w.length-1];}catch(h){o.error(`Error reading OpenAI stream: ${h.message}`,{error:h,threadId:r,traceId:n}),yield {type:"ERROR",data:h instanceof d?h:new d(`Error reading OpenAI stream: ${h.message}`,"LLM_PROVIDER_ERROR",h),threadId:r??"",traceId:n??"",sessionId:a??""},O=true;}let p=Date.now()-i;yield {type:"METADATA",data:{stopReason:g,outputTokens:c>0?c:void 0,timeToFirstTokenMs:s,totalGenerationTimeMs:p,providerRawUsage:{finish_reason:g,usage:y,aggregatedToolCalls:A},traceId:n},threadId:r??"",traceId:n??"",sessionId:a??""},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:a??""},o.debug("OpenAI stream processing finished.",{threadId:r,traceId:n});}translateToOpenAI(t){return t.map(e=>{switch(e.role){case "system":return typeof e.content!="string"?(o.warn("OpenAIAdapter: System message content is not a string. Stringifying.",{content:e.content}),{role:"system",content:String(e.content)}):{role:"system",content:e.content};case "user":return typeof e.content!="string"?(o.warn("OpenAIAdapter: User message content is not a string. Stringifying.",{content:e.content}),{role:"user",content:String(e.content)}):{role:"user",content:e.content};case "assistant":{let r={role:"assistant",content:typeof e.content=="string"?e.content:null};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new d(`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(!e.tool_call_id)throw new d("OpenAIAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return typeof e.content!="string"&&o.warn("OpenAIAdapter: Tool result content is not a string. Stringifying.",{content:e.content}),{role:"tool",tool_call_id:e.tool_call_id,content:String(e.content)}}case "tool_request":throw o.debug("OpenAIAdapter: Skipping 'tool_request' role message as it's handled by assistant's tool_calls."),new d("OpenAIAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw o.warn(`OpenAIAdapter: Skipping message with unknown role: ${e.role}`),new d(`OpenAIAdapter: Unknown message role '${e.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var fe=class{providerName="anthropic";apiKey;model;apiVersion;apiBaseUrl;defaultMaxTokens=1024;constructor(t){if(!t.apiKey)throw new Error("AnthropicAdapter requires an apiKey in options.");this.apiKey=t.apiKey,this.model=t.model||"claude-3-haiku-20240307",this.apiVersion=t.apiVersion||"2023-06-01",this.apiBaseUrl=t.apiBaseUrl||"https://api.anthropic.com/v1",o.debug(`AnthropicAdapter initialized with model: ${this.model}, version: ${this.apiVersion}`);}async call(t,e){let{threadId:r,traceId:n=`anthropic-trace-${Date.now()}`,sessionId:a,stream:l,callContext:i,model:s}=e,c=s||this.model;if(l)return o.warn("AnthropicAdapter: Streaming requested but not implemented. Returning error stream.",{threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new d("Streaming is not yet implemented for the AnthropicAdapter.","LLM_PROVIDER_ERROR"),threadId:r??"",traceId:n??"",sessionId:a},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:a};}();let g=e.max_tokens||e.maxOutputTokens||e.max_tokens_to_sample||this.defaultMaxTokens;if(!g){let h=new d("Anthropic API requires 'max_tokens' or equivalent ('maxOutputTokens', 'max_tokens_to_sample') in call options.","INVALID_CONFIG");return async function*(){yield {type:"ERROR",data:h,threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}()}let y,A;try{let h=this.translateToAnthropic(t);y=h.systemPrompt,A=h.messages;}catch(h){return o.error(`Error translating ArtStandardPrompt to Anthropic format: ${h.message}`,{error:h,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:h instanceof d?h:new d(`Prompt translation failed: ${h.message}`,"PROMPT_TRANSLATION_FAILED",h),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}()}let f=`${this.apiBaseUrl}/messages`,T={model:c,messages:A,system:y,max_tokens:g,temperature:e.temperature,top_p:e.top_p||e.topP,top_k:e.top_k||e.topK,stop_sequences:e.stop||e.stop_sequences||e.stopSequences,stream:false};Object.keys(T).forEach(h=>{let I=h;I!=="max_tokens"&&T[I]===void 0&&delete T[I];}),o.debug(`Calling Anthropic API (non-streaming): ${f} with model ${this.model}`,{threadId:r,traceId:n});let O=this.apiKey,p=this.apiVersion;return async function*(){try{let h=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":O,"anthropic-version":p},body:JSON.stringify(T)});if(!h.ok){let M=await h.text(),x=M;try{let v=JSON.parse(M);v?.error?.message&&(x=v.error.message);}catch{}yield {type:"ERROR",data:new d(`Anthropic API request failed: ${h.status} ${h.statusText} - ${x}`,"LLM_PROVIDER_ERROR",new Error(M)),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};return}let I=await h.json(),N=I.content?.filter(M=>M.type==="text")?.map(M=>M.text).join(`
34
+ `)??"",_=I.content?.filter(M=>M.type==="tool_use");if(_&&_.length>0&&o.debug("Anthropic response included tool use requests",{toolUseBlocks:_,threadId:r,traceId:n}),I.stop_reason!=="tool_use"&&N===""&&(!_||_.length===0)){yield {type:"ERROR",data:new d("Invalid response structure from Anthropic API: No text content found and stop reason is not tool_use.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(I))),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};return}o.debug(`Anthropic API call successful. Stop Reason: ${I.stop_reason}`,{threadId:r,traceId:n});let R=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:N.trim(),threadId:r,traceId:n,sessionId:a,tokenType:R},yield {type:"METADATA",data:{inputTokens:I.usage?.input_tokens,outputTokens:I.usage?.output_tokens,stopReason:I.stop_reason??void 0,providerRawUsage:{usage:I.usage,stop_reason:I.stop_reason,stop_sequence:I.stop_sequence},traceId:n},threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}catch(h){o.error(`Error during Anthropic API call: ${h.message}`,{error:h,threadId:r,traceId:n}),yield {type:"ERROR",data:h instanceof d?h:new d(h.message,"LLM_PROVIDER_ERROR",h),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}}()}translateToAnthropic(t){let e,r=[],n=null;for(let i=0;i<t.length;i++){let s=t[i];if(s.role==="system"&&!e){typeof s.content!="string"?(o.warn("AnthropicAdapter: System message content is not a string. Stringifying.",{content:s.content}),e=String(s.content)):e=s.content;continue}if(s.role==="system"&&e){o.warn("AnthropicAdapter: Multiple system messages found. Only the first one is used by Anthropic. Skipping subsequent ones.");continue}if(s.role==="user"){if(n==="user"){let c=r[r.length-1];if(c&&c.role==="user"){let g=typeof c.content=="string"?[{type:"text",text:c.content}]:c.content,y=typeof s.content=="string"?[{type:"text",text:s.content}]:this.mapArtContentToAnthropicBlocks(s.content,s.role);c.content=[...g,...y],o.debug("AnthropicAdapter: Merged consecutive user messages.");continue}}r.push({role:"user",content:typeof s.content=="string"?s.content:this.mapArtContentToAnthropicBlocks(s.content,s.role)}),n="user";}else if(s.role==="assistant"){if(n==="assistant"){let c=r[r.length-1];if(c&&c.role==="assistant"){let g=typeof c.content=="string"?[{type:"text",text:c.content}]:c.content,y=typeof s.content=="string"?[{type:"text",text:s.content}]:this.mapArtContentToAnthropicBlocks(s.content,s.role,s.tool_calls);c.content=[...g,...y],o.debug("AnthropicAdapter: Merged consecutive assistant messages.");continue}}r.push({role:"assistant",content:typeof s.content=="string"?s.content:this.mapArtContentToAnthropicBlocks(s.content,s.role,s.tool_calls)}),n="assistant";}else if(s.role==="tool_result"){if(!s.tool_call_id)throw new d("AnthropicAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");let c={type:"tool_result",tool_use_id:s.tool_call_id,content:String(s.content)};if(n==="user"){let g=r[r.length-1];if(g&&g.role==="user"){let y=typeof g.content=="string"?[{type:"text",text:g.content}]:g.content;g.content=[...y,c];}else r.push({role:"user",content:[c]}),n="user";}else r.push({role:"user",content:[c]}),n="user";}else throw s.role==="tool_request"?new d("AnthropicAdapter: Unexpected 'tool_request' role encountered during translation. These should be part of an 'assistant' message's tool_calls.","PROMPT_TRANSLATION_FAILED"):new d(`AnthropicAdapter: Unknown message role '${s.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}let a=t[t.length-1],l=r[r.length-1];if(a?.role==="assistant"&&a.tool_calls&&l?.role!=="user"&&o.debug("AnthropicAdapter: Prompt ends with assistant tool calls, but last translated message is not 'user'. This might be expected if waiting for tool execution."),!e&&r.length>0&&r[0].role!=="user")throw new d("AnthropicAdapter: First message must be 'user' if no system prompt is provided.","PROMPT_TRANSLATION_FAILED");return {systemPrompt:e,messages:r}}mapArtContentToAnthropicBlocks(t,e,r){let n=[];return typeof t=="string"&&t.trim()!==""?n.push({type:"text",text:t}):t!==null&&typeof t!="string"&&(o.warn(`AnthropicAdapter: Non-string, non-null content found for ${e} message. Stringifying.`,{content:t}),n.push({type:"text",text:JSON.stringify(t)})),e==="assistant"&&r&&r.length>0&&r.forEach(a=>{if(a.type!=="function"){o.warn(`AnthropicAdapter: Skipping non-function tool call type: ${a.type}`);return}try{n.push({type:"tool_use",id:a.id,name:a.function.name,input:JSON.parse(a.function.arguments||"{}")});}catch(l){throw new d(`AnthropicAdapter: Failed to parse tool call arguments for tool ${a.function.name} (ID: ${a.id}). Arguments must be valid JSON. Error: ${l.message}`,"PROMPT_TRANSLATION_FAILED",l)}}),n}};var he=class{providerName="openrouter";apiKey;model;apiBaseUrl;siteUrl;appName;constructor(t){if(!t.apiKey)throw new Error("OpenRouterAdapter requires an apiKey in options.");if(!t.model)throw new Error("OpenRouterAdapter requires a model identifier in options (e.g., 'google/gemini-pro').");this.apiKey=t.apiKey,this.model=t.model,this.apiBaseUrl=t.apiBaseUrl||"https://openrouter.ai/api/v1",this.siteUrl=t.siteUrl,this.appName=t.appName,o.debug(`OpenRouterAdapter initialized for model: ${this.model}`);}async call(t,e){let{threadId:r,traceId:n=`openrouter-trace-${Date.now()}`,sessionId:a,stream:l,callContext:i,model:s}=e,c=s||this.model;if(l)return o.warn("OpenRouterAdapter: Streaming requested but not implemented. Returning error stream.",{threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new d("Streaming is not yet implemented for the OpenRouterAdapter.","LLM_PROVIDER_ERROR"),threadId:r??"",traceId:n??"",sessionId:a},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:a};}();let g;try{g=this.translateToOpenAI(t);}catch(p){return o.error(`Error translating ArtStandardPrompt to OpenRouter/OpenAI format: ${p.message}`,{error:p,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:p instanceof d?p:new d(`Prompt translation failed: ${p.message}`,"PROMPT_TRANSLATION_FAILED",p),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}()}let y=`${this.apiBaseUrl}/chat/completions`,A=e.stop||e.stop_sequences||e.stopSequences,f={model:c,messages:g,temperature:e.temperature,max_tokens:e.max_tokens||e.maxOutputTokens,top_p:e.top_p||e.topP,stop:A,stream:false};Object.keys(f).forEach(p=>f[p]===void 0&&delete f[p]);let T={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return this.siteUrl&&(T["HTTP-Referer"]=this.siteUrl),this.appName&&(T["X-Title"]=this.appName),o.debug(`Calling OpenRouter API (non-streaming): ${y} with model ${this.model}`,{threadId:r,traceId:n}),async function*(){try{let p=await fetch(y,{method:"POST",headers:T,body:JSON.stringify(f)});if(!p.ok){let R=await p.text(),P=R;try{let x=JSON.parse(R);x?.error?.message&&(P=x.error.message);}catch{}yield {type:"ERROR",data:new d(`OpenRouter API request failed: ${p.status} ${p.statusText} - ${P}`,"LLM_PROVIDER_ERROR",new Error(R)),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};return}let b=await p.json(),h=b.choices?.[0];if(!h?.message){yield {type:"ERROR",data:new d("Invalid response structure from OpenRouter API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(b))),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};return}let I=h.message;I.tool_calls&&o.debug("OpenRouter response included tool calls (non-streaming)",{toolCalls:I.tool_calls,threadId:r,traceId:n}),o.debug(`OpenRouter API call successful. Finish reason: ${h.finish_reason}`,{threadId:r,traceId:n});let w=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(I.content??"").trim(),threadId:r,traceId:n,sessionId:a,tokenType:w},yield {type:"METADATA",data:{inputTokens:b.usage?.prompt_tokens,outputTokens:b.usage?.completion_tokens,stopReason:h.finish_reason,providerRawUsage:{usage:b.usage,finish_reason:h.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}catch(p){o.error(`Error during OpenRouter API call: ${p.message}`,{error:p,threadId:r,traceId:n}),yield {type:"ERROR",data:p instanceof d?p:new d(p.message,"LLM_PROVIDER_ERROR",p),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}}()}translateToOpenAI(t){return t.map(e=>{switch(e.role){case "system":return typeof e.content!="string"?(o.warn("OpenRouterAdapter: System message content is not a string. Stringifying.",{content:e.content}),{role:"system",content:String(e.content)}):{role:"system",content:e.content};case "user":return typeof e.content!="string"?(o.warn("OpenRouterAdapter: User message content is not a string. Stringifying.",{content:e.content}),{role:"user",content:String(e.content)}):{role:"user",content:e.content};case "assistant":{let r={role:"assistant",content:typeof e.content=="string"?e.content:null};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new d(`OpenRouterAdapter: Invalid tool_call structure in assistant message. ID: ${n.id}`,"PROMPT_TRANSLATION_FAILED");return {id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}})),r.content===""&&!r.tool_calls&&(r.content=null),r.content===""&&r.tool_calls&&(r.content=null),typeof r.content!="string"&&r.content!==null&&(r.content=null),r}case "tool_result":{if(!e.tool_call_id)throw new d("OpenRouterAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return typeof e.content!="string"&&o.warn("OpenRouterAdapter: Tool result content is not a string. Stringifying.",{content:e.content}),{role:"tool",tool_call_id:e.tool_call_id,content:String(e.content)}}case "tool_request":throw new d("OpenRouterAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new d(`OpenRouterAdapter: Unknown message role '${e.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var ye=class{providerName="deepseek";apiKey;model;apiBaseUrl;constructor(t){if(!t.apiKey)throw new Error("DeepSeekAdapter requires an apiKey in options.");this.apiKey=t.apiKey,this.model=t.model||"deepseek-chat",this.apiBaseUrl=t.apiBaseUrl||"https://api.deepseek.com/v1",o.debug(`DeepSeekAdapter initialized with model: ${this.model}`);}async call(t,e){let{threadId:r,traceId:n=`deepseek-trace-${Date.now()}`,sessionId:a,stream:l,callContext:i,model:s}=e,c=s||this.model;if(l)return o.warn("DeepSeekAdapter: Streaming requested but not implemented. Returning error stream.",{threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:new d("Streaming is not yet implemented for the DeepSeekAdapter.","LLM_PROVIDER_ERROR"),threadId:r??"",traceId:n??"",sessionId:a},yield {type:"END",data:null,threadId:r??"",traceId:n??"",sessionId:a};}();let g;try{g=this.translateToOpenAI(t);}catch(p){return o.error(`Error translating ArtStandardPrompt to DeepSeek/OpenAI format: ${p.message}`,{error:p,threadId:r,traceId:n}),async function*(){yield {type:"ERROR",data:p instanceof d?p:new d(`Prompt translation failed: ${p.message}`,"PROMPT_TRANSLATION_FAILED",p),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}()}let y=`${this.apiBaseUrl}/chat/completions`,A=e.stop||e.stop_sequences||e.stopSequences,f={model:c,messages:g,temperature:e.temperature,max_tokens:e.max_tokens||e.maxOutputTokens,top_p:e.top_p||e.topP,stop:A,stream:false};Object.keys(f).forEach(p=>f[p]===void 0&&delete f[p]);let T={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return o.debug(`Calling DeepSeek API (non-streaming): ${y} with model ${this.model}`,{threadId:r,traceId:n}),async function*(){try{let p=await fetch(y,{method:"POST",headers:T,body:JSON.stringify(f)});if(!p.ok){let R=await p.text(),P=R;try{let x=JSON.parse(R);x?.error?.message&&(P=x.error.message);}catch{}yield {type:"ERROR",data:new d(`DeepSeek API request failed: ${p.status} ${p.statusText} - ${P}`,"LLM_PROVIDER_ERROR",new Error(R)),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};return}let b=await p.json(),h=b.choices?.[0];if(!h?.message){yield {type:"ERROR",data:new d("Invalid response structure from DeepSeek API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(b))),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};return}let I=h.message;I.tool_calls&&o.debug("DeepSeek response included tool calls (non-streaming)",{toolCalls:I.tool_calls,threadId:r,traceId:n}),o.debug(`DeepSeek API call successful. Finish reason: ${h.finish_reason}`,{threadId:r,traceId:n});let w=i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(I.content??"").trim(),threadId:r,traceId:n,sessionId:a,tokenType:w},yield {type:"METADATA",data:{inputTokens:b.usage?.prompt_tokens,outputTokens:b.usage?.completion_tokens,stopReason:h.finish_reason,providerRawUsage:{usage:b.usage,finish_reason:h.finish_reason},traceId:n},threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}catch(p){o.error(`Error during DeepSeek API call: ${p.message}`,{error:p,threadId:r,traceId:n}),yield {type:"ERROR",data:p instanceof d?p:new d(p.message,"LLM_PROVIDER_ERROR",p),threadId:r,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:r,traceId:n,sessionId:a};}}()}translateToOpenAI(t){return t.map(e=>{switch(e.role){case "system":return typeof e.content!="string"?(o.warn("DeepSeekAdapter: System message content is not a string. Stringifying.",{content:e.content}),{role:"system",content:String(e.content)}):{role:"system",content:e.content};case "user":return typeof e.content!="string"?(o.warn("DeepSeekAdapter: User message content is not a string. Stringifying.",{content:e.content}),{role:"user",content:String(e.content)}):{role:"user",content:e.content};case "assistant":{let r={role:"assistant",content:typeof e.content=="string"?e.content:null};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new d(`DeepSeekAdapter: Invalid tool_call structure in assistant message. ID: ${n.id}`,"PROMPT_TRANSLATION_FAILED");return {id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}})),r.content===""&&!r.tool_calls&&(r.content=null),r.content===""&&r.tool_calls&&(r.content=null),typeof r.content!="string"&&r.content!==null&&(r.content=null),r}case "tool_result":{if(!e.tool_call_id)throw new d("DeepSeekAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");return typeof e.content!="string"&&o.warn("DeepSeekAdapter: Tool result content is not a string. Stringifying.",{content:e.content}),{role:"tool",tool_call_id:e.tool_call_id,content:String(e.content)}}case "tool_request":throw new d("DeepSeekAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new d(`DeepSeekAdapter: Unknown message role '${e.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var Ue={sqrt:m__namespace.sqrt,cbrt:m__namespace.cbrt,abs:m__namespace.abs,pow:m__namespace.pow,exp:m__namespace.exp,log:m__namespace.log,log10:m__namespace.log10,log2:m__namespace.log2,sin:m__namespace.sin,cos:m__namespace.cos,tan:m__namespace.tan,asin:m__namespace.asin,acos:m__namespace.acos,atan:m__namespace.atan,atan2:m__namespace.atan2,round:m__namespace.round,floor:m__namespace.floor,ceil:m__namespace.ceil,mod:m__namespace.mod,mean:m__namespace.mean,median:m__namespace.median,std:m__namespace.std,variance:m__namespace.variance,max:m__namespace.max,min:m__namespace.min,factorial:m__namespace.factorial,gamma:m__namespace.gamma,combinations:m__namespace.combinations,permutations:m__namespace.permutations,format:m__namespace.format},Ae=class u{static toolName="calculator";resultStore=new Map;schema={name:u.toolName,description:`Evaluates mathematical expressions using a sandboxed mathjs environment.
35
+ You can reference previous calculation results using the 'ans' variable.
45
36
  Supports standard operators (+, -, *, /, %, ^), variables via 'scope', complex numbers, and the following allowed functions:
46
- sqrt, cbrt, abs, pow, exp, log, log10, log2, sin, cos, tan, asin, acos, atan, atan2, round, floor, ceil, mod.`,inputSchema:{type:"object",properties:{expression:{type:"string",description:'The mathematical expression to evaluate (e.g., "2 + 2", "sqrt(a)", "a * b", "sqrt(-4)").'},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"}]};async execute(e,t){let r=e.expression,o={...ve,...e.scope||{}},a=t.traceId||"calculator-call";s.debug(`CalculatorTool executing with expression: "${r}" and combined scope keys: ${Object.keys(o).join(", ")}`,{callId:a,context:t});try{let i=g.evaluate(r,o),n;if(typeof i=="number"&&Number.isFinite(i))n=i;else if(g__namespace.isComplex(i))n=i.toString();else throw new Error(`Evaluation resulted in an unsupported type: ${g__namespace.typeOf(i)}`);return s.info(`CalculatorTool evaluated "${r}" to ${n}`,{callId:a}),{callId:a,toolName:this.schema.name,status:"success",output:{result:n}}}catch(i){return s.error(`CalculatorTool failed to evaluate expression "${r}": ${i.message}`,{callId:a,error:i}),{callId:a,toolName:this.schema.name,status:"error",error:`Failed to evaluate expression: ${i.message}`}}}};var dr="0.2.4";exports.AnthropicAdapter=R;exports.CalculatorTool=te;exports.DeepSeekAdapter=$;exports.GeminiAdapter=C;exports.InMemoryStorageAdapter=x;exports.IndexedDBStorageAdapter=w;exports.LogLevel=oe;exports.Logger=s;exports.MessageRole=W;exports.ObservationType=Q;exports.OpenAIAdapter=P;exports.OpenRouterAdapter=E;exports.PESAgent=A;exports.VERSION=dr;exports.createArtInstance=ye;exports.generateUUID=S;//# sourceMappingURL=index.cjs.map
37
+ sqrt, cbrt, abs, pow, exp, log, log10, log2, sin, cos, tan, asin, acos, atan, atan2, round, floor, ceil, mod,
38
+ 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(t,e){let r=t.expression,n=e.threadId||"default-thread",a=this.resultStore.get(n),l={...Ue,...t.scope||{},...a!==void 0?{ans:a}:{}},i=e.traceId||"calculator-call";o.debug(`CalculatorTool executing with expression: "${r}" and combined scope keys: ${Object.keys(l).join(", ")}`,{callId:i,context:e});try{let s=m.evaluate(r,l),c;if(typeof s=="number"&&Number.isFinite(s))c=s;else if(m__namespace.isComplex(s))c=s.toString();else throw new Error(`Evaluation resulted in an unsupported type: ${m__namespace.typeOf(s)}`);return this.resultStore.set(n,s),o.info(`CalculatorTool evaluated "${r}" to ${c}`,{callId:i}),{callId:i,toolName:this.schema.name,status:"success",output:{result:c}}}catch(s){return o.error(`CalculatorTool failed to evaluate expression "${r}": ${s.message}`,{callId:i,error:s}),{callId:i,toolName:this.schema.name,status:"error",error:`Failed to evaluate expression: ${s.message}`}}}};var zr="0.2.4";exports.AnthropicAdapter=fe;exports.CalculatorTool=Ae;exports.DeepSeekAdapter=ye;exports.GeminiAdapter=me;exports.InMemoryStorageAdapter=G;exports.IndexedDBStorageAdapter=B;exports.LogLevel=Te;exports.Logger=o;exports.MessageRole=Ie;exports.ModelCapability=Se;exports.ObservationType=ce;exports.OpenAIAdapter=ue;exports.OpenRouterAdapter=he;exports.PESAgent=q;exports.VERSION=zr;exports.createArtInstance=ke;exports.generateUUID=F;//# sourceMappingURL=index.cjs.map
47
39
  //# sourceMappingURL=index.cjs.map