@lunora/agent 1.0.0-alpha.26 → 1.0.0-alpha.260

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 (96) hide show
  1. package/dist/channels.d.mts +23 -12
  2. package/dist/channels.d.ts +23 -12
  3. package/dist/channels.mjs +1 -1
  4. package/dist/component.d.mts +54 -2
  5. package/dist/component.d.ts +54 -2
  6. package/dist/component.mjs +2 -2
  7. package/dist/inbound.d.mts +9 -7
  8. package/dist/inbound.d.ts +9 -7
  9. package/dist/inbound.mjs +1 -1
  10. package/dist/index.d.mts +207 -18
  11. package/dist/index.d.ts +207 -18
  12. package/dist/index.mjs +1 -1
  13. package/dist/naming.d.mts +15 -7
  14. package/dist/naming.d.ts +15 -7
  15. package/dist/naming.mjs +1 -1
  16. package/dist/packem_shared/AGENT_MODULE-CYBmT9SD.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-CE08SIwv.mjs +1 -0
  18. package/dist/packem_shared/SecretUnavailableError-BCp40Leh.mjs +1 -0
  19. package/dist/packem_shared/VoiceSessionDO-REut3oqY.mjs +1 -0
  20. package/dist/packem_shared/adaptMcpResult-DFF_g58r.mjs +2 -0
  21. package/dist/packem_shared/agent-ai-CP87uSoZ.mjs +1 -0
  22. package/dist/packem_shared/agent-loop-BgOHoyg_.mjs +3 -0
  23. package/dist/packem_shared/agentAsTool-CA7Sha2i.mjs +1 -0
  24. package/dist/packem_shared/braintrustTelemetry-Ck09dC4G.mjs +1 -0
  25. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  26. package/dist/packem_shared/buildModelMessages-DVQdQ7_1.mjs +5 -0
  27. package/dist/packem_shared/codeTool-Hm_Af6t4.mjs +1 -0
  28. package/dist/packem_shared/collectAgenticMemoryTools-BWdIhOfY.mjs +1 -0
  29. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  30. package/dist/packem_shared/common-DBc9y7Np.mjs +1 -0
  31. package/dist/packem_shared/compileAgentWorkflow-yYM18j57.mjs +1 -0
  32. package/dist/packem_shared/component-shared-DdXFbng-.mjs +1 -0
  33. package/dist/packem_shared/consoleTelemetry-Cl-WQEsZ.mjs +1 -0
  34. package/dist/packem_shared/createAgentContext-CqF7NfUY.mjs +1 -0
  35. package/dist/packem_shared/createAgentGenerate-DSLXAeY2.mjs +3 -0
  36. package/dist/packem_shared/defineAgent-D7wY7Jl3.mjs +3 -0
  37. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  38. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  39. package/dist/packem_shared/functionTool-C95ns65V.mjs +1 -0
  40. package/dist/packem_shared/in-flight-calls-C9QGq8uH.mjs +1 -0
  41. package/dist/packem_shared/jsCodeTool-CIlCK1bG.mjs +18 -0
  42. package/dist/packem_shared/normalizeEntityName-Rr5OQxhc.mjs +2 -0
  43. package/dist/packem_shared/otlpTelemetry-CiSI9HE_.mjs +1 -0
  44. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  45. package/dist/packem_shared/runAgentLoop-CoQUnwKs.mjs +1 -0
  46. package/dist/packem_shared/runVoiceTurn-BpC_9Mm3.mjs +1 -0
  47. package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
  48. package/dist/packem_shared/sandboxComponent-Du0yENEO.mjs +7 -0
  49. package/dist/packem_shared/sentryTelemetry-B1BuLxxj.mjs +1 -0
  50. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  51. package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-vAmttAsE.d.mts} +355 -33
  52. package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-vAmttAsE.d.ts} +355 -33
  53. package/dist/packem_shared/voice-turn-hIZ7r1ST.mjs +1 -0
  54. package/dist/packem_shared/webSearchTool-BobmV4cD.mjs +1 -0
  55. package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
  56. package/dist/packem_shared/wrapUntrusted-BuHBC6sV.mjs +2 -0
  57. package/dist/reply.d.mts +58 -0
  58. package/dist/reply.d.ts +58 -0
  59. package/dist/reply.mjs +1 -0
  60. package/dist/sandbox.d.mts +157 -16
  61. package/dist/sandbox.d.ts +157 -16
  62. package/dist/sandbox.mjs +1 -1
  63. package/dist/skill-markdown.d.mts +36 -0
  64. package/dist/skill-markdown.d.ts +36 -0
  65. package/dist/skill-markdown.mjs +1 -0
  66. package/dist/telemetry/index.d.mts +165 -38
  67. package/dist/telemetry/index.d.ts +165 -38
  68. package/dist/telemetry/index.mjs +1 -1
  69. package/package.json +20 -9
  70. package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
  71. package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
  72. package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
  73. package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
  74. package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
  75. package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
  76. package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
  77. package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
  78. package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
  79. package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
  80. package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
  81. package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
  82. package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
  83. package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
  84. package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
  85. package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
  86. package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
  87. package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
  88. package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
  89. package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
  90. package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
  91. package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
  92. package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
  93. package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
  94. package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
  95. package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
  96. package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{jsonSchema as y,asSchema as w}from"@ai-sdk/provider-utils";import{LunoraError as a}from"@lunora/errors";import{i as v}from"./positive-integer-ztHqqpBk.mjs";import{M as A,c as T}from"./tool-output-Cmk3JWMG.mjs";const g=16,$=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=A?e:T(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}=w(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}`)},E=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}`},h=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,h);i[s.id]=f,p.push({id:s.id,output:$(f)})}return{final:p.at(-1)?.output,results:p}},O=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("; ")}.`,_=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"}),N=(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(i.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&&!v(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const n=o.maxSteps??g;return{description:o.description??O(e),execute:(r,i)=>E(r,e,i,n),inputSchema:_,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{N as codeTool,l as resolveReferences,E as runToolScript};
@@ -0,0 +1 @@
1
+ import{jsonSchema as u}from"@ai-sdk/provider-utils";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};
@@ -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
+ import{tokenCount as f,breakdownCount as T}from"@lunora/ai/create";const o=(t,e)=>{if(!(t===null||typeof t!="object"))return t[e]},h=t=>{const e=o(t,"inputTokenDetails"),s=o(t,"outputTokenDetails"),a={},n=(i,c)=>{c!==void 0&&(a[i]=c)};return n("inputTokens",f(o(t,"inputTokens"))),n("outputTokens",f(o(t,"outputTokens"))),n("totalTokens",f(o(t,"totalTokens"))),n("cacheReadTokens",T(o(e,"cacheReadTokens"))),n("cacheWriteTokens",T(o(e,"cacheWriteTokens"))),n("reasoningTokens",T(o(s,"reasoningTokens"))),Object.keys(a).length>0?a:void 0},y=Symbol.for("lunora.failedTurnUsage"),b=t=>{if(typeof t!="object"||t===null)return;const e=t[y];if(e!==void 0)return{usage:{inputTokenDetails:{cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens},inputTokens:e.inputTokens,outputTokenDetails:{reasoningTokens:e.reasoningTokens},outputTokens:e.outputTokens,totalTokens:e.totalTokens}}},v=t=>{const e=o(o(t,"providerMetadata"),"gateway"),s=o(o(t,"response"),"headers"),a=k=>{const g=o(s,"get"),p=typeof g=="function"?g.call(s,k):o(s,k);return typeof p=="string"&&p.length>0?p:void 0},n={},i=o(e,"cost");typeof i=="number"&&Number.isFinite(i)&&(n.cost=i);const c=o(e,"cached"),r=o(e,"cacheStatus"),u=typeof r=="string"?r:a("cf-aig-cache-status");typeof c=="boolean"?n.cached=c:typeof u=="string"&&(n.cached=u.toUpperCase()==="HIT");const l=o(e,"logId")??o(e,"log_id"),d=typeof l=="string"&&l.length>0?l:a("cf-aig-log-id");return typeof d=="string"&&d.length>0&&(n.logId=d),Object.keys(n).length>0?n:void 0},x=t=>{const e=o(t,"toolCall"),s=o(e,"toolName"),a=typeof s=="string"?s:void 0,n=o(t,"toolOutput"),i=o(n,"type"),c=o(t,"success"),r=typeof c=="boolean"?c:i!=="tool-error",u=o(t,"toolExecutionMs");return{error:r?void 0:o(n,"error")??o(t,"error"),name:a,output:r?o(n,"output"):void 0,success:r,toolExecutionMs:typeof u=="number"?u:void 0}},C=t=>{const e=o(o(t,"toolCall"),"toolName");return typeof e=="string"?e:void 0},D=t=>o(o(t,"toolCall"),"input"),E=t=>{if(!Array.isArray(t))return;let e="";for(const s of t)if(o(s,"type")==="text"){const a=o(s,"text");typeof a=="string"&&(e+=a)}return e.length>0?e:void 0},F=t=>t instanceof Error?{message:t.message,name:t.name}:t;export{y as F,C as a,x as b,E as c,F as d,v as e,b as f,o as r,h as s,D as t};
@@ -0,0 +1 @@
1
+ import{defineWorkflow as i}from"@lunora/workflow";import{r as m}from"./agent-loop-BgOHoyg_.mjs";import{createStreamGenerate as p,createAgentGenerate as l,createEpisodeExtract as f,createGraphExtract as d,createCompact as u}from"./createAgentGenerate-DSLXAeY2.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-CE08SIwv.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};
@@ -0,0 +1 @@
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};
@@ -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-DBc9y7Np.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{a as f}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-CE08SIwv.mjs";import{LunoraError as o}from"@lunora/errors";import{h as g,B as w}from"./branch-marker-boZ00zmk.mjs";import{r as h}from"./workflow-binding-Dm9hBzx_.mjs";import{toFunctionReference as E,DEFAULT_AGENT_FUNCTION_PATHS as N}from"./AGENT_MODULE-CYBmT9SD.mjs";const _=(r,c,i={})=>{const{dispatch:u,exports:l}=i,s={},d=E(N.patchThread),p=()=>u??f({env:r,label:"@lunora/agent"});for(const e of c){const n=()=>{const t=h(r,l,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()(d,{instanceId:t,status:"cancelled"})}catch{}},publicRun:e.publicRun===!0,run:async(t,a)=>{if(g(t))throw new o("BAD_REQUEST",`@lunora/agent: run input ${w}`);return{id:(await n().create({...a?.id===void 0?{}:{id:a.id},params:t})).id}},sendEvent:async(t,a)=>{await(await n().get(t)).sendEvent(a)},status:async t=>(await n().get(t)).status()}}return s};export{_ as default};
@@ -0,0 +1,3 @@
1
+ import{jsonSchema as O}from"@ai-sdk/provider-utils";import{usageStatus as j}from"@lunora/ai/create";import{LunoraError as P}from"@lunora/errors";import{r as R}from"./agent-ai-CP87uSoZ.mjs";import{F as v,s as b}from"./common-DBc9y7Np.mjs";const m=e=>({...e,status:j(e)}),k=e=>m(b(e)),x=e=>e.map(t=>{const o={id:t.toolCallId,input:t.input,name:t.toolName};return t.invalid!==!0?o:{...o,invalid:t.error instanceof Error?t.error.message:String(t.error)}}),h=(e,t)=>{if(typeof e=="function")return e(t);if(typeof e=="string"){const o=R(t);if(!o)throw new P("INTERNAL",`@lunora/agent: the agent model "${e}" is a Workers AI id but there is no \`AI\` binding on the workflow env — declare the ai binding in wrangler.jsonc`);return o.model(e)}return e};let T;const f=()=>(T??=import("ai").catch(e=>{throw T=void 0,e}),T),q=(e,t,o)=>{const r=h(t.model,o),n={};for(const[a,u]of Object.entries(t.tools??{}))n[a]=e.tool({description:u.description,inputSchema:e.asSchema(u.inputSchema)});const i=t.output===void 0?void 0:e.Output.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:r,output:i,staticSettings:s,tools:n}},E=(e,t)=>{let o;return()=>(o??=f().then(r=>({ai:r,base:q(r,e,t)})).catch(r=>{throw o=void 0,r}),o)},S=(e,{activeTools:t,messages:o,model:r,signal:n,toolChoice:i})=>{const{defaultModel:s,output:a,staticSettings:u,tools:l}=e,d=t===void 0?l:Object.fromEntries(Object.entries(l).filter(([g])=>t.includes(g)));return{messages:o,model:r??s,...u,...Object.keys(d).length>0?{tools:d}:{},...i===void 0?{}:{toolChoice:i},...a===void 0?{}:{output:a},...n===void 0?{}:{abortSignal:n}}},M=e=>e instanceof Error?e:new Error(`model stream failed: ${String(e)}`,{cause:e}),N=e=>({inputTokens:{cacheRead:e?.inputTokens?.cacheRead,cacheWrite:e?.inputTokens?.cacheWrite,noCache:void 0,total:e?.inputTokens?.total},outputTokens:{reasoning:e?.outputTokens?.reasoning,text:void 0,total:e?.outputTokens?.total}}),_=e=>{if(e===void 0)return m(void 0);const t=e.inputTokens?.total,o=e.outputTokens?.total,r=t===void 0||o===void 0?void 0:t+o;return m(b({inputTokens:t,inputTokenDetails:{cacheReadTokens:e.inputTokens?.cacheRead,cacheWriteTokens:e.inputTokens?.cacheWrite},outputTokens:o,outputTokenDetails:{reasoningTokens:e.outputTokens?.reasoning},totalTokens:r}))},y=(e,t)=>{const o=new Error(e.raw===void 0?"model finished with an error reason":`model finished with an error reason (provider reason: ${e.raw})`,{cause:e});return o[v]=_(t),o},B=e=>{if(!(typeof e!="object"||e===null))return e[v]},I=(e,t)=>e.wrapLanguageModel({middleware:{wrapGenerate:async({doGenerate:o})=>{const r=await o();if(r.finishReason.unified==="error")throw y(r.finishReason,r.usage);return r},wrapStream:async({doStream:o})=>{const{stream:r,...n}=await o();let i=!1;return{...n,stream:r.pipeThrough(new TransformStream({flush:s=>{i||s.enqueue({error:new Error("model stream ended without a finish part"),type:"error"})},transform:(s,a)=>{if(s.type==="finish"&&(i=!0,s.finishReason.unified==="error")){a.enqueue({...s,usage:N(s.usage)}),a.enqueue({error:y(s.finishReason,s.usage),type:"error"});return}a.enqueue(s)}}))}}},model:t}),p=(e,t)=>typeof t=="string"?t:I(e,t),H=(e,t)=>{const o=E(e,t);return async r=>{const{ai:n,base:i}=await o(),s=S(i,r),a=await n.generateText({...s,model:p(n,s.model)});return{text:a.text,toolCalls:x(a.toolCalls),usage:k(a.usage),...i.output===void 0?{}:{output:a.output}}}},X=(e,t)=>{const o=E(e,t);return async(r,n)=>{const{ai:i,base:s}=await o(),a=S(s,r),u=i.streamText({...a,model:p(i,a.model)});let l="";try{for await(const c of u.stream){if(c.type==="error")throw M(c.error);c.type==="text-delta"&&(l+=c.text,n(c.text))}}catch(c){if(!r.signal?.aborted)throw c}if(r.signal?.aborted)return{text:l,toolCalls:[],usage:m(void 0)};const[d,g,A,C]=await Promise.all([u.text,u.toolCalls,u.usage,s.output===void 0?Promise.resolve(void 0):u.output]);return{text:d,toolCalls:x(g),usage:k(A),...s.output===void 0?{}:{output:C}}}},U=O({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"}),$=(e,t)=>["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: ${e}`,"",`Assistant: ${t}`].join(`
2
+ `),J=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{output:i}=await n.generateText({model:p(n,h(o,t)),output:n.Output.object({schema:U}),prompt:$(r,e)});return i},G=(e,t)=>["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: ${e}`,"",`Assistant: ${t}`].join(`
3
+ `),K=()=>async({assistantText:e,env:t,model:o,userInput:r})=>{const n=await f(),{text:i}=await n.generateText({model:p(n,h(o,t)),prompt:G(r,e)});return{summary:i.trim()}},w="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.",W=" An existing brief of the earlier conversation is included above. UPDATE that brief: keep every still-relevant fact from it and fold in the newly aged-out messages. Do not replace it with a summary of only the new messages.",Q=()=>async({env:e,messages:t,model:o,previousSummary:r})=>{const n=await f(),{text:i}=await n.generateText({messages:t,model:p(n,h(o,e)),system:r===void 0?w:`${w}${W}`});return i.trim()};export{H as createAgentGenerate,Q as createCompact,K as createEpisodeExtract,J as createGraphExtract,X as createStreamGenerate,h as resolveAgentModel,B as usageOfFailedTurn};
@@ -0,0 +1,3 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{a as f,i as m}from"./agent-loop-BgOHoyg_.mjs";import{collectAgenticMemoryTools as g}from"./collectAgenticMemoryTools-BWdIhOfY.mjs";import{agentAsTool as p}from"./agentAsTool-CA7Sha2i.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-CYBmT9SD.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-DBc9y7Np.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,18 @@
1
+ import{jsonSchema as m}from"@ai-sdk/provider-utils";import{LunoraError as y}from"@lunora/errors";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=m({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
+ const format = (value) => { if (typeof value === "string") return value; try { return JSON.stringify(value); } catch { return String(value); } };
3
+ const record = (...values) => { if (logs.length < ${String(f)}) logs.push(values.map(format).join(" ")); };
4
+ const sandboxConsole = { debug: record, error: record, info: record, log: record, warn: record };
5
+ const run = async (console) => {
6
+ ${e}
7
+ };
8
+ export default {
9
+ async fetch() {
10
+ try {
11
+ const value = await run(sandboxConsole);
12
+ return new Response(JSON.stringify({ logs, value: value === undefined ? null : value }));
13
+ } catch (error) {
14
+ return new Response(JSON.stringify({ error: error instanceof Error ? (error.stack ?? error.message) : String(error), logs }));
15
+ }
16
+ },
17
+ };
18
+ `,E=e=>e instanceof Error?e.message:String(e),_=async(e,r)=>{const o=e.body?.getReader();if(o===void 0)return"";const t=new TextDecoder;let n="",a=0;for(;;){const{done:s,value:i}=await o.read();if(s)break;if(a+=i.byteLength,a>r){await o.cancel();return}n+=t.decode(i,{stream:!0})}return n+t.decode()},L=e=>(Array.isArray(e)?e:[]).slice(0,f).map(r=>String(r).slice(0,v)),A=async(e,r,o)=>{let t;const n=new Promise(s=>{t=setTimeout(()=>{s({error:`the script did not finish within ${String(p)} ms`,logs:[]})},p)}),a=async()=>{const i=await e.load({compatibilityDate:b,env:{},globalOutbound:null,limits:{cpuMs:o,subRequests:0},mainModule:"main.js",modules:{"main.js":w(r)}}).getEntrypoint().fetch("https://sandbox/"),l=await _(i,g);if(l===void 0)return{error:`the script's result is over ${String(g)} bytes — return less`,logs:[]};const c=JSON.parse(l),d=L(c.logs);return typeof c.error=="string"?{error:c.error,logs:d}:{logs:d,value:c.value}};try{return await Promise.race([a(),n])}catch(s){return{error:E(s),logs:[]}}finally{clearTimeout(t)}},M=(e={})=>{const r=e.cpuMs??S;if(!Number.isInteger(r)||r<=0)throw new y("INTERNAL","@lunora/agent: jsCodeTool `cpuMs` must be a positive integer");return{description:e.description??T,execute:async(o,t)=>{const n=t.env[u];return typeof n?.load!="function"?{error:`jsCodeTool: no Worker Loader binding "${u}" on env — declare \`"worker_loaders": [{ "binding": "${u}" }]\` in wrangler.jsonc`,logs:[]}:A(n,o.code,r)},inputSchema:h,isLunoraAgentTool:!0}};export{M as jsCodeTool};
@@ -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-DdXFbng-.mjs";const T="entities",x="edges",h=`${_}_${T}`,w=`${_}_${x}`,X={[T]:A({createdAt:e.number(),firstMessageKey:e.optional(e.string()),name:e.string(),owner:e.string(),type:e.optional(e.string()),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerName",["owner","name"],{unique:!0}).index("byOwnerUpdatedAt",["owner","updatedAt"]).public(),[x]:A({createdAt:e.number(),dstName:e.string(),label:e.string(),messageKey:e.string(),owner:e.string(),srcName:e.string(),updatedAt:e.number(),weight:e.optional(e.number())}).index("byOwnerSrc",["owner","srcName"]).index("byOwnerDst",["owner","dstName"]).index("byTriple",["owner","srcName","label","dstName"],{unique:!0}).public()},E=64,O=2,G=4,D=8,C=32,R=500,I=/\s+/gu,K=/[^\p{L}\p{N}]+/u,N=t=>t.trim().replaceAll(I," ").toLowerCase(),L=t=>t.toLowerCase().split(K).filter(o=>o.length>=2),P=t=>({dstName:t.dstName,label:t.label,srcName:t.srcName,weight:t.weight??1}),U=(t,o)=>o.weight-t.weight||t.label.localeCompare(o.label)||t.srcName.localeCompare(o.srcName)||t.dstName.localeCompare(o.dstName),$=(t,o)=>o.some(n=>t.includes(n)||n.includes(t)),v=t=>t.map(o=>`- ${o.srcName} —[${o.label}]→ ${o.dstName}`).toSorted((o,n)=>o.localeCompare(n)).join(`
2
+ `),H=t=>`${t.srcName}\0${t.label}\0${t.dstName}`,B=(t,o,n,r)=>{const a=H(t);r.collectedKeys.has(a)||(r.collectedKeys.add(a),r.collected.push(t));const l=t.srcName===o?t.dstName:t.srcName;!r.seen.has(l)&&r.seen.size<n.maxNodes&&(r.seen.add(l),r.next.push(l))},F=async(t,o,n)=>{const r={collected:[],collectedKeys:new Set,next:[],seen:new Set(o)};let a=o.slice(0,n.maxNodes);for(let l=0;l<n.depth&&a.length>0;l+=1){r.next=[];for(const m of a){const p=(await t(m)).toSorted(U).slice(0,n.fanOut);for(const s of p)B(s,m,n,r)}a=r.next}return r.collected},{mutation:M,query:W}=q.dataModel().create(),Y=()=>{const t=M.input({entities:e.array(e.object({name:e.string(),type:e.optional(e.string())})),messageKey:e.string(),owner:e.string(),relations:e.array(e.object({confidence:e.optional(e.number()),dst:e.string(),label:e.string(),src:e.string()}))}).mutation(async({args:n,ctx:r})=>{const a=Date.now(),l=async(s,i)=>{const c=N(s);if(c.length===0)return;const d=await r.db.query(h).withIndex("byOwnerName",g=>g.eq("owner",n.owner).eq("name",c)).first();return d?(i!==void 0&&d.type===void 0&&await r.db.patch(h,d._id,{type:i,updatedAt:a}),c):(await r.db.insert(h,{createdAt:a,name:c,owner:n.owner,updatedAt:a,weight:1,...S({firstMessageKey:n.messageKey,type:i})}),c)},m=async s=>{const i=N(s.src),c=N(s.dst),d=N(s.label);if(i.length===0||c.length===0||d.length===0||i===c)return!1;await l(i),await l(c);const g=s.confidence??1,y=await r.db.query(w).withIndex("byTriple",b=>b.eq("owner",n.owner).eq("srcName",i).eq("label",d).eq("dstName",c)).first();if(y){const b=y.weight??1;await r.db.patch(w,y._id,{updatedAt:a,weight:Math.max(b,g)})}else await r.db.insert(w,{createdAt:a,dstName:c,label:d,messageKey:n.messageKey,owner:n.owner,srcName:i,updatedAt:a,weight:g});return!0};let u=0;for(const s of n.entities.slice(0,E))await l(s.name,s.type)!==void 0&&(u+=1);let p=0;for(const s of n.relations.slice(0,E))await m(s)&&(p+=1);return{entities:u,relations:p}}),o=W.input({depth:e.optional(e.number()),fanOut:e.optional(e.number()),maxNodes:e.optional(e.number()),maxSeeds:e.optional(e.number()),owner:e.string(),query:e.string()}).query(async({args:n,ctx:r})=>{const a=L(n.query);if(a.length===0)return{context:""};const m=(await r.db.query(h).withIndex("byOwnerUpdatedAt",s=>s.eq("owner",n.owner)).order("desc").take(R)).filter(s=>$(s.name,a)).toSorted((s,i)=>(i.weight??1)-(s.weight??1)||s.name.localeCompare(i.name)).slice(0,n.maxSeeds??G).map(s=>s.name);if(m.length===0)return{context:""};const p=await F(async s=>{const[i,c]=await Promise.all([r.db.query(w).withIndex("byOwnerSrc",d=>d.eq("owner",n.owner).eq("srcName",s)).collect(),r.db.query(w).withIndex("byOwnerDst",d=>d.eq("owner",n.owner).eq("dstName",s)).collect()]);return[...i,...c].map(d=>P(d))},m,{depth:n.depth??O,fanOut:n.fanOut??D,maxNodes:n.maxNodes??C});return{context:v(p)}});return{agentGraphTraverse:f(o),agentGraphUpsert:f(t)}};export{Y as graphComponent,X as graphTables,N as normalizeEntityName};
@@ -0,0 +1 @@
1
+ import{usageStatus as X,USAGE_ATTRIBUTE as _,estimateModelCost as Y}from"@lunora/ai/create";import{a as G,r as d,f as H,s as q,e as j,c as K,t as Q}from"./common-DBc9y7Np.mjs";import{c as Z}from"./in-flight-calls-C9QGq8uH.mjs";const W=t=>`${String(Math.round(t))}000000`,ee=Array.from({length:256},(t,o)=>o.toString(16).padStart(2,"0")),O=512,$=new Uint8Array(O);let k=O;const D=(t,o,n)=>{let l="";for(let i=0;i<n;i+=1)l+=ee[t[o+i]];return l},F=t=>{if(t>O){const n=new Uint8Array(t);return crypto.getRandomValues(n),D(n,0,t)}k+t>O&&(crypto.getRandomValues($),k=0);const o=D($,k,t);return k+=t,o},w=(t,o)=>typeof o=="boolean"?{key:t,value:{boolValue:o}}:typeof o=="number"?Number.isFinite(o)?Number.isSafeInteger(o)?{key:t,value:{intValue:String(o)}}:{key:t,value:{doubleValue:o}}:{key:t,value:{stringValue:String(o)}}:{key:t,value:{stringValue:o}},te=(t,o,n)=>{const l={},i=new Map,S=(p,h)=>{const b=p.toLowerCase(),x=i.get(b);x===void 0?(i.set(b,p),l[p]=h):l[x]=h};for(const[p,h]of Object.entries(t))S(p,h);for(const[p,h]of Object.entries(o??{}))S(p,h);return n!==void 0&&n.length>0&&S("authorization",`Bearer ${n}`),l},oe=t=>Array.isArray(t)?t:[t],ne=(t,o)=>{const n={"service.name":t};for(const[l,i]of Object.entries({}))n[l]=i;return Object.entries(n).map(([l,i])=>w(l,i))},se=(t,o,n,l)=>({resourceSpans:[{resource:{attributes:ne(n)},scopeSpans:[{scope:{name:o},spans:oe(t)}]}]}),re=50,ae=256*1024,ce=new TextEncoder,r=(t,o,n)=>{if(n!=null){if(typeof n=="boolean"||typeof n=="number"||typeof n=="string"){t.push(w(o,n));return}t.push(w(o,JSON.stringify(n)))}},ie=(t,o)=>{(async()=>{let l;try{l=await t}catch(i){o(!1,i instanceof Error?i.message:String(i),void 0);return}o(!0,void 0,l)})().catch(()=>{})},ge=t=>{const{conversationId:o,endpoint:n,headers:l,recordInputs:i=!1,recordOutputs:S=!1,token:p,traceId:h,waitUntil:b}=t,x=t.serviceName??"lunora";let A=n;for(;A.endsWith("/");)A=A.slice(0,-1);const P=`${A}/v1/traces`,z=te({"content-type":"application/json"},l,p);let I=[],N=0;const R=()=>{if(I.length===0)return;const e=I;I=[],N=0;try{const s=fetch(P,{body:JSON.stringify(se(e,"@lunora/agent",x)),headers:z,method:"POST"}).catch(()=>{});b?.(s)}catch{}},U=(e,s,a,u,y)=>{const f={attributes:y,endTimeUnixNano:W(Date.now()),kind:1,name:e,spanId:F(8),startTimeUnixNano:W(s),status:a?{code:1}:{code:2,message:u??""},traceId:h??F(16)};I.push(f),N+=ce.encode(JSON.stringify(f)).byteLength,(I.length>=re||N>=ae)&&R()},T=Z((e,s,a,u)=>{const{messages:y,modelId:f,provider:C,result:m,startTs:J}=e,c=[];r(c,"gen_ai.operation.name","chat"),r(c,"gen_ai.request.model",f),r(c,"gen_ai.system",C),r(c,"gen_ai.conversation.id",o);const g=q(d(u,"usage")??d(m,"usage")),L=X(g);r(c,"lunora.usage.status",L),r(c,_.inputTokens,g?.inputTokens),r(c,_.outputTokens,g?.outputTokens),r(c,"gen_ai.usage.total_tokens",g?.totalTokens),r(c,_.cacheReadTokens,g?.cacheReadTokens),r(c,_.cacheWriteTokens,g?.cacheWriteTokens),r(c,_.reasoningTokens,g?.reasoningTokens);const E=j(u)??j(m);E&&(r(c,"gen_ai.response.cached",E.cached),r(c,"cf.aig.log_id",E.logId));const M=E?.cost,V=M??(typeof f=="string"&&L==="complete"?Y(f,{cacheReadTokens:g?.cacheReadTokens,cacheWriteTokens:g?.cacheWriteTokens,inputTokens:g?.inputTokens,outputTokens:g?.outputTokens}):void 0);V!==void 0&&(r(c,"gen_ai.usage.cost",V),r(c,"lunora.usage.cost.source",M===void 0?"estimated":"provider")),i&&r(c,"gen_ai.prompt",y),S&&r(c,"gen_ai.completion",K(d(u,"content")??d(m,"content"))),U(typeof f=="string"?`chat ${f}`:"language_model_call",J,s,a,c)}),v=(e,s,a)=>{const u=d(e,"callId");if(typeof u!="string")return;let y=a;s instanceof Error?y=s.message:typeof s=="string"&&s.length>0&&(y=s),T.close(u,!1,y,H(s))},B=e=>({messages:d(e,"messages"),modelId:d(e,"modelId"),provider:d(e,"provider"),result:void 0,startTs:Date.now()});return{flush:R,executeLanguageModelCall:async e=>{const{callId:s}=e;T.open(s,()=>B(e));try{const a=await e.execute(),u=T.get(s);return u!==void 0&&(u.result=a),a}catch(a){throw T.close(s,!1,a instanceof Error?a.message:String(a),H(a)),a}},onAbort:e=>{v(e,d(e,"reason"),"aborted")},onEnd:e=>{T.fromLifecycle(e)},onError:e=>{v(e,d(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{typeof d(e,"callId")=="string"&&T.fromLifecycle(e)},onLanguageModelCallStart:e=>{const s=d(e,"callId");typeof s=="string"&&T.open(s,()=>B(e))},onStepEnd:e=>{T.fromLifecycle(e)},executeTool:e=>{const s=Date.now(),a=G(e),u=e.execute();return ie(u,(f,C)=>{const m=[];r(m,"gen_ai.operation.name","execute_tool"),r(m,"gen_ai.tool.name",a),r(m,"gen_ai.tool.call.id",d(e,"toolCallId")),i&&r(m,"gen_ai.tool.input",Q(e)),U(typeof a=="string"?`execute_tool ${a}`:"execute_tool",s,f,C,m)}),u}}};export{ge as otlpTelemetry};
@@ -0,0 +1 @@
1
+ const i=e=>Number.isInteger(e)&&e>0;export{i};
@@ -0,0 +1 @@
1
+ import"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-CE08SIwv.mjs";import"./workflow-binding-Dm9hBzx_.mjs";import"./component-shared-DdXFbng-.mjs";import"./createAgentGenerate-DSLXAeY2.mjs";import{b as g,a as l,c as u,r as b,s as f}from"./agent-loop-BgOHoyg_.mjs";import"./buildModelMessages-DVQdQ7_1.mjs";import"../naming.mjs";import"./AGENT_MODULE-CYBmT9SD.mjs";import"./positive-integer-ztHqqpBk.mjs";import"./SecretUnavailableError-BCp40Leh.mjs";import"./tool-output-Cmk3JWMG.mjs";export{g as addUsage,l as approvalTimeoutMs,u as compactHistory,b as runAgentLoop,f as splitForCompaction};
@@ -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-hIZ7r1ST.mjs";import"./agent-loop-BgOHoyg_.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};
@@ -0,0 +1 @@
1
+ const _=12e4,S=15e4,T=12e4,O=12e4,E=15e4;export{S,E as a,_ as b,T as c,O as d};
@@ -0,0 +1,7 @@
1
+ import{LunoraError as c,isLunoraError as $}from"@lunora/errors";import{initLunora as N}from"@lunora/server";import{v as s}from"@lunora/values";import{b as v,c as A,d as _}from"./sandbox-budgets-DDvj4Orr.mjs";const y=async(o,t,n)=>{if(o===null)return{overflowed:!1,text:""};const r=o.getReader(),e=new TextDecoder,a=()=>{r.cancel().catch(()=>{})};n?.addEventListener("abort",a);let i="",l=0,p=!1;try{for(;n?.aborted!==!0;){const{done:h,value:u}=await r.read();if(h)break;if(l+u.byteLength>t){p=!0,i+=e.decode(u.subarray(0,t-l),{stream:!0});break}l+=u.byteLength,i+=e.decode(u,{stream:!0})}i+=e.decode()}finally{n?.removeEventListener("abort",a),r.cancel().catch(()=>{})}if(n?.aborted===!0)throw n.reason;return{overflowed:p,text:i}},{internalAction:R}=N.dataModel().create(),L=()=>globalThis.document?.documentElement?.outerHTML??"",d=1e6,w=1e6,O=20,E=new TextEncoder,B=o=>{const t=[`exit code: ${String(o.code)}`];return o.stdout.length>0&&t.push(`stdout:
2
+ ${o.stdout}`),o.stderr.length>0&&t.push(`stderr:
3
+ ${o.stderr}`),t.join(`
4
+
5
+ `)},D=async(o,t)=>{const n=AbortSignal.timeout(_);try{const r=await o.fetch(t.path??"/",{...t.body===void 0?{}:{body:t.body},method:t.method??"GET",signal:n}),e=await y(r.body,w,n);return e.overflowed?`${e.text}
6
+
7
+ [truncated at ${String(w)} bytes]`:e.text}catch(r){return`fetch failed: ${r instanceof Error?r.message:String(r)}`}},x=(o,t)=>{if(t.instance===void 0||t.instance.length===0)throw new c("BAD_REQUEST","@lunora/agent: sandbox container op arrived with no `instance` — the tool pins the thread's own container");return o.get(t.instance)},k=async(o,t)=>{const n=x(o,t);if(t.op==="exec")try{return B(await n.exec(t.command??"",{args:t.args??[],timeoutMs:A}))}catch(r){return`exec failed: ${r instanceof Error?r.message:String(r)}`}if(t.op==="fetch")return await D(n,t);throw new c("INTERNAL",`@lunora/agent: sandbox container op "${t.op}" is not supported`)},S=(o,t)=>new c("INTERNAL",`@lunora/agent: sandbox ${o} op found no R2 bucket "${t}" on env — declare the r2_bucket binding in wrangler.jsonc and run codegen`),g=(o,t)=>{const n=o.env?.[t.bucket??""];return n&&typeof n.get=="function"?n:void 0},b=(o,t)=>{if(!o)throw S("browser",t.bucket??"");return o},T=o=>{let t=0,n=o.length;for(;t<n&&o[t]==="/";)t+=1;for(;n>t&&o[n-1]==="/";)n-=1;return o.slice(t,n)},f=(o,t)=>{const n=T(o),r=[];for(const a of t.split("/"))if(!(a===""||a===".")){if(a===".."){if(r.length===0)throw new c("BAD_REQUEST","@lunora/agent: fs path escapes the sandbox root");r.pop();continue}r.push(a)}const e=r.join("/");return n&&e?`${n}/${e}`:n||e},F=async(o,t,n)=>{const r=t.length>0?`${t}/`:"",e=n.length>0?n.length+1:0,a=[];let i;for(let l=0;l<O;l+=1){const p=await o.list({prefix:r,...i===void 0?{}:{cursor:i}});for(const h of p.objects)a.push(h.key.slice(e));if(!p.truncated||p.cursor===void 0)return{entries:a,truncated:!1};i=p.cursor}return{entries:a,truncated:!0}},m=async(o,t,n,r,e)=>{const a=f(t,n);return await o.put(a,r),{bytes:r.byteLength,key:a,mediaType:e}},I=async(o,t,n)=>{const r=t.url??"",e={timeoutMs:v};switch(t.op){case"content":return o.content(r,e);case"pdf":return m(b(n,t),t.root??"",t.path??"",await o.pdf(r,e),"application/pdf");case"scrape":return o.scrape(r,L,e);case"screenshot":{const a=b(n,t),i=await o.screenshot(r,{...e,...t.fullPage===void 0?{}:{fullPage:t.fullPage},...t.type===void 0?{}:{type:t.type}});return m(a,t.root??"",t.path??"",i,t.type==="jpeg"?"image/jpeg":"image/png")}default:throw new c("INTERNAL",`@lunora/agent: sandbox browser op "${t.op}" is not supported`)}},M=async(o,t,n)=>{const r=T(t),e=f(t,n.path??"");switch(n.op){case"ls":{const{entries:a,truncated:i}=await F(o,e,r);return i?{entries:a,truncated:!0}:{entries:a}}case"read":{const a=await o.head(e);if(a&&a.size>d)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${n.path??""}" is ${String(a.size)} bytes (max ${String(d)})`);const i=await o.get(e);if(!i)throw new c("NOT_FOUND",`@lunora/agent: fs read: no file at "${n.path??""}"`);return i.text()}case"rm":return await o.delete(e),{path:n.path??"",removed:!0};case"stat":{const a=await o.head(e);return a?{exists:!0,size:a.size}:{exists:!1}}case"write":{const a=n.content??"",i=E.encode(a).length;if(i>d)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(i)} bytes exceeds the max (${String(d)})`);return await o.put(e,a),{bytes:i,path:n.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${n.op}" is not supported`)}},U=o=>o.slice(0,o.lastIndexOf("/"))||"/",C=async(o,t)=>{const{files:n}=x(o,t);if(n===void 0)throw new c("INTERNAL","@lunora/agent: containerFsTool needs ctx.containers.<name>.get(id).files — update @lunora/container");const r=`/${f(t.root??"/",t.path??"")}`;switch(t.op){case"ls":return{entries:(await n.readDirectory(r)).map(a=>a.type==="directory"?`${a.name}/`:a.name)};case"read":{const{size:e}=await n.stat(r);if(Number(e)>d)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${t.path??""}" is ${String(e)} bytes (max ${String(d)})`);const a=await n.readFile(r),i=await y(a.body,d);if(i.overflowed)throw new c("BAD_REQUEST",`@lunora/agent: fs read: "${t.path??""}" exceeds ${String(d)} bytes`);return i.text}case"rm":return await n.remove(r,{force:!0}),{path:t.path??"",removed:!0};case"stat":try{const{size:e,type:a}=await n.stat(r);return{exists:!0,size:Number(e),type:a}}catch(e){if($(e)&&e.code==="NOT_FOUND")return{exists:!1};throw e}case"write":{const e=t.content??"",a=E.encode(e).length;if(a>d)throw new c("BAD_REQUEST",`@lunora/agent: fs write: ${String(a)} bytes exceeds the max (${String(d)})`);return await n.mkdir(U(r),{recursive:!0}),await n.writeFile(r,e),{bytes:a,path:t.path??"",wrote:!0}}default:throw new c("INTERNAL",`@lunora/agent: sandbox fs op "${t.op}" is not supported`)}},P=()=>({invoke:R.input({args:s.optional(s.array(s.string())),body:s.optional(s.string()),bucket:s.optional(s.string()),command:s.optional(s.string()),content:s.optional(s.string()),fullPage:s.optional(s.boolean()),instance:s.optional(s.string()),kind:s.union(s.literal("browser"),s.literal("container"),s.literal("containerFs"),s.literal("fs")),method:s.optional(s.string()),name:s.optional(s.string()),op:s.string(),path:s.optional(s.string()),root:s.optional(s.string()),selector:s.optional(s.string()),type:s.optional(s.string()),url:s.optional(s.string())}).action(async({args:t,ctx:n})=>{const r=n,e=t;if(e.kind==="browser"){if(!r.browser)throw new c("INTERNAL","@lunora/agent: sandbox browser op needs `ctx.browser` — install @lunora/browser and run codegen");return I(r.browser,e,g(r,e))}if(e.kind==="fs"){const l=g(r,e);if(!l)throw S("fs",e.bucket??"");return M(l,e.root??"",e)}const a=e.name??"",i=r.containers?.[a];if(!i)throw new c("INTERNAL",`@lunora/agent: sandbox container op found no ctx.containers["${a}"] — declare the container in lunora/containers.ts and run codegen`);return e.kind==="containerFs"?C(i,e):k(i,e)})});export{f as resolveFsKey,C as runContainerFsOp,M as runFsOp,P as sandboxComponent};
@@ -0,0 +1 @@
1
+ import{usageStatus as x,USAGE_ATTRIBUTE as E}from"@lunora/ai/create";import{r as n,t as b,f as p,s as S,c as T}from"./common-DBc9y7Np.mjs";import{c as h}from"./in-flight-calls-C9QGq8uH.mjs";const d=(c,u)=>typeof c=="string"&&c.length>0?c:u,k=c=>{const{functionId:u,recordInputs:f=!1,recordOutputs:y=!1,Sentry:g}=c,s=h((e,o,a,r)=>{const t={},l=S(n(r,"usage")??n(e.result,"usage"));t["lunora.usage.status"]=x(l);const I={totalTokens:"gen_ai.usage.total_tokens",...E};for(const[i,_]of Object.entries(I))l?.[i]!==void 0&&(t[_]=l[i]);if(y){const i=T(n(r,"content")??n(e.result,"content"));i!==void 0&&(t["gen_ai.completion"]=i)}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()}),m=(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,p(o))};return{executeLanguageModelCall:e=>{const{callId:o}=e,a={"gen_ai.operation.name":d(u,"language_model_call"),"gen_ai.request.model":n(e,"modelId"),"gen_ai.system":n(e,"provider")};return f&&(a["gen_ai.prompt"]=n(e,"messages")),g.startSpanManual({attributes:a,name:d(u,"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),p(t)),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 f&&(a["gen_ai.tool.input"]=b(e)),g.startSpan({attributes:a,name:`execute_tool ${d(o,"tool")}`,op:"gen_ai.execute_tool"},()=>e.execute())},onAbort:e=>{m(e,n(e,"reason"),"aborted")},onEnd:e=>{s.fromLifecycle(e)},onError:e=>{g.captureException(n(e,"error")??e),m(e,n(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{typeof n(e,"callId")=="string"&&s.fromLifecycle(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};