@lunora/agent 1.0.0-alpha.277 → 1.0.0-alpha.278

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 (36) hide show
  1. package/dist/channels.d.mts +2 -2
  2. package/dist/channels.d.ts +2 -2
  3. package/dist/channels.mjs +1 -1
  4. package/dist/core.d.mts +19 -3
  5. package/dist/core.d.ts +19 -3
  6. package/dist/core.mjs +1 -1
  7. package/dist/inbound.d.mts +4 -4
  8. package/dist/inbound.d.ts +4 -4
  9. package/dist/inbound.mjs +1 -1
  10. package/dist/index.d.mts +3 -3
  11. package/dist/index.d.ts +3 -3
  12. package/dist/index.mjs +1 -1
  13. package/dist/packem_chunks/runAgentLoop.mjs +2 -2
  14. package/dist/packem_shared/agentAsTool-BF-7Dnzy.mjs +1 -0
  15. package/dist/packem_shared/app-call-options-BE0CQ6Qg.mjs +1 -0
  16. package/dist/packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs +1 -0
  17. package/dist/packem_shared/createAgentContext-C8k1y2Ot.mjs +1 -0
  18. package/dist/packem_shared/defineAgent-6Ih7L9E9.mjs +3 -0
  19. package/dist/packem_shared/functionTool-Cf433Hdo.mjs +1 -0
  20. package/dist/packem_shared/inbound-shard-A7S7dnf_.mjs +1 -0
  21. package/dist/packem_shared/run-shard-B7iMrAI0.mjs +1 -0
  22. package/dist/packem_shared/{types.d-Bq-ZDGI6.d.mts → types.d-Bzy_Qah6.d.mts} +81 -2
  23. package/dist/packem_shared/{types.d-Bq-ZDGI6.d.ts → types.d-Bzy_Qah6.d.ts} +81 -2
  24. package/dist/packem_shared/withAgentScheduleShard-Bn3bdW5b.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 +1 -1
  32. package/dist/packem_shared/agentAsTool-DiIz7AR0.mjs +0 -1
  33. package/dist/packem_shared/collectAgenticMemoryTools-RTz0T3qJ.mjs +0 -1
  34. package/dist/packem_shared/createAgentContext-CjdW-jip.mjs +0 -1
  35. package/dist/packem_shared/defineAgent-DVPP9V_-.mjs +0 -3
  36. package/dist/packem_shared/functionTool-C95ns65V.mjs +0 -1
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-Bq-ZDGI6.mjs";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-Bq-ZDGI6.mjs";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-Bzy_Qah6.mjs";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-Bzy_Qah6.mjs";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-Bq-ZDGI6.js";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-Bq-ZDGI6.js";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-Bzy_Qah6.js";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-Bzy_Qah6.js";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
package/dist/channels.mjs CHANGED
@@ -1 +1 @@
1
- import{LunoraError as f}from"@lunora/errors";import{isDuplicateInstanceError as x}from"@lunora/workflow";import{h as A,B as N}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{f as R}from"./packem_shared/fnv1a-BNN96GYb.mjs";import{r as S}from"./packem_shared/workflow-binding-Dm9hBzx_.mjs";const k=(t,e)=>{if(t.size<e)return;const n=t.keys().next().value;n!==void 0&&t.delete(n)},C=(t,e,n,r)=>{const a=t.get(e);if(a!==void 0)return a;k(t,r);const s=n().catch(o=>{throw t.get(e)===s&&t.delete(e),o});return t.set(e,s),s},H=new TextEncoder,T=64,_=new Map,M=async t=>C(_,t,async()=>crypto.subtle.importKey("raw",H.encode(t),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),T),v=300,I=/[^0-9a-f]/iu,B=new TextEncoder,l=t=>new Uint8Array(B.encode(t)),u=t=>{if(t.length%2!==0||I.test(t))throw new f("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{return await crypto.subtle.verify("HMAC",await M(t),u(n),l(e))}catch{return!1}},E=(t,e,n)=>Number.isFinite(t)&&Math.abs(e-t)<=n,D=async t=>{const{body:e,now:n=Date.now()/1e3,signature:r,signingSecret:a,timestamp:s,tolerance:o=v}=t;return!r||!s||!r.startsWith("v0=")||!E(Number(s),n,o)?!1:b(a,`v0:${s}:${e}`,r.slice(3))},K=async t=>{const{body:e,secret:n,signature:r}=t;return r?.startsWith("sha256=")?b(n,e,r.slice(7)):!1},O=async t=>{const{body:e,now:n=Date.now()/1e3,publicKey:r,signature:a,timestamp:s,tolerance:o=v}=t;if(!a||!s||!E(Number(s),n,o))return!1;try{const c=await crypto.subtle.importKey("raw",u(r),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},c,u(a),l(s+e))}catch{return!1}},U=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"},$=(t,e)=>{if(typeof t=="function")return t(e);const n=e[t];return typeof n=="string"?n:void 0},j=async(t,e,n,r)=>{switch(t){case"discord":return O({body:r,publicKey:e,signature:n.get("x-signature-ed25519")??void 0,timestamp:n.get("x-signature-timestamp")??void 0});case"github":return K({body:r,secret:e,signature:n.get("x-hub-signature-256")??void 0});case"slack":return D({body:r,signature:n.get("x-slack-signature")??void 0,signingSecret:e,timestamp:n.get("x-slack-request-timestamp")??void 0});default:return!1}},J=(t,e)=>{if(t==="discord")try{if(JSON.parse(e).type===1)return Response.json({type:1})}catch{}},m=()=>new Response(void 0,{status:200}),L=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",l(t)))].map(e=>e.toString(16).padStart(2,"0")).join(""),z=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 L(e)},F=async(t,e,n,r)=>{if(A(e))throw new f("BAD_REQUEST",`@lunora/agent: inbound channel run params ${N}`);try{await t.create({id:`${n}-${R(r)}`,params:e})}catch(a){if(x(a))return m();throw a}return m()},Y=t=>async(e,n,r)=>{const a=await e.text(),s=U(e.headers);if(s===void 0)return new Response("Unrecognized webhook",{status:400});const o=t.map(i=>({config:i.agent.onInbound,target:i})).filter(i=>i.config?.channel===s),c={channel:s,headers:e.headers,json:()=>JSON.parse(a),rawBody:a};let d=!1;for(const{config:i,target:g}of o){const y=$(i.secret,n);if(y===void 0||!await j(s,y,e.headers,a))continue;d=!0;const h=J(s,a);if(h)return h;const p=await i.map(c);if(!p)continue;const w=S(n,r.exports,g.className,["create"]);if(w===void 0)throw new f("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 F(w,p,s,await z(s,a))}return d?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{Y as dispatchAgentChannel,O as verifyDiscord,K as verifyGithub,D as verifySlack};
1
+ import{LunoraError as l}from"@lunora/errors";import{isDuplicateInstanceError as k}from"@lunora/workflow";import{h as N,B as C}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{f as H}from"./packem_shared/fnv1a-BNN96GYb.mjs";import{w as I}from"./packem_shared/run-shard-B7iMrAI0.mjs";import{r as T}from"./packem_shared/workflow-binding-Dm9hBzx_.mjs";import{r as _}from"./packem_shared/inbound-shard-A7S7dnf_.mjs";const M=(t,e)=>{if(t.size<e)return;const r=t.keys().next().value;r!==void 0&&t.delete(r)},O=(t,e,r,s)=>{const a=t.get(e);if(a!==void 0)return a;M(t,s);const n=r().catch(o=>{throw t.get(e)===n&&t.delete(e),o});return t.set(e,n),n},B=new TextEncoder,K=64,U=new Map,j=async t=>O(U,t,async()=>crypto.subtle.importKey("raw",B.encode(t),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),K),S=300,D=/[^0-9a-f]/iu,J=new TextEncoder,g=t=>new Uint8Array(J.encode(t)),d=t=>{if(t.length%2!==0||D.test(t))throw new l("BAD_REQUEST","@lunora/agent: malformed hex signature");const e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r+=1)e[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return e},E=async(t,e,r)=>{try{return await crypto.subtle.verify("HMAC",await j(t),d(r),g(e))}catch{return!1}},A=(t,e,r)=>Number.isFinite(t)&&Math.abs(e-t)<=r,L=async t=>{const{body:e,now:r=Date.now()/1e3,signature:s,signingSecret:a,timestamp:n,tolerance:o=S}=t;return!s||!n||!s.startsWith("v0=")||!A(Number(n),r,o)?!1:E(a,`v0:${n}:${e}`,s.slice(3))},W=async t=>{const{body:e,secret:r,signature:s}=t;return s?.startsWith("sha256=")?E(r,e,s.slice(7)):!1},$=async t=>{const{body:e,now:r=Date.now()/1e3,publicKey:s,signature:a,timestamp:n,tolerance:o=S}=t;if(!a||!n||!A(Number(n),r,o))return!1;try{const u=await crypto.subtle.importKey("raw",d(s),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},u,d(a),g(n+e))}catch{return!1}},P=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"},z=(t,e)=>{if(typeof t=="function")return t(e);const r=e[t];return typeof r=="string"?r:void 0},F=async(t,e,r,s)=>{switch(t){case"discord":return $({body:s,publicKey:e,signature:r.get("x-signature-ed25519")??void 0,timestamp:r.get("x-signature-timestamp")??void 0});case"github":return W({body:s,secret:e,signature:r.get("x-hub-signature-256")??void 0});case"slack":return L({body:s,signature:r.get("x-slack-signature")??void 0,signingSecret:e,timestamp:r.get("x-slack-request-timestamp")??void 0});default:return!1}},Q=(t,e)=>{if(t==="discord")try{if(JSON.parse(e).type===1)return Response.json({type:1})}catch{}},b=()=>new Response(void 0,{status:200}),X=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",g(t)))].map(e=>e.toString(16).padStart(2,"0")).join(""),f=t=>{try{const e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}},x=t=>t.startsWith("payload=")?f(String(new URLSearchParams(t).get("payload"))):f(t)??Object.fromEntries(new URLSearchParams(t)),G=(t,e)=>e.startsWith("payload=")?x(e)===void 0:t!=="slack"&&f(e)===void 0,c=t=>typeof t=="string"&&t!==""?t:typeof t=="number"?String(t):void 0,Y=(t,e)=>{const r=x(e);if(r!==void 0)return t==="slack"?c(r.team_id)??c(r.team?.id):c(t==="github"?r.installation?.id:r.guild_id)},V=async(t,e)=>{if(t!=="github")try{const r=JSON.parse(e),s=t==="slack"?r.event_id:r.id;if(typeof s=="string"&&s!=="")return s}catch{}return X(e)},Z=async(t,e,r)=>{const{channel:s,id:a,shardKey:n}=r;if(N(e))throw new l("BAD_REQUEST",`@lunora/agent: inbound channel run params ${C}`);try{await t.create({id:`${s}-${H(a)}`,params:I(e,n)})}catch(o){if(k(o))return b();throw o}return b()},ot=t=>async(e,r,s)=>{const a=await e.text(),n=P(e.headers);if(n===void 0)return new Response("Unrecognized webhook",{status:400});const o=t.map(i=>({config:i.agent.onInbound,target:i})).filter(i=>i.config?.channel===n),u={channel:n,headers:e.headers,json:()=>JSON.parse(a),rawBody:a};let h=!1;for(const{config:i,target:p}of o){const y=z(i.secret,r);if(y===void 0||!await F(n,y,e.headers,a))continue;h=!0;const m=Q(n,a);if(m)return m;if(G(n,a))return new Response("Malformed webhook body",{status:400});const w=await i.map(u);if(!w)continue;const v=T(r,s.exports,p.className,["create"]);if(v===void 0)throw new l("INTERNAL",`@lunora/agent: no "${p.className}" on ctx.exports or env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`);const R=await _(i.resolveShard,{channel:n,workspaceId:Y(n,a)},"onInbound.resolveShard");return await Z(v,w,{channel:n,id:await V(n,a),shardKey:R})}return h?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{ot as dispatchAgentChannel,$ as verifyDiscord,W as verifyGithub,L as verifySlack};
package/dist/core.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { x as AgentBindingSpec, l as AgentRunFunction, D as AgentHandle, q as AgentConfig, A as AgentDefinition, Z as AgentToolConfig, c as AgentToolDefinition, v as AgentFunctionReference, a3 as SkillConfig, b as SkillDefinition, k as AgentFunctionPaths, j as AgentRunInput, o as AgentRunResult } from "./packem_shared/types.d-Bq-ZDGI6.mjs";
2
- export type { w as AgentApprovalContext, s as AgentAsToolOptions, y as AgentEmailMapper, z as AgentEmailRun, h as AgentGenerate, B as AgentGenerateOptions, C as AgentGenerateResult, E as AgentInstructionsContext, F as AgentLiveEvent, G as AgentMemoryOptions, H as AgentMemorySource, p as AgentMessageRow, J as AgentMessageStatus, u as AgentModelInput, K as AgentOnReply, L as AgentOnStepFinish, M as AgentPrepareStep, N as AgentPrepareStepInput, O as AgentPrepareStepResult, P as AgentProgressEvent, Q as AgentReplyInfo, a as AgentReplyRef, R as AgentRunHandle, T as AgentRunOptions, U as AgentStepFinishInfo, V as AgentStepInfo, m as AgentStepLike, n as AgentStreamGenerate, t as AgentSubToolInput, W as AgentThreadStatus, X as AgentTokenDelta, i as AgentTokenSink, Y as AgentToolCall, d as AgentToolContext, _ as AgentUsage, $ as AgentVoiceConfig, a0 as AgentWorkflowBindingLike, a1 as AgentWorkflowInstanceLike, r as AnyAgentTool, a2 as EnsureThreadOutcome } from "./packem_shared/types.d-Bq-ZDGI6.mjs";
1
+ import { x as AgentBindingSpec, l as AgentRunFunction, F as AgentHandle, q as AgentConfig, A as AgentDefinition, a0 as AgentToolConfig, c as AgentToolDefinition, v as AgentFunctionReference, a6 as SkillConfig, b as SkillDefinition, k as AgentFunctionPaths, j as AgentRunInput, o as AgentRunResult } from "./packem_shared/types.d-Bzy_Qah6.mjs";
2
+ export type { w as AgentApprovalContext, s as AgentAsToolOptions, z as AgentEmailMapper, B as AgentEmailRun, h as AgentGenerate, D as AgentGenerateOptions, E as AgentGenerateResult, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, p as AgentMessageRow, M as AgentMessageStatus, u as AgentModelInput, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, m as AgentStepLike, n as AgentStreamGenerate, t as AgentSubToolInput, Z as AgentThreadStatus, _ as AgentTokenDelta, i as AgentTokenSink, $ as AgentToolCall, d as AgentToolContext, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, r as AnyAgentTool, a5 as EnsureThreadOutcome } from "./packem_shared/types.d-Bzy_Qah6.mjs";
3
3
  import { FlexibleSchema } from 'ai';
4
4
  import { jsonSchema as jsonSchema$1, ValidationResult, Schema } from '@ai-sdk/provider-utils';
5
5
  import { WorkflowDefinition } from '@lunora/workflow';
@@ -16,11 +16,16 @@ import '@lunora/mail/inbound';
16
16
  * and the env-backed `createDispatchRunner` (the same runner the workflow body
17
17
  * uses — it POSTs to `/_lunora/scheduler/dispatch`) is built on demand; tests
18
18
  * inject a `dispatch` double.
19
+ *
20
+ * `shardKey` is the shard of the ctx this producer rides (the generated shard passes
21
+ * its own). Every run started here carries it, so the run's tools reach the same
22
+ * tenant's `.shardBy(...)` data the starting mutation could; absent for the default shard.
19
23
  * @experimental
20
24
  */
21
25
  declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
22
26
  dispatch?: AgentRunFunction;
23
27
  exports?: unknown;
28
+ shardKey?: string;
24
29
  }) => Record<string, AgentHandle>;
