@trayai/helix-sdk 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
- import { z } from 'zod';
1
+ import { z, ZodType } from 'zod';
2
+ import { P as PlatformContext } from './types-Ci9SeHOE.js';
2
3
 
3
4
  interface SdkRuntimeConfig {
4
5
  /**
@@ -58,6 +59,38 @@ declare function getSdkConfig(): Readonly<SdkRuntimeConfig>;
58
59
 
59
60
  declare const projectIdSchema: z.ZodString;
60
61
  declare const workspaceIdSchema: z.ZodString;
62
+ /**
63
+ * Agent session storage (helix-spec 14 → Sessions & Memory → Pluggable
64
+ * Backend). v1 supports only the bring-your-own-DynamoDB backend — the
65
+ * managed Helix session store does not exist yet, so `store: "dynamodb"` is
66
+ * currently the only durable option (in-memory otherwise). The table is
67
+ * accessed through the credentials broker with the named authentication's
68
+ * AWS credentials; no keys in the runtime.
69
+ */
70
+ declare const agentSessionsSchema: z.ZodDiscriminatedUnion<"store", [z.ZodObject<{
71
+ store: z.ZodLiteral<"managed">;
72
+ }, "strip", z.ZodTypeAny, {
73
+ store: "managed";
74
+ }, {
75
+ store: "managed";
76
+ }>, z.ZodObject<{
77
+ store: z.ZodLiteral<"dynamodb">;
78
+ /** Authentication alias (from `authentications`) holding AWS credentials. */
79
+ auth: z.ZodString;
80
+ table: z.ZodString;
81
+ region: z.ZodString;
82
+ }, "strip", z.ZodTypeAny, {
83
+ auth: string;
84
+ store: "dynamodb";
85
+ table: string;
86
+ region: string;
87
+ }, {
88
+ auth: string;
89
+ store: "dynamodb";
90
+ table: string;
91
+ region: string;
92
+ }>]>;
93
+ type AgentSessionsConfig = z.infer<typeof agentSessionsSchema>;
61
94
  /**
62
95
  * AI provider declaration (helix-spec 11). The Vercel AI SDK builds
63
96
  * provider-native requests client-side, so `ctx.ai(alias)` must know which
@@ -116,6 +149,29 @@ declare const trayConfigSchema: z.ZodEffects<z.ZodObject<{
116
149
  env: z.ZodOptional<z.ZodLiteral<"production">>;
117
150
  authentications: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
118
151
  config: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
152
+ agentSessions: z.ZodOptional<z.ZodDiscriminatedUnion<"store", [z.ZodObject<{
153
+ store: z.ZodLiteral<"managed">;
154
+ }, "strip", z.ZodTypeAny, {
155
+ store: "managed";
156
+ }, {
157
+ store: "managed";
158
+ }>, z.ZodObject<{
159
+ store: z.ZodLiteral<"dynamodb">;
160
+ /** Authentication alias (from `authentications`) holding AWS credentials. */
161
+ auth: z.ZodString;
162
+ table: z.ZodString;
163
+ region: z.ZodString;
164
+ }, "strip", z.ZodTypeAny, {
165
+ auth: string;
166
+ store: "dynamodb";
167
+ table: string;
168
+ region: string;
169
+ }, {
170
+ auth: string;
171
+ store: "dynamodb";
172
+ table: string;
173
+ region: string;
174
+ }>]>>;
119
175
  aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
120
176
  service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
121
177
  baseUrl: z.ZodOptional<z.ZodString>;
@@ -142,22 +198,38 @@ declare const trayConfigSchema: z.ZodEffects<z.ZodObject<{
142
198
  name: string;
143
199
  authentications: Record<string, string>;
144
200
  config: Record<string, unknown>;
201
+ region?: string | undefined;
145
202
  projectId?: string | undefined;
146
203
  workspaceId?: string | undefined;
147
- region?: string | undefined;
148
204
  env?: "production" | undefined;
205
+ agentSessions?: {
206
+ store: "managed";
207
+ } | {
208
+ auth: string;
209
+ store: "dynamodb";
210
+ table: string;
211
+ region: string;
212
+ } | undefined;
149
213
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
150
214
  service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
151
215
  baseUrl?: string | undefined;
152
216
  }> | undefined;
