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

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 (57) 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/component.mjs +1 -1
  5. package/dist/core.d.mts +188 -0
  6. package/dist/core.d.ts +188 -0
  7. package/dist/core.mjs +1 -0
  8. package/dist/inbound.d.mts +1 -1
  9. package/dist/inbound.d.ts +1 -1
  10. package/dist/index.d.mts +7 -167
  11. package/dist/index.d.ts +7 -167
  12. package/dist/index.mjs +1 -1
  13. package/dist/packem_chunks/createAgentGenerate.mjs +3 -0
  14. package/dist/packem_chunks/otlpTelemetry.mjs +1 -0
  15. package/dist/packem_chunks/resolve-run.mjs +1 -0
  16. package/dist/packem_chunks/runAgentLoop.mjs +3 -0
  17. package/dist/packem_shared/SecretUnavailableError-DOy2M4Ak.mjs +1 -0
  18. package/dist/packem_shared/VoiceSessionDO-CdvG2L-D.mjs +1 -0
  19. package/dist/packem_shared/{adaptMcpResult-DFF_g58r.mjs → adaptMcpResult-CA-3ovJd.mjs} +1 -1
  20. package/dist/packem_shared/agentAsTool-DiIz7AR0.mjs +1 -0
  21. package/dist/packem_shared/codeTool-Cn8TuNjk.mjs +1 -0
  22. package/dist/packem_shared/collectAgenticMemoryTools-RTz0T3qJ.mjs +1 -0
  23. package/dist/packem_shared/compileAgentWorkflow-yZB8fbYc.mjs +1 -0
  24. package/dist/packem_shared/component-shared--SPcu0Iw.mjs +1 -0
  25. package/dist/packem_shared/{defineAgent-D4eUl6YE.mjs → defineAgent-DVPP9V_-.mjs} +2 -2
  26. package/dist/packem_shared/{jsCodeTool-CIlCK1bG.mjs → jsCodeTool-BJB3Fpm2.mjs} +2 -2
  27. package/dist/packem_shared/jsonSchema-fhoaBWpN.mjs +1 -0
  28. package/dist/packem_shared/memory-JI0lUu84.mjs +1 -0
  29. package/dist/packem_shared/{normalizeEntityName-Rr5OQxhc.mjs → normalizeEntityName-BiUH5B5W.mjs} +1 -1
  30. package/dist/packem_shared/runVoiceTurn-DPa5UZ45.mjs +1 -0
  31. package/dist/packem_shared/{types.d-vAmttAsE.d.mts → types.d-Bq-ZDGI6.d.mts} +1 -1
  32. package/dist/packem_shared/{types.d-vAmttAsE.d.ts → types.d-Bq-ZDGI6.d.ts} +1 -1
  33. package/dist/packem_shared/voice-turn-B9omvXoR.mjs +1 -0
  34. package/dist/packem_shared/webSearchTool-BzXW0R4r.mjs +1 -0
  35. package/dist/reply.d.mts +1 -1
  36. package/dist/reply.d.ts +1 -1
  37. package/dist/sandbox.d.mts +1 -1
  38. package/dist/sandbox.d.ts +1 -1
  39. package/dist/sandbox.mjs +1 -1
  40. package/dist/skill-markdown.d.mts +1 -1
  41. package/dist/skill-markdown.d.ts +1 -1
  42. package/dist/telemetry/index.mjs +1 -1
  43. package/package.json +11 -7
  44. package/dist/packem_shared/SecretUnavailableError-BCp40Leh.mjs +0 -1
  45. package/dist/packem_shared/VoiceSessionDO-BIfcyunp.mjs +0 -1
  46. package/dist/packem_shared/agent-loop-ByDqRJo7.mjs +0 -3
  47. package/dist/packem_shared/agentAsTool-CA7Sha2i.mjs +0 -1
  48. package/dist/packem_shared/codeTool-Hm_Af6t4.mjs +0 -1
  49. package/dist/packem_shared/collectAgenticMemoryTools-BWdIhOfY.mjs +0 -1
  50. package/dist/packem_shared/compileAgentWorkflow-BkVDrDvM.mjs +0 -1
  51. package/dist/packem_shared/component-shared-DdXFbng-.mjs +0 -1
  52. package/dist/packem_shared/createAgentGenerate-DSLXAeY2.mjs +0 -3
  53. package/dist/packem_shared/otlpTelemetry-CiSI9HE_.mjs +0 -1
  54. package/dist/packem_shared/runAgentLoop-Cv661XGm.mjs +0 -1
  55. package/dist/packem_shared/runVoiceTurn-DAtWSeXj.mjs +0 -1
  56. package/dist/packem_shared/voice-turn-DBWkPcQH.mjs +0 -1
  57. package/dist/packem_shared/webSearchTool-BobmV4cD.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-Bq-ZDGI6.mjs";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-Bq-ZDGI6.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-Bq-ZDGI6.js";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-Bq-ZDGI6.js";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