25
30
  /**
26
31
  * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
@@ -117,6 +122,17 @@ declare const functionTool: <Input extends Record<string, unknown> = Record<stri
117
122
  declare const jsonSchema: <OBJECT = unknown>(schema: Parameters<typeof jsonSchema$1>[0], { validate }?: {
118
123
  validate?: (value: unknown) => PromiseLike<ValidationResult<OBJECT>> | ValidationResult<OBJECT>;
119
124
  }) => Schema<OBJECT>;
125
+ /**
126
+ * The shard DO's `ctx.scheduler`, with every agent target stamped with the scheduling
127
+ * shard (`RunOptions.shardKey`) unless the app named one. A function job only lands on a
128
+ * shard the app names, but a scheduled agent run is the same act as `ctx.agents.<name>.run`
129
+ * from this shard, so its tools read this tenant's data like an immediate run's do. The
130
+ * stamp travels on the scheduler record, which the worker trusts over the job's args
131
+ * (`WorkerOptions.agentWorkflows`); it is applied before the deferral facade buffers the
132
+ * call, so an outbox retry replays it.
133
+ * @experimental
134
+ */
135
+ declare const withAgentScheduleShard: <S extends object>(scheduler: S, specs: ReadonlyArray<AgentBindingSpec>, shardKey: string) => S;
120
136
  /**
121
137
  * Declare a reusable skill: a bundle of expertise — an instruction fragment,
122
138
  * tools, and retrieval `knowledge` — an agent composes in via
@@ -185,4 +201,4 @@ export { type AgentBindingSpec, type AgentConfig, type AgentDefinition, type Age
185
201
  * run. The `@lunora/agent` barrel re-exports all of this plus the heavy tools and
186
202
  * runtime, so importing from it puts them back in the startup graph.
187
203
  */
188
- createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema };
204
+ createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard };
package/dist/core.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { x as AgentBindingSpec, l as AgentRunFunction, D as AgentHandle, q as AgentConfig, A as AgentDefinition, Z as AgentToolConfig, c as AgentToolDefinition, v as AgentFunctionReference, a3 as SkillConfig, b as SkillDefinition, k as AgentFunctionPaths, j as AgentRunInput, o as AgentRunResult } from "./packem_shared/types.d-Bq-ZDGI6.js";
2
- export type { w as AgentApprovalContext, s as AgentAsToolOptions, y as AgentEmailMapper, z as AgentEmailRun, h as AgentGenerate, B as AgentGenerateOptions, C as AgentGenerateResult, E as AgentInstructionsContext, F as AgentLiveEvent, G as AgentMemoryOptions, H as AgentMemorySource, p as AgentMessageRow, J as AgentMessageStatus, u as AgentModelInput, K as AgentOnReply, L as AgentOnStepFinish, M as AgentPrepareStep, N as AgentPrepareStepInput, O as AgentPrepareStepResult, P as AgentProgressEvent, Q as AgentReplyInfo, a as AgentReplyRef, R as AgentRunHandle, T as AgentRunOptions, U as AgentStepFinishInfo, V as AgentStepInfo, m as AgentStepLike, n as AgentStreamGenerate, t as AgentSubToolInput, W as AgentThreadStatus, X as AgentTokenDelta, i as AgentTokenSink, Y as AgentToolCall, d as AgentToolContext, _ as AgentUsage, $ as AgentVoiceConfig, a0 as AgentWorkflowBindingLike, a1 as AgentWorkflowInstanceLike, r as AnyAgentTool, a2 as EnsureThreadOutcome } from "./packem_shared/types.d-Bq-ZDGI6.js";
1
+ import { x as AgentBindingSpec, l as AgentRunFunction, F as AgentHandle, q as AgentConfig, A as AgentDefinition, a0 as AgentToolConfig, c as AgentToolDefinition, v as AgentFunctionReference, a6 as SkillConfig, b as SkillDefinition, k as AgentFunctionPaths, j as AgentRunInput, o as AgentRunResult } from "./packem_shared/types.d-Bzy_Qah6.js";
2
+ export type { w as AgentApprovalContext, s as AgentAsToolOptions, z as AgentEmailMapper, B as AgentEmailRun, h as AgentGenerate, D as AgentGenerateOptions, E as AgentGenerateResult, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, p as AgentMessageRow, M as AgentMessageStatus, u as AgentModelInput, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, m as AgentStepLike, n as AgentStreamGenerate, t as AgentSubToolInput, Z as AgentThreadStatus, _ as AgentTokenDelta, i as AgentTokenSink, $ as AgentToolCall, d as AgentToolContext, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, r as AnyAgentTool, a5 as EnsureThreadOutcome } from "./packem_shared/types.d-Bzy_Qah6.js";
3
3
  import { FlexibleSchema } from 'ai';
4
4
  import { jsonSchema as jsonSchema$1, ValidationResult, Schema } from '@ai-sdk/provider-utils';
5
5
  import { WorkflowDefinition } from '@lunora/workflow';
@@ -16,11 +16,16 @@ import '@lunora/mail/inbound';
16
16
  * and the env-backed `createDispatchRunner` (the same runner the workflow body
17
17
  * uses — it POSTs to `/_lunora/scheduler/dispatch`) is built on demand; tests
18
18
  * inject a `dispatch` double.
19
+ *
20
+ * `shardKey` is the shard of the ctx this producer rides (the generated shard passes
21
+ * its own). Every run started here carries it, so the run's tools reach the same
22
+ * tenant's `.shardBy(...)` data the starting mutation could; absent for the default shard.
19
23
  * @experimental
20
24
  */
21
25
  declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
22
26
  dispatch?: AgentRunFunction;
23
27
  exports?: unknown;
28
+ shardKey?: string;
24
29
  }) => Record<string, AgentHandle>;
25
30
  /**
26
31
  * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
@@ -117,6 +122,17 @@ declare const functionTool: <Input extends Record<string, unknown> = Record<stri
117
122
  declare const jsonSchema: <OBJECT = unknown>(schema: Parameters<typeof jsonSchema$1>[0], { validate }?: {
118
123
  validate?: (value: unknown) => PromiseLike<ValidationResult<OBJECT>> | ValidationResult<OBJECT>;
119
124
  }) => Schema<OBJECT>;
125
+ /**
126
+ * The shard DO's `ctx.scheduler`, with every agent target stamped with the scheduling
127
+ * shard (`RunOptions.shardKey`) unless the app named one. A function job only lands on a
128
+ * shard the app names, but a scheduled agent run is the same act as `ctx.agents.<name>.run`
129
+ * from this shard, so its tools read this tenant's data like an immediate run's do. The
130
+ * stamp travels on the scheduler record, which the worker trusts over the job's args
131
+ * (`WorkerOptions.agentWorkflows`); it is applied before the deferral facade buffers the
132
+ * call, so an outbox retry replays it.
133
+ * @experimental
134
+ */
135
+ declare const withAgentScheduleShard: <S extends object>(scheduler: S, specs: ReadonlyArray<AgentBindingSpec>, shardKey: string) => S;
120
136
  /**
121
137
  * Declare a reusable skill: a bundle of expertise — an instruction fragment,
122
138
  * tools, and retrieval `knowledge` — an agent composes in via
@@ -185,4 +201,4 @@ export { type AgentBindingSpec, type AgentConfig, type AgentDefinition, type Age
185
201
  * run. The `@lunora/agent` barrel re-exports all of this plus the heavy tools and
186
202
  * runtime, so importing from it puts them back in the startup graph.
187
203
  */
188
- createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema };
204
+ createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard };
package/dist/core.mjs CHANGED
@@ -1 +1 @@
1
- import{default as t}from"./packem_shared/createAgentContext-CjdW-jip.mjs";import{defineAgent as n,defineAgentTool as i,isAgentDefinition as r}from"./packem_shared/defineAgent-DVPP9V_-.mjs";import{functionTool as a}from"./packem_shared/functionTool-C95ns65V.mjs";import{default as p}from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{defineSkill as d,isSkillDefinition as s}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as A}from"./packem_shared/compileAgentWorkflow-yZB8fbYc.mjs";export{A as compileAgentWorkflow,t as createAgentContext,n as defineAgent,i as defineAgentTool,d as defineSkill,a as functionTool,r as isAgentDefinition,s as isSkillDefinition,p as jsonSchema};
1
+ import{default as t}from"./packem_shared/createAgentContext-C8k1y2Ot.mjs";import{defineAgent as n,defineAgentTool as r,isAgentDefinition as i}from"./packem_shared/defineAgent-6Ih7L9E9.mjs";import{functionTool as a}from"./packem_shared/functionTool-Cf433Hdo.mjs";import{default as m}from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{default as x}from"./packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs";import{defineSkill as g,isSkillDefinition as u}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as c}from"./packem_shared/compileAgentWorkflow-yZB8fbYc.mjs";export{c as compileAgentWorkflow,t as createAgentContext,n as defineAgent,r as defineAgentTool,g as defineSkill,a as functionTool,i as isAgentDefinition,u as isSkillDefinition,m as jsonSchema,x as withAgentScheduleShard};
@@ -1,4 +1,4 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-Bq-ZDGI6.mjs";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-Bzy_Qah6.mjs";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -7,10 +7,10 @@ import 'ai';
7
7
  */
8
8
  interface AgentEmailTarget {
9
9
  /**
10
- * The agent definition — only its `onEmail` mapper is read, deciding whether
11
- * this agent claims the message and, if so, the run to start.
10
+ * The agent definition — its `onEmail` mapper decides whether this agent claims
11
+ * the message and the run to start; `resolveEmailShard` picks the run's shard.
12
12
  */
13
- agent: Pick<AgentDefinition, "onEmail">;
13
+ agent: Pick<AgentDefinition, "onEmail" | "resolveEmailShard">;
14
14
  /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
15
15
  className: string;
16
16
  }
package/dist/inbound.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-Bq-ZDGI6.js";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-Bzy_Qah6.js";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
@@ -7,10 +7,10 @@ import 'ai';
7
7
  */
8
8
  interface AgentEmailTarget {
9
9
  /**
10
- * The agent definition — only its `onEmail` mapper is read, deciding whether
11
- * this agent claims the message and, if so, the run to start.
10
+ * The agent definition — its `onEmail` mapper decides whether this agent claims
11
+ * the message and the run to start; `resolveEmailShard` picks the run's shard.
12
12
  */
13
- agent: Pick<AgentDefinition, "onEmail">;
13
+ agent: Pick<AgentDefinition, "onEmail" | "resolveEmailShard">;
14
14
  /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
15
15
  className: string;
16
16
  }
package/dist/inbound.mjs CHANGED
@@ -1 +1 @@
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};
1
+ import{createInboundEmailHandler as m,authenticatesFrom as d,parseInboundEmail as u}from"@lunora/mail/inbound";import{h as p,B as g}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{w as f}from"./packem_shared/run-shard-B7iMrAI0.mjs";import{r as E}from"./packem_shared/workflow-binding-Dm9hBzx_.mjs";import{r as h}from"./packem_shared/inbound-shard-A7S7dnf_.mjs";const v="message could not be processed",c=(o,s)=>{console.error("@lunora/agent/inbound: bouncing message —",s),o.message.setReject(v)},I=o=>{const s=m({dispatch:async(a,e)=>{for(const r of o){const t=r.agent.onEmail;if(!t)continue;const n=await t(a);if(n==null)continue;const i=E(e.env,e.ctx?.exports,r.className,["create"]);if(i===void 0){c(e,`@lunora/agent: no "${r.className}" on ctx.exports or env for an inbound agent — run codegen/dev so wrangler.jsonc declares it`);return}if(p(n)){c(e,`@lunora/agent: inbound run params ${g}`);return}const l=await h(r.agent.resolveEmailShard,{email:a,envelopeTo:e.message.to},"resolveEmailShard");await i.create({params:f(n,l)});return}},parse:u,verify:d});return async(a,e,r)=>s(a,e,r)};export{I as dispatchAgentEmail};
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
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 AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-Bq-ZDGI6.mjs";
2
- export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentEmailMapper, z as AgentEmailRun, B as AgentGenerateOptions, C as AgentGenerateResult, D as AgentHandle, E as AgentInstructionsContext, F as AgentLiveEvent, G as AgentMemoryOptions, H as AgentMemorySource, J as AgentMessageStatus, K as AgentOnReply, L as AgentOnStepFinish, M as AgentPrepareStep, N as AgentPrepareStepInput, O as AgentPrepareStepResult, P as AgentProgressEvent, Q as AgentReplyInfo, a as AgentReplyRef, R as AgentRunHandle, T as AgentRunOptions, U as AgentStepFinishInfo, V as AgentStepInfo, W as AgentThreadStatus, X as AgentTokenDelta, Y as AgentToolCall, Z as AgentToolConfig, _ as AgentUsage, $ as AgentVoiceConfig, a0 as AgentWorkflowBindingLike, a1 as AgentWorkflowInstanceLike, a2 as EnsureThreadOutcome, a3 as SkillConfig } from "./packem_shared/types.d-Bq-ZDGI6.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 AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-Bzy_Qah6.mjs";
2
+ export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentChannelShardInput, z as AgentEmailMapper, B as AgentEmailRun, C as AgentEmailShardInput, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentHandle, G as AgentInboundShardResolver, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, M as AgentMessageStatus, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, Z as AgentThreadStatus, _ as AgentTokenDelta, $ as AgentToolCall, a0 as AgentToolConfig, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, a5 as EnsureThreadOutcome, a6 as SkillConfig } from "./packem_shared/types.d-Bzy_Qah6.mjs";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
4
- export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema } from "./core.mjs";
4
+ export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard } from "./core.mjs";
5
5
  import { LanguageModel, ModelMessage } from 'ai';
