@dudko.dev/agent 0.0.46 → 0.0.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,7 +1,5 @@
1
- import { OAuthClientProvider, OAuthDiscoveryState } from '@modelcontextprotocol/sdk/client/auth.js';
2
- import { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
3
- import { ToolSet, LanguageModel, Tool, SystemModelMessage, ModelMessage } from 'ai';
4
- import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
1
+ import { OAuthClientProvider, FetchLike, OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthDiscoveryState } from '@modelcontextprotocol/client';
2
+ import { Experimental_DecisionModel, ToolSet, Tool, ImageModel, SpeechModel, TranscriptionModel, LanguageModel, SystemModelMessage, ModelMessage } from 'ai';
5
3
  import { JsonWebKey, KeyObject } from 'node:crypto';
6
4
 
7
5
  /**
@@ -28,6 +26,13 @@ interface SubagentInfo {
28
26
  /** The profile the parent chose for this call, when it chose one. */
29
27
  profile?: string;
30
28
  startedAt: number;
29
+ /** The subagent that started it; absent when the run itself did. */
30
+ parentId?: string;
31
+ /** 1 for the run's own subagents, 2 for theirs, ... (set for helpers the model started). */
32
+ depth?: number;
33
+ /** Set for a helper the model started with spawn_subagent: the role it was given, if any. */
34
+ dynamic?: true;
35
+ role?: string;
31
36
  }