153
217
  }, {
154
218
  name: string;
219
+ region?: string | undefined;
155
220
  projectId?: string | undefined;
156
221
  workspaceId?: string | undefined;
157
- region?: string | undefined;
158
222
  env?: "production" | undefined;
159
223
  authentications?: Record<string, string> | undefined;
160
224
  config?: Record<string, unknown> | undefined;
225
+ agentSessions?: {
226
+ store: "managed";
227
+ } | {
228
+ auth: string;
229
+ store: "dynamodb";
230
+ table: string;
231
+ region: string;
232
+ } | undefined;
161
233
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
162
234
  service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
163
235
  baseUrl?: string | undefined;
@@ -169,18 +241,34 @@ declare const trayConfigSchema: z.ZodEffects<z.ZodObject<{
169
241
  config: Record<string, unknown>;
170
242
  projectId?: string | undefined;
171
243
  workspaceId?: string | undefined;
244
+ agentSessions?: {
245
+ store: "managed";
246
+ } | {
247
+ auth: string;
248
+ store: "dynamodb";
249
+ table: string;
250
+ region: string;
251
+ } | undefined;
172
252
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
173
253
  service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
174
254
  baseUrl?: string | undefined;
175
255
  }> | undefined;
176
256
  }, {
177
257
  name: string;
258
+ region?: string | undefined;
178
259
  projectId?: string | undefined;
179
260
  workspaceId?: string | undefined;
180
- region?: string | undefined;
181
261
  env?: "production" | undefined;
182
262
  authentications?: Record<string, string> | undefined;
183
263
  config?: Record<string, unknown> | undefined;
264
+ agentSessions?: {
265
+ store: "managed";
266
+ } | {
267
+ auth: string;
268
+ store: "dynamodb";
269
+ table: string;
270
+ region: string;
271
+ } | undefined;
184
272
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
185
273
  service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
186
274
  baseUrl?: string | undefined;
@@ -200,6 +288,29 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
200
288
  region: z.ZodEffects<z.ZodString, string, string>;
201
289
  authentications: z.ZodRecord<z.ZodString, z.ZodString>;
202
290
  config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
291
+ agentSessions: z.ZodOptional<z.ZodDiscriminatedUnion<"store", [z.ZodObject<{
292
+ store: z.ZodLiteral<"managed">;
293
+ }, "strip", z.ZodTypeAny, {
294
+ store: "managed";
295
+ }, {
296
+ store: "managed";
297
+ }>, z.ZodObject<{
298
+ store: z.ZodLiteral<"dynamodb">;
299
+ /** Authentication alias (from `authentications`) holding AWS credentials. */
300
+ auth: z.ZodString;
301
+ table: z.ZodString;
302
+ region: z.ZodString;
303
+ }, "strip", z.ZodTypeAny, {
304
+ auth: string;
305
+ store: "dynamodb";
306
+ table: string;
307
+ region: string;
308
+ }, {
309
+ auth: string;
310
+ store: "dynamodb";
311
+ table: string;
312
+ region: string;
313
+ }>]>>;
203
314
  aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
204
315
  service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
205
316
  baseUrl: z.ZodOptional<z.ZodString>;
@@ -227,24 +338,40 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
227
338
  projectId: z.ZodString;
228
339
  }, "strip", z.ZodTypeAny, {
229
340
  kind: "provisioned";
341
+ region: string;
230
342
  name: string;
231
343
  projectId: string;
232
- region: string;
233
344
  authentications: Record<string, string>;
234
345
  config: Record<string, unknown>;
235
346
  workspaceId?: string | undefined;
347
+ agentSessions?: {
348
+ store: "managed";
349
+ } | {
350
+ auth: string;
351
+ store: "dynamodb";
352
+ table: string;
353
+ region: string;
354
+ } | undefined;
236
355
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
237
356
  service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
238
357
  baseUrl?: string | undefined;
239
358
  }> | undefined;
240
359
  }, {
241
360
  kind: "provisioned";
361
+ region: string;
242
362
  name: string;
243
363
  projectId: string;
244
- region: string;
245
364
  authentications: Record<string, string>;
246
365
  config: Record<string, unknown>;
247
366
  workspaceId?: string | undefined;
367
+ agentSessions?: {
368
+ store: "managed";
369
+ } | {
370
+ auth: string;
371
+ store: "dynamodb";
372
+ table: string;
373
+ region: string;
374
+ } | undefined;
248
375
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
249
376
  service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
250
377
  baseUrl?: string | undefined;
@@ -255,6 +382,29 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
255
382
  region: z.ZodEffects<z.ZodString, string, string>;
256
383
  authentications: z.ZodRecord<z.ZodString, z.ZodString>;
257
384
  config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
385
+ agentSessions: z.ZodOptional<z.ZodDiscriminatedUnion<"store", [z.ZodObject<{
386
+ store: z.ZodLiteral<"managed">;
387
+ }, "strip", z.ZodTypeAny, {
388
+ store: "managed";
389
+ }, {
390
+ store: "managed";
391
+ }>, z.ZodObject<{
392
+ store: z.ZodLiteral<"dynamodb">;
393
+ /** Authentication alias (from `authentications`) holding AWS credentials. */
394
+ auth: z.ZodString;
395
+ table: z.ZodString;
396
+ region: z.ZodString;
397
+ }, "strip", z.ZodTypeAny, {
398
+ auth: string;
399
+ store: "dynamodb";
400
+ table: string;
401
+ region: string;
402
+ }, {
403
+ auth: string;
404
+ store: "dynamodb";
405
+ table: string;
406
+ region: string;
407
+ }>]>>;
258
408
  aiProviders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere"]>, z.ZodEffects<z.ZodEffects<z.ZodObject<{
259
409
  service: z.ZodEnum<["openai", "anthropic", "google", "mistral", "cohere", "openai-compatible"]>;
260
410
  baseUrl: z.ZodOptional<z.ZodString>;
@@ -281,22 +431,38 @@ declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObje
281
431
  kind: z.ZodLiteral<"unprovisioned">;
282
432
  }, "strip", z.ZodTypeAny, {
283
433
  kind: "unprovisioned";
284
- name: string;
285
434
  region: string;
435
+ name: string;
286
436
  authentications: Record<string, string>;
287
437
  config: Record<string, unknown>;
288
438
  workspaceId?: string | undefined;
439
+ agentSessions?: {
440
+ store: "managed";
441
+ } | {
442
+ auth: string;
443
+ store: "dynamodb";
444
+ table: string;
445
+ region: string;
446
+ } | undefined;
289
447
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
290
448
  service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
291
449
  baseUrl?: string | undefined;
292
450
  }> | undefined;
