@modelrelay/sdk 5.3.0 → 8.0.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.
Files changed (45) hide show
  1. package/README.md +122 -0
  2. package/dist/{api-7TVb2cnl.d.cts → api-B7SmXjnr.d.cts} +599 -1
  3. package/dist/{api-7TVb2cnl.d.ts → api-B7SmXjnr.d.ts} +599 -1
  4. package/dist/api-CdHqjsU_.d.cts +6062 -0
  5. package/dist/api-CdHqjsU_.d.ts +6062 -0
  6. package/dist/api-DP9MoKHy.d.cts +5993 -0
  7. package/dist/api-DP9MoKHy.d.ts +5993 -0
  8. package/dist/{api-BRAJe_xm.d.cts → api-c1j5ycVR.d.cts} +0 -54
  9. package/dist/{api-BRAJe_xm.d.ts → api-c1j5ycVR.d.ts} +0 -54
  10. package/dist/billing/index.d.cts +1 -1
  11. package/dist/billing/index.d.ts +1 -1
  12. package/dist/chunk-27KGKJLT.js +1194 -0
  13. package/dist/{chunk-5O4NJXLJ.js → chunk-HHBAD7FF.js} +1 -1
  14. package/dist/{chunk-LZDGY24E.js → chunk-PKGWFDGU.js} +111 -59
  15. package/dist/{chunk-HLJAMT7F.js → chunk-RVHKBQ7X.js} +1 -1
  16. package/dist/chunk-SJC7Q4NK.js +1199 -0
  17. package/dist/{chunk-JZRSCFQH.js → chunk-YQWOQ74P.js} +53 -20
  18. package/dist/index.cjs +3134 -897
  19. package/dist/index.d.cts +894 -85
  20. package/dist/index.d.ts +894 -85
  21. package/dist/index.js +3056 -905
  22. package/dist/node.cjs +6 -2
  23. package/dist/node.d.cts +1 -1
  24. package/dist/node.d.ts +1 -1
  25. package/dist/node.js +1 -1
  26. package/dist/{tools-Db-F5rIL.d.cts → tools-Bxdv0Np2.d.cts} +101 -218
  27. package/dist/{tools-Db-F5rIL.d.ts → tools-Bxdv0Np2.d.ts} +101 -218
  28. package/dist/tools-DHCGz_lx.d.cts +1041 -0
  29. package/dist/tools-DHCGz_lx.d.ts +1041 -0
  30. package/dist/tools-ZpcYacSo.d.cts +1000 -0
  31. package/dist/tools-ZpcYacSo.d.ts +1000 -0
  32. package/package.json +6 -1
  33. package/dist/api-B9x3HA3Z.d.cts +0 -5292
  34. package/dist/api-B9x3HA3Z.d.ts +0 -5292
  35. package/dist/api-Bitsm1tl.d.cts +0 -5290
  36. package/dist/api-Bitsm1tl.d.ts +0 -5290
  37. package/dist/api-D0wnVpwn.d.cts +0 -5292
  38. package/dist/api-D0wnVpwn.d.ts +0 -5292
  39. package/dist/api-HVh8Lusf.d.cts +0 -5300
  40. package/dist/api-HVh8Lusf.d.ts +0 -5300
  41. package/dist/chunk-BL7GWXRZ.js +0 -1196
  42. package/dist/chunk-CV3DTA6P.js +0 -1196
  43. package/dist/chunk-G5H7EY4F.js +0 -1196
  44. package/dist/chunk-OJFVI3QJ.js +0 -1133
  45. package/dist/chunk-Z6R4G2TU.js +0 -1133
package/dist/index.d.cts CHANGED
@@ -1,6 +1,7 @@
1
- import { A as ApiKey, R as RetryConfig, M as MetricsCallbacks, T as TraceCallbacks, a as RequestContext, b as TokenProvider, C as CustomerTokenRequest, c as CustomerToken, G as GetOrCreateCustomerTokenRequest, P as ProviderId, d as ModelId, I as InputItem, O as OutputFormat, e as Tool, f as ToolChoice, Z as ZodLikeSchema, g as ResponseEvent, h as Response$1, S as StructuredJSONEvent, F as FieldError, i as RetryMetadata, j as TransportErrorKind, k as ToolRegistry, l as ToolExecutionResult, m as TierCode, n as SecretKey, o as ModelRelayKeyOptions, p as ModelRelayOptions } from './tools-bCt1QwNk.cjs';
2
- export { ba as APICheckoutSession, b9 as APICustomerRef, bd as APIKey, bc as APIResponsesResponse, bb as APIUsage, ak as BillingProvider, aj as BillingProviders, aT as Citation, aL as CodeExecConfig, ay as ContentPart, ax as ContentPartType, aw as ContentPartTypes, al as CustomerMetadata, D as DEFAULT_BASE_URL, a7 as DEFAULT_CLIENT_HEADER, a8 as DEFAULT_CONNECT_TIMEOUT_MS, a9 as DEFAULT_REQUEST_TIMEOUT_MS, b8 as DeepPartial, aO as FunctionCall, b6 as FunctionCallDelta, aI as FunctionTool, aU as HttpRequestMetrics, aA as InputItemType, az as InputItemTypes, aS as JSONSchemaFormat, a2 as JsonSchemaOptions, ac as KnownStopReason, b3 as MessageDeltaData, av as MessageRole, au as MessageRoles, b2 as MessageStartData, b4 as MessageStopData, am as ModelRelayBaseOptions, an as ModelRelayTokenOptions, ao as ModelRelayTokenProviderOptions, aa as NonEmptyArray, aR as OutputFormatType, aQ as OutputFormatTypes, aD as OutputItem, aC as OutputItemType, aB as OutputItemTypes, at as Project, b1 as ResponseEventType, a5 as RetryOptions, a6 as SDK_VERSION, a3 as Schema, ad as StopReason, ab as StopReasons, aV as StreamFirstTokenMetrics, b7 as StructuredJSONRecordType, ai as SubscriptionStatusKind, ah as SubscriptionStatuses, ap as TokenType, aW as TokenUsageMetrics, X as ToolArgsError, aP as ToolCall, N as ToolCallAccumulator, b5 as ToolCallDelta, aN as ToolChoiceType, aM as ToolChoiceTypes, a4 as ToolHandler, aF as ToolType, aE as ToolTypes, aq as Usage, as as UsageSummary, aJ as WebSearchConfig, aH as WebToolIntent, aG as WebToolIntents, aK as XSearchConfig, af as asModelId, ae as asProviderId, ag as asTierCode, J as assistantMessageWithToolCalls, z as createAssistantMessage, L as createFunctionCall, q as createFunctionTool, r as createFunctionToolFromSchema, a0 as createRetryMessages, B as createSystemMessage, K as createToolCall, ar as createUsage, y as createUserMessage, s as createWebTool, a1 as executeWithRetry, x as firstToolCall, Y as formatToolErrorForModel, $ as getRetryableErrors, _ as hasRetryableErrors, w as hasToolCalls, aX as mergeMetrics, aY as mergeTrace, b0 as modelToString, a$ as normalizeModelId, aZ as normalizeStopReason, U as parseToolArgs, W as parseToolArgsRaw, H as respondToToolCall, a_ as stopReasonToString, t as toolChoiceAuto, v as toolChoiceNone, u as toolChoiceRequired, E as toolResultMessage, V as tryParseToolArgs, Q as zodToJsonSchema } from './tools-bCt1QwNk.cjs';
3
- import { c as components, $ as $defs, o as operations, p as paths, w as webhooks } from './api-7TVb2cnl.cjs';
1
+ import { A as ApiKey, R as RetryConfig, M as MetricsCallbacks, T as TraceCallbacks, a as RequestContext, b as TokenProvider, C as CustomerTokenRequest, c as CustomerToken, G as GetOrCreateCustomerTokenRequest, P as ProviderId, d as ModelId, I as InputItem, O as OutputFormat, e as Tool, f as ToolChoice, Z as ZodLikeSchema, g as ToolCall, h as Response$1, i as ResponseEvent, S as StructuredJSONEvent, F as FieldError, j as RetryMetadata, k as TransportErrorKind, l as ToolRegistry, m as ToolExecutionResult, n as TierCode, o as AnySchema, p as SecretKey, q as ModelRelayKeyOptions, r as ModelRelayOptions } from './tools-DHCGz_lx.cjs';
2
+ export { bf as APICheckoutSession, be as APICustomerRef, bi as APIKey, bh as APIResponsesResponse, bg as APIUsage, at as BillingProvider, as as BillingProviders, aY as Citation, aR as CodeExecConfig, aH as ContentPart, aG as ContentPartType, aF as ContentPartTypes, au as CustomerMetadata, D as DEFAULT_BASE_URL, ag as DEFAULT_CLIENT_HEADER, ah as DEFAULT_CONNECT_TIMEOUT_MS, ai as DEFAULT_REQUEST_TIMEOUT_MS, bd as DeepPartial, aU as FunctionCall, bb as FunctionCallDelta, aP as FunctionTool, aZ as HttpRequestMetrics, a9 as InferSchema, aJ as InputItemType, aI as InputItemTypes, aX as JSONSchemaFormat, a8 as JsonSchemaOptions, al as KnownStopReason, b8 as MessageDeltaData, aE as MessageRole, aD as MessageRoles, b7 as MessageStartData, b9 as MessageStopData, av as ModelRelayBaseOptions, aw as ModelRelayTokenOptions, ax as ModelRelayTokenProviderOptions, aj as NonEmptyArray, aW as OutputFormatType, aV as OutputFormatTypes, aM as OutputItem, aL as OutputItemType, aK as OutputItemTypes, aC as Project, b6 as ResponseEventType, ad as RetryOptions, af as SDK_VERSION, am as StopReason, ak as StopReasons, a_ as StreamFirstTokenMetrics, bc as StructuredJSONRecordType, ar as SubscriptionStatusKind, aq as SubscriptionStatuses, ay as TokenType, a$ as TokenUsageMetrics, a2 as ToolArgsError, ae as ToolArgsResult, a0 as ToolCallAccumulator, ba as ToolCallDelta, aT as ToolChoiceType, aS as ToolChoiceTypes, ac as ToolHandler, aO as ToolType, aN as ToolTypes, aa as TypedFunctionTool, ab as TypedToolCall, az as Usage, aB as UsageSummary, aQ as XSearchConfig, ao as asModelId, an as asProviderId, ap as asTierCode, K as assistantMessageWithToolCalls, B as createAssistantMessage, N as createFunctionCall, s as createFunctionTool, a6 as createRetryMessages, E as createSystemMessage, L as createToolCall, t as createTypedTool, aA as createUsage, z as createUserMessage, a7 as executeWithRetry, y as firstToolCall, a3 as formatToolErrorForModel, W as getAllToolCalls, $ as getAssistantText, a5 as getRetryableErrors, V as getToolArgs, U as getToolArgsRaw, Q as getToolName, X as getTypedToolCall, Y as getTypedToolCalls, a4 as hasRetryableErrors, x as hasToolCalls, b0 as mergeMetrics, b1 as mergeTrace, b5 as modelToString, b4 as normalizeModelId, b2 as normalizeStopReason, _ as parseTypedToolCall, J as respondToToolCall, b3 as stopReasonToString, u as toolChoiceAuto, w as toolChoiceNone, v as toolChoiceRequired, H as toolResultMessage, a1 as zodToJsonSchema } from './tools-DHCGz_lx.cjs';
3
+ import { c as components, $ as $defs, o as operations, p as paths, w as webhooks } from './api-CdHqjsU_.cjs';
4
+ import { z } from 'zod';
4
5
 
