@lunora/agent 1.0.0-alpha.235 → 1.0.0-alpha.237

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.
@@ -125,6 +125,7 @@ interface AgentComponent {
125
125
  agentMessages: AgentRegisteredFunction;
126
126
  agentOpenSecretRequest: AgentRegisteredFunction;
127
127
  agentPatchThread: AgentRegisteredFunction;
128
+ agentPendingApprovals: AgentRegisteredFunction;
128
129
  agentResolveApproval: AgentRegisteredFunction;
129
130
  agentRevokeApprovalGrant: AgentRegisteredFunction;
130
131
  agentRun: AgentRegisteredFunction;
@@ -125,6 +125,7 @@ interface AgentComponent {
125
125
  agentMessages: AgentRegisteredFunction;
126
126
  agentOpenSecretRequest: AgentRegisteredFunction;
127
127
  agentPatchThread: AgentRegisteredFunction;
128
+ agentPendingApprovals: AgentRegisteredFunction;
128
129
  agentResolveApproval: AgentRegisteredFunction;
129
130
  agentRevokeApprovalGrant: AgentRegisteredFunction;
130
131
  agentRun: AgentRegisteredFunction;
@@ -1,2 +1,2 @@
1
- import{LunoraError as h}from"@lunora/errors";import{SecretValueTooLargeError as pe}from"@lunora/platform";import{defineTable as E,initLunora as W,defineSchemaExtension as he}from"@lunora/server";import{v as e}from"@lunora/values";import{a as K,A as _,d as me,b as we,c as Ie,S as be}from"./packem_shared/component-shared-DdXFbng-.mjs";import{graphTables as ge,graphComponent as fe}from"./packem_shared/normalizeEntityName-CmalZhT_.mjs";import{normalizeEntityName as Xe}from"./packem_shared/normalizeEntityName-CmalZhT_.mjs";import{sandboxComponent as Ye}from"./packem_shared/sandboxComponent-Du0yENEO.mjs";const x="agent_episodes",qe=5,Ke=20,ve=500,G=200,Ae=/\s+/gu,Te=s=>s===void 0||!Number.isFinite(s)?qe:Math.min(Ke,Math.max(1,Math.trunc(s))),Ce={episodes:E({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:Ee,query:_e}=W.dataModel().create(),ke=()=>{const s=Ee.input({createdAt:e.optional(e.number()),messageKey:e.string(),owner:e.string(),summary:e.string(),threadKey:e.optional(e.string())}).mutation(async({args:d,ctx:l})=>{const c=d.summary.replaceAll(Ae," ").trim().slice(0,ve);if(c.length===0)return{recorded:!1};if(await l.db.query(x).withIndex("byOwnerMessageKey",y=>y.eq("owner",d.owner).eq("messageKey",d.messageKey)).first())return{recorded:!1};await l.db.insert(x,{createdAt:d.createdAt??Date.now(),messageKey:d.messageKey,owner:d.owner,summary:c,...d.threadKey===void 0?{}:{threadKey:d.threadKey}});const g=await l.db.query(x).withIndex("byOwnerCreatedAt",y=>y.eq("owner",d.owner)).order("asc").take(G+1);for(const y of g.slice(0,Math.max(0,g.length-G)))await l.db.delete(y._id);return{recorded:!0}}),o=_e.input({limit:e.optional(e.number()),owner:e.string()}).query(async({args:d,ctx:l})=>{const c=await l.db.query(x).withIndex("byOwnerCreatedAt",p=>p.eq("owner",d.owner)).order("desc").take(Te(d.limit));return c.length===0?{context:""}:{context:c.toReversed().map(p=>`- ${p.summary}`).join(`
2
- `)}});return{agentEpisodeRecall:K(o),agentEpisodeUpsert:K(s)}},X="threads",V="messages",Y="run_queue",z="approval_grants",J="secret_requests",w=`${_}_${X}`,A=`${_}_${V}`,R=`${_}_${Y}`,$=`${_}_${z}`,O=`${_}_${J}`,P=5,B=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())}),Se=780*60*1e3,Ne=he(_,{tables:{[V]:E({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(),[X]:E({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(B)}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).public(),[Y]:E({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]:E({createdAt:e.number(),threadKey:e.string(),toolName:e.string()}).index("byThreadTool",["threadKey","toolName"],{unique:!0}).public(),[J]:E({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(),...ge,...Ce}}),{mutation:q,query:C}=W.dataModel().create(),Re=async(s,o,d,l)=>{const c=await s.query(A).withIndex("byMessageKey",k=>k.eq("threadKey",o).eq("messageKey",`${d}:approval:${l}`)).first();if(c?.status!=="awaiting_approval")throw new h("CONFLICT",`@lunora/agent: no pending approval for tool call "${l}" to grant for thread "${o}"`);const{expiresAt:p}=c;if(typeof p!="number")throw new h("CONFLICT",`@lunora/agent: the approval for tool call "${l}" on thread "${o}" has no recorded deadline, so it cannot be granted for the thread`);if(Date.now()>=p)throw new h("CONFLICT",`@lunora/agent: the approval for tool call "${l}" on thread "${o}" has timed out`);const g=c.toolName;await s.query($).withIndex("byThreadTool",k=>k.eq("threadKey",o).eq("toolName",g)).first()||await s.insert($,{createdAt:Date.now(),threadKey:o,toolName:g})},$e=async(s,o,d,l)=>(await s.query(A).withIndex("byMessageKey",p=>p.eq("threadKey",o).eq("messageKey",`${d}:approval:${l}`)).first())?.status==="awaiting_approval",xe=async(s,o,d,l)=>{const c=await s.query(A).withIndex("byMessageKey",p=>p.eq("threadKey",o).eq("messageKey",`${d}:approval:${l}`)).first();c?.status==="awaiting_approval"&&await s.delete(c._id)},M=s=>{const{agentSecrets:o}=s;if(o===void 0)throw new h("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},D=(s,o,d)=>{const l=o.userId??void 0;if(s===null||l===void 0||s.owner!==l)throw new h("FORBIDDEN",`@lunora/agent: only the thread's owner can ${d}`);return s},j=async(s,o,d)=>{const{instanceId:l,key:c}=o,p=typeof l=="string"?await s.query(A).withIndex("byMessageKey",g=>g.eq("threadKey",c).eq("messageKey",`${l}:secret:${d}`)).first():void 0;if(p?.status!=="awaiting_secret")throw new h("CONFLICT",`@lunora/agent: no pending secret request for tool call "${d}" on thread "${c}"`);return p},N=async(s,o,d)=>await s.query(O).withIndex("byThreadCall",c=>c.eq("threadKey",o).eq("toolCallId",d)).first()??void 0,H=async(s,o,d,l,c)=>{const g=(await s.query(O).withIndex("byThreadCallId",y=>y.eq("threadKey",o).eq("callId",l)).collect()).filter(y=>y.status==="pending"&&y.instanceId===d&&c<y.expiresAt);if(g.length!==1)throw new h("CONFLICT",`@lunora/agent: no pending secret request for tool call "${l}" on thread "${o}"`);return g[0]},De=(s,o)=>Math.max(Ie,s+be-o),L=async(s,o,d,l)=>{const c=await N(s,o,d);if(c?.status!=="pending"||l>=c.expiresAt)throw new h("CONFLICT",`@lunora/agent: no open secret request for tool call "${d}" on thread "${o}"`);return c},Q=(s,o)=>{const{instanceId:d}=o,{agents:l}=s,c=l?.[o.agent];if(typeof d!="string"||typeof c?.sendEvent!="function")throw new h("INTERNAL",`@lunora/agent: no ctx.agents["${String(o.agent)}"] producer to deliver the secret — run codegen/dev`);return{instanceId:d,sendEvent:c.sendEvent}},Oe=async(s,o,d)=>{if(o.instanceId===void 0)throw new h("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:l}=o,c=await s.query(R).withIndex("byThreadInstance",y=>y.eq("threadKey",o.key).eq("instanceId",l)).first();if(c)return{outcome:"queued",position:c.position};const p=await s.query(R).withIndex("byThread",y=>y.eq("threadKey",o.key)).collect();if(p.length>=P)throw new h("CONFLICT",`@lunora/agent: thread "${o.key}" run queue is full (depth ${String(P)}) — rejecting instance "${l}"`);const g=(p.at(-1)?.position??-1)+1;return await s.insert(R,{agent:o.agent,enqueuedAt:d,instanceId:l,position:g,threadKey:o.key}),{outcome:"queued",position:g}},Me=async(s,o,d)=>{if(o.policy==="queue")return Oe(s,{agent:o.agent,instanceId:o.instanceId,key:o.key,priorInstanceId:o.priorInstanceId},d);if(o.policy!=="replace")throw new h("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:d,...o.instanceId===void 0?{}:{completedInstanceId:null,instanceId:o.instanceId}}),{outcome:"replaced",priorInstanceId:o.priorInstanceId}},Le=(s,o,d)=>{const l=s.instanceId;if(l===void 0||o===l||s.status!=="running"&&s.status!=="awaiting_input")return;const c=typeof s.updatedAt=="number"?s.updatedAt:0,p=s.status==="awaiting_input"?we:Se;return d-c>p?void 0:l},He=()=>{const s=q.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(w).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=Le(i,t.instanceId,a);return r!==void 0?Me(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(w,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...me({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),o=q.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(A).withIndex("byMessageKey",m=>m.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();if(a)return{seq:a.seq};const i=await n.db.query(w).withIndex("byKey",m=>m.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,u=Date.now();return await n.db.insert(A,{content:t.content,createdAt:u,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:u}),{seq:r}}),d=q.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(A).withIndex("byMessageKey",i=>i.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(a._id)}),l=q.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(B)}).mutation(async({args:t,ctx:n})=>{const{instanceId:a,key:i}=t;let r;i!==void 0?r=await n.db.query(w).withIndex("byKey",u=>u.eq("key",i)).first():a!==void 0&&(r=await n.db.query(w).withIndex("byInstance",u=>u.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=C.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",b=>b.eq("key",t.key)).first(),i=a?.summary,r=a?.summaryThroughSeq,u=a?.summaryRebuiltSeq,m=a?.summaryConfig,I=typeof i=="string"&&i.length>0&&typeof r=="number",f=t.configKey===void 0||m===t.configKey,v=typeof u!="number"||typeof r=="number"&&r>=2*u+1,S=I&&f&&!v,T=await n.db.query(A).withIndex("byThread",b=>S?b.eq("threadKey",t.key).gt("seq",r):b.eq("threadKey",t.key)).collect();return S?{messages:T,summary:i}:I?{fallback:{summary:i,throughSeq:r},messages:T}:{messages:T}}),p=q.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(B)}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),i=await n.db.query(w).withIndex("byKey",f=>f.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 f=await n.db.query(R).withIndex("byThreadInstance",v=>v.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return f&&await n.db.delete(f._id),{}}const m=(i.completedInstanceId===t.instanceId?[]:await n.db.query(R).withIndex("byThread",f=>f.eq("threadKey",t.key)).collect())[0];if(!m)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=m.instanceId;return await n.db.delete(m._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}}),g=q.input({key:e.string(),state:e.any()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(w).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},k=C.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",i=>i.eq("key",t.key)).first();return y(a,n.auth)}),Z=C.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",i=>i.eq("key",t.key)).first();return y(a,n.auth)?.state}),ee=C.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",i=>i.eq("key",t.key)).first();return y(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(A).withIndex("byThread",r=>r.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(A).withIndex("byThread",i=>i.eq("threadKey",t.key)).collect()}),te=q.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(w).withIndex("byKey",I=>I.eq("key",t.threadKey)).first(),i=y(a,n.auth);if(i===void 0)throw new h("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(i.instanceId!==t.instanceId)throw new h("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const r=i.agent,{agents:u}=n,m=u?.[r];if(typeof m?.sendEvent!="function")throw new h("INTERNAL",`@lunora/agent: no ctx.agents["${r}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);if(!await $e(n.db,t.threadKey,t.instanceId,t.toolCallId))throw new h("CONFLICT",`@lunora/agent: no pending approval for tool call "${t.toolCallId}" on thread "${t.threadKey}" to decide`);return t.decision==="approve_for_thread"&&(D(a,n.auth,"grant a lasting approval for a tool"),await Re(n.db,t.threadKey,t.instanceId,t.toolCallId)),await xe(n.db,t.threadKey,t.instanceId,t.toolCallId),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.toolCallId}`}),{resolved:!0}}),ne=q.input({secret:e.sensitive(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=D(await n.db.query(w).withIndex("byKey",b=>b.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),i=M(n),u=(await H(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,m=await j(n.db,a,u),I=Q(n,a),f=a.instanceId,v=b=>{if(b.instanceId!==f)throw new h("CONFLICT",`@lunora/agent: tool call "${t.toolCallId}" on thread "${t.threadKey}" was reopened by a newer run while its secret was being stored`)},S=await L(n.db,t.threadKey,u,Date.now());v(S);let T;try{T=await i.put(t.secret,{scope:t.threadKey,ttlMs:De(S.expiresAt,Date.now())})}catch(b){throw b instanceof pe?new h("PAYLOAD_TOO_LARGE",b.message):b}try{const b=await L(n.db,t.threadKey,u,Date.now());v(b),await n.db.patch(b._id,{ref:T,status:"supplied",updatedAt:Date.now()}),await n.db.delete(m._id)}catch(b){throw await i.discard(T).catch(()=>{}),b}try{await I.sendEvent(I.instanceId,{payload:{},type:`agent-secret:${u}`})}catch{}return{resolved:!0}}),ae=q.input({threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=D(await n.db.query(w).withIndex("byKey",f=>f.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),r=(await H(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,u=await j(n.db,a,r),m=Q(n,a),I=await L(n.db,t.threadKey,r,Date.now());await n.db.patch(I._id,{status:"declined",updatedAt:Date.now()}),await n.db.delete(u._id);try{await m.sendEvent(m.instanceId,{payload:{},type:`agent-secret:${r}`})}catch{}return{resolved:!0}}),ie=K(q.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 N(n.db,t.threadKey,t.toolCallId),i=Date.now();if(a===void 0){await n.db.insert(O,{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})}})),oe=K(q.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await N(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"}})),re=K(q.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 N(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 M(n).take(a.ref,{claimant:t.claimant,scope:t.threadKey})})),se=K(q.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await N(n.db,t.threadKey,t.toolCallId);a?.instanceId===t.instanceId&&(typeof a.ref=="string"&&await M(n).discard(a.ref),a.status==="supplied"&&await n.db.patch(a._id,{status:"consumed",updatedAt:Date.now()}))})),de=C.input({threadKey:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",u=>u.eq("key",t.threadKey)).first();D(a,n.auth,"list its secret requests");const i=await n.db.query(O).withIndex("byThreadCall",u=>u.eq("threadKey",t.threadKey)).collect(),r=Date.now();return i.map(u=>({createdAt:u.createdAt,expiresAt:u.expiresAt,...typeof u.label=="string"?{label:u.label}:{},status:u.status==="pending"&&r>=u.expiresAt?"expired":u.status,toolCallId:u.callId??u.toolCallId,toolName:u.toolName}))}),le=K(C.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)),ue=C.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(w).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}))}),ce=q.input({threadKey:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(w).withIndex("byKey",r=>r.eq("key",t.threadKey)).first();if(y(a,n.auth)===void 0)throw new h("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}}),ye=q.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 h("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 h("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,u=await n.db.query(w).withIndex("byKey",I=>I.eq("key",t.threadKey)).first();if(u){const I=u.status,f=u.instanceId,v=u.owner;if((I==="running"||I==="awaiting_input")&&f!==void 0&&(v===void 0||v===r))return{id:f,threadKey:t.threadKey};if(v!==r)throw new h("FORBIDDEN",`@lunora/agent: thread "${t.threadKey}" belongs to another owner`)}const{id:m}=await i.run({input:t.input,threadKey:t.threadKey,...r===void 0?{}:{owner:r},...t.title===void 0?{}:{title:t.title}});return{id:m,threadKey:t.threadKey}}),F=fe(),U=ke();return{extension:Ne,functions:{agentApprovalGranted:le,agentApprovalGrants:ue,agentAppendMessage:K(o),agentCompleteRun:K(p),agentEnsureThread:K(s),agentEpisodeRecall:U.agentEpisodeRecall,agentEpisodeUpsert:U.agentEpisodeUpsert,agentGraphTraverse:F.agentGraphTraverse,agentGraphUpsert:F.agentGraphUpsert,agentHistory:K(c),agentMessages:ee,agentDeleteMessage:K(d),agentPatchThread:K(l),agentResolveApproval:te,agentRevokeApprovalGrant:ce,agentRun:ye,agentSetState:K(g),agentState:Z,agentSupplySecret:ne,agentTakeSecret:re,agentThread:k,agentDeclineSecret:ae,agentDiscardSecret:se,agentOpenSecretRequest:ie,agentSecretRequests:de,agentSettleSecretRequest:oe}}};export{He as agentComponent,Ne as agentExtension,Xe as normalizeEntityName,Ye as sandboxComponent};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/agent",
3
- "version": "1.0.0-alpha.235",
3
+ "version": "1.0.0-alpha.237",
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.142",
88
+ "@lunora/ai": "1.0.0-alpha.143",
89
89
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
90
- "@lunora/mail": "1.0.0-alpha.119",
90
+ "@lunora/mail": "1.0.0-alpha.120",
91
91
  "@lunora/platform": "1.0.0-alpha.73",
92
- "@lunora/server": "1.0.0-alpha.227",
93
- "@lunora/values": "1.0.0-alpha.77",
94
- "@lunora/workflow": "1.0.0-alpha.91",
92
+ "@lunora/server": "1.0.0-alpha.228",
93
+ "@lunora/values": "1.0.0-alpha.78",
94
+ "@lunora/workflow": "1.0.0-alpha.92",
95
95
  "@modelcontextprotocol/sdk": "^1.32.0",
96
96
  "ai": "7.0.127",
97
97
  "yaml": "^2.9.1"