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