32
37
  interface RunControl {
33
38
  /**
@@ -55,6 +60,74 @@ interface RunControl {
55
60
  }
56
61
  declare const createRunControl: () => RunControl;
57
62
 
63
+ interface IDecisionOption {
64
+ id: string;
65
+ description?: string;
66
+ }
67
+ interface IDecisionQuestion {
68
+ id: string;
69
+ prompt: string;
70
+ options: readonly IDecisionOption[];
71
+ context?: string;
72
+ }
73
+ interface IDecisionCallOptions {
74
+ abortSignal?: AbortSignal;
75
+ }
76
+ interface IDecisionAnswer {
77
+ choice: string;
78
+ confidence: number;
79
+ usage?: {
80
+ inputTokens?: number;
81
+ outputTokens?: number;
82
+ };
83
+ }
84
+ interface IDecisionModel {
85
+ readonly name?: string;
86
+ decide: (question: IDecisionQuestion, options: IDecisionCallOptions) => Promise<IDecisionAnswer>;
87
+ }
88
+ interface IDecisionConfig {
89
+ confidenceThreshold?: number;
90
+ timeoutMs?: number;
91
+ replan?: boolean;
92
+ route?: boolean;
93
+ }
94
+ declare const DEFAULT_DECISION_CONFIDENCE_THRESHOLD = 0.8;
95
+ declare const DEFAULT_DECISION_TIMEOUT_MS = 5000;
96
+ type DecisionPoint = 'replan' | 'route';
97
+ type DecisionFallbackReason = 'low-confidence' | 'invalid-choice' | 'invalid-confidence' | 'error' | 'timeout' | 'needs-model';
98
+ interface IDecisionOutcome {
99
+ accepted: boolean;
100
+ choice?: string;
101
+ confidence?: number;
102
+ threshold: number;
103
+ reason?: DecisionFallbackReason;
104
+ error?: string;
105
+ durationMs: number;
106
+ usage?: {
107
+ inputTokens?: number;
108
+ outputTokens?: number;
109
+ };
110
+ }
111
+ interface IDecisionEvent {
112
+ type: 'decision';
113
+ point: DecisionPoint;
114
+ accepted: boolean;
115
+ choice?: string;
116
+ confidence?: number;
117
+ threshold: number;
118
+ reason?: DecisionFallbackReason;
119
+ error?: string;
120
+ durationMs: number;
121
+ model?: string;
122
+ }
123
+ declare const askDecisionModel: (model: IDecisionModel, question: IDecisionQuestion, config?: IDecisionConfig, signal?: AbortSignal) => Promise<IDecisionOutcome>;
124
+ interface IAiSdkDecisionOptions {
125
+ name?: string;
126
+ maxRetries?: number;
127
+ headers?: Record<string, string>;
128
+ }
129
+ declare const decisionModelFromAiSdk: (model: Experimental_DecisionModel, options?: IAiSdkDecisionOptions) => IDecisionModel;
130
+
58
131
  interface PipelineDefinition {
59
132
  version: 1;
60
133
  name?: string;
@@ -295,6 +368,123 @@ declare const checkRedirect: (from: URL, to: URL) => void;
295
368
  type SafeFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
296
369
  declare const createSafeFetch: (policy?: IEgressPolicy) => SafeFetch;
297
370
 
371
+ /**
372
+ * What the `web_search` tools of the two agent packages share: the result shape and its caps, how
373
+ * a search engine's answer is cleaned before a model reads it, and the built-in adapters as pure
374
+ * request builders and response parsers (one HTTP call each). Pure, no imports: the request itself
375
+ * is made by each package's own safe fetch.
376
+ *
377
+ * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/web-search-shared.ts`) and
378
+ * `@dudko.dev/agent-web` (`src/tools/web-search-shared.ts`): change both. The Node package's
379
+ * `tests/web-search-shared.test.ts` compares the two files and tests every cap and guard here.
380
+ */
381
+ declare const WEB_SEARCH_TOOL = "web_search";
382
+ /** Results returned when neither the host nor the model says how many. */
383
+ declare const SEARCH_DEFAULT_MAX_RESULTS = 5;
384
+ /** The most results one call returns, whatever the host or the model asks for. */
385
+ declare const SEARCH_MAX_RESULTS = 10;
386
+ /** The longest query sent to a search engine, in characters. */
387
+ declare const SEARCH_MAX_QUERY_CHARS = 400;
388
+ /** The most of a result's title a model sees. */
389
+ declare const SEARCH_MAX_TITLE_CHARS = 200;
390
+ /** A result whose URL is longer than this is dropped (a cut URL is another URL). */
391
+ declare const SEARCH_MAX_URL_CHARS = 2000;
392
+ /** The most of a result's snippet a model sees. */
393
+ declare const SEARCH_MAX_SNIPPET_CHARS = 500;
394
+ /** The most all results of one call take together (titles, URLs, snippets, dates). */
395
+ declare const SEARCH_MAX_TOTAL_CHARS = 6000;
396
+ /** One search result, as the model sees it. Third-party text: data, never instructions. */
397
+ interface ISearchResult {
398
+ title: string;
399
+ url: string;
400
+ snippet: string;
401
+ /** When the page was published or last changed, as the engine reported it. */
402
+ date?: string;
403
+ }
404
+ type SearchFreshness = 'day' | 'week' | 'month' | 'year';
405
+ /** What a search engine function is called with, next to the query. */
406
+ interface ISearchOptions {
407
+ /** How many results are wanted (1..SEARCH_MAX_RESULTS); more are cut. */
408
+ maxResults: number;
409
+ /** Only results from the last day / week / month / year, when the model asked for it. */
410
+ freshness?: SearchFreshness;
411
+ /** Aborted when the run is stopped. */
412
+ signal?: AbortSignal;
413
+ }
414
+ /**
415
+ * A search engine of the host's own: any function that answers a query with results. What it
416
+ * returns is treated like a built-in adapter's answer - cleaned, capped and filtered.
417
+ */
418
+ type SearchEngine = (query: string, options: ISearchOptions) => Promise<ISearchResult[]>;
419
+ /** The hosted search APIs with a built-in adapter. */
420
+ type SearchProvider = 'brave' | 'tavily' | 'searxng';
421
+ declare const SEARCH_PROVIDERS: readonly SearchProvider[];
422
+ /** Where each hosted API lives. SearXNG is self-hosted: its `baseURL` is the host's to give. */
423
+ declare const SEARCH_API_BASE_URL: Record<'brave' | 'tavily', string>;
424
+ /** One HTTP call to a search API. The key, if any, is in `headers` only - never in the URL. */
425
+ interface ISearchRequest {
426
+ url: string;
427
+ method: 'GET' | 'POST';
428
+ headers: Record<string, string>;
429
+ body?: string;
430
+ }
431
+ interface ISearchRequestInput {
432
+ provider: SearchProvider;
433
+ query: string;
434
+ maxResults: number;
435
+ freshness?: SearchFreshness;
436
+ apiKey?: string;
437
+ baseURL?: string;
438
+ }
439
+ /**
440
+ * The request for one query, per the API's public documentation:
441
+ * - brave: GET {base}/res/v1/web/search?q=&count= header X-Subscription-Token
442
+ * - tavily: POST {base}/search { query, max_results } header Authorization: Bearer
443
+ * - searxng: GET {base}/search?q=&format=json no key
444
+ */
445
+ declare const buildSearchRequest: (input: ISearchRequestInput) => ISearchRequest;
446
+ /**
447
+ * The results inside an API's JSON answer, mapped to `{ title, url, snippet, date }` and nothing
448
+ * else. Still raw third-party values: `sanitizeSearchResults` is what makes them safe to show.
449
+ */
450
+ declare const parseSearchResponse: (provider: SearchProvider, json: unknown) => unknown[];
451
+ interface ISanitizedSearch {
452
+ results: ISearchResult[];
453
+ /** Results dropped because the host's egress policy does not let the model reach them. */
454
+ filtered: number;
455
+ /** True when results were left out for a cap (the count, or the total size). */
456
+ truncated: boolean;
457
+ }
458
+ /**
459
+ * What a model sees of an engine's answer. `raw` is whatever came back - nothing about it is
460
+ * trusted: a result needs a valid http(s) URL, every field is cleaned and capped, duplicates go,
461
+ * `accepts` (the egress policy) drops links the model could not fetch, and the list stops at
462
+ * `maxResults` and at SEARCH_MAX_TOTAL_CHARS.
463
+ */
464
+ declare const sanitizeSearchResults: (raw: unknown, options?: {
465
+ maxResults?: number;
466
+ accepts?: (url: URL) => boolean;
467
+ }) => ISanitizedSearch;
468
+
469
+ interface ISearchConfig {
470
+ engine?: SearchEngine;
471
+ provider?: SearchProvider;
472
+ apiKey?: string;
473
+ baseURL?: string;
474
+ maxResults?: number;
475
+ allowPrivateNetwork?: boolean;
476
+ timeoutMs?: number;
477
+ readOnly?: boolean;
478
+ }
479
+ interface IWebSearchOptions {
480
+ search: ISearchConfig;
481
+ egress?: boolean | IEgressPolicy;
482
+ fetch?: SafeFetch;
483
+ }
484
+ declare const searchEgressPolicy: (search: ISearchConfig, egress?: boolean | IEgressPolicy) => IEgressPolicy;
485
+ declare const createWebSearchTool: (options: IWebSearchOptions) => Tool;
486
+ declare const createSearchTools: (search: ISearchConfig | undefined, egress?: boolean | IEgressPolicy) => ToolSet | undefined;
487
+
298
488
  declare const RUN_JS_TOOL = "run_js";
299
489
  interface ISandboxConfig {
300
490
  timeoutMs?: number;
@@ -327,10 +517,179 @@ declare class SandboxUnavailableError extends Error {
327
517
  constructor(message: string);
328
518
  }
329
519
 
520
+ declare const GENERATE_IMAGE_TOOL = "generate_image";
521
+ declare const GENERATE_SPEECH_TOOL = "generate_speech";
522
+ declare const TRANSCRIBE_AUDIO_TOOL = "transcribe_audio";
523
+ type MediaKind = 'image' | 'speech' | 'transcription';
524
+ declare const MEDIA_DEFAULT_MAX_CALLS = 8;
525
+ declare const MEDIA_TIMEOUT_MS = 120000;
526
+ declare const MEDIA_MAX_IMAGE_BYTES: number;
527
+ declare const MEDIA_MAX_SPEECH_BYTES: number;
528
+ declare const MEDIA_MAX_AUDIO_INPUT_BYTES: number;
529
+ declare const MEDIA_MAX_PROMPT_CHARS = 4000;
530
+ declare const MEDIA_MAX_SPEECH_CHARS = 4000;
531
+ declare const MEDIA_MAX_TRANSCRIPT_CHARS = 20000;
532
+ declare const MEDIA_MAX_ATTACHED_AUDIO = 4;
533
+ declare const MEDIA_FOLDER = "media";
534
+ declare class MediaError extends Error {
535
+ constructor(message: string);
536
+ toJSON(): string;
537
+ }
538
+ declare class MediaBudgetError extends MediaError {
539
+ constructor(cap: number);
540
+ }
541
+ declare const MEDIA_IMAGE_TYPES: Readonly<Record<string, string>>;
542
+ declare const MEDIA_AUDIO_TYPES: Readonly<Record<string, string>>;
543
+ declare const sniffMediaType: (bytes: Uint8Array) => string | undefined;
544
+ interface IAcceptedMedia {
545
+ mediaType: string;
546
+ ext: string;
547
+ }
548
+ declare const acceptMedia: (family: "image" | "audio", bytes: Uint8Array, maxBytes: number, what: string) => IAcceptedMedia;
549
+ interface IMediaUsage {
550
+ mediaCalls: number;
551
+ imagesGenerated: number;
552
+ speechCharacters: number;
553
+ transcriptionSeconds: number;
554
+ }
555
+ declare const mediaUsageOf: (usage: Partial<IMediaUsage> | undefined) => IMediaUsage | undefined;
556
+ interface ITranscriptBlock {
557
+ name: string;
558
+ text: string;
559
+ language?: string;
560
+ durationInSeconds?: number;
561
+ }
562
+ declare const wrapTranscript: (block: ITranscriptBlock) => string;
563
+
564
+ type IMediaModelSpec = IAgentStageOverride & {
565
+ model: string;
566
+ };
567
+ type MediaImageModel = Exclude<ImageModel, string>;
568
+ type MediaSpeechModel = Exclude<SpeechModel, string>;
569
+ type MediaTranscriptionModel = Exclude<TranscriptionModel, string>;
570
+ interface IMediaConfig {
571
+ imageModel?: MediaImageModel | IMediaModelSpec;
572
+ speechModel?: MediaSpeechModel | IMediaModelSpec;
573
+ transcriptionModel?: MediaTranscriptionModel | IMediaModelSpec;
574
+ maxCalls?: number;
575
+ timeoutMs?: number;
576
+ dir?: string;
577
+ voice?: string;
578
+ speechFormat?: string;
579
+ }
580
+ interface IRunFile {
581
+ data: string | Uint8Array;
582
+ mediaType?: string;
583
+ name?: string;
584
+ }
585
+ interface IMediaFile {
586
+ path: string;
587
+ mediaType: string;
588
+ bytes: number;
589
+ }
590
+ interface ITranscription {
591
+ path: string;
592
+ text: string;
593
+ language?: string;
594
+ durationInSeconds?: number;
595
+ truncated?: true;
596
+ untrusted: true;
597
+ }
598
+ interface IMedia {
599
+ tools: ToolSet;
600
+ attach: (input: string, files: IRunFile[], signal?: AbortSignal) => Promise<string>;
601
+ }
602
+ declare const createMedia: (config: IAgentConfig) => Promise<IMedia | undefined>;
603
+
604
+ declare const SPAWN_SUBAGENT_TOOL = "spawn_subagent";
605
+ type SubagentDefaultTools = 'read-only' | 'all';
606
+ interface IDynamicSubagentsConfig {
607
+ maxDepth?: number;
608
+ maxChildren?: number;
609
+ maxConcurrent?: number;
610
+ budgetShare?: number;
611
+ minTokens?: number;
612
+ timeoutMs?: number;
613
+ defaultTools?: SubagentDefaultTools;
614
+ }
615
+ interface ISubagentsConfig {
616
+ dynamic?: boolean | IDynamicSubagentsConfig;
617
+ }
618
+ interface IResolvedDynamicSubagents {
619
+ maxDepth: number;
620
+ maxChildren: number;
621
+ maxConcurrent: number;
622
+ budgetShare: number;
623
+ minTokens: number;
624
+ timeoutMs: number;
625
+ defaultTools: SubagentDefaultTools;
626
+ }
627
+ declare const SUBAGENT_DEFAULTS: IResolvedDynamicSubagents;
628
+ declare const SUBAGENT_MAX_DEPTH_LIMIT = 4;
629
+ /**
630
+ * The effective settings, or undefined when the feature is off (nothing is mounted, nothing is
631
+ * added to a prompt). A bad value is a configuration error, thrown when the agent is created.
632
+ */
633
+ declare const resolveDynamicSubagents: (subagents: ISubagentsConfig | undefined) => IResolvedDynamicSubagents | undefined;
634
+ /**
635
+ * A spawn that was refused: the model reads the message as the tool's error and can correct the
636
+ * call or carry on without a helper.
637
+ */
638
+ declare class SubagentSpawnError extends Error {
639
+ constructor(message: string);
640
+ toJSON(): string;
641
+ }
642
+ declare const SPAWN_INPUT_SCHEMA: {
643
+ readonly type: "object";
644
+ readonly properties: {
645
+ readonly task: {
646
+ readonly type: "string";
647
+ readonly description: "The complete, self-contained sub-task. The helper sees nothing of your context except this text: include every fact, id and constraint it needs, and say what to return.";
648
+ };
649
+ readonly role: {
650
+ readonly type: "string";
651
+ readonly description: "Optional: who the helper should be for this task and how to work, in a sentence or two (e.g. \"a careful code reviewer; report only real bugs\").";
652
+ };
653
+ readonly tools: {
654
+ readonly type: "array";
655
+ readonly items: {
656
+ readonly type: "string";
657
+ };
658
+ readonly description: "Optional: the names of YOUR tools the helper may use. Only tools you have can be named. Omit it for the default set; pass [] for a helper that only reasons.";
659
+ };
660
+ };
661
+ readonly required: readonly ["task"];
662
+ readonly additionalProperties: false;
663
+ };
664
+ /**
665
+ * A child's event on its way up through the subagent `parentId` (the `subagent.event` envelope is
666
+ * added by the caller). A `subagent.start` is emitted with `depth: 1` and the id of the run that
667
+ * made the call as `parentId`; each subagent it passes through on the way up adds one level, and
668
+ * the first one - its real parent - puts its own id in `parentId`. So at the top of the stream
669
+ * every start carries its true depth and parent, whatever mix of static and dynamic subagents,
670
+ * threads and workers is below.
671
+ */
672
+ declare const adoptSubagentEvent: <E extends {
673
+ type: string;
674
+ }>(event: E, parentId: string) => E;
675
+
330
676
  type ProviderType = 'openai' | 'anthropic' | 'openai-compatible' | 'google' | 'xai' | 'azure' | 'amazon-bedrock' | 'google-vertex' | 'deepseek' | 'gateway' | 'cloudflare';
331
677
  type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug';
332
678
  type ToolSelectionStrategy = 'all' | 'plan-narrowed' | 'search' | 'auto';
333
679
  type AgentStage = 'planner' | 'executor' | 'replanner' | 'synthesizer';
680
+ type ModelTier = 'light' | 'standard' | 'strong';
681
+ type StepComplexity = 'low' | 'medium' | 'high';
682
+ type TierReason = 'planned' | 'default' | 'fallback';
683
+ type EscalationReason = 'blocked' | 'empty-result' | 'tool-arguments' | 'output-cut' | 'error';
684
+ interface IStepEscalation {
685
+ from: ModelTier;
686
+ to: ModelTier;
687
+ reason: EscalationReason;
688
+ }
689
+ interface IEscalationConfig {
690
+ maxPerStep?: number;
691
+ maxPerRun?: number;
692
+ }
334
693
  type ThinkingLevel = 'provider-default' | 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
335
694
  interface IThinkingConfig {
336
695
  level?: ThinkingLevel;
@@ -408,6 +767,10 @@ interface IToolApprovalRequest {
408
767
  readOnly: boolean;
409
768
  step?: IPlanStep;
410
769
  runId?: string;
770
+ subagent?: {
771
+ id: string;
772
+ depth: number;
773
+ };
411
774
  }
412
775
  type ToolApprovalDecision = boolean | {
413
776
  approved: boolean;
@@ -462,14 +825,21 @@ interface IAgentConfig {
462
825
  providerOptions?: Record<string, unknown>;
463
826
  planner?: IAgentStageOverride;
464
827
  synthesizer?: IAgentStageOverride;
828
+ executorTiers?: Partial<Record<ModelTier, IAgentStageOverride>>;
829
+ escalation?: boolean | IEscalationConfig;
465
830
  /** @deprecated use `planner: { model }` */
466
831
  plannerModel?: string;
467
832
  /** @deprecated use `synthesizer: { model }` */
468
833
  synthesizerModel?: string;
469
834
  mcpServers: Record<string, IMcpServerConfig>;
470
835
  egress?: boolean | IEgressPolicy;
836
+ search?: ISearchConfig;
837
+ decisionModel?: IDecisionModel;
838
+ decision?: IDecisionConfig;
471
839
  learning?: boolean | ILearningConfig;
472
840
  sandbox?: boolean | ISandboxConfig;
841
+ media?: IMediaConfig;
842
+ subagents?: ISubagentsConfig;
473
843
  tools?: ToolSet;
474
844
  availableTools?: string[];
475
845
  excludedTools?: string[];
@@ -488,6 +858,7 @@ interface IAgentConfig {
488
858
  toolApproval?: IToolApprovalConfig;
489
859
  toolSearchThreshold?: number;
490
860
  mcpConnectTimeoutMs?: number;
861
+ mcpInstructions?: boolean;
491
862
  promptCaching?: PromptCachingSetting;
492
863
  llmTimeoutMs?: number;
493
864
  llmMaxRetries?: number;
@@ -513,6 +884,11 @@ interface IUsage {
513
884
  reasoningTokens?: number;
514
885
  cachedInputTokens?: number;
515
886
  cacheWriteTokens?: number;
887
+ mediaCalls?: number;
888
+ imagesGenerated?: number;
889
+ speechCharacters?: number;
890
+ transcriptionSeconds?: number;
891
+ decisionCalls?: number;
516
892
  }
517
893
  interface IPlanStep {
518
894
  id: string;
@@ -520,6 +896,7 @@ interface IPlanStep {
520
896
  expectedOutcome: string;
521
897
  suggestedTools?: string[];
522
898
  requiresTools?: boolean;
899
+ complexity?: StepComplexity;
523
900
  }
524
901
  interface IPlan {
525
902
  thought: string;
@@ -537,10 +914,13 @@ interface IStepResult {
537
914
  }[];
538
915
  durationMs: number;
539
916
  blocked: boolean;
917
+ tier?: ModelTier;
918
+ model?: string;
919
+ escalations?: IStepEscalation[];
540
920
  }
541
921
  type ReplanTrigger = 'failure' | 'always' | ((result: IStepResult) => boolean | Promise<boolean>);
542
- type ReplanCause = 'last-step' | 'clean-step' | 'llm-decision' | 'user-message';
543
- type UsagePhase = 'plan' | 'execute' | 'replan' | 'synthesize' | 'compact' | 'subagent';
922
+ type ReplanCause = 'last-step' | 'clean-step' | 'llm-decision' | 'user-message' | 'decision-model';
923
+ type UsagePhase = 'plan' | 'execute' | 'replan' | 'synthesize' | 'compact' | 'subagent' | 'decision' | 'media';
544
924
  type AgentEventBody = {
545
925
  type: 'plan.thought-delta';
546
926
  delta: string;
@@ -559,6 +939,16 @@ type AgentEventBody = {
559
939
  type: 'step.start';
560
940
  step: IPlanStep;
561
941
  index: number;
942
+ tier?: ModelTier;
943
+ model?: string;
944
+ tierReason?: TierReason;
945
+ } | {
946
+ type: 'step.escalated';
947
+ step: IPlanStep;
948
+ from: ModelTier;
949
+ to: ModelTier;
950
+ model: string;
951
+ reason: EscalationReason;
562
952
  } | {
563
953
  type: 'step.text-delta';
564
954
  step: IPlanStep;
@@ -587,7 +977,9 @@ type AgentEventBody = {
587
977
  mode: 'continue' | 'revise' | 'finish';
588
978
  reason: string;
589
979
  cause: ReplanCause;
590
- } | {
980
+ failed?: true;
981
+ confidence?: number;
982
+ } | IDecisionEvent | {
591
983
  type: 'final.text-delta';
592
984
  delta: string;
593
985
  } | {
@@ -635,6 +1027,10 @@ type AgentEventBody = {
635
1027
  input: unknown;
636
1028
  readOnly: boolean;
637
1029
  step?: IPlanStep;
1030
+ subagent?: {
1031
+ id: string;
1032
+ depth: number;
1033
+ };
638
1034
  } | {
639
1035
  type: 'tool.approval-resolved';
640
1036
  id: string;
@@ -648,6 +1044,11 @@ type AgentEventBody = {
648
1044
  name: string;
649
1045
  task: string;
650
1046
  profile?: string;
1047
+ parentId?: string;
1048
+ depth?: number;
1049
+ dynamic?: true;
1050
+ role?: string;
1051
+ tools?: string[];
651
1052
  } | {
652
1053
  type: 'subagent.event';
653
1054
  id: string;
@@ -665,6 +1066,7 @@ type AgentEventBody = {
665
1066
  name: string;
666
1067
  error: string;
667
1068
  stopped?: boolean;
1069
+ usage?: IUsage;
668
1070
  } | {
669
1071
  type: 'message.queued';
670
1072
  id: string;
@@ -690,6 +1092,22 @@ type AgentEventBody = {
690
1092
  } | {
691
1093
  type: 'skill.forgotten';
692
1094
  name: string;
1095
+ } | {
1096
+ type: 'media.generated';
1097
+ kind: 'image' | 'speech';
1098
+ path: string;
1099
+ mediaType: string;
1100
+ bytes: number;
1101
+ model: string;
1102
+ step?: IPlanStep;
1103
+ } | {
1104
+ type: 'media.transcribed';
1105
+ source: 'attachment' | 'tool';
1106
+ name: string;
1107
+ text: string;
1108
+ language?: string;
1109
+ durationInSeconds?: number;
1110
+ model: string;
693
1111
  } | {
694
1112
  type: 'revisions.exceeded';
695
1113
  cap: number;
@@ -712,6 +1130,7 @@ interface IStepStartInfo {
712
1130
  interface IAgentRunOptions {
713
1131
  input: string;
714
1132
  history?: IConversationTurn[];
1133
+ files?: IRunFile[];
715
1134
  signal?: AbortSignal;
716
1135
  onEvent?: EventHandler;
717
1136
  onStepStart?: (info: IStepStartInfo) => void;
@@ -750,6 +1169,8 @@ interface IRunSnapshot {
750
1169
  text: string;
751
1170
  reconciled: boolean;
752
1171
  }[];
1172
+ escalations?: number;
1173
+ subagentsSpawned?: number;
753
1174
  }
754
1175
  interface IPersistence {
755
1176
  onRunStart?: (snapshot: IRunSnapshot) => void | Promise<void>;
@@ -835,10 +1256,14 @@ interface IToolDecision {
835
1256
  */
836
1257
  declare const decideToolPermission: (input: IToolDecisionInput) => IToolDecision;
837
1258
 
1259
+ declare const REPLAY_NOTE = "[not run again: this exact call already succeeded in an earlier attempt at this step, and its effect is in place. Its result then:]";
1260
+ declare const isReplayedToolOutput: (output: unknown) => boolean;
1261
+
838
1262
  declare const getCurrentRunId: () => string | undefined;
839
1263
  declare const getCurrentRunSandbox: () => string | undefined;
840
1264
 
841
1265
  declare const redactHeaders: (headers: Record<string, string> | undefined) => Record<string, string> | undefined;
1266
+ type IFilledUsage = Required<Omit<IUsage, 'decisionCalls' | keyof IMediaUsage>> & Pick<IUsage, 'decisionCalls'> & Partial<IMediaUsage>;
842
1267
  interface ISdkUsageLike {
843
1268
  inputTokens?: number;
844
1269
  outputTokens?: number;
@@ -850,11 +1275,16 @@ interface ISdkUsageLike {
850
1275
  outputTokenDetails?: {
851
1276
  reasoningTokens?: number;
852
1277
  };
1278
+ decisionCalls?: number;
853
1279
  reasoningTokens?: number;
854
1280
  cachedInputTokens?: number;
1281
+ mediaCalls?: number;
1282
+ imagesGenerated?: number;
1283
+ speechCharacters?: number;
1284
+ transcriptionSeconds?: number;
855
1285
  }
856
- declare const normalizeUsage: (usage: ISdkUsageLike | undefined | null) => Required<IUsage>;
857
- declare const addUsage: (a: IUsage, b: IUsage) => Required<IUsage>;
1286
+ declare const normalizeUsage: (usage: ISdkUsageLike | undefined | null) => IFilledUsage;
1287
+ declare const addUsage: (a: IUsage, b: IUsage) => IFilledUsage;
858
1288
 
859
1289
  /**
860
1290
  * OAuth 2.1 for remote MCP servers, from Node.
@@ -960,7 +1390,8 @@ interface INodeOAuthProviderOptions {
960
1390
  * `authorization_response_iss_parameter_supported: true`;
961
1391
  * - no stored discovery state (a store written by an older version): `iss` is
962
1392
  * compared with the issuer stamped on the stored client information, and with
963
- * nothing to compare against the response is accepted.
1393
+ * nothing to compare against the response is accepted. ({@link finishMcpOAuth}
1394
+ * does not exchange a code in that case: see there.)
964
1395
  *
965
1396
  * The browser package carries the same function; change both.
966
1397
  */
@@ -1007,9 +1438,11 @@ declare class NodeOAuthProvider implements OAuthClientProvider {
1007
1438
  redirectToAuthorization(url: URL): Promise<void>;
1008
1439
  /**
1009
1440
  * Called by the SDK when the server rejects what we hold: `'tokens'` on an
1010
- * `invalid_grant` (dead refresh token), `'all'` on an `invalid_client` (the
1011
- * AS forgot our dynamic registration). `'client'`, `'verifier'` and
1012
- * `'discovery'` are in its type and handled the same way: one key each.
1441
+ * `invalid_grant` (dead refresh token); `'client'` and then `'tokens'` on an
1442
+ * `invalid_client` (the AS forgot our dynamic registration) - what discovery
1443
+ * found is kept on purpose, the SDK checks the next callback against it.
1444
+ * `'verifier'` and `'discovery'` are in its type and handled the same way:
1445
+ * one key each. `'all'` is what {@link reset} asks for.
1013
1446
  */
1014
1447
  invalidateCredentials(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): Promise<void>;
1015
1448
  /** True when there is no access token, or it expires within the skew window. */
@@ -1038,6 +1471,12 @@ declare const beginMcpOAuth: (provider: NodeOAuthProvider, opts?: IOAuthRequestO
1038
1471
  * issuer (RFC 9207, {@link checkAuthorizationResponseIssuer}), exchanges the
1039
1472
  * code with the stored PKCE verifier and persists the tokens. Throws unless the
1040
1473
  * exchange fully succeeded.
1474
+ *
1475
+ * A flow whose discovery state is not in the store any more (started by a
1476
+ * version that did not keep it, or cleared in between) is not completed: the
1477
+ * code is bound to the authorization server the operator was sent to, and
1478
+ * without the record of which one that was the SDK refuses the exchange.
1479
+ * Start again with {@link beginMcpOAuth}; stored tokens are not touched.
1041
1480
  */
1042
1481
  declare const finishMcpOAuth: (provider: NodeOAuthProvider, callback: {
1043
1482
  code: string;
@@ -1045,6 +1484,34 @@ declare const finishMcpOAuth: (provider: NodeOAuthProvider, callback: {
1045
1484
  iss?: string;
1046
1485
  }, opts?: IOAuthRequestOptions) => Promise<void>;
1047
1486
 
1487
+ /**
1488
+ * What the MCP connectors of the two agent packages share: how a server's `instructions` reach a
1489
+ * system prompt, and how a tool result's `structuredContent` reaches the model. Pure, no imports.
1490
+ *
1491
+ * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/mcp-shared.ts`) and
1492
+ * `@dudko.dev/agent-web` (`src/mcp/shared.ts`): change both. The Node package's
1493
+ * `tests/mcp-shared.test.ts` compares the two files and tests every cap and guard here.
1494
+ */
1495
+ /** The `instructions` one connected MCP server returned in its `initialize` result. */
1496
+ interface McpServerInstructions {
1497
+ /** The server's name: its key in the host's configuration. */
1498
+ server: string;
1499
+ instructions: string;
1500
+ }
1501
+ /** The most one server's instructions take in a system prompt, in characters. */
1502
+ declare const MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER = 2000;
1503
+ /** The most all servers' instructions take together, in characters. */
1504
+ declare const MCP_INSTRUCTIONS_MAX_CHARS_TOTAL = 8000;
1505
+ /**
1506
+ * The system-prompt section for the servers' instructions, or '' when no server sent any (the
1507
+ * prompt is then exactly what it was). Each server's text is capped
1508
+ * (MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER), so is the sum (MCP_INSTRUCTIONS_MAX_CHARS_TOTAL, in
1509
+ * the order given: a server past the total is named as omitted), and every line of it is
1510
+ * prefixed with "| ", so a server cannot write something that reads as a heading of this prompt
1511
+ * or as another server's note.
1512
+ */
1513
+ declare const renderMcpInstructions: (list: readonly McpServerInstructions[] | undefined) => string;
1514
+
1048
1515
  /**
1049
1516
  * Enterprise-Managed Authorization for remote MCP servers (the MCP extension
1050
1517
  * `io.modelcontextprotocol/enterprise-managed-authorization`, also called Cross
@@ -1553,6 +2020,16 @@ interface IWebFetchOptions {
1553
2020
  declare const createWebFetchTool: (options?: IWebFetchOptions) => Tool;
1554
2021
  declare const createEgressTools: (egress: boolean | IEgressPolicy | undefined) => ToolSet | undefined;
1555
2022
 
2023
+ interface IResolvedStage {
2024
+ providerType: ProviderType;
2025
+ baseURL?: string;
2026
+ apiKey: string;
2027
+ model: string;
2028
+ providerOptions?: Record<string, unknown>;
2029
+ }
2030
+ type MediaModelKind = 'image' | 'speech' | 'transcription';
2031
+ declare const buildMediaModelFromStage: (clientName: string, stage: IResolvedStage, kind: MediaModelKind) => Promise<unknown>;
2032
+
1556
2033
  interface ISandboxDeps {
1557
2034
  workerUrl?: URL;
1558
2035
  peerInstalled?: () => boolean;
@@ -1575,7 +2052,7 @@ interface Pipeline {
1575
2052
  close: () => Promise<void>;
1576
2053
  }
1577
2054
  declare const createPipeline: (definition: PipelineDefinition, options: PipelineOptions) => Pipeline;
1578
- type PipelineModelConfig = Pick<IAgentConfig, 'model'> & Partial<Pick<IAgentConfig, 'providerType' | 'baseURL' | 'apiKey' | 'providerOptions' | 'planner' | 'synthesizer'>>;
2055
+ type PipelineModelConfig = Pick<IAgentConfig, 'model'> & Partial<Pick<IAgentConfig, 'providerType' | 'baseURL' | 'apiKey' | 'providerOptions' | 'planner' | 'synthesizer' | 'executorTiers'>>;
1579
2056
  interface NodeResolverOptions {
1580
2057
  base: IAgentConfig;
1581
2058
  models?: Record<string, PipelineModelConfig>;
@@ -1612,5 +2089,5 @@ interface ISubagentToolOptions {
1612
2089
  */
1613
2090
  declare const createSubagentTool: (opts: ISubagentToolOptions) => Tool;
1614
2091
 
1615
- export { DEFAULT_COMPACTION_THRESHOLD_RATIO, DirSkillStore, ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION, EgressError, EnterpriseOAuthError, FORGET_SKILL_TOOL, FileOAuthStore, MemoryOAuthStore, MemorySkillStore, NodeEnterpriseOAuthProvider, NodeOAuthProvider, PIPELINE_LIMITS, PipelineNodeError, PipelineValidationError, RUN_JS_TOOL, SAVE_SKILL_TOOL, SUMMARY_PREFIX, SandboxUnavailableError, ToolBudgetError, ToolDeniedError, WEB_FETCH_TOOL, addUsage, beginMcpOAuth, buildInstructions, checkAuthorizationResponseIssuer, checkEgressUrl, checkLimits, checkRedirect, classifyAddress, compactHistory, createAgent, createEgressTools, createEnterpriseOAuthProvider, createLearning, createNodeOAuthProvider, createPipeline, createRunControl, createSafeFetch, createSandboxTool, createSandboxTools, createSubagentTool, createToolResultClearer, createWebFetchTool, decideToolPermission, defineSkill, estimateTokens, findSecret, finishMcpOAuth, getCurrentRunId, getCurrentRunSandbox, hostMatches, htmlToText, isReadOnlyTool, loadSkillsFromDir, markReadOnly, matchToolRule, mergeProviderOptions, nodeResolver, normalizePipeline, normalizeSkillName, normalizeUsage, parseSkillMarkdown, redactHeaders, renderPipelineNodeInput, resolveCompaction, resolveEgressPolicy, resolveLimits, resolvePromptCaching, resolveSandboxLimits, resolveThinking, searchTools, testPipelineCondition, truncateToolModelOutput, validatePipeline, withRollingBreakpoint, withToolOutputLimit };
1616
- export type { AgentEvent, AgentStage, BudgetKind, EgressErrorCode, EnterpriseAssertionAlgorithm, EnterpriseAssertionAudience, EnterpriseAssertionType, EnterpriseOAuthHop, EnterpriseOAuthLog, EnterprisePrivateKey, EventHandler, IAgent, IAgentConfig, IAgentRunOptions, IAgentRunResult, IAgentStageOverride, IClearedInfo, ICloseOptions, ICompactHistoryOptions, ICompactHistoryResult, ICompactOptions, ICompactResult, ICompactionConfig, IConversationTurn, IEgressPolicy, IEnterpriseIdpOptions, IEnterpriseOAuthProviderOptions, ILearning, ILearningConfig, ILimitBreach, IMcpHttpServerConfig, IMcpServerConfig, IMcpStdioServerConfig, INodeOAuthProviderOptions, IOAuthRequestOptions, IOAuthStore, IPersistence, IPlan, IPlanStep, IResolvedAddress, IResolvedThinking, IRunSnapshot, ISandboxConfig, ISandboxError, ISandboxLimits, ISandboxResult, ISaveSkillInput, ISearchToolsOptions, ISkill, ISkillOrigin, ISkillStore, IStepResult, IStepStartInfo, ISubagentProfile, ISubagentToolOptions, IThinkingConfig, ITokenLimits, IToolApprovalConfig, IToolApprovalRequest, IToolCatalogEntry, IToolDecision, IToolDecisionInput, IToolResultClearing, IUsage, LogLevel, NodeResolverOptions, Pipeline, PipelineCondition, PipelineDefinition, PipelineEdge, PipelineEvent, PipelineIssue, PipelineModelConfig, PipelineNode, PipelineNodeContext, PipelineNodeInput, PipelineNodeOutput, PipelineNodeRunner, PipelineNodeSource, PipelineOptions, PipelineResult, PipelineRoute, PipelineRunOptions, PipelineStop, PipelineTraceEntry, PipelineUsage, PipelineValidation, PromptCachingSetting, ProviderType, ReplanCause, ReplanTrigger, RunControl, SafeFetch, SubagentInfo, SubagentIsolation, ThinkingLevel, ThinkingSetting, TokenLimitKind, ToolApprovalDecision, ToolApprovalMode, ToolPermission, ToolSelectionStrategy, UsagePhase };
2092
+ export { DEFAULT_COMPACTION_THRESHOLD_RATIO, DEFAULT_DECISION_CONFIDENCE_THRESHOLD, DEFAULT_DECISION_TIMEOUT_MS, DirSkillStore, ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION, EgressError, EnterpriseOAuthError, FORGET_SKILL_TOOL, FileOAuthStore, GENERATE_IMAGE_TOOL, GENERATE_SPEECH_TOOL, MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER, MCP_INSTRUCTIONS_MAX_CHARS_TOTAL, MEDIA_AUDIO_TYPES, MEDIA_DEFAULT_MAX_CALLS, MEDIA_FOLDER, MEDIA_IMAGE_TYPES, MEDIA_MAX_ATTACHED_AUDIO, MEDIA_MAX_AUDIO_INPUT_BYTES, MEDIA_MAX_IMAGE_BYTES, MEDIA_MAX_PROMPT_CHARS, MEDIA_MAX_SPEECH_BYTES, MEDIA_MAX_SPEECH_CHARS, MEDIA_MAX_TRANSCRIPT_CHARS, MEDIA_TIMEOUT_MS, MediaBudgetError, MediaError, MemoryOAuthStore, MemorySkillStore, NodeEnterpriseOAuthProvider, NodeOAuthProvider, PIPELINE_LIMITS, PipelineNodeError, PipelineValidationError, REPLAY_NOTE, RUN_JS_TOOL, SAVE_SKILL_TOOL, SEARCH_API_BASE_URL, SEARCH_DEFAULT_MAX_RESULTS, SEARCH_MAX_QUERY_CHARS, SEARCH_MAX_RESULTS, SEARCH_MAX_SNIPPET_CHARS, SEARCH_MAX_TITLE_CHARS, SEARCH_MAX_TOTAL_CHARS, SEARCH_MAX_URL_CHARS, SEARCH_PROVIDERS, SPAWN_INPUT_SCHEMA, SPAWN_SUBAGENT_TOOL, SUBAGENT_DEFAULTS, SUBAGENT_MAX_DEPTH_LIMIT, SUMMARY_PREFIX, SandboxUnavailableError, SubagentSpawnError, TRANSCRIBE_AUDIO_TOOL, ToolBudgetError, ToolDeniedError, WEB_FETCH_TOOL, WEB_SEARCH_TOOL, acceptMedia, addUsage, adoptSubagentEvent, askDecisionModel, beginMcpOAuth, buildInstructions, buildMediaModelFromStage, buildSearchRequest, checkAuthorizationResponseIssuer, checkEgressUrl, checkLimits, checkRedirect, classifyAddress, compactHistory, createAgent, createEgressTools, createEnterpriseOAuthProvider, createLearning, createMedia, createNodeOAuthProvider, createPipeline, createRunControl, createSafeFetch, createSandboxTool, createSandboxTools, createSearchTools, createSubagentTool, createToolResultClearer, createWebFetchTool, createWebSearchTool, decideToolPermission, decisionModelFromAiSdk, defineSkill, estimateTokens, findSecret, finishMcpOAuth, getCurrentRunId, getCurrentRunSandbox, hostMatches, htmlToText, isReadOnlyTool, isReplayedToolOutput, loadSkillsFromDir, markReadOnly, matchToolRule, mediaUsageOf, mergeProviderOptions, nodeResolver, normalizePipeline, normalizeSkillName, normalizeUsage, parseSearchResponse, parseSkillMarkdown, redactHeaders, renderMcpInstructions, renderPipelineNodeInput, resolveCompaction, resolveDynamicSubagents, resolveEgressPolicy, resolveLimits, resolvePromptCaching, resolveSandboxLimits, resolveThinking, sanitizeSearchResults, searchEgressPolicy, searchTools, sniffMediaType, testPipelineCondition, truncateToolModelOutput, validatePipeline, withRollingBreakpoint, withToolOutputLimit, wrapTranscript };
2093
+ export type { AgentEvent, AgentStage, BudgetKind, DecisionFallbackReason, DecisionPoint, EgressErrorCode, EnterpriseAssertionAlgorithm, EnterpriseAssertionAudience, EnterpriseAssertionType, EnterpriseOAuthHop, EnterpriseOAuthLog, EnterprisePrivateKey, EscalationReason, EventHandler, IAgent, IAgentConfig, IAgentRunOptions, IAgentRunResult, IAgentStageOverride, IAiSdkDecisionOptions, IClearedInfo, ICloseOptions, ICompactHistoryOptions, ICompactHistoryResult, ICompactOptions, ICompactResult, ICompactionConfig, IConversationTurn, IDecisionAnswer, IDecisionCallOptions, IDecisionConfig, IDecisionEvent, IDecisionModel, IDecisionOption, IDecisionOutcome, IDecisionQuestion, IDynamicSubagentsConfig, IEgressPolicy, IEnterpriseIdpOptions, IEnterpriseOAuthProviderOptions, IEscalationConfig, ILearning, ILearningConfig, ILimitBreach, IMcpHttpServerConfig, IMcpServerConfig, IMcpStdioServerConfig, IMedia, IMediaConfig, IMediaFile, IMediaModelSpec, IMediaUsage, INodeOAuthProviderOptions, IOAuthRequestOptions, IOAuthStore, IPersistence, IPlan, IPlanStep, IResolvedAddress, IResolvedDynamicSubagents, IResolvedThinking, IRunFile, IRunSnapshot, ISandboxConfig, ISandboxError, ISandboxLimits, ISandboxResult, ISanitizedSearch, ISaveSkillInput, ISearchConfig, ISearchOptions, ISearchRequest, ISearchResult, ISearchToolsOptions, ISkill, ISkillOrigin, ISkillStore, IStepEscalation, IStepResult, IStepStartInfo, ISubagentProfile, ISubagentToolOptions, ISubagentsConfig, IThinkingConfig, ITokenLimits, IToolApprovalConfig, IToolApprovalRequest, IToolCatalogEntry, IToolDecision, IToolDecisionInput, IToolResultClearing, ITranscription, IUsage, IWebSearchOptions, LogLevel, McpServerInstructions, MediaImageModel, MediaKind, MediaModelKind, MediaSpeechModel, MediaTranscriptionModel, ModelTier, NodeResolverOptions, Pipeline, PipelineCondition, PipelineDefinition, PipelineEdge, PipelineEvent, PipelineIssue, PipelineModelConfig, PipelineNode, PipelineNodeContext, PipelineNodeInput, PipelineNodeOutput, PipelineNodeRunner, PipelineNodeSource, PipelineOptions, PipelineResult, PipelineRoute, PipelineRunOptions, PipelineStop, PipelineTraceEntry, PipelineUsage, PipelineValidation, PromptCachingSetting, ProviderType, ReplanCause, ReplanTrigger, RunControl, SafeFetch, SearchEngine, SearchFreshness, SearchProvider, StepComplexity, SubagentDefaultTools, SubagentInfo, SubagentIsolation, ThinkingLevel, ThinkingSetting, TierReason, TokenLimitKind, ToolApprovalDecision, ToolApprovalMode, ToolPermission, ToolSelectionStrategy, UsagePhase };