@trayai/helix-sdk 1.3.0 → 1.5.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 +15 -0
- package/README.md +3 -3
- package/dist/broker/index.js +1 -1
- package/dist/chunk-3T2WZMJJ.js +1 -0
- package/dist/chunk-7R345MR6.js +7 -0
- package/dist/{config-loader-BqIGpFg8.d.ts → define-agent-CICJokmS.d.ts} +419 -9
- package/dist/index.d.ts +9 -5
- package/dist/index.js +3 -3
- package/dist/internal/index.d.ts +62 -3
- package/dist/internal/index.js +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/{types-B9ZTUx-H.d.ts → types-Ci9SeHOE.d.ts} +169 -8
- package/package.json +1 -1
- package/dist/chunk-CYG3GXE2.js +0 -7
- package/dist/chunk-HEA646WT.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,21 @@ 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.4.0
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- **Plain `ctx.http` calls now share the same `https:`-only and no-auto-redirect behavior as
|
|
16
|
+
`ctx.http.authed()`.** Outbound URLs must be `https:` (otherwise `SdkError.unsupportedScheme`),
|
|
17
|
+
and redirects are no longer followed automatically — a 3xx response now reaches your code
|
|
18
|
+
instead, and (unless you pass `{ throwHttpErrors: false }`) it throws like any other non-2xx
|
|
19
|
+
status; inspect the thrown error's response or pass that option to handle it as a value, then
|
|
20
|
+
re-request the `location` header yourself if you need to follow it. Previously, plain
|
|
21
|
+
`ctx.http` behaved like a bare HTTP client (any scheme, redirects followed automatically);
|
|
22
|
+
this brings it in line with `ctx.http.authed()`, which has always worked this way. Plain
|
|
23
|
+
`ctx.http` now also requires you to be authenticated — the same platform login every other
|
|
24
|
+
SDK feature already needs — where previously it had no prerequisites at all.
|
|
25
|
+
|
|
11
26
|
## 1.3.0
|
|
12
27
|
|
|
13
28
|
No user-visible changes in this release — co-versioned with `@trayai/helix-cli`'s changes.
|
package/README.md
CHANGED
|
@@ -78,7 +78,7 @@ Every HTTP handler receives a `ctx` (`TrayContext`); scheduled handlers receive
|
|
|
78
78
|
| `ctx.input` | Validated input — query, body, and path params merged (path wins, then body, then query) |
|
|
79
79
|
| `ctx.method` / `ctx.path` | Request method and path |
|
|
80
80
|
| `ctx.headers` | Sanitized request headers |
|
|
81
|
-
| `ctx.http` | HTTP client for outbound requests |
|
|
81
|
+
| `ctx.http` | HTTP client for outbound requests — `https:` URLs only; a 3xx is not auto-followed and throws like any other non-2xx status by default (pass `{ throwHttpErrors: false }` to get it back as a value) |
|
|
82
82
|
| `ctx.http.authed(alias)` | Authenticated HTTP — credentials are injected by the platform; secrets never touch your code |
|
|
83
83
|
| `ctx.kv()` | Key-value store |
|
|
84
84
|
| `ctx.files()` | File storage |
|
|
@@ -108,10 +108,10 @@ export default defineFunction(async (ctx) => {
|
|
|
108
108
|
|
|
109
109
|
Each method returns `{ status, body?, headers }`. An upstream non-2xx response is **not** thrown — you get the status as a value, matching `ctx.http`. Behavior and constraints in this release:
|
|
110
110
|
|
|
111
|
-
- Outbound URLs must be `https:` (otherwise `SdkError.unsupportedScheme`).
|
|
111
|
+
- Outbound URLs must be `https:` (otherwise `SdkError.unsupportedScheme`) — this applies to plain `ctx.http` too, not just `.authed()`.
|
|
112
112
|
- Request bodies are transmitted byte-for-byte: strings, `Uint8Array`/`ArrayBuffer`, `Blob`, `FormData`, and streams are sent verbatim (a string is never JSON-quoted); plain objects and arrays are serialized as JSON with a default `content-type: application/json` unless you set your own. Request bodies are capped at 16 MB — for anything larger, use the target API's multipart or chunked/resumable upload flow, keeping each part under the cap.
|
|
113
113
|
- Response bodies are decoded by content-type: JSON is parsed, textual types come back as a string, and everything else (e.g. `application/octet-stream`) is returned as raw bytes (`Uint8Array`) — binary downloads arrive unmangled.
|
|
114
|
-
- Redirects are not followed: a 3xx response is returned to your code with its `location` header, and following it is your decision.
|
|
114
|
+
- Redirects are not followed: a 3xx response is returned to your code with its `location` header, and following it is your decision. Plain `ctx.http` also stops auto-following redirects, but — unlike this authed client — it throws for a 3xx by default like any other non-2xx status; pass `{ throwHttpErrors: false }` to get it back as a value instead.
|
|
115
115
|
- An unknown alias throws `SdkError.unknownAlias` (the error lists the configured aliases).
|
|
116
116
|
|
|
117
117
|
### Signed S3 URLs — `s3Sign`
|
package/dist/broker/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as n,D as o,
|
|
1
|
+
import{B as n,D as o,F as i,G as s,H as d,I as u,J as l}from"../chunk-3T2WZMJJ.js";async function a(e){let r=o({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),t=await s({proxyUrl:n(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},request:r,timeoutMs:e.timeoutMs??i});return t.kind==="brokerError"?{kind:"brokerError",brokerStatus:t.status,code:t.code,body:t.body}:{kind:"upstream",upstream:t.response}}async function k(e){d(e.url);let r=await l({signUrl:u(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 r.kind==="brokerError"?{kind:"brokerError",brokerStatus:r.status,code:r.code,body:r.body}:{kind:"signed",signed:r.result}}export{a as callBrokerDev,k as callS3SignDev};
|
|
@@ -0,0 +1 @@
|
|
|
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};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{a as hn,b as Xe}from"./chunk-WUCX7RZO.js";import{A as Sn,B as me,C as G,D as ne,E as bn,G as vn,H as xn,I as An,J as En,a as U,b as ue,d as A,e as de,f as $,h as fn,j,k as gn,o as yn,r as u,t as Ce,u as Ye,v as te,w as ke,x as We,y as pe,z as wn}from"./chunk-3T2WZMJJ.js";var Za="tray-config-bridge",ec="tray-dev-token-bridge",Qe=null;function tc(e){Qe=e}function v(){if(!Qe)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return Qe}function nc(){Qe=null}import{AsyncLocalStorage as qn}from"async_hooks";import{trace as as,SpanKind as cs,SpanStatusCode as rt}from"@opentelemetry/api";import{ExportResultCode as ls,W3CTraceContextPropagator as us}from"@opentelemetry/core";import{NodeTracerProvider as ds,SimpleSpanProcessor as ps,BatchSpanProcessor as ms}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Go}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Jo}from"@opentelemetry/exporter-logs-otlp-proto";function Tt(e){return j(e).hosts.ingest}function Xo(){return $()??""}function In(){return{[U]:Xo()}}function Rn(){let e=Tt(v().region);return new Go({url:`${e}/v1/traces`,headers:()=>Promise.resolve(In())})}function Tn(){let e=Tt(v().region);return new Jo({url:`${e}/v1/logs`,headers:()=>Promise.resolve(In())})}import{logs as Pn,SeverityNumber as Ze}from"@opentelemetry/api-logs";import{LoggerProvider as Qo,BatchLogRecordProcessor as Zo}from"@opentelemetry/sdk-logs";function Pe(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 Cn="\u2026[truncated]",Wo=Yo(Cn),Oe=4096;function re(e,t=Oe){let n=new TextEncoder().encode(e);if(n.length<=t)return e;let r=n.subarray(0,t-Wo);return new TextDecoder("utf-8").decode(r).replace(/�$/,"")+Cn}function R(e,t=Oe){return re(Pe(e),t)}var es="@trayai/helix-sdk",_e,kn={debug:{number:Ze.DEBUG,text:"DEBUG"},info:{number:Ze.INFO,text:"INFO"},warn:{number:Ze.WARN,text:"WARN"},error:{number:Ze.ERROR,text:"ERROR"}};function ts(){return A().mode==="lambda"?[new Zo({exporter:Tn()})]:[]}function On(){if(_e!==void 0)return;let e=ts();e.length!==0&&(_e=new Qo({processors:e}),Pn.setGlobalLoggerProvider(_e))}function ns(e,t,n){let r=kn[e]??kn.info;return{severityNumber:r.number,severityText:r.text,body:t,...n?{attributes:{"tray.log.meta":R(n)}}:{}}}function _n(e,t,n){Pn.getLogger(es).emit(ns(e,t,n))}async function Dn(e=2e3){if(_e===void 0)return;let t;try{await Promise.race([_e.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 Ct(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function rs(){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 O(e,t){return rs()?`\x1B[${e}m${t}\x1B[0m`:t}var os=5,ss={FN:"1;35",INFO:"34",AUTH:"35",API:"36",AGENT:"1;36",TOOL:"36",WARN:"33",ERROR:"31",DEBUG:"90"},et="32",tt="31",is="33",oe="2",nt="1";function se(e){return O(ss[e]??"0",e.padEnd(os))}function Fn(e,t){return`${se("FN")} ${O(nt,`${e} ${t}`.trim())}`}function Mn(e,t,n,r){let o=e.toUpperCase(),i=`${r?`${O(oe,r)} `:""}${se(o)} ${t}`;return n&&Object.keys(n).length>0&&(i+=` ${O(oe,Pe(n))}`),i}function Ln(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Nn(e){return`${se("AUTH")} ${e}`}function Un(e,t,n,r,o){let s=n===void 0?"ERR":String(n),i=O(o==="error"?tt:et,s);return`${se("API")} ${e} ${t} \u2192 ${i} ${O(oe,`${r}ms`)}`}function $n(e){return`${se("AGENT")} ${O(nt,e)}`}function jn(e,t,n,r){let o=t==="error"?tt:t==="awaiting-approval"?is:et,s=n!==void 0?`${O(oe,`${n} step${n===1?"":"s"}`)} `:"";return`${se("AGENT")} ${O(nt,e)} \u2192 ${O(o,t)} ${s}${O(oe,`${r}ms`)}`}function Bn(e,t,n){let r=t==="error"?O(tt,"error"):O(et,"ok");return`${se("TOOL")} ${e} \u2192 ${r} ${O(oe,`${n}ms`)}`}function Kn(e,t,n){let r=t?tt:et,o=O(r,"\u25CF"),s=O(r,t?"error":"success");return`${o} ${O(nt,e)} ${s} ${O(oe,`${n}ms`)}`}function q(e){try{process.stdout.write(e+`
|
|
3
|
+
`)}catch{}}var Vn=new qn,fs=new qn;function k(e){let t=fs.getStore();t&&(t[e]=!0)}var gs=/^[0-9a-f]{32}$/;function ys(e){let t=e.replace(/-/g,"").toLowerCase();return gs.test(t)?t:null}var hs={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},fe=new Map;function zn(e,t,n){let r=fe.get(e);r?r[t]=n:fe.set(e,{[t]:n})}function V(e,t,n){e.setAttribute(t,R(n))}var De;function Hn(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function kt(e){return Math.round(e[0]*1e3+e[1]/1e6)}function Gn(e){try{process.stdout.write(Pe(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,d]of Object.entries(s))typeof d=="string"?i[l]=re(d):typeof d=="object"&&d!==null?i[l]=R(d):i[l]=d;fe.delete(o)}let a=Vn.getStore(),c=a?ys(a):null;Gn({_otel:"span",traceId:c??r.spanContext().traceId,spanId:o,parentSpanId:r.parentSpanContext?.spanId??"",name:r.name,kind:r.kind,startTimeUnixNano:Hn(r.startTime),endTimeUnixNano:Hn(r.endTime),attributes:i,status:{code:hs[r.status.code]??"STATUS_CODE_UNSET",...r.status.message?{message:re(r.status.message)}:{}}})}n({code:ls.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")&&q(`
|
|
5
|
+
`+Fn(String(n.attributes.method??""),String(n.attributes.route??""))),(n.name==="agent.generate"||n.name==="agent.stream")&&q($n(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;q(Mn(String(n.level??"info"),String(n.message??""),o,Ln(t.startTime)));break}case"auth":q(Nn(String(n.alias??"")));break;case"externalApi":{let r=typeof n.statusCode=="number"?n.statusCode:void 0;q(Un(String(n.method??""),String(n.host??""),r,kt(t.duration),n.status==="error"?"error":"success"));break}case"agent.tool":{q(Bn(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===rt.ERROR?"error":"completed";q(jn(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 ws(){let t=[Ct()?new _t:new ps(new Pt)];return A().mode==="lambda"&&t.push(new Dt(new ms(Rn()))),t.push(new Ot),t}function Ss(){De===void 0&&(De=new ds({spanProcessors:ws()}),De.register({propagator:new us}),On())}async function bs(e=2e3){let t=[Dn(e)];De!==void 0&&t.push((async()=>{let n;try{await Promise.race([De.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=as.getTracer("@trayai/helix-sdk");function vs({executionId:e,deploymentId:t,triggerType:n="http",routeOrJob:r,startedAt:o,startMs:s,errored:i,errorMessage:a,userId:c,flags:l}){let d=new Date().toISOString(),p=Date.now()-s;if(Ct()){q(`
|
|
7
|
+
`+Kn(r,i,p));return}Gn({_otel:"summary",executionId:e,deploymentId:t,triggerType:n,routeOrJob:r,status:i?"error":"success",startedAt:o,finishedAt:d,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 Pc(e,t){let n=e.startMs??Date.now();Ss();let r=!1,o=null;try{return await Vn.run(e.executionId,()=>F.startActiveSpan("App",{kind:cs.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?rt.ERROR:rt.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:rt.ERROR,message:o}),i}finally{s.end()}}))}finally{vs({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 bs()}}var Yn=1024,J=100*1024*1024,Jn=250,xs=3600,As=xs*1e3,Xn=new TextEncoder,Es=/(^|\/)\.\.(\/|$)/,Is=/[?#]/;function Rs(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=Yn){if(e.length===0)throw u.filesPathInvalid("Path must be a non-empty string");ot(e,t)}function Ft(e){return e.endsWith("/")?e.slice(0,-1):e}function ot(e,t=Yn){if(e.length===0)return;if(Es.test(e))throw u.filesPathInvalid("Path contains path traversal segment");if(Is.test(e)||Rs(e))throw u.filesPathInvalid("Path contains illegal characters");let n=e.split("/");if(e.startsWith("/")||e.endsWith("/")||n.some(o=>o===""))throw u.filesPathInvalid("Path must not contain empty path segments");for(let o of n){let s=Xn.encode(o).length;if(s>Jn)throw u.filesPathInvalid(`Path segment exceeds ${Jn} UTF-8 bytes (got ${s})`)}let r=Xn.encode(e).length;if(r<1||r>t)throw u.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${r})`)}function Wn(e){if(e>J)throw u.filesValueTooLarge(`File exceeds maximum size of ${J} bytes (got ${e})`,J)}function ge(e){let t=e!==void 0?e*1e3:As;return new Date(Date.now()+t)}import{join as Me}from"path";var Ts="files",Cs="files-meta",ks=1023,Ps=1,Os=5;function Qn(e){let t=Math.max(Buffer.byteLength(st(e),"utf8"),Buffer.byteLength(Fe(e),"utf8"));return Math.max(0,ks-t-Ps-Os)}function st(e){return Me(e,".helix",Ts)}function Fe(e){return Me(e,".helix",Cs)}function Le(e,t){return Me(st(e),...t.split("/"))}function it(e,t){return Me(Fe(e),...t.split("/"))+".json"}function at(e,t){return t.length===0?st(e):Le(e,t)}function Zn(e,t){return t.length===0?Fe(e):Me(Fe(e),...t.split("/"))}import{z as _s}from"zod";var Uc=["us1","eu1","ap1","ap2"],Mt=_s.string().refine(e=>fn(e),e=>({message:`Invalid enum value. Expected ${gn().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));import{resolve as X}from"path";import{existsSync as ct,realpathSync as er}from"fs";import{loadConfig as Ds}from"c12";import{z as b}from"zod";var nr=b.string().uuid("projectId must be a valid UUID"),rr=b.string().min(1,"workspaceId must be a non-empty string"),or=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")})]),Ne=["openai","anthropic","google","mistral","cohere","openai-compatible"],Fs=["openai","anthropic","google","mistral","cohere"],sr=b.union([b.enum(Fs),b.object({service:b.enum(Ne),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)"})]),Ms=b.object({name:b.string().min(1,"name is required"),projectId:nr.optional(),workspaceId:rr.optional(),region:Mt.optional(),env:b.literal("production").optional(),authentications:b.record(b.string()).optional().default({}),config:b.record(b.unknown()).optional().default({}),agentSessions:or.optional(),aiProviders:b.record(sr).optional()}).transform(({env:e,region:t,...n})=>({...n,region:t??"us1"})),tr=b.object({name:b.string().min(1,"name is required"),workspaceId:rr.optional(),region:Mt,authentications:b.record(b.string()),config:b.record(b.unknown()),agentSessions:or.optional(),aiProviders:b.record(sr).optional()}),Gc=b.discriminatedUnion("kind",[tr.extend({kind:b.literal("provisioned"),projectId:nr}),tr.extend({kind:b.literal("unprovisioned")})]),ir=["helix","tray"],ar=["ts","mts","cts","js","mjs","cjs"],cr="HELIX_CONFIG";function Lt(e){let t=e?.trim();return t||process.env[cr]?.trim()||void 0}function Ls(e,t){let n=Lt(t?.configFile);if(n!==void 0){let r=X(e,n);return ct(r)?r:void 0}for(let r of ir)for(let o of ar){let s=X(e,`${r}.config.${o}`);if(ct(s))return s}}function Ns(e){for(let t of ir)if(ar.some(n=>ct(X(e,`${t}.config.${n}`))))return t;return"helix"}function Us(e,t){return X(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function $s(e,t){let n=Lt(t?.configFile);return{name:Ns(e),cwd:e,...n!==void 0?{configFile:Us(e,n)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function js(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw u.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let n=Ms.safeParse(e);if(!n.success){let l=n.error.issues.map(d=>d.message).join("; ");throw u.configLoadFailed(`Invalid helix.config.ts at ${t}: ${l}`)}let{projectId:r,workspaceId:o,...s}=n.data,i=o!==void 0?{workspaceId:o}:{},a=yn(),c=a!==void 0?{...s,region:a}:s;return r!==void 0?{kind:"provisioned",projectId:r,...c,...i}:{kind:"unprovisioned",...c,...i}}async function Jc(e,t){let n=e??process.cwd(),r=Lt(t?.configFile),o=r!==void 0?X(n,r):void 0;if(o!==void 0&&!ct(o)){let a=t?.configFile?.trim()?"":` (from ${cr})`;throw u.configLoadFailed(`Config file not found: ${o}${a}`)}let s;try{s=await Ds($s(n,t))}catch(a){throw u.configLoadFailed(`Failed to load helix.config.ts: ${a instanceof Error?a.message:String(a)}`)}let i=s._configFile??Ls(n,t);if(!i)throw u.configLoadFailed(`helix.config.ts not found at ${X(n,"helix.config.ts")}`);if(o!==void 0&&s._configFile!==void 0){let a=er(o);if(er(X(s._configFile))!==a)throw u.configLoadFailed(`Config file conflict: requested ${o} but ${X(s._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return js(s.config,i)}var Bs="WORKSPACE_ID_REQUIRED";function Xc(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:Bs});return e.workspaceId}var lr="helix-tool",Ks=/^[a-z][a-z0-9_]{0,63}$/;function Zc(e){if(typeof e.name!="string"||!Ks.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 u.inputValidationFailed(s.error.issues.map(i=>i.path.join(".")||"(root)"));return e.handler({...o,input:s.data})},n=(async r=>t(r,Xe()));return Object.defineProperties(n,{kind:{value:lr,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 ur(e){return typeof e=="function"&&e.kind===lr&&typeof e.name=="string"}var M=class extends Error{constructor(t){super(t),this.name="AgentCallerError"}};import{readFileSync as Hs}from"fs";import{isAbsolute as qs,resolve as Vs}from"path";var B=new Map;function dr(e){B.set(e.name,{definition:e});for(let t of B.values())t.referencesValidated=void 0}function sl(e,t){let n=B.get(e);n&&(n.baseDir=t,n.resolvedInstructions=void 0)}function il(e,t){let n=B.get(e);n&&(n.resolvedInstructions=t)}function Ue(e){let t=B.get(e);if(!t){let n=[...B.keys()].sort();throw new M(`Unknown agent "${e}". Registered agents: ${n.join(", ")||"(none \u2014 are the functions/_agents/ modules imported?)"}`)}return t.definition}function al(){return[...B.values()].map(e=>e.definition)}function pr(e){let t=B.get(e);if(!t)throw new M(`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=qs(r)?r:t.baseDir!==void 0?Vs(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=Hs(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 mr(e){let t=B.get(e);if(t?.referencesValidated)return;let n=Ue(e);for(let r of n.agents??[]){let s=(Ue(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 cl(){B.clear()}import{z as T}from"zod";var fr="helix-agent",zs=/^[a-z][a-z0-9-]{0,63}$/,Gs=T.object({model:T.string().min(1),auth:T.string().min(1)}),Js=T.object({name:T.string().regex(zs,'agent name must be kebab-case (e.g. "support-agent"); name is required in v1'),description:T.string().min(1,"description is required"),model:T.string().min(1,"model is required"),auth:T.string().min(1,"auth (authentication alias) is required"),fallbacks:T.array(Gs).optional(),instructions:T.string().min(1).optional(),instructionsFile:T.string().min(1).optional(),tools:T.array(T.custom(ur,"tools entries must be defineTool exports")).optional(),agents:T.array(T.string().min(1)).optional(),memory:T.object({maxSessionMessages:T.number().int().positive().optional(),ttl:T.number().int().positive().optional(),scope:T.enum(["user","project"]).optional()}).optional(),limits:T.object({maxIterations:T.number().int().positive().optional(),maxToolCalls:T.number().int().positive().optional()}).optional()}).refine(e=>e.instructions===void 0!=(e.instructionsFile===void 0),{message:"exactly one of instructions / instructionsFile must be set"}),ye=200,he=3600*24*30,gr=25,yr=50,Nt=3;function ml(e){let t=Js.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:fr,...t.data};return dr(r),r}function fl(e){return typeof e=="object"&&e!==null&&e.kind===fr&&typeof e.name=="string"}var Y=new Map;function $t(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 hr(e,t){return!e||!Array.isArray(e.content)?!1:e.content.some(n=>typeof n=="object"&&n!==null&&n.type==="tool-approval-request"&&t.has(String(n.approvalId)))}function jt(e,t,n){let r=new Set;if(t<=0)return r;let o=t,s=0;for(;s<e.length&&o>0;s++)hr(e[s],n)||(r.add(s),o-=1);let i=[];for(;s<e.length;s++){let a=e[s];if(!hr(a,n)){if(a?.role==="user"){for(let c of i)r.add(c);break}i.push(s)}}return r}function Xs(e){let t=e.messages.length-e.maxSessionMessages;if(t<=0)return;let n=new Set(e.pendingApprovals.map(o=>o.approvalId)),r=jt(e.messages,t,n);r.size!==0&&(e.truncated=!0,e.messages=e.messages.filter((o,s)=>!r.has(s)))}function Bt(e,t){return t-e.lastActiveAt>e.ttlSeconds*1e3}var Ys=6e4,Ut=0;function Ws(e){if(!(e-Ut<Ys)){Ut=e;for(let[t,n]of Y)if(Bt(n,e)){if(n.pendingApprovals.length>0){n.messages=[];continue}Y.delete(t)}}}var ae=class extends Error{constructor(t){super(`Agent session "${t}" has expired (session-expired)`),this.name="SessionExpiredError"}};function wr(e,t,n,r){let o=Date.now();Ws(o);let s=n?.maxSessionMessages??ye,i=n?.ttl??he,a=t??`ses_${crypto.randomUUID().replaceAll("-","")}`,c=$t(e,a,r),l=Y.get(c);if(l&&Bt(l,o)){if(Y.delete(c),l.pendingApprovals.length>0)throw new ae(a);l=void 0}l||(l={id:a,agentName:e,...r!==void 0?{ownerUserId:r}:{},messages:[],createdAt:o,lastActiveAt:o,truncated:!1,pendingApprovals:[],maxSessionMessages:s,ttlSeconds:i},Y.set(c,l));let d=l,p=()=>{d.lastActiveAt=Date.now()};return{id:a,async messages(m){p();let g=d.messages;return m?.limit!==void 0?g.slice(-m.limit):[...g]},async append(...m){p(),d.messages.push(...m),Xs(d)},async clear(){Y.delete(c)},async truncated(){return d.truncated},async pendingApprovals(){return p(),[...d.pendingApprovals]},async addPendingApprovals(m){p(),d.pendingApprovals.push(...m)},async resolveApproval(m){p();let g=d.pendingApprovals.findIndex(w=>w.approvalId===m);return g===-1?"already-resolved":(d.pendingApprovals.splice(g,1),"resolved")}}}function Sr(e,t,n={}){let r=Date.now(),o=n.first??20,s=n.cursor!==void 0&&Number.parseInt(n.cursor,10)||0,i=[...Y.values()].filter(c=>c.agentName===e&&c.ownerUserId===t&&!Bt(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 hl(){Y.clear(),Ut=0}import{AsyncLocalStorage as bi}from"async_hooks";import{z as Vr}from"zod";import{generateText as vi,streamText as xi,tool as zr,stepCountIs as Ai}from"ai";import{SpanKind as Xt,SpanStatusCode as ve,context as Gr,trace as Ei}from"@opentelemetry/api";import{embed as Er,embedMany as Ir,generateImage as Rr,generateObject as Tr,generateSpeech as Cr,generateText as kr,streamObject as Pr,streamText as Or,transcribe as _r}from"ai";import{SpanKind as ci,SpanStatusCode as Ar}from"@opentelemetry/api";import{createOpenAI as ti}from"@ai-sdk/openai";import{createAnthropic as ni}from"@ai-sdk/anthropic";import{createGoogle as ri}from"@ai-sdk/google";import{createMistral as oi}from"@ai-sdk/mistral";import{createCohere as si}from"@ai-sdk/cohere";import{createOpenAICompatible as ii}from"@ai-sdk/openai-compatible";var Qs=new Set(["x-api-key","x-goog-api-key"]);function Zs(e){return wn(e)||Qs.has(e.toLowerCase())}function ei(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function br(e){return async(t,n)=>{let r=ei(t),o=new URL(r);if(o.protocol!=="https:")throw u.unsupportedScheme(o.protocol.replace(/:$/,""));let s=A(),{region:i}=v(),a=new Headers(n?.headers??(t instanceof Request?t.headers:void 0)),c=new Headers;for(let[f,y]of a.entries())Zs(f)||c.append(f,y);c.set(Ce,r),c.set(Ye,e),s.executionId&&c.set(ke,s.executionId);let{headers:l,deploymentId:d}=G(s);for(let[f,y]of Object.entries(l))c.set(f,y);d&&c.set(te,d);let p=me(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(f){if(f instanceof Error&&f.name==="AbortError")throw f;let y=f instanceof Error?f.message??String(f):String(f);throw u.brokerError(0,y)}let D=w.headers.get(We);if(D!==null){let f=await w.text(),y=f||D;try{let E=Sn.safeParse(JSON.parse(f));E.success&&(y=E.data.error.message)}catch{}throw D===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"),u.brokerError(w.status,y,f||void 0,D)}return w}}var we="helix-broker";function vr(e){let{alias:t,service:n,baseUrl:r,authenticationId:o}=e,s=br(o);switch(n){case"openai":return ti({apiKey:we,fetch:s});case"anthropic":return ni({apiKey:we,fetch:s});case"google":return ri({apiKey:we,fetch:s});case"mistral":return oi({apiKey:we,fetch:s});case"cohere":return si({apiKey:we,fetch:s});case"openai-compatible":{if(!r)throw u.aiUnsupportedService(t,n,[...Ne]);return ii({name:t,baseURL:r,apiKey:we,fetch:s})}}}var xr={"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}},ai=Object.keys(xr).sort((e,t)=>t.length-e.length);function lt(e,t){let n=ai.find(s=>e.startsWith(s));if(!n||!t)return{amount:0,currency:"USD"};let r=xr[n],o=((t.inputTokens??0)*r.input+(t.outputTokens??0)*r.output)/1e6;return{amount:Number(o.toFixed(8)),currency:"USD"}}function N(e,t,n){return F.startActiveSpan("ai",{kind:ci.CLIENT},async r=>{r.setAttributes({operation:e.operation,model:e.model,...e.alias!==void 0?{alias:e.alias}:{}}),k("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:Ar.OK}),o}catch(o){let s=o instanceof Error?o.message:String(o);throw r.setAttribute("status","error"),r.setStatus({code:Ar.ERROR,message:s}),o}finally{r.end()}})}function li(){return`aireq_${crypto.randomUUID().replaceAll("-","")}`}function Se(e,t){return{cost:lt(e,t),requestId:li()}}function ce(e){return typeof e=="object"&&e!==null&&"modelId"in e?String(e.modelId):String(e)}var Dr=new WeakSet;function $e(e){return Dr.add(e),e}function z(e){if(typeof e!="object"||e===null)throw u.aiModelInstanceRequired(typeof e=="string"?e:String(e));if(!Dr.has(e))throw u.aiForeignModelRejected()}function ut(e){return e.totalUsage??e.usage}function dt(e){return e.usage?.tokens!==void 0?{inputTokens:e.usage.tokens}:void 0}function pt(e){return e.usage}function Kt(e){let t=v(),n=t.authentications??{};if(!n[e])throw u.unknownAlias(e,Object.keys(n));let r=n[e],o=(t.aiProviders??{})[e];if(o===void 0)throw u.aiProviderNotConfigured(e,[...Ne]);let{service:s,baseUrl:i}=typeof o=="string"?{service:o,baseUrl:void 0}:o,a=vr({alias:e,service:s,baseUrl:i,authenticationId:r}),c=f=>$e(a.languageModel(f)),l=f=>$e(a.embeddingModel(f)),d=f=>$e(a.imageModel(f)),p=f=>{if(!a.transcriptionModel)throw new Error(`AI provider "${s}" (alias "${e}") has no transcription models`);return $e(a.transcriptionModel(f))},m=f=>{if(!a.speechModel)throw new Error(`AI provider "${s}" (alias "${e}") has no speech models`);return $e(a.speechModel(f))},g=(f=>c(f)),w=(f,y)=>{let E=f.model;if(typeof E!="string")throw u.aiModelIdRequired(e,y);return E};return Object.assign(g,{specificationVersion:"v4",languageModel:c,embeddingModel:l,textEmbeddingModel:l,imageModel:d,transcriptionModel:p,speechModel:m,async generateText(f){let y=w(f,"generateText"),E=await N({operation:"generateText",model:y,alias:e},()=>kr({...f,model:c(y)}),ut);return Object.assign(E,{helix:Se(y,ut(E))})},streamText(f){let y=w(f,"streamText");return k("hasAi"),Or({...f,model:c(y)})},async generateObject(f){let y=w(f,"generateObject"),E=await N({operation:"generateObject",model:y,alias:e},()=>Tr({...f,model:c(y)}),S=>S.usage),h=E.usage;return Object.assign(E,{helix:Se(y,h)})},streamObject(f){let y=w(f,"streamObject");return k("hasAi"),Pr({...f,model:c(y)})},async embed(f){let y=w(f,"embed");return N({operation:"embed",model:y,alias:e},()=>Er({...f,model:l(y)}),dt)},async embedMany(f){let y=w(f,"embedMany");return N({operation:"embedMany",model:y,alias:e},()=>Ir({...f,model:l(y)}),dt)},async generateImage(f){let y=w(f,"generateImage"),E=await N({operation:"generateImage",model:y,alias:e},()=>Rr({...f,model:d(y)}),pt);return Object.assign(E,{helix:Se(y,pt(E))})},async transcribe(f){let y=w(f,"transcribe");return N({operation:"transcribe",model:y,alias:e},()=>_r({...f,model:p(y)}))},async generateSpeech(f){let y=w(f,"generateSpeech");return N({operation:"generateSpeech",model:y,alias:e},()=>Cr({...f,model:m(y)}))}})}function Hl(){let e=new Map;return Object.assign((r=>{let o=e.get(r);return o||(o=Kt(r),e.set(r,o)),o}),{async generateText(r){z(r.model);let o=ce(r.model),s=await N({operation:"generateText",model:o},()=>kr(r),ut);return Object.assign(s,{helix:Se(o,ut(s))})},streamText(r){return z(r.model),k("hasAi"),Or(r)},async generateObject(r){z(r.model);let o=ce(r.model),s=await N({operation:"generateObject",model:o},()=>Tr(r),a=>a.usage),i=s.usage;return Object.assign(s,{helix:Se(o,i)})},streamObject(r){return z(r.model),k("hasAi"),Pr(r)},async embed(r){return z(r.model),N({operation:"embed",model:ce(r.model)},()=>Er(r),dt)},async embedMany(r){return z(r.model),N({operation:"embedMany",model:ce(r.model)},()=>Ir(r),dt)},async generateImage(r){z(r.model);let o=ce(r.model),s=await N({operation:"generateImage",model:o},()=>Rr(r),pt);return Object.assign(s,{helix:Se(o,pt(s))})},async transcribe(r){return z(r.model),N({operation:"transcribe",model:ce(r.model)},()=>_r(r))},async generateSpeech(r){return z(r.model),N({operation:"generateSpeech",model:ce(r.model)},()=>Cr(r))}})}var Ht=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 Fr(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 Ht(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 qt(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 u.brokerError(e.status,t,R(e.body),e.code)}async function be(e,t={}){let n=A(),{region:r}=v(),{headers:o,deploymentId:s}=G(n);s&&(o[te]=s);let i=me(r,n.mode==="lambda"?"runtime":"dev"),a;try{a=await vn({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 u.brokerError(0,l)}return a.kind==="brokerError"&&qt(a),a.response}var ui=8,Nr="msg#",di="meta",Mr=25,Lr=3,pi=400*1024-1024,mi=32,K=e=>({S:e}),je=e=>({N:String(e)});function Vt(e,t){let n=e?.[t]?.S;return typeof n=="string"?n:void 0}function zt(e,t){let n=e?.[t]?.N;return typeof n=="string"?Number(n):void 0}function fi(e,t){return e?.[t]?.BOOL===!0}function Gt(e,t){let n=e?.[t]?.M;return typeof n=="object"&&n!==null?n:{}}function gi(e){return`${Nr}${String(e).padStart(ui,"0")}`}function yi(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?.maxSessionMessages??ye,i=e.options?.ttl??he,a=e.sessionId??`ses_${crypto.randomUUID().replaceAll("-","")}`,c=$t(t,a,e.ownerUserId),l={pk:K(c),sk:K(di)};async function d(h,S){let x=ne({authenticationId:o,method:"POST",url:`https://dynamodb.${r}.amazonaws.com/`,body:S,headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${h}`}}),C,L;try{({status:C,body:L}=await be(x))}catch(I){throw I instanceof u?I:u.agentSessionsFailed(I instanceof Error?I.message:String(I))}if(C>=400){let I=yi(L);throw I==="ConditionalCheckFailedException"?new mt:u.agentSessionsFailed(`DynamoDB ${h} failed (${C}): ${I??JSON.stringify(L).slice(0,300)}`)}if(typeof L=="string")try{return JSON.parse(L)}catch{throw u.agentSessionsFailed(`DynamoDB ${h}: non-JSON response body`)}return L??{}}async function p(){return(await d("GetItem",{TableName:n,Key:l,ConsistentRead:!0})).Item}let m=!1;async function g(){if(m)return;m=!0;let h=await p();if(!h)return;let S=zt(h,"lastActiveAt")??0;if(!(Date.now()-S<=i*1e3)){if(Object.keys(Gt(h,"pendingApprovals")).length>0)throw new ae(a);await f()}}async function w(h){let S=[],x;do{let C=await d("Query",{TableName:n,KeyConditionExpression:"pk = :pk AND begins_with(sk, :prefix)",ExpressionAttributeValues:{":pk":K(c),":prefix":K(Nr)},ConsistentRead:!0,ScanIndexForward:h.ascending,...h.limit!==void 0?{Limit:h.limit}:{},...h.projection!==void 0?{ProjectionExpression:h.projection}:{},...x!==void 0?{ExclusiveStartKey:x}:{}});if(S.push(...C.Items??[]),x=C.LastEvaluatedKey,h.limit!==void 0&&S.length>=h.limit)break}while(x!==void 0);return S}async function D(h){for(let S=0;S<h.length;S+=Mr){let x=h.slice(S,S+Mr);for(let C=0;x.length>0;C++){let I=(await d("BatchWriteItem",{RequestItems:{[n]:x}})).UnprocessedItems?.[n];if(!I||I.length===0)break;if(C>=Lr)throw u.agentSessionsFailed(`DynamoDB BatchWriteItem: ${I.length} items still unprocessed after ${Lr} retries`);x=I}}}async function f(){let S=(await w({ascending:!0,projection:"sk"})).map(x=>({DeleteRequest:{Key:{pk:K(c),sk:x.sk}}}));S.push({DeleteRequest:{Key:l}}),await D(S)}async function y(h){let S=Date.now();return(await d("UpdateItem",{TableName:n,Key:l,UpdateExpression:"ADD nextSeq :reserve, messageCount :reserve SET lastActiveAt = :now, expiresAt = :expires, createdAt = if_not_exists(createdAt, :now), truncated = if_not_exists(truncated, :false), pendingApprovals = if_not_exists(pendingApprovals, :emptyMap)",ExpressionAttributeValues:{":reserve":je(h),":now":je(S),":expires":je(Math.floor(S/1e3)+i),":false":{BOOL:!1},":emptyMap":{M:{}}},ReturnValues:"ALL_NEW"})).Attributes??{}}async function E(h){let x=(zt(h,"messageCount")??0)-s;if(x<=0)return;let C=new Set(Object.keys(Gt(h,"pendingApprovals"))),L=await w({ascending:!0,limit:x+C.size+mi}),I=L.map(Je=>JSON.parse(Vt(Je,"message")??"null")),ee=jt(I,x,C),Te=L.filter((Je,zo)=>ee.has(zo));Te.length!==0&&(await D(Te.map(Je=>({DeleteRequest:{Key:{pk:K(c),sk:Je.sk}}}))),await d("UpdateItem",{TableName:n,Key:l,UpdateExpression:"ADD messageCount :delta SET truncated = :true",ExpressionAttributeValues:{":delta":je(-Te.length),":true":{BOOL:!0}}}))}return{id:a,async messages(h){await g();let S=h?.limit;return S!==void 0?(await w({ascending:!1,limit:S})).reverse().map(L=>JSON.parse(Vt(L,"message")??"null")):(await w({ascending:!0})).map(C=>JSON.parse(Vt(C,"message")??"null"))},async append(...h){if(h.length===0)return;let S=h.map(ee=>JSON.stringify(ee)),x=S.findIndex(ee=>Buffer.byteLength(ee,"utf8")>pi);if(x!==-1)throw u.agentSessionsFailed(`a ${h[x].role} message of ${Buffer.byteLength(S[x],"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 g();let C=await y(h.length),I=(zt(C,"nextSeq")??h.length)-h.length+1;await D(S.map((ee,Te)=>({PutRequest:{Item:{pk:K(c),sk:K(gi(I+Te)),message:K(ee)}}}))),await E(C)},async clear(){await f()},async truncated(){return await g(),fi(await p(),"truncated")},async pendingApprovals(){await g();let h=Gt(await p(),"pendingApprovals");return Object.values(h).map(S=>{let x=S.S;return x!==void 0?JSON.parse(x):void 0}).filter(S=>S!==void 0)},async addPendingApprovals(h){if(h.length===0)return;await g(),await y(0);let S={},x={},C=[];h.forEach((L,I)=>{S[`#a${I}`]=L.approvalId,x[`:v${I}`]=K(JSON.stringify(L)),C.push(`pendingApprovals.#a${I} = :v${I}`)}),await d("UpdateItem",{TableName:n,Key:l,UpdateExpression:`SET ${C.join(", ")}`,ExpressionAttributeNames:S,ExpressionAttributeValues:x})},async resolveApproval(h){await g();try{return await d("UpdateItem",{TableName:n,Key:l,UpdateExpression:"REMOVE pendingApprovals.#id SET lastActiveAt = :now",ConditionExpression:"attribute_exists(pendingApprovals.#id)",ExpressionAttributeNames:{"#id":h},ExpressionAttributeValues:{":now":je(Date.now())}}),"resolved"}catch(S){if(S instanceof mt)return"already-resolved";throw S}}}}var mt=class extends Error{constructor(){super("ConditionalCheckFailedException"),this.name="ConditionalCheckFailed"}};import hi from"ky";async function H(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 wi=6e4;function $r(e){let t=v();if(t.kind!=="provisioned")throw u.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 Si(){let e=de(),t=$(),n={Accept:"application/json"};if(e&&e.trim().length>0&&(n[ue]=e),t&&t.trim().length>0&&(n[U]=t),Object.keys(n).length===1)throw u.missingExecutionCredentials();return n}async function W(e,t,n){try{let r=await hi(t,{method:e,headers:Si(),...n!==void 0?{json:n}:{},throwHttpErrors:!1,timeout:wi});return{status:r.status,body:await H(r)}}catch(r){throw r instanceof u?r:u.agentSessionsFailed(`managed session store unreachable: ${r instanceof Error?r.message:String(r)}`)}}function Jt(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 ae(e):t===404?new M(`Agent session "${e}" was not found (it may belong to a different user or have expired).`):u.agentSessionsFailed(`managed session store error ${t}: ${Jt(n)}`)}function jr(e){let t=$r(e.agentName),n=e.sessionId??`ses_${crypto.randomUUID().replaceAll("-","")}`,r=e.options?.scope,o=e.options?.ttl??he,s=e.options?.maxSessionMessages??ye,i=async a=>{let c=new URL(`${t}/${encodeURIComponent(n)}/messages`);a!==void 0&&c.searchParams.set("cursor",a);let{status:l,body:d}=await W("get",c.toString());if(l!==404)return(l<200||l>=300)&&le(n,l,d),d};return{id:n,async messages(a){let c=[],l;for(;;){let p=await i(l);if(p===void 0)return[];if(c.push(...p.elements),!p.pageInfo.hasNextPage||p.pageInfo.endCursor===null)break;l=p.pageInfo.endCursor}let d=c.map(p=>p.message);return a?.limit!==void 0?d.slice(-a.limit):d},async append(...a){if(a.length===0)return;let{status:c,body:l}=await W("post",`${t}/${encodeURIComponent(n)}/messages`,{messages:a,...r!==void 0?{scope:r}:{},ttl:o,maxMessages:s});(c<200||c>=300)&&le(n,c,l)},async clear(){let{status:a,body:c}=await W("delete",`${t}/${encodeURIComponent(n)}`);a!==204&&a!==404&&le(n,a,c)},async truncated(){let{status:a,body:c}=await W("get",`${t}/${encodeURIComponent(n)}`);return a===404?!1:((a<200||a>=300)&&le(n,a,c),c.truncated===!0)},async pendingApprovals(){let{status:a,body:c}=await W("get",`${t}/${encodeURIComponent(n)}`);return(a<200||a>=300)&&le(n,a,c),c.pendingApprovals},async addPendingApprovals(a){if(a.length===0)return;let{status:c,body:l}=await W("post",`${t}/${encodeURIComponent(n)}/approvals`,{approvals:a});c!==204&&le(n,c,l)},async resolveApproval(a){let{status:c,body:l}=await W("post",`${t}/${encodeURIComponent(n)}/approvals/${encodeURIComponent(a)}/resolve`);return(c<200||c>=300)&&le(n,c,l),l.status}}}async function Br(e,t={}){let n=$r(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 W("get",r.toString());if(o===400)throw new M(Jt(s));if(o<200||o>=300)throw u.agentSessionsFailed(`managed session store error ${o}: ${Jt(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 Kr(e){if(e?.scope!=="user")return;let t=hn.getStore()?.userId;if(typeof t!="string"||t.length===0)throw new M('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 Hr(){return A().mode==="lambda"}function ft(e,t,n){let r=v(),o=r.agentSessions,s=Kr(n);if(o?.store==="dynamodb"){let i=r.authentications??{},a=i[o.auth];if(!a)throw u.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 Hr()?jr({agentName:e,sessionId:t,options:n}):wr(e,t,n,s)}async function qr(e,t,n={}){if(t?.scope!=="user")throw new M(`agent.sessions() lists the calling user's sessions \u2014 the agent must declare memory.scope: "user".`);if(v().agentSessions?.store==="dynamodb")throw new M('agent.sessions() is not supported on the bring-your-own DynamoDB session store \u2014 use the managed store (agentSessions: { store: "managed" }).');let o=Kr(t);return Hr()?Br(e,n):Sr(e,o,n)}var Jr=new bi;function Ii(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:Xt.INTERNAL,attributes:{agent:e,tool:t,...n}},async o=>{try{let s=await r();return o.setAttribute("status","success"),o.setStatus({code:ve.OK}),s}catch(s){throw o.setAttribute("status","error"),o.setStatus({code:ve.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o.end()}})}function Ri(e){let t={};for(let n of e.tools??[]){let r=n.needsApproval;t[n.name]=zr({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,Xe()))})}for(let n of e.agents??[]){let r=Ue(n),o=`agent_${n.replaceAll("-","_")}`;t[o]=zr({description:r.description,inputSchema:Vr.object({prompt:Vr.string().describe("The task or question for the agent")}),execute:({prompt:s})=>Xr(e.name,o,{delegateAgent:n},async()=>{let i=Jr.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 Jr.run(i+1,()=>_i(n).generate({prompt:s}))).text})})}return t}function Ti(e){let t=[{model:e.model,auth:e.auth},...e.fallbacks??[]];return Fr(t.map(n=>Kt(n.auth)(n.model)))}function Yt(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 Ci(e){return{id:e.approvalId,toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input}}function ki(e){let t=new Set;for(let n of e)if(Array.isArray(n.content))for(let r of Yt(n.content))t.add(r.approvalId);return t}function Pi(e,t){let n=e.reduce((r,o)=>r+lt(o.response.modelId??t,o.usage).amount,0);return{amount:Number(n.toFixed(8)),currency:"USD"}}async function Oi(e,t,n){let r=[],o=[];if(n.approvals&&n.approvals.length>0){let s=new Map((await e.pendingApprovals()).map(l=>[l.approvalId,l])),i=ki(t),a=n.approvals.map(l=>l.id).filter(l=>!s.has(l)&&!i.has(l));if(a.length>0)throw new M(`Unknown approval id(s) for session "${e.id}": ${a.join(", ")} \u2014 use the ids from \`pendingApprovals\` on the paused result.`);let c=[];for(let l of n.approvals){let d=s.get(l.id);!d||await e.resolveApproval(l.id)==="already-resolved"||(o.push(d),c.push({type:"tool-approval-response",approvalId:l.id,approved:l.approved,...l.reason!==void 0?{reason:l.reason}:{}}))}c.length>0&&r.push({role:"tool",content:c})}if(n.prompt!==void 0?r.push({role:"user",content:n.prompt}):n.messages&&r.push(...n.messages),r.length===0)throw new M("agent.generate() requires `prompt`, `messages`, or `approvals` \u2014 nothing to do.");return{turn:r,claimed:o}}function _i(e){let t=Ue(e);mr(e);let n=pr(e),r=Ti(t),o=Ri(t),s=t.limits?.maxIterations??gr,i=t.limits?.maxToolCalls??yr,a=c=>({model:r,system:n,tools:o,stopWhen:c.stopWhen??[Ai(s),Ii(i)],...c.prepareStep!==void 0?{prepareStep:c.prepareStep}:{},...c.activeTools!==void 0?{activeTools:c.activeTools}:{},...c.toolChoice!==void 0?{toolChoice:c.toolChoice}:{},...c.providerOptions!==void 0?{providerOptions:c.providerOptions}:{}});return{model:r,tools:o,instructions:n,session(c){return ft(e,c,t.memory)},sessions(c){return qr(e,t.memory,c)},async generate(c){return F.startActiveSpan("agent.generate",{kind:Xt.INTERNAL,attributes:{agent:e,model:t.model}},async l=>{let d=ft(e,c.sessionId,t.memory);l.setAttribute("sessionId",d.id),k("hasAi");let p=[];try{let m=await d.messages(),g=await Oi(d,m,c);p=g.claimed;let w;try{w=await vi({...a(c),messages:[...m,...g.turn]})}catch(y){if(p.length>0)try{await d.addPendingApprovals(p),p=[]}catch(E){console.error(`[helix-sdk] agent "${e}" session "${d.id}": failed to restore ${p.length} pending approval(s) after a failed resume \u2014 ${E instanceof Error?E.message:String(E)}`)}throw y}let D=Yt(w.content),f=D.length>0?"awaiting-approval":"completed";return await d.append(...g.turn,...w.response.messages),D.length>0&&await d.addPendingApprovals(D.map(Yr)),l.setAttributes({steps:w.steps.length,status:f}),l.setStatus({code:ve.OK}),Object.assign(w,{sessionId:d.id,status:f,...D.length>0?{pendingApprovals:D.map(Ci)}:{},helix:{cost:Pi(w.steps,t.model),model:w.response.modelId??t.model}})}catch(m){throw l.setAttribute("status","error"),l.setStatus({code:ve.ERROR,message:m instanceof Error?m.message:String(m)}),m}finally{l.end()}})},async stream(c){let l=F.startSpan("agent.stream",{kind:Xt.INTERNAL,attributes:{agent:e,model:t.model}}),d=!1,p=(m,g)=>{d||(d=!0,l.setAttribute("status",m),l.setStatus(m==="error"?{code:ve.ERROR,...g!==void 0?{message:g}:{}}:{code:ve.OK}),l.end())};try{let m=ft(e,c.sessionId,t.memory);if(l.setAttribute("sessionId",m.id),k("hasAi"),c.approvals&&c.approvals.length>0)throw new M("agent.stream() does not accept approvals \u2014 resume paused runs with generate().");if(c.prompt===void 0&&!c.messages)throw new M("agent.stream() requires `prompt` or `messages`.");let g=c.prompt!==void 0?[{role:"user",content:c.prompt}]:[...c.messages],w=await m.messages(),D=Gr.with(Ei.setSpan(Gr.active(),l),()=>xi({...a(c),messages:[...w,...g],onFinish:async f=>{try{await m.append(...g,...f.response.messages);let y=Yt(f.content);y.length>0&&await m.addPendingApprovals(y.map(Yr)),p(y.length>0?"awaiting-approval":"completed")}catch(y){let E=y instanceof Error?y.message:String(y);console.error(`[helix-sdk] agent "${e}" session "${m.id}": failed to persist the streamed turn \u2014 ${E}`),p("error",E)}},onError:({error:f})=>{p("error",f instanceof Error?f.message:String(f))},onAbort:()=>{p("error","stream aborted")}}));return Object.assign(D,{sessionId:m.id})}catch(m){throw p("error",m instanceof Error?m.message:String(m)),m}}}}var Wr="helix-schedule",Q=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function $u(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"||!Di(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:Wr,cron:t.trim(),timezone:n,concurrent:r,handler:o})}function ju(e){return typeof e=="object"&&e!==null&&e.kind===Wr&&typeof e.handler=="function"}function Di(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 Fi}from"@opentelemetry/api";function gt(e,t,n){let r=F.startSpan("log",{kind:Fi.INTERNAL});r.setAttribute("message",t),r.setAttribute("level",e),n&&zn(r.spanContext().spanId,"properties",n),r.end(),_n(e,t,n)}function Qr(){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 Gu(){try{return v().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import Mi from"ky";import{context as Wt,trace as Li,SpanKind as Ke,SpanStatusCode as eo}from"@opentelemetry/api";async function Zr(e){xn(e.url);let t=A(),{region:n}=v(),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}=G(t);s&&(r.deploymentId=s);let i=An(n,t.mode==="lambda"?"runtime":"dev"),a;try{a=await En({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 u.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 u.brokerError(a.status,c,R(a.body),a.code)}return a.result}var Ni=new Set([Ce,Ye,te,ke,"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 Ui(e){let t=e.toLowerCase();return Ni.has(t)||t.startsWith("x-tray-internal-")}async function $i(e,t){let n=e instanceof Request?e:new Request(e,t),r=new URL(n.url);if(r.protocol!=="https:")throw u.unsupportedScheme(r.protocol.replace(/:$/,""));let o=A(),{region:s}=v(),{headers:i,deploymentId:a}=G(o),c=me(s,o.mode==="lambda"?"runtime":"dev"),l=new Headers;for(let[g,w]of n.headers.entries())Ui(g)||l.append(g,w);l.set(Ce,n.url);for(let[g,w]of Object.entries(i))l.set(g,w);a&&l.set(te,a),o.executionId&&l.set(ke,o.executionId);let d={method:n.method,headers:l,redirect:"manual",signal:n.signal};n.body&&(d.body=n.body,d.duplex="half");let p;try{p=await fetch(c,d)}catch(g){throw g instanceof Error&&g.name==="AbortError"?g:u.brokerError(0,g instanceof Error?g.message:String(g))}let m=p.headers.get(We);return m!==null&&qt(await bn(p,m)),p}var ji=["get","post","put","patch","delete","head","options"],no="[stream body omitted]";function ro(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?no: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 Qt(e){try{return new URL(e).hostname}catch{return e}}function to(e,t,n,r,o){let s=Qt(t),i="externalApi",a={kind:Ke.CLIENT};return F.startActiveSpan(i,a,async c=>(c.setAttributes({method:e,host:s,"peer.service":r}),V(c,"request",{url:t,method:e,...n!==void 0?{body:ro(n)}:{}}),o(c)))}function Be(e,t,n){e.setAttribute("status",t),e.setStatus(t==="success"?{code:eo.OK}:{code:eo.ERROR,message:n}),e.end()}var Bi=16;async function Ki(e,t){let n=e.clone().body;return n?oo(n,t):new Uint8Array(0)}async function oo(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>=Bi)break;continue}s=0;let d=t+1-o;if(l.byteLength>=d){r.push(l.slice(0,d)),o+=d;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 so(e,t,n){if("kyResponse"in n)try{let r=await Ki(n.kyResponse,Oe),o=new TextDecoder("utf-8").decode(r,{stream:!0}),s;try{s=JSON.parse(o)}catch{s=o}V(e,"response",s)}catch{V(e,"response",{status:t})}else V(e,"response",ro(n.bodyValue))}async function Hi(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 oo(o,Oe);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:no}}}return typeof t=="string"?{body:t}:{}}function pd(){let e=Mi.create({fetch:$i,retry:{shouldRetry:({error:r})=>r instanceof u?!1:void 0}});function t(r){return(o,s)=>{let i=Wt.active(),a,c=!1,l=(p,m)=>{a&&!c&&(c=!0,Be(a,p,m))},d=e.extend({hooks:{beforeRequest:[async(p,m)=>{let g=await Hi(p,m.body),w=g.body;if(a||(a=F.startSpan("externalApi",{kind:Ke.CLIENT},i)),a.setAttributes({method:p.method.toUpperCase(),host:Qt(p.url)}),V(a,"request",{url:p.url,method:p.method.toUpperCase(),...w!==void 0?{body:w}:{}}),c=!1,k("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 so(a,g.status,{kyResponse:g}),g.ok?l("success"):s?.throwHttpErrors===!1&&(k("hasError"),l("error",`HTTP ${g.status}`)))}],beforeError:[p=>(k("hasError"),l("error",p.message),p)]}});return a=F.startSpan("externalApi",{kind:Ke.CLIENT},i),a.setAttributes({method:r.toUpperCase(),host:Qt(String(o))}),Wt.with(Li.setSpan(Wt.active(),a),()=>{let p=r==="options"?d(o,{...s,method:"OPTIONS"}):d[r](o,s);return p.catch(m=>{k("hasError"),l("error",m instanceof Error?m.message:String(m))}),p})}}let n=Object.fromEntries(ji.map(r=>[r,t(r)]));return{...e,...n,authed(r){return qi(r)}}}function qi(e){let n=v().authentications??{};if(!n[e])throw u.unknownAlias(e,Object.keys(n));let r=n[e];function o(i){return(a,c={})=>{let l=i.toUpperCase();return to(l,a,c.body,e,async d=>{k("hasAuth");let p=F.startSpan("auth",{kind:Ke.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 be(m,{timeout:c.timeout});return d.setAttribute("statusCode",g.status),await so(d,g.status,{bodyValue:g.body}),Be(d,"success"),g}catch(m){throw k("hasError"),m instanceof u&&m.detail.kind==="broker_error"&&m.detail.status>0&&d.setAttribute("statusCode",m.detail.status),Be(d,"error",m instanceof Error?m.message:String(m)),m}})}}function s(i,a={}){let c=a.method??"GET";return to(c,i,void 0,e,async l=>{k("hasAuth");let d=F.startSpan("auth",{kind:Ke.INTERNAL});d.setAttribute("alias",e),d.setAttribute("id",r),d.end();try{let p=await Zr({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),Be(l,"success"),p}catch(p){throw k("hasError"),p instanceof u&&p.detail.kind==="broker_error"&&p.detail.status>0&&l.setAttribute("statusCode",p.detail.status),Be(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 Zi,SpanStatusCode as lo}from"@opentelemetry/api";function He(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Vi=18e4,io=Vi-1e4,zi=2e3;async function ao(e,t,n){let r=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<io;){let i=await e(t,"DescribeStatement",{Id:n}),a=i.Status;if(r.has(a))return i;let c=Math.min(zi,200*2**s),l=c/2+Math.random()*(c/2),d=io-(Date.now()-o);await new Promise(p=>setTimeout(p,Math.min(l,d))),s++}throw u.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Gi=new Set(["SELECT","WITH","SHOW"]),Ji=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function Xi(e){if(!e.clusterIdentifier&&!e.workgroupName)throw u.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw u.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw u.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw u.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw u.dbInvalidParameters("region is required")}function Yi(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 u.dbQueryFailed(`${r}: ${o}`);let s=typeof t=="string"?re(t):R(t);return u.dbCallFailed(s)}function Wi(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw u.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Qi(e,t){return typeof t!="number"||t<0?{}:Gi.has(e)?{rowsRead:t}:Ji.has(e)?{rowsWritten:t}:{}}function co(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 be(s);if(i>=400)throw Yi(i,a);return Wi(a)}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw u.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:Xi,async execute(n,r){let o=He(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=R(i);throw u.dbCallFailed(`ExecuteStatement response missing Id; got: ${g}`)}let l=await ao(t,n.region,c),d=l.Status;if(d==="FAILED"){let g=typeof l.Error=="string"?l.Error:"statement failed";throw u.dbQueryFailed(`${g} (statement: ${c})`)}if(d==="ABORTED")throw u.dbQueryFailed(`statement aborted (statement: ${c})`);let p=Qi(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 Zt=64*1024;function ea(e){return e.length>Zt?`${e.slice(0,Zt)}...[truncated]`:e}function ta(e,t,n,r,o){e.setAttributes({system:t.system,statement:o,namespace:n.database,operation:r})}function na(e,t,n){let r=typeof t=="string"?t:JSON.stringify(t);return r.length>Zt?V(e,"result",{truncated:!0,size:r.length}):V(e,"result",t),n.rowsRead!==void 0&&e.setAttribute("rowsRead",n.rowsRead),n.rowsWritten!==void 0&&e.setAttribute("rowsWritten",n.rowsWritten),r}async function ra(e,t,n){let r=He(n),o=ea(n);return F.startActiveSpan("database",{kind:Zi.CLIENT},async s=>{ta(s,e,t,r,o);try{k("hasDb");let{result:i,metadata:a}=await e.execute(t,n),c=na(s,i,a);return s.setAttribute("status","success"),s.setStatus({code:lo.OK}),c}catch(i){k("hasError");let a=i instanceof Error?i.message:String(i);throw s.setAttribute("status","error"),s.setStatus({code:lo.ERROR,message:a}),i}finally{s.end()}})}function oa(e){let n=v().authentications??{};if(!n[e])throw u.unknownAlias(e,Object.keys(n));let r=n[e],o=co(r);function s(i,a){return o.validate(i),ra(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as la}from"unstorage";var uo=1024,en=250*1024,sa=new TextEncoder,ia=/(^|\/)\.\.(\/|$)/,aa=/[?#]/,ca=/[\u0000-\u001F\u007F]/;function po(e){if(e.length===0)throw u.kvKeyInvalid("Key must be a non-empty string");if(ia.test(e))throw u.kvKeyInvalid("Key contains path traversal segment");if(aa.test(e)||ca.test(e))throw u.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(n=>n===""))throw u.kvKeyInvalid("Key must not contain empty path segments");let t=sa.encode(e).length;if(t<1||t>uo)throw u.kvKeyInvalid(`Key must be between 1 and ${uo} UTF-8 bytes (got ${t})`)}function mo(e){if(!Number.isInteger(e)||e<=0)throw u.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function fo(e){let t;try{t=JSON.stringify(e)}catch{throw u.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw u.kvValueInvalid("Value must be JSON-serializable");let n=Buffer.byteLength(t,"utf8");if(n>en)throw u.kvValueTooLarge(`Value exceeds maximum size of ${en} bytes (got ${n})`,en)}function qe(e){po(e)}function yt(e,t){let n=e[t];if(typeof n!="function")throw new Error(`KV driver is missing ${t}`);return n}function go(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 qe(i),t(i,a)},setItem(i,a,c){return qe(i),n(i,a,c)},removeItem(i,a){return qe(i),r(i,a)},hasItem(i,a){return qe(i),o(i,a)},getKeys(i,a){return i.length>0&&qe(i),s(i,a)}}}function ht(e){return la({driver:go(e)})}import{defineDriver as ua}from"unstorage";function da(e){try{return JSON.parse(e)}catch{return e}}var pa=ua(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=da(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 yo(e){return pa({client:e})}import ga from"ky";import{z as _}from"zod";function ho(e){return j(e).hosts.api}function ma(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function fa(e){return e.split("/").map(encodeURIComponent).join("/")}function Ve(e,t,n){return`${e}${ma(t)}/${fa(n)}`}var ya=6e4,tn=_.lazy(()=>_.union([_.string(),_.number(),_.boolean(),_.null(),_.array(tn),_.record(tn)])),ha=_.object({projectId:_.string(),key:_.string(),value:tn,type:_.enum(["string","number","boolean","null","array","object"]),organizationId:_.string(),scope:_.string(),createdBy:_.string(),createdAt:_.number(),updatedBy:_.string(),updatedAt:_.number()});function wa(){let e=de(),t=$(),n=!!(e&&e.trim().length>0),r=!!(t&&t.trim().length>0);if(!n&&!r)throw u.missingExecutionCredentials();let o={Accept:"application/json"};return n&&(o[ue]=e),r&&(o[U]=t),o}function Sa(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 u.kvCallFailed(e,Sa(t),R(t))}async function St(e,t,n={}){try{let r=await ga(t,{method:e,headers:wa(),...n.json!==void 0?{json:n.json}:{},throwHttpErrors:!1,timeout:ya}),o=e==="head"?void 0:await H(r);return{status:r.status,body:o}}catch(r){if(r instanceof u)throw r;let o=r instanceof Error?r.message??String(r):String(r);throw u.kvCallFailed(0,o)}}function wo(e){let t=ho(e.env),{projectId:n}=e;return{async get(r){let{status:o,body:s}=await St("get",Ve(t,n,r));if(o===404)return null;(o<200||o>=300)&&wt(o,s);let i=ha.safeParse(s);if(!i.success)throw u.kvCallFailed(o,"platform returned malformed KeyValueEntry",R(s));return i.data.value},async set(r,o,s){let{status:i,body:a}=await St("put",Ve(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",Ve(t,n,r));o!==204&&wt(o,s)},async has(r){let{status:o,body:s}=await St("head",Ve(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;fo(n),typeof o=="number"&&mo(o),await e.setItem(t,n,o!==void 0?{ttl:o}:void 0)}}}function ba(){let e=v();if(e.kind!=="provisioned")throw u.kvRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function So(e){let t=ba(),n=e??wo(t),r=ht(yo(n));return bt(r)}import{defineDriver as va}from"unstorage";var xa=va(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 bo(){return xa({})}var nn;function Aa(){return nn||(nn=ht(bo())),nn}function vo(){return bt(Aa())}function Ea(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":A().mode==="lambda"}function yp(){return Ea()?So():vo()}import{createHash as Ta}from"crypto";import{mkdir as Ca,readFile as Ro,readdir as To,rm as Ao,unlink as ka,writeFile as Eo}from"fs/promises";import{dirname as Pa}from"path";async function Ia(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>J)throw await t.cancel(),u.filesValueTooLarge(`File exceeds maximum size of ${J} bytes (got more than ${J})`,J);n.push(s)}}return Buffer.concat(n)}async function xe(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?Ia(e):Buffer.from(e)}var Ra={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"},xo="application/octet-stream";function vt(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return xo;let n=e.slice(t+1).toLowerCase();return Ra[n]??xo}function Ee(){let e=A().projectRoot;if(!e)throw u.filesNotAvailable();return e}async function Ae(e){try{return await e()}catch(t){if(t instanceof u)throw t;let n=t?.code;throw n?u.filesCallFailed(0,`Local file storage operation failed: ${n}`):u.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 rn(e){try{let t=await Ro(it(Ee(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Io(e){await Ca(Pa(e),{recursive:!0})}async function Oa(e,t){let n=at(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 Co(e,t){let n=at(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 Co(e,i)):s.isFile()&&o.push(i)}return o}function ko(){return{async put(e,t,n){return Ae(async()=>{let r=Ee(),o=await xe(t),s=n?.contentType??vt(e),i=Ta("sha1").update(o).digest("hex"),a=new Date,c=Le(r,e);await Io(c),await Eo(c,o);let l={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},d=it(r,e);return await Io(d),await Eo(d,JSON.stringify(l)),xt(e,l)})},async get(e){return Ae(async()=>{let t=await rn(e);return t?{data:await Ro(Le(Ee(),e)),metadata:xt(e,t)}:null})},async head(e){return Ae(async()=>{let t=await rn(e);return t?xt(e,t):null})},async delete(e){return Ae(async()=>{let t=Ee();await Promise.all([Le(t,e),it(t,e)].map(async n=>{try{await ka(n)}catch(r){if(r.code!=="ENOENT")throw r}}))})},async deleteMany(e){return Ae(async()=>{let t=Ee(),n=await Co(t,e);return await Promise.all([Ao(at(t,e),{recursive:!0,force:!0}),Ao(Zn(t,e),{recursive:!0,force:!0})]),{deleted:n.length}})},async list(e,t){return Ae(async()=>{let n=Ee(),r=t?.limit??100,s=(await Oa(n,e??"")).slice(0,r);return{files:(await Promise.all(s.map(async a=>{let c=await rn(a);return c?xt(a,c):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let n=A().devServerUrl;if(!n)throw u.filesNotAvailable();return{url:`${n}/_helix/files/${e}`,expiresAt:ge(t?.expiresIn)}},async getDownloadUrl(e,t){let n=A().devServerUrl;if(!n)throw u.filesNotAvailable();return{url:`${n}/_helix/files/${e}`,expiresAt:ge(t?.expiresIn)}}}}import{createHash as Ua}from"crypto";function At(e){return j(e).hosts.api}function _a(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ze(e,t){return`${e}${_a(t)}`}function Ie(e,t,n){return`${ze(e,t)}/${encodeURIComponent(n)}`}function Et(e,t,n){return`${Ie(e,t,n)}/upload`}function Po(e,t,n){return`${Ie(e,t,n)}/download`}function Oo(e,t,n){return`${Ie(e,t,n)}/signed-url`}function _o(e,t,n,r){let o=new URLSearchParams({name:r});return n&&o.set("parentFolder",n),`${ze(e,t)}/file?${o.toString()}`}function Do(e,t,n,r){let o=new URLSearchParams({limit:String(r)});return n&&o.set("id",n),`${ze(e,t)}?${o.toString()}`}import sn from"ky";import{z as P}from"zod";var an=6e4,Fo=P.object({id:P.string(),workspaceId:P.string(),projectId:P.string(),parentFolder:P.string().nullable().optional(),name:P.string(),size:P.number().nullable().optional(),objectType:P.enum(["Folder","File"]),contentType:P.string().nullable().optional(),createdAt:P.string(),updatedAt:P.string()}),Da=P.object({signedURL:P.string()}),Fa=P.object({path:P.array(P.object({id:P.string(),name:P.string()})),elements:P.array(Fo)});function cn(){let e=de(),t=$(),n=!!(e&&e.trim().length>0),r=!!(t&&t.trim().length>0);if(!n&&!r)throw u.missingExecutionCredentials();let o={Accept:"application/json"};return n&&(o[ue]=e),r&&(o[U]=t),o}function Mo(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 u.filesCallFailed(e,Mo(t),R(t))}function Ma(e,t){return e===400&&Mo(t).toLowerCase()==="resource not found"}async function La(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 Re(e,t,n={}){try{let r=await sn(t,{method:e,headers:cn(),...n.json!==void 0?{json:n.json}:{},throwHttpErrors:!1,timeout:an}),o=await H(r);return{status:r.status,body:o}}catch(r){if(r instanceof u)throw r;let o=r instanceof Error?r.message:String(r);throw u.filesCallFailed(0,o)}}function on(e,t){let n=Fo.safeParse(t);if(!n.success)throw u.filesCallFailed(e,"platform returned malformed ObjectMetadata",R(t));return n.data}function Lo(e){let t=At(e.env),{projectId:n}=e;return{async createMetadata(r){let{status:o,body:s}=await Re("post",ze(t,n),{json:r});return(o<200||o>=300)&&Z(o,s),on(o,s)},async getByName(r,o){let{status:s,body:i}=await Re("get",_o(t,n,r,o));return s===404||Ma(s,i)?null:((s<200||s>=300)&&Z(s,i),on(s,i))},async getById(r){let{status:o,body:s}=await Re("get",Ie(t,n,r));return o===404?null:((o<200||o>=300)&&Z(o,s),on(o,s))},async listChildren(r,o){let{status:s,body:i}=await Re("get",Do(t,n,r,o));(s<200||s>=300)&&Z(s,i);let a=Fa.safeParse(i);if(!a.success)throw u.filesCallFailed(s,"platform returned malformed listing",R(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 La(a),d;try{d=await sn(Et(t,n,r),{method:"post",headers:{...cn(),"content-type":l},body:new Uint8Array(c),throwHttpErrors:!1,timeout:an})}catch(m){if(m instanceof u)throw m;let g=m instanceof Error?m.message:String(m);throw u.filesCallFailed(0,g)}let p=await H(d);(d.status<200||d.status>=300)&&Z(d.status,p)},async downloadContent(r){let o;try{o=await sn(Po(t,n,r),{method:"get",headers:cn(),throwHttpErrors:!1,timeout:an})}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message:String(i);throw u.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await H(o);Z(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(r){let{status:o,body:s}=await Re("get",Oo(t,n,r));(o<200||o>=300)&&Z(o,s);let i=Da.safeParse(s);if(!i.success)throw u.filesCallFailed(o,"platform returned malformed signed URL response",R(s));return i.data.signedURL},async deleteById(r){let{status:o,body:s}=await Re("delete",Ie(t,n,r));o===204||o===404||(o<200||o>=300)&&Z(o,s)}}}function ln(e){return e.split("/").filter(t=>t.length>0)}function un(e){return e instanceof u&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Na(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(un(o)){let s=await e.getByName(t,n);if(s)return s}throw o}}async function dn(e,t){let n=ln(t),r=n[n.length-1],o;for(let s of n.slice(0,-1))o=(await Na(e,o,s)).id;return{parentFolder:o,name:r}}async function Ge(e,t){let n=ln(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 pn(e,t){if(t.length===0)return;let n=ln(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 $a=500,ja=8;async function Ba(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 Ka(){let e=v();if(e.kind!=="provisioned")throw u.filesRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function Ha(e){return Ua("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:Ha(t)}}async function No(e,t,n,r){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:r,name:n})}catch(o){if(un(o)){let s=await e.getByName(t,n);if(s)return s}throw o}}async function Uo(e,t){let{elements:n}=await e.listChildren(t,$a);return(await Ba(n,ja,async o=>{let s=o.objectType==="Folder"?await Uo(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function $o(e){let t=Ka(),n=e??Lo(t),r=At(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:c,name:l}=await dn(n,s),d=await xe(i),p=a?.contentType??vt(s),m=await n.getByName(c,l);if(m&&m.objectType!=="File")throw u.filesCallFailed(409,`A folder already exists at "${s}"`);let g=m??await No(n,c,l,p);await n.uploadContent(g.id,d,l,p);let w=await n.getById(g.id);return It(s,w??g,p)},async get(s){let i=await Ge(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 Ge(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 Ge(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 pn(n,s);if(i===null)return{deleted:0};let a=await Uo(n,i);return s.length>0&&i!==void 0&&await n.deleteById(i),{deleted:a}},async list(s,i){let a=await pn(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 dn(n,s),d=await n.getByName(a,c)??await No(n,a,c,i?.contentType);return{url:Et(r,o,d.id),expiresAt:ge(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await Ge(n,s),c=a?await n.getByName(a.parentFolder,a.name):null;if(!c||c.objectType!=="File")throw u.filesCallFailed(404,`File not found: ${s}`);return{url:await n.getSignedDownloadUrl(c.id),expiresAt:ge(i?.expiresIn)}}}}function mn(e,t){let n=t?.maxPathBytes;return{async put(r,o,s){ie(r,n);let i=await xe(o);return Wn(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=Ft(r);return ot(o,n),e.deleteMany(o)},async list(r,o){let s=Ft(r??"");return ot(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 qa(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":A().mode==="lambda"}function cm(){if(qa())return mn($o());let e=A().projectRoot;return mn(ko(),{maxPathBytes:e?Qn(e):void 0})}import za from"ky";function jo(e){return j(e).hosts.api}function Va(){return"/private/v1/helix/function-calls"}function Bo(e){return`${e}${Va()}`}var Ga=5e3;function Ja(){let e=$();if(!!!(e&&e.trim().length>0))throw u.callFunctionMissingExecutionJwt();return{Accept:"application/json",[U]:e}}function Xa(e,t){throw u.callFunctionCallFailed(e,Ya(t),R(t))}function Ya(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 Ko(e){let t=jo(e.env);return{async callAsync(n,r){let o,s;try{let i=await za(Bo(t),{method:"post",headers:Ja(),json:{functionPath:n,input:r},throwHttpErrors:!1,timeout:Ga});o=i.status,s=await H(i)}catch(i){if(i instanceof u)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw u.callFunctionCallFailed(0,a)}(o<200||o>=300)&&Xa(o,s)}}}var Ho=1024;function Rt(e){if(typeof e!="string"||e.trim().length===0)throw u.callFunctionPathInvalid("functionPath must be a non-empty string");if(e.length>Ho)throw u.callFunctionPathInvalid(`functionPath must be at most ${Ho} characters`)}function Wa(){let e=v();if(e.kind!=="provisioned")throw u.callFunctionRequiresProvisioning();return{env:e.region}}function qo(e){return async function(n,r){Rt(n),await(e??Ko(Wa())).callAsync(n,r)}}function Vo(){return async function(t,n){Rt(t);let r=A().devServerUrl;if(!r)throw u.callFunctionNotAvailable();let o=t.startsWith("/")?t:`/${t}`,s=Qr();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 Qa(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":A().mode==="lambda"}function Fm(){return Qa()?qo():Vo()}export{Za as a,ec as b,tc as c,v as d,nc as e,Vn as f,fs as g,k as h,V as i,Ss as j,bs as k,F as l,vs as m,Pc as n,Qr as o,Gu as p,pd as q,oa as r,yp as s,ie as t,Le as u,it as v,cm as w,Fm as x,Uc as y,Mt as z,nr as A,rr as B,or as C,Ne as D,sr as E,Gc as F,cr as G,Lt as H,Ls as I,$s as J,js as K,Jc as L,Bs as M,Xc as N,Hl as O,lr as P,Zc as Q,ur as R,M as S,sl as T,il as U,Ue as V,al as W,cl as X,fr as Y,ml as Z,fl as _,ae as $,hl as aa,Ii as ba,_i as ca,Wr as da,Q as ea,$u as fa,ju as ga};
|