@lunora/agent 1.0.0-alpha.276 → 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 (69) hide show
  1. package/README.md +1 -2
  2. package/dist/channels.d.mts +2 -2
  3. package/dist/channels.d.ts +2 -2
  4. package/dist/channels.mjs +1 -1
  5. package/dist/component.mjs +1 -1
  6. package/dist/core.d.mts +204 -0
  7. package/dist/core.d.ts +204 -0
  8. package/dist/core.mjs +1 -0
  9. package/dist/inbound.d.mts +4 -4
  10. package/dist/inbound.d.ts +4 -4
  11. package/dist/inbound.mjs +1 -1
  12. package/dist/index.d.mts +7 -167
  13. package/dist/index.d.ts +7 -167
  14. package/dist/index.mjs +1 -1
  15. package/dist/packem_chunks/createAgentGenerate.mjs +3 -0
  16. package/dist/packem_chunks/otlpTelemetry.mjs +1 -0
  17. package/dist/packem_chunks/resolve-run.mjs +1 -0
  18. package/dist/packem_chunks/runAgentLoop.mjs +3 -0
  19. package/dist/packem_shared/SecretUnavailableError-DOy2M4Ak.mjs +1 -0
  20. package/dist/packem_shared/VoiceSessionDO-CdvG2L-D.mjs +1 -0
  21. package/dist/packem_shared/{adaptMcpResult-DOud9k_Q.mjs → adaptMcpResult-CA-3ovJd.mjs} +1 -1
  22. package/dist/packem_shared/agentAsTool-BF-7Dnzy.mjs +1 -0
  23. package/dist/packem_shared/app-call-options-BE0CQ6Qg.mjs +1 -0
  24. package/dist/packem_shared/codeTool-Cn8TuNjk.mjs +1 -0
  25. package/dist/packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs +1 -0
  26. package/dist/packem_shared/compileAgentWorkflow-yZB8fbYc.mjs +1 -0
  27. package/dist/packem_shared/component-shared--SPcu0Iw.mjs +1 -0
  28. package/dist/packem_shared/createAgentContext-C8k1y2Ot.mjs +1 -0
  29. package/dist/packem_shared/defineAgent-6Ih7L9E9.mjs +3 -0
  30. package/dist/packem_shared/functionTool-Cf433Hdo.mjs +1 -0
  31. package/dist/packem_shared/inbound-shard-A7S7dnf_.mjs +1 -0
  32. package/dist/packem_shared/{jsCodeTool-Bh4jaeoy.mjs → jsCodeTool-BJB3Fpm2.mjs} +1 -1
  33. package/dist/packem_shared/jsonSchema-fhoaBWpN.mjs +1 -0
  34. package/dist/packem_shared/memory-JI0lUu84.mjs +1 -0
  35. package/dist/packem_shared/{normalizeEntityName-Rr5OQxhc.mjs → normalizeEntityName-BiUH5B5W.mjs} +1 -1
  36. package/dist/packem_shared/run-shard-B7iMrAI0.mjs +1 -0
  37. package/dist/packem_shared/runVoiceTurn-DPa5UZ45.mjs +1 -0
  38. package/dist/packem_shared/{types.d-vAmttAsE.d.mts → types.d-Bzy_Qah6.d.mts} +81 -2
  39. package/dist/packem_shared/{types.d-vAmttAsE.d.ts → types.d-Bzy_Qah6.d.ts} +81 -2
  40. package/dist/packem_shared/voice-turn-B9omvXoR.mjs +1 -0
  41. package/dist/packem_shared/webSearchTool-BzXW0R4r.mjs +1 -0
  42. package/dist/packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs +1 -0
  43. package/dist/reply.d.mts +1 -1
  44. package/dist/reply.d.ts +1 -1
  45. package/dist/sandbox.d.mts +1 -1
  46. package/dist/sandbox.d.ts +1 -1
  47. package/dist/sandbox.mjs +1 -1
  48. package/dist/skill-markdown.d.mts +1 -1
  49. package/dist/skill-markdown.d.ts +1 -1
  50. package/dist/telemetry/index.mjs +1 -1
  51. package/package.json +5 -1
  52. package/dist/packem_shared/SecretUnavailableError-D8u6pPM6.mjs +0 -1
  53. package/dist/packem_shared/VoiceSessionDO-D4dEV12P.mjs +0 -1
  54. package/dist/packem_shared/agent-loop-C11GY0Yw.mjs +0 -3
  55. package/dist/packem_shared/agentAsTool-ifwGRMR6.mjs +0 -1
  56. package/dist/packem_shared/codeTool-BZkKDqsZ.mjs +0 -1
  57. package/dist/packem_shared/collectAgenticMemoryTools-Dxs7mpo6.mjs +0 -1
  58. package/dist/packem_shared/compileAgentWorkflow-DDQ-_8S0.mjs +0 -1
  59. package/dist/packem_shared/component-shared-DdXFbng-.mjs +0 -1
  60. package/dist/packem_shared/createAgentContext-CjdW-jip.mjs +0 -1
  61. package/dist/packem_shared/createAgentGenerate-CTkL_e0Z.mjs +0 -3
  62. package/dist/packem_shared/defineAgent-BsDM3vh8.mjs +0 -3
  63. package/dist/packem_shared/functionTool-C95ns65V.mjs +0 -1
  64. package/dist/packem_shared/json-schema-CHVg-SsJ.mjs +0 -1
  65. package/dist/packem_shared/otlpTelemetry-CiSI9HE_.mjs +0 -1
  66. package/dist/packem_shared/runAgentLoop-8K0vPhGY.mjs +0 -1
  67. package/dist/packem_shared/runVoiceTurn-C4BAG61O.mjs +0 -1
  68. package/dist/packem_shared/voice-turn-BjkorohD.mjs +0 -1
  69. package/dist/packem_shared/webSearchTool-DUubGqov.mjs +0 -1