@@ -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,188 @@
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";
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
+ * @experimental
20
+ */
21
+ declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
22
+ dispatch?: AgentRunFunction;
23
+ exports?: unknown;
24
+ }) => Record<string, AgentHandle>;
25
+ /**
26
+ * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
27
+ * (each LLM turn and each tool call a named durable step; thread messages
28
+ * persisted idempotently in DO SQLite), invoked from mutations/actions via
29
+ * `ctx.agents.NAME.run(...)` and observed live by subscribing to the
30
+ * `agents:agentMessages` query.
31
+ *
32
+ * ```ts
33
+ * // lunora/agents.ts
34
+ * import { defineAgent, defineAgentTool } from "@lunora/agent";
35
+ *
36
+ * export const support = defineAgent({
37
+ * instructions: "You are a helpful support agent.",
38
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
39
+ * tools: {
40
+ * getWeather: defineAgentTool({
41
+ * description: "Look up the current weather for a city.",
42
+ * execute: async ({ city }, { run }) => run(api.weather.lookup, { city }),
43
+ * inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
44
+ * }),
45
+ * },
46
+ * });
47
+ * ```
48
+ *
49
+ * Declaring an agent is enough — codegen auto-registers the `agents:*` runtime
50
+ * functions (from `agentComponent()`) and the `ctx.agents` producer surface.
51
+ * @experimental
52
+ */
53
+ declare const defineAgent: (config: AgentConfig) => AgentDefinition;
54
+ /**
55
+ * Runtime brand check for a {@link AgentDefinition}.
56
+ * @experimental
57
+ */
58
+ declare const isAgentDefinition: (value: unknown) => value is AgentDefinition;
59
+ /**
60
+ * Declare an agent tool — see `AgentToolDefinition` for why `execute` runs in
61
+ * the loop's durable step (with an `AgentToolContext`) rather than inside the
62
+ * model call.
63
+ * @experimental
64
+ */
65
+ declare const defineAgentTool: <Input, Output>(config: AgentToolConfig<Input, Output>) => AgentToolDefinition<Input, Output>;
66
+ /**
67
+ * Author-supplied config for {@link functionTool}.
68
+ * @experimental
69
+ */
70
+ interface FunctionToolOptions<Input> {
71
+ /** What the tool does — shown to the model (the model decides from it). */
72
+ description: string;
73
+ /** The input schema shown to the model (a zod schema or `jsonSchema(...)`). */
74
+ inputSchema: FlexibleSchema<Input>;
75
+ }
76
+ /**
77
+ * Expose any Lunora query/mutation/action as an agent tool. The returned
78
+ * definition's `execute` dispatches the referenced function through the loop's
79
+ * existing `run` seam (the workflow `ctx.run`) — so there is no bespoke wrapper
80
+ * per tool, and the call runs inside the loop's named durable step exactly like
81
+ * any other tool.
82
+ *
83
+ * ```ts
84
+ * import { functionTool } from "@lunora/agent";
85
+ * import { api } from "./_generated/api";
86
+ *
87
+ * export const support = defineAgent({
88
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
89
+ * tools: {
90
+ * lookupOrder: functionTool(api.orders.byId, {
91
+ * description: "Look up an order by its id.",
92
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
93
+ * }),
94
+ * },
95
+ * });
96
+ * ```
97
+ *
98
+ * The function reference may be a typed `api.*` reference or a `"module:name"`
99
+ * path. The model-provided input is passed as the function's args, so
100
+ * `inputSchema` should mirror the referenced function's argument validator —
101
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
102
+ * input (so out-of-schema model input can never override it). A function
103
+ * that wants to dedupe a side-effecting call across an at-least-once step
104
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
105
+ * and checks it; a function that ignores it is unaffected — an args field
106
+ * the function's own validator doesn't declare is dropped, not rejected.
107
+ * @experimental
108
+ */
109
+ declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
110
+ /**
111
+ * `jsonSchema` from `@ai-sdk/provider-utils`, built without importing it. That package's root
112
+ * evaluates zod (about a hundred modules) as soon as anything is imported from it, and every
113
+ * tool module here builds a schema at module scope, so the root import put zod in every Worker's
114
+ * startup graph that wires an agent. A schema is a plain object, so the agent builds its own; the
115
+ * SDK itself is only imported where a zod schema has to be converted (`code-tool`).
116
+ */
117
+ declare const jsonSchema: <OBJECT = unknown>(schema: Parameters<typeof jsonSchema$1>[0], { validate }?: {
118
+ validate?: (value: unknown) => PromiseLike<ValidationResult<OBJECT>> | ValidationResult<OBJECT>;
119
+ }) => Schema<OBJECT>;
120
+ /**
121
+ * Declare a reusable skill: a bundle of expertise — an instruction fragment,
122
+ * tools, and retrieval `knowledge` — an agent composes in via
123
+ * `defineAgent({ skills: [...] })`. Reuse-first: a skill's `tools` carry the
124
+ * SAME `AnyAgentTool` shape agents already use (`functionTool` / `mcpTools` /
125
+ * `agentAsTool`), and `knowledge` reuses `memory`'s `AgentMemoryOptions`
126
+ * retrieval verbatim.
127
+ *
128
+ * ```ts
129
+ * import { defineSkill, functionTool } from "@lunora/agent";
130
+ *
131
+ * export const billing = defineSkill({
132
+ * name: "billing",
133
+ * instructions: "When asked about invoices, cite the invoice id.",
134
+ * knowledge: { source: "rag:searchBillingDocs", topK: 4 },
135
+ * tools: {
136
+ * lookupInvoice: functionTool(api.billing.invoiceById, {
137
+ * description: "Look up an invoice by id.",
138
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
139
+ * }),
140
+ * },
141
+ * });
142
+ * ```
143
+ *
144
+ * The merge into the agent's flat namespace (tool-name collisions, instruction
145
+ * ordering, per-skill knowledge retrieval) happens in `defineAgent` — a skill
146
+ * only validates its own `name`; tool-name validation is deferred to the merge,
147
+ * which owns the flat model-facing namespace.
148
+ * @experimental
149
+ */
150
+ declare const defineSkill: (config: SkillConfig) => SkillDefinition;
151
+ /**
152
+ * Runtime brand check for a {@link SkillDefinition}.
153
+ * @experimental
154
+ */
155
+ declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
156
+ /**
157
+ * Compile a `defineAgent` definition into the workflow the generated
158
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
159
+ *
160
+ * ```ts
161
+ * import LunoraWorkflow from "@lunora/workflow/do";
162
+ * import { compileAgentWorkflow } from "@lunora/agent";
163
+ * import { support } from "../agents.js";
164
+ *
165
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
166
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
167
+ * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
168
+ * }
169
+ * }
170
+ * ```
171
+ *
172
+ * The workflow ctx supplies durability (`step.do`) and the Lunora dispatcher
173
+ * (`run`); the loop supplies determinism (step naming + idempotent persists).
174
+ * @experimental
175
+ */
176
+ declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
177
+ paths?: AgentFunctionPaths;
178
+ }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
179
+ 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,
180
+ /**
181
+ * The part of `@lunora/agent` a Worker evaluates at startup: the definition builders
182
+ * a `lunora/agents.ts` calls at module scope, and what the generated shard and agent
183
+ * Workflow classes import. Nothing here statically reaches the agent loop, the model
184
+ * adapters or the AI SDK (and its zod); `compileAgentWorkflow` loads them on the first
185
+ * run. The `@lunora/agent` barrel re-exports all of this plus the heavy tools and
186
+ * runtime, so importing from it puts them back in the startup graph.
187
+ */
188
+ createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema };
package/dist/core.d.ts ADDED
@@ -0,0 +1,188 @@
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";
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
+ * @experimental
20
+ */
21
+ declare const createAgentContext: (env: Record<string, unknown>, specs: ReadonlyArray<AgentBindingSpec>, context?: {
22
+ dispatch?: AgentRunFunction;
23
+ exports?: unknown;
24
+ }) => Record<string, AgentHandle>;
25
+ /**
26
+ * Declare a durable agent. The definition compiles onto a Cloudflare Workflow
27
+ * (each LLM turn and each tool call a named durable step; thread messages
28
+ * persisted idempotently in DO SQLite), invoked from mutations/actions via
29
+ * `ctx.agents.NAME.run(...)` and observed live by subscribing to the
30
+ * `agents:agentMessages` query.
31
+ *
32
+ * ```ts
33
+ * // lunora/agents.ts
34
+ * import { defineAgent, defineAgentTool } from "@lunora/agent";
35
+ *
36
+ * export const support = defineAgent({
37
+ * instructions: "You are a helpful support agent.",
38
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
39
+ * tools: {
40
+ * getWeather: defineAgentTool({
41
+ * description: "Look up the current weather for a city.",
42
+ * execute: async ({ city }, { run }) => run(api.weather.lookup, { city }),
43
+ * inputSchema: jsonSchema({ properties: { city: { type: "string" } }, required: ["city"], type: "object" }),
44
+ * }),
45
+ * },
46
+ * });
47
+ * ```
48
+ *
49
+ * Declaring an agent is enough — codegen auto-registers the `agents:*` runtime
50
+ * functions (from `agentComponent()`) and the `ctx.agents` producer surface.
51
+ * @experimental
52
+ */
53
+ declare const defineAgent: (config: AgentConfig) => AgentDefinition;
54
+ /**
55
+ * Runtime brand check for a {@link AgentDefinition}.
56
+ * @experimental
57
+ */
58
+ declare const isAgentDefinition: (value: unknown) => value is AgentDefinition;
59
+ /**
60
+ * Declare an agent tool — see `AgentToolDefinition` for why `execute` runs in
61
+ * the loop's durable step (with an `AgentToolContext`) rather than inside the
62
+ * model call.
63
+ * @experimental
64
+ */
65
+ declare const defineAgentTool: <Input, Output>(config: AgentToolConfig<Input, Output>) => AgentToolDefinition<Input, Output>;
66
+ /**
67
+ * Author-supplied config for {@link functionTool}.
68
+ * @experimental
69
+ */
70
+ interface FunctionToolOptions<Input> {
71
+ /** What the tool does — shown to the model (the model decides from it). */
72
+ description: string;
73
+ /** The input schema shown to the model (a zod schema or `jsonSchema(...)`). */
74
+ inputSchema: FlexibleSchema<Input>;
75
+ }
76
+ /**
77
+ * Expose any Lunora query/mutation/action as an agent tool. The returned
78
+ * definition's `execute` dispatches the referenced function through the loop's
79
+ * existing `run` seam (the workflow `ctx.run`) — so there is no bespoke wrapper
80
+ * per tool, and the call runs inside the loop's named durable step exactly like
81
+ * any other tool.
82
+ *
83
+ * ```ts
84
+ * import { functionTool } from "@lunora/agent";
85
+ * import { api } from "./_generated/api";
86
+ *
87
+ * export const support = defineAgent({
88
+ * model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
89
+ * tools: {
90
+ * lookupOrder: functionTool(api.orders.byId, {
91
+ * description: "Look up an order by its id.",
92
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
93
+ * }),
94
+ * },
95
+ * });
96
+ * ```
97
+ *
98
+ * The function reference may be a typed `api.*` reference or a `"module:name"`
99
+ * path. The model-provided input is passed as the function's args, so
100
+ * `inputSchema` should mirror the referenced function's argument validator —
101
+ * PLUS the call's `idempotencyKey`, pinned onto the args after the model
102
+ * input (so out-of-schema model input can never override it). A function
103
+ * that wants to dedupe a side-effecting call across an at-least-once step
104
+ * retry declares `idempotencyKey: v.optional(v.string())` in its own args
105
+ * and checks it; a function that ignores it is unaffected — an args field
106
+ * the function's own validator doesn't declare is dropped, not rejected.
107
+ * @experimental
108
+ */
109
+ declare const functionTool: <Input extends Record<string, unknown> = Record<string, unknown>, Output = unknown>(reference: AgentFunctionReference | string, options: FunctionToolOptions<Input>) => AgentToolDefinition<Input, Output>;
110
+ /**
111
+ * `jsonSchema` from `@ai-sdk/provider-utils`, built without importing it. That package's root
112
+ * evaluates zod (about a hundred modules) as soon as anything is imported from it, and every
113
+ * tool module here builds a schema at module scope, so the root import put zod in every Worker's
114
+ * startup graph that wires an agent. A schema is a plain object, so the agent builds its own; the
115
+ * SDK itself is only imported where a zod schema has to be converted (`code-tool`).
116
+ */
117
+ declare const jsonSchema: <OBJECT = unknown>(schema: Parameters<typeof jsonSchema$1>[0], { validate }?: {
118
+ validate?: (value: unknown) => PromiseLike<ValidationResult<OBJECT>> | ValidationResult<OBJECT>;
119
+ }) => Schema<OBJECT>;
120
+ /**
121
+ * Declare a reusable skill: a bundle of expertise — an instruction fragment,
122
+ * tools, and retrieval `knowledge` — an agent composes in via
123
+ * `defineAgent({ skills: [...] })`. Reuse-first: a skill's `tools` carry the
124
+ * SAME `AnyAgentTool` shape agents already use (`functionTool` / `mcpTools` /
125
+ * `agentAsTool`), and `knowledge` reuses `memory`'s `AgentMemoryOptions`
126
+ * retrieval verbatim.
127
+ *
128
+ * ```ts
129
+ * import { defineSkill, functionTool } from "@lunora/agent";
130
+ *
131
+ * export const billing = defineSkill({
132
+ * name: "billing",
133
+ * instructions: "When asked about invoices, cite the invoice id.",
134
+ * knowledge: { source: "rag:searchBillingDocs", topK: 4 },
135
+ * tools: {
136
+ * lookupInvoice: functionTool(api.billing.invoiceById, {
137
+ * description: "Look up an invoice by id.",
138
+ * inputSchema: jsonSchema({ properties: { id: { type: "string" } }, required: ["id"], type: "object" }),
139
+ * }),
140
+ * },
141
+ * });
142
+ * ```
143
+ *
144
+ * The merge into the agent's flat namespace (tool-name collisions, instruction
145
+ * ordering, per-skill knowledge retrieval) happens in `defineAgent` — a skill
146
+ * only validates its own `name`; tool-name validation is deferred to the merge,
147
+ * which owns the flat model-facing namespace.
148
+ * @experimental
149
+ */
150
+ declare const defineSkill: (config: SkillConfig) => SkillDefinition;
151
+ /**
152
+ * Runtime brand check for a {@link SkillDefinition}.
153
+ * @experimental
154
+ */
155
+ declare const isSkillDefinition: (value: unknown) => value is SkillDefinition;
156
+ /**
157
+ * Compile a `defineAgent` definition into the workflow the generated
158
+ * `<Name>AgentWorkflow` entrypoint class runs. Codegen emits, per agent:
159
+ *
160
+ * ```ts
161
+ * import LunoraWorkflow from "@lunora/workflow/do";
162
+ * import { compileAgentWorkflow } from "@lunora/agent";
163
+ * import { support } from "../agents.js";
164
+ *
165
+ * export class SupportAgentWorkflow extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
166
+ * public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
167
+ * super(ctx, env, compileAgentWorkflow(support, "support"), "support");
168
+ * }
169
+ * }
170
+ * ```
171
+ *
172
+ * The workflow ctx supplies durability (`step.do`) and the Lunora dispatcher
173
+ * (`run`); the loop supplies determinism (step naming + idempotent persists).
174
+ * @experimental
175
+ */
176
+ declare const compileAgentWorkflow: (agent: AgentDefinition, exportName: string, options?: {
177
+ paths?: AgentFunctionPaths;
178
+ }) => WorkflowDefinition<AgentRunInput, AgentRunResult>;
179
+ 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,
180
+ /**
181
+ * The part of `@lunora/agent` a Worker evaluates at startup: the definition builders
182
+ * a `lunora/agents.ts` calls at module scope, and what the generated shard and agent
183
+ * Workflow classes import. Nothing here statically reaches the agent loop, the model
184
+ * adapters or the AI SDK (and its zod); `compileAgentWorkflow` loads them on the first
185
+ * run. The `@lunora/agent` barrel re-exports all of this plus the heavy tools and
186
+ * runtime, so importing from it puts them back in the startup graph.
187
+ */
188
+ createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema };
package/dist/core.mjs ADDED
@@ -0,0 +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,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-Bq-ZDGI6.mjs";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**
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-Bq-ZDGI6.js";
2
2
  import '@lunora/mail/inbound';
3
3
  import 'ai';
4
4
  /**