@runtypelabs/sdk 2.0.1 → 2.1.1

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
@@ -7808,6 +7808,10 @@ function createExternalTool(config) {
7808
7808
  function isObjectRecord(value) {
7809
7809
  return typeof value === "object" && value !== null;
7810
7810
  }
7811
+ function hasToolEntryShape(value) {
7812
+ if (!isObjectRecord(value)) return false;
7813
+ return typeof value.execute === "function" && typeof value.description === "string" && typeof value.parametersSchema === "object" && value.parametersSchema !== null;
7814
+ }
7811
7815
  function isPausedLocalActionResult(value) {
7812
7816
  if (!isObjectRecord(value) || value.status !== "paused") {
7813
7817
  return false;
@@ -7867,7 +7871,7 @@ var RuntypeClient2 = class {
7867
7871
  return new ClientFlowBuilder(
7868
7872
  {
7869
7873
  dispatch: (config) => this.dispatch.executeStream(config),
7870
- runWithLocalTools: (config, tools) => this.runWithLocalTools(config, tools)
7874
+ runWithLocalTools: (config, tools, callbacks, opts) => this.runWithLocalTools(config, tools, callbacks, opts)
7871
7875
  },
7872
7876
  name
7873
7877
  );
@@ -7878,18 +7882,26 @@ var RuntypeClient2 = class {
7878
7882
  clearApiKey() {
7879
7883
  delete this.headers.Authorization;
7880
7884
  }
7881
- /**
7882
- * Run a flow with client-side tools (automatic pause/resume loop)
7883
- *
7884
- * @param request - The dispatch request configuration
7885
- * @param clientTools - Map of tool names to async functions that execute the tool logic
7886
- * @param callbacks - Optional callbacks for streaming events
7887
- * @returns The final result of the flow execution or summary if streaming
7888
- */
7889
- async runWithLocalTools(request, localTools, callbacks) {
7885
+ async runWithLocalTools(request, localTools, arg3, arg4) {
7886
+ const isOptionsObject = (val) => typeof val === "object" && val !== null && "scope" in val;
7887
+ const callbacks = isOptionsObject(arg3) ? void 0 : arg3;
7888
+ const options = (isOptionsObject(arg3) ? arg3 : arg4) ?? {};
7889
+ const scope = options.scope ?? "session";
7890
7890
  const isStreaming = !!callbacks;
7891
+ const derivedClientTools = scope === "turn" ? Object.entries(localTools).filter(
7892
+ (entry) => hasToolEntryShape(entry[1])
7893
+ ).map(([name, entry]) => ({
7894
+ name,
7895
+ description: entry.description,
7896
+ parametersSchema: entry.parametersSchema,
7897
+ ...entry.origin ? { origin: entry.origin } : {},
7898
+ ...entry.pageOrigin ? { pageOrigin: entry.pageOrigin } : {}
7899
+ })) : [];
7891
7900
  const modifiedRequest = {
7892
7901
  ...request,
7902
+ ...derivedClientTools.length > 0 ? {
7903
+ clientTools: [...request.clientTools ?? [], ...derivedClientTools]
7904
+ } : {},
7893
7905
  options: {
7894
7906
  ...request.options || {},
7895
7907
  streamResponse: isStreaming
@@ -7991,11 +8003,21 @@ var RuntypeClient2 = class {
7991
8003
  }
7992
8004
  if (isPausedLocalActionResult(result) && result.pausedReason?.type === "local_action") {
7993
8005
  const { toolName, parameters, executionId } = result.pausedReason;
7994
- if (!localTools[toolName]) {
8006
+ const BARE_NAME_NAMESPACES = ["webmcp:"];
8007
+ const lookupCandidates = [toolName];
8008
+ for (const ns of BARE_NAME_NAMESPACES) {
8009
+ if (toolName.startsWith(ns)) {
8010
+ lookupCandidates.push(toolName.slice(ns.length));
8011
+ }
8012
+ }
8013
+ const matchedKey = lookupCandidates.find((key) => localTools[key]);
8014
+ const toolEntry = matchedKey ? localTools[matchedKey] : void 0;
8015
+ if (!toolEntry) {
7995
8016
  throw new Error(`Local tool "${toolName}" required but not provided in localTools map`);
7996
8017
  }
8018
+ const handler = hasToolEntryShape(toolEntry) ? toolEntry.execute : toolEntry;
7997
8019
  try {
7998
- const toolResult = await localTools[toolName](parameters);
8020
+ const toolResult = await handler(parameters);
7999
8021
  const resumeData = {
8000
8022
  executionId,
8001
8023
  toolOutputs: { [toolName]: toolResult },
package/dist/index.d.cts CHANGED
@@ -973,9 +973,14 @@ interface DispatchClient {
973
973
  * @param config - The dispatch request configuration
974
974
  * @param localTools - Map of tool names to async functions that execute the tool logic
975
975
  * @param callbacks - Optional callbacks for streaming events
976
+ * @param options - Optional behavior tweaks (e.g. `{ scope: 'turn' }` to
977
+ * inject the schema as `dispatch.clientTools[]` instead of the legacy
978
+ * step-level `runtimeTools` path)
976
979
  * @returns The final result of the flow execution or summary if streaming
977
980
  */
978
- runWithLocalTools(config: DispatchRequest, localTools: Record<string, (args: any) => Promise<any>>, callbacks?: StreamCallbacks): Promise<FlowResult | FlowSummary>;
981
+ runWithLocalTools(config: DispatchRequest, localTools: Record<string, (args: any) => Promise<any>>, callbacks?: StreamCallbacks, options?: {
982
+ scope?: 'turn' | 'session';
983
+ }): Promise<FlowResult | FlowSummary>;
979
984
  dispatch(config: DispatchRequest): Promise<Response>;
980
985
  }
981
986
  /**
@@ -1389,6 +1394,35 @@ interface UpsertOptions {
1389
1394
  * Environment type for dispatch requests
1390
1395
  */
1391
1396
  type DispatchEnvironment = 'development' | 'production';
1397
+ /**
1398
+ * Inline tool definition that executes on the dispatching client.
1399
+ *
1400
+ * The wire shape matches the server-side `InlineClientToolSchema` in
1401
+ * `@runtypelabs/shared/api-schemas/dispatch`. Two flavors share the wire:
1402
+ *
1403
+ * - `origin: 'sdk'` (default) — caller-defined locals. No name-prefix rule.
1404
+ * - `origin: 'webmcp'` — page-discovered tools via
1405
+ * `document.modelContext.registerTool(...)`. The server applies a
1406
+ * `webmcp:` name prefix before merge so audit logs are filterable.
1407
+ *
1408
+ * Use {@link runWithLocalTools} with `{ scope: 'turn' }` to ship these in
1409
+ * the dispatch envelope; with `{ scope: 'session' }` (default) the SDK
1410
+ * still injects them as step-level runtimeTools for back-compat.
1411
+ */
1412
+ interface ClientToolDefinition {
1413
+ name: string;
1414
+ description: string;
1415
+ /**
1416
+ * JSON Schema for the tool's input. Type is intentionally
1417
+ * `Record<string, unknown>` (matching {@link LocalToolDefinition} in
1418
+ * `endpoints.ts`) so callers can pass JSON Schema fragments built with
1419
+ * any helper library (Zod-to-JSON-Schema, ajv, hand-written, etc.)
1420
+ * without fighting the strict {@link JSONSchema} surface.
1421
+ */
1422
+ parametersSchema: Record<string, unknown>;
1423
+ origin?: 'webmcp' | 'sdk';
1424
+ pageOrigin?: string;
1425
+ }
1392
1426
  interface DispatchRequest {
1393
1427
  record?: {
1394
1428
  id?: number | string;
@@ -1408,6 +1442,16 @@ interface DispatchRequest {
1408
1442
  role: 'system' | 'user' | 'assistant';
1409
1443
  content: MessageContent;
1410
1444
  }>;
1445
+ /**
1446
+ * Per-dispatch client tools. The SDK populates this when
1447
+ * `runWithLocalTools` is invoked with `{ scope: 'turn' }` (or when
1448
+ * Persona snapshots the host page's WebMCP registry). Tool execution
1449
+ * happens client-side; the server pauses the agent with
1450
+ * `step_await` / `agent_await` and resumes once the client posts the
1451
+ * result. Complementary to the in-engine `resolveTools` callback —
1452
+ * `clientTools[]` is per-dispatch, `resolveTools` is per-iteration.
1453
+ */
1454
+ clientTools?: ClientToolDefinition[];
1411
1455
  secrets?: Record<string, string>;
1412
1456
  inputs?: Record<string, unknown>;
1413
1457
  options?: {
@@ -3934,8 +3978,16 @@ interface AgentToolStartEvent extends BaseAgentEvent {
3934
3978
  iteration: number;
3935
3979
  toolCallId: string;
3936
3980
  toolName: string;
3937
- toolType: 'flow' | 'mcp' | 'builtin' | 'custom' | 'external' | 'advisor' | 'subagent';
3981
+ toolType: 'flow' | 'mcp' | 'builtin' | 'custom' | 'external' | 'advisor' | 'subagent' | 'local';
3938
3982
  parameters?: Record<string, unknown>;
3983
+ /**
3984
+ * Provenance for client-executed tools (entered via
3985
+ * `dispatch.clientTools[]`). `'webmcp'` marks page-discovered tools
3986
+ * via the WebMCP polyfill; `'sdk'` marks SDK-provided locals.
3987
+ */
3988
+ origin?: 'webmcp' | 'sdk';
3989
+ /** `window.location.origin` of the page that registered a WebMCP tool. */
3990
+ pageOrigin?: string;
3939
3991
  }
3940
3992
  /**
3941
3993
  * Agent tool delta event (reserved for future execution progress)
@@ -4136,6 +4188,10 @@ interface AgentPausedEvent extends BaseAgentEvent {
4136
4188
  toolName: string;
4137
4189
  parameters?: Record<string, unknown>;
4138
4190
  awaitedAt: string;
4191
+ /** Provenance for tools registered via `dispatch.clientTools[]`. */
4192
+ origin?: 'webmcp' | 'sdk';
4193
+ /** `window.location.origin` of the page that registered a WebMCP tool. */
4194
+ pageOrigin?: string;
4139
4195
  }
4140
4196
  /**
4141
4197
  * Synthetic SDK event fired when client-side local tool execution begins.
@@ -4902,6 +4958,43 @@ declare class AgentsEndpoint {
4902
4958
  */
4903
4959
 
4904
4960
  type LocalToolHandler = (args: unknown) => Promise<unknown>;
4961
+ /**
4962
+ * Richer local tool entry that pairs a handler with the wire schema the
4963
+ * server should announce to the model. Required when running with
4964
+ * `scope: 'turn'` — the SDK reads the handler's `description` /
4965
+ * `parametersSchema` to build the dispatch envelope's `clientTools[]`.
4966
+ * Optional otherwise (a bare handler still works under `scope: 'session'`
4967
+ * because the caller is expected to have stamped the schema into the
4968
+ * step's `tools.runtimeTools` already).
4969
+ */
4970
+ interface LocalToolEntry {
4971
+ description: string;
4972
+ parametersSchema: Record<string, unknown>;
4973
+ execute: (args: unknown) => Promise<unknown>;
4974
+ origin?: 'webmcp' | 'sdk';
4975
+ pageOrigin?: string;
4976
+ }
4977
+ /**
4978
+ * Options accepted by {@link RuntypeClient.runWithLocalTools}.
4979
+ *
4980
+ * `scope` controls how the SDK delivers the schema for caller-supplied
4981
+ * local tools to the server:
4982
+ *
4983
+ * - `'session'` (default) — back-compat. The caller has already injected
4984
+ * the schema into the flow's step-level `tools.runtimeTools`; the SDK
4985
+ * only handles the pause/resume loop with the matching handlers.
4986
+ * - `'turn'` — the SDK auto-builds `dispatch.clientTools[]` from the
4987
+ * handler map and ships them in the dispatch envelope. The tools live
4988
+ * for one user turn (one dispatch). Use this for page-side WebMCP
4989
+ * tools or any per-turn snapshot pattern.
4990
+ *
4991
+ * `'session'` is named for the FlowBuilder use case where the tool config
4992
+ * is stamped once on the flow definition. `'turn'` aligns with the
4993
+ * WebMCP "snapshot at the start of every model turn" refresh model.
4994
+ */
4995
+ interface RunWithLocalToolsOptions {
4996
+ scope?: 'turn' | 'session';
4997
+ }
4905
4998
  /**
4906
4999
  * RuntypeClient - The main entry point for interacting with the Runtype API
4907
5000
  *
@@ -4955,11 +5048,16 @@ declare class RuntypeClient implements ApiClient {
4955
5048
  * Run a flow with client-side tools (automatic pause/resume loop)
4956
5049
  *
4957
5050
  * @param request - The dispatch request configuration
4958
- * @param clientTools - Map of tool names to async functions that execute the tool logic
4959
- * @param callbacks - Optional callbacks for streaming events
5051
+ * @param localTools - Map of tool names to async functions (or full
5052
+ * `LocalToolEntry` objects) that execute the tool logic
5053
+ * @param callbacksOrOptions - Either {@link StreamCallbacks} (legacy) or
5054
+ * {@link RunWithLocalToolsOptions}. To pass both, use the 4-arg
5055
+ * overload.
5056
+ * @param options - Per-call options when callbacks are also supplied
4960
5057
  * @returns The final result of the flow execution or summary if streaming
4961
5058
  */
4962
- runWithLocalTools(request: DispatchRequest, localTools: Record<string, LocalToolHandler>, callbacks?: StreamCallbacks): Promise<FlowResult | FlowSummary>;
5059
+ runWithLocalTools(request: DispatchRequest, localTools: Record<string, LocalToolHandler | LocalToolEntry>, callbacks?: StreamCallbacks, options?: RunWithLocalToolsOptions): Promise<FlowResult | FlowSummary>;
5060
+ runWithLocalTools(request: DispatchRequest, localTools: Record<string, LocalToolHandler | LocalToolEntry>, options: RunWithLocalToolsOptions): Promise<FlowResult | FlowSummary>;
4963
5061
  /**
4964
5062
  * Generic GET request
4965
5063
  */
@@ -5535,4 +5633,4 @@ declare function getLikelySupportingCandidatePaths(bestCandidatePath: string | u
5535
5633
  declare function getDefaultPlanPath(taskName: string): string;
5536
5634
  declare function sanitizeTaskSlug(taskName: string): string;
5537
5635
 
5538
- 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 ExternalAgentContext, 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 ReasoningContentPart, 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 };
5636
+ 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 ClientToolDefinition, 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 ExternalAgentContext, 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 ReasoningContentPart, 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 };
package/dist/index.d.ts CHANGED
@@ -973,9 +973,14 @@ interface DispatchClient {
973
973
  * @param config - The dispatch request configuration
974
974
  * @param localTools - Map of tool names to async functions that execute the tool logic
975
975
  * @param callbacks - Optional callbacks for streaming events
976
+ * @param options - Optional behavior tweaks (e.g. `{ scope: 'turn' }` to
977
+ * inject the schema as `dispatch.clientTools[]` instead of the legacy
978
+ * step-level `runtimeTools` path)
976
979
  * @returns The final result of the flow execution or summary if streaming
977
980
  */
978
- runWithLocalTools(config: DispatchRequest, localTools: Record<string, (args: any) => Promise<any>>, callbacks?: StreamCallbacks): Promise<FlowResult | FlowSummary>;
981
+ runWithLocalTools(config: DispatchRequest, localTools: Record<string, (args: any) => Promise<any>>, callbacks?: StreamCallbacks, options?: {
982
+ scope?: 'turn' | 'session';
983
+ }): Promise<FlowResult | FlowSummary>;
979
984
  dispatch(config: DispatchRequest): Promise<Response>;
980
985
  }
981
986
  /**
@@ -1389,6 +1394,35 @@ interface UpsertOptions {
1389
1394
  * Environment type for dispatch requests
1390
1395
  */
1391
1396
  type DispatchEnvironment = 'development' | 'production';
1397
+ /**
1398
+ * Inline tool definition that executes on the dispatching client.
1399
+ *
1400
+ * The wire shape matches the server-side `InlineClientToolSchema` in
1401
+ * `@runtypelabs/shared/api-schemas/dispatch`. Two flavors share the wire:
1402
+ *
1403
+ * - `origin: 'sdk'` (default) — caller-defined locals. No name-prefix rule.
1404
+ * - `origin: 'webmcp'` — page-discovered tools via
1405
+ * `document.modelContext.registerTool(...)`. The server applies a
1406
+ * `webmcp:` name prefix before merge so audit logs are filterable.
1407
+ *
1408
+ * Use {@link runWithLocalTools} with `{ scope: 'turn' }` to ship these in
1409
+ * the dispatch envelope; with `{ scope: 'session' }` (default) the SDK
1410
+ * still injects them as step-level runtimeTools for back-compat.
1411
+ */
1412
+ interface ClientToolDefinition {
1413
+ name: string;
1414
+ description: string;
1415
+ /**
1416
+ * JSON Schema for the tool's input. Type is intentionally
1417
+ * `Record<string, unknown>` (matching {@link LocalToolDefinition} in
1418
+ * `endpoints.ts`) so callers can pass JSON Schema fragments built with
1419
+ * any helper library (Zod-to-JSON-Schema, ajv, hand-written, etc.)
1420
+ * without fighting the strict {@link JSONSchema} surface.
1421
+ */
1422
+ parametersSchema: Record<string, unknown>;
1423
+ origin?: 'webmcp' | 'sdk';
1424
+ pageOrigin?: string;
1425
+ }
1392
1426
  interface DispatchRequest {
1393
1427
  record?: {
1394
1428
  id?: number | string;
@@ -1408,6 +1442,16 @@ interface DispatchRequest {
1408
1442
  role: 'system' | 'user' | 'assistant';
1409
1443
  content: MessageContent;
1410
1444
  }>;
1445
+ /**
1446
+ * Per-dispatch client tools. The SDK populates this when
1447
+ * `runWithLocalTools` is invoked with `{ scope: 'turn' }` (or when
1448
+ * Persona snapshots the host page's WebMCP registry). Tool execution
1449
+ * happens client-side; the server pauses the agent with
1450
+ * `step_await` / `agent_await` and resumes once the client posts the
1451
+ * result. Complementary to the in-engine `resolveTools` callback —
1452
+ * `clientTools[]` is per-dispatch, `resolveTools` is per-iteration.
1453
+ */
1454
+ clientTools?: ClientToolDefinition[];
1411
1455
  secrets?: Record<string, string>;
1412
1456
  inputs?: Record<string, unknown>;
1413
1457
  options?: {
@@ -3934,8 +3978,16 @@ interface AgentToolStartEvent extends BaseAgentEvent {
3934
3978
  iteration: number;
3935
3979
  toolCallId: string;
3936
3980
  toolName: string;
3937
- toolType: 'flow' | 'mcp' | 'builtin' | 'custom' | 'external' | 'advisor' | 'subagent';
3981
+ toolType: 'flow' | 'mcp' | 'builtin' | 'custom' | 'external' | 'advisor' | 'subagent' | 'local';
3938
3982
  parameters?: Record<string, unknown>;
3983
+ /**
3984
+ * Provenance for client-executed tools (entered via
3985
+ * `dispatch.clientTools[]`). `'webmcp'` marks page-discovered tools
3986
+ * via the WebMCP polyfill; `'sdk'` marks SDK-provided locals.
3987
+ */
3988
+ origin?: 'webmcp' | 'sdk';
3989
+ /** `window.location.origin` of the page that registered a WebMCP tool. */
3990
+ pageOrigin?: string;
3939
3991
  }
3940
3992
  /**
3941
3993
  * Agent tool delta event (reserved for future execution progress)
@@ -4136,6 +4188,10 @@ interface AgentPausedEvent extends BaseAgentEvent {
4136
4188
  toolName: string;
4137
4189
  parameters?: Record<string, unknown>;
4138
4190
  awaitedAt: string;
4191
+ /** Provenance for tools registered via `dispatch.clientTools[]`. */
4192
+ origin?: 'webmcp' | 'sdk';
4193
+ /** `window.location.origin` of the page that registered a WebMCP tool. */
4194
+ pageOrigin?: string;
4139
4195
  }
4140
4196
  /**
4141
4197
  * Synthetic SDK event fired when client-side local tool execution begins.
@@ -4902,6 +4958,43 @@ declare class AgentsEndpoint {
4902
4958
  */
4903
4959
 
4904
4960
  type LocalToolHandler = (args: unknown) => Promise<unknown>;
4961
+ /**
4962
+ * Richer local tool entry that pairs a handler with the wire schema the
4963
+ * server should announce to the model. Required when running with
4964
+ * `scope: 'turn'` — the SDK reads the handler's `description` /
4965
+ * `parametersSchema` to build the dispatch envelope's `clientTools[]`.
4966
+ * Optional otherwise (a bare handler still works under `scope: 'session'`
4967
+ * because the caller is expected to have stamped the schema into the
4968
+ * step's `tools.runtimeTools` already).
4969
+ */
4970
+ interface LocalToolEntry {
4971
+ description: string;
4972
+ parametersSchema: Record<string, unknown>;
4973
+ execute: (args: unknown) => Promise<unknown>;
4974
+ origin?: 'webmcp' | 'sdk';
4975
+ pageOrigin?: string;
4976
+ }
4977
+ /**
4978
+ * Options accepted by {@link RuntypeClient.runWithLocalTools}.
4979
+ *
4980
+ * `scope` controls how the SDK delivers the schema for caller-supplied
4981
+ * local tools to the server:
4982
+ *
4983
+ * - `'session'` (default) — back-compat. The caller has already injected
4984
+ * the schema into the flow's step-level `tools.runtimeTools`; the SDK
4985
+ * only handles the pause/resume loop with the matching handlers.
4986
+ * - `'turn'` — the SDK auto-builds `dispatch.clientTools[]` from the
4987
+ * handler map and ships them in the dispatch envelope. The tools live
4988
+ * for one user turn (one dispatch). Use this for page-side WebMCP
4989
+ * tools or any per-turn snapshot pattern.
4990
+ *
4991
+ * `'session'` is named for the FlowBuilder use case where the tool config
4992
+ * is stamped once on the flow definition. `'turn'` aligns with the
4993
+ * WebMCP "snapshot at the start of every model turn" refresh model.
4994
+ */
4995
+ interface RunWithLocalToolsOptions {
4996
+ scope?: 'turn' | 'session';
4997
+ }
4905
4998
  /**
4906
4999
  * RuntypeClient - The main entry point for interacting with the Runtype API
4907
5000
  *
@@ -4955,11 +5048,16 @@ declare class RuntypeClient implements ApiClient {
4955
5048
  * Run a flow with client-side tools (automatic pause/resume loop)
4956
5049
  *
4957
5050
  * @param request - The dispatch request configuration
4958
- * @param clientTools - Map of tool names to async functions that execute the tool logic
4959
- * @param callbacks - Optional callbacks for streaming events
5051
+ * @param localTools - Map of tool names to async functions (or full
5052
+ * `LocalToolEntry` objects) that execute the tool logic
5053
+ * @param callbacksOrOptions - Either {@link StreamCallbacks} (legacy) or
5054
+ * {@link RunWithLocalToolsOptions}. To pass both, use the 4-arg
5055
+ * overload.
5056
+ * @param options - Per-call options when callbacks are also supplied
4960
5057
  * @returns The final result of the flow execution or summary if streaming
4961
5058
  */
4962
- runWithLocalTools(request: DispatchRequest, localTools: Record<string, LocalToolHandler>, callbacks?: StreamCallbacks): Promise<FlowResult | FlowSummary>;
5059
+ runWithLocalTools(request: DispatchRequest, localTools: Record<string, LocalToolHandler | LocalToolEntry>, callbacks?: StreamCallbacks, options?: RunWithLocalToolsOptions): Promise<FlowResult | FlowSummary>;
5060
+ runWithLocalTools(request: DispatchRequest, localTools: Record<string, LocalToolHandler | LocalToolEntry>, options: RunWithLocalToolsOptions): Promise<FlowResult | FlowSummary>;
4963
5061
  /**
4964
5062
  * Generic GET request
4965
5063
  */
@@ -5535,4 +5633,4 @@ declare function getLikelySupportingCandidatePaths(bestCandidatePath: string | u
5535
5633
  declare function getDefaultPlanPath(taskName: string): string;
5536
5634
  declare function sanitizeTaskSlug(taskName: string): string;
5537
5635
 
5538
- 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 ExternalAgentContext, 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 ReasoningContentPart, 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 };
5636
+ 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 ClientToolDefinition, 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 ExternalAgentContext, 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 ReasoningContentPart, 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 };
package/dist/index.mjs CHANGED
@@ -7736,6 +7736,10 @@ function createExternalTool(config) {
7736
7736
  function isObjectRecord(value) {
7737
7737
  return typeof value === "object" && value !== null;
7738
7738
  }
7739
+ function hasToolEntryShape(value) {
7740
+ if (!isObjectRecord(value)) return false;
7741
+ return typeof value.execute === "function" && typeof value.description === "string" && typeof value.parametersSchema === "object" && value.parametersSchema !== null;
7742
+ }
7739
7743
  function isPausedLocalActionResult(value) {
7740
7744
  if (!isObjectRecord(value) || value.status !== "paused") {
7741
7745
  return false;
@@ -7795,7 +7799,7 @@ var RuntypeClient2 = class {
7795
7799
  return new ClientFlowBuilder(
7796
7800
  {
7797
7801
  dispatch: (config) => this.dispatch.executeStream(config),
7798
- runWithLocalTools: (config, tools) => this.runWithLocalTools(config, tools)
7802
+ runWithLocalTools: (config, tools, callbacks, opts) => this.runWithLocalTools(config, tools, callbacks, opts)
7799
7803
  },
7800
7804
  name
7801
7805
  );
@@ -7806,18 +7810,26 @@ var RuntypeClient2 = class {
7806
7810
  clearApiKey() {
7807
7811
  delete this.headers.Authorization;
7808
7812
  }
7809
- /**
7810
- * Run a flow with client-side tools (automatic pause/resume loop)
7811
- *
7812
- * @param request - The dispatch request configuration
7813
- * @param clientTools - Map of tool names to async functions that execute the tool logic
7814
- * @param callbacks - Optional callbacks for streaming events
7815
- * @returns The final result of the flow execution or summary if streaming
7816
- */
7817
- async runWithLocalTools(request, localTools, callbacks) {
7813
+ async runWithLocalTools(request, localTools, arg3, arg4) {
7814
+ const isOptionsObject = (val) => typeof val === "object" && val !== null && "scope" in val;
7815
+ const callbacks = isOptionsObject(arg3) ? void 0 : arg3;
7816
+ const options = (isOptionsObject(arg3) ? arg3 : arg4) ?? {};
7817
+ const scope = options.scope ?? "session";
7818
7818
  const isStreaming = !!callbacks;
7819
+ const derivedClientTools = scope === "turn" ? Object.entries(localTools).filter(
7820
+ (entry) => hasToolEntryShape(entry[1])
7821
+ ).map(([name, entry]) => ({
7822
+ name,
7823
+ description: entry.description,
7824
+ parametersSchema: entry.parametersSchema,
7825
+ ...entry.origin ? { origin: entry.origin } : {},
7826
+ ...entry.pageOrigin ? { pageOrigin: entry.pageOrigin } : {}
7827
+ })) : [];
7819
7828
  const modifiedRequest = {
7820
7829
  ...request,
7830
+ ...derivedClientTools.length > 0 ? {
7831
+ clientTools: [...request.clientTools ?? [], ...derivedClientTools]
7832
+ } : {},
7821
7833
  options: {
7822
7834
  ...request.options || {},
7823
7835
  streamResponse: isStreaming
@@ -7919,11 +7931,21 @@ var RuntypeClient2 = class {
7919
7931
  }
7920
7932
  if (isPausedLocalActionResult(result) && result.pausedReason?.type === "local_action") {
7921
7933
  const { toolName, parameters, executionId } = result.pausedReason;
7922
- if (!localTools[toolName]) {
7934
+ const BARE_NAME_NAMESPACES = ["webmcp:"];
7935
+ const lookupCandidates = [toolName];
7936
+ for (const ns of BARE_NAME_NAMESPACES) {
7937
+ if (toolName.startsWith(ns)) {
7938
+ lookupCandidates.push(toolName.slice(ns.length));
7939
+ }
7940
+ }
7941
+ const matchedKey = lookupCandidates.find((key) => localTools[key]);
7942
+ const toolEntry = matchedKey ? localTools[matchedKey] : void 0;
7943
+ if (!toolEntry) {
7923
7944
  throw new Error(`Local tool "${toolName}" required but not provided in localTools map`);
7924
7945
  }
7946
+ const handler = hasToolEntryShape(toolEntry) ? toolEntry.execute : toolEntry;
7925
7947
  try {
7926
- const toolResult = await localTools[toolName](parameters);
7948
+ const toolResult = await handler(parameters);
7927
7949
  const resumeData = {
7928
7950
  executionId,
7929
7951
  toolOutputs: { [toolName]: toolResult },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runtypelabs/sdk",
3
- "version": "2.0.1",
3
+ "version": "2.1.1",
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",