@runtypelabs/sdk 1.22.0 → 1.23.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.cts CHANGED
@@ -1,1685 +1,1687 @@
1
1
  /**
2
- * SDK type definitions — self-contained for zero-dependency npm distribution.
2
+ * Error Handling Types
3
3
  *
4
- * These types mirror the canonical entity definitions in @runtypelabs/shared
5
- * (packages/shared/src/types/entities.ts and client-types.ts). When adding or
6
- * modifying entity fields, update both locations.
4
+ * Provides consistent error handling configuration across all step types
5
+ * with support for retry, model fallback, step fallback, and flow fallback.
6
+ *
7
+ * Note: These types are inlined from the internal shared package to avoid
8
+ * requiring users to install @runtypelabs/shared.
7
9
  */
8
- type JsonPrimitive = string | number | boolean | null;
9
- type JsonArray = JsonValue[];
10
- type JsonObject = {
11
- [key: string]: JsonValue;
12
- };
13
- type JsonValue = JsonPrimitive | JsonObject | JsonArray;
14
- type Metadata = JsonObject;
15
- interface JSONSchema {
16
- type: 'object' | 'string' | 'number' | 'boolean' | 'array' | 'null';
17
- properties?: Record<string, JSONSchema>;
18
- required?: string[];
19
- items?: JSONSchema;
20
- description?: string;
21
- default?: JsonValue;
22
- enum?: JsonPrimitive[];
23
- minimum?: number;
24
- maximum?: number;
25
- minLength?: number;
26
- maxLength?: number;
27
- pattern?: string;
28
- }
29
- interface ClientConfig {
30
- apiKey?: string;
31
- baseUrl?: string;
32
- apiVersion?: string;
33
- timeout?: number;
34
- headers?: Record<string, string>;
35
- }
36
- interface PaginationResponse<T> {
37
- data: T[];
38
- pagination: {
39
- nextCursor: string | null;
40
- prevCursor: string | null;
41
- hasMore: boolean;
42
- hasPrev: boolean;
43
- limit: number;
44
- currentOffset: number;
45
- totalPages?: number;
46
- currentPage?: number;
47
- totalCount?: number;
48
- };
49
- }
50
- interface ApiResponse<T> {
51
- data?: T;
52
- success?: boolean;
53
- error?: string;
54
- message?: string;
55
- }
56
- interface FlowStep {
57
- id: string;
58
- flowId: string;
59
- type: string;
60
- name: string;
61
- order: number;
62
- enabled: boolean;
63
- config: Record<string, unknown>;
64
- outputVariable?: string | null;
65
- streamOutput?: boolean;
66
- createdAt: string;
67
- updatedAt: string;
10
+ type ErrorHandlingMode = 'fail' | 'continue' | 'fallback';
11
+ /**
12
+ * Base fallback configuration
13
+ */
14
+ interface BaseFallback {
15
+ delay?: number;
68
16
  }
69
- interface Flow {
70
- id: string;
71
- name: string;
72
- description?: string | null;
73
- status: 'draft' | 'active' | 'paused' | 'failed';
74
- config?: JsonObject;
75
- userId: string;
76
- organizationId: string | null;
77
- createdAt: string;
78
- updatedAt: string;
79
- lastRunAt?: string | null;
80
- /** Flow steps embedded in the flow response */
81
- flowSteps?: FlowStep[];
82
- /** Number of steps in the flow */
83
- stepCount?: number;
17
+ /**
18
+ * Retry fallback - retry the same step with same config
19
+ */
20
+ interface RetryFallback extends BaseFallback {
21
+ type: 'retry';
84
22
  }
85
- interface Prompt$1 {
86
- id: string;
87
- name: string;
88
- text: string;
89
- responseFormat: 'default' | 'json' | 'markdown' | 'html' | 'xml';
23
+ /**
24
+ * Model fallback for prompts - retry with different model/settings
25
+ */
26
+ interface ModelFallback extends BaseFallback {
27
+ type: 'model';
90
28
  model: string;
91
- isStreamed: boolean;
92
- tools: string[];
93
- inputVariables?: string;
94
- estimatedTokens?: number;
95
- estimatedCost?: string;
96
- userId: string;
97
- createdAt: string;
98
- updatedAt: string;
99
- flows?: FlowAttachment[];
100
- }
101
- interface FlowAttachment {
102
- flowId: string;
103
- flowName: string;
104
- order: number;
105
- }
106
- interface RuntypeRecord {
107
- id: string;
108
- type: string;
109
- name: string;
110
- metadata: Metadata;
111
- metadataLabels?: {
112
- [key: string]: string;
113
- };
114
- metadataSchema?: {
115
- keys: string[];
116
- keyMapping?: {
117
- [key: string]: string;
118
- };
119
- keyTypes?: {
120
- [key: string]: string;
121
- };
122
- types?: {
123
- [key: string]: string;
124
- };
125
- sizeKb: number;
126
- keyCount: number;
127
- updatedAt: string;
128
- };
129
- messages?: Array<{
130
- role: 'user' | 'assistant';
131
- content: string | unknown[];
132
- }> | null;
133
- availableFields?: string[];
134
- userId: string;
135
- organizationId?: string | null;
136
- createdAt: string;
137
- updatedAt: string;
138
- }
139
- interface ApiKey {
140
- id: string;
141
- name: string;
142
- keyPrefix: string;
143
- searchHint?: string;
144
- permissions: string[];
145
- isActive: boolean;
146
- expiresAt?: string;
147
- allowedIps: string[];
148
- createdAt: string;
149
- updatedAt?: string;
150
- lastUsedAt?: string;
151
- }
152
- interface ModelConfig {
153
- id: string;
154
- provider: string;
155
- modelId: string;
156
- displayName?: string;
157
- /** @deprecated Use keyStatus instead */
158
- supportsCustomKey: boolean;
159
- keyStatus?: 'platform' | 'custom' | 'needs_setup';
160
- costPer1kTokens?: number;
161
- contextLength?: number;
162
- maxOutputTokens?: number;
29
+ temperature?: number;
163
30
  maxTokens?: number;
164
- supportsStreaming?: boolean;
165
- supportedResponseFormats?: string[];
166
- supportsSearch?: boolean;
167
- isEnabled: boolean;
168
- isDefault: boolean;
169
- settings: JsonObject;
170
- createdAt: string;
171
- updatedAt: string;
172
- providerKeyId?: string | null;
173
- requiresIntegration?: string;
174
- apiKey?: string;
175
- scope?: 'personal' | 'organization';
176
- organizationId?: string;
31
+ topP?: number;
32
+ topK?: number;
33
+ frequencyPenalty?: number;
34
+ presencePenalty?: number;
35
+ seed?: number;
177
36
  }
178
- interface UserProfile {
179
- id: string;
180
- firstName?: string;
181
- lastName?: string;
182
- email: string;
183
- preferences?: {
184
- theme?: 'light' | 'dark' | 'system';
185
- notifications?: boolean;
186
- defaultModel?: string;
187
- };
37
+ /**
38
+ * Step fallback for context steps - run a different step type
39
+ */
40
+ interface StepFallback extends BaseFallback {
41
+ type: 'step';
42
+ stepType: string;
43
+ stepConfig: Record<string, unknown>;
188
44
  }
189
- interface CreateFlowRequest {
190
- name: string;
191
- description?: string;
192
- flowSteps?: Array<{
193
- type: 'prompt' | 'context' | 'condition' | 'output' | 'email';
194
- name: string;
195
- order?: number;
196
- enabled?: boolean;
197
- config: JsonObject;
198
- }>;
45
+ /**
46
+ * Flow fallback - call another flow
47
+ */
48
+ interface FlowFallback extends BaseFallback {
49
+ type: 'flow';
50
+ flowId: string;
51
+ inputs?: Record<string, unknown>;
199
52
  }
200
- interface CreatePromptRequest {
201
- flowIds?: string[];
202
- name: string;
203
- text: string;
204
- responseFormat?: 'json' | 'markdown' | 'text' | 'html' | 'xml';
205
- model?: string;
206
- inputVariables?: string;
53
+ /**
54
+ * Union of all prompt fallback types
55
+ */
56
+ type PromptFallback = RetryFallback | ModelFallback;
57
+ /**
58
+ * Union of all context step fallback types
59
+ */
60
+ type ContextFallback = RetryFallback | StepFallback | FlowFallback;
61
+ /**
62
+ * Error handling configuration for prompts
63
+ */
64
+ interface PromptErrorHandling {
65
+ onError: ErrorHandlingMode;
66
+ fallbacks?: PromptFallback[];
207
67
  }
208
- interface CreateRecordRequest {
209
- type: string;
210
- name: string;
211
- metadata?: Metadata;
212
- }
213
- interface BulkEditCondition {
214
- field: string;
215
- operator: 'equals' | 'equals_ci' | 'not_equals' | 'contains' | 'not_contains';
216
- value: string | number | boolean;
217
- }
218
- interface BulkEditRequest {
219
- recordIds?: string[];
220
- conditions?: BulkEditCondition[];
221
- updates?: JsonObject;
222
- deleteFields?: string[];
223
- dryRun?: boolean;
224
- applyToAll?: boolean;
225
- }
226
- interface BulkEditResult {
227
- id: string;
228
- before: JsonObject;
229
- after: JsonObject;
230
- }
231
- interface BulkEditResponse {
232
- data: BulkEditResult[];
233
- recordIds?: number[];
234
- }
235
- interface ProviderApiKey {
236
- id: number;
237
- provider: 'openai' | 'anthropic' | 'huggingface' | 'google' | 'xai' | 'mixlayer' | 'togetherai';
238
- name: string;
239
- keyPreview: string;
240
- isDefault: boolean;
241
- isActive: boolean;
242
- usageCount: number;
243
- lastUsedAt?: string;
244
- createdAt: string;
245
- updatedAt: string;
246
- }
247
- interface CreateProviderKeyRequest {
248
- provider: 'openai' | 'anthropic' | 'huggingface' | 'google' | 'xai' | 'mixlayer' | 'togetherai';
249
- name: string;
250
- apiKey: string;
251
- isDefault?: boolean;
252
- }
253
- interface UpdateProviderKeyRequest {
254
- name?: string;
255
- apiKey?: string;
256
- isDefault?: boolean;
257
- isActive?: boolean;
258
- }
259
- interface CreateApiKeyRequest {
260
- name: string;
261
- permissions?: string[];
262
- expiresAt?: string;
263
- allowedIps?: string[];
264
- environment?: 'test' | 'production';
265
- }
266
- interface CreateModelConfigRequest {
267
- provider: 'mixlayer' | 'openai' | 'anthropic' | 'google' | 'xai' | 'huggingface' | 'togetherai';
268
- modelId: string;
269
- apiKey?: string;
270
- settings?: JsonObject;
271
- }
272
- /** Content part types for multi-modal messages */
273
- interface TextContentPart {
274
- type: 'text';
275
- text: string;
276
- }
277
- interface ImageContentPart {
278
- type: 'image';
279
- image: string;
280
- mimeType?: string;
281
- }
282
- interface FileContentPart {
283
- type: 'file';
284
- data: string;
285
- mimeType: string;
286
- filename: string;
68
+ /**
69
+ * Error handling configuration for context steps
70
+ */
71
+ interface ContextErrorHandling {
72
+ onError: ErrorHandlingMode;
73
+ fallbacks?: ContextFallback[];
287
74
  }
288
- type MessageContent = string | Array<TextContentPart | ImageContentPart | FileContentPart>;
75
+
289
76
  /**
290
- * Options for upsert mode - controls conflict detection and versioning
77
+ * FlowResult - Wrapper for streaming flow execution responses
78
+ *
79
+ * Provides convenient methods for processing streaming responses
80
+ * from the Runtype API dispatch endpoint.
291
81
  */
292
- interface UpsertOptions$1 {
293
- /** Whether to create a version snapshot before updating (default: true) */
294
- createVersionOnChange?: boolean;
295
- /** Allow overwriting changes made via dashboard/API (default: false) */
296
- allowOverwriteExternalChanges?: boolean;
82
+
83
+ /**
84
+ * Result wrapper for flow execution
85
+ *
86
+ * Provides multiple ways to consume the streaming response:
87
+ * - `.stream(callbacks)` - Process with callbacks
88
+ * - `.getResult(stepName)` - Get result from a specific step
89
+ * - `.getAllResults()` - Get all step results
90
+ * - `.raw` - Access the raw Response for manual handling
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * const result = await flow.run(apiClient, options)
95
+ *
96
+ * // Option 1: Process with callbacks
97
+ * const summary = await result.stream({
98
+ * onStepDelta: (text) => process.stdout.write(text),
99
+ * })
100
+ *
101
+ * // Option 2: Just get a specific step's result
102
+ * const analysis = await result.getResult('Analyze Data')
103
+ *
104
+ * // Option 3: Get all results
105
+ * const allResults = await result.getAllResults()
106
+ * ```
107
+ */
108
+ declare class FlowResult {
109
+ private response;
110
+ private consumed;
111
+ private cachedSummary;
112
+ constructor(response: Response, summary?: FlowSummary);
113
+ /**
114
+ * Get the raw Response object for manual handling
115
+ *
116
+ * Note: The response body can only be consumed once.
117
+ * Using this will prevent using other methods like stream() or getResult().
118
+ */
119
+ get raw(): Response;
120
+ /**
121
+ * Check if the response has already been consumed
122
+ */
123
+ get isConsumed(): boolean;
124
+ /**
125
+ * Process the streaming response with callbacks
126
+ *
127
+ * @param callbacks - Callbacks for different event types
128
+ * @returns Promise resolving to FlowSummary when complete
129
+ *
130
+ * @example
131
+ * ```typescript
132
+ * const summary = await result.stream({
133
+ * onStepStart: (event) => console.log('Starting:', event.name),
134
+ * onStepDelta: (text) => process.stdout.write(text),
135
+ * onStepComplete: (result, event) => console.log('Done:', event.name),
136
+ * onFlowComplete: (event) => console.log('Flow complete!'),
137
+ * })
138
+ * ```
139
+ */
140
+ stream(callbacks?: StreamCallbacks): Promise<FlowSummary>;
141
+ /**
142
+ * Get the result from a specific step by its name
143
+ *
144
+ * Matches against the `name` property you set when creating the step.
145
+ * - **Case-sensitive**: `'Analyze'` ≠ `'analyze'`
146
+ * - **Exact match only**: no partial or fuzzy matching
147
+ * - Returns `undefined` if no step with that name is found
148
+ *
149
+ * @param stepName - The exact step name (from the `name` property when creating the step)
150
+ * @returns The step's result, or undefined if not found
151
+ *
152
+ * @example
153
+ * ```typescript
154
+ * // When building:
155
+ * .prompt({ name: 'Analyze Screenshot', model: 'gpt-4', ... })
156
+ *
157
+ * // When retrieving (must match exactly):
158
+ * const analysis = await result.getResult('Analyze Screenshot') // ✓ Works
159
+ * const analysis = await result.getResult('analyze screenshot') // ✗ undefined
160
+ * ```
161
+ */
162
+ getResult(stepName: string): Promise<any>;
163
+ /**
164
+ * Get all step results as a Map
165
+ *
166
+ * @returns Map of step name to result
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * const allResults = await result.getAllResults()
171
+ * for (const [stepName, result] of allResults) {
172
+ * console.log(stepName, result)
173
+ * }
174
+ * ```
175
+ */
176
+ getAllResults(): Promise<Map<string, any>>;
177
+ /**
178
+ * Get the flow summary after processing
179
+ *
180
+ * @returns FlowSummary with execution details
181
+ */
182
+ getSummary(): Promise<FlowSummary>;
183
+ /**
184
+ * Ensure the stream has been processed and return the summary
185
+ */
186
+ private ensureSummary;
187
+ /**
188
+ * Ensure the response hasn't been consumed yet
189
+ */
190
+ private ensureNotConsumed;
297
191
  }
192
+
298
193
  /**
299
- * Environment type for dispatch requests
194
+ * FlowBuilder - Fluent builder for constructing dispatch configurations
195
+ *
196
+ * Provides a chainable API for building flows with steps, making flow
197
+ * construction more readable and type-safe.
198
+ *
199
+ * @example
200
+ * ```typescript
201
+ * import { FlowBuilder } from '@runtypelabs/sdk'
202
+ *
203
+ * const config = new FlowBuilder()
204
+ * .createFlow({ name: "My Flow" })
205
+ * .withRecord({ name: "Record", type: "data", metadata: { key: "value" } })
206
+ * .fetchUrl({ name: "Fetch", url: "https://api.example.com", outputVariable: "data" })
207
+ * .prompt({ name: "Process", model: "gpt-4", userPrompt: "Analyze: {{data}}" })
208
+ * .withOptions({ streamResponse: true, flowMode: "virtual" })
209
+ * .build()
210
+ * ```
300
211
  */
301
- type DispatchEnvironment = 'development' | 'production';
302
- interface DispatchRequest {
303
- record?: {
304
- id?: number | string;
305
- name?: string;
306
- type?: string;
307
- metadata?: Metadata;
308
- };
309
- flow: {
310
- id?: string;
311
- name?: string;
312
- steps?: Array<any>;
313
- };
314
- messages?: Array<{
315
- role: 'system' | 'user' | 'assistant';
316
- content: MessageContent;
212
+
213
+ interface PromptStepConfig$1 {
214
+ name: string;
215
+ model: string;
216
+ userPrompt: string;
217
+ systemPrompt?: string;
218
+ previousMessages?: string | Array<{
219
+ role: string;
220
+ content: string;
317
221
  }>;
318
- secrets?: Record<string, string>;
319
- inputs?: Record<string, unknown>;
320
- options?: {
321
- streamResponse?: boolean;
322
- modelOverride?: string;
323
- recordMode?: 'existing' | 'create' | 'virtual';
324
- flowMode?: 'existing' | 'create' | 'virtual' | 'upsert';
325
- storeResults?: boolean;
326
- autoAppendMetadata?: boolean;
327
- debugMode?: boolean;
328
- environment?: DispatchEnvironment;
329
- createVersion?: boolean;
330
- versionType?: 'published' | 'draft' | 'test' | 'virtual';
331
- versionLabel?: string;
332
- versionNotes?: string;
333
- flowVersionId?: string;
334
- upsertOptions?: UpsertOptions$1;
335
- flowTimeoutMs?: number;
336
- stepTimeoutMs?: number;
337
- };
338
- }
339
- interface ListParams {
340
- limit?: number;
341
- cursor?: string;
342
- direction?: 'next' | 'prev';
343
- }
344
- interface RecordListParams extends ListParams {
345
- metadataKeys?: string;
346
- metadataKeysAll?: string;
347
- minFields?: number;
348
- maxFields?: number;
349
- metadataTypes?: string;
350
- hasLargeFields?: boolean;
351
- minSizeKb?: number;
352
- maxSizeKb?: number;
353
- sortBy?: string;
354
- sortOrder?: 'asc' | 'desc';
355
- includeFields?: boolean;
222
+ outputVariable?: string;
223
+ responseFormat?: 'text' | 'json';
224
+ temperature?: number;
225
+ topP?: number;
226
+ topK?: number;
227
+ frequencyPenalty?: number;
228
+ presencePenalty?: number;
229
+ seed?: number;
230
+ maxTokens?: number;
231
+ /**
232
+ * Enable reasoning/extended thinking for models that support it.
233
+ * - `true`: Enable with provider defaults
234
+ * - `ReasoningConfig`: Fine-grained control over reasoning behavior
235
+ *
236
+ * @example GPT-5 with streaming reasoning
237
+ * ```typescript
238
+ * reasoning: { enabled: true, reasoningSummary: 'auto' }
239
+ * ```
240
+ */
241
+ reasoning?: boolean | ReasoningConfig;
242
+ streamOutput?: boolean;
243
+ /** Tools configuration - supports saved tools (toolIds) and inline runtime tools */
244
+ tools?: ToolsConfig;
245
+ /** Error handling configuration - supports simple mode or fallback chains */
246
+ errorHandling?: ErrorHandlingMode | PromptErrorHandling;
247
+ enabled?: boolean;
248
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
249
+ when?: string;
356
250
  }
357
- interface Tool {
358
- id: string;
359
- userId: string;
360
- organizationId?: string;
251
+ interface FetchUrlStepConfig$1 {
361
252
  name: string;
362
- description: string;
363
- toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
364
- parametersSchema: JSONSchema;
365
- config: ToolConfig;
366
- isActive: boolean;
367
- createdAt: string;
368
- updatedAt: string;
369
- }
370
- type ToolConfig = FlowToolConfig | CustomToolConfig | ExternalToolConfig | LocalToolConfig | SubagentToolConfig;
371
- interface FlowToolConfig {
372
- flowId?: string;
373
- toolId?: string;
374
- parameterMapping: Record<string, string>;
375
- outputMapping?: string;
376
- }
377
- interface CustomToolConfig {
378
- code: string;
379
- timeout: number;
380
- allowedApis: string[];
381
- }
382
- interface ExternalToolConfig {
383
253
  url: string;
384
- method: 'GET' | 'POST' | 'PUT' | 'DELETE';
254
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
385
255
  headers?: Record<string, string>;
386
256
  body?: string;
387
- authType?: 'none' | 'bearer' | 'api_key';
257
+ responseType?: 'json' | 'text' | 'xml';
258
+ markdownIfAvailable?: boolean;
259
+ outputVariable?: string;
260
+ fetchMethod?: 'http' | 'firecrawl';
261
+ firecrawl?: {
262
+ formats?: string[];
263
+ [key: string]: any;
264
+ };
265
+ /** Error handling configuration - supports simple mode or fallback chains */
266
+ errorHandling?: ErrorHandlingMode | ContextErrorHandling;
267
+ streamOutput?: boolean;
268
+ enabled?: boolean;
269
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
270
+ when?: string;
388
271
  }
389
- interface LocalToolConfig {
390
- [key: string]: JsonValue;
272
+ interface CrawlStepConfig {
273
+ name: string;
274
+ url: string;
275
+ limit?: number;
276
+ depth?: number;
277
+ source?: string;
278
+ formats?: string[];
279
+ render?: boolean;
280
+ maxAge?: number;
281
+ modifiedSince?: string;
282
+ options?: Record<string, unknown>;
283
+ authenticate?: Record<string, unknown>;
284
+ cookies?: Array<Record<string, unknown>>;
285
+ setExtraHTTPHeaders?: Record<string, string>;
286
+ gotoOptions?: Record<string, unknown>;
287
+ waitForSelector?: string;
288
+ rejectResourceTypes?: string[];
289
+ rejectRequestPattern?: string | string[];
290
+ userAgent?: string;
291
+ jsonOptions?: Record<string, unknown>;
292
+ outputVariable?: string;
293
+ streamOutput?: boolean;
294
+ errorHandling?: ErrorHandlingMode | ContextErrorHandling;
295
+ pollIntervalMs?: number;
296
+ completionTimeoutMs?: number;
297
+ enabled?: boolean;
298
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
299
+ when?: string;
391
300
  }
392
- interface SubagentToolConfig {
393
- agentId?: string;
394
- agent?: JsonObject;
395
- allowedTools: string[];
396
- maxTurns?: number;
397
- maxCost?: number;
398
- timeoutMs?: number;
399
- outputFormat?: 'text' | 'json' | 'last_message';
400
- inheritMessages?: boolean;
401
- taskTemplate?: string;
301
+ interface TransformDataStepConfig$1 {
302
+ name: string;
303
+ script: string;
304
+ outputVariable?: string;
305
+ sandboxProvider?: 'quickjs' | 'daytona' | 'cloudflare-worker';
306
+ streamOutput?: boolean;
307
+ enabled?: boolean;
308
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
309
+ when?: string;
402
310
  }
403
- interface BuiltInTool {
404
- id: string;
311
+ interface SetVariableStepConfig$1 {
405
312
  name: string;
406
- description: string;
407
- category: 'image_generation' | 'web_search' | 'web_scraping' | 'code_execution' | 'file_operations' | 'data_analysis' | 'knowledge_retrieval' | 'text_to_speech' | 'voice_processing' | 'third_party_api' | 'artifact' | 'data_management' | 'commerce' | 'browser';
408
- providers: string[];
409
- parametersSchema: JSONSchema;
410
- defaultConfig?: JsonObject;
411
- documentationUrl?: string;
313
+ variableName: string;
314
+ value: string | number | boolean | object;
315
+ enabled?: boolean;
316
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
317
+ when?: string;
412
318
  }
413
- interface ToolExecution {
414
- id: string;
415
- toolId: string;
416
- flowExecutionId?: string;
417
- stepId?: string;
418
- userId: string;
419
- inputParameters: JsonObject;
420
- outputResult: JsonValue;
421
- status: 'pending' | 'success' | 'failed';
422
- errorMessage?: string;
423
- executionTimeMs?: number;
424
- createdAt: string;
319
+ interface ConditionalStepConfig$1 {
320
+ name: string;
321
+ condition: string;
322
+ trueSteps?: any[];
323
+ falseSteps?: any[];
324
+ enabled?: boolean;
325
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
326
+ when?: string;
425
327
  }
426
- interface CreateToolRequest {
328
+ interface SearchStepConfig$1 {
427
329
  name: string;
428
- description: string;
429
- toolType: 'flow' | 'custom' | 'external' | 'subagent';
430
- parametersSchema: JSONSchema;
431
- config: ToolConfig;
330
+ provider: string;
331
+ query: string;
332
+ maxResults?: number;
333
+ outputVariable?: string;
334
+ returnCitations?: boolean;
335
+ /** Error handling configuration - supports simple mode or fallback chains */
336
+ errorHandling?: ErrorHandlingMode | ContextErrorHandling;
337
+ streamOutput?: boolean;
338
+ enabled?: boolean;
339
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
340
+ when?: string;
432
341
  }
433
- interface UpdateToolRequest {
434
- name?: string;
435
- description?: string;
436
- parametersSchema?: JSONSchema;
437
- config?: ToolConfig;
438
- isActive?: boolean;
342
+ interface SendEmailStepConfig$1 {
343
+ name: string;
344
+ to: string;
345
+ from?: string;
346
+ subject: string;
347
+ html: string;
348
+ outputVariable?: string;
349
+ /** Error handling configuration - supports simple mode or fallback chains */
350
+ errorHandling?: ErrorHandlingMode | ContextErrorHandling;
351
+ streamOutput?: boolean;
352
+ enabled?: boolean;
353
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
354
+ when?: string;
439
355
  }
440
- interface ExecuteToolRequest {
441
- toolId: string;
442
- parameters: JsonObject;
356
+ interface SendStreamStepConfig$1 {
357
+ name: string;
358
+ message: string;
359
+ enabled?: boolean;
360
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
361
+ when?: string;
443
362
  }
444
- interface ExecuteToolResponse {
445
- executionId: string;
446
- result: JsonValue;
447
- status: 'success' | 'failed';
448
- errorMessage?: string;
449
- executionTimeMs: number;
363
+ /**
364
+ * Operator allowlist for chip-style record filters. Mirrors the API's
365
+ * `record-filter-compiler.ts`. Kept inline here to avoid a hard dependency
366
+ * on `@runtypelabs/shared` from the published SDK.
367
+ */
368
+ type RecordFilterOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'between' | 'contains' | 'startsWith' | 'endsWith' | 'in' | 'notIn' | 'isSet' | 'isNotSet' | 'isTrue' | 'isFalse' | 'withinLastDays' | 'olderThanDays';
369
+ interface RecordFilterCondition {
370
+ field: string;
371
+ op: RecordFilterOperator;
372
+ value?: unknown;
450
373
  }
451
- interface DeploySandboxRequest {
452
- code: string;
453
- packageJson?: string;
454
- language?: 'javascript' | 'typescript' | 'python';
455
- port?: number;
456
- sandboxId?: string;
457
- startCommand?: string;
458
- files?: Record<string, string>;
374
+ interface RecordFilterGroup {
375
+ op: 'and' | 'or';
376
+ conditions: Array<RecordFilterCondition | RecordFilterGroup>;
459
377
  }
460
- interface DeploySandboxResponse {
461
- sandboxId: string;
462
- previewUrl: string;
463
- output: string;
464
- status: 'running' | 'error';
465
- error?: string;
466
- }
467
- interface DeployCfSandboxRequest {
468
- code: string;
469
- packageJson?: string;
470
- language?: 'javascript' | 'typescript' | 'python';
471
- port?: number;
472
- sandboxId?: string;
473
- startCommand?: string;
474
- files?: Record<string, string>;
475
- }
476
- interface DeployCfSandboxResponse {
477
- sandboxId: string;
478
- previewUrl: string;
479
- output: string;
480
- status: 'running' | 'error';
481
- stage?: 'validate_port' | 'validate_files' | 'write_package_json' | 'npm_install' | 'write_main_file' | 'write_additional_files' | 'start_process' | 'expose_port';
482
- error?: string;
378
+ interface RecordFilter {
379
+ type: string;
380
+ where?: RecordFilterCondition | RecordFilterGroup;
483
381
  }
484
- interface ModelUsageQueryParams {
485
- startDate?: string;
486
- endDate?: string;
487
- period?: 'today' | 'yesterday' | 'last_7_days' | 'last_30_days' | 'current_month' | 'last_month' | 'current_year';
488
- granularity?: 'hour' | 'day' | 'week' | 'month';
489
- modelConfigId?: string;
382
+ interface RetrieveRecordStepConfig$1 {
383
+ name: string;
384
+ recordType?: string;
385
+ recordName?: string;
386
+ /**
387
+ * Optional chip-style filter (metadata + top-level columns: id, name,
388
+ * createdAt, updatedAt). Coexists with recordType/recordName for
389
+ * backward compatibility; the API executor prefers recordFilter when
390
+ * both are set.
391
+ */
392
+ recordFilter?: RecordFilter;
393
+ fieldsToInclude?: string[];
394
+ fieldsToExclude?: string[];
395
+ outputVariable?: string;
396
+ streamOutput?: boolean;
397
+ enabled?: boolean;
398
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
399
+ when?: string;
490
400
  }
491
- interface ModelUsageSummary {
492
- totalRequests: number;
493
- totalCost: number;
494
- totalTokens: number;
495
- platformCost?: number;
496
- userCost?: number;
497
- platformTokens?: number;
498
- userTokens?: number;
401
+ interface UpsertRecordStepConfig$1 {
402
+ name: string;
403
+ recordType: string;
404
+ recordName?: string;
405
+ sourceVariable?: string;
406
+ mergeStrategy?: 'merge' | 'replace';
407
+ outputVariable?: string;
408
+ /** Error handling configuration - supports simple mode or fallback chains */
409
+ errorHandling?: ErrorHandlingMode | ContextErrorHandling;
410
+ streamOutput?: boolean;
411
+ enabled?: boolean;
412
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
413
+ when?: string;
499
414
  }
500
- interface ModelUsageDetail {
501
- modelId: string;
502
- modelName?: string;
503
- provider: string;
504
- requestCount: number;
505
- totalCost: number;
506
- totalTokens: number;
507
- avgCostPerRequest: number;
415
+ interface VectorSearchStepConfig$1 {
416
+ name: string;
417
+ query: string;
418
+ recordType?: string;
419
+ embeddingModel?: string;
420
+ limit?: number;
421
+ threshold?: number;
422
+ outputVariable?: string;
423
+ streamOutput?: boolean;
424
+ enabled?: boolean;
425
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
426
+ when?: string;
508
427
  }
509
- interface ModelUsageTimeSeries {
510
- date: string;
511
- requests: number;
512
- cost: number;
513
- tokens: number;
428
+ interface GenerateEmbeddingStepConfig$1 {
429
+ name: string;
430
+ text: string;
431
+ embeddingModel?: string;
432
+ maxLength?: number;
433
+ outputVariable?: string;
434
+ streamOutput?: boolean;
435
+ enabled?: boolean;
436
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
437
+ when?: string;
514
438
  }
515
- interface ModelUsageResponse {
516
- meta: {
517
- startDate: string;
518
- endDate: string;
519
- period?: string;
520
- granularity?: string;
439
+ interface WaitUntilStepConfig$1 {
440
+ name: string;
441
+ delayMs?: number;
442
+ continueOnTimeout?: boolean;
443
+ poll?: {
444
+ enabled: boolean;
445
+ intervalMs?: number;
446
+ maxAttempts?: number;
447
+ condition?: string;
521
448
  };
522
- summary: ModelUsageSummary;
523
- usageByModel: Record<string, ModelUsageDetail>;
524
- timeSeries?: ModelUsageTimeSeries[];
449
+ outputVariable?: string;
450
+ /** Error handling configuration - supports simple mode or fallback chains */
451
+ errorHandling?: ErrorHandlingMode | ContextErrorHandling;
452
+ streamOutput?: boolean;
453
+ enabled?: boolean;
454
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
455
+ when?: string;
525
456
  }
526
- interface RuntimeTool {
457
+ interface SendEventStepConfig$1 {
527
458
  name: string;
528
- description: string;
529
- toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
530
- parametersSchema: JSONSchema;
531
- config?: RuntimeToolConfig;
532
- }
533
- type RuntimeToolConfig = RuntimeFlowToolConfig | RuntimeCustomToolConfig | RuntimeExternalToolConfig | RuntimeLocalToolConfig | RuntimeSubagentToolConfig;
534
- interface RuntimeLocalToolConfig {
535
- [key: string]: JsonValue;
536
- }
537
- interface RuntimeFlowToolConfig {
538
- flowId?: string;
539
- toolId?: string;
540
- parameterMapping?: Record<string, string>;
541
- outputMapping?: string;
459
+ provider: string;
460
+ eventName: string;
461
+ properties?: Record<string, any>;
462
+ outputVariable?: string;
463
+ /** Error handling configuration - supports simple mode or fallback chains */
464
+ errorHandling?: ErrorHandlingMode | ContextErrorHandling;
465
+ streamOutput?: boolean;
466
+ enabled?: boolean;
467
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
468
+ when?: string;
542
469
  }
543
- interface RuntimeCustomToolConfig {
544
- code: string;
545
- language?: 'javascript' | 'typescript' | 'python';
546
- sandboxProvider?: 'quickjs' | 'daytona' | 'cloudflare-worker';
547
- timeout?: number;
470
+ interface SendTextStepConfig$1 {
471
+ name: string;
472
+ to: string;
473
+ from?: string;
474
+ message: string;
475
+ outputVariable?: string;
476
+ /** Error handling configuration - supports simple mode or fallback chains */
477
+ errorHandling?: ErrorHandlingMode | ContextErrorHandling;
478
+ streamOutput?: boolean;
479
+ enabled?: boolean;
480
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
481
+ when?: string;
548
482
  }
549
- interface RuntimeExternalToolConfig {
550
- url: string;
551
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
552
- headers?: Record<string, string>;
553
- body?: string;
483
+ interface FetchGitHubStepConfig$1 {
484
+ name: string;
485
+ repository: string;
486
+ branch?: string;
487
+ path?: string;
488
+ outputVariable?: string;
489
+ streamOutput?: boolean;
490
+ enabled?: boolean;
491
+ /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
492
+ when?: string;
554
493
  }
555
- type RuntimeSubagentToolConfig = SubagentToolConfig;
556
- interface AgentSubagentConfig {
557
- toolPool: string[];
558
- defaultMaxTurns?: number;
559
- maxTurnsLimit?: number;
560
- maxSpawnsPerRun?: number;
561
- defaultModel?: string;
562
- allowNesting?: boolean;
563
- defaultTimeoutMs?: number;
494
+ interface FlowConfig$1 {
495
+ name: string;
496
+ description?: string;
564
497
  }
565
- interface CustomMCPServerAuth {
566
- type: 'bearer' | 'api_key' | 'basic' | 'custom_header' | 'oauth2' | 'none';
567
- headerName?: string;
568
- token?: string;
569
- username?: string;
570
- password?: string;
571
- oauth2?: {
572
- accessToken?: string;
573
- refreshToken?: string;
574
- tokenEndpoint?: string;
575
- clientId?: string;
576
- clientSecret?: string;
577
- expiresAt?: number;
578
- scope?: string;
579
- issuer?: string;
580
- };
498
+ /**
499
+ * Configuration for upsert flow - includes flow name and upsert behavior options
500
+ */
501
+ interface UpsertFlowConfig$1 extends FlowConfig$1 {
502
+ /** Whether to create a version snapshot before updating (default: true) */
503
+ createVersionOnChange?: boolean;
504
+ /** Allow overwriting changes made via dashboard/API (default: false) */
505
+ allowOverwriteExternalChanges?: boolean;
581
506
  }
582
- interface CustomMCPServer {
583
- id: string;
507
+ interface RecordConfig$1 {
508
+ id?: number | string;
584
509
  name?: string;
585
- url: string;
586
- auth?: CustomMCPServerAuth;
587
- allowedTools?: string[];
588
- timeout?: number;
589
- transport?: 'streamable_http' | 'rest';
590
- enabled?: boolean;
591
- }
592
- interface ToolsConfig {
593
- toolIds?: string[];
594
- runtimeTools?: RuntimeTool[];
595
- subagentConfig?: AgentSubagentConfig;
596
- mcpServers?: CustomMCPServer[];
597
- maxToolCalls?: number;
598
- toolCallStrategy?: 'auto' | 'required' | 'none';
599
- parallelCalls?: boolean;
600
- toolConfigs?: Record<string, JsonObject>;
601
- }
602
- interface ReasoningConfig {
603
- enabled: boolean;
604
- reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
605
- reasoningSummary?: 'auto' | 'detailed';
606
- budgetTokens?: number;
607
- thinkingBudget?: number;
608
- includeThoughts?: boolean;
510
+ type?: string;
511
+ metadata?: Record<string, any>;
609
512
  }
610
- type ReasoningValue = boolean | ReasoningConfig;
611
-
612
513
  /**
613
- * Error Handling Types
614
- *
615
- * Provides consistent error handling configuration across all step types
616
- * with support for retry, model fallback, step fallback, and flow fallback.
617
- *
618
- * Note: These types are inlined from the internal shared package to avoid
619
- * requiring users to install @runtypelabs/shared.
620
- */
621
- type ErrorHandlingMode = 'fail' | 'continue' | 'fallback';
622
- /**
623
- * Base fallback configuration
514
+ * Options for upsert mode - controls conflict detection and versioning
624
515
  */
625
- interface BaseFallback {
626
- delay?: number;
516
+ interface UpsertOptions$1 {
517
+ /** Whether to create a version snapshot before updating (default: true) */
518
+ createVersionOnChange?: boolean;
519
+ /** Allow overwriting changes made via dashboard/API (default: false) */
520
+ allowOverwriteExternalChanges?: boolean;
627
521
  }
628
- /**
629
- * Retry fallback - retry the same step with same config
630
- */
631
- interface RetryFallback extends BaseFallback {
632
- type: 'retry';
522
+ interface DispatchOptions$1 {
523
+ streamResponse?: boolean;
524
+ modelOverride?: string;
525
+ recordMode?: 'existing' | 'create' | 'virtual';
526
+ flowMode?: 'existing' | 'create' | 'virtual' | 'upsert';
527
+ storeResults?: boolean;
528
+ autoAppendMetadata?: boolean;
529
+ debugMode?: boolean;
530
+ createVersion?: boolean;
531
+ versionType?: 'published' | 'draft' | 'test' | 'virtual';
532
+ versionLabel?: string;
533
+ versionNotes?: string;
534
+ flowVersionId?: string;
535
+ /** Options for upsert mode (only used when flowMode is 'upsert') */
536
+ upsertOptions?: UpsertOptions$1;
537
+ flowTimeoutMs?: number;
538
+ stepTimeoutMs?: number;
633
539
  }
634
- /**
635
- * Model fallback for prompts - retry with different model/settings
636
- */
637
- interface ModelFallback extends BaseFallback {
638
- type: 'model';
639
- model: string;
640
- temperature?: number;
641
- maxTokens?: number;
642
- topP?: number;
643
- topK?: number;
644
- frequencyPenalty?: number;
645
- presencePenalty?: number;
646
- seed?: number;
540
+ interface Message$1 {
541
+ role: 'system' | 'user' | 'assistant';
542
+ content: MessageContent;
647
543
  }
648
- /**
649
- * Step fallback for context steps - run a different step type
650
- */
651
- interface StepFallback extends BaseFallback {
652
- type: 'step';
544
+ interface FlowPausedEvent {
545
+ type: 'flow_await';
546
+ executionId: string;
547
+ flowId: string;
548
+ toolId: string;
549
+ toolName: string;
550
+ awaitedAt: string;
551
+ }
552
+ interface StepWaitingLocalEvent {
553
+ type: 'step_await';
554
+ id: string;
555
+ name: string;
556
+ index: number;
653
557
  stepType: string;
654
- stepConfig: Record<string, unknown>;
558
+ toolId: string;
559
+ toolName: string;
560
+ executionId: string;
561
+ parameters: any;
655
562
  }
656
563
  /**
657
- * Flow fallback - call another flow
564
+ * Emitted when a fallback chain starts execution
658
565
  */
659
- interface FlowFallback extends BaseFallback {
660
- type: 'flow';
661
- flowId: string;
662
- inputs?: Record<string, unknown>;
566
+ interface FallbacksInitiatedEvent {
567
+ type: 'fallbacks_initiated';
568
+ id: string;
569
+ totalFallbacks: number;
570
+ originalError: string;
571
+ timestamp: string;
663
572
  }
664
573
  /**
665
- * Union of all prompt fallback types
574
+ * Emitted when a fallback attempt starts
666
575
  */
667
- type PromptFallback = RetryFallback | ModelFallback;
576
+ interface FallbackStartEvent {
577
+ type: 'fallback_start';
578
+ id: string;
579
+ attempt: number;
580
+ fallbackType: string;
581
+ timestamp: string;
582
+ }
668
583
  /**
669
- * Union of all context step fallback types
584
+ * Emitted when a fallback attempt succeeds
670
585
  */
671
- type ContextFallback = RetryFallback | StepFallback | FlowFallback;
586
+ interface FallbackSuccessEvent {
587
+ type: 'fallback_success';
588
+ id: string;
589
+ attempt: number;
590
+ fallbackType: string;
591
+ timestamp: string;
592
+ }
672
593
  /**
673
- * Error handling configuration for prompts
594
+ * Emitted when a fallback attempt fails
674
595
  */
675
- interface PromptErrorHandling {
676
- onError: ErrorHandlingMode;
677
- fallbacks?: PromptFallback[];
596
+ interface FallbackFailEvent {
597
+ type: 'fallback_fail';
598
+ id: string;
599
+ attempt: number;
600
+ fallbackType: string;
601
+ error: string;
602
+ timestamp: string;
678
603
  }
679
604
  /**
680
- * Error handling configuration for context steps
605
+ * Emitted when all fallbacks in the chain have been exhausted
681
606
  */
682
- interface ContextErrorHandling {
683
- onError: ErrorHandlingMode;
684
- fallbacks?: ContextFallback[];
607
+ interface FallbacksExhaustedEvent {
608
+ type: 'fallbacks_exhausted';
609
+ id: string;
610
+ totalAttempts: number;
611
+ finalError: string;
612
+ timestamp: string;
613
+ }
614
+ interface FlowStartEvent {
615
+ type: 'flow_start';
616
+ flowId: string;
617
+ flowName: string;
618
+ totalSteps: number;
619
+ }
620
+ interface StepStartEvent {
621
+ type: 'step_start';
622
+ id: string;
623
+ name: string;
624
+ index: number;
625
+ stepType: string;
626
+ }
627
+ interface StepDeltaEvent {
628
+ type: 'step_delta';
629
+ id: string;
630
+ index: number;
631
+ /** Streaming text fragment. */
632
+ text: string;
633
+ }
634
+ interface StepCompleteEvent {
635
+ type: 'step_complete';
636
+ id: string;
637
+ name: string;
638
+ index: number;
639
+ stepType: string;
640
+ /** Step result - used by all step types */
641
+ result?: any;
642
+ executionTime: number;
643
+ }
644
+ interface FlowCompleteEvent {
645
+ type: 'flow_complete';
646
+ flowId: string;
647
+ totalSteps: number;
648
+ successfulSteps: number;
649
+ failedSteps: number;
650
+ executionTime: number;
651
+ }
652
+ interface FlowErrorEvent {
653
+ type: 'flow_error';
654
+ error: string;
655
+ stepId?: string;
685
656
  }
686
-
687
657
  /**
688
- * FlowResult - Wrapper for streaming flow execution responses
689
- *
690
- * Provides convenient methods for processing streaming responses
691
- * from the Runtype API dispatch endpoint.
658
+ * Union type of all possible SSE events
692
659
  */
693
-
660
+ type StreamEvent = FlowStartEvent | StepStartEvent | StepDeltaEvent | StepCompleteEvent | FlowCompleteEvent | FlowErrorEvent | FlowPausedEvent | StepWaitingLocalEvent | FallbacksInitiatedEvent | FallbackStartEvent | FallbackSuccessEvent | FallbackFailEvent | FallbacksExhaustedEvent;
694
661
  /**
695
- * Result wrapper for flow execution
696
- *
697
- * Provides multiple ways to consume the streaming response:
698
- * - `.stream(callbacks)` - Process with callbacks
699
- * - `.getResult(stepName)` - Get result from a specific step
700
- * - `.getAllResults()` - Get all step results
701
- * - `.raw` - Access the raw Response for manual handling
662
+ * Callbacks for streaming flow execution
702
663
  *
703
664
  * @example
704
665
  * ```typescript
705
- * const result = await flow.run(apiClient, options)
706
- *
707
- * // Option 1: Process with callbacks
708
- * const summary = await result.stream({
709
- * onStepDelta: (text) => process.stdout.write(text),
666
+ * await flow.run(apiClient, options, {
667
+ * onStepStart: (event) => console.log('Starting:', event.name),
668
+ * onStepDelta: (chunk, event) => process.stdout.write(chunk),
669
+ * onStepComplete: (result, event) => console.log('Done:', event.name),
670
+ * onFlowComplete: (event) => console.log('Flow complete'),
671
+ * onError: (error) => console.error(error),
710
672
  * })
711
- *
712
- * // Option 2: Just get a specific step's result
713
- * const analysis = await result.getResult('Analyze Data')
714
- *
715
- * // Option 3: Get all results
716
- * const allResults = await result.getAllResults()
717
673
  * ```
718
674
  */
719
- declare class FlowResult {
720
- private response;
721
- private consumed;
722
- private cachedSummary;
723
- constructor(response: Response, summary?: FlowSummary);
675
+ interface StreamCallbacks {
676
+ /** Called when flow execution starts */
677
+ onFlowStart?: (event: FlowStartEvent) => void;
678
+ /** Called when a step starts executing */
679
+ onStepStart?: (event: StepStartEvent) => void;
680
+ /** Called for each text fragment of streaming output from a step */
681
+ onStepDelta?: (text: string, event: StepDeltaEvent) => void;
682
+ /** Called when a step completes */
683
+ onStepComplete?: (result: any, event: StepCompleteEvent) => void;
684
+ /** Called when the entire flow completes */
685
+ onFlowComplete?: (event: FlowCompleteEvent) => void;
686
+ /** Called when an error occurs */
687
+ onError?: (error: Error) => void;
688
+ }
689
+ /**
690
+ * Summary returned after flow execution completes
691
+ */
692
+ interface FlowSummary {
693
+ flowId: string;
694
+ flowName: string;
695
+ totalSteps: number;
696
+ successfulSteps: number;
697
+ failedSteps: number;
698
+ executionTime: number;
699
+ /** Results from each step, keyed by step name */
700
+ results: Map<string, any>;
701
+ /** Whether the flow completed successfully */
702
+ success: boolean;
703
+ }
704
+ declare class FlowBuilder {
705
+ private flowConfig;
706
+ private steps;
707
+ private recordConfig;
708
+ private messagesConfig;
709
+ private inputsConfig;
710
+ private optionsConfig;
711
+ private stepCounter;
712
+ private existingFlowId;
724
713
  /**
725
- * Get the raw Response object for manual handling
726
- *
727
- * Note: The response body can only be consumed once.
728
- * Using this will prevent using other methods like stream() or getResult().
729
- */
730
- get raw(): Response;
731
- /**
732
- * Check if the response has already been consumed
714
+ * Initialize the flow with a name and optional description.
715
+ * Use this for virtual/one-off flows or when specifying flowMode in run().
733
716
  */
734
- get isConsumed(): boolean;
717
+ createFlow(config: FlowConfig$1): this;
735
718
  /**
736
- * Process the streaming response with callbacks
737
- *
738
- * @param callbacks - Callbacks for different event types
739
- * @returns Promise resolving to FlowSummary when complete
719
+ * Define a flow for upsert - creates if it doesn't exist, updates if steps changed.
720
+ * This is the recommended pattern for code-first flow management.
740
721
  *
741
722
  * @example
742
723
  * ```typescript
743
- * const summary = await result.stream({
744
- * onStepStart: (event) => console.log('Starting:', event.name),
745
- * onStepDelta: (text) => process.stdout.write(text),
746
- * onStepComplete: (result, event) => console.log('Done:', event.name),
747
- * onFlowComplete: (event) => console.log('Flow complete!'),
748
- * })
724
+ * const result = await new FlowBuilder()
725
+ * .upsertFlow({
726
+ * name: 'My Flow',
727
+ * createVersionOnChange: true
728
+ * })
729
+ * .prompt({ name: 'Analyze', model: 'gpt-4o', userPrompt: '...' })
730
+ * .run(apiClient, { streamResponse: true })
749
731
  * ```
750
732
  */
751
- stream(callbacks?: StreamCallbacks): Promise<FlowSummary>;
733
+ upsertFlow(config: UpsertFlowConfig$1): this;
752
734
  /**
753
- * Get the result from a specific step by its name
754
- *
755
- * Matches against the `name` property you set when creating the step.
756
- * - **Case-sensitive**: `'Analyze'` ≠ `'analyze'`
757
- * - **Exact match only**: no partial or fuzzy matching
758
- * - Returns `undefined` if no step with that name is found
759
- *
760
- * @param stepName - The exact step name (from the `name` property when creating the step)
761
- * @returns The step's result, or undefined if not found
735
+ * Use an existing flow by ID instead of defining steps inline
762
736
  *
763
737
  * @example
764
738
  * ```typescript
765
- * // When building:
766
- * .prompt({ name: 'Analyze Screenshot', model: 'gpt-4', ... })
767
- *
768
- * // When retrieving (must match exactly):
769
- * const analysis = await result.getResult('Analyze Screenshot') // ✓ Works
770
- * const analysis = await result.getResult('analyze screenshot') // ✗ undefined
739
+ * const result = await new FlowBuilder()
740
+ * .useExistingFlow('flow_abc123')
741
+ * .withRecord({ name: 'Test', type: 'data' })
742
+ * .run(apiClient, { streamResponse: true })
771
743
  * ```
772
744
  */
773
- getResult(stepName: string): Promise<any>;
745
+ useExistingFlow(flowId: string): this;
774
746
  /**
775
- * Get all step results as a Map
776
- *
777
- * @returns Map of step name to result
747
+ * Set the record configuration
748
+ */
749
+ withRecord(config: RecordConfig$1): this;
750
+ /**
751
+ * Set conversation messages
752
+ */
753
+ withMessages(messages: Message$1[]): this;
754
+ /**
755
+ * Set top-level input variables accessible as {{varName}} in templates
778
756
  *
779
757
  * @example
780
758
  * ```typescript
781
- * const allResults = await result.getAllResults()
782
- * for (const [stepName, result] of allResults) {
783
- * console.log(stepName, result)
784
- * }
759
+ * const result = await new FlowBuilder()
760
+ * .useExistingFlow('flow_abc123')
761
+ * .withInputs({
762
+ * customerName: 'John',
763
+ * topic: 'billing'
764
+ * })
765
+ * .run(apiClient, { streamResponse: true })
785
766
  * ```
786
767
  */
787
- getAllResults(): Promise<Map<string, any>>;
768
+ withInputs(inputs: Record<string, unknown>): this;
788
769
  /**
789
- * Get the flow summary after processing
790
- *
791
- * @returns FlowSummary with execution details
770
+ * Set dispatch options
792
771
  */
793
- getSummary(): Promise<FlowSummary>;
772
+ withOptions(options: DispatchOptions$1): this;
794
773
  /**
795
- * Ensure the stream has been processed and return the summary
774
+ * Add a prompt step
796
775
  */
797
- private ensureSummary;
776
+ prompt(config: PromptStepConfig$1): this;
798
777
  /**
799
- * Ensure the response hasn't been consumed yet
778
+ * Add a crawl step
800
779
  */
801
- private ensureNotConsumed;
802
- }
803
-
804
- /**
805
- * FlowBuilder - Fluent builder for constructing dispatch configurations
806
- *
807
- * Provides a chainable API for building flows with steps, making flow
808
- * construction more readable and type-safe.
809
- *
810
- * @example
811
- * ```typescript
812
- * import { FlowBuilder } from '@runtypelabs/sdk'
813
- *
814
- * const config = new FlowBuilder()
815
- * .createFlow({ name: "My Flow" })
816
- * .withRecord({ name: "Record", type: "data", metadata: { key: "value" } })
817
- * .fetchUrl({ name: "Fetch", url: "https://api.example.com", outputVariable: "data" })
818
- * .prompt({ name: "Process", model: "gpt-4", userPrompt: "Analyze: {{data}}" })
819
- * .withOptions({ streamResponse: true, flowMode: "virtual" })
820
- * .build()
821
- * ```
822
- */
823
-
824
- interface PromptStepConfig$1 {
825
- name: string;
826
- model: string;
827
- userPrompt: string;
828
- systemPrompt?: string;
829
- previousMessages?: string | Array<{
830
- role: string;
831
- content: string;
832
- }>;
833
- outputVariable?: string;
834
- responseFormat?: 'text' | 'json';
835
- temperature?: number;
836
- topP?: number;
837
- topK?: number;
838
- frequencyPenalty?: number;
839
- presencePenalty?: number;
840
- seed?: number;
841
- maxTokens?: number;
780
+ crawl(config: CrawlStepConfig): this;
842
781
  /**
843
- * Enable reasoning/extended thinking for models that support it.
844
- * - `true`: Enable with provider defaults
845
- * - `ReasoningConfig`: Fine-grained control over reasoning behavior
782
+ * Add a fetch URL step
783
+ */
784
+ fetchUrl(config: FetchUrlStepConfig$1): this;
785
+ /**
786
+ * Add a transform data step
787
+ */
788
+ transformData(config: TransformDataStepConfig$1): this;
789
+ /**
790
+ * Add a set variable step
791
+ */
792
+ setVariable(config: SetVariableStepConfig$1): this;
793
+ /**
794
+ * Add a conditional step
795
+ */
796
+ conditional(config: ConditionalStepConfig$1): this;
797
+ /**
798
+ * Add a search step
799
+ */
800
+ search(config: SearchStepConfig$1): this;
801
+ /**
802
+ * Add a send email step
803
+ */
804
+ sendEmail(config: SendEmailStepConfig$1): this;
805
+ /**
806
+ * Add a send stream step
807
+ */
808
+ sendStream(config: SendStreamStepConfig$1): this;
809
+ /**
810
+ * Add a retrieve record step
811
+ */
812
+ retrieveRecord(config: RetrieveRecordStepConfig$1): this;
813
+ /**
814
+ * Add an upsert record step
815
+ */
816
+ upsertRecord(config: UpsertRecordStepConfig$1): this;
817
+ /**
818
+ * Add a vector search step
819
+ */
820
+ vectorSearch(config: VectorSearchStepConfig$1): this;
821
+ /**
822
+ * Add a generate embedding step
823
+ */
824
+ generateEmbedding(config: GenerateEmbeddingStepConfig$1): this;
825
+ /**
826
+ * Add a wait until step
827
+ */
828
+ waitUntil(config: WaitUntilStepConfig$1): this;
829
+ /**
830
+ * Add a send event step
831
+ */
832
+ sendEvent(config: SendEventStepConfig$1): this;
833
+ /**
834
+ * Add a send text step
835
+ */
836
+ sendText(config: SendTextStepConfig$1): this;
837
+ /**
838
+ * Add a fetch GitHub step
839
+ */
840
+ fetchGitHub(config: FetchGitHubStepConfig$1): this;
841
+ /**
842
+ * Attach a subagent runtime tool to the most recent prompt step.
846
843
  *
847
- * @example GPT-5 with streaming reasoning
844
+ * A subagent tool spawns a focused child agent in its own context window
845
+ * when the parent's model calls it. The child runs with a whitelisted tool
846
+ * subset drawn from `allowedTools` (every entry must be available on the
847
+ * parent step). The parent only sees the child's final result.
848
+ *
849
+ * Pass either `agentId` (for a saved agent in the same org) or `agent`
850
+ * (an inline exported-agent JSON shape) — exactly one is required.
851
+ *
852
+ * @example
848
853
  * ```typescript
849
- * reasoning: { enabled: true, reasoningSummary: 'auto' }
854
+ * new FlowBuilder()
855
+ * .createFlow({ name: 'Research' })
856
+ * .prompt({ name: 'Plan', model: 'claude-sonnet-4-5', userPrompt: '...' })
857
+ * .withSubagentTool('research_topic', {
858
+ * agentId: 'agent_01h...',
859
+ * allowedTools: ['builtin:exa_search'],
860
+ * outputFormat: 'text',
861
+ * })
850
862
  * ```
851
863
  */
852
- reasoning?: boolean | ReasoningConfig;
853
- streamOutput?: boolean;
854
- /** Tools configuration - supports saved tools (toolIds) and inline runtime tools */
855
- tools?: ToolsConfig;
856
- /** Error handling configuration - supports simple mode or fallback chains */
857
- errorHandling?: ErrorHandlingMode | PromptErrorHandling;
858
- enabled?: boolean;
859
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
860
- when?: string;
861
- }
862
- interface FetchUrlStepConfig$1 {
863
- name: string;
864
- url: string;
865
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
866
- headers?: Record<string, string>;
867
- body?: string;
868
- responseType?: 'json' | 'text' | 'xml';
869
- markdownIfAvailable?: boolean;
870
- outputVariable?: string;
871
- fetchMethod?: 'http' | 'firecrawl';
872
- firecrawl?: {
873
- formats?: string[];
874
- [key: string]: any;
875
- };
876
- /** Error handling configuration - supports simple mode or fallback chains */
877
- errorHandling?: ErrorHandlingMode | ContextErrorHandling;
878
- streamOutput?: boolean;
879
- enabled?: boolean;
880
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
881
- when?: string;
882
- }
883
- interface CrawlStepConfig {
884
- name: string;
885
- url: string;
886
- limit?: number;
887
- depth?: number;
888
- source?: string;
889
- formats?: string[];
890
- render?: boolean;
891
- maxAge?: number;
892
- modifiedSince?: string;
893
- options?: Record<string, unknown>;
894
- authenticate?: Record<string, unknown>;
895
- cookies?: Array<Record<string, unknown>>;
896
- setExtraHTTPHeaders?: Record<string, string>;
897
- gotoOptions?: Record<string, unknown>;
898
- waitForSelector?: string;
899
- rejectResourceTypes?: string[];
900
- rejectRequestPattern?: string | string[];
901
- userAgent?: string;
902
- jsonOptions?: Record<string, unknown>;
903
- outputVariable?: string;
904
- streamOutput?: boolean;
905
- errorHandling?: ErrorHandlingMode | ContextErrorHandling;
906
- pollIntervalMs?: number;
907
- completionTimeoutMs?: number;
908
- enabled?: boolean;
909
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
910
- when?: string;
911
- }
912
- interface TransformDataStepConfig$1 {
913
- name: string;
914
- script: string;
915
- outputVariable?: string;
916
- sandboxProvider?: 'quickjs' | 'daytona' | 'cloudflare-worker';
917
- streamOutput?: boolean;
918
- enabled?: boolean;
919
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
920
- when?: string;
921
- }
922
- interface SetVariableStepConfig$1 {
923
- name: string;
924
- variableName: string;
925
- value: string | number | boolean | object;
926
- enabled?: boolean;
927
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
928
- when?: string;
929
- }
930
- interface ConditionalStepConfig$1 {
931
- name: string;
932
- condition: string;
933
- trueSteps?: any[];
934
- falseSteps?: any[];
935
- enabled?: boolean;
936
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
937
- when?: string;
938
- }
939
- interface SearchStepConfig$1 {
940
- name: string;
941
- provider: string;
942
- query: string;
943
- maxResults?: number;
944
- outputVariable?: string;
945
- returnCitations?: boolean;
946
- /** Error handling configuration - supports simple mode or fallback chains */
947
- errorHandling?: ErrorHandlingMode | ContextErrorHandling;
948
- streamOutput?: boolean;
949
- enabled?: boolean;
950
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
951
- when?: string;
952
- }
953
- interface SendEmailStepConfig$1 {
954
- name: string;
955
- to: string;
956
- from?: string;
957
- subject: string;
958
- html: string;
959
- outputVariable?: string;
960
- /** Error handling configuration - supports simple mode or fallback chains */
961
- errorHandling?: ErrorHandlingMode | ContextErrorHandling;
962
- streamOutput?: boolean;
963
- enabled?: boolean;
964
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
965
- when?: string;
966
- }
967
- interface SendStreamStepConfig$1 {
968
- name: string;
969
- message: string;
970
- enabled?: boolean;
971
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
972
- when?: string;
864
+ withSubagentTool(name: string, opts: {
865
+ description?: string;
866
+ agentId?: string;
867
+ agent?: JsonObject;
868
+ allowedTools: string[];
869
+ parametersSchema?: JSONSchema;
870
+ maxTurns?: number;
871
+ maxCost?: number;
872
+ timeoutMs?: number;
873
+ outputFormat?: 'text' | 'json' | 'last_message';
874
+ inheritMessages?: boolean;
875
+ taskTemplate?: string;
876
+ }): this;
877
+ /**
878
+ * Enable agent-driven dynamic subagent spawning on the most recent prompt
879
+ * step (surface C of the subagent design).
880
+ *
881
+ * When set, the API synthesizes a `spawn_subagent` tool the parent's model
882
+ * can call at runtime to spin off a focused child agent. The child's tools
883
+ * are drawn from `toolPool`, which must be a subset of the parent step's
884
+ * resolved tools. The API validates pool entries and rejects escalation.
885
+ *
886
+ * @example
887
+ * ```typescript
888
+ * new FlowBuilder()
889
+ * .createFlow({ name: 'Explore' })
890
+ * .prompt({ name: 'Research', model: 'claude-sonnet-4-5', userPrompt: '...' })
891
+ * .withSubagents({
892
+ * toolPool: ['builtin:exa_search', 'mcp:*'],
893
+ * maxSpawnsPerRun: 3,
894
+ * allowNesting: false,
895
+ * })
896
+ * ```
897
+ */
898
+ withSubagents(opts: AgentSubagentConfig): this;
899
+ /**
900
+ * Build the final dispatch request configuration
901
+ */
902
+ build(): DispatchRequest;
903
+ /**
904
+ * Build and execute the flow with the provided client
905
+ *
906
+ * Returns a FlowResult that can be used to:
907
+ * - Process with callbacks via `.stream(callbacks)`
908
+ * - Get a specific step result via `.getResult(stepName)`
909
+ * - Get all results via `.getAllResults()`
910
+ * - Access raw response via `.raw`
911
+ *
912
+ * @param client - Client with dispatch capability
913
+ * @param options - Optional execution options (merged with any .withOptions() settings)
914
+ * @returns FlowResult for processing the streaming response
915
+ *
916
+ * @example
917
+ * ```typescript
918
+ * // Simple execution with result extraction
919
+ * const result = await flow.run(apiClient, { streamResponse: true })
920
+ * const analysis = await result.getResult('Analyze Data')
921
+ *
922
+ * // With streaming callbacks
923
+ * const result = await flow.run(apiClient, options)
924
+ * await result.stream({
925
+ * onStepDelta: (chunk) => process.stdout.write(chunk),
926
+ * onFlowComplete: () => console.log('Done!'),
927
+ * })
928
+ * ```
929
+ */
930
+ run(client: DispatchClient, options?: DispatchOptions$1): Promise<FlowResult>;
931
+ /**
932
+ * Build and execute the flow with callbacks for streaming events
933
+ *
934
+ * @param client - Client with dispatch capability
935
+ * @param options - Execution options (merged with any .withOptions() settings)
936
+ * @param callbacks - Callbacks for streaming events
937
+ * @returns FlowSummary when execution completes
938
+ *
939
+ * @example
940
+ * ```typescript
941
+ * const summary = await flow.run(apiClient, options, {
942
+ * onStepStart: (event) => console.log('Starting:', event.name),
943
+ * onStepDelta: (chunk) => process.stdout.write(chunk),
944
+ * onStepComplete: (result, event) => console.log('Done:', event.name),
945
+ * onFlowComplete: (event) => console.log('Flow complete!'),
946
+ * })
947
+ * ```
948
+ */
949
+ run(client: DispatchClient, options: DispatchOptions$1, callbacks: StreamCallbacks): Promise<FlowSummary>;
950
+ /**
951
+ * Set a run condition (when predicate) on the last added step.
952
+ * If the expression evaluates to falsy at runtime, the step is skipped.
953
+ *
954
+ * @example
955
+ * ```typescript
956
+ * new FlowBuilder()
957
+ * .createFlow({ name: 'Conditional' })
958
+ * .prompt({ name: 'Summarize', model: 'gpt-4', userPrompt: '...' })
959
+ * .when('data.length > 0')
960
+ * .build()
961
+ * ```
962
+ */
963
+ when(expression: string): this;
964
+ private addStep;
973
965
  }
974
966
  /**
975
- * Operator allowlist for chip-style record filters. Mirrors the API's
976
- * `record-filter-compiler.ts`. Kept inline here to avoid a hard dependency
977
- * on `@runtypelabs/shared` from the published SDK.
967
+ * Interface for clients that can dispatch flows
978
968
  */
979
- type RecordFilterOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'between' | 'contains' | 'startsWith' | 'endsWith' | 'in' | 'notIn' | 'isSet' | 'isNotSet' | 'isTrue' | 'isFalse' | 'withinLastDays' | 'olderThanDays';
980
- interface RecordFilterCondition {
981
- field: string;
982
- op: RecordFilterOperator;
983
- value?: unknown;
984
- }
985
- interface RecordFilterGroup {
986
- op: 'and' | 'or';
987
- conditions: Array<RecordFilterCondition | RecordFilterGroup>;
988
- }
989
- interface RecordFilter {
990
- type: string;
991
- where?: RecordFilterCondition | RecordFilterGroup;
992
- }
993
- interface RetrieveRecordStepConfig$1 {
994
- name: string;
995
- recordType?: string;
996
- recordName?: string;
969
+ interface DispatchClient {
997
970
  /**
998
- * Optional chip-style filter (metadata + top-level columns: id, name,
999
- * createdAt, updatedAt). Coexists with recordType/recordName for
1000
- * backward compatibility; the API executor prefers recordFilter when
1001
- * both are set.
971
+ * Run a flow with local tools (automatic pause/resume loop)
972
+ *
973
+ * @param config - The dispatch request configuration
974
+ * @param localTools - Map of tool names to async functions that execute the tool logic
975
+ * @param callbacks - Optional callbacks for streaming events
976
+ * @returns The final result of the flow execution or summary if streaming
1002
977
  */
1003
- recordFilter?: RecordFilter;
1004
- fieldsToInclude?: string[];
1005
- fieldsToExclude?: string[];
1006
- outputVariable?: string;
1007
- streamOutput?: boolean;
1008
- enabled?: boolean;
1009
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
1010
- when?: string;
1011
- }
1012
- interface UpsertRecordStepConfig$1 {
1013
- name: string;
1014
- recordType: string;
1015
- recordName?: string;
1016
- sourceVariable?: string;
1017
- mergeStrategy?: 'merge' | 'replace';
1018
- outputVariable?: string;
1019
- /** Error handling configuration - supports simple mode or fallback chains */
1020
- errorHandling?: ErrorHandlingMode | ContextErrorHandling;
1021
- streamOutput?: boolean;
1022
- enabled?: boolean;
1023
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
1024
- when?: string;
1025
- }
1026
- interface VectorSearchStepConfig$1 {
1027
- name: string;
1028
- query: string;
1029
- recordType?: string;
1030
- embeddingModel?: string;
1031
- limit?: number;
1032
- threshold?: number;
1033
- outputVariable?: string;
1034
- streamOutput?: boolean;
1035
- enabled?: boolean;
1036
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
1037
- when?: string;
978
+ runWithLocalTools(config: DispatchRequest, localTools: Record<string, (args: any) => Promise<any>>, callbacks?: StreamCallbacks): Promise<FlowResult | FlowSummary>;
979
+ dispatch(config: DispatchRequest): Promise<Response>;
1038
980
  }
1039
- interface GenerateEmbeddingStepConfig$1 {
1040
- name: string;
1041
- text: string;
1042
- embeddingModel?: string;
1043
- maxLength?: number;
1044
- outputVariable?: string;
1045
- streamOutput?: boolean;
1046
- enabled?: boolean;
1047
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
1048
- when?: string;
981
+ /**
982
+ * FlowBuilder that is bound to a client for direct execution
983
+ *
984
+ * @example
985
+ * ```typescript
986
+ * // Via RuntypeClient.flow()
987
+ * const result = await runtype
988
+ * .flow('My Flow')
989
+ * .fetchUrl({ name: 'Fetch', url: '...', outputVariable: 'data' })
990
+ * .prompt({ name: 'Process', model: 'gpt-4', userPrompt: '...' })
991
+ * .run({ streamResponse: true })
992
+ *
993
+ * const data = await result.getResult('Process')
994
+ * ```
995
+ */
996
+ declare class ClientFlowBuilder extends FlowBuilder {
997
+ private boundClient;
998
+ constructor(client: DispatchClient, name: string);
999
+ /**
1000
+ * Build and execute the flow using the bound client
1001
+ *
1002
+ * For ClientFlowBuilder, you can either:
1003
+ * 1. Pass a client (which is ignored, the bound client is used)
1004
+ * 2. Pass options directly as the first argument
1005
+ *
1006
+ * @example
1007
+ * ```typescript
1008
+ * // Simple execution (no args needed)
1009
+ * const result = await builder.run()
1010
+ * const data = await result.getResult('Process')
1011
+ *
1012
+ * // With options only
1013
+ * const result = await builder.run({ streamResponse: true, flowMode: 'virtual' })
1014
+ *
1015
+ * // With options and callbacks
1016
+ * const summary = await builder.run({ streamResponse: true }, {
1017
+ * onStepDelta: (chunk) => process.stdout.write(chunk),
1018
+ * onFlowComplete: () => console.log('Done!'),
1019
+ * })
1020
+ *
1021
+ * // Parent class signature (client ignored)
1022
+ * const result = await builder.run(someClient, { streamResponse: true })
1023
+ * ```
1024
+ */
1025
+ run(): Promise<FlowResult>;
1026
+ run(options: DispatchOptions$1): Promise<FlowResult>;
1027
+ run(options: DispatchOptions$1, callbacks: StreamCallbacks): Promise<FlowSummary>;
1028
+ run(localTools: Record<string, (args: any) => Promise<any>>): Promise<FlowResult>;
1029
+ run(options: DispatchOptions$1, localTools: Record<string, (args: any) => Promise<any>>): Promise<FlowResult>;
1030
+ run(localTools: Record<string, (args: any) => Promise<any>>, callbacks: StreamCallbacks): Promise<FlowSummary>;
1031
+ run(options: DispatchOptions$1, localTools: Record<string, (args: any) => Promise<any>>, callbacks: StreamCallbacks): Promise<FlowSummary>;
1032
+ run(client: DispatchClient, options?: DispatchOptions$1): Promise<FlowResult>;
1033
+ run(client: DispatchClient, options: DispatchOptions$1, callbacks: StreamCallbacks): Promise<FlowSummary>;
1049
1034
  }
1050
- interface WaitUntilStepConfig$1 {
1035
+ /**
1036
+ * Create an external runtime tool definition.
1037
+ *
1038
+ * External tools make HTTP requests to external APIs with support for
1039
+ * variable substitution in URLs and headers.
1040
+ *
1041
+ * Special internal variables are available for auth:
1042
+ * - `{{_internal.auth_token}}` - Bearer token for Runtype API auth
1043
+ * - `{{_internal.user_id}}` - Current user ID
1044
+ * - `{{_internal.org_id}}` - Current organization ID
1045
+ *
1046
+ * @example
1047
+ * ```typescript
1048
+ * const listFlowsTool = createExternalTool({
1049
+ * name: 'list_flows',
1050
+ * description: 'List all flows in the workspace',
1051
+ * parametersSchema: {
1052
+ * type: 'object',
1053
+ * properties: {
1054
+ * limit: { type: 'number', description: 'Max results', default: 20 }
1055
+ * }
1056
+ * },
1057
+ * url: 'https://api.runtype.com/v1/flows',
1058
+ * method: 'GET',
1059
+ * headers: { Authorization: '{{_internal.auth_token}}' }
1060
+ * })
1061
+ * ```
1062
+ */
1063
+ declare function createExternalTool(config: {
1051
1064
  name: string;
1052
- delayMs?: number;
1053
- continueOnTimeout?: boolean;
1054
- poll?: {
1055
- enabled: boolean;
1056
- intervalMs?: number;
1057
- maxAttempts?: number;
1058
- condition?: string;
1065
+ description: string;
1066
+ parametersSchema: any;
1067
+ url: string;
1068
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
1069
+ headers?: Record<string, string>;
1070
+ body?: string;
1071
+ }): RuntimeTool;
1072
+
1073
+ /**
1074
+ * SDK type definitions — self-contained for zero-dependency npm distribution.
1075
+ *
1076
+ * These types mirror the canonical entity definitions in @runtypelabs/shared
1077
+ * (packages/shared/src/types/entities.ts and client-types.ts). When adding or
1078
+ * modifying entity fields, update both locations.
1079
+ */
1080
+ type JsonPrimitive = string | number | boolean | null;
1081
+ type JsonArray = JsonValue[];
1082
+ type JsonObject = {
1083
+ [key: string]: JsonValue;
1084
+ };
1085
+ type JsonValue = JsonPrimitive | JsonObject | JsonArray;
1086
+ type Metadata = JsonObject;
1087
+ interface JSONSchema {
1088
+ type: 'object' | 'string' | 'number' | 'boolean' | 'array' | 'null';
1089
+ properties?: Record<string, JSONSchema>;
1090
+ required?: string[];
1091
+ items?: JSONSchema;
1092
+ description?: string;
1093
+ default?: JsonValue;
1094
+ enum?: JsonPrimitive[];
1095
+ minimum?: number;
1096
+ maximum?: number;
1097
+ minLength?: number;
1098
+ maxLength?: number;
1099
+ pattern?: string;
1100
+ }
1101
+ interface ClientConfig {
1102
+ apiKey?: string;
1103
+ baseUrl?: string;
1104
+ apiVersion?: string;
1105
+ timeout?: number;
1106
+ headers?: Record<string, string>;
1107
+ }
1108
+ interface PaginationResponse<T> {
1109
+ data: T[];
1110
+ pagination: {
1111
+ nextCursor: string | null;
1112
+ prevCursor: string | null;
1113
+ hasMore: boolean;
1114
+ hasPrev: boolean;
1115
+ limit: number;
1116
+ currentOffset: number;
1117
+ totalPages?: number;
1118
+ currentPage?: number;
1119
+ totalCount?: number;
1059
1120
  };
1060
- outputVariable?: string;
1061
- /** Error handling configuration - supports simple mode or fallback chains */
1062
- errorHandling?: ErrorHandlingMode | ContextErrorHandling;
1063
- streamOutput?: boolean;
1064
- enabled?: boolean;
1065
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
1066
- when?: string;
1067
1121
  }
1068
- interface SendEventStepConfig$1 {
1069
- name: string;
1070
- provider: string;
1071
- eventName: string;
1072
- properties?: Record<string, any>;
1073
- outputVariable?: string;
1074
- /** Error handling configuration - supports simple mode or fallback chains */
1075
- errorHandling?: ErrorHandlingMode | ContextErrorHandling;
1076
- streamOutput?: boolean;
1077
- enabled?: boolean;
1078
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
1079
- when?: string;
1122
+ interface ApiResponse<T> {
1123
+ data?: T;
1124
+ success?: boolean;
1125
+ error?: string;
1126
+ message?: string;
1080
1127
  }
1081
- interface SendTextStepConfig$1 {
1128
+ interface FlowStep {
1129
+ id: string;
1130
+ flowId: string;
1131
+ type: string;
1082
1132
  name: string;
1083
- to: string;
1084
- from?: string;
1085
- message: string;
1086
- outputVariable?: string;
1087
- /** Error handling configuration - supports simple mode or fallback chains */
1088
- errorHandling?: ErrorHandlingMode | ContextErrorHandling;
1133
+ order: number;
1134
+ enabled: boolean;
1135
+ config: Record<string, unknown>;
1136
+ outputVariable?: string | null;
1089
1137
  streamOutput?: boolean;
1090
- enabled?: boolean;
1091
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
1092
- when?: string;
1138
+ createdAt: string;
1139
+ updatedAt: string;
1093
1140
  }
1094
- interface FetchGitHubStepConfig$1 {
1141
+ interface Flow {
1142
+ id: string;
1095
1143
  name: string;
1096
- repository: string;
1097
- branch?: string;
1098
- path?: string;
1099
- outputVariable?: string;
1100
- streamOutput?: boolean;
1101
- enabled?: boolean;
1102
- /** JavaScript predicate evaluated at runtime. If falsy, the step is skipped. */
1103
- when?: string;
1144
+ description?: string | null;
1145
+ status: 'draft' | 'active' | 'paused' | 'failed';
1146
+ config?: JsonObject;
1147
+ userId: string;
1148
+ organizationId: string | null;
1149
+ createdAt: string;
1150
+ updatedAt: string;
1151
+ lastRunAt?: string | null;
1152
+ /** Flow steps embedded in the flow response */
1153
+ flowSteps?: FlowStep[];
1154
+ /** Number of steps in the flow */
1155
+ stepCount?: number;
1104
1156
  }
1105
- interface FlowConfig$1 {
1157
+ interface Prompt$1 {
1158
+ id: string;
1106
1159
  name: string;
1107
- description?: string;
1108
- }
1109
- /**
1110
- * Configuration for upsert flow - includes flow name and upsert behavior options
1111
- */
1112
- interface UpsertFlowConfig$1 extends FlowConfig$1 {
1113
- /** Whether to create a version snapshot before updating (default: true) */
1114
- createVersionOnChange?: boolean;
1115
- /** Allow overwriting changes made via dashboard/API (default: false) */
1116
- allowOverwriteExternalChanges?: boolean;
1160
+ text: string;
1161
+ responseFormat: 'default' | 'json' | 'markdown' | 'html' | 'xml';
1162
+ model: string;
1163
+ isStreamed: boolean;
1164
+ tools: string[];
1165
+ inputVariables?: string;
1166
+ estimatedTokens?: number;
1167
+ estimatedCost?: string;
1168
+ userId: string;
1169
+ createdAt: string;
1170
+ updatedAt: string;
1171
+ flows?: FlowAttachment[];
1117
1172
  }
1118
- interface RecordConfig$1 {
1119
- id?: number | string;
1120
- name?: string;
1121
- type?: string;
1122
- metadata?: Record<string, any>;
1173
+ interface FlowAttachment {
1174
+ flowId: string;
1175
+ flowName: string;
1176
+ order: number;
1123
1177
  }
1124
- /**
1125
- * Options for upsert mode - controls conflict detection and versioning
1126
- */
1127
- interface UpsertOptions {
1128
- /** Whether to create a version snapshot before updating (default: true) */
1129
- createVersionOnChange?: boolean;
1130
- /** Allow overwriting changes made via dashboard/API (default: false) */
1131
- allowOverwriteExternalChanges?: boolean;
1132
- }
1133
- interface DispatchOptions$1 {
1134
- streamResponse?: boolean;
1135
- modelOverride?: string;
1136
- recordMode?: 'existing' | 'create' | 'virtual';
1137
- flowMode?: 'existing' | 'create' | 'virtual' | 'upsert';
1138
- storeResults?: boolean;
1139
- autoAppendMetadata?: boolean;
1140
- debugMode?: boolean;
1141
- createVersion?: boolean;
1142
- versionType?: 'published' | 'draft' | 'test' | 'virtual';
1143
- versionLabel?: string;
1144
- versionNotes?: string;
1145
- flowVersionId?: string;
1146
- /** Options for upsert mode (only used when flowMode is 'upsert') */
1147
- upsertOptions?: UpsertOptions;
1148
- flowTimeoutMs?: number;
1149
- stepTimeoutMs?: number;
1150
- }
1151
- interface Message$1 {
1152
- role: 'system' | 'user' | 'assistant';
1153
- content: MessageContent;
1154
- }
1155
- interface FlowPausedEvent {
1156
- type: 'flow_await';
1157
- executionId: string;
1158
- flowId: string;
1159
- toolId: string;
1160
- toolName: string;
1161
- awaitedAt: string;
1162
- }
1163
- interface StepWaitingLocalEvent {
1164
- type: 'step_await';
1178
+ interface RuntypeRecord {
1165
1179
  id: string;
1180
+ type: string;
1166
1181
  name: string;
1167
- index: number;
1168
- stepType: string;
1169
- toolId: string;
1170
- toolName: string;
1171
- executionId: string;
1172
- parameters: any;
1173
- }
1174
- /**
1175
- * Emitted when a fallback chain starts execution
1176
- */
1177
- interface FallbacksInitiatedEvent {
1178
- type: 'fallbacks_initiated';
1179
- id: string;
1180
- totalFallbacks: number;
1181
- originalError: string;
1182
- timestamp: string;
1182
+ metadata: Metadata;
1183
+ metadataLabels?: {
1184
+ [key: string]: string;
1185
+ };
1186
+ metadataSchema?: {
1187
+ keys: string[];
1188
+ keyMapping?: {
1189
+ [key: string]: string;
1190
+ };
1191
+ keyTypes?: {
1192
+ [key: string]: string;
1193
+ };
1194
+ types?: {
1195
+ [key: string]: string;
1196
+ };
1197
+ sizeKb: number;
1198
+ keyCount: number;
1199
+ updatedAt: string;
1200
+ };
1201
+ messages?: Array<{
1202
+ role: 'user' | 'assistant';
1203
+ content: string | unknown[];
1204
+ }> | null;
1205
+ availableFields?: string[];
1206
+ userId: string;
1207
+ organizationId?: string | null;
1208
+ createdAt: string;
1209
+ updatedAt: string;
1183
1210
  }
1184
- /**
1185
- * Emitted when a fallback attempt starts
1186
- */
1187
- interface FallbackStartEvent {
1188
- type: 'fallback_start';
1211
+ interface ApiKey {
1189
1212
  id: string;
1190
- attempt: number;
1191
- fallbackType: string;
1192
- timestamp: string;
1213
+ name: string;
1214
+ keyPrefix: string;
1215
+ searchHint?: string;
1216
+ permissions: string[];
1217
+ isActive: boolean;
1218
+ expiresAt?: string;
1219
+ allowedIps: string[];
1220
+ createdAt: string;
1221
+ updatedAt?: string;
1222
+ lastUsedAt?: string;
1193
1223
  }
1194
- /**
1195
- * Emitted when a fallback attempt succeeds
1196
- */
1197
- interface FallbackSuccessEvent {
1198
- type: 'fallback_success';
1224
+ interface ModelConfig {
1199
1225
  id: string;
1200
- attempt: number;
1201
- fallbackType: string;
1202
- timestamp: string;
1226
+ provider: string;
1227
+ modelId: string;
1228
+ displayName?: string;
1229
+ /** @deprecated Use keyStatus instead */
1230
+ supportsCustomKey: boolean;
1231
+ keyStatus?: 'platform' | 'custom' | 'needs_setup';
1232
+ costPer1kTokens?: number;
1233
+ contextLength?: number;
1234
+ maxOutputTokens?: number;
1235
+ maxTokens?: number;
1236
+ supportsStreaming?: boolean;
1237
+ supportedResponseFormats?: string[];
1238
+ supportsSearch?: boolean;
1239
+ isEnabled: boolean;
1240
+ isDefault: boolean;
1241
+ settings: JsonObject;
1242
+ createdAt: string;
1243
+ updatedAt: string;
1244
+ providerKeyId?: string | null;
1245
+ requiresIntegration?: string;
1246
+ apiKey?: string;
1247
+ scope?: 'personal' | 'organization';
1248
+ organizationId?: string;
1203
1249
  }
1204
- /**
1205
- * Emitted when a fallback attempt fails
1206
- */
1207
- interface FallbackFailEvent {
1208
- type: 'fallback_fail';
1250
+ interface UserProfile {
1209
1251
  id: string;
1210
- attempt: number;
1211
- fallbackType: string;
1212
- error: string;
1213
- timestamp: string;
1252
+ firstName?: string;
1253
+ lastName?: string;
1254
+ email: string;
1255
+ preferences?: {
1256
+ theme?: 'light' | 'dark' | 'system';
1257
+ notifications?: boolean;
1258
+ defaultModel?: string;
1259
+ };
1214
1260
  }
1215
- /**
1216
- * Emitted when all fallbacks in the chain have been exhausted
1217
- */
1218
- interface FallbacksExhaustedEvent {
1219
- type: 'fallbacks_exhausted';
1220
- id: string;
1221
- totalAttempts: number;
1222
- finalError: string;
1223
- timestamp: string;
1261
+ interface CreateFlowRequest {
1262
+ name: string;
1263
+ description?: string;
1264
+ flowSteps?: Array<{
1265
+ type: 'prompt' | 'context' | 'condition' | 'output' | 'email';
1266
+ name: string;
1267
+ order?: number;
1268
+ enabled?: boolean;
1269
+ config: JsonObject;
1270
+ }>;
1224
1271
  }
1225
- interface FlowStartEvent {
1226
- type: 'flow_start';
1227
- flowId: string;
1228
- flowName: string;
1229
- totalSteps: number;
1272
+ interface CreatePromptRequest {
1273
+ flowIds?: string[];
1274
+ name: string;
1275
+ text: string;
1276
+ responseFormat?: 'json' | 'markdown' | 'text' | 'html' | 'xml';
1277
+ model?: string;
1278
+ inputVariables?: string;
1230
1279
  }
1231
- interface StepStartEvent {
1232
- type: 'step_start';
1233
- id: string;
1280
+ interface CreateRecordRequest {
1281
+ type: string;
1234
1282
  name: string;
1235
- index: number;
1236
- stepType: string;
1283
+ metadata?: Metadata;
1237
1284
  }
1238
- interface StepDeltaEvent {
1239
- type: 'step_delta';
1240
- id: string;
1241
- index: number;
1242
- /** Streaming text fragment. */
1243
- text: string;
1285
+ interface BulkEditCondition {
1286
+ field: string;
1287
+ operator: 'equals' | 'equals_ci' | 'not_equals' | 'contains' | 'not_contains';
1288
+ value: string | number | boolean;
1244
1289
  }
1245
- interface StepCompleteEvent {
1246
- type: 'step_complete';
1290
+ interface BulkEditRequest {
1291
+ recordIds?: string[];
1292
+ conditions?: BulkEditCondition[];
1293
+ /** Type-scoped record-filter DSL. Mutually exclusive with `conditions`. */
1294
+ recordFilter?: RecordFilter;
1295
+ updates?: JsonObject;
1296
+ deleteFields?: string[];
1297
+ dryRun?: boolean;
1298
+ applyToAll?: boolean;
1299
+ }
1300
+ interface BulkEditResult {
1247
1301
  id: string;
1302
+ before: JsonObject;
1303
+ after: JsonObject;
1304
+ }
1305
+ interface BulkEditResponse {
1306
+ data: BulkEditResult[];
1307
+ recordIds?: number[];
1308
+ }
1309
+ interface ProviderApiKey {
1310
+ id: number;
1311
+ provider: 'openai' | 'anthropic' | 'huggingface' | 'google' | 'xai' | 'mixlayer' | 'togetherai';
1248
1312
  name: string;
1249
- index: number;
1250
- stepType: string;
1251
- /** Step result - used by all step types */
1252
- result?: any;
1253
- executionTime: number;
1313
+ keyPreview: string;
1314
+ isDefault: boolean;
1315
+ isActive: boolean;
1316
+ usageCount: number;
1317
+ lastUsedAt?: string;
1318
+ createdAt: string;
1319
+ updatedAt: string;
1254
1320
  }
1255
- interface FlowCompleteEvent {
1256
- type: 'flow_complete';
1257
- flowId: string;
1258
- totalSteps: number;
1259
- successfulSteps: number;
1260
- failedSteps: number;
1261
- executionTime: number;
1321
+ interface CreateProviderKeyRequest {
1322
+ provider: 'openai' | 'anthropic' | 'huggingface' | 'google' | 'xai' | 'mixlayer' | 'togetherai';
1323
+ name: string;
1324
+ apiKey: string;
1325
+ isDefault?: boolean;
1262
1326
  }
1263
- interface FlowErrorEvent {
1264
- type: 'flow_error';
1265
- error: string;
1266
- stepId?: string;
1327
+ interface UpdateProviderKeyRequest {
1328
+ name?: string;
1329
+ apiKey?: string;
1330
+ isDefault?: boolean;
1331
+ isActive?: boolean;
1267
1332
  }
1268
- /**
1269
- * Union type of all possible SSE events
1270
- */
1271
- type StreamEvent = FlowStartEvent | StepStartEvent | StepDeltaEvent | StepCompleteEvent | FlowCompleteEvent | FlowErrorEvent | FlowPausedEvent | StepWaitingLocalEvent | FallbacksInitiatedEvent | FallbackStartEvent | FallbackSuccessEvent | FallbackFailEvent | FallbacksExhaustedEvent;
1272
- /**
1273
- * Callbacks for streaming flow execution
1274
- *
1275
- * @example
1276
- * ```typescript
1277
- * await flow.run(apiClient, options, {
1278
- * onStepStart: (event) => console.log('Starting:', event.name),
1279
- * onStepDelta: (chunk, event) => process.stdout.write(chunk),
1280
- * onStepComplete: (result, event) => console.log('Done:', event.name),
1281
- * onFlowComplete: (event) => console.log('Flow complete'),
1282
- * onError: (error) => console.error(error),
1283
- * })
1284
- * ```
1333
+ interface CreateApiKeyRequest {
1334
+ name: string;
1335
+ permissions?: string[];
1336
+ expiresAt?: string;
1337
+ allowedIps?: string[];
1338
+ environment?: 'test' | 'production';
1339
+ }
1340
+ interface CreateModelConfigRequest {
1341
+ provider: 'mixlayer' | 'openai' | 'anthropic' | 'google' | 'xai' | 'huggingface' | 'togetherai';
1342
+ modelId: string;
1343
+ apiKey?: string;
1344
+ settings?: JsonObject;
1345
+ }
1346
+ /** Content part types for multi-modal messages */
1347
+ interface TextContentPart {
1348
+ type: 'text';
1349
+ text: string;
1350
+ }
1351
+ interface ImageContentPart {
1352
+ type: 'image';
1353
+ image: string;
1354
+ mimeType?: string;
1355
+ }
1356
+ interface FileContentPart {
1357
+ type: 'file';
1358
+ data: string;
1359
+ mimeType: string;
1360
+ filename: string;
1361
+ }
1362
+ type MessageContent = string | Array<TextContentPart | ImageContentPart | FileContentPart>;
1363
+ /**
1364
+ * Options for upsert mode - controls conflict detection and versioning
1285
1365
  */
1286
- interface StreamCallbacks {
1287
- /** Called when flow execution starts */
1288
- onFlowStart?: (event: FlowStartEvent) => void;
1289
- /** Called when a step starts executing */
1290
- onStepStart?: (event: StepStartEvent) => void;
1291
- /** Called for each text fragment of streaming output from a step */
1292
- onStepDelta?: (text: string, event: StepDeltaEvent) => void;
1293
- /** Called when a step completes */
1294
- onStepComplete?: (result: any, event: StepCompleteEvent) => void;
1295
- /** Called when the entire flow completes */
1296
- onFlowComplete?: (event: FlowCompleteEvent) => void;
1297
- /** Called when an error occurs */
1298
- onError?: (error: Error) => void;
1366
+ interface UpsertOptions {
1367
+ /** Whether to create a version snapshot before updating (default: true) */
1368
+ createVersionOnChange?: boolean;
1369
+ /** Allow overwriting changes made via dashboard/API (default: false) */
1370
+ allowOverwriteExternalChanges?: boolean;
1299
1371
  }
1300
1372
  /**
1301
- * Summary returned after flow execution completes
1373
+ * Environment type for dispatch requests
1302
1374
  */
1303
- interface FlowSummary {
1304
- flowId: string;
1305
- flowName: string;
1306
- totalSteps: number;
1307
- successfulSteps: number;
1308
- failedSteps: number;
1309
- executionTime: number;
1310
- /** Results from each step, keyed by step name */
1311
- results: Map<string, any>;
1312
- /** Whether the flow completed successfully */
1313
- success: boolean;
1375
+ type DispatchEnvironment = 'development' | 'production';
1376
+ interface DispatchRequest {
1377
+ record?: {
1378
+ id?: number | string;
1379
+ name?: string;
1380
+ type?: string;
1381
+ metadata?: Metadata;
1382
+ };
1383
+ flow: {
1384
+ id?: string;
1385
+ name?: string;
1386
+ steps?: Array<any>;
1387
+ };
1388
+ messages?: Array<{
1389
+ role: 'system' | 'user' | 'assistant';
1390
+ content: MessageContent;
1391
+ }>;
1392
+ secrets?: Record<string, string>;
1393
+ inputs?: Record<string, unknown>;
1394
+ options?: {
1395
+ streamResponse?: boolean;
1396
+ modelOverride?: string;
1397
+ recordMode?: 'existing' | 'create' | 'virtual';
1398
+ flowMode?: 'existing' | 'create' | 'virtual' | 'upsert';
1399
+ storeResults?: boolean;
1400
+ autoAppendMetadata?: boolean;
1401
+ debugMode?: boolean;
1402
+ environment?: DispatchEnvironment;
1403
+ createVersion?: boolean;
1404
+ versionType?: 'published' | 'draft' | 'test' | 'virtual';
1405
+ versionLabel?: string;
1406
+ versionNotes?: string;
1407
+ flowVersionId?: string;
1408
+ upsertOptions?: UpsertOptions;
1409
+ flowTimeoutMs?: number;
1410
+ stepTimeoutMs?: number;
1411
+ };
1314
1412
  }
1315
- declare class FlowBuilder {
1316
- private flowConfig;
1317
- private steps;
1318
- private recordConfig;
1319
- private messagesConfig;
1320
- private inputsConfig;
1321
- private optionsConfig;
1322
- private stepCounter;
1323
- private existingFlowId;
1324
- /**
1325
- * Initialize the flow with a name and optional description.
1326
- * Use this for virtual/one-off flows or when specifying flowMode in run().
1327
- */
1328
- createFlow(config: FlowConfig$1): this;
1329
- /**
1330
- * Define a flow for upsert - creates if it doesn't exist, updates if steps changed.
1331
- * This is the recommended pattern for code-first flow management.
1332
- *
1333
- * @example
1334
- * ```typescript
1335
- * const result = await new FlowBuilder()
1336
- * .upsertFlow({
1337
- * name: 'My Flow',
1338
- * createVersionOnChange: true
1339
- * })
1340
- * .prompt({ name: 'Analyze', model: 'gpt-4o', userPrompt: '...' })
1341
- * .run(apiClient, { streamResponse: true })
1342
- * ```
1343
- */
1344
- upsertFlow(config: UpsertFlowConfig$1): this;
1345
- /**
1346
- * Use an existing flow by ID instead of defining steps inline
1347
- *
1348
- * @example
1349
- * ```typescript
1350
- * const result = await new FlowBuilder()
1351
- * .useExistingFlow('flow_abc123')
1352
- * .withRecord({ name: 'Test', type: 'data' })
1353
- * .run(apiClient, { streamResponse: true })
1354
- * ```
1355
- */
1356
- useExistingFlow(flowId: string): this;
1357
- /**
1358
- * Set the record configuration
1359
- */
1360
- withRecord(config: RecordConfig$1): this;
1361
- /**
1362
- * Set conversation messages
1363
- */
1364
- withMessages(messages: Message$1[]): this;
1365
- /**
1366
- * Set top-level input variables accessible as {{varName}} in templates
1367
- *
1368
- * @example
1369
- * ```typescript
1370
- * const result = await new FlowBuilder()
1371
- * .useExistingFlow('flow_abc123')
1372
- * .withInputs({
1373
- * customerName: 'John',
1374
- * topic: 'billing'
1375
- * })
1376
- * .run(apiClient, { streamResponse: true })
1377
- * ```
1378
- */
1379
- withInputs(inputs: Record<string, unknown>): this;
1380
- /**
1381
- * Set dispatch options
1382
- */
1383
- withOptions(options: DispatchOptions$1): this;
1384
- /**
1385
- * Add a prompt step
1386
- */
1387
- prompt(config: PromptStepConfig$1): this;
1388
- /**
1389
- * Add a crawl step
1390
- */
1391
- crawl(config: CrawlStepConfig): this;
1392
- /**
1393
- * Add a fetch URL step
1394
- */
1395
- fetchUrl(config: FetchUrlStepConfig$1): this;
1396
- /**
1397
- * Add a transform data step
1398
- */
1399
- transformData(config: TransformDataStepConfig$1): this;
1400
- /**
1401
- * Add a set variable step
1402
- */
1403
- setVariable(config: SetVariableStepConfig$1): this;
1404
- /**
1405
- * Add a conditional step
1406
- */
1407
- conditional(config: ConditionalStepConfig$1): this;
1408
- /**
1409
- * Add a search step
1410
- */
1411
- search(config: SearchStepConfig$1): this;
1412
- /**
1413
- * Add a send email step
1414
- */
1415
- sendEmail(config: SendEmailStepConfig$1): this;
1416
- /**
1417
- * Add a send stream step
1418
- */
1419
- sendStream(config: SendStreamStepConfig$1): this;
1420
- /**
1421
- * Add a retrieve record step
1422
- */
1423
- retrieveRecord(config: RetrieveRecordStepConfig$1): this;
1424
- /**
1425
- * Add an upsert record step
1426
- */
1427
- upsertRecord(config: UpsertRecordStepConfig$1): this;
1428
- /**
1429
- * Add a vector search step
1430
- */
1431
- vectorSearch(config: VectorSearchStepConfig$1): this;
1432
- /**
1433
- * Add a generate embedding step
1434
- */
1435
- generateEmbedding(config: GenerateEmbeddingStepConfig$1): this;
1436
- /**
1437
- * Add a wait until step
1438
- */
1439
- waitUntil(config: WaitUntilStepConfig$1): this;
1440
- /**
1441
- * Add a send event step
1442
- */
1443
- sendEvent(config: SendEventStepConfig$1): this;
1444
- /**
1445
- * Add a send text step
1446
- */
1447
- sendText(config: SendTextStepConfig$1): this;
1448
- /**
1449
- * Add a fetch GitHub step
1450
- */
1451
- fetchGitHub(config: FetchGitHubStepConfig$1): this;
1452
- /**
1453
- * Attach a subagent runtime tool to the most recent prompt step.
1454
- *
1455
- * A subagent tool spawns a focused child agent in its own context window
1456
- * when the parent's model calls it. The child runs with a whitelisted tool
1457
- * subset drawn from `allowedTools` (every entry must be available on the
1458
- * parent step). The parent only sees the child's final result.
1459
- *
1460
- * Pass either `agentId` (for a saved agent in the same org) or `agent`
1461
- * (an inline exported-agent JSON shape) — exactly one is required.
1462
- *
1463
- * @example
1464
- * ```typescript
1465
- * new FlowBuilder()
1466
- * .createFlow({ name: 'Research' })
1467
- * .prompt({ name: 'Plan', model: 'claude-sonnet-4-5', userPrompt: '...' })
1468
- * .withSubagentTool('research_topic', {
1469
- * agentId: 'agent_01h...',
1470
- * allowedTools: ['builtin:exa_search'],
1471
- * outputFormat: 'text',
1472
- * })
1473
- * ```
1474
- */
1475
- withSubagentTool(name: string, opts: {
1476
- description?: string;
1477
- agentId?: string;
1478
- agent?: JsonObject;
1479
- allowedTools: string[];
1480
- parametersSchema?: JSONSchema;
1481
- maxTurns?: number;
1482
- maxCost?: number;
1483
- timeoutMs?: number;
1484
- outputFormat?: 'text' | 'json' | 'last_message';
1485
- inheritMessages?: boolean;
1486
- taskTemplate?: string;
1487
- }): this;
1488
- /**
1489
- * Enable agent-driven dynamic subagent spawning on the most recent prompt
1490
- * step (surface C of the subagent design).
1491
- *
1492
- * When set, the API synthesizes a `spawn_subagent` tool the parent's model
1493
- * can call at runtime to spin off a focused child agent. The child's tools
1494
- * are drawn from `toolPool`, which must be a subset of the parent step's
1495
- * resolved tools. The API validates pool entries and rejects escalation.
1496
- *
1497
- * @example
1498
- * ```typescript
1499
- * new FlowBuilder()
1500
- * .createFlow({ name: 'Explore' })
1501
- * .prompt({ name: 'Research', model: 'claude-sonnet-4-5', userPrompt: '...' })
1502
- * .withSubagents({
1503
- * toolPool: ['builtin:exa_search', 'mcp:*'],
1504
- * maxSpawnsPerRun: 3,
1505
- * allowNesting: false,
1506
- * })
1507
- * ```
1508
- */
1509
- withSubagents(opts: AgentSubagentConfig): this;
1510
- /**
1511
- * Build the final dispatch request configuration
1512
- */
1513
- build(): DispatchRequest;
1514
- /**
1515
- * Build and execute the flow with the provided client
1516
- *
1517
- * Returns a FlowResult that can be used to:
1518
- * - Process with callbacks via `.stream(callbacks)`
1519
- * - Get a specific step result via `.getResult(stepName)`
1520
- * - Get all results via `.getAllResults()`
1521
- * - Access raw response via `.raw`
1522
- *
1523
- * @param client - Client with dispatch capability
1524
- * @param options - Optional execution options (merged with any .withOptions() settings)
1525
- * @returns FlowResult for processing the streaming response
1526
- *
1527
- * @example
1528
- * ```typescript
1529
- * // Simple execution with result extraction
1530
- * const result = await flow.run(apiClient, { streamResponse: true })
1531
- * const analysis = await result.getResult('Analyze Data')
1532
- *
1533
- * // With streaming callbacks
1534
- * const result = await flow.run(apiClient, options)
1535
- * await result.stream({
1536
- * onStepDelta: (chunk) => process.stdout.write(chunk),
1537
- * onFlowComplete: () => console.log('Done!'),
1538
- * })
1539
- * ```
1540
- */
1541
- run(client: DispatchClient, options?: DispatchOptions$1): Promise<FlowResult>;
1542
- /**
1543
- * Build and execute the flow with callbacks for streaming events
1544
- *
1545
- * @param client - Client with dispatch capability
1546
- * @param options - Execution options (merged with any .withOptions() settings)
1547
- * @param callbacks - Callbacks for streaming events
1548
- * @returns FlowSummary when execution completes
1549
- *
1550
- * @example
1551
- * ```typescript
1552
- * const summary = await flow.run(apiClient, options, {
1553
- * onStepStart: (event) => console.log('Starting:', event.name),
1554
- * onStepDelta: (chunk) => process.stdout.write(chunk),
1555
- * onStepComplete: (result, event) => console.log('Done:', event.name),
1556
- * onFlowComplete: (event) => console.log('Flow complete!'),
1557
- * })
1558
- * ```
1559
- */
1560
- run(client: DispatchClient, options: DispatchOptions$1, callbacks: StreamCallbacks): Promise<FlowSummary>;
1561
- /**
1562
- * Set a run condition (when predicate) on the last added step.
1563
- * If the expression evaluates to falsy at runtime, the step is skipped.
1564
- *
1565
- * @example
1566
- * ```typescript
1567
- * new FlowBuilder()
1568
- * .createFlow({ name: 'Conditional' })
1569
- * .prompt({ name: 'Summarize', model: 'gpt-4', userPrompt: '...' })
1570
- * .when('data.length > 0')
1571
- * .build()
1572
- * ```
1573
- */
1574
- when(expression: string): this;
1575
- private addStep;
1413
+ interface ListParams {
1414
+ limit?: number;
1415
+ cursor?: string;
1416
+ direction?: 'next' | 'prev';
1417
+ }
1418
+ interface RecordListParams extends ListParams {
1419
+ metadataKeys?: string;
1420
+ metadataKeysAll?: string;
1421
+ minFields?: number;
1422
+ maxFields?: number;
1423
+ metadataTypes?: string;
1424
+ hasLargeFields?: boolean;
1425
+ minSizeKb?: number;
1426
+ maxSizeKb?: number;
1427
+ sortBy?: string;
1428
+ sortOrder?: 'asc' | 'desc';
1429
+ includeFields?: boolean;
1430
+ }
1431
+ interface Tool {
1432
+ id: string;
1433
+ userId: string;
1434
+ organizationId?: string;
1435
+ name: string;
1436
+ description: string;
1437
+ toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
1438
+ parametersSchema: JSONSchema;
1439
+ config: ToolConfig;
1440
+ isActive: boolean;
1441
+ createdAt: string;
1442
+ updatedAt: string;
1443
+ }
1444
+ type ToolConfig = FlowToolConfig | CustomToolConfig | ExternalToolConfig | LocalToolConfig | SubagentToolConfig;
1445
+ interface FlowToolConfig {
1446
+ flowId?: string;
1447
+ toolId?: string;
1448
+ parameterMapping: Record<string, string>;
1449
+ outputMapping?: string;
1450
+ }
1451
+ interface CustomToolConfig {
1452
+ code: string;
1453
+ timeout: number;
1454
+ allowedApis: string[];
1455
+ }
1456
+ interface ExternalToolConfig {
1457
+ url: string;
1458
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
1459
+ headers?: Record<string, string>;
1460
+ body?: string;
1461
+ authType?: 'none' | 'bearer' | 'api_key';
1462
+ }
1463
+ interface LocalToolConfig {
1464
+ [key: string]: JsonValue;
1465
+ }
1466
+ interface SubagentToolConfig {
1467
+ agentId?: string;
1468
+ agent?: JsonObject;
1469
+ allowedTools: string[];
1470
+ maxTurns?: number;
1471
+ maxCost?: number;
1472
+ timeoutMs?: number;
1473
+ outputFormat?: 'text' | 'json' | 'last_message';
1474
+ inheritMessages?: boolean;
1475
+ taskTemplate?: string;
1476
+ }
1477
+ interface BuiltInTool {
1478
+ id: string;
1479
+ name: string;
1480
+ description: string;
1481
+ category: 'image_generation' | 'web_search' | 'web_scraping' | 'code_execution' | 'file_operations' | 'data_analysis' | 'knowledge_retrieval' | 'text_to_speech' | 'voice_processing' | 'third_party_api' | 'artifact' | 'data_management' | 'commerce' | 'browser';
1482
+ providers: string[];
1483
+ parametersSchema: JSONSchema;
1484
+ defaultConfig?: JsonObject;
1485
+ documentationUrl?: string;
1486
+ }
1487
+ interface ToolExecution {
1488
+ id: string;
1489
+ toolId: string;
1490
+ flowExecutionId?: string;
1491
+ stepId?: string;
1492
+ userId: string;
1493
+ inputParameters: JsonObject;
1494
+ outputResult: JsonValue;
1495
+ status: 'pending' | 'success' | 'failed';
1496
+ errorMessage?: string;
1497
+ executionTimeMs?: number;
1498
+ createdAt: string;
1499
+ }
1500
+ interface CreateToolRequest {
1501
+ name: string;
1502
+ description: string;
1503
+ toolType: 'flow' | 'custom' | 'external' | 'subagent';
1504
+ parametersSchema: JSONSchema;
1505
+ config: ToolConfig;
1506
+ }
1507
+ interface UpdateToolRequest {
1508
+ name?: string;
1509
+ description?: string;
1510
+ parametersSchema?: JSONSchema;
1511
+ config?: ToolConfig;
1512
+ isActive?: boolean;
1513
+ }
1514
+ interface ExecuteToolRequest {
1515
+ toolId: string;
1516
+ parameters: JsonObject;
1517
+ }
1518
+ interface ExecuteToolResponse {
1519
+ executionId: string;
1520
+ result: JsonValue;
1521
+ status: 'success' | 'failed';
1522
+ errorMessage?: string;
1523
+ executionTimeMs: number;
1576
1524
  }
1577
- /**
1578
- * Interface for clients that can dispatch flows
1579
- */
1580
- interface DispatchClient {
1581
- /**
1582
- * Run a flow with local tools (automatic pause/resume loop)
1583
- *
1584
- * @param config - The dispatch request configuration
1585
- * @param localTools - Map of tool names to async functions that execute the tool logic
1586
- * @param callbacks - Optional callbacks for streaming events
1587
- * @returns The final result of the flow execution or summary if streaming
1588
- */
1589
- runWithLocalTools(config: DispatchRequest, localTools: Record<string, (args: any) => Promise<any>>, callbacks?: StreamCallbacks): Promise<FlowResult | FlowSummary>;
1590
- dispatch(config: DispatchRequest): Promise<Response>;
1525
+ interface DeploySandboxRequest {
1526
+ code: string;
1527
+ packageJson?: string;
1528
+ language?: 'javascript' | 'typescript' | 'python';
1529
+ port?: number;
1530
+ sandboxId?: string;
1531
+ startCommand?: string;
1532
+ files?: Record<string, string>;
1591
1533
  }
1592
- /**
1593
- * FlowBuilder that is bound to a client for direct execution
1594
- *
1595
- * @example
1596
- * ```typescript
1597
- * // Via RuntypeClient.flow()
1598
- * const result = await runtype
1599
- * .flow('My Flow')
1600
- * .fetchUrl({ name: 'Fetch', url: '...', outputVariable: 'data' })
1601
- * .prompt({ name: 'Process', model: 'gpt-4', userPrompt: '...' })
1602
- * .run({ streamResponse: true })
1603
- *
1604
- * const data = await result.getResult('Process')
1605
- * ```
1606
- */
1607
- declare class ClientFlowBuilder extends FlowBuilder {
1608
- private boundClient;
1609
- constructor(client: DispatchClient, name: string);
1610
- /**
1611
- * Build and execute the flow using the bound client
1612
- *
1613
- * For ClientFlowBuilder, you can either:
1614
- * 1. Pass a client (which is ignored, the bound client is used)
1615
- * 2. Pass options directly as the first argument
1616
- *
1617
- * @example
1618
- * ```typescript
1619
- * // Simple execution (no args needed)
1620
- * const result = await builder.run()
1621
- * const data = await result.getResult('Process')
1622
- *
1623
- * // With options only
1624
- * const result = await builder.run({ streamResponse: true, flowMode: 'virtual' })
1625
- *
1626
- * // With options and callbacks
1627
- * const summary = await builder.run({ streamResponse: true }, {
1628
- * onStepDelta: (chunk) => process.stdout.write(chunk),
1629
- * onFlowComplete: () => console.log('Done!'),
1630
- * })
1631
- *
1632
- * // Parent class signature (client ignored)
1633
- * const result = await builder.run(someClient, { streamResponse: true })
1634
- * ```
1635
- */
1636
- run(): Promise<FlowResult>;
1637
- run(options: DispatchOptions$1): Promise<FlowResult>;
1638
- run(options: DispatchOptions$1, callbacks: StreamCallbacks): Promise<FlowSummary>;
1639
- run(localTools: Record<string, (args: any) => Promise<any>>): Promise<FlowResult>;
1640
- run(options: DispatchOptions$1, localTools: Record<string, (args: any) => Promise<any>>): Promise<FlowResult>;
1641
- run(localTools: Record<string, (args: any) => Promise<any>>, callbacks: StreamCallbacks): Promise<FlowSummary>;
1642
- run(options: DispatchOptions$1, localTools: Record<string, (args: any) => Promise<any>>, callbacks: StreamCallbacks): Promise<FlowSummary>;
1643
- run(client: DispatchClient, options?: DispatchOptions$1): Promise<FlowResult>;
1644
- run(client: DispatchClient, options: DispatchOptions$1, callbacks: StreamCallbacks): Promise<FlowSummary>;
1534
+ interface DeploySandboxResponse {
1535
+ sandboxId: string;
1536
+ previewUrl: string;
1537
+ output: string;
1538
+ status: 'running' | 'error';
1539
+ error?: string;
1645
1540
  }
1646
- /**
1647
- * Create an external runtime tool definition.
1648
- *
1649
- * External tools make HTTP requests to external APIs with support for
1650
- * variable substitution in URLs and headers.
1651
- *
1652
- * Special internal variables are available for auth:
1653
- * - `{{_internal.auth_token}}` - Bearer token for Runtype API auth
1654
- * - `{{_internal.user_id}}` - Current user ID
1655
- * - `{{_internal.org_id}}` - Current organization ID
1656
- *
1657
- * @example
1658
- * ```typescript
1659
- * const listFlowsTool = createExternalTool({
1660
- * name: 'list_flows',
1661
- * description: 'List all flows in the workspace',
1662
- * parametersSchema: {
1663
- * type: 'object',
1664
- * properties: {
1665
- * limit: { type: 'number', description: 'Max results', default: 20 }
1666
- * }
1667
- * },
1668
- * url: 'https://api.runtype.com/v1/flows',
1669
- * method: 'GET',
1670
- * headers: { Authorization: '{{_internal.auth_token}}' }
1671
- * })
1672
- * ```
1673
- */
1674
- declare function createExternalTool(config: {
1541
+ interface DeployCfSandboxRequest {
1542
+ code: string;
1543
+ packageJson?: string;
1544
+ language?: 'javascript' | 'typescript' | 'python';
1545
+ port?: number;
1546
+ sandboxId?: string;
1547
+ startCommand?: string;
1548
+ files?: Record<string, string>;
1549
+ }
1550
+ interface DeployCfSandboxResponse {
1551
+ sandboxId: string;
1552
+ previewUrl: string;
1553
+ output: string;
1554
+ status: 'running' | 'error';
1555
+ stage?: 'validate_port' | 'validate_files' | 'write_package_json' | 'npm_install' | 'write_main_file' | 'write_additional_files' | 'start_process' | 'expose_port';
1556
+ error?: string;
1557
+ }
1558
+ interface ModelUsageQueryParams {
1559
+ startDate?: string;
1560
+ endDate?: string;
1561
+ period?: 'today' | 'yesterday' | 'last_7_days' | 'last_30_days' | 'current_month' | 'last_month' | 'current_year';
1562
+ granularity?: 'hour' | 'day' | 'week' | 'month';
1563
+ modelConfigId?: string;
1564
+ }
1565
+ interface ModelUsageSummary {
1566
+ totalRequests: number;
1567
+ totalCost: number;
1568
+ totalTokens: number;
1569
+ platformCost?: number;
1570
+ userCost?: number;
1571
+ platformTokens?: number;
1572
+ userTokens?: number;
1573
+ }
1574
+ interface ModelUsageDetail {
1575
+ modelId: string;
1576
+ modelName?: string;
1577
+ provider: string;
1578
+ requestCount: number;
1579
+ totalCost: number;
1580
+ totalTokens: number;
1581
+ avgCostPerRequest: number;
1582
+ }
1583
+ interface ModelUsageTimeSeries {
1584
+ date: string;
1585
+ requests: number;
1586
+ cost: number;
1587
+ tokens: number;
1588
+ }
1589
+ interface ModelUsageResponse {
1590
+ meta: {
1591
+ startDate: string;
1592
+ endDate: string;
1593
+ period?: string;
1594
+ granularity?: string;
1595
+ };
1596
+ summary: ModelUsageSummary;
1597
+ usageByModel: Record<string, ModelUsageDetail>;
1598
+ timeSeries?: ModelUsageTimeSeries[];
1599
+ }
1600
+ interface RuntimeTool {
1675
1601
  name: string;
1676
1602
  description: string;
1677
- parametersSchema: any;
1603
+ toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
1604
+ parametersSchema: JSONSchema;
1605
+ config?: RuntimeToolConfig;
1606
+ }
1607
+ type RuntimeToolConfig = RuntimeFlowToolConfig | RuntimeCustomToolConfig | RuntimeExternalToolConfig | RuntimeLocalToolConfig | RuntimeSubagentToolConfig;
1608
+ interface RuntimeLocalToolConfig {
1609
+ [key: string]: JsonValue;
1610
+ }
1611
+ interface RuntimeFlowToolConfig {
1612
+ flowId?: string;
1613
+ toolId?: string;
1614
+ parameterMapping?: Record<string, string>;
1615
+ outputMapping?: string;
1616
+ }
1617
+ interface RuntimeCustomToolConfig {
1618
+ code: string;
1619
+ language?: 'javascript' | 'typescript' | 'python';
1620
+ sandboxProvider?: 'quickjs' | 'daytona' | 'cloudflare-worker';
1621
+ timeout?: number;
1622
+ }
1623
+ interface RuntimeExternalToolConfig {
1678
1624
  url: string;
1679
1625
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
1680
1626
  headers?: Record<string, string>;
1681
1627
  body?: string;
1682
- }): RuntimeTool;
1628
+ }
1629
+ type RuntimeSubagentToolConfig = SubagentToolConfig;
1630
+ interface AgentSubagentConfig {
1631
+ toolPool: string[];
1632
+ defaultMaxTurns?: number;
1633
+ maxTurnsLimit?: number;
1634
+ maxSpawnsPerRun?: number;
1635
+ defaultModel?: string;
1636
+ allowNesting?: boolean;
1637
+ defaultTimeoutMs?: number;
1638
+ }
1639
+ interface CustomMCPServerAuth {
1640
+ type: 'bearer' | 'api_key' | 'basic' | 'custom_header' | 'oauth2' | 'none';
1641
+ headerName?: string;
1642
+ token?: string;
1643
+ username?: string;
1644
+ password?: string;
1645
+ oauth2?: {
1646
+ accessToken?: string;
1647
+ refreshToken?: string;
1648
+ tokenEndpoint?: string;
1649
+ clientId?: string;
1650
+ clientSecret?: string;
1651
+ expiresAt?: number;
1652
+ scope?: string;
1653
+ issuer?: string;
1654
+ };
1655
+ }
1656
+ interface CustomMCPServer {
1657
+ id: string;
1658
+ name?: string;
1659
+ url: string;
1660
+ auth?: CustomMCPServerAuth;
1661
+ allowedTools?: string[];
1662
+ timeout?: number;
1663
+ transport?: 'streamable_http' | 'rest';
1664
+ enabled?: boolean;
1665
+ }
1666
+ interface ToolsConfig {
1667
+ toolIds?: string[];
1668
+ runtimeTools?: RuntimeTool[];
1669
+ subagentConfig?: AgentSubagentConfig;
1670
+ mcpServers?: CustomMCPServer[];
1671
+ maxToolCalls?: number;
1672
+ toolCallStrategy?: 'auto' | 'required' | 'none';
1673
+ parallelCalls?: boolean;
1674
+ toolConfigs?: Record<string, JsonObject>;
1675
+ }
1676
+ interface ReasoningConfig {
1677
+ enabled: boolean;
1678
+ reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
1679
+ reasoningSummary?: 'auto' | 'detailed';
1680
+ budgetTokens?: number;
1681
+ thinkingBudget?: number;
1682
+ includeThoughts?: boolean;
1683
+ }
1684
+ type ReasoningValue = boolean | ReasoningConfig;
1683
1685
 
1684
1686
  /**
1685
1687
  * FlowsNamespace - Static namespace for flow operations
@@ -3155,6 +3157,10 @@ declare class FlowsEndpoint {
3155
3157
  * Delete a flow
3156
3158
  */
3157
3159
  delete(id: string): Promise<void>;
3160
+ /**
3161
+ * Export a flow as a self-contained runtime definition for @runtypelabs/runtime
3162
+ */
3163
+ exportRuntime(id: string): Promise<any>;
3158
3164
  /**
3159
3165
  * Run a flow on all records of a specific type
3160
3166
  */
@@ -4534,6 +4540,10 @@ declare class AgentsEndpoint {
4534
4540
  * Delete an agent
4535
4541
  */
4536
4542
  delete(id: string): Promise<void>;
4543
+ /**
4544
+ * Export an agent as a self-contained runtime definition for @runtypelabs/runtime
4545
+ */
4546
+ exportRuntime(id: string): Promise<any>;
4537
4547
  /**
4538
4548
  * Evaluate a model-proposed runtime tool against a configurable allowlist policy.
4539
4549
  * Useful for local `propose_runtime_tool` handlers before follow-up execution.
@@ -5433,4 +5443,4 @@ declare function getLikelySupportingCandidatePaths(bestCandidatePath: string | u
5433
5443
  declare function getDefaultPlanPath(taskName: string): string;
5434
5444
  declare function sanitizeTaskSlug(taskName: string): string;
5435
5445
 
5436
- export { type Agent, type AgentApprovalCompleteEvent, type AgentApprovalStartEvent, type AgentCompleteEvent, type AgentErrorEvent, type AgentEvent, type AgentEventType, type AgentExecuteRequest, type AgentExecuteResponse, type AgentIterationCompleteEvent, type AgentIterationStartEvent, type AgentMediaEvent, type AgentMessage, type AgentPausedEvent, type AgentPingEvent, type AgentReflectionEvent, type AgentRuntimeToolDefinition, type AgentStartEvent, type AgentStreamCallbacks, type AgentSubagentConfig, type AgentToolCompleteEvent, type AgentToolDeltaEvent, type AgentToolInputCompleteEvent, type AgentToolInputDeltaEvent, type AgentToolStartEvent, type AgentTurnCompleteEvent, type AgentTurnDeltaEvent, type AgentTurnStartEvent, AgentsEndpoint, AnalyticsEndpoint, type ApiClient, type ApiKey, ApiKeysEndpoint, type ApiResponse, type ApplyGeneratedProposalOptions, type ApplyGeneratedProposalResult, type AttachRuntimeToolsOptions, type BaseAgentEvent, BatchBuilder, type BatchClient, type BatchListParams, type BatchOptions, type BatchRequest, type BatchResult, type BatchScheduleConfig, type BatchStatus, BatchesNamespace, type BuiltInTool, type BulkEditCondition, type BulkEditRequest, type BulkEditResponse, type BulkEditResult, ChatEndpoint, ClientBatchBuilder, type ClientConfig, type ClientConversation, ClientEvalBuilder, ClientFlowBuilder, type ClientToken, type ClientTokenConfig, type ClientTokenEnvironment, type ClientTokenVersionPin, ClientTokensEndpoint, type ClientWidgetTheme, type ConditionalStepConfig$1 as ConditionalStepConfig, type ContextErrorHandling, type ContextFallback, ContextTemplatesEndpoint, type CreateApiKeyRequest, type CreateClientTokenRequest, type CreateClientTokenResponse, type CreateFlowRequest, type CreateModelConfigRequest, type CreatePromptData, type CreatePromptRequest, type CreateProviderKeyRequest, type CreateRecordRequest, type CreateToolRequest, type CustomMCPServer, type CustomMCPServerAuth, type CustomToolConfig, type DeployCfSandboxRequest, type DeployCfSandboxResponse, type DeploySandboxRequest, type DeploySandboxResponse, type DispatchClient, DispatchEndpoint, type DispatchEnvironment, type DispatchOptions$1 as DispatchOptions, type DispatchRequest, type ErrorHandlingMode, EvalBuilder, type EvalClient, EvalEndpoint, type EvalListParams, type EvalOptions, type EvalRecord, type EvalRequest, type EvalResult, type EvalRunConfig, EvalRunner, type EvalStatus, EvalsNamespace, type ExecuteToolRequest, type ExecuteToolResponse, type ExternalToolConfig, type FallbackFailEvent, type FallbackStartEvent, type FallbackSuccessEvent, type FallbacksExhaustedEvent, type FallbacksInitiatedEvent, type FetchGitHubStepConfig$1 as FetchGitHubStepConfig, type FetchUrlStepConfig$1 as FetchUrlStepConfig, type FieldFormat, type FileContentPart, type Flow, type FlowAttachment, FlowBuilder, type FlowCompleteEvent, type FlowConfig$1 as FlowConfig, type FlowErrorEvent, type FlowFallback, type FlowPausedEvent, FlowResult, type FlowStartEvent, type FlowStep, FlowStepsEndpoint, type FlowSummary, type FlowToolConfig, FlowsEndpoint, FlowsNamespace, type GenerateEmbeddingStepConfig$1 as GenerateEmbeddingStepConfig, type GeneratedRuntimeToolGateDecision, type GeneratedRuntimeToolGateOptions, type ImageContentPart, type JSONSchema, type JsonArray, type JsonObject, type JsonPrimitive, type JsonValue, type ListConversationsResponse, type ListParams, type LocalToolConfig, type LocalToolDefinition, type LocalToolExecutionCompleteEvent, type LocalToolExecutionLoopSnapshotSlice, type LocalToolExecutionStartEvent, type Message$1 as Message, type MessageContent, type Metadata, type ModelConfig, ModelConfigsEndpoint, type ModelFallback, type ModelOverride, type ModelUsageDetail, type ModelUsageQueryParams, type ModelUsageResponse, type ModelUsageSummary, type ModelUsageTimeSeries, type PaginationResponse, type Prompt$1 as Prompt, type PromptErrorHandling, type PromptFallback, type PromptListParams, type PromptRunOptions, PromptRunner, type PromptStepConfig$1 as PromptStepConfig, PromptsEndpoint, PromptsNamespace, type ProviderApiKey, type ReasoningConfig, type ReasoningValue, type RecordConfig$1 as RecordConfig, type RecordListParams, RecordsEndpoint, type RetrieveRecordStepConfig$1 as RetrieveRecordStepConfig, type RetryFallback, type RunTaskContextBudgetBreakdown, type RunTaskContextCompactionEvent, type RunTaskContextCompactionStrategy, type RunTaskContextNoticeEvent, type RunTaskContinuation, type RunTaskOnContextCompaction, type RunTaskOnContextNotice, type RunTaskOnSession, type RunTaskOptions, type RunTaskResult, type RunTaskResumeState, type RunTaskSessionSummary, type RunTaskState, type RunTaskStateSlice, type RunTaskStatus, type RunTaskToolTraceSlice, type RuntimeCustomToolConfig, type RuntimeExternalToolConfig, type RuntimeFlowToolConfig, type RuntimeLocalToolConfig, type RuntimeSubagentToolConfig, type RuntimeTool, type RuntimeToolConfig, Runtype, RuntypeApiError, RuntypeClient, type ConditionalStepConfig as RuntypeConditionalStepConfig, type RuntypeConfig, type FetchGitHubStepConfig as RuntypeFetchGitHubStepConfig, type FetchUrlStepConfig as RuntypeFetchUrlStepConfig, RuntypeFlowBuilder, type FlowConfig as RuntypeFlowConfig, type GenerateEmbeddingStepConfig as RuntypeGenerateEmbeddingStepConfig, type Message as RuntypeMessage, type ModelOverride$1 as RuntypeModelOverride, type Prompt as RuntypePrompt, type PromptStepConfig as RuntypePromptStepConfig, type RuntypeRecord, type RecordConfig as RuntypeRecordConfig, type RetrieveRecordStepConfig as RuntypeRetrieveRecordStepConfig, type SearchStepConfig as RuntypeSearchStepConfig, type SendEmailStepConfig as RuntypeSendEmailStepConfig, type SendEventStepConfig as RuntypeSendEventStepConfig, type SendStreamStepConfig as RuntypeSendStreamStepConfig, type SendTextStepConfig as RuntypeSendTextStepConfig, type SetVariableStepConfig as RuntypeSetVariableStepConfig, type TransformDataStepConfig as RuntypeTransformDataStepConfig, type UpsertFlowConfig as RuntypeUpsertFlowConfig, type UpsertRecordStepConfig as RuntypeUpsertRecordStepConfig, type VectorSearchStepConfig as RuntypeVectorSearchStepConfig, type WaitUntilStepConfig as RuntypeWaitUntilStepConfig, STEP_FIELD_REGISTRY, STEP_TYPE_TO_METHOD, type SearchStepConfig$1 as SearchStepConfig, type SendEmailStepConfig$1 as SendEmailStepConfig, type SendEventStepConfig$1 as SendEventStepConfig, type SendStreamStepConfig$1 as SendStreamStepConfig, type SendTextStepConfig$1 as SendTextStepConfig, type SetVariableStepConfig$1 as SetVariableStepConfig, type StepCompleteEvent, type StepDeltaEvent, type StepFallback, type StepFieldMeta, type StepStartEvent, type StepWaitingLocalEvent, type StreamCallbacks, type StreamEvent, type SubagentToolConfig, type TextContentPart, type Tool, type ToolConfig, type ToolExecution, type ToolsConfig, ToolsEndpoint, type TransformDataStepConfig$1 as TransformDataStepConfig, type UpdateClientTokenRequest, type UpdatePromptData, type UpdateProviderKeyRequest, type UpdateToolRequest, type UpsertFlowConfig$1 as UpsertFlowConfig, type UpsertOptions$1 as UpsertOptions, type UpsertRecordStepConfig$1 as UpsertRecordStepConfig, type UserProfile, UsersEndpoint, type VectorSearchStepConfig$1 as VectorSearchStepConfig, type WaitUntilStepConfig$1 as WaitUntilStepConfig, type WorkflowContext, type WorkflowDefinition, type WorkflowPhase, applyGeneratedRuntimeToolProposalToDispatchRequest, attachRuntimeToolsToDispatchRequest, buildGeneratedRuntimeToolGateOutput, createClient, createExternalTool, defaultWorkflow, deployWorkflow, evaluateGeneratedRuntimeToolProposal, gameWorkflow, getDefaultPlanPath, getLikelySupportingCandidatePaths, isDiscoveryToolName, isMarathonArtifactPath, isPreservationSensitiveTask, normalizeCandidatePath, parseFinalBuffer, parseSSEChunk, processStream, sanitizeTaskSlug, streamEvents };
5446
+ export { type Agent, type AgentApprovalCompleteEvent, type AgentApprovalStartEvent, type AgentCompleteEvent, type AgentErrorEvent, type AgentEvent, type AgentEventType, type AgentExecuteRequest, type AgentExecuteResponse, type AgentIterationCompleteEvent, type AgentIterationStartEvent, type AgentMediaEvent, type AgentMessage, type AgentPausedEvent, type AgentPingEvent, type AgentReflectionEvent, type AgentRuntimeToolDefinition, type AgentStartEvent, type AgentStreamCallbacks, type AgentSubagentConfig, type AgentToolCompleteEvent, type AgentToolDeltaEvent, type AgentToolInputCompleteEvent, type AgentToolInputDeltaEvent, type AgentToolStartEvent, type AgentTurnCompleteEvent, type AgentTurnDeltaEvent, type AgentTurnStartEvent, AgentsEndpoint, AnalyticsEndpoint, type ApiClient, type ApiKey, ApiKeysEndpoint, type ApiResponse, type ApplyGeneratedProposalOptions, type ApplyGeneratedProposalResult, type AttachRuntimeToolsOptions, type BaseAgentEvent, BatchBuilder, type BatchClient, type BatchListParams, type BatchOptions, type BatchRequest, type BatchResult, type BatchScheduleConfig, type BatchStatus, BatchesNamespace, type BuiltInTool, type BulkEditCondition, type BulkEditRequest, type BulkEditResponse, type BulkEditResult, ChatEndpoint, ClientBatchBuilder, type ClientConfig, type ClientConversation, ClientEvalBuilder, ClientFlowBuilder, type ClientToken, type ClientTokenConfig, type ClientTokenEnvironment, type ClientTokenVersionPin, ClientTokensEndpoint, type ClientWidgetTheme, type ConditionalStepConfig$1 as ConditionalStepConfig, type ContextErrorHandling, type ContextFallback, ContextTemplatesEndpoint, type CreateApiKeyRequest, type CreateClientTokenRequest, type CreateClientTokenResponse, type CreateFlowRequest, type CreateModelConfigRequest, type CreatePromptData, type CreatePromptRequest, type CreateProviderKeyRequest, type CreateRecordRequest, type CreateToolRequest, type CustomMCPServer, type CustomMCPServerAuth, type CustomToolConfig, type DeployCfSandboxRequest, type DeployCfSandboxResponse, type DeploySandboxRequest, type DeploySandboxResponse, type DispatchClient, DispatchEndpoint, type DispatchEnvironment, type DispatchOptions$1 as DispatchOptions, type DispatchRequest, type ErrorHandlingMode, EvalBuilder, type EvalClient, EvalEndpoint, type EvalListParams, type EvalOptions, type EvalRecord, type EvalRequest, type EvalResult, type EvalRunConfig, EvalRunner, type EvalStatus, EvalsNamespace, type ExecuteToolRequest, type ExecuteToolResponse, type ExternalToolConfig, type FallbackFailEvent, type FallbackStartEvent, type FallbackSuccessEvent, type FallbacksExhaustedEvent, type FallbacksInitiatedEvent, type FetchGitHubStepConfig$1 as FetchGitHubStepConfig, type FetchUrlStepConfig$1 as FetchUrlStepConfig, type FieldFormat, type FileContentPart, type Flow, type FlowAttachment, FlowBuilder, type FlowCompleteEvent, type FlowConfig$1 as FlowConfig, type FlowErrorEvent, type FlowFallback, type FlowPausedEvent, FlowResult, type FlowStartEvent, type FlowStep, FlowStepsEndpoint, type FlowSummary, type FlowToolConfig, FlowsEndpoint, FlowsNamespace, type GenerateEmbeddingStepConfig$1 as GenerateEmbeddingStepConfig, type GeneratedRuntimeToolGateDecision, type GeneratedRuntimeToolGateOptions, type ImageContentPart, type JSONSchema, type JsonArray, type JsonObject, type JsonPrimitive, type JsonValue, type ListConversationsResponse, type ListParams, type LocalToolConfig, type LocalToolDefinition, type LocalToolExecutionCompleteEvent, type LocalToolExecutionLoopSnapshotSlice, type LocalToolExecutionStartEvent, type Message$1 as Message, type MessageContent, type Metadata, type ModelConfig, ModelConfigsEndpoint, type ModelFallback, type ModelOverride, type ModelUsageDetail, type ModelUsageQueryParams, type ModelUsageResponse, type ModelUsageSummary, type ModelUsageTimeSeries, type PaginationResponse, type Prompt$1 as Prompt, type PromptErrorHandling, type PromptFallback, type PromptListParams, type PromptRunOptions, PromptRunner, type PromptStepConfig$1 as PromptStepConfig, PromptsEndpoint, PromptsNamespace, type ProviderApiKey, type ReasoningConfig, type ReasoningValue, type RecordConfig$1 as RecordConfig, type RecordFilter, type RecordFilterCondition, type RecordFilterGroup, type RecordFilterOperator, type RecordListParams, RecordsEndpoint, type RetrieveRecordStepConfig$1 as RetrieveRecordStepConfig, type RetryFallback, type RunTaskContextBudgetBreakdown, type RunTaskContextCompactionEvent, type RunTaskContextCompactionStrategy, type RunTaskContextNoticeEvent, type RunTaskContinuation, type RunTaskOnContextCompaction, type RunTaskOnContextNotice, type RunTaskOnSession, type RunTaskOptions, type RunTaskResult, type RunTaskResumeState, type RunTaskSessionSummary, type RunTaskState, type RunTaskStateSlice, type RunTaskStatus, type RunTaskToolTraceSlice, type RuntimeCustomToolConfig, type RuntimeExternalToolConfig, type RuntimeFlowToolConfig, type RuntimeLocalToolConfig, type RuntimeSubagentToolConfig, type RuntimeTool, type RuntimeToolConfig, Runtype, RuntypeApiError, RuntypeClient, type ConditionalStepConfig as RuntypeConditionalStepConfig, type RuntypeConfig, type FetchGitHubStepConfig as RuntypeFetchGitHubStepConfig, type FetchUrlStepConfig as RuntypeFetchUrlStepConfig, RuntypeFlowBuilder, type FlowConfig as RuntypeFlowConfig, type GenerateEmbeddingStepConfig as RuntypeGenerateEmbeddingStepConfig, type Message as RuntypeMessage, type ModelOverride$1 as RuntypeModelOverride, type Prompt as RuntypePrompt, type PromptStepConfig as RuntypePromptStepConfig, type RuntypeRecord, type RecordConfig as RuntypeRecordConfig, type RetrieveRecordStepConfig as RuntypeRetrieveRecordStepConfig, type SearchStepConfig as RuntypeSearchStepConfig, type SendEmailStepConfig as RuntypeSendEmailStepConfig, type SendEventStepConfig as RuntypeSendEventStepConfig, type SendStreamStepConfig as RuntypeSendStreamStepConfig, type SendTextStepConfig as RuntypeSendTextStepConfig, type SetVariableStepConfig as RuntypeSetVariableStepConfig, type TransformDataStepConfig as RuntypeTransformDataStepConfig, type UpsertFlowConfig as RuntypeUpsertFlowConfig, type UpsertRecordStepConfig as RuntypeUpsertRecordStepConfig, type VectorSearchStepConfig as RuntypeVectorSearchStepConfig, type WaitUntilStepConfig as RuntypeWaitUntilStepConfig, STEP_FIELD_REGISTRY, STEP_TYPE_TO_METHOD, type SearchStepConfig$1 as SearchStepConfig, type SendEmailStepConfig$1 as SendEmailStepConfig, type SendEventStepConfig$1 as SendEventStepConfig, type SendStreamStepConfig$1 as SendStreamStepConfig, type SendTextStepConfig$1 as SendTextStepConfig, type SetVariableStepConfig$1 as SetVariableStepConfig, type StepCompleteEvent, type StepDeltaEvent, type StepFallback, type StepFieldMeta, type StepStartEvent, type StepWaitingLocalEvent, type StreamCallbacks, type StreamEvent, type SubagentToolConfig, type TextContentPart, type Tool, type ToolConfig, type ToolExecution, type ToolsConfig, ToolsEndpoint, type TransformDataStepConfig$1 as TransformDataStepConfig, type UpdateClientTokenRequest, type UpdatePromptData, type UpdateProviderKeyRequest, type UpdateToolRequest, type UpsertFlowConfig$1 as UpsertFlowConfig, type UpsertOptions, type UpsertRecordStepConfig$1 as UpsertRecordStepConfig, type UserProfile, UsersEndpoint, type VectorSearchStepConfig$1 as VectorSearchStepConfig, type WaitUntilStepConfig$1 as WaitUntilStepConfig, type WorkflowContext, type WorkflowDefinition, type WorkflowPhase, applyGeneratedRuntimeToolProposalToDispatchRequest, attachRuntimeToolsToDispatchRequest, buildGeneratedRuntimeToolGateOutput, createClient, createExternalTool, defaultWorkflow, deployWorkflow, evaluateGeneratedRuntimeToolProposal, gameWorkflow, getDefaultPlanPath, getLikelySupportingCandidatePaths, isDiscoveryToolName, isMarathonArtifactPath, isPreservationSensitiveTask, normalizeCandidatePath, parseFinalBuffer, parseSSEChunk, processStream, sanitizeTaskSlug, streamEvents };