@dudko.dev/agent 0.0.46 → 0.0.47

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,6 +1,6 @@
1
1
  import { OAuthClientProvider, OAuthDiscoveryState } from '@modelcontextprotocol/sdk/client/auth.js';
2
2
  import { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
3
- import { ToolSet, LanguageModel, Tool, SystemModelMessage, ModelMessage } from 'ai';
3
+ import { Experimental_DecisionModel, ToolSet, Tool, ImageModel, SpeechModel, TranscriptionModel, LanguageModel, SystemModelMessage, ModelMessage } from 'ai';
4
4
  import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
5
5
  import { JsonWebKey, KeyObject } from 'node:crypto';
6
6
 
@@ -28,6 +28,13 @@ interface SubagentInfo {
28
28
  /** The profile the parent chose for this call, when it chose one. */
29
29
  profile?: string;
30
30
  startedAt: number;
31
+ /** The subagent that started it; absent when the run itself did. */
32
+ parentId?: string;
33
+ /** 1 for the run's own subagents, 2 for theirs, ... (set for helpers the model started). */
34
+ depth?: number;
35
+ /** Set for a helper the model started with spawn_subagent: the role it was given, if any. */
36
+ dynamic?: true;
37
+ role?: string;
31
38
  }
32
39
  interface RunControl {
33
40
  /**
@@ -55,6 +62,74 @@ interface RunControl {
55
62
  }
56
63
  declare const createRunControl: () => RunControl;
57
64
 
65
+ interface IDecisionOption {
66
+ id: string;
67
+ description?: string;
68
+ }
69
+ interface IDecisionQuestion {
70
+ id: string;
71
+ prompt: string;
72
+ options: readonly IDecisionOption[];
73
+ context?: string;
74
+ }
75
+ interface IDecisionCallOptions {
76
+ abortSignal?: AbortSignal;
77
+ }
78
+ interface IDecisionAnswer {
79
+ choice: string;
80
+ confidence: number;
81
+ usage?: {
82
+ inputTokens?: number;
83
+ outputTokens?: number;
84
+ };
85
+ }
86
+ interface IDecisionModel {
87
+ readonly name?: string;
88
+ decide: (question: IDecisionQuestion, options: IDecisionCallOptions) => Promise<IDecisionAnswer>;
89
+ }
90
+ interface IDecisionConfig {
91
+ confidenceThreshold?: number;
92
+ timeoutMs?: number;
93
+ replan?: boolean;
94
+ route?: boolean;
95
+ }
96
+ declare const DEFAULT_DECISION_CONFIDENCE_THRESHOLD = 0.8;
97
+ declare const DEFAULT_DECISION_TIMEOUT_MS = 5000;
98
+ type DecisionPoint = 'replan' | 'route';
99
+ type DecisionFallbackReason = 'low-confidence' | 'invalid-choice' | 'invalid-confidence' | 'error' | 'timeout' | 'needs-model';
100
+ interface IDecisionOutcome {
101
+ accepted: boolean;
102
+ choice?: string;
103
+ confidence?: number;
104
+ threshold: number;
105
+ reason?: DecisionFallbackReason;
106
+ error?: string;
107
+ durationMs: number;
108
+ usage?: {
109
+ inputTokens?: number;
110
+ outputTokens?: number;
111
+ };
112
+ }
113
+ interface IDecisionEvent {
114
+ type: 'decision';
115
+ point: DecisionPoint;
116
+ accepted: boolean;
117
+ choice?: string;
118
+ confidence?: number;
119
+ threshold: number;
120
+ reason?: DecisionFallbackReason;
121
+ error?: string;
122
+ durationMs: number;
123
+ model?: string;
124
+ }
125
+ declare const askDecisionModel: (model: IDecisionModel, question: IDecisionQuestion, config?: IDecisionConfig, signal?: AbortSignal) => Promise<IDecisionOutcome>;
126
+ interface IAiSdkDecisionOptions {
127
+ name?: string;
128
+ maxRetries?: number;
129
+ headers?: Record<string, string>;
130
+ }
131
+ declare const decisionModelFromAiSdk: (model: Experimental_DecisionModel, options?: IAiSdkDecisionOptions) => IDecisionModel;
132
+
58
133
  interface PipelineDefinition {
59
134
  version: 1;
60
135
  name?: string;
@@ -295,6 +370,123 @@ declare const checkRedirect: (from: URL, to: URL) => void;
295
370
  type SafeFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
296
371
  declare const createSafeFetch: (policy?: IEgressPolicy) => SafeFetch;
297
372
 
373
+ /**
374
+ * What the `web_search` tools of the two agent packages share: the result shape and its caps, how
375
+ * a search engine's answer is cleaned before a model reads it, and the built-in adapters as pure
376
+ * request builders and response parsers (one HTTP call each). Pure, no imports: the request itself
377
+ * is made by each package's own safe fetch.
378
+ *
379
+ * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/web-search-shared.ts`) and
380
+ * `@dudko.dev/agent-web` (`src/tools/web-search-shared.ts`): change both. The Node package's
381
+ * `tests/web-search-shared.test.ts` compares the two files and tests every cap and guard here.
382
+ */
383
+ declare const WEB_SEARCH_TOOL = "web_search";
384
+ /** Results returned when neither the host nor the model says how many. */
385
+ declare const SEARCH_DEFAULT_MAX_RESULTS = 5;
386
+ /** The most results one call returns, whatever the host or the model asks for. */
387
+ declare const SEARCH_MAX_RESULTS = 10;
388
+ /** The longest query sent to a search engine, in characters. */
389
+ declare const SEARCH_MAX_QUERY_CHARS = 400;
390
+ /** The most of a result's title a model sees. */
391
+ declare const SEARCH_MAX_TITLE_CHARS = 200;
392
+ /** A result whose URL is longer than this is dropped (a cut URL is another URL). */
393
+ declare const SEARCH_MAX_URL_CHARS = 2000;
394
+ /** The most of a result's snippet a model sees. */
395
+ declare const SEARCH_MAX_SNIPPET_CHARS = 500;
396
+ /** The most all results of one call take together (titles, URLs, snippets, dates). */
397
+ declare const SEARCH_MAX_TOTAL_CHARS = 6000;
398
+ /** One search result, as the model sees it. Third-party text: data, never instructions. */
399
+ interface ISearchResult {
400
+ title: string;
401
+ url: string;
402
+ snippet: string;
403
+ /** When the page was published or last changed, as the engine reported it. */
404
+ date?: string;
405
+ }
406
+ type SearchFreshness = 'day' | 'week' | 'month' | 'year';
407
+ /** What a search engine function is called with, next to the query. */
408
+ interface ISearchOptions {
409
+ /** How many results are wanted (1..SEARCH_MAX_RESULTS); more are cut. */
410
+ maxResults: number;
411
+ /** Only results from the last day / week / month / year, when the model asked for it. */
412
+ freshness?: SearchFreshness;
413
+ /** Aborted when the run is stopped. */
414
+ signal?: AbortSignal;
415
+ }
416
+ /**
417
+ * A search engine of the host's own: any function that answers a query with results. What it
418
+ * returns is treated like a built-in adapter's answer - cleaned, capped and filtered.
419
+ */
420
+ type SearchEngine = (query: string, options: ISearchOptions) => Promise<ISearchResult[]>;
421
+ /** The hosted search APIs with a built-in adapter. */
422
+ type SearchProvider = 'brave' | 'tavily' | 'searxng';
423
+ declare const SEARCH_PROVIDERS: readonly SearchProvider[];
424
+ /** Where each hosted API lives. SearXNG is self-hosted: its `baseURL` is the host's to give. */
425
+ declare const SEARCH_API_BASE_URL: Record<'brave' | 'tavily', string>;
426
+ /** One HTTP call to a search API. The key, if any, is in `headers` only - never in the URL. */
427
+ interface ISearchRequest {
428
+ url: string;
429
+ method: 'GET' | 'POST';
430
+ headers: Record<string, string>;
431
+ body?: string;
432
+ }
433
+ interface ISearchRequestInput {
434
+ provider: SearchProvider;
435
+ query: string;
436
+ maxResults: number;
437
+ freshness?: SearchFreshness;
438
+ apiKey?: string;
439
+ baseURL?: string;
440
+ }
441
+ /**
442
+ * The request for one query, per the API's public documentation:
443
+ * - brave: GET {base}/res/v1/web/search?q=&count= header X-Subscription-Token
444
+ * - tavily: POST {base}/search { query, max_results } header Authorization: Bearer
445
+ * - searxng: GET {base}/search?q=&format=json no key
446
+ */
447
+ declare const buildSearchRequest: (input: ISearchRequestInput) => ISearchRequest;
448
+ /**
449
+ * The results inside an API's JSON answer, mapped to `{ title, url, snippet, date }` and nothing
450
+ * else. Still raw third-party values: `sanitizeSearchResults` is what makes them safe to show.
451
+ */
452
+ declare const parseSearchResponse: (provider: SearchProvider, json: unknown) => unknown[];
453
+ interface ISanitizedSearch {
454
+ results: ISearchResult[];
455
+ /** Results dropped because the host's egress policy does not let the model reach them. */
456
+ filtered: number;
457
+ /** True when results were left out for a cap (the count, or the total size). */
458
+ truncated: boolean;
459
+ }
460
+ /**
461
+ * What a model sees of an engine's answer. `raw` is whatever came back - nothing about it is
462
+ * trusted: a result needs a valid http(s) URL, every field is cleaned and capped, duplicates go,
463
+ * `accepts` (the egress policy) drops links the model could not fetch, and the list stops at
464
+ * `maxResults` and at SEARCH_MAX_TOTAL_CHARS.
465
+ */
466
+ declare const sanitizeSearchResults: (raw: unknown, options?: {
467
+ maxResults?: number;
468
+ accepts?: (url: URL) => boolean;
469
+ }) => ISanitizedSearch;
470
+
471
+ interface ISearchConfig {
472
+ engine?: SearchEngine;
473
+ provider?: SearchProvider;
474
+ apiKey?: string;
475
+ baseURL?: string;
476
+ maxResults?: number;
477
+ allowPrivateNetwork?: boolean;
478
+ timeoutMs?: number;
479
+ readOnly?: boolean;
480
+ }
481
+ interface IWebSearchOptions {
482
+ search: ISearchConfig;
483
+ egress?: boolean | IEgressPolicy;
484
+ fetch?: SafeFetch;
485
+ }
486
+ declare const searchEgressPolicy: (search: ISearchConfig, egress?: boolean | IEgressPolicy) => IEgressPolicy;
487
+ declare const createWebSearchTool: (options: IWebSearchOptions) => Tool;
488
+ declare const createSearchTools: (search: ISearchConfig | undefined, egress?: boolean | IEgressPolicy) => ToolSet | undefined;
489
+
298
490
  declare const RUN_JS_TOOL = "run_js";
299
491
  interface ISandboxConfig {
300
492
  timeoutMs?: number;
@@ -327,10 +519,179 @@ declare class SandboxUnavailableError extends Error {
327
519
  constructor(message: string);
328
520
  }
329
521
 
522
+ declare const GENERATE_IMAGE_TOOL = "generate_image";
523
+ declare const GENERATE_SPEECH_TOOL = "generate_speech";
524
+ declare const TRANSCRIBE_AUDIO_TOOL = "transcribe_audio";
525
+ type MediaKind = 'image' | 'speech' | 'transcription';
526
+ declare const MEDIA_DEFAULT_MAX_CALLS = 8;
527
+ declare const MEDIA_TIMEOUT_MS = 120000;
528
+ declare const MEDIA_MAX_IMAGE_BYTES: number;
529
+ declare const MEDIA_MAX_SPEECH_BYTES: number;
530
+ declare const MEDIA_MAX_AUDIO_INPUT_BYTES: number;
531
+ declare const MEDIA_MAX_PROMPT_CHARS = 4000;
532
+ declare const MEDIA_MAX_SPEECH_CHARS = 4000;
533
+ declare const MEDIA_MAX_TRANSCRIPT_CHARS = 20000;
534
+ declare const MEDIA_MAX_ATTACHED_AUDIO = 4;
535
+ declare const MEDIA_FOLDER = "media";
536
+ declare class MediaError extends Error {
537
+ constructor(message: string);
538
+ toJSON(): string;
539
+ }
540
+ declare class MediaBudgetError extends MediaError {
541
+ constructor(cap: number);
542
+ }
543
+ declare const MEDIA_IMAGE_TYPES: Readonly<Record<string, string>>;
544
+ declare const MEDIA_AUDIO_TYPES: Readonly<Record<string, string>>;
545
+ declare const sniffMediaType: (bytes: Uint8Array) => string | undefined;
546
+ interface IAcceptedMedia {
547
+ mediaType: string;
548
+ ext: string;
549
+ }
550
+ declare const acceptMedia: (family: "image" | "audio", bytes: Uint8Array, maxBytes: number, what: string) => IAcceptedMedia;
551
+ interface IMediaUsage {
552
+ mediaCalls: number;
553
+ imagesGenerated: number;
554
+ speechCharacters: number;
555
+ transcriptionSeconds: number;
556
+ }
557
+ declare const mediaUsageOf: (usage: Partial<IMediaUsage> | undefined) => IMediaUsage | undefined;
558
+ interface ITranscriptBlock {
559
+ name: string;
560
+ text: string;
561
+ language?: string;
562
+ durationInSeconds?: number;
563
+ }
564
+ declare const wrapTranscript: (block: ITranscriptBlock) => string;
565
+
566
+ type IMediaModelSpec = IAgentStageOverride & {
567
+ model: string;
568
+ };
569
+ type MediaImageModel = Exclude<ImageModel, string>;
570
+ type MediaSpeechModel = Exclude<SpeechModel, string>;
571
+ type MediaTranscriptionModel = Exclude<TranscriptionModel, string>;
572
+ interface IMediaConfig {
573
+ imageModel?: MediaImageModel | IMediaModelSpec;
574
+ speechModel?: MediaSpeechModel | IMediaModelSpec;
575
+ transcriptionModel?: MediaTranscriptionModel | IMediaModelSpec;
576
+ maxCalls?: number;
577
+ timeoutMs?: number;
578
+ dir?: string;
579
+ voice?: string;
580
+ speechFormat?: string;
581
+ }
582
+ interface IRunFile {
583
+ data: string | Uint8Array;
584
+ mediaType?: string;
585
+ name?: string;
586
+ }
587
+ interface IMediaFile {
588
+ path: string;
589
+ mediaType: string;
590
+ bytes: number;
591
+ }
592
+ interface ITranscription {
593
+ path: string;
594
+ text: string;
595
+ language?: string;
596
+ durationInSeconds?: number;
597
+ truncated?: true;
598
+ untrusted: true;
599
+ }
600
+ interface IMedia {
601
+ tools: ToolSet;
602
+ attach: (input: string, files: IRunFile[], signal?: AbortSignal) => Promise<string>;
603
+ }
604
+ declare const createMedia: (config: IAgentConfig) => Promise<IMedia | undefined>;
605
+
606
+ declare const SPAWN_SUBAGENT_TOOL = "spawn_subagent";
607
+ type SubagentDefaultTools = 'read-only' | 'all';
608
+ interface IDynamicSubagentsConfig {
609
+ maxDepth?: number;
610
+ maxChildren?: number;
611
+ maxConcurrent?: number;
612
+ budgetShare?: number;
613
+ minTokens?: number;
614
+ timeoutMs?: number;
615
+ defaultTools?: SubagentDefaultTools;
616
+ }
617
+ interface ISubagentsConfig {
618
+ dynamic?: boolean | IDynamicSubagentsConfig;
619
+ }
620
+ interface IResolvedDynamicSubagents {
621
+ maxDepth: number;
622
+ maxChildren: number;
623
+ maxConcurrent: number;
624
+ budgetShare: number;
625
+ minTokens: number;
626
+ timeoutMs: number;
627
+ defaultTools: SubagentDefaultTools;
628
+ }
629
+ declare const SUBAGENT_DEFAULTS: IResolvedDynamicSubagents;
630
+ declare const SUBAGENT_MAX_DEPTH_LIMIT = 4;
631
+ /**
632
+ * The effective settings, or undefined when the feature is off (nothing is mounted, nothing is
633
+ * added to a prompt). A bad value is a configuration error, thrown when the agent is created.
634
+ */
635
+ declare const resolveDynamicSubagents: (subagents: ISubagentsConfig | undefined) => IResolvedDynamicSubagents | undefined;
636
+ /**
637
+ * A spawn that was refused: the model reads the message as the tool's error and can correct the
638
+ * call or carry on without a helper.
639
+ */
640
+ declare class SubagentSpawnError extends Error {
641
+ constructor(message: string);
642
+ toJSON(): string;
643
+ }
644
+ declare const SPAWN_INPUT_SCHEMA: {
645
+ readonly type: "object";
646
+ readonly properties: {
647
+ readonly task: {
648
+ readonly type: "string";
649
+ 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.";
650
+ };
651
+ readonly role: {
652
+ readonly type: "string";
653
+ 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\").";
654
+ };
655
+ readonly tools: {
656
+ readonly type: "array";
657
+ readonly items: {
658
+ readonly type: "string";
659
+ };
660
+ 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.";
661
+ };
662
+ };
663
+ readonly required: readonly ["task"];
664
+ readonly additionalProperties: false;
665
+ };
666
+ /**
667
+ * A child's event on its way up through the subagent `parentId` (the `subagent.event` envelope is
668
+ * added by the caller). A `subagent.start` is emitted with `depth: 1` and the id of the run that
669
+ * made the call as `parentId`; each subagent it passes through on the way up adds one level, and
670
+ * the first one - its real parent - puts its own id in `parentId`. So at the top of the stream
671
+ * every start carries its true depth and parent, whatever mix of static and dynamic subagents,
672
+ * threads and workers is below.
673
+ */
674
+ declare const adoptSubagentEvent: <E extends {
675
+ type: string;
676
+ }>(event: E, parentId: string) => E;
677
+
330
678
  type ProviderType = 'openai' | 'anthropic' | 'openai-compatible' | 'google' | 'xai' | 'azure' | 'amazon-bedrock' | 'google-vertex' | 'deepseek' | 'gateway' | 'cloudflare';
331
679
  type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug';
332
680
  type ToolSelectionStrategy = 'all' | 'plan-narrowed' | 'search' | 'auto';
333
681
  type AgentStage = 'planner' | 'executor' | 'replanner' | 'synthesizer';
682
+ type ModelTier = 'light' | 'standard' | 'strong';
683
+ type StepComplexity = 'low' | 'medium' | 'high';
684
+ type TierReason = 'planned' | 'default' | 'fallback';
685
+ type EscalationReason = 'blocked' | 'empty-result' | 'tool-arguments' | 'output-cut' | 'error';
686
+ interface IStepEscalation {
687
+ from: ModelTier;
688
+ to: ModelTier;
689
+ reason: EscalationReason;
690
+ }
691
+ interface IEscalationConfig {
692
+ maxPerStep?: number;
693
+ maxPerRun?: number;
694
+ }
334
695
  type ThinkingLevel = 'provider-default' | 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
335
696
  interface IThinkingConfig {
336
697
  level?: ThinkingLevel;
@@ -408,6 +769,10 @@ interface IToolApprovalRequest {
408
769
  readOnly: boolean;
409
770
  step?: IPlanStep;
410
771
  runId?: string;
772
+ subagent?: {
773
+ id: string;
774
+ depth: number;
775
+ };
411
776
  }
412
777
  type ToolApprovalDecision = boolean | {
413
778
  approved: boolean;
@@ -462,14 +827,21 @@ interface IAgentConfig {
462
827
  providerOptions?: Record<string, unknown>;
463
828
  planner?: IAgentStageOverride;
464
829
  synthesizer?: IAgentStageOverride;
830
+ executorTiers?: Partial<Record<ModelTier, IAgentStageOverride>>;
831
+ escalation?: boolean | IEscalationConfig;
465
832
  /** @deprecated use `planner: { model }` */
466
833
  plannerModel?: string;
467
834
  /** @deprecated use `synthesizer: { model }` */
468
835
  synthesizerModel?: string;
469
836
  mcpServers: Record<string, IMcpServerConfig>;
470
837
  egress?: boolean | IEgressPolicy;
838
+ search?: ISearchConfig;
839
+ decisionModel?: IDecisionModel;
840
+ decision?: IDecisionConfig;
471
841
  learning?: boolean | ILearningConfig;
472
842
  sandbox?: boolean | ISandboxConfig;
843
+ media?: IMediaConfig;
844
+ subagents?: ISubagentsConfig;
473
845
  tools?: ToolSet;
474
846
  availableTools?: string[];
475
847
  excludedTools?: string[];
@@ -488,6 +860,7 @@ interface IAgentConfig {
488
860
  toolApproval?: IToolApprovalConfig;
489
861
  toolSearchThreshold?: number;
490
862
  mcpConnectTimeoutMs?: number;
863
+ mcpInstructions?: boolean;
491
864
  promptCaching?: PromptCachingSetting;
492
865
  llmTimeoutMs?: number;
493
866
  llmMaxRetries?: number;
@@ -513,6 +886,11 @@ interface IUsage {
513
886
  reasoningTokens?: number;
514
887
  cachedInputTokens?: number;
515
888
  cacheWriteTokens?: number;
889
+ mediaCalls?: number;
890
+ imagesGenerated?: number;
891
+ speechCharacters?: number;
892
+ transcriptionSeconds?: number;
893
+ decisionCalls?: number;
516
894
  }
517
895
  interface IPlanStep {
518
896
  id: string;
@@ -520,6 +898,7 @@ interface IPlanStep {
520
898
  expectedOutcome: string;
521
899
  suggestedTools?: string[];
522
900
  requiresTools?: boolean;
901
+ complexity?: StepComplexity;
523
902
  }
524
903
  interface IPlan {
525
904
  thought: string;
@@ -537,10 +916,13 @@ interface IStepResult {
537
916
  }[];
538
917
  durationMs: number;
539
918
  blocked: boolean;
919
+ tier?: ModelTier;
920
+ model?: string;
921
+ escalations?: IStepEscalation[];
540
922
  }
541
923
  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';
924
+ type ReplanCause = 'last-step' | 'clean-step' | 'llm-decision' | 'user-message' | 'decision-model';
925
+ type UsagePhase = 'plan' | 'execute' | 'replan' | 'synthesize' | 'compact' | 'subagent' | 'decision' | 'media';
544
926
  type AgentEventBody = {
545
927
  type: 'plan.thought-delta';
546
928
  delta: string;
@@ -559,6 +941,16 @@ type AgentEventBody = {
559
941
  type: 'step.start';
560
942
  step: IPlanStep;
561
943
  index: number;
944
+ tier?: ModelTier;
945
+ model?: string;
946
+ tierReason?: TierReason;
947
+ } | {
948
+ type: 'step.escalated';
949
+ step: IPlanStep;
950
+ from: ModelTier;
951
+ to: ModelTier;
952
+ model: string;
953
+ reason: EscalationReason;
562
954
  } | {
563
955
  type: 'step.text-delta';
564
956
  step: IPlanStep;
@@ -587,7 +979,9 @@ type AgentEventBody = {
587
979
  mode: 'continue' | 'revise' | 'finish';
588
980
  reason: string;
589
981
  cause: ReplanCause;
590
- } | {
982
+ failed?: true;
983
+ confidence?: number;
984
+ } | IDecisionEvent | {
591
985
  type: 'final.text-delta';
592
986
  delta: string;
593
987
  } | {
@@ -635,6 +1029,10 @@ type AgentEventBody = {
635
1029
  input: unknown;
636
1030
  readOnly: boolean;
637
1031
  step?: IPlanStep;
1032
+ subagent?: {
1033
+ id: string;
1034
+ depth: number;
1035
+ };
638
1036
  } | {
639
1037
  type: 'tool.approval-resolved';
640
1038
  id: string;
@@ -648,6 +1046,11 @@ type AgentEventBody = {
648
1046
  name: string;
649
1047
  task: string;
650
1048
  profile?: string;
1049
+ parentId?: string;
1050
+ depth?: number;
1051
+ dynamic?: true;
1052
+ role?: string;
1053
+ tools?: string[];
651
1054
  } | {
652
1055
  type: 'subagent.event';
653
1056
  id: string;
@@ -665,6 +1068,7 @@ type AgentEventBody = {
665
1068
  name: string;
666
1069
  error: string;
667
1070
  stopped?: boolean;
1071
+ usage?: IUsage;
668
1072
  } | {
669
1073
  type: 'message.queued';
670
1074
  id: string;
@@ -690,6 +1094,22 @@ type AgentEventBody = {
690
1094
  } | {
691
1095
  type: 'skill.forgotten';
692
1096
  name: string;
1097
+ } | {
1098
+ type: 'media.generated';
1099
+ kind: 'image' | 'speech';
1100
+ path: string;
1101
+ mediaType: string;
1102
+ bytes: number;
1103
+ model: string;
1104
+ step?: IPlanStep;
1105
+ } | {
1106
+ type: 'media.transcribed';
1107
+ source: 'attachment' | 'tool';
1108
+ name: string;
1109
+ text: string;
1110
+ language?: string;
1111
+ durationInSeconds?: number;
1112
+ model: string;
693
1113
  } | {
694
1114
  type: 'revisions.exceeded';
695
1115
  cap: number;
@@ -712,6 +1132,7 @@ interface IStepStartInfo {
712
1132
  interface IAgentRunOptions {
713
1133
  input: string;
714
1134
  history?: IConversationTurn[];
1135
+ files?: IRunFile[];
715
1136
  signal?: AbortSignal;
716
1137
  onEvent?: EventHandler;
717
1138
  onStepStart?: (info: IStepStartInfo) => void;
@@ -750,6 +1171,8 @@ interface IRunSnapshot {
750
1171
  text: string;
751
1172
  reconciled: boolean;
752
1173
  }[];
1174
+ escalations?: number;
1175
+ subagentsSpawned?: number;
753
1176
  }
754
1177
  interface IPersistence {
755
1178
  onRunStart?: (snapshot: IRunSnapshot) => void | Promise<void>;
@@ -835,10 +1258,14 @@ interface IToolDecision {
835
1258
  */
836
1259
  declare const decideToolPermission: (input: IToolDecisionInput) => IToolDecision;
837
1260
 
1261
+ 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:]";
1262
+ declare const isReplayedToolOutput: (output: unknown) => boolean;
1263
+
838
1264
  declare const getCurrentRunId: () => string | undefined;
839
1265
  declare const getCurrentRunSandbox: () => string | undefined;
840
1266
 
841
1267
  declare const redactHeaders: (headers: Record<string, string> | undefined) => Record<string, string> | undefined;
1268
+ type IFilledUsage = Required<Omit<IUsage, 'decisionCalls' | keyof IMediaUsage>> & Pick<IUsage, 'decisionCalls'> & Partial<IMediaUsage>;
842
1269
  interface ISdkUsageLike {
843
1270
  inputTokens?: number;
844
1271
  outputTokens?: number;
@@ -850,11 +1277,16 @@ interface ISdkUsageLike {
850
1277
  outputTokenDetails?: {
851
1278
  reasoningTokens?: number;
852
1279
  };
1280
+ decisionCalls?: number;
853
1281
  reasoningTokens?: number;
854
1282
  cachedInputTokens?: number;
1283
+ mediaCalls?: number;
1284
+ imagesGenerated?: number;
1285
+ speechCharacters?: number;
1286
+ transcriptionSeconds?: number;
855
1287
  }
856
- declare const normalizeUsage: (usage: ISdkUsageLike | undefined | null) => Required<IUsage>;
857
- declare const addUsage: (a: IUsage, b: IUsage) => Required<IUsage>;
1288
+ declare const normalizeUsage: (usage: ISdkUsageLike | undefined | null) => IFilledUsage;
1289
+ declare const addUsage: (a: IUsage, b: IUsage) => IFilledUsage;
858
1290
 
859
1291
  /**
860
1292
  * OAuth 2.1 for remote MCP servers, from Node.
@@ -1045,6 +1477,34 @@ declare const finishMcpOAuth: (provider: NodeOAuthProvider, callback: {
1045
1477
  iss?: string;
1046
1478
  }, opts?: IOAuthRequestOptions) => Promise<void>;
1047
1479
 
1480
+ /**
1481
+ * What the MCP connectors of the two agent packages share: how a server's `instructions` reach a
1482
+ * system prompt, and how a tool result's `structuredContent` reaches the model. Pure, no imports.
1483
+ *
1484
+ * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/mcp-shared.ts`) and
1485
+ * `@dudko.dev/agent-web` (`src/mcp/shared.ts`): change both. The Node package's
1486
+ * `tests/mcp-shared.test.ts` compares the two files and tests every cap and guard here.
1487
+ */
1488
+ /** The `instructions` one connected MCP server returned in its `initialize` result. */
1489
+ interface McpServerInstructions {
1490
+ /** The server's name: its key in the host's configuration. */
1491
+ server: string;
1492
+ instructions: string;
1493
+ }
1494
+ /** The most one server's instructions take in a system prompt, in characters. */
1495
+ declare const MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER = 2000;
1496
+ /** The most all servers' instructions take together, in characters. */
1497
+ declare const MCP_INSTRUCTIONS_MAX_CHARS_TOTAL = 8000;
1498
+ /**
1499
+ * The system-prompt section for the servers' instructions, or '' when no server sent any (the
1500
+ * prompt is then exactly what it was). Each server's text is capped
1501
+ * (MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER), so is the sum (MCP_INSTRUCTIONS_MAX_CHARS_TOTAL, in
1502
+ * the order given: a server past the total is named as omitted), and every line of it is
1503
+ * prefixed with "| ", so a server cannot write something that reads as a heading of this prompt
1504
+ * or as another server's note.
1505
+ */
1506
+ declare const renderMcpInstructions: (list: readonly McpServerInstructions[] | undefined) => string;
1507
+
1048
1508
  /**
1049
1509
  * Enterprise-Managed Authorization for remote MCP servers (the MCP extension
1050
1510
  * `io.modelcontextprotocol/enterprise-managed-authorization`, also called Cross
@@ -1553,6 +2013,16 @@ interface IWebFetchOptions {
1553
2013
  declare const createWebFetchTool: (options?: IWebFetchOptions) => Tool;
1554
2014
  declare const createEgressTools: (egress: boolean | IEgressPolicy | undefined) => ToolSet | undefined;
1555
2015
 
2016
+ interface IResolvedStage {
2017
+ providerType: ProviderType;
2018
+ baseURL?: string;
2019
+ apiKey: string;
2020
+ model: string;
2021
+ providerOptions?: Record<string, unknown>;
2022
+ }
2023
+ type MediaModelKind = 'image' | 'speech' | 'transcription';
2024
+ declare const buildMediaModelFromStage: (clientName: string, stage: IResolvedStage, kind: MediaModelKind) => Promise<unknown>;
2025
+
1556
2026
  interface ISandboxDeps {
1557
2027
  workerUrl?: URL;
1558
2028
  peerInstalled?: () => boolean;
@@ -1575,7 +2045,7 @@ interface Pipeline {
1575
2045
  close: () => Promise<void>;
1576
2046
  }
1577
2047
  declare const createPipeline: (definition: PipelineDefinition, options: PipelineOptions) => Pipeline;
1578
- type PipelineModelConfig = Pick<IAgentConfig, 'model'> & Partial<Pick<IAgentConfig, 'providerType' | 'baseURL' | 'apiKey' | 'providerOptions' | 'planner' | 'synthesizer'>>;
2048
+ type PipelineModelConfig = Pick<IAgentConfig, 'model'> & Partial<Pick<IAgentConfig, 'providerType' | 'baseURL' | 'apiKey' | 'providerOptions' | 'planner' | 'synthesizer' | 'executorTiers'>>;
1579
2049
  interface NodeResolverOptions {
1580
2050
  base: IAgentConfig;
1581
2051
  models?: Record<string, PipelineModelConfig>;
@@ -1612,5 +2082,5 @@ interface ISubagentToolOptions {
1612
2082
  */
1613
2083
  declare const createSubagentTool: (opts: ISubagentToolOptions) => Tool;
1614
2084
 
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 };
2085
+ 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 };
2086
+ 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 };