package/README.md CHANGED
@@ -6,8 +6,7 @@ Durable AI agents for [Lunora](https://lunora.sh): `defineAgent` compiles a repl
6
6
 
7
7
  ```ts
8
8
  // lunora/agents.ts
9
- import { defineAgent, defineAgentTool } from "@lunora/agent";
10
- import { jsonSchema } from "@lunora/ai";
9
+ import { defineAgent, defineAgentTool, jsonSchema } from "@lunora/agent/core";
11
10
 
12
11
  export const support = defineAgent({
13
12
  instructions: "You are a helpful support agent.",
@@ -1,5 +1,5 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-vAmttAsE.mjs";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-vAmttAsE.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-vAmttAsE.js";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-vAmttAsE.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};
@@ -1,2 +1,2 @@
1
- import{LunoraError as w}from"@lunora/errors";import{SecretValueTooLargeError as we}from"@lunora/platform";import{defineTable as N,initLunora as W,defineSchemaExtension as Ie}from"@lunora/server";import{v as e}from"@lunora/values";import{a as T,A as x,d as G,b as be,c as ge,S as fe}from"./packem_shared/component-shared-DdXFbng-.mjs";import{graphTables as qe,graphComponent as Ae}from"./packem_shared/normalizeEntityName-Rr5OQxhc.mjs";import{normalizeEntityName as et}from"./packem_shared/normalizeEntityName-Rr5OQxhc.mjs";import{sandboxComponent as nt}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const D="agent_episodes",Ke=5,ve=20,Te=500,j=200,Ce=/\s+/gu,Ee=s=>s===void 0||!Number.isFinite(s)?Ke:Math.min(ve,Math.max(1,Math.trunc(s))),_e={episodes:N({createdAt:e.number(),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).index("byOwnerCreatedAt",["owner","createdAt"]).index("byOwnerMessageKey",["owner","messageKey"],{unique:!0}).public()},{mutation:ke,query:Se}=W.dataModel().create(),Ne=()=>{const s=ke.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:l,ctx:u})=>{const c=l.summary.replaceAll(Ce," ").trim().slice(0,Te);if(c.length===0)return{recorded:!1};if(await u.db.query(D).withIndex("byOwnerMessageKey",h=>h.eq("owner",l.owner).eq("messageKey",l.messageKey)).first())return{recorded:!1};await u.db.insert(D,{createdAt:l.createdAt??Date.now(),messageKey:l.messageKey,owner:l.owner,summary:c,...l.threadKey===void 0?{}:{threadKey:l.threadKey}});const q=await u.db.query(D).withIndex("byOwnerCreatedAt",h=>h.eq("owner",l.owner)).order("asc").take(j+1);for(const h of q.slice(0,Math.max(0,q.length-j)))await u.db.delete(D,h._id);return{recorded:!0}}),o=Se.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:l,ctx:u})=>{const c=await u.db.query(D).withIndex("byOwnerCreatedAt",m=>m.eq("owner",l.owner)).order("desc").take(Ee(l.limit));return c.length===0?{context:""}:{context:c.toReversed().map(m=>`- ${m.summary}`).join(`
1
+ import{LunoraError as w}from"@lunora/errors";import{SecretValueTooLargeError as we}from"@lunora/platform";import{defineTable as N,initLunora as W,defineSchemaExtension as Ie}from"@lunora/server";import{v as e}from"@lunora/values";import{b as T,A as x,d as G,c as be,e as ge,S as fe}from"./packem_shared/component-shared--SPcu0Iw.mjs";import{graphTables as qe,graphComponent as Ae}from"./packem_shared/normalizeEntityName-BiUH5B5W.mjs";import{normalizeEntityName as et}from"./packem_shared/normalizeEntityName-BiUH5B5W.mjs";import{sandboxComponent as nt}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const D="agent_episodes",Ke=5,ve=20,Te=500,j=200,Ce=/\s+/gu,Ee=s=>s===void 0||!Number.isFinite(s)?Ke:Math.min(ve,Math.max(1,Math.trunc(s))),_e={episodes:N({createdAt:e.number(),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).index("byOwnerCreatedAt",["owner","createdAt"]).index("byOwnerMessageKey",["owner","messageKey"],{unique:!0}).public()},{mutation:ke,query:Se}=W.dataModel().create(),Ne=()=>{const s=ke.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:l,ctx:u})=>{const c=l.summary.replaceAll(Ce," ").trim().slice(0,Te);if(c.length===0)return{recorded:!1};if(await u.db.query(D).withIndex("byOwnerMessageKey",h=>h.eq("owner",l.owner).eq("messageKey",l.messageKey)).first())return{recorded:!1};await u.db.insert(D,{createdAt:l.createdAt??Date.now(),messageKey:l.messageKey,owner:l.owner,summary:c,...l.threadKey===void 0?{}:{threadKey:l.threadKey}});const q=await u.db.query(D).withIndex("byOwnerCreatedAt",h=>h.eq("owner",l.owner)).order("asc").take(j+1);for(const h of q.slice(0,Math.max(0,q.length-j)))await u.db.delete(D,h._id);return{recorded:!0}}),o=Se.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:l,ctx:u})=>{const c=await u.db.query(D).withIndex("byOwnerCreatedAt",m=>m.eq("owner",l.owner)).order("desc").take(Ee(l.limit));return c.length===0?{context:""}:{context:c.toReversed().map(m=>`- ${m.summary}`).join(`
2
2
  `)}});return{agentEpisodeRecall:T(o),agentEpisodeUpsert:T(s)}},Y="threads",z="messages",J="run_queue",Z="approval_grants",ee="secret_requests",p=`${x}_${Y}`,K=`${x}_${z}`,S=`${x}_${J}`,R=`${x}_${Z}`,_=`${x}_${ee}`,Re=50,xe=200,$e=500,H=5,P=e.object({cacheReadTokens:e.optional(e.number()),cacheWriteTokens:e.optional(e.number()),inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),reasoningTokens:e.optional(e.number()),status:e.optional(e.union(e.literal("complete"),e.literal("partial"),e.literal("unavailable"))),totalTokens:e.optional(e.number())}),De=780*60*1e3,Oe=Ie(x,{tables:{[z]:N({approvalScope:e.optional(e.literal("thread")),content:e.string(),createdAt:e.number(),expiresAt:e.optional(e.number()),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),seq:e.number(),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("awaiting_secret"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).index("byThread",["threadKey","seq"]).index("byMessageKey",["threadKey","messageKey"],{unique:!0}).public(),[Y]:N({agent:e.string(),createdAt:e.number(),error:e.optional(e.string().nullable()),completedInstanceId:e.optional(e.string().nullable()),instanceId:e.optional(e.string()),key:e.string(),messageCount:e.number(),owner:e.optional(e.string()),state:e.optional(e.any()),status:e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input")),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(P)}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).index("byOwnerStatus",["owner","status","updatedAt"]).public(),[J]:N({agent:e.string(),enqueuedAt:e.number(),instanceId:e.string(),position:e.number(),threadKey:e.string()}).index("byThread",["threadKey","position"]).index("byThreadInstance",["threadKey","instanceId"],{unique:!0}).public(),[Z]:N({createdAt:e.number(),threadKey:e.string(),toolName:e.string()}).index("byThreadTool",["threadKey","toolName"],{unique:!0}).public(),[ee]:N({consumerTool:e.string(),createdAt:e.number(),expiresAt:e.number(),instanceId:e.string(),ref:e.optional(e.string().nullable()),label:e.optional(e.string().nullable()),status:e.union(e.literal("pending"),e.literal("supplied"),e.literal("declined"),e.literal("expired"),e.literal("consumed")),threadKey:e.string(),toolCallId:e.string(),callId:e.optional(e.string()),toolName:e.string(),updatedAt:e.number()}).index("byThreadCall",["threadKey","toolCallId"],{unique:!0}).index("byThreadCallId",["threadKey","callId"]).public(),...qe,..._e}}),{mutation:A,query:k}=W.dataModel().create(),Me=async(s,o,l,u)=>{const c=await s.query(K).withIndex("byMessageKey",$=>$.eq("threadKey",o).eq("messageKey",`${l}:approval:${u}`)).first();if(c?.status!=="awaiting_approval")throw new w("CONFLICT",`@lunora/agent: no pending approval for tool call "${u}" to grant for thread "${o}"`);const{expiresAt:m}=c;if(typeof m!="number")throw new w("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${o}" has no recorded deadline, so it cannot be granted for the thread`);if(Date.now()>=m)throw new w("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${o}" has timed out`);const q=c.toolName;await s.query(R).withIndex("byThreadTool",$=>$.eq("threadKey",o).eq("toolName",q)).first()||await s.insert(R,{createdAt:Date.now(),threadKey:o,toolName:q})},Le=async(s,o,l,u)=>(await s.query(K).withIndex("byMessageKey",m=>m.eq("threadKey",o).eq("messageKey",`${l}:approval:${u}`)).first())?.status==="awaiting_approval",Be=async(s,o,l,u)=>{const c=await s.query(K).withIndex("byMessageKey",m=>m.eq("threadKey",o).eq("messageKey",`${l}:approval:${u}`)).first();c?.status==="awaiting_approval"&&await s.delete(K,c._id)},L=s=>{const{agentSecrets:o}=s;if(o===void 0)throw new w("NOT_IMPLEMENTED","@lunora/agent: no secret store is wired on this deployment. Codegen wires one only when a source in lunora/ value-imports requestSecretTool from @lunora/agent (directly, through a namespace import, or through a relative barrel that re-exports it); add that import, or this target cannot hold a human-supplied secret value");return o},M=(s,o,l)=>{const u=o.userId??void 0;if(s===null||u===void 0||s.owner!==u)throw new w("FORBIDDEN",`@lunora/agent: only the thread's owner can ${l}`);return s},V=async(s,o,l)=>{const{instanceId:u,key:c}=o,m=typeof u=="string"?await s.query(K).withIndex("byMessageKey",q=>q.eq("threadKey",c).eq("messageKey",`${u}:secret:${l}`)).first():void 0;if(m?.status!=="awaiting_secret")throw new w("CONFLICT",`@lunora/agent: no pending secret request for tool call "${l}" on thread "${c}"`);return m},O=async(s,o,l)=>await s.query(_).withIndex("byThreadCall",c=>c.eq("threadKey",o).eq("toolCallId",l)).first()??void 0,X=async(s,o,l,u,c)=>{const q=(await s.query(_).withIndex("byThreadCallId",h=>h.eq("threadKey",o).eq("callId",u)).collect()).filter(h=>h.status==="pending"&&h.instanceId===l&&c<h.expiresAt);if(q.length!==1)throw new w("CONFLICT",`@lunora/agent: no pending secret request for tool call "${u}" on thread "${o}"`);return q[0]},Pe=(s,o)=>Math.max(ge,s+fe-o),B=async(s,o,l,u)=>{const c=await O(s,o,l);if(c?.status!=="pending"||u>=c.expiresAt)throw new w("CONFLICT",`@lunora/agent: no open secret request for tool call "${l}" on thread "${o}"`);return c},Q=(s,o)=>{const{instanceId:l}=o,{agents:u}=s,c=u?.[o.agent];if(typeof l!="string"||typeof c?.sendEvent!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${String(o.agent)}"] producer to deliver the secret — run codegen/dev`);return{instanceId:l,sendEvent:c.sendEvent}},Ue=async(s,o,l)=>{if(o.instanceId===void 0)throw new w("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:u}=o,c=await s.query(S).withIndex("byThreadInstance",h=>h.eq("threadKey",o.key).eq("instanceId",u)).first();if(c)return{outcome:"queued",position:c.position};const m=await s.query(S).withIndex("byThread",h=>h.eq("threadKey",o.key)).collect();if(m.length>=H)throw new w("CONFLICT",`@lunora/agent: thread "${o.key}" run queue is full (depth ${String(H)}) — rejecting instance "${u}"`);const q=(m.at(-1)?.position??-1)+1;return await s.insert(S,{agent:o.agent,enqueuedAt:l,instanceId:u,position:q,threadKey:o.key}),{outcome:"queued",position:q}},Fe=async(s,o,l)=>{if(o.policy==="queue")return Ue(s,{agent:o.agent,instanceId:o.instanceId,key:o.key,priorInstanceId:o.priorInstanceId},l);if(o.policy!=="replace")throw new w("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — onConcurrentRun="${o.policy}"`);return await s.patch(p,o.existingId,{error:null,status:"running",updatedAt:l,...o.instanceId===void 0?{}:{completedInstanceId:null,instanceId:o.instanceId}}),{outcome:"replaced",priorInstanceId:o.priorInstanceId}},Ge=(s,o,l)=>{const u=s.instanceId;if(u===void 0||o===u||s.status!=="running"&&s.status!=="awaiting_input")return;const c=typeof s.updatedAt=="number"?s.updatedAt:0,m=s.status==="awaiting_input"?be:De;return l-c>m?void 0:u},ze=()=>{const s=A.input({agent:e.string(),initialState:e.optional(e.any()),instanceId:e.optional(e.string()),key:e.string(),onConcurrentRun:e.optional(e.union(e.literal("reject"),e.literal("queue"),e.literal("replace"))),owner:e.optional(e.string()),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.key)).first();if(i){if(i.owner!==t.owner)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);if(t.instanceId!==void 0&&i.completedInstanceId===t.instanceId)return{outcome:"completed"};const r=Ge(i,t.instanceId,a);return r!==void 0?Fe(n.db,{agent:t.agent,existingId:i._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:r},a):(await n.db.patch(p,i._id,{error:null,status:"running",updatedAt:a,...t.instanceId===void 0?{}:{completedInstanceId:null,instanceId:t.instanceId}}),{outcome:"continued"})}return await n.db.insert(p,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...G({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),o=A.input({approvalScope:e.optional(e.literal("thread")),content:e.string(),expiresAt:e.optional(e.number()),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("awaiting_secret"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(K).withIndex("byMessageKey",I=>I.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const i=await n.db.query(p).withIndex("byKey",I=>I.eq("key",t.threadKey)).first();if(!i)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const r=i.messageCount,d=Date.now();return await n.db.insert(K,{content:t.content,createdAt:d,messageKey:t.messageKey,role:t.role,seq:r,threadKey:t.threadKey,...t.approvalScope===void 0?{}:{approvalScope:t.approvalScope},...t.expiresAt===void 0?{}:{expiresAt:t.expiresAt},...t.status===void 0?{}:{status:t.status},...t.stepName===void 0?{}:{stepName:t.stepName},...t.toolCallId===void 0?{}:{toolCallId:t.toolCallId},...t.toolCalls===void 0?{}:{toolCalls:t.toolCalls},...t.toolName===void 0?{}:{toolName:t.toolName}}),await n.db.patch(p,i._id,{messageCount:r+1,updatedAt:d}),{seq:r}}),l=A.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(K).withIndex("byMessageKey",i=>i.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(K,a._id)}),u=A.input({error:e.optional(e.string()),ifInstanceId:e.optional(e.string()),instanceId:e.optional(e.string()),key:e.optional(e.string()),status:e.optional(e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input"))),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),usage:e.optional(P)}).mutation(async({args:t,ctx:n})=>{const{instanceId:a,key:i}=t;let r;i!==void 0?r=await n.db.query(p).withIndex("byKey",d=>d.eq("key",i)).first():a!==void 0&&(r=await n.db.query(p).withIndex("byInstance",d=>d.eq("instanceId",a)).first()),!(!r||t.ifInstanceId!==void 0&&r.instanceId!==t.ifInstanceId)&&await n.db.patch(p,r._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.summary===void 0?{}:{summary:t.summary},...t.summaryConfig===void 0?{}:{summaryConfig:t.summaryConfig},...t.summaryRebuiltSeq===void 0?{}:{summaryRebuiltSeq:t.summaryRebuiltSeq},...t.summaryThroughSeq===void 0?{}:{summaryThroughSeq:t.summaryThroughSeq},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),c=k.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",f=>f.eq("key",t.key)).first(),i=a?.summary,r=a?.summaryThroughSeq,d=a?.summaryRebuiltSeq,I=a?.summaryConfig,b=typeof i=="string"&&i.length>0&&typeof r=="number",g=t.configKey===void 0||I===t.configKey,y=typeof d!="number"||typeof r=="number"&&r>=2*d+1,C=b&&g&&!y,v=await n.db.query(K).withIndex("byThread",f=>C?f.eq("threadKey",t.key).gt("seq",r):f.eq("threadKey",t.key)).collect();return C?{messages:v,summary:i}:b?{fallback:{summary:i,throughSeq:r},messages:v}:{messages:v}}),m=A.input({error:e.optional(e.string()),instanceId:e.string(),key:e.string(),status:e.union(e.literal("idle"),e.literal("error"),e.literal("cancelled")),usage:e.optional(P)}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(p).withIndex("byKey",g=>g.eq("key",t.key)).first();if(i?.instanceId!==t.instanceId){if(i?.completedInstanceId===t.instanceId&&i.status==="running"&&typeof i.instanceId=="string")return{dequeued:i.instanceId};const g=await n.db.query(S).withIndex("byThreadInstance",y=>y.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return g&&await n.db.delete(S,g._id),{}}const I=(i.completedInstanceId===t.instanceId?[]:await n.db.query(S).withIndex("byThread",g=>g.eq("threadKey",t.key)).collect())[0];if(!I)return await n.db.patch(p,i._id,{completedInstanceId:t.instanceId,status:t.status,updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{};const b=I.instanceId;return await n.db.delete(S,I._id),await n.db.patch(p,i._id,{completedInstanceId:t.instanceId,instanceId:b,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:b}}),q=A.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();a&&await n.db.patch(p,a._id,{state:t.state,updatedAt:Date.now()})}),h=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},$=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return h(a,n.auth)}),te=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return h(a,n.auth)?.state}),ne=k.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return h(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(K).withIndex("byThread",r=>r.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(K).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),ae=k.input({limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const{userId:a}=n.auth;if(!a)return[];const i=await n.db.query(p).withIndex("byOwnerStatus",y=>y.eq("owner",a).eq("status","awaiting_input")).order("desc").take($e),r=Date.now(),d=Math.min(xe,Math.max(1,Math.trunc(t.limit??Re))),I=async y=>{const C=y.instanceId;if(C===void 0)return[];const v=`${C}:approval:`,f=`${C}:approval;`;return(await n.db.query(K).withIndex("byMessageKey",E=>E.eq("threadKey",y.key).gte("messageKey",v).lt("messageKey",f)).collect()).filter(E=>E.status==="awaiting_approval"&&typeof E.expiresAt=="number"&&r<E.expiresAt).map(E=>G({agent:y.agent,content:E.content,instanceId:C,requestedAt:E.createdAt,threadKey:y.key,threadTitle:y.title,threadUpdatedAt:y.updatedAt,toolCallId:E.toolCallId,toolName:E.toolName}))},b=[];let g=0;for(let y=0;y<i.length&&g<d;y+=d){const C=await Promise.all(i.slice(y,y+d).map(v=>I(v)));for(const v of C)v.length>0&&g<d&&(b.push(...v),g+=1)}return b}),ie=A.input({decision:e.union(e.literal("approve"),e.literal("approve_for_thread"),e.literal("reject")),instanceId:e.string(),note:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",b=>b.eq("key",t.threadKey)).first(),i=h(a,n.auth);if(i===void 0)throw new w("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(i.instanceId!==t.instanceId)throw new w("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const r=i.agent,{agents:d}=n,I=d?.[r];if(typeof I?.sendEvent!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${r}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);if(!await Le(n.db,t.threadKey,t.instanceId,t.toolCallId))throw new w("CONFLICT",`@lunora/agent: no pending approval for tool call "${t.toolCallId}" on thread "${t.threadKey}" to decide`);return t.decision==="approve_for_thread"&&(M(a,n.auth,"grant a lasting approval for a tool"),await Me(n.db,t.threadKey,t.instanceId,t.toolCallId)),await Be(n.db,t.threadKey,t.instanceId,t.toolCallId),await I.sendEvent(t.instanceId,{payload:{decision:t.decision==="reject"?"reject":"approve",toolCallId:t.toolCallId,...t.decision==="approve_for_thread"?{scope:"thread"}:{},...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),oe=A.input({secret:e.sensitive(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=M(await n.db.query(p).withIndex("byKey",f=>f.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),i=L(n),d=(await X(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,I=await V(n.db,a,d),b=Q(n,a),g=a.instanceId,y=f=>{if(f.instanceId!==g)throw new w("CONFLICT",`@lunora/agent: tool call "${t.toolCallId}" on thread "${t.threadKey}" was reopened by a newer run while its secret was being stored`)},C=await B(n.db,t.threadKey,d,Date.now());y(C);let v;try{v=await i.put(t.secret,{scope:t.threadKey,ttlMs:Pe(C.expiresAt,Date.now())})}catch(f){throw f instanceof we?new w("PAYLOAD_TOO_LARGE",f.message):f}try{const f=await B(n.db,t.threadKey,d,Date.now());y(f),await n.db.patch(_,f._id,{ref:v,status:"supplied",updatedAt:Date.now()}),await n.db.delete(K,I._id)}catch(f){throw await i.discard(v).catch(()=>{}),f}try{await b.sendEvent(b.instanceId,{payload:{},type:`agent-secret:${d}`})}catch{}return{resolved:!0}}),re=A.input({threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=M(await n.db.query(p).withIndex("byKey",g=>g.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),r=(await X(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,d=await V(n.db,a,r),I=Q(n,a),b=await B(n.db,t.threadKey,r,Date.now());await n.db.patch(_,b._id,{status:"declined",updatedAt:Date.now()}),await n.db.delete(K,d._id);try{await I.sendEvent(I.instanceId,{payload:{},type:`agent-secret:${r}`})}catch{}return{resolved:!0}}),se=T(A.input({consumerTool:e.string(),expiresAt:e.number(),instanceId:e.string(),callId:e.optional(e.string()),label:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await O(n.db,t.threadKey,t.toolCallId),i=Date.now();if(a===void 0){await n.db.insert(_,{consumerTool:t.consumerTool,createdAt:i,expiresAt:t.expiresAt,instanceId:t.instanceId,label:t.label??null,status:"pending",callId:t.callId??t.toolCallId,threadKey:t.threadKey,toolCallId:t.toolCallId,toolName:t.toolName,updatedAt:i});return}if(a.instanceId!==t.instanceId){if(typeof a.ref=="string"){const{agentSecrets:r}=n;await r?.discard(a.ref)}await n.db.patch(_,a._id,{consumerTool:t.consumerTool,createdAt:i,expiresAt:t.expiresAt,label:t.label??null,ref:null,callId:t.callId??t.toolCallId,instanceId:t.instanceId,status:"pending",toolName:t.toolName,updatedAt:i})}})),de=T(A.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await O(n.db,t.threadKey,t.toolCallId);if(a?.instanceId!==t.instanceId)return{status:"expired"};const{status:i}=a;return i==="pending"?(await n.db.patch(_,a._id,{status:"expired",updatedAt:Date.now()}),{status:"expired"}):i==="supplied"||i==="consumed"?{status:"supplied"}:{status:i==="declined"?"declined":"expired"}})),le=T(A.input({claimant:e.string(),consumerCallId:e.string(),instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await O(n.db,t.threadKey,t.toolCallId);if(!(a?.instanceId!==t.instanceId||a.status!=="supplied"&&a.status!=="consumed")&&!(typeof a.ref!="string"||t.claimant!==`tool:${a.consumerTool}:${t.consumerCallId}`))return L(n).take(a.ref,{claimant:t.claimant,scope:t.threadKey})})),ue=T(A.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await O(n.db,t.threadKey,t.toolCallId);a?.instanceId===t.instanceId&&(typeof a.ref=="string"&&await L(n).discard(a.ref),a.status==="supplied"&&await n.db.patch(_,a._id,{status:"consumed",updatedAt:Date.now()}))})),ce=k.input({threadKey:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",d=>d.eq("key",t.threadKey)).first();M(a,n.auth,"list its secret requests");const i=await n.db.query(_).withIndex("byThreadCall",d=>d.eq("threadKey",t.threadKey)).collect(),r=Date.now();return i.map(d=>({createdAt:d.createdAt,expiresAt:d.expiresAt,...typeof d.label=="string"?{label:d.label}:{},status:d.status==="pending"&&r>=d.expiresAt?"expired":d.status,toolCallId:d.callId??d.toolCallId,toolName:d.toolName}))}),pe=T(k.input({key:e.string(),toolName:e.string()}).query(async({args:t,ctx:n})=>await n.db.query(R).withIndex("byThreadTool",i=>i.eq("threadKey",t.key).eq("toolName",t.toolName)).first()!==null)),ye=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.key)).first();return h(a,n.auth)===void 0?[]:(await n.db.query(R).withIndex("byThreadTool",r=>r.eq("threadKey",t.key)).collect()).map(r=>({createdAt:r.createdAt,toolName:r.toolName}))}),he=A.input({threadKey:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.threadKey)).first();if(h(a,n.auth)===void 0)throw new w("FORBIDDEN",`@lunora/agent: not allowed to revoke approvals on thread "${t.threadKey}"`);const i=await n.db.query(R).withIndex("byThreadTool",r=>r.eq("threadKey",t.threadKey).eq("toolName",t.toolName)).first();return i?(await n.db.delete(R,i._id),{revoked:!0}):{revoked:!1}}),me=A.input({agent:e.string(),input:e.string(),threadKey:e.string(),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const{agents:a}=n,i=a?.[t.agent];if(typeof i?.run!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${t.agent}"] producer to start a run — run codegen/dev so the agent binding is wired, and check the agent name`);if(i.publicRun!==!0)throw new w("FORBIDDEN",`@lunora/agent: agent "${t.agent}" is not enabled for public runs — set defineAgent({ publicRun: true }) to allow an external client (e.g. the @lunora/mcp server) to start it`);const r=n.auth.userId??void 0,d=await n.db.query(p).withIndex("byKey",b=>b.eq("key",t.threadKey)).first();if(d){const b=d.status,g=d.instanceId,y=d.owner;if((b==="running"||b==="awaiting_input")&&g!==void 0&&(y===void 0||y===r))return{id:g,threadKey:t.threadKey};if(y!==r)throw new w("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:I}=await i.run({input:t.input,threadKey:t.threadKey,...r===void 0?{}:{owner:r},...t.title===void 0?{}:{title:t.title}});return{id:I,threadKey:t.threadKey}}),U=Ae(),F=Ne();return{extension:Oe,functions:{agentApprovalGranted:pe,agentApprovalGrants:ye,agentAppendMessage:T(o),agentCompleteRun:T(m),agentEnsureThread:T(s),agentEpisodeRecall:F.agentEpisodeRecall,agentEpisodeUpsert:F.agentEpisodeUpsert,agentGraphTraverse:U.agentGraphTraverse,agentGraphUpsert:U.agentGraphUpsert,agentHistory:T(c),agentMessages:ne,agentDeleteMessage:T(l),agentPatchThread:T(u),agentPendingApprovals:ae,agentResolveApproval:ie,agentRevokeApprovalGrant:he,agentRun:me,agentSetState:T(q),agentState:te,agentSupplySecret:oe,agentTakeSecret:le,agentThread:$,agentDeclineSecret:re,agentDiscardSecret:ue,agentOpenSecretRequest:se,agentSecretRequests:ce,agentSettleSecretRequest:de}}};export{ze as agentComponent,Oe as agentExtension,et as normalizeEntityName,nt as sandboxComponent};
