@lunora/agent 1.0.0-alpha.155 → 1.0.0-alpha.157

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 (35) hide show
  1. package/dist/channels.d.mts +13 -5
  2. package/dist/channels.d.ts +13 -5
  3. package/dist/channels.mjs +1 -1
  4. package/dist/inbound.d.mts +3 -3
  5. package/dist/inbound.d.ts +3 -3
  6. package/dist/inbound.mjs +1 -1
  7. package/dist/index.d.mts +12 -6
  8. package/dist/index.d.ts +12 -6
  9. package/dist/index.mjs +1 -1
  10. package/dist/naming.d.mts +3 -7
  11. package/dist/naming.d.ts +3 -7
  12. package/dist/naming.mjs +1 -1
  13. package/dist/packem_shared/{VoiceSessionDO-BkPBpwRR.mjs → VoiceSessionDO-Dc09ClZz.mjs} +1 -1
  14. package/dist/packem_shared/agent-loop-CQUKMFWA.mjs +3 -0
  15. package/dist/packem_shared/agentAsTool-1Gwq45M3.mjs +1 -0
  16. package/dist/packem_shared/{compileAgentWorkflow-D3BN5OWk.mjs → compileAgentWorkflow-Dijgn4Cz.mjs} +1 -1
  17. package/dist/packem_shared/createAgentContext-D3mf7LEU.mjs +1 -0
  18. package/dist/packem_shared/{defineAgent-uEeT0WuM.mjs → defineAgent-CK3CpiOr.mjs} +1 -1
  19. package/dist/packem_shared/runAgentLoop-DFDJPAyk.mjs +1 -0
  20. package/dist/packem_shared/{runVoiceTurn-Bs47Kfx2.mjs → runVoiceTurn-xFvfDZ2Q.mjs} +1 -1
  21. package/dist/packem_shared/{types.d-DS2wmzMe.d.mts → types.d-CbYtFBw9.d.mts} +7 -4
  22. package/dist/packem_shared/{types.d-DS2wmzMe.d.ts → types.d-CbYtFBw9.d.ts} +7 -4
  23. package/dist/packem_shared/{voice-turn-7a1NoDHS.mjs → voice-turn-BiDZeZwp.mjs} +1 -1
  24. package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
  25. package/dist/reply.d.mts +1 -1
  26. package/dist/reply.d.ts +1 -1
  27. package/dist/sandbox.d.mts +1 -1
  28. package/dist/sandbox.d.ts +1 -1
  29. package/dist/skill-markdown.d.mts +1 -1
  30. package/dist/skill-markdown.d.ts +1 -1
  31. package/package.json +7 -7
  32. package/dist/packem_shared/agent-loop-CR27O7MC.mjs +0 -3
  33. package/dist/packem_shared/agentAsTool-CgZb6ycK.mjs +0 -1
  34. package/dist/packem_shared/createAgentContext-BVy7RzqD.mjs +0 -1
  35. package/dist/packem_shared/runAgentLoop-Dg1GXqsX.mjs +0 -1
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-DS2wmzMe.mjs";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-DS2wmzMe.mjs";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-CbYtFBw9.mjs";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
@@ -54,14 +54,22 @@ declare const verifyDiscord: (options: {
54
54
  interface AgentChannelTarget {
55
55
  /** The agent definition — only its `onInbound` config is read. */
56
56
  agent: Pick<AgentDefinition, "onInbound">;
57
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
58
- binding: string;
57
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
58
+ className: string;
59
59
  }
60
60
  /**
61
61
  * The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
62
62
  * @experimental
63
63
  */
64
- type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
64
+ /**
65
+ * A Worker `fetch`-shaped handler. The Worker `ctx` is required: on Cloudflare
66
+ * the agent is reached as `ctx.exports.<Class>`, so a handler mounted without it
67
+ * could never start a run (from an `httpRouter` route: `handler(c.req.raw,
68
+ * c.env, c.executionCtx)`).
69
+ */
70
+ type InboundChannelHandler = (request: Request, env: Record<string, unknown>, context: {
71
+ exports?: unknown;
72
+ }) => Promise<Response>;
65
73
  /**
66
74
  * Build an HTTP handler that starts a durable agent run from a verified inbound
67
75
  * webhook. The channel is detected from the signature headers; EACH eligible
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-DS2wmzMe.js";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-DS2wmzMe.js";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.js";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-CbYtFBw9.js";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
@@ -54,14 +54,22 @@ declare const verifyDiscord: (options: {
54
54
  interface AgentChannelTarget {
55
55
  /** The agent definition — only its `onInbound` config is read. */
56
56
  agent: Pick<AgentDefinition, "onInbound">;
57
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
58
- binding: string;
57
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
58
+ className: string;
59
59
  }
60
60
  /**
61
61
  * The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
62
62
  * @experimental
63
63
  */
64
- type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
64
+ /**
65
+ * A Worker `fetch`-shaped handler. The Worker `ctx` is required: on Cloudflare
66
+ * the agent is reached as `ctx.exports.<Class>`, so a handler mounted without it
67
+ * could never start a run (from an `httpRouter` route: `handler(c.req.raw,
68
+ * c.env, c.executionCtx)`).
69
+ */
70
+ type InboundChannelHandler = (request: Request, env: Record<string, unknown>, context: {
71
+ exports?: unknown;
72
+ }) => Promise<Response>;
65
73
  /**
66
74
  * Build an HTTP handler that starts a durable agent run from a verified inbound
67
75
  * webhook. The channel is detected from the signature headers; EACH eligible
package/dist/channels.mjs CHANGED
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{isDuplicateInstanceError as E}from"@lunora/workflow";import{h as A,B as R}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{f as k}from"./packem_shared/fnv1a-BNN96GYb.mjs";const m=300,N=/[^0-9a-f]/iu,S=new TextEncoder,u=t=>new Uint8Array(S.encode(t)),l=t=>{if(t.length%2!==0||N.test(t))throw new g("BAD_REQUEST","@lunora/agent: malformed hex signature");const e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n+=1)e[n]=Number.parseInt(t.slice(n*2,n*2+2),16);return e},v=async(t,e,n)=>{try{const r=await crypto.subtle.importKey("raw",u(t),{hash:"SHA-256",name:"HMAC"},!1,["verify"]);return await crypto.subtle.verify("HMAC",r,l(n),u(e))}catch{return!1}},b=(t,e,n)=>Number.isFinite(t)&&Math.abs(e-t)<=n,x=async t=>{const{body:e,now:n=Date.now()/1e3,signature:r,signingSecret:a,timestamp:s,tolerance:o=m}=t;return!r||!s||!r.startsWith("v0=")||!b(Number(s),n,o)?!1:v(a,`v0:${s}:${e}`,r.slice(3))},T=async t=>{const{body:e,secret:n,signature:r}=t;return r?.startsWith("sha256=")?v(n,e,r.slice(7)):!1},C=async t=>{const{body:e,now:n=Date.now()/1e3,publicKey:r,signature:a,timestamp:s,tolerance:o=m}=t;if(!a||!s||!b(Number(s),n,o))return!1;try{const c=await crypto.subtle.importKey("raw",l(r),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},c,l(a),u(s+e))}catch{return!1}},H=t=>{if(t.has("x-slack-signature"))return"slack";if(t.has("x-hub-signature-256"))return"github";if(t.has("x-signature-ed25519"))return"discord"},I=(t,e)=>{if(typeof t=="function")return t(e);const n=e[t];return typeof n=="string"?n:void 0},_=async(t,e,n,r)=>{switch(t){case"discord":return C({body:r,publicKey:e,signature:n.get("x-signature-ed25519")??void 0,timestamp:n.get("x-signature-timestamp")??void 0});case"github":return T({body:r,secret:e,signature:n.get("x-hub-signature-256")??void 0});case"slack":return x({body:r,signature:n.get("x-slack-signature")??void 0,signingSecret:e,timestamp:n.get("x-slack-request-timestamp")??void 0});default:return!1}},B=(t,e)=>{if(t==="discord")try{if(JSON.parse(e).type===1)return Response.json({type:1})}catch{}},w=()=>new Response(void 0,{status:200}),D=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",u(t)))].map(e=>e.toString(16).padStart(2,"0")).join(""),M=async(t,e)=>{if(t!=="github")try{const n=JSON.parse(e),r=t==="slack"?n.event_id:n.id;if(typeof r=="string"&&r!=="")return r}catch{}return D(e)},U=async(t,e,n,r)=>{if(A(e))throw new g("BAD_REQUEST",`@lunora/agent: inbound channel run params ${R}`);try{await t.create({id:`${n}-${k(r)}`,params:e})}catch(a){if(E(a))return w();throw a}return w()},J=t=>async(e,n)=>{const r=await e.text(),a=H(e.headers);if(a===void 0)return new Response("Unrecognized webhook",{status:400});const s=t.map(i=>({config:i.agent.onInbound,target:i})).filter(i=>i.config?.channel===a),o={channel:a,headers:e.headers,json:()=>JSON.parse(r),rawBody:r};let c=!1;for(const{config:i,target:d}of s){const y=I(i.secret,n);if(y===void 0||!await _(a,y,e.headers,r))continue;c=!0;const p=B(a,r);if(p)return p;const h=await i.map(o);if(!h)continue;const f=n[d.binding];if(!f||typeof f.create!="function")throw new g("INTERNAL",`@lunora/agent: no Workflow binding "${d.binding}" on env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`);return await U(f,h,a,await M(a,r))}return c?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{J as dispatchAgentChannel,C as verifyDiscord,T as verifyGithub,x as verifySlack};
1
+ import{LunoraError as l}from"@lunora/errors";import{isDuplicateInstanceError as A}from"@lunora/workflow";import{h as x,B as N}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{f as R}from"./packem_shared/fnv1a-BNN96GYb.mjs";import{r as k}from"./packem_shared/workflow-binding-Dm9hBzx_.mjs";const v=300,S=/[^0-9a-f]/iu,T=new TextEncoder,c=t=>new Uint8Array(T.encode(t)),f=t=>{if(t.length%2!==0||S.test(t))throw new l("BAD_REQUEST","@lunora/agent: malformed hex signature");const e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n+=1)e[n]=Number.parseInt(t.slice(n*2,n*2+2),16);return e},b=async(t,e,n)=>{try{const r=await crypto.subtle.importKey("raw",c(t),{hash:"SHA-256",name:"HMAC"},!1,["verify"]);return await crypto.subtle.verify("HMAC",r,f(n),c(e))}catch{return!1}},E=(t,e,n)=>Number.isFinite(t)&&Math.abs(e-t)<=n,H=async t=>{const{body:e,now:n=Date.now()/1e3,signature:r,signingSecret:a,timestamp:s,tolerance:i=v}=t;return!r||!s||!r.startsWith("v0=")||!E(Number(s),n,i)?!1:b(a,`v0:${s}:${e}`,r.slice(3))},C=async t=>{const{body:e,secret:n,signature:r}=t;return r?.startsWith("sha256=")?b(n,e,r.slice(7)):!1},I=async t=>{const{body:e,now:n=Date.now()/1e3,publicKey:r,signature:a,timestamp:s,tolerance:i=v}=t;if(!a||!s||!E(Number(s),n,i))return!1;try{const u=await crypto.subtle.importKey("raw",f(r),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},u,f(a),c(s+e))}catch{return!1}},_=t=>{if(t.has("x-slack-signature"))return"slack";if(t.has("x-hub-signature-256"))return"github";if(t.has("x-signature-ed25519"))return"discord"},B=(t,e)=>{if(typeof t=="function")return t(e);const n=e[t];return typeof n=="string"?n:void 0},D=async(t,e,n,r)=>{switch(t){case"discord":return I({body:r,publicKey:e,signature:n.get("x-signature-ed25519")??void 0,timestamp:n.get("x-signature-timestamp")??void 0});case"github":return C({body:r,secret:e,signature:n.get("x-hub-signature-256")??void 0});case"slack":return H({body:r,signature:n.get("x-slack-signature")??void 0,signingSecret:e,timestamp:n.get("x-slack-request-timestamp")??void 0});default:return!1}},M=(t,e)=>{if(t==="discord")try{if(JSON.parse(e).type===1)return Response.json({type:1})}catch{}},w=()=>new Response(void 0,{status:200}),U=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",c(t)))].map(e=>e.toString(16).padStart(2,"0")).join(""),O=async(t,e)=>{if(t!=="github")try{const n=JSON.parse(e),r=t==="slack"?n.event_id:n.id;if(typeof r=="string"&&r!=="")return r}catch{}return U(e)},$=async(t,e,n,r)=>{if(x(e))throw new l("BAD_REQUEST",`@lunora/agent: inbound channel run params ${N}`);try{await t.create({id:`${n}-${R(r)}`,params:e})}catch(a){if(A(a))return w();throw a}return w()},W=t=>async(e,n,r)=>{const a=await e.text(),s=_(e.headers);if(s===void 0)return new Response("Unrecognized webhook",{status:400});const i=t.map(o=>({config:o.agent.onInbound,target:o})).filter(o=>o.config?.channel===s),u={channel:s,headers:e.headers,json:()=>JSON.parse(a),rawBody:a};let d=!1;for(const{config:o,target:g}of i){const p=B(o.secret,n);if(p===void 0||!await D(s,p,e.headers,a))continue;d=!0;const y=M(s,a);if(y)return y;const h=await o.map(u);if(!h)continue;const m=k(n,r.exports,g.className,["create"]);if(m===void 0)throw new l("INTERNAL",`@lunora/agent: no "${g.className}" on ctx.exports or env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`);return await $(m,h,s,await O(s,a))}return d?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{W as dispatchAgentChannel,I as verifyDiscord,C as verifyGithub,H as verifySlack};
@@ -1,4 +1,4 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-DS2wmzMe.mjs";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -11,8 +11,8 @@ interface AgentEmailTarget {
11
11
  * this agent claims the message and, if so, the run to start.
12
12
  */
13
13
  agent: Pick<AgentDefinition, "onEmail">;
14
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
15
- binding: string;
14
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
15
+ className: string;
16
16
  }