6
6
  export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.mjs";
7
7
  export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
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 AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-Bq-ZDGI6.js";
2
- export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentEmailMapper, z as AgentEmailRun, B as AgentGenerateOptions, C as AgentGenerateResult, D as AgentHandle, E as AgentInstructionsContext, F as AgentLiveEvent, G as AgentMemoryOptions, H as AgentMemorySource, J as AgentMessageStatus, K as AgentOnReply, L as AgentOnStepFinish, M as AgentPrepareStep, N as AgentPrepareStepInput, O as AgentPrepareStepResult, P as AgentProgressEvent, Q as AgentReplyInfo, a as AgentReplyRef, R as AgentRunHandle, T as AgentRunOptions, U as AgentStepFinishInfo, V as AgentStepInfo, W as AgentThreadStatus, X as AgentTokenDelta, Y as AgentToolCall, Z as AgentToolConfig, _ as AgentUsage, $ as AgentVoiceConfig, a0 as AgentWorkflowBindingLike, a1 as AgentWorkflowInstanceLike, a2 as EnsureThreadOutcome, a3 as SkillConfig } from "./packem_shared/types.d-Bq-ZDGI6.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 AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-Bzy_Qah6.js";
2
+ export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentChannelShardInput, z as AgentEmailMapper, B as AgentEmailRun, C as AgentEmailShardInput, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentHandle, G as AgentInboundShardResolver, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, M as AgentMessageStatus, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, Z as AgentThreadStatus, _ as AgentTokenDelta, $ as AgentToolCall, a0 as AgentToolConfig, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, a5 as EnsureThreadOutcome, a6 as SkillConfig } from "./packem_shared/types.d-Bzy_Qah6.js";
3
3
  export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
4
- export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema } from "./core.js";
4
+ export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard } from "./core.js";
5
5
  import { LanguageModel, ModelMessage } from 'ai';
6
6
  export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.js";
7
7
  export { agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{runAgentLoop as r,splitForCompaction as t}from"./packem_chunks/runAgentLoop.mjs";import{collectAgenticMemoryTools as n,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-RTz0T3qJ.mjs";import{agentAsTool as m}from"./packem_shared/agentAsTool-DiIz7AR0.mjs";import{codeTool as s}from"./packem_shared/codeTool-Cn8TuNjk.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as d}from"./packem_shared/createAgentContext-CjdW-jip.mjs";import{defineAgent as g,defineAgentTool as u,isAgentDefinition as S}from"./packem_shared/defineAgent-DVPP9V_-.mjs";import{functionTool as N}from"./packem_shared/functionTool-C95ns65V.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as U}from"./packem_chunks/createAgentGenerate.mjs";import{jsCodeTool as w}from"./packem_shared/jsCodeTool-BJB3Fpm2.mjs";import{default as G}from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{adaptMcpResult as v,mcpTools as L}from"./packem_shared/adaptMcpResult-CA-3ovJd.mjs";import{buildModelMessages as B}from"./packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as V,agentDefaultName as j,voiceBindingName as H,voiceClassName as I}from"./naming.mjs";import{AGENT_MODULE as X,DEFAULT_AGENT_FUNCTION_PATHS as q,SANDBOX_INVOKE_PATH as y,SANDBOX_MODULE as K,toFunctionReference as W}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as J,containerFsTool as Q,containerTool as Y,fsTool as Z}from"./sandbox.mjs";import{SecretUnavailableError as ee,requestSecretTool as oe,withSecret as re}from"./packem_shared/SecretUnavailableError-DOy2M4Ak.mjs";import{defineSkill as ae,isSkillDefinition as ne}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as le}from"./packem_shared/wrapUntrusted-BuHBC6sV.mjs";import{default as pe}from"./packem_shared/VoiceSessionDO-CdvG2L-D.mjs";import{r as ie}from"./packem_shared/voice-turn-B9omvXoR.mjs";import{webSearchTool as xe}from"./packem_shared/webSearchTool-BzXW0R4r.mjs";import{default as de}from"./packem_shared/compileAgentWorkflow-yZB8fbYc.mjs";export{X as AGENT_MODULE,q as DEFAULT_AGENT_FUNCTION_PATHS,y as SANDBOX_INVOKE_PATH,K as SANDBOX_MODULE,ee as SecretUnavailableError,pe as VoiceSessionDO,v as adaptMcpResult,m as agentAsTool,V as agentClassName,c as agentComponent,j as agentDefaultName,x as agentExtension,J as browserTool,B as buildModelMessages,s as codeTool,n as collectAgenticMemoryTools,de as compileAgentWorkflow,Q as containerFsTool,Y as containerTool,d as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,g as defineAgent,u as defineAgentTool,ae as defineSkill,Z as fsTool,N as functionTool,S as isAgentDefinition,ne as isSkillDefinition,w as jsCodeTool,G as jsonSchema,L as mcpTools,oe as requestSecretTool,U as resolveAgentModel,r as runAgentLoop,ie as runVoiceTurn,t as splitForCompaction,W as toFunctionReference,f as toSearchResults,H as voiceBindingName,I as voiceClassName,xe as webSearchTool,re as withSecret,le as wrapUntrusted};
