@lunora/agent 1.0.0-alpha.86 → 1.0.0-alpha.88
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.mjs +1 -1
- package/dist/component.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/VoiceSessionDO-DhmYu8wo.mjs +1 -0
- package/dist/packem_shared/agent-loop-Cotwgugs.mjs +3 -0
- package/dist/packem_shared/agentAsTool-CgZb6ycK.mjs +1 -0
- package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
- package/dist/packem_shared/compileAgentWorkflow-8pHFPjec.mjs +1 -0
- package/dist/packem_shared/{component-shared-IZozysYq.mjs → component-shared-G8ngerkU.mjs} +1 -1
- package/dist/packem_shared/{createAgentContext-CpXkr16T.mjs → createAgentContext-Ds2VaveB.mjs} +1 -1
- package/dist/packem_shared/createDispatchRunner-BrbbxS2q-DBBqImoR.mjs +1 -0
- package/dist/packem_shared/defineAgent-DM0fNEY6.mjs +3 -0
- package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
- package/dist/packem_shared/{normalizeEntityName-Ce0X6Afj.mjs → normalizeEntityName-k3fjicAG.mjs} +1 -1
- package/dist/packem_shared/runAgentLoop-Dmq-FWJk.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-DGD90HuL.mjs +1 -0
- package/dist/packem_shared/voice-turn-B9dc3mvG.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/VoiceSessionDO-Cu-TK8zq.mjs +0 -1
- package/dist/packem_shared/agentAsTool-DnQ2245q.mjs +0 -1
- package/dist/packem_shared/codeTool-C1tpwXz8.mjs +0 -1
- package/dist/packem_shared/compileAgentWorkflow-Ci5gTX6C.mjs +0 -1
- package/dist/packem_shared/createDispatchRunner-BrbbxS2q-Dbic8l08.mjs +0 -1
- package/dist/packem_shared/defineAgent-DievK_TE.mjs +0 -3
- package/dist/packem_shared/memory-JI0lUu84.mjs +0 -1
- package/dist/packem_shared/runAgentLoop-D7nLAmvV.mjs +0 -3
- package/dist/packem_shared/runVoiceTurn-B6vzVw6L.mjs +0 -1
- package/dist/packem_shared/voice-turn-CVPDDTTC.mjs +0 -1
package/dist/channels.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as d}from"@lunora/errors";import{isDuplicateInstanceError as w}from"@lunora/workflow";import{h as b,B as E}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{f as A}from"./packem_shared/fnv1a-BNN96GYb.mjs";const R=300,k=/[^0-9a-f]/iu,x=new TextEncoder,f=t=>new Uint8Array(x.encode(t)),l=t=>{if(t.length%2!==0||k.test(t))throw new d("BAD_REQUEST","@lunora/agent: malformed hex signature");const e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n+=1)e[n]=Number.parseInt(t.slice(n*2,n*2+2),16);return e},m=async(t,e,n)=>{try{const r=await crypto.subtle.importKey("raw",f(t),{hash:"SHA-256",name:"HMAC"},!1,["verify"]);return await crypto.subtle.verify("HMAC",r,l(n),f(e))}catch{return!1}},N=(t,e,n)=>Number.isFinite(t)&&Math.abs(e-t)<=n,S=async t=>{const{body:e,now:n=Date.now()/1e3,signature:r,signingSecret:s,timestamp:a,tolerance:o=R}=t;return!r||!a||!r.startsWith("v0=")||!N(Number(a),n,o)?!1:m(s,`v0:${a}:${e}`,r.slice(3))},T=async t=>{const{body:e,secret:n,signature:r}=t;return r?.startsWith("sha256=")?m(n,e,r.slice(7)):!1},C=async t=>{const{body:e,publicKey:n,signature:r,timestamp:s}=t;if(!r||!s)return!1;try{const a=await crypto.subtle.importKey("raw",l(n),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},a,l(r),f(s+e))}catch{return!1}},I=t=>{if(t.has("x-slack-signature"))return"slack";if(t.has("x-hub-signature-256"))return"github";if(t.has("x-signature-ed25519"))return"discord"},_=(t,e)=>{if(typeof t=="function")return t(e);const n=e[t];return typeof n=="string"?n:void 0},B=async(t,e,n,r)=>{switch(t){case"discord":return C({body:r,publicKey:e,signature:n.get("x-signature-ed25519")??void 0,timestamp:n.get("x-signature-timestamp")??void 0});case"github":return T({body:r,secret:e,signature:n.get("x-hub-signature-256")??void 0});case"slack":return S({body:r,signature:n.get("x-slack-signature")??void 0,signingSecret:e,timestamp:n.get("x-slack-request-timestamp")??void 0});default:return!1}},H=(t,e)=>{if(t==="discord")try{if(JSON.parse(e).type===1)return Response.json({type:1})}catch{}},u=()=>new Response(void 0,{status:200}),M=(t,e,n)=>{if(t==="github")return e.get("x-github-delivery")??void 0;try{const r=JSON.parse(n),s=t==="slack"?r.event_id:r.id;return typeof s=="string"?s:void 0}catch{return}},D=async(t,e,n,r)=>{if(b(e))throw new d("BAD_REQUEST",`@lunora/agent: inbound channel run params ${E}`);if(r===void 0||r==="")return await t.create({params:e}),u();try{await t.create({id:`${n}-${A(r)}`,params:e})}catch(s){if(w(s))return u();throw s}return u()},J=t=>async(e,n)=>{const r=await e.text(),s=I(e.headers);if(s===void 0)return new Response("Unrecognized webhook",{status:400});const a=t.map(i=>({config:i.agent.onInbound,target:i})).filter(i=>i.config?.channel===s),o={channel:s,headers:e.headers,json:()=>JSON.parse(r),rawBody:r};let g=!1;for(const{config:i,target:y}of a){const h=_(i.secret,n);if(h===void 0||!await B(s,h,e.headers,r))continue;g=!0;const p=H(s,r);if(p)return p;const v=await i.map(o);if(!v)continue;const c=n[y.binding];if(!c||typeof c.create!="function")throw new d("INTERNAL",`@lunora/agent: no Workflow binding "${y.binding}" on env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`);return await D(c,v,s,M(s,e.headers,r))}return g?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{J as dispatchAgentChannel,C as verifyDiscord,T as verifyGithub,S as verifySlack};
|
package/dist/component.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{defineTable as v,initLunora as D,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{a as f,A as k,
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{defineTable as v,initLunora as D,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{a as f,A as k,b as P,d as F}from"./packem_shared/component-shared-G8ngerkU.mjs";import{graphTables as G,graphComponent as H}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{normalizeEntityName as pe}from"./packem_shared/normalizeEntityName-k3fjicAG.mjs";import{sandboxComponent as we}from"./packem_shared/sandboxComponent-BtOkUYpY.mjs";const A="agent_episodes",X=5,Q=20,Y=500,x=200,z=/\s+/gu,V=u=>u===void 0||!Number.isFinite(u)?X:Math.min(Q,Math.max(1,Math.trunc(u))),W={episodes:v({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:J,query:Z}=D.dataModel().create(),ee=()=>{const u=J.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:s,ctx:y})=>{const w=s.summary.replaceAll(z," ").trim().slice(0,Y);if(w.length===0)return{recorded:!1};if(await y.db.query(A).withIndex("byOwnerMessageKey",h=>h.eq("owner",s.owner).eq("messageKey",s.messageKey)).first())return{recorded:!1};await y.db.insert(A,{createdAt:s.createdAt??Date.now(),messageKey:s.messageKey,owner:s.owner,summary:w,...s.threadKey===void 0?{}:{threadKey:s.threadKey}});const m=await y.db.query(A).withIndex("byOwnerCreatedAt",h=>h.eq("owner",s.owner)).order("asc").take(x+1);for(const h of m.slice(0,Math.max(0,m.length-x)))await y.db.delete(h._id);return{recorded:!0}}),o=Z.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:s,ctx:y})=>{const w=await y.db.query(A).withIndex("byOwnerCreatedAt",I=>I.eq("owner",s.owner)).order("desc").take(V(s.limit));return w.length===0?{context:""}:{context:w.toReversed().map(I=>`- ${I.summary}`).join(`
|
|
2
2
|
`)}});return{agentEpisodeRecall:f(o),agentEpisodeUpsert:f(u)}},S="threads",$="messages",M="run_queue",p=`${k}_${S}`,K=`${k}_${$}`,E=`${k}_${M}`,N=5,te=780*60*1e3,ne=j(k,{tables:{[$]:v({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]:v({agent:e.string(),createdAt:e.number(),error:e.optional(e.string()),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]:v({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,...W}}),{mutation:b,query:T}=D.dataModel().create(),ie=async(u,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:y}=o,w=await u.query(E).withIndex("byThreadInstance",h=>h.eq("threadKey",o.key).eq("instanceId",y)).first();if(w)return{outcome:"queued",position:w.position};const I=await u.query(E).withIndex("byThread",h=>h.eq("threadKey",o.key)).collect();if(I.length>=N)throw new g("CONFLICT",`@lunora/agent: thread "${o.key}" run queue is full (depth ${String(N)}) — rejecting instance "${y}"`);const m=(I.at(-1)?.position??-1)+1;return await u.insert(E,{agent:o.agent,enqueuedAt:s,instanceId:y,position:m,threadKey:o.key}),{outcome:"queued",position:m}},ae=async(u,o,s)=>{if(o.policy==="queue")return ie(u,{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 u.patch(o.existingId,{error:void 0,status:"running",updatedAt:s,...o.instanceId===void 0?{}:{instanceId:o.instanceId}}),{outcome:"replaced",priorInstanceId:o.priorInstanceId}},le=()=>{const u=b.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`);const r=i.instanceId,d=typeof i.updatedAt=="number"?i.updatedAt:0,c=i.status==="awaiting_input"?P:te;return!(a-d>c)&&(i.status==="running"||i.status==="awaiting_input")&&r!==void 0&&(t.instanceId===void 0||t.instanceId!==r)?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:void 0,status:"running",updatedAt:a,...t.instanceId===void 0?{}:{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,...F({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),o=b.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(K).withIndex("byMessageKey",c=>c.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const i=await n.db.query(p).withIndex("byKey",c=>c.eq("key",t.threadKey)).first();if(!i)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const r=i.messageCount,d=Date.now();return await n.db.insert(K,{content:t.content,createdAt:d,messageKey:t.messageKey,role:t.role,seq:r,threadKey:t.threadKey,...t.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:d}),{seq:r}}),s=b.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(K).withIndex("byMessageKey",i=>i.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(a._id)}),y=b.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",d=>d.eq("key",i)).first():a!==void 0&&(r=await n.db.query(p).withIndex("byInstance",d=>d.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}})}),w=b.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",l=>l.eq("key",t.key)).first();if(i?.instanceId!==t.instanceId){const l=await n.db.query(E).withIndex("byThreadInstance",q=>q.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return l&&await n.db.delete(l._id),{}}const d=(await n.db.query(E).withIndex("byThread",l=>l.eq("threadKey",t.key)).collect())[0];if(!d)return await n.db.patch(i._id,{status:t.status,updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{};const c=d.instanceId;return await n.db.delete(d._id),await n.db.patch(i._id,{instanceId:c,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:c}}),I=b.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()})}),m=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},h=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 m(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 m(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 m(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(K).withIndex("byThread",r=>r.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(K).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),U=b.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",l=>l.eq("key",t.threadKey)).first(),i=m(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:d}=n,c=d?.[r];if(typeof c?.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 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}}),B=b.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,d=await n.db.query(p).withIndex("byKey",l=>l.eq("key",t.threadKey)).first();if(d){const l=d.status,q=d.instanceId,_=d.owner;if((l==="running"||l==="awaiting_input")&&q!==void 0&&(_===void 0||_===r))return{id:q,threadKey:t.threadKey};if(_!==r)throw new g("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:c}=await i.run({input:t.input,threadKey:t.threadKey,...r===void 0?{}:{owner:r},...t.title===void 0?{}:{title:t.title}});return{id:c,threadKey:t.threadKey}}),C=H(),R=ee();return{extension:ne,functions:{agentAppendMessage:f(o),agentCompleteRun:f(w),agentEnsureThread:f(u),agentEpisodeRecall:R.agentEpisodeRecall,agentEpisodeUpsert:R.agentEpisodeUpsert,agentGraphTraverse:C.agentGraphTraverse,agentGraphUpsert:C.agentGraphUpsert,agentMessages:L,agentDeleteMessage:f(s),agentPatchThread:f(y),agentResolveApproval:U,agentRun:B,agentSetState:f(I),agentState:O,agentThread:h}}};export{le as agentComponent,ne as agentExtension,pe as normalizeEntityName,we as sandboxComponent};
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as t,s as r}from"./packem_shared/agent-loop-Cotwgugs.mjs";import{collectAgenticMemoryTools as a,toSearchResults as i}from"./packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as l}from"./packem_shared/agentAsTool-CgZb6ycK.mjs";import{codeTool as m}from"./packem_shared/codeTool-BQb-K3my.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-Ds2VaveB.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-DM0fNEY6.mjs";import{functionTool as D}from"./packem_shared/functionTool-D3CP4f8-.mjs";import{createAgentGenerate as M,createEpisodeExtract as O,createGraphExtract as _,createStreamGenerate as C,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-BOILDUZj.mjs";import{adaptMcpResult as F,mcpTools as L}from"./packem_shared/adaptMcpResult-CVlq-_TO.mjs";import{buildModelMessages as k}from"./packem_shared/buildModelMessages-Y4tGo1T9.mjs";import{agentBindingName as R,agentClassName as V,agentDefaultName as b,voiceBindingName as h,voiceClassName as w}from"./naming.mjs";import{AGENT_MODULE as I,DEFAULT_AGENT_FUNCTION_PATHS as P,SANDBOX_INVOKE_PATH as X,SANDBOX_MODULE as y,toFunctionReference as K}from"./packem_shared/AGENT_MODULE-M4D1EejI.mjs";import{browserTool as j,containerTool as q,fsTool as z}from"./sandbox.mjs";import{defineSkill as Q,isSkillDefinition as Y}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as $}from"./packem_shared/VoiceSessionDO-DhmYu8wo.mjs";import{r as oe}from"./packem_shared/voice-turn-B9dc3mvG.mjs";import{default as re}from"./packem_shared/compileAgentWorkflow-8pHFPjec.mjs";export{I as AGENT_MODULE,P as DEFAULT_AGENT_FUNCTION_PATHS,X as SANDBOX_INVOKE_PATH,y as SANDBOX_MODULE,$ as VoiceSessionDO,F as adaptMcpResult,l as agentAsTool,R as agentBindingName,V as agentClassName,c as agentComponent,b as agentDefaultName,x as agentExtension,j as browserTool,k as buildModelMessages,m as codeTool,a as collectAgenticMemoryTools,re as compileAgentWorkflow,q as containerTool,A as createAgentContext,M as createAgentGenerate,O as createEpisodeExtract,_ as createGraphExtract,C as createStreamGenerate,d as defineAgent,u as defineAgentTool,Q as defineSkill,z as fsTool,D as functionTool,N as isAgentDefinition,Y as isSkillDefinition,L as mcpTools,G as resolveAgentModel,t as runAgentLoop,oe as runVoiceTurn,r as splitForCompaction,K as toFunctionReference,i as toSearchResults,h as voiceBindingName,w as voiceClassName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as A}from"@lunora/ai";import{J as b}from"./createDispatchRunner-BrbbxS2q-DBBqImoR.mjs";import{t as x}from"./base64-5eyBfWO3.mjs";import{p as T,d as _,a as v,i as p,b as y,c as E,e as k,f as M,r as w,t as C}from"./voice-turn-B9dc3mvG.mjs";import{createStreamGenerate as I,createCompact as R}from"./createAgentGenerate-BOILDUZj.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as L,toFunctionReference as m}from"./AGENT_MODULE-M4D1EejI.mjs";const N="@cf/openai/whisper-large-v3-turbo",O="@cf/deepgram/aura-1",U=8*1024*1024,B=100,f=4e3,g=f*4+1024,F=4002,D=4003,z=4004,W=256*1024,S=15,G=5e3,X=h=>{if(h===null||typeof h!="object")return!1;const{text:e,type:t}=h;return t==="commit"||t==="interrupt"||t==="text"&&typeof e=="string"};class Y{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(e,t,r,s){this.state=e,this.env=t,this.agent=r,this.exportName=s,this.paths=L,this.ai=A({binding:t.AI,env:t}),this.streamGenerate=I(r,t),this.sttModel=r.voice?.stt??N,this.ttsModel=r.voice?.tts??O,this.maxSessionTurns=r.voice?.maxTurns??B}fetch(e){if(e.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(e.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=T(e.headers.get("x-lunora-identity")),a=_(e.headers.get("x-lunora-userid")),u=v(e.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(e,t){const r=e.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(e);return}try{if(typeof t=="string"){await this.handleControl(e,r,t);return}this.bufferAudio(r.connectionId,new Uint8Array(t),e)}catch(s){this.send(e,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(e){this.cleanupSocket(e)}webSocketError(e){this.cleanupSocket(e)}resolveRun(e,t){const r=e===void 0&&t===void 0?void 0:{...t===void 0?{}:{claims:t},...e===void 0?{}:{userId:e}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(e){const t=E(e);return k(await this.ai.run(this.sttModel,{audio:x(t)}))}async synthesize(e,t){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:e,...r===void 0?{}:{speaker:r}},t===void 0?void 0:{signal:t}))}async handleControl(e,t,r){if(r.length>g){this.send(e,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(e,z,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!X(s)){this.send(e,{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(t.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(e,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(t.turn>=this.maxSessionTurns){this.send(e,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(e,F,"turn_limit");return}if(this.controllers.has(t.connectionId)){this.send(e,{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(t.connectionId);await this.runTurn(e,t,{pcm:n});return}await this.runTurn(e,t,{text:i.text})}bufferAudio(e,t,r){const s=(this.bufferedBytes.get(e)??0)+t.byteLength;if(s>U){this.audioBuffers.delete(e),this.bufferedBytes.delete(e),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,D,"utterance_too_large");return}const i=this.audioBuffers.get(e)??[];i.push(t),this.audioBuffers.set(e,i),this.bufferedBytes.set(e,s)}drainAudio(e){const t=this.audioBuffers.get(e)??[];this.audioBuffers.delete(e),this.bufferedBytes.delete(e);const r=t.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of t)s.set(n,i),i+=n.byteLength;return s}async runTurn(e,t,r){const s=new AbortController;this.controllers.set(t.connectionId,s);try{await w({agent:this.agent,compact:R(),connectionId:t.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(t.userId,t.identity),send:i=>{this.send(e,i)},sendAudio:i=>{this.sendAudio(e,i)},signal:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:t.threadKey,transcribe:async i=>this.transcribe(i),turn:t.turn,waitForDrain:async()=>this.waitForSocketDrain(e),...t.userId===void 0?{}:{owner:t.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(t.connectionId)===s&&this.controllers.delete(t.connectionId),e.serializeAttachment?.({...t,turn:t.turn+1})}}async speakGreeting(e,t,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(t,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(e),d()))break;this.sendAudio(e,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(e,{text:n,type:"assistant_done"}))}catch(a){this.send(e,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(t)===c&&this.controllers.delete(t)}}async synthesizeWithSignal(e,t){return t.aborted?new Uint8Array(0):this.synthesize(e,t)}cleanupSocket(e){const t=e.deserializeAttachment?.();t&&(this.controllers.get(t.connectionId)?.abort(),this.controllers.delete(t.connectionId),this.audioBuffers.delete(t.connectionId),this.bufferedBytes.delete(t.connectionId))}closeSocket(e,t,r){try{e.close?.(t,r)}catch{}}send(e,t){try{e.send(JSON.stringify(t))}catch{}}sendAudio(e,t){try{e.send(t)}catch{}}async waitForSocketDrain(e){const t=e;let r=0;for(;typeof t.bufferedAmount=="number"&&t.bufferedAmount>W&&r<G;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{Y as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{k as Z}from"./createDispatchRunner-BrbbxS2q-DBBqImoR.mjs";import{c as F,d as tt}from"./component-shared-G8ngerkU.mjs";import{resolveAgentModel as et}from"./createAgentGenerate-BOILDUZj.mjs";import{buildModelMessages as G}from"./buildModelMessages-Y4tGo1T9.mjs";import{agentBindingName as L}from"../naming.mjs";import{toFunctionReference as h}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as ot}from"./positive-integer-ztHqqpBk.mjs";import{c as j}from"./tool-output-Cmk3JWMG.mjs";const nt=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",P=e=>e.memorySources?e.memorySources:e.memory&&nt(e.memory)?[{key:"default",...e.memory}]:[],at=e=>P(e).find(t=>t.kind==="graph"),st=e=>P(e).find(t=>t.kind==="episodic"),S=(e,t)=>t==="default"?e:`${e}:${t}`,rt=8,it=e=>ot(e)?e:0,b=e=>e===void 0?"null":JSON.stringify(e),ct=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)}},ut=e=>e===void 0?[]:[e].flat(),dt=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),pt=(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},lt=async(e,t,n,o,a)=>{const{needsApproval:r}=e;return r===void 0||r===!1?!1:r===!0?!0:n.do(o,async()=>r(t,a))},mt="WorkflowTimeoutError",yt=e=>e instanceof Error&&e.name===mt,q=4320*60*1e3,ft={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},vt=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,ht=e=>{if(e===void 0)return q;if(typeof e=="number")return Math.min(e,F);const t=vt.exec(e);return t===null?q:Math.min(Number(t[1])*ft[t[2]],F)},gt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:r,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 r({status:"awaiting_input"});const i=await u.waitForEvent(`approval:${t.id}`,{timeout:ht(n.approvalTimeout),type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note}})).catch(p=>{if(!yt(p))throw p;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await r({status:"running"}),i},O="lunoraToolOutcome",wt=e=>typeof e=="object"&&e!==null&&O in e?e[O]:{ok:e},Tt=async(e,t)=>{const{depth:n,env:o,getState:a,instanceId:r,onTokenDelta:c,owner:u,persist:i,run:p,setState:s,step:d,threadKey:l,tools:y}=e,f=`tool:${t.name}:${t.id}`,g=y[t.name],w=`${r}:tool:${t.id}`;if(!g){await i({content:`Error: unknown tool "${t.name}"`,messageKey:w,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await i({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:w,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}const C={depth:n,env:o,getState:a,idempotencyKey:f,owner:u,reportProgress:T=>{c?.({data:T,kind:"progress",threadKey:l,toolCallId:t.id})},run:p,setState:s,step:d,threadKey:l,toolCallId:t.id},$={depth:n,env:o,getState:a,idempotencyKey:f,run:p,threadKey:l,toolCallId:t.id},A=`tool:approval-gate:${t.id}`;let x;if(await lt(g,t.input,d,A,$)){const{decision:T,note:K}=await gt(e,t);if(T==="reject"){const _=K===void 0?"":` Reason: ${K}`;await i({content:`Tool "${t.name}" was rejected by the user and not run.${_}`,messageKey:w,role:"tool",status:"rejected",stepName:f,toolCallId:t.id,toolName:t.name});return}x="approved"}const M=wt(await d.do(f,async()=>{try{return{[O]:{ok:await g.execute(t.input,C)}}}catch(T){if(Z(T))return{[O]:{failed:T.message}};throw T}}));if("failed"in M){await i({content:j(`Error: tool "${t.name}" failed and will not be retried. ${M.failed}`),messageKey:w,role:"tool",stepName:f,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name});return}const R=M.ok;await i({content:j(typeof R=="string"?R:b(R)),messageKey:w,role:"tool",stepName:f,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},xt=(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:et(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},kt=(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)}},St=async(e,t)=>{const{agent:n,compact:o,env:a}=e,r=kt(t,n.compaction);if(r===void 0||o===void 0)return{history:t,summary:void 0};try{const c=await o({env:a,messages:G({history:r.older}),model:n.compaction?.model??n.model});return c.length>0?{history:r.recent,summary:c}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Ct=async(e,t,n)=>{const{agent:o,env:a,generate:r,instructions:c,listMessages:u,memoryContext:i,onTokenDelta:p,run:s,step:d,streamGenerate:l,threadKey:y}=e;return d.do(`llm:turn:${String(t)}`,async()=>{const f=await s(u,{key:y}),{history:g,summary:w}=await St(e,f);let v={activeTools:o.activeTools,messages:G({history:g,instructions:c,memoryContext:i,summary:w}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(v=xt(v,await o.prepareStep({messages:v.messages,stepNumber:t,steps:n}),a));const C={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&&p?l(C,$=>{p({text:$,threadKey:y,turn:t})}):r(C)})},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))},$t=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}}),D=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},Mt=e=>tt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Rt=async(e,t,n,o)=>{if(e.source===void 0)return;const a=h(e.source),{topK:r}=e,c=S("memory:retrieve",e.key),u=await n.do(c,async()=>o(a,{query:t,...r===void 0?{}:{topK:r}}));return D(u)},Kt=async(e,t,n,o,a,r)=>{if(n===void 0)return;const c=S("memory:traverse",e.key),u=await a.do(c,async()=>r(o,{owner:n,query:t,...Mt(e.graph)}));return D(u)},Et=async(e,t,n,o,a)=>{if(t===void 0)return;const r=S("memory:recall",e.key),c={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},u=await o.do(r,async()=>a(n,c));return D(u)},It=async(e,t)=>e.kind==="episodic"?Et(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?Kt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Rt(e,t.input,t.step,t.run),Nt=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},Ot=async(e,t,n,o,a,r)=>{const c=Nt(P(e));if(c.length===0)return;const u=h(o.graphTraverse),i=h(o.episodeRecall),p=[];for(const s of c){const d=await It(s,{episodeRecall:i,graphTraverse:u,input:t,owner:n,run:r,step:a});d!==void 0&&p.push(d)}return p.length>0?p.join(`
|
|
2
|
+
|
|
3
|
+
`):void 0},At=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:r,instanceId:c,owner:u,paths:i,run:p,step:s}=e;if(o===void 0||u===void 0||a===void 0||a.length===0)return;const d=at(t);if(d!==void 0)try{const l={assistantText:a,env:n,model:d.graph?.extractionModel??t.model,userInput:r},y=await s.do(S("memory:extract",d.key),async()=>o(l));await p(h(i.graphUpsert),{...y,messageKey:`${c}:${S("extract",d.key)}`,owner:u})}catch{}},_t=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:r,instanceId:c,owner:u,paths:i,run:p,step:s,threadKey:d}=e;if(o===void 0||u===void 0||a===void 0||a.length===0)return;const l=st(t);if(l!==void 0)try{const y={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:r},{summary:f}=await s.do(S("memory:episode",l.key),async()=>o(y));await p(h(i.episodeUpsert),{messageKey:`${c}:${S("episode",l.key)}`,owner:u,summary:f,threadKey:d})}catch{}},Ut=async(e,t,n)=>{const o=e[L(t)];if(!(!o||typeof o.get!="function"))try{await(await o.get(n)).terminate()}catch{}},Pt="12 hours",Dt=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:Pt,type:`agent-dequeue:${t}:${n}`})},Ft=async(e,t,n)=>{const o=e.env[L(e.exportName)];if(!o||typeof o.get!="function")return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},jt=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{}},qt=async(e,t,n,o,a)=>{const{instanceId:r,persist:c}=e,u=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const i=n.output!==void 0&&n.text.length===0?b(n.output):n.text;return await c({content:i,messageKey:`${r}:assistant:${String(t)}`,role:"assistant"}),await B(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:`${r}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const i of n.toolCalls)await Tt(e,i);if(await B(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...u}),o.push($t(n)),a.length>0&&await dt(a,o))return"stopCondition"},Bt=async(e,t,n,o)=>{const a=[];let r,c=!1,u=0;for(let i=0;i<t;i+=1){const p=await Ct(e,i,a);o.value=pt(o.value,p.usage),u=i+1;const s=await qt(e,i,p,a,n);if(s==="stopCondition"){c=!0;break}if(s!==void 0){r=s.final;break}}return{final:r,stoppedByCondition:c,turnsRun:u}},Jt=async e=>{const{agent:t,compact:n,env:o,exportName:a,extractEpisode:r,extractGraph:c,generate:u,instanceId:i,onTokenDelta:p,params:s,paths:d,run:l,step:y,streamGenerate:f}=e,g=t.maxTurns??rt,w=ut(t.stopWhen),v=h(d.appendMessage),C=h(d.completeRun),$=h(d.ensureThread),A=h(d.listMessages),x=h(d.deleteMessage),M=h(d.patchThread),R=h(d.setState),T=h(d.state),K=async m=>{await l(v,{threadKey:s.threadKey,...m})},_=async m=>{await l(M,{key:s.threadKey,...m})},W=async m=>{await l(x,{messageKey:m,threadKey:s.threadKey})},z=async()=>{await K({content:s.input,messageKey:`${i}:user`,role:"user"})},E=async m=>{const N=await l(C,{instanceId:i,key:s.threadKey,...m});N?.dequeued!==void 0&&await Ft({env:o,exportName:a,step:y},s.threadKey,N.dequeued)},H=async()=>await l(T,{key:s.threadKey}),V=async m=>{await l(R,{key:s.threadKey,state:m})},U=await l($,{agent:a,instanceId:i,key:s.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...s.owner===void 0?{}:{owner:s.owner},...s.title===void 0?{}:{title:s.title}});U?.outcome==="replaced"&&await Ut(o,a,U.priorInstanceId);const X=await Ot(t,s.input,s.owner,d,y,l),J=typeof t.instructions=="function"?t.instructions({env:o,input:s.input,threadKey:s.threadKey}):t.instructions,Q={agent:t,compact:n,depth:it(s.depth),env:o,generate:u,getState:H,instanceId:i,instructions:J,listMessages:A,memoryContext:X,onTokenDelta:p,owner:s.owner,deleteMessage:W,patchThread:_,persist:K,run:l,setState:V,step:y,streamGenerate:f,threadKey:s.threadKey,tools:t.tools??{}},I={value:void 0};try{U?.outcome==="queued"&&await Dt(y,s.threadKey,i),await z();const{final:m,stoppedByCondition:N,turnsRun:Y}=await Bt(Q,g,w,I),k=I.value===void 0?{}:{usage:I.value};return await At({agent:t,env:o,extractGraph:c,finalText:m?.text,input:s.input,instanceId:i,owner:s.owner,paths:d,run:l,step:y}),await _t({agent:t,env:o,extractEpisode:r,finalText:m?.text,input:s.input,instanceId:i,owner:s.owner,paths:d,run:l,step:y,threadKey:s.threadKey}),m?(await jt(t,{env:o,params:s,step:y},{...m,...k}),await E({status:"idle",...k}),{...m,...k}):N?(await E({status:"idle",...k}),{stopped:"stopCondition",turns:Y,...k}):(await E({error:`agent stopped: maxTurns (${String(g)}) reached`,status:"error",...k}),{stopped:"maxTurns",turns:g,...k})}catch(m){throw await ct(E,m,I.value),m}};export{ht as a,St as c,nt as i,Jt as r,kt as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as N}from"@lunora/workflow";import{jsonSchema as I}from"ai";import{f as L}from"./fnv1a-BNN96GYb.mjs";import{agentBindingName as S}from"../naming.mjs";import{toFunctionReference as v,DEFAULT_AGENT_FUNCTION_PATHS as $}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),P=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",D=t=>t!==null&&typeof t=="object"?t.output:void 0,U=async t=>{await new Promise(e=>{setTimeout(e,t)})},j=async(t,e,n,m)=>{for(let a=0;a<e;a+=1){const i=await t.status(),s=R(i);if(_.has(s))return{output:D(i),status:s};await m(n)}return{output:void 0,status:"timeout"}},k=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},x=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},W=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its AGENT_* binding)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=S(e),m=t.maxPolls??P,a=t.pollIntervalMs??M,i=t.wait??U,s=v($.listMessages),T=async(y,r)=>{const p=(h(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const o=r.env[n];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no Workflow binding "${n}" on env — declare the "${e}" agent so codegen wires its binding`);const g=`${r.threadKey}::sub::${e}::${r.toolCallId}`,f=`sub-${e}-${L(r.toolCallId)}`,A={depth:p,input:y.prompt,threadKey:g,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await o.create({id:f,params:A});l=await o.get(d.id)}catch(d){if(!N(d))throw d;l=await o.get(f)}const{output:b,status:u}=await j(l,m,a,i);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(k(b)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const E=await r.run(s,{key:g});return x(E)};return{description:t.description,execute:T,inputSchema:I({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{W as agentAsTool};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defineWorkflow as s}from"@lunora/workflow";import{r as m}from"./agent-loop-Cotwgugs.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-BOILDUZj.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-M4D1EejI.mjs";import{J as T}from"./createDispatchRunner-BrbbxS2q-DBBqImoR.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-CywiFp-X.mjs";const E=(r,t,a)=>t===void 0?r:T({env:a,identity:{userId:t},label:"@lunora/agent"}),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,i=[r.telemetry?.integrations].flat().filter(o=>o!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...i,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>s({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:u(),env:e.env,exportName:t,extractGraph:d(),extractEpisode:f(),generate:l(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??A,run:E(e.run,e.params.owner,e.env),step:e.step,streamGenerate:p(n,e.env)})},name:r.name??c(t)});export{I as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="agent",A=6048e5,a=12096e5,r=n=>({...n,visibility:"internal"}),_=n=>{const s={};for(const[e,t]of Object.entries(n))t!==void 0&&(s[e]=t);return s};export{o as A,r as a,
|
|
1
|
+
const o="agent",A=6048e5,a=12096e5,r=n=>({...n,visibility:"internal"}),_=n=>{const s={};for(const[e,t]of Object.entries(n))t!==void 0&&(s[e]=t);return s};export{o as A,r as a,a as b,A as c,_ as d};
|
package/dist/packem_shared/{createAgentContext-CpXkr16T.mjs → createAgentContext-Ds2VaveB.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{J as g}from"./createDispatchRunner-BrbbxS2q-
|
|
1
|
+
import{J as g}from"./createDispatchRunner-BrbbxS2q-DBBqImoR.mjs";import{LunoraError as o}from"@lunora/errors";import{h as l,B as p}from"./branch-marker-boZ00zmk.mjs";import{toFunctionReference as w,DEFAULT_AGENT_FUNCTION_PATHS as m}from"./AGENT_MODULE-M4D1EejI.mjs";const T=(r,s,i)=>{const c={},u=w(m.patchThread),d=()=>i??g({env:r,label:"@lunora/agent"});for(const e of s){const a=()=>{const n=r[e.binding];if(!n||typeof n.create!="function"||typeof n.get!="function")throw new o("INTERNAL",`@lunora/agent: no Workflow binding "${e.binding}" on env for agent "${e.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return n};c[e.exportName]={cancel:async n=>{await(await a().get(n)).terminate();try{await d()(u,{instanceId:n,status:"cancelled"})}catch{}},publicRun:e.publicRun===!0,run:async(n,t)=>{if(l(n))throw new o("BAD_REQUEST",`@lunora/agent: run input ${p}`);return{id:(await a().create({...t?.id===void 0?{}:{id:t.id},params:n})).id}},sendEvent:async(n,t)=>{await(await a().get(n)).sendEvent(t)},status:async n=>(await a().get(n)).status()}}return c};export{T as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as d,isLunoraError as O}from"@lunora/errors";const $=(t,e,n)=>{if(e===void 0)return{dispose:()=>{},signal:t};const s=new AbortController,r=setTimeout(()=>{s.abort(n())},e);return{dispose:()=>{clearTimeout(r)},signal:s.signal}},a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",A=t=>{let e="",n=0;const s=t.length-2;for(;n<s;n+=3){const o=t[n]<<16|t[n+1]<<8|t[n+2];e+=a.charAt(o>>18&63)+a.charAt(o>>12&63)+a.charAt(o>>6&63)+a.charAt(o&63)}const r=t.length-n;if(r===1){const o=t[n]<<16;e+=a.charAt(o>>18&63)+a.charAt(o>>12&63)}else if(r===2){const o=t[n]<<16|t[n+1]<<8;e+=a.charAt(o>>18&63)+a.charAt(o>>12&63)+a.charAt(o>>6&63)}return e};new TextDecoder;const w=new TextEncoder,m="=",R=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},S=t=>A(w.encode(JSON.stringify(t))),v=t=>!t.startsWith(m)&&R(t)?t:`${m}${A(w.encode(t))}`,L="/_lunora/scheduler/dispatch",_=3e4,x=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},T=Symbol("lunoraDispatchFailure"),D=Symbol("lunoraDispatchMessageId"),I=(t,e)=>(e!==void 0&&Object.defineProperty(t,D,{value:e}),t),U=(t,e)=>(Object.defineProperty(t,T,{value:!0}),I(t,e)),J=(t,e,n,s)=>{try{const r=JSON.parse(n)?.error;if(typeof r=="object"&&r!==null&&typeof r.code=="string"){const{code:o,data:u,message:h}=r;return U(new d(o,typeof h=="string"?h:void 0,{data:u,status:e}),s)}}catch{}return I(new d("INTERNAL",`${t}: function dispatch failed (${String(e)}): ${n}`,{status:e}),s)},M=new Set([400,403,404,422]),P=new Set(["DISPATCH_UNAUTHENTICATED"]),j=t=>O(t)&&t[T]===!0&&M.has(t.status)&&!P.has(t.code),k=(t,e,n)=>new d("INTERNAL",`${t}: function dispatch to "${e}" timed out after ${String(n)}ms`,{status:503}),K=t=>{const{label:e}=t,n=globalThis.fetch,s=t.fetchImpl??(typeof n=="function"?n.bind(globalThis):void 0);return async(r,o,u={})=>{if(typeof s!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const h=t.env.LUNORA_ORIGIN_URL;if(typeof h!="string"||h.length===0)throw new d("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const f=t.env.LUNORA_ADMIN_TOKEN;if(typeof f!="string"||f.length===0)throw new d("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const b=`${x(h)}${L}`,p={authorization:`Bearer ${f}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(p["x-lunora-userid"]=v(t.identity.userId)),t.identity?.claims!==void 0&&(p["x-lunora-identity"]=S(t.identity.claims));const y=u.timeoutMs??_,N=$(void 0,y,()=>new DOMException(`dispatch timed out after ${String(y)}ms`,"TimeoutError")),g=i=>{throw i instanceof Error&&i.name==="TimeoutError"?k(e,r.__lunoraRef,y):i};let c;try{try{c=await s(b,{body:JSON.stringify({args:o??{},functionPath:r.__lunoraRef,id:u.dedupId,shardKey:u.shardKey}),headers:p,method:"POST",signal:N.signal})}catch(l){return g(l)}if(!c.ok){let l;try{l=await c.text()}catch(E){return g(E)}throw J(e,c.status,l,u.messageId)}let i;try{i=await c.text()}catch(l){return g(l)}if(i.length===0)return;try{return JSON.parse(i)}catch{throw new d("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(c.status)}): ${i}`,{status:c.status})}}finally{N.dispose()}}};export{K as J,j as k};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-Cotwgugs.mjs";import{collectAgenticMemoryTools as g}from"./collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as p}from"./agentAsTool-CgZb6ycK.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=/^[a-zA-Z][\w-]*$/u,N=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=a}return o},A=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
|
|
2
|
+
|
|
3
|
+
`)},k=(e,n)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const t of n)t.knowledge&&m(t.knowledge)&&o.push({key:t.name,...t.knowledge});return o},y=e=>{const n=new Set;for(const o of e){if(typeof o.name!="string"||!w.test(o.name))throw new r("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new r("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(n.has(o.name))throw new r("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);n.add(o.name)}},v=(e,n)=>{if(e===void 0)return;const o=Object.keys(n).filter(t=>!e.includes(t));if(o.length>0)throw new r("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(t=>`"${t}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},E=(e,n)=>{const o=(t,s)=>{if(t&&t.kind!=="graph"&&t.kind!=="episodic"&&t.source===void 0)throw new r("INTERNAL",`@lunora/agent: ${s} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const t of n)o(t.knowledge,`skill "${t.name}" \`knowledge\``)},L=e=>{if(e===void 0)return;const n=f(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},$=e=>{const n=e.model;if(n==null||typeof n=="string"&&n.length===0)throw new r("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(e.maxTurns!==void 0&&!u(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!u(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");L(e.approvalTimeout);const o=e.skills??[];y(o),E(e,o);const t=N(e,o),s=g(e,o);for(const[i,h]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=h}const a=Object.keys(s).length>0;v(e.activeTools,s);for(const i of Object.keys(t))if(!T.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=k(e,o),d=A(e,o);return{...e,asTool:p,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:t}:{}}},j=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,M=e=>{if(typeof e.execute!="function")throw new r("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{$ as defineAgent,M as defineAgentTool,j as isAgentDefinition};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=c=>c.toString(16).padStart(4,"0"),g=c=>{let t=8997,n=33826,e=40164,s=52210;for(let h=0;h<c.length;h+=1){t^=c.charCodeAt(h);const r=t*435,p=n*435,x=e*435+t*256,d=s*435+n*256,l=p+(r>>>16),a=x+(l>>>16),f=d+(a>>>16);t=r&65535,n=l&65535,e=a&65535,s=f&65535}return o(s)+o(e)+o(n)+o(t)};export{g as f};
|
package/dist/packem_shared/{normalizeEntityName-Ce0X6Afj.mjs → normalizeEntityName-k3fjicAG.mjs}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{defineTable as A,initLunora as q}from"@lunora/server";import{v as e}from"@lunora/values";import{A as _,a as f,d as S}from"./component-shared-
|
|
1
|
+
import{defineTable as A,initLunora as q}from"@lunora/server";import{v as e}from"@lunora/values";import{A as _,a as f,d as S}from"./component-shared-G8ngerkU.mjs";const T="entities",x="edges",b=`${_}_${T}`,g=`${_}_${x}`,X={[T]:A({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[x]:A({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},E=64,O=2,G=4,D=8,C=32,R=500,I=/\s+/gu,K=/[^\p{L}\p{N}]+/u,h=t=>t.trim().replaceAll(I," ").toLowerCase(),L=t=>t.toLowerCase().split(K).filter(o=>o.length>=2),P=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,o)=>o.weight-t.weight||t.label.localeCompare(o.label)||t.srcName.localeCompare(o.srcName)||t.dstName.localeCompare(o.dstName),$=(t,o)=>o.some(n=>t.includes(n)||n.includes(t)),v=t=>t.map(o=>`- ${o.srcName} —[${o.label}]→ ${o.dstName}`).toSorted((o,n)=>o.localeCompare(n)).join(`
|
|
2
2
|
`),H=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,B=(t,o,n,r)=>{const a=H(t);r.collectedKeys.has(a)||(r.collectedKeys.add(a),r.collected.push(t));const l=t.srcName===o?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<n.maxNodes&&(r.seen.add(l),r.next.push(l))},F=async(t,o,n)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(o)};let a=o.slice(0,n.maxNodes);for(let l=0;l<n.depth&&a.length>0;l+=1){r.next=[];for(const m of a){const p=(await t(m)).toSorted(U).slice(0,n.fanOut);for(const s of p)B(s,m,n,r)}a=r.next}return r.collected},{mutation:M,query:W}=q.dataModel().create(),Y=()=>{const t=M.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:n,ctx:r})=>{const a=Date.now(),l=async(s,i)=>{const c=h(s);if(c.length===0)return;const d=await r.db.query(b).withIndex("byOwnerName",u=>u.eq("owner",n.owner).eq("name",c)).first();return d?(i!==void 0&&d.type===void 0&&await r.db.patch(d._id,{type:i,updatedAt:a}),c):(await r.db.insert(b,{createdAt:a,name:c,owner:n.owner,updatedAt:a,weight:1,...S({firstMessageKey:n.messageKey,type:i})}),c)},m=async s=>{const i=h(s.src),c=h(s.dst),d=h(s.label);if(i.length===0||c.length===0||d.length===0||i===c)return!1;await l(i),await l(c);const u=s.confidence??1,N=await r.db.query(g).withIndex("byTriple",y=>y.eq("owner",n.owner).eq("srcName",i).eq("label",d).eq("dstName",c)).first();if(N){const y=N.weight??1;await r.db.patch(N._id,{updatedAt:a,weight:Math.max(y,u)})}else await r.db.insert(g,{createdAt:a,dstName:c,label:d,messageKey:n.messageKey,owner:n.owner,srcName:i,updatedAt:a,weight:u});return!0};let w=0;for(const s of n.entities.slice(0,E))await l(s.name,s.type)!==void 0&&(w+=1);let p=0;for(const s of n.relations.slice(0,E))await m(s)&&(p+=1);return{entities:w,relations:p}}),o=W.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:n,ctx:r})=>{const a=L(n.query);if(a.length===0)return{context:""};const m=(await r.db.query(b).withIndex("byOwnerUpdatedAt",s=>s.eq("owner",n.owner)).order("desc").take(R)).filter(s=>$(s.name,a)).toSorted((s,i)=>(i.weight??1)-(s.weight??1)||s.name.localeCompare(i.name)).slice(0,n.maxSeeds??G).map(s=>s.name);if(m.length===0)return{context:""};const p=await F(async s=>{const[i,c]=await Promise.all([r.db.query(g).withIndex("byOwnerSrc",d=>d.eq("owner",n.owner).eq("srcName",s)).collect(),r.db.query(g).withIndex("byOwnerDst",d=>d.eq("owner",n.owner).eq("dstName",s)).collect()]);return[...i,...c].map(d=>P(d))},m,{depth:n.depth??O,fanOut:n.fanOut??D,maxNodes:n.maxNodes??C});return{context:v(p)}});return{agentGraphTraverse:f(o),agentGraphUpsert:f(t)}};export{Y as graphComponent,X as graphTables,h as normalizeEntityName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./createDispatchRunner-BrbbxS2q-DBBqImoR.mjs";import"./component-shared-G8ngerkU.mjs";import"./createAgentGenerate-BOILDUZj.mjs";import{a as n,c as l,r as u,s as f}from"./agent-loop-Cotwgugs.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"../naming.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./tool-output-Cmk3JWMG.mjs";export{n as approvalTimeoutMs,l as compactHistory,u as runAgentLoop,f as splitForCompaction};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./base64-5eyBfWO3.mjs";import{p as s,c as p,f as m,e as n,r as c,t as d}from"./voice-turn-B9dc3mvG.mjs";import"./agent-loop-Cotwgugs.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";export{s as parseIdentity,p as pcmToWav,m as readSynthesisAudio,n as readTranscriptionText,c as runVoiceTurn,d as toByteIterable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as P,a as q}from"./base64-5eyBfWO3.mjs";import{c as z}from"./agent-loop-Cotwgugs.mjs";import{buildModelMessages as G}from"./buildModelMessages-Y4tGo1T9.mjs";import{toFunctionReference as T}from"./AGENT_MODULE-M4D1EejI.mjs";const D=new TextDecoder;new TextEncoder;const N="=",Q=t=>{if(t)try{const e=t[0]==="{"?t:D.decode(P(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(P(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,ft=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},yt=(t,e=Y,n=Z,r=tt)=>{const i=n*r/8,p=e*i,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(l,E)=>{for(let d=0;d<E.length;d+=1)s.setUint8(l+d,E.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,p,!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},st=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 p=n.slice(0,i).trim();p.length>0&&e.push(p),n=n.slice(i),r=M.exec(n)}return{rest:n,sentences:e}},pt=async t=>{const{agent:e,compact:n,connectionId:r,env:i,exportName:p,owner:m,paths:s,pcm:u,run:a,send:l,sendAudio:E,signal:d,streamGenerate:C,synthesize:H,text:L,threadKey:o,transcribe:F,turn:U,waitForDrain:O}=t,h=()=>d.aborted,v=T(s.appendMessage),$=T(s.ensureThread),B=T(s.listMessages),b=T(s.patchThread);await a($,{agent:p,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const f=(L??(u?await F(u):"")).trim();if(f.length===0)return await a(b,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};l({text:f,type:"user_transcript"}),await a(v,{content:f,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await a(b,{key:o,status:"running"});const I=typeof e.instructions=="function"?e.instructions({env:i,input:f,threadKey:o}):e.instructions,K=await a(B,{key:o}),{history:j,summary:R}=await z({agent:e,compact:n,env:i},K),W=G({history:j,...I===void 0?{}:{instructions:I},...R===void 0?{}:{summary:R}});let g="",w="",S=Promise.resolve();const V=async c=>{if(h()||c.length===0)return;let x=!1;try{for await(const y of nt(await H(c,d))){if(h()||(await O?.(),h()))break;E(y),x=!0}}catch(y){l({message:y instanceof Error?y.message:String(y),type:"error"})}x&&(w=w.length>0?`${w} ${c}`:c)},_=c=>{S=S.then(async()=>V(c))},X=await C({messages:W,signal:d},c=>{if(h())return;l({text:c,type:"assistant_delta"}),g+=c;const{rest:x,sentences:y}=st(g);g=x;for(const J of y)_(J)});!h()&&g.trim().length>0&&_(g.trim()),g="",await S;const k=h(),A=k?w:X.text;return await a(v,{content:A,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await a(b,{key:o,status:"idle"}),l(k?{type:"interrupted"}:{text:A,type:"assistant_done"}),{assistantText:A,interrupted:k,userText:f}}catch(f){throw await a(b,{key:o,status:"idle"}),f}},lt=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 q(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{dt as a,ft as b,yt as c,ct as d,ht as e,gt as f,ut as i,lt as p,pt as r,nt as t};
|
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.88",
|
|
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",
|
|
@@ -86,10 +86,10 @@
|
|
|
86
86
|
"dependencies": {
|
|
87
87
|
"@lunora/ai": "1.0.0-alpha.72",
|
|
88
88
|
"@lunora/errors": "1.0.0-alpha.31",
|
|
89
|
-
"@lunora/mail": "1.0.0-alpha.
|
|
89
|
+
"@lunora/mail": "1.0.0-alpha.63",
|
|
90
90
|
"@lunora/server": "1.0.0-alpha.102",
|
|
91
91
|
"@lunora/values": "1.0.0-alpha.39",
|
|
92
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
92
|
+
"@lunora/workflow": "1.0.0-alpha.45",
|
|
93
93
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
94
94
|
"ai": "7.0.59",
|
|
95
95
|
"yaml": "^2.9.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createAi as S}from"@lunora/ai";import{J as A}from"./createDispatchRunner-BrbbxS2q-Dbic8l08.mjs";import{t as b}from"./base64-5eyBfWO3.mjs";import{p as T,d as _,a as x,i as f,b as p,c as v,e as E,f as k,r as M,t as w}from"./voice-turn-CVPDDTTC.mjs";import{createStreamGenerate as I,createCompact as R}from"./createAgentGenerate-BOILDUZj.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as C,toFunctionReference as y}from"./AGENT_MODULE-M4D1EejI.mjs";const L="@cf/openai/whisper-large-v3-turbo",N="@cf/deepgram/aura-1",O=8*1024*1024,U=100,l=4e3,m=l*4+1024,B=4002,D=4003,F=4004,z=256*1024,g=15,W=5e3;class V{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(e,t,s,r){this.state=e,this.env=t,this.agent=s,this.exportName=r,this.paths=C,this.ai=S({binding:t.AI,env:t}),this.streamGenerate=I(s,t),this.sttModel=s.voice?.stt??L,this.ttsModel=s.voice?.tts??N,this.maxSessionTurns=s.voice?.maxTurns??U}fetch(e){if(e.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const s=new URL(e.url).searchParams.get("threadKey");if(!s)return new Response("Missing threadKey",{status:400});const r=globalThis.WebSocketPair,i=new r,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=T(e.headers.get("x-lunora-identity")),a=_(e.headers.get("x-lunora-userid")),h=x(e.headers.get("x-lunora-identity-exp"));if(f(h))return p(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:s,turn:0,...h===void 0?{}:{expiresAt:h},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const u=this.agent.voice?.greeting;return u&&u.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,s,a,d,u)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(e,t){const s=e.deserializeAttachment?.();if(s){if(f(s.expiresAt)){p(e);return}try{if(typeof t=="string"){await this.handleControl(e,s,t);return}this.bufferAudio(s.connectionId,new Uint8Array(t),e)}catch(r){this.send(e,{message:r instanceof Error?r.message:String(r),type:"error"})}}}webSocketClose(e){this.cleanupSocket(e)}webSocketError(e){this.cleanupSocket(e)}resolveRun(e,t){const s=e===void 0&&t===void 0?void 0:{...t===void 0?{}:{claims:t},...e===void 0?{}:{userId:e}};return A({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(e){const t=v(e);return E(await this.ai.run(this.sttModel,{audio:b(t)}))}async synthesize(e,t){const s=this.agent.voice?.speaker;return k(await this.ai.run(this.ttsModel,{text:e,...s===void 0?{}:{speaker:s}},t===void 0?void 0:{signal:t}))}async handleControl(e,t,s){if(s.length>m){this.send(e,{message:`control frame exceeds the maximum of ${String(m)} characters`,type:"error"}),this.closeSocket(e,F,"control_frame_limit");return}let r;try{r=JSON.parse(s)}catch{return}if(r.type==="interrupt"){this.controllers.get(t.connectionId)?.abort();return}if(r.type==="text"&&r.text.length>l){this.send(e,{message:`text frame exceeds the maximum of ${String(l)} characters`,type:"error"});return}if(t.turn>=this.maxSessionTurns){this.send(e,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(e,B,"turn_limit");return}if(this.controllers.has(t.connectionId)){this.send(e,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(r.type==="commit"){const i=this.drainAudio(t.connectionId);await this.runTurn(e,t,{pcm:i});return}await this.runTurn(e,t,{text:r.text})}bufferAudio(e,t,s){const r=(this.bufferedBytes.get(e)??0)+t.byteLength;if(r>O){this.audioBuffers.delete(e),this.bufferedBytes.delete(e),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(s,D,"utterance_too_large");return}const i=this.audioBuffers.get(e)??[];i.push(t),this.audioBuffers.set(e,i),this.bufferedBytes.set(e,r)}drainAudio(e){const t=this.audioBuffers.get(e)??[];this.audioBuffers.delete(e),this.bufferedBytes.delete(e);const s=t.reduce((n,o)=>n+o.byteLength,0),r=new Uint8Array(s);let i=0;for(const n of t)r.set(n,i),i+=n.byteLength;return r}async runTurn(e,t,s){const r=new AbortController;this.controllers.set(t.connectionId,r);try{await M({agent:this.agent,compact:R(),connectionId:t.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(t.userId,t.identity),send:i=>{this.send(e,i)},sendAudio:i=>{this.sendAudio(e,i)},signal:r.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:t.threadKey,transcribe:async i=>this.transcribe(i),turn:t.turn,waitForDrain:async()=>this.waitForSocketDrain(e),...t.userId===void 0?{}:{owner:t.userId},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(t.connectionId)===r&&this.controllers.delete(t.connectionId),e.serializeAttachment?.({...t,turn:t.turn+1})}}async speakGreeting(e,t,s,r,i,n){const o=this.resolveRun(r,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(t,c);try{if((await o(y(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...r===void 0?{}:{owner:r}}))?.outcome!=="created")return;for await(const h of w(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(e),d()))break;this.sendAudio(e,h)}d()||(await o(y(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(e,{text:n,type:"assistant_done"}))}catch(a){this.send(e,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(t)===c&&this.controllers.delete(t)}}async synthesizeWithSignal(e,t){return t.aborted?new Uint8Array(0):this.synthesize(e,t)}cleanupSocket(e){const t=e.deserializeAttachment?.();t&&(this.controllers.get(t.connectionId)?.abort(),this.controllers.delete(t.connectionId),this.audioBuffers.delete(t.connectionId),this.bufferedBytes.delete(t.connectionId))}closeSocket(e,t,s){try{e.close?.(t,s)}catch{}}send(e,t){try{e.send(JSON.stringify(t))}catch{}}sendAudio(e,t){try{e.send(t)}catch{}}async waitForSocketDrain(e){const t=e;let s=0;for(;typeof t.bufferedAmount=="number"&&t.bufferedAmount>z&&s<W;)await new Promise(r=>{setTimeout(r,g)}),s+=g}}export{V as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as N}from"@lunora/workflow";import{jsonSchema as I}from"ai";import{agentBindingName as L}from"../naming.mjs";import{toFunctionReference as S,DEFAULT_AGENT_FUNCTION_PATHS as v}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const $=new Set(["complete","errored","terminated"]),_=600,w=3,P=500,M=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",R=t=>t!==null&&typeof t=="object"?t.output:void 0,D=async t=>{await new Promise(e=>{setTimeout(e,t)})},U=async(t,e,n,m)=>{for(let a=0;a<e;a+=1){const i=await t.status(),s=M(i);if($.has(s))return{output:R(i),status:s};await m(n)}return{output:void 0,status:"timeout"}},j=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},k=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""},K=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its AGENT_* binding)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!h(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=L(e),m=t.maxPolls??_,a=t.pollIntervalMs??P,i=t.wait??D,s=S(v.listMessages),T=async(y,r)=>{const g=(h(r.depth)?r.depth:0)+1;if(g>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const o=r.env[n];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no Workflow binding "${n}" on env — declare the "${e}" agent so codegen wires its binding`);const p=`${r.threadKey}::sub::${e}::${r.toolCallId}`,f=`sub-${e}-${r.toolCallId}`,A={depth:g,input:y.prompt,threadKey:p,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await o.create({id:f,params:A});l=await o.get(d.id)}catch(d){if(!N(d))throw d;l=await o.get(f)}const{output:b,status:u}=await U(l,m,a,i);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(j(b)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const E=await r.run(s,{key:p});return k(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{K as agentAsTool};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";import{jsonSchema as h,asSchema as A}from"ai";import{i as g}from"./positive-integer-ztHqqpBk.mjs";import{M as v,c as $}from"./tool-output-Cmk3JWMG.mjs";const T=16,w=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=v?e:$(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(!(r in o))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}=A(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}`)},E=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=o[s.tool];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:w(f)})}return{final:p.at(-1)?.output,results:p}},_=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("; ")}.`,O=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&&!g(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const n=o.maxSteps??T;return{description:o.description??_(e),execute:(r,i)=>E(r,e,i,n),inputSchema:O,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{P as codeTool,l as resolveReferences,E as runToolScript};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{defineWorkflow as s}from"@lunora/workflow";import{runAgentLoop as m}from"./runAgentLoop-D7nLAmvV.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-BOILDUZj.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-M4D1EejI.mjs";import{J as T}from"./createDispatchRunner-BrbbxS2q-Dbic8l08.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-CywiFp-X.mjs";const E=(r,t,a)=>t===void 0?r:T({env:a,identity:{userId:t},label:"@lunora/agent"}),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,i=[r.telemetry?.integrations].flat().filter(o=>o!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...i,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>s({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:u(),env:e.env,exportName:t,extractGraph:d(),extractEpisode:f(),generate:l(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??A,run:E(e.run,e.params.owner,e.env),step:e.step,streamGenerate:p(n,e.env)})},name:r.name??c(t)});export{I as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";const T=(t,e,n)=>{if(e===void 0)return{dispose:()=>{},signal:t};const s=new AbortController,o=setTimeout(()=>{s.abort(n())},e);return{dispose:()=>{clearTimeout(o)},signal:s.signal}},a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",A=t=>{let e="",n=0;const s=t.length-2;for(;n<s;n+=3){const r=t[n]<<16|t[n+1]<<8|t[n+2];e+=a.charAt(r>>18&63)+a.charAt(r>>12&63)+a.charAt(r>>6&63)+a.charAt(r&63)}const o=t.length-n;if(o===1){const r=t[n]<<16;e+=a.charAt(r>>18&63)+a.charAt(r>>12&63)}else if(o===2){const r=t[n]<<16|t[n+1]<<8;e+=a.charAt(r>>18&63)+a.charAt(r>>12&63)+a.charAt(r>>6&63)}return e};new TextDecoder;const w=new TextEncoder,N="=",$=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},R=t=>A(w.encode(JSON.stringify(t))),v=t=>!t.startsWith(N)&&$(t)?t:`${N}${A(w.encode(t))}`,E="/_lunora/scheduler/dispatch",L=3e4,_=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},S=Symbol("lunoraDispatchFailure"),x=Symbol("lunoraDispatchMessageId"),b=(t,e)=>(e!==void 0&&Object.defineProperty(t,x,{value:e}),t),D=(t,e)=>(Object.defineProperty(t,S,{value:!0}),b(t,e)),U=(t,e,n,s)=>{try{const o=JSON.parse(n)?.error;if(typeof o=="object"&&o!==null&&typeof o.code=="string"){const{code:r,data:u,message:l}=o;return D(new d(r,typeof l=="string"?l:void 0,{data:u,status:e}),s)}}catch{}return b(new d("INTERNAL",`${t}: function dispatch failed (${String(e)}): ${n}`,{status:e}),s)},J=(t,e,n)=>new d("INTERNAL",`${t}: function dispatch to "${e}" timed out after ${String(n)}ms`,{status:503}),P=t=>{const{label:e}=t,n=globalThis.fetch,s=t.fetchImpl??(typeof n=="function"?n.bind(globalThis):void 0);return async(o,r,u={})=>{if(typeof s!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const l=t.env.LUNORA_ORIGIN_URL;if(typeof l!="string"||l.length===0)throw new d("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const f=t.env.LUNORA_ADMIN_TOKEN;if(typeof f!="string"||f.length===0)throw new d("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const I=`${_(l)}${E}`,p={authorization:`Bearer ${f}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(p["x-lunora-userid"]=v(t.identity.userId)),t.identity?.claims!==void 0&&(p["x-lunora-identity"]=R(t.identity.claims));const y=u.timeoutMs??L,m=T(void 0,y,()=>new DOMException(`dispatch timed out after ${String(y)}ms`,"TimeoutError")),g=i=>{throw i instanceof Error&&i.name==="TimeoutError"?J(e,o.__lunoraRef,y):i};let c;try{try{c=await s(I,{body:JSON.stringify({args:r??{},functionPath:o.__lunoraRef,id:u.dedupId,shardKey:u.shardKey}),headers:p,method:"POST",signal:m.signal})}catch(h){return g(h)}if(!c.ok){let h;try{h=await c.text()}catch(O){return g(O)}throw U(e,c.status,h,u.messageId)}let i;try{i=await c.text()}catch(h){return g(h)}if(i.length===0)return;try{return JSON.parse(i)}catch{throw new d("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(c.status)}): ${i}`,{status:c.status})}}finally{m.dispose()}}};export{P as J};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as g}from"./agentAsTool-DnQ2245q.mjs";import{i as m}from"./memory-JI0lUu84.mjs";import{i as c}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as u}from"./defineSkill-DGGvDWNq.mjs";const T=/^[a-zA-Z][\w-]*$/u,p=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,l]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]=l}return o},N=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
|
|
2
|
-
|
|
3
|
-
`)},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},A=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===u)throw new r("INTERNAL",`@lunora/agent: skill name "${u}" 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)}},y=(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\``)},S=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&&!c(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!c(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");const o=e.skills??[];A(o),E(e,o);const t=p(e,o),s=f(e,o);for(const[i,h]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=h}const l=Object.keys(s).length>0;y(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 a=k(e,o),d=N(e,o);return{...e,asTool:g,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...a.length>0?{memorySources:a}:{},...o.length>0||l?{tools:t}:{}}},O=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,$=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{S as defineAgent,$ as defineAgentTool,O as isAgentDefinition};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const s=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",o=e=>e.memorySources?e.memorySources:e.memory&&s(e.memory)?[{key:"default",...e.memory}]:[],i=e=>o(e).find(r=>r.kind==="graph"),c=e=>o(e).find(r=>r.kind==="episodic"),d=(e,r)=>r==="default"?e:`${e}:${r}`;export{c as a,i as f,s as i,d as m,o as r};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{d as J,b as O}from"./component-shared-IZozysYq.mjs";import{resolveAgentModel as Q}from"./createAgentGenerate-BOILDUZj.mjs";import{r as Y,f as Z,m as x,a as tt}from"./memory-JI0lUu84.mjs";import{buildModelMessages as F}from"./buildModelMessages-Y4tGo1T9.mjs";import{agentBindingName as q}from"../naming.mjs";import{toFunctionReference as f}from"./AGENT_MODULE-M4D1EejI.mjs";import{i as et}from"./positive-integer-ztHqqpBk.mjs";import{c as ot}from"./tool-output-Cmk3JWMG.mjs";const nt=8,at=e=>et(e)?e:0,j=e=>e===void 0?"null":JSON.stringify(e),st=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)}},rt=e=>e===void 0?[]:[e].flat(),it=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),ct=(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},ut=async(e,t,n,o,a)=>{const{needsApproval:r}=e;return r===void 0||r===!1?!1:r===!0?!0:n.do(o,async()=>r(t,a))},dt="WorkflowTimeoutError",pt=e=>e instanceof Error&&e.name===dt,P=4320*60*1e3,lt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},mt=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,yt=e=>{if(e===void 0)return P;if(typeof e=="number")return Math.min(e,O);const t=mt.exec(e);return t===null?P:Math.min(Number(t[1])*lt[t[2]],O)},vt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:r,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 r({status:"awaiting_input"});const i=await u.waitForEvent(`approval:${t.id}`,{timeout:yt(n.approvalTimeout),type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note}})).catch(p=>{if(!pt(p))throw p;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await r({status:"running"}),i},ht=async(e,t)=>{const{depth:n,env:o,getState:a,instanceId:r,onTokenDelta:c,owner:u,persist:i,run:p,setState:s,step:d,threadKey:l,tools:y}=e,v=`tool:${t.name}:${t.id}`,g=y[t.name],w=`${r}:tool:${t.id}`;if(!g){await i({content:`Error: unknown tool "${t.name}"`,messageKey:w,role:"tool",stepName:v,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await i({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:w,role:"tool",stepName:v,toolCallId:t.id,toolName:t.name});return}const S={depth:n,env:o,getState:a,idempotencyKey:v,owner:u,reportProgress:$=>{c?.({data:$,kind:"progress",threadKey:l,toolCallId:t.id})},run:p,setState:s,step:d,threadKey:l,toolCallId:t.id},C={depth:n,env:o,getState:a,idempotencyKey:v,run:p,threadKey:l,toolCallId:t.id},A=`tool:approval-gate:${t.id}`;let M;if(await ut(g,t.input,d,A,C)){const{decision:$,note:k}=await vt(e,t);if($==="reject"){const K=k===void 0?"":` Reason: ${k}`;await i({content:`Tool "${t.name}" was rejected by the user and not run.${K}`,messageKey:w,role:"tool",status:"rejected",stepName:v,toolCallId:t.id,toolName:t.name});return}M="approved"}const R=await d.do(v,()=>Promise.resolve(g.execute(t.input,S)));await i({content:ot(typeof R=="string"?R:j(R)),messageKey:w,role:"tool",stepName:v,...M===void 0?{}:{status:M},toolCallId:t.id,toolName:t.name})},ft=(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:Q(t.model,n),toolChoice:t.toolChoice??e.toolChoice}},gt=(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)}},wt=async(e,t)=>{const{agent:n,compact:o,env:a}=e,r=gt(t,n.compaction);if(r===void 0||o===void 0)return{history:t,summary:void 0};try{const c=await o({env:a,messages:F({history:r.older}),model:n.compaction?.model??n.model});return c.length>0?{history:r.recent,summary:c}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Tt=async(e,t,n)=>{const{agent:o,env:a,generate:r,instructions:c,listMessages:u,memoryContext:i,onTokenDelta:p,run:s,step:d,streamGenerate:l,threadKey:y}=e;return d.do(`llm:turn:${String(t)}`,async()=>{const v=await s(u,{key:y}),{history:g,summary:w}=await wt(e,v);let h={activeTools:o.activeTools,messages:F({history:g,instructions:c,memoryContext:i,summary:w}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(h=ft(h,await o.prepareStep({messages:h.messages,stepNumber:t,steps:n}),a));const S={messages:h.messages,...h.activeTools===void 0?{}:{activeTools:h.activeTools},...h.model===void 0?{}:{model:h.model},...h.toolChoice===void 0?{}:{toolChoice:h.toolChoice}};return l&&p?l(S,C=>{p({text:C,threadKey:y,turn:t})}):r(S)})},D=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))},xt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),_=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},St=e=>J({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Ct=async(e,t,n,o)=>{if(e.source===void 0)return;const a=f(e.source),{topK:r}=e,c=x("memory:retrieve",e.key),u=await n.do(c,async()=>o(a,{query:t,...r===void 0?{}:{topK:r}}));return _(u)},Mt=async(e,t,n,o,a,r)=>{if(n===void 0)return;const c=x("memory:traverse",e.key),u=await a.do(c,async()=>r(o,{owner:n,query:t,...St(e.graph)}));return _(u)},Rt=async(e,t,n,o,a)=>{if(t===void 0)return;const r=x("memory:recall",e.key),c={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},u=await o.do(r,async()=>a(n,c));return _(u)},$t=async(e,t)=>e.kind==="episodic"?Rt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?Mt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Ct(e,t.input,t.step,t.run),kt=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},Kt=async(e,t,n,o,a,r)=>{const c=kt(Y(e));if(c.length===0)return;const u=f(o.graphTraverse),i=f(o.episodeRecall),p=[];for(const s of c){const d=await $t(s,{episodeRecall:i,graphTraverse:u,input:t,owner:n,run:r,step:a});d!==void 0&&p.push(d)}return p.length>0?p.join(`
|
|
2
|
-
|
|
3
|
-
`):void 0},Et=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:r,instanceId:c,owner:u,paths:i,run:p,step:s}=e;if(o===void 0||u===void 0||a===void 0||a.length===0)return;const d=Z(t);if(d!==void 0)try{const l={assistantText:a,env:n,model:d.graph?.extractionModel??t.model,userInput:r},y=await s.do(x("memory:extract",d.key),async()=>o(l));await p(f(i.graphUpsert),{...y,messageKey:`${c}:${x("extract",d.key)}`,owner:u})}catch{}},It=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:r,instanceId:c,owner:u,paths:i,run:p,step:s,threadKey:d}=e;if(o===void 0||u===void 0||a===void 0||a.length===0)return;const l=tt(t);if(l!==void 0)try{const y={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:r},{summary:v}=await s.do(x("memory:episode",l.key),async()=>o(y));await p(f(i.episodeUpsert),{messageKey:`${c}:${x("episode",l.key)}`,owner:u,summary:v,threadKey:d})}catch{}},Nt=async(e,t,n)=>{const o=e[q(t)];if(!(!o||typeof o.get!="function"))try{await(await o.get(n)).terminate()}catch{}},At="12 hours",Ut=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:At,type:`agent-dequeue:${t}:${n}`})},_t=async(e,t,n)=>{const o=e.env[q(e.exportName)];if(!o||typeof o.get!="function")return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},Ot=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{}},Pt=async(e,t,n,o,a)=>{const{instanceId:r,persist:c}=e,u=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const i=n.output!==void 0&&n.text.length===0?j(n.output):n.text;return await c({content:i,messageKey:`${r}:assistant:${String(t)}`,role:"assistant"}),await D(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:`${r}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const i of n.toolCalls)await ht(e,i);if(await D(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...u}),o.push(xt(n)),a.length>0&&await it(a,o))return"stopCondition"},Dt=async(e,t,n,o)=>{const a=[];let r,c=!1,u=0;for(let i=0;i<t;i+=1){const p=await Tt(e,i,a);o.value=ct(o.value,p.usage),u=i+1;const s=await Pt(e,i,p,a,n);if(s==="stopCondition"){c=!0;break}if(s!==void 0){r=s.final;break}}return{final:r,stoppedByCondition:c,turnsRun:u}},zt=async e=>{const{agent:t,compact:n,env:o,exportName:a,extractEpisode:r,extractGraph:c,generate:u,instanceId:i,onTokenDelta:p,params:s,paths:d,run:l,step:y,streamGenerate:v}=e,g=t.maxTurns??nt,w=rt(t.stopWhen),h=f(d.appendMessage),S=f(d.completeRun),C=f(d.ensureThread),A=f(d.listMessages),M=f(d.deleteMessage),R=f(d.patchThread),$=f(d.setState),k=f(d.state),K=async m=>{await l(h,{threadKey:s.threadKey,...m})},B=async m=>{await l(R,{key:s.threadKey,...m})},G=async m=>{await l(M,{messageKey:m,threadKey:s.threadKey})},L=async()=>{await K({content:s.input,messageKey:`${i}:user`,role:"user"})},E=async m=>{const N=await l(S,{instanceId:i,key:s.threadKey,...m});N?.dequeued!==void 0&&await _t({env:o,exportName:a,step:y},s.threadKey,N.dequeued)},b=async()=>await l(k,{key:s.threadKey}),W=async m=>{await l($,{key:s.threadKey,state:m})},U=await l(C,{agent:a,instanceId:i,key:s.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...s.owner===void 0?{}:{owner:s.owner},...s.title===void 0?{}:{title:s.title}});U?.outcome==="replaced"&&await Nt(o,a,U.priorInstanceId);const z=await Kt(t,s.input,s.owner,d,y,l),H=typeof t.instructions=="function"?t.instructions({env:o,input:s.input,threadKey:s.threadKey}):t.instructions,V={agent:t,compact:n,depth:at(s.depth),env:o,generate:u,getState:b,instanceId:i,instructions:H,listMessages:A,memoryContext:z,onTokenDelta:p,owner:s.owner,deleteMessage:G,patchThread:B,persist:K,run:l,setState:W,step:y,streamGenerate:v,threadKey:s.threadKey,tools:t.tools??{}},I={value:void 0};try{U?.outcome==="queued"&&await Ut(y,s.threadKey,i),await L();const{final:m,stoppedByCondition:N,turnsRun:X}=await Dt(V,g,w,I),T=I.value===void 0?{}:{usage:I.value};return await Et({agent:t,env:o,extractGraph:c,finalText:m?.text,input:s.input,instanceId:i,owner:s.owner,paths:d,run:l,step:y}),await It({agent:t,env:o,extractEpisode:r,finalText:m?.text,input:s.input,instanceId:i,owner:s.owner,paths:d,run:l,step:y,threadKey:s.threadKey}),m?(await Ot(t,{env:o,params:s,step:y},{...m,...T}),await E({status:"idle",...T}),{...m,...T}):N?(await E({status:"idle",...T}),{stopped:"stopCondition",turns:X,...T}):(await E({error:`agent stopped: maxTurns (${String(g)}) reached`,status:"error",...T}),{stopped:"maxTurns",turns:g,...T})}catch(m){throw await st(E,m,I.value),m}};export{wt as compactHistory,zt as runAgentLoop,gt as splitForCompaction};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./base64-5eyBfWO3.mjs";import{p as s,c as p,f as m,e as n,r as c,t as d}from"./voice-turn-CVPDDTTC.mjs";import"./runAgentLoop-D7nLAmvV.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";export{s as parseIdentity,p as pcmToWav,m as readSynthesisAudio,n as readTranscriptionText,c as runVoiceTurn,d as toByteIterable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as P,a as q}from"./base64-5eyBfWO3.mjs";import{compactHistory as z}from"./runAgentLoop-D7nLAmvV.mjs";import{buildModelMessages as G}from"./buildModelMessages-Y4tGo1T9.mjs";import{toFunctionReference as T}from"./AGENT_MODULE-M4D1EejI.mjs";const D=new TextDecoder;new TextEncoder;const N="=",Q=t=>{if(t)try{const e=t[0]==="{"?t:D.decode(P(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(P(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,ft=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},yt=(t,e=Y,n=Z,r=tt)=>{const i=n*r/8,p=e*i,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(l,E)=>{for(let d=0;d<E.length;d+=1)s.setUint8(l+d,E.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,p,!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},st=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 p=n.slice(0,i).trim();p.length>0&&e.push(p),n=n.slice(i),r=M.exec(n)}return{rest:n,sentences:e}},pt=async t=>{const{agent:e,compact:n,connectionId:r,env:i,exportName:p,owner:m,paths:s,pcm:u,run:a,send:l,sendAudio:E,signal:d,streamGenerate:C,synthesize:H,text:L,threadKey:o,transcribe:F,turn:U,waitForDrain:O}=t,h=()=>d.aborted,v=T(s.appendMessage),$=T(s.ensureThread),B=T(s.listMessages),b=T(s.patchThread);await a($,{agent:p,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const f=(L??(u?await F(u):"")).trim();if(f.length===0)return await a(b,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};l({text:f,type:"user_transcript"}),await a(v,{content:f,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await a(b,{key:o,status:"running"});const I=typeof e.instructions=="function"?e.instructions({env:i,input:f,threadKey:o}):e.instructions,K=await a(B,{key:o}),{history:j,summary:R}=await z({agent:e,compact:n,env:i},K),W=G({history:j,...I===void 0?{}:{instructions:I},...R===void 0?{}:{summary:R}});let g="",w="",S=Promise.resolve();const V=async c=>{if(h()||c.length===0)return;let x=!1;try{for await(const y of nt(await H(c,d))){if(h()||(await O?.(),h()))break;E(y),x=!0}}catch(y){l({message:y instanceof Error?y.message:String(y),type:"error"})}x&&(w=w.length>0?`${w} ${c}`:c)},_=c=>{S=S.then(async()=>V(c))},X=await C({messages:W,signal:d},c=>{if(h())return;l({text:c,type:"assistant_delta"}),g+=c;const{rest:x,sentences:y}=st(g);g=x;for(const J of y)_(J)});!h()&&g.trim().length>0&&_(g.trim()),g="",await S;const k=h(),A=k?w:X.text;return await a(v,{content:A,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await a(b,{key:o,status:"idle"}),l(k?{type:"interrupted"}:{text:A,type:"assistant_done"}),{assistantText:A,interrupted:k,userText:f}}catch(f){throw await a(b,{key:o,status:"idle"}),f}},lt=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 q(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{dt as a,ft as b,yt as c,ct as d,ht as e,gt as f,ut as i,lt as p,pt as r,nt as t};
|