@trayai/helix-sdk 1.6.1 → 1.8.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 CHANGED
@@ -8,6 +8,22 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
8
  The SDK and [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) are
9
9
  released together and share a version — install matching versions.
10
10
 
11
+ ## 1.8.0
12
+
13
+ ### Added
14
+
15
+ - **Amazon Bedrock support in `ctx.ai` and agents.** `aiProviders` accepts a new `bedrock`
16
+ service in the object form — `{ service: 'bedrock', region: 'us-east-1' }` (or `baseUrl`
17
+ for a VPC / custom endpoint) — mapped to an **Amazon Bedrock** authentication in your
18
+ workspace. Use Bedrock model ids (`anthropic.claude-sonnet-4-5-20250929-v1:0`,
19
+ `us.anthropic.…`, `amazon.nova-…`) with `ctx.ai(alias)` and as an agent's `model`/`auth`
20
+ pair. A `bedrock` entry with neither `region` nor `baseUrl` is rejected when your config
21
+ loads.
22
+
23
+ ## 1.7.0
24
+
25
+ No user-visible changes in this release — co-versioned with `@trayai/helix-cli`'s changes.
26
+
11
27
  ## 1.6.0
12
28
 
13
29
  ### Changed
package/README.md CHANGED
@@ -325,7 +325,8 @@ export default defineConfig({
325
325
  anthropicKey: '<your-anthropic-auth-uuid>',
326
326
  },
327
327
  aiProviders: {
328
- // 'openai' | 'anthropic' | 'google' | 'mistral' | 'cohere', or the object form
328
+ // 'openai' | 'anthropic' | 'google' | 'mistral' | 'cohere', or the object forms
329
+ // { service: 'bedrock', region } for Amazon Bedrock and
329
330
  // { service: 'openai-compatible', baseUrl } for self-hosted endpoints
330
331
  anthropicKey: 'anthropic',
331
332
  },
@@ -365,10 +366,16 @@ export default defineFunction(async (ctx) => {
365
366
  per image and report no token usage at all, so `generateImage`'s cost estimates to `0` for
366
367
  them regardless of whether the model is recognized; token-billed image models (e.g.
367
368
  `gpt-image-1`) get a real estimate.
368
- - Supported services: `openai`, `anthropic`, `google`, `mistral`, `cohere`, and
369
- `openai-compatible` (self-hosted endpoints — use the object form with `baseUrl` instead of
370
- the shorthand string). `baseUrl` must be `https:` — this is enforced when your config loads,
371
- not just on the first call.
369
+ - Supported services: `openai`, `anthropic`, `google`, `mistral`, `cohere`, `bedrock`
370
+ (Amazon Bedrock — use the object form with the AWS `region` your models are enabled in,
371
+ e.g. `{ service: 'bedrock', region: 'us-east-1' }`, and Bedrock model ids such as
372
+ `anthropic.claude-sonnet-4-5-20250929-v1:0` or `us.anthropic.…`; pass `baseUrl` instead of
373
+ `region` for a VPC or other custom endpoint), and `openai-compatible` (self-hosted
374
+ endpoints — use the object form with `baseUrl` instead of the shorthand string). `baseUrl`
375
+ must be `https:` — this is enforced when your config loads, not just on the first call.
376
+ - A `bedrock` alias points at an **Amazon Bedrock** authentication (AWS access key and secret)
377
+ in your workspace; `ctx.ai` never handles the AWS keys and signs nothing itself. The AI
378
+ SDK's own `providerOptions.bedrock` passthrough works as usual.
372
379
  - An alias with no matching `aiProviders` entry throws `SdkError.aiProviderNotConfigured`,
373
380
  naming the exact config line to add.
374
381
  - The top-level `ctx.ai.*` functions only accept a model instance obtained from `ctx.ai(alias)`
@@ -1 +1 @@
1
- import{A as u,B as d,D as p,F as m,G as c,H as k,I as g,J as b,j as l}from"../chunk-3T2WZMJJ.js";import{z as s}from"zod";function v(e,t){let r=`${l(e).hosts.api}/private/v1/helix/authentications/templates`;return t==="dev"?`${r}/dev`:r}var h=s.object({templates:s.array(s.object({serviceName:s.string(),serviceVersion:s.number().int(),authenticationType:s.string(),strategy:s.string().optional()}))}),S=3e4;async function y(e){let t=new Headers;for(let[n,T]of Object.entries(e.credentialHeaders))t.set(n,T);let r=await fetch(e.templatesUrl,{method:"GET",headers:t,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??S)}),a=await r.text(),o=a;try{o=JSON.parse(a)}catch{}if(r.ok){let n=h.safeParse(o);return n.success?{kind:"templates",result:n.data}:{kind:"brokerError",status:r.status,message:"malformed templates-discovery response",body:o}}let i=u.safeParse(o);return i.success?{kind:"brokerError",status:r.status,code:i.data.error.code,message:i.data.error.message,body:o}:{kind:"brokerError",status:r.status,message:a||`templates-discovery request failed with status ${r.status}`,body:o}}async function R(e){let t=p({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),r=await c({proxyUrl:d(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},request:t,timeoutMs:e.timeoutMs??m});return r.kind==="brokerError"?{kind:"brokerError",brokerStatus:r.status,code:r.code,body:r.body}:{kind:"upstream",upstream:r.response}}async function f(e){k(e.url);let t=await b({signUrl:g(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},body:{authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},timeoutMs:e.timeoutMs});return t.kind==="brokerError"?{kind:"brokerError",brokerStatus:t.status,code:t.code,body:t.body}:{kind:"signed",signed:t.result}}async function x(e){let t=await y({templatesUrl:v(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},timeoutMs:e.timeoutMs});return t.kind==="brokerError"?{kind:"brokerError",brokerStatus:t.status,code:t.code,body:t.body}:{kind:"templates",templates:t.result.templates}}export{R as callBrokerDev,f as callS3SignDev,x as callTemplatesDev};
1
+ import{A as u,B as d,D as p,F as m,G as c,H as k,I as g,J as b,j as l}from"../chunk-JKFMPHA4.js";import{z as s}from"zod";function v(e,t){let r=`${l(e).hosts.api}/private/v1/helix/authentications/templates`;return t==="dev"?`${r}/dev`:r}var h=s.object({templates:s.array(s.object({serviceName:s.string(),serviceVersion:s.number().int(),authenticationType:s.string(),strategy:s.string().optional()}))}),S=3e4;async function y(e){let t=new Headers;for(let[n,T]of Object.entries(e.credentialHeaders))t.set(n,T);let r=await fetch(e.templatesUrl,{method:"GET",headers:t,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??S)}),a=await r.text(),o=a;try{o=JSON.parse(a)}catch{}if(r.ok){let n=h.safeParse(o);return n.success?{kind:"templates",result:n.data}:{kind:"brokerError",status:r.status,message:"malformed templates-discovery response",body:o}}let i=u.safeParse(o);return i.success?{kind:"brokerError",status:r.status,code:i.data.error.code,message:i.data.error.message,body:o}:{kind:"brokerError",status:r.status,message:a||`templates-discovery request failed with status ${r.status}`,body:o}}async function R(e){let t=p({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),r=await c({proxyUrl:d(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},request:t,timeoutMs:e.timeoutMs??m});return r.kind==="brokerError"?{kind:"brokerError",brokerStatus:r.status,code:r.code,body:r.body}:{kind:"upstream",upstream:r.response}}async function f(e){k(e.url);let t=await b({signUrl:g(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},body:{authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},timeoutMs:e.timeoutMs});return t.kind==="brokerError"?{kind:"brokerError",brokerStatus:t.status,code:t.code,body:t.body}:{kind:"signed",signed:t.result}}async function x(e){let t=await y({templatesUrl:v(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},timeoutMs:e.timeoutMs});return t.kind==="brokerError"?{kind:"brokerError",brokerStatus:t.status,code:t.code,body:t.body}:{kind:"templates",templates:t.result.templates}}export{R as callBrokerDev,f as callS3SignDev,x as callTemplatesDev};
@@ -0,0 +1,7 @@
1
+ import{a as mn,b as Ve}from"./chunk-WUCX7RZO.js";import{A as yn,B as fe,C as z,D as ne,E as hn,G as wn,H as Sn,I as bn,J as vn,a as U,b as de,d as E,e as ue,f as $,h as un,j,k as pn,o as fn,r as d,t as Ie,u as ze,v as te,w as Re,x as Ge,y as pe,z as gn}from"./chunk-JKFMPHA4.js";var sc="tray-config-bridge",ic="tray-dev-token-bridge",Je=null;function ac(e){Je=e}function A(){if(!Je)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return Je}function cc(){Je=null}import{AsyncLocalStorage as Bn}from"async_hooks";import{trace as cs,SpanKind as ls,SpanStatusCode as Ze}from"@opentelemetry/api";import{ExportResultCode as ds,W3CTraceContextPropagator as us}from"@opentelemetry/core";import{NodeTracerProvider as ps,SimpleSpanProcessor as fs,BatchSpanProcessor as ms}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Jo}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Wo}from"@opentelemetry/exporter-logs-otlp-proto";function Ct(e){return j(e).hosts.ingest}function Xo(){return $()??""}function xn(){return{[U]:Xo()}}function An(){let e=Ct(A().region);return new Jo({url:`${e}/v1/traces`,headers:()=>Promise.resolve(xn())})}function En(){let e=Ct(A().region);return new Wo({url:`${e}/v1/logs`,headers:()=>Promise.resolve(xn())})}import{logs as Cn,SeverityNumber as We}from"@opentelemetry/api-logs";import{LoggerProvider as Zo,BatchLogRecordProcessor as es}from"@opentelemetry/sdk-logs";function Ce(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Yo(e){return new TextEncoder().encode(e).length}var In="\u2026[truncated]",Qo=Yo(In),Te=4096;function re(e,t=Te){let n=new TextEncoder().encode(e);if(n.length<=t)return e;let r=n.subarray(0,t-Qo);return new TextDecoder("utf-8").decode(r).replace(/�$/,"")+In}function k(e,t=Te){return re(Ce(e),t)}var ts="@trayai/helix-sdk",ke,Rn={debug:{number:We.DEBUG,text:"DEBUG"},info:{number:We.INFO,text:"INFO"},warn:{number:We.WARN,text:"WARN"},error:{number:We.ERROR,text:"ERROR"}};function ns(){return E().mode==="lambda"?[new es({exporter:En()})]:[]}function Tn(){if(ke!==void 0)return;let e=ns();e.length!==0&&(ke=new Zo({processors:e}),Cn.setGlobalLoggerProvider(ke))}function rs(e,t,n){let r=Rn[e]??Rn.info;return{severityNumber:r.number,severityText:r.text,body:t,...n?{attributes:{"tray.log.meta":k(n)}}:{}}}function kn(e,t,n){Cn.getLogger(ts).emit(rs(e,t,n))}async function Pn(e=2e3){if(ke===void 0)return;let t;try{await Promise.race([ke.forceFlush(),new Promise(n=>{t=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel log flush failed: ${n instanceof Error?n.message:String(n)}
2
+ `)}finally{t!==void 0&&clearTimeout(t)}}function Tt(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function os(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function D(e,t){return os()?`\x1B[${e}m${t}\x1B[0m`:t}var ss=5,is={FN:"1;35",INFO:"34",AUTH:"35",API:"36",AGENT:"1;36",TOOL:"36",WARN:"33",ERROR:"31",DEBUG:"90"},Xe="32",Ye="31",as="33",oe="2",Qe="1";function se(e){return D(is[e]??"0",e.padEnd(ss))}function On(e,t){return`${se("FN")} ${D(Qe,`${e} ${t}`.trim())}`}function _n(e,t,n,r){let o=e.toUpperCase(),i=`${r?`${D(oe,r)} `:""}${se(o)} ${t}`;return n&&Object.keys(n).length>0&&(i+=` ${D(oe,Ce(n))}`),i}function Dn(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Mn(e){return`${se("AUTH")} ${e}`}function Fn(e,t,n,r,o){let s=n===void 0?"ERR":String(n),i=D(o==="error"?Ye:Xe,s);return`${se("API")} ${e} ${t} \u2192 ${i} ${D(oe,`${r}ms`)}`}function Ln(e){return`${se("AGENT")} ${D(Qe,e)}`}function Nn(e,t,n,r){let o=t==="error"?Ye:t==="awaiting-approval"?as:Xe,s=n!==void 0?`${D(oe,`${n} step${n===1?"":"s"}`)} `:"";return`${se("AGENT")} ${D(Qe,e)} \u2192 ${D(o,t)} ${s}${D(oe,`${r}ms`)}`}function Un(e,t,n){let r=t==="error"?D(Ye,"error"):D(Xe,"ok");return`${se("TOOL")} ${e} \u2192 ${r} ${D(oe,`${n}ms`)}`}function $n(e,t,n){let r=t?Ye:Xe,o=D(r,"\u25CF"),s=D(r,t?"error":"success");return`${o} ${D(Qe,e)} ${s} ${D(oe,`${n}ms`)}`}function H(e){try{process.stdout.write(e+`
3
+ `)}catch{}}var Kn=new Bn,gs=new Bn;function O(e){let t=gs.getStore();t&&(t[e]=!0)}var ys=/^[0-9a-f]{32}$/;function hs(e){let t=e.replace(/-/g,"").toLowerCase();return ys.test(t)?t:null}var ws={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},me=new Map;function Hn(e,t,n){let r=me.get(e);r?r[t]=n:me.set(e,{[t]:n})}function q(e,t,n){e.setAttribute(t,k(n))}var Pe;function jn(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function kt(e){return Math.round(e[0]*1e3+e[1]/1e6)}function qn(e){try{process.stdout.write(Ce(e)+`
4
+ `)}catch{}}var Pt=class{export(t,n){for(let r of t){let o=r.spanContext().spanId,s=me.get(o),i={...r.attributes};if(s!==void 0){for(let[l,u]of Object.entries(s))typeof u=="string"?i[l]=re(u):typeof u=="object"&&u!==null?i[l]=k(u):i[l]=u;me.delete(o)}let a=Kn.getStore(),c=a?hs(a):null;qn({_otel:"span",traceId:c??r.spanContext().traceId,spanId:o,parentSpanId:r.parentSpanContext?.spanId??"",name:r.name,kind:r.kind,startTimeUnixNano:jn(r.startTime),endTimeUnixNano:jn(r.endTime),attributes:i,status:{code:ws[r.status.code]??"STATUS_CODE_UNSET",...r.status.message?{message:re(r.status.message)}:{}}})}n({code:ds.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ot=class{onStart(t,n){}onEnd(t){me.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},_t=class{onStart(t){let n=t;(n.name==="function"||n.name==="App")&&H(`
5
+ `+On(String(n.attributes.method??""),String(n.attributes.route??""))),(n.name==="agent.generate"||n.name==="agent.stream")&&H(Ln(String(n.attributes.agent??"")))}onEnd(t){let n=t.attributes;switch(t.name){case"log":{let r=t.spanContext().spanId,o=me.get(r)?.properties;H(_n(String(n.level??"info"),String(n.message??""),o,Dn(t.startTime)));break}case"auth":H(Mn(String(n.alias??"")));break;case"externalApi":{let r=typeof n.statusCode=="number"?n.statusCode:void 0;H(Fn(String(n.method??""),String(n.host??""),r,kt(t.duration),n.status==="error"?"error":"success"));break}case"agent.tool":{H(Un(String(n.tool??""),n.status==="error"?"error":"success",kt(t.duration)));break}case"agent.generate":case"agent.stream":{let r=typeof n.status=="string"?n.status:t.status.code===Ze.ERROR?"error":"completed";H(Nn(String(n.agent??""),r,typeof n.steps=="number"?n.steps:void 0,kt(t.duration)));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Dt=class{constructor(t){this.inner=t}inner;onStart(t,n){this.inner.onStart(t,n)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function Ss(){let t=[Tt()?new _t:new fs(new Pt)];return E().mode==="lambda"&&t.push(new Dt(new ms(An()))),t.push(new Ot),t}function bs(){Pe===void 0&&(Pe=new ps({spanProcessors:Ss()}),Pe.register({propagator:new us}),Tn())}async function vs(e=2e3){let t=[Pn(e)];Pe!==void 0&&t.push((async()=>{let n;try{await Promise.race([Pe.forceFlush(),new Promise(r=>{n=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel flush failed: ${r instanceof Error?r.message:String(r)}
6
+ `)}finally{n!==void 0&&clearTimeout(n)}})()),await Promise.all(t)}var F=cs.getTracer("@trayai/helix-sdk");function xs({executionId:e,deploymentId:t,triggerType:n="http",routeOrJob:r,startedAt:o,startMs:s,errored:i,errorMessage:a,userId:c,flags:l}){let u=new Date().toISOString(),p=Date.now()-s;if(Tt()){H(`
7
+ `+$n(r,i,p));return}qn({_otel:"summary",executionId:e,deploymentId:t,triggerType:n,routeOrJob:r,status:i?"error":"success",startedAt:o,finishedAt:u,durationMs:p,userId:c,hasError:i||l.hasError,hasAuth:l.hasAuth,hasAi:l.hasAi,hasExternal:l.hasExternal,hasDb:l.hasDb,errorSummary:i&&a!==null?re(a):null})}async function Lc(e,t){let n=e.startMs??Date.now();bs();let r=!1,o=null;try{return await Kn.run(e.executionId,()=>F.startActiveSpan("App",{kind:ls.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async s=>{try{let i=await t(),a=i?.httpResponse?.status??404;return r=a>=400,s.setAttribute("http.response.status_code",a),s.setAttribute("helix.status",r?"error":"success"),s.setStatus({code:r?Ze.ERROR:Ze.OK}),i}catch(i){throw r=!0,o=i instanceof Error?i.message:String(i),s.setAttribute("http.response.status_code",500),s.setAttribute("helix.status","error"),s.setStatus({code:Ze.ERROR,message:o}),i}finally{s.end()}}))}finally{xs({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:n,errored:r,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1}}),await vs()}}var Gn=1024,G=100*1024*1024,Vn=250,As=3600,Es=As*1e3,zn=new TextEncoder,Is=/(^|\/)\.\.(\/|$)/,Rs=/[?#]/;function Cs(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}function ie(e,t=Gn){if(e.length===0)throw d.filesPathInvalid("Path must be a non-empty string");et(e,t)}function Mt(e){return e.endsWith("/")?e.slice(0,-1):e}function et(e,t=Gn){if(e.length===0)return;if(Is.test(e))throw d.filesPathInvalid("Path contains path traversal segment");if(Rs.test(e)||Cs(e))throw d.filesPathInvalid("Path contains illegal characters");let n=e.split("/");if(e.startsWith("/")||e.endsWith("/")||n.some(o=>o===""))throw d.filesPathInvalid("Path must not contain empty path segments");for(let o of n){let s=zn.encode(o).length;if(s>Vn)throw d.filesPathInvalid(`Path segment exceeds ${Vn} UTF-8 bytes (got ${s})`)}let r=zn.encode(e).length;if(r<1||r>t)throw d.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${r})`)}function Jn(e){if(e>G)throw d.filesValueTooLarge(`File exceeds maximum size of ${G} bytes (got ${e})`,G)}function ge(e){let t=e!==void 0?e*1e3:Es;return new Date(Date.now()+t)}import{join as _e}from"path";var Ts="files",ks="files-meta",Ps=1023,Os=1,_s=5;function Wn(e){let t=Math.max(Buffer.byteLength(tt(e),"utf8"),Buffer.byteLength(Oe(e),"utf8"));return Math.max(0,Ps-t-Os-_s)}function tt(e){return _e(e,".helix",Ts)}function Oe(e){return _e(e,".helix",ks)}function De(e,t){return _e(tt(e),...t.split("/"))}function nt(e,t){return _e(Oe(e),...t.split("/"))+".json"}function rt(e,t){return t.length===0?tt(e):De(e,t)}function Xn(e,t){return t.length===0?Oe(e):_e(Oe(e),...t.split("/"))}import{z as Ds}from"zod";var qc=["us1","eu1","ap1","ap2"],Ft=Ds.string().refine(e=>un(e),e=>({message:`Invalid enum value. Expected ${pn().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));import{resolve as J}from"path";import{existsSync as ot,realpathSync as Yn}from"fs";import{loadConfig as Ms}from"c12";import{z as b}from"zod";var Zn=b.string().uuid("projectId must be a valid UUID"),er=b.string().min(1,"workspaceId must be a non-empty string"),tr=b.discriminatedUnion("store",[b.object({store:b.literal("managed")}),b.object({store:b.literal("dynamodb"),auth:b.string().min(1,"agentSessions.auth is required"),table:b.string().min(1,"agentSessions.table is required"),region:b.string().min(1,"agentSessions.region is required")})]),st=["openai","anthropic","google","mistral","cohere","bedrock","openai-compatible"],Fs=["openai","anthropic","google","mistral","cohere"],Ls=/^[a-z0-9][a-z0-9-]*$/i,nr=b.union([b.enum(Fs),b.object({service:b.enum(st),baseUrl:b.string().url().optional(),region:b.string().regex(Ls,"aiProviders: region must be an AWS region name (e.g. us-east-1)").optional()}).refine(e=>e.service!=="openai-compatible"||e.baseUrl!==void 0,{message:'aiProviders: baseUrl is required when service is "openai-compatible"'}).refine(e=>e.service!=="bedrock"||e.region!==void 0||e.baseUrl!==void 0,{message:'aiProviders: region (e.g. "us-east-1") or baseUrl is required when service is "bedrock"'}).refine(e=>e.service==="bedrock"||e.region===void 0,{message:'aiProviders: region only applies to service "bedrock"'}).refine(e=>e.baseUrl===void 0?!0:new URL(e.baseUrl).protocol==="https:",{message:"aiProviders: baseUrl must use https \u2014 ctx.ai requests route through the credentials broker's proxy, which rejects non-https destinations on every call (a plain-http endpoint, e.g. a local Ollama/vLLM instance over http, is not supported)"})]),Ns=b.object({name:b.string().min(1,"name is required"),projectId:Zn.optional(),workspaceId:er.optional(),region:Ft.optional(),env:b.literal("production").optional(),authentications:b.record(b.string()).optional().default({}),config:b.record(b.unknown()).optional().default({}),agentSessions:tr.optional(),aiProviders:b.record(nr).optional()}).transform(({env:e,region:t,...n})=>({...n,region:t??"us1"})),Qn=b.object({name:b.string().min(1,"name is required"),workspaceId:er.optional(),region:Ft,authentications:b.record(b.string()),config:b.record(b.unknown()),agentSessions:tr.optional(),aiProviders:b.record(nr).optional()}),Zc=b.discriminatedUnion("kind",[Qn.extend({kind:b.literal("provisioned"),projectId:Zn}),Qn.extend({kind:b.literal("unprovisioned")})]),rr=["helix","tray"],or=["ts","mts","cts","js","mjs","cjs"],sr="HELIX_CONFIG";function Lt(e){let t=e?.trim();return t||process.env[sr]?.trim()||void 0}function Us(e,t){let n=Lt(t?.configFile);if(n!==void 0){let r=J(e,n);return ot(r)?r:void 0}for(let r of rr)for(let o of or){let s=J(e,`${r}.config.${o}`);if(ot(s))return s}}function $s(e){for(let t of rr)if(or.some(n=>ot(J(e,`${t}.config.${n}`))))return t;return"helix"}function js(e,t){return J(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function Bs(e,t){let n=Lt(t?.configFile);return{name:$s(e),cwd:e,...n!==void 0?{configFile:js(e,n)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function Ks(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw d.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let n=Ns.safeParse(e);if(!n.success){let l=n.error.issues.map(u=>u.message).join("; ");throw d.configLoadFailed(`Invalid helix.config.ts at ${t}: ${l}`)}let{projectId:r,workspaceId:o,...s}=n.data,i=o!==void 0?{workspaceId:o}:{},a=fn(),c=a!==void 0?{...s,region:a}:s;return r!==void 0?{kind:"provisioned",projectId:r,...c,...i}:{kind:"unprovisioned",...c,...i}}async function el(e,t){let n=e??process.cwd(),r=Lt(t?.configFile),o=r!==void 0?J(n,r):void 0;if(o!==void 0&&!ot(o)){let a=t?.configFile?.trim()?"":` (from ${sr})`;throw d.configLoadFailed(`Config file not found: ${o}${a}`)}let s;try{s=await Ms(Bs(n,t))}catch(a){throw d.configLoadFailed(`Failed to load helix.config.ts: ${a instanceof Error?a.message:String(a)}`)}let i=s._configFile??Us(n,t);if(!i)throw d.configLoadFailed(`helix.config.ts not found at ${J(n,"helix.config.ts")}`);if(o!==void 0&&s._configFile!==void 0){let a=Yn(o);if(Yn(J(s._configFile))!==a)throw d.configLoadFailed(`Config file conflict: requested ${o} but ${J(s._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return Ks(s.config,i)}var Hs="WORKSPACE_ID_REQUIRED";function tl(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:Hs});return e.workspaceId}var ir="helix-tool",qs=/^[a-z][a-z0-9_]{0,63}$/;function sl(e){if(typeof e.name!="string"||!qs.test(e.name))throw new Error(`defineTool: invalid tool name ${JSON.stringify(e.name)} \u2014 use snake_case (e.g. "lookup_customer")`);if(typeof e.description!="string"||e.description.trim().length===0)throw new Error(`defineTool("${e.name}"): description is required`);if(!e.input||typeof e.input.safeParse!="function")throw new Error(`defineTool("${e.name}"): input must be a Zod schema`);if(typeof e.handler!="function")throw new Error(`defineTool("${e.name}"): handler must be a function`);let t=async(r,o)=>{let s=e.input.safeParse(r);if(!s.success)throw d.inputValidationFailed(s.error.issues.map(i=>i.path.join(".")||"(root)"));return e.handler({...o,input:s.data})},n=(async r=>t(r,Ve()));return Object.defineProperties(n,{kind:{value:ir,enumerable:!0},name:{value:e.name,enumerable:!0},description:{value:e.description,enumerable:!0},inputSchema:{value:e.input,enumerable:!0},needsApproval:{value:e.needsApproval,enumerable:!0},execute:{value:t,enumerable:!0}}),n}function ar(e){return typeof e=="function"&&e.kind===ir&&typeof e.name=="string"}var I=class extends Error{constructor(t){super(t),this.name="AgentCallerError"}};import{readFileSync as Vs}from"fs";import{isAbsolute as zs,resolve as Gs}from"path";var B=new Map;function cr(e){B.set(e.name,{definition:e});for(let t of B.values())t.referencesValidated=void 0}function ul(e,t){let n=B.get(e);n&&(n.baseDir=t,n.resolvedInstructions=void 0)}function pl(e,t){let n=B.get(e);n&&(n.resolvedInstructions=t)}function Me(e){let t=B.get(e);if(!t){let n=[...B.keys()].sort();throw new I(`Unknown agent "${e}". Registered agents: ${n.join(", ")||"(none \u2014 are the functions/_agents/ modules imported?)"}`)}return t.definition}function fl(){return[...B.values()].map(e=>e.definition)}function lr(e){let t=B.get(e);if(!t)throw new I(`Unknown agent "${e}"`);if(t.resolvedInstructions!==void 0)return t.resolvedInstructions;let{definition:n}=t;if(n.instructions!==void 0)return t.resolvedInstructions=n.instructions,n.instructions;let r=n.instructionsFile,o=zs(r)?r:t.baseDir!==void 0?Gs(t.baseDir,r):void 0;if(o===void 0)throw new Error(`Agent "${e}" uses instructionsFile "${r}" but its base directory is unknown \u2014 load the agent through helix dev (which records it), or use inline \`instructions\`.`);let s;try{s=Vs(o,"utf-8")}catch(i){throw new Error(`Agent "${e}": failed to read instructionsFile ${o}: ${i instanceof Error?i.message:String(i)}`)}if(s.trim().length===0)throw new Error(`Agent "${e}": instructionsFile ${o} is empty`);return t.resolvedInstructions=s,s}function dr(e){let t=B.get(e);if(t?.referencesValidated)return;let n=Me(e);for(let r of n.agents??[]){let s=(Me(r).tools??[]).filter(i=>i.needsApproval);if(s.length>0)throw new Error(`Agent "${e}" delegates to "${r}", which has needsApproval tools (${s.map(i=>i.name).join(", ")}) \u2014 approval cannot pause a parent's loop through delegation in v1. Put approval-gated tools on the orchestrating agent.`)}t&&(t.referencesValidated=!0)}function ml(){B.clear()}import{z as P}from"zod";var ur="helix-agent",Js=/^[a-z][a-z0-9-]{0,63}$/,Ws=P.object({model:P.string().min(1),auth:P.string().min(1)}),Xs=P.object({name:P.string().regex(Js,'agent name must be kebab-case (e.g. "support-agent"); name is required in v1'),description:P.string().min(1,"description is required"),model:P.string().min(1,"model is required"),auth:P.string().min(1,"auth (authentication alias) is required"),fallbacks:P.array(Ws).optional(),instructions:P.string().min(1).optional(),instructionsFile:P.string().min(1).optional(),tools:P.array(P.custom(ar,"tools entries must be defineTool exports")).optional(),agents:P.array(P.string().min(1)).optional(),memory:P.object({maxSessionMessages:P.number().int().positive().optional(),ttl:P.number().int().positive().optional(),scope:P.enum(["user","project"]).optional()}).optional(),limits:P.object({maxIterations:P.number().int().positive().optional(),maxToolCalls:P.number().int().positive().optional()}).optional()}).refine(e=>e.instructions===void 0!=(e.instructionsFile===void 0),{message:"exactly one of instructions / instructionsFile must be set"}),pr=200,fr=25,mr=50,Nt=3;function Sl(e){let t=Xs.safeParse(e);if(!t.success){let o=typeof e?.name=="string"?e.name:"(unnamed)",s=t.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new Error(`defineAgent(${o}): invalid definition \u2014 ${s}`)}let n=new Set;for(let o of t.data.tools??[]){if(n.has(o.name))throw new Error(`defineAgent(${t.data.name}): duplicate tool "${o.name}"`);n.add(o.name)}let r={kind:ur,...t.data};return cr(r),r}function bl(e){return typeof e=="object"&&e!==null&&e.kind===ur&&typeof e.name=="string"}var Ys=50,gr=500;function Fe(e){let t=e?.limit??Ys;if(!Number.isInteger(t)||t<1||t>gr)throw new I(`session.page(): limit must be an integer from 1 to ${gr}.`);let n=e?.order??"asc";if(n!=="asc"&&n!=="desc")throw new I('session.page(): order must be "asc" or "desc".');return{limit:t,order:n,cursor:e?.cursor}}function $t(){return new I("session.page(): invalid cursor \u2014 pass the `nextCursor` of the previous page, with the same `order`.")}var W=new Map;function jt(e,t,n){let r=encodeURIComponent;return n!==void 0?`agent:${r(e)}:user:${r(n)}:session:${r(t)}`:`agent:${r(e)}:session:${r(t)}`}function Qs(e,t,n){let r=Math.max(0,e.length-t);for(let s=r;s<e.length;s++)if(e[s]?.role==="user")return e.slice(s);for(let s=r-1;s>=0;s--)if(e[s]?.role==="user")return e.slice(s);if(!n)return;let o=r;for(;o<e.length&&e[o]?.role==="tool";)o++;return e.slice(o)}var Zs=32;async function Bt(e,t){let n=t+Zs;for(;;){let r=await e.messages({limit:n}),o=Qs(r,t,r.length<n);if(o!==void 0)return o;n*=2}}function Kt(e,t){return e.ttlSeconds!==void 0&&t-e.lastActiveAt>e.ttlSeconds*1e3}var ei=6e4,Ut=0;function ti(e){if(!(e-Ut<ei)){Ut=e;for(let[t,n]of W)if(Kt(n,e)){if(n.pendingApprovals.length>0){n.messages=[];continue}W.delete(t)}}}var X=class extends Error{constructor(t){super(`Agent session "${t}" has expired (session-expired)`),this.name="SessionExpiredError"}};function yr(e,t,n,r){let o=Date.now();ti(o);let s=n?.ttl,i=t??`ses_${crypto.randomUUID().replaceAll("-","")}`,a=jt(e,i,r),c=W.get(a);if(c&&(c.ttlSeconds=s),c&&Kt(c,o)){if(W.delete(a),c.pendingApprovals.length>0)throw new X(i);c=void 0}c||(c={id:i,agentName:e,...r!==void 0?{ownerUserId:r}:{},messages:[],createdAt:o,lastActiveAt:o,pendingApprovals:[],ttlSeconds:s},W.set(a,c));let l=c,u=()=>{l.lastActiveAt=Date.now()};return{id:i,async messages(p){u();let m=l.messages;return p?.limit!==void 0?m.slice(-p.limit):[...m]},async page(p){let{limit:m,order:g,cursor:w}=Fe(p);u();let S=w===void 0?0:Number(w);if(!Number.isInteger(S)||S<0)throw $t();let x=g==="desc"?[...l.messages].reverse():l.messages,y=x.slice(S,S+m),f=S+y.length;return{messages:y,nextCursor:f<x.length?String(f):null}},async append(...p){u(),l.messages.push(...p)},async clear(){W.delete(a)},async truncated(){return!1},async pendingApprovals(){return u(),[...l.pendingApprovals]},async addPendingApprovals(p){u(),l.pendingApprovals.push(...p)},async resolveApproval(p){u();let m=l.pendingApprovals.findIndex(g=>g.approvalId===p);return m===-1?"already-resolved":(l.pendingApprovals.splice(m,1),"resolved")}}}function hr(e,t,n={}){let r=Date.now(),o=n.first??20,s=n.cursor!==void 0&&Number.parseInt(n.cursor,10)||0,i=[...W.values()].filter(c=>c.agentName===e&&c.ownerUserId===t&&!Kt(c,r)).sort((c,l)=>l.lastActiveAt-c.lastActiveAt);return{sessions:i.slice(s,s+o).map(c=>({id:c.id,createdAt:c.createdAt,lastActivityAt:c.lastActiveAt,messageCount:c.messages.length,pendingApprovals:c.pendingApprovals.length})),nextCursor:s+o<i.length?String(s+o):null}}function Al(){W.clear(),Ut=0}import{AsyncLocalStorage as Ri}from"async_hooks";import{z as zr}from"zod";import{generateText as Ci,streamText as Ti,tool as Gr,stepCountIs as ki}from"ai";import{SpanKind as zt,SpanStatusCode as Se,context as Jr,trace as Pi}from"@opentelemetry/api";import{embed as xr,embedMany as Ar,generateImage as Er,generateObject as Ir,generateSpeech as Rr,generateText as Cr,streamObject as Tr,streamText as kr,transcribe as Pr}from"ai";import{SpanKind as fi,SpanStatusCode as vr}from"@opentelemetry/api";import{createOpenAI as si}from"@ai-sdk/openai";import{createAnthropic as ii}from"@ai-sdk/anthropic";import{createGoogle as ai}from"@ai-sdk/google";import{createMistral as ci}from"@ai-sdk/mistral";import{createCohere as li}from"@ai-sdk/cohere";import{createAmazonBedrock as di}from"@ai-sdk/amazon-bedrock";import{createOpenAICompatible as ui}from"@ai-sdk/openai-compatible";var ni=new Set(["x-api-key","x-goog-api-key"]);function ri(e){return gn(e)||ni.has(e.toLowerCase())}function oi(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function wr(e){return async(t,n)=>{let r=oi(t),o=new URL(r);if(o.protocol!=="https:")throw d.unsupportedScheme(o.protocol.replace(/:$/,""));let s=E(),{region:i}=A(),a=new Headers(n?.headers??(t instanceof Request?t.headers:void 0)),c=new Headers;for(let[x,y]of a.entries())ri(x)||c.append(x,y);c.set(Ie,r),c.set(ze,e),s.executionId&&c.set(Re,s.executionId);let{headers:l,deploymentId:u}=z(s);for(let[x,y]of Object.entries(l))c.set(x,y);u&&c.set(te,u);let p=fe(i,s.mode==="lambda"?"runtime":"dev"),m=n?.body??(t instanceof Request?t.clone().body:void 0),g={method:n?.method??(t instanceof Request?t.method:"GET"),headers:c,redirect:"manual",signal:n?.signal??void 0};m!=null&&(g.body=m,typeof ReadableStream<"u"&&m instanceof ReadableStream&&(g.duplex="half"));let w;try{w=await fetch(p,g)}catch(x){if(x instanceof Error&&x.name==="AbortError")throw x;let y=x instanceof Error?x.message??String(x):String(x);throw d.brokerError(0,y)}let S=w.headers.get(Ge);if(S!==null){let x=await w.text(),y=x||S;try{let f=yn.safeParse(JSON.parse(x));f.success&&(y=f.data.error.message)}catch{}throw S===pe&&(y="credential broker does not support the raw proxy endpoint required by ctx.ai \u2014 deploy a newer broker or pin an older SDK"),d.brokerError(w.status,y,x||void 0,S)}return w}}var ae="helix-broker";function Sr(e){let{alias:t,service:n,baseUrl:r,region:o,authenticationId:s}=e,i=wr(s);switch(n){case"openai":return si({apiKey:ae,fetch:i});case"anthropic":return ii({apiKey:ae,fetch:i});case"google":return ai({apiKey:ae,fetch:i});case"mistral":return ci({apiKey:ae,fetch:i});case"cohere":return li({apiKey:ae,fetch:i});case"bedrock":{if(!o&&!r)throw d.aiProviderMisconfigured(t,n,'set region (e.g. "us-east-1") or baseUrl for the Bedrock runtime endpoint');return di({apiKey:ae,region:o??"helix-broker",...r?{baseURL:r}:{},fetch:i})}case"openai-compatible":{if(!r)throw d.aiProviderMisconfigured(t,n,"set baseUrl for the endpoint");return ui({name:t,baseURL:r,apiKey:ae,fetch:i})}}}var br={"gpt-4o-mini":{input:.15,output:.6},"gpt-4o":{input:2.5,output:10},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4.1":{input:2,output:8},"text-embedding-3-small":{input:.02,output:0},"text-embedding-3-large":{input:.13,output:0},"gpt-image-1":{input:5,output:40},"claude-opus-4":{input:15,output:75},"claude-sonnet-4":{input:3,output:15},"claude-haiku-4":{input:1,output:5},"claude-3-5-haiku":{input:.8,output:4},"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.3,output:2.5},"text-embedding-004":{input:0,output:0},"mistral-large":{input:2,output:6},"mistral-small":{input:.1,output:.3},"command-r-plus":{input:2.5,output:10},"command-r":{input:.15,output:.6}},pi=Object.keys(br).sort((e,t)=>t.length-e.length);function it(e,t){let n=pi.find(s=>e.startsWith(s));if(!n||!t)return{amount:0,currency:"USD"};let r=br[n],o=((t.inputTokens??0)*r.input+(t.outputTokens??0)*r.output)/1e6;return{amount:Number(o.toFixed(8)),currency:"USD"}}function L(e,t,n){return F.startActiveSpan("ai",{kind:fi.CLIENT},async r=>{r.setAttributes({operation:e.operation,model:e.model,...e.alias!==void 0?{alias:e.alias}:{}}),O("hasAi");try{let o=await t(),s=n?.(o);return s&&r.setAttributes({...s.inputTokens!==void 0?{inputTokens:s.inputTokens}:{},...s.outputTokens!==void 0?{outputTokens:s.outputTokens}:{}}),r.setAttribute("status","success"),r.setStatus({code:vr.OK}),o}catch(o){let s=o instanceof Error?o.message:String(o);throw r.setAttribute("status","error"),r.setStatus({code:vr.ERROR,message:s}),o}finally{r.end()}})}function mi(){return`aireq_${crypto.randomUUID().replaceAll("-","")}`}function he(e,t){return{cost:it(e,t),requestId:mi()}}function ce(e){return typeof e=="object"&&e!==null&&"modelId"in e?String(e.modelId):String(e)}var Or=new WeakSet;function ye(e){return Or.add(e),e}function _r(e){return ye(e)}function V(e){if(typeof e!="object"||e===null)throw d.aiModelInstanceRequired(typeof e=="string"?e:String(e));if(!Or.has(e))throw d.aiForeignModelRejected()}function at(e){return e.totalUsage??e.usage}function ct(e){return e.usage?.tokens!==void 0?{inputTokens:e.usage.tokens}:void 0}function lt(e){return e.usage}function Ht(e){let t=A(),n=t.authentications??{};if(!n[e])throw d.unknownAlias(e,Object.keys(n));let r=n[e],o=(t.aiProviders??{})[e];if(o===void 0)throw d.aiProviderNotConfigured(e,[...st]);let{service:s,baseUrl:i,region:a}=typeof o=="string"?{service:o,baseUrl:void 0,region:void 0}:o,c=Sr({alias:e,service:s,baseUrl:i,region:a,authenticationId:r}),l=y=>ye(c.languageModel(y)),u=y=>ye(c.embeddingModel(y)),p=y=>ye(c.imageModel(y)),m=y=>{if(!c.transcriptionModel)throw new Error(`AI provider "${s}" (alias "${e}") has no transcription models`);return ye(c.transcriptionModel(y))},g=y=>{if(!c.speechModel)throw new Error(`AI provider "${s}" (alias "${e}") has no speech models`);return ye(c.speechModel(y))},w=(y=>l(y)),S=(y,f)=>{let h=y.model;if(typeof h!="string")throw d.aiModelIdRequired(e,f);return h};return Object.assign(w,{specificationVersion:"v4",languageModel:l,embeddingModel:u,textEmbeddingModel:u,imageModel:p,transcriptionModel:m,speechModel:g,async generateText(y){let f=S(y,"generateText"),h=await L({operation:"generateText",model:f,alias:e},()=>Cr({...y,model:l(f)}),at);return Object.assign(h,{helix:he(f,at(h))})},streamText(y){let f=S(y,"streamText");return O("hasAi"),kr({...y,model:l(f)})},async generateObject(y){let f=S(y,"generateObject"),h=await L({operation:"generateObject",model:f,alias:e},()=>Ir({...y,model:l(f)}),R=>R.usage),v=h.usage;return Object.assign(h,{helix:he(f,v)})},streamObject(y){let f=S(y,"streamObject");return O("hasAi"),Tr({...y,model:l(f)})},async embed(y){let f=S(y,"embed");return L({operation:"embed",model:f,alias:e},()=>xr({...y,model:u(f)}),ct)},async embedMany(y){let f=S(y,"embedMany");return L({operation:"embedMany",model:f,alias:e},()=>Ar({...y,model:u(f)}),ct)},async generateImage(y){let f=S(y,"generateImage"),h=await L({operation:"generateImage",model:f,alias:e},()=>Er({...y,model:p(f)}),lt);return Object.assign(h,{helix:he(f,lt(h))})},async transcribe(y){let f=S(y,"transcribe");return L({operation:"transcribe",model:f,alias:e},()=>Pr({...y,model:m(f)}))},async generateSpeech(y){let f=S(y,"generateSpeech");return L({operation:"generateSpeech",model:f,alias:e},()=>Rr({...y,model:g(f)}))}})}function Xl(){let e=new Map;return Object.assign((r=>{let o=e.get(r);return o||(o=Ht(r),e.set(r,o)),o}),{async generateText(r){V(r.model);let o=ce(r.model),s=await L({operation:"generateText",model:o},()=>Cr(r),at);return Object.assign(s,{helix:he(o,at(s))})},streamText(r){return V(r.model),O("hasAi"),kr(r)},async generateObject(r){V(r.model);let o=ce(r.model),s=await L({operation:"generateObject",model:o},()=>Ir(r),a=>a.usage),i=s.usage;return Object.assign(s,{helix:he(o,i)})},streamObject(r){return V(r.model),O("hasAi"),Tr(r)},async embed(r){return V(r.model),L({operation:"embed",model:ce(r.model)},()=>xr(r),ct)},async embedMany(r){return V(r.model),L({operation:"embedMany",model:ce(r.model)},()=>Ar(r),ct)},async generateImage(r){V(r.model);let o=ce(r.model),s=await L({operation:"generateImage",model:o},()=>Er(r),lt);return Object.assign(s,{helix:he(o,lt(s))})},async transcribe(r){return V(r.model),L({operation:"transcribe",model:ce(r.model)},()=>Pr(r))},async generateSpeech(r){return V(r.model),L({operation:"generateSpeech",model:ce(r.model)},()=>Rr(r))}})}var qt=class extends Error{errors;constructor(t){super(`all ${t.length} models in the fallback chain failed \u2014 `+t.map(({modelId:n,error:r})=>`${n}: ${r instanceof Error?r.message:String(r)}`).join("; ")),this.name="FallbackExhaustedError",this.errors=t.map(n=>n.error)}};function Dr(e){if(e.length===0)throw new Error("createFallbackModel: at least one model required");if(e.length===1)return e[0];let t=e[0];async function n(r){let o=[];for(let s of e)try{return await r(s)}catch(i){if(i instanceof Error&&i.name==="AbortError")throw i;o.push({modelId:s.modelId,error:i})}throw new qt(o)}return{specificationVersion:"v4",provider:t.provider,modelId:t.modelId,get supportedUrls(){return Promise.resolve(t.supportedUrls)},doGenerate:r=>n(o=>o.doGenerate(r)),doStream:r=>n(o=>o.doStream(r))}}function Vt(e){let t=e.code===pe?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":e.message;throw d.brokerError(e.status,t,k(e.body),e.code)}async function we(e,t={}){let n=E(),{region:r}=A(),{headers:o,deploymentId:s}=z(n);s&&(o[te]=s);let i=fe(r,n.mode==="lambda"?"runtime":"dev"),a;try{a=await wn({proxyUrl:i,credentialHeaders:o,request:e,timeoutMs:t.timeout,executionId:n.executionId})}catch(c){let l=c instanceof Error?c.message??String(c):String(c);throw d.brokerError(0,l)}return a.kind==="brokerError"&&Vt(a),a.response}var gi=8,ut="msg#",yi="meta",Mr=25,Fr=3,hi=400*1024-1024;function wi(e){let t=new Set,n=new Set;for(let r of e)if(Array.isArray(r?.content))for(let o of r.content){if(typeof o!="object"||o===null)continue;let{type:s,approvalId:i,isAutomatic:a}=o;typeof i=="string"&&(s==="tool-approval-request"&&a!==!0&&t.add(i),s==="tool-approval-response"&&n.add(i))}for(let r of n)t.delete(r);return t}var N=e=>({S:e}),dt=e=>({N:String(e)});function Le(e,t){let n=e?.[t]?.S;return typeof n=="string"?n:void 0}function Lr(e,t){let n=e?.[t]?.N;return typeof n=="string"?Number(n):void 0}function Si(e,t){return e?.[t]?.BOOL===!0}function Nr(e,t){let n=e?.[t]?.M;return typeof n=="object"&&n!==null?n:{}}function bi(e){return`${ut}${String(e).padStart(gi,"0")}`}function vi(e){let t=null;if(typeof e=="string")try{t=JSON.parse(e)}catch{return}else e!==null&&typeof e=="object"&&(t=e);let n=t?.__type;return typeof n=="string"?n.split("#").pop():void 0}function Ur(e){let{agentName:t,table:n,region:r,authenticationId:o}=e,s=e.options?.ttl,i=e.sessionId??`ses_${crypto.randomUUID().replaceAll("-","")}`,a=jt(t,i,e.ownerUserId),c={pk:N(a),sk:N(yi)};async function l(f,h){let v=ne({authenticationId:o,method:"POST",url:`https://dynamodb.${r}.amazonaws.com/`,body:h,headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${f}`}}),R,T;try{({status:R,body:T}=await we(v))}catch(C){throw C instanceof d?C:d.agentSessionsFailed(C instanceof Error?C.message:String(C))}if(R>=400){let C=vi(T);throw C==="ConditionalCheckFailedException"?new pt:d.agentSessionsFailed(`DynamoDB ${f} failed (${R}): ${C??JSON.stringify(T).slice(0,300)}`)}if(typeof T=="string")try{return JSON.parse(T)}catch{throw d.agentSessionsFailed(`DynamoDB ${f}: non-JSON response body`)}return T??{}}async function u(){return(await l("GetItem",{TableName:n,Key:c,ConsistentRead:!0})).Item}let p=!1;async function m(){p||(await g(),p=!0)}async function g(){let f=await u();if(!f){let v=await w({ascending:!0});if(v.length===0||await u())return;let R=v.map(T=>JSON.parse(Le(T,"message")??"null"));if(await S(v.map(T=>({DeleteRequest:{Key:{pk:N(a),sk:T.sk}}}))),wi(R).size>0)throw new X(i);return}if(s===void 0)return;let h=Lr(f,"lastActiveAt")??0;if(!(Date.now()-h<=s*1e3)){if(Object.keys(Nr(f,"pendingApprovals")).length>0)throw new X(i);await x()}}async function w(f){let h=[],v;do{let R=await l("Query",{TableName:n,KeyConditionExpression:"pk = :pk AND begins_with(sk, :prefix)",ExpressionAttributeValues:{":pk":N(a),":prefix":N(ut)},ConsistentRead:!0,ScanIndexForward:f.ascending,...f.limit!==void 0?{Limit:f.limit}:{},...f.projection!==void 0?{ProjectionExpression:f.projection}:{},...v!==void 0?{ExclusiveStartKey:v}:{}});if(h.push(...R.Items??[]),v=R.LastEvaluatedKey,f.limit!==void 0&&h.length>=f.limit)break}while(v!==void 0);return h}async function S(f){for(let h=0;h<f.length;h+=Mr){let v=f.slice(h,h+Mr);for(let R=0;v.length>0;R++){let C=(await l("BatchWriteItem",{RequestItems:{[n]:v}})).UnprocessedItems?.[n];if(!C||C.length===0)break;if(R>=Fr)throw d.agentSessionsFailed(`DynamoDB BatchWriteItem: ${C.length} items still unprocessed after ${Fr} retries`);v=C}}}async function x(){let h=(await w({ascending:!0,projection:"sk"})).map(v=>({DeleteRequest:{Key:{pk:N(a),sk:v.sk}}}));h.push({DeleteRequest:{Key:c}}),await S(h)}async function y(f){let h=Date.now();return(await l("UpdateItem",{TableName:n,Key:c,UpdateExpression:"ADD nextSeq :reserve, messageCount :reserve SET lastActiveAt = :now, "+(s!==void 0?"expiresAt = :expires, ":"")+"createdAt = if_not_exists(createdAt, :now), truncated = if_not_exists(truncated, :false), pendingApprovals = if_not_exists(pendingApprovals, :emptyMap)"+(s===void 0?" REMOVE expiresAt":""),ExpressionAttributeValues:{":reserve":dt(f),":now":dt(h),...s!==void 0?{":expires":dt(Math.floor(h/1e3)+s)}:{},":false":{BOOL:!1},":emptyMap":{M:{}}},ReturnValues:"ALL_NEW"})).Attributes??{}}return{id:i,async messages(f){await m();let h=f?.limit;return h!==void 0?(await w({ascending:!1,limit:h})).reverse().map(T=>JSON.parse(Le(T,"message")??"null")):(await w({ascending:!0})).map(R=>JSON.parse(Le(R,"message")??"null"))},async page(f){let{limit:h,order:v,cursor:R}=Fe(f);await m();let T;if(R!==void 0&&(T=Buffer.from(R,"base64url").toString("utf8"),!T.startsWith(ut)))throw $t();let C=await l("Query",{TableName:n,KeyConditionExpression:"pk = :pk AND begins_with(sk, :prefix)",ExpressionAttributeValues:{":pk":N(a),":prefix":N(ut)},ConsistentRead:!0,ScanIndexForward:v==="asc",Limit:h,...T!==void 0?{ExclusiveStartKey:{pk:N(a),sk:N(T)}}:{}}),ee=C.Items??[],qe=Le(C.LastEvaluatedKey,"sk");return{messages:ee.map(Go=>JSON.parse(Le(Go,"message")??"null")),nextCursor:qe!==void 0?Buffer.from(qe,"utf8").toString("base64url"):null}},async append(...f){if(f.length===0)return;let h=f.map(ee=>JSON.stringify(ee)),v=h.findIndex(ee=>Buffer.byteLength(ee,"utf8")>hi);if(v!==-1)throw d.agentSessionsFailed(`a ${f[v].role} message of ${Buffer.byteLength(h[v],"utf8")} bytes exceeds DynamoDB's 400 KB item limit \u2014 the session store keeps one item per message; have tools summarise or offload (ctx.files) large results`);await m();let R=await y(f.length),C=(Lr(R,"nextSeq")??f.length)-f.length+1;await S(h.map((ee,qe)=>({PutRequest:{Item:{pk:N(a),sk:N(bi(C+qe)),message:N(ee)}}})))},async clear(){await x()},async truncated(){return await m(),Si(await u(),"truncated")},async pendingApprovals(){await m();let f=Nr(await u(),"pendingApprovals");return Object.values(f).map(h=>{let v=h.S;return v!==void 0?JSON.parse(v):void 0}).filter(h=>h!==void 0)},async addPendingApprovals(f){if(f.length===0)return;await m(),await y(0);let h={},v={},R=[];f.forEach((T,C)=>{h[`#a${C}`]=T.approvalId,v[`:v${C}`]=N(JSON.stringify(T)),R.push(`pendingApprovals.#a${C} = :v${C}`)}),await l("UpdateItem",{TableName:n,Key:c,UpdateExpression:`SET ${R.join(", ")}`,ExpressionAttributeNames:h,ExpressionAttributeValues:v})},async resolveApproval(f){await m();try{return await l("UpdateItem",{TableName:n,Key:c,UpdateExpression:"REMOVE pendingApprovals.#id SET lastActiveAt = :now",ConditionExpression:"attribute_exists(pendingApprovals.#id)",ExpressionAttributeNames:{"#id":f},ExpressionAttributeValues:{":now":dt(Date.now())}}),"resolved"}catch(h){if(h instanceof pt)return"already-resolved";throw h}}}}var pt=class extends Error{constructor(){super("ConditionalCheckFailedException"),this.name="ConditionalCheckFailed"}};import xi from"ky";async function K(e){let t=e.headers.get("content-type")??"",n=await e.text();if(n.length!==0)return t.includes("application/json")?JSON.parse(n):n}var Ai=6e4,Ei=500,$r=500;function jr(e){let t=A();if(t.kind!=="provisioned")throw d.agentSessionsFailed("the managed session store requires a provisioned project (projectId in helix.config.ts)");return`${j(t.region).hosts.api}/private/v1/helix/projects/${encodeURIComponent(t.projectId)}/storage/agent-sessions/${encodeURIComponent(e)}`}function Ii(){let e=ue(),t=$(),n={Accept:"application/json"};if(e&&e.trim().length>0&&(n[de]=e),t&&t.trim().length>0&&(n[U]=t),Object.keys(n).length===1)throw d.missingExecutionCredentials();return n}async function Y(e,t,n){try{let r=await xi(t,{method:e,headers:Ii(),...n!==void 0?{json:n}:{},throwHttpErrors:!1,timeout:Ai});return{status:r.status,body:await K(r)}}catch(r){throw r instanceof d?r:d.agentSessionsFailed(`managed session store unreachable: ${r instanceof Error?r.message:String(r)}`)}}function ft(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message}return String(e??"unknown error")}function le(e,t,n){throw t===410?new X(e):t===404?new I(`Agent session "${e}" was not found (it may belong to a different user or have expired).`):d.agentSessionsFailed(`managed session store error ${t}: ${ft(n)}`)}function Br(e){let t=jr(e.agentName),n=e.sessionId??`ses_${crypto.randomUUID().replaceAll("-","")}`,r=e.options?.scope,o=e.options?.ttl,s=async c=>{let l=new URL(`${t}/${encodeURIComponent(n)}/messages`);c.first!==void 0&&l.searchParams.set("first",String(c.first)),c.cursor!==void 0&&l.searchParams.set("cursor",c.cursor),c.order!==void 0&&l.searchParams.set("order",c.order);let{status:u,body:p}=await Y("get",l.toString());if(u!==404){if(u===400&&c.cursor!==void 0)throw new I(`session.page(): ${ft(p)}`);return(u<200||u>=300)&&le(n,u,p),p}},i=c=>c.elements.length<2||c.elements[0].id>c.elements[1].id,a=async()=>{let c=[],l;for(;;){let u=await s({...l!==void 0?{cursor:l}:{}});if(u===void 0)return[];if(c.push(...u.elements.map(p=>p.message)),!u.pageInfo.hasNextPage||u.pageInfo.endCursor===null)break;l=u.pageInfo.endCursor}return c};return{id:n,async messages(c){let l=c?.limit;if(l===void 0)return a();let u=[],p;for(;u.length<l;){let m=await s({order:"desc",first:Math.min(l-u.length,Ei),...p!==void 0?{cursor:p}:{}});if(m===void 0)return[];if(!i(m))return(await a()).slice(-l);if(u.push(...m.elements.map(g=>g.message)),!m.pageInfo.hasNextPage||m.pageInfo.endCursor===null)break;p=m.pageInfo.endCursor}return u.slice(0,l).reverse()},async page(c){let{limit:l,order:u,cursor:p}=Fe(c),m=await s({first:l,order:u,...p!==void 0?{cursor:p}:{}});if(m===void 0)return{messages:[],nextCursor:null};if(u==="desc"&&!i(m))throw d.agentSessionsFailed('the managed session store in this environment does not support newest-first paging yet \u2014 page with order: "asc", or read the latest messages with session.messages({ limit }).');return{messages:m.elements.map(g=>g.message),nextCursor:m.pageInfo.hasNextPage?m.pageInfo.endCursor:null}},async append(...c){if(c.length===0)return;let{status:l,body:u}=await Y("post",`${t}/${encodeURIComponent(n)}/messages`,{messages:c,...r!==void 0?{scope:r}:{},...o!==void 0?{ttl:o}:{}});(l<200||l>=300)&&le(n,l,u)},async clear(){for(let c=0;c<$r;c++){let{status:l,body:u}=await Y("delete",`${t}/${encodeURIComponent(n)}`);if(l===204||l===404)return;if(!(l===200&&u?.more===!0)){if(l===200)return;le(n,l,u)}}throw d.agentSessionsFailed(`clearing session "${n}" did not complete after ${$r} calls \u2014 call clear() again to continue.`)},async truncated(){let{status:c,body:l}=await Y("get",`${t}/${encodeURIComponent(n)}`);return c===404?!1:((c<200||c>=300)&&le(n,c,l),l.truncated===!0)},async pendingApprovals(){let{status:c,body:l}=await Y("get",`${t}/${encodeURIComponent(n)}`);return c===404?[]:((c<200||c>=300)&&le(n,c,l),l.pendingApprovals)},async addPendingApprovals(c){if(c.length===0)return;let{status:l,body:u}=await Y("post",`${t}/${encodeURIComponent(n)}/approvals`,{approvals:c});l!==204&&le(n,l,u)},async resolveApproval(c){let{status:l,body:u}=await Y("post",`${t}/${encodeURIComponent(n)}/approvals/${encodeURIComponent(c)}/resolve`);return(l<200||l>=300)&&le(n,l,u),u.status}}}async function Kr(e,t={}){let n=jr(e),r=new URL(n);t.first!==void 0&&r.searchParams.set("first",String(t.first)),t.cursor!==void 0&&r.searchParams.set("cursor",t.cursor);let{status:o,body:s}=await Y("get",r.toString());if(o===400)throw new I(ft(s));if(o<200||o>=300)throw d.agentSessionsFailed(`managed session store error ${o}: ${ft(s)}`);let i=s;return{sessions:i.elements.map(a=>({id:a.sessionId,createdAt:a.createdAt,lastActivityAt:a.lastActivityAt,messageCount:a.messageCount,pendingApprovals:a.pendingApprovalCount})),nextCursor:i.pageInfo.endCursor}}function Hr(e){if(e?.scope!=="user")return;let t=mn.getStore()?.userId;if(typeof t!="string"||t.length===0)throw new I('This agent is user-scoped (memory.scope: "user") \u2014 it can only run in a user execution with a user identity (ctx.userId); schedules have none.');return t}function qr(){return E().mode==="lambda"}function mt(e,t,n){let r=A(),o=r.agentSessions,s=Hr(n);if(o?.store==="dynamodb"){let i=r.authentications??{},a=i[o.auth];if(!a)throw d.unknownAlias(o.auth,Object.keys(i));return Ur({agentName:e,sessionId:t,authenticationId:a,table:o.table,region:o.region,options:n,...s!==void 0?{ownerUserId:s}:{}})}return qr()?Br({agentName:e,sessionId:t,options:n}):yr(e,t,n,s)}async function Vr(e,t,n={}){if(t?.scope!=="user")throw new I(`agent.sessions() lists the calling user's sessions \u2014 the agent must declare memory.scope: "user".`);if(A().agentSessions?.store==="dynamodb")throw new I('agent.sessions() is not supported on the bring-your-own DynamoDB session store \u2014 use the managed store (agentSessions: { store: "managed" }).');let o=Hr(t);return qr()?Kr(e,n):hr(e,o,n)}var Wr=new Ri;function Oi(e){return({steps:t})=>t.reduce((n,r)=>n+r.toolCalls.length,0)>=e}function Xr(e,t,n,r){return F.startActiveSpan("agent.tool",{kind:zt.INTERNAL,attributes:{agent:e,tool:t,...n}},async o=>{try{let s=await r();return o.setAttribute("status","success"),o.setStatus({code:Se.OK}),s}catch(s){throw o.setAttribute("status","error"),o.setStatus({code:Se.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o.end()}})}function _i(e){let t={};for(let n of e.tools??[]){let r=n.needsApproval;t[n.name]=Gr({description:n.description,inputSchema:n.inputSchema,...r!==void 0?{needsApproval:typeof r=="function"?o=>r(o):r}:{},execute:o=>Xr(e.name,n.name,{},()=>n.execute(o,Ve()))})}for(let n of e.agents??[]){let r=Me(n),o=`agent_${n.replaceAll("-","_")}`;t[o]=Gr({description:r.description,inputSchema:zr.object({prompt:zr.string().describe("The task or question for the agent")}),execute:({prompt:s})=>Xr(e.name,o,{delegateAgent:n},async()=>{let i=Wr.getStore()??0;return i>=Nt?{error:"delegation_depth_exceeded",message:`Delegation depth limit (${Nt}) reached \u2014 answer with what you have instead of delegating further.`}:(await Wr.run(i+1,()=>Ui(n).generate({prompt:s}))).text})})}return t}function Di(e){let t=[{model:e.model,auth:e.auth},...e.fallbacks??[]];return _r(Dr(t.map(n=>Ht(n.auth)(n.model))))}function Gt(e){return e.filter(t=>typeof t=="object"&&t!==null&&t.type==="tool-approval-request"&&!t.isAutomatic)}function Yr(e){return{approvalId:e.approvalId,toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input,requestedAt:new Date().toISOString()}}function Mi(e){return{id:e.approvalId,toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input}}function Fi(e){let t=new Set;for(let n of e)if(Array.isArray(n.content))for(let r of Gt(n.content))t.add(r.approvalId);return t}function Li(e,t){let n=e.reduce((r,o)=>r+it(o.response.modelId??t,o.usage).amount,0);return{amount:Number(n.toFixed(8)),currency:"USD"}}async function Ni(e,t,n){let r=[],o=[];if(n.approvals&&n.approvals.length>0){if(n.prompt!==void 0||(n.messages?.length??0)>0)throw new I("agent.generate() cannot combine `approvals` with `prompt` or `messages` \u2014 send the approvals on their own, then send new input on the next call.");let s=new Map((await e.pendingApprovals()).map(p=>[p.approvalId,p]));if(s.size===0&&t.length===0)throw new I(`Session "${e.id}" has no history and nothing awaiting approval \u2014 it does not exist, has expired, or belongs to a different user.`);let i=Fi(t),a=new Set(n.approvals.map(p=>p.id)),c=[...a].filter(p=>!s.has(p)&&!i.has(p));if(c.length>0)throw new I(`Unknown approval id(s) for session "${e.id}": ${c.join(", ")} \u2014 use the ids from \`pendingApprovals\` on the paused result.`);let l=[...s.keys()].filter(p=>!a.has(p));if(l.length>0)throw new I(`Session "${e.id}" has ${l.length} pending approval(s) not decided in this call: ${l.join(", ")} \u2014 decide every pending approval in one generate() call.`);let u=[];for(let p of n.approvals){let m=s.get(p.id);!m||await e.resolveApproval(p.id)==="already-resolved"||(o.push(m),u.push({type:"tool-approval-response",approvalId:p.id,approved:p.approved,...p.reason!==void 0?{reason:p.reason}:{}}))}u.length>0&&r.push({role:"tool",content:u})}if(n.prompt!==void 0?r.push({role:"user",content:n.prompt}):n.messages&&r.push(...n.messages),r.length===0)throw new I("agent.generate() requires `prompt`, `messages`, or `approvals` \u2014 nothing to do.");return{turn:r,claimed:o}}function Ui(e){let t=Me(e);dr(e);let n=lr(e),r=Di(t),o=_i(t),s=t.limits?.maxIterations??fr,i=t.limits?.maxToolCalls??mr,a=t.memory?.maxSessionMessages??pr,c=l=>({model:r,system:n,tools:o,stopWhen:l.stopWhen??[ki(s),Oi(i)],...l.prepareStep!==void 0?{prepareStep:l.prepareStep}:{},...l.activeTools!==void 0?{activeTools:l.activeTools}:{},...l.toolChoice!==void 0?{toolChoice:l.toolChoice}:{},...l.providerOptions!==void 0?{providerOptions:l.providerOptions}:{}});return{model:r,tools:o,instructions:n,session(l){return mt(e,l,t.memory)},sessions(l){return Vr(e,t.memory,l)},async generate(l){return F.startActiveSpan("agent.generate",{kind:zt.INTERNAL,attributes:{agent:e,model:t.model}},async u=>{let p=mt(e,l.sessionId,t.memory);u.setAttribute("sessionId",p.id),O("hasAi");let m=[];try{let g=await Bt(p,a),w=await Ni(p,g,l);m=w.claimed;let S;try{S=await Ci({...c(l),messages:[...g,...w.turn]})}catch(f){if(m.length>0)try{await p.addPendingApprovals(m),m=[]}catch(h){console.error(`[helix-sdk] agent "${e}" session "${p.id}": failed to restore ${m.length} pending approval(s) after a failed resume \u2014 ${h instanceof Error?h.message:String(h)}`)}throw f}let x=Gt(S.content),y=x.length>0?"awaiting-approval":"completed";return await p.append(...w.turn,...S.responseMessages),x.length>0&&await p.addPendingApprovals(x.map(Yr)),u.setAttributes({steps:S.steps.length,status:y}),u.setStatus({code:Se.OK}),Object.assign(S,{sessionId:p.id,status:y,...x.length>0?{pendingApprovals:x.map(Mi)}:{},helix:{cost:Li(S.steps,t.model),model:S.response.modelId??t.model}})}catch(g){throw u.setAttribute("status","error"),u.setStatus({code:Se.ERROR,message:g instanceof Error?g.message:String(g)}),g}finally{u.end()}})},async stream(l){let u=F.startSpan("agent.stream",{kind:zt.INTERNAL,attributes:{agent:e,model:t.model}}),p=!1,m=(g,w)=>{p||(p=!0,u.setAttribute("status",g),u.setStatus(g==="error"?{code:Se.ERROR,...w!==void 0?{message:w}:{}}:{code:Se.OK}),u.end())};try{let g=mt(e,l.sessionId,t.memory);if(u.setAttribute("sessionId",g.id),O("hasAi"),l.approvals&&l.approvals.length>0)throw new I("agent.stream() does not accept approvals \u2014 resume paused runs with generate().");if(l.prompt===void 0&&!l.messages)throw new I("agent.stream() requires `prompt` or `messages`.");let w=l.prompt!==void 0?[{role:"user",content:l.prompt}]:[...l.messages],S=await Bt(g,a),x=Jr.with(Pi.setSpan(Jr.active(),u),()=>Ti({...c(l),messages:[...S,...w],onFinish:async y=>{try{await g.append(...w,...y.responseMessages);let f=Gt(y.content);f.length>0&&await g.addPendingApprovals(f.map(Yr)),m(f.length>0?"awaiting-approval":"completed")}catch(f){let h=f instanceof Error?f.message:String(f);console.error(`[helix-sdk] agent "${e}" session "${g.id}": failed to persist the streamed turn \u2014 ${h}`),m("error",h)}},onError:({error:y})=>{m("error",y instanceof Error?y.message:String(y))},onAbort:()=>{m("error","stream aborted")}}));return Object.assign(x,{sessionId:g.id})}catch(g){throw m("error",g instanceof Error?g.message:String(g)),g}}}}var Qr="helix-schedule",Q=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function Vd(e){if(typeof e!="object"||e===null)throw new Q("expected a config object");let{cron:t,timezone:n="UTC",concurrent:r=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new Q("`cron` must be a non-empty string");let s=t.trim().split(/\s+/).length;if(s!==5)throw new Q(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${s} field(s) in "${t}"`);if(typeof n!="string"||!$i(n))throw new Q(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(n)}"`);if(typeof r!="boolean")throw new Q("`concurrent` must be a boolean");if(typeof o!="function")throw new Q("`handler` must be a function");return Object.freeze({kind:Qr,cron:t.trim(),timezone:n,concurrent:r,handler:o})}function zd(e){return typeof e=="object"&&e!==null&&e.kind===Qr&&typeof e.handler=="function"}function $i(e){if(!/^[A-Za-z]/.test(e))return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}import{SpanKind as ji}from"@opentelemetry/api";function gt(e,t,n){let r=F.startSpan("log",{kind:ji.INTERNAL});r.setAttribute("message",t),r.setAttribute("level",e),n&&Hn(r.spanContext().spanId,"properties",n),r.end(),kn(e,t,n)}function Zr(){return{info:(e,t)=>gt("info",e,t),warn:(e,t)=>gt("warn",e,t),error:(e,t)=>gt("error",e,t),debug:(e,t)=>gt("debug",e,t)}}function Zd(){try{return A().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import Bi from"ky";import{context as Jt,trace as Ki,SpanKind as Ue,SpanStatusCode as to}from"@opentelemetry/api";async function eo(e){Sn(e.url);let t=E(),{region:n}=A(),r={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},{headers:o,deploymentId:s}=z(t);s&&(r.deploymentId=s);let i=bn(n,t.mode==="lambda"?"runtime":"dev"),a;try{a=await vn({signUrl:i,credentialHeaders:o,body:r,timeoutMs:e.timeout,executionId:t.executionId})}catch(c){let l=c instanceof Error?c.message??String(c):String(c);throw d.brokerError(0,l)}if(a.kind==="brokerError"){let c=a.code===pe?"credential broker does not support the s3 sign endpoint required by this SDK version \u2014 deploy a newer broker or pin an older SDK":a.message;throw d.brokerError(a.status,c,k(a.body),a.code)}return a.result}var Hi=new Set([Ie,ze,te,Re,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id"]);function qi(e){let t=e.toLowerCase();return Hi.has(t)||t.startsWith("x-tray-internal-")}async function Vi(e,t){let n=e instanceof Request?e:new Request(e,t),r=new URL(n.url);if(r.protocol!=="https:")throw d.unsupportedScheme(r.protocol.replace(/:$/,""));let o=E(),{region:s}=A(),{headers:i,deploymentId:a}=z(o),c=fe(s,o.mode==="lambda"?"runtime":"dev"),l=new Headers;for(let[g,w]of n.headers.entries())qi(g)||l.append(g,w);l.set(Ie,n.url);for(let[g,w]of Object.entries(i))l.set(g,w);a&&l.set(te,a),o.executionId&&l.set(Re,o.executionId);let u={method:n.method,headers:l,redirect:"manual",signal:n.signal};n.body&&(u.body=n.body,u.duplex="half");let p;try{p=await fetch(c,u)}catch(g){throw g instanceof Error&&g.name==="AbortError"?g:d.brokerError(0,g instanceof Error?g.message:String(g))}let m=p.headers.get(Ge);return m!==null&&Vt(await hn(p,m)),p}var zi=["get","post","put","patch","delete","head","options"],ro="[stream body omitted]";function oo(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?ro:e instanceof ArrayBuffer?`[binary body: ${e.byteLength} bytes]`:ArrayBuffer.isView(e)?`[binary body: ${e.byteLength} bytes]`:typeof Blob<"u"&&e instanceof Blob?`[binary body: ${e.size} bytes]`:e}function Wt(e){try{return new URL(e).hostname}catch{return e}}function no(e,t,n,r,o){let s=Wt(t),i="externalApi",a={kind:Ue.CLIENT};return F.startActiveSpan(i,a,async c=>(c.setAttributes({method:e,host:s,"peer.service":r}),q(c,"request",{url:t,method:e,...n!==void 0?{body:oo(n)}:{}}),o(c)))}function Ne(e,t,n){e.setAttribute("status",t),e.setStatus(t==="success"?{code:to.OK}:{code:to.ERROR,message:n}),e.end()}var Gi=16;async function Ji(e,t){let n=e.clone().body;return n?so(n,t):new Uint8Array(0)}async function so(e,t){let n=e.getReader(),r=[],o=0,s=0;try{for(;;){let{done:c,value:l}=await n.read();if(c)break;if(!l||l.byteLength===0){if(s+=1,s>=Gi)break;continue}s=0;let u=t+1-o;if(l.byteLength>=u){r.push(l.slice(0,u)),o+=u;break}r.push(l),o+=l.byteLength}}finally{n.cancel().catch(()=>{}),n.releaseLock()}let i=new Uint8Array(o),a=0;for(let c of r)i.set(c,a),a+=c.byteLength;return i}async function io(e,t,n){if("kyResponse"in n)try{let r=await Ji(n.kyResponse,Te),o=new TextDecoder("utf-8").decode(r,{stream:!0}),s;try{s=JSON.parse(o)}catch{s=o}q(e,"response",s)}catch{q(e,"response",{status:t})}else q(e,"response",oo(n.bodyValue))}async function Wi(e,t){if(t instanceof ReadableStream){let n=e.body??t;try{let[r,o]=n.tee(),s=new Request(e,{body:r,duplex:"half"}),i=await so(o,Te);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:ro}}}return typeof t=="string"?{body:t}:{}}function wu(){let e=Bi.create({fetch:Vi,retry:{shouldRetry:({error:r})=>r instanceof d?!1:void 0}});function t(r){return(o,s)=>{let i=Jt.active(),a,c=!1,l=(p,m)=>{a&&!c&&(c=!0,Ne(a,p,m))},u=e.extend({hooks:{beforeRequest:[async(p,m)=>{let g=await Wi(p,m.body),w=g.body;if(a||(a=F.startSpan("externalApi",{kind:Ue.CLIENT},i)),a.setAttributes({method:p.method.toUpperCase(),host:Wt(p.url)}),q(a,"request",{url:p.url,method:p.method.toUpperCase(),...w!==void 0?{body:w}:{}}),c=!1,O("hasExternal"),g.request)return g.request}],beforeRetry:[p=>{l("error","retry"),a=void 0,c=!1}],afterResponse:[async(p,m,g)=>{a&&(a.setAttribute("statusCode",g.status),await io(a,g.status,{kyResponse:g}),g.ok?l("success"):s?.throwHttpErrors===!1&&(O("hasError"),l("error",`HTTP ${g.status}`)))}],beforeError:[p=>(O("hasError"),l("error",p.message),p)]}});return a=F.startSpan("externalApi",{kind:Ue.CLIENT},i),a.setAttributes({method:r.toUpperCase(),host:Wt(String(o))}),Jt.with(Ki.setSpan(Jt.active(),a),()=>{let p=r==="options"?u(o,{...s,method:"OPTIONS"}):u[r](o,s);return p.catch(m=>{O("hasError"),l("error",m instanceof Error?m.message:String(m))}),p})}}let n=Object.fromEntries(zi.map(r=>[r,t(r)]));return{...e,...n,authed(r){return Xi(r)}}}function Xi(e){let n=A().authentications??{};if(!n[e])throw d.unknownAlias(e,Object.keys(n));let r=n[e];function o(i){return(a,c={})=>{let l=i.toUpperCase();return no(l,a,c.body,e,async u=>{O("hasAuth");let p=F.startSpan("auth",{kind:Ue.INTERNAL});p.setAttribute("alias",e),p.setAttribute("id",r),p.end();try{let m=ne({authenticationId:r,method:l,url:a,body:c.body,headers:c.headers,query:c.query}),g=await we(m,{timeout:c.timeout});return u.setAttribute("statusCode",g.status),await io(u,g.status,{bodyValue:g.body}),Ne(u,"success"),g}catch(m){throw O("hasError"),m instanceof d&&m.detail.kind==="broker_error"&&m.detail.status>0&&u.setAttribute("statusCode",m.detail.status),Ne(u,"error",m instanceof Error?m.message:String(m)),m}})}}function s(i,a={}){let c=a.method??"GET";return no(c,i,void 0,e,async l=>{O("hasAuth");let u=F.startSpan("auth",{kind:Ue.INTERNAL});u.setAttribute("alias",e),u.setAttribute("id",r),u.end();try{let p=await eo({authenticationId:r,url:i,method:c,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return l.setAttribute("statusCode",200),Ne(l,"success"),p}catch(p){throw O("hasError"),p instanceof d&&p.detail.kind==="broker_error"&&p.detail.status>0&&l.setAttribute("statusCode",p.detail.status),Ne(l,"error",p instanceof Error?p.message:String(p)),p}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:s}}import{SpanKind as sa,SpanStatusCode as uo}from"@opentelemetry/api";function $e(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Yi=18e4,ao=Yi-1e4,Qi=2e3;async function co(e,t,n){let r=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<ao;){let i=await e(t,"DescribeStatement",{Id:n}),a=i.Status;if(r.has(a))return i;let c=Math.min(Qi,200*2**s),l=c/2+Math.random()*(c/2),u=ao-(Date.now()-o);await new Promise(p=>setTimeout(p,Math.min(l,u))),s++}throw d.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Zi=new Set(["SELECT","WITH","SHOW"]),ea=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function ta(e){if(!e.clusterIdentifier&&!e.workgroupName)throw d.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw d.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw d.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw d.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw d.dbInvalidParameters("region is required")}function na(e,t){let n=null;if(typeof t=="string")try{n=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(n=t);let r=typeof n?.__type=="string"?n.__type:void 0,o=typeof n?.message=="string"?n.message:void 0;if(r&&o)return d.dbQueryFailed(`${r}: ${o}`);let s=typeof t=="string"?re(t):k(t);return d.dbCallFailed(s)}function ra(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw d.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function oa(e,t){return typeof t!="number"||t<0?{}:Zi.has(e)?{rowsRead:t}:ea.has(e)?{rowsWritten:t}:{}}function lo(e){async function t(n,r,o){let s=ne({authenticationId:e,method:"POST",url:`https://redshift-data.${n}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${r}`}});try{let{status:i,body:a}=await we(s);if(i>=400)throw na(i,a);return ra(a)}catch(i){if(i instanceof d)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw d.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:ta,async execute(n,r){let o=$e(r),s={Sql:r,Database:n.database,...n.clusterIdentifier&&{ClusterIdentifier:n.clusterIdentifier,DbUser:n.dbUser},...n.workgroupName&&{WorkgroupName:n.workgroupName},...n.statementName&&{StatementName:n.statementName}},i=await t(n.region,"ExecuteStatement",s),a=i,c=typeof a?.Id=="string"?a.Id:void 0;if(!c){let g=k(i);throw d.dbCallFailed(`ExecuteStatement response missing Id; got: ${g}`)}let l=await co(t,n.region,c),u=l.Status;if(u==="FAILED"){let g=typeof l.Error=="string"?l.Error:"statement failed";throw d.dbQueryFailed(`${g} (statement: ${c})`)}if(u==="ABORTED")throw d.dbQueryFailed(`statement aborted (statement: ${c})`);let p=oa(o,l.ResultRows);return l.HasResultSet===!1?{result:{rowsAffected:l.ResultRows??0},metadata:p}:{result:await t(n.region,"GetStatementResult",{Id:c}),metadata:p}}}}var Xt=64*1024;function ia(e){return e.length>Xt?`${e.slice(0,Xt)}...[truncated]`:e}function aa(e,t,n,r,o){e.setAttributes({system:t.system,statement:o,namespace:n.database,operation:r})}function ca(e,t,n){let r=typeof t=="string"?t:JSON.stringify(t);return r.length>Xt?q(e,"result",{truncated:!0,size:r.length}):q(e,"result",t),n.rowsRead!==void 0&&e.setAttribute("rowsRead",n.rowsRead),n.rowsWritten!==void 0&&e.setAttribute("rowsWritten",n.rowsWritten),r}async function la(e,t,n){let r=$e(n),o=ia(n);return F.startActiveSpan("database",{kind:sa.CLIENT},async s=>{aa(s,e,t,r,o);try{O("hasDb");let{result:i,metadata:a}=await e.execute(t,n),c=ca(s,i,a);return s.setAttribute("status","success"),s.setStatus({code:uo.OK}),c}catch(i){O("hasError");let a=i instanceof Error?i.message:String(i);throw s.setAttribute("status","error"),s.setStatus({code:uo.ERROR,message:a}),i}finally{s.end()}})}function da(e){let n=A().authentications??{};if(!n[e])throw d.unknownAlias(e,Object.keys(n));let r=n[e],o=lo(r);function s(i,a){return o.validate(i),la(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as ga}from"unstorage";var po=1024,Yt=250*1024,ua=new TextEncoder,pa=/(^|\/)\.\.(\/|$)/,fa=/[?#]/,ma=/[\u0000-\u001F\u007F]/;function fo(e){if(e.length===0)throw d.kvKeyInvalid("Key must be a non-empty string");if(pa.test(e))throw d.kvKeyInvalid("Key contains path traversal segment");if(fa.test(e)||ma.test(e))throw d.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(n=>n===""))throw d.kvKeyInvalid("Key must not contain empty path segments");let t=ua.encode(e).length;if(t<1||t>po)throw d.kvKeyInvalid(`Key must be between 1 and ${po} UTF-8 bytes (got ${t})`)}function mo(e){if(!Number.isInteger(e)||e<=0)throw d.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function go(e){let t;try{t=JSON.stringify(e)}catch{throw d.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw d.kvValueInvalid("Value must be JSON-serializable");let n=Buffer.byteLength(t,"utf8");if(n>Yt)throw d.kvValueTooLarge(`Value exceeds maximum size of ${Yt} bytes (got ${n})`,Yt)}function je(e){fo(e)}function yt(e,t){let n=e[t];if(typeof n!="function")throw new Error(`KV driver is missing ${t}`);return n}function yo(e){let t=yt(e,"getItem"),n=yt(e,"setItem"),r=yt(e,"removeItem"),o=yt(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return je(i),t(i,a)},setItem(i,a,c){return je(i),n(i,a,c)},removeItem(i,a){return je(i),r(i,a)},hasItem(i,a){return je(i),o(i,a)},getKeys(i,a){return i.length>0&&je(i),s(i,a)}}}function ht(e){return ga({driver:yo(e)})}import{defineDriver as ya}from"unstorage";function ha(e){try{return JSON.parse(e)}catch{return e}}var wa=ya(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(n){let r=await t.get(n);return r===null?null:JSON.stringify(r)},async setItem(n,r,o){let s=o?.ttl,i=ha(r);s!==void 0?await t.set(n,i,{ttl:s}):await t.set(n,i)},async removeItem(n){await t.delete(n)},async hasItem(n){return await t.has(n)},async getKeys(){throw new Error("KV key listing is not supported")}}});function ho(e){return wa({client:e})}import va from"ky";import{z as M}from"zod";function wo(e){return j(e).hosts.api}function Sa(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function ba(e){return e.split("/").map(encodeURIComponent).join("/")}function Be(e,t,n){return`${e}${Sa(t)}/${ba(n)}`}var xa=6e4,Qt=M.lazy(()=>M.union([M.string(),M.number(),M.boolean(),M.null(),M.array(Qt),M.record(Qt)])),Aa=M.object({projectId:M.string(),key:M.string(),value:Qt,type:M.enum(["string","number","boolean","null","array","object"]),organizationId:M.string(),scope:M.string(),createdBy:M.string(),createdAt:M.number(),updatedBy:M.string(),updatedAt:M.number()});function Ea(){let e=ue(),t=$(),n=!!(e&&e.trim().length>0),r=!!(t&&t.trim().length>0);if(!n&&!r)throw d.missingExecutionCredentials();let o={Accept:"application/json"};return n&&(o[de]=e),r&&(o[U]=t),o}function Ia(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function wt(e,t){throw d.kvCallFailed(e,Ia(t),k(t))}async function St(e,t,n={}){try{let r=await va(t,{method:e,headers:Ea(),...n.json!==void 0?{json:n.json}:{},throwHttpErrors:!1,timeout:xa}),o=e==="head"?void 0:await K(r);return{status:r.status,body:o}}catch(r){if(r instanceof d)throw r;let o=r instanceof Error?r.message??String(r):String(r);throw d.kvCallFailed(0,o)}}function So(e){let t=wo(e.env),{projectId:n}=e;return{async get(r){let{status:o,body:s}=await St("get",Be(t,n,r));if(o===404)return null;(o<200||o>=300)&&wt(o,s);let i=Aa.safeParse(s);if(!i.success)throw d.kvCallFailed(o,"platform returned malformed KeyValueEntry",k(s));return i.data.value},async set(r,o,s){let{status:i,body:a}=await St("put",Be(t,n,r),{json:s?.ttl!==void 0?{value:o,ttl:s.ttl}:{value:o}});(i<200||i>=300)&&wt(i,a)},async delete(r){let{status:o,body:s}=await St("delete",Be(t,n,r));o!==204&&wt(o,s)},async has(r){let{status:o,body:s}=await St("head",Be(t,n,r));if(o===200)return!0;if(o===404)return!1;wt(o,s)}}}function bt(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,n,r)=>{let o=r?.ttl;go(n),typeof o=="number"&&mo(o),await e.setItem(t,n,o!==void 0?{ttl:o}:void 0)}}}function Ra(){let e=A();if(e.kind!=="provisioned")throw d.kvRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function bo(e){let t=Ra(),n=e??So(t),r=ht(ho(n));return bt(r)}import{defineDriver as Ca}from"unstorage";var Ta=Ca(e=>{let t=new Map;function n(r){let o=t.get(r);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(r);return}return o}return{name:"memory-ttl",getItem(r){return n(r)?.value??null},setItem(r,o,s){let i=s?.ttl,a=n(r),c=typeof i=="number"?Date.now()+i*1e3:i===null?void 0:a?.expiresAt;t.set(r,{value:o,expiresAt:c})},removeItem(r){t.delete(r)},hasItem(r){return n(r)!==void 0},getKeys(){return[...t.keys()].filter(r=>n(r)!==void 0)},clear(){t.clear()}}});function vo(){return Ta({})}var Zt;function ka(){return Zt||(Zt=ht(vo())),Zt}function xo(){return bt(ka())}function Pa(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":E().mode==="lambda"}function xp(){return Pa()?bo():xo()}import{createHash as Da}from"crypto";import{mkdir as Ma,readFile as Co,readdir as To,rm as Eo,unlink as Fa,writeFile as Io}from"fs/promises";import{dirname as La}from"path";async function Oa(e){let t=e.getReader(),n=[],r=0;for(;;){let{done:o,value:s}=await t.read();if(o)break;if(s){if(r+=s.byteLength,r>G)throw await t.cancel(),d.filesValueTooLarge(`File exceeds maximum size of ${G} bytes (got more than ${G})`,G);n.push(s)}}return Buffer.concat(n)}async function be(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?Oa(e):Buffer.from(e)}var _a={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},Ao="application/octet-stream";function vt(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return Ao;let n=e.slice(t+1).toLowerCase();return _a[n]??Ao}function xe(){let e=E().projectRoot;if(!e)throw d.filesNotAvailable();return e}async function ve(e){try{return await e()}catch(t){if(t instanceof d)throw t;let n=t?.code;throw n?d.filesCallFailed(0,`Local file storage operation failed: ${n}`):d.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function xt(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function en(e){try{let t=await Co(nt(xe(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Ro(e){await Ma(La(e),{recursive:!0})}async function Na(e,t){let n=rt(e,t),r;try{r=await To(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function ko(e,t){let n=rt(e,t),r;try{r=await To(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return[];throw s}let o=[];for(let s of r){let i=t.length===0?s.name:`${t}/${s.name}`;s.isDirectory()?o.push(...await ko(e,i)):s.isFile()&&o.push(i)}return o}function Po(){return{async put(e,t,n){return ve(async()=>{let r=xe(),o=await be(t),s=n?.contentType??vt(e),i=Da("sha1").update(o).digest("hex"),a=new Date,c=De(r,e);await Ro(c),await Io(c,o);let l={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},u=nt(r,e);return await Ro(u),await Io(u,JSON.stringify(l)),xt(e,l)})},async get(e){return ve(async()=>{let t=await en(e);return t?{data:await Co(De(xe(),e)),metadata:xt(e,t)}:null})},async head(e){return ve(async()=>{let t=await en(e);return t?xt(e,t):null})},async delete(e){return ve(async()=>{let t=xe();await Promise.all([De(t,e),nt(t,e)].map(async n=>{try{await Fa(n)}catch(r){if(r.code!=="ENOENT")throw r}}))})},async deleteMany(e){return ve(async()=>{let t=xe(),n=await ko(t,e);return await Promise.all([Eo(rt(t,e),{recursive:!0,force:!0}),Eo(Xn(t,e),{recursive:!0,force:!0})]),{deleted:n.length}})},async list(e,t){return ve(async()=>{let n=xe(),r=t?.limit??100,s=(await Na(n,e??"")).slice(0,r);return{files:(await Promise.all(s.map(async a=>{let c=await en(a);return c?xt(a,c):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let n=E().devServerUrl;if(!n)throw d.filesNotAvailable();return{url:`${n}/_helix/files/${e}`,expiresAt:ge(t?.expiresIn)}},async getDownloadUrl(e,t){let n=E().devServerUrl;if(!n)throw d.filesNotAvailable();return{url:`${n}/_helix/files/${e}`,expiresAt:ge(t?.expiresIn)}}}}import{createHash as qa}from"crypto";function At(e){return j(e).hosts.api}function Ua(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function Ke(e,t){return`${e}${Ua(t)}`}function Ae(e,t,n){return`${Ke(e,t)}/${encodeURIComponent(n)}`}function Et(e,t,n){return`${Ae(e,t,n)}/upload`}function Oo(e,t,n){return`${Ae(e,t,n)}/download`}function _o(e,t,n){return`${Ae(e,t,n)}/signed-url`}function Do(e,t,n,r){let o=new URLSearchParams({name:r});return n&&o.set("parentFolder",n),`${Ke(e,t)}/file?${o.toString()}`}function Mo(e,t,n,r){let o=new URLSearchParams({limit:String(r)});return n&&o.set("id",n),`${Ke(e,t)}?${o.toString()}`}import nn from"ky";import{z as _}from"zod";var rn=6e4,Fo=_.object({id:_.string(),workspaceId:_.string(),projectId:_.string(),parentFolder:_.string().nullable().optional(),name:_.string(),size:_.number().nullable().optional(),objectType:_.enum(["Folder","File"]),contentType:_.string().nullable().optional(),createdAt:_.string(),updatedAt:_.string()}),$a=_.object({signedURL:_.string()}),ja=_.object({path:_.array(_.object({id:_.string(),name:_.string()})),elements:_.array(Fo)});function on(){let e=ue(),t=$(),n=!!(e&&e.trim().length>0),r=!!(t&&t.trim().length>0);if(!n&&!r)throw d.missingExecutionCredentials();let o={Accept:"application/json"};return n&&(o[de]=e),r&&(o[U]=t),o}function Lo(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Z(e,t){throw d.filesCallFailed(e,Lo(t),k(t))}function Ba(e,t){return e===400&&Lo(t).toLowerCase()==="resource not found"}async function Ka(e){let t=new Response(e),n=t.headers.get("content-type")??"multipart/form-data",r=await t.arrayBuffer();return{body:Buffer.from(r),contentType:n}}async function Ee(e,t,n={}){try{let r=await nn(t,{method:e,headers:on(),...n.json!==void 0?{json:n.json}:{},throwHttpErrors:!1,timeout:rn}),o=await K(r);return{status:r.status,body:o}}catch(r){if(r instanceof d)throw r;let o=r instanceof Error?r.message:String(r);throw d.filesCallFailed(0,o)}}function tn(e,t){let n=Fo.safeParse(t);if(!n.success)throw d.filesCallFailed(e,"platform returned malformed ObjectMetadata",k(t));return n.data}function No(e){let t=At(e.env),{projectId:n}=e;return{async createMetadata(r){let{status:o,body:s}=await Ee("post",Ke(t,n),{json:r});return(o<200||o>=300)&&Z(o,s),tn(o,s)},async getByName(r,o){let{status:s,body:i}=await Ee("get",Do(t,n,r,o));return s===404||Ba(s,i)?null:((s<200||s>=300)&&Z(s,i),tn(s,i))},async getById(r){let{status:o,body:s}=await Ee("get",Ae(t,n,r));return o===404?null:((o<200||o>=300)&&Z(o,s),tn(o,s))},async listChildren(r,o){let{status:s,body:i}=await Ee("get",Mo(t,n,r,o));(s<200||s>=300)&&Z(s,i);let a=ja.safeParse(i);if(!a.success)throw d.filesCallFailed(s,"platform returned malformed listing",k(i));return a.data},async uploadContent(r,o,s,i){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:i}),s);let{body:c,contentType:l}=await Ka(a),u;try{u=await nn(Et(t,n,r),{method:"post",headers:{...on(),"content-type":l},body:new Uint8Array(c),throwHttpErrors:!1,timeout:rn})}catch(m){if(m instanceof d)throw m;let g=m instanceof Error?m.message:String(m);throw d.filesCallFailed(0,g)}let p=await K(u);(u.status<200||u.status>=300)&&Z(u.status,p)},async downloadContent(r){let o;try{o=await nn(Oo(t,n,r),{method:"get",headers:on(),throwHttpErrors:!1,timeout:rn})}catch(i){if(i instanceof d)throw i;let a=i instanceof Error?i.message:String(i);throw d.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await K(o);Z(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(r){let{status:o,body:s}=await Ee("get",_o(t,n,r));(o<200||o>=300)&&Z(o,s);let i=$a.safeParse(s);if(!i.success)throw d.filesCallFailed(o,"platform returned malformed signed URL response",k(s));return i.data.signedURL},async deleteById(r){let{status:o,body:s}=await Ee("delete",Ae(t,n,r));o===204||o===404||(o<200||o>=300)&&Z(o,s)}}}function sn(e){return e.split("/").filter(t=>t.length>0)}function an(e){return e instanceof d&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Ha(e,t,n){let r=await e.getByName(t,n);if(r)return r;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:n})}catch(o){if(an(o)){let s=await e.getByName(t,n);if(s)return s}throw o}}async function cn(e,t){let n=sn(t),r=n[n.length-1],o;for(let s of n.slice(0,-1))o=(await Ha(e,o,s)).id;return{parentFolder:o,name:r}}async function He(e,t){let n=sn(t),r=n[n.length-1],o;for(let s of n.slice(0,-1)){let i=await e.getByName(o,s);if(!i||i.objectType!=="Folder")return null;o=i.id}return{parentFolder:o,name:r}}async function ln(e,t){if(t.length===0)return;let n=sn(t),r;for(let o of n){let s=await e.getByName(r,o);if(!s||s.objectType!=="Folder")return null;r=s.id}return r}var Va=500,za=8;async function Ga(e,t,n){let r=new Array(e.length),o=0;async function s(){for(;o<e.length;){let i=o++;r[i]=await n(e[i])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},s)),r}function Ja(){let e=A();if(e.kind!=="provisioned")throw d.filesRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function Wa(e){return qa("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function It(e,t,n){return{path:e,size:t.size??0,contentType:t.contentType??n??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Wa(t)}}async function Uo(e,t,n,r){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:r,name:n})}catch(o){if(an(o)){let s=await e.getByName(t,n);if(s)return s}throw o}}async function $o(e,t){let{elements:n}=await e.listChildren(t,Va);return(await Ga(n,za,async o=>{let s=o.objectType==="Folder"?await $o(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function jo(e){let t=Ja(),n=e??No(t),r=At(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:c,name:l}=await cn(n,s),u=await be(i),p=a?.contentType??vt(s),m=await n.getByName(c,l);if(m&&m.objectType!=="File")throw d.filesCallFailed(409,`A folder already exists at "${s}"`);let g=m??await Uo(n,c,l,p);await n.uploadContent(g.id,u,l,p);let w=await n.getById(g.id);return It(s,w??g,p)},async get(s){let i=await He(n,s);if(!i)return null;let a=await n.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:{data:await n.downloadContent(a.id),metadata:It(s,a)}},async head(s){let i=await He(n,s);if(!i)return null;let a=await n.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:It(s,a)},async delete(s){let i=await He(n,s);if(!i)return;let a=await n.getByName(i.parentFolder,i.name);a&&await n.deleteById(a.id)},async deleteMany(s){let i=await ln(n,s);if(i===null)return{deleted:0};let a=await $o(n,i);return s.length>0&&i!==void 0&&await n.deleteById(i),{deleted:a}},async list(s,i){let a=await ln(n,s??"");if(a===null)return{files:[],cursor:null};let c=i?.limit??100,{elements:l}=await n.listChildren(a,c);return{files:l.filter(p=>p.objectType==="File").map(p=>It(s?`${s}/${p.name}`:p.name,p)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:c}=await cn(n,s),u=await n.getByName(a,c)??await Uo(n,a,c,i?.contentType);return{url:Et(r,o,u.id),expiresAt:ge(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await He(n,s),c=a?await n.getByName(a.parentFolder,a.name):null;if(!c||c.objectType!=="File")throw d.filesCallFailed(404,`File not found: ${s}`);return{url:await n.getSignedDownloadUrl(c.id),expiresAt:ge(i?.expiresIn)}}}}function dn(e,t){let n=t?.maxPathBytes;return{async put(r,o,s){ie(r,n);let i=await be(o);return Jn(i.byteLength),e.put(r,i,s)},async get(r){return ie(r,n),e.get(r)},async head(r){return ie(r,n),e.head(r)},async delete(r){return ie(r,n),e.delete(r)},async deleteMany(r){let o=Mt(r);return et(o,n),e.deleteMany(o)},async list(r,o){let s=Mt(r??"");return et(s,n),e.list(s,o)},async getUploadUrl(r,o){return ie(r,n),e.getUploadUrl(r,o)},async getDownloadUrl(r,o){return ie(r,n),e.getDownloadUrl(r,o)}}}function Xa(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":E().mode==="lambda"}function gf(){if(Xa())return dn(jo());let e=E().projectRoot;return dn(Po(),{maxPathBytes:e?Wn(e):void 0})}import Qa from"ky";function Bo(e){return j(e).hosts.api}function Ya(){return"/private/v1/helix/function-calls"}function Ko(e){return`${e}${Ya()}`}var Za=5e3;function ec(){let e=$();if(!!!(e&&e.trim().length>0))throw d.callFunctionMissingExecutionJwt();return{Accept:"application/json",[U]:e}}function tc(e,t){throw d.callFunctionCallFailed(e,nc(t),k(t))}function nc(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Ho(e){let t=Bo(e.env);return{async callAsync(n,r){let o,s;try{let i=await Qa(Ko(t),{method:"post",headers:ec(),json:{functionPath:n,input:r},throwHttpErrors:!1,timeout:Za});o=i.status,s=await K(i)}catch(i){if(i instanceof d)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw d.callFunctionCallFailed(0,a)}(o<200||o>=300)&&tc(o,s)}}}var qo=1024;function Rt(e){if(typeof e!="string"||e.trim().length===0)throw d.callFunctionPathInvalid("functionPath must be a non-empty string");if(e.length>qo)throw d.callFunctionPathInvalid(`functionPath must be at most ${qo} characters`)}function rc(){let e=A();if(e.kind!=="provisioned")throw d.callFunctionRequiresProvisioning();return{env:e.region}}function Vo(e){return async function(n,r){Rt(n),await(e??Ho(rc())).callAsync(n,r)}}function zo(){return async function(t,n){Rt(t);let r=E().devServerUrl;if(!r)throw d.callFunctionNotAvailable();let o=t.startsWith("/")?t:`/${t}`,s=Zr();fetch(`${r}${o}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n??{})}).then(i=>{i.ok||s.warn("ctx.callFunctionAsync: dev-mode dispatch returned a non-2xx response",{functionPath:t,status:i.status})}).catch(i=>{s.warn("ctx.callFunctionAsync: dev-mode dispatch failed",{functionPath:t,error:i instanceof Error?i.message:String(i)})})}}function oc(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":E().mode==="lambda"}function Bf(){return oc()?Vo():zo()}export{sc as a,ic as b,ac as c,A as d,cc as e,Kn as f,gs as g,O as h,q as i,bs as j,vs as k,F as l,xs as m,Lc as n,Zr as o,Zd as p,wu as q,da as r,xp as s,ie as t,De as u,nt as v,gf as w,Bf as x,qc as y,Ft as z,Zn as A,er as B,tr as C,st as D,nr as E,Zc as F,sr as G,Lt as H,Us as I,Bs as J,Ks as K,el as L,Hs as M,tl as N,Xl as O,ir as P,sl as Q,ar as R,I as S,ul as T,pl as U,Me as V,fl as W,ml as X,ur as Y,Sl as Z,bl as _,X as $,Al as aa,Oi as ba,Ui as ca,Qr as da,Q as ea,Vd as fa,zd as ga};
@@ -0,0 +1 @@
1
+ var b="X-Helix-Project-Execution-Token",R="X-Tray-Token",q={mode:"dev",deploymentId:null},k={...q},p={};function te(e){let{internalJwt:r,helixExecutionJwt:t,devToken:n,...i}=e;"internalJwt"in e&&(p.internalJwt=r),"helixExecutionJwt"in e&&(p.helixExecutionJwt=t),"devToken"in e&&(p.devToken=n),k={...k,...i}}function ne(){return k}function S(){return p.internalJwt}function P(){return p.helixExecutionJwt}function I(){return p.devToken}var O=new Set(["us1","eu1","ap1","ap2"]),s=new Map,h={name:"us1",exposedName:"us1",displayName:"us1",hosts:{api:"https://api.tray.io",broker:"https://api.tray.io/private/v1/code",ingest:"https://api.tray.io/private/v1/helix/otlp",weaver:"https://weaver.tray.io",app:"https://app.tray.io",projectHost:"helix-app.ai",dashboard:"https://app.helix.tray.ai",auth:"https://auth.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}},v={name:"eu1",exposedName:"eu1",displayName:"eu1",hosts:{api:"https://api.eu1.tray.io",broker:"https://api.eu1.tray.io/private/v1/code",ingest:"https://api.eu1.tray.io/private/v1/helix/otlp",weaver:"https://weaver.eu1.tray.io",app:"https://app.eu1.tray.io",projectHost:"eu1.helix-app.ai",dashboard:"https://app.helix.eu1.tray.ai",auth:"https://auth.eu1.tray.io"},login:{storePrefix:"EU1",appUrl:"https://app.eu1.tray.io",cookieName:"prod_tray_lid_eu",cookieDomain:"tray.io"}},x={name:"ap1",exposedName:"ap1",displayName:"ap1",hosts:{api:"https://api.ap1.tray.io",broker:"https://api.ap1.tray.io/private/v1/code",ingest:"https://api.ap1.tray.io/private/v1/helix/otlp",weaver:"https://weaver.ap1.tray.io",app:"https://app.ap1.tray.io",projectHost:"ap1.helix-app.ai",dashboard:"https://app.helix.ap1.tray.ai",auth:"https://auth.ap1.tray.io"},login:{storePrefix:"AP1",appUrl:"https://app.ap1.tray.io",cookieName:"prod_tray_lid_ap",cookieDomain:"tray.io"}},E={name:"ap2",exposedName:"ap2",displayName:"ap2",hosts:{api:"https://api.ap2.tray.io",broker:"https://api.ap2.tray.io/private/v1/code",ingest:"https://api.ap2.tray.io/private/v1/helix/otlp",weaver:"https://weaver.ap2.tray.io",app:"https://app.ap2.tray.io",projectHost:"ap2.helix-app.ai",dashboard:"https://app.helix.ap2.tray.ai",auth:"https://auth.ap2.tray.io"},login:{storePrefix:"AP2",appUrl:"https://app.ap2.tray.io",cookieName:"prod_tray_lid_ap2",cookieDomain:"tray.io"}};s.set(h.name,h);s.set(v.name,v);s.set(x.name,x);s.set(E.name,E);var T=["api","broker","ingest","weaver","app","projectHost","dashboard"],N=["auth"],D=["storePrefix","appUrl","cookieName","cookieDomain"];function C(e){if(!e.name||typeof e.name!="string")throw new Error("RegionProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("RegionProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("RegionProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("RegionProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("RegionProfile.login must be an object");for(let r of T)if(typeof e.hosts[r]!="string"||!e.hosts[r])throw new Error(`RegionProfile.hosts.${r} must be a non-empty string`);for(let r of N){let t=e.hosts[r];if(t!==void 0&&(typeof t!="string"||!t))throw new Error(`RegionProfile.hosts.${r} must be a non-empty string when set`)}for(let r of D)if(typeof e.login[r]!="string"||!e.login[r])throw new Error(`RegionProfile.login.${r} must be a non-empty string`)}function j(e,r){return e.name===r.name&&e.exposedName===r.exposedName&&e.displayName===r.displayName&&T.every(t=>e.hosts[t]===r.hosts[t])&&N.every(t=>e.hosts[t]===r.hosts[t])&&D.every(t=>e.login[t]===r.login[t])}function oe(e){C(e);let r=s.get(e.name);if(r){if(j(r,e))return;throw new Error(`RegionProfile.name "${e.name}" is already registered with different values`)}for(let t of s.values())if(t.exposedName===e.exposedName)throw new Error(`RegionProfile.exposedName "${e.exposedName}" is already used by "${t.name}"`);s.set(e.name,e)}function H(e){return s.has(e)}function se(e){return s.get(e)}function m(e){let r=s.get(e);if(!r)throw new Error(`Unknown region: ${e}`);return r}function ae(){return[...s.keys()]}function de(){return[...s.values()].map(e=>e.exposedName)}function F(e){for(let r of s.values())if(r.exposedName===e)return r.name}var f=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function B(e){let r=globalThis;if(e===void 0||e.trim()===""){delete r[f];return}let t=e.trim(),n=F(t);if(n){r[f]=n;return}if(H(t)){r[f]=t;return}throw new Error(`Unknown region: ${t}`)}function le(){return globalThis[f]}function ue(){return[...s.values()].filter(e=>!O.has(e.name))}function ce(){B(void 0),s.clear();for(let e of[h,v,x,E])s.set(e.name,{...e,hosts:{...e.hosts},login:{...e.login}})}var u=class e extends Error{detail;constructor(r){super(L(r)),this.name="SdkError",this.detail=r}get kind(){return this.detail.kind}static unknownAlias(r,t){return new e({kind:"unknown_alias",alias:r,available:t})}static inputValidationFailed(r){return new e({kind:"input_validation_failed",fields:r})}static outputValidationFailed(r){return new e({kind:"output_validation_failed",fields:r})}static configLoadFailed(r){return new e({kind:"config_load_failed",cause:r})}static brokerError(r,t,n,i){return new e({kind:"broker_error",status:r,message:t,body:n,code:i})}static unsupportedBodyType(r){return new e({kind:"unsupported_body_type",actualType:r})}static unsupportedScheme(r){return new e({kind:"unsupported_scheme",scheme:r})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(r,t){return new e({kind:"db_call_failed",message:r,cause:t})}static dbQueryFailed(r){return new e({kind:"db_query_failed",message:r})}static dbInvalidParameters(r){return new e({kind:"db_invalid_parameters",message:r})}static kvKeyInvalid(r){return new e({kind:"kv_key_invalid",message:r})}static kvValueInvalid(r){return new e({kind:"kv_value_invalid",message:r})}static kvValueTooLarge(r,t){return new e({kind:"kv_value_too_large",message:r,maxBytes:t})}static kvTtlInvalid(r){return new e({kind:"kv_ttl_invalid",message:r})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(r,t,n){return new e({kind:"kv_call_failed",status:r,message:t,body:n})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(r){return new e({kind:"files_path_invalid",message:r})}static filesValueInvalid(r){return new e({kind:"files_value_invalid",message:r})}static filesValueTooLarge(r,t){return new e({kind:"files_value_too_large",message:r,maxBytes:t})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(r,t,n){return new e({kind:"files_call_failed",status:r,message:t,body:n})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}static callFunctionPathInvalid(r){return new e({kind:"call_function_path_invalid",message:r})}static callFunctionCallFailed(r,t,n){return new e({kind:"call_function_call_failed",status:r,message:t,body:n})}static callFunctionRequiresProvisioning(){return new e({kind:"call_function_requires_provisioning"})}static callFunctionNotAvailable(){return new e({kind:"call_function_not_available"})}static callFunctionMissingExecutionJwt(){return new e({kind:"call_function_missing_execution_jwt"})}static aiUnsupportedService(r,t,n){return new e({kind:"ai_unsupported_service",alias:r,service:t,supported:n})}static aiModelIdRequired(r,t){return new e({kind:"ai_model_id_required",alias:r,operation:t})}static aiModelInstanceRequired(r){return new e({kind:"ai_model_instance_required",modelId:r})}static aiProviderNotConfigured(r,t){return new e({kind:"ai_provider_not_configured",alias:r,supported:t})}static aiProviderMisconfigured(r,t,n){return new e({kind:"ai_provider_misconfigured",alias:r,service:t,message:n})}static aiForeignModelRejected(){return new e({kind:"ai_foreign_model_rejected"})}static agentSessionsFailed(r){return new e({kind:"agent_sessions_failed",message:r})}};function ge(e){return e instanceof u}function L(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return e.code?`broker error: ${e.status} ${e.code}: ${e.message}`:`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_ttl_invalid":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)";case"call_function_path_invalid":return`Invalid function path: ${e.message}`;case"call_function_call_failed":return`Async function call failed: ${e.status} ${e.message}`;case"call_function_requires_provisioning":return"callFunctionAsync requires a provisioned project (run helix project set)";case"call_function_not_available":return"callFunctionAsync is not available: no running dev server was found";case"call_function_missing_execution_jwt":return"ctx.callFunctionAsync requires a helix project-execution JWT \u2014 a legacy internalJwt-only execution cannot call it";case"ai_unsupported_service":return`Authentication alias "${e.alias}" resolves to service "${e.service}", which ctx.ai does not support. Supported AI services: ${e.supported.join(", ")}`;case"ai_model_id_required":return`ctx.ai("${e.alias}").${e.operation} requires \`model\` as a string model id. To pass a model instance, use the top-level ctx.ai.${e.operation} instead.`;case"ai_model_instance_required":return`ctx.ai.* call functions require a model instance from ctx.ai(alias), got the string "${e.modelId}". Bare model ids would route outside the credentials broker and are not supported.`;case"ai_provider_not_configured":return`No AI provider configured for authentication alias "${e.alias}". Add \`aiProviders: { "${e.alias}": "<service>" }\` to helix.config.ts (supported services: ${e.supported.join(", ")}; bedrock needs the object form with region, openai-compatible the object form with baseUrl).`;case"ai_provider_misconfigured":return`aiProviders entry for authentication alias "${e.alias}" (service "${e.service}") is incomplete: ${e.message}`;case"ai_foreign_model_rejected":return"ctx.ai.* call functions require a model instance minted by ctx.ai(alias). A model built directly against a raw @ai-sdk/* provider carries its own transport and credentials, and would bypass the credentials broker, proxy policy, and metering.";case"agent_sessions_failed":return`Agent session store error: ${e.message}`}}import{z as g}from"zod";var A="x-helix-destination-url",U="x-helix-authentication-id",J="x-helix-deployment-id",_="x-execution-id",M="x-helix-broker-error",he="route_not_found",K=new Set([A,U,J,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id",_]);function V(e){let r=e.toLowerCase();return K.has(r)||r.startsWith("x-tray-internal-")}var w=g.object({error:g.object({code:g.string(),message:g.string(),issues:g.array(g.unknown()).optional()})});function ve(e,r){let t=`${m(e).hosts.api}/private/v1/helix/broker/http/raw`;return r==="dev"?`${t}/dev`:t}function xe(e){if(e.mode==="lambda"){let t=S(),n=P(),i=!!(t&&t.trim().length>0),o=!!(n&&n.trim().length>0);if(!i&&!o)throw u.missingExecutionCredentials();let a={};return i&&(a[R]=t),o&&(a[b]=n),{headers:a,deploymentId:e.deploymentId??null}}let r=I();if(!r)throw u.missingTrayToken();return{headers:{Authorization:`Bearer ${r}`},deploymentId:null}}function G(e){return typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream}function Ee(e){let r=new URL(e.url);if(r.protocol!=="https:")throw u.unsupportedScheme(r.protocol.replace(/:$/,""));if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[l,d]of e.query.entries())r.searchParams.append(l,d);else for(let[l,d]of Object.entries(e.query))for(let $ of Array.isArray(d)?d:[d])r.searchParams.append(l,$);let t;e.headers===void 0?t=[]:e.headers instanceof Headers?t=Array.from(e.headers.entries()):Array.isArray(e.headers)?t=e.headers:t=Object.entries(e.headers);let n=t.filter(([l])=>!V(l)),i=e.body!==void 0&&e.body!==null,o,a,c=!1;return i&&(G(e.body)?(o=e.body,c=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(o=JSON.stringify(e.body),n.some(([d])=>d.toLowerCase()==="content-type")||(a="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:r.toString(),headers:n,body:o,isStreamBody:c,defaultContentType:a}}async function X(e,r){let t=await e.text(),n=t,i=t||r;try{n=JSON.parse(t);let o=w.safeParse(n);o.success&&(i=o.data.error.message)}catch{}return{status:e.status,code:r,message:i,body:n}}var Y=6e4;function z(e){return e.includes("json")}function W(e){return e.startsWith("text/")||e.includes("xml")||e.includes("urlencoded")||e.includes("javascript")||e.includes("ecmascript")}function Q(e,r){if(e.byteLength===0)return;let t=r.toLowerCase();if(z(t)){let n=new TextDecoder("utf-8").decode(e);try{return JSON.parse(n)}catch{return n}}return W(t)?new TextDecoder("utf-8").decode(e):e}function Z(e){let r={};for(let[t,n]of e.entries())r[t.toLowerCase()]=n;return r}async function we(e){let{request:r}=e,t=new Headers;for(let[l,d]of r.headers)t.append(l,d);r.defaultContentType&&!t.has("content-type")&&t.set("content-type",r.defaultContentType),t.set(A,r.destinationUrl),t.set(U,r.authenticationId);for(let[l,d]of Object.entries(e.credentialHeaders))t.set(l,d);e.executionId&&t.set(_,e.executionId);let n={method:r.method,headers:t,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??Y)};r.body!==void 0&&(n.body=r.body,r.isStreamBody&&(n.duplex="half"));let i=await fetch(e.proxyUrl,n),o=i.headers.get(M);if(o!==null)return{kind:"brokerError",...await X(i,o)};let a=new Uint8Array(await i.arrayBuffer()),c=i.headers.get("content-type")??"";return{kind:"upstream",response:{status:i.status,headers:Z(i.headers),body:Q(a,c)}}}import{z as y}from"zod";var ee=3e4;function Te(e){let r=new URL(e);if(r.protocol!=="https:")throw u.unsupportedScheme(r.protocol.replace(/:$/,""))}function Ne(e,r){let t=`${m(e).hosts.api}/private/v1/helix/broker/s3/sign`;return r==="dev"?`${t}/dev`:t}var re=y.object({url:y.string(),method:y.string(),expiresAt:y.string()});async function De(e){let r=new Headers({"content-type":"application/json"});for(let[a,c]of Object.entries(e.credentialHeaders))r.set(a,c);e.executionId&&r.set(_,e.executionId);let t=await fetch(e.signUrl,{method:"POST",headers:r,body:JSON.stringify(e.body),redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??ee)}),n=await t.text(),i=n;try{i=JSON.parse(n)}catch{}if(t.ok){let a=re.safeParse(i);return a.success?{kind:"signed",result:a.data}:{kind:"brokerError",status:t.status,message:"malformed s3-sign response from credential broker",body:i}}let o=w.safeParse(i);return o.success?{kind:"brokerError",status:t.status,code:o.data.error.code,message:o.data.error.message,body:i}:{kind:"brokerError",status:t.status,message:n||`s3-sign request failed with status ${t.status}`,body:i}}export{b as a,R as b,te as c,ne as d,S as e,P as f,oe as g,H as h,se as i,m as j,ae as k,de as l,F as m,B as n,le as o,ue as p,ce as q,u as r,ge as s,A as t,U as u,J as v,_ as w,M as x,he as y,V as z,w as A,ve as B,xe as C,Ee as D,X as E,Y as F,we as G,Te as H,Ne as I,De as J};
@@ -98,7 +98,10 @@ type AgentSessionsConfig = z.infer<typeof agentSessionsSchema>;
98
98
  * platform authentications carry no service identifier, so the project
99
99
  * declares it here: `aiProviders: { <authAlias>: "<service>" }`. The
100
100
  * `openai-compatible` service (self-hosted vLLM, Ollama, …) additionally
101
- * needs the endpoint base URL, so it uses the object form.
101
+ * needs the endpoint base URL, so it uses the object form. `bedrock` likewise
102
+ * needs the object form: the provider package derives the regional runtime
103
+ * endpoint (`bedrock-runtime.<region>.amazonaws.com`) from `region`, or takes
104
+ * `baseUrl` verbatim for VPC / custom endpoints.
102
105
  *
103
106
  * `baseUrl` must be https: every `ctx.ai` request egresses through the
104
107
  * credentials broker's raw forward proxy, and `createBrokerFetch` rejects
@@ -107,28 +110,51 @@ type AgentSessionsConfig = z.infer<typeof agentSessionsSchema>;
107
110
  * and then fail on every request. Catching it in the schema turns that into
108
111
  * one clear config error instead of a confusing first-call failure.
109
112
  */
110
- declare const AI_SERVICES: readonly ["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"];
113
+ declare const AI_SERVICES: readonly ["openai", "anthropic", "google", "mistral", "cohere", "bedrock", "openai-compatible"];
111
114
  type AiService = (typeof AI_SERVICES)[number];
112
- declare const aiProviderEntrySchema: z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
113
- service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
115
+ declare const aiProviderEntrySchema: z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodObject<{
116
+ service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "bedrock", "openai-compatible"]>;
114
117
  baseUrl: z.ZodOptional<z.ZodString>;
118
+ region: z.ZodOptional<z.ZodString>;
115
119
  }, "strip", z.ZodTypeAny, {
116
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
120
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
121
+ region?: string | undefined;
117
122
  baseUrl?: string | undefined;
118
123
  }, {
119
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
124
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
125
+ region?: string | undefined;
120
126
  baseUrl?: string | undefined;
121
127
  }>, {
122
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
128
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
129
+ region?: string | undefined;
123
130
  baseUrl?: string | undefined;
124
131
  }, {
125
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
132
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
133
+ region?: string | undefined;
126
134
  baseUrl?: string | undefined;
127
135
  }>, {
128
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
136
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
137
+ region?: string | undefined;
129
138
  baseUrl?: string | undefined;
130
139
  }, {
131
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
140
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
141
+ region?: string | undefined;
142
+ baseUrl?: string | undefined;
143
+ }>, {
144
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
145
+ region?: string | undefined;
146
+ baseUrl?: string | undefined;
147
+ }, {
148
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
149
+ region?: string | undefined;
150
+ baseUrl?: string | undefined;
151
+ }>, {
152
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
153
+ region?: string | undefined;
154
+ baseUrl?: string | undefined;
155
+ }, {
156
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
157
+ region?: string | undefined;
132
158
  baseUrl?: string | undefined;
133
159
  }>]>;
134
160
  type AiProviderEntry = z.infer<typeof aiProviderEntrySchema>;
@@ -172,26 +198,49 @@ declare const trayConfigSchema: z.ZodEffects<z.ZodObject<{
172
198
  table: string;
173
199
  region: string;
174
200
  }>]>>;
175
- aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
176
- service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
201
+ aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodObject<{
202
+ service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "bedrock", "openai-compatible"]>;
177
203
  baseUrl: z.ZodOptional<z.ZodString>;
204
+ region: z.ZodOptional<z.ZodString>;
178
205
  }, "strip", z.ZodTypeAny, {
179
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
206
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
207
+ region?: string | undefined;
208
+ baseUrl?: string | undefined;
209
+ }, {
210
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
211
+ region?: string | undefined;
212
+ baseUrl?: string | undefined;
213
+ }>, {
214
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
215
+ region?: string | undefined;
216
+ baseUrl?: string | undefined;
217
+ }, {
218
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
219
+ region?: string | undefined;
220
+ baseUrl?: string | undefined;
221
+ }>, {
222
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
223
+ region?: string | undefined;
180
224
  baseUrl?: string | undefined;
181
225
  }, {
182
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
226
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
227
+ region?: string | undefined;
183
228
  baseUrl?: string | undefined;
184
229
  }>, {
185
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
230
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
231
+ region?: string | undefined;
186
232
  baseUrl?: string | undefined;
187
233
  }, {
188
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
234
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
235
+ region?: string | undefined;
189
236
  baseUrl?: string | undefined;
190
237
  }>, {
191
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
238
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
239
+ region?: string | undefined;
192
240
  baseUrl?: string | undefined;
193
241
  }, {
194
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
242
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
243
+ region?: string | undefined;
195
244
  baseUrl?: string | undefined;
196
245
  }>]>>>;
197
246
  }, "strip", z.ZodTypeAny, {
@@ -211,7 +260,8 @@ declare const trayConfigSchema: z.ZodEffects<z.ZodObject<{
211
260
  region: string;
212
261
  } | undefined;
213
262
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
214
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
263
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
264
+ region?: string | undefined;
215
265
  baseUrl?: string | undefined;
216
266
  }> | undefined;
217
267
  }, {
@@ -231,7 +281,8 @@ declare const trayConfigSchema: z.ZodEffects<z.ZodObject<{
231
281
  region: string;
232
282
  } | undefined;
233
283
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
234
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
284
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
285
+ region?: string | undefined;
235
286
  baseUrl?: string | undefined;
236
287
  }> | undefined;
