@lunora/agent 1.0.0-alpha.275 → 1.0.0-alpha.276

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.
Files changed (25) hide show
  1. package/dist/index.mjs +1 -1
  2. package/dist/packem_shared/SecretUnavailableError-D8u6pPM6.mjs +1 -0
  3. package/dist/packem_shared/{VoiceSessionDO-BIfcyunp.mjs → VoiceSessionDO-D4dEV12P.mjs} +1 -1
  4. package/dist/packem_shared/{adaptMcpResult-DFF_g58r.mjs → adaptMcpResult-DOud9k_Q.mjs} +1 -1
  5. package/dist/packem_shared/{agent-loop-ByDqRJo7.mjs → agent-loop-C11GY0Yw.mjs} +1 -1
  6. package/dist/packem_shared/agentAsTool-ifwGRMR6.mjs +1 -0
  7. package/dist/packem_shared/codeTool-BZkKDqsZ.mjs +1 -0
  8. package/dist/packem_shared/collectAgenticMemoryTools-Dxs7mpo6.mjs +1 -0
  9. package/dist/packem_shared/{compileAgentWorkflow-BkVDrDvM.mjs → compileAgentWorkflow-DDQ-_8S0.mjs} +1 -1
  10. package/dist/packem_shared/createAgentGenerate-CTkL_e0Z.mjs +3 -0
  11. package/dist/packem_shared/{defineAgent-D4eUl6YE.mjs → defineAgent-BsDM3vh8.mjs} +1 -1
  12. package/dist/packem_shared/{jsCodeTool-CIlCK1bG.mjs → jsCodeTool-Bh4jaeoy.mjs} +2 -2
  13. package/dist/packem_shared/json-schema-CHVg-SsJ.mjs +1 -0
  14. package/dist/packem_shared/{runAgentLoop-Cv661XGm.mjs → runAgentLoop-8K0vPhGY.mjs} +1 -1
  15. package/dist/packem_shared/{runVoiceTurn-DAtWSeXj.mjs → runVoiceTurn-C4BAG61O.mjs} +1 -1
  16. package/dist/packem_shared/{voice-turn-DBWkPcQH.mjs → voice-turn-BjkorohD.mjs} +1 -1
  17. package/dist/packem_shared/webSearchTool-DUubGqov.mjs +1 -0
  18. package/dist/sandbox.mjs +1 -1
  19. package/package.json +7 -7
  20. package/dist/packem_shared/SecretUnavailableError-BCp40Leh.mjs +0 -1
  21. package/dist/packem_shared/agentAsTool-CA7Sha2i.mjs +0 -1
  22. package/dist/packem_shared/codeTool-Hm_Af6t4.mjs +0 -1
  23. package/dist/packem_shared/collectAgenticMemoryTools-BWdIhOfY.mjs +0 -1
  24. package/dist/packem_shared/createAgentGenerate-DSLXAeY2.mjs +0 -3
  25. package/dist/packem_shared/webSearchTool-BobmV4cD.mjs +0 -1
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{r,s as t}from"./packem_shared/agent-loop-ByDqRJo7.mjs";import{collectAgenticMemoryTools as n,toSearchResults as l}from"./packem_shared/collectAgenticMemoryTools-BWdIhOfY.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-CA7Sha2i.mjs";import{codeTool as p}from"./packem_shared/codeTool-Hm_Af6t4.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-CjdW-jip.mjs";import{defineAgent as g,defineAgentTool as u,isAgentDefinition as S}from"./packem_shared/defineAgent-D4eUl6YE.mjs";import{functionTool as N}from"./packem_shared/functionTool-C95ns65V.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as U}from"./packem_shared/createAgentGenerate-DSLXAeY2.mjs";import{jsCodeTool as F}from"./packem_shared/jsCodeTool-CIlCK1bG.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-DFF_g58r.mjs";import{buildModelMessages as L}from"./packem_shared/buildModelMessages-DVQdQ7_1.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 q,toFunctionReference as y}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as W,containerFsTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{SecretUnavailableError as Z,requestSecretTool as $,withSecret as ee}from"./packem_shared/SecretUnavailableError-BCp40Leh.mjs";import{defineSkill as re,isSkillDefinition as te}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as ne}from"./packem_shared/wrapUntrusted-BuHBC6sV.mjs";import{default as fe}from"./packem_shared/VoiceSessionDO-BIfcyunp.mjs";import{r as ie}from"./packem_shared/voice-turn-DBWkPcQH.mjs";import{webSearchTool as me}from"./packem_shared/webSearchTool-BobmV4cD.mjs";import{default as xe}from"./packem_shared/compileAgentWorkflow-BkVDrDvM.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,q as SANDBOX_MODULE,Z as SecretUnavailableError,fe as VoiceSessionDO,b as adaptMcpResult,s as agentAsTool,B as agentClassName,c as agentComponent,R as agentDefaultName,x as agentExtension,W as browserTool,L as buildModelMessages,p as codeTool,n as collectAgenticMemoryTools,xe as compileAgentWorkflow,z as containerFsTool,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,g as defineAgent,u as defineAgentTool,re as defineSkill,Q as fsTool,N as functionTool,S as isAgentDefinition,te as isSkillDefinition,F as jsCodeTool,h as mcpTools,$ as requestSecretTool,U as resolveAgentModel,r as runAgentLoop,ie as runVoiceTurn,t as splitForCompaction,y as toFunctionReference,l as toSearchResults,V as voiceBindingName,H as voiceClassName,me as webSearchTool,ee as withSecret,ne as wrapUntrusted};
1
+ import{r,s as t}from"./packem_shared/agent-loop-C11GY0Yw.mjs";import{collectAgenticMemoryTools as n,toSearchResults as l}from"./packem_shared/collectAgenticMemoryTools-Dxs7mpo6.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-ifwGRMR6.mjs";import{codeTool as p}from"./packem_shared/codeTool-BZkKDqsZ.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-CjdW-jip.mjs";import{defineAgent as g,defineAgentTool as u,isAgentDefinition as S}from"./packem_shared/defineAgent-BsDM3vh8.mjs";import{functionTool as N}from"./packem_shared/functionTool-C95ns65V.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as U}from"./packem_shared/createAgentGenerate-CTkL_e0Z.mjs";import{jsCodeTool as F}from"./packem_shared/jsCodeTool-Bh4jaeoy.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-DOud9k_Q.mjs";import{buildModelMessages as L}from"./packem_shared/buildModelMessages-DVQdQ7_1.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 q,toFunctionReference as y}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as W,containerFsTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{SecretUnavailableError as Z,requestSecretTool as $,withSecret as ee}from"./packem_shared/SecretUnavailableError-D8u6pPM6.mjs";import{defineSkill as re,isSkillDefinition as te}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as ne}from"./packem_shared/wrapUntrusted-BuHBC6sV.mjs";import{default as fe}from"./packem_shared/VoiceSessionDO-D4dEV12P.mjs";import{r as ie}from"./packem_shared/voice-turn-BjkorohD.mjs";import{webSearchTool as me}from"./packem_shared/webSearchTool-DUubGqov.mjs";import{default as xe}from"./packem_shared/compileAgentWorkflow-DDQ-_8S0.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,q as SANDBOX_MODULE,Z as SecretUnavailableError,fe as VoiceSessionDO,b as adaptMcpResult,s as agentAsTool,B as agentClassName,c as agentComponent,R as agentDefaultName,x as agentExtension,W as browserTool,L as buildModelMessages,p as codeTool,n as collectAgenticMemoryTools,xe as compileAgentWorkflow,z as containerFsTool,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,g as defineAgent,u as defineAgentTool,re as defineSkill,Q as fsTool,N as functionTool,S as isAgentDefinition,te as isSkillDefinition,F as jsCodeTool,h as mcpTools,$ as requestSecretTool,U as resolveAgentModel,r as runAgentLoop,ie as runVoiceTurn,t as splitForCompaction,y as toFunctionReference,l as toSearchResults,V as voiceBindingName,H as voiceClassName,me as webSearchTool,ee as withSecret,ne as wrapUntrusted};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{j as y}from"./json-schema-CHVg-SsJ.mjs";import{toFunctionReference as l,DEFAULT_AGENT_FUNCTION_PATHS as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const p=200,N=e=>{const t=typeof e=="object"&&e!==null?e.label:void 0;if(!(typeof t!="string"||t.trim().length===0))return[...t.trim()].slice(0,p).join("")};class g extends Error{code="SECRET_UNAVAILABLE";constructor(){super("the secret is no longer available: it expired, was already used by another tool call, or was never supplied"),this.name="SecretUnavailableError"}}const T=e=>{if(typeof e.description!="string"||e.description.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `description` (the model decides from it)");if(typeof e.consumer!="string"||e.consumer.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `consumer`: the name of the one tool allowed to read the value");return{description:e.description,execute:()=>{throw new s("INTERNAL","@lunora/agent: requestSecretTool is resolved by the loop and must never be executed")},inputSchema:y({properties:{label:{description:"What the secret is for, shown to the person asked.",type:"string"}},required:["label"],type:"object"}),isLunoraAgentTool:!0,secretRequest:{consumer:e.consumer}}},w=(e,t)=>t instanceof Error?{...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name,stack:t.stack}:t,f=e=>{const t=new TextEncoder().encode(e),n=Array.from(t,r=>String.fromCodePoint(r)).join(""),a=btoa(n),o=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return[...new Set([a,a.replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),encodeURIComponent(e),o,JSON.stringify(e).slice(1,-1),e])]},h=(e,t)=>{if(t.length===0||e===void 0||typeof e=="function"||typeof e=="symbol")return!1;let n;try{n=JSON.stringify(e,w)}catch{return!1}return f(t).some(a=>n.includes(a))},E="[redacted]",u="@lunora/agent: withSecret's callback threw a value that is withheld, in case it carries the secret",c=(e,t)=>{if(t.length===0)return e;let n=e;for(const a of f(t).toSorted((o,r)=>r.length-o.length))n=n.split(a).join(E);return n},m=(e,t,n=new Set)=>{if(!(e instanceof Error))return new s("INTERNAL",u);if(n.has(e))return e;n.add(e);try{e.message=c(e.message,t),typeof e.stack=="string"&&(e.stack=c(e.stack,t));const a=e;for(const o of Object.getOwnPropertyNames(e)){if(o==="message"||o==="stack")continue;const r=a[o];if(r instanceof Error){const i=m(r,t,n);i!==r&&(a[o]=i)}else h(r,t)&&(a[o]=JSON.parse(c(JSON.stringify(r),t)))}}catch{return new s("INTERNAL",u)}return e},I=async(e,t,n)=>{const a=await e.step.do(`secret:consume:${e.idempotencyKey}:${t}`,async()=>{const o=await e.run(l(d.takeSecret),{claimant:e.idempotencyKey,consumerCallId:e.toolCallId,instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t});if(typeof o!="string")return{unavailable:!0};let r;try{r=await n(o)}catch(i){throw m(i,o)}return h(r,o)?{leaked:!0}:{result:r}});if("unavailable"in a)throw new g;if(await e.step.do(`secret:discard:${e.idempotencyKey}:${t}`,async()=>{await e.run(l(d.discardSecret),{instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t})}),"leaked"in a)throw new s("INTERNAL","@lunora/agent: withSecret's callback returned the secret, so its result was not recorded");return a.result};export{g as SecretUnavailableError,T as requestSecretTool,N as secretLabelOf,I as withSecret};
@@ -1 +1 @@
1
- import{createAi as A}from"@lunora/ai/create";import{a as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.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-DBWkPcQH.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-DSLXAeY2.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.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};
1
+ import{createAi as A}from"@lunora/ai/create";import{a as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.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-BjkorohD.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-CTkL_e0Z.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.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};
@@ -1,2 +1,2 @@
1
- import{jsonSchema as i}from"@ai-sdk/provider-utils";import{LunoraError as c}from"@lunora/errors";const s=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const n=(t.content??[]).filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
1
+ import{LunoraError as c}from"@lunora/errors";import{j as i}from"./json-schema-CHVg-SsJ.mjs";const s=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const n=(t.content??[]).filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
2
2
  `);return t.isError===!0?`MCP tool error: ${n.length>0?n:"unknown error"}`:n.length>0?n:t.content},l=(t,n,e)=>({description:n.description??`MCP tool "${n.name}".`,execute:async r=>s(await t.callTool({arguments:r,name:n.name})),inputSchema:i(n.inputSchema),isLunoraAgentTool:!0,...e===void 0?{}:{needsApproval:typeof e=="function"?r=>e(n.name,r):e}}),u=async t=>{if(t.command!==void 0)throw new c("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 c("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const n=new URL(t.url),{Client:e}=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(n)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(n)}const o=new e({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await o.connect(r),o},T=async t=>{const n=t.client??await u(t),{tools:e}=await n.listTools(),r={};for(const o of e)t.only!==void 0&&!t.only.includes(o.name)||(r[`${t.prefix??""}${o.name}`]=l(n,o,t.needsApproval));return r};export{s as adaptMcpResult,T as mcpTools};
@@ -1,3 +1,3 @@
1
- import{usageStatus as pt}from"@lunora/ai/create";import{e as mt}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as yt}from"@lunora/platform";import{r as Z}from"./workflow-binding-Dm9hBzx_.mjs";import{e as X,d as ft,S as Y}from"./component-shared-DdXFbng-.mjs";import{usageOfFailedTurn as ht,resolveAgentModel as wt}from"./createAgentGenerate-DSLXAeY2.mjs";import{buildModelMessages as W}from"./buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as tt}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as vt}from"./positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as gt,secretLabelOf as Tt}from"./SecretUnavailableError-BCp40Leh.mjs";import{combineTelemetry as St}from"./combineTelemetry-DgE9W9G8.mjs";import{c as z}from"./tool-output-Cmk3JWMG.mjs";const $t=200,Et=e=>{const t=e.findIndex(n=>n.role!=="tool");return t===-1?[]:e.slice(t)},Rt=async e=>{let t=$t;for(;;){const n=await e(t),o=Et(n);if(o.length>0||n.length<t)return o;t*=2}},It=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",B=e=>e.memorySources?e.memorySources:e.memory&&It(e.memory)?[{key:"default",...e.memory}]:[],xt=e=>B(e).find(t=>t.kind==="graph"),Ct=e=>B(e).find(t=>t.kind==="episodic"),I=(e,t)=>t==="default"?e:`${e}:${t}`,kt=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:St(...n)},Mt=async e=>{e===void 0||e.isEnabled===!1||await Promise.all([e.integrations].flat().map(async t=>{try{await t?.flush?.()}catch{}}))},Kt=async(e,t,n)=>{const o=kt(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},i=Date.now();await o.onToolExecutionStart?.(s);let c;const d=()=>(c??=n(),c);try{if(o.executeTool===void 0)await d();else try{await o.executeTool({...s,execute:d,toolCallId:t.id})}catch{}const u=await d();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,input:t.input,output:u,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),u}catch(u){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:u,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),u}},Nt=8,At=e=>vt(e)?e:0,et=e=>e===void 0?"null":JSON.stringify(e),Ot=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)}},_t=e=>e===void 0?[]:[e].flat(),qt=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),Ut=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],j=e=>e.status??pt(e),bt=(e,t)=>e===t?e:"partial",ot=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:j(t)};const n={status:bt(j(e),j(t))};for(const o of Ut)(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},Dt=async(e,t,n,o,a,s)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:n.do(o,async()=>await s()?!1:i===!0||i(t,a))},Ft="WorkflowTimeoutError",nt=e=>e instanceof Error&&e.name===Ft,J=4320*60*1e3,Pt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Gt=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,at=e=>{if(e===void 0)return J;if(typeof e=="number")return Math.min(e,X);const t=Gt.exec(e);return t===null?J:Math.min(Number(t[1])*Pt[t[2]],X)},Lt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:i,step:c}=e,d=at(n.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+d,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"})});const u=await c.waitForEvent(`approval:${t.id}`,{timeout:d,type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note},...p.payload.scope===void 0?{}:{scope:p.payload.scope}})).catch(p=>{if(!nt(p))throw p;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),u},jt={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Wt=(e,t)=>`${String(e)}:${t}`,Bt=async(e,t,n,o,a)=>{const{agent:s,deleteMessage:i,instanceId:c,openSecretRef:d,patchThread:u,persist:p,run:r,settleSecretRef:l,step:m,threadKey:h}=e,T=`${c}:secret:${a}`,y=Math.min(at(s.approvalTimeout),yt-Y);await m.do(`secret:request:${a}`,async()=>{await r(d,{consumerTool:n,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:o,threadKey:h,toolCallId:a,toolName:t.name})}),await m.do(`secret:await:${a}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${o}`,messageKey:T,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await u({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${a}`,{timeout:y+Y,type:`agent-secret:${a}`}).catch(f=>{if(!nt(f))throw f});const{status:v}=await m.do(`secret:settle:${a}`,async()=>await r(l,{instanceId:c,threadKey:h,toolCallId:a}));return await i(T),await u({ifInstanceId:c,status:"running"}),v},U="lunoraToolOutcome",Ht=e=>typeof e=="object"&&e!==null&&U in e?e[U]:{ok:e},Vt=async(e,t,n,o)=>{const{instanceId:a,persist:s}=e,i=Wt(o,t.id),c=`${a}:secret-result:${i}`,d=`tool:${t.name}:${i}`,u=Tt(t.input);if(u===void 0){await s({content:`Error: invalid input for tool "${t.name}" — it was not run. \`label\` must be a non-empty string saying what the secret is for.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}if(e.owner===void 0){await s({content:`Error: tool "${t.name}" was not run: this run has no owner, so no one can supply a secret for it.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const p=await Bt(e,t,n,u,i);await s({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${jt[p]}.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name})},Xt=async(e,t,n)=>{const{agent:o,approvalGrantedRef:a,depth:s,env:i,exports:c,getState:d,instanceId:u,onTokenDelta:p,owner:r,persist:l,run:m,setState:h,step:T,threadKey:y,tools:v}=e,f=`tool:${t.name}:${t.id}`,$=v[t.name],E=`${u}:tool:${t.id}`;if(!$){await l({content:`Error: unknown tool "${t.name}"`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await l({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if($.secretRequest!==void 0){await Vt(e,t,$.secretRequest.consumer,n);return}const b={depth:s,env:i,exports:c,getState:d,idempotencyKey:f,instanceId:u,owner:r,reportProgress:S=>{p?.({data:S,kind:"progress",threadKey:y,toolCallId:t.id})},run:m,setState:h,step:T,threadKey:y,toolCallId:t.id},D={depth:s,env:i,getState:d,idempotencyKey:f,instanceId:u,run:m,threadKey:y,toolCallId:t.id},F=`tool:approval-gate:${t.id}`;let M,K;const P=async()=>await m(a,{key:y,toolName:t.name})===!0;if(await Dt($,t.input,T,F,D,P)){const{decision:S,note:C,scope:G}=await Lt(e,t);if(S==="reject"){const O=C===void 0?"":` Reason: ${C}`;await l({content:`Tool "${t.name}" was rejected by the user and not run.${O}`,messageKey:E,role:"tool",status:"rejected",stepName:f,toolCallId:t.id,toolName:t.name});return}M="approved",K=G}const A={...M===void 0?{}:{status:M},...K===void 0?{}:{approvalScope:K}},N=Ht(await T.do(f,async()=>{try{const S=()=>Promise.resolve($.execute(t.input,b)),C=await Kt(o.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[U]:{ok:C}}}catch(S){if(mt(S)||S instanceof gt)return{[U]:{failed:S.message}};throw S}}));if("failed"in N){await l({content:z(`Error: tool "${t.name}" failed and will not be retried. ${N.failed}`),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name});return}const x=N.ok;await l({content:z(typeof x=="string"?x:et(x)),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name})},Yt=(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:wt(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},st=(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)}},zt=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=st(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:a,messages:W({history:s.older}),model:n.compaction?.model??n.model});return i.length>0?{history:s.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Jt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},Qt=async e=>{const{agent:t,compact:n,env:o,historyRef:a,instanceId:s,patchThread:i,run:c,threadKey:d}=e,u=Jt(t.compaction),p=await c(a,{configKey:u,key:d}),{messages:r,summary:l}=p,m=st(r,t.compaction);if(m===void 0||n===void 0)return{history:r,summary:l};const h=async()=>{const{fallback:v}=p;return v===void 0?{history:r,summary:l}:(await i({ifInstanceId:s,summaryRebuiltSeq:v.throughSeq}).catch(f=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${d}"`,f)}),{history:r.filter(f=>f.seq>v.throughSeq),summary:v.summary})};let T;try{T=await n({env:o,messages:W({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(v){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,v),h()}if(T.length===0)return h();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:s,summary:T,summaryConfig:u,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(v=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,v)}),{history:m.recent,summary:T}},Zt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:i,listMessages:c,memoryContext:d,onTokenDelta:u,run:p,step:r,streamGenerate:l,threadKey:m}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const{history:h,summary:T}=o.compaction!==void 0&&e.compact!==void 0?await Qt(e):await zt(e,await Rt(async f=>await p(c,{key:m,limit:f})));let y={activeTools:o.activeTools,messages:W({history:h,instructions:i,memoryContext:d,summary:T}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(y=Yt(y,await o.prepareStep({messages:y.messages,stepNumber:t,steps:n}),a));const v={messages:y.messages,...y.activeTools===void 0?{}:{activeTools:y.activeTools},...y.model===void 0?{}:{model:y.model},...y.toolChoice===void 0?{}:{toolChoice:y.toolChoice}};return l&&u?l(v,f=>{u({text:f,threadKey:m,turn:t})}):s(v)})},Q=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))},te=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}}),H=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},ee=e=>ft({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),oe=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:s}=e,i=I("memory:retrieve",e.key),c=await n.do(i,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return H(c)},ne=async(e,t,n,o,a,s)=>{if(n===void 0)return;const i=I("memory:traverse",e.key),c=await a.do(i,async()=>s(o,{owner:n,query:t,...ee(e.graph)}));return H(c)},ae=async(e,t,n,o,a)=>{if(t===void 0)return;const s=I("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await o.do(s,async()=>a(n,i));return H(c)},se=async(e,t)=>e.kind==="episodic"?ae(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?ne(e,t.input,t.owner,t.graphTraverse,t.step,t.run):oe(e,t.input,t.step,t.run),re=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},ie=async(e,t,n,o,a,s)=>{const i=re(B(e));if(i.length===0)return;const c=g(o.graphTraverse),d=g(o.episodeRecall),u=[];for(const p of i){const r=await se(p,{episodeRecall:d,graphTraverse:c,input:t,owner:n,run:s,step:a});r!==void 0&&u.push(r)}return u.length>0?u.join(`
1
+ import{usageStatus as pt}from"@lunora/ai/create";import{e as mt}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as yt}from"@lunora/platform";import{r as Z}from"./workflow-binding-Dm9hBzx_.mjs";import{e as X,d as ft,S as Y}from"./component-shared-DdXFbng-.mjs";import{usageOfFailedTurn as ht,resolveAgentModel as wt}from"./createAgentGenerate-CTkL_e0Z.mjs";import{buildModelMessages as W}from"./buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as tt}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as vt}from"./positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as gt,secretLabelOf as Tt}from"./SecretUnavailableError-D8u6pPM6.mjs";import{combineTelemetry as St}from"./combineTelemetry-DgE9W9G8.mjs";import{c as z}from"./tool-output-Cmk3JWMG.mjs";const $t=200,Et=e=>{const t=e.findIndex(n=>n.role!=="tool");return t===-1?[]:e.slice(t)},Rt=async e=>{let t=$t;for(;;){const n=await e(t),o=Et(n);if(o.length>0||n.length<t)return o;t*=2}},It=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",B=e=>e.memorySources?e.memorySources:e.memory&&It(e.memory)?[{key:"default",...e.memory}]:[],xt=e=>B(e).find(t=>t.kind==="graph"),Ct=e=>B(e).find(t=>t.kind==="episodic"),I=(e,t)=>t==="default"?e:`${e}:${t}`,kt=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:St(...n)},Mt=async e=>{e===void 0||e.isEnabled===!1||await Promise.all([e.integrations].flat().map(async t=>{try{await t?.flush?.()}catch{}}))},Kt=async(e,t,n)=>{const o=kt(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},i=Date.now();await o.onToolExecutionStart?.(s);let c;const d=()=>(c??=n(),c);try{if(o.executeTool===void 0)await d();else try{await o.executeTool({...s,execute:d,toolCallId:t.id})}catch{}const u=await d();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,input:t.input,output:u,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),u}catch(u){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:u,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),u}},Nt=8,At=e=>vt(e)?e:0,et=e=>e===void 0?"null":JSON.stringify(e),Ot=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)}},_t=e=>e===void 0?[]:[e].flat(),qt=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),Ut=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],j=e=>e.status??pt(e),bt=(e,t)=>e===t?e:"partial",ot=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:j(t)};const n={status:bt(j(e),j(t))};for(const o of Ut)(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},Dt=async(e,t,n,o,a,s)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:n.do(o,async()=>await s()?!1:i===!0||i(t,a))},Ft="WorkflowTimeoutError",nt=e=>e instanceof Error&&e.name===Ft,J=4320*60*1e3,Pt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Gt=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,at=e=>{if(e===void 0)return J;if(typeof e=="number")return Math.min(e,X);const t=Gt.exec(e);return t===null?J:Math.min(Number(t[1])*Pt[t[2]],X)},Lt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:i,step:c}=e,d=at(n.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+d,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"})});const u=await c.waitForEvent(`approval:${t.id}`,{timeout:d,type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note},...p.payload.scope===void 0?{}:{scope:p.payload.scope}})).catch(p=>{if(!nt(p))throw p;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),u},jt={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Wt=(e,t)=>`${String(e)}:${t}`,Bt=async(e,t,n,o,a)=>{const{agent:s,deleteMessage:i,instanceId:c,openSecretRef:d,patchThread:u,persist:p,run:r,settleSecretRef:l,step:m,threadKey:h}=e,T=`${c}:secret:${a}`,y=Math.min(at(s.approvalTimeout),yt-Y);await m.do(`secret:request:${a}`,async()=>{await r(d,{consumerTool:n,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:o,threadKey:h,toolCallId:a,toolName:t.name})}),await m.do(`secret:await:${a}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${o}`,messageKey:T,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await u({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${a}`,{timeout:y+Y,type:`agent-secret:${a}`}).catch(f=>{if(!nt(f))throw f});const{status:v}=await m.do(`secret:settle:${a}`,async()=>await r(l,{instanceId:c,threadKey:h,toolCallId:a}));return await i(T),await u({ifInstanceId:c,status:"running"}),v},U="lunoraToolOutcome",Ht=e=>typeof e=="object"&&e!==null&&U in e?e[U]:{ok:e},Vt=async(e,t,n,o)=>{const{instanceId:a,persist:s}=e,i=Wt(o,t.id),c=`${a}:secret-result:${i}`,d=`tool:${t.name}:${i}`,u=Tt(t.input);if(u===void 0){await s({content:`Error: invalid input for tool "${t.name}" — it was not run. \`label\` must be a non-empty string saying what the secret is for.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}if(e.owner===void 0){await s({content:`Error: tool "${t.name}" was not run: this run has no owner, so no one can supply a secret for it.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const p=await Bt(e,t,n,u,i);await s({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${jt[p]}.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name})},Xt=async(e,t,n)=>{const{agent:o,approvalGrantedRef:a,depth:s,env:i,exports:c,getState:d,instanceId:u,onTokenDelta:p,owner:r,persist:l,run:m,setState:h,step:T,threadKey:y,tools:v}=e,f=`tool:${t.name}:${t.id}`,$=v[t.name],E=`${u}:tool:${t.id}`;if(!$){await l({content:`Error: unknown tool "${t.name}"`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await l({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if($.secretRequest!==void 0){await Vt(e,t,$.secretRequest.consumer,n);return}const b={depth:s,env:i,exports:c,getState:d,idempotencyKey:f,instanceId:u,owner:r,reportProgress:S=>{p?.({data:S,kind:"progress",threadKey:y,toolCallId:t.id})},run:m,setState:h,step:T,threadKey:y,toolCallId:t.id},D={depth:s,env:i,getState:d,idempotencyKey:f,instanceId:u,run:m,threadKey:y,toolCallId:t.id},F=`tool:approval-gate:${t.id}`;let M,K;const P=async()=>await m(a,{key:y,toolName:t.name})===!0;if(await Dt($,t.input,T,F,D,P)){const{decision:S,note:C,scope:G}=await Lt(e,t);if(S==="reject"){const O=C===void 0?"":` Reason: ${C}`;await l({content:`Tool "${t.name}" was rejected by the user and not run.${O}`,messageKey:E,role:"tool",status:"rejected",stepName:f,toolCallId:t.id,toolName:t.name});return}M="approved",K=G}const A={...M===void 0?{}:{status:M},...K===void 0?{}:{approvalScope:K}},N=Ht(await T.do(f,async()=>{try{const S=()=>Promise.resolve($.execute(t.input,b)),C=await Kt(o.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[U]:{ok:C}}}catch(S){if(mt(S)||S instanceof gt)return{[U]:{failed:S.message}};throw S}}));if("failed"in N){await l({content:z(`Error: tool "${t.name}" failed and will not be retried. ${N.failed}`),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name});return}const x=N.ok;await l({content:z(typeof x=="string"?x:et(x)),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name})},Yt=(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:wt(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},st=(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)}},zt=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=st(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:a,messages:W({history:s.older}),model:n.compaction?.model??n.model});return i.length>0?{history:s.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Jt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},Qt=async e=>{const{agent:t,compact:n,env:o,historyRef:a,instanceId:s,patchThread:i,run:c,threadKey:d}=e,u=Jt(t.compaction),p=await c(a,{configKey:u,key:d}),{messages:r,summary:l}=p,m=st(r,t.compaction);if(m===void 0||n===void 0)return{history:r,summary:l};const h=async()=>{const{fallback:v}=p;return v===void 0?{history:r,summary:l}:(await i({ifInstanceId:s,summaryRebuiltSeq:v.throughSeq}).catch(f=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${d}"`,f)}),{history:r.filter(f=>f.seq>v.throughSeq),summary:v.summary})};let T;try{T=await n({env:o,messages:W({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(v){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,v),h()}if(T.length===0)return h();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:s,summary:T,summaryConfig:u,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(v=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,v)}),{history:m.recent,summary:T}},Zt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:i,listMessages:c,memoryContext:d,onTokenDelta:u,run:p,step:r,streamGenerate:l,threadKey:m}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const{history:h,summary:T}=o.compaction!==void 0&&e.compact!==void 0?await Qt(e):await zt(e,await Rt(async f=>await p(c,{key:m,limit:f})));let y={activeTools:o.activeTools,messages:W({history:h,instructions:i,memoryContext:d,summary:T}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(y=Yt(y,await o.prepareStep({messages:y.messages,stepNumber:t,steps:n}),a));const v={messages:y.messages,...y.activeTools===void 0?{}:{activeTools:y.activeTools},...y.model===void 0?{}:{model:y.model},...y.toolChoice===void 0?{}:{toolChoice:y.toolChoice}};return l&&u?l(v,f=>{u({text:f,threadKey:m,turn:t})}):s(v)})},Q=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))},te=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}}),H=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},ee=e=>ft({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),oe=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:s}=e,i=I("memory:retrieve",e.key),c=await n.do(i,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return H(c)},ne=async(e,t,n,o,a,s)=>{if(n===void 0)return;const i=I("memory:traverse",e.key),c=await a.do(i,async()=>s(o,{owner:n,query:t,...ee(e.graph)}));return H(c)},ae=async(e,t,n,o,a)=>{if(t===void 0)return;const s=I("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await o.do(s,async()=>a(n,i));return H(c)},se=async(e,t)=>e.kind==="episodic"?ae(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?ne(e,t.input,t.owner,t.graphTraverse,t.step,t.run):oe(e,t.input,t.step,t.run),re=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},ie=async(e,t,n,o,a,s)=>{const i=re(B(e));if(i.length===0)return;const c=g(o.graphTraverse),d=g(o.episodeRecall),u=[];for(const p of i){const r=await se(p,{episodeRecall:d,graphTraverse:c,input:t,owner:n,run:s,step:a});r!==void 0&&u.push(r)}return u.length>0?u.join(`
2
2
 
3
3
  `):void 0},ce=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:i,owner:c,paths:d,run:u,step:p}=e;if(o===void 0||c===void 0||a===void 0||a.length===0)return;const r=xt(t);if(r!==void 0)try{const l={assistantText:a,env:n,model:r.graph?.extractionModel??t.model,userInput:s},m=await p.do(I("memory:extract",r.key),async()=>o(l));await u(g(d.graphUpsert),{...m,messageKey:`${i}:${I("extract",r.key)}`,owner:c})}catch{}},ue=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:i,owner:c,paths:d,run:u,step:p,threadKey:r}=e;if(o===void 0||c===void 0||a===void 0||a.length===0)return;const l=Ct(t);if(l!==void 0)try{const m={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:h}=await p.do(I("memory:episode",l.key),async()=>o(m));await u(g(d.episodeUpsert),{messageKey:`${i}:${I("episode",l.key)}`,owner:c,summary:h,threadKey:r})}catch{}},de=async(e,t,n)=>{const o=Z(e.env,e.exports,tt(t),["get"]);if(o!==void 0)try{await(await o.get(n)).terminate()}catch{}},le="12 hours",pe=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:le,type:`agent-dequeue:${t}:${n}`})},me=async(e,t,n)=>{const o=Z(e.env,e.exports,tt(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{}},ye=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{}},fe=async(e,t,n,o,a)=>{const{instanceId:s,persist:i}=e,c=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const d=n.output!==void 0&&n.text.length===0?et(n.output):n.text;return await i({content:d,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await Q(e,{text:n.text,toolCalls:[],turn:t,...c}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await i({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const d of n.toolCalls)await Xt(e,d,t);if(await Q(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...c}),o.push(te(n)),a.length>0&&await qt(a,o))return"stopCondition"},he=async(e,t,n,o)=>{const a=[];let s,i=!1,c=0;for(let d=0;d<t;d+=1){const u=await Zt(e,d,a);o.value=ot(o.value,u.usage),c=d+1;const p=await fe(e,d,u,a,n);if(p==="stopCondition"){i=!0;break}if(p!==void 0){s=p.final;break}}return{final:s,stoppedByCondition:i,turnsRun:c}},Ke=async e=>{const{agent:t,compact:n,env:o,exportName:a,exports:s,extractEpisode:i,extractGraph:c,generate:d,instanceId:u,onTokenDelta:p,params:r,paths:l,run:m,step:h,streamGenerate:T}=e,y=t.maxTurns??Nt,v=_t(t.stopWhen),f=g(l.appendMessage),$=g(l.approvalGranted),E=g(l.openSecretRequest),V=g(l.settleSecretRequest),b=g(l.completeRun),D=g(l.ensureThread),F=g(l.listMessages),M=g(l.history),K=g(l.deleteMessage),P=g(l.patchThread),A=g(l.setState),N=g(l.state),x=async w=>{await m(f,{threadKey:r.threadKey,...w})},S=async w=>{await m(P,{key:r.threadKey,...w})},C=async w=>{await m(K,{messageKey:w,threadKey:r.threadKey})},G=async()=>{await x({content:r.input,messageKey:`${u}:user`,role:"user"})},O={dispatched:!1},_=async w=>{O.dispatched=!0;const q=await m(b,{instanceId:u,key:r.threadKey,...w});q?.dequeued!==void 0&&await me({env:o,exportName:a,exports:s,step:h},r.threadKey,q.dequeued)},rt=async()=>await m(N,{key:r.threadKey}),it=async w=>{await m(A,{key:r.threadKey,state:w})},L=await m(D,{agent:a,instanceId:u,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}});L?.outcome==="replaced"&&await de({env:o,exports:s},a,L.priorInstanceId);const ct=await ie(t,r.input,r.owner,l,h,m),ut=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,dt={agent:t,approvalGrantedRef:$,openSecretRef:E,settleSecretRef:V,compact:n,depth:At(r.depth),env:o,exports:s,generate:d,getState:rt,historyRef:M,instanceId:u,instructions:ut,listMessages:F,memoryContext:ct,onTokenDelta:p,owner:r.owner,deleteMessage:C,patchThread:S,persist:x,run:m,setState:it,step:h,streamGenerate:T,threadKey:r.threadKey,tools:t.tools??{}},k={value:void 0};try{L?.outcome==="queued"&&await pe(h,r.threadKey,u),await G();const{final:w,stoppedByCondition:q,turnsRun:lt}=await he(dt,y,v,k),R=k.value===void 0?{}:{usage:k.value};return await ce({agent:t,env:o,extractGraph:c,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h}),await ue({agent:t,env:o,extractEpisode:i,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h,threadKey:r.threadKey}),w?(await ye(t,{env:o,params:r,step:h},{...w,...R}),await _({status:"idle",...R}),{...w,...R}):q?(await _({status:"idle",...R}),{stopped:"stopCondition",turns:lt,...R}):(await _({error:`agent stopped: maxTurns (${String(y)}) reached`,status:"error",...R}),{stopped:"maxTurns",turns:y,...R})}catch(w){throw O.dispatched||(k.value=ot(k.value,ht(w)),await Ot(_,w,k.value)),w}finally{await Mt(t.telemetry)}};export{at as a,ot as b,zt as c,It as i,Ke as r,st as s};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as I}from"@lunora/workflow";import{f as L}from"./fnv1a-BNN96GYb.mjs";import{r as S}from"./workflow-binding-Dm9hBzx_.mjs";import{j as b}from"./json-schema-CHVg-SsJ.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as $,DEFAULT_AGENT_FUNCTION_PATHS as P}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),x=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",j=t=>t!==null&&typeof t=="object"?t.output:void 0,k=async t=>{await new Promise(e=>{setTimeout(e,t)})},C=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=R(a);if(_.has(s))return{output:j(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},D=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},U=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},V=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??x,o=t.pollIntervalMs??M,a=t.wait??k,s=$(P.listMessages),T=async(y,r)=>{const p=(h(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=S(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,g=`sub-${e}-${L(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:g,params:A});l=await i.get(d.id)}catch(d){if(!I(d))throw d;l=await i.get(g)}const{output:v,status:u}=await C(l,m,o,a);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(D(v)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const E=await r.run(s,{key:f});return U(E)};return{description:t.description,execute:T,inputSchema:b({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{V as agentAsTool};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{j as y}from"./json-schema-CHVg-SsJ.mjs";import{i as w}from"./positive-integer-ztHqqpBk.mjs";import{M as v,c as A}from"./tool-output-Cmk3JWMG.mjs";const T=16,g=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=v?e:A(o)},$=(e,o)=>{let t=e;for(const i of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))return;t=t[i]}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(!Object.hasOwn(o,r))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?$(o[r],t.$path):o[r]}const i={};for(const[r,n]of Object.entries(t))r!=="__proto__"&&(i[r]=l(n,o));return i},S=async(e,o,t)=>{const{asSchema:i}=await import("@ai-sdk/provider-utils"),{validate:r}=i(o.inputSchema);if(r===void 0)return t;const n=await r(t);if(n.success)return n.value;throw new a("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${n.error.message}`)},b=async(e,o,t,i)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>i)throw new a("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(i)}. Split it across several code calls.`);const n={},p=[],d=new Set;for(const s of r){if(d.has(s.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${s.id}" — each step id must be unique (later steps reference an output by id via $from)`);d.add(s.id)}for(const s of r){const c=Object.hasOwn(o,s.tool)?o[s.tool]:void 0;if(!c)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${s.tool}" (available: ${Object.keys(o).join(", ")})`);const m=await S(s,c,l(s.input??{},n)),u={...t,idempotencyKey:`${t.idempotencyKey}:${s.id}`,toolCallId:`${t.toolCallId}:${s.id}`},h=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,h);n[s.id]=f,p.push({id:s.id,output:g(f)})}return{final:p.at(-1)?.output,results:p}},E=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("; ")}.`,O=y({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"}),L=(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,n]of Object.entries(t)){if(n.needsApproval!==void 0&&n.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\`.`);if(n.secretRequest!==void 0)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it is a requestSecretTool, which a code-mode script can't pause for the owner to supply. Expose it as a normal top-level tool.`)}if(o.maxSteps!==void 0&&!w(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const i=o.maxSteps??T;return{description:o.description??E(e),execute:(r,n)=>b(r,e,n,i),inputSchema:O,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{L as codeTool,l as resolveReferences,b as runToolScript};
@@ -0,0 +1 @@
1
+ import{j as u}from"./json-schema-CHVg-SsJ.mjs";import{toFunctionReference as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const h=240,m=50,y=(t,s)=>t.length<=s?t:`${t.slice(0,s)}…`,f=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(m,Math.max(1,Math.trunc(t)))},g=(t,s)=>{const r=t??{},i=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:y(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},S=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"}),A=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),b=(t,s,r)=>{const i=d(s),e=Math.max(1,t.snippetChars??h),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,p)=>{const a=f(n.topK)??o,l=await p.run(i,{query:n.query,...a===void 0?{}:{topK:a}});return g(l,e)},inputSchema:S,isLunoraAgentTool:!0}},T=t=>{const s=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,i)=>i.run(s,{id:r.id}),inputSchema:A,isLunoraAgentTool:!0}},k=(t,s)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of s)e.knowledge&&r.push({key:e.name,...e.knowledge});const i={};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}`,c=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=b(e,e.source,n?c:void 0),n&&(i[c]=T(e.read))}return i};export{k as collectAgenticMemoryTools,g as toSearchResults};
@@ -1 +1 @@
1
- import{defineWorkflow as i}from"@lunora/workflow";import{r as m}from"./agent-loop-ByDqRJo7.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-DSLXAeY2.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-CYBmT9SD.mjs";import{a as T}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-CiSI9HE_.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};
1
+ import{defineWorkflow as i}from"@lunora/workflow";import{r as m}from"./agent-loop-C11GY0Yw.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-CTkL_e0Z.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-CYBmT9SD.mjs";import{a as T}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-CiSI9HE_.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{usageStatus as O}from"@lunora/ai/create";import{LunoraError as j}from"@lunora/errors";import{r as P}from"./agent-ai-CP87uSoZ.mjs";import{j as R}from"./json-schema-CHVg-SsJ.mjs";import{F as v,s as b}from"./common-DBc9y7Np.mjs";const m=e=>({...e,status:O(e)}),k=e=>m(b(e)),x=e=>e.map(t=>{const o={id:t.toolCallId,input:t.input,name:t.toolName};return t.invalid!==!0?o:{...o,invalid:t.error instanceof Error?t.error.message:String(t.error)}}),h=(e,t)=>{if(typeof e=="function")return e(t);if(typeof e=="string"){const o=P(t);if(!o)throw new j("INTERNAL",`@lunora/agent: the agent model "${e}" 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(e)}return e};let T;const f=()=>(T??=import("ai").catch(e=>{throw T=void 0,e}),T),q=(e,t,o)=>{const r=h(t.model,o),n={};for(const[a,u]of Object.entries(t.tools??{}))n[a]=e.tool({description:u.description,inputSchema:e.asSchema(u.inputSchema)});const i=t.output===void 0?void 0:e.Output.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:r,output:i,staticSettings:s,tools:n}},E=(e,t)=>{let o;return()=>(o??=f().then(r=>({ai:r,base:q(r,e,t)})).catch(r=>{throw o=void 0,r}),o)},S=(e,{activeTools:t,messages:o,model:r,signal:n,toolChoice:i})=>{const{defaultModel:s,output:a,staticSettings:u,tools:l}=e,d=t===void 0?l:Object.fromEntries(Object.entries(l).filter(([g])=>t.includes(g)));return{messages:o,model:r??s,...u,...Object.keys(d).length>0?{tools:d}:{},...i===void 0?{}:{toolChoice:i},...a===void 0?{}:{output:a},...n===void 0?{}:{abortSignal:n}}},M=e=>e instanceof Error?e:new Error(`model stream failed: ${String(e)}`,{cause:e}),N=e=>({inputTokens:{cacheRead:e?.inputTokens?.cacheRead,cacheWrite:e?.inputTokens?.cacheWrite,noCache:void 0,total:e?.inputTokens?.total},outputTokens:{reasoning:e?.outputTokens?.reasoning,text:void 0,total:e?.outputTokens?.total}}),_=e=>{if(e===void 0)return m(void 0);const t=e.inputTokens?.total,o=e.outputTokens?.total,r=t===void 0||o===void 0?void 0:t+o;return m(b({inputTokens:t,inputTokenDetails:{cacheReadTokens:e.inputTokens?.cacheRead,cacheWriteTokens:e.inputTokens?.cacheWrite},outputTokens:o,outputTokenDetails:{reasoningTokens:e.outputTokens?.reasoning},totalTokens:r}))},y=(e,t)=>{const o=new Error(e.raw===void 0?"model finished with an error reason":`model finished with an error reason (provider reason: ${e.raw})`,{cause:e});return o[v]=_(t),o},B=e=>{if(!(typeof e!="object"||e===null))return e[v]},I=(e,t)=>e.wrapLanguageModel({middleware:{wrapGenerate:async({doGenerate:o})=>{const r=await o();if(r.finishReason.unified==="error")throw y(r.finishReason,r.usage);return r},wrapStream:async({doStream:o})=>{const{stream:r,...n}=await o();let i=!1;return{...n,stream:r.pipeThrough(new TransformStream({flush:s=>{i||s.enqueue({error:new Error("model stream ended without a finish part"),type:"error"})},transform:(s,a)=>{if(s.type==="finish"&&(i=!0,s.finishReason.unified==="error")){a.enqueue({...s,usage:N(s.usage)}),a.enqueue({error:y(s.finishReason,s.usage),type:"error"});return}a.enqueue(s)}}))}}},model:t}),p=(e,t)=>typeof t=="string"?t:I(e,t),H=(e,t)=>{const o=E(e,t);return async r=>{const{ai:n,base:i}=await o(),s=S(i,r),a=await n.generateText({...s,model:p(n,s.model)});return{text:a.text,toolCalls:x(a.toolCalls),usage:k(a.usage),...i.output===void 0?{}:{output:a.output}}}},X=(e,t)=>{const o=E(e,t);return async(r,n)=>{const{ai:i,base:s}=await o(),a=S(s,r),u=i.streamText({...a,model:p(i,a.model)});let l="";try{for await(const c of u.stream){if(c.type==="error")throw M(c.error);c.type==="text-delta"&&(l+=c.text,n(c.text))}}catch(c){if(!r.signal?.aborted)throw c}if(r.signal?.aborted)return{text:l,toolCalls:[],usage:m(void 0)};const[d,g,A,C]=await Promise.all([u.text,u.toolCalls,u.usage,s.output===void 0?Promise.resolve(void 0):u.output]);return{text:d,toolCalls:x(g),usage:k(A),...s.output===void 0?{}:{output:C}}}},U=R({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"}),$=(e,t)=>["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: ${e}`,"",`Assistant: ${t}`].join(`
2
+ `),J=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{output:i}=await n.generateText({model:p(n,h(o,t)),output:n.Output.object({schema:U}),prompt:$(r,e)});return i},G=(e,t)=>["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: ${e}`,"",`Assistant: ${t}`].join(`
3
+ `),K=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{text:i}=await n.generateText({model:p(n,h(o,t)),prompt:G(r,e)});return{summary:i.trim()}},w="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.",W=" An existing brief of the earlier conversation is included above. UPDATE that brief: keep every still-relevant fact from it and fold in the newly aged-out messages. Do not replace it with a summary of only the new messages.",Q=()=>async({env:e,messages:t,model:o,previousSummary:r})=>{const n=await f(),{text:i}=await n.generateText({messages:t,model:p(n,h(o,e)),system:r===void 0?w:`${w}${W}`});return i.trim()};export{H as createAgentGenerate,Q as createCompact,K as createEpisodeExtract,J as createGraphExtract,X as createStreamGenerate,h as resolveAgentModel,B as usageOfFailedTurn};
@@ -1,3 +1,3 @@
1
- import{LunoraError as r}from"@lunora/errors";import{a as g,i as m}from"./agent-loop-ByDqRJo7.mjs";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-BWdIhOfY.mjs";import{agentAsTool as p}from"./agentAsTool-CA7Sha2i.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=e=>{if(e!==void 0&&(typeof e!="string"||e.length===0))throw new r("INTERNAL","@lunora/agent: defineAgent `name` must be a non-empty string when provided")},N=/^[a-zA-Z][\w-]*$/u,A=(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},k=(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(`
1
+ import{LunoraError as r}from"@lunora/errors";import{a as g,i as m}from"./agent-loop-C11GY0Yw.mjs";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-Dxs7mpo6.mjs";import{agentAsTool as p}from"./agentAsTool-ifwGRMR6.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=e=>{if(e!==void 0&&(typeof e!="string"||e.length===0))throw new r("INTERNAL","@lunora/agent: defineAgent `name` must be a non-empty string when provided")},N=/^[a-zA-Z][\w-]*$/u,A=(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},k=(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
  `)},y=(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},v=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)}},E=(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)`)},L=(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\``)},I=e=>{if(e===void 0)return;const n=g(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},j=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(T(e.name),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");I(e.approvalTimeout);const o=e.skills??[];v(o),L(e,o);const t=A(e,o),s=f(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;E(e.activeTools,s);for(const i of Object.keys(t))if(!N.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=y(e,o),d=k(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}:{}}},M=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,_=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{j as defineAgent,_ as defineAgentTool,M as isAgentDefinition};
@@ -1,4 +1,4 @@
1
- import{jsonSchema as m}from"@ai-sdk/provider-utils";import{LunoraError as y}from"@lunora/errors";const u="LOADER",b="2026-04-07",S=1e3,f=100,v=2e3,g=256*1024,p=3e4,T="Run JavaScript in an isolated sandbox and get its result. Provide `code`: the body of an async function — `return` the answer. Use it for calculation, parsing and data transformation. The sandbox has no network, no bindings and no tools; `console.log` output is returned as `logs`.",h=m({additionalProperties:!1,properties:{code:{description:"The body of an async function. `return` the result; it must be JSON-serializable.",type:"string"}},required:["code"],type:"object"}),w=e=>`const logs = [];
1
+ import{LunoraError as m}from"@lunora/errors";import{j as y}from"./json-schema-CHVg-SsJ.mjs";const u="LOADER",b="2026-04-07",S=1e3,f=100,v=2e3,g=256*1024,p=3e4,T="Run JavaScript in an isolated sandbox and get its result. Provide `code`: the body of an async function — `return` the answer. Use it for calculation, parsing and data transformation. The sandbox has no network, no bindings and no tools; `console.log` output is returned as `logs`.",h=y({additionalProperties:!1,properties:{code:{description:"The body of an async function. `return` the result; it must be JSON-serializable.",type:"string"}},required:["code"],type:"object"}),w=e=>`const logs = [];
2
2
  const format = (value) => { if (typeof value === "string") return value; try { return JSON.stringify(value); } catch { return String(value); } };
3
3
  const record = (...values) => { if (logs.length < ${String(f)}) logs.push(values.map(format).join(" ")); };
4
4
  const sandboxConsole = { debug: record, error: record, info: record, log: record, warn: record };
@@ -15,4 +15,4 @@ export default {
15
15
  }
16
16
  },
17
17
  };
18
- `,E=e=>e instanceof Error?e.message:String(e),_=async(e,r)=>{const o=e.body?.getReader();if(o===void 0)return"";const t=new TextDecoder;let n="",a=0;for(;;){const{done:s,value:i}=await o.read();if(s)break;if(a+=i.byteLength,a>r){await o.cancel();return}n+=t.decode(i,{stream:!0})}return n+t.decode()},L=e=>(Array.isArray(e)?e:[]).slice(0,f).map(r=>String(r).slice(0,v)),A=async(e,r,o)=>{let t;const n=new Promise(s=>{t=setTimeout(()=>{s({error:`the script did not finish within ${String(p)} ms`,logs:[]})},p)}),a=async()=>{const i=await e.load({compatibilityDate:b,env:{},globalOutbound:null,limits:{cpuMs:o,subRequests:0},mainModule:"main.js",modules:{"main.js":w(r)}}).getEntrypoint().fetch("https://sandbox/"),l=await _(i,g);if(l===void 0)return{error:`the script's result is over ${String(g)} bytes — return less`,logs:[]};const c=JSON.parse(l),d=L(c.logs);return typeof c.error=="string"?{error:c.error,logs:d}:{logs:d,value:c.value}};try{return await Promise.race([a(),n])}catch(s){return{error:E(s),logs:[]}}finally{clearTimeout(t)}},M=(e={})=>{const r=e.cpuMs??S;if(!Number.isInteger(r)||r<=0)throw new y("INTERNAL","@lunora/agent: jsCodeTool `cpuMs` must be a positive integer");return{description:e.description??T,execute:async(o,t)=>{const n=t.env[u];return typeof n?.load!="function"?{error:`jsCodeTool: no Worker Loader binding "${u}" on env — declare \`"worker_loaders": [{ "binding": "${u}" }]\` in wrangler.jsonc`,logs:[]}:A(n,o.code,r)},inputSchema:h,isLunoraAgentTool:!0}};export{M as jsCodeTool};
18
+ `,E=e=>e instanceof Error?e.message:String(e),_=async(e,r)=>{const o=e.body?.getReader();if(o===void 0)return"";const t=new TextDecoder;let n="",a=0;for(;;){const{done:s,value:i}=await o.read();if(s)break;if(a+=i.byteLength,a>r){await o.cancel();return}n+=t.decode(i,{stream:!0})}return n+t.decode()},L=e=>(Array.isArray(e)?e:[]).slice(0,f).map(r=>String(r).slice(0,v)),A=async(e,r,o)=>{let t;const n=new Promise(s=>{t=setTimeout(()=>{s({error:`the script did not finish within ${String(p)} ms`,logs:[]})},p)}),a=async()=>{const i=await e.load({compatibilityDate:b,env:{},globalOutbound:null,limits:{cpuMs:o,subRequests:0},mainModule:"main.js",modules:{"main.js":w(r)}}).getEntrypoint().fetch("https://sandbox/"),l=await _(i,g);if(l===void 0)return{error:`the script's result is over ${String(g)} bytes — return less`,logs:[]};const c=JSON.parse(l),d=L(c.logs);return typeof c.error=="string"?{error:c.error,logs:d}:{logs:d,value:c.value}};try{return await Promise.race([a(),n])}catch(s){return{error:E(s),logs:[]}}finally{clearTimeout(t)}},M=(e={})=>{const r=e.cpuMs??S;if(!Number.isInteger(r)||r<=0)throw new m("INTERNAL","@lunora/agent: jsCodeTool `cpuMs` must be a positive integer");return{description:e.description??T,execute:async(o,t)=>{const n=t.env[u];return typeof n?.load!="function"?{error:`jsCodeTool: no Worker Loader binding "${u}" on env — declare \`"worker_loaders": [{ "binding": "${u}" }]\` in wrangler.jsonc`,logs:[]}:A(n,o.code,r)},inputSchema:h,isLunoraAgentTool:!0}};export{M as jsCodeTool};
@@ -0,0 +1 @@
1
+ const r=Symbol.for("vercel.ai.schema"),n=(o,{validate:t}={})=>{let e=o;return{[r]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}};export{n as j};
@@ -1 +1 @@
1
- import"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import"./workflow-binding-Dm9hBzx_.mjs";import"./component-shared-DdXFbng-.mjs";import"./createAgentGenerate-DSLXAeY2.mjs";import{b as g,a as l,c as u,r as b,s as f}from"./agent-loop-ByDqRJo7.mjs";import"./buildModelMessages-DVQdQ7_1.mjs";import"../naming.mjs";import"./AGENT_MODULE-CYBmT9SD.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./SecretUnavailableError-BCp40Leh.mjs";import"./tool-output-Cmk3JWMG.mjs";export{g as addUsage,l as approvalTimeoutMs,u as compactHistory,b as runAgentLoop,f as splitForCompaction};
1
+ import"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import"./workflow-binding-Dm9hBzx_.mjs";import"./component-shared-DdXFbng-.mjs";import"./createAgentGenerate-CTkL_e0Z.mjs";import{b as g,a as l,c as u,r as b,s as f}from"./agent-loop-C11GY0Yw.mjs";import"./buildModelMessages-DVQdQ7_1.mjs";import"../naming.mjs";import"./AGENT_MODULE-CYBmT9SD.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./SecretUnavailableError-D8u6pPM6.mjs";import"./tool-output-Cmk3JWMG.mjs";export{g as addUsage,l as approvalTimeoutMs,u as compactHistory,b as runAgentLoop,f 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-DBWkPcQH.mjs";import"./agent-loop-ByDqRJo7.mjs";import"./buildModelMessages-DVQdQ7_1.mjs";import"./AGENT_MODULE-CYBmT9SD.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,c as toByteIterable};
1
+ import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-BjkorohD.mjs";import"./agent-loop-C11GY0Yw.mjs";import"./buildModelMessages-DVQdQ7_1.mjs";import"./AGENT_MODULE-CYBmT9SD.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 Y}from"./agent-loop-ByDqRJo7.mjs";import{buildModelMessages as Z}from"./buildModelMessages-DVQdQ7_1.mjs";import{toFunctionReference as A}from"./AGENT_MODULE-CYBmT9SD.mjs";const ut=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},C=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},F=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),n=e+"=".repeat((4-e.length%4)%4);return C(n)},H=new TextDecoder;new TextEncoder;const M="=",tt=t=>{if(t)try{const e=t[0]==="{"?t:H.decode(F(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},yt=t=>{if(t){if(!t.startsWith(M))return t;try{return H.decode(F(t.slice(M.length)))}catch{return}}},ft=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},lt=t=>typeof t=="number"&&Date.now()>=t,pt=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{}},et=16e3,nt=1,rt=16,P=/[.!?]\s/u,st=/\s/u,at=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},ht=(t,e=et,n=nt,r=rt)=>{const a=n*r/8,p=e*a,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(y,b)=>{for(let d=0;d<b.length;d+=1)s.setUint8(y+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,p,!0),s.setUint16(32,a,!0),s.setUint16(34,r,!0),u(36,"data"),s.setUint32(40,t.byteLength,!0);const i=new Uint8Array(m);return i.set(t,44),i},it=t=>{const e=[];let n=t,r=P.exec(n);for(;r;){let a=r.index+1;for(;a<n.length&&st.test(n[a]??"");)a+=1;const p=n.slice(0,a).trim();p.length>0&&e.push(p),n=n.slice(a),r=P.exec(n)}return{rest:n,sentences:e}},gt=async t=>{const{agent:e,compact:n,connectionId:r,env:a,exportName:p,owner:m,paths:s,pcm:u,run:i,send:y,sendAudio:b,signal:d,streamGenerate:L,synthesize:B,text:O,threadKey:o,transcribe:$,turn:U,waitForDrain:K}=t;let _=!1,v=!1;const j=()=>v,h=()=>d.aborted||_,I=A(s.appendMessage),W=A(s.ensureThread),V=A(s.listMessages),x=A(s.patchThread);await i(W,{agent:p,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const f=(O??(u?await $(u):"")).trim();if(f.length===0)return await i(x,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};y({text:f,type:"user_transcript"}),await i(I,{content:f,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await i(x,{key:o,status:"running"});const R=typeof e.instructions=="function"?e.instructions({env:a,input:f,threadKey:o}):e.instructions,X=await i(V,{key:o}),{history:J,summary:N}=await Y({agent:e,compact:n,env:a},X),q=Z({history:J,...R===void 0?{}:{instructions:R},...N===void 0?{}:{summary:N}});let g="",E="",k=Promise.resolve();const z=async c=>{if(h()||c.length===0)return;let w=!1;try{for await(const l of at(await B(c,d))){if(h()||(await K?.(),h()))break;b(l),w=!0}}catch(l){y({message:l instanceof Error?l.message:String(l),type:"error"})}w&&(E=E.length>0?`${E} ${c}`:c)},D=c=>{k=k.then(async()=>z(c))},G=await L({messages:q,signal:d},c=>{if(h())return;v=!0,y({text:c,type:"assistant_delta"}),g+=c;const{rest:w,sentences:l}=it(g);g=w;for(const Q of l)D(Q)});!h()&&g.trim().length>0&&D(g.trim()),g="",await k;const S=h(),T=S?E:G.text;return await i(I,{content:T,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await i(x,{key:o,status:"idle"}),y(S?{type:"interrupted"}:{text:T,type:"assistant_done"}),{assistantText:T,interrupted:S,userText:f}}catch(f){throw _=!0,j()&&y({type:"assistant_discarded"}),await i(x,{key:o,status:"idle"}),f}},mt=t=>tt(t),bt=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},xt=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 C(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{ft as a,pt as b,ht as c,yt as d,bt as e,xt as f,at as g,lt as i,mt as p,gt as r,ut as t};
1
+ import{c as Y}from"./agent-loop-C11GY0Yw.mjs";import{buildModelMessages as Z}from"./buildModelMessages-DVQdQ7_1.mjs";import{toFunctionReference as A}from"./AGENT_MODULE-CYBmT9SD.mjs";const ut=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},C=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},F=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),n=e+"=".repeat((4-e.length%4)%4);return C(n)},H=new TextDecoder;new TextEncoder;const M="=",tt=t=>{if(t)try{const e=t[0]==="{"?t:H.decode(F(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},yt=t=>{if(t){if(!t.startsWith(M))return t;try{return H.decode(F(t.slice(M.length)))}catch{return}}},ft=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},lt=t=>typeof t=="number"&&Date.now()>=t,pt=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{}},et=16e3,nt=1,rt=16,P=/[.!?]\s/u,st=/\s/u,at=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},ht=(t,e=et,n=nt,r=rt)=>{const a=n*r/8,p=e*a,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(y,b)=>{for(let d=0;d<b.length;d+=1)s.setUint8(y+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,p,!0),s.setUint16(32,a,!0),s.setUint16(34,r,!0),u(36,"data"),s.setUint32(40,t.byteLength,!0);const i=new Uint8Array(m);return i.set(t,44),i},it=t=>{const e=[];let n=t,r=P.exec(n);for(;r;){let a=r.index+1;for(;a<n.length&&st.test(n[a]??"");)a+=1;const p=n.slice(0,a).trim();p.length>0&&e.push(p),n=n.slice(a),r=P.exec(n)}return{rest:n,sentences:e}},gt=async t=>{const{agent:e,compact:n,connectionId:r,env:a,exportName:p,owner:m,paths:s,pcm:u,run:i,send:y,sendAudio:b,signal:d,streamGenerate:L,synthesize:B,text:O,threadKey:o,transcribe:$,turn:U,waitForDrain:K}=t;let _=!1,v=!1;const j=()=>v,h=()=>d.aborted||_,I=A(s.appendMessage),W=A(s.ensureThread),V=A(s.listMessages),x=A(s.patchThread);await i(W,{agent:p,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const f=(O??(u?await $(u):"")).trim();if(f.length===0)return await i(x,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};y({text:f,type:"user_transcript"}),await i(I,{content:f,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await i(x,{key:o,status:"running"});const R=typeof e.instructions=="function"?e.instructions({env:a,input:f,threadKey:o}):e.instructions,X=await i(V,{key:o}),{history:J,summary:N}=await Y({agent:e,compact:n,env:a},X),q=Z({history:J,...R===void 0?{}:{instructions:R},...N===void 0?{}:{summary:N}});let g="",E="",k=Promise.resolve();const z=async c=>{if(h()||c.length===0)return;let w=!1;try{for await(const l of at(await B(c,d))){if(h()||(await K?.(),h()))break;b(l),w=!0}}catch(l){y({message:l instanceof Error?l.message:String(l),type:"error"})}w&&(E=E.length>0?`${E} ${c}`:c)},D=c=>{k=k.then(async()=>z(c))},G=await L({messages:q,signal:d},c=>{if(h())return;v=!0,y({text:c,type:"assistant_delta"}),g+=c;const{rest:w,sentences:l}=it(g);g=w;for(const Q of l)D(Q)});!h()&&g.trim().length>0&&D(g.trim()),g="",await k;const S=h(),T=S?E:G.text;return await i(I,{content:T,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await i(x,{key:o,status:"idle"}),y(S?{type:"interrupted"}:{text:T,type:"assistant_done"}),{assistantText:T,interrupted:S,userText:f}}catch(f){throw _=!0,j()&&y({type:"assistant_discarded"}),await i(x,{key:o,status:"idle"}),f}},mt=t=>tt(t),bt=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},xt=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 C(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{ft as a,pt as b,ht as c,yt as d,bt as e,xt as f,at as g,lt as i,mt as p,gt as r,ut as t};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{r as h}from"./agent-ai-CP87uSoZ.mjs";import{j as u}from"./json-schema-CHVg-SsJ.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=u({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=h(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/dist/sandbox.mjs CHANGED
@@ -1 +1 @@
1
- import{jsonSchema as a}from"@ai-sdk/provider-utils";import{LunoraError as s}from"@lunora/errors";import{toFunctionReference as T,SANDBOX_INVOKE_PATH as m}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{S as g,a as c}from"./packem_shared/sandbox-budgets-DDvj4Orr.mjs";import{jsCodeTool as j}from"./packem_shared/jsCodeTool-CIlCK1bG.mjs";const i=T(m),f=e=>{if(e.op==="pdf")return"pdf";if(e.op==="screenshot")return e.type==="jpeg"?"jpeg":"png"},E=new Set(["bucket","path","root"]),S='Drive a headless browser: screenshot a page, render it to PDF, read its HTML content, or scrape it. Set `op` to "screenshot" | "pdf" | "content" | "scrape" and pass the target `url`.',y='Talk to a sandboxed container: `fetch` an HTTP path on it, or `exec` a command inside it. Set `op` to "fetch" (with `path`) or "exec" (with `command`).',A='Read and write files in a persistent sandbox filesystem. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',w='Read and write files on the sandboxed container\'s own disk — the same disk its commands run against. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',_="/workspace",p=e=>e.op==="write"||e.op==="rm",d=a({properties:{content:{description:"write: the file contents.",type:"string"},op:{description:"The filesystem operation to run.",enum:["ls","read","write","rm","stat"],type:"string"},path:{description:"The file or directory path, relative to the sandbox root.",type:"string"}},required:["op"],type:"object"}),N=a({properties:{fullPage:{description:"screenshot: capture the full scrollable page rather than just the viewport.",type:"boolean"},op:{description:"The browser operation to run.",enum:["screenshot","scrape","pdf","content"],type:"string"},selector:{description:"scrape: optional CSS selector hint to narrow the extraction.",type:"string"},type:{description:"screenshot: image encoding (default png).",enum:["png","jpeg"],type:"string"},url:{description:"The URL to operate on.",type:"string"}},required:["op","url"],type:"object"}),O=new Set(["DELETE","PATCH","POST","PUT"]),b=e=>e.op==="exec"||O.has((e.method??"GET").toUpperCase()),R=a({properties:{args:{description:"exec: command arguments.",items:{type:"string"},type:"array"},body:{description:"fetch: request body.",type:"string"},command:{description:"exec: the command to run.",type:"string"},method:{description:"fetch: HTTP method (default GET).",type:"string"},op:{description:"The container operation to run.",enum:["fetch","exec"],type:"string"},path:{description:"fetch: request path on the container (e.g. /health).",type:"string"}},required:["op"],type:"object"}),L=(e={})=>{const t=e.bucket!==void 0&&e.bucket.length>0?e.bucket:void 0;return{description:e.description??S,execute:async(o,n)=>{const r=f(o);if(r!==void 0&&t===void 0)return`Cannot run a "${o.op}": this browser tool has no \`bucket\` configured, so the render has nowhere to go. Use "content" or "scrape" for page text, or ask the operator to pass \`browserTool({ bucket })\`.`;const h=r===void 0?{}:{bucket:t,path:`${n.threadKey}/${n.toolCallId}.${r}`,...e.root===void 0?{}:{root:e.root}},u=Object.fromEntries(Object.entries(o).filter(([l])=>!E.has(l)));return await n.run(i,{...u,...h,kind:"browser"},{timeoutMs:g})},inputSchema:N,isLunoraAgentTool:!0,...e.needsApproval===void 0?{}:{needsApproval:e.needsApproval}}},k=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.needsApproval??b;return{description:t.description??y,execute:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"container",name:e},{timeoutMs:c}),inputSchema:R,isLunoraAgentTool:!0,needsApproval:o}},x=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: fsTool requires an R2 `bucket` binding name (the r2_bucket declared in wrangler.jsonc)");return{description:t.description??A,execute:(o,n)=>{const r=typeof t.root=="function"?t.root(n):t.root??"";return n.run(i,{...o,bucket:e,kind:"fs",root:r})},inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}},F=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerFsTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.root??_;if(!o.startsWith("/"))throw new s("INTERNAL",`@lunora/agent: containerFsTool \`root\` must be an absolute path inside the container (got "${o}")`);return{description:t.description??w,execute:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"containerFs",name:e,root:o},{timeoutMs:c}),inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}};export{L as browserTool,F as containerFsTool,k as containerTool,x as fsTool,j as jsCodeTool};
1
+ import{LunoraError as s}from"@lunora/errors";import{j as a}from"./packem_shared/json-schema-CHVg-SsJ.mjs";import{toFunctionReference as T,SANDBOX_INVOKE_PATH as m}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{S as g,a as c}from"./packem_shared/sandbox-budgets-DDvj4Orr.mjs";import{jsCodeTool as M}from"./packem_shared/jsCodeTool-Bh4jaeoy.mjs";const i=T(m),f=e=>{if(e.op==="pdf")return"pdf";if(e.op==="screenshot")return e.type==="jpeg"?"jpeg":"png"},E=new Set(["bucket","path","root"]),S='Drive a headless browser: screenshot a page, render it to PDF, read its HTML content, or scrape it. Set `op` to "screenshot" | "pdf" | "content" | "scrape" and pass the target `url`.',y='Talk to a sandboxed container: `fetch` an HTTP path on it, or `exec` a command inside it. Set `op` to "fetch" (with `path`) or "exec" (with `command`).',A='Read and write files in a persistent sandbox filesystem. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',w='Read and write files on the sandboxed container\'s own disk — the same disk its commands run against. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',_="/workspace",p=e=>e.op==="write"||e.op==="rm",d=a({properties:{content:{description:"write: the file contents.",type:"string"},op:{description:"The filesystem operation to run.",enum:["ls","read","write","rm","stat"],type:"string"},path:{description:"The file or directory path, relative to the sandbox root.",type:"string"}},required:["op"],type:"object"}),N=a({properties:{fullPage:{description:"screenshot: capture the full scrollable page rather than just the viewport.",type:"boolean"},op:{description:"The browser operation to run.",enum:["screenshot","scrape","pdf","content"],type:"string"},selector:{description:"scrape: optional CSS selector hint to narrow the extraction.",type:"string"},type:{description:"screenshot: image encoding (default png).",enum:["png","jpeg"],type:"string"},url:{description:"The URL to operate on.",type:"string"}},required:["op","url"],type:"object"}),O=new Set(["DELETE","PATCH","POST","PUT"]),b=e=>e.op==="exec"||O.has((e.method??"GET").toUpperCase()),R=a({properties:{args:{description:"exec: command arguments.",items:{type:"string"},type:"array"},body:{description:"fetch: request body.",type:"string"},command:{description:"exec: the command to run.",type:"string"},method:{description:"fetch: HTTP method (default GET).",type:"string"},op:{description:"The container operation to run.",enum:["fetch","exec"],type:"string"},path:{description:"fetch: request path on the container (e.g. /health).",type:"string"}},required:["op"],type:"object"}),L=(e={})=>{const t=e.bucket!==void 0&&e.bucket.length>0?e.bucket:void 0;return{description:e.description??S,execute:async(o,n)=>{const r=f(o);if(r!==void 0&&t===void 0)return`Cannot run a "${o.op}": this browser tool has no \`bucket\` configured, so the render has nowhere to go. Use "content" or "scrape" for page text, or ask the operator to pass \`browserTool({ bucket })\`.`;const h=r===void 0?{}:{bucket:t,path:`${n.threadKey}/${n.toolCallId}.${r}`,...e.root===void 0?{}:{root:e.root}},u=Object.fromEntries(Object.entries(o).filter(([l])=>!E.has(l)));return await n.run(i,{...u,...h,kind:"browser"},{timeoutMs:g})},inputSchema:N,isLunoraAgentTool:!0,...e.needsApproval===void 0?{}:{needsApproval:e.needsApproval}}},k=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.needsApproval??b;return{description:t.description??y,execute:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"container",name:e},{timeoutMs:c}),inputSchema:R,isLunoraAgentTool:!0,needsApproval:o}},x=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: fsTool requires an R2 `bucket` binding name (the r2_bucket declared in wrangler.jsonc)");return{description:t.description??A,execute:(o,n)=>{const r=typeof t.root=="function"?t.root(n):t.root??"";return n.run(i,{...o,bucket:e,kind:"fs",root:r})},inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}},F=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerFsTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.root??_;if(!o.startsWith("/"))throw new s("INTERNAL",`@lunora/agent: containerFsTool \`root\` must be an absolute path inside the container (got "${o}")`);return{description:t.description??w,execute:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"containerFs",name:e,root:o},{timeoutMs:c}),inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}};export{L as browserTool,F as containerFsTool,k as containerTool,x as fsTool,M as jsCodeTool};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/agent",
3
- "version": "1.0.0-alpha.275",
3
+ "version": "1.0.0-alpha.276",
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",
@@ -85,13 +85,13 @@
85
85
  },
86
86
  "dependencies": {
87
87
  "@ai-sdk/provider-utils": "5.0.53",
88
- "@lunora/ai": "1.0.0-alpha.163",
88
+ "@lunora/ai": "1.0.0-alpha.164",
89
89
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
90
- "@lunora/mail": "1.0.0-alpha.137",
91
- "@lunora/platform": "1.0.0-alpha.78",
92
- "@lunora/server": "1.0.0-alpha.264",
93
- "@lunora/values": "1.0.0-alpha.93",
94
- "@lunora/workflow": "1.0.0-alpha.109",
90
+ "@lunora/mail": "1.0.0-alpha.138",
91
+ "@lunora/platform": "1.0.0-alpha.79",
92
+ "@lunora/server": "1.0.0-alpha.265",
93
+ "@lunora/values": "1.0.0-alpha.94",
94
+ "@lunora/workflow": "1.0.0-alpha.110",
95
95
  "@modelcontextprotocol/sdk": "^1.32.0",
96
96
  "ai": "7.0.127",
97
97
  "yaml": "^2.9.1"
@@ -1 +0,0 @@
1
- import{jsonSchema as y}from"@ai-sdk/provider-utils";import{LunoraError as s}from"@lunora/errors";import{toFunctionReference as l,DEFAULT_AGENT_FUNCTION_PATHS as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const p=200,N=e=>{const t=typeof e=="object"&&e!==null?e.label:void 0;if(!(typeof t!="string"||t.trim().length===0))return[...t.trim()].slice(0,p).join("")};class g extends Error{code="SECRET_UNAVAILABLE";constructor(){super("the secret is no longer available: it expired, was already used by another tool call, or was never supplied"),this.name="SecretUnavailableError"}}const T=e=>{if(typeof e.description!="string"||e.description.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `description` (the model decides from it)");if(typeof e.consumer!="string"||e.consumer.length===0)throw new s("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `consumer`: the name of the one tool allowed to read the value");return{description:e.description,execute:()=>{throw new s("INTERNAL","@lunora/agent: requestSecretTool is resolved by the loop and must never be executed")},inputSchema:y({properties:{label:{description:"What the secret is for, shown to the person asked.",type:"string"}},required:["label"],type:"object"}),isLunoraAgentTool:!0,secretRequest:{consumer:e.consumer}}},w=(e,t)=>t instanceof Error?{...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name,stack:t.stack}:t,f=e=>{const t=new TextEncoder().encode(e),n=Array.from(t,r=>String.fromCodePoint(r)).join(""),a=btoa(n),o=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return[...new Set([a,a.replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),encodeURIComponent(e),o,JSON.stringify(e).slice(1,-1),e])]},h=(e,t)=>{if(t.length===0||e===void 0||typeof e=="function"||typeof e=="symbol")return!1;let n;try{n=JSON.stringify(e,w)}catch{return!1}return f(t).some(a=>n.includes(a))},E="[redacted]",u="@lunora/agent: withSecret's callback threw a value that is withheld, in case it carries the secret",c=(e,t)=>{if(t.length===0)return e;let n=e;for(const a of f(t).toSorted((o,r)=>r.length-o.length))n=n.split(a).join(E);return n},m=(e,t,n=new Set)=>{if(!(e instanceof Error))return new s("INTERNAL",u);if(n.has(e))return e;n.add(e);try{e.message=c(e.message,t),typeof e.stack=="string"&&(e.stack=c(e.stack,t));const a=e;for(const o of Object.getOwnPropertyNames(e)){if(o==="message"||o==="stack")continue;const r=a[o];if(r instanceof Error){const i=m(r,t,n);i!==r&&(a[o]=i)}else h(r,t)&&(a[o]=JSON.parse(c(JSON.stringify(r),t)))}}catch{return new s("INTERNAL",u)}return e},I=async(e,t,n)=>{const a=await e.step.do(`secret:consume:${e.idempotencyKey}:${t}`,async()=>{const o=await e.run(l(d.takeSecret),{claimant:e.idempotencyKey,consumerCallId:e.toolCallId,instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t});if(typeof o!="string")return{unavailable:!0};let r;try{r=await n(o)}catch(i){throw m(i,o)}return h(r,o)?{leaked:!0}:{result:r}});if("unavailable"in a)throw new g;if(await e.step.do(`secret:discard:${e.idempotencyKey}:${t}`,async()=>{await e.run(l(d.discardSecret),{instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t})}),"leaked"in a)throw new s("INTERNAL","@lunora/agent: withSecret's callback returned the secret, so its result was not recorded");return a.result};export{g as SecretUnavailableError,T as requestSecretTool,N as secretLabelOf,I as withSecret};
@@ -1 +0,0 @@
1
- import{jsonSchema as I}from"@ai-sdk/provider-utils";import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as L}from"@lunora/workflow";import{f as S}from"./fnv1a-BNN96GYb.mjs";import{r as b}from"./workflow-binding-Dm9hBzx_.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as $,DEFAULT_AGENT_FUNCTION_PATHS as P}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),x=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",k=t=>t!==null&&typeof t=="object"?t.output:void 0,C=async t=>{await new Promise(e=>{setTimeout(e,t)})},D=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=R(a);if(_.has(s))return{output:k(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},U=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},j=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},V=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??x,o=t.pollIntervalMs??M,a=t.wait??C,s=$(P.listMessages),T=async(y,r)=>{const p=(h(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=b(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,g=`sub-${e}-${S(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:g,params:A});l=await i.get(d.id)}catch(d){if(!L(d))throw d;l=await i.get(g)}const{output:v,status:u}=await D(l,m,o,a);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(U(v)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const E=await r.run(s,{key:f});return j(E)};return{description:t.description,execute:T,inputSchema:I({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{V as agentAsTool};
@@ -1 +0,0 @@
1
- import{jsonSchema as y,asSchema as w}from"@ai-sdk/provider-utils";import{LunoraError as a}from"@lunora/errors";import{i as v}from"./positive-integer-ztHqqpBk.mjs";import{M as A,c as T}from"./tool-output-Cmk3JWMG.mjs";const g=16,$=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=A?e:T(o)},S=(e,o)=>{let t=e;for(const n of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,n))return;t=t[n]}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(!Object.hasOwn(o,r))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?S(o[r],t.$path):o[r]}const n={};for(const[r,i]of Object.entries(t))r!=="__proto__"&&(n[r]=l(i,o));return n},b=async(e,o,t)=>{const{validate:n}=w(o.inputSchema);if(n===void 0)return t;const r=await n(t);if(r.success)return r.value;throw new a("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${r.error.message}`)},E=async(e,o,t,n)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>n)throw new a("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(n)}. Split it across several code calls.`);const i={},p=[],d=new Set;for(const s of r){if(d.has(s.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${s.id}" — each step id must be unique (later steps reference an output by id via $from)`);d.add(s.id)}for(const s of r){const c=Object.hasOwn(o,s.tool)?o[s.tool]:void 0;if(!c)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${s.tool}" (available: ${Object.keys(o).join(", ")})`);const m=await b(s,c,l(s.input??{},i)),u={...t,idempotencyKey:`${t.idempotencyKey}:${s.id}`,toolCallId:`${t.toolCallId}:${s.id}`},h=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,h);i[s.id]=f,p.push({id:s.id,output:$(f)})}return{final:p.at(-1)?.output,results:p}},O=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("; ")}.`,_=y({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"}),N=(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\`.`);if(i.secretRequest!==void 0)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it is a requestSecretTool, which a code-mode script can't pause for the owner to supply. Expose it as a normal top-level tool.`)}if(o.maxSteps!==void 0&&!v(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const n=o.maxSteps??g;return{description:o.description??O(e),execute:(r,i)=>E(r,e,i,n),inputSchema:_,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{N as codeTool,l as resolveReferences,E as runToolScript};
@@ -1 +0,0 @@
1
- import{jsonSchema as u}from"@ai-sdk/provider-utils";import{toFunctionReference as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const h=240,m=50,y=(t,s)=>t.length<=s?t:`${t.slice(0,s)}…`,f=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(m,Math.max(1,Math.trunc(t)))},g=(t,s)=>{const r=t??{},i=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:y(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},S=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"}),A=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),b=(t,s,r)=>{const i=d(s),e=Math.max(1,t.snippetChars??h),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,p)=>{const a=f(n.topK)??o,l=await p.run(i,{query:n.query,...a===void 0?{}:{topK:a}});return g(l,e)},inputSchema:S,isLunoraAgentTool:!0}},T=t=>{const s=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,i)=>i.run(s,{id:r.id}),inputSchema:A,isLunoraAgentTool:!0}},k=(t,s)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of s)e.knowledge&&r.push({key:e.name,...e.knowledge});const i={};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}`,c=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=b(e,e.source,n?c:void 0),n&&(i[c]=T(e.read))}return i};export{k as collectAgenticMemoryTools,g as toSearchResults};
@@ -1,3 +0,0 @@
1
- import{jsonSchema as O}from"@ai-sdk/provider-utils";import{usageStatus as j}from"@lunora/ai/create";import{LunoraError as P}from"@lunora/errors";import{r as R}from"./agent-ai-CP87uSoZ.mjs";import{F as v,s as b}from"./common-DBc9y7Np.mjs";const m=e=>({...e,status:j(e)}),k=e=>m(b(e)),x=e=>e.map(t=>{const o={id:t.toolCallId,input:t.input,name:t.toolName};return t.invalid!==!0?o:{...o,invalid:t.error instanceof Error?t.error.message:String(t.error)}}),h=(e,t)=>{if(typeof e=="function")return e(t);if(typeof e=="string"){const o=R(t);if(!o)throw new P("INTERNAL",`@lunora/agent: the agent model "${e}" 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(e)}return e};let T;const f=()=>(T??=import("ai").catch(e=>{throw T=void 0,e}),T),q=(e,t,o)=>{const r=h(t.model,o),n={};for(const[a,u]of Object.entries(t.tools??{}))n[a]=e.tool({description:u.description,inputSchema:e.asSchema(u.inputSchema)});const i=t.output===void 0?void 0:e.Output.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:r,output:i,staticSettings:s,tools:n}},E=(e,t)=>{let o;return()=>(o??=f().then(r=>({ai:r,base:q(r,e,t)})).catch(r=>{throw o=void 0,r}),o)},S=(e,{activeTools:t,messages:o,model:r,signal:n,toolChoice:i})=>{const{defaultModel:s,output:a,staticSettings:u,tools:l}=e,d=t===void 0?l:Object.fromEntries(Object.entries(l).filter(([g])=>t.includes(g)));return{messages:o,model:r??s,...u,...Object.keys(d).length>0?{tools:d}:{},...i===void 0?{}:{toolChoice:i},...a===void 0?{}:{output:a},...n===void 0?{}:{abortSignal:n}}},M=e=>e instanceof Error?e:new Error(`model stream failed: ${String(e)}`,{cause:e}),N=e=>({inputTokens:{cacheRead:e?.inputTokens?.cacheRead,cacheWrite:e?.inputTokens?.cacheWrite,noCache:void 0,total:e?.inputTokens?.total},outputTokens:{reasoning:e?.outputTokens?.reasoning,text:void 0,total:e?.outputTokens?.total}}),_=e=>{if(e===void 0)return m(void 0);const t=e.inputTokens?.total,o=e.outputTokens?.total,r=t===void 0||o===void 0?void 0:t+o;return m(b({inputTokens:t,inputTokenDetails:{cacheReadTokens:e.inputTokens?.cacheRead,cacheWriteTokens:e.inputTokens?.cacheWrite},outputTokens:o,outputTokenDetails:{reasoningTokens:e.outputTokens?.reasoning},totalTokens:r}))},y=(e,t)=>{const o=new Error(e.raw===void 0?"model finished with an error reason":`model finished with an error reason (provider reason: ${e.raw})`,{cause:e});return o[v]=_(t),o},B=e=>{if(!(typeof e!="object"||e===null))return e[v]},I=(e,t)=>e.wrapLanguageModel({middleware:{wrapGenerate:async({doGenerate:o})=>{const r=await o();if(r.finishReason.unified==="error")throw y(r.finishReason,r.usage);return r},wrapStream:async({doStream:o})=>{const{stream:r,...n}=await o();let i=!1;return{...n,stream:r.pipeThrough(new TransformStream({flush:s=>{i||s.enqueue({error:new Error("model stream ended without a finish part"),type:"error"})},transform:(s,a)=>{if(s.type==="finish"&&(i=!0,s.finishReason.unified==="error")){a.enqueue({...s,usage:N(s.usage)}),a.enqueue({error:y(s.finishReason,s.usage),type:"error"});return}a.enqueue(s)}}))}}},model:t}),p=(e,t)=>typeof t=="string"?t:I(e,t),H=(e,t)=>{const o=E(e,t);return async r=>{const{ai:n,base:i}=await o(),s=S(i,r),a=await n.generateText({...s,model:p(n,s.model)});return{text:a.text,toolCalls:x(a.toolCalls),usage:k(a.usage),...i.output===void 0?{}:{output:a.output}}}},X=(e,t)=>{const o=E(e,t);return async(r,n)=>{const{ai:i,base:s}=await o(),a=S(s,r),u=i.streamText({...a,model:p(i,a.model)});let l="";try{for await(const c of u.stream){if(c.type==="error")throw M(c.error);c.type==="text-delta"&&(l+=c.text,n(c.text))}}catch(c){if(!r.signal?.aborted)throw c}if(r.signal?.aborted)return{text:l,toolCalls:[],usage:m(void 0)};const[d,g,A,C]=await Promise.all([u.text,u.toolCalls,u.usage,s.output===void 0?Promise.resolve(void 0):u.output]);return{text:d,toolCalls:x(g),usage:k(A),...s.output===void 0?{}:{output:C}}}},U=O({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"}),$=(e,t)=>["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: ${e}`,"",`Assistant: ${t}`].join(`
2
- `),J=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{output:i}=await n.generateText({model:p(n,h(o,t)),output:n.Output.object({schema:U}),prompt:$(r,e)});return i},G=(e,t)=>["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: ${e}`,"",`Assistant: ${t}`].join(`
3
- `),K=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{text:i}=await n.generateText({model:p(n,h(o,t)),prompt:G(r,e)});return{summary:i.trim()}},w="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.",W=" An existing brief of the earlier conversation is included above. UPDATE that brief: keep every still-relevant fact from it and fold in the newly aged-out messages. Do not replace it with a summary of only the new messages.",Q=()=>async({env:e,messages:t,model:o,previousSummary:r})=>{const n=await f(),{text:i}=await n.generateText({messages:t,model:p(n,h(o,e)),system:r===void 0?w:`${w}${W}`});return i.trim()};export{H as createAgentGenerate,Q as createCompact,K as createEpisodeExtract,J as createGraphExtract,X as createStreamGenerate,h as resolveAgentModel,B as usageOfFailedTurn};
@@ -1 +0,0 @@
1
- import{jsonSchema as c}from"@ai-sdk/provider-utils";import{LunoraError as h}from"@lunora/errors";import{r as u}from"./agent-ai-CP87uSoZ.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=c({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 h&&E.has(e.code))return`Web search failed: ${e.message}`;throw e}},inputSchema:m,isLunoraAgentTool:!0}};export{T as webSearchTool};