@@ -0,0 +1,204 @@
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
+ import { FlexibleSchema } from 'ai';
4
+ import { jsonSchema as jsonSchema$1, ValidationResult, Schema } from '@ai-sdk/provider-utils';
5
+ import { WorkflowDefinition } from '@lunora/workflow';
6
+ import '@lunora/mail/inbound';
7
+ /**
8
+ * Build the `ctx.agents` producer surface from the codegen-emitted spec list
9
+ * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
10
+ * declared agent resolves by its export key (the generated class name) off the
11
+ * invoking context's `exports` — or `env`, on a host without workflow exports —
12
+ * lazily, so a missing agent only errors when it is actually started.
13
+ *
14
+ * `cancel` also needs to write the thread's status, so it dispatches the agent
15
+ * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
16
+ * and the env-backed `createDispatchRunner` (the same runner the workflow body
17
+ * uses — it POSTs to `/_lunora/scheduler/dispatch`) is built on demand; tests
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.
23
+ * @experimental
24
+ */
25
+ declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
26
+ dispatch?: AgentRunFunction;
27
+ exports?: unknown;
28
+ shardKey?: string;
29
+ }) => Record<string, AgentHandle>;
30
+ /**
31
+ * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
32
+ * (each LLM turn and each tool call a named durable step; thread messages
33
+ * persisted idempotently in DO SQLite), invoked from mutations/actions via
34
+ * `ctx.agents.NAME.run(...)` and observed live by subscribing to the
35
+ * `agents:agentMessages` query.
36
+ *
37
+ * ```ts
38
+ * // lunora/agents.ts
39
+ * import { defineAgent, defineAgentTool } from "@lunora/agent";
40
+ *
41
+ * export const support = defineAgent({
42
+ * instructions: "You are a helpful support agent.",
43
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
44
+ * tools: {
45
+ * getWeather: defineAgentTool({
46
+ * description: "Look up the current weather for a city.",
47
+ * execute: async ({ city }, { run }) => run(api.weather.lookup, { city }),
48
+ * inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
49
+ * }),
50
+ * },
51
+ * });
52
+ * ```
53
+ *
54
+ * Declaring an agent is enough — codegen auto-registers the `agents:*` runtime
55
+ * functions (from `agentComponent()`) and the `ctx.agents` producer surface.
56
+ * @experimental
57
+ */
58
+ declare const defineAgent: (config: AgentConfig) => AgentDefinition;
59
+ /**
60
+ * Runtime brand check for a {@link AgentDefinition}.
61
+ * @experimental
62
+ */
63
+ declare const isAgentDefinition: (value: unknown) => value is AgentDefinition;
64
+ /**
65
+ * Declare an agent tool — see `AgentToolDefinition` for why `execute` runs in
66
+ * the loop's durable step (with an `AgentToolContext`) rather than inside the
67
+ * model call.
68
+ * @experimental
69
+ */
70
+ declare const defineAgentTool: <Input, Output>(config: AgentToolConfig<Input, Output>) => AgentToolDefinition<Input, Output>;
71
+ /**
72
+ * Author-supplied config for {@link functionTool}.
73
+ * @experimental
74
+ */
75
+ interface FunctionToolOptions<Input> {
76
+ /** What the tool does — shown to the model (the model decides from it). */
77
+ description: string;
78
+ /** The input schema shown to the model (a zod schema or `jsonSchema(...)`). */
79
+ inputSchema: FlexibleSchema<Input>;
80
+ }
81
+ /**
82
+ * Expose any Lunora query/mutation/action as an agent tool. The returned
83
+ * definition's `execute` dispatches the referenced function through the loop's
84
+ * existing `run` seam (the workflow `ctx.run`) — so there is no bespoke wrapper
85
+ * per tool, and the call runs inside the loop's named durable step exactly like
86
+ * any other tool.
87
+ *
88
+ * ```ts
89
+ * import { functionTool } from "@lunora/agent";
90
+ * import { api } from "./_generated/api";
91
+ *
92
+ * export const support = defineAgent({
93
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
94
+ * tools: {
95
+ * lookupOrder: functionTool(api.orders.byId, {
96
+ * description: "Look up an order by its id.",
97
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
98
+ * }),
99
+ * },
100
+ * });
101
+ * ```
102
+ *
103
+ * The function reference may be a typed `api.*` reference or a `"module:name"`
104
+ * path. The model-provided input is passed as the function's args, so
105
+ * `inputSchema` should mirror the referenced function's argument validator —
106
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
107
+ * input (so out-of-schema model input can never override it). A function
108
+ * that wants to dedupe a side-effecting call across an at-least-once step
109
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
110
+ * and checks it; a function that ignores it is unaffected — an args field
111
+ * the function's own validator doesn't declare is dropped, not rejected.
112
+ * @experimental
113
+ */
114
+ declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
115
+ /**
116
+ * `jsonSchema` from `@ai-sdk/provider-utils`, built without importing it. That package's root
117
+ * evaluates zod (about a hundred modules) as soon as anything is imported from it, and every
118
+ * tool module here builds a schema at module scope, so the root import put zod in every Worker's
119
+ * startup graph that wires an agent. A schema is a plain object, so the agent builds its own; the
120
+ * SDK itself is only imported where a zod schema has to be converted (`code-tool`).
121
+ */
122
+ declare const jsonSchema: <OBJECT = unknown>(schema: Parameters<typeof jsonSchema$1>[0], { validate }?: {
123
+ validate?: (value: unknown) => PromiseLike<ValidationResult<OBJECT>> | ValidationResult<OBJECT>;
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;
136
+ /**
137
+ * Declare a reusable skill: a bundle of expertise — an instruction fragment,
138
+ * tools, and retrieval `knowledge` — an agent composes in via
139
+ * `defineAgent({ skills: [...] })`. Reuse-first: a skill's `tools` carry the
140
+ * SAME `AnyAgentTool` shape agents already use (`functionTool` / `mcpTools` /
141
+ * `agentAsTool`), and `knowledge` reuses `memory`'s `AgentMemoryOptions`
142
+ * retrieval verbatim.
143
+ *
144
+ * ```ts
145
+ * import { defineSkill, functionTool } from "@lunora/agent";
146
+ *
147
+ * export const billing = defineSkill({
148
+ * name: "billing",
149
+ * instructions: "When asked about invoices, cite the invoice id.",
150
+ * knowledge: { source: "rag:searchBillingDocs", topK: 4 },
151
+ * tools: {
152
+ * lookupInvoice: functionTool(api.billing.invoiceById, {
153
+ * description: "Look up an invoice by id.",
154
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
155
+ * }),
156
+ * },
157
+ * });
158
+ * ```
159
+ *
160
+ * The merge into the agent's flat namespace (tool-name collisions, instruction
161
+ * ordering, per-skill knowledge retrieval) happens in `defineAgent` — a skill
162
+ * only validates its own `name`; tool-name validation is deferred to the merge,
163
+ * which owns the flat model-facing namespace.
164
+ * @experimental
165
+ */
166
+ declare const defineSkill: (config: SkillConfig) => SkillDefinition;
167
+ /**
168
+ * Runtime brand check for a {@link SkillDefinition}.
169
+ * @experimental
170
+ */
171
+ declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
172
+ /**
173
+ * Compile a `defineAgent` definition into the workflow the generated
174
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
175
+ *
176
+ * ```ts
177
+ * import LunoraWorkflow from "@lunora/workflow/do";
178
+ * import { compileAgentWorkflow } from "@lunora/agent";
179
+ * import { support } from "../agents.js";
180
+ *
181
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
182
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
183
+ * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
184
+ * }
185
+ * }
186
+ * ```
187
+ *
188
+ * The workflow ctx supplies durability (`step.do`) and the Lunora dispatcher
189
+ * (`run`); the loop supplies determinism (step naming + idempotent persists).
190
+ * @experimental
191
+ */
192
+ declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
193
+ paths?: AgentFunctionPaths;
194
+ }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
195
+ export { type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentHandle, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentToolConfig, type AgentToolDefinition, type FunctionToolOptions, type SkillConfig, type SkillDefinition, compileAgentWorkflow,
196
+ /**
197
+ * The part of `@lunora/agent` a Worker evaluates at startup: the definition builders
198
+ * a `lunora/agents.ts` calls at module scope, and what the generated shard and agent
199
+ * Workflow classes import. Nothing here statically reaches the agent loop, the model
200
+ * adapters or the AI SDK (and its zod); `compileAgentWorkflow` loads them on the first
201
+ * run. The `@lunora/agent` barrel re-exports all of this plus the heavy tools and
202
+ * runtime, so importing from it puts them back in the startup graph.
203
+ */
204
+ createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard };
package/dist/core.d.ts ADDED
@@ -0,0 +1,204 @@
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
+ import { FlexibleSchema } from 'ai';
4
+ import { jsonSchema as jsonSchema$1, ValidationResult, Schema } from '@ai-sdk/provider-utils';
5
+ import { WorkflowDefinition } from '@lunora/workflow';
6
+ import '@lunora/mail/inbound';
7
+ /**
8
+ * Build the `ctx.agents` producer surface from the codegen-emitted spec list
9
+ * (`LUNORA_AGENTS`), mirroring the `ctx.queues` property-access pattern: each
10
+ * declared agent resolves by its export key (the generated class name) off the
11
+ * invoking context's `exports` — or `env`, on a host without workflow exports —
12
+ * lazily, so a missing agent only errors when it is actually started.
13
+ *
14
+ * `cancel` also needs to write the thread's status, so it dispatches the agent
15
+ * runtime's `agentPatchThread` mutation. Production leaves `dispatch` undefined
16
+ * and the env-backed `createDispatchRunner` (the same runner the workflow body
17
+ * uses — it POSTs to `/_lunora/scheduler/dispatch`) is built on demand; tests
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.
23
+ * @experimental
24
+ */
25
+ declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
26
+ dispatch?: AgentRunFunction;
27
+ exports?: unknown;
28
+ shardKey?: string;
29
+ }) => Record<string, AgentHandle>;
30
+ /**
31
+ * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
32
+ * (each LLM turn and each tool call a named durable step; thread messages
33
+ * persisted idempotently in DO SQLite), invoked from mutations/actions via
34
+ * `ctx.agents.NAME.run(...)` and observed live by subscribing to the
35
+ * `agents:agentMessages` query.
36
+ *
37
+ * ```ts
38
+ * // lunora/agents.ts
39
+ * import { defineAgent, defineAgentTool } from "@lunora/agent";
40
+ *
41
+ * export const support = defineAgent({
42
+ * instructions: "You are a helpful support agent.",
43
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
44
+ * tools: {
45
+ * getWeather: defineAgentTool({
46
+ * description: "Look up the current weather for a city.",
47
+ * execute: async ({ city }, { run }) => run(api.weather.lookup, { city }),
48
+ * inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
49
+ * }),
50
+ * },
51
+ * });
52
+ * ```
53
+ *
54
+ * Declaring an agent is enough — codegen auto-registers the `agents:*` runtime
55
+ * functions (from `agentComponent()`) and the `ctx.agents` producer surface.
56
+ * @experimental
57
+ */
58
+ declare const defineAgent: (config: AgentConfig) => AgentDefinition;
59
+ /**
60
+ * Runtime brand check for a {@link AgentDefinition}.
61
+ * @experimental
62
+ */
63
+ declare const isAgentDefinition: (value: unknown) => value is AgentDefinition;
64
+ /**
65
+ * Declare an agent tool — see `AgentToolDefinition` for why `execute` runs in
66
+ * the loop's durable step (with an `AgentToolContext`) rather than inside the
67
+ * model call.
68
+ * @experimental
69
+ */
70
+ declare const defineAgentTool: <Input, Output>(config: AgentToolConfig<Input, Output>) => AgentToolDefinition<Input, Output>;
71
+ /**
72
+ * Author-supplied config for {@link functionTool}.
73
+ * @experimental
74
+ */
75
+ interface FunctionToolOptions<Input> {
76
+ /** What the tool does — shown to the model (the model decides from it). */
77
+ description: string;
78
+ /** The input schema shown to the model (a zod schema or `jsonSchema(...)`). */
79
+ inputSchema: FlexibleSchema<Input>;
80
+ }
81
+ /**
82
+ * Expose any Lunora query/mutation/action as an agent tool. The returned
83
+ * definition's `execute` dispatches the referenced function through the loop's
84
+ * existing `run` seam (the workflow `ctx.run`) — so there is no bespoke wrapper
85
+ * per tool, and the call runs inside the loop's named durable step exactly like
86
+ * any other tool.
87
+ *
88
+ * ```ts
89
+ * import { functionTool } from "@lunora/agent";
90
+ * import { api } from "./_generated/api";
91
+ *
92
+ * export const support = defineAgent({
93
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
94
+ * tools: {
95
+ * lookupOrder: functionTool(api.orders.byId, {
96
+ * description: "Look up an order by its id.",
97
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
98
+ * }),
99
+ * },
100
+ * });
101
+ * ```
102
+ *
103
+ * The function reference may be a typed `api.*` reference or a `"module:name"`
104
+ * path. The model-provided input is passed as the function's args, so
105
+ * `inputSchema` should mirror the referenced function's argument validator —
106
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
107
+ * input (so out-of-schema model input can never override it). A function
108
+ * that wants to dedupe a side-effecting call across an at-least-once step
109
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
110
+ * and checks it; a function that ignores it is unaffected — an args field
111
+ * the function's own validator doesn't declare is dropped, not rejected.
112
+ * @experimental
113
+ */
114
+ declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
115
+ /**
116
+ * `jsonSchema` from `@ai-sdk/provider-utils`, built without importing it. That package's root
117
+ * evaluates zod (about a hundred modules) as soon as anything is imported from it, and every
118
+ * tool module here builds a schema at module scope, so the root import put zod in every Worker's
119
+ * startup graph that wires an agent. A schema is a plain object, so the agent builds its own; the
120
+ * SDK itself is only imported where a zod schema has to be converted (`code-tool`).
121
+ */
122
+ declare const jsonSchema: <OBJECT = unknown>(schema: Parameters<typeof jsonSchema$1>[0], { validate }?: {
123
+ validate?: (value: unknown) => PromiseLike<ValidationResult<OBJECT>> | ValidationResult<OBJECT>;
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;
136
+ /**
137
+ * Declare a reusable skill: a bundle of expertise — an instruction fragment,
138
+ * tools, and retrieval `knowledge` — an agent composes in via
139
+ * `defineAgent({ skills: [...] })`. Reuse-first: a skill's `tools` carry the
140
+ * SAME `AnyAgentTool` shape agents already use (`functionTool` / `mcpTools` /
141
+ * `agentAsTool`), and `knowledge` reuses `memory`'s `AgentMemoryOptions`
142
+ * retrieval verbatim.
143
+ *
144
+ * ```ts
145
+ * import { defineSkill, functionTool } from "@lunora/agent";
146
+ *
147
+ * export const billing = defineSkill({
148
+ * name: "billing",
149
+ * instructions: "When asked about invoices, cite the invoice id.",
150
+ * knowledge: { source: "rag:searchBillingDocs", topK: 4 },
151
+ * tools: {
152
+ * lookupInvoice: functionTool(api.billing.invoiceById, {
153
+ * description: "Look up an invoice by id.",
154
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
155
+ * }),
156
+ * },
157
+ * });
158
+ * ```
159
+ *
160
+ * The merge into the agent's flat namespace (tool-name collisions, instruction
161
+ * ordering, per-skill knowledge retrieval) happens in `defineAgent` — a skill
162
+ * only validates its own `name`; tool-name validation is deferred to the merge,
163
+ * which owns the flat model-facing namespace.
164
+ * @experimental
165
+ */
166
+ declare const defineSkill: (config: SkillConfig) => SkillDefinition;
167
+ /**
168
+ * Runtime brand check for a {@link SkillDefinition}.
169
+ * @experimental
170
+ */
171
+ declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
172
+ /**
173
+ * Compile a `defineAgent` definition into the workflow the generated
174
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
175
+ *
176
+ * ```ts
177
+ * import LunoraWorkflow from "@lunora/workflow/do";
178
+ * import { compileAgentWorkflow } from "@lunora/agent";
179
+ * import { support } from "../agents.js";
180
+ *
181
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
182
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
183
+ * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
184
+ * }
185
+ * }
186
+ * ```
187
+ *
188
+ * The workflow ctx supplies durability (`step.do`) and the Lunora dispatcher
189
+ * (`run`); the loop supplies determinism (step naming + idempotent persists).
190
+ * @experimental
191
+ */
192
+ declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
193
+ paths?: AgentFunctionPaths;
194
+ }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
195
+ export { type AgentBindingSpec, type AgentConfig, type AgentDefinition, type AgentFunctionPaths, type AgentFunctionReference, type AgentHandle, type AgentRunFunction, type AgentRunInput, type AgentRunResult, type AgentToolConfig, type AgentToolDefinition, type FunctionToolOptions, type SkillConfig, type SkillDefinition, compileAgentWorkflow,
196
+ /**
197
+ * The part of `@lunora/agent` a Worker evaluates at startup: the definition builders
198
+ * a `lunora/agents.ts` calls at module scope, and what the generated shard and agent
199
+ * Workflow classes import. Nothing here statically reaches the agent loop, the model
200
+ * adapters or the AI SDK (and its zod); `compileAgentWorkflow` loads them on the first
201
+ * run. The `@lunora/agent` barrel re-exports all of this plus the heavy tools and
202
+ * runtime, so importing from it puts them back in the startup graph.
203
+ */
204
+ createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard };
package/dist/core.mjs ADDED
@@ -0,0 +1 @@
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-vAmttAsE.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-vAmttAsE.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};