@lunora/agent 1.0.0-alpha.205 → 1.0.0-alpha.207
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.
- package/dist/channels.d.mts +2 -2
- package/dist/channels.d.ts +2 -2
- package/dist/component.d.mts +1 -0
- package/dist/component.d.ts +1 -0
- package/dist/component.mjs +2 -2
- package/dist/inbound.d.mts +1 -1
- package/dist/inbound.d.ts +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/AGENT_MODULE-B6FqQC80.mjs +1 -0
- package/dist/packem_shared/{VoiceSessionDO-CB_yuzWV.mjs → VoiceSessionDO-CoAY8Ik1.mjs} +1 -1
- package/dist/packem_shared/{adaptMcpResult-CVlq-_TO.mjs → adaptMcpResult-DFF_g58r.mjs} +1 -1
- package/dist/packem_shared/agent-loop-BD9gwYAm.mjs +3 -0
- package/dist/packem_shared/agentAsTool-BJi-uU4s.mjs +1 -0
- package/dist/packem_shared/codeTool-dpJANTDc.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-D07XhGKr.mjs +1 -0
- package/dist/packem_shared/{compileAgentWorkflow-C287O2ux.mjs → compileAgentWorkflow-CrK26Wb8.mjs} +1 -1
- package/dist/packem_shared/{createAgentContext-BxDMNWNG.mjs → createAgentContext-D8M9JoBR.mjs} +1 -1
- package/dist/packem_shared/createAgentGenerate-BvCZrr1X.mjs +3 -0
- package/dist/packem_shared/{defineAgent-CjxGfOg7.mjs → defineAgent-DGcFPe8V.mjs} +1 -1
- package/dist/packem_shared/{functionTool-D3CP4f8-.mjs → functionTool-Baqdn0OK.mjs} +1 -1
- package/dist/packem_shared/{jsCodeTool-BLOvjXGF.mjs → jsCodeTool-CIlCK1bG.mjs} +2 -2
- package/dist/packem_shared/{runAgentLoop-BIjYgCLE.mjs → runAgentLoop-BLRjBI5c.mjs} +1 -1
- package/dist/packem_shared/{runVoiceTurn-CtKjHnfU.mjs → runVoiceTurn-tIMTlxmP.mjs} +1 -1
- package/dist/packem_shared/{types.d-CbYtFBw9.d.mts → types.d-C4vYEYW6.d.mts} +5 -0
- package/dist/packem_shared/{types.d-CbYtFBw9.d.ts → types.d-C4vYEYW6.d.ts} +5 -0
- package/dist/packem_shared/{voice-turn-DZNbOsWB.mjs → voice-turn-DJWmnCuv.mjs} +1 -1
- package/dist/packem_shared/webSearchTool-DGEFTSp1.mjs +1 -0
- package/dist/reply.d.mts +1 -1
- package/dist/reply.d.ts +1 -1
- package/dist/sandbox.d.mts +1 -1
- package/dist/sandbox.d.ts +1 -1
- package/dist/sandbox.mjs +1 -1
- package/dist/skill-markdown.d.mts +1 -1
- package/dist/skill-markdown.d.ts +1 -1
- package/package.json +4 -3
- package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +0 -1
- package/dist/packem_shared/agent-loop-DyJWnyiT.mjs +0 -3
- package/dist/packem_shared/agentAsTool-1Gwq45M3.mjs +0 -1
- package/dist/packem_shared/codeTool-BQb-K3my.mjs +0 -1
- package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +0 -1
- package/dist/packem_shared/createAgentGenerate-EEFNvpS5.mjs +0 -3
- package/dist/packem_shared/webSearchTool-BptEsfd9.mjs +0 -1
package/dist/channels.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-C4vYEYW6.mjs";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-C4vYEYW6.mjs";
|
|
3
3
|
import '@lunora/mail/inbound';
|
|
4
4
|
import 'ai';
|
|
5
5
|
/**
|
package/dist/channels.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-C4vYEYW6.js";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-C4vYEYW6.js";
|
|
3
3
|
import '@lunora/mail/inbound';
|
|
4
4
|
import 'ai';
|
|
5
5
|
/**
|
package/dist/component.d.mts
CHANGED
|
@@ -115,6 +115,7 @@ interface AgentComponent {
|
|
|
115
115
|
agentEpisodeUpsert: AgentRegisteredFunction;
|
|
116
116
|
agentGraphTraverse: AgentRegisteredFunction;
|
|
117
117
|
agentGraphUpsert: AgentRegisteredFunction;
|
|
118
|
+
agentHistory: AgentRegisteredFunction;
|
|
118
119
|
agentMessages: AgentRegisteredFunction;
|
|
119
120
|
agentPatchThread: AgentRegisteredFunction;
|
|
120
121
|
agentResolveApproval: AgentRegisteredFunction;
|
package/dist/component.d.ts
CHANGED
|
@@ -115,6 +115,7 @@ interface AgentComponent {
|
|
|
115
115
|
agentEpisodeUpsert: AgentRegisteredFunction;
|
|
116
116
|
agentGraphTraverse: AgentRegisteredFunction;
|
|
117
117
|
agentGraphUpsert: AgentRegisteredFunction;
|
|
118
|
+
agentHistory: AgentRegisteredFunction;
|
|
118
119
|
agentMessages: AgentRegisteredFunction;
|
|
119
120
|
agentPatchThread: AgentRegisteredFunction;
|
|
120
121
|
agentResolveApproval: AgentRegisteredFunction;
|
package/dist/component.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{defineTable as
|
|
2
|
-
`)}});return{agentEpisodeRecall:q(o),agentEpisodeUpsert:q(d)}},S="threads",$="messages",M="run_queue",p=`${_}_${S}`,E=`${_}_${$}`,A=`${_}_${M}`,x=5,te=780*60*1e3,ne=j(_,{tables:{[$]:k({content:e.string(),createdAt: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("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(),[S]:k({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")),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).public(),[M]:k({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(),...G,...V}}),{mutation:f,query:T}=D.dataModel().create(),ie=async(d,o,s)=>{if(o.instanceId===void 0)throw new g("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 d.query(A).withIndex("byThreadInstance",I=>I.eq("threadKey",o.key).eq("instanceId",u)).first();if(c)return{outcome:"queued",position:c.position};const h=await d.query(A).withIndex("byThread",I=>I.eq("threadKey",o.key)).collect();if(h.length>=x)throw new g("CONFLICT",`@lunora/agent: thread "${o.key}" run queue is full (depth ${String(x)}) — rejecting instance "${u}"`);const w=(h.at(-1)?.position??-1)+1;return await d.insert(A,{agent:o.agent,enqueuedAt:s,instanceId:u,position:w,threadKey:o.key}),{outcome:"queued",position:w}},ae=async(d,o,s)=>{if(o.policy==="queue")return ie(d,{agent:o.agent,instanceId:o.instanceId,key:o.key,priorInstanceId:o.priorInstanceId},s);if(o.policy!=="replace")throw new g("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — onConcurrentRun="${o.policy}"`);return await d.patch(o.existingId,{error:null,status:"running",updatedAt:s,...o.instanceId===void 0?{}:{completedInstanceId:null,instanceId:o.instanceId}}),{outcome:"replaced",priorInstanceId:o.priorInstanceId}},oe=(d,o,s)=>{const u=d.instanceId;if(u===void 0||o===u||d.status!=="running"&&d.status!=="awaiting_input")return;const c=typeof d.updatedAt=="number"?d.updatedAt:0,h=d.status==="awaiting_input"?F:te;return s-c>h?void 0:u},ce=()=>{const d=f.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=oe(i,t.instanceId,a);return r!==void 0?ae(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(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,...P({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),o=f.input({content:e.string(),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("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(E).withIndex("byMessageKey",y=>y.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const i=await n.db.query(p).withIndex("byKey",y=>y.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,l=Date.now();return await n.db.insert(E,{content:t.content,createdAt:l,messageKey:t.messageKey,role:t.role,seq:r,threadKey:t.threadKey,...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(i._id,{messageCount:r+1,updatedAt:l}),{seq:r}}),s=f.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(E).withIndex("byMessageKey",i=>i.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(a._id)}),u=f.input({error: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"))),title:e.optional(e.string()),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).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",l=>l.eq("key",i)).first():a!==void 0&&(r=await n.db.query(p).withIndex("byInstance",l=>l.eq("instanceId",a)).first()),r&&await n.db.patch(r._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),c=f.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(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(p).withIndex("byKey",b=>b.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 b=await n.db.query(A).withIndex("byThreadInstance",K=>K.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return b&&await n.db.delete(b._id),{}}const y=(i.completedInstanceId===t.instanceId?[]:await n.db.query(A).withIndex("byThread",b=>b.eq("threadKey",t.key)).collect())[0];if(!y)return await n.db.patch(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 m=y.instanceId;return await n.db.delete(y._id),await n.db.patch(i._id,{completedInstanceId:t.instanceId,instanceId:m,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:m}}),h=f.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(a._id,{state:t.state,updatedAt:Date.now()})}),w=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},I=T.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 w(a,n.auth)}),O=T.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 w(a,n.auth)?.state}),L=T.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 w(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(E).withIndex("byThread",r=>r.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(E).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),U=f.input({decision:e.union(e.literal("approve"),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",m=>m.eq("key",t.threadKey)).first(),i=w(a,n.auth);if(i===void 0)throw new g("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(i.instanceId!==t.instanceId)throw new g("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const r=i.agent,{agents:l}=n,y=l?.[r];if(typeof y?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${r}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);return await y.sendEvent(t.instanceId,{payload:{decision:t.decision,toolCallId:t.toolCallId,...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),B=f.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 g("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 g("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,l=await n.db.query(p).withIndex("byKey",m=>m.eq("key",t.threadKey)).first();if(l){const m=l.status,b=l.instanceId,K=l.owner;if((m==="running"||m==="awaiting_input")&&b!==void 0&&(K===void 0||K===r))return{id:b,threadKey:t.threadKey};if(K!==r)throw new g("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:y}=await i.run({input:t.input,threadKey:t.threadKey,...r===void 0?{}:{owner:r},...t.title===void 0?{}:{title:t.title}});return{id:y,threadKey:t.threadKey}}),C=H(),R=ee();return{extension:ne,functions:{agentAppendMessage:q(o),agentCompleteRun:q(c),agentEnsureThread:q(d),agentEpisodeRecall:R.agentEpisodeRecall,agentEpisodeUpsert:R.agentEpisodeUpsert,agentGraphTraverse:C.agentGraphTraverse,agentGraphUpsert:C.agentGraphUpsert,agentMessages:L,agentDeleteMessage:q(s),agentPatchThread:q(u),agentResolveApproval:U,agentRun:B,agentSetState:q(h),agentState:O,agentThread:I}}};export{ce as agentComponent,ne as agentExtension,he as normalizeEntityName,we as sandboxComponent};
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{defineTable as T,initLunora as x,defineSchemaExtension as P}from"@lunora/server";import{v as e}from"@lunora/values";import{a as b,A as _,d as F,b as G}from"./packem_shared/component-shared-G8ngerkU.mjs";import{graphTables as H,graphComponent as X}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{normalizeEntityName as Ie}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{sandboxComponent as be}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const v="agent_episodes",Q=5,Y=20,V=500,N=200,W=/\s+/gu,z=s=>s===void 0||!Number.isFinite(s)?Q:Math.min(Y,Math.max(1,Math.trunc(s))),J={episodes:T({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:Z,query:ee}=x.dataModel().create(),te=()=>{const s=Z.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:d,ctx:l})=>{const I=d.summary.replaceAll(W," ").trim().slice(0,V);if(I.length===0)return{recorded:!1};if(await l.db.query(v).withIndex("byOwnerMessageKey",y=>y.eq("owner",d.owner).eq("messageKey",d.messageKey)).first())return{recorded:!1};await l.db.insert(v,{createdAt:d.createdAt??Date.now(),messageKey:d.messageKey,owner:d.owner,summary:I,...d.threadKey===void 0?{}:{threadKey:d.threadKey}});const q=await l.db.query(v).withIndex("byOwnerCreatedAt",y=>y.eq("owner",d.owner)).order("asc").take(N+1);for(const y of q.slice(0,Math.max(0,q.length-N)))await l.db.delete(y._id);return{recorded:!0}}),r=ee.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:d,ctx:l})=>{const I=await l.db.query(v).withIndex("byOwnerCreatedAt",w=>w.eq("owner",d.owner)).order("desc").take(z(d.limit));return I.length===0?{context:""}:{context:I.toReversed().map(w=>`- ${w.summary}`).join(`
|
|
2
|
+
`)}});return{agentEpisodeRecall:b(r),agentEpisodeUpsert:b(s)}},D="threads",M="messages",$="run_queue",m=`${_}_${D}`,K=`${_}_${M}`,A=`${_}_${$}`,S=5,ne=10,ae=780*60*1e3,ie=P(_,{tables:{[M]:T({content:e.string(),createdAt: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("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(),[D]:T({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()),summaryRuns:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).public(),[$]:T({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(),...H,...J}}),{mutation:f,query:k}=x.dataModel().create(),oe=async(s,r,d)=>{if(r.instanceId===void 0)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:l}=r,I=await s.query(A).withIndex("byThreadInstance",y=>y.eq("threadKey",r.key).eq("instanceId",l)).first();if(I)return{outcome:"queued",position:I.position};const w=await s.query(A).withIndex("byThread",y=>y.eq("threadKey",r.key)).collect();if(w.length>=S)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" run queue is full (depth ${String(S)}) — rejecting instance "${l}"`);const q=(w.at(-1)?.position??-1)+1;return await s.insert(A,{agent:r.agent,enqueuedAt:d,instanceId:l,position:q,threadKey:r.key}),{outcome:"queued",position:q}},re=async(s,r,d)=>{if(r.policy==="queue")return oe(s,{agent:r.agent,instanceId:r.instanceId,key:r.key,priorInstanceId:r.priorInstanceId},d);if(r.policy!=="replace")throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — onConcurrentRun="${r.policy}"`);return await s.patch(r.existingId,{error:null,status:"running",updatedAt:d,...r.instanceId===void 0?{}:{completedInstanceId:null,instanceId:r.instanceId}}),{outcome:"replaced",priorInstanceId:r.priorInstanceId}},se=(s,r,d)=>{const l=s.instanceId;if(l===void 0||r===l||s.status!=="running"&&s.status!=="awaiting_input")return;const I=typeof s.updatedAt=="number"?s.updatedAt:0,w=s.status==="awaiting_input"?G:ae;return d-I>w?void 0:l},pe=()=>{const s=f.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 i=Date.now(),a=await n.db.query(m).withIndex("byKey",o=>o.eq("key",t.key)).first();if(a){if(a.owner!==t.owner)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);if(t.instanceId!==void 0&&a.completedInstanceId===t.instanceId)return{outcome:"completed"};const o=se(a,t.instanceId,i);return o!==void 0?re(n.db,{agent:t.agent,existingId:a._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:o},i):(await n.db.patch(a._id,{error:null,status:"running",updatedAt:i,...t.instanceId===void 0?{}:{completedInstanceId:null,instanceId:t.instanceId}}),{outcome:"continued"})}return await n.db.insert(m,{agent:t.agent,createdAt:i,key:t.key,messageCount:0,status:"running",updatedAt:i,...F({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),r=f.input({content:e.string(),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("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 i=await n.db.query(K).withIndex("byMessageKey",c=>c.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(i)return{seq:i.seq};const a=await n.db.query(m).withIndex("byKey",c=>c.eq("key",t.threadKey)).first();if(!a)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const o=a.messageCount,u=Date.now();return await n.db.insert(K,{content:t.content,createdAt:u,messageKey:t.messageKey,role:t.role,seq:o,threadKey:t.threadKey,...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(a._id,{messageCount:o+1,updatedAt:u}),{seq:o}}),d=f.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const i=await n.db.query(K).withIndex("byMessageKey",a=>a.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();i&&await n.db.delete(i._id)}),l=f.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()),summaryRuns:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),usage:e.optional(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).mutation(async({args:t,ctx:n})=>{const{instanceId:i,key:a}=t;let o;a!==void 0?o=await n.db.query(m).withIndex("byKey",u=>u.eq("key",a)).first():i!==void 0&&(o=await n.db.query(m).withIndex("byInstance",u=>u.eq("instanceId",i)).first()),!(!o||t.ifInstanceId!==void 0&&o.instanceId!==t.ifInstanceId)&&await n.db.patch(o._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.summaryRuns===void 0?{}:{summaryRuns:t.summaryRuns},...t.summaryThroughSeq===void 0?{}:{summaryThroughSeq:t.summaryThroughSeq},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),I=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const i=await n.db.query(m).withIndex("byKey",p=>p.eq("key",t.key)).first(),a=i?.summary,o=i?.summaryThroughSeq,u=i?.summaryRuns??0,c=typeof a=="string"&&a.length>0&&typeof o=="number"&&u<ne,h=await n.db.query(K).withIndex("byThread",p=>c?p.eq("threadKey",t.key).gt("seq",o):p.eq("threadKey",t.key)).collect();return c?{messages:h,runs:u,summary:a}:typeof a=="string"&&a.length>0&&typeof o=="number"?{fallback:{summary:a,throughSeq:o},messages:h,runs:0}:{messages:h,runs:0}}),w=f.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(e.object({inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),totalTokens:e.optional(e.number())}))}).mutation(async({args:t,ctx:n})=>{const i=Date.now(),a=await n.db.query(m).withIndex("byKey",p=>p.eq("key",t.key)).first();if(a?.instanceId!==t.instanceId){if(a?.completedInstanceId===t.instanceId&&a.status==="running"&&typeof a.instanceId=="string")return{dequeued:a.instanceId};const p=await n.db.query(A).withIndex("byThreadInstance",E=>E.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return p&&await n.db.delete(p._id),{}}const c=(a.completedInstanceId===t.instanceId?[]:await n.db.query(A).withIndex("byThread",p=>p.eq("threadKey",t.key)).collect())[0];if(!c)return await n.db.patch(a._id,{completedInstanceId:t.instanceId,status:t.status,updatedAt:i,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{};const h=c.instanceId;return await n.db.delete(c._id),await n.db.patch(a._id,{completedInstanceId:t.instanceId,instanceId:h,status:"running",updatedAt:i,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:h}}),q=f.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const i=await n.db.query(m).withIndex("byKey",a=>a.eq("key",t.key)).first();i&&await n.db.patch(i._id,{state:t.state,updatedAt:Date.now()})}),y=(t,n)=>{if(!t)return;const{owner:i}=t;if(!(i!==void 0&&i!==(n.userId??void 0)))return t},O=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const i=await n.db.query(m).withIndex("byKey",a=>a.eq("key",t.key)).first();return y(i,n.auth)}),L=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const i=await n.db.query(m).withIndex("byKey",a=>a.eq("key",t.key)).first();return y(i,n.auth)?.state}),U=k.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const i=await n.db.query(m).withIndex("byKey",a=>a.eq("key",t.key)).first();return y(i,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(K).withIndex("byThread",o=>o.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(K).withIndex("byThread",a=>a.eq("threadKey",t.key)).collect()}),B=f.input({decision:e.union(e.literal("approve"),e.literal("reject")),instanceId:e.string(),note:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const i=await n.db.query(m).withIndex("byKey",h=>h.eq("key",t.threadKey)).first(),a=y(i,n.auth);if(a===void 0)throw new g("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(a.instanceId!==t.instanceId)throw new g("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const o=a.agent,{agents:u}=n,c=u?.[o];if(typeof c?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${o}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);return await c.sendEvent(t.instanceId,{payload:{decision:t.decision,toolCallId:t.toolCallId,...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),j=f.input({agent:e.string(),input:e.string(),threadKey:e.string(),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const{agents:i}=n,a=i?.[t.agent];if(typeof a?.run!="function")throw new g("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(a.publicRun!==!0)throw new g("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 o=n.auth.userId??void 0,u=await n.db.query(m).withIndex("byKey",h=>h.eq("key",t.threadKey)).first();if(u){const h=u.status,p=u.instanceId,E=u.owner;if((h==="running"||h==="awaiting_input")&&p!==void 0&&(E===void 0||E===o))return{id:p,threadKey:t.threadKey};if(E!==o)throw new g("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:c}=await a.run({input:t.input,threadKey:t.threadKey,...o===void 0?{}:{owner:o},...t.title===void 0?{}:{title:t.title}});return{id:c,threadKey:t.threadKey}}),R=X(),C=te();return{extension:ie,functions:{agentAppendMessage:b(r),agentCompleteRun:b(w),agentEnsureThread:b(s),agentEpisodeRecall:C.agentEpisodeRecall,agentEpisodeUpsert:C.agentEpisodeUpsert,agentGraphTraverse:R.agentGraphTraverse,agentGraphUpsert:R.agentGraphUpsert,agentHistory:b(I),agentMessages:U,agentDeleteMessage:b(d),agentPatchThread:b(l),agentResolveApproval:B,agentRun:j,agentSetState:b(q),agentState:L,agentThread:O}}};export{pe as agentComponent,ie as agentExtension,Ie as normalizeEntityName,be as sandboxComponent};
|
package/dist/inbound.d.mts
CHANGED
package/dist/inbound.d.ts
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-
|
|
2
|
-
export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-C4vYEYW6.mjs";
|
|
2
|
+
export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-C4vYEYW6.mjs";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
5
|
export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.mjs";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-
|
|
2
|
-
export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentBindingSpec, v as AgentHandle, w as AgentToolConfig, x as AgentFunctionReference, y as AgentModelInput, z as SkillConfig } from "./packem_shared/types.d-C4vYEYW6.js";
|
|
2
|
+
export type { B as AgentApprovalContext, C as AgentEmailMapper, D as AgentEmailRun, E as AgentGenerateOptions, F as AgentGenerateResult, G as AgentInstructionsContext, H as AgentLiveEvent, J as AgentMemoryOptions, K as AgentMemorySource, L as AgentMessageStatus, M as AgentOnReply, N as AgentOnStepFinish, O as AgentPrepareStep, P as AgentPrepareStepInput, Q as AgentPrepareStepResult, R as AgentProgressEvent, T as AgentReplyInfo, a as AgentReplyRef, U as AgentRunHandle, V as AgentRunOptions, W as AgentStepFinishInfo, X as AgentStepInfo, Y as AgentThreadStatus, Z as AgentTokenDelta, _ as AgentToolCall, d as AgentToolContext, $ as AgentUsage, a0 as AgentVoiceConfig, a1 as AgentWorkflowBindingLike, a2 as AgentWorkflowInstanceLike, a3 as EnsureThreadOutcome } from "./packem_shared/types.d-C4vYEYW6.js";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
5
|
export { type BrowserRenderResult, type BrowserToolInput, type BrowserToolOptions, type ContainerFsToolOptions, type ContainerToolInput, type ContainerToolOptions, type FsToolInput, type FsToolOptions, type JsCodeToolInput, type JsCodeToolOptions, type JsCodeToolResult, browserTool, containerFsTool, containerTool, fsTool, jsCodeTool } from "./sandbox.js";
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as t,s as r}from"./packem_shared/agent-loop-
|
|
1
|
+
import{r as t,s as r}from"./packem_shared/agent-loop-BD9gwYAm.mjs";import{collectAgenticMemoryTools as a,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-D07XhGKr.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-BJi-uU4s.mjs";import{codeTool as m}from"./packem_shared/codeTool-dpJANTDc.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-D8M9JoBR.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-DGcFPe8V.mjs";import{functionTool as D}from"./packem_shared/functionTool-Baqdn0OK.mjs";import{createAgentGenerate as C,createEpisodeExtract as M,createGraphExtract as O,createStreamGenerate as _,resolveAgentModel as F}from"./packem_shared/createAgentGenerate-BvCZrr1X.mjs";import{jsCodeTool as L}from"./packem_shared/jsCodeTool-CIlCK1bG.mjs";import{adaptMcpResult as b,mcpTools as h}from"./packem_shared/adaptMcpResult-DFF_g58r.mjs";import{buildModelMessages as v}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as B,agentDefaultName as R,voiceBindingName as V,voiceClassName as H}from"./naming.mjs";import{AGENT_MODULE as P,DEFAULT_AGENT_FUNCTION_PATHS as X,SANDBOX_INVOKE_PATH as j,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-B6FqQC80.mjs";import{browserTool as q,containerFsTool as z,containerTool as J,fsTool as Q}from"./sandbox.mjs";import{defineSkill as Z,isSkillDefinition as $}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as oe}from"./packem_shared/VoiceSessionDO-CoAY8Ik1.mjs";import{r as re}from"./packem_shared/voice-turn-DJWmnCuv.mjs";import{webSearchTool as ae}from"./packem_shared/webSearchTool-DGEFTSp1.mjs";import{default as le}from"./packem_shared/compileAgentWorkflow-CrK26Wb8.mjs";export{P as AGENT_MODULE,X as DEFAULT_AGENT_FUNCTION_PATHS,j as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,oe as VoiceSessionDO,b as adaptMcpResult,s as agentAsTool,B as agentClassName,c as agentComponent,R as agentDefaultName,x as agentExtension,q as browserTool,v as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,le as compileAgentWorkflow,z as containerFsTool,J as containerTool,A as createAgentContext,C as createAgentGenerate,M as createEpisodeExtract,O as createGraphExtract,_ as createStreamGenerate,d as defineAgent,u as defineAgentTool,Z as defineSkill,Q as fsTool,D as functionTool,N as isAgentDefinition,$ as isSkillDefinition,L as jsCodeTool,h as mcpTools,F as resolveAgentModel,t as runAgentLoop,re as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,f as toSearchResults,V as voiceBindingName,H as voiceClassName,ae as webSearchTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="agents",a="sandbox",n=`${a}:invoke`,s={appendMessage:`${e}:agentAppendMessage`,completeRun:`${e}:agentCompleteRun`,deleteMessage:`${e}:agentDeleteMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,history:`${e}:agentHistory`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`},r=t=>typeof t=="string"?{__lunoraRef:t}:t;export{e as AGENT_MODULE,s as DEFAULT_AGENT_FUNCTION_PATHS,n as SANDBOX_INVOKE_PATH,a as SANDBOX_MODULE,r as toFunctionReference};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createAi as A}from"@lunora/ai";import{l as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as C}from"./voice-turn-
|
|
1
|
+
import{createAi as A}from"@lunora/ai";import{l as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as C}from"./voice-turn-DJWmnCuv.mjs";import{r as I}from"./agent-ai-CxEYOyOu.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-BvCZrr1X.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-B6FqQC80.mjs";const O="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",B=8*1024*1024,F=100,f=4e3,g=f*4+1024,D=4002,z=4003,W=4004,G=256*1024,S=15,X=5e3,K=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class j{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,r,s){this.state=t,this.env=e,this.agent=r,this.exportName=s,this.paths=N,this.ai=I(e)??A({env:e}),this.streamGenerate=R(r,e),this.sttModel=r.voice?.stt??O,this.ttsModel=r.voice?.tts??U,this.maxSessionTurns=r.voice?.maxTurns??F}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(t.url).searchParams.get("threadKey");if(!r)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,i=new s,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:r,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,r,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const r=t.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,r,e);return}this.bufferAudio(r.connectionId,new Uint8Array(e),t)}catch(s){this.send(t,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const r=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...r===void 0?{}:{speaker:r}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,r){if(r.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,W,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!K(s)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=s;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,D,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,r){const s=(this.bufferedBytes.get(t)??0)+e.byteLength;if(s>B){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,z,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,s)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const r=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of e)s.set(n,i),i+=n.byteLength;return s}async runTurn(t,e,r){const s=new AbortController;this.controllers.set(e.connectionId,s);try{await w({agent:this.agent,compact:L(),connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(e.connectionId)===s&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:r,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...s===void 0?{}:{owner:s}}))?.outcome!=="created")return;for await(const u of C(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}closeSocket(t,e,r){try{t.close?.(e,r)}catch{}}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let r=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>G&&r<X;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{j as default};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{jsonSchema as i}from"@ai-sdk/provider-utils";import{LunoraError as c}from"@lunora/errors";const s=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const n=(t.content??[]).filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
2
2
|
`);return t.isError===!0?`MCP tool error: ${n.length>0?n:"unknown error"}`:n.length>0?n:t.content},l=(t,n,e)=>({description:n.description??`MCP tool "${n.name}".`,execute:async r=>s(await t.callTool({arguments:r,name:n.name})),inputSchema:i(n.inputSchema),isLunoraAgentTool:!0,...e===void 0?{}:{needsApproval:typeof e=="function"?r=>e(n.name,r):e}}),u=async t=>{if(t.command!==void 0)throw new c("INTERNAL","@lunora/agent: mcpTools `command` (stdio transport) cannot run in the Workers runtime — pass a `url` for an HTTP/SSE MCP server, or inject a connected `client`");if(t.url===void 0)throw new c("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const n=new URL(t.url),{Client:e}=await import("@modelcontextprotocol/sdk/client/index.js");let r;if(t.transport==="sse"){const{SSEClientTransport:a}=await import("@modelcontextprotocol/sdk/client/sse.js");r=new a(n)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(n)}const o=new e({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await o.connect(r),o},T=async t=>{const n=t.client??await u(t),{tools:e}=await n.listTools(),r={};for(const o of e)t.only!==void 0&&!t.only.includes(o.name)||(r[`${t.prefix??""}${o.name}`]=l(n,o,t.needsApproval));return r};export{s as adaptMcpResult,T as mcpTools};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{f as at}from"./DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs";import{r as z}from"./workflow-binding-Dm9hBzx_.mjs";import{c as G,d as st}from"./component-shared-G8ngerkU.mjs";import{resolveAgentModel as rt}from"./createAgentGenerate-BvCZrr1X.mjs";import{buildModelMessages as q}from"./buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as H}from"../naming.mjs";import{toFunctionReference as v}from"./AGENT_MODULE-B6FqQC80.mjs";import{i as it}from"./positive-integer-ztHqqpBk.mjs";import{combineTelemetry as ct}from"./combineTelemetry-DgE9W9G8.mjs";import{c as L}from"./tool-output-Cmk3JWMG.mjs";const ut=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",P=e=>e.memorySources?e.memorySources:e.memory&&ut(e.memory)?[{key:"default",...e.memory}]:[],dt=e=>P(e).find(t=>t.kind==="graph"),lt=e=>P(e).find(t=>t.kind==="episodic"),$=(e,t)=>t==="default"?e:`${e}:${t}`,pt=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const n=Array.isArray(t)?t:[t];return n.length===0?void 0:ct(...n)},mt=async(e,t,n)=>{const o=pt(e);if(o===void 0)return n();const a={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:a,toolContext:void 0},c=Date.now();await o.onToolExecutionStart?.(s);let u;const d=()=>(u??=n(),u);try{if(o.executeTool===void 0)await d();else try{await o.executeTool({...s,execute:d,toolCallId:t.id})}catch{}const i=await d();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,input:t.input,output:i,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),i}catch(i){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,error:i,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),i}},yt=8,ht=e=>it(e)?e:0,V=e=>e===void 0?"null":JSON.stringify(e),ft=async(e,t,n)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...n===void 0?{}:{usage:n}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},vt=e=>e===void 0?[]:[e].flat(),gt=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),wt=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const n={};for(const o of["inputTokens","outputTokens","totalTokens"])(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},Tt=async(e,t,n,o,a)=>{const{needsApproval:s}=e;return s===void 0||s===!1?!1:s===!0?!0:n.do(o,async()=>s(t,a))},xt="WorkflowTimeoutError",kt=e=>e instanceof Error&&e.name===xt,B=4320*60*1e3,Ct={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},St=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,$t=e=>{if(e===void 0)return B;if(typeof e=="number")return Math.min(e,G);const t=St.exec(e);return t===null?B:Math.min(Number(t[1])*Ct[t[2]],G)},Et=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:c,step:u}=e;await c({content:`Awaiting approval to run tool "${t.name}".`,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"});const d=await u.waitForEvent(`approval:${t.id}`,{timeout:$t(n.approvalTimeout),type:`agent-approval:${t.id}`}).then(i=>({decision:i.payload.decision,...i.payload.note===void 0?{}:{note:i.payload.note}})).catch(i=>{if(!kt(i))throw i;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),d},N="lunoraToolOutcome",Mt=e=>typeof e=="object"&&e!==null&&N in e?e[N]:{ok:e},It=async(e,t)=>{const{agent:n,depth:o,env:a,exports:s,getState:c,instanceId:u,onTokenDelta:d,owner:i,persist:y,run:r,setState:l,step:m,threadKey:h,tools:g}=e,p=`tool:${t.name}:${t.id}`,x=g[t.name],T=`${u}:tool:${t.id}`;if(!x){await y({content:`Error: unknown tool "${t.name}"`,messageKey:T,role:"tool",stepName:p,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await y({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:T,role:"tool",stepName:p,toolCallId:t.id,toolName:t.name});return}const A={depth:o,env:a,exports:s,getState:c,idempotencyKey:p,owner:i,reportProgress:w=>{d?.({data:w,kind:"progress",threadKey:h,toolCallId:t.id})},run:r,setState:l,step:m,threadKey:h,toolCallId:t.id},O={depth:o,env:a,getState:c,idempotencyKey:p,run:r,threadKey:h,toolCallId:t.id},_=`tool:approval-gate:${t.id}`;let k;if(await Tt(x,t.input,m,_,O)){const{decision:w,note:C}=await Et(e,t);if(w==="reject"){const U=C===void 0?"":` Reason: ${C}`;await y({content:`Tool "${t.name}" was rejected by the user and not run.${U}`,messageKey:T,role:"tool",status:"rejected",stepName:p,toolCallId:t.id,toolName:t.name});return}k="approved"}const E=Mt(await m.do(p,async()=>{try{const w=()=>Promise.resolve(x.execute(t.input,A)),C=await mt(n.telemetry,{id:t.id,input:t.input,name:t.name},w);return{[N]:{ok:C}}}catch(w){if(at(w))return{[N]:{failed:w.message}};throw w}}));if("failed"in E){await y({content:L(`Error: tool "${t.name}" failed and will not be retried. ${E.failed}`),messageKey:T,role:"tool",stepName:p,...k===void 0?{}:{status:k},toolCallId:t.id,toolName:t.name});return}const M=E.ok;await y({content:L(typeof M=="string"?M:V(M)),messageKey:T,role:"tool",stepName:p,...k===void 0?{}:{status:k},toolCallId:t.id,toolName:t.name})},Rt=(e,t,n)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:rt(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},X=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const n=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=n)return;let o=e.length-n;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},Kt=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=X(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const c=await o({env:a,messages:q({history:s.older}),model:n.compaction?.model??n.model});return c.length>0?{history:s.recent,summary:c}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Nt=async e=>{const{agent:t,compact:n,env:o,historyRef:a,instanceId:s,patchThread:c,run:u,threadKey:d}=e,i=await u(a,{key:d}),{messages:y,summary:r}=i,l=X(y,t.compaction);if(l===void 0||n===void 0)return{history:y,summary:r};const m=async()=>{const{fallback:g}=i;return g===void 0?{history:y,summary:r}:(await c({ifInstanceId:s,summaryRuns:0}).catch(p=>{console.warn(`@lunora/agent: could not reset the summary run counter for thread "${d}"`,p)}),{history:y.filter(p=>p.seq>g.throughSeq),summary:g.summary})};let h;try{h=await n({env:o,messages:q({history:l.older,summary:r}),model:t.compaction?.model??t.model})}catch(g){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,g),m()}return h.length===0?m():(await c({ifInstanceId:s,summary:h,summaryRuns:r===void 0?1:i.runs+1,summaryThroughSeq:l.older.at(-1)?.seq}).catch(g=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,g)}),{history:l.recent,summary:h})},At=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:c,listMessages:u,memoryContext:d,onTokenDelta:i,run:y,step:r,streamGenerate:l,threadKey:m}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const{history:h,summary:g}=o.compaction!==void 0&&e.compact!==void 0?await Nt(e):await Kt(e,await y(u,{key:m}));let p={activeTools:o.activeTools,messages:q({history:h,instructions:c,memoryContext:d,summary:g}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(p=Rt(p,await o.prepareStep({messages:p.messages,stepNumber:t,steps:n}),a));const x={messages:p.messages,...p.activeTools===void 0?{}:{activeTools:p.activeTools},...p.model===void 0?{}:{model:p.model},...p.toolChoice===void 0?{}:{toolChoice:p.toolChoice}};return l&&i?l(x,T=>{i({text:T,threadKey:m,turn:t})}):s(x)})},W=async(e,t)=>{const{agent:n,step:o}=e;n.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await n.onStepFinish?.(t),!0))},Ot=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),F=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},_t=e=>st({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Ut=async(e,t,n,o)=>{if(e.source===void 0)return;const a=v(e.source),{topK:s}=e,c=$("memory:retrieve",e.key),u=await n.do(c,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return F(u)},Dt=async(e,t,n,o,a,s)=>{if(n===void 0)return;const c=$("memory:traverse",e.key),u=await a.do(c,async()=>s(o,{owner:n,query:t,..._t(e.graph)}));return F(u)},qt=async(e,t,n,o,a)=>{if(t===void 0)return;const s=$("memory:recall",e.key),c={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},u=await o.do(s,async()=>a(n,c));return F(u)},Pt=async(e,t)=>e.kind==="episodic"?qt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?Dt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Ut(e,t.input,t.step,t.run),Ft=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},bt=async(e,t,n,o,a,s)=>{const c=Ft(P(e));if(c.length===0)return;const u=v(o.graphTraverse),d=v(o.episodeRecall),i=[];for(const y of c){const r=await Pt(y,{episodeRecall:d,graphTraverse:u,input:t,owner:n,run:s,step:a});r!==void 0&&i.push(r)}return i.length>0?i.join(`
|
|
2
|
+
|
|
3
|
+
`):void 0},jt=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:c,owner:u,paths:d,run:i,step:y}=e;if(o===void 0||u===void 0||a===void 0||a.length===0)return;const r=dt(t);if(r!==void 0)try{const l={assistantText:a,env:n,model:r.graph?.extractionModel??t.model,userInput:s},m=await y.do($("memory:extract",r.key),async()=>o(l));await i(v(d.graphUpsert),{...m,messageKey:`${c}:${$("extract",r.key)}`,owner:u})}catch{}},Gt=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:c,owner:u,paths:d,run:i,step:y,threadKey:r}=e;if(o===void 0||u===void 0||a===void 0||a.length===0)return;const l=lt(t);if(l!==void 0)try{const m={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:h}=await y.do($("memory:episode",l.key),async()=>o(m));await i(v(d.episodeUpsert),{messageKey:`${c}:${$("episode",l.key)}`,owner:u,summary:h,threadKey:r})}catch{}},Lt=async(e,t,n)=>{const o=z(e.env,e.exports,H(t),["get"]);if(o!==void 0)try{await(await o.get(n)).terminate()}catch{}},Bt="12 hours",Wt=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:Bt,type:`agent-dequeue:${t}:${n}`})},zt=async(e,t,n)=>{const o=z(e.env,e.exports,H(e.exportName),["get"]);if(o===void 0)return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},Ht=async(e,t,n)=>{const{onReply:o}=e,{replyRef:a}=t.params;if(!(o===void 0||a===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:a,result:n,threadKey:t.params.threadKey}),a.channel))}catch{}},Vt=async(e,t,n,o,a)=>{const{instanceId:s,persist:c}=e,u=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const d=n.output!==void 0&&n.text.length===0?V(n.output):n.text;return await c({content:d,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await W(e,{text:n.text,toolCalls:[],turn:t,...u}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await c({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const d of n.toolCalls)await It(e,d);if(await W(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...u}),o.push(Ot(n)),a.length>0&&await gt(a,o))return"stopCondition"},Xt=async(e,t,n,o)=>{const a=[];let s,c=!1,u=0;for(let d=0;d<t;d+=1){const i=await At(e,d,a);o.value=wt(o.value,i.usage),u=d+1;const y=await Vt(e,d,i,a,n);if(y==="stopCondition"){c=!0;break}if(y!==void 0){s=y.final;break}}return{final:s,stoppedByCondition:c,turnsRun:u}},re=async e=>{const{agent:t,compact:n,env:o,exportName:a,exports:s,extractEpisode:c,extractGraph:u,generate:d,instanceId:i,onTokenDelta:y,params:r,paths:l,run:m,step:h,streamGenerate:g}=e,p=t.maxTurns??yt,x=vt(t.stopWhen),T=v(l.appendMessage),b=v(l.completeRun),A=v(l.ensureThread),O=v(l.listMessages),_=v(l.history),k=v(l.deleteMessage),E=v(l.patchThread),M=v(l.setState),w=v(l.state),C=async f=>{await m(T,{threadKey:r.threadKey,...f})},U=async f=>{await m(E,{key:r.threadKey,...f})},J=async f=>{await m(k,{messageKey:f,threadKey:r.threadKey})},Q=async()=>{await C({content:r.input,messageKey:`${i}:user`,role:"user"})},j={dispatched:!1},I=async f=>{j.dispatched=!0;const K=await m(b,{instanceId:i,key:r.threadKey,...f});K?.dequeued!==void 0&&await zt({env:o,exportName:a,exports:s,step:h},r.threadKey,K.dequeued)},Y=async()=>await m(w,{key:r.threadKey}),Z=async f=>{await m(M,{key:r.threadKey,state:f})},D=await m(A,{agent:a,instanceId:i,key:r.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...r.owner===void 0?{}:{owner:r.owner},...r.title===void 0?{}:{title:r.title}});D?.outcome==="replaced"&&await Lt({env:o,exports:s},a,D.priorInstanceId);const tt=await bt(t,r.input,r.owner,l,h,m),et=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,ot={agent:t,compact:n,depth:ht(r.depth),env:o,exports:s,generate:d,getState:Y,historyRef:_,instanceId:i,instructions:et,listMessages:O,memoryContext:tt,onTokenDelta:y,owner:r.owner,deleteMessage:J,patchThread:U,persist:C,run:m,setState:Z,step:h,streamGenerate:g,threadKey:r.threadKey,tools:t.tools??{}},R={value:void 0};try{D?.outcome==="queued"&&await Wt(h,r.threadKey,i),await Q();const{final:f,stoppedByCondition:K,turnsRun:nt}=await Xt(ot,p,x,R),S=R.value===void 0?{}:{usage:R.value};return await jt({agent:t,env:o,extractGraph:u,finalText:f?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:m,step:h}),await Gt({agent:t,env:o,extractEpisode:c,finalText:f?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:m,step:h,threadKey:r.threadKey}),f?(await Ht(t,{env:o,params:r,step:h},{...f,...S}),await I({status:"idle",...S}),{...f,...S}):K?(await I({status:"idle",...S}),{stopped:"stopCondition",turns:nt,...S}):(await I({error:`agent stopped: maxTurns (${String(p)}) reached`,status:"error",...S}),{stopped:"maxTurns",turns:p,...S})}catch(f){throw j.dispatched||await ft(I,f,R.value),f}};export{$t as a,Kt as c,ut as i,re as r,X as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonSchema as I}from"@ai-sdk/provider-utils";import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as L}from"@lunora/workflow";import{f as S}from"./fnv1a-BNN96GYb.mjs";import{r as b}from"./workflow-binding-Dm9hBzx_.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as $,DEFAULT_AGENT_FUNCTION_PATHS as P}from"./AGENT_MODULE-B6FqQC80.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),x=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",k=t=>t!==null&&typeof t=="object"?t.output:void 0,C=async t=>{await new Promise(e=>{setTimeout(e,t)})},D=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=R(a);if(_.has(s))return{output:k(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},U=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},j=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},V=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??x,o=t.pollIntervalMs??M,a=t.wait??C,s=$(P.listMessages),T=async(y,r)=>{const p=(h(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=b(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,g=`sub-${e}-${S(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:g,params:A});l=await i.get(d.id)}catch(d){if(!L(d))throw d;l=await i.get(g)}const{output:v,status:u}=await D(l,m,o,a);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(U(v)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const E=await r.run(s,{key:f});return j(E)};return{description:t.description,execute:T,inputSchema:I({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{V as agentAsTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonSchema as h,asSchema as v}from"@ai-sdk/provider-utils";import{LunoraError as a}from"@lunora/errors";import{i as A}from"./positive-integer-ztHqqpBk.mjs";import{M as g,c as w}from"./tool-output-Cmk3JWMG.mjs";const $=16,T=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=g?e:w(o)},S=(e,o)=>{let t=e;for(const n of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,n))return;t=t[n]}return t},l=(e,o)=>{if(Array.isArray(e))return e.map(r=>l(r,o));if(e===null||typeof e!="object")return e;const t=e;if(typeof t.$from=="string"){const r=t.$from;if(!Object.hasOwn(o,r))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?S(o[r],t.$path):o[r]}const n={};for(const[r,i]of Object.entries(t))r!=="__proto__"&&(n[r]=l(i,o));return n},b=async(e,o,t)=>{const{validate:n}=v(o.inputSchema);if(n===void 0)return t;const r=await n(t);if(r.success)return r.value;throw new a("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${r.error.message}`)},O=async(e,o,t,n)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>n)throw new a("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(n)}. Split it across several code calls.`);const i={},p=[],d=new Set;for(const s of r){if(d.has(s.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${s.id}" — each step id must be unique (later steps reference an output by id via $from)`);d.add(s.id)}for(const s of r){const c=Object.hasOwn(o,s.tool)?o[s.tool]:void 0;if(!c)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${s.tool}" (available: ${Object.keys(o).join(", ")})`);const m=await b(s,c,l(s.input??{},i)),u={...t,idempotencyKey:`${t.idempotencyKey}:${s.id}`,toolCallId:`${t.toolCallId}:${s.id}`},y=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,y);i[s.id]=f,p.push({id:s.id,output:T(f)})}return{final:p.at(-1)?.output,results:p}},E=e=>`Compose MULTIPLE tool calls in one turn as a script, instead of one call per turn. Provide \`steps\`: an ordered array of \`{ id, tool, input }\`. A later step's \`input\` may reference an earlier step's output with \`{ "$from": "<stepId>", "$path": "optional.dot.path" }\`. Available tools: ${Object.entries(e).map(([o,t])=>`"${o}" — ${t.description}`).join("; ")}.`,_=h({properties:{steps:{description:"Ordered tool calls; a later input may reference an earlier output via { $from, $path }.",items:{additionalProperties:!1,properties:{id:{description:"A name later steps reference this output by.",type:"string"},input:{additionalProperties:!0,description:"The tool input (may embed $from refs).",type:"object"},tool:{description:"The tool to call.",type:"string"}},required:["id","tool"],type:"object"},type:"array"}},required:["steps"],type:"object"}),P=(e,o={})=>{const t=e;if(!t||typeof t!="object"||Object.keys(t).length===0)throw new a("INTERNAL","@lunora/agent: codeTool requires a non-empty map of tools to compose");for(const[r,i]of Object.entries(t))if(i.needsApproval!==void 0&&i.needsApproval!==!1)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it has a \`needsApproval\` gate a code-mode script can't pause for. Expose it as a normal top-level tool, or gate the whole script via codeTool's \`needsApproval\`.`);if(o.maxSteps!==void 0&&!A(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const n=o.maxSteps??$;return{description:o.description??E(e),execute:(r,i)=>O(r,e,i,n),inputSchema:_,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{P as codeTool,l as resolveReferences,O as runToolScript};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonSchema as u}from"@ai-sdk/provider-utils";import{toFunctionReference as d}from"./AGENT_MODULE-B6FqQC80.mjs";const h=240,m=50,y=(t,s)=>t.length<=s?t:`${t.slice(0,s)}…`,f=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(m,Math.max(1,Math.trunc(t)))},g=(t,s)=>{const r=t??{},i=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:y(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},S=u({additionalProperties:!1,properties:{query:{description:"Natural-language search query.",type:"string"},topK:{description:"Maximum number of hits to return.",type:"number"}},required:["query"],type:"object"}),A=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),b=(t,s,r)=>{const i=d(s),e=Math.max(1,t.snippetChars??h),o=t.topK;return{description:`Search long-term memory for passages relevant to a query. Returns ranked { id, sourceId, score, snippet } hits — call again with a refined query to dig deeper.${r===void 0?"":` Use \`${r}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,p)=>{const a=f(n.topK)??o,l=await p.run(i,{query:n.query,...a===void 0?{}:{topK:a}});return g(l,e)},inputSchema:S,isLunoraAgentTool:!0}},T=t=>{const s=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,i)=>i.run(s,{id:r.id}),inputSchema:A,isLunoraAgentTool:!0}},k=(t,s)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of s)e.knowledge&&r.push({key:e.name,...e.knowledge});const i={};for(const e of r){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,c=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=b(e,e.source,n?c:void 0),n&&(i[c]=T(e.read))}return i};export{k as collectAgenticMemoryTools,g as toSearchResults};
|
package/dist/packem_shared/{compileAgentWorkflow-C287O2ux.mjs → compileAgentWorkflow-CrK26Wb8.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineWorkflow as i}from"@lunora/workflow";import{r as m}from"./agent-loop-
|
|
1
|
+
import{defineWorkflow as i}from"@lunora/workflow";import{r as m}from"./agent-loop-BD9gwYAm.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-BvCZrr1X.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-B6FqQC80.mjs";import{l as T}from"./DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-ByqrB-72.mjs";const E=(r,t,a)=>T({env:t,label:"@lunora/agent",...a===void 0?{}:{fetchImpl:a},...r===void 0?{}:{identity:{userId:r}}}),O=(r,t,a)=>{const e=t.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||r.telemetry?.isEnabled===!1)return r;const n=typeof t.LUNORA_OTLP_TOKEN=="string"?t.LUNORA_OTLP_TOKEN:void 0,o=[r.telemetry?.integrations].flat().filter(s=>s!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...o,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>i({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:u(),env:e.env,exports:e.exports,exportName:t,extractGraph:d(),extractEpisode:f(),generate:l(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??A,run:E(e.params.owner,e.env,e.fetchImpl),step:e.step,streamGenerate:p(n,e.env)})},name:r.name??c(t)});export{I as default};
|
package/dist/packem_shared/{createAgentContext-BxDMNWNG.mjs → createAgentContext-D8M9JoBR.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as f}from"./DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs";import{LunoraError as o}from"@lunora/errors";import{h as g,B as w}from"./branch-marker-boZ00zmk.mjs";import{r as h}from"./workflow-binding-Dm9hBzx_.mjs";import{toFunctionReference as E,DEFAULT_AGENT_FUNCTION_PATHS as N}from"./AGENT_MODULE-
|
|
1
|
+
import{l as f}from"./DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs";import{LunoraError as o}from"@lunora/errors";import{h as g,B as w}from"./branch-marker-boZ00zmk.mjs";import{r as h}from"./workflow-binding-Dm9hBzx_.mjs";import{toFunctionReference as E,DEFAULT_AGENT_FUNCTION_PATHS as N}from"./AGENT_MODULE-B6FqQC80.mjs";const _=(r,c,i={})=>{const{dispatch:l,exports:u}=i,s={},d=E(N.patchThread),p=()=>l??f({env:r,label:"@lunora/agent"});for(const n of c){const a=()=>{const t=h(r,u,n.className,["create","get"]);if(t===void 0)throw new o("INTERNAL",`@lunora/agent: no "${n.className}" on ctx.exports or env for agent "${n.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return t};s[n.exportName]={cancel:async t=>{await(await a().get(t)).terminate();try{await p()(d,{instanceId:t,status:"cancelled"})}catch{}},publicRun:n.publicRun===!0,run:async(t,e)=>{if(g(t))throw new o("BAD_REQUEST",`@lunora/agent: run input ${w}`);return{id:(await a().create({...e?.id===void 0?{}:{id:e.id},params:t})).id}},sendEvent:async(t,e)=>{await(await a().get(t)).sendEvent(e)},status:async t=>(await a().get(t)).status()}}return s};export{_ as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{jsonSchema as x}from"@ai-sdk/provider-utils";import{LunoraError as A}from"@lunora/errors";import{r as C}from"./agent-ai-CxEYOyOu.mjs";const y=e=>{if(!e)return;const t={};for(const o of["inputTokens","outputTokens","totalTokens"]){const r=e[o];r!==void 0&&(t[o]=r)}return Object.keys(t).length>0?t:void 0},b=e=>e.map(t=>{const o={id:t.toolCallId,input:t.input,name:t.toolName};return t.invalid!==!0?o:{...o,invalid:t.error instanceof Error?t.error.message:String(t.error)}}),d=(e,t)=>{if(typeof e=="function")return e(t);if(typeof e=="string"){const o=C(t);if(!o)throw new A("INTERNAL",`@lunora/agent: the agent model "${e}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return o.model(e)}return e};let g;const m=()=>(g??=import("ai").catch(e=>{throw g=void 0,e}),g),k=(e,t,o)=>{const r=d(t.model,o),n={};for(const[i,c]of Object.entries(t.tools??{}))n[i]=e.tool({description:c.description,inputSchema:c.inputSchema});const s=t.output===void 0?void 0:e.Output.object({schema:t.output}),a={...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{maxOutputTokens:t.maxOutputTokens},...t.telemetry===void 0?{}:{telemetry:t.telemetry},...t.repairToolCall===void 0?{}:{experimental_repairToolCall:t.repairToolCall}};return{defaultModel:r,output:s,staticSettings:a,tools:n}},v=(e,t)=>{let o;return()=>(o??=m().then(r=>({ai:r,base:k(r,e,t)})).catch(r=>{throw o=void 0,r}),o)},w=(e,{activeTools:t,messages:o,model:r,signal:n,toolChoice:s})=>{const{defaultModel:a,output:i,staticSettings:c,tools:l}=e,u=t===void 0?l:Object.fromEntries(Object.entries(l).filter(([h])=>t.includes(h)));return{messages:o,model:r??a,...c,...Object.keys(u).length>0?{tools:u}:{},...s===void 0?{}:{toolChoice:s},...i===void 0?{}:{output:i},...n===void 0?{}:{abortSignal:n}}},I=(e,t)=>{const o=v(e,t);return async r=>{const{ai:n,base:s}=await o(),a=await n.generateText(w(s,r)),i=y(a.usage);return{text:a.text,toolCalls:b(a.toolCalls),...i===void 0?{}:{usage:i},...s.output===void 0?{}:{output:a.output}}}},M=(e,t)=>{const o=v(e,t);return async(r,n)=>{const{ai:s,base:a}=await o(),i=s.streamText(w(a,r));let c="";try{for await(const p of i.textStream)c+=p,n(p)}catch(p){if(r.signal?.aborted)return{text:c,toolCalls:[]};throw p}const[l,u,h,T]=await Promise.all([i.text,i.toolCalls,i.usage,a.output===void 0?Promise.resolve(void 0):i.output]),f=y(h);return{text:l,toolCalls:b(u),...f===void 0?{}:{usage:f},...a.output===void 0?{}:{output:T}}}},O=x({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),j=(e,t)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${e}`,"",`Assistant: ${t}`].join(`
|
|
2
|
+
`),_=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await m(),{output:s}=await n.generateText({model:d(o,t),output:n.Output.object({schema:O}),prompt:j(r,e)});return s},E=(e,t)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${e}`,"",`Assistant: ${t}`].join(`
|
|
3
|
+
`),R=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await m(),{text:s}=await n.generateText({model:d(o,t),prompt:E(r,e)});return{summary:s.trim()}},S="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",$=()=>async({env:e,messages:t,model:o})=>{const r=await m(),{text:n}=await r.generateText({messages:t,model:d(o,e),system:S});return n.trim()};export{I as createAgentGenerate,$ as createCompact,R as createEpisodeExtract,_ as createGraphExtract,M as createStreamGenerate,d as resolveAgentModel};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-BD9gwYAm.mjs";import{collectAgenticMemoryTools as g}from"./collectAgenticMemoryTools-D07XhGKr.mjs";import{agentAsTool as p}from"./agentAsTool-BJi-uU4s.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=/^[a-zA-Z][\w-]*$/u,N=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=a}return o},A=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
|
|
2
2
|
|
|
3
3
|
`)},k=(e,n)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const t of n)t.knowledge&&m(t.knowledge)&&o.push({key:t.name,...t.knowledge});return o},y=e=>{const n=new Set;for(const o of e){if(typeof o.name!="string"||!w.test(o.name))throw new r("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new r("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(n.has(o.name))throw new r("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);n.add(o.name)}},v=(e,n)=>{if(e===void 0)return;const o=Object.keys(n).filter(t=>!e.includes(t));if(o.length>0)throw new r("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(t=>`"${t}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},E=(e,n)=>{const o=(t,s)=>{if(t&&t.kind!=="graph"&&t.kind!=="episodic"&&t.source===void 0)throw new r("INTERNAL",`@lunora/agent: ${s} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const t of n)o(t.knowledge,`skill "${t.name}" \`knowledge\``)},L=e=>{if(e===void 0)return;const n=f(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},$=e=>{const n=e.model;if(n==null||typeof n=="string"&&n.length===0)throw new r("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(e.maxTurns!==void 0&&!u(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!u(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");L(e.approvalTimeout);const o=e.skills??[];y(o),E(e,o);const t=N(e,o),s=g(e,o);for(const[i,h]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=h}const a=Object.keys(s).length>0;v(e.activeTools,s);for(const i of Object.keys(t))if(!T.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=k(e,o),d=A(e,o);return{...e,asTool:p,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:t}:{}}},j=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,M=e=>{if(typeof e.execute!="function")throw new r("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{$ as defineAgent,M as defineAgentTool,j as isAgentDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as o}from"@lunora/errors";import{toFunctionReference as c}from"./AGENT_MODULE-
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";import{toFunctionReference as c}from"./AGENT_MODULE-B6FqQC80.mjs";const m=(r,e)=>{if(typeof e.description!="string"||e.description.length===0)throw new o("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(e.inputSchema===void 0)throw new o("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const t=c(r);return{description:e.description,execute:(i,n)=>n.run(t,{...i,idempotencyKey:n.idempotencyKey}),inputSchema:e.inputSchema,isLunoraAgentTool:!0}};export{m as functionTool};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{jsonSchema as m}from"@ai-sdk/provider-utils";import{LunoraError as y}from"@lunora/errors";const u="LOADER",b="2026-04-07",S=1e3,f=100,v=2e3,g=256*1024,p=3e4,T="Run JavaScript in an isolated sandbox and get its result. Provide `code`: the body of an async function — `return` the answer. Use it for calculation, parsing and data transformation. The sandbox has no network, no bindings and no tools; `console.log` output is returned as `logs`.",h=m({additionalProperties:!1,properties:{code:{description:"The body of an async function. `return` the result; it must be JSON-serializable.",type:"string"}},required:["code"],type:"object"}),w=e=>`const logs = [];
|
|
2
2
|
const format = (value) => { if (typeof value === "string") return value; try { return JSON.stringify(value); } catch { return String(value); } };
|
|
3
3
|
const record = (...values) => { if (logs.length < ${String(f)}) logs.push(values.map(format).join(" ")); };
|
|
4
4
|
const sandboxConsole = { debug: record, error: record, info: record, log: record, warn: record };
|
|
@@ -15,4 +15,4 @@ export default {
|
|
|
15
15
|
}
|
|
16
16
|
},
|
|
17
17
|
};
|
|
18
|
-
`,E=e=>e instanceof Error?e.message:String(e),_=async(e,r)=>{const o=e.body?.getReader();if(o===void 0)return"";const t=new TextDecoder;let n="",a=0;for(;;){const{done:s,value:i}=await o.read();if(s)break;if(a+=i.byteLength,a>r){await o.cancel();return}n+=t.decode(i,{stream:!0})}return n+t.decode()},L=e=>(Array.isArray(e)?e:[]).slice(0,f).map(r=>String(r).slice(0,v)),A=async(e,r,o)=>{let t;const n=new Promise(s=>{t=setTimeout(()=>{s({error:`the script did not finish within ${String(p)} ms`,logs:[]})},p)}),a=async()=>{const i=await e.load({compatibilityDate:b,env:{},globalOutbound:null,limits:{cpuMs:o,subRequests:0},mainModule:"main.js",modules:{"main.js":w(r)}}).getEntrypoint().fetch("https://sandbox/"),l=await _(i,g);if(l===void 0)return{error:`the script's result is over ${String(g)} bytes — return less`,logs:[]};const c=JSON.parse(l),d=L(c.logs);return typeof c.error=="string"?{error:c.error,logs:d}:{logs:d,value:c.value}};try{return await Promise.race([a(),n])}catch(s){return{error:E(s),logs:[]}}finally{clearTimeout(t)}},M=(e={})=>{const r=e.cpuMs??S;if(!Number.isInteger(r)||r<=0)throw new
|
|
18
|
+
`,E=e=>e instanceof Error?e.message:String(e),_=async(e,r)=>{const o=e.body?.getReader();if(o===void 0)return"";const t=new TextDecoder;let n="",a=0;for(;;){const{done:s,value:i}=await o.read();if(s)break;if(a+=i.byteLength,a>r){await o.cancel();return}n+=t.decode(i,{stream:!0})}return n+t.decode()},L=e=>(Array.isArray(e)?e:[]).slice(0,f).map(r=>String(r).slice(0,v)),A=async(e,r,o)=>{let t;const n=new Promise(s=>{t=setTimeout(()=>{s({error:`the script did not finish within ${String(p)} ms`,logs:[]})},p)}),a=async()=>{const i=await e.load({compatibilityDate:b,env:{},globalOutbound:null,limits:{cpuMs:o,subRequests:0},mainModule:"main.js",modules:{"main.js":w(r)}}).getEntrypoint().fetch("https://sandbox/"),l=await _(i,g);if(l===void 0)return{error:`the script's result is over ${String(g)} bytes — return less`,logs:[]};const c=JSON.parse(l),d=L(c.logs);return typeof c.error=="string"?{error:c.error,logs:d}:{logs:d,value:c.value}};try{return await Promise.race([a(),n])}catch(s){return{error:E(s),logs:[]}}finally{clearTimeout(t)}},M=(e={})=>{const r=e.cpuMs??S;if(!Number.isInteger(r)||r<=0)throw new y("INTERNAL","@lunora/agent: jsCodeTool `cpuMs` must be a positive integer");return{description:e.description??T,execute:async(o,t)=>{const n=t.env[u];return typeof n?.load!="function"?{error:`jsCodeTool: no Worker Loader binding "${u}" on env — declare \`"worker_loaders": [{ "binding": "${u}" }]\` in wrangler.jsonc`,logs:[]}:A(n,o.code,r)},inputSchema:h,isLunoraAgentTool:!0}};export{M as jsCodeTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs";import"./workflow-binding-Dm9hBzx_.mjs";import"./component-shared-G8ngerkU.mjs";import"./createAgentGenerate-
|
|
1
|
+
import"./DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs";import"./workflow-binding-Dm9hBzx_.mjs";import"./component-shared-G8ngerkU.mjs";import"./createAgentGenerate-BvCZrr1X.mjs";import{a as l,c as u,r as f,s as g}from"./agent-loop-BD9gwYAm.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"../naming.mjs";import"./AGENT_MODULE-B6FqQC80.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./tool-output-Cmk3JWMG.mjs";export{l as approvalTimeoutMs,u as compactHistory,f as runAgentLoop,g as splitForCompaction};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-
|
|
1
|
+
import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-DJWmnCuv.mjs";import"./agent-loop-BD9gwYAm.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"./AGENT_MODULE-B6FqQC80.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,c as toByteIterable};
|
|
@@ -1035,6 +1035,11 @@ interface AgentFunctionPaths {
|
|
|
1035
1035
|
graphTraverse: string;
|
|
1036
1036
|
/** The internal `agents:agentGraphUpsert` mutation the loop dispatches on run-end graph extraction. */
|
|
1037
1037
|
graphUpsert: string;
|
|
1038
|
+
/**
|
|
1039
|
+
* The internal `agents:agentHistory` query the loop dispatches for a compacting
|
|
1040
|
+
* turn: the stored running summary plus only the messages it does not yet cover.
|
|
1041
|
+
*/
|
|
1042
|
+
history: string;
|
|
1038
1043
|
listMessages: string;
|
|
1039
1044
|
patchThread: string;
|
|
1040
1045
|
/**
|
|
@@ -1035,6 +1035,11 @@ interface AgentFunctionPaths {
|
|
|
1035
1035
|
graphTraverse: string;
|
|
1036
1036
|
/** The internal `agents:agentGraphUpsert` mutation the loop dispatches on run-end graph extraction. */
|
|
1037
1037
|
graphUpsert: string;
|
|
1038
|
+
/**
|
|
1039
|
+
* The internal `agents:agentHistory` query the loop dispatches for a compacting
|
|
1040
|
+
* turn: the stored running summary plus only the messages it does not yet cover.
|
|
1041
|
+
*/
|
|
1042
|
+
history: string;
|
|
1038
1043
|
listMessages: string;
|
|
1039
1044
|
patchThread: string;
|
|
1040
1045
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as z}from"./agent-loop-
|
|
1
|
+
import{c as z}from"./agent-loop-BD9gwYAm.mjs";import{buildModelMessages as G}from"./buildModelMessages-Y4tGo1T9.mjs";import{toFunctionReference as A}from"./AGENT_MODULE-B6FqQC80.mjs";const ot=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},P=t=>{const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.codePointAt(r)??0;return n},C=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),n=e+"=".repeat((4-e.length%4)%4);return P(n)},D=new TextDecoder;new TextEncoder;const N="=",Q=t=>{if(t)try{const e=t[0]==="{"?t:D.decode(C(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},ct=t=>{if(t){if(!t.startsWith(N))return t;try{return D.decode(C(t.slice(N.length)))}catch{return}}},dt=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},ut=t=>typeof t=="number"&&Date.now()>=t,yt=t=>{try{t.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},message:"authentication token expired",type:"error"})),t.close?.(4001,"token_expired")}catch{}},Y=16e3,Z=1,tt=16,M=/[.!?]\s/u,et=/\s/u,nt=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{e.releaseLock()}return}yield*t},ft=(t,e=Y,n=Z,r=tt)=>{const i=n*r/8,l=e*i,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(p,b)=>{for(let d=0;d<b.length;d+=1)s.setUint8(p+d,b.codePointAt(d)??0)};u(0,"RIFF"),s.setUint32(4,36+t.byteLength,!0),u(8,"WAVE"),u(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,e,!0),s.setUint32(28,l,!0),s.setUint16(32,i,!0),s.setUint16(34,r,!0),u(36,"data"),s.setUint32(40,t.byteLength,!0);const a=new Uint8Array(m);return a.set(t,44),a},rt=t=>{const e=[];let n=t,r=M.exec(n);for(;r;){let i=r.index+1;for(;i<n.length&&et.test(n[i]??"");)i+=1;const l=n.slice(0,i).trim();l.length>0&&e.push(l),n=n.slice(i),r=M.exec(n)}return{rest:n,sentences:e}},lt=async t=>{const{agent:e,compact:n,connectionId:r,env:i,exportName:l,owner:m,paths:s,pcm:u,run:a,send:p,sendAudio:b,signal:d,streamGenerate:H,synthesize:L,text:B,threadKey:o,transcribe:F,turn:U,waitForDrain:O}=t,h=()=>d.aborted,v=A(s.appendMessage),$=A(s.ensureThread),K=A(s.listMessages),x=A(s.patchThread);await a($,{agent:l,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const y=(B??(u?await F(u):"")).trim();if(y.length===0)return await a(x,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};p({text:y,type:"user_transcript"}),await a(v,{content:y,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await a(x,{key:o,status:"running"});const _=typeof e.instructions=="function"?e.instructions({env:i,input:y,threadKey:o}):e.instructions,j=await a(K,{key:o}),{history:W,summary:I}=await z({agent:e,compact:n,env:i},j),V=G({history:W,..._===void 0?{}:{instructions:_},...I===void 0?{}:{summary:I}});let g="",E="",k=Promise.resolve();const X=async c=>{if(h()||c.length===0)return;let w=!1;try{for await(const f of nt(await L(c,d))){if(h()||(await O?.(),h()))break;b(f),w=!0}}catch(f){p({message:f instanceof Error?f.message:String(f),type:"error"})}w&&(E=E.length>0?`${E} ${c}`:c)},R=c=>{k=k.then(async()=>X(c))},J=await H({messages:V,signal:d},c=>{if(h())return;p({text:c,type:"assistant_delta"}),g+=c;const{rest:w,sentences:f}=rt(g);g=w;for(const q of f)R(q)});!h()&&g.trim().length>0&&R(g.trim()),g="",await k;const S=h(),T=S?E:J.text;return await a(v,{content:T,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await a(x,{key:o,status:"idle"}),p(S?{type:"interrupted"}:{text:T,type:"assistant_done"}),{assistantText:T,interrupted:S,userText:y}}catch(y){throw await a(x,{key:o,status:"idle"}),y}},pt=t=>Q(t),ht=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},gt=t=>{if(t instanceof Uint8Array||t instanceof ReadableStream)return t;if(t instanceof Response&&t.body)return t.body;if(typeof t=="object"&&t!==null&&"audio"in t){const{audio:e}=t;if(typeof e=="string")return P(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{dt as a,yt as b,ft as c,ct as d,ht as e,gt as f,nt as g,ut as i,pt as p,lt as r,ot as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{jsonSchema as c}from"@ai-sdk/provider-utils";import{LunoraError as h}from"@lunora/errors";import{r as u}from"./agent-ai-CxEYOyOu.mjs";const l=5,d="Search the web for current information. Returns up to a handful of results, each with a url, a title and (when the provider has one) a description. Use it for facts that may have changed after your training data, then cite the urls you relied on.",m=c({properties:{query:{description:"The search query, 1–1024 characters.",maxLength:1024,minLength:1,type:"string"}},required:["query"],type:"object"}),E=new Set(["BAD_REQUEST","INTERNAL","NOT_IMPLEMENTED"]),T=(t={})=>{const{description:a=d,limit:o=l,...n}=t;return{description:a,execute:async(s,i)=>{const r=u(i.env);if(!r)return"Web search is unavailable: this Worker has no `AI` binding. Answer from what you already know, and say that you could not search.";try{return(await r.websearch(s.query,{...n,limit:o})).items}catch(e){if(e instanceof h&&E.has(e.code))return`Web search failed: ${e.message}`;throw e}},inputSchema:m,isLunoraAgentTool:!0}};export{T as webSearchTool};
|
package/dist/reply.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Mailer } from '@lunora/mail';
|
|
2
2
|
import { InboundEmail } from '@lunora/mail/inbound';
|
|
3
|
-
import { a as AgentReplyRef } from "./packem_shared/types.d-
|
|
3
|
+
import { a as AgentReplyRef } from "./packem_shared/types.d-C4vYEYW6.mjs";
|
|
4
4
|
import 'ai';
|
|
5
5
|
/** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
|
|
6
6
|
type EmailReplyRef = Extract<AgentReplyRef, {
|
package/dist/reply.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Mailer } from '@lunora/mail';
|
|
2
2
|
import { InboundEmail } from '@lunora/mail/inbound';
|
|
3
|
-
import { a as AgentReplyRef } from "./packem_shared/types.d-
|
|
3
|
+
import { a as AgentReplyRef } from "./packem_shared/types.d-C4vYEYW6.js";
|
|
4
4
|
import 'ai';
|
|
5
5
|
/** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
|
|
6
6
|
type EmailReplyRef = Extract<AgentReplyRef, {
|
package/dist/sandbox.d.mts
CHANGED
package/dist/sandbox.d.ts
CHANGED
package/dist/sandbox.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{jsonSchema as a}from"@ai-sdk/provider-utils";import{LunoraError as s}from"@lunora/errors";import{toFunctionReference as T,SANDBOX_INVOKE_PATH as m}from"./packem_shared/AGENT_MODULE-B6FqQC80.mjs";import{S as g,a as c}from"./packem_shared/sandbox-budgets-DDvj4Orr.mjs";import{jsCodeTool as j}from"./packem_shared/jsCodeTool-CIlCK1bG.mjs";const i=T(m),f=e=>{if(e.op==="pdf")return"pdf";if(e.op==="screenshot")return e.type==="jpeg"?"jpeg":"png"},E=new Set(["bucket","path","root"]),S='Drive a headless browser: screenshot a page, render it to PDF, read its HTML content, or scrape it. Set `op` to "screenshot" | "pdf" | "content" | "scrape" and pass the target `url`.',y='Talk to a sandboxed container: `fetch` an HTTP path on it, or `exec` a command inside it. Set `op` to "fetch" (with `path`) or "exec" (with `command`).',A='Read and write files in a persistent sandbox filesystem. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',w='Read and write files on the sandboxed container\'s own disk — the same disk its commands run against. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',_="/workspace",p=e=>e.op==="write"||e.op==="rm",d=a({properties:{content:{description:"write: the file contents.",type:"string"},op:{description:"The filesystem operation to run.",enum:["ls","read","write","rm","stat"],type:"string"},path:{description:"The file or directory path, relative to the sandbox root.",type:"string"}},required:["op"],type:"object"}),N=a({properties:{fullPage:{description:"screenshot: capture the full scrollable page rather than just the viewport.",type:"boolean"},op:{description:"The browser operation to run.",enum:["screenshot","scrape","pdf","content"],type:"string"},selector:{description:"scrape: optional CSS selector hint to narrow the extraction.",type:"string"},type:{description:"screenshot: image encoding (default png).",enum:["png","jpeg"],type:"string"},url:{description:"The URL to operate on.",type:"string"}},required:["op","url"],type:"object"}),O=new Set(["DELETE","PATCH","POST","PUT"]),b=e=>e.op==="exec"||O.has((e.method??"GET").toUpperCase()),R=a({properties:{args:{description:"exec: command arguments.",items:{type:"string"},type:"array"},body:{description:"fetch: request body.",type:"string"},command:{description:"exec: the command to run.",type:"string"},method:{description:"fetch: HTTP method (default GET).",type:"string"},op:{description:"The container operation to run.",enum:["fetch","exec"],type:"string"},path:{description:"fetch: request path on the container (e.g. /health).",type:"string"}},required:["op"],type:"object"}),L=(e={})=>{const t=e.bucket!==void 0&&e.bucket.length>0?e.bucket:void 0;return{description:e.description??S,execute:async(o,n)=>{const r=f(o);if(r!==void 0&&t===void 0)return`Cannot run a "${o.op}": this browser tool has no \`bucket\` configured, so the render has nowhere to go. Use "content" or "scrape" for page text, or ask the operator to pass \`browserTool({ bucket })\`.`;const h=r===void 0?{}:{bucket:t,path:`${n.threadKey}/${n.toolCallId}.${r}`,...e.root===void 0?{}:{root:e.root}},u=Object.fromEntries(Object.entries(o).filter(([l])=>!E.has(l)));return await n.run(i,{...u,...h,kind:"browser"},{timeoutMs:g})},inputSchema:N,isLunoraAgentTool:!0,...e.needsApproval===void 0?{}:{needsApproval:e.needsApproval}}},k=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.needsApproval??b;return{description:t.description??y,execute:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"container",name:e},{timeoutMs:c}),inputSchema:R,isLunoraAgentTool:!0,needsApproval:o}},x=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: fsTool requires an R2 `bucket` binding name (the r2_bucket declared in wrangler.jsonc)");return{description:t.description??A,execute:(o,n)=>{const r=typeof t.root=="function"?t.root(n):t.root??"";return n.run(i,{...o,bucket:e,kind:"fs",root:r})},inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}},F=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerFsTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.root??_;if(!o.startsWith("/"))throw new s("INTERNAL",`@lunora/agent: containerFsTool \`root\` must be an absolute path inside the container (got "${o}")`);return{description:t.description??w,execute:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"containerFs",name:e,root:o},{timeoutMs:c}),inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}};export{L as browserTool,F as containerFsTool,k as containerTool,x as fsTool,j as jsCodeTool};
|
package/dist/skill-markdown.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/agent",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.207",
|
|
4
4
|
"description": "Durable AI agents for Lunora: defineAgent compiles a replay-safe tool-loop onto Cloudflare Workflows, with DO SQLite threads and live message subscriptions",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|
|
@@ -84,10 +84,11 @@
|
|
|
84
84
|
"access": "public"
|
|
85
85
|
},
|
|
86
86
|
"dependencies": {
|
|
87
|
-
"@
|
|
87
|
+
"@ai-sdk/provider-utils": "5.0.53",
|
|
88
|
+
"@lunora/ai": "1.0.0-alpha.126",
|
|
88
89
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
89
90
|
"@lunora/mail": "1.0.0-alpha.107",
|
|
90
|
-
"@lunora/server": "1.0.0-alpha.
|
|
91
|
+
"@lunora/server": "1.0.0-alpha.201",
|
|
91
92
|
"@lunora/values": "1.0.0-alpha.65",
|
|
92
93
|
"@lunora/workflow": "1.0.0-alpha.77",
|
|
93
94
|
"@modelcontextprotocol/sdk": "^1.32.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e="agents",a="sandbox",n=`${a}:invoke`,s={appendMessage:`${e}:agentAppendMessage`,completeRun:`${e}:agentCompleteRun`,deleteMessage:`${e}:agentDeleteMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`},r=t=>typeof t=="string"?{__lunoraRef:t}:t;export{e as AGENT_MODULE,s as DEFAULT_AGENT_FUNCTION_PATHS,n as SANDBOX_INVOKE_PATH,a as SANDBOX_MODULE,r as toFunctionReference};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{f as ot}from"./DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs";import{r as W}from"./workflow-binding-Dm9hBzx_.mjs";import{c as b,d as nt}from"./component-shared-G8ngerkU.mjs";import{resolveAgentModel as at}from"./createAgentGenerate-EEFNvpS5.mjs";import{buildModelMessages as H}from"./buildModelMessages-Y4tGo1T9.mjs";import{agentClassName as z}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as st}from"./positive-integer-ztHqqpBk.mjs";import{combineTelemetry as rt}from"./combineTelemetry-DgE9W9G8.mjs";import{c as G}from"./tool-output-Cmk3JWMG.mjs";const it=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",F=e=>e.memorySources?e.memorySources:e.memory&&it(e.memory)?[{key:"default",...e.memory}]:[],ct=e=>F(e).find(t=>t.kind==="graph"),dt=e=>F(e).find(t=>t.kind==="episodic"),S=(e,t)=>t==="default"?e:`${e}:${t}`,ut=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const n=Array.isArray(t)?t:[t];return n.length===0?void 0:rt(...n)},lt=async(e,t,n)=>{const o=ut(e);if(o===void 0)return n();const a={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:a,toolContext:void 0},c=Date.now();await o.onToolExecutionStart?.(s);let d;const u=()=>(d??=n(),d);try{if(o.executeTool===void 0)await u();else try{await o.executeTool({...s,execute:u,toolCallId:t.id})}catch{}const i=await u();return await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,input:t.input,output:i,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),i}catch(i){throw await o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-c,toolOutput:{dynamic:!0,error:i,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),i}},pt=8,mt=e=>st(e)?e:0,V=e=>e===void 0?"null":JSON.stringify(e),yt=async(e,t,n)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...n===void 0?{}:{usage:n}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},vt=e=>e===void 0?[]:[e].flat(),ft=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),ht=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const n={};for(const o of["inputTokens","outputTokens","totalTokens"])(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},gt=async(e,t,n,o,a)=>{const{needsApproval:s}=e;return s===void 0||s===!1?!1:s===!0?!0:n.do(o,async()=>s(t,a))},wt="WorkflowTimeoutError",Tt=e=>e instanceof Error&&e.name===wt,L=4320*60*1e3,xt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Ct=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,St=e=>{if(e===void 0)return L;if(typeof e=="number")return Math.min(e,b);const t=Ct.exec(e);return t===null?L:Math.min(Number(t[1])*xt[t[2]],b)},kt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:c,step:d}=e;await c({content:`Awaiting approval to run tool "${t.name}".`,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({status:"awaiting_input"});const u=await d.waitForEvent(`approval:${t.id}`,{timeout:St(n.approvalTimeout),type:`agent-approval:${t.id}`}).then(i=>({decision:i.payload.decision,...i.payload.note===void 0?{}:{note:i.payload.note}})).catch(i=>{if(!Tt(i))throw i;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),u},A="lunoraToolOutcome",Et=e=>typeof e=="object"&&e!==null&&A in e?e[A]:{ok:e},Mt=async(e,t)=>{const{agent:n,depth:o,env:a,exports:s,getState:c,instanceId:d,onTokenDelta:u,owner:i,persist:m,run:r,setState:l,step:p,threadKey:f,tools:E}=e,h=`tool:${t.name}:${t.id}`,v=E[t.name],T=`${d}:tool:${t.id}`;if(!v){await m({content:`Error: unknown tool "${t.name}"`,messageKey:T,role:"tool",stepName:h,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await m({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:T,role:"tool",stepName:h,toolCallId:t.id,toolName:t.name});return}const O={depth:o,env:a,exports:s,getState:c,idempotencyKey:h,owner:i,reportProgress:w=>{u?.({data:w,kind:"progress",threadKey:f,toolCallId:t.id})},run:r,setState:l,step:p,threadKey:f,toolCallId:t.id},_={depth:o,env:a,getState:c,idempotencyKey:h,run:r,threadKey:f,toolCallId:t.id},U=`tool:approval-gate:${t.id}`;let x;if(await gt(v,t.input,p,U,_)){const{decision:w,note:k}=await kt(e,t);if(w==="reject"){const D=k===void 0?"":` Reason: ${k}`;await m({content:`Tool "${t.name}" was rejected by the user and not run.${D}`,messageKey:T,role:"tool",status:"rejected",stepName:h,toolCallId:t.id,toolName:t.name});return}x="approved"}const M=Et(await p.do(h,async()=>{try{const w=()=>Promise.resolve(v.execute(t.input,O)),k=await lt(n.telemetry,{id:t.id,input:t.input,name:t.name},w);return{[A]:{ok:k}}}catch(w){if(ot(w))return{[A]:{failed:w.message}};throw w}}));if("failed"in M){await m({content:G(`Error: tool "${t.name}" failed and will not be retried. ${M.failed}`),messageKey:T,role:"tool",stepName:h,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name});return}const $=M.ok;await m({content:G(typeof $=="string"?$:V($)),messageKey:T,role:"tool",stepName:h,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},$t=(e,t,n)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:at(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},Rt=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const n=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=n)return;let o=e.length-n;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},It=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=Rt(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const c=await o({env:a,messages:H({history:s.older}),model:n.compaction?.model??n.model});return c.length>0?{history:s.recent,summary:c}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Kt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:c,listMessages:d,memoryContext:u,onTokenDelta:i,run:m,step:r,streamGenerate:l,threadKey:p}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const f=await m(d,{key:p}),{history:E,summary:h}=await It(e,f);let v={activeTools:o.activeTools,messages:H({history:E,instructions:c,memoryContext:u,summary:h}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(v=$t(v,await o.prepareStep({messages:v.messages,stepNumber:t,steps:n}),a));const T={messages:v.messages,...v.activeTools===void 0?{}:{activeTools:v.activeTools},...v.model===void 0?{}:{model:v.model},...v.toolChoice===void 0?{}:{toolChoice:v.toolChoice}};return l&&i?l(T,R=>{i({text:R,threadKey:p,turn:t})}):s(T)})},B=async(e,t)=>{const{agent:n,step:o}=e;n.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await n.onStepFinish?.(t),!0))},Nt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),j=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},At=e=>nt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Ot=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:s}=e,c=S("memory:retrieve",e.key),d=await n.do(c,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return j(d)},_t=async(e,t,n,o,a,s)=>{if(n===void 0)return;const c=S("memory:traverse",e.key),d=await a.do(c,async()=>s(o,{owner:n,query:t,...At(e.graph)}));return j(d)},Ut=async(e,t,n,o,a)=>{if(t===void 0)return;const s=S("memory:recall",e.key),c={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},d=await o.do(s,async()=>a(n,c));return j(d)},Dt=async(e,t)=>e.kind==="episodic"?Ut(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?_t(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Ot(e,t.input,t.step,t.run),Pt=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},Ft=async(e,t,n,o,a,s)=>{const c=Pt(F(e));if(c.length===0)return;const d=g(o.graphTraverse),u=g(o.episodeRecall),i=[];for(const m of c){const r=await Dt(m,{episodeRecall:u,graphTraverse:d,input:t,owner:n,run:s,step:a});r!==void 0&&i.push(r)}return i.length>0?i.join(`
|
|
2
|
-
|
|
3
|
-
`):void 0},jt=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:c,owner:d,paths:u,run:i,step:m}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const r=ct(t);if(r!==void 0)try{const l={assistantText:a,env:n,model:r.graph?.extractionModel??t.model,userInput:s},p=await m.do(S("memory:extract",r.key),async()=>o(l));await i(g(u.graphUpsert),{...p,messageKey:`${c}:${S("extract",r.key)}`,owner:d})}catch{}},qt=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:c,owner:d,paths:u,run:i,step:m,threadKey:r}=e;if(o===void 0||d===void 0||a===void 0||a.length===0)return;const l=dt(t);if(l!==void 0)try{const p={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:f}=await m.do(S("memory:episode",l.key),async()=>o(p));await i(g(u.episodeUpsert),{messageKey:`${c}:${S("episode",l.key)}`,owner:d,summary:f,threadKey:r})}catch{}},bt=async(e,t,n)=>{const o=W(e.env,e.exports,z(t),["get"]);if(o!==void 0)try{await(await o.get(n)).terminate()}catch{}},Gt="12 hours",Lt=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:Gt,type:`agent-dequeue:${t}:${n}`})},Bt=async(e,t,n)=>{const o=W(e.env,e.exports,z(e.exportName),["get"]);if(o===void 0)return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},Wt=async(e,t,n)=>{const{onReply:o}=e,{replyRef:a}=t.params;if(!(o===void 0||a===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:a,result:n,threadKey:t.params.threadKey}),a.channel))}catch{}},Ht=async(e,t,n,o,a)=>{const{instanceId:s,persist:c}=e,d=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const u=n.output!==void 0&&n.text.length===0?V(n.output):n.text;return await c({content:u,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await B(e,{text:n.text,toolCalls:[],turn:t,...d}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await c({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const u of n.toolCalls)await Mt(e,u);if(await B(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...d}),o.push(Nt(n)),a.length>0&&await ft(a,o))return"stopCondition"},zt=async(e,t,n,o)=>{const a=[];let s,c=!1,d=0;for(let u=0;u<t;u+=1){const i=await Kt(e,u,a);o.value=ht(o.value,i.usage),d=u+1;const m=await Ht(e,u,i,a,n);if(m==="stopCondition"){c=!0;break}if(m!==void 0){s=m.final;break}}return{final:s,stoppedByCondition:c,turnsRun:d}},ae=async e=>{const{agent:t,compact:n,env:o,exportName:a,exports:s,extractEpisode:c,extractGraph:d,generate:u,instanceId:i,onTokenDelta:m,params:r,paths:l,run:p,step:f,streamGenerate:E}=e,h=t.maxTurns??pt,v=vt(t.stopWhen),T=g(l.appendMessage),R=g(l.completeRun),O=g(l.ensureThread),_=g(l.listMessages),U=g(l.deleteMessage),x=g(l.patchThread),M=g(l.setState),$=g(l.state),w=async y=>{await p(T,{threadKey:r.threadKey,...y})},k=async y=>{await p(x,{key:r.threadKey,...y})},D=async y=>{await p(U,{messageKey:y,threadKey:r.threadKey})},X=async()=>{await w({content:r.input,messageKey:`${i}:user`,role:"user"})},q={dispatched:!1},I=async y=>{q.dispatched=!0;const N=await p(R,{instanceId:i,key:r.threadKey,...y});N?.dequeued!==void 0&&await Bt({env:o,exportName:a,exports:s,step:f},r.threadKey,N.dequeued)},J=async()=>await p($,{key:r.threadKey}),Q=async y=>{await p(M,{key:r.threadKey,state:y})},P=await p(O,{agent:a,instanceId:i,key:r.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...r.owner===void 0?{}:{owner:r.owner},...r.title===void 0?{}:{title:r.title}});P?.outcome==="replaced"&&await bt({env:o,exports:s},a,P.priorInstanceId);const Y=await Ft(t,r.input,r.owner,l,f,p),Z=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,tt={agent:t,compact:n,depth:mt(r.depth),env:o,exports:s,generate:u,getState:J,instanceId:i,instructions:Z,listMessages:_,memoryContext:Y,onTokenDelta:m,owner:r.owner,deleteMessage:D,patchThread:k,persist:w,run:p,setState:Q,step:f,streamGenerate:E,threadKey:r.threadKey,tools:t.tools??{}},K={value:void 0};try{P?.outcome==="queued"&&await Lt(f,r.threadKey,i),await X();const{final:y,stoppedByCondition:N,turnsRun:et}=await zt(tt,h,v,K),C=K.value===void 0?{}:{usage:K.value};return await jt({agent:t,env:o,extractGraph:d,finalText:y?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:p,step:f}),await qt({agent:t,env:o,extractEpisode:c,finalText:y?.text,input:r.input,instanceId:i,owner:r.owner,paths:l,run:p,step:f,threadKey:r.threadKey}),y?(await Wt(t,{env:o,params:r,step:f},{...y,...C}),await I({status:"idle",...C}),{...y,...C}):N?(await I({status:"idle",...C}),{stopped:"stopCondition",turns:et,...C}):(await I({error:`agent stopped: maxTurns (${String(h)}) reached`,status:"error",...C}),{stopped:"maxTurns",turns:h,...C})}catch(y){throw q.dispatched||await yt(I,y,K.value),y}};export{St as a,It as c,it as i,ae as r,Rt as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as I}from"@lunora/workflow";import{jsonSchema as L}from"ai";import{f as S}from"./fnv1a-BNN96GYb.mjs";import{r as b}from"./workflow-binding-Dm9hBzx_.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as $,DEFAULT_AGENT_FUNCTION_PATHS as P}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),x=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",k=t=>t!==null&&typeof t=="object"?t.output:void 0,C=async t=>{await new Promise(e=>{setTimeout(e,t)})},D=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=R(a);if(_.has(s))return{output:k(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},U=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},j=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},V=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??x,o=t.pollIntervalMs??M,a=t.wait??C,s=$(P.listMessages),T=async(y,r)=>{const p=(h(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=b(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,g=`sub-${e}-${S(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:g,params:A});l=await i.get(d.id)}catch(d){if(!I(d))throw d;l=await i.get(g)}const{output:v,status:u}=await D(l,m,o,a);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(U(v)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const E=await r.run(s,{key:f});return j(E)};return{description:t.description,execute:T,inputSchema:L({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{V as agentAsTool};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";import{jsonSchema as h,asSchema as v}from"ai";import{i as A}from"./positive-integer-ztHqqpBk.mjs";import{M as g,c as w}from"./tool-output-Cmk3JWMG.mjs";const $=16,T=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=g?e:w(o)},S=(e,o)=>{let t=e;for(const n of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,n))return;t=t[n]}return t},l=(e,o)=>{if(Array.isArray(e))return e.map(r=>l(r,o));if(e===null||typeof e!="object")return e;const t=e;if(typeof t.$from=="string"){const r=t.$from;if(!Object.hasOwn(o,r))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?S(o[r],t.$path):o[r]}const n={};for(const[r,i]of Object.entries(t))r!=="__proto__"&&(n[r]=l(i,o));return n},b=async(e,o,t)=>{const{validate:n}=v(o.inputSchema);if(n===void 0)return t;const r=await n(t);if(r.success)return r.value;throw new a("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${r.error.message}`)},O=async(e,o,t,n)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>n)throw new a("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(n)}. Split it across several code calls.`);const i={},p=[],d=new Set;for(const s of r){if(d.has(s.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${s.id}" — each step id must be unique (later steps reference an output by id via $from)`);d.add(s.id)}for(const s of r){const c=Object.hasOwn(o,s.tool)?o[s.tool]:void 0;if(!c)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${s.tool}" (available: ${Object.keys(o).join(", ")})`);const m=await b(s,c,l(s.input??{},i)),u={...t,idempotencyKey:`${t.idempotencyKey}:${s.id}`,toolCallId:`${t.toolCallId}:${s.id}`},y=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,y);i[s.id]=f,p.push({id:s.id,output:T(f)})}return{final:p.at(-1)?.output,results:p}},E=e=>`Compose MULTIPLE tool calls in one turn as a script, instead of one call per turn. Provide \`steps\`: an ordered array of \`{ id, tool, input }\`. A later step's \`input\` may reference an earlier step's output with \`{ "$from": "<stepId>", "$path": "optional.dot.path" }\`. Available tools: ${Object.entries(e).map(([o,t])=>`"${o}" — ${t.description}`).join("; ")}.`,_=h({properties:{steps:{description:"Ordered tool calls; a later input may reference an earlier output via { $from, $path }.",items:{additionalProperties:!1,properties:{id:{description:"A name later steps reference this output by.",type:"string"},input:{additionalProperties:!0,description:"The tool input (may embed $from refs).",type:"object"},tool:{description:"The tool to call.",type:"string"}},required:["id","tool"],type:"object"},type:"array"}},required:["steps"],type:"object"}),P=(e,o={})=>{const t=e;if(!t||typeof t!="object"||Object.keys(t).length===0)throw new a("INTERNAL","@lunora/agent: codeTool requires a non-empty map of tools to compose");for(const[r,i]of Object.entries(t))if(i.needsApproval!==void 0&&i.needsApproval!==!1)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it has a \`needsApproval\` gate a code-mode script can't pause for. Expose it as a normal top-level tool, or gate the whole script via codeTool's \`needsApproval\`.`);if(o.maxSteps!==void 0&&!A(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const n=o.maxSteps??$;return{description:o.description??E(e),execute:(r,i)=>O(r,e,i,n),inputSchema:_,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{P as codeTool,l as resolveReferences,O as runToolScript};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{jsonSchema as u}from"ai";import{toFunctionReference as d}from"./AGENT_MODULE-M4D1EejI.mjs";const h=240,m=50,y=(t,s)=>t.length<=s?t:`${t.slice(0,s)}…`,f=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(m,Math.max(1,Math.trunc(t)))},g=(t,s)=>{const r=t??{},i=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:y(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},S=u({additionalProperties:!1,properties:{query:{description:"Natural-language search query.",type:"string"},topK:{description:"Maximum number of hits to return.",type:"number"}},required:["query"],type:"object"}),A=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),b=(t,s,r)=>{const i=d(s),e=Math.max(1,t.snippetChars??h),o=t.topK;return{description:`Search long-term memory for passages relevant to a query. Returns ranked { id, sourceId, score, snippet } hits — call again with a refined query to dig deeper.${r===void 0?"":` Use \`${r}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,p)=>{const a=f(n.topK)??o,l=await p.run(i,{query:n.query,...a===void 0?{}:{topK:a}});return g(l,e)},inputSchema:S,isLunoraAgentTool:!0}},T=t=>{const s=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,i)=>i.run(s,{id:r.id}),inputSchema:A,isLunoraAgentTool:!0}},k=(t,s)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of s)e.knowledge&&r.push({key:e.name,...e.knowledge});const i={};for(const e of r){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,c=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=b(e,e.source,n?c:void 0),n&&(i[c]=T(e.read))}return i};export{k as collectAgenticMemoryTools,g as toSearchResults};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{LunoraError as w}from"@lunora/errors";import{jsonSchema as T,generateText as d,Output as f,streamText as x,tool as C}from"ai";import{r as A}from"./agent-ai-CxEYOyOu.mjs";const g=t=>{if(!t)return;const e={};for(const o of["inputTokens","outputTokens","totalTokens"]){const r=t[o];r!==void 0&&(e[o]=r)}return Object.keys(e).length>0?e:void 0},y=t=>t.map(e=>{const o={id:e.toolCallId,input:e.input,name:e.toolName};return e.invalid!==!0?o:{...o,invalid:e.error instanceof Error?e.error.message:String(e.error)}}),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=A(e);if(!o)throw new w("INTERNAL",`@lunora/agent: the agent model "${t}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return o.model(t)}return t},b=(t,e)=>{const o=m(t.model,e),r={};for(const[a,i]of Object.entries(t.tools??{}))r[a]=C({description:i.description,inputSchema:i.inputSchema});const n=t.output===void 0?void 0:f.object({schema:t.output}),s={...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{maxOutputTokens:t.maxOutputTokens},...t.telemetry===void 0?{}:{telemetry:t.telemetry},...t.repairToolCall===void 0?{}:{experimental_repairToolCall:t.repairToolCall}};return{defaultModel:o,output:n,staticSettings:s,tools:r}},v=(t,{activeTools:e,messages:o,model:r,signal:n,toolChoice:s})=>{const{defaultModel:a,output:i,staticSettings:h,tools:c}=t,l=e===void 0?c:Object.fromEntries(Object.entries(c).filter(([p])=>e.includes(p)));return{messages:o,model:r??a,...h,...Object.keys(l).length>0?{tools:l}:{},...s===void 0?{}:{toolChoice:s},...i===void 0?{}:{output:i},...n===void 0?{}:{abortSignal:n}}},q=(t,e)=>{const o=b(t,e);return async r=>{const n=await d(v(o,r)),s=g(n.usage);return{text:n.text,toolCalls:y(n.toolCalls),...s===void 0?{}:{usage:s},...o.output===void 0?{}:{output:n.output}}}},I=(t,e)=>{const o=b(t,e);return async(r,n)=>{const s=x(v(o,r));let a="";try{for await(const u of s.textStream)a+=u,n(u)}catch(u){if(r.signal?.aborted)return{text:a,toolCalls:[]};throw u}const[i,h,c,l]=await Promise.all([s.text,s.toolCalls,s.usage,o.output===void 0?Promise.resolve(void 0):s.output]),p=g(c);return{text:i,toolCalls:y(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:l}}}},k=T({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),j=(t,e)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
2
|
-
`),M=()=>async({assistantText:t,env:e,model:o,userInput:r})=>{const{output:n}=await d({model:m(o,e),output:f.object({schema:k}),prompt:j(r,t)});return n},E=(t,e)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
3
|
-
`),_=()=>async({assistantText:t,env:e,model:o,userInput:r})=>{const{text:n}=await d({model:m(o,e),prompt:E(r,t)});return{summary:n.trim()}},O="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",R=()=>async({env:t,messages:e,model:o})=>{const{text:r}=await d({messages:e,model:m(o,t),system:O});return r.trim()};export{q as createAgentGenerate,R as createCompact,_ as createEpisodeExtract,M as createGraphExtract,I as createStreamGenerate,m as resolveAgentModel};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{jsonSchema as h}from"ai";import{r as u}from"./agent-ai-CxEYOyOu.mjs";const l=5,d="Search the web for current information. Returns up to a handful of results, each with a url, a title and (when the provider has one) a description. Use it for facts that may have changed after your training data, then cite the urls you relied on.",m=h({properties:{query:{description:"The search query, 1–1024 characters.",maxLength:1024,minLength:1,type:"string"}},required:["query"],type:"object"}),E=new Set(["BAD_REQUEST","INTERNAL","NOT_IMPLEMENTED"]),T=(t={})=>{const{description:a=d,limit:o=l,...n}=t;return{description:a,execute:async(s,i)=>{const r=u(i.env);if(!r)return"Web search is unavailable: this Worker has no `AI` binding. Answer from what you already know, and say that you could not search.";try{return(await r.websearch(s.query,{...n,limit:o})).items}catch(e){if(e instanceof c&&E.has(e.code))return`Web search failed: ${e.message}`;throw e}},inputSchema:m,isLunoraAgentTool:!0}};export{T as webSearchTool};
|