art-framework 0.2.4
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/LICENSE +21 -0
- package/README.md +0 -0
- package/dist/index.cjs +47 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +937 -0
- package/dist/index.d.ts +937 -0
- package/dist/index.js +47 -0
- package/dist/index.js.map +1 -0
- package/package.json +71 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 [Hashan Wickramasinghe]
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
Binary file
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
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}}
|
|
10
|
+
|
|
11
|
+
Available Tools:
|
|
12
|
+
{{tools}}
|
|
13
|
+
|
|
14
|
+
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
|
+
Respond in the following format:
|
|
16
|
+
Intent: [Briefly describe the user's goal]
|
|
17
|
+
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}}
|
|
26
|
+
|
|
27
|
+
Original Intent:
|
|
28
|
+
{{intent}}
|
|
29
|
+
|
|
30
|
+
Execution Plan:
|
|
31
|
+
{{plan}}
|
|
32
|
+
|
|
33
|
+
Tool Execution Results:
|
|
34
|
+
{{toolResults}}
|
|
35
|
+
|
|
36
|
+
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.
|
|
45
|
+
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
|
|
47
|
+
//# sourceMappingURL=index.cjs.map
|