art-framework 0.2.5 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +22 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +33 -25
- package/dist/index.d.ts +33 -25
- package/dist/index.js +22 -17
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -1,39 +1,44 @@
|
|
|
1
|
-
import {v4}from'uuid';import
|
|
2
|
-
Caused by: ${this.originalError.stack||this.originalError.toString()}`),
|
|
1
|
+
import {v4}from'uuid';import Le from'ajv';import*as $ from'zod';import {z as z$1,ZodError}from'zod';import {GoogleGenAI}from'@google/genai';import {Anthropic}from'@anthropic-ai/sdk';import*as h from'mathjs';import {evaluate}from'mathjs';var c=class g extends Error{code;originalError;constructor(r,e,t){super(r),this.name="ARTError",this.code=e,this.originalError=t,Error.captureStackTrace&&Error.captureStackTrace(this,g);}toString(){let r=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(r+=`
|
|
2
|
+
Caused by: ${this.originalError.stack||this.originalError.toString()}`),r}},j=class extends c{constructor(r){super(`Unknown provider requested: ${r}`,"UNKNOWN_PROVIDER"),this.name="UnknownProviderError";}},V=class extends c{constructor(r,e){super(`Cannot activate local provider '${r}'. Local provider '${e}' is already active.`,"LOCAL_PROVIDER_CONFLICT"),this.name="LocalProviderConflictError";}},J=class extends c{constructor(r,e){super(`Local provider instance '${r}:${e}' is currently busy.`,"LOCAL_INSTANCE_BUSY"),this.name="LocalInstanceBusyError";}};var Y=class extends c{constructor(r,e){super(`Failed to instantiate adapter for provider '${r}'.`,"ADAPTER_INSTANTIATION_ERROR",e),this.name="AdapterInstantiationError";}};var z=class{availableProviders;maxParallelApiInstancesPerProvider;apiInstanceIdleTimeoutMs;managedInstances;requestQueue;constructor(r){this.availableProviders=new Map(r.availableProviders.map(e=>[e.name,e])),this.maxParallelApiInstancesPerProvider=r.maxParallelApiInstancesPerProvider??5,this.apiInstanceIdleTimeoutMs=(r.apiInstanceIdleTimeoutSeconds??300)*1e3,this.managedInstances=new Map,this.requestQueue=[];}_getConfigSignature(r){let e=r.adapterOptions?Object.keys(r.adapterOptions).sort().reduce((t,n)=>(t[n]=r.adapterOptions[n],t),{}):{};return JSON.stringify({providerName:r.providerName,modelId:r.modelId,adapterOptions:e})}getAvailableProviders(){return Array.from(this.availableProviders.keys())}async getAdapter(r){let e=this._getConfigSignature(r),t=this.managedInstances.get(e);if(t&&t.state==="idle"){t.state="active",t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0),console.log(`Reusing idle instance for signature: ${e}`);let l=()=>this._releaseAdapter(e);return {adapter:t.adapter,release:l}}let n=this.availableProviders.get(r.providerName);if(!n)throw new j(r.providerName);if(n.isLocal){let l;for(let[f,y]of this.managedInstances.entries()){let T=this.availableProviders.get(y.configSignature.split('"providerName":"')[1].split('"')[0]);if(T?.isLocal){if(y.state==="active")throw f!==e?new V(r.providerName,T.name):new J(r.providerName,r.modelId);y.state==="idle"&&f!==e&&(l=y);}}l&&(console.log(`Evicting idle local instance with different signature: ${l.configSignature}`),await this._evictInstance(l.configSignature));}if(!n.isLocal&&Array.from(this.managedInstances.values()).filter(f=>{let y=this.availableProviders.get(f.configSignature.split('"providerName":"')[1].split('"')[0]);return y&&!y.isLocal&&f.state==="active"&&y.name===r.providerName}).length>=this.maxParallelApiInstancesPerProvider)return console.log(`API limit reached for ${r.providerName}. Queueing request.`),new Promise((f,y)=>{this.requestQueue.push({config:r,resolve:f,reject:y});});let a;try{a=new n.adapter(r.adapterOptions);}catch(l){throw new Y(r.providerName,l)}let i={adapter:a,configSignature:e,state:"active"};this.managedInstances.set(e,i),console.log(`Created new instance for signature: ${e}`);let s=()=>this._releaseAdapter(e);return {adapter:i.adapter,release:s}}_releaseAdapter(r){console.log(`Release called for signature: ${r}`);let e=this.managedInstances.get(r);if(!e){console.warn(`Attempted to release unknown instance with signature: ${r}`);return}e.state="idle",e.lastUsedTimestamp=Date.now();let t=this.availableProviders.get(e.configSignature.split('"providerName":"')[1].split('"')[0]);if(t&&!t.isLocal&&(e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this._evictInstance(r);},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(r){console.log(`Attempting to evict instance with signature: ${r}`);let e=this.managedInstances.get(r);if(e&&e.state==="idle"){if(console.log(`Evicting idle instance with signature: ${r}`),e.adapter.shutdown)try{await e.adapter.shutdown(),console.log(`Adapter shutdown successful for ${r}`);}catch(t){console.error(`Error during adapter shutdown for ${r}:`,t);}this.managedInstances.delete(r),e.idleTimer&&(clearTimeout(e.idleTimer),e.idleTimer=void 0);}else e&&e.state==="active"?console.log(`Instance with signature ${r} is active, not evicting.`):console.log(`Instance with signature ${r} not found, cannot evict.`);}};var Re=(n=>(n.USER="USER",n.AI="AI",n.SYSTEM="SYSTEM",n.TOOL="TOOL",n))(Re||{}),ge=(m=>(m.INTENT="INTENT",m.PLAN="PLAN",m.THOUGHTS="THOUGHTS",m.TOOL_CALL="TOOL_CALL",m.TOOL_EXECUTION="TOOL_EXECUTION",m.SYNTHESIS="SYNTHESIS",m.ERROR="ERROR",m.FINAL_RESPONSE="FINAL_RESPONSE",m.STATE_UPDATE="STATE_UPDATE",m.LLM_STREAM_START="LLM_STREAM_START",m.LLM_STREAM_METADATA="LLM_STREAM_METADATA",m.LLM_STREAM_END="LLM_STREAM_END",m.LLM_STREAM_ERROR="LLM_STREAM_ERROR",m))(ge||{}),_e=(s=>(s.TEXT="text",s.VISION="vision",s.STREAMING="streaming",s.TOOL_USE="tool_use",s.RAG="rag",s.CODE="code",s.REASONING="reasoning",s))(_e||{});var U=()=>v4();var Oe=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(Oe||{}),o=class g{static config={level:1};static configure(r){g.config={...g.config,...r};}static debug(r,...e){g.config.level<=0&&console.debug(`${g.config.prefix||"[ART]"} ${r}`,...e);}static info(r,...e){g.config.level<=1&&console.info(`${g.config.prefix||"[ART]"} ${r}`,...e);}static warn(r,...e){g.config.level<=2&&console.warn(`${g.config.prefix||"[ART]"} ${r}`,...e);}static error(r,...e){g.config.level<=3&&console.error(`${g.config.prefix||"[ART]"} ${r}`,...e);}};var Ne="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.",B=class{deps;defaultSystemPrompt=Ne;constructor(r){this.deps=r;}async process(r){let e=Date.now(),t=r.traceId??U(),n="success",a,i=0,s=0,l,f;try{o.debug(`[${t}] Stage 1: Initiation & Config`);let u=await this.deps.stateManager.loadThreadContext(r.threadId,r.userId);if(!u)throw new c(`Thread context not found for threadId: ${r.threadId}`,"THREAD_NOT_FOUND");let m=await this.deps.stateManager.getThreadConfigValue(r.threadId,"systemPrompt")||this.defaultSystemPrompt,I=r.options?.providerConfig||u.config.providerConfig;if(!I)throw new c(`RuntimeProviderConfig is missing in AgentProps.options or ThreadConfig for threadId: ${r.threadId}`,"INVALID_CONFIG");o.debug(`[${t}] Stage 2: Planning Context Assembly`);let E={limit:u.config.historyLimit},d=await this.deps.conversationManager.getMessages(r.threadId,E),M=await this.deps.toolRegistry.getAvailableTools({enabledForThreadId:r.threadId}),R=this.formatHistoryForPrompt(d);o.debug(`[${t}] Stage 3: Planning Prompt Construction`);let b;try{b=[{role:"system",content:m},...R,{role:"user",content:`User Query: ${r.query}
|
|
3
3
|
|
|
4
4
|
Available Tools:
|
|
5
|
-
${
|
|
6
|
-
Input Schema: ${JSON.stringify(
|
|
5
|
+
${M.length>0?M.map(A=>`- ${A.name}: ${A.description}
|
|
6
|
+
Input Schema: ${JSON.stringify(A.inputSchema)}`).join(`
|
|
7
7
|
`):"No tools available."}
|
|
8
8
|
|
|
9
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.
|
|
10
10
|
Respond in the following format:
|
|
11
11
|
Intent: [Briefly describe the user's goal]
|
|
12
12
|
Plan: [Provide a step-by-step plan. If tools are needed, list them clearly.]
|
|
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(
|
|
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(A){throw o.error(`[${t}] Failed to construct planning prompt object:`,A),new c(`Failed to construct planning prompt object: ${A.message}`,"PROMPT_ASSEMBLY_FAILED",A)}o.debug(`[${t}] Stage 3b: Planning LLM Call`);let L={threadId:r.threadId,traceId:t,userId:r.userId,sessionId:r.sessionId,stream:!0,callContext:"AGENT_THOUGHT",requiredCapabilities:["reasoning"],providerConfig:I,...r.options?.llmParams??{}},w="",N={},p=null;try{await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"PLAN",content:{message:"Preparing for planning LLM call."},metadata:{timestamp:Date.now()}}).catch(_=>o.error(`[${t}] Failed to record PLAN observation:`,_)),i++;let A=await this.deps.reasoningEngine.call(b,L);await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"LLM_STREAM_START",content:{phase:"planning"},metadata:{timestamp:Date.now()}}).catch(_=>o.error(`[${t}] Failed to record LLM_STREAM_START observation:`,_));for await(let _ of A){switch(this.deps.uiSystem.getLLMStreamSocket().notify(_,{targetThreadId:_.threadId,targetSessionId:_.sessionId}),_.type){case "TOKEN":w+=_.data;break;case "METADATA":await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"LLM_STREAM_METADATA",content:_.data,metadata:{phase:"planning",timestamp:Date.now()}}).catch(O=>o.error(`[${t}] Failed to record LLM_STREAM_METADATA observation:`,O)),f={...f??{},..._.data};break;case "ERROR":p=_.data instanceof Error?_.data:new Error(String(_.data)),n="error",a=`Planning phase stream error: ${p.message}`,o.error(`[${t}] Planning Stream Error:`,p),await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"LLM_STREAM_ERROR",content:{phase:"planning",error:p.message,stack:p.stack},metadata:{timestamp:Date.now()}}).catch(O=>o.error(`[${t}] Failed to record LLM_STREAM_ERROR observation:`,O));break;case "END":await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"LLM_STREAM_END",content:{phase:"planning"},metadata:{timestamp:Date.now()}}).catch(O=>o.error(`[${t}] Failed to record LLM_STREAM_END observation:`,O));break}if(p)break}if(p)throw new c(a,"PLANNING_FAILED",p);N=await this.deps.outputParser.parsePlanningOutput(w),await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"INTENT",content:{intent:N.intent},metadata:{timestamp:Date.now()}}),await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"PLAN",content:{plan:N.plan,rawOutput:w},metadata:{timestamp:Date.now()}}),N.toolCalls&&N.toolCalls.length>0&&await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"TOOL_CALL",content:{toolCalls:N.toolCalls},metadata:{timestamp:Date.now()}});}catch(A){throw n="error",a=a??`Planning phase failed: ${A.message}`,o.error(`[${t}] Planning Error:`,A),p||await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"ERROR",content:{phase:"planning",error:A.message,stack:A.stack},metadata:{timestamp:Date.now()}}),A instanceof c?A:new c(a,"PLANNING_FAILED",A)}let v=[];if(N.toolCalls&&N.toolCalls.length>0){o.debug(`[${t}] Stage 4: Tool Execution (${N.toolCalls.length} calls)`);try{v=await this.deps.toolSystem.executeTools(N.toolCalls,r.threadId,t),s=v.length,v.some(A=>A.status==="error")&&(n="partial",o.warn(`[${t}] Partial success in tool execution.`),a=a?`${a}; Tool execution errors occurred.`:"Tool execution errors occurred.");}catch(A){throw n="error",a=`Tool execution phase failed: ${A.message}`,o.error(`[${t}] Tool Execution System Error:`,A),await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"ERROR",content:{phase:"tool_execution",error:A.message,stack:A.stack},metadata:{timestamp:Date.now()}}),new c(a,"TOOL_EXECUTION_FAILED",A)}}else o.debug(`[${t}] Stage 4: Tool Execution (No tool calls)`);o.debug(`[${t}] Stage 5: Synthesis Call`),await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"SYNTHESIS",content:{message:"Preparing for synthesis LLM call."},metadata:{timestamp:Date.now()}}).catch(A=>o.error(`[${t}] Failed to record SYNTHESIS observation:`,A)),o.debug(`[${t}] Stage 5: Synthesis Prompt Construction`);let x;try{x=[{role:"system",content:m},...R,{role:"user",content:`User Query: ${r.query}
|
|
14
14
|
|
|
15
|
-
Original Intent: ${
|
|
16
|
-
Execution Plan: ${
|
|
15
|
+
Original Intent: ${N.intent??""}
|
|
16
|
+
Execution Plan: ${N.plan??""}
|
|
17
17
|
|
|
18
18
|
Tool Execution Results:
|
|
19
|
-
${
|
|
20
|
-
Status: ${
|
|
21
|
-
${
|
|
22
|
-
${
|
|
19
|
+
${v.length>0?v.map(A=>`- Tool: ${A.toolName} (Call ID: ${A.callId})
|
|
20
|
+
Status: ${A.status}
|
|
21
|
+
${A.status==="success"?`Output: ${JSON.stringify(A.output)}`:""}
|
|
22
|
+
${A.status==="error"?`Error: ${A.error??"Unknown error"}`:""}`).join(`
|
|
23
23
|
`):"No tools were executed."}
|
|
24
24
|
|
|
25
25
|
Based on the user query, the plan, and the results of any tool executions, synthesize a final response to the user.
|
|
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({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=z$1.object({role:z$1.custom(u=>typeof u=="string"&&["system","user","assistant","tool","tool_request","tool_result"].includes(u),{message:"Invalid message role"}),content:z$1.union([z$1.string(),z$1.record(z$1.any()),z$1.null()]),name:z$1.string().optional(),tool_calls:z$1.array(z$1.object({id:z$1.string(),type:z$1.literal("function"),function:z$1.object({name:z$1.string(),arguments:z$1.string()})})).optional(),tool_call_id:z$1.string().optional()}).strict().refine(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=z$1.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:
|
|
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(A){throw o.error(`[${t}] Failed to construct synthesis prompt object:`,A),new c(`Failed to construct synthesis prompt object: ${A.message}`,"PROMPT_ASSEMBLY_FAILED",A)}o.debug(`[${t}] Stage 5b: Synthesis LLM Call`);let P={threadId:r.threadId,traceId:t,userId:r.userId,sessionId:r.sessionId,stream:!0,callContext:"FINAL_SYNTHESIS",requiredCapabilities:["text"],providerConfig:I,...r.options?.llmParams??{}},C="",S=null;try{i++;let A=await this.deps.reasoningEngine.call(x,P);await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"LLM_STREAM_START",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}}).catch(_=>o.error(`[${t}] Failed to record LLM_STREAM_START observation:`,_));for await(let _ of A){switch(this.deps.uiSystem.getLLMStreamSocket().notify(_,{targetThreadId:_.threadId,targetSessionId:_.sessionId}),_.type){case "TOKEN":(_.tokenType==="FINAL_SYNTHESIS_LLM_RESPONSE"||_.tokenType==="LLM_RESPONSE")&&(C+=_.data);break;case "METADATA":f={...f??{},..._.data},await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"LLM_STREAM_METADATA",content:_.data,metadata:{phase:"synthesis",timestamp:Date.now()}}).catch(O=>o.error(`[${t}] Failed to record LLM_STREAM_METADATA observation:`,O));break;case "ERROR":S=_.data instanceof Error?_.data:new Error(String(_.data)),n=n==="partial"?"partial":"error",a=a?`${a}; Synthesis stream error: ${S.message}`:`Synthesis stream error: ${S.message}`,o.error(`[${t}] Synthesis Stream Error:`,S),await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"LLM_STREAM_ERROR",content:{phase:"synthesis",error:S.message,stack:S.stack},metadata:{timestamp:Date.now()}}).catch(O=>o.error(`[${t}] Failed to record LLM_STREAM_ERROR observation:`,O));break;case "END":await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"LLM_STREAM_END",content:{phase:"synthesis"},metadata:{timestamp:Date.now()}}).catch(O=>o.error(`[${t}] Failed to record LLM_STREAM_END observation:`,O));break}if(S)break}if(S){if(n!=="partial")throw new c(a,"SYNTHESIS_FAILED",S);C=a;}}catch(A){n=n==="partial"?"partial":"error";let _=`Synthesis phase failed: ${A.message}`;if(a=a?`${a}; ${_}`:_,o.error(`[${t}] Synthesis Error:`,A),S||await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"ERROR",content:{phase:"synthesis",error:A.message,stack:A.stack},metadata:{timestamp:Date.now()}}),n!=="partial")throw A instanceof c?A:new c(_,"SYNTHESIS_FAILED",A);C=a;}o.debug(`[${t}] Stage 6: Finalization`);let D=Date.now();l={messageId:U(),threadId:r.threadId,role:"AI",content:C,timestamp:D,metadata:{traceId:t}},await this.deps.conversationManager.addMessages(r.threadId,[l]),await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"FINAL_RESPONSE",content:{message:l},metadata:{timestamp:D}}),await this.deps.stateManager.saveStateIfModified(r.threadId);}catch(u){o.error(`[${t}] PESAgent process error:`,u),n=n==="partial"?"partial":"error",a=a??(u instanceof c?u.message:"An unexpected error occurred."),n==="error"&&(l=void 0),u instanceof c&&(u.code==="PLANNING_FAILED"||u.code==="TOOL_EXECUTION_FAILED"||u.code==="SYNTHESIS_FAILED")||await this.deps.observationManager.record({threadId:r.threadId,traceId:t,type:"ERROR",content:{phase:"agent_process",error:u.message,stack:u.stack},metadata:{timestamp:Date.now()}}).catch(m=>o.error(`[${t}] Failed to record top-level error observation:`,m));}finally{try{await this.deps.stateManager.saveStateIfModified(r.threadId);}catch(u){o.error(`[${t}] Failed to save state during finalization:`,u);}}let y=Date.now(),T={threadId:r.threadId,traceId:t,userId:r.userId,status:n,totalDurationMs:y-e,llmCalls:i,toolCalls:s,error:a,llmMetadata:f};if(!l&&n!=="success")l={messageId:U(),threadId:r.threadId,role:"AI",content:a??"Agent execution failed.",timestamp:Date.now(),metadata:{traceId:t,error:true}};else if(!l)throw new c("Agent finished with success status but no final message was generated.","UNKNOWN_ERROR");return {response:l,metadata:T}}formatHistoryForPrompt(r){return r.map(e=>{let t;switch(e.role){case "USER":t="user";break;case "AI":t="assistant";break;case "SYSTEM":t="system";break;case "TOOL":t="tool";break;default:o.warn(`Unhandled message role '${e.role}' in formatHistoryForPrompt. Defaulting to 'user'.`),t="user";}return {role:t,content:e.content}}).filter(e=>e.content)}};var H=class{storage=new Map;async init(r){return Promise.resolve()}async get(r,e){let t=this.storage.get(r);if(!t)return null;let n=t.get(e);return n?JSON.parse(JSON.stringify(n)):null}async set(r,e,t){return this.storage.has(r)||this.storage.set(r,new Map),this.storage.get(r).set(e,JSON.parse(JSON.stringify(t))),Promise.resolve()}async delete(r,e){let t=this.storage.get(r);return t&&t.delete(e),Promise.resolve()}async query(r,e){let t=this.storage.get(r);if(!t)return [];let n=Array.from(t.values());return e.filter&&(n=n.filter(a=>{for(let i in e.filter)if(e.filter.hasOwnProperty(i)&&a[i]!==e.filter[i])return false;return true})),typeof e.limit=="number"&&e.limit>=0&&(n=n.slice(0,e.limit)),JSON.parse(JSON.stringify(n))}async clearCollection(r){return this.storage.delete(r),Promise.resolve()}async clearAll(){return this.storage.clear(),Promise.resolve()}};var Ce="ART_Framework_DB",xe=1,K=class{db=null;dbName;dbVersion;requiredObjectStores;initPromise=null;constructor(r){this.dbName=r.dbName||Ce,this.dbVersion=r.dbVersion||xe,this.requiredObjectStores=new Set(["conversations","observations","state",...r.objectStores||[]]);}async init(){return this.initPromise?this.initPromise:(this.initPromise=new Promise((r,e)=>{if(!("indexedDB"in window))return o.error("IndexedDBStorageAdapter: IndexedDB not supported in this browser."),e(new Error("IndexedDB not supported"));let t=indexedDB.open(this.dbName,this.dbVersion);t.onerror=n=>{o.error(`IndexedDBStorageAdapter: Database error: ${t.error}`,n),e(new Error(`IndexedDB error: ${t.error?.message}`));},t.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)),i=[...this.requiredObjectStores].filter(s=>!a.has(s));i.length>0&&o.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=s=>{o.error("IndexedDBStorageAdapter: Generic database error:",s);},r();},t.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 i=new Set(Array.from(this.db.objectStoreNames));this.requiredObjectStores.forEach(s=>{i.has(s)||(o.info(`IndexedDBStorageAdapter: Creating object store '${s}'...`),this.db?.createObjectStore(s,{keyPath:"id"}));}),o.info("IndexedDBStorageAdapter: Database upgrade complete.");},t.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(r,e){if(!this.db)throw new Error("IndexedDBStorageAdapter: Database not initialized. Ensure init() was called and awaited.");return (Array.isArray(r)?r:[r]).forEach(n=>{if(!this.db?.objectStoreNames.contains(n))throw new Error(`IndexedDBStorageAdapter: Object store "${n}" does not exist in the database.`)}),this.db.transaction(r,e)}async get(r,e){return await this.init(),new Promise((t,n)=>{try{let s=this.getTransaction(r,"readonly").objectStore(r).get(e);s.onsuccess=()=>{t(s.result?{...s.result}:null);},s.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error getting item '${e}' from '${r}':`,s.error),n(new Error(`Failed to get item: ${s.error?.message}`));};}catch(a){n(a);}})}async set(r,e,t){let n=t;return typeof n.id>"u"?Promise.reject(new Error(`IndexedDBStorageAdapter: Data for collection '${r}' 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 '${r}'. Using data.id as the key.`),await this.init(),new Promise((a,i)=>{try{let s=structuredClone(t),l=this.getTransaction(r,"readwrite"),y=l.objectStore(r).put(s);y.onsuccess=()=>{a();},y.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error setting item with id '${n.id}' in '${r}':`,y.error),i(new Error(`Failed to set item: ${y.error?.message}`));},l.oncomplete=()=>{},l.onerror=T=>{o.error(`IndexedDBStorageAdapter: Transaction error setting item with id '${n.id}' in '${r}':`,l.error,T),i(new Error(`Transaction failed: ${l.error?.message}`));};}catch(s){i(s);}}))}async delete(r,e){return await this.init(),new Promise((t,n)=>{try{let a=this.getTransaction(r,"readwrite"),s=a.objectStore(r).delete(e);s.onsuccess=()=>{t();},s.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error deleting item '${e}' from '${r}':`,s.error),n(new Error(`Failed to delete item: ${s.error?.message}`));},a.onerror=l=>{o.error(`IndexedDBStorageAdapter: Transaction error deleting item '${e}' from '${r}':`,a.error,l),n(new Error(`Transaction failed: ${a.error?.message}`));};}catch(a){n(a);}})}async query(r,e){return await this.init(),new Promise((t,n)=>{try{let s=this.getTransaction(r,"readonly").objectStore(r).getAll();s.onsuccess=()=>{let l=s.result||[];if(e.filter&&(l=l.filter(T=>{for(let u in e.filter)if(e.filter.hasOwnProperty(u)&&T[u]!==e.filter[u])return !1;return !0})),e.sort){let T=Object.keys(e.sort)[0],u=e.sort[T];T&&l.sort((m,I)=>{let E=m[T],d=I[T];return E<d?u==="asc"?-1:1:E>d?u==="asc"?1:-1:0});}let f=e.skip||0,y=e.limit??1/0;l=l.slice(f,f+y),t(l.map(T=>({...T})));},s.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error querying collection '${r}':`,s.error),n(new Error(`Failed to query collection: ${s.error?.message}`));};}catch(a){n(a);}})}async clearCollection(r){return await this.init(),new Promise((e,t)=>{try{let n=this.getTransaction(r,"readwrite"),i=n.objectStore(r).clear();i.onsuccess=()=>{e();},i.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error clearing collection '${r}':`,i.error),t(new Error(`Failed to clear collection: ${i.error?.message}`));},n.onerror=s=>{o.error(`IndexedDBStorageAdapter: Transaction error clearing collection '${r}':`,n.error,s),t(new Error(`Transaction failed: ${n.error?.message}`));};}catch(n){t(n);}})}async clearAll(){if(await this.init(),!this.db)throw new Error("Database not initialized.");let r=Array.from(this.db.objectStoreNames);return r.length===0?Promise.resolve():new Promise((e,t)=>{try{let n=this.getTransaction(r,"readwrite"),a=0,i=r.length;r.forEach(s=>{let l=n.objectStore(s).clear();l.onsuccess=()=>{a++;},l.onerror=()=>{o.error(`IndexedDBStorageAdapter: Error clearing object store '${s}':`,l.error);};}),n.oncomplete=()=>{o.info("IndexedDBStorageAdapter: All object stores cleared successfully."),e();},n.onerror=s=>{o.error("IndexedDBStorageAdapter: Transaction error during clearAll:",n.error,s),t(new Error(`Failed to clear all stores: ${n.error?.message}`));};}catch(n){t(n);}})}};var X=class{adapter;collectionName="conversations";constructor(r){if(!r)throw new Error("ConversationRepository requires a valid StorageAdapter instance.");this.adapter=r;}async addMessages(r,e){if(!e||e.length===0)return Promise.resolve();let t=e.map(n=>{n.threadId!==r&&console.warn(`ConversationRepository: Message ${n.messageId} has mismatching threadId (${n.threadId}) for repository operation on thread ${r}.`);let a={...n,id:n.messageId};return this.adapter.set(this.collectionName,a.id,a)});await Promise.all(t);}async getMessages(r,e){let n=await this.adapter.query(this.collectionName,{filter:{threadId:r}});return n.sort((i,s)=>i.timestamp-s.timestamp),e?.beforeTimestamp!==void 0&&(n=n.filter(i=>i.timestamp<e.beforeTimestamp)),e?.afterTimestamp!==void 0&&(n=n.filter(i=>i.timestamp>e.afterTimestamp)),e?.limit!==void 0&&e.limit>0&&(n=n.slice(-e.limit)),n.map(({id:i,...s})=>s)}};var Q=class{adapter;collectionName="observations";constructor(r){if(!r)throw new Error("ObservationRepository requires a valid StorageAdapter instance.");this.adapter=r;}async addObservation(r){if(typeof r.id>"u")return Promise.reject(new Error("ObservationRepository: Observation must have an 'id' property."));await this.adapter.set(this.collectionName,r.id,r);}async getObservations(r,e){let n=await this.adapter.query(this.collectionName,{filter:{threadId:r}});if(n.sort((a,i)=>a.timestamp-i.timestamp),e?.types&&e.types.length>0){let a=new Set(e.types);n=n.filter(i=>a.has(i.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 W=class{adapter;collectionName="state";constructor(r){if(!r)throw new Error("StateRepository requires a valid StorageAdapter instance.");this.adapter=r;}async getThreadContext(r){let e=await this.adapter.get(this.collectionName,r);if(!e)return null;let t={...e};return delete t.id,t}async setThreadContext(r,e){if(!e||typeof e.config>"u")return Promise.reject(new Error("StateRepository: ThreadContext must contain a 'config' property."));let t={...e,id:r};await this.adapter.set(this.collectionName,r,t);}async getThreadConfig(r){return (await this.getThreadContext(r))?.config??null}async setThreadConfig(r,e){let t=await this.getThreadContext(r),n={config:e,state:t?.state??null};await this.setThreadContext(r,n);}async getAgentState(r){return (await this.getThreadContext(r))?.state??null}async setAgentState(r,e){let t=await this.getThreadContext(r);if(!t||!t.config)return Promise.reject(new Error(`StateRepository: Cannot set AgentState for thread '${r}' because no ThreadConfig exists. Set config first.`));let n={config:t.config,state:e};await this.setThreadContext(r,n);}};var Z=class{repository;conversationSocket;constructor(r,e){this.repository=r,this.conversationSocket=e;}async addMessages(r,e){if(!r)return Promise.reject(new Error("ConversationManager: threadId cannot be empty."));if(!e||e.length===0)return Promise.resolve();await this.repository.addMessages(r,e),e.forEach(t=>{try{this.conversationSocket.notify(t,{targetThreadId:r});}catch(n){console.error(`ConversationManager: Failed to notify message ${t.messageId} via socket for thread ${r}`,n);}});}async getMessages(r,e){return r?await this.repository.getMessages(r,e):Promise.reject(new Error("ConversationManager: threadId cannot be empty."))}};var ee=class{repository;constructor(r){this.repository=r;}async loadThreadContext(r,e){if(!r)throw new Error("StateManager: threadId cannot be empty.");let t=await this.repository.getThreadContext(r);if(!t)throw new Error(`StateManager: Thread context not found for threadId '${r}'.`);return t}async isToolEnabled(r,e){try{return (await this.loadThreadContext(r)).config?.enabledTools?.includes(e)??!1}catch(t){return console.warn(`StateManager: Could not check if tool '${e}' is enabled for thread '${r}' because context failed to load: ${t}`),false}}async getThreadConfigValue(r,e){let t=await this.loadThreadContext(r);if(t.config&&e in t.config)return t.config[e]}async saveStateIfModified(r){return r?(console.warn(`StateManager: saveStateIfModified called for thread ${r}, 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(r,e){if(!r||!e)throw new Error("StateManager: threadId and config are required for setThreadConfig.");await this.repository.setThreadConfig(r,e);}};var te=class{observationRepository;observationSocket;constructor(r,e){this.observationRepository=r,this.observationSocket=e;}async record(r){let e={...r,id:U(),timestamp:Date.now(),title:`${r.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(t){throw console.error("Error recording observation:",t),t}}async getObservations(r,e){try{return await this.observationRepository.getObservations(r,e)}catch(t){throw console.error(`Error retrieving observations for thread ${r}:`,t),t}}};var re=class{executors=new Map;stateManager;constructor(r){this.stateManager=r,o.debug(`ToolRegistry initialized ${r?"with":"without"} StateManager.`);}async registerTool(r){if(!r||!r.schema||!r.schema.name)throw o.error("ToolRegistry: Attempted to register an invalid tool executor."),new Error("Invalid tool executor provided for registration.");let e=r.schema.name;this.executors.has(e)&&o.warn(`ToolRegistry: Overwriting existing tool registration for "${e}".`),this.executors.set(e,r),o.debug(`ToolRegistry: Registered tool "${e}".`);}async getToolExecutor(r){let e=this.executors.get(r);return e||o.debug(`ToolRegistry: Tool "${r}" not found.`),e}async getAvailableTools(r){let e=Array.from(this.executors.values()),t=e.map(n=>n.schema);if(r?.enabledForThreadId&&this.stateManager){let n=r.enabledForThreadId;o.debug(`ToolRegistry: Attempting to filter tools for threadId: ${n}`);try{let i=(await this.stateManager.loadThreadContext(n))?.config?.enabledTools;if(i&&Array.isArray(i)){o.debug(`ToolRegistry: Found enabled tools for thread ${n}: ${i.join(", ")}`);let l=e.filter(f=>i.includes(f.schema.name)).map(f=>f.schema);return o.debug(`ToolRegistry: Returning ${l.length} enabled tool schemas for thread ${n}.`),l}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 r?.enabledForThreadId&&!this.stateManager&&o.warn("ToolRegistry: Filtering by enabledForThreadId requested, but StateManager was not provided. Returning all tools.");return o.debug(`ToolRegistry: Returning all ${t.length} registered tool schemas.`),t}async clearAllTools(){this.executors.clear(),o.debug("ToolRegistry: Cleared all registered tools.");}};var ke=new Le({allErrors:true}),he=new Map;function be(g,r){let e=JSON.stringify(g),t;if(he.has(e))t=he.get(e),o.debug("Using cached JSON schema validator.");else try{t=ke.compile(g),he.set(e,t),o.debug("Compiled and cached new JSON schema validator.");}catch(a){return o.error(`Failed to compile JSON schema: ${a.message}`,{schema:g,error:a}),{isValid:false,errors:[{keyword:"compilation",instancePath:"",schemaPath:"",params:{},message:`Schema compilation failed: ${a.message}`}]}}return t(r)?{isValid:true,errors:null}:(o.warn("JSON schema validation failed.",{errors:t.errors,data:r}),{isValid:false,errors:t.errors||[]})}var ne=class{toolRegistry;stateManager;observationManager;constructor(r,e,t){if(!r)throw new Error("ToolSystem constructor requires a ToolRegistry instance.");if(!e)throw new Error("ToolSystem constructor requires a StateManager instance.");if(!t)throw new Error("ToolSystem constructor requires an ObservationManager instance.");this.toolRegistry=r,this.stateManager=e,this.observationManager=t,o.info("ToolSystem initialized.");}async executeTools(r,e,t){let n=[];o.debug(`ToolSystem executing ${r.length} tool calls for thread ${e}`,{traceId:t});for(let a of r){let i=null,s,l=a.toolName,f=a.callId;try{if(!await this.stateManager.isToolEnabled(e,l))throw new Error(`Tool "${l}" is not enabled for thread "${e}".`);if(s=await this.toolRegistry.getToolExecutor(l),!s)throw new Error(`Tool "${l}" not found in registry.`);let T=be(s.schema.inputSchema,a.arguments);if(!T.isValid){let I=T.errors?.map(E=>`${E.instancePath||"input"} ${E.message}`).join(", ")||"Unknown validation error";throw new Error(`Invalid arguments for tool "${l}": ${I}`)}o.debug(`Executing tool "${l}" with callId "${f}"`,{args:a.arguments,threadId:e,traceId:t});let u={threadId:e,traceId:t};i={...await s.execute(a.arguments,u),callId:f,toolName:l},o.debug(`Tool "${l}" execution successful`,{callId:f,result:i.output,threadId:e,traceId:t});}catch(y){o.error(`Tool "${l}" execution failed for callId "${f}": ${y.message}`,{error:y,threadId:e,traceId:t}),i={callId:f,toolName:l,status:"error",error:y.message||"Unknown execution error"};}i?(this.observationManager.record({threadId:e,traceId:t,type:"TOOL_EXECUTION",content:i,metadata:{timestamp:Date.now(),callId:a.callId}}).catch(y=>o.error(`Failed to record TOOL_EXECUTION observation for callId ${a.callId}:`,y)),n.push(i)):o.error(`ToolSystem finished processing call ${a.callId} but result object was null.`);}return n}};var De=z$1.object({role:z$1.custom(g=>typeof g=="string"&&["system","user","assistant","tool","tool_request","tool_result"].includes(g),{message:"Invalid message role"}),content:z$1.union([z$1.string(),z$1.record(z$1.any()),z$1.null()]),name:z$1.string().optional(),tool_calls:z$1.array(z$1.object({id:z$1.string(),type:z$1.literal("function"),function:z$1.object({name:z$1.string(),arguments:z$1.string()})})).optional(),tool_call_id:z$1.string().optional()}).strict().refine(g=>!((g.role==="tool"||g.role==="tool_result")&&!g.tool_call_id||g.role==="assistant"&&g.content!==null&&typeof g.content!="string"||(g.role==="user"||g.role==="system")&&typeof g.content!="string"),{message:"Invalid message structure based on role (e.g., tool_call_id missing for tool role, invalid content type for user/system, assistant content not string/null)"}),Me=z$1.array(De);var Fe={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
27
|
Intent: [Briefly describe the user's goal]
|
|
28
28
|
Plan: [Provide a step-by-step plan. If tools are needed, list them clearly.]
|
|
29
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 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.object({callId:k.string().min(1),toolName:k.string().min(1),arguments:k.unknown()}),Le=k.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=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 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+`
|
|
30
|
+
If the tools failed or provided unexpected results, explain the issue and try to answer based on available information or ask for clarification.`},oe=class{getFragment(r,e){let t=Fe[r];if(t===void 0)throw o.error(`[PromptManager] Prompt fragment not found: ${r}`),new c(`Prompt fragment not found: ${r}`,"PROMPT_FRAGMENT_NOT_FOUND");return e?t.replace(/\{\{([^}]+)\}\}/g,(n,a)=>{let i=a.trim(),s=e[i];return s!==void 0?String(s):n}):t}validatePrompt(r){try{return Me.parse(r)}catch(e){throw e instanceof ZodError?(o.error("[PromptManager] Prompt validation failed:",e.errors),new c(`Constructed prompt failed validation: ${e.message}`,"PROMPT_VALIDATION_FAILED",e)):(o.error("[PromptManager] Unexpected error during prompt validation:",e),new c(`Unexpected error during prompt validation: ${e.message}`,"PROMPT_VALIDATION_FAILED",e))}}};var ae=class{providerManager;constructor(r){this.providerManager=r,o.info("ReasoningEngine initialized with ProviderManager");}async call(r,e){let t=e.providerConfig;if(!t)throw new Error("CallOptions must include 'providerConfig' for multi-provider architecture.");o.debug(`ReasoningEngine requesting adapter for provider: ${t.providerName}, model: ${t.modelId}`,{threadId:e.threadId,traceId:e.traceId,stream:e.stream});let n;try{n=await this.providerManager.getAdapter(t),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(r,e);return async function*(){try{for await(let s of a)yield s;}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 se=class{constructor(r,e,t=0){this.tagName=r;this.transform=e;this.position=t;}index=0;currentChunks=[];cachedBuffer=[];isCurrentlyMatched=false;tagDepth=0;pointer=0;S_TEXT=0;S_TAG_OPEN=1;S_TAG_NAME=2;S_TAG_CLOSING_SLASH=3;S_IGNORE_UNTIL_GT=4;state=this.S_TEXT;collectCurrentCache(r){if(this.cachedBuffer.length===0){r!==void 0&&this.currentChunks.length>0;return}let e=this.cachedBuffer.join("");this.cachedBuffer=[];let t=r===void 0?this.isCurrentlyMatched:!r,n=this.currentChunks.length>0?this.currentChunks[this.currentChunks.length-1]:null;n&&n.matched===t?n.data+=e:this.currentChunks.push({matched:t,data:e});}flushProcessedChunks(){let r=this.currentChunks;return this.currentChunks=[],this.transform?r.map(this.transform):r}update(r){for(let e=0;e<r.length;e++){let t=r[e];this.pointer++,this.state===this.S_TEXT?t==="<"&&(this.pointer>this.position||this.isCurrentlyMatched||this.tagDepth>0)?(this.collectCurrentCache(),this.state=this.S_TAG_OPEN,this.cachedBuffer.push(t)):this.cachedBuffer.push(t):this.state===this.S_TAG_OPEN?(this.cachedBuffer.push(t),t==="/"?(this.state=this.S_TAG_CLOSING_SLASH,this.index=0):t.match(/[a-zA-Z]/)?(this.state=this.S_TAG_NAME,this.index=0,this.cachedBuffer.pop(),e--):this.state=this.S_TEXT):this.state===this.S_TAG_NAME?this.index<this.tagName.length&&t===this.tagName[this.index]?(this.cachedBuffer.push(t),this.index++):t===">"&&this.index===this.tagName.length?(this.cachedBuffer.push(t),this.collectCurrentCache(true),this.isCurrentlyMatched=true,this.tagDepth++,this.state=this.S_TEXT,this.cachedBuffer=[]):(t===" "||t===" "||t===`
|
|
31
|
+
`||t==="\r"||t===">")&&this.index===this.tagName.length?(this.cachedBuffer.push(t),t===">"?(this.collectCurrentCache(true),this.isCurrentlyMatched=true,this.tagDepth++,this.state=this.S_TEXT,this.cachedBuffer=[]):this.state=this.S_IGNORE_UNTIL_GT):(this.state=this.S_IGNORE_UNTIL_GT,this.cachedBuffer.push(t)):this.state===this.S_TAG_CLOSING_SLASH?(this.cachedBuffer.push(t),this.index<this.tagName.length&&t===this.tagName[this.index]?this.index++:t===">"&&this.index===this.tagName.length?(this.collectCurrentCache(false),this.tagDepth--,this.isCurrentlyMatched=this.tagDepth>0,this.state=this.S_TEXT,this.cachedBuffer=[]):this.state=this.S_IGNORE_UNTIL_GT):this.state===this.S_IGNORE_UNTIL_GT&&(this.cachedBuffer.push(t),t===">"&&(this.state=this.S_TEXT));}return this.flushProcessedChunks()}final(r){return r&&this.update(r),this.collectCurrentCache(),this.flushProcessedChunks()}};var Ue=$.object({callId:$.string().min(1),toolName:$.string().min(1),arguments:$.unknown()}),Ge=$.array(Ue),ie=class{async parsePlanningOutput(r){let e={},t=r,n=[],i=new se("think").final(r),s="";i.forEach(u=>{u.matched?n.push(u.data.trim()):s+=u.data;}),n.length>0&&(e.thoughts=n.join(`
|
|
31
32
|
|
|
32
|
-
|
|
33
|
-
|
|
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.sqrt,cbrt:m.cbrt,abs:m.abs,pow:m.pow,exp:m.exp,log:m.log,log10:m.log10,log2:m.log2,sin:m.sin,cos:m.cos,tan:m.tan,asin:m.asin,acos:m.acos,atan:m.atan,atan2:m.atan2,round:m.round,floor:m.floor,ceil:m.ceil,mod:m.mod,mean:m.mean,median:m.median,std:m.std,variance:m.variance,max:m.max,min:m.min,factorial:m.factorial,gamma:m.gamma,combinations:m.combinations,permutations:m.permutations,format:m.format},Ae=class u{static toolName="calculator";resultStore=new Map;schema={name:u.toolName,description:`Evaluates mathematical expressions using a sandboxed mathjs environment.
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
`)),t=s;let l=t.match(/Intent:\s*([\s\S]*?)(Plan:|Tool Calls:|$)/i);e.intent=l?.[1]?.trim();let f=t.match(/Plan:\s*([\s\S]*?)(Tool Calls:|$)/i);e.plan=f?.[1]?.trim();let y=t.match(/Tool Calls:\s*([\s\S]*?)$/i),T=y?.[1]?.trim();if(e.toolCalls=void 0,T){let u=null,m=null,I=/```(?:json)?\s*(\[[\s\S]*?\])\s*```|(\[[\s\S]*?\])/,E=T.match(I);if(E?u=E[1]?E[1].trim():E[2]?E[2].trim():null:o.debug(`OutputParser: No JSON array found in Tool Calls section. Content: ${T}`),u)try{let d=u.replace(/,\s*(?=]$)/,"");m=JSON.parse(d);}catch(d){o.error(`OutputParser: Failed to parse extracted JSON array. Error: ${d}. Extracted Content: ${u}. Original Content: ${T}`);}if(m!==null){let d=Ge.safeParse(m);d.success?e.toolCalls=d.data:(o.warn(`OutputParser: Tool Calls JSON structure validation failed. Errors: ${d.error.toString()}. Parsed Content: ${JSON.stringify(m)}`),e.toolCalls=[]);}else e.toolCalls=[];}else y&&(e.toolCalls=[]);return !e.intent&&!e.plan&&(e.toolCalls===void 0||e.toolCalls.length===0)&&!e.thoughts?(o.warn(`OutputParser: Could not parse any structured data (Intent, Plan, Tool Calls, Thoughts) from planning output. Original output: ${r}`),!e.intent&&!e.plan&&(e.toolCalls===void 0||e.toolCalls.length===0)&&o.debug(`OutputParser: No Intent, Plan, or Tool Calls found in non-thinking content part: ${t}`)):!e.intent&&!e.plan&&!e.toolCalls&&!e.thoughts&&o.warn(`OutputParser: Complete failure to parse any structured data or thoughts from planning output: ${r}`),e}async parseSynthesisOutput(r){return r.trim()}};var F=class{subscriptions=new Map;constructor(){}subscribe(r,e,t){let n=v4(),a={id:n,callback:r,filter:e,options:t};return this.subscriptions.set(n,a),o.debug(`New subscription added: ${n}, Filter: ${JSON.stringify(e)}, Options: ${JSON.stringify(t)}`),()=>{this.subscriptions.delete(n),o.debug(`Subscription removed: ${n}`);}}notify(r,e,t){let n=this.constructor.name;o.debug(`[${n}] notify() called. Data type: ${typeof r}, Sub count: ${this.subscriptions.size}, Options: ${JSON.stringify(e)}`),o.debug(`Notifying ${this.subscriptions.size} subscribers. Data: ${JSON.stringify(r).substring(0,100)}..., Options: ${JSON.stringify(e)}`),this.subscriptions.forEach(a=>{try{if(a.options?.threadId&&e?.targetThreadId&&a.options.threadId!==e.targetThreadId||t&&a.filter!==void 0&&!t(r,a.filter))return;o.debug(`Checks passed for sub ${a.id}. Invoking callback.`),a.callback(r);}catch(i){o.error(`Error executing subscription callback ${a.id}:`,i);}});}async getHistory(r,e){return o.warn("getHistory is not implemented in the base TypedSocket."),[]}clearAllSubscriptions(){this.subscriptions.clear(),o.debug("All subscriptions cleared.");}};var le=class extends F{observationRepository;constructor(r){super(),this.observationRepository=r,o.debug("ObservationSocket initialized.");}notifyObservation(r){o.debug(`Notifying Observation: ${r.id} (${r.type}) for thread ${r.threadId}`),super.notify(r,{targetThreadId:r.threadId},(e,t)=>t?Array.isArray(t)?t.includes(e.type):e.type===t:true);}async getHistory(r,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(r)}, Limit: ${e.limit}`);let t={};r&&(t.types=Array.isArray(r)?r:[r]),e.limit!==void 0&&o.debug(`Limit requested: ${e.limit}. Repository implementation must handle this.`);try{return await this.observationRepository.getObservations(e.threadId,t)}catch(n){return o.error(`Error fetching observation history for thread ${e.threadId} with filter ${JSON.stringify(t)}:`,n),[]}}};var de=class extends F{conversationRepository;constructor(r){super(),this.conversationRepository=r,o.debug("ConversationSocket initialized.");}notifyMessage(r){o.debug(`Notifying Message: ${r.messageId} (${r.role}) for thread ${r.threadId}`),super.notify(r,{targetThreadId:r.threadId},(e,t)=>t?Array.isArray(t)?t.includes(e.role):e.role===t:true);}async getHistory(r,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(r)}, Limit: ${e.limit}`);let t={};e.limit!==void 0&&(t.limit=e.limit),r&&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,t)}catch(n){return o.error(`Error fetching message history for thread ${e.threadId}:`,n),[]}}};var ce=class extends F{constructor(){super(),o.debug("LLMStreamSocket initialized.");}notifyStreamEvent(r){o.debug(`Notifying LLMStreamEvent: ${r.type} for thread ${r.threadId}, trace ${r.traceId}`),super.notify(r,{targetThreadId:r.threadId,targetSessionId:r.sessionId},(e,t)=>t?Array.isArray(t)?t.includes(e.type):e.type===t:true);}};var pe=class{observationSocketInstance;conversationSocketInstance;llmStreamSocketInstance;constructor(r,e){this.observationSocketInstance=new le(r),this.conversationSocketInstance=new de(e),this.llmStreamSocketInstance=new ce,o.debug("UISystem initialized with Observation, Conversation, and LLM Stream sockets.");}getObservationSocket(){return this.observationSocketInstance}getConversationSocket(){return this.conversationSocketInstance}getLLMStreamSocket(){return this.llmStreamSocketInstance}};var fe=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(r){if(this.config=r,!r.storage)throw new Error("AgentFactoryConfig requires 'storage' configuration.");if(!r.providers)throw new Error("AgentFactoryConfig requires 'providers' configuration.")}async initialize(){switch(this.config.storage.type){case "indexedDB":this.storageAdapter=new K({dbName:this.config.storage.dbName||"ARTDB",objectStores:["conversations","observations","state"]});break;case "memory":default:this.storageAdapter=new H;break}if(await this.storageAdapter.init?.(),this.conversationRepository=new X(this.storageAdapter),this.observationRepository=new Q(this.storageAdapter),this.stateRepository=new W(this.storageAdapter),this.uiSystem=new pe(this.observationRepository,this.conversationRepository),this.conversationManager=new Z(this.conversationRepository,this.uiSystem.getConversationSocket()),this.stateManager=new ee(this.stateRepository),this.observationManager=new te(this.observationRepository,this.uiSystem.getObservationSocket()),this.toolRegistry=new re(this.stateManager),this.config.tools)for(let r of this.config.tools)await this.toolRegistry.registerTool(r);this.providerManager=new z(this.config.providers),o.info("ProviderManager initialized."),this.reasoningEngine=new ae(this.providerManager),this.promptManager=new oe,this.outputParser=new ie,this.toolSystem=new ne(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 r={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||B;return new e(r)}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 Be(g){let r=new fe(g);await r.initialize();let e=r.createAgent(),t=r.getUISystem(),n=r.getStateManager(),a=r.getConversationManager(),i=r.getToolRegistry(),s=r.getObservationManager();if(!t||!n||!a||!i||!s)throw new Error("Failed to initialize one or more core components within AgentFactory.");return {process:e.process.bind(e),uiSystem:t,stateManager:n,conversationManager:a,toolRegistry:i,observationManager:s}}var ye=class{providerName="gemini";apiKey;defaultModel;genAI;constructor(r){if(!r.apiKey)throw new Error("GeminiAdapter requires an apiKey in options.");this.apiKey=r.apiKey,this.defaultModel=r.model||"gemini-1.5-flash-latest",this.genAI=new GoogleGenAI({apiKey:this.apiKey}),o.debug(`GeminiAdapter initialized with default model: ${this.defaultModel}`);}async call(r,e){let{threadId:t,traceId:n=`gemini-trace-${Date.now()}`,sessionId:a,stream:i,callContext:s,model:l}=e,f=l||this.defaultModel,y;try{y=this.translateToGemini(r);}catch(I){return o.error(`Error translating ArtStandardPrompt to Gemini format: ${I.message}`,{error:I,threadId:t,traceId:n}),async function*(){yield {type:"ERROR",data:I instanceof Error?I:new Error(String(I)),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}()}let T={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(T).forEach(I=>T[I]===void 0&&delete T[I]),o.debug(`Calling Gemini SDK with model ${f}, stream: ${!!i}`,{threadId:t,traceId:n});let u=this.genAI;return async function*(){let I=Date.now(),E,d,M,R;try{if(i){let b=await u.models.generateContentStream({model:f,contents:y,config:T});for await(let p of b){R=p,E||(E=Date.now()-I);let v=p.text;v&&(yield {type:"TOKEN",data:v,threadId:t,traceId:n,sessionId:a,tokenType:s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"}),p.usageMetadata&&(o.debug("Gemini stream chunk usageMetadata:",{usageMetadata:p.usageMetadata,threadId:t,traceId:n}),d={...d||{},...p.usageMetadata});}let L=Date.now()-I;o.debug("Gemini stream finished processing chunks.",{totalGenerationTimeMs:L,threadId:t,traceId:n}),R?(M=R.candidates?.[0]?.finishReason,d=R.usageMetadata,o.debug("Gemini stream - Extracted from last chunk:",{finishReason:M,usageMetadata:d,threadId:t,traceId:n})):o.warn("Gemini stream - No last chunk found after loop.",{threadId:t,traceId:n});let w=d||{};yield {type:"METADATA",data:{stopReason:M,inputTokens:w?.promptTokenCount,outputTokens:w?.candidatesTokenCount,timeToFirstTokenMs:E,totalGenerationTimeMs:L,providerRawUsage:w,traceId:n},threadId:t,traceId:n,sessionId:a};}else {let b=await u.models.generateContent({model:f,contents:y,config:T}),L=b.candidates?.[0],w=b.text,N=L?.finishReason,p=b.usageMetadata,v=Date.now()-I;if(!L||!w){if(b.promptFeedback?.blockReason){o.error("Gemini SDK call blocked.",{feedback:b.promptFeedback,threadId:t,traceId:n}),yield {type:"ERROR",data:new Error(`Gemini API call blocked: ${b.promptFeedback.blockReason}`),threadId:t,traceId:n,sessionId:a};return}o.error("Invalid response structure from Gemini SDK: No text content found",{responseData:b,threadId:t,traceId:n}),yield {type:"ERROR",data:new Error("Invalid response structure from Gemini SDK: No text content found."),threadId:t,traceId:n,sessionId:a};return}let x=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"LLM_RESPONSE";yield {type:"TOKEN",data:w.trim(),threadId:t,traceId:n,sessionId:a,tokenType:x},yield {type:"METADATA",data:{stopReason:N,inputTokens:p?.promptTokenCount,outputTokens:p?.candidatesTokenCount,totalGenerationTimeMs:v,providerRawUsage:p,traceId:n},threadId:t,traceId:n,sessionId:a};}yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}catch(b){o.error(`Error during Gemini SDK call: ${b.message}`,{error:b,threadId:t,traceId:n}),yield {type:"ERROR",data:b instanceof Error?b:new Error(String(b)),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}}()}translateToGemini(r){let e=[],t=null;for(let n of r){let a,i=[];switch(n.role){case "system":typeof n.content=="string"?t=n.content:o.warn("GeminiAdapter: Ignoring non-string system prompt content.",{content:n.content});continue;case "user":{a="user";let s="";t&&(s+=t+`
|
|
36
|
+
|
|
37
|
+
`,t=null),typeof n.content=="string"?s+=n.content:(o.warn("GeminiAdapter: Stringifying non-string user content.",{content:n.content}),s+=JSON.stringify(n.content)),i.push({text:s});break}case "assistant":a="model",typeof n.content=="string"&&n.content.trim()!==""&&i.push({text:n.content}),n.tool_calls&&n.tool_calls.length>0&&n.tool_calls.forEach(s=>{s.type==="function"?i.push({functionCall:{name:s.function.name,args:JSON.parse(s.function.arguments||"{}")}}):o.warn(`GeminiAdapter: Skipping unsupported tool call type: ${s.type}`);}),i.length===0&&i.push({text:""});break;case "tool_result":if(a="user",!n.tool_call_id||!n.name)throw new c("GeminiAdapter: 'tool_result' message missing required 'tool_call_id' or 'name'.","PROMPT_TRANSLATION_FAILED");i.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:i});}return t&&(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:t}]})),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 Ae=class{providerName="openai";apiKey;model;apiBaseUrl;constructor(r){if(!r.apiKey)throw new Error("OpenAIAdapter requires an apiKey in options.");this.apiKey=r.apiKey,this.model=r.model||"gpt-3.5-turbo",this.apiBaseUrl=r.apiBaseUrl||"https://api.openai.com/v1",o.debug(`OpenAIAdapter initialized with model: ${this.model}`);}async call(r,e){let{threadId:t,traceId:n=`openai-trace-${Date.now()}`,sessionId:a,stream:i,callContext:s,model:l}=e,f=l||this.model,y;try{y=this.translateToOpenAI(r);}catch(m){return o.error(`Error translating ArtStandardPrompt to OpenAI format: ${m.message}`,{error:m,threadId:t,traceId:n}),async function*(){yield {type:"ERROR",data:m instanceof c?m:new c(`Prompt translation failed: ${m.message}`,"PROMPT_TRANSLATION_FAILED",m),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}()}let T=`${this.apiBaseUrl}/chat/completions`,u={model:f,messages:y,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:!!i};Object.keys(u).forEach(m=>u[m]===void 0&&delete u[m]),o.debug(`Calling OpenAI API: ${T} with model ${f}, stream: ${!!i}`,{threadId:t,traceId:n});try{let m=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(u)});if(!m.ok){let I=await m.text();return o.error(`OpenAI API request failed with status ${m.status}: ${I}`,{threadId:t,traceId:n}),async function*(){yield {type:"ERROR",data:new c(`OpenAI API request failed: ${m.status} ${m.statusText} - ${I}`,"LLM_PROVIDER_ERROR",new Error(I)),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}()}if(i&&m.body)return this.processStream(m.body,e);{let I=await m.json(),E=I.choices?.[0];if(!E?.message)return o.error("Invalid response structure from OpenAI API: No message found",{responseData:I,threadId:t,traceId:n}),async function*(){yield {type:"ERROR",data:new c("Invalid response structure from OpenAI API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(I))),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}();let d=E.message;return d.tool_calls&&o.debug("OpenAI response included tool calls (non-streaming)",{toolCalls:d.tool_calls,threadId:t,traceId:n}),o.debug(`OpenAI API call successful. Finish reason: ${E.finish_reason}`,{threadId:t,traceId:n}),async function*(){let R=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(d.content??"").trim(),threadId:t,traceId:n,sessionId:a,tokenType:R},yield {type:"METADATA",data:{stopReason:E.finish_reason,inputTokens:I.usage?.prompt_tokens,outputTokens:I.usage?.completion_tokens,providerRawUsage:{usage:I.usage,finish_reason:E.finish_reason},traceId:n},threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}()}}catch(m){return o.error(`Error during OpenAI API call: ${m.message}`,{error:m,threadId:t,traceId:n}),async function*(){yield {type:"ERROR",data:m instanceof c?m:new c(m.message,"LLM_PROVIDER_ERROR",m),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}()}}async*processStream(r,e){let{threadId:t,traceId:n,sessionId:a,callContext:i}=e,s=Date.now(),l,f=0,y,T=void 0,u,m=r.pipeThrough(new TextDecoderStream).getReader(),I="",E=false;for(;!E;)try{let{value:R,done:b}=await m.read();if(E=b,E)break;I+=R;let L=I.split(`
|
|
38
|
+
`);for(let w=0;w<L.length-1;w++){let N=L[w].trim();if(N!==""&&N.startsWith("data: ")){let p=N.substring(6);if(p==="[DONE]"){E=!0;break}try{let x=JSON.parse(p).choices?.[0];if(!x)continue;let P=x.delta?.content;if(typeof P=="string"&&P.length>0){let S=Date.now();l===void 0&&(l=S-s),f++,yield {type:"TOKEN",data:P,threadId:t??"",traceId:n??"",sessionId:a,tokenType:i==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"};}let C=x.delta?.tool_calls;C&&(u||(u=[]),C.forEach(S=>{S.index!==void 0&&(u[S.index]||(u[S.index]={}),S.id&&(u[S.index].id=S.id),S.type&&(u[S.index].type=S.type),S.function&&(u[S.index].function||(u[S.index].function={}),S.function.name&&(u[S.index].function.name=S.function.name),S.function.arguments&&(u[S.index].function.arguments=(u[S.index].function.arguments||"")+S.function.arguments)));}),o.debug("OpenAI stream tool call delta:",{deltaToolCalls:C,threadId:t,traceId:n})),x.finish_reason&&(y=x.finish_reason,o.debug(`OpenAI stream finish reason received: ${y}`,{threadId:t,traceId:n}));}catch(v){o.warn(`Failed to parse OpenAI stream chunk: ${p}`,{parseError:v,threadId:t,traceId:n});}}}I=L[L.length-1];}catch(R){o.error(`Error reading OpenAI stream: ${R.message}`,{error:R,threadId:t,traceId:n}),yield {type:"ERROR",data:R instanceof c?R:new c(`Error reading OpenAI stream: ${R.message}`,"LLM_PROVIDER_ERROR",R),threadId:t??"",traceId:n??"",sessionId:a??""},E=true;}let d=Date.now()-s;yield {type:"METADATA",data:{stopReason:y,outputTokens:f>0?f:void 0,timeToFirstTokenMs:l,totalGenerationTimeMs:d,providerRawUsage:{finish_reason:y,usage:T,aggregatedToolCalls:u},traceId:n},threadId:t??"",traceId:n??"",sessionId:a??""},yield {type:"END",data:null,threadId:t??"",traceId:n??"",sessionId:a??""},o.debug("OpenAI stream processing finished.",{threadId:t,traceId:n});}translateToOpenAI(r){return r.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 t={role:"assistant",content:typeof e.content=="string"?e.content:null};return e.tool_calls&&e.tool_calls.length>0&&(t.tool_calls=e.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new c(`OpenAIAdapter: Invalid tool_call structure in assistant message. ID: ${n.id}`,"PROMPT_TRANSLATION_FAILED");return {id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}})),t.content===""&&!t.tool_calls&&(t.content=null),t.content===""&&t.tool_calls&&(t.content=null),typeof t.content!="string"&&t.content!==null&&(t.content=null),t}case "tool_result":{if(!e.tool_call_id)throw new c("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 c("OpenAIAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw o.warn(`OpenAIAdapter: Skipping message with unknown role: ${e.role}`),new c(`OpenAIAdapter: Unknown message role '${e.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var Ke="claude-3-7-sonnet-20250219",je=4096,Te=class{providerName="anthropic";client;defaultModel;defaultMaxTokens;defaultTemperature;constructor(r){if(!r.apiKey)throw new c("AnthropicAdapter requires an apiKey in options.","INVALID_CONFIG");this.client=new Anthropic({apiKey:r.apiKey,baseURL:r.apiBaseUrl||void 0}),this.defaultModel=r.model||Ke,this.defaultMaxTokens=r.defaultMaxTokens||je,this.defaultTemperature=r.defaultTemperature,o.debug(`AnthropicAdapter initialized with model: ${this.defaultModel}`);}async call(r,e){let{threadId:t,traceId:n=`anthropic-trace-${Date.now()}`,sessionId:a,stream:i=false,callContext:s,model:l,tools:f,providerConfig:y}=e,T=y?.modelId||l||this.defaultModel,u=y?.adapterOptions||{},m=u.max_tokens||u.maxTokens||e.max_tokens||e.maxOutputTokens||this.defaultMaxTokens,I=u.temperature??e.temperature??this.defaultTemperature,E=u.top_p||u.topP||e.top_p||e.topP,d=u.top_k||u.topK||e.top_k||e.topK,M=u.stop_sequences||u.stopSequences||e.stop||e.stop_sequences||e.stopSequences;if(!m){let p=new c("Anthropic API requires 'max_tokens'.","INVALID_CONFIG");return async function*(){yield {type:"ERROR",data:p,threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}()}let R,b;try{let p=this.translateToAnthropicSdk(r);R=p.systemPrompt,b=p.messages;}catch(p){o.error(`Error translating ArtStandardPrompt to Anthropic SDK format: ${p.message}`,{error:p,threadId:t,traceId:n});let v=p instanceof c?p:new c(`Prompt translation failed: ${p.message}`,"PROMPT_TRANSLATION_FAILED",p);return async function*(){yield {type:"ERROR",data:v,threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}()}let L=f?this.translateArtToolsToAnthropic(f):void 0,w={model:T,messages:b,max_tokens:m,system:R,temperature:I,top_p:E,top_k:d,stop_sequences:M,stream:i,tools:L};return Object.keys(w).forEach(p=>{let v=p;w[v]===void 0&&delete w[v];}),o.debug(`Calling Anthropic API with model ${T}`,{stream:i,tools:!!L,threadId:t,traceId:n}),async function*(){try{if(i){let p=await this.client.messages.create(w,this.getRequestOptions(T)),v="",x=[],P,C,S=null,D={input_tokens:void 0,output_tokens:void 0},A,_;for await(let O of p)switch(O.type){case "message_start":o.debug("Anthropic stream: message_start",{usage:O.message.usage,threadId:t,traceId:n}),D.input_tokens=O.message.usage.input_tokens,D.output_tokens=O.message.usage.output_tokens,P=D.input_tokens,C=D.output_tokens,A={inputTokens:P,outputTokens:C,providerRawUsage:{usage:{...O.message.usage}},traceId:n},yield {type:"METADATA",data:A,threadId:t,traceId:n,sessionId:a};break;case "content_block_start":o.debug("Anthropic stream: content_block_start",{index:O.index,block:O.content_block,threadId:t,traceId:n});break;case "content_block_delta":if(o.debug("Anthropic stream: content_block_delta",{index:O.index,delta:O.delta,threadId:t,traceId:n}),O.delta.type==="text_delta"){let ue=O.delta.text;v+=ue,yield {type:"TOKEN",data:ue,threadId:t,traceId:n,sessionId:a,tokenType:s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE"};}break;case "content_block_stop":o.debug("Anthropic stream: content_block_stop",{index:O.index,threadId:t,traceId:n});break;case "message_delta":o.debug("Anthropic stream: message_delta",{delta:O.delta,usage:O.usage,threadId:t,traceId:n}),S=O.delta.stop_reason??S,O.usage.output_tokens!==void 0&&O.usage.output_tokens!==null&&(D.output_tokens=O.usage.output_tokens),C=D.output_tokens,_={inputTokens:P,outputTokens:C,stopReason:O.delta.stop_reason??void 0,providerRawUsage:{usage:{input_tokens:P,output_tokens:O.usage.output_tokens??void 0},delta:O.delta},traceId:n},yield {type:"METADATA",data:_,threadId:t,traceId:n,sessionId:a};break;case "message_stop":{if(o.debug("Anthropic stream: message_stop. Using accumulated data.",{threadId:t,traceId:n}),S==="tool_use"&&x.length>0){let q=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE",Ee=x.map(me=>({type:"tool_use",id:me.id,name:me.name,input:me.input}));v.trim()?yield {type:"TOKEN",data:[{type:"text",text:v.trim()},...Ee],threadId:t,traceId:n,sessionId:a,tokenType:q}:yield {type:"TOKEN",data:Ee,threadId:t,traceId:n,sessionId:a,tokenType:q};}else if(v.trim()){let q=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:v.trim(),threadId:t,traceId:n,sessionId:a,tokenType:q};}yield {type:"METADATA",data:{inputTokens:D.input_tokens??void 0,outputTokens:D.output_tokens??void 0,stopReason:S??void 0,providerRawUsage:{usage:{input_tokens:D.input_tokens??void 0,output_tokens:D.output_tokens??void 0},stop_reason:S},traceId:n},threadId:t,traceId:n,sessionId:a};break}default:{o.warn("Anthropic stream: unhandled raw stream event type",{eventType:O.type,event:O,threadId:t,traceId:n});break}}}else {let p=await this.client.messages.create(w,this.getRequestOptions(T));o.debug(`Anthropic API call successful (non-streaming). Stop Reason: ${p.stop_reason}`,{threadId:t,traceId:n});let v="",x=[];p.content.forEach(C=>{C.type==="text"?v+=C.text:C.type==="tool_use"&&x.push(C);}),v=v.trim();let P=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";if(p.stop_reason==="tool_use"&&x.length>0){let C=x.map(S=>({type:"tool_use",id:S.id,name:S.name,input:S.input}));v?yield {type:"TOKEN",data:[{type:"text",text:v},...C],threadId:t,traceId:n,sessionId:a,tokenType:P}:yield {type:"TOKEN",data:C,threadId:t,traceId:n,sessionId:a,tokenType:P};}else v?yield {type:"TOKEN",data:v,threadId:t,traceId:n,sessionId:a,tokenType:P}:p.stop_reason!=="tool_use"&&o.warn("Anthropic API (non-streaming): Empty response text and not a tool_use stop_reason.",{response:p,threadId:t,traceId:n});p.usage&&(yield {type:"METADATA",data:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,stopReason:p.stop_reason??void 0,providerRawUsage:{usage:p.usage,stop_reason:p.stop_reason,stop_sequence:p.stop_sequence},traceId:n},threadId:t,traceId:n,sessionId:a});}yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}catch(p){o.error(`Error during Anthropic API call: ${p.message}`,{error:p,threadId:t,traceId:n}),yield {type:"ERROR",data:p instanceof c?p:p instanceof Anthropic.APIError?new c(`Anthropic API Error (${p.status}): ${p.message}`,"LLM_PROVIDER_ERROR",p):new c(p.message||"Unknown Anthropic adapter error","LLM_PROVIDER_ERROR",p),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}}.bind(this)()}getRequestOptions(r){let e=[];return e.length>0?{headers:{"anthropic-beta":e.join(",")}}:{}}translateToAnthropicSdk(r){let e,t=[],n=null;for(let i of r){if(i.role==="system"){let f=typeof i.content=="string"?i.content:String(i.content);e?(o.warn("AnthropicAdapter: Multiple system messages found. Appending to existing system prompt."),e+=`
|
|
39
|
+
${f}`):e=f;continue}let s=this.mapArtMessageToAnthropicContent(i),l=i.role==="user"||i.role==="tool_result"?"user":"assistant";if(n===l&&t.length>0){let f=t[t.length-1],y;typeof f.content=="string"?y=[{type:"text",text:f.content}]:y=f.content;let T=typeof s=="string"?[{type:"text",text:s}]:s,u=[...y,...T];f.content=u,o.debug(`AnthropicAdapter: Merged consecutive ${l} messages.`);}else t.push({role:l,content:s}),n=l;}!e&&t.length>0&&t[0].role!=="user"&&(o.warn("AnthropicAdapter: Prompt does not start with user message and has no system prompt. Prepending an empty user message for compatibility."),t.unshift({role:"user",content:"(Previous turn context)"}));let a=r[r.length-1];return a?.role==="assistant"&&a.tool_calls&&a.tool_calls.length>0&&o.debug("AnthropicAdapter: Prompt ends with assistant requesting tool calls."),{systemPrompt:e,messages:t}}mapArtMessageToAnthropicContent(r){let e=[];if(r.content&&typeof r.content=="string"&&r.content.trim()!==""?e.push({type:"text",text:r.content}):r.content&&typeof r.content!="string"&&r.role!=="tool_result"&&(!r.tool_calls||r.tool_calls.length===0)&&(o.warn(`AnthropicAdapter: Non-string, non-tool_result, non-tool_call-only content for role ${r.role}, stringifying.`,{content:r.content}),e.push({type:"text",text:JSON.stringify(r.content)})),r.role==="assistant"&&r.tool_calls&&r.tool_calls.length>0&&r.tool_calls.forEach(t=>{if(t.type==="function")try{e.push({type:"tool_use",id:t.id,name:t.function.name,input:JSON.parse(t.function.arguments||"{}")});}catch(n){throw new c(`AnthropicAdapter: Failed to parse tool call arguments for tool ${t.function.name} (ID: ${t.id}). Arguments must be valid JSON. Error: ${n.message}`,"PROMPT_TRANSLATION_FAILED",n)}else o.warn(`AnthropicAdapter: Skipping non-function tool_call type: ${t.type}`);}),r.role==="tool_result"){if(!r.tool_call_id)throw new c("AnthropicAdapter: 'tool_result' message missing required 'tool_call_id'.","PROMPT_TRANSLATION_FAILED");let t={type:"tool_result",tool_use_id:r.tool_call_id};typeof r.content=="string"?t.content=r.content:Array.isArray(r.content)&&r.content.every(n=>typeof n=="object"&&n.type==="text"&&typeof n.text=="string")?t.content=r.content.map(n=>({type:"text",text:n.text})):r.content!==null&&r.content!==void 0&&(t.content=JSON.stringify(r.content)),e.push(t);}return e.length===1&&e[0].type==="text"?e[0].text:e.length===0?"":e}translateArtToolsToAnthropic(r){return r.map(e=>{if(!e.inputSchema||typeof e.inputSchema!="object")throw new c(`Invalid inputSchema definition for tool '${e.name}'. Expected a JSON schema object.`,"INVALID_CONFIG");return {name:e.name,description:e.description,input_schema:e.inputSchema}})}};var Ie=class{providerName="openrouter";apiKey;model;apiBaseUrl;siteUrl;appName;constructor(r){if(!r.apiKey)throw new Error("OpenRouterAdapter requires an apiKey in options.");if(!r.model)throw new Error("OpenRouterAdapter requires a model identifier in options (e.g., 'google/gemini-pro').");this.apiKey=r.apiKey,this.model=r.model,this.apiBaseUrl=r.apiBaseUrl||"https://openrouter.ai/api/v1",this.siteUrl=r.siteUrl,this.appName=r.appName,o.debug(`OpenRouterAdapter initialized for model: ${this.model}`);}async call(r,e){let{threadId:t,traceId:n=`openrouter-trace-${Date.now()}`,sessionId:a,stream:i,callContext:s,model:l}=e,f=l||this.model;if(i)return o.warn("OpenRouterAdapter: Streaming requested but not implemented. Returning error stream.",{threadId:t,traceId:n}),async function*(){yield {type:"ERROR",data:new c("Streaming is not yet implemented for the OpenRouterAdapter.","LLM_PROVIDER_ERROR"),threadId:t??"",traceId:n??"",sessionId:a},yield {type:"END",data:null,threadId:t??"",traceId:n??"",sessionId:a};}();let y;try{y=this.translateToOpenAI(r);}catch(d){return o.error(`Error translating ArtStandardPrompt to OpenRouter/OpenAI format: ${d.message}`,{error:d,threadId:t,traceId:n}),async function*(){yield {type:"ERROR",data:d instanceof c?d:new c(`Prompt translation failed: ${d.message}`,"PROMPT_TRANSLATION_FAILED",d),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}()}let T=`${this.apiBaseUrl}/chat/completions`,u=e.stop||e.stop_sequences||e.stopSequences,m={model:f,messages:y,temperature:e.temperature,max_tokens:e.max_tokens||e.maxOutputTokens,top_p:e.top_p||e.topP,stop:u,stream:false};Object.keys(m).forEach(d=>m[d]===void 0&&delete m[d]);let I={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return this.siteUrl&&(I["HTTP-Referer"]=this.siteUrl),this.appName&&(I["X-Title"]=this.appName),o.debug(`Calling OpenRouter API (non-streaming): ${T} with model ${this.model}`,{threadId:t,traceId:n}),async function*(){try{let d=await fetch(T,{method:"POST",headers:I,body:JSON.stringify(m)});if(!d.ok){let p=await d.text(),v=p;try{let P=JSON.parse(p);P?.error?.message&&(v=P.error.message);}catch{}yield {type:"ERROR",data:new c(`OpenRouter API request failed: ${d.status} ${d.statusText} - ${v}`,"LLM_PROVIDER_ERROR",new Error(p)),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};return}let M=await d.json(),R=M.choices?.[0];if(!R?.message){yield {type:"ERROR",data:new c("Invalid response structure from OpenRouter API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(M))),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};return}let b=R.message;b.tool_calls&&o.debug("OpenRouter response included tool calls (non-streaming)",{toolCalls:b.tool_calls,threadId:t,traceId:n}),o.debug(`OpenRouter API call successful. Finish reason: ${R.finish_reason}`,{threadId:t,traceId:n});let L=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(b.content??"").trim(),threadId:t,traceId:n,sessionId:a,tokenType:L},yield {type:"METADATA",data:{inputTokens:M.usage?.prompt_tokens,outputTokens:M.usage?.completion_tokens,stopReason:R.finish_reason,providerRawUsage:{usage:M.usage,finish_reason:R.finish_reason},traceId:n},threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}catch(d){o.error(`Error during OpenRouter API call: ${d.message}`,{error:d,threadId:t,traceId:n}),yield {type:"ERROR",data:d instanceof c?d:new c(d.message,"LLM_PROVIDER_ERROR",d),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}}()}translateToOpenAI(r){return r.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 t={role:"assistant",content:typeof e.content=="string"?e.content:null};return e.tool_calls&&e.tool_calls.length>0&&(t.tool_calls=e.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new c(`OpenRouterAdapter: Invalid tool_call structure in assistant message. ID: ${n.id}`,"PROMPT_TRANSLATION_FAILED");return {id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}})),t.content===""&&!t.tool_calls&&(t.content=null),t.content===""&&t.tool_calls&&(t.content=null),typeof t.content!="string"&&t.content!==null&&(t.content=null),t}case "tool_result":{if(!e.tool_call_id)throw new c("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 c("OpenRouterAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new c(`OpenRouterAdapter: Unknown message role '${e.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var Se=class{providerName="deepseek";apiKey;model;apiBaseUrl;constructor(r){if(!r.apiKey)throw new Error("DeepSeekAdapter requires an apiKey in options.");this.apiKey=r.apiKey,this.model=r.model||"deepseek-chat",this.apiBaseUrl=r.apiBaseUrl||"https://api.deepseek.com/v1",o.debug(`DeepSeekAdapter initialized with model: ${this.model}`);}async call(r,e){let{threadId:t,traceId:n=`deepseek-trace-${Date.now()}`,sessionId:a,stream:i,callContext:s,model:l}=e,f=l||this.model;if(i)return o.warn("DeepSeekAdapter: Streaming requested but not implemented. Returning error stream.",{threadId:t,traceId:n}),async function*(){yield {type:"ERROR",data:new c("Streaming is not yet implemented for the DeepSeekAdapter.","LLM_PROVIDER_ERROR"),threadId:t??"",traceId:n??"",sessionId:a},yield {type:"END",data:null,threadId:t??"",traceId:n??"",sessionId:a};}();let y;try{y=this.translateToOpenAI(r);}catch(d){return o.error(`Error translating ArtStandardPrompt to DeepSeek/OpenAI format: ${d.message}`,{error:d,threadId:t,traceId:n}),async function*(){yield {type:"ERROR",data:d instanceof c?d:new c(`Prompt translation failed: ${d.message}`,"PROMPT_TRANSLATION_FAILED",d),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}()}let T=`${this.apiBaseUrl}/chat/completions`,u=e.stop||e.stop_sequences||e.stopSequences,m={model:f,messages:y,temperature:e.temperature,max_tokens:e.max_tokens||e.maxOutputTokens,top_p:e.top_p||e.topP,stop:u,stream:false};Object.keys(m).forEach(d=>m[d]===void 0&&delete m[d]);let I={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return o.debug(`Calling DeepSeek API (non-streaming): ${T} with model ${this.model}`,{threadId:t,traceId:n}),async function*(){try{let d=await fetch(T,{method:"POST",headers:I,body:JSON.stringify(m)});if(!d.ok){let p=await d.text(),v=p;try{let P=JSON.parse(p);P?.error?.message&&(v=P.error.message);}catch{}yield {type:"ERROR",data:new c(`DeepSeek API request failed: ${d.status} ${d.statusText} - ${v}`,"LLM_PROVIDER_ERROR",new Error(p)),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};return}let M=await d.json(),R=M.choices?.[0];if(!R?.message){yield {type:"ERROR",data:new c("Invalid response structure from DeepSeek API: No message found.","LLM_PROVIDER_ERROR",new Error(JSON.stringify(M))),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};return}let b=R.message;b.tool_calls&&o.debug("DeepSeek response included tool calls (non-streaming)",{toolCalls:b.tool_calls,threadId:t,traceId:n}),o.debug(`DeepSeek API call successful. Finish reason: ${R.finish_reason}`,{threadId:t,traceId:n});let L=s==="AGENT_THOUGHT"?"AGENT_THOUGHT_LLM_RESPONSE":"FINAL_SYNTHESIS_LLM_RESPONSE";yield {type:"TOKEN",data:(b.content??"").trim(),threadId:t,traceId:n,sessionId:a,tokenType:L},yield {type:"METADATA",data:{inputTokens:M.usage?.prompt_tokens,outputTokens:M.usage?.completion_tokens,stopReason:R.finish_reason,providerRawUsage:{usage:M.usage,finish_reason:R.finish_reason},traceId:n},threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}catch(d){o.error(`Error during DeepSeek API call: ${d.message}`,{error:d,threadId:t,traceId:n}),yield {type:"ERROR",data:d instanceof c?d:new c(d.message,"LLM_PROVIDER_ERROR",d),threadId:t,traceId:n,sessionId:a},yield {type:"END",data:null,threadId:t,traceId:n,sessionId:a};}}()}translateToOpenAI(r){return r.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 t={role:"assistant",content:typeof e.content=="string"?e.content:null};return e.tool_calls&&e.tool_calls.length>0&&(t.tool_calls=e.tool_calls.map(n=>{if(n.type!=="function"||!n.function?.name||typeof n.function?.arguments!="string")throw new c(`DeepSeekAdapter: Invalid tool_call structure in assistant message. ID: ${n.id}`,"PROMPT_TRANSLATION_FAILED");return {id:n.id,type:n.type,function:{name:n.function.name,arguments:n.function.arguments}}})),t.content===""&&!t.tool_calls&&(t.content=null),t.content===""&&t.tool_calls&&(t.content=null),typeof t.content!="string"&&t.content!==null&&(t.content=null),t}case "tool_result":{if(!e.tool_call_id)throw new c("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 c("DeepSeekAdapter: Unexpected 'tool_request' role encountered during translation.","PROMPT_TRANSLATION_FAILED");default:throw new c(`DeepSeekAdapter: Unknown message role '${e.role}' encountered during translation.`,"PROMPT_TRANSLATION_FAILED")}})}};var Je={sqrt:h.sqrt,cbrt:h.cbrt,abs:h.abs,pow:h.pow,exp:h.exp,log:h.log,log10:h.log10,log2:h.log2,sin:h.sin,cos:h.cos,tan:h.tan,asin:h.asin,acos:h.acos,atan:h.atan,atan2:h.atan2,round:h.round,floor:h.floor,ceil:h.ceil,mod:h.mod,mean:h.mean,median:h.median,std:h.std,variance:h.variance,max:h.max,min:h.min,factorial:h.factorial,gamma:h.gamma,combinations:h.combinations,permutations:h.permutations,format:h.format},ve=class g{static toolName="calculator";resultStore=new Map;schema={name:g.toolName,description:`Evaluates mathematical expressions using a sandboxed mathjs environment.
|
|
35
40
|
You can reference previous calculation results using the 'ans' variable.
|
|
36
41
|
Supports standard operators (+, -, *, /, %, ^), variables via 'scope', complex numbers, and the following allowed functions:
|
|
37
42
|
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(
|
|
43
|
+
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(r,e){let t=r.expression,n=e.threadId||"default-thread",a=this.resultStore.get(n),i={...Je,...r.scope||{},...a!==void 0?{ans:a}:{}},s=e.traceId||"calculator-call";o.debug(`CalculatorTool executing with expression: "${t}" and combined scope keys: ${Object.keys(i).join(", ")}`,{callId:s,context:e});try{let l=evaluate(t,i),f;if(typeof l=="number"&&Number.isFinite(l))f=l;else if(h.isComplex(l))f=l.toString();else throw new Error(`Evaluation resulted in an unsupported type: ${h.typeOf(l)}`);return this.resultStore.set(n,l),o.info(`CalculatorTool evaluated "${t}" to ${f}`,{callId:s}),{callId:s,toolName:this.schema.name,status:"success",output:{result:f}}}catch(l){return o.error(`CalculatorTool failed to evaluate expression "${t}": ${l.message}`,{callId:s,error:l}),{callId:s,toolName:this.schema.name,status:"error",error:`Failed to evaluate expression: ${l.message}`}}}};var an="0.2.4";export{Te as AnthropicAdapter,ve as CalculatorTool,Se as DeepSeekAdapter,ye as GeminiAdapter,H as InMemoryStorageAdapter,K as IndexedDBStorageAdapter,Oe as LogLevel,o as Logger,Re as MessageRole,_e as ModelCapability,ge as ObservationType,Ae as OpenAIAdapter,Ie as OpenRouterAdapter,B as PESAgent,an as VERSION,Be as createArtInstance,U as generateUUID};//# sourceMappingURL=index.js.map
|
|
39
44
|
//# sourceMappingURL=index.js.map
|