@teamkeel/functions-runtime 0.458.0 → 0.460.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/dist/index.d.ts CHANGED
@@ -2,6 +2,49 @@ import * as kysely from 'kysely';
2
2
  import { Kysely } from 'kysely';
3
3
  export { default as KSUID } from 'ksuid';
4
4
  import * as opentelemetry from '@opentelemetry/api';
5
+ import { StandardSchemaV1 } from '@standard-schema/spec';
6
+ import { LanguageModel } from 'ai';
7
+ export { z } from 'zod';
8
+
9
+ interface RecipientUser {
10
+ id: string;
11
+ email?: string | null;
12
+ }
13
+ interface RecipientIdentity {
14
+ id: string;
15
+ email?: string | null;
16
+ }
17
+ interface EmailActionButton {
18
+ label: string;
19
+ url: string;
20
+ }
21
+ interface StructuredEmailContent {
22
+ title?: string;
23
+ body: string;
24
+ actions?: EmailActionButton[];
25
+ }
26
+ type EmailContent = string | StructuredEmailContent;
27
+ interface EmailRecipientGroup {
28
+ emails?: string | string[];
29
+ users?: string | RecipientUser | Array<string | RecipientUser>;
30
+ identities?: string | RecipientIdentity | Array<string | RecipientIdentity>;
31
+ teams?: string | string[];
32
+ }
33
+ interface EmailRecipients {
34
+ to: EmailRecipientGroup;
35
+ cc?: EmailRecipientGroup;
36
+ bcc?: EmailRecipientGroup;
37
+ }
38
+ interface EmailInput {
39
+ recipients: EmailRecipients;
40
+ subject: string;
41
+ content: EmailContent;
42
+ }
43
+
44
+ interface NotifyApi {
45
+ email(input: EmailInput): Promise<string>;
46
+ }
47
+ declare function createNotifier(): NotifyApi;
5
48
 
