@lunora/agent 1.0.0-alpha.35 → 1.0.0-alpha.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/channels.d.mts +2 -2
- package/dist/channels.d.ts +2 -2
- package/dist/channels.mjs +1 -1
- package/dist/component.mjs +1 -1
- package/dist/inbound.d.mts +1 -1
- package/dist/inbound.d.ts +1 -1
- package/dist/inbound.mjs +1 -1
- package/dist/index.d.mts +15 -2
- package/dist/index.d.ts +15 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/VoiceSessionDO-bNlFmRop.mjs +1 -0
- package/dist/packem_shared/{agentAsTool-CJCTyAQG.mjs → agentAsTool-gH17BQ8M.mjs} +1 -1
- package/dist/packem_shared/base64-B_qZ_Tyh.mjs +1 -0
- package/dist/packem_shared/branch-marker-DELZqEOQ.mjs +1 -0
- package/dist/packem_shared/{compileAgentWorkflow-C4xqSw82.mjs → compileAgentWorkflow-Bzd8oR9X.mjs} +1 -1
- package/dist/packem_shared/createAgentContext-D1cXHQO2.mjs +1 -0
- package/dist/packem_shared/{createAgentGenerate-BUVImo85.mjs → createAgentGenerate-D96dEdYw.mjs} +3 -3
- package/dist/packem_shared/createDispatchRunner-EYOnoElU-CpVpdTXn.mjs +1 -0
- package/dist/packem_shared/{defineAgent-CKhzzmys.mjs → defineAgent-D0VIzlhu.mjs} +1 -1
- package/dist/packem_shared/runAgentLoop-BHjAmXGh.mjs +3 -0
- package/dist/packem_shared/runVoiceTurn-DhN9Asnn.mjs +1 -0
- package/dist/packem_shared/{sandboxComponent-BhaGHsQZ.mjs → sandboxComponent-CKDGyK4Y.mjs} +1 -1
- package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-BC_N2z6_.d.mts} +24 -7
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-BC_N2z6_.d.ts} +24 -7
- package/dist/packem_shared/voice-turn-DzRKyf-x.mjs +1 -0
- package/dist/sandbox.d.mts +1 -1
- package/dist/sandbox.d.ts +1 -1
- package/package.json +7 -7
- package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
- package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
- package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
- package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
- package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
- package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
package/dist/channels.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-BC_N2z6_.mjs";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-BC_N2z6_.mjs";
|
|
3
3
|
import '@lunora/mail/inbound';
|
|
4
4
|
import 'ai';
|
|
5
5
|
/**
|
package/dist/channels.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-BC_N2z6_.js";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-BC_N2z6_.js";
|
|
3
3
|
import '@lunora/mail/inbound';
|
|
4
4
|
import 'ai';
|
|
5
5
|
/**
|
package/dist/channels.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{h as b,B as v}from"./packem_shared/branch-marker-DELZqEOQ.mjs";const x=300,E=/[^0-9a-f]/iu,A=new TextEncoder,d=e=>new Uint8Array(A.encode(e)),g=e=>{if(e.length%2!==0||E.test(e))throw new f("BAD_REQUEST","@lunora/agent: malformed hex signature");const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r+=1)t[r]=Number.parseInt(e.slice(r*2,r*2+2),16);return t},m=async(e,t,r)=>{try{const a=await crypto.subtle.importKey("raw",d(e),{hash:"SHA-256",name:"HMAC"},!1,["verify"]);return await crypto.subtle.verify("HMAC",a,g(r),d(t))}catch{return!1}},R=(e,t,r)=>Number.isFinite(e)&&Math.abs(t-e)<=r,N=async e=>{const{body:t,now:r=Date.now()/1e3,signature:a,signingSecret:n,timestamp:s,tolerance:o=x}=e;return!a||!s||!a.startsWith("v0=")||!R(Number(s),r,o)?!1:m(n,`v0:${s}:${t}`,a.slice(3))},S=async e=>{const{body:t,secret:r,signature:a}=e;return a?.startsWith("sha256=")?m(r,t,a.slice(7)):!1},k=async e=>{const{body:t,publicKey:r,signature:a,timestamp:n}=e;if(!a||!n)return!1;try{const s=await crypto.subtle.importKey("raw",g(r),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},s,g(a),d(n+t))}catch{return!1}},B=e=>{if(e.has("x-slack-signature"))return"slack";if(e.has("x-hub-signature-256"))return"github";if(e.has("x-signature-ed25519"))return"discord"},C=(e,t)=>{if(typeof e=="function")return e(t);const r=t[e];return typeof r=="string"?r:void 0},D=async(e,t,r,a)=>{switch(e){case"discord":return k({body:a,publicKey:t,signature:r.get("x-signature-ed25519")??void 0,timestamp:r.get("x-signature-timestamp")??void 0});case"github":return S({body:a,secret:t,signature:r.get("x-hub-signature-256")??void 0});case"slack":return N({body:a,signature:r.get("x-slack-signature")??void 0,signingSecret:t,timestamp:r.get("x-slack-request-timestamp")??void 0});default:return!1}},I=(e,t)=>{if(e==="discord")try{if(JSON.parse(t).type===1)return Response.json({type:1})}catch{}},K=/[^\w-]/gu,T=/already[\s-]?exists/iu,u=()=>new Response(void 0,{status:200}),U=e=>T.test(e instanceof Error?e.message:String(e)),_=(e,t,r)=>{if(e==="github")return t.get("x-github-delivery")??void 0;try{const a=JSON.parse(r),n=e==="slack"?a.event_id:a.id;return typeof n=="string"?n:void 0}catch{return}},$=async(e,t,r,a)=>{if(b(t))throw new f("BAD_REQUEST",`@lunora/agent: inbound channel run params ${v}`);const n=a===void 0?"":a.replaceAll(K,"");if(n==="")return await e.create({params:t}),u();try{await e.create({id:`${r}-${n}`.slice(0,60),params:t})}catch(s){if(U(s))return u();throw s}return u()},J=e=>async(t,r)=>{const a=await t.text(),n=B(t.headers);if(n===void 0)return new Response("Unrecognized webhook",{status:400});const s=e.map(i=>({config:i.agent.onInbound,target:i})).filter(i=>i.config?.channel===n),o={channel:n,headers:t.headers,json:()=>JSON.parse(a),rawBody:a};let l=!1;for(const{config:i,target:h}of s){const y=C(i.secret,r);if(y===void 0||!await D(n,y,t.headers,a))continue;l=!0;const p=I(n,a);if(p)return p;const w=await i.map(o);if(!w)continue;const c=r[h.binding];if(!c||typeof c.create!="function")throw new f("INTERNAL",`@lunora/agent: no Workflow binding "${h.binding}" on env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`);return await $(c,w,n,_(n,t.headers,a))}return l?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{J as dispatchAgentChannel,U as isDuplicateInstanceError,k as verifyDiscord,S as verifyGithub,N as verifySlack};
|
package/dist/component.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{LunoraError as w}from"@lunora/errors";import{defineTable as x,initLunora as $,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{i as b,o as k,q as O,s as S,j as F}from"./packem_shared/graph-component-B2YmC2eL.mjs";import{p as ne}from"./packem_shared/graph-component-B2YmC2eL.mjs";import{sandboxComponent as ie}from"./packem_shared/sandboxComponent-
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{defineTable as x,initLunora as $,defineSchemaExtension as j}from"@lunora/server";import{v as e}from"@lunora/values";import{i as b,o as k,q as O,s as S,j as F}from"./packem_shared/graph-component-B2YmC2eL.mjs";import{p as ne}from"./packem_shared/graph-component-B2YmC2eL.mjs";import{sandboxComponent as ie}from"./packem_shared/sandboxComponent-CKDGyK4Y.mjs";const I="agent_episodes",L=5,U=20,B=500,N=200,G=/\s+/gu,z=c=>c===void 0||!Number.isFinite(c)?L:Math.min(U,Math.max(1,Math.trunc(c))),P={episodes:x({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:H,query:J}=$.dataModel().create(),Q=()=>{const c=H.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:u})=>{const l=s.summary.replaceAll(G," ").trim().slice(0,B);if(l.length===0)return{recorded:!1};if(await u.db.query(I).withIndex("byOwnerMessageKey",p=>p.eq("owner",s.owner).eq("messageKey",s.messageKey)).first())return{recorded:!1};await u.db.insert(I,{createdAt:s.createdAt??Date.now(),messageKey:s.messageKey,owner:s.owner,summary:l,...s.threadKey===void 0?{}:{threadKey:s.threadKey}});const g=await u.db.query(I).withIndex("byOwnerCreatedAt",p=>p.eq("owner",s.owner)).order("asc").take(N+1);for(const p of g.slice(0,Math.max(0,g.length-N)))await u.db.delete(p._id);return{recorded:!0}}),v=J.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:s,ctx:u})=>{const l=await u.db.query(I).withIndex("byOwnerCreatedAt",g=>g.eq("owner",s.owner)).order("desc").take(z(s.limit));return l.length===0?{context:""}:{context:l.toReversed().map(g=>`- ${g.summary}`).join(`
|
|
2
2
|
`)}});return{agentEpisodeRecall:b(v),agentEpisodeUpsert:b(c)}},T="threads",R="messages",d=`${k}_${T}`,K=`${k}_${R}`,V=j(k,{tables:{[R]:x({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(),[T]:x({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(),...O,...P}}),{mutation:m,query:q}=$.dataModel().create(),ee=()=>{const c=m.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:a})=>{const r=Date.now(),n=await a.db.query(d).withIndex("byKey",i=>i.eq("key",t.key)).first();if(n){if(n.owner!==t.owner&&t.owner!==void 0)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);const i=n.instanceId;if((n.status==="running"||n.status==="awaiting_input")&&i!==void 0&&(t.instanceId===void 0||t.instanceId!==i)){const o=t.onConcurrentRun??"reject";if(o!=="replace")throw new w("CONFLICT",`@lunora/agent: thread "${t.key}" already has a run in flight (instance "${i}") — onConcurrentRun="${o}"`);return await a.db.patch(n._id,{error:void 0,status:"running",updatedAt:r,...t.instanceId===void 0?{}:{instanceId:t.instanceId}}),{created:!1,priorInstanceId:i,replaced:!0}}return await a.db.patch(n._id,{error:void 0,status:"running",updatedAt:r,...t.instanceId===void 0?{}:{instanceId:t.instanceId}}),{created:!1}}return await a.db.insert(d,{agent:t.agent,createdAt:r,key:t.key,messageCount:0,status:"running",updatedAt:r,...S({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{created:!0}}),v=m.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:a})=>{const r=await a.db.query(K).withIndex("byMessageKey",y=>y.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(r)return{seq:r.seq};const n=await a.db.query(d).withIndex("byKey",y=>y.eq("key",t.threadKey)).first();if(!n)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const i=n.messageCount,o=Date.now();return await a.db.insert(K,{content:t.content,createdAt:o,messageKey:t.messageKey,role:t.role,seq:i,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 a.db.patch(n._id,{messageCount:i+1,updatedAt:o}),{seq:i}}),s=m.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:a})=>{const{instanceId:r,key:n}=t;let i;n!==void 0?i=await a.db.query(d).withIndex("byKey",o=>o.eq("key",n)).first():r!==void 0&&(i=await a.db.query(d).withIndex("byInstance",o=>o.eq("instanceId",r)).first()),i&&await a.db.patch(i._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}})}),u=m.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();r&&await a.db.patch(r._id,{state:t.state,updatedAt:Date.now()})}),l=(t,a)=>{if(!t)return;const{owner:r}=t;if(!(r!==void 0&&r!==(a.userId??void 0)))return t},g=q.input({key:e.string()}).query(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();return l(r,a.auth)}),p=q.input({key:e.string()}).query(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();return l(r,a.auth)?.state}),_=q.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:a})=>{const r=await a.db.query(d).withIndex("byKey",n=>n.eq("key",t.key)).first();return l(r,a.auth)===void 0?[]:t.limit!==void 0?(await a.db.query(K).withIndex("byThread",n=>n.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():a.db.query(K).withIndex("byThread",n=>n.eq("threadKey",t.key)).collect()}),D=m.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:a})=>{const r=await a.db.query(d).withIndex("byKey",h=>h.eq("key",t.threadKey)).first(),n=l(r,a.auth);if(n===void 0)throw new w("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(n.instanceId!==t.instanceId)throw new w("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const i=n.agent,{agents:o}=a,y=o?.[i];if(typeof y?.sendEvent!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${i}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);return await y.sendEvent(t.instanceId,{payload:{decision:t.decision,toolCallId:t.toolCallId,...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),M=m.input({agent:e.string(),input:e.string(),threadKey:e.string(),title:e.optional(e.string())}).mutation(async({args:t,ctx:a})=>{const{agents:r}=a,n=r?.[t.agent];if(typeof n?.run!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${t.agent}"] producer to start a run — run codegen/dev so the agent binding is wired, and check the agent name`);if(n.publicRun!==!0)throw new w("FORBIDDEN",`@lunora/agent: agent "${t.agent}" is not enabled for public runs — set defineAgent({ publicRun: true }) to allow an external client (e.g. the @lunora/mcp server) to start it`);const i=a.auth.userId??void 0,o=await a.db.query(d).withIndex("byKey",h=>h.eq("key",t.threadKey)).first();if(o){const h=o.status,E=o.instanceId,f=o.owner;if((h==="running"||h==="awaiting_input")&&E!==void 0&&(f===void 0||f===i))return{id:E,threadKey:t.threadKey};if(f!==i&&i!==void 0)throw new w("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:y}=await n.run({input:t.input,threadKey:t.threadKey,...i===void 0?{}:{owner:i},...t.title===void 0?{}:{title:t.title}});return{id:y,threadKey:t.threadKey}}),C=F(),A=Q();return{extension:V,functions:{agentAppendMessage:b(v),agentEnsureThread:b(c),agentEpisodeRecall:A.agentEpisodeRecall,agentEpisodeUpsert:A.agentEpisodeUpsert,agentGraphTraverse:C.agentGraphTraverse,agentGraphUpsert:C.agentGraphUpsert,agentMessages:_,agentPatchThread:b(s),agentResolveApproval:D,agentRun:M,agentSetState:b(u),agentState:p,agentThread:g}}};export{ee as agentComponent,V as agentExtension,ne as normalizeEntityName,ie as sandboxComponent};
|
package/dist/inbound.d.mts
CHANGED
package/dist/inbound.d.ts
CHANGED
package/dist/inbound.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{createInboundEmailHandler as u,parseInboundEmail as d}from"@lunora/mail/inbound";import{h as f,B as l}from"./packem_shared/branch-marker-DELZqEOQ.mjs";const E=c=>{const s=u({dispatch:async(o,a)=>{for(const n of c){const t=n.agent.onEmail;if(!t)continue;const r=await t(o);if(r==null)continue;const e=a.env[n.binding];if(!e||typeof e.create!="function")throw new i("INTERNAL",`@lunora/agent: no Workflow binding "${n.binding}" on env for an inbound agent — run codegen/dev so wrangler.jsonc declares it`);if(f(r))throw new i("BAD_REQUEST",`@lunora/agent: inbound run params ${l}`);await e.create({params:r});return}},parse:d});return async(o,a,n)=>s(o,a,n)};export{E as dispatchAgentEmail};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition, c as AgentCompact, d as AgentEpisodeExtract, e as AgentGraphExtract, f as AgentGenerate, g as AgentTokenSink, h as AgentRunInput, i as AgentFunctionPaths, j as AgentRunFunction, k as AgentStepLike, l as AgentStreamGenerate, m as AgentRunResult, n as AgentMessageRow, o as AgentConfig, S as SkillDefinition, p as AnyAgentTool, q as AgentAsToolOptions, r as AgentSubToolInput, b as AgentToolDefinition, s as AgentBindingSpec, t as AgentHandle, u as AgentToolConfig, v as AgentFunctionReference, w as AgentModelInput, x as SkillConfig } from "./packem_shared/types.d-
|
|
2
|
-
export type { y as
|
|
1
|
+
import { A as AgentDefinition, c as AgentCompact, d as AgentEpisodeExtract, e as AgentGraphExtract, f as AgentGenerate, g as AgentTokenSink, h as AgentRunInput, i as AgentFunctionPaths, j as AgentRunFunction, k as AgentStepLike, l as AgentStreamGenerate, m as AgentRunResult, n as AgentMessageRow, o as AgentConfig, S as SkillDefinition, p as AnyAgentTool, q as AgentAsToolOptions, r as AgentSubToolInput, b as AgentToolDefinition, s as AgentBindingSpec, t as AgentHandle, u as AgentToolConfig, v as AgentFunctionReference, w as AgentModelInput, x as SkillConfig } from "./packem_shared/types.d-BC_N2z6_.mjs";
|
|
2
|
+
export type { y as AgentApprovalContext, z as AgentEmailMapper, B as AgentEmailRun, C as AgentGenerateOptions, D as AgentGenerateResult, E as AgentInstructionsContext, F as AgentLiveEvent, G as AgentMemoryOptions, H as AgentMemorySource, J as AgentMessageStatus, K as AgentOnStepFinish, L as AgentPrepareStep, M as AgentPrepareStepInput, N as AgentPrepareStepResult, O as AgentProgressEvent, P as AgentRunHandle, Q as AgentStepFinishInfo, R as AgentStepInfo, T as AgentThreadStatus, U as AgentTokenDelta, V as AgentToolCall, a as AgentToolContext, W as AgentUsage, X as AgentVoiceConfig, Y as AgentWorkflowBindingLike, Z as AgentWorkflowInstanceLike } from "./packem_shared/types.d-BC_N2z6_.mjs";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
5
|
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.mjs";
|
|
@@ -793,6 +793,19 @@ declare class VoiceSessionDO {
|
|
|
793
793
|
private synthesizeWithSignal;
|
|
794
794
|
/** Abort an in-flight turn and free a socket's transient buffers. */
|
|
795
795
|
private cleanupSocket;
|
|
796
|
+
/**
|
|
797
|
+
* Whether `attachment` carries a credential whose expiry (stamped at
|
|
798
|
+
* upgrade) is now past. Delegates to the shared boundary check
|
|
799
|
+
* `@lunora/do`'s `ShardDO` uses for the same decision, so the two DOs can
|
|
800
|
+
* never disagree about it.
|
|
801
|
+
*/
|
|
802
|
+
private isSocketExpired;
|
|
803
|
+
/**
|
|
804
|
+
* Drop an expired-credential socket via the shared `TOKEN_EXPIRED`/`4001`
|
|
805
|
+
* helper `@lunora/do`'s `ShardDO` also calls, so both DOs send the
|
|
806
|
+
* client-facing wire shape from one place.
|
|
807
|
+
*/
|
|
808
|
+
private dropExpiredSocket;
|
|
796
809
|
/** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
|
|
797
810
|
private send;
|
|
798
811
|
/** Send a binary audio frame, swallowing a closed-socket error. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition, c as AgentCompact, d as AgentEpisodeExtract, e as AgentGraphExtract, f as AgentGenerate, g as AgentTokenSink, h as AgentRunInput, i as AgentFunctionPaths, j as AgentRunFunction, k as AgentStepLike, l as AgentStreamGenerate, m as AgentRunResult, n as AgentMessageRow, o as AgentConfig, S as SkillDefinition, p as AnyAgentTool, q as AgentAsToolOptions, r as AgentSubToolInput, b as AgentToolDefinition, s as AgentBindingSpec, t as AgentHandle, u as AgentToolConfig, v as AgentFunctionReference, w as AgentModelInput, x as SkillConfig } from "./packem_shared/types.d-
|
|
2
|
-
export type { y as
|
|
1
|
+
import { A as AgentDefinition, c as AgentCompact, d as AgentEpisodeExtract, e as AgentGraphExtract, f as AgentGenerate, g as AgentTokenSink, h as AgentRunInput, i as AgentFunctionPaths, j as AgentRunFunction, k as AgentStepLike, l as AgentStreamGenerate, m as AgentRunResult, n as AgentMessageRow, o as AgentConfig, S as SkillDefinition, p as AnyAgentTool, q as AgentAsToolOptions, r as AgentSubToolInput, b as AgentToolDefinition, s as AgentBindingSpec, t as AgentHandle, u as AgentToolConfig, v as AgentFunctionReference, w as AgentModelInput, x as SkillConfig } from "./packem_shared/types.d-BC_N2z6_.js";
|
|
2
|
+
export type { y as AgentApprovalContext, z as AgentEmailMapper, B as AgentEmailRun, C as AgentGenerateOptions, D as AgentGenerateResult, E as AgentInstructionsContext, F as AgentLiveEvent, G as AgentMemoryOptions, H as AgentMemorySource, J as AgentMessageStatus, K as AgentOnStepFinish, L as AgentPrepareStep, M as AgentPrepareStepInput, N as AgentPrepareStepResult, O as AgentProgressEvent, P as AgentRunHandle, Q as AgentStepFinishInfo, R as AgentStepInfo, T as AgentThreadStatus, U as AgentTokenDelta, V as AgentToolCall, a as AgentToolContext, W as AgentUsage, X as AgentVoiceConfig, Y as AgentWorkflowBindingLike, Z as AgentWorkflowInstanceLike } from "./packem_shared/types.d-BC_N2z6_.js";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
|
|
4
4
|
import { FlexibleSchema, LanguageModel, ModelMessage } from 'ai';
|
|
5
5
|
export { agentBindingName, agentClassName, agentDefaultName, voiceBindingName, voiceClassName } from "./naming.js";
|
|
@@ -793,6 +793,19 @@ declare class VoiceSessionDO {
|
|
|
793
793
|
private synthesizeWithSignal;
|
|
794
794
|
/** Abort an in-flight turn and free a socket's transient buffers. */
|
|
795
795
|
private cleanupSocket;
|
|
796
|
+
/**
|
|
797
|
+
* Whether `attachment` carries a credential whose expiry (stamped at
|
|
798
|
+
* upgrade) is now past. Delegates to the shared boundary check
|
|
799
|
+
* `@lunora/do`'s `ShardDO` uses for the same decision, so the two DOs can
|
|
800
|
+
* never disagree about it.
|
|
801
|
+
*/
|
|
802
|
+
private isSocketExpired;
|
|
803
|
+
/**
|
|
804
|
+
* Drop an expired-credential socket via the shared `TOKEN_EXPIRED`/`4001`
|
|
805
|
+
* helper `@lunora/do`'s `ShardDO` also calls, so both DOs send the
|
|
806
|
+
* client-facing wire shape from one place.
|
|
807
|
+
*/
|
|
808
|
+
private dropExpiredSocket;
|
|
796
809
|
/** Send a JSON control frame, swallowing a closed-socket error (never throw from a handler). */
|
|
797
810
|
private send;
|
|
798
811
|
/** Send a binary audio frame, swallowing a closed-socket error. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runAgentLoop as t,splitForCompaction as r}from"./packem_shared/runAgentLoop-
|
|
1
|
+
import{runAgentLoop as t,splitForCompaction as r}from"./packem_shared/runAgentLoop-BHjAmXGh.mjs";import{collectAgenticMemoryTools as a,toSearchResults as i}from"./packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as l}from"./packem_shared/agentAsTool-gH17BQ8M.mjs";import{codeTool as p}from"./packem_shared/codeTool-DYJVy-bH.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as A}from"./packem_shared/createAgentContext-D1cXHQO2.mjs";import{defineAgent as d,defineAgentTool as u,isAgentDefinition as N}from"./packem_shared/defineAgent-D0VIzlhu.mjs";import{functionTool as D}from"./packem_shared/functionTool-CWHhkYqd.mjs";import{createAgentGenerate as M,createEpisodeExtract as O,createGraphExtract as _,createStreamGenerate as C,resolveAgentModel as G}from"./packem_shared/createAgentGenerate-D96dEdYw.mjs";import{adaptMcpResult as F,mcpTools as L}from"./packem_shared/adaptMcpResult-18G7zpFo.mjs";import{buildModelMessages as k}from"./packem_shared/buildModelMessages-Dm2wVNQy.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-BXx-tSCe.mjs";import{browserTool as W,containerTool as j,fsTool as q}from"./sandbox.mjs";import{defineSkill as J,isSkillDefinition as Y}from"./packem_shared/defineSkill-DfJxCwfZ.mjs";import{default as $}from"./packem_shared/VoiceSessionDO-bNlFmRop.mjs";import{Q as oe}from"./packem_shared/voice-turn-DzRKyf-x.mjs";import{default as re}from"./packem_shared/compileAgentWorkflow-Bzd8oR9X.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,W as browserTool,k as buildModelMessages,p as codeTool,a as collectAgenticMemoryTools,re as compileAgentWorkflow,j as containerTool,A as createAgentContext,M as createAgentGenerate,O as createEpisodeExtract,_ as createGraphExtract,C as createStreamGenerate,d as defineAgent,u as defineAgentTool,J as defineSkill,q 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 g}from"@lunora/ai";import{A as y}from"./createDispatchRunner-EYOnoElU-CpVpdTXn.mjs";import{a as m}from"./base64-B_qZ_Tyh.mjs";import{X as w,l as b,g as v,p as u,E as l,Y as S,Z as x,e as A,Q as k,P as I}from"./voice-turn-DzRKyf-x.mjs";import{createStreamGenerate as M}from"./createAgentGenerate-D96dEdYw.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as B,toFunctionReference as p}from"./AGENT_MODULE-BXx-tSCe.mjs";const E="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",z=8*1024*1024,F=256*1024,f=15,N=5e3;class L{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,n){this.state=t,this.env=e,this.agent=s,this.exportName=n,this.paths=B,this.ai=g({binding:e.AI,env:e}),this.streamGenerate=M(s,e),this.sttModel=s.voice?.stt??E,this.ttsModel=s.voice?.tts??U}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const e=new URL(t.url).searchParams.get("threadKey");if(!e)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,n=new s,i=n[0],r=n[1];this.state.acceptWebSocket(r);const c=crypto.randomUUID(),a=w(t.headers.get("x-lunora-identity")),d=b(t.headers.get("x-lunora-userid")),o=v(t.headers.get("x-lunora-identity-exp"));if(u(o))return l(r),new Response(null,{status:101,webSocket:i});r.serializeAttachment?.({connectionId:c,threadKey:e,turn:0,...o===void 0?{}:{expiresAt:o},...a===void 0?{}:{identity:a},...d===void 0?{}:{userId:d}}),this.send(r,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const h=this.agent.voice?.greeting;return h&&h.length>0&&this.state.waitUntil?.(this.speakGreeting(r,c,e,d,a,h)),new Response(null,{status:101,webSocket:i})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s){if(this.isSocketExpired(s)){this.dropExpiredSocket(t);return}try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(n){this.send(t,{message:n instanceof Error?n.message:String(n),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const s=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return y({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=S(t);return x(await this.ai.run(this.sttModel,{audio:m(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return A(await this.ai.run(this.ttsModel,{text:t,...s===void 0?{}:{speaker:s}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,s){let n;try{n=JSON.parse(s)}catch{return}if(n.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(this.controllers.has(e.connectionId)){this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(n.type==="commit"){const i=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:i});return}await this.runTurn(t,e,{text:n.text})}bufferAudio(t,e,s){const n=(this.bufferedBytes.get(t)??0)+e.byteLength;if(n>z){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"});return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,n)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((r,c)=>r+c.byteLength,0),n=new Uint8Array(s);let i=0;for(const r of e)n.set(r,i),i+=r.byteLength;return n}async runTurn(t,e,s){const n=new AbortController;this.controllers.set(e.connectionId,n);try{await k({agent:this.agent,connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:n.signal,streamGenerate:this.streamGenerate,synthesize:async(i,r)=>this.synthesizeWithSignal(i,r),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(e.connectionId)===n&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,n,i,r){const c=this.resolveRun(n,i),a=new AbortController,d=()=>a.signal.aborted;this.controllers.set(e,a);try{await c(p(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...n===void 0?{}:{owner:n}});for await(const o of I(await this.synthesizeWithSignal(r,a.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,o)}d()||(await c(p(this.paths.appendMessage),{content:r,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(t,{text:r,type:"assistant_done"}))}catch(o){this.send(t,{message:o instanceof Error?o.message:String(o),type:"error"})}finally{this.controllers.get(e)===a&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}isSocketExpired(t){return u(t.expiresAt)}dropExpiredSocket(t){l(t)}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>F&&s<N;)await new Promise(n=>{setTimeout(n,f)}),s+=f}}export{L as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{jsonSchema as T}from"ai";import{isDuplicateInstanceError as $}from"../channels.mjs";import{agentBindingName as N}from"../naming.mjs";import{toFunctionReference as b,DEFAULT_AGENT_FUNCTION_PATHS as
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{jsonSchema as T}from"ai";import{isDuplicateInstanceError as $}from"../channels.mjs";import{agentBindingName as N}from"../naming.mjs";import{toFunctionReference as b,DEFAULT_AGENT_FUNCTION_PATHS as E}from"./AGENT_MODULE-BXx-tSCe.mjs";const A=new Set(["complete","errored","terminated"]),I=120,S=500,L=e=>e!==null&&typeof e=="object"&&typeof e.status=="string"?e.status:"unknown",k=async e=>{await new Promise(t=>{setTimeout(t,e)})},C=async(e,t,n,u)=>{for(let a=0;a<t;a+=1){const i=L(await e.status());if(A.has(i))return i;await u(n)}return"timeout"},R=e=>{for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},j=e=>{if(typeof e.name!="string"||e.name.length===0)throw new p("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its AGENT_* binding)");if(typeof e.description!="string"||e.description.length===0)throw new p("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");const{name:t}=e,n=N(t),u=e.maxPolls??I,a=e.pollIntervalMs??S,i=e.wait??k,m=b(E.listMessages),f=async(w,r)=>{const o=r.env[n];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new p("INTERNAL",`@lunora/agent: agent.asTool("${t}") found no Workflow binding "${n}" on env — declare the "${t}" agent so codegen wires its binding`);const d=`${r.threadKey}::sub::${t}::${r.toolCallId}`,g=`sub-${t}-${r.toolCallId}`,h={input:w.prompt,threadKey:d};let c;try{const l=await o.create({id:g,params:h});c=await o.get(l.id)}catch(l){if(!$(l))throw l;c=await o.get(g)}const s=await C(c,u,a,i);if(s==="errored"||s==="terminated")return`Sub-agent "${t}" ${s} before producing an answer.`;if(s==="timeout")return`Sub-agent "${t}" did not finish within the allotted time.`;const y=await r.run(m,{key:d});return R(y)};return{description:e.description,execute:f,inputSchema:T({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{j as agentAsTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=e=>{let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)},l=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)r[n]=t.codePointAt(n)??0;return r},a=e=>{const t=e.replaceAll("-","+").replaceAll("_","/"),r=t+"=".repeat((4-t.length%4)%4);return l(r)};export{o as a,l as o,a as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r="__lunoraBranch",e=a=>typeof a=="object"&&a!==null&&Object.hasOwn(a,r),o=`may not contain the reserved workflow branch-marker key ("${r}")`;export{o as B,e as h};
|
package/dist/packem_shared/{compileAgentWorkflow-C4xqSw82.mjs → compileAgentWorkflow-Bzd8oR9X.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineWorkflow as m}from"@lunora/workflow";import{runAgentLoop as i}from"./runAgentLoop-
|
|
1
|
+
import{defineWorkflow as m}from"@lunora/workflow";import{runAgentLoop as i}from"./runAgentLoop-BHjAmXGh.mjs";import{createStreamGenerate as p,createAgentGenerate as c,createEpisodeExtract as l,createGraphExtract as d,createCompact as f}from"./createAgentGenerate-D96dEdYw.mjs";import{agentDefaultName as u}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as v}from"./AGENT_MODULE-BXx-tSCe.mjs";import{A as E}from"./createDispatchRunner-EYOnoElU-CpVpdTXn.mjs";import{otlpTelemetry as N}from"./otlpTelemetry-DcW9mOLV.mjs";const T=(t,r,a)=>r===void 0?t:E({env:a,identity:{userId:r},label:"@lunora/agent"}),y=(t,r,a)=>{const e=r.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||t.telemetry?.isEnabled===!1)return t;const n=typeof r.LUNORA_OTLP_TOKEN=="string"?r.LUNORA_OTLP_TOKEN:void 0,o=[t.telemetry?.integrations].flat().filter(s=>s!==void 0);return{...t,telemetry:{...t.telemetry,integrations:[...o,N({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},G=(t,r,a)=>m({handler:async e=>{const n=y(t,e.env,e.params.threadKey);return i({agent:n,compact:f(),env:e.env,exportName:r,extractGraph:d(),extractEpisode:l(),generate:c(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??v,run:T(e.run,e.params.owner,e.env),step:e.step,streamGenerate:p(n,e.env)})},name:t.name??u(r)});export{G as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as f}from"./createDispatchRunner-EYOnoElU-CpVpdTXn.mjs";import{LunoraError as i}from"@lunora/errors";import{h as g,B as l}from"./branch-marker-DELZqEOQ.mjs";import{toFunctionReference as p,DEFAULT_AGENT_FUNCTION_PATHS as w}from"./AGENT_MODULE-BXx-tSCe.mjs";const h=(r,c,s)=>{const o={},u=p(w.patchThread),d=()=>s??f({env:r,label:"@lunora/agent"});for(const t of c){const a=()=>{const n=r[t.binding];if(!n||typeof n.create!="function"||typeof n.get!="function")throw new i("INTERNAL",`@lunora/agent: no Workflow binding "${t.binding}" on env for agent "${t.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return n};o[t.exportName]={cancel:async n=>{await(await a().get(n)).terminate();try{await d()(u,{instanceId:n,status:"cancelled"})}catch{}},publicRun:t.publicRun===!0,run:async(n,e)=>{if(g(n))throw new i("BAD_REQUEST",`@lunora/agent: run input ${l}`);return{id:(await a().create({...e?.id===void 0?{}:{id:e.id},params:n})).id}},sendEvent:async(n,e)=>{await(await a().get(n)).sendEvent(e)},status:async n=>(await a().get(n)).status()}}return o};export{h as default};
|
package/dist/packem_shared/{createAgentGenerate-BUVImo85.mjs → createAgentGenerate-D96dEdYw.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createAi as T}from"@lunora/ai";import{LunoraError as w}from"@lunora/errors";import{jsonSchema as x,generateText as d,streamText as k,Output as g,tool as j}from"ai";const y=t=>{if(!t)return;const e={};return t.inputTokens!==void 0&&(e.inputTokens=t.inputTokens),t.outputTokens!==void 0&&(e.outputTokens=t.outputTokens),t.totalTokens!==void 0&&(e.totalTokens=t.totalTokens),Object.keys(e).length>0?e:void 0},f=t=>t.map(e=>({id:e.toolCallId,input:e.input,name:e.toolName})),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=e.AI;if(!o)throw new w("INTERNAL",`@lunora/agent: the agent model "${t}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return T({binding:o,env:e}).model(t)}return t},v=(t,e)=>{const o=m(t.model,e),n={};for(const[i,a]of Object.entries(t.tools??{}))n[i]=j({description:a.description,inputSchema:a.inputSchema});const s=t.output===void 0?void 0:g.object({schema:t.output}),r={...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{maxOutputTokens:t.maxOutputTokens},...t.telemetry===void 0?{}:{telemetry:t.telemetry},...t.repairToolCall===void 0?{}:{experimental_repairToolCall:t.repairToolCall}};return{defaultModel:o,output:s,staticSettings:r,tools:n}},b=(t,{activeTools:e,messages:o,model:n,signal:s,toolChoice:r})=>{const{defaultModel:i,output:a,staticSettings:h,tools:l}=t,c=e===void 0?l:Object.fromEntries(Object.entries(l).filter(([p])=>e.includes(p)));return{messages:o,model:n??i,...h,...Object.keys(c).length>0?{tools:c}:{},...r===void 0?{}:{toolChoice:r},...a===void 0?{}:{output:a},...s===void 0?{}:{abortSignal:s}}},N=(t,e)=>{const o=v(t,e);return async n=>{const s=await d(b(o,n)),r=y(s.usage);return{text:s.text,toolCalls:f(s.toolCalls),...r===void 0?{}:{usage:r},...o.output===void 0?{}:{output:s.output}}}}
|
|
2
|
-
`)
|
|
3
|
-
`),G=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{text:s}=await d({model:m(o,e),prompt:A(n,t)});return{summary:s.trim()}},S="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",M=()=>async({env:t,messages:e,model:o})=>{const{text:n}=await d({messages:e,model:m(o,t),system:S});return n.trim()};export{N as createAgentGenerate,M as createCompact,G as createEpisodeExtract
|
|
1
|
+
import{createAi as T}from"@lunora/ai";import{LunoraError as w}from"@lunora/errors";import{jsonSchema as x,generateText as d,streamText as k,Output as g,tool as j}from"ai";const y=t=>{if(!t)return;const e={};return t.inputTokens!==void 0&&(e.inputTokens=t.inputTokens),t.outputTokens!==void 0&&(e.outputTokens=t.outputTokens),t.totalTokens!==void 0&&(e.totalTokens=t.totalTokens),Object.keys(e).length>0?e:void 0},f=t=>t.map(e=>({id:e.toolCallId,input:e.input,name:e.toolName})),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=e.AI;if(!o)throw new w("INTERNAL",`@lunora/agent: the agent model "${t}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return T({binding:o,env:e}).model(t)}return t},v=(t,e)=>{const o=m(t.model,e),n={};for(const[i,a]of Object.entries(t.tools??{}))n[i]=j({description:a.description,inputSchema:a.inputSchema});const s=t.output===void 0?void 0:g.object({schema:t.output}),r={...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{maxOutputTokens:t.maxOutputTokens},...t.telemetry===void 0?{}:{telemetry:t.telemetry},...t.repairToolCall===void 0?{}:{experimental_repairToolCall:t.repairToolCall}};return{defaultModel:o,output:s,staticSettings:r,tools:n}},b=(t,{activeTools:e,messages:o,model:n,signal:s,toolChoice:r})=>{const{defaultModel:i,output:a,staticSettings:h,tools:l}=t,c=e===void 0?l:Object.fromEntries(Object.entries(l).filter(([p])=>e.includes(p)));return{messages:o,model:n??i,...h,...Object.keys(c).length>0?{tools:c}:{},...r===void 0?{}:{toolChoice:r},...a===void 0?{}:{output:a},...s===void 0?{}:{abortSignal:s}}},N=(t,e)=>{const o=v(t,e);return async n=>{const s=await d(b(o,n)),r=y(s.usage);return{text:s.text,toolCalls:f(s.toolCalls),...r===void 0?{}:{usage:r},...o.output===void 0?{}:{output:s.output}}}},$=(t,e)=>{const o=v(t,e);return async(n,s)=>{const r=k(b(o,n));let i="";try{for await(const u of r.textStream)i+=u,s(u)}catch(u){if(n.signal?.aborted)return{text:i,toolCalls:[]};throw u}const[a,h,l,c]=await Promise.all([r.text,r.toolCalls,r.usage,o.output===void 0?Promise.resolve(void 0):r.output]),p=y(l);return{text:a,toolCalls:f(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:c}}}},C=x({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),O=(t,e)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
2
|
+
`),q=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{output:s}=await d({model:m(o,e),output:g.object({schema:C}),prompt:O(n,t)});return s},A=(t,e)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
|
|
3
|
+
`),G=()=>async({assistantText:t,env:e,model:o,userInput:n})=>{const{text:s}=await d({model:m(o,e),prompt:A(n,t)});return{summary:s.trim()}},S="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",M=()=>async({env:t,messages:e,model:o})=>{const{text:n}=await d({messages:e,model:m(o,t),system:S});return n.trim()};export{N as createAgentGenerate,M as createCompact,G as createEpisodeExtract,q as createGraphExtract,$ as createStreamGenerate,m as resolveAgentModel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";const g=t=>{let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)},p=t=>g(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");new TextDecoder;const y=new TextEncoder,f="=",w=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},$=t=>p(y.encode(JSON.stringify(t))),b=t=>!t.startsWith(f)&&w(t)?t:`${f}${p(y.encode(t))}`,m="/_lunora/scheduler/dispatch",I=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},A=(t,e,n)=>{try{const r=JSON.parse(n)?.error;if(typeof r=="object"&&r!==null&&typeof r.code=="string"){const{code:s,data:c,message:i}=r;return new a(s,typeof i=="string"?i:void 0,{data:c,status:e})}}catch{}return new a("INTERNAL",`${t}: function dispatch failed (${String(e)}): ${n}`,{status:e})},R=t=>{const{label:e}=t,n=globalThis.fetch,r=t.fetchImpl??(typeof n=="function"?n.bind(globalThis):void 0);return async(s,c,i={})=>{if(typeof r!="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 a("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const u=t.env.LUNORA_ADMIN_TOKEN;if(typeof u!="string"||u.length===0)throw new a("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const N=`${I(l)}${m}`,h={authorization:`Bearer ${u}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(h["x-lunora-userid"]=b(t.identity.userId)),t.identity?.claims!==void 0&&(h["x-lunora-identity"]=$(t.identity.claims));const o=await r(N,{body:JSON.stringify({args:c??{},functionPath:s.__lunoraRef,shardKey:i.shardKey}),headers:h,method:"POST"});if(!o.ok)throw A(e,o.status,await o.text());const d=await o.text();if(d.length!==0)try{return JSON.parse(d)}catch{throw new a("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(o.status)}): ${d}`,{status:o.status})}}};export{R as A};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as d}from"./agentAsTool-
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-DBcP8dUa.mjs";import{agentAsTool as d}from"./agentAsTool-gH17BQ8M.mjs";import{r as m}from"./memory-DNRyyp1b.mjs";import{SKILL_NAME_PATTERN as h,RESERVED_SKILL_NAME as c}from"./defineSkill-DfJxCwfZ.mjs";const w=/^[a-zA-Z][\w-]*$/u,p=(e,r)=>{const o={...e.tools};for(const n of r)for(const[t,a]of Object.entries(n.tools??{})){if(Object.hasOwn(o,t))throw new s("INTERNAL",`@lunora/agent: skill "${n.name}" tool "${t}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[t]=a}return o},y=(e,r)=>{const o=[];for(const n of[e.instructions,...r.map(t=>t.instructions)])n&&o.push(n);return o.length<=1?o[0]:n=>o.map(t=>typeof t=="function"?t(n):t).filter(t=>t.length>0).join(`
|
|
2
2
|
|
|
3
3
|
`)},N=(e,r)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const n of r)n.knowledge&&m(n.knowledge)&&o.push({key:n.name,...n.knowledge});return o},T=e=>{const r=new Set;for(const o of e){if(typeof o.name!="string"||!h.test(o.name))throw new s("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 s("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(r.has(o.name))throw new s("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)`);r.add(o.name)}},A=(e,r)=>{if(e===void 0)return;const o=Object.keys(r).filter(n=>!e.includes(n));if(o.length>0)throw new s("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(n=>`"${n}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},k=(e,r)=>{const o=(n,t)=>{if(n&&n.kind!=="graph"&&n.kind!=="episodic"&&n.source===void 0)throw new s("INTERNAL",`@lunora/agent: ${t} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const n of r)o(n.knowledge,`skill "${n.name}" \`knowledge\``)},$=e=>{const r=e.model;if(r==null||typeof r=="string"&&r.length===0)throw new s("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&&(!Number.isInteger(e.maxTurns)||e.maxTurns<1))throw new s("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");const o=e.skills??[];T(o),k(e,o);const n=p(e,o),t=f(e,o);for(const[i,g]of Object.entries(t)){if(Object.hasOwn(n,i))throw new s("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);n[i]=g}const a=Object.keys(t).length>0;A(e.activeTools,t);for(const i of Object.keys(n))if(!w.test(i))throw new s("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=N(e,o),u=y(e,o);return{...e,asTool:d,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:u}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:n}:{}}},b=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,j=e=>{if(typeof e.execute!="function")throw new s("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new s("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{$ as defineAgent,j as defineAgentTool,b as isAgentDefinition};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{resolveAgentModel as q}from"./createAgentGenerate-D96dEdYw.mjs";import{i as L,c as T,t as J,n as Q}from"./memory-DNRyyp1b.mjs";import{buildModelMessages as G}from"./buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as V}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-BXx-tSCe.mjs";const W=8,b=e=>e===void 0?"null":JSON.stringify(e),X=e=>e===void 0?[]:Array.isArray(e)?e:[e],Y=async(e,t)=>(await Promise.all(e.map(async a=>a({steps:t})))).some(Boolean),A=(e,t)=>e===void 0&&t===void 0?void 0:(e??0)+(t??0),Z=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const a={},o=A(e.inputTokens,t.inputTokens),r=A(e.outputTokens,t.outputTokens),n=A(e.totalTokens,t.totalTokens);return o!==void 0&&(a.inputTokens=o),r!==void 0&&(a.outputTokens=r),n!==void 0&&(a.totalTokens=n),a},z=async(e,t,a,o,r)=>{const{needsApproval:n}=e;return n===void 0||n===!1?!1:n===!0?!0:a.do(o,async()=>n(t,r))},H=async(e,t)=>{const{instanceId:a,patchThread:o,persist:r,step:n}=e;await r({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 o({status:"awaiting_input"});const i=await n.waitForEvent(`approval:${t.id}`,{type:`agent-approval:${t.id}`});return await o({status:"running"}),{decision:i.payload.decision,...i.payload.note===void 0?{}:{note:i.payload.note}}},tt=async(e,t)=>{const{env:a,getState:o,instanceId:r,onTokenDelta:n,persist:i,run:l,setState:c,step:p,threadKey:s,tools:u}=e,d=`tool:${t.name}:${t.id}`,m=u[t.name],h=`${r}:tool:${t.id}`;if(!m){await i({content:`Error: unknown tool "${t.name}"`,messageKey:h,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const f=$=>{n?.({data:$,kind:"progress",threadKey:s,toolCallId:t.id})},K={env:a,getState:o,idempotencyKey:d,reportProgress:f,run:l,setState:c,threadKey:s,toolCallId:t.id},v={env:a,getState:o,idempotencyKey:d,reportProgress:f,run:l,threadKey:s,toolCallId:t.id},C=`tool:approval-gate:${t.id}`;let x;if(await z(m,t.input,p,C,v)){const{decision:$,note:I}=await H(e,t);if($==="reject"){const N=I===void 0?"":` Reason: ${I}`;await i({content:`Tool "${t.name}" was rejected by the user and not run.${N}`,messageKey:h,role:"tool",status:"rejected",stepName:d,toolCallId:t.id,toolName:t.name});return}x="approved"}const w=await p.do(d,()=>Promise.resolve(m.execute(t.input,K)));await i({content:typeof w=="string"?w:b(w),messageKey:h,role:"tool",stepName:d,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},et=(e,t,a)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:q(t.model,a),toolChoice:t.toolChoice??e.toolChoice}},at=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const a=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=a)return;let o=e.length-a;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},ot=async(e,t)=>{const{agent:a,compact:o,env:r}=e,n=at(t,a.compaction);if(n===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:r,messages:G({history:n.older}),model:a.compaction?.model??a.model});return i.length>0?{history:n.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},st=async(e,t,a)=>{const{agent:o,env:r,generate:n,instructions:i,listMessages:l,memoryContext:c,onTokenDelta:p,run:s,step:u,streamGenerate:d,threadKey:m}=e;return u.do(`llm:turn:${String(t)}`,async()=>{const h=await s(l,{key:m}),{history:f,summary:K}=await ot(e,h);let v={activeTools:o.activeTools,messages:G({history:f,instructions:i,memoryContext:c,summary:K}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(v=et(v,await o.prepareStep({messages:v.messages,stepNumber:t,steps:a}),r));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 d&&p?d(C,x=>{p({text:x,threadKey:m,turn:t})}):n(C)})},E=async(e,t)=>{const{agent:a,step:o}=e;a.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await a.onStepFinish?.(t),!0))},nt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),R=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},rt=e=>{const t={};return e?.depth!==void 0&&(t.depth=e.depth),e?.fanOut!==void 0&&(t.fanOut=e.fanOut),e?.maxNodes!==void 0&&(t.maxNodes=e.maxNodes),e?.maxSeeds!==void 0&&(t.maxSeeds=e.maxSeeds),t},it=async(e,t,a,o)=>{if(e.source===void 0)return;const r=g(e.source),{topK:n}=e,i=T("memory:retrieve",e.key),l=await a.do(i,async()=>o(r,{query:t,...n===void 0?{}:{topK:n}}));return R(l)},dt=async(e,t,a,o,r,n)=>{if(a===void 0)return;const i=T("memory:traverse",e.key),l=await r.do(i,async()=>n(o,{owner:a,query:t,...rt(e.graph)}));return R(l)},lt=async(e,t,a,o,r)=>{if(t===void 0)return;const n=T("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},l=await o.do(n,async()=>r(a,i));return R(l)},ct=async(e,t)=>e.kind==="episodic"?lt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?dt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):it(e,t.input,t.step,t.run),ut=e=>{let t=!1;return e.filter(a=>a.kind!=="episodic"?!0:t?!1:(t=!0,!0))},pt=async(e,t,a,o,r,n)=>{const i=ut(Q(e));if(i.length===0)return;const l=g(o.graphTraverse),c=g(o.episodeRecall),p=[];for(const s of i){const u=await ct(s,{episodeRecall:c,graphTraverse:l,input:t,owner:a,run:n,step:r});u!==void 0&&p.push(u)}return p.length>0?p.join(`
|
|
2
|
+
|
|
3
|
+
`):void 0},mt=async e=>{const{agent:t,env:a,extractGraph:o,finalText:r,input:n,instanceId:i,owner:l,paths:c,run:p,step:s}=e;if(o===void 0||l===void 0||r===void 0||r.length===0)return;const u=L(t);if(u!==void 0)try{const d={assistantText:r,env:a,model:u.graph?.extractionModel??t.model,userInput:n},m=await s.do(T("memory:extract",u.key),async()=>o(d));await p(g(c.graphUpsert),{...m,messageKey:`${i}:${T("extract",u.key)}`,owner:l})}catch{}},yt=async e=>{const{agent:t,env:a,extractEpisode:o,finalText:r,input:n,instanceId:i,owner:l,paths:c,run:p,step:s,threadKey:u}=e;if(o===void 0||l===void 0||r===void 0||r.length===0)return;const d=J(t);if(d!==void 0)try{const m={assistantText:r,env:a,model:d.episodic?.extractionModel??t.model,userInput:n},{summary:h}=await s.do(T("memory:episode",d.key),async()=>o(m));await p(g(c.episodeUpsert),{messageKey:`${i}:${T("episode",d.key)}`,owner:l,summary:h,threadKey:u})}catch{}},vt=async(e,t,a)=>{const o=e[V(t)];if(!(!o||typeof o.get!="function"))try{await(await o.get(a)).terminate()}catch{}},gt=async(e,t,a,o,r)=>{const{instanceId:n,persist:i}=e,l=a.usage===void 0?{}:{usage:a.usage};if(a.toolCalls.length===0){const c=a.output!==void 0&&a.text.length===0?b(a.output):a.text;return await i({content:c,messageKey:`${n}:assistant:${String(t)}`,role:"assistant"}),await E(e,{text:a.text,toolCalls:[],turn:t,...l}),{final:{stopped:"final",text:a.text,turns:t+1,...a.output===void 0?{}:{output:a.output}}}}await i({content:a.text,messageKey:`${n}:assistant:${String(t)}`,role:"assistant",toolCalls:a.toolCalls});for(const c of a.toolCalls)await tt(e,c);if(await E(e,{text:a.text,toolCalls:a.toolCalls,turn:t,...l}),o.push(nt(a)),r.length>0&&await Y(r,o))return"stopCondition"},ht=async(e,t,a,o)=>{const r=[];let n,i=!1,l=0;for(let c=0;c<t;c+=1){const p=await st(e,c,r);o.value=Z(o.value,p.usage),l=c+1;const s=await gt(e,c,p,r,a);if(s==="stopCondition"){i=!0;break}if(s!==void 0){n=s.final;break}}return{final:n,stoppedByCondition:i,turnsRun:l}},kt=async e=>{const{agent:t,compact:a,env:o,exportName:r,extractEpisode:n,extractGraph:i,generate:l,instanceId:c,onTokenDelta:p,params:s,paths:u,run:d,step:m,streamGenerate:h}=e,f=t.maxTurns??W,K=X(t.stopWhen),v=g(u.appendMessage),C=g(u.ensureThread),x=g(u.listMessages),w=g(u.patchThread),$=g(u.setState),I=g(u.state),N=async y=>{await d(v,{threadKey:s.threadKey,...y})},F=async y=>{await d(w,{key:s.threadKey,...y})},j=async()=>await d(I,{key:s.threadKey}),B=async y=>{await d($,{key:s.threadKey,state:y})},M=await d(C,{agent:r,instanceId:c,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}});M?.replaced&&M.priorInstanceId!==void 0&&await vt(o,r,M.priorInstanceId),await N({content:s.input,messageKey:`${c}:user`,role:"user"});const D=await pt(t,s.input,s.owner,u,m,d),O=typeof t.instructions=="function"?t.instructions({env:o,input:s.input,threadKey:s.threadKey}):t.instructions,P={agent:t,compact:a,env:o,generate:l,getState:j,instanceId:c,instructions:O,listMessages:x,memoryContext:D,onTokenDelta:p,patchThread:F,persist:N,run:d,setState:B,step:m,streamGenerate:h,threadKey:s.threadKey,tools:t.tools??{}},S={value:void 0};try{const{final:y,stoppedByCondition:U,turnsRun:_}=await ht(P,f,K,S),k=S.value===void 0?{}:{usage:S.value};return await mt({agent:t,env:o,extractGraph:i,finalText:y?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:m}),await yt({agent:t,env:o,extractEpisode:n,finalText:y?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:m,threadKey:s.threadKey}),y?(await d(w,{key:s.threadKey,status:"idle",...k}),{...y,...k}):U?(await d(w,{key:s.threadKey,status:"idle",...k}),{stopped:"stopCondition",turns:_,...k}):(await d(w,{error:`agent stopped: maxTurns (${String(f)}) reached`,key:s.threadKey,status:"error",...k}),{stopped:"maxTurns",turns:f,...k})}catch(y){throw await d(w,{error:y instanceof Error?y.message:String(y),key:s.threadKey,status:"error",...S.value===void 0?{}:{usage:S.value}}),y}};export{kt as runAgentLoop,at as splitForCompaction};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./base64-B_qZ_Tyh.mjs";import{X as s,Y as i,e as p,Z as n,Q as m,P as d}from"./voice-turn-DzRKyf-x.mjs";import"./buildModelMessages-Dm2wVNQy.mjs";import"./AGENT_MODULE-BXx-tSCe.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,d as toByteIterable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{initLunora as h}from"@lunora/server";import{v as n}from"@lunora/values";import{
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{initLunora as h}from"@lunora/server";import{v as n}from"@lunora/values";import{a as d}from"./base64-B_qZ_Tyh.mjs";const{internalAction:w}=h.dataModel().create(),b=()=>globalThis.document?.documentElement?.outerHTML??"",u=1e6,m=20,y=new TextEncoder,x=async(o,t)=>{const e=t.url??"";switch(t.op){case"content":return o.content(e);case"pdf":return{data:d(await o.pdf(e)),encoding:"base64",mediaType:"application/pdf"};case"scrape":return o.scrape(e,b);case"screenshot":{const r=await o.screenshot(e,{...t.fullPage===void 0?{}:{fullPage:t.fullPage},...t.type===void 0?{}:{type:t.type}});return{data:d(r),encoding:"base64",mediaType:t.type==="jpeg"?"image/jpeg":"image/png"}}default:throw new c("INTERNAL",`@lunora/agent: sandbox browser op "${t.op}" is not supported`)}},T=async(o,t)=>{const e=o.any();if(t.op==="exec")return(await e.fetch("/exec",{body:JSON.stringify({args:t.args??[],command:t.command??""}),headers:{"content-type":"application/json"},method:"POST"})).text();if(t.op==="fetch")return(await e.fetch(t.path??"/",{...t.body===void 0?{}:{body:t.body},method:t.method??"GET"})).text();throw new c("INTERNAL",`@lunora/agent: sandbox container op "${t.op}" is not supported`)},g=o=>{let t=0,e=o.length;for(;t<e&&o[t]==="/";)t+=1;for(;e>t&&o[e-1]==="/";)e-=1;return o.slice(t,e)},E=(o,t)=>{const e=g(o),r=[];for(const a of t.split("/"))if(!(a===""||a===".")){if(a===".."){if(r.length===0)throw new c("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");r.pop();continue}r.push(a)}const i=r.join("/");return e&&i?`${e}/${i}`:e||i},N=async(o,t,e)=>{const r=t.length>0?`${t}/`:"",i=e.length>0?e.length+1:0,a=[];let s;for(let l=0;l<m;l+=1){const p=await o.list({prefix:r,...s===void 0?{}:{cursor:s}});for(const f of p.objects)a.push(f.key.slice(i));if(!p.truncated||p.cursor===void 0)return{entries:a,truncated:!1};s=p.cursor}return{entries:a,truncated:!0}},$=async(o,t,e)=>{const r=g(t),i=E(t,e.path??"");switch(e.op){case"ls":{const{entries:a,truncated:s}=await N(o,i,r);return s?{entries:a,truncated:!0}:{entries:a}}case"read":{const a=await o.head(i);if(a&&a.size>u)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${e.path??""}" is ${String(a.size)} bytes (max ${String(u)})`);const s=await o.get(i);if(!s)throw new c("NOT_FOUND",`@lunora/agent: fs read: no file at "${e.path??""}"`);return s.text()}case"rm":return await o.delete(i),{path:e.path??"",removed:!0};case"stat":{const a=await o.head(i);return a?{exists:!0,size:a.size}:{exists:!1}}case"write":{const a=e.content??"",s=y.encode(a).length;if(s>u)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(s)} bytes exceeds the max (${String(u)})`);return await o.put(i,a),{bytes:s,path:e.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${e.op}" is not supported`)}},S=()=>({invoke:w.input({args:n.optional(n.array(n.string())),body:n.optional(n.string()),bucket:n.optional(n.string()),command:n.optional(n.string()),content:n.optional(n.string()),fullPage:n.optional(n.boolean()),kind:n.union(n.literal("browser"),n.literal("container"),n.literal("fs")),method:n.optional(n.string()),name:n.optional(n.string()),op:n.string(),path:n.optional(n.string()),root:n.optional(n.string()),selector:n.optional(n.string()),type:n.optional(n.string()),url:n.optional(n.string())}).action(async({args:o,ctx:t})=>{const e=t,r=o;if(r.kind==="browser"){if(!e.browser)throw new c("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return x(e.browser,r)}if(r.kind==="fs"){const s=e.env?.[r.bucket??""];if(!s||typeof s.get!="function")throw new c("INTERNAL",`@lunora/agent: sandbox fs op found no R2 bucket "${r.bucket??""}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`);return $(s,r.root??"",r)}const i=r.name??"",a=e.containers?.[i];if(!a)throw new c("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${i}"] — declare the container in lunora/containers.ts and run codegen`);return T(a,r)})});export{E as resolveFsKey,$ as runFsOp,S as sandboxComponent};
|
|
@@ -107,6 +107,17 @@ interface AgentToolContext {
|
|
|
107
107
|
/** The provider-issued tool-call id. */
|
|
108
108
|
toolCallId: string;
|
|
109
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* The READ-ONLY view of {@link AgentToolContext} handed to a `needsApproval`
|
|
112
|
+
* gate function — every field except `setState`. A gate that mutates thread
|
|
113
|
+
* state is a side effect inside a decision predicate, which this type makes a
|
|
114
|
+
* compile-time error rather than a documented-but-unenforced rule: `getState`
|
|
115
|
+
* and `run` stay available (reads are legitimate gate inputs, and the
|
|
116
|
+
* function form is resolved inside its own durable step, so they are
|
|
117
|
+
* replay-safe there too).
|
|
118
|
+
* @experimental
|
|
119
|
+
*/
|
|
120
|
+
type AgentApprovalContext = Omit<AgentToolContext, "setState">;
|
|
110
121
|
/**
|
|
111
122
|
* An agent tool. Unlike a raw AI SDK tool, `execute` is NOT handed to the
|
|
112
123
|
* model call — the loop runs it itself inside a named durable step so a
|
|
@@ -131,13 +142,19 @@ interface AgentToolDefinition<Input = unknown, Output = unknown> {
|
|
|
131
142
|
* On approve the tool runs exactly as normal; on reject it is skipped and a
|
|
132
143
|
* tool result explaining the rejection is persisted so the next turn recovers.
|
|
133
144
|
* A boolean gates statically; a function gates per input. Default: `false`
|
|
134
|
-
* (unchanged behavior).
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
145
|
+
* (unchanged behavior).
|
|
146
|
+
*
|
|
147
|
+
* The boolean/`undefined` forms are compile-time constants re-derived
|
|
148
|
+
* identically on every replay — no durable step. The FUNCTION form runs
|
|
149
|
+
* inside its OWN durable step (`tool:approval-gate:<toolCallId>`, distinct
|
|
150
|
+
* from the tool's own step), so it now runs exactly once per call, not once
|
|
151
|
+
* per replay. It must still be otherwise pure: deterministic given its
|
|
152
|
+
* inputs (no `Date.now()`/`Math.random()`) and free of side effects — the
|
|
153
|
+
* context it receives is {@link AgentApprovalContext}, which has no
|
|
154
|
+
* `setState`; state writes belong only in `execute`, inside the tool's own
|
|
155
|
+
* memoized step.
|
|
139
156
|
*/
|
|
140
|
-
needsApproval?: ((input: Input, context:
|
|
157
|
+
needsApproval?: ((input: Input, context: AgentApprovalContext) => boolean | Promise<boolean>) | boolean;
|
|
141
158
|
}
|
|
142
159
|
/**
|
|
143
160
|
* Author-supplied tool config (see {@link AgentToolDefinition}).
|
|
@@ -1111,4 +1128,4 @@ interface AgentHandle {
|
|
|
1111
1128
|
/** Read a run's workflow status by instance id. */
|
|
1112
1129
|
status: (id: string) => Promise<unknown>;
|
|
1113
1130
|
}
|
|
1114
|
-
export { AgentDefinition as A,
|
|
1131
|
+
export { AgentDefinition as A, AgentEmailRun as B, AgentGenerateOptions as C, AgentGenerateResult as D, AgentInstructionsContext as E, AgentLiveEvent as F, AgentMemoryOptions as G, AgentMemorySource as H, InboundChannelEvent as I, AgentMessageStatus as J, AgentOnStepFinish as K, AgentPrepareStep as L, AgentPrepareStepInput as M, AgentPrepareStepResult as N, AgentProgressEvent as O, AgentRunHandle as P, AgentStepFinishInfo as Q, AgentStepInfo as R, SkillDefinition as S, AgentThreadStatus as T, AgentTokenDelta as U, AgentToolCall as V, AgentUsage as W, AgentVoiceConfig as X, AgentWorkflowBindingLike as Y, AgentWorkflowInstanceLike as Z, AgentToolContext as a, AgentToolDefinition as b, AgentCompact as c, AgentEpisodeExtract as d, AgentGraphExtract as e, AgentGenerate as f, AgentTokenSink as g, AgentRunInput as h, AgentFunctionPaths as i, AgentRunFunction as j, AgentStepLike as k, AgentStreamGenerate as l, AgentRunResult as m, AgentMessageRow as n, AgentConfig as o, AnyAgentTool as p, AgentAsToolOptions as q, AgentSubToolInput as r, AgentBindingSpec as s, AgentHandle as t, AgentToolConfig as u, AgentFunctionReference as v, AgentModelInput as w, SkillConfig as x, AgentApprovalContext as y, AgentEmailMapper as z };
|
|
@@ -107,6 +107,17 @@ interface AgentToolContext {
|
|
|
107
107
|
/** The provider-issued tool-call id. */
|
|
108
108
|
toolCallId: string;
|
|
109
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* The READ-ONLY view of {@link AgentToolContext} handed to a `needsApproval`
|
|
112
|
+
* gate function — every field except `setState`. A gate that mutates thread
|
|
113
|
+
* state is a side effect inside a decision predicate, which this type makes a
|
|
114
|
+
* compile-time error rather than a documented-but-unenforced rule: `getState`
|
|
115
|
+
* and `run` stay available (reads are legitimate gate inputs, and the
|
|
116
|
+
* function form is resolved inside its own durable step, so they are
|
|
117
|
+
* replay-safe there too).
|
|
118
|
+
* @experimental
|
|
119
|
+
*/
|
|
120
|
+
type AgentApprovalContext = Omit<AgentToolContext, "setState">;
|
|
110
121
|
/**
|
|
111
122
|
* An agent tool. Unlike a raw AI SDK tool, `execute` is NOT handed to the
|
|
112
123
|
* model call — the loop runs it itself inside a named durable step so a
|
|
@@ -131,13 +142,19 @@ interface AgentToolDefinition<Input = unknown, Output = unknown> {
|
|
|
131
142
|
* On approve the tool runs exactly as normal; on reject it is skipped and a
|
|
132
143
|
* tool result explaining the rejection is persisted so the next turn recovers.
|
|
133
144
|
* A boolean gates statically; a function gates per input. Default: `false`
|
|
134
|
-
* (unchanged behavior).
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
145
|
+
* (unchanged behavior).
|
|
146
|
+
*
|
|
147
|
+
* The boolean/`undefined` forms are compile-time constants re-derived
|
|
148
|
+
* identically on every replay — no durable step. The FUNCTION form runs
|
|
149
|
+
* inside its OWN durable step (`tool:approval-gate:<toolCallId>`, distinct
|
|
150
|
+
* from the tool's own step), so it now runs exactly once per call, not once
|
|
151
|
+
* per replay. It must still be otherwise pure: deterministic given its
|
|
152
|
+
* inputs (no `Date.now()`/`Math.random()`) and free of side effects — the
|
|
153
|
+
* context it receives is {@link AgentApprovalContext}, which has no
|
|
154
|
+
* `setState`; state writes belong only in `execute`, inside the tool's own
|
|
155
|
+
* memoized step.
|
|
139
156
|
*/
|
|
140
|
-
needsApproval?: ((input: Input, context:
|
|
157
|
+
needsApproval?: ((input: Input, context: AgentApprovalContext) => boolean | Promise<boolean>) | boolean;
|
|
141
158
|
}
|
|
142
159
|
/**
|
|
143
160
|
* Author-supplied tool config (see {@link AgentToolDefinition}).
|
|
@@ -1111,4 +1128,4 @@ interface AgentHandle {
|
|
|
1111
1128
|
/** Read a run's workflow status by instance id. */
|
|
1112
1129
|
status: (id: string) => Promise<unknown>;
|
|
1113
1130
|
}
|
|
1114
|
-
export { AgentDefinition as A,
|
|
1131
|
+
export { AgentDefinition as A, AgentEmailRun as B, AgentGenerateOptions as C, AgentGenerateResult as D, AgentInstructionsContext as E, AgentLiveEvent as F, AgentMemoryOptions as G, AgentMemorySource as H, InboundChannelEvent as I, AgentMessageStatus as J, AgentOnStepFinish as K, AgentPrepareStep as L, AgentPrepareStepInput as M, AgentPrepareStepResult as N, AgentProgressEvent as O, AgentRunHandle as P, AgentStepFinishInfo as Q, AgentStepInfo as R, SkillDefinition as S, AgentThreadStatus as T, AgentTokenDelta as U, AgentToolCall as V, AgentUsage as W, AgentVoiceConfig as X, AgentWorkflowBindingLike as Y, AgentWorkflowInstanceLike as Z, AgentToolContext as a, AgentToolDefinition as b, AgentCompact as c, AgentEpisodeExtract as d, AgentGraphExtract as e, AgentGenerate as f, AgentTokenSink as g, AgentRunInput as h, AgentFunctionPaths as i, AgentRunFunction as j, AgentStepLike as k, AgentStreamGenerate as l, AgentRunResult as m, AgentMessageRow as n, AgentConfig as o, AnyAgentTool as p, AgentAsToolOptions as q, AgentSubToolInput as r, AgentBindingSpec as s, AgentHandle as t, AgentToolConfig as u, AgentFunctionReference as v, AgentModelInput as w, SkillConfig as x, AgentApprovalContext as y, AgentEmailMapper as z };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as $,o as z}from"./base64-B_qZ_Tyh.mjs";import{buildModelMessages as B}from"./buildModelMessages-Dm2wVNQy.mjs";import{toFunctionReference as b}from"./AGENT_MODULE-BXx-tSCe.mjs";const D=new TextDecoder;new TextEncoder;const K="=",G=t=>{if(t)try{const e=t[0]==="{"?t:D.decode($(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},nt=t=>{if(t){if(!t.startsWith(K))return t;try{return D.decode($(t.slice(K.length)))}catch{return}}},rt=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},st=t=>typeof t=="number"&&Date.now()>=t,it=t=>{try{t.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},type:"error"})),t.close?.(4001,"token_expired")}catch{}},q=16e3,C=1,H=16,N=/[^.!?]*[.!?]+\s+/u,Q=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:i}=await e.read();if(n)break;yield i}}finally{e.releaseLock()}return}yield*t},at=(t,e=q,n=C,i=H)=>{const u=n*i/8,y=e*u,d=new ArrayBuffer(44+t.byteLength),r=new DataView(d),s=(U,l)=>{for(let g=0;g<l.length;g+=1)r.setUint8(U+g,l.codePointAt(g)??0)};s(0,"RIFF"),r.setUint32(4,36+t.byteLength,!0),s(8,"WAVE"),s(12,"fmt "),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,n,!0),r.setUint32(24,e,!0),r.setUint32(28,y,!0),r.setUint16(32,u,!0),r.setUint16(34,i,!0),s(36,"data"),r.setUint32(40,t.byteLength,!0);const f=new Uint8Array(d);return f.set(t,44),f},Y=t=>{const e=[];let n=t,i=N.exec(n);for(;i&&i[0].length>0;){const u=i[0],y=u.trim();y.length>0&&e.push(y),n=n.slice(u.length),i=N.exec(n)}return{rest:n,sentences:e}},ot=async t=>{const{agent:e,connectionId:n,env:i,exportName:u,owner:y,paths:d,pcm:r,run:s,send:f,sendAudio:U,signal:l,streamGenerate:g,synthesize:_,text:F,threadKey:c,transcribe:I,turn:k,waitForDrain:L}=t,p=()=>l.aborted,E=b(d.appendMessage),M=b(d.ensureThread),P=b(d.listMessages),A=b(d.patchThread),w=(F??(r?await I(r):"")).trim();if(w.length===0)return{assistantText:"",interrupted:!1,userText:""};f({text:w,type:"user_transcript"}),await s(M,{agent:u,key:c,...e.initialState===void 0?{}:{initialState:e.initialState},...y===void 0?{}:{owner:y}}),await s(E,{content:w,messageKey:`voice:${n}:${String(k)}:user`,role:"user",threadKey:c}),await s(A,{key:c,status:"running"});const T=typeof e.instructions=="function"?e.instructions({env:i,input:w,threadKey:c}):e.instructions,O=await s(P,{key:c}),j=B({history:O,...T===void 0?{}:{instructions:T}});let h="",x="",S=Promise.resolve();const J=async a=>{if(p()||a.length===0)return;let m=!1;try{for await(const o of Q(await _(a,l))){if(p()||(await L?.(),p()))break;U(o),m=!0}}catch(o){f({message:o instanceof Error?o.message:String(o),type:"error"})}m&&(x=x.length>0?`${x} ${a}`:a)},R=a=>{S=S.then(async()=>J(a))};try{const a=await g({messages:j,signal:l},v=>{if(p())return;f({text:v,type:"assistant_delta"}),h+=v;const{rest:V,sentences:W}=Y(h);h=V;for(const X of W)R(X)});!p()&&h.trim().length>0&&R(h.trim()),h="",await S;const m=p(),o=m?x:a.text;return await s(E,{content:o,messageKey:`voice:${n}:${String(k)}:assistant`,role:"assistant",threadKey:c}),await s(A,{key:c,status:"idle"}),f(m?{type:"interrupted"}:{text:o,type:"assistant_done"}),{assistantText:o,interrupted:m,userText:w}}catch(a){throw await s(A,{key:c,status:"idle"}),a}},ct=t=>G(t),ut=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},yt=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 z(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{it as E,Q as P,ot as Q,ct as X,at as Y,ut as Z,yt as e,rt as g,nt as l,st as p};
|
package/dist/sandbox.d.mts
CHANGED
package/dist/sandbox.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/agent",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.37",
|
|
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",
|
|
@@ -76,12 +76,12 @@
|
|
|
76
76
|
"access": "public"
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
|
-
"@lunora/ai": "1.0.0-alpha.
|
|
80
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
81
|
-
"@lunora/mail": "1.0.0-alpha.
|
|
82
|
-
"@lunora/server": "1.0.0-alpha.
|
|
83
|
-
"@lunora/values": "1.0.0-alpha.
|
|
84
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
79
|
+
"@lunora/ai": "1.0.0-alpha.46",
|
|
80
|
+
"@lunora/errors": "1.0.0-alpha.12",
|
|
81
|
+
"@lunora/mail": "1.0.0-alpha.39",
|
|
82
|
+
"@lunora/server": "1.0.0-alpha.58",
|
|
83
|
+
"@lunora/values": "1.0.0-alpha.15",
|
|
84
|
+
"@lunora/workflow": "1.0.0-alpha.17",
|
|
85
85
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
86
86
|
"ai": "7.0.37"
|
|
87
87
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createAi as l}from"@lunora/ai";import{g as f}from"./createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs";import{o as y}from"./base64-jU-Ci6Tu.mjs";import{createStreamGenerate as p}from"./createAgentGenerate-BUVImo85.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as g,toFunctionReference as h}from"./AGENT_MODULE-BXx-tSCe.mjs";import{parseIdentity as m,pcmToWav as b,readTranscriptionText as w,readSynthesisAudio as v,runVoiceTurn as S,toByteIterable as A}from"./runVoiceTurn-PkMsfG_v.mjs";const I="@cf/openai/whisper-large-v3-turbo",k="@cf/deepgram/aura-1",x=8*1024*1024,B=256*1024,u=15,T=5e3;class W{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,s,n){this.state=t,this.env=e,this.agent=s,this.exportName=n,this.paths=g,this.ai=l({binding:e.AI,env:e}),this.streamGenerate=p(s,e),this.sttModel=s.voice?.stt??I,this.ttsModel=s.voice?.tts??k}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const e=new URL(t.url).searchParams.get("threadKey");if(!e)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,n=new s,i=n[0],r=n[1];this.state.acceptWebSocket(r);const c=crypto.randomUUID(),o=m(t.headers.get("x-lunora-identity")),d=t.headers.get("x-lunora-userid")??void 0;r.serializeAttachment?.({connectionId:c,threadKey:e,turn:0,...o===void 0?{}:{identity:o},...d===void 0?{}:{userId:d}}),this.send(r,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const a=this.agent.voice?.greeting;return a&&a.length>0&&this.state.waitUntil?.(this.speakGreeting(r,c,e,d,o,a)),new Response(null,{status:101,webSocket:i})}async webSocketMessage(t,e){const s=t.deserializeAttachment?.();if(s)try{if(typeof e=="string"){await this.handleControl(t,s,e);return}this.bufferAudio(s.connectionId,new Uint8Array(e),t)}catch(n){this.send(t,{message:n instanceof Error?n.message:String(n),type:"error"})}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const s=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return f({env:this.env,label:"@lunora/agent voice",...s===void 0?{}:{identity:s}})}async transcribe(t){const e=b(t);return w(await this.ai.run(this.sttModel,{audio:y(e)}))}async synthesize(t,e){const s=this.agent.voice?.speaker;return v(await this.ai.run(this.ttsModel,{text:t,...s===void 0?{}:{speaker:s}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,s){let n;try{n=JSON.parse(s)}catch{return}if(n.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(this.controllers.has(e.connectionId)){this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(n.type==="commit"){const i=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:i});return}await this.runTurn(t,e,{text:n.text})}bufferAudio(t,e,s){const n=(this.bufferedBytes.get(t)??0)+e.byteLength;if(n>x){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(s,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"});return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,n)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const s=e.reduce((r,c)=>r+c.byteLength,0),n=new Uint8Array(s);let i=0;for(const r of e)n.set(r,i),i+=r.byteLength;return n}async runTurn(t,e,s){const n=new AbortController;this.controllers.set(e.connectionId,n);try{await S({agent:this.agent,connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:n.signal,streamGenerate:this.streamGenerate,synthesize:async(i,r)=>this.synthesizeWithSignal(i,r),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...s.pcm===void 0?{}:{pcm:s.pcm},...s.text===void 0?{}:{text:s.text}})}finally{this.controllers.get(e.connectionId)===n&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,s,n,i,r){const c=this.resolveRun(n,i),o=new AbortController,d=()=>o.signal.aborted;this.controllers.set(e,o);try{await c(h(this.paths.ensureThread),{agent:this.exportName,key:s,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...n===void 0?{}:{owner:n}});for await(const a of A(await this.synthesizeWithSignal(r,o.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,a)}d()||(await c(h(this.paths.appendMessage),{content:r,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:s}),this.send(t,{text:r,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===o&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let s=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>B&&s<T;)await new Promise(n=>{setTimeout(n,u)}),s+=u}}export{W as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const o=n=>{let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)},a=n=>{const e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.codePointAt(r)??0;return t};export{a,o};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{g as d}from"./createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs";import{LunoraError as f}from"@lunora/errors";import{toFunctionReference as g,DEFAULT_AGENT_FUNCTION_PATHS as l}from"./AGENT_MODULE-BXx-tSCe.mjs";const y=(r,i,c)=>{const o={},s=g(l.patchThread),u=()=>c??d({env:r,label:"@lunora/agent"});for(const n of i){const e=()=>{const t=r[n.binding];if(!t||typeof t.create!="function"||typeof t.get!="function")throw new f("INTERNAL",`@lunora/agent: no Workflow binding "${n.binding}" on env for agent "${n.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return t};o[n.exportName]={cancel:async t=>{await(await e().get(t)).terminate();try{await u()(s,{instanceId:t,status:"cancelled"})}catch{}},publicRun:n.publicRun===!0,run:async(t,a)=>({id:(await e().create({...a?.id===void 0?{}:{id:a.id},params:t})).id}),sendEvent:async(t,a)=>{await(await e().get(t)).sendEvent(a)},status:async t=>(await e().get(t)).status()}}return o};export{y as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";const p="/_lunora/scheduler/dispatch",y=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},N=(t,e,r)=>{try{const n=JSON.parse(r)?.error;if(typeof n=="object"&&n!==null&&typeof n.code=="string"){const{code:s,data:c,message:i}=n;return new a(s,typeof i=="string"?i:void 0,{data:c,status:e})}}catch{}return new a("INTERNAL",`${t}: function dispatch failed (${String(e)}): ${r}`,{status:e})},w=t=>{const{label:e}=t,r=globalThis.fetch,n=t.fetchImpl??(typeof r=="function"?r.bind(globalThis):void 0);return async(s,c,i={})=>{if(typeof n!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const u=t.env.LUNORA_ORIGIN_URL;if(typeof u!="string"||u.length===0)throw new a("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const h=t.env.LUNORA_ADMIN_TOKEN;if(typeof h!="string"||h.length===0)throw new a("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const d=`${y(u)}${p}`,l={authorization:`Bearer ${h}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(l["x-lunora-userid"]=t.identity.userId),t.identity?.claims!==void 0&&(l["x-lunora-identity"]=JSON.stringify(t.identity.claims));const o=await n(d,{body:JSON.stringify({args:c??{},functionPath:s.__lunoraRef,shardKey:i.shardKey}),headers:l,method:"POST"});if(!o.ok)throw N(e,o.status,await o.text());const f=await o.text();if(f.length!==0)try{return JSON.parse(f)}catch{throw new a("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(o.status)}): ${f}`,{status:o.status})}}};export{w as g};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{resolveAgentModel as q}from"./createAgentGenerate-BUVImo85.mjs";import{i as L,c as T,t as J,n as Q}from"./memory-DNRyyp1b.mjs";import{buildModelMessages as R}from"./buildModelMessages-Dm2wVNQy.mjs";import{agentBindingName as V}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-BXx-tSCe.mjs";const W=8,E=e=>e===void 0?"null":JSON.stringify(e),X=e=>e===void 0?[]:Array.isArray(e)?e:[e],Y=async(e,t)=>(await Promise.all(e.map(async a=>a({steps:t})))).some(Boolean),I=(e,t)=>e===void 0&&t===void 0?void 0:(e??0)+(t??0),Z=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t};const a={},o=I(e.inputTokens,t.inputTokens),n=I(e.outputTokens,t.outputTokens),i=I(e.totalTokens,t.totalTokens);return o!==void 0&&(a.inputTokens=o),n!==void 0&&(a.outputTokens=n),i!==void 0&&(a.totalTokens=i),a},z=async(e,t,a)=>{const{needsApproval:o}=e;return o===void 0||o===!1?!1:o===!0?!0:o(t,a)},H=async(e,t)=>{const{instanceId:a,patchThread:o,persist:n,step:i}=e;await n({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 o({status:"awaiting_input"});const r=await i.waitForEvent(`approval:${t.id}`,{type:`agent-approval:${t.id}`});return await o({status:"running"}),{decision:r.payload.decision,...r.payload.note===void 0?{}:{note:r.payload.note}}},tt=async(e,t)=>{const{env:a,getState:o,instanceId:n,onTokenDelta:i,persist:r,run:l,setState:c,step:p,threadKey:s,tools:u}=e,d=`tool:${t.name}:${t.id}`,y=u[t.name],h=`${n}:tool:${t.id}`;if(!y){await r({content:`Error: unknown tool "${t.name}"`,messageKey:h,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const w={env:a,getState:o,idempotencyKey:d,reportProgress:f=>{i?.({data:f,kind:"progress",threadKey:s,toolCallId:t.id})},run:l,setState:c,threadKey:s,toolCallId:t.id};let x;if(await z(y,t.input,w)){const{decision:f,note:C}=await H(e,t);if(f==="reject"){const k=C===void 0?"":` Reason: ${C}`;await r({content:`Tool "${t.name}" was rejected by the user and not run.${k}`,messageKey:h,role:"tool",status:"rejected",stepName:d,toolCallId:t.id,toolName:t.name});return}x="approved"}const m=await p.do(d,()=>Promise.resolve(y.execute(t.input,w)));await r({content:typeof m=="string"?m:E(m),messageKey:h,role:"tool",stepName:d,...x===void 0?{}:{status:x},toolCallId:t.id,toolName:t.name})},et=(e,t,a)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:q(t.model,a),toolChoice:t.toolChoice??e.toolChoice}},at=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const a=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=a)return;let o=e.length-a;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},ot=async(e,t)=>{const{agent:a,compact:o,env:n}=e,i=at(t,a.compaction);if(i===void 0||o===void 0)return{history:t,summary:void 0};try{const r=await o({env:n,messages:R({history:i.older}),model:a.compaction?.model??a.model});return r.length>0?{history:i.recent,summary:r}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},st=async(e,t,a)=>{const{agent:o,env:n,generate:i,instructions:r,listMessages:l,memoryContext:c,onTokenDelta:p,run:s,step:u,streamGenerate:d,threadKey:y}=e;return u.do(`llm:turn:${String(t)}`,async()=>{const h=await s(l,{key:y}),{history:w,summary:x}=await ot(e,h);let m={activeTools:o.activeTools,messages:R({history:w,instructions:r,memoryContext:c,summary:x}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(m=et(m,await o.prepareStep({messages:m.messages,stepNumber:t,steps:a}),n));const f={messages:m.messages,...m.activeTools===void 0?{}:{activeTools:m.activeTools},...m.model===void 0?{}:{model:m.model},...m.toolChoice===void 0?{}:{toolChoice:m.toolChoice}};return d&&p?d(f,C=>{p({text:C,threadKey:y,turn:t})}):i(f)})},A=async(e,t)=>{const{agent:a,step:o}=e;a.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await a.onStepFinish?.(t),!0))},nt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),N=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},it=e=>{const t={};return e?.depth!==void 0&&(t.depth=e.depth),e?.fanOut!==void 0&&(t.fanOut=e.fanOut),e?.maxNodes!==void 0&&(t.maxNodes=e.maxNodes),e?.maxSeeds!==void 0&&(t.maxSeeds=e.maxSeeds),t},rt=async(e,t,a,o)=>{if(e.source===void 0)return;const n=g(e.source),{topK:i}=e,r=T("memory:retrieve",e.key),l=await a.do(r,async()=>o(n,{query:t,...i===void 0?{}:{topK:i}}));return N(l)},dt=async(e,t,a,o,n,i)=>{if(a===void 0)return;const r=T("memory:traverse",e.key),l=await n.do(r,async()=>i(o,{owner:a,query:t,...it(e.graph)}));return N(l)},lt=async(e,t,a,o,n)=>{if(t===void 0)return;const i=T("memory:recall",e.key),r={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},l=await o.do(i,async()=>n(a,r));return N(l)},ct=async(e,t)=>e.kind==="episodic"?lt(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?dt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):rt(e,t.input,t.step,t.run),ut=e=>{let t=!1;return e.filter(a=>a.kind!=="episodic"?!0:t?!1:(t=!0,!0))},pt=async(e,t,a,o,n,i)=>{const r=ut(Q(e));if(r.length===0)return;const l=g(o.graphTraverse),c=g(o.episodeRecall),p=[];for(const s of r){const u=await ct(s,{episodeRecall:c,graphTraverse:l,input:t,owner:a,run:i,step:n});u!==void 0&&p.push(u)}return p.length>0?p.join(`
|
|
2
|
-
|
|
3
|
-
`):void 0},mt=async e=>{const{agent:t,env:a,extractGraph:o,finalText:n,input:i,instanceId:r,owner:l,paths:c,run:p,step:s}=e;if(o===void 0||l===void 0||n===void 0||n.length===0)return;const u=L(t);if(u!==void 0)try{const d={assistantText:n,env:a,model:u.graph?.extractionModel??t.model,userInput:i},y=await s.do(T("memory:extract",u.key),async()=>o(d));await p(g(c.graphUpsert),{...y,messageKey:`${r}:${T("extract",u.key)}`,owner:l})}catch{}},yt=async e=>{const{agent:t,env:a,extractEpisode:o,finalText:n,input:i,instanceId:r,owner:l,paths:c,run:p,step:s,threadKey:u}=e;if(o===void 0||l===void 0||n===void 0||n.length===0)return;const d=J(t);if(d!==void 0)try{const y={assistantText:n,env:a,model:d.episodic?.extractionModel??t.model,userInput:i},{summary:h}=await s.do(T("memory:episode",d.key),async()=>o(y));await p(g(c.episodeUpsert),{messageKey:`${r}:${T("episode",d.key)}`,owner:l,summary:h,threadKey:u})}catch{}},vt=async(e,t,a)=>{const o=e[V(t)];if(!(!o||typeof o.get!="function"))try{await(await o.get(a)).terminate()}catch{}},gt=async(e,t,a,o,n)=>{const{instanceId:i,persist:r}=e,l=a.usage===void 0?{}:{usage:a.usage};if(a.toolCalls.length===0){const c=a.output!==void 0&&a.text.length===0?E(a.output):a.text;return await r({content:c,messageKey:`${i}:assistant:${String(t)}`,role:"assistant"}),await A(e,{text:a.text,toolCalls:[],turn:t,...l}),{final:{stopped:"final",text:a.text,turns:t+1,...a.output===void 0?{}:{output:a.output}}}}await r({content:a.text,messageKey:`${i}:assistant:${String(t)}`,role:"assistant",toolCalls:a.toolCalls});for(const c of a.toolCalls)await tt(e,c);if(await A(e,{text:a.text,toolCalls:a.toolCalls,turn:t,...l}),o.push(nt(a)),n.length>0&&await Y(n,o))return"stopCondition"},ht=async(e,t,a,o)=>{const n=[];let i,r=!1,l=0;for(let c=0;c<t;c+=1){const p=await st(e,c,n);o.value=Z(o.value,p.usage),l=c+1;const s=await gt(e,c,p,n,a);if(s==="stopCondition"){r=!0;break}if(s!==void 0){i=s.final;break}}return{final:i,stoppedByCondition:r,turnsRun:l}},Ct=async e=>{const{agent:t,compact:a,env:o,exportName:n,extractEpisode:i,extractGraph:r,generate:l,instanceId:c,onTokenDelta:p,params:s,paths:u,run:d,step:y,streamGenerate:h}=e,w=t.maxTurns??W,x=X(t.stopWhen),m=g(u.appendMessage),f=g(u.ensureThread),C=g(u.listMessages),k=g(u.patchThread),b=g(u.setState),F=g(u.state),M=async v=>{await d(m,{threadKey:s.threadKey,...v})},G=async v=>{await d(k,{key:s.threadKey,...v})},j=async()=>await d(F,{key:s.threadKey}),B=async v=>{await d(b,{key:s.threadKey,state:v})},S=await d(f,{agent:n,instanceId:c,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}});S?.replaced&&S.priorInstanceId!==void 0&&await vt(o,n,S.priorInstanceId),await M({content:s.input,messageKey:`${c}:user`,role:"user"});const D=await pt(t,s.input,s.owner,u,y,d),O=typeof t.instructions=="function"?t.instructions({env:o,input:s.input,threadKey:s.threadKey}):t.instructions,P={agent:t,compact:a,env:o,generate:l,getState:j,instanceId:c,instructions:O,listMessages:C,memoryContext:D,onTokenDelta:p,patchThread:G,persist:M,run:d,setState:B,step:y,streamGenerate:h,threadKey:s.threadKey,tools:t.tools??{}},$={value:void 0};try{const{final:v,stoppedByCondition:U,turnsRun:_}=await ht(P,w,x,$),K=$.value===void 0?{}:{usage:$.value};return await mt({agent:t,env:o,extractGraph:r,finalText:v?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:y}),await yt({agent:t,env:o,extractEpisode:i,finalText:v?.text,input:s.input,instanceId:c,owner:s.owner,paths:u,run:d,step:y,threadKey:s.threadKey}),v?(await d(k,{key:s.threadKey,status:"idle",...K}),{...v,...K}):U?(await d(k,{key:s.threadKey,status:"idle",...K}),{stopped:"stopCondition",turns:_,...K}):(await d(k,{error:`agent stopped: maxTurns (${String(w)}) reached`,key:s.threadKey,status:"error",...K}),{stopped:"maxTurns",turns:w,...K})}catch(v){throw await d(k,{error:v instanceof Error?v.message:String(v),key:s.threadKey,status:"error",...$.value===void 0?{}:{usage:$.value}}),v}};export{Ct as runAgentLoop,at as splitForCompaction};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as W}from"./base64-jU-Ci6Tu.mjs";import{buildModelMessages as z}from"./buildModelMessages-Dm2wVNQy.mjs";import{toFunctionReference as x}from"./AGENT_MODULE-BXx-tSCe.mjs";const G=16e3,J=1,q=16,K=/[^.!?]*[.!?]+\s+/u,C=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:s}=await e.read();if(n)break;yield s}}finally{e.releaseLock()}return}yield*t},Y=(t,e=G,n=J,s=q)=>{const u=n*s/8,y=e*u,f=new ArrayBuffer(44+t.byteLength),r=new DataView(f),a=(U,l)=>{for(let g=0;g<l.length;g+=1)r.setUint8(U+g,l.codePointAt(g)??0)};a(0,"RIFF"),r.setUint32(4,36+t.byteLength,!0),a(8,"WAVE"),a(12,"fmt "),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,n,!0),r.setUint32(24,e,!0),r.setUint32(28,y,!0),r.setUint16(32,u,!0),r.setUint16(34,s,!0),a(36,"data"),r.setUint32(40,t.byteLength,!0);const d=new Uint8Array(f);return d.set(t,44),d},H=t=>{const e=[];let n=t,s=K.exec(n);for(;s&&s[0].length>0;){const u=s[0],y=u.trim();y.length>0&&e.push(y),n=n.slice(u.length),s=K.exec(n)}return{rest:n,sentences:e}},Z=async t=>{const{agent:e,connectionId:n,env:s,exportName:u,owner:y,paths:f,pcm:r,run:a,send:d,sendAudio:U,signal:l,streamGenerate:g,synthesize:F,text:I,threadKey:c,transcribe:L,turn:T,waitForDrain:M}=t,p=()=>l.aborted,v=x(f.appendMessage),j=x(f.ensureThread),V=x(f.listMessages),A=x(f.patchThread),w=(I??(r?await L(r):"")).trim();if(w.length===0)return{assistantText:"",interrupted:!1,userText:""};d({text:w,type:"user_transcript"}),await a(j,{agent:u,key:c,...e.initialState===void 0?{}:{initialState:e.initialState},...y===void 0?{}:{owner:y}}),await a(v,{content:w,messageKey:`voice:${n}:${String(T)}:user`,role:"user",threadKey:c}),await a(A,{key:c,status:"running"});const k=typeof e.instructions=="function"?e.instructions({env:s,input:w,threadKey:c}):e.instructions,_=await a(V,{key:c}),B=z({history:_,...k===void 0?{}:{instructions:k}});let h="",b="",S=Promise.resolve();const D=async i=>{if(p()||i.length===0)return;let m=!1;try{for await(const o of C(await F(i,l))){if(p()||(await M?.(),p()))break;U(o),m=!0}}catch(o){d({message:o instanceof Error?o.message:String(o),type:"error"})}m&&(b=b.length>0?`${b} ${i}`:i)},R=i=>{S=S.then(async()=>D(i))};try{const i=await g({messages:B,signal:l},$=>{if(p())return;d({text:$,type:"assistant_delta"}),h+=$;const{rest:E,sentences:N}=H(h);h=E;for(const P of N)R(P)});!p()&&h.trim().length>0&&R(h.trim()),h="",await S;const m=p(),o=m?b:i.text;return await a(v,{content:o,messageKey:`voice:${n}:${String(T)}:assistant`,role:"assistant",threadKey:c}),await a(A,{key:c,status:"idle"}),d(m?{type:"interrupted"}:{text:o,type:"assistant_done"}),{assistantText:o,interrupted:m,userText:w}}catch(i){throw await a(A,{key:c,status:"idle"}),i}},tt=t=>{if(t)try{const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:void 0}catch{return}},et=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},nt=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 W(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{tt as parseIdentity,Y as pcmToWav,nt as readSynthesisAudio,et as readTranscriptionText,Z as runVoiceTurn,C as toByteIterable};
|