293
451
  }, {
294
452
  kind: "unprovisioned";
295
- name: string;
296
453
  region: string;
454
+ name: string;
297
455
  authentications: Record<string, string>;
298
456
  config: Record<string, unknown>;
299
457
  workspaceId?: string | undefined;
458
+ agentSessions?: {
459
+ store: "managed";
460
+ } | {
461
+ auth: string;
462
+ store: "dynamodb";
463
+ table: string;
464
+ region: string;
465
+ } | undefined;
300
466
  aiProviders?: Record<string, "openai" | "anthropic" | "google" | "mistral" | "cohere" | {
301
467
  service: "openai" | "anthropic" | "google" | "mistral" | "cohere" | "openai-compatible";
302
468
  baseUrl?: string | undefined;
@@ -380,4 +546,248 @@ type WorkspaceIdRequiredError = Error & {
380
546
  */
381
547
  declare function requireWorkspaceId(config: LoadedTrayConfig): string;
382
548
 
383
- 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 };
549
+ /**
550
+ * `defineTool` (helix-spec 12) — the subset agents consume (helix-spec 14).
551
+ *
552
+ * **Beta.** Agents and tools are in beta: this API may change in a future
553
+ * release without a major version bump.
554
+ *
555
+ * A tool is a *definition*: name, description, input schema, approval policy,
556
+ * and handler together in one default export. Tools are:
557
+ *
558
+ * - invoked **in-process** by importing the definition and calling it — the
559
+ * handler runs inside the current execution with the caller's context (via
560
+ * getContext()), input validated against the schema;
561
+ * - given to agents via `defineAgent({ tools: [...] })`, where the agent
562
+ * runtime compiles them to AI SDK tools (the same validation + handler,
563
+ * `needsApproval` compiled to the loop's native approval mechanism).
564
+ *
565
+ * MCP exposure (spec 12's `mcp.tools`) is not built yet — tools exist today
566
+ * for in-process use and agents.
567
+ */
568
+ declare const TOOL_DEFINITION_KIND = "helix-tool";
569
+ interface DefineToolConfig<TSchema extends ZodType = ZodType> {
570
+ /** Tool name (snake_case convention). */
571
+ name: string;
572
+ /** Human-readable description for AI agents. */
573
+ description: string;
574
+ /** Input schema (Zod), validated before the handler runs. */
575
+ input: TSchema;
576
+ /**
577
+ * Require human approval before an agent may execute this tool — boolean,
578
+ * or an (optionally async) predicate of the validated input. Enforced in
579
+ * agent loops (the loop pauses; see ctx.agent). Direct in-process
580
+ * invocation is not gated — calling the tool yourself is the confirmation.
581
+ */
582
+ needsApproval?: boolean | ((input: z.infer<TSchema>) => boolean | Promise<boolean>);
583
+ /** Handler — receives the caller's ctx with `input` validated and typed. */
584
+ handler: (ctx: PlatformContext & {
585
+ input: z.infer<TSchema>;
586
+ }) => Promise<unknown> | unknown;
587
+ }
588
+ interface HelixTool<TSchema extends ZodType = ZodType> {
589
+ /** In-process invocation: validate input, run handler with the caller's ctx. */
590
+ (input: z.infer<TSchema>): Promise<unknown>;
591
+ readonly kind: typeof TOOL_DEFINITION_KIND;
592
+ readonly name: string;
593
+ readonly description: string;
594
+ readonly inputSchema: TSchema;
595
+ readonly needsApproval?: DefineToolConfig<TSchema>["needsApproval"];
596
+ /** Validate + execute with an explicit ctx (used by the agent runtime). */
597
+ readonly execute: (input: unknown, ctx: PlatformContext) => Promise<unknown>;
598
+ }
599
+ /**
600
+ * Type-erased view of a tool definition — what agent definitions accept.
601
+ * (HelixTool<TSchema> is invariant in its schema because of the callable's
602
+ * input position; this structural view is what `tools: [...]` is typed as.)
603
+ */
604
+ interface HelixToolLike {
605
+ readonly kind: typeof TOOL_DEFINITION_KIND;
606
+ readonly name: string;
607
+ readonly description: string;
608
+ readonly inputSchema: ZodType;
609
+ readonly needsApproval?: boolean | ((input: never) => boolean | Promise<boolean>);
610
+ readonly execute: (input: unknown, ctx: PlatformContext) => Promise<unknown>;
611
+ }
612
+ /**
613
+ * Define a tool an agent can call (or that your code can invoke in-process).
614
+ *
615
+ * @beta Agents and tools are in beta and may change in a future release.
616
+ */
617
+ declare function defineTool<TSchema extends ZodType>(config: DefineToolConfig<TSchema>): HelixTool<TSchema>;
618
+ /** Structural check for defineTool output — see TOOL_DEFINITION_KIND. */
619
+ declare function isToolDefinition(value: unknown): value is HelixTool;
620
+
621
+ /**
622
+ * `defineAgent` (helix-spec 14) — one file per agent under
623
+ * `functions/_agents/`, definitions in code, the file system as the source of
624
+ * truth.
625
+ *
626
+ * **Beta.** Agents and tools are in beta: this API may change in a future
627
+ * release without a major version bump.
628
+ *
629
+ * Like `defineSchedule`, the SDK owns the definition + runtime and the
630
+ * host (dev server, lambda router) owns discovery: importing the module
631
+ * registers the agent by name.
632
+ *
633
+ * v1 deviations from the spec, both enforced with clear errors:
634
+ * - `name` is required (filename defaulting needs build-time discovery, which
635
+ * arrives with the deploy-side scan);
636
+ * - `instructionsFile` resolution requires the host to record the agent
637
+ * file's directory (the dev server does; direct imports in tests should use
638
+ * inline `instructions`).
639
+ */
640
+ declare const AGENT_DEFINITION_KIND = "helix-agent";
641
+ declare const agentConfigSchema: z.ZodEffects<z.ZodObject<{
642
+ name: z.ZodString;
643
+ description: z.ZodString;
644
+ model: z.ZodString;
645
+ auth: z.ZodString;
646
+ fallbacks: z.ZodOptional<z.ZodArray<z.ZodObject<{
647
+ model: z.ZodString;
648
+ auth: z.ZodString;
649
+ }, "strip", z.ZodTypeAny, {
650
+ auth: string;
651
+ model: string;
652
+ }, {
653
+ auth: string;
654
+ model: string;
655
+ }>, "many">>;
656
+ instructions: z.ZodOptional<z.ZodString>;
657
+ instructionsFile: z.ZodOptional<z.ZodString>;
658
+ tools: z.ZodOptional<z.ZodArray<z.ZodType<HelixToolLike, z.ZodTypeDef, HelixToolLike>, "many">>;
659
+ agents: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
660
+ memory: z.ZodOptional<z.ZodObject<{
661
+ maxSessionMessages: z.ZodOptional<z.ZodNumber>;
662
+ ttl: z.ZodOptional<z.ZodNumber>;
663
+ /**
664
+ * `"user"` declares the agent is executed BY a user: sessions are
665
+ * keyed by (and only visible to) the `ctx.userId` of the invoking
666
+ * execution, and `agent.sessions()` lists the calling user's recent
667
+ * sessions. Invoking a user-scoped agent without a user identity
668
+ * (schedules) is a caller error. Default `"project"`: sessions are
669
+ * shared across the project's executions.
670
+ */
671
+ scope: z.ZodOptional<z.ZodEnum<["user", "project"]>>;
672
+ }, "strip", z.ZodTypeAny, {
673
+ maxSessionMessages?: number | undefined;
674
+ ttl?: number | undefined;
675
+ scope?: "user" | "project" | undefined;
676
+ }, {
677
+ maxSessionMessages?: number | undefined;
678
+ ttl?: number | undefined;
679
+ scope?: "user" | "project" | undefined;
680
+ }>>;
681
+ limits: z.ZodOptional<z.ZodObject<{
682
+ maxIterations: z.ZodOptional<z.ZodNumber>;
683
+ maxToolCalls: z.ZodOptional<z.ZodNumber>;
684
+ }, "strip", z.ZodTypeAny, {
685
+ maxIterations?: number | undefined;
686
+ maxToolCalls?: number | undefined;
687
+ }, {
688
+ maxIterations?: number | undefined;
689
+ maxToolCalls?: number | undefined;
690
+ }>>;
691
+ }, "strip", z.ZodTypeAny, {
692
+ auth: string;
693
+ name: string;
694
+ model: string;
695
+ description: string;
696
+ instructions?: string | undefined;
697
+ tools?: HelixToolLike[] | undefined;
698
+ fallbacks?: {
699
+ auth: string;
700
+ model: string;
701
+ }[] | undefined;
702
+ instructionsFile?: string | undefined;
703
+ agents?: string[] | undefined;
704
+ memory?: {
705
+ maxSessionMessages?: number | undefined;
706
+ ttl?: number | undefined;
707
+ scope?: "user" | "project" | undefined;
708
+ } | undefined;
709
+ limits?: {
710
+ maxIterations?: number | undefined;
711
+ maxToolCalls?: number | undefined;
712
+ } | undefined;
713
+ }, {
714
+ auth: string;
715
+ name: string;
716
+ model: string;
717
+ description: string;
718
+ instructions?: string | undefined;
719
+ tools?: HelixToolLike[] | undefined;
720
+ fallbacks?: {
721
+ auth: string;
722
+ model: string;
723
+ }[] | undefined;
724
+ instructionsFile?: string | undefined;
725
+ agents?: string[] | undefined;
726
+ memory?: {
727
+ maxSessionMessages?: number | undefined;
728
+ ttl?: number | undefined;
729
+ scope?: "user" | "project" | undefined;
730
+ } | undefined;
731
+ limits?: {
732
+ maxIterations?: number | undefined;
733
+ maxToolCalls?: number | undefined;
734
+ } | undefined;
735
+ }>, {
736
+ auth: string;
737
+ name: string;
738
+ model: string;
739
+ description: string;
740
+ instructions?: string | undefined;
741
+ tools?: HelixToolLike[] | undefined;
742
+ fallbacks?: {
743
+ auth: string;
744
+ model: string;
745
+ }[] | undefined;
746
+ instructionsFile?: string | undefined;
747
+ agents?: string[] | undefined;
748
+ memory?: {
749
+ maxSessionMessages?: number | undefined;
750
+ ttl?: number | undefined;
751
+ scope?: "user" | "project" | undefined;
752
+ } | undefined;
753
+ limits?: {
754
+ maxIterations?: number | undefined;
755
+ maxToolCalls?: number | undefined;
756
+ } | undefined;
757
+ }, {
758
+ auth: string;
759
+ name: string;
760
+ model: string;
761
+ description: string;
762
+ instructions?: string | undefined;
763
+ tools?: HelixToolLike[] | undefined;
764
+ fallbacks?: {
765
+ auth: string;
766
+ model: string;
767
+ }[] | undefined;
768
+ instructionsFile?: string | undefined;
769
+ agents?: string[] | undefined;
770
+ memory?: {
771
+ maxSessionMessages?: number | undefined;
772
+ ttl?: number | undefined;
773
+ scope?: "user" | "project" | undefined;
774
+ } | undefined;
775
+ limits?: {
776
+ maxIterations?: number | undefined;
777
+ maxToolCalls?: number | undefined;
778
+ } | undefined;
779
+ }>;
780
+ type AgentDefinitionConfig = z.input<typeof agentConfigSchema>;
781
+ interface AgentDefinition extends z.output<typeof agentConfigSchema> {
782
+ kind: typeof AGENT_DEFINITION_KIND;
783
+ }
784
+ /**
785
+ * Define an agent (default export of a file under `functions/_agents/`).
786
+ *
787
+ * @beta Agents and tools are in beta and may change in a future release.
788
+ */
789
+ declare function defineAgent(config: AgentDefinitionConfig): AgentDefinition;
790
+ /** Structural check for defineAgent output — see AGENT_DEFINITION_KIND. */
791
+ declare function isAgentDefinition(value: unknown): value is AgentDefinition;
792
+
793
+ export { AGENT_DEFINITION_KIND as A, setSdkConfig as B, type ConfigFileOptions as C, type DefineToolConfig as D, 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, AI_SERVICES as a, type AgentDefinition as b, type AgentDefinitionConfig as c, type AgentSessionsConfig as d, type AiProviderEntry as e, type AiService as f, type HelixTool as g, type HelixToolLike as h, TOOL_DEFINITION_KIND as i, WORKSPACE_ID_REQUIRED_CODE as j, type WorkspaceIdRequiredError as k, agentSessionsSchema as l, aiProviderEntrySchema as m, defineAgent as n, defineTool as o, getSdkConfig as p, isAgentDefinition as q, isToolDefinition as r, loadConfig as s, loadedTrayConfigSchema as t, projectIdSchema as u, requireWorkspaceId as v, resolveConfigFile as w, resolveConfigOverride as x, workspaceIdSchema as y, type SdkConfigInput as z };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
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-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-BqIGpFg8.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-BqIGpFg8.js';
3
+ import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-Ci9SeHOE.js';
4
+ export { A as AgentApprovalDecision, b as AgentCallOptions, c as AgentClient, d as AgentPendingApproval, e as AgentResult, f as AgentSession, g as AgentSessionSummary, h as AgentSessionsList, i as AgentStreamResult, j as AiEmbeddingModelInstance, k as AiImageModelInstance, l as AiLanguageModelInstance, m as AiSpeechModelInstance, n as AiTranscriptionModelInstance, B as BrokerAuthedClient, o as BrokerCallOptions, p as BrokerCallResult, C as CallFunctionAsync, q as DbCallParameters, r as DbClient, s as FileSystemClient, H as HelixAI, t as HelixAIProvider, u as HelixAgent, v as HelixCost, w as HelixResultMeta, x as HttpClient, K as KeyValueStore, L as Logger, y as S3SignOptions, z as S3SignResult, E as ScheduleContext, G as ScheduleHandler, I as ScheduleTrigger, J as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-Ci9SeHOE.js';
5
+ import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './define-agent-CICJokmS.js';
6
+ export { A as AGENT_DEFINITION_KIND, a as AI_SERVICES, b as AgentDefinition, c as AgentDefinitionConfig, d as AgentSessionsConfig, e as AiProviderEntry, f as AiService, C as ConfigFileOptions, D as DefineToolConfig, H as HELIX_CONFIG_ENV, g as HelixTool, h as HelixToolLike, P as ProvisionedTrayConfig, S as SdkRuntimeConfig, i as TOOL_DEFINITION_KIND, U as UnprovisionedTrayConfig, j as WORKSPACE_ID_REQUIRED_CODE, k as WorkspaceIdRequiredError, l as agentSessionsSchema, m as aiProviderEntrySchema, n as defineAgent, o as defineTool, p as getSdkConfig, q as isAgentDefinition, r as isToolDefinition, s as loadConfig, t as loadedTrayConfigSchema, u as projectIdSchema, v as requireWorkspaceId, w as resolveConfigFile, x as resolveConfigOverride, y as workspaceIdSchema } from './define-agent-CICJokmS.js';
7
7
  export { a as REGION_VALUES, R as Region, r as regionSchema } from './region-schema-COfWyGI9.js';
8
+ import { StopCondition, ToolSet } from 'ai';
8
9
  export { EmbedManyResult, EmbedResult, EmbeddingModel, FinishReason, GenerateImageResult, GenerateObjectResult, GenerateTextResult, ImageModel, LanguageModel, LanguageModelUsage, ModelMessage, Output, PrepareStepFunction, SpeechModel, SpeechResult, StopCondition, StreamObjectResult, StreamTextResult, TextStreamPart, ToolChoice, ToolSet, TranscriptionModel, TranscriptionResult, UIMessage, convertToModelMessages, cosineSimilarity, dynamicTool, hasToolCall, jsonSchema, smoothStream, stepCountIs, tool, zodSchema } from 'ai';
9
10
  import 'ky';
10
11
  import '@ai-sdk/provider';
@@ -142,4 +143,7 @@ interface ConfigService {
142
143
  */
143
144
  declare function createConfigService(options: CreateConfigServiceOptions): Promise<ConfigService>;
144
145
 
145
- export { type ConfigService, type CreateConfigServiceOptions, DefineFunctionOptions, DefineScheduleConfig, FunctionHandler, LoadedTrayConfig, PlatformContext, type RunWithinAppSpanArgs, SCHEDULE_DEFINITION_KIND, ScheduleConfigError, ScheduleDefinition, TrayConfig, WatchErrorPhase, createConfigService, defineConfig, defineFunction, defineSchedule, getContext, isScheduleDefinition, runWithinAppSpan };
146
+ /** Helix stop condition: total tool executions across all steps. */
147
+ declare function totalToolCallsIs(max: number): StopCondition<ToolSet>;
148
+
149
+ export { type ConfigService, type CreateConfigServiceOptions, DefineFunctionOptions, DefineScheduleConfig, FunctionHandler, LoadedTrayConfig, PlatformContext, type RunWithinAppSpanArgs, SCHEDULE_DEFINITION_KIND, ScheduleConfigError, ScheduleDefinition, TrayConfig, WatchErrorPhase, createConfigService, defineConfig, defineFunction, defineSchedule, getContext, isScheduleDefinition, runWithinAppSpan, totalToolCallsIs };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{A as ce,B as le,C as fe,D as pe,E as ge,F as me,G as _,H as x,I as V,J as z,K as y,L as he,M as ye,N as B,O as Ce,P as ve,Q as we,R as Se,f as P,g as k,h as A,i as h,j as H,k as F,l as L,m as O,n as ae,o as M,p as D,q,r as Z,s as N,w as $,x as K,y as de,z as ue}from"./chunk-CYG3GXE2.js";import{a as j,b as ie}from"./chunk-WUCX7RZO.js";import{d as E,r as W,s as U}from"./chunk-HEA646WT.js";import{randomUUID as Pe}from"crypto";import{SpanStatusCode as Y,SpanKind as Ae}from"@opentelemetry/api";import{defineEventHandler as He,getMethod as Fe,getRequestURL as Le,getHeaders as te,getHeader as ee}from"h3";import{readBody as Ee,getQuery as ke,getRouterParams as _e}from"h3";async function G(e,t){let r=await xe(e),n=ke(e),o=_e(e)??{},s={...n,...r,...o};return t?be(s,t):s}async function xe(e){try{let t=await Ee(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function be(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var C=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function J(e){return t=>{e.node.res.statusCode=t}}function Q(){return(e,t)=>{throw new C(e,t)}}function X(e,t){let{statusCode:r,message:n}=Te(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Te(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_path_invalid":return{statusCode:400,message:e.message};case"call_function_call_failed":return{statusCode:502,message:"Async function call failed"};case"call_function_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_not_available":return{statusCode:501,message:"callFunctionAsync is not available in this environment"};case"call_function_missing_execution_jwt":return{statusCode:401,message:"Missing execution credentials"};case"ai_unsupported_service":case"ai_model_id_required":case"ai_model_instance_required":case"ai_provider_not_configured":case"ai_foreign_model_rejected":return{statusCode:500,message:e.kind==="ai_unsupported_service"?`AI service not supported for alias "${e.alias}"`:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Ie=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Re(e){return e.toLowerCase().includes("tray_lid")}function b(e){let t={};for(let[r,n]of Object.entries(e))if(!Ie.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let d=s.split("=")[0].trim();return!Re(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Oe(e,t){let{inputSchema:r,outputSchema:n}=qe(t),o=e;return He(async s=>{let d=E(),{executionId:i,userId:a,deploymentId:l}=Ze(d,s),f=d.mode==="lambda"?d.parentExecutionId??null:null,p=Date.now(),v=new Date().toISOString(),c=Fe(s),u=Le(s).pathname,g=D(),m=M(),oe=`${c} ${u}`;H();let R={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1};return je(()=>k.run(R,()=>P.run(i,async()=>{let w=await Me(s,r);if(!w.ok)return{response:w.response,errored:!1,errorMessage:null};let se=$e(s,w.input,g,m,c,u,i,l,a,f);return De(o,se,n,s,m,i,l,{method:c,path:u,rawInput:w.input})})),{executionId:i,deploymentId:l,routeOrJob:oe,startedAt:v,startMs:p,userId:a,flags:R})})}async function je(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{O({...t,errored:r,errorMessage:n}),await F()}}async function Me(e,t){try{return{ok:!0,input:await G(e,t)}}catch(r){let n=Ne(e,r);if(n)return{ok:!1,response:n};throw r}}async function De(e,t,r,n,o,s,d,i){return L.startActiveSpan("function",{root:!0,kind:Ae.SERVER,attributes:{method:i.method,route:i.path,executionId:s,...d?{deploymentId:d}:{}}},async a=>{t.traceId=a.spanContext().traceId;let l=b(te(n));h(a,"input",i.rawInput),h(a,"request",{method:i.method,path:i.path,headers:l,body:i.rawInput});let f=!1,p=null,v,c;try{let u=await j.run(t,()=>e(t));if(v=u,u==null)n.node.res.statusCode=204,c="";else if(u instanceof Response)c=u;else if(r){let g=r.safeParse(u);if(!g.success){let m=Object.keys(g.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:m,executionId:s}),W.outputValidationFailed(m)}c=g.data}else c=u}catch(u){f=!0,p=u instanceof Error?u.message:String(u),A("hasError"),c=We(u,n,o,s)}finally{Ue(a,n,{errored:f,errorMessage:p,handlerResult:v,response:c})}return{response:c,errored:f,errorMessage:p}})}function We(e,t,r,n){if(e instanceof C)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(U(e))return X(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function Ue(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&h(e,"output",r.handlerResult),h(e,"response",r.response);let n=k.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasAi",n?.hasAi??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?Y.ERROR:Y.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function qe(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Ze(e,t){let r=e.mode==="lambda",n=(r?e.executionId:ee(t,"x-tray-execution-id"))??Pe(),o=(r?e.userId:ee(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Ne(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function $e(e,t,r,n,o,s,d,i,a,l){return{input:t,method:o,path:s,headers:b(te(e)),http:q(),db:f=>Z(f),kv:()=>N(),files:()=>$(),callFunctionAsync:K(),ai:B(),log:n,config:r,status:J(e),error:Q(),state:{},request:e,executionId:d,deploymentId:i,userId:a,parentExecutionId:l,identity:a!==null?{user:{id:a}}:null,traceId:""}}function Ke(e){return e}import{existsSync as Ve,watch as ze,writeSync as Be}from"fs";import{basename as Ge,dirname as Je,join as Qe,resolve as S}from"path";import{watchConfig as Xe}from"c12";function Ye(e,t){let r=e instanceof Error?e.message:String(e);Be(2,`[helix-watch] ${t.phase} error: ${r}
2
- `)}function T(){return{kind:"unprovisioned",name:"",authentications:{},config:{},region:"us1"}}var et=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,re=new Set;function ne(e,t){return x(e,{configFile:t})!==void 0}async function tt(e,t,r){if(ne(e.cwd,t))try{return{current:await y(e.cwd,{configFile:t}),initialLoadSucceeded:!0}}catch(n){return r(n,{phase:"reload"}),{current:T(),initialLoadSucceeded:!1}}if(e.watch){let n=t!==void 0?S(e.cwd,t):S(e.cwd);re.has(n)||(process.stderr.write(t!==void 0?`warning: config file ${S(e.cwd,t)} not found; tray running with default config
1
+ import{A as le,B as fe,C as pe,D as ge,E as me,F as he,G as ye,H as x,I as k,J as V,K as z,L as y,M as Ce,N as ve,O as B,P as Se,Q as we,R as Ee,Y as _e,Z as xe,_ as ke,ba as Te,ca as G,da as be,ea as Ie,f as A,fa as Re,g as _,ga as Ae,h as P,i as h,j as H,k as F,l as D,m as L,n as ae,o as j,p as M,q,r as N,s as Z,w as K,x as $,y as ue,z as ce}from"./chunk-7R345MR6.js";import{a as O,b as de}from"./chunk-WUCX7RZO.js";import{d as E,r as W,s as U}from"./chunk-3T2WZMJJ.js";import{randomUUID as We}from"crypto";import{SpanStatusCode as ee,SpanKind as Ue}from"@opentelemetry/api";import{defineEventHandler as qe,getMethod as Ne,getRequestURL as Ze,getHeaders as re,getHeader as te}from"h3";import{readBody as Pe,getQuery as He,getRouterParams as Fe}from"h3";async function J(e,t){let r=await De(e),n=He(e),o=Fe(e)??{},s={...n,...r,...o};return t?Le(s,t):s}async function De(e){try{let t=await Pe(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function Le(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var C=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function Q(e){return t=>{e.node.res.statusCode=t}}function X(){return(e,t)=>{throw new C(e,t)}}function Y(e,t){let{statusCode:r,message:n}=Oe(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Oe(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_path_invalid":return{statusCode:400,message:e.message};case"call_function_call_failed":return{statusCode:502,message:"Async function call failed"};case"call_function_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"call_function_not_available":return{statusCode:501,message:"callFunctionAsync is not available in this environment"};case"call_function_missing_execution_jwt":return{statusCode:401,message:"Missing execution credentials"};case"ai_unsupported_service":case"ai_model_id_required":case"ai_model_instance_required":case"ai_provider_not_configured":case"ai_foreign_model_rejected":case"agent_sessions_failed":return{statusCode:500,message:e.kind==="ai_unsupported_service"?`AI service not supported for alias "${e.alias}"`:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var je=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Me(e){return e.toLowerCase().includes("tray_lid")}function T(e){let t={};for(let[r,n]of Object.entries(e))if(!je.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let d=s.split("=")[0].trim();return!Me(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ke(e,t){let{inputSchema:r,outputSchema:n}=Je(t),o=e;return qe(async s=>{let d=E(),{executionId:a,userId:i,deploymentId:f}=Qe(d,s),c=d.mode==="lambda"?d.parentExecutionId??null:null,p=Date.now(),v=new Date().toISOString(),l=Ne(s),u=Ze(s).pathname,g=M(),m=j(),se=`${l} ${u}`;H();let R={hasDb:!1,hasExternal:!1,hasAuth:!1,hasAi:!1,hasError:!1};return $e(()=>_.run(R,()=>A.run(a,async()=>{let S=await Ve(s,r);if(!S.ok)return{response:S.response,errored:!1,errorMessage:null};let ie=Ye(s,S.input,g,m,l,u,a,f,i,c);return ze(o,ie,n,s,m,a,f,{method:l,path:u,rawInput:S.input})})),{executionId:a,deploymentId:f,routeOrJob:se,startedAt:v,startMs:p,userId:i,flags:R})})}async function $e(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{L({...t,errored:r,errorMessage:n}),await F()}}async function Ve(e,t){try{return{ok:!0,input:await J(e,t)}}catch(r){let n=Xe(e,r);if(n)return{ok:!1,response:n};throw r}}async function ze(e,t,r,n,o,s,d,a){return D.startActiveSpan("function",{root:!0,kind:Ue.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...d?{deploymentId:d}:{}}},async i=>{t.traceId=i.spanContext().traceId;let f=T(re(n));h(i,"input",a.rawInput),h(i,"request",{method:a.method,path:a.path,headers:f,body:a.rawInput});let c=!1,p=null,v,l;try{let u=await O.run(t,()=>e(t));if(v=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let g=r.safeParse(u);if(!g.success){let m=Object.keys(g.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:m,executionId:s}),W.outputValidationFailed(m)}l=g.data}else l=u}catch(u){c=!0,p=u instanceof Error?u.message:String(u),P("hasError"),l=Be(u,n,o,s)}finally{Ge(i,n,{errored:c,errorMessage:p,handlerResult:v,response:l})}return{response:l,errored:c,errorMessage:p}})}function Be(e,t,r,n){if(e instanceof C)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(U(e))return Y(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function Ge(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&h(e,"output",r.handlerResult),h(e,"response",r.response);let n=_.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasAi",n?.hasAi??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?ee.ERROR:ee.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Je(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Qe(e,t){let r=e.mode==="lambda",n=(r?e.executionId:te(t,"x-tray-execution-id"))??We(),o=(r?e.userId:te(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function Xe(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function Ye(e,t,r,n,o,s,d,a,i,f){return{input:t,method:o,path:s,headers:T(re(e)),http:q(),db:c=>N(c),kv:()=>Z(),files:()=>K(),callFunctionAsync:$(),ai:B(),agent:c=>G(c),log:n,config:r,status:Q(e),error:X(),state:{},request:e,executionId:d,deploymentId:a,userId:i,parentExecutionId:f,identity:i!==null?{user:{id:i}}:null,traceId:""}}function et(e){return e}import{existsSync as tt,watch as rt,writeSync as nt}from"fs";import{basename as ot,dirname as st,join as it,resolve as w}from"path";import{watchConfig as at}from"c12";function dt(e,t){let r=e instanceof Error?e.message:String(e);nt(2,`[helix-watch] ${t.phase} error: ${r}
2
+ `)}function b(){return{kind:"unprovisioned",name:"",authentications:{},config:{},region:"us1"}}var ut=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,ne=new Set;function oe(e,t){return k(e,{configFile:t})!==void 0}async function ct(e,t,r){if(oe(e.cwd,t))try{return{current:await y(e.cwd,{configFile:t}),initialLoadSucceeded:!0}}catch(n){return r(n,{phase:"reload"}),{current:b(),initialLoadSucceeded:!1}}if(e.watch){let n=t!==void 0?w(e.cwd,t):w(e.cwd);ne.has(n)||(process.stderr.write(t!==void 0?`warning: config file ${w(e.cwd,t)} not found; tray running with default config
3
3
  `:`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
4
- `),re.add(n))}return{current:T(),initialLoadSucceeded:!1}}var I=class{constructor(t,r,n,o){this.cwd=t;this.configFile=r;this.onError=n;this.emit=o}cwd;configFile;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=Xe({...V(this.cwd,{configFile:this.configFile}),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=z(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,s)=>{n.once("ready",o),n.once("error",s)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){let t=this.configFile!==void 0?S(this.cwd,this.configFile):void 0,r=t!==void 0?Je(t):this.cwd;try{this.directoryWatcher=ze(r,{persistent:!1},(n,o)=>{if(this.stopped||!o)return;let s=o.toString();if(t!==void 0){if(s!==Ge(t))return}else if(!et.test(s))return;Ve(Qe(r,s))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let d;try{d=await y(this.cwd,{configFile:this.configFile})}catch(a){this.onError(a,{phase:"reload"});return}if(this.stopped)return;this.emit(d);let i=this.directoryWatcher;i&&(this.directoryWatcher=null,i.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",n=>{this.onError(n,{phase:"attach"})})}catch(n){this.onError(n,{phase:"attach"})}}};async function rt(e){let t=e.onError??Ye,r=new Set,n=_(e.configFile),o=await tt(e,n,t),s=o.current;function d(a){s=a;for(let l of[...r])try{l(a)}catch(f){t(f,{phase:"reload"})}}let i=new I(e.cwd,n,t,d);return e.watch&&i.start(o.initialLoadSucceeded),{get(){return s},async reload(){if(!ne(e.cwd,n)){let a=T();return d(a),a}try{let a=await y(e.cwd,{configFile:n});return d(a),a}catch(a){return t(a,{phase:"reload"}),s}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await i.stop()},ready(){return i.watcherReady()}}}import{tool as Vt,dynamicTool as zt,jsonSchema as Bt,zodSchema as Gt,stepCountIs as Jt,hasToolCall as Qt,convertToModelMessages as Xt,cosineSimilarity as Yt,smoothStream as er,Output as tr}from"ai";export{fe as AI_SERVICES,me as HELIX_CONFIG_ENV,tr as Output,de as REGION_VALUES,Ce as SCHEDULE_DEFINITION_KIND,ve as ScheduleConfigError,he as WORKSPACE_ID_REQUIRED_CODE,pe as aiProviderEntrySchema,Xt as convertToModelMessages,Yt as cosineSimilarity,rt as createConfigService,Ke as defineConfig,Oe as defineFunction,we as defineSchedule,zt as dynamicTool,ie as getContext,E as getSdkConfig,Qt as hasToolCall,Se as isScheduleDefinition,Bt as jsonSchema,y as loadConfig,ge as loadedTrayConfigSchema,ce as projectIdSchema,ue as regionSchema,ye as requireWorkspaceId,x as resolveConfigFile,_ as resolveConfigOverride,ae as runWithinAppSpan,er as smoothStream,Jt as stepCountIs,Vt as tool,le as workspaceIdSchema,Gt as zodSchema};
4
+ `),ne.add(n))}return{current:b(),initialLoadSucceeded:!1}}var I=class{constructor(t,r,n,o){this.cwd=t;this.configFile=r;this.onError=n;this.emit=o}cwd;configFile;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=at({...V(this.cwd,{configFile:this.configFile}),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=z(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,s)=>{n.once("ready",o),n.once("error",s)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){let t=this.configFile!==void 0?w(this.cwd,this.configFile):void 0,r=t!==void 0?st(t):this.cwd;try{this.directoryWatcher=rt(r,{persistent:!1},(n,o)=>{if(this.stopped||!o)return;let s=o.toString();if(t!==void 0){if(s!==ot(t))return}else if(!ut.test(s))return;tt(it(r,s))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let d;try{d=await y(this.cwd,{configFile:this.configFile})}catch(i){this.onError(i,{phase:"reload"});return}if(this.stopped)return;this.emit(d);let a=this.directoryWatcher;a&&(this.directoryWatcher=null,a.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",n=>{this.onError(n,{phase:"attach"})})}catch(n){this.onError(n,{phase:"attach"})}}};async function lt(e){let t=e.onError??dt,r=new Set,n=x(e.configFile),o=await ct(e,n,t),s=o.current;function d(i){s=i;for(let f of[...r])try{f(i)}catch(c){t(c,{phase:"reload"})}}let a=new I(e.cwd,n,t,d);return e.watch&&a.start(o.initialLoadSucceeded),{get(){return s},async reload(){if(!oe(e.cwd,n)){let i=b();return d(i),i}try{let i=await y(e.cwd,{configFile:n});return d(i),i}catch(i){return t(i,{phase:"reload"}),s}},subscribe(i){return r.add(i),()=>{r.delete(i)}},async stop(){r.clear(),await a.stop()},ready(){return a.watcherReady()}}}import{tool as sr,dynamicTool as ir,jsonSchema as ar,zodSchema as dr,stepCountIs as ur,hasToolCall as cr,convertToModelMessages as lr,cosineSimilarity as fr,smoothStream as pr,Output as gr}from"ai";export{_e as AGENT_DEFINITION_KIND,ge as AI_SERVICES,ye as HELIX_CONFIG_ENV,gr as Output,ue as REGION_VALUES,be as SCHEDULE_DEFINITION_KIND,Ie as ScheduleConfigError,Se as TOOL_DEFINITION_KIND,Ce as WORKSPACE_ID_REQUIRED_CODE,pe as agentSessionsSchema,me as aiProviderEntrySchema,lr as convertToModelMessages,fr as cosineSimilarity,lt as createConfigService,xe as defineAgent,et as defineConfig,Ke as defineFunction,Re as defineSchedule,we as defineTool,ir as dynamicTool,de as getContext,E as getSdkConfig,cr as hasToolCall,ke as isAgentDefinition,Ae as isScheduleDefinition,Ee as isToolDefinition,ar as jsonSchema,y as loadConfig,he as loadedTrayConfigSchema,le as projectIdSchema,ce as regionSchema,ve as requireWorkspaceId,k as resolveConfigFile,x as resolveConfigOverride,ae as runWithinAppSpan,pr as smoothStream,ur as stepCountIs,sr as tool,Te as totalToolCallsIs,fe as workspaceIdSchema,dr as zodSchema};