@lunora/agent 1.0.0-alpha.2 → 1.0.0-alpha.21
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/channels.d.mts +39 -31
- package/dist/channels.d.ts +39 -31
- package/dist/channels.mjs +1 -181
- package/dist/component.d.mts +57 -68
- package/dist/component.d.ts +57 -68
- package/dist/component.mjs +2 -407
- package/dist/inbound.d.mts +20 -20
- package/dist/inbound.d.ts +20 -20
- package/dist/inbound.mjs +1 -32
- package/dist/index.d.mts +474 -490
- package/dist/index.d.ts +474 -490
- package/dist/index.mjs +1 -18
- package/dist/naming.d.mts +19 -19
- package/dist/naming.d.ts +19 -19
- package/dist/naming.mjs +1 -8
- package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +2 -0
- package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +1 -0
- package/dist/packem_shared/base64-jU-Ci6Tu.mjs +1 -0
- package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +1 -0
- package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +5 -0
- package/dist/packem_shared/codeTool-DYJVy-bH.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +1 -0
- package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +1 -0
- package/dist/packem_shared/common-Dck97z3Y.mjs +1 -0
- package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +1 -0
- package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +1 -0
- package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +1 -0
- package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +3 -0
- package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +1 -0
- package/dist/packem_shared/defineAgent-CKhzzmys.mjs +3 -0
- package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +1 -0
- package/dist/packem_shared/functionTool-CWHhkYqd.mjs +1 -0
- package/dist/packem_shared/graph-component-B2YmC2eL.mjs +2 -0
- package/dist/packem_shared/memory-DNRyyp1b.mjs +1 -0
- package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +1 -0
- package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +1 -0
- package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +3 -0
- package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +1 -0
- package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +1 -0
- package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +1 -0
- package/dist/packem_shared/types.d-boAM2Yi1.d.mts +1114 -0
- package/dist/packem_shared/types.d-boAM2Yi1.d.ts +1114 -0
- package/dist/sandbox.d.mts +126 -122
- package/dist/sandbox.d.ts +126 -122
- package/dist/sandbox.mjs +1 -109
- package/dist/telemetry/index.d.mts +185 -104
- package/dist/telemetry/index.d.ts +185 -104
- package/dist/telemetry/index.mjs +1 -4
- package/package.json +8 -8
- package/dist/packem_shared/AGENT_MODULE-Dnt_-AAT.mjs +0 -24
- package/dist/packem_shared/VoiceSessionDO-DLoXsHGF.mjs +0 -297
- package/dist/packem_shared/adaptMcpResult-wtNMvLoP.mjs +0 -65
- package/dist/packem_shared/agentAsTool-Dt8NlU6k.mjs +0 -94
- package/dist/packem_shared/base64-BVwtgRJV.mjs +0 -18
- package/dist/packem_shared/braintrustTelemetry-wuGDErob.mjs +0 -47
- package/dist/packem_shared/buildModelMessages-BWFigaoo.mjs +0 -69
- package/dist/packem_shared/codeTool-CjgJOC9t.mjs +0 -122
- package/dist/packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs +0 -97
- package/dist/packem_shared/combineTelemetry-DCyaaWAI.mjs +0 -43
- package/dist/packem_shared/common-DAeFCot5.mjs +0 -61
- package/dist/packem_shared/compileAgentWorkflow-BxJjHgtD.mjs +0 -55
- package/dist/packem_shared/consoleTelemetry-z2MiP1jt.mjs +0 -93
- package/dist/packem_shared/createAgentContext-4xJGXNR4.mjs +0 -50
- package/dist/packem_shared/createAgentGenerate-BQv9YJ01.mjs +0 -192
- package/dist/packem_shared/createDispatchRunner-DSbp_dph-ZHTtxy3f.mjs +0 -69
- package/dist/packem_shared/defineAgent-D6maSbVc.mjs +0 -148
- package/dist/packem_shared/defineSkill-Ctf_S-rz.mjs +0 -22
- package/dist/packem_shared/functionTool-D6lCa2jB.mjs +0 -20
- package/dist/packem_shared/graph-component-aoUwO-f0.mjs +0 -216
- package/dist/packem_shared/memory-D4FPcBsX.mjs +0 -12
- package/dist/packem_shared/normalizeEntityName-CyEEWFkR.mjs +0 -3
- package/dist/packem_shared/runAgentLoop-Dhg4ZNvw.mjs +0 -493
- package/dist/packem_shared/runVoiceTurn-LnqLvCRR.mjs +0 -211
- package/dist/packem_shared/sandboxComponent-DR3pTwBL.mjs +0 -194
- package/dist/packem_shared/sentryTelemetry-CgqFJyLO.mjs +0 -36
- package/dist/packem_shared/types.d-BhJFTvz_.d.mts +0 -1114
- package/dist/packem_shared/types.d-BhJFTvz_.d.ts +0 -1114
package/dist/index.mjs
CHANGED
|
@@ -1,18 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { collectAgenticMemoryTools, toSearchResults } from './packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs';
|
|
3
|
-
export { agentAsTool } from './packem_shared/agentAsTool-Dt8NlU6k.mjs';
|
|
4
|
-
export { codeTool } from './packem_shared/codeTool-CjgJOC9t.mjs';
|
|
5
|
-
export { agentComponent, agentExtension } from './component.mjs';
|
|
6
|
-
export { default as createAgentContext } from './packem_shared/createAgentContext-4xJGXNR4.mjs';
|
|
7
|
-
export { defineAgent, defineAgentTool, isAgentDefinition } from './packem_shared/defineAgent-D6maSbVc.mjs';
|
|
8
|
-
export { functionTool } from './packem_shared/functionTool-D6lCa2jB.mjs';
|
|
9
|
-
export { createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, resolveAgentModel } from './packem_shared/createAgentGenerate-BQv9YJ01.mjs';
|
|
10
|
-
export { adaptMcpResult, mcpTools } from './packem_shared/adaptMcpResult-wtNMvLoP.mjs';
|
|
11
|
-
export { buildModelMessages } from './packem_shared/buildModelMessages-BWFigaoo.mjs';
|
|
12
|
-
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from './naming.mjs';
|
|
13
|
-
export { AGENT_MODULE, DEFAULT_AGENT_FUNCTION_PATHS, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, toFunctionReference } from './packem_shared/AGENT_MODULE-Dnt_-AAT.mjs';
|
|
14
|
-
export { browserTool, containerTool, fsTool } from './sandbox.mjs';
|
|
15
|
-
export { defineSkill, isSkillDefinition } from './packem_shared/defineSkill-Ctf_S-rz.mjs';
|
|
16
|
-
export { default as VoiceSessionDO } from './packem_shared/VoiceSessionDO-DLoXsHGF.mjs';
|
|
17
|
-
export { runVoiceTurn } from './packem_shared/runVoiceTurn-LnqLvCRR.mjs';
|
|
18
|
-
export { default as compileAgentWorkflow } from './packem_shared/compileAgentWorkflow-BxJjHgtD.mjs';
|
|
1
|
+
import{runAgentLoop as t,splitForCompaction as r}from"./packem_shared/runAgentLoop-DNAt-pGz.mjs";import{collectAgenticMemoryTools as a,toSearchResults as i}from"./packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as l}from"./packem_shared/agentAsTool-CJCTyAQG.mjs";import{codeTool as p}from"./packem_shared/codeTool-DYJVy-bH.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-B1IfI7ro.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-CKhzzmys.mjs";import{functionTool as D}from"./packem_shared/functionTool-CWHhkYqd.mjs";import{createAgentGenerate as M,createEpisodeExtract as O,createGraphExtract as _,createStreamGenerate as C,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BUVImo85.mjs";import{adaptMcpResult as F,mcpTools as L}from"./packem_shared/adaptMcpResult-18G7zpFo.mjs";import{buildModelMessages as k}from"./packem_shared/buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as R,agentClassName as V,agentDefaultName as b,voiceBindingName as h,voiceClassName as w}from"./naming.mjs";import{AGENT_MODULE as I,DEFAULT_AGENT_FUNCTION_PATHS as P,SANDBOX_INVOKE_PATH as X,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-BXx-tSCe.mjs";import{browserTool as j,containerTool as q,fsTool as z}from"./sandbox.mjs";import{defineSkill as Q,isSkillDefinition as Y}from"./packem_shared/defineSkill-DfJxCwfZ.mjs";import{default as $}from"./packem_shared/VoiceSessionDO-CTaBSdXk.mjs";import{runVoiceTurn as oe}from"./packem_shared/runVoiceTurn-PkMsfG_v.mjs";import{default as re}from"./packem_shared/compileAgentWorkflow-C4xqSw82.mjs";export{I as AGENT_MODULE,P as DEFAULT_AGENT_FUNCTION_PATHS,X as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,$ as VoiceSessionDO,F as adaptMcpResult,l as agentAsTool,R as agentBindingName,V as agentClassName,c as agentComponent,b as agentDefaultName,x as agentExtension,j as browserTool,k as buildModelMessages,p as codeTool,a as collectAgenticMemoryTools,re as compileAgentWorkflow,q as containerTool,A as createAgentContext,M as createAgentGenerate,O as createEpisodeExtract,_ as createGraphExtract,C as createStreamGenerate,d as defineAgent,u as defineAgentTool,Q as defineSkill,z as fsTool,D as functionTool,N as isAgentDefinition,Y as isSkillDefinition,L as mcpTools,G as resolveAgentModel,t as runAgentLoop,oe as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,i as toSearchResults,h as voiceBindingName,w as voiceClassName};
|
package/dist/naming.d.mts
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name.
|
|
3
|
-
* @experimental
|
|
4
|
-
*/
|
|
2
|
+
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name.
|
|
3
|
+
* @experimental
|
|
4
|
+
*/
|
|
5
5
|
declare const agentClassName: (exportName: string) => string;
|
|
6
6
|
/**
|
|
7
|
-
* `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
|
|
8
|
-
* @experimental
|
|
9
|
-
*/
|
|
7
|
+
* `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
|
|
8
|
+
* @experimental
|
|
9
|
+
*/
|
|
10
10
|
declare const agentBindingName: (exportName: string) => string;
|
|
11
11
|
/**
|
|
12
|
-
* `supportBot` → `agent-support-bot` — the default deployed workflow name.
|
|
13
|
-
* @experimental
|
|
14
|
-
*/
|
|
12
|
+
* `supportBot` → `agent-support-bot` — the default deployed workflow name.
|
|
13
|
+
* @experimental
|
|
14
|
+
*/
|
|
15
15
|
declare const agentDefaultName: (exportName: string) => string;
|
|
16
16
|
/**
|
|
17
|
-
* `support` → `SupportVoiceDO` — the generated voice-session Durable Object
|
|
18
|
-
* class name (a subclass of `VoiceSessionDO`). Distinct from the agent's
|
|
19
|
-
* `WorkflowEntrypoint` (`SupportAgentWorkflow`): the voice path is a
|
|
20
|
-
* hibernatable-WebSocket DO that runs the per-turn STT→LLM→TTS pipeline in-DO,
|
|
21
|
-
* NOT the replay-durable Workflow.
|
|
22
|
-
* @experimental
|
|
23
|
-
*/
|
|
17
|
+
* `support` → `SupportVoiceDO` — the generated voice-session Durable Object
|
|
18
|
+
* class name (a subclass of `VoiceSessionDO`). Distinct from the agent's
|
|
19
|
+
* `WorkflowEntrypoint` (`SupportAgentWorkflow`): the voice path is a
|
|
20
|
+
* hibernatable-WebSocket DO that runs the per-turn STT→LLM→TTS pipeline in-DO,
|
|
21
|
+
* NOT the replay-durable Workflow.
|
|
22
|
+
* @experimental
|
|
23
|
+
*/
|
|
24
24
|
declare const voiceClassName: (exportName: string) => string;
|
|
25
25
|
/**
|
|
26
|
-
* `support` → `VOICE_SUPPORT` — the Cloudflare Durable Object binding name for the voice session.
|
|
27
|
-
* @experimental
|
|
28
|
-
*/
|
|
26
|
+
* `support` → `VOICE_SUPPORT` — the Cloudflare Durable Object binding name for the voice session.
|
|
27
|
+
* @experimental
|
|
28
|
+
*/
|
|
29
29
|
declare const voiceBindingName: (exportName: string) => string;
|
|
30
30
|
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
|
package/dist/naming.d.ts
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name.
|
|
3
|
-
* @experimental
|
|
4
|
-
*/
|
|
2
|
+
* `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name.
|
|
3
|
+
* @experimental
|
|
4
|
+
*/
|
|
5
5
|
declare const agentClassName: (exportName: string) => string;
|
|
6
6
|
/**
|
|
7
|
-
* `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
|
|
8
|
-
* @experimental
|
|
9
|
-
*/
|
|
7
|
+
* `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
|
|
8
|
+
* @experimental
|
|
9
|
+
*/
|
|
10
10
|
declare const agentBindingName: (exportName: string) => string;
|
|
11
11
|
/**
|
|
12
|
-
* `supportBot` → `agent-support-bot` — the default deployed workflow name.
|
|
13
|
-
* @experimental
|
|
14
|
-
*/
|
|
12
|
+
* `supportBot` → `agent-support-bot` — the default deployed workflow name.
|
|
13
|
+
* @experimental
|
|
14
|
+
*/
|
|
15
15
|
declare const agentDefaultName: (exportName: string) => string;
|
|
16
16
|
/**
|
|
17
|
-
* `support` → `SupportVoiceDO` — the generated voice-session Durable Object
|
|
18
|
-
* class name (a subclass of `VoiceSessionDO`). Distinct from the agent's
|
|
19
|
-
* `WorkflowEntrypoint` (`SupportAgentWorkflow`): the voice path is a
|
|
20
|
-
* hibernatable-WebSocket DO that runs the per-turn STT→LLM→TTS pipeline in-DO,
|
|
21
|
-
* NOT the replay-durable Workflow.
|
|
22
|
-
* @experimental
|
|
23
|
-
*/
|
|
17
|
+
* `support` → `SupportVoiceDO` — the generated voice-session Durable Object
|
|
18
|
+
* class name (a subclass of `VoiceSessionDO`). Distinct from the agent's
|
|
19
|
+
* `WorkflowEntrypoint` (`SupportAgentWorkflow`): the voice path is a
|
|
20
|
+
* hibernatable-WebSocket DO that runs the per-turn STT→LLM→TTS pipeline in-DO,
|
|
21
|
+
* NOT the replay-durable Workflow.
|
|
22
|
+
* @experimental
|
|
23
|
+
*/
|
|
24
24
|
declare const voiceClassName: (exportName: string) => string;
|
|
25
25
|
/**
|
|
26
|
-
* `support` → `VOICE_SUPPORT` — the Cloudflare Durable Object binding name for the voice session.
|
|
27
|
-
* @experimental
|
|
28
|
-
*/
|
|
26
|
+
* `support` → `VOICE_SUPPORT` — the Cloudflare Durable Object binding name for the voice session.
|
|
27
|
+
* @experimental
|
|
28
|
+
*/
|
|
29
29
|
declare const voiceBindingName: (exportName: string) => string;
|
|
30
30
|
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
|
package/dist/naming.mjs
CHANGED
|
@@ -1,8 +1 @@
|
|
|
1
|
-
const
|
|
2
|
-
const agentClassName = (exportName) => `${exportName.charAt(0).toUpperCase()}${exportName.slice(1)}AgentWorkflow`;
|
|
3
|
-
const agentBindingName = (exportName) => `AGENT_${exportName.replaceAll(CAMEL_BOUNDARY, "$1_$2").toUpperCase()}`;
|
|
4
|
-
const agentDefaultName = (exportName) => `agent-${exportName.replaceAll(CAMEL_BOUNDARY, "$1-$2").toLowerCase()}`;
|
|
5
|
-
const voiceClassName = (exportName) => `${exportName.charAt(0).toUpperCase()}${exportName.slice(1)}VoiceDO`;
|
|
6
|
-
const voiceBindingName = (exportName) => `VOICE_${exportName.replaceAll(CAMEL_BOUNDARY, "$1_$2").toUpperCase()}`;
|
|
7
|
-
|
|
8
|
-
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
|
|
1
|
+
const a=/([a-z0-9])([A-Z])/gu,s=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,t=e=>`AGENT_${e.replaceAll(a,"$1_$2").toUpperCase()}`,l=e=>`agent-${e.replaceAll(a,"$1-$2").toLowerCase()}`,o=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,r=e=>`VOICE_${e.replaceAll(a,"$1_$2").toUpperCase()}`;export{t as agentBindingName,s as agentClassName,l as agentDefaultName,r as voiceBindingName,o as voiceClassName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="agents",t="sandbox",s=`${t}:invoke`,n={appendMessage:`${e}:agentAppendMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`},r=a=>typeof a=="string"?{__lunoraRef:a}:a;export{e as AGENT_MODULE,n as DEFAULT_AGENT_FUNCTION_PATHS,s as SANDBOX_INVOKE_PATH,t as SANDBOX_MODULE,r as toFunctionReference};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as l}from"@lunora/ai";import{g as f}from"./createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs";import{o as y}from"./base64-jU-Ci6Tu.mjs";import{createStreamGenerate as p}from"./createAgentGenerate-BUVImo85.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as g,toFunctionReference as h}from"./AGENT_MODULE-BXx-tSCe.mjs";import{parseIdentity as m,pcmToWav as b,readTranscriptionText as w,readSynthesisAudio as v,runVoiceTurn as S,toByteIterable as A}from"./runVoiceTurn-PkMsfG_v.mjs";const I="@cf/openai/whisper-large-v3-turbo",k="@cf/deepgram/aura-1",x=8*1024*1024,B=256*1024,u=15,T=5e3;class W{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,n){this.state=t,this.env=e,this.agent=s,this.exportName=n,this.paths=g,this.ai=l({binding:e.AI,env:e}),this.streamGenerate=p(s,e),this.sttModel=s.voice?.stt??I,this.ttsModel=s.voice?.tts??k}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const e=new URL(t.url).searchParams.get("threadKey");if(!e)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,n=new s,i=n[0],r=n[1];this.state.acceptWebSocket(r);const c=crypto.randomUUID(),o=m(t.headers.get("x-lunora-identity")),d=t.headers.get("x-lunora-userid")??void 0;r.serializeAttachment?.({connectionId:c,threadKey:e,turn:0,...o===void 0?{}:{identity:o},...d===void 0?{}:{userId:d}}),this.send(r,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const a=this.agent.voice?.greeting;return a&&a.length>0&&this.state.waitUntil?.(this.speakGreeting(r,c,e,d,o,a)),new Response(null,{status:101,webSocket:i})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s)try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(n){this.send(t,{message:n instanceof Error?n.message:String(n),type:"error"})}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const s=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return f({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=b(t);return w(await this.ai.run(this.sttModel,{audio:y(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return v(await this.ai.run(this.ttsModel,{text:t,...s===void 0?{}:{speaker:s}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,s){let n;try{n=JSON.parse(s)}catch{return}if(n.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(this.controllers.has(e.connectionId)){this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(n.type==="commit"){const i=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:i});return}await this.runTurn(t,e,{text:n.text})}bufferAudio(t,e,s){const n=(this.bufferedBytes.get(t)??0)+e.byteLength;if(n>x){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"});return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,n)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((r,c)=>r+c.byteLength,0),n=new Uint8Array(s);let i=0;for(const r of e)n.set(r,i),i+=r.byteLength;return n}async runTurn(t,e,s){const n=new AbortController;this.controllers.set(e.connectionId,n);try{await S({agent:this.agent,connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:n.signal,streamGenerate:this.streamGenerate,synthesize:async(i,r)=>this.synthesizeWithSignal(i,r),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(e.connectionId)===n&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,n,i,r){const c=this.resolveRun(n,i),o=new AbortController,d=()=>o.signal.aborted;this.controllers.set(e,o);try{await c(h(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...n===void 0?{}:{owner:n}});for await(const a of A(await this.synthesizeWithSignal(r,o.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,a)}d()||(await c(h(this.paths.appendMessage),{content:r,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(t,{text:r,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===o&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>B&&s<T;)await new Promise(n=>{setTimeout(n,u)}),s+=u}}export{W as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{jsonSchema as s}from"ai";const c=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const e=(t.content??[]).filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>o.text).join(`
|
|
2
|
+
`);return t.isError===!0?`MCP tool error: ${e.length>0?e:"unknown error"}`:e.length>0?e:t.content},l=(t,e)=>({description:e.description??`MCP tool "${e.name}".`,execute:async o=>c(await t.callTool({arguments:o,name:e.name})),inputSchema:s(e.inputSchema),isLunoraAgentTool:!0}),u=async t=>{if(t.command!==void 0)throw new i("INTERNAL","@lunora/agent: mcpTools `command` (stdio transport) cannot run in the Workers runtime — pass a `url` for an HTTP/SSE MCP server, or inject a connected `client`");if(t.url===void 0)throw new i("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const e=new URL(t.url),{Client:o}=await import("@modelcontextprotocol/sdk/client/index.js");let r;if(t.transport==="sse"){const{SSEClientTransport:a}=await import("@modelcontextprotocol/sdk/client/sse.js");r=new a(e)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(e)}const n=new o({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await n.connect(r),n},w=async t=>{const e=t.client??await u(t),{tools:o}=await e.listTools(),r={};for(const n of o)t.only!==void 0&&!t.only.includes(n.name)||(r[`${t.prefix??""}${n.name}`]=l(e,n));return r};export{c as adaptMcpResult,w as mcpTools};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{jsonSchema as T}from"ai";import{isDuplicateInstanceError as $}from"../channels.mjs";import{agentBindingName as N}from"../naming.mjs";import{toFunctionReference as b,DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-BXx-tSCe.mjs";const E=new Set(["complete","errored","terminated"]),I=120,S=500,k=e=>e!==null&&typeof e=="object"&&typeof e.status=="string"?e.status:"unknown",L=async e=>{await new Promise(t=>{setTimeout(t,e)})},C=async(e,t,n,u)=>{for(let a=0;a<t;a+=1){const i=k(await e.status());if(E.has(i))return i;await u(n)}return"timeout"},R=e=>{for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},j=e=>{if(typeof e.name!="string"||e.name.length===0)throw new p("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its AGENT_* binding)");if(typeof e.description!="string"||e.description.length===0)throw new p("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");const{name:t}=e,n=N(t),u=e.maxPolls??I,a=e.pollIntervalMs??S,i=e.wait??L,m=b(A.listMessages),f=async(w,r)=>{const o=r.env[n];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new p("INTERNAL",`@lunora/agent: agent.asTool("${t}") found no Workflow binding "${n}" on env — declare the "${t}" agent so codegen wires its binding`);const d=`${r.threadKey}::sub::${t}::${r.toolCallId}`,g=`sub-${t}-${r.toolCallId}`,h={input:w.prompt,threadKey:d};let c;try{const l=await o.create({id:g,params:h});c=await o.get(l.id)}catch(l){if(!$(l))throw l;c=await o.get(g)}const s=await C(c,u,a,i);if(s==="errored"||s==="terminated")return`Sub-agent "${t}" ${s} before producing an answer.`;if(s==="timeout")return`Sub-agent "${t}" did not finish within the allotted time.`;const y=await r.run(m,{key:d});return R(y)};return{description:e.description,execute:f,inputSchema:T({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{j as agentAsTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=n=>{let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)},a=n=>{const e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.codePointAt(r)??0;return t};export{a,o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as g,t as p,r as l}from"./common-Dck97z3Y.mjs";const d=(o,a)=>typeof o=="string"&&o.length>0?o:a,i=o=>{const{functionId:a,logger:n,recordInputs:u=!1,recordOutputs:c=!1}=o;return{executeLanguageModelCall:e=>n.traced(async t=>{u&&t.log({input:l(e,"messages"),model:l(e,"modelId")});const r=await e.execute();return c&&t.log({output:r}),r},{name:d(a,"language_model_call"),type:"llm"}),executeTool:e=>{const t=l(l(e,"toolCall"),"toolName");return n.traced(async r=>{u&&r.log({input:p(e),tool:t});const s=await e.execute();return c&&r.log({output:s}),s},{name:d(t,"execute_tool"),type:"tool"})},onError:e=>{n.traced(t=>{t.log({error:g(e)})},{name:"error",type:"error"})}}};export{i as braintrustTelemetry};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const n=t=>t.toolCalls===void 0||t.toolCalls.length===0?{content:t.content,role:"assistant"}:{content:[...t.content.length>0?[{text:t.content,type:"text"}]:[],...t.toolCalls.map(o=>({input:o.input,toolCallId:o.id,toolName:o.name,type:"tool-call"}))],role:"assistant"},s=t=>({content:[{output:{type:"text",value:t.content},toolCallId:t.toolCallId??"",toolName:t.toolName??"",type:"tool-result"}],role:"tool"}),l=t=>{const o=[];t.instructions!==void 0&&t.instructions.length>0&&o.push({content:t.instructions,role:"system"}),t.memoryContext!==void 0&&t.memoryContext.length>0&&o.push({content:`Relevant context retrieved for this conversation:
|
|
2
|
+
|
|
3
|
+
${t.memoryContext}`,role:"system"}),t.summary!==void 0&&t.summary.length>0&&o.push({content:`Summary of the earlier conversation:
|
|
4
|
+
|
|
5
|
+
${t.summary}`,role:"system"});for(const e of t.history)if(e.status!=="awaiting_approval")switch(e.role){case"assistant":{o.push(n(e));break}case"system":{o.push({content:e.content,role:"system"});break}case"tool":{o.push(s(e));break}case"user":{o.push({content:e.content,role:"user"});break}}return o};export{l as buildModelMessages};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";import{jsonSchema as h}from"ai";const $=16,f=4e3,A=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=f?e:`${o.slice(0,f)}… [truncated]`},b=(e,o)=>{let t=e;for(const s of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,s))return;t=t[s]}return t},l=(e,o)=>{if(Array.isArray(e))return e.map(r=>l(r,o));if(e===null||typeof e!="object")return e;const t=e;if(typeof t.$from=="string"){const r=t.$from;if(!(r in o))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?b(o[r],t.$path):o[r]}const s={};for(const[r,i]of Object.entries(t))s[r]=l(i,o);return s},v=async(e,o,t,s)=>{const r=Array.isArray(e.steps)?e.steps.slice(0,s):[],i={},p=[],c=new Set;for(const n of r){if(c.has(n.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${n.id}" — each step id must be unique (later steps reference an output by id via $from)`);c.add(n.id)}for(const n of r){const d=o[n.tool];if(!d)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${n.tool}" (available: ${Object.keys(o).join(", ")})`);const y=l(n.input??{},i),m={...t,idempotencyKey:`${t.idempotencyKey}:${n.id}`,toolCallId:`${t.toolCallId}:${n.id}`},u=await d.execute(y,m);i[n.id]=u,p.push({id:n.id,output:A(u)})}return{final:p.at(-1)?.output,results:p}},w=e=>`Compose MULTIPLE tool calls in one turn as a script, instead of one call per turn. Provide \`steps\`: an ordered array of \`{ id, tool, input }\`. A later step's \`input\` may reference an earlier step's output with \`{ "$from": "<stepId>", "$path": "optional.dot.path" }\`. Available tools: ${Object.entries(e).map(([o,t])=>`"${o}" — ${t.description}`).join("; ")}.`,g=h({properties:{steps:{description:"Ordered tool calls; a later input may reference an earlier output via { $from, $path }.",items:{additionalProperties:!1,properties:{id:{description:"A name later steps reference this output by.",type:"string"},input:{additionalProperties:!0,description:"The tool input (may embed $from refs).",type:"object"},tool:{description:"The tool to call.",type:"string"}},required:["id","tool"],type:"object"},type:"array"}},required:["steps"],type:"object"}),E=(e,o={})=>{const t=e;if(!t||typeof t!="object"||Object.keys(t).length===0)throw new a("INTERNAL","@lunora/agent: codeTool requires a non-empty map of tools to compose");for(const[r,i]of Object.entries(t))if(i.needsApproval!==void 0&&i.needsApproval!==!1)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it has a \`needsApproval\` gate a code-mode script can't pause for. Expose it as a normal top-level tool, or gate the whole script via codeTool's \`needsApproval\`.`);const s=o.maxSteps??$;return{description:o.description??w(e),execute:(r,i)=>v(r,e,i,s),inputSchema:g,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{E as codeTool,l as resolveReferences,v as runToolScript};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonSchema as u}from"ai";import{toFunctionReference as d}from"./AGENT_MODULE-BXx-tSCe.mjs";const y=240,h=50,m=(t,i)=>t.length<=i?t:`${t.slice(0,i)}…`,l=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(h,Math.max(1,Math.trunc(t)))},f=(t,i)=>{const r=t??{},s=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:s.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:m(typeof o.text=="string"?o.text:"",i),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},g=u({additionalProperties:!1,properties:{query:{description:"Natural-language search query.",type:"string"},topK:{description:"Maximum number of hits to return.",type:"number"}},required:["query"],type:"object"}),k=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),x=(t,i,r)=>{const s=d(i),e=Math.max(1,t.snippetChars??y),o=t.topK;return{description:`Search long-term memory for passages relevant to a query. Returns ranked { id, sourceId, score, snippet } hits — call again with a refined query to dig deeper.${r===void 0?"":` Use \`${r}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,a)=>{const c=l(n.topK)??o,p=await a.run(s,{query:n.query,...c===void 0?{}:{topK:c}});return f(p,e)},inputSchema:g,isLunoraAgentTool:!0}},q=t=>{const i=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,s)=>s.run(i,{id:r.id}),inputSchema:k,isLunoraAgentTool:!0}},A=(t,i)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of i)e.knowledge&&r.push({key:e.name,...e.knowledge});const s={};for(const e of r){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,n=e.key==="default"?"readMemory":`read_${e.key}`,a=e.read!==void 0;s[o]=x(e,e.source,a?n:void 0),a&&(s[n]=q(e.read))}return s};export{A as collectAgenticMemoryTools,f as toSearchResults};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=e=>async n=>{await Promise.allSettled(e.map(async a=>a?.(n)))},r=e=>{const n=e.filter(a=>typeof a=="function");return a=>{let o=a.execute;for(const p of n.toReversed()){const l=o;o=()=>p({...a,execute:l})}return o()}},d=(...e)=>({executeLanguageModelCall:r(e.map(n=>n.executeLanguageModelCall)),executeTool:r(e.map(n=>n.executeTool)),onAbort:t(e.map(n=>n.onAbort)),onEmbedEnd:t(e.map(n=>n.onEmbedEnd)),onEmbedStart:t(e.map(n=>n.onEmbedStart)),onEnd:t(e.map(n=>n.onEnd)),onError:t(e.map(n=>n.onError)),onLanguageModelCallEnd:t(e.map(n=>n.onLanguageModelCallEnd)),onLanguageModelCallStart:t(e.map(n=>n.onLanguageModelCallStart)),onObjectStepEnd:t(e.map(n=>n.onObjectStepEnd)),onObjectStepStart:t(e.map(n=>n.onObjectStepStart)),onRerankEnd:t(e.map(n=>n.onRerankEnd)),onRerankStart:t(e.map(n=>n.onRerankStart)),onStart:t(e.map(n=>n.onStart)),onStepEnd:t(e.map(n=>n.onStepEnd)),onStepFinish:t(e.map(n=>n.onStepFinish)),onStepStart:t(e.map(n=>n.onStepStart)),onToolExecutionEnd:t(e.map(n=>n.onToolExecutionEnd)),onToolExecutionStart:t(e.map(n=>n.onToolExecutionStart))});export{d as combineTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=(o,e)=>{if(!(o===null||typeof o!="object"))return o[e]},y=o=>{const e={};for(const r of["inputTokens","outputTokens","totalTokens"]){const s=t(o,r);typeof s=="number"&&(e[r]=s)}return Object.keys(e).length>0?e:void 0},m=o=>{const e=t(t(o,"providerMetadata"),"gateway"),r=t(t(o,"response"),"headers"),s=d=>{const g=t(r,"get"),f=typeof g=="function"?g.call(r,d):t(r,d);return typeof f=="string"&&f.length>0?f:void 0},n={},c=t(e,"cost");typeof c=="number"&&Number.isFinite(c)&&(n.cost=c);const i=t(e,"cached"),a=t(e,"cacheStatus"),l=typeof a=="string"?a:s("cf-aig-cache-status");typeof i=="boolean"?n.cached=i:typeof l=="string"&&(n.cached=l.toUpperCase()==="HIT");const u=t(e,"logId")??t(e,"log_id"),p=typeof u=="string"&&u.length>0?u:s("cf-aig-log-id");return typeof p=="string"&&p.length>0&&(n.logId=p),Object.keys(n).length>0?n:void 0},b=o=>{const e=t(o,"toolCall"),r=t(e,"toolName"),s=typeof r=="string"?r:void 0,n=t(o,"toolOutput"),c=t(n,"type"),i=t(o,"success"),a=typeof i=="boolean"?i:c!=="tool-error",l=t(o,"toolExecutionMs");return{error:a?void 0:t(n,"error")??t(o,"error"),name:s,output:a?t(n,"output"):void 0,success:a,toolExecutionMs:typeof l=="number"?l:void 0}},h=o=>{const e=t(t(o,"toolCall"),"toolName");return typeof e=="string"?e:void 0},v=o=>t(t(o,"toolCall"),"input"),T=o=>{if(!Array.isArray(o))return;let e="";for(const r of o)if(t(r,"type")==="text"){const s=t(r,"text");typeof s=="string"&&(e+=s)}return e.length>0?e:void 0},x=o=>o instanceof Error?{message:o.message,name:o.name}:o;export{b as a,h as b,T as c,x as d,m as e,t as r,y as s,v as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defineWorkflow as m}from"@lunora/workflow";import{runAgentLoop as i}from"./runAgentLoop-DNAt-pGz.mjs";import{createStreamGenerate as p,createAgentGenerate as c,createEpisodeExtract as l,createGraphExtract as d,createCompact as f}from"./createAgentGenerate-BUVImo85.mjs";import{agentDefaultName as u}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as v}from"./AGENT_MODULE-BXx-tSCe.mjs";import{g as E}from"./createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs";import{otlpTelemetry as N}from"./otlpTelemetry-DcW9mOLV.mjs";const T=(t,r,a)=>r===void 0?t:E({env:a,identity:{userId:r},label:"@lunora/agent"}),g=(t,r,a)=>{const e=r.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||t.telemetry?.isEnabled===!1)return t;const n=typeof r.LUNORA_OTLP_TOKEN=="string"?r.LUNORA_OTLP_TOKEN:void 0,o=[t.telemetry?.integrations].flat().filter(s=>s!==void 0);return{...t,telemetry:{...t.telemetry,integrations:[...o,N({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},G=(t,r,a)=>m({handler:async e=>{const n=g(t,e.env,e.params.threadKey);return i({agent:n,compact:f(),env:e.env,exportName:r,extractGraph:d(),extractEpisode:l(),generate:c(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??v,run:T(e.run,e.params.owner,e.env),step:e.step,streamGenerate:p(n,e.env)})},name:t.name??u(r)});export{G as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as f,d as u,s as l,c as g,a as I,r as o,b as m}from"./common-Dck97z3Y.mjs";const b=(i,r,s)=>{const a=globalThis.console;i==="error"?a.error(r,s):i==="warn"?a.warn(r,s):a.info(r,s)},x=(i={})=>{const{functionId:r,logger:s=b,recordInputs:a=!1,recordOutputs:c=!1}=i,p=r===void 0?"":`[${r}] `,t=(e,n,d)=>{s(e,`${p}${n}`,d)};return{onAbort:e=>{t("warn","agent operation aborted",{callId:o(e,"callId"),reason:o(e,"reason")})},onEnd:e=>{t("info","agent operation completed",{callId:o(e,"callId"),finishReason:o(e,"finishReason"),operationId:o(e,"operationId"),usage:l(o(e,"usage"))})},onError:e=>{t("error","agent operation errored",{error:u(e)})},onLanguageModelCallEnd:e=>{const n={callId:o(e,"callId"),finishReason:o(e,"finishReason"),modelId:o(e,"modelId"),provider:o(e,"provider"),usage:l(o(e,"usage"))};c&&(n.text=g(o(e,"content"))),t("info","language model call ended",n)},onStart:e=>{t("info","agent operation started",{callId:o(e,"callId"),modelId:o(e,"modelId"),operationId:o(e,"operationId"),provider:o(e,"provider")})},onStepEnd:e=>{t("info","agent step ended",{finishReason:o(e,"finishReason"),stepNumber:o(e,"stepNumber"),usage:l(o(e,"usage"))})},onStepStart:e=>{t("info","agent step started",{stepNumber:o(e,"stepNumber")})},onToolExecutionEnd:e=>{const n=I(e),d={success:n.success,tool:n.name,toolExecutionMs:n.toolExecutionMs};n.success||(d.error=u(n.error)),c&&n.success&&(d.output=n.output),t(n.success?"info":"warn","tool execution ended",d)},onToolExecutionStart:e=>{const n={tool:m(e)};a&&(n.input=f(e)),t("info","tool execution started",n)}}};export{x as consoleTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{g as d}from"./createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs";import{LunoraError as f}from"@lunora/errors";import{toFunctionReference as g,DEFAULT_AGENT_FUNCTION_PATHS as l}from"./AGENT_MODULE-BXx-tSCe.mjs";const y=(r,i,c)=>{const o={},s=g(l.patchThread),u=()=>c??d({env:r,label:"@lunora/agent"});for(const n of i){const e=()=>{const t=r[n.binding];if(!t||typeof t.create!="function"||typeof t.get!="function")throw new f("INTERNAL",`@lunora/agent: no Workflow binding "${n.binding}" on env for agent "${n.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return t};o[n.exportName]={cancel:async t=>{await(await e().get(t)).terminate();try{await u()(s,{instanceId:t,status:"cancelled"})}catch{}},publicRun:n.publicRun===!0,run:async(t,a)=>({id:(await e().create({...a?.id===void 0?{}:{id:a.id},params:t})).id}),sendEvent:async(t,a)=>{await(await e().get(t)).sendEvent(a)},status:async t=>(await e().get(t)).status()}}return o};export{y as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{createAi as T}from"@lunora/ai";import{LunoraError as w}from"@lunora/errors";import{jsonSchema as x,generateText as d,streamText as k,Output as g,tool as j}from"ai";const y=t=>{if(!t)return;const e={};return t.inputTokens!==void 0&&(e.inputTokens=t.inputTokens),t.outputTokens!==void 0&&(e.outputTokens=t.outputTokens),t.totalTokens!==void 0&&(e.totalTokens=t.totalTokens),Object.keys(e).length>0?e:void 0},f=t=>t.map(e=>({id:e.toolCallId,input:e.input,name:e.toolName})),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=e.AI;if(!o)throw new w("INTERNAL",`@lunora/agent: the agent model "${t}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return T({binding:o,env:e}).model(t)}return t},v=(t,e)=>{const o=m(t.model,e),n={};for(const[i,a]of Object.entries(t.tools??{}))n[i]=j({description:a.description,inputSchema:a.inputSchema});const s=t.output===void 0?void 0:g.object({schema:t.output}),r={...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{maxOutputTokens:t.maxOutputTokens},...t.telemetry===void 0?{}:{telemetry:t.telemetry},...t.repairToolCall===void 0?{}:{experimental_repairToolCall:t.repairToolCall}};return{defaultModel:o,output:s,staticSettings:r,tools:n}},b=(t,{activeTools:e,messages:o,model:n,signal:s,toolChoice:r})=>{const{defaultModel:i,output:a,staticSettings:h,tools:l}=t,c=e===void 0?l:Object.fromEntries(Object.entries(l).filter(([p])=>e.includes(p)));return{messages:o,model:n??i,...h,...Object.keys(c).length>0?{tools:c}:{},...r===void 0?{}:{toolChoice:r},...a===void 0?{}:{output:a},...s===void 0?{}:{abortSignal:s}}},N=(t,e)=>{const o=v(t,e);return async n=>{const s=await d(b(o,n)),r=y(s.usage);return{text:s.text,toolCalls:f(s.toolCalls),...r===void 0?{}:{usage:r},...o.output===void 0?{}:{output:s.output}}}},q=(t,e)=>{const o=v(t,e);return async(n,s)=>{const r=k(b(o,n));let i="";try{for await(const u of r.textStream)i+=u,s(u)}catch(u){if(n.signal?.aborted)return{text:i,toolCalls:[]};throw u}const[a,h,l,c]=await Promise.all([r.text,r.toolCalls,r.usage,o.output===void 0?Promise.resolve(void 0):r.output]),p=y(l);return{text:a,toolCalls:f(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:c}}}},C=x({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),O=(t,e)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
2
|
+
`),$=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{output:s}=await d({model:m(o,e),output:g.object({schema:C}),prompt:O(n,t)});return s},A=(t,e)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
3
|
+
`),G=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{text:s}=await d({model:m(o,e),prompt:A(n,t)});return{summary:s.trim()}},S="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",M=()=>async({env:t,messages:e,model:o})=>{const{text:n}=await d({messages:e,model:m(o,t),system:S});return n.trim()};export{N as createAgentGenerate,M as createCompact,G as createEpisodeExtract,$ as createGraphExtract,q as createStreamGenerate,m as resolveAgentModel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";const p="/_lunora/scheduler/dispatch",y=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},N=(t,e,r)=>{try{const n=JSON.parse(r)?.error;if(typeof n=="object"&&n!==null&&typeof n.code=="string"){const{code:s,data:c,message:i}=n;return new a(s,typeof i=="string"?i:void 0,{data:c,status:e})}}catch{}return new a("INTERNAL",`${t}: function dispatch failed (${String(e)}): ${r}`,{status:e})},w=t=>{const{label:e}=t,r=globalThis.fetch,n=t.fetchImpl??(typeof r=="function"?r.bind(globalThis):void 0);return async(s,c,i={})=>{if(typeof n!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const u=t.env.LUNORA_ORIGIN_URL;if(typeof u!="string"||u.length===0)throw new a("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const h=t.env.LUNORA_ADMIN_TOKEN;if(typeof h!="string"||h.length===0)throw new a("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const d=`${y(u)}${p}`,l={authorization:`Bearer ${h}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(l["x-lunora-userid"]=t.identity.userId),t.identity?.claims!==void 0&&(l["x-lunora-identity"]=JSON.stringify(t.identity.claims));const o=await n(d,{body:JSON.stringify({args:c??{},functionPath:s.__lunoraRef,shardKey:i.shardKey}),headers:l,method:"POST"});if(!o.ok)throw N(e,o.status,await o.text());const f=await o.text();if(f.length!==0)try{return JSON.parse(f)}catch{throw new a("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(o.status)}): ${f}`,{status:o.status})}}};export{w as g};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as d}from"./agentAsTool-CJCTyAQG.mjs";import{r as m}from"./memory-DNRyyp1b.mjs";import{SKILL_NAME_PATTERN as h,RESERVED_SKILL_NAME as c}from"./defineSkill-DfJxCwfZ.mjs";const w=/^[a-zA-Z][\w-]*$/u,p=(e,r)=>{const o={...e.tools};for(const n of r)for(const[t,a]of Object.entries(n.tools??{})){if(Object.hasOwn(o,t))throw new s("INTERNAL",`@lunora/agent: skill "${n.name}" tool "${t}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[t]=a}return o},y=(e,r)=>{const o=[];for(const n of[e.instructions,...r.map(t=>t.instructions)])n&&o.push(n);return o.length<=1?o[0]:n=>o.map(t=>typeof t=="function"?t(n):t).filter(t=>t.length>0).join(`
|
|
2
|
+
|
|
3
|
+
`)},N=(e,r)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const n of r)n.knowledge&&m(n.knowledge)&&o.push({key:n.name,...n.knowledge});return o},T=e=>{const r=new Set;for(const o of e){if(typeof o.name!="string"||!h.test(o.name))throw new s("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new s("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(r.has(o.name))throw new s("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);r.add(o.name)}},A=(e,r)=>{if(e===void 0)return;const o=Object.keys(r).filter(n=>!e.includes(n));if(o.length>0)throw new s("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(n=>`"${n}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},k=(e,r)=>{const o=(n,t)=>{if(n&&n.kind!=="graph"&&n.kind!=="episodic"&&n.source===void 0)throw new s("INTERNAL",`@lunora/agent: ${t} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const n of r)o(n.knowledge,`skill "${n.name}" \`knowledge\``)},$=e=>{const r=e.model;if(r==null||typeof r=="string"&&r.length===0)throw new s("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(e.maxTurns!==void 0&&(!Number.isInteger(e.maxTurns)||e.maxTurns<1))throw new s("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");const o=e.skills??[];T(o),k(e,o);const n=p(e,o),t=f(e,o);for(const[i,g]of Object.entries(t)){if(Object.hasOwn(n,i))throw new s("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);n[i]=g}const a=Object.keys(t).length>0;A(e.activeTools,t);for(const i of Object.keys(n))if(!w.test(i))throw new s("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=N(e,o),u=y(e,o);return{...e,asTool:d,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:u}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:n}:{}}},b=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,j=e=>{if(typeof e.execute!="function")throw new s("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new s("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{$ as defineAgent,j as defineAgentTool,b as isAgentDefinition};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as t}from"@lunora/errors";const r=/^[a-zA-Z][\w-]*$/u,i="default",a=e=>{if(typeof e.name!="string"||!r.test(e.name))throw new t("INTERNAL",`@lunora/agent: defineSkill requires a \`name\` that is a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(e.name)}`);if(e.name===i)throw new t("INTERNAL",`@lunora/agent: skill name "${i}" is reserved (it keys the agent's own \`memory\` source / the historic \`memory:retrieve\` step) — choose another name`);return{...e,isLunoraSkill:!0}},o=e=>typeof e=="object"&&e!==null&&e.isLunoraSkill===!0;export{i as RESERVED_SKILL_NAME,r as SKILL_NAME_PATTERN,a as defineSkill,o as isSkillDefinition};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as e}from"@lunora/errors";import{toFunctionReference as c}from"./AGENT_MODULE-BXx-tSCe.mjs";const s=(n,o)=>{if(typeof o.description!="string"||o.description.length===0)throw new e("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(o.inputSchema===void 0)throw new e("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const t=c(n);return{description:o.description,execute:(r,i)=>i.run(t,r),inputSchema:o.inputSchema,isLunoraAgentTool:!0}};export{s as functionTool};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{defineTable as f,initLunora as v}from"@lunora/server";import{v as e}from"@lunora/values";const A="agent",x=t=>({...t,visibility:"internal"}),S=t=>{const n={};for(const[a,r]of Object.entries(t))r!==void 0&&(n[a]=r);return n},O="entities",K="edges",N=`${A}_${O}`,g=`${A}_${K}`,E={[O]:f({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[K]:f({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},q=64,C=2,$=4,I=8,j=32,L=500,M=/\s+/gu,T=/[^\p{L}\p{N}]+/u,b=t=>t.trim().replaceAll(M," ").toLowerCase(),_=t=>t.toLowerCase().split(T).filter(n=>n.length>=2),D=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,n)=>n.weight-t.weight||t.label.localeCompare(n.label)||t.srcName.localeCompare(n.srcName)||t.dstName.localeCompare(n.dstName),k=(t,n)=>n.some(a=>t.includes(a)||a.includes(t)),G=t=>t.map(n=>`- ${n.srcName} —[${n.label}]→ ${n.dstName}`).toSorted((n,a)=>n.localeCompare(a)).join(`
|
|
2
|
+
`),P=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,z=(t,n,a,r)=>{const s=P(t);r.collectedKeys.has(s)||(r.collectedKeys.add(s),r.collected.push(t));const l=t.srcName===n?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<a.maxNodes&&(r.seen.add(l),r.next.push(l))},B=async(t,n,a)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(n)};let s=n.slice(0,a.maxNodes);for(let l=0;l<a.depth&&s.length>0;l+=1){r.next=[];for(const u of s){const o=(await t(u)).toSorted(U).slice(0,a.fanOut);for(const m of o)z(m,u,a,r)}s=r.next}return r.collected},{mutation:F,query:H}=v.dataModel().create(),J=()=>{const t=F.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:a,ctx:r})=>{const s=Date.now(),l=async(c,i)=>{const d=b(c);if(d.length===0)return;const w=await r.db.query(N).withIndex("byOwnerName",p=>p.eq("owner",a.owner).eq("name",d)).first();return w?(i!==void 0&&w.type===void 0&&await r.db.patch(w._id,{type:i,updatedAt:s}),d):(await r.db.insert(N,{createdAt:s,name:d,owner:a.owner,updatedAt:s,weight:1,...S({firstMessageKey:a.messageKey,type:i})}),d)},u=async c=>{const i=b(c.src),d=b(c.dst),w=b(c.label);if(i.length===0||d.length===0||w.length===0||i===d)return!1;await l(i),await l(d);const p=c.confidence??1,y=await r.db.query(g).withIndex("byTriple",h=>h.eq("owner",a.owner).eq("srcName",i).eq("label",w).eq("dstName",d)).first();if(y){const h=y.weight??1;await r.db.patch(y._id,{updatedAt:s,weight:Math.max(h,p)})}else await r.db.insert(g,{createdAt:s,dstName:d,label:w,messageKey:a.messageKey,owner:a.owner,srcName:i,updatedAt:s,weight:p});return!0};let o=0;for(const c of a.entities.slice(0,q))await l(c.name,c.type)!==void 0&&(o+=1);let m=0;for(const c of a.relations.slice(0,q))await u(c)&&(m+=1);return{entities:o,relations:m}}),n=H.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:a,ctx:r})=>{const s=_(a.query);if(s.length===0)return{context:""};const l=(await r.db.query(N).withIndex("byOwnerUpdatedAt",o=>o.eq("owner",a.owner)).order("desc").take(L)).filter(o=>k(o.name,s)).toSorted((o,m)=>(m.weight??1)-(o.weight??1)||o.name.localeCompare(m.name)).slice(0,a.maxSeeds??$).map(o=>o.name);if(l.length===0)return{context:""};const u=await B(async o=>{const[m,c]=await Promise.all([r.db.query(g).withIndex("byOwnerSrc",i=>i.eq("owner",a.owner).eq("srcName",o)).collect(),r.db.query(g).withIndex("byOwnerDst",i=>i.eq("owner",a.owner).eq("dstName",o)).collect()]);return[...m,...c].map(i=>D(i))},l,{depth:a.depth??C,fanOut:a.fanOut??I,maxNodes:a.maxNodes??j});return{context:G(u)}});return{agentGraphTraverse:x(n),agentGraphUpsert:x(t)}};export{x as i,J as j,A as o,b as p,E as q,S as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=i=>i.kind==="graph"||i.kind==="episodic"||i.mode!=="agentic",m=i=>i.memorySources?i.memorySources:i.memory&&o(i.memory)?[{key:"default",...i.memory}]:[],r=i=>m(i).find(d=>d.kind==="graph"),n=i=>m(i).find(d=>d.kind==="episodic"),e=(i,d)=>d==="default"?i:`${i}:${d}`;export{e as c,r as i,m as n,o as r,n as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@lunora/server";import"@lunora/values";import{j as m,q as t,p as e}from"./graph-component-B2YmC2eL.mjs";export{m as graphComponent,t as graphTables,e as normalizeEntityName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as U,r as d,e as V,c as j,t as A,b as z}from"./common-Dck97z3Y.mjs";const I=e=>`${String(Math.round(e))}000000`,w=e=>{const t=new Uint8Array(e);crypto.getRandomValues(t);let o="";for(const n of t)o+=n.toString(16).padStart(2,"0");return o},x=(e,t)=>typeof t=="boolean"?{key:e,value:{boolValue:t}}:typeof t=="number"?Number.isFinite(t)?Number.isSafeInteger(t)?{key:e,value:{intValue:String(t)}}:{key:e,value:{doubleValue:t}}:{key:e,value:{stringValue:String(t)}}:{key:e,value:{stringValue:t}},C=(e,t,o)=>{const n={},c=new Map,m=(u,g)=>{const h=u.toLowerCase(),b=c.get(h);b===void 0?(c.set(h,u),n[u]=g):n[b]=g};for(const[u,g]of Object.entries(e))m(u,g);for(const[u,g]of Object.entries(t??{}))m(u,g);return o!==void 0&&o.length>0&&m("authorization",`Bearer ${o}`),n},D=e=>Array.isArray(e)?e:[e],M=(e,t)=>{const o={"service.name":e};for(const[n,c]of Object.entries({}))o[n]=c;return Object.entries(o).map(([n,c])=>x(n,c))},F=(e,t,o,n)=>({resourceSpans:[{resource:{attributes:M(o)},scopeSpans:[{scope:{name:t},spans:D(e)}]}]}),a=(e,t,o)=>{if(o!=null){if(typeof o=="boolean"||typeof o=="number"||typeof o=="string"){e.push(x(t,o));return}e.push(x(t,JSON.stringify(o)))}},T=(e,t)=>{(async()=>{let o;try{o=await e}catch(n){t(!1,n instanceof Error?n.message:String(n),void 0);return}t(!0,void 0,o)})().catch(()=>{})},L=e=>{const{conversationId:t,endpoint:o,headers:n,recordInputs:c=!1,recordOutputs:m=!1,token:u,traceId:g,waitUntil:h}=e,b=e.serviceName??"lunora";let v=o;for(;v.endsWith("/");)v=v.slice(0,-1);const N=`${v}/v1/traces`,$=C({"content-type":"application/json"},n,u),O=(r,f,l,p,y)=>{const _={attributes:y,endTimeUnixNano:I(Date.now()),kind:1,name:r,spanId:w(8),startTimeUnixNano:I(f),status:l?{code:1}:{code:2,message:p??""},traceId:g??w(16)};try{const i=fetch(N,{body:JSON.stringify(F(_,"@lunora/agent",b)),headers:$,method:"POST"}).catch(()=>{});h?.(i)}catch{}};return{executeLanguageModelCall:r=>{const f=Date.now(),l=d(r,"modelId"),p=r.execute();return T(p,(y,_,i)=>{const s=[];a(s,"gen_ai.operation.name","chat"),a(s,"gen_ai.request.model",l),a(s,"gen_ai.system",d(r,"provider")),a(s,"gen_ai.conversation.id",t);const k=U(d(i,"usage"));k&&(a(s,"gen_ai.usage.input_tokens",k.inputTokens),a(s,"gen_ai.usage.output_tokens",k.outputTokens),a(s,"gen_ai.usage.total_tokens",k.totalTokens));const S=V(i);S&&(a(s,"gen_ai.usage.cost",S.cost),a(s,"gen_ai.response.cached",S.cached),a(s,"cf.aig.log_id",S.logId)),c&&a(s,"gen_ai.prompt",d(r,"messages")),m&&a(s,"gen_ai.completion",j(d(i,"content"))),O(typeof l=="string"?`chat ${l}`:"language_model_call",f,y,_,s)}),p},executeTool:r=>{const f=Date.now(),l=z(r),p=r.execute();return T(p,(y,_)=>{const i=[];a(i,"gen_ai.operation.name","execute_tool"),a(i,"gen_ai.tool.name",l),a(i,"gen_ai.tool.call.id",d(r,"toolCallId")),c&&a(i,"gen_ai.tool.input",A(r)),O(typeof l=="string"?`execute_tool ${l}`:"execute_tool",f,y,_,i)}),p}}};export{L as otlpTelemetry};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{resolveAgentModel as q}from"./createAgentGenerate-BUVImo85.mjs";import{i as L,c as T,t as J,n as Q}from"./memory-DNRyyp1b.mjs";import{buildModelMessages as R}from"./buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as V}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-BXx-tSCe.mjs";const W=8,E=e=>e===void 0?"null":JSON.stringify(e),X=e=>e===void 0?[]:Array.isArray(e)?e:[e],Y=async(e,t)=>(await Promise.all(e.map(async a=>a({steps:t})))).some(Boolean),I=(e,t)=>e===void 0&&t===void 0?void 0:(e??0)+(t??0),Z=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const a={},o=I(e.inputTokens,t.inputTokens),n=I(e.outputTokens,t.outputTokens),i=I(e.totalTokens,t.totalTokens);return o!==void 0&&(a.inputTokens=o),n!==void 0&&(a.outputTokens=n),i!==void 0&&(a.totalTokens=i),a},z=async(e,t,a)=>{const{needsApproval:o}=e;return o===void 0||o===!1?!1:o===!0?!0:o(t,a)},H=async(e,t)=>{const{instanceId:a,patchThread:o,persist:n,step:i}=e;await n({content:`Awaiting approval to run tool "${t.name}".`,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await o({status:"awaiting_input"});const r=await i.waitForEvent(`approval:${t.id}`,{type:`agent-approval:${t.id}`});return await o({status:"running"}),{decision:r.payload.decision,...r.payload.note===void 0?{}:{note:r.payload.note}}},tt=async(e,t)=>{const{env:a,getState:o,instanceId:n,onTokenDelta:i,persist:r,run:l,setState:c,step:p,threadKey:s,tools:u}=e,d=`tool:${t.name}:${t.id}`,y=u[t.name],h=`${n}:tool:${t.id}`;if(!y){await r({content:`Error: unknown tool "${t.name}"`,messageKey:h,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const w={env:a,getState:o,idempotencyKey:d,reportProgress:f=>{i?.({data:f,kind:"progress",threadKey:s,toolCallId:t.id})},run:l,setState:c,threadKey:s,toolCallId:t.id};let x;if(await z(y,t.input,w)){const{decision:f,note:C}=await H(e,t);if(f==="reject"){const k=C===void 0?"":` Reason: ${C}`;await r({content:`Tool "${t.name}" was rejected by the user and not run.${k}`,messageKey:h,role:"tool",status:"rejected",stepName:d,toolCallId:t.id,toolName:t.name});return}x="approved"}const m=await p.do(d,()=>Promise.resolve(y.execute(t.input,w)));await r({content:typeof m=="string"?m:E(m),messageKey:h,role:"tool",stepName:d,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},et=(e,t,a)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:q(t.model,a),toolChoice:t.toolChoice??e.toolChoice}},at=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const a=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=a)return;let o=e.length-a;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},ot=async(e,t)=>{const{agent:a,compact:o,env:n}=e,i=at(t,a.compaction);if(i===void 0||o===void 0)return{history:t,summary:void 0};try{const r=await o({env:n,messages:R({history:i.older}),model:a.compaction?.model??a.model});return r.length>0?{history:i.recent,summary:r}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},st=async(e,t,a)=>{const{agent:o,env:n,generate:i,instructions:r,listMessages:l,memoryContext:c,onTokenDelta:p,run:s,step:u,streamGenerate:d,threadKey:y}=e;return u.do(`llm:turn:${String(t)}`,async()=>{const h=await s(l,{key:y}),{history:w,summary:x}=await ot(e,h);let m={activeTools:o.activeTools,messages:R({history:w,instructions:r,memoryContext:c,summary:x}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(m=et(m,await o.prepareStep({messages:m.messages,stepNumber:t,steps:a}),n));const f={messages:m.messages,...m.activeTools===void 0?{}:{activeTools:m.activeTools},...m.model===void 0?{}:{model:m.model},...m.toolChoice===void 0?{}:{toolChoice:m.toolChoice}};return d&&p?d(f,C=>{p({text:C,threadKey:y,turn:t})}):i(f)})},A=async(e,t)=>{const{agent:a,step:o}=e;a.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await a.onStepFinish?.(t),!0))},nt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),N=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},it=e=>{const t={};return e?.depth!==void 0&&(t.depth=e.depth),e?.fanOut!==void 0&&(t.fanOut=e.fanOut),e?.maxNodes!==void 0&&(t.maxNodes=e.maxNodes),e?.maxSeeds!==void 0&&(t.maxSeeds=e.maxSeeds),t},rt=async(e,t,a,o)=>{if(e.source===void 0)return;const n=g(e.source),{topK:i}=e,r=T("memory:retrieve",e.key),l=await a.do(r,async()=>o(n,{query:t,...i===void 0?{}:{topK:i}}));return N(l)},dt=async(e,t,a,o,n,i)=>{if(a===void 0)return;const r=T("memory:traverse",e.key),l=await n.do(r,async()=>i(o,{owner:a,query:t,...it(e.graph)}));return N(l)},lt=async(e,t,a,o,n)=>{if(t===void 0)return;const i=T("memory:recall",e.key),r={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},l=await o.do(i,async()=>n(a,r));return N(l)},ct=async(e,t)=>e.kind==="episodic"?lt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?dt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):rt(e,t.input,t.step,t.run),ut=e=>{let t=!1;return e.filter(a=>a.kind!=="episodic"?!0:t?!1:(t=!0,!0))},pt=async(e,t,a,o,n,i)=>{const r=ut(Q(e));if(r.length===0)return;const l=g(o.graphTraverse),c=g(o.episodeRecall),p=[];for(const s of r){const u=await ct(s,{episodeRecall:c,graphTraverse:l,input:t,owner:a,run:i,step:n});u!==void 0&&p.push(u)}return p.length>0?p.join(`
|
|
2
|
+
|
|
3
|
+
`):void 0},mt=async e=>{const{agent:t,env:a,extractGraph:o,finalText:n,input:i,instanceId:r,owner:l,paths:c,run:p,step:s}=e;if(o===void 0||l===void 0||n===void 0||n.length===0)return;const u=L(t);if(u!==void 0)try{const d={assistantText:n,env:a,model:u.graph?.extractionModel??t.model,userInput:i},y=await s.do(T("memory:extract",u.key),async()=>o(d));await p(g(c.graphUpsert),{...y,messageKey:`${r}:${T("extract",u.key)}`,owner:l})}catch{}},yt=async e=>{const{agent:t,env:a,extractEpisode:o,finalText:n,input:i,instanceId:r,owner:l,paths:c,run:p,step:s,threadKey:u}=e;if(o===void 0||l===void 0||n===void 0||n.length===0)return;const d=J(t);if(d!==void 0)try{const y={assistantText:n,env:a,model:d.episodic?.extractionModel??t.model,userInput:i},{summary:h}=await s.do(T("memory:episode",d.key),async()=>o(y));await p(g(c.episodeUpsert),{messageKey:`${r}:${T("episode",d.key)}`,owner:l,summary:h,threadKey:u})}catch{}},vt=async(e,t,a)=>{const o=e[V(t)];if(!(!o||typeof o.get!="function"))try{await(await o.get(a)).terminate()}catch{}},gt=async(e,t,a,o,n)=>{const{instanceId:i,persist:r}=e,l=a.usage===void 0?{}:{usage:a.usage};if(a.toolCalls.length===0){const c=a.output!==void 0&&a.text.length===0?E(a.output):a.text;return await r({content:c,messageKey:`${i}:assistant:${String(t)}`,role:"assistant"}),await A(e,{text:a.text,toolCalls:[],turn:t,...l}),{final:{stopped:"final",text:a.text,turns:t+1,...a.output===void 0?{}:{output:a.output}}}}await r({content:a.text,messageKey:`${i}:assistant:${String(t)}`,role:"assistant",toolCalls:a.toolCalls});for(const c of a.toolCalls)await tt(e,c);if(await A(e,{text:a.text,toolCalls:a.toolCalls,turn:t,...l}),o.push(nt(a)),n.length>0&&await Y(n,o))return"stopCondition"},ht=async(e,t,a,o)=>{const n=[];let i,r=!1,l=0;for(let c=0;c<t;c+=1){const p=await st(e,c,n);o.value=Z(o.value,p.usage),l=c+1;const s=await gt(e,c,p,n,a);if(s==="stopCondition"){r=!0;break}if(s!==void 0){i=s.final;break}}return{final:i,stoppedByCondition:r,turnsRun:l}},Ct=async e=>{const{agent:t,compact:a,env:o,exportName:n,extractEpisode:i,extractGraph:r,generate:l,instanceId:c,onTokenDelta:p,params:s,paths:u,run:d,step:y,streamGenerate:h}=e,w=t.maxTurns??W,x=X(t.stopWhen),m=g(u.appendMessage),f=g(u.ensureThread),C=g(u.listMessages),k=g(u.patchThread),b=g(u.setState),F=g(u.state),M=async v=>{await d(m,{threadKey:s.threadKey,...v})},G=async v=>{await d(k,{key:s.threadKey,...v})},j=async()=>await d(F,{key:s.threadKey}),B=async v=>{await d(b,{key:s.threadKey,state:v})},S=await d(f,{agent:n,instanceId:c,key:s.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...s.owner===void 0?{}:{owner:s.owner},...s.title===void 0?{}:{title:s.title}});S?.replaced&&S.priorInstanceId!==void 0&&await vt(o,n,S.priorInstanceId),await M({content:s.input,messageKey:`${c}:user`,role:"user"});const D=await pt(t,s.input,s.owner,u,y,d),O=typeof t.instructions=="function"?t.instructions({env:o,input:s.input,threadKey:s.threadKey}):t.instructions,P={agent:t,compact:a,env:o,generate:l,getState:j,instanceId:c,instructions:O,listMessages:C,memoryContext:D,onTokenDelta:p,patchThread:G,persist:M,run:d,setState:B,step:y,streamGenerate:h,threadKey:s.threadKey,tools:t.tools??{}},$={value:void 0};try{const{final:v,stoppedByCondition:U,turnsRun:_}=await ht(P,w,x,$),K=$.value===void 0?{}:{usage:$.value};return await mt({agent:t,env:o,extractGraph:r,finalText:v?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:y}),await yt({agent:t,env:o,extractEpisode:i,finalText:v?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:y,threadKey:s.threadKey}),v?(await d(k,{key:s.threadKey,status:"idle",...K}),{...v,...K}):U?(await d(k,{key:s.threadKey,status:"idle",...K}),{stopped:"stopCondition",turns:_,...K}):(await d(k,{error:`agent stopped: maxTurns (${String(w)}) reached`,key:s.threadKey,status:"error",...K}),{stopped:"maxTurns",turns:w,...K})}catch(v){throw await d(k,{error:v instanceof Error?v.message:String(v),key:s.threadKey,status:"error",...$.value===void 0?{}:{usage:$.value}}),v}};export{Ct as runAgentLoop,at as splitForCompaction};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as W}from"./base64-jU-Ci6Tu.mjs";import{buildModelMessages as z}from"./buildModelMessages-Dm2wVNQy.mjs";import{toFunctionReference as x}from"./AGENT_MODULE-BXx-tSCe.mjs";const G=16e3,J=1,q=16,K=/[^.!?]*[.!?]+\s+/u,C=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:s}=await e.read();if(n)break;yield s}}finally{e.releaseLock()}return}yield*t},Y=(t,e=G,n=J,s=q)=>{const u=n*s/8,y=e*u,f=new ArrayBuffer(44+t.byteLength),r=new DataView(f),a=(U,l)=>{for(let g=0;g<l.length;g+=1)r.setUint8(U+g,l.codePointAt(g)??0)};a(0,"RIFF"),r.setUint32(4,36+t.byteLength,!0),a(8,"WAVE"),a(12,"fmt "),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,n,!0),r.setUint32(24,e,!0),r.setUint32(28,y,!0),r.setUint16(32,u,!0),r.setUint16(34,s,!0),a(36,"data"),r.setUint32(40,t.byteLength,!0);const d=new Uint8Array(f);return d.set(t,44),d},H=t=>{const e=[];let n=t,s=K.exec(n);for(;s&&s[0].length>0;){const u=s[0],y=u.trim();y.length>0&&e.push(y),n=n.slice(u.length),s=K.exec(n)}return{rest:n,sentences:e}},Z=async t=>{const{agent:e,connectionId:n,env:s,exportName:u,owner:y,paths:f,pcm:r,run:a,send:d,sendAudio:U,signal:l,streamGenerate:g,synthesize:F,text:I,threadKey:c,transcribe:L,turn:T,waitForDrain:M}=t,p=()=>l.aborted,v=x(f.appendMessage),j=x(f.ensureThread),V=x(f.listMessages),A=x(f.patchThread),w=(I??(r?await L(r):"")).trim();if(w.length===0)return{assistantText:"",interrupted:!1,userText:""};d({text:w,type:"user_transcript"}),await a(j,{agent:u,key:c,...e.initialState===void 0?{}:{initialState:e.initialState},...y===void 0?{}:{owner:y}}),await a(v,{content:w,messageKey:`voice:${n}:${String(T)}:user`,role:"user",threadKey:c}),await a(A,{key:c,status:"running"});const k=typeof e.instructions=="function"?e.instructions({env:s,input:w,threadKey:c}):e.instructions,_=await a(V,{key:c}),B=z({history:_,...k===void 0?{}:{instructions:k}});let h="",b="",S=Promise.resolve();const D=async i=>{if(p()||i.length===0)return;let m=!1;try{for await(const o of C(await F(i,l))){if(p()||(await M?.(),p()))break;U(o),m=!0}}catch(o){d({message:o instanceof Error?o.message:String(o),type:"error"})}m&&(b=b.length>0?`${b} ${i}`:i)},R=i=>{S=S.then(async()=>D(i))};try{const i=await g({messages:B,signal:l},$=>{if(p())return;d({text:$,type:"assistant_delta"}),h+=$;const{rest:E,sentences:N}=H(h);h=E;for(const P of N)R(P)});!p()&&h.trim().length>0&&R(h.trim()),h="",await S;const m=p(),o=m?b:i.text;return await a(v,{content:o,messageKey:`voice:${n}:${String(T)}:assistant`,role:"assistant",threadKey:c}),await a(A,{key:c,status:"idle"}),d(m?{type:"interrupted"}:{text:o,type:"assistant_done"}),{assistantText:o,interrupted:m,userText:w}}catch(i){throw await a(A,{key:c,status:"idle"}),i}},tt=t=>{if(t)try{const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}},et=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},nt=t=>{if(t instanceof Uint8Array||t instanceof ReadableStream)return t;if(t instanceof Response&&t.body)return t.body;if(typeof t=="object"&&t!==null&&"audio"in t){const{audio:e}=t;if(typeof e=="string")return W(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{tt as parseIdentity,Y as pcmToWav,nt as readSynthesisAudio,et as readTranscriptionText,Z as runVoiceTurn,C as toByteIterable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{initLunora as h}from"@lunora/server";import{v as n}from"@lunora/values";import{o as d}from"./base64-jU-Ci6Tu.mjs";const{internalAction:w}=h.dataModel().create(),b=()=>globalThis.document?.documentElement?.outerHTML??"",u=1e6,m=20,y=new TextEncoder,x=async(o,t)=>{const e=t.url??"";switch(t.op){case"content":return o.content(e);case"pdf":return{data:d(await o.pdf(e)),encoding:"base64",mediaType:"application/pdf"};case"scrape":return o.scrape(e,b);case"screenshot":{const r=await o.screenshot(e,{...t.fullPage===void 0?{}:{fullPage:t.fullPage},...t.type===void 0?{}:{type:t.type}});return{data:d(r),encoding:"base64",mediaType:t.type==="jpeg"?"image/jpeg":"image/png"}}default:throw new c("INTERNAL",`@lunora/agent: sandbox browser op "${t.op}" is not supported`)}},T=async(o,t)=>{const e=o.any();if(t.op==="exec")return(await e.fetch("/exec",{body:JSON.stringify({args:t.args??[],command:t.command??""}),headers:{"content-type":"application/json"},method:"POST"})).text();if(t.op==="fetch")return(await e.fetch(t.path??"/",{...t.body===void 0?{}:{body:t.body},method:t.method??"GET"})).text();throw new c("INTERNAL",`@lunora/agent: sandbox container op "${t.op}" is not supported`)},g=o=>{let t=0,e=o.length;for(;t<e&&o[t]==="/";)t+=1;for(;e>t&&o[e-1]==="/";)e-=1;return o.slice(t,e)},E=(o,t)=>{const e=g(o),r=[];for(const a of t.split("/"))if(!(a===""||a===".")){if(a===".."){if(r.length===0)throw new c("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");r.pop();continue}r.push(a)}const i=r.join("/");return e&&i?`${e}/${i}`:e||i},N=async(o,t,e)=>{const r=t.length>0?`${t}/`:"",i=e.length>0?e.length+1:0,a=[];let s;for(let l=0;l<m;l+=1){const p=await o.list({prefix:r,...s===void 0?{}:{cursor:s}});for(const f of p.objects)a.push(f.key.slice(i));if(!p.truncated||p.cursor===void 0)return{entries:a,truncated:!1};s=p.cursor}return{entries:a,truncated:!0}},$=async(o,t,e)=>{const r=g(t),i=E(t,e.path??"");switch(e.op){case"ls":{const{entries:a,truncated:s}=await N(o,i,r);return s?{entries:a,truncated:!0}:{entries:a}}case"read":{const a=await o.head(i);if(a&&a.size>u)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${e.path??""}" is ${String(a.size)} bytes (max ${String(u)})`);const s=await o.get(i);if(!s)throw new c("NOT_FOUND",`@lunora/agent: fs read: no file at "${e.path??""}"`);return s.text()}case"rm":return await o.delete(i),{path:e.path??"",removed:!0};case"stat":{const a=await o.head(i);return a?{exists:!0,size:a.size}:{exists:!1}}case"write":{const a=e.content??"",s=y.encode(a).length;if(s>u)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(s)} bytes exceeds the max (${String(u)})`);return await o.put(i,a),{bytes:s,path:e.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${e.op}" is not supported`)}},S=()=>({invoke:w.input({args:n.optional(n.array(n.string())),body:n.optional(n.string()),bucket:n.optional(n.string()),command:n.optional(n.string()),content:n.optional(n.string()),fullPage:n.optional(n.boolean()),kind:n.union(n.literal("browser"),n.literal("container"),n.literal("fs")),method:n.optional(n.string()),name:n.optional(n.string()),op:n.string(),path:n.optional(n.string()),root:n.optional(n.string()),selector:n.optional(n.string()),type:n.optional(n.string()),url:n.optional(n.string())}).action(async({args:o,ctx:t})=>{const e=t,r=o;if(r.kind==="browser"){if(!e.browser)throw new c("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return x(e.browser,r)}if(r.kind==="fs"){const s=e.env?.[r.bucket??""];if(!s||typeof s.get!="function")throw new c("INTERNAL",`@lunora/agent: sandbox fs op found no R2 bucket "${r.bucket??""}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`);return $(s,r.root??"",r)}const i=r.name??"",a=e.containers?.[i];if(!a)throw new c("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${i}"] — declare the container in lunora/containers.ts and run codegen`);return T(a,r)})});export{E as resolveFsKey,$ as runFsOp,S as sandboxComponent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as u,r as t}from"./common-Dck97z3Y.mjs";const r=(o,n)=>typeof o=="string"&&o.length>0?o:n,c=o=>{const{functionId:n,recordInputs:i=!1,Sentry:l}=o;return{executeLanguageModelCall:e=>{const a={"gen_ai.operation.name":r(n,"language_model_call"),"gen_ai.request.model":t(e,"modelId"),"gen_ai.system":t(e,"provider")};return i&&(a["gen_ai.prompt"]=t(e,"messages")),l.startSpan({attributes:a,name:r(n,"language_model_call"),op:"gen_ai.generate"},()=>e.execute())},executeTool:e=>{const a=t(t(e,"toolCall"),"toolName"),s={"gen_ai.operation.name":"execute_tool","gen_ai.tool.call.id":t(e,"toolCallId"),"gen_ai.tool.name":a};return i&&(s["gen_ai.tool.input"]=u(e)),l.startSpan({attributes:s,name:`execute_tool ${r(a,"tool")}`,op:"gen_ai.execute_tool"},()=>e.execute())},onError:e=>{l.captureException(e)}}};export{c as sentryTelemetry};
|