237
288
  }>, {
@@ -250,7 +301,8 @@ declare const trayConfigSchema: z.ZodEffects<z.ZodObject<{
250
301
  region: string;
251
302
  } | undefined;
252
303
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
253
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
304
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
305
+ region?: string | undefined;
254
306
  baseUrl?: string | undefined;
255
307
  }> | undefined;
256
308
  }, {
@@ -270,7 +322,8 @@ declare const trayConfigSchema: z.ZodEffects<z.ZodObject<{
270
322
  region: string;
271
323
  } | undefined;
272
324
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
273
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
325
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
326
+ region?: string | undefined;
274
327
  baseUrl?: string | undefined;
275
328
  }> | undefined;
276
329
  }>;
@@ -311,26 +364,49 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
311
364
  table: string;
312
365
  region: string;
313
366
  }>]>>;
314
- aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
315
- service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
367
+ aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodObject<{
368
+ service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "bedrock", "openai-compatible"]>;
316
369
  baseUrl: z.ZodOptional<z.ZodString>;
370
+ region: z.ZodOptional<z.ZodString>;
317
371
  }, "strip", z.ZodTypeAny, {
318
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
372
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
373
+ region?: string | undefined;
319
374
  baseUrl?: string | undefined;
320
375
  }, {
321
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
376
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
377
+ region?: string | undefined;
322
378
  baseUrl?: string | undefined;
323
379
  }>, {
324
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
380
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
381
+ region?: string | undefined;
325
382
  baseUrl?: string | undefined;
326
383
  }, {
327
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
384
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
385
+ region?: string | undefined;
328
386
  baseUrl?: string | undefined;
329
387
  }>, {
330
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
388
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
389
+ region?: string | undefined;
331
390
  baseUrl?: string | undefined;
332
391
  }, {
333
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
392
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
393
+ region?: string | undefined;
394
+ baseUrl?: string | undefined;
395
+ }>, {
396
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
397
+ region?: string | undefined;
398
+ baseUrl?: string | undefined;
399
+ }, {
400
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
401
+ region?: string | undefined;
402
+ baseUrl?: string | undefined;
403
+ }>, {
404
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
405
+ region?: string | undefined;
406
+ baseUrl?: string | undefined;
407
+ }, {
408
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
409
+ region?: string | undefined;
334
410
  baseUrl?: string | undefined;
335
411
  }>]>>>;
