@runtypelabs/sdk 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -7453,6 +7453,103 @@ var FlowBuilder = class {
7453
7453
  return this;
7454
7454
  }
7455
7455
  // ============================================================================
7456
+ // Subagent Helpers
7457
+ // ============================================================================
7458
+ /**
7459
+ * Attach a subagent runtime tool to the most recent prompt step.
7460
+ *
7461
+ * A subagent tool spawns a focused child agent in its own context window
7462
+ * when the parent's model calls it. The child runs with a whitelisted tool
7463
+ * subset drawn from `allowedTools` (every entry must be available on the
7464
+ * parent step). The parent only sees the child's final result.
7465
+ *
7466
+ * Pass either `agentId` (for a saved agent in the same org) or `agent`
7467
+ * (an inline exported-agent JSON shape) — exactly one is required.
7468
+ *
7469
+ * @example
7470
+ * ```typescript
7471
+ * new FlowBuilder()
7472
+ * .createFlow({ name: 'Research' })
7473
+ * .prompt({ name: 'Plan', model: 'claude-sonnet-4-5', userPrompt: '...' })
7474
+ * .withSubagentTool('research_topic', {
7475
+ * agentId: 'agent_01h...',
7476
+ * allowedTools: ['builtin:exa_search'],
7477
+ * outputFormat: 'text',
7478
+ * })
7479
+ * ```
7480
+ */
7481
+ withSubagentTool(name, opts) {
7482
+ const lastStep = this.steps[this.steps.length - 1];
7483
+ if (!lastStep || lastStep.type !== "prompt") {
7484
+ throw new Error(
7485
+ "withSubagentTool() must be called after a .prompt() step \u2014 it attaches a runtime tool to the last prompt step."
7486
+ );
7487
+ }
7488
+ const config = {
7489
+ agentId: opts.agentId,
7490
+ agent: opts.agent,
7491
+ allowedTools: opts.allowedTools,
7492
+ maxTurns: opts.maxTurns,
7493
+ maxCost: opts.maxCost,
7494
+ timeoutMs: opts.timeoutMs,
7495
+ outputFormat: opts.outputFormat,
7496
+ inheritMessages: opts.inheritMessages,
7497
+ taskTemplate: opts.taskTemplate
7498
+ };
7499
+ const tool = {
7500
+ name,
7501
+ description: opts.description ?? `Spawn the ${name} subagent for a focused sub-task. Returns only the subagent's final result.`,
7502
+ toolType: "subagent",
7503
+ parametersSchema: opts.parametersSchema ?? {
7504
+ type: "object",
7505
+ properties: {
7506
+ task: {
7507
+ type: "string",
7508
+ description: "Self-contained task for the subagent. The subagent cannot see this conversation."
7509
+ }
7510
+ },
7511
+ required: ["task"]
7512
+ },
7513
+ config
7514
+ };
7515
+ const existingTools = lastStep.config.tools ?? {};
7516
+ const runtimeTools = [...existingTools.runtimeTools ?? [], tool];
7517
+ lastStep.config.tools = { ...existingTools, runtimeTools };
7518
+ return this;
7519
+ }
7520
+ /**
7521
+ * Enable agent-driven dynamic subagent spawning on the most recent prompt
7522
+ * step (surface C of the subagent design).
7523
+ *
7524
+ * When set, the API synthesizes a `spawn_subagent` tool the parent's model
7525
+ * can call at runtime to spin off a focused child agent. The child's tools
7526
+ * are drawn from `toolPool`, which must be a subset of the parent step's
7527
+ * resolved tools. The API validates pool entries and rejects escalation.
7528
+ *
7529
+ * @example
7530
+ * ```typescript
7531
+ * new FlowBuilder()
7532
+ * .createFlow({ name: 'Explore' })
7533
+ * .prompt({ name: 'Research', model: 'claude-sonnet-4-5', userPrompt: '...' })
7534
+ * .withSubagents({
7535
+ * toolPool: ['builtin:exa_search', 'mcp:*'],
7536
+ * maxSpawnsPerRun: 3,
7537
+ * allowNesting: false,
7538
+ * })
7539
+ * ```
7540
+ */
7541
+ withSubagents(opts) {
7542
+ const lastStep = this.steps[this.steps.length - 1];
7543
+ if (!lastStep || lastStep.type !== "prompt") {
7544
+ throw new Error(
7545
+ "withSubagents() must be called after a .prompt() step \u2014 it configures subagent spawning on the last prompt step."
7546
+ );
7547
+ }
7548
+ const existingTools = lastStep.config.tools ?? {};
7549
+ lastStep.config.tools = { ...existingTools, subagentConfig: opts };
7550
+ return this;
7551
+ }
7552
+ // ============================================================================
7456
7553
  // Build Method