1
+ import{runAgentLoop as r,splitForCompaction as t}from"./packem_chunks/runAgentLoop.mjs";import{collectAgenticMemoryTools as n,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as m}from"./packem_shared/agentAsTool-BF-7Dnzy.mjs";import{codeTool as s}from"./packem_shared/codeTool-Cn8TuNjk.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as T}from"./packem_shared/createAgentContext-C8k1y2Ot.mjs";import{defineAgent as A,defineAgentTool as g,isAgentDefinition as S}from"./packem_shared/defineAgent-6Ih7L9E9.mjs";import{functionTool as N}from"./packem_shared/functionTool-Cf433Hdo.mjs";import{createAgentGenerate as h,createEpisodeExtract as C,createGraphExtract as M,createStreamGenerate as O,resolveAgentModel as _}from"./packem_chunks/createAgentGenerate.mjs";import{jsCodeTool as U}from"./packem_shared/jsCodeTool-BJB3Fpm2.mjs";import{default as G}from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{adaptMcpResult as v,mcpTools as L}from"./packem_shared/adaptMcpResult-CA-3ovJd.mjs";import{buildModelMessages as B}from"./packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as V,agentDefaultName as j,voiceBindingName as H,voiceClassName as I}from"./naming.mjs";import{AGENT_MODULE as X,DEFAULT_AGENT_FUNCTION_PATHS as q,SANDBOX_INVOKE_PATH as y,SANDBOX_MODULE as K,toFunctionReference as W}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as J,containerFsTool as Q,containerTool as Y,fsTool as Z}from"./sandbox.mjs";import{default as ee}from"./packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs";import{SecretUnavailableError as re,requestSecretTool as te,withSecret as ae}from"./packem_shared/SecretUnavailableError-DOy2M4Ak.mjs";import{defineSkill as fe,isSkillDefinition as le}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as pe}from"./packem_shared/wrapUntrusted-BuHBC6sV.mjs";import{default as ie}from"./packem_shared/VoiceSessionDO-CdvG2L-D.mjs";import{r as xe}from"./packem_shared/voice-turn-B9omvXoR.mjs";import{webSearchTool as Te}from"./packem_shared/webSearchTool-BzXW0R4r.mjs";import{default as Ae}from"./packem_shared/compileAgentWorkflow-yZB8fbYc.mjs";export{X as AGENT_MODULE,q as DEFAULT_AGENT_FUNCTION_PATHS,y as SANDBOX_INVOKE_PATH,K as SANDBOX_MODULE,re as SecretUnavailableError,ie as VoiceSessionDO,v as adaptMcpResult,m as agentAsTool,V as agentClassName,c as agentComponent,j as agentDefaultName,x as agentExtension,J as browserTool,B as buildModelMessages,s as codeTool,n as collectAgenticMemoryTools,Ae as compileAgentWorkflow,Q as containerFsTool,Y as containerTool,T as createAgentContext,h as createAgentGenerate,C as createEpisodeExtract,M as createGraphExtract,O as createStreamGenerate,A as defineAgent,g as defineAgentTool,fe as defineSkill,Z as fsTool,N as functionTool,S as isAgentDefinition,le as isSkillDefinition,U as jsCodeTool,G as jsonSchema,L as mcpTools,te as requestSecretTool,_ as resolveAgentModel,r as runAgentLoop,xe as runVoiceTurn,t as splitForCompaction,W as toFunctionReference,f as toSearchResults,H as voiceBindingName,I as voiceClassName,Te as webSearchTool,ee as withAgentScheduleShard,ae as withSecret,pe as wrapUntrusted};
@@ -1,3 +1,3 @@
1
- import{usageStatus as ut}from"@lunora/ai/create";import{e as dt}from"../packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as lt}from"@lunora/platform";import{r as X}from"../packem_shared/workflow-binding-Dm9hBzx_.mjs";import{d as pt,a as Q,S as Y}from"../packem_shared/component-shared--SPcu0Iw.mjs";import{usageOfFailedTurn as mt,resolveAgentModel as yt}from"./createAgentGenerate.mjs";import{r as ft,f as ht,m as C,a as wt}from"../packem_shared/memory-JI0lUu84.mjs";import{buildModelMessages as j}from"../packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as V}from"../naming.mjs";import{toFunctionReference as v}from"../packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{i as gt}from"../packem_shared/positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as vt,secretLabelOf as Tt}from"../packem_shared/SecretUnavailableError-DOy2M4Ak.mjs";import{combineTelemetry as St}from"../packem_shared/combineTelemetry-DgE9W9G8.mjs";import{c as z}from"../packem_shared/tool-output-Cmk3JWMG.mjs";const $t=200,Et=e=>{const t=e.findIndex(a=>a.role!=="tool");return t===-1?[]:e.slice(t)},xt=async e=>{let t=$t;for(;;){const a=await e(t),o=Et(a);if(o.length>0||a.length<t)return o;t*=2}},Ct=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const a=Array.isArray(t)?t:[t];return a.length===0?void 0:St(...a)},Rt=async e=>{e===void 0||e.isEnabled===!1||await Promise.all([e.integrations].flat().map(async t=>{try{await t?.flush?.()}catch{}}))},It=async(e,t,a)=>{const o=Ct(e);if(o===void 0)return a();const n={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:n,toolContext:void 0},i=Date.now();await o.onToolExecutionStart?.(s);let c;const d=()=>(c??=a(),c);try{if(o.executeTool===void 0)await d();else try{await o.executeTool({...s,execute:d,toolCallId:t.id})}catch{}const u=await d();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,input:t.input,output:u,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),u}catch(u){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:u,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),u}},kt=8,Kt=e=>gt(e)?e:0,Z=e=>e===void 0?"null":JSON.stringify(e),Mt=async(e,t,a)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...a===void 0?{}:{usage:a}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},Nt=e=>e===void 0?[]:[e].flat(),Ot=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),At=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],W=e=>e.status??ut(e),_t=(e,t)=>e===t?e:"partial",tt=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:W(t)};const a={status:_t(W(e),W(t))};for(const o of At)(e[o]!==void 0||t[o]!==void 0)&&(a[o]=(e[o]??0)+(t[o]??0));return a},qt=async(e,t,a,o,n,s)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:a.do(o,async()=>await s()?!1:i===!0||i(t,n))},Ut="WorkflowTimeoutError",et=e=>e instanceof Error&&e.name===Ut,bt=async(e,t)=>{const{agent:a,deleteMessage:o,instanceId:n,patchThread:s,persist:i,step:c}=e,d=Q(a.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+d,messageKey:`${n}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"})});const u=await c.waitForEvent(`approval:${t.id}`,{timeout:d,type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note},...p.payload.scope===void 0?{}:{scope:p.payload.scope}})).catch(p=>{if(!et(p))throw p;return{decision:"reject",note:"approval timed out"}});return await o(`${n}:approval:${t.id}`),await s({status:"running"}),u},Dt={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Ft=(e,t)=>`${String(e)}:${t}`,Gt=async(e,t,a,o,n)=>{const{agent:s,deleteMessage:i,instanceId:c,openSecretRef:d,patchThread:u,persist:p,run:r,settleSecretRef:l,step:m,threadKey:h}=e,T=`${c}:secret:${n}`,y=Math.min(Q(s.approvalTimeout),lt-Y);await m.do(`secret:request:${n}`,async()=>{await r(d,{consumerTool:a,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:o,threadKey:h,toolCallId:n,toolName:t.name})}),await m.do(`secret:await:${n}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${o}`,messageKey:T,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await u({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${n}`,{timeout:y+Y,type:`agent-secret:${n}`}).catch(f=>{if(!et(f))throw f});const{status:g}=await m.do(`secret:settle:${n}`,async()=>await r(l,{instanceId:c,threadKey:h,toolCallId:n}));return await i(T),await u({ifInstanceId:c,status:"running"}),g},U="lunoraToolOutcome",Lt=e=>typeof e=="object"&&e!==null&&U in e?e[U]:{ok:e},Pt=async(e,t,a,o)=>{const{instanceId:n,persist:s}=e,i=Ft(o,t.id),c=`${n}:secret-result:${i}`,d=`tool:${t.name}:${i}`,u=Tt(t.input);if(u===void 0){await s({content:`Error: invalid input for tool "${t.name}" — it was not run. \`label\` must be a non-empty string saying what the secret is for.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}if(e.owner===void 0){await s({content:`Error: tool "${t.name}" was not run: this run has no owner, so no one can supply a secret for it.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const p=await Gt(e,t,a,u,i);await s({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${Dt[p]}.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name})},Wt=async(e,t,a)=>{const{agent:o,approvalGrantedRef:n,depth:s,env:i,exports:c,getState:d,instanceId:u,onTokenDelta:p,owner:r,persist:l,run:m,setState:h,step:T,threadKey:y,tools:g}=e,f=`tool:${t.name}:${t.id}`,$=g[t.name],E=`${u}:tool:${t.id}`;if(!$){await l({content:`Error: unknown tool "${t.name}"`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await l({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if($.secretRequest!==void 0){await Pt(e,t,$.secretRequest.consumer,a);return}const b={depth:s,env:i,exports:c,getState:d,idempotencyKey:f,instanceId:u,owner:r,reportProgress:S=>{p?.({data:S,kind:"progress",threadKey:y,toolCallId:t.id})},run:m,setState:h,step:T,threadKey:y,toolCallId:t.id},D={depth:s,env:i,getState:d,idempotencyKey:f,instanceId:u,run:m,threadKey:y,toolCallId:t.id},F=`tool:approval-gate:${t.id}`;let K,M;const G=async()=>await m(n,{key:y,toolName:t.name})===!0;if(await qt($,t.input,T,F,D,G)){const{decision:S,note:I,scope:L}=await bt(e,t);if(S==="reject"){const A=I===void 0?"":` Reason: ${I}`;await l({content:`Tool "${t.name}" was rejected by the user and not run.${A}`,messageKey:E,role:"tool",status:"rejected",stepName:f,toolCallId:t.id,toolName:t.name});return}K="approved",M=L}const O={...K===void 0?{}:{status:K},...M===void 0?{}:{approvalScope:M}},N=Lt(await T.do(f,async()=>{try{const S=()=>Promise.resolve($.execute(t.input,b)),I=await It(o.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[U]:{ok:I}}}catch(S){if(dt(S)||S instanceof vt)return{[U]:{failed:S.message}};throw S}}));if("failed"in N){await l({content:z(`Error: tool "${t.name}" failed and will not be retried. ${N.failed}`),messageKey:E,role:"tool",stepName:f,...O,toolCallId:t.id,toolName:t.name});return}const R=N.ok;await l({content:z(typeof R=="string"?R:Z(R)),messageKey:E,role:"tool",stepName:f,...O,toolCallId:t.id,toolName:t.name})},jt=(e,t,a)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:yt(t.model,a),toolChoice:t.toolChoice??e.toolChoice}},ot=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const a=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=a)return;let o=e.length-a;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},Bt=async(e,t)=>{const{agent:a,compact:o,env:n}=e,s=ot(t,a.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:n,messages:j({history:s.older}),model:a.compaction?.model??a.model});return i.length>0?{history:s.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Ht=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},Yt=async e=>{const{agent:t,compact:a,env:o,historyRef:n,instanceId:s,patchThread:i,run:c,threadKey:d}=e,u=Ht(t.compaction),p=await c(n,{configKey:u,key:d}),{messages:r,summary:l}=p,m=ot(r,t.compaction);if(m===void 0||a===void 0)return{history:r,summary:l};const h=async()=>{const{fallback:g}=p;return g===void 0?{history:r,summary:l}:(await i({ifInstanceId:s,summaryRebuiltSeq:g.throughSeq}).catch(f=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${d}"`,f)}),{history:r.filter(f=>f.seq>g.throughSeq),summary:g.summary})};let T;try{T=await a({env:o,messages:j({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(g){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,g),h()}if(T.length===0)return h();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:s,summary:T,summaryConfig:u,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(g=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,g)}),{history:m.recent,summary:T}},zt=async(e,t,a)=>{const{agent:o,env:n,generate:s,instructions:i,listMessages:c,memoryContext:d,onTokenDelta:u,run:p,step:r,streamGenerate:l,threadKey:m}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const{history:h,summary:T}=o.compaction!==void 0&&e.compact!==void 0?await Yt(e):await Bt(e,await xt(async f=>await p(c,{key:m,limit:f})));let y={activeTools:o.activeTools,messages:j({history:h,instructions:i,memoryContext:d,summary:T}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(y=jt(y,await o.prepareStep({messages:y.messages,stepNumber:t,steps:a}),n));const g={messages:y.messages,...y.activeTools===void 0?{}:{activeTools:y.activeTools},...y.model===void 0?{}:{model:y.model},...y.toolChoice===void 0?{}:{toolChoice:y.toolChoice}};return l&&u?l(g,f=>{u({text:f,threadKey:m,turn:t})}):s(g)})},J=async(e,t)=>{const{agent:a,step:o}=e;a.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await a.onStepFinish?.(t),!0))},Jt=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}}),B=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},Xt=e=>pt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Qt=async(e,t,a,o)=>{if(e.source===void 0)return;const n=v(e.source),{topK:s}=e,i=C("memory:retrieve",e.key),c=await a.do(i,async()=>o(n,{query:t,...s===void 0?{}:{topK:s}}));return B(c)},Vt=async(e,t,a,o,n,s)=>{if(a===void 0)return;const i=C("memory:traverse",e.key),c=await n.do(i,async()=>s(o,{owner:a,query:t,...Xt(e.graph)}));return B(c)},Zt=async(e,t,a,o,n)=>{if(t===void 0)return;const s=C("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await o.do(s,async()=>n(a,i));return B(c)},te=async(e,t)=>e.kind==="episodic"?Zt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?Vt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Qt(e,t.input,t.step,t.run),ee=e=>{const t=e.findIndex(a=>a.kind==="episodic");return e.filter((a,o)=>a.kind!=="episodic"||o===t)},oe=async(e,t,a,o,n,s)=>{const i=ee(ft(e));if(i.length===0)return;const c=v(o.graphTraverse),d=v(o.episodeRecall),u=[];for(const p of i){const r=await te(p,{episodeRecall:d,graphTraverse:c,input:t,owner:a,run:s,step:n});r!==void 0&&u.push(r)}return u.length>0?u.join(`
1
+ import{usageStatus as ut}from"@lunora/ai/create";import{e as dt}from"../packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as lt}from"@lunora/platform";import{r as X}from"../packem_shared/workflow-binding-Dm9hBzx_.mjs";import{a as pt}from"../packem_shared/app-call-options-BE0CQ6Qg.mjs";import{d as mt,a as Q,S as Y}from"../packem_shared/component-shared--SPcu0Iw.mjs";import{usageOfFailedTurn as yt,resolveAgentModel as ft}from"./createAgentGenerate.mjs";import{r as ht,f as wt,m as R,a as gt}from"../packem_shared/memory-JI0lUu84.mjs";import{buildModelMessages as j}from"../packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as V}from"../naming.mjs";import{toFunctionReference as g}from"../packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{i as vt}from"../packem_shared/positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as Tt,secretLabelOf as St}from"../packem_shared/SecretUnavailableError-DOy2M4Ak.mjs";import{combineTelemetry as $t}from"../packem_shared/combineTelemetry-DgE9W9G8.mjs";import{c as z}from"../packem_shared/tool-output-Cmk3JWMG.mjs";const Ct=200,Et=e=>{const t=e.findIndex(o=>o.role!=="tool");return t===-1?[]:e.slice(t)},xt=async e=>{let t=Ct;for(;;){const o=await e(t),a=Et(o);if(a.length>0||o.length<t)return a;t*=2}},Rt=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const o=Array.isArray(t)?t:[t];return o.length===0?void 0:$t(...o)},It=async e=>{e===void 0||e.isEnabled===!1||await Promise.all([e.integrations].flat().map(async t=>{try{await t?.flush?.()}catch{}}))},Kt=async(e,t,o)=>{const a=Rt(e);if(a===void 0)return o();const n={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:n,toolContext:void 0},i=Date.now();await a.onToolExecutionStart?.(s);let c;const u=()=>(c??=o(),c);try{if(a.executeTool===void 0)await u();else try{await a.executeTool({...s,execute:u,toolCallId:t.id})}catch{}const d=await u();return await a.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,input:t.input,output:d,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),d}catch(d){throw await a.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:d,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),d}},kt=8,Mt=e=>vt(e)?e:0,Z=e=>e===void 0?"null":JSON.stringify(e),Nt=async(e,t,o)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...o===void 0?{}:{usage:o}})}catch(a){t instanceof Error&&t.cause===void 0&&(t.cause=a)}},Ot=e=>e===void 0?[]:[e].flat(),At=async(e,t)=>(await Promise.all(e.map(async a=>a({steps:t})))).some(Boolean),_t=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],W=e=>e.status??ut(e),qt=(e,t)=>e===t?e:"partial",tt=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:W(t)};const o={status:qt(W(e),W(t))};for(const a of _t)(e[a]!==void 0||t[a]!==void 0)&&(o[a]=(e[a]??0)+(t[a]??0));return o},Ut=async(e,t,o,a,n,s)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:o.do(a,async()=>await s()?!1:i===!0||i(t,n))},bt="WorkflowTimeoutError",et=e=>e instanceof Error&&e.name===bt,Dt=async(e,t)=>{const{agent:o,deleteMessage:a,instanceId:n,patchThread:s,persist:i,step:c}=e,u=Q(o.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+u,messageKey:`${n}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"})});const d=await c.waitForEvent(`approval:${t.id}`,{timeout:u,type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note},...p.payload.scope===void 0?{}:{scope:p.payload.scope}})).catch(p=>{if(!et(p))throw p;return{decision:"reject",note:"approval timed out"}});return await a(`${n}:approval:${t.id}`),await s({status:"running"}),d},Ft={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Gt=(e,t)=>`${String(e)}:${t}`,Lt=async(e,t,o,a,n)=>{const{agent:s,deleteMessage:i,instanceId:c,openSecretRef:u,patchThread:d,persist:p,run:r,settleSecretRef:l,step:m,threadKey:h}=e,v=`${c}:secret:${n}`,y=Math.min(Q(s.approvalTimeout),lt-Y);await m.do(`secret:request:${n}`,async()=>{await r(u,{consumerTool:o,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:a,threadKey:h,toolCallId:n,toolName:t.name})}),await m.do(`secret:await:${n}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${a}`,messageKey:v,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await d({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${n}`,{timeout:y+Y,type:`agent-secret:${n}`}).catch(T=>{if(!et(T))throw T});const{status:f}=await m.do(`secret:settle:${n}`,async()=>await r(l,{instanceId:c,threadKey:h,toolCallId:n}));return await i(v),await d({ifInstanceId:c,status:"running"}),f},b="lunoraToolOutcome",Pt=e=>typeof e=="object"&&e!==null&&b in e?e[b]:{ok:e},Wt=async(e,t,o,a)=>{const{instanceId:n,persist:s}=e,i=Gt(a,t.id),c=`${n}:secret-result:${i}`,u=`tool:${t.name}:${i}`,d=St(t.input);if(d===void 0){await s({content:`Error: invalid input for tool "${t.name}" — it was not run. \`label\` must be a non-empty string saying what the secret is for.`,messageKey:c,role:"tool",stepName:u,toolCallId:t.id,toolName:t.name});return}if(e.owner===void 0){await s({content:`Error: tool "${t.name}" was not run: this run has no owner, so no one can supply a secret for it.`,messageKey:c,role:"tool",stepName:u,toolCallId:t.id,toolName:t.name});return}const p=await Lt(e,t,o,d,i);await s({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${Ft[p]}.`,messageKey:c,role:"tool",stepName:u,toolCallId:t.id,toolName:t.name})},jt=async(e,t,o)=>{const{agent:a,approvalGrantedRef:n,depth:s,env:i,exports:c,getState:u,instanceId:d,onTokenDelta:p,owner:r,persist:l,run:m,setState:h,shardKey:v,step:y,threadKey:f,tools:T}=e,$=`tool:${t.name}:${t.id}`,C=T[t.name],E=`${d}:tool:${t.id}`;if(!C){await l({content:`Error: unknown tool "${t.name}"`,messageKey:E,role:"tool",stepName:$,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await l({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:E,role:"tool",stepName:$,toolCallId:t.id,toolName:t.name});return}if(C.secretRequest!==void 0){await Wt(e,t,C.secretRequest.consumer,o);return}const D={depth:s,env:i,exports:c,getState:u,idempotencyKey:$,instanceId:d,owner:r,reportProgress:S=>{p?.({data:S,kind:"progress",threadKey:f,toolCallId:t.id})},run:m,setState:h,shardKey:v,step:y,threadKey:f,toolCallId:t.id},F={depth:s,env:i,getState:u,idempotencyKey:$,instanceId:d,run:m,shardKey:v,threadKey:f,toolCallId:t.id},G=`tool:approval-gate:${t.id}`;let N,O;const L=async()=>await m(n,{key:f,toolName:t.name})===!0;if(await Ut(C,t.input,y,G,F,L)){const{decision:S,note:K,scope:q}=await Dt(e,t);if(S==="reject"){const k=K===void 0?"":` Reason: ${K}`;await l({content:`Tool "${t.name}" was rejected by the user and not run.${k}`,messageKey:E,role:"tool",status:"rejected",stepName:$,toolCallId:t.id,toolName:t.name});return}N="approved",O=q}const _={...N===void 0?{}:{status:N},...O===void 0?{}:{approvalScope:O}},I=Pt(await y.do($,async()=>{try{const S=()=>Promise.resolve(C.execute(t.input,D)),K=await Kt(a.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[b]:{ok:K}}}catch(S){if(dt(S)||S instanceof Tt)return{[b]:{failed:S.message}};throw S}}));if("failed"in I){await l({content:z(`Error: tool "${t.name}" failed and will not be retried. ${I.failed}`),messageKey:E,role:"tool",stepName:$,..._,toolCallId:t.id,toolName:t.name});return}const A=I.ok;await l({content:z(typeof A=="string"?A:Z(A)),messageKey:E,role:"tool",stepName:$,..._,toolCallId:t.id,toolName:t.name})},Bt=(e,t,o)=>{if(!t)return e;let{messages:a}=e;return t.messages!==void 0&&(a=t.messages),t.system!==void 0&&(a=[{content:t.system,role:"system"},...a]),{activeTools:t.activeTools??e.activeTools,messages:a,model:t.model===void 0?e.model:ft(t.model,o),toolChoice:t.toolChoice??e.toolChoice}},ot=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const o=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=o)return;let a=e.length-o;for(;a>0&&e[a]?.role==="tool";)a-=1;if(!(a<=0))return{older:e.slice(0,a),recent:e.slice(a)}},Ht=async(e,t)=>{const{agent:o,compact:a,env:n}=e,s=ot(t,o.compaction);if(s===void 0||a===void 0)return{history:t,summary:void 0};try{const i=await a({env:n,messages:j({history:s.older}),model:o.compaction?.model??o.model});return i.length>0?{history:s.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Yt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},zt=async e=>{const{agent:t,compact:o,env:a,historyRef:n,instanceId:s,patchThread:i,run:c,threadKey:u}=e,d=Yt(t.compaction),p=await c(n,{configKey:d,key:u}),{messages:r,summary:l}=p,m=ot(r,t.compaction);if(m===void 0||o===void 0)return{history:r,summary:l};const h=async()=>{const{fallback:f}=p;return f===void 0?{history:r,summary:l}:(await i({ifInstanceId:s,summaryRebuiltSeq:f.throughSeq}).catch(T=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${u}"`,T)}),{history:r.filter(T=>T.seq>f.throughSeq),summary:f.summary})};let v;try{v=await o({env:a,messages:j({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(f){return console.warn(`@lunora/agent: summarising thread "${u}" failed`,f),h()}if(v.length===0)return h();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:s,summary:v,summaryConfig:d,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(f=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${u}"`,f)}),{history:m.recent,summary:v}},Jt=async(e,t,o)=>{const{agent:a,env:n,generate:s,instructions:i,listMessages:c,memoryContext:u,onTokenDelta:d,run:p,step:r,streamGenerate:l,threadKey:m}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const{history:h,summary:v}=a.compaction!==void 0&&e.compact!==void 0?await zt(e):await Ht(e,await xt(async T=>await p(c,{key:m,limit:T})));let y={activeTools:a.activeTools,messages:j({history:h,instructions:i,memoryContext:u,summary:v}),model:void 0,toolChoice:a.toolChoice};a.prepareStep&&(y=Bt(y,await a.prepareStep({messages:y.messages,stepNumber:t,steps:o}),n));const f={messages:y.messages,...y.activeTools===void 0?{}:{activeTools:y.activeTools},...y.model===void 0?{}:{model:y.model},...y.toolChoice===void 0?{}:{toolChoice:y.toolChoice}};return l&&d?l(f,T=>{d({text:T,threadKey:m,turn:t})}):s(f)})},J=async(e,t)=>{const{agent:o,step:a}=e;o.onStepFinish&&await a.do(`agent:step-finish:${String(t.turn)}`,async()=>(await o.onStepFinish?.(t),!0))},Xt=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}}),B=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},Qt=e=>mt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Vt=async(e,t,o,a,n)=>{if(e.source===void 0)return;const s=g(e.source),{topK:i}=e,c=R("memory:retrieve",e.key),u={query:t,...i===void 0?{}:{topK:i}},d=await a.do(c,async()=>n(s,u,pt(o)));return B(d)},Zt=async(e,t,o,a,n,s)=>{if(o===void 0)return;const i=R("memory:traverse",e.key),c=await n.do(i,async()=>s(a,{owner:o,query:t,...Qt(e.graph)}));return B(c)},te=async(e,t,o,a,n)=>{if(t===void 0)return;const s=R("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await a.do(s,async()=>n(o,i));return B(c)},ee=async(e,t)=>e.kind==="episodic"?te(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?Zt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Vt(e,t.input,t.shardKey,t.step,t.run),oe=e=>{const t=e.findIndex(o=>o.kind==="episodic");return e.filter((o,a)=>o.kind!=="episodic"||a===t)},ae=async(e,t,o,a,n,s,i)=>{const c=oe(ht(e));if(c.length===0)return;const u=g(n.graphTraverse),d=g(n.episodeRecall),p=[];for(const r of c){const l=await ee(r,{episodeRecall:d,graphTraverse:u,input:t,owner:o,run:i,shardKey:a,step:s});l!==void 0&&p.push(l)}return p.length>0?p.join(`
2
2
 
3
- `):void 0},ae=async e=>{const{agent:t,env:a,extractGraph:o,finalText:n,input:s,instanceId:i,owner:c,paths:d,run:u,step:p}=e;if(o===void 0||c===void 0||n===void 0||n.length===0)return;const r=ht(t);if(r!==void 0)try{const l={assistantText:n,env:a,model:r.graph?.extractionModel??t.model,userInput:s},m=await p.do(C("memory:extract",r.key),async()=>o(l));await u(v(d.graphUpsert),{...m,messageKey:`${i}:${C("extract",r.key)}`,owner:c})}catch{}},ne=async e=>{const{agent:t,env:a,extractEpisode:o,finalText:n,input:s,instanceId:i,owner:c,paths:d,run:u,step:p,threadKey:r}=e;if(o===void 0||c===void 0||n===void 0||n.length===0)return;const l=wt(t);if(l!==void 0)try{const m={assistantText:n,env:a,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:h}=await p.do(C("memory:episode",l.key),async()=>o(m));await u(v(d.episodeUpsert),{messageKey:`${i}:${C("episode",l.key)}`,owner:c,summary:h,threadKey:r})}catch{}},se=async(e,t,a)=>{const o=X(e.env,e.exports,V(t),["get"]);if(o!==void 0)try{await(await o.get(a)).terminate()}catch{}},re="12 hours",ie=async(e,t,a)=>{await e.waitForEvent(`dequeue:${a}`,{timeout:re,type:`agent-dequeue:${t}:${a}`})},ce=async(e,t,a)=>{const o=X(e.env,e.exports,V(e.exportName),["get"]);if(o===void 0)return;const n=o.get.bind(o);try{await e.step.do(`dequeue-wake:${a}`,async()=>(await(await n(a)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${a}`}),a))}catch{}},ue=async(e,t,a)=>{const{onReply:o}=e,{replyRef:n}=t.params;if(!(o===void 0||n===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:n,result:a,threadKey:t.params.threadKey}),n.channel))}catch{}},de=async(e,t,a,o,n)=>{const{instanceId:s,persist:i}=e,c=a.usage===void 0?{}:{usage:a.usage};if(a.toolCalls.length===0){const d=a.output!==void 0&&a.text.length===0?Z(a.output):a.text;return await i({content:d,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await J(e,{text:a.text,toolCalls:[],turn:t,...c}),{final:{stopped:"final",text:a.text,turns:t+1,...a.output===void 0?{}:{output:a.output}}}}await i({content:a.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:a.toolCalls});for(const d of a.toolCalls)await Wt(e,d,t);if(await J(e,{text:a.text,toolCalls:a.toolCalls,turn:t,...c}),o.push(Jt(a)),n.length>0&&await Ot(n,o))return"stopCondition"},le=async(e,t,a,o)=>{const n=[];let s,i=!1,c=0;for(let d=0;d<t;d+=1){const u=await zt(e,d,n);o.value=tt(o.value,u.usage),c=d+1;const p=await de(e,d,u,n,a);if(p==="stopCondition"){i=!0;break}if(p!==void 0){s=p.final;break}}return{final:s,stoppedByCondition:i,turnsRun:c}},Re=async e=>{const{agent:t,compact:a,env:o,exportName:n,exports:s,extractEpisode:i,extractGraph:c,generate:d,instanceId:u,onTokenDelta:p,params:r,paths:l,run:m,step:h,streamGenerate:T}=e,y=t.maxTurns??kt,g=Nt(t.stopWhen),f=v(l.appendMessage),$=v(l.approvalGranted),E=v(l.openSecretRequest),H=v(l.settleSecretRequest),b=v(l.completeRun),D=v(l.ensureThread),F=v(l.listMessages),K=v(l.history),M=v(l.deleteMessage),G=v(l.patchThread),O=v(l.setState),N=v(l.state),R=async w=>{await m(f,{threadKey:r.threadKey,...w})},S=async w=>{await m(G,{key:r.threadKey,...w})},I=async w=>{await m(M,{messageKey:w,threadKey:r.threadKey})},L=async()=>{await R({content:r.input,messageKey:`${u}:user`,role:"user"})},A={dispatched:!1},_=async w=>{A.dispatched=!0;const q=await m(b,{instanceId:u,key:r.threadKey,...w});q?.dequeued!==void 0&&await ce({env:o,exportName:n,exports:s,step:h},r.threadKey,q.dequeued)},at=async()=>await m(N,{key:r.threadKey}),nt=async w=>{await m(O,{key:r.threadKey,state:w})},P=await m(D,{agent:n,instanceId:u,key:r.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...r.owner===void 0?{}:{owner:r.owner},...r.title===void 0?{}:{title:r.title}});P?.outcome==="replaced"&&await se({env:o,exports:s},n,P.priorInstanceId);const st=await oe(t,r.input,r.owner,l,h,m),rt=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,it={agent:t,approvalGrantedRef:$,openSecretRef:E,settleSecretRef:H,compact:a,depth:Kt(r.depth),env:o,exports:s,generate:d,getState:at,historyRef:K,instanceId:u,instructions:rt,listMessages:F,memoryContext:st,onTokenDelta:p,owner:r.owner,deleteMessage:I,patchThread:S,persist:R,run:m,setState:nt,step:h,streamGenerate:T,threadKey:r.threadKey,tools:t.tools??{}},k={value:void 0};try{P?.outcome==="queued"&&await ie(h,r.threadKey,u),await L();const{final:w,stoppedByCondition:q,turnsRun:ct}=await le(it,y,g,k),x=k.value===void 0?{}:{usage:k.value};return await ae({agent:t,env:o,extractGraph:c,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h}),await ne({agent:t,env:o,extractEpisode:i,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h,threadKey:r.threadKey}),w?(await ue(t,{env:o,params:r,step:h},{...w,...x}),await _({status:"idle",...x}),{...w,...x}):q?(await _({status:"idle",...x}),{stopped:"stopCondition",turns:ct,...x}):(await _({error:`agent stopped: maxTurns (${String(y)}) reached`,status:"error",...x}),{stopped:"maxTurns",turns:y,...x})}catch(w){throw A.dispatched||(k.value=tt(k.value,mt(w)),await Mt(_,w,k.value)),w}finally{await Rt(t.telemetry)}};export{tt as addUsage,Bt as compactHistory,Re as runAgentLoop,ot as splitForCompaction};
3
+ `):void 0},ne=async e=>{const{agent:t,env:o,extractGraph:a,finalText:n,input:s,instanceId:i,owner:c,paths:u,run:d,step:p}=e;if(a===void 0||c===void 0||n===void 0||n.length===0)return;const r=wt(t);if(r!==void 0)try{const l={assistantText:n,env:o,model:r.graph?.extractionModel??t.model,userInput:s},m=await p.do(R("memory:extract",r.key),async()=>a(l));await d(g(u.graphUpsert),{...m,messageKey:`${i}:${R("extract",r.key)}`,owner:c})}catch{}},se=async e=>{const{agent:t,env:o,extractEpisode:a,finalText:n,input:s,instanceId:i,owner:c,paths:u,run:d,step:p,threadKey:r}=e;if(a===void 0||c===void 0||n===void 0||n.length===0)return;const l=gt(t);if(l!==void 0)try{const m={assistantText:n,env:o,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:h}=await p.do(R("memory:episode",l.key),async()=>a(m));await d(g(u.episodeUpsert),{messageKey:`${i}:${R("episode",l.key)}`,owner:c,summary:h,threadKey:r})}catch{}},re=async(e,t,o)=>{const a=X(e.env,e.exports,V(t),["get"]);if(a!==void 0)try{await(await a.get(o)).terminate()}catch{}},ie="12 hours",ce=async(e,t,o)=>{await e.waitForEvent(`dequeue:${o}`,{timeout:ie,type:`agent-dequeue:${t}:${o}`})},ue=async(e,t,o)=>{const a=X(e.env,e.exports,V(e.exportName),["get"]);if(a===void 0)return;const n=a.get.bind(a);try{await e.step.do(`dequeue-wake:${o}`,async()=>(await(await n(o)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${o}`}),o))}catch{}},de=async(e,t,o)=>{const{onReply:a}=e,{replyRef:n}=t.params;if(!(a===void 0||n===void 0))try{await t.step.do("agent:reply",async()=>(await a({env:t.env,replyRef:n,result:o,threadKey:t.params.threadKey}),n.channel))}catch{}},le=async(e,t,o,a,n)=>{const{instanceId:s,persist:i}=e,c=o.usage===void 0?{}:{usage:o.usage};if(o.toolCalls.length===0){const u=o.output!==void 0&&o.text.length===0?Z(o.output):o.text;return await i({content:u,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await J(e,{text:o.text,toolCalls:[],turn:t,...c}),{final:{stopped:"final",text:o.text,turns:t+1,...o.output===void 0?{}:{output:o.output}}}}await i({content:o.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:o.toolCalls});for(const u of o.toolCalls)await jt(e,u,t);if(await J(e,{text:o.text,toolCalls:o.toolCalls,turn:t,...c}),a.push(Xt(o)),n.length>0&&await At(n,a))return"stopCondition"},pe=async(e,t,o,a)=>{const n=[];let s,i=!1,c=0;for(let u=0;u<t;u+=1){const d=await Jt(e,u,n);a.value=tt(a.value,d.usage),c=u+1;const p=await le(e,u,d,n,o);if(p==="stopCondition"){i=!0;break}if(p!==void 0){s=p.final;break}}return{final:s,stoppedByCondition:i,turnsRun:c}},Ke=async e=>{const{agent:t,compact:o,env:a,exportName:n,exports:s,extractEpisode:i,extractGraph:c,generate:u,instanceId:d,onTokenDelta:p,params:r,paths:l,run:m,step:h,streamGenerate:v}=e,y=t.maxTurns??kt,f=Ot(t.stopWhen),T=g(l.appendMessage),$=g(l.approvalGranted),C=g(l.openSecretRequest),E=g(l.settleSecretRequest),H=g(l.completeRun),D=g(l.ensureThread),F=g(l.listMessages),G=g(l.history),N=g(l.deleteMessage),O=g(l.patchThread),L=g(l.setState),_=g(l.state),I=async w=>{await m(T,{threadKey:r.threadKey,...w})},A=async w=>{await m(O,{key:r.threadKey,...w})},S=async w=>{await m(N,{messageKey:w,threadKey:r.threadKey})},K=async()=>{await I({content:r.input,messageKey:`${d}:user`,role:"user"})},q={dispatched:!1},k=async w=>{q.dispatched=!0;const U=await m(H,{instanceId:d,key:r.threadKey,...w});U?.dequeued!==void 0&&await ue({env:a,exportName:n,exports:s,step:h},r.threadKey,U.dequeued)},at=async()=>await m(_,{key:r.threadKey}),nt=async w=>{await m(L,{key:r.threadKey,state:w})},P=await m(D,{agent:n,instanceId:d,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 re({env:a,exports:s},n,P.priorInstanceId);const st=await ae(t,r.input,r.owner,r.shardKey,l,h,m),rt=typeof t.instructions=="function"?t.instructions({env:a,input:r.input,threadKey:r.threadKey}):t.instructions,it={agent:t,approvalGrantedRef:$,openSecretRef:C,settleSecretRef:E,compact:o,depth:Mt(r.depth),env:a,exports:s,generate:u,getState:at,historyRef:G,instanceId:d,instructions:rt,listMessages:F,memoryContext:st,onTokenDelta:p,owner:r.owner,deleteMessage:S,patchThread:A,persist:I,run:m,setState:nt,shardKey:r.shardKey,step:h,streamGenerate:v,threadKey:r.threadKey,tools:t.tools??{}},M={value:void 0};try{P?.outcome==="queued"&&await ce(h,r.threadKey,d),await K();const{final:w,stoppedByCondition:U,turnsRun:ct}=await pe(it,y,f,M),x=M.value===void 0?{}:{usage:M.value};return await ne({agent:t,env:a,extractGraph:c,finalText:w?.text,input:r.input,instanceId:d,owner:r.owner,paths:l,run:m,step:h}),await se({agent:t,env:a,extractEpisode:i,finalText:w?.text,input:r.input,instanceId:d,owner:r.owner,paths:l,run:m,step:h,threadKey:r.threadKey}),w?(await de(t,{env:a,params:r,step:h},{...w,...x}),await k({status:"idle",...x}),{...w,...x}):U?(await k({status:"idle",...x}),{stopped:"stopCondition",turns:ct,...x}):(await k({error:`agent stopped: maxTurns (${String(y)}) reached`,status:"error",...x}),{stopped:"maxTurns",turns:y,...x})}catch(w){throw q.dispatched||(M.value=tt(M.value,yt(w)),await Nt(k,w,M.value)),w}finally{await It(t.telemetry)}};export{tt as addUsage,Ht as compactHistory,Ke as runAgentLoop,ot as splitForCompaction};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as S}from"@lunora/workflow";import{f as $}from"./fnv1a-BNN96GYb.mjs";import{w as E}from"./run-shard-B7iMrAI0.mjs";import{r as L}from"./workflow-binding-Dm9hBzx_.mjs";import b from"./jsonSchema-fhoaBWpN.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as P,DEFAULT_AGENT_FUNCTION_PATHS as _}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as g}from"./positive-integer-ztHqqpBk.mjs";const M=new Set(["complete","errored","terminated"]),R=600,w=3,k=500,x=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",C=t=>t!==null&&typeof t=="object"?t.output:void 0,D=async t=>{await new Promise(e=>{setTimeout(e,t)})},U=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=x(a);if(M.has(s))return{output:C(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},j=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},F=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""},B=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&&!g(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??R,o=t.pollIntervalMs??k,a=t.wait??D,s=P(_.listMessages),T=async(y,r)=>{const p=(g(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=L(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}`,h=`sub-${e}-${$(`${r.instanceId}:${e}:${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:h,params:E(A,r.shardKey)});l=await i.get(d.id)}catch(d){if(!S(d))throw d;l=await i.get(h)}const{output:v,status:u}=await U(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(j(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 I=await r.run(s,{key:f});return F(I)};return{description:t.description,execute:T,inputSchema:b({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{B as agentAsTool};
@@ -0,0 +1 @@
1
+ const p=o=>o===void 0?void 0:{shardKey:o};export{p as a};
@@ -0,0 +1 @@
1
+ import{a as u}from"./app-call-options-BE0CQ6Qg.mjs";import p from"./jsonSchema-fhoaBWpN.mjs";import{toFunctionReference as l}from"./AGENT_MODULE-CYBmT9SD.mjs";const m=240,y=50,f=(r,s)=>r.length<=s?r:`${r.slice(0,s)}…`,g=r=>{if(!(r===void 0||!Number.isFinite(r)))return Math.min(y,Math.max(1,Math.trunc(r)))},S=(r,s)=>{const t=r??{},i=Array.isArray(t.chunks)?t.chunks:[],e=Array.isArray(t.sources)?t.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:f(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},A=p({additionalProperties:!1,properties:{query:{description:"Natural-language search query.",type:"string"},topK:{description:"Maximum number of hits to return.",type:"number"}},required:["query"],type:"object"}),b=p({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),T=(r,s,t)=>{const i=l(s),e=Math.max(1,r.snippetChars??m),o=r.topK;return{description:`Search long-term memory for passages relevant to a query. Returns ranked { id, sourceId, score, snippet } hits — call again with a refined query to dig deeper.${t===void 0?"":` Use \`${t}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,c)=>{const d=g(n.topK)??o,h=await c.run(i,{query:n.query,...d===void 0?{}:{topK:d}},u(c.shardKey));return S(h,e)},inputSchema:A,isLunoraAgentTool:!0}},q=r=>{const s=l(r);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(t,i)=>i.run(s,{id:t.id},u(i.shardKey)),inputSchema:b,isLunoraAgentTool:!0}},v=(r,s)=>{const t=[];r.memory&&t.push({key:"default",...r.memory});for(const e of s)e.knowledge&&t.push({key:e.name,...e.knowledge});const i={};for(const e of t){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,a=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=T(e,e.source,n?a:void 0),n&&(i[a]=q(e.read))}return i};export{v as collectAgenticMemoryTools,S as toSearchResults};
@@ -0,0 +1 @@
1
+ import{a as w}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{LunoraError as o}from"@lunora/errors";import{h as f,B as g}from"./branch-marker-boZ00zmk.mjs";import{w as E}from"./run-shard-B7iMrAI0.mjs";import{r as N}from"./workflow-binding-Dm9hBzx_.mjs";import{toFunctionReference as R,DEFAULT_AGENT_FUNCTION_PATHS as T}from"./AGENT_MODULE-CYBmT9SD.mjs";const B=(r,c,i={})=>{const{dispatch:u,exports:d,shardKey:l}=i,s={},m=R(T.patchThread),p=()=>u??w({env:r,label:"@lunora/agent"});for(const e of c){const n=()=>{const t=N(r,d,e.className,["create","get"]);if(t===void 0)throw new o("INTERNAL",`@lunora/agent: no "${e.className}" on ctx.exports or env for agent "${e.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return t};s[e.exportName]={cancel:async t=>{await(await n().get(t)).terminate();try{await p()(m,{instanceId:t,status:"cancelled"})}catch{}},publicRun:e.publicRun===!0,run:async(t,a)=>{if(f(t))throw new o("BAD_REQUEST",`@lunora/agent: run input ${g}`);return{id:(await n().create({...a?.id===void 0?{}:{id:a.id},params:E(t,l)})).id}},sendEvent:async(t,a)=>{await(await n().get(t)).sendEvent(a)},status:async t=>(await n().get(t)).status()}}return s};export{B as default};
@@ -0,0 +1,3 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as p}from"./agentAsTool-BF-7Dnzy.mjs";import{a as g}from"./component-shared--SPcu0Iw.mjs";import{i as m}from"./memory-JI0lUu84.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=e=>{if(e!==void 0&&(typeof e!="string"||e.length===0))throw new r("INTERNAL","@lunora/agent: defineAgent `name` must be a non-empty string when provided")},N=/^[a-zA-Z][\w-]*$/u,A=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=a}return o},k=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
2
+
3
+ `)},v=(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)}},E=(e,n)=>{if(e===void 0)return;const o=Object.keys(n).filter(t=>!e.includes(t));if(o.length>0)throw new r("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(t=>`"${t}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},I=(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=>{for(const[n,o]of[["resolveEmailShard",e.resolveEmailShard],["onInbound.resolveShard",e.onInbound?.resolveShard]])if(o!==void 0&&typeof o!="function")throw new r("INTERNAL",`@lunora/agent: \`${n}\` must be a function`)},b=e=>{if(e===void 0)return;const n=g(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},_=e=>{const n=e.model;if(n==null||typeof n=="string"&&n.length===0)throw new r("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(T(e.name),e.maxTurns!==void 0&&!u(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!u(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");b(e.approvalTimeout),L(e);const o=e.skills??[];y(o),I(e,o);const t=A(e,o),s=f(e,o);for(const[i,h]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=h}const a=Object.keys(s).length>0;E(e.activeTools,s);for(const i of Object.keys(t))if(!N.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=v(e,o),d=k(e,o);return{...e,asTool:p,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:t}:{}}},q=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,P=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,P as defineAgentTool,q as isAgentDefinition};
@@ -0,0 +1 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{a as c}from"./app-call-options-BE0CQ6Qg.mjs";import{AGENT_MODULE as u,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.mjs";const f=(t,e)=>{if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(e.inputSchema===void 0)throw new r("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const o=m(t),i=o.__lunoraRef.startsWith(`${u}:`);return{description:e.description,execute:(a,n)=>n.run(o,{...a,idempotencyKey:n.idempotencyKey},i?void 0:c(n.shardKey)),inputSchema:e.inputSchema,isLunoraAgentTool:!0}};export{f as functionTool};
@@ -0,0 +1 @@
1
+ import{LunoraError as e}from"@lunora/errors";const i=async(n,o,t)=>{if(n===void 0)return;const r=await n(o);if(r!==void 0){if(typeof r!="string"||r.length===0)throw new e("INTERNAL",`@lunora/agent: \`${t}\` must return a non-empty shard key or undefined`);return r}};export{i as r};
@@ -0,0 +1 @@
1
+ const a=(t,r)=>{const e={...t};return delete e.shardKey,r!==void 0&&(e.shardKey=r),e};export{a as w};
@@ -16,6 +16,13 @@ interface AgentFunctionReference {
16
16
  * @experimental
17
17
  */
18
18
  interface AgentRunOptions {
19
+ /**
20
+ * Route the call to this shard instead of the default one. Pass
21
+ * {@link AgentToolContext.shardKey} when the target reads `.shardBy(...)` tables —
22
+ * `functionTool` does — and leave it unset for the agent's own `agents:*`
23
+ * functions, whose threads, state and secrets live on the default shard.
24
+ */
25
+ shardKey?: string;
19
26
  /**
20
27
  * Abort the dispatch after this many ms, overriding the runner's 30s
21
28
  * default (`DEFAULT_DISPATCH_TIMEOUT_MS`).
@@ -129,7 +136,10 @@ interface AgentToolContext {
129
136
  * {@link AgentToolContext.toolCallId}. `data` must be JSON-serializable.
130
137
  */
131
138
  reportProgress: (data: unknown) => void;
132
- /** Dispatch a Lunora function (the workflow `ctx.run`). */
139
+ /**
140
+ * Dispatch a Lunora function (the workflow `ctx.run`). Calls go to the default
141
+ * shard unless they pass {@link AgentRunOptions.shardKey}.
142
+ */
133
143
  run: AgentRunFunction;
134
144
  /**
135
145
  * Replace the thread's synced state — dispatches the internal
@@ -153,6 +163,12 @@ interface AgentToolContext {
153
163
  * skip the write when it is already present.
154
164
  */
155
165
  setState: (state: Record<string, unknown>) => Promise<void>;
166
+ /**
167
+ * The shard the run was started on ({@link AgentRunInput.shardKey}); `undefined`
168
+ * for the default shard. Pass it as {@link AgentRunOptions.shardKey} to reach the
169
+ * tenant's `.shardBy(...)` data from a hand-written tool.
170
+ */
171
+ shardKey?: string;
156
172
  /**
157
173
  * The durable-step handle (`step.do`/`waitForEvent`). ALWAYS present:
158
174
  * `agent-loop.ts` threads it into every tool's context unconditionally, and
@@ -630,6 +646,53 @@ interface AgentEmailRun {
630
646
  * @experimental
631
647
  */
632
648
  type AgentEmailMapper = (email: InboundEmail) => AgentEmailRun | null | Promise<AgentEmailRun | null | undefined> | undefined;
649
+ /**
650
+ * Pick the shard an inbound-triggered run's tools use: the app maps a verified identity
651
+ * to a tenant shard. Return `undefined` for the default shard.
652
+ *
653
+ * This is the only way an inbound run gets a shard. A `shardKey` in the mapped run is
654
+ * dropped, because the mapper's output is built from attacker-written content. The hook
655
+ * runs after the sender or signature gate and after the mapper claimed the message, and
656
+ * it is handed only what the platform verified ({@link AgentEmailShardInput},
657
+ * {@link AgentChannelShardInput}). Returning a shard is an authorization decision, since
658
+ * the run's tools dispatch past `authorizeShard`: look the identity up in a table you
659
+ * trust. A throw fails the delivery rather than falling back to the default shard.
660
+ * @experimental
661
+ */
662
+ type AgentInboundShardResolver<Input> = (input: Input) => Promise<string | undefined> | string | undefined;
663
+ /**
664
+ * What `resolveEmailShard` gets.
665
+ * @experimental
666
+ */
667
+ interface AgentEmailShardInput {
668
+ /**
669
+ * The parsed message, for context only. Its headers are sender-written: `email.to`
670
+ * is the `To:` header, which any sender can set to another tenant's address, and
671
+ * `email.from` is only as good as the authentication verdicts. Never derive the
672
+ * shard from it.
673
+ */
674
+ email: InboundEmail;
675
+ /**
676
+ * The SMTP envelope recipient Cloudflare Email Routing delivered this message to.
677
+ * Routing only delivers to addresses you configured, so this is the field to map
678
+ * to a tenant.
679
+ */
680
+ envelopeTo: string;
681
+ }
682
+ /**
683
+ * What `onInbound.resolveShard` gets: the channel and the workspace the signed payload
684
+ * belongs to, never the event's message content.
685
+ * @experimental
686
+ */
687
+ interface AgentChannelShardInput {
688
+ channel: AgentInboundChannelKind;
689
+ /**
690
+ * The provider-set tenant id from the signature-verified body: Slack `team_id`,
691
+ * GitHub `installation.id`, Discord `guild_id`. `undefined` when the payload carries
692
+ * none (a DM interaction, a GitHub event outside an app installation).
693
+ */
694
+ workspaceId: string | undefined;
695
+ }
633
696
  /** The inbound webhook channels an agent can be triggered from — see `@lunora/agent/channels`. */
634
697
  type AgentInboundChannelKind = "discord" | "github" | "slack";
635
698
  /** The run-input an inbound-channel mapper returns — the same shape as {@link AgentEmailRun}. */
@@ -668,6 +731,8 @@ interface AgentInboundChannel {
668
731
  channel: AgentInboundChannelKind;
669
732
  /** Map a verified event to a run (or `null` to decline). */
670
733
  map: AgentChannelMapper;
734
+ /** The shard a claimed event's run uses — see {@link AgentInboundShardResolver}. Default shard when absent. */
735
+ resolveShard?: AgentInboundShardResolver<AgentChannelShardInput>;
671
736
  /**
672
737
  * The verification credential, from `env`: an env-var NAME (string) or an
673
738
  * `(env) => value` resolver. Slack → signing secret; GitHub → webhook secret;
@@ -823,6 +888,12 @@ interface AgentConfig {
823
888
  * unknown-tool-name recovery as the only repair path.
824
889
  */
825
890
  repairToolCall?: ToolCallRepairFunction<ToolSet>;
891
+ /**
892
+ * The shard an `onEmail` run's tools use — see {@link AgentInboundShardResolver}. Map
893
+ * `envelopeTo`, the routed recipient; the parsed headers are sender-written. Default
894
+ * shard when absent.
895
+ */
896
+ resolveEmailShard?: AgentInboundShardResolver<AgentEmailShardInput>;
826
897
  /**
827
898
  * Reusable {@link SkillDefinition}s to compose in — each contributes an
828
899
  * instruction fragment, tools (merged into the flat namespace; collisions
@@ -1016,6 +1087,14 @@ interface AgentRunInput {
1016
1087
  owner?: string;
1017
1088
  /** Where a triggered run sends its answer — see {@link AgentReplyRef}. */
1018
1089
  replyRef?: AgentReplyRef;
1090
+ /**
1091
+ * The shard whose app data the run's tools read and write. Set only by the boundary
1092
+ * that starts the run, from a source it trusts: `ctx.agents.<name>.run` uses the
1093
+ * shard of the mutation or action that calls it, a scheduled run the scheduling
1094
+ * shard, an inbound run the app's `resolveEmailShard` / `resolveShard` hook. A
1095
+ * value in the input is always overwritten, since the input may be a client's.
1096
+ */
1097
+ shardKey?: string;
1019
1098
  /** The thread key — reuse to continue a conversation. */
1020
1099
  threadKey: string;
1021
1100
  /** Optional thread title, set on first creation. */
@@ -1433,4 +1512,4 @@ interface AgentHandle {
1433
1512
  /** Read a run's workflow status by instance id. */
1434
1513
  status: (id: string) => Promise<unknown>;
1435
1514
  }
1436
- export { AgentVoiceConfig as $, AgentDefinition as A, AgentGenerateOptions as B, AgentGenerateResult as C, AgentHandle as D, AgentInstructionsContext as E, AgentLiveEvent as F, AgentMemoryOptions as G, AgentMemorySource as H, InboundChannelEvent as I, AgentMessageStatus as J, AgentOnReply as K, AgentOnStepFinish as L, AgentPrepareStep as M, AgentPrepareStepInput as N, AgentPrepareStepResult as O, AgentProgressEvent as P, AgentReplyInfo as Q, AgentRunHandle as R, SkillMarkdownExtras as S, AgentRunOptions as T, AgentStepFinishInfo as U, AgentStepInfo as V, AgentThreadStatus as W, AgentTokenDelta as X, AgentToolCall as Y, AgentToolConfig as Z, AgentUsage as _, AgentReplyRef as a, AgentWorkflowBindingLike as a0, AgentWorkflowInstanceLike as a1, EnsureThreadOutcome as a2, SkillConfig as a3, SkillDefinition as b, AgentToolDefinition as c, AgentToolContext as d, AgentCompact as e, AgentEpisodeExtract as f, AgentGraphExtract as g, AgentGenerate as h, AgentTokenSink as i, AgentRunInput as j, AgentFunctionPaths as k, AgentRunFunction as l, AgentStepLike as m, AgentStreamGenerate as n, AgentRunResult as o, AgentMessageRow as p, AgentConfig as q, AnyAgentTool as r, AgentAsToolOptions as s, AgentSubToolInput as t, AgentModelInput as u, AgentFunctionReference as v, AgentApprovalContext as w, AgentBindingSpec as x, AgentEmailMapper as y, AgentEmailRun as z };
1515
+ export { AgentToolCall as $, AgentDefinition as A, AgentEmailRun as B, AgentEmailShardInput as C, AgentGenerateOptions as D, AgentGenerateResult as E, AgentHandle as F, AgentInboundShardResolver as G, AgentInstructionsContext as H, InboundChannelEvent as I, AgentLiveEvent as J, AgentMemoryOptions as K, AgentMemorySource as L, AgentMessageStatus as M, AgentOnReply as N, AgentOnStepFinish as O, AgentPrepareStep as P, AgentPrepareStepInput as Q, AgentPrepareStepResult as R, SkillMarkdownExtras as S, AgentProgressEvent as T, AgentReplyInfo as U, AgentRunHandle as V, AgentRunOptions as W, AgentStepFinishInfo as X, AgentStepInfo as Y, AgentThreadStatus as Z, AgentTokenDelta as _, AgentReplyRef as a, AgentToolConfig as a0, AgentUsage as a1, AgentVoiceConfig as a2, AgentWorkflowBindingLike as a3, AgentWorkflowInstanceLike as a4, EnsureThreadOutcome as a5, SkillConfig as a6, SkillDefinition as b, AgentToolDefinition as c, AgentToolContext as d, AgentCompact as e, AgentEpisodeExtract as f, AgentGraphExtract as g, AgentGenerate as h, AgentTokenSink as i, AgentRunInput as j, AgentFunctionPaths as k, AgentRunFunction as l, AgentStepLike as m, AgentStreamGenerate as n, AgentRunResult as o, AgentMessageRow as p, AgentConfig as q, AnyAgentTool as r, AgentAsToolOptions as s, AgentSubToolInput as t, AgentModelInput as u, AgentFunctionReference as v, AgentApprovalContext as w, AgentBindingSpec as x, AgentChannelShardInput as y, AgentEmailMapper as z };
@@ -16,6 +16,13 @@ interface AgentFunctionReference {
16
16
  * @experimental
17
17
  */
18
18
  interface AgentRunOptions {
19
+ /**
20
+ * Route the call to this shard instead of the default one. Pass
21
+ * {@link AgentToolContext.shardKey} when the target reads `.shardBy(...)` tables —
22
+ * `functionTool` does — and leave it unset for the agent's own `agents:*`
23
+ * functions, whose threads, state and secrets live on the default shard.
24
+ */
25
+ shardKey?: string;
19
26
  /**
20
27
  * Abort the dispatch after this many ms, overriding the runner's 30s
21
28
  * default (`DEFAULT_DISPATCH_TIMEOUT_MS`).
@@ -129,7 +136,10 @@ interface AgentToolContext {
129
136
  * {@link AgentToolContext.toolCallId}. `data` must be JSON-serializable.
130
137
  */
131
138
  reportProgress: (data: unknown) => void;
132
- /** Dispatch a Lunora function (the workflow `ctx.run`). */
139
+ /**
140
+ * Dispatch a Lunora function (the workflow `ctx.run`). Calls go to the default
141
+ * shard unless they pass {@link AgentRunOptions.shardKey}.
142
+ */
133
143
  run: AgentRunFunction;
134
144
  /**
135
145
  * Replace the thread's synced state — dispatches the internal
@@ -153,6 +163,12 @@ interface AgentToolContext {
153
163
  * skip the write when it is already present.
154
164
  */
155
165
  setState: (state: Record<string, unknown>) => Promise<void>;
166
+ /**
167
+ * The shard the run was started on ({@link AgentRunInput.shardKey}); `undefined`
168
+ * for the default shard. Pass it as {@link AgentRunOptions.shardKey} to reach the
169
+ * tenant's `.shardBy(...)` data from a hand-written tool.
170
+ */
171
+ shardKey?: string;
156
172
  /**
157
173
  * The durable-step handle (`step.do`/`waitForEvent`). ALWAYS present:
158
174
  * `agent-loop.ts` threads it into every tool's context unconditionally, and
@@ -630,6 +646,53 @@ interface AgentEmailRun {
630
646
  * @experimental
631
647
  */
632
648
  type AgentEmailMapper = (email: InboundEmail) => AgentEmailRun | null | Promise<AgentEmailRun | null | undefined> | undefined;
649
+ /**
650
+ * Pick the shard an inbound-triggered run's tools use: the app maps a verified identity
651
+ * to a tenant shard. Return `undefined` for the default shard.
652
+ *
653
+ * This is the only way an inbound run gets a shard. A `shardKey` in the mapped run is
654
+ * dropped, because the mapper's output is built from attacker-written content. The hook
655
+ * runs after the sender or signature gate and after the mapper claimed the message, and
656
+ * it is handed only what the platform verified ({@link AgentEmailShardInput},
657
+ * {@link AgentChannelShardInput}). Returning a shard is an authorization decision, since
658
+ * the run's tools dispatch past `authorizeShard`: look the identity up in a table you
659
+ * trust. A throw fails the delivery rather than falling back to the default shard.
660
+ * @experimental
661
+ */
662
+ type AgentInboundShardResolver<Input> = (input: Input) => Promise<string | undefined> | string | undefined;
663
+ /**
664
+ * What `resolveEmailShard` gets.
665
+ * @experimental
666
+ */
667
+ interface AgentEmailShardInput {
668
+ /**
669
+ * The parsed message, for context only. Its headers are sender-written: `email.to`
670
+ * is the `To:` header, which any sender can set to another tenant's address, and
671
+ * `email.from` is only as good as the authentication verdicts. Never derive the
672
+ * shard from it.
673
+ */
674
+ email: InboundEmail;
675
+ /**
676
+ * The SMTP envelope recipient Cloudflare Email Routing delivered this message to.
677
+ * Routing only delivers to addresses you configured, so this is the field to map
678
+ * to a tenant.
679
+ */
680
+ envelopeTo: string;
681
+ }
682
+ /**
683
+ * What `onInbound.resolveShard` gets: the channel and the workspace the signed payload
684
+ * belongs to, never the event's message content.
685
+ * @experimental
686
+ */
687
+ interface AgentChannelShardInput {
688
+ channel: AgentInboundChannelKind;
689
+ /**
690
+ * The provider-set tenant id from the signature-verified body: Slack `team_id`,
691
+ * GitHub `installation.id`, Discord `guild_id`. `undefined` when the payload carries
692
+ * none (a DM interaction, a GitHub event outside an app installation).
693
+ */
694
+ workspaceId: string | undefined;
695
+ }
633
696
  /** The inbound webhook channels an agent can be triggered from — see `@lunora/agent/channels`. */
634
697
  type AgentInboundChannelKind = "discord" | "github" | "slack";
635
698
  /** The run-input an inbound-channel mapper returns — the same shape as {@link AgentEmailRun}. */
@@ -668,6 +731,8 @@ interface AgentInboundChannel {
668
731
  channel: AgentInboundChannelKind;
669
732
  /** Map a verified event to a run (or `null` to decline). */
670
733
  map: AgentChannelMapper;
734
+ /** The shard a claimed event's run uses — see {@link AgentInboundShardResolver}. Default shard when absent. */
735
+ resolveShard?: AgentInboundShardResolver<AgentChannelShardInput>;
671
736
  /**
672
737
  * The verification credential, from `env`: an env-var NAME (string) or an
673
738
  * `(env) => value` resolver. Slack → signing secret; GitHub → webhook secret;
@@ -823,6 +888,12 @@ interface AgentConfig {
823
888
  * unknown-tool-name recovery as the only repair path.
824
889
  */
825
890
  repairToolCall?: ToolCallRepairFunction<ToolSet>;
891
+ /**
892
+ * The shard an `onEmail` run's tools use — see {@link AgentInboundShardResolver}. Map
893
+ * `envelopeTo`, the routed recipient; the parsed headers are sender-written. Default
894
+ * shard when absent.
895
+ */
896
+ resolveEmailShard?: AgentInboundShardResolver<AgentEmailShardInput>;
826
897
  /**
827
898
  * Reusable {@link SkillDefinition}s to compose in — each contributes an
828
899
  * instruction fragment, tools (merged into the flat namespace; collisions
@@ -1016,6 +1087,14 @@ interface AgentRunInput {
1016
1087
  owner?: string;
1017
1088
  /** Where a triggered run sends its answer — see {@link AgentReplyRef}. */
1018
1089
  replyRef?: AgentReplyRef;
1090
+ /**
1091
+ * The shard whose app data the run's tools read and write. Set only by the boundary
1092
+ * that starts the run, from a source it trusts: `ctx.agents.<name>.run` uses the
1093
+ * shard of the mutation or action that calls it, a scheduled run the scheduling
1094
+ * shard, an inbound run the app's `resolveEmailShard` / `resolveShard` hook. A
1095
+ * value in the input is always overwritten, since the input may be a client's.
1096
+ */
1097
+ shardKey?: string;
1019
1098
  /** The thread key — reuse to continue a conversation. */
1020
1099
  threadKey: string;
1021
1100
  /** Optional thread title, set on first creation. */
@@ -1433,4 +1512,4 @@ interface AgentHandle {
1433
1512
  /** Read a run's workflow status by instance id. */
1434
1513
  status: (id: string) => Promise<unknown>;
1435
1514
  }
1436
- export { AgentVoiceConfig as $, AgentDefinition as A, AgentGenerateOptions as B, AgentGenerateResult as C, AgentHandle as D, AgentInstructionsContext as E, AgentLiveEvent as F, AgentMemoryOptions as G, AgentMemorySource as H, InboundChannelEvent as I, AgentMessageStatus as J, AgentOnReply as K, AgentOnStepFinish as L, AgentPrepareStep as M, AgentPrepareStepInput as N, AgentPrepareStepResult as O, AgentProgressEvent as P, AgentReplyInfo as Q, AgentRunHandle as R, SkillMarkdownExtras as S, AgentRunOptions as T, AgentStepFinishInfo as U, AgentStepInfo as V, AgentThreadStatus as W, AgentTokenDelta as X, AgentToolCall as Y, AgentToolConfig as Z, AgentUsage as _, AgentReplyRef as a, AgentWorkflowBindingLike as a0, AgentWorkflowInstanceLike as a1, EnsureThreadOutcome as a2, SkillConfig as a3, SkillDefinition as b, AgentToolDefinition as c, AgentToolContext as d, AgentCompact as e, AgentEpisodeExtract as f, AgentGraphExtract as g, AgentGenerate as h, AgentTokenSink as i, AgentRunInput as j, AgentFunctionPaths as k, AgentRunFunction as l, AgentStepLike as m, AgentStreamGenerate as n, AgentRunResult as o, AgentMessageRow as p, AgentConfig as q, AnyAgentTool as r, AgentAsToolOptions as s, AgentSubToolInput as t, AgentModelInput as u, AgentFunctionReference as v, AgentApprovalContext as w, AgentBindingSpec as x, AgentEmailMapper as y, AgentEmailRun as z };
1515
+ export { AgentToolCall as $, AgentDefinition as A, AgentEmailRun as B, AgentEmailShardInput as C, AgentGenerateOptions as D, AgentGenerateResult as E, AgentHandle as F, AgentInboundShardResolver as G, AgentInstructionsContext as H, InboundChannelEvent as I, AgentLiveEvent as J, AgentMemoryOptions as K, AgentMemorySource as L, AgentMessageStatus as M, AgentOnReply as N, AgentOnStepFinish as O, AgentPrepareStep as P, AgentPrepareStepInput as Q, AgentPrepareStepResult as R, SkillMarkdownExtras as S, AgentProgressEvent as T, AgentReplyInfo as U, AgentRunHandle as V, AgentRunOptions as W, AgentStepFinishInfo as X, AgentStepInfo as Y, AgentThreadStatus as Z, AgentTokenDelta as _, AgentReplyRef as a, AgentToolConfig as a0, AgentUsage as a1, AgentVoiceConfig as a2, AgentWorkflowBindingLike as a3, AgentWorkflowInstanceLike as a4, EnsureThreadOutcome as a5, SkillConfig as a6, SkillDefinition as b, AgentToolDefinition as c, AgentToolContext as d, AgentCompact as e, AgentEpisodeExtract as f, AgentGraphExtract as g, AgentGenerate as h, AgentTokenSink as i, AgentRunInput as j, AgentFunctionPaths as k, AgentRunFunction as l, AgentStepLike as m, AgentStreamGenerate as n, AgentRunResult as o, AgentMessageRow as p, AgentConfig as q, AnyAgentTool as r, AgentAsToolOptions as s, AgentSubToolInput as t, AgentModelInput as u, AgentFunctionReference as v, AgentApprovalContext as w, AgentBindingSpec as x, AgentChannelShardInput as y, AgentEmailMapper as z };
@@ -0,0 +1 @@
1
+ const p=(n,c,o)=>{const f=new Set(c.map(r=>r.className)),i=r=>{const e=r?.className;return typeof r=="object"&&typeof e=="string"&&f.has(e)};return new Proxy({},{get(r,e){const t=Reflect.get(n,e,n);if(e==="runAfter"||e==="runAt"){if(typeof t!="function")return t;const u=t;return async(y,s,g,a)=>{const l=i(s)?{...a,shardKey:a?.shardKey??o}:a;return Reflect.apply(u,n,[y,s,g,l])}}return typeof t=="function"?t.bind(n):t},has(r,e){return Reflect.has(n,e)},ownKeys(){return Reflect.ownKeys(n)},getOwnPropertyDescriptor(r,e){const t=Reflect.getOwnPropertyDescriptor(n,e);return t===void 0?void 0:{...t,configurable:!0}}})};export{p as default};
package/dist/reply.d.mts CHANGED
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { Mailer } from '@lunora/mail';
20
20
  import { InboundEmail } from '@lunora/mail/inbound';
21
- import { a as AgentReplyRef } from "./packem_shared/types.d-Bq-ZDGI6.mjs";
21
+ import { a as AgentReplyRef } from "./packem_shared/types.d-Bzy_Qah6.mjs";
22
22
  import 'ai';
23
23
  /** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
24
24
  type EmailReplyRef = Extract<AgentReplyRef, {
package/dist/reply.d.ts CHANGED
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { Mailer } from '@lunora/mail';
20
20
  import { InboundEmail } from '@lunora/mail/inbound';
21
- import { a as AgentReplyRef } from "./packem_shared/types.d-Bq-ZDGI6.js";
21
+ import { a as AgentReplyRef } from "./packem_shared/types.d-Bzy_Qah6.js";
22
22
  import 'ai';
23
23
  /** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
24
24
  type EmailReplyRef = Extract<AgentReplyRef, {
@@ -1,4 +1,4 @@
1
- import { c as AgentToolDefinition, d as AgentToolContext } from "./packem_shared/types.d-Bq-ZDGI6.mjs";
1
+ import { c as AgentToolDefinition, d as AgentToolContext } from "./packem_shared/types.d-Bzy_Qah6.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-Bq-ZDGI6.js";
1
+ import { c as AgentToolDefinition, d as AgentToolContext } from "./packem_shared/types.d-Bzy_Qah6.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-Bq-ZDGI6.mjs";
1
+ import { S as SkillMarkdownExtras, b as SkillDefinition } from "./packem_shared/types.d-Bzy_Qah6.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-Bq-ZDGI6.js";
1
+ import { S as SkillMarkdownExtras, b as SkillDefinition } from "./packem_shared/types.d-Bzy_Qah6.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.277",
3
+ "version": "1.0.0-alpha.278",
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",
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as I}from"@lunora/workflow";import{f as L}from"./fnv1a-BNN96GYb.mjs";import{r as S}from"./workflow-binding-Dm9hBzx_.mjs";import b from"./jsonSchema-fhoaBWpN.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as $,DEFAULT_AGENT_FUNCTION_PATHS as P}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),x=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",k=t=>t!==null&&typeof t=="object"?t.output:void 0,C=async t=>{await new Promise(e=>{setTimeout(e,t)})},D=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=R(a);if(_.has(s))return{output:k(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},U=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},j=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},V=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??x,o=t.pollIntervalMs??M,a=t.wait??C,s=$(P.listMessages),T=async(y,r)=>{const p=(h(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=S(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,g=`sub-${e}-${L(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:g,params:A});l=await i.get(d.id)}catch(d){if(!I(d))throw d;l=await i.get(g)}const{output:v,status:u}=await 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:b({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{V as agentAsTool};
@@ -1 +0,0 @@
1
- import u from"./jsonSchema-fhoaBWpN.mjs";import{toFunctionReference as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const h=240,m=50,y=(t,s)=>t.length<=s?t:`${t.slice(0,s)}…`,f=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(m,Math.max(1,Math.trunc(t)))},g=(t,s)=>{const r=t??{},i=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:y(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},S=u({additionalProperties:!1,properties:{query:{description:"Natural-language search query.",type:"string"},topK:{description:"Maximum number of hits to return.",type:"number"}},required:["query"],type:"object"}),A=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),b=(t,s,r)=>{const i=d(s),e=Math.max(1,t.snippetChars??h),o=t.topK;return{description:`Search long-term memory for passages relevant to a query. Returns ranked { id, sourceId, score, snippet } hits — call again with a refined query to dig deeper.${r===void 0?"":` Use \`${r}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,p)=>{const a=f(n.topK)??o,l=await p.run(i,{query:n.query,...a===void 0?{}:{topK:a}});return g(l,e)},inputSchema:S,isLunoraAgentTool:!0}},T=t=>{const s=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,i)=>i.run(s,{id:r.id}),inputSchema:A,isLunoraAgentTool:!0}},k=(t,s)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of s)e.knowledge&&r.push({key:e.name,...e.knowledge});const i={};for(const e of r){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,c=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=b(e,e.source,n?c:void 0),n&&(i[c]=T(e.read))}return i};export{k as collectAgenticMemoryTools,g as toSearchResults};
@@ -1 +0,0 @@
1
- import{a as f}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.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-CYBmT9SD.mjs";const _=(r,c,i={})=>{const{dispatch:u,exports:l}=i,s={},d=E(N.patchThread),p=()=>u??f({env:r,label:"@lunora/agent"});for(const e of c){const n=()=>{const t=h(r,l,e.className,["create","get"]);if(t===void 0)throw new o("INTERNAL",`@lunora/agent: no "${e.className}" on ctx.exports or env for agent "${e.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return t};s[e.exportName]={cancel:async t=>{await(await n().get(t)).terminate();try{await p()(d,{instanceId:t,status:"cancelled"})}catch{}},publicRun:e.publicRun===!0,run:async(t,a)=>{if(g(t))throw new o("BAD_REQUEST",`@lunora/agent: run input ${w}`);return{id:(await n().create({...a?.id===void 0?{}:{id:a.id},params:t})).id}},sendEvent:async(t,a)=>{await(await n().get(t)).sendEvent(a)},status:async t=>(await n().get(t)).status()}}return s};export{_ as default};
@@ -1,3 +0,0 @@
1
- import{LunoraError as r}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-RTz0T3qJ.mjs";import{agentAsTool as g}from"./agentAsTool-DiIz7AR0.mjs";import{a as p}from"./component-shared--SPcu0Iw.mjs";import{i as m}from"./memory-JI0lUu84.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=e=>{if(e!==void 0&&(typeof e!="string"||e.length===0))throw new r("INTERNAL","@lunora/agent: defineAgent `name` must be a non-empty string when provided")},N=/^[a-zA-Z][\w-]*$/u,A=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=a}return o},k=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
2
-
3
- `)},y=(e,n)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const t of n)t.knowledge&&m(t.knowledge)&&o.push({key:t.name,...t.knowledge});return o},v=e=>{const n=new Set;for(const o of e){if(typeof o.name!="string"||!w.test(o.name))throw new r("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new r("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(n.has(o.name))throw new r("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);n.add(o.name)}},E=(e,n)=>{if(e===void 0)return;const o=Object.keys(n).filter(t=>!e.includes(t));if(o.length>0)throw new r("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(t=>`"${t}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},L=(e,n)=>{const o=(t,s)=>{if(t&&t.kind!=="graph"&&t.kind!=="episodic"&&t.source===void 0)throw new r("INTERNAL",`@lunora/agent: ${s} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const t of n)o(t.knowledge,`skill "${t.name}" \`knowledge\``)},I=e=>{if(e===void 0)return;const n=p(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},M=e=>{const n=e.model;if(n==null||typeof n=="string"&&n.length===0)throw new r("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(T(e.name),e.maxTurns!==void 0&&!u(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!u(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");I(e.approvalTimeout);const o=e.skills??[];v(o),L(e,o);const t=A(e,o),s=f(e,o);for(const[i,h]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=h}const a=Object.keys(s).length>0;E(e.activeTools,s);for(const i of Object.keys(t))if(!N.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=y(e,o),d=k(e,o);return{...e,asTool:g,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:t}:{}}},_=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,q=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{M as defineAgent,q as defineAgentTool,_ as isAgentDefinition};
@@ -1 +0,0 @@
1
- import{LunoraError as o}from"@lunora/errors";import{toFunctionReference as c}from"./AGENT_MODULE-CYBmT9SD.mjs";const m=(r,e)=>{if(typeof e.description!="string"||e.description.length===0)throw new o("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(e.inputSchema===void 0)throw new o("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const t=c(r);return{description:e.description,execute:(i,n)=>n.run(t,{...i,idempotencyKey:n.idempotencyKey}),inputSchema:e.inputSchema,isLunoraAgentTool:!0}};export{m as functionTool};