5
6
  interface RequestOptions {
6
7
  method?: string;
@@ -130,6 +131,7 @@ type ResponsesRequest = {
130
131
  type WireResponsesRequest = {
131
132
  provider?: ProviderId;
132
133
  model?: ModelId;
134
+ state_id?: string;
133
135
  input: InputItem[];
134
136
  output_format?: OutputFormat;
135
137
  max_output_tokens?: number;
@@ -351,10 +353,32 @@ declare class ResponseBuilder {
351
353
  private readonly options;
352
354
  constructor(body?: Partial<WireResponsesRequest>, options?: ResponsesRequestOptions);
353
355
  private with;
354
- /** @returns A new builder with the provider set. */
355
- provider(provider: ProviderId): ResponseBuilder;
356
- /** @returns A new builder with the model set. */
357
- model(model: ModelId): ResponseBuilder;
356
+ /**
357
+ * Set the provider for this request.
358
+ *
359
+ * Accepts either a string or ProviderId for convenience.
360
+ *
361
+ * @example
362
+ * ```typescript
363
+ * .provider("anthropic") // String works
364
+ * .provider(asProviderId("anthropic")) // ProviderId also works
365
+ * ```
366
+ */
367
+ provider(provider: string | ProviderId): ResponseBuilder;
368
+ /**
369
+ * Set the model for this request.
370
+ *
371
+ * Accepts either a string or ModelId for convenience.
372
+ *
373
+ * @example
374
+ * ```typescript
375
+ * .model("claude-sonnet-4-5") // String works
376
+ * .model(asModelId("claude-sonnet-4-5")) // ModelId also works
377
+ * ```
378
+ */
379
+ model(model: string | ModelId): ResponseBuilder;
380
+ /** @returns A new builder with state-scoped tool state. */
381
+ stateId(stateId: string): ResponseBuilder;
358
382
  /** @returns A new builder with the full input array replaced. */
359
383
  input(items: InputItem[]): ResponseBuilder;
360
384
  /** @returns A new builder with the input item appended. */
@@ -417,6 +441,86 @@ declare class ResponseBuilder {
417
441
  streamTotalTimeoutMs(timeoutMs: number): ResponseBuilder;
418
442
  /** @returns A new builder with the abort signal set. */
419
443
  signal(signal: AbortSignal): ResponseBuilder;
444
+ /**
445
+ * Add an assistant message with tool calls from a previous response.
446
+ *
447
+ * This is useful for continuing a conversation after handling tool calls.
448
+ *
449
+ * @example
450
+ * ```typescript
451
+ * const response = await mr.responses.create(request);
452
+ * if (hasToolCalls(response)) {
453
+ * const toolCalls = response.output[0].toolCalls!;
454
+ * const results = await registry.executeAll(toolCalls);
455
+ *
456
+ * const followUp = await mr.responses.create(
457
+ * mr.responses.new()
458
+ * .model("claude-sonnet-4-5")
459
+ * .user("What's the weather in Paris?")
460
+ * .assistantToolCalls(toolCalls)
461
+ * .toolResults(results.map(r => ({ id: r.toolCallId, result: r.result })))
462
+ * .build()
463
+ * );
464
+ * }
465
+ * ```
466
+ */
467
+ assistantToolCalls(toolCalls: ToolCall[], content?: string): ResponseBuilder;
468
+ /**
469
+ * Add tool results to the conversation.
470
+ *
471
+ * @example
472
+ * ```typescript
473
+ * .toolResults([
474
+ * { id: "call_123", result: { temp: 72 } },
475
+ * { id: "call_456", result: "File contents here" },
476
+ * ])
477
+ * ```
478
+ */
479
+ toolResults(results: Array<{
480
+ id: string;
481
+ result: unknown;
482
+ }>): ResponseBuilder;
483
+ /**
484
+ * Add a single tool result to the conversation.
485
+ *
486
+ * @example
487
+ * ```typescript
488
+ * .toolResult("call_123", { temp: 72, unit: "fahrenheit" })
489
+ * ```
490
+ */
491
+ toolResult(toolCallId: string, result: unknown): ResponseBuilder;
492
+ /**
493
+ * Continue from a previous response that contains tool calls.
494
+ *
495
+ * This is the most ergonomic way to continue a conversation after handling tools.
496
+ * It automatically adds the assistant's tool call message and your tool results.
497
+ *
498
+ * @example
499
+ * ```typescript
500
+ * const response = await mr.responses.create(request);
501
+ *
502
+ * if (hasToolCalls(response)) {
503
+ * const toolCalls = response.output[0].toolCalls!;
504
+ * const results = await registry.executeAll(toolCalls);
505
+ *
506
+ * const followUp = await mr.responses.create(
507
+ * mr.responses.new()
508
+ * .model("claude-sonnet-4-5")
509
+ * .tools(myTools)
510
+ * .user("What's the weather in Paris?")
511
+ * .continueFrom(response, results.map(r => ({
512
+ * id: r.toolCallId,
513
+ * result: r.result,
514
+ * })))
515
+ * .build()
516
+ * );
517
+ * }
518
+ * ```
519
+ */
520
+ continueFrom(response: Response$1, toolResults: Array<{
521
+ id: string;
522
+ result: unknown;
523
+ }>): ResponseBuilder;
420
524
  /** @returns A finalized, immutable request payload. */
421
525
  build(): ResponsesRequest;
422
526
  }
@@ -656,7 +760,7 @@ declare const WorkflowKinds: {
656
760
  };
657
761
  type WorkflowKindIntent = (typeof WorkflowKinds)["WorkflowIntent"];
658
762
  type WorkflowKind = WorkflowKindIntent;
659
- declare const WorkflowNodeTypesLite: {
763
+ declare const WorkflowNodeTypesIntent: {
660
764
  readonly LLM: "llm";
661
765
  readonly JoinAll: "join.all";
662
766
  readonly JoinAny: "join.any";
@@ -664,7 +768,7 @@ declare const WorkflowNodeTypesLite: {
664
768
  readonly TransformJSON: "transform.json";
665
769
  readonly MapFanout: "map.fanout";
666
770
  };
667
- type WorkflowNodeTypeLite = (typeof WorkflowNodeTypesLite)[keyof typeof WorkflowNodeTypesLite];
771
+ type WorkflowNodeTypeIntent = (typeof WorkflowNodeTypesIntent)[keyof typeof WorkflowNodeTypesIntent];
668
772
  type WorkflowIntentConditionSource = "node_output" | "node_status";
669
773
  type WorkflowIntentConditionOp = "equals" | "matches" | "exists";
670
774
  type WorkflowIntentCondition = {
@@ -679,7 +783,7 @@ type WorkflowIntentTransformValue = {
679
783
  };
680
784
  type WorkflowIntentNode = {
681
785
  id: NodeId$1;
682
- type: WorkflowNodeTypeLite;
786
+ type: WorkflowNodeTypeIntent;
683
787
  depends_on?: ReadonlyArray<NodeId$1>;
684
788
  model?: string;
685
789
  system?: string;
@@ -702,17 +806,26 @@ type WorkflowIntentNode = {
702
806
  object?: Record<string, WorkflowIntentTransformValue>;
703
807
  merge?: Array<WorkflowIntentTransformValue>;
704
808
  };
705
- type WorkflowOutputRefLiteV1 = {
809
+ type WorkflowOutputRefIntentV1 = {
706
810
  name: OutputName$1;
707
811
  from: NodeId$1;
708
812
  pointer?: string;
709
813
  };
710
- type WorkflowSpecLiteV1 = {
814
+ type WorkflowInputDeclIntentV1 = {
815
+ name: string;
816
+ type?: string;
817
+ required?: boolean;
818
+ description?: string;
819
+ default?: unknown;
820
+ };
821
+ type WorkflowSpecIntentV1 = {
711
822
  kind: WorkflowKindIntent;
712
823
  name?: string;
713
824
  model?: string;
825
+ max_parallelism?: number;
826
+ inputs?: ReadonlyArray<WorkflowInputDeclIntentV1>;
714
827
  nodes: ReadonlyArray<WorkflowIntentNode>;
715
- outputs: ReadonlyArray<WorkflowOutputRefLiteV1>;
828
+ outputs: ReadonlyArray<WorkflowOutputRefIntentV1>;
716
829
  };
717
830
  type RunStatusV0 = "running" | "waiting" | "succeeded" | "failed" | "canceled";
718
831
  type PayloadInfoV0$1 = {
@@ -720,7 +833,7 @@ type PayloadInfoV0$1 = {
720
833
  sha256: string;
721
834
  included: boolean;
722
835
  };
723
- type RunEventTypeV0 = "run_compiled" | "run_started" | "run_completed" | "run_failed" | "run_canceled" | "node_llm_call" | "node_tool_call" | "node_tool_result" | "node_waiting" | "node_started" | "node_succeeded" | "node_failed" | "node_output_delta" | "node_output";
836
+ type RunEventTypeV0 = "run_compiled" | "run_started" | "run_completed" | "run_failed" | "run_canceled" | "node_llm_call" | "node_tool_call" | "node_tool_result" | "node_waiting" | "node_user_ask" | "node_user_answer" | "node_started" | "node_succeeded" | "node_failed" | "node_output_delta" | "node_output";
724
837
  type NodeErrorV0$1 = {
725
838
  code?: string;
726
839
  message: string;
@@ -784,6 +897,25 @@ type NodeWaitingV0$1 = {
784
897
  pending_tool_calls: PendingToolCallV0$1[];
785
898
  reason: string;
786
899
  };
900
+ type UserAskOptionV0 = {
901
+ label: string;
902
+ description?: string;
903
+ };
904
+ type NodeUserAskV0 = {
905
+ step: number;
906
+ request_id: string;
907
+ tool_call: ToolCallWithArgumentsV0$1;
908
+ question: string;
909
+ options?: UserAskOptionV0[];
910
+ allow_freeform: boolean;
911
+ };
912
+ type NodeUserAnswerV0 = {
913
+ step: number;
914
+ request_id: string;
915
+ tool_call: ToolCallV0$1;
916
+ answer: string;
917
+ is_freeform: boolean;
918
+ };
787
919
  type RunEventBaseV0 = {
788
920
  envelope_version: "v2";
789
921
  run_id: RunId$1;
@@ -846,6 +978,16 @@ type RunEventNodeWaitingV0 = RunEventBaseV0 & {
846
978
  node_id: NodeId$1;
847
979
  waiting: NodeWaitingV0$1;
848
980
  };
981
+ type RunEventNodeUserAskV0 = RunEventBaseV0 & {
982
+ type: "node_user_ask";
983
+ node_id: NodeId$1;
984
+ user_ask: NodeUserAskV0;
985
+ };
986
+ type RunEventNodeUserAnswerV0 = RunEventBaseV0 & {
987
+ type: "node_user_answer";
988
+ node_id: NodeId$1;
989
+ user_answer: NodeUserAnswerV0;
990
+ };
849
991
  type RunEventNodeOutputDeltaV0 = RunEventBaseV0 & {
850
992
  type: "node_output_delta";
851
993
  node_id: NodeId$1;
@@ -856,7 +998,7 @@ type RunEventNodeOutputV0 = RunEventBaseV0 & {
856
998
  node_id: NodeId$1;
857
999
  output: PayloadArtifactV0$1;
858
1000
  };
859
- type RunEventV0 = RunEventRunCompiledV0 | RunEventRunStartedV0 | RunEventRunCompletedV0 | RunEventRunFailedV0 | RunEventRunCanceledV0 | RunEventNodeLLMCallV0 | RunEventNodeToolCallV0 | RunEventNodeToolResultV0 | RunEventNodeWaitingV0 | RunEventNodeStartedV0 | RunEventNodeSucceededV0 | RunEventNodeFailedV0 | RunEventNodeOutputDeltaV0 | RunEventNodeOutputV0;
1001
+ type RunEventV0 = RunEventRunCompiledV0 | RunEventRunStartedV0 | RunEventRunCompletedV0 | RunEventRunFailedV0 | RunEventRunCanceledV0 | RunEventNodeLLMCallV0 | RunEventNodeToolCallV0 | RunEventNodeToolResultV0 | RunEventNodeWaitingV0 | RunEventNodeUserAskV0 | RunEventNodeUserAnswerV0 | RunEventNodeStartedV0 | RunEventNodeSucceededV0 | RunEventNodeFailedV0 | RunEventNodeOutputDeltaV0 | RunEventNodeOutputV0;
860
1002
 
861
1003
  type NodeStatusV0 = "pending" | "running" | "waiting" | "succeeded" | "failed" | "canceled";
862
1004
  type RunsToolResultsRequest = {
@@ -955,6 +1097,16 @@ type RunsCreateOptions = {
955
1097
  sessionId?: string;
956
1098
  idempotencyKey?: string;
957
1099
  input?: Record<string, unknown>;
1100
+ modelOverride?: string;
1101
+ modelOverrides?: {
1102
+ nodes?: Record<string, string>;
1103
+ fanoutSubnodes?: Array<{
1104
+ parentId: string;
1105
+ subnodeId: string;
1106
+ model: string;
1107
+ }>;
1108
+ };
1109
+ stream?: boolean;
958
1110
  signal?: AbortSignal;
959
1111
  headers?: Record<string, string>;
960
1112
  timeoutMs?: number;
@@ -1015,7 +1167,20 @@ declare class RunsClient {
1015
1167
  trace?: TraceCallbacks;
1016
1168
  });
1017
1169
  private applyCustomerHeader;
1018
- create(spec: WorkflowSpecLiteV1, options?: RunsCreateOptions): Promise<RunsCreateResponse>;
1170
+ create(spec: WorkflowSpecIntentV1, options?: RunsCreateOptions): Promise<RunsCreateResponse>;
1171
+ /**
1172
+ * Starts a workflow run using a precompiled plan hash.
1173
+ *
1174
+ * Use workflows.compile() to compile a workflow spec and obtain a plan_hash,
1175
+ * then use this method to start runs without re-compiling each time.
1176
+ * This is useful for workflows that are run repeatedly with the same structure
1177
+ * but different inputs.
1178
+ *
1179
+ * The plan_hash must have been compiled in the current server session;
1180
+ * if the server has restarted since compilation, the plan will not be found
1181
+ * and you'll need to recompile.
1182
+ */
1183
+ createFromPlan(planHash: PlanHash$1, options?: RunsCreateOptions): Promise<RunsCreateResponse>;
1019
1184
  runEventSchemaV0(options?: {
1020
1185
  signal?: AbortSignal;
1021
1186
  headers?: Record<string, string>;
@@ -1162,6 +1327,14 @@ declare class PathEscapeError extends ModelRelayError {
1162
1327
  resolvedPath: string;
1163
1328
  });
1164
1329
  }
1330
+ /**
1331
+ * Error thrown when the agent exceeds its maximum turn limit without completing.
1332
+ * This means the model kept requesting tool calls for more turns than allowed.
1333
+ */
1334
+ declare class AgentMaxTurnsError extends ModelRelayError {
1335
+ readonly maxTurns: number;
1336
+ constructor(maxTurns: number);
1337
+ }
1165
1338
  declare function parseErrorResponse(response: Response, retries?: RetryMetadata): Promise<ModelRelayError>;
1166
1339
 
1167
1340
  type WorkflowsCompileOptions = {
@@ -1207,7 +1380,7 @@ declare class WorkflowsClient {
1207
1380
  metrics?: MetricsCallbacks;
1208
1381
  trace?: TraceCallbacks;
1209
1382
  });
1210
- compile(spec: WorkflowSpecLiteV1, options?: WorkflowsCompileOptions): Promise<WorkflowsCompileResult>;
1383
+ compile(spec: WorkflowSpecIntentV1, options?: WorkflowsCompileOptions): Promise<WorkflowsCompileResult>;
1211
1384
  }
1212
1385
 
1213
1386
  /**
@@ -1304,6 +1477,64 @@ declare class ImagesClient {
1304
1477
  unpin(imageId: string): Promise<ImagePinResponse>;
1305
1478
  }
1306
1479
 
1480
+ type StateHandleCreateRequest = components["schemas"]["StateHandleCreateRequest"];
1481
+ type StateHandleResponse = components["schemas"]["StateHandleResponse"];
1482
+ type StateHandleListResponse = components["schemas"]["StateHandleListResponse"];
1483
+ /** Maximum allowed TTL for a state handle (1 year in seconds). */
1484
+ declare const MAX_STATE_HANDLE_TTL_SECONDS = 31536000;
1485
+ declare class StateHandlesClient {
1486
+ private readonly http;
1487
+ private readonly auth;
1488
+ constructor(http: HTTPClient, auth: AuthClient);
1489
+ /** Make an authenticated request to the state handles API. */
1490
+ private request;
1491
+ create(request?: StateHandleCreateRequest): Promise<StateHandleResponse>;
1492
+ list(params?: {
1493
+ limit?: number;
1494
+ offset?: number;
1495
+ }): Promise<StateHandleListResponse>;
1496
+ delete(stateId: string): Promise<void>;
1497
+ }
1498
+
1499
+ type ContextManagementStrategy = "truncate" | "summarize";
1500
+ interface ContextTruncateInfo {
1501
+ readonly model: ModelId;
1502
+ readonly originalMessages: number;
1503
+ readonly keptMessages: number;
1504
+ readonly maxHistoryTokens: number;
1505
+ readonly reservedOutputTokens?: number;
1506
+ }
1507
+ interface ContextManagerOptions {
1508
+ strategy?: ContextManagementStrategy;
1509
+ maxHistoryTokens?: number;
1510
+ reserveOutputTokens?: number;
1511
+ onTruncate?: (info: ContextTruncateInfo) => void;
1512
+ }
1513
+ interface ContextPrepareOptions extends ContextManagerOptions {
1514
+ model?: ModelId;
1515
+ }
1516
+ interface ModelContextWindow {
1517
+ contextWindow: number;
1518
+ maxOutputTokens?: number;
1519
+ }
1520
+ type ModelContextResolver = (modelId: ModelId) => Promise<ModelContextWindow | null>;
1521
+ type ModelListClient = {
1522
+ http: {
1523
+ json: <T>(path: string, options?: {
1524
+ method?: string;
1525
+ }) => Promise<T>;
1526
+ };
1527
+ };
1528
+ declare function createModelContextResolver(client: ModelListClient): ModelContextResolver;
1529
+ declare class ContextManager {
1530
+ private readonly resolveModelContext;
1531
+ private readonly defaults;
1532
+ constructor(resolveModelContext: ModelContextResolver, defaults?: ContextManagerOptions);
1533
+ prepare(input: InputItem[], options?: ContextPrepareOptions): Promise<InputItem[]>;
1534
+ }
1535
+ declare function prepareInputWithContext(input: InputItem[], options: ContextPrepareOptions, resolveModelContext: ModelContextResolver): Promise<InputItem[]>;
1536
+ declare function truncateInputByTokens(input: InputItem[], maxHistoryTokens: number): InputItem[];
1537
+
1307
1538
  /**
1308
1539
  * Session types for multi-turn conversations.
1309
1540
  *
@@ -1417,12 +1648,16 @@ interface SessionRunResult {
1417
1648
  readonly pendingTools?: SessionPendingToolCall[];
1418
1649
  /** Error message (when status is 'error'). */
1419
1650
  readonly error?: string;
1420
- /** The run ID from the server. */
1421
- readonly runId: RunId$1;
1651
+ /** The original error that caused the failure (when status is 'error'). */
1652
+ readonly cause?: Error;
1653
+ /** The response object for responses-based runs. */
1654
+ readonly response?: Response$1;
1655
+ /** The run ID from the server (when using /runs). */
1656
+ readonly runId?: RunId$1;
1422
1657
  /** Token and call usage. */
1423
1658
  readonly usage: SessionUsageSummary;
1424
- /** All events from this run. */
1425
- readonly events: RunEventV0[];
1659
+ /** All events from this run (when using /runs). */
1660
+ readonly events?: RunEventV0[];
1426
1661
  }
1427
1662
  /**
1428
1663
  * Session type discriminator.
@@ -1485,16 +1720,22 @@ type LocalSessionPersistence = "memory" | "file" | "sqlite";
1485
1720
  interface LocalSessionOptions {
1486
1721
  /** Tool registry for handling tool calls. */
1487
1722
  toolRegistry?: ToolRegistry;
1723
+ /** Optional context manager for input truncation or summarization. */
1724
+ contextManager?: ContextManager;
1488
1725
  /** Default model for runs (can be overridden per-run). */
1489
1726
  defaultModel?: ModelId;
1490
1727
  /** Default provider for runs (can be overridden per-run). */
1491
1728
  defaultProvider?: ProviderId;
1492
1729
  /** Default tools for runs (merged with per-run tools). */
1493
1730
  defaultTools?: Tool[];
1731
+ /** System prompt to prepend to all conversations. */
1732
+ systemPrompt?: string;
1494
1733
  /** Persistence mode (default: 'memory'). */
1495
1734
  persistence?: LocalSessionPersistence;
1496
- /** Storage path for file/sqlite persistence (default: ~/.modelrelay/sessions/). */
1735
+ /** Storage path for file/sqlite persistence (default: ~/.modelrelay/sessions or ~/.modelrelay/sessions.sqlite). */
1497
1736
  storagePath?: string;
1737
+ /** Custom conversation store (overrides persistence/storagePath). */
1738
+ conversationStore?: ConversationStore;
1498
1739
  /** Session ID to use (default: generate new). */
1499
1740
  sessionId?: SessionId;
1500
1741
  /** Session metadata. */
@@ -1548,7 +1789,7 @@ interface RemoteSessionInfo {
1548
1789
  /**
1549
1790
  * Serialized session state for persistence.
1550
1791
  */
1551
- interface SessionState {
1792
+ interface ConversationState {
1552
1793
  id: SessionId;
1553
1794
  messages: SessionMessage[];
1554
1795
  artifacts: Record<string, unknown>;
@@ -1557,13 +1798,13 @@ interface SessionState {
1557
1798
  updatedAt: string;
1558
1799
  }
1559
1800
  /**
1560
- * Interface for session storage backends.
1801
+ * Interface for conversation storage backends.
1561
1802
  */
1562
- interface SessionStore {
1563
- /** Load a session by ID. Returns null if not found. */
1564
- load(id: SessionId): Promise<SessionState | null>;
1565
- /** Save a session state. */
1566
- save(state: SessionState): Promise<void>;
1803
+ interface ConversationStore {
1804
+ /** Load a conversation by ID. Returns null if not found. */
1805
+ load(id: SessionId): Promise<ConversationState | null>;
1806
+ /** Save a conversation state. */
1807
+ save(state: ConversationState): Promise<void>;
1567
1808
  /** Delete a session by ID. */
1568
1809
  delete(id: SessionId): Promise<void>;
1569
1810
  /** List all session IDs. */
@@ -1763,21 +2004,17 @@ declare class LocalSession implements Session {
1763
2004
  private readonly client;
1764
2005
  private readonly store;
1765
2006
  private readonly toolRegistry?;
2007
+ private readonly contextManager?;
1766
2008
  private readonly defaultModel?;
1767
2009
  private readonly defaultProvider?;
1768
2010
  private readonly defaultTools?;
2011
+ private readonly systemPrompt?;
1769
2012
  private readonly metadata;
1770
- private readonly resolveModelContext;
1771
2013
  private messages;
1772
2014
  private artifacts;
1773
- private nextSeq;
1774
2015
  private createdAt;
1775
2016
  private updatedAt;
1776
- private currentRunId?;
1777
- private currentNodeId?;
1778
- private currentWaiting?;
1779
- private currentEvents;
1780
- private currentUsage;
2017
+ private pendingLoop?;
1781
2018
  private constructor();
1782
2019
  /**
1783
2020
  * Create a new local session.
@@ -1803,34 +2040,11 @@ declare class LocalSession implements Session {
1803
2040
  close(): Promise<void>;
1804
2041
  /**
1805
2042
  * Sync this local session's messages to a remote session.
1806
- *
1807
- * This uploads all local messages to the remote session, enabling
1808
- * cross-device access and server-side backup. Messages are synced
1809
- * in order and the remote session's history will contain all local
1810
- * messages after sync completes.
1811
- *
1812
- * @param remoteSession - The remote session to sync to
1813
- * @param options - Optional sync configuration
1814
- * @returns Sync result with message count
1815
- *
1816
- * @example
1817
- * ```typescript
1818
- * // Create local session and work offline
1819
- * const local = LocalSession.create(client, { ... });
1820
- * await local.run("Implement the feature");
1821
- *
1822
- * // Later, sync to remote for backup/sharing
1823
- * const remote = await RemoteSession.create(client);
1824
- * const result = await local.syncTo(remote, {
1825
- * onProgress: (synced, total) => console.log(`${synced}/${total}`),
1826
- * });
1827
- * ```
1828
2043
  */
1829
2044
  syncTo(remoteSession: RemoteSession, options?: SessionSyncOptions): Promise<SessionSyncResult>;
1830
- private addMessage;
1831
- private buildInput;
1832
- private processRunEvents;
1833
- private executeTools;
2045
+ private buildContextOptions;
2046
+ private prepareInput;
2047
+ private replaceHistory;
1834
2048
  private persist;
1835
2049
  }
1836
2050
  /**
@@ -2081,6 +2295,220 @@ declare class TiersClient {
2081
2295
  checkout(tierId: string, request: TierCheckoutRequest): Promise<TierCheckoutSession>;
2082
2296
  }
2083
2297
 
2298
+ type PluginId = string & {
2299
+ readonly __brand: "PluginId";
2300
+ };
2301
+ type PluginUrl = string & {
2302
+ readonly __brand: "PluginUrl";
2303
+ };
2304
+ type PluginCommandName = string & {
2305
+ readonly __brand: "PluginCommandName";
2306
+ };
2307
+ type PluginAgentName = string & {
2308
+ readonly __brand: "PluginAgentName";
2309
+ };
2310
+ declare const PluginToolNames: {
2311
+ readonly FS_READ_FILE: "fs.read_file";
2312
+ readonly FS_LIST_FILES: "fs.list_files";
2313
+ readonly FS_SEARCH: "fs.search";
2314
+ readonly FS_EDIT: "fs.edit";
2315
+ readonly BASH: "bash";
2316
+ readonly WRITE_FILE: "write_file";
2317
+ readonly USER_ASK: "user.ask";
2318
+ };
2319
+ type PluginToolName = (typeof PluginToolNames)[keyof typeof PluginToolNames];
2320
+ declare const OrchestrationModes: {
2321
+ readonly DAG: "dag";
2322
+ readonly Dynamic: "dynamic";
2323
+ };
2324
+ type OrchestrationMode = (typeof OrchestrationModes)[keyof typeof OrchestrationModes];
2325
+ type PluginManifest = {
2326
+ name?: string;
2327
+ description?: string;
2328
+ version?: string;
2329
+ commands?: PluginCommandName[];
2330
+ agents?: PluginAgentName[];
2331
+ };
2332
+ type PluginCommand = {
2333
+ name: PluginCommandName;
2334
+ prompt: string;
2335
+ agentRefs?: PluginAgentName[];
2336
+ tools?: PluginToolName[];
2337
+ };
2338
+ type PluginAgent = {
2339
+ name: PluginAgentName;
2340
+ systemPrompt: string;
2341
+ description?: string;
2342
+ tools?: PluginToolName[];
2343
+ };
2344
+ type Plugin = {
2345
+ id: PluginId;
2346
+ url: PluginUrl;
2347
+ manifest: PluginManifest;
2348
+ commands: Record<string, PluginCommand>;
2349
+ agents: Record<string, PluginAgent>;
2350
+ rawFiles: Record<string, string>;
2351
+ ref: PluginGitHubRef;
2352
+ loadedAt: Date;
2353
+ };
2354
+ type PluginGitHubRef = {
2355
+ owner: string;
2356
+ repo: string;
2357
+ ref: string;
2358
+ path?: string;
2359
+ };
2360
+ type PluginRunConfig = {
2361
+ model?: string | ModelId;
2362
+ converterModel?: string | ModelId;
2363
+ orchestrationMode?: OrchestrationMode;
2364
+ userTask: string;
2365
+ toolRegistry?: ToolRegistry;
2366
+ runOptions?: RunsCreateOptions;
2367
+ };
2368
+ type PluginRunResult = {
2369
+ runId: RunId$1;
2370
+ status: RunStatusV0;
2371
+ outputs?: Record<string, unknown>;
2372
+ costSummary?: Record<string, unknown>;
2373
+ events: RunEventV0[];
2374
+ };
2375
+ type PluginLoaderOptions = {
2376
+ fetch?: typeof fetch;
2377
+ apiBaseUrl?: string;
2378
+ rawBaseUrl?: string;
2379
+ cacheTtlMs?: number;
2380
+ now?: () => Date;
2381
+ };
2382
+ type PluginConverterOptions = {
2383
+ converterModel?: string | ModelId;
2384
+ };
2385
+ type PluginsClientOptions = {
2386
+ fetch?: typeof fetch;
2387
+ apiBaseUrl?: string;
2388
+ rawBaseUrl?: string;
2389
+ cacheTtlMs?: number;
2390
+ now?: () => Date;
2391
+ };
2392
+ declare const PluginOrchestrationErrorCodes: {
2393
+ readonly InvalidPlan: "INVALID_PLAN";
2394
+ readonly UnknownAgent: "UNKNOWN_AGENT";
2395
+ readonly MissingDescription: "MISSING_DESCRIPTION";
2396
+ readonly UnknownTool: "UNKNOWN_TOOL";
2397
+ readonly InvalidDependency: "INVALID_DEPENDENCY";
2398
+ readonly InvalidToolConfig: "INVALID_TOOL_CONFIG";
2399
+ };
2400
+ type PluginOrchestrationErrorCode = (typeof PluginOrchestrationErrorCodes)[keyof typeof PluginOrchestrationErrorCodes];
2401
+ declare class PluginOrchestrationError extends Error {
2402
+ readonly code: PluginOrchestrationErrorCode;
2403
+ constructor(code: PluginOrchestrationErrorCode, message: string);
2404
+ }
2405
+ declare const orchestrationPlanSchema: z.ZodObject<{
2406
+ kind: z.ZodLiteral<"orchestration.plan.v1">;
2407
+ max_parallelism: z.ZodOptional<z.ZodNumber>;
2408
+ steps: z.ZodArray<z.ZodObject<{
2409
+ id: z.ZodOptional<z.ZodString>;
2410
+ depends_on: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
2411
+ agents: z.ZodArray<z.ZodObject<{
2412
+ id: z.ZodString;
2413
+ reason: z.ZodString;
2414
+ }, "strip", z.ZodTypeAny, {
2415
+ id: string;
2416
+ reason: string;
2417
+ }, {
2418
+ id: string;
2419
+ reason: string;
2420
+ }>, "many">;
2421
+ }, "strict", z.ZodTypeAny, {
2422
+ agents: {
2423
+ id: string;
2424
+ reason: string;
2425
+ }[];
2426
+ id?: string | undefined;
2427
+ depends_on?: string[] | undefined;
2428
+ }, {
2429
+ agents: {
2430
+ id: string;
2431
+ reason: string;
2432
+ }[];
2433
+ id?: string | undefined;
2434
+ depends_on?: string[] | undefined;
2435
+ }>, "many">;
2436
+ }, "strict", z.ZodTypeAny, {
2437
+ kind: "orchestration.plan.v1";
2438
+ steps: {
2439
+ agents: {
2440
+ id: string;
2441
+ reason: string;
2442
+ }[];
2443
+ id?: string | undefined;
2444
+ depends_on?: string[] | undefined;
2445
+ }[];
2446
+ max_parallelism?: number | undefined;
2447
+ }, {
2448
+ kind: "orchestration.plan.v1";
2449
+ steps: {
2450
+ agents: {
2451
+ id: string;
2452
+ reason: string;
2453
+ }[];
2454
+ id?: string | undefined;
2455
+ depends_on?: string[] | undefined;
2456
+ }[];
2457
+ max_parallelism?: number | undefined;
2458
+ }>;
2459
+ type OrchestrationPlan = z.infer<typeof orchestrationPlanSchema>;
2460
+ declare class PluginLoader {
2461
+ private readonly fetchFn;
2462
+ private readonly apiBaseUrl;
2463
+ private readonly rawBaseUrl;
2464
+ private readonly cacheTtlMs;
2465
+ private readonly now;
2466
+ private readonly cache;
2467
+ constructor(options?: PluginLoaderOptions);
2468
+ load(sourceUrl: string, options?: {
2469
+ signal?: AbortSignal;
2470
+ }): Promise<Plugin>;
2471
+ private listMarkdownFiles;
2472
+ private rawUrl;
2473
+ private fetchText;
2474
+ private fetchJson;
2475
+ }
2476
+ declare class PluginConverter {
2477
+ private readonly responses;
2478
+ private readonly http;
2479
+ private readonly auth;
2480
+ private readonly converterModel;
2481
+ constructor(responses: ResponsesClient, http: HTTPClient, auth: AuthClient, options?: PluginConverterOptions);
2482
+ toWorkflow(plugin: Plugin, commandName: string, task: string): Promise<WorkflowSpecIntentV1>;
2483
+ toWorkflowDynamic(plugin: Plugin, commandName: string, task: string): Promise<WorkflowSpecIntentV1>;
2484
+ }
2485
+ declare class PluginRunner {
2486
+ private readonly runs;
2487
+ constructor(runs: RunsClient);
2488
+ run(spec: WorkflowSpecIntentV1, config: PluginRunConfig): Promise<PluginRunResult>;
2489
+ wait(runId: RunId$1, config: PluginRunConfig): Promise<PluginRunResult>;
2490
+ }
2491
+ declare class PluginsClient {
2492
+ private readonly loader;
2493
+ private readonly converter;
2494
+ private readonly runner;
2495
+ private readonly responses;
2496
+ private readonly http;
2497
+ private readonly auth;
2498
+ constructor(deps: {
2499
+ responses: ResponsesClient;
2500
+ http: HTTPClient;
2501
+ auth: AuthClient;
2502
+ runs: RunsClient;
2503
+ options?: PluginsClientOptions;
2504
+ });
2505
+ load(url: string, options?: {
2506
+ signal?: AbortSignal;
2507
+ }): Promise<Plugin>;
2508
+ run(plugin: Plugin, command: string, config: PluginRunConfig): Promise<PluginRunResult>;
2509
+ quickRun(pluginUrl: string, command: string, userTask: string, config?: Omit<PluginRunConfig, "userTask">): Promise<PluginRunResult>;
2510
+ }
2511
+
2084
2512
  declare class CustomerResponsesClient {
2085
2513
  private readonly base;
2086
2514
  private readonly customerId;
@@ -2101,6 +2529,151 @@ declare class CustomerScopedModelRelay {
2101
2529
  constructor(responses: ResponsesClient, customerId: string, baseUrl: string);
2102
2530
  }
2103
2531
 
2532
+ /**
2533
+ * Fluent tool builder for defining tools with Zod schemas and handlers.
2534
+ *
2535
+ * This provides a more ergonomic way to define tools compared to using
2536
+ * createFunctionTool and ToolRegistry separately.
2537
+ */
2538
+
2539
+ /**
2540
+ * Fluent builder for defining tools with Zod schemas.
2541
+ *
2542
+ * Tools defined with this builder include both the JSON Schema for the API
2543
+ * and the handler function for execution, providing a single source of truth.
2544
+ *
2545
+ * @example
2546
+ * ```typescript
2547
+ * import { z } from "zod";
2548
+ *
2549
+ * const tools = new ToolBuilder()
2550
+ * .add(
2551
+ * "get_weather",
2552
+ * "Get current weather for a location",
2553
+ * z.object({ location: z.string().describe("City name") }),
2554
+ * async (args) => ({ temp: 72, unit: "fahrenheit" })
2555
+ * )
2556
+ * .add(
2557
+ * "read_file",
2558
+ * "Read a file from disk",
2559
+ * z.object({ path: z.string().describe("File path") }),
2560
+ * async (args) => fs.readFile(args.path, "utf-8")
2561
+ * );
2562
+ *
2563
+ * // Get the tool registry for use with LocalSession or mr.agent()
2564
+ * const registry = tools.registry();
2565
+ *
2566
+ * // Get tool definitions for use with ResponseBuilder
2567
+ * const defs = tools.definitions();
2568
+ * ```
2569
+ */
2570
+ declare class ToolBuilder {
2571
+ private entries;
2572
+ /**
2573
+ * Add a tool with a Zod schema and handler.
2574
+ *
2575
+ * The handler receives parsed and validated arguments matching the schema.
2576
+ *
2577
+ * @param name - Tool name (must be unique)
2578
+ * @param description - Human-readable description of what the tool does
2579
+ * @param schema - Zod schema for the tool's parameters
2580
+ * @param handler - Function to execute when the tool is called
2581
+ * @returns this for chaining
2582
+ *
2583
+ * @example
2584
+ * ```typescript
2585
+ * tools.add(
2586
+ * "search_web",
2587
+ * "Search the web for information",
2588
+ * z.object({
2589
+ * query: z.string().describe("Search query"),
2590
+ * maxResults: z.number().optional().describe("Max results to return"),
2591
+ * }),
2592
+ * async (args) => {
2593
+ * // args is typed as { query: string; maxResults?: number }
2594
+ * return await searchAPI(args.query, args.maxResults);
2595
+ * }
2596
+ * );
2597
+ * ```
2598
+ */
2599
+ add<S extends AnySchema, R>(name: string, description: string, schema: S, handler: (args: S extends {
2600
+ parse(data: unknown): infer T;
2601
+ } ? T : unknown, call: ToolCall) => R | Promise<R>): this;
2602
+ /**
2603
+ * Get tool definitions for use with ResponseBuilder.tools().
2604
+ *
2605
+ * @example
2606
+ * ```typescript
2607
+ * const response = await mr.responses.create(
2608
+ * mr.responses.new()
2609
+ * .model("claude-sonnet-4-5")
2610
+ * .tools(tools.definitions())
2611
+ * .user("What's the weather in Paris?")
2612
+ * .build()
2613
+ * );
2614
+ * ```
2615
+ */
2616
+ definitions(): Tool[];
2617
+ /**
2618
+ * Get a ToolRegistry with all handlers registered.
2619
+ *
2620
+ * The handlers are wrapped to validate arguments against the schema
2621
+ * before invoking the user's handler. If validation fails, a
2622
+ * ToolArgsError is thrown (which ToolRegistry marks as retryable).
2623
+ *
2624
+ * Note: For mr.agent(), pass the ToolBuilder directly instead of calling
2625
+ * registry(). The agent method extracts both definitions and registry.
2626
+ *
2627
+ * @example
2628
+ * ```typescript
2629
+ * const registry = tools.registry();
2630
+ *
2631
+ * // Use with LocalSession (also pass definitions via defaultTools)
2632
+ * const session = mr.sessions.createLocal({
2633
+ * toolRegistry: registry,
2634
+ * defaultTools: tools.definitions(),
2635
+ * defaultModel: "claude-sonnet-4-5",
2636
+ * });
2637
+ * ```
2638
+ */
2639
+ registry(): ToolRegistry;
2640
+ /**
2641
+ * Get both definitions and registry.
2642
+ *
2643
+ * Useful when you need both for manual tool handling.
2644
+ *
2645
+ * @example
2646
+ * ```typescript
2647
+ * const { definitions, registry } = tools.build();
2648
+ *
2649
+ * const response = await mr.responses.create(
2650
+ * mr.responses.new()
2651
+ * .model("claude-sonnet-4-5")
2652
+ * .tools(definitions)
2653
+ * .user("What's the weather?")
2654
+ * .build()
2655
+ * );
2656
+ *
2657
+ * if (hasToolCalls(response)) {
2658
+ * const results = await registry.executeAll(response.output[0].toolCalls!);
2659
+ * // ...
2660
+ * }
2661
+ * ```
2662
+ */
2663
+ build(): {
2664
+ definitions: Tool[];
2665
+ registry: ToolRegistry;
2666
+ };
2667
+ /**
2668
+ * Get the number of tools defined.
2669
+ */
2670
+ get size(): number;
2671
+ /**
2672
+ * Check if a tool is defined.
2673
+ */
2674
+ has(name: string): boolean;
2675
+ }
2676
+
2104
2677
  declare class CustomerTokenProvider implements TokenProvider {
2105
2678
  private readonly auth;
2106
2679
  private readonly req;
@@ -2253,9 +2826,11 @@ type WorkflowIntentEdge = {
2253
2826
  type WorkflowIntentBuilderState = {
2254
2827
  readonly name?: string;
2255
2828
  readonly model?: string;
2829
+ readonly maxParallelism?: number;
2830
+ readonly inputs?: ReadonlyArray<WorkflowInputDeclIntentV1>;
2256
2831
  readonly nodes: ReadonlyArray<WorkflowIntentNode>;
2257
2832
  readonly edges: ReadonlyArray<WorkflowIntentEdge>;
2258
- readonly outputs: ReadonlyArray<WorkflowOutputRefLiteV1>;
2833
+ readonly outputs: ReadonlyArray<WorkflowOutputRefIntentV1>;
2259
2834
  };
2260
2835
  declare class WorkflowIntentBuilder {
2261
2836
  private readonly state;
@@ -2263,6 +2838,8 @@ declare class WorkflowIntentBuilder {
2263
2838
  private with;
2264
2839
  name(name: string): WorkflowIntentBuilder;
2265
2840
  model(model: string): WorkflowIntentBuilder;
2841
+ maxParallelism(n: number): WorkflowIntentBuilder;
2842
+ inputs(decls: ReadonlyArray<WorkflowInputDeclIntentV1>): WorkflowIntentBuilder;
2266
2843
  node(node: WorkflowIntentNode): WorkflowIntentBuilder;
2267
2844
  llm(id: NodeId$1, configure?: (node: LLMNodeBuilder) => LLMNodeBuilder): WorkflowIntentBuilder;
2268
2845
  joinAll(id: NodeId$1): WorkflowIntentBuilder;
@@ -2282,7 +2859,7 @@ declare class WorkflowIntentBuilder {
2282
2859
  }): WorkflowIntentBuilder;
2283
2860
  edge(from: NodeId$1, to: NodeId$1): WorkflowIntentBuilder;
2284
2861
  output(name: OutputName$1, from: NodeId$1, pointer?: string): WorkflowIntentBuilder;
2285
- build(): WorkflowSpecLiteV1;
2862
+ build(): WorkflowSpecIntentV1;
2286
2863
  }
2287
2864
  declare class LLMNodeBuilder {
2288
2865
  private readonly node;
@@ -2355,7 +2932,7 @@ type ParallelOptions = {
2355
2932
  declare function parallel(steps: WorkflowIntentNode[], options?: ParallelOptions): WorkflowIntentBuilder;
2356
2933
 
2357
2934
  declare const WORKFLOWS_COMPILE_PATH = "/workflows/compile";
2358
- type WorkflowsCompileRequest = WorkflowSpecLiteV1;
2935
+ type WorkflowsCompileRequest = WorkflowSpecIntentV1;
2359
2936
 
2360
2937
  type NDJSONDelayStep = {
2361
2938
  delayMs: number;
@@ -2377,6 +2954,62 @@ declare function parseApiKey(raw: string): ApiKey;
2377
2954
  declare function parseSecretKey(raw: string): SecretKey;
2378
2955
  declare function isSecretKey(key: ApiKey): key is SecretKey;
2379
2956
 
2957
+ type ToolLoopUsage = {
2958
+ inputTokens: number;
2959
+ outputTokens: number;
2960
+ totalTokens: number;
2961
+ llmCalls: number;
2962
+ toolCalls: number;
2963
+ };
2964
+ type ToolLoopComplete = {
2965
+ status: "complete";
2966
+ output: string;
2967
+ response: Response$1;
2968
+ usage: ToolLoopUsage;
2969
+ input: InputItem[];
2970
+ turnsUsed: number;
2971
+ };
2972
+ type ToolLoopWaiting = {
2973
+ status: "waiting_for_tools";
2974
+ pendingToolCalls: ToolCall[];
2975
+ response: Response$1;
2976
+ usage: ToolLoopUsage;
2977
+ input: InputItem[];
2978
+ turnsUsed: number;
2979
+ };
2980
+ type ToolLoopOutcome = ToolLoopComplete | ToolLoopWaiting;
2981
+ type ToolLoopConfig = {
2982
+ client: ResponsesClient;
2983
+ input: InputItem[];
2984
+ tools?: Tool[];
2985
+ registry?: ToolRegistry;
2986
+ maxTurns?: number;
2987
+ requestOptions?: ResponsesRequestOptions;
2988
+ buildRequest?: (builder: ResponseBuilder) => ResponseBuilder;
2989
+ };
2990
+ declare function runToolLoop(config: ToolLoopConfig): Promise<ToolLoopOutcome>;
2991
+
2992
+ declare const USER_ASK_TOOL_NAME = "user.ask";
2993
+ type UserAskOption = {
2994
+ label: string;
2995
+ description?: string;
2996
+ };
2997
+ type UserAskArgs = {
2998
+ question: string;
2999
+ options?: UserAskOption[];
3000
+ allow_freeform?: boolean;
3001
+ };
3002
+ type UserAskResponse = {
3003
+ answer: string;
3004
+ is_freeform: boolean;
3005
+ };
3006
+ declare function createUserAskTool(): Tool;
3007
+ declare function isUserAskToolCall(call: ToolCall): boolean;
3008
+ declare function parseUserAskArgs(call: ToolCall): UserAskArgs;
3009
+ declare function serializeUserAskResult(result: UserAskResponse): string;
3010
+ declare function userAskResultFreeform(answer: string): string;
3011
+ declare function userAskResultChoice(answer: string): string;
3012
+
2380
3013
  /**
2381
3014
  * Tool runner for executing client-side tools in workflow runs.
2382
3015
  *
@@ -2400,6 +3033,8 @@ interface ToolRunnerOptions {
2400
3033
  onAfterExecute?: (result: ToolExecutionResult) => void | Promise<void>;
2401
3034
  /** Called when results are successfully submitted (optional). */
2402
3035
  onSubmitted?: (runId: RunId$1, count: number, status: RunStatusV0) => void | Promise<void>;
3036
+ /** Called when a user.ask tool needs a response (optional). */
3037
+ onUserAsk?: (pending: PendingToolCallV0$1, args: UserAskArgs) => Promise<UserAskResponse | string> | UserAskResponse | string;
2403
3038
  /** Called when an error occurs during execution (optional). */
2404
3039
  onError?: (error: Error, pending?: PendingToolCallV0$1) => void | Promise<void>;
2405
3040
  }
@@ -2445,6 +3080,7 @@ declare class ToolRunner {
2445
3080
  private readonly onBeforeExecute?;
2446
3081
  private readonly onAfterExecute?;
2447
3082
  private readonly onSubmitted?;
3083
+ private readonly onUserAsk?;
2448
3084
  private readonly onError?;
2449
3085
  constructor(options: ToolRunnerOptions);
2450
3086
  /**
@@ -2537,15 +3173,15 @@ declare namespace index$1 {
2537
3173
  }
2538
3174
 
2539
3175
  /**
2540
- * Workflow.lite.v1 types with clean naming (no Workflow prefix).
3176
+ * Workflow intent types with clean naming (no Workflow prefix).
2541
3177
  *
2542
3178
  * @example
2543
3179
  * ```typescript
2544
3180
  * import { workflow } from "@modelrelay/sdk";
2545
3181
  *
2546
- * const spec: workflow.SpecLiteV1 = {
3182
+ * const spec: workflow.SpecIntentV1 = {
2547
3183
  * kind: workflow.KindIntent,
2548
- * nodes: [{ id: "my_node", type: workflow.NodeTypesLite.LLM, user: "hello" }],
3184
+ * nodes: [{ id: "my_node", type: workflow.NodeTypesIntent.LLM, user: "hello" }],
2549
3185
  * outputs: [],
2550
3186
  * };
2551
3187
  * ```
@@ -2557,9 +3193,9 @@ type RunId = RunId$1;
2557
3193
  type PlanHash = PlanHash$1;
2558
3194
 
2559
3195
  type Kind = WorkflowKind;
2560
- type SpecLiteV1 = WorkflowSpecLiteV1;
3196
+ type SpecIntentV1 = WorkflowSpecIntentV1;
2561
3197
  type IntentNode = WorkflowIntentNode;
2562
- type OutputRefLiteV1 = WorkflowOutputRefLiteV1;
3198
+ type OutputRefIntentV1 = WorkflowOutputRefIntentV1;
2563
3199
  type Condition = WorkflowIntentCondition;
2564
3200
  type ConditionOp = WorkflowIntentConditionOp;
2565
3201
  type ConditionSource = WorkflowIntentConditionSource;
@@ -2595,7 +3231,7 @@ type PayloadInfoV0 = PayloadInfoV0$1;
2595
3231
  type PayloadArtifactV0 = PayloadArtifactV0$1;
2596
3232
  type StreamEventKind = StreamEventKind$1;
2597
3233
  declare const KindIntent: "workflow";
2598
- declare const NodeTypesLite: {
3234
+ declare const NodeTypesIntent: {
2599
3235
  readonly LLM: "llm";
2600
3236
  readonly JoinAll: "join.all";
2601
3237
  readonly JoinAny: "join.any";
@@ -2603,7 +3239,7 @@ declare const NodeTypesLite: {
2603
3239
  readonly TransformJSON: "transform.json";
2604
3240
  readonly MapFanout: "map.fanout";
2605
3241
  };
2606
- type NodeTypeLite = (typeof NodeTypesLite)[keyof typeof NodeTypesLite];
3242
+ type NodeTypeIntent = (typeof NodeTypesIntent)[keyof typeof NodeTypesIntent];
2607
3243
 
2608
3244
  type index_Condition = Condition;
2609
3245
  type index_ConditionOp = ConditionOp;
@@ -2638,17 +3274,17 @@ type index_NodeLLMCallV0 = NodeLLMCallV0;
2638
3274
  type index_NodeOutputDeltaV0 = NodeOutputDeltaV0;
2639
3275
  type index_NodeToolCallV0 = NodeToolCallV0;
2640
3276
  type index_NodeToolResultV0 = NodeToolResultV0;
2641
- type index_NodeTypeLite = NodeTypeLite;
2642
- declare const index_NodeTypesLite: typeof NodeTypesLite;
3277
+ type index_NodeTypeIntent = NodeTypeIntent;
3278
+ declare const index_NodeTypesIntent: typeof NodeTypesIntent;
2643
3279
  type index_NodeWaitingV0 = NodeWaitingV0;
2644
3280
  type index_OutputName = OutputName;
2645
- type index_OutputRefLiteV1 = OutputRefLiteV1;
3281
+ type index_OutputRefIntentV1 = OutputRefIntentV1;
2646
3282
  type index_PayloadArtifactV0 = PayloadArtifactV0;
2647
3283
  type index_PayloadInfoV0 = PayloadInfoV0;
2648
3284
  type index_PendingToolCallV0 = PendingToolCallV0;
2649
3285
  type index_PlanHash = PlanHash;
2650
3286
  type index_RunId = RunId;
2651
- type index_SpecLiteV1 = SpecLiteV1;
3287
+ type index_SpecIntentV1 = SpecIntentV1;
2652
3288
  type index_StatusV0 = StatusV0;
2653
3289
  type index_StreamEventKind = StreamEventKind;
2654
3290
  type index_TokenUsageV0 = TokenUsageV0;
@@ -2662,11 +3298,11 @@ declare const index_parsePlanHash: typeof parsePlanHash;
2662
3298
  declare const index_parseRunId: typeof parseRunId;
2663
3299
  declare const index_workflowIntent: typeof workflowIntent;
2664
3300
  declare namespace index {
2665
- export { type index_Condition as Condition, type index_ConditionOp as ConditionOp, type index_ConditionSource as ConditionSource, type index_EventBaseV0 as EventBaseV0, type index_EventNodeFailedV0 as EventNodeFailedV0, type index_EventNodeLLMCallV0 as EventNodeLLMCallV0, type index_EventNodeOutputDeltaV0 as EventNodeOutputDeltaV0, type index_EventNodeOutputV0 as EventNodeOutputV0, type index_EventNodeStartedV0 as EventNodeStartedV0, type index_EventNodeSucceededV0 as EventNodeSucceededV0, type index_EventNodeToolCallV0 as EventNodeToolCallV0, type index_EventNodeToolResultV0 as EventNodeToolResultV0, type index_EventNodeWaitingV0 as EventNodeWaitingV0, type index_EventRunCanceledV0 as EventRunCanceledV0, type index_EventRunCompiledV0 as EventRunCompiledV0, type index_EventRunCompletedV0 as EventRunCompletedV0, type index_EventRunFailedV0 as EventRunFailedV0, type index_EventRunStartedV0 as EventRunStartedV0, type index_EventTypeV0 as EventTypeV0, type index_EventV0 as EventV0, type index_IntentNode as IntentNode, type index_Kind as Kind, index_KindIntent as KindIntent, index_LLMNodeBuilder as LLMNodeBuilder, index_LLM_TEXT_OUTPUT as LLM_TEXT_OUTPUT, index_LLM_USER_MESSAGE_TEXT as LLM_USER_MESSAGE_TEXT, type index_NodeErrorV0 as NodeErrorV0, type index_NodeId as NodeId, type index_NodeLLMCallV0 as NodeLLMCallV0, type index_NodeOutputDeltaV0 as NodeOutputDeltaV0, type index_NodeToolCallV0 as NodeToolCallV0, type index_NodeToolResultV0 as NodeToolResultV0, type index_NodeTypeLite as NodeTypeLite, index_NodeTypesLite as NodeTypesLite, type index_NodeWaitingV0 as NodeWaitingV0, type index_OutputName as OutputName, type index_OutputRefLiteV1 as OutputRefLiteV1, type index_PayloadArtifactV0 as PayloadArtifactV0, type index_PayloadInfoV0 as PayloadInfoV0, type index_PendingToolCallV0 as PendingToolCallV0, type index_PlanHash as PlanHash, type index_RunId as RunId, type index_SpecLiteV1 as SpecLiteV1, type index_StatusV0 as StatusV0, type index_StreamEventKind as StreamEventKind, type index_TokenUsageV0 as TokenUsageV0, type index_ToolCallV0 as ToolCallV0, type index_ToolCallWithArgumentsV0 as ToolCallWithArgumentsV0, index_WorkflowIntentBuilder as WorkflowIntentBuilder, index_parseNodeId as parseNodeId, index_parseOutputName as parseOutputName, index_parsePlanHash as parsePlanHash, index_parseRunId as parseRunId, index_workflowIntent as workflowIntent };
3301
+ export { type index_Condition as Condition, type index_ConditionOp as ConditionOp, type index_ConditionSource as ConditionSource, type index_EventBaseV0 as EventBaseV0, type index_EventNodeFailedV0 as EventNodeFailedV0, type index_EventNodeLLMCallV0 as EventNodeLLMCallV0, type index_EventNodeOutputDeltaV0 as EventNodeOutputDeltaV0, type index_EventNodeOutputV0 as EventNodeOutputV0, type index_EventNodeStartedV0 as EventNodeStartedV0, type index_EventNodeSucceededV0 as EventNodeSucceededV0, type index_EventNodeToolCallV0 as EventNodeToolCallV0, type index_EventNodeToolResultV0 as EventNodeToolResultV0, type index_EventNodeWaitingV0 as EventNodeWaitingV0, type index_EventRunCanceledV0 as EventRunCanceledV0, type index_EventRunCompiledV0 as EventRunCompiledV0, type index_EventRunCompletedV0 as EventRunCompletedV0, type index_EventRunFailedV0 as EventRunFailedV0, type index_EventRunStartedV0 as EventRunStartedV0, type index_EventTypeV0 as EventTypeV0, type index_EventV0 as EventV0, type index_IntentNode as IntentNode, type index_Kind as Kind, index_KindIntent as KindIntent, index_LLMNodeBuilder as LLMNodeBuilder, index_LLM_TEXT_OUTPUT as LLM_TEXT_OUTPUT, index_LLM_USER_MESSAGE_TEXT as LLM_USER_MESSAGE_TEXT, type index_NodeErrorV0 as NodeErrorV0, type index_NodeId as NodeId, type index_NodeLLMCallV0 as NodeLLMCallV0, type index_NodeOutputDeltaV0 as NodeOutputDeltaV0, type index_NodeToolCallV0 as NodeToolCallV0, type index_NodeToolResultV0 as NodeToolResultV0, type index_NodeTypeIntent as NodeTypeIntent, index_NodeTypesIntent as NodeTypesIntent, type index_NodeWaitingV0 as NodeWaitingV0, type index_OutputName as OutputName, type index_OutputRefIntentV1 as OutputRefIntentV1, type index_PayloadArtifactV0 as PayloadArtifactV0, type index_PayloadInfoV0 as PayloadInfoV0, type index_PendingToolCallV0 as PendingToolCallV0, type index_PlanHash as PlanHash, type index_RunId as RunId, type index_SpecIntentV1 as SpecIntentV1, type index_StatusV0 as StatusV0, type index_StreamEventKind as StreamEventKind, type index_TokenUsageV0 as TokenUsageV0, type index_ToolCallV0 as ToolCallV0, type index_ToolCallWithArgumentsV0 as ToolCallWithArgumentsV0, index_WorkflowIntentBuilder as WorkflowIntentBuilder, index_parseNodeId as parseNodeId, index_parseOutputName as parseOutputName, index_parsePlanHash as parsePlanHash, index_parseRunId as parseRunId, index_workflowIntent as workflowIntent };
2666
3302
  }
2667
3303
 
2668
3304
  /**
2669
- * In-memory session store.
3305
+ * In-memory conversation store.
2670
3306
  *
2671
3307
  * Session data is lost when the process exits. Use for:
2672
3308
  * - Development/testing
@@ -2677,14 +3313,14 @@ declare namespace index {
2677
3313
  */
2678
3314
 
2679
3315
  /**
2680
- * In-memory implementation of SessionStore.
3316
+ * In-memory implementation of ConversationStore.
2681
3317
  *
2682
3318
  * All operations are synchronous but wrapped in promises for interface compatibility.
2683
3319
  */
2684
- declare class MemorySessionStore implements SessionStore {
3320
+ declare class MemoryConversationStore implements ConversationStore {
2685
3321
  private readonly sessions;
2686
- load(id: SessionId): Promise<SessionState | null>;
2687
- save(state: SessionState): Promise<void>;
3322
+ load(id: SessionId): Promise<ConversationState | null>;
3323
+ save(state: ConversationState): Promise<void>;
2688
3324
  delete(id: SessionId): Promise<void>;
2689
3325
  list(): Promise<SessionId[]>;
2690
3326
  close(): Promise<void>;
@@ -2695,9 +3331,48 @@ declare class MemorySessionStore implements SessionStore {
2695
3331
  get size(): number;
2696
3332
  }
2697
3333
  /**
2698
- * Create a new in-memory session store.
3334
+ * Create a new in-memory conversation store.
3335
+ */
3336
+ declare function createMemoryConversationStore(): MemoryConversationStore;
3337
+
3338
+ /**
3339
+ * File-based conversation store (Node.js/Bun only).
3340
+ */
3341
+
3342
+ declare class FileConversationStore implements ConversationStore {
3343
+ private readonly storagePath?;
3344
+ constructor(storagePath?: string);
3345
+ load(id: SessionId): Promise<ConversationState | null>;
3346
+ save(state: ConversationState): Promise<void>;
3347
+ delete(id: SessionId): Promise<void>;
3348
+ list(): Promise<SessionId[]>;
3349
+ close(): Promise<void>;
3350
+ private resolveSessionPath;
3351
+ private resolveSessionDir;
3352
+ }
3353
+ declare function createFileConversationStore(storagePath?: string): FileConversationStore;
3354
+
3355
+ /**
3356
+ * SQLite-backed conversation store (Node.js/Bun only).
2699
3357
  */
2700
- declare function createMemorySessionStore(): MemorySessionStore;
3358
+
3359
+ declare class SqliteConversationStore implements ConversationStore {
3360
+ private readonly storagePath?;
3361
+ private db?;
3362
+ private initPromise?;
3363
+ private statements?;
3364
+ constructor(storagePath?: string);
3365
+ load(id: SessionId): Promise<ConversationState | null>;
3366
+ save(state: ConversationState): Promise<void>;
3367
+ delete(id: SessionId): Promise<void>;
3368
+ list(): Promise<SessionId[]>;
3369
+ close(): Promise<void>;
3370
+ private ensureInitialized;
3371
+ private getStatements;
3372
+ private initialize;
3373
+ private resolveDbPath;
3374
+ }
3375
+ declare function createSqliteConversationStore(storagePath?: string): SqliteConversationStore;
2701
3376
 
2702
3377
  declare class ModelRelay {
2703
3378
  readonly responses: ResponsesClient;
@@ -2706,7 +3381,9 @@ declare class ModelRelay {
2706
3381
  readonly images: ImagesClient;
2707
3382
  readonly auth: AuthClient;
2708
3383
  readonly sessions: SessionsClient;
3384
+ readonly stateHandles: StateHandlesClient;
2709
3385
  readonly tiers: TiersClient;
3386
+ readonly plugins: PluginsClient;
2710
3387
  readonly baseUrl: string;
2711
3388
  /** @internal HTTP client for internal use by session sync */
2712
3389
  readonly http: HTTPClient;
@@ -2714,6 +3391,138 @@ declare class ModelRelay {
2714
3391
  static fromApiKey(apiKey: string, options?: Omit<ModelRelayKeyOptions, "key">): ModelRelay;
2715
3392
  constructor(options: ModelRelayOptions);
2716
3393
  forCustomer(customerId: string): CustomerScopedModelRelay;
3394
+ /** Default maximum turns for agent loops. */
3395
+ static readonly DEFAULT_MAX_TURNS = 100;
3396
+ /**
3397
+ * Use this for maxTurns to disable the turn limit.
3398
+ * Use with caution as this can lead to infinite loops and runaway API costs.
3399
+ */
3400
+ static readonly NO_TURN_LIMIT: number;
3401
+ /**
3402
+ * Simple chat completion with system and user prompt.
3403
+ *
3404
+ * Returns the full Response object for access to usage, model, etc.
3405
+ *
3406
+ * @example
3407
+ * ```typescript
3408
+ * const response = await mr.chat("claude-sonnet-4-5", "Hello!");
3409
+ * console.log(response.output);
3410
+ * console.log(response.usage);
3411
+ * ```
3412
+ *
3413
+ * @example With system prompt
3414
+ * ```typescript
3415
+ * const response = await mr.chat("claude-sonnet-4-5", "Explain quantum computing", {
3416
+ * system: "You are a physics professor",
3417
+ * });
3418
+ * ```
3419
+ */
3420
+ chat(model: string | ModelId, prompt: string, options?: {
3421
+ system?: string;
3422
+ customerId?: string;
3423
+ } & ResponsesRequestOptions): Promise<Response$1>;
3424
+ /**
3425
+ * Simple prompt that returns just the text response.
3426
+ *
3427
+ * The most ergonomic way to get a quick answer.
3428
+ *
3429
+ * @example
3430
+ * ```typescript
3431
+ * const answer = await mr.ask("claude-sonnet-4-5", "What is 2 + 2?");
3432
+ * console.log(answer); // "4"
3433
+ * ```
3434
+ *
3435
+ * @example With system prompt
3436
+ * ```typescript
3437
+ * const haiku = await mr.ask("claude-sonnet-4-5", "Write about the ocean", {
3438
+ * system: "You are a poet who only writes haikus",
3439
+ * });
3440
+ * ```
3441
+ */
3442
+ ask(model: string | ModelId, prompt: string, options?: {
3443
+ system?: string;
3444
+ customerId?: string;
3445
+ } & ResponsesRequestOptions): Promise<string>;
3446
+ /**
3447
+ * Run an agentic tool loop to completion.
3448
+ *
3449
+ * Runs API calls in a loop until the model stops calling tools
3450
+ * or maxTurns is reached.
3451
+ *
3452
+ * @example
3453
+ * ```typescript
3454
+ * import { z } from "zod";
3455
+ *
3456
+ * const tools = mr.tools()
3457
+ * .add("read_file", "Read a file", z.object({ path: z.string() }), async (args) => {
3458
+ * return fs.readFile(args.path, "utf-8");
3459
+ * })
3460
+ * .add("write_file", "Write a file", z.object({ path: z.string(), content: z.string() }), async (args) => {
3461
+ * await fs.writeFile(args.path, args.content);
3462
+ * return "File written successfully";
3463
+ * });
3464
+ *
3465
+ * const result = await mr.agent("claude-sonnet-4-5", {
3466
+ * tools,
3467
+ * prompt: "Read config.json and add a version field",
3468
+ * });
3469
+ *
3470
+ * console.log(result.output); // Final text response
3471
+ * console.log(result.usage); // Total tokens used
3472
+ * ```
3473
+ *
3474
+ * @example With system prompt and maxTurns
3475
+ * ```typescript
3476
+ * const result = await mr.agent("claude-sonnet-4-5", {
3477
+ * tools,
3478
+ * prompt: "Refactor the auth module",
3479
+ * system: "You are a senior TypeScript developer",
3480
+ * maxTurns: 50, // or ModelRelay.NO_TURN_LIMIT for unlimited
3481
+ * });
3482
+ * ```
3483
+ */
3484
+ agent(model: string | ModelId, options: {
3485
+ tools: ToolBuilder;
3486
+ prompt: string;
3487
+ system?: string;
3488
+ maxTurns?: number;
3489
+ }): Promise<{
3490
+ output: string;
3491
+ usage: {
3492
+ inputTokens: number;
3493
+ outputTokens: number;
3494
+ totalTokens: number;
3495
+ llmCalls: number;
3496
+ toolCalls: number;
3497
+ };
3498
+ response: Response$1;
3499
+ }>;
3500
+ /**
3501
+ * Creates a fluent tool builder for defining tools with Zod schemas.
3502
+ *
3503
+ * @example
3504
+ * ```typescript
3505
+ * import { z } from "zod";
3506
+ *
3507
+ * const tools = mr.tools()
3508
+ * .add("get_weather", "Get current weather", z.object({ location: z.string() }), async (args) => {
3509
+ * return { temp: 72, unit: "fahrenheit" };
3510
+ * })
3511
+ * .add("read_file", "Read a file", z.object({ path: z.string() }), async (args) => {
3512
+ * return fs.readFile(args.path, "utf-8");
3513
+ * });
3514
+ *
3515
+ * // Use with agent (pass ToolBuilder directly)
3516
+ * const result = await mr.agent("claude-sonnet-4-5", {
3517
+ * tools,
3518
+ * prompt: "What's the weather in Paris?",
3519
+ * });
3520
+ *
3521
+ * // Or get tool definitions for manual use
3522
+ * const toolDefs = tools.definitions();
3523
+ * ```
3524
+ */
3525
+ tools(): ToolBuilder;
2717
3526
  }
2718
3527
 
2719
- export { APIError, ApiKey, type AttemptRecord, AuthClient, type AuthHeaders, type ChainOptions, ConfigError, CustomerResponsesClient, CustomerScopedModelRelay, CustomerToken, CustomerTokenProvider, CustomerTokenRequest, type ErrorCategory, type ErrorCode, ErrorCodes, FieldError, GetOrCreateCustomerTokenRequest, type HandleWaitingResult, type ImageData, type ImagePinResponse, type ImageRequest, type ImageResponse, type ImageResponseFormat, type ImageUsage, ImagesClient, InputItem, type JSONPointer, JoinOutput, JoinOutputPath, LLMInput, LLMInputContentItemPath, LLMInputFirstMessageText, LLMInputMessagePath, LLMInputPath, LLMInputSystemText, LLMInputUserText, LLMNodeBuilder, LLMOutput, LLMOutputContentItemPath, LLMOutputContentPath, LLMOutputPath, LLMOutputText, LLM_TEXT_OUTPUT, LLM_USER_MESSAGE_TEXT, type ListSessionsOptions, type ListSessionsResponse, LocalSession, type LocalSessionOptions, type LocalSessionPersistence, MemorySessionStore, MetricsCallbacks, type MockFetchCall, type MockFetchResponder, ModelId, ModelRelay, ModelRelayError, ModelRelayKeyOptions, ModelRelayOptions, type NDJSONDelayStep, type NodeErrorV0$1 as NodeErrorV0, type NodeId$1 as NodeId, OutputFormat, type OutputName$1 as OutputName, type ParallelOptions, PathEscapeError, type PayloadInfoV0$1 as PayloadInfoV0, type PlanHash$1 as PlanHash, type PriceInterval, ProviderId, type RemoteSessionInfo, type RemoteSessionOptions, RequestContext, Response$1 as Response, ResponseEvent, ResponsesClient, ResponsesStream, RetryConfig, type RetryHandler, RetryMetadata, type RunEventTypeV0, type RunEventV0, type RunId$1 as RunId, type RunStatusV0, RunsClient, RunsEventStream, SecretKey, type Session, type SessionArtifacts, type SessionContextManagement, type SessionContextTruncateInfo, type SessionId, type SessionMessage, type SessionPendingToolCall, type SessionRunOptions, type SessionRunResult, type SessionRunStatus, type SessionState, type SessionStore, type SessionSyncOptions, type SessionSyncResult, type SessionType, type SessionUsageSummary, SessionsClient, StreamProtocolError, StreamTimeoutError, type StreamTimeoutKind, StructuredDecodeError, type StructuredErrorKind, StructuredExhaustedError, StructuredJSONEvent, StructuredJSONStream, type StructuredOptions, type StructuredResult, type Tier, type TierCheckoutRequest, type TierCheckoutSession, TierCode, type TierModel, TiersClient, TokenProvider, Tool, ToolArgumentError, ToolChoice, ToolExecutionResult, ToolRegistry, ToolRunner, type ToolRunnerOptions, TraceCallbacks, TransportError, TransportErrorKind, type ValidationIssue, WORKFLOWS_COMPILE_PATH, WorkflowIntentBuilder, type WorkflowIntentBuilderState, type WorkflowKind, WorkflowKinds, WorkflowNodeTypesLite as WorkflowNodeTypes, WorkflowNodeTypesLite, WorkflowValidationError, type WorkflowValidationIssue, WorkflowsClient, type WorkflowsCompileOptions, type WorkflowsCompileRequest, type WorkflowsCompileResponse, type WorkflowsCompileResult, ZodLikeSchema, asSessionId, buildDelayedNDJSONResponse, buildNDJSONResponse, chain, createAccessTokenAuth, createApiKeyAuth, createLocalSession, createMemorySessionStore, createMockFetchQueue, createToolRunner, defaultRetryHandler, defaultTierModelId, generateSessionId, index$1 as generated, isSecretKey, llm, outputFormatFromZod, parallel, parseApiKey, parseErrorResponse, parseNodeId, parseOutputName, parsePlanHash, parseRunId, parseSecretKey, validateWithZod, index as workflow, workflowIntent };
3528
+ export { APIError, AgentMaxTurnsError, ApiKey, type AttemptRecord, AuthClient, type AuthHeaders, type ChainOptions, ConfigError, type ContextManagementStrategy, ContextManager, type ContextManagerOptions, type ContextPrepareOptions, type ContextTruncateInfo, type ConversationState, type ConversationStore, CustomerResponsesClient, CustomerScopedModelRelay, CustomerToken, CustomerTokenProvider, CustomerTokenRequest, type ErrorCategory, type ErrorCode, ErrorCodes, FieldError, FileConversationStore, GetOrCreateCustomerTokenRequest, type HandleWaitingResult, type ImageData, type ImagePinResponse, type ImageRequest, type ImageResponse, type ImageResponseFormat, type ImageUsage, ImagesClient, InputItem, type JSONPointer, JoinOutput, JoinOutputPath, LLMInput, LLMInputContentItemPath, LLMInputFirstMessageText, LLMInputMessagePath, LLMInputPath, LLMInputSystemText, LLMInputUserText, LLMNodeBuilder, LLMOutput, LLMOutputContentItemPath, LLMOutputContentPath, LLMOutputPath, LLMOutputText, LLM_TEXT_OUTPUT, LLM_USER_MESSAGE_TEXT, type ListSessionsOptions, type ListSessionsResponse, LocalSession, type LocalSessionOptions, type LocalSessionPersistence, MAX_STATE_HANDLE_TTL_SECONDS, MemoryConversationStore, MetricsCallbacks, type MockFetchCall, type MockFetchResponder, type ModelContextResolver, type ModelContextWindow, ModelId, ModelRelay, ModelRelayError, ModelRelayKeyOptions, ModelRelayOptions, type NDJSONDelayStep, type NodeErrorV0$1 as NodeErrorV0, type NodeId$1 as NodeId, type OrchestrationMode, OrchestrationModes, type OrchestrationPlan, OutputFormat, type OutputName$1 as OutputName, type ParallelOptions, PathEscapeError, type PayloadInfoV0$1 as PayloadInfoV0, type PlanHash$1 as PlanHash, type Plugin, type PluginAgent, type PluginAgentName, type PluginCommand, type PluginCommandName, PluginConverter, type PluginConverterOptions, type PluginGitHubRef, type PluginId, PluginLoader, type PluginLoaderOptions, type PluginManifest, PluginOrchestrationError, type PluginOrchestrationErrorCode, PluginOrchestrationErrorCodes, type PluginRunConfig, type PluginRunResult, PluginRunner, type PluginToolName, PluginToolNames, type PluginUrl, PluginsClient, type PluginsClientOptions, type PriceInterval, ProviderId, type RemoteSessionInfo, type RemoteSessionOptions, RequestContext, Response$1 as Response, ResponseEvent, ResponsesClient, ResponsesStream, RetryConfig, type RetryHandler, RetryMetadata, type RunEventTypeV0, type RunEventV0, type RunId$1 as RunId, type RunStatusV0, RunsClient, RunsEventStream, SecretKey, type Session, type SessionArtifacts, type SessionContextManagement, type SessionContextTruncateInfo, type SessionId, type SessionMessage, type SessionPendingToolCall, type SessionRunOptions, type SessionRunResult, type SessionRunStatus, type SessionSyncOptions, type SessionSyncResult, type SessionType, type SessionUsageSummary, SessionsClient, SqliteConversationStore, type StateHandleCreateRequest, type StateHandleListResponse, type StateHandleResponse, StreamProtocolError, StreamTimeoutError, type StreamTimeoutKind, StructuredDecodeError, type StructuredErrorKind, StructuredExhaustedError, StructuredJSONEvent, StructuredJSONStream, type StructuredOptions, type StructuredResult, type Tier, type TierCheckoutRequest, type TierCheckoutSession, TierCode, type TierModel, TiersClient, TokenProvider, Tool, ToolArgumentError, ToolBuilder, ToolCall, ToolChoice, ToolExecutionResult, type ToolLoopComplete, type ToolLoopConfig, type ToolLoopOutcome, type ToolLoopUsage, type ToolLoopWaiting, ToolRegistry, ToolRunner, type ToolRunnerOptions, TraceCallbacks, TransportError, TransportErrorKind, USER_ASK_TOOL_NAME, type UserAskArgs, type UserAskOption, type UserAskResponse, type ValidationIssue, WORKFLOWS_COMPILE_PATH, WorkflowIntentBuilder, type WorkflowIntentBuilderState, type WorkflowKind, WorkflowKinds, WorkflowNodeTypesIntent as WorkflowNodeTypes, WorkflowNodeTypesIntent, WorkflowValidationError, type WorkflowValidationIssue, WorkflowsClient, type WorkflowsCompileOptions, type WorkflowsCompileRequest, type WorkflowsCompileResponse, type WorkflowsCompileResult, ZodLikeSchema, asSessionId, buildDelayedNDJSONResponse, buildNDJSONResponse, chain, createAccessTokenAuth, createApiKeyAuth, createFileConversationStore, createLocalSession, createMemoryConversationStore, createMockFetchQueue, createModelContextResolver, createSqliteConversationStore, createToolRunner, createUserAskTool, defaultRetryHandler, defaultTierModelId, generateSessionId, index$1 as generated, isSecretKey, isUserAskToolCall, llm, outputFormatFromZod, parallel, parseApiKey, parseErrorResponse, parseNodeId, parseOutputName, parsePlanHash, parseRunId, parseSecretKey, parseUserAskArgs, prepareInputWithContext, runToolLoop, serializeUserAskResult, truncateInputByTokens, userAskResultChoice, userAskResultFreeform, validateWithZod, index as workflow, workflowIntent };