@trayai/helix-sdk 0.112.1 → 0.114.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,43 @@ general availability, minor versions may include breaking changes.
9
9
  The SDK and [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) are
10
10
  released together and share a version — install matching versions.
11
11
 
12
+ ## 0.114.0
13
+
14
+ ### Added
15
+
16
+ - **AI gateway — `ctx.ai`.** `ctx.ai(alias)` is a real [AI SDK](https://ai-sdk.dev/) provider
17
+ bound to a `helix.config.ts` authentication alias, with the platform injecting the model
18
+ provider's API key so it never touches your code. Declare the service backing each alias
19
+ with the new `aiProviders` config field, then call `generateText`, `streamText`,
20
+ `generateObject`, `streamObject`, `embed`, `embedMany`, `generateImage`, `transcribe`, or
21
+ `generateSpeech` on it with a string model id. The top-level `ctx.ai.*` functions take a
22
+ model instance instead, for handing a model to a custom agent loop. Generate-style results
23
+ carry an estimated `result.helix.cost` alongside the AI SDK's own fields. Supported
24
+ services: `openai`, `anthropic`, `google`, `mistral`, `cohere`, `openai-compatible`. AI SDK
25
+ helpers and types (`tool`, `stepCountIs`, `convertToModelMessages`, message/stream/result
26
+ types, etc.) are re-exported so your project needs no separate `ai` dependency. See the
27
+ README's "AI — `ctx.ai`" section for the full surface and config shape. New exported types:
28
+ `HelixAI`, `HelixAIProvider`, `HelixResultMeta`, `HelixCost`, `AiLanguageModelInstance`,
29
+ `AiEmbeddingModelInstance`, `AiImageModelInstance`, `AiTranscriptionModelInstance`,
30
+ `AiSpeechModelInstance`, `AiService`, `AiProviderEntry`.
31
+ - The top-level `ctx.ai.*` functions now reject a model instance that wasn't obtained from
32
+ `ctx.ai(alias)` (`SdkError.aiForeignModelRejected`) — such an instance would carry its own
33
+ API key and connect directly to the provider instead of routing through the platform.
34
+ - An `aiProviders` entry's `baseUrl` must be `https:`; this is now validated when your config
35
+ loads instead of failing on the first `ctx.ai` call.
36
+ - `generateImage`'s `result.helix.cost` now reflects the provider's reported token usage
37
+ (previously always `0`) — real for token-billed image models like `gpt-image-1`; most image
38
+ models (e.g. `dall-e-3`) bill per image and report no usage, so they still estimate to `0`.
39
+
40
+ ## 0.113.0
41
+
42
+ ### Changed
43
+
44
+ - **Node.js 24.19.0 or newer is now required** (was 24.18.0). Deploys reject dependencies
45
+ published within the last 7 days, and `@trayai/*` is exempt from that rule — but npm only
46
+ learned to honour such an exemption in 11.17.0, which ships with Node 24.19. On older versions
47
+ the exemption is silently ignored, which would hold Helix releases back for a week.
48
+
12
49
  ## 0.112.0
13
50
 
14
51
  ### Added
package/README.md CHANGED
@@ -14,6 +14,7 @@ The runtime SDK for **Helix** — a TypeScript-first platform for building integ
14
14
  - [Capability modules](#capability-modules)
15
15
  - [Scheduled functions](#scheduled-functions)
16
16
  - [Async function calls](#async-function-calls)
17
+ - [AI — `ctx.ai`](#ai--ctxai)
17
18
  - [Authentication](#authentication)
18
19
  - [Configuration](#configuration)
19
20
  - [Logging](#logging)
@@ -25,7 +26,7 @@ The runtime SDK for **Helix** — a TypeScript-first platform for building integ
25
26
 
26
27
  ## Requirements
27
28
 
28
- - **Node.js ≥ 24.18.0**
29
+ - **Node.js ≥ 24.19.0**
29
30
  - ESM only (`"type": "module"`) — this package ships no CommonJS build
30
31
  - A [Tray Helix](https://helix.tray.ai/) account for authenticated calls (see [Authentication](#authentication))
31
32
  - The [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) for scaffolding, local dev, and deploy (recommended)
@@ -81,6 +82,7 @@ Every HTTP handler receives a `ctx` (`TrayContext`); scheduled handlers receive
81
82
  | `ctx.http.authed(alias)` | Authenticated HTTP — credentials are injected by the platform; secrets never touch your code |
82
83
  | `ctx.kv()` | Key-value store |
83
84
  | `ctx.files()` | File storage |
85
+ | `ctx.ai(alias)` | AI provider access — credentials are injected by the platform, same as `ctx.http.authed` |
84
86
  | `ctx.log.info/warn/error/debug` | Structured logging |
85
87
  | `ctx.config` | The `config` block from `helix.config.ts` |
86
88
  | `ctx.state` | Per-request scratch space |
@@ -276,9 +278,74 @@ Things to know:
276
278
  `ctx.parentExecutionId` is always `null` in dev, since there's no real calling execution to
277
279
  report.
278
280
 
281
+ ## AI — `ctx.ai`
282
+
283
+ `ctx.ai(alias)` gives you a real [AI SDK](https://ai-sdk.dev/) provider whose calls are routed
284
+ through the platform, so you never handle a model provider's API key directly. Declare which
285
+ service backs each alias in `helix.config.ts`:
286
+
287
+ ```typescript
288
+ // helix.config.ts
289
+ export default defineConfig({
290
+ // ...
291
+ authentications: {
292
+ anthropicKey: '<your-anthropic-auth-uuid>',
293
+ },
294
+ aiProviders: {
295
+ // 'openai' | 'anthropic' | 'google' | 'mistral' | 'cohere', or the object form
296
+ // { service: 'openai-compatible', baseUrl } for self-hosted endpoints
297
+ anthropicKey: 'anthropic',
298
+ },
299
+ });
300
+ ```
301
+
302
+ ```typescript
303
+ import { defineFunction } from '@trayai/helix-sdk';
304
+
305
+ export default defineFunction(async (ctx) => {
306
+ const result = await ctx.ai('anthropicKey').generateText({
307
+ model: 'claude-sonnet-4-5',
308
+ prompt: ctx.input.prompt,
309
+ });
310
+ return { text: result.text, cost: result.helix.cost };
311
+ });
312
+ ```
313
+
314
+ - **`ctx.ai(alias)`** returns a provider scoped to that alias, with methods
315
+ (`generateText`, `streamText`, `generateObject`, `streamObject`, `embed`, `embedMany`,
316
+ `generateImage`, `transcribe`, `generateSpeech`, plus `languageModel`/`embeddingModel`/
317
+ `imageModel`/`transcriptionModel`/`speechModel` for building a model instance) that take
318
+ `model` as a string id.
319
+ - **`ctx.ai.generateText`** and the other top-level `ctx.ai.*` functions take a model
320
+ *instance* (e.g. `ctx.ai(alias).languageModel(id)`) instead of a string — use them when
321
+ handing a model to a custom agent loop or a third-party helper that expects an AI SDK
322
+ model instance rather than a string id.
323
+ - AI SDK helpers and types (`tool`, `dynamicTool`, `jsonSchema`, `zodSchema`, `stepCountIs`,
324
+ `hasToolCall`, `convertToModelMessages`, message/stream/result types, etc.) are re-exported
325
+ from `@trayai/helix-sdk` so your project needs no separate `ai` dependency. The `ai`
326
+ package's own call functions (`generateText`, `streamText`, …) are **not** re-exported —
327
+ always call through `ctx.ai`.
328
+ - Generate-style calls (`generateText`, `generateObject`, `generateImage`) resolve with
329
+ `result.helix.cost` and `result.helix.requestId` alongside the AI SDK's own result fields.
330
+ `cost` is an estimate derived from the provider's reported token usage and public list
331
+ prices — an unrecognized model estimates to `0`. Most image models (e.g. `dall-e-3`) bill
332
+ per image and report no token usage at all, so `generateImage`'s cost estimates to `0` for
333
+ them regardless of whether the model is recognized; token-billed image models (e.g.
334
+ `gpt-image-1`) get a real estimate.
335
+ - Supported services: `openai`, `anthropic`, `google`, `mistral`, `cohere`, and
336
+ `openai-compatible` (self-hosted endpoints — use the object form with `baseUrl` instead of
337
+ the shorthand string). `baseUrl` must be `https:` — this is enforced when your config loads,
338
+ not just on the first call.
339
+ - An alias with no matching `aiProviders` entry throws `SdkError.aiProviderNotConfigured`,
340
+ naming the exact config line to add.
341
+ - The top-level `ctx.ai.*` functions only accept a model instance obtained from `ctx.ai(alias)`
342
+ — passing a string, or omitting `model` entirely, throws `SdkError.aiModelInstanceRequired`,
343
+ and passing a model instance built directly against a third-party AI SDK provider (bypassing
344
+ `ctx.ai`) throws `SdkError.aiForeignModelRejected`.
345
+
279
346
  ## Authentication
280
347
 
281
- Authenticated features (`ctx.http.authed`, `ctx.kv`, `ctx.files`) require you to be logged in during local development:
348
+ Authenticated features (`ctx.http.authed`, `ctx.kv`, `ctx.files`, `ctx.ai`) require you to be logged in during local development:
282
349
 
283
350
  - **Local (`helix dev`):** run `helix login` once, then `helix dev`.
284
351
  - **Deployed:** no token is needed — the platform handles credentials for you.
@@ -306,6 +373,10 @@ export default defineConfig({
306
373
  config: {
307
374
  apiVersion: '2022-06-28',
308
375
  },
376
+ aiProviders: {
377
+ // maps an authentication alias to the AI service it authenticates against
378
+ // — see AI — `ctx.ai` below
379
+ },
309
380
  });
310
381
  ```
311
382
 
@@ -1 +1 @@
1
- import{p as n,q as o,r as i,s,t as d,u,v as l}from"../chunk-KUXDW5ED.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
+ import{B as n,D as o,E as i,F as s,G as d,H as u,I as l}from"../chunk-CIHDQISD.js";async function a(e){let r=o({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),t=await s({proxyUrl:n(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},request:r,timeoutMs:e.timeoutMs??i});return t.kind==="brokerError"?{kind:"brokerError",brokerStatus:t.status,code:t.code,body:t.body}:{kind:"upstream",upstream:t.response}}async function k(e){d(e.url);let r=await l({signUrl:u(e.env,"dev"),credentialHeaders:{Authorization:`Bearer ${e.devToken}`},body:{authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},timeoutMs:e.timeoutMs});return r.kind==="brokerError"?{kind:"brokerError",brokerStatus:r.status,code:r.code,body:r.body}:{kind:"signed",signed:r.result}}export{a as callBrokerDev,k as callS3SignDev};
@@ -0,0 +1 @@
1
+ var w="X-Helix-Project-Execution-Token",b="X-Tray-Token",q={mode:"dev",deploymentId:null},E={...q},g={};function Z(e){let{internalJwt:n,helixExecutionJwt:r,devToken:t,...i}=e;"internalJwt"in e&&(g.internalJwt=n),"helixExecutionJwt"in e&&(g.helixExecutionJwt=r),"devToken"in e&&(g.devToken=t),E={...E,...i}}function ee(){return E}function S(){return g.internalJwt}function R(){return g.helixExecutionJwt}function I(){return g.devToken}var $=new Set(["production"]),l=new Map,f={name:"production",exposedName:"us1",displayName:"production",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"}};l.set(f.name,f);var P=["api","broker","ingest","weaver","app","projectHost","dashboard"],T=["auth"],N=["storePrefix","appUrl","cookieName","cookieDomain"];function U(e){if(!e.name||typeof e.name!="string")throw new Error("EnvironmentProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("EnvironmentProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("EnvironmentProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("EnvironmentProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("EnvironmentProfile.login must be an object");for(let n of P)if(typeof e.hosts[n]!="string"||!e.hosts[n])throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string`);for(let n of T){let r=e.hosts[n];if(r!==void 0&&(typeof r!="string"||!r))throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string when set`)}for(let n of N)if(typeof e.login[n]!="string"||!e.login[n])throw new Error(`EnvironmentProfile.login.${n} must be a non-empty string`)}function C(e,n){return e.name===n.name&&e.exposedName===n.exposedName&&e.displayName===n.displayName&&P.every(r=>e.hosts[r]===n.hosts[r])&&T.every(r=>e.hosts[r]===n.hosts[r])&&N.every(r=>e.login[r]===n.login[r])}function re(e){U(e);let n=l.get(e.name);if(n){if(C(n,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let r of l.values())if(r.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${r.name}"`);l.set(e.name,e)}function O(e){return l.has(e)}function te(e){return l.get(e)}function k(e){let n=l.get(e);if(!n)throw new Error(`Unknown environment: ${e}`);return n}function ie(){return[...l.keys()]}function oe(){return[...l.values()].map(e=>e.exposedName)}function j(e){for(let n of l.values())if(n.exposedName===e)return n.name}var _=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function H(e){let n=globalThis;if(e===void 0||e.trim()===""){delete n[_];return}let r=e.trim(),t=j(r);if(t){n[_]=t;return}if(O(r)){n[_]=r;return}throw new Error(`Unknown environment: ${r}`)}function se(){return globalThis[_]}function ae(){return[...l.values()].filter(e=>!$.has(e.name))}function de(){H(void 0),l.clear(),l.set(f.name,{...f,hosts:{...f.hosts},login:{...f.login}})}var u=class e extends Error{detail;constructor(n){super(F(n)),this.name="SdkError",this.detail=n}get kind(){return this.detail.kind}static unknownAlias(n,r){return new e({kind:"unknown_alias",alias:n,available:r})}static inputValidationFailed(n){return new e({kind:"input_validation_failed",fields:n})}static outputValidationFailed(n){return new e({kind:"output_validation_failed",fields:n})}static configLoadFailed(n){return new e({kind:"config_load_failed",cause:n})}static brokerError(n,r,t,i){return new e({kind:"broker_error",status:n,message:r,body:t,code:i})}static unsupportedBodyType(n){return new e({kind:"unsupported_body_type",actualType:n})}static unsupportedScheme(n){return new e({kind:"unsupported_scheme",scheme:n})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(n,r){return new e({kind:"db_call_failed",message:n,cause:r})}static dbQueryFailed(n){return new e({kind:"db_query_failed",message:n})}static dbInvalidParameters(n){return new e({kind:"db_invalid_parameters",message:n})}static kvKeyInvalid(n){return new e({kind:"kv_key_invalid",message:n})}static kvValueInvalid(n){return new e({kind:"kv_value_invalid",message:n})}static kvValueTooLarge(n,r){return new e({kind:"kv_value_too_large",message:n,maxBytes:r})}static kvTtlInvalid(n){return new e({kind:"kv_ttl_invalid",message:n})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(n,r,t){return new e({kind:"kv_call_failed",status:n,message:r,body:t})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(n){return new e({kind:"files_path_invalid",message:n})}static filesValueInvalid(n){return new e({kind:"files_value_invalid",message:n})}static filesValueTooLarge(n,r){return new e({kind:"files_value_too_large",message:n,maxBytes:r})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(n,r,t){return new e({kind:"files_call_failed",status:n,message:r,body:t})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}static callFunctionPathInvalid(n){return new e({kind:"call_function_path_invalid",message:n})}static callFunctionCallFailed(n,r,t){return new e({kind:"call_function_call_failed",status:n,message:r,body:t})}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(n,r,t){return new e({kind:"ai_unsupported_service",alias:n,service:r,supported:t})}static aiModelIdRequired(n,r){return new e({kind:"ai_model_id_required",alias:n,operation:r})}static aiModelInstanceRequired(n){return new e({kind:"ai_model_instance_required",modelId:n})}static aiProviderNotConfigured(n,r){return new e({kind:"ai_provider_not_configured",alias:n,supported:r})}static aiForeignModelRejected(){return new e({kind:"ai_foreign_model_rejected"})}};function ue(e){return e instanceof u}function F(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 p}from"zod";var D="x-helix-destination-url",A="x-helix-authentication-id",B="x-helix-deployment-id",v="x-execution-id",L="x-helix-broker-error",_e="route_not_found",J=new Set([D,A,B,"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",v]);function M(e){let n=e.toLowerCase();return J.has(n)||n.startsWith("x-tray-internal-")}var h=p.object({error:p.object({code:p.string(),message:p.string(),issues:p.array(p.unknown()).optional()})});function ke(e,n){let r=`${k(e).hosts.api}/private/v1/helix/broker/http/raw`;return n==="dev"?`${r}/dev`:r}function ve(e){if(e.mode==="lambda"){let r=S(),t=R(),i=!!(r&&r.trim().length>0),s=!!(t&&t.trim().length>0);if(!i&&!s)throw u.missingExecutionCredentials();let d={};return i&&(d[b]=r),s&&(d[w]=t),{headers:d,deploymentId:e.deploymentId??null}}let n=I();if(!n)throw u.missingTrayToken();return{headers:{Authorization:`Bearer ${n}`},deploymentId:null}}function K(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 ye(e){let n=new URL(e.url);if(n.protocol!=="https:")throw u.unsupportedScheme(n.protocol.replace(/:$/,""));if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[a,o]of e.query.entries())n.searchParams.append(a,o);else for(let[a,o]of Object.entries(e.query))for(let m of Array.isArray(o)?o:[o])n.searchParams.append(a,m);let r;e.headers===void 0?r=[]:e.headers instanceof Headers?r=Array.from(e.headers.entries()):Array.isArray(e.headers)?r=e.headers:r=Object.entries(e.headers);let t=r.filter(([a])=>!M(a)),i=e.body!==void 0&&e.body!==null,s,d,c=!1;return i&&(K(e.body)?(s=e.body,c=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(s=JSON.stringify(e.body),t.some(([o])=>o.toLowerCase()==="content-type")||(d="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:n.toString(),headers:t,body:s,isStreamBody:c,defaultContentType:d}}var V=6e4;function G(e){return e.includes("json")}function X(e){return e.startsWith("text/")||e.includes("xml")||e.includes("urlencoded")||e.includes("javascript")||e.includes("ecmascript")}function Y(e,n){if(e.byteLength===0)return;let r=n.toLowerCase();if(G(r)){let t=new TextDecoder("utf-8").decode(e);try{return JSON.parse(t)}catch{return t}}return X(r)?new TextDecoder("utf-8").decode(e):e}function z(e){let n={};for(let[r,t]of e.entries())n[r.toLowerCase()]=t;return n}async function Ee(e){let{request:n}=e,r=new Headers;for(let[a,o]of n.headers)r.append(a,o);n.defaultContentType&&!r.has("content-type")&&r.set("content-type",n.defaultContentType),r.set(D,n.destinationUrl),r.set(A,n.authenticationId);for(let[a,o]of Object.entries(e.credentialHeaders))r.set(a,o);e.executionId&&r.set(v,e.executionId);let t={method:n.method,headers:r,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??V)};n.body!==void 0&&(t.body=n.body,n.isStreamBody&&(t.duplex="half"));let i=await fetch(e.proxyUrl,t),s=i.headers.get(L);if(s!==null){let a=await i.text(),o=a,m=a||s;try{o=JSON.parse(a);let x=h.safeParse(o);x.success&&(m=x.data.error.message)}catch{}return{kind:"brokerError",status:i.status,code:s,message:m,body:o}}let d=new Uint8Array(await i.arrayBuffer()),c=i.headers.get("content-type")??"";return{kind:"upstream",response:{status:i.status,headers:z(i.headers),body:Y(d,c)}}}import{z as y}from"zod";var W=3e4;function Re(e){let n=new URL(e);if(n.protocol!=="https:")throw u.unsupportedScheme(n.protocol.replace(/:$/,""))}function Ie(e,n){let r=`${k(e).hosts.api}/private/v1/helix/broker/s3/sign`;return n==="dev"?`${r}/dev`:r}var Q=y.object({url:y.string(),method:y.string(),expiresAt:y.string()});async function Pe(e){let n=new Headers({"content-type":"application/json"});for(let[d,c]of Object.entries(e.credentialHeaders))n.set(d,c);e.executionId&&n.set(v,e.executionId);let r=await fetch(e.signUrl,{method:"POST",headers:n,body:JSON.stringify(e.body),redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??W)}),t=await r.text(),i=t;try{i=JSON.parse(t)}catch{}if(r.ok){let d=Q.safeParse(i);return d.success?{kind:"signed",result:d.data}:{kind:"brokerError",status:r.status,message:"malformed s3-sign response from credential broker",body:i}}let s=h.safeParse(i);return s.success?{kind:"brokerError",status:r.status,code:s.data.error.code,message:s.data.error.message,body:i}:{kind:"brokerError",status:r.status,message:t||`s3-sign request failed with status ${r.status}`,body:i}}export{w as a,b,Z as c,ee as d,S as e,R as f,re as g,O as h,te as i,k as j,ie as k,oe as l,j as m,H as n,se as o,ae as p,de as q,u as r,ue as s,D as t,A as u,B as v,v as w,L as x,_e as y,M as z,h as A,ke as B,ve as C,ye as D,V as E,Ee as F,Re as G,Ie as H,Pe as I};
@@ -0,0 +1,7 @@
1
+ import{A as Pt,B as Se,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 vt,o as St,r as c,t as xt,u as Et,v as ve,w as Rt,x as It,y as K,z as Ct}from"./chunk-CIHDQISD.js";var Zi="tray-config-bridge",es="tray-dev-token-bridge",xe=null;function ts(e){xe=e}function w(){if(!xe)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return xe}function rs(){xe=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().env);return new Pn({url:`${e}/v1/traces`,headers:()=>Promise.resolve(Ft())})}function Dt(){let e=Je(w().env);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 v(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":v(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,v(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]=v(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=["production"],tt=mo.string().refine(e=>wt(e),e=>({message:`Invalid enum value. Expected ${vt().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(),env:tt.default("production"),authentications:h.record(h.string()).optional().default({}),config:h.record(h.unknown()).optional().default({}),aiProviders:h.record(dr).optional()}),cr=h.object({name:h.string().min(1,"name is required"),workspaceId:ur.optional(),env: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 vo(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 So(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=St(),l=a!==void 0?{...i,env: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(vo(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 So(i.config,s)}var xo="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:xo});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(),{env:n}=w(),{headers:o,deploymentId:i}=H(r);i&&(o[ve]=i);let s=Se(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,v(a.body),a.code)}return a.response}async function hr(e){Tt(e.url);let t=b(),{env: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,v(a.body),a.code)}return a.result}var Po=["get","post","put","patch","delete","head","options"],vr="[stream body omitted]";function Sr(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?vr: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:Sr(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?xr(r,t):new Uint8Array(0)}async function xr(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",Sr(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 xr(o,ne);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:vr}}}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),S=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(),...S!==void 0?{body:S}:{}}),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):v(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=v(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),v(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",v(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.env}}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 x}from"zod";var ft=6e4,Xr=x.object({id:x.string(),workspaceId:x.string(),projectId:x.string(),parentFolder:x.string().nullable().optional(),name:x.string(),size:x.number().nullable().optional(),objectType:x.enum(["Folder","File"]),contentType:x.string().nullable().optional(),createdAt:x.string(),updatedAt:x.string()}),vi=x.object({signedURL:x.string()}),Si=x.object({path:x.array(x.object({id:x.string(),name:x.string()})),elements:x.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),v(t))}function xi(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",v(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||xi(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=Si.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",v(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=vi.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",v(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.env}}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 S=await r.getById(y.id);return Ke(i,S??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),v(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.env}}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 vn,streamObject as Sn,streamText as xn,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(),{env: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(xt,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(ve,m);let f=Se(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 S;try{S=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=S.headers.get(It);if(ee!==null){let d=await S.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(S.status,p,d||void 0,ee)}return S}}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)),S=(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=S(d,"generateText"),I=await C({operation:"generateText",model:p,alias:e},()=>vn({...d,model:l(p)}),Ve);return Object.assign(I,{helix:Z(p,Ve(I))})},streamText(d){let p=S(d,"streamText");return E("hasAi"),xn({...d,model:l(p)})},async generateObject(d){let p=S(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=S(d,"streamObject");return E("hasAi"),Sn({...d,model:l(p)})},async embed(d){let p=S(d,"embed");return C({operation:"embed",model:p,alias:e},()=>gn({...d,model:u(p)}),qe)},async embedMany(d){let p=S(d,"embedMany");return C({operation:"embedMany",model:p,alias:e},()=>yn({...d,model:u(p)}),qe)},async generateImage(d){let p=S(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=S(d,"transcribe");return C({operation:"transcribe",model:p,alias:e},()=>En({...d,model:f(p)}))},async generateSpeech(d){let p=S(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},()=>vn(n),Ve);return Object.assign(i,{helix:Z(o,Ve(i))})},streamText(n){return k(n.model),E("hasAi"),xn(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"),Sn(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,vo as I,So as J,Ys as K,xo as L,Gs as M,Iu as N,gr as O,U as P,Xs as Q,Qs as R};
@@ -1,7 +1,104 @@
1
1
  import { z } from 'zod';
2
2
 
3
+ interface SdkRuntimeConfig {
4
+ /**
5
+ * Execution mode. `"lambda"` is set via `setSdkConfig({ mode: "lambda", ... })`
6
+ * before the first handler invocation. `"dev"` is the default for `helix dev`
7
+ * and local invocations.
8
+ */
9
+ mode: "lambda" | "dev";
10
+ /**
11
+ * Execution ID for the current invocation. Set via `setSdkConfig(...)` at
12
+ * handler entry in lambda mode. In `dev` mode, define-function falls back to
13
+ * the `x-tray-execution-id` header (or a random UUID).
14
+ */
15
+ executionId?: string;
16
+ /**
17
+ * User ID for the current invocation. Set via `setSdkConfig(...)` at handler
18
+ * entry in lambda mode. In `dev` mode, define-function reads from the
19
+ * `x-tray-user-id` header.
20
+ */
21
+ userId?: string;
22
+ /**
23
+ * Deployment ID for the current invocation. Set via `setSdkConfig(...)` at
24
+ * handler entry. Only meaningful in `lambda` mode; `dev` mode has no
25
+ * deployment concept yet.
26
+ */
27
+ deploymentId?: string | null;
28
+ /**
29
+ * Running dev server's own base URL (e.g. `http://localhost:3000`). Set by
30
+ * the CLI's `sdk-context` Nitro plugin in `dev` mode so `ctx.files()` can
31
+ * build local signed URLs pointing at `/_helix/files/**`. Absent in `lambda`
32
+ * mode — production signed URLs point at the platform API host instead.
33
+ */
34
+ devServerUrl?: string;
35
+ /**
36
+ * Absolute path to the project root in `dev` mode, set by the CLI's
37
+ * `sdk-context` Nitro plugin. Used by `ctx.files()`'s local dev store to
38
+ * resolve `.helix/files/` on disk. Absent in `lambda` mode.
39
+ */
40
+ projectRoot?: string;
41
+ /**
42
+ * The calling execution's id, set via `setSdkConfig(...)` only for a
43
+ * function-call-triggered invocation (`ctx.callFunctionAsync`, SUR-929).
44
+ * The shim explicitly clears this (passes `undefined`) on every other
45
+ * invocation kind so a warm container never leaks a prior call's parentage.
46
+ */
47
+ parentExecutionId?: string | null;
48
+ }
49
+ interface BrokerSecrets {
50
+ internalJwt?: string;
51
+ helixExecutionJwt?: string;
52
+ devToken?: string;
53
+ }
54
+ interface SdkConfigInput extends Partial<SdkRuntimeConfig>, BrokerSecrets {
55
+ }
56
+ declare function setSdkConfig(options: SdkConfigInput): void;
57
+ declare function getSdkConfig(): Readonly<SdkRuntimeConfig>;
58
+
3
59
  declare const projectIdSchema: z.ZodString;
4
60
  declare const workspaceIdSchema: z.ZodString;
61
+ /**
62
+ * AI provider declaration (helix-spec 11). The Vercel AI SDK builds
63
+ * provider-native requests client-side, so `ctx.ai(alias)` must know which
64
+ * `@ai-sdk/*` package serves the alias BEFORE any request exists — and
65
+ * platform authentications carry no service identifier, so the project
66
+ * declares it here: `aiProviders: { <authAlias>: "<service>" }`. The
67
+ * `openai-compatible` service (self-hosted vLLM, Ollama, …) additionally
68
+ * needs the endpoint base URL, so it uses the object form.
69
+ *
70
+ * `baseUrl` must be https: every `ctx.ai` request egresses through the
71
+ * credentials broker's raw forward proxy, and `createBrokerFetch` rejects
72
+ * non-https destinations unconditionally (no dev/local exception) — so an
73
+ * http endpoint (a bare local Ollama/vLLM instance, say) would load fine here
74
+ * and then fail on every request. Catching it in the schema turns that into
75
+ * one clear config error instead of a confusing first-call failure.
76
+ */
77
+ declare const AI_SERVICES: readonly ["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"];
78
+ type AiService = (typeof AI_SERVICES)[number];
79
+ declare const aiProviderEntrySchema: z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
80
+ service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
81
+ baseUrl: z.ZodOptional<z.ZodString>;
82
+ }, "strip", z.ZodTypeAny, {
83
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
84
+ baseUrl?: string | undefined;
85
+ }, {
86
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
87
+ baseUrl?: string | undefined;
88
+ }>, {
89
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
90
+ baseUrl?: string | undefined;
91
+ }, {
92
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
93
+ baseUrl?: string | undefined;
94
+ }>, {
95
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
96
+ baseUrl?: string | undefined;
97
+ }, {
98
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
99
+ baseUrl?: string | undefined;
100
+ }>]>;
101
+ type AiProviderEntry = z.infer<typeof aiProviderEntrySchema>;
5
102
  declare const trayConfigSchema: z.ZodObject<{
6
103
  name: z.ZodString;
7
104
  projectId: z.ZodOptional<z.ZodString>;
@@ -9,6 +106,28 @@ declare const trayConfigSchema: z.ZodObject<{
9
106
  env: z.ZodDefault<z.ZodEffects<z.ZodString, string, string>>;
10
107
  authentications: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
11
108
  config: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
109
+ aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
110
+ service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
111
+ baseUrl: z.ZodOptional<z.ZodString>;
112
+ }, "strip", z.ZodTypeAny, {
113
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
114
+ baseUrl?: string | undefined;
115
+ }, {
116
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
117
+ baseUrl?: string | undefined;
118
+ }>, {
119
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
120
+ baseUrl?: string | undefined;
121
+ }, {
122
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
123
+ baseUrl?: string | undefined;
124
+ }>, {
125
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
126
+ baseUrl?: string | undefined;
127
+ }, {
128
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
129
+ baseUrl?: string | undefined;
130
+ }>]>>>;
12
131
  }, "strip", z.ZodTypeAny, {
13
132
  name: string;
14
133
  env: string;
@@ -16,6 +135,10 @@ declare const trayConfigSchema: z.ZodObject<{
16
135
  config: Record<string, unknown>;
17
136
  projectId?: string | undefined;
18
137
  workspaceId?: string | undefined;
138
+ aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
139
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
140
+ baseUrl?: string | undefined;
141
+ }> | undefined;
19
142
  }, {
20
143
  name: string;
21
144
  projectId?: string | undefined;
@@ -23,6 +146,10 @@ declare const trayConfigSchema: z.ZodObject<{
23
146
  env?: string | undefined;
24
147
  authentications?: Record<string, string> | undefined;
25
148
  config?: Record<string, unknown> | undefined;
149
+ aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
150
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
151
+ baseUrl?: string | undefined;
152
+ }> | undefined;
26
153
  }>;
27
154
  /** User-facing config type — auth/config optional; Zod defaults fill at load time. */
28
155
  type TrayConfig = z.input<typeof trayConfigSchema>;
@@ -38,6 +165,28 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
38
165
  env: z.ZodEffects<z.ZodString, string, string>;
39
166
  authentications: z.ZodRecord<z.ZodString, z.ZodString>;
40
167
  config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
168
+ aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
169
+ service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
170
+ baseUrl: z.ZodOptional<z.ZodString>;
171
+ }, "strip", z.ZodTypeAny, {
172
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
173
+ baseUrl?: string | undefined;
174
+ }, {
175
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
176
+ baseUrl?: string | undefined;
177
+ }>, {
178
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
179
+ baseUrl?: string | undefined;
180
+ }, {
181
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
182
+ baseUrl?: string | undefined;
183
+ }>, {
184
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
185
+ baseUrl?: string | undefined;
186
+ }, {
187
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
188
+ baseUrl?: string | undefined;
189
+ }>]>>>;
41
190
  } & {
42
191
  kind: z.ZodLiteral<"provisioned">;
43
192
  projectId: z.ZodString;
@@ -49,6 +198,10 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
49
198
  authentications: Record<string, string>;
50
199
  config: Record<string, unknown>;
51
200
  workspaceId?: string | undefined;
201
+ aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
202
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
203
+ baseUrl?: string | undefined;
204
+ }> | undefined;
52
205
  }, {
53
206
  kind: "provisioned";
54
207
  name: string;
@@ -57,12 +210,38 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
57
210
  authentications: Record<string, string>;
58
211
  config: Record<string, unknown>;
59
212
  workspaceId?: string | undefined;
213
+ aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
214
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
215
+ baseUrl?: string | undefined;
216
+ }> | undefined;
60
217
  }>, z.ZodObject<{
61
218
  name: z.ZodString;
62
219
  workspaceId: z.ZodOptional<z.ZodString>;
63
220
  env: z.ZodEffects<z.ZodString, string, string>;
64
221
  authentications: z.ZodRecord<z.ZodString, z.ZodString>;
65
222
  config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
223
+ aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
224
+ service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
225
+ baseUrl: z.ZodOptional<z.ZodString>;
226
+ }, "strip", z.ZodTypeAny, {
227
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
228
+ baseUrl?: string | undefined;
229
+ }, {
230
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
231
+ baseUrl?: string | undefined;
232
+ }>, {
233
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
234
+ baseUrl?: string | undefined;
235
+ }, {
236
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
237
+ baseUrl?: string | undefined;
238
+ }>, {
239
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
240
+ baseUrl?: string | undefined;
241
+ }, {
242
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
243
+ baseUrl?: string | undefined;
244
+ }>]>>>;
66
245
  } & {
67
246
  kind: z.ZodLiteral<"unprovisioned">;
68
247
  }, "strip", z.ZodTypeAny, {
@@ -72,6 +251,10 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
72
251
  authentications: Record<string, string>;
73
252
  config: Record<string, unknown>;
74
253
  workspaceId?: string | undefined;
254
+ aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
255
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
256
+ baseUrl?: string | undefined;
257
+ }> | undefined;
75
258
  }, {
76
259
  kind: "unprovisioned";
77
260
  name: string;
@@ -79,6 +262,10 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
79
262
  authentications: Record<string, string>;
80
263
  config: Record<string, unknown>;
81
264
  workspaceId?: string | undefined;
265
+ aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
266
+ service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
267
+ baseUrl?: string | undefined;
268
+ }> | undefined;
82
269
  }>]>;
