@lunora/agent 1.0.0-alpha.251 → 1.0.0-alpha.253

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.
@@ -1,2 +1,2 @@
1
- import{LunoraError as m}from"@lunora/errors";import{SecretValueTooLargeError as we}from"@lunora/platform";import{defineTable as k,initLunora as W,defineSchemaExtension as Ie}from"@lunora/server";import{v as e}from"@lunora/values";import{a as v,A as S,d as G,b as be,c as ge,S as fe}from"./packem_shared/component-shared-DdXFbng-.mjs";import{graphTables as qe,graphComponent as Ae}from"./packem_shared/normalizeEntityName-CmalZhT_.mjs";import{normalizeEntityName as et}from"./packem_shared/normalizeEntityName-CmalZhT_.mjs";import{sandboxComponent as nt}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const D="agent_episodes",Ke=5,ve=20,Te=500,j=200,Ce=/\s+/gu,Ee=s=>s===void 0||!Number.isFinite(s)?Ke:Math.min(ve,Math.max(1,Math.trunc(s))),_e={episodes:k({createdAt:e.number(),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).index("byOwnerCreatedAt",["owner","createdAt"]).index("byOwnerMessageKey",["owner","messageKey"],{unique:!0}).public()},{mutation:ke,query:Se}=W.dataModel().create(),Ne=()=>{const s=ke.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:l,ctx:u})=>{const c=l.summary.replaceAll(Ce," ").trim().slice(0,Te);if(c.length===0)return{recorded:!1};if(await u.db.query(D).withIndex("byOwnerMessageKey",y=>y.eq("owner",l.owner).eq("messageKey",l.messageKey)).first())return{recorded:!1};await u.db.insert(D,{createdAt:l.createdAt??Date.now(),messageKey:l.messageKey,owner:l.owner,summary:c,...l.threadKey===void 0?{}:{threadKey:l.threadKey}});const q=await u.db.query(D).withIndex("byOwnerCreatedAt",y=>y.eq("owner",l.owner)).order("asc").take(j+1);for(const y of q.slice(0,Math.max(0,q.length-j)))await u.db.delete(y._id);return{recorded:!0}}),o=Se.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:l,ctx:u})=>{const c=await u.db.query(D).withIndex("byOwnerCreatedAt",h=>h.eq("owner",l.owner)).order("desc").take(Ee(l.limit));return c.length===0?{context:""}:{context:c.toReversed().map(h=>`- ${h.summary}`).join(`
2
- `)}});return{agentEpisodeRecall:v(o),agentEpisodeUpsert:v(s)}},Y="threads",z="messages",J="run_queue",Z="approval_grants",ee="secret_requests",f=`${S}_${Y}`,C=`${S}_${z}`,x=`${S}_${J}`,$=`${S}_${Z}`,M=`${S}_${ee}`,Re=50,xe=200,$e=500,H=5,P=e.object({cacheReadTokens:e.optional(e.number()),cacheWriteTokens:e.optional(e.number()),inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),reasoningTokens:e.optional(e.number()),status:e.optional(e.union(e.literal("complete"),e.literal("partial"),e.literal("unavailable"))),totalTokens:e.optional(e.number())}),De=780*60*1e3,Oe=Ie(S,{tables:{[z]:k({approvalScope:e.optional(e.literal("thread")),content:e.string(),createdAt:e.number(),expiresAt:e.optional(e.number()),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),seq:e.number(),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("awaiting_secret"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).index("byThread",["threadKey","seq"]).index("byMessageKey",["threadKey","messageKey"],{unique:!0}).public(),[Y]:k({agent:e.string(),createdAt:e.number(),error:e.optional(e.string().nullable()),completedInstanceId:e.optional(e.string().nullable()),instanceId:e.optional(e.string()),key:e.string(),messageCount:e.number(),owner:e.optional(e.string()),state:e.optional(e.any()),status:e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input")),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(P)}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).index("byOwnerStatus",["owner","status","updatedAt"]).public(),[J]:k({agent:e.string(),enqueuedAt:e.number(),instanceId:e.string(),position:e.number(),threadKey:e.string()}).index("byThread",["threadKey","position"]).index("byThreadInstance",["threadKey","instanceId"],{unique:!0}).public(),[Z]:k({createdAt:e.number(),threadKey:e.string(),toolName:e.string()}).index("byThreadTool",["threadKey","toolName"],{unique:!0}).public(),[ee]:k({consumerTool:e.string(),createdAt:e.number(),expiresAt:e.number(),instanceId:e.string(),ref:e.optional(e.string().nullable()),label:e.optional(e.string().nullable()),status:e.union(e.literal("pending"),e.literal("supplied"),e.literal("declined"),e.literal("expired"),e.literal("consumed")),threadKey:e.string(),toolCallId:e.string(),callId:e.optional(e.string()),toolName:e.string(),updatedAt:e.number()}).index("byThreadCall",["threadKey","toolCallId"],{unique:!0}).index("byThreadCallId",["threadKey","callId"]).public(),...qe,..._e}}),{mutation:A,query:_}=W.dataModel().create(),Me=async(s,o,l,u)=>{const c=await s.query(C).withIndex("byMessageKey",N=>N.eq("threadKey",o).eq("messageKey",`${l}:approval:${u}`)).first();if(c?.status!=="awaiting_approval")throw new m("CONFLICT",`@lunora/agent: no pending approval for tool call "${u}" to grant for thread "${o}"`);const{expiresAt:h}=c;if(typeof h!="number")throw new m("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${o}" has no recorded deadline, so it cannot be granted for the thread`);if(Date.now()>=h)throw new m("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${o}" has timed out`);const q=c.toolName;await s.query($).withIndex("byThreadTool",N=>N.eq("threadKey",o).eq("toolName",q)).first()||await s.insert($,{createdAt:Date.now(),threadKey:o,toolName:q})},Le=async(s,o,l,u)=>(await s.query(C).withIndex("byMessageKey",h=>h.eq("threadKey",o).eq("messageKey",`${l}:approval:${u}`)).first())?.status==="awaiting_approval",Be=async(s,o,l,u)=>{const c=await s.query(C).withIndex("byMessageKey",h=>h.eq("threadKey",o).eq("messageKey",`${l}:approval:${u}`)).first();c?.status==="awaiting_approval"&&await s.delete(c._id)},L=s=>{const{agentSecrets:o}=s;if(o===void 0)throw new m("NOT_IMPLEMENTED","@lunora/agent: no secret store is wired on this deployment. Codegen wires one only when a source in lunora/ value-imports requestSecretTool from @lunora/agent (directly, through a namespace import, or through a relative barrel that re-exports it); add that import, or this target cannot hold a human-supplied secret value");return o},O=(s,o,l)=>{const u=o.userId??void 0;if(s===null||u===void 0||s.owner!==u)throw new m("FORBIDDEN",`@lunora/agent: only the thread's owner can ${l}`);return s},V=async(s,o,l)=>{const{instanceId:u,key:c}=o,h=typeof u=="string"?await s.query(C).withIndex("byMessageKey",q=>q.eq("threadKey",c).eq("messageKey",`${u}:secret:${l}`)).first():void 0;if(h?.status!=="awaiting_secret")throw new m("CONFLICT",`@lunora/agent: no pending secret request for tool call "${l}" on thread "${c}"`);return h},R=async(s,o,l)=>await s.query(M).withIndex("byThreadCall",c=>c.eq("threadKey",o).eq("toolCallId",l)).first()??void 0,X=async(s,o,l,u,c)=>{const q=(await s.query(M).withIndex("byThreadCallId",y=>y.eq("threadKey",o).eq("callId",u)).collect()).filter(y=>y.status==="pending"&&y.instanceId===l&&c<y.expiresAt);if(q.length!==1)throw new m("CONFLICT",`@lunora/agent: no pending secret request for tool call "${u}" on thread "${o}"`);return q[0]},Pe=(s,o)=>Math.max(ge,s+fe-o),B=async(s,o,l,u)=>{const c=await R(s,o,l);if(c?.status!=="pending"||u>=c.expiresAt)throw new m("CONFLICT",`@lunora/agent: no open secret request for tool call "${l}" on thread "${o}"`);return c},Q=(s,o)=>{const{instanceId:l}=o,{agents:u}=s,c=u?.[o.agent];if(typeof l!="string"||typeof c?.sendEvent!="function")throw new m("INTERNAL",`@lunora/agent: no ctx.agents["${String(o.agent)}"] producer to deliver the secret — run codegen/dev`);return{instanceId:l,sendEvent:c.sendEvent}},Ue=async(s,o,l)=>{if(o.instanceId===void 0)throw new m("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:u}=o,c=await s.query(x).withIndex("byThreadInstance",y=>y.eq("threadKey",o.key).eq("instanceId",u)).first();if(c)return{outcome:"queued",position:c.position};const h=await s.query(x).withIndex("byThread",y=>y.eq("threadKey",o.key)).collect();if(h.length>=H)throw new m("CONFLICT",`@lunora/agent: thread "${o.key}" run queue is full (depth ${String(H)}) — rejecting instance "${u}"`);const q=(h.at(-1)?.position??-1)+1;return await s.insert(x,{agent:o.agent,enqueuedAt:l,instanceId:u,position:q,threadKey:o.key}),{outcome:"queued",position:q}},Fe=async(s,o,l)=>{if(o.policy==="queue")return Ue(s,{agent:o.agent,instanceId:o.instanceId,key:o.key,priorInstanceId:o.priorInstanceId},l);if(o.policy!=="replace")throw new m("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — onConcurrentRun="${o.policy}"`);return await s.patch(o.existingId,{error:null,status:"running",updatedAt:l,...o.instanceId===void 0?{}:{completedInstanceId:null,instanceId:o.instanceId}}),{outcome:"replaced",priorInstanceId:o.priorInstanceId}},Ge=(s,o,l)=>{const u=s.instanceId;if(u===void 0||o===u||s.status!=="running"&&s.status!=="awaiting_input")return;const c=typeof s.updatedAt=="number"?s.updatedAt:0,h=s.status==="awaiting_input"?be:De;return l-c>h?void 0:u},ze=()=>{const s=A.input({agent:e.string(),initialState:e.optional(e.any()),instanceId:e.optional(e.string()),key:e.string(),onConcurrentRun:e.optional(e.union(e.literal("reject"),e.literal("queue"),e.literal("replace"))),owner:e.optional(e.string()),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(f).withIndex("byKey",r=>r.eq("key",t.key)).first();if(i){if(i.owner!==t.owner)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);if(t.instanceId!==void 0&&i.completedInstanceId===t.instanceId)return{outcome:"completed"};const r=Ge(i,t.instanceId,a);return r!==void 0?Fe(n.db,{agent:t.agent,existingId:i._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:r},a):(await n.db.patch(i._id,{error:null,status:"running",updatedAt:a,...t.instanceId===void 0?{}:{completedInstanceId:null,instanceId:t.instanceId}}),{outcome:"continued"})}return await n.db.insert(f,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...G({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),o=A.input({approvalScope:e.optional(e.literal("thread")),content:e.string(),expiresAt:e.optional(e.number()),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("awaiting_secret"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(C).withIndex("byMessageKey",w=>w.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const i=await n.db.query(f).withIndex("byKey",w=>w.eq("key",t.threadKey)).first();if(!i)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const r=i.messageCount,d=Date.now();return await n.db.insert(C,{content:t.content,createdAt:d,messageKey:t.messageKey,role:t.role,seq:r,threadKey:t.threadKey,...t.approvalScope===void 0?{}:{approvalScope:t.approvalScope},...t.expiresAt===void 0?{}:{expiresAt:t.expiresAt},...t.status===void 0?{}:{status:t.status},...t.stepName===void 0?{}:{stepName:t.stepName},...t.toolCallId===void 0?{}:{toolCallId:t.toolCallId},...t.toolCalls===void 0?{}:{toolCalls:t.toolCalls},...t.toolName===void 0?{}:{toolName:t.toolName}}),await n.db.patch(i._id,{messageCount:r+1,updatedAt:d}),{seq:r}}),l=A.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(C).withIndex("byMessageKey",i=>i.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(a._id)}),u=A.input({error:e.optional(e.string()),ifInstanceId:e.optional(e.string()),instanceId:e.optional(e.string()),key:e.optional(e.string()),status:e.optional(e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input"))),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),usage:e.optional(P)}).mutation(async({args:t,ctx:n})=>{const{instanceId:a,key:i}=t;let r;i!==void 0?r=await n.db.query(f).withIndex("byKey",d=>d.eq("key",i)).first():a!==void 0&&(r=await n.db.query(f).withIndex("byInstance",d=>d.eq("instanceId",a)).first()),!(!r||t.ifInstanceId!==void 0&&r.instanceId!==t.ifInstanceId)&&await n.db.patch(r._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.summary===void 0?{}:{summary:t.summary},...t.summaryConfig===void 0?{}:{summaryConfig:t.summaryConfig},...t.summaryRebuiltSeq===void 0?{}:{summaryRebuiltSeq:t.summaryRebuiltSeq},...t.summaryThroughSeq===void 0?{}:{summaryThroughSeq:t.summaryThroughSeq},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),c=_.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(f).withIndex("byKey",g=>g.eq("key",t.key)).first(),i=a?.summary,r=a?.summaryThroughSeq,d=a?.summaryRebuiltSeq,w=a?.summaryConfig,I=typeof i=="string"&&i.length>0&&typeof r=="number",b=t.configKey===void 0||w===t.configKey,p=typeof d!="number"||typeof r=="number"&&r>=2*d+1,T=I&&b&&!p,K=await n.db.query(C).withIndex("byThread",g=>T?g.eq("threadKey",t.key).gt("seq",r):g.eq("threadKey",t.key)).collect();return T?{messages:K,summary:i}:I?{fallback:{summary:i,throughSeq:r},messages:K}:{messages:K}}),h=A.input({error:e.optional(e.string()),instanceId:e.string(),key:e.string(),status:e.union(e.literal("idle"),e.literal("error"),e.literal("cancelled")),usage:e.optional(P)}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(f).withIndex("byKey",b=>b.eq("key",t.key)).first();if(i?.instanceId!==t.instanceId){if(i?.completedInstanceId===t.instanceId&&i.status==="running"&&typeof i.instanceId=="string")return{dequeued:i.instanceId};const b=await n.db.query(x).withIndex("byThreadInstance",p=>p.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return b&&await n.db.delete(b._id),{}}const w=(i.completedInstanceId===t.instanceId?[]:await n.db.query(x).withIndex("byThread",b=>b.eq("threadKey",t.key)).collect())[0];if(!w)return await n.db.patch(i._id,{completedInstanceId:t.instanceId,status:t.status,updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{};const I=w.instanceId;return await n.db.delete(w._id),await n.db.patch(i._id,{completedInstanceId:t.instanceId,instanceId:I,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:I}}),q=A.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(f).withIndex("byKey",i=>i.eq("key",t.key)).first();a&&await n.db.patch(a._id,{state:t.state,updatedAt:Date.now()})}),y=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},N=_.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(f).withIndex("byKey",i=>i.eq("key",t.key)).first();return y(a,n.auth)}),te=_.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(f).withIndex("byKey",i=>i.eq("key",t.key)).first();return y(a,n.auth)?.state}),ne=_.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(f).withIndex("byKey",i=>i.eq("key",t.key)).first();return y(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(C).withIndex("byThread",r=>r.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(C).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),ae=_.input({limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const{userId:a}=n.auth;if(!a)return[];const i=await n.db.query(f).withIndex("byOwnerStatus",p=>p.eq("owner",a).eq("status","awaiting_input")).order("desc").take($e),r=Date.now(),d=Math.min(xe,Math.max(1,Math.trunc(t.limit??Re))),w=async p=>{const T=p.instanceId;if(T===void 0)return[];const K=`${T}:approval:`,g=`${T}:approval;`;return(await n.db.query(C).withIndex("byMessageKey",E=>E.eq("threadKey",p.key).gte("messageKey",K).lt("messageKey",g)).collect()).filter(E=>E.status==="awaiting_approval"&&typeof E.expiresAt=="number"&&r<E.expiresAt).map(E=>G({agent:p.agent,content:E.content,instanceId:T,requestedAt:E.createdAt,threadKey:p.key,threadTitle:p.title,threadUpdatedAt:p.updatedAt,toolCallId:E.toolCallId,toolName:E.toolName}))},I=[];let b=0;for(let p=0;p<i.length&&b<d;p+=d){const T=await Promise.all(i.slice(p,p+d).map(K=>w(K)));for(const K of T)K.length>0&&b<d&&(I.push(...K),b+=1)}return I}),ie=A.input({decision:e.union(e.literal("approve"),e.literal("approve_for_thread"),e.literal("reject")),instanceId:e.string(),note:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(f).withIndex("byKey",I=>I.eq("key",t.threadKey)).first(),i=y(a,n.auth);if(i===void 0)throw new m("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(i.instanceId!==t.instanceId)throw new m("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const r=i.agent,{agents:d}=n,w=d?.[r];if(typeof w?.sendEvent!="function")throw new m("INTERNAL",`@lunora/agent: no ctx.agents["${r}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);if(!await Le(n.db,t.threadKey,t.instanceId,t.toolCallId))throw new m("CONFLICT",`@lunora/agent: no pending approval for tool call "${t.toolCallId}" on thread "${t.threadKey}" to decide`);return t.decision==="approve_for_thread"&&(O(a,n.auth,"grant a lasting approval for a tool"),await Me(n.db,t.threadKey,t.instanceId,t.toolCallId)),await Be(n.db,t.threadKey,t.instanceId,t.toolCallId),await w.sendEvent(t.instanceId,{payload:{decision:t.decision==="reject"?"reject":"approve",toolCallId:t.toolCallId,...t.decision==="approve_for_thread"?{scope:"thread"}:{},...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),oe=A.input({secret:e.sensitive(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=O(await n.db.query(f).withIndex("byKey",g=>g.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),i=L(n),d=(await X(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,w=await V(n.db,a,d),I=Q(n,a),b=a.instanceId,p=g=>{if(g.instanceId!==b)throw new m("CONFLICT",`@lunora/agent: tool call "${t.toolCallId}" on thread "${t.threadKey}" was reopened by a newer run while its secret was being stored`)},T=await B(n.db,t.threadKey,d,Date.now());p(T);let K;try{K=await i.put(t.secret,{scope:t.threadKey,ttlMs:Pe(T.expiresAt,Date.now())})}catch(g){throw g instanceof we?new m("PAYLOAD_TOO_LARGE",g.message):g}try{const g=await B(n.db,t.threadKey,d,Date.now());p(g),await n.db.patch(g._id,{ref:K,status:"supplied",updatedAt:Date.now()}),await n.db.delete(w._id)}catch(g){throw await i.discard(K).catch(()=>{}),g}try{await I.sendEvent(I.instanceId,{payload:{},type:`agent-secret:${d}`})}catch{}return{resolved:!0}}),re=A.input({threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=O(await n.db.query(f).withIndex("byKey",b=>b.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),r=(await X(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,d=await V(n.db,a,r),w=Q(n,a),I=await B(n.db,t.threadKey,r,Date.now());await n.db.patch(I._id,{status:"declined",updatedAt:Date.now()}),await n.db.delete(d._id);try{await w.sendEvent(w.instanceId,{payload:{},type:`agent-secret:${r}`})}catch{}return{resolved:!0}}),se=v(A.input({consumerTool:e.string(),expiresAt:e.number(),instanceId:e.string(),callId:e.optional(e.string()),label:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await R(n.db,t.threadKey,t.toolCallId),i=Date.now();if(a===void 0){await n.db.insert(M,{consumerTool:t.consumerTool,createdAt:i,expiresAt:t.expiresAt,instanceId:t.instanceId,label:t.label??null,status:"pending",callId:t.callId??t.toolCallId,threadKey:t.threadKey,toolCallId:t.toolCallId,toolName:t.toolName,updatedAt:i});return}if(a.instanceId!==t.instanceId){if(typeof a.ref=="string"){const{agentSecrets:r}=n;await r?.discard(a.ref)}await n.db.patch(a._id,{consumerTool:t.consumerTool,createdAt:i,expiresAt:t.expiresAt,label:t.label??null,ref:null,callId:t.callId??t.toolCallId,instanceId:t.instanceId,status:"pending",toolName:t.toolName,updatedAt:i})}})),de=v(A.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await R(n.db,t.threadKey,t.toolCallId);if(a?.instanceId!==t.instanceId)return{status:"expired"};const{status:i}=a;return i==="pending"?(await n.db.patch(a._id,{status:"expired",updatedAt:Date.now()}),{status:"expired"}):i==="supplied"||i==="consumed"?{status:"supplied"}:{status:i==="declined"?"declined":"expired"}})),le=v(A.input({claimant:e.string(),consumerCallId:e.string(),instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await R(n.db,t.threadKey,t.toolCallId);if(!(a?.instanceId!==t.instanceId||a.status!=="supplied"&&a.status!=="consumed")&&!(typeof a.ref!="string"||t.claimant!==`tool:${a.consumerTool}:${t.consumerCallId}`))return L(n).take(a.ref,{claimant:t.claimant,scope:t.threadKey})})),ue=v(A.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await R(n.db,t.threadKey,t.toolCallId);a?.instanceId===t.instanceId&&(typeof a.ref=="string"&&await L(n).discard(a.ref),a.status==="supplied"&&await n.db.patch(a._id,{status:"consumed",updatedAt:Date.now()}))})),ce=_.input({threadKey:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(f).withIndex("byKey",d=>d.eq("key",t.threadKey)).first();O(a,n.auth,"list its secret requests");const i=await n.db.query(M).withIndex("byThreadCall",d=>d.eq("threadKey",t.threadKey)).collect(),r=Date.now();return i.map(d=>({createdAt:d.createdAt,expiresAt:d.expiresAt,...typeof d.label=="string"?{label:d.label}:{},status:d.status==="pending"&&r>=d.expiresAt?"expired":d.status,toolCallId:d.callId??d.toolCallId,toolName:d.toolName}))}),pe=v(_.input({key:e.string(),toolName:e.string()}).query(async({args:t,ctx:n})=>await n.db.query($).withIndex("byThreadTool",i=>i.eq("threadKey",t.key).eq("toolName",t.toolName)).first()!==null)),ye=_.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(f).withIndex("byKey",r=>r.eq("key",t.key)).first();return y(a,n.auth)===void 0?[]:(await n.db.query($).withIndex("byThreadTool",r=>r.eq("threadKey",t.key)).collect()).map(r=>({createdAt:r.createdAt,toolName:r.toolName}))}),he=A.input({threadKey:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(f).withIndex("byKey",r=>r.eq("key",t.threadKey)).first();if(y(a,n.auth)===void 0)throw new m("FORBIDDEN",`@lunora/agent: not allowed to revoke approvals on thread "${t.threadKey}"`);const i=await n.db.query($).withIndex("byThreadTool",r=>r.eq("threadKey",t.threadKey).eq("toolName",t.toolName)).first();return i?(await n.db.delete(i._id),{revoked:!0}):{revoked:!1}}),me=A.input({agent:e.string(),input:e.string(),threadKey:e.string(),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const{agents:a}=n,i=a?.[t.agent];if(typeof i?.run!="function")throw new m("INTERNAL",`@lunora/agent: no ctx.agents["${t.agent}"] producer to start a run — run codegen/dev so the agent binding is wired, and check the agent name`);if(i.publicRun!==!0)throw new m("FORBIDDEN",`@lunora/agent: agent "${t.agent}" is not enabled for public runs — set defineAgent({ publicRun: true }) to allow an external client (e.g. the @lunora/mcp server) to start it`);const r=n.auth.userId??void 0,d=await n.db.query(f).withIndex("byKey",I=>I.eq("key",t.threadKey)).first();if(d){const I=d.status,b=d.instanceId,p=d.owner;if((I==="running"||I==="awaiting_input")&&b!==void 0&&(p===void 0||p===r))return{id:b,threadKey:t.threadKey};if(p!==r)throw new m("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:w}=await i.run({input:t.input,threadKey:t.threadKey,...r===void 0?{}:{owner:r},...t.title===void 0?{}:{title:t.title}});return{id:w,threadKey:t.threadKey}}),U=Ae(),F=Ne();return{extension:Oe,functions:{agentApprovalGranted:pe,agentApprovalGrants:ye,agentAppendMessage:v(o),agentCompleteRun:v(h),agentEnsureThread:v(s),agentEpisodeRecall:F.agentEpisodeRecall,agentEpisodeUpsert:F.agentEpisodeUpsert,agentGraphTraverse:U.agentGraphTraverse,agentGraphUpsert:U.agentGraphUpsert,agentHistory:v(c),agentMessages:ne,agentDeleteMessage:v(l),agentPatchThread:v(u),agentPendingApprovals:ae,agentResolveApproval:ie,agentRevokeApprovalGrant:he,agentRun:me,agentSetState:v(q),agentState:te,agentSupplySecret:oe,agentTakeSecret:le,agentThread:N,agentDeclineSecret:re,agentDiscardSecret:ue,agentOpenSecretRequest:se,agentSecretRequests:ce,agentSettleSecretRequest:de}}};export{ze as agentComponent,Oe as agentExtension,et as normalizeEntityName,nt as sandboxComponent};
1
+ import{LunoraError as w}from"@lunora/errors";import{SecretValueTooLargeError as we}from"@lunora/platform";import{defineTable as N,initLunora as W,defineSchemaExtension as Ie}from"@lunora/server";import{v as e}from"@lunora/values";import{a as T,A as x,d as G,b as be,c as ge,S as fe}from"./packem_shared/component-shared-DdXFbng-.mjs";import{graphTables as qe,graphComponent as Ae}from"./packem_shared/normalizeEntityName-Rr5OQxhc.mjs";import{normalizeEntityName as et}from"./packem_shared/normalizeEntityName-Rr5OQxhc.mjs";import{sandboxComponent as nt}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const D="agent_episodes",Ke=5,ve=20,Te=500,j=200,Ce=/\s+/gu,Ee=s=>s===void 0||!Number.isFinite(s)?Ke:Math.min(ve,Math.max(1,Math.trunc(s))),_e={episodes:N({createdAt:e.number(),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).index("byOwnerCreatedAt",["owner","createdAt"]).index("byOwnerMessageKey",["owner","messageKey"],{unique:!0}).public()},{mutation:ke,query:Se}=W.dataModel().create(),Ne=()=>{const s=ke.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:l,ctx:u})=>{const c=l.summary.replaceAll(Ce," ").trim().slice(0,Te);if(c.length===0)return{recorded:!1};if(await u.db.query(D).withIndex("byOwnerMessageKey",h=>h.eq("owner",l.owner).eq("messageKey",l.messageKey)).first())return{recorded:!1};await u.db.insert(D,{createdAt:l.createdAt??Date.now(),messageKey:l.messageKey,owner:l.owner,summary:c,...l.threadKey===void 0?{}:{threadKey:l.threadKey}});const q=await u.db.query(D).withIndex("byOwnerCreatedAt",h=>h.eq("owner",l.owner)).order("asc").take(j+1);for(const h of q.slice(0,Math.max(0,q.length-j)))await u.db.delete(D,h._id);return{recorded:!0}}),o=Se.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:l,ctx:u})=>{const c=await u.db.query(D).withIndex("byOwnerCreatedAt",m=>m.eq("owner",l.owner)).order("desc").take(Ee(l.limit));return c.length===0?{context:""}:{context:c.toReversed().map(m=>`- ${m.summary}`).join(`
2
+ `)}});return{agentEpisodeRecall:T(o),agentEpisodeUpsert:T(s)}},Y="threads",z="messages",J="run_queue",Z="approval_grants",ee="secret_requests",p=`${x}_${Y}`,K=`${x}_${z}`,S=`${x}_${J}`,R=`${x}_${Z}`,_=`${x}_${ee}`,Re=50,xe=200,$e=500,H=5,P=e.object({cacheReadTokens:e.optional(e.number()),cacheWriteTokens:e.optional(e.number()),inputTokens:e.optional(e.number()),outputTokens:e.optional(e.number()),reasoningTokens:e.optional(e.number()),status:e.optional(e.union(e.literal("complete"),e.literal("partial"),e.literal("unavailable"))),totalTokens:e.optional(e.number())}),De=780*60*1e3,Oe=Ie(x,{tables:{[z]:N({approvalScope:e.optional(e.literal("thread")),content:e.string(),createdAt:e.number(),expiresAt:e.optional(e.number()),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),seq:e.number(),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("awaiting_secret"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).index("byThread",["threadKey","seq"]).index("byMessageKey",["threadKey","messageKey"],{unique:!0}).public(),[Y]:N({agent:e.string(),createdAt:e.number(),error:e.optional(e.string().nullable()),completedInstanceId:e.optional(e.string().nullable()),instanceId:e.optional(e.string()),key:e.string(),messageCount:e.number(),owner:e.optional(e.string()),state:e.optional(e.any()),status:e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input")),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(P)}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).index("byOwnerStatus",["owner","status","updatedAt"]).public(),[J]:N({agent:e.string(),enqueuedAt:e.number(),instanceId:e.string(),position:e.number(),threadKey:e.string()}).index("byThread",["threadKey","position"]).index("byThreadInstance",["threadKey","instanceId"],{unique:!0}).public(),[Z]:N({createdAt:e.number(),threadKey:e.string(),toolName:e.string()}).index("byThreadTool",["threadKey","toolName"],{unique:!0}).public(),[ee]:N({consumerTool:e.string(),createdAt:e.number(),expiresAt:e.number(),instanceId:e.string(),ref:e.optional(e.string().nullable()),label:e.optional(e.string().nullable()),status:e.union(e.literal("pending"),e.literal("supplied"),e.literal("declined"),e.literal("expired"),e.literal("consumed")),threadKey:e.string(),toolCallId:e.string(),callId:e.optional(e.string()),toolName:e.string(),updatedAt:e.number()}).index("byThreadCall",["threadKey","toolCallId"],{unique:!0}).index("byThreadCallId",["threadKey","callId"]).public(),...qe,..._e}}),{mutation:A,query:k}=W.dataModel().create(),Me=async(s,o,l,u)=>{const c=await s.query(K).withIndex("byMessageKey",$=>$.eq("threadKey",o).eq("messageKey",`${l}:approval:${u}`)).first();if(c?.status!=="awaiting_approval")throw new w("CONFLICT",`@lunora/agent: no pending approval for tool call "${u}" to grant for thread "${o}"`);const{expiresAt:m}=c;if(typeof m!="number")throw new w("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${o}" has no recorded deadline, so it cannot be granted for the thread`);if(Date.now()>=m)throw new w("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${o}" has timed out`);const q=c.toolName;await s.query(R).withIndex("byThreadTool",$=>$.eq("threadKey",o).eq("toolName",q)).first()||await s.insert(R,{createdAt:Date.now(),threadKey:o,toolName:q})},Le=async(s,o,l,u)=>(await s.query(K).withIndex("byMessageKey",m=>m.eq("threadKey",o).eq("messageKey",`${l}:approval:${u}`)).first())?.status==="awaiting_approval",Be=async(s,o,l,u)=>{const c=await s.query(K).withIndex("byMessageKey",m=>m.eq("threadKey",o).eq("messageKey",`${l}:approval:${u}`)).first();c?.status==="awaiting_approval"&&await s.delete(K,c._id)},L=s=>{const{agentSecrets:o}=s;if(o===void 0)throw new w("NOT_IMPLEMENTED","@lunora/agent: no secret store is wired on this deployment. Codegen wires one only when a source in lunora/ value-imports requestSecretTool from @lunora/agent (directly, through a namespace import, or through a relative barrel that re-exports it); add that import, or this target cannot hold a human-supplied secret value");return o},M=(s,o,l)=>{const u=o.userId??void 0;if(s===null||u===void 0||s.owner!==u)throw new w("FORBIDDEN",`@lunora/agent: only the thread's owner can ${l}`);return s},V=async(s,o,l)=>{const{instanceId:u,key:c}=o,m=typeof u=="string"?await s.query(K).withIndex("byMessageKey",q=>q.eq("threadKey",c).eq("messageKey",`${u}:secret:${l}`)).first():void 0;if(m?.status!=="awaiting_secret")throw new w("CONFLICT",`@lunora/agent: no pending secret request for tool call "${l}" on thread "${c}"`);return m},O=async(s,o,l)=>await s.query(_).withIndex("byThreadCall",c=>c.eq("threadKey",o).eq("toolCallId",l)).first()??void 0,X=async(s,o,l,u,c)=>{const q=(await s.query(_).withIndex("byThreadCallId",h=>h.eq("threadKey",o).eq("callId",u)).collect()).filter(h=>h.status==="pending"&&h.instanceId===l&&c<h.expiresAt);if(q.length!==1)throw new w("CONFLICT",`@lunora/agent: no pending secret request for tool call "${u}" on thread "${o}"`);return q[0]},Pe=(s,o)=>Math.max(ge,s+fe-o),B=async(s,o,l,u)=>{const c=await O(s,o,l);if(c?.status!=="pending"||u>=c.expiresAt)throw new w("CONFLICT",`@lunora/agent: no open secret request for tool call "${l}" on thread "${o}"`);return c},Q=(s,o)=>{const{instanceId:l}=o,{agents:u}=s,c=u?.[o.agent];if(typeof l!="string"||typeof c?.sendEvent!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${String(o.agent)}"] producer to deliver the secret — run codegen/dev`);return{instanceId:l,sendEvent:c.sendEvent}},Ue=async(s,o,l)=>{if(o.instanceId===void 0)throw new w("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:u}=o,c=await s.query(S).withIndex("byThreadInstance",h=>h.eq("threadKey",o.key).eq("instanceId",u)).first();if(c)return{outcome:"queued",position:c.position};const m=await s.query(S).withIndex("byThread",h=>h.eq("threadKey",o.key)).collect();if(m.length>=H)throw new w("CONFLICT",`@lunora/agent: thread "${o.key}" run queue is full (depth ${String(H)}) — rejecting instance "${u}"`);const q=(m.at(-1)?.position??-1)+1;return await s.insert(S,{agent:o.agent,enqueuedAt:l,instanceId:u,position:q,threadKey:o.key}),{outcome:"queued",position:q}},Fe=async(s,o,l)=>{if(o.policy==="queue")return Ue(s,{agent:o.agent,instanceId:o.instanceId,key:o.key,priorInstanceId:o.priorInstanceId},l);if(o.policy!=="replace")throw new w("CONFLICT",`@lunora/agent: thread "${o.key}" already has a run in flight (instance "${o.priorInstanceId}") — onConcurrentRun="${o.policy}"`);return await s.patch(p,o.existingId,{error:null,status:"running",updatedAt:l,...o.instanceId===void 0?{}:{completedInstanceId:null,instanceId:o.instanceId}}),{outcome:"replaced",priorInstanceId:o.priorInstanceId}},Ge=(s,o,l)=>{const u=s.instanceId;if(u===void 0||o===u||s.status!=="running"&&s.status!=="awaiting_input")return;const c=typeof s.updatedAt=="number"?s.updatedAt:0,m=s.status==="awaiting_input"?be:De;return l-c>m?void 0:u},ze=()=>{const s=A.input({agent:e.string(),initialState:e.optional(e.any()),instanceId:e.optional(e.string()),key:e.string(),onConcurrentRun:e.optional(e.union(e.literal("reject"),e.literal("queue"),e.literal("replace"))),owner:e.optional(e.string()),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.key)).first();if(i){if(i.owner!==t.owner)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);if(t.instanceId!==void 0&&i.completedInstanceId===t.instanceId)return{outcome:"completed"};const r=Ge(i,t.instanceId,a);return r!==void 0?Fe(n.db,{agent:t.agent,existingId:i._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:r},a):(await n.db.patch(p,i._id,{error:null,status:"running",updatedAt:a,...t.instanceId===void 0?{}:{completedInstanceId:null,instanceId:t.instanceId}}),{outcome:"continued"})}return await n.db.insert(p,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...G({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),o=A.input({approvalScope:e.optional(e.literal("thread")),content:e.string(),expiresAt:e.optional(e.number()),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("awaiting_secret"),e.literal("approved"),e.literal("rejected"))),stepName:e.optional(e.string()),threadKey:e.string(),toolCallId:e.optional(e.string()),toolCalls:e.optional(e.array(e.object({id:e.string(),input:e.any(),name:e.string()}))),toolName:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(K).withIndex("byMessageKey",I=>I.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const i=await n.db.query(p).withIndex("byKey",I=>I.eq("key",t.threadKey)).first();if(!i)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const r=i.messageCount,d=Date.now();return await n.db.insert(K,{content:t.content,createdAt:d,messageKey:t.messageKey,role:t.role,seq:r,threadKey:t.threadKey,...t.approvalScope===void 0?{}:{approvalScope:t.approvalScope},...t.expiresAt===void 0?{}:{expiresAt:t.expiresAt},...t.status===void 0?{}:{status:t.status},...t.stepName===void 0?{}:{stepName:t.stepName},...t.toolCallId===void 0?{}:{toolCallId:t.toolCallId},...t.toolCalls===void 0?{}:{toolCalls:t.toolCalls},...t.toolName===void 0?{}:{toolName:t.toolName}}),await n.db.patch(p,i._id,{messageCount:r+1,updatedAt:d}),{seq:r}}),l=A.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(K).withIndex("byMessageKey",i=>i.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(K,a._id)}),u=A.input({error:e.optional(e.string()),ifInstanceId:e.optional(e.string()),instanceId:e.optional(e.string()),key:e.optional(e.string()),status:e.optional(e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input"))),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),usage:e.optional(P)}).mutation(async({args:t,ctx:n})=>{const{instanceId:a,key:i}=t;let r;i!==void 0?r=await n.db.query(p).withIndex("byKey",d=>d.eq("key",i)).first():a!==void 0&&(r=await n.db.query(p).withIndex("byInstance",d=>d.eq("instanceId",a)).first()),!(!r||t.ifInstanceId!==void 0&&r.instanceId!==t.ifInstanceId)&&await n.db.patch(p,r._id,{updatedAt:Date.now(),...t.error===void 0?{}:{error:t.error},...t.status===void 0?{}:{status:t.status},...t.summary===void 0?{}:{summary:t.summary},...t.summaryConfig===void 0?{}:{summaryConfig:t.summaryConfig},...t.summaryRebuiltSeq===void 0?{}:{summaryRebuiltSeq:t.summaryRebuiltSeq},...t.summaryThroughSeq===void 0?{}:{summaryThroughSeq:t.summaryThroughSeq},...t.title===void 0?{}:{title:t.title},...t.usage===void 0?{}:{usage:t.usage}})}),c=k.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",f=>f.eq("key",t.key)).first(),i=a?.summary,r=a?.summaryThroughSeq,d=a?.summaryRebuiltSeq,I=a?.summaryConfig,b=typeof i=="string"&&i.length>0&&typeof r=="number",g=t.configKey===void 0||I===t.configKey,y=typeof d!="number"||typeof r=="number"&&r>=2*d+1,C=b&&g&&!y,v=await n.db.query(K).withIndex("byThread",f=>C?f.eq("threadKey",t.key).gt("seq",r):f.eq("threadKey",t.key)).collect();return C?{messages:v,summary:i}:b?{fallback:{summary:i,throughSeq:r},messages:v}:{messages:v}}),m=A.input({error:e.optional(e.string()),instanceId:e.string(),key:e.string(),status:e.union(e.literal("idle"),e.literal("error"),e.literal("cancelled")),usage:e.optional(P)}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(p).withIndex("byKey",g=>g.eq("key",t.key)).first();if(i?.instanceId!==t.instanceId){if(i?.completedInstanceId===t.instanceId&&i.status==="running"&&typeof i.instanceId=="string")return{dequeued:i.instanceId};const g=await n.db.query(S).withIndex("byThreadInstance",y=>y.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return g&&await n.db.delete(S,g._id),{}}const I=(i.completedInstanceId===t.instanceId?[]:await n.db.query(S).withIndex("byThread",g=>g.eq("threadKey",t.key)).collect())[0];if(!I)return await n.db.patch(p,i._id,{completedInstanceId:t.instanceId,status:t.status,updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{};const b=I.instanceId;return await n.db.delete(S,I._id),await n.db.patch(p,i._id,{completedInstanceId:t.instanceId,instanceId:b,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:b}}),q=A.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();a&&await n.db.patch(p,a._id,{state:t.state,updatedAt:Date.now()})}),h=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},$=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return h(a,n.auth)}),te=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return h(a,n.auth)?.state}),ne=k.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",i=>i.eq("key",t.key)).first();return h(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(K).withIndex("byThread",r=>r.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(K).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),ae=k.input({limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const{userId:a}=n.auth;if(!a)return[];const i=await n.db.query(p).withIndex("byOwnerStatus",y=>y.eq("owner",a).eq("status","awaiting_input")).order("desc").take($e),r=Date.now(),d=Math.min(xe,Math.max(1,Math.trunc(t.limit??Re))),I=async y=>{const C=y.instanceId;if(C===void 0)return[];const v=`${C}:approval:`,f=`${C}:approval;`;return(await n.db.query(K).withIndex("byMessageKey",E=>E.eq("threadKey",y.key).gte("messageKey",v).lt("messageKey",f)).collect()).filter(E=>E.status==="awaiting_approval"&&typeof E.expiresAt=="number"&&r<E.expiresAt).map(E=>G({agent:y.agent,content:E.content,instanceId:C,requestedAt:E.createdAt,threadKey:y.key,threadTitle:y.title,threadUpdatedAt:y.updatedAt,toolCallId:E.toolCallId,toolName:E.toolName}))},b=[];let g=0;for(let y=0;y<i.length&&g<d;y+=d){const C=await Promise.all(i.slice(y,y+d).map(v=>I(v)));for(const v of C)v.length>0&&g<d&&(b.push(...v),g+=1)}return b}),ie=A.input({decision:e.union(e.literal("approve"),e.literal("approve_for_thread"),e.literal("reject")),instanceId:e.string(),note:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",b=>b.eq("key",t.threadKey)).first(),i=h(a,n.auth);if(i===void 0)throw new w("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(i.instanceId!==t.instanceId)throw new w("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const r=i.agent,{agents:d}=n,I=d?.[r];if(typeof I?.sendEvent!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${r}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);if(!await Le(n.db,t.threadKey,t.instanceId,t.toolCallId))throw new w("CONFLICT",`@lunora/agent: no pending approval for tool call "${t.toolCallId}" on thread "${t.threadKey}" to decide`);return t.decision==="approve_for_thread"&&(M(a,n.auth,"grant a lasting approval for a tool"),await Me(n.db,t.threadKey,t.instanceId,t.toolCallId)),await Be(n.db,t.threadKey,t.instanceId,t.toolCallId),await I.sendEvent(t.instanceId,{payload:{decision:t.decision==="reject"?"reject":"approve",toolCallId:t.toolCallId,...t.decision==="approve_for_thread"?{scope:"thread"}:{},...t.note===void 0?{}:{note:t.note}},type:`agent-approval:${t.toolCallId}`}),{resolved:!0}}),oe=A.input({secret:e.sensitive(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=M(await n.db.query(p).withIndex("byKey",f=>f.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),i=L(n),d=(await X(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,I=await V(n.db,a,d),b=Q(n,a),g=a.instanceId,y=f=>{if(f.instanceId!==g)throw new w("CONFLICT",`@lunora/agent: tool call "${t.toolCallId}" on thread "${t.threadKey}" was reopened by a newer run while its secret was being stored`)},C=await B(n.db,t.threadKey,d,Date.now());y(C);let v;try{v=await i.put(t.secret,{scope:t.threadKey,ttlMs:Pe(C.expiresAt,Date.now())})}catch(f){throw f instanceof we?new w("PAYLOAD_TOO_LARGE",f.message):f}try{const f=await B(n.db,t.threadKey,d,Date.now());y(f),await n.db.patch(_,f._id,{ref:v,status:"supplied",updatedAt:Date.now()}),await n.db.delete(K,I._id)}catch(f){throw await i.discard(v).catch(()=>{}),f}try{await b.sendEvent(b.instanceId,{payload:{},type:`agent-secret:${d}`})}catch{}return{resolved:!0}}),re=A.input({threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=M(await n.db.query(p).withIndex("byKey",g=>g.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),r=(await X(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,d=await V(n.db,a,r),I=Q(n,a),b=await B(n.db,t.threadKey,r,Date.now());await n.db.patch(_,b._id,{status:"declined",updatedAt:Date.now()}),await n.db.delete(K,d._id);try{await I.sendEvent(I.instanceId,{payload:{},type:`agent-secret:${r}`})}catch{}return{resolved:!0}}),se=T(A.input({consumerTool:e.string(),expiresAt:e.number(),instanceId:e.string(),callId:e.optional(e.string()),label:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await O(n.db,t.threadKey,t.toolCallId),i=Date.now();if(a===void 0){await n.db.insert(_,{consumerTool:t.consumerTool,createdAt:i,expiresAt:t.expiresAt,instanceId:t.instanceId,label:t.label??null,status:"pending",callId:t.callId??t.toolCallId,threadKey:t.threadKey,toolCallId:t.toolCallId,toolName:t.toolName,updatedAt:i});return}if(a.instanceId!==t.instanceId){if(typeof a.ref=="string"){const{agentSecrets:r}=n;await r?.discard(a.ref)}await n.db.patch(_,a._id,{consumerTool:t.consumerTool,createdAt:i,expiresAt:t.expiresAt,label:t.label??null,ref:null,callId:t.callId??t.toolCallId,instanceId:t.instanceId,status:"pending",toolName:t.toolName,updatedAt:i})}})),de=T(A.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await O(n.db,t.threadKey,t.toolCallId);if(a?.instanceId!==t.instanceId)return{status:"expired"};const{status:i}=a;return i==="pending"?(await n.db.patch(_,a._id,{status:"expired",updatedAt:Date.now()}),{status:"expired"}):i==="supplied"||i==="consumed"?{status:"supplied"}:{status:i==="declined"?"declined":"expired"}})),le=T(A.input({claimant:e.string(),consumerCallId:e.string(),instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await O(n.db,t.threadKey,t.toolCallId);if(!(a?.instanceId!==t.instanceId||a.status!=="supplied"&&a.status!=="consumed")&&!(typeof a.ref!="string"||t.claimant!==`tool:${a.consumerTool}:${t.consumerCallId}`))return L(n).take(a.ref,{claimant:t.claimant,scope:t.threadKey})})),ue=T(A.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await O(n.db,t.threadKey,t.toolCallId);a?.instanceId===t.instanceId&&(typeof a.ref=="string"&&await L(n).discard(a.ref),a.status==="supplied"&&await n.db.patch(_,a._id,{status:"consumed",updatedAt:Date.now()}))})),ce=k.input({threadKey:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",d=>d.eq("key",t.threadKey)).first();M(a,n.auth,"list its secret requests");const i=await n.db.query(_).withIndex("byThreadCall",d=>d.eq("threadKey",t.threadKey)).collect(),r=Date.now();return i.map(d=>({createdAt:d.createdAt,expiresAt:d.expiresAt,...typeof d.label=="string"?{label:d.label}:{},status:d.status==="pending"&&r>=d.expiresAt?"expired":d.status,toolCallId:d.callId??d.toolCallId,toolName:d.toolName}))}),pe=T(k.input({key:e.string(),toolName:e.string()}).query(async({args:t,ctx:n})=>await n.db.query(R).withIndex("byThreadTool",i=>i.eq("threadKey",t.key).eq("toolName",t.toolName)).first()!==null)),ye=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.key)).first();return h(a,n.auth)===void 0?[]:(await n.db.query(R).withIndex("byThreadTool",r=>r.eq("threadKey",t.key)).collect()).map(r=>({createdAt:r.createdAt,toolName:r.toolName}))}),he=A.input({threadKey:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.threadKey)).first();if(h(a,n.auth)===void 0)throw new w("FORBIDDEN",`@lunora/agent: not allowed to revoke approvals on thread "${t.threadKey}"`);const i=await n.db.query(R).withIndex("byThreadTool",r=>r.eq("threadKey",t.threadKey).eq("toolName",t.toolName)).first();return i?(await n.db.delete(R,i._id),{revoked:!0}):{revoked:!1}}),me=A.input({agent:e.string(),input:e.string(),threadKey:e.string(),title:e.optional(e.string())}).mutation(async({args:t,ctx:n})=>{const{agents:a}=n,i=a?.[t.agent];if(typeof i?.run!="function")throw new w("INTERNAL",`@lunora/agent: no ctx.agents["${t.agent}"] producer to start a run — run codegen/dev so the agent binding is wired, and check the agent name`);if(i.publicRun!==!0)throw new w("FORBIDDEN",`@lunora/agent: agent "${t.agent}" is not enabled for public runs — set defineAgent({ publicRun: true }) to allow an external client (e.g. the @lunora/mcp server) to start it`);const r=n.auth.userId??void 0,d=await n.db.query(p).withIndex("byKey",b=>b.eq("key",t.threadKey)).first();if(d){const b=d.status,g=d.instanceId,y=d.owner;if((b==="running"||b==="awaiting_input")&&g!==void 0&&(y===void 0||y===r))return{id:g,threadKey:t.threadKey};if(y!==r)throw new w("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:I}=await i.run({input:t.input,threadKey:t.threadKey,...r===void 0?{}:{owner:r},...t.title===void 0?{}:{title:t.title}});return{id:I,threadKey:t.threadKey}}),U=Ae(),F=Ne();return{extension:Oe,functions:{agentApprovalGranted:pe,agentApprovalGrants:ye,agentAppendMessage:T(o),agentCompleteRun:T(m),agentEnsureThread:T(s),agentEpisodeRecall:F.agentEpisodeRecall,agentEpisodeUpsert:F.agentEpisodeUpsert,agentGraphTraverse:U.agentGraphTraverse,agentGraphUpsert:U.agentGraphUpsert,agentHistory:T(c),agentMessages:ne,agentDeleteMessage:T(l),agentPatchThread:T(u),agentPendingApprovals:ae,agentResolveApproval:ie,agentRevokeApprovalGrant:he,agentRun:me,agentSetState:T(q),agentState:te,agentSupplySecret:oe,agentTakeSecret:le,agentThread:$,agentDeclineSecret:re,agentDiscardSecret:ue,agentOpenSecretRequest:se,agentSecretRequests:ce,agentSettleSecretRequest:de}}};export{ze as agentComponent,Oe as agentExtension,et as normalizeEntityName,nt as sandboxComponent};
@@ -0,0 +1,2 @@
1
+ import{defineTable as A,initLunora as q}from"@lunora/server";import{v as e}from"@lunora/values";import{A as _,a as f,d as S}from"./component-shared-DdXFbng-.mjs";const T="entities",x="edges",h=`${_}_${T}`,w=`${_}_${x}`,X={[T]:A({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[x]:A({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},E=64,O=2,G=4,D=8,C=32,R=500,I=/\s+/gu,K=/[^\p{L}\p{N}]+/u,N=t=>t.trim().replaceAll(I," ").toLowerCase(),L=t=>t.toLowerCase().split(K).filter(o=>o.length>=2),P=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,o)=>o.weight-t.weight||t.label.localeCompare(o.label)||t.srcName.localeCompare(o.srcName)||t.dstName.localeCompare(o.dstName),$=(t,o)=>o.some(n=>t.includes(n)||n.includes(t)),v=t=>t.map(o=>`- ${o.srcName} —[${o.label}]→ ${o.dstName}`).toSorted((o,n)=>o.localeCompare(n)).join(`
2
+ `),H=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,B=(t,o,n,r)=>{const a=H(t);r.collectedKeys.has(a)||(r.collectedKeys.add(a),r.collected.push(t));const l=t.srcName===o?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<n.maxNodes&&(r.seen.add(l),r.next.push(l))},F=async(t,o,n)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(o)};let a=o.slice(0,n.maxNodes);for(let l=0;l<n.depth&&a.length>0;l+=1){r.next=[];for(const m of a){const p=(await t(m)).toSorted(U).slice(0,n.fanOut);for(const s of p)B(s,m,n,r)}a=r.next}return r.collected},{mutation:M,query:W}=q.dataModel().create(),Y=()=>{const t=M.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:n,ctx:r})=>{const a=Date.now(),l=async(s,i)=>{const c=N(s);if(c.length===0)return;const d=await r.db.query(h).withIndex("byOwnerName",g=>g.eq("owner",n.owner).eq("name",c)).first();return d?(i!==void 0&&d.type===void 0&&await r.db.patch(h,d._id,{type:i,updatedAt:a}),c):(await r.db.insert(h,{createdAt:a,name:c,owner:n.owner,updatedAt:a,weight:1,...S({firstMessageKey:n.messageKey,type:i})}),c)},m=async s=>{const i=N(s.src),c=N(s.dst),d=N(s.label);if(i.length===0||c.length===0||d.length===0||i===c)return!1;await l(i),await l(c);const g=s.confidence??1,y=await r.db.query(w).withIndex("byTriple",b=>b.eq("owner",n.owner).eq("srcName",i).eq("label",d).eq("dstName",c)).first();if(y){const b=y.weight??1;await r.db.patch(w,y._id,{updatedAt:a,weight:Math.max(b,g)})}else await r.db.insert(w,{createdAt:a,dstName:c,label:d,messageKey:n.messageKey,owner:n.owner,srcName:i,updatedAt:a,weight:g});return!0};let u=0;for(const s of n.entities.slice(0,E))await l(s.name,s.type)!==void 0&&(u+=1);let p=0;for(const s of n.relations.slice(0,E))await m(s)&&(p+=1);return{entities:u,relations:p}}),o=W.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:n,ctx:r})=>{const a=L(n.query);if(a.length===0)return{context:""};const m=(await r.db.query(h).withIndex("byOwnerUpdatedAt",s=>s.eq("owner",n.owner)).order("desc").take(R)).filter(s=>$(s.name,a)).toSorted((s,i)=>(i.weight??1)-(s.weight??1)||s.name.localeCompare(i.name)).slice(0,n.maxSeeds??G).map(s=>s.name);if(m.length===0)return{context:""};const p=await F(async s=>{const[i,c]=await Promise.all([r.db.query(w).withIndex("byOwnerSrc",d=>d.eq("owner",n.owner).eq("srcName",s)).collect(),r.db.query(w).withIndex("byOwnerDst",d=>d.eq("owner",n.owner).eq("dstName",s)).collect()]);return[...i,...c].map(d=>P(d))},m,{depth:n.depth??O,fanOut:n.fanOut??D,maxNodes:n.maxNodes??C});return{context:v(p)}});return{agentGraphTraverse:f(o),agentGraphUpsert:f(t)}};export{Y as graphComponent,X as graphTables,N as normalizeEntityName};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/agent",
3
- "version": "1.0.0-alpha.251",
3
+ "version": "1.0.0-alpha.253",
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",
@@ -85,13 +85,13 @@
85
85
  },