7457
7554
  // ============================================================================
7458
7555
  /**
package/dist/index.d.cts CHANGED
@@ -367,14 +367,14 @@ interface Tool {
367
367
  organizationId?: string;
368
368
  name: string;
369
369
  description: string;
370
- toolType: 'flow' | 'custom' | 'external' | 'local';
370
+ toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
371
371
  parametersSchema: JSONSchema;
372
372
  config: ToolConfig;
373
373
  isActive: boolean;
374
374
  createdAt: string;
375
375
  updatedAt: string;
376
376
  }
377
- type ToolConfig = FlowToolConfig | CustomToolConfig | ExternalToolConfig | LocalToolConfig;
377
+ type ToolConfig = FlowToolConfig | CustomToolConfig | ExternalToolConfig | LocalToolConfig | SubagentToolConfig;
378
378
  interface FlowToolConfig {
379
379
  flowId: string;
380
380
  parameterMapping: Record<string, string>;
@@ -395,6 +395,35 @@ interface ExternalToolConfig {
395
395
  interface LocalToolConfig {
396
396
  [key: string]: JsonValue;
397
397
  }
398
+ /**
399
+ * Subagent tool configuration (surfaces A + B in the subagent design plan).
400
+ *
401
+ * Surface A — saved subagent: set `agentId` to a saved agent in the same org.
402
+ * Surface B — inline subagent: set `agent` to a full exported agent JSON shape
403
+ * validated by the API at dispatch time.
404
+ *
405
+ * Exactly one of `agentId` / `agent` must be present; the API validator enforces this.
406
+ */
407
+ interface SubagentToolConfig {
408
+ /** (A) Saved agent — org-scoped, ownership-checked at dispatch. */
409
+ agentId?: string;
410
+ /** (B) Inline agent definition. Full exported-agent JSON shape. */
411
+ agent?: JsonObject;
412
+ /** Tool subset granted to the child. REQUIRED. Must be a subset of the parent's resolved tools. */
413
+ allowedTools: string[];
414
+ /** Override the child agent's loop maxTurns. Default 5. */
415
+ maxTurns?: number;
416
+ /** Optional cap on the child's running cost. Default: inherits parent budget. */
417
+ maxCost?: number;
418
+ /** Per-invocation timeout in ms. Default 300_000 (5 min). */
419
+ timeoutMs?: number;
420
+ /** How the child's result is returned. Default 'text'. */
421
+ outputFormat?: 'text' | 'json' | 'last_message';
422
+ /** If true, prepend the parent's current messages to the child's initial context. Default false. */
423
+ inheritMessages?: boolean;
424
+ /** Optional template rendering the child's initial user message from the tool-call `parameters`. */
425
+ taskTemplate?: string;
426
+ }
398
427
  interface BuiltInTool {
399
428
  id: string;
400
429
  name: string;
@@ -421,7 +450,7 @@ interface ToolExecution {
421
450
  interface CreateToolRequest {
422
451
  name: string;
423
452
  description: string;
424
- toolType: 'flow' | 'custom' | 'external';
453
+ toolType: 'flow' | 'custom' | 'external' | 'subagent';
425
454
  parametersSchema: JSONSchema;
426
455
  config: ToolConfig;
427
456
  }
@@ -555,14 +584,14 @@ interface ModelUsageResponse {
555
584
  interface RuntimeTool {
556
585
  name: string;
557
586
  description: string;
558
- toolType: 'flow' | 'custom' | 'external' | 'local';
587
+ toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
559
588
  parametersSchema: JSONSchema;
560
589
  config?: RuntimeToolConfig;
561
590
  }
562
591
  /**
563
592
  * Config options for runtime tools
564
593
  */
565
- type RuntimeToolConfig = RuntimeFlowToolConfig | RuntimeCustomToolConfig | RuntimeExternalToolConfig | RuntimeLocalToolConfig;
594
+ type RuntimeToolConfig = RuntimeFlowToolConfig | RuntimeCustomToolConfig | RuntimeExternalToolConfig | RuntimeLocalToolConfig | RuntimeSubagentToolConfig;
566
595
  interface RuntimeLocalToolConfig {
567
596
  [key: string]: JsonValue;
568
597
  }
@@ -583,6 +612,41 @@ interface RuntimeExternalToolConfig {
583
612
  headers?: Record<string, string>;
584
613
  body?: string;
585
614
  }
615
+ /**
616
+ * Runtime subagent tool config — inline form used when passing a subagent
617
+ * tool via `runtimeTools[]` rather than saving it.
618
+ *
619
+ * Structurally identical to `SubagentToolConfig`: the API validates the same
620
+ * fields on both paths, so keeping a single source of truth avoids silent
621
+ * divergence if a field is added on one side only. Kept as a named alias for
622
+ * readability at call sites that deal with runtime-only tools.
623
+ */
624
+ type RuntimeSubagentToolConfig = SubagentToolConfig;
625
+ /**
626
+ * Opt-in configuration for agent-driven dynamic subagent spawning (surface C
627
+ * of the subagent design).
628
+ *
629
+ * When present on a prompt step's `tools.subagentConfig`, the API synthesizes
630
+ * a `spawn_subagent` tool that the parent LLM can call at runtime to spin off
631
+ * a focused child agent. The child's tools are drawn from `toolPool`, which
632
+ * must be a subset of the parent step's resolved tools.
633
+ */
634
+ interface AgentSubagentConfig {
635
+ /** Pool of tool IDs the parent is permitted to grant. Supports wildcards (e.g. `mcp:*`). */
636
+ toolPool: string[];
637
+ /** Default iteration cap for spawned subagents. Default 5. */
638
+ defaultMaxTurns?: number;
639
+ /** Hard ceiling a subagent may request via maxTurns. Default 10. */
640
+ maxTurnsLimit?: number;
641
+ /** Total spawns per top-level parent run. Default 5. */
642
+ maxSpawnsPerRun?: number;
643
+ /** Default model for spawned subagents. Defaults to parent's model. */
644
+ defaultModel?: string;
645
+ /** Whether spawned subagents can themselves spawn. Default false. */
646
+ allowNesting?: boolean;
647
+ /** Default per-spawn timeout. Default 300_000. */
648
+ defaultTimeoutMs?: number;
649
+ }
586
650
  /**
587
651
  * Tools configuration for prompt steps.
588
652
  * Supports both saved tools (by ID) and runtime tools (inline definitions).
@@ -677,6 +741,12 @@ interface ToolsConfig {
677
741
  toolIds?: string[];
678
742
  /** Inline runtime tool definitions (not persisted) */
679
743
  runtimeTools?: RuntimeTool[];
744
+ /**
745
+ * Opt-in agent-driven subagent spawning. When set, the API synthesizes a
746
+ * `spawn_subagent` tool that the step's model can call at runtime. Pool
747
+ * entries must be a subset of the parent step's resolved tools.
748
+ */
749
+ subagentConfig?: AgentSubagentConfig;
680
750
  /**
681
751
  * Custom MCP servers with credentials passed at runtime.
682
752
  * Maximum 5 servers per step.
@@ -1425,6 +1495,64 @@ declare class FlowBuilder {
1425
1495
  * Add a fetch GitHub step
1426
1496
  */
1427
1497
  fetchGitHub(config: FetchGitHubStepConfig$1): this;
1498
+ /**
1499
+ * Attach a subagent runtime tool to the most recent prompt step.
1500
+ *
1501
+ * A subagent tool spawns a focused child agent in its own context window
1502
+ * when the parent's model calls it. The child runs with a whitelisted tool
1503
+ * subset drawn from `allowedTools` (every entry must be available on the
1504
+ * parent step). The parent only sees the child's final result.
1505
+ *
1506
+ * Pass either `agentId` (for a saved agent in the same org) or `agent`
1507
+ * (an inline exported-agent JSON shape) — exactly one is required.
1508
+ *
1509
+ * @example
1510
+ * ```typescript
1511
+ * new FlowBuilder()
1512
+ * .createFlow({ name: 'Research' })
1513
+ * .prompt({ name: 'Plan', model: 'claude-sonnet-4-5', userPrompt: '...' })
1514
+ * .withSubagentTool('research_topic', {
1515
+ * agentId: 'agent_01h...',
1516
+ * allowedTools: ['builtin:exa_search'],
1517
+ * outputFormat: 'text',
1518
+ * })
1519
+ * ```
1520
+ */
1521
+ withSubagentTool(name: string, opts: {
1522
+ description?: string;
1523
+ agentId?: string;
1524
+ agent?: JsonObject;
1525
+ allowedTools: string[];
1526
+ parametersSchema?: JSONSchema;
1527
+ maxTurns?: number;
1528
+ maxCost?: number;
1529
+ timeoutMs?: number;
1530
+ outputFormat?: 'text' | 'json' | 'last_message';
1531
+ inheritMessages?: boolean;
1532
+ taskTemplate?: string;
1533
+ }): this;
1534
+ /**
1535
+ * Enable agent-driven dynamic subagent spawning on the most recent prompt
1536
+ * step (surface C of the subagent design).
1537
+ *
1538
+ * When set, the API synthesizes a `spawn_subagent` tool the parent's model
1539
+ * can call at runtime to spin off a focused child agent. The child's tools
1540
+ * are drawn from `toolPool`, which must be a subset of the parent step's
1541
+ * resolved tools. The API validates pool entries and rejects escalation.
1542
+ *
1543
+ * @example
1544
+ * ```typescript
1545
+ * new FlowBuilder()
1546
+ * .createFlow({ name: 'Explore' })
1547
+ * .prompt({ name: 'Research', model: 'claude-sonnet-4-5', userPrompt: '...' })
1548
+ * .withSubagents({
1549
+ * toolPool: ['builtin:exa_search', 'mcp:*'],
1550
+ * maxSpawnsPerRun: 3,
1551
+ * allowNesting: false,
1552
+ * })
1553
+ * ```
1554
+ */
1555
+ withSubagents(opts: AgentSubagentConfig): this;
1428
1556
  /**
1429
1557
  * Build the final dispatch request configuration
1430
1558
  */
@@ -4065,7 +4193,7 @@ interface AgentToolStartEvent extends BaseAgentEvent {
4065
4193
  iteration: number;
4066
4194
  toolCallId: string;
4067
4195
  toolName: string;
4068
- toolType: 'flow' | 'mcp' | 'builtin' | 'custom' | 'external';
4196
+ toolType: 'flow' | 'mcp' | 'builtin' | 'custom' | 'external' | 'advisor' | 'subagent';
4069
4197
  parameters?: Record<string, unknown>;
4070
4198
  }
4071
4199
  /**
@@ -4283,7 +4411,7 @@ interface LocalToolDefinition {
4283
4411
  interface AgentRuntimeToolDefinition {
4284
4412
  name: string;
4285
4413
  description: string;
4286
- toolType: 'flow' | 'custom' | 'external' | 'local';
4414
+ toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
4287
4415
  parametersSchema: Record<string, unknown>;
4288
4416
  config?: Record<string, unknown>;
4289
4417
  }
@@ -5518,4 +5646,4 @@ declare function getLikelySupportingCandidatePaths(bestCandidatePath: string | u
5518
5646
  declare function getDefaultPlanPath(taskName: string): string;
5519
5647
  declare function sanitizeTaskSlug(taskName: string): string;
5520
5648
 
5521
- export { type Agent, type AgentCompleteEvent, type AgentErrorEvent, type AgentEvent, type AgentEventType, type AgentExecuteRequest, type AgentExecuteResponse, type AgentIterationCompleteEvent, type AgentIterationStartEvent, type AgentMessage, type AgentPausedEvent, type AgentPingEvent, type AgentReflectionEvent, type AgentRuntimeToolDefinition, type AgentStartEvent, type AgentStreamCallbacks, 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 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 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, 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 StepChunkEvent, type StepCompleteEvent, type StepDeltaEvent, type StepFallback, type StepStartEvent, type StepWaitingLocalEvent, type StreamCallbacks, type StreamEvent, 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$2 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 };
5649
+ export { type Agent, type AgentCompleteEvent, type AgentErrorEvent, type AgentEvent, type AgentEventType, type AgentExecuteRequest, type AgentExecuteResponse, type AgentIterationCompleteEvent, type AgentIterationStartEvent, 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 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, 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 StepChunkEvent, type StepCompleteEvent, type StepDeltaEvent, type StepFallback, 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$2 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 };
package/dist/index.d.ts CHANGED
@@ -367,14 +367,14 @@ interface Tool {
367
367
  organizationId?: string;
368
368
  name: string;
369
369
  description: string;
370
- toolType: 'flow' | 'custom' | 'external' | 'local';
370
+ toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
371
371
  parametersSchema: JSONSchema;
372
372
  config: ToolConfig;
373
373
  isActive: boolean;
374
374
  createdAt: string;
375
375
  updatedAt: string;
376
376
  }
377
- type ToolConfig = FlowToolConfig | CustomToolConfig | ExternalToolConfig | LocalToolConfig;
377
+ type ToolConfig = FlowToolConfig | CustomToolConfig | ExternalToolConfig | LocalToolConfig | SubagentToolConfig;
378
378
  interface FlowToolConfig {
379
379
  flowId: string;
380
380
  parameterMapping: Record<string, string>;
@@ -395,6 +395,35 @@ interface ExternalToolConfig {
395
395
  interface LocalToolConfig {
396
396
  [key: string]: JsonValue;
397
397
  }
398
+ /**
399
+ * Subagent tool configuration (surfaces A + B in the subagent design plan).
400
+ *
401
+ * Surface A — saved subagent: set `agentId` to a saved agent in the same org.
402
+ * Surface B — inline subagent: set `agent` to a full exported agent JSON shape
403
+ * validated by the API at dispatch time.
404
+ *
405
+ * Exactly one of `agentId` / `agent` must be present; the API validator enforces this.
406
+ */
407
+ interface SubagentToolConfig {
408
+ /** (A) Saved agent — org-scoped, ownership-checked at dispatch. */
409
+ agentId?: string;
410
+ /** (B) Inline agent definition. Full exported-agent JSON shape. */
411
+ agent?: JsonObject;
412
+ /** Tool subset granted to the child. REQUIRED. Must be a subset of the parent's resolved tools. */
413
+ allowedTools: string[];
414
+ /** Override the child agent's loop maxTurns. Default 5. */
415
+ maxTurns?: number;
416
+ /** Optional cap on the child's running cost. Default: inherits parent budget. */
417
+ maxCost?: number;
418
+ /** Per-invocation timeout in ms. Default 300_000 (5 min). */
419
+ timeoutMs?: number;
420
+ /** How the child's result is returned. Default 'text'. */
421
+ outputFormat?: 'text' | 'json' | 'last_message';
422
+ /** If true, prepend the parent's current messages to the child's initial context. Default false. */
423
+ inheritMessages?: boolean;
424
+ /** Optional template rendering the child's initial user message from the tool-call `parameters`. */
425
+ taskTemplate?: string;
426
+ }
398
427
  interface BuiltInTool {
399
428
  id: string;
400
429
  name: string;
@@ -421,7 +450,7 @@ interface ToolExecution {
421
450
  interface CreateToolRequest {
422
451
  name: string;
423
452
  description: string;
424
- toolType: 'flow' | 'custom' | 'external';
453
+ toolType: 'flow' | 'custom' | 'external' | 'subagent';
425
454
  parametersSchema: JSONSchema;
426
455
  config: ToolConfig;
427
456
  }
@@ -555,14 +584,14 @@ interface ModelUsageResponse {
555
584
  interface RuntimeTool {
556
585
  name: string;
557
586
  description: string;
558
- toolType: 'flow' | 'custom' | 'external' | 'local';
587
+ toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
559
588
  parametersSchema: JSONSchema;
560
589
  config?: RuntimeToolConfig;
561
590
  }
562
591
  /**
563
592
  * Config options for runtime tools
564
593
  */
565
- type RuntimeToolConfig = RuntimeFlowToolConfig | RuntimeCustomToolConfig | RuntimeExternalToolConfig | RuntimeLocalToolConfig;
594
+ type RuntimeToolConfig = RuntimeFlowToolConfig | RuntimeCustomToolConfig | RuntimeExternalToolConfig | RuntimeLocalToolConfig | RuntimeSubagentToolConfig;
566
595
  interface RuntimeLocalToolConfig {
567
596
  [key: string]: JsonValue;
568
597
  }
@@ -583,6 +612,41 @@ interface RuntimeExternalToolConfig {
583
612
  headers?: Record<string, string>;
584
613
  body?: string;
585
614
  }
615
+ /**
616
+ * Runtime subagent tool config — inline form used when passing a subagent
617
+ * tool via `runtimeTools[]` rather than saving it.
618
+ *
619
+ * Structurally identical to `SubagentToolConfig`: the API validates the same
620
+ * fields on both paths, so keeping a single source of truth avoids silent
621
+ * divergence if a field is added on one side only. Kept as a named alias for
622
+ * readability at call sites that deal with runtime-only tools.
623
+ */
624
+ type RuntimeSubagentToolConfig = SubagentToolConfig;
625
+ /**
626
+ * Opt-in configuration for agent-driven dynamic subagent spawning (surface C
627
+ * of the subagent design).
628
+ *
629
+ * When present on a prompt step's `tools.subagentConfig`, the API synthesizes
630
+ * a `spawn_subagent` tool that the parent LLM can call at runtime to spin off
631
+ * a focused child agent. The child's tools are drawn from `toolPool`, which
632
+ * must be a subset of the parent step's resolved tools.
633
+ */
634
+ interface AgentSubagentConfig {
635
+ /** Pool of tool IDs the parent is permitted to grant. Supports wildcards (e.g. `mcp:*`). */
636
+ toolPool: string[];
637
+ /** Default iteration cap for spawned subagents. Default 5. */
638
+ defaultMaxTurns?: number;
639
+ /** Hard ceiling a subagent may request via maxTurns. Default 10. */
640
+ maxTurnsLimit?: number;
641
+ /** Total spawns per top-level parent run. Default 5. */
642
+ maxSpawnsPerRun?: number;
643
+ /** Default model for spawned subagents. Defaults to parent's model. */
644
+ defaultModel?: string;
645
+ /** Whether spawned subagents can themselves spawn. Default false. */
646
+ allowNesting?: boolean;
647
+ /** Default per-spawn timeout. Default 300_000. */
648
+ defaultTimeoutMs?: number;
649
+ }
586
650
  /**
587
651
  * Tools configuration for prompt steps.
588
652
  * Supports both saved tools (by ID) and runtime tools (inline definitions).
@@ -677,6 +741,12 @@ interface ToolsConfig {
677
741
  toolIds?: string[];
678
742
  /** Inline runtime tool definitions (not persisted) */
679
743
  runtimeTools?: RuntimeTool[];
744
+ /**
745
+ * Opt-in agent-driven subagent spawning. When set, the API synthesizes a
746
+ * `spawn_subagent` tool that the step's model can call at runtime. Pool
747
+ * entries must be a subset of the parent step's resolved tools.
748
+ */
749
+ subagentConfig?: AgentSubagentConfig;
680
750
  /**
681
751
  * Custom MCP servers with credentials passed at runtime.
682
752
  * Maximum 5 servers per step.
@@ -1425,6 +1495,64 @@ declare class FlowBuilder {
1425
1495
  * Add a fetch GitHub step
1426
1496
  */
1427
1497
  fetchGitHub(config: FetchGitHubStepConfig$1): this;
1498
+ /**
1499
+ * Attach a subagent runtime tool to the most recent prompt step.
1500
+ *
1501
+ * A subagent tool spawns a focused child agent in its own context window
1502
+ * when the parent's model calls it. The child runs with a whitelisted tool
1503
+ * subset drawn from `allowedTools` (every entry must be available on the
1504
+ * parent step). The parent only sees the child's final result.
1505
+ *
1506
+ * Pass either `agentId` (for a saved agent in the same org) or `agent`
1507
+ * (an inline exported-agent JSON shape) — exactly one is required.
1508
+ *
1509
+ * @example
1510
+ * ```typescript
1511
+ * new FlowBuilder()
1512
+ * .createFlow({ name: 'Research' })
1513
+ * .prompt({ name: 'Plan', model: 'claude-sonnet-4-5', userPrompt: '...' })
1514
+ * .withSubagentTool('research_topic', {
1515
+ * agentId: 'agent_01h...',
1516
+ * allowedTools: ['builtin:exa_search'],
1517
+ * outputFormat: 'text',
1518
+ * })
1519
+ * ```
1520
+ */
1521
+ withSubagentTool(name: string, opts: {
1522
+ description?: string;
1523
+ agentId?: string;
1524
+ agent?: JsonObject;
1525
+ allowedTools: string[];
1526
+ parametersSchema?: JSONSchema;
1527
+ maxTurns?: number;
1528
+ maxCost?: number;
1529
+ timeoutMs?: number;
1530
+ outputFormat?: 'text' | 'json' | 'last_message';
1531
+ inheritMessages?: boolean;
1532
+ taskTemplate?: string;
1533
+ }): this;
1534
+ /**
1535
+ * Enable agent-driven dynamic subagent spawning on the most recent prompt
1536
+ * step (surface C of the subagent design).
1537
+ *
1538
+ * When set, the API synthesizes a `spawn_subagent` tool the parent's model
1539
+ * can call at runtime to spin off a focused child agent. The child's tools
1540
+ * are drawn from `toolPool`, which must be a subset of the parent step's
1541
+ * resolved tools. The API validates pool entries and rejects escalation.
1542
+ *
1543
+ * @example
1544
+ * ```typescript
1545
+ * new FlowBuilder()
1546
+ * .createFlow({ name: 'Explore' })
1547
+ * .prompt({ name: 'Research', model: 'claude-sonnet-4-5', userPrompt: '...' })
1548
+ * .withSubagents({
1549
+ * toolPool: ['builtin:exa_search', 'mcp:*'],
1550
+ * maxSpawnsPerRun: 3,
1551
+ * allowNesting: false,
1552
+ * })
1553
+ * ```
1554
+ */
1555
+ withSubagents(opts: AgentSubagentConfig): this;
1428
1556
  /**
1429
1557
  * Build the final dispatch request configuration
1430
1558
  */
@@ -4065,7 +4193,7 @@ interface AgentToolStartEvent extends BaseAgentEvent {
4065
4193
  iteration: number;
4066
4194
  toolCallId: string;
4067
4195
  toolName: string;
4068
- toolType: 'flow' | 'mcp' | 'builtin' | 'custom' | 'external';
4196
+ toolType: 'flow' | 'mcp' | 'builtin' | 'custom' | 'external' | 'advisor' | 'subagent';
4069
4197
  parameters?: Record<string, unknown>;
4070
4198
  }
4071
4199
  /**
@@ -4283,7 +4411,7 @@ interface LocalToolDefinition {
4283
4411
  interface AgentRuntimeToolDefinition {
4284
4412
  name: string;
4285
4413
  description: string;
4286
- toolType: 'flow' | 'custom' | 'external' | 'local';
4414
+ toolType: 'flow' | 'custom' | 'external' | 'local' | 'subagent';
4287
4415
  parametersSchema: Record<string, unknown>;
4288
4416
  config?: Record<string, unknown>;
4289
4417
  }
@@ -5518,4 +5646,4 @@ declare function getLikelySupportingCandidatePaths(bestCandidatePath: string | u
5518
5646
  declare function getDefaultPlanPath(taskName: string): string;
5519
5647
  declare function sanitizeTaskSlug(taskName: string): string;
5520
5648
 
5521
- export { type Agent, type AgentCompleteEvent, type AgentErrorEvent, type AgentEvent, type AgentEventType, type AgentExecuteRequest, type AgentExecuteResponse, type AgentIterationCompleteEvent, type AgentIterationStartEvent, type AgentMessage, type AgentPausedEvent, type AgentPingEvent, type AgentReflectionEvent, type AgentRuntimeToolDefinition, type AgentStartEvent, type AgentStreamCallbacks, 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 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 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, 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 StepChunkEvent, type StepCompleteEvent, type StepDeltaEvent, type StepFallback, type StepStartEvent, type StepWaitingLocalEvent, type StreamCallbacks, type StreamEvent, 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$2 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 };
5649
+ export { type Agent, type AgentCompleteEvent, type AgentErrorEvent, type AgentEvent, type AgentEventType, type AgentExecuteRequest, type AgentExecuteResponse, type AgentIterationCompleteEvent, type AgentIterationStartEvent, 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 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, 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 StepChunkEvent, type StepCompleteEvent, type StepDeltaEvent, type StepFallback, 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$2 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 };
package/dist/index.mjs CHANGED
@@ -7383,6 +7383,103 @@ var FlowBuilder = class {
7383
7383
  return this;
7384
7384
  }
7385
7385
  // ============================================================================
7386
+ // Subagent Helpers
7387
+ // ============================================================================
7388
+ /**
7389
+ * Attach a subagent runtime tool to the most recent prompt step.
7390
+ *
7391
+ * A subagent tool spawns a focused child agent in its own context window
7392
+ * when the parent's model calls it. The child runs with a whitelisted tool
7393
+ * subset drawn from `allowedTools` (every entry must be available on the
7394
+ * parent step). The parent only sees the child's final result.
7395
+ *
7396
+ * Pass either `agentId` (for a saved agent in the same org) or `agent`
7397
+ * (an inline exported-agent JSON shape) — exactly one is required.
7398
+ *
7399
+ * @example
7400
+ * ```typescript
7401
+ * new FlowBuilder()
7402
+ * .createFlow({ name: 'Research' })
7403
+ * .prompt({ name: 'Plan', model: 'claude-sonnet-4-5', userPrompt: '...' })
7404
+ * .withSubagentTool('research_topic', {
7405
+ * agentId: 'agent_01h...',
7406
+ * allowedTools: ['builtin:exa_search'],
7407
+ * outputFormat: 'text',
7408
+ * })
7409
+ * ```
7410
+ */
7411
+ withSubagentTool(name, opts) {
7412
+ const lastStep = this.steps[this.steps.length - 1];
7413
+ if (!lastStep || lastStep.type !== "prompt") {
7414
+ throw new Error(
7415
+ "withSubagentTool() must be called after a .prompt() step \u2014 it attaches a runtime tool to the last prompt step."
7416
+ );
7417
+ }
7418
+ const config = {
7419
+ agentId: opts.agentId,
7420
+ agent: opts.agent,
7421
+ allowedTools: opts.allowedTools,
7422
+ maxTurns: opts.maxTurns,
7423
+ maxCost: opts.maxCost,
7424
+ timeoutMs: opts.timeoutMs,
7425
+ outputFormat: opts.outputFormat,
7426
+ inheritMessages: opts.inheritMessages,
7427
+ taskTemplate: opts.taskTemplate
7428
+ };
7429
+ const tool = {
7430
+ name,
7431
+ description: opts.description ?? `Spawn the ${name} subagent for a focused sub-task. Returns only the subagent's final result.`,
7432
+ toolType: "subagent",
7433
+ parametersSchema: opts.parametersSchema ?? {
7434
+ type: "object",
7435
+ properties: {
7436
+ task: {
7437
+ type: "string",
7438
+ description: "Self-contained task for the subagent. The subagent cannot see this conversation."
7439
+ }
7440
+ },
7441
+ required: ["task"]
7442
+ },
7443
+ config
7444
+ };
7445
+ const existingTools = lastStep.config.tools ?? {};
7446
+ const runtimeTools = [...existingTools.runtimeTools ?? [], tool];
7447
+ lastStep.config.tools = { ...existingTools, runtimeTools };
7448
+ return this;
7449
+ }
7450
+ /**
7451
+ * Enable agent-driven dynamic subagent spawning on the most recent prompt
7452
+ * step (surface C of the subagent design).
7453
+ *
7454
+ * When set, the API synthesizes a `spawn_subagent` tool the parent's model
7455
+ * can call at runtime to spin off a focused child agent. The child's tools
7456
+ * are drawn from `toolPool`, which must be a subset of the parent step's
7457
+ * resolved tools. The API validates pool entries and rejects escalation.
7458
+ *
7459
+ * @example
7460
+ * ```typescript
7461
+ * new FlowBuilder()
7462
+ * .createFlow({ name: 'Explore' })
7463
+ * .prompt({ name: 'Research', model: 'claude-sonnet-4-5', userPrompt: '...' })
7464
+ * .withSubagents({
7465
+ * toolPool: ['builtin:exa_search', 'mcp:*'],
7466
+ * maxSpawnsPerRun: 3,
7467
+ * allowNesting: false,
7468
+ * })
7469
+ * ```
7470
+ */
7471
+ withSubagents(opts) {
7472
+ const lastStep = this.steps[this.steps.length - 1];
7473
+ if (!lastStep || lastStep.type !== "prompt") {
7474
+ throw new Error(
7475
+ "withSubagents() must be called after a .prompt() step \u2014 it configures subagent spawning on the last prompt step."
7476
+ );
7477
+ }
7478
+ const existingTools = lastStep.config.tools ?? {};
7479
+ lastStep.config.tools = { ...existingTools, subagentConfig: opts };
7480
+ return this;
7481
+ }
7482
+ // ============================================================================
7386
7483
  // Build Method
7387
7484
  // ============================================================================
7388
7485
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runtypelabs/sdk",
3
- "version": "1.16.0",
3
+ "version": "1.17.0",
4
4
  "type": "module",
5
5
  "description": "TypeScript SDK for the Runtype API with fluent methods. Use it to quickly realize AI products, agents, and workflows.",
6
6
  "main": "dist/index.cjs",