@lunora/agent 1.0.0-alpha.11 → 1.0.0-alpha.110

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.
Files changed (88) hide show
  1. package/dist/channels.d.mts +3 -11
  2. package/dist/channels.d.ts +3 -11
  3. package/dist/channels.mjs +1 -1
  4. package/dist/component.d.mts +2 -0
  5. package/dist/component.d.ts +2 -0
  6. package/dist/component.mjs +2 -2
  7. package/dist/inbound.d.mts +7 -5
  8. package/dist/inbound.d.ts +7 -5
  9. package/dist/inbound.mjs +1 -1
  10. package/dist/index.d.mts +49 -8
  11. package/dist/index.d.ts +49 -8
  12. package/dist/index.mjs +1 -1
  13. package/dist/naming.mjs +1 -1
  14. package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
  15. package/dist/packem_shared/VoiceSessionDO-D238XrlM.mjs +1 -0
  16. package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
  17. package/dist/packem_shared/agent-loop-CE_Q6bk9.mjs +3 -0
  18. package/dist/packem_shared/agentAsTool-CgZb6ycK.mjs +1 -0
  19. package/dist/packem_shared/base64-5eyBfWO3.mjs +1 -0
  20. package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
  21. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  22. package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
  23. package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
  24. package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
  25. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  26. package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
  27. package/dist/packem_shared/compileAgentWorkflow-DVHi7NYD.mjs +1 -0
  28. package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
  29. package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
  30. package/dist/packem_shared/createAgentContext-BvU9LP43.mjs +1 -0
  31. package/dist/packem_shared/createAgentGenerate-BOILDUZj.mjs +3 -0
  32. package/dist/packem_shared/createDispatchRunner-BxtGxAQi-DXXP7SxZ.mjs +1 -0
  33. package/dist/packem_shared/defineAgent-KgH-gwYg.mjs +3 -0
  34. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  35. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  36. package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
  37. package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
  38. package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
  39. package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
  40. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  41. package/dist/packem_shared/runAgentLoop-Drn1NcCc.mjs +1 -0
  42. package/dist/packem_shared/runVoiceTurn-BtcmyaBo.mjs +1 -0
  43. package/dist/packem_shared/sandboxComponent-BtOkUYpY.mjs +5 -0
  44. package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
  45. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  46. package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-B8WZl1rU.d.mts} +255 -22
  47. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-B8WZl1rU.d.ts} +255 -22
  48. package/dist/packem_shared/voice-turn-BRj_it54.mjs +1 -0
  49. package/dist/reply.d.mts +40 -0
  50. package/dist/reply.d.ts +40 -0
  51. package/dist/reply.mjs +1 -0
  52. package/dist/sandbox.d.mts +14 -13
  53. package/dist/sandbox.d.ts +14 -13
  54. package/dist/sandbox.mjs +1 -1
  55. package/dist/skill-markdown.d.mts +36 -0
  56. package/dist/skill-markdown.d.ts +36 -0
  57. package/dist/skill-markdown.mjs +1 -0
  58. package/dist/telemetry/index.d.mts +152 -33
  59. package/dist/telemetry/index.d.ts +152 -33
  60. package/dist/telemetry/index.mjs +1 -1
  61. package/package.json +18 -9
  62. package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
  63. package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
  64. package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
  65. package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
  66. package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
  67. package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
  68. package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
  69. package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
  70. package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
  71. package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
  72. package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
  73. package/dist/packem_shared/compileAgentWorkflow-Dwp-xNNO.mjs +0 -1
  74. package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
  75. package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
  76. package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
  77. package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
  78. package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
  79. package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
  80. package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
  81. package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
  82. package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
  83. package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
  84. package/dist/packem_shared/otlpTelemetry-B829MdU-.mjs +0 -1
  85. package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
  86. package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
  87. package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
  88. package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{r as o,d as E,t as C,s as T,c as b}from"./common-CJSjtsfv.mjs";import{c as v}from"./in-flight-calls-GH1A_1P3.mjs";const k=(i,g)=>typeof i=="string"&&i.length>0?i:g,P=i=>{const{functionId:g,logger:m,recordInputs:p=!1,recordOutputs:y=!1}=i,n=v((e,t,s,r)=>{const l={},c=T(o(r,"usage")??o(e.result,"usage"));if(c&&(l.metrics={completion_tokens:c.outputTokens,prompt_tokens:c.inputTokens,tokens:c.totalTokens}),t||(l.error=s??"the model call failed"),y){const d=b(o(r,"content")??o(e.result,"content"));d!==void 0&&(l.output=d)}Object.keys(l).length>0&&e.span.log(l),e.finish()},e=>{e.finish()}),h=(e,t,s)=>{const r=o(e,"callId");if(typeof r!="string")return;let l=s;t instanceof Error?l=t.message:typeof t=="string"&&t.length>0&&(l=t),n.close(r,!1,l,void 0)};return{executeLanguageModelCall:e=>{const{callId:t,execute:s}=e;let r,l;const c=new Promise((a,f)=>{r=a,l=f});let d;const x=new Promise(a=>{d=a});return Promise.resolve(m.traced(async a=>{n.open(t,()=>({finish:d,result:void 0,span:a})),p&&a.log({input:o(e,"messages"),model:o(e,"modelId")});let f;try{f=await s()}catch(u){n.close(t,!1,u instanceof Error?u.message:String(u),void 0),l(u);return}const I=n.get(t);I!==void 0&&(I.result=f),r(f),await x},{name:k(g,"language_model_call"),type:"llm"})).catch(()=>{}),c},executeTool:e=>{const t=o(o(e,"toolCall"),"toolName");return m.traced(async s=>{p&&s.log({input:C(e),tool:t});const r=await e.execute();return y&&s.log({output:r}),r},{name:k(t,"execute_tool"),type:"tool"})},onAbort:e=>{h(e,o(e,"reason"),"aborted")},onEnd:e=>{n.fromLifecycle(e)},onError:e=>{m.traced(t=>{t.log({error:E(o(e,"error")??e)})},{name:"error",type:"error"}),h(e,o(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{const t=o(e,"callId");typeof t=="string"&&n.close(t,!0,void 0,e)},onStepEnd:e=>{n.fromLifecycle(e)}}};export{P as braintrustTelemetry};
@@ -0,0 +1 @@
1
+ const e="__lunoraBranch",o=n=>typeof n=="object"&&n!==null&&Object.hasOwn(n,e),r=`may not contain the reserved workflow branch-marker key ("${e}")`;export{r as B,o as h};
@@ -0,0 +1,5 @@
1
+ const o=t=>t.toolCalls===void 0||t.toolCalls.length===0?{content:t.content,role:"assistant"}:{content:[...t.content.length>0?[{text:t.content,type:"text"}]:[],...t.toolCalls.map(e=>({input:e.input,toolCallId:e.id,toolName:e.name,type:"tool-call"}))],role:"assistant"},n=t=>({content:[{output:{type:"text",value:t.content},toolCallId:t.toolCallId??"",toolName:t.toolName??"",type:"tool-result"}],role:"tool"}),l=t=>{const e=[];t.instructions!==void 0&&t.instructions.length>0&&e.push({content:t.instructions,role:"system"}),t.memoryContext!==void 0&&t.memoryContext.length>0&&e.push({content:`Relevant context retrieved for this conversation:
2
+
3
+ ${t.memoryContext}`,role:"system"}),t.summary!==void 0&&t.summary.length>0&&e.push({content:`Summary of the earlier conversation:
4
+
5
+ ${t.summary}`,role:"system"});for(const s of t.history)if(s.status!=="awaiting_approval")switch(s.role){case"assistant":{e.push(o(s));break}case"system":{e.push({content:s.content,role:"system"});break}case"tool":{e.push(n(s));break}case"user":{e.push({content:s.content,role:"user"});break}}return e};export{l as buildModelMessages};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{jsonSchema as h,asSchema as v}from"ai";import{i as A}from"./positive-integer-ztHqqpBk.mjs";import{M as g,c as w}from"./tool-output-Cmk3JWMG.mjs";const $=16,T=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=g?e:w(o)},S=(e,o)=>{let t=e;for(const n of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,n))return;t=t[n]}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"?S(o[r],t.$path):o[r]}const n={};for(const[r,i]of Object.entries(t))r!=="__proto__"&&(n[r]=l(i,o));return n},b=async(e,o,t)=>{const{validate:n}=v(o.inputSchema);if(n===void 0)return t;const r=await n(t);if(r.success)return r.value;throw new a("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${r.error.message}`)},O=async(e,o,t,n)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>n)throw new a("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(n)}. Split it across several code calls.`);const i={},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 b(s,c,l(s.input??{},i)),u={...t,idempotencyKey:`${t.idempotencyKey}:${s.id}`,toolCallId:`${t.toolCallId}:${s.id}`},y=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,y);i[s.id]=f,p.push({id:s.id,output:T(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("; ")}.`,_=h({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"}),P=(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,i]of Object.entries(t))if(i.needsApproval!==void 0&&i.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(o.maxSteps!==void 0&&!A(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const n=o.maxSteps??$;return{description:o.description??E(e),execute:(r,i)=>O(r,e,i,n),inputSchema:_,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{P as codeTool,l as resolveReferences,O as runToolScript};
@@ -0,0 +1 @@
1
+ import{jsonSchema as u}from"ai";import{toFunctionReference as d}from"./AGENT_MODULE-M4D1EejI.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};
@@ -0,0 +1 @@
1
+ const n=o=>async e=>{await Promise.allSettled(o.map(async p=>p?.(e)))},d=o=>{const e=o.filter(a=>typeof a=="function");return a=>{let t=a.execute;for(const m of e.toReversed()){const l=t;t=()=>m({...a,execute:l})}return t()}},c=(...o)=>({executeLanguageModelCall:d(o.map(e=>e.executeLanguageModelCall)),executeTool:d(o.map(e=>e.executeTool)),onAbort:n(o.map(e=>e.onAbort)),onEmbedEnd:n(o.map(e=>e.onEmbedEnd)),onEmbedStart:n(o.map(e=>e.onEmbedStart)),onEnd:n(o.map(e=>e.onEnd)),onError:n(o.map(e=>e.onError)),onLanguageModelCallEnd:n(o.map(e=>e.onLanguageModelCallEnd)),onLanguageModelCallStart:n(o.map(e=>e.onLanguageModelCallStart)),onObjectStepEnd:n(o.map(e=>e.onObjectStepEnd)),onObjectStepStart:n(o.map(e=>e.onObjectStepStart)),onRerankEnd:n(o.map(e=>e.onRerankEnd)),onRerankStart:n(o.map(e=>e.onRerankStart)),onStart:n(o.map(e=>e.onStart)),onStepEnd:n(o.map(e=>e.onStepEnd)),onStepFinish:n(o.map(e=>e.onStepFinish)),onStepStart:n(o.map(e=>e.onStepStart)),onToolExecutionEnd:n(o.map(e=>e.onToolExecutionEnd)),onToolExecutionStart:n(o.map(e=>e.onToolExecutionStart))});export{c as combineTelemetry};
@@ -0,0 +1 @@
1
+ const t=(o,e)=>{if(!(o===null||typeof o!="object"))return o[e]},y=o=>{const e={};for(const s of["inputTokens","outputTokens","totalTokens"]){const n=t(o,s);typeof n=="number"&&(e[s]=n)}return Object.keys(e).length>0?e:void 0},m=o=>{const e=t(t(o,"providerMetadata"),"gateway"),s=t(t(o,"response"),"headers"),n=p=>{const g=t(s,"get"),f=typeof g=="function"?g.call(s,p):t(s,p);return typeof f=="string"&&f.length>0?f:void 0},a={},r=t(e,"cost");typeof r=="number"&&Number.isFinite(r)&&(a.cost=r);const i=t(e,"cached"),c=t(e,"cacheStatus"),l=typeof c=="string"?c:n("cf-aig-cache-status");typeof i=="boolean"?a.cached=i:typeof l=="string"&&(a.cached=l.toUpperCase()==="HIT");const u=t(e,"logId")??t(e,"log_id"),d=typeof u=="string"&&u.length>0?u:n("cf-aig-log-id");return typeof d=="string"&&d.length>0&&(a.logId=d),Object.keys(a).length>0?a:void 0},h=o=>{const e=t(o,"toolCall"),s=t(e,"toolName"),n=typeof s=="string"?s:void 0,a=t(o,"toolOutput"),r=t(a,"type"),i=t(o,"success"),c=typeof i=="boolean"?i:r!=="tool-error",l=t(o,"toolExecutionMs");return{error:c?void 0:t(a,"error")??t(o,"error"),name:n,output:c?t(a,"output"):void 0,success:c,toolExecutionMs:typeof l=="number"?l:void 0}},b=o=>{const e=t(t(o,"toolCall"),"toolName");return typeof e=="string"?e:void 0},v=o=>t(t(o,"toolCall"),"input"),x=o=>{if(!Array.isArray(o))return;let e="";for(const s of o)if(t(s,"type")==="text"){const n=t(s,"text");typeof n=="string"&&(e+=n)}return e.length>0?e:void 0},T=o=>o instanceof Error?{message:o.message,name:o.name}:o;export{b as a,h as b,x as c,T as d,m as e,t as r,y as s,v as t};
@@ -0,0 +1 @@
1
+ import{defineWorkflow as s}from"@lunora/workflow";import{r as m}from"./agent-loop-CE_Q6bk9.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-BOILDUZj.mjs";import{agentDefaultName as c}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-M4D1EejI.mjs";import{t as T}from"./createDispatchRunner-BxtGxAQi-DXXP7SxZ.mjs";import{otlpTelemetry as y}from"./otlpTelemetry-ByqrB-72.mjs";const E=(r,t,a)=>t===void 0?r:T({env:a,identity:{userId:t},label:"@lunora/agent"}),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,i=[r.telemetry?.integrations].flat().filter(o=>o!==void 0);return{...r,telemetry:{...r.telemetry,integrations:[...i,y({conversationId:a,endpoint:e,token:n})],isEnabled:!0}}},I=(r,t,a)=>s({handler:async e=>{const n=O(r,e.env,e.params.threadKey);return m({agent:n,compact:u(),env:e.env,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.run,e.params.owner,e.env),step:e.step,streamGenerate:p(n,e.env)})},name:r.name??c(t)});export{I as default};
@@ -0,0 +1 @@
1
+ const o="agent",A=6048e5,a=12096e5,r=n=>({...n,visibility:"internal"}),_=n=>{const s={};for(const[e,t]of Object.entries(n))t!==void 0&&(s[e]=t);return s};export{o as A,r as a,a as b,A as c,_ as d};
@@ -0,0 +1 @@
1
+ import{a as f,t as g,b as m,d as c,r as e,s as i,c as I}from"./common-CJSjtsfv.mjs";const b=(n,a,d)=>{globalThis.console[n](a,d)},E=(n={})=>{const{functionId:a,logger:d=b,recordInputs:u=!1,recordOutputs:l=!1}=n,p=a===void 0?"":`[${a}] `,r=(o,s,t)=>{d(o,`${p}${s}`,t)};return{onAbort:o=>{r("warn","agent operation aborted",{callId:e(o,"callId"),reason:e(o,"reason")})},onEnd:o=>{r("info","agent operation completed",{callId:e(o,"callId"),finishReason:e(o,"finishReason"),operationId:e(o,"operationId"),usage:i(e(o,"usage"))})},onError:o=>{r("error","agent operation errored",{error:c(o)})},onLanguageModelCallEnd:o=>{const s={callId:e(o,"callId"),finishReason:e(o,"finishReason"),modelId:e(o,"modelId"),provider:e(o,"provider"),usage:i(e(o,"usage"))};l&&(s.text=I(e(o,"content"))),r("info","language model call ended",s)},onStart:o=>{r("info","agent operation started",{callId:e(o,"callId"),modelId:e(o,"modelId"),operationId:e(o,"operationId"),provider:e(o,"provider")})},onStepEnd:o=>{r("info","agent step ended",{finishReason:e(o,"finishReason"),stepNumber:e(o,"stepNumber"),usage:i(e(o,"usage"))})},onStepStart:o=>{r("info","agent step started",{stepNumber:e(o,"stepNumber")})},onToolExecutionEnd:o=>{const s=m(o),t={success:s.success,tool:s.name,toolExecutionMs:s.toolExecutionMs};s.success||(t.error=c(s.error)),l&&s.success&&(t.output=s.output),r(s.success?"info":"warn","tool execution ended",t)},onToolExecutionStart:o=>{const s={tool:f(o)};u&&(s.input=g(o)),r("info","tool execution started",s)}}};export{E as consoleTelemetry};
@@ -0,0 +1 @@
1
+ import{t as g}from"./createDispatchRunner-BxtGxAQi-DXXP7SxZ.mjs";import{LunoraError as o}from"@lunora/errors";import{h as l,B as p}from"./branch-marker-boZ00zmk.mjs";import{toFunctionReference as w,DEFAULT_AGENT_FUNCTION_PATHS as m}from"./AGENT_MODULE-M4D1EejI.mjs";const T=(r,s,i)=>{const c={},u=w(m.patchThread),d=()=>i??g({env:r,label:"@lunora/agent"});for(const e of s){const a=()=>{const n=r[e.binding];if(!n||typeof n.create!="function"||typeof n.get!="function")throw new o("INTERNAL",`@lunora/agent: no Workflow binding "${e.binding}" on env for agent "${e.exportName}" — run codegen/dev so wrangler.jsonc declares it`);return n};c[e.exportName]={cancel:async n=>{await(await a().get(n)).terminate();try{await d()(u,{instanceId:n,status:"cancelled"})}catch{}},publicRun:e.publicRun===!0,run:async(n,t)=>{if(l(n))throw new o("BAD_REQUEST",`@lunora/agent: run input ${p}`);return{id:(await a().create({...t?.id===void 0?{}:{id:t.id},params:n})).id}},sendEvent:async(n,t)=>{await(await a().get(n)).sendEvent(t)},status:async n=>(await a().get(n)).status()}}return c};export{T as default};
@@ -0,0 +1,3 @@
1
+ import{createAi as w}from"@lunora/ai";import{LunoraError as T}from"@lunora/errors";import{jsonSchema as x,generateText as d,Output as f,streamText as C,tool as A}from"ai";const g=t=>{if(!t)return;const e={};for(const o of["inputTokens","outputTokens","totalTokens"]){const r=t[o];r!==void 0&&(e[o]=r)}return Object.keys(e).length>0?e:void 0},y=t=>t.map(e=>{const o={id:e.toolCallId,input:e.input,name:e.toolName};return e.invalid!==!0?o:{...o,invalid:e.error instanceof Error?e.error.message:String(e.error)}}),m=(t,e)=>{if(typeof t=="function")return t(e);if(typeof t=="string"){const o=e.AI;if(!o)throw new T("INTERNAL",`@lunora/agent: the agent model "${t}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return w({binding:o,env:e}).model(t)}return t},b=(t,e)=>{const o=m(t.model,e),r={};for(const[a,i]of Object.entries(t.tools??{}))r[a]=A({description:i.description,inputSchema:i.inputSchema});const n=t.output===void 0?void 0:f.object({schema:t.output}),s={...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{maxOutputTokens:t.maxOutputTokens},...t.telemetry===void 0?{}:{telemetry:t.telemetry},...t.repairToolCall===void 0?{}:{experimental_repairToolCall:t.repairToolCall}};return{defaultModel:o,output:n,staticSettings:s,tools:r}},v=(t,{activeTools:e,messages:o,model:r,signal:n,toolChoice:s})=>{const{defaultModel:a,output:i,staticSettings:h,tools:c}=t,l=e===void 0?c:Object.fromEntries(Object.entries(c).filter(([p])=>e.includes(p)));return{messages:o,model:r??a,...h,...Object.keys(l).length>0?{tools:l}:{},...s===void 0?{}:{toolChoice:s},...i===void 0?{}:{output:i},...n===void 0?{}:{abortSignal:n}}},I=(t,e)=>{const o=b(t,e);return async r=>{const n=await d(v(o,r)),s=g(n.usage);return{text:n.text,toolCalls:y(n.toolCalls),...s===void 0?{}:{usage:s},...o.output===void 0?{}:{output:n.output}}}},q=(t,e)=>{const o=b(t,e);return async(r,n)=>{const s=C(v(o,r));let a="";try{for await(const u of s.textStream)a+=u,n(u)}catch(u){if(r.signal?.aborted)return{text:a,toolCalls:[]};throw u}const[i,h,c,l]=await Promise.all([s.text,s.toolCalls,s.usage,o.output===void 0?Promise.resolve(void 0):s.output]),p=g(c);return{text:i,toolCalls:y(h),...p===void 0?{}:{usage:p},...o.output===void 0?{}:{output:l}}}},k=x({additionalProperties:!1,properties:{entities:{description:"The distinct entities (people, orgs, places, things, concepts) named in the exchange.",items:{additionalProperties:!1,properties:{name:{description:"The entity's canonical name.",type:"string"},type:{description:"An optional coarse type, e.g. person, org, place, product.",type:"string"}},required:["name"],type:"object"},type:"array"},relations:{description:"The directed relationships between the entities, as (src)-[label]->(dst) triples.",items:{additionalProperties:!1,properties:{confidence:{description:"Confidence in the relation, 0..1.",type:"number"},dst:{description:"The destination entity name (must appear in `entities`).",type:"string"},label:{description:"The relationship, a short snake_case verb phrase, e.g. works_at.",type:"string"},src:{description:"The source entity name (must appear in `entities`).",type:"string"}},required:["src","dst","label"],type:"object"},type:"array"}},required:["entities","relations"],type:"object"}),j=(t,e)=>["Extract a knowledge graph of the durable facts stated in the following exchange.","Return the distinct entities and the directed relationships between them.","Only include facts actually stated — do not invent entities or relations. Prefer few, high-signal triples.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
2
+ `),M=()=>async({assistantText:t,env:e,model:o,userInput:r})=>{const{output:n}=await d({model:m(o,e),output:f.object({schema:k}),prompt:j(r,t)});return n},E=(t,e)=>["Summarize the following exchange as ONE concise past-tense sentence for a long-term memory log.","Capture what the user wanted and what was done or decided — a durable fact worth recalling in a later conversation.","No preamble and no quotes: return only the sentence.","",`User: ${t}`,"",`Assistant: ${e}`].join(`
3
+ `),_=()=>async({assistantText:t,env:e,model:o,userInput:r})=>{const{text:n}=await d({model:m(o,e),prompt:E(r,t)});return{summary:n.trim()}},O="You are compacting an ongoing conversation. Summarize the messages so far into a concise brief that preserves decisions made, facts established, open questions, and current task state — everything the assistant needs to continue coherently. Write it as notes for the assistant, not a reply to the user. No preamble.",R=()=>async({env:t,messages:e,model:o})=>{const{text:r}=await d({messages:e,model:m(o,t),system:O});return r.trim()};export{I as createAgentGenerate,R as createCompact,_ as createEpisodeExtract,M as createGraphExtract,q as createStreamGenerate,m as resolveAgentModel};
@@ -0,0 +1 @@
1
+ import{LunoraError as b,isLunoraError as D}from"@lunora/errors";const k=(e,t,o)=>{if(t===void 0)return{dispose:()=>{},signal:e};const a=new AbortController,n=setTimeout(()=>{a.abort(o())},t);return{dispose:()=>{clearTimeout(n)},signal:a.signal}},A=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},B=e=>{const t=atob(e),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.codePointAt(a)??0;return o},p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",j=e=>{let t="",o=0;const a=e.length-2;for(;o<a;o+=3){const r=e[o]<<16|e[o+1]<<8|e[o+2];t+=p.charAt(r>>18&63)+p.charAt(r>>12&63)+p.charAt(r>>6&63)+p.charAt(r&63)}const n=e.length-o;if(n===1){const r=e[o]<<16;t+=p.charAt(r>>18&63)+p.charAt(r>>12&63)}else if(n===2){const r=e[o]<<16|e[o+1]<<8;t+=p.charAt(r>>18&63)+p.charAt(r>>12&63)+p.charAt(r>>6&63)}return t};new TextDecoder;const L=new TextEncoder,$="=",M=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},C=e=>j(L.encode(JSON.stringify(e))),J=e=>!e.startsWith($)&&M(e)?e:`${$}${j(L.encode(e))}`,u="$lunora.wire$",E=64,I=1024,v="__proto__",R={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},S={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},K=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},h=(e,t=0)=>{if(t>E)throw new RangeError(`wire-codec: value nesting exceeds the ${E}-level limit`);if(e===void 0)return[u,"undefined"];if(e===null)return null;const o=typeof e;if(o==="bigint")return[u,"bigint",e.toString()];if(o==="number"){const r=e;return Number.isNaN(r)?[u,"nan"]:r===1/0?[u,"inf"]:r===-1/0?[u,"-inf"]:r}if(o!=="object")return e;if(e instanceof Date)return[u,"date",h(e.getTime(),t+1)];if(e instanceof Error){const r=e,s={};for(const c of Object.keys(r)){if(r[c]===void 0)continue;const f=h(r[c],t+1);c===v?Object.defineProperty(s,c,{configurable:!0,enumerable:!0,value:f,writable:!0}):s[c]=f}const i=[u,"error",String(r.name),String(r.message),s];return r.cause!==void 0&&i.push(h(r.cause,t+1)),i}if(e instanceof URL)return[u,"url",e.href];if(e instanceof Map)return[u,"map",[...e.entries()].map(([r,s])=>[h(r,t+1),h(s,t+1)])];if(e instanceof Set)return[u,"set",[...e].map(r=>h(r,t+1))];if(e instanceof ArrayBuffer)return[u,"bytes",A(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,s=r.constructor.name,i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return s==="Uint8Array"?[u,"bytes",A(i)]:[u,"bytes",A(i),s]}if(Array.isArray(e)){const r=e.map(s=>h(s,t+1));return r.length>0&&r[0]===u?[u,"arr",r]:r}if(!K(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=e,n={};for(const r of Object.keys(a)){const s=a[r];if(s===void 0)continue;const i=h(s,t+1);r===v?Object.defineProperty(n,r,{configurable:!0,enumerable:!0,value:i,writable:!0}):n[r]=i}return n},l=(e,t=0)=>{if(t>E)throw new RangeError(`wire-codec: value nesting exceeds the ${E}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===u)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(n=>l(n,t+1));case"bigint":{const n=e[2];if(typeof n!="string"||n.length>I||!/^-?\d+$/.test(n))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${I} digits)`);return BigInt(n)}case"date":{const n=l(e[2],t+1);if(typeof n!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(n)}case"map":{const n=e[2];return new Map(n.map(r=>{if(!Array.isArray(r)||r.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[l(r[0],t+1),l(r[1],t+1)]}))}case"set":return new Set(e[2].map(n=>l(n,t+1)));case"url":{const n=e[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(n)}case"error":{const n=e[2],r=e[3];if(typeof n!="string"||typeof r!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(S,n)?S[n]:void 0)??Error,i=new s(r);i.name!==n&&Object.defineProperty(i,"name",{configurable:!0,value:n,writable:!0});const c=l(e[4],t+1);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const f of Object.keys(c))f===v?Object.defineProperty(i,f,{configurable:!0,enumerable:!0,value:c[f],writable:!0}):i[f]=c[f];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:l(e[5],t+1),writable:!0}),i}case"bytes":{const n=e[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const r=B(n);if(A(r)!==n)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const i=Object.hasOwn(R,s)?R[s]:void 0;return i?new i(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(n=>l(n,t+1))}return e.map(n=>l(n,t+1))}const o=e,a={};for(const n of Object.keys(o)){const r=l(o[n],t+1);n===v?Object.defineProperty(a,n,{configurable:!0,enumerable:!0,value:r,writable:!0}):a[n]=r}return a},F=(e,t,o)=>{try{return h(o)}catch(a){throw new TypeError(`${e}: cannot encode args for '${t}' — ${a instanceof Error?a.message:String(a)}`,a instanceof Error?{cause:a}:void 0)}},W="/_lunora/scheduler/dispatch",G=3e4,H=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},U=Symbol("lunoraDispatchFailure"),z=Symbol("lunoraDispatchMessageId"),_=(e,t)=>(t!==void 0&&Object.defineProperty(e,z,{value:t}),e),V=(e,t)=>(Object.defineProperty(e,U,{value:!0}),_(e,t)),q=(e,t,o,a)=>{try{const n=JSON.parse(o)?.error;if(typeof n=="object"&&n!==null&&typeof n.code=="string"){const{code:r,data:s,message:i}=n;return V(new b(r,typeof i=="string"?i:void 0,{data:s,status:t}),a)}}catch{}return _(new b("INTERNAL",`${e}: function dispatch failed (${String(t)}): ${o}`,{status:t}),a)},Q=new Set([400,403,404,422]),X=new Set(["DISPATCH_UNAUTHENTICATED"]),ee=e=>D(e)&&e[U]===!0&&Q.has(e.status)&&!X.has(e.code),Y=(e,t,o)=>new b("INTERNAL",`${e}: function dispatch to "${t}" timed out after ${String(o)}ms`,{status:503}),te=e=>{const{label:t}=e,o=globalThis.fetch,a=e.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(n,r,s={})=>{if(typeof a!="function")throw new TypeError(`${t}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const i=()=>e.argsAlreadyEncoded===!0?r??{}:F(t,n.__lunoraRef,r??{}),c=e.env.LUNORA_ORIGIN_URL;if(typeof c!="string"||c.length===0)throw new b("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const f=e.env.LUNORA_ADMIN_TOKEN;if(typeof f!="string"||f.length===0)throw new b("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const x=`${H(c)}${W}`,m={authorization:`Bearer ${f}`,"content-type":"application/json"};e.traceparent!==void 0&&e.traceparent.length>0&&(m.traceparent=e.traceparent),e.identity?.userId!==void 0&&(m["x-lunora-userid"]=J(e.identity.userId)),e.identity?.claims!==void 0&&(m["x-lunora-identity"]=C(e.identity.claims));const N=s.timeoutMs??G,T=k(void 0,N,()=>new DOMException(`dispatch timed out after ${String(N)}ms`,"TimeoutError")),O=y=>{throw y instanceof Error&&y.name==="TimeoutError"?Y(t,n.__lunoraRef,N):y};let d;try{try{d=await a(x,{body:JSON.stringify({args:i(),functionPath:n.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:m,method:"POST",signal:T.signal})}catch(g){return O(g)}if(!d.ok){let g;try{g=await d.text()}catch(P){return O(P)}throw q(t,d.status,g,s.messageId)}let y;try{y=await d.text()}catch(g){return O(g)}if(y.length===0)return;let w;try{w=JSON.parse(y)}catch{throw new b("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(d.status)}): ${y}`,{status:d.status})}if(w===null||typeof w!="object"||Array.isArray(w)||!("result"in w))throw new b("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(d.status)}): ${y}`,{status:d.status});return l(w.result)}finally{T.dispose()}}};export{ee as e,te as t};
@@ -0,0 +1,3 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-CE_Q6bk9.mjs";import{collectAgenticMemoryTools as g}from"./collectAgenticMemoryTools-BeMWT2qt.mjs";import{agentAsTool as p}from"./agentAsTool-CgZb6ycK.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=/^[a-zA-Z][\w-]*$/u,N=(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},A=(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
+ `)},k=(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)}},v=(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)`)},E=(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=>{if(e===void 0)return;const n=f(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(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");L(e.approvalTimeout);const o=e.skills??[];y(o),E(e,o);const t=N(e,o),s=g(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;v(e.activeTools,s);for(const i of Object.keys(t))if(!T.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=k(e,o),d=A(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}:{}}},j=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,M=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,M as defineAgentTool,j as isAgentDefinition};
@@ -0,0 +1 @@
1
+ import{LunoraError as t}from"@lunora/errors";const i=/^[a-zA-Z][\w-]*$/u,r="default",o=e=>{if(typeof e.name!="string"||!i.test(e.name))throw new t("INTERNAL",`@lunora/agent: defineSkill requires a \`name\` that is a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(e.name)}`);if(e.name===r)throw new t("INTERNAL",`@lunora/agent: skill name "${r}" is reserved (it keys the agent's own \`memory\` source / the historic \`memory:retrieve\` step) — choose another name`);return{...e,isLunoraSkill:!0}},s=e=>typeof e=="object"&&e!==null&&e.isLunoraSkill===!0;export{r as RESERVED_SKILL_NAME,i as SKILL_NAME_PATTERN,o as defineSkill,s as isSkillDefinition};
@@ -0,0 +1 @@
1
+ const o=c=>c.toString(16).padStart(4,"0"),g=c=>{let t=8997,n=33826,e=40164,s=52210;for(let h=0;h<c.length;h+=1){t^=c.charCodeAt(h);const r=t*435,p=n*435,x=e*435+t*256,d=s*435+n*256,l=p+(r>>>16),a=x+(l>>>16),f=d+(a>>>16);t=r&65535,n=l&65535,e=a&65535,s=f&65535}return o(s)+o(e)+o(n)+o(t)};export{g as f};
@@ -0,0 +1 @@
1
+ import{LunoraError as o}from"@lunora/errors";import{toFunctionReference as c}from"./AGENT_MODULE-M4D1EejI.mjs";const m=(r,e)=>{if(typeof e.description!="string"||e.description.length===0)throw new o("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(e.inputSchema===void 0)throw new o("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const t=c(r);return{description:e.description,execute:(i,n)=>n.run(t,{...i,idempotencyKey:n.idempotencyKey}),inputSchema:e.inputSchema,isLunoraAgentTool:!0}};export{m as functionTool};
@@ -0,0 +1 @@
1
+ import{r as s}from"./common-CJSjtsfv.mjs";const f=600*1e3,h=(i,a)=>{const t=new Map,c=(e,o,n,r)=>{const l=t.get(e);l!==void 0&&(t.delete(e),i(l.call,o,n,r))};return{close:c,fromLifecycle:e=>{const o=s(e,"callId");if(typeof o!="string"||!t.has(o))return;const n=s(e,"finishReason"),r=n==="error"||s(n,"unified")==="error";c(o,!r,r?"the model call ended with an error":void 0,e)},get:e=>t.get(e)?.call,open:(e,o)=>{const n=Date.now()-f;for(const[r,l]of t)l.openedAt<n&&(t.delete(r),a?.(l.call));t.has(e)||t.set(e,{call:o(),openedAt:Date.now()})}}};export{h as c};
@@ -0,0 +1,2 @@
1
+ import{defineTable as A,initLunora as q}from"@lunora/server";import{v as e}from"@lunora/values";import{A as _,a as f,d as S}from"./component-shared-G8ngerkU.mjs";const T="entities",x="edges",b=`${_}_${T}`,g=`${_}_${x}`,X={[T]:A({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[x]:A({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},E=64,O=2,G=4,D=8,C=32,R=500,I=/\s+/gu,K=/[^\p{L}\p{N}]+/u,h=t=>t.trim().replaceAll(I," ").toLowerCase(),L=t=>t.toLowerCase().split(K).filter(o=>o.length>=2),P=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,o)=>o.weight-t.weight||t.label.localeCompare(o.label)||t.srcName.localeCompare(o.srcName)||t.dstName.localeCompare(o.dstName),$=(t,o)=>o.some(n=>t.includes(n)||n.includes(t)),v=t=>t.map(o=>`- ${o.srcName} —[${o.label}]→ ${o.dstName}`).toSorted((o,n)=>o.localeCompare(n)).join(`
2
+ `),H=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,B=(t,o,n,r)=>{const a=H(t);r.collectedKeys.has(a)||(r.collectedKeys.add(a),r.collected.push(t));const l=t.srcName===o?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<n.maxNodes&&(r.seen.add(l),r.next.push(l))},F=async(t,o,n)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(o)};let a=o.slice(0,n.maxNodes);for(let l=0;l<n.depth&&a.length>0;l+=1){r.next=[];for(const m of a){const p=(await t(m)).toSorted(U).slice(0,n.fanOut);for(const s of p)B(s,m,n,r)}a=r.next}return r.collected},{mutation:M,query:W}=q.dataModel().create(),Y=()=>{const t=M.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:n,ctx:r})=>{const a=Date.now(),l=async(s,i)=>{const c=h(s);if(c.length===0)return;const d=await r.db.query(b).withIndex("byOwnerName",u=>u.eq("owner",n.owner).eq("name",c)).first();return d?(i!==void 0&&d.type===void 0&&await r.db.patch(d._id,{type:i,updatedAt:a}),c):(await r.db.insert(b,{createdAt:a,name:c,owner:n.owner,updatedAt:a,weight:1,...S({firstMessageKey:n.messageKey,type:i})}),c)},m=async s=>{const i=h(s.src),c=h(s.dst),d=h(s.label);if(i.length===0||c.length===0||d.length===0||i===c)return!1;await l(i),await l(c);const u=s.confidence??1,N=await r.db.query(g).withIndex("byTriple",y=>y.eq("owner",n.owner).eq("srcName",i).eq("label",d).eq("dstName",c)).first();if(N){const y=N.weight??1;await r.db.patch(N._id,{updatedAt:a,weight:Math.max(y,u)})}else await r.db.insert(g,{createdAt:a,dstName:c,label:d,messageKey:n.messageKey,owner:n.owner,srcName:i,updatedAt:a,weight:u});return!0};let w=0;for(const s of n.entities.slice(0,E))await l(s.name,s.type)!==void 0&&(w+=1);let p=0;for(const s of n.relations.slice(0,E))await m(s)&&(p+=1);return{entities:w,relations:p}}),o=W.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:n,ctx:r})=>{const a=L(n.query);if(a.length===0)return{context:""};const m=(await r.db.query(b).withIndex("byOwnerUpdatedAt",s=>s.eq("owner",n.owner)).order("desc").take(R)).filter(s=>$(s.name,a)).toSorted((s,i)=>(i.weight??1)-(s.weight??1)||s.name.localeCompare(i.name)).slice(0,n.maxSeeds??G).map(s=>s.name);if(m.length===0)return{context:""};const p=await F(async s=>{const[i,c]=await Promise.all([r.db.query(g).withIndex("byOwnerSrc",d=>d.eq("owner",n.owner).eq("srcName",s)).collect(),r.db.query(g).withIndex("byOwnerDst",d=>d.eq("owner",n.owner).eq("dstName",s)).collect()]);return[...i,...c].map(d=>P(d))},m,{depth:n.depth??O,fanOut:n.fanOut??D,maxNodes:n.maxNodes??C});return{context:v(p)}});return{agentGraphTraverse:f(o),agentGraphUpsert:f(t)}};export{Y as graphComponent,X as graphTables,h as normalizeEntityName};
@@ -0,0 +1 @@
1
+ import{estimateModelCost as z}from"@lunora/ai";import{a as D,r as d,s as F,e as V,c as P,t as J}from"./common-CJSjtsfv.mjs";import{c as Y}from"./in-flight-calls-GH1A_1P3.mjs";const k=e=>`${String(Math.round(e))}000000`,q=Array.from({length:256},(e,o)=>o.toString(16).padStart(2,"0")),v=512,M=new Uint8Array(v);let w=v;const j=(e,o,n)=>{let c="";for(let s=0;s<n;s+=1)c+=q[e[o+s]];return c},R=e=>{if(e>v){const n=new Uint8Array(e);return crypto.getRandomValues(n),j(n,0,e)}w+e>v&&(crypto.getRandomValues(M),w=0);const o=j(M,w,e);return w+=e,o},A=(e,o)=>typeof o=="boolean"?{key:e,value:{boolValue:o}}:typeof o=="number"?Number.isFinite(o)?Number.isSafeInteger(o)?{key:e,value:{intValue:String(o)}}:{key:e,value:{doubleValue:o}}:{key:e,value:{stringValue:String(o)}}:{key:e,value:{stringValue:o}},G=(e,o,n)=>{const c={},s=new Map,_=(g,m)=>{const x=g.toLowerCase(),T=s.get(x);T===void 0?(s.set(x,g),c[g]=m):c[T]=m};for(const[g,m]of Object.entries(e))_(g,m);for(const[g,m]of Object.entries(o??{}))_(g,m);return n!==void 0&&n.length>0&&_("authorization",`Bearer ${n}`),c},W=e=>Array.isArray(e)?e:[e],X=(e,o)=>{const n={"service.name":e};for(const[c,s]of Object.entries({}))n[c]=s;return Object.entries(n).map(([c,s])=>A(c,s))},K=(e,o,n,c)=>({resourceSpans:[{resource:{attributes:X(n)},scopeSpans:[{scope:{name:o},spans:W(e)}]}]}),i=(e,o,n)=>{if(n!=null){if(typeof n=="boolean"||typeof n=="number"||typeof n=="string"){e.push(A(o,n));return}e.push(A(o,JSON.stringify(n)))}},Q=(e,o)=>{(async()=>{let c;try{c=await e}catch(s){o(!1,s instanceof Error?s.message:String(s),void 0);return}o(!0,void 0,c)})().catch(()=>{})},oe=e=>{const{conversationId:o,endpoint:n,headers:c,recordInputs:s=!1,recordOutputs:_=!1,token:g,traceId:m,waitUntil:x}=e,T=e.serviceName??"lunora";let S=n;for(;S.endsWith("/");)S=S.slice(0,-1);const $=`${S}/v1/traces`,B=G({"content-type":"application/json"},c,g),N=(t,r,a,l,y)=>{const f={attributes:y,endTimeUnixNano:k(Date.now()),kind:1,name:t,spanId:R(8),startTimeUnixNano:k(r),status:a?{code:1}:{code:2,message:l??""},traceId:m??R(16)};try{const b=fetch($,{body:JSON.stringify(K(f,"@lunora/agent",T)),headers:B,method:"POST"}).catch(()=>{});x?.(b)}catch{}},h=Y((t,r,a,l)=>{const{messages:y,modelId:f,provider:b,result:p,startTs:H}=t,u=[];i(u,"gen_ai.operation.name","chat"),i(u,"gen_ai.request.model",f),i(u,"gen_ai.system",b),i(u,"gen_ai.conversation.id",o);const I=F(d(l,"usage")??d(p,"usage"));I&&(i(u,"gen_ai.usage.input_tokens",I.inputTokens),i(u,"gen_ai.usage.output_tokens",I.outputTokens),i(u,"gen_ai.usage.total_tokens",I.totalTokens));const O=V(l)??V(p);O&&(i(u,"gen_ai.response.cached",O.cached),i(u,"cf.aig.log_id",O.logId));const U=O?.cost,L=U??(typeof f=="string"?z(f,{inputTokens:I?.inputTokens,outputTokens:I?.outputTokens}):void 0);L!==void 0&&(i(u,"gen_ai.usage.cost",L),i(u,"lunora.usage.cost.source",U===void 0?"estimated":"provider")),s&&i(u,"gen_ai.prompt",y),_&&i(u,"gen_ai.completion",P(d(l,"content")??d(p,"content"))),N(typeof f=="string"?`chat ${f}`:"language_model_call",H,r,a,u)}),C=(t,r,a)=>{const l=d(t,"callId");if(typeof l!="string")return;let y=a;r instanceof Error?y=r.message:typeof r=="string"&&r.length>0&&(y=r),h.close(l,!1,y,void 0)},E=t=>({messages:d(t,"messages"),modelId:d(t,"modelId"),provider:d(t,"provider"),result:void 0,startTs:Date.now()});return{executeLanguageModelCall:async t=>{const{callId:r}=t;h.open(r,()=>E(t));try{const a=await t.execute(),l=h.get(r);return l!==void 0&&(l.result=a),a}catch(a){throw h.close(r,!1,a instanceof Error?a.message:String(a),void 0),a}},onAbort:t=>{C(t,d(t,"reason"),"aborted")},onEnd:t=>{h.fromLifecycle(t)},onError:t=>{C(t,d(t,"error"),"the model call failed")},onLanguageModelCallEnd:t=>{const r=d(t,"callId");typeof r=="string"&&h.close(r,!0,void 0,t)},onLanguageModelCallStart:t=>{const r=d(t,"callId");typeof r=="string"&&h.open(r,()=>E(t))},onStepEnd:t=>{h.fromLifecycle(t)},executeTool:t=>{const r=Date.now(),a=D(t),l=t.execute();return Q(l,(f,b)=>{const p=[];i(p,"gen_ai.operation.name","execute_tool"),i(p,"gen_ai.tool.name",a),i(p,"gen_ai.tool.call.id",d(t,"toolCallId")),s&&i(p,"gen_ai.tool.input",J(t)),N(typeof a=="string"?`execute_tool ${a}`:"execute_tool",r,f,b,p)}),l}}};export{oe as otlpTelemetry};
@@ -0,0 +1 @@
1
+ const i=e=>Number.isInteger(e)&&e>0;export{i};
@@ -0,0 +1 @@
1
+ import"./createDispatchRunner-BxtGxAQi-DXXP7SxZ.mjs";import"./component-shared-G8ngerkU.mjs";import"./createAgentGenerate-BOILDUZj.mjs";import{a as n,c as l,r as u,s as f}from"./agent-loop-CE_Q6bk9.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"../naming.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./tool-output-Cmk3JWMG.mjs";export{n as approvalTimeoutMs,l as compactHistory,u as runAgentLoop,f as splitForCompaction};
@@ -0,0 +1 @@
1
+ import"./base64-5eyBfWO3.mjs";import{p as s,c as p,f as m,e as n,r as c,t as d}from"./voice-turn-BRj_it54.mjs";import"./agent-loop-CE_Q6bk9.mjs";import"./buildModelMessages-Y4tGo1T9.mjs";import"./AGENT_MODULE-M4D1EejI.mjs";export{s as parseIdentity,p as pcmToWav,m as readSynthesisAudio,n as readTranscriptionText,c as runVoiceTurn,d as toByteIterable};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{initLunora as h}from"@lunora/server";import{v as t}from"@lunora/values";import{t as g}from"./base64-5eyBfWO3.mjs";const{internalAction:w}=h.dataModel().create(),m=()=>globalThis.document?.documentElement?.outerHTML??"",l=1e6,b=20,x=new TextEncoder,y=async(e,n)=>{const o=n.url??"";switch(n.op){case"content":return e.content(o);case"pdf":return{data:g(await e.pdf(o)),encoding:"base64",mediaType:"application/pdf"};case"scrape":return e.scrape(o,m);case"screenshot":{const s=await e.screenshot(o,{...n.fullPage===void 0?{}:{fullPage:n.fullPage},...n.type===void 0?{}:{type:n.type}});return{data:g(s),encoding:"base64",mediaType:n.type==="jpeg"?"image/jpeg":"image/png"}}default:throw new c("INTERNAL",`@lunora/agent: sandbox browser op "${n.op}" is not supported`)}},E=e=>{const n=[`exit code: ${String(e.code)}`];return e.stdout.length>0&&n.push(`stdout:
2
+ ${e.stdout}`),e.stderr.length>0&&n.push(`stderr:
3
+ ${e.stderr}`),n.join(`
4
+
5
+ `)},$=async(e,n)=>{const o=e.any();if(n.op==="exec")try{return E(await o.exec(n.command??"",{args:n.args??[]}))}catch(s){return`exec failed: ${s instanceof Error?s.message:String(s)}`}if(n.op==="fetch")return(await o.fetch(n.path??"/",{...n.body===void 0?{}:{body:n.body},method:n.method??"GET"})).text();throw new c("INTERNAL",`@lunora/agent: sandbox container op "${n.op}" is not supported`)},u=e=>{let n=0,o=e.length;for(;n<o&&e[n]==="/";)n+=1;for(;o>n&&e[o-1]==="/";)o-=1;return e.slice(n,o)},T=(e,n)=>{const o=u(e),s=[];for(const r of n.split("/"))if(!(r===""||r===".")){if(r===".."){if(s.length===0)throw new c("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");s.pop();continue}s.push(r)}const a=s.join("/");return o&&a?`${o}/${a}`:o||a},S=async(e,n,o)=>{const s=n.length>0?`${n}/`:"",a=o.length>0?o.length+1:0,r=[];let i;for(let d=0;d<b;d+=1){const p=await e.list({prefix:s,...i===void 0?{}:{cursor:i}});for(const f of p.objects)r.push(f.key.slice(a));if(!p.truncated||p.cursor===void 0)return{entries:r,truncated:!1};i=p.cursor}return{entries:r,truncated:!0}},N=async(e,n,o)=>{const s=u(n),a=T(n,o.path??"");switch(o.op){case"ls":{const{entries:r,truncated:i}=await S(e,a,s);return i?{entries:r,truncated:!0}:{entries:r}}case"read":{const r=await e.head(a);if(r&&r.size>l)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${o.path??""}" is ${String(r.size)} bytes (max ${String(l)})`);const i=await e.get(a);if(!i)throw new c("NOT_FOUND",`@lunora/agent: fs read: no file at "${o.path??""}"`);return i.text()}case"rm":return await e.delete(a),{path:o.path??"",removed:!0};case"stat":{const r=await e.head(a);return r?{exists:!0,size:r.size}:{exists:!1}}case"write":{const r=o.content??"",i=x.encode(r).length;if(i>l)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(i)} bytes exceeds the max (${String(l)})`);return await e.put(a,r),{bytes:i,path:o.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${o.op}" is not supported`)}},_=()=>({invoke:w.input({args:t.optional(t.array(t.string())),body:t.optional(t.string()),bucket:t.optional(t.string()),command:t.optional(t.string()),content:t.optional(t.string()),fullPage:t.optional(t.boolean()),kind:t.union(t.literal("browser"),t.literal("container"),t.literal("fs")),method:t.optional(t.string()),name:t.optional(t.string()),op:t.string(),path:t.optional(t.string()),root:t.optional(t.string()),selector:t.optional(t.string()),type:t.optional(t.string()),url:t.optional(t.string())}).action(async({args:n,ctx:o})=>{const s=o,a=n;if(a.kind==="browser"){if(!s.browser)throw new c("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return y(s.browser,a)}if(a.kind==="fs"){const d=s.env?.[a.bucket??""];if(!d||typeof d.get!="function")throw new c("INTERNAL",`@lunora/agent: sandbox fs op found no R2 bucket "${a.bucket??""}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`);return N(d,a.root??"",a)}const r=a.name??"",i=s.containers?.[r];if(!i)throw new c("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${r}"] — declare the container in lunora/containers.ts and run codegen`);return $(i,a)})});export{T as resolveFsKey,N as runFsOp,_ as sandboxComponent};
@@ -0,0 +1 @@
1
+ import{r as n,t as _,s as y,c as I}from"./common-CJSjtsfv.mjs";import{c as x}from"./in-flight-calls-GH1A_1P3.mjs";const g=(c,i)=>typeof c=="string"&&c.length>0?c:i,k=c=>{const{functionId:i,recordInputs:d=!1,recordOutputs:p=!1,Sentry:u}=c,s=x((e,o,a,r)=>{const t={},l=y(n(r,"usage")??n(e.result,"usage"));if(l&&(t["gen_ai.usage.input_tokens"]=l.inputTokens,t["gen_ai.usage.output_tokens"]=l.outputTokens,t["gen_ai.usage.total_tokens"]=l.totalTokens),p){const m=I(n(r,"content")??n(e.result,"content"));m!==void 0&&(t["gen_ai.completion"]=m)}Object.keys(t).length>0&&e.span.setAttributes?.(t),e.span.setStatus?.(o?{code:1}:{code:2,message:a??""}),e.span.end()},e=>{e.span.end()}),f=(e,o,a)=>{const r=n(e,"callId");if(typeof r!="string")return;let t=a;o instanceof Error?t=o.message:typeof o=="string"&&o.length>0&&(t=o),s.close(r,!1,t,void 0)};return{executeLanguageModelCall:e=>{const{callId:o}=e,a={"gen_ai.operation.name":g(i,"language_model_call"),"gen_ai.request.model":n(e,"modelId"),"gen_ai.system":n(e,"provider")};return d&&(a["gen_ai.prompt"]=n(e,"messages")),u.startSpanManual({attributes:a,name:g(i,"language_model_call"),op:"gen_ai.generate"},async r=>{s.open(o,()=>({result:void 0,span:r}));try{const t=await e.execute(),l=s.get(o);return l!==void 0&&(l.result=t),t}catch(t){throw s.close(o,!1,t instanceof Error?t.message:String(t),void 0),t}})},executeTool:e=>{const o=n(n(e,"toolCall"),"toolName"),a={"gen_ai.operation.name":"execute_tool","gen_ai.tool.call.id":n(e,"toolCallId"),"gen_ai.tool.name":o};return d&&(a["gen_ai.tool.input"]=_(e)),u.startSpan({attributes:a,name:`execute_tool ${g(o,"tool")}`,op:"gen_ai.execute_tool"},()=>e.execute())},onAbort:e=>{f(e,n(e,"reason"),"aborted")},onEnd:e=>{s.fromLifecycle(e)},onError:e=>{u.captureException(n(e,"error")??e),f(e,n(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{const o=n(e,"callId");typeof o=="string"&&s.close(o,!0,void 0,e)},onStepEnd:e=>{s.fromLifecycle(e)}}};export{k as sentryTelemetry};
@@ -0,0 +1 @@
1
+ const _=4e3,O="… [truncated]",t=T=>T.length<=4e3?T:`${T.slice(0,4e3-O.length)}${O}`;export{_ as M,t as c};