@lunora/agent 1.0.0-alpha.28 → 1.0.0-alpha.281
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -2
- package/dist/channels.d.mts +23 -12
- package/dist/channels.d.ts +23 -12
- package/dist/channels.mjs +1 -1
- package/dist/component.d.mts +54 -2
- package/dist/component.d.ts +54 -2
- package/dist/component.mjs +2 -2
- package/dist/core.d.mts +204 -0
- package/dist/core.d.ts +204 -0
- package/dist/core.mjs +1 -0
- package/dist/inbound.d.mts +12 -10
- package/dist/inbound.d.ts +12 -10
- package/dist/inbound.mjs +1 -1
- package/dist/index.d.mts +172 -143
- package/dist/index.d.ts +172 -143
- package/dist/index.mjs +1 -1
- package/dist/naming.d.mts +15 -7
- package/dist/naming.d.ts +15 -7
- package/dist/naming.mjs +1 -1
- package/dist/packem_chunks/createAgentGenerate.mjs +3 -0
- package/dist/packem_chunks/otlpTelemetry.mjs +1 -0
- package/dist/packem_chunks/resolve-run.mjs +1 -0
- package/dist/packem_chunks/runAgentLoop.mjs +3 -0
- package/dist/packem_shared/AGENT_MODULE-CYBmT9SD.mjs +1 -0
- package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs +1 -0
- package/dist/packem_shared/SecretUnavailableError-BsJMGfML.mjs +1 -0
- package/dist/packem_shared/VoiceSessionDO-CdvG2L-D.mjs +1 -0
- package/dist/packem_shared/adaptMcpResult-CA-3ovJd.mjs +2 -0
- package/dist/packem_shared/agent-ai-CP87uSoZ.mjs +1 -0
- package/dist/packem_shared/agentAsTool-BF-7Dnzy.mjs +1 -0
- package/dist/packem_shared/app-call-options-BE0CQ6Qg.mjs +1 -0
- package/dist/packem_shared/braintrustTelemetry-Ck09dC4G.mjs +1 -0
- package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
- package/dist/packem_shared/buildModelMessages-DVQdQ7_1.mjs +5 -0
- package/dist/packem_shared/codeTool-Cn8TuNjk.mjs +1 -0
- package/dist/packem_shared/collectAgenticMemoryTools-X7AqELV3.mjs +1 -0
- package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
- package/dist/packem_shared/common-DBc9y7Np.mjs +1 -0
- package/dist/packem_shared/compileAgentWorkflow-yZB8fbYc.mjs +1 -0
- package/dist/packem_shared/component-shared--SPcu0Iw.mjs +1 -0
- package/dist/packem_shared/consoleTelemetry-Cl-WQEsZ.mjs +1 -0
- package/dist/packem_shared/createAgentContext-TMvmjncE.mjs +1 -0
- package/dist/packem_shared/defineAgent-6Ih7L9E9.mjs +3 -0
- package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
- package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
- package/dist/packem_shared/functionTool-Cf433Hdo.mjs +1 -0
- package/dist/packem_shared/in-flight-calls-C9QGq8uH.mjs +1 -0
- package/dist/packem_shared/inbound-shard-A7S7dnf_.mjs +1 -0
- package/dist/packem_shared/jsCodeTool-BJB3Fpm2.mjs +18 -0
- package/dist/packem_shared/jsonSchema-fhoaBWpN.mjs +1 -0
- package/dist/packem_shared/memory-JI0lUu84.mjs +1 -0
- package/dist/packem_shared/normalizeEntityName-BiUH5B5W.mjs +2 -0
- package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
- package/dist/packem_shared/run-shard-B7iMrAI0.mjs +1 -0
- package/dist/packem_shared/runVoiceTurn-DPa5UZ45.mjs +1 -0
- package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
- package/dist/packem_shared/sandboxComponent-Du0yENEO.mjs +7 -0
- package/dist/packem_shared/sentryTelemetry-B1BuLxxj.mjs +1 -0
- package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
- package/dist/packem_shared/{types.d-boAM2Yi1.d.mts → types.d-Bzy_Qah6.d.mts} +435 -34
- package/dist/packem_shared/{types.d-boAM2Yi1.d.ts → types.d-Bzy_Qah6.d.ts} +435 -34
- package/dist/packem_shared/voice-turn-B9omvXoR.mjs +1 -0
- package/dist/packem_shared/webSearchTool-BzXW0R4r.mjs +1 -0
- package/dist/packem_shared/withAgentScheduleShard-Bn3bdW5b.mjs +1 -0
- package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
- package/dist/packem_shared/wrapUntrusted-CEngnRHW.mjs +2 -0
- package/dist/reply.d.mts +58 -0
- package/dist/reply.d.ts +58 -0
- package/dist/reply.mjs +1 -0
- package/dist/sandbox.d.mts +159 -18
- package/dist/sandbox.d.ts +159 -18
- package/dist/sandbox.mjs +1 -1
- package/dist/skill-markdown.d.mts +36 -0
- package/dist/skill-markdown.d.ts +36 -0
- package/dist/skill-markdown.mjs +1 -0
- package/dist/telemetry/index.d.mts +165 -38
- package/dist/telemetry/index.d.ts +165 -38
- package/dist/telemetry/index.mjs +1 -1
- package/package.json +24 -9
- package/dist/packem_shared/AGENT_MODULE-BXx-tSCe.mjs +0 -1
- package/dist/packem_shared/VoiceSessionDO-CTaBSdXk.mjs +0 -1
- package/dist/packem_shared/adaptMcpResult-18G7zpFo.mjs +0 -2
- package/dist/packem_shared/agentAsTool-CJCTyAQG.mjs +0 -1
- package/dist/packem_shared/base64-jU-Ci6Tu.mjs +0 -1
- package/dist/packem_shared/braintrustTelemetry-CnOI5WAw.mjs +0 -1
- package/dist/packem_shared/buildModelMessages-Dm2wVNQy.mjs +0 -5
- package/dist/packem_shared/codeTool-DYJVy-bH.mjs +0 -1
- package/dist/packem_shared/collectAgenticMemoryTools-DBcP8dUa.mjs +0 -1
- package/dist/packem_shared/combineTelemetry-oLCV_EPV.mjs +0 -1
- package/dist/packem_shared/common-Dck97z3Y.mjs +0 -1
- package/dist/packem_shared/compileAgentWorkflow-C4xqSw82.mjs +0 -1
- package/dist/packem_shared/consoleTelemetry-CaoI-NGg.mjs +0 -1
- package/dist/packem_shared/createAgentContext-B1IfI7ro.mjs +0 -1
- package/dist/packem_shared/createAgentGenerate-BUVImo85.mjs +0 -3
- package/dist/packem_shared/createDispatchRunner-CQ8HXscn-BrqT0bIG.mjs +0 -1
- package/dist/packem_shared/defineAgent-CKhzzmys.mjs +0 -3
- package/dist/packem_shared/defineSkill-DfJxCwfZ.mjs +0 -1
- package/dist/packem_shared/functionTool-CWHhkYqd.mjs +0 -1
- package/dist/packem_shared/graph-component-B2YmC2eL.mjs +0 -2
- package/dist/packem_shared/memory-DNRyyp1b.mjs +0 -1
- package/dist/packem_shared/normalizeEntityName-BQpyssvL.mjs +0 -1
- package/dist/packem_shared/otlpTelemetry-DcW9mOLV.mjs +0 -1
- package/dist/packem_shared/runAgentLoop-DNAt-pGz.mjs +0 -3
- package/dist/packem_shared/runVoiceTurn-PkMsfG_v.mjs +0 -1
- package/dist/packem_shared/sandboxComponent-BhaGHsQZ.mjs +0 -1
- package/dist/packem_shared/sentryTelemetry-Dr2aPuvl.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="agents",a="sandbox",n=`${a}:invoke`,s={appendMessage:`${e}:agentAppendMessage`,approvalGranted:`${e}:agentApprovalGranted`,completeRun:`${e}:agentCompleteRun`,deleteMessage:`${e}:agentDeleteMessage`,ensureThread:`${e}:agentEnsureThread`,episodeRecall:`${e}:agentEpisodeRecall`,episodeUpsert:`${e}:agentEpisodeUpsert`,graphTraverse:`${e}:agentGraphTraverse`,graphUpsert:`${e}:agentGraphUpsert`,history:`${e}:agentHistory`,listMessages:`${e}:agentMessages`,patchThread:`${e}:agentPatchThread`,run:`${e}:agentRun`,setState:`${e}:agentSetState`,state:`${e}:agentState`,takeSecret:`${e}:agentTakeSecret`,discardSecret:`${e}:agentDiscardSecret`,openSecretRequest:`${e}:agentOpenSecretRequest`,settleSecretRequest:`${e}:agentSettleSecretRequest`},r=t=>typeof t=="string"?{__lunoraRef:t}:t;export{e as AGENT_MODULE,s as DEFAULT_AGENT_FUNCTION_PATHS,n as SANDBOX_INVOKE_PATH,a as SANDBOX_MODULE,r as toFunctionReference};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y,isLunoraError as H}from"@lunora/errors";const g=t=>{try{return t(),!0}catch{return!1}},V=new Set([Object.prototype,Function.prototype]),A=(t,e,r)=>{let n;for(let o=t;o!==null&&!V.has(o);o=Object.getPrototypeOf(o)){const a=Object.getOwnPropertyDescriptor(o,e)?.[r];typeof a=="function"&&(n=a)}return n},i=(t,e)=>A(t,e,"get"),k=A(Date.prototype,"getTime","value"),z=i(Map.prototype,"size"),q=i(Set.prototype,"size"),Y=i(ArrayBuffer.prototype,"byteLength"),m=typeof URL=="function"?i(URL.prototype,"href"):void 0,L=typeof URL=="function"?URL.prototype:void 0,Q=m!==void 0&&Function.prototype.toString.call(m).includes("[native code]"),D=A(Error,"isError","value"),P=Error.prototype,X=(t,e)=>typeof D=="function"?D(t):e!==null&&(e===P||P.isPrototypeOf(e)),Z=A(Map.prototype,"forEach","value"),tt=A(Set.prototype,"forEach","value"),I=Object.getPrototypeOf(Uint8Array.prototype),j={data:{buffer:i(DataView.prototype,"buffer"),byteLength:i(DataView.prototype,"byteLength"),byteOffset:i(DataView.prototype,"byteOffset")},typed:{buffer:i(I,"buffer"),byteLength:i(I,"byteLength"),byteOffset:i(I,"byteOffset")}},et=t=>Reflect.apply(k,t,[]),rt=t=>Reflect.apply(m,t,[]),nt=t=>{const e=[];return Reflect.apply(Z,t,[(r,n)=>e.push([n,r])]),e},ot=t=>{const e=[];return Reflect.apply(tt,t,[r=>e.push(r)]),e},at=t=>{const e=g(()=>Reflect.apply(j.typed.buffer,t,[]))?j.typed:j.data;return new Uint8Array(Reflect.apply(e.buffer,t,[]),Reflect.apply(e.byteOffset,t,[]),Reflect.apply(e.byteLength,t,[]))},st=t=>{if(Array.isArray(t))return"array";const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype?"plain":g(()=>Reflect.apply(k,t,[]))?"builtin-date":g(()=>Reflect.apply(z,t,[]))?"builtin-map":g(()=>Reflect.apply(q,t,[]))?"builtin-set":g(()=>Reflect.apply(Y,t,[]))?"builtin-array-buffer":ArrayBuffer.isView(t)?"builtin-view":X(t,e)?"builtin-error":m!==void 0&&(Q||L!==void 0&&e!==null&&(e===L||L.isPrototypeOf(e)))&&g(()=>Reflect.apply(m,t,[]))?"builtin-url":"other"},E=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},ct=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.codePointAt(n)??0;return r},s="$lunora.wire$",v=64,O=1024,it="__proto__",ut=/^-?\d+$/,x={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},B={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},U=(t,e,r)=>{e===it?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r},lt=t=>{const e=t.toString();if(e.length>O)throw new RangeError(`wire-codec: over-long bigint (max ${String(O)} digits)`);return[s,"bigint",e]},ft=t=>Number.isNaN(t)?[s,"nan"]:t===1/0?[s,"inf"]:t===-1/0?[s,"-inf"]:t,pt=(t,e)=>{const r=e(Object.fromEntries(Object.keys(t).map(a=>[a,t[a]]))),n=t,o=[s,"error",String(n.name),String(n.message),r];return t.cause!==void 0&&o.push(e(t.cause)),o},yt=t=>{const e=t.constructor.name,r=at(t);return e==="Uint8Array"?[s,"bytes",E(r)]:[s,"bytes",E(r),e]},dt=(t,e,r)=>{switch(e){case"builtin-array-buffer":return[s,"bytes",E(new Uint8Array(t)),"ArrayBuffer"];case"builtin-date":return[s,"date",r(et(t))];case"builtin-error":return pt(t,r);case"builtin-map":return[s,"map",nt(t).map(([n,o])=>[r(n),r(o)])];case"builtin-set":return[s,"set",ot(t).map(n=>r(n))];case"builtin-url":return[s,"url",rt(t)];case"builtin-view":return yt(t);default:return}},bt=(t,e)=>{const r=t.map(n=>S(n,e));return r.length>0&&r[0]===s?[s,"arr",r]:r},ht=(t,e)=>{const r={};for(const n of Object.keys(t)){const o=t[n];o!==void 0&&U(r,n,S(o,e))}return r},S=(t,e=0)=>{if(e>v)throw new RangeError(`wire-codec: value nesting exceeds the ${String(v)}-level limit`);if(t===void 0)return[s,"undefined"];if(t===null)return t;if(typeof t=="bigint")return lt(t);if(typeof t=="number")return ft(t);if(typeof t!="object")return t;const r=st(t);if(r==="array")return bt(t,e+1);if(r==="plain")return ht(t,e+1);const n=dt(t,r,a=>S(a,e+1));if(n!==void 0)return n;const o=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${o} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)},gt=t=>{const e=t[2];if(typeof e!="string"||e.length>O||!ut.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(O)} digits)`);return BigInt(e)},wt=(t,e)=>{const r=e(t[2]);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)},mt=(t,e)=>{const r=t[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[e(n[0]),e(n[1])]}))},At=t=>{const e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(e)},$t=(t,e)=>{const r=t[2],n=t[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const o=(Object.hasOwn(B,r)?B[r]:void 0)??Error,a=new o(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const c=e(t[4]);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const[w,p]of Object.entries(c))U(a,w,p);return t.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:e(t[5]),writable:!0}),a},Et=t=>{const e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const r=ct(e);if(E(r)!==e)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const n=t[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:new Uint8Array(r).buffer;const o=Object.hasOwn(x,n)?x[n]:void 0;return o?new o(new Uint8Array(r).buffer):r},vt=(t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(r=>e(r));case"bigint":return gt(t);case"bytes":return Et(t);case"date":return wt(t,e);case"error":return $t(t,e);case"inf":return 1/0;case"map":return mt(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(r=>e(r)));case"undefined":return;case"url":return At(t);default:return t.map(r=>e(r))}},Ot=(t,e)=>{const r={};for(const n of Object.keys(t))U(r,n,R(t[n],e));return r},R=(t,e=0)=>{if(e>v)throw new RangeError(`wire-codec: value nesting exceeds the ${String(v)}-level limit`);if(t===null||typeof t!="object")return t;if(Array.isArray(t)){const r=t;return r[0]===s?vt(r,n=>R(n,e+1)):r.map(n=>R(n,e+1))}return Ot(t,e+1)},Rt=(t,e,r)=>{try{return S(r)}catch(n){throw new TypeError(`${t}: cannot encode args for '${e}' — ${n instanceof Error?n.message:String(n)}`,n instanceof Error?{cause:n}:void 0)}},St="DISPATCH_IN_PROGRESS",Nt="x-lunora-dispatch-declined",Tt=(t,e,r)=>{if(e===void 0)return{dispose:()=>{},signal:t};const n=new AbortController,o=setTimeout(()=>{n.abort(r())},e);return{dispose:()=>{clearTimeout(o)},signal:n.signal}},f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",C=t=>{let e="",r=0;const n=t.length-2;for(;r<n;r+=3){const a=t[r]<<16|t[r+1]<<8|t[r+2];e+=f.charAt(a>>18&63)+f.charAt(a>>12&63)+f.charAt(a>>6&63)+f.charAt(a&63)}const o=t.length-r;if(o===1){const a=t[r]<<16;e+=f.charAt(a>>18&63)+f.charAt(a>>12&63)}else if(o===2){const a=t[r]<<16|t[r+1]<<8;e+=f.charAt(a>>18&63)+f.charAt(a>>12&63)+f.charAt(a>>6&63)}return e};new TextDecoder;const F=new TextEncoder,M="=",Lt=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},It=t=>C(F.encode(t)),jt=t=>It(JSON.stringify(t)),Ut=t=>!t.startsWith(M)&&Lt(t)?t:`${M}${C(F.encode(t))}`,_t="/_lunora/scheduler/dispatch",Dt=3e4,Pt=t=>{let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)},J=Symbol("lunoraDispatchFailure"),xt=Symbol("lunoraDispatchDecline"),Bt=Symbol("lunoraDispatchMessageId"),G=(t,e)=>(e!==void 0&&Object.defineProperty(t,Bt,{value:e}),t),Mt=(t,e)=>(Object.defineProperty(t,J,{value:!0}),G(t,e)),kt=(t,e,r,n)=>{const{status:o}=e;try{const a=JSON.parse(r)?.error;if(typeof a=="object"&&a!==null&&typeof a.code=="string"){const{code:c,data:w,message:p}=a,d=Mt(new y(c,typeof p=="string"?p:void 0,{data:w,status:o}),n);return e.headers.get(Nt)==="1"&&Object.defineProperty(d,xt,{value:!0}),d}}catch{}return G(new y("INTERNAL",`${t}: function dispatch failed (${String(o)}): ${r}`,{status:o}),n)},Ct=new Set([400,403,404,422]),Ft=new Set([St,"DISPATCH_UNAUTHENTICATED"]),Jt=t=>H(t)&&t[J]===!0,Wt=t=>Jt(t)&&Ct.has(t.status)&&!Ft.has(t.code),Gt=(t,e,r)=>new y("INTERNAL",`${t}: function dispatch to "${e}" timed out after ${String(r)}ms`,{status:503}),Ht=t=>{const{label:e}=t,r=globalThis.fetch,n=t.fetchImpl??(typeof r=="function"?r.bind(globalThis):void 0);return async(o,a,c={})=>{if(typeof n!="function")throw new TypeError(`${e}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const w=()=>t.argsAlreadyEncoded===!0?a??{}:Rt(e,o.__lunoraRef,a??{}),p=t.env.LUNORA_ORIGIN_URL;if(typeof p!="string"||p.length===0)throw new y("INTERNAL",`${e}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const d=t.env.LUNORA_ADMIN_TOKEN;if(typeof d!="string"||d.length===0)throw new y("INTERNAL",`${e}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const K=`${Pt(p)}${_t}`,$={authorization:`Bearer ${d}`,"content-type":"application/json"};t.traceparent!==void 0&&t.traceparent.length>0&&($.traceparent=t.traceparent),t.identity?.userId!==void 0&&($["x-lunora-userid"]=Ut(t.identity.userId)),t.identity?.claims!==void 0&&($["x-lunora-identity"]=jt(t.identity.claims));const N=c.timeoutMs??Dt,_=Tt(void 0,N,()=>new DOMException(`dispatch timed out after ${String(N)}ms`,"TimeoutError")),T=l=>{throw l instanceof Error&&l.name==="TimeoutError"?Gt(e,o.__lunoraRef,N):l};let u;try{try{u=await n(K,{body:JSON.stringify({args:w(),functionPath:o.__lunoraRef,id:c.dedupId,shardKey:c.shardKey}),headers:$,method:"POST",signal:_.signal})}catch(h){return T(h)}if(!u.ok){let h;try{h=await u.text()}catch(W){return T(W)}throw kt(e,u,h,c.messageId)}let l;try{l=await u.text()}catch(h){return T(h)}if(l.length===0)return;let b;try{b=JSON.parse(l)}catch{throw new y("INTERNAL",`${e}: function dispatch returned a non-JSON body (${String(u.status)}): ${l}`,{status:u.status})}if(b===null||typeof b!="object"||Array.isArray(b)||!("result"in b))throw new y("INTERNAL",`${e}: function dispatch returned a JSON body that is not a { result } envelope (${String(u.status)}): ${l}`,{status:u.status});return R(b.result)}finally{_.dispose()}}};export{Ht as a,Wt as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import p from"./jsonSchema-fhoaBWpN.mjs";import{toFunctionReference as d,DEFAULT_AGENT_FUNCTION_PATHS as u}from"./AGENT_MODULE-CYBmT9SD.mjs";const g=200,T=e=>{const t=typeof e=="object"&&e!==null?e.label:void 0;if(!(typeof t!="string"||t.trim().length===0))return[...t.trim()].slice(0,g).join("")};class w extends Error{code="SECRET_UNAVAILABLE";constructor(){super("the secret is no longer available: it expired, was already used by another tool call, or was never supplied"),this.name="SecretUnavailableError"}}const I=e=>{if(typeof e.description!="string"||e.description.length===0)throw new i("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `description` (the model decides from it)");if(typeof e.consumer!="string"||e.consumer.length===0)throw new i("INTERNAL","@lunora/agent: requestSecretTool requires a non-empty `consumer`: the name of the one tool allowed to read the value");return{description:e.description,execute:()=>{throw new i("INTERNAL","@lunora/agent: requestSecretTool is resolved by the loop and must never be executed")},inputSchema:p({properties:{label:{description:"What the secret is for, shown to the person asked.",type:"string"}},required:["label"],type:"object"}),isLunoraAgentTool:!0,secretRequest:{consumer:e.consumer}}},E=(e,t)=>t instanceof Error?{...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name,stack:t.stack}:t,h=e=>{const t=new TextEncoder().encode(e),n=Array.from(t,r=>String.fromCodePoint(r)).join(""),a=btoa(n),o=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return[...new Set([a,a.replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),encodeURIComponent(e),o,JSON.stringify(e).slice(1,-1),e])]},m=(e,t)=>{if(t.length===0||e===void 0||typeof e=="function"||typeof e=="symbol")return!1;let n;try{n=JSON.stringify(e,E)}catch{return!1}return h(t).some(a=>n.includes(a))},b="[redacted]",f="@lunora/agent: withSecret's callback threw a value that is withheld, in case it carries the secret",c=(e,t)=>{if(t.length===0)return e;let n=e;for(const a of h(t).toSorted((o,r)=>r.length-o.length))n=n.split(a).join(b);return n},y=(e,t,n=new Set)=>{if(!(e instanceof Error))return new i("INTERNAL",f);if(n.has(e))return e;n.add(e);try{const{name:a}=e;typeof a=="string"&&Object.defineProperty(e,"name",{configurable:!0,value:c(a,t),writable:!0}),e.message=c(e.message,t),typeof e.stack=="string"&&(e.stack=c(e.stack,t));const o=e;for(const r of Object.getOwnPropertyNames(e)){if(r==="message"||r==="stack")continue;const s=o[r];if(s instanceof Error){const l=y(s,t,n);l!==s&&(o[r]=l)}else m(s,t)&&(o[r]=JSON.parse(c(JSON.stringify(s),t)))}}catch{return new i("INTERNAL",f)}return e},L=async(e,t,n)=>{const a=await e.step.do(`secret:consume:${e.idempotencyKey}:${t}`,async()=>{const o=await e.run(d(u.takeSecret),{claimant:e.idempotencyKey,consumerCallId:e.toolCallId,instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t});if(typeof o!="string")return{unavailable:!0};let r;try{r=await n(o)}catch(s){throw y(s,o)}return m(r,o)?{leaked:!0}:{result:r}});if("unavailable"in a)throw new w;if(await e.step.do(`secret:discard:${e.idempotencyKey}:${t}`,async()=>{await e.run(d(u.discardSecret),{instanceId:e.instanceId,threadKey:e.threadKey,toolCallId:t})}),"leaked"in a)throw new i("INTERNAL","@lunora/agent: withSecret's callback returned the secret, so its result was not recorded");return a.result};export{w as SecretUnavailableError,I as requestSecretTool,T as secretLabelOf,L as withSecret};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as A}from"@lunora/ai/create";import{a as b}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{p as x,d as T,a as _,i as p,b as y,c as v,e as E,t as k,f as M,r as w,g as C}from"./voice-turn-B9omvXoR.mjs";import{r as I}from"./agent-ai-CP87uSoZ.mjs";import{createStreamGenerate as R,createCompact as L}from"../packem_chunks/createAgentGenerate.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as N,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.mjs";const O="@cf/openai/whisper-large-v3-turbo",U="@cf/deepgram/aura-1",B=8*1024*1024,F=100,f=4e3,g=f*4+1024,D=4002,z=4003,W=4004,G=256*1024,S=15,X=5e3,K=h=>{if(h===null||typeof h!="object")return!1;const{text:t,type:e}=h;return e==="commit"||e==="interrupt"||e==="text"&&typeof t=="string"};class j{agent;ai;env;exportName;paths;streamGenerate;sttModel;ttsModel;maxSessionTurns;audioBuffers=new Map;bufferedBytes=new Map;controllers=new Map;state;constructor(t,e,r,s){this.state=t,this.env=e,this.agent=r,this.exportName=s,this.paths=N,this.ai=I(e)??A({env:e}),this.streamGenerate=R(r,e),this.sttModel=r.voice?.stt??O,this.ttsModel=r.voice?.tts??U,this.maxSessionTurns=r.voice?.maxTurns??F}fetch(t){if(t.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{status:426});const r=new URL(t.url).searchParams.get("threadKey");if(!r)return new Response("Missing threadKey",{status:400});const s=globalThis.WebSocketPair,i=new s,n=i[0],o=i[1];this.state.acceptWebSocket(o);const c=crypto.randomUUID(),d=x(t.headers.get("x-lunora-identity")),a=T(t.headers.get("x-lunora-userid")),u=_(t.headers.get("x-lunora-identity-exp"));if(p(u))return y(o),new Response(null,{status:101,webSocket:n});o.serializeAttachment?.({connectionId:c,threadKey:r,turn:0,...u===void 0?{}:{expiresAt:u},...d===void 0?{}:{identity:d},...a===void 0?{}:{userId:a}}),this.send(o,{audioFormat:this.agent.voice?.audioFormat??"mp3",type:"ready"});const l=this.agent.voice?.greeting;return l&&l.length>0&&this.state.waitUntil?.(this.speakGreeting(o,c,r,a,d,l)),new Response(null,{status:101,webSocket:n})}async webSocketMessage(t,e){const r=t.deserializeAttachment?.();if(r){if(p(r.expiresAt)){y(t);return}try{if(typeof e=="string"){await this.handleControl(t,r,e);return}this.bufferAudio(r.connectionId,new Uint8Array(e),t)}catch(s){this.send(t,{message:s instanceof Error?s.message:String(s),type:"error"})}}}webSocketClose(t){this.cleanupSocket(t)}webSocketError(t){this.cleanupSocket(t)}resolveRun(t,e){const r=t===void 0&&e===void 0?void 0:{...e===void 0?{}:{claims:e},...t===void 0?{}:{userId:t}};return b({env:this.env,label:"@lunora/agent voice",...r===void 0?{}:{identity:r}})}async transcribe(t){const e=v(t);return E(await this.ai.run(this.sttModel,{audio:k(e)}))}async synthesize(t,e){const r=this.agent.voice?.speaker;return M(await this.ai.run(this.ttsModel,{text:t,...r===void 0?{}:{speaker:r}},e===void 0?void 0:{signal:e}))}async handleControl(t,e,r){if(r.length>g){this.send(t,{message:`control frame exceeds the maximum of ${String(g)} characters`,type:"error"}),this.closeSocket(t,W,"control_frame_limit");return}let s;try{s=JSON.parse(r)}catch{return}if(!K(s)){this.send(t,{message:'unsupported control frame — expected { type: "text", text }, { type: "commit" } or { type: "interrupt" }',type:"error"});return}const i=s;if(i.type==="interrupt"){this.controllers.get(e.connectionId)?.abort();return}if(i.type==="text"&&i.text.length>f){this.send(t,{message:`text frame exceeds the maximum of ${String(f)} characters`,type:"error"});return}if(e.turn>=this.maxSessionTurns){this.send(t,{message:`voice session reached its ${String(this.maxSessionTurns)}-turn limit — reconnect to continue`,type:"error"}),this.closeSocket(t,D,"turn_limit");return}if(this.controllers.has(e.connectionId)){i.type==="commit"&&this.drainAudio(e.connectionId),this.send(t,{message:"a turn is already in progress — send an interrupt before the next utterance",type:"error"});return}if(i.type==="commit"){const n=this.drainAudio(e.connectionId);await this.runTurn(t,e,{pcm:n});return}await this.runTurn(t,e,{text:i.text})}bufferAudio(t,e,r){const s=(this.bufferedBytes.get(t)??0)+e.byteLength;if(s>B){this.audioBuffers.delete(t),this.bufferedBytes.delete(t),this.send(r,{message:"utterance exceeded the maximum buffer — send a commit sooner",type:"error"}),this.closeSocket(r,z,"utterance_too_large");return}const i=this.audioBuffers.get(t)??[];i.push(e),this.audioBuffers.set(t,i),this.bufferedBytes.set(t,s)}drainAudio(t){const e=this.audioBuffers.get(t)??[];this.audioBuffers.delete(t),this.bufferedBytes.delete(t);const r=e.reduce((n,o)=>n+o.byteLength,0),s=new Uint8Array(r);let i=0;for(const n of e)s.set(n,i),i+=n.byteLength;return s}async runTurn(t,e,r){const s=new AbortController;this.controllers.set(e.connectionId,s);try{await w({agent:this.agent,compact:L(),connectionId:e.connectionId,env:this.env,exportName:this.exportName,paths:this.paths,run:this.resolveRun(e.userId,e.identity),send:i=>{this.send(t,i)},sendAudio:i=>{this.sendAudio(t,i)},signal:s.signal,streamGenerate:this.streamGenerate,synthesize:async(i,n)=>this.synthesizeWithSignal(i,n),threadKey:e.threadKey,transcribe:async i=>this.transcribe(i),turn:e.turn,waitForDrain:async()=>this.waitForSocketDrain(t),...e.userId===void 0?{}:{owner:e.userId},...r.pcm===void 0?{}:{pcm:r.pcm},...r.text===void 0?{}:{text:r.text}})}finally{this.controllers.get(e.connectionId)===s&&this.controllers.delete(e.connectionId),t.serializeAttachment?.({...e,turn:e.turn+1})}}async speakGreeting(t,e,r,s,i,n){const o=this.resolveRun(s,i),c=new AbortController,d=()=>c.signal.aborted;this.controllers.set(e,c);try{if((await o(m(this.paths.ensureThread),{agent:this.exportName,key:r,...this.agent.initialState===void 0?{}:{initialState:this.agent.initialState},...s===void 0?{}:{owner:s}}))?.outcome!=="created")return;for await(const u of C(await this.synthesizeWithSignal(n,c.signal))){if(d()||(await this.waitForSocketDrain(t),d()))break;this.sendAudio(t,u)}d()||(await o(m(this.paths.appendMessage),{content:n,messageKey:"voice:greeting:assistant",role:"assistant",threadKey:r}),this.send(t,{text:n,type:"assistant_done"}))}catch(a){this.send(t,{message:a instanceof Error?a.message:String(a),type:"error"})}finally{this.controllers.get(e)===c&&this.controllers.delete(e)}}async synthesizeWithSignal(t,e){return e.aborted?new Uint8Array(0):this.synthesize(t,e)}cleanupSocket(t){const e=t.deserializeAttachment?.();e&&(this.controllers.get(e.connectionId)?.abort(),this.controllers.delete(e.connectionId),this.audioBuffers.delete(e.connectionId),this.bufferedBytes.delete(e.connectionId))}closeSocket(t,e,r){try{t.close?.(e,r)}catch{}}send(t,e){try{t.send(JSON.stringify(e))}catch{}}sendAudio(t,e){try{t.send(e)}catch{}}async waitForSocketDrain(t){const e=t;let r=0;for(;typeof e.bufferedAmount=="number"&&e.bufferedAmount>G&&r<X;)await new Promise(s=>{setTimeout(s,S)}),r+=S}}export{j as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import i from"./jsonSchema-fhoaBWpN.mjs";const s=t=>{if(t.structuredContent!==void 0)return t.structuredContent;const n=(t.content??[]).filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
2
|
+
`);return t.isError===!0?`MCP tool error: ${n.length>0?n:"unknown error"}`:n.length>0?n:t.content},l=(t,n,e)=>({description:n.description??`MCP tool "${n.name}".`,execute:async r=>s(await t.callTool({arguments:r,name:n.name})),inputSchema:i(n.inputSchema),isLunoraAgentTool:!0,...e===void 0?{}:{needsApproval:typeof e=="function"?r=>e(n.name,r):e}}),u=async t=>{if(t.command!==void 0)throw new c("INTERNAL","@lunora/agent: mcpTools `command` (stdio transport) cannot run in the Workers runtime — pass a `url` for an HTTP/SSE MCP server, or inject a connected `client`");if(t.url===void 0)throw new c("INTERNAL","@lunora/agent: mcpTools requires a `url` (an HTTP/SSE MCP server) or an injected `client`");const n=new URL(t.url),{Client:e}=await import("@modelcontextprotocol/sdk/client/index.js");let r;if(t.transport==="sse"){const{SSEClientTransport:a}=await import("@modelcontextprotocol/sdk/client/sse.js");r=new a(n)}else{const{StreamableHTTPClientTransport:a}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");r=new a(n)}const o=new e({name:t.name??"lunora-agent",version:t.version??"0.0.0"});return await o.connect(r),o},T=async t=>{const n=t.client??await u(t),{tools:e}=await n.listTools(),r={};for(const o of e)t.only!==void 0&&!t.only.includes(o.name)||(r[`${t.prefix??""}${o.name}`]=l(n,o,t.needsApproval));return r};export{s as adaptMcpResult,T as mcpTools};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAi as t}from"@lunora/ai/create";const i=r=>{const o=r.AI;return o?t({binding:o,env:r}):void 0};export{i as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{isDuplicateInstanceError as S}from"@lunora/workflow";import{f as $}from"./fnv1a-BNN96GYb.mjs";import{w as E}from"./run-shard-B7iMrAI0.mjs";import{r as L}from"./workflow-binding-Dm9hBzx_.mjs";import b from"./jsonSchema-fhoaBWpN.mjs";import{agentClassName as N}from"../naming.mjs";import{toFunctionReference as P,DEFAULT_AGENT_FUNCTION_PATHS as _}from"./AGENT_MODULE-CYBmT9SD.mjs";import{i as g}from"./positive-integer-ztHqqpBk.mjs";const M=new Set(["complete","errored","terminated"]),R=600,w=3,k=500,x=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",C=t=>t!==null&&typeof t=="object"?t.output:void 0,D=async t=>{await new Promise(e=>{setTimeout(e,t)})},U=async(t,e,n,m)=>{for(let o=0;o<e;o+=1){const a=await t.status(),s=x(a);if(M.has(s))return{output:C(a),status:s};await m(n)}return{output:void 0,status:"timeout"}},j=t=>{if(t!==null&&typeof t=="object"&&typeof t.stopped=="string")return t.stopped},F=t=>{for(let e=t.length-1;e>=0;e-=1){const n=t[e];if(n?.role==="assistant"&&(n.toolCalls===void 0||n.toolCalls.length===0))return n.content}return""},B=t=>{if(typeof t.name!="string"||t.name.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a `name` (the child agent's export name, selecting its exported workflow)");if(typeof t.description!="string"||t.description.length===0)throw new c("INTERNAL","@lunora/agent: agent.asTool requires a non-empty `description` (the parent model decides from it)");if(t.maxPolls!==void 0&&!g(t.maxPolls))throw new c("INTERNAL","@lunora/agent: agent.asTool `maxPolls` must be a positive integer");const{name:e}=t,n=N(e),m=t.maxPolls??R,o=t.pollIntervalMs??k,a=t.wait??D,s=P(_.listMessages),T=async(y,r)=>{const p=(g(r.depth)?r.depth:0)+1;if(p>w)return`Sub-agent "${e}" was not started: the maximum delegation depth of ${String(w)} is already reached. Answer with what you have instead of delegating further.`;const i=L(r.env,r.exports,n,["create","get"]);if(i===void 0)throw new c("INTERNAL",`@lunora/agent: agent.asTool("${e}") found no "${n}" on ctx.exports or env — declare the "${e}" agent so codegen wires it`);const f=`${r.threadKey}::sub::${e}::${r.toolCallId}`,h=`sub-${e}-${$(`${r.instanceId}:${e}:${r.toolCallId}`)}`,A={depth:p,input:y.prompt,threadKey:f,...r.owner===void 0?{}:{owner:r.owner}};let l;try{const d=await i.create({id:h,params:E(A,r.shardKey)});l=await i.get(d.id)}catch(d){if(!S(d))throw d;l=await i.get(h)}const{output:v,status:u}=await U(l,m,o,a);if(u==="errored"||u==="terminated")return`Sub-agent "${e}" ${u} before producing an answer.`;if(u==="timeout"){try{await l.terminate()}catch{}return`Sub-agent "${e}" did not finish within the allotted time.`}if(j(v)==="maxTurns")return`Sub-agent "${e}" hit its turn cap (maxTurns) before producing a final answer. Ask it something narrower, or answer with what you have.`;const I=await r.run(s,{key:f});return F(I)};return{description:t.description,execute:T,inputSchema:b({properties:{prompt:{description:"The task or question to delegate to the sub-agent.",type:"string"}},required:["prompt"],type:"object"}),isLunoraAgentTool:!0}};export{B as agentAsTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const p=o=>o===void 0?void 0:{shardKey:o};export{p as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{usageStatus as _}from"@lunora/ai/create";import{r as s,d as b,t as x,f as T,s as C,c as v}from"./common-DBc9y7Np.mjs";import{c as L}from"./in-flight-calls-C9QGq8uH.mjs";const E=(l,c)=>typeof l=="string"&&l.length>0?l:c,O={cacheReadTokens:"prompt_cached_tokens",cacheWriteTokens:"prompt_cache_creation_tokens",inputTokens:"prompt_tokens",outputTokens:"completion_tokens",reasoningTokens:"completion_reasoning_tokens",totalTokens:"tokens"},M=l=>{const c={};for(const[u,p]of Object.entries(O)){const f=l[u];f!==void 0&&(c[p]=f)}return c},P=l=>{const{functionId:c,logger:u,recordInputs:p=!1,recordOutputs:f=!1}=l,a=L((e,t,r,n)=>{const o={},d=C(s(n,"usage")??s(e.result,"usage")),y=_(d);if(o.metadata={"lunora.usage.status":y},d!==void 0&&(o.metrics=M(d)),t||(o.error=r??"the model call failed"),f){const h=v(s(n,"content")??s(e.result,"content"));h!==void 0&&(o.output=h)}Object.keys(o).length>0&&e.span.log(o),e.finish()},e=>{e.finish()}),k=(e,t,r)=>{const n=s(e,"callId");if(typeof n!="string")return;let o=r;t instanceof Error?o=t.message:typeof t=="string"&&t.length>0&&(o=t),a.close(n,!1,o,T(t))};return{executeLanguageModelCall:e=>{const{callId:t,execute:r}=e;let n,o;const d=new Promise((i,m)=>{n=i,o=m});let y;const h=new Promise(i=>{y=i});return Promise.resolve(u.traced(async i=>{a.open(t,()=>({finish:y,result:void 0,span:i})),p&&i.log({input:s(e,"messages"),model:s(e,"modelId")});let m;try{m=await r()}catch(g){a.close(t,!1,g instanceof Error?g.message:String(g),T(g)),o(g);return}const I=a.get(t);I!==void 0&&(I.result=m),n(m),await h},{name:E(c,"language_model_call"),type:"llm"})).catch(()=>{}),d},executeTool:e=>{const t=s(s(e,"toolCall"),"toolName");return u.traced(async r=>{p&&r.log({input:x(e),tool:t});const n=await e.execute();return f&&r.log({output:n}),n},{name:E(t,"execute_tool"),type:"tool"})},onAbort:e=>{k(e,s(e,"reason"),"aborted")},onEnd:e=>{a.fromLifecycle(e)},onError:e=>{u.traced(t=>{t.log({error:b(s(e,"error")??e)})},{name:"error",type:"error"}),k(e,s(e,"error"),"the model call failed")},onLanguageModelCallEnd:e=>{typeof s(e,"callId")=="string"&&a.fromLifecycle(e)},onStepEnd:e=>{a.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 u=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"},i=t=>({content:[{output:{type:"text",value:t.content},toolCallId:t.toolCallId??"",toolName:t.toolName??"",type:"tool-result"}],role:"tool"}),c=(t,e)=>({content:[{output:{type:"text",value:e?"Tool call is awaiting approval and has not run.":"Tool call outcome unknown: the run was interrupted before its result was recorded."},toolCallId:t.id,toolName:t.name,type:"tool-result"}],role:"tool"}),d=t=>{const e=new Map;let n;for(const o of t)o.role==="assistant"?(n={answered:new Set,awaitingApproval:new Set},e.set(o,n)):o.role==="tool"&&o.toolCallId!==void 0&&n!==void 0&&(o.status==="awaiting_approval"?n.awaitingApproval.add(o.toolCallId):o.status!=="awaiting_secret"&&n.answered.add(o.toolCallId));return e},m=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"});const n=d(t.history);let o=[];const l=()=>{e.push(...o),o=[]};for(const s of t.history)if(!(s.status==="awaiting_approval"||s.status==="awaiting_secret"))switch(s.role!=="tool"&&l(),s.role){case"assistant":{e.push(u(s));const r=n.get(s);o=(s.toolCalls??[]).filter(a=>r?.answered.has(a.id)!==!0).map(a=>c(a,r?.awaitingApproval.has(a.id)===!0));break}case"system":{e.push({content:s.content,role:"system"});break}case"tool":{e.push(i(s));break}case"user":{e.push({content:s.content,role:"user"});break}}return l(),e};export{m as buildModelMessages};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";import y from"./jsonSchema-fhoaBWpN.mjs";import{i as w}from"./positive-integer-ztHqqpBk.mjs";import{M as v,c as A}from"./tool-output-Cmk3JWMG.mjs";const T=16,g=e=>{if(e===void 0)return e;const o=typeof e=="string"?e:JSON.stringify(e);return o.length<=v?e:A(o)},$=(e,o)=>{let t=e;for(const i of o.split(".")){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))return;t=t[i]}return t},l=(e,o)=>{if(Array.isArray(e))return e.map(r=>l(r,o));if(e===null||typeof e!="object")return e;const t=e;if(typeof t.$from=="string"){const r=t.$from;if(!Object.hasOwn(o,r))throw new a("BAD_REQUEST",`@lunora/agent: code step references unknown result "${r}" (define it in an earlier step)`);return typeof t.$path=="string"?$(o[r],t.$path):o[r]}const i={};for(const[r,n]of Object.entries(t))r!=="__proto__"&&(i[r]=l(n,o));return i},S=async(e,o,t)=>{const{asSchema:i}=await import("@ai-sdk/provider-utils"),{validate:r}=i(o.inputSchema);if(r===void 0)return t;const n=await r(t);if(n.success)return n.value;throw new a("BAD_REQUEST",`@lunora/agent: code step "${e.id}" input is invalid for tool "${e.tool}": ${n.error.message}`)},b=async(e,o,t,i)=>{const r=Array.isArray(e.steps)?e.steps:[];if(r.length>i)throw new a("BAD_REQUEST",`@lunora/agent: code_tool_too_many_steps — the script has ${String(r.length)} steps, over the cap of ${String(i)}. Split it across several code calls.`);const n={},p=[],d=new Set;for(const s of r){if(d.has(s.id))throw new a("BAD_REQUEST",`@lunora/agent: duplicate code step id "${s.id}" — each step id must be unique (later steps reference an output by id via $from)`);d.add(s.id)}for(const s of r){const c=Object.hasOwn(o,s.tool)?o[s.tool]:void 0;if(!c)throw new a("BAD_REQUEST",`@lunora/agent: code step calls unknown tool "${s.tool}" (available: ${Object.keys(o).join(", ")})`);const m=await S(s,c,l(s.input??{},n)),u={...t,idempotencyKey:`${t.idempotencyKey}:${s.id}`,toolCallId:`${t.toolCallId}:${s.id}`},h=()=>Promise.resolve(c.execute(m,u)),f=await t.step.do(u.idempotencyKey,h);n[s.id]=f,p.push({id:s.id,output:g(f)})}return{final:p.at(-1)?.output,results:p}},E=e=>`Compose MULTIPLE tool calls in one turn as a script, instead of one call per turn. Provide \`steps\`: an ordered array of \`{ id, tool, input }\`. A later step's \`input\` may reference an earlier step's output with \`{ "$from": "<stepId>", "$path": "optional.dot.path" }\`. Available tools: ${Object.entries(e).map(([o,t])=>`"${o}" — ${t.description}`).join("; ")}.`,O=y({properties:{steps:{description:"Ordered tool calls; a later input may reference an earlier output via { $from, $path }.",items:{additionalProperties:!1,properties:{id:{description:"A name later steps reference this output by.",type:"string"},input:{additionalProperties:!0,description:"The tool input (may embed $from refs).",type:"object"},tool:{description:"The tool to call.",type:"string"}},required:["id","tool"],type:"object"},type:"array"}},required:["steps"],type:"object"}),L=(e,o={})=>{const t=e;if(!t||typeof t!="object"||Object.keys(t).length===0)throw new a("INTERNAL","@lunora/agent: codeTool requires a non-empty map of tools to compose");for(const[r,n]of Object.entries(t)){if(n.needsApproval!==void 0&&n.needsApproval!==!1)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it has a \`needsApproval\` gate a code-mode script can't pause for. Expose it as a normal top-level tool, or gate the whole script via codeTool's \`needsApproval\`.`);if(n.secretRequest!==void 0)throw new a("INTERNAL",`@lunora/agent: codeTool cannot compose "${r}" — it is a requestSecretTool, which a code-mode script can't pause for the owner to supply. Expose it as a normal top-level tool.`)}if(o.maxSteps!==void 0&&!w(o.maxSteps))throw new a("INTERNAL","@lunora/agent: codeTool `maxSteps` must be a positive integer");const i=o.maxSteps??T;return{description:o.description??E(e),execute:(r,n)=>b(r,e,n,i),inputSchema:O,isLunoraAgentTool:!0,...o.needsApproval===void 0?{}:{needsApproval:o.needsApproval}}};export{L as codeTool,l as resolveReferences,b as runToolScript};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as u}from"./app-call-options-BE0CQ6Qg.mjs";import p from"./jsonSchema-fhoaBWpN.mjs";import{toFunctionReference as l}from"./AGENT_MODULE-CYBmT9SD.mjs";const m=240,y=50,f=(r,s)=>r.length<=s?r:`${r.slice(0,s)}…`,g=r=>{if(!(r===void 0||!Number.isFinite(r)))return Math.min(y,Math.max(1,Math.trunc(r)))},S=(r,s)=>{const t=r??{},i=Array.isArray(t.chunks)?t.chunks:[],e=Array.isArray(t.sources)?t.sources:[];return{results:i.map(o=>({id:typeof o.id=="string"?o.id:"",score:typeof o.score=="number"?o.score:0,snippet:f(typeof o.text=="string"?o.text:"",s),sourceId:typeof o.sourceId=="string"?o.sourceId:""})),sources:e}},A=p({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"}),b=p({additionalProperties:!1,properties:{id:{description:"The `id` of a hit returned by the search tool.",type:"string"}},required:["id"],type:"object"}),T=(r,s,t)=>{const i=l(s),e=Math.max(1,r.snippetChars??m),o=r.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.${t===void 0?"":` Use \`${t}\` with a hit's \`id\` to fetch its full text.`}`,execute:async(n,c)=>{const d=g(n.topK)??o,h=await c.run(i,{query:n.query,...d===void 0?{}:{topK:d}},u(c.shardKey));return S(h,e)},inputSchema:A,isLunoraAgentTool:!0}},q=r=>{const s=l(r);return{description:"Fetch the full text of a memory document by the `id` from a search hit.",execute:(t,i)=>i.run(s,{id:t.id},u(i.shardKey)),inputSchema:b,isLunoraAgentTool:!0}},v=(r,s)=>{const t=[];r.memory&&t.push({key:"default",...r.memory});for(const e of s)e.knowledge&&t.push({key:e.name,...e.knowledge});const i={};for(const e of t){if(e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic"||e.source===void 0)continue;const o=e.key==="default"?"searchMemory":`search_${e.key}`,a=e.key==="default"?"readMemory":`read_${e.key}`,n=e.read!==void 0;i[o]=T(e,e.source,n?a:void 0),n&&(i[a]=q(e.read))}return i};export{v as collectAgenticMemoryTools,S 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 c}from"@lunora/workflow";import{agentDefaultName as u}from"../naming.mjs";import{DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-CYBmT9SD.mjs";const T=(t,r,n,e)=>{const a=r.LUNORA_OTLP_ENDPOINT;if(typeof a!="string"||a===""||t.telemetry?.isEnabled===!1)return t;const s=typeof r.LUNORA_OTLP_TOKEN=="string"?r.LUNORA_OTLP_TOKEN:void 0,i=[t.telemetry?.integrations].flat().filter(o=>o!==void 0);return{...t,telemetry:{...t.telemetry,integrations:[...i,n({conversationId:e,endpoint:a,token:s})],isEnabled:!0}}},N=(t,r,n)=>c({handler:async e=>{const[{runAgentLoop:a},{createAgentGenerate:s,createCompact:i,createEpisodeExtract:o,createGraphExtract:m,createStreamGenerate:l},{default:f},{otlpTelemetry:d}]=await Promise.all([import("../packem_chunks/runAgentLoop.mjs"),import("../packem_chunks/createAgentGenerate.mjs"),import("../packem_chunks/resolve-run.mjs"),import("../packem_chunks/otlpTelemetry.mjs")]),p=T(t,e.env,d,e.params.threadKey);return a({agent:p,compact:i(),env:e.env,exports:e.exports,exportName:r,extractGraph:m(),extractEpisode:o(),generate:s(p,e.env),instanceId:e.event.instanceId,params:e.params,paths:n?.paths??A,run:f(e.params.owner,e.env,e.fetchImpl),step:e.step,streamGenerate:l(p,e.env)})},name:t.name??u(r)});export{N as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s="agent";const o=12096e5,M=e=>({...e,visibility:"internal"}),a=e=>{const t={};for(const[_,n]of Object.entries(e))n!==void 0&&(t[_]=n);return t},r=9e5,E=6e4;const A={day:864e5,hour:36e5,minute:6e4,month:2592e6,second:1e3,week:6048e5,year:31536e6},T=/^(\d+(?:\.\d+)?) (day|hour|minute|month|second|week|year)s?$/u,O=e=>{if(e===void 0)return 2592e5;if(typeof e=="number")return Math.min(e,6048e5);const t=T.exec(e);return t===null?2592e5:Math.min(Number(t[1])*A[t[2]],6048e5)};export{s as A,E as S,O as a,M as b,o as c,a as d,r 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 h}from"./DEFAULT_DISPATCH_TIMEOUT_MS-DiRHEqJU-BRtWNzq1.mjs";import{LunoraError as c}from"@lunora/errors";import{h as w,B as g}from"./branch-marker-boZ00zmk.mjs";import{w as E}from"./run-shard-B7iMrAI0.mjs";import{r as T}from"./workflow-binding-Dm9hBzx_.mjs";import{toFunctionReference as N,DEFAULT_AGENT_FUNCTION_PATHS as A}from"./AGENT_MODULE-CYBmT9SD.mjs";const R=3,B=(s,i,u={})=>{const{dispatch:d,exports:l,shardKey:m}=u,o={},p=N(A.patchThread),f=()=>d??h({env:s,label:"@lunora/agent"});for(const e of i){const n=()=>{const t=T(s,l,e.className,["create","get"]);if(t===void 0)throw new c("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};o[e.exportName]={cancel:async t=>{await(await n().get(t)).terminate();for(let r=0;r<R;r+=1)try{await f()(p,{instanceId:t,status:"cancelled"});break}catch{}},publicRun:e.publicRun===!0,run:async(t,a)=>{if(w(t))throw new c("BAD_REQUEST",`@lunora/agent: run input ${g}`);return{id:(await n().create({...a?.id===void 0?{}:{id:a.id},params:E(t,m)})).id}},sendEvent:async(t,a)=>{await(await n().get(t)).sendEvent(a)},status:async t=>(await n().get(t)).status()}}return o};export{B as default};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{collectAgenticMemoryTools as f}from"./collectAgenticMemoryTools-X7AqELV3.mjs";import{agentAsTool as p}from"./agentAsTool-BF-7Dnzy.mjs";import{a as g}from"./component-shared--SPcu0Iw.mjs";import{i as m}from"./memory-JI0lUu84.mjs";import{i as u}from"./positive-integer-ztHqqpBk.mjs";import{SKILL_NAME_PATTERN as w,RESERVED_SKILL_NAME as c}from"./defineSkill-DGGvDWNq.mjs";const T=e=>{if(e!==void 0&&(typeof e!="string"||e.length===0))throw new r("INTERNAL","@lunora/agent: defineAgent `name` must be a non-empty string when provided")},N=/^[a-zA-Z][\w-]*$/u,A=(e,n)=>{const o={...e.tools};for(const t of n)for(const[s,a]of Object.entries(t.tools??{})){if(Object.hasOwn(o,s))throw new r("INTERNAL",`@lunora/agent: skill "${t.name}" tool "${s}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);o[s]=a}return o},k=(e,n)=>{const o=[];for(const t of[e.instructions,...n.map(s=>s.instructions)])t&&o.push(t);return o.length<=1?o[0]:t=>o.map(s=>typeof s=="function"?s(t):s).filter(s=>s.length>0).join(`
|
|
2
|
+
|
|
3
|
+
`)},v=(e,n)=>{const o=[];e.memory&&m(e.memory)&&o.push({key:"default",...e.memory});for(const t of n)t.knowledge&&m(t.knowledge)&&o.push({key:t.name,...t.knowledge});return o},y=e=>{const n=new Set;for(const o of e){if(typeof o.name!="string"||!w.test(o.name))throw new r("INTERNAL",`@lunora/agent: skill \`name\` must be a valid identifier (letters, digits, _ or -, starting with a letter), got ${JSON.stringify(o.name)}`);if(o.name===c)throw new r("INTERNAL",`@lunora/agent: skill name "${c}" is reserved (it keys the agent's own \`memory\` source / the \`memory:retrieve\` step) — choose another name`);if(n.has(o.name))throw new r("INTERNAL",`@lunora/agent: skill name "${o.name}" is used by more than one skill — rename one (a skill name keys its knowledge memory source, which must be unique)`);n.add(o.name)}},E=(e,n)=>{if(e===void 0)return;const o=Object.keys(n).filter(t=>!e.includes(t));if(o.length>0)throw new r("INTERNAL",`@lunora/agent: \`activeTools\` omits the agentic-memory tool(s) ${o.map(t=>`"${t}"`).join(", ")} — the model could never call them; add them to \`activeTools\` (or drop \`activeTools\` to expose every tool)`)},I=(e,n)=>{const o=(t,s)=>{if(t&&t.kind!=="graph"&&t.kind!=="episodic"&&t.source===void 0)throw new r("INTERNAL",`@lunora/agent: ${s} requires a \`source\` action unless \`kind: "graph"\` or \`kind: "episodic"\``)};o(e.memory,"`memory`");for(const t of n)o(t.knowledge,`skill "${t.name}" \`knowledge\``)},L=e=>{for(const[n,o]of[["resolveEmailShard",e.resolveEmailShard],["onInbound.resolveShard",e.onInbound?.resolveShard]])if(o!==void 0&&typeof o!="function")throw new r("INTERNAL",`@lunora/agent: \`${n}\` must be a function`)},b=e=>{if(e===void 0)return;const n=g(e);if(!Number.isFinite(n)||n<=0)throw new r("INTERNAL","@lunora/agent: `approvalTimeout` must resolve to a positive duration")},_=e=>{const n=e.model;if(n==null||typeof n=="string"&&n.length===0)throw new r("INTERNAL","@lunora/agent: defineAgent requires a `model` (a Workers AI id, an AI SDK LanguageModel, or an (env) => model thunk)");if(T(e.name),e.maxTurns!==void 0&&!u(e.maxTurns))throw new r("INTERNAL","@lunora/agent: `maxTurns` must be a positive integer");if(e.voice?.maxTurns!==void 0&&!u(e.voice.maxTurns))throw new r("INTERNAL","@lunora/agent: `voice.maxTurns` must be a positive integer");b(e.approvalTimeout),L(e);const o=e.skills??[];y(o),I(e,o);const t=A(e,o),s=f(e,o);for(const[i,h]of Object.entries(s)){if(Object.hasOwn(t,i))throw new r("INTERNAL",`@lunora/agent: agentic-memory tool "${i}" collides with an existing tool — rename one (the agent's tool namespace is flat)`);t[i]=h}const a=Object.keys(s).length>0;E(e.activeTools,s);for(const i of Object.keys(t))if(!N.test(i))throw new r("INTERNAL",`@lunora/agent: tool name "${i}" is not a valid identifier (letters, digits, _ or -, starting with a letter)`);const l=v(e,o),d=k(e,o);return{...e,asTool:p,isLunoraAgent:!0,...o.some(i=>!!i.instructions)?{instructions:d}:{},...l.length>0?{memorySources:l}:{},...o.length>0||a?{tools:t}:{}}},q=e=>typeof e=="object"&&e!==null&&e.isLunoraAgent===!0,P=e=>{if(typeof e.execute!="function")throw new r("INTERNAL","@lunora/agent: defineAgentTool requires an `execute` function");if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: defineAgentTool requires a non-empty `description` (the model decides from it)");return{...e,isLunoraAgentTool:!0}};export{_ as defineAgent,P as defineAgentTool,q as isAgentDefinition};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as 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 r}from"@lunora/errors";import{a as c}from"./app-call-options-BE0CQ6Qg.mjs";import{AGENT_MODULE as u,toFunctionReference as m}from"./AGENT_MODULE-CYBmT9SD.mjs";const f=(t,e)=>{if(typeof e.description!="string"||e.description.length===0)throw new r("INTERNAL","@lunora/agent: functionTool requires a non-empty `description` (the model decides from it)");if(e.inputSchema===void 0)throw new r("INTERNAL","@lunora/agent: functionTool requires an `inputSchema` (a zod schema or `jsonSchema(...)`)");const o=m(t),i=o.__lunoraRef.startsWith(`${u}:`);return{description:e.description,execute:(a,n)=>n.run(o,{...a,idempotencyKey:n.idempotencyKey},i?void 0:c(n.shardKey)),inputSchema:e.inputSchema,isLunoraAgentTool:!0}};export{f as functionTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{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 @@
|
|
|
1
|
+
import{LunoraError as e}from"@lunora/errors";const i=async(n,o,t)=>{if(n===void 0)return;const r=await n(o);if(r!==void 0){if(typeof r!="string"||r.length===0)throw new e("INTERNAL",`@lunora/agent: \`${t}\` must return a non-empty shard key or undefined`);return r}};export{i as r};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import y from"./jsonSchema-fhoaBWpN.mjs";const u="LOADER",b="2026-04-07",S=1e3,f=100,v=2e3,g=256*1024,p=3e4,T="Run JavaScript in an isolated sandbox and get its result. Provide `code`: the body of an async function — `return` the answer. Use it for calculation, parsing and data transformation. The sandbox has no network, no bindings and no tools; `console.log` output is returned as `logs`.",h=y({additionalProperties:!1,properties:{code:{description:"The body of an async function. `return` the result; it must be JSON-serializable.",type:"string"}},required:["code"],type:"object"}),w=e=>`const logs = [];
|
|
2
|
+
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 m("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 @@
|
|
|
1
|
+
const r=Symbol.for("vercel.ai.schema"),n=(t,{validate:o}={})=>{let e=t;return{[r]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:o}};export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=e=>e.kind==="graph"||e.kind==="episodic"||e.mode!=="agentic",o=e=>e.memorySources?e.memorySources:e.memory&&s(e.memory)?[{key:"default",...e.memory}]:[],i=e=>o(e).find(r=>r.kind==="graph"),c=e=>o(e).find(r=>r.kind==="episodic"),d=(e,r)=>r==="default"?e:`${e}:${r}`;export{c as a,i as f,s as i,d as m,o as r};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{defineTable as A,initLunora as q}from"@lunora/server";import{v as e}from"@lunora/values";import{A as _,b as f,d as S}from"./component-shared--SPcu0Iw.mjs";const 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
|
+
const i=e=>Number.isInteger(e)&&e>0;export{i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=(t,r)=>{const e={...t};return delete e.shardKey,r!==void 0&&(e.shardKey=r),e};export{a as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{p as s,c as i,f as p,e as n,r as m,g as c}from"./voice-turn-B9omvXoR.mjs";import"../packem_chunks/runAgentLoop.mjs";import"./buildModelMessages-DVQdQ7_1.mjs";import"./AGENT_MODULE-CYBmT9SD.mjs";export{s as parseIdentity,i as pcmToWav,p as readSynthesisAudio,n as readTranscriptionText,m as runVoiceTurn,c as toByteIterable};
|
|
@@ -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};
|