17
17
  /**
18
18
  * The worker `email(message, env, ctx)` callback. Typed with `unknown`
package/dist/inbound.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-DS2wmzMe.js";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.js";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -11,8 +11,8 @@ interface AgentEmailTarget {
11
11
  * this agent claims the message and, if so, the run to start.
12
12
  */
13
13
  agent: Pick<AgentDefinition, "onEmail">;
14
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
15
- binding: string;
14
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
15
+ className: string;
16
16
  }
17
17
  /**
18
18
  * The worker `email(message, env, ctx)` callback. Typed with `unknown`
package/dist/inbound.mjs CHANGED
@@ -1 +1 @@
1
- import{createInboundEmailHandler as u,authenticatesFrom as d,parseInboundEmail as g}from"@lunora/mail/inbound";import{h as l,B as m}from"./packem_shared/branch-marker-boZ00zmk.mjs";const f="message could not be processed",c=(r,o)=>{console.error("@lunora/agent/inbound: bouncing message —",o),r.message.setReject(f)},b=r=>{const o=u({dispatch:async(t,n)=>{for(const e of r){const s=e.agent.onEmail;if(!s)continue;const a=await s(t);if(a==null)continue;const i=n.env[e.binding];if(!i||typeof i.create!="function"){c(n,`@lunora/agent: no Workflow binding "${e.binding}" on env for an inbound agent — run codegen/dev so wrangler.jsonc declares it`);return}if(l(a)){c(n,`@lunora/agent: inbound run params ${m}`);return}await i.create({params:a});return}},parse:g,verify:d});return async(t,n,e)=>o(t,n,e)};export{b as dispatchAgentEmail};
1
+ import{createInboundEmailHandler as l,authenticatesFrom as u,parseInboundEmail as m}from"@lunora/mail/inbound";import{h as d,B as p}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{r as g}from"./packem_shared/workflow-binding-Dm9hBzx_.mjs";const f="message could not be processed",i=(a,o)=>{console.error("@lunora/agent/inbound: bouncing message —",o),a.message.setReject(f)},h=a=>{const o=l({dispatch:async(s,n)=>{for(const e of a){const t=e.agent.onEmail;if(!t)continue;const r=await t(s);if(r==null)continue;const c=g(n.env,n.ctx?.exports,e.className,["create"]);if(c===void 0){i(n,`@lunora/agent: no "${e.className}" on ctx.exports or env for an inbound agent — run codegen/dev so wrangler.jsonc declares it`);return}if(d(r)){i(n,`@lunora/agent: inbound run params ${p}`);return}await c.create({params:r});return}},parse:m,verify:u});return async(s,n,e)=>o(s,n,e)};export{h as dispatchAgentEmail};
package/dist/index.d.mts CHANGED
@@ -1,9 +1,9 @@
1
- import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-DS2wmzMe.mjs";
2
- export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-DS2wmzMe.mjs";
1
+ import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
+ export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-CbYtFBw9.mjs";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
5
  export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerTool, fsTool, jsCodeTool } from "./sandbox.mjs";
6
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
6
+ export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
7
7
  import { createAi } from '@lunora/ai';
8
8
  import { WorkflowDefinition } from '@lunora/workflow';
9
9
  import '@lunora/mail/inbound';
@@ -23,6 +23,8 @@ interface AgentLoopOptions {
23
23
  env: Record<string, unknown>;
24
24
  /** The agent's `lunora/agents.ts` export name (thread attribution). */
25
25
  exportName: string;
26
+ /** The invoking context's `ctx.exports`, where Cloudflare exposes this and sibling agents. */
27
+ exports?: unknown;
26
28
  /**
27
29
  * The run-end episode-summary seam — production wires AI SDK `generateText`.
28
30
  * Absent (the default) disables episode recording, so an agent with no
@@ -269,8 +271,9 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
269
271
  /**
270
272
  * Build the `ctx.agents` producer surface from the codegen-emitted spec list
271
273
  * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
272
- * declared agent resolves its `AGENT_*` Workflow binding off `env` lazily, so
273
- * a missing binding only errors when that agent is actually started.
274
+ * declared agent resolves by its export key (the generated class name) off the
275
+ * invoking context's `exports` — or `env`, on a host without workflow exports —
276
+ * lazily, so a missing agent only errors when it is actually started.
274
277
  *
275
278
  * `cancel` also needs to write the thread's status, so it dispatches the agent
276
279
  * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
@@ -279,7 +282,10 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
279
282
  * inject a `dispatch` double.
280
283
  * @experimental
281
284
  */
282
- declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, dispatch?: AgentRunFunction) => Record<string, AgentHandle>;
285
+ declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
286
+ dispatch?: AgentRunFunction;
287
+ exports?: unknown;
288
+ }) => Record<string, AgentHandle>;
283
289
  /**
284
290
  * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
285
291
  * (each LLM turn and each tool call a named durable step; thread messages
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-DS2wmzMe.js";
2
- export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-DS2wmzMe.js";
1
+ import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-CbYtFBw9.js";
2
+ export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-CbYtFBw9.js";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
4
4
  import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
5
5
  export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerTool, fsTool, jsCodeTool } from "./sandbox.js";
6
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
6
+ export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
7
7
  import { createAi } from '@lunora/ai';
8
8
  import { WorkflowDefinition } from '@lunora/workflow';
9
9
  import '@lunora/mail/inbound';
@@ -23,6 +23,8 @@ interface AgentLoopOptions {
23
23
  env: Record<string, unknown>;
24
24
  /** The agent's `lunora/agents.ts` export name (thread attribution). */
25
25
  exportName: string;
26
+ /** The invoking context's `ctx.exports`, where Cloudflare exposes this and sibling agents. */
27
+ exports?: unknown;
26
28
  /**
27
29
  * The run-end episode-summary seam — production wires AI SDK `generateText`.
28
30
  * Absent (the default) disables episode recording, so an agent with no
@@ -269,8 +271,9 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
269
271
  /**
270
272
  * Build the `ctx.agents` producer surface from the codegen-emitted spec list
271
273
  * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
272
- * declared agent resolves its `AGENT_*` Workflow binding off `env` lazily, so
273
- * a missing binding only errors when that agent is actually started.
274
+ * declared agent resolves by its export key (the generated class name) off the
275
+ * invoking context's `exports` — or `env`, on a host without workflow exports —
276
+ * lazily, so a missing agent only errors when it is actually started.
274
277
  *
275
278
  * `cancel` also needs to write the thread's status, so it dispatches the agent
276
279
  * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
@@ -279,7 +282,10 @@ declare const codeTool: (tools: Record<string, AnyAgentTool>, options?: CodeTool
279
282
  * inject a `dispatch` double.
280
283
  * @experimental
281
284
  */