336
412
  } & {
@@ -353,7 +429,8 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
353
429
  region: string;
354
430
  } | undefined;
355
431
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
356
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
432
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
433
+ region?: string | undefined;
357
434
  baseUrl?: string | undefined;
358
435
  }> | undefined;
359
436
  }, {
@@ -373,7 +450,8 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
373
450
  region: string;
374
451
  } | undefined;
375
452
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
376
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
453
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
454
+ region?: string | undefined;
377
455
  baseUrl?: string | undefined;
378
456
  }> | undefined;
379
457
  }>, z.ZodObject<{
@@ -405,26 +483,49 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
405
483
  table: string;
406
484
  region: string;
407
485
  }>]>>;
408
- aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
409
- service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
486
+ aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodObject<{
487
+ service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "bedrock", "openai-compatible"]>;
410
488
  baseUrl: z.ZodOptional<z.ZodString>;
489
+ region: z.ZodOptional<z.ZodString>;
411
490
  }, "strip", z.ZodTypeAny, {
412
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
491
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
492
+ region?: string | undefined;
493
+ baseUrl?: string | undefined;
494
+ }, {
495
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
496
+ region?: string | undefined;
497
+ baseUrl?: string | undefined;
498
+ }>, {
499
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
500
+ region?: string | undefined;
501
+ baseUrl?: string | undefined;
502
+ }, {
503
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
504
+ region?: string | undefined;
505
+ baseUrl?: string | undefined;
506
+ }>, {
507
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
508
+ region?: string | undefined;
413
509
  baseUrl?: string | undefined;
414
510
  }, {
415
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
511
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
512
+ region?: string | undefined;
416
513
  baseUrl?: string | undefined;
417
514
  }>, {
418
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
515
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
516
+ region?: string | undefined;
419
517
  baseUrl?: string | undefined;
420
518
  }, {
421
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
519
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
520
+ region?: string | undefined;
422
521
  baseUrl?: string | undefined;
423
522
  }>, {
424
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
523
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
524
+ region?: string | undefined;
425
525
  baseUrl?: string | undefined;
426
526
  }, {
427
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
527
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
528
+ region?: string | undefined;
428
529
  baseUrl?: string | undefined;
429
530
  }>]>>>;
