@lunora/agent 1.0.0-alpha.285 → 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/channels.d.mts +2 -2
- package/dist/channels.d.ts +2 -2
- package/dist/component.mjs +2 -2
- package/dist/core.d.mts +2 -2
- package/dist/core.d.ts +2 -2
- package/dist/core.mjs +1 -1
- package/dist/inbound.d.mts +1 -1
- package/dist/inbound.d.ts +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/runAgentLoop.mjs +2 -2
- package/dist/packem_shared/{SecretUnavailableError-BsJMGfML.mjs → SecretUnavailableError-CL7caQjN.mjs} +1 -1
- package/dist/packem_shared/agentAsTool-Bwq7pYHQ.mjs +1 -0
- package/dist/packem_shared/code-tool-DgKolSi1.mjs +1 -0
- package/dist/packem_shared/codeTool-sxRmNlUR.mjs +1 -0
- package/dist/packem_shared/{defineAgent-6Ih7L9E9.mjs → defineAgent-Cqr8-Kf1.mjs} +1 -1
- package/dist/packem_shared/normalizeEntityName-CknxOaNc.mjs +2 -0
- package/dist/packem_shared/{types.d-Bzy_Qah6.d.mts → types.d-BdKHdKQu.d.mts} +8 -1
- package/dist/packem_shared/{types.d-Bzy_Qah6.d.ts → types.d-BdKHdKQu.d.ts} +8 -1
- package/dist/reply.d.mts +1 -1
- package/dist/reply.d.ts +1 -1
- package/dist/sandbox.d.mts +1 -1
- package/dist/sandbox.d.ts +1 -1
- package/dist/sandbox.mjs +1 -1
- package/dist/skill-markdown.d.mts +1 -1
- package/dist/skill-markdown.d.ts +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/agentAsTool-BF-7Dnzy.mjs +0 -1
- package/dist/packem_shared/codeTool-Cn8TuNjk.mjs +0 -1
- package/dist/packem_shared/normalizeEntityName-BiUH5B5W.mjs +0 -2
- package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +0 -1
package/dist/channels.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-BdKHdKQu.mjs";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-BdKHdKQu.mjs";
|
|
3
3
|
import '@lunora/mail/inbound';
|
|
4
4
|
import 'ai';
|
|
5
5
|
/**
|
package/dist/channels.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition } from "./packem_shared/types.d-
|
|
2
|
-
export type { I as InboundChannelEvent } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition } from "./packem_shared/types.d-BdKHdKQu.js";
|
|
2
|
+
export type { I as InboundChannelEvent } from "./packem_shared/types.d-BdKHdKQu.js";
|
|
3
3
|
import '@lunora/mail/inbound';
|
|
4
4
|
import 'ai';
|
|
5
5
|
/**
|
package/dist/component.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{LunoraError as
|
|
2
|
-
`)}});return{agentEpisodeRecall:T(i),agentEpisodeUpsert:T(d)}},z="threads",J="messages",Z="run_queue",ee="approval_grants",te="secret_requests",p=`${x}_${z}`,v=`${x}_${J}`,S=`${x}_${Z}`,R=`${x}_${ee}`,_=`${x}_${te}`,Re=50,xe=200,$e=500,V=5,U=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(x,{tables:{[J]:N({approvalScope:e.optional(e.literal("thread")),content:e.string(),createdAt:e.number(),expiresAt:e.optional(e.number()),messageKey:e.string(),role:e.union(e.literal("user"),e.literal("assistant"),e.literal("tool"),e.literal("system")),seq:e.number(),status:e.optional(e.union(e.literal("awaiting_approval"),e.literal("awaiting_secret"),e.literal("approved"),e.literal("rejected"))),approvalAgent: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]:N({agent:e.string(),createdAt:e.number(),error:e.optional(e.string().nullable()),completedInstanceId:e.optional(e.string().nullable()),instanceId:e.optional(e.string()),key:e.string(),messageCount:e.number(),owner:e.optional(e.string()),state:e.optional(e.any()),status:e.union(e.literal("idle"),e.literal("running"),e.literal("error"),e.literal("cancelled"),e.literal("awaiting_input")),summary:e.optional(e.string()),summaryConfig:e.optional(e.string()),summaryRebuiltSeq:e.optional(e.number()),summaryThroughSeq:e.optional(e.number()),title:e.optional(e.string()),updatedAt:e.number(),usage:e.optional(U)}).index("byKey",["key"],{unique:!0}).index("byAgent",["agent"]).index("byInstance",["instanceId"]).index("byOwnerStatus",["owner","status","updatedAt"]).public(),[Z]:N({agent:e.string(),enqueuedAt:e.number(),instanceId:e.string(),position:e.number(),threadKey:e.string()}).index("byThread",["threadKey","position"]).index("byThreadInstance",["threadKey","instanceId"],{unique:!0}).public(),[ee]:N({agent:e.string(),createdAt:e.number(),threadKey:e.string(),toolName:e.string()}).index("byThreadAgentTool",["threadKey","agent","toolName"],{unique:!0}).public(),[te]:N({consumerTool:e.string(),createdAt:e.number(),expiresAt:e.number(),instanceId:e.string(),ref:e.optional(e.string().nullable()),label:e.optional(e.string().nullable()),status:e.union(e.literal("pending"),e.literal("supplied"),e.literal("declined"),e.literal("expired"),e.literal("consumed")),threadKey:e.string(),toolCallId:e.string(),callId:e.optional(e.string()),toolName:e.string(),updatedAt:e.number()}).index("byThreadCall",["threadKey","toolCallId"],{unique:!0}).index("byThreadCallId",["threadKey","callId"]).public(),...qe,..._e}}),{mutation:A,query:k}=Y.dataModel().create(),Oe=async(d,i,l,c,u)=>{const m=await d.query(v).withIndex("byMessageKey",$=>$.eq("threadKey",i).eq("messageKey",`${c}:approval:${u}`)).first();if(m?.status!=="awaiting_approval")throw new b("CONFLICT",`@lunora/agent: no pending approval for tool call "${u}" to grant for thread "${i}"`);const{expiresAt:q}=m;if(typeof q!="number")throw new b("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${i}" has no recorded deadline, so it cannot be granted for the thread`);if(Date.now()>=q)throw new b("CONFLICT",`@lunora/agent: the approval for tool call "${u}" on thread "${i}" has timed out`);const y=m.toolName;await d.query(R).withIndex("byThreadAgentTool",$=>$.eq("threadKey",i).eq("agent",l).eq("toolName",y)).first()||await d.insert(R,{agent:l,createdAt:Date.now(),threadKey:i,toolName:y})},Le=async(d,i,l,c)=>{const u=await d.query(v).withIndex("byMessageKey",q=>q.eq("threadKey",i).eq("messageKey",`${l}:approval:${c}`)).first();if(u?.status!=="awaiting_approval")return;const m=u.approvalAgent;return typeof m=="string"?m:void 0},Be=async(d,i,l,c)=>{const u=await d.query(v).withIndex("byMessageKey",m=>m.eq("threadKey",i).eq("messageKey",`${l}:approval:${c}`)).first();u?.status==="awaiting_approval"&&await d.delete(v,u._id)},L=d=>{const{agentSecrets:i}=d;if(i===void 0)throw new b("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 i},O=(d,i,l)=>{const c=i.userId??void 0;if(d===null||c===void 0||d.owner!==c)throw new b("FORBIDDEN",`@lunora/agent: only the thread's owner can ${l}`);return d},X=async(d,i,l)=>{const{instanceId:c,key:u}=i,m=typeof c=="string"?await d.query(v).withIndex("byMessageKey",q=>q.eq("threadKey",u).eq("messageKey",`${c}:secret:${l}`)).first():void 0;if(m?.status!=="awaiting_secret")throw new b("CONFLICT",`@lunora/agent: no pending secret request for tool call "${l}" on thread "${u}"`);return m},M=async(d,i,l)=>await d.query(_).withIndex("byThreadCall",u=>u.eq("threadKey",i).eq("toolCallId",l)).first()??void 0,Q=async(d,i,l,c,u)=>{const q=(await d.query(_).withIndex("byThreadCallId",y=>y.eq("threadKey",i).eq("callId",c)).collect()).filter(y=>y.status==="pending"&&y.instanceId===l&&u<y.expiresAt);if(q.length!==1)throw new b("CONFLICT",`@lunora/agent: no pending secret request for tool call "${c}" on thread "${i}"`);return q[0]},Ue=(d,i)=>Math.max(be,d+fe-i),B=async(d,i,l,c)=>{const u=await M(d,i,l);if(u?.status!=="pending"||c>=u.expiresAt)throw new b("CONFLICT",`@lunora/agent: no open secret request for tool call "${l}" on thread "${i}"`);return u},W=(d,i)=>{const{instanceId:l}=i,{agents:c}=d,u=c?.[i.agent];if(typeof l!="string"||typeof u?.sendEvent!="function")throw new b("INTERNAL",`@lunora/agent: no ctx.agents["${String(i.agent)}"] producer to deliver the secret — run codegen/dev`);return{instanceId:l,sendEvent:u.sendEvent}},Pe=async(d,i,l)=>{if(i.instanceId===void 0)throw new b("CONFLICT",`@lunora/agent: thread "${i.key}" already has a run in flight (instance "${i.priorInstanceId}") — cannot queue a dispatch with no instance id`);const{instanceId:c}=i,u=await d.query(S).withIndex("byThreadInstance",y=>y.eq("threadKey",i.key).eq("instanceId",c)).first();if(u)return{outcome:"queued",position:u.position};const m=await d.query(S).withIndex("byThread",y=>y.eq("threadKey",i.key)).collect();if(m.length>=V)throw new b("CONFLICT",`@lunora/agent: thread "${i.key}" run queue is full (depth ${String(V)}) — rejecting instance "${c}"`);const q=(m.at(-1)?.position??-1)+1;return await d.insert(S,{agent:i.agent,enqueuedAt:l,instanceId:c,position:q,threadKey:i.key}),{outcome:"queued",position:q}},Fe=async(d,i,l)=>{if(i.policy==="queue")return Pe(d,{agent:i.agent,instanceId:i.instanceId,key:i.key,priorInstanceId:i.priorInstanceId},l);if(i.policy!=="replace")throw new b("CONFLICT",`@lunora/agent: thread "${i.key}" already has a run in flight (instance "${i.priorInstanceId}") — onConcurrentRun="${i.policy}"`);return await d.patch(p,i.existingId,{error:null,status:"running",updatedAt:l,...i.instanceId===void 0?{}:{completedInstanceId:null,instanceId:i.instanceId}}),{outcome:"replaced",priorInstanceId:i.priorInstanceId}},Ge=(d,i,l)=>{const c=d.instanceId;if(c===void 0||i===c||d.status!=="running"&&d.status!=="awaiting_input")return;const u=typeof d.updatedAt=="number"?d.updatedAt:0,m=d.status==="awaiting_input"?ge:De;return l-u>m?void 0:c},ze=()=>{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(p).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=Ge(o,t.instanceId,a);return s!==void 0?Fe(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(p,o._id,{error:null,status:"running",updatedAt:a,...t.instanceId===void 0?{}:{completedInstanceId:null,instanceId:t.instanceId}}),{outcome:"continued"})}return await n.db.insert(p,{agent:t.agent,createdAt:a,key:t.key,messageCount:0,status:"running",updatedAt:a,...j({instanceId:t.instanceId,owner:t.owner,state:t.initialState,title:t.title})}),{outcome:"created"}}),i=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()),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(v).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(p).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,r=Date.now();return await n.db.insert(v,{content:t.content,createdAt:r,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.expiresAt===void 0?{}:{expiresAt:t.expiresAt},...t.status===void 0?{}:{status:t.status},...t.stepName===void 0?{}:{stepName:t.stepName},...t.toolCallId===void 0?{}:{toolCallId:t.toolCallId},...t.toolCalls===void 0?{}:{toolCalls:t.toolCalls},...t.toolName===void 0?{}:{toolName:t.toolName}}),await n.db.patch(p,o._id,{messageCount:s+1,updatedAt:r}),{seq:s}}),l=A.input({messageKey:e.string(),threadKey:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(v).withIndex("byMessageKey",o=>o.eq("threadKey",t.threadKey).eq("messageKey",t.messageKey)).first();a&&await n.db.delete(v,a._id)}),c=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(U)}).mutation(async({args:t,ctx:n})=>{const{instanceId:a,key:o}=t;let s;o!==void 0?s=await n.db.query(p).withIndex("byKey",r=>r.eq("key",o)).first():a!==void 0&&(s=await n.db.query(p).withIndex("byInstance",r=>r.eq("instanceId",a)).first()),!(!s||t.ifInstanceId!==void 0&&s.instanceId!==t.ifInstanceId)&&await n.db.patch(p,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}})}),u=k.input({configKey:e.optional(e.string()),key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",f=>f.eq("key",t.key)).first(),o=a?.summary,s=a?.summaryThroughSeq,r=a?.summaryRebuiltSeq,h=a?.summaryConfig,I=typeof o=="string"&&o.length>0&&typeof s=="number",g=t.configKey===void 0||h===t.configKey,w=typeof r!="number"||typeof s=="number"&&s>=2*r+1,C=I&&g&&!w,K=await n.db.query(v).withIndex("byThread",f=>C?f.eq("threadKey",t.key).gt("seq",s):f.eq("threadKey",t.key)).collect();return C?{messages:K,summary:o}:I?{fallback:{summary:o,throughSeq:s},messages:K}:{messages:K}}),m=A.input({error:e.optional(e.string()),instanceId:e.string(),key:e.string(),status:e.union(e.literal("idle"),e.literal("error"),e.literal("cancelled")),usage:e.optional(U)}).mutation(async({args:t,ctx:n})=>{const a=Date.now(),o=await n.db.query(p).withIndex("byKey",g=>g.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 g=await n.db.query(S).withIndex("byThreadInstance",w=>w.eq("threadKey",t.key).eq("instanceId",t.instanceId)).first();return g&&await n.db.delete(S,g._id),{}}const h=(o.completedInstanceId===t.instanceId?[]:await n.db.query(S).withIndex("byThread",g=>g.eq("threadKey",t.key)).collect())[0];if(!h)return await n.db.patch(p,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 I=h.instanceId;return await n.db.delete(S,h._id),await n.db.patch(p,o._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(p).withIndex("byKey",o=>o.eq("key",t.key)).first();a&&await n.db.patch(p,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},P=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",o=>o.eq("key",t.key)).first();return y(a,n.auth)}),$=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",o=>o.eq("key",t.key)).first();return y(a,n.auth)?.state}),ne=k.input({key:e.string(),limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",o=>o.eq("key",t.key)).first();return y(a,n.auth)===void 0?[]:t.limit!==void 0?(await n.db.query(v).withIndex("byThread",s=>s.eq("threadKey",t.key)).order("desc").take(t.limit)).toReversed():n.db.query(v).withIndex("byThread",o=>o.eq("threadKey",t.key)).collect()}),ae=k.input({limit:e.optional(e.number())}).query(async({args:t,ctx:n})=>{const{userId:a}=n.auth;if(!a)return[];const o=await n.db.query(p).withIndex("byOwnerStatus",w=>w.eq("owner",a).eq("status","awaiting_input")).order("desc").take($e),s=Date.now(),r=Math.min(xe,Math.max(1,Math.trunc(t.limit??Re))),h=async w=>{const C=w.instanceId;if(C===void 0)return[];const K=`${C}:approval:`,f=`${C}:approval;`;return(await n.db.query(v).withIndex("byMessageKey",E=>E.eq("threadKey",w.key).gte("messageKey",K).lt("messageKey",f)).collect()).filter(E=>E.status==="awaiting_approval"&&typeof E.expiresAt=="number"&&s<E.expiresAt).map(E=>j({agent:w.agent,content:E.content,instanceId:C,requestedAt:E.createdAt,threadKey:w.key,threadTitle:w.title,threadUpdatedAt:w.updatedAt,toolCallId:E.toolCallId,toolName:E.toolName}))},I=[];let g=0;for(let w=0;w<o.length&&g<r;w+=r){const C=await Promise.all(o.slice(w,w+r).map(K=>h(K)));for(const K of C)K.length>0&&g<r&&(I.push(...K),g+=1)}return I}),oe=A.input({decision:e.union(e.literal("approve"),e.literal("approve_for_thread"),e.literal("reject")),instanceId:e.string(),note:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",I=>I.eq("key",t.threadKey)).first(),o=y(a,n.auth);if(o===void 0)throw new b("FORBIDDEN",`@lunora/agent: not allowed to resolve approvals on thread "${t.threadKey}"`);if(o.instanceId!==t.instanceId)throw new b("FORBIDDEN",`@lunora/agent: instance "${t.instanceId}" does not own thread "${t.threadKey}"`);const s=await Le(n.db,t.threadKey,t.instanceId,t.toolCallId);if(s===void 0)throw new b("CONFLICT",`@lunora/agent: no pending approval for tool call "${t.toolCallId}" on thread "${t.threadKey}" to decide`);const{agents:r}=n,h=r?.[s];if(typeof h?.sendEvent!="function")throw new b("INTERNAL",`@lunora/agent: no ctx.agents["${s}"] producer to resolve the approval — run codegen/dev so the agent binding is wired`);return t.decision==="approve_for_thread"&&(O(a,n.auth,"grant a lasting approval for a tool"),await Oe(n.db,t.threadKey,s,t.instanceId,t.toolCallId)),await Be(n.db,t.threadKey,t.instanceId,t.toolCallId),await h.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}}),ie=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(p).withIndex("byKey",f=>f.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),o=L(n),r=(await Q(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,h=await X(n.db,a,r),I=W(n,a),g=a.instanceId,w=f=>{if(f.instanceId!==g)throw new b("CONFLICT",`@lunora/agent: tool call "${t.toolCallId}" on thread "${t.threadKey}" was reopened by a newer run while its secret was being stored`)},C=await B(n.db,t.threadKey,r,Date.now());w(C);let K;try{K=await o.put(t.secret,{scope:t.threadKey,ttlMs:Ue(C.expiresAt,Date.now())})}catch(f){throw f instanceof we?new b("PAYLOAD_TOO_LARGE",f.message):f}try{const f=await B(n.db,t.threadKey,r,Date.now());w(f),await n.db.patch(_,f._id,{ref:K,status:"supplied",updatedAt:Date.now()}),await n.db.delete(v,h._id)}catch(f){throw await o.discard(K).catch(()=>{}),f}try{await I.sendEvent(I.instanceId,{payload:{},type:`agent-secret:${r}`})}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(p).withIndex("byKey",g=>g.eq("key",t.threadKey)).first(),n.auth,"supply or decline a secret on it"),s=(await Q(n.db,t.threadKey,a.instanceId,t.toolCallId,Date.now())).toolCallId,r=await X(n.db,a,s),h=W(n,a),I=await B(n.db,t.threadKey,s,Date.now());await n.db.patch(_,I._id,{status:"declined",updatedAt:Date.now()}),await n.db.delete(v,r._id);try{await h.sendEvent(h.instanceId,{payload:{},type:`agent-secret:${s}`})}catch{}return{resolved:!0}}),se=T(A.input({consumerTool:e.string(),expiresAt:e.number(),instanceId:e.string(),callId:e.optional(e.string()),label:e.optional(e.string()),threadKey:e.string(),toolCallId:e.string(),toolName:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await M(n.db,t.threadKey,t.toolCallId),o=Date.now();if(a===void 0){await n.db.insert(_,{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,{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=T(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=T(A.input({claimant:e.string(),consumerCallId:e.string(),instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await 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 L(n).take(a.ref,{claimant:t.claimant,scope:t.threadKey})})),ue=T(A.input({instanceId:e.string(),threadKey:e.string(),toolCallId:e.string()}).mutation(async({args:t,ctx:n})=>{const a=await M(n.db,t.threadKey,t.toolCallId);a?.instanceId===t.instanceId&&(typeof a.ref=="string"&&await L(n).discard(a.ref),a.status==="supplied"&&await n.db.patch(_,a._id,{status:"consumed",updatedAt:Date.now()}))})),ce=k.input({threadKey:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.threadKey)).first();O(a,n.auth,"list its secret requests");const o=await n.db.query(_).withIndex("byThreadCall",r=>r.eq("threadKey",t.threadKey)).collect(),s=Date.now();return o.map(r=>({createdAt:r.createdAt,expiresAt:r.expiresAt,...typeof r.label=="string"?{label:r.label}:{},status:r.status==="pending"&&s>=r.expiresAt?"expired":r.status,toolCallId:r.callId??r.toolCallId,toolName:r.toolName}))}),pe=T(k.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=k.input({key:e.string()}).query(async({args:t,ctx:n})=>{const a=await n.db.query(p).withIndex("byKey",r=>r.eq("key",t.key)).first();if(y(a,n.auth)===void 0)return[];const o=await n.db.query(R).withIndex("byThreadAgentTool",r=>r.eq("threadKey",t.key)).collect(),s=new Map;for(const r of o){if(r.agent===void 0)continue;const h=r.toolName,I=r.createdAt,g=s.get(h);(g===void 0||I<g.createdAt)&&s.set(h,{createdAt:I,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(p).withIndex("byKey",r=>r.eq("key",t.threadKey)).first();if(y(a,n.auth)===void 0)throw new b("FORBIDDEN",`@lunora/agent: not allowed to revoke approvals on thread "${t.threadKey}"`);const s=(await n.db.query(R).withIndex("byThreadAgentTool",r=>r.eq("threadKey",t.threadKey)).collect()).filter(r=>r.toolName===t.toolName);for(const r of s)await n.db.delete(R,r._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 b("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 b("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,r=await n.db.query(p).withIndex("byKey",I=>I.eq("key",t.threadKey)).first();if(r){const I=r.status,g=r.instanceId,w=r.owner;if((I==="running"||I==="awaiting_input")&&g!==void 0&&(w===void 0||w===s))return{id:g,threadKey:t.threadKey};if(w!==s)throw new b("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:T(i),agentCompleteRun:T(m),agentEnsureThread:T(d),agentEpisodeRecall:G.agentEpisodeRecall,agentEpisodeUpsert:G.agentEpisodeUpsert,agentGraphTraverse:F.agentGraphTraverse,agentGraphUpsert:F.agentGraphUpsert,agentHistory:T(u),agentMessages:ne,agentDeleteMessage:T(l),agentPatchThread:T(c),agentPendingApprovals:ae,agentResolveApproval:oe,agentRevokeApprovalGrant:he,agentRun:me,agentSetState:T(q),agentState:$,agentSupplySecret:ie,agentTakeSecret:le,agentThread:P,agentDeclineSecret:re,agentDiscardSecret:ue,agentOpenSecretRequest:se,agentSecretRequests:ce,agentSettleSecretRequest:de}}};export{ze as agentComponent,Me as agentExtension,et as normalizeEntityName,nt 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};
|
package/dist/core.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { x as AgentBindingSpec, l as AgentRunFunction, F as AgentHandle, q as AgentConfig, A as AgentDefinition, a0 as AgentToolConfig, c as AgentToolDefinition, v as AgentFunctionReference, a6 as SkillConfig, b as SkillDefinition, k as AgentFunctionPaths, j as AgentRunInput, o as AgentRunResult } from "./packem_shared/types.d-
|
|
2
|
-
export type { w as AgentApprovalContext, s as AgentAsToolOptions, z as AgentEmailMapper, B as AgentEmailRun, h as AgentGenerate, D as AgentGenerateOptions, E as AgentGenerateResult, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, p as AgentMessageRow, M as AgentMessageStatus, u as AgentModelInput, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, m as AgentStepLike, n as AgentStreamGenerate, t as AgentSubToolInput, Z as AgentThreadStatus, _ as AgentTokenDelta, i as AgentTokenSink, $ as AgentToolCall, d as AgentToolContext, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, r as AnyAgentTool, a5 as EnsureThreadOutcome } from "./packem_shared/types.d-
|
|
1
|
+
import { x as AgentBindingSpec, l as AgentRunFunction, F as AgentHandle, q as AgentConfig, A as AgentDefinition, a0 as AgentToolConfig, c as AgentToolDefinition, v as AgentFunctionReference, a6 as SkillConfig, b as SkillDefinition, k as AgentFunctionPaths, j as AgentRunInput, o as AgentRunResult } from "./packem_shared/types.d-BdKHdKQu.mjs";
|
|
2
|
+
export type { w as AgentApprovalContext, s as AgentAsToolOptions, z as AgentEmailMapper, B as AgentEmailRun, h as AgentGenerate, D as AgentGenerateOptions, E as AgentGenerateResult, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, p as AgentMessageRow, M as AgentMessageStatus, u as AgentModelInput, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, m as AgentStepLike, n as AgentStreamGenerate, t as AgentSubToolInput, Z as AgentThreadStatus, _ as AgentTokenDelta, i as AgentTokenSink, $ as AgentToolCall, d as AgentToolContext, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, r as AnyAgentTool, a5 as EnsureThreadOutcome } from "./packem_shared/types.d-BdKHdKQu.mjs";
|
|
3
3
|
import { FlexibleSchema } from 'ai';
|
|
4
4
|
import { jsonSchema as jsonSchema$1, ValidationResult, Schema } from '@ai-sdk/provider-utils';
|
|
5
5
|
import { WorkflowDefinition } from '@lunora/workflow';
|
package/dist/core.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { x as AgentBindingSpec, l as AgentRunFunction, F as AgentHandle, q as AgentConfig, A as AgentDefinition, a0 as AgentToolConfig, c as AgentToolDefinition, v as AgentFunctionReference, a6 as SkillConfig, b as SkillDefinition, k as AgentFunctionPaths, j as AgentRunInput, o as AgentRunResult } from "./packem_shared/types.d-
|
|
2
|
-
export type { w as AgentApprovalContext, s as AgentAsToolOptions, z as AgentEmailMapper, B as AgentEmailRun, h as AgentGenerate, D as AgentGenerateOptions, E as AgentGenerateResult, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, p as AgentMessageRow, M as AgentMessageStatus, u as AgentModelInput, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, m as AgentStepLike, n as AgentStreamGenerate, t as AgentSubToolInput, Z as AgentThreadStatus, _ as AgentTokenDelta, i as AgentTokenSink, $ as AgentToolCall, d as AgentToolContext, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, r as AnyAgentTool, a5 as EnsureThreadOutcome } from "./packem_shared/types.d-
|
|
1
|
+
import { x as AgentBindingSpec, l as AgentRunFunction, F as AgentHandle, q as AgentConfig, A as AgentDefinition, a0 as AgentToolConfig, c as AgentToolDefinition, v as AgentFunctionReference, a6 as SkillConfig, b as SkillDefinition, k as AgentFunctionPaths, j as AgentRunInput, o as AgentRunResult } from "./packem_shared/types.d-BdKHdKQu.js";
|
|
2
|
+
export type { w as AgentApprovalContext, s as AgentAsToolOptions, z as AgentEmailMapper, B as AgentEmailRun, h as AgentGenerate, D as AgentGenerateOptions, E as AgentGenerateResult, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, p as AgentMessageRow, M as AgentMessageStatus, u as AgentModelInput, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, m as AgentStepLike, n as AgentStreamGenerate, t as AgentSubToolInput, Z as AgentThreadStatus, _ as AgentTokenDelta, i as AgentTokenSink, $ as AgentToolCall, d as AgentToolContext, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, r as AnyAgentTool, a5 as EnsureThreadOutcome } from "./packem_shared/types.d-BdKHdKQu.js";
|
|
3
3
|
import { FlexibleSchema } from 'ai';
|
|
4
4
|
import { jsonSchema as jsonSchema$1, ValidationResult, Schema } from '@ai-sdk/provider-utils';
|
|
5
5
|
import { WorkflowDefinition } from '@lunora/workflow';
|
package/dist/core.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as t}from"./packem_shared/createAgentContext-TMvmjncE.mjs";import{defineAgent as n,defineAgentTool as r,isAgentDefinition as i}from"./packem_shared/defineAgent-
|
|
1
|
+
import{default as t}from"./packem_shared/createAgentContext-TMvmjncE.mjs";import{defineAgent as n,defineAgentTool as r,isAgentDefinition as i}from"./packem_shared/defineAgent-Cqr8-Kf1.mjs";import{functionTool as a}from"./packem_shared/functionTool-Cf433Hdo.mjs";import{default as m}from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{default as x}from"./packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs";import{defineSkill as g,isSkillDefinition as u}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as c}from"./packem_shared/compileAgentWorkflow-yZB8fbYc.mjs";export{c as compileAgentWorkflow,t as createAgentContext,n as defineAgent,r as defineAgentTool,g as defineSkill,a as functionTool,i as isAgentDefinition,u as isSkillDefinition,m as jsonSchema,x as withAgentScheduleShard};
|
package/dist/inbound.d.mts
CHANGED
package/dist/inbound.d.ts
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-
|
|
2
|
-
export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentChannelShardInput, z as AgentEmailMapper, B as AgentEmailRun, C as AgentEmailShardInput, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentHandle, G as AgentInboundShardResolver, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, M as AgentMessageStatus, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, Z as AgentThreadStatus, _ as AgentTokenDelta, $ as AgentToolCall, a0 as AgentToolConfig, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, a5 as EnsureThreadOutcome, a6 as SkillConfig } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-BdKHdKQu.mjs";
|
|
2
|
+
export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentChannelShardInput, z as AgentEmailMapper, B as AgentEmailRun, C as AgentEmailShardInput, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentHandle, G as AgentInboundShardResolver, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, M as AgentMessageStatus, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, Z as AgentThreadStatus, _ as AgentTokenDelta, $ as AgentToolCall, a0 as AgentToolConfig, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, a5 as EnsureThreadOutcome, a6 as SkillConfig } from "./packem_shared/types.d-BdKHdKQu.mjs";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.mjs";
|
|
4
4
|
export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard } from "./core.mjs";
|
|
5
5
|
import { LanguageModel, ModelMessage } from 'ai';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-
|
|
2
|
-
export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentChannelShardInput, z as AgentEmailMapper, B as AgentEmailRun, C as AgentEmailShardInput, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentHandle, G as AgentInboundShardResolver, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, M as AgentMessageStatus, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, Z as AgentThreadStatus, _ as AgentTokenDelta, $ as AgentToolCall, a0 as AgentToolConfig, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, a5 as EnsureThreadOutcome, a6 as SkillConfig } from "./packem_shared/types.d-
|
|
1
|
+
import { A as AgentDefinition, e as AgentCompact, f as AgentEpisodeExtract, g as AgentGraphExtract, h as AgentGenerate, i as AgentTokenSink, j as AgentRunInput, k as AgentFunctionPaths, l as AgentRunFunction, m as AgentStepLike, n as AgentStreamGenerate, o as AgentRunResult, p as AgentMessageRow, q as AgentConfig, b as SkillDefinition, r as AnyAgentTool, s as AgentAsToolOptions, t as AgentSubToolInput, c as AgentToolDefinition, u as AgentModelInput, v as AgentFunctionReference, d as AgentToolContext } from "./packem_shared/types.d-BdKHdKQu.js";
|
|
2
|
+
export type { w as AgentApprovalContext, x as AgentBindingSpec, y as AgentChannelShardInput, z as AgentEmailMapper, B as AgentEmailRun, C as AgentEmailShardInput, D as AgentGenerateOptions, E as AgentGenerateResult, F as AgentHandle, G as AgentInboundShardResolver, H as AgentInstructionsContext, J as AgentLiveEvent, K as AgentMemoryOptions, L as AgentMemorySource, M as AgentMessageStatus, N as AgentOnReply, O as AgentOnStepFinish, P as AgentPrepareStep, Q as AgentPrepareStepInput, R as AgentPrepareStepResult, T as AgentProgressEvent, U as AgentReplyInfo, a as AgentReplyRef, V as AgentRunHandle, W as AgentRunOptions, X as AgentStepFinishInfo, Y as AgentStepInfo, Z as AgentThreadStatus, _ as AgentTokenDelta, $ as AgentToolCall, a0 as AgentToolConfig, a1 as AgentUsage, a2 as AgentVoiceConfig, a3 as AgentWorkflowBindingLike, a4 as AgentWorkflowInstanceLike, a5 as EnsureThreadOutcome, a6 as SkillConfig } from "./packem_shared/types.d-BdKHdKQu.js";
|
|
3
3
|
export { type AgentComponent, agentComponent, agentExtension } from "./component.js";
|
|
4
4
|
export { type FunctionToolOptions, compileAgentWorkflow, createAgentContext, defineAgent, defineAgentTool, defineSkill, functionTool, isAgentDefinition, isSkillDefinition, jsonSchema, withAgentScheduleShard } from "./core.js";
|
|
5
5
|
import { LanguageModel, ModelMessage } from 'ai';
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runAgentLoop as r,splitForCompaction as t}from"./packem_chunks/runAgentLoop.mjs";import{collectAgenticMemoryTools as n,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as
|
|
1
|
+
import{runAgentLoop as r,splitForCompaction as t}from"./packem_chunks/runAgentLoop.mjs";import{collectAgenticMemoryTools as n,toSearchResults as f}from"./packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as s}from"./packem_shared/agentAsTool-Bwq7pYHQ.mjs";import{c as p}from"./packem_shared/code-tool-DgKolSi1.mjs";import{agentComponent as c,agentExtension as x}from"./component.mjs";import{default as T}from"./packem_shared/createAgentContext-TMvmjncE.mjs";import{defineAgent as A,defineAgentTool as g,isAgentDefinition as S}from"./packem_shared/defineAgent-Cqr8-Kf1.mjs";import{functionTool as N}from"./packem_shared/functionTool-Cf433Hdo.mjs";import{createAgentGenerate as h,createEpisodeExtract as C,createGraphExtract as M,createStreamGenerate as O,resolveAgentModel as _}from"./packem_chunks/createAgentGenerate.mjs";import{jsCodeTool as U}from"./packem_shared/jsCodeTool-BJB3Fpm2.mjs";import{default as G}from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{adaptMcpResult as v,mcpTools as L}from"./packem_shared/adaptMcpResult-CA-3ovJd.mjs";import{buildModelMessages as B}from"./packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as V,agentDefaultName as j,voiceBindingName as H,voiceClassName as I}from"./naming.mjs";import{AGENT_MODULE as X,DEFAULT_AGENT_FUNCTION_PATHS as q,SANDBOX_INVOKE_PATH as y,SANDBOX_MODULE as K,toFunctionReference as W}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{browserTool as J,containerFsTool as Q,containerTool as Y,fsTool as Z}from"./sandbox.mjs";import{default as ee}from"./packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs";import{SecretUnavailableError as re,requestSecretTool as te,withSecret as ae}from"./packem_shared/SecretUnavailableError-CL7caQjN.mjs";import{defineSkill as fe,isSkillDefinition as le}from"./packem_shared/defineSkill-DGGvDWNq.mjs";import{default as me}from"./packem_shared/wrapUntrusted-CEngnRHW.mjs";import{default as ie}from"./packem_shared/VoiceSessionDO-CdvG2L-D.mjs";import{r as xe}from"./packem_shared/voice-turn-B9omvXoR.mjs";import{webSearchTool as Te}from"./packem_shared/webSearchTool-BzXW0R4r.mjs";import{default as Ae}from"./packem_shared/compileAgentWorkflow-yZB8fbYc.mjs";export{X as AGENT_MODULE,q as DEFAULT_AGENT_FUNCTION_PATHS,y as SANDBOX_INVOKE_PATH,K as SANDBOX_MODULE,re as SecretUnavailableError,ie as VoiceSessionDO,v as adaptMcpResult,s as agentAsTool,V as agentClassName,c as agentComponent,j as agentDefaultName,x as agentExtension,J as browserTool,B as buildModelMessages,p as codeTool,n as collectAgenticMemoryTools,Ae as compileAgentWorkflow,Q as containerFsTool,Y as containerTool,T as createAgentContext,h as createAgentGenerate,C as createEpisodeExtract,M as createGraphExtract,O as createStreamGenerate,A as defineAgent,g as defineAgentTool,fe as defineSkill,Z as fsTool,N as functionTool,S as isAgentDefinition,le as isSkillDefinition,U as jsCodeTool,G as jsonSchema,L as mcpTools,te as requestSecretTool,_ as resolveAgentModel,r as runAgentLoop,xe as runVoiceTurn,t as splitForCompaction,W as toFunctionReference,f as toSearchResults,H as voiceBindingName,I as voiceClassName,Te as webSearchTool,ee as withAgentScheduleShard,ae as withSecret,me as wrapUntrusted};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{usageStatus as dt}from"@lunora/ai/create";import{e as ut}from"../packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as lt}from"@lunora/platform";import{r as Q}from"../packem_shared/workflow-binding-Dm9hBzx_.mjs";import{a as pt}from"../packem_shared/app-call-options-BE0CQ6Qg.mjs";import{d as mt,a as V,S as z}from"../packem_shared/component-shared--SPcu0Iw.mjs";import{usageOfFailedTurn as yt,resolveAgentModel as ft}from"./createAgentGenerate.mjs";import{r as ht,f as gt,m as I,a as wt}from"../packem_shared/memory-JI0lUu84.mjs";import{buildModelMessages as B}from"../packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as Z}from"../naming.mjs";import{toFunctionReference as v}from"../packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{i as vt}from"../packem_shared/positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as Tt,secretLabelOf as St}from"../packem_shared/SecretUnavailableError-BsJMGfML.mjs";import{combineTelemetry as $t}from"../packem_shared/combineTelemetry-DgE9W9G8.mjs";import{c as J}from"../packem_shared/tool-output-Cmk3JWMG.mjs";const Et=200,Ct=e=>{const t=e.findIndex(o=>o.role!=="tool");return t===-1?[]:e.slice(t)},Rt=async e=>{let t=Et;for(;;){const o=await e(t),a=Ct(o);if(a.length>0||o.length<t)return a;t*=2}},xt=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const o=Array.isArray(t)?t:[t];return o.length===0?void 0:$t(...o)},It=async e=>{e===void 0||e.isEnabled===!1||await Promise.all([e.integrations].flat().map(async t=>{try{await t?.flush?.()}catch{}}))},Kt=async(e,t,o)=>{const a=xt(e);if(a===void 0)return o();const n={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},r={callId:t.id,messages:[],toolCall:n,toolContext:void 0},i=Date.now();await a.onToolExecutionStart?.(r);let c;const d=()=>(c??=o(),c);try{if(a.executeTool===void 0)await d();else try{await a.executeTool({...r,execute:d,toolCallId:t.id})}catch{}const u=await d();return await a.onToolExecutionEnd?.({...r,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,input:t.input,output:u,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),u}catch(u){throw await a.onToolExecutionEnd?.({...r,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:u,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),u}},kt=8,Mt=e=>vt(e)?e:0,tt=e=>e===void 0?"null":JSON.stringify(e),Nt=async(e,t,o)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...o===void 0?{}:{usage:o}})}catch(a){t instanceof Error&&t.cause===void 0&&(t.cause=a)}},Ot=e=>e===void 0?[]:[e].flat(),At=async(e,t)=>(await Promise.all(e.map(async a=>a({steps:t})))).some(Boolean),_t=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],j=e=>e.status??dt(e),qt=(e,t)=>e===t?e:"partial",et=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:j(t)};const o={status:qt(j(e),j(t))};for(const a of _t)(e[a]!==void 0||t[a]!==void 0)&&(o[a]=(e[a]??0)+(t[a]??0));return o},Ut=async(e,t,o,a,n,r)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:o.do(a,async()=>await r()?!1:i===!0||i(t,n))},bt="WorkflowTimeoutError",ot=e=>e instanceof Error&&e.name===bt,Dt=async(e,t)=>{const{agent:o,deleteMessage:a,instanceId:n,patchThread:r,persist:i,step:c}=e,d=V(o.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+d,messageKey:`${n}:approval:${t.id}`,role:"tool",approvalAgent:e.agentName,status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await r({status:"awaiting_input"})});const u=await c.waitForEvent(`approval:${t.id}`,{timeout:d,type:`agent-approval:${t.id}`}).then(p=>({decision:p.payload.decision,...p.payload.note===void 0?{}:{note:p.payload.note},...p.payload.scope===void 0?{}:{scope:p.payload.scope}})).catch(p=>{if(!ot(p))throw p;return{decision:"reject",note:"approval timed out"}});return await a(`${n}:approval:${t.id}`),await r({status:"running"}),u},Ft={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Gt=(e,t)=>`${String(e)}:${t}`,Lt=async(e,t,o,a,n)=>{const{agent:r,deleteMessage:i,instanceId:c,openSecretRef:d,patchThread:u,persist:p,run:s,settleSecretRef:l,step:m,threadKey:f}=e,T=`${c}:secret:${n}`,y=Math.min(V(r.approvalTimeout),lt-z);await m.do(`secret:request:${n}`,async()=>{await s(d,{consumerTool:o,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:a,threadKey:f,toolCallId:n,toolName:t.name})}),await m.do(`secret:await:${n}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${a}`,messageKey:T,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await u({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${n}`,{timeout:y+z,type:`agent-secret:${n}`}).catch(w=>{if(!ot(w))throw w});const{status:h}=await m.do(`secret:settle:${n}`,async()=>await s(l,{instanceId:c,threadKey:f,toolCallId:n}));return await i(T),await u({ifInstanceId:c,status:"running"}),h},U="lunoraToolOutcome",Pt=e=>typeof e=="object"&&e!==null&&U in e?e[U]:{ok:e},Wt=async(e,t,o,a)=>{const{instanceId:n,persist:r}=e,i=Gt(a,t.id),c=`${n}:secret-result:${i}`,d=`tool:${t.name}:${i}`,u=St(t.input);if(u===void 0){await r({content:`Error: invalid input for tool "${t.name}" — it was not run. \`label\` must be a non-empty string saying what the secret is for.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}if(e.owner===void 0){await r({content:`Error: tool "${t.name}" was not run: this run has no owner, so no one can supply a secret for it.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const p=await Lt(e,t,o,u,i);await r({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${Ft[p]}.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name})},jt=async(e,t,o)=>{const{agent:a,agentName:n,approvalGrantedRef:r,depth:i,env:c,exports:d,getState:u,instanceId:p,onTokenDelta:s,owner:l,persist:m,run:f,setState:T,shardKey:y,step:h,threadKey:w,tools:b}=e,$=`tool:${t.name}:${t.id}`,E=b[t.name],C=`${p}:tool:${t.id}`;if(!E){await m({content:`Error: unknown tool "${t.name}"`,messageKey:C,role:"tool",stepName:$,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await m({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:C,role:"tool",stepName:$,toolCallId:t.id,toolName:t.name});return}if(E.secretRequest!==void 0){await Wt(e,t,E.secretRequest.consumer,o);return}const D={depth:i,env:c,exports:d,getState:u,idempotencyKey:$,instanceId:p,owner:l,reportProgress:S=>{s?.({data:S,kind:"progress",threadKey:w,toolCallId:t.id})},run:f,setState:T,shardKey:y,step:h,threadKey:w,toolCallId:t.id},F={depth:i,env:c,getState:u,idempotencyKey:$,instanceId:p,run:f,shardKey:y,threadKey:w,toolCallId:t.id},G=`tool:approval-gate:${t.id}`;let M,N;const L=async()=>await f(r,{agent:n,key:w,toolName:t.name})===!0;if(await Ut(E,t.input,h,G,F,L)){const{decision:S,note:R,scope:K}=await Dt(e,t);if(S==="reject"){const P=R===void 0?"":` Reason: ${R}`;await m({content:`Tool "${t.name}" was rejected by the user and not run.${P}`,messageKey:C,role:"tool",status:"rejected",stepName:$,toolCallId:t.id,toolName:t.name});return}M="approved",N=K}const O={...M===void 0?{}:{status:M},...N===void 0?{}:{approvalScope:N}},A=Pt(await h.do($,async()=>{try{const S=()=>Promise.resolve(E.execute(t.input,D)),R=await Kt(a.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[U]:{ok:R}}}catch(S){if(ut(S)||S instanceof Tt)return{[U]:{failed:S.message}};throw S}}));if("failed"in A){await m({content:J(`Error: tool "${t.name}" failed and will not be retried. ${A.failed}`),messageKey:C,role:"tool",stepName:$,...O,toolCallId:t.id,toolName:t.name});return}const _=A.ok;await m({content:J(typeof _=="string"?_:tt(_)),messageKey:C,role:"tool",stepName:$,...O,toolCallId:t.id,toolName:t.name})},Bt=(e,t,o)=>{if(!t)return e;let{messages:a}=e;return t.messages!==void 0&&(a=t.messages),t.system!==void 0&&(a=[{content:t.system,role:"system"},...a]),{activeTools:t.activeTools??e.activeTools,messages:a,model:t.model===void 0?e.model:ft(t.model,o),toolChoice:t.toolChoice??e.toolChoice}},at=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const o=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=o)return;let a=e.length-o;for(;a>0&&e[a]?.role==="tool";)a-=1;if(!(a<=0))return{older:e.slice(0,a),recent:e.slice(a)}},Ht=async(e,t)=>{const{agent:o,compact:a,env:n}=e,r=at(t,o.compaction);if(r===void 0||a===void 0)return{history:t,summary:void 0};try{const i=await a({env:n,messages:B({history:r.older}),model:o.compaction?.model??o.model});return i.length>0?{history:r.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Yt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},zt=async e=>{const{agent:t,compact:o,env:a,historyRef:n,instanceId:r,patchThread:i,run:c,threadKey:d}=e,u=Yt(t.compaction),p=await c(n,{configKey:u,key:d}),{messages:s,summary:l}=p,m=at(s,t.compaction);if(m===void 0||o===void 0)return{history:s,summary:l};const f=async()=>{const{fallback:h}=p;return h===void 0?{history:s,summary:l}:(await i({ifInstanceId:r,summaryRebuiltSeq:h.throughSeq}).catch(w=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${d}"`,w)}),{history:s.filter(w=>w.seq>h.throughSeq),summary:h.summary})};let T;try{T=await o({env:a,messages:B({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(h){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,h),f()}if(T.length===0)return f();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:r,summary:T,summaryConfig:u,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(h=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,h)}),{history:m.recent,summary:T}},Jt=async(e,t,o)=>{const{agent:a,env:n,generate:r,instructions:i,listMessages:c,memoryContext:d,onTokenDelta:u,run:p,step:s,streamGenerate:l,threadKey:m}=e;return s.do(`llm:turn:${String(t)}`,async()=>{const{history:f,summary:T}=a.compaction!==void 0&&e.compact!==void 0?await zt(e):await Ht(e,await Rt(async w=>await p(c,{key:m,limit:w})));let y={activeTools:a.activeTools,messages:B({history:f,instructions:i,memoryContext:d,summary:T}),model:void 0,toolChoice:a.toolChoice};a.prepareStep&&(y=Bt(y,await a.prepareStep({messages:y.messages,stepNumber:t,steps:o}),n));const h={messages:y.messages,...y.activeTools===void 0?{}:{activeTools:y.activeTools},...y.model===void 0?{}:{model:y.model},...y.toolChoice===void 0?{}:{toolChoice:y.toolChoice}};return l&&u?l(h,w=>{u({text:w,threadKey:m,turn:t})}):r(h)})},X=async(e,t)=>{const{agent:o,step:a}=e;o.onStepFinish&&await a.do(`agent:step-finish:${String(t.turn)}`,async()=>(await o.onStepFinish?.(t),!0))},Xt=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),H=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},Qt=e=>mt({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),Vt=async(e,t,o,a,n)=>{if(e.source===void 0)return;const r=v(e.source),{topK:i}=e,c=I("memory:retrieve",e.key),d={query:t,...i===void 0?{}:{topK:i}},u=await a.do(c,async()=>n(r,d,pt(o)));return H(u)},Zt=async(e,t,o,a,n,r)=>{if(o===void 0)return;const i=I("memory:traverse",e.key),c=await n.do(i,async()=>r(a,{owner:o,query:t,...Qt(e.graph)}));return H(c)},te=async(e,t,o,a,n)=>{if(t===void 0)return;const r=I("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await a.do(r,async()=>n(o,i));return H(c)},ee=async(e,t)=>e.kind==="episodic"?te(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?Zt(e,t.input,t.owner,t.graphTraverse,t.step,t.run):Vt(e,t.input,t.shardKey,t.step,t.run),oe=e=>{const t=e.findIndex(o=>o.kind==="episodic");return e.filter((o,a)=>o.kind!=="episodic"||a===t)},ae=async(e,t,o,a,n,r,i)=>{const c=oe(ht(e));if(c.length===0)return;const d=v(n.graphTraverse),u=v(n.episodeRecall),p=[];for(const s of c){const l=await ee(s,{episodeRecall:u,graphTraverse:d,input:t,owner:o,run:i,shardKey:a,step:r});l!==void 0&&p.push(l)}return p.length>0?p.join(`
|
|
1
|
+
import{usageStatus as lt}from"@lunora/ai/create";import{e as pt}from"../packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as mt}from"@lunora/platform";import{r as V}from"../packem_shared/workflow-binding-Dm9hBzx_.mjs";import{a as yt}from"../packem_shared/app-call-options-BE0CQ6Qg.mjs";import{a as z,C as ft}from"../packem_shared/code-tool-DgKolSi1.mjs";import{d as ht,a as Z,S as J}from"../packem_shared/component-shared--SPcu0Iw.mjs";import{usageOfFailedTurn as gt,resolveAgentModel as wt}from"./createAgentGenerate.mjs";import{r as vt,f as Tt,m as I,a as St}from"../packem_shared/memory-JI0lUu84.mjs";import{buildModelMessages as H}from"../packem_shared/buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as tt}from"../naming.mjs";import{toFunctionReference as w}from"../packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{i as Ct}from"../packem_shared/positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as $t,secretLabelOf as Et}from"../packem_shared/SecretUnavailableError-CL7caQjN.mjs";import{combineTelemetry as Rt}from"../packem_shared/combineTelemetry-DgE9W9G8.mjs";const xt=200,It=e=>{const t=e.findIndex(a=>a.role!=="tool");return t===-1?[]:e.slice(t)},kt=async e=>{let t=xt;for(;;){const a=await e(t),o=It(a);if(o.length>0||a.length<t)return o;t*=2}},Kt=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const a=Array.isArray(t)?t:[t];return a.length===0?void 0:Rt(...a)},Mt=async e=>{e===void 0||e.isEnabled===!1||await Promise.all([e.integrations].flat().map(async t=>{try{await t?.flush?.()}catch{}}))},Nt=async(e,t,a)=>{const o=Kt(e);if(o===void 0)return a();const n={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},r={callId:t.id,messages:[],toolCall:n,toolContext:void 0},i=Date.now();await o.onToolExecutionStart?.(r);let u;const d=()=>(u??=a(),u);try{if(o.executeTool===void 0)await d();else try{await o.executeTool({...r,execute:d,toolCallId:t.id})}catch{}const c=await d();return await o.onToolExecutionEnd?.({...r,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,input:t.input,output:c,toolCallId:t.id,toolName:t.name,type:"tool-result"}}),c}catch(c){throw await o.onToolExecutionEnd?.({...r,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:c,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),c}},Ot=8,_t=e=>Ct(e)?e:0,et=e=>e===void 0?"null":JSON.stringify(e),At=async(e,t,a)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...a===void 0?{}:{usage:a}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},qt=e=>e===void 0?[]:[e].flat(),Ut=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),bt=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],B=e=>e.status??lt(e),Dt=(e,t)=>e===t?e:"partial",ot=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:B(t)};const a={status:Dt(B(e),B(t))};for(const o of bt)(e[o]!==void 0||t[o]!==void 0)&&(a[o]=(e[o]??0)+(t[o]??0));return a},Ft=async(e,t,a,o,n,r)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:a.do(o,async()=>await r()?!1:i===!0||i(t,n))},Gt="WorkflowTimeoutError",at=e=>e instanceof Error&&e.name===Gt,Pt=async(e,t,a)=>{const{agent:o,deleteMessage:n,instanceId:r,patchThread:i,persist:u,step:d}=e,c=Z(o.approvalTimeout);await d.do(`approval:request:${a}`,async()=>{await u({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+c,messageKey:`${r}:approval:${a}`,role:"tool",approvalAgent:e.agentName,approvalSlot:a,status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await i({status:"awaiting_input"})});const p=await d.waitForEvent(`approval:${a}`,{timeout:c,type:`agent-approval:${a}`}).then(s=>({decision:s.payload.decision,...s.payload.note===void 0?{}:{note:s.payload.note},...s.payload.scope===void 0?{}:{scope:s.payload.scope}})).catch(s=>{if(!at(s))throw s;return{decision:"reject",note:"approval timed out"}});return await n(`${r}:approval:${a}`),await i({status:"running"}),p},Lt={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},nt=(e,t)=>`${String(e)}:${t}`,Wt=(e,t,a)=>{let o=t;for(;a.has(o)||o.startsWith(ft);)o=nt(e,o);return o},st=(e,t,a)=>t.map(o=>{const n=Wt(e,o,a);return a.add(n),n}),jt=e=>{const t=new Set;for(const[a,o]of e.entries())st(a,o.toolCalls.map(n=>n.toolCallId),t);return t},Bt=async(e,t,a,o,n)=>{const{agent:r,deleteMessage:i,instanceId:u,openSecretRef:d,patchThread:c,persist:p,run:s,settleSecretRef:l,step:m,threadKey:y}=e,T=`${u}:secret:${n}`,f=Math.min(Z(r.approvalTimeout),mt-J);await m.do(`secret:request:${n}`,async()=>{await s(d,{agent:e.agentName,consumerTool:a,expiresAt:Date.now()+f,instanceId:u,callId:t.id,label:o,threadKey:y,toolCallId:n,toolName:t.name})}),await m.do(`secret:await:${n}`,async()=>{await p({content:`Awaiting a secret for tool "${t.name}": ${o}`,messageKey:T,role:"tool",status:"awaiting_secret",toolCallId:t.id,toolName:t.name}),await c({ifInstanceId:u,status:"awaiting_input"})}),await m.waitForEvent(`secret:${n}`,{timeout:f+J,type:`agent-secret:${n}`}).catch(v=>{if(!at(v))throw v});const{status:g}=await m.do(`secret:settle:${n}`,async()=>await s(l,{instanceId:u,threadKey:y,toolCallId:n}));return await i(T),await c({ifInstanceId:u,status:"running"}),g},b="lunoraToolOutcome",Ht=e=>typeof e=="object"&&e!==null&&b in e?e[b]:{ok:e},Yt=async(e,t,a,o)=>{const{instanceId:n,persist:r}=e,i=nt(o,t.id),u=`${n}:secret-result:${i}`,d=`tool:${t.name}:${i}`,c=Et(t.input);if(c===void 0){await r({content:`Error: invalid input for tool "${t.name}" — it was not run. \`label\` must be a non-empty string saying what the secret is for.`,messageKey:u,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}if(e.owner===void 0){await r({content:`Error: tool "${t.name}" was not run: this run has no owner, so no one can supply a secret for it.`,messageKey:u,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name});return}const p=await Bt(e,t,a,c,i);await r({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${Lt[p]}.`,messageKey:u,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name})},Xt=async(e,t,a,o)=>{const{agent:n,agentName:r,approvalGrantedRef:i,depth:u,env:d,exports:c,getState:p,instanceId:s,onTokenDelta:l,owner:m,persist:y,run:T,setState:f,shardKey:g,step:v,threadKey:k,tools:D}=e,C=`tool:${t.name}:${o}`,E=D[t.name],R=`${s}:tool:${o}`;if(!E){await y({content:`Error: unknown tool "${t.name}"`,messageKey:R,role:"tool",stepName:C,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await y({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:R,role:"tool",stepName:C,toolCallId:t.id,toolName:t.name});return}if(E.secretRequest!==void 0){await Yt(e,t,E.secretRequest.consumer,a);return}const F={callKey:o,depth:u,env:d,exports:c,getState:p,idempotencyKey:C,instanceId:s,owner:m,reportProgress:S=>{l?.({data:S,kind:"progress",threadKey:k,toolCallId:t.id})},run:T,setState:f,shardKey:g,step:v,threadKey:k,toolCallId:t.id},G={callKey:o,depth:u,env:d,getState:p,idempotencyKey:C,instanceId:s,run:T,shardKey:g,threadKey:k,toolCallId:t.id},P=`tool:approval-gate:${o}`;let M,N;const A=async()=>await T(i,{agent:r,key:k,toolName:t.name})===!0;if(await Ft(E,t.input,v,P,G,A)){const{decision:S,note:$,scope:L}=await Pt(e,t,o);if(S==="reject"){const W=$===void 0?"":` Reason: ${$}`;await y({content:`Tool "${t.name}" was rejected by the user and not run.${W}`,messageKey:R,role:"tool",status:"rejected",stepName:C,toolCallId:t.id,toolName:t.name});return}M="approved",N=L}const q={...M===void 0?{}:{status:M},...N===void 0?{}:{approvalScope:N}},O=Ht(await v.do(C,async()=>{try{const S=()=>Promise.resolve(E.execute(t.input,F)),$=await Nt(n.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[b]:{ok:$}}}catch(S){if(pt(S)||S instanceof $t)return{[b]:{failed:S.message}};throw S}}));if("failed"in O){await y({content:z(`Error: tool "${t.name}" failed and will not be retried. ${O.failed}`),messageKey:R,role:"tool",stepName:C,...q,toolCallId:t.id,toolName:t.name});return}const _=O.ok;await y({content:z(typeof _=="string"?_:et(_)),messageKey:R,role:"tool",stepName:C,...q,toolCallId:t.id,toolName:t.name})},zt=(e,t,a)=>{if(!t)return e;let{messages:o}=e;return t.messages!==void 0&&(o=t.messages),t.system!==void 0&&(o=[{content:t.system,role:"system"},...o]),{activeTools:t.activeTools??e.activeTools,messages:o,model:t.model===void 0?e.model:wt(t.model,a),toolChoice:t.toolChoice??e.toolChoice}},rt=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const a=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=a)return;let o=e.length-a;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},Jt=async(e,t)=>{const{agent:a,compact:o,env:n}=e,r=rt(t,a.compaction);if(r===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:n,messages:H({history:r.older}),model:a.compaction?.model??a.model});return i.length>0?{history:r.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Qt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},Vt=async e=>{const{agent:t,compact:a,env:o,historyRef:n,instanceId:r,patchThread:i,run:u,threadKey:d}=e,c=Qt(t.compaction),p=await u(n,{configKey:c,key:d}),{messages:s,summary:l}=p,m=rt(s,t.compaction);if(m===void 0||a===void 0)return{history:s,summary:l};const y=async()=>{const{fallback:g}=p;return g===void 0?{history:s,summary:l}:(await i({ifInstanceId:r,summaryRebuiltSeq:g.throughSeq}).catch(v=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${d}"`,v)}),{history:s.filter(v=>v.seq>g.throughSeq),summary:g.summary})};let T;try{T=await a({env:o,messages:H({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(g){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,g),y()}if(T.length===0)return y();const f=m.older.at(-1)?.seq;return await i({ifInstanceId:r,summary:T,summaryConfig:c,...l===void 0?{summaryRebuiltSeq:f}:{},summaryThroughSeq:f}).catch(g=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,g)}),{history:m.recent,summary:T}},Zt=async(e,t,a)=>{const{agent:o,env:n,generate:r,instructions:i,listMessages:u,memoryContext:d,onTokenDelta:c,run:p,step:s,streamGenerate:l,threadKey:m}=e;return s.do(`llm:turn:${String(t)}`,async()=>{const{history:y,summary:T}=o.compaction!==void 0&&e.compact!==void 0?await Vt(e):await Jt(e,await kt(async v=>await p(u,{key:m,limit:v})));let f={activeTools:o.activeTools,messages:H({history:y,instructions:i,memoryContext:d,summary:T}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(f=zt(f,await o.prepareStep({messages:f.messages,stepNumber:t,steps:a}),n));const g={messages:f.messages,...f.activeTools===void 0?{}:{activeTools:f.activeTools},...f.model===void 0?{}:{model:f.model},...f.toolChoice===void 0?{}:{toolChoice:f.toolChoice}};return l&&c?l(g,v=>{c({text:v,threadKey:m,turn:t})}):r(g)})},Q=async(e,t)=>{const{agent:a,step:o}=e;a.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await a.onStepFinish?.(t),!0))},te=e=>({text:e.text,toolCalls:e.toolCalls.map(t=>({input:t.input,toolCallId:t.id,toolName:t.name})),...e.usage===void 0?{}:{usage:e.usage}}),Y=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},ee=e=>ht({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),oe=async(e,t,a,o,n)=>{if(e.source===void 0)return;const r=w(e.source),{topK:i}=e,u=I("memory:retrieve",e.key),d={query:t,...i===void 0?{}:{topK:i}},c=await o.do(u,async()=>n(r,d,yt(a)));return Y(c)},ae=async(e,t,a,o,n,r)=>{if(a===void 0)return;const i=I("memory:traverse",e.key),u=await n.do(i,async()=>r(o,{owner:a,query:t,...ee(e.graph)}));return Y(u)},ne=async(e,t,a,o,n)=>{if(t===void 0)return;const r=I("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},u=await o.do(r,async()=>n(a,i));return Y(u)},se=async(e,t)=>e.kind==="episodic"?ne(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?ae(e,t.input,t.owner,t.graphTraverse,t.step,t.run):oe(e,t.input,t.shardKey,t.step,t.run),re=e=>{const t=e.findIndex(a=>a.kind==="episodic");return e.filter((a,o)=>a.kind!=="episodic"||o===t)},ie=async(e,t,a,o,n,r,i)=>{const u=re(vt(e));if(u.length===0)return;const d=w(n.graphTraverse),c=w(n.episodeRecall),p=[];for(const s of u){const l=await se(s,{episodeRecall:c,graphTraverse:d,input:t,owner:a,run:i,shardKey:o,step:r});l!==void 0&&p.push(l)}return p.length>0?p.join(`
|
|
2
2
|
|
|
3
|
-
`):void 0},
|
|
3
|
+
`):void 0},ce=async e=>{const{agent:t,env:a,extractGraph:o,finalText:n,input:r,instanceId:i,owner:u,paths:d,run:c,step:p}=e;if(o===void 0||u===void 0||n===void 0||n.length===0)return;const s=Tt(t);if(s!==void 0)try{const l={assistantText:n,env:a,model:s.graph?.extractionModel??t.model,userInput:r},m=await p.do(I("memory:extract",s.key),async()=>o(l));await c(w(d.graphUpsert),{...m,messageKey:`${i}:${I("extract",s.key)}`,owner:u})}catch{}},ue=async e=>{const{agent:t,env:a,extractEpisode:o,finalText:n,input:r,instanceId:i,owner:u,paths:d,run:c,step:p,threadKey:s}=e;if(o===void 0||u===void 0||n===void 0||n.length===0)return;const l=St(t);if(l!==void 0)try{const m={assistantText:n,env:a,model:l.episodic?.extractionModel??t.model,userInput:r},{summary:y}=await p.do(I("memory:episode",l.key),async()=>o(m));await c(w(d.episodeUpsert),{messageKey:`${i}:${I("episode",l.key)}`,owner:u,summary:y,threadKey:s})}catch{}},de=async(e,t,a)=>{const o=V(e.env,e.exports,tt(t),["get"]);if(o!==void 0)try{await(await o.get(a)).terminate()}catch{}},le="12 hours",pe=async(e,t,a)=>{await e.waitForEvent(`dequeue:${a}`,{timeout:le,type:`agent-dequeue:${t}:${a}`})},me=async(e,t,a)=>{const o=V(e.env,e.exports,tt(e.exportName),["get"]);if(o===void 0)return;const n=o.get.bind(o);try{await e.step.do(`dequeue-wake:${a}`,async()=>(await(await n(a)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${a}`}),a))}catch{}},ye=async(e,t,a)=>{const{onReply:o}=e,{replyRef:n}=t.params;if(!(o===void 0||n===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:n,result:a,threadKey:t.params.threadKey}),n.channel))}catch{}},fe=async(e,t,a,o,n)=>{const{instanceId:r,persist:i}=e,u=a.usage===void 0?{}:{usage:a.usage};if(a.toolCalls.length===0){const c=a.output!==void 0&&a.text.length===0?et(a.output):a.text;return await i({content:c,messageKey:`${r}:assistant:${String(t)}`,role:"assistant"}),await Q(e,{text:a.text,toolCalls:[],turn:t,...u}),{final:{stopped:"final",text:a.text,turns:t+1,...a.output===void 0?{}:{output:a.output}}}}await i({content:a.text,messageKey:`${r}:assistant:${String(t)}`,role:"assistant",toolCalls:a.toolCalls});const d=st(t,a.toolCalls.map(c=>c.id),jt(o));for(const[c,p]of a.toolCalls.entries())await Xt(e,p,t,d[c]??p.id);if(await Q(e,{text:a.text,toolCalls:a.toolCalls,turn:t,...u}),o.push(te(a)),n.length>0&&await Ut(n,o))return"stopCondition"},he=async(e,t,a,o)=>{const n=[];let r,i=!1,u=0;for(let d=0;d<t;d+=1){const c=await Zt(e,d,n);o.value=ot(o.value,c.usage),u=d+1;const p=await fe(e,d,c,n,a);if(p==="stopCondition"){i=!0;break}if(p!==void 0){r=p.final;break}}return{final:r,stoppedByCondition:i,turnsRun:u}},Oe=async e=>{const{agent:t,compact:a,env:o,exportName:n,exports:r,extractEpisode:i,extractGraph:u,generate:d,instanceId:c,onTokenDelta:p,params:s,paths:l,run:m,step:y,streamGenerate:T}=e,f=t.maxTurns??Ot,g=qt(t.stopWhen),v=w(l.appendMessage),k=w(l.approvalGranted),D=w(l.openSecretRequest),C=w(l.settleSecretRequest),E=w(l.completeRun),R=w(l.ensureThread),X=w(l.listMessages),F=w(l.history),G=w(l.deleteMessage),P=w(l.patchThread),M=w(l.setState),N=w(l.state),A=async h=>{await m(v,{threadKey:s.threadKey,...h})},q=async h=>{await m(P,{key:s.threadKey,...h})},O=async h=>{await m(G,{messageKey:h,threadKey:s.threadKey})},_=async()=>{await A({content:s.input,messageKey:`${c}:user`,role:"user"})},S={dispatched:!1},$=async h=>{S.dispatched=!0;const U=await m(E,{instanceId:c,key:s.threadKey,...h});U?.dequeued!==void 0&&await me({env:o,exportName:n,exports:r,step:y},s.threadKey,U.dequeued)},L=async()=>await m(N,{key:s.threadKey}),W=async h=>{await m(M,{key:s.threadKey,state:h})},j=await m(R,{agent:n,instanceId:c,key:s.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...s.owner===void 0?{}:{owner:s.owner},...s.title===void 0?{}:{title:s.title}});j?.outcome==="replaced"&&await de({env:o,exports:r},n,j.priorInstanceId);const it=await ie(t,s.input,s.owner,s.shardKey,l,y,m),ct=typeof t.instructions=="function"?t.instructions({env:o,input:s.input,threadKey:s.threadKey}):t.instructions,ut={agent:t,agentName:n,approvalGrantedRef:k,openSecretRef:D,settleSecretRef:C,compact:a,depth:_t(s.depth),env:o,exports:r,generate:d,getState:L,historyRef:F,instanceId:c,instructions:ct,listMessages:X,memoryContext:it,onTokenDelta:p,owner:s.owner,deleteMessage:O,patchThread:q,persist:A,run:m,setState:W,shardKey:s.shardKey,step:y,streamGenerate:T,threadKey:s.threadKey,tools:t.tools??{}},K={value:void 0};try{j?.outcome==="queued"&&await pe(y,s.threadKey,c),await _();const{final:h,stoppedByCondition:U,turnsRun:dt}=await he(ut,f,g,K),x=K.value===void 0?{}:{usage:K.value};return await ce({agent:t,env:o,extractGraph:u,finalText:h?.text,input:s.input,instanceId:c,owner:s.owner,paths:l,run:m,step:y}),await ue({agent:t,env:o,extractEpisode:i,finalText:h?.text,input:s.input,instanceId:c,owner:s.owner,paths:l,run:m,step:y,threadKey:s.threadKey}),h?(await ye(t,{env:o,params:s,step:y},{...h,...x}),await $({status:"idle",...x}),{...h,...x}):U?(await $({status:"idle",...x}),{stopped:"stopCondition",turns:dt,...x}):(await $({error:`agent stopped: maxTurns (${String(f)}) reached`,status:"error",...x}),{stopped:"maxTurns",turns:f,...x})}catch(h){throw S.dispatched||(K.value=ot(K.value,gt(h)),await At($,h,K.value)),h}finally{await Mt(t.telemetry)}};export{ot as addUsage,Jt as compactHistory,Oe as runAgentLoop,rt as splitForCompaction};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import p from"./jsonSchema-fhoaBWpN.mjs";import{toFunctionReference as d,DEFAULT_AGENT_FUNCTION_PATHS as u}from"./AGENT_MODULE-CYBmT9SD.mjs";const g=200,T=e=>{const t=typeof e=="object"&&e!==null?e.label:void 0;if(!(typeof t!="string"||t.trim().length===0))return[...t.trim()].slice(0,g).join("")};class w extends Error{code="SECRET_UNAVAILABLE";constructor(){super("the secret is no longer available: it expired, was already used by another tool call, or was never supplied"),this.name="SecretUnavailableError"}}const I=e=>{if(typeof e.description!="string"||e.description.length===0)throw new i("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `description` (the model decides from it)");if(typeof e.consumer!="string"||e.consumer.length===0)throw new i("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `consumer`: the name of the one tool allowed to read the value");return{description:e.description,execute:()=>{throw new i("INTERNAL","@lunora/agent: requestSecretTool is resolved by the loop and must never be executed")},inputSchema:p({properties:{label:{description:"What the secret is for, shown to the person asked.",type:"string"}},required:["label"],type:"object"}),isLunoraAgentTool:!0,secretRequest:{consumer:e.consumer}}},E=(e,t)=>t instanceof Error?{...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name,stack:t.stack}:t,h=e=>{const t=new TextEncoder().encode(e),n=Array.from(t,r=>String.fromCodePoint(r)).join(""),a=btoa(n),o=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return[...new Set([a,a.replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),encodeURIComponent(e),o,JSON.stringify(e).slice(1,-1),e])]},m=(e,t)=>{if(t.length===0||e===void 0||typeof e=="function"||typeof e=="symbol")return!1;let n;try{n=JSON.stringify(e,E)}catch{return!1}return h(t).some(a=>n.includes(a))},b="[redacted]",f="@lunora/agent: withSecret's callback threw a value that is withheld, in case it carries the secret",c=(e,t)=>{if(t.length===0)return e;let n=e;for(const a of h(t).toSorted((o,r)=>r.length-o.length))n=n.split(a).join(b);return n},y=(e,t,n=new Set)=>{if(!(e instanceof Error))return new i("INTERNAL",f);if(n.has(e))return e;n.add(e);try{const{name:a}=e;typeof a=="string"&&Object.defineProperty(e,"name",{configurable:!0,value:c(a,t),writable:!0}),e.message=c(e.message,t),typeof e.stack=="string"&&(e.stack=c(e.stack,t));const o=e;for(const r of Object.getOwnPropertyNames(e)){if(r==="message"||r==="stack")continue;const s=o[r];if(s instanceof Error){const l=y(s,t,n);l!==s&&(o[r]=l)}else m(s,t)&&(o[r]=JSON.parse(c(JSON.stringify(s),t)))}}catch{return new i("INTERNAL",f)}return e},L=async(e,t,n)=>{const a=await e.step.do(`secret:consume:${e.idempotencyKey}:${t}`,async()=>{const o=await e.run(d(u.takeSecret),{claimant:e.idempotencyKey,consumerCallId:e.toolCallId,instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t});if(typeof o!="string")return{unavailable:!0};let r;try{r=await n(o)}catch(s){throw y(s,o)}return m(r,o)?{leaked:!0}:{result:r}});if("unavailable"in a)throw new w;if(await e.step.do(`secret:discard:${e.idempotencyKey}:${t}`,async()=>{await e.run(d(u.discardSecret),{instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t})}),"leaked"in a)throw new i("INTERNAL","@lunora/agent: withSecret's callback returned the secret, so its result was not recorded");return a.result};export{w as SecretUnavailableError,I as requestSecretTool,T as secretLabelOf,L as withSecret};
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import p from"./jsonSchema-fhoaBWpN.mjs";import{toFunctionReference as d,DEFAULT_AGENT_FUNCTION_PATHS as u}from"./AGENT_MODULE-CYBmT9SD.mjs";const g=200,T=e=>{const t=typeof e=="object"&&e!==null?e.label:void 0;if(!(typeof t!="string"||t.trim().length===0))return[...t.trim()].slice(0,g).join("")};class w extends Error{code="SECRET_UNAVAILABLE";constructor(){super("the secret is no longer available: it expired, was already used by another tool call, or was never supplied"),this.name="SecretUnavailableError"}}const I=e=>{if(typeof e.description!="string"||e.description.length===0)throw new i("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `description` (the model decides from it)");if(typeof e.consumer!="string"||e.consumer.length===0)throw new i("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `consumer`: the name of the one tool allowed to read the value");return{description:e.description,execute:()=>{throw new i("INTERNAL","@lunora/agent: requestSecretTool is resolved by the loop and must never be executed")},inputSchema:p({properties:{label:{description:"What the secret is for, shown to the person asked.",type:"string"}},required:["label"],type:"object"}),isLunoraAgentTool:!0,secretRequest:{consumer:e.consumer}}},E=(e,t)=>t instanceof Error?{...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name,stack:t.stack}:t,h=e=>{const t=new TextEncoder().encode(e),n=Array.from(t,r=>String.fromCodePoint(r)).join(""),a=btoa(n),o=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return[...new Set([a,a.replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),encodeURIComponent(e),o,JSON.stringify(e).slice(1,-1),e])]},m=(e,t)=>{if(t.length===0||e===void 0||typeof e=="function"||typeof e=="symbol")return!1;let n;try{n=JSON.stringify(e,E)}catch{return!1}return h(t).some(a=>n.includes(a))},b="[redacted]",f="@lunora/agent: withSecret's callback threw a value that is withheld, in case it carries the secret",c=(e,t)=>{if(t.length===0)return e;let n=e;for(const a of h(t).toSorted((o,r)=>r.length-o.length))n=n.split(a).join(b);return n},y=(e,t,n=new Set)=>{if(!(e instanceof Error))return new i("INTERNAL",f);if(n.has(e))return e;n.add(e);try{const{name:a}=e;typeof a=="string"&&Object.defineProperty(e,"name",{configurable:!0,value:c(a,t),writable:!0}),e.message=c(e.message,t),typeof e.stack=="string"&&(e.stack=c(e.stack,t));const o=e;for(const r of Object.getOwnPropertyNames(e)){if(r==="message"||r==="stack")continue;const s=o[r];if(s instanceof Error){const l=y(s,t,n);l!==s&&(o[r]=l)}else m(s,t)&&(o[r]=JSON.parse(c(JSON.stringify(s),t)))}}catch{return new i("INTERNAL",f)}return e},L=async(e,t,n)=>{const a=await e.step.do(`secret:consume:${e.idempotencyKey}:${t}`,async()=>{const o=await e.run(d(u.takeSecret),{claimant:e.idempotencyKey,consumerCallId:e.callKey??e.toolCallId,instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t});if(typeof o!="string")return{unavailable:!0};let r;try{r=await n(o)}catch(s){throw y(s,o)}return m(r,o)?{leaked:!0}:{result:r}});if("unavailable"in a)throw new w;if(await e.step.do(`secret:discard:${e.idempotencyKey}:${t}`,async()=>{await e.run(d(u.discardSecret),{instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t})}),"leaked"in a)throw new i("INTERNAL","@lunora/agent: withSecret's callback returned the secret, so its result was not recorded");return a.result};export{w as SecretUnavailableError,I as requestSecretTool,T as secretLabelOf,L as withSecret};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as E}from"@lunora/workflow";import{f as I}from"./fnv1a-BNN96GYb.mjs";import{w as L}from"./run-shard-B7iMrAI0.mjs";import{r as b}from"./workflow-binding-Dm9hBzx_.mjs";import N from"./jsonSchema-fhoaBWpN.mjs";import{agentClassName as P}from"../naming.mjs";import{toFunctionReference as _,DEFAULT_AGENT_FUNCTION_PATHS as M}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as w}from"./positive-integer-ztHqqpBk.mjs";const R=new Set(["complete","errored","terminated"]),K=600,T=3,k=500,x=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",D=t=>t!==null&&typeof t=="object"?t.output:void 0,U=async t=>{await new Promise(e=>{setTimeout(e,t)})},j=async(t,e,n,m)=>{for(let a=0;a<e;a+=1){const o=await t.status(),s=x(o);if(R.has(s))return{output:D(o),status:s};await m(n)}return{output:void 0,status:"timeout"}},C=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},F=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},J=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!w(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=P(e),m=t.maxPolls??K,a=t.pollIntervalMs??k,o=t.wait??U,s=_(M.listMessages),y=async(A,r)=>{const p=(w(r.depth)?r.depth:0)+1;if(p>T)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(T)} is already reached. Answer with what you have instead of delegating further.`;const i=b(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=r.callKey??r.toolCallId,h=`${r.threadKey}::sub::${e}::${f}`,g=`sub-${e}-${I(`${r.instanceId}:${e}:${f}`)}`,v={depth:p,input:A.prompt,threadKey:h,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:g,params:L(v,r.shardKey)});l=await i.get(d.id)}catch(d){if(!E(d))throw d;l=await i.get(g)}const{output:S,status:u}=await j(l,m,a,o);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(C(S)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const $=await r.run(s,{key:h});return F($)};return{description:t.description,execute:y,inputSchema:N({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{J as agentAsTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import T from"./jsonSchema-fhoaBWpN.mjs";import{i as $}from"./positive-integer-ztHqqpBk.mjs";const l=4e3,y="… [truncated]",v=e=>e.length<=l?e:`${e.slice(0,l-y.length)}${y}`,S=16,E=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=l?e:v(o)},b=(e,o)=>{let t=e;for(const a of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,a))return;t=t[a]}return t},d=(e,o)=>{if(Array.isArray(e))return e.map(r=>d(r,o));if(e===null||typeof e!="object")return e;const t=e;if(typeof t.$from=="string"){const r=t.$from;if(!Object.hasOwn(o,r))throw new i("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?b(o[r],t.$path):o[r]}const a={};for(const[r,n]of Object.entries(t))r!=="__proto__"&&(a[r]=d(n,o));return a},O=async(e,o,t)=>{const{asSchema:a}=await import("@ai-sdk/provider-utils"),{validate:r}=a(o.inputSchema);if(r===void 0)return t;const n=await r(t);if(n.success)return n.value;throw new i("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${n.error.message}`)},_="code-step:",u=e=>e.replaceAll("\\",String.raw`\\`).replaceAll(":",String.raw`\:`),w=(e,o)=>`${_}${u(e)}:${u(o)}`,j=async(e,o,t,a)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>a)throw new i("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(a)}. Split it across several code calls.`);const n={},p=[],f=new Set;for(const s of r){if(f.has(s.id))throw new i("BAD_REQUEST",`@lunora/agent: duplicate code step id "${s.id}" — each step id must be unique (later steps reference an output by id via $from)`);f.add(s.id)}for(const s of r){const c=Object.hasOwn(o,s.tool)?o[s.tool]:void 0;if(!c)throw new i("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${s.tool}" (available: ${Object.keys(o).join(", ")})`);const A=await O(s,c,d(s.input??{},n)),m={...t,callKey:w(t.callKey??t.toolCallId,s.id),idempotencyKey:w(t.idempotencyKey,s.id),toolCallId:`${t.toolCallId}:${u(s.id)}`},g=()=>Promise.resolve(c.execute(A,m)),h=await t.step.do(m.idempotencyKey,g);n[s.id]=h,p.push({id:s.id,output:E(h)})}return{final:p.at(-1)?.output,results:p}},R=e=>`Compose MULTIPLE tool calls in one turn as a script, instead of one call per turn. Provide \`steps\`: an ordered array of \`{ id, tool, input }\`. A later step's \`input\` may reference an earlier step's output with \`{ "$from": "<stepId>", "$path": "optional.dot.path" }\`. Available tools: ${Object.entries(e).map(([o,t])=>`"${o}" — ${t.description}`).join("; ")}.`,I=T({properties:{steps:{description:"Ordered tool calls; a later input may reference an earlier output via { $from, $path }.",items:{additionalProperties:!1,properties:{id:{description:"A name later steps reference this output by.",type:"string"},input:{additionalProperties:!0,description:"The tool input (may embed $from refs).",type:"object"},tool:{description:"The tool to call.",type:"string"}},required:["id","tool"],type:"object"},type:"array"}},required:["steps"],type:"object"}),N=(e,o={})=>{const t=e;if(!t||typeof t!="object"||Object.keys(t).length===0)throw new i("INTERNAL","@lunora/agent: codeTool requires a non-empty map of tools to compose");for(const[r,n]of Object.entries(t)){if(n.needsApproval!==void 0&&n.needsApproval!==!1)throw new i("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it has a \`needsApproval\` gate a code-mode script can't pause for. Expose it as a normal top-level tool, or gate the whole script via codeTool's \`needsApproval\`.`);if(n.secretRequest!==void 0)throw new i("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it is a requestSecretTool, which a code-mode script can't pause for the owner to supply. Expose it as a normal top-level tool.`)}if(o.maxSteps!==void 0&&!$(o.maxSteps))throw new i("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const a=o.maxSteps??S;return{description:o.description??R(e),execute:(r,n)=>j(r,e,n,a),inputSchema:I,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{_ as C,v as a,j as b,N as c,d as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./jsonSchema-fhoaBWpN.mjs";import"./positive-integer-ztHqqpBk.mjs";import{C as a,c,r as p,b as t}from"./code-tool-DgKolSi1.mjs";export{a as CODE_STEP_KEY_PREFIX,c as codeTool,p as resolveReferences,t as runToolScript};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as p}from"./agentAsTool-
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as p}from"./agentAsTool-Bwq7pYHQ.mjs";import{a as g}from"./component-shared--SPcu0Iw.mjs";import{i as m}from"./memory-JI0lUu84.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=e=>{if(e!==void 0&&(typeof e!="string"||e.length===0))throw new r("INTERNAL","@lunora/agent: defineAgent `name` must be a non-empty string when provided")},N=/^[a-zA-Z][\w-]*$/u,A=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=a}return o},k=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
|
|
2
2
|
|
|
3
3
|
`)},v=(e,n)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const t of n)t.knowledge&&m(t.knowledge)&&o.push({key:t.name,...t.knowledge});return o},y=e=>{const n=new Set;for(const o of e){if(typeof o.name!="string"||!w.test(o.name))throw new r("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new r("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(n.has(o.name))throw new r("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);n.add(o.name)}},E=(e,n)=>{if(e===void 0)return;const o=Object.keys(n).filter(t=>!e.includes(t));if(o.length>0)throw new r("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(t=>`"${t}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},I=(e,n)=>{const o=(t,s)=>{if(t&&t.kind!=="graph"&&t.kind!=="episodic"&&t.source===void 0)throw new r("INTERNAL",`@lunora/agent: ${s} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const t of n)o(t.knowledge,`skill "${t.name}" \`knowledge\``)},L=e=>{for(const[n,o]of[["resolveEmailShard",e.resolveEmailShard],["onInbound.resolveShard",e.onInbound?.resolveShard]])if(o!==void 0&&typeof o!="function")throw new r("INTERNAL",`@lunora/agent: \`${n}\` must be a function`)},b=e=>{if(e===void 0)return;const n=g(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},_=e=>{const n=e.model;if(n==null||typeof n=="string"&&n.length===0)throw new r("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(T(e.name),e.maxTurns!==void 0&&!u(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!u(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");b(e.approvalTimeout),L(e);const o=e.skills??[];y(o),I(e,o);const t=A(e,o),s=f(e,o);for(const[i,h]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=h}const a=Object.keys(s).length>0;E(e.activeTools,s);for(const i of Object.keys(t))if(!N.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=v(e,o),d=k(e,o);return{...e,asTool:p,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:t}:{}}},q=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,P=e=>{if(typeof e.execute!="function")throw new r("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{_ as defineAgent,P as defineAgentTool,q as isAgentDefinition};
|
|
@@ -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};
|
|
@@ -72,7 +72,8 @@ interface AgentStepLike {
|
|
|
72
72
|
*
|
|
73
73
|
* The `idempotencyKey` is the deterministic durable-step name
|
|
74
74
|
* (`tool:<name>:<toolCallId>`, further suffixed per script step for a
|
|
75
|
-
* `codeTool`). A
|
|
75
|
+
* `codeTool`). A call whose id repeats one from an earlier turn of the same run
|
|
76
|
+
* carries that turn in its key (`tool:<name>:<turn>:<toolCallId>`). A COMPLETED tool step is never re-run on a workflow replay
|
|
76
77
|
* (native step memoization) — but a step that FAILS mid-body is retried
|
|
77
78
|
* at-least-once, so a side-effecting tool (charge a card, send a mail) must
|
|
78
79
|
* dedupe on this key itself. `functionTool` forwards it to the dispatched
|
|
@@ -84,6 +85,12 @@ interface AgentStepLike {
|
|
|
84
85
|
* @experimental
|
|
85
86
|
*/
|
|
86
87
|
interface AgentToolContext {
|
|
88
|
+
/**
|
|
89
|
+
* The key this call's steps and rows are stored under: {@link AgentToolContext.toolCallId} on its first use in the run,
|
|
90
|
+
* turn-scoped (`<turn>:<id>`) when a provider reuses the id in a later turn. Key anything a tool derives per call
|
|
91
|
+
* (a sub-run, a stored object) on this, or a reused id finds the earlier call's. Absent outside the agent loop.
|
|
92
|
+
*/
|
|
93
|
+
callKey?: string;
|
|
87
94
|
/**
|
|
88
95
|
* How many sub-agent delegations deep this run already is — 0 for a run a
|
|
89
96
|
* user started, one more per `agent.asTool` hop. The loop copies it off
|
|
@@ -72,7 +72,8 @@ interface AgentStepLike {
|
|
|
72
72
|
*
|
|
73
73
|
* The `idempotencyKey` is the deterministic durable-step name
|
|
74
74
|
* (`tool:<name>:<toolCallId>`, further suffixed per script step for a
|
|
75
|
-
* `codeTool`). A
|
|
75
|
+
* `codeTool`). A call whose id repeats one from an earlier turn of the same run
|
|
76
|
+
* carries that turn in its key (`tool:<name>:<turn>:<toolCallId>`). A COMPLETED tool step is never re-run on a workflow replay
|
|
76
77
|
* (native step memoization) — but a step that FAILS mid-body is retried
|
|
77
78
|
* at-least-once, so a side-effecting tool (charge a card, send a mail) must
|
|
78
79
|
* dedupe on this key itself. `functionTool` forwards it to the dispatched
|
|
@@ -84,6 +85,12 @@ interface AgentStepLike {
|
|
|
84
85
|
* @experimental
|
|
85
86
|
*/
|
|
86
87
|
interface AgentToolContext {
|
|
88
|
+
/**
|
|
89
|
+
* The key this call's steps and rows are stored under: {@link AgentToolContext.toolCallId} on its first use in the run,
|
|
90
|
+
* turn-scoped (`<turn>:<id>`) when a provider reuses the id in a later turn. Key anything a tool derives per call
|
|
91
|
+
* (a sub-run, a stored object) on this, or a reused id finds the earlier call's. Absent outside the agent loop.
|
|
92
|
+
*/
|
|
93
|
+
callKey?: string;
|
|
87
94
|
/**
|
|
88
95
|
* How many sub-agent delegations deep this run already is — 0 for a run a
|
|
89
96
|
* user started, one more per `agent.asTool` hop. The loop copies it off
|
package/dist/reply.d.mts
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { Mailer } from '@lunora/mail';
|
|
20
20
|
import { InboundEmail } from '@lunora/mail/inbound';
|
|
21
|
-
import { a as AgentReplyRef } from "./packem_shared/types.d-
|
|
21
|
+
import { a as AgentReplyRef } from "./packem_shared/types.d-BdKHdKQu.mjs";
|
|
22
22
|
import 'ai';
|
|
23
23
|
/** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
|
|
24
24
|
type EmailReplyRef = Extract<AgentReplyRef, {
|
package/dist/reply.d.ts
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { Mailer } from '@lunora/mail';
|
|
20
20
|
import { InboundEmail } from '@lunora/mail/inbound';
|
|
21
|
-
import { a as AgentReplyRef } from "./packem_shared/types.d-
|
|
21
|
+
import { a as AgentReplyRef } from "./packem_shared/types.d-BdKHdKQu.js";
|
|
22
22
|
import 'ai';
|
|
23
23
|
/** The email arm of {@link AgentReplyRef}, narrowed for the helpers below. */
|
|
24
24
|
type EmailReplyRef = Extract<AgentReplyRef, {
|
package/dist/sandbox.d.mts
CHANGED
package/dist/sandbox.d.ts
CHANGED
package/dist/sandbox.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import a from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{toFunctionReference as T,SANDBOX_INVOKE_PATH as m}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{S as g,a as c}from"./packem_shared/sandbox-budgets-DDvj4Orr.mjs";import{jsCodeTool as j}from"./packem_shared/jsCodeTool-BJB3Fpm2.mjs";const i=T(m),f=e=>{if(e.op==="pdf")return"pdf";if(e.op==="screenshot")return e.type==="jpeg"?"jpeg":"png"},E=new Set(["bucket","path","root"]),
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import a from"./packem_shared/jsonSchema-fhoaBWpN.mjs";import{toFunctionReference as T,SANDBOX_INVOKE_PATH as m}from"./packem_shared/AGENT_MODULE-CYBmT9SD.mjs";import{S as g,a as c}from"./packem_shared/sandbox-budgets-DDvj4Orr.mjs";import{jsCodeTool as j}from"./packem_shared/jsCodeTool-BJB3Fpm2.mjs";const i=T(m),f=e=>{if(e.op==="pdf")return"pdf";if(e.op==="screenshot")return e.type==="jpeg"?"jpeg":"png"},E=new Set(["bucket","path","root"]),y='Drive a headless browser: screenshot a page, render it to PDF, read its HTML content, or scrape it. Set `op` to "screenshot" | "pdf" | "content" | "scrape" and pass the target `url`.',S='Talk to a sandboxed container: `fetch` an HTTP path on it, or `exec` a command inside it. Set `op` to "fetch" (with `path`) or "exec" (with `command`).',A='Read and write files in a persistent sandbox filesystem. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',w='Read and write files on the sandboxed container\'s own disk — the same disk its commands run against. Set `op` to "ls" (list a directory), "read", "write" (with `content`), "rm", or "stat", and pass `path`.',_="/workspace",p=e=>e.op==="write"||e.op==="rm",d=a({properties:{content:{description:"write: the file contents.",type:"string"},op:{description:"The filesystem operation to run.",enum:["ls","read","write","rm","stat"],type:"string"},path:{description:"The file or directory path, relative to the sandbox root.",type:"string"}},required:["op"],type:"object"}),N=a({properties:{fullPage:{description:"screenshot: capture the full scrollable page rather than just the viewport.",type:"boolean"},op:{description:"The browser operation to run.",enum:["screenshot","scrape","pdf","content"],type:"string"},selector:{description:"scrape: optional CSS selector hint to narrow the extraction.",type:"string"},type:{description:"screenshot: image encoding (default png).",enum:["png","jpeg"],type:"string"},url:{description:"The URL to operate on.",type:"string"}},required:["op","url"],type:"object"}),O=new Set(["DELETE","PATCH","POST","PUT"]),b=e=>e.op==="exec"||O.has((e.method??"GET").toUpperCase()),R=a({properties:{args:{description:"exec: command arguments.",items:{type:"string"},type:"array"},body:{description:"fetch: request body.",type:"string"},command:{description:"exec: the command to run.",type:"string"},method:{description:"fetch: HTTP method (default GET).",type:"string"},op:{description:"The container operation to run.",enum:["fetch","exec"],type:"string"},path:{description:"fetch: request path on the container (e.g. /health).",type:"string"}},required:["op"],type:"object"}),L=(e={})=>{const t=e.bucket!==void 0&&e.bucket.length>0?e.bucket:void 0;return{description:e.description??y,execute:async(o,r)=>{const n=f(o);if(n!==void 0&&t===void 0)return`Cannot run a "${o.op}": this browser tool has no \`bucket\` configured, so the render has nowhere to go. Use "content" or "scrape" for page text, or ask the operator to pass \`browserTool({ bucket })\`.`;const h=n===void 0?{}:{bucket:t,path:`${r.threadKey}/${r.callKey??r.toolCallId}.${n}`,...e.root===void 0?{}:{root:e.root}},l=Object.fromEntries(Object.entries(o).filter(([u])=>!E.has(u)));return await r.run(i,{...l,...h,kind:"browser"},{timeoutMs:g})},inputSchema:N,isLunoraAgentTool:!0,...e.needsApproval===void 0?{}:{needsApproval:e.needsApproval}}},k=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.needsApproval??b;return{description:t.description??S,execute:(r,n)=>n.run(i,{...r,instance:n.threadKey,kind:"container",name:e},{timeoutMs:c}),inputSchema:R,isLunoraAgentTool:!0,needsApproval:o}},F=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: fsTool requires an R2 `bucket` binding name (the r2_bucket declared in wrangler.jsonc)");return{description:t.description??A,execute:(o,r)=>{const n=typeof t.root=="function"?t.root(r):t.root??"";return r.run(i,{...o,bucket:e,kind:"fs",root:n})},inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}},x=(e,t={})=>{if(typeof e!="string"||e.length===0)throw new s("INTERNAL","@lunora/agent: containerFsTool requires a container `name` (the ctx.containers.<name> key from lunora/containers.ts)");const o=t.root??_;if(!o.startsWith("/"))throw new s("INTERNAL",`@lunora/agent: containerFsTool \`root\` must be an absolute path inside the container (got "${o}")`);return{description:t.description??w,execute:(r,n)=>n.run(i,{...r,instance:n.threadKey,kind:"containerFs",name:e,root:o},{timeoutMs:c}),inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}};export{L as browserTool,x as containerFsTool,k as containerTool,F as fsTool,j as jsCodeTool};
|
package/dist/skill-markdown.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/agent",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.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 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as S}from"@lunora/workflow";import{f as $}from"./fnv1a-BNN96GYb.mjs";import{w as E}from"./run-shard-B7iMrAI0.mjs";import{r as L}from"./workflow-binding-Dm9hBzx_.mjs";import b from"./jsonSchema-fhoaBWpN.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as P,DEFAULT_AGENT_FUNCTION_PATHS as _}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as g}from"./positive-integer-ztHqqpBk.mjs";const M=new Set(["complete","errored","terminated"]),R=600,w=3,k=500,x=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",C=t=>t!==null&&typeof t=="object"?t.output:void 0,D=async t=>{await new Promise(e=>{setTimeout(e,t)})},U=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=x(a);if(M.has(s))return{output:C(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},j=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},F=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},B=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!g(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??R,o=t.pollIntervalMs??k,a=t.wait??D,s=P(_.listMessages),T=async(y,r)=>{const p=(g(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=L(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,h=`sub-${e}-${$(`${r.instanceId}:${e}:${r.toolCallId}`)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:h,params:E(A,r.shardKey)});l=await i.get(d.id)}catch(d){if(!S(d))throw d;l=await i.get(h)}const{output:v,status:u}=await U(l,m,o,a);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(j(v)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const I=await r.run(s,{key:f});return F(I)};return{description:t.description,execute:T,inputSchema:b({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{B as agentAsTool};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";import y from"./jsonSchema-fhoaBWpN.mjs";import{i as w}from"./positive-integer-ztHqqpBk.mjs";import{M as v,c as A}from"./tool-output-Cmk3JWMG.mjs";const T=16,g=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=v?e:A(o)},$=(e,o)=>{let t=e;for(const i of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))return;t=t[i]}return t},l=(e,o)=>{if(Array.isArray(e))return e.map(r=>l(r,o));if(e===null||typeof e!="object")return e;const t=e;if(typeof t.$from=="string"){const r=t.$from;if(!Object.hasOwn(o,r))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?$(o[r],t.$path):o[r]}const i={};for(const[r,n]of Object.entries(t))r!=="__proto__"&&(i[r]=l(n,o));return i},S=async(e,o,t)=>{const{asSchema:i}=await import("@ai-sdk/provider-utils"),{validate:r}=i(o.inputSchema);if(r===void 0)return t;const n=await r(t);if(n.success)return n.value;throw new a("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${n.error.message}`)},b=async(e,o,t,i)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>i)throw new a("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(i)}. Split it across several code calls.`);const n={},p=[],d=new Set;for(const s of r){if(d.has(s.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${s.id}" — each step id must be unique (later steps reference an output by id via $from)`);d.add(s.id)}for(const s of r){const c=Object.hasOwn(o,s.tool)?o[s.tool]:void 0;if(!c)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${s.tool}" (available: ${Object.keys(o).join(", ")})`);const m=await S(s,c,l(s.input??{},n)),u={...t,idempotencyKey:`${t.idempotencyKey}:${s.id}`,toolCallId:`${t.toolCallId}:${s.id}`},h=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,h);n[s.id]=f,p.push({id:s.id,output:g(f)})}return{final:p.at(-1)?.output,results:p}},E=e=>`Compose MULTIPLE tool calls in one turn as a script, instead of one call per turn. Provide \`steps\`: an ordered array of \`{ id, tool, input }\`. A later step's \`input\` may reference an earlier step's output with \`{ "$from": "<stepId>", "$path": "optional.dot.path" }\`. Available tools: ${Object.entries(e).map(([o,t])=>`"${o}" — ${t.description}`).join("; ")}.`,O=y({properties:{steps:{description:"Ordered tool calls; a later input may reference an earlier output via { $from, $path }.",items:{additionalProperties:!1,properties:{id:{description:"A name later steps reference this output by.",type:"string"},input:{additionalProperties:!0,description:"The tool input (may embed $from refs).",type:"object"},tool:{description:"The tool to call.",type:"string"}},required:["id","tool"],type:"object"},type:"array"}},required:["steps"],type:"object"}),L=(e,o={})=>{const t=e;if(!t||typeof t!="object"||Object.keys(t).length===0)throw new a("INTERNAL","@lunora/agent: codeTool requires a non-empty map of tools to compose");for(const[r,n]of Object.entries(t)){if(n.needsApproval!==void 0&&n.needsApproval!==!1)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it has a \`needsApproval\` gate a code-mode script can't pause for. Expose it as a normal top-level tool, or gate the whole script via codeTool's \`needsApproval\`.`);if(n.secretRequest!==void 0)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it is a requestSecretTool, which a code-mode script can't pause for the owner to supply. Expose it as a normal top-level tool.`)}if(o.maxSteps!==void 0&&!w(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const i=o.maxSteps??T;return{description:o.description??E(e),execute:(r,n)=>b(r,e,n,i),inputSchema:O,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{L as codeTool,l as resolveReferences,b as runToolScript};
|
|
@@ -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};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const _=4e3,O="… [truncated]",t=T=>T.length<=4e3?T:`${T.slice(0,4e3-O.length)}${O}`;export{_ as M,t as c};
|