282
- declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, dispatch?: AgentRunFunction) => Record<string, AgentHandle>;
285
+ declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
286
+ dispatch?: AgentRunFunction;
287
+ exports?: unknown;
288
+ }) => Record<string, AgentHandle>;
283
289
  /**
284
290
  * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
285
291
  * (each LLM turn and each tool call a named durable step; thread messages
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{r as t,s as r}from"./packem_shared/agent-loop-CR27O7MC.mjs";import{collectAgenticMemoryTools as a,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as l}from"./packem_shared/agentAsTool-CgZb6ycK.mjs";import{codeTool as m}from"./packem_shared/codeTool-BQb-K3my.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-BVy7RzqD.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-uEeT0WuM.mjs";import{functionTool as D}from"./packem_shared/functionTool-D3CP4f8-.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BOILDUZj.mjs";import{jsCodeTool as F}from"./packem_shared/jsCodeTool-BLOvjXGF.mjs";import{adaptMcpResult as U,mcpTools as k}from"./packem_shared/adaptMcpResult-CVlq-_TO.mjs";import{buildModelMessages as R}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentBindingName as b,agentClassName as h,agentDefaultName as w,voiceBindingName as H,voiceClassName as I}from"./naming.mjs";import{AGENT_MODULE as X,DEFAULT_AGENT_FUNCTION_PATHS as j,SANDBOX_INVOKE_PATH as y,SANDBOX_MODULE as K,toFunctionReference as W}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{browserTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{defineSkill as Z,isSkillDefinition as $}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as oe}from"./packem_shared/VoiceSessionDO-BkPBpwRR.mjs";import{r as re}from"./packem_shared/voice-turn-7a1NoDHS.mjs";import{default as ae}from"./packem_shared/compileAgentWorkflow-D3BN5OWk.mjs";export{X as AGENT_MODULE,j as DEFAULT_AGENT_FUNCTION_PATHS,y as SANDBOX_INVOKE_PATH,K as SANDBOX_MODULE,oe as VoiceSessionDO,U as adaptMcpResult,l as agentAsTool,b as agentBindingName,h as agentClassName,c as agentComponent,w as agentDefaultName,x as agentExtension,z as browserTool,R as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,ae as compileAgentWorkflow,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,d as defineAgent,u as defineAgentTool,Z as defineSkill,Q as fsTool,D as functionTool,N as isAgentDefinition,$ as isSkillDefinition,F as jsCodeTool,k as mcpTools,G as resolveAgentModel,t as runAgentLoop,re as runVoiceTurn,r as splitForCompaction,W as toFunctionReference,f as toSearchResults,H as voiceBindingName,I as voiceClassName};
1
+ import{r as t,s as r}from"./packem_shared/agent-loop-CQUKMFWA.mjs";import{collectAgenticMemoryTools as a,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-1Gwq45M3.mjs";import{codeTool as m}from"./packem_shared/codeTool-BQb-K3my.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as T}from"./packem_shared/createAgentContext-D3mf7LEU.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-CK3CpiOr.mjs";import{functionTool as D}from"./packem_shared/functionTool-D3CP4f8-.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BOILDUZj.mjs";import{jsCodeTool as L}from"./packem_shared/jsCodeTool-BLOvjXGF.mjs";import{adaptMcpResult as k,mcpTools as v}from"./packem_shared/adaptMcpResult-CVlq-_TO.mjs";import{buildModelMessages as R}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as b,agentDefaultName as h,voiceBindingName as w,voiceClassName as H}from"./naming.mjs";import{AGENT_MODULE as P,DEFAULT_AGENT_FUNCTION_PATHS as X,SANDBOX_INVOKE_PATH as j,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{browserTool as q,containerTool as z,fsTool as J}from"./sandbox.mjs";import{defineSkill as Y,isSkillDefinition as Z}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as ee}from"./packem_shared/VoiceSessionDO-Dc09ClZz.mjs";import{r as te}from"./packem_shared/voice-turn-BiDZeZwp.mjs";import{default as ne}from"./packem_shared/compileAgentWorkflow-Dijgn4Cz.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,ee as VoiceSessionDO,k as adaptMcpResult,s as agentAsTool,b as agentClassName,c as agentComponent,h as agentDefaultName,x as agentExtension,q as browserTool,R as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,ne as compileAgentWorkflow,z as containerTool,T as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,d as defineAgent,u as defineAgentTool,Y as defineSkill,J as fsTool,D as functionTool,N as isAgentDefinition,Z as isSkillDefinition,L as jsCodeTool,v as mcpTools,G as resolveAgentModel,t as runAgentLoop,te as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,f as toSearchResults,w as voiceBindingName,H as voiceClassName};
package/dist/naming.d.mts CHANGED
@@ -1,13 +1,9 @@
1
1
  /**
2
- * `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name.
2
+ * `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name,
3
+ * and the agent's key at runtime: `ctx.exports.SupportAgentWorkflow` on Cloudflare.
3
4
  * @experimental
4
5
  */
5
6
  declare const agentClassName: (exportName: string) => string;
6
- /**
7
- * `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
8
- * @experimental
9
- */
10
- declare const agentBindingName: (exportName: string) => string;
11
7
  /**
12
8
  * `supportBot` → `agent-support-bot` — the default deployed workflow name.
13
9
  * @experimental
@@ -27,4 +23,4 @@ declare const voiceClassName: (exportName: string) => string;
27
23
  * @experimental
28
24
  */
29
25
  declare const voiceBindingName: (exportName: string) => string;
30
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
26
+ export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
package/dist/naming.d.ts CHANGED
@@ -1,13 +1,9 @@
1
1
  /**
2
- * `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name.
2
+ * `support` → `SupportAgentWorkflow` — the generated WorkflowEntrypoint class name,
3
+ * and the agent's key at runtime: `ctx.exports.SupportAgentWorkflow` on Cloudflare.
3
4
  * @experimental
4
5
  */
5
6
  declare const agentClassName: (exportName: string) => string;
6
- /**
7
- * `support` → `AGENT_SUPPORT` — the Cloudflare Workflows binding name.
8
- * @experimental
9
- */
10
- declare const agentBindingName: (exportName: string) => string;
11
7
  /**
12
8
  * `supportBot` → `agent-support-bot` — the default deployed workflow name.
13
9
  * @experimental
@@ -27,4 +23,4 @@ declare const voiceClassName: (exportName: string) => string;
27
23
  * @experimental
28
24
  */
29
25
  declare const voiceBindingName: (exportName: string) => string;
