@trayai/helix-sdk 1.2.0 → 1.4.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 +19 -0
- package/README.md +3 -3
- package/dist/broker/index.js +1 -1
- package/dist/{chunk-HEA646WT.js → chunk-HCGX7VQE.js} +1 -1
- package/dist/chunk-UKKHDA5X.js +7 -0
- package/dist/index.js +1 -1
- package/dist/internal/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-CYG3GXE2.js +0 -7
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,25 @@ 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
|
+
|
|
26
|
+
## 1.3.0
|
|
27
|
+
|
|
28
|
+
No user-visible changes in this release — co-versioned with `@trayai/helix-cli`'s changes.
|
|
29
|
+
|
|
11
30
|
## 1.0.0
|
|
12
31
|
|
|
13
32
|
### Changed
|
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-HCGX7VQE.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var S="X-Helix-Project-Execution-Token",P="X-Tray-Token",$={mode:"dev",deploymentId:null},h={...$},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),h={...h,...i}}function ne(){return h}function I(){return p.internalJwt}function T(){return p.helixExecutionJwt}function N(){return p.devToken}var C=new Set(["us1","eu1","ap1","ap2"]),o=new Map,v={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"}},x={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"}},E={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"}},w={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"}};o.set(v.name,v);o.set(x.name,x);o.set(E.name,E);o.set(w.name,w);var D=["api","broker","ingest","weaver","app","projectHost","dashboard"],A=["auth"],U=["storePrefix","appUrl","cookieName","cookieDomain"];function j(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 D)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 A){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 U)if(typeof e.login[r]!="string"||!e.login[r])throw new Error(`RegionProfile.login.${r} must be a non-empty string`)}function H(e,r){return e.name===r.name&&e.exposedName===r.exposedName&&e.displayName===r.displayName&&D.every(t=>e.hosts[t]===r.hosts[t])&&A.every(t=>e.hosts[t]===r.hosts[t])&&U.every(t=>e.login[t]===r.login[t])}function oe(e){j(e);let r=o.get(e.name);if(r){if(H(r,e))return;throw new Error(`RegionProfile.name "${e.name}" is already registered with different values`)}for(let t of o.values())if(t.exposedName===e.exposedName)throw new Error(`RegionProfile.exposedName "${e.exposedName}" is already used by "${t.name}"`);o.set(e.name,e)}function F(e){return o.has(e)}function se(e){return o.get(e)}function _(e){let r=o.get(e);if(!r)throw new Error(`Unknown region: ${e}`);return r}function ae(){return[...o.keys()]}function de(){return[...o.values()].map(e=>e.exposedName)}function B(e){for(let r of o.values())if(r.exposedName===e)return r.name}var m=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function L(e){let r=globalThis;if(e===void 0||e.trim()===""){delete r[m];return}let t=e.trim(),n=B(t);if(n){r[m]=n;return}if(F(t)){r[m]=t;return}throw new Error(`Unknown region: ${t}`)}function le(){return globalThis[m]}function ue(){return[...o.values()].filter(e=>!C.has(e.name))}function ce(){L(void 0),o.clear();for(let e of[v,x,E,w])o.set(e.name,{...e,hosts:{...e.hosts},login:{...e.login}})}var u=class e extends Error{detail;constructor(r){super(J(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"})}};function ge(e){return e instanceof u}function J(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."}}import{z as g}from"zod";var q="x-helix-destination-url",O="x-helix-authentication-id",M="x-helix-deployment-id",y="x-execution-id",K="x-helix-broker-error",he="route_not_found",V=new Set([q,O,M,"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",y]);function G(e){let r=e.toLowerCase();return V.has(r)||r.startsWith("x-tray-internal-")}var b=g.object({error:g.object({code:g.string(),message:g.string(),issues:g.array(g.unknown()).optional()})});function ve(e,r){let t=`${_(e).hosts.api}/private/v1/helix/broker/http/raw`;return r==="dev"?`${t}/dev`:t}function xe(e){if(e.mode==="lambda"){let t=I(),n=T(),i=!!(t&&t.trim().length>0),a=!!(n&&n.trim().length>0);if(!i&&!a)throw u.missingExecutionCredentials();let l={};return i&&(l[P]=t),a&&(l[S]=n),{headers:l,deploymentId:e.deploymentId??null}}let r=N();if(!r)throw u.missingTrayToken();return{headers:{Authorization:`Bearer ${r}`},deploymentId:null}}function X(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[d,s]of e.query.entries())r.searchParams.append(d,s);else for(let[d,s]of Object.entries(e.query))for(let f of Array.isArray(s)?s:[s])r.searchParams.append(d,f);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(([d])=>!G(d)),i=e.body!==void 0&&e.body!==null,a,l,c=!1;return i&&(X(e.body)?(a=e.body,c=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(a=JSON.stringify(e.body),n.some(([s])=>s.toLowerCase()==="content-type")||(l="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:r.toString(),headers:n,body:a,isStreamBody:c,defaultContentType:l}}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[d,s]of r.headers)t.append(d,s);r.defaultContentType&&!t.has("content-type")&&t.set("content-type",r.defaultContentType),t.set(q,r.destinationUrl),t.set(O,r.authenticationId);for(let[d,s]of Object.entries(e.credentialHeaders))t.set(d,s);e.executionId&&t.set(y,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),a=i.headers.get(K);if(a!==null){let d=await i.text(),s=d,f=d||a;try{s=JSON.parse(d);let R=b.safeParse(s);R.success&&(f=R.data.error.message)}catch{}return{kind:"brokerError",status:i.status,code:a,message:f,body:s}}let l=new Uint8Array(await i.arrayBuffer()),c=i.headers.get("content-type")??"";return{kind:"upstream",response:{status:i.status,headers:Z(i.headers),body:Q(l,c)}}}import{z as k}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=`${_(e).hosts.api}/private/v1/helix/broker/s3/sign`;return r==="dev"?`${t}/dev`:t}var re=k.object({url:k.string(),method:k.string(),expiresAt:k.string()});async function De(e){let r=new Headers({"content-type":"application/json"});for(let[l,c]of Object.entries(e.credentialHeaders))r.set(l,c);e.executionId&&r.set(y,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 l=re.safeParse(i);return l.success?{kind:"signed",result:l.data}:{kind:"brokerError",status:t.status,message:"malformed s3-sign response from credential broker",body:i}}let a=b.safeParse(i);return a.success?{kind:"brokerError",status:t.status,code:a.data.error.code,message:a.data.error.message,body:i}:{kind:"brokerError",status:t.status,message:n||`s3-sign request failed with status ${t.status}`,body:i}}export{S as a,P as b,te as c,ne as d,I as e,T as f,oe as g,F as h,se as i,_ as j,ae as k,de as l,B as m,L as n,le as o,ue as p,ce as q,u as r,ge as s,q as t,O as u,M as v,y as w,K as x,he as y,G as z,b as A,ve as B,xe as C,Ee as D,Y as E,we as F,Te as G,Ne as H,De as I};
|
|
1
|
+
var b="X-Helix-Project-Execution-Token",R="X-Tray-Token",O={mode:"dev",deploymentId:null},k={...O},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 $=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=>!$.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"})}};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."}}import{z as g}from"zod";var A="x-helix-destination-url",U="x-helix-authentication-id",J="x-helix-deployment-id",y="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",y]);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(y,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 _}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=_.object({url:_.string(),method:_.string(),expiresAt:_.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(y,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,y 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 Pt,B as q,C as F,D as ie,E as Tt,G as kt,H as Ot,I as _t,J as Dt,a as O,b as Ee,d as h,e as ve,f as _,h as Rt,j as D,k as It,o as Ct,r as c,t as ne,u as Re,v as B,w as oe,x as Ie,y as V,z as At}from"./chunk-HCGX7VQE.js";var os="tray-config-bridge",is="tray-dev-token-bridge",Ce=null;function ss(e){Ce=e}function x(){if(!Ce)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return Ce}function as(){Ce=null}import{AsyncLocalStorage as Zt}from"async_hooks";import{trace as Hn,SpanKind as Kn,SpanStatusCode as Ze}from"@opentelemetry/api";import{ExportResultCode as Vn,W3CTraceContextPropagator as qn}from"@opentelemetry/core";import{NodeTracerProvider as zn,SimpleSpanProcessor as Yn,BatchSpanProcessor as Jn}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Tn}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as kn}from"@opentelemetry/exporter-logs-otlp-proto";function Xe(e){return D(e).hosts.ingest}function On(){return _()??""}function Ft(){return{[O]:On()}}function Lt(){let e=Xe(x().region);return new Tn({url:`${e}/v1/traces`,headers:()=>Promise.resolve(Ft())})}function Ut(){let e=Xe(x().region);return new kn({url:`${e}/v1/logs`,headers:()=>Promise.resolve(Ft())})}import{logs as jt,SeverityNumber as Ae}from"@opentelemetry/api-logs";import{LoggerProvider as Fn,BatchLogRecordProcessor as Ln}from"@opentelemetry/sdk-logs";function se(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function _n(e){return new TextEncoder().encode(e).length}var Mt="\u2026[truncated]",Dn=_n(Mt),ae=4096;function $(e,t=ae){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Dn);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+Mt}function S(e,t=ae){return $(se(e),t)}var Un="@trayai/helix-sdk",ce,Nt={debug:{number:Ae.DEBUG,text:"DEBUG"},info:{number:Ae.INFO,text:"INFO"},warn:{number:Ae.WARN,text:"WARN"},error:{number:Ae.ERROR,text:"ERROR"}};function Mn(){return h().mode==="lambda"?[new Ln({exporter:Ut()})]:[]}function Bt(){if(ce!==void 0)return;let e=Mn();e.length!==0&&(ce=new Fn({processors:e}),jt.setGlobalLoggerProvider(ce))}function Nn(e,t,r){let n=Nt[e]??Nt.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":S(r)}}:{}}}function $t(e,t,r){jt.getLogger(Un).emit(Nn(e,t,r))}async function Ht(e=2e3){if(ce===void 0)return;let t;try{await Promise.race([ce.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
|
|
2
|
+
`)}finally{t!==void 0&&clearTimeout(t)}}function Qe(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function jn(){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 P(e,t){return jn()?`\x1B[${e}m${t}\x1B[0m`:t}var Bn=5,$n={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},Kt="32",Vt="31",Pe="2",qt="1";function Te(e){return P($n[e]??"0",e.padEnd(Bn))}function zt(e,t){return`${Te("FN")} ${P(qt,`${e} ${t}`.trim())}`}function Yt(e,t,r,n){let o=e.toUpperCase(),s=`${n?`${P(Pe,n)} `:""}${Te(o)} ${t}`;return r&&Object.keys(r).length>0&&(s+=` ${P(Pe,se(r))}`),s}function Jt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Wt(e){return`${Te("AUTH")} ${e}`}function Gt(e,t,r,n,o){let i=r===void 0?"ERR":String(r),s=P(o==="error"?Vt:Kt,i);return`${Te("API")} ${e} ${t} \u2192 ${s} ${P(Pe,`${n}ms`)}`}function Xt(e,t,r){let n=t?Vt:Kt,o=P(n,"\u25CF"),i=P(n,t?"error":"success");return`${o} ${P(qt,e)} ${i} ${P(Pe,`${r}ms`)}`}function z(e){try{process.stdout.write(e+`
|
|
3
|
+
`)}catch{}}var er=new Zt,Wn=new Zt;function v(e){let t=Wn.getStore();t&&(t[e]=!0)}var Gn=/^[0-9a-f]{32}$/;function Xn(e){let t=e.replace(/-/g,"").toLowerCase();return Gn.test(t)?t:null}var Qn={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},Y=new Map;function tr(e,t,r){let n=Y.get(e);n?n[t]=r:Y.set(e,{[t]:r})}function T(e,t,r){e.setAttribute(t,S(r))}var le;function Qt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function Zn(e){return Math.round(e[0]*1e3+e[1]/1e6)}function rr(e){try{process.stdout.write(se(e)+`
|
|
4
|
+
`)}catch{}}var et=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,i=Y.get(o),s={...n.attributes};if(i!==void 0){for(let[u,m]of Object.entries(i))typeof m=="string"?s[u]=$(m):typeof m=="object"&&m!==null?s[u]=S(m):s[u]=m;Y.delete(o)}let a=er.getStore(),l=a?Xn(a):null;rr({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Qt(n.startTime),endTimeUnixNano:Qt(n.endTime),attributes:s,status:{code:Qn[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:$(n.status.message)}:{}}})}r({code:Vn.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},tt=class{onStart(t,r){}onEnd(t){Y.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},rt=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&z(`
|
|
5
|
+
`+zt(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=Y.get(n)?.properties;z(Yt(String(r.level??"info"),String(r.message??""),o,Jt(t.startTime)));break}case"auth":z(Wt(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;z(Gt(String(r.method??""),String(r.host??""),n,Zn(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},nt=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function eo(){let t=[Qe()?new rt:new Yn(new et)];return h().mode==="lambda"&&t.push(new nt(new Jn(Lt()))),t.push(new tt),t}function to(){le===void 0&&(le=new zn({spanProcessors:eo()}),le.register({propagator:new qn}),Bt())}async function ro(e=2e3){let t=[Ht(e)];le!==void 0&&t.push((async()=>{let r;try{await Promise.race([le.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
|
|
6
|
+
`)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var A=Hn.getTracer("@trayai/helix-sdk");function no({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:i,errored:s,errorMessage:a,userId:l,flags:u}){let m=new Date().toISOString(),d=Date.now()-i;if(Qe()){z(`
|
|
7
|
+
`+Xt(n,s,d));return}rr({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:m,durationMs:d,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasAi:u.hasAi,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?$(a):null})}async function Ls(e,t){let r=e.startMs??Date.now();to();let n=!1,o=null;try{return await er.run(e.executionId,()=>A.startActiveSpan("App",{kind:Kn.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async i=>{try{let s=await t(),a=s?.httpResponse?.status??404;return n=a>=400,i.setAttribute("http.response.status_code",a),i.setAttribute("helix.status",n?"error":"success"),i.setStatus({code:n?Ze.ERROR:Ze.OK}),s}catch(s){throw n=!0,o=s instanceof Error?s.message:String(s),i.setAttribute("http.response.status_code",500),i.setAttribute("helix.status","error"),i.setStatus({code:Ze.ERROR,message:o}),s}finally{i.end()}}))}finally{no({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:r,errored:n,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1}}),await ro()}}var ir=1024,L=100*1024*1024,nr=250,oo=3600,io=oo*1e3,or=new TextEncoder,so=/(^|\/)\.\.(\/|$)/,ao=/[?#]/;function co(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function H(e,t=ir){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");ke(e,t)}function ot(e){return e.endsWith("/")?e.slice(0,-1):e}function ke(e,t=ir){if(e.length===0)return;if(so.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(ao.test(e)||co(e))throw c.filesPathInvalid("Path contains illegal characters");let r=e.split("/");if(e.startsWith("/")||e.endsWith("/")||r.some(o=>o===""))throw c.filesPathInvalid("Path must not contain empty path segments");for(let o of r){let i=or.encode(o).length;if(i>nr)throw c.filesPathInvalid(`Path segment exceeds ${nr} UTF-8 bytes (got ${i})`)}let n=or.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function sr(e){if(e>L)throw c.filesValueTooLarge(`File exceeds maximum size of ${L} bytes (got ${e})`,L)}function J(e){let t=e!==void 0?e*1e3:io;return new Date(Date.now()+t)}import{join as de}from"path";var lo="files",uo="files-meta",fo=1023,mo=1,po=5;function ar(e){let t=Math.max(Buffer.byteLength(Oe(e),"utf8"),Buffer.byteLength(ue(e),"utf8"));return Math.max(0,fo-t-mo-po)}function Oe(e){return de(e,".helix",lo)}function ue(e){return de(e,".helix",uo)}function fe(e,t){return de(Oe(e),...t.split("/"))}function _e(e,t){return de(ue(e),...t.split("/"))+".json"}function De(e,t){return t.length===0?Oe(e):fe(e,t)}function cr(e,t){return t.length===0?ue(e):de(ue(e),...t.split("/"))}import{z as go}from"zod";var Ks=["us1","eu1","ap1","ap2"],it=go.string().refine(e=>Rt(e),e=>({message:`Invalid enum value. Expected ${It().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));import{resolve as U}from"path";import{existsSync as Fe,realpathSync as lr}from"fs";import{loadConfig as yo}from"c12";import{z as w}from"zod";var dr=w.string().uuid("projectId must be a valid UUID"),fr=w.string().min(1,"workspaceId must be a non-empty string"),me=["openai","anthropic","google","mistral","cohere","openai-compatible"],ho=["openai","anthropic","google","mistral","cohere"],mr=w.union([w.enum(ho),w.object({service:w.enum(me),baseUrl:w.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)"})]),wo=w.object({name:w.string().min(1,"name is required"),projectId:dr.optional(),workspaceId:fr.optional(),region:it.optional(),env:w.literal("production").optional(),authentications:w.record(w.string()).optional().default({}),config:w.record(w.unknown()).optional().default({}),aiProviders:w.record(mr).optional()}).transform(({env:e,region:t,...r})=>({...r,region:t??"us1"})),ur=w.object({name:w.string().min(1,"name is required"),workspaceId:fr.optional(),region:it,authentications:w.record(w.string()),config:w.record(w.unknown()),aiProviders:w.record(mr).optional()}),Qs=w.discriminatedUnion("kind",[ur.extend({kind:w.literal("provisioned"),projectId:dr}),ur.extend({kind:w.literal("unprovisioned")})]),pr=["helix","tray"],gr=["ts","mts","cts","js","mjs","cjs"],yr="HELIX_CONFIG";function st(e){let t=e?.trim();return t||process.env[yr]?.trim()||void 0}function bo(e,t){let r=st(t?.configFile);if(r!==void 0){let n=U(e,r);return Fe(n)?n:void 0}for(let n of pr)for(let o of gr){let i=U(e,`${n}.config.${o}`);if(Fe(i))return i}}function xo(e){for(let t of pr)if(gr.some(r=>Fe(U(e,`${t}.config.${r}`))))return t;return"helix"}function So(e,t){return U(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function Eo(e,t){let r=st(t?.configFile);return{name:xo(e),cwd:e,...r!==void 0?{configFile:So(e,r)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function vo(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw c.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=wo.safeParse(e);if(!r.success){let u=r.error.issues.map(m=>m.message).join("; ");throw c.configLoadFailed(`Invalid helix.config.ts at ${t}: ${u}`)}let{projectId:n,workspaceId:o,...i}=r.data,s=o!==void 0?{workspaceId:o}:{},a=Ct(),l=a!==void 0?{...i,region:a}:i;return n!==void 0?{kind:"provisioned",projectId:n,...l,...s}:{kind:"unprovisioned",...l,...s}}async function Zs(e,t){let r=e??process.cwd(),n=st(t?.configFile),o=n!==void 0?U(r,n):void 0;if(o!==void 0&&!Fe(o)){let a=t?.configFile?.trim()?"":` (from ${yr})`;throw c.configLoadFailed(`Config file not found: ${o}${a}`)}let i;try{i=await yo(Eo(r,t))}catch(a){throw c.configLoadFailed(`Failed to load helix.config.ts: ${a instanceof Error?a.message:String(a)}`)}let s=i._configFile??bo(r,t);if(!s)throw c.configLoadFailed(`helix.config.ts not found at ${U(r,"helix.config.ts")}`);if(o!==void 0&&i._configFile!==void 0){let a=lr(o);if(lr(U(i._configFile))!==a)throw c.configLoadFailed(`Config file conflict: requested ${o} but ${U(i._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return vo(i.config,s)}var Ro="WORKSPACE_ID_REQUIRED";function ea(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:Ro});return e.workspaceId}var hr="helix-schedule",M=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function ra(e){if(typeof e!="object"||e===null)throw new M("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new M("`cron` must be a non-empty string");let i=t.trim().split(/\s+/).length;if(i!==5)throw new M(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${i} field(s) in "${t}"`);if(typeof r!="string"||!Io(r))throw new M(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new M("`concurrent` must be a boolean");if(typeof o!="function")throw new M("`handler` must be a function");return Object.freeze({kind:hr,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function na(e){return typeof e=="object"&&e!==null&&e.kind===hr&&typeof e.handler=="function"}function Io(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 Co}from"@opentelemetry/api";function Le(e,t,r){let n=A.startSpan("log",{kind:Co.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&tr(n.spanContext().spanId,"properties",r),n.end(),$t(e,t,r)}function wr(){return{info:(e,t)=>Le("info",e,t),warn:(e,t)=>Le("warn",e,t),error:(e,t)=>Le("error",e,t),debug:(e,t)=>Le("debug",e,t)}}function ua(){try{return x().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import Ao from"ky";import{context as ct,trace as Po,SpanKind as ge,SpanStatusCode as xr}from"@opentelemetry/api";function at(e){let t=e.code===V?"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 c.brokerError(e.status,t,S(e.body),e.code)}async function Ue(e,t={}){let r=h(),{region:n}=x(),{headers:o,deploymentId:i}=F(r);i&&(o[B]=i);let s=q(n,r.mode==="lambda"?"runtime":"dev"),a;try{a=await kt({proxyUrl:s,credentialHeaders:o,request:e,timeoutMs:t.timeout,executionId:r.executionId})}catch(l){let u=l instanceof Error?l.message??String(l):String(l);throw c.brokerError(0,u)}return a.kind==="brokerError"&&at(a),a.response}async function br(e){Ot(e.url);let t=h(),{region:r}=x(),n={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},{headers:o,deploymentId:i}=F(t);i&&(n.deploymentId=i);let s=_t(r,t.mode==="lambda"?"runtime":"dev"),a;try{a=await Dt({signUrl:s,credentialHeaders:o,body:n,timeoutMs:e.timeout,executionId:t.executionId})}catch(l){let u=l instanceof Error?l.message??String(l):String(l);throw c.brokerError(0,u)}if(a.kind==="brokerError"){let l=a.code===V?"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 c.brokerError(a.status,l,S(a.body),a.code)}return a.result}var To=new Set([ne,Re,B,oe,"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 ko(e){let t=e.toLowerCase();return To.has(t)||t.startsWith("x-tray-internal-")}async function Oo(e,t){let r=e instanceof Request?e:new Request(e,t),n=new URL(r.url);if(n.protocol!=="https:")throw c.unsupportedScheme(n.protocol.replace(/:$/,""));let o=h(),{region:i}=x(),{headers:s,deploymentId:a}=F(o),l=q(i,o.mode==="lambda"?"runtime":"dev"),u=new Headers;for(let[p,b]of r.headers.entries())ko(p)||u.append(p,b);u.set(ne,r.url);for(let[p,b]of Object.entries(s))u.set(p,b);a&&u.set(B,a),o.executionId&&u.set(oe,o.executionId);let m={method:r.method,headers:u,redirect:"manual",signal:r.signal};r.body&&(m.body=r.body,m.duplex="half");let d;try{d=await fetch(l,m)}catch(p){throw p instanceof Error&&p.name==="AbortError"?p:c.brokerError(0,p instanceof Error?p.message:String(p))}let g=d.headers.get(Ie);return g!==null&&at(await Tt(d,g)),d}var _o=["get","post","put","patch","delete","head","options"],Er="[stream body omitted]";function vr(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?Er: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 lt(e){try{return new URL(e).hostname}catch{return e}}function Sr(e,t,r,n,o){let i=lt(t),s="externalApi",a={kind:ge.CLIENT};return A.startActiveSpan(s,a,async l=>(l.setAttributes({method:e,host:i,"peer.service":n}),T(l,"request",{url:t,method:e,...r!==void 0?{body:vr(r)}:{}}),o(l)))}function pe(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:xr.OK}:{code:xr.ERROR,message:r}),e.end()}var Do=16;async function Fo(e,t){let r=e.clone().body;return r?Rr(r,t):new Uint8Array(0)}async function Rr(e,t){let r=e.getReader(),n=[],o=0,i=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(i+=1,i>=Do)break;continue}i=0;let m=t+1-o;if(u.byteLength>=m){n.push(u.slice(0,m)),o+=m;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let s=new Uint8Array(o),a=0;for(let l of n)s.set(l,a),a+=l.byteLength;return s}async function Ir(e,t,r){if("kyResponse"in r)try{let n=await Fo(r.kyResponse,ae),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}T(e,"response",i)}catch{T(e,"response",{status:t})}else T(e,"response",vr(r.bodyValue))}async function Lo(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),i=new Request(e,{body:n,duplex:"half"}),s=await Rr(o,ae);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:Er}}}return typeof t=="string"?{body:t}:{}}function Ma(){let e=Ao.create({fetch:Oo,retry:{shouldRetry:({error:n})=>n instanceof c?!1:void 0}});function t(n){return(o,i)=>{let s=ct.active(),a,l=!1,u=(d,g)=>{a&&!l&&(l=!0,pe(a,d,g))},m=e.extend({hooks:{beforeRequest:[async(d,g)=>{let p=await Lo(d,g.body),b=p.body;if(a||(a=A.startSpan("externalApi",{kind:ge.CLIENT},s)),a.setAttributes({method:d.method.toUpperCase(),host:lt(d.url)}),T(a,"request",{url:d.url,method:d.method.toUpperCase(),...b!==void 0?{body:b}:{}}),l=!1,v("hasExternal"),p.request)return p.request}],beforeRetry:[d=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(d,g,p)=>{a&&(a.setAttribute("statusCode",p.status),await Ir(a,p.status,{kyResponse:p}),p.ok?u("success"):i?.throwHttpErrors===!1&&(v("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[d=>(v("hasError"),u("error",d.message),d)]}});return a=A.startSpan("externalApi",{kind:ge.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:lt(String(o))}),ct.with(Po.setSpan(ct.active(),a),()=>{let d=n==="options"?m(o,{...i,method:"OPTIONS"}):m[n](o,i);return d.catch(g=>{v("hasError"),u("error",g instanceof Error?g.message:String(g))}),d})}}let r=Object.fromEntries(_o.map(n=>[n,t(n)]));return{...e,...r,authed(n){return Uo(n)}}}function Uo(e){let r=x().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(a,l={})=>{let u=s.toUpperCase();return Sr(u,a,l.body,e,async m=>{v("hasAuth");let d=A.startSpan("auth",{kind:ge.INTERNAL});d.setAttribute("alias",e),d.setAttribute("id",n),d.end();try{let g=ie({authenticationId:n,method:u,url:a,body:l.body,headers:l.headers,query:l.query}),p=await Ue(g,{timeout:l.timeout});return m.setAttribute("statusCode",p.status),await Ir(m,p.status,{bodyValue:p.body}),pe(m,"success"),p}catch(g){throw v("hasError"),g instanceof c&&g.detail.kind==="broker_error"&&g.detail.status>0&&m.setAttribute("statusCode",g.detail.status),pe(m,"error",g instanceof Error?g.message:String(g)),g}})}}function i(s,a={}){let l=a.method??"GET";return Sr(l,s,void 0,e,async u=>{v("hasAuth");let m=A.startSpan("auth",{kind:ge.INTERNAL});m.setAttribute("alias",e),m.setAttribute("id",n),m.end();try{let d=await br({authenticationId:n,url:s,method:l,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return u.setAttribute("statusCode",200),pe(u,"success"),d}catch(d){throw v("hasError"),d instanceof c&&d.detail.kind==="broker_error"&&d.detail.status>0&&u.setAttribute("statusCode",d.detail.status),pe(u,"error",d instanceof Error?d.message:String(d)),d}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:i}}import{SpanKind as qo,SpanStatusCode as Tr}from"@opentelemetry/api";function ye(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Mo=18e4,Cr=Mo-1e4,No=2e3;async function Ar(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<Cr;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(No,200*2**i),u=l/2+Math.random()*(l/2),m=Cr-(Date.now()-o);await new Promise(d=>setTimeout(d,Math.min(u,m))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var jo=new Set(["SELECT","WITH","SHOW"]),Bo=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function $o(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function Ho(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let i=typeof t=="string"?$(t):S(t);return c.dbCallFailed(i)}function Ko(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Vo(e,t){return typeof t!="number"||t<0?{}:jo.has(e)?{rowsRead:t}:Bo.has(e)?{rowsWritten:t}:{}}function Pr(e){async function t(r,n,o){let i=ie({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:s,body:a}=await Ue(i);if(s>=400)throw Ho(s,a);return Ko(a)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.dbCallFailed(a,s instanceof Error?s:void 0)}}return{system:"redshift",validate:$o,async execute(r,n){let o=ye(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=S(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Ar(t,r.region,l),m=u.Status;if(m==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(m==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let d=Vo(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:d}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:d}}}}var ut=64*1024;function zo(e){return e.length>ut?`${e.slice(0,ut)}...[truncated]`:e}function Yo(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Jo(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>ut?T(e,"result",{truncated:!0,size:n.length}):T(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Wo(e,t,r){let n=ye(r),o=zo(r);return A.startActiveSpan("database",{kind:qo.CLIENT},async i=>{Yo(i,e,t,n,o);try{v("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Jo(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:Tr.OK}),l}catch(s){v("hasError");let a=s instanceof Error?s.message:String(s);throw i.setAttribute("status","error"),i.setStatus({code:Tr.ERROR,message:a}),s}finally{i.end()}})}function Go(e){let r=x().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Pr(n);function i(s,a){return o.validate(s),Wo(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as ti}from"unstorage";var kr=1024,dt=250*1024,Xo=new TextEncoder,Qo=/(^|\/)\.\.(\/|$)/,Zo=/[?#]/,ei=/[\u0000-\u001F\u007F]/;function Or(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(Qo.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(Zo.test(e)||ei.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=Xo.encode(e).length;if(t<1||t>kr)throw c.kvKeyInvalid(`Key must be between 1 and ${kr} UTF-8 bytes (got ${t})`)}function _r(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Dr(e){let t;try{t=JSON.stringify(e)}catch{throw c.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw c.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>dt)throw c.kvValueTooLarge(`Value exceeds maximum size of ${dt} bytes (got ${r})`,dt)}function he(e){Or(e)}function Me(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Fr(e){let t=Me(e,"getItem"),r=Me(e,"setItem"),n=Me(e,"removeItem"),o=Me(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return he(s),t(s,a)},setItem(s,a,l){return he(s),r(s,a,l)},removeItem(s,a){return he(s),n(s,a)},hasItem(s,a){return he(s),o(s,a)},getKeys(s,a){return s.length>0&&he(s),i(s,a)}}}function Ne(e){return ti({driver:Fr(e)})}import{defineDriver as ri}from"unstorage";function ni(e){try{return JSON.parse(e)}catch{return e}}var oi=ri(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n,o){let i=o?.ttl,s=ni(n);i!==void 0?await t.set(r,s,{ttl:i}):await t.set(r,s)},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function Lr(e){return oi({client:e})}import ai from"ky";import{z as R}from"zod";async function N(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function Ur(e){return D(e).hosts.api}function ii(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function si(e){return e.split("/").map(encodeURIComponent).join("/")}function we(e,t,r){return`${e}${ii(t)}/${si(r)}`}var ci=6e4,ft=R.lazy(()=>R.union([R.string(),R.number(),R.boolean(),R.null(),R.array(ft),R.record(ft)])),li=R.object({projectId:R.string(),key:R.string(),value:ft,type:R.enum(["string","number","boolean","null","array","object"]),organizationId:R.string(),scope:R.string(),createdBy:R.string(),createdAt:R.number(),updatedBy:R.string(),updatedAt:R.number()});function ui(){let e=ve(),t=_(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[Ee]=e),n&&(o[O]=t),o}function di(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 je(e,t){throw c.kvCallFailed(e,di(t),S(t))}async function Be(e,t,r={}){try{let n=await ai(t,{method:e,headers:ui(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ci}),o=e==="head"?void 0:await N(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw c.kvCallFailed(0,o)}}function Mr(e){let t=Ur(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await Be("get",we(t,r,n));if(o===404)return null;(o<200||o>=300)&&je(o,i);let s=li.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",S(i));return s.data.value},async set(n,o,i){let{status:s,body:a}=await Be("put",we(t,r,n),{json:i?.ttl!==void 0?{value:o,ttl:i.ttl}:{value:o}});(s<200||s>=300)&&je(s,a)},async delete(n){let{status:o,body:i}=await Be("delete",we(t,r,n));o!==204&&je(o,i)},async has(n){let{status:o,body:i}=await Be("head",we(t,r,n));if(o===200)return!0;if(o===404)return!1;je(o,i)}}}function $e(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,r,n)=>{let o=n?.ttl;Dr(r),typeof o=="number"&&_r(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function fi(){let e=x();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function Nr(e){let t=fi(),r=e??Mr(t),n=Ne(Lr(r));return $e(n)}import{defineDriver as mi}from"unstorage";var pi=mi(e=>{let t=new Map;function r(n){let o=t.get(n);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(n);return}return o}return{name:"memory-ttl",getItem(n){return r(n)?.value??null},setItem(n,o,i){let s=i?.ttl,a=r(n),l=typeof s=="number"?Date.now()+s*1e3:s===null?void 0:a?.expiresAt;t.set(n,{value:o,expiresAt:l})},removeItem(n){t.delete(n)},hasItem(n){return r(n)!==void 0},getKeys(){return[...t.keys()].filter(n=>r(n)!==void 0)},clear(){t.clear()}}});function jr(){return pi({})}var mt;function gi(){return mt||(mt=Ne(jr())),mt}function Br(){return $e(gi())}function yi(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":h().mode==="lambda"}function Hc(){return yi()?Nr():Br()}import{createHash as bi}from"crypto";import{mkdir as xi,readFile as qr,readdir as zr,rm as Hr,unlink as Si,writeFile as Kr}from"fs/promises";import{dirname as Ei}from"path";async function hi(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:i}=await t.read();if(o)break;if(i){if(n+=i.byteLength,n>L)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${L} bytes (got more than ${L})`,L);r.push(i)}}return Buffer.concat(r)}async function W(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?hi(e):Buffer.from(e)}var wi={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"},$r="application/octet-stream";function He(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return $r;let r=e.slice(t+1).toLowerCase();return wi[r]??$r}function X(){let e=h().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function G(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function Ke(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function pt(e){try{let t=await qr(_e(X(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Vr(e){await xi(Ei(e),{recursive:!0})}async function vi(e,t){let r=De(e,t),n;try{n=await zr(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return n.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function Yr(e,t){let r=De(e,t),n;try{n=await zr(r,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let o=[];for(let i of n){let s=t.length===0?i.name:`${t}/${i.name}`;i.isDirectory()?o.push(...await Yr(e,s)):i.isFile()&&o.push(s)}return o}function Jr(){return{async put(e,t,r){return G(async()=>{let n=X(),o=await W(t),i=r?.contentType??He(e),s=bi("sha1").update(o).digest("hex"),a=new Date,l=fe(n,e);await Vr(l),await Kr(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},m=_e(n,e);return await Vr(m),await Kr(m,JSON.stringify(u)),Ke(e,u)})},async get(e){return G(async()=>{let t=await pt(e);return t?{data:await qr(fe(X(),e)),metadata:Ke(e,t)}:null})},async head(e){return G(async()=>{let t=await pt(e);return t?Ke(e,t):null})},async delete(e){return G(async()=>{let t=X();await Promise.all([fe(t,e),_e(t,e)].map(async r=>{try{await Si(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return G(async()=>{let t=X(),r=await Yr(t,e);return await Promise.all([Hr(De(t,e),{recursive:!0,force:!0}),Hr(cr(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return G(async()=>{let r=X(),n=t?.limit??100,i=(await vi(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await pt(a);return l?Ke(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=h().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:J(t?.expiresIn)}},async getDownloadUrl(e,t){let r=h().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:J(t?.expiresIn)}}}}import{createHash as ki}from"crypto";function Ve(e){return D(e).hosts.api}function Ri(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function be(e,t){return`${e}${Ri(t)}`}function Q(e,t,r){return`${be(e,t)}/${encodeURIComponent(r)}`}function qe(e,t,r){return`${Q(e,t,r)}/upload`}function Wr(e,t,r){return`${Q(e,t,r)}/download`}function Gr(e,t,r){return`${Q(e,t,r)}/signed-url`}function Xr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${be(e,t)}/file?${o.toString()}`}function Qr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${be(e,t)}?${o.toString()}`}import yt from"ky";import{z as E}from"zod";var ht=6e4,Zr=E.object({id:E.string(),workspaceId:E.string(),projectId:E.string(),parentFolder:E.string().nullable().optional(),name:E.string(),size:E.number().nullable().optional(),objectType:E.enum(["Folder","File"]),contentType:E.string().nullable().optional(),createdAt:E.string(),updatedAt:E.string()}),Ii=E.object({signedURL:E.string()}),Ci=E.object({path:E.array(E.object({id:E.string(),name:E.string()})),elements:E.array(Zr)});function wt(){let e=ve(),t=_(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[Ee]=e),n&&(o[O]=t),o}function en(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 j(e,t){throw c.filesCallFailed(e,en(t),S(t))}function Ai(e,t){return e===400&&en(t).toLowerCase()==="resource not found"}async function Pi(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function Z(e,t,r={}){try{let n=await yt(t,{method:e,headers:wt(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ht}),o=await N(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function gt(e,t){let r=Zr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",S(t));return r.data}function tn(e){let t=Ve(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await Z("post",be(t,r),{json:n});return(o<200||o>=300)&&j(o,i),gt(o,i)},async getByName(n,o){let{status:i,body:s}=await Z("get",Xr(t,r,n,o));return i===404||Ai(i,s)?null:((i<200||i>=300)&&j(i,s),gt(i,s))},async getById(n){let{status:o,body:i}=await Z("get",Q(t,r,n));return o===404?null:((o<200||o>=300)&&j(o,i),gt(o,i))},async listChildren(n,o){let{status:i,body:s}=await Z("get",Qr(t,r,n,o));(i<200||i>=300)&&j(i,s);let a=Ci.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",S(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await Pi(a),m;try{m=await yt(qe(t,r,n),{method:"post",headers:{...wt(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:ht})}catch(g){if(g instanceof c)throw g;let p=g instanceof Error?g.message:String(g);throw c.filesCallFailed(0,p)}let d=await N(m);(m.status<200||m.status>=300)&&j(m.status,d)},async downloadContent(n){let o;try{o=await yt(Wr(t,r,n),{method:"get",headers:wt(),throwHttpErrors:!1,timeout:ht})}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message:String(s);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let s=await N(o);j(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await Z("get",Gr(t,r,n));(o<200||o>=300)&&j(o,i);let s=Ii.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",S(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await Z("delete",Q(t,r,n));o===204||o===404||(o<200||o>=300)&&j(o,i)}}}function bt(e){return e.split("/").filter(t=>t.length>0)}function xt(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Ti(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(xt(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function St(e,t){let r=bt(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await Ti(e,o,i)).id;return{parentFolder:o,name:n}}async function xe(e,t){let r=bt(t),n=r[r.length-1],o;for(let i of r.slice(0,-1)){let s=await e.getByName(o,i);if(!s||s.objectType!=="Folder")return null;o=s.id}return{parentFolder:o,name:n}}async function Et(e,t){if(t.length===0)return;let r=bt(t),n;for(let o of r){let i=await e.getByName(n,o);if(!i||i.objectType!=="Folder")return null;n=i.id}return n}var Oi=500,_i=8;async function Di(e,t,r){let n=new Array(e.length),o=0;async function i(){for(;o<e.length;){let s=o++;n[s]=await r(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}function Fi(){let e=x();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function Li(e){return ki("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function ze(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Li(t)}}async function rn(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(xt(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function nn(e,t){let{elements:r}=await e.listChildren(t,Oi);return(await Di(r,_i,async o=>{let i=o.objectType==="Folder"?await nn(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function on(e){let t=Fi(),r=e??tn(t),n=Ve(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await St(r,i),m=await W(s),d=a?.contentType??He(i),g=await r.getByName(l,u);if(g&&g.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${i}"`);let p=g??await rn(r,l,u,d);await r.uploadContent(p.id,m,u,d);let b=await r.getById(p.id);return ze(i,b??p,d)},async get(i){let s=await xe(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:ze(i,a)}},async head(i){let s=await xe(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:ze(i,a)},async delete(i){let s=await xe(r,i);if(!s)return;let a=await r.getByName(s.parentFolder,s.name);a&&await r.deleteById(a.id)},async deleteMany(i){let s=await Et(r,i);if(s===null)return{deleted:0};let a=await nn(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await Et(r,i??"");if(a===null)return{files:[],cursor:null};let l=s?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(d=>d.objectType==="File").map(d=>ze(i?`${i}/${d.name}`:d.name,d)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await St(r,i),m=await r.getByName(a,l)??await rn(r,a,l,s?.contentType);return{url:qe(n,o,m.id),expiresAt:J(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await xe(r,i),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${i}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:J(s?.expiresIn)}}}}function vt(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){H(n,r);let s=await W(o);return sr(s.byteLength),e.put(n,s,i)},async get(n){return H(n,r),e.get(n)},async head(n){return H(n,r),e.head(n)},async delete(n){return H(n,r),e.delete(n)},async deleteMany(n){let o=ot(n);return ke(o,r),e.deleteMany(o)},async list(n,o){let i=ot(n??"");return ke(i,r),e.list(i,o)},async getUploadUrl(n,o){return H(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return H(n,r),e.getDownloadUrl(n,o)}}}function Ui(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":h().mode==="lambda"}function Fl(){if(Ui())return vt(on());let e=h().projectRoot;return vt(Jr(),{maxPathBytes:e?ar(e):void 0})}import Ni from"ky";function sn(e){return D(e).hosts.api}function Mi(){return"/private/v1/helix/function-calls"}function an(e){return`${e}${Mi()}`}var ji=5e3;function Bi(){let e=_();if(!!!(e&&e.trim().length>0))throw c.callFunctionMissingExecutionJwt();return{Accept:"application/json",[O]:e}}function $i(e,t){throw c.callFunctionCallFailed(e,Hi(t),S(t))}function Hi(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 cn(e){let t=sn(e.env);return{async callAsync(r,n){let o,i;try{let s=await Ni(an(t),{method:"post",headers:Bi(),json:{functionPath:r,input:n},throwHttpErrors:!1,timeout:ji});o=s.status,i=await N(s)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.callFunctionCallFailed(0,a)}(o<200||o>=300)&&$i(o,i)}}}var ln=1024;function Ye(e){if(typeof e!="string"||e.trim().length===0)throw c.callFunctionPathInvalid("functionPath must be a non-empty string");if(e.length>ln)throw c.callFunctionPathInvalid(`functionPath must be at most ${ln} characters`)}function Ki(){let e=x();if(e.kind!=="provisioned")throw c.callFunctionRequiresProvisioning();return{env:e.region}}function un(e){return async function(r,n){Ye(r),await(e??cn(Ki())).callAsync(r,n)}}function dn(){return async function(t,r){Ye(t);let n=h().devServerUrl;if(!n)throw c.callFunctionNotAvailable();let o=t.startsWith("/")?t:`/${t}`,i=wr();fetch(`${n}${o}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r??{})}).then(s=>{s.ok||i.warn("ctx.callFunctionAsync: dev-mode dispatch returned a non-2xx response",{functionPath:t,status:s.status})}).catch(s=>{i.warn("ctx.callFunctionAsync: dev-mode dispatch failed",{functionPath:t,error:s instanceof Error?s.message:String(s)})})}}function Vi(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":h().mode==="lambda"}function su(){return Vi()?un():dn()}import{embed as hn,embedMany as wn,generateImage as bn,generateObject as xn,generateSpeech as Sn,generateText as En,streamObject as vn,streamText as Rn,transcribe as In}from"ai";import{SpanKind as ts,SpanStatusCode as yn}from"@opentelemetry/api";import{createOpenAI as Ji}from"@ai-sdk/openai";import{createAnthropic as Wi}from"@ai-sdk/anthropic";import{createGoogle as Gi}from"@ai-sdk/google";import{createMistral as Xi}from"@ai-sdk/mistral";import{createCohere as Qi}from"@ai-sdk/cohere";import{createOpenAICompatible as Zi}from"@ai-sdk/openai-compatible";var qi=new Set(["x-api-key","x-goog-api-key"]);function zi(e){return At(e)||qi.has(e.toLowerCase())}function Yi(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function fn(e){return async(t,r)=>{let n=Yi(t),o=new URL(n);if(o.protocol!=="https:")throw c.unsupportedScheme(o.protocol.replace(/:$/,""));let i=h(),{region:s}=x(),a=new Headers(r?.headers??(t instanceof Request?t.headers:void 0)),l=new Headers;for(let[f,y]of a.entries())zi(f)||l.append(f,y);l.set(ne,n),l.set(Re,e),i.executionId&&l.set(oe,i.executionId);let{headers:u,deploymentId:m}=F(i);for(let[f,y]of Object.entries(u))l.set(f,y);m&&l.set(B,m);let d=q(s,i.mode==="lambda"?"runtime":"dev"),g=r?.body??(t instanceof Request?t.clone().body:void 0),p={method:r?.method??(t instanceof Request?t.method:"GET"),headers:l,redirect:"manual",signal:r?.signal??void 0};g!=null&&(p.body=g,typeof ReadableStream<"u"&&g instanceof ReadableStream&&(p.duplex="half"));let b;try{b=await fetch(d,p)}catch(f){if(f instanceof Error&&f.name==="AbortError")throw f;let y=f instanceof Error?f.message??String(f):String(f);throw c.brokerError(0,y)}let re=b.headers.get(Ie);if(re!==null){let f=await b.text(),y=f||re;try{let I=Pt.safeParse(JSON.parse(f));I.success&&(y=I.data.error.message)}catch{}throw re===V&&(y="credential broker does not support the raw proxy endpoint required by ctx.ai \u2014 deploy a newer broker or pin an older SDK"),c.brokerError(b.status,y,f||void 0,re)}return b}}var ee="helix-broker";function mn(e){let{alias:t,service:r,baseUrl:n,authenticationId:o}=e,i=fn(o);switch(r){case"openai":return Ji({apiKey:ee,fetch:i});case"anthropic":return Wi({apiKey:ee,fetch:i});case"google":return Gi({apiKey:ee,fetch:i});case"mistral":return Xi({apiKey:ee,fetch:i});case"cohere":return Qi({apiKey:ee,fetch:i});case"openai-compatible":{if(!n)throw c.aiUnsupportedService(t,r,[...me]);return Zi({name:t,baseURL:n,apiKey:ee,fetch:i})}}}var pn={"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}},es=Object.keys(pn).sort((e,t)=>t.length-e.length);function gn(e,t){let r=es.find(i=>e.startsWith(i));if(!r||!t)return{amount:0,currency:"USD"};let n=pn[r],o=((t.inputTokens??0)*n.input+(t.outputTokens??0)*n.output)/1e6;return{amount:Number(o.toFixed(8)),currency:"USD"}}function C(e,t,r){return A.startActiveSpan("ai",{kind:ts.CLIENT},async n=>{n.setAttributes({operation:e.operation,model:e.model,...e.alias!==void 0?{alias:e.alias}:{}}),v("hasAi");try{let o=await t(),i=r?.(o);return i&&n.setAttributes({...i.inputTokens!==void 0?{inputTokens:i.inputTokens}:{},...i.outputTokens!==void 0?{outputTokens:i.outputTokens}:{}}),n.setAttribute("status","success"),n.setStatus({code:yn.OK}),o}catch(o){let i=o instanceof Error?o.message:String(o);throw n.setAttribute("status","error"),n.setStatus({code:yn.ERROR,message:i}),o}finally{n.end()}})}function rs(){return`aireq_${crypto.randomUUID().replaceAll("-","")}`}function te(e,t){return{cost:gn(e,t),requestId:rs()}}function K(e){return typeof e=="object"&&e!==null&&"modelId"in e?String(e.modelId):String(e)}var Cn=new WeakSet;function Se(e){return Cn.add(e),e}function k(e){if(typeof e!="object"||e===null)throw c.aiModelInstanceRequired(typeof e=="string"?e:String(e));if(!Cn.has(e))throw c.aiForeignModelRejected()}function Je(e){return e.totalUsage??e.usage}function We(e){return e.usage?.tokens!==void 0?{inputTokens:e.usage.tokens}:void 0}function Ge(e){return e.usage}function ns(e){let t=x(),r=t.authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=(t.aiProviders??{})[e];if(o===void 0)throw c.aiProviderNotConfigured(e,[...me]);let{service:i,baseUrl:s}=typeof o=="string"?{service:o,baseUrl:void 0}:o,a=mn({alias:e,service:i,baseUrl:s,authenticationId:n}),l=f=>Se(a.languageModel(f)),u=f=>Se(a.embeddingModel(f)),m=f=>Se(a.imageModel(f)),d=f=>{if(!a.transcriptionModel)throw new Error(`AI provider "${i}" (alias "${e}") has no transcription models`);return Se(a.transcriptionModel(f))},g=f=>{if(!a.speechModel)throw new Error(`AI provider "${i}" (alias "${e}") has no speech models`);return Se(a.speechModel(f))},p=(f=>l(f)),b=(f,y)=>{let I=f.model;if(typeof I!="string")throw c.aiModelIdRequired(e,y);return I};return Object.assign(p,{specificationVersion:"v4",languageModel:l,embeddingModel:u,textEmbeddingModel:u,imageModel:m,transcriptionModel:d,speechModel:g,async generateText(f){let y=b(f,"generateText"),I=await C({operation:"generateText",model:y,alias:e},()=>En({...f,model:l(y)}),Je);return Object.assign(I,{helix:te(y,Je(I))})},streamText(f){let y=b(f,"streamText");return v("hasAi"),Rn({...f,model:l(y)})},async generateObject(f){let y=b(f,"generateObject"),I=await C({operation:"generateObject",model:y,alias:e},()=>xn({...f,model:l(y)}),Pn=>Pn.usage),An=I.usage;return Object.assign(I,{helix:te(y,An)})},streamObject(f){let y=b(f,"streamObject");return v("hasAi"),vn({...f,model:l(y)})},async embed(f){let y=b(f,"embed");return C({operation:"embed",model:y,alias:e},()=>hn({...f,model:u(y)}),We)},async embedMany(f){let y=b(f,"embedMany");return C({operation:"embedMany",model:y,alias:e},()=>wn({...f,model:u(y)}),We)},async generateImage(f){let y=b(f,"generateImage"),I=await C({operation:"generateImage",model:y,alias:e},()=>bn({...f,model:m(y)}),Ge);return Object.assign(I,{helix:te(y,Ge(I))})},async transcribe(f){let y=b(f,"transcribe");return C({operation:"transcribe",model:y,alias:e},()=>In({...f,model:d(y)}))},async generateSpeech(f){let y=b(f,"generateSpeech");return C({operation:"generateSpeech",model:y,alias:e},()=>Sn({...f,model:g(y)}))}})}function _u(){let e=new Map;return Object.assign((n=>{let o=e.get(n);return o||(o=ns(n),e.set(n,o)),o}),{async generateText(n){k(n.model);let o=K(n.model),i=await C({operation:"generateText",model:o},()=>En(n),Je);return Object.assign(i,{helix:te(o,Je(i))})},streamText(n){return k(n.model),v("hasAi"),Rn(n)},async generateObject(n){k(n.model);let o=K(n.model),i=await C({operation:"generateObject",model:o},()=>xn(n),a=>a.usage),s=i.usage;return Object.assign(i,{helix:te(o,s)})},streamObject(n){return k(n.model),v("hasAi"),vn(n)},async embed(n){return k(n.model),C({operation:"embed",model:K(n.model)},()=>hn(n),We)},async embedMany(n){return k(n.model),C({operation:"embedMany",model:K(n.model)},()=>wn(n),We)},async generateImage(n){k(n.model);let o=K(n.model),i=await C({operation:"generateImage",model:o},()=>bn(n),Ge);return Object.assign(i,{helix:te(o,Ge(i))})},async transcribe(n){return k(n.model),C({operation:"transcribe",model:K(n.model)},()=>In(n))},async generateSpeech(n){return k(n.model),C({operation:"generateSpeech",model:K(n.model)},()=>Sn(n))}})}export{os as a,is as b,ss as c,x as d,as as e,er as f,Wn as g,v as h,T as i,to as j,ro as k,A as l,no as m,Ls as n,wr as o,ua as p,Ma as q,Go as r,Hc as s,H as t,fe as u,_e as v,Fl as w,su as x,Ks as y,it as z,dr as A,fr as B,me as C,mr as D,Qs as E,yr as F,st as G,bo as H,Eo as I,vo as J,Zs as K,Ro as L,ea as M,_u as N,hr as O,M as P,ra as Q,na as R};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as ce,B as le,C as fe,D as pe,E as ge,F as me,G as _,H as x,I as V,J as z,K as y,L as he,M as ye,N as B,O as Ce,P as ve,Q as we,R as Se,f as P,g as k,h as A,i as h,j as H,k as F,l as L,m as O,n as ae,o as M,p as D,q,r as Z,s as N,w as $,x as K,y as de,z as ue}from"./chunk-
|
|
1
|
+
import{A as ce,B as le,C as fe,D as pe,E as ge,F as me,G as _,H as x,I as V,J as z,K as y,L as he,M as ye,N as B,O as Ce,P as ve,Q as we,R as Se,f as P,g as k,h as A,i as h,j as H,k as F,l as L,m as O,n as ae,o as M,p as D,q,r as Z,s as N,w as $,x as K,y as de,z as ue}from"./chunk-UKKHDA5X.js";import{a as j,b as ie}from"./chunk-WUCX7RZO.js";import{d as E,r as W,s as U}from"./chunk-HCGX7VQE.js";import{randomUUID as Pe}from"crypto";import{SpanStatusCode as Y,SpanKind as Ae}from"@opentelemetry/api";import{defineEventHandler as He,getMethod as Fe,getRequestURL as Le,getHeaders as te,getHeader as ee}from"h3";import{readBody as Ee,getQuery as ke,getRouterParams as _e}from"h3";async function G(e,t){let r=await xe(e),n=ke(e),o=_e(e)??{},s={...n,...r,...o};return t?be(s,t):s}async function xe(e){try{let t=await Ee(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function be(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var C=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function J(e){return t=>{e.node.res.statusCode=t}}function Q(){return(e,t)=>{throw new C(e,t)}}function X(e,t){let{statusCode:r,message:n}=Te(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Te(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_path_invalid":return{statusCode:400,message:e.message};case"call_function_call_failed":return{statusCode:502,message:"Async function call failed"};case"call_function_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_not_available":return{statusCode:501,message:"callFunctionAsync is not available in this environment"};case"call_function_missing_execution_jwt":return{statusCode:401,message:"Missing execution credentials"};case"ai_unsupported_service":case"ai_model_id_required":case"ai_model_instance_required":case"ai_provider_not_configured":case"ai_foreign_model_rejected":return{statusCode:500,message:e.kind==="ai_unsupported_service"?`AI service not supported for alias "${e.alias}"`:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Ie=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Re(e){return e.toLowerCase().includes("tray_lid")}function b(e){let t={};for(let[r,n]of Object.entries(e))if(!Ie.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let d=s.split("=")[0].trim();return!Re(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Oe(e,t){let{inputSchema:r,outputSchema:n}=qe(t),o=e;return He(async s=>{let d=E(),{executionId:i,userId:a,deploymentId:l}=Ze(d,s),f=d.mode==="lambda"?d.parentExecutionId??null:null,p=Date.now(),v=new Date().toISOString(),c=Fe(s),u=Le(s).pathname,g=D(),m=M(),oe=`${c} ${u}`;H();let R={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1};return je(()=>k.run(R,()=>P.run(i,async()=>{let w=await Me(s,r);if(!w.ok)return{response:w.response,errored:!1,errorMessage:null};let se=$e(s,w.input,g,m,c,u,i,l,a,f);return De(o,se,n,s,m,i,l,{method:c,path:u,rawInput:w.input})})),{executionId:i,deploymentId:l,routeOrJob:oe,startedAt:v,startMs:p,userId:a,flags:R})})}async function je(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{O({...t,errored:r,errorMessage:n}),await F()}}async function Me(e,t){try{return{ok:!0,input:await G(e,t)}}catch(r){let n=Ne(e,r);if(n)return{ok:!1,response:n};throw r}}async function De(e,t,r,n,o,s,d,i){return L.startActiveSpan("function",{root:!0,kind:Ae.SERVER,attributes:{method:i.method,route:i.path,executionId:s,...d?{deploymentId:d}:{}}},async a=>{t.traceId=a.spanContext().traceId;let l=b(te(n));h(a,"input",i.rawInput),h(a,"request",{method:i.method,path:i.path,headers:l,body:i.rawInput});let f=!1,p=null,v,c;try{let u=await j.run(t,()=>e(t));if(v=u,u==null)n.node.res.statusCode=204,c="";else if(u instanceof Response)c=u;else if(r){let g=r.safeParse(u);if(!g.success){let m=Object.keys(g.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:m,executionId:s}),W.outputValidationFailed(m)}c=g.data}else c=u}catch(u){f=!0,p=u instanceof Error?u.message:String(u),A("hasError"),c=We(u,n,o,s)}finally{Ue(a,n,{errored:f,errorMessage:p,handlerResult:v,response:c})}return{response:c,errored:f,errorMessage:p}})}function We(e,t,r,n){if(e instanceof C)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(U(e))return X(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function Ue(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&h(e,"output",r.handlerResult),h(e,"response",r.response);let n=k.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasAi",n?.hasAi??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?Y.ERROR:Y.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function qe(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Ze(e,t){let r=e.mode==="lambda",n=(r?e.executionId:ee(t,"x-tray-execution-id"))??Pe(),o=(r?e.userId:ee(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Ne(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function $e(e,t,r,n,o,s,d,i,a,l){return{input:t,method:o,path:s,headers:b(te(e)),http:q(),db:f=>Z(f),kv:()=>N(),files:()=>$(),callFunctionAsync:K(),ai:B(),log:n,config:r,status:J(e),error:Q(),state:{},request:e,executionId:d,deploymentId:i,userId:a,parentExecutionId:l,identity:a!==null?{user:{id:a}}:null,traceId:""}}function Ke(e){return e}import{existsSync as Ve,watch as ze,writeSync as Be}from"fs";import{basename as Ge,dirname as Je,join as Qe,resolve as S}from"path";import{watchConfig as Xe}from"c12";function Ye(e,t){let r=e instanceof Error?e.message:String(e);Be(2,`[helix-watch] ${t.phase} error: ${r}
|
|
2
2
|
`)}function T(){return{kind:"unprovisioned",name:"",authentications:{},config:{},region:"us1"}}var et=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,re=new Set;function ne(e,t){return x(e,{configFile:t})!==void 0}async function tt(e,t,r){if(ne(e.cwd,t))try{return{current:await y(e.cwd,{configFile:t}),initialLoadSucceeded:!0}}catch(n){return r(n,{phase:"reload"}),{current:T(),initialLoadSucceeded:!1}}if(e.watch){let n=t!==void 0?S(e.cwd,t):S(e.cwd);re.has(n)||(process.stderr.write(t!==void 0?`warning: config file ${S(e.cwd,t)} not found; tray running with default config
|
|
3
3
|
`:`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
|
|
4
4
|
`),re.add(n))}return{current:T(),initialLoadSucceeded:!1}}var I=class{constructor(t,r,n,o){this.cwd=t;this.configFile=r;this.onError=n;this.emit=o}cwd;configFile;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=Xe({...V(this.cwd,{configFile:this.configFile}),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=z(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,s)=>{n.once("ready",o),n.once("error",s)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){let t=this.configFile!==void 0?S(this.cwd,this.configFile):void 0,r=t!==void 0?Je(t):this.cwd;try{this.directoryWatcher=ze(r,{persistent:!1},(n,o)=>{if(this.stopped||!o)return;let s=o.toString();if(t!==void 0){if(s!==Ge(t))return}else if(!et.test(s))return;Ve(Qe(r,s))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let d;try{d=await y(this.cwd,{configFile:this.configFile})}catch(a){this.onError(a,{phase:"reload"});return}if(this.stopped)return;this.emit(d);let i=this.directoryWatcher;i&&(this.directoryWatcher=null,i.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",n=>{this.onError(n,{phase:"attach"})})}catch(n){this.onError(n,{phase:"attach"})}}};async function rt(e){let t=e.onError??Ye,r=new Set,n=_(e.configFile),o=await tt(e,n,t),s=o.current;function d(a){s=a;for(let l of[...r])try{l(a)}catch(f){t(f,{phase:"reload"})}}let i=new I(e.cwd,n,t,d);return e.watch&&i.start(o.initialLoadSucceeded),{get(){return s},async reload(){if(!ne(e.cwd,n)){let a=T();return d(a),a}try{let a=await y(e.cwd,{configFile:n});return d(a),a}catch(a){return t(a,{phase:"reload"}),s}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await i.stop()},ready(){return i.watcherReady()}}}import{tool as Vt,dynamicTool as zt,jsonSchema as Bt,zodSchema as Gt,stepCountIs as Jt,hasToolCall as Qt,convertToModelMessages as Xt,cosineSimilarity as Yt,smoothStream as er,Output as tr}from"ai";export{fe as AI_SERVICES,me as HELIX_CONFIG_ENV,tr as Output,de as REGION_VALUES,Ce as SCHEDULE_DEFINITION_KIND,ve as ScheduleConfigError,he as WORKSPACE_ID_REQUIRED_CODE,pe as aiProviderEntrySchema,Xt as convertToModelMessages,Yt as cosineSimilarity,rt as createConfigService,Ke as defineConfig,Oe as defineFunction,we as defineSchedule,zt as dynamicTool,ie as getContext,E as getSdkConfig,Qt as hasToolCall,Se as isScheduleDefinition,Bt as jsonSchema,y as loadConfig,ge as loadedTrayConfigSchema,ce as projectIdSchema,ue as regionSchema,ye as requireWorkspaceId,x as resolveConfigFile,_ as resolveConfigOverride,ae as runWithinAppSpan,er as smoothStream,Jt as stepCountIs,Vt as tool,le as workspaceIdSchema,Gt as zodSchema};
|
package/dist/internal/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as P,R as O,a as G,b as J,c as U,d as V,e as B,f as g,g as h,h as p,i as S,j as A,k as x,l as y,m as E,o as I,p as w,q as R,r as C,s as D,t as se,u as ie,v as ae,w as F,x as N}from"../chunk-
|
|
1
|
+
import{N as P,R as O,a as G,b as J,c as U,d as V,e as B,f as g,g as h,h as p,i as S,j as A,k as x,l as y,m as E,o as I,p as w,q as R,r as C,s as D,t as se,u as ie,v as ae,w as F,x as N}from"../chunk-UKKHDA5X.js";import{a as b}from"../chunk-WUCX7RZO.js";import{c as T,d as m,g as q,h as z,i as Q,j as W,k as X,l as Y,m as Z,n as ee,o as te,p as re,q as oe,s as ne}from"../chunk-HCGX7VQE.js";import{randomUUID as le}from"crypto";import{SpanStatusCode as k,SpanKind as ce}from"@opentelemetry/api";var r=class extends Error{constructor(e){super(`runScheduledFunction: ${e}`),this.name="ScheduleInvocationError"}};async function ue(i,e){if(typeof e!="object"||e===null)throw new r("`invocation` must be an object");let{schedulePath:o}=e;if(typeof o!="string"||o.length===0)throw new r("`schedulePath` must be a non-empty string");if(typeof e.isManual!="boolean")throw new r("`isManual` must be a boolean");if(!O(i))throw new r(`default export of "${o}" is not a defineSchedule definition`);let j=M("scheduledAt",e.scheduledAt),$=M("firedAt",e.firedAt),d=m(),a=d.executionId??le(),l=d.deploymentId??null,H=Date.now(),K=new Date().toISOString(),_=w(),v=I();A();let s={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1},c=!1,u=null;try{await h.run(s,()=>g.run(a,()=>y.startActiveSpan("schedule",{root:!0,kind:ce.SERVER,attributes:{method:"SCHEDULE",route:o,executionId:a,...l?{deploymentId:l}:{}}},async t=>{let L={type:"schedule",scheduledAt:j,firedAt:$,isManual:e.isManual},f={http:R(),db:n=>C(n),kv:()=>D(),files:()=>F(),callFunctionAsync:N(),ai:P(),log:v,config:_,state:{},executionId:a,deploymentId:l,traceId:t.spanContext().traceId,parentExecutionId:null,trigger:L};S(t,"input",{scheduledAt:e.scheduledAt,firedAt:e.firedAt,isManual:e.isManual});try{await b.run(f,()=>i.handler(f))}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),p("hasError"),n}finally{t.setAttribute("hasAuth",s.hasAuth),t.setAttribute("hasAi",s.hasAi),t.setAttribute("hasExternal",s.hasExternal),t.setAttribute("hasDb",s.hasDb),t.setAttribute("status",c?"error":"success");let n=c||s.hasError;t.setStatus({code:n?k.ERROR:k.OK,...u?{message:u}:{}}),t.end()}})))}finally{E({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:o,startedAt:K,startMs:H,errored:c,errorMessage:u,userId:null,flags:s}),await x()}}function M(i,e){if(typeof e!="string"||e.length===0)throw new r(`\`${i}\` must be a timestamp string; got ${JSON.stringify(e)}`);let o=new Date(e);if(Number.isNaN(o.getTime()))throw new r(`\`${i}\` must be a Date-parseable timestamp; got ${JSON.stringify(e)}`);return o}export{G as CONFIG_BRIDGE_CHANNEL,J as DEV_TOKEN_BRIDGE_CHANNEL,r as ScheduleInvocationError,se as assertValidPath,B as clearActiveConfig,ie as contentFilePath,V as getActiveConfig,re as getAdditionalRegionProfiles,Q as getRegionProfile,z as isKnownRegion,ne as isSdkError,Y as listExposedRegionNames,X as listRegionNames,ae as metaFilePath,Z as parseExposedRegionName,q as registerRegionProfile,W as requireRegionProfile,oe as resetRegionRegistryForTests,te as resolveForcedRegion,ue as runScheduledFunction,U as setActiveConfig,ee as setForcedRegion,T as setSdkConfig};
|
package/package.json
CHANGED
package/dist/chunk-CYG3GXE2.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{A as Pt,B as xe,C as H,D as te,F as At,G as Tt,H as kt,I as Ot,a as O,b as be,d as b,e as we,f as F,h as wt,j as _,k as St,o as xt,r as c,t as vt,u as Et,v as Se,w as Rt,x as It,y as K,z as Ct}from"./chunk-HEA646WT.js";var Zi="tray-config-bridge",es="tray-dev-token-bridge",ve=null;function ts(e){ve=e}function w(){if(!ve)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return ve}function rs(){ve=null}import{AsyncLocalStorage as Xt}from"async_hooks";import{trace as Bn,SpanKind as $n,SpanStatusCode as Ge}from"@opentelemetry/api";import{ExportResultCode as Kn,W3CTraceContextPropagator as Hn}from"@opentelemetry/core";import{NodeTracerProvider as Vn,SimpleSpanProcessor as qn,BatchSpanProcessor as zn}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Pn}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as An}from"@opentelemetry/exporter-logs-otlp-proto";function Je(e){return _(e).hosts.ingest}function Tn(){return F()??""}function Ft(){return{[O]:Tn()}}function _t(){let e=Je(w().region);return new Pn({url:`${e}/v1/traces`,headers:()=>Promise.resolve(Ft())})}function Dt(){let e=Je(w().region);return new An({url:`${e}/v1/logs`,headers:()=>Promise.resolve(Ft())})}import{logs as Mt,SeverityNumber as Ee}from"@opentelemetry/api-logs";import{LoggerProvider as Fn,BatchLogRecordProcessor as _n}from"@opentelemetry/sdk-logs";function re(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function kn(e){return new TextEncoder().encode(e).length}var Lt="\u2026[truncated]",On=kn(Lt),ne=4096;function j(e,t=ne){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-On);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+Lt}function S(e,t=ne){return j(re(e),t)}var Dn="@trayai/helix-sdk",oe,Ut={debug:{number:Ee.DEBUG,text:"DEBUG"},info:{number:Ee.INFO,text:"INFO"},warn:{number:Ee.WARN,text:"WARN"},error:{number:Ee.ERROR,text:"ERROR"}};function Ln(){return b().mode==="lambda"?[new _n({exporter:Dt()})]:[]}function Nt(){if(oe!==void 0)return;let e=Ln();e.length!==0&&(oe=new Fn({processors:e}),Mt.setGlobalLoggerProvider(oe))}function Un(e,t,r){let n=Ut[e]??Ut.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":S(r)}}:{}}}function jt(e,t,r){Mt.getLogger(Dn).emit(Un(e,t,r))}async function Bt(e=2e3){if(oe===void 0)return;let t;try{await Promise.race([oe.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
|
|
2
|
-
`)}finally{t!==void 0&&clearTimeout(t)}}function Ye(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function Mn(){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 A(e,t){return Mn()?`\x1B[${e}m${t}\x1B[0m`:t}var Nn=5,jn={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},$t="32",Kt="31",Re="2",Ht="1";function Ie(e){return A(jn[e]??"0",e.padEnd(Nn))}function Vt(e,t){return`${Ie("FN")} ${A(Ht,`${e} ${t}`.trim())}`}function qt(e,t,r,n){let o=e.toUpperCase(),s=`${n?`${A(Re,n)} `:""}${Ie(o)} ${t}`;return r&&Object.keys(r).length>0&&(s+=` ${A(Re,re(r))}`),s}function zt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Jt(e){return`${Ie("AUTH")} ${e}`}function Yt(e,t,r,n,o){let i=r===void 0?"ERR":String(r),s=A(o==="error"?Kt:$t,i);return`${Ie("API")} ${e} ${t} \u2192 ${s} ${A(Re,`${n}ms`)}`}function Gt(e,t,r){let n=t?Kt:$t,o=A(n,"\u25CF"),i=A(n,t?"error":"success");return`${o} ${A(Ht,e)} ${i} ${A(Re,`${r}ms`)}`}function V(e){try{process.stdout.write(e+`
|
|
3
|
-
`)}catch{}}var Qt=new Xt,Jn=new Xt;function E(e){let t=Jn.getStore();t&&(t[e]=!0)}var Yn=/^[0-9a-f]{32}$/;function Gn(e){let t=e.replace(/-/g,"").toLowerCase();return Yn.test(t)?t:null}var Wn={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},q=new Map;function Zt(e,t,r){let n=q.get(e);n?n[t]=r:q.set(e,{[t]:r})}function T(e,t,r){e.setAttribute(t,S(r))}var ie;function Wt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function Xn(e){return Math.round(e[0]*1e3+e[1]/1e6)}function er(e){try{process.stdout.write(re(e)+`
|
|
4
|
-
`)}catch{}}var We=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,i=q.get(o),s={...n.attributes};if(i!==void 0){for(let[u,m]of Object.entries(i))typeof m=="string"?s[u]=j(m):typeof m=="object"&&m!==null?s[u]=S(m):s[u]=m;q.delete(o)}let a=Qt.getStore(),l=a?Gn(a):null;er({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Wt(n.startTime),endTimeUnixNano:Wt(n.endTime),attributes:s,status:{code:Wn[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:j(n.status.message)}:{}}})}r({code:Kn.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Xe=class{onStart(t,r){}onEnd(t){q.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Qe=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&V(`
|
|
5
|
-
`+Vt(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=q.get(n)?.properties;V(qt(String(r.level??"info"),String(r.message??""),o,zt(t.startTime)));break}case"auth":V(Jt(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;V(Yt(String(r.method??""),String(r.host??""),n,Xn(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ze=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function Qn(){let t=[Ye()?new Qe:new qn(new We)];return b().mode==="lambda"&&t.push(new Ze(new zn(_t()))),t.push(new Xe),t}function Zn(){ie===void 0&&(ie=new Vn({spanProcessors:Qn()}),ie.register({propagator:new Hn}),Nt())}async function eo(e=2e3){let t=[Bt(e)];ie!==void 0&&t.push((async()=>{let r;try{await Promise.race([ie.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
|
|
6
|
-
`)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var P=Bn.getTracer("@trayai/helix-sdk");function to({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:i,errored:s,errorMessage:a,userId:l,flags:u}){let m=new Date().toISOString(),f=Date.now()-i;if(Ye()){V(`
|
|
7
|
-
`+Gt(n,s,f));return}er({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:m,durationMs:f,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasAi:u.hasAi,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?j(a):null})}async function ks(e,t){let r=e.startMs??Date.now();Zn();let n=!1,o=null;try{return await Qt.run(e.executionId,()=>P.startActiveSpan("App",{kind:$n.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async i=>{try{let s=await t(),a=s?.httpResponse?.status??404;return n=a>=400,i.setAttribute("http.response.status_code",a),i.setAttribute("helix.status",n?"error":"success"),i.setStatus({code:n?Ge.ERROR:Ge.OK}),s}catch(s){throw n=!0,o=s instanceof Error?s.message:String(s),i.setAttribute("http.response.status_code",500),i.setAttribute("helix.status","error"),i.setStatus({code:Ge.ERROR,message:o}),s}finally{i.end()}}))}finally{to({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:r,errored:n,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1}}),await eo()}}var nr=1024,D=100*1024*1024,tr=250,ro=3600,no=ro*1e3,rr=new TextEncoder,oo=/(^|\/)\.\.(\/|$)/,io=/[?#]/;function so(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function B(e,t=nr){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");Ce(e,t)}function et(e){return e.endsWith("/")?e.slice(0,-1):e}function Ce(e,t=nr){if(e.length===0)return;if(oo.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(io.test(e)||so(e))throw c.filesPathInvalid("Path contains illegal characters");let r=e.split("/");if(e.startsWith("/")||e.endsWith("/")||r.some(o=>o===""))throw c.filesPathInvalid("Path must not contain empty path segments");for(let o of r){let i=rr.encode(o).length;if(i>tr)throw c.filesPathInvalid(`Path segment exceeds ${tr} UTF-8 bytes (got ${i})`)}let n=rr.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function or(e){if(e>D)throw c.filesValueTooLarge(`File exceeds maximum size of ${D} bytes (got ${e})`,D)}function z(e){let t=e!==void 0?e*1e3:no;return new Date(Date.now()+t)}import{join as ae}from"path";var ao="files",co="files-meta",lo=1023,uo=1,fo=5;function ir(e){let t=Math.max(Buffer.byteLength(Pe(e),"utf8"),Buffer.byteLength(se(e),"utf8"));return Math.max(0,lo-t-uo-fo)}function Pe(e){return ae(e,".helix",ao)}function se(e){return ae(e,".helix",co)}function ce(e,t){return ae(Pe(e),...t.split("/"))}function Ae(e,t){return ae(se(e),...t.split("/"))+".json"}function Te(e,t){return t.length===0?Pe(e):ce(e,t)}function sr(e,t){return t.length===0?se(e):ae(se(e),...t.split("/"))}import{z as mo}from"zod";var Ns=["us1","eu1","ap1","ap2"],tt=mo.string().refine(e=>wt(e),e=>({message:`Invalid enum value. Expected ${St().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));import{resolve as L}from"path";import{existsSync as ke,realpathSync as ar}from"fs";import{loadConfig as po}from"c12";import{z as h}from"zod";var lr=h.string().uuid("projectId must be a valid UUID"),ur=h.string().min(1,"workspaceId must be a non-empty string"),le=["openai","anthropic","google","mistral","cohere","openai-compatible"],go=["openai","anthropic","google","mistral","cohere"],dr=h.union([h.enum(go),h.object({service:h.enum(le),baseUrl:h.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)"})]),yo=h.object({name:h.string().min(1,"name is required"),projectId:lr.optional(),workspaceId:ur.optional(),region:tt.optional(),env:h.literal("production").optional(),authentications:h.record(h.string()).optional().default({}),config:h.record(h.unknown()).optional().default({}),aiProviders:h.record(dr).optional()}).transform(({env:e,region:t,...r})=>({...r,region:t??"us1"})),cr=h.object({name:h.string().min(1,"name is required"),workspaceId:ur.optional(),region:tt,authentications:h.record(h.string()),config:h.record(h.unknown()),aiProviders:h.record(dr).optional()}),Js=h.discriminatedUnion("kind",[cr.extend({kind:h.literal("provisioned"),projectId:lr}),cr.extend({kind:h.literal("unprovisioned")})]),fr=["helix","tray"],mr=["ts","mts","cts","js","mjs","cjs"],pr="HELIX_CONFIG";function rt(e){let t=e?.trim();return t||process.env[pr]?.trim()||void 0}function ho(e,t){let r=rt(t?.configFile);if(r!==void 0){let n=L(e,r);return ke(n)?n:void 0}for(let n of fr)for(let o of mr){let i=L(e,`${n}.config.${o}`);if(ke(i))return i}}function bo(e){for(let t of fr)if(mr.some(r=>ke(L(e,`${t}.config.${r}`))))return t;return"helix"}function wo(e,t){return L(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function So(e,t){let r=rt(t?.configFile);return{name:bo(e),cwd:e,...r!==void 0?{configFile:wo(e,r)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function xo(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw c.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=yo.safeParse(e);if(!r.success){let u=r.error.issues.map(m=>m.message).join("; ");throw c.configLoadFailed(`Invalid helix.config.ts at ${t}: ${u}`)}let{projectId:n,workspaceId:o,...i}=r.data,s=o!==void 0?{workspaceId:o}:{},a=xt(),l=a!==void 0?{...i,region:a}:i;return n!==void 0?{kind:"provisioned",projectId:n,...l,...s}:{kind:"unprovisioned",...l,...s}}async function Ys(e,t){let r=e??process.cwd(),n=rt(t?.configFile),o=n!==void 0?L(r,n):void 0;if(o!==void 0&&!ke(o)){let a=t?.configFile?.trim()?"":` (from ${pr})`;throw c.configLoadFailed(`Config file not found: ${o}${a}`)}let i;try{i=await po(So(r,t))}catch(a){throw c.configLoadFailed(`Failed to load helix.config.ts: ${a instanceof Error?a.message:String(a)}`)}let s=i._configFile??ho(r,t);if(!s)throw c.configLoadFailed(`helix.config.ts not found at ${L(r,"helix.config.ts")}`);if(o!==void 0&&i._configFile!==void 0){let a=ar(o);if(ar(L(i._configFile))!==a)throw c.configLoadFailed(`Config file conflict: requested ${o} but ${L(i._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return xo(i.config,s)}var vo="WORKSPACE_ID_REQUIRED";function Gs(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:vo});return e.workspaceId}var gr="helix-schedule",U=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function Xs(e){if(typeof e!="object"||e===null)throw new U("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new U("`cron` must be a non-empty string");let i=t.trim().split(/\s+/).length;if(i!==5)throw new U(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${i} field(s) in "${t}"`);if(typeof r!="string"||!Eo(r))throw new U(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new U("`concurrent` must be a boolean");if(typeof o!="function")throw new U("`handler` must be a function");return Object.freeze({kind:gr,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function Qs(e){return typeof e=="object"&&e!==null&&e.kind===gr&&typeof e.handler=="function"}function Eo(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 Ro}from"@opentelemetry/api";function Oe(e,t,r){let n=P.startSpan("log",{kind:Ro.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Zt(n.spanContext().spanId,"properties",r),n.end(),jt(e,t,r)}function yr(){return{info:(e,t)=>Oe("info",e,t),warn:(e,t)=>Oe("warn",e,t),error:(e,t)=>Oe("error",e,t),debug:(e,t)=>Oe("debug",e,t)}}function ia(){try{return w().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import Io from"ky";import{context as nt,trace as Co,SpanKind as de,SpanStatusCode as br}from"@opentelemetry/api";async function Fe(e,t={}){let r=b(),{region:n}=w(),{headers:o,deploymentId:i}=H(r);i&&(o[Se]=i);let s=xe(n,r.mode==="lambda"?"runtime":"dev"),a;try{a=await At({proxyUrl:s,credentialHeaders:o,request:e,timeoutMs:t.timeout,executionId:r.executionId})}catch(l){let u=l instanceof Error?l.message??String(l):String(l);throw c.brokerError(0,u)}if(a.kind==="brokerError"){let l=a.code===K?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":a.message;throw c.brokerError(a.status,l,S(a.body),a.code)}return a.response}async function hr(e){Tt(e.url);let t=b(),{region:r}=w(),n={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},{headers:o,deploymentId:i}=H(t);i&&(n.deploymentId=i);let s=kt(r,t.mode==="lambda"?"runtime":"dev"),a;try{a=await Ot({signUrl:s,credentialHeaders:o,body:n,timeoutMs:e.timeout,executionId:t.executionId})}catch(l){let u=l instanceof Error?l.message??String(l):String(l);throw c.brokerError(0,u)}if(a.kind==="brokerError"){let l=a.code===K?"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 c.brokerError(a.status,l,S(a.body),a.code)}return a.result}var Po=["get","post","put","patch","delete","head","options"],Sr="[stream body omitted]";function xr(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?Sr: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 ot(e){try{return new URL(e).hostname}catch{return e}}function wr(e,t,r,n,o){let i=ot(t),s="externalApi",a={kind:de.CLIENT};return P.startActiveSpan(s,a,async l=>(l.setAttributes({method:e,host:i,"peer.service":n}),T(l,"request",{url:t,method:e,...r!==void 0?{body:xr(r)}:{}}),o(l)))}function ue(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:br.OK}:{code:br.ERROR,message:r}),e.end()}var Ao=16;async function To(e,t){let r=e.clone().body;return r?vr(r,t):new Uint8Array(0)}async function vr(e,t){let r=e.getReader(),n=[],o=0,i=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(i+=1,i>=Ao)break;continue}i=0;let m=t+1-o;if(u.byteLength>=m){n.push(u.slice(0,m)),o+=m;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let s=new Uint8Array(o),a=0;for(let l of n)s.set(l,a),a+=l.byteLength;return s}async function Er(e,t,r){if("kyResponse"in r)try{let n=await To(r.kyResponse,ne),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}T(e,"response",i)}catch{T(e,"response",{status:t})}else T(e,"response",xr(r.bodyValue))}async function ko(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),i=new Request(e,{body:n,duplex:"half"}),s=await vr(o,ne);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:Sr}}}return typeof t=="string"?{body:t}:{}}function ka(){let e=Io.create({});function t(n){return(o,i)=>{let s=nt.active(),a,l=!1,u=(f,g)=>{a&&!l&&(l=!0,ue(a,f,g))},m=e.extend({hooks:{beforeRequest:[async(f,g)=>{let y=await ko(f,g.body),x=y.body;if(a||(a=P.startSpan("externalApi",{kind:de.CLIENT},s)),a.setAttributes({method:f.method.toUpperCase(),host:ot(f.url)}),T(a,"request",{url:f.url,method:f.method.toUpperCase(),...x!==void 0?{body:x}:{}}),l=!1,E("hasExternal"),y.request)return y.request}],beforeRetry:[f=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(f,g,y)=>{a&&(a.setAttribute("statusCode",y.status),await Er(a,y.status,{kyResponse:y}),y.ok?u("success"):i?.throwHttpErrors===!1&&(E("hasError"),u("error",`HTTP ${y.status}`)))}],beforeError:[f=>(E("hasError"),u("error",f.message),f)]}});return a=P.startSpan("externalApi",{kind:de.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:ot(String(o))}),nt.with(Co.setSpan(nt.active(),a),()=>{let f=n==="options"?m(o,{...i,method:"OPTIONS"}):m[n](o,i);return f.catch(g=>{E("hasError"),u("error",g instanceof Error?g.message:String(g))}),f})}}let r=Object.fromEntries(Po.map(n=>[n,t(n)]));return{...e,...r,authed(n){return Oo(n)}}}function Oo(e){let r=w().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(a,l={})=>{let u=s.toUpperCase();return wr(u,a,l.body,e,async m=>{E("hasAuth");let f=P.startSpan("auth",{kind:de.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let g=te({authenticationId:n,method:u,url:a,body:l.body,headers:l.headers,query:l.query}),y=await Fe(g,{timeout:l.timeout});return m.setAttribute("statusCode",y.status),await Er(m,y.status,{bodyValue:y.body}),ue(m,"success"),y}catch(g){throw E("hasError"),g instanceof c&&g.detail.kind==="broker_error"&&g.detail.status>0&&m.setAttribute("statusCode",g.detail.status),ue(m,"error",g instanceof Error?g.message:String(g)),g}})}}function i(s,a={}){let l=a.method??"GET";return wr(l,s,void 0,e,async u=>{E("hasAuth");let m=P.startSpan("auth",{kind:de.INTERNAL});m.setAttribute("alias",e),m.setAttribute("id",n),m.end();try{let f=await hr({authenticationId:n,url:s,method:l,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return u.setAttribute("statusCode",200),ue(u,"success"),f}catch(f){throw E("hasError"),f instanceof c&&f.detail.kind==="broker_error"&&f.detail.status>0&&u.setAttribute("statusCode",f.detail.status),ue(u,"error",f instanceof Error?f.message:String(f)),f}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:i}}import{SpanKind as Bo,SpanStatusCode as Pr}from"@opentelemetry/api";function fe(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Fo=18e4,Rr=Fo-1e4,_o=2e3;async function Ir(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<Rr;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(_o,200*2**i),u=l/2+Math.random()*(l/2),m=Rr-(Date.now()-o);await new Promise(f=>setTimeout(f,Math.min(u,m))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Do=new Set(["SELECT","WITH","SHOW"]),Lo=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function Uo(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function Mo(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let i=typeof t=="string"?j(t):S(t);return c.dbCallFailed(i)}function No(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function jo(e,t){return typeof t!="number"||t<0?{}:Do.has(e)?{rowsRead:t}:Lo.has(e)?{rowsWritten:t}:{}}function Cr(e){async function t(r,n,o){let i=te({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:s,body:a}=await Fe(i);if(s>=400)throw Mo(s,a);return No(a)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.dbCallFailed(a,s instanceof Error?s:void 0)}}return{system:"redshift",validate:Uo,async execute(r,n){let o=fe(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let y=S(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${y}`)}let u=await Ir(t,r.region,l),m=u.Status;if(m==="FAILED"){let y=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${y} (statement: ${l})`)}if(m==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let f=jo(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:f}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:f}}}}var it=64*1024;function $o(e){return e.length>it?`${e.slice(0,it)}...[truncated]`:e}function Ko(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Ho(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>it?T(e,"result",{truncated:!0,size:n.length}):T(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Vo(e,t,r){let n=fe(r),o=$o(r);return P.startActiveSpan("database",{kind:Bo.CLIENT},async i=>{Ko(i,e,t,n,o);try{E("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Ho(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:Pr.OK}),l}catch(s){E("hasError");let a=s instanceof Error?s.message:String(s);throw i.setAttribute("status","error"),i.setStatus({code:Pr.ERROR,message:a}),s}finally{i.end()}})}function qo(e){let r=w().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Cr(n);function i(s,a){return o.validate(s),Vo(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as Wo}from"unstorage";var Ar=1024,st=250*1024,zo=new TextEncoder,Jo=/(^|\/)\.\.(\/|$)/,Yo=/[?#]/,Go=/[\u0000-\u001F\u007F]/;function Tr(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(Jo.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(Yo.test(e)||Go.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=zo.encode(e).length;if(t<1||t>Ar)throw c.kvKeyInvalid(`Key must be between 1 and ${Ar} UTF-8 bytes (got ${t})`)}function kr(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Or(e){let t;try{t=JSON.stringify(e)}catch{throw c.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw c.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>st)throw c.kvValueTooLarge(`Value exceeds maximum size of ${st} bytes (got ${r})`,st)}function me(e){Tr(e)}function _e(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Fr(e){let t=_e(e,"getItem"),r=_e(e,"setItem"),n=_e(e,"removeItem"),o=_e(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return me(s),t(s,a)},setItem(s,a,l){return me(s),r(s,a,l)},removeItem(s,a){return me(s),n(s,a)},hasItem(s,a){return me(s),o(s,a)},getKeys(s,a){return s.length>0&&me(s),i(s,a)}}}function De(e){return Wo({driver:Fr(e)})}import{defineDriver as Xo}from"unstorage";function Qo(e){try{return JSON.parse(e)}catch{return e}}var Zo=Xo(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n,o){let i=o?.ttl,s=Qo(n);i!==void 0?await t.set(r,s,{ttl:i}):await t.set(r,s)},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function _r(e){return Zo({client:e})}import ri from"ky";import{z as R}from"zod";async function M(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function Dr(e){return _(e).hosts.api}function ei(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function ti(e){return e.split("/").map(encodeURIComponent).join("/")}function pe(e,t,r){return`${e}${ei(t)}/${ti(r)}`}var ni=6e4,at=R.lazy(()=>R.union([R.string(),R.number(),R.boolean(),R.null(),R.array(at),R.record(at)])),oi=R.object({projectId:R.string(),key:R.string(),value:at,type:R.enum(["string","number","boolean","null","array","object"]),organizationId:R.string(),scope:R.string(),createdBy:R.string(),createdAt:R.number(),updatedBy:R.string(),updatedAt:R.number()});function ii(){let e=we(),t=F(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[be]=e),n&&(o[O]=t),o}function si(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 Le(e,t){throw c.kvCallFailed(e,si(t),S(t))}async function Ue(e,t,r={}){try{let n=await ri(t,{method:e,headers:ii(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ni}),o=e==="head"?void 0:await M(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw c.kvCallFailed(0,o)}}function Lr(e){let t=Dr(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await Ue("get",pe(t,r,n));if(o===404)return null;(o<200||o>=300)&&Le(o,i);let s=oi.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",S(i));return s.data.value},async set(n,o,i){let{status:s,body:a}=await Ue("put",pe(t,r,n),{json:i?.ttl!==void 0?{value:o,ttl:i.ttl}:{value:o}});(s<200||s>=300)&&Le(s,a)},async delete(n){let{status:o,body:i}=await Ue("delete",pe(t,r,n));o!==204&&Le(o,i)},async has(n){let{status:o,body:i}=await Ue("head",pe(t,r,n));if(o===200)return!0;if(o===404)return!1;Le(o,i)}}}function Me(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,r,n)=>{let o=n?.ttl;Or(r),typeof o=="number"&&kr(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function ai(){let e=w();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function Ur(e){let t=ai(),r=e??Lr(t),n=De(_r(r));return Me(n)}import{defineDriver as ci}from"unstorage";var li=ci(e=>{let t=new Map;function r(n){let o=t.get(n);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(n);return}return o}return{name:"memory-ttl",getItem(n){return r(n)?.value??null},setItem(n,o,i){let s=i?.ttl,a=r(n),l=typeof s=="number"?Date.now()+s*1e3:s===null?void 0:a?.expiresAt;t.set(n,{value:o,expiresAt:l})},removeItem(n){t.delete(n)},hasItem(n){return r(n)!==void 0},getKeys(){return[...t.keys()].filter(n=>r(n)!==void 0)},clear(){t.clear()}}});function Mr(){return li({})}var ct;function ui(){return ct||(ct=De(Mr())),ct}function Nr(){return Me(ui())}function di(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":b().mode==="lambda"}function Lc(){return di()?Ur():Nr()}import{createHash as pi}from"crypto";import{mkdir as gi,readFile as Hr,readdir as Vr,rm as Br,unlink as yi,writeFile as $r}from"fs/promises";import{dirname as hi}from"path";async function fi(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:i}=await t.read();if(o)break;if(i){if(n+=i.byteLength,n>D)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${D} bytes (got more than ${D})`,D);r.push(i)}}return Buffer.concat(r)}async function J(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?fi(e):Buffer.from(e)}var mi={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"},jr="application/octet-stream";function Ne(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return jr;let r=e.slice(t+1).toLowerCase();return mi[r]??jr}function G(){let e=b().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function Y(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function je(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function lt(e){try{let t=await Hr(Ae(G(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Kr(e){await gi(hi(e),{recursive:!0})}async function bi(e,t){let r=Te(e,t),n;try{n=await Vr(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return n.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function qr(e,t){let r=Te(e,t),n;try{n=await Vr(r,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let o=[];for(let i of n){let s=t.length===0?i.name:`${t}/${i.name}`;i.isDirectory()?o.push(...await qr(e,s)):i.isFile()&&o.push(s)}return o}function zr(){return{async put(e,t,r){return Y(async()=>{let n=G(),o=await J(t),i=r?.contentType??Ne(e),s=pi("sha1").update(o).digest("hex"),a=new Date,l=ce(n,e);await Kr(l),await $r(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},m=Ae(n,e);return await Kr(m),await $r(m,JSON.stringify(u)),je(e,u)})},async get(e){return Y(async()=>{let t=await lt(e);return t?{data:await Hr(ce(G(),e)),metadata:je(e,t)}:null})},async head(e){return Y(async()=>{let t=await lt(e);return t?je(e,t):null})},async delete(e){return Y(async()=>{let t=G();await Promise.all([ce(t,e),Ae(t,e)].map(async r=>{try{await yi(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return Y(async()=>{let t=G(),r=await qr(t,e);return await Promise.all([Br(Te(t,e),{recursive:!0,force:!0}),Br(sr(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return Y(async()=>{let r=G(),n=t?.limit??100,i=(await bi(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await lt(a);return l?je(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=b().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:z(t?.expiresIn)}},async getDownloadUrl(e,t){let r=b().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:z(t?.expiresIn)}}}}import{createHash as Ii}from"crypto";function Be(e){return _(e).hosts.api}function wi(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ge(e,t){return`${e}${wi(t)}`}function W(e,t,r){return`${ge(e,t)}/${encodeURIComponent(r)}`}function $e(e,t,r){return`${W(e,t,r)}/upload`}function Jr(e,t,r){return`${W(e,t,r)}/download`}function Yr(e,t,r){return`${W(e,t,r)}/signed-url`}function Gr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${ge(e,t)}/file?${o.toString()}`}function Wr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${ge(e,t)}?${o.toString()}`}import dt from"ky";import{z as v}from"zod";var ft=6e4,Xr=v.object({id:v.string(),workspaceId:v.string(),projectId:v.string(),parentFolder:v.string().nullable().optional(),name:v.string(),size:v.number().nullable().optional(),objectType:v.enum(["Folder","File"]),contentType:v.string().nullable().optional(),createdAt:v.string(),updatedAt:v.string()}),Si=v.object({signedURL:v.string()}),xi=v.object({path:v.array(v.object({id:v.string(),name:v.string()})),elements:v.array(Xr)});function mt(){let e=we(),t=F(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[be]=e),n&&(o[O]=t),o}function Qr(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 N(e,t){throw c.filesCallFailed(e,Qr(t),S(t))}function vi(e,t){return e===400&&Qr(t).toLowerCase()==="resource not found"}async function Ei(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function X(e,t,r={}){try{let n=await dt(t,{method:e,headers:mt(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ft}),o=await M(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function ut(e,t){let r=Xr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",S(t));return r.data}function Zr(e){let t=Be(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await X("post",ge(t,r),{json:n});return(o<200||o>=300)&&N(o,i),ut(o,i)},async getByName(n,o){let{status:i,body:s}=await X("get",Gr(t,r,n,o));return i===404||vi(i,s)?null:((i<200||i>=300)&&N(i,s),ut(i,s))},async getById(n){let{status:o,body:i}=await X("get",W(t,r,n));return o===404?null:((o<200||o>=300)&&N(o,i),ut(o,i))},async listChildren(n,o){let{status:i,body:s}=await X("get",Wr(t,r,n,o));(i<200||i>=300)&&N(i,s);let a=xi.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",S(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await Ei(a),m;try{m=await dt($e(t,r,n),{method:"post",headers:{...mt(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:ft})}catch(g){if(g instanceof c)throw g;let y=g instanceof Error?g.message:String(g);throw c.filesCallFailed(0,y)}let f=await M(m);(m.status<200||m.status>=300)&&N(m.status,f)},async downloadContent(n){let o;try{o=await dt(Jr(t,r,n),{method:"get",headers:mt(),throwHttpErrors:!1,timeout:ft})}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message:String(s);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let s=await M(o);N(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await X("get",Yr(t,r,n));(o<200||o>=300)&&N(o,i);let s=Si.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",S(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await X("delete",W(t,r,n));o===204||o===404||(o<200||o>=300)&&N(o,i)}}}function pt(e){return e.split("/").filter(t=>t.length>0)}function gt(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Ri(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(gt(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function yt(e,t){let r=pt(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await Ri(e,o,i)).id;return{parentFolder:o,name:n}}async function ye(e,t){let r=pt(t),n=r[r.length-1],o;for(let i of r.slice(0,-1)){let s=await e.getByName(o,i);if(!s||s.objectType!=="Folder")return null;o=s.id}return{parentFolder:o,name:n}}async function ht(e,t){if(t.length===0)return;let r=pt(t),n;for(let o of r){let i=await e.getByName(n,o);if(!i||i.objectType!=="Folder")return null;n=i.id}return n}var Ci=500,Pi=8;async function Ai(e,t,r){let n=new Array(e.length),o=0;async function i(){for(;o<e.length;){let s=o++;n[s]=await r(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}function Ti(){let e=w();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function ki(e){return Ii("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Ke(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:ki(t)}}async function en(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(gt(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function tn(e,t){let{elements:r}=await e.listChildren(t,Ci);return(await Ai(r,Pi,async o=>{let i=o.objectType==="Folder"?await tn(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function rn(e){let t=Ti(),r=e??Zr(t),n=Be(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await yt(r,i),m=await J(s),f=a?.contentType??Ne(i),g=await r.getByName(l,u);if(g&&g.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${i}"`);let y=g??await en(r,l,u,f);await r.uploadContent(y.id,m,u,f);let x=await r.getById(y.id);return Ke(i,x??y,f)},async get(i){let s=await ye(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Ke(i,a)}},async head(i){let s=await ye(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:Ke(i,a)},async delete(i){let s=await ye(r,i);if(!s)return;let a=await r.getByName(s.parentFolder,s.name);a&&await r.deleteById(a.id)},async deleteMany(i){let s=await ht(r,i);if(s===null)return{deleted:0};let a=await tn(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await ht(r,i??"");if(a===null)return{files:[],cursor:null};let l=s?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(f=>f.objectType==="File").map(f=>Ke(i?`${i}/${f.name}`:f.name,f)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await yt(r,i),m=await r.getByName(a,l)??await en(r,a,l,s?.contentType);return{url:$e(n,o,m.id),expiresAt:z(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await ye(r,i),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${i}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:z(s?.expiresIn)}}}}function bt(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){B(n,r);let s=await J(o);return or(s.byteLength),e.put(n,s,i)},async get(n){return B(n,r),e.get(n)},async head(n){return B(n,r),e.head(n)},async delete(n){return B(n,r),e.delete(n)},async deleteMany(n){let o=et(n);return Ce(o,r),e.deleteMany(o)},async list(n,o){let i=et(n??"");return Ce(i,r),e.list(i,o)},async getUploadUrl(n,o){return B(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return B(n,r),e.getDownloadUrl(n,o)}}}function Oi(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":b().mode==="lambda"}function Pl(){if(Oi())return bt(rn());let e=b().projectRoot;return bt(zr(),{maxPathBytes:e?ir(e):void 0})}import _i from"ky";function nn(e){return _(e).hosts.api}function Fi(){return"/private/v1/helix/function-calls"}function on(e){return`${e}${Fi()}`}var Di=5e3;function Li(){let e=F();if(!!!(e&&e.trim().length>0))throw c.callFunctionMissingExecutionJwt();return{Accept:"application/json",[O]:e}}function Ui(e,t){throw c.callFunctionCallFailed(e,Mi(t),S(t))}function Mi(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 sn(e){let t=nn(e.env);return{async callAsync(r,n){let o,i;try{let s=await _i(on(t),{method:"post",headers:Li(),json:{functionPath:r,input:n},throwHttpErrors:!1,timeout:Di});o=s.status,i=await M(s)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.callFunctionCallFailed(0,a)}(o<200||o>=300)&&Ui(o,i)}}}var an=1024;function He(e){if(typeof e!="string"||e.trim().length===0)throw c.callFunctionPathInvalid("functionPath must be a non-empty string");if(e.length>an)throw c.callFunctionPathInvalid(`functionPath must be at most ${an} characters`)}function Ni(){let e=w();if(e.kind!=="provisioned")throw c.callFunctionRequiresProvisioning();return{env:e.region}}function cn(e){return async function(r,n){He(r),await(e??sn(Ni())).callAsync(r,n)}}function ln(){return async function(t,r){He(t);let n=b().devServerUrl;if(!n)throw c.callFunctionNotAvailable();let o=t.startsWith("/")?t:`/${t}`,i=yr();fetch(`${n}${o}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r??{})}).then(s=>{s.ok||i.warn("ctx.callFunctionAsync: dev-mode dispatch returned a non-2xx response",{functionPath:t,status:s.status})}).catch(s=>{i.warn("ctx.callFunctionAsync: dev-mode dispatch failed",{functionPath:t,error:s instanceof Error?s.message:String(s)})})}}function ji(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":b().mode==="lambda"}function Zl(){return ji()?cn():ln()}import{embed as gn,embedMany as yn,generateImage as hn,generateObject as bn,generateSpeech as wn,generateText as Sn,streamObject as xn,streamText as vn,transcribe as En}from"ai";import{SpanKind as Wi,SpanStatusCode as pn}from"@opentelemetry/api";import{createOpenAI as Hi}from"@ai-sdk/openai";import{createAnthropic as Vi}from"@ai-sdk/anthropic";import{createGoogle as qi}from"@ai-sdk/google";import{createMistral as zi}from"@ai-sdk/mistral";import{createCohere as Ji}from"@ai-sdk/cohere";import{createOpenAICompatible as Yi}from"@ai-sdk/openai-compatible";var Bi=new Set(["x-api-key","x-goog-api-key"]);function $i(e){return Ct(e)||Bi.has(e.toLowerCase())}function Ki(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function un(e){return async(t,r)=>{let n=Ki(t),o=new URL(n);if(o.protocol!=="https:")throw c.unsupportedScheme(o.protocol.replace(/:$/,""));let i=b(),{region:s}=w(),a=new Headers(r?.headers??(t instanceof Request?t.headers:void 0)),l=new Headers;for(let[d,p]of a.entries())$i(d)||l.append(d,p);l.set(vt,n),l.set(Et,e),i.executionId&&l.set(Rt,i.executionId);let{headers:u,deploymentId:m}=H(i);for(let[d,p]of Object.entries(u))l.set(d,p);m&&l.set(Se,m);let f=xe(s,i.mode==="lambda"?"runtime":"dev"),g=r?.body??(t instanceof Request?t.clone().body:void 0),y={method:r?.method??(t instanceof Request?t.method:"GET"),headers:l,redirect:"manual",signal:r?.signal??void 0};g!=null&&(y.body=g,typeof ReadableStream<"u"&&g instanceof ReadableStream&&(y.duplex="half"));let x;try{x=await fetch(f,y)}catch(d){if(d instanceof Error&&d.name==="AbortError")throw d;let p=d instanceof Error?d.message??String(d):String(d);throw c.brokerError(0,p)}let ee=x.headers.get(It);if(ee!==null){let d=await x.text(),p=d||ee;try{let I=Pt.safeParse(JSON.parse(d));I.success&&(p=I.data.error.message)}catch{}throw ee===K&&(p="credential broker does not support the raw proxy endpoint required by ctx.ai \u2014 deploy a newer broker or pin an older SDK"),c.brokerError(x.status,p,d||void 0,ee)}return x}}var Q="helix-broker";function dn(e){let{alias:t,service:r,baseUrl:n,authenticationId:o}=e,i=un(o);switch(r){case"openai":return Hi({apiKey:Q,fetch:i});case"anthropic":return Vi({apiKey:Q,fetch:i});case"google":return qi({apiKey:Q,fetch:i});case"mistral":return zi({apiKey:Q,fetch:i});case"cohere":return Ji({apiKey:Q,fetch:i});case"openai-compatible":{if(!n)throw c.aiUnsupportedService(t,r,[...le]);return Yi({name:t,baseURL:n,apiKey:Q,fetch:i})}}}var fn={"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}},Gi=Object.keys(fn).sort((e,t)=>t.length-e.length);function mn(e,t){let r=Gi.find(i=>e.startsWith(i));if(!r||!t)return{amount:0,currency:"USD"};let n=fn[r],o=((t.inputTokens??0)*n.input+(t.outputTokens??0)*n.output)/1e6;return{amount:Number(o.toFixed(8)),currency:"USD"}}function C(e,t,r){return P.startActiveSpan("ai",{kind:Wi.CLIENT},async n=>{n.setAttributes({operation:e.operation,model:e.model,...e.alias!==void 0?{alias:e.alias}:{}}),E("hasAi");try{let o=await t(),i=r?.(o);return i&&n.setAttributes({...i.inputTokens!==void 0?{inputTokens:i.inputTokens}:{},...i.outputTokens!==void 0?{outputTokens:i.outputTokens}:{}}),n.setAttribute("status","success"),n.setStatus({code:pn.OK}),o}catch(o){let i=o instanceof Error?o.message:String(o);throw n.setAttribute("status","error"),n.setStatus({code:pn.ERROR,message:i}),o}finally{n.end()}})}function Xi(){return`aireq_${crypto.randomUUID().replaceAll("-","")}`}function Z(e,t){return{cost:mn(e,t),requestId:Xi()}}function $(e){return typeof e=="object"&&e!==null&&"modelId"in e?String(e.modelId):String(e)}var Rn=new WeakSet;function he(e){return Rn.add(e),e}function k(e){if(typeof e!="object"||e===null)throw c.aiModelInstanceRequired(typeof e=="string"?e:String(e));if(!Rn.has(e))throw c.aiForeignModelRejected()}function Ve(e){return e.totalUsage??e.usage}function qe(e){return e.usage?.tokens!==void 0?{inputTokens:e.usage.tokens}:void 0}function ze(e){return e.usage}function Qi(e){let t=w(),r=t.authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=(t.aiProviders??{})[e];if(o===void 0)throw c.aiProviderNotConfigured(e,[...le]);let{service:i,baseUrl:s}=typeof o=="string"?{service:o,baseUrl:void 0}:o,a=dn({alias:e,service:i,baseUrl:s,authenticationId:n}),l=d=>he(a.languageModel(d)),u=d=>he(a.embeddingModel(d)),m=d=>he(a.imageModel(d)),f=d=>{if(!a.transcriptionModel)throw new Error(`AI provider "${i}" (alias "${e}") has no transcription models`);return he(a.transcriptionModel(d))},g=d=>{if(!a.speechModel)throw new Error(`AI provider "${i}" (alias "${e}") has no speech models`);return he(a.speechModel(d))},y=(d=>l(d)),x=(d,p)=>{let I=d.model;if(typeof I!="string")throw c.aiModelIdRequired(e,p);return I};return Object.assign(y,{specificationVersion:"v4",languageModel:l,embeddingModel:u,textEmbeddingModel:u,imageModel:m,transcriptionModel:f,speechModel:g,async generateText(d){let p=x(d,"generateText"),I=await C({operation:"generateText",model:p,alias:e},()=>Sn({...d,model:l(p)}),Ve);return Object.assign(I,{helix:Z(p,Ve(I))})},streamText(d){let p=x(d,"streamText");return E("hasAi"),vn({...d,model:l(p)})},async generateObject(d){let p=x(d,"generateObject"),I=await C({operation:"generateObject",model:p,alias:e},()=>bn({...d,model:l(p)}),Cn=>Cn.usage),In=I.usage;return Object.assign(I,{helix:Z(p,In)})},streamObject(d){let p=x(d,"streamObject");return E("hasAi"),xn({...d,model:l(p)})},async embed(d){let p=x(d,"embed");return C({operation:"embed",model:p,alias:e},()=>gn({...d,model:u(p)}),qe)},async embedMany(d){let p=x(d,"embedMany");return C({operation:"embedMany",model:p,alias:e},()=>yn({...d,model:u(p)}),qe)},async generateImage(d){let p=x(d,"generateImage"),I=await C({operation:"generateImage",model:p,alias:e},()=>hn({...d,model:m(p)}),ze);return Object.assign(I,{helix:Z(p,ze(I))})},async transcribe(d){let p=x(d,"transcribe");return C({operation:"transcribe",model:p,alias:e},()=>En({...d,model:f(p)}))},async generateSpeech(d){let p=x(d,"generateSpeech");return C({operation:"generateSpeech",model:p,alias:e},()=>wn({...d,model:g(p)}))}})}function Iu(){let e=new Map;return Object.assign((n=>{let o=e.get(n);return o||(o=Qi(n),e.set(n,o)),o}),{async generateText(n){k(n.model);let o=$(n.model),i=await C({operation:"generateText",model:o},()=>Sn(n),Ve);return Object.assign(i,{helix:Z(o,Ve(i))})},streamText(n){return k(n.model),E("hasAi"),vn(n)},async generateObject(n){k(n.model);let o=$(n.model),i=await C({operation:"generateObject",model:o},()=>bn(n),a=>a.usage),s=i.usage;return Object.assign(i,{helix:Z(o,s)})},streamObject(n){return k(n.model),E("hasAi"),xn(n)},async embed(n){return k(n.model),C({operation:"embed",model:$(n.model)},()=>gn(n),qe)},async embedMany(n){return k(n.model),C({operation:"embedMany",model:$(n.model)},()=>yn(n),qe)},async generateImage(n){k(n.model);let o=$(n.model),i=await C({operation:"generateImage",model:o},()=>hn(n),ze);return Object.assign(i,{helix:Z(o,ze(i))})},async transcribe(n){return k(n.model),C({operation:"transcribe",model:$(n.model)},()=>En(n))},async generateSpeech(n){return k(n.model),C({operation:"generateSpeech",model:$(n.model)},()=>wn(n))}})}export{Zi as a,es as b,ts as c,w as d,rs as e,Qt as f,Jn as g,E as h,T as i,Zn as j,eo as k,P as l,to as m,ks as n,yr as o,ia as p,ka as q,qo as r,Lc as s,B as t,ce as u,Ae as v,Pl as w,Zl as x,Ns as y,tt as z,lr as A,ur as B,le as C,dr as D,Js as E,pr as F,rt as G,ho as H,So as I,xo as J,Ys as K,vo as L,Gs as M,Iu as N,gr as O,U as P,Xs as Q,Qs as R};
|