86
86
  "dependencies": {
87
87
  "@ai-sdk/provider-utils": "5.0.53",
88
- "@lunora/ai": "1.0.0-alpha.147",
88
+ "@lunora/ai": "1.0.0-alpha.148",
89
89
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
90
- "@lunora/mail": "1.0.0-alpha.125",
90
+ "@lunora/mail": "1.0.0-alpha.126",
91
91
  "@lunora/platform": "1.0.0-alpha.75",
92
- "@lunora/server": "1.0.0-alpha.241",
93
- "@lunora/values": "1.0.0-alpha.82",
94
- "@lunora/workflow": "1.0.0-alpha.96",
92
+ "@lunora/server": "1.0.0-alpha.243",
93
+ "@lunora/values": "1.0.0-alpha.83",
94
+ "@lunora/workflow": "1.0.0-alpha.97",
95
95
  "@modelcontextprotocol/sdk": "^1.32.0",
96
96
  "ai": "7.0.127",
97
97
  "yaml": "^2.9.1"
@@ -1,2 +0,0 @@
1
- import{defineTable as A,initLunora as q}from"@lunora/server";import{v as e}from"@lunora/values";import{A as _,a as f,d as S}from"./component-shared-DdXFbng-.mjs";const T="entities",x="edges",b=`${_}_${T}`,g=`${_}_${x}`,X={[T]:A({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[x]:A({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},E=64,O=2,G=4,D=8,C=32,R=500,I=/\s+/gu,K=/[^\p{L}\p{N}]+/u,h=t=>t.trim().replaceAll(I," ").toLowerCase(),L=t=>t.toLowerCase().split(K).filter(o=>o.length>=2),P=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,o)=>o.weight-t.weight||t.label.localeCompare(o.label)||t.srcName.localeCompare(o.srcName)||t.dstName.localeCompare(o.dstName),$=(t,o)=>o.some(n=>t.includes(n)||n.includes(t)),v=t=>t.map(o=>`- ${o.srcName} —[${o.label}]→ ${o.dstName}`).toSorted((o,n)=>o.localeCompare(n)).join(`
2
- `),H=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,B=(t,o,n,r)=>{const a=H(t);r.collectedKeys.has(a)||(r.collectedKeys.add(a),r.collected.push(t));const l=t.srcName===o?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<n.maxNodes&&(r.seen.add(l),r.next.push(l))},F=async(t,o,n)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(o)};let a=o.slice(0,n.maxNodes);for(let l=0;l<n.depth&&a.length>0;l+=1){r.next=[];for(const m of a){const p=(await t(m)).toSorted(U).slice(0,n.fanOut);for(const s of p)B(s,m,n,r)}a=r.next}return r.collected},{mutation:M,query:W}=q.dataModel().create(),Y=()=>{const t=M.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:n,ctx:r})=>{const a=Date.now(),l=async(s,i)=>{const c=h(s);if(c.length===0)return;const d=await r.db.query(b).withIndex("byOwnerName",u=>u.eq("owner",n.owner).eq("name",c)).first();return d?(i!==void 0&&d.type===void 0&&await r.db.patch(d._id,{type:i,updatedAt:a}),c):(await r.db.insert(b,{createdAt:a,name:c,owner:n.owner,updatedAt:a,weight:1,...S({firstMessageKey:n.messageKey,type:i})}),c)},m=async s=>{const i=h(s.src),c=h(s.dst),d=h(s.label);if(i.length===0||c.length===0||d.length===0||i===c)return!1;await l(i),await l(c);const u=s.confidence??1,N=await r.db.query(g).withIndex("byTriple",y=>y.eq("owner",n.owner).eq("srcName",i).eq("label",d).eq("dstName",c)).first();if(N){const y=N.weight??1;await r.db.patch(N._id,{updatedAt:a,weight:Math.max(y,u)})}else await r.db.insert(g,{createdAt:a,dstName:c,label:d,messageKey:n.messageKey,owner:n.owner,srcName:i,updatedAt:a,weight:u});return!0};let w=0;for(const s of n.entities.slice(0,E))await l(s.name,s.type)!==void 0&&(w+=1);let p=0;for(const s of n.relations.slice(0,E))await m(s)&&(p+=1);return{entities:w,relations:p}}),o=W.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:n,ctx:r})=>{const a=L(n.query);if(a.length===0)return{context:""};const m=(await r.db.query(b).withIndex("byOwnerUpdatedAt",s=>s.eq("owner",n.owner)).order("desc").take(R)).filter(s=>$(s.name,a)).toSorted((s,i)=>(i.weight??1)-(s.weight??1)||s.name.localeCompare(i.name)).slice(0,n.maxSeeds??G).map(s=>s.name);if(m.length===0)return{context:""};const p=await F(async s=>{const[i,c]=await Promise.all([r.db.query(g).withIndex("byOwnerSrc",d=>d.eq("owner",n.owner).eq("srcName",s)).collect(),r.db.query(g).withIndex("byOwnerDst",d=>d.eq("owner",n.owner).eq("dstName",s)).collect()]);return[...i,...c].map(d=>P(d))},m,{depth:n.depth??O,fanOut:n.fanOut??D,maxNodes:n.maxNodes??C});return{context:v(p)}});return{agentGraphTraverse:f(o),agentGraphUpsert:f(t)}};export{Y as graphComponent,X as graphTables,h as normalizeEntityName};