@lunora/agent 1.0.0-alpha.162 → 1.0.0-alpha.164
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.d.mts +50 -2
- package/dist/index.d.ts +50 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/VoiceSessionDO-c8KpjkPk.mjs +1 -0
- package/dist/packem_shared/agent-ai-CxEYOyOu.mjs +1 -0
- package/dist/packem_shared/{agent-loop-CQUKMFWA.mjs → agent-loop-B8Ra_VJg.mjs} +1 -1
- package/dist/packem_shared/{compileAgentWorkflow-Dijgn4Cz.mjs → compileAgentWorkflow-C1-gaq8q.mjs} +1 -1
- package/dist/packem_shared/createAgentGenerate-EEFNvpS5.mjs +3 -0
- package/dist/packem_shared/{defineAgent-CK3CpiOr.mjs → defineAgent-vb1xAmyx.mjs} +1 -1
- package/dist/packem_shared/{runAgentLoop-DFDJPAyk.mjs → runAgentLoop-B9Wc9zPg.mjs} +1 -1
- package/dist/packem_shared/{runVoiceTurn-xFvfDZ2Q.mjs → runVoiceTurn-TLyTQ_UA.mjs} +1 -1
- package/dist/packem_shared/{voice-turn-BiDZeZwp.mjs → voice-turn-obvJnpv6.mjs} +1 -1
- package/dist/packem_shared/webSearchTool-BptEsfd9.mjs +1 -0
- package/package.json +7 -7
- package/dist/packem_shared/VoiceSessionDO-Dc09ClZz.mjs +0 -1
- package/dist/packem_shared/createAgentGenerate-BOILDUZj.mjs +0 -3
package/dist/index.d.mts
CHANGED
|
@@ -4,7 +4,7 @@ export { type AgentComponent, agentComponent, agentExtension } from "./component
|
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
5
|
export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.mjs";
|
|
6
6
|
export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
|
|
7
|
-
import { createAi } from '@lunora/ai';
|
|
7
|
+
import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai';
|
|
8
8
|
import { WorkflowDefinition } from '@lunora/workflow';
|
|
9
9
|
import '@lunora/mail/inbound';
|
|
10
10
|
import '@lunora/server';
|
|
@@ -853,6 +853,54 @@ declare class VoiceSessionDO {
|
|
|
853
853
|
*/
|
|
854
854
|
private waitForSocketDrain;
|
|
855
855
|
}
|
|
856
|
+
/**
|
|
857
|
+
* Config for {@link webSearchTool}.
|
|
858
|
+
* @experimental
|
|
859
|
+
*/
|
|
860
|
+
interface WebSearchToolOptions {
|
|
861
|
+
/** Alias of a provider key stored on the gateway to bill instead of the `default` alias. */
|
|
862
|
+
byokAlias?: string;
|
|
863
|
+
/** Overrides the description shown to the model. */
|
|
864
|
+
description?: string;
|
|
865
|
+
/**
|
|
866
|
+
* The AI Gateway that brokers and bills the search. Defaults to
|
|
867
|
+
* `LUNORA_AI_GATEWAY_ID`, else the account's `default` gateway.
|
|
868
|
+
*/
|
|
869
|
+
gatewayId?: string;
|
|
870
|
+
/** Maximum results per search, 1–10. Defaults to 5: every result is prompt the next turn pays for. */
|
|
871
|
+
limit?: number;
|
|
872
|
+
/** Defaults to the Web Search API's own default (`"ceramic"`). */
|
|
873
|
+
provider?: AiWebSearchProvider;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* What the model passes.
|
|
877
|
+
* @experimental
|
|
878
|
+
*/
|
|
879
|
+
interface WebSearchToolInput {
|
|
880
|
+
query: string;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* A batteries-included agent tool over the Cloudflare Web Search API (beta,
|
|
884
|
+
* `ctx.ai.websearch`), so an agent can ground an answer in live results.
|
|
885
|
+
* A search bills a provider key stored on the gateway (`byokAlias`, else the
|
|
886
|
+
* `default` alias) when there is one, otherwise AI Gateway credits; every
|
|
887
|
+
* provider runs under Zero Data Retention.
|
|
888
|
+
*
|
|
889
|
+
* It calls the `AI` binding straight from the tool's durable step: a search
|
|
890
|
+
* is a read, so the at-least-once step retry repeats nothing but a query, and
|
|
891
|
+
* there is no dispatcher action to register.
|
|
892
|
+
*
|
|
893
|
+
* ```ts
|
|
894
|
+
* import { defineAgent, webSearchTool } from "@lunora/agent";
|
|
895
|
+
*
|
|
896
|
+
* export const researcher = defineAgent({
|
|
897
|
+
* model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
|
|
898
|
+
* tools: { search: webSearchTool({ provider: "exa" }) },
|
|
899
|
+
* });
|
|
900
|
+
* ```
|
|
901
|
+
* @experimental
|
|
902
|
+
*/
|
|
903
|
+
declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
|
|
856
904
|
/**
|
|
857
905
|
* Compile a `defineAgent` definition into the workflow the generated
|
|
858
906
|
* `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
|
|
@@ -876,4 +924,4 @@ declare class VoiceSessionDO {
|
|
|
876
924
|
declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
|
|
877
925
|
paths?: AgentFunctionPaths;
|
|
878
926
|
}) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
|
|
879
|
-
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults };
|
|
927
|
+
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool };
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export { type AgentComponent, agentComponent, agentExtension } from "./component
|
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
5
|
export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.js";
|
|
6
6
|
export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
|
|
7
|
-
import { createAi } from '@lunora/ai';
|
|
7
|
+
import { createAi, AiWebSearchProvider, AiWebSearchItem } from '@lunora/ai';
|
|
8
8
|
import { WorkflowDefinition } from '@lunora/workflow';
|
|
9
9
|
import '@lunora/mail/inbound';
|
|
10
10
|
import '@lunora/server';
|
|
@@ -853,6 +853,54 @@ declare class VoiceSessionDO {
|
|
|
853
853
|
*/
|
|
854
854
|
private waitForSocketDrain;
|
|
855
855
|
}
|
|
856
|
+
/**
|
|
857
|
+
* Config for {@link webSearchTool}.
|
|
858
|
+
* @experimental
|
|
859
|
+
*/
|
|
860
|
+
interface WebSearchToolOptions {
|
|
861
|
+
/** Alias of a provider key stored on the gateway to bill instead of the `default` alias. */
|
|
862
|
+
byokAlias?: string;
|
|
863
|
+
/** Overrides the description shown to the model. */
|
|
864
|
+
description?: string;
|
|
865
|
+
/**
|
|
866
|
+
* The AI Gateway that brokers and bills the search. Defaults to
|
|
867
|
+
* `LUNORA_AI_GATEWAY_ID`, else the account's `default` gateway.
|
|
868
|
+
*/
|
|
869
|
+
gatewayId?: string;
|
|
870
|
+
/** Maximum results per search, 1–10. Defaults to 5: every result is prompt the next turn pays for. */
|
|
871
|
+
limit?: number;
|
|
872
|
+
/** Defaults to the Web Search API's own default (`"ceramic"`). */
|
|
873
|
+
provider?: AiWebSearchProvider;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* What the model passes.
|
|
877
|
+
* @experimental
|
|
878
|
+
*/
|
|
879
|
+
interface WebSearchToolInput {
|
|
880
|
+
query: string;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* A batteries-included agent tool over the Cloudflare Web Search API (beta,
|
|
884
|
+
* `ctx.ai.websearch`), so an agent can ground an answer in live results.
|
|
885
|
+
* A search bills a provider key stored on the gateway (`byokAlias`, else the
|
|
886
|
+
* `default` alias) when there is one, otherwise AI Gateway credits; every
|
|
887
|
+
* provider runs under Zero Data Retention.
|
|
888
|
+
*
|
|
889
|
+
* It calls the `AI` binding straight from the tool's durable step: a search
|
|
890
|
+
* is a read, so the at-least-once step retry repeats nothing but a query, and
|
|
891
|
+
* there is no dispatcher action to register.
|
|
892
|
+
*
|
|
893
|
+
* ```ts
|
|
894
|
+
* import { defineAgent, webSearchTool } from "@lunora/agent";
|
|
895
|
+
*
|
|
896
|
+
* export const researcher = defineAgent({
|
|
897
|
+
* model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
|
|
898
|
+
* tools: { search: webSearchTool({ provider: "exa" }) },
|
|
899
|
+
* });
|
|
900
|
+
* ```
|
|
901
|
+
* @experimental
|
|
902
|
+
*/
|
|
903
|
+
declare const webSearchTool: (options?: WebSearchToolOptions) => AgentToolDefinition<WebSearchToolInput, AiWebSearchItem[] | string>;
|
|
856
904
|
/**
|
|
857
905
|
* Compile a `defineAgent` definition into the workflow the generated
|
|
858
906
|
* `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
|
|
@@ -876,4 +924,4 @@ declare class VoiceSessionDO {
|
|
|
876
924
|
declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
|
|
877
925
|
paths?: AgentFunctionPaths;
|
|
878
926
|
}) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
|
|
879
|
-
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults };
|
|
927
|
+
export { AGENT_MODULE, type AgentAsToolOptions, type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentGenerate, type AgentHandle, type AgentLoopOptions, type AgentMemoryReadInput, type AgentMemorySearchHit, type AgentMemorySearchInput, type AgentMemorySearchResult, type AgentMessageRow, type AgentModelInput, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentStepLike, type AgentStreamGenerate, type AgentSubToolInput, type AgentTokenSink, type AgentToolConfig, type AgentToolDefinition, type AnyAgentTool, type CodeToolOptions, DEFAULT_AGENT_FUNCTION_PATHS, type FunctionToolOptions, type McpCallResult, type McpClientLike, type McpContentPart, type McpToolInfo, type McpToolsOptions, type RunVoiceTurnOptions, SANDBOX_INVOKE_PATH, SANDBOX_MODULE, type SkillConfig, type SkillDefinition, type ToolScript, type ToolScriptResult, type ToolScriptStep, type VoiceAudioSource, type VoiceClientFrame, type VoiceSend, type VoiceSendAudio, type VoiceServerFrame, VoiceSessionDO, type VoiceSynthesize, type VoiceTranscribe, type VoiceTurnResult, type WebSearchToolInput, type WebSearchToolOptions, adaptMcpResult, agentAsTool, buildModelMessages, codeTool, collectAgenticMemoryTools, compileAgentWorkflow, createAgentContext, createAgentGenerate, createEpisodeExtract, createGraphExtract, createStreamGenerate, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, mcpTools, resolveAgentModel, runAgentLoop, runVoiceTurn, splitForCompaction, toFunctionReference, toSearchResults, webSearchTool };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as t,s as r}from"./packem_shared/agent-loop-
|
|
1
|
+
import{r as t,s as r}from"./packem_shared/agent-loop-B8Ra_VJg.mjs";import{collectAgenticMemoryTools as a,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-1Gwq45M3.mjs";import{codeTool as m}from"./packem_shared/codeTool-BQb-K3my.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-D3mf7LEU.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-vb1xAmyx.mjs";import{functionTool as D}from"./packem_shared/functionTool-D3CP4f8-.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as F}from"./packem_shared/createAgentGenerate-EEFNvpS5.mjs";import{jsCodeTool as L}from"./packem_shared/jsCodeTool-BLOvjXGF.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-CVlq-_TO.mjs";import{buildModelMessages as v}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as B,agentDefaultName as R,voiceBindingName as V,voiceClassName as H}from"./naming.mjs";import{AGENT_MODULE as P,DEFAULT_AGENT_FUNCTION_PATHS as X,SANDBOX_INVOKE_PATH as j,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{browserTool as q,containerFsTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{defineSkill as Z,isSkillDefinition as $}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as oe}from"./packem_shared/VoiceSessionDO-c8KpjkPk.mjs";import{r as re}from"./packem_shared/voice-turn-obvJnpv6.mjs";import{webSearchTool as ae}from"./packem_shared/webSearchTool-BptEsfd9.mjs";import{default as le}from"./packem_shared/compileAgentWorkflow-C1-gaq8q.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,oe as VoiceSessionDO,b as adaptMcpResult,s as agentAsTool,B as agentClassName,c as agentComponent,R as agentDefaultName,x as agentExtension,q as browserTool,v as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,le as compileAgentWorkflow,z as containerFsTool,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,d as defineAgent,u as defineAgentTool,Z as defineSkill,Q as fsTool,D as functionTool,N as isAgentDefinition,$ as isSkillDefinition,L as jsCodeTool,h as mcpTools,F as resolveAgentModel,t as runAgentLoop,re as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,f as toSearchResults,V as voiceBindingName,H as voiceClassName,ae as webSearchTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as A}from"@lunora/ai";import{l as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as C}from"./voice-turn-obvJnpv6.mjs";import{r as I}from"./agent-ai-CxEYOyOu.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-EEFNvpS5.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-M4D1EejI.mjs";const O="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",B=8*1024*1024,F=100,f=4e3,g=f*4+1024,D=4002,z=4003,W=4004,G=256*1024,S=15,X=5e3,K=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class j{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,r,s){this.state=t,this.env=e,this.agent=r,this.exportName=s,this.paths=N,this.ai=I(e)??A({env:e}),this.streamGenerate=R(r,e),this.sttModel=r.voice?.stt??O,this.ttsModel=r.voice?.tts??U,this.maxSessionTurns=r.voice?.maxTurns??F}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(t.url).searchParams.get("threadKey");if(!r)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,i=new s,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:r,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,r,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const r=t.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,r,e);return}this.bufferAudio(r.connectionId,new Uint8Array(e),t)}catch(s){this.send(t,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const r=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...r===void 0?{}:{speaker:r}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,r){if(r.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,W,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!K(s)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=s;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,D,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,r){const s=(this.bufferedBytes.get(t)??0)+e.byteLength;if(s>B){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,z,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,s)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const r=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of e)s.set(n,i),i+=n.byteLength;return s}async runTurn(t,e,r){const s=new AbortController;this.controllers.set(e.connectionId,s);try{await w({agent:this.agent,compact:L(),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:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(e.connectionId)===s&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:r,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...s===void 0?{}:{owner:s}}))?.outcome!=="created")return;for await(const u of C(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&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))}closeSocket(t,e,r){try{t.close?.(e,r)}catch{}}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 r=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>G&&r<X;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{j as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as t}from"@lunora/ai";const i=r=>{const o=r.AI;return o?t({binding:o,env:r}):void 0};export{i as r};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{f as ot}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{r as W}from"./workflow-binding-Dm9hBzx_.mjs";import{c as b,d as nt}from"./component-shared-G8ngerkU.mjs";import{resolveAgentModel as at}from"./createAgentGenerate-
|
|
1
|
+
import{f as ot}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{r as W}from"./workflow-binding-Dm9hBzx_.mjs";import{c as b,d as nt}from"./component-shared-G8ngerkU.mjs";import{resolveAgentModel as at}from"./createAgentGenerate-EEFNvpS5.mjs";import{buildModelMessages as H}from"./buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as z}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as st}from"./positive-integer-ztHqqpBk.mjs";import{combineTelemetry as rt}from"./combineTelemetry-DgE9W9G8.mjs";import{c as G}from"./tool-output-Cmk3JWMG.mjs";const it=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",F=e=>e.memorySources?e.memorySources:e.memory&&it(e.memory)?[{key:"default",...e.memory}]:[],ct=e=>F(e).find(t=>t.kind==="graph"),dt=e=>F(e).find(t=>t.kind==="episodic"),S=(e,t)=>t==="default"?e:`${e}:${t}`,ut=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const n=Array.isArray(t)?t:[t];return n.length===0?void 0:rt(...n)},lt=async(e,t,n)=>{const o=ut(e);if(o===void 0)return n();const a={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:a,toolContext:void 0},c=Date.now();await o.onToolExecutionStart?.(s);let d;const u=()=>(d??=n(),d);try{if(o.executeTool===void 0)await u();else try{await o.executeTool({...s,execute:u,toolCallId:t.id})}catch{}const i=await u();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,input:t.input,output:i,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),i}catch(i){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,error:i,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),i}},pt=8,mt=e=>st(e)?e:0,V=e=>e===void 0?"null":JSON.stringify(e),yt=async(e,t,n)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...n===void 0?{}:{usage:n}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},vt=e=>e===void 0?[]:[e].flat(),ft=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),ht=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const n={};for(const o of["inputTokens","outputTokens","totalTokens"])(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},gt=async(e,t,n,o,a)=>{const{needsApproval:s}=e;return s===void 0||s===!1?!1:s===!0?!0:n.do(o,async()=>s(t,a))},wt="WorkflowTimeoutError",Tt=e=>e instanceof Error&&e.name===wt,L=4320*60*1e3,xt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Ct=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,St=e=>{if(e===void 0)return L;if(typeof e=="number")return Math.min(e,b);const t=Ct.exec(e);return t===null?L:Math.min(Number(t[1])*xt[t[2]],b)},kt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:c,step:d}=e;await c({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 s({status:"awaiting_input"});const u=await d.waitForEvent(`approval:${t.id}`,{timeout:St(n.approvalTimeout),type:`agent-approval:${t.id}`}).then(i=>({decision:i.payload.decision,...i.payload.note===void 0?{}:{note:i.payload.note}})).catch(i=>{if(!Tt(i))throw i;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),u},A="lunoraToolOutcome",Et=e=>typeof e=="object"&&e!==null&&A in e?e[A]:{ok:e},Mt=async(e,t)=>{const{agent:n,depth:o,env:a,exports:s,getState:c,instanceId:d,onTokenDelta:u,owner:i,persist:m,run:r,setState:l,step:p,threadKey:f,tools:E}=e,h=`tool:${t.name}:${t.id}`,v=E[t.name],T=`${d}:tool:${t.id}`;if(!v){await m({content:`Error: unknown tool "${t.name}"`,messageKey:T,role:"tool",stepName:h,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await m({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:T,role:"tool",stepName:h,toolCallId:t.id,toolName:t.name});return}const O={depth:o,env:a,exports:s,getState:c,idempotencyKey:h,owner:i,reportProgress:w=>{u?.({data:w,kind:"progress",threadKey:f,toolCallId:t.id})},run:r,setState:l,step:p,threadKey:f,toolCallId:t.id},_={depth:o,env:a,getState:c,idempotencyKey:h,run:r,threadKey:f,toolCallId:t.id},U=`tool:approval-gate:${t.id}`;let x;if(await gt(v,t.input,p,U,_)){const{decision:w,note:k}=await kt(e,t);if(w==="reject"){const D=k===void 0?"":` Reason: ${k}`;await m({content:`Tool "${t.name}" was rejected by the user and not run.${D}`,messageKey:T,role:"tool",status:"rejected",stepName:h,toolCallId:t.id,toolName:t.name});return}x="approved"}const M=Et(await p.do(h,async()=>{try{const w=()=>Promise.resolve(v.execute(t.input,O)),k=await lt(n.telemetry,{id:t.id,input:t.input,name:t.name},w);return{[A]:{ok:k}}}catch(w){if(ot(w))return{[A]:{failed:w.message}};throw w}}));if("failed"in M){await m({content:G(`Error: tool "${t.name}" failed and will not be retried. ${M.failed}`),messageKey:T,role:"tool",stepName:h,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name});return}const $=M.ok;await m({content:G(typeof $=="string"?$:V($)),messageKey:T,role:"tool",stepName:h,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},$t=(e,t,n)=>{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:at(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},Rt=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const n=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=n)return;let o=e.length-n;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},It=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=Rt(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const c=await o({env:a,messages:H({history:s.older}),model:n.compaction?.model??n.model});return c.length>0?{history:s.recent,summary:c}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Kt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:c,listMessages:d,memoryContext:u,onTokenDelta:i,run:m,step:r,streamGenerate:l,threadKey:p}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const f=await m(d,{key:p}),{history:E,summary:h}=await It(e,f);let v={activeTools:o.activeTools,messages:H({history:E,instructions:c,memoryContext:u,summary:h}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(v=$t(v,await o.prepareStep({messages:v.messages,stepNumber:t,steps:n}),a));const T={messages:v.messages,...v.activeTools===void 0?{}:{activeTools:v.activeTools},...v.model===void 0?{}:{model:v.model},...v.toolChoice===void 0?{}:{toolChoice:v.toolChoice}};return l&&i?l(T,R=>{i({text:R,threadKey:p,turn:t})}):s(T)})},B=async(e,t)=>{const{agent:n,step:o}=e;n.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await n.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}}),j=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},At=e=>nt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Ot=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:s}=e,c=S("memory:retrieve",e.key),d=await n.do(c,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return j(d)},_t=async(e,t,n,o,a,s)=>{if(n===void 0)return;const c=S("memory:traverse",e.key),d=await a.do(c,async()=>s(o,{owner:n,query:t,...At(e.graph)}));return j(d)},Ut=async(e,t,n,o,a)=>{if(t===void 0)return;const s=S("memory:recall",e.key),c={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},d=await o.do(s,async()=>a(n,c));return j(d)},Dt=async(e,t)=>e.kind==="episodic"?Ut(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?_t(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Ot(e,t.input,t.step,t.run),Pt=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},Ft=async(e,t,n,o,a,s)=>{const c=Pt(F(e));if(c.length===0)return;const d=g(o.graphTraverse),u=g(o.episodeRecall),i=[];for(const m of c){const r=await Dt(m,{episodeRecall:u,graphTraverse:d,input:t,owner:n,run:s,step:a});r!==void 0&&i.push(r)}return i.length>0?i.join(`
|
|
2
2
|
|
|
3
3
|
`):void 0},jt=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:c,owner:d,paths:u,run:i,step:m}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const r=ct(t);if(r!==void 0)try{const l={assistantText:a,env:n,model:r.graph?.extractionModel??t.model,userInput:s},p=await m.do(S("memory:extract",r.key),async()=>o(l));await i(g(u.graphUpsert),{...p,messageKey:`${c}:${S("extract",r.key)}`,owner:d})}catch{}},qt=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:c,owner:d,paths:u,run:i,step:m,threadKey:r}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const l=dt(t);if(l!==void 0)try{const p={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:f}=await m.do(S("memory:episode",l.key),async()=>o(p));await i(g(u.episodeUpsert),{messageKey:`${c}:${S("episode",l.key)}`,owner:d,summary:f,threadKey:r})}catch{}},bt=async(e,t,n)=>{const o=W(e.env,e.exports,z(t),["get"]);if(o!==void 0)try{await(await o.get(n)).terminate()}catch{}},Gt="12 hours",Lt=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:Gt,type:`agent-dequeue:${t}:${n}`})},Bt=async(e,t,n)=>{const o=W(e.env,e.exports,z(e.exportName),["get"]);if(o===void 0)return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},Wt=async(e,t,n)=>{const{onReply:o}=e,{replyRef:a}=t.params;if(!(o===void 0||a===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:a,result:n,threadKey:t.params.threadKey}),a.channel))}catch{}},Ht=async(e,t,n,o,a)=>{const{instanceId:s,persist:c}=e,d=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const u=n.output!==void 0&&n.text.length===0?V(n.output):n.text;return await c({content:u,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await B(e,{text:n.text,toolCalls:[],turn:t,...d}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await c({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const u of n.toolCalls)await Mt(e,u);if(await B(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...d}),o.push(Nt(n)),a.length>0&&await ft(a,o))return"stopCondition"},zt=async(e,t,n,o)=>{const a=[];let s,c=!1,d=0;for(let u=0;u<t;u+=1){const i=await Kt(e,u,a);o.value=ht(o.value,i.usage),d=u+1;const m=await Ht(e,u,i,a,n);if(m==="stopCondition"){c=!0;break}if(m!==void 0){s=m.final;break}}return{final:s,stoppedByCondition:c,turnsRun:d}},ae=async e=>{const{agent:t,compact:n,env:o,exportName:a,exports:s,extractEpisode:c,extractGraph:d,generate:u,instanceId:i,onTokenDelta:m,params:r,paths:l,run:p,step:f,streamGenerate:E}=e,h=t.maxTurns??pt,v=vt(t.stopWhen),T=g(l.appendMessage),R=g(l.completeRun),O=g(l.ensureThread),_=g(l.listMessages),U=g(l.deleteMessage),x=g(l.patchThread),M=g(l.setState),$=g(l.state),w=async y=>{await p(T,{threadKey:r.threadKey,...y})},k=async y=>{await p(x,{key:r.threadKey,...y})},D=async y=>{await p(U,{messageKey:y,threadKey:r.threadKey})},X=async()=>{await w({content:r.input,messageKey:`${i}:user`,role:"user"})},q={dispatched:!1},I=async y=>{q.dispatched=!0;const N=await p(R,{instanceId:i,key:r.threadKey,...y});N?.dequeued!==void 0&&await Bt({env:o,exportName:a,exports:s,step:f},r.threadKey,N.dequeued)},J=async()=>await p($,{key:r.threadKey}),Q=async y=>{await p(M,{key:r.threadKey,state:y})},P=await p(O,{agent:a,instanceId:i,key:r.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...r.owner===void 0?{}:{owner:r.owner},...r.title===void 0?{}:{title:r.title}});P?.outcome==="replaced"&&await bt({env:o,exports:s},a,P.priorInstanceId);const Y=await Ft(t,r.input,r.owner,l,f,p),Z=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,tt={agent:t,compact:n,depth:mt(r.depth),env:o,exports:s,generate:u,getState:J,instanceId:i,instructions:Z,listMessages:_,memoryContext:Y,onTokenDelta:m,owner:r.owner,deleteMessage:D,patchThread:k,persist:w,run:p,setState:Q,step:f,streamGenerate:E,threadKey:r.threadKey,tools:t.tools??{}},K={value:void 0};try{P?.outcome==="queued"&&await Lt(f,r.threadKey,i),await X();const{final:y,stoppedByCondition:N,turnsRun:et}=await zt(tt,h,v,K),C=K.value===void 0?{}:{usage:K.value};return await jt({agent:t,env:o,extractGraph:d,finalText:y?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:p,step:f}),await qt({agent:t,env:o,extractEpisode:c,finalText:y?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:p,step:f,threadKey:r.threadKey}),y?(await Wt(t,{env:o,params:r,step:f},{...y,...C}),await I({status:"idle",...C}),{...y,...C}):N?(await I({status:"idle",...C}),{stopped:"stopCondition",turns:et,...C}):(await I({error:`agent stopped: maxTurns (${String(h)}) reached`,status:"error",...C}),{stopped:"maxTurns",turns:h,...C})}catch(y){throw q.dispatched||await yt(I,y,K.value),y}};export{St as a,It as c,it as i,ae as r,Rt as s};
|
package/dist/packem_shared/{compileAgentWorkflow-Dijgn4Cz.mjs → compileAgentWorkflow-C1-gaq8q.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineWorkflow as i}from"@lunora/workflow";import{r as m}from"./agent-loop-
|
|
1
|
+
import{defineWorkflow as i}from"@lunora/workflow";import{r as m}from"./agent-loop-B8Ra_VJg.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-EEFNvpS5.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-M4D1EejI.mjs";import{l as T}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-ByqrB-72.mjs";const E=(r,t,a)=>T({env:t,label:"@lunora/agent",...a===void 0?{}:{fetchImpl:a},...r===void 0?{}:{identity:{userId:r}}}),O=(r,t,a)=>{const e=t.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||r.telemetry?.isEnabled===!1)return r;const n=typeof t.LUNORA_OTLP_TOKEN=="string"?t.LUNORA_OTLP_TOKEN:void 0,o=[r.telemetry?.integrations].flat().filter(s=>s!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...o,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>i({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:u(),env:e.env,exports:e.exports,exportName:t,extractGraph:d(),extractEpisode:f(),generate:l(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??A,run:E(e.params.owner,e.env,e.fetchImpl),step:e.step,streamGenerate:p(n,e.env)})},name:r.name??c(t)});export{I as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{jsonSchema as T,generateText as d,Output as f,streamText as x,tool as C}from"ai";import{r as A}from"./agent-ai-CxEYOyOu.mjs";const g=t=>{if(!t)return;const e={};for(const o of["inputTokens","outputTokens","totalTokens"]){const r=t[o];r!==void 0&&(e[o]=r)}return Object.keys(e).length>0?e:void 0},y=t=>t.map(e=>{const o={id:e.toolCallId,input:e.input,name:e.toolName};return e.invalid!==!0?o:{...o,invalid:e.error instanceof Error?e.error.message:String(e.error)}}),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=A(e);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 o.model(t)}return t},b=(t,e)=>{const o=m(t.model,e),r={};for(const[a,i]of Object.entries(t.tools??{}))r[a]=C({description:i.description,inputSchema:i.inputSchema});const n=t.output===void 0?void 0:f.object({schema:t.output}),s={...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:n,staticSettings:s,tools:r}},v=(t,{activeTools:e,messages:o,model:r,signal:n,toolChoice:s})=>{const{defaultModel:a,output:i,staticSettings:h,tools:c}=t,l=e===void 0?c:Object.fromEntries(Object.entries(c).filter(([p])=>e.includes(p)));return{messages:o,model:r??a,...h,...Object.keys(l).length>0?{tools:l}:{},...s===void 0?{}:{toolChoice:s},...i===void 0?{}:{output:i},...n===void 0?{}:{abortSignal:n}}},q=(t,e)=>{const o=b(t,e);return async r=>{const n=await d(v(o,r)),s=g(n.usage);return{text:n.text,toolCalls:y(n.toolCalls),...s===void 0?{}:{usage:s},...o.output===void 0?{}:{output:n.output}}}},I=(t,e)=>{const o=b(t,e);return async(r,n)=>{const s=x(v(o,r));let a="";try{for await(const u of s.textStream)a+=u,n(u)}catch(u){if(r.signal?.aborted)return{text:a,toolCalls:[]};throw u}const[i,h,c,l]=await Promise.all([s.text,s.toolCalls,s.usage,o.output===void 0?Promise.resolve(void 0):s.output]),p=g(c);return{text:i,toolCalls:y(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:l}}}},k=T({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"}),j=(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
|
+
`),M=()=>async({assistantText:t,env:e,model:o,userInput:r})=>{const{output:n}=await d({model:m(o,e),output:f.object({schema:k}),prompt:j(r,t)});return n},E=(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
|
+
`),_=()=>async({assistantText:t,env:e,model:o,userInput:r})=>{const{text:n}=await d({model:m(o,e),prompt:E(r,t)});return{summary:n.trim()}},O="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.",R=()=>async({env:t,messages:e,model:o})=>{const{text:r}=await d({messages:e,model:m(o,t),system:O});return r.trim()};export{q as createAgentGenerate,R as createCompact,_ as createEpisodeExtract,M as createGraphExtract,I as createStreamGenerate,m as resolveAgentModel};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-B8Ra_VJg.mjs";import{collectAgenticMemoryTools as g}from"./collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as p}from"./agentAsTool-1Gwq45M3.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=/^[a-zA-Z][\w-]*$/u,N=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=a}return o},A=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
|
|
2
2
|
|
|
3
3
|
`)},k=(e,n)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const t of n)t.knowledge&&m(t.knowledge)&&o.push({key:t.name,...t.knowledge});return o},y=e=>{const n=new Set;for(const o of e){if(typeof o.name!="string"||!w.test(o.name))throw new r("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 r("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(n.has(o.name))throw new r("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)`);n.add(o.name)}},v=(e,n)=>{if(e===void 0)return;const o=Object.keys(n).filter(t=>!e.includes(t));if(o.length>0)throw new r("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(t=>`"${t}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},E=(e,n)=>{const o=(t,s)=>{if(t&&t.kind!=="graph"&&t.kind!=="episodic"&&t.source===void 0)throw new r("INTERNAL",`@lunora/agent: ${s} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const t of n)o(t.knowledge,`skill "${t.name}" \`knowledge\``)},L=e=>{if(e===void 0)return;const n=f(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},$=e=>{const n=e.model;if(n==null||typeof n=="string"&&n.length===0)throw new r("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&&!u(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!u(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");L(e.approvalTimeout);const o=e.skills??[];y(o),E(e,o);const t=N(e,o),s=g(e,o);for(const[i,h]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=h}const a=Object.keys(s).length>0;v(e.activeTools,s);for(const i of Object.keys(t))if(!T.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=k(e,o),d=A(e,o);return{...e,asTool:p,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:t}:{}}},j=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,M=e=>{if(typeof e.execute!="function")throw new r("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{$ as defineAgent,M as defineAgentTool,j as isAgentDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import"./workflow-binding-Dm9hBzx_.mjs";import"./component-shared-G8ngerkU.mjs";import"./createAgentGenerate-
|
|
1
|
+
import"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import"./workflow-binding-Dm9hBzx_.mjs";import"./component-shared-G8ngerkU.mjs";import"./createAgentGenerate-EEFNvpS5.mjs";import{a as l,c as u,r as f,s as g}from"./agent-loop-B8Ra_VJg.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"../naming.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./tool-output-Cmk3JWMG.mjs";export{l as approvalTimeoutMs,u as compactHistory,f as runAgentLoop,g as splitForCompaction};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-
|
|
1
|
+
import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-obvJnpv6.mjs";import"./agent-loop-B8Ra_VJg.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,c as toByteIterable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as z}from"./agent-loop-
|
|
1
|
+
import{c as z}from"./agent-loop-B8Ra_VJg.mjs";import{buildModelMessages as G}from"./buildModelMessages-Y4tGo1T9.mjs";import{toFunctionReference as A}from"./AGENT_MODULE-M4D1EejI.mjs";const ot=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},P=t=>{const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.codePointAt(r)??0;return n},C=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),n=e+"=".repeat((4-e.length%4)%4);return P(n)},D=new TextDecoder;new TextEncoder;const N="=",Q=t=>{if(t)try{const e=t[0]==="{"?t:D.decode(C(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},ct=t=>{if(t){if(!t.startsWith(N))return t;try{return D.decode(C(t.slice(N.length)))}catch{return}}},dt=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},ut=t=>typeof t=="number"&&Date.now()>=t,yt=t=>{try{t.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},message:"authentication token expired",type:"error"})),t.close?.(4001,"token_expired")}catch{}},Y=16e3,Z=1,tt=16,M=/[.!?]\s/u,et=/\s/u,nt=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{e.releaseLock()}return}yield*t},ft=(t,e=Y,n=Z,r=tt)=>{const i=n*r/8,l=e*i,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(p,b)=>{for(let d=0;d<b.length;d+=1)s.setUint8(p+d,b.codePointAt(d)??0)};u(0,"RIFF"),s.setUint32(4,36+t.byteLength,!0),u(8,"WAVE"),u(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,e,!0),s.setUint32(28,l,!0),s.setUint16(32,i,!0),s.setUint16(34,r,!0),u(36,"data"),s.setUint32(40,t.byteLength,!0);const a=new Uint8Array(m);return a.set(t,44),a},rt=t=>{const e=[];let n=t,r=M.exec(n);for(;r;){let i=r.index+1;for(;i<n.length&&et.test(n[i]??"");)i+=1;const l=n.slice(0,i).trim();l.length>0&&e.push(l),n=n.slice(i),r=M.exec(n)}return{rest:n,sentences:e}},lt=async t=>{const{agent:e,compact:n,connectionId:r,env:i,exportName:l,owner:m,paths:s,pcm:u,run:a,send:p,sendAudio:b,signal:d,streamGenerate:H,synthesize:L,text:B,threadKey:o,transcribe:F,turn:U,waitForDrain:O}=t,h=()=>d.aborted,v=A(s.appendMessage),$=A(s.ensureThread),K=A(s.listMessages),x=A(s.patchThread);await a($,{agent:l,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const y=(B??(u?await F(u):"")).trim();if(y.length===0)return await a(x,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};p({text:y,type:"user_transcript"}),await a(v,{content:y,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await a(x,{key:o,status:"running"});const _=typeof e.instructions=="function"?e.instructions({env:i,input:y,threadKey:o}):e.instructions,j=await a(K,{key:o}),{history:W,summary:I}=await z({agent:e,compact:n,env:i},j),V=G({history:W,..._===void 0?{}:{instructions:_},...I===void 0?{}:{summary:I}});let g="",E="",k=Promise.resolve();const X=async c=>{if(h()||c.length===0)return;let w=!1;try{for await(const f of nt(await L(c,d))){if(h()||(await O?.(),h()))break;b(f),w=!0}}catch(f){p({message:f instanceof Error?f.message:String(f),type:"error"})}w&&(E=E.length>0?`${E} ${c}`:c)},R=c=>{k=k.then(async()=>X(c))},J=await H({messages:V,signal:d},c=>{if(h())return;p({text:c,type:"assistant_delta"}),g+=c;const{rest:w,sentences:f}=rt(g);g=w;for(const q of f)R(q)});!h()&&g.trim().length>0&&R(g.trim()),g="",await k;const S=h(),T=S?E:J.text;return await a(v,{content:T,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await a(x,{key:o,status:"idle"}),p(S?{type:"interrupted"}:{text:T,type:"assistant_done"}),{assistantText:T,interrupted:S,userText:y}}catch(y){throw await a(x,{key:o,status:"idle"}),y}},pt=t=>Q(t),ht=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},gt=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 P(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{dt as a,yt as b,ft as c,ct as d,ht as e,gt as f,nt as g,ut as i,pt as p,lt as r,ot as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{jsonSchema as h}from"ai";import{r as u}from"./agent-ai-CxEYOyOu.mjs";const l=5,d="Search the web for current information. Returns up to a handful of results, each with a url, a title and (when the provider has one) a description. Use it for facts that may have changed after your training data, then cite the urls you relied on.",m=h({properties:{query:{description:"The search query, 1–1024 characters.",maxLength:1024,minLength:1,type:"string"}},required:["query"],type:"object"}),E=new Set(["BAD_REQUEST","INTERNAL","NOT_IMPLEMENTED"]),T=(t={})=>{const{description:a=d,limit:o=l,...n}=t;return{description:a,execute:async(s,i)=>{const r=u(i.env);if(!r)return"Web search is unavailable: this Worker has no `AI` binding. Answer from what you already know, and say that you could not search.";try{return(await r.websearch(s.query,{...n,limit:o})).items}catch(e){if(e instanceof c&&E.has(e.code))return`Web search failed: ${e.message}`;throw e}},inputSchema:m,isLunoraAgentTool:!0}};export{T as webSearchTool};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/agent",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.164",
|
|
4
4
|
"description": "Durable AI agents for Lunora: defineAgent compiles a replay-safe tool-loop onto Cloudflare Workflows, with DO SQLite threads and live message subscriptions",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|
|
@@ -84,12 +84,12 @@
|
|
|
84
84
|
"access": "public"
|
|
85
85
|
},
|
|
86
86
|
"dependencies": {
|
|
87
|
-
"@lunora/ai": "1.0.0-alpha.
|
|
88
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
89
|
-
"@lunora/mail": "1.0.0-alpha.
|
|
90
|
-
"@lunora/server": "1.0.0-alpha.
|
|
91
|
-
"@lunora/values": "1.0.0-alpha.
|
|
92
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
87
|
+
"@lunora/ai": "1.0.0-alpha.106",
|
|
88
|
+
"@lunora/errors": "1.0.0-alpha.49",
|
|
89
|
+
"@lunora/mail": "1.0.0-alpha.95",
|
|
90
|
+
"@lunora/server": "1.0.0-alpha.171",
|
|
91
|
+
"@lunora/values": "1.0.0-alpha.59",
|
|
92
|
+
"@lunora/workflow": "1.0.0-alpha.70",
|
|
93
93
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
94
94
|
"ai": "7.0.93",
|
|
95
95
|
"yaml": "^2.9.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createAi as A}from"@lunora/ai";import{l as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as I}from"./voice-turn-BiDZeZwp.mjs";import{createStreamGenerate as C,createCompact as R}from"./createAgentGenerate-BOILDUZj.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as L,toFunctionReference as m}from"./AGENT_MODULE-M4D1EejI.mjs";const N="@cf/openai/whisper-large-v3-turbo",O="@cf/deepgram/aura-1",U=8*1024*1024,B=100,f=4e3,g=f*4+1024,F=4002,D=4003,z=4004,W=256*1024,S=15,G=5e3,X=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class J{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,r){this.state=t,this.env=e,this.agent=s,this.exportName=r,this.paths=L,this.ai=A({binding:e.AI,env:e}),this.streamGenerate=C(s,e),this.sttModel=s.voice?.stt??N,this.ttsModel=s.voice?.tts??O,this.maxSessionTurns=s.voice?.maxTurns??B}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const s=new URL(t.url).searchParams.get("threadKey");if(!s)return new Response("Missing threadKey",{status:400});const r=globalThis.WebSocketPair,i=new r,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:s,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,s,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s){if(p(s.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(r){this.send(t,{message:r instanceof Error?r.message:String(r),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 b({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return M(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){if(s.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,z,"control_frame_limit");return}let r;try{r=JSON.parse(s)}catch{return}if(!X(r)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=r;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,F,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,s){const r=(this.bufferedBytes.get(t)??0)+e.byteLength;if(r>U){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(s,D,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,r)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((n,o)=>n+o.byteLength,0),r=new Uint8Array(s);let i=0;for(const n of e)r.set(n,i),i+=n.byteLength;return r}async runTurn(t,e,s){const r=new AbortController;this.controllers.set(e.connectionId,r);try{await w({agent:this.agent,compact:R(),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:r.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),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)===r&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,r,i,n){const o=this.resolveRun(r,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...r===void 0?{}:{owner:r}}))?.outcome!=="created")return;for await(const u of I(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&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))}closeSocket(t,e,s){try{t.close?.(e,s)}catch{}}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>W&&s<G;)await new Promise(r=>{setTimeout(r,S)}),s+=S}}export{J as default};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{createAi as w}from"@lunora/ai";import{LunoraError as T}from"@lunora/errors";import{jsonSchema as x,generateText as d,Output as f,streamText as C,tool as A}from"ai";const g=t=>{if(!t)return;const e={};for(const o of["inputTokens","outputTokens","totalTokens"]){const r=t[o];r!==void 0&&(e[o]=r)}return Object.keys(e).length>0?e:void 0},y=t=>t.map(e=>{const o={id:e.toolCallId,input:e.input,name:e.toolName};return e.invalid!==!0?o:{...o,invalid:e.error instanceof Error?e.error.message:String(e.error)}}),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=e.AI;if(!o)throw new T("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 w({binding:o,env:e}).model(t)}return t},b=(t,e)=>{const o=m(t.model,e),r={};for(const[a,i]of Object.entries(t.tools??{}))r[a]=A({description:i.description,inputSchema:i.inputSchema});const n=t.output===void 0?void 0:f.object({schema:t.output}),s={...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:n,staticSettings:s,tools:r}},v=(t,{activeTools:e,messages:o,model:r,signal:n,toolChoice:s})=>{const{defaultModel:a,output:i,staticSettings:h,tools:c}=t,l=e===void 0?c:Object.fromEntries(Object.entries(c).filter(([p])=>e.includes(p)));return{messages:o,model:r??a,...h,...Object.keys(l).length>0?{tools:l}:{},...s===void 0?{}:{toolChoice:s},...i===void 0?{}:{output:i},...n===void 0?{}:{abortSignal:n}}},I=(t,e)=>{const o=b(t,e);return async r=>{const n=await d(v(o,r)),s=g(n.usage);return{text:n.text,toolCalls:y(n.toolCalls),...s===void 0?{}:{usage:s},...o.output===void 0?{}:{output:n.output}}}},q=(t,e)=>{const o=b(t,e);return async(r,n)=>{const s=C(v(o,r));let a="";try{for await(const u of s.textStream)a+=u,n(u)}catch(u){if(r.signal?.aborted)return{text:a,toolCalls:[]};throw u}const[i,h,c,l]=await Promise.all([s.text,s.toolCalls,s.usage,o.output===void 0?Promise.resolve(void 0):s.output]),p=g(c);return{text:i,toolCalls:y(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:l}}}},k=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"}),j=(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
|
-
`),M=()=>async({assistantText:t,env:e,model:o,userInput:r})=>{const{output:n}=await d({model:m(o,e),output:f.object({schema:k}),prompt:j(r,t)});return n},E=(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
|
-
`),_=()=>async({assistantText:t,env:e,model:o,userInput:r})=>{const{text:n}=await d({model:m(o,e),prompt:E(r,t)});return{summary:n.trim()}},O="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.",R=()=>async({env:t,messages:e,model:o})=>{const{text:r}=await d({messages:e,model:m(o,t),system:O});return r.trim()};export{I as createAgentGenerate,R as createCompact,_ as createEpisodeExtract,M as createGraphExtract,q as createStreamGenerate,m as resolveAgentModel};
|