430
531
  } & {
@@ -445,7 +546,8 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
445
546
  region: string;
446
547
  } | undefined;
447
548
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
448
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
549
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
550
+ region?: string | undefined;
449
551
  baseUrl?: string | undefined;
450
552
  }> | undefined;
451
553
  }, {
@@ -464,7 +566,8 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
464
566
  region: string;
465
567
  } | undefined;
466
568
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
467
- service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
569
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "bedrock" | "openai-compatible";
570
+ region?: string | undefined;
468
571
  baseUrl?: string | undefined;
469
572
  }> | undefined;
470
573
  }>]>;
package/dist/index.d.ts CHANGED
@@ -2,8 +2,8 @@ import * as h3 from 'h3';
2
2
  import { ZodType } from 'zod';
3
3
  import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-CRUtefiq.js';
4
4
  export { A as AgentApprovalDecision, b as AgentCallOptions, c as AgentClient, d as AgentPendingApproval, e as AgentResult, f as AgentSession, g as AgentSessionPage, h as AgentSessionPageOptions, i as AgentSessionSummary, j as AgentSessionsList, k as AgentStreamResult, l as AiEmbeddingModelInstance, m as AiImageModelInstance, n as AiLanguageModelInstance, o as AiSpeechModelInstance, p as AiTranscriptionModelInstance, B as BrokerAuthedClient, q as BrokerCallOptions, r as BrokerCallResult, C as CallFunctionAsync, s as DbCallParameters, t as DbClient, u as FileSystemClient, H as HelixAI, v as HelixAIProvider, w as HelixAgent, x as HelixCost, y as HelixResultMeta, z as HttpClient, K as KeyValueStore, L as Logger, E as S3SignOptions, G as S3SignResult, I as ScheduleContext, J as ScheduleHandler, M as ScheduleTrigger, N as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-CRUtefiq.js';
5
- import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './define-agent-C0qXub7P.js';
6
- export { A as AGENT_DEFINITION_KIND, a as AI_SERVICES, b as AgentDefinition, c as AgentDefinitionConfig, d as AgentSessionsConfig, e as AiProviderEntry, f as AiService, C as ConfigFileOptions, D as DefineToolConfig, H as HELIX_CONFIG_ENV, g as HelixTool, h as HelixToolLike, P as ProvisionedTrayConfig, S as SdkRuntimeConfig, i as TOOL_DEFINITION_KIND, U as UnprovisionedTrayConfig, j as WORKSPACE_ID_REQUIRED_CODE, k as WorkspaceIdRequiredError, l as agentSessionsSchema, m as aiProviderEntrySchema, n as defineAgent, o as defineTool, p as getSdkConfig, q as isAgentDefinition, r as isToolDefinition, s as loadConfig, t as loadedTrayConfigSchema, u as projectIdSchema, v as requireWorkspaceId, w as resolveConfigFile, x as resolveConfigOverride, y as workspaceIdSchema } from './define-agent-C0qXub7P.js';
5
+ import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './define-agent-Cc6mFat1.js';
6
+ export { A as AGENT_DEFINITION_KIND, a as AI_SERVICES, b as AgentDefinition, c as AgentDefinitionConfig, d as AgentSessionsConfig, e as AiProviderEntry, f as AiService, C as ConfigFileOptions, D as DefineToolConfig, H as HELIX_CONFIG_ENV, g as HelixTool, h as HelixToolLike, P as ProvisionedTrayConfig, S as SdkRuntimeConfig, i as TOOL_DEFINITION_KIND, U as UnprovisionedTrayConfig, j as WORKSPACE_ID_REQUIRED_CODE, k as WorkspaceIdRequiredError, l as agentSessionsSchema, m as aiProviderEntrySchema, n as defineAgent, o as defineTool, p as getSdkConfig, q as isAgentDefinition, r as isToolDefinition, s as loadConfig, t as loadedTrayConfigSchema, u as projectIdSchema, v as requireWorkspaceId, w as resolveConfigFile, x as resolveConfigOverride, y as workspaceIdSchema } from './define-agent-Cc6mFat1.js';
7
7
  export { a as REGION_VALUES, R as Region, r as regionSchema } from './region-schema-COfWyGI9.js';
8
8
  import { StopCondition, ToolSet } from 'ai';
9
9
  export { EmbedManyResult, EmbedResult, EmbeddingModel, FinishReason, GenerateImageResult, GenerateObjectResult, GenerateTextResult, ImageModel, LanguageModel, LanguageModelUsage, ModelMessage, Output, PrepareStepFunction, SpeechModel, SpeechResult, StopCondition, StreamObjectResult, StreamTextResult, TextStreamPart, ToolChoice, ToolSet, TranscriptionModel, TranscriptionResult, UIMessage, convertToModelMessages, cosineSimilarity, dynamicTool, hasToolCall, jsonSchema, smoothStream, stepCountIs, tool, zodSchema } from 'ai';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{A as le,B as fe,C as pe,D as ge,E as me,F as he,G as ye,H as x,I as k,J as V,K as z,L as y,M as Ce,N as ve,O as B,P as Se,Q as we,R as Ee,Y as _e,Z as xe,_ as ke,ba as Te,ca as G,da as be,ea as Ie,f as A,fa as Re,g as _,ga as Ae,h as P,i as h,j as H,k as F,l as D,m as O,n as ae,o as j,p as M,q,r as N,s as Z,w as K,x as $,y as ue,z as ce}from"./chunk-D44IVAUR.js";import{a as L,b as de}from"./chunk-WUCX7RZO.js";import{d as E,r as W,s as U}from"./chunk-3T2WZMJJ.js";import{randomUUID as We}from"crypto";import{SpanStatusCode as ee,SpanKind as Ue}from"@opentelemetry/api";import{defineEventHandler as qe,getMethod as Ne,getRequestURL as Ze,getHeaders as re,getHeader as te}from"h3";import{readBody as Pe,getQuery as He,getRouterParams as Fe}from"h3";async function J(e,t){let r=await De(e),n=He(e),o=Fe(e)??{},s={...n,...r,...o};return t?Oe(s,t):s}async function De(e){try{let t=await Pe(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function Oe(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var C=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function Q(e){return t=>{e.node.res.statusCode=t}}function X(){return(e,t)=>{throw new C(e,t)}}function Y(e,t){let{statusCode:r,message:n}=Le(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Le(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_path_invalid":return{statusCode:400,message:e.message};case"call_function_call_failed":return{statusCode:502,message:"Async function call failed"};case"call_function_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_not_available":return{statusCode:501,message:"callFunctionAsync is not available in this environment"};case"call_function_missing_execution_jwt":return{statusCode:401,message:"Missing execution credentials"};case"ai_unsupported_service":case"ai_model_id_required":case"ai_model_instance_required":case"ai_provider_not_configured":case"ai_foreign_model_rejected":case"agent_sessions_failed":return{statusCode:500,message:e.kind==="ai_unsupported_service"?`AI service not supported for alias "${e.alias}"`:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var je=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Me(e){return e.toLowerCase().includes("tray_lid")}function T(e){let t={};for(let[r,n]of Object.entries(e))if(!je.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let d=s.split("=")[0].trim();return!Me(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ke(e,t){let{inputSchema:r,outputSchema:n}=Je(t),o=e;return qe(async s=>{let d=E(),{executionId:a,userId:i,deploymentId:f}=Qe(d,s),c=d.mode==="lambda"?d.parentExecutionId??null:null,p=Date.now(),v=new Date().toISOString(),l=Ne(s),u=Ze(s).pathname,g=M(),m=j(),se=`${l} ${u}`;H();let R={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1};return $e(()=>_.run(R,()=>A.run(a,async()=>{let S=await Ve(s,r);if(!S.ok)return{response:S.response,errored:!1,errorMessage:null};let ie=Ye(s,S.input,g,m,l,u,a,f,i,c);return ze(o,ie,n,s,m,a,f,{method:l,path:u,rawInput:S.input})})),{executionId:a,deploymentId:f,routeOrJob:se,startedAt:v,startMs:p,userId:i,flags:R})})}async function $e(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{O({...t,errored:r,errorMessage:n}),await F()}}async function Ve(e,t){try{return{ok:!0,input:await J(e,t)}}catch(r){let n=Xe(e,r);if(n)return{ok:!1,response:n};throw r}}async function ze(e,t,r,n,o,s,d,a){return D.startActiveSpan("function",{root:!0,kind:Ue.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...d?{deploymentId:d}:{}}},async i=>{t.traceId=i.spanContext().traceId;let f=T(re(n));h(i,"input",a.rawInput),h(i,"request",{method:a.method,path:a.path,headers:f,body:a.rawInput});let c=!1,p=null,v,l;try{let u=await L.run(t,()=>e(t));if(v=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let g=r.safeParse(u);if(!g.success){let m=Object.keys(g.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:m,executionId:s}),W.outputValidationFailed(m)}l=g.data}else l=u}catch(u){c=!0,p=u instanceof Error?u.message:String(u),P("hasError"),l=Be(u,n,o,s)}finally{Ge(i,n,{errored:c,errorMessage:p,handlerResult:v,response:l})}return{response:l,errored:c,errorMessage:p}})}function Be(e,t,r,n){if(e instanceof C)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(U(e))return Y(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function Ge(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&h(e,"output",r.handlerResult),h(e,"response",r.response);let n=_.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasAi",n?.hasAi??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?ee.ERROR:ee.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Je(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Qe(e,t){let r=e.mode==="lambda",n=(r?e.executionId:te(t,"x-tray-execution-id"))??We(),o=(r?e.userId:te(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Xe(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function Ye(e,t,r,n,o,s,d,a,i,f){return{input:t,method:o,path:s,headers:T(re(e)),http:q(),db:c=>N(c),kv:()=>Z(),files:()=>K(),callFunctionAsync:$(),ai:B(),agent:c=>G(c),log:n,config:r,status:Q(e),error:X(),state:{},request:e,executionId:d,deploymentId:a,userId:i,parentExecutionId:f,identity:i!==null?{user:{id:i}}:null,traceId:""}}function et(e){return e}import{existsSync as tt,watch as rt,writeSync as nt}from"fs";import{basename as ot,dirname as st,join as it,resolve as w}from"path";import{watchConfig as at}from"c12";function dt(e,t){let r=e instanceof Error?e.message:String(e);nt(2,`[helix-watch] ${t.phase} error: ${r}
1
+ import{A as le,B as fe,C as pe,D as ge,E as me,F as he,G as ye,H as x,I as k,J as V,K as z,L as y,M as Ce,N as ve,O as B,P as Se,Q as we,R as Ee,Y as _e,Z as xe,_ as ke,ba as Te,ca as G,da as be,ea as Ie,f as A,fa as Re,g as _,ga as Ae,h as P,i as h,j as H,k as F,l as D,m as O,n as ae,o as j,p as M,q,r as N,s as Z,w as K,x as $,y as ue,z as ce}from"./chunk-3WKD2ENP.js";import{a as L,b as de}from"./chunk-WUCX7RZO.js";import{d as E,r as W,s as U}from"./chunk-JKFMPHA4.js";import{randomUUID as We}from"crypto";import{SpanStatusCode as ee,SpanKind as Ue}from"@opentelemetry/api";import{defineEventHandler as qe,getMethod as Ne,getRequestURL as Ze,getHeaders as re,getHeader as te}from"h3";import{readBody as Pe,getQuery as He,getRouterParams as Fe}from"h3";async function J(e,t){let r=await De(e),n=He(e),o=Fe(e)??{},s={...n,...r,...o};return t?Oe(s,t):s}async function De(e){try{let t=await Pe(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function Oe(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var C=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function Q(e){return t=>{e.node.res.statusCode=t}}function X(){return(e,t)=>{throw new C(e,t)}}function Y(e,t){let{statusCode:r,message:n}=Le(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Le(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_path_invalid":return{statusCode:400,message:e.message};case"call_function_call_failed":return{statusCode:502,message:"Async function call failed"};case"call_function_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_not_available":return{statusCode:501,message:"callFunctionAsync is not available in this environment"};case"call_function_missing_execution_jwt":return{statusCode:401,message:"Missing execution credentials"};case"ai_unsupported_service":case"ai_provider_misconfigured":case"ai_model_id_required":case"ai_model_instance_required":case"ai_provider_not_configured":case"ai_foreign_model_rejected":case"agent_sessions_failed":return{statusCode:500,message:e.kind==="ai_unsupported_service"?`AI service not supported for alias "${e.alias}"`:e.kind==="ai_provider_misconfigured"?`AI provider misconfigured for alias "${e.alias}"`:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var je=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Me(e){return e.toLowerCase().includes("tray_lid")}function T(e){let t={};for(let[r,n]of Object.entries(e))if(!je.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let d=s.split("=")[0].trim();return!Me(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ke(e,t){let{inputSchema:r,outputSchema:n}=Je(t),o=e;return qe(async s=>{let d=E(),{executionId:a,userId:i,deploymentId:f}=Qe(d,s),c=d.mode==="lambda"?d.parentExecutionId??null:null,p=Date.now(),v=new Date().toISOString(),l=Ne(s),u=Ze(s).pathname,g=M(),m=j(),se=`${l} ${u}`;H();let R={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1};return $e(()=>_.run(R,()=>A.run(a,async()=>{let S=await Ve(s,r);if(!S.ok)return{response:S.response,errored:!1,errorMessage:null};let ie=Ye(s,S.input,g,m,l,u,a,f,i,c);return ze(o,ie,n,s,m,a,f,{method:l,path:u,rawInput:S.input})})),{executionId:a,deploymentId:f,routeOrJob:se,startedAt:v,startMs:p,userId:i,flags:R})})}async function $e(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{O({...t,errored:r,errorMessage:n}),await F()}}async function Ve(e,t){try{return{ok:!0,input:await J(e,t)}}catch(r){let n=Xe(e,r);if(n)return{ok:!1,response:n};throw r}}async function ze(e,t,r,n,o,s,d,a){return D.startActiveSpan("function",{root:!0,kind:Ue.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...d?{deploymentId:d}:{}}},async i=>{t.traceId=i.spanContext().traceId;let f=T(re(n));h(i,"input",a.rawInput),h(i,"request",{method:a.method,path:a.path,headers:f,body:a.rawInput});let c=!1,p=null,v,l;try{let u=await L.run(t,()=>e(t));if(v=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let g=r.safeParse(u);if(!g.success){let m=Object.keys(g.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:m,executionId:s}),W.outputValidationFailed(m)}l=g.data}else l=u}catch(u){c=!0,p=u instanceof Error?u.message:String(u),P("hasError"),l=Be(u,n,o,s)}finally{Ge(i,n,{errored:c,errorMessage:p,handlerResult:v,response:l})}return{response:l,errored:c,errorMessage:p}})}function Be(e,t,r,n){if(e instanceof C)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(U(e))return Y(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function Ge(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&h(e,"output",r.handlerResult),h(e,"response",r.response);let n=_.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasAi",n?.hasAi??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?ee.ERROR:ee.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Je(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Qe(e,t){let r=e.mode==="lambda",n=(r?e.executionId:te(t,"x-tray-execution-id"))??We(),o=(r?e.userId:te(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Xe(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function Ye(e,t,r,n,o,s,d,a,i,f){return{input:t,method:o,path:s,headers:T(re(e)),http:q(),db:c=>N(c),kv:()=>Z(),files:()=>K(),callFunctionAsync:$(),ai:B(),agent:c=>G(c),log:n,config:r,status:Q(e),error:X(),state:{},request:e,executionId:d,deploymentId:a,userId:i,parentExecutionId:f,identity:i!==null?{user:{id:i}}:null,traceId:""}}function et(e){return e}import{existsSync as tt,watch as rt,writeSync as nt}from"fs";import{basename as ot,dirname as st,join as it,resolve as w}from"path";import{watchConfig as at}from"c12";function dt(e,t){let r=e instanceof Error?e.message:String(e);nt(2,`[helix-watch] ${t.phase} error: ${r}
2
2
  `)}function b(){return{kind:"unprovisioned",name:"",authentications:{},config:{},region:"us1"}}var ut=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,ne=new Set;function oe(e,t){return k(e,{configFile:t})!==void 0}async function ct(e,t,r){if(oe(e.cwd,t))try{return{current:await y(e.cwd,{configFile:t}),initialLoadSucceeded:!0}}catch(n){return r(n,{phase:"reload"}),{current:b(),initialLoadSucceeded:!1}}if(e.watch){let n=t!==void 0?w(e.cwd,t):w(e.cwd);ne.has(n)||(process.stderr.write(t!==void 0?`warning: config file ${w(e.cwd,t)} not found; tray running with default config
3
3
  `:`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
4
4
  `),ne.add(n))}return{current:b(),initialLoadSucceeded:!1}}var I=class{constructor(t,r,n,o){this.cwd=t;this.configFile=r;this.onError=n;this.emit=o}cwd;configFile;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=at({...V(this.cwd,{configFile:this.configFile}),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=z(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,s)=>{n.once("ready",o),n.once("error",s)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){let t=this.configFile!==void 0?w(this.cwd,this.configFile):void 0,r=t!==void 0?st(t):this.cwd;try{this.directoryWatcher=rt(r,{persistent:!1},(n,o)=>{if(this.stopped||!o)return;let s=o.toString();if(t!==void 0){if(s!==ot(t))return}else if(!ut.test(s))return;tt(it(r,s))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let d;try{d=await y(this.cwd,{configFile:this.configFile})}catch(i){this.onError(i,{phase:"reload"});return}if(this.stopped)return;this.emit(d);let a=this.directoryWatcher;a&&(this.directoryWatcher=null,a.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",n=>{this.onError(n,{phase:"attach"})})}catch(n){this.onError(n,{phase:"attach"})}}};async function lt(e){let t=e.onError??dt,r=new Set,n=x(e.configFile),o=await ct(e,n,t),s=o.current;function d(i){s=i;for(let f of[...r])try{f(i)}catch(c){t(c,{phase:"reload"})}}let a=new I(e.cwd,n,t,d);return e.watch&&a.start(o.initialLoadSucceeded),{get(){return s},async reload(){if(!oe(e.cwd,n)){let i=b();return d(i),i}try{let i=await y(e.cwd,{configFile:n});return d(i),i}catch(i){return t(i,{phase:"reload"}),s}},subscribe(i){return r.add(i),()=>{r.delete(i)}},async stop(){r.clear(),await a.stop()},ready(){return a.watcherReady()}}}import{tool as sr,dynamicTool as ir,jsonSchema as ar,zodSchema as dr,stepCountIs as ur,hasToolCall as cr,convertToModelMessages as lr,cosineSimilarity as fr,smoothStream as pr,Output as gr}from"ai";export{_e as AGENT_DEFINITION_KIND,ge as AI_SERVICES,ye as HELIX_CONFIG_ENV,gr as Output,ue as REGION_VALUES,be as SCHEDULE_DEFINITION_KIND,Ie as ScheduleConfigError,Se as TOOL_DEFINITION_KIND,Ce as WORKSPACE_ID_REQUIRED_CODE,pe as agentSessionsSchema,me as aiProviderEntrySchema,lr as convertToModelMessages,fr as cosineSimilarity,lt as createConfigService,xe as defineAgent,et as defineConfig,Ke as defineFunction,Re as defineSchedule,we as defineTool,ir as dynamicTool,de as getContext,E as getSdkConfig,cr as hasToolCall,ke as isAgentDefinition,Ae as isScheduleDefinition,Ee as isToolDefinition,ar as jsonSchema,y as loadConfig,he as loadedTrayConfigSchema,le as projectIdSchema,ce as regionSchema,ve as requireWorkspaceId,k as resolveConfigFile,x as resolveConfigOverride,ae as runWithinAppSpan,pr as smoothStream,ur as stepCountIs,sr as tool,Te as totalToolCallsIs,fe as workspaceIdSchema,dr as zodSchema};
@@ -1,5 +1,5 @@
1
- import { L as LoadedTrayConfig, b as AgentDefinition } from '../define-agent-C0qXub7P.js';
2
- export { z as SdkConfigInput, B as setSdkConfig } from '../define-agent-C0qXub7P.js';
1
+ import { L as LoadedTrayConfig, b as AgentDefinition } from '../define-agent-Cc6mFat1.js';
2
+ export { z as SdkConfigInput, B as setSdkConfig } from '../define-agent-Cc6mFat1.js';
3
3
  import { j as AgentSessionsList, b as AgentCallOptions, e as AgentResult } from '../types-CRUtefiq.js';
4
4
  export { O as SessionExpiredError, Q as clearAgentSessions } from '../types-CRUtefiq.js';
5
5
  import 'zod';
@@ -211,6 +211,11 @@ type SdkErrorDetail = {
211
211
  readonly kind: "ai_provider_not_configured";
212
212
  alias: string;
213
213
  supported: string[];
214
+ } | {
215
+ readonly kind: "ai_provider_misconfigured";
216
+ alias: string;
217
+ service: string;
218
+ message: string;
214
219
  } | {
215
220
  readonly kind: "ai_foreign_model_rejected";
216
221
  } | {
@@ -255,6 +260,7 @@ declare class SdkError extends Error {
255
260
  static aiModelIdRequired(alias: string, operation: string): SdkError;
256
261
  static aiModelInstanceRequired(modelId: string): SdkError;
257
262
  static aiProviderNotConfigured(alias: string, supported: string[]): SdkError;
263
+ static aiProviderMisconfigured(alias: string, service: string, message: string): SdkError;
258
264
  static aiForeignModelRejected(): SdkError;
259
265
  static agentSessionsFailed(message: string): SdkError;
260
266
  }
@@ -1 +1 @@
1
- import{$ as At,O as E,S as ft,T as dt,U as mt,V as gt,W as pt,X as ht,a as J,aa as St,b as V,c as q,ca as l,d as R,e as z,f as g,g as P,ga as v,h as F,i as N,j as p,k as O,l as k,m as j,o as A,p as M,q as S,r as x,s as y,t as lt,u as ct,v as ut,w as I,x as C}from"../chunk-D44IVAUR.js";import{a as h}from"../chunk-WUCX7RZO.js";import{c as G,d as D,g as Q,h as W,i as X,j as Y,k as Z,l as tt,m as et,n as rt,o as ot,p as nt,q as it,r as st,s as at}from"../chunk-3T2WZMJJ.js";import{randomUUID as xt}from"crypto";import{SpanStatusCode as H,SpanKind as yt}from"@opentelemetry/api";var i=class extends Error{constructor(t){super(`runScheduledFunction: ${t}`),this.name="ScheduleInvocationError"}};async function It(e,t){if(typeof t!="object"||t===null)throw new i("`invocation` must be an object");let{schedulePath:r}=t;if(typeof r!="string"||r.length===0)throw new i("`schedulePath` must be a non-empty string");if(typeof t.isManual!="boolean")throw new i("`isManual` must be a boolean");if(!v(e))throw new i(`default export of "${r}" is not a defineSchedule definition`);let c=L("scheduledAt",t.scheduledAt),b=L("firedAt",t.firedAt),a=D(),u=a.executionId??xt(),f=a.deploymentId??null,K=Date.now(),$=new Date().toISOString(),U=M(),_=A();p();let s={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1},d=!1,m=null;try{await P.run(s,()=>g.run(u,()=>k.startActiveSpan("schedule",{root:!0,kind:yt.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:u,...f?{deploymentId:f}:{}}},async n=>{let B={type:"schedule",scheduledAt:c,firedAt:b,isManual:t.isManual},w={http:S(),db:o=>x(o),kv:()=>y(),files:()=>I(),callFunctionAsync:C(),ai:E(),agent:o=>l(o),log:_,config:U,state:{},executionId:u,deploymentId:f,traceId:n.spanContext().traceId,parentExecutionId:null,trigger:B};N(n,"input",{scheduledAt:t.scheduledAt,firedAt:t.firedAt,isManual:t.isManual});try{await h.run(w,()=>e.handler(w))}catch(o){throw d=!0,m=o instanceof Error?o.message:String(o),F("hasError"),o}finally{n.setAttribute("hasAuth",s.hasAuth),n.setAttribute("hasAi",s.hasAi),n.setAttribute("hasExternal",s.hasExternal),n.setAttribute("hasDb",s.hasDb),n.setAttribute("status",d?"error":"success");let o=d||s.hasError;n.setStatus({code:o?H.ERROR:H.OK,...m?{message:m}:{}}),n.end()}})))}finally{j({executionId:u,deploymentId:f,triggerType:"schedule",routeOrJob:r,startedAt:$,startMs:K,errored:d,errorMessage:m,userId:null,flags:s}),await O()}}function L(e,t){if(typeof t!="string"||t.length===0)throw new i(`\`${e}\` must be a timestamp string; got ${JSON.stringify(t)}`);let r=new Date(t);if(Number.isNaN(r.getTime()))throw new i(`\`${e}\` must be a Date-parseable timestamp; got ${JSON.stringify(t)}`);return r}function T(e,t){p();let r=R(),c=crypto.randomUUID(),b={http:S(),db:a=>x(a),kv:()=>y(),files:()=>I(),callFunctionAsync:C(),ai:E(),agent:a=>l(a),log:A(),config:r.config??{},state:{},executionId:c,deploymentId:null,traceId:"",parentExecutionId:null,userId:e.userId??null};return g.run(c,()=>h.run(b,t))}async function Ct(e,t,r={}){return T(r,()=>l(e).generate(t))}async function Et(e,t){return T({userId:t.userId},()=>l(e).sessions({...t.first!==void 0?{first:t.first}:{},...t.cursor!==void 0?{cursor:t.cursor}:{}}))}export{ft as AgentCallerError,J as CONFIG_BRIDGE_CHANNEL,V as DEV_TOKEN_BRIDGE_CHANNEL,i as ScheduleInvocationError,st as SdkError,At as SessionExpiredError,lt as assertValidPath,z as clearActiveConfig,ht as clearAgentRegistry,St as clearAgentSessions,ct as contentFilePath,R as getActiveConfig,nt as getAdditionalRegionProfiles,gt as getAgentDefinition,X as getRegionProfile,W as isKnownRegion,at as isSdkError,Et as listAgentSessionsStandalone,pt as listAgents,tt as listExposedRegionNames,Z as listRegionNames,ut as metaFilePath,et as parseExposedRegionName,Q as registerRegionProfile,Y as requireRegionProfile,it as resetRegionRegistryForTests,ot as resolveForcedRegion,Ct as runAgentStandalone,It as runScheduledFunction,q as setActiveConfig,dt as setAgentBaseDir,mt as setAgentInstructions,rt as setForcedRegion,G as setSdkConfig};
1
+ import{$ as At,O as E,S as ft,T as dt,U as mt,V as gt,W as pt,X as ht,a as J,aa as St,b as V,c as q,ca as l,d as R,e as z,f as g,g as P,ga as v,h as F,i as N,j as p,k as O,l as k,m as j,o as A,p as M,q as S,r as x,s as y,t as lt,u as ct,v as ut,w as I,x as C}from"../chunk-3WKD2ENP.js";import{a as h}from"../chunk-WUCX7RZO.js";import{c as G,d as D,g as Q,h as W,i as X,j as Y,k as Z,l as tt,m as et,n as rt,o as ot,p as nt,q as it,r as st,s as at}from"../chunk-JKFMPHA4.js";import{randomUUID as xt}from"crypto";import{SpanStatusCode as H,SpanKind as yt}from"@opentelemetry/api";var i=class extends Error{constructor(t){super(`runScheduledFunction: ${t}`),this.name="ScheduleInvocationError"}};async function It(e,t){if(typeof t!="object"||t===null)throw new i("`invocation` must be an object");let{schedulePath:r}=t;if(typeof r!="string"||r.length===0)throw new i("`schedulePath` must be a non-empty string");if(typeof t.isManual!="boolean")throw new i("`isManual` must be a boolean");if(!v(e))throw new i(`default export of "${r}" is not a defineSchedule definition`);let c=L("scheduledAt",t.scheduledAt),b=L("firedAt",t.firedAt),a=D(),u=a.executionId??xt(),f=a.deploymentId??null,K=Date.now(),$=new Date().toISOString(),U=M(),_=A();p();let s={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1},d=!1,m=null;try{await P.run(s,()=>g.run(u,()=>k.startActiveSpan("schedule",{root:!0,kind:yt.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:u,...f?{deploymentId:f}:{}}},async n=>{let B={type:"schedule",scheduledAt:c,firedAt:b,isManual:t.isManual},w={http:S(),db:o=>x(o),kv:()=>y(),files:()=>I(),callFunctionAsync:C(),ai:E(),agent:o=>l(o),log:_,config:U,state:{},executionId:u,deploymentId:f,traceId:n.spanContext().traceId,parentExecutionId:null,trigger:B};N(n,"input",{scheduledAt:t.scheduledAt,firedAt:t.firedAt,isManual:t.isManual});try{await h.run(w,()=>e.handler(w))}catch(o){throw d=!0,m=o instanceof Error?o.message:String(o),F("hasError"),o}finally{n.setAttribute("hasAuth",s.hasAuth),n.setAttribute("hasAi",s.hasAi),n.setAttribute("hasExternal",s.hasExternal),n.setAttribute("hasDb",s.hasDb),n.setAttribute("status",d?"error":"success");let o=d||s.hasError;n.setStatus({code:o?H.ERROR:H.OK,...m?{message:m}:{}}),n.end()}})))}finally{j({executionId:u,deploymentId:f,triggerType:"schedule",routeOrJob:r,startedAt:$,startMs:K,errored:d,errorMessage:m,userId:null,flags:s}),await O()}}function L(e,t){if(typeof t!="string"||t.length===0)throw new i(`\`${e}\` must be a timestamp string; got ${JSON.stringify(t)}`);let r=new Date(t);if(Number.isNaN(r.getTime()))throw new i(`\`${e}\` must be a Date-parseable timestamp; got ${JSON.stringify(t)}`);return r}function T(e,t){p();let r=R(),c=crypto.randomUUID(),b={http:S(),db:a=>x(a),kv:()=>y(),files:()=>I(),callFunctionAsync:C(),ai:E(),agent:a=>l(a),log:A(),config:r.config??{},state:{},executionId:c,deploymentId:null,traceId:"",parentExecutionId:null,userId:e.userId??null};return g.run(c,()=>h.run(b,t))}async function Ct(e,t,r={}){return T(r,()=>l(e).generate(t))}async function Et(e,t){return T({userId:t.userId},()=>l(e).sessions({...t.first!==void 0?{first:t.first}:{},...t.cursor!==void 0?{cursor:t.cursor}:{}}))}export{ft as AgentCallerError,J as CONFIG_BRIDGE_CHANNEL,V as DEV_TOKEN_BRIDGE_CHANNEL,i as ScheduleInvocationError,st as SdkError,At as SessionExpiredError,lt as assertValidPath,z as clearActiveConfig,ht as clearAgentRegistry,St as clearAgentSessions,ct as contentFilePath,R as getActiveConfig,nt as getAdditionalRegionProfiles,gt as getAgentDefinition,X as getRegionProfile,W as isKnownRegion,at as isSdkError,Et as listAgentSessionsStandalone,pt as listAgents,tt as listExposedRegionNames,Z as listRegionNames,ut as metaFilePath,et as parseExposedRegionName,Q as registerRegionProfile,Y as requireRegionProfile,it as resetRegionRegistryForTests,ot as resolveForcedRegion,Ct as runAgentStandalone,It as runScheduledFunction,q as setActiveConfig,dt as setAgentBaseDir,mt as setAgentInstructions,rt as setForcedRegion,G as setSdkConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "1.6.1",
3
+ "version": "1.8.0",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",
@@ -41,13 +41,14 @@
41
41
  "node": ">=24.19.0"
42
42
  },
43
43
  "dependencies": {
44
- "@ai-sdk/anthropic": "^4.0.49",
45
- "@ai-sdk/cohere": "^4.0.37",
46
- "@ai-sdk/google": "^4.0.63",
47
- "@ai-sdk/mistral": "^4.0.39",
48
- "@ai-sdk/openai": "^4.0.58",
49
- "@ai-sdk/openai-compatible": "^3.0.43",
50
- "@ai-sdk/provider": "^4.0.10",
44
+ "@ai-sdk/amazon-bedrock": "^5.0.101",
45
+ "@ai-sdk/anthropic": "^4.0.68",
46
+ "@ai-sdk/cohere": "^4.0.52",
47
+ "@ai-sdk/google": "^4.0.85",
48
+ "@ai-sdk/mistral": "^4.0.54",
49
+ "@ai-sdk/openai": "^4.0.81",
50
+ "@ai-sdk/openai-compatible": "^3.0.59",
51
+ "@ai-sdk/provider": "^4.0.19",
51
52
  "@opentelemetry/api": "^1.9.1",
52
53
  "@opentelemetry/api-logs": "0.220.0",
53
54
  "@opentelemetry/core": ">=2.8.0 <3",
@@ -57,7 +58,7 @@
57
58
  "@opentelemetry/sdk-logs": "0.220.0",
58
59
  "@opentelemetry/sdk-trace-base": "^2.11.0",
59
60
  "@opentelemetry/sdk-trace-node": "^2.11.0",
60
- "ai": "^7.0.92",
61
+ "ai": "^7.0.122",
61
62
  "c12": "^3.3.4",
62
63
  "chokidar": "^5.0.0",
63
64
  "h3": "^1.15.11",
@@ -1 +0,0 @@
1
- var b="X-Helix-Project-Execution-Token",R="X-Tray-Token",$={mode:"dev",deploymentId:null},k={...$},p={};function te(e){let{internalJwt:r,helixExecutionJwt:t,devToken:n,...i}=e;"internalJwt"in e&&(p.internalJwt=r),"helixExecutionJwt"in e&&(p.helixExecutionJwt=t),"devToken"in e&&(p.devToken=n),k={...k,...i}}function ne(){return k}function S(){return p.internalJwt}function P(){return p.helixExecutionJwt}function I(){return p.devToken}var O=new Set(["us1","eu1","ap1","ap2"]),s=new Map,h={name:"us1",exposedName:"us1",displayName:"us1",hosts:{api:"https://api.tray.io",broker:"https://api.tray.io/private/v1/code",ingest:"https://api.tray.io/private/v1/helix/otlp",weaver:"https://weaver.tray.io",app:"https://app.tray.io",projectHost:"helix-app.ai",dashboard:"https://app.helix.tray.ai",auth:"https://auth.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}},v={name:"eu1",exposedName:"eu1",displayName:"eu1",hosts:{api:"https://api.eu1.tray.io",broker:"https://api.eu1.tray.io/private/v1/code",ingest:"https://api.eu1.tray.io/private/v1/helix/otlp",weaver:"https://weaver.eu1.tray.io",app:"https://app.eu1.tray.io",projectHost:"eu1.helix-app.ai",dashboard:"https://app.helix.eu1.tray.ai",auth:"https://auth.eu1.tray.io"},login:{storePrefix:"EU1",appUrl:"https://app.eu1.tray.io",cookieName:"prod_tray_lid_eu",cookieDomain:"tray.io"}},x={name:"ap1",exposedName:"ap1",displayName:"ap1",hosts:{api:"https://api.ap1.tray.io",broker:"https://api.ap1.tray.io/private/v1/code",ingest:"https://api.ap1.tray.io/private/v1/helix/otlp",weaver:"https://weaver.ap1.tray.io",app:"https://app.ap1.tray.io",projectHost:"ap1.helix-app.ai",dashboard:"https://app.helix.ap1.tray.ai",auth:"https://auth.ap1.tray.io"},login:{storePrefix:"AP1",appUrl:"https://app.ap1.tray.io",cookieName:"prod_tray_lid_ap",cookieDomain:"tray.io"}},E={name:"ap2",exposedName:"ap2",displayName:"ap2",hosts:{api:"https://api.ap2.tray.io",broker:"https://api.ap2.tray.io/private/v1/code",ingest:"https://api.ap2.tray.io/private/v1/helix/otlp",weaver:"https://weaver.ap2.tray.io",app:"https://app.ap2.tray.io",projectHost:"ap2.helix-app.ai",dashboard:"https://app.helix.ap2.tray.ai",auth:"https://auth.ap2.tray.io"},login:{storePrefix:"AP2",appUrl:"https://app.ap2.tray.io",cookieName:"prod_tray_lid_ap2",cookieDomain:"tray.io"}};s.set(h.name,h);s.set(v.name,v);s.set(x.name,x);s.set(E.name,E);var T=["api","broker","ingest","weaver","app","projectHost","dashboard"],N=["auth"],D=["storePrefix","appUrl","cookieName","cookieDomain"];function C(e){if(!e.name||typeof e.name!="string")throw new Error("RegionProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("RegionProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("RegionProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("RegionProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("RegionProfile.login must be an object");for(let r of T)if(typeof e.hosts[r]!="string"||!e.hosts[r])throw new Error(`RegionProfile.hosts.${r} must be a non-empty string`);for(let r of N){let t=e.hosts[r];if(t!==void 0&&(typeof t!="string"||!t))throw new Error(`RegionProfile.hosts.${r} must be a non-empty string when set`)}for(let r of D)if(typeof e.login[r]!="string"||!e.login[r])throw new Error(`RegionProfile.login.${r} must be a non-empty string`)}function j(e,r){return e.name===r.name&&e.exposedName===r.exposedName&&e.displayName===r.displayName&&T.every(t=>e.hosts[t]===r.hosts[t])&&N.every(t=>e.hosts[t]===r.hosts[t])&&D.every(t=>e.login[t]===r.login[t])}function oe(e){C(e);let r=s.get(e.name);if(r){if(j(r,e))return;throw new Error(`RegionProfile.name "${e.name}" is already registered with different values`)}for(let t of s.values())if(t.exposedName===e.exposedName)throw new Error(`RegionProfile.exposedName "${e.exposedName}" is already used by "${t.name}"`);s.set(e.name,e)}function H(e){return s.has(e)}function se(e){return s.get(e)}function m(e){let r=s.get(e);if(!r)throw new Error(`Unknown region: ${e}`);return r}function ae(){return[...s.keys()]}function de(){return[...s.values()].map(e=>e.exposedName)}function F(e){for(let r of s.values())if(r.exposedName===e)return r.name}var f=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function B(e){let r=globalThis;if(e===void 0||e.trim()===""){delete r[f];return}let t=e.trim(),n=F(t);if(n){r[f]=n;return}if(H(t)){r[f]=t;return}throw new Error(`Unknown region: ${t}`)}function le(){return globalThis[f]}function ue(){return[...s.values()].filter(e=>!O.has(e.name))}function ce(){B(void 0),s.clear();for(let e of[h,v,x,E])s.set(e.name,{...e,hosts:{...e.hosts},login:{...e.login}})}var u=class e extends Error{detail;constructor(r){super(L(r)),this.name="SdkError",this.detail=r}get kind(){return this.detail.kind}static unknownAlias(r,t){return new e({kind:"unknown_alias",alias:r,available:t})}static inputValidationFailed(r){return new e({kind:"input_validation_failed",fields:r})}static outputValidationFailed(r){return new e({kind:"output_validation_failed",fields:r})}static configLoadFailed(r){return new e({kind:"config_load_failed",cause:r})}static brokerError(r,t,n,i){return new e({kind:"broker_error",status:r,message:t,body:n,code:i})}static unsupportedBodyType(r){return new e({kind:"unsupported_body_type",actualType:r})}static unsupportedScheme(r){return new e({kind:"unsupported_scheme",scheme:r})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(r,t){return new e({kind:"db_call_failed",message:r,cause:t})}static dbQueryFailed(r){return new e({kind:"db_query_failed",message:r})}static dbInvalidParameters(r){return new e({kind:"db_invalid_parameters",message:r})}static kvKeyInvalid(r){return new e({kind:"kv_key_invalid",message:r})}static kvValueInvalid(r){return new e({kind:"kv_value_invalid",message:r})}static kvValueTooLarge(r,t){return new e({kind:"kv_value_too_large",message:r,maxBytes:t})}static kvTtlInvalid(r){return new e({kind:"kv_ttl_invalid",message:r})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(r,t,n){return new e({kind:"kv_call_failed",status:r,message:t,body:n})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(r){return new e({kind:"files_path_invalid",message:r})}static filesValueInvalid(r){return new e({kind:"files_value_invalid",message:r})}static filesValueTooLarge(r,t){return new e({kind:"files_value_too_large",message:r,maxBytes:t})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(r,t,n){return new e({kind:"files_call_failed",status:r,message:t,body:n})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}static callFunctionPathInvalid(r){return new e({kind:"call_function_path_invalid",message:r})}static callFunctionCallFailed(r,t,n){return new e({kind:"call_function_call_failed",status:r,message:t,body:n})}static callFunctionRequiresProvisioning(){return new e({kind:"call_function_requires_provisioning"})}static callFunctionNotAvailable(){return new e({kind:"call_function_not_available"})}static callFunctionMissingExecutionJwt(){return new e({kind:"call_function_missing_execution_jwt"})}static aiUnsupportedService(r,t,n){return new e({kind:"ai_unsupported_service",alias:r,service:t,supported:n})}static aiModelIdRequired(r,t){return new e({kind:"ai_model_id_required",alias:r,operation:t})}static aiModelInstanceRequired(r){return new e({kind:"ai_model_instance_required",modelId:r})}static aiProviderNotConfigured(r,t){return new e({kind:"ai_provider_not_configured",alias:r,supported:t})}static aiForeignModelRejected(){return new e({kind:"ai_foreign_model_rejected"})}static agentSessionsFailed(r){return new e({kind:"agent_sessions_failed",message:r})}};function ge(e){return e instanceof u}function L(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return e.code?`broker error: ${e.status} ${e.code}: ${e.message}`:`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_ttl_invalid":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)";case"call_function_path_invalid":return`Invalid function path: ${e.message}`;case"call_function_call_failed":return`Async function call failed: ${e.status} ${e.message}`;case"call_function_requires_provisioning":return"callFunctionAsync requires a provisioned project (run helix project set)";case"call_function_not_available":return"callFunctionAsync is not available: no running dev server was found";case"call_function_missing_execution_jwt":return"ctx.callFunctionAsync requires a helix project-execution JWT \u2014 a legacy internalJwt-only execution cannot call it";case"ai_unsupported_service":return`Authentication alias "${e.alias}" resolves to service "${e.service}", which ctx.ai does not support. Supported AI services: ${e.supported.join(", ")}`;case"ai_model_id_required":return`ctx.ai("${e.alias}").${e.operation} requires \`model\` as a string model id. To pass a model instance, use the top-level ctx.ai.${e.operation} instead.`;case"ai_model_instance_required":return`ctx.ai.* call functions require a model instance from ctx.ai(alias), got the string "${e.modelId}". Bare model ids would route outside the credentials broker and are not supported.`;case"ai_provider_not_configured":return`No AI provider configured for authentication alias "${e.alias}". Add \`aiProviders: { "${e.alias}": "<service>" }\` to helix.config.ts (supported services: ${e.supported.join(", ")}; openai-compatible needs the object form with baseUrl).`;case"ai_foreign_model_rejected":return"ctx.ai.* call functions require a model instance minted by ctx.ai(alias). A model built directly against a raw @ai-sdk/* provider carries its own transport and credentials, and would bypass the credentials broker, proxy policy, and metering.";case"agent_sessions_failed":return`Agent session store error: ${e.message}`}}import{z as g}from"zod";var A="x-helix-destination-url",U="x-helix-authentication-id",J="x-helix-deployment-id",_="x-execution-id",M="x-helix-broker-error",he="route_not_found",K=new Set([A,U,J,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id",_]);function V(e){let r=e.toLowerCase();return K.has(r)||r.startsWith("x-tray-internal-")}var w=g.object({error:g.object({code:g.string(),message:g.string(),issues:g.array(g.unknown()).optional()})});function ve(e,r){let t=`${m(e).hosts.api}/private/v1/helix/broker/http/raw`;return r==="dev"?`${t}/dev`:t}function xe(e){if(e.mode==="lambda"){let t=S(),n=P(),i=!!(t&&t.trim().length>0),o=!!(n&&n.trim().length>0);if(!i&&!o)throw u.missingExecutionCredentials();let a={};return i&&(a[R]=t),o&&(a[b]=n),{headers:a,deploymentId:e.deploymentId??null}}let r=I();if(!r)throw u.missingTrayToken();return{headers:{Authorization:`Bearer ${r}`},deploymentId:null}}function G(e){return typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream}function Ee(e){let r=new URL(e.url);if(r.protocol!=="https:")throw u.unsupportedScheme(r.protocol.replace(/:$/,""));if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[l,d]of e.query.entries())r.searchParams.append(l,d);else for(let[l,d]of Object.entries(e.query))for(let q of Array.isArray(d)?d:[d])r.searchParams.append(l,q);let t;e.headers===void 0?t=[]:e.headers instanceof Headers?t=Array.from(e.headers.entries()):Array.isArray(e.headers)?t=e.headers:t=Object.entries(e.headers);let n=t.filter(([l])=>!V(l)),i=e.body!==void 0&&e.body!==null,o,a,c=!1;return i&&(G(e.body)?(o=e.body,c=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(o=JSON.stringify(e.body),n.some(([d])=>d.toLowerCase()==="content-type")||(a="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:r.toString(),headers:n,body:o,isStreamBody:c,defaultContentType:a}}async function X(e,r){let t=await e.text(),n=t,i=t||r;try{n=JSON.parse(t);let o=w.safeParse(n);o.success&&(i=o.data.error.message)}catch{}return{status:e.status,code:r,message:i,body:n}}var Y=6e4;function z(e){return e.includes("json")}function W(e){return e.startsWith("text/")||e.includes("xml")||e.includes("urlencoded")||e.includes("javascript")||e.includes("ecmascript")}function Q(e,r){if(e.byteLength===0)return;let t=r.toLowerCase();if(z(t)){let n=new TextDecoder("utf-8").decode(e);try{return JSON.parse(n)}catch{return n}}return W(t)?new TextDecoder("utf-8").decode(e):e}function Z(e){let r={};for(let[t,n]of e.entries())r[t.toLowerCase()]=n;return r}async function we(e){let{request:r}=e,t=new Headers;for(let[l,d]of r.headers)t.append(l,d);r.defaultContentType&&!t.has("content-type")&&t.set("content-type",r.defaultContentType),t.set(A,r.destinationUrl),t.set(U,r.authenticationId);for(let[l,d]of Object.entries(e.credentialHeaders))t.set(l,d);e.executionId&&t.set(_,e.executionId);let n={method:r.method,headers:t,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??Y)};r.body!==void 0&&(n.body=r.body,r.isStreamBody&&(n.duplex="half"));let i=await fetch(e.proxyUrl,n),o=i.headers.get(M);if(o!==null)return{kind:"brokerError",...await X(i,o)};let a=new Uint8Array(await i.arrayBuffer()),c=i.headers.get("content-type")??"";return{kind:"upstream",response:{status:i.status,headers:Z(i.headers),body:Q(a,c)}}}import{z as y}from"zod";var ee=3e4;function Te(e){let r=new URL(e);if(r.protocol!=="https:")throw u.unsupportedScheme(r.protocol.replace(/:$/,""))}function Ne(e,r){let t=`${m(e).hosts.api}/private/v1/helix/broker/s3/sign`;return r==="dev"?`${t}/dev`:t}var re=y.object({url:y.string(),method:y.string(),expiresAt:y.string()});async function De(e){let r=new Headers({"content-type":"application/json"});for(let[a,c]of Object.entries(e.credentialHeaders))r.set(a,c);e.executionId&&r.set(_,e.executionId);let t=await fetch(e.signUrl,{method:"POST",headers:r,body:JSON.stringify(e.body),redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??ee)}),n=await t.text(),i=n;try{i=JSON.parse(n)}catch{}if(t.ok){let a=re.safeParse(i);return a.success?{kind:"signed",result:a.data}:{kind:"brokerError",status:t.status,message:"malformed s3-sign response from credential broker",body:i}}let o=w.safeParse(i);return o.success?{kind:"brokerError",status:t.status,code:o.data.error.code,message:o.data.error.message,body:i}:{kind:"brokerError",status:t.status,message:n||`s3-sign request failed with status ${t.status}`,body:i}}export{b as a,R as b,te as c,ne as d,S as e,P as f,oe as g,H as h,se as i,m as j,ae as k,de as l,F as m,B as n,le as o,ue as p,ce as q,u as r,ge as s,A as t,U as u,J as v,_ as w,M as x,he as y,V as z,w as A,ve as B,xe as C,Ee as D,X as E,Y as F,we as G,Te as H,Ne as I,De as J};
@@ -1,7 +0,0 @@
1
- import{a as mn,b as ze}from"./chunk-WUCX7RZO.js";import{A as yn,B as pe,C as z,D as ne,E as hn,G as wn,H as Sn,I as bn,J as vn,a as U,b as le,d as A,e as de,f as $,h as un,j,k as pn,o as fn,r as d,t as Ie,u as Ge,v as te,w as Re,x as Je,y as ue,z as gn}from"./chunk-3T2WZMJJ.js";var rc="tray-config-bridge",oc="tray-dev-token-bridge",We=null;function sc(e){We=e}function x(){if(!We)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return We}function ic(){We=null}import{AsyncLocalStorage as Bn}from"async_hooks";import{trace as cs,SpanKind as ls,SpanStatusCode as et}from"@opentelemetry/api";import{ExportResultCode as ds,W3CTraceContextPropagator as us}from"@opentelemetry/core";import{NodeTracerProvider as ps,SimpleSpanProcessor as fs,BatchSpanProcessor as ms}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Jo}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Wo}from"@opentelemetry/exporter-logs-otlp-proto";function Ct(e){return j(e).hosts.ingest}function Xo(){return $()??""}function xn(){return{[U]:Xo()}}function An(){let e=Ct(x().region);return new Jo({url:`${e}/v1/traces`,headers:()=>Promise.resolve(xn())})}function En(){let e=Ct(x().region);return new Wo({url:`${e}/v1/logs`,headers:()=>Promise.resolve(xn())})}import{logs as Cn,SeverityNumber as Xe}from"@opentelemetry/api-logs";import{LoggerProvider as Zo,BatchLogRecordProcessor as es}from"@opentelemetry/sdk-logs";function Ce(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Yo(e){return new TextEncoder().encode(e).length}var In="\u2026[truncated]",Qo=Yo(In),Te=4096;function re(e,t=Te){let n=new TextEncoder().encode(e);if(n.length<=t)return e;let r=n.subarray(0,t-Qo);return new TextDecoder("utf-8").decode(r).replace(/�$/,"")+In}function k(e,t=Te){return re(Ce(e),t)}var ts="@trayai/helix-sdk",ke,Rn={debug:{number:Xe.DEBUG,text:"DEBUG"},info:{number:Xe.INFO,text:"INFO"},warn:{number:Xe.WARN,text:"WARN"},error:{number:Xe.ERROR,text:"ERROR"}};function ns(){return A().mode==="lambda"?[new es({exporter:En()})]:[]}function Tn(){if(ke!==void 0)return;let e=ns();e.length!==0&&(ke=new Zo({processors:e}),Cn.setGlobalLoggerProvider(ke))}function rs(e,t,n){let r=Rn[e]??Rn.info;return{severityNumber:r.number,severityText:r.text,body:t,...n?{attributes:{"tray.log.meta":k(n)}}:{}}}function kn(e,t,n){Cn.getLogger(ts).emit(rs(e,t,n))}async function Pn(e=2e3){if(ke===void 0)return;let t;try{await Promise.race([ke.forceFlush(),new Promise(n=>{t=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel log flush failed: ${n instanceof Error?n.message:String(n)}
2
- `)}finally{t!==void 0&&clearTimeout(t)}}function Tt(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function os(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function D(e,t){return os()?`\x1B[${e}m${t}\x1B[0m`:t}var ss=5,is={FN:"1;35",INFO:"34",AUTH:"35",API:"36",AGENT:"1;36",TOOL:"36",WARN:"33",ERROR:"31",DEBUG:"90"},Ye="32",Qe="31",as="33",oe="2",Ze="1";function se(e){return D(is[e]??"0",e.padEnd(ss))}function On(e,t){return`${se("FN")} ${D(Ze,`${e} ${t}`.trim())}`}function _n(e,t,n,r){let o=e.toUpperCase(),i=`${r?`${D(oe,r)} `:""}${se(o)} ${t}`;return n&&Object.keys(n).length>0&&(i+=` ${D(oe,Ce(n))}`),i}function Dn(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Mn(e){return`${se("AUTH")} ${e}`}function Fn(e,t,n,r,o){let s=n===void 0?"ERR":String(n),i=D(o==="error"?Qe:Ye,s);return`${se("API")} ${e} ${t} \u2192 ${i} ${D(oe,`${r}ms`)}`}function Ln(e){return`${se("AGENT")} ${D(Ze,e)}`}function Nn(e,t,n,r){let o=t==="error"?Qe:t==="awaiting-approval"?as:Ye,s=n!==void 0?`${D(oe,`${n} step${n===1?"":"s"}`)} `:"";return`${se("AGENT")} ${D(Ze,e)} \u2192 ${D(o,t)} ${s}${D(oe,`${r}ms`)}`}function Un(e,t,n){let r=t==="error"?D(Qe,"error"):D(Ye,"ok");return`${se("TOOL")} ${e} \u2192 ${r} ${D(oe,`${n}ms`)}`}function $n(e,t,n){let r=t?Qe:Ye,o=D(r,"\u25CF"),s=D(r,t?"error":"success");return`${o} ${D(Ze,e)} ${s} ${D(oe,`${n}ms`)}`}function H(e){try{process.stdout.write(e+`
3
- `)}catch{}}var Kn=new Bn,gs=new Bn;function O(e){let t=gs.getStore();t&&(t[e]=!0)}var ys=/^[0-9a-f]{32}$/;function hs(e){let t=e.replace(/-/g,"").toLowerCase();return ys.test(t)?t:null}var ws={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},fe=new Map;function Hn(e,t,n){let r=fe.get(e);r?r[t]=n:fe.set(e,{[t]:n})}function q(e,t,n){e.setAttribute(t,k(n))}var Pe;function jn(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function kt(e){return Math.round(e[0]*1e3+e[1]/1e6)}function qn(e){try{process.stdout.write(Ce(e)+`
4
- `)}catch{}}var Pt=class{export(t,n){for(let r of t){let o=r.spanContext().spanId,s=fe.get(o),i={...r.attributes};if(s!==void 0){for(let[l,u]of Object.entries(s))typeof u=="string"?i[l]=re(u):typeof u=="object"&&u!==null?i[l]=k(u):i[l]=u;fe.delete(o)}let a=Kn.getStore(),c=a?hs(a):null;qn({_otel:"span",traceId:c??r.spanContext().traceId,spanId:o,parentSpanId:r.parentSpanContext?.spanId??"",name:r.name,kind:r.kind,startTimeUnixNano:jn(r.startTime),endTimeUnixNano:jn(r.endTime),attributes:i,status:{code:ws[r.status.code]??"STATUS_CODE_UNSET",...r.status.message?{message:re(r.status.message)}:{}}})}n({code:ds.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ot=class{onStart(t,n){}onEnd(t){fe.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},_t=class{onStart(t){let n=t;(n.name==="function"||n.name==="App")&&H(`
5
- `+On(String(n.attributes.method??""),String(n.attributes.route??""))),(n.name==="agent.generate"||n.name==="agent.stream")&&H(Ln(String(n.attributes.agent??"")))}onEnd(t){let n=t.attributes;switch(t.name){case"log":{let r=t.spanContext().spanId,o=fe.get(r)?.properties;H(_n(String(n.level??"info"),String(n.message??""),o,Dn(t.startTime)));break}case"auth":H(Mn(String(n.alias??"")));break;case"externalApi":{let r=typeof n.statusCode=="number"?n.statusCode:void 0;H(Fn(String(n.method??""),String(n.host??""),r,kt(t.duration),n.status==="error"?"error":"success"));break}case"agent.tool":{H(Un(String(n.tool??""),n.status==="error"?"error":"success",kt(t.duration)));break}case"agent.generate":case"agent.stream":{let r=typeof n.status=="string"?n.status:t.status.code===et.ERROR?"error":"completed";H(Nn(String(n.agent??""),r,typeof n.steps=="number"?n.steps:void 0,kt(t.duration)));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Dt=class{constructor(t){this.inner=t}inner;onStart(t,n){this.inner.onStart(t,n)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function Ss(){let t=[Tt()?new _t:new fs(new Pt)];return A().mode==="lambda"&&t.push(new Dt(new ms(An()))),t.push(new Ot),t}function bs(){Pe===void 0&&(Pe=new ps({spanProcessors:Ss()}),Pe.register({propagator:new us}),Tn())}async function vs(e=2e3){let t=[Pn(e)];Pe!==void 0&&t.push((async()=>{let n;try{await Promise.race([Pe.forceFlush(),new Promise(r=>{n=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel flush failed: ${r instanceof Error?r.message:String(r)}
6
- `)}finally{n!==void 0&&clearTimeout(n)}})()),await Promise.all(t)}var F=cs.getTracer("@trayai/helix-sdk");function xs({executionId:e,deploymentId:t,triggerType:n="http",routeOrJob:r,startedAt:o,startMs:s,errored:i,errorMessage:a,userId:c,flags:l}){let u=new Date().toISOString(),p=Date.now()-s;if(Tt()){H(`
7
- `+$n(r,i,p));return}qn({_otel:"summary",executionId:e,deploymentId:t,triggerType:n,routeOrJob:r,status:i?"error":"success",startedAt:o,finishedAt:u,durationMs:p,userId:c,hasError:i||l.hasError,hasAuth:l.hasAuth,hasAi:l.hasAi,hasExternal:l.hasExternal,hasDb:l.hasDb,errorSummary:i&&a!==null?re(a):null})}async function Mc(e,t){let n=e.startMs??Date.now();bs();let r=!1,o=null;try{return await Kn.run(e.executionId,()=>F.startActiveSpan("App",{kind:ls.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async s=>{try{let i=await t(),a=i?.httpResponse?.status??404;return r=a>=400,s.setAttribute("http.response.status_code",a),s.setAttribute("helix.status",r?"error":"success"),s.setStatus({code:r?et.ERROR:et.OK}),i}catch(i){throw r=!0,o=i instanceof Error?i.message:String(i),s.setAttribute("http.response.status_code",500),s.setAttribute("helix.status","error"),s.setStatus({code:et.ERROR,message:o}),i}finally{s.end()}}))}finally{xs({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:n,errored:r,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1}}),await vs()}}var Gn=1024,G=100*1024*1024,Vn=250,As=3600,Es=As*1e3,zn=new TextEncoder,Is=/(^|\/)\.\.(\/|$)/,Rs=/[?#]/;function Cs(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}function ie(e,t=Gn){if(e.length===0)throw d.filesPathInvalid("Path must be a non-empty string");tt(e,t)}function Mt(e){return e.endsWith("/")?e.slice(0,-1):e}function tt(e,t=Gn){if(e.length===0)return;if(Is.test(e))throw d.filesPathInvalid("Path contains path traversal segment");if(Rs.test(e)||Cs(e))throw d.filesPathInvalid("Path contains illegal characters");let n=e.split("/");if(e.startsWith("/")||e.endsWith("/")||n.some(o=>o===""))throw d.filesPathInvalid("Path must not contain empty path segments");for(let o of n){let s=zn.encode(o).length;if(s>Vn)throw d.filesPathInvalid(`Path segment exceeds ${Vn} UTF-8 bytes (got ${s})`)}let r=zn.encode(e).length;if(r<1||r>t)throw d.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${r})`)}function Jn(e){if(e>G)throw d.filesValueTooLarge(`File exceeds maximum size of ${G} bytes (got ${e})`,G)}function me(e){let t=e!==void 0?e*1e3:Es;return new Date(Date.now()+t)}import{join as _e}from"path";var Ts="files",ks="files-meta",Ps=1023,Os=1,_s=5;function Wn(e){let t=Math.max(Buffer.byteLength(nt(e),"utf8"),Buffer.byteLength(Oe(e),"utf8"));return Math.max(0,Ps-t-Os-_s)}function nt(e){return _e(e,".helix",Ts)}function Oe(e){return _e(e,".helix",ks)}function De(e,t){return _e(nt(e),...t.split("/"))}function rt(e,t){return _e(Oe(e),...t.split("/"))+".json"}function ot(e,t){return t.length===0?nt(e):De(e,t)}function Xn(e,t){return t.length===0?Oe(e):_e(Oe(e),...t.split("/"))}import{z as Ds}from"zod";var Kc=["us1","eu1","ap1","ap2"],Ft=Ds.string().refine(e=>un(e),e=>({message:`Invalid enum value. Expected ${pn().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));import{resolve as J}from"path";import{existsSync as st,realpathSync as Yn}from"fs";import{loadConfig as Ms}from"c12";import{z as b}from"zod";var Zn=b.string().uuid("projectId must be a valid UUID"),er=b.string().min(1,"workspaceId must be a non-empty string"),tr=b.discriminatedUnion("store",[b.object({store:b.literal("managed")}),b.object({store:b.literal("dynamodb"),auth:b.string().min(1,"agentSessions.auth is required"),table:b.string().min(1,"agentSessions.table is required"),region:b.string().min(1,"agentSessions.region is required")})]),Me=["openai","anthropic","google","mistral","cohere","openai-compatible"],Fs=["openai","anthropic","google","mistral","cohere"],nr=b.union([b.enum(Fs),b.object({service:b.enum(Me),baseUrl:b.string().url().optional()}).refine(e=>e.service!=="openai-compatible"||e.baseUrl!==void 0,{message:'aiProviders: baseUrl is required when service is "openai-compatible"'}).refine(e=>e.baseUrl===void 0?!0:new URL(e.baseUrl).protocol==="https:",{message:"aiProviders: baseUrl must use https \u2014 ctx.ai requests route through the credentials broker's proxy, which rejects non-https destinations on every call (a plain-http endpoint, e.g. a local Ollama/vLLM instance over http, is not supported)"})]),Ls=b.object({name:b.string().min(1,"name is required"),projectId:Zn.optional(),workspaceId:er.optional(),region:Ft.optional(),env:b.literal("production").optional(),authentications:b.record(b.string()).optional().default({}),config:b.record(b.unknown()).optional().default({}),agentSessions:tr.optional(),aiProviders:b.record(nr).optional()}).transform(({env:e,region:t,...n})=>({...n,region:t??"us1"})),Qn=b.object({name:b.string().min(1,"name is required"),workspaceId:er.optional(),region:Ft,authentications:b.record(b.string()),config:b.record(b.unknown()),agentSessions:tr.optional(),aiProviders:b.record(nr).optional()}),Yc=b.discriminatedUnion("kind",[Qn.extend({kind:b.literal("provisioned"),projectId:Zn}),Qn.extend({kind:b.literal("unprovisioned")})]),rr=["helix","tray"],or=["ts","mts","cts","js","mjs","cjs"],sr="HELIX_CONFIG";function Lt(e){let t=e?.trim();return t||process.env[sr]?.trim()||void 0}function Ns(e,t){let n=Lt(t?.configFile);if(n!==void 0){let r=J(e,n);return st(r)?r:void 0}for(let r of rr)for(let o of or){let s=J(e,`${r}.config.${o}`);if(st(s))return s}}function Us(e){for(let t of rr)if(or.some(n=>st(J(e,`${t}.config.${n}`))))return t;return"helix"}function $s(e,t){return J(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function js(e,t){let n=Lt(t?.configFile);return{name:Us(e),cwd:e,...n!==void 0?{configFile:$s(e,n)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function Bs(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw d.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let n=Ls.safeParse(e);if(!n.success){let l=n.error.issues.map(u=>u.message).join("; ");throw d.configLoadFailed(`Invalid helix.config.ts at ${t}: ${l}`)}let{projectId:r,workspaceId:o,...s}=n.data,i=o!==void 0?{workspaceId:o}:{},a=fn(),c=a!==void 0?{...s,region:a}:s;return r!==void 0?{kind:"provisioned",projectId:r,...c,...i}:{kind:"unprovisioned",...c,...i}}async function Qc(e,t){let n=e??process.cwd(),r=Lt(t?.configFile),o=r!==void 0?J(n,r):void 0;if(o!==void 0&&!st(o)){let a=t?.configFile?.trim()?"":` (from ${sr})`;throw d.configLoadFailed(`Config file not found: ${o}${a}`)}let s;try{s=await Ms(js(n,t))}catch(a){throw d.configLoadFailed(`Failed to load helix.config.ts: ${a instanceof Error?a.message:String(a)}`)}let i=s._configFile??Ns(n,t);if(!i)throw d.configLoadFailed(`helix.config.ts not found at ${J(n,"helix.config.ts")}`);if(o!==void 0&&s._configFile!==void 0){let a=Yn(o);if(Yn(J(s._configFile))!==a)throw d.configLoadFailed(`Config file conflict: requested ${o} but ${J(s._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return Bs(s.config,i)}var Ks="WORKSPACE_ID_REQUIRED";function Zc(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:Ks});return e.workspaceId}var ir="helix-tool",Hs=/^[a-z][a-z0-9_]{0,63}$/;function rl(e){if(typeof e.name!="string"||!Hs.test(e.name))throw new Error(`defineTool: invalid tool name ${JSON.stringify(e.name)} \u2014 use snake_case (e.g. "lookup_customer")`);if(typeof e.description!="string"||e.description.trim().length===0)throw new Error(`defineTool("${e.name}"): description is required`);if(!e.input||typeof e.input.safeParse!="function")throw new Error(`defineTool("${e.name}"): input must be a Zod schema`);if(typeof e.handler!="function")throw new Error(`defineTool("${e.name}"): handler must be a function`);let t=async(r,o)=>{let s=e.input.safeParse(r);if(!s.success)throw d.inputValidationFailed(s.error.issues.map(i=>i.path.join(".")||"(root)"));return e.handler({...o,input:s.data})},n=(async r=>t(r,ze()));return Object.defineProperties(n,{kind:{value:ir,enumerable:!0},name:{value:e.name,enumerable:!0},description:{value:e.description,enumerable:!0},inputSchema:{value:e.input,enumerable:!0},needsApproval:{value:e.needsApproval,enumerable:!0},execute:{value:t,enumerable:!0}}),n}function ar(e){return typeof e=="function"&&e.kind===ir&&typeof e.name=="string"}var I=class extends Error{constructor(t){super(t),this.name="AgentCallerError"}};import{readFileSync as qs}from"fs";import{isAbsolute as Vs,resolve as zs}from"path";var B=new Map;function cr(e){B.set(e.name,{definition:e});for(let t of B.values())t.referencesValidated=void 0}function ll(e,t){let n=B.get(e);n&&(n.baseDir=t,n.resolvedInstructions=void 0)}function dl(e,t){let n=B.get(e);n&&(n.resolvedInstructions=t)}function Fe(e){let t=B.get(e);if(!t){let n=[...B.keys()].sort();throw new I(`Unknown agent "${e}". Registered agents: ${n.join(", ")||"(none \u2014 are the functions/_agents/ modules imported?)"}`)}return t.definition}function ul(){return[...B.values()].map(e=>e.definition)}function lr(e){let t=B.get(e);if(!t)throw new I(`Unknown agent "${e}"`);if(t.resolvedInstructions!==void 0)return t.resolvedInstructions;let{definition:n}=t;if(n.instructions!==void 0)return t.resolvedInstructions=n.instructions,n.instructions;let r=n.instructionsFile,o=Vs(r)?r:t.baseDir!==void 0?zs(t.baseDir,r):void 0;if(o===void 0)throw new Error(`Agent "${e}" uses instructionsFile "${r}" but its base directory is unknown \u2014 load the agent through helix dev (which records it), or use inline \`instructions\`.`);let s;try{s=qs(o,"utf-8")}catch(i){throw new Error(`Agent "${e}": failed to read instructionsFile ${o}: ${i instanceof Error?i.message:String(i)}`)}if(s.trim().length===0)throw new Error(`Agent "${e}": instructionsFile ${o} is empty`);return t.resolvedInstructions=s,s}function dr(e){let t=B.get(e);if(t?.referencesValidated)return;let n=Fe(e);for(let r of n.agents??[]){let s=(Fe(r).tools??[]).filter(i=>i.needsApproval);if(s.length>0)throw new Error(`Agent "${e}" delegates to "${r}", which has needsApproval tools (${s.map(i=>i.name).join(", ")}) \u2014 approval cannot pause a parent's loop through delegation in v1. Put approval-gated tools on the orchestrating agent.`)}t&&(t.referencesValidated=!0)}function pl(){B.clear()}import{z as P}from"zod";var ur="helix-agent",Gs=/^[a-z][a-z0-9-]{0,63}$/,Js=P.object({model:P.string().min(1),auth:P.string().min(1)}),Ws=P.object({name:P.string().regex(Gs,'agent name must be kebab-case (e.g. "support-agent"); name is required in v1'),description:P.string().min(1,"description is required"),model:P.string().min(1,"model is required"),auth:P.string().min(1,"auth (authentication alias) is required"),fallbacks:P.array(Js).optional(),instructions:P.string().min(1).optional(),instructionsFile:P.string().min(1).optional(),tools:P.array(P.custom(ar,"tools entries must be defineTool exports")).optional(),agents:P.array(P.string().min(1)).optional(),memory:P.object({maxSessionMessages:P.number().int().positive().optional(),ttl:P.number().int().positive().optional(),scope:P.enum(["user","project"]).optional()}).optional(),limits:P.object({maxIterations:P.number().int().positive().optional(),maxToolCalls:P.number().int().positive().optional()}).optional()}).refine(e=>e.instructions===void 0!=(e.instructionsFile===void 0),{message:"exactly one of instructions / instructionsFile must be set"}),pr=200,fr=25,mr=50,Nt=3;function hl(e){let t=Ws.safeParse(e);if(!t.success){let o=typeof e?.name=="string"?e.name:"(unnamed)",s=t.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new Error(`defineAgent(${o}): invalid definition \u2014 ${s}`)}let n=new Set;for(let o of t.data.tools??[]){if(n.has(o.name))throw new Error(`defineAgent(${t.data.name}): duplicate tool "${o.name}"`);n.add(o.name)}let r={kind:ur,...t.data};return cr(r),r}function wl(e){return typeof e=="object"&&e!==null&&e.kind===ur&&typeof e.name=="string"}var Xs=50,gr=500;function Le(e){let t=e?.limit??Xs;if(!Number.isInteger(t)||t<1||t>gr)throw new I(`session.page(): limit must be an integer from 1 to ${gr}.`);let n=e?.order??"asc";if(n!=="asc"&&n!=="desc")throw new I('session.page(): order must be "asc" or "desc".');return{limit:t,order:n,cursor:e?.cursor}}function $t(){return new I("session.page(): invalid cursor \u2014 pass the `nextCursor` of the previous page, with the same `order`.")}var W=new Map;function jt(e,t,n){let r=encodeURIComponent;return n!==void 0?`agent:${r(e)}:user:${r(n)}:session:${r(t)}`:`agent:${r(e)}:session:${r(t)}`}function Ys(e,t,n){let r=Math.max(0,e.length-t);for(let s=r;s<e.length;s++)if(e[s]?.role==="user")return e.slice(s);for(let s=r-1;s>=0;s--)if(e[s]?.role==="user")return e.slice(s);if(!n)return;let o=r;for(;o<e.length&&e[o]?.role==="tool";)o++;return e.slice(o)}var Qs=32;async function Bt(e,t){let n=t+Qs;for(;;){let r=await e.messages({limit:n}),o=Ys(r,t,r.length<n);if(o!==void 0)return o;n*=2}}function Kt(e,t){return e.ttlSeconds!==void 0&&t-e.lastActiveAt>e.ttlSeconds*1e3}var Zs=6e4,Ut=0;function ei(e){if(!(e-Ut<Zs)){Ut=e;for(let[t,n]of W)if(Kt(n,e)){if(n.pendingApprovals.length>0){n.messages=[];continue}W.delete(t)}}}var X=class extends Error{constructor(t){super(`Agent session "${t}" has expired (session-expired)`),this.name="SessionExpiredError"}};function yr(e,t,n,r){let o=Date.now();ei(o);let s=n?.ttl,i=t??`ses_${crypto.randomUUID().replaceAll("-","")}`,a=jt(e,i,r),c=W.get(a);if(c&&(c.ttlSeconds=s),c&&Kt(c,o)){if(W.delete(a),c.pendingApprovals.length>0)throw new X(i);c=void 0}c||(c={id:i,agentName:e,...r!==void 0?{ownerUserId:r}:{},messages:[],createdAt:o,lastActiveAt:o,pendingApprovals:[],ttlSeconds:s},W.set(a,c));let l=c,u=()=>{l.lastActiveAt=Date.now()};return{id:i,async messages(p){u();let f=l.messages;return p?.limit!==void 0?f.slice(-p.limit):[...f]},async page(p){let{limit:f,order:m,cursor:S}=Le(p);u();let E=S===void 0?0:Number(S);if(!Number.isInteger(E)||E<0)throw $t();let g=m==="desc"?[...l.messages].reverse():l.messages,h=g.slice(E,E+f),y=E+h.length;return{messages:h,nextCursor:y<g.length?String(y):null}},async append(...p){u(),l.messages.push(...p)},async clear(){W.delete(a)},async truncated(){return!1},async pendingApprovals(){return u(),[...l.pendingApprovals]},async addPendingApprovals(p){u(),l.pendingApprovals.push(...p)},async resolveApproval(p){u();let f=l.pendingApprovals.findIndex(m=>m.approvalId===p);return f===-1?"already-resolved":(l.pendingApprovals.splice(f,1),"resolved")}}}function hr(e,t,n={}){let r=Date.now(),o=n.first??20,s=n.cursor!==void 0&&Number.parseInt(n.cursor,10)||0,i=[...W.values()].filter(c=>c.agentName===e&&c.ownerUserId===t&&!Kt(c,r)).sort((c,l)=>l.lastActiveAt-c.lastActiveAt);return{sessions:i.slice(s,s+o).map(c=>({id:c.id,createdAt:c.createdAt,lastActivityAt:c.lastActiveAt,messageCount:c.messages.length,pendingApprovals:c.pendingApprovals.length})),nextCursor:s+o<i.length?String(s+o):null}}function vl(){W.clear(),Ut=0}import{AsyncLocalStorage as Ei}from"async_hooks";import{z as zr}from"zod";import{generateText as Ii,streamText as Ri,tool as Gr,stepCountIs as Ci}from"ai";import{SpanKind as zt,SpanStatusCode as Se,context as Jr,trace as Ti}from"@opentelemetry/api";import{embed as xr,embedMany as Ar,generateImage as Er,generateObject as Ir,generateSpeech as Rr,generateText as Cr,streamObject as Tr,streamText as kr,transcribe as Pr}from"ai";import{SpanKind as ui,SpanStatusCode as vr}from"@opentelemetry/api";import{createOpenAI as oi}from"@ai-sdk/openai";import{createAnthropic as si}from"@ai-sdk/anthropic";import{createGoogle as ii}from"@ai-sdk/google";import{createMistral as ai}from"@ai-sdk/mistral";import{createCohere as ci}from"@ai-sdk/cohere";import{createOpenAICompatible as li}from"@ai-sdk/openai-compatible";var ti=new Set(["x-api-key","x-goog-api-key"]);function ni(e){return gn(e)||ti.has(e.toLowerCase())}function ri(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function wr(e){return async(t,n)=>{let r=ri(t),o=new URL(r);if(o.protocol!=="https:")throw d.unsupportedScheme(o.protocol.replace(/:$/,""));let s=A(),{region:i}=x(),a=new Headers(n?.headers??(t instanceof Request?t.headers:void 0)),c=new Headers;for(let[g,h]of a.entries())ni(g)||c.append(g,h);c.set(Ie,r),c.set(Ge,e),s.executionId&&c.set(Re,s.executionId);let{headers:l,deploymentId:u}=z(s);for(let[g,h]of Object.entries(l))c.set(g,h);u&&c.set(te,u);let p=pe(i,s.mode==="lambda"?"runtime":"dev"),f=n?.body??(t instanceof Request?t.clone().body:void 0),m={method:n?.method??(t instanceof Request?t.method:"GET"),headers:c,redirect:"manual",signal:n?.signal??void 0};f!=null&&(m.body=f,typeof ReadableStream<"u"&&f instanceof ReadableStream&&(m.duplex="half"));let S;try{S=await fetch(p,m)}catch(g){if(g instanceof Error&&g.name==="AbortError")throw g;let h=g instanceof Error?g.message??String(g):String(g);throw d.brokerError(0,h)}let E=S.headers.get(Je);if(E!==null){let g=await S.text(),h=g||E;try{let y=yn.safeParse(JSON.parse(g));y.success&&(h=y.data.error.message)}catch{}throw E===ue&&(h="credential broker does not support the raw proxy endpoint required by ctx.ai \u2014 deploy a newer broker or pin an older SDK"),d.brokerError(S.status,h,g||void 0,E)}return S}}var ge="helix-broker";function Sr(e){let{alias:t,service:n,baseUrl:r,authenticationId:o}=e,s=wr(o);switch(n){case"openai":return oi({apiKey:ge,fetch:s});case"anthropic":return si({apiKey:ge,fetch:s});case"google":return ii({apiKey:ge,fetch:s});case"mistral":return ai({apiKey:ge,fetch:s});case"cohere":return ci({apiKey:ge,fetch:s});case"openai-compatible":{if(!r)throw d.aiUnsupportedService(t,n,[...Me]);return li({name:t,baseURL:r,apiKey:ge,fetch:s})}}}var br={"gpt-4o-mini":{input:.15,output:.6},"gpt-4o":{input:2.5,output:10},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4.1":{input:2,output:8},"text-embedding-3-small":{input:.02,output:0},"text-embedding-3-large":{input:.13,output:0},"gpt-image-1":{input:5,output:40},"claude-opus-4":{input:15,output:75},"claude-sonnet-4":{input:3,output:15},"claude-haiku-4":{input:1,output:5},"claude-3-5-haiku":{input:.8,output:4},"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.3,output:2.5},"text-embedding-004":{input:0,output:0},"mistral-large":{input:2,output:6},"mistral-small":{input:.1,output:.3},"command-r-plus":{input:2.5,output:10},"command-r":{input:.15,output:.6}},di=Object.keys(br).sort((e,t)=>t.length-e.length);function it(e,t){let n=di.find(s=>e.startsWith(s));if(!n||!t)return{amount:0,currency:"USD"};let r=br[n],o=((t.inputTokens??0)*r.input+(t.outputTokens??0)*r.output)/1e6;return{amount:Number(o.toFixed(8)),currency:"USD"}}function L(e,t,n){return F.startActiveSpan("ai",{kind:ui.CLIENT},async r=>{r.setAttributes({operation:e.operation,model:e.model,...e.alias!==void 0?{alias:e.alias}:{}}),O("hasAi");try{let o=await t(),s=n?.(o);return s&&r.setAttributes({...s.inputTokens!==void 0?{inputTokens:s.inputTokens}:{},...s.outputTokens!==void 0?{outputTokens:s.outputTokens}:{}}),r.setAttribute("status","success"),r.setStatus({code:vr.OK}),o}catch(o){let s=o instanceof Error?o.message:String(o);throw r.setAttribute("status","error"),r.setStatus({code:vr.ERROR,message:s}),o}finally{r.end()}})}function pi(){return`aireq_${crypto.randomUUID().replaceAll("-","")}`}function he(e,t){return{cost:it(e,t),requestId:pi()}}function ae(e){return typeof e=="object"&&e!==null&&"modelId"in e?String(e.modelId):String(e)}var Or=new WeakSet;function ye(e){return Or.add(e),e}function _r(e){return ye(e)}function V(e){if(typeof e!="object"||e===null)throw d.aiModelInstanceRequired(typeof e=="string"?e:String(e));if(!Or.has(e))throw d.aiForeignModelRejected()}function at(e){return e.totalUsage??e.usage}function ct(e){return e.usage?.tokens!==void 0?{inputTokens:e.usage.tokens}:void 0}function lt(e){return e.usage}function Ht(e){let t=x(),n=t.authentications??{};if(!n[e])throw d.unknownAlias(e,Object.keys(n));let r=n[e],o=(t.aiProviders??{})[e];if(o===void 0)throw d.aiProviderNotConfigured(e,[...Me]);let{service:s,baseUrl:i}=typeof o=="string"?{service:o,baseUrl:void 0}:o,a=Sr({alias:e,service:s,baseUrl:i,authenticationId:r}),c=g=>ye(a.languageModel(g)),l=g=>ye(a.embeddingModel(g)),u=g=>ye(a.imageModel(g)),p=g=>{if(!a.transcriptionModel)throw new Error(`AI provider "${s}" (alias "${e}") has no transcription models`);return ye(a.transcriptionModel(g))},f=g=>{if(!a.speechModel)throw new Error(`AI provider "${s}" (alias "${e}") has no speech models`);return ye(a.speechModel(g))},m=(g=>c(g)),S=(g,h)=>{let y=g.model;if(typeof y!="string")throw d.aiModelIdRequired(e,h);return y};return Object.assign(m,{specificationVersion:"v4",languageModel:c,embeddingModel:l,textEmbeddingModel:l,imageModel:u,transcriptionModel:p,speechModel:f,async generateText(g){let h=S(g,"generateText"),y=await L({operation:"generateText",model:h,alias:e},()=>Cr({...g,model:c(h)}),at);return Object.assign(y,{helix:he(h,at(y))})},streamText(g){let h=S(g,"streamText");return O("hasAi"),kr({...g,model:c(h)})},async generateObject(g){let h=S(g,"generateObject"),y=await L({operation:"generateObject",model:h,alias:e},()=>Ir({...g,model:c(h)}),v=>v.usage),w=y.usage;return Object.assign(y,{helix:he(h,w)})},streamObject(g){let h=S(g,"streamObject");return O("hasAi"),Tr({...g,model:c(h)})},async embed(g){let h=S(g,"embed");return L({operation:"embed",model:h,alias:e},()=>xr({...g,model:l(h)}),ct)},async embedMany(g){let h=S(g,"embedMany");return L({operation:"embedMany",model:h,alias:e},()=>Ar({...g,model:l(h)}),ct)},async generateImage(g){let h=S(g,"generateImage"),y=await L({operation:"generateImage",model:h,alias:e},()=>Er({...g,model:u(h)}),lt);return Object.assign(y,{helix:he(h,lt(y))})},async transcribe(g){let h=S(g,"transcribe");return L({operation:"transcribe",model:h,alias:e},()=>Pr({...g,model:p(h)}))},async generateSpeech(g){let h=S(g,"generateSpeech");return L({operation:"generateSpeech",model:h,alias:e},()=>Rr({...g,model:f(h)}))}})}function Gl(){let e=new Map;return Object.assign((r=>{let o=e.get(r);return o||(o=Ht(r),e.set(r,o)),o}),{async generateText(r){V(r.model);let o=ae(r.model),s=await L({operation:"generateText",model:o},()=>Cr(r),at);return Object.assign(s,{helix:he(o,at(s))})},streamText(r){return V(r.model),O("hasAi"),kr(r)},async generateObject(r){V(r.model);let o=ae(r.model),s=await L({operation:"generateObject",model:o},()=>Ir(r),a=>a.usage),i=s.usage;return Object.assign(s,{helix:he(o,i)})},streamObject(r){return V(r.model),O("hasAi"),Tr(r)},async embed(r){return V(r.model),L({operation:"embed",model:ae(r.model)},()=>xr(r),ct)},async embedMany(r){return V(r.model),L({operation:"embedMany",model:ae(r.model)},()=>Ar(r),ct)},async generateImage(r){V(r.model);let o=ae(r.model),s=await L({operation:"generateImage",model:o},()=>Er(r),lt);return Object.assign(s,{helix:he(o,lt(s))})},async transcribe(r){return V(r.model),L({operation:"transcribe",model:ae(r.model)},()=>Pr(r))},async generateSpeech(r){return V(r.model),L({operation:"generateSpeech",model:ae(r.model)},()=>Rr(r))}})}var qt=class extends Error{errors;constructor(t){super(`all ${t.length} models in the fallback chain failed \u2014 `+t.map(({modelId:n,error:r})=>`${n}: ${r instanceof Error?r.message:String(r)}`).join("; ")),this.name="FallbackExhaustedError",this.errors=t.map(n=>n.error)}};function Dr(e){if(e.length===0)throw new Error("createFallbackModel: at least one model required");if(e.length===1)return e[0];let t=e[0];async function n(r){let o=[];for(let s of e)try{return await r(s)}catch(i){if(i instanceof Error&&i.name==="AbortError")throw i;o.push({modelId:s.modelId,error:i})}throw new qt(o)}return{specificationVersion:"v4",provider:t.provider,modelId:t.modelId,get supportedUrls(){return Promise.resolve(t.supportedUrls)},doGenerate:r=>n(o=>o.doGenerate(r)),doStream:r=>n(o=>o.doStream(r))}}function Vt(e){let t=e.code===ue?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":e.message;throw d.brokerError(e.status,t,k(e.body),e.code)}async function we(e,t={}){let n=A(),{region:r}=x(),{headers:o,deploymentId:s}=z(n);s&&(o[te]=s);let i=pe(r,n.mode==="lambda"?"runtime":"dev"),a;try{a=await wn({proxyUrl:i,credentialHeaders:o,request:e,timeoutMs:t.timeout,executionId:n.executionId})}catch(c){let l=c instanceof Error?c.message??String(c):String(c);throw d.brokerError(0,l)}return a.kind==="brokerError"&&Vt(a),a.response}var fi=8,ut="msg#",mi="meta",Mr=25,Fr=3,gi=400*1024-1024;function yi(e){let t=new Set,n=new Set;for(let r of e)if(Array.isArray(r?.content))for(let o of r.content){if(typeof o!="object"||o===null)continue;let{type:s,approvalId:i,isAutomatic:a}=o;typeof i=="string"&&(s==="tool-approval-request"&&a!==!0&&t.add(i),s==="tool-approval-response"&&n.add(i))}for(let r of n)t.delete(r);return t}var N=e=>({S:e}),dt=e=>({N:String(e)});function Ne(e,t){let n=e?.[t]?.S;return typeof n=="string"?n:void 0}function Lr(e,t){let n=e?.[t]?.N;return typeof n=="string"?Number(n):void 0}function hi(e,t){return e?.[t]?.BOOL===!0}function Nr(e,t){let n=e?.[t]?.M;return typeof n=="object"&&n!==null?n:{}}function wi(e){return`${ut}${String(e).padStart(fi,"0")}`}function Si(e){let t=null;if(typeof e=="string")try{t=JSON.parse(e)}catch{return}else e!==null&&typeof e=="object"&&(t=e);let n=t?.__type;return typeof n=="string"?n.split("#").pop():void 0}function Ur(e){let{agentName:t,table:n,region:r,authenticationId:o}=e,s=e.options?.ttl,i=e.sessionId??`ses_${crypto.randomUUID().replaceAll("-","")}`,a=jt(t,i,e.ownerUserId),c={pk:N(a),sk:N(mi)};async function l(y,w){let v=ne({authenticationId:o,method:"POST",url:`https://dynamodb.${r}.amazonaws.com/`,body:w,headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${y}`}}),C,T;try{({status:C,body:T}=await we(v))}catch(R){throw R instanceof d?R:d.agentSessionsFailed(R instanceof Error?R.message:String(R))}if(C>=400){let R=Si(T);throw R==="ConditionalCheckFailedException"?new pt:d.agentSessionsFailed(`DynamoDB ${y} failed (${C}): ${R??JSON.stringify(T).slice(0,300)}`)}if(typeof T=="string")try{return JSON.parse(T)}catch{throw d.agentSessionsFailed(`DynamoDB ${y}: non-JSON response body`)}return T??{}}async function u(){return(await l("GetItem",{TableName:n,Key:c,ConsistentRead:!0})).Item}let p=!1;async function f(){p||(await m(),p=!0)}async function m(){let y=await u();if(!y){let v=await S({ascending:!0});if(v.length===0||await u())return;let C=v.map(T=>JSON.parse(Ne(T,"message")??"null"));if(await E(v.map(T=>({DeleteRequest:{Key:{pk:N(a),sk:T.sk}}}))),yi(C).size>0)throw new X(i);return}if(s===void 0)return;let w=Lr(y,"lastActiveAt")??0;if(!(Date.now()-w<=s*1e3)){if(Object.keys(Nr(y,"pendingApprovals")).length>0)throw new X(i);await g()}}async function S(y){let w=[],v;do{let C=await l("Query",{TableName:n,KeyConditionExpression:"pk = :pk AND begins_with(sk, :prefix)",ExpressionAttributeValues:{":pk":N(a),":prefix":N(ut)},ConsistentRead:!0,ScanIndexForward:y.ascending,...y.limit!==void 0?{Limit:y.limit}:{},...y.projection!==void 0?{ProjectionExpression:y.projection}:{},...v!==void 0?{ExclusiveStartKey:v}:{}});if(w.push(...C.Items??[]),v=C.LastEvaluatedKey,y.limit!==void 0&&w.length>=y.limit)break}while(v!==void 0);return w}async function E(y){for(let w=0;w<y.length;w+=Mr){let v=y.slice(w,w+Mr);for(let C=0;v.length>0;C++){let R=(await l("BatchWriteItem",{RequestItems:{[n]:v}})).UnprocessedItems?.[n];if(!R||R.length===0)break;if(C>=Fr)throw d.agentSessionsFailed(`DynamoDB BatchWriteItem: ${R.length} items still unprocessed after ${Fr} retries`);v=R}}}async function g(){let w=(await S({ascending:!0,projection:"sk"})).map(v=>({DeleteRequest:{Key:{pk:N(a),sk:v.sk}}}));w.push({DeleteRequest:{Key:c}}),await E(w)}async function h(y){let w=Date.now();return(await l("UpdateItem",{TableName:n,Key:c,UpdateExpression:"ADD nextSeq :reserve, messageCount :reserve SET lastActiveAt = :now, "+(s!==void 0?"expiresAt = :expires, ":"")+"createdAt = if_not_exists(createdAt, :now), truncated = if_not_exists(truncated, :false), pendingApprovals = if_not_exists(pendingApprovals, :emptyMap)"+(s===void 0?" REMOVE expiresAt":""),ExpressionAttributeValues:{":reserve":dt(y),":now":dt(w),...s!==void 0?{":expires":dt(Math.floor(w/1e3)+s)}:{},":false":{BOOL:!1},":emptyMap":{M:{}}},ReturnValues:"ALL_NEW"})).Attributes??{}}return{id:i,async messages(y){await f();let w=y?.limit;return w!==void 0?(await S({ascending:!1,limit:w})).reverse().map(T=>JSON.parse(Ne(T,"message")??"null")):(await S({ascending:!0})).map(C=>JSON.parse(Ne(C,"message")??"null"))},async page(y){let{limit:w,order:v,cursor:C}=Le(y);await f();let T;if(C!==void 0&&(T=Buffer.from(C,"base64url").toString("utf8"),!T.startsWith(ut)))throw $t();let R=await l("Query",{TableName:n,KeyConditionExpression:"pk = :pk AND begins_with(sk, :prefix)",ExpressionAttributeValues:{":pk":N(a),":prefix":N(ut)},ConsistentRead:!0,ScanIndexForward:v==="asc",Limit:w,...T!==void 0?{ExclusiveStartKey:{pk:N(a),sk:N(T)}}:{}}),ee=R.Items??[],Ve=Ne(R.LastEvaluatedKey,"sk");return{messages:ee.map(Go=>JSON.parse(Ne(Go,"message")??"null")),nextCursor:Ve!==void 0?Buffer.from(Ve,"utf8").toString("base64url"):null}},async append(...y){if(y.length===0)return;let w=y.map(ee=>JSON.stringify(ee)),v=w.findIndex(ee=>Buffer.byteLength(ee,"utf8")>gi);if(v!==-1)throw d.agentSessionsFailed(`a ${y[v].role} message of ${Buffer.byteLength(w[v],"utf8")} bytes exceeds DynamoDB's 400 KB item limit \u2014 the session store keeps one item per message; have tools summarise or offload (ctx.files) large results`);await f();let C=await h(y.length),R=(Lr(C,"nextSeq")??y.length)-y.length+1;await E(w.map((ee,Ve)=>({PutRequest:{Item:{pk:N(a),sk:N(wi(R+Ve)),message:N(ee)}}})))},async clear(){await g()},async truncated(){return await f(),hi(await u(),"truncated")},async pendingApprovals(){await f();let y=Nr(await u(),"pendingApprovals");return Object.values(y).map(w=>{let v=w.S;return v!==void 0?JSON.parse(v):void 0}).filter(w=>w!==void 0)},async addPendingApprovals(y){if(y.length===0)return;await f(),await h(0);let w={},v={},C=[];y.forEach((T,R)=>{w[`#a${R}`]=T.approvalId,v[`:v${R}`]=N(JSON.stringify(T)),C.push(`pendingApprovals.#a${R} = :v${R}`)}),await l("UpdateItem",{TableName:n,Key:c,UpdateExpression:`SET ${C.join(", ")}`,ExpressionAttributeNames:w,ExpressionAttributeValues:v})},async resolveApproval(y){await f();try{return await l("UpdateItem",{TableName:n,Key:c,UpdateExpression:"REMOVE pendingApprovals.#id SET lastActiveAt = :now",ConditionExpression:"attribute_exists(pendingApprovals.#id)",ExpressionAttributeNames:{"#id":y},ExpressionAttributeValues:{":now":dt(Date.now())}}),"resolved"}catch(w){if(w instanceof pt)return"already-resolved";throw w}}}}var pt=class extends Error{constructor(){super("ConditionalCheckFailedException"),this.name="ConditionalCheckFailed"}};import bi from"ky";async function K(e){let t=e.headers.get("content-type")??"",n=await e.text();if(n.length!==0)return t.includes("application/json")?JSON.parse(n):n}var vi=6e4,xi=500,$r=500;function jr(e){let t=x();if(t.kind!=="provisioned")throw d.agentSessionsFailed("the managed session store requires a provisioned project (projectId in helix.config.ts)");return`${j(t.region).hosts.api}/private/v1/helix/projects/${encodeURIComponent(t.projectId)}/storage/agent-sessions/${encodeURIComponent(e)}`}function Ai(){let e=de(),t=$(),n={Accept:"application/json"};if(e&&e.trim().length>0&&(n[le]=e),t&&t.trim().length>0&&(n[U]=t),Object.keys(n).length===1)throw d.missingExecutionCredentials();return n}async function Y(e,t,n){try{let r=await bi(t,{method:e,headers:Ai(),...n!==void 0?{json:n}:{},throwHttpErrors:!1,timeout:vi});return{status:r.status,body:await K(r)}}catch(r){throw r instanceof d?r:d.agentSessionsFailed(`managed session store unreachable: ${r instanceof Error?r.message:String(r)}`)}}function ft(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message}return String(e??"unknown error")}function ce(e,t,n){throw t===410?new X(e):t===404?new I(`Agent session "${e}" was not found (it may belong to a different user or have expired).`):d.agentSessionsFailed(`managed session store error ${t}: ${ft(n)}`)}function Br(e){let t=jr(e.agentName),n=e.sessionId??`ses_${crypto.randomUUID().replaceAll("-","")}`,r=e.options?.scope,o=e.options?.ttl,s=async c=>{let l=new URL(`${t}/${encodeURIComponent(n)}/messages`);c.first!==void 0&&l.searchParams.set("first",String(c.first)),c.cursor!==void 0&&l.searchParams.set("cursor",c.cursor),c.order!==void 0&&l.searchParams.set("order",c.order);let{status:u,body:p}=await Y("get",l.toString());if(u!==404){if(u===400&&c.cursor!==void 0)throw new I(`session.page(): ${ft(p)}`);return(u<200||u>=300)&&ce(n,u,p),p}},i=c=>c.elements.length<2||c.elements[0].id>c.elements[1].id,a=async()=>{let c=[],l;for(;;){let u=await s({...l!==void 0?{cursor:l}:{}});if(u===void 0)return[];if(c.push(...u.elements.map(p=>p.message)),!u.pageInfo.hasNextPage||u.pageInfo.endCursor===null)break;l=u.pageInfo.endCursor}return c};return{id:n,async messages(c){let l=c?.limit;if(l===void 0)return a();let u=[],p;for(;u.length<l;){let f=await s({order:"desc",first:Math.min(l-u.length,xi),...p!==void 0?{cursor:p}:{}});if(f===void 0)return[];if(!i(f))return(await a()).slice(-l);if(u.push(...f.elements.map(m=>m.message)),!f.pageInfo.hasNextPage||f.pageInfo.endCursor===null)break;p=f.pageInfo.endCursor}return u.slice(0,l).reverse()},async page(c){let{limit:l,order:u,cursor:p}=Le(c),f=await s({first:l,order:u,...p!==void 0?{cursor:p}:{}});if(f===void 0)return{messages:[],nextCursor:null};if(u==="desc"&&!i(f))throw d.agentSessionsFailed('the managed session store in this environment does not support newest-first paging yet \u2014 page with order: "asc", or read the latest messages with session.messages({ limit }).');return{messages:f.elements.map(m=>m.message),nextCursor:f.pageInfo.hasNextPage?f.pageInfo.endCursor:null}},async append(...c){if(c.length===0)return;let{status:l,body:u}=await Y("post",`${t}/${encodeURIComponent(n)}/messages`,{messages:c,...r!==void 0?{scope:r}:{},...o!==void 0?{ttl:o}:{}});(l<200||l>=300)&&ce(n,l,u)},async clear(){for(let c=0;c<$r;c++){let{status:l,body:u}=await Y("delete",`${t}/${encodeURIComponent(n)}`);if(l===204||l===404)return;if(!(l===200&&u?.more===!0)){if(l===200)return;ce(n,l,u)}}throw d.agentSessionsFailed(`clearing session "${n}" did not complete after ${$r} calls \u2014 call clear() again to continue.`)},async truncated(){let{status:c,body:l}=await Y("get",`${t}/${encodeURIComponent(n)}`);return c===404?!1:((c<200||c>=300)&&ce(n,c,l),l.truncated===!0)},async pendingApprovals(){let{status:c,body:l}=await Y("get",`${t}/${encodeURIComponent(n)}`);return c===404?[]:((c<200||c>=300)&&ce(n,c,l),l.pendingApprovals)},async addPendingApprovals(c){if(c.length===0)return;let{status:l,body:u}=await Y("post",`${t}/${encodeURIComponent(n)}/approvals`,{approvals:c});l!==204&&ce(n,l,u)},async resolveApproval(c){let{status:l,body:u}=await Y("post",`${t}/${encodeURIComponent(n)}/approvals/${encodeURIComponent(c)}/resolve`);return(l<200||l>=300)&&ce(n,l,u),u.status}}}async function Kr(e,t={}){let n=jr(e),r=new URL(n);t.first!==void 0&&r.searchParams.set("first",String(t.first)),t.cursor!==void 0&&r.searchParams.set("cursor",t.cursor);let{status:o,body:s}=await Y("get",r.toString());if(o===400)throw new I(ft(s));if(o<200||o>=300)throw d.agentSessionsFailed(`managed session store error ${o}: ${ft(s)}`);let i=s;return{sessions:i.elements.map(a=>({id:a.sessionId,createdAt:a.createdAt,lastActivityAt:a.lastActivityAt,messageCount:a.messageCount,pendingApprovals:a.pendingApprovalCount})),nextCursor:i.pageInfo.endCursor}}function Hr(e){if(e?.scope!=="user")return;let t=mn.getStore()?.userId;if(typeof t!="string"||t.length===0)throw new I('This agent is user-scoped (memory.scope: "user") \u2014 it can only run in a user execution with a user identity (ctx.userId); schedules have none.');return t}function qr(){return A().mode==="lambda"}function mt(e,t,n){let r=x(),o=r.agentSessions,s=Hr(n);if(o?.store==="dynamodb"){let i=r.authentications??{},a=i[o.auth];if(!a)throw d.unknownAlias(o.auth,Object.keys(i));return Ur({agentName:e,sessionId:t,authenticationId:a,table:o.table,region:o.region,options:n,...s!==void 0?{ownerUserId:s}:{}})}return qr()?Br({agentName:e,sessionId:t,options:n}):yr(e,t,n,s)}async function Vr(e,t,n={}){if(t?.scope!=="user")throw new I(`agent.sessions() lists the calling user's sessions \u2014 the agent must declare memory.scope: "user".`);if(x().agentSessions?.store==="dynamodb")throw new I('agent.sessions() is not supported on the bring-your-own DynamoDB session store \u2014 use the managed store (agentSessions: { store: "managed" }).');let o=Hr(t);return qr()?Kr(e,n):hr(e,o,n)}var Wr=new Ei;function ki(e){return({steps:t})=>t.reduce((n,r)=>n+r.toolCalls.length,0)>=e}function Xr(e,t,n,r){return F.startActiveSpan("agent.tool",{kind:zt.INTERNAL,attributes:{agent:e,tool:t,...n}},async o=>{try{let s=await r();return o.setAttribute("status","success"),o.setStatus({code:Se.OK}),s}catch(s){throw o.setAttribute("status","error"),o.setStatus({code:Se.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o.end()}})}function Pi(e){let t={};for(let n of e.tools??[]){let r=n.needsApproval;t[n.name]=Gr({description:n.description,inputSchema:n.inputSchema,...r!==void 0?{needsApproval:typeof r=="function"?o=>r(o):r}:{},execute:o=>Xr(e.name,n.name,{},()=>n.execute(o,ze()))})}for(let n of e.agents??[]){let r=Fe(n),o=`agent_${n.replaceAll("-","_")}`;t[o]=Gr({description:r.description,inputSchema:zr.object({prompt:zr.string().describe("The task or question for the agent")}),execute:({prompt:s})=>Xr(e.name,o,{delegateAgent:n},async()=>{let i=Wr.getStore()??0;return i>=Nt?{error:"delegation_depth_exceeded",message:`Delegation depth limit (${Nt}) reached \u2014 answer with what you have instead of delegating further.`}:(await Wr.run(i+1,()=>Li(n).generate({prompt:s}))).text})})}return t}function Oi(e){let t=[{model:e.model,auth:e.auth},...e.fallbacks??[]];return _r(Dr(t.map(n=>Ht(n.auth)(n.model))))}function Gt(e){return e.filter(t=>typeof t=="object"&&t!==null&&t.type==="tool-approval-request"&&!t.isAutomatic)}function Yr(e){return{approvalId:e.approvalId,toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input,requestedAt:new Date().toISOString()}}function _i(e){return{id:e.approvalId,toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input}}function Di(e){let t=new Set;for(let n of e)if(Array.isArray(n.content))for(let r of Gt(n.content))t.add(r.approvalId);return t}function Mi(e,t){let n=e.reduce((r,o)=>r+it(o.response.modelId??t,o.usage).amount,0);return{amount:Number(n.toFixed(8)),currency:"USD"}}async function Fi(e,t,n){let r=[],o=[];if(n.approvals&&n.approvals.length>0){if(n.prompt!==void 0||(n.messages?.length??0)>0)throw new I("agent.generate() cannot combine `approvals` with `prompt` or `messages` \u2014 send the approvals on their own, then send new input on the next call.");let s=new Map((await e.pendingApprovals()).map(p=>[p.approvalId,p]));if(s.size===0&&t.length===0)throw new I(`Session "${e.id}" has no history and nothing awaiting approval \u2014 it does not exist, has expired, or belongs to a different user.`);let i=Di(t),a=new Set(n.approvals.map(p=>p.id)),c=[...a].filter(p=>!s.has(p)&&!i.has(p));if(c.length>0)throw new I(`Unknown approval id(s) for session "${e.id}": ${c.join(", ")} \u2014 use the ids from \`pendingApprovals\` on the paused result.`);let l=[...s.keys()].filter(p=>!a.has(p));if(l.length>0)throw new I(`Session "${e.id}" has ${l.length} pending approval(s) not decided in this call: ${l.join(", ")} \u2014 decide every pending approval in one generate() call.`);let u=[];for(let p of n.approvals){let f=s.get(p.id);!f||await e.resolveApproval(p.id)==="already-resolved"||(o.push(f),u.push({type:"tool-approval-response",approvalId:p.id,approved:p.approved,...p.reason!==void 0?{reason:p.reason}:{}}))}u.length>0&&r.push({role:"tool",content:u})}if(n.prompt!==void 0?r.push({role:"user",content:n.prompt}):n.messages&&r.push(...n.messages),r.length===0)throw new I("agent.generate() requires `prompt`, `messages`, or `approvals` \u2014 nothing to do.");return{turn:r,claimed:o}}function Li(e){let t=Fe(e);dr(e);let n=lr(e),r=Oi(t),o=Pi(t),s=t.limits?.maxIterations??fr,i=t.limits?.maxToolCalls??mr,a=t.memory?.maxSessionMessages??pr,c=l=>({model:r,system:n,tools:o,stopWhen:l.stopWhen??[Ci(s),ki(i)],...l.prepareStep!==void 0?{prepareStep:l.prepareStep}:{},...l.activeTools!==void 0?{activeTools:l.activeTools}:{},...l.toolChoice!==void 0?{toolChoice:l.toolChoice}:{},...l.providerOptions!==void 0?{providerOptions:l.providerOptions}:{}});return{model:r,tools:o,instructions:n,session(l){return mt(e,l,t.memory)},sessions(l){return Vr(e,t.memory,l)},async generate(l){return F.startActiveSpan("agent.generate",{kind:zt.INTERNAL,attributes:{agent:e,model:t.model}},async u=>{let p=mt(e,l.sessionId,t.memory);u.setAttribute("sessionId",p.id),O("hasAi");let f=[];try{let m=await Bt(p,a),S=await Fi(p,m,l);f=S.claimed;let E;try{E=await Ii({...c(l),messages:[...m,...S.turn]})}catch(y){if(f.length>0)try{await p.addPendingApprovals(f),f=[]}catch(w){console.error(`[helix-sdk] agent "${e}" session "${p.id}": failed to restore ${f.length} pending approval(s) after a failed resume \u2014 ${w instanceof Error?w.message:String(w)}`)}throw y}let g=Gt(E.content),h=g.length>0?"awaiting-approval":"completed";return await p.append(...S.turn,...E.responseMessages),g.length>0&&await p.addPendingApprovals(g.map(Yr)),u.setAttributes({steps:E.steps.length,status:h}),u.setStatus({code:Se.OK}),Object.assign(E,{sessionId:p.id,status:h,...g.length>0?{pendingApprovals:g.map(_i)}:{},helix:{cost:Mi(E.steps,t.model),model:E.response.modelId??t.model}})}catch(m){throw u.setAttribute("status","error"),u.setStatus({code:Se.ERROR,message:m instanceof Error?m.message:String(m)}),m}finally{u.end()}})},async stream(l){let u=F.startSpan("agent.stream",{kind:zt.INTERNAL,attributes:{agent:e,model:t.model}}),p=!1,f=(m,S)=>{p||(p=!0,u.setAttribute("status",m),u.setStatus(m==="error"?{code:Se.ERROR,...S!==void 0?{message:S}:{}}:{code:Se.OK}),u.end())};try{let m=mt(e,l.sessionId,t.memory);if(u.setAttribute("sessionId",m.id),O("hasAi"),l.approvals&&l.approvals.length>0)throw new I("agent.stream() does not accept approvals \u2014 resume paused runs with generate().");if(l.prompt===void 0&&!l.messages)throw new I("agent.stream() requires `prompt` or `messages`.");let S=l.prompt!==void 0?[{role:"user",content:l.prompt}]:[...l.messages],E=await Bt(m,a),g=Jr.with(Ti.setSpan(Jr.active(),u),()=>Ri({...c(l),messages:[...E,...S],onFinish:async h=>{try{await m.append(...S,...h.responseMessages);let y=Gt(h.content);y.length>0&&await m.addPendingApprovals(y.map(Yr)),f(y.length>0?"awaiting-approval":"completed")}catch(y){let w=y instanceof Error?y.message:String(y);console.error(`[helix-sdk] agent "${e}" session "${m.id}": failed to persist the streamed turn \u2014 ${w}`),f("error",w)}},onError:({error:h})=>{f("error",h instanceof Error?h.message:String(h))},onAbort:()=>{f("error","stream aborted")}}));return Object.assign(g,{sessionId:m.id})}catch(m){throw f("error",m instanceof Error?m.message:String(m)),m}}}}var Qr="helix-schedule",Q=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function Kd(e){if(typeof e!="object"||e===null)throw new Q("expected a config object");let{cron:t,timezone:n="UTC",concurrent:r=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new Q("`cron` must be a non-empty string");let s=t.trim().split(/\s+/).length;if(s!==5)throw new Q(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${s} field(s) in "${t}"`);if(typeof n!="string"||!Ni(n))throw new Q(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(n)}"`);if(typeof r!="boolean")throw new Q("`concurrent` must be a boolean");if(typeof o!="function")throw new Q("`handler` must be a function");return Object.freeze({kind:Qr,cron:t.trim(),timezone:n,concurrent:r,handler:o})}function Hd(e){return typeof e=="object"&&e!==null&&e.kind===Qr&&typeof e.handler=="function"}function Ni(e){if(!/^[A-Za-z]/.test(e))return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}import{SpanKind as Ui}from"@opentelemetry/api";function gt(e,t,n){let r=F.startSpan("log",{kind:Ui.INTERNAL});r.setAttribute("message",t),r.setAttribute("level",e),n&&Hn(r.spanContext().spanId,"properties",n),r.end(),kn(e,t,n)}function Zr(){return{info:(e,t)=>gt("info",e,t),warn:(e,t)=>gt("warn",e,t),error:(e,t)=>gt("error",e,t),debug:(e,t)=>gt("debug",e,t)}}function Xd(){try{return x().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import $i from"ky";import{context as Jt,trace as ji,SpanKind as $e,SpanStatusCode as to}from"@opentelemetry/api";async function eo(e){Sn(e.url);let t=A(),{region:n}=x(),r={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},{headers:o,deploymentId:s}=z(t);s&&(r.deploymentId=s);let i=bn(n,t.mode==="lambda"?"runtime":"dev"),a;try{a=await vn({signUrl:i,credentialHeaders:o,body:r,timeoutMs:e.timeout,executionId:t.executionId})}catch(c){let l=c instanceof Error?c.message??String(c):String(c);throw d.brokerError(0,l)}if(a.kind==="brokerError"){let c=a.code===ue?"credential broker does not support the s3 sign endpoint required by this SDK version \u2014 deploy a newer broker or pin an older SDK":a.message;throw d.brokerError(a.status,c,k(a.body),a.code)}return a.result}var Bi=new Set([Ie,Ge,te,Re,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id"]);function Ki(e){let t=e.toLowerCase();return Bi.has(t)||t.startsWith("x-tray-internal-")}async function Hi(e,t){let n=e instanceof Request?e:new Request(e,t),r=new URL(n.url);if(r.protocol!=="https:")throw d.unsupportedScheme(r.protocol.replace(/:$/,""));let o=A(),{region:s}=x(),{headers:i,deploymentId:a}=z(o),c=pe(s,o.mode==="lambda"?"runtime":"dev"),l=new Headers;for(let[m,S]of n.headers.entries())Ki(m)||l.append(m,S);l.set(Ie,n.url);for(let[m,S]of Object.entries(i))l.set(m,S);a&&l.set(te,a),o.executionId&&l.set(Re,o.executionId);let u={method:n.method,headers:l,redirect:"manual",signal:n.signal};n.body&&(u.body=n.body,u.duplex="half");let p;try{p=await fetch(c,u)}catch(m){throw m instanceof Error&&m.name==="AbortError"?m:d.brokerError(0,m instanceof Error?m.message:String(m))}let f=p.headers.get(Je);return f!==null&&Vt(await hn(p,f)),p}var qi=["get","post","put","patch","delete","head","options"],ro="[stream body omitted]";function oo(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?ro:e instanceof ArrayBuffer?`[binary body: ${e.byteLength} bytes]`:ArrayBuffer.isView(e)?`[binary body: ${e.byteLength} bytes]`:typeof Blob<"u"&&e instanceof Blob?`[binary body: ${e.size} bytes]`:e}function Wt(e){try{return new URL(e).hostname}catch{return e}}function no(e,t,n,r,o){let s=Wt(t),i="externalApi",a={kind:$e.CLIENT};return F.startActiveSpan(i,a,async c=>(c.setAttributes({method:e,host:s,"peer.service":r}),q(c,"request",{url:t,method:e,...n!==void 0?{body:oo(n)}:{}}),o(c)))}function Ue(e,t,n){e.setAttribute("status",t),e.setStatus(t==="success"?{code:to.OK}:{code:to.ERROR,message:n}),e.end()}var Vi=16;async function zi(e,t){let n=e.clone().body;return n?so(n,t):new Uint8Array(0)}async function so(e,t){let n=e.getReader(),r=[],o=0,s=0;try{for(;;){let{done:c,value:l}=await n.read();if(c)break;if(!l||l.byteLength===0){if(s+=1,s>=Vi)break;continue}s=0;let u=t+1-o;if(l.byteLength>=u){r.push(l.slice(0,u)),o+=u;break}r.push(l),o+=l.byteLength}}finally{n.cancel().catch(()=>{}),n.releaseLock()}let i=new Uint8Array(o),a=0;for(let c of r)i.set(c,a),a+=c.byteLength;return i}async function io(e,t,n){if("kyResponse"in n)try{let r=await zi(n.kyResponse,Te),o=new TextDecoder("utf-8").decode(r,{stream:!0}),s;try{s=JSON.parse(o)}catch{s=o}q(e,"response",s)}catch{q(e,"response",{status:t})}else q(e,"response",oo(n.bodyValue))}async function Gi(e,t){if(t instanceof ReadableStream){let n=e.body??t;try{let[r,o]=n.tee(),s=new Request(e,{body:r,duplex:"half"}),i=await so(o,Te);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:ro}}}return typeof t=="string"?{body:t}:{}}function gu(){let e=$i.create({fetch:Hi,retry:{shouldRetry:({error:r})=>r instanceof d?!1:void 0}});function t(r){return(o,s)=>{let i=Jt.active(),a,c=!1,l=(p,f)=>{a&&!c&&(c=!0,Ue(a,p,f))},u=e.extend({hooks:{beforeRequest:[async(p,f)=>{let m=await Gi(p,f.body),S=m.body;if(a||(a=F.startSpan("externalApi",{kind:$e.CLIENT},i)),a.setAttributes({method:p.method.toUpperCase(),host:Wt(p.url)}),q(a,"request",{url:p.url,method:p.method.toUpperCase(),...S!==void 0?{body:S}:{}}),c=!1,O("hasExternal"),m.request)return m.request}],beforeRetry:[p=>{l("error","retry"),a=void 0,c=!1}],afterResponse:[async(p,f,m)=>{a&&(a.setAttribute("statusCode",m.status),await io(a,m.status,{kyResponse:m}),m.ok?l("success"):s?.throwHttpErrors===!1&&(O("hasError"),l("error",`HTTP ${m.status}`)))}],beforeError:[p=>(O("hasError"),l("error",p.message),p)]}});return a=F.startSpan("externalApi",{kind:$e.CLIENT},i),a.setAttributes({method:r.toUpperCase(),host:Wt(String(o))}),Jt.with(ji.setSpan(Jt.active(),a),()=>{let p=r==="options"?u(o,{...s,method:"OPTIONS"}):u[r](o,s);return p.catch(f=>{O("hasError"),l("error",f instanceof Error?f.message:String(f))}),p})}}let n=Object.fromEntries(qi.map(r=>[r,t(r)]));return{...e,...n,authed(r){return Ji(r)}}}function Ji(e){let n=x().authentications??{};if(!n[e])throw d.unknownAlias(e,Object.keys(n));let r=n[e];function o(i){return(a,c={})=>{let l=i.toUpperCase();return no(l,a,c.body,e,async u=>{O("hasAuth");let p=F.startSpan("auth",{kind:$e.INTERNAL});p.setAttribute("alias",e),p.setAttribute("id",r),p.end();try{let f=ne({authenticationId:r,method:l,url:a,body:c.body,headers:c.headers,query:c.query}),m=await we(f,{timeout:c.timeout});return u.setAttribute("statusCode",m.status),await io(u,m.status,{bodyValue:m.body}),Ue(u,"success"),m}catch(f){throw O("hasError"),f instanceof d&&f.detail.kind==="broker_error"&&f.detail.status>0&&u.setAttribute("statusCode",f.detail.status),Ue(u,"error",f instanceof Error?f.message:String(f)),f}})}}function s(i,a={}){let c=a.method??"GET";return no(c,i,void 0,e,async l=>{O("hasAuth");let u=F.startSpan("auth",{kind:$e.INTERNAL});u.setAttribute("alias",e),u.setAttribute("id",r),u.end();try{let p=await eo({authenticationId:r,url:i,method:c,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return l.setAttribute("statusCode",200),Ue(l,"success"),p}catch(p){throw O("hasError"),p instanceof d&&p.detail.kind==="broker_error"&&p.detail.status>0&&l.setAttribute("statusCode",p.detail.status),Ue(l,"error",p instanceof Error?p.message:String(p)),p}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:s}}import{SpanKind as ra,SpanStatusCode as uo}from"@opentelemetry/api";function je(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Wi=18e4,ao=Wi-1e4,Xi=2e3;async function co(e,t,n){let r=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<ao;){let i=await e(t,"DescribeStatement",{Id:n}),a=i.Status;if(r.has(a))return i;let c=Math.min(Xi,200*2**s),l=c/2+Math.random()*(c/2),u=ao-(Date.now()-o);await new Promise(p=>setTimeout(p,Math.min(l,u))),s++}throw d.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Yi=new Set(["SELECT","WITH","SHOW"]),Qi=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function Zi(e){if(!e.clusterIdentifier&&!e.workgroupName)throw d.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw d.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw d.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw d.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw d.dbInvalidParameters("region is required")}function ea(e,t){let n=null;if(typeof t=="string")try{n=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(n=t);let r=typeof n?.__type=="string"?n.__type:void 0,o=typeof n?.message=="string"?n.message:void 0;if(r&&o)return d.dbQueryFailed(`${r}: ${o}`);let s=typeof t=="string"?re(t):k(t);return d.dbCallFailed(s)}function ta(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw d.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function na(e,t){return typeof t!="number"||t<0?{}:Yi.has(e)?{rowsRead:t}:Qi.has(e)?{rowsWritten:t}:{}}function lo(e){async function t(n,r,o){let s=ne({authenticationId:e,method:"POST",url:`https://redshift-data.${n}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${r}`}});try{let{status:i,body:a}=await we(s);if(i>=400)throw ea(i,a);return ta(a)}catch(i){if(i instanceof d)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw d.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:Zi,async execute(n,r){let o=je(r),s={Sql:r,Database:n.database,...n.clusterIdentifier&&{ClusterIdentifier:n.clusterIdentifier,DbUser:n.dbUser},...n.workgroupName&&{WorkgroupName:n.workgroupName},...n.statementName&&{StatementName:n.statementName}},i=await t(n.region,"ExecuteStatement",s),a=i,c=typeof a?.Id=="string"?a.Id:void 0;if(!c){let m=k(i);throw d.dbCallFailed(`ExecuteStatement response missing Id; got: ${m}`)}let l=await co(t,n.region,c),u=l.Status;if(u==="FAILED"){let m=typeof l.Error=="string"?l.Error:"statement failed";throw d.dbQueryFailed(`${m} (statement: ${c})`)}if(u==="ABORTED")throw d.dbQueryFailed(`statement aborted (statement: ${c})`);let p=na(o,l.ResultRows);return l.HasResultSet===!1?{result:{rowsAffected:l.ResultRows??0},metadata:p}:{result:await t(n.region,"GetStatementResult",{Id:c}),metadata:p}}}}var Xt=64*1024;function oa(e){return e.length>Xt?`${e.slice(0,Xt)}...[truncated]`:e}function sa(e,t,n,r,o){e.setAttributes({system:t.system,statement:o,namespace:n.database,operation:r})}function ia(e,t,n){let r=typeof t=="string"?t:JSON.stringify(t);return r.length>Xt?q(e,"result",{truncated:!0,size:r.length}):q(e,"result",t),n.rowsRead!==void 0&&e.setAttribute("rowsRead",n.rowsRead),n.rowsWritten!==void 0&&e.setAttribute("rowsWritten",n.rowsWritten),r}async function aa(e,t,n){let r=je(n),o=oa(n);return F.startActiveSpan("database",{kind:ra.CLIENT},async s=>{sa(s,e,t,r,o);try{O("hasDb");let{result:i,metadata:a}=await e.execute(t,n),c=ia(s,i,a);return s.setAttribute("status","success"),s.setStatus({code:uo.OK}),c}catch(i){O("hasError");let a=i instanceof Error?i.message:String(i);throw s.setAttribute("status","error"),s.setStatus({code:uo.ERROR,message:a}),i}finally{s.end()}})}function ca(e){let n=x().authentications??{};if(!n[e])throw d.unknownAlias(e,Object.keys(n));let r=n[e],o=lo(r);function s(i,a){return o.validate(i),aa(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as fa}from"unstorage";var po=1024,Yt=250*1024,la=new TextEncoder,da=/(^|\/)\.\.(\/|$)/,ua=/[?#]/,pa=/[\u0000-\u001F\u007F]/;function fo(e){if(e.length===0)throw d.kvKeyInvalid("Key must be a non-empty string");if(da.test(e))throw d.kvKeyInvalid("Key contains path traversal segment");if(ua.test(e)||pa.test(e))throw d.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(n=>n===""))throw d.kvKeyInvalid("Key must not contain empty path segments");let t=la.encode(e).length;if(t<1||t>po)throw d.kvKeyInvalid(`Key must be between 1 and ${po} UTF-8 bytes (got ${t})`)}function mo(e){if(!Number.isInteger(e)||e<=0)throw d.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function go(e){let t;try{t=JSON.stringify(e)}catch{throw d.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw d.kvValueInvalid("Value must be JSON-serializable");let n=Buffer.byteLength(t,"utf8");if(n>Yt)throw d.kvValueTooLarge(`Value exceeds maximum size of ${Yt} bytes (got ${n})`,Yt)}function Be(e){fo(e)}function yt(e,t){let n=e[t];if(typeof n!="function")throw new Error(`KV driver is missing ${t}`);return n}function yo(e){let t=yt(e,"getItem"),n=yt(e,"setItem"),r=yt(e,"removeItem"),o=yt(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return Be(i),t(i,a)},setItem(i,a,c){return Be(i),n(i,a,c)},removeItem(i,a){return Be(i),r(i,a)},hasItem(i,a){return Be(i),o(i,a)},getKeys(i,a){return i.length>0&&Be(i),s(i,a)}}}function ht(e){return fa({driver:yo(e)})}import{defineDriver as ma}from"unstorage";function ga(e){try{return JSON.parse(e)}catch{return e}}var ya=ma(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(n){let r=await t.get(n);return r===null?null:JSON.stringify(r)},async setItem(n,r,o){let s=o?.ttl,i=ga(r);s!==void 0?await t.set(n,i,{ttl:s}):await t.set(n,i)},async removeItem(n){await t.delete(n)},async hasItem(n){return await t.has(n)},async getKeys(){throw new Error("KV key listing is not supported")}}});function ho(e){return ya({client:e})}import Sa from"ky";import{z as M}from"zod";function wo(e){return j(e).hosts.api}function ha(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function wa(e){return e.split("/").map(encodeURIComponent).join("/")}function Ke(e,t,n){return`${e}${ha(t)}/${wa(n)}`}var ba=6e4,Qt=M.lazy(()=>M.union([M.string(),M.number(),M.boolean(),M.null(),M.array(Qt),M.record(Qt)])),va=M.object({projectId:M.string(),key:M.string(),value:Qt,type:M.enum(["string","number","boolean","null","array","object"]),organizationId:M.string(),scope:M.string(),createdBy:M.string(),createdAt:M.number(),updatedBy:M.string(),updatedAt:M.number()});function xa(){let e=de(),t=$(),n=!!(e&&e.trim().length>0),r=!!(t&&t.trim().length>0);if(!n&&!r)throw d.missingExecutionCredentials();let o={Accept:"application/json"};return n&&(o[le]=e),r&&(o[U]=t),o}function Aa(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function wt(e,t){throw d.kvCallFailed(e,Aa(t),k(t))}async function St(e,t,n={}){try{let r=await Sa(t,{method:e,headers:xa(),...n.json!==void 0?{json:n.json}:{},throwHttpErrors:!1,timeout:ba}),o=e==="head"?void 0:await K(r);return{status:r.status,body:o}}catch(r){if(r instanceof d)throw r;let o=r instanceof Error?r.message??String(r):String(r);throw d.kvCallFailed(0,o)}}function So(e){let t=wo(e.env),{projectId:n}=e;return{async get(r){let{status:o,body:s}=await St("get",Ke(t,n,r));if(o===404)return null;(o<200||o>=300)&&wt(o,s);let i=va.safeParse(s);if(!i.success)throw d.kvCallFailed(o,"platform returned malformed KeyValueEntry",k(s));return i.data.value},async set(r,o,s){let{status:i,body:a}=await St("put",Ke(t,n,r),{json:s?.ttl!==void 0?{value:o,ttl:s.ttl}:{value:o}});(i<200||i>=300)&&wt(i,a)},async delete(r){let{status:o,body:s}=await St("delete",Ke(t,n,r));o!==204&&wt(o,s)},async has(r){let{status:o,body:s}=await St("head",Ke(t,n,r));if(o===200)return!0;if(o===404)return!1;wt(o,s)}}}function bt(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,n,r)=>{let o=r?.ttl;go(n),typeof o=="number"&&mo(o),await e.setItem(t,n,o!==void 0?{ttl:o}:void 0)}}}function Ea(){let e=x();if(e.kind!=="provisioned")throw d.kvRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function bo(e){let t=Ea(),n=e??So(t),r=ht(ho(n));return bt(r)}import{defineDriver as Ia}from"unstorage";var Ra=Ia(e=>{let t=new Map;function n(r){let o=t.get(r);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(r);return}return o}return{name:"memory-ttl",getItem(r){return n(r)?.value??null},setItem(r,o,s){let i=s?.ttl,a=n(r),c=typeof i=="number"?Date.now()+i*1e3:i===null?void 0:a?.expiresAt;t.set(r,{value:o,expiresAt:c})},removeItem(r){t.delete(r)},hasItem(r){return n(r)!==void 0},getKeys(){return[...t.keys()].filter(r=>n(r)!==void 0)},clear(){t.clear()}}});function vo(){return Ra({})}var Zt;function Ca(){return Zt||(Zt=ht(vo())),Zt}function xo(){return bt(Ca())}function Ta(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":A().mode==="lambda"}function Sp(){return Ta()?bo():xo()}import{createHash as Oa}from"crypto";import{mkdir as _a,readFile as Co,readdir as To,rm as Eo,unlink as Da,writeFile as Io}from"fs/promises";import{dirname as Ma}from"path";async function ka(e){let t=e.getReader(),n=[],r=0;for(;;){let{done:o,value:s}=await t.read();if(o)break;if(s){if(r+=s.byteLength,r>G)throw await t.cancel(),d.filesValueTooLarge(`File exceeds maximum size of ${G} bytes (got more than ${G})`,G);n.push(s)}}return Buffer.concat(n)}async function be(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?ka(e):Buffer.from(e)}var Pa={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},Ao="application/octet-stream";function vt(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return Ao;let n=e.slice(t+1).toLowerCase();return Pa[n]??Ao}function xe(){let e=A().projectRoot;if(!e)throw d.filesNotAvailable();return e}async function ve(e){try{return await e()}catch(t){if(t instanceof d)throw t;let n=t?.code;throw n?d.filesCallFailed(0,`Local file storage operation failed: ${n}`):d.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function xt(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function en(e){try{let t=await Co(rt(xe(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Ro(e){await _a(Ma(e),{recursive:!0})}async function Fa(e,t){let n=ot(e,t),r;try{r=await To(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function ko(e,t){let n=ot(e,t),r;try{r=await To(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return[];throw s}let o=[];for(let s of r){let i=t.length===0?s.name:`${t}/${s.name}`;s.isDirectory()?o.push(...await ko(e,i)):s.isFile()&&o.push(i)}return o}function Po(){return{async put(e,t,n){return ve(async()=>{let r=xe(),o=await be(t),s=n?.contentType??vt(e),i=Oa("sha1").update(o).digest("hex"),a=new Date,c=De(r,e);await Ro(c),await Io(c,o);let l={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},u=rt(r,e);return await Ro(u),await Io(u,JSON.stringify(l)),xt(e,l)})},async get(e){return ve(async()=>{let t=await en(e);return t?{data:await Co(De(xe(),e)),metadata:xt(e,t)}:null})},async head(e){return ve(async()=>{let t=await en(e);return t?xt(e,t):null})},async delete(e){return ve(async()=>{let t=xe();await Promise.all([De(t,e),rt(t,e)].map(async n=>{try{await Da(n)}catch(r){if(r.code!=="ENOENT")throw r}}))})},async deleteMany(e){return ve(async()=>{let t=xe(),n=await ko(t,e);return await Promise.all([Eo(ot(t,e),{recursive:!0,force:!0}),Eo(Xn(t,e),{recursive:!0,force:!0})]),{deleted:n.length}})},async list(e,t){return ve(async()=>{let n=xe(),r=t?.limit??100,s=(await Fa(n,e??"")).slice(0,r);return{files:(await Promise.all(s.map(async a=>{let c=await en(a);return c?xt(a,c):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let n=A().devServerUrl;if(!n)throw d.filesNotAvailable();return{url:`${n}/_helix/files/${e}`,expiresAt:me(t?.expiresIn)}},async getDownloadUrl(e,t){let n=A().devServerUrl;if(!n)throw d.filesNotAvailable();return{url:`${n}/_helix/files/${e}`,expiresAt:me(t?.expiresIn)}}}}import{createHash as Ka}from"crypto";function At(e){return j(e).hosts.api}function La(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function He(e,t){return`${e}${La(t)}`}function Ae(e,t,n){return`${He(e,t)}/${encodeURIComponent(n)}`}function Et(e,t,n){return`${Ae(e,t,n)}/upload`}function Oo(e,t,n){return`${Ae(e,t,n)}/download`}function _o(e,t,n){return`${Ae(e,t,n)}/signed-url`}function Do(e,t,n,r){let o=new URLSearchParams({name:r});return n&&o.set("parentFolder",n),`${He(e,t)}/file?${o.toString()}`}function Mo(e,t,n,r){let o=new URLSearchParams({limit:String(r)});return n&&o.set("id",n),`${He(e,t)}?${o.toString()}`}import nn from"ky";import{z as _}from"zod";var rn=6e4,Fo=_.object({id:_.string(),workspaceId:_.string(),projectId:_.string(),parentFolder:_.string().nullable().optional(),name:_.string(),size:_.number().nullable().optional(),objectType:_.enum(["Folder","File"]),contentType:_.string().nullable().optional(),createdAt:_.string(),updatedAt:_.string()}),Na=_.object({signedURL:_.string()}),Ua=_.object({path:_.array(_.object({id:_.string(),name:_.string()})),elements:_.array(Fo)});function on(){let e=de(),t=$(),n=!!(e&&e.trim().length>0),r=!!(t&&t.trim().length>0);if(!n&&!r)throw d.missingExecutionCredentials();let o={Accept:"application/json"};return n&&(o[le]=e),r&&(o[U]=t),o}function Lo(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Z(e,t){throw d.filesCallFailed(e,Lo(t),k(t))}function $a(e,t){return e===400&&Lo(t).toLowerCase()==="resource not found"}async function ja(e){let t=new Response(e),n=t.headers.get("content-type")??"multipart/form-data",r=await t.arrayBuffer();return{body:Buffer.from(r),contentType:n}}async function Ee(e,t,n={}){try{let r=await nn(t,{method:e,headers:on(),...n.json!==void 0?{json:n.json}:{},throwHttpErrors:!1,timeout:rn}),o=await K(r);return{status:r.status,body:o}}catch(r){if(r instanceof d)throw r;let o=r instanceof Error?r.message:String(r);throw d.filesCallFailed(0,o)}}function tn(e,t){let n=Fo.safeParse(t);if(!n.success)throw d.filesCallFailed(e,"platform returned malformed ObjectMetadata",k(t));return n.data}function No(e){let t=At(e.env),{projectId:n}=e;return{async createMetadata(r){let{status:o,body:s}=await Ee("post",He(t,n),{json:r});return(o<200||o>=300)&&Z(o,s),tn(o,s)},async getByName(r,o){let{status:s,body:i}=await Ee("get",Do(t,n,r,o));return s===404||$a(s,i)?null:((s<200||s>=300)&&Z(s,i),tn(s,i))},async getById(r){let{status:o,body:s}=await Ee("get",Ae(t,n,r));return o===404?null:((o<200||o>=300)&&Z(o,s),tn(o,s))},async listChildren(r,o){let{status:s,body:i}=await Ee("get",Mo(t,n,r,o));(s<200||s>=300)&&Z(s,i);let a=Ua.safeParse(i);if(!a.success)throw d.filesCallFailed(s,"platform returned malformed listing",k(i));return a.data},async uploadContent(r,o,s,i){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:i}),s);let{body:c,contentType:l}=await ja(a),u;try{u=await nn(Et(t,n,r),{method:"post",headers:{...on(),"content-type":l},body:new Uint8Array(c),throwHttpErrors:!1,timeout:rn})}catch(f){if(f instanceof d)throw f;let m=f instanceof Error?f.message:String(f);throw d.filesCallFailed(0,m)}let p=await K(u);(u.status<200||u.status>=300)&&Z(u.status,p)},async downloadContent(r){let o;try{o=await nn(Oo(t,n,r),{method:"get",headers:on(),throwHttpErrors:!1,timeout:rn})}catch(i){if(i instanceof d)throw i;let a=i instanceof Error?i.message:String(i);throw d.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await K(o);Z(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(r){let{status:o,body:s}=await Ee("get",_o(t,n,r));(o<200||o>=300)&&Z(o,s);let i=Na.safeParse(s);if(!i.success)throw d.filesCallFailed(o,"platform returned malformed signed URL response",k(s));return i.data.signedURL},async deleteById(r){let{status:o,body:s}=await Ee("delete",Ae(t,n,r));o===204||o===404||(o<200||o>=300)&&Z(o,s)}}}function sn(e){return e.split("/").filter(t=>t.length>0)}function an(e){return e instanceof d&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Ba(e,t,n){let r=await e.getByName(t,n);if(r)return r;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:n})}catch(o){if(an(o)){let s=await e.getByName(t,n);if(s)return s}throw o}}async function cn(e,t){let n=sn(t),r=n[n.length-1],o;for(let s of n.slice(0,-1))o=(await Ba(e,o,s)).id;return{parentFolder:o,name:r}}async function qe(e,t){let n=sn(t),r=n[n.length-1],o;for(let s of n.slice(0,-1)){let i=await e.getByName(o,s);if(!i||i.objectType!=="Folder")return null;o=i.id}return{parentFolder:o,name:r}}async function ln(e,t){if(t.length===0)return;let n=sn(t),r;for(let o of n){let s=await e.getByName(r,o);if(!s||s.objectType!=="Folder")return null;r=s.id}return r}var Ha=500,qa=8;async function Va(e,t,n){let r=new Array(e.length),o=0;async function s(){for(;o<e.length;){let i=o++;r[i]=await n(e[i])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},s)),r}function za(){let e=x();if(e.kind!=="provisioned")throw d.filesRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function Ga(e){return Ka("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function It(e,t,n){return{path:e,size:t.size??0,contentType:t.contentType??n??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Ga(t)}}async function Uo(e,t,n,r){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:r,name:n})}catch(o){if(an(o)){let s=await e.getByName(t,n);if(s)return s}throw o}}async function $o(e,t){let{elements:n}=await e.listChildren(t,Ha);return(await Va(n,qa,async o=>{let s=o.objectType==="Folder"?await $o(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function jo(e){let t=za(),n=e??No(t),r=At(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:c,name:l}=await cn(n,s),u=await be(i),p=a?.contentType??vt(s),f=await n.getByName(c,l);if(f&&f.objectType!=="File")throw d.filesCallFailed(409,`A folder already exists at "${s}"`);let m=f??await Uo(n,c,l,p);await n.uploadContent(m.id,u,l,p);let S=await n.getById(m.id);return It(s,S??m,p)},async get(s){let i=await qe(n,s);if(!i)return null;let a=await n.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:{data:await n.downloadContent(a.id),metadata:It(s,a)}},async head(s){let i=await qe(n,s);if(!i)return null;let a=await n.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:It(s,a)},async delete(s){let i=await qe(n,s);if(!i)return;let a=await n.getByName(i.parentFolder,i.name);a&&await n.deleteById(a.id)},async deleteMany(s){let i=await ln(n,s);if(i===null)return{deleted:0};let a=await $o(n,i);return s.length>0&&i!==void 0&&await n.deleteById(i),{deleted:a}},async list(s,i){let a=await ln(n,s??"");if(a===null)return{files:[],cursor:null};let c=i?.limit??100,{elements:l}=await n.listChildren(a,c);return{files:l.filter(p=>p.objectType==="File").map(p=>It(s?`${s}/${p.name}`:p.name,p)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:c}=await cn(n,s),u=await n.getByName(a,c)??await Uo(n,a,c,i?.contentType);return{url:Et(r,o,u.id),expiresAt:me(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await qe(n,s),c=a?await n.getByName(a.parentFolder,a.name):null;if(!c||c.objectType!=="File")throw d.filesCallFailed(404,`File not found: ${s}`);return{url:await n.getSignedDownloadUrl(c.id),expiresAt:me(i?.expiresIn)}}}}function dn(e,t){let n=t?.maxPathBytes;return{async put(r,o,s){ie(r,n);let i=await be(o);return Jn(i.byteLength),e.put(r,i,s)},async get(r){return ie(r,n),e.get(r)},async head(r){return ie(r,n),e.head(r)},async delete(r){return ie(r,n),e.delete(r)},async deleteMany(r){let o=Mt(r);return tt(o,n),e.deleteMany(o)},async list(r,o){let s=Mt(r??"");return tt(s,n),e.list(s,o)},async getUploadUrl(r,o){return ie(r,n),e.getUploadUrl(r,o)},async getDownloadUrl(r,o){return ie(r,n),e.getDownloadUrl(r,o)}}}function Ja(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":A().mode==="lambda"}function pf(){if(Ja())return dn(jo());let e=A().projectRoot;return dn(Po(),{maxPathBytes:e?Wn(e):void 0})}import Xa from"ky";function Bo(e){return j(e).hosts.api}function Wa(){return"/private/v1/helix/function-calls"}function Ko(e){return`${e}${Wa()}`}var Ya=5e3;function Qa(){let e=$();if(!!!(e&&e.trim().length>0))throw d.callFunctionMissingExecutionJwt();return{Accept:"application/json",[U]:e}}function Za(e,t){throw d.callFunctionCallFailed(e,ec(t),k(t))}function ec(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Ho(e){let t=Bo(e.env);return{async callAsync(n,r){let o,s;try{let i=await Xa(Ko(t),{method:"post",headers:Qa(),json:{functionPath:n,input:r},throwHttpErrors:!1,timeout:Ya});o=i.status,s=await K(i)}catch(i){if(i instanceof d)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw d.callFunctionCallFailed(0,a)}(o<200||o>=300)&&Za(o,s)}}}var qo=1024;function Rt(e){if(typeof e!="string"||e.trim().length===0)throw d.callFunctionPathInvalid("functionPath must be a non-empty string");if(e.length>qo)throw d.callFunctionPathInvalid(`functionPath must be at most ${qo} characters`)}function tc(){let e=x();if(e.kind!=="provisioned")throw d.callFunctionRequiresProvisioning();return{env:e.region}}function Vo(e){return async function(n,r){Rt(n),await(e??Ho(tc())).callAsync(n,r)}}function zo(){return async function(t,n){Rt(t);let r=A().devServerUrl;if(!r)throw d.callFunctionNotAvailable();let o=t.startsWith("/")?t:`/${t}`,s=Zr();fetch(`${r}${o}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n??{})}).then(i=>{i.ok||s.warn("ctx.callFunctionAsync: dev-mode dispatch returned a non-2xx response",{functionPath:t,status:i.status})}).catch(i=>{s.warn("ctx.callFunctionAsync: dev-mode dispatch failed",{functionPath:t,error:i instanceof Error?i.message:String(i)})})}}function nc(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":A().mode==="lambda"}function Uf(){return nc()?Vo():zo()}export{rc as a,oc as b,sc as c,x as d,ic as e,Kn as f,gs as g,O as h,q as i,bs as j,vs as k,F as l,xs as m,Mc as n,Zr as o,Xd as p,gu as q,ca as r,Sp as s,ie as t,De as u,rt as v,pf as w,Uf as x,Kc as y,Ft as z,Zn as A,er as B,tr as C,Me as D,nr as E,Yc as F,sr as G,Lt as H,Ns as I,js as J,Bs as K,Qc as L,Ks as M,Zc as N,Gl as O,ir as P,rl as Q,ar as R,I as S,ll as T,dl as U,Fe as V,ul as W,pl as X,ur as Y,hl as Z,wl as _,X as $,vl as aa,ki as ba,Li as ca,Qr as da,Q as ea,Kd as fa,Hd as ga};