@trayai/helix-sdk 1.15.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,60 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
8
  The SDK and [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) are
9
9
  released together and share a version — install matching versions.
10
10
 
11
+ ## 1.16.0
12
+
13
+ The SDK now supports **Zod 4** alongside Zod 3, which clears a high-severity advisory. Projects
14
+ on Zod 3 need no code changes — see "Upgrading" below.
15
+
16
+ ### Added
17
+
18
+ - **`region`** — a namespace exposing the built-in region `values`, an `isKnown(name)` helper,
19
+ and a Zod 4 `schema` for composing region validation into your own Zod 4 schemas.
20
+ - **`HelixSchema`** type export: the minimal `parse`/`safeParse` shape the SDK accepts for
21
+ input and output schemas, so a Zod 3 or a Zod 4 schema both satisfy it.
22
+
23
+ ### Changed
24
+
25
+ - **Zod 4 support.** The SDK now depends on `zod@^4.6.6`, which clears a high-severity advisory
26
+ (GHSA-mrhx-c7xc-m3w5) present in earlier Zod versions and blocking some deployments. Zod 3
27
+ has no patched release, so clearing it requires Zod 4. The advisory is not reachable through
28
+ the SDK's own code; it affects your project only if one of your functions validates untrusted
29
+ input with an unbounded `z.array(...)` — add a `.max(...)` bound in that case.
30
+ - **Your Zod 3 schemas still work** in `defineFunction`, `defineTool` and
31
+ `DefineFunctionOptions` — they accept any schema with `parse`/`safeParse` (Zod 3.25, via
32
+ `zod` or `zod/v3`, or Zod 4), `ctx.input` is still inferred from the schema, and the `400`
33
+ validation error response is unchanged.
34
+ - **`regionSchema` stays a Zod 3 schema**, so it still composes into your own Zod 3 schemas
35
+ (`z.object({ region: regionSchema })`). On Zod 4, compose `region.schema` instead.
36
+ - The SDK's other exported schemas (`projectIdSchema`, `workspaceIdSchema`, and the config
37
+ schemas) are Zod 4. Calling `.parse()` / `.safeParse()` on them works from either Zod version;
38
+ only *nesting* one inside your own schema requires Zod 4 (a Zod 4 schema can't be composed into
39
+ a Zod 3 object).
40
+ - `helix init` now scaffolds `zod@^4.6.6`.
41
+
42
+ ### Upgrading
43
+
44
+ 1. Update `@trayai/helix-sdk` and `@trayai/helix-cli` together to 1.16.0. Projects on Zod 3
45
+ need no code changes.
46
+ 2. **To clear the Zod advisory in your own dependency tree, upgrade your project's own `zod` to
47
+ `^4.6.6`** (`npm install -D zod@^4.6.6`). Updating the SDK alone does not remove a Zod 3 that
48
+ your `package.json` lists directly. A future `2.0` will drop Zod 3 support.
49
+ 3. If you move your own schemas to Zod 4, the changes most likely to affect you:
50
+ - If you compose the SDK's `regionSchema` into one of your schemas, switch that schema to
51
+ `region.schema` (the Zod 4 variant), or keep both on Zod 3.
52
+ - Single-argument `z.record(value)` no longer exists. Write `z.record(z.string(), value)`.
53
+ - `z.uuid()` is strict (RFC version and variant bits), unlike Zod 3's `.uuid()`. For IDs
54
+ that are only 8-4-4-4-12 hex, use `z.guid()`.
55
+ - `z.string().email()`, `.url()` and `.uuid()` still work but are deprecated in favour of
56
+ `z.email()`, `z.url()` and `z.uuid()`; the top-level forms don't exist in Zod 3.
57
+ - `.default(value)` returns the default without parsing it, so it must already match the
58
+ output type; use `.prefault(value)` for the old behaviour.
59
+ - A bare `z.unknown()` or `z.any()` object field is now required; add `.optional()` if the
60
+ key can be absent.
61
+ - `ZodError.errors` is gone (use `.issues`), and `.flatten()`/`.format()` are deprecated
62
+ but still work.
63
+ - Default error messages differ slightly between the two versions.
64
+
11
65
  ## 1.14.0
12
66
 
13
67
  ### Added
package/README.md CHANGED
@@ -46,6 +46,11 @@ schemas, so your project must declare it as a dependency — the SDK does not re
46
46
  relying on it transitively through the SDK breaks under strict package managers like pnpm.
47
47
  Listing it as a dev dependency matches what `helix init` scaffolds.
48
48
 
49
+ The SDK works with Zod 3.25 (`zod`, or `zod/v3`) and Zod 4 schemas, but Zod 4 is recommended
50
+ (`zod@^4.6.6`) — earlier versions have a known security advisory (GHSA-mrhx-c7xc-m3w5), and
51
+ `helix init` scaffolds `^4.6.6`. If you upgrade, note that single-argument `z.record(value)` is
52
+ gone in Zod 4: write `z.record(z.string(), value)`.
53
+
49
54
  Most projects are created with `helix init`, which wires both dependencies for you.
50
55
 
51
56
  ## Quick start