83
270
  /** Base fields on all config variants — schema output minus projectId. */
84
271
  type LoadedTrayConfigBase = Omit<z.output<typeof trayConfigSchema>, "projectId">;
@@ -158,60 +345,4 @@ type WorkspaceIdRequiredError = Error & {
158
345
  */
159
346
  declare function requireWorkspaceId(config: LoadedTrayConfig): string;
160
347
 
161
- interface SdkRuntimeConfig {
162
- /**
163
- * Execution mode. `"lambda"` is set via `setSdkConfig({ mode: "lambda", ... })`
164
- * before the first handler invocation. `"dev"` is the default for `helix dev`
165
- * and local invocations.
166
- */
167
- mode: "lambda" | "dev";
168
- /**
169
- * Execution ID for the current invocation. Set via `setSdkConfig(...)` at
170
- * handler entry in lambda mode. In `dev` mode, define-function falls back to
171
- * the `x-tray-execution-id` header (or a random UUID).
172
- */
173
- executionId?: string;
174
- /**
175
- * User ID for the current invocation. Set via `setSdkConfig(...)` at handler
176
- * entry in lambda mode. In `dev` mode, define-function reads from the
177
- * `x-tray-user-id` header.
178
- */
179
- userId?: string;
180
- /**
181
- * Deployment ID for the current invocation. Set via `setSdkConfig(...)` at
182
- * handler entry. Only meaningful in `lambda` mode; `dev` mode has no
183
- * deployment concept yet.
184
- */
185
- deploymentId?: string | null;
186
- /**
187
- * Running dev server's own base URL (e.g. `http://localhost:3000`). Set by
188
- * the CLI's `sdk-context` Nitro plugin in `dev` mode so `ctx.files()` can
189
- * build local signed URLs pointing at `/_helix/files/**`. Absent in `lambda`
190
- * mode — production signed URLs point at the platform API host instead.
191
- */
192
- devServerUrl?: string;
193
- /**
194
- * Absolute path to the project root in `dev` mode, set by the CLI's
195
- * `sdk-context` Nitro plugin. Used by `ctx.files()`'s local dev store to
196
- * resolve `.helix/files/` on disk. Absent in `lambda` mode.
197
- */
198
- projectRoot?: string;
199
- /**
200
- * The calling execution's id, set via `setSdkConfig(...)` only for a
201
- * function-call-triggered invocation (`ctx.callFunctionAsync`, SUR-929).
202
- * The shim explicitly clears this (passes `undefined`) on every other
203
- * invocation kind so a warm container never leaks a prior call's parentage.
204
- */
205
- parentExecutionId?: string | null;
206
- }
207
- interface BrokerSecrets {
208
- internalJwt?: string;
209
- helixExecutionJwt?: string;
210
- devToken?: string;
211
- }
212
- interface SdkConfigInput extends Partial<SdkRuntimeConfig>, BrokerSecrets {
213
- }
214
- declare function setSdkConfig(options: SdkConfigInput): void;
215
- declare function getSdkConfig(): Readonly<SdkRuntimeConfig>;
216
-
217
- export { type ConfigFileOptions as C, HELIX_CONFIG_ENV as H, type LoadedTrayConfig as L, type ProvisionedTrayConfig as P, type SdkRuntimeConfig as S, type TrayConfig as T, type UnprovisionedTrayConfig as U, type WatchErrorPhase as W, WORKSPACE_ID_REQUIRED_CODE as a, type WorkspaceIdRequiredError as b, loadedTrayConfigSchema as c, resolveConfigFile as d, resolveConfigOverride as e, type SdkConfigInput as f, getSdkConfig as g, loadConfig as l, projectIdSchema as p, requireWorkspaceId as r, setSdkConfig as s, workspaceIdSchema as w };
348
+ export { AI_SERVICES as A, type ConfigFileOptions as C, HELIX_CONFIG_ENV as H, type LoadedTrayConfig as L, type ProvisionedTrayConfig as P, type SdkRuntimeConfig as S, type TrayConfig as T, type UnprovisionedTrayConfig as U, type WatchErrorPhase as W, type AiProviderEntry as a, type AiService as b, WORKSPACE_ID_REQUIRED_CODE as c, type WorkspaceIdRequiredError as d, aiProviderEntrySchema as e, loadedTrayConfigSchema as f, getSdkConfig as g, resolveConfigFile as h, resolveConfigOverride as i, type SdkConfigInput as j, loadConfig as l, projectIdSchema as p, requireWorkspaceId as r, setSdkConfig as s, workspaceIdSchema as w };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import * as h3 from 'h3';
2
2
  import { ZodType } from 'zod';
3
- import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-DoNQWbb9.js';
4
- export { B as BrokerAuthedClient, b as BrokerCallOptions, c as BrokerCallResult, C as CallFunctionAsync, d as DbCallParameters, e as DbClient, f as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, g as S3SignOptions, h as S3SignResult, i as ScheduleContext, j as ScheduleHandler, k as ScheduleTrigger, l as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-DoNQWbb9.js';
5
- import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './sdk-config-DU6cWbLW.js';
6
- export { C as ConfigFileOptions, H as HELIX_CONFIG_ENV, P as ProvisionedTrayConfig, S as SdkRuntimeConfig, U as UnprovisionedTrayConfig, a as WORKSPACE_ID_REQUIRED_CODE, b as WorkspaceIdRequiredError, g as getSdkConfig, l as loadConfig, c as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, d as resolveConfigFile, e as resolveConfigOverride, w as workspaceIdSchema } from './sdk-config-DU6cWbLW.js';
3
+ import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-B9ZTUx-H.js';
4
+ export { A as AiEmbeddingModelInstance, b as AiImageModelInstance, c as AiLanguageModelInstance, d as AiSpeechModelInstance, e as AiTranscriptionModelInstance, B as BrokerAuthedClient, f as BrokerCallOptions, g as BrokerCallResult, C as CallFunctionAsync, h as DbCallParameters, i as DbClient, j as FileSystemClient, H as HelixAI, k as HelixAIProvider, l as HelixCost, m as HelixResultMeta, n as HttpClient, K as KeyValueStore, L as Logger, o as S3SignOptions, p as S3SignResult, q as ScheduleContext, r as ScheduleHandler, s as ScheduleTrigger, t as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-B9ZTUx-H.js';
5
+ import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './config-loader-CavQGiQ0.js';
6
+ export { A as AI_SERVICES, a as AiProviderEntry, b as AiService, C as ConfigFileOptions, H as HELIX_CONFIG_ENV, P as ProvisionedTrayConfig, S as SdkRuntimeConfig, U as UnprovisionedTrayConfig, c as WORKSPACE_ID_REQUIRED_CODE, d as WorkspaceIdRequiredError, e as aiProviderEntrySchema, g as getSdkConfig, l as loadConfig, f as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, h as resolveConfigFile, i as resolveConfigOverride, w as workspaceIdSchema } from './config-loader-CavQGiQ0.js';
7
7
  export { a as ENVIRONMENT_VALUES, E as Environment, e as environmentSchema } from './env-schema-DkgTG5b0.js';
8
+ export { EmbedManyResult, EmbedResult, EmbeddingModel, FinishReason, GenerateImageResult, GenerateObjectResult, GenerateTextResult, ImageModel, LanguageModel, LanguageModelUsage, ModelMessage, Output, PrepareStepFunction, SpeechModel, SpeechResult, StopCondition, StreamObjectResult, StreamTextResult, TextStreamPart, ToolChoice, ToolSet, TranscriptionModel, TranscriptionResult, UIMessage, convertToModelMessages, cosineSimilarity, dynamicTool, hasToolCall, jsonSchema, smoothStream, stepCountIs, tool, zodSchema } from 'ai';
8
9
  import 'ky';
10
+ import '@ai-sdk/provider';
9
11
 
10
12
  declare function defineFunction<TInput extends ZodType | undefined = undefined, TOutput extends ZodType | undefined = undefined>(handler: FunctionHandler<TInput extends ZodType ? ReturnType<TInput["parse"]> : Record<string, unknown>>, schemaOrOptions?: ZodType | DefineFunctionOptions<TInput, TOutput>): h3.EventHandler<h3.EventHandlerRequest, Promise<unknown>>;
11
13
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{A as ke,B as Se,C as xe,D as _e,b as R,h as M,i as F,j as Z,k as E,l as B,m as K,n as V,o as z,p as Ee,q as J,r as Q,s as Y,t as ee,u as te,y as re,z as ne}from"./chunk-QWCCRTLO.js";import{a as G,b as we}from"./chunk-WUCX7RZO.js";import{b as U,e as $,i as q,l as g,m as X}from"./chunk-KUXDW5ED.js";import{randomUUID as je}from"crypto";import{SpanStatusCode as de,SpanKind as De}from"@opentelemetry/api";import{defineEventHandler as Ae,getMethod as He,getRequestURL as We,getHeaders as ue,getHeader as ce}from"h3";import{readBody as Ie,getQuery as be,getRouterParams as Te}from"h3";async function oe(e,t){let r=await Re(e),n=be(e),o=Te(e)??{},i={...n,...r,...o};return t?Fe(i,t):i}async function Re(e){try{let t=await Ie(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 Fe(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 w=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function ie(e){return t=>{e.node.res.statusCode=t}}function se(){return(e,t)=>{throw new w(e,t)}}function ae(e,t){let{statusCode:r,message:n}=Pe(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Pe(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"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Le=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Oe(e){return e.toLowerCase().includes("tray_lid")}function P(e){let t={};for(let[r,n]of Object.entries(e))if(!Le.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(i=>i.trim()).filter(i=>{let d=i.split("=")[0].trim();return!Oe(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ne(e,t){let{inputSchema:r,outputSchema:n}=Be(t),o=e;return Ae(async i=>{let d=R(),{executionId:s,userId:a,deploymentId:f}=Ke(d,i),l=d.mode==="lambda"?d.parentExecutionId??null:null,y=Date.now(),S=new Date().toISOString(),p=He(i),u=We(i).pathname,C=Q(),v=J(),Ce=`${p} ${u}`;B();let N={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return Ue(()=>F.run(N,()=>M.run(s,async()=>{let x=await $e(i,r);if(!x.ok)return{response:x.response,errored:!1,errorMessage:null};let ve=ze(i,x.input,C,v,p,u,s,f,a,l);return qe(o,ve,n,i,v,s,f,{method:p,path:u,rawInput:x.input})})),{executionId:s,deploymentId:f,routeOrJob:Ce,startedAt:S,startMs:y,userId:a,flags:N})})}async function Ue(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{z({...t,errored:r,errorMessage:n}),await K()}}async function $e(e,t){try{return{ok:!0,input:await oe(e,t)}}catch(r){let n=Ve(e,r);if(n)return{ok:!1,response:n};throw r}}async function qe(e,t,r,n,o,i,d,s){return V.startActiveSpan("function",{root:!0,kind:De.SERVER,attributes:{method:s.method,route:s.path,executionId:i,...d?{deploymentId:d}:{}}},async a=>{t.traceId=a.spanContext().traceId;let f=P(ue(n));E(a,"input",s.rawInput),E(a,"request",{method:s.method,path:s.path,headers:f,body:s.rawInput});let l=!1,y=null,S,p;try{let u=await G.run(t,()=>e(t));if(S=u,u==null)n.node.res.statusCode=204,p="";else if(u instanceof Response)p=u;else if(r){let C=r.safeParse(u);if(!C.success){let v=Object.keys(C.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:v,executionId:i}),g.outputValidationFailed(v)}p=C.data}else p=u}catch(u){l=!0,y=u instanceof Error?u.message:String(u),Z("hasError"),p=Me(u,n,o,i)}finally{Ze(a,n,{errored:l,errorMessage:y,handlerResult:S,response:p})}return{response:p,errored:l,errorMessage:y}})}function Me(e,t,r,n){if(e instanceof w)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(X(e))return ae(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 Ze(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&E(e,"output",r.handlerResult),E(e,"response",r.response);let n=F.getStore();e.setAttribute("hasAuth",n?.hasAuth??!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?de.ERROR:de.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Be(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 Ke(e,t){let r=e.mode==="lambda",n=(r?e.executionId:ce(t,"x-tray-execution-id"))??je(),o=(r?e.userId:ce(t,"x-tray-user-id"))??null,i=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:i}}function Ve(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 ze(e,t,r,n,o,i,d,s,a,f){return{input:t,method:o,path:i,headers:P(ue(e)),http:Y(),db:l=>ee(l),kv:()=>te(),files:()=>re(),callFunctionAsync:ne(),log:n,config:r,status:ie(e),error:se(),state:{},request:e,executionId:d,deploymentId:s,userId:a,parentExecutionId:f,identity:a!==null?{user:{id:a}}:null,traceId:""}}function Ge(e){return e}import{resolve as m}from"path";import{existsSync as I,realpathSync as fe}from"fs";import{loadConfig as Xe}from"c12";import{z as c}from"zod";import{z as Je}from"zod";var Qe=["production"],_=Je.string().refine(e=>U(e),e=>({message:`Invalid enum value. Expected ${$().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var L=c.string().uuid("projectId must be a valid UUID"),O=c.string().min(1,"workspaceId must be a non-empty string"),Ye=c.object({name:c.string().min(1,"name is required"),projectId:L.optional(),workspaceId:O.optional(),env:_.default("production"),authentications:c.record(c.string()).optional().default({}),config:c.record(c.unknown()).optional().default({})}),le=c.object({name:c.string().min(1,"name is required"),workspaceId:O.optional(),env:_,authentications:c.record(c.string()),config:c.record(c.unknown())}),et=c.discriminatedUnion("kind",[le.extend({kind:c.literal("provisioned"),projectId:L}),le.extend({kind:c.literal("unprovisioned")})]),pe=["helix","tray"],ge=["ts","mts","cts","js","mjs","cjs"],j="HELIX_CONFIG";function h(e){let t=e?.trim();return t||process.env[j]?.trim()||void 0}function b(e,t){let r=h(t?.configFile);if(r!==void 0){let n=m(e,r);return I(n)?n:void 0}for(let n of pe)for(let o of ge){let i=m(e,`${n}.config.${o}`);if(I(i))return i}}function tt(e){for(let t of pe)if(ge.some(r=>I(m(e,`${t}.config.${r}`))))return t;return"helix"}function rt(e,t){return m(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function D(e,t){let r=h(t?.configFile);return{name:tt(e),cwd:e,...r!==void 0?{configFile:rt(e,r)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function A(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw g.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=Ye.safeParse(e);if(!r.success){let f=r.error.issues.map(l=>l.message).join("; ");throw g.configLoadFailed(`Invalid helix.config.ts at ${t}: ${f}`)}let{projectId:n,workspaceId:o,...i}=r.data,d=o!==void 0?{workspaceId:o}:{},s=q(),a=s!==void 0?{...i,env:s}:i;return n!==void 0?{kind:"provisioned",projectId:n,...a,...d}:{kind:"unprovisioned",...a,...d}}async function k(e,t){let r=e??process.cwd(),n=h(t?.configFile),o=n!==void 0?m(r,n):void 0;if(o!==void 0&&!I(o)){let s=t?.configFile?.trim()?"":` (from ${j})`;throw g.configLoadFailed(`Config file not found: ${o}${s}`)}let i;try{i=await Xe(D(r,t))}catch(s){throw g.configLoadFailed(`Failed to load helix.config.ts: ${s instanceof Error?s.message:String(s)}`)}let d=i._configFile??b(r,t);if(!d)throw g.configLoadFailed(`helix.config.ts not found at ${m(r,"helix.config.ts")}`);if(o!==void 0&&i._configFile!==void 0){let s=fe(o);if(fe(m(i._configFile))!==s)throw g.configLoadFailed(`Config file conflict: requested ${o} but ${m(i._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return A(i.config,d)}var me="WORKSPACE_ID_REQUIRED";function nt(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:me});return e.workspaceId}import{existsSync as ot,watch as it,writeSync as st}from"fs";import{basename as at,dirname as dt,join as ct,resolve as T}from"path";import{watchConfig as ut}from"c12";function ft(e,t){let r=e instanceof Error?e.message:String(e);st(2,`[helix-watch] ${t.phase} error: ${r}
2
- `)}function H(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var lt=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,he=new Set;function ye(e,t){return b(e,{configFile:t})!==void 0}async function pt(e,t,r){if(ye(e.cwd,t))try{return{current:await k(e.cwd,{configFile:t}),initialLoadSucceeded:!0}}catch(n){return r(n,{phase:"reload"}),{current:H(),initialLoadSucceeded:!1}}if(e.watch){let n=t!==void 0?T(e.cwd,t):T(e.cwd);he.has(n)||(process.stderr.write(t!==void 0?`warning: config file ${T(e.cwd,t)} not found; tray running with default config
1
+ import{A as ce,B as le,C as fe,D as pe,E as me,F as ge,G as _,H as x,I as K,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 M,n as ae,o as j,p as D,q,r as Z,s as N,w as V,x as $,y as de,z as ue}from"./chunk-RB3QC3LX.js";import{a as O,b as ie}from"./chunk-WUCX7RZO.js";import{d as E,r as W,s as U}from"./chunk-CIHDQISD.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 Me(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,m=D(),g=j(),oe=`${c} ${u}`;H();let R={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1};return Oe(()=>k.run(R,()=>P.run(i,async()=>{let w=await je(s,r);if(!w.ok)return{response:w.response,errored:!1,errorMessage:null};let se=Ve(s,w.input,m,g,c,u,i,l,a,f);return De(o,se,n,s,g,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 Oe(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{M({...t,errored:r,errorMessage:n}),await F()}}async function je(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 O.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 m=r.safeParse(u);if(!m.success){let g=Object.keys(m.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:g,executionId:s}),W.outputValidationFailed(g)}c=m.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 Ve(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:()=>V(),callFunctionAsync:$(),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 $e(e){return e}import{existsSync as Ke,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
+ `)}function T(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}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
- `),he.add(n))}return{current:H(),initialLoadSucceeded:!1}}var W=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=ut({...D(this.cwd,{configFile:this.configFile}),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=A(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,i)=>{n.once("ready",o),n.once("error",i)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){let t=this.configFile!==void 0?T(this.cwd,this.configFile):void 0,r=t!==void 0?dt(t):this.cwd;try{this.directoryWatcher=it(r,{persistent:!1},(n,o)=>{if(this.stopped||!o)return;let i=o.toString();if(t!==void 0){if(i!==at(t))return}else if(!lt.test(i))return;ot(ct(r,i))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let d;try{d=await k(this.cwd,{configFile:this.configFile})}catch(a){this.onError(a,{phase:"reload"});return}if(this.stopped)return;this.emit(d);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",n=>{this.onError(n,{phase:"attach"})})}catch(n){this.onError(n,{phase:"attach"})}}};async function gt(e){let t=e.onError??ft,r=new Set,n=h(e.configFile),o=await pt(e,n,t),i=o.current;function d(a){i=a;for(let f of[...r])try{f(a)}catch(l){t(l,{phase:"reload"})}}let s=new W(e.cwd,n,t,d);return e.watch&&s.start(o.initialLoadSucceeded),{get(){return i},async reload(){if(!ye(e.cwd,n)){let a=H();return d(a),a}try{let a=await k(e.cwd,{configFile:n});return d(a),a}catch(a){return t(a,{phase:"reload"}),i}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await s.stop()},ready(){return s.watcherReady()}}}export{Qe as ENVIRONMENT_VALUES,j as HELIX_CONFIG_ENV,ke as SCHEDULE_DEFINITION_KIND,Se as ScheduleConfigError,me as WORKSPACE_ID_REQUIRED_CODE,gt as createConfigService,Ge as defineConfig,Ne as defineFunction,xe as defineSchedule,_ as environmentSchema,we as getContext,R as getSdkConfig,_e as isScheduleDefinition,k as loadConfig,et as loadedTrayConfigSchema,L as projectIdSchema,nt as requireWorkspaceId,b as resolveConfigFile,h as resolveConfigOverride,Ee as runWithinAppSpan,O as workspaceIdSchema};
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({...K(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;Ke(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 Kt,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,de as ENVIRONMENT_VALUES,ge as HELIX_CONFIG_ENV,tr as Output,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,$e as defineConfig,Me as defineFunction,we as defineSchedule,zt as dynamicTool,ue as environmentSchema,ie as getContext,E as getSdkConfig,Qt as hasToolCall,Se as isScheduleDefinition,Bt as jsonSchema,y as loadConfig,me as loadedTrayConfigSchema,ce as projectIdSchema,ye as requireWorkspaceId,x as resolveConfigFile,_ as resolveConfigOverride,ae as runWithinAppSpan,er as smoothStream,Jt as stepCountIs,Kt as tool,le as workspaceIdSchema,Gt as zodSchema};
@@ -1,5 +1,5 @@
1
- import { L as LoadedTrayConfig } from '../sdk-config-DU6cWbLW.js';
2
- export { f as SdkConfigInput, s as setSdkConfig } from '../sdk-config-DU6cWbLW.js';
1
+ import { L as LoadedTrayConfig } from '../config-loader-CavQGiQ0.js';
2
+ export { j as SdkConfigInput, s as setSdkConfig } from '../config-loader-CavQGiQ0.js';
3
3
  import 'zod';
4
4
 
5
5
  /** BroadcastChannel name for parent→worker config updates. */
@@ -140,6 +140,24 @@ type SdkErrorDetail = {
140
140
  readonly kind: "call_function_not_available";
141
141
  } | {
142
142
  readonly kind: "call_function_missing_execution_jwt";
143
+ } | {
144
+ readonly kind: "ai_unsupported_service";
145
+ alias: string;
146
+ service: string;
147
+ supported: string[];
148
+ } | {
149
+ readonly kind: "ai_model_id_required";
150
+ alias: string;
151
+ operation: string;
152
+ } | {
153
+ readonly kind: "ai_model_instance_required";
154
+ modelId: string;
155
+ } | {
156
+ readonly kind: "ai_provider_not_configured";
157
+ alias: string;
158
+ supported: string[];
159
+ } | {
160
+ readonly kind: "ai_foreign_model_rejected";
143
161
  };
144
162
  declare class SdkError extends Error {
145
163
  readonly detail: SdkErrorDetail;
@@ -175,6 +193,11 @@ declare class SdkError extends Error {
175
193
  static callFunctionRequiresProvisioning(): SdkError;
176
194
  static callFunctionNotAvailable(): SdkError;
177
195
  static callFunctionMissingExecutionJwt(): SdkError;
196
+ static aiUnsupportedService(alias: string, service: string, supported: string[]): SdkError;
197
+ static aiModelIdRequired(alias: string, operation: string): SdkError;
198
+ static aiModelInstanceRequired(modelId: string): SdkError;
199
+ static aiProviderNotConfigured(alias: string, supported: string[]): SdkError;
200
+ static aiForeignModelRejected(): SdkError;
178
201
  }
179
202
  declare function isSdkError(err: unknown): err is SdkError;
180
203
 
@@ -1 +1 @@
1
- import{D as P,a as L,b as m,c as T,d as G,e as J,f as U,g as V,h,i as p,j as g,k as E,l as S,m as y,n as x,o as A,q as I,r as w,s as C,t as v,u as D,v as nt,w as st,x as it,y as F,z as N}from"../chunk-QWCCRTLO.js";import{a as b}from"../chunk-WUCX7RZO.js";import{a as B,b as q,c as z,d as Q,e as W,f as X,g as Y,h as Z,i as tt,j as et,k as rt,m as ot}from"../chunk-KUXDW5ED.js";import{randomUUID as at}from"crypto";import{SpanStatusCode as O,SpanKind as lt}from"@opentelemetry/api";var e=class extends Error{constructor(t){super(`runScheduledFunction: ${t}`),this.name="ScheduleInvocationError"}};async function ct(s,t){if(typeof t!="object"||t===null)throw new e("`invocation` must be an object");let{schedulePath:r}=t;if(typeof r!="string"||r.length===0)throw new e("`schedulePath` must be a non-empty string");if(typeof t.isManual!="boolean")throw new e("`isManual` must be a boolean");if(!P(s))throw new e(`default export of "${r}" is not a defineSchedule definition`);let M=k("scheduledAt",t.scheduledAt),R=k("firedAt",t.firedAt),d=m(),a=d.executionId??at(),l=d.deploymentId??null,j=Date.now(),$=new Date().toISOString(),K=w(),_=I();S();let i={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1},c=!1,u=null;try{await p.run(i,()=>h.run(a,()=>x.startActiveSpan("schedule",{root:!0,kind:lt.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:a,...l?{deploymentId:l}:{}}},async o=>{let H={type:"schedule",scheduledAt:M,firedAt:R,isManual:t.isManual},f={http:C(),db:n=>v(n),kv:()=>D(),files:()=>F(),callFunctionAsync:N(),log:_,config:K,state:{},executionId:a,deploymentId:l,traceId:o.spanContext().traceId,parentExecutionId:null,trigger:H};E(o,"input",{scheduledAt:t.scheduledAt,firedAt:t.firedAt,isManual:t.isManual});try{await b.run(f,()=>s.handler(f))}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),g("hasError"),n}finally{o.setAttribute("hasAuth",i.hasAuth),o.setAttribute("hasExternal",i.hasExternal),o.setAttribute("hasDb",i.hasDb),o.setAttribute("status",c?"error":"success");let n=c||i.hasError;o.setStatus({code:n?O.ERROR:O.OK,...u?{message:u}:{}}),o.end()}})))}finally{A({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:r,startedAt:$,startMs:j,errored:c,errorMessage:u,userId:null,flags:i}),await y()}}function k(s,t){if(typeof t!="string"||t.length===0)throw new e(`\`${s}\` must be a timestamp string; got ${JSON.stringify(t)}`);let r=new Date(t);if(Number.isNaN(r.getTime()))throw new e(`\`${s}\` must be a Date-parseable timestamp; got ${JSON.stringify(t)}`);return r}export{T as CONFIG_BRIDGE_CHANNEL,G as DEV_TOKEN_BRIDGE_CHANNEL,e as ScheduleInvocationError,nt as assertValidPath,V as clearActiveConfig,st as contentFilePath,U as getActiveConfig,et as getAdditionalEnvironmentProfiles,z as getEnvironmentProfile,q as isKnownEnvironment,ot as isSdkError,W as listEnvironmentNames,X as listExposedEnvNames,it as metaFilePath,Y as parseExposedEnvironment,B as registerEnvironmentProfile,Q as requireEnvironmentProfile,rt as resetEnvironmentRegistryForTests,tt as resolveForcedEnvironment,ct as runScheduledFunction,J as setActiveConfig,Z as setForcedEnvironment,L as setSdkConfig};
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 h,g as p,h as g,i as E,j as S,k as A,l as x,m as y,o as I,p as w,q as C,r as v,s as D,t as st,u as it,v as at,w as F,x as N}from"../chunk-RB3QC3LX.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 tt,o as et,p as rt,q as ot,s as nt}from"../chunk-CIHDQISD.js";import{randomUUID as lt}from"crypto";import{SpanStatusCode as k,SpanKind as ct}from"@opentelemetry/api";var r=class extends Error{constructor(t){super(`runScheduledFunction: ${t}`),this.name="ScheduleInvocationError"}};async function ut(i,t){if(typeof t!="object"||t===null)throw new r("`invocation` must be an object");let{schedulePath:o}=t;if(typeof o!="string"||o.length===0)throw new r("`schedulePath` must be a non-empty string");if(typeof t.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 R=M("scheduledAt",t.scheduledAt),j=M("firedAt",t.firedAt),d=m(),a=d.executionId??lt(),l=d.deploymentId??null,$=Date.now(),H=new Date().toISOString(),K=w(),_=I();S();let s={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1},c=!1,u=null;try{await p.run(s,()=>h.run(a,()=>x.startActiveSpan("schedule",{root:!0,kind:ct.SERVER,attributes:{method:"SCHEDULE",route:o,executionId:a,...l?{deploymentId:l}:{}}},async e=>{let L={type:"schedule",scheduledAt:R,firedAt:j,isManual:t.isManual},f={http:C(),db:n=>v(n),kv:()=>D(),files:()=>F(),callFunctionAsync:N(),ai:P(),log:_,config:K,state:{},executionId:a,deploymentId:l,traceId:e.spanContext().traceId,parentExecutionId:null,trigger:L};E(e,"input",{scheduledAt:t.scheduledAt,firedAt:t.firedAt,isManual:t.isManual});try{await b.run(f,()=>i.handler(f))}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),g("hasError"),n}finally{e.setAttribute("hasAuth",s.hasAuth),e.setAttribute("hasAi",s.hasAi),e.setAttribute("hasExternal",s.hasExternal),e.setAttribute("hasDb",s.hasDb),e.setAttribute("status",c?"error":"success");let n=c||s.hasError;e.setStatus({code:n?k.ERROR:k.OK,...u?{message:u}:{}}),e.end()}})))}finally{y({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:o,startedAt:H,startMs:$,errored:c,errorMessage:u,userId:null,flags:s}),await A()}}function M(i,t){if(typeof t!="string"||t.length===0)throw new r(`\`${i}\` must be a timestamp string; got ${JSON.stringify(t)}`);let o=new Date(t);if(Number.isNaN(o.getTime()))throw new r(`\`${i}\` must be a Date-parseable timestamp; got ${JSON.stringify(t)}`);return o}export{G as CONFIG_BRIDGE_CHANNEL,J as DEV_TOKEN_BRIDGE_CHANNEL,r as ScheduleInvocationError,st as assertValidPath,B as clearActiveConfig,it as contentFilePath,V as getActiveConfig,rt as getAdditionalEnvironmentProfiles,Q as getEnvironmentProfile,z as isKnownEnvironment,nt as isSdkError,X as listEnvironmentNames,Y as listExposedEnvNames,at as metaFilePath,Z as parseExposedEnvironment,q as registerEnvironmentProfile,W as requireEnvironmentProfile,ot as resetEnvironmentRegistryForTests,et as resolveForcedEnvironment,ut as runScheduledFunction,U as setActiveConfig,tt as setForcedEnvironment,T as setSdkConfig};
@@ -1,7 +1,9 @@
1
- import { P as PlatformContext } from '../types-DoNQWbb9.js';
1
+ import { P as PlatformContext } from '../types-B9ZTUx-H.js';
2
2
  import 'h3';
3
3
  import 'ky';
4
4
  import 'zod';
5
+ import 'ai';
6
+ import '@ai-sdk/provider';
5
7
 
6
8
  /**
7
9
  * Run code within a mock PlatformContext — for unit testing shared code that
@@ -1 +1 @@
1
- import{a as n}from"../chunk-WUCX7RZO.js";var f={http:!0,db:!0,kv:!0,files:!0,callFunctionAsync:!0,log:!0,config:!0,state:!0,executionId:!0,deploymentId:!0,traceId:!0,parentExecutionId:!0},d={input:!0,method:!0,path:!0,headers:!0,status:!0,error:!0,request:!0,userId:!0,identity:!0,trigger:!0};async function l(o,u){let i=new Proxy(o,{get(e,t,r){if(typeof t=="symbol"||t==="then"||t==="toJSON"||t in e)return Reflect.get(e,t,r);if(!(t in d))throw t in f?new Error(`Accessed unset context field "${String(t)}" in test. Provide it via runWithContext({ ${String(t)}: ... }, fn).`):new Error(`Accessed unknown context field "${String(t)}" in test \u2014 not a PlatformContext member.`)}});return n.run(i,u)}export{l as runWithContext};
1
+ import{a as n}from"../chunk-WUCX7RZO.js";var f={http:!0,db:!0,kv:!0,files:!0,callFunctionAsync:!0,ai:!0,log:!0,config:!0,state:!0,executionId:!0,deploymentId:!0,traceId:!0,parentExecutionId:!0},d={input:!0,method:!0,path:!0,headers:!0,status:!0,error:!0,request:!0,userId:!0,identity:!0,trigger:!0};async function l(o,u){let i=new Proxy(o,{get(e,t,r){if(typeof t=="symbol"||t==="then"||t==="toJSON"||t in e)return Reflect.get(e,t,r);if(!(t in d))throw t in f?new Error(`Accessed unset context field "${String(t)}" in test. Provide it via runWithContext({ ${String(t)}: ... }, fn).`):new Error(`Accessed unknown context field "${String(t)}" in test \u2014 not a PlatformContext member.`)}});return n.run(i,u)}export{l as runWithContext};
@@ -1,6 +1,8 @@
1
1
  import { H3Event } from 'h3';
2
2
  import { KyInstance } from 'ky';
3
3
  import { ZodType } from 'zod';
4
+ import { EmbeddingModel, ImageModel, LanguageModel, SpeechModel, TranscriptionModel, generateText, streamText, generateObject, streamObject, embed, embedMany, generateImage, transcribe, generateSpeech } from 'ai';
5
+ import { LanguageModelV4, EmbeddingModelV4, ImageModelV4, TranscriptionModelV4, SpeechModelV4 } from '@ai-sdk/provider';
4
6
 
5
7
  /** Connection + call params supplied by the caller at `.parameters()` time. */
6
8
  interface DbCallParameters {
@@ -118,6 +120,113 @@ interface FileSystemClient {
118
120
  */
119
121
  type CallFunctionAsync = (functionPath: string, input?: unknown) => Promise<void>;
120
122
 
123
+ /**
124
+ * Interim client-side cost estimation.
125
+ *
126
+ * The AI-gateway spec (helix-spec 11) makes the credentials broker the
127
+ * authority on cost: it sees model + token usage on every forwarded request
128
+ * and meters centrally (surfaced via `helix ai usage`). Until broker-side
129
+ * metering returns per-request cost to the SDK, `result.helix.cost` is
130
+ * estimated here from the provider's reported usage and public list prices.
131
+ * Unknown models estimate to 0 — the platform-side record remains authoritative.
132
+ *
133
+ * Prices are USD per 1M tokens, matched by longest model-id prefix so dated
134
+ * snapshot ids (e.g. `gpt-4o-2024-11-20`) resolve to their family.
135
+ */
136
+ interface HelixCost {
137
+ amount: number;
138
+ currency: "USD";
139
+ }
140
+
141
+ /**
142
+ * Public `ctx.ai` types (helix-spec 11).
143
+ *
144
+ * Options and results are the AI SDK's own — derived from the `ai` package's
145
+ * call functions so they track the pinned major exactly. The alias-scoped
146
+ * methods take `model` as a string id resolved against the provider; the
147
+ * top-level `ctx.ai.*` functions take a model *instance* (the `& object`
148
+ * intersection strips the AI SDK's string arm — bare ids would route via the
149
+ * implicit global provider, which Helix disables).
150
+ */
151
+ interface HelixResultMeta {
152
+ helix: {
153
+ /** Estimated from provider-reported usage (broker-side metering is the
154
+ authoritative record — see `helix ai usage`). */
155
+ cost: HelixCost;
156
+ requestId: string;
157
+ };
158
+ }
159
+ type AiLanguageModelInstance = LanguageModel & object;
160
+ type AiEmbeddingModelInstance = EmbeddingModel & object;
161
+ type AiImageModelInstance = ImageModel & object;
162
+ type AiTranscriptionModelInstance = TranscriptionModel & object;
163
+ type AiSpeechModelInstance = SpeechModel & object;
164
+ type WithStringModel<O> = Omit<O, "model"> & {
165
+ model: string;
166
+ };
167
+ type WithModelInstance<O, M> = Omit<O, "model"> & {
168
+ model: M;
169
+ };
170
+ type GenerateTextOptions = Parameters<typeof generateText>[0];
171
+ type StreamTextOptions = Parameters<typeof streamText>[0];
172
+ type GenerateObjectOptions = Parameters<typeof generateObject>[0];
173
+ type StreamObjectOptions = Parameters<typeof streamObject>[0];
174
+ type EmbedOptions = Parameters<typeof embed>[0];
175
+ type EmbedManyOptions = Parameters<typeof embedMany>[0];
176
+ type GenerateImageOptions = Parameters<typeof generateImage>[0];
177
+ type TranscribeOptions = Parameters<typeof transcribe>[0];
178
+ type GenerateSpeechOptions = Parameters<typeof generateSpeech>[0];
179
+ type GenerateTextReturn = Awaited<ReturnType<typeof generateText>>;
180
+ type StreamTextReturn = ReturnType<typeof streamText>;
181
+ type GenerateObjectReturn = Awaited<ReturnType<typeof generateObject>>;
182
+ type StreamObjectReturn = ReturnType<typeof streamObject>;
183
+ type EmbedReturn = Awaited<ReturnType<typeof embed>>;
184
+ type EmbedManyReturn = Awaited<ReturnType<typeof embedMany>>;
185
+ type GenerateImageReturn = Awaited<ReturnType<typeof generateImage>>;
186
+ type TranscribeReturn = Awaited<ReturnType<typeof transcribe>>;
187
+ type GenerateSpeechReturn = Awaited<ReturnType<typeof generateSpeech>>;
188
+ /**
189
+ * `ctx.ai(alias)` — a real AI SDK provider bound to the credentials broker,
190
+ * plus mirrored call functions taking string model ids.
191
+ */
192
+ interface HelixAIProvider {
193
+ /** Callable shorthand for languageModel(). */
194
+ (modelId: string): LanguageModelV4;
195
+ languageModel(modelId: string): LanguageModelV4;
196
+ embeddingModel(modelId: string): EmbeddingModelV4;
197
+ /** Spec-11 name for embeddingModel — same models. */
198
+ textEmbeddingModel(modelId: string): EmbeddingModelV4;
199
+ imageModel(modelId: string): ImageModelV4;
200
+ transcriptionModel(modelId: string): TranscriptionModelV4;
201
+ speechModel(modelId: string): SpeechModelV4;
202
+ generateText(options: WithStringModel<GenerateTextOptions>): Promise<GenerateTextReturn & HelixResultMeta>;
203
+ streamText(options: WithStringModel<StreamTextOptions>): StreamTextReturn;
204
+ generateObject(options: WithStringModel<GenerateObjectOptions>): Promise<GenerateObjectReturn & HelixResultMeta>;
205
+ streamObject(options: WithStringModel<StreamObjectOptions>): StreamObjectReturn;
206
+ embed(options: WithStringModel<EmbedOptions>): Promise<EmbedReturn>;
207
+ embedMany(options: WithStringModel<EmbedManyOptions>): Promise<EmbedManyReturn>;
208
+ generateImage(options: WithStringModel<GenerateImageOptions>): Promise<GenerateImageReturn & HelixResultMeta>;
209
+ transcribe(options: WithStringModel<TranscribeOptions>): Promise<TranscribeReturn>;
210
+ generateSpeech(options: WithStringModel<GenerateSpeechOptions>): Promise<GenerateSpeechReturn>;
211
+ }
212
+ /**
213
+ * `ctx.ai` — callable (alias → provider) and carrying the top-level call
214
+ * functions that take a model instance (from any `ctx.ai(alias)` provider).
215
+ * This is the governed request entry point for custom agent loops.
216
+ */
217
+ interface HelixAI {
218
+ (alias: string): HelixAIProvider;
219
+ generateText(options: WithModelInstance<GenerateTextOptions, AiLanguageModelInstance>): Promise<GenerateTextReturn & HelixResultMeta>;
220
+ streamText(options: WithModelInstance<StreamTextOptions, AiLanguageModelInstance>): StreamTextReturn;
221
+ generateObject(options: WithModelInstance<GenerateObjectOptions, AiLanguageModelInstance>): Promise<GenerateObjectReturn & HelixResultMeta>;
222
+ streamObject(options: WithModelInstance<StreamObjectOptions, AiLanguageModelInstance>): StreamObjectReturn;
223
+ embed(options: WithModelInstance<EmbedOptions, AiEmbeddingModelInstance>): Promise<EmbedReturn>;
224
+ embedMany(options: WithModelInstance<EmbedManyOptions, AiEmbeddingModelInstance>): Promise<EmbedManyReturn>;
225
+ generateImage(options: WithModelInstance<GenerateImageOptions, AiImageModelInstance>): Promise<GenerateImageReturn & HelixResultMeta>;
226
+ transcribe(options: WithModelInstance<TranscribeOptions, AiTranscriptionModelInstance>): Promise<TranscribeReturn>;
227
+ generateSpeech(options: WithModelInstance<GenerateSpeechOptions, AiSpeechModelInstance>): Promise<GenerateSpeechReturn>;
228
+ }
229
+
121
230
  interface Logger {
122
231
  info(message: string, data?: Record<string, unknown>): void;
123
232
  warn(message: string, data?: Record<string, unknown>): void;
@@ -203,6 +312,9 @@ interface ContextCore {
203
312
  * reports) that execution's outcome.
204
313
  */
205
314
  callFunctionAsync: CallFunctionAsync;
315
+ /** AI client (helix-spec 11): `ctx.ai(alias)` for broker-routed providers,
316
+ `ctx.ai.generateText({ model })` etc. for model-instance calls. */
317
+ ai: HelixAI;
206
318
  log: Logger;
207
319
  config: Record<string, unknown>;
208
320
  state: Record<string, unknown>;
@@ -321,4 +433,4 @@ interface ScheduleDefinition {
321
433
  handler: ScheduleHandler;
322
434
  }
323
435
 
324
- export type { BrokerAuthedClient as B, CallFunctionAsync as C, DefineFunctionOptions as D, FunctionHandler as F, HttpClient as H, KeyValueStore as K, Logger as L, PlatformContext as P, ScheduleDefinition as S, TrayContext as T, UnvalidatedInput as U, DefineScheduleConfig as a, BrokerCallOptions as b, BrokerCallResult as c, DbCallParameters as d, DbClient as e, FileSystemClient as f, S3SignOptions as g, S3SignResult as h, ScheduleContext as i, ScheduleHandler as j, ScheduleTrigger as k, SqlBuilder as l };
436
+ export type { AiEmbeddingModelInstance as A, BrokerAuthedClient as B, CallFunctionAsync as C, DefineFunctionOptions as D, FunctionHandler as F, HelixAI as H, KeyValueStore as K, Logger as L, PlatformContext as P, ScheduleDefinition as S, TrayContext as T, UnvalidatedInput as U, DefineScheduleConfig as a, AiImageModelInstance as b, AiLanguageModelInstance as c, AiSpeechModelInstance as d, AiTranscriptionModelInstance as e, BrokerCallOptions as f, BrokerCallResult as g, DbCallParameters as h, DbClient as i, FileSystemClient as j, HelixAIProvider as k, HelixCost as l, HelixResultMeta as m, HttpClient as n, S3SignOptions as o, S3SignResult as p, ScheduleContext as q, ScheduleHandler as r, ScheduleTrigger as s, SqlBuilder as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.112.1",
3
+ "version": "0.114.0",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",
@@ -38,9 +38,16 @@
38
38
  "./package.json": "./package.json"
39
39
  },
40
40
  "engines": {
41
- "node": ">=24.18.0"
41
+ "node": ">=24.19.0"
42
42
  },
43
43
  "dependencies": {
44
+ "@ai-sdk/anthropic": "^4.0.49",
45
+ "@ai-sdk/cohere": "^4.0.37",
46
+ "@ai-sdk/google": "^4.0.63",
47
+ "@ai-sdk/mistral": "^4.0.39",
48
+ "@ai-sdk/openai": "^4.0.58",
49
+ "@ai-sdk/openai-compatible": "^3.0.43",
50
+ "@ai-sdk/provider": "^4.0.10",
44
51
  "@opentelemetry/api": "^1.9.1",
45
52
  "@opentelemetry/api-logs": "0.220.0",
46
53
  "@opentelemetry/core": ">=2.8.0 <3",
@@ -50,6 +57,7 @@
50
57
  "@opentelemetry/sdk-logs": "0.220.0",
51
58
  "@opentelemetry/sdk-trace-base": "^2.11.0",
52
59
  "@opentelemetry/sdk-trace-node": "^2.11.0",
60
+ "ai": "^7.0.92",
53
61
  "c12": "^3.3.4",
54
62
  "chokidar": "^5.0.0",
55
63
  "h3": "^1.15.11",
@@ -1 +0,0 @@
1
- var P=new Set(["production"]),a=new Map,g={name:"production",exposedName:"us1",displayName:"production",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"}};a.set(g.name,g);var E=["api","broker","ingest","weaver","app","projectHost","dashboard"],x=["auth"],b=["storePrefix","appUrl","cookieName","cookieDomain"];function R(e){if(!e.name||typeof e.name!="string")throw new Error("EnvironmentProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("EnvironmentProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("EnvironmentProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("EnvironmentProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("EnvironmentProfile.login must be an object");for(let n of E)if(typeof e.hosts[n]!="string"||!e.hosts[n])throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string`);for(let n of x){let r=e.hosts[n];if(r!==void 0&&(typeof r!="string"||!r))throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string when set`)}for(let n of b)if(typeof e.login[n]!="string"||!e.login[n])throw new Error(`EnvironmentProfile.login.${n} must be a non-empty string`)}function I(e,n){return e.name===n.name&&e.exposedName===n.exposedName&&e.displayName===n.displayName&&E.every(r=>e.hosts[r]===n.hosts[r])&&x.every(r=>e.hosts[r]===n.hosts[r])&&b.every(r=>e.login[r]===n.login[r])}function V(e){R(e);let n=a.get(e.name);if(n){if(I(n,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let r of a.values())if(r.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${r.name}"`);a.set(e.name,e)}function N(e){return a.has(e)}function J(e){return a.get(e)}function y(e){let n=a.get(e);if(!n)throw new Error(`Unknown environment: ${e}`);return n}function G(){return[...a.keys()]}function Y(){return[...a.values()].map(e=>e.exposedName)}function T(e){for(let n of a.values())if(n.exposedName===e)return n.name}var m=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function D(e){let n=globalThis;if(e===void 0||e.trim()===""){delete n[m];return}let r=e.trim(),t=T(r);if(t){n[m]=t;return}if(N(r)){n[m]=r;return}throw new Error(`Unknown environment: ${r}`)}function z(){return globalThis[m]}function W(){return[...a.values()].filter(e=>!P.has(e.name))}function X(){D(void 0),a.clear(),a.set(g.name,{...g,hosts:{...g.hosts},login:{...g.login}})}var u=class e extends Error{detail;constructor(n){super(U(n)),this.name="SdkError",this.detail=n}get kind(){return this.detail.kind}static unknownAlias(n,r){return new e({kind:"unknown_alias",alias:n,available:r})}static inputValidationFailed(n){return new e({kind:"input_validation_failed",fields:n})}static outputValidationFailed(n){return new e({kind:"output_validation_failed",fields:n})}static configLoadFailed(n){return new e({kind:"config_load_failed",cause:n})}static brokerError(n,r,t,i){return new e({kind:"broker_error",status:n,message:r,body:t,code:i})}static unsupportedBodyType(n){return new e({kind:"unsupported_body_type",actualType:n})}static unsupportedScheme(n){return new e({kind:"unsupported_scheme",scheme:n})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(n,r){return new e({kind:"db_call_failed",message:n,cause:r})}static dbQueryFailed(n){return new e({kind:"db_query_failed",message:n})}static dbInvalidParameters(n){return new e({kind:"db_invalid_parameters",message:n})}static kvKeyInvalid(n){return new e({kind:"kv_key_invalid",message:n})}static kvValueInvalid(n){return new e({kind:"kv_value_invalid",message:n})}static kvValueTooLarge(n,r){return new e({kind:"kv_value_too_large",message:n,maxBytes:r})}static kvTtlInvalid(n){return new e({kind:"kv_ttl_invalid",message:n})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(n,r,t){return new e({kind:"kv_call_failed",status:n,message:r,body:t})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(n){return new e({kind:"files_path_invalid",message:n})}static filesValueInvalid(n){return new e({kind:"files_value_invalid",message:n})}static filesValueTooLarge(n,r){return new e({kind:"files_value_too_large",message:n,maxBytes:r})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(n,r,t){return new e({kind:"files_call_failed",status:n,message:r,body:t})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}static callFunctionPathInvalid(n){return new e({kind:"call_function_path_invalid",message:n})}static callFunctionCallFailed(n,r,t){return new e({kind:"call_function_call_failed",status:n,message:r,body:t})}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"})}};function Z(e){return e instanceof u}function U(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"}}import{z as f}from"zod";var w="x-helix-destination-url",S="x-helix-authentication-id",A="x-helix-deployment-id",v="x-execution-id",q="x-helix-broker-error",ie="route_not_found",O=new Set([w,S,A,"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",v]);function $(e){let n=e.toLowerCase();return O.has(n)||n.startsWith("x-tray-internal-")}var k=f.object({error:f.object({code:f.string(),message:f.string(),issues:f.array(f.unknown()).optional()})});function oe(e,n){let r=`${y(e).hosts.api}/private/v1/helix/broker/http/raw`;return n==="dev"?`${r}/dev`:r}function F(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 se(e){let n=new URL(e.url);if(n.protocol!=="https:")throw u.unsupportedScheme(n.protocol.replace(/:$/,""));if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[s,o]of e.query.entries())n.searchParams.append(s,o);else for(let[s,o]of Object.entries(e.query))for(let p of Array.isArray(o)?o:[o])n.searchParams.append(s,p);let r;e.headers===void 0?r=[]:e.headers instanceof Headers?r=Array.from(e.headers.entries()):Array.isArray(e.headers)?r=e.headers:r=Object.entries(e.headers);let t=r.filter(([s])=>!$(s)),i=e.body!==void 0&&e.body!==null,d,l,c=!1;return i&&(F(e.body)?(d=e.body,c=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(d=JSON.stringify(e.body),t.some(([o])=>o.toLowerCase()==="content-type")||(l="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:n.toString(),headers:t,body:d,isStreamBody:c,defaultContentType:l}}var j=6e4;function H(e){return e.includes("json")}function C(e){return e.startsWith("text/")||e.includes("xml")||e.includes("urlencoded")||e.includes("javascript")||e.includes("ecmascript")}function B(e,n){if(e.byteLength===0)return;let r=n.toLowerCase();if(H(r)){let t=new TextDecoder("utf-8").decode(e);try{return JSON.parse(t)}catch{return t}}return C(r)?new TextDecoder("utf-8").decode(e):e}function L(e){let n={};for(let[r,t]of e.entries())n[r.toLowerCase()]=t;return n}async function ae(e){let{request:n}=e,r=new Headers;for(let[s,o]of n.headers)r.append(s,o);n.defaultContentType&&!r.has("content-type")&&r.set("content-type",n.defaultContentType),r.set(w,n.destinationUrl),r.set(S,n.authenticationId);for(let[s,o]of Object.entries(e.credentialHeaders))r.set(s,o);e.executionId&&r.set(v,e.executionId);let t={method:n.method,headers:r,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??j)};n.body!==void 0&&(t.body=n.body,n.isStreamBody&&(t.duplex="half"));let i=await fetch(e.proxyUrl,t),d=i.headers.get(q);if(d!==null){let s=await i.text(),o=s,p=s||d;try{o=JSON.parse(s);let h=k.safeParse(o);h.success&&(p=h.data.error.message)}catch{}return{kind:"brokerError",status:i.status,code:d,message:p,body:o}}let l=new Uint8Array(await i.arrayBuffer()),c=i.headers.get("content-type")??"";return{kind:"upstream",response:{status:i.status,headers:L(i.headers),body:B(l,c)}}}import{z as _}from"zod";var M=3e4;function fe(e){let n=new URL(e);if(n.protocol!=="https:")throw u.unsupportedScheme(n.protocol.replace(/:$/,""))}function pe(e,n){let r=`${y(e).hosts.api}/private/v1/helix/broker/s3/sign`;return n==="dev"?`${r}/dev`:r}var K=_.object({url:_.string(),method:_.string(),expiresAt:_.string()});async function me(e){let n=new Headers({"content-type":"application/json"});for(let[l,c]of Object.entries(e.credentialHeaders))n.set(l,c);e.executionId&&n.set(v,e.executionId);let r=await fetch(e.signUrl,{method:"POST",headers:n,body:JSON.stringify(e.body),redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??M)}),t=await r.text(),i=t;try{i=JSON.parse(t)}catch{}if(r.ok){let l=K.safeParse(i);return l.success?{kind:"signed",result:l.data}:{kind:"brokerError",status:r.status,message:"malformed s3-sign response from credential broker",body:i}}let d=k.safeParse(i);return d.success?{kind:"brokerError",status:r.status,code:d.data.error.code,message:d.data.error.message,body:i}:{kind:"brokerError",status:r.status,message:t||`s3-sign request failed with status ${r.status}`,body:i}}export{V as a,N as b,J as c,y as d,G as e,Y as f,T as g,D as h,z as i,W as j,X as k,u as l,Z as m,A as n,ie as o,oe as p,se as q,j as r,ae as s,fe as t,pe as u,me as v};
@@ -1,7 +0,0 @@
1
- import{d as T,l as c,n as rt,o as se,p as Ae,q as J,s as nt,t as ot,u as ke,v as it}from"./chunk-KUXDW5ED.js";var S="X-Helix-Project-Execution-Token",P="X-Tray-Token",Ar={mode:"dev",deploymentId:null},De={...Ar},N={};function Oo(e){let{internalJwt:t,helixExecutionJwt:r,devToken:n,...o}=e;"internalJwt"in e&&(N.internalJwt=t),"helixExecutionJwt"in e&&(N.helixExecutionJwt=r),"devToken"in e&&(N.devToken=n),De={...De,...o}}function y(){return De}function I(){return N.internalJwt}function E(){return N.helixExecutionJwt}function ae(){return N.devToken}var Lo="tray-config-bridge",Mo="tray-dev-token-bridge",ce=null;function Uo(e){ce=e}function h(){if(!ce)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return ce}function Bo(){ce=null}import{AsyncLocalStorage as Ct}from"async_hooks";import{trace as Hr,SpanKind as Jr,SpanStatusCode as Oe}from"@opentelemetry/api";import{ExportResultCode as Vr,W3CTraceContextPropagator as zr}from"@opentelemetry/core";import{NodeTracerProvider as qr,SimpleSpanProcessor as Yr,BatchSpanProcessor as Xr}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as kr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Dr}from"@opentelemetry/exporter-logs-otlp-proto";function Fe(e){return T(e).hosts.ingest}function Fr(){return E()??""}function st(){return{[S]:Fr()}}function at(){let e=Fe(h().env);return new kr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(st())})}function ct(){let e=Fe(h().env);return new Dr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(st())})}import{logs as dt,SeverityNumber as le}from"@opentelemetry/api-logs";import{LoggerProvider as Nr,BatchLogRecordProcessor as Lr}from"@opentelemetry/sdk-logs";function V(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function _r(e){return new TextEncoder().encode(e).length}var lt="\u2026[truncated]",Or=_r(lt),z=4096;function _(e,t=z){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Or);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+lt}function g(e,t=z){return _(V(e),t)}var Mr="@trayai/helix-sdk",q,ut={debug:{number:le.DEBUG,text:"DEBUG"},info:{number:le.INFO,text:"INFO"},warn:{number:le.WARN,text:"WARN"},error:{number:le.ERROR,text:"ERROR"}};function Ur(){return y().mode==="lambda"?[new Lr({exporter:ct()})]:[]}function ft(){if(q!==void 0)return;let e=Ur();e.length!==0&&(q=new Nr({processors:e}),dt.setGlobalLoggerProvider(q))}function Br(e,t,r){let n=ut[e]??ut.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":g(r)}}:{}}}function mt(e,t,r){dt.getLogger(Mr).emit(Br(e,t,r))}async function pt(e=2e3){if(q===void 0)return;let t;try{await Promise.race([q.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 _e(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function jr(){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 R(e,t){return jr()?`\x1B[${e}m${t}\x1B[0m`:t}var Kr=5,$r={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},gt="32",yt="31",ue="2",ht="1";function de(e){return R($r[e]??"0",e.padEnd(Kr))}function wt(e,t){return`${de("FN")} ${R(ht,`${e} ${t}`.trim())}`}function bt(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${R(ue,n)} `:""}${de(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${R(ue,V(r))}`),i}function St(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Et(e){return`${de("AUTH")} ${e}`}function xt(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=R(o==="error"?yt:gt,s);return`${de("API")} ${e} ${t} \u2192 ${i} ${R(ue,`${n}ms`)}`}function vt(e,t,r){let n=t?yt:gt,o=R(n,"\u25CF"),s=R(n,t?"error":"success");return`${o} ${R(ht,e)} ${s} ${R(ue,`${r}ms`)}`}function L(e){try{process.stdout.write(e+`
3
- `)}catch{}}var Tt=new Ct,Gr=new Ct;function x(e){let t=Gr.getStore();t&&(t[e]=!0)}var Wr=/^[0-9a-f]{32}$/;function Qr(e){let t=e.replace(/-/g,"").toLowerCase();return Wr.test(t)?t:null}var Zr={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},M=new Map;function Pt(e,t,r){let n=M.get(e);n?n[t]=r:M.set(e,{[t]:r})}function C(e,t,r){e.setAttribute(t,g(r))}var Y;function Rt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function en(e){return Math.round(e[0]*1e3+e[1]/1e6)}function It(e){try{process.stdout.write(V(e)+`
4
- `)}catch{}}var Ne=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,s=M.get(o),i={...n.attributes};if(s!==void 0){for(let[u,d]of Object.entries(s))typeof d=="string"?i[u]=_(d):typeof d=="object"&&d!==null?i[u]=g(d):i[u]=d;M.delete(o)}let a=Tt.getStore(),l=a?Qr(a):null;It({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Rt(n.startTime),endTimeUnixNano:Rt(n.endTime),attributes:i,status:{code:Zr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:_(n.status.message)}:{}}})}r({code:Vr.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Le=class{onStart(t,r){}onEnd(t){M.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Me=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&L(`
5
- `+wt(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=M.get(n)?.properties;L(bt(String(r.level??"info"),String(r.message??""),o,St(t.startTime)));break}case"auth":L(Et(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;L(xt(String(r.method??""),String(r.host??""),n,en(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ue=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 tn(){let t=[_e()?new Me:new Yr(new Ne)];return y().mode==="lambda"&&t.push(new Ue(new Xr(at()))),t.push(new Le),t}function rn(){Y===void 0&&(Y=new qr({spanProcessors:tn()}),Y.register({propagator:new zr}),ft())}async function nn(e=2e3){let t=[pt(e)];Y!==void 0&&t.push((async()=>{let r;try{await Promise.race([Y.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 v=Hr.getTracer("@trayai/helix-sdk");function on({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:s,errored:i,errorMessage:a,userId:l,flags:u}){let d=new Date().toISOString(),f=Date.now()-s;if(_e()){L(`
7
- `+vt(n,i,f));return}It({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:i?"error":"success",startedAt:o,finishedAt:d,durationMs:f,userId:l,hasError:i||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:i&&a!==null?_(a):null})}async function mi(e,t){let r=e.startMs??Date.now();rn();let n=!1,o=null;try{return await Tt.run(e.executionId,()=>v.startActiveSpan("App",{kind:Jr.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async s=>{try{let i=await t(),a=i?.httpResponse?.status??404;return n=a>=400,s.setAttribute("http.response.status_code",a),s.setAttribute("helix.status",n?"error":"success"),s.setStatus({code:n?Oe.ERROR:Oe.OK}),i}catch(i){throw n=!0,o=i instanceof Error?i.message:String(i),s.setAttribute("http.response.status_code",500),s.setAttribute("helix.status","error"),s.setStatus({code:Oe.ERROR,message:o}),i}finally{s.end()}}))}finally{on({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,hasError:!1}}),await nn()}}var Dt=1024,A=100*1024*1024,At=250,sn=3600,an=sn*1e3,kt=new TextEncoder,cn=/(^|\/)\.\.(\/|$)/,ln=/[?#]/;function un(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function O(e,t=Dt){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");fe(e,t)}function Be(e){return e.endsWith("/")?e.slice(0,-1):e}function fe(e,t=Dt){if(e.length===0)return;if(cn.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(ln.test(e)||un(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 s=kt.encode(o).length;if(s>At)throw c.filesPathInvalid(`Path segment exceeds ${At} UTF-8 bytes (got ${s})`)}let n=kt.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function Ft(e){if(e>A)throw c.filesValueTooLarge(`File exceeds maximum size of ${A} bytes (got ${e})`,A)}function U(e){let t=e!==void 0?e*1e3:an;return new Date(Date.now()+t)}import{join as G}from"path";var dn="files",fn="files-meta",mn=1023,pn=1,gn=5;function _t(e){let t=Math.max(Buffer.byteLength(me(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,mn-t-pn-gn)}function me(e){return G(e,".helix",dn)}function X(e){return G(e,".helix",fn)}function W(e,t){return G(me(e),...t.split("/"))}function pe(e,t){return G(X(e),...t.split("/"))+".json"}function ge(e,t){return t.length===0?me(e):W(e,t)}function Ot(e,t){return t.length===0?X(e):G(X(e),...t.split("/"))}var Nt="helix-schedule",k=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function bi(e){if(typeof e!="object"||e===null)throw new k("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new k("`cron` must be a non-empty string");let s=t.trim().split(/\s+/).length;if(s!==5)throw new k(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${s} field(s) in "${t}"`);if(typeof r!="string"||!yn(r))throw new k(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new k("`concurrent` must be a boolean");if(typeof o!="function")throw new k("`handler` must be a function");return Object.freeze({kind:Nt,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function Si(e){return typeof e=="object"&&e!==null&&e.kind===Nt&&typeof e.handler=="function"}function yn(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 hn}from"@opentelemetry/api";function ye(e,t,r){let n=v.startSpan("log",{kind:hn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Pt(n.spanContext().spanId,"properties",r),n.end(),mt(e,t,r)}function Lt(){return{info:(e,t)=>ye("info",e,t),warn:(e,t)=>ye("warn",e,t),error:(e,t)=>ye("error",e,t),debug:(e,t)=>ye("debug",e,t)}}function Pi(){try{return h().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import wn from"ky";import{context as je,trace as bn,SpanKind as Z,SpanStatusCode as Ut}from"@opentelemetry/api";async function he(e,t={}){let r=y(),{env:n}=h(),o,s={};if(r.mode==="lambda"){let a=I(),l=E(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(s[P]=a),d&&(s[S]=l),r.deploymentId&&(s[rt]=r.deploymentId),o=Ae(n,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();s.Authorization=`Bearer ${a}`,o=Ae(n,"dev")}let i;try{i=await nt({proxyUrl:o,credentialHeaders:s,request:e,timeoutMs:t.timeout,executionId:r.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(i.kind==="brokerError"){let a=i.code===se?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":i.message;throw c.brokerError(i.status,a,g(i.body),i.code)}return i.response}async function Mt(e){ot(e.url);let t=y(),{env:r}=h(),n,o={},s={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}};if(t.mode==="lambda"){let a=I(),l=E(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(o[P]=a),d&&(o[S]=l),t.deploymentId&&(s.deploymentId=t.deploymentId),n=ke(r,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();o.Authorization=`Bearer ${a}`,n=ke(r,"dev")}let i;try{i=await it({signUrl:n,credentialHeaders:o,body:s,timeoutMs:e.timeout,executionId:t.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(i.kind==="brokerError"){let a=i.code===se?"credential broker does not support the s3 sign endpoint required by this SDK version \u2014 deploy a newer broker or pin an older SDK":i.message;throw c.brokerError(i.status,a,g(i.body),i.code)}return i.result}var Sn=["get","post","put","patch","delete","head","options"],jt="[stream body omitted]";function Kt(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?jt: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 Ke(e){try{return new URL(e).hostname}catch{return e}}function Bt(e,t,r,n,o){let s=Ke(t),i="externalApi",a={kind:Z.CLIENT};return v.startActiveSpan(i,a,async l=>(l.setAttributes({method:e,host:s,"peer.service":n}),C(l,"request",{url:t,method:e,...r!==void 0?{body:Kt(r)}:{}}),o(l)))}function Q(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Ut.OK}:{code:Ut.ERROR,message:r}),e.end()}var En=16;async function xn(e,t){let r=e.clone().body;return r?$t(r,t):new Uint8Array(0)}async function $t(e,t){let r=e.getReader(),n=[],o=0,s=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(s+=1,s>=En)break;continue}s=0;let d=t+1-o;if(u.byteLength>=d){n.push(u.slice(0,d)),o+=d;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let i=new Uint8Array(o),a=0;for(let l of n)i.set(l,a),a+=l.byteLength;return i}async function Ht(e,t,r){if("kyResponse"in r)try{let n=await xn(r.kyResponse,z),o=new TextDecoder("utf-8").decode(n,{stream:!0}),s;try{s=JSON.parse(o)}catch{s=o}C(e,"response",s)}catch{C(e,"response",{status:t})}else C(e,"response",Kt(r.bodyValue))}async function vn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),s=new Request(e,{body:n,duplex:"half"}),i=await $t(o,z);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:jt}}}return typeof t=="string"?{body:t}:{}}function Qi(){let e=wn.create({});function t(n){return(o,s)=>{let i=je.active(),a,l=!1,u=(f,m)=>{a&&!l&&(l=!0,Q(a,f,m))},d=e.extend({hooks:{beforeRequest:[async(f,m)=>{let p=await vn(f,m.body),ie=p.body;if(a||(a=v.startSpan("externalApi",{kind:Z.CLIENT},i)),a.setAttributes({method:f.method.toUpperCase(),host:Ke(f.url)}),C(a,"request",{url:f.url,method:f.method.toUpperCase(),...ie!==void 0?{body:ie}:{}}),l=!1,x("hasExternal"),p.request)return p.request}],beforeRetry:[f=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(f,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Ht(a,p.status,{kyResponse:p}),p.ok?u("success"):s?.throwHttpErrors===!1&&(x("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[f=>(x("hasError"),u("error",f.message),f)]}});return a=v.startSpan("externalApi",{kind:Z.CLIENT},i),a.setAttributes({method:n.toUpperCase(),host:Ke(String(o))}),je.with(bn.setSpan(je.active(),a),()=>{let f=n==="options"?d(o,{...s,method:"OPTIONS"}):d[n](o,s);return f.catch(m=>{x("hasError"),u("error",m instanceof Error?m.message:String(m))}),f})}}let r=Object.fromEntries(Sn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return Rn(n)}}}function Rn(e){let r=h().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(i){return(a,l={})=>{let u=i.toUpperCase();return Bt(u,a,l.body,e,async d=>{x("hasAuth");let f=v.startSpan("auth",{kind:Z.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let m=J({authenticationId:n,method:u,url:a,body:l.body,headers:l.headers,query:l.query}),p=await he(m,{timeout:l.timeout});return d.setAttribute("statusCode",p.status),await Ht(d,p.status,{bodyValue:p.body}),Q(d,"success"),p}catch(m){throw x("hasError"),m instanceof c&&m.detail.kind==="broker_error"&&m.detail.status>0&&d.setAttribute("statusCode",m.detail.status),Q(d,"error",m instanceof Error?m.message:String(m)),m}})}}function s(i,a={}){let l=a.method??"GET";return Bt(l,i,void 0,e,async u=>{x("hasAuth");let d=v.startSpan("auth",{kind:Z.INTERNAL});d.setAttribute("alias",e),d.setAttribute("id",n),d.end();try{let f=await Mt({authenticationId:n,url:i,method:l,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return u.setAttribute("statusCode",200),Q(u,"success"),f}catch(f){throw x("hasError"),f instanceof c&&f.detail.kind==="broker_error"&&f.detail.status>0&&u.setAttribute("statusCode",f.detail.status),Q(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:s}}import{SpanKind as _n,SpanStatusCode as qt}from"@opentelemetry/api";function ee(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Cn=18e4,Jt=Cn-1e4,Tn=2e3;async function Vt(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<Jt;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let l=Math.min(Tn,200*2**s),u=l/2+Math.random()*(l/2),d=Jt-(Date.now()-o);await new Promise(f=>setTimeout(f,Math.min(u,d))),s++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Pn=new Set(["SELECT","WITH","SHOW"]),In=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function An(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 kn(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 s=typeof t=="string"?_(t):g(t);return c.dbCallFailed(s)}function Dn(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 Fn(e,t){return typeof t!="number"||t<0?{}:Pn.has(e)?{rowsRead:t}:In.has(e)?{rowsWritten:t}:{}}function zt(e){async function t(r,n,o){let s=J({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:i,body:a}=await he(s);if(i>=400)throw kn(i,a);return Dn(a)}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw c.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:An,async execute(r,n){let o=ee(n),s={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},i=await t(r.region,"ExecuteStatement",s),a=i,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=g(i);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Vt(t,r.region,l),d=u.Status;if(d==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(d==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let f=Fn(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 $e=64*1024;function On(e){return e.length>$e?`${e.slice(0,$e)}...[truncated]`:e}function Nn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Ln(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>$e?C(e,"result",{truncated:!0,size:n.length}):C(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Mn(e,t,r){let n=ee(r),o=On(r);return v.startActiveSpan("database",{kind:_n.CLIENT},async s=>{Nn(s,e,t,n,o);try{x("hasDb");let{result:i,metadata:a}=await e.execute(t,r),l=Ln(s,i,a);return s.setAttribute("status","success"),s.setStatus({code:qt.OK}),l}catch(i){x("hasError");let a=i instanceof Error?i.message:String(i);throw s.setAttribute("status","error"),s.setStatus({code:qt.ERROR,message:a}),i}finally{s.end()}})}function Un(e){let r=h().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=zt(n);function s(i,a){return o.validate(i),Mn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as Hn}from"unstorage";var Yt=1024,He=250*1024,Bn=new TextEncoder,jn=/(^|\/)\.\.(\/|$)/,Kn=/[?#]/,$n=/[\u0000-\u001F\u007F]/;function Xt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(jn.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(Kn.test(e)||$n.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=Bn.encode(e).length;if(t<1||t>Yt)throw c.kvKeyInvalid(`Key must be between 1 and ${Yt} UTF-8 bytes (got ${t})`)}function Gt(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Wt(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>He)throw c.kvValueTooLarge(`Value exceeds maximum size of ${He} bytes (got ${r})`,He)}function te(e){Xt(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Qt(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return te(i),t(i,a)},setItem(i,a,l){return te(i),r(i,a,l)},removeItem(i,a){return te(i),n(i,a)},hasItem(i,a){return te(i),o(i,a)},getKeys(i,a){return i.length>0&&te(i),s(i,a)}}}function be(e){return Hn({driver:Qt(e)})}import{defineDriver as Jn}from"unstorage";function Vn(e){try{return JSON.parse(e)}catch{return e}}var zn=Jn(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 s=o?.ttl,i=Vn(n);s!==void 0?await t.set(r,i,{ttl:s}):await t.set(r,i)},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 Zt(e){return zn({client:e})}import Xn from"ky";import{z as b}from"zod";async function D(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 er(e){return T(e).hosts.api}function qn(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function Yn(e){return e.split("/").map(encodeURIComponent).join("/")}function re(e,t,r){return`${e}${qn(t)}/${Yn(r)}`}var Gn=6e4,Je=b.lazy(()=>b.union([b.string(),b.number(),b.boolean(),b.null(),b.array(Je),b.record(Je)])),Wn=b.object({projectId:b.string(),key:b.string(),value:Je,type:b.enum(["string","number","boolean","null","array","object"]),organizationId:b.string(),scope:b.string(),createdBy:b.string(),createdAt:b.number(),updatedBy:b.string(),updatedAt:b.number()});function Qn(){let e=I(),t=E(),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[P]=e),n&&(o[S]=t),o}function Zn(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 Se(e,t){throw c.kvCallFailed(e,Zn(t),g(t))}async function Ee(e,t,r={}){try{let n=await Xn(t,{method:e,headers:Qn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Gn}),o=e==="head"?void 0:await D(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 tr(e){let t=er(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await Ee("get",re(t,r,n));if(o===404)return null;(o<200||o>=300)&&Se(o,s);let i=Wn.safeParse(s);if(!i.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",g(s));return i.data.value},async set(n,o,s){let{status:i,body:a}=await Ee("put",re(t,r,n),{json:s?.ttl!==void 0?{value:o,ttl:s.ttl}:{value:o}});(i<200||i>=300)&&Se(i,a)},async delete(n){let{status:o,body:s}=await Ee("delete",re(t,r,n));o!==204&&Se(o,s)},async has(n){let{status:o,body:s}=await Ee("head",re(t,r,n));if(o===200)return!0;if(o===404)return!1;Se(o,s)}}}function xe(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;Wt(r),typeof o=="number"&&Gt(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function eo(){let e=h();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function rr(e){let t=eo(),r=e??tr(t),n=be(Zt(r));return xe(n)}import{defineDriver as to}from"unstorage";var ro=to(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,s){let i=s?.ttl,a=r(n),l=typeof i=="number"?Date.now()+i*1e3:i===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 nr(){return ro({})}var Ve;function no(){return Ve||(Ve=be(nr())),Ve}function or(){return xe(no())}function oo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function na(){return oo()?rr():or()}import{createHash as ao}from"crypto";import{mkdir as co,readFile as lr,readdir as ur,rm as sr,unlink as lo,writeFile as ar}from"fs/promises";import{dirname as uo}from"path";async function io(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:s}=await t.read();if(o)break;if(s){if(n+=s.byteLength,n>A)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${A} bytes (got more than ${A})`,A);r.push(s)}}return Buffer.concat(r)}async function B(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?io(e):Buffer.from(e)}var so={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"},ir="application/octet-stream";function ve(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return ir;let r=e.slice(t+1).toLowerCase();return so[r]??ir}function K(){let e=y().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function j(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 Re(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function ze(e){try{let t=await lr(pe(K(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function cr(e){await co(uo(e),{recursive:!0})}async function fo(e,t){let r=ge(e,t),n;try{n=await ur(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 dr(e,t){let r=ge(e,t),n;try{n=await ur(r,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return[];throw s}let o=[];for(let s of n){let i=t.length===0?s.name:`${t}/${s.name}`;s.isDirectory()?o.push(...await dr(e,i)):s.isFile()&&o.push(i)}return o}function fr(){return{async put(e,t,r){return j(async()=>{let n=K(),o=await B(t),s=r?.contentType??ve(e),i=ao("sha1").update(o).digest("hex"),a=new Date,l=W(n,e);await cr(l),await ar(l,o);let u={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},d=pe(n,e);return await cr(d),await ar(d,JSON.stringify(u)),Re(e,u)})},async get(e){return j(async()=>{let t=await ze(e);return t?{data:await lr(W(K(),e)),metadata:Re(e,t)}:null})},async head(e){return j(async()=>{let t=await ze(e);return t?Re(e,t):null})},async delete(e){return j(async()=>{let t=K();await Promise.all([W(t,e),pe(t,e)].map(async r=>{try{await lo(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=K(),r=await dr(t,e);return await Promise.all([sr(ge(t,e),{recursive:!0,force:!0}),sr(Ot(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=K(),n=t?.limit??100,s=(await fo(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let l=await ze(a);return l?Re(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=y().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:U(t?.expiresIn)}},async getDownloadUrl(e,t){let r=y().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:U(t?.expiresIn)}}}}import{createHash as bo}from"crypto";function Ce(e){return T(e).hosts.api}function mo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ne(e,t){return`${e}${mo(t)}`}function $(e,t,r){return`${ne(e,t)}/${encodeURIComponent(r)}`}function Te(e,t,r){return`${$(e,t,r)}/upload`}function mr(e,t,r){return`${$(e,t,r)}/download`}function pr(e,t,r){return`${$(e,t,r)}/signed-url`}function gr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${ne(e,t)}/file?${o.toString()}`}function yr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${ne(e,t)}?${o.toString()}`}import Ye from"ky";import{z as w}from"zod";var Xe=6e4,hr=w.object({id:w.string(),workspaceId:w.string(),projectId:w.string(),parentFolder:w.string().nullable().optional(),name:w.string(),size:w.number().nullable().optional(),objectType:w.enum(["Folder","File"]),contentType:w.string().nullable().optional(),createdAt:w.string(),updatedAt:w.string()}),po=w.object({signedURL:w.string()}),go=w.object({path:w.array(w.object({id:w.string(),name:w.string()})),elements:w.array(hr)});function Ge(){let e=I(),t=E(),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[P]=e),n&&(o[S]=t),o}function wr(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 F(e,t){throw c.filesCallFailed(e,wr(t),g(t))}function yo(e,t){return e===400&&wr(t).toLowerCase()==="resource not found"}async function ho(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 H(e,t,r={}){try{let n=await Ye(t,{method:e,headers:Ge(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Xe}),o=await D(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 qe(e,t){let r=hr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",g(t));return r.data}function br(e){let t=Ce(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await H("post",ne(t,r),{json:n});return(o<200||o>=300)&&F(o,s),qe(o,s)},async getByName(n,o){let{status:s,body:i}=await H("get",gr(t,r,n,o));return s===404||yo(s,i)?null:((s<200||s>=300)&&F(s,i),qe(s,i))},async getById(n){let{status:o,body:s}=await H("get",$(t,r,n));return o===404?null:((o<200||o>=300)&&F(o,s),qe(o,s))},async listChildren(n,o){let{status:s,body:i}=await H("get",yr(t,r,n,o));(s<200||s>=300)&&F(s,i);let a=go.safeParse(i);if(!a.success)throw c.filesCallFailed(s,"platform returned malformed listing",g(i));return a.data},async uploadContent(n,o,s,i){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:i}),s);let{body:l,contentType:u}=await ho(a),d;try{d=await Ye(Te(t,r,n),{method:"post",headers:{...Ge(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:Xe})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let f=await D(d);(d.status<200||d.status>=300)&&F(d.status,f)},async downloadContent(n){let o;try{o=await Ye(mr(t,r,n),{method:"get",headers:Ge(),throwHttpErrors:!1,timeout:Xe})}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message:String(i);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await D(o);F(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(n){let{status:o,body:s}=await H("get",pr(t,r,n));(o<200||o>=300)&&F(o,s);let i=po.safeParse(s);if(!i.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",g(s));return i.data.signedURL},async deleteById(n){let{status:o,body:s}=await H("delete",$(t,r,n));o===204||o===404||(o<200||o>=300)&&F(o,s)}}}function We(e){return e.split("/").filter(t=>t.length>0)}function Qe(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function wo(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(Qe(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Ze(e,t){let r=We(t),n=r[r.length-1],o;for(let s of r.slice(0,-1))o=(await wo(e,o,s)).id;return{parentFolder:o,name:n}}async function oe(e,t){let r=We(t),n=r[r.length-1],o;for(let s of r.slice(0,-1)){let i=await e.getByName(o,s);if(!i||i.objectType!=="Folder")return null;o=i.id}return{parentFolder:o,name:n}}async function et(e,t){if(t.length===0)return;let r=We(t),n;for(let o of r){let s=await e.getByName(n,o);if(!s||s.objectType!=="Folder")return null;n=s.id}return n}var So=500,Eo=8;async function xo(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;o<e.length;){let i=o++;n[i]=await r(e[i])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},s)),n}function vo(){let e=h();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Ro(e){return bo("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Pe(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Ro(t)}}async function Sr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(Qe(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Er(e,t){let{elements:r}=await e.listChildren(t,So);return(await xo(r,Eo,async o=>{let s=o.objectType==="Folder"?await Er(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function xr(e){let t=vo(),r=e??br(t),n=Ce(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:l,name:u}=await Ze(r,s),d=await B(i),f=a?.contentType??ve(s),m=await r.getByName(l,u);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${s}"`);let p=m??await Sr(r,l,u,f);await r.uploadContent(p.id,d,u,f);let ie=await r.getById(p.id);return Pe(s,ie??p,f)},async get(s){let i=await oe(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Pe(s,a)}},async head(s){let i=await oe(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:Pe(s,a)},async delete(s){let i=await oe(r,s);if(!i)return;let a=await r.getByName(i.parentFolder,i.name);a&&await r.deleteById(a.id)},async deleteMany(s){let i=await et(r,s);if(i===null)return{deleted:0};let a=await Er(r,i);return s.length>0&&i!==void 0&&await r.deleteById(i),{deleted:a}},async list(s,i){let a=await et(r,s??"");if(a===null)return{files:[],cursor:null};let l=i?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(f=>f.objectType==="File").map(f=>Pe(s?`${s}/${f.name}`:f.name,f)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:l}=await Ze(r,s),d=await r.getByName(a,l)??await Sr(r,a,l,i?.contentType);return{url:Te(n,o,d.id),expiresAt:U(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await oe(r,s),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${s}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:U(i?.expiresIn)}}}}function tt(e,t){let r=t?.maxPathBytes;return{async put(n,o,s){O(n,r);let i=await B(o);return Ft(i.byteLength),e.put(n,i,s)},async get(n){return O(n,r),e.get(n)},async head(n){return O(n,r),e.head(n)},async delete(n){return O(n,r),e.delete(n)},async deleteMany(n){let o=Be(n);return fe(o,r),e.deleteMany(o)},async list(n,o){let s=Be(n??"");return fe(s,r),e.list(s,o)},async getUploadUrl(n,o){return O(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return O(n,r),e.getDownloadUrl(n,o)}}}function Co(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Xa(){if(Co())return tt(xr());let e=y().projectRoot;return tt(fr(),{maxPathBytes:e?_t(e):void 0})}import Po from"ky";function vr(e){return T(e).hosts.api}function To(){return"/private/v1/helix/function-calls"}function Rr(e){return`${e}${To()}`}var Io=5e3;function Ao(){let e=E();if(!!!(e&&e.trim().length>0))throw c.callFunctionMissingExecutionJwt();return{Accept:"application/json",[S]:e}}function ko(e,t){throw c.callFunctionCallFailed(e,Do(t),g(t))}function Do(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 Cr(e){let t=vr(e.env);return{async callAsync(r,n){let o,s;try{let i=await Po(Rr(t),{method:"post",headers:Ao(),json:{functionPath:r,input:n},throwHttpErrors:!1,timeout:Io});o=i.status,s=await D(i)}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw c.callFunctionCallFailed(0,a)}(o<200||o>=300)&&ko(o,s)}}}var Tr=1024;function Ie(e){if(typeof e!="string"||e.trim().length===0)throw c.callFunctionPathInvalid("functionPath must be a non-empty string");if(e.length>Tr)throw c.callFunctionPathInvalid(`functionPath must be at most ${Tr} characters`)}function Fo(){let e=h();if(e.kind!=="provisioned")throw c.callFunctionRequiresProvisioning();return{env:e.env}}function Pr(e){return async function(r,n){Ie(r),await(e??Cr(Fo())).callAsync(r,n)}}function Ir(){return async function(t,r){Ie(t);let n=y().devServerUrl;if(!n)throw c.callFunctionNotAvailable();let o=t.startsWith("/")?t:`/${t}`,s=Lt();fetch(`${n}${o}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r??{})}).then(i=>{i.ok||s.warn("ctx.callFunctionAsync: dev-mode dispatch returned a non-2xx response",{functionPath:t,status:i.status})}).catch(i=>{s.warn("ctx.callFunctionAsync: dev-mode dispatch failed",{functionPath:t,error:i instanceof Error?i.message:String(i)})})}}function _o(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Ec(){return _o()?Pr():Ir()}export{Oo as a,y as b,Lo as c,Mo as d,Uo as e,h as f,Bo as g,Tt as h,Gr as i,x as j,C as k,rn as l,nn as m,v as n,on as o,mi as p,Lt as q,Pi as r,Qi as s,Un as t,na as u,O as v,W as w,pe as x,Xa as y,Ec as z,Nt as A,k as B,bi as C,Si as D};