@lunora/agent 1.0.0-alpha.286 → 1.0.0-alpha.287
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/component.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{SecretValueTooLargeError as we}from"@lunora/platform";import{defineTable as
|
|
2
|
-
`)}});return{agentEpisodeRecall:K(r),agentEpisodeUpsert:K(d)}},z="threads",J="messages",Z="run_queue",ee="approval_grants",te="secret_requests",y=`${$}_${z}`,T=`${$}_${J}`,N=`${$}_${Z}`,x=`${$}_${ee}`,_=`${$}_${te}`,Re=50,xe=200,$e=500,V=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($,{tables:{[J]:R({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"))),approvalAgent:e.optional(e.string()),approvalSlot:e.optional(e.string()),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(),[z]:R({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(),[Z]:R({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(),[ee]:R({agent:e.string(),createdAt:e.number(),threadKey:e.string(),toolName:e.string()}).index("byThreadAgentTool",["threadKey","agent","toolName"],{unique:!0}).public(),[te]:R({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(),agent:e.optional(e.string().nullable())}).index("byThreadCall",["threadKey","toolCallId"],{unique:!0}).index("byThreadCallId",["threadKey","callId"]).public(),...qe,..._e}}),{mutation:A,query:S}=Y.dataModel().create(),Me=async(d,r,l,u,c)=>{const b=(await d.query(T).withIndex("byMessageKey",k=>k.eq("threadKey",r).gte("messageKey",`${l}:approval:`).lt("messageKey",`${l}:approval;`)).collect()).filter(k=>k.status==="awaiting_approval"&&k.toolCallId===u&&k.approvalSlot===c),[p]=b;if(b.length!==1||p===void 0)throw new g("CONFLICT",`@lunora/agent: no pending approval for tool call "${u}" on thread "${r}" to decide`);const{expiresAt:M}=p;if(typeof M=="number"&&Date.now()>=M)throw new g("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${r}" has timed out`);return p},Le=async(d,r,l,u)=>{if(typeof u.expiresAt!="number")throw new g("CONFLICT",`@lunora/agent: the approval for tool call "${String(u.toolCallId)}" on thread "${r}" has no recorded deadline, so it cannot be granted for the thread`);const c=u.toolName;await d.query(x).withIndex("byThreadAgentTool",b=>b.eq("threadKey",r).eq("agent",l).eq("toolName",c)).first()||await d.insert(x,{agent:l,createdAt:Date.now(),threadKey:r,toolName:c})},B=d=>{const{agentSecrets:r}=d;if(r===void 0)throw new g("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 r},L=(d,r,l)=>{const u=r.userId??void 0;if(d===null||u===void 0||d.owner!==u)throw new g("FORBIDDEN",`@lunora/agent: only the thread's owner can ${l}`);return d},X=async(d,r,l)=>{const{instanceId:u,key:c}=r,f=typeof u=="string"?await d.query(T).withIndex("byMessageKey",b=>b.eq("threadKey",c).eq("messageKey",`${u}:secret:${l}`)).first():void 0;if(f?.status!=="awaiting_secret")throw new g("CONFLICT",`@lunora/agent: no pending secret request for tool call "${l}" on thread "${c}"`);return f},O=async(d,r,l)=>await d.query(_).withIndex("byThreadCall",c=>c.eq("threadKey",r).eq("toolCallId",l)).first()??void 0,Q=async(d,r,l,u,c)=>{const b=(await d.query(_).withIndex("byThreadCallId",p=>p.eq("threadKey",r).eq("callId",u)).collect()).filter(p=>p.status==="pending"&&p.instanceId===l&&c<p.expiresAt);if(b.length!==1)throw new g("CONFLICT",`@lunora/agent: no pending secret request for tool call "${u}" on thread "${r}"`);return b[0]},Be=(d,r)=>Math.max(be,d+fe-r),U=async(d,r,l,u)=>{const c=await O(d,r,l);if(c?.status!=="pending"||u>=c.expiresAt)throw new g("CONFLICT",`@lunora/agent: no open secret request for tool call "${l}" on thread "${r}"`);return c},W=(d,r,l)=>{const{instanceId:u}=r,c=typeof l.agent=="string"?l.agent:r.agent,{agents:f}=d,b=f?.[c];if(typeof u!="string"||typeof b?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${c}"] producer to deliver the secret — run codegen/dev`);return{instanceId:u,sendEvent:b.sendEvent}},Ue=async(d,r,l)=>{if(r.instanceId===void 0)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:u}=r,c=await d.query(N).withIndex("byThreadInstance",p=>p.eq("threadKey",r.key).eq("instanceId",u)).first();if(c)return{outcome:"queued",position:c.position};const f=await d.query(N).withIndex("byThread",p=>p.eq("threadKey",r.key)).collect();if(f.length>=V)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" run queue is full (depth ${String(V)}) — rejecting instance "${u}"`);const b=(f.at(-1)?.position??-1)+1;return await d.insert(N,{agent:r.agent,enqueuedAt:l,instanceId:u,position:b,threadKey:r.key}),{outcome:"queued",position:b}},Pe=async(d,r,l)=>{if(r.policy==="queue")return Ue(d,{agent:r.agent,instanceId:r.instanceId,key:r.key,priorInstanceId:r.priorInstanceId},l);if(r.policy!=="replace")throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — onConcurrentRun="${r.policy}"`);return await d.patch(y,r.existingId,{error:null,status:"running",updatedAt:l,...r.instanceId===void 0?{}:{completedInstanceId:null,instanceId:r.instanceId}}),{outcome:"replaced",priorInstanceId:r.priorInstanceId}},Fe=(d,r,l)=>{const u=d.instanceId;if(u===void 0||r===u||d.status!=="running"&&d.status!=="awaiting_input")return;const c=typeof d.updatedAt=="number"?d.updatedAt:0,f=d.status==="awaiting_input"?ge:De;return l-c>f?void 0:u},Ye=()=>{const d=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(),o=await n.db.query(y).withIndex("byKey",s=>s.eq("key",t.key)).first();if(o){if(o.owner!==t.owner)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);if(t.instanceId!==void 0&&o.completedInstanceId===t.instanceId)return{outcome:"completed"};const s=Fe(o,t.instanceId,a);return s!==void 0?Pe(n.db,{agent:t.agent,existingId:o._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:s},a):(await n.db.patch(y,o._id,{error:null,status:"running",updatedAt:a,...t.instanceId===void 0?{}:{completedInstanceId:null,instanceId:t.instanceId}}),{outcome:"continued"})}return await n.db.insert(y,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...j({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),r=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"))),approvalAgent:e.optional(e.string()),approvalSlot:e.optional(e.string()),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(T).withIndex("byMessageKey",h=>h.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const o=await n.db.query(y).withIndex("byKey",h=>h.eq("key",t.threadKey)).first();if(!o)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const s=o.messageCount,i=Date.now();return await n.db.insert(T,{content:t.content,createdAt:i,messageKey:t.messageKey,role:t.role,seq:s,threadKey:t.threadKey,...t.approvalScope===void 0?{}:{approvalScope:t.approvalScope},...t.approvalAgent===void 0?{}:{approvalAgent:t.approvalAgent},...t.approvalSlot===void 0?{}:{approvalSlot:t.approvalSlot},...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(y,o._id,{messageCount:s+1,updatedAt:i}),{seq:s}}),l=A.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(T).withIndex("byMessageKey",o=>o.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(T,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:o}=t;let s;o!==void 0?s=await n.db.query(y).withIndex("byKey",i=>i.eq("key",o)).first():a!==void 0&&(s=await n.db.query(y).withIndex("byInstance",i=>i.eq("instanceId",a)).first()),!(!s||t.ifInstanceId!==void 0&&s.instanceId!==t.ifInstanceId)&&await n.db.patch(y,s._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=S.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",q=>q.eq("key",t.key)).first(),o=a?.summary,s=a?.summaryThroughSeq,i=a?.summaryRebuiltSeq,h=a?.summaryConfig,m=typeof o=="string"&&o.length>0&&typeof s=="number",w=t.configKey===void 0||h===t.configKey,I=typeof i!="number"||typeof s=="number"&&s>=2*i+1,C=m&&w&&!I,v=await n.db.query(T).withIndex("byThread",q=>C?q.eq("threadKey",t.key).gt("seq",s):q.eq("threadKey",t.key)).collect();return C?{messages:v,summary:o}:m?{fallback:{summary:o,throughSeq:s},messages:v}:{messages:v}}),f=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(),o=await n.db.query(y).withIndex("byKey",w=>w.eq("key",t.key)).first();if(o?.instanceId!==t.instanceId){if(o?.completedInstanceId===t.instanceId&&o.status==="running"&&typeof o.instanceId=="string")return{dequeued:o.instanceId};const w=await n.db.query(N).withIndex("byThreadInstance",I=>I.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return w&&await n.db.delete(N,w._id),{}}const h=(o.completedInstanceId===t.instanceId?[]:await n.db.query(N).withIndex("byThread",w=>w.eq("threadKey",t.key)).collect())[0];if(!h)return await n.db.patch(y,o._id,{completedInstanceId:t.instanceId,status:t.status,updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{};const m=h.instanceId;return await n.db.delete(N,h._id),await n.db.patch(y,o._id,{completedInstanceId:t.instanceId,instanceId:m,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:m}}),b=A.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",o=>o.eq("key",t.key)).first();a&&await n.db.patch(y,a._id,{state:t.state,updatedAt:Date.now()})}),p=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},M=S.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",o=>o.eq("key",t.key)).first();return p(a,n.auth)}),k=S.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",o=>o.eq("key",t.key)).first();return p(a,n.auth)?.state}),ne=S.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",o=>o.eq("key",t.key)).first();return p(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(T).withIndex("byThread",s=>s.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(T).withIndex("byThread",o=>o.eq("threadKey",t.key)).collect()}),ae=S.input({limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const{userId:a}=n.auth;if(!a)return[];const o=await n.db.query(y).withIndex("byOwnerStatus",I=>I.eq("owner",a).eq("status","awaiting_input")).order("desc").take($e),s=Date.now(),i=Math.min(xe,Math.max(1,Math.trunc(t.limit??Re))),h=async I=>{const C=I.instanceId;if(C===void 0)return[];const v=`${C}:approval:`,q=`${C}:approval;`;return(await n.db.query(T).withIndex("byMessageKey",E=>E.eq("threadKey",I.key).gte("messageKey",v).lt("messageKey",q)).collect()).filter(E=>E.status==="awaiting_approval"&&typeof E.expiresAt=="number"&&s<E.expiresAt).map(E=>j({agent:I.agent,approvalSlot:E.approvalSlot,content:E.content,instanceId:C,requestedAt:E.createdAt,threadKey:I.key,threadTitle:I.title,threadUpdatedAt:I.updatedAt,toolCallId:E.toolCallId,toolName:E.toolName}))},m=[];let w=0;for(let I=0;I<o.length&&w<i;I+=i){const C=await Promise.all(o.slice(I,I+i).map(v=>h(v)));for(const v of C)v.length>0&&w<i&&(m.push(...v),w+=1)}return m}),oe=A.input({approvalSlot:e.string(),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(y).withIndex("byKey",w=>w.eq("key",t.threadKey)).first(),o=p(a,n.auth);if(o===void 0)throw new g("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(o.instanceId!==t.instanceId)throw new g("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const s=await Me(n.db,t.threadKey,t.instanceId,t.toolCallId,t.approvalSlot),i=s.approvalAgent;if(typeof i!="string")throw new g("CONFLICT",`@lunora/agent: no pending approval for tool call "${t.toolCallId}" on thread "${t.threadKey}" to decide`);const{agents:h}=n,m=h?.[i];if(typeof m?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${i}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);return t.decision==="approve_for_thread"&&(L(a,n.auth,"grant a lasting approval for a tool"),await Le(n.db,t.threadKey,i,s)),await n.db.delete(T,s._id),await m.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.approvalSlot}`}),{resolved:!0}}),ie=A.input({secret:e.sensitive(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=L(await n.db.query(y).withIndex("byKey",q=>q.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),o=B(n),s=await Q(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now()),i=s.toolCallId,h=await X(n.db,a,i),m=W(n,a,s),w=a.instanceId,I=q=>{if(q.instanceId!==w)throw new g("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 U(n.db,t.threadKey,i,Date.now());I(C);let v;try{v=await o.put(t.secret,{scope:t.threadKey,ttlMs:Be(C.expiresAt,Date.now())})}catch(q){throw q instanceof we?new g("PAYLOAD_TOO_LARGE",q.message):q}try{const q=await U(n.db,t.threadKey,i,Date.now());I(q),await n.db.patch(_,q._id,{ref:v,status:"supplied",updatedAt:Date.now()}),await n.db.delete(T,h._id)}catch(q){throw await o.discard(v).catch(()=>{}),q}try{await m.sendEvent(m.instanceId,{payload:{},type:`agent-secret:${i}`})}catch{}return{resolved:!0}}),re=A.input({threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=L(await n.db.query(y).withIndex("byKey",w=>w.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),o=await Q(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now()),s=o.toolCallId,i=await X(n.db,a,s),h=W(n,a,o),m=await U(n.db,t.threadKey,s,Date.now());await n.db.patch(_,m._id,{status:"declined",updatedAt:Date.now()}),await n.db.delete(T,i._id);try{await h.sendEvent(h.instanceId,{payload:{},type:`agent-secret:${s}`})}catch{}return{resolved:!0}}),se=K(A.input({agent:e.optional(e.string()),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),o=Date.now();if(a===void 0){await n.db.insert(_,{agent:t.agent??null,consumerTool:t.consumerTool,createdAt:o,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:o});return}if(a.instanceId!==t.instanceId){if(typeof a.ref=="string"){const{agentSecrets:s}=n;await s?.discard(a.ref)}await n.db.patch(_,a._id,{agent:t.agent??null,consumerTool:t.consumerTool,createdAt:o,expiresAt:t.expiresAt,label:t.label??null,ref:null,callId:t.callId??t.toolCallId,instanceId:t.instanceId,status:"pending",toolName:t.toolName,updatedAt:o})}})),de=K(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:o}=a;return o==="pending"?(await n.db.patch(_,a._id,{status:"expired",updatedAt:Date.now()}),{status:"expired"}):o==="supplied"||o==="consumed"?{status:"supplied"}:{status:o==="declined"?"declined":"expired"}})),le=K(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 B(n).take(a.ref,{claimant:t.claimant,scope:t.threadKey})})),ue=K(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 B(n).discard(a.ref),a.status==="supplied"&&await n.db.patch(_,a._id,{status:"consumed",updatedAt:Date.now()}))})),ce=S.input({threadKey:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",i=>i.eq("key",t.threadKey)).first();L(a,n.auth,"list its secret requests");const o=await n.db.query(_).withIndex("byThreadCall",i=>i.eq("threadKey",t.threadKey)).collect(),s=Date.now();return o.map(i=>({createdAt:i.createdAt,expiresAt:i.expiresAt,...typeof i.label=="string"?{label:i.label}:{},status:i.status==="pending"&&s>=i.expiresAt?"expired":i.status,toolCallId:i.callId??i.toolCallId,toolName:i.toolName}))}),pe=K(S.input({agent:e.string(),key:e.string(),toolName:e.string()}).query(async({args:t,ctx:n})=>await n.db.query(x).withIndex("byThreadAgentTool",o=>o.eq("threadKey",t.key).eq("agent",t.agent).eq("toolName",t.toolName)).first()!==null)),ye=S.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",i=>i.eq("key",t.key)).first();if(p(a,n.auth)===void 0)return[];const o=await n.db.query(x).withIndex("byThreadAgentTool",i=>i.eq("threadKey",t.key)).collect(),s=new Map;for(const i of o){if(i.agent===void 0)continue;const h=i.toolName,m=i.createdAt,w=s.get(h);(w===void 0||m<w.createdAt)&&s.set(h,{createdAt:m,toolName:h})}return[...s.values()]}),he=A.input({threadKey:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",i=>i.eq("key",t.threadKey)).first();if(p(a,n.auth)===void 0)throw new g("FORBIDDEN",`@lunora/agent: not allowed to revoke approvals on thread "${t.threadKey}"`);const s=(await n.db.query(x).withIndex("byThreadAgentTool",i=>i.eq("threadKey",t.threadKey)).collect()).filter(i=>i.toolName===t.toolName);for(const i of s)await n.db.delete(x,i._id);return{revoked:s.length>0}}),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,o=a?.[t.agent];if(typeof o?.run!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${t.agent}"] producer to start a run — run codegen/dev so the agent binding is wired, and check the agent name`);if(o.publicRun!==!0)throw new g("FORBIDDEN",`@lunora/agent: agent "${t.agent}" is not enabled for public runs — set defineAgent({ publicRun: true }) to allow an external client (e.g. the @lunora/mcp server) to start it`);const s=n.auth.userId??void 0,i=await n.db.query(y).withIndex("byKey",m=>m.eq("key",t.threadKey)).first();if(i){const m=i.status,w=i.instanceId,I=i.owner;if((m==="running"||m==="awaiting_input")&&w!==void 0&&(I===void 0||I===s))return{id:w,threadKey:t.threadKey};if(I!==s)throw new g("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:h}=await o.run({input:t.input,threadKey:t.threadKey,...s===void 0?{}:{owner:s},...t.title===void 0?{}:{title:t.title}});return{id:h,threadKey:t.threadKey}}),F=Ae(),G=Ne();return{extension:Oe,functions:{agentApprovalGranted:pe,agentApprovalGrants:ye,agentAppendMessage:K(r),agentCompleteRun:K(f),agentEnsureThread:K(d),agentEpisodeRecall:G.agentEpisodeRecall,agentEpisodeUpsert:G.agentEpisodeUpsert,agentGraphTraverse:F.agentGraphTraverse,agentGraphUpsert:F.agentGraphUpsert,agentHistory:K(c),agentMessages:ne,agentDeleteMessage:K(l),agentPatchThread:K(u),agentPendingApprovals:ae,agentResolveApproval:oe,agentRevokeApprovalGrant:he,agentRun:me,agentSetState:K(b),agentState:k,agentSupplySecret:ie,agentTakeSecret:le,agentThread:M,agentDeclineSecret:re,agentDiscardSecret:ue,agentOpenSecretRequest:se,agentSecretRequests:ce,agentSettleSecretRequest:de}}};export{Ye as agentComponent,Oe as agentExtension,Ze as normalizeEntityName,tt as sandboxComponent};
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{SecretValueTooLargeError as we}from"@lunora/platform";import{defineTable as x,initLunora as Y,defineSchemaExtension as Ie}from"@lunora/server";import{v as e}from"@lunora/values";import{b as K,A as $,d as j,c as ge,e as be,S as fe}from"./packem_shared/component-shared--SPcu0Iw.mjs";import{graphTables as qe,graphComponent as Ae}from"./packem_shared/normalizeEntityName-CknxOaNc.mjs";import{normalizeEntityName as Ze}from"./packem_shared/normalizeEntityName-CknxOaNc.mjs";import{sandboxComponent as tt}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const D="agent_episodes",ve=5,Ke=20,Te=500,H=200,Ce=/\s+/gu,Ee=d=>d===void 0||!Number.isFinite(d)?ve:Math.min(Ke,Math.max(1,Math.trunc(d))),_e={episodes:x({createdAt:e.number(),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).externallyManaged().index("byOwnerCreatedAt",["owner","createdAt"]).index("byOwnerMessageKey",["owner","messageKey"],{unique:!0}).public()},{mutation:Se,query:ke}=Y.dataModel().create(),Ne=()=>{const d=Se.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",p=>p.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 b=await u.db.query(D).withIndex("byOwnerCreatedAt",p=>p.eq("owner",l.owner)).order("asc").take(H+1);for(const p of b.slice(0,Math.max(0,b.length-H)))await u.db.delete(D,p._id);return{recorded:!0}}),r=ke.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:l,ctx:u})=>{const c=await u.db.query(D).withIndex("byOwnerCreatedAt",f=>f.eq("owner",l.owner)).order("desc").take(Ee(l.limit));return c.length===0?{context:""}:{context:c.toReversed().map(f=>`- ${f.summary}`).join(`
|
|
2
|
+
`)}});return{agentEpisodeRecall:K(r),agentEpisodeUpsert:K(d)}},z="threads",J="messages",Z="run_queue",ee="approval_grants",te="secret_requests",y=`${$}_${z}`,T=`${$}_${J}`,N=`${$}_${Z}`,R=`${$}_${ee}`,_=`${$}_${te}`,xe=50,Re=200,$e=500,V=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,Me=Ie($,{tables:{[J]:x({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"))),approvalAgent:e.optional(e.string()),approvalSlot:e.optional(e.string()),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())}).externallyManaged().index("byThread",["threadKey","seq"]).index("byMessageKey",["threadKey","messageKey"],{unique:!0}).public(),[z]:x({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)}).externallyManaged().index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).index("byOwnerStatus",["owner","status","updatedAt"]).public(),[Z]:x({agent:e.string(),enqueuedAt:e.number(),instanceId:e.string(),position:e.number(),threadKey:e.string()}).externallyManaged().index("byThread",["threadKey","position"]).index("byThreadInstance",["threadKey","instanceId"],{unique:!0}).public(),[ee]:x({agent:e.string(),createdAt:e.number(),threadKey:e.string(),toolName:e.string()}).externallyManaged().index("byThreadAgentTool",["threadKey","agent","toolName"],{unique:!0}).public(),[te]:x({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(),agent:e.optional(e.string().nullable())}).externallyManaged().index("byThreadCall",["threadKey","toolCallId"],{unique:!0}).index("byThreadCallId",["threadKey","callId"]).public(),...qe,..._e}}),{mutation:A,query:S}=Y.dataModel().create(),Oe=async(d,r,l,u,c)=>{const b=(await d.query(T).withIndex("byMessageKey",k=>k.eq("threadKey",r).gte("messageKey",`${l}:approval:`).lt("messageKey",`${l}:approval;`)).collect()).filter(k=>k.status==="awaiting_approval"&&k.toolCallId===u&&k.approvalSlot===c),[p]=b;if(b.length!==1||p===void 0)throw new g("CONFLICT",`@lunora/agent: no pending approval for tool call "${u}" on thread "${r}" to decide`);const{expiresAt:O}=p;if(typeof O=="number"&&Date.now()>=O)throw new g("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${r}" has timed out`);return p},Le=async(d,r,l,u)=>{if(typeof u.expiresAt!="number")throw new g("CONFLICT",`@lunora/agent: the approval for tool call "${String(u.toolCallId)}" on thread "${r}" has no recorded deadline, so it cannot be granted for the thread`);const c=u.toolName;await d.query(R).withIndex("byThreadAgentTool",b=>b.eq("threadKey",r).eq("agent",l).eq("toolName",c)).first()||await d.insert(R,{agent:l,createdAt:Date.now(),threadKey:r,toolName:c})},B=d=>{const{agentSecrets:r}=d;if(r===void 0)throw new g("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 r},L=(d,r,l)=>{const u=r.userId??void 0;if(d===null||u===void 0||d.owner!==u)throw new g("FORBIDDEN",`@lunora/agent: only the thread's owner can ${l}`);return d},X=async(d,r,l)=>{const{instanceId:u,key:c}=r,f=typeof u=="string"?await d.query(T).withIndex("byMessageKey",b=>b.eq("threadKey",c).eq("messageKey",`${u}:secret:${l}`)).first():void 0;if(f?.status!=="awaiting_secret")throw new g("CONFLICT",`@lunora/agent: no pending secret request for tool call "${l}" on thread "${c}"`);return f},M=async(d,r,l)=>await d.query(_).withIndex("byThreadCall",c=>c.eq("threadKey",r).eq("toolCallId",l)).first()??void 0,Q=async(d,r,l,u,c)=>{const b=(await d.query(_).withIndex("byThreadCallId",p=>p.eq("threadKey",r).eq("callId",u)).collect()).filter(p=>p.status==="pending"&&p.instanceId===l&&c<p.expiresAt);if(b.length!==1)throw new g("CONFLICT",`@lunora/agent: no pending secret request for tool call "${u}" on thread "${r}"`);return b[0]},Be=(d,r)=>Math.max(be,d+fe-r),U=async(d,r,l,u)=>{const c=await M(d,r,l);if(c?.status!=="pending"||u>=c.expiresAt)throw new g("CONFLICT",`@lunora/agent: no open secret request for tool call "${l}" on thread "${r}"`);return c},W=(d,r,l)=>{const{instanceId:u}=r,c=typeof l.agent=="string"?l.agent:r.agent,{agents:f}=d,b=f?.[c];if(typeof u!="string"||typeof b?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${c}"] producer to deliver the secret — run codegen/dev`);return{instanceId:u,sendEvent:b.sendEvent}},Ue=async(d,r,l)=>{if(r.instanceId===void 0)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:u}=r,c=await d.query(N).withIndex("byThreadInstance",p=>p.eq("threadKey",r.key).eq("instanceId",u)).first();if(c)return{outcome:"queued",position:c.position};const f=await d.query(N).withIndex("byThread",p=>p.eq("threadKey",r.key)).collect();if(f.length>=V)throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" run queue is full (depth ${String(V)}) — rejecting instance "${u}"`);const b=(f.at(-1)?.position??-1)+1;return await d.insert(N,{agent:r.agent,enqueuedAt:l,instanceId:u,position:b,threadKey:r.key}),{outcome:"queued",position:b}},Pe=async(d,r,l)=>{if(r.policy==="queue")return Ue(d,{agent:r.agent,instanceId:r.instanceId,key:r.key,priorInstanceId:r.priorInstanceId},l);if(r.policy!=="replace")throw new g("CONFLICT",`@lunora/agent: thread "${r.key}" already has a run in flight (instance "${r.priorInstanceId}") — onConcurrentRun="${r.policy}"`);return await d.patch(y,r.existingId,{error:null,status:"running",updatedAt:l,...r.instanceId===void 0?{}:{completedInstanceId:null,instanceId:r.instanceId}}),{outcome:"replaced",priorInstanceId:r.priorInstanceId}},Fe=(d,r,l)=>{const u=d.instanceId;if(u===void 0||r===u||d.status!=="running"&&d.status!=="awaiting_input")return;const c=typeof d.updatedAt=="number"?d.updatedAt:0,f=d.status==="awaiting_input"?ge:De;return l-c>f?void 0:u},Ye=()=>{const d=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(),o=await n.db.query(y).withIndex("byKey",s=>s.eq("key",t.key)).first();if(o){if(o.owner!==t.owner)throw new Error(`@lunora/agent: thread "${t.key}" belongs to another owner`);if(t.instanceId!==void 0&&o.completedInstanceId===t.instanceId)return{outcome:"completed"};const s=Fe(o,t.instanceId,a);return s!==void 0?Pe(n.db,{agent:t.agent,existingId:o._id,instanceId:t.instanceId,key:t.key,policy:t.onConcurrentRun??"reject",priorInstanceId:s},a):(await n.db.patch(y,o._id,{error:null,status:"running",updatedAt:a,...t.instanceId===void 0?{}:{completedInstanceId:null,instanceId:t.instanceId}}),{outcome:"continued"})}return await n.db.insert(y,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...j({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),r=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"))),approvalAgent:e.optional(e.string()),approvalSlot:e.optional(e.string()),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(T).withIndex("byMessageKey",h=>h.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const o=await n.db.query(y).withIndex("byKey",h=>h.eq("key",t.threadKey)).first();if(!o)throw new Error(`@lunora/agent: cannot append to unknown thread "${t.threadKey}" — run agentEnsureThread first`);const s=o.messageCount,i=Date.now();return await n.db.insert(T,{content:t.content,createdAt:i,messageKey:t.messageKey,role:t.role,seq:s,threadKey:t.threadKey,...t.approvalScope===void 0?{}:{approvalScope:t.approvalScope},...t.approvalAgent===void 0?{}:{approvalAgent:t.approvalAgent},...t.approvalSlot===void 0?{}:{approvalSlot:t.approvalSlot},...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(y,o._id,{messageCount:s+1,updatedAt:i}),{seq:s}}),l=A.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(T).withIndex("byMessageKey",o=>o.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(T,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:o}=t;let s;o!==void 0?s=await n.db.query(y).withIndex("byKey",i=>i.eq("key",o)).first():a!==void 0&&(s=await n.db.query(y).withIndex("byInstance",i=>i.eq("instanceId",a)).first()),!(!s||t.ifInstanceId!==void 0&&s.instanceId!==t.ifInstanceId)&&await n.db.patch(y,s._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=S.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",q=>q.eq("key",t.key)).first(),o=a?.summary,s=a?.summaryThroughSeq,i=a?.summaryRebuiltSeq,h=a?.summaryConfig,m=typeof o=="string"&&o.length>0&&typeof s=="number",w=t.configKey===void 0||h===t.configKey,I=typeof i!="number"||typeof s=="number"&&s>=2*i+1,C=m&&w&&!I,v=await n.db.query(T).withIndex("byThread",q=>C?q.eq("threadKey",t.key).gt("seq",s):q.eq("threadKey",t.key)).collect();return C?{messages:v,summary:o}:m?{fallback:{summary:o,throughSeq:s},messages:v}:{messages:v}}),f=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(),o=await n.db.query(y).withIndex("byKey",w=>w.eq("key",t.key)).first();if(o?.instanceId!==t.instanceId){if(o?.completedInstanceId===t.instanceId&&o.status==="running"&&typeof o.instanceId=="string")return{dequeued:o.instanceId};const w=await n.db.query(N).withIndex("byThreadInstance",I=>I.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return w&&await n.db.delete(N,w._id),{}}const h=(o.completedInstanceId===t.instanceId?[]:await n.db.query(N).withIndex("byThread",w=>w.eq("threadKey",t.key)).collect())[0];if(!h)return await n.db.patch(y,o._id,{completedInstanceId:t.instanceId,status:t.status,updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{};const m=h.instanceId;return await n.db.delete(N,h._id),await n.db.patch(y,o._id,{completedInstanceId:t.instanceId,instanceId:m,status:"running",updatedAt:a,...t.error===void 0?{}:{error:t.error},...t.usage===void 0?{}:{usage:t.usage}}),{dequeued:m}}),b=A.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",o=>o.eq("key",t.key)).first();a&&await n.db.patch(y,a._id,{state:t.state,updatedAt:Date.now()})}),p=(t,n)=>{if(!t)return;const{owner:a}=t;if(!(a!==void 0&&a!==(n.userId??void 0)))return t},O=S.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",o=>o.eq("key",t.key)).first();return p(a,n.auth)}),k=S.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",o=>o.eq("key",t.key)).first();return p(a,n.auth)?.state}),ne=S.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",o=>o.eq("key",t.key)).first();return p(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(T).withIndex("byThread",s=>s.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(T).withIndex("byThread",o=>o.eq("threadKey",t.key)).collect()}),ae=S.input({limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const{userId:a}=n.auth;if(!a)return[];const o=await n.db.query(y).withIndex("byOwnerStatus",I=>I.eq("owner",a).eq("status","awaiting_input")).order("desc").take($e),s=Date.now(),i=Math.min(Re,Math.max(1,Math.trunc(t.limit??xe))),h=async I=>{const C=I.instanceId;if(C===void 0)return[];const v=`${C}:approval:`,q=`${C}:approval;`;return(await n.db.query(T).withIndex("byMessageKey",E=>E.eq("threadKey",I.key).gte("messageKey",v).lt("messageKey",q)).collect()).filter(E=>E.status==="awaiting_approval"&&typeof E.expiresAt=="number"&&s<E.expiresAt).map(E=>j({agent:I.agent,approvalSlot:E.approvalSlot,content:E.content,instanceId:C,requestedAt:E.createdAt,threadKey:I.key,threadTitle:I.title,threadUpdatedAt:I.updatedAt,toolCallId:E.toolCallId,toolName:E.toolName}))},m=[];let w=0;for(let I=0;I<o.length&&w<i;I+=i){const C=await Promise.all(o.slice(I,I+i).map(v=>h(v)));for(const v of C)v.length>0&&w<i&&(m.push(...v),w+=1)}return m}),oe=A.input({approvalSlot:e.string(),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(y).withIndex("byKey",w=>w.eq("key",t.threadKey)).first(),o=p(a,n.auth);if(o===void 0)throw new g("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(o.instanceId!==t.instanceId)throw new g("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const s=await Oe(n.db,t.threadKey,t.instanceId,t.toolCallId,t.approvalSlot),i=s.approvalAgent;if(typeof i!="string")throw new g("CONFLICT",`@lunora/agent: no pending approval for tool call "${t.toolCallId}" on thread "${t.threadKey}" to decide`);const{agents:h}=n,m=h?.[i];if(typeof m?.sendEvent!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${i}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);return t.decision==="approve_for_thread"&&(L(a,n.auth,"grant a lasting approval for a tool"),await Le(n.db,t.threadKey,i,s)),await n.db.delete(T,s._id),await m.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.approvalSlot}`}),{resolved:!0}}),ie=A.input({secret:e.sensitive(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=L(await n.db.query(y).withIndex("byKey",q=>q.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),o=B(n),s=await Q(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now()),i=s.toolCallId,h=await X(n.db,a,i),m=W(n,a,s),w=a.instanceId,I=q=>{if(q.instanceId!==w)throw new g("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 U(n.db,t.threadKey,i,Date.now());I(C);let v;try{v=await o.put(t.secret,{scope:t.threadKey,ttlMs:Be(C.expiresAt,Date.now())})}catch(q){throw q instanceof we?new g("PAYLOAD_TOO_LARGE",q.message):q}try{const q=await U(n.db,t.threadKey,i,Date.now());I(q),await n.db.patch(_,q._id,{ref:v,status:"supplied",updatedAt:Date.now()}),await n.db.delete(T,h._id)}catch(q){throw await o.discard(v).catch(()=>{}),q}try{await m.sendEvent(m.instanceId,{payload:{},type:`agent-secret:${i}`})}catch{}return{resolved:!0}}),re=A.input({threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=L(await n.db.query(y).withIndex("byKey",w=>w.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),o=await Q(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now()),s=o.toolCallId,i=await X(n.db,a,s),h=W(n,a,o),m=await U(n.db,t.threadKey,s,Date.now());await n.db.patch(_,m._id,{status:"declined",updatedAt:Date.now()}),await n.db.delete(T,i._id);try{await h.sendEvent(h.instanceId,{payload:{},type:`agent-secret:${s}`})}catch{}return{resolved:!0}}),se=K(A.input({agent:e.optional(e.string()),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 M(n.db,t.threadKey,t.toolCallId),o=Date.now();if(a===void 0){await n.db.insert(_,{agent:t.agent??null,consumerTool:t.consumerTool,createdAt:o,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:o});return}if(a.instanceId!==t.instanceId){if(typeof a.ref=="string"){const{agentSecrets:s}=n;await s?.discard(a.ref)}await n.db.patch(_,a._id,{agent:t.agent??null,consumerTool:t.consumerTool,createdAt:o,expiresAt:t.expiresAt,label:t.label??null,ref:null,callId:t.callId??t.toolCallId,instanceId:t.instanceId,status:"pending",toolName:t.toolName,updatedAt:o})}})),de=K(A.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await M(n.db,t.threadKey,t.toolCallId);if(a?.instanceId!==t.instanceId)return{status:"expired"};const{status:o}=a;return o==="pending"?(await n.db.patch(_,a._id,{status:"expired",updatedAt:Date.now()}),{status:"expired"}):o==="supplied"||o==="consumed"?{status:"supplied"}:{status:o==="declined"?"declined":"expired"}})),le=K(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 M(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 B(n).take(a.ref,{claimant:t.claimant,scope:t.threadKey})})),ue=K(A.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await M(n.db,t.threadKey,t.toolCallId);a?.instanceId===t.instanceId&&(typeof a.ref=="string"&&await B(n).discard(a.ref),a.status==="supplied"&&await n.db.patch(_,a._id,{status:"consumed",updatedAt:Date.now()}))})),ce=S.input({threadKey:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",i=>i.eq("key",t.threadKey)).first();L(a,n.auth,"list its secret requests");const o=await n.db.query(_).withIndex("byThreadCall",i=>i.eq("threadKey",t.threadKey)).collect(),s=Date.now();return o.map(i=>({createdAt:i.createdAt,expiresAt:i.expiresAt,...typeof i.label=="string"?{label:i.label}:{},status:i.status==="pending"&&s>=i.expiresAt?"expired":i.status,toolCallId:i.callId??i.toolCallId,toolName:i.toolName}))}),pe=K(S.input({agent:e.string(),key:e.string(),toolName:e.string()}).query(async({args:t,ctx:n})=>await n.db.query(R).withIndex("byThreadAgentTool",o=>o.eq("threadKey",t.key).eq("agent",t.agent).eq("toolName",t.toolName)).first()!==null)),ye=S.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",i=>i.eq("key",t.key)).first();if(p(a,n.auth)===void 0)return[];const o=await n.db.query(R).withIndex("byThreadAgentTool",i=>i.eq("threadKey",t.key)).collect(),s=new Map;for(const i of o){if(i.agent===void 0)continue;const h=i.toolName,m=i.createdAt,w=s.get(h);(w===void 0||m<w.createdAt)&&s.set(h,{createdAt:m,toolName:h})}return[...s.values()]}),he=A.input({threadKey:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(y).withIndex("byKey",i=>i.eq("key",t.threadKey)).first();if(p(a,n.auth)===void 0)throw new g("FORBIDDEN",`@lunora/agent: not allowed to revoke approvals on thread "${t.threadKey}"`);const s=(await n.db.query(R).withIndex("byThreadAgentTool",i=>i.eq("threadKey",t.threadKey)).collect()).filter(i=>i.toolName===t.toolName);for(const i of s)await n.db.delete(R,i._id);return{revoked:s.length>0}}),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,o=a?.[t.agent];if(typeof o?.run!="function")throw new g("INTERNAL",`@lunora/agent: no ctx.agents["${t.agent}"] producer to start a run — run codegen/dev so the agent binding is wired, and check the agent name`);if(o.publicRun!==!0)throw new g("FORBIDDEN",`@lunora/agent: agent "${t.agent}" is not enabled for public runs — set defineAgent({ publicRun: true }) to allow an external client (e.g. the @lunora/mcp server) to start it`);const s=n.auth.userId??void 0,i=await n.db.query(y).withIndex("byKey",m=>m.eq("key",t.threadKey)).first();if(i){const m=i.status,w=i.instanceId,I=i.owner;if((m==="running"||m==="awaiting_input")&&w!==void 0&&(I===void 0||I===s))return{id:w,threadKey:t.threadKey};if(I!==s)throw new g("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:h}=await o.run({input:t.input,threadKey:t.threadKey,...s===void 0?{}:{owner:s},...t.title===void 0?{}:{title:t.title}});return{id:h,threadKey:t.threadKey}}),F=Ae(),G=Ne();return{extension:Me,functions:{agentApprovalGranted:pe,agentApprovalGrants:ye,agentAppendMessage:K(r),agentCompleteRun:K(f),agentEnsureThread:K(d),agentEpisodeRecall:G.agentEpisodeRecall,agentEpisodeUpsert:G.agentEpisodeUpsert,agentGraphTraverse:F.agentGraphTraverse,agentGraphUpsert:F.agentGraphUpsert,agentHistory:K(c),agentMessages:ne,agentDeleteMessage:K(l),agentPatchThread:K(u),agentPendingApprovals:ae,agentResolveApproval:oe,agentRevokeApprovalGrant:he,agentRun:me,agentSetState:K(b),agentState:k,agentSupplySecret:ie,agentTakeSecret:le,agentThread:O,agentDeclineSecret:re,agentDiscardSecret:ue,agentOpenSecretRequest:se,agentSecretRequests:ce,agentSettleSecretRequest:de}}};export{Ye as agentComponent,Me as agentExtension,Ze as normalizeEntityName,tt 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 _,b as f,d as S}from"./component-shared--SPcu0Iw.mjs";const x="entities",T="edges",h=`${_}_${x}`,w=`${_}_${T}`,X={[x]: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())}).externallyManaged().index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[T]: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())}).externallyManaged().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(a=>a.length>=2),P=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,a)=>a.weight-t.weight||t.label.localeCompare(a.label)||t.srcName.localeCompare(a.srcName)||t.dstName.localeCompare(a.dstName),$=(t,a)=>a.some(n=>t.includes(n)||n.includes(t)),v=t=>t.map(a=>`- ${a.srcName} —[${a.label}]→ ${a.dstName}`).toSorted((a,n)=>a.localeCompare(n)).join(`
|
|
2
|
+
`),H=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,M=(t,a,n,r)=>{const o=H(t);r.collectedKeys.has(o)||(r.collectedKeys.add(o),r.collected.push(t));const l=t.srcName===a?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<n.maxNodes&&(r.seen.add(l),r.next.push(l))},B=async(t,a,n)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(a)};let o=a.slice(0,n.maxNodes);for(let l=0;l<n.depth&&o.length>0;l+=1){r.next=[];for(const m of o){const p=(await t(m)).toSorted(U).slice(0,n.fanOut);for(const s of p)M(s,m,n,r)}o=r.next}return r.collected},{mutation:F,query:W}=q.dataModel().create(),Y=()=>{const t=F.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 o=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:o}),c):(await r.db.insert(h,{createdAt:o,name:c,owner:n.owner,updatedAt:o,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:o,weight:Math.max(b,g)})}else await r.db.insert(w,{createdAt:o,dstName:c,label:d,messageKey:n.messageKey,owner:n.owner,srcName:i,updatedAt:o,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}}),a=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 o=L(n.query);if(o.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,o)).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 B(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(a),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.
|
|
3
|
+
"version": "1.0.0-alpha.287",
|
|
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",
|
|
@@ -93,7 +93,7 @@
|
|
|
93
93
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
94
94
|
"@lunora/mail": "^1.0.0-alpha.139",
|
|
95
95
|
"@lunora/platform": "^1.0.0-alpha.81",
|
|
96
|
-
"@lunora/server": "^1.0.0-alpha.
|
|
96
|
+
"@lunora/server": "^1.0.0-alpha.280",
|
|
97
97
|
"@lunora/values": "^1.0.0-alpha.95",
|
|
98
98
|
"@lunora/workflow": "^1.0.0-alpha.111",
|
|
99
99
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
@@ -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 _,b as f,d as S}from"./component-shared--SPcu0Iw.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};
|