@@ -576,16 +581,21 @@ Use the CLI (`helix project set`, `helix workspace set`, `helix region set`, `he
576
581
  ### Regions
577
582
 
578
583
  Tray runs in four regions: `us1` (default), `eu1`, `ap1`, `ap2`. `region` in `helix.config.ts`
579
- pins a project to one. `REGION_VALUES` (the array of valid field values —
580
- `['us1', 'eu1', 'ap1', 'ap2']`) and `regionSchema` (the Zod schema backing the `region` field)
581
- are exported for validating a region string yourself, and `Region` is the corresponding type.
584
+ pins a project to one. For validating a region string yourself, the SDK exports `REGION_VALUES`
585
+ (the array of valid values — `['us1', 'eu1', 'ap1', 'ap2']`), `regionSchema` (a schema you can
586
+ call or compose), the `region` namespace, and the `Region` type.
582
587
 
583
588
  ```typescript
584
- import { REGION_VALUES, regionSchema, type Region } from '@trayai/helix-sdk';
589
+ import { REGION_VALUES, regionSchema, region, type Region } from '@trayai/helix-sdk';
585
590
 
586
- regionSchema.parse('eu1'); // 'eu1'
591
+ regionSchema.parse('eu1'); // 'eu1'
592
+ region.isKnown('eu1'); // true
587
593
  ```
588
594
 
595
+ `regionSchema` is a Zod 3 schema, so it composes into your own Zod 3 schemas
596
+ (`z.object({ region: regionSchema })`). If your project is on Zod 4, compose `region.schema`
597
+ (the Zod 4 equivalent) instead — Zod 3 and Zod 4 schemas can't be mixed in one object.
598
+
589
599
  > Projects created before the `region` rename may still have an `env` field in
590
600
  > `helix.config.ts` — it's accepted as a deprecated alias for one release cycle. Rename it to
591
601
  > `region` when convenient.
@@ -1,5 +1,6 @@
1
- import { R as Region } from '../region-schema-COfWyGI9.js';
1
+ import { R as Region } from '../region-schema-DAE9PT3S.js';
2
2
  import { z } from 'zod';
3
+ import 'zod/v3';
3
4
 
4
5
  type BrokerRegion = Region;
5
6
 
@@ -14,32 +15,8 @@ declare const TemplatesResponseSchema: z.ZodObject<{
14
15
  serviceVersion: z.ZodNumber;
15
16
  authenticationType: z.ZodString;
16
17
  strategy: z.ZodOptional<z.ZodString>;
17
- }, "strip", z.ZodTypeAny, {
18
- serviceName: string;
19
- serviceVersion: number;
20
- authenticationType: string;
21
- strategy?: string | undefined;
22
- }, {
23
- serviceName: string;
24
- serviceVersion: number;
25
- authenticationType: string;
26
- strategy?: string | undefined;
27
- }>, "many">;
28
- }, "strip", z.ZodTypeAny, {
29
- templates: {
30
- serviceName: string;
31
- serviceVersion: number;
32
- authenticationType: string;
33
- strategy?: string | undefined;
34
- }[];
35
- }, {
36
- templates: {
37
- serviceName: string;
38
- serviceVersion: number;
39
- authenticationType: string;
40
- strategy?: string | undefined;
41
- }[];
42
- }>;
18
+ }, z.core.$strip>>;
19
+ }, z.core.$strip>;
43
20
  type TemplatesResponse = z.infer<typeof TemplatesResponseSchema>;
44
21
 
45
22
  interface BrokerDevCallParams {
@@ -0,0 +1,7 @@
1
+ import{a as mn,b as ze}from"./chunk-WUCX7RZO.js";import{A as yn,B as fe,C as z,D as ne,E as hn,G as wn,H as Sn,I as bn,J as vn,a as U,b as de,d as E,e as ue,f as $,h as Ve,j,k as pn,o as fn,r as d,t as Ie,u as Ge,v as te,w as Re,x as Je,y as pe,z as gn}from"./chunk-LKZKDHYO.js";var cc="tray-config-bridge",lc="tray-dev-token-bridge",We=null;function dc(e){We=e}function A(){if(!We)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return We}function uc(){We=null}import{AsyncLocalStorage as Bn}from"async_hooks";import{trace as ls,SpanKind as ds,SpanStatusCode as et}from"@opentelemetry/api";import{ExportResultCode as us,W3CTraceContextPropagator as ps}from"@opentelemetry/core";import{NodeTracerProvider as fs,SimpleSpanProcessor as ms,BatchSpanProcessor as gs}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Wo}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Xo}from"@opentelemetry/exporter-logs-otlp-proto";function Ct(e){return j(e).hosts.ingest}function Yo(){return $()??""}function xn(){return{[U]:Yo()}}function An(){let e=Ct(A().region);return new Wo({url:`${e}/v1/traces`,headers:()=>Promise.resolve(xn())})}function En(){let e=Ct(A().region);return new Xo({url:`${e}/v1/logs`,headers:()=>Promise.resolve(xn())})}import{logs as kn,SeverityNumber as Xe}from"@opentelemetry/api-logs";import{LoggerProvider as es,BatchLogRecordProcessor as ts}from"@opentelemetry/sdk-logs";function ke(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Qo(e){return new TextEncoder().encode(e).length}var In="\u2026[truncated]",Zo=Qo(In),Ce=4096;function re(e,t=Ce){let n=new TextEncoder().encode(e);if(n.length<=t)return e;let r=n.subarray(0,t-Zo);return new TextDecoder("utf-8").decode(r).replace(/�$/,"")+In}function T(e,t=Ce){return re(ke(e),t)}var ns="@trayai/helix-sdk",Te,Rn={debug:{number:Xe.DEBUG,text:"DEBUG"},info:{number:Xe.INFO,text:"INFO"},warn:{number:Xe.WARN,text:"WARN"},error:{number:Xe.ERROR,text:"ERROR"}};function rs(){return E().mode==="lambda"?[new ts({exporter:En()})]:[]}function Cn(){if(Te!==void 0)return;let e=rs();e.length!==0&&(Te=new es({processors:e}),kn.setGlobalLoggerProvider(Te))}function os(e,t,n){let r=Rn[e]??Rn.info;return{severityNumber:r.number,severityText:r.text,body:t,...n?{attributes:{"tray.log.meta":T(n)}}:{}}}function Tn(e,t,n){kn.getLogger(ns).emit(os(e,t,n))}async function Pn(e=2e3){if(Te===void 0)return;let t;try{await Promise.race([Te.forceFlush(),new Promise(n=>{t=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel log flush failed: ${n instanceof Error?n.message:String(n)}
2
+ `)}finally{t!==void 0&&clearTimeout(t)}}function Tt(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function ss(){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 M(e,t){return ss()?`\x1B[${e}m${t}\x1B[0m`:t}var is=5,as={FN:"1;35",INFO:"34",AUTH:"35",API:"36",AGENT:"1;36",TOOL:"36",WARN:"33",ERROR:"31",DEBUG:"90"},Ye="32",Qe="31",cs="33",oe="2",Ze="1";function se(e){return M(as[e]??"0",e.padEnd(is))}function On(e,t){return`${se("FN")} ${M(Ze,`${e} ${t}`.trim())}`}function _n(e,t,n,r){let o=e.toUpperCase(),i=`${r?`${M(oe,r)} `:""}${se(o)} ${t}`;return n&&Object.keys(n).length>0&&(i+=` ${M(oe,ke(n))}`),i}function Dn(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Mn(e){return`${se("AUTH")} ${e}`}function Fn(e,t,n,r,o){let s=n===void 0?"ERR":String(n),i=M(o==="error"?Qe:Ye,s);return`${se("API")} ${e} ${t} \u2192 ${i} ${M(oe,`${r}ms`)}`}function Ln(e){return`${se("AGENT")} ${M(Ze,e)}`}function Nn(e,t,n,r){let o=t==="error"?Qe:t==="awaiting-approval"?cs:Ye,s=n!==void 0?`${M(oe,`${n} step${n===1?"":"s"}`)} `:"";return`${se("AGENT")} ${M(Ze,e)} \u2192 ${M(o,t)} ${s}${M(oe,`${r}ms`)}`}function Un(e,t,n){let r=t==="error"?M(Qe,"error"):M(Ye,"ok");return`${se("TOOL")} ${e} \u2192 ${r} ${M(oe,`${n}ms`)}`}function $n(e,t,n){let r=t?Qe:Ye,o=M(r,"\u25CF"),s=M(r,t?"error":"success");return`${o} ${M(Ze,e)} ${s} ${M(oe,`${n}ms`)}`}function K(e){try{process.stdout.write(e+`
3
+ `)}catch{}}var Hn=new Bn,ys=new Bn;function O(e){let t=ys.getStore();t&&(t[e]=!0)}var hs=/^[0-9a-f]{32}$/;function ws(e){let t=e.replace(/-/g,"").toLowerCase();return hs.test(t)?t:null}var Ss={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},me=new Map;function Kn(e,t,n){let r=me.get(e);r?r[t]=n:me.set(e,{[t]:n})}function q(e,t,n){e.setAttribute(t,T(n))}var Pe;function jn(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function Pt(e){return Math.round(e[0]*1e3+e[1]/1e6)}function qn(e){try{process.stdout.write(ke(e)+`
4
+ `)}catch{}}var Ot=class{export(t,n){for(let r of t){let o=r.spanContext().spanId,s=me.get(o),i={...r.attributes};if(s!==void 0){for(let[l,u]of Object.entries(s))typeof u=="string"?i[l]=re(u):typeof u=="object"&&u!==null?i[l]=T(u):i[l]=u;me.delete(o)}let a=Hn.getStore(),c=a?ws(a):null;qn({_otel:"span",traceId:c??r.spanContext().traceId,spanId:o,parentSpanId:r.parentSpanContext?.spanId??"",name:r.name,kind:r.kind,startTimeUnixNano:jn(r.startTime),endTimeUnixNano:jn(r.endTime),attributes:i,status:{code:Ss[r.status.code]??"STATUS_CODE_UNSET",...r.status.message?{message:re(r.status.message)}:{}}})}n({code:us.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},_t=class{onStart(t,n){}onEnd(t){me.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Dt=class{onStart(t){let n=t;(n.name==="function"||n.name==="App")&&K(`
5
+ `+On(String(n.attributes.method??""),String(n.attributes.route??""))),(n.name==="agent.generate"||n.name==="agent.stream")&&K(Ln(String(n.attributes.agent??"")))}onEnd(t){let n=t.attributes;switch(t.name){case"log":{let r=t.spanContext().spanId,o=me.get(r)?.properties;K(_n(String(n.level??"info"),String(n.message??""),o,Dn(t.startTime)));break}case"auth":K(Mn(String(n.alias??"")));break;case"externalApi":{let r=typeof n.statusCode=="number"?n.statusCode:void 0;K(Fn(String(n.method??""),String(n.host??""),r,Pt(t.duration),n.status==="error"?"error":"success"));break}case"agent.tool":{K(Un(String(n.tool??""),n.status==="error"?"error":"success",Pt(t.duration)));break}case"agent.generate":case"agent.stream":{let r=typeof n.status=="string"?n.status:t.status.code===et.ERROR?"error":"completed";K(Nn(String(n.agent??""),r,typeof n.steps=="number"?n.steps:void 0,Pt(t.duration)));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Mt=class{constructor(t){this.inner=t}inner;onStart(t,n){this.inner.onStart(t,n)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function bs(){let t=[Tt()?new Dt:new ms(new Ot)];return E().mode==="lambda"&&t.push(new Mt(new gs(An()))),t.push(new _t),t}function vs(){Pe===void 0&&(Pe=new fs({spanProcessors:bs()}),Pe.register({propagator:new ps}),Cn())}async function xs(e=2e3){let t=[Pn(e)];Pe!==void 0&&t.push((async()=>{let n;try{await Promise.race([Pe.forceFlush(),new Promise(r=>{n=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel flush failed: ${r instanceof Error?r.message:String(r)}
6
+ `)}finally{n!==void 0&&clearTimeout(n)}})()),await Promise.all(t)}var F=ls.getTracer("@trayai/helix-sdk");function As({executionId:e,deploymentId:t,triggerType:n="http",routeOrJob:r,startedAt:o,startMs:s,errored:i,errorMessage:a,userId:c,flags:l}){let u=new Date().toISOString(),p=Date.now()-s;if(Tt()){K(`
7
+ `+$n(r,i,p));return}qn({_otel:"summary",executionId:e,deploymentId:t,triggerType:n,routeOrJob:r,status:i?"error":"success",startedAt:o,finishedAt:u,durationMs:p,userId:c,hasError:i||l.hasError,hasAuth:l.hasAuth,hasAi:l.hasAi,hasExternal:l.hasExternal,hasDb:l.hasDb,errorSummary:i&&a!==null?re(a):null})}async function $c(e,t){let n=e.startMs??Date.now();vs();let r=!1,o=null;try{return await Hn.run(e.executionId,()=>F.startActiveSpan("App",{kind:ds.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async s=>{try{let i=await t(),a=i?.httpResponse?.status??404;return r=a>=400,s.setAttribute("http.response.status_code",a),s.setAttribute("helix.status",r?"error":"success"),s.setStatus({code:r?et.ERROR:et.OK}),i}catch(i){throw r=!0,o=i instanceof Error?i.message:String(i),s.setAttribute("http.response.status_code",500),s.setAttribute("helix.status","error"),s.setStatus({code:et.ERROR,message:o}),i}finally{s.end()}}))}finally{As({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:n,errored:r,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1}}),await xs()}}var Gn=1024,G=100*1024*1024,Vn=250,Es=3600,Is=Es*1e3,zn=new TextEncoder,Rs=/(^|\/)\.\.(\/|$)/,ks=/[?#]/;function Cs(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}function ie(e,t=Gn){if(e.length===0)throw d.filesPathInvalid("Path must be a non-empty string");tt(e,t)}function Ft(e){return e.endsWith("/")?e.slice(0,-1):e}function tt(e,t=Gn){if(e.length===0)return;if(Rs.test(e))throw d.filesPathInvalid("Path contains path traversal segment");if(ks.test(e)||Cs(e))throw d.filesPathInvalid("Path contains illegal characters");let n=e.split("/");if(e.startsWith("/")||e.endsWith("/")||n.some(o=>o===""))throw d.filesPathInvalid("Path must not contain empty path segments");for(let o of n){let s=zn.encode(o).length;if(s>Vn)throw d.filesPathInvalid(`Path segment exceeds ${Vn} UTF-8 bytes (got ${s})`)}let r=zn.encode(e).length;if(r<1||r>t)throw d.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${r})`)}function Jn(e){if(e>G)throw d.filesValueTooLarge(`File exceeds maximum size of ${G} bytes (got ${e})`,G)}function ge(e){let t=e!==void 0?e*1e3:Is;return new Date(Date.now()+t)}import{join as _e}from"path";var Ts="files",Ps="files-meta",Os=1023,_s=1,Ds=5;function Wn(e){let t=Math.max(Buffer.byteLength(nt(e),"utf8"),Buffer.byteLength(Oe(e),"utf8"));return Math.max(0,Os-t-_s-Ds)}function nt(e){return _e(e,".helix",Ts)}function Oe(e){return _e(e,".helix",Ps)}function De(e,t){return _e(nt(e),...t.split("/"))}function rt(e,t){return _e(Oe(e),...t.split("/"))+".json"}function ot(e,t){return t.length===0?nt(e):De(e,t)}function Xn(e,t){return t.length===0?Oe(e):_e(Oe(e),...t.split("/"))}import{z as Ms}from"zod";import{z as Fs}from"zod/v3";var Ls=["us1","eu1","ap1","ap2"],Yn=e=>`Invalid enum value. Expected ${pn().map(t=>`'${t}'`).join(" | ")}, received '${String(e)}'`,Jc=Fs.string().refine(Ve,e=>({message:Yn(e)})),Lt={values:Ls,isKnown:e=>Ve(e),schema:Ms.string().refine(Ve,{error:e=>Yn(e.input)})};import{resolve as J}from"path";import{existsSync as st,realpathSync as Qn}from"fs";import{loadConfig as Ns}from"c12";import{z as w}from"zod";var er=w.guid("projectId must be a valid UUID"),tr=w.string().min(1,"workspaceId must be a non-empty string"),nr=w.discriminatedUnion("store",[w.object({store:w.literal("managed")}),w.object({store:w.literal("dynamodb"),auth:w.string().min(1,"agentSessions.auth is required"),table:w.string().min(1,"agentSessions.table is required"),region:w.string().min(1,"agentSessions.region is required")})]),it=["openai","anthropic","google","mistral","cohere","bedrock","openai-compatible"],Us=["openai","anthropic","google","mistral","cohere"],$s=/^[a-z0-9][a-z0-9-]*$/i,rr=w.union([w.enum(Us),w.object({service:w.enum(it),baseUrl:w.string().url().optional(),region:w.string().regex($s,"aiProviders: region must be an AWS region name (e.g. us-east-1)").optional()}).refine(e=>e.service!=="openai-compatible"||e.baseUrl!==void 0,{message:'aiProviders: baseUrl is required when service is "openai-compatible"'}).refine(e=>e.service!=="bedrock"||e.region!==void 0||e.baseUrl!==void 0,{message:'aiProviders: region (e.g. "us-east-1") or baseUrl is required when service is "bedrock"'}).refine(e=>e.service==="bedrock"||e.region===void 0,{message:'aiProviders: region only applies to service "bedrock"'}).refine(e=>e.baseUrl===void 0?!0:new URL(e.baseUrl).protocol==="https:",{message:"aiProviders: baseUrl must use https \u2014 ctx.ai requests route through the credentials broker's proxy, which rejects non-https destinations on every call (a plain-http endpoint, e.g. a local Ollama/vLLM instance over http, is not supported)"})]),js=w.object({name:w.string().min(1,"name is required"),projectId:er.optional(),workspaceId:tr.optional(),region:Lt.schema.optional(),env:w.literal("production").optional(),authentications:w.record(w.string(),w.string()).optional().default({}),config:w.record(w.string(),w.unknown()).optional().default({}),agentSessions:nr.optional(),aiProviders:w.record(w.string(),rr).optional()}).transform(({env:e,region:t,...n})=>({...n,region:t??"us1"})),Zn=w.object({name:w.string().min(1,"name is required"),workspaceId:tr.optional(),region:Lt.schema,authentications:w.record(w.string(),w.string()),config:w.record(w.string(),w.unknown()),agentSessions:nr.optional(),aiProviders:w.record(w.string(),rr).optional()}),rl=w.discriminatedUnion("kind",[Zn.extend({kind:w.literal("provisioned"),projectId:er}),Zn.extend({kind:w.literal("unprovisioned")})]),or=["helix","tray"],sr=["ts","mts","cts","js","mjs","cjs"],ir="HELIX_CONFIG";function Nt(e){let t=e?.trim();return t||process.env[ir]?.trim()||void 0}function Bs(e,t){let n=Nt(t?.configFile);if(n!==void 0){let r=J(e,n);return st(r)?r:void 0}for(let r of or)for(let o of sr){let s=J(e,`${r}.config.${o}`);if(st(s))return s}}function Hs(e){for(let t of or)if(sr.some(n=>st(J(e,`${t}.config.${n}`))))return t;return"helix"}function Ks(e,t){return J(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function qs(e,t){let n=Nt(t?.configFile);return{name:Hs(e),cwd:e,...n!==void 0?{configFile:Ks(e,n)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function Vs(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw d.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let n=js.safeParse(e);if(!n.success){let l=n.error.issues.map(u=>u.message).join("; ");throw d.configLoadFailed(`Invalid helix.config.ts at ${t}: ${l}`)}let{projectId:r,workspaceId:o,...s}=n.data,i=o!==void 0?{workspaceId:o}:{},a=fn(),c=a!==void 0?{...s,region:a}:s;return r!==void 0?{kind:"provisioned",projectId:r,...c,...i}:{kind:"unprovisioned",...c,...i}}async function ol(e,t){let n=e??process.cwd(),r=Nt(t?.configFile),o=r!==void 0?J(n,r):void 0;if(o!==void 0&&!st(o)){let a=t?.configFile?.trim()?"":` (from ${ir})`;throw d.configLoadFailed(`Config file not found: ${o}${a}`)}let s;try{s=await Ns(qs(n,t))}catch(a){throw d.configLoadFailed(`Failed to load helix.config.ts: ${a instanceof Error?a.message:String(a)}`)}let i=s._configFile??Bs(n,t);if(!i)throw d.configLoadFailed(`helix.config.ts not found at ${J(n,"helix.config.ts")}`);if(o!==void 0&&s._configFile!==void 0){let a=Qn(o);if(Qn(J(s._configFile))!==a)throw d.configLoadFailed(`Config file conflict: requested ${o} but ${J(s._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return Vs(s.config,i)}var zs="WORKSPACE_ID_REQUIRED";function sl(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:zs});return e.workspaceId}var ar="helix-tool",Gs=/^[a-z][a-z0-9_]{0,63}$/;function ll(e){if(typeof e.name!="string"||!Gs.test(e.name))throw new Error(`defineTool: invalid tool name ${JSON.stringify(e.name)} \u2014 use snake_case (e.g. "lookup_customer")`);if(typeof e.description!="string"||e.description.trim().length===0)throw new Error(`defineTool("${e.name}"): description is required`);if(!e.input||typeof e.input.safeParse!="function")throw new Error(`defineTool("${e.name}"): input must be a Zod schema`);if(typeof e.handler!="function")throw new Error(`defineTool("${e.name}"): handler must be a function`);let t=async(r,o)=>{let s=e.input.safeParse(r);if(!s.success)throw d.inputValidationFailed(s.error.issues.map(i=>i.path.join(".")||"(root)"));return e.handler({...o,input:s.data})},n=(async r=>t(r,ze()));return Object.defineProperties(n,{kind:{value:ar,enumerable:!0},name:{value:e.name,enumerable:!0},description:{value:e.description,enumerable:!0},inputSchema:{value:e.input,enumerable:!0},needsApproval:{value:e.needsApproval,enumerable:!0},execute:{value:t,enumerable:!0}}),n}function cr(e){return typeof e=="function"&&e.kind===ar&&typeof e.name=="string"}var I=class extends Error{constructor(t){super(t),this.name="AgentCallerError"}};import{readFileSync as Js}from"fs";import{isAbsolute as Ws,resolve as Xs}from"path";var B=new Map;function lr(e){B.set(e.name,{definition:e});for(let t of B.values())t.referencesValidated=void 0}function gl(e,t){let n=B.get(e);n&&(n.baseDir=t,n.resolvedInstructions=void 0)}function yl(e,t){let n=B.get(e);n&&(n.resolvedInstructions=t)}function Me(e){let t=B.get(e);if(!t){let n=[...B.keys()].sort();throw new I(`Unknown agent "${e}". Registered agents: ${n.join(", ")||"(none \u2014 are the functions/_agents/ modules imported?)"}`)}return t.definition}function hl(){return[...B.values()].map(e=>e.definition)}function dr(e){let t=B.get(e);if(!t)throw new I(`Unknown agent "${e}"`);if(t.resolvedInstructions!==void 0)return t.resolvedInstructions;let{definition:n}=t;if(n.instructions!==void 0)return t.resolvedInstructions=n.instructions,n.instructions;let r=n.instructionsFile,o=Ws(r)?r:t.baseDir!==void 0?Xs(t.baseDir,r):void 0;if(o===void 0)throw new Error(`Agent "${e}" uses instructionsFile "${r}" but its base directory is unknown \u2014 load the agent through helix dev (which records it), or use inline \`instructions\`.`);let s;try{s=Js(o,"utf-8")}catch(i){throw new Error(`Agent "${e}": failed to read instructionsFile ${o}: ${i instanceof Error?i.message:String(i)}`)}if(s.trim().length===0)throw new Error(`Agent "${e}": instructionsFile ${o} is empty`);return t.resolvedInstructions=s,s}function ur(e){let t=B.get(e);if(t?.referencesValidated)return;let n=Me(e);for(let r of n.agents??[]){let s=(Me(r).tools??[]).filter(i=>i.needsApproval);if(s.length>0)throw new Error(`Agent "${e}" delegates to "${r}", which has needsApproval tools (${s.map(i=>i.name).join(", ")}) \u2014 approval cannot pause a parent's loop through delegation in v1. Put approval-gated tools on the orchestrating agent.`)}t&&(t.referencesValidated=!0)}function wl(){B.clear()}import{z as P}from"zod";var pr="helix-agent",Ys=/^[a-z][a-z0-9-]{0,63}$/,Qs=P.object({model:P.string().min(1),auth:P.string().min(1)}),Zs=P.object({name:P.string().regex(Ys,'agent name must be kebab-case (e.g. "support-agent"); name is required in v1'),description:P.string().min(1,"description is required"),model:P.string().min(1,"model is required"),auth:P.string().min(1,"auth (authentication alias) is required"),fallbacks:P.array(Qs).optional(),instructions:P.string().min(1).optional(),instructionsFile:P.string().min(1).optional(),tools:P.array(P.custom(cr,"tools entries must be defineTool exports")).optional(),agents:P.array(P.string().min(1)).optional(),memory:P.object({maxSessionMessages:P.number().int().positive().optional(),ttl:P.number().int().positive().optional(),scope:P.enum(["user","project"]).optional()}).optional(),limits:P.object({maxIterations:P.number().int().positive().optional(),maxToolCalls:P.number().int().positive().optional()}).optional()}).refine(e=>e.instructions===void 0!=(e.instructionsFile===void 0),{message:"exactly one of instructions / instructionsFile must be set"}),fr=200,mr=25,gr=50,Ut=3;function Al(e){let t=Zs.safeParse(e);if(!t.success){let o=typeof e?.name=="string"?e.name:"(unnamed)",s=t.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new Error(`defineAgent(${o}): invalid definition \u2014 ${s}`)}let n=new Set;for(let o of t.data.tools??[]){if(n.has(o.name))throw new Error(`defineAgent(${t.data.name}): duplicate tool "${o.name}"`);n.add(o.name)}let r={kind:pr,...t.data};return lr(r),r}function El(e){return typeof e=="object"&&e!==null&&e.kind===pr&&typeof e.name=="string"}var ei=50,yr=500;function Fe(e){let t=e?.limit??ei;if(!Number.isInteger(t)||t<1||t>yr)throw new I(`session.page(): limit must be an integer from 1 to ${yr}.`);let n=e?.order??"asc";if(n!=="asc"&&n!=="desc")throw new I('session.page(): order must be "asc" or "desc".');return{limit:t,order:n,cursor:e?.cursor}}function jt(){return new I("session.page(): invalid cursor \u2014 pass the `nextCursor` of the previous page, with the same `order`.")}var W=new Map;function Bt(e,t,n){let r=encodeURIComponent;return n!==void 0?`agent:${r(e)}:user:${r(n)}:session:${r(t)}`:`agent:${r(e)}:session:${r(t)}`}function ti(e,t,n){let r=Math.max(0,e.length-t);for(let s=r;s<e.length;s++)if(e[s]?.role==="user")return e.slice(s);for(let s=r-1;s>=0;s--)if(e[s]?.role==="user")return e.slice(s);if(!n)return;let o=r;for(;o<e.length&&e[o]?.role==="tool";)o++;return e.slice(o)}var ni=32;async function Ht(e,t){let n=t+ni;for(;;){let r=await e.messages({limit:n}),o=ti(r,t,r.length<n);if(o!==void 0)return o;n*=2}}function Kt(e,t){return e.ttlSeconds!==void 0&&t-e.lastActiveAt>e.ttlSeconds*1e3}var ri=6e4,$t=0;function oi(e){if(!(e-$t<ri)){$t=e;for(let[t,n]of W)if(Kt(n,e)){if(n.pendingApprovals.length>0){n.messages=[];continue}W.delete(t)}}}var X=class extends Error{constructor(t){super(`Agent session "${t}" has expired (session-expired)`),this.name="SessionExpiredError"}};function hr(e,t,n,r){let o=Date.now();oi(o);let s=n?.ttl,i=t??`ses_${crypto.randomUUID().replaceAll("-","")}`,a=Bt(e,i,r),c=W.get(a);if(c&&(c.ttlSeconds=s),c&&Kt(c,o)){if(W.delete(a),c.pendingApprovals.length>0)throw new X(i);c=void 0}c||(c={id:i,agentName:e,...r!==void 0?{ownerUserId:r}:{},messages:[],createdAt:o,lastActiveAt:o,pendingApprovals:[],ttlSeconds:s},W.set(a,c));let l=c,u=()=>{l.lastActiveAt=Date.now()};return{id:i,async messages(p){u();let m=l.messages;return p?.limit!==void 0?m.slice(-p.limit):[...m]},async page(p){let{limit:m,order:g,cursor:S}=Fe(p);u();let b=S===void 0?0:Number(S);if(!Number.isInteger(b)||b<0)throw jt();let x=g==="desc"?[...l.messages].reverse():l.messages,y=x.slice(b,b+m),f=b+y.length;return{messages:y,nextCursor:f<x.length?String(f):null}},async append(...p){u(),l.messages.push(...p)},async clear(){W.delete(a)},async truncated(){return!1},async pendingApprovals(){return u(),[...l.pendingApprovals]},async addPendingApprovals(p){u(),l.pendingApprovals.push(...p)},async resolveApproval(p){u();let m=l.pendingApprovals.findIndex(g=>g.approvalId===p);return m===-1?"already-resolved":(l.pendingApprovals.splice(m,1),"resolved")}}}function wr(e,t,n={}){let r=Date.now(),o=n.first??20,s=n.cursor!==void 0&&Number.parseInt(n.cursor,10)||0,i=[...W.values()].filter(c=>c.agentName===e&&c.ownerUserId===t&&!Kt(c,r)).sort((c,l)=>l.lastActiveAt-c.lastActiveAt);return{sessions:i.slice(s,s+o).map(c=>({id:c.id,createdAt:c.createdAt,lastActivityAt:c.lastActiveAt,messageCount:c.messages.length,pendingApprovals:c.pendingApprovals.length})),nextCursor:s+o<i.length?String(s+o):null}}function kl(){W.clear(),$t=0}import{AsyncLocalStorage as Ti}from"async_hooks";import{z as Gr}from"zod";import{generateText as Pi,streamText as Oi,tool as Jr,stepCountIs as _i}from"ai";import{SpanKind as Gt,SpanStatusCode as Se,context as Wr,trace as Di}from"@opentelemetry/api";import{embed as Ar,embedMany as Er,generateImage as Ir,generateObject as Rr,generateSpeech as kr,generateText as Cr,streamObject as Tr,streamText as Pr,transcribe as Or}from"ai";import{SpanKind as yi,SpanStatusCode as xr}from"@opentelemetry/api";import{createOpenAI as ci}from"@ai-sdk/openai";import{createAnthropic as li}from"@ai-sdk/anthropic";import{createGoogle as di}from"@ai-sdk/google";import{createMistral as ui}from"@ai-sdk/mistral";import{createCohere as pi}from"@ai-sdk/cohere";import{createAmazonBedrock as fi}from"@ai-sdk/amazon-bedrock";import{createOpenAICompatible as mi}from"@ai-sdk/openai-compatible";var si=new Set(["x-api-key","x-goog-api-key"]);function ii(e){return gn(e)||si.has(e.toLowerCase())}function ai(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function Sr(e){return async(t,n)=>{let r=ai(t),o=new URL(r);if(o.protocol!=="https:")throw d.unsupportedScheme(o.protocol.replace(/:$/,""));let s=E(),{region:i}=A(),a=new Headers(n?.headers??(t instanceof Request?t.headers:void 0)),c=new Headers;for(let[x,y]of a.entries())ii(x)||c.append(x,y);c.set(Ie,r),c.set(Ge,e),s.executionId&&c.set(Re,s.executionId);let{headers:l,deploymentId:u}=z(s);for(let[x,y]of Object.entries(l))c.set(x,y);u&&c.set(te,u);let p=fe(i,s.mode==="lambda"?"runtime":"dev"),m=n?.body??(t instanceof Request?t.clone().body:void 0),g={method:n?.method??(t instanceof Request?t.method:"GET"),headers:c,redirect:"manual",signal:n?.signal??void 0};m!=null&&(g.body=m,typeof ReadableStream<"u"&&m instanceof ReadableStream&&(g.duplex="half"));let S;try{S=await fetch(p,g)}catch(x){if(x instanceof Error&&x.name==="AbortError")throw x;let y=x instanceof Error?x.message??String(x):String(x);throw d.brokerError(0,y)}let b=S.headers.get(Je);if(b!==null){let x=await S.text(),y=x||b;try{let f=yn.safeParse(JSON.parse(x));f.success&&(y=f.data.error.message)}catch{}throw b===pe&&(y="credential broker does not support the raw proxy endpoint required by ctx.ai \u2014 deploy a newer broker or pin an older SDK"),d.brokerError(S.status,y,x||void 0,b)}return S}}var ae="helix-broker";function br(e){let{alias:t,service:n,baseUrl:r,region:o,authenticationId:s}=e,i=Sr(s);switch(n){case"openai":return ci({apiKey:ae,fetch:i});case"anthropic":return li({apiKey:ae,fetch:i});case"google":return di({apiKey:ae,fetch:i});case"mistral":return ui({apiKey:ae,fetch:i});case"cohere":return pi({apiKey:ae,fetch:i});case"bedrock":{if(!o&&!r)throw d.aiProviderMisconfigured(t,n,'set region (e.g. "us-east-1") or baseUrl for the Bedrock runtime endpoint');return fi({apiKey:ae,region:o??"helix-broker",...r?{baseURL:r}:{},fetch:i})}case"openai-compatible":{if(!r)throw d.aiProviderMisconfigured(t,n,"set baseUrl for the endpoint");return mi({name:t,baseURL:r,apiKey:ae,fetch:i})}}}var vr={"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(vr).sort((e,t)=>t.length-e.length);function at(e,t){let n=gi.find(s=>e.startsWith(s));if(!n||!t)return{amount:0,currency:"USD"};let r=vr[n],o=((t.inputTokens??0)*r.input+(t.outputTokens??0)*r.output)/1e6;return{amount:Number(o.toFixed(8)),currency:"USD"}}function L(e,t,n){return F.startActiveSpan("ai",{kind:yi.CLIENT},async r=>{r.setAttributes({operation:e.operation,model:e.model,...e.alias!==void 0?{alias:e.alias}:{}}),O("hasAi");try{let o=await t(),s=n?.(o);return s&&r.setAttributes({...s.inputTokens!==void 0?{inputTokens:s.inputTokens}:{},...s.outputTokens!==void 0?{outputTokens:s.outputTokens}:{}}),r.setAttribute("status","success"),r.setStatus({code:xr.OK}),o}catch(o){let s=o instanceof Error?o.message:String(o);throw r.setAttribute("status","error"),r.setStatus({code:xr.ERROR,message:s}),o}finally{r.end()}})}function hi(){return`aireq_${crypto.randomUUID().replaceAll("-","")}`}function he(e,t){return{cost:at(e,t),requestId:hi()}}function ce(e){return typeof e=="object"&&e!==null&&"modelId"in e?String(e.modelId):String(e)}var _r=new WeakSet;function ye(e){return _r.add(e),e}function Dr(e){return ye(e)}function V(e){if(typeof e!="object"||e===null)throw d.aiModelInstanceRequired(typeof e=="string"?e:String(e));if(!_r.has(e))throw d.aiForeignModelRejected()}function ct(e){return e.totalUsage??e.usage}function lt(e){return e.usage?.tokens!==void 0?{inputTokens:e.usage.tokens}:void 0}function dt(e){return e.usage}function qt(e){let t=A(),n=t.authentications??{};if(!n[e])throw d.unknownAlias(e,Object.keys(n));let r=n[e],o=(t.aiProviders??{})[e];if(o===void 0)throw d.aiProviderNotConfigured(e,[...it]);let{service:s,baseUrl:i,region:a}=typeof o=="string"?{service:o,baseUrl:void 0,region:void 0}:o,c=br({alias:e,service:s,baseUrl:i,region:a,authenticationId:r}),l=y=>ye(c.languageModel(y)),u=y=>ye(c.embeddingModel(y)),p=y=>ye(c.imageModel(y)),m=y=>{if(!c.transcriptionModel)throw new Error(`AI provider "${s}" (alias "${e}") has no transcription models`);return ye(c.transcriptionModel(y))},g=y=>{if(!c.speechModel)throw new Error(`AI provider "${s}" (alias "${e}") has no speech models`);return ye(c.speechModel(y))},S=(y=>l(y)),b=(y,f)=>{let h=y.model;if(typeof h!="string")throw d.aiModelIdRequired(e,f);return h};return Object.assign(S,{specificationVersion:"v4",languageModel:l,embeddingModel:u,textEmbeddingModel:u,imageModel:p,transcriptionModel:m,speechModel:g,async generateText(y){let f=b(y,"generateText"),h=await L({operation:"generateText",model:f,alias:e},()=>Cr({...y,model:l(f)}),ct);return Object.assign(h,{helix:he(f,ct(h))})},streamText(y){let f=b(y,"streamText");return O("hasAi"),Pr({...y,model:l(f)})},async generateObject(y){let f=b(y,"generateObject"),h=await L({operation:"generateObject",model:f,alias:e},()=>Rr({...y,model:l(f)}),R=>R.usage),v=h.usage;return Object.assign(h,{helix:he(f,v)})},streamObject(y){let f=b(y,"streamObject");return O("hasAi"),Tr({...y,model:l(f)})},async embed(y){let f=b(y,"embed");return L({operation:"embed",model:f,alias:e},()=>Ar({...y,model:u(f)}),lt)},async embedMany(y){let f=b(y,"embedMany");return L({operation:"embedMany",model:f,alias:e},()=>Er({...y,model:u(f)}),lt)},async generateImage(y){let f=b(y,"generateImage"),h=await L({operation:"generateImage",model:f,alias:e},()=>Ir({...y,model:p(f)}),dt);return Object.assign(h,{helix:he(f,dt(h))})},async transcribe(y){let f=b(y,"transcribe");return L({operation:"transcribe",model:f,alias:e},()=>Or({...y,model:m(f)}))},async generateSpeech(y){let f=b(y,"generateSpeech");return L({operation:"generateSpeech",model:f,alias:e},()=>kr({...y,model:g(f)}))}})}function ed(){let e=new Map;return Object.assign((r=>{let o=e.get(r);return o||(o=qt(r),e.set(r,o)),o}),{async generateText(r){V(r.model);let o=ce(r.model),s=await L({operation:"generateText",model:o},()=>Cr(r),ct);return Object.assign(s,{helix:he(o,ct(s))})},streamText(r){return V(r.model),O("hasAi"),Pr(r)},async generateObject(r){V(r.model);let o=ce(r.model),s=await L({operation:"generateObject",model:o},()=>Rr(r),a=>a.usage),i=s.usage;return Object.assign(s,{helix:he(o,i)})},streamObject(r){return V(r.model),O("hasAi"),Tr(r)},async embed(r){return V(r.model),L({operation:"embed",model:ce(r.model)},()=>Ar(r),lt)},async embedMany(r){return V(r.model),L({operation:"embedMany",model:ce(r.model)},()=>Er(r),lt)},async generateImage(r){V(r.model);let o=ce(r.model),s=await L({operation:"generateImage",model:o},()=>Ir(r),dt);return Object.assign(s,{helix:he(o,dt(s))})},async transcribe(r){return V(r.model),L({operation:"transcribe",model:ce(r.model)},()=>Or(r))},async generateSpeech(r){return V(r.model),L({operation:"generateSpeech",model:ce(r.model)},()=>kr(r))}})}var Vt=class extends Error{errors;constructor(t){super(`all ${t.length} models in the fallback chain failed \u2014 `+t.map(({modelId:n,error:r})=>`${n}: ${r instanceof Error?r.message:String(r)}`).join("; ")),this.name="FallbackExhaustedError",this.errors=t.map(n=>n.error)}};function Mr(e){if(e.length===0)throw new Error("createFallbackModel: at least one model required");if(e.length===1)return e[0];let t=e[0];async function n(r){let o=[];for(let s of e)try{return await r(s)}catch(i){if(i instanceof Error&&i.name==="AbortError")throw i;o.push({modelId:s.modelId,error:i})}throw new Vt(o)}return{specificationVersion:"v4",provider:t.provider,modelId:t.modelId,get supportedUrls(){return Promise.resolve(t.supportedUrls)},doGenerate:r=>n(o=>o.doGenerate(r)),doStream:r=>n(o=>o.doStream(r))}}function zt(e){let t=e.code===pe?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":e.message;throw d.brokerError(e.status,t,T(e.body),e.code)}async function we(e,t={}){let n=E(),{region:r}=A(),{headers:o,deploymentId:s}=z(n);s&&(o[te]=s);let i=fe(r,n.mode==="lambda"?"runtime":"dev"),a;try{a=await wn({proxyUrl:i,credentialHeaders:o,request:e,timeoutMs:t.timeout,executionId:n.executionId})}catch(c){let l=c instanceof Error?c.message??String(c):String(c);throw d.brokerError(0,l)}return a.kind==="brokerError"&&zt(a),a.response}var wi=8,pt="msg#",Si="meta",Fr=25,Lr=3,bi=400*1024-1024;function vi(e){let t=new Set,n=new Set;for(let r of e)if(Array.isArray(r?.content))for(let o of r.content){if(typeof o!="object"||o===null)continue;let{type:s,approvalId:i,isAutomatic:a}=o;typeof i=="string"&&(s==="tool-approval-request"&&a!==!0&&t.add(i),s==="tool-approval-response"&&n.add(i))}for(let r of n)t.delete(r);return t}var N=e=>({S:e}),ut=e=>({N:String(e)});function Le(e,t){let n=e?.[t]?.S;return typeof n=="string"?n:void 0}function Nr(e,t){let n=e?.[t]?.N;return typeof n=="string"?Number(n):void 0}function xi(e,t){return e?.[t]?.BOOL===!0}function Ur(e,t){let n=e?.[t]?.M;return typeof n=="object"&&n!==null?n:{}}function Ai(e){return`${pt}${String(e).padStart(wi,"0")}`}function Ei(e){let t=null;if(typeof e=="string")try{t=JSON.parse(e)}catch{return}else e!==null&&typeof e=="object"&&(t=e);let n=t?.__type;return typeof n=="string"?n.split("#").pop():void 0}function $r(e){let{agentName:t,table:n,region:r,authenticationId:o}=e,s=e.options?.ttl,i=e.sessionId??`ses_${crypto.randomUUID().replaceAll("-","")}`,a=Bt(t,i,e.ownerUserId),c={pk:N(a),sk:N(Si)};async function l(f,h){let v=ne({authenticationId:o,method:"POST",url:`https://dynamodb.${r}.amazonaws.com/`,body:h,headers:{"Content-Type":"application/x-amz-json-1.0","X-Amz-Target":`DynamoDB_20120810.${f}`}}),R,C;try{({status:R,body:C}=await we(v))}catch(k){throw k instanceof d?k:d.agentSessionsFailed(k instanceof Error?k.message:String(k))}if(R>=400){let k=Ei(C);throw k==="ConditionalCheckFailedException"?new ft:d.agentSessionsFailed(`DynamoDB ${f} failed (${R}): ${k??JSON.stringify(C).slice(0,300)}`)}if(typeof C=="string")try{return JSON.parse(C)}catch{throw d.agentSessionsFailed(`DynamoDB ${f}: non-JSON response body`)}return C??{}}async function u(){return(await l("GetItem",{TableName:n,Key:c,ConsistentRead:!0})).Item}let p=!1;async function m(){p||(await g(),p=!0)}async function g(){let f=await u();if(!f){let v=await S({ascending:!0});if(v.length===0||await u())return;let R=v.map(C=>JSON.parse(Le(C,"message")??"null"));if(await b(v.map(C=>({DeleteRequest:{Key:{pk:N(a),sk:C.sk}}}))),vi(R).size>0)throw new X(i);return}if(s===void 0)return;let h=Nr(f,"lastActiveAt")??0;if(!(Date.now()-h<=s*1e3)){if(Object.keys(Ur(f,"pendingApprovals")).length>0)throw new X(i);await x()}}async function S(f){let h=[],v;do{let R=await l("Query",{TableName:n,KeyConditionExpression:"pk = :pk AND begins_with(sk, :prefix)",ExpressionAttributeValues:{":pk":N(a),":prefix":N(pt)},ConsistentRead:!0,ScanIndexForward:f.ascending,...f.limit!==void 0?{Limit:f.limit}:{},...f.projection!==void 0?{ProjectionExpression:f.projection}:{},...v!==void 0?{ExclusiveStartKey:v}:{}});if(h.push(...R.Items??[]),v=R.LastEvaluatedKey,f.limit!==void 0&&h.length>=f.limit)break}while(v!==void 0);return h}async function b(f){for(let h=0;h<f.length;h+=Fr){let v=f.slice(h,h+Fr);for(let R=0;v.length>0;R++){let k=(await l("BatchWriteItem",{RequestItems:{[n]:v}})).UnprocessedItems?.[n];if(!k||k.length===0)break;if(R>=Lr)throw d.agentSessionsFailed(`DynamoDB BatchWriteItem: ${k.length} items still unprocessed after ${Lr} retries`);v=k}}}async function x(){let h=(await S({ascending:!0,projection:"sk"})).map(v=>({DeleteRequest:{Key:{pk:N(a),sk:v.sk}}}));h.push({DeleteRequest:{Key:c}}),await b(h)}async function y(f){let h=Date.now();return(await l("UpdateItem",{TableName:n,Key:c,UpdateExpression:"ADD nextSeq :reserve, messageCount :reserve SET lastActiveAt = :now, "+(s!==void 0?"expiresAt = :expires, ":"")+"createdAt = if_not_exists(createdAt, :now), truncated = if_not_exists(truncated, :false), pendingApprovals = if_not_exists(pendingApprovals, :emptyMap)"+(s===void 0?" REMOVE expiresAt":""),ExpressionAttributeValues:{":reserve":ut(f),":now":ut(h),...s!==void 0?{":expires":ut(Math.floor(h/1e3)+s)}:{},":false":{BOOL:!1},":emptyMap":{M:{}}},ReturnValues:"ALL_NEW"})).Attributes??{}}return{id:i,async messages(f){await m();let h=f?.limit;return h!==void 0?(await S({ascending:!1,limit:h})).reverse().map(C=>JSON.parse(Le(C,"message")??"null")):(await S({ascending:!0})).map(R=>JSON.parse(Le(R,"message")??"null"))},async page(f){let{limit:h,order:v,cursor:R}=Fe(f);await m();let C;if(R!==void 0&&(C=Buffer.from(R,"base64url").toString("utf8"),!C.startsWith(pt)))throw jt();let k=await l("Query",{TableName:n,KeyConditionExpression:"pk = :pk AND begins_with(sk, :prefix)",ExpressionAttributeValues:{":pk":N(a),":prefix":N(pt)},ConsistentRead:!0,ScanIndexForward:v==="asc",Limit:h,...C!==void 0?{ExclusiveStartKey:{pk:N(a),sk:N(C)}}:{}}),ee=k.Items??[],qe=Le(k.LastEvaluatedKey,"sk");return{messages:ee.map(Jo=>JSON.parse(Le(Jo,"message")??"null")),nextCursor:qe!==void 0?Buffer.from(qe,"utf8").toString("base64url"):null}},async append(...f){if(f.length===0)return;let h=f.map(ee=>JSON.stringify(ee)),v=h.findIndex(ee=>Buffer.byteLength(ee,"utf8")>bi);if(v!==-1)throw d.agentSessionsFailed(`a ${f[v].role} message of ${Buffer.byteLength(h[v],"utf8")} bytes exceeds DynamoDB's 400 KB item limit \u2014 the session store keeps one item per message; have tools summarise or offload (ctx.files) large results`);await m();let R=await y(f.length),k=(Nr(R,"nextSeq")??f.length)-f.length+1;await b(h.map((ee,qe)=>({PutRequest:{Item:{pk:N(a),sk:N(Ai(k+qe)),message:N(ee)}}})))},async clear(){await x()},async truncated(){return await m(),xi(await u(),"truncated")},async pendingApprovals(){await m();let f=Ur(await u(),"pendingApprovals");return Object.values(f).map(h=>{let v=h.S;return v!==void 0?JSON.parse(v):void 0}).filter(h=>h!==void 0)},async addPendingApprovals(f){if(f.length===0)return;await m(),await y(0);let h={},v={},R=[];f.forEach((C,k)=>{h[`#a${k}`]=C.approvalId,v[`:v${k}`]=N(JSON.stringify(C)),R.push(`pendingApprovals.#a${k} = :v${k}`)}),await l("UpdateItem",{TableName:n,Key:c,UpdateExpression:`SET ${R.join(", ")}`,ExpressionAttributeNames:h,ExpressionAttributeValues:v})},async resolveApproval(f){await m();try{return await l("UpdateItem",{TableName:n,Key:c,UpdateExpression:"REMOVE pendingApprovals.#id SET lastActiveAt = :now",ConditionExpression:"attribute_exists(pendingApprovals.#id)",ExpressionAttributeNames:{"#id":f},ExpressionAttributeValues:{":now":ut(Date.now())}}),"resolved"}catch(h){if(h instanceof ft)return"already-resolved";throw h}}}}var ft=class extends Error{constructor(){super("ConditionalCheckFailedException"),this.name="ConditionalCheckFailed"}};import Ii from"ky";async function H(e){let t=e.headers.get("content-type")??"",n=await e.text();if(n.length!==0)return t.includes("application/json")?JSON.parse(n):n}var Ri=6e4,ki=500,jr=500;function Br(e){let t=A();if(t.kind!=="provisioned")throw d.agentSessionsFailed("the managed session store requires a provisioned project (projectId in helix.config.ts)");return`${j(t.region).hosts.api}/private/v1/helix/projects/${encodeURIComponent(t.projectId)}/storage/agent-sessions/${encodeURIComponent(e)}`}function Ci(){let e=ue(),t=$(),n={Accept:"application/json"};if(e&&e.trim().length>0&&(n[de]=e),t&&t.trim().length>0&&(n[U]=t),Object.keys(n).length===1)throw d.missingExecutionCredentials();return n}async function Y(e,t,n){try{let r=await Ii(t,{method:e,headers:Ci(),...n!==void 0?{json:n}:{},throwHttpErrors:!1,timeout:Ri});return{status:r.status,body:await H(r)}}catch(r){throw r instanceof d?r:d.agentSessionsFailed(`managed session store unreachable: ${r instanceof Error?r.message:String(r)}`)}}function mt(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message}return String(e??"unknown error")}function le(e,t,n){throw t===410?new X(e):t===404?new I(`Agent session "${e}" was not found (it may belong to a different user or have expired).`):d.agentSessionsFailed(`managed session store error ${t}: ${mt(n)}`)}function Hr(e){let t=Br(e.agentName),n=e.sessionId??`ses_${crypto.randomUUID().replaceAll("-","")}`,r=e.options?.scope,o=e.options?.ttl,s=async c=>{let l=new URL(`${t}/${encodeURIComponent(n)}/messages`);c.first!==void 0&&l.searchParams.set("first",String(c.first)),c.cursor!==void 0&&l.searchParams.set("cursor",c.cursor),c.order!==void 0&&l.searchParams.set("order",c.order);let{status:u,body:p}=await Y("get",l.toString());if(u!==404){if(u===400&&c.cursor!==void 0)throw new I(`session.page(): ${mt(p)}`);return(u<200||u>=300)&&le(n,u,p),p}},i=c=>c.elements.length<2||c.elements[0].id>c.elements[1].id,a=async()=>{let c=[],l;for(;;){let u=await s({...l!==void 0?{cursor:l}:{}});if(u===void 0)return[];if(c.push(...u.elements.map(p=>p.message)),!u.pageInfo.hasNextPage||u.pageInfo.endCursor===null)break;l=u.pageInfo.endCursor}return c};return{id:n,async messages(c){let l=c?.limit;if(l===void 0)return a();let u=[],p;for(;u.length<l;){let m=await s({order:"desc",first:Math.min(l-u.length,ki),...p!==void 0?{cursor:p}:{}});if(m===void 0)return[];if(!i(m))return(await a()).slice(-l);if(u.push(...m.elements.map(g=>g.message)),!m.pageInfo.hasNextPage||m.pageInfo.endCursor===null)break;p=m.pageInfo.endCursor}return u.slice(0,l).reverse()},async page(c){let{limit:l,order:u,cursor:p}=Fe(c),m=await s({first:l,order:u,...p!==void 0?{cursor:p}:{}});if(m===void 0)return{messages:[],nextCursor:null};if(u==="desc"&&!i(m))throw d.agentSessionsFailed('the managed session store in this environment does not support newest-first paging yet \u2014 page with order: "asc", or read the latest messages with session.messages({ limit }).');return{messages:m.elements.map(g=>g.message),nextCursor:m.pageInfo.hasNextPage?m.pageInfo.endCursor:null}},async append(...c){if(c.length===0)return;let{status:l,body:u}=await Y("post",`${t}/${encodeURIComponent(n)}/messages`,{messages:c,...r!==void 0?{scope:r}:{},...o!==void 0?{ttl:o}:{}});(l<200||l>=300)&&le(n,l,u)},async clear(){for(let c=0;c<jr;c++){let{status:l,body:u}=await Y("delete",`${t}/${encodeURIComponent(n)}`);if(l===204||l===404)return;if(!(l===200&&u?.more===!0)){if(l===200)return;le(n,l,u)}}throw d.agentSessionsFailed(`clearing session "${n}" did not complete after ${jr} calls \u2014 call clear() again to continue.`)},async truncated(){let{status:c,body:l}=await Y("get",`${t}/${encodeURIComponent(n)}`);return c===404?!1:((c<200||c>=300)&&le(n,c,l),l.truncated===!0)},async pendingApprovals(){let{status:c,body:l}=await Y("get",`${t}/${encodeURIComponent(n)}`);return c===404?[]:((c<200||c>=300)&&le(n,c,l),l.pendingApprovals)},async addPendingApprovals(c){if(c.length===0)return;let{status:l,body:u}=await Y("post",`${t}/${encodeURIComponent(n)}/approvals`,{approvals:c});l!==204&&le(n,l,u)},async resolveApproval(c){let{status:l,body:u}=await Y("post",`${t}/${encodeURIComponent(n)}/approvals/${encodeURIComponent(c)}/resolve`);return(l<200||l>=300)&&le(n,l,u),u.status}}}async function Kr(e,t={}){let n=Br(e),r=new URL(n);t.first!==void 0&&r.searchParams.set("first",String(t.first)),t.cursor!==void 0&&r.searchParams.set("cursor",t.cursor);let{status:o,body:s}=await Y("get",r.toString());if(o===400)throw new I(mt(s));if(o<200||o>=300)throw d.agentSessionsFailed(`managed session store error ${o}: ${mt(s)}`);let i=s;return{sessions:i.elements.map(a=>({id:a.sessionId,createdAt:a.createdAt,lastActivityAt:a.lastActivityAt,messageCount:a.messageCount,pendingApprovals:a.pendingApprovalCount})),nextCursor:i.pageInfo.endCursor}}function qr(e){if(e?.scope!=="user")return;let t=mn.getStore()?.userId;if(typeof t!="string"||t.length===0)throw new I('This agent is user-scoped (memory.scope: "user") \u2014 it can only run in a user execution with a user identity (ctx.userId); schedules have none.');return t}function Vr(){return E().mode==="lambda"}function gt(e,t,n){let r=A(),o=r.agentSessions,s=qr(n);if(o?.store==="dynamodb"){let i=r.authentications??{},a=i[o.auth];if(!a)throw d.unknownAlias(o.auth,Object.keys(i));return $r({agentName:e,sessionId:t,authenticationId:a,table:o.table,region:o.region,options:n,...s!==void 0?{ownerUserId:s}:{}})}return Vr()?Hr({agentName:e,sessionId:t,options:n}):hr(e,t,n,s)}async function zr(e,t,n={}){if(t?.scope!=="user")throw new I(`agent.sessions() lists the calling user's sessions \u2014 the agent must declare memory.scope: "user".`);if(A().agentSessions?.store==="dynamodb")throw new I('agent.sessions() is not supported on the bring-your-own DynamoDB session store \u2014 use the managed store (agentSessions: { store: "managed" }).');let o=qr(t);return Vr()?Kr(e,n):wr(e,o,n)}var Xr=new Ti;function Mi(e){return({steps:t})=>t.reduce((n,r)=>n+r.toolCalls.length,0)>=e}function Yr(e,t,n,r){return F.startActiveSpan("agent.tool",{kind:Gt.INTERNAL,attributes:{agent:e,tool:t,...n}},async o=>{try{let s=await r();return o.setAttribute("status","success"),o.setStatus({code:Se.OK}),s}catch(s){throw o.setAttribute("status","error"),o.setStatus({code:Se.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o.end()}})}function Fi(e){let t={};for(let n of e.tools??[]){let r=n.needsApproval;t[n.name]=Jr({description:n.description,inputSchema:n.inputSchema,...r!==void 0?{needsApproval:typeof r=="function"?o=>r(o):r}:{},execute:o=>Yr(e.name,n.name,{},()=>n.execute(o,ze()))})}for(let n of e.agents??[]){let r=Me(n),o=`agent_${n.replaceAll("-","_")}`;t[o]=Jr({description:r.description,inputSchema:Gr.object({prompt:Gr.string().describe("The task or question for the agent")}),execute:({prompt:s})=>Yr(e.name,o,{delegateAgent:n},async()=>{let i=Xr.getStore()??0;return i>=Ut?{error:"delegation_depth_exceeded",message:`Delegation depth limit (${Ut}) reached \u2014 answer with what you have instead of delegating further.`}:(await Xr.run(i+1,()=>Bi(n).generate({prompt:s}))).text})})}return t}function Li(e){let t=[{model:e.model,auth:e.auth},...e.fallbacks??[]];return Dr(Mr(t.map(n=>qt(n.auth)(n.model))))}function Jt(e){return e.filter(t=>typeof t=="object"&&t!==null&&t.type==="tool-approval-request"&&!t.isAutomatic)}function Qr(e){return{approvalId:e.approvalId,toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input,requestedAt:new Date().toISOString()}}function Ni(e){return{id:e.approvalId,toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId,input:e.toolCall.input}}function Ui(e){let t=new Set;for(let n of e)if(Array.isArray(n.content))for(let r of Jt(n.content))t.add(r.approvalId);return t}function $i(e,t){let n=e.reduce((r,o)=>r+at(o.response.modelId??t,o.usage).amount,0);return{amount:Number(n.toFixed(8)),currency:"USD"}}async function ji(e,t,n){let r=[],o=[];if(n.approvals&&n.approvals.length>0){if(n.prompt!==void 0||(n.messages?.length??0)>0)throw new I("agent.generate() cannot combine `approvals` with `prompt` or `messages` \u2014 send the approvals on their own, then send new input on the next call.");let s=new Map((await e.pendingApprovals()).map(p=>[p.approvalId,p]));if(s.size===0&&t.length===0)throw new I(`Session "${e.id}" has no history and nothing awaiting approval \u2014 it does not exist, has expired, or belongs to a different user.`);let i=Ui(t),a=new Set(n.approvals.map(p=>p.id)),c=[...a].filter(p=>!s.has(p)&&!i.has(p));if(c.length>0)throw new I(`Unknown approval id(s) for session "${e.id}": ${c.join(", ")} \u2014 use the ids from \`pendingApprovals\` on the paused result.`);let l=[...s.keys()].filter(p=>!a.has(p));if(l.length>0)throw new I(`Session "${e.id}" has ${l.length} pending approval(s) not decided in this call: ${l.join(", ")} \u2014 decide every pending approval in one generate() call.`);let u=[];for(let p of n.approvals){let m=s.get(p.id);!m||await e.resolveApproval(p.id)==="already-resolved"||(o.push(m),u.push({type:"tool-approval-response",approvalId:p.id,approved:p.approved,...p.reason!==void 0?{reason:p.reason}:{}}))}u.length>0&&r.push({role:"tool",content:u})}if(n.prompt!==void 0?r.push({role:"user",content:n.prompt}):n.messages&&r.push(...n.messages),r.length===0)throw new I("agent.generate() requires `prompt`, `messages`, or `approvals` \u2014 nothing to do.");return{turn:r,claimed:o}}function Bi(e){let t=Me(e);ur(e);let n=dr(e),r=Li(t),o=Fi(t),s=t.limits?.maxIterations??mr,i=t.limits?.maxToolCalls??gr,a=t.memory?.maxSessionMessages??fr,c=l=>({model:r,system:n,tools:o,stopWhen:l.stopWhen??[_i(s),Mi(i)],...l.prepareStep!==void 0?{prepareStep:l.prepareStep}:{},...l.activeTools!==void 0?{activeTools:l.activeTools}:{},...l.toolChoice!==void 0?{toolChoice:l.toolChoice}:{},...l.providerOptions!==void 0?{providerOptions:l.providerOptions}:{}});return{model:r,tools:o,instructions:n,session(l){return gt(e,l,t.memory)},sessions(l){return zr(e,t.memory,l)},async generate(l){return F.startActiveSpan("agent.generate",{kind:Gt.INTERNAL,attributes:{agent:e,model:t.model}},async u=>{let p=gt(e,l.sessionId,t.memory);u.setAttribute("sessionId",p.id),O("hasAi");let m=[];try{let g=await Ht(p,a),S=await ji(p,g,l);m=S.claimed;let b;try{b=await Pi({...c(l),messages:[...g,...S.turn]})}catch(f){if(m.length>0)try{await p.addPendingApprovals(m),m=[]}catch(h){console.error(`[helix-sdk] agent "${e}" session "${p.id}": failed to restore ${m.length} pending approval(s) after a failed resume \u2014 ${h instanceof Error?h.message:String(h)}`)}throw f}let x=Jt(b.content),y=x.length>0?"awaiting-approval":"completed";return await p.append(...S.turn,...b.responseMessages),x.length>0&&await p.addPendingApprovals(x.map(Qr)),u.setAttributes({steps:b.steps.length,status:y}),u.setStatus({code:Se.OK}),Object.assign(b,{sessionId:p.id,status:y,...x.length>0?{pendingApprovals:x.map(Ni)}:{},helix:{cost:$i(b.steps,t.model),model:b.response.modelId??t.model}})}catch(g){throw u.setAttribute("status","error"),u.setStatus({code:Se.ERROR,message:g instanceof Error?g.message:String(g)}),g}finally{u.end()}})},async stream(l){let u=F.startSpan("agent.stream",{kind:Gt.INTERNAL,attributes:{agent:e,model:t.model}}),p=!1,m=(g,S)=>{p||(p=!0,u.setAttribute("status",g),u.setStatus(g==="error"?{code:Se.ERROR,...S!==void 0?{message:S}:{}}:{code:Se.OK}),u.end())};try{let g=gt(e,l.sessionId,t.memory);if(u.setAttribute("sessionId",g.id),O("hasAi"),l.approvals&&l.approvals.length>0)throw new I("agent.stream() does not accept approvals \u2014 resume paused runs with generate().");if(l.prompt===void 0&&!l.messages)throw new I("agent.stream() requires `prompt` or `messages`.");let S=l.prompt!==void 0?[{role:"user",content:l.prompt}]:[...l.messages],b=await Ht(g,a),x=Wr.with(Di.setSpan(Wr.active(),u),()=>Oi({...c(l),messages:[...b,...S],onFinish:async y=>{try{await g.append(...S,...y.responseMessages);let f=Jt(y.content);f.length>0&&await g.addPendingApprovals(f.map(Qr)),m(f.length>0?"awaiting-approval":"completed")}catch(f){let h=f instanceof Error?f.message:String(f);console.error(`[helix-sdk] agent "${e}" session "${g.id}": failed to persist the streamed turn \u2014 ${h}`),m("error",h)}},onError:({error:y})=>{m("error",y instanceof Error?y.message:String(y))},onAbort:()=>{m("error","stream aborted")}}));return Object.assign(x,{sessionId:g.id})}catch(g){throw m("error",g instanceof Error?g.message:String(g)),g}}}}var Zr="helix-schedule",Q=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function Wd(e){if(typeof e!="object"||e===null)throw new Q("expected a config object");let{cron:t,timezone:n="UTC",concurrent:r=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new Q("`cron` must be a non-empty string");let s=t.trim().split(/\s+/).length;if(s!==5)throw new Q(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${s} field(s) in "${t}"`);if(typeof n!="string"||!Hi(n))throw new Q(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(n)}"`);if(typeof r!="boolean")throw new Q("`concurrent` must be a boolean");if(typeof o!="function")throw new Q("`handler` must be a function");return Object.freeze({kind:Zr,cron:t.trim(),timezone:n,concurrent:r,handler:o})}function Xd(e){return typeof e=="object"&&e!==null&&e.kind===Zr&&typeof e.handler=="function"}function Hi(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 Ki}from"@opentelemetry/api";function yt(e,t,n){let r=F.startSpan("log",{kind:Ki.INTERNAL});r.setAttribute("message",t),r.setAttribute("level",e),n&&Kn(r.spanContext().spanId,"properties",n),r.end(),Tn(e,t,n)}function eo(){return{info:(e,t)=>yt("info",e,t),warn:(e,t)=>yt("warn",e,t),error:(e,t)=>yt("error",e,t),debug:(e,t)=>yt("debug",e,t)}}function ru(){try{return A().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import qi from"ky";import{context as Wt,trace as Vi,SpanKind as Ue,SpanStatusCode as no}from"@opentelemetry/api";async function to(e){Sn(e.url);let t=E(),{region:n}=A(),r={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}},{headers:o,deploymentId:s}=z(t);s&&(r.deploymentId=s);let i=bn(n,t.mode==="lambda"?"runtime":"dev"),a;try{a=await vn({signUrl:i,credentialHeaders:o,body:r,timeoutMs:e.timeout,executionId:t.executionId})}catch(c){let l=c instanceof Error?c.message??String(c):String(c);throw d.brokerError(0,l)}if(a.kind==="brokerError"){let c=a.code===pe?"credential broker does not support the s3 sign endpoint required by this SDK version \u2014 deploy a newer broker or pin an older SDK":a.message;throw d.brokerError(a.status,c,T(a.body),a.code)}return a.result}var zi=new Set([Ie,Ge,te,Re,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id"]);function Gi(e){let t=e.toLowerCase();return zi.has(t)||t.startsWith("x-tray-internal-")}async function Ji(e,t){let n=e instanceof Request?e:new Request(e,t),r=new URL(n.url);if(r.protocol!=="https:")throw d.unsupportedScheme(r.protocol.replace(/:$/,""));let o=E(),{region:s}=A(),{headers:i,deploymentId:a}=z(o),c=fe(s,o.mode==="lambda"?"runtime":"dev"),l=new Headers;for(let[g,S]of n.headers.entries())Gi(g)||l.append(g,S);l.set(Ie,n.url);for(let[g,S]of Object.entries(i))l.set(g,S);a&&l.set(te,a),o.executionId&&l.set(Re,o.executionId);let u={method:n.method,headers:l,redirect:"manual",signal:n.signal};n.body&&(u.body=n.body,u.duplex="half");let p;try{p=await fetch(c,u)}catch(g){throw g instanceof Error&&g.name==="AbortError"?g:d.brokerError(0,g instanceof Error?g.message:String(g))}let m=p.headers.get(Je);return m!==null&&zt(await hn(p,m)),p}var Wi=["get","post","put","patch","delete","head","options"],oo="[stream body omitted]";function so(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?oo: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 Xt(e){try{return new URL(e).hostname}catch{return e}}function ro(e,t,n,r,o){let s=Xt(t),i="externalApi",a={kind:Ue.CLIENT};return F.startActiveSpan(i,a,async c=>(c.setAttributes({method:e,host:s,"peer.service":r}),q(c,"request",{url:t,method:e,...n!==void 0?{body:so(n)}:{}}),o(c)))}function Ne(e,t,n){e.setAttribute("status",t),e.setStatus(t==="success"?{code:no.OK}:{code:no.ERROR,message:n}),e.end()}var Xi=16;async function Yi(e,t){let n=e.clone().body;return n?io(n,t):new Uint8Array(0)}async function io(e,t){let n=e.getReader(),r=[],o=0,s=0;try{for(;;){let{done:c,value:l}=await n.read();if(c)break;if(!l||l.byteLength===0){if(s+=1,s>=Xi)break;continue}s=0;let u=t+1-o;if(l.byteLength>=u){r.push(l.slice(0,u)),o+=u;break}r.push(l),o+=l.byteLength}}finally{n.cancel().catch(()=>{}),n.releaseLock()}let i=new Uint8Array(o),a=0;for(let c of r)i.set(c,a),a+=c.byteLength;return i}async function ao(e,t,n){if("kyResponse"in n)try{let r=await Yi(n.kyResponse,Ce),o=new TextDecoder("utf-8").decode(r,{stream:!0}),s;try{s=JSON.parse(o)}catch{s=o}q(e,"response",s)}catch{q(e,"response",{status:t})}else q(e,"response",so(n.bodyValue))}async function Qi(e,t){if(t instanceof ReadableStream){let n=e.body??t;try{let[r,o]=n.tee(),s=new Request(e,{body:r,duplex:"half"}),i=await io(o,Ce);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:oo}}}return typeof t=="string"?{body:t}:{}}function xu(){let e=qi.create({fetch:Ji,retry:{shouldRetry:({error:r})=>r instanceof d?!1:void 0}});function t(r){return(o,s)=>{let i=Wt.active(),a,c=!1,l=(p,m)=>{a&&!c&&(c=!0,Ne(a,p,m))},u=e.extend({hooks:{beforeRequest:[async(p,m)=>{let g=await Qi(p,m.body),S=g.body;if(a||(a=F.startSpan("externalApi",{kind:Ue.CLIENT},i)),a.setAttributes({method:p.method.toUpperCase(),host:Xt(p.url)}),q(a,"request",{url:p.url,method:p.method.toUpperCase(),...S!==void 0?{body:S}:{}}),c=!1,O("hasExternal"),g.request)return g.request}],beforeRetry:[p=>{l("error","retry"),a=void 0,c=!1}],afterResponse:[async(p,m,g)=>{a&&(a.setAttribute("statusCode",g.status),await ao(a,g.status,{kyResponse:g}),g.ok?l("success"):s?.throwHttpErrors===!1&&(O("hasError"),l("error",`HTTP ${g.status}`)))}],beforeError:[p=>(O("hasError"),l("error",p.message),p)]}});return a=F.startSpan("externalApi",{kind:Ue.CLIENT},i),a.setAttributes({method:r.toUpperCase(),host:Xt(String(o))}),Wt.with(Vi.setSpan(Wt.active(),a),()=>{let p=r==="options"?u(o,{...s,method:"OPTIONS"}):u[r](o,s);return p.catch(m=>{O("hasError"),l("error",m instanceof Error?m.message:String(m))}),p})}}let n=Object.fromEntries(Wi.map(r=>[r,t(r)]));return{...e,...n,authed(r){return Zi(r)}}}function Zi(e){let n=A().authentications??{};if(!n[e])throw d.unknownAlias(e,Object.keys(n));let r=n[e];function o(i){return(a,c={})=>{let l=i.toUpperCase();return ro(l,a,c.body,e,async u=>{O("hasAuth");let p=F.startSpan("auth",{kind:Ue.INTERNAL});p.setAttribute("alias",e),p.setAttribute("id",r),p.end();try{let m=ne({authenticationId:r,method:l,url:a,body:c.body,headers:c.headers,query:c.query}),g=await we(m,{timeout:c.timeout});return u.setAttribute("statusCode",g.status),await ao(u,g.status,{bodyValue:g.body}),Ne(u,"success"),g}catch(m){throw O("hasError"),m instanceof d&&m.detail.kind==="broker_error"&&m.detail.status>0&&u.setAttribute("statusCode",m.detail.status),Ne(u,"error",m instanceof Error?m.message:String(m)),m}})}}function s(i,a={}){let c=a.method??"GET";return ro(c,i,void 0,e,async l=>{O("hasAuth");let u=F.startSpan("auth",{kind:Ue.INTERNAL});u.setAttribute("alias",e),u.setAttribute("id",r),u.end();try{let p=await to({authenticationId:r,url:i,method:c,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return l.setAttribute("statusCode",200),Ne(l,"success"),p}catch(p){throw O("hasError"),p instanceof d&&p.detail.kind==="broker_error"&&p.detail.status>0&&l.setAttribute("statusCode",p.detail.status),Ne(l,"error",p instanceof Error?p.message:String(p)),p}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:s}}import{SpanKind as ca,SpanStatusCode as po}from"@opentelemetry/api";function $e(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var ea=18e4,co=ea-1e4,ta=2e3;async function lo(e,t,n){let r=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<co;){let i=await e(t,"DescribeStatement",{Id:n}),a=i.Status;if(r.has(a))return i;let c=Math.min(ta,200*2**s),l=c/2+Math.random()*(c/2),u=co-(Date.now()-o);await new Promise(p=>setTimeout(p,Math.min(l,u))),s++}throw d.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var na=new Set(["SELECT","WITH","SHOW"]),ra=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function oa(e){if(!e.clusterIdentifier&&!e.workgroupName)throw d.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw d.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw d.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw d.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw d.dbInvalidParameters("region is required")}function sa(e,t){let n=null;if(typeof t=="string")try{n=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(n=t);let r=typeof n?.__type=="string"?n.__type:void 0,o=typeof n?.message=="string"?n.message:void 0;if(r&&o)return d.dbQueryFailed(`${r}: ${o}`);let s=typeof t=="string"?re(t):T(t);return d.dbCallFailed(s)}function ia(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw d.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function aa(e,t){return typeof t!="number"||t<0?{}:na.has(e)?{rowsRead:t}:ra.has(e)?{rowsWritten:t}:{}}function uo(e){async function t(n,r,o){let s=ne({authenticationId:e,method:"POST",url:`https://redshift-data.${n}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${r}`}});try{let{status:i,body:a}=await we(s);if(i>=400)throw sa(i,a);return ia(a)}catch(i){if(i instanceof d)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw d.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:oa,async execute(n,r){let o=$e(r),s={Sql:r,Database:n.database,...n.clusterIdentifier&&{ClusterIdentifier:n.clusterIdentifier,DbUser:n.dbUser},...n.workgroupName&&{WorkgroupName:n.workgroupName},...n.statementName&&{StatementName:n.statementName}},i=await t(n.region,"ExecuteStatement",s),a=i,c=typeof a?.Id=="string"?a.Id:void 0;if(!c){let g=T(i);throw d.dbCallFailed(`ExecuteStatement response missing Id; got: ${g}`)}let l=await lo(t,n.region,c),u=l.Status;if(u==="FAILED"){let g=typeof l.Error=="string"?l.Error:"statement failed";throw d.dbQueryFailed(`${g} (statement: ${c})`)}if(u==="ABORTED")throw d.dbQueryFailed(`statement aborted (statement: ${c})`);let p=aa(o,l.ResultRows);return l.HasResultSet===!1?{result:{rowsAffected:l.ResultRows??0},metadata:p}:{result:await t(n.region,"GetStatementResult",{Id:c}),metadata:p}}}}var Yt=64*1024;function la(e){return e.length>Yt?`${e.slice(0,Yt)}...[truncated]`:e}function da(e,t,n,r,o){e.setAttributes({system:t.system,statement:o,namespace:n.database,operation:r})}function ua(e,t,n){let r=typeof t=="string"?t:JSON.stringify(t);return r.length>Yt?q(e,"result",{truncated:!0,size:r.length}):q(e,"result",t),n.rowsRead!==void 0&&e.setAttribute("rowsRead",n.rowsRead),n.rowsWritten!==void 0&&e.setAttribute("rowsWritten",n.rowsWritten),r}async function pa(e,t,n){let r=$e(n),o=la(n);return F.startActiveSpan("database",{kind:ca.CLIENT},async s=>{da(s,e,t,r,o);try{O("hasDb");let{result:i,metadata:a}=await e.execute(t,n),c=ua(s,i,a);return s.setAttribute("status","success"),s.setStatus({code:po.OK}),c}catch(i){O("hasError");let a=i instanceof Error?i.message:String(i);throw s.setAttribute("status","error"),s.setStatus({code:po.ERROR,message:a}),i}finally{s.end()}})}function fa(e){let n=A().authentications??{};if(!n[e])throw d.unknownAlias(e,Object.keys(n));let r=n[e],o=uo(r);function s(i,a){return o.validate(i),pa(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as wa}from"unstorage";var fo=1024,Qt=250*1024,ma=new TextEncoder,ga=/(^|\/)\.\.(\/|$)/,ya=/[?#]/,ha=/[\u0000-\u001F\u007F]/;function mo(e){if(e.length===0)throw d.kvKeyInvalid("Key must be a non-empty string");if(ga.test(e))throw d.kvKeyInvalid("Key contains path traversal segment");if(ya.test(e)||ha.test(e))throw d.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(n=>n===""))throw d.kvKeyInvalid("Key must not contain empty path segments");let t=ma.encode(e).length;if(t<1||t>fo)throw d.kvKeyInvalid(`Key must be between 1 and ${fo} UTF-8 bytes (got ${t})`)}function go(e){if(!Number.isInteger(e)||e<=0)throw d.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function yo(e){let t;try{t=JSON.stringify(e)}catch{throw d.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw d.kvValueInvalid("Value must be JSON-serializable");let n=Buffer.byteLength(t,"utf8");if(n>Qt)throw d.kvValueTooLarge(`Value exceeds maximum size of ${Qt} bytes (got ${n})`,Qt)}function je(e){mo(e)}function ht(e,t){let n=e[t];if(typeof n!="function")throw new Error(`KV driver is missing ${t}`);return n}function ho(e){let t=ht(e,"getItem"),n=ht(e,"setItem"),r=ht(e,"removeItem"),o=ht(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return je(i),t(i,a)},setItem(i,a,c){return je(i),n(i,a,c)},removeItem(i,a){return je(i),r(i,a)},hasItem(i,a){return je(i),o(i,a)},getKeys(i,a){return i.length>0&&je(i),s(i,a)}}}function wt(e){return wa({driver:ho(e)})}import{defineDriver as Sa}from"unstorage";function ba(e){try{return JSON.parse(e)}catch{return e}}var va=Sa(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(n){let r=await t.get(n);return r===null?null:JSON.stringify(r)},async setItem(n,r,o){let s=o?.ttl,i=ba(r);s!==void 0?await t.set(n,i,{ttl:s}):await t.set(n,i)},async removeItem(n){await t.delete(n)},async hasItem(n){return await t.has(n)},async getKeys(){throw new Error("KV key listing is not supported")}}});function wo(e){return va({client:e})}import Ea from"ky";import{z as _}from"zod";function So(e){return j(e).hosts.api}function xa(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function Aa(e){return e.split("/").map(encodeURIComponent).join("/")}function Be(e,t,n){return`${e}${xa(t)}/${Aa(n)}`}var Ia=6e4,Zt=_.lazy(()=>_.union([_.string(),_.number(),_.boolean(),_.null(),_.array(Zt),_.record(_.string(),Zt)])),Ra=_.object({projectId:_.string(),key:_.string(),value:Zt,type:_.enum(["string","number","boolean","null","array","object"]),organizationId:_.string(),scope:_.string(),createdBy:_.string(),createdAt:_.number(),updatedBy:_.string(),updatedAt:_.number()});function ka(){let e=ue(),t=$(),n=!!(e&&e.trim().length>0),r=!!(t&&t.trim().length>0);if(!n&&!r)throw d.missingExecutionCredentials();let o={Accept:"application/json"};return n&&(o[de]=e),r&&(o[U]=t),o}function Ca(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 St(e,t){throw d.kvCallFailed(e,Ca(t),T(t))}async function bt(e,t,n={}){try{let r=await Ea(t,{method:e,headers:ka(),...n.json!==void 0?{json:n.json}:{},throwHttpErrors:!1,timeout:Ia}),o=e==="head"?void 0:await H(r);return{status:r.status,body:o}}catch(r){if(r instanceof d)throw r;let o=r instanceof Error?r.message??String(r):String(r);throw d.kvCallFailed(0,o)}}function bo(e){let t=So(e.env),{projectId:n}=e;return{async get(r){let{status:o,body:s}=await bt("get",Be(t,n,r));if(o===404)return null;(o<200||o>=300)&&St(o,s);let i=Ra.safeParse(s);if(!i.success)throw d.kvCallFailed(o,"platform returned malformed KeyValueEntry",T(s));return i.data.value},async set(r,o,s){let{status:i,body:a}=await bt("put",Be(t,n,r),{json:s?.ttl!==void 0?{value:o,ttl:s.ttl}:{value:o}});(i<200||i>=300)&&St(i,a)},async delete(r){let{status:o,body:s}=await bt("delete",Be(t,n,r));o!==204&&St(o,s)},async has(r){let{status:o,body:s}=await bt("head",Be(t,n,r));if(o===200)return!0;if(o===404)return!1;St(o,s)}}}function vt(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,n,r)=>{let o=r?.ttl;yo(n),typeof o=="number"&&go(o),await e.setItem(t,n,o!==void 0?{ttl:o}:void 0)}}}function Ta(){let e=A();if(e.kind!=="provisioned")throw d.kvRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function vo(e){let t=Ta(),n=e??bo(t),r=wt(wo(n));return vt(r)}import{defineDriver as Pa}from"unstorage";var Oa=Pa(e=>{let t=new Map;function n(r){let o=t.get(r);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(r);return}return o}return{name:"memory-ttl",getItem(r){return n(r)?.value??null},setItem(r,o,s){let i=s?.ttl,a=n(r),c=typeof i=="number"?Date.now()+i*1e3:i===null?void 0:a?.expiresAt;t.set(r,{value:o,expiresAt:c})},removeItem(r){t.delete(r)},hasItem(r){return n(r)!==void 0},getKeys(){return[...t.keys()].filter(r=>n(r)!==void 0)},clear(){t.clear()}}});function xo(){return Oa({})}var en;function _a(){return en||(en=wt(xo())),en}function Ao(){return vt(_a())}function Da(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":E().mode==="lambda"}function Rp(){return Da()?vo():Ao()}import{createHash as La}from"crypto";import{mkdir as Na,readFile as Co,readdir as To,rm as Io,unlink as Ua,writeFile as Ro}from"fs/promises";import{dirname as $a}from"path";async function Ma(e){let t=e.getReader(),n=[],r=0;for(;;){let{done:o,value:s}=await t.read();if(o)break;if(s){if(r+=s.byteLength,r>G)throw await t.cancel(),d.filesValueTooLarge(`File exceeds maximum size of ${G} bytes (got more than ${G})`,G);n.push(s)}}return Buffer.concat(n)}async function be(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?Ma(e):Buffer.from(e)}var Fa={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"},Eo="application/octet-stream";function xt(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return Eo;let n=e.slice(t+1).toLowerCase();return Fa[n]??Eo}function xe(){let e=E().projectRoot;if(!e)throw d.filesNotAvailable();return e}async function ve(e){try{return await e()}catch(t){if(t instanceof d)throw t;let n=t?.code;throw n?d.filesCallFailed(0,`Local file storage operation failed: ${n}`):d.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function At(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function tn(e){try{let t=await Co(rt(xe(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function ko(e){await Na($a(e),{recursive:!0})}async function ja(e,t){let n=ot(e,t),r;try{r=await To(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function Po(e,t){let n=ot(e,t),r;try{r=await To(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return[];throw s}let o=[];for(let s of r){let i=t.length===0?s.name:`${t}/${s.name}`;s.isDirectory()?o.push(...await Po(e,i)):s.isFile()&&o.push(i)}return o}function Oo(){return{async put(e,t,n){return ve(async()=>{let r=xe(),o=await be(t),s=n?.contentType??xt(e),i=La("sha1").update(o).digest("hex"),a=new Date,c=De(r,e);await ko(c),await Ro(c,o);let l={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},u=rt(r,e);return await ko(u),await Ro(u,JSON.stringify(l)),At(e,l)})},async get(e){return ve(async()=>{let t=await tn(e);return t?{data:await Co(De(xe(),e)),metadata:At(e,t)}:null})},async head(e){return ve(async()=>{let t=await tn(e);return t?At(e,t):null})},async delete(e){return ve(async()=>{let t=xe();await Promise.all([De(t,e),rt(t,e)].map(async n=>{try{await Ua(n)}catch(r){if(r.code!=="ENOENT")throw r}}))})},async deleteMany(e){return ve(async()=>{let t=xe(),n=await Po(t,e);return await Promise.all([Io(ot(t,e),{recursive:!0,force:!0}),Io(Xn(t,e),{recursive:!0,force:!0})]),{deleted:n.length}})},async list(e,t){return ve(async()=>{let n=xe(),r=t?.limit??100,s=(await ja(n,e??"")).slice(0,r);return{files:(await Promise.all(s.map(async a=>{let c=await tn(a);return c?At(a,c):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let n=E().devServerUrl;if(!n)throw d.filesNotAvailable();return{url:`${n}/_helix/files/${e}`,expiresAt:ge(t?.expiresIn)}},async getDownloadUrl(e,t){let n=E().devServerUrl;if(!n)throw d.filesNotAvailable();return{url:`${n}/_helix/files/${e}`,expiresAt:ge(t?.expiresIn)}}}}import{createHash as Ga}from"crypto";function Et(e){return j(e).hosts.api}function Ba(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function He(e,t){return`${e}${Ba(t)}`}function Ae(e,t,n){return`${He(e,t)}/${encodeURIComponent(n)}`}function It(e,t,n){return`${Ae(e,t,n)}/upload`}function _o(e,t,n){return`${Ae(e,t,n)}/download`}function Do(e,t,n){return`${Ae(e,t,n)}/signed-url`}function Mo(e,t,n,r){let o=new URLSearchParams({name:r});return n&&o.set("parentFolder",n),`${He(e,t)}/file?${o.toString()}`}function Fo(e,t,n,r){let o=new URLSearchParams({limit:String(r)});return n&&o.set("id",n),`${He(e,t)}?${o.toString()}`}import rn from"ky";import{z as D}from"zod";var on=6e4,Lo=D.object({id:D.string(),workspaceId:D.string(),projectId:D.string(),parentFolder:D.string().nullable().optional(),name:D.string(),size:D.number().nullable().optional(),objectType:D.enum(["Folder","File"]),contentType:D.string().nullable().optional(),createdAt:D.string(),updatedAt:D.string()}),Ha=D.object({signedURL:D.string()}),Ka=D.object({path:D.array(D.object({id:D.string(),name:D.string()})),elements:D.array(Lo)});function sn(){let e=ue(),t=$(),n=!!(e&&e.trim().length>0),r=!!(t&&t.trim().length>0);if(!n&&!r)throw d.missingExecutionCredentials();let o={Accept:"application/json"};return n&&(o[de]=e),r&&(o[U]=t),o}function No(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Z(e,t){throw d.filesCallFailed(e,No(t),T(t))}function qa(e,t){return e===400&&No(t).toLowerCase()==="resource not found"}async function Va(e){let t=new Response(e),n=t.headers.get("content-type")??"multipart/form-data",r=await t.arrayBuffer();return{body:Buffer.from(r),contentType:n}}async function Ee(e,t,n={}){try{let r=await rn(t,{method:e,headers:sn(),...n.json!==void 0?{json:n.json}:{},throwHttpErrors:!1,timeout:on}),o=await H(r);return{status:r.status,body:o}}catch(r){if(r instanceof d)throw r;let o=r instanceof Error?r.message:String(r);throw d.filesCallFailed(0,o)}}function nn(e,t){let n=Lo.safeParse(t);if(!n.success)throw d.filesCallFailed(e,"platform returned malformed ObjectMetadata",T(t));return n.data}function Uo(e){let t=Et(e.env),{projectId:n}=e;return{async createMetadata(r){let{status:o,body:s}=await Ee("post",He(t,n),{json:r});return(o<200||o>=300)&&Z(o,s),nn(o,s)},async getByName(r,o){let{status:s,body:i}=await Ee("get",Mo(t,n,r,o));return s===404||qa(s,i)?null:((s<200||s>=300)&&Z(s,i),nn(s,i))},async getById(r){let{status:o,body:s}=await Ee("get",Ae(t,n,r));return o===404?null:((o<200||o>=300)&&Z(o,s),nn(o,s))},async listChildren(r,o){let{status:s,body:i}=await Ee("get",Fo(t,n,r,o));(s<200||s>=300)&&Z(s,i);let a=Ka.safeParse(i);if(!a.success)throw d.filesCallFailed(s,"platform returned malformed listing",T(i));return a.data},async uploadContent(r,o,s,i){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:i}),s);let{body:c,contentType:l}=await Va(a),u;try{u=await rn(It(t,n,r),{method:"post",headers:{...sn(),"content-type":l},body:new Uint8Array(c),throwHttpErrors:!1,timeout:on})}catch(m){if(m instanceof d)throw m;let g=m instanceof Error?m.message:String(m);throw d.filesCallFailed(0,g)}let p=await H(u);(u.status<200||u.status>=300)&&Z(u.status,p)},async downloadContent(r){let o;try{o=await rn(_o(t,n,r),{method:"get",headers:sn(),throwHttpErrors:!1,timeout:on})}catch(i){if(i instanceof d)throw i;let a=i instanceof Error?i.message:String(i);throw d.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await H(o);Z(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(r){let{status:o,body:s}=await Ee("get",Do(t,n,r));(o<200||o>=300)&&Z(o,s);let i=Ha.safeParse(s);if(!i.success)throw d.filesCallFailed(o,"platform returned malformed signed URL response",T(s));return i.data.signedURL},async deleteById(r){let{status:o,body:s}=await Ee("delete",Ae(t,n,r));o===204||o===404||(o<200||o>=300)&&Z(o,s)}}}function an(e){return e.split("/").filter(t=>t.length>0)}function cn(e){return e instanceof d&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function za(e,t,n){let r=await e.getByName(t,n);if(r)return r;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:n})}catch(o){if(cn(o)){let s=await e.getByName(t,n);if(s)return s}throw o}}async function ln(e,t){let n=an(t),r=n[n.length-1],o;for(let s of n.slice(0,-1))o=(await za(e,o,s)).id;return{parentFolder:o,name:r}}async function Ke(e,t){let n=an(t),r=n[n.length-1],o;for(let s of n.slice(0,-1)){let i=await e.getByName(o,s);if(!i||i.objectType!=="Folder")return null;o=i.id}return{parentFolder:o,name:r}}async function dn(e,t){if(t.length===0)return;let n=an(t),r;for(let o of n){let s=await e.getByName(r,o);if(!s||s.objectType!=="Folder")return null;r=s.id}return r}var Ja=500,Wa=8;async function Xa(e,t,n){let r=new Array(e.length),o=0;async function s(){for(;o<e.length;){let i=o++;r[i]=await n(e[i])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},s)),r}function Ya(){let e=A();if(e.kind!=="provisioned")throw d.filesRequiresProvisioning();return{projectId:e.projectId,env:e.region}}function Qa(e){return Ga("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Rt(e,t,n){return{path:e,size:t.size??0,contentType:t.contentType??n??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Qa(t)}}async function $o(e,t,n,r){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:r,name:n})}catch(o){if(cn(o)){let s=await e.getByName(t,n);if(s)return s}throw o}}async function jo(e,t){let{elements:n}=await e.listChildren(t,Ja);return(await Xa(n,Wa,async o=>{let s=o.objectType==="Folder"?await jo(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function Bo(e){let t=Ya(),n=e??Uo(t),r=Et(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:c,name:l}=await ln(n,s),u=await be(i),p=a?.contentType??xt(s),m=await n.getByName(c,l);if(m&&m.objectType!=="File")throw d.filesCallFailed(409,`A folder already exists at "${s}"`);let g=m??await $o(n,c,l,p);await n.uploadContent(g.id,u,l,p);let S=await n.getById(g.id);return Rt(s,S??g,p)},async get(s){let i=await Ke(n,s);if(!i)return null;let a=await n.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:{data:await n.downloadContent(a.id),metadata:Rt(s,a)}},async head(s){let i=await Ke(n,s);if(!i)return null;let a=await n.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:Rt(s,a)},async delete(s){let i=await Ke(n,s);if(!i)return;let a=await n.getByName(i.parentFolder,i.name);a&&await n.deleteById(a.id)},async deleteMany(s){let i=await dn(n,s);if(i===null)return{deleted:0};let a=await jo(n,i);return s.length>0&&i!==void 0&&await n.deleteById(i),{deleted:a}},async list(s,i){let a=await dn(n,s??"");if(a===null)return{files:[],cursor:null};let c=i?.limit??100,{elements:l}=await n.listChildren(a,c);return{files:l.filter(p=>p.objectType==="File").map(p=>Rt(s?`${s}/${p.name}`:p.name,p)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:c}=await ln(n,s),u=await n.getByName(a,c)??await $o(n,a,c,i?.contentType);return{url:It(r,o,u.id),expiresAt:ge(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await Ke(n,s),c=a?await n.getByName(a.parentFolder,a.name):null;if(!c||c.objectType!=="File")throw d.filesCallFailed(404,`File not found: ${s}`);return{url:await n.getSignedDownloadUrl(c.id),expiresAt:ge(i?.expiresIn)}}}}function un(e,t){let n=t?.maxPathBytes;return{async put(r,o,s){ie(r,n);let i=await be(o);return Jn(i.byteLength),e.put(r,i,s)},async get(r){return ie(r,n),e.get(r)},async head(r){return ie(r,n),e.head(r)},async delete(r){return ie(r,n),e.delete(r)},async deleteMany(r){let o=Ft(r);return tt(o,n),e.deleteMany(o)},async list(r,o){let s=Ft(r??"");return tt(s,n),e.list(s,o)},async getUploadUrl(r,o){return ie(r,n),e.getUploadUrl(r,o)},async getDownloadUrl(r,o){return ie(r,n),e.getDownloadUrl(r,o)}}}function Za(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":E().mode==="lambda"}function Sf(){if(Za())return un(Bo());let e=E().projectRoot;return un(Oo(),{maxPathBytes:e?Wn(e):void 0})}import tc from"ky";function Ho(e){return j(e).hosts.api}function ec(){return"/private/v1/helix/function-calls"}function Ko(e){return`${e}${ec()}`}var nc=5e3;function rc(){let e=$();if(!!!(e&&e.trim().length>0))throw d.callFunctionMissingExecutionJwt();return{Accept:"application/json",[U]:e}}function oc(e,t){throw d.callFunctionCallFailed(e,sc(t),T(t))}function sc(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 qo(e){let t=Ho(e.env);return{async callAsync(n,r){let o,s;try{let i=await tc(Ko(t),{method:"post",headers:rc(),json:{functionPath:n,input:r},throwHttpErrors:!1,timeout:nc});o=i.status,s=await H(i)}catch(i){if(i instanceof d)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw d.callFunctionCallFailed(0,a)}(o<200||o>=300)&&oc(o,s)}}}var Vo=1024;function kt(e){if(typeof e!="string"||e.trim().length===0)throw d.callFunctionPathInvalid("functionPath must be a non-empty string");if(e.length>Vo)throw d.callFunctionPathInvalid(`functionPath must be at most ${Vo} characters`)}function ic(){let e=A();if(e.kind!=="provisioned")throw d.callFunctionRequiresProvisioning();return{env:e.region}}function zo(e){return async function(n,r){kt(n),await(e??qo(ic())).callAsync(n,r)}}function Go(){return async function(t,n){kt(t);let r=E().devServerUrl;if(!r)throw d.callFunctionNotAvailable();let o=t.startsWith("/")?t:`/${t}`,s=eo();fetch(`${r}${o}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n??{})}).then(i=>{i.ok||s.warn("ctx.callFunctionAsync: dev-mode dispatch returned a non-2xx response",{functionPath:t,status:i.status})}).catch(i=>{s.warn("ctx.callFunctionAsync: dev-mode dispatch failed",{functionPath:t,error:i instanceof Error?i.message:String(i)})})}}function ac(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":E().mode==="lambda"}function Vf(){return ac()?zo():Go()}export{cc as a,lc as b,dc as c,A as d,uc as e,Hn as f,ys as g,O as h,q as i,vs as j,xs as k,F as l,As as m,$c as n,eo as o,ru as p,xu as q,fa as r,Rp as s,ie as t,De as u,rt as v,Sf as w,Vf as x,Ls as y,Jc as z,Lt as A,er as B,tr as C,nr as D,it as E,rr as F,rl as G,ir as H,Nt as I,Bs as J,qs as K,Vs as L,ol as M,zs as N,sl as O,ed as P,ar as Q,ll as R,cr as S,I as T,gl as U,yl as V,Me as W,hl as X,wl as Y,pr as Z,Al as _,El as $,X as aa,kl as ba,Mi as ca,Bi as da,Zr as ea,Q as fa,Wd as ga,Xd as ha};