@lunora/agent 1.0.0-alpha.276 → 1.0.0-alpha.278
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/README.md +1 -2
- package/dist/channels.d.mts +2 -2
- package/dist/channels.d.ts +2 -2
- package/dist/channels.mjs +1 -1
- package/dist/component.mjs +1 -1
- package/dist/core.d.mts +204 -0
- package/dist/core.d.ts +204 -0
- package/dist/core.mjs +1 -0
- package/dist/inbound.d.mts +4 -4
- package/dist/inbound.d.ts +4 -4
- package/dist/inbound.mjs +1 -1
- package/dist/index.d.mts +7 -167
- package/dist/index.d.ts +7 -167
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/createAgentGenerate.mjs +3 -0
- package/dist/packem_chunks/otlpTelemetry.mjs +1 -0
- package/dist/packem_chunks/resolve-run.mjs +1 -0
- package/dist/packem_chunks/runAgentLoop.mjs +3 -0
- package/dist/packem_shared/SecretUnavailableError-DOy2M4Ak.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-CdvG2L-D.mjs +1 -0
- package/dist/packem_shared/{adaptMcpResult-DOud9k_Q.mjs → adaptMcpResult-CA-3ovJd.mjs} +1 -1
- package/dist/packem_shared/agentAsTool-BF-7Dnzy.mjs +1 -0
- package/dist/packem_shared/app-call-options-BE0CQ6Qg.mjs +1 -0
- package/dist/packem_shared/codeTool-Cn8TuNjk.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs +1 -0
- package/dist/packem_shared/compileAgentWorkflow-yZB8fbYc.mjs +1 -0
- package/dist/packem_shared/component-shared--SPcu0Iw.mjs +1 -0
- package/dist/packem_shared/createAgentContext-C8k1y2Ot.mjs +1 -0
- package/dist/packem_shared/defineAgent-6Ih7L9E9.mjs +3 -0
- package/dist/packem_shared/functionTool-Cf433Hdo.mjs +1 -0
- package/dist/packem_shared/inbound-shard-A7S7dnf_.mjs +1 -0
- package/dist/packem_shared/{jsCodeTool-Bh4jaeoy.mjs → jsCodeTool-BJB3Fpm2.mjs} +1 -1
- package/dist/packem_shared/jsonSchema-fhoaBWpN.mjs +1 -0
- package/dist/packem_shared/memory-JI0lUu84.mjs +1 -0
- package/dist/packem_shared/{normalizeEntityName-Rr5OQxhc.mjs → normalizeEntityName-BiUH5B5W.mjs} +1 -1
- package/dist/packem_shared/run-shard-B7iMrAI0.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-DPa5UZ45.mjs +1 -0
- package/dist/packem_shared/{types.d-vAmttAsE.d.mts → types.d-Bzy_Qah6.d.mts} +81 -2
- package/dist/packem_shared/{types.d-vAmttAsE.d.ts → types.d-Bzy_Qah6.d.ts} +81 -2
- package/dist/packem_shared/voice-turn-B9omvXoR.mjs +1 -0
- package/dist/packem_shared/webSearchTool-BzXW0R4r.mjs +1 -0
- package/dist/packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs +1 -0
- 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/dist/telemetry/index.mjs +1 -1
- package/package.json +5 -1
- package/dist/packem_shared/SecretUnavailableError-D8u6pPM6.mjs +0 -1
- package/dist/packem_shared/VoiceSessionDO-D4dEV12P.mjs +0 -1
- package/dist/packem_shared/agent-loop-C11GY0Yw.mjs +0 -3
- package/dist/packem_shared/agentAsTool-ifwGRMR6.mjs +0 -1
- package/dist/packem_shared/codeTool-BZkKDqsZ.mjs +0 -1
- package/dist/packem_shared/collectAgenticMemoryTools-Dxs7mpo6.mjs +0 -1
- package/dist/packem_shared/compileAgentWorkflow-DDQ-_8S0.mjs +0 -1
- package/dist/packem_shared/component-shared-DdXFbng-.mjs +0 -1
- package/dist/packem_shared/createAgentContext-CjdW-jip.mjs +0 -1
- package/dist/packem_shared/createAgentGenerate-CTkL_e0Z.mjs +0 -3
- package/dist/packem_shared/defineAgent-BsDM3vh8.mjs +0 -3
- package/dist/packem_shared/functionTool-C95ns65V.mjs +0 -1
- package/dist/packem_shared/json-schema-CHVg-SsJ.mjs +0 -1
- package/dist/packem_shared/otlpTelemetry-CiSI9HE_.mjs +0 -1
- package/dist/packem_shared/runAgentLoop-8K0vPhGY.mjs +0 -1
- package/dist/packem_shared/runVoiceTurn-C4BAG61O.mjs +0 -1
- package/dist/packem_shared/voice-turn-BjkorohD.mjs +0 -1
- package/dist/packem_shared/webSearchTool-DUubGqov.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as w}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{LunoraError as o}from"@lunora/errors";import{h as f,B as g}from"./branch-marker-boZ00zmk.mjs";import{w as E}from"./run-shard-B7iMrAI0.mjs";import{r as N}from"./workflow-binding-Dm9hBzx_.mjs";import{toFunctionReference as R,DEFAULT_AGENT_FUNCTION_PATHS as T}from"./AGENT_MODULE-CYBmT9SD.mjs";const B=(r,c,i={})=>{const{dispatch:u,exports:d,shardKey:l}=i,s={},m=R(T.patchThread),p=()=>u??w({env:r,label:"@lunora/agent"});for(const e of c){const n=()=>{const t=N(r,d,e.className,["create","get"]);if(t===void 0)throw new o("INTERNAL",`@lunora/agent: no "${e.className}" on ctx.exports or env for agent "${e.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return t};s[e.exportName]={cancel:async t=>{await(await n().get(t)).terminate();try{await p()(m,{instanceId:t,status:"cancelled"})}catch{}},publicRun:e.publicRun===!0,run:async(t,a)=>{if(f(t))throw new o("BAD_REQUEST",`@lunora/agent: run input ${g}`);return{id:(await n().create({...a?.id===void 0?{}:{id:a.id},params:E(t,l)})).id}},sendEvent:async(t,a)=>{await(await n().get(t)).sendEvent(a)},status:async t=>(await n().get(t)).status()}}return s};export{B as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as p}from"./agentAsTool-BF-7Dnzy.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
|
+
|
|
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 @@
|
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{a as c}from"./app-call-options-BE0CQ6Qg.mjs";import{AGENT_MODULE as u,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.mjs";const f=(t,e)=>{if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(e.inputSchema===void 0)throw new r("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const o=m(t),i=o.__lunoraRef.startsWith(`${u}:`);return{description:e.description,execute:(a,n)=>n.run(o,{...a,idempotencyKey:n.idempotencyKey},i?void 0:c(n.shardKey)),inputSchema:e.inputSchema,isLunoraAgentTool:!0}};export{f as functionTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as e}from"@lunora/errors";const i=async(n,o,t)=>{if(n===void 0)return;const r=await n(o);if(r!==void 0){if(typeof r!="string"||r.length===0)throw new e("INTERNAL",`@lunora/agent: \`${t}\` must return a non-empty shard key or undefined`);return r}};export{i as r};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import y from"./jsonSchema-fhoaBWpN.mjs";const u="LOADER",b="2026-04-07",S=1e3,f=100,v=2e3,g=256*1024,p=3e4,T="Run JavaScript in an isolated sandbox and get its result. Provide `code`: the body of an async function — `return` the answer. Use it for calculation, parsing and data transformation. The sandbox has no network, no bindings and no tools; `console.log` output is returned as `logs`.",h=y({additionalProperties:!1,properties:{code:{description:"The body of an async function. `return` the result; it must be JSON-serializable.",type:"string"}},required:["code"],type:"object"}),w=e=>`const logs = [];
|
|
2
2
|
const format = (value) => { if (typeof value === "string") return value; try { return JSON.stringify(value); } catch { return String(value); } };
|
|
3
3
|
const record = (...values) => { if (logs.length < ${String(f)}) logs.push(values.map(format).join(" ")); };
|
|
4
4
|
const sandboxConsole = { debug: record, error: record, info: record, log: record, warn: record };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=Symbol.for("vercel.ai.schema"),n=(t,{validate:o}={})=>{let e=t;return{[r]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:o}};export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",o=e=>e.memorySources?e.memorySources:e.memory&&s(e.memory)?[{key:"default",...e.memory}]:[],i=e=>o(e).find(r=>r.kind==="graph"),c=e=>o(e).find(r=>r.kind==="episodic"),d=(e,r)=>r==="default"?e:`${e}:${r}`;export{c as a,i as f,s as i,d as m,o as r};
|
package/dist/packem_shared/{normalizeEntityName-Rr5OQxhc.mjs → normalizeEntityName-BiUH5B5W.mjs}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{defineTable as A,initLunora as q}from"@lunora/server";import{v as e}from"@lunora/values";import{A as _,
|
|
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
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=(t,r)=>{const e={...t};return delete e.shardKey,r!==void 0&&(e.shardKey=r),e};export{a as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-B9omvXoR.mjs";import"../packem_chunks/runAgentLoop.mjs";import"./buildModelMessages-DVQdQ7_1.mjs";import"./AGENT_MODULE-CYBmT9SD.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,c as toByteIterable};
|
|
@@ -16,6 +16,13 @@ interface AgentFunctionReference {
|
|
|
16
16
|
* @experimental
|
|
17
17
|
*/
|
|
18
18
|
interface AgentRunOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Route the call to this shard instead of the default one. Pass
|
|
21
|
+
* {@link AgentToolContext.shardKey} when the target reads `.shardBy(...)` tables —
|
|
22
|
+
* `functionTool` does — and leave it unset for the agent's own `agents:*`
|
|
23
|
+
* functions, whose threads, state and secrets live on the default shard.
|
|
24
|
+
*/
|
|
25
|
+
shardKey?: string;
|
|
19
26
|
/**
|
|
20
27
|
* Abort the dispatch after this many ms, overriding the runner's 30s
|
|
21
28
|
* default (`DEFAULT_DISPATCH_TIMEOUT_MS`).
|
|
@@ -129,7 +136,10 @@ interface AgentToolContext {
|
|
|
129
136
|
* {@link AgentToolContext.toolCallId}. `data` must be JSON-serializable.
|
|
130
137
|
*/
|
|
131
138
|
reportProgress: (data: unknown) => void;
|
|
132
|
-
/**
|
|
139
|
+
/**
|
|
140
|
+
* Dispatch a Lunora function (the workflow `ctx.run`). Calls go to the default
|
|
141
|
+
* shard unless they pass {@link AgentRunOptions.shardKey}.
|
|
142
|
+
*/
|
|
133
143
|
run: AgentRunFunction;
|
|
134
144
|
/**
|
|
135
145
|
* Replace the thread's synced state — dispatches the internal
|
|
@@ -153,6 +163,12 @@ interface AgentToolContext {
|
|
|
153
163
|
* skip the write when it is already present.
|
|
154
164
|
*/
|
|
155
165
|
setState: (state: Record<string, unknown>) => Promise<void>;
|
|
166
|
+
/**
|
|
167
|
+
* The shard the run was started on ({@link AgentRunInput.shardKey}); `undefined`
|
|
168
|
+
* for the default shard. Pass it as {@link AgentRunOptions.shardKey} to reach the
|
|
169
|
+
* tenant's `.shardBy(...)` data from a hand-written tool.
|
|
170
|
+
*/
|
|
171
|
+
shardKey?: string;
|
|
156
172
|
/**
|
|
157
173
|
* The durable-step handle (`step.do`/`waitForEvent`). ALWAYS present:
|
|
158
174
|
* `agent-loop.ts` threads it into every tool's context unconditionally, and
|
|
@@ -630,6 +646,53 @@ interface AgentEmailRun {
|
|
|
630
646
|
* @experimental
|
|
631
647
|
*/
|
|
632
648
|
type AgentEmailMapper = (email: InboundEmail) => AgentEmailRun | null | Promise<AgentEmailRun | null | undefined> | undefined;
|
|
649
|
+
/**
|
|
650
|
+
* Pick the shard an inbound-triggered run's tools use: the app maps a verified identity
|
|
651
|
+
* to a tenant shard. Return `undefined` for the default shard.
|
|
652
|
+
*
|
|
653
|
+
* This is the only way an inbound run gets a shard. A `shardKey` in the mapped run is
|
|
654
|
+
* dropped, because the mapper's output is built from attacker-written content. The hook
|
|
655
|
+
* runs after the sender or signature gate and after the mapper claimed the message, and
|
|
656
|
+
* it is handed only what the platform verified ({@link AgentEmailShardInput},
|
|
657
|
+
* {@link AgentChannelShardInput}). Returning a shard is an authorization decision, since
|
|
658
|
+
* the run's tools dispatch past `authorizeShard`: look the identity up in a table you
|
|
659
|
+
* trust. A throw fails the delivery rather than falling back to the default shard.
|
|
660
|
+
* @experimental
|
|
661
|
+
*/
|
|
662
|
+
type AgentInboundShardResolver<Input> = (input: Input) => Promise<string | undefined> | string | undefined;
|
|
663
|
+
/**
|
|
664
|
+
* What `resolveEmailShard` gets.
|
|
665
|
+
* @experimental
|
|
666
|
+
*/
|
|
667
|
+
interface AgentEmailShardInput {
|
|
668
|
+
/**
|
|
669
|
+
* The parsed message, for context only. Its headers are sender-written: `email.to`
|
|
670
|
+
* is the `To:` header, which any sender can set to another tenant's address, and
|
|
671
|
+
* `email.from` is only as good as the authentication verdicts. Never derive the
|
|
672
|
+
* shard from it.
|
|
673
|
+
*/
|
|
674
|
+
email: InboundEmail;
|
|
675
|
+
/**
|
|
676
|
+
* The SMTP envelope recipient Cloudflare Email Routing delivered this message to.
|
|
677
|
+
* Routing only delivers to addresses you configured, so this is the field to map
|
|
678
|
+
* to a tenant.
|
|
679
|
+
*/
|
|
680
|
+
envelopeTo: string;
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* What `onInbound.resolveShard` gets: the channel and the workspace the signed payload
|
|
684
|
+
* belongs to, never the event's message content.
|
|
685
|
+
* @experimental
|
|
686
|
+
*/
|
|
687
|
+
interface AgentChannelShardInput {
|
|
688
|
+
channel: AgentInboundChannelKind;
|
|
689
|
+
/**
|
|
690
|
+
* The provider-set tenant id from the signature-verified body: Slack `team_id`,
|
|
691
|
+
* GitHub `installation.id`, Discord `guild_id`. `undefined` when the payload carries
|
|
692
|
+
* none (a DM interaction, a GitHub event outside an app installation).
|
|
693
|
+
*/
|
|
694
|
+
workspaceId: string | undefined;
|
|
695
|
+
}
|
|
633
696
|
/** The inbound webhook channels an agent can be triggered from — see `@lunora/agent/channels`. */
|
|
634
697
|
type AgentInboundChannelKind = "discord" | "github" | "slack";
|
|
635
698
|
/** The run-input an inbound-channel mapper returns — the same shape as {@link AgentEmailRun}. */
|
|
@@ -668,6 +731,8 @@ interface AgentInboundChannel {
|
|
|
668
731
|
channel: AgentInboundChannelKind;
|
|
669
732
|
/** Map a verified event to a run (or `null` to decline). */
|
|
670
733
|
map: AgentChannelMapper;
|
|
734
|
+
/** The shard a claimed event's run uses — see {@link AgentInboundShardResolver}. Default shard when absent. */
|
|
735
|
+
resolveShard?: AgentInboundShardResolver<AgentChannelShardInput>;
|
|
671
736
|
/**
|
|
672
737
|
* The verification credential, from `env`: an env-var NAME (string) or an
|
|
673
738
|
* `(env) => value` resolver. Slack → signing secret; GitHub → webhook secret;
|
|
@@ -823,6 +888,12 @@ interface AgentConfig {
|
|
|
823
888
|
* unknown-tool-name recovery as the only repair path.
|
|
824
889
|
*/
|
|
825
890
|
repairToolCall?: ToolCallRepairFunction<ToolSet>;
|
|
891
|
+
/**
|
|
892
|
+
* The shard an `onEmail` run's tools use — see {@link AgentInboundShardResolver}. Map
|
|
893
|
+
* `envelopeTo`, the routed recipient; the parsed headers are sender-written. Default
|
|
894
|
+
* shard when absent.
|
|
895
|
+
*/
|
|
896
|
+
resolveEmailShard?: AgentInboundShardResolver<AgentEmailShardInput>;
|
|
826
897
|
/**
|
|
827
898
|
* Reusable {@link SkillDefinition}s to compose in — each contributes an
|
|
828
899
|
* instruction fragment, tools (merged into the flat namespace; collisions
|
|
@@ -1016,6 +1087,14 @@ interface AgentRunInput {
|
|
|
1016
1087
|
owner?: string;
|
|
1017
1088
|
/** Where a triggered run sends its answer — see {@link AgentReplyRef}. */
|
|
1018
1089
|
replyRef?: AgentReplyRef;
|
|
1090
|
+
/**
|
|
1091
|
+
* The shard whose app data the run's tools read and write. Set only by the boundary
|
|
1092
|
+
* that starts the run, from a source it trusts: `ctx.agents.<name>.run` uses the
|
|
1093
|
+
* shard of the mutation or action that calls it, a scheduled run the scheduling
|
|
1094
|
+
* shard, an inbound run the app's `resolveEmailShard` / `resolveShard` hook. A
|
|
1095
|
+
* value in the input is always overwritten, since the input may be a client's.
|
|
1096
|
+
*/
|
|
1097
|
+
shardKey?: string;
|
|
1019
1098
|
/** The thread key — reuse to continue a conversation. */
|
|
1020
1099
|
threadKey: string;
|
|
1021
1100
|
/** Optional thread title, set on first creation. */
|
|
@@ -1433,4 +1512,4 @@ interface AgentHandle {
|
|
|
1433
1512
|
/** Read a run's workflow status by instance id. */
|
|
1434
1513
|
status: (id: string) => Promise<unknown>;
|
|
1435
1514
|
}
|
|
1436
|
-
export {
|
|
1515
|
+
export { AgentToolCall as $, AgentDefinition as A, AgentEmailRun as B, AgentEmailShardInput as C, AgentGenerateOptions as D, AgentGenerateResult as E, AgentHandle as F, AgentInboundShardResolver as G, AgentInstructionsContext as H, InboundChannelEvent as I, AgentLiveEvent as J, AgentMemoryOptions as K, AgentMemorySource as L, AgentMessageStatus as M, AgentOnReply as N, AgentOnStepFinish as O, AgentPrepareStep as P, AgentPrepareStepInput as Q, AgentPrepareStepResult as R, SkillMarkdownExtras as S, AgentProgressEvent as T, AgentReplyInfo as U, AgentRunHandle as V, AgentRunOptions as W, AgentStepFinishInfo as X, AgentStepInfo as Y, AgentThreadStatus as Z, AgentTokenDelta as _, AgentReplyRef as a, AgentToolConfig as a0, AgentUsage as a1, AgentVoiceConfig as a2, AgentWorkflowBindingLike as a3, AgentWorkflowInstanceLike as a4, EnsureThreadOutcome as a5, SkillConfig as a6, SkillDefinition as b, AgentToolDefinition as c, AgentToolContext as d, AgentCompact as e, AgentEpisodeExtract as f, AgentGraphExtract as g, AgentGenerate as h, AgentTokenSink as i, AgentRunInput as j, AgentFunctionPaths as k, AgentRunFunction as l, AgentStepLike as m, AgentStreamGenerate as n, AgentRunResult as o, AgentMessageRow as p, AgentConfig as q, AnyAgentTool as r, AgentAsToolOptions as s, AgentSubToolInput as t, AgentModelInput as u, AgentFunctionReference as v, AgentApprovalContext as w, AgentBindingSpec as x, AgentChannelShardInput as y, AgentEmailMapper as z };
|
|
@@ -16,6 +16,13 @@ interface AgentFunctionReference {
|
|
|
16
16
|
* @experimental
|
|
17
17
|
*/
|
|
18
18
|
interface AgentRunOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Route the call to this shard instead of the default one. Pass
|
|
21
|
+
* {@link AgentToolContext.shardKey} when the target reads `.shardBy(...)` tables —
|
|
22
|
+
* `functionTool` does — and leave it unset for the agent's own `agents:*`
|
|
23
|
+
* functions, whose threads, state and secrets live on the default shard.
|
|
24
|
+
*/
|
|
25
|
+
shardKey?: string;
|
|
19
26
|
/**
|
|
20
27
|
* Abort the dispatch after this many ms, overriding the runner's 30s
|
|
21
28
|
* default (`DEFAULT_DISPATCH_TIMEOUT_MS`).
|
|
@@ -129,7 +136,10 @@ interface AgentToolContext {
|
|
|
129
136
|
* {@link AgentToolContext.toolCallId}. `data` must be JSON-serializable.
|
|
130
137
|
*/
|
|
131
138
|
reportProgress: (data: unknown) => void;
|
|
132
|
-
/**
|
|
139
|
+
/**
|
|
140
|
+
* Dispatch a Lunora function (the workflow `ctx.run`). Calls go to the default
|
|
141
|
+
* shard unless they pass {@link AgentRunOptions.shardKey}.
|
|
142
|
+
*/
|
|
133
143
|
run: AgentRunFunction;
|
|
134
144
|
/**
|
|
135
145
|
* Replace the thread's synced state — dispatches the internal
|
|
@@ -153,6 +163,12 @@ interface AgentToolContext {
|
|
|
153
163
|
* skip the write when it is already present.
|
|
154
164
|
*/
|
|
155
165
|
setState: (state: Record<string, unknown>) => Promise<void>;
|
|
166
|
+
/**
|
|
167
|
+
* The shard the run was started on ({@link AgentRunInput.shardKey}); `undefined`
|
|
168
|
+
* for the default shard. Pass it as {@link AgentRunOptions.shardKey} to reach the
|
|
169
|
+
* tenant's `.shardBy(...)` data from a hand-written tool.
|
|
170
|
+
*/
|
|
171
|
+
shardKey?: string;
|
|
156
172
|
/**
|
|
157
173
|
* The durable-step handle (`step.do`/`waitForEvent`). ALWAYS present:
|
|
158
174
|
* `agent-loop.ts` threads it into every tool's context unconditionally, and
|
|
@@ -630,6 +646,53 @@ interface AgentEmailRun {
|
|
|
630
646
|
* @experimental
|
|
631
647
|
*/
|
|
632
648
|
type AgentEmailMapper = (email: InboundEmail) => AgentEmailRun | null | Promise<AgentEmailRun | null | undefined> | undefined;
|
|
649
|
+
/**
|
|
650
|
+
* Pick the shard an inbound-triggered run's tools use: the app maps a verified identity
|
|
651
|
+
* to a tenant shard. Return `undefined` for the default shard.
|
|
652
|
+
*
|
|
653
|
+
* This is the only way an inbound run gets a shard. A `shardKey` in the mapped run is
|
|
654
|
+
* dropped, because the mapper's output is built from attacker-written content. The hook
|
|
655
|
+
* runs after the sender or signature gate and after the mapper claimed the message, and
|
|
656
|
+
* it is handed only what the platform verified ({@link AgentEmailShardInput},
|
|
657
|
+
* {@link AgentChannelShardInput}). Returning a shard is an authorization decision, since
|
|
658
|
+
* the run's tools dispatch past `authorizeShard`: look the identity up in a table you
|
|
659
|
+
* trust. A throw fails the delivery rather than falling back to the default shard.
|
|
660
|
+
* @experimental
|
|
661
|
+
*/
|
|
662
|
+
type AgentInboundShardResolver<Input> = (input: Input) => Promise<string | undefined> | string | undefined;
|
|
663
|
+
/**
|
|
664
|
+
* What `resolveEmailShard` gets.
|
|
665
|
+
* @experimental
|
|
666
|
+
*/
|
|
667
|
+
interface AgentEmailShardInput {
|
|
668
|
+
/**
|
|
669
|
+
* The parsed message, for context only. Its headers are sender-written: `email.to`
|
|
670
|
+
* is the `To:` header, which any sender can set to another tenant's address, and
|
|
671
|
+
* `email.from` is only as good as the authentication verdicts. Never derive the
|
|
672
|
+
* shard from it.
|
|
673
|
+
*/
|
|
674
|
+
email: InboundEmail;
|
|
675
|
+
/**
|
|
676
|
+
* The SMTP envelope recipient Cloudflare Email Routing delivered this message to.
|
|
677
|
+
* Routing only delivers to addresses you configured, so this is the field to map
|
|
678
|
+
* to a tenant.
|
|
679
|
+
*/
|
|
680
|
+
envelopeTo: string;
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* What `onInbound.resolveShard` gets: the channel and the workspace the signed payload
|
|
684
|
+
* belongs to, never the event's message content.
|
|
685
|
+
* @experimental
|
|
686
|
+
*/
|
|
687
|
+
interface AgentChannelShardInput {
|
|
688
|
+
channel: AgentInboundChannelKind;
|
|
689
|
+
/**
|
|
690
|
+
* The provider-set tenant id from the signature-verified body: Slack `team_id`,
|
|
691
|
+
* GitHub `installation.id`, Discord `guild_id`. `undefined` when the payload carries
|
|
692
|
+
* none (a DM interaction, a GitHub event outside an app installation).
|
|
693
|
+
*/
|
|
694
|
+
workspaceId: string | undefined;
|
|
695
|
+
}
|
|
633
696
|
/** The inbound webhook channels an agent can be triggered from — see `@lunora/agent/channels`. */
|
|
634
697
|
type AgentInboundChannelKind = "discord" | "github" | "slack";
|
|
635
698
|
/** The run-input an inbound-channel mapper returns — the same shape as {@link AgentEmailRun}. */
|
|
@@ -668,6 +731,8 @@ interface AgentInboundChannel {
|
|
|
668
731
|
channel: AgentInboundChannelKind;
|
|
669
732
|
/** Map a verified event to a run (or `null` to decline). */
|
|
670
733
|
map: AgentChannelMapper;
|
|
734
|
+
/** The shard a claimed event's run uses — see {@link AgentInboundShardResolver}. Default shard when absent. */
|
|
735
|
+
resolveShard?: AgentInboundShardResolver<AgentChannelShardInput>;
|
|
671
736
|
/**
|
|
672
737
|
* The verification credential, from `env`: an env-var NAME (string) or an
|
|
673
738
|
* `(env) => value` resolver. Slack → signing secret; GitHub → webhook secret;
|
|
@@ -823,6 +888,12 @@ interface AgentConfig {
|
|
|
823
888
|
* unknown-tool-name recovery as the only repair path.
|
|
824
889
|
*/
|
|
825
890
|
repairToolCall?: ToolCallRepairFunction<ToolSet>;
|
|
891
|
+
/**
|
|
892
|
+
* The shard an `onEmail` run's tools use — see {@link AgentInboundShardResolver}. Map
|
|
893
|
+
* `envelopeTo`, the routed recipient; the parsed headers are sender-written. Default
|
|
894
|
+
* shard when absent.
|
|
895
|
+
*/
|
|
896
|
+
resolveEmailShard?: AgentInboundShardResolver<AgentEmailShardInput>;
|
|
826
897
|
/**
|
|
827
898
|
* Reusable {@link SkillDefinition}s to compose in — each contributes an
|
|
828
899
|
* instruction fragment, tools (merged into the flat namespace; collisions
|
|
@@ -1016,6 +1087,14 @@ interface AgentRunInput {
|
|
|
1016
1087
|
owner?: string;
|
|
1017
1088
|
/** Where a triggered run sends its answer — see {@link AgentReplyRef}. */
|
|
1018
1089
|
replyRef?: AgentReplyRef;
|
|
1090
|
+
/**
|
|
1091
|
+
* The shard whose app data the run's tools read and write. Set only by the boundary
|
|
1092
|
+
* that starts the run, from a source it trusts: `ctx.agents.<name>.run` uses the
|
|
1093
|
+
* shard of the mutation or action that calls it, a scheduled run the scheduling
|
|
1094
|
+
* shard, an inbound run the app's `resolveEmailShard` / `resolveShard` hook. A
|
|
1095
|
+
* value in the input is always overwritten, since the input may be a client's.
|
|
1096
|
+
*/
|
|
1097
|
+
shardKey?: string;
|
|
1019
1098
|
/** The thread key — reuse to continue a conversation. */
|
|
1020
1099
|
threadKey: string;
|
|
1021
1100
|
/** Optional thread title, set on first creation. */
|
|
@@ -1433,4 +1512,4 @@ interface AgentHandle {
|
|
|
1433
1512
|
/** Read a run's workflow status by instance id. */
|
|
1434
1513
|
status: (id: string) => Promise<unknown>;
|
|
1435
1514
|
}
|
|
1436
|
-
export {
|
|
1515
|
+
export { AgentToolCall as $, AgentDefinition as A, AgentEmailRun as B, AgentEmailShardInput as C, AgentGenerateOptions as D, AgentGenerateResult as E, AgentHandle as F, AgentInboundShardResolver as G, AgentInstructionsContext as H, InboundChannelEvent as I, AgentLiveEvent as J, AgentMemoryOptions as K, AgentMemorySource as L, AgentMessageStatus as M, AgentOnReply as N, AgentOnStepFinish as O, AgentPrepareStep as P, AgentPrepareStepInput as Q, AgentPrepareStepResult as R, SkillMarkdownExtras as S, AgentProgressEvent as T, AgentReplyInfo as U, AgentRunHandle as V, AgentRunOptions as W, AgentStepFinishInfo as X, AgentStepInfo as Y, AgentThreadStatus as Z, AgentTokenDelta as _, AgentReplyRef as a, AgentToolConfig as a0, AgentUsage as a1, AgentVoiceConfig as a2, AgentWorkflowBindingLike as a3, AgentWorkflowInstanceLike as a4, EnsureThreadOutcome as a5, SkillConfig as a6, SkillDefinition as b, AgentToolDefinition as c, AgentToolContext as d, AgentCompact as e, AgentEpisodeExtract as f, AgentGraphExtract as g, AgentGenerate as h, AgentTokenSink as i, AgentRunInput as j, AgentFunctionPaths as k, AgentRunFunction as l, AgentStepLike as m, AgentStreamGenerate as n, AgentRunResult as o, AgentMessageRow as p, AgentConfig as q, AnyAgentTool as r, AgentAsToolOptions as s, AgentSubToolInput as t, AgentModelInput as u, AgentFunctionReference as v, AgentApprovalContext as w, AgentBindingSpec as x, AgentChannelShardInput as y, AgentEmailMapper as z };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{compactHistory as Y}from"../packem_chunks/runAgentLoop.mjs";import{buildModelMessages as Z}from"./buildModelMessages-DVQdQ7_1.mjs";import{toFunctionReference as A}from"./AGENT_MODULE-CYBmT9SD.mjs";const ut=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},C=t=>{const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.codePointAt(r)??0;return n},F=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),n=e+"=".repeat((4-e.length%4)%4);return C(n)},H=new TextDecoder;new TextEncoder;const M="=",tt=t=>{if(t)try{const e=t[0]==="{"?t:H.decode(F(t)),n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},yt=t=>{if(t){if(!t.startsWith(M))return t;try{return H.decode(F(t.slice(M.length)))}catch{return}}},ft=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},lt=t=>typeof t=="number"&&Date.now()>=t,pt=t=>{try{t.send(JSON.stringify({code:"TOKEN_EXPIRED",error:{code:"TOKEN_EXPIRED",message:"authentication token expired"},message:"authentication token expired",type:"error"})),t.close?.(4001,"token_expired")}catch{}},et=16e3,nt=1,rt=16,P=/[.!?]\s/u,st=/\s/u,at=async function*(t){if(t instanceof Uint8Array){yield t;return}if(t instanceof ReadableStream){const e=t.getReader();try{for(;;){const{done:n,value:r}=await e.read();if(n)break;yield r}}finally{e.releaseLock()}return}yield*t},ht=(t,e=et,n=nt,r=rt)=>{const a=n*r/8,p=e*a,m=new ArrayBuffer(44+t.byteLength),s=new DataView(m),u=(y,b)=>{for(let d=0;d<b.length;d+=1)s.setUint8(y+d,b.codePointAt(d)??0)};u(0,"RIFF"),s.setUint32(4,36+t.byteLength,!0),u(8,"WAVE"),u(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,e,!0),s.setUint32(28,p,!0),s.setUint16(32,a,!0),s.setUint16(34,r,!0),u(36,"data"),s.setUint32(40,t.byteLength,!0);const i=new Uint8Array(m);return i.set(t,44),i},it=t=>{const e=[];let n=t,r=P.exec(n);for(;r;){let a=r.index+1;for(;a<n.length&&st.test(n[a]??"");)a+=1;const p=n.slice(0,a).trim();p.length>0&&e.push(p),n=n.slice(a),r=P.exec(n)}return{rest:n,sentences:e}},gt=async t=>{const{agent:e,compact:n,connectionId:r,env:a,exportName:p,owner:m,paths:s,pcm:u,run:i,send:y,sendAudio:b,signal:d,streamGenerate:L,synthesize:B,text:O,threadKey:o,transcribe:$,turn:U,waitForDrain:K}=t;let _=!1,v=!1;const j=()=>v,h=()=>d.aborted||_,I=A(s.appendMessage),W=A(s.ensureThread),V=A(s.listMessages),x=A(s.patchThread);await i(W,{agent:p,key:o,...e.initialState===void 0?{}:{initialState:e.initialState},...m===void 0?{}:{owner:m}});try{const f=(O??(u?await $(u):"")).trim();if(f.length===0)return await i(x,{key:o,status:"idle"}),{assistantText:"",interrupted:!1,userText:""};y({text:f,type:"user_transcript"}),await i(I,{content:f,messageKey:`voice:${r}:${String(U)}:user`,role:"user",threadKey:o}),await i(x,{key:o,status:"running"});const R=typeof e.instructions=="function"?e.instructions({env:a,input:f,threadKey:o}):e.instructions,X=await i(V,{key:o}),{history:J,summary:N}=await Y({agent:e,compact:n,env:a},X),q=Z({history:J,...R===void 0?{}:{instructions:R},...N===void 0?{}:{summary:N}});let g="",E="",k=Promise.resolve();const z=async c=>{if(h()||c.length===0)return;let w=!1;try{for await(const l of at(await B(c,d))){if(h()||(await K?.(),h()))break;b(l),w=!0}}catch(l){y({message:l instanceof Error?l.message:String(l),type:"error"})}w&&(E=E.length>0?`${E} ${c}`:c)},D=c=>{k=k.then(async()=>z(c))},G=await L({messages:q,signal:d},c=>{if(h())return;v=!0,y({text:c,type:"assistant_delta"}),g+=c;const{rest:w,sentences:l}=it(g);g=w;for(const Q of l)D(Q)});!h()&&g.trim().length>0&&D(g.trim()),g="",await k;const S=h(),T=S?E:G.text;return await i(I,{content:T,messageKey:`voice:${r}:${String(U)}:assistant`,role:"assistant",threadKey:o}),await i(x,{key:o,status:"idle"}),y(S?{type:"interrupted"}:{text:T,type:"assistant_done"}),{assistantText:T,interrupted:S,userText:f}}catch(f){throw _=!0,j()&&y({type:"assistant_discarded"}),await i(x,{key:o,status:"idle"}),f}},mt=t=>tt(t),bt=t=>{if(typeof t=="object"&&t!==null&&"text"in t){const{text:e}=t;return typeof e=="string"?e:""}return""},xt=t=>{if(t instanceof Uint8Array||t instanceof ReadableStream)return t;if(t instanceof Response&&t.body)return t.body;if(typeof t=="object"&&t!==null&&"audio"in t){const{audio:e}=t;if(typeof e=="string")return C(e);if(e instanceof ReadableStream||e instanceof Uint8Array)return e}return new Uint8Array(0)};export{ft as a,pt as b,ht as c,yt as d,bt as e,xt as f,at as g,lt as i,mt as p,gt as r,ut as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{r as h}from"./agent-ai-CP87uSoZ.mjs";import u from"./jsonSchema-fhoaBWpN.mjs";const l=5,d="Search the web for current information. Returns up to a handful of results, each with a url, a title and (when the provider has one) a description. Use it for facts that may have changed after your training data, then cite the urls you relied on.",m=u({properties:{query:{description:"The search query, 1–1024 characters.",maxLength:1024,minLength:1,type:"string"}},required:["query"],type:"object"}),E=new Set(["BAD_REQUEST","INTERNAL","NOT_IMPLEMENTED"]),T=(t={})=>{const{description:a=d,limit:o=l,...n}=t;return{description:a,execute:async(s,i)=>{const r=h(i.env);if(!r)return"Web search is unavailable: this Worker has no `AI` binding. Answer from what you already know, and say that you could not search.";try{return(await r.websearch(s.query,{...n,limit:o})).items}catch(e){if(e instanceof c&&E.has(e.code))return`Web search failed: ${e.message}`;throw e}},inputSchema:m,isLunoraAgentTool:!0}};export{T as webSearchTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const p=(n,c,o)=>{const f=new Set(c.map(r=>r.className)),i=r=>{const e=r?.className;return typeof r=="object"&&typeof e=="string"&&f.has(e)};return new Proxy({},{get(r,e){const t=Reflect.get(n,e,n);if(e==="runAfter"||e==="runAt"){if(typeof t!="function")return t;const u=t;return async(y,s,g,a)=>{const l=i(s)?{...a,shardKey:a?.shardKey??o}:a;return Reflect.apply(u,n,[y,s,g,l])}}return typeof t=="function"?t.bind(n):t},has(r,e){return Reflect.has(n,e)},ownKeys(){return Reflect.ownKeys(n)},getOwnPropertyDescriptor(r,e){const t=Reflect.getOwnPropertyDescriptor(n,e);return t===void 0?void 0:{...t,configurable:!0}}})};export{p as default};
|
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-Bzy_Qah6.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-Bzy_Qah6.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
|
|
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"]),S='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`.',y='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??S,execute:async(o,n)=>{const r=f(o);if(r!==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=r===void 0?{}:{bucket:t,path:`${n.threadKey}/${n.toolCallId}.${r}`,...e.root===void 0?{}:{root:e.root}},u=Object.fromEntries(Object.entries(o).filter(([l])=>!E.has(l)));return await n.run(i,{...u,...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??y,execute:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"container",name:e},{timeoutMs:c}),inputSchema:R,isLunoraAgentTool:!0,needsApproval:o}},x=(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,n)=>{const r=typeof t.root=="function"?t.root(n):t.root??"";return n.run(i,{...o,bucket:e,kind:"fs",root:r})},inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}},F=(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:(n,r)=>r.run(i,{...n,instance:r.threadKey,kind:"containerFs",name:e,root:o},{timeoutMs:c}),inputSchema:d,isLunoraAgentTool:!0,needsApproval:t.needsApproval??p}};export{L as browserTool,F as containerFsTool,k as containerTool,x as fsTool,j as jsCodeTool};
|
package/dist/skill-markdown.d.ts
CHANGED
package/dist/telemetry/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{braintrustTelemetry as o}from"../packem_shared/braintrustTelemetry-Ck09dC4G.mjs";import{combineTelemetry as m}from"../packem_shared/combineTelemetry-DgE9W9G8.mjs";import{consoleTelemetry as p}from"../packem_shared/consoleTelemetry-Cl-WQEsZ.mjs";import{otlpTelemetry as f}from"../
|
|
1
|
+
import{braintrustTelemetry as o}from"../packem_shared/braintrustTelemetry-Ck09dC4G.mjs";import{combineTelemetry as m}from"../packem_shared/combineTelemetry-DgE9W9G8.mjs";import{consoleTelemetry as p}from"../packem_shared/consoleTelemetry-Cl-WQEsZ.mjs";import{otlpTelemetry as f}from"../packem_chunks/otlpTelemetry.mjs";import{sentryTelemetry as T}from"../packem_shared/sentryTelemetry-B1BuLxxj.mjs";export{o as braintrustTelemetry,m as combineTelemetry,p as consoleTelemetry,f as otlpTelemetry,T as sentryTelemetry};
|
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.278",
|
|
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",
|
|
@@ -54,6 +54,10 @@
|
|
|
54
54
|
"types": "./dist/component.d.ts",
|
|
55
55
|
"import": "./dist/component.mjs"
|
|
56
56
|
},
|
|
57
|
+
"./core": {
|
|
58
|
+
"types": "./dist/core.d.ts",
|
|
59
|
+
"import": "./dist/core.mjs"
|
|
60
|
+
},
|
|
57
61
|
"./inbound": {
|
|
58
62
|
"types": "./dist/inbound.d.ts",
|
|
59
63
|
"import": "./dist/inbound.mjs"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{j as y}from"./json-schema-CHVg-SsJ.mjs";import{toFunctionReference as l,DEFAULT_AGENT_FUNCTION_PATHS as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const p=200,N=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,p).join("")};class g 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 T=e=>{if(typeof e.description!="string"||e.description.length===0)throw new s("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 s("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 s("INTERNAL","@lunora/agent: requestSecretTool is resolved by the loop and must never be executed")},inputSchema:y({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}}},w=(e,t)=>t instanceof Error?{...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name,stack:t.stack}:t,f=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])]},h=(e,t)=>{if(t.length===0||e===void 0||typeof e=="function"||typeof e=="symbol")return!1;let n;try{n=JSON.stringify(e,w)}catch{return!1}return f(t).some(a=>n.includes(a))},E="[redacted]",u="@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 f(t).toSorted((o,r)=>r.length-o.length))n=n.split(a).join(E);return n},m=(e,t,n=new Set)=>{if(!(e instanceof Error))return new s("INTERNAL",u);if(n.has(e))return e;n.add(e);try{e.message=c(e.message,t),typeof e.stack=="string"&&(e.stack=c(e.stack,t));const a=e;for(const o of Object.getOwnPropertyNames(e)){if(o==="message"||o==="stack")continue;const r=a[o];if(r instanceof Error){const i=m(r,t,n);i!==r&&(a[o]=i)}else h(r,t)&&(a[o]=JSON.parse(c(JSON.stringify(r),t)))}}catch{return new s("INTERNAL",u)}return e},I=async(e,t,n)=>{const a=await e.step.do(`secret:consume:${e.idempotencyKey}:${t}`,async()=>{const o=await e.run(l(d.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(i){throw m(i,o)}return h(r,o)?{leaked:!0}:{result:r}});if("unavailable"in a)throw new g;if(await e.step.do(`secret:discard:${e.idempotencyKey}:${t}`,async()=>{await e.run(l(d.discardSecret),{instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t})}),"leaked"in a)throw new s("INTERNAL","@lunora/agent: withSecret's callback returned the secret, so its result was not recorded");return a.result};export{g as SecretUnavailableError,T as requestSecretTool,N as secretLabelOf,I as withSecret};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createAi as A}from"@lunora/ai/create";import{a as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as C}from"./voice-turn-BjkorohD.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"./createAgentGenerate-CTkL_e0Z.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.mjs";const O="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",B=8*1024*1024,F=100,f=4e3,g=f*4+1024,D=4002,z=4003,W=4004,G=256*1024,S=15,X=5e3,K=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class j{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,r,s){this.state=t,this.env=e,this.agent=r,this.exportName=s,this.paths=N,this.ai=I(e)??A({env:e}),this.streamGenerate=R(r,e),this.sttModel=r.voice?.stt??O,this.ttsModel=r.voice?.tts??U,this.maxSessionTurns=r.voice?.maxTurns??F}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(t.url).searchParams.get("threadKey");if(!r)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,i=new s,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:r,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,r,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const r=t.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,r,e);return}this.bufferAudio(r.connectionId,new Uint8Array(e),t)}catch(s){this.send(t,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const r=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...r===void 0?{}:{speaker:r}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,r){if(r.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,W,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!K(s)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=s;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,D,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,r){const s=(this.bufferedBytes.get(t)??0)+e.byteLength;if(s>B){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,z,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,s)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const r=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of e)s.set(n,i),i+=n.byteLength;return s}async runTurn(t,e,r){const s=new AbortController;this.controllers.set(e.connectionId,s);try{await w({agent:this.agent,compact:L(),connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(e.connectionId)===s&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:r,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...s===void 0?{}:{owner:s}}))?.outcome!=="created")return;for await(const u of C(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}closeSocket(t,e,r){try{t.close?.(e,r)}catch{}}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let r=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>G&&r<X;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{j as default};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{usageStatus as pt}from"@lunora/ai/create";import{e as mt}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{SECRET_VALUE_MAX_TTL_MS as yt}from"@lunora/platform";import{r as Z}from"./workflow-binding-Dm9hBzx_.mjs";import{e as X,d as ft,S as Y}from"./component-shared-DdXFbng-.mjs";import{usageOfFailedTurn as ht,resolveAgentModel as wt}from"./createAgentGenerate-CTkL_e0Z.mjs";import{buildModelMessages as W}from"./buildModelMessages-DVQdQ7_1.mjs";import{agentClassName as tt}from"../naming.mjs";import{toFunctionReference as g}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as vt}from"./positive-integer-ztHqqpBk.mjs";import{SecretUnavailableError as gt,secretLabelOf as Tt}from"./SecretUnavailableError-D8u6pPM6.mjs";import{combineTelemetry as St}from"./combineTelemetry-DgE9W9G8.mjs";import{c as z}from"./tool-output-Cmk3JWMG.mjs";const $t=200,Et=e=>{const t=e.findIndex(n=>n.role!=="tool");return t===-1?[]:e.slice(t)},Rt=async e=>{let t=$t;for(;;){const n=await e(t),o=Et(n);if(o.length>0||n.length<t)return o;t*=2}},It=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",B=e=>e.memorySources?e.memorySources:e.memory&&It(e.memory)?[{key:"default",...e.memory}]:[],xt=e=>B(e).find(t=>t.kind==="graph"),Ct=e=>B(e).find(t=>t.kind==="episodic"),I=(e,t)=>t==="default"?e:`${e}:${t}`,kt=e=>{if(e===void 0||e.isEnabled===!1)return;const{integrations:t}=e;if(t===void 0)return;const n=Array.isArray(t)?t:[t];return n.length===0?void 0:St(...n)},Mt=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,n)=>{const o=kt(e);if(o===void 0)return n();const a={dynamic:!0,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-call"},s={callId:t.id,messages:[],toolCall:a,toolContext:void 0},i=Date.now();await o.onToolExecutionStart?.(s);let c;const d=()=>(c??=n(),c);try{if(o.executeTool===void 0)await d();else try{await o.executeTool({...s,execute:d,toolCallId:t.id})}catch{}const u=await d();return await o.onToolExecutionEnd?.({...s,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 o.onToolExecutionEnd?.({...s,toolExecutionMs:Date.now()-i,toolOutput:{dynamic:!0,error:u,input:t.input,toolCallId:t.id,toolName:t.name,type:"tool-error"}}),u}},Nt=8,At=e=>vt(e)?e:0,et=e=>e===void 0?"null":JSON.stringify(e),Ot=async(e,t,n)=>{try{await e({error:t instanceof Error?t.message:String(t),status:"error",...n===void 0?{}:{usage:n}})}catch(o){t instanceof Error&&t.cause===void 0&&(t.cause=o)}},_t=e=>e===void 0?[]:[e].flat(),qt=async(e,t)=>(await Promise.all(e.map(async o=>o({steps:t})))).some(Boolean),Ut=["inputTokens","outputTokens","totalTokens","cacheReadTokens","cacheWriteTokens","reasoningTokens"],j=e=>e.status??pt(e),bt=(e,t)=>e===t?e:"partial",ot=(e,t)=>{if(t===void 0)return e;if(e===void 0)return{...t,status:j(t)};const n={status:bt(j(e),j(t))};for(const o of Ut)(e[o]!==void 0||t[o]!==void 0)&&(n[o]=(e[o]??0)+(t[o]??0));return n},Dt=async(e,t,n,o,a,s)=>{const{needsApproval:i}=e;return i===void 0||i===!1?!1:n.do(o,async()=>await s()?!1:i===!0||i(t,a))},Ft="WorkflowTimeoutError",nt=e=>e instanceof Error&&e.name===Ft,J=4320*60*1e3,Pt={day:864e5,hour:36e5,minute:6e4,month:30*864e5,second:1e3,week:7*864e5,year:365*864e5},Gt=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,at=e=>{if(e===void 0)return J;if(typeof e=="number")return Math.min(e,X);const t=Gt.exec(e);return t===null?J:Math.min(Number(t[1])*Pt[t[2]],X)},Lt=async(e,t)=>{const{agent:n,deleteMessage:o,instanceId:a,patchThread:s,persist:i,step:c}=e,d=at(n.approvalTimeout);await c.do(`approval:request:${t.id}`,async()=>{await i({content:`Awaiting approval to run tool "${t.name}".`,expiresAt:Date.now()+d,messageKey:`${a}:approval:${t.id}`,role:"tool",status:"awaiting_approval",toolCallId:t.id,toolName:t.name}),await s({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(!nt(p))throw p;return{decision:"reject",note:"approval timed out"}});return await o(`${a}:approval:${t.id}`),await s({status:"running"}),u},jt={declined:"the user declined to supply it",expired:"the secret was not supplied before the timeout"},Wt=(e,t)=>`${String(e)}:${t}`,Bt=async(e,t,n,o,a)=>{const{agent:s,deleteMessage:i,instanceId:c,openSecretRef:d,patchThread:u,persist:p,run:r,settleSecretRef:l,step:m,threadKey:h}=e,T=`${c}:secret:${a}`,y=Math.min(at(s.approvalTimeout),yt-Y);await m.do(`secret:request:${a}`,async()=>{await r(d,{consumerTool:n,expiresAt:Date.now()+y,instanceId:c,callId:t.id,label:o,threadKey:h,toolCallId:a,toolName:t.name})}),await m.do(`secret:await:${a}`,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 u({ifInstanceId:c,status:"awaiting_input"})}),await m.waitForEvent(`secret:${a}`,{timeout:y+Y,type:`agent-secret:${a}`}).catch(f=>{if(!nt(f))throw f});const{status:v}=await m.do(`secret:settle:${a}`,async()=>await r(l,{instanceId:c,threadKey:h,toolCallId:a}));return await i(T),await u({ifInstanceId:c,status:"running"}),v},U="lunoraToolOutcome",Ht=e=>typeof e=="object"&&e!==null&&U in e?e[U]:{ok:e},Vt=async(e,t,n,o)=>{const{instanceId:a,persist:s}=e,i=Wt(o,t.id),c=`${a}:secret-result:${i}`,d=`tool:${t.name}:${i}`,u=Tt(t.input);if(u===void 0){await s({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 s({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 Bt(e,t,n,u,i);await s({content:p==="supplied"?JSON.stringify({secretRef:i}):`Error: tool "${t.name}" was not run: ${jt[p]}.`,messageKey:c,role:"tool",stepName:d,toolCallId:t.id,toolName:t.name})},Xt=async(e,t,n)=>{const{agent:o,approvalGrantedRef:a,depth:s,env:i,exports:c,getState:d,instanceId:u,onTokenDelta:p,owner:r,persist:l,run:m,setState:h,step:T,threadKey:y,tools:v}=e,f=`tool:${t.name}:${t.id}`,$=v[t.name],E=`${u}:tool:${t.id}`;if(!$){await l({content:`Error: unknown tool "${t.name}"`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if(t.invalid!==void 0){await l({content:`Error: invalid input for tool "${t.name}" — it was not run. ${t.invalid}`,messageKey:E,role:"tool",stepName:f,toolCallId:t.id,toolName:t.name});return}if($.secretRequest!==void 0){await Vt(e,t,$.secretRequest.consumer,n);return}const b={depth:s,env:i,exports:c,getState:d,idempotencyKey:f,instanceId:u,owner:r,reportProgress:S=>{p?.({data:S,kind:"progress",threadKey:y,toolCallId:t.id})},run:m,setState:h,step:T,threadKey:y,toolCallId:t.id},D={depth:s,env:i,getState:d,idempotencyKey:f,instanceId:u,run:m,threadKey:y,toolCallId:t.id},F=`tool:approval-gate:${t.id}`;let M,K;const P=async()=>await m(a,{key:y,toolName:t.name})===!0;if(await Dt($,t.input,T,F,D,P)){const{decision:S,note:C,scope:G}=await Lt(e,t);if(S==="reject"){const O=C===void 0?"":` Reason: ${C}`;await l({content:`Tool "${t.name}" was rejected by the user and not run.${O}`,messageKey:E,role:"tool",status:"rejected",stepName:f,toolCallId:t.id,toolName:t.name});return}M="approved",K=G}const A={...M===void 0?{}:{status:M},...K===void 0?{}:{approvalScope:K}},N=Ht(await T.do(f,async()=>{try{const S=()=>Promise.resolve($.execute(t.input,b)),C=await Kt(o.telemetry,{id:t.id,input:t.input,name:t.name},S);return{[U]:{ok:C}}}catch(S){if(mt(S)||S instanceof gt)return{[U]:{failed:S.message}};throw S}}));if("failed"in N){await l({content:z(`Error: tool "${t.name}" failed and will not be retried. ${N.failed}`),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name});return}const x=N.ok;await l({content:z(typeof x=="string"?x:et(x)),messageKey:E,role:"tool",stepName:f,...A,toolCallId:t.id,toolName:t.name})},Yt=(e,t,n)=>{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,n),toolChoice:t.toolChoice??e.toolChoice}},st=(e,t)=>{if(t===void 0||e.length<=t.maxMessages)return;const n=Math.max(1,t.keepRecent??Math.ceil(t.maxMessages/2));if(e.length<=n)return;let o=e.length-n;for(;o>0&&e[o]?.role==="tool";)o-=1;if(!(o<=0))return{older:e.slice(0,o),recent:e.slice(o)}},zt=async(e,t)=>{const{agent:n,compact:o,env:a}=e,s=st(t,n.compaction);if(s===void 0||o===void 0)return{history:t,summary:void 0};try{const i=await o({env:a,messages:W({history:s.older}),model:n.compaction?.model??n.model});return i.length>0?{history:s.recent,summary:i}:{history:t,summary:void 0}}catch{return{history:t,summary:void 0}}},Jt=e=>{if(e!==void 0)return`${String(e.maxMessages)}:${String(e.keepRecent??"")}`},Qt=async e=>{const{agent:t,compact:n,env:o,historyRef:a,instanceId:s,patchThread:i,run:c,threadKey:d}=e,u=Jt(t.compaction),p=await c(a,{configKey:u,key:d}),{messages:r,summary:l}=p,m=st(r,t.compaction);if(m===void 0||n===void 0)return{history:r,summary:l};const h=async()=>{const{fallback:v}=p;return v===void 0?{history:r,summary:l}:(await i({ifInstanceId:s,summaryRebuiltSeq:v.throughSeq}).catch(f=>{console.warn(`@lunora/agent: could not reset the summary rebuild anchor for thread "${d}"`,f)}),{history:r.filter(f=>f.seq>v.throughSeq),summary:v.summary})};let T;try{T=await n({env:o,messages:W({history:m.older,summary:l}),model:t.compaction?.model??t.model,previousSummary:l})}catch(v){return console.warn(`@lunora/agent: summarising thread "${d}" failed`,v),h()}if(T.length===0)return h();const y=m.older.at(-1)?.seq;return await i({ifInstanceId:s,summary:T,summaryConfig:u,...l===void 0?{summaryRebuiltSeq:y}:{},summaryThroughSeq:y}).catch(v=>{console.warn(`@lunora/agent: could not persist the summary checkpoint for thread "${d}"`,v)}),{history:m.recent,summary:T}},Zt=async(e,t,n)=>{const{agent:o,env:a,generate:s,instructions:i,listMessages:c,memoryContext:d,onTokenDelta:u,run:p,step:r,streamGenerate:l,threadKey:m}=e;return r.do(`llm:turn:${String(t)}`,async()=>{const{history:h,summary:T}=o.compaction!==void 0&&e.compact!==void 0?await Qt(e):await zt(e,await Rt(async f=>await p(c,{key:m,limit:f})));let y={activeTools:o.activeTools,messages:W({history:h,instructions:i,memoryContext:d,summary:T}),model:void 0,toolChoice:o.toolChoice};o.prepareStep&&(y=Yt(y,await o.prepareStep({messages:y.messages,stepNumber:t,steps:n}),a));const v={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(v,f=>{u({text:f,threadKey:m,turn:t})}):s(v)})},Q=async(e,t)=>{const{agent:n,step:o}=e;n.onStepFinish&&await o.do(`agent:step-finish:${String(t.turn)}`,async()=>(await n.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}}),H=e=>{const t=e?.context;return typeof t=="string"&&t.length>0?t:void 0},ee=e=>ft({depth:e?.depth,fanOut:e?.fanOut,maxNodes:e?.maxNodes,maxSeeds:e?.maxSeeds}),oe=async(e,t,n,o)=>{if(e.source===void 0)return;const a=g(e.source),{topK:s}=e,i=I("memory:retrieve",e.key),c=await n.do(i,async()=>o(a,{query:t,...s===void 0?{}:{topK:s}}));return H(c)},ne=async(e,t,n,o,a,s)=>{if(n===void 0)return;const i=I("memory:traverse",e.key),c=await a.do(i,async()=>s(o,{owner:n,query:t,...ee(e.graph)}));return H(c)},ae=async(e,t,n,o,a)=>{if(t===void 0)return;const s=I("memory:recall",e.key),i={owner:t,...e.episodic?.recall===void 0?{}:{limit:e.episodic.recall}},c=await o.do(s,async()=>a(n,i));return H(c)},se=async(e,t)=>e.kind==="episodic"?ae(e,t.owner,t.episodeRecall,t.step,t.run):e.kind==="graph"?ne(e,t.input,t.owner,t.graphTraverse,t.step,t.run):oe(e,t.input,t.step,t.run),re=e=>{const t=e.findIndex(n=>n.kind==="episodic");return e.filter((n,o)=>n.kind!=="episodic"||o===t)},ie=async(e,t,n,o,a,s)=>{const i=re(B(e));if(i.length===0)return;const c=g(o.graphTraverse),d=g(o.episodeRecall),u=[];for(const p of i){const r=await se(p,{episodeRecall:d,graphTraverse:c,input:t,owner:n,run:s,step:a});r!==void 0&&u.push(r)}return u.length>0?u.join(`
|
|
2
|
-
|
|
3
|
-
`):void 0},ce=async e=>{const{agent:t,env:n,extractGraph:o,finalText:a,input:s,instanceId:i,owner:c,paths:d,run:u,step:p}=e;if(o===void 0||c===void 0||a===void 0||a.length===0)return;const r=xt(t);if(r!==void 0)try{const l={assistantText:a,env:n,model:r.graph?.extractionModel??t.model,userInput:s},m=await p.do(I("memory:extract",r.key),async()=>o(l));await u(g(d.graphUpsert),{...m,messageKey:`${i}:${I("extract",r.key)}`,owner:c})}catch{}},ue=async e=>{const{agent:t,env:n,extractEpisode:o,finalText:a,input:s,instanceId:i,owner:c,paths:d,run:u,step:p,threadKey:r}=e;if(o===void 0||c===void 0||a===void 0||a.length===0)return;const l=Ct(t);if(l!==void 0)try{const m={assistantText:a,env:n,model:l.episodic?.extractionModel??t.model,userInput:s},{summary:h}=await p.do(I("memory:episode",l.key),async()=>o(m));await u(g(d.episodeUpsert),{messageKey:`${i}:${I("episode",l.key)}`,owner:c,summary:h,threadKey:r})}catch{}},de=async(e,t,n)=>{const o=Z(e.env,e.exports,tt(t),["get"]);if(o!==void 0)try{await(await o.get(n)).terminate()}catch{}},le="12 hours",pe=async(e,t,n)=>{await e.waitForEvent(`dequeue:${n}`,{timeout:le,type:`agent-dequeue:${t}:${n}`})},me=async(e,t,n)=>{const o=Z(e.env,e.exports,tt(e.exportName),["get"]);if(o===void 0)return;const a=o.get.bind(o);try{await e.step.do(`dequeue-wake:${n}`,async()=>(await(await a(n)).sendEvent({payload:{threadKey:t},type:`agent-dequeue:${t}:${n}`}),n))}catch{}},ye=async(e,t,n)=>{const{onReply:o}=e,{replyRef:a}=t.params;if(!(o===void 0||a===void 0))try{await t.step.do("agent:reply",async()=>(await o({env:t.env,replyRef:a,result:n,threadKey:t.params.threadKey}),a.channel))}catch{}},fe=async(e,t,n,o,a)=>{const{instanceId:s,persist:i}=e,c=n.usage===void 0?{}:{usage:n.usage};if(n.toolCalls.length===0){const d=n.output!==void 0&&n.text.length===0?et(n.output):n.text;return await i({content:d,messageKey:`${s}:assistant:${String(t)}`,role:"assistant"}),await Q(e,{text:n.text,toolCalls:[],turn:t,...c}),{final:{stopped:"final",text:n.text,turns:t+1,...n.output===void 0?{}:{output:n.output}}}}await i({content:n.text,messageKey:`${s}:assistant:${String(t)}`,role:"assistant",toolCalls:n.toolCalls});for(const d of n.toolCalls)await Xt(e,d,t);if(await Q(e,{text:n.text,toolCalls:n.toolCalls,turn:t,...c}),o.push(te(n)),a.length>0&&await qt(a,o))return"stopCondition"},he=async(e,t,n,o)=>{const a=[];let s,i=!1,c=0;for(let d=0;d<t;d+=1){const u=await Zt(e,d,a);o.value=ot(o.value,u.usage),c=d+1;const p=await fe(e,d,u,a,n);if(p==="stopCondition"){i=!0;break}if(p!==void 0){s=p.final;break}}return{final:s,stoppedByCondition:i,turnsRun:c}},Ke=async e=>{const{agent:t,compact:n,env:o,exportName:a,exports:s,extractEpisode:i,extractGraph:c,generate:d,instanceId:u,onTokenDelta:p,params:r,paths:l,run:m,step:h,streamGenerate:T}=e,y=t.maxTurns??Nt,v=_t(t.stopWhen),f=g(l.appendMessage),$=g(l.approvalGranted),E=g(l.openSecretRequest),V=g(l.settleSecretRequest),b=g(l.completeRun),D=g(l.ensureThread),F=g(l.listMessages),M=g(l.history),K=g(l.deleteMessage),P=g(l.patchThread),A=g(l.setState),N=g(l.state),x=async w=>{await m(f,{threadKey:r.threadKey,...w})},S=async w=>{await m(P,{key:r.threadKey,...w})},C=async w=>{await m(K,{messageKey:w,threadKey:r.threadKey})},G=async()=>{await x({content:r.input,messageKey:`${u}:user`,role:"user"})},O={dispatched:!1},_=async w=>{O.dispatched=!0;const q=await m(b,{instanceId:u,key:r.threadKey,...w});q?.dequeued!==void 0&&await me({env:o,exportName:a,exports:s,step:h},r.threadKey,q.dequeued)},rt=async()=>await m(N,{key:r.threadKey}),it=async w=>{await m(A,{key:r.threadKey,state:w})},L=await m(D,{agent:a,instanceId:u,key:r.threadKey,...t.initialState===void 0?{}:{initialState:t.initialState},...t.onConcurrentRun===void 0?{}:{onConcurrentRun:t.onConcurrentRun},...r.owner===void 0?{}:{owner:r.owner},...r.title===void 0?{}:{title:r.title}});L?.outcome==="replaced"&&await de({env:o,exports:s},a,L.priorInstanceId);const ct=await ie(t,r.input,r.owner,l,h,m),ut=typeof t.instructions=="function"?t.instructions({env:o,input:r.input,threadKey:r.threadKey}):t.instructions,dt={agent:t,approvalGrantedRef:$,openSecretRef:E,settleSecretRef:V,compact:n,depth:At(r.depth),env:o,exports:s,generate:d,getState:rt,historyRef:M,instanceId:u,instructions:ut,listMessages:F,memoryContext:ct,onTokenDelta:p,owner:r.owner,deleteMessage:C,patchThread:S,persist:x,run:m,setState:it,step:h,streamGenerate:T,threadKey:r.threadKey,tools:t.tools??{}},k={value:void 0};try{L?.outcome==="queued"&&await pe(h,r.threadKey,u),await G();const{final:w,stoppedByCondition:q,turnsRun:lt}=await he(dt,y,v,k),R=k.value===void 0?{}:{usage:k.value};return await ce({agent:t,env:o,extractGraph:c,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h}),await ue({agent:t,env:o,extractEpisode:i,finalText:w?.text,input:r.input,instanceId:u,owner:r.owner,paths:l,run:m,step:h,threadKey:r.threadKey}),w?(await ye(t,{env:o,params:r,step:h},{...w,...R}),await _({status:"idle",...R}),{...w,...R}):q?(await _({status:"idle",...R}),{stopped:"stopCondition",turns:lt,...R}):(await _({error:`agent stopped: maxTurns (${String(y)}) reached`,status:"error",...R}),{stopped:"maxTurns",turns:y,...R})}catch(w){throw O.dispatched||(k.value=ot(k.value,ht(w)),await Ot(_,w,k.value)),w}finally{await Mt(t.telemetry)}};export{at as a,ot as b,zt as c,It as i,Ke as r,st as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as I}from"@lunora/workflow";import{f as L}from"./fnv1a-BNN96GYb.mjs";import{r as S}from"./workflow-binding-Dm9hBzx_.mjs";import{j as b}from"./json-schema-CHVg-SsJ.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as $,DEFAULT_AGENT_FUNCTION_PATHS as P}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as h}from"./positive-integer-ztHqqpBk.mjs";const _=new Set(["complete","errored","terminated"]),x=600,w=3,M=500,R=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",j=t=>t!==null&&typeof t=="object"?t.output:void 0,k=async t=>{await new Promise(e=>{setTimeout(e,t)})},C=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=R(a);if(_.has(s))return{output:j(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},D=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},U=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""},V=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&&!h(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??x,o=t.pollIntervalMs??M,a=t.wait??k,s=$(P.listMessages),T=async(y,r)=>{const p=(h(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=S(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}`,g=`sub-${e}-${L(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:g,params:A});l=await i.get(d.id)}catch(d){if(!I(d))throw d;l=await i.get(g)}const{output:v,status:u}=await C(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(D(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 E=await r.run(s,{key:f});return U(E)};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{V as agentAsTool};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";import{j as y}from"./json-schema-CHVg-SsJ.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 +0,0 @@
|
|
|
1
|
-
import{j as u}from"./json-schema-CHVg-SsJ.mjs";import{toFunctionReference as d}from"./AGENT_MODULE-CYBmT9SD.mjs";const h=240,m=50,y=(t,s)=>t.length<=s?t:`${t.slice(0,s)}…`,f=t=>{if(!(t===void 0||!Number.isFinite(t)))return Math.min(m,Math.max(1,Math.trunc(t)))},g=(t,s)=>{const r=t??{},i=Array.isArray(r.chunks)?r.chunks:[],e=Array.isArray(r.sources)?r.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:y(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},S=u({additionalProperties:!1,properties:{query:{description:"Natural-language search query.",type:"string"},topK:{description:"Maximum number of hits to return.",type:"number"}},required:["query"],type:"object"}),A=u({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),b=(t,s,r)=>{const i=d(s),e=Math.max(1,t.snippetChars??h),o=t.topK;return{description:`Search long-term memory for passages relevant to a query. Returns ranked { id, sourceId, score, snippet } hits — call again with a refined query to dig deeper.${r===void 0?"":` Use \`${r}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,p)=>{const a=f(n.topK)??o,l=await p.run(i,{query:n.query,...a===void 0?{}:{topK:a}});return g(l,e)},inputSchema:S,isLunoraAgentTool:!0}},T=t=>{const s=d(t);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(r,i)=>i.run(s,{id:r.id}),inputSchema:A,isLunoraAgentTool:!0}},k=(t,s)=>{const r=[];t.memory&&r.push({key:"default",...t.memory});for(const e of s)e.knowledge&&r.push({key:e.name,...e.knowledge});const i={};for(const e of r){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,c=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=b(e,e.source,n?c:void 0),n&&(i[c]=T(e.read))}return i};export{k as collectAgenticMemoryTools,g as toSearchResults};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{defineWorkflow as i}from"@lunora/workflow";import{r as m}from"./agent-loop-C11GY0Yw.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-CTkL_e0Z.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-CYBmT9SD.mjs";import{a as T}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-CiSI9HE_.mjs";const E=(r,t,a)=>T({env:t,label:"@lunora/agent",...a===void 0?{}:{fetchImpl:a},...r===void 0?{}:{identity:{userId:r}}}),O=(r,t,a)=>{const e=t.LUNORA_OTLP_ENDPOINT;if(typeof e!="string"||e===""||r.telemetry?.isEnabled===!1)return r;const n=typeof t.LUNORA_OTLP_TOKEN=="string"?t.LUNORA_OTLP_TOKEN:void 0,o=[r.telemetry?.integrations].flat().filter(s=>s!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...o,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>i({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:u(),env:e.env,exports:e.exports,exportName:t,extractGraph:d(),extractEpisode:f(),generate:l(n,e.env),instanceId:e.event.instanceId,params:e.params,paths:a?.paths??A,run:E(e.params.owner,e.env,e.fetchImpl),step:e.step,streamGenerate:p(n,e.env)})},name:r.name??c(t)});export{I as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const _="agent",A=6048e5,o=12096e5,a=s=>({...s,visibility:"internal"}),E=s=>{const n={};for(const[e,t]of Object.entries(s))t!==void 0&&(n[e]=t);return n},T=9e5,c=6e4;export{_ as A,c as S,a,o as b,T as c,E as d,A as e};
|