experimental-ash 0.38.1 → 0.40.0
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/CHANGELOG.md +21 -0
- package/dist/docs/public/tools.md +4 -1
- package/dist/src/compiled/.vendor-stamp.json +6 -6
- package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +2 -2
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/anthropic/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/google/index.d.ts +2 -2
- package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
- package/dist/src/compiled/@ai-sdk/google/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.d.ts +8 -0
- package/dist/src/compiled/@ai-sdk/openai/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/package.json +1 -1
- package/dist/src/compiled/@ai-sdk/otel/index.js +3 -3
- package/dist/src/compiled/@ai-sdk/otel/package.json +1 -1
- package/dist/src/compiled/@vercel/oidc/index.js +2 -2
- package/dist/src/compiled/@vercel/oidc/package.json +1 -1
- package/dist/src/compiler/compile-from-memory.js +1 -1
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.d.ts +2 -2
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-skill.js +1 -1
- package/dist/src/context/run-step.d.ts +17 -6
- package/dist/src/context/run-step.js +1 -1
- package/dist/src/discover/manifest.js +1 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +0 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/packages/ash-scaffold/src/channels.js +1 -1
- package/dist/src/public/channels/discord/defaults.js +1 -1
- package/dist/src/public/channels/discord/discordChannel.d.ts +2 -1
- package/dist/src/public/channels/index.d.ts +1 -1
- package/dist/src/public/channels/slack/defaults.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +2 -1
- package/dist/src/public/channels/teams/defaults.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.d.ts +2 -1
- package/dist/src/public/channels/telegram/defaults.js +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +2 -1
- package/dist/src/public/channels/twilio/defaults.js +1 -1
- package/dist/src/public/channels/twilio/twilioChannel.d.ts +2 -1
- package/dist/src/public/definitions/connections/mcp.d.ts +2 -2
- package/dist/src/public/definitions/defineChannel.d.ts +4 -3
- package/dist/src/public/definitions/defineChannel.js +1 -1
- package/dist/src/public/definitions/instructions.d.ts +1 -1
- package/dist/src/public/definitions/tool.d.ts +10 -0
- package/dist/src/runtime/agent/bootstrap.d.ts +0 -2
- package/dist/src/runtime/agent/bootstrap.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/types.d.ts +1 -2
- package/dist/src/shared/agent-definition.d.ts +12 -14
- package/dist/src/shared/sandbox-definition.d.ts +3 -1
- package/dist/src/shared/skill-definition.d.ts +6 -6
- package/dist/src/shared/tool-definition.d.ts +3 -2
- package/package.json +9 -9
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{t as e}from"../../_chunks/workflow/src-B54rYDvB.js";import{convertDataContentToBase64String as t}from"ai";var n=e();function r(e){let t=e.toLowerCase();for(let[e,n]of[[`google.vertex`,`gcp.vertex_ai`],[`google.generative-ai`,`gcp.gemini`],[`google-vertex`,`gcp.vertex_ai`],[`amazon-bedrock`,`aws.bedrock`],[`azure-openai`,`azure.ai.openai`],[`anthropic`,`anthropic`],[`openai`,`openai`],[`azure`,`azure.ai.inference`],[`google`,`gcp.gemini`],[`mistral`,`mistral_ai`],[`cohere`,`cohere`],[`bedrock`,`aws.bedrock`],[`groq`,`groq`],[`deepseek`,`deepseek`],[`perplexity`,`perplexity`],[`xai`,`x_ai`]])if(t===e||t.startsWith(e+`.`)||t.startsWith(e+`-`))return n;return e}function i(e){return{"ai.generateText":`invoke_agent`,"ai.streamText":`invoke_agent`,"ai.generateObject":`invoke_agent`,"ai.streamObject":`invoke_agent`,"ai.embed":`embeddings`,"ai.embedMany":`embeddings`,"ai.rerank":`rerank`}[e]??e}function a(e){return typeof e==`string`?[{type:`text`,content:e}]:Array.isArray(e)?e.map(e=>({type:`text`,content:e.content})):[{type:`text`,content:e.content}]}function o(e){switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})(),i;if(r instanceof Uint8Array)i=t(r);else if(typeof r==`string`){if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r};i=r}else if(r instanceof URL)return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()};else i=String(r);return{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:i}}case`tool-approval-response`:return{type:`tool_approval_response`,approval_id:e.approvalId,approved:e.approved,reason:e.reason};case`custom`:return{type:`custom`,kind:e.kind};case`reasoning-file`:return{type:String(e.type)};default:return{type:String(e.type)}}}function s(e){return!e||e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`image`}function c(e){return e.filter(e=>e.role!==`system`).map(e=>{if(e.role===`system`)return{role:`system`,parts:[{type:`text`,content:e.content}]};let t=e.content.map(o);return{role:e.role,parts:t}})}function l({prompt:e,messages:t}){let n=[];if(typeof e==`string`)n.push({role:`user`,parts:[{type:`text`,content:e}]});else if(Array.isArray(e))for(let t of e){let e=u(t);e&&n.push(e)}if(t)for(let e of t){let t=u(e);t&&n.push(t)}return n}function u(e){if(e.role!==`system`){if(e.role===`user`)return typeof e.content==`string`?{role:`user`,parts:[{type:`text`,content:e.content}]}:{role:`user`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`image`:{let n=e.image;return n instanceof URL?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n.toString()}:typeof n==`string`?n.startsWith(`http://`)||n.startsWith(`https://`)?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:t(n)}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})();return r instanceof URL?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()}:typeof r==`string`?r.startsWith(`http://`)||r.startsWith(`https://`)?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:t(r)}}default:return{type:String(e.type)}}})};if(e.role===`assistant`)return typeof e.content==`string`?{role:`assistant`,parts:[{type:`text`,content:e.content}]}:{role:`assistant`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}default:return{type:String(e.type)}}})};if(e.role===`tool`)return{role:`tool`,parts:e.content.map(e=>{if(e.type===`tool-result`){let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}return{type:String(e.type)}})}}}function d({text:e,reasoning:t,toolCalls:n,files:r,finishReason:i}){let a=[];if(t)for(let e of t)`text`in e&&e.text&&a.push({type:`reasoning`,content:e.text});if(e!=null&&e.length>0&&a.push({type:`text`,content:e}),n)for(let e of n)a.push({type:`tool_call`,id:e.toolCallId,name:e.toolName,arguments:e.input});if(r)for(let e of r)a.push({type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType,content:e.base64});return[{role:`assistant`,parts:a,finish_reason:p(i)}]}function f({objectText:e,finishReason:t}){return[{role:`assistant`,parts:[{type:`text`,content:e}],finish_reason:p(t)}]}function p(e){return{stop:`stop`,length:`length`,"content-filter":`content_filter`,"tool-calls":`tool_call`,error:`error`,other:`stop`,unknown:`stop`}[e]??e}function m(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function h(e){return e?.isEnabled!==!1}function g(e,t){if(!h(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var _={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function v(e){return{..._,usage:e.usage??!1,providerMetadata:e.providerMetadata??!1,embedding:e.embedding??!1,reranking:e.reranking??!1,runtimeContext:e.runtimeContext??!1,headers:e.headers??!1,toolChoice:e.toolChoice??!1,schema:e.schema??!1}}function y(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!=null).map(([e,t])=>[`ai.settings.context.${e}`,t]))}function b(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!=null).map(([e,t])=>[`ai.request.headers.${e}`,t]))}function x(e){return{"ai.usage.inputTokenDetails.noCacheTokens":e.inputTokenDetails?.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":e.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.outputTokenDetails?.reasoningTokens}}function S(e,t,n){let r={};for(let[i,a]of Object.entries(n))!t[i]||a==null||Object.assign(r,g(e,a));return r}var C=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`gen_ai`),this.supplementalAttributes=v(e),this.enrichSpan=e.enrichSpan}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}getSpanAttributes({attributes:e,spanType:t,operationId:n,callId:r,runtimeContext:i}){let a;try{a=this.enrichSpan?.call(this,{spanType:t,operationId:n,callId:r,runtimeContext:i})}catch{a=void 0}return{...a,...e}}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e),i=r?.inferenceContext??r?.stepContext;return i==null?t():n.context.with(i,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=e.runtimeContext,d=S(t,this.supplementalAttributes,{runtimeContext:y(u),headers:b(e.headers)}),f=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.stop_sequences":e.stopSequences,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.instructions?{input:()=>JSON.stringify(a(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:void 0,messages:e.messages}))},...d}),p=`${c} ${e.modelId}`,m=this.tracer.startSpan(p,{attributes:this.getSpanAttributes({attributes:f,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:u}),kind:n.SpanKind.INTERNAL}),h=n.trace.setSpan(n.context.active(),m);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:m,rootContext:h,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:u,baseSupplementalAttributes:d})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=S(t,this.supplementalAttributes,{headers:b(e.headers)}),d=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.system?{input:()=>JSON.stringify(a(e.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:e.prompt,messages:e.messages}))},...u,...S(t,this.supplementalAttributes,{schema:{"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}})}),f=`${c} ${e.modelId}`,p=this.tracer.startSpan(f,{attributes:this.getSpanAttributes({attributes:d,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.INTERNAL}),m=n.trace.setSpan(n.context.active(),p);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:p,rootContext:m,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:u})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>e.promptMessages?JSON.stringify(c(e.promptMessages)):void 0},...t.baseSupplementalAttributes}),o=`chat ${e.modelId}`;t.inferenceSpan=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),t.inferenceContext=n.trace.setSpan(t.rootContext,t.inferenceSpan)}onObjectStepFinish(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(f({objectText:e.objectText,finishReason:e.finishReason}))}catch{return e.objectText}}},...S(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:x(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=S(t,this.supplementalAttributes,{headers:b(e.headers)}),o=e.value,s=e.operationId===`ai.embedMany`,c=g(t,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...S(t,this.supplementalAttributes,{embedding:s?{"ai.values":{input:()=>o.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(o)}}})}),l=`embeddings ${e.modelId}`,u=this.tracer.startSpan(l,{attributes:this.getSpanAttributes({attributes:c,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),d=n.trace.setSpan(n.context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t;t.runtimeContext=e.runtimeContext;let i=g(r,{"gen_ai.operation.name":`agent_step`,...t.baseSupplementalAttributes,...S(r,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)}}})});t.stepSpan=this.tracer.startSpan(`step ${e.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:i,spanType:`step`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onLanguageModelCallStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>{let t=l({prompt:void 0,messages:e.messages});return t.length>0?JSON.stringify(t):void 0}},"gen_ai.tool.definitions":{input:()=>e.tools?JSON.stringify(e.tools):void 0}});t.inferenceSpan=this.tracer.startSpan(`chat ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.stepContext),t.inferenceContext=n.trace.setSpan(t.stepContext,t.inferenceSpan)}onLanguageModelCallEnd(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.responseId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)||void 0,reasoning:e.content.filter(e=>e.type===`reasoning`),toolCalls:e.content.filter(e=>e.type===`tool-call`),files:e.content.filter(e=>e.type===`file`).map(e=>e.file),finishReason:e.finishReason}))},...S(n,this.supplementalAttributes,{usage:x(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=g(r,{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":i.toolName,"gen_ai.tool.call.id":i.toolCallId,"gen_ai.tool.type":`function`,"gen_ai.tool.call.arguments":{input:()=>JSON.stringify(i.input)}}),o=`execute_tool ${i.toolName}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`tool`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.stepContext),c=n.trace.setSpan(t.stepContext,s);t.toolSpans.set(i.toolCallId,{span:s,context:c})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(g(i,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else m(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepFinish(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(S(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:x(e.usage)})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.totalUsage.inputTokens,"gen_ai.usage.output_tokens":e.totalUsage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.totalUsage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.totalUsage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.text??void 0,reasoning:e.reasoning,toolCalls:e.toolCalls,files:e.files,finishReason:e.finishReason}))},...S(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:x(e.totalUsage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onObjectOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>e.object==null?void 0:JSON.stringify(f({objectText:JSON.stringify(e.object),finishReason:e.finishReason}))},...S(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:x(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.embedMany`;t.rootSpan.setAttributes(g(n,{"gen_ai.usage.input_tokens":e.usage.tokens,...S(n,this.supplementalAttributes,{embedding:r?{"ai.embeddings":{output:()=>e.embedding.map(e=>JSON.stringify(e))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}}})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...S(i,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>e.values.map(e=>JSON.stringify(e))}}})}),o=`embeddings ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`embedding`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),c=n.trace.setSpan(t.rootContext,s);t.embedSpans.set(e.embedCallId,{span:s,context:c})}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.embedSpans.get(e.embedCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t;r.setAttributes(g(i,{"gen_ai.usage.input_tokens":e.usage.tokens,...S(i,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>e.embeddings.map(e=>JSON.stringify(e))}}})})),r.end(),t.embedSpans.delete(e.embedCallId)}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=S(t,this.supplementalAttributes,{headers:b(e.headers)}),o=g(t,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...S(t,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),s=`rerank ${e.modelId}`,c=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:o,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId))}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...S(i,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),o=`rerank ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`reranking`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext);t.rerankSpan={span:s,context:n.trace.setSpan(t.rootContext,s)}}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:n}=t.rerankSpan,{telemetry:r}=t;n.setAttributes(S(r,this.supplementalAttributes,{reranking:{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(e=>JSON.stringify(e))}}})),n.end(),t.rerankSpan=void 0}onError(e){let t=e;if(!t?.callId)return;let n=this.getCallState(t.callId);if(!n?.rootSpan)return;let r=t.error??e;for(let{span:e}of n.toolSpans.values())m(e,r),e.end();n.toolSpans.clear(),n.inferenceSpan&&(m(n.inferenceSpan,r),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0),n.stepSpan&&(m(n.stepSpan,r),n.stepSpan.end(),n.stepSpan=void 0,n.stepContext=void 0);for(let{span:e}of n.embedSpans.values())m(e,r),e.end();n.embedSpans.clear(),n.rerankSpan&&=(m(n.rerankSpan.span,r),n.rerankSpan.span.end(),void 0),m(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(t.callId)}};function w({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId==null?``:` ${t.functionId}`}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function T({model:e,settings:t,headers:n,context:r}){return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,n])=>(e[`ai.settings.${t}`]=n,e),{}),...Object.entries(r??{}).reduce((e,[t,n])=>(n!=null&&(e[`ai.settings.context.${t}`]=n),e),{}),...Object.entries(n??{}).reduce((e,[t,n])=>(n!==void 0&&(e[`ai.request.headers.${t}`]=n),e),{})}}function E(e){return JSON.stringify(e.map(e=>({...e,content:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`file`?{...e,data:D(e.data)}:e)})))}function D(e){switch(e.type){case`data`:return e.data instanceof Uint8Array?t(e.data):e.data;case`url`:return e.url.toString();case`reference`:return e.reference;case`text`:return e.text}}function O(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function k(e){return e?.isEnabled!==!1}function A(e,t){if(!k(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var j=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`ai`)}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e)?.stepContext;return r==null?t():n.context.with(r,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},i=T({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:e.runtimeContext}),a=A(t,{...w({operationId:e.operationId,telemetry:t}),...i,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt":{input:()=>JSON.stringify({system:e.instructions,messages:e.messages})}}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},i=T({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=A(t,{...w({operationId:e.operationId,telemetry:t}),...i,"ai.prompt":{input:()=>JSON.stringify({system:e.system,prompt:e.prompt,messages:e.messages})},"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamObject`?`ai.streamObject.doStream`:`ai.generateObject.doGenerate`,a=A(r,{...w({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.prompt.messages":{input:()=>e.promptMessages?E(e.promptMessages):void 0},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onObjectStepFinish(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(A(n,{"ai.response.finishReason":e.finishReason,"ai.response.object":{output:()=>{try{return JSON.stringify(JSON.parse(e.objectText))}catch{return e.objectText}}},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),e.msToFirstChunk!=null&&(t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.stream.msToFirstChunk":e.msToFirstChunk}),t.stepSpan.setAttributes({"ai.stream.msToFirstChunk":e.msToFirstChunk})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxRetries:e.maxRetries},i=T({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=e.value,o=e.operationId===`ai.embedMany`,s=A(t,{...w({operationId:e.operationId,telemetry:t}),...i,...o?{"ai.values":{input:()=>a.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(a)}}}),c=this.tracer.startSpan(e.operationId,{attributes:s}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamText`?`ai.streamText.doStream`:`ai.generateText.doGenerate`,a=A(r,{...w({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt.messages":{input:()=>e.promptMessages?E(e.promptMessages):void 0},"ai.prompt.tools":{input:()=>e.stepTools?.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=A(r,{...w({operationId:`ai.toolCall`,telemetry:r}),"ai.toolCall.name":i.toolName,"ai.toolCall.id":i.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(i.input)}}),o=this.tracer.startSpan(`ai.toolCall`,{attributes:a},t.stepContext),s=n.trace.setSpan(t.stepContext,o);t.toolSpans.set(i.toolCallId,{span:o,context:s})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(A(i,{"ai.toolCall.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else O(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepFinish(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.streamText`;t.stepSpan.setAttributes(A(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.reasoning.length>0?e.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
|
|
2
|
-
`):void 0},"ai.response.toolCalls":{output:()=>e.toolCalls.length>0?JSON.stringify(e.toolCalls.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}))):void 0},"ai.response.files":{output:()=>e.files.length>0?JSON.stringify(e.files.map(e=>({type:`file`,mediaType:e.mediaType,data:e.base64}))):void 0},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.response.msToFirstChunk":r?e.performance.
|
|
3
|
-
`):void 0},"ai.response.toolCalls":{output:()=>e.toolCalls.length>0?JSON.stringify(e.toolCalls.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}))):void 0},"ai.response.files":{output:()=>e.files.length>0?JSON.stringify(e.files.map(e=>({type:`file`,mediaType:e.mediaType,data:e.base64}))):void 0},"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.
|
|
1
|
+
import{t as e}from"../../_chunks/workflow/src-B54rYDvB.js";import{convertDataContentToBase64String as t}from"ai";var n=e();function r(e){let t=e.toLowerCase();for(let[e,n]of[[`google.vertex`,`gcp.vertex_ai`],[`google.generative-ai`,`gcp.gemini`],[`google-vertex`,`gcp.vertex_ai`],[`amazon-bedrock`,`aws.bedrock`],[`azure-openai`,`azure.ai.openai`],[`anthropic`,`anthropic`],[`openai`,`openai`],[`azure`,`azure.ai.inference`],[`google`,`gcp.gemini`],[`mistral`,`mistral_ai`],[`cohere`,`cohere`],[`bedrock`,`aws.bedrock`],[`groq`,`groq`],[`deepseek`,`deepseek`],[`perplexity`,`perplexity`],[`xai`,`x_ai`]])if(t===e||t.startsWith(e+`.`)||t.startsWith(e+`-`))return n;return e}function i(e){return{"ai.generateText":`invoke_agent`,"ai.streamText":`invoke_agent`,"ai.generateObject":`invoke_agent`,"ai.streamObject":`invoke_agent`,"ai.embed":`embeddings`,"ai.embedMany":`embeddings`,"ai.rerank":`rerank`}[e]??e}function a(e){return typeof e==`string`?[{type:`text`,content:e}]:Array.isArray(e)?e.map(e=>({type:`text`,content:e.content})):[{type:`text`,content:e.content}]}function o(e){switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})(),i;if(r instanceof Uint8Array)i=t(r);else if(typeof r==`string`){if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r};i=r}else if(r instanceof URL)return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()};else i=String(r);return{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:i}}case`tool-approval-response`:return{type:`tool_approval_response`,approval_id:e.approvalId,approved:e.approved,reason:e.reason};case`custom`:return{type:`custom`,kind:e.kind};case`reasoning-file`:return{type:String(e.type)};default:return{type:String(e.type)}}}function s(e){return!e||e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`image`}function c(e){return e.filter(e=>e.role!==`system`).map(e=>{if(e.role===`system`)return{role:`system`,parts:[{type:`text`,content:e.content}]};let t=e.content.map(o);return{role:e.role,parts:t}})}function l({prompt:e,messages:t}){let n=[];if(typeof e==`string`)n.push({role:`user`,parts:[{type:`text`,content:e}]});else if(Array.isArray(e))for(let t of e){let e=u(t);e&&n.push(e)}if(t)for(let e of t){let t=u(e);t&&n.push(t)}return n}function u(e){if(e.role!==`system`){if(e.role===`user`)return typeof e.content==`string`?{role:`user`,parts:[{type:`text`,content:e.content}]}:{role:`user`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`image`:{let n=e.image;return n instanceof URL?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n.toString()}:typeof n==`string`?n.startsWith(`http://`)||n.startsWith(`https://`)?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:t(n)}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})();return r instanceof URL?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()}:typeof r==`string`?r.startsWith(`http://`)||r.startsWith(`https://`)?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:t(r)}}default:return{type:String(e.type)}}})};if(e.role===`assistant`)return typeof e.content==`string`?{role:`assistant`,parts:[{type:`text`,content:e.content}]}:{role:`assistant`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}default:return{type:String(e.type)}}})};if(e.role===`tool`)return{role:`tool`,parts:e.content.map(e=>{if(e.type===`tool-result`){let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}return{type:String(e.type)}})}}}function d({text:e,reasoning:t,toolCalls:n,files:r,finishReason:i}){let a=[];if(t)for(let e of t)`text`in e&&e.text&&a.push({type:`reasoning`,content:e.text});if(e!=null&&e.length>0&&a.push({type:`text`,content:e}),n)for(let e of n)a.push({type:`tool_call`,id:e.toolCallId,name:e.toolName,arguments:e.input});if(r)for(let e of r)a.push({type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType,content:e.base64});return[{role:`assistant`,parts:a,finish_reason:p(i)}]}function f({objectText:e,finishReason:t}){return[{role:`assistant`,parts:[{type:`text`,content:e}],finish_reason:p(t)}]}function p(e){return{stop:`stop`,length:`length`,"content-filter":`content_filter`,"tool-calls":`tool_call`,error:`error`,other:`stop`,unknown:`stop`}[e]??e}function m(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function h(e){return e?.isEnabled!==!1}function g(e,t){if(!h(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var _={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function v(e){return{..._,usage:e.usage??!1,providerMetadata:e.providerMetadata??!1,embedding:e.embedding??!1,reranking:e.reranking??!1,runtimeContext:e.runtimeContext??!1,headers:e.headers??!1,toolChoice:e.toolChoice??!1,schema:e.schema??!1}}function y(e){let t={};for(let[n,r]of Object.entries(e??{}))b(t,`ai.settings.context.${n}`,r);return t}function b(e,t,n){if(n!=null){if(Array.isArray(n)||typeof n!=`object`){e[t]=n;return}for(let[r,i]of Object.entries(n))b(e,`${t}.${r}`,i)}}function x(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!=null).map(([e,t])=>[`ai.request.headers.${e}`,t]))}function S(e){return{"ai.usage.inputTokenDetails.noCacheTokens":e.inputTokenDetails?.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":e.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.outputTokenDetails?.reasoningTokens}}function C(e,t,n){let r={};for(let[i,a]of Object.entries(n))!t[i]||a==null||Object.assign(r,g(e,a));return r}var w=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`gen_ai`),this.supplementalAttributes=v(e),this.enrichSpan=e.enrichSpan}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}getSpanAttributes({attributes:e,spanType:t,operationId:n,callId:r,runtimeContext:i}){let a;try{a=this.enrichSpan?.call(this,{spanType:t,operationId:n,callId:r,runtimeContext:i})}catch{a=void 0}return{...a,...e}}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e),i=r?.inferenceContext??r?.stepContext;return i==null?t():n.context.with(i,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=e.runtimeContext,d=C(t,this.supplementalAttributes,{runtimeContext:y(u),headers:x(e.headers)}),f=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.stop_sequences":e.stopSequences,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.instructions?{input:()=>JSON.stringify(a(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:void 0,messages:e.messages}))},...d}),p=`${c} ${e.modelId}`,m=this.tracer.startSpan(p,{attributes:this.getSpanAttributes({attributes:f,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:u}),kind:n.SpanKind.INTERNAL}),h=n.trace.setSpan(n.context.active(),m);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:m,rootContext:h,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:u,baseSupplementalAttributes:d})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=C(t,this.supplementalAttributes,{headers:x(e.headers)}),d=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.system?{input:()=>JSON.stringify(a(e.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:e.prompt,messages:e.messages}))},...u,...C(t,this.supplementalAttributes,{schema:{"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}})}),f=`${c} ${e.modelId}`,p=this.tracer.startSpan(f,{attributes:this.getSpanAttributes({attributes:d,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.INTERNAL}),m=n.trace.setSpan(n.context.active(),p);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:p,rootContext:m,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:u})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>e.promptMessages?JSON.stringify(c(e.promptMessages)):void 0},...t.baseSupplementalAttributes}),o=`chat ${e.modelId}`;t.inferenceSpan=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),t.inferenceContext=n.trace.setSpan(t.rootContext,t.inferenceSpan)}onObjectStepFinish(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(f({objectText:e.objectText,finishReason:e.finishReason}))}catch{return e.objectText}}},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=e.value,s=e.operationId===`ai.embedMany`,c=g(t,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{embedding:s?{"ai.values":{input:()=>o.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(o)}}})}),l=`embeddings ${e.modelId}`,u=this.tracer.startSpan(l,{attributes:this.getSpanAttributes({attributes:c,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),d=n.trace.setSpan(n.context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t;t.runtimeContext=e.runtimeContext;let i=g(r,{"gen_ai.operation.name":`agent_step`,...t.baseSupplementalAttributes,...C(r,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)}}})});t.stepSpan=this.tracer.startSpan(`step ${e.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:i,spanType:`step`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onLanguageModelCallStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>{let t=l({prompt:void 0,messages:e.messages});return t.length>0?JSON.stringify(t):void 0}},"gen_ai.tool.definitions":{input:()=>e.tools?JSON.stringify(e.tools):void 0}});t.inferenceSpan=this.tracer.startSpan(`chat ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.stepContext),t.inferenceContext=n.trace.setSpan(t.stepContext,t.inferenceSpan)}onLanguageModelCallEnd(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.responseId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)||void 0,reasoning:e.content.filter(e=>e.type===`reasoning`),toolCalls:e.content.filter(e=>e.type===`tool-call`),files:e.content.filter(e=>e.type===`file`).map(e=>e.file),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=g(r,{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":i.toolName,"gen_ai.tool.call.id":i.toolCallId,"gen_ai.tool.type":`function`,"gen_ai.tool.call.arguments":{input:()=>JSON.stringify(i.input)}}),o=`execute_tool ${i.toolName}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`tool`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.stepContext),c=n.trace.setSpan(t.stepContext,s);t.toolSpans.set(i.toolCallId,{span:s,context:c})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(g(i,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else m(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepFinish(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.text??void 0,reasoning:e.finalStep.reasoning,toolCalls:e.toolCalls,files:e.files,finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onObjectOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>e.object==null?void 0:JSON.stringify(f({objectText:JSON.stringify(e.object),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.embedMany`;t.rootSpan.setAttributes(g(n,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(n,this.supplementalAttributes,{embedding:r?{"ai.embeddings":{output:()=>e.embedding.map(e=>JSON.stringify(e))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}}})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>e.values.map(e=>JSON.stringify(e))}}})}),o=`embeddings ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`embedding`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),c=n.trace.setSpan(t.rootContext,s);t.embedSpans.set(e.embedCallId,{span:s,context:c})}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.embedSpans.get(e.embedCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t;r.setAttributes(g(i,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(i,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>e.embeddings.map(e=>JSON.stringify(e))}}})})),r.end(),t.embedSpans.delete(e.embedCallId)}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=g(t,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),s=`rerank ${e.modelId}`,c=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:o,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId))}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),o=`rerank ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`reranking`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext);t.rerankSpan={span:s,context:n.trace.setSpan(t.rootContext,s)}}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:n}=t.rerankSpan,{telemetry:r}=t;n.setAttributes(C(r,this.supplementalAttributes,{reranking:{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(e=>JSON.stringify(e))}}})),n.end(),t.rerankSpan=void 0}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:e}of t.toolSpans.values())e.end();t.toolSpans.clear(),t.inferenceSpan&&(t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:e}of t.embedSpans.values())e.end();t.embedSpans.clear(),t.rerankSpan&&=(t.rerankSpan.span.end(),void 0),t.rootSpan.end(),this.cleanupCallState(e.callId)}}onError(e){let t=e;if(!t?.callId)return;let n=this.getCallState(t.callId);if(!n?.rootSpan)return;let r=t.error??e;for(let{span:e}of n.toolSpans.values())m(e,r),e.end();n.toolSpans.clear(),n.inferenceSpan&&(m(n.inferenceSpan,r),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0),n.stepSpan&&(m(n.stepSpan,r),n.stepSpan.end(),n.stepSpan=void 0,n.stepContext=void 0);for(let{span:e}of n.embedSpans.values())m(e,r),e.end();n.embedSpans.clear(),n.rerankSpan&&=(m(n.rerankSpan.span,r),n.rerankSpan.span.end(),void 0),m(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(t.callId)}};function T({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId==null?``:` ${t.functionId}`}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function E({model:e,settings:t,headers:n,context:r}){return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,n])=>(e[`ai.settings.${t}`]=n,e),{}),...y(r),...Object.entries(n??{}).reduce((e,[t,n])=>(n!==void 0&&(e[`ai.request.headers.${t}`]=n),e),{})}}function D(e){return JSON.stringify(e.map(e=>({...e,content:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`file`?{...e,data:O(e.data)}:e)})))}function O(e){switch(e.type){case`data`:return e.data instanceof Uint8Array?t(e.data):e.data;case`url`:return e.url.toString();case`reference`:return e.reference;case`text`:return e.text}}function k(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function A(e){return e?.isEnabled!==!1}function j(e,t){if(!A(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var M=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`ai`)}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e)?.stepContext;return r==null?t():n.context.with(r,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:e.runtimeContext}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt":{input:()=>JSON.stringify({system:e.instructions,messages:e.messages})}}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.prompt":{input:()=>JSON.stringify({system:e.system,prompt:e.prompt,messages:e.messages})},"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamObject`?`ai.streamObject.doStream`:`ai.generateObject.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onObjectStepFinish(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.object":{output:()=>{try{return JSON.stringify(JSON.parse(e.objectText))}catch{return e.objectText}}},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),e.msToFirstChunk!=null&&(t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.stream.msToFirstChunk":e.msToFirstChunk}),t.stepSpan.setAttributes({"ai.stream.msToFirstChunk":e.msToFirstChunk})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=e.value,o=e.operationId===`ai.embedMany`,s=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,...o?{"ai.values":{input:()=>a.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(a)}}}),c=this.tracer.startSpan(e.operationId,{attributes:s}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamText`?`ai.streamText.doStream`:`ai.generateText.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"ai.prompt.tools":{input:()=>e.stepTools?.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=j(r,{...T({operationId:`ai.toolCall`,telemetry:r}),"ai.toolCall.name":i.toolName,"ai.toolCall.id":i.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(i.input)}}),o=this.tracer.startSpan(`ai.toolCall`,{attributes:a},t.stepContext),s=n.trace.setSpan(t.stepContext,o);t.toolSpans.set(i.toolCallId,{span:o,context:s})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(j(i,{"ai.toolCall.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else k(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepFinish(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.streamText`;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.reasoning.length>0?e.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
|
|
2
|
+
`):void 0},"ai.response.toolCalls":{output:()=>e.toolCalls.length>0?JSON.stringify(e.toolCalls.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}))):void 0},"ai.response.files":{output:()=>e.files.length>0?JSON.stringify(e.files.map(e=>({type:`file`,mediaType:e.mediaType,data:e.base64}))):void 0},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.response.msToFirstChunk":r?e.performance.timeToFirstOutputMs:void 0,"ai.response.msToFinish":r?e.performance.responseTimeMs:void 0,"ai.response.avgOutputTokensPerSecond":r?e.performance.effectiveOutputTokensPerSecond:void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.noCacheTokens":e.usage.inputTokenDetails?.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":e.usage.inputTokenDetails?.cacheWriteTokens,"ai.usage.outputTokenDetails.textTokens":e.usage.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),r&&e.performance.timeToFirstOutputMs!=null&&t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.response.msToFirstChunk":e.performance.timeToFirstOutputMs}),r&&t.stepSpan.addEvent(`ai.stream.finish`,{"ai.response.msToFinish":e.performance.responseTimeMs,"ai.response.avgOutputTokensPerSecond":e.performance.effectiveOutputTokensPerSecond}),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.finalStep.reasoning.length>0?e.finalStep.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
|
|
3
|
+
`):void 0},"ai.response.toolCalls":{output:()=>e.toolCalls.length>0?JSON.stringify(e.toolCalls.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}))):void 0},"ai.response.files":{output:()=>e.files.length>0?JSON.stringify(e.files.map(e=>({type:`file`,mediaType:e.mediaType,data:e.base64}))):void 0},"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.noCacheTokens":e.usage.inputTokenDetails?.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":e.usage.inputTokenDetails?.cacheWriteTokens,"ai.usage.outputTokenDetails.textTokens":e.usage.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onObjectOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.object":{output:()=>e.object==null?void 0:JSON.stringify(e.object)},"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.embedMany`;t.rootSpan.setAttributes(j(n,{...r?{"ai.embeddings":{output:()=>e.embedding.map(e=>JSON.stringify(e))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}},"ai.usage.tokens":e.usage.tokens})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=j(r,{...T({operationId:e.operationId,telemetry:r}),...t.baseTelemetryAttributes,"ai.values":{input:()=>e.values.map(e=>JSON.stringify(e))}}),a=this.tracer.startSpan(e.operationId,{attributes:i},t.rootContext),o=n.trace.setSpan(t.rootContext,a);t.embedSpans.set(e.embedCallId,{span:a,context:o})}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.embedSpans.get(e.embedCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t;r.setAttributes(j(i,{"ai.embeddings":{output:()=>e.embeddings.map(e=>JSON.stringify(e))},"ai.usage.tokens":e.usage.tokens})),r.end(),t.embedSpans.delete(e.embedCallId)}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId))}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=j(r,{...T({operationId:e.operationId,telemetry:r}),...t.baseTelemetryAttributes,"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}),a=this.tracer.startSpan(e.operationId,{attributes:i},t.rootContext);t.rerankSpan={span:a,context:n.trace.setSpan(t.rootContext,a)}}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:n}=t.rerankSpan,{telemetry:r}=t;n.setAttributes(j(r,{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(e=>JSON.stringify(e))}})),n.end(),t.rerankSpan=void 0}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:e}of t.toolSpans.values())e.end();t.toolSpans.clear(),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:e}of t.embedSpans.values())e.end();t.embedSpans.clear(),t.rerankSpan&&=(t.rerankSpan.span.end(),void 0),t.rootSpan.end(),this.cleanupCallState(e.callId)}}onError(e){let t=e;if(!t?.callId)return;let n=this.getCallState(t.callId);if(!n?.rootSpan)return;let r=t.error??e;n.stepSpan&&(k(n.stepSpan,r),n.stepSpan.end());for(let{span:e}of n.embedSpans.values())k(e,r),e.end();n.embedSpans.clear(),n.rerankSpan&&=(k(n.rerankSpan.span,r),n.rerankSpan.span.end(),void 0),k(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(t.callId)}};export{M as LegacyOpenTelemetry,w as OpenTelemetry};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e)),u=e(import.meta.url),d=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}})),f=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{VercelOidcTokenError:()=>u}),t.exports=c(l);var u=class extends Error{constructor(e,t){super(e),this.name=`VercelOidcTokenError`,this.cause=t}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}}})),p=s(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),p=e=>l(r({},`__esModule`,{value:!0}),e),m={};c(m,{findRootDir:()=>y,getUserDataDir:()=>b}),t.exports=p(m);var h=d(u(`path`)),g=d(u(`fs`)),_=d(u(`os`)),v=f();function y(){try{let e=process.cwd();for(;e!==h.default.dirname(e);){let t=h.default.join(e,`.vercel`);if(g.default.existsSync(t))return e;e=h.default.dirname(e)}}catch{throw new v.VercelOidcTokenError(`Token refresh only supported in node server environments`)}return null}function b(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(_.default.platform()){case`darwin`:return h.default.join(_.default.homedir(),`Library/Application Support`);case`linux`:return h.default.join(_.default.homedir(),`.local/share`);case`win32`:return process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:null;default:return null}}})),m=s(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),p={};c(p,{isValidAccessToken:()=>x,readAuthConfig:()=>y,writeAuthConfig:()=>b}),t.exports=f(p);var m=d(u(`fs`)),h=d(u(`path`)),g=_();function v(){let e=(0,g.getVercelDataDir)();if(!e)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(e,`auth.json`)}function y(){try{let e=v();if(!m.existsSync(e))return null;let t=m.readFileSync(e,`utf8`);return t?JSON.parse(t):null}catch{return null}}function b(e){let t=v(),n=h.dirname(t);m.existsSync(n)||m.mkdirSync(n,{mode:504,recursive:!0}),m.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}function x(e,t=0){if(!e.token)return!1;if(typeof e.expiresAt!=`number`)return!0;let n=Math.floor(Date.now()/1e3),r=t/1e3;return e.expiresAt>=n+r}})),h=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{processTokenResponse:()=>g,refreshTokenRequest:()=>h}),t.exports=c(l);var d=u(`os`);let f=`@vercel/oidc node-${process.version} ${(0,d.platform)()} (${(0,d.arch)()}) ${(0,d.hostname)()}`,p=null;async function m(){if(p)return p;let e=await fetch(`https://vercel.com/.well-known/openid-configuration`,{headers:{"user-agent":f}});if(!e.ok)throw Error(`Failed to discover OAuth endpoints`);let t=await e.json();if(!t||typeof t.token_endpoint!=`string`)throw Error(`Invalid OAuth discovery response`);let n=t.token_endpoint;return p=n,n}async function h(e){let t=await m();return await fetch(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":f},body:new URLSearchParams({client_id:`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,grant_type:`refresh_token`,...e})})}async function g(e){let t=await e.json();if(!e.ok){let e=typeof t==`object`&&t&&`error`in t?String(t.error):`Token refresh failed`;return[Error(e)]}return typeof t!=`object`||!t?[Error(`Invalid token response`)]:typeof t.access_token==`string`?t.token_type===`Bearer`?typeof t.expires_in==`number`?[null,t]:[Error(`Missing expires_in in response`)]:[Error(`Invalid token_type in response`)]:[Error(`Missing access_token in response`)]}})),g=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>u,RefreshAccessTokenFailedError:()=>d}),t.exports=c(l);var u=class extends Error{constructor(){super(`No authentication found. Please log in with the Vercel CLI (vercel login).`),this.name=`AccessTokenMissingError`}},d=class extends Error{constructor(e){super(`Failed to refresh authentication token.`,{cause:e}),this.name=`RefreshAccessTokenFailedError`}}})),_=s(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),_=e=>l(r({},`__esModule`,{value:!0}),e),v={};c(v,{assertVercelOidcTokenResponse:()=>k,findProjectInfo:()=>A,getTokenPayload:()=>N,getVercelDataDir:()=>E,getVercelOidcToken:()=>O,getVercelToken:()=>D,isExpired:()=>P,loadToken:()=>M,saveToken:()=>j}),t.exports=_(v);var y=d(u(`path`)),b=d(u(`fs`)),x=f(),S=p(),C=m(),w=h(),T=g();function E(){let e=(0,S.getUserDataDir)();return e?y.join(e,`com.vercel.cli`):null}async function D(e){let t=(0,C.readAuthConfig)();if(!t?.token)throw new T.AccessTokenMissingError;if((0,C.isValidAccessToken)(t,e?.expirationBufferMs))return t.token;if(!t.refreshToken)throw(0,C.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(`No refresh token available`);try{let e=await(0,w.refreshTokenRequest)({refresh_token:t.refreshToken}),[n,r]=await(0,w.processTokenResponse)(e);if(n||!r)throw(0,C.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(n);let i={token:r.access_token,expiresAt:Math.floor(Date.now()/1e3)+r.expires_in};return r.refresh_token&&(i.refreshToken=r.refresh_token),(0,C.writeAuthConfig)(i),i.token}catch(e){throw(0,C.writeAuthConfig)({}),e instanceof T.AccessTokenMissingError||e instanceof T.RefreshAccessTokenFailedError?e:new T.RefreshAccessTokenFailedError(e)}}async function O(e,t,n){let r=`https://api.vercel.com/v1/projects/${t}/token?source=vercel-oidc-refresh${n?`&teamId=${n}`:``}`,i=await fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new x.VercelOidcTokenError(`Failed to refresh OIDC token: ${i.statusText}`);let a=await i.json();return k(a),a}function k(e){if(!e||typeof e!=`object`)throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!(`token`in e)||typeof e.token!=`string`)throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function A(){let e=(0,S.findRootDir)();if(!e)throw new x.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let t=y.join(e,`.vercel`,`project.json`);if(!b.existsSync(t))throw new x.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let n=JSON.parse(b.readFileSync(t,`utf8`));if(typeof n.projectId!=`string`&&typeof n.orgId!=`string`)throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:n.projectId,teamId:n.orgId}}function j(e,t){let n=(0,S.getUserDataDir)();if(!n)throw new x.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let r=y.join(n,`com.vercel.token`,`${t}.json`),i=JSON.stringify(e);b.mkdirSync(y.dirname(r),{mode:504,recursive:!0}),b.writeFileSync(r,i),b.chmodSync(r,432)}function M(e){let t=(0,S.getUserDataDir)();if(!t)throw new x.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let n=y.join(t,`com.vercel.token`,`${e}.json`);if(!b.existsSync(n))return null;let r=JSON.parse(b.readFileSync(n,`utf8`));return k(r),r}function N(e){let t=e.split(`.`);if(t.length!==3)throw new x.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=n.padEnd(n.length+(4-n.length%4)%4,`=`);return JSON.parse(Buffer.from(r,`base64`).toString(`utf8`))}function P(e,t=0){return e.exp*1e3<Date.now()+t}})),v=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{refreshToken:()=>p}),t.exports=c(l);var u=f(),d=_();async function p(e){let t=e?.project,n=e?.team;if(!t&&!n){let e=(0,d.findProjectInfo)();t=e.projectId,n=e.teamId}else if(!t||!n){let e=(0,d.findProjectInfo)();t??=e.projectId,n??=e.teamId}if(!t)throw new u.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let r=(0,d.loadToken)(t);if(!r||(0,d.isExpired)((0,d.getTokenPayload)(r.token),e?.expirationBufferMs)){let i=await(0,d.getVercelToken)({expirationBufferMs:e?.expirationBufferMs});if(r=await(0,d.getVercelOidcToken)(i,t,n),!r)throw new u.VercelOidcTokenError(`Failed to refresh OIDC token`);(0,d.saveToken)(r,t)}process.env.VERCEL_OIDC_TOKEN=r.token}})),y=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),u={};o(u,{getVercelOidcToken:()=>h,getVercelOidcTokenSync:()=>g}),t.exports=c(u);var p=d(),m=f();async function h(e){let t=``,n;try{t=g()}catch(e){n=e}try{let[{getTokenPayload:n,isExpired:r},{refreshToken:i}]=await Promise.all([await Promise.resolve().then(()=>l(_())),await Promise.resolve().then(()=>l(v()))]);(!t||r(n(t),e?.expirationBufferMs))&&(await i(e),t=g())}catch(e){let t=n instanceof Error?n.message:``;throw e instanceof Error&&(t=`${t}
|
|
2
|
-
${e.message}`),t?new m.VercelOidcTokenError(t):e}return t}
|
|
1
|
+
import{createRequire as e}from"node:module";var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e)),u=e(import.meta.url),d=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}})),f=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{getVercelOidcTokenSync:()=>f}),t.exports=c(l);var u=d();function f(){let e=(0,u.getContext)().headers?.[`x-vercel-oidc-token`]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error(`The 'x-vercel-oidc-token' header is missing from the request.`);return e}})),p=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{VercelOidcTokenError:()=>u}),t.exports=c(l);var u=class extends Error{constructor(e,t){super(e),this.name=`VercelOidcTokenError`,this.cause=t}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}}})),m=s(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),m={};c(m,{findRootDir:()=>y,getUserDataDir:()=>b}),t.exports=f(m);var h=d(u(`path`)),g=d(u(`fs`)),_=d(u(`os`)),v=p();function y(){try{let e=process.cwd();for(;e!==h.default.dirname(e);){let t=h.default.join(e,`.vercel`);if(g.default.existsSync(t))return e;e=h.default.dirname(e)}}catch{throw new v.VercelOidcTokenError(`Token refresh only supported in node server environments`)}return null}function b(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(_.default.platform()){case`darwin`:return h.default.join(_.default.homedir(),`Library/Application Support`);case`linux`:return h.default.join(_.default.homedir(),`.local/share`);case`win32`:return process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:null;default:return null}}})),h=s(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),p={};c(p,{isValidAccessToken:()=>x,readAuthConfig:()=>y,writeAuthConfig:()=>b}),t.exports=f(p);var m=d(u(`fs`)),h=d(u(`path`)),g=v();function _(){let e=(0,g.getVercelDataDir)();if(!e)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(e,`auth.json`)}function y(){try{let e=_();if(!m.existsSync(e))return null;let t=m.readFileSync(e,`utf8`);return t?JSON.parse(t):null}catch{return null}}function b(e){let t=_(),n=h.dirname(t);m.existsSync(n)||m.mkdirSync(n,{mode:504,recursive:!0}),m.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}function x(e,t=0){if(!e.token)return!1;if(typeof e.expiresAt!=`number`)return!0;let n=Math.floor(Date.now()/1e3),r=t/1e3;return e.expiresAt>=n+r}})),g=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{processTokenResponse:()=>g,refreshTokenRequest:()=>h}),t.exports=c(l);var d=u(`os`);let f=`@vercel/oidc node-${process.version} ${(0,d.platform)()} (${(0,d.arch)()}) ${(0,d.hostname)()}`,p=null;async function m(){if(p)return p;let e=await fetch(`https://vercel.com/.well-known/openid-configuration`,{headers:{"user-agent":f}});if(!e.ok)throw Error(`Failed to discover OAuth endpoints`);let t=await e.json();if(!t||typeof t.token_endpoint!=`string`)throw Error(`Invalid OAuth discovery response`);let n=t.token_endpoint;return p=n,n}async function h(e){let t=await m();return await fetch(t,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":f},body:new URLSearchParams({client_id:`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,grant_type:`refresh_token`,...e})})}async function g(e){let t=await e.json();if(!e.ok){let e=typeof t==`object`&&t&&`error`in t?String(t.error):`Token refresh failed`;return[Error(e)]}return typeof t!=`object`||!t?[Error(`Invalid token response`)]:typeof t.access_token==`string`?t.token_type===`Bearer`?typeof t.expires_in==`number`?[null,t]:[Error(`Missing expires_in in response`)]:[Error(`Invalid token_type in response`)]:[Error(`Missing access_token in response`)]}})),_=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>u,RefreshAccessTokenFailedError:()=>d}),t.exports=c(l);var u=class extends Error{constructor(){super(`No authentication found. Please log in with the Vercel CLI (vercel login).`),this.name=`AccessTokenMissingError`}},d=class extends Error{constructor(e){super(`Failed to refresh authentication token.`,{cause:e}),this.name=`RefreshAccessTokenFailedError`}}})),v=s(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},d=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),v={};c(v,{assertVercelOidcTokenResponse:()=>k,findProjectInfo:()=>A,getTokenPayload:()=>N,getVercelDataDir:()=>E,getVercelOidcToken:()=>O,getVercelToken:()=>D,isExpired:()=>P,loadToken:()=>M,saveToken:()=>j}),t.exports=f(v);var y=d(u(`path`)),b=d(u(`fs`)),x=p(),S=m(),C=h(),w=g(),T=_();function E(){let e=(0,S.getUserDataDir)();return e?y.join(e,`com.vercel.cli`):null}async function D(e){let t=(0,C.readAuthConfig)();if(!t?.token)throw new T.AccessTokenMissingError;if((0,C.isValidAccessToken)(t,e?.expirationBufferMs))return t.token;if(!t.refreshToken)throw(0,C.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(`No refresh token available`);try{let e=await(0,w.refreshTokenRequest)({refresh_token:t.refreshToken}),[n,r]=await(0,w.processTokenResponse)(e);if(n||!r)throw(0,C.writeAuthConfig)({}),new T.RefreshAccessTokenFailedError(n);let i={token:r.access_token,expiresAt:Math.floor(Date.now()/1e3)+r.expires_in};return r.refresh_token&&(i.refreshToken=r.refresh_token),(0,C.writeAuthConfig)(i),i.token}catch(e){throw(0,C.writeAuthConfig)({}),e instanceof T.AccessTokenMissingError||e instanceof T.RefreshAccessTokenFailedError?e:new T.RefreshAccessTokenFailedError(e)}}async function O(e,t,n){let r=`https://api.vercel.com/v1/projects/${t}/token?source=vercel-oidc-refresh${n?`&teamId=${n}`:``}`,i=await fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new x.VercelOidcTokenError(`Failed to refresh OIDC token: ${i.statusText}`);let a=await i.json();return k(a),a}function k(e){if(!e||typeof e!=`object`)throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!(`token`in e)||typeof e.token!=`string`)throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function A(){let e=(0,S.findRootDir)();if(!e)throw new x.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let t=y.join(e,`.vercel`,`project.json`);if(!b.existsSync(t))throw new x.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let n=JSON.parse(b.readFileSync(t,`utf8`));if(typeof n.projectId!=`string`&&typeof n.orgId!=`string`)throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:n.projectId,teamId:n.orgId}}function j(e,t){let n=(0,S.getUserDataDir)();if(!n)throw new x.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let r=y.join(n,`com.vercel.token`,`${t}.json`),i=JSON.stringify(e);b.mkdirSync(y.dirname(r),{mode:504,recursive:!0}),b.writeFileSync(r,i),b.chmodSync(r,432)}function M(e){let t=(0,S.getUserDataDir)();if(!t)throw new x.VercelOidcTokenError(`Unable to find user data directory. Please reach out to Vercel support.`);let n=y.join(t,`com.vercel.token`,`${e}.json`);if(!b.existsSync(n))return null;let r=JSON.parse(b.readFileSync(n,`utf8`));return k(r),r}function N(e){let t=e.split(`.`);if(t.length!==3)throw new x.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=n.padEnd(n.length+(4-n.length%4)%4,`=`);return JSON.parse(Buffer.from(r,`base64`).toString(`utf8`))}function P(e,t=0){return e.exp*1e3<Date.now()+t}})),y=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{refreshToken:()=>f}),t.exports=c(l);var u=p(),d=v();async function f(e){let t=e?.project,n=e?.team;if(!t&&!n){let e=(0,d.findProjectInfo)();t=e.projectId,n=e.teamId}else if(!t||!n){let e=(0,d.findProjectInfo)();t??=e.projectId,n??=e.teamId}if(!t)throw new u.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let r=(0,d.loadToken)(t);if(!r||(0,d.isExpired)((0,d.getTokenPayload)(r.token),e?.expirationBufferMs)){let i=await(0,d.getVercelToken)({expirationBufferMs:e?.expirationBufferMs});if(r=await(0,d.getVercelOidcToken)(i,t,n),!r)throw new u.VercelOidcTokenError(`Failed to refresh OIDC token`);(0,d.saveToken)(r,t)}process.env.VERCEL_OIDC_TOKEN=r.token}})),b=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),u={};o(u,{getVercelOidcToken:()=>h}),t.exports=c(u);var d=f(),m=p();async function h(e){let t=``,n;try{t=(0,d.getVercelOidcTokenSync)()}catch(e){n=e}try{let[{getTokenPayload:n,isExpired:r},{refreshToken:i}]=await Promise.all([await Promise.resolve().then(()=>l(v())),await Promise.resolve().then(()=>l(y()))]);(!t||r(n(t),e?.expirationBufferMs))&&(await i(e),t=(0,d.getVercelOidcTokenSync)())}catch(e){let t=n instanceof Error?n.message:``;throw e instanceof Error&&(t=`${t}
|
|
2
|
+
${e.message}`),t?new m.VercelOidcTokenError(t):e}return t}})),x=s(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{AccessTokenMissingError:()=>h.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>h.RefreshAccessTokenFailedError,getContext:()=>m.getContext,getVercelOidcToken:()=>u.getVercelOidcToken,getVercelOidcTokenSync:()=>p.getVercelOidcTokenSync,getVercelToken:()=>g.getVercelToken}),t.exports=c(l);var u=b(),p=f(),m=d(),h=_(),g=v()}))(),S=x.AccessTokenMissingError,C=x.RefreshAccessTokenFailedError,w=x.getContext,T=x.getVercelOidcToken,E=x.getVercelOidcTokenSync,D=x.getVercelToken;export{S as AccessTokenMissingError,C as RefreshAccessTokenFailedError,w as getContext,T as getVercelOidcToken,E as getVercelOidcTokenSync,D as getVercelToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest}from"#compiler/manifest.js";function compileFromMemory(t){let n=t.appRoot??`/virtual/ash-memory-app`,r=t.agentRoot??`${n}/agent`,i=t.name??`memory-agent`,a={
|
|
1
|
+
import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest}from"#compiler/manifest.js";function compileFromMemory(t){let n=t.appRoot??`/virtual/ash-memory-app`,r=t.agentRoot??`${n}/agent`,i=t.name??`memory-agent`,a={model:{id:t.model},name:i},o=(t.tools??[]).map(e=>({description:e.description??`${e.name} test tool.`,inputSchema:e.inputSchema??null,logicalPath:`tools/${e.name}.ts`,name:e.name,sourceId:createMemorySourceId(`tools/${e.name}.ts`),sourceKind:`module`}));return{manifest:createCompiledAgentManifest({agentRoot:r,appRoot:n,config:a,skills:(t.skills??[]).map(e=>({description:e.description,logicalPath:`skills/${e.name}.md`,markdown:e.markdown??`# ${e.name}\n`,name:e.name,sourceId:createMemorySourceId(`skills/${e.name}.md`),sourceKind:`markdown`})),tools:o}),moduleMap:{nodes:{[ROOT_COMPILED_AGENT_NODE_ID]:{modules:Object.fromEntries(o.map(e=>[e.sourceId,Object.freeze({})]))}}}}}function createMemorySourceId(e){return`memory::${e}`}export{compileFromMemory};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const COMPILED_AGENT_MANIFEST_KIND=`ash-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=24,moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`)]),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional()}).strict(),disabledCompiledChannelEntrySchema=z.object({kind:z.literal(`disabled`),name:z.string(),logicalPath:z.string()}).strict(),compiledChannelEntrySchema=z.union([compiledChannelDefinitionSchema,disabledCompiledChannelEntrySchema]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),source:moduleSourceRefSchema.optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional()}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),compiledAgentConfigSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),description:z.string().optional(),
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const COMPILED_AGENT_MANIFEST_KIND=`ash-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=24,moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`)]),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional()}).strict(),disabledCompiledChannelEntrySchema=z.object({kind:z.literal(`disabled`),name:z.string(),logicalPath:z.string()}).strict(),compiledChannelEntrySchema=z.union([compiledChannelDefinitionSchema,disabledCompiledChannelEntrySchema]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),source:moduleSourceRefSchema.optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional()}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),compiledAgentConfigSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),description:z.string().optional(),model:compiledRuntimeModelReferenceSchema,name:z.string(),source:moduleSourceRefSchema.optional()}).strict(),compiledInstructionsSchema=z.object({name:z.string(),logicalPath:z.string(),markdown:z.string(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSkillBaseFields={name:z.string(),description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional(),sourceId:z.string(),logicalPath:z.string()},compiledSkillSourceSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledSkillBaseFields,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`skill-package`),skillId:z.string(),skillFilePath:z.string(),rootPath:z.string(),assetsPath:z.string().optional(),referencesPath:z.string().optional(),scriptsPath:z.string().optional()}).strict()]),compiledScheduleDefinitionSchema=z.object({cron:z.string(),hasRun:z.boolean(),name:z.string(),logicalPath:z.string(),markdown:z.string().optional(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSandboxDefinitionSchema=z.object({description:z.string().optional(),exportName:z.string().optional(),logicalPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSandboxWorkspaceSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly(),sourceId:z.string(),sourcePath:z.string()}).strict(),compiledWorkspaceResourceRootSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly()}).strict(),compiledConnectionDefinitionSchema=z.object({connectionName:z.string(),description:z.string(),exportName:z.string().optional(),logicalPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string(),vercelConnect:z.object({connector:z.string()}).strict().optional()}).strict(),compiledToolDefinitionSchema=z.object({description:z.string(),exportName:z.string().optional(),inputSchema:jsonObjectSchema.nullable(),logicalPath:z.string(),name:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledHookDefinitionSchema=z.object({exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledAgentNodeManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),hooks:z.array(compiledHookDefinitionSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),remoteAgents:z.array(compiledRemoteAgentNodeSchema),skills:z.array(compiledSkillSourceSchema).readonly(),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict(),compiledSubagentNodeSchema=z.object({agent:compiledAgentNodeManifestSchema,description:z.string(),entryPath:z.string(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),compiledSubagentEdgeSchema=z.object({childNodeId:z.string(),parentNodeId:z.string()}).strict(),compiledAgentManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),hooks:z.array(compiledHookDefinitionSchema),kind:z.literal(COMPILED_AGENT_MANIFEST_KIND),remoteAgents:z.array(compiledRemoteAgentNodeSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),skills:z.array(compiledSkillSourceSchema).readonly(),subagentEdges:z.array(compiledSubagentEdgeSchema),subagents:z.array(compiledSubagentNodeSchema),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),version:z.literal(24),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict();function createCompiledAgentNodeManifest(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:cloneCompiledRuntimeModelReference(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,model:cloneCompiledRuntimeModelReference(e.config.model),name:e.config.name,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],hooks:[...e.hooks??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:deriveResourceRootEntries({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function deriveResourceRootEntries(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function createCompiledSubagentNodeId(e,t){return e===`__root__`?t:`${e}::${t}`}function createCompiledAgentManifest(e){return{...createCompiledAgentNodeManifest(e),kind:COMPILED_AGENT_MANIFEST_KIND,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:24}}function cloneCompiledRuntimeModelReference(e){return e.contextWindowTokens===void 0&&e.source===void 0&&e.providerOptions===void 0?{id:e.id}:e.source===void 0?e.providerOptions===void 0?{contextWindowTokens:e.contextWindowTokens,id:e.id}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:{...e.providerOptions}}:e.contextWindowTokens===void 0&&e.providerOptions===void 0?{id:e.id,source:{...e.source}}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:e.providerOptions===void 0?void 0:{...e.providerOptions},source:{...e.source}}}export{COMPILED_AGENT_MANIFEST_KIND,COMPILED_AGENT_MANIFEST_VERSION,ROOT_COMPILED_AGENT_NODE_ID,compiledAgentManifestSchema,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledSubagentNodeId,deriveResourceRootEntries};
|
|
@@ -12,7 +12,7 @@ export declare class MissingAgentConfigModuleError extends Error {
|
|
|
12
12
|
constructor(agentId: string);
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
|
-
* Compiles the agent-level configuration (model, compaction,
|
|
16
|
-
*
|
|
15
|
+
* Compiles the agent-level configuration (model, compaction, build,
|
|
16
|
+
* workspace) for one authored agent node.
|
|
17
17
|
*/
|
|
18
18
|
export declare function compileAgentConfig(manifest: AgentSourceManifest, context: ManifestCompileContext): Promise<CompiledAgentDefinition>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorMessage}from"#shared/errors.js";import{normalizeAgentDefinition}from"#internal/authored-definition/core.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{parseJsonObject}from"#shared/json.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";var MissingAgentConfigModuleError=class extends Error{agentId;constructor(e){super(`Agent "${e}" does not have an agent.ts config module. The "model" field is required.`),this.name=`MissingAgentConfigModuleError`,this.agentId=e}};async function compileAgentConfig(e,n){if(e.configModule===void 0)throw new MissingAgentConfigModuleError(e.agentId);let r=normalizeAgentDefinition(await loadModuleBackedDefinition({agentRoot:e.agentRoot,kind:`agent config`,source:e.configModule}),`Expected the agent config export "${e.configModule.exportName??`default`}" from "${e.configModule.logicalPath}" to match the public Ash shape.`),a=await normalizeAuthoredModelReference({modelCatalog:n.modelCatalog,purpose:`the primary compaction trigger model`,contextWindowTokens:r.modelContextWindowTokens,providerOptions:r.modelOptions?.providerOptions,source:e.configModule,value:r.model}),o={},s={compaction:o,
|
|
1
|
+
import{toErrorMessage}from"#shared/errors.js";import{normalizeAgentDefinition}from"#internal/authored-definition/core.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{parseJsonObject}from"#shared/json.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";var MissingAgentConfigModuleError=class extends Error{agentId;constructor(e){super(`Agent "${e}" does not have an agent.ts config module. The "model" field is required.`),this.name=`MissingAgentConfigModuleError`,this.agentId=e}};async function compileAgentConfig(e,n){if(e.configModule===void 0)throw new MissingAgentConfigModuleError(e.agentId);let r=normalizeAgentDefinition(await loadModuleBackedDefinition({agentRoot:e.agentRoot,kind:`agent config`,source:e.configModule}),`Expected the agent config export "${e.configModule.exportName??`default`}" from "${e.configModule.logicalPath}" to match the public Ash shape.`),a=await normalizeAuthoredModelReference({modelCatalog:n.modelCatalog,purpose:`the primary compaction trigger model`,contextWindowTokens:r.modelContextWindowTokens,providerOptions:r.modelOptions?.providerOptions,source:e.configModule,value:r.model}),o={},s={compaction:o,model:a,name:e.agentId};return r.description!==void 0&&(s.description=r.description),r.build!==void 0&&(s.build={externalDependencies:r.build.externalDependencies===void 0?void 0:[...r.build.externalDependencies]}),s.source={exportName:e.configModule.exportName,sourceKind:`module`,logicalPath:e.configModule.logicalPath,sourceId:e.configModule.sourceId},r.compaction?.model!==void 0&&(o.model=await normalizeAuthoredModelReference({modelCatalog:n.modelCatalog,purpose:`the compaction summary model`,contextWindowTokens:r.compaction.modelContextWindowTokens,providerOptions:r.modelOptions?.providerOptions,source:e.configModule,value:r.compaction.model})),r.compaction?.thresholdPercent!==void 0&&(o.thresholdPercent=r.compaction.thresholdPercent),s}async function normalizeAuthoredModelReference(e){if(typeof e.value==`string`)return await withCompiledRuntimeModelLimits({id:formatLanguageModelGatewayId(e.value),providerOptions:parseProviderOptionsRecord(e.providerOptions)},e);let t=e.source;if(t===void 0)throw Error(`Expected ${e.purpose} to provide a valid AI SDK language model reference.`);let r=e.value,i=r.specificationVersion;if(i!==`v2`&&i!==`v3`&&i!==`v4`||typeof r.provider!=`string`||typeof r.modelId!=`string`||typeof r.doGenerate!=`function`||typeof r.doStream!=`function`)throw Error(`Expected the authored agent config export "${t.exportName??`default`}" from "${t.logicalPath}" to provide a valid AI SDK language model.`);let a={id:formatLanguageModelGatewayId(r),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:parseProviderOptionsRecord(e.providerOptions)};if(e.contextWindowTokens===void 0){let t=await e.modelCatalog.getByProviderModelId(r.provider,r.modelId);if(t)return{...a,id:t.slug,contextWindowTokens:t.limits.contextWindowTokens}}return await withCompiledRuntimeModelLimits(a,e)}async function withCompiledRuntimeModelLimits(t,n){if(n.contextWindowTokens!==void 0)return{...t,contextWindowTokens:n.contextWindowTokens};let r;try{r=await n.modelCatalog.getModelLimits(t.id)}catch(r){throw Error(`Failed to load AI Gateway model metadata for ${n.purpose} "${t.id}". ${toErrorMessage(r)}`)}if(r===null)throw Error(`Cannot compile agent compaction because ${n.purpose} "${t.id}" does not have known AI Gateway context window metadata.`);return{...t,contextWindowTokens:r.contextWindowTokens}}function parseProviderOptionsRecord(e){if(e===void 0)return;let t={};for(let[n,i]of Object.entries(e))t[n]=parseJsonObject(i);return t}export{MissingAgentConfigModuleError,compileAgentConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stripLogicalPathExtension}from"#discover/filesystem.js";import{normalizeSkillDefinition}from"#internal/authored-definition/core.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function compileSkillSource(t,n){if(n.sourceKind===`skill-package`)return compileSkillPackageSource(n);let r=n.sourceKind===`markdown`?normalizeSkillDefinition(n.definition,`Expected the compiled skill definition at "${n.logicalPath}" to match the public Ash shape.`):normalizeSkillDefinition(await loadModuleBackedDefinition({agentRoot:t,kind:`skill`,source:n}),`Expected the skill export "${n.exportName??`default`}" from "${n.logicalPath}" to match the public Ash shape.`)
|
|
1
|
+
import{stripLogicalPathExtension}from"#discover/filesystem.js";import{normalizeSkillDefinition}from"#internal/authored-definition/core.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function compileSkillSource(t,n){if(n.sourceKind===`skill-package`)return compileSkillPackageSource(n);let r=n.sourceKind===`markdown`?normalizeSkillDefinition(n.definition,`Expected the compiled skill definition at "${n.logicalPath}" to match the public Ash shape.`):normalizeSkillDefinition(await loadModuleBackedDefinition({agentRoot:t,kind:`skill`,source:n}),`Expected the skill export "${n.exportName??`default`}" from "${n.logicalPath}" to match the public Ash shape.`);return{description:r.description,files:r.files,license:r.license,logicalPath:n.logicalPath,markdown:r.markdown,metadata:r.metadata===void 0?void 0:{...r.metadata},name:stripLogicalPathExtension(n.logicalPath).replace(/^skills\//,``),sourceId:n.sourceId,sourceKind:n.sourceKind}}function compileSkillPackageSource(e){return{assetsPath:e.assetsPath,description:e.description,license:e.license,logicalPath:e.logicalPath,markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name,referencesPath:e.referencesPath,rootPath:e.rootPath,scriptsPath:e.scriptsPath,skillId:e.skillId,skillFilePath:e.skillFilePath,sourceId:e.sourceId,sourceKind:`skill-package`}}export{compileSkillSource};
|
|
@@ -1,12 +1,23 @@
|
|
|
1
1
|
import type { HarnessSession, StepResult } from "#harness/types.js";
|
|
2
2
|
import { type ContextContainer } from "#context/container.js";
|
|
3
|
+
interface ContextScopeResult<T> {
|
|
4
|
+
readonly result: T;
|
|
5
|
+
readonly session: HarnessSession;
|
|
6
|
+
}
|
|
3
7
|
/**
|
|
4
|
-
* Runs
|
|
8
|
+
* Runs `callback` inside a fully-initialized ALS scope with all framework
|
|
9
|
+
* providers (session, connection, sandbox) built and committed.
|
|
5
10
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
|
|
10
|
-
|
|
11
|
+
* The callback receives the enriched session and must return both its own
|
|
12
|
+
* result and the (possibly mutated) session so provider commit hooks can
|
|
13
|
+
* persist provider-owned state (e.g. sandbox snapshots).
|
|
14
|
+
*/
|
|
15
|
+
export declare function withContextScope<T>(ctx: ContextContainer, harnessSession: HarnessSession, callback: (session: HarnessSession) => Promise<ContextScopeResult<T>>): Promise<ContextScopeResult<T>>;
|
|
16
|
+
/**
|
|
17
|
+
* Runs one harness step inside the unified context.
|
|
18
|
+
*
|
|
19
|
+
* Delegates to {@link withContextScope} for provider lifecycle, then
|
|
20
|
+
* reassembles the {@link StepResult}.
|
|
11
21
|
*/
|
|
12
22
|
export declare function runStep(ctx: ContextContainer, harnessSession: HarnessSession, callback: (session: HarnessSession) => Promise<StepResult>): Promise<StepResult>;
|
|
23
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage}from"#context/container.js";import{connectionProvider}from"#context/providers/connection.js";import{sandboxProvider}from"#context/providers/sandbox.js";import{sessionProvider}from"#context/providers/session.js";const frameworkProviders=[sessionProvider,connectionProvider,sandboxProvider];async function
|
|
1
|
+
import{contextStorage}from"#context/container.js";import{connectionProvider}from"#context/providers/connection.js";import{sandboxProvider}from"#context/providers/sandbox.js";import{sessionProvider}from"#context/providers/session.js";const frameworkProviders=[sessionProvider,connectionProvider,sandboxProvider];async function withContextScope(t,n,r){let a=n;t.clearVirtualContext();for(let e of frameworkProviders){let n=await e.create(t,a);n!==void 0&&(t.setVirtualContext(e.key,n.value),n.session!==void 0&&(a=n.session))}let o=await contextStorage.run(t,()=>r(a)),s=o.session;for(let e of frameworkProviders)e.commit&&t.has(e.key)&&(s=await e.commit(t.require(e.key),s));return s===o.session?o:{result:o.result,session:s}}async function runStep(e,t,n){let{result:r,session:i}=await withContextScope(e,t,async e=>{let t=await n(e);return{result:t.next,session:t.session}});return{next:r,session:i}}export{runStep,withContextScope};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename,relative,resolve}from"node:path";import{summarizeDiscoverDiagnostics}from"#discover/diagnostics.js";import{normalizeLogicalPath}from"#discover/filesystem.js";const AGENT_SOURCE_MANIFEST_KIND=`ash-agent-discovery-manifest`,AGENT_SOURCE_MANIFEST_VERSION=12;function createAgentSourceManifest(e){let t=resolve(e.appRoot),i=resolve(e.agentRoot),o={agentId:e.agentId??deriveAgentIdFromRoots(t,i,e.packageName),agentRoot:i,appRoot:t,channels:[...e.channels??[]],connections:[...e.connections??[]],diagnosticsSummary:summarizeDiscoverDiagnostics(e.diagnostics??[]),hooks:[...e.hooks??[]],lib:[...e.lib??[]],kind:AGENT_SOURCE_MANIFEST_KIND,sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],version:12,subagents:[...e.subagents??[]]};return e.configModule!==void 0&&(o.configModule=e.configModule),e.instructions!==void 0&&(o.instructions=e.instructions),o}function deriveAgentIdFromRoots(n,r,a){let o=normalizeLogicalPath(relative(n,r));return o===``||o===`.`||o===`agent`?a??basename(n):basename(r)}function createPathDerivedSourceId(e){return normalizeLogicalPath(e)}function createModuleSourceRef(e){let t=normalizeLogicalPath(e.logicalPath),n={sourceKind:`module`,logicalPath:t,sourceId:e.sourceId??createPathDerivedSourceId(t)};return e.exportName!==void 0&&(n.exportName=e.exportName),n}function createConnectionSourceRef(e){return{...createModuleSourceRef(e),connectionName:e.connectionName}}function createLocalSubagentSourceRef(e){let t=normalizeLogicalPath(e.logicalPath);return{entryPath:e.entryPath,logicalPath:t,manifest:e.manifest,rootPath:e.rootPath,sourceId:e.sourceId??createPathDerivedSourceId(t),subagentId:e.subagentId}}function createSkillPackageSourceRef(e){
|
|
1
|
+
import{basename,relative,resolve}from"node:path";import{summarizeDiscoverDiagnostics}from"#discover/diagnostics.js";import{normalizeLogicalPath}from"#discover/filesystem.js";const AGENT_SOURCE_MANIFEST_KIND=`ash-agent-discovery-manifest`,AGENT_SOURCE_MANIFEST_VERSION=12;function createAgentSourceManifest(e){let t=resolve(e.appRoot),i=resolve(e.agentRoot),o={agentId:e.agentId??deriveAgentIdFromRoots(t,i,e.packageName),agentRoot:i,appRoot:t,channels:[...e.channels??[]],connections:[...e.connections??[]],diagnosticsSummary:summarizeDiscoverDiagnostics(e.diagnostics??[]),hooks:[...e.hooks??[]],lib:[...e.lib??[]],kind:AGENT_SOURCE_MANIFEST_KIND,sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],version:12,subagents:[...e.subagents??[]]};return e.configModule!==void 0&&(o.configModule=e.configModule),e.instructions!==void 0&&(o.instructions=e.instructions),o}function deriveAgentIdFromRoots(n,r,a){let o=normalizeLogicalPath(relative(n,r));return o===``||o===`.`||o===`agent`?a??basename(n):basename(r)}function createPathDerivedSourceId(e){return normalizeLogicalPath(e)}function createModuleSourceRef(e){let t=normalizeLogicalPath(e.logicalPath),n={sourceKind:`module`,logicalPath:t,sourceId:e.sourceId??createPathDerivedSourceId(t)};return e.exportName!==void 0&&(n.exportName=e.exportName),n}function createConnectionSourceRef(e){return{...createModuleSourceRef(e),connectionName:e.connectionName}}function createLocalSubagentSourceRef(e){let t=normalizeLogicalPath(e.logicalPath);return{entryPath:e.entryPath,logicalPath:t,manifest:e.manifest,rootPath:e.rootPath,sourceId:e.sourceId??createPathDerivedSourceId(t),subagentId:e.subagentId}}function createSkillPackageSourceRef(e){return{assetsPath:e.assetsPath,description:e.description,license:e.license,logicalPath:normalizeLogicalPath(e.logicalPath),markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name,referencesPath:e.referencesPath,rootPath:e.rootPath,scriptsPath:e.scriptsPath,skillFilePath:e.skillFilePath,skillId:e.skillId,sourceId:e.sourceId,sourceKind:`skill-package`}}export{AGENT_SOURCE_MANIFEST_KIND,AGENT_SOURCE_MANIFEST_VERSION,createAgentSourceManifest,createConnectionSourceRef,createLocalSubagentSourceRef,createModuleSourceRef,createPathDerivedSourceId,createSkillPackageSourceRef,deriveAgentIdFromRoots};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getRuntimeCompiledArtifactsAppRoot}from"#runtime/compiled-artifacts-source.js";import{createRuntimeSandboxKeys}from"#runtime/sandbox/keys.js";async function ensureSandboxAccess(
|
|
1
|
+
import{buildCallbackContext}from"#context/build-callback-context.js";import{getRuntimeCompiledArtifactsAppRoot}from"#runtime/compiled-artifacts-source.js";import{createRuntimeSandboxKeys}from"#runtime/sandbox/keys.js";async function ensureSandboxAccess(n){let r=n.state?.initialized??!1,i=n.state?.session??null,a=getRuntimeCompiledArtifactsAppRoot(n.compiledArtifactsSource)??process.cwd(),o=n.registry.sandbox,s;function getHandle(){return s===void 0&&(s=createHandle().catch(e=>{throw s=void 0,e})),s}async function createHandle(){if(o===null)return null;let t=o.definition,s=t.backend,c=await createRuntimeSandboxKeys({backendName:s.name,compiledArtifactsSource:n.compiledArtifactsSource,nodeId:n.nodeId,sessionId:n.sessionId,sourceId:t.sourceId}),l=await s.create({existingMetadata:i?.backendName===s.name&&i.sessionKey===c.sessionKey?i.metadata:void 0,runtimeContext:{appRoot:a},sessionKey:c.sessionKey,tags:n.tags,templateKey:c.templateKey});return r||=(await runOnSession(async()=>{await t.onSession?.({ctx:buildCallbackContext(),use:l.useSessionFn})}),!0),l}async function runOnSession(e){if(n.runOnSession!==void 0){await n.runOnSession(e);return}await e()}return{async captureState(){if(s!==void 0){let e=await s;e!==null&&(i=await e.captureState())}return{initialized:r,session:i}},async dispose(){s!==void 0&&await(await s)?.dispose()},async get(){return(await getHandle())?.session??null}}}export{ensureSandboxAccess};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ASH_SESSION_STREAM_NAMESPACE}from"#execution/durable-session-store.js";import{accumulateRuntimeActionResults}from"#harness/runtime-actions.js";import{resolveVercelProductionCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{normalizeSerializableError,rebuildSerializableError}from"#execution/workflow-errors.js";import{dispatchTurnStep,emitTerminalSessionFailureStep,routeProxiedDeliverStep,runProxyInputRequestStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{coalesceDeliveries}from"#harness/messages.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{createSessionStep}from"#execution/create-session-step.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";async function workflowEntry(t){"use workflow";let{workflowRunId:n}=getWorkflowMetadata(),i=t.serializedContext[`ash.continuationToken`]||``,a=t.serializedContext[`ash.mode`],s=t.serializedContext[`ash.capabilities`],c=t.serializedContext[`ash.bundle`];t.serializedContext[`ash.sessionId`]=n;let l=getWritable(),d=getWritable({namespace:ASH_SESSION_STREAM_NAMESPACE});try{let e=await createSessionStep({compiledArtifactsSource:c.source,continuationToken:i,nodeId:c.nodeId,sessionId:n,sessionWritable:d});return await runDriverLoop({capabilities:s,driverWritable:l,initialInput:{kind:`deliver`,payloads:[{message:t.input.message,modelContext:t.input.modelContext}]},mode:a,serializedContext:t.serializedContext,sessionState:e,sessionWritable:d})}catch(e){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(e),parentWritable:l,serializedContext:t.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(e),serializedContext:t.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(t.serializedContext,e),serializedContext:t.serializedContext}),e}}async function runDriverLoop(e){let t=createHook({token:`${e.sessionState.sessionId}:auth`}),r=t[Symbol.asyncIterator](),i=await dispatchAndAwaitTurn({capabilities:e.capabilities,delivery:e.initialInput,mode:e.mode,parentWritable:e.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState,sessionWritable:e.sessionWritable});if(
|
|
1
|
+
import{ASH_SESSION_STREAM_NAMESPACE}from"#execution/durable-session-store.js";import{accumulateRuntimeActionResults}from"#harness/runtime-actions.js";import{resolveVercelProductionCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{normalizeSerializableError,rebuildSerializableError}from"#execution/workflow-errors.js";import{dispatchTurnStep,emitTerminalSessionFailureStep,routeProxiedDeliverStep,runProxyInputRequestStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{coalesceDeliveries}from"#harness/messages.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{createSessionStep}from"#execution/create-session-step.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";async function workflowEntry(t){"use workflow";let{workflowRunId:n}=getWorkflowMetadata(),i=t.serializedContext[`ash.continuationToken`]||``,a=t.serializedContext[`ash.mode`],s=t.serializedContext[`ash.capabilities`],c=t.serializedContext[`ash.bundle`];t.serializedContext[`ash.sessionId`]=n;let l=getWritable(),d=getWritable({namespace:ASH_SESSION_STREAM_NAMESPACE});try{let e=await createSessionStep({compiledArtifactsSource:c.source,continuationToken:i,nodeId:c.nodeId,sessionId:n,sessionWritable:d});return await runDriverLoop({capabilities:s,driverWritable:l,initialInput:{kind:`deliver`,payloads:[{message:t.input.message,modelContext:t.input.modelContext}]},mode:a,serializedContext:t.serializedContext,sessionState:e,sessionWritable:d})}catch(e){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(e),parentWritable:l,serializedContext:t.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(e),serializedContext:t.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(t.serializedContext,e),serializedContext:t.serializedContext}),e}}async function runDriverLoop(e){let t=createHook({token:`${e.sessionState.sessionId}:auth`}),r=t[Symbol.asyncIterator](),i=e.sessionState.continuationToken,a=createHook({token:i}),o=a[Symbol.asyncIterator](),s=null,c=[],getNextPromise=()=>(s??=o.next(),s),consumeNext=()=>{s=null},rekeyHook=async e=>{e===i||!e||(await closeHookIterator(o),await disposeHook(a),i=e,a=createHook({token:i}),o=a[Symbol.asyncIterator](),s=null)},u=await dispatchAndAwaitTurn({capabilities:e.capabilities,delivery:e.initialInput,mode:e.mode,parentWritable:e.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState,sessionWritable:e.sessionWritable});if(u.kind===`done`)return await closeHookIterator(r),await disposeHook(t),await closeHookIterator(o),await disposeHook(a),await finalizeDone({action:u,driverWritable:e.driverWritable});if(!u.sessionState.continuationToken)throw Error("Cannot park: no continuation token available. The channel must post the first message during the initial turn (anchoring the session) or `send()` must be called with an explicit continuationToken.");await rekeyHook(u.sessionState.continuationToken);try{for(;;)switch(u.kind){case`done`:return await finalizeDone({action:u,driverWritable:e.driverWritable});case`dispatch-runtime-actions`:{let t=await dispatchRuntimeActionsStep({callbackBaseUrl:resolveVercelProductionCallbackBaseUrl()??getWorkflowMetadata().url,parentWritable:e.driverWritable,serializedContext:u.serializedContext,sessionState:u.sessionState,sessionWritable:e.sessionWritable}),r=await waitForPendingRuntimeActionResults({bufferedDeliveries:c,consumeNext,getNextPromise,initialResults:t.results,parentWritable:e.driverWritable,pendingActionKeys:u.pendingActionKeys,rekeyHook,serializedContext:u.serializedContext,sessionState:t.sessionState,sessionWritable:e.sessionWritable});if(r===null)return{output:``};u=await dispatchAndAwaitTurn({capabilities:e.capabilities,delivery:{kind:`runtime-action-result`,results:r.results},mode:e.mode,parentWritable:e.driverWritable,serializedContext:r.serializedContext,sessionState:r.sessionState,sessionWritable:e.sessionWritable}),await rekeyHook(u.sessionState.continuationToken);break}case`park`:{if(u.authorizationNames&&u.authorizationNames.length>0){let t=u.authorizationNames.length,n=[];for(;n.length<t;){let e=await r.next();if(e.done)break;e.value.kind===`deliver`&&n.push(...e.value.payloads)}u=await dispatchAndAwaitTurn({capabilities:e.capabilities,delivery:{kind:`deliver`,payloads:n},mode:e.mode,parentWritable:e.driverWritable,serializedContext:u.serializedContext,sessionState:u.sessionState,sessionWritable:e.sessionWritable}),await rekeyHook(u.sessionState.continuationToken);break}let t=await waitForNextDeliver({bufferedDeliveries:c,consumeNext,getNextPromise});if(t===null)return{output:``};let n=await routeDeliverForChildren({auth:t.auth,parentWritable:e.driverWritable,payloads:t.payloads,sessionState:u.sessionState});if(n===void 0)continue;u=await dispatchAndAwaitTurn({capabilities:e.capabilities,delivery:{auth:t.auth,kind:`deliver`,payloads:[n]},mode:e.mode,parentWritable:e.driverWritable,serializedContext:u.serializedContext,sessionState:u.sessionState,sessionWritable:e.sessionWritable}),await rekeyHook(u.sessionState.continuationToken);break}}}finally{await closeHookIterator(o),await disposeHook(a),await closeHookIterator(r),await disposeHook(t)}}async function finalizeDone(e){return await fireSessionCallbackStep({output:e.action.output,serializedContext:e.action.serializedContext,status:`completed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentSuccessResult(e.action.serializedContext,e.action.output),serializedContext:e.action.serializedContext}),{output:e.action.output}}async function dispatchAndAwaitTurn(e){let t=createHook(),n=t.token;try{await dispatchTurnStep({capabilities:e.capabilities,completionToken:n,delivery:e.delivery,mode:e.mode,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:e.sessionState,sessionWritable:e.sessionWritable});let r=await awaitHookPayload(t);if(r.kind===`turn-error`)throw rebuildSerializableError(r.error);return r.action}finally{await disposeHook(t)}}async function awaitHookPayload(e){for await(let t of e)return t;throw Error(`Turn completion hook closed before delivering a result.`)}async function waitForPendingRuntimeActionResults(e){let n=e.sessionState,r=e.serializedContext,i=await accumulateRuntimeActionResults({bufferedDeliveries:e.bufferedDeliveries,async getNext(){for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;let i=t.value;if(i.kind===`deliver`){let t=await routeDeliverForChildren({auth:i.auth,parentWritable:e.parentWritable,payloads:i.payloads,sessionState:n});if(t===void 0)continue;return{kind:`deliver`,value:{...i,payloads:[t]}}}if(i.kind===`runtime-action-result`)return{kind:`runtime-action-result`,results:i.results};let a=await runProxyInputRequestStep({hookPayload:i,parentWritable:e.parentWritable,serializedContext:r,sessionState:n,sessionWritable:e.sessionWritable});n=a.sessionState,r=a.serializedContext,await e.rekeyHook(n.continuationToken)}},initialResults:e.initialResults,pendingActionKeys:e.pendingActionKeys});return i===null?null:{results:i,serializedContext:r,sessionState:n}}async function routeDeliverForChildren(e){let t=coalescePayloads(e.payloads);return e.sessionState.hasProxyInputRequests?(await routeProxiedDeliverStep({auth:e.auth,parentWritable:e.parentWritable,payload:t,sessionState:e.sessionState})).remainder:t}async function waitForNextDeliver(e){if(e.bufferedDeliveries.length>0)return coalesceDeliveries(e.bufferedDeliveries.splice(0));for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;if(t.value.kind!==`deliver`)continue;let n=t.value;for(;;){let t=await takeReadyPayload(e.getNextPromise());if(t===NO_READY_MESSAGE||(e.consumeNext(),t.done))break;t.value.kind===`deliver`&&(n=coalesceDeliveries([n,t.value]))}return n}}function coalescePayloads(e){if(e.length===0)return{};if(e.length===1)return e[0]??{};let t={},n=[];for(let r of e){for(let[e,n]of Object.entries(r))e!==`inputResponses`&&n!==void 0&&(t[e]=n);r.inputResponses!==void 0&&n.push(...r.inputResponses)}return n.length>0&&(t.inputResponses=n),t}const NO_READY_MESSAGE=Symbol(`no-ready-message`);async function takeReadyPayload(e){return await Promise.resolve(),await Promise.race([e,Promise.resolve(NO_READY_MESSAGE)])}async function closeHookIterator(e){typeof e.return==`function`&&await e.return(void 0)}async function disposeHook(e){let t=e.dispose;if(typeof t==`function`){await t.call(e);return}let n=e[Symbol.dispose];typeof n==`function`&&await n.call(e)}export{workflowEntry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,formatError}from"#internal/logging.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{getHarnessEmissionState,isHarnessBetweenTurns}from"#harness/emission.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{readDurableSession,writeDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceTurnInputs}from"#harness/messages.js";import{dispatchStreamEventHooks,runHookLifecycleStep}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,getPendingAuthorization}from"#harness/authorization.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";let t=await readDurableSession(e.sessionState),i=await deserializeContext(e.serializedContext),s=i.require(ChannelKey),d=i.require(BundleKey),f=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:d.turnAgent});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&i.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let p=getPendingAuthorization(t.state),m;if(p&&e.input?.kind===`deliver`){let t=[],n=[];for(let r of e.input.payloads){let e=r.authorizationCallback;if(e){let n=p.challenges.find(t=>t.name===e.connectionName);n&&t.push({name:n.name,state:n.state,callback:e.request,hookUrl:n.hookUrl})}else n.push(r)}t.length>0&&(i.set(PendingAuthorizationResultKey,t),m=t.map(e=>e.name),e=n.length>0?{...e,input:{...e.input,payloads:n}}:{...e,input:void 0})}e.input?.kind===`deliver`&&e.input.auth!==void 0&&i.set(AuthKey,e.input.auth??null);let h=buildAdapterContext(s,i),g;if(e.input?.kind===`deliver`){let t=[];for(let n of e.input.payloads){let e=s.deliver?await s.deliver(n,h):defaultDeliverResult(n);e!=null&&t.push(e)}g=t.length===0?void 0:t.reduce(coalesceTurnInputs)}else e.input?.kind===`runtime-action-result`&&(g={runtimeActionResults:e.input.results});if(e.input?.kind===`deliver`){let e={...s,state:{...h.state}};i.set(ChannelKey,e)}if(e.input?.kind===`deliver`&&g===void 0){let t=reconcileSessionContinuationToken(i,f),n=serializeContext(i),r=t===f?e.sessionState:await writeDurableSession({session:t,writable:e.sessionWritable});return{action:`park`,...derivePendingState(t),serializedContext:n,sessionState:r}}let _=e.parentWritable.getWriter(),v=i.require(BundleKey).hookRegistry,emit=async e=>{let t=await callAdapterEventHandler(s,e,h);i.set(ChannelKey,{...s,state:{...h.state}}),await _.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),await dispatchStreamEventHooks({ctx:i,registry:v,event:t})}
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{getHarnessEmissionState,isHarnessBetweenTurns}from"#harness/emission.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{readDurableSession,writeDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceTurnInputs}from"#harness/messages.js";import{dispatchStreamEventHooks,runHookLifecycleStep}from"#context/hook-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,getPendingAuthorization}from"#harness/authorization.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";let t=await readDurableSession(e.sessionState),i=await deserializeContext(e.serializedContext),s=i.require(ChannelKey),d=i.require(BundleKey),f=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:d.turnAgent});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&i.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let p=getPendingAuthorization(t.state),m;if(p&&e.input?.kind===`deliver`){let t=[],n=[];for(let r of e.input.payloads){let e=r.authorizationCallback;if(e){let n=p.challenges.find(t=>t.name===e.connectionName);n&&t.push({name:n.name,state:n.state,callback:e.request,hookUrl:n.hookUrl})}else n.push(r)}t.length>0&&(i.set(PendingAuthorizationResultKey,t),m=t.map(e=>e.name),e=n.length>0?{...e,input:{...e.input,payloads:n}}:{...e,input:void 0})}e.input?.kind===`deliver`&&e.input.auth!==void 0&&i.set(AuthKey,e.input.auth??null);let h=buildAdapterContext(s,i),g;if(e.input?.kind===`deliver`){let t=[];for(let n of e.input.payloads){let e=s.deliver?await s.deliver(n,h):defaultDeliverResult(n);e!=null&&t.push(e)}g=t.length===0?void 0:t.reduce(coalesceTurnInputs)}else e.input?.kind===`runtime-action-result`&&(g={runtimeActionResults:e.input.results});if(e.input?.kind===`deliver`){let e={...s,state:{...h.state}};i.set(ChannelKey,e)}if(e.input?.kind===`deliver`&&g===void 0){let t=reconcileSessionContinuationToken(i,f),n=serializeContext(i),r=t===f?e.sessionState:await writeDurableSession({session:t,writable:e.sessionWritable});return{action:`park`,...derivePendingState(t),serializedContext:n,sessionState:r}}let _=e.parentWritable.getWriter(),v=i.require(BundleKey).hookRegistry,emit=async e=>{let t=await callAdapterEventHandler(s,e,h);i.set(ChannelKey,{...s,state:{...h.state}}),await _.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),await dispatchStreamEventHooks({ctx:i,registry:v,event:t})},y=await runStep(i,f,async e=>{if(m){let t=getHarnessEmissionState(e.state);for(let e of m)await emit(createAuthorizationCompletedEvent({name:e,outcome:`authorized`,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}))}let t=i.require(BundleKey),n=i.get(CapabilitiesKey),s=i.require(ModeKey),runHarnessStep=async(e,r)=>{let i=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:t.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:t.turnAgent});return createExecutionNodeStep({capabilities:n,compiledArtifactsSource:t.compiledArtifactsSource,createRuntime:createWorkflowRuntime,emit,mode:s,node:t.graph.root})(i,r)};return g!==void 0&&isHarnessBetweenTurns(e)?runHookLifecycleStep({ctx:i,emit,input:g,mode:s,registry:t.hookRegistry,session:e},runHarnessStep):runHarnessStep(e,g)}),b=reconcileSessionContinuationToken(i,y.session),x=serializeContext(i);y={...y,session:b};let S=await writeDurableSession({session:y.session,writable:e.sessionWritable});return y.next!==null&&typeof y.next==`object`&&`done`in y.next?(await _.close(),{action:`done`,output:y.next.output,serializedContext:x,sessionState:S}):y.next===null?(_.releaseLock(),{action:`park`,...derivePendingState(y.session),serializedContext:x,sessionState:S}):(_.releaseLock(),{action:`continue`,serializedContext:x,sessionState:S})}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let n=formatError(e.error),r=typeof n.name==`string`?n.name:`WORKFLOW_EXECUTION_FAILED`,i=typeof n.message==`string`?n.message:String(e.error),a=e.serializedContext[`ash.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:a,errorId:typeof n.errorId==`string`?n.errorId:void 0,code:r,message:i,detail:typeof n.detail==`string`?n.detail:void 0});let o=createSessionFailedEvent({code:r,details:n,message:i,sessionId:a});try{let t=await deserializeContext(e.serializedContext),n=t.get(ChannelKey);n!==void 0&&await callAdapterEventHandler(n,o,buildAdapterContext(n,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof n.errorId==`string`?n.errorId:void 0,sessionId:a,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(o)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof n.errorId==`string`?n.errorId:void 0,sessionId:a,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),n=await deserializeContext(e.serializedContext),r=n.require(ChannelKey),i=buildAdapterContext(r,n),o=n.require(ModeKey),s=n.require(BundleKey),c=hydrateDurableSession({compactionOverrides:{thresholdPercent:s.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:s.turnAgent}),l=e.parentWritable.getWriter(),u;try{let emit=async e=>{let t=await callAdapterEventHandler(r,e,i);await l.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};u=await withContextScope(n,c,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{l.releaseLock()}return n.set(ChannelKey,{...r,state:{...i.state}}),{serializedContext:serializeContext(n),sessionState:await writeDurableSession({session:reconcileSessionContinuationToken(n,upsertProxyInputRequests({entries:u.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:u.session})),writable:e.sessionWritable})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state}),{resumeHook:r}=await import(`#compiled/@workflow/core/runtime.js`);for(let t of n.forChildren)await r(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[e])).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
|