6
49
  declare namespace ErrorPresets {
7
50
  export { NotFoundError$1 as NotFound };
@@ -166,13 +209,14 @@ declare class ModelAPI {
166
209
  * @param {Function} _ Used to be a function that returns the default values for a row in this table. No longer used.
167
210
  * @param {TableConfigMap} tableConfigMap
168
211
  */
169
- constructor(tableName: string, _: Function, tableConfigMap?: TableConfigMap);
212
+ constructor(tableName: string, _: Function, tableConfigMap?: TableConfigMap, fileFieldsMap?: {});
170
213
  _tableName: string;
171
214
  _tableConfigMap: {
172
215
  [x: string]: {
173
216
  [x: string]: RelationshipConfig;
174
217
  };
175
218
  };
219
+ _fileFields: any;
176
220
  _modelName: any;
177
221
  create(values: any): Promise<any>;
178
222
  findOne(where?: {}): Promise<any>;
@@ -180,6 +224,8 @@ declare class ModelAPI {
180
224
  update(where: any, values: any): Promise<any>;
181
225
  delete(where: any): Promise<any>;
182
226
  where(where: any): QueryBuilder;
227
+ _selectExistingFileValues(where: any, fileColumns: any): Promise<{}[]>;
228
+ _deferReplacedFiles(existingRows: any, fileColumns: any, newRow: any): void;
183
229
  }
184
230
 
185
231
  /**
@@ -350,6 +396,28 @@ declare class FlowsAPI {
350
396
  * @returns {Promise<FlowRun>} The created flow run
351
397
  */
352
398
  start(inputs?: Object): Promise<FlowRun$1>;
399
+ /**
400
+ * Mints a signed link that lets an external, unauthenticated actor execute this flow. The flow
401
+ * must be declared with @externalAccess. Each time the link is opened a fresh flow run is created;
402
+ * a reusable link can be opened many times, otherwise it permits exactly one run.
403
+ * @param {Object} [options] Signed link options
404
+ * @param {Object} [options.inputs] Default inputs applied to every run created from the link
405
+ * @param {Date} [options.expiresAt] When the link stops being valid
406
+ * @param {boolean} [options.reusable] Whether the link can be opened more than once
407
+ * @returns {Promise<{url: string, expiresAt: Date|null, flow: {name: string, runId: string|null}}>} The signed link
408
+ */
409
+ signedLink(options?: {
410
+ inputs?: Object | undefined;
411
+ expiresAt?: Date | undefined;
412
+ reusable?: boolean | undefined;
413
+ }): Promise<{
414
+ url: string;
415
+ expiresAt: Date | null;
416
+ flow: {
417
+ name: string;
418
+ runId: string | null;
419
+ };
420
+ }>;
353
421
  /**
354
422
  * Gets a flow run by ID.
355
423
  * @param {string} runId The flow run ID
@@ -424,6 +492,10 @@ declare class FlowRun$1 {
424
492
  cancel(): Promise<FlowRun$1>;
425
493
  }
426
494
 
495
+ declare function createIntegrationServer(name: any, identity: any): {
496
+ do: (request: any) => Promise<unknown>;
497
+ };
498
+
427
499
  interface RequestHeadersMap {
428
500
  [key: string]: string;
429
501
  }
@@ -539,7 +611,10 @@ declare class File extends InlineFile {
539
611
  get isPublic(): boolean;
540
612
  read(): Promise<Buffer>;
541
613
  store(expires?: Date | null): Promise<File>;
542
- getPresignedUrl(): Promise<URL>;
614
+ getPresignedUrl(options?: {
615
+ contentDisposition?: "inline" | "attachment";
616
+ filename?: string;
617
+ }): Promise<URL>;
543
618
  getPresignedUploadUrl(): Promise<URL>;
544
619
  toDbRecord(): FileDbRecord;
545
620
  toJSON(): FileDbRecord;
@@ -1335,6 +1410,75 @@ declare class NonRetriableError extends Error {
1335
1410
  constructor(message?: string);
1336
1411
  }
1337
1412
 
1413
+ /** A JSON-serializable message in an agent conversation. Library-neutral —
1414
+ * engine adapters map this to their provider's shape. */
1415
+ type AgentMessage = {
1416
+ role: "user";
1417
+ content: string;
1418
+ } | {
1419
+ role: "assistant";
1420
+ content: string;
1421
+ toolCalls?: ToolCallRequest[];
1422
+ } | {
1423
+ role: "tool";
1424
+ toolCallId: string;
1425
+ toolName: string;
1426
+ result: string;
1427
+ };
1428
+ interface ToolCallRequest {
1429
+ id: string;
1430
+ name: string;
1431
+ arguments: Record<string, unknown>;
1432
+ }
1433
+ /** A tool as presented to the model. `parameters` is a JSON Schema object. */
1434
+ interface ToolSpec {
1435
+ name: string;
1436
+ description: string;
1437
+ parameters: Record<string, unknown>;
1438
+ }
1439
+ interface TurnRequest {
1440
+ model: string;
1441
+ system?: string;
1442
+ messages: AgentMessage[];
1443
+ tools?: ToolSpec[];
1444
+ /** Force the model to call a specific tool (used for structured output). */
1445
+ toolChoice?: "auto" | {
1446
+ name: string;
1447
+ };
1448
+ }
1449
+ interface TurnUsage {
1450
+ inputTokens: number;
1451
+ outputTokens: number;
1452
+ }
1453
+ interface TurnResult {
1454
+ /** Empty string when the model only returned tool calls. */
1455
+ text: string;
1456
+ toolCalls: ToolCallRequest[];
1457
+ usage: TurnUsage;
1458
+ stopReason: "end_turn" | "tool_calls";
1459
+ }
1460
+ /** The turn primitive: ONE model call, no looping, no tool execution.
1461
+ * The flows replay engine owns the loop; adapters must never auto-execute tools. */
1462
+ interface TurnEngine {
1463
+ turn(req: TurnRequest): Promise<TurnResult>;
1464
+ }
1465
+ type ScriptEntry = TurnResult | ((req: TurnRequest) => TurnResult);
1466
+ /** Deterministic fake engine for tests. Returns scripted results in order. */
1467
+ declare class ScriptedEngine implements TurnEngine {
1468
+ private readonly script;
1469
+ private _requests;
1470
+ private index;
1471
+ constructor(script: ScriptEntry[]);
1472
+ get requests(): readonly TurnRequest[];
1473
+ turn(req: TurnRequest): Promise<TurnResult>;
1474
+ }
1475
+ /** Helpers for building scripted turns concisely in tests. */
1476
+ declare const scriptedTurn: {
1477
+ text(text: string): TurnResult;
1478
+ /** Auto-generated ids increment per process — pass an explicit `id` when asserting on ids in tests. */
1479
+ toolCall(name: string, args: Record<string, unknown>, id?: string): TurnResult;
1480
+ };
1481
+
1338
1482
  declare const enum STEP_STATUS {
1339
1483
  NEW = "NEW",
1340
1484
  RUNNING = "RUNNING",
@@ -1374,6 +1518,22 @@ interface FlowContext<C extends FlowConfig, E, S, Id, I, H extends NullableHardw
1374
1518
  secrets: S;
1375
1519
  identity: Id;
1376
1520
  trace: TraceAPI;
1521
+ module(name: string): {
1522
+ secret(key: string): string;
1523
+ server: {
1524
+ do(request: {
1525
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
1526
+ path: string;
1527
+ query?: Record<string, string | string[]>;
1528
+ headers?: Record<string, string>;
1529
+ body?: unknown;
1530
+ }): Promise<{
1531
+ status: number;
1532
+ headers: Record<string, string[]>;
1533
+ body: unknown;
1534
+ }>;
1535
+ };
1536
+ };
1377
1537
  }
1378
1538
  type NullableHardware = Hardware | undefined;
1379
1539
  type Hardware = {
@@ -1382,9 +1542,13 @@ type Hardware = {
1382
1542
  interface Printer {
1383
1543
  name: string;
1384
1544
  }
1385
- type JsonSerializable = string | number | boolean | null | JsonSerializable[] | {
1386
- [key: string]: JsonSerializable;
1545
+ type JsonValue$1<T> = T extends string | number | boolean | null ? T : T extends (...args: any[]) => any ? never : T extends (infer E)[] ? JsonValue$1<E>[] : T extends object ? keyof T extends never ? never : {
1546
+ [K in keyof T]: JsonValue$1<T[K]>;
1547
+ } : never;
1548
+ type Serializable<T> = string | number | boolean | null | void | {
1549
+ [K in keyof T]: JsonValue$1<T[K]>;
1387
1550
  };
1551
+ type StepReturn<R> = [R] extends [JsonValue$1<R> | void] ? R : JsonValue$1<R>;
1388
1552
  type StepOptions<C extends FlowConfig> = {
1389
1553
  stage?: ExtractStageKeys<C>;
1390
1554
  /** Number of times to retry the step after it fails. Defaults to 4. */
@@ -1397,18 +1561,18 @@ type StepOptions<C extends FlowConfig> = {
1397
1561
  onFailure?: () => Promise<void> | void;
1398
1562
  };
1399
1563
  type Step<C extends FlowConfig> = {
1400
- <R extends JsonSerializable | void>(
1564
+ <R extends Serializable<R>>(
1401
1565
  /** The unique name of this step. */
1402
1566
  name: string,
1403
1567
  /** Configuration options for the step. */
1404
1568
  options: StepOptions<C>,
1405
1569
  /** The step function to execute. */
1406
- fn: StepFunction<C, R>): Promise<R>;
1407
- <R extends JsonSerializable | void>(
1570
+ fn: StepFunction<C, StepReturn<R>>): Promise<R>;
1571
+ <R extends Serializable<R>>(
1408
1572
  /** The unique name of this step. */
1409
1573
  name: string,
1410
1574
  /** The step function to execute. */
1411
- fn: StepFunction<C, R>): Promise<R>;
1575
+ fn: StepFunction<C, StepReturn<R>>): Promise<R>;
1412
1576
  };
1413
1577
  type StepArgs<C extends FlowConfig> = {
1414
1578
  attempt: number;
@@ -1446,17 +1610,147 @@ type StageConfigObject = {
1446
1610
  initiallyHidden?: boolean;
1447
1611
  };
1448
1612
  type StageConfig = string | StageConfigObject;
1613
+ declare function insertNewStep(db: Kysely<any>, runId: string, name: string, stage: string | undefined): Promise<void>;
1449
1614
  declare function createFlowContext<C extends FlowConfig, E, S, Id, I, H extends NullableHardware>(runId: string, data: any, action: string | null, callback: string | null, element: string | null, spanId: string, ctx: {
1450
1615
  env: E;
1451
1616
  now: () => Date;
1452
1617
  secrets: S;
1453
1618
  identity: Id;
1454
1619
  trace: TraceAPI;
1620
+ engine?: TurnEngine;
1621
+ module: FlowContext<C, E, S, Id, I, H>["module"];
1455
1622
  }): FlowContext<C, E, S, Id, I, H>;
1456
1623
 
1624
+ type JsonValue = string | number | boolean | null | JsonValue[] | {
1625
+ [k: string]: JsonValue;
1626
+ };
1627
+ interface ToolDefinition<P = any> {
1628
+ /** snake_case identifier the model sees. */
1629
+ name: string;
1630
+ description: string;
1631
+ /** Extra guidance on when/how to use the tool, appended to the description. */
1632
+ usage?: string;
1633
+ /** Standard Schema (Zod v4) for the tool's arguments. */
1634
+ parameters: StandardSchemaV1<unknown, P>;
1635
+ /** true = always gate behind a UI approval step; predicate = gate when it returns true. */
1636
+ approval?: boolean | ((args: P) => boolean);
1637
+ execute: (args: P) => Promise<JsonValue | void>;
1638
+ }
1639
+ declare function defineTool<P>(config: ToolDefinition<P>): Readonly<ToolDefinition<P>>;
1640
+
1641
+ interface AgentConfig<I = any, R = any> {
1642
+ /** Unique agent name; used to namespace checkpointed steps. */
1643
+ name: string;
1644
+ model: string;
1645
+ instructions: string;
1646
+ tools?: ReadonlyArray<ToolDefinition>;
1647
+ /** Sealed prompt template — callers pass inputs, never a raw prompt. */
1648
+ prompt: (args: {
1649
+ inputs: I;
1650
+ context: Record<string, unknown>;
1651
+ }) => string;
1652
+ /** Result contract. Omit for free-text agents (run resolves to final assistant text). */
1653
+ result?: StandardSchemaV1<unknown, R>;
1654
+ /** Max LLM turns before the run fails. Default 10. */
1655
+ maxTurns?: number;
1656
+ /**
1657
+ * Pre-run hook; the object it returns merges into the prompt template context.
1658
+ * Like the agent body, this runs again on every orchestrator replay, so any
1659
+ * side effects must be wrapped in `ctx.step(...)` to stay idempotent (see the
1660
+ * `beforeRun` test, which loads its value through a checkpointed step).
1661
+ */
1662
+ beforeRun?: (ctx: any, args: {
1663
+ inputs: I;
1664
+ }) => Promise<Record<string, unknown> | void>;
1665
+ /**
1666
+ * Post-run hook, called with the final result once the agent completes. Like
1667
+ * `beforeRun` it runs again on every orchestrator replay, so any side effects
1668
+ * (writes, notifications) must be wrapped in `ctx.step(...)` to stay
1669
+ * idempotent — an un-checkpointed write here repeats on each replay.
1670
+ */
1671
+ afterRun?: (ctx: any, result: R | string) => Promise<void>;
1672
+ }
1673
+ interface Agent<I = any, R = any> {
1674
+ readonly name: string;
1675
+ readonly config: AgentConfig<I, R>;
1676
+ run(ctx: any, inputs: I): Promise<any>;
1677
+ }
1678
+ declare function defineAgent<I = any, R = any>(config: AgentConfig<I, R>): Agent<I, R>;
1679
+
1680
+ interface AiSdkEngineOptions {
1681
+ /** Standard API key (sk-ant-api...), sent as x-api-key. */
1682
+ apiKey?: string;
1683
+ /** Bearer token (e.g. sk-ant-oat... OAuth tokens, or the future platform
1684
+ * LLM proxy's scoped tokens), sent as Authorization: Bearer. */
1685
+ authToken?: string;
1686
+ /** Override the provider base URL (future: the platform LLM proxy). */
1687
+ baseURL?: string;
1688
+ }
1689
+ /** Reference TurnEngine over the Vercel AI SDK. One turn per call: tools are
1690
+ * declared WITHOUT execute functions, so generateText returns tool calls
1691
+ * without running them or looping. */
1692
+ declare class AiSdkEngine implements TurnEngine {
1693
+ private opts;
1694
+ constructor(opts: AiSdkEngineOptions);
1695
+ resolveModel(model: string): LanguageModel;
1696
+ turn(req: TurnRequest): Promise<TurnResult>;
1697
+ }
1698
+
1699
+ type LlmOptions<R> = {
1700
+ /** Provider-prefixed model, e.g. "anthropic/claude-sonnet-4-6". */
1701
+ model: string;
1702
+ prompt: string;
1703
+ /** Optional system instructions. */
1704
+ system?: string;
1705
+ /** Standard Schema for the typed result. Omit for plain text. */
1706
+ result?: StandardSchemaV1<unknown, R>;
1707
+ /** Max wall-clock ms for the step (default 300000). */
1708
+ timeout?: number;
1709
+ };
1710
+ /**
1711
+ * Run one typed LLM call as a single checkpointed flow step. No tools, no loop:
1712
+ * it's an ordinary step, so the result is cached on replay and retried on
1713
+ * transient failure. Pass a `result` schema for structured output (validated
1714
+ * with a bounded repair loop) or omit it to get the model's plain text.
1715
+ *
1716
+ * Takes the flow `ctx` explicitly so it can be called as a free function:
1717
+ *
1718
+ * const triage = await experimental.LlmFlowStep(ctx, "classify", {
1719
+ * model: "anthropic/claude-haiku-4-5",
1720
+ * prompt: `Classify this ticket: ${body}`,
1721
+ * result: z.object({ category: z.enum(["billing", "bug", "other"]) }),
1722
+ * });
1723
+ */
1724
+ declare function LlmFlowStep<R>(ctx: any, name: string, options: LlmOptions<R> & {
1725
+ result: StandardSchemaV1<unknown, R>;
1726
+ }): Promise<R>;
1727
+ declare function LlmFlowStep(ctx: any, name: string, options: LlmOptions<never>): Promise<string>;
1728
+
1729
+ type experimental_Agent<I = any, R = any> = Agent<I, R>;
1730
+ type experimental_AgentConfig<I = any, R = any> = AgentConfig<I, R>;
1731
+ type experimental_AgentMessage = AgentMessage;
1732
+ type experimental_AiSdkEngine = AiSdkEngine;
1733
+ declare const experimental_AiSdkEngine: typeof AiSdkEngine;
1734
+ declare const experimental_LlmFlowStep: typeof LlmFlowStep;
1735
+ type experimental_LlmOptions<R> = LlmOptions<R>;
1736
+ type experimental_ScriptedEngine = ScriptedEngine;
1737
+ declare const experimental_ScriptedEngine: typeof ScriptedEngine;
1738
+ type experimental_ToolDefinition<P = any> = ToolDefinition<P>;
1739
+ type experimental_TurnEngine = TurnEngine;
1740
+ type experimental_TurnRequest = TurnRequest;
1741
+ type experimental_TurnResult = TurnResult;
1742
+ declare const experimental_defineAgent: typeof defineAgent;
1743
+ declare const experimental_defineTool: typeof defineTool;
1744
+ declare const experimental_scriptedTurn: typeof scriptedTurn;
1745
+ declare namespace experimental {
1746
+ export { type experimental_Agent as Agent, type experimental_AgentConfig as AgentConfig, type experimental_AgentMessage as AgentMessage, experimental_AiSdkEngine as AiSdkEngine, experimental_LlmFlowStep as LlmFlowStep, type experimental_LlmOptions as LlmOptions, experimental_ScriptedEngine as ScriptedEngine, type experimental_ToolDefinition as ToolDefinition, type experimental_TurnEngine as TurnEngine, type experimental_TurnRequest as TurnRequest, type experimental_TurnResult as TurnResult, experimental_defineAgent as defineAgent, experimental_defineTool as defineTool, experimental_scriptedTurn as scriptedTurn };
1747
+ }
1748
+
1457
1749
  declare const createTraceAPI: typeof createTraceAPI$1;
1458
1750
  declare function ksuid(): string;
1459
1751
 
1752
+ declare const notify: NotifyApi;
1753
+
1460
1754
  type IDWhereCondition = {
1461
1755
  equals?: string | null;
1462
1756
  notEquals?: string | null;
@@ -1695,5 +1989,18 @@ type FlowListResult = {
1695
1989
  hasNextPage: boolean;
1696
1990
  };
1697
1991
  };
1992
+ type SignedLinkOptions<Inputs = any> = {
1993
+ inputs?: Inputs;
1994
+ expiresAt?: Date;
1995
+ reusable?: boolean;
1996
+ };
1997
+ type SignedLinkResult = {
1998
+ url: string;
1999
+ expiresAt: Date | null;
2000
+ flow: {
2001
+ name: string;
2002
+ runId: string | null;
2003
+ };
2004
+ };
1698
2005
 
1699
- export { type BooleanArrayQueryWhereCondition, type BooleanArrayWhereCondition, type BooleanWhereCondition, type ContextAPI, type DateArrayQueryWhereCondition, type DateArrayWhereCondition, type DateQueryInput, type DateWhereCondition, Duration, type DurationString, type DurationWhereCondition, ErrorPresets, type Errors, type ExtractStageKeys, File, type FlowConfig, type FlowConfigAPI, type FlowContext, type FlowFunction, type FlowListOptions, type FlowListResult, type FlowRun, type FlowRunStatus, type FlowRunStep, FlowsAPI, type FuncWithConfig, type FunctionConfig, type Hardware, type IDWhereCondition, InlineFile, type ListResult, ModelAPI, NonRetriableError, type NullableHardware, type NumberArrayQueryWhereCondition, type NumberArrayWhereCondition, type NumberWhereCondition, PERMISSION_STATE, type PageInfo, type PartialPageInfo, Permissions, type Printer, type RelativeDateString, RequestHeaders, type Response, RetryBackoffExponential, RetryBackoffLinear, RetryConstant, STEP_STATUS, STEP_TYPE, Signature, type SortDirection, type Step, type StringArrayQueryWhereCondition, type StringArrayWhereCondition, type StringWhereCondition, type Task, TaskAPI, type TaskCreateOptions, type TaskFlowFunction, type TaskStatus, type TimestampQueryInput, type TraceAPI, type TraceAttributeValue, type TraceAttributes, type UI, type UIApiResponses, checkBuiltInPermissions, createFlowContext, createTraceAPI, handleFlow, handleJob, handleRequest, handleRoute, handleSubscriber, ksuid, tracing, useDatabase };
2006
+ export { type BooleanArrayQueryWhereCondition, type BooleanArrayWhereCondition, type BooleanWhereCondition, type ContextAPI, type DateArrayQueryWhereCondition, type DateArrayWhereCondition, type DateQueryInput, type DateWhereCondition, Duration, type DurationString, type DurationWhereCondition, type EmailContent, type EmailInput, type EmailRecipientGroup, type EmailRecipients, ErrorPresets, type Errors, type ExtractStageKeys, File, type FlowConfig, type FlowConfigAPI, type FlowContext, type FlowFunction, type FlowListOptions, type FlowListResult, type FlowRun, type FlowRunStatus, type FlowRunStep, FlowsAPI, type FuncWithConfig, type FunctionConfig, type Hardware, type IDWhereCondition, InlineFile, type ListResult, ModelAPI, NonRetriableError, type NotifyApi, type NullableHardware, type NumberArrayQueryWhereCondition, type NumberArrayWhereCondition, type NumberWhereCondition, PERMISSION_STATE, type PageInfo, type PartialPageInfo, Permissions, type Printer, type RecipientIdentity, type RecipientUser, type RelativeDateString, RequestHeaders, type Response, RetryBackoffExponential, RetryBackoffLinear, RetryConstant, STEP_STATUS, STEP_TYPE, Signature, type SignedLinkOptions, type SignedLinkResult, type SortDirection, type Step, type StringArrayQueryWhereCondition, type StringArrayWhereCondition, type StringWhereCondition, type Task, TaskAPI, type TaskCreateOptions, type TaskFlowFunction, type TaskStatus, type TimestampQueryInput, type TraceAPI, type TraceAttributeValue, type TraceAttributes, type UI, type UIApiResponses, checkBuiltInPermissions, createFlowContext, createIntegrationServer, createNotifier, createTraceAPI, experimental, handleFlow, handleJob, handleRequest, handleRoute, handleSubscriber, insertNewStep, ksuid, notify, tracing, useDatabase };