30
- export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
26
+ export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName };
package/dist/naming.mjs CHANGED
@@ -1 +1 @@
1
- const a=/([a-z0-9])([A-Z])/gu,t=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,s=e=>`AGENT_${e.replaceAll(a,"$1_$2").toUpperCase()}`,c=e=>`agent-${e.replaceAll(a,"$1-$2").toLowerCase()}`,o=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,l=e=>`VOICE_${e.replaceAll(a,"$1_$2").toUpperCase()}`;export{s as agentBindingName,t as agentClassName,c as agentDefaultName,l as voiceBindingName,o as voiceClassName};
1
+ const a=/([a-z0-9])([A-Z])/gu,s=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}AgentWorkflow`,t=e=>`agent-${e.replaceAll(a,"$1-$2").toLowerCase()}`,c=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}VoiceDO`,o=e=>`VOICE_${e.replaceAll(a,"$1_$2").toUpperCase()}`;export{s as agentClassName,t as agentDefaultName,o as voiceBindingName,c as voiceClassName};
@@ -1 +1 @@
1
- import{createAi as A}from"@lunora/ai";import{l as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as I}from"./voice-turn-7a1NoDHS.mjs";import{createStreamGenerate as C,createCompact as R}from"./createAgentGenerate-BOILDUZj.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as L,toFunctionReference as m}from"./AGENT_MODULE-M4D1EejI.mjs";const N="@cf/openai/whisper-large-v3-turbo",O="@cf/deepgram/aura-1",U=8*1024*1024,B=100,f=4e3,g=f*4+1024,F=4002,D=4003,z=4004,W=256*1024,S=15,G=5e3,X=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class J{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,r){this.state=t,this.env=e,this.agent=s,this.exportName=r,this.paths=L,this.ai=A({binding:e.AI,env:e}),this.streamGenerate=C(s,e),this.sttModel=s.voice?.stt??N,this.ttsModel=s.voice?.tts??O,this.maxSessionTurns=s.voice?.maxTurns??B}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const s=new URL(t.url).searchParams.get("threadKey");if(!s)return new Response("Missing threadKey",{status:400});const r=globalThis.WebSocketPair,i=new r,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:s,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,s,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s){if(p(s.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(r){this.send(t,{message:r instanceof Error?r.message:String(r),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const s=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...s===void 0?{}:{speaker:s}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,s){if(s.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,z,"control_frame_limit");return}let r;try{r=JSON.parse(s)}catch{return}if(!X(r)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=r;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,F,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,s){const r=(this.bufferedBytes.get(t)??0)+e.byteLength;if(r>U){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(s,D,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,r)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((n,o)=>n+o.byteLength,0),r=new Uint8Array(s);let i=0;for(const n of e)r.set(n,i),i+=n.byteLength;return r}async runTurn(t,e,s){const r=new AbortController;this.controllers.set(e.connectionId,r);try{await w({agent:this.agent,compact:R(),connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:r.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(e.connectionId)===r&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,r,i,n){const o=this.resolveRun(r,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...r===void 0?{}:{owner:r}}))?.outcome!=="created")return;for await(const u of I(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}closeSocket(t,e,s){try{t.close?.(e,s)}catch{}}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>W&&s<G;)await new Promise(r=>{setTimeout(r,S)}),s+=S}}export{J as default};
1
+ import{createAi as A}from"@lunora/ai";import{l as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as I}from"./voice-turn-BiDZeZwp.mjs";import{createStreamGenerate as C,createCompact as R}from"./createAgentGenerate-BOILDUZj.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as L,toFunctionReference as m}from"./AGENT_MODULE-M4D1EejI.mjs";const N="@cf/openai/whisper-large-v3-turbo",O="@cf/deepgram/aura-1",U=8*1024*1024,B=100,f=4e3,g=f*4+1024,F=4002,D=4003,z=4004,W=256*1024,S=15,G=5e3,X=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class J{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,r){this.state=t,this.env=e,this.agent=s,this.exportName=r,this.paths=L,this.ai=A({binding:e.AI,env:e}),this.streamGenerate=C(s,e),this.sttModel=s.voice?.stt??N,this.ttsModel=s.voice?.tts??O,this.maxSessionTurns=s.voice?.maxTurns??B}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const s=new URL(t.url).searchParams.get("threadKey");if(!s)return new Response("Missing threadKey",{status:400});const r=globalThis.WebSocketPair,i=new r,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:s,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,s,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s){if(p(s.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(r){this.send(t,{message:r instanceof Error?r.message:String(r),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const s=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...s===void 0?{}:{speaker:s}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,s){if(s.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,z,"control_frame_limit");return}let r;try{r=JSON.parse(s)}catch{return}if(!X(r)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=r;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,F,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,s){const r=(this.bufferedBytes.get(t)??0)+e.byteLength;if(r>U){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(s,D,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,r)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((n,o)=>n+o.byteLength,0),r=new Uint8Array(s);let i=0;for(const n of e)r.set(n,i),i+=n.byteLength;return r}async runTurn(t,e,s){const r=new AbortController;this.controllers.set(e.connectionId,r);try{await w({agent:this.agent,compact:R(),connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:r.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(e.connectionId)===r&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,r,i,n){const o=this.resolveRun(r,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...r===void 0?{}:{owner:r}}))?.outcome!=="created")return;for await(const u of I(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}closeSocket(t,e,s){try{t.close?.(e,s)}catch{}}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>W&&s<G;)await new Promise(r=>{setTimeout(r,S)}),s+=S}}export{J as default};
@@ -0,0 +1,3 @@
1
+ import{f as ot}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{r as W}from"./workflow-binding-Dm9hBzx_.mjs";import{c as b,d as nt}from"./component-shared-G8ngerkU.mjs";import{resolveAgentModel as at}from"./createAgentGenerate-BOILDUZj.mjs";import{buildModelMessages as H}from"./buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as z}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as st}from"./positive-integer-ztHqqpBk.mjs";import{combineTelemetry as rt}from"./combineTelemetry-DgE9W9G8.mjs";import{c as G}from"./tool-output-Cmk3JWMG.mjs";const it=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",F=e=>e.memorySources?e.memorySources:e.memory&&it(e.memory)?[{key:"default",...e.memory}]:[],ct=e=>F(e).find(t=>t.kind==="graph"),dt=e=>F(e).find(t=>t.kind==="episodic"),S=(e,t)=>t==="default"?e:`${e}:${t}`,ut=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const n=Array.isArray(t)?t:[t];return n.length===0?void 0:rt(...n)},lt=async(e,t,n)=>{const o=ut(e);if(o===void 0)return n();const a={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:a,toolContext:void 0},c=Date.now();await o.onToolExecutionStart?.(s);let d;const u=()=>(d??=n(),d);try{if(o.executeTool===void 0)await u();else try{await o.executeTool({...s,execute:u,toolCallId:t.id})}catch{}const i=await u();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,input:t.input,output:i,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),i}catch(i){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,error:i,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),i}},pt=8,mt=e=>st(e)?e:0,V=e=>e===void 0?"null":JSON.stringify(e),yt=async(e,t,n)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...n===void 0?{}:{usage:n}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},vt=e=>e===void 0?[]:[e].flat(),ft=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),ht=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const n={};for(const o of["inputTokens","outputTokens","totalTokens"])(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},gt=async(e,t,n,o,a)=>{const{needsApproval:s}=e;return s===void 0||s===!1?!1:s===!0?!0:n.do(o,async()=>s(t,a))},wt="WorkflowTimeoutError",Tt=e=>e instanceof Error&&e.name===wt,L=4320*60*1e3,xt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Ct=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,St=e=>{if(e===void 0)return L;if(typeof e=="number")return Math.min(e,b);const t=Ct.exec(e);return t===null?L:Math.min(Number(t[1])*xt[t[2]],b)},kt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:c,step:d}=e;await c({content:`Awaiting approval to run tool "${t.name}".`,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"});const u=await d.waitForEvent(`approval:${t.id}`,{timeout:St(n.approvalTimeout),type:`agent-approval:${t.id}`}).then(i=>({decision:i.payload.decision,...i.payload.note===void 0?{}:{note:i.payload.note}})).catch(i=>{if(!Tt(i))throw i;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),u},A="lunoraToolOutcome",Et=e=>typeof e=="object"&&e!==null&&A in e?e[A]:{ok:e},Mt=async(e,t)=>{const{agent:n,depth:o,env:a,exports:s,getState:c,instanceId:d,onTokenDelta:u,owner:i,persist:m,run:r,setState:l,step:p,threadKey:f,tools:E}=e,h=`tool:${t.name}:${t.id}`,v=E[t.name],T=`${d}:tool:${t.id}`;if(!v){await m({content:`Error: unknown tool "${t.name}"`,messageKey:T,role:"tool",stepName:h,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await m({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:T,role:"tool",stepName:h,toolCallId:t.id,toolName:t.name});return}const O={depth:o,env:a,exports:s,getState:c,idempotencyKey:h,owner:i,reportProgress:w=>{u?.({data:w,kind:"progress",threadKey:f,toolCallId:t.id})},run:r,setState:l,step:p,threadKey:f,toolCallId:t.id},_={depth:o,env:a,getState:c,idempotencyKey:h,run:r,threadKey:f,toolCallId:t.id},U=`tool:approval-gate:${t.id}`;let x;if(await gt(v,t.input,p,U,_)){const{decision:w,note:k}=await kt(e,t);if(w==="reject"){const D=k===void 0?"":` Reason: ${k}`;await m({content:`Tool "${t.name}" was rejected by the user and not run.${D}`,messageKey:T,role:"tool",status:"rejected",stepName:h,toolCallId:t.id,toolName:t.name});return}x="approved"}const M=Et(await p.do(h,async()=>{try{const w=()=>Promise.resolve(v.execute(t.input,O)),k=await lt(n.telemetry,{id:t.id,input:t.input,name:t.name},w);return{[A]:{ok:k}}}catch(w){if(ot(w))return{[A]:{failed:w.message}};throw w}}));if("failed"in M){await m({content:G(`Error: tool "${t.name}" failed and will not be retried. ${M.failed}`),messageKey:T,role:"tool",stepName:h,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name});return}const $=M.ok;await m({content:G(typeof $=="string"?$:V($)),messageKey:T,role:"tool",stepName:h,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},$t=(e,t,n)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:at(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},Rt=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const n=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=n)return;let o=e.length-n;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},It=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=Rt(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const c=await o({env:a,messages:H({history:s.older}),model:n.compaction?.model??n.model});return c.length>0?{history:s.recent,summary:c}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Kt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:c,listMessages:d,memoryContext:u,onTokenDelta:i,run:m,step:r,streamGenerate:l,threadKey:p}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const f=await m(d,{key:p}),{history:E,summary:h}=await It(e,f);let v={activeTools:o.activeTools,messages:H({history:E,instructions:c,memoryContext:u,summary:h}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(v=$t(v,await o.prepareStep({messages:v.messages,stepNumber:t,steps:n}),a));const T={messages:v.messages,...v.activeTools===void 0?{}:{activeTools:v.activeTools},...v.model===void 0?{}:{model:v.model},...v.toolChoice===void 0?{}:{toolChoice:v.toolChoice}};return l&&i?l(T,R=>{i({text:R,threadKey:p,turn:t})}):s(T)})},B=async(e,t)=>{const{agent:n,step:o}=e;n.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await n.onStepFinish?.(t),!0))},Nt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),j=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},At=e=>nt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Ot=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:s}=e,c=S("memory:retrieve",e.key),d=await n.do(c,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return j(d)},_t=async(e,t,n,o,a,s)=>{if(n===void 0)return;const c=S("memory:traverse",e.key),d=await a.do(c,async()=>s(o,{owner:n,query:t,...At(e.graph)}));return j(d)},Ut=async(e,t,n,o,a)=>{if(t===void 0)return;const s=S("memory:recall",e.key),c={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},d=await o.do(s,async()=>a(n,c));return j(d)},Dt=async(e,t)=>e.kind==="episodic"?Ut(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?_t(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Ot(e,t.input,t.step,t.run),Pt=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},Ft=async(e,t,n,o,a,s)=>{const c=Pt(F(e));if(c.length===0)return;const d=g(o.graphTraverse),u=g(o.episodeRecall),i=[];for(const m of c){const r=await Dt(m,{episodeRecall:u,graphTraverse:d,input:t,owner:n,run:s,step:a});r!==void 0&&i.push(r)}return i.length>0?i.join(`
2
+
3
+ `):void 0},jt=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:c,owner:d,paths:u,run:i,step:m}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const r=ct(t);if(r!==void 0)try{const l={assistantText:a,env:n,model:r.graph?.extractionModel??t.model,userInput:s},p=await m.do(S("memory:extract",r.key),async()=>o(l));await i(g(u.graphUpsert),{...p,messageKey:`${c}:${S("extract",r.key)}`,owner:d})}catch{}},qt=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:c,owner:d,paths:u,run:i,step:m,threadKey:r}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const l=dt(t);if(l!==void 0)try{const p={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:f}=await m.do(S("memory:episode",l.key),async()=>o(p));await i(g(u.episodeUpsert),{messageKey:`${c}:${S("episode",l.key)}`,owner:d,summary:f,threadKey:r})}catch{}},bt=async(e,t,n)=>{const o=W(e.env,e.exports,z(t),["get"]);if(o!==void 0)try{await(await o.get(n)).terminate()}catch{}},Gt="12 hours",Lt=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:Gt,type:`agent-dequeue:${t}:${n}`})},Bt=async(e,t,n)=>{const o=W(e.env,e.exports,z(e.exportName),["get"]);if(o===void 0)return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},Wt=async(e,t,n)=>{const{onReply:o}=e,{replyRef:a}=t.params;if(!(o===void 0||a===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:a,result:n,threadKey:t.params.threadKey}),a.channel))}catch{}},Ht=async(e,t,n,o,a)=>{const{instanceId:s,persist:c}=e,d=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const u=n.output!==void 0&&n.text.length===0?V(n.output):n.text;return await c({content:u,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await B(e,{text:n.text,toolCalls:[],turn:t,...d}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await c({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const u of n.toolCalls)await Mt(e,u);if(await B(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...d}),o.push(Nt(n)),a.length>0&&await ft(a,o))return"stopCondition"},zt=async(e,t,n,o)=>{const a=[];let s,c=!1,d=0;for(let u=0;u<t;u+=1){const i=await Kt(e,u,a);o.value=ht(o.value,i.usage),d=u+1;const m=await Ht(e,u,i,a,n);if(m==="stopCondition"){c=!0;break}if(m!==void 0){s=m.final;break}}return{final:s,stoppedByCondition:c,turnsRun:d}},ae=async e=>{const{agent:t,compact:n,env:o,exportName:a,exports:s,extractEpisode:c,extractGraph:d,generate:u,instanceId:i,onTokenDelta:m,params:r,paths:l,run:p,step:f,streamGenerate:E}=e,h=t.maxTurns??pt,v=vt(t.stopWhen),T=g(l.appendMessage),R=g(l.completeRun),O=g(l.ensureThread),_=g(l.listMessages),U=g(l.deleteMessage),x=g(l.patchThread),M=g(l.setState),$=g(l.state),w=async y=>{await p(T,{threadKey:r.threadKey,...y})},k=async y=>{await p(x,{key:r.threadKey,...y})},D=async y=>{await p(U,{messageKey:y,threadKey:r.threadKey})},X=async()=>{await w({content:r.input,messageKey:`${i}:user`,role:"user"})},q={dispatched:!1},I=async y=>{q.dispatched=!0;const N=await p(R,{instanceId:i,key:r.threadKey,...y});N?.dequeued!==void 0&&await Bt({env:o,exportName:a,exports:s,step:f},r.threadKey,N.dequeued)},J=async()=>await p($,{key:r.threadKey}),Q=async y=>{await p(M,{key:r.threadKey,state:y})},P=await p(O,{agent:a,instanceId:i,key:r.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...r.owner===void 0?{}:{owner:r.owner},...r.title===void 0?{}:{title:r.title}});P?.outcome==="replaced"&&await bt({env:o,exports:s},a,P.priorInstanceId);const Y=await Ft(t,r.input,r.owner,l,f,p),Z=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,tt={agent:t,compact:n,depth:mt(r.depth),env:o,exports:s,generate:u,getState:J,instanceId:i,instructions:Z,listMessages:_,memoryContext:Y,onTokenDelta:m,owner:r.owner,deleteMessage:D,patchThread:k,persist:w,run:p,setState:Q,step:f,streamGenerate:E,threadKey:r.threadKey,tools:t.tools??{}},K={value:void 0};try{P?.outcome==="queued"&&await Lt(f,r.threadKey,i),await X();const{final:y,stoppedByCondition:N,turnsRun:et}=await zt(tt,h,v,K),C=K.value===void 0?{}:{usage:K.value};return await jt({agent:t,env:o,extractGraph:d,finalText:y?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:p,step:f}),await qt({agent:t,env:o,extractEpisode:c,finalText:y?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:p,step:f,threadKey:r.threadKey}),y?(await Wt(t,{env:o,params:r,step:f},{...y,...C}),await I({status:"idle",...C}),{...y,...C}):N?(await I({status:"idle",...C}),{stopped:"stopCondition",turns:et,...C}):(await I({error:`agent stopped: maxTurns (${String(h)}) reached`,status:"error",...C}),{stopped:"maxTurns",turns:h,...C})}catch(y){throw q.dispatched||await yt(I,y,K.value),y}};export{St as a,It as c,it as i,ae as r,Rt as s};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as I}from"@lunora/workflow";import{jsonSchema as L}from"ai";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-M4D1EejI.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(!I(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:L({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 +1 @@
1
- import{defineWorkflow as s}from"@lunora/workflow";import{r as m}from"./agent-loop-CR27O7MC.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as c}from"./createAgentGenerate-BOILDUZj.mjs";import{agentDefaultName as u}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-M4D1EejI.mjs";import{l as T}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-ByqrB-72.mjs";const E=(r,t,a)=>T({env:t,label:"@lunora/agent",...a===void 0?{}:{fetchImpl:a},...r===void 0?{}:{identity:{userId:r}}}),O=(r,t,a)=>{const e=t.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||r.telemetry?.isEnabled===!1)return r;const n=typeof t.LUNORA_OTLP_TOKEN=="string"?t.LUNORA_OTLP_TOKEN:void 0,o=[r.telemetry?.integrations].flat().filter(i=>i!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...o,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>s({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:c(),env:e.env,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??u(t)});export{I as default};
1
+ import{defineWorkflow as i}from"@lunora/workflow";import{r as m}from"./agent-loop-CQUKMFWA.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-BOILDUZj.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-M4D1EejI.mjs";import{l as T}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-ByqrB-72.mjs";const E=(r,t,a)=>T({env:t,label:"@lunora/agent",...a===void 0?{}:{fetchImpl:a},...r===void 0?{}:{identity:{userId:r}}}),O=(r,t,a)=>{const e=t.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||r.telemetry?.isEnabled===!1)return r;const n=typeof t.LUNORA_OTLP_TOKEN=="string"?t.LUNORA_OTLP_TOKEN:void 0,o=[r.telemetry?.integrations].flat().filter(s=>s!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...o,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>i({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:u(),env:e.env,exports:e.exports,exportName:t,extractGraph:d(),extractEpisode:f(),generate:l(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??A,run:E(e.params.owner,e.env,e.fetchImpl),step:e.step,streamGenerate:p(n,e.env)})},name:r.name??c(t)});export{I as default};
@@ -0,0 +1 @@
1
+ import{l as f}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{LunoraError as o}from"@lunora/errors";import{h as g,B as w}from"./branch-marker-boZ00zmk.mjs";import{r as h}from"./workflow-binding-Dm9hBzx_.mjs";import{toFunctionReference as E,DEFAULT_AGENT_FUNCTION_PATHS as N}from"./AGENT_MODULE-M4D1EejI.mjs";const _=(r,c,i={})=>{const{dispatch:l,exports:u}=i,s={},d=E(N.patchThread),p=()=>l??f({env:r,label:"@lunora/agent"});for(const n of c){const a=()=>{const t=h(r,u,n.className,["create","get"]);if(t===void 0)throw new o("INTERNAL",`@lunora/agent: no "${n.className}" on ctx.exports or env for agent "${n.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return t};s[n.exportName]={cancel:async t=>{await(await a().get(t)).terminate();try{await p()(d,{instanceId:t,status:"cancelled"})}catch{}},publicRun:n.publicRun===!0,run:async(t,e)=>{if(g(t))throw new o("BAD_REQUEST",`@lunora/agent: run input ${w}`);return{id:(await a().create({...e?.id===void 0?{}:{id:e.id},params:t})).id}},sendEvent:async(t,e)=>{await(await a().get(t)).sendEvent(e)},status:async t=>(await a().get(t)).status()}}return s};export{_ as default};
@@ -1,3 +1,3 @@
1
- import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-CR27O7MC.mjs";import{collectAgenticMemoryTools as g}from"./collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as p}from"./agentAsTool-CgZb6ycK.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=/^[a-zA-Z][\w-]*$/u,N=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=a}return o},A=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
1
+ import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-CQUKMFWA.mjs";import{collectAgenticMemoryTools as g}from"./collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as p}from"./agentAsTool-1Gwq45M3.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=/^[a-zA-Z][\w-]*$/u,N=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=a}return o},A=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
2
2
 
3
3
  `)},k=(e,n)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const t of n)t.knowledge&&m(t.knowledge)&&o.push({key:t.name,...t.knowledge});return o},y=e=>{const n=new Set;for(const o of e){if(typeof o.name!="string"||!w.test(o.name))throw new r("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new r("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(n.has(o.name))throw new r("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);n.add(o.name)}},v=(e,n)=>{if(e===void 0)return;const o=Object.keys(n).filter(t=>!e.includes(t));if(o.length>0)throw new r("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(t=>`"${t}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},E=(e,n)=>{const o=(t,s)=>{if(t&&t.kind!=="graph"&&t.kind!=="episodic"&&t.source===void 0)throw new r("INTERNAL",`@lunora/agent: ${s} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const t of n)o(t.knowledge,`skill "${t.name}" \`knowledge\``)},L=e=>{if(e===void 0)return;const n=f(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},$=e=>{const n=e.model;if(n==null||typeof n=="string"&&n.length===0)throw new r("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(e.maxTurns!==void 0&&!u(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!u(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");L(e.approvalTimeout);const o=e.skills??[];y(o),E(e,o);const t=N(e,o),s=g(e,o);for(const[i,h]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=h}const a=Object.keys(s).length>0;v(e.activeTools,s);for(const i of Object.keys(t))if(!T.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=k(e,o),d=A(e,o);return{...e,asTool:p,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:t}:{}}},j=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,M=e=>{if(typeof e.execute!="function")throw new r("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{$ as defineAgent,M as defineAgentTool,j as isAgentDefinition};
@@ -0,0 +1 @@
1
+ import"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import"./workflow-binding-Dm9hBzx_.mjs";import"./component-shared-G8ngerkU.mjs";import"./createAgentGenerate-BOILDUZj.mjs";import{a as l,c as u,r as f,s as g}from"./agent-loop-CQUKMFWA.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"../naming.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./tool-output-Cmk3JWMG.mjs";export{l as approvalTimeoutMs,u as compactHistory,f as runAgentLoop,g as splitForCompaction};
@@ -1 +1 @@
1
- import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-7a1NoDHS.mjs";import"./agent-loop-CR27O7MC.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,c as toByteIterable};
1
+ import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-BiDZeZwp.mjs";import"./agent-loop-CQUKMFWA.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,c as toByteIterable};
@@ -86,6 +86,8 @@ interface AgentToolContext {
86
86
  depth?: number;
87
87
  /** The Worker environment bindings. */
88
88
  env: Record<string, unknown>;
89
+ /** The invoking context's `ctx.exports`, where Cloudflare exposes the declared agents (see `agent.asTool`). */
90
+ exports?: unknown;
89
91
  /**
90
92
  * Read the thread's synced state — dispatches the public owner-gated
91
93
  * `agents:agentState` query through {@link AgentToolContext.run} (the same
@@ -711,7 +713,7 @@ interface AgentConfig {
711
713
  * Optional override for the deployed workflow name (`wrangler.jsonc`
712
714
  * `workflows[].name`). Defaults to `agent-<kebab-cased export name>`. Does
713
715
  * NOT change the binding name, which is always derived from the export
714
- * name (`support` → `AGENT_SUPPORT`).
716
+ * name (`support` → `SupportAgentWorkflow`).
715
717
  */
716
718
  name?: string;
717
719
  /**
@@ -895,7 +897,7 @@ interface AgentAsToolOptions {
895
897
  maxPolls?: number;
896
898
  /**
897
899
  * The child agent's export name — selects its `AGENT_<NAME>` Workflow
898
- * binding (e.g. `"researcher"` → `AGENT_RESEARCHER`). The model-facing tool
900
+ * export key (e.g. `"researcher"` → `ResearcherAgentWorkflow`). The model-facing tool
899
901
  * name is the KEY assigned in the parent's `tools` map, not this.
900
902
  */
901
903
  name: string;
@@ -1277,11 +1279,12 @@ type AgentTokenSink = (event: AgentLiveEvent) => void;
1277
1279
  */
1278
1280
  type AgentStreamGenerate = (options: AgentGenerateOptions, onDelta: (text: string) => void) => Promise<AgentGenerateResult>;
1279
1281
  /**
1280
- * Spec entry codegen emits per agent: `{ binding: "AGENT_SUPPORT", exportName: "support" }`.
1282
+ * Spec entry codegen emits per agent: `{ className: "SupportAgentWorkflow", exportName: "support" }`.
1281
1283
  * @experimental
1282
1284
  */
1283
1285
  interface AgentBindingSpec {
1284
- binding: string;
1286
+ /** The agent's export key — its generated class name, e.g. `SupportAgentWorkflow`. */
1287
+ className: string;
1285
1288
  exportName: string;
1286
1289
  /**
1287
1290
  * Whether the app author opted this agent into public run-starts (via
@@ -86,6 +86,8 @@ interface AgentToolContext {
86
86
  depth?: number;
87
87
  /** The Worker environment bindings. */
88
88
  env: Record<string, unknown>;
89
+ /** The invoking context's `ctx.exports`, where Cloudflare exposes the declared agents (see `agent.asTool`). */
90
+ exports?: unknown;
89
91
  /**
90
92
  * Read the thread's synced state — dispatches the public owner-gated
91
93
  * `agents:agentState` query through {@link AgentToolContext.run} (the same
@@ -711,7 +713,7 @@ interface AgentConfig {
711
713
  * Optional override for the deployed workflow name (`wrangler.jsonc`
712
714
  * `workflows[].name`). Defaults to `agent-<kebab-cased export name>`. Does
713
715
  * NOT change the binding name, which is always derived from the export
714
- * name (`support` → `AGENT_SUPPORT`).
716
+ * name (`support` → `SupportAgentWorkflow`).
715
717
  */
716
718
  name?: string;
717
719
  /**
@@ -895,7 +897,7 @@ interface AgentAsToolOptions {
895
897
  maxPolls?: number;
896
898
  /**
897
899
  * The child agent's export name — selects its `AGENT_<NAME>` Workflow
898
- * binding (e.g. `"researcher"` → `AGENT_RESEARCHER`). The model-facing tool
900
+ * export key (e.g. `"researcher"` → `ResearcherAgentWorkflow`). The model-facing tool
899
901
  * name is the KEY assigned in the parent's `tools` map, not this.
900
902
  */
901
903
  name: string;
@@ -1277,11 +1279,12 @@ type AgentTokenSink = (event: AgentLiveEvent) => void;
1277
1279
  */
1278
1280
  type AgentStreamGenerate = (options: AgentGenerateOptions, onDelta: (text: string) => void) => Promise<AgentGenerateResult>;
1279
1281
  /**
1280
- * Spec entry codegen emits per agent: `{ binding: "AGENT_SUPPORT", exportName: "support" }`.
1282
+ * Spec entry codegen emits per agent: `{ className: "SupportAgentWorkflow", exportName: "support" }`.
1281
1283
  * @experimental
1282
1284
  */
1283
1285
  interface AgentBindingSpec {
1284
- binding: string;
1286
+ /** The agent's export key — its generated class name, e.g. `SupportAgentWorkflow`. */
1287
+ className: string;
1285
1288
  exportName: string;
1286
1289
  /**
1287
1290
  * Whether the app author opted this agent into public run-starts (via
@@ -1 +1 @@
1
- import{c as z}from"./agent-loop-CR27O7MC.mjs";import{buildModelMessages as G}from"./buildModelMessages-Y4tGo1T9.mjs";import{toFunctionReference as A}from"./AGENT_MODULE-M4D1EejI.mjs";const ot=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},P=t=>{const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.codePointAt(r)??0;return n},C=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),n=e+"=".repeat((4-e.length%4)%4);return P(n)},D=new TextDecoder;new TextEncoder;const N="=",Q=t=>{if(t)try{const e=t[0]==="{"?t:D.decode(C(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},ct=t=>{if(t){if(!t.startsWith(N))return t;try{return D.decode(C(t.slice(N.length)))}catch{return}}},dt=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},ut=t=>typeof t=="number"&&Date.now()>=t,yt=t=>{try{t.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},message:"authentication token expired",type:"error"})),t.close?.(4001,"token_expired")}catch{}},Y=16e3,Z=1,tt=16,M=/[.!?]\s/u,et=/\s/u,nt=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{e.releaseLock()}return}yield*t},ft=(t,e=Y,n=Z,r=tt)=>{const i=n*r/8,l=e*i,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(p,b)=>{for(let d=0;d<b.length;d+=1)s.setUint8(p+d,b.codePointAt(d)??0)};u(0,"RIFF"),s.setUint32(4,36+t.byteLength,!0),u(8,"WAVE"),u(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,e,!0),s.setUint32(28,l,!0),s.setUint16(32,i,!0),s.setUint16(34,r,!0),u(36,"data"),s.setUint32(40,t.byteLength,!0);const a=new Uint8Array(m);return a.set(t,44),a},rt=t=>{const e=[];let n=t,r=M.exec(n);for(;r;){let i=r.index+1;for(;i<n.length&&et.test(n[i]??"");)i+=1;const l=n.slice(0,i).trim();l.length>0&&e.push(l),n=n.slice(i),r=M.exec(n)}return{rest:n,sentences:e}},lt=async t=>{const{agent:e,compact:n,connectionId:r,env:i,exportName:l,owner:m,paths:s,pcm:u,run:a,send:p,sendAudio:b,signal:d,streamGenerate:H,synthesize:L,text:B,threadKey:o,transcribe:F,turn:U,waitForDrain:O}=t,h=()=>d.aborted,v=A(s.appendMessage),$=A(s.ensureThread),K=A(s.listMessages),x=A(s.patchThread);await a($,{agent:l,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const y=(B??(u?await F(u):"")).trim();if(y.length===0)return await a(x,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};p({text:y,type:"user_transcript"}),await a(v,{content:y,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await a(x,{key:o,status:"running"});const _=typeof e.instructions=="function"?e.instructions({env:i,input:y,threadKey:o}):e.instructions,j=await a(K,{key:o}),{history:W,summary:I}=await z({agent:e,compact:n,env:i},j),V=G({history:W,..._===void 0?{}:{instructions:_},...I===void 0?{}:{summary:I}});let g="",E="",k=Promise.resolve();const X=async c=>{if(h()||c.length===0)return;let w=!1;try{for await(const f of nt(await L(c,d))){if(h()||(await O?.(),h()))break;b(f),w=!0}}catch(f){p({message:f instanceof Error?f.message:String(f),type:"error"})}w&&(E=E.length>0?`${E} ${c}`:c)},R=c=>{k=k.then(async()=>X(c))},J=await H({messages:V,signal:d},c=>{if(h())return;p({text:c,type:"assistant_delta"}),g+=c;const{rest:w,sentences:f}=rt(g);g=w;for(const q of f)R(q)});!h()&&g.trim().length>0&&R(g.trim()),g="",await k;const S=h(),T=S?E:J.text;return await a(v,{content:T,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await a(x,{key:o,status:"idle"}),p(S?{type:"interrupted"}:{text:T,type:"assistant_done"}),{assistantText:T,interrupted:S,userText:y}}catch(y){throw await a(x,{key:o,status:"idle"}),y}},pt=t=>Q(t),ht=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},gt=t=>{if(t instanceof Uint8Array||t instanceof ReadableStream)return t;if(t instanceof Response&&t.body)return t.body;if(typeof t=="object"&&t!==null&&"audio"in t){const{audio:e}=t;if(typeof e=="string")return P(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{dt as a,yt as b,ft as c,ct as d,ht as e,gt as f,nt as g,ut as i,pt as p,lt as r,ot as t};
1
+ import{c as z}from"./agent-loop-CQUKMFWA.mjs";import{buildModelMessages as G}from"./buildModelMessages-Y4tGo1T9.mjs";import{toFunctionReference as A}from"./AGENT_MODULE-M4D1EejI.mjs";const ot=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},P=t=>{const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.codePointAt(r)??0;return n},C=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),n=e+"=".repeat((4-e.length%4)%4);return P(n)},D=new TextDecoder;new TextEncoder;const N="=",Q=t=>{if(t)try{const e=t[0]==="{"?t:D.decode(C(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},ct=t=>{if(t){if(!t.startsWith(N))return t;try{return D.decode(C(t.slice(N.length)))}catch{return}}},dt=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},ut=t=>typeof t=="number"&&Date.now()>=t,yt=t=>{try{t.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},message:"authentication token expired",type:"error"})),t.close?.(4001,"token_expired")}catch{}},Y=16e3,Z=1,tt=16,M=/[.!?]\s/u,et=/\s/u,nt=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{e.releaseLock()}return}yield*t},ft=(t,e=Y,n=Z,r=tt)=>{const i=n*r/8,l=e*i,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(p,b)=>{for(let d=0;d<b.length;d+=1)s.setUint8(p+d,b.codePointAt(d)??0)};u(0,"RIFF"),s.setUint32(4,36+t.byteLength,!0),u(8,"WAVE"),u(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,e,!0),s.setUint32(28,l,!0),s.setUint16(32,i,!0),s.setUint16(34,r,!0),u(36,"data"),s.setUint32(40,t.byteLength,!0);const a=new Uint8Array(m);return a.set(t,44),a},rt=t=>{const e=[];let n=t,r=M.exec(n);for(;r;){let i=r.index+1;for(;i<n.length&&et.test(n[i]??"");)i+=1;const l=n.slice(0,i).trim();l.length>0&&e.push(l),n=n.slice(i),r=M.exec(n)}return{rest:n,sentences:e}},lt=async t=>{const{agent:e,compact:n,connectionId:r,env:i,exportName:l,owner:m,paths:s,pcm:u,run:a,send:p,sendAudio:b,signal:d,streamGenerate:H,synthesize:L,text:B,threadKey:o,transcribe:F,turn:U,waitForDrain:O}=t,h=()=>d.aborted,v=A(s.appendMessage),$=A(s.ensureThread),K=A(s.listMessages),x=A(s.patchThread);await a($,{agent:l,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const y=(B??(u?await F(u):"")).trim();if(y.length===0)return await a(x,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};p({text:y,type:"user_transcript"}),await a(v,{content:y,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await a(x,{key:o,status:"running"});const _=typeof e.instructions=="function"?e.instructions({env:i,input:y,threadKey:o}):e.instructions,j=await a(K,{key:o}),{history:W,summary:I}=await z({agent:e,compact:n,env:i},j),V=G({history:W,..._===void 0?{}:{instructions:_},...I===void 0?{}:{summary:I}});let g="",E="",k=Promise.resolve();const X=async c=>{if(h()||c.length===0)return;let w=!1;try{for await(const f of nt(await L(c,d))){if(h()||(await O?.(),h()))break;b(f),w=!0}}catch(f){p({message:f instanceof Error?f.message:String(f),type:"error"})}w&&(E=E.length>0?`${E} ${c}`:c)},R=c=>{k=k.then(async()=>X(c))},J=await H({messages:V,signal:d},c=>{if(h())return;p({text:c,type:"assistant_delta"}),g+=c;const{rest:w,sentences:f}=rt(g);g=w;for(const q of f)R(q)});!h()&&g.trim().length>0&&R(g.trim()),g="",await k;const S=h(),T=S?E:J.text;return await a(v,{content:T,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await a(x,{key:o,status:"idle"}),p(S?{type:"interrupted"}:{text:T,type:"assistant_done"}),{assistantText:T,interrupted:S,userText:y}}catch(y){throw await a(x,{key:o,status:"idle"}),y}},pt=t=>Q(t),ht=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},gt=t=>{if(t instanceof Uint8Array||t instanceof ReadableStream)return t;if(t instanceof Response&&t.body)return t.body;if(typeof t=="object"&&t!==null&&"audio"in t){const{audio:e}=t;if(typeof e=="string")return P(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{dt as a,yt as b,ft as c,ct as d,ht as e,gt as f,nt as g,ut as i,pt as p,lt as r,ot as t};
@@ -0,0 +1 @@
1
+ const l=(e,r,o)=>e?.[o]??r?.[o],f=(e,r,o,t)=>{const n=l(e,r,o);if(!(typeof n!="object"||n===null))return t.every(i=>typeof n[i]=="function")?n:void 0};export{f as r};
package/dist/reply.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Mailer } from '@lunora/mail';
2
2
  import { InboundEmail } from '@lunora/mail/inbound';
3
- import { a as AgentReplyRef } from "./packem_shared/types.d-DS2wmzMe.mjs";
3
+ import { a as AgentReplyRef } from "./packem_shared/types.d-CbYtFBw9.mjs";
4
4
  import 'ai';
5
5
  /** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
6
6
  type EmailReplyRef = Extract<AgentReplyRef, {
package/dist/reply.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Mailer } from '@lunora/mail';
2
2
  import { InboundEmail } from '@lunora/mail/inbound';
3
- import { a as AgentReplyRef } from "./packem_shared/types.d-DS2wmzMe.js";
3
+ import { a as AgentReplyRef } from "./packem_shared/types.d-CbYtFBw9.js";
4
4
  import 'ai';
5
5
  /** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
6
6
  type EmailReplyRef = Extract<AgentReplyRef, {
@@ -1,4 +1,4 @@
1
- import { c as AgentToolDefinition, d as AgentToolContext } from "./packem_shared/types.d-DS2wmzMe.mjs";
1
+ import { c as AgentToolDefinition, d as AgentToolContext } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
package/dist/sandbox.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as AgentToolDefinition, d as AgentToolContext } from "./packem_shared/types.d-DS2wmzMe.js";
1
+ import { c as AgentToolDefinition, d as AgentToolContext } from "./packem_shared/types.d-CbYtFBw9.js";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { S as SkillMarkdownExtras, b as SkillDefinition } from "./packem_shared/types.d-DS2wmzMe.mjs";
1
+ import { S as SkillMarkdownExtras, b as SkillDefinition } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { S as SkillMarkdownExtras, b as SkillDefinition } from "./packem_shared/types.d-DS2wmzMe.js";
1
+ import { S as SkillMarkdownExtras, b as SkillDefinition } from "./packem_shared/types.d-CbYtFBw9.js";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/agent",
3
- "version": "1.0.0-alpha.155",
3
+ "version": "1.0.0-alpha.157",
4
4
  "description": "Durable AI agents for Lunora: defineAgent compiles a replay-safe tool-loop onto Cloudflare Workflows, with DO SQLite threads and live message subscriptions",
5
5
  "keywords": [
6
6
  "agent",
@@ -84,12 +84,12 @@
84
84
  "access": "public"
85
85
  },
86
86
  "dependencies": {
87
- "@lunora/ai": "1.0.0-alpha.104",
88
- "@lunora/errors": "1.0.0-alpha.47",
89
- "@lunora/mail": "1.0.0-alpha.93",
90
- "@lunora/server": "1.0.0-alpha.162",
91
- "@lunora/values": "1.0.0-alpha.57",
92
- "@lunora/workflow": "1.0.0-alpha.68",
87
+ "@lunora/ai": "1.0.0-alpha.105",
88
+ "@lunora/errors": "1.0.0-alpha.48",
89
+ "@lunora/mail": "1.0.0-alpha.94",
90
+ "@lunora/server": "1.0.0-alpha.164",
91
+ "@lunora/values": "1.0.0-alpha.58",
92
+ "@lunora/workflow": "1.0.0-alpha.69",
93
93
  "@modelcontextprotocol/sdk": "^1.30.0",
94
94
  "ai": "7.0.93",
95
95
  "yaml": "^2.9.0"
@@ -1,3 +0,0 @@
1
- import{f as tt}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{c as q,d as et}from"./component-shared-G8ngerkU.mjs";import{resolveAgentModel as ot}from"./createAgentGenerate-BOILDUZj.mjs";import{buildModelMessages as L}from"./buildModelMessages-Y4tGo1T9.mjs";import{agentBindingName as W}from"../naming.mjs";import{toFunctionReference as h}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as nt}from"./positive-integer-ztHqqpBk.mjs";import{combineTelemetry as at}from"./combineTelemetry-DgE9W9G8.mjs";import{c as b}from"./tool-output-Cmk3JWMG.mjs";const st=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",P=e=>e.memorySources?e.memorySources:e.memory&&st(e.memory)?[{key:"default",...e.memory}]:[],rt=e=>P(e).find(t=>t.kind==="graph"),it=e=>P(e).find(t=>t.kind==="episodic"),S=(e,t)=>t==="default"?e:`${e}:${t}`,ct=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:at(...n)},ut=async(e,t,n)=>{const o=ct(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},u=Date.now();await o.onToolExecutionStart?.(s);let d;const c=()=>(d??=n(),d);try{if(o.executeTool===void 0)await c();else try{await o.executeTool({...s,execute:c,toolCallId:t.id})}catch{}const i=await c();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-u,toolOutput:{dynamic:!0,input:t.input,output:i,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),i}catch(i){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-u,toolOutput:{dynamic:!0,error:i,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),i}},dt=8,lt=e=>nt(e)?e:0,z=e=>e===void 0?"null":JSON.stringify(e),pt=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)}},mt=e=>e===void 0?[]:[e].flat(),yt=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),ft=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const n={};for(const o of["inputTokens","outputTokens","totalTokens"])(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},vt=async(e,t,n,o,a)=>{const{needsApproval:s}=e;return s===void 0||s===!1?!1:s===!0?!0:n.do(o,async()=>s(t,a))},ht="WorkflowTimeoutError",gt=e=>e instanceof Error&&e.name===ht,B=4320*60*1e3,wt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Tt=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,xt=e=>{if(e===void 0)return B;if(typeof e=="number")return Math.min(e,q);const t=Tt.exec(e);return t===null?B:Math.min(Number(t[1])*wt[t[2]],q)},Ct=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:u,step:d}=e;await u({content:`Awaiting approval to run tool "${t.name}".`,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"});const c=await d.waitForEvent(`approval:${t.id}`,{timeout:xt(n.approvalTimeout),type:`agent-approval:${t.id}`}).then(i=>({decision:i.payload.decision,...i.payload.note===void 0?{}:{note:i.payload.note}})).catch(i=>{if(!gt(i))throw i;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),c},A="lunoraToolOutcome",St=e=>typeof e=="object"&&e!==null&&A in e?e[A]:{ok:e},Et=async(e,t)=>{const{agent:n,depth:o,env:a,getState:s,instanceId:u,onTokenDelta:d,owner:c,persist:i,run:r,setState:l,step:p,threadKey:m,tools:w}=e,v=`tool:${t.name}:${t.id}`,T=w[t.name],y=`${u}:tool:${t.id}`;if(!T){await i({content:`Error: unknown tool "${t.name}"`,messageKey:y,role:"tool",stepName:v,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await i({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:y,role:"tool",stepName:v,toolCallId:t.id,toolName:t.name});return}const M={depth:o,env:a,getState:s,idempotencyKey:v,owner:c,reportProgress:g=>{d?.({data:g,kind:"progress",threadKey:m,toolCallId:t.id})},run:r,setState:l,step:p,threadKey:m,toolCallId:t.id},O={depth:o,env:a,getState:s,idempotencyKey:v,run:r,threadKey:m,toolCallId:t.id},_=`tool:approval-gate:${t.id}`;let x;if(await vt(T,t.input,p,_,O)){const{decision:g,note:E}=await Ct(e,t);if(g==="reject"){const U=E===void 0?"":` Reason: ${E}`;await i({content:`Tool "${t.name}" was rejected by the user and not run.${U}`,messageKey:y,role:"tool",status:"rejected",stepName:v,toolCallId:t.id,toolName:t.name});return}x="approved"}const $=St(await p.do(v,async()=>{try{const g=()=>Promise.resolve(T.execute(t.input,M)),E=await ut(n.telemetry,{id:t.id,input:t.input,name:t.name},g);return{[A]:{ok:E}}}catch(g){if(tt(g))return{[A]:{failed:g.message}};throw g}}));if("failed"in $){await i({content:b(`Error: tool "${t.name}" failed and will not be retried. ${$.failed}`),messageKey:y,role:"tool",stepName:v,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name});return}const R=$.ok;await i({content:b(typeof R=="string"?R:z(R)),messageKey:y,role:"tool",stepName:v,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},kt=(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:ot(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},Mt=(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)}},$t=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=Mt(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const u=await o({env:a,messages:L({history:s.older}),model:n.compaction?.model??n.model});return u.length>0?{history:s.recent,summary:u}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Rt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:u,listMessages:d,memoryContext:c,onTokenDelta:i,run:r,step:l,streamGenerate:p,threadKey:m}=e;return l.do(`llm:turn:${String(t)}`,async()=>{const w=await r(d,{key:m}),{history:v,summary:T}=await $t(e,w);let y={activeTools:o.activeTools,messages:L({history:v,instructions:u,memoryContext:c,summary:T}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(y=kt(y,await o.prepareStep({messages:y.messages,stepNumber:t,steps:n}),a));const k={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 p&&i?p(k,M=>{i({text:M,threadKey:m,turn:t})}):s(k)})},G=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))},It=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}}),F=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},Kt=e=>et({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Nt=async(e,t,n,o)=>{if(e.source===void 0)return;const a=h(e.source),{topK:s}=e,u=S("memory:retrieve",e.key),d=await n.do(u,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return F(d)},At=async(e,t,n,o,a,s)=>{if(n===void 0)return;const u=S("memory:traverse",e.key),d=await a.do(u,async()=>s(o,{owner:n,query:t,...Kt(e.graph)}));return F(d)},Ot=async(e,t,n,o,a)=>{if(t===void 0)return;const s=S("memory:recall",e.key),u={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},d=await o.do(s,async()=>a(n,u));return F(d)},_t=async(e,t)=>e.kind==="episodic"?Ot(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?At(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Nt(e,t.input,t.step,t.run),Ut=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},Dt=async(e,t,n,o,a,s)=>{const u=Ut(P(e));if(u.length===0)return;const d=h(o.graphTraverse),c=h(o.episodeRecall),i=[];for(const r of u){const l=await _t(r,{episodeRecall:c,graphTraverse:d,input:t,owner:n,run:s,step:a});l!==void 0&&i.push(l)}return i.length>0?i.join(`
2
-
3
- `):void 0},Pt=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:u,owner:d,paths:c,run:i,step:r}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const l=rt(t);if(l!==void 0)try{const p={assistantText:a,env:n,model:l.graph?.extractionModel??t.model,userInput:s},m=await r.do(S("memory:extract",l.key),async()=>o(p));await i(h(c.graphUpsert),{...m,messageKey:`${u}:${S("extract",l.key)}`,owner:d})}catch{}},Ft=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:u,owner:d,paths:c,run:i,step:r,threadKey:l}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const p=it(t);if(p!==void 0)try{const m={assistantText:a,env:n,model:p.episodic?.extractionModel??t.model,userInput:s},{summary:w}=await r.do(S("memory:episode",p.key),async()=>o(m));await i(h(c.episodeUpsert),{messageKey:`${u}:${S("episode",p.key)}`,owner:d,summary:w,threadKey:l})}catch{}},jt=async(e,t,n)=>{const o=e[W(t)];if(!(!o||typeof o.get!="function"))try{await(await o.get(n)).terminate()}catch{}},qt="12 hours",bt=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:qt,type:`agent-dequeue:${t}:${n}`})},Bt=async(e,t,n)=>{const o=e.env[W(e.exportName)];if(!o||typeof o.get!="function")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{}},Gt=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{}},Lt=async(e,t,n,o,a)=>{const{instanceId:s,persist:u}=e,d=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const c=n.output!==void 0&&n.text.length===0?z(n.output):n.text;return await u({content:c,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await G(e,{text:n.text,toolCalls:[],turn:t,...d}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await u({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const c of n.toolCalls)await Et(e,c);if(await G(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...d}),o.push(It(n)),a.length>0&&await yt(a,o))return"stopCondition"},Wt=async(e,t,n,o)=>{const a=[];let s,u=!1,d=0;for(let c=0;c<t;c+=1){const i=await Rt(e,c,a);o.value=ft(o.value,i.usage),d=c+1;const r=await Lt(e,c,i,a,n);if(r==="stopCondition"){u=!0;break}if(r!==void 0){s=r.final;break}}return{final:s,stoppedByCondition:u,turnsRun:d}},ee=async e=>{const{agent:t,compact:n,env:o,exportName:a,extractEpisode:s,extractGraph:u,generate:d,instanceId:c,onTokenDelta:i,params:r,paths:l,run:p,step:m,streamGenerate:w}=e,v=t.maxTurns??dt,T=mt(t.stopWhen),y=h(l.appendMessage),k=h(l.completeRun),M=h(l.ensureThread),O=h(l.listMessages),_=h(l.deleteMessage),x=h(l.patchThread),$=h(l.setState),R=h(l.state),g=async f=>{await p(y,{threadKey:r.threadKey,...f})},E=async f=>{await p(x,{key:r.threadKey,...f})},U=async f=>{await p(_,{messageKey:f,threadKey:r.threadKey})},H=async()=>{await g({content:r.input,messageKey:`${c}:user`,role:"user"})},j={dispatched:!1},I=async f=>{j.dispatched=!0;const N=await p(k,{instanceId:c,key:r.threadKey,...f});N?.dequeued!==void 0&&await Bt({env:o,exportName:a,step:m},r.threadKey,N.dequeued)},V=async()=>await p(R,{key:r.threadKey}),X=async f=>{await p($,{key:r.threadKey,state:f})},D=await p(M,{agent:a,instanceId:c,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}});D?.outcome==="replaced"&&await jt(o,a,D.priorInstanceId);const J=await Dt(t,r.input,r.owner,l,m,p),Q=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,Y={agent:t,compact:n,depth:lt(r.depth),env:o,generate:d,getState:V,instanceId:c,instructions:Q,listMessages:O,memoryContext:J,onTokenDelta:i,owner:r.owner,deleteMessage:U,patchThread:E,persist:g,run:p,setState:X,step:m,streamGenerate:w,threadKey:r.threadKey,tools:t.tools??{}},K={value:void 0};try{D?.outcome==="queued"&&await bt(m,r.threadKey,c),await H();const{final:f,stoppedByCondition:N,turnsRun:Z}=await Wt(Y,v,T,K),C=K.value===void 0?{}:{usage:K.value};return await Pt({agent:t,env:o,extractGraph:u,finalText:f?.text,input:r.input,instanceId:c,owner:r.owner,paths:l,run:p,step:m}),await Ft({agent:t,env:o,extractEpisode:s,finalText:f?.text,input:r.input,instanceId:c,owner:r.owner,paths:l,run:p,step:m,threadKey:r.threadKey}),f?(await Gt(t,{env:o,params:r,step:m},{...f,...C}),await I({status:"idle",...C}),{...f,...C}):N?(await I({status:"idle",...C}),{stopped:"stopCondition",turns:Z,...C}):(await I({error:`agent stopped: maxTurns (${String(v)}) reached`,status:"error",...C}),{stopped:"maxTurns",turns:v,...C})}catch(f){throw j.dispatched||await pt(I,f,K.value),f}};export{xt as a,$t as c,st as i,ee as r,Mt as s};
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as N}from"@lunora/workflow";import{jsonSchema as I}from"ai";import{f as L}from"./fnv1a-BNN96GYb.mjs";import{agentBindingName as S}from"../naming.mjs";import{toFunctionReference as v,DEFAULT_AGENT_FUNCTION_PATHS as $}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),P=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",D=t=>t!==null&&typeof t=="object"?t.output:void 0,U=async t=>{await new Promise(e=>{setTimeout(e,t)})},j=async(t,e,n,m)=>{for(let a=0;a<e;a+=1){const i=await t.status(),s=R(i);if(_.has(s))return{output:D(i),status:s};await m(n)}return{output:void 0,status:"timeout"}},k=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},x=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""},W=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 AGENT_* binding)");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=S(e),m=t.maxPolls??P,a=t.pollIntervalMs??M,i=t.wait??U,s=v($.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 o=r.env[n];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no Workflow binding "${n}" on env — declare the "${e}" agent so codegen wires its binding`);const g=`${r.threadKey}::sub::${e}::${r.toolCallId}`,f=`sub-${e}-${L(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:g,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await o.create({id:f,params:A});l=await o.get(d.id)}catch(d){if(!N(d))throw d;l=await o.get(f)}const{output:b,status:u}=await j(l,m,a,i);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(k(b)==="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:g});return x(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{W as agentAsTool};
@@ -1 +0,0 @@
1
- import{l as f}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import{LunoraError as o}from"@lunora/errors";import{h as g,B as p}from"./branch-marker-boZ00zmk.mjs";import{toFunctionReference as w,DEFAULT_AGENT_FUNCTION_PATHS as m}from"./AGENT_MODULE-M4D1EejI.mjs";const T=(r,s,i)=>{const c={},u=w(m.patchThread),d=()=>i??f({env:r,label:"@lunora/agent"});for(const e of s){const a=()=>{const n=r[e.binding];if(!n||typeof n.create!="function"||typeof n.get!="function")throw new o("INTERNAL",`@lunora/agent: no Workflow binding "${e.binding}" on env for agent "${e.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return n};c[e.exportName]={cancel:async n=>{await(await a().get(n)).terminate();try{await d()(u,{instanceId:n,status:"cancelled"})}catch{}},publicRun:e.publicRun===!0,run:async(n,t)=>{if(g(n))throw new o("BAD_REQUEST",`@lunora/agent: run input ${p}`);return{id:(await a().create({...t?.id===void 0?{}:{id:t.id},params:n})).id}},sendEvent:async(n,t)=>{await(await a().get(n)).sendEvent(t)},status:async n=>(await a().get(n)).status()}}return c};export{T as default};
@@ -1 +0,0 @@
1
- import"./DEFAULT_DISPATCH_TIMEOUT_MS-DRXZ0uJJ-CzPOpA2g.mjs";import"./component-shared-G8ngerkU.mjs";import"./createAgentGenerate-BOILDUZj.mjs";import{a as n,c as l,r as u,s as f}from"./agent-loop-CR27O7MC.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"../naming.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./tool-output-Cmk3JWMG.mjs";export{n as approvalTimeoutMs,l as compactHistory,u as runAgentLoop,f as splitForCompaction};