@dudko.dev/agent-web 0.0.37 → 0.0.39

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 (39) hide show
  1. package/README.md +179 -7
  2. package/dist/agent-web.js +315 -125
  3. package/dist/agent-web.js.map +1 -1
  4. package/dist/{chunk-Y7OGKYE5.js → chunk-3V27UZT6.js} +35 -9
  5. package/dist/chunk-3V27UZT6.js.map +1 -0
  6. package/dist/chunk-A6ZJALLU.js +254 -0
  7. package/dist/chunk-A6ZJALLU.js.map +1 -0
  8. package/dist/chunk-CTXDKSDD.js +39 -0
  9. package/dist/chunk-CTXDKSDD.js.map +1 -0
  10. package/dist/chunk-TZITKUFW.js +800 -0
  11. package/dist/chunk-TZITKUFW.js.map +1 -0
  12. package/dist/chunk-V3JOK7EW.js +929 -0
  13. package/dist/chunk-V3JOK7EW.js.map +1 -0
  14. package/dist/index.cjs +7253 -2159
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +1714 -324
  17. package/dist/index.d.ts +1714 -324
  18. package/dist/index.js +3832 -862
  19. package/dist/index.js.map +1 -1
  20. package/dist/mcp.cjs +1031 -24
  21. package/dist/mcp.cjs.map +1 -1
  22. package/dist/mcp.d.cts +409 -13
  23. package/dist/mcp.d.ts +409 -13
  24. package/dist/mcp.js +918 -26
  25. package/dist/mcp.js.map +1 -1
  26. package/dist/sandbox-KG6OUG24.js +269 -0
  27. package/dist/sandbox-KG6OUG24.js.map +1 -0
  28. package/dist/sandbox-worker.cjs +745 -0
  29. package/dist/sandbox-worker.cjs.map +1 -0
  30. package/dist/sandbox-worker.d.cts +37 -0
  31. package/dist/sandbox-worker.d.ts +37 -0
  32. package/dist/sandbox-worker.js +27 -0
  33. package/dist/sandbox-worker.js.map +1 -0
  34. package/dist/{webllm-PCPDLDQA.js → webllm-BEL5A4OF.js} +2 -2
  35. package/package.json +23 -4
  36. package/dist/chunk-CPSDKXO6.js +0 -132
  37. package/dist/chunk-CPSDKXO6.js.map +0 -1
  38. package/dist/chunk-Y7OGKYE5.js.map +0 -1
  39. /package/dist/{webllm-PCPDLDQA.js.map → webllm-BEL5A4OF.js.map} +0 -0
package/dist/index.d.cts CHANGED
@@ -1,5 +1,4 @@
1
- import * as ai from 'ai';
2
- import { LanguageModel, ToolSet, Tool, FilePart, SystemModelMessage, ModelMessage, generateText, streamText } from 'ai';
1
+ import { LanguageModel, ToolSet, Experimental_DecisionModel, FilePart, ImageModel, SpeechModel, TranscriptionModel, Tool, SystemModelMessage, ModelMessage, generateText, streamText } from 'ai';
3
2
  import { V as VaultOptions } from './vault-BatBaRQP.cjs';
4
3
  export { I as IndexedDBVault } from './vault-BatBaRQP.cjs';
5
4
  import { A as AgentToolSet, a as AgentTool } from './types-DwSMj_Xs.cjs';
@@ -7,6 +6,37 @@ export { p as promptHintOf } from './types-DwSMj_Xs.cjs';
7
6
  import { z, ZodType } from 'zod';
8
7
  import { IDBPDatabase } from 'idb';
9
8
 
9
+ /** Executor models by strength (`config.executorTiers`), weakest first. */
10
+ type ModelTier = 'light' | 'standard' | 'strong';
11
+ /**
12
+ * What the planner marks a step with when tiers are configured: how hard the step is. It names
13
+ * the tier the step should run on (low -> light, medium -> standard, high -> strong).
14
+ */
15
+ type StepComplexity = 'low' | 'medium' | 'high';
16
+ /**
17
+ * Why a step started on its tier: 'planned' - the planner's complexity named a configured tier;
18
+ * 'default' - the planner did not mark the step, so it runs on `standard`; 'fallback' - the tier
19
+ * the planner named is not configured, so the nearest configured one runs it.
20
+ */
21
+ type TierReason = 'planned' | 'default' | 'fallback';
22
+ /**
23
+ * Why a step was retried on a stronger tier: the executor reported a blocker; it produced no
24
+ * text and no successful tool call; it kept calling a tool with arguments that did not parse;
25
+ * its output was cut by the per-call cap; or its model call failed.
26
+ */
27
+ type EscalationReason = 'blocked' | 'empty-result' | 'tool-arguments' | 'output-cut' | 'error';
28
+ /** One escalation of a step, kept on its result. */
29
+ interface IStepEscalation {
30
+ from: ModelTier;
31
+ to: ModelTier;
32
+ reason: EscalationReason;
33
+ }
34
+ interface EscalationConfig {
35
+ /** Retries of ONE step on stronger tiers (each on the next stronger configured tier). Default 1. */
36
+ maxPerStep?: number;
37
+ /** Escalations in one run, a resumed run included. Default 3. */
38
+ maxPerRun?: number;
39
+ }
10
40
  /** A single step of a plan. Mirrors the Node sibling's IPlanStep. */
11
41
  interface IPlanStep {
12
42
  id: string;
@@ -16,6 +46,8 @@ interface IPlanStep {
16
46
  suggestedTools?: string[];
17
47
  /** Set by the pipeline when suggestedTools were named but all were unknown. */
18
48
  requiresTools?: boolean;
49
+ /** How hard the planner rated the step. Only when `config.executorTiers` is on. */
50
+ complexity?: StepComplexity;
19
51
  }
20
52
  interface IPlan {
21
53
  thought: string;
@@ -31,6 +63,20 @@ interface IUsage {
31
63
  cachedInputTokens?: number;
32
64
  /** Input tokens written to the provider's prompt cache. */
33
65
  cacheWriteTokens?: number;
66
+ /**
67
+ * What the media models (`config.media`) were asked for - calls (failed ones included), images
68
+ * written, characters sent to the speech model, seconds of audio transcribed. Not tokens and
69
+ * not part of the counts above. Absent until a media model is called (see `IMediaUsage`).
70
+ */
71
+ mediaCalls?: number;
72
+ imagesGenerated?: number;
73
+ speechCharacters?: number;
74
+ transcriptionSeconds?: number;
75
+ /**
76
+ * Calls made to `config.decisionModel`. A call is not a token: what the API billed for it (when
77
+ * it says) is in the token fields, the number of calls is here. Absent when zero.
78
+ */
79
+ decisionCalls?: number;
34
80
  }
35
81
  interface IToolCall {
36
82
  name: string;
@@ -44,6 +90,13 @@ interface IStepResult {
44
90
  toolCalls: IToolCall[];
45
91
  /** True when the executor signalled it could not complete the step ([BLOCKER]). */
46
92
  blocked: boolean;
93
+ /**
94
+ * Only when `config.executorTiers` is on: the tier (and its model id) the step FINISHED on, and
95
+ * the escalations that led there, in order. `toolCalls` then holds every attempt's calls.
96
+ */
97
+ tier?: ModelTier;
98
+ model?: string;
99
+ escalations?: IStepEscalation[];
47
100
  }
48
101
 
49
102
  /**
@@ -115,6 +168,10 @@ interface RunSnapshot {
115
168
  text: string;
116
169
  reconciled: boolean;
117
170
  }[];
171
+ /** Escalations so far (counts against `escalation.maxPerRun` on resume). */
172
+ escalations?: number;
173
+ /** Helpers the model started so far (counts against `subagents.dynamic.maxChildren` on resume). */
174
+ subagentsSpawned?: number;
118
175
  /** Final answer (status `complete`). */
119
176
  text?: string;
120
177
  /** What ended the run (status `failed`). */
@@ -517,6 +574,12 @@ interface PlannerPromptContext {
517
574
  skills?: string;
518
575
  /** The catalogue is condensed and the executor can search the rest (large catalogues). */
519
576
  searchMode?: boolean;
577
+ /** Set when `config.sandbox` is on: when to plan a `run_js` step. */
578
+ sandbox?: string;
579
+ /** Set while `spawn_subagent` is callable (`subagents.dynamic`): when a helper is worth a step. */
580
+ subagents?: string;
581
+ /** Set when `config.executorTiers` is on: the planner rates every step's complexity. */
582
+ tiers?: boolean;
520
583
  }
521
584
  interface ExecutorPromptContext {
522
585
  goal: string;
@@ -540,6 +603,10 @@ interface ExecutorPromptContext {
540
603
  learning?: {
541
604
  fetch: boolean;
542
605
  };
606
+ /** Set when `config.sandbox` is on: what `run_js` is, and never to report code as run without it. */
607
+ sandbox?: string;
608
+ /** Set while `spawn_subagent` is callable (`subagents.dynamic`): when to hand work to a helper. */
609
+ subagents?: string;
543
610
  }
544
611
  interface ReplannerPromptContext {
545
612
  goal: string;
@@ -552,6 +619,8 @@ interface ReplannerPromptContext {
552
619
  updates?: string[];
553
620
  /** How many of `updates` (the last ones) the plan has not been weighed against yet. */
554
621
  newUpdates?: number;
622
+ /** Set when `config.executorTiers` is on: the steps of a revised plan are rated too. */
623
+ tiers?: boolean;
555
624
  }
556
625
  interface SynthesizerPromptContext {
557
626
  goal: string;
@@ -562,6 +631,8 @@ interface SynthesizerPromptContext {
562
631
  activeSkills?: string;
563
632
  /** What the user said while the run was going, oldest first. */
564
633
  updates?: string[];
634
+ /** Set when `config.sandbox` is on: the output of code is reported only when `run_js` returned it. */
635
+ sandbox?: string;
565
636
  }
566
637
  interface Prompts {
567
638
  planner(ctx: PlannerPromptContext): PromptParts;
@@ -807,6 +878,156 @@ interface SaveSkillInput {
807
878
  */
808
879
  declare const createLearning: (cfg: LearningConfig, skills: Skill[], warn: (message: string) => void) => Promise<Learning>;
809
880
 
881
+ interface ISandboxConfig {
882
+ timeoutMs?: number;
883
+ memoryLimitBytes?: number;
884
+ maxOutputChars?: number;
885
+ maxCodeChars?: number;
886
+ files?: boolean;
887
+ }
888
+ interface ISandboxLimits {
889
+ timeoutMs: number;
890
+ memoryLimitBytes: number;
891
+ maxOutputChars: number;
892
+ maxCodeChars: number;
893
+ }
894
+ interface ISandboxError {
895
+ name: string;
896
+ message: string;
897
+ stack?: string;
898
+ }
899
+ interface ISandboxResult {
900
+ ok: boolean;
901
+ stdout: string;
902
+ result?: unknown;
903
+ error?: ISandboxError;
904
+ truncated: boolean;
905
+ durationMs: number;
906
+ }
907
+
908
+ /**
909
+ * `config.sandbox`: the `run_js` tool - the model's code runs in QuickJS compiled to
910
+ * WebAssembly (the optional peer `quickjs-emscripten`), never in the page's own JavaScript
911
+ * engine. This module is loaded only when the sandbox is switched on.
912
+ *
913
+ * Where the guest runs:
914
+ * - `worker` given: in a Web Worker that is terminated when the run is over or over time (the
915
+ * hard stop). One worker per run. The worker module is `@dudko.dev/agent-web/sandbox-worker`.
916
+ * - no `worker`: on the page's thread, stopped by the engine's interrupt handler only. A single
917
+ * long native call in the guest then blocks the page until it returns - prefer a worker.
918
+ */
919
+ /** A worker as the sandbox uses it: a real `Worker`, or a `MessagePort` in tests. */
920
+ interface SandboxWorkerLike {
921
+ postMessage(message: unknown): void;
922
+ addEventListener(type: string, listener: (ev: any) => void): void;
923
+ terminate?(): void;
924
+ }
925
+ interface SandboxConfig extends ISandboxConfig {
926
+ /**
927
+ * Builds a fresh Worker for one run, e.g.
928
+ * `() => new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' })`
929
+ * (Vite: `import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'`). Without it
930
+ * the guest runs on the page's thread - isolated all the same, but only softly interruptible.
931
+ */
932
+ worker?: () => SandboxWorkerLike;
933
+ /**
934
+ * Loads the engine for the page-thread fallback, e.g. `() => import('quickjs-emscripten')`, so
935
+ * that your bundler resolves it. Default: a runtime `import('quickjs-emscripten')` (Node, or a
936
+ * page with an import map). Not used when `worker` is given.
937
+ */
938
+ engine?: () => Promise<unknown>;
939
+ }
940
+
941
+ declare const SPAWN_SUBAGENT_TOOL = "spawn_subagent";
942
+ type SubagentDefaultTools = 'read-only' | 'all';
943
+ interface IDynamicSubagentsConfig {
944
+ maxDepth?: number;
945
+ maxChildren?: number;
946
+ maxConcurrent?: number;
947
+ budgetShare?: number;
948
+ minTokens?: number;
949
+ timeoutMs?: number;
950
+ defaultTools?: SubagentDefaultTools;
951
+ }
952
+ interface ISubagentsConfig {
953
+ dynamic?: boolean | IDynamicSubagentsConfig;
954
+ }
955
+ interface IResolvedDynamicSubagents {
956
+ maxDepth: number;
957
+ maxChildren: number;
958
+ maxConcurrent: number;
959
+ budgetShare: number;
960
+ minTokens: number;
961
+ timeoutMs: number;
962
+ defaultTools: SubagentDefaultTools;
963
+ }
964
+ declare const SUBAGENT_DEFAULTS: IResolvedDynamicSubagents;
965
+ declare const SUBAGENT_MAX_DEPTH_LIMIT = 4;
966
+ /**
967
+ * The effective settings, or undefined when the feature is off (nothing is mounted, nothing is
968
+ * added to a prompt). A bad value is a configuration error, thrown when the agent is created.
969
+ */
970
+ declare const resolveDynamicSubagents: (subagents: ISubagentsConfig | undefined) => IResolvedDynamicSubagents | undefined;
971
+ /**
972
+ * A spawn that was refused: the model reads the message as the tool's error and can correct the
973
+ * call or carry on without a helper.
974
+ */
975
+ declare class SubagentSpawnError extends Error {
976
+ constructor(message: string);
977
+ toJSON(): string;
978
+ }
979
+ declare const SPAWN_INPUT_SCHEMA: {
980
+ readonly type: "object";
981
+ readonly properties: {
982
+ readonly task: {
983
+ readonly type: "string";
984
+ 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.";
985
+ };
986
+ readonly role: {
987
+ readonly type: "string";
988
+ 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\").";
989
+ };
990
+ readonly tools: {
991
+ readonly type: "array";
992
+ readonly items: {
993
+ readonly type: "string";
994
+ };
995
+ 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.";
996
+ };
997
+ };
998
+ readonly required: readonly ["task"];
999
+ readonly additionalProperties: false;
1000
+ };
1001
+ interface ISpawnTokenLimits {
1002
+ maxInputTokens?: number;
1003
+ maxOutputTokens?: number;
1004
+ maxReasoningTokens?: number;
1005
+ maxTotalTokens?: number;
1006
+ }
1007
+ interface ISpawnUsage {
1008
+ inputTokens: number;
1009
+ outputTokens: number;
1010
+ totalTokens: number;
1011
+ reasoningTokens?: number;
1012
+ }
1013
+ interface ISpawnReservation {
1014
+ limits: ISpawnTokenLimits;
1015
+ maxToolCalls?: number;
1016
+ usage: () => ISpawnUsage;
1017
+ toolCalls: () => number;
1018
+ }
1019
+ /**
1020
+ * A child's event on its way up through the subagent `parentId` (the `subagent.event` envelope is
1021
+ * added by the caller). A `subagent.start` is emitted with `depth: 1` and the id of the run that
1022
+ * made the call as `parentId`; each subagent it passes through on the way up adds one level, and
1023
+ * the first one - its real parent - puts its own id in `parentId`. So at the top of the stream
1024
+ * every start carries its true depth and parent, whatever mix of static and dynamic subagents,
1025
+ * threads and workers is below.
1026
+ */
1027
+ declare const adoptSubagentEvent: <E extends {
1028
+ type: string;
1029
+ }>(event: E, parentId: string) => E;
1030
+
810
1031
  type EgressErrorCode = 'disabled' | 'bad-url' | 'bad-protocol' | 'bad-port' | 'bad-method' | 'credentials-in-url' | 'denied-host' | 'not-allowed-host' | 'denied-address' | 'bad-redirect' | 'network' | 'too-large' | 'timeout';
811
1032
  declare class EgressError extends Error {
812
1033
  readonly code: EgressErrorCode;
@@ -875,249 +1096,448 @@ declare const createWebFetchTool: (options?: IWebFetchOptions) => AgentTool;
875
1096
  declare const createEgressTools: (egress: boolean | IEgressPolicy | undefined) => AgentToolSet | undefined;
876
1097
 
877
1098
  /**
878
- * Tool consent. Every tool call passes a gate that decides allow / ask / deny:
879
- *
880
- * - `autopilot` — run everything (default; explicit `rules` still apply);
881
- * - `ask-writes` — run read-only tools, ask before anything that may change state;
882
- * - `ask-all` — ask before every call;
883
- * - `read-only` — run read-only tools, refuse the rest without asking.
1099
+ * What the `web_search` tools of the two agent packages share: the result shape and its caps, how
1100
+ * a search engine's answer is cleaned before a model reads it, and the built-in adapters as pure
1101
+ * request builders and response parsers (one HTTP call each). Pure, no imports: the request itself
1102
+ * is made by each package's own safe fetch.
884
1103
  *
885
- * A tool is read-only when its MCP annotations say so (`readOnlyHint`) or the
886
- * host marked it (`defineTool({ readOnly: true })` / `markReadOnly`). Unknown =
887
- * may write: the safe assumption.
888
- */
889
- type ToolApprovalMode = 'autopilot' | 'ask-writes' | 'ask-all' | 'read-only';
890
- type ToolPermission = 'allow' | 'ask' | 'deny';
891
- declare const TOOL_APPROVAL_MODES: readonly ToolApprovalMode[];
892
- interface ToolApprovalRequest {
893
- /** Unique per request — echo it back from a UI. */
894
- id: string;
895
- toolName: string;
896
- input: unknown;
897
- readOnly: boolean;
898
- step?: IPlanStep;
1104
+ * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/web-search-shared.ts`) and
1105
+ * `@dudko.dev/agent-web` (`src/tools/web-search-shared.ts`): change both. The Node package's
1106
+ * `tests/web-search-shared.test.ts` compares the two files and tests every cap and guard here.
1107
+ */
1108
+ declare const WEB_SEARCH_TOOL = "web_search";
1109
+ /** Results returned when neither the host nor the model says how many. */
1110
+ declare const SEARCH_DEFAULT_MAX_RESULTS = 5;
1111
+ /** The most results one call returns, whatever the host or the model asks for. */
1112
+ declare const SEARCH_MAX_RESULTS = 10;
1113
+ /** The longest query sent to a search engine, in characters. */
1114
+ declare const SEARCH_MAX_QUERY_CHARS = 400;
1115
+ /** The most of a result's title a model sees. */
1116
+ declare const SEARCH_MAX_TITLE_CHARS = 200;
1117
+ /** A result whose URL is longer than this is dropped (a cut URL is another URL). */
1118
+ declare const SEARCH_MAX_URL_CHARS = 2000;
1119
+ /** The most of a result's snippet a model sees. */
1120
+ declare const SEARCH_MAX_SNIPPET_CHARS = 500;
1121
+ /** The most all results of one call take together (titles, URLs, snippets, dates). */
1122
+ declare const SEARCH_MAX_TOTAL_CHARS = 6000;
1123
+ /** One search result, as the model sees it. Third-party text: data, never instructions. */
1124
+ interface ISearchResult {
1125
+ title: string;
1126
+ url: string;
1127
+ snippet: string;
1128
+ /** When the page was published or last changed, as the engine reported it. */
1129
+ date?: string;
1130
+ }
1131
+ type SearchFreshness = 'day' | 'week' | 'month' | 'year';
1132
+ /** What a search engine function is called with, next to the query. */
1133
+ interface ISearchOptions {
1134
+ /** How many results are wanted (1..SEARCH_MAX_RESULTS); more are cut. */
1135
+ maxResults: number;
1136
+ /** Only results from the last day / week / month / year, when the model asked for it. */
1137
+ freshness?: SearchFreshness;
1138
+ /** Aborted when the run is stopped. */
1139
+ signal?: AbortSignal;
899
1140
  }
900
1141
  /**
901
- * `true`/`false`, or an object. `remember: true` on an approval allows this
902
- * tool for the rest of the agent's life ("always allow").
1142
+ * A search engine of the host's own: any function that answers a query with results. What it
1143
+ * returns is treated like a built-in adapter's answer - cleaned, capped and filtered.
903
1144
  */
904
- type ToolApprovalDecision = boolean | {
905
- approved: boolean;
906
- reason?: string;
907
- remember?: boolean;
908
- };
909
- interface ToolApprovalConfig {
910
- /** Default policy (default 'autopilot'). */
911
- mode?: ToolApprovalMode;
912
- /**
913
- * Per-tool overrides by exact name or `*` glob, e.g. `{ 'github__delete_*': 'deny' }`.
914
- * They win over the mode — an explicit 'ask' still asks under autopilot.
915
- */
916
- rules?: Record<string, ToolPermission>;
917
- /** Resolves an approval request (a UI prompt, a policy service, …). */
918
- onRequest?: (req: ToolApprovalRequest) => ToolApprovalDecision | Promise<ToolApprovalDecision>;
919
- /** No decision within this many ms → deny. Default: wait indefinitely. */
920
- timeoutMs?: number;
1145
+ type SearchEngine = (query: string, options: ISearchOptions) => Promise<ISearchResult[]>;
1146
+ /** The hosted search APIs with a built-in adapter. */
1147
+ type SearchProvider = 'brave' | 'tavily' | 'searxng';
1148
+ declare const SEARCH_PROVIDERS: readonly SearchProvider[];
1149
+ /** Where each hosted API lives. SearXNG is self-hosted: its `baseURL` is the host's to give. */
1150
+ declare const SEARCH_API_BASE_URL: Record<'brave' | 'tavily', string>;
1151
+ /** One HTTP call to a search API. The key, if any, is in `headers` only - never in the URL. */
1152
+ interface ISearchRequest {
1153
+ url: string;
1154
+ method: 'GET' | 'POST';
1155
+ headers: Record<string, string>;
1156
+ body?: string;
921
1157
  }
922
- /** Raised by a denied tool call; recorded as a failed call the replanner sees. */
923
- declare class ToolDeniedError extends Error {
924
- constructor(reason?: string);
925
- toJSON(): string;
1158
+ interface ISearchRequestInput {
1159
+ provider: SearchProvider;
1160
+ query: string;
1161
+ maxResults: number;
1162
+ freshness?: SearchFreshness;
1163
+ apiKey?: string;
1164
+ baseURL?: string;
926
1165
  }
927
- /** Mark a tool as read-only so `ask-writes` / `read-only` let it through. Returns it. */
928
- declare const markReadOnly: <T extends object>(tool: T, readOnly?: boolean) => T;
929
- declare const isReadOnlyTool: (tool: Tool | undefined) => boolean;
930
- /** The most specific matching rule: an exact name, else the longest glob. Pure. */
931
- declare const matchRule: (rules: Record<string, ToolPermission> | undefined, toolName: string) => ToolPermission | undefined;
932
1166
  /**
933
- * What the gate does for one call, before any human is involved. Order:
934
- * remembered "always allow" → most specific rule → mode default. Pure.
1167
+ * The request for one query, per the API's public documentation:
1168
+ * - brave: GET {base}/res/v1/web/search?q=&count= header X-Subscription-Token
1169
+ * - tavily: POST {base}/search { query, max_results } header Authorization: Bearer
1170
+ * - searxng: GET {base}/search?q=&format=json no key
935
1171
  */
936
- declare const decideToolPermission: (opts: {
937
- toolName: string;
938
- readOnly: boolean;
939
- mode: ToolApprovalMode;
940
- rules?: Record<string, ToolPermission>;
941
- remembered?: ReadonlySet<string>;
942
- }) => ToolPermission;
943
-
944
- /** Force a tool-calling strategy, or let the agent pick per model ('auto'). */
945
- type ToolMode = 'auto' | 'native' | 'prompted';
1172
+ declare const buildSearchRequest: (input: ISearchRequestInput) => ISearchRequest;
946
1173
  /**
947
- * When to consult the replanner after an executed step (given `replan` is on):
948
- * 'failure' — after a blocked step or a failed tool call (default);
949
- * 'always' — after every step, so the replanner can react to problems the host
950
- * surfaces via `describeState` (one extra model call per step);
951
- * predicate — decides per step result; closes over host state if needed, and
952
- * falls back to 'failure' behaviour if it throws.
1174
+ * The results inside an API's JSON answer, mapped to `{ title, url, snippet, date }` and nothing
1175
+ * else. Still raw third-party values: `sanitizeSearchResults` is what makes them safe to show.
953
1176
  */
954
- type ReplanTrigger = 'failure' | 'always' | ((result: IStepResult) => boolean | Promise<boolean>);
1177
+ declare const parseSearchResponse: (provider: SearchProvider, json: unknown) => unknown[];
1178
+ interface ISanitizedSearch {
1179
+ results: ISearchResult[];
1180
+ /** Results dropped because the host's egress policy does not let the model reach them. */
1181
+ filtered: number;
1182
+ /** True when results were left out for a cap (the count, or the total size). */
1183
+ truncated: boolean;
1184
+ }
955
1185
  /**
956
- * 'all' — the executor sees the full ToolSet on every step.
957
- * 'plan-narrowed' — the executor sees only a step's suggestedTools (the planner
958
- * must populate them). Empty means a reasoning-only step.
959
- * 'search' — for large catalogues: the executor starts with the step's
960
- * suggestedTools plus a `find_tools` meta-tool that activates
961
- * more on demand; the planner sees a condensed catalogue.
962
- * 'auto' — 'all' up to `toolSearchThreshold` tools, 'search' above (default).
1186
+ * What a model sees of an engine's answer. `raw` is whatever came back - nothing about it is
1187
+ * trusted: a result needs a valid http(s) URL, every field is cleaned and capped, duplicates go,
1188
+ * `accepts` (the egress policy) drops links the model could not fetch, and the list stops at
1189
+ * `maxResults` and at SEARCH_MAX_TOTAL_CHARS.
963
1190
  */
964
- type ToolSelectionStrategy = 'all' | 'plan-narrowed' | 'search' | 'auto';
965
- /** Per-phase generation budgets (max output tokens). */
966
- interface PhaseBudgets {
967
- planner?: number;
968
- executor?: number;
969
- replanner?: number;
970
- synthesizer?: number;
971
- }
972
- interface BrowserAgentConfig {
973
- /** The default (executor) model: a ready AI SDK model, or a ProviderModelSpec to resolve. */
974
- model: ModelInput;
975
- /** Optional per-stage model overrides. A partial override inherits base provider/creds. */
976
- planner?: StageInput;
977
- synthesizer?: StageInput;
978
- /** Fetches API keys for ProviderModelSpec models. Default: none (inline keys only). */
979
- credentials?: CredentialStore;
980
- /** Propagated to the openai-compatible provider name and the MCP client. */
981
- clientName?: string;
1191
+ declare const sanitizeSearchResults: (raw: unknown, options?: {
1192
+ maxResults?: number;
1193
+ accepts?: (url: URL) => boolean;
1194
+ }) => ISanitizedSearch;
1195
+
1196
+ /**
1197
+ * `config.search`: the `web_search` tool, the companion of `web_fetch`. Off unless set. The
1198
+ * library ships no key and no engine of its own: the host names a hosted search API (a built-in
1199
+ * adapter, one HTTP call) or passes a function. Browser sibling of the server's `ISearchConfig`
1200
+ * - same names - except that a key is never written here: `credentialRef` names it in the
1201
+ * `CredentialStore` the agent was given (`config.credentials`).
1202
+ *
1203
+ * A page can call an API only if that API allows cross-origin requests. Tavily does; Brave does
1204
+ * not answer a preflight (use a gateway of yours as `baseURL`); a SearXNG instance does only if
1205
+ * you configure it to (or serve it from your own origin). See docs/capabilities.md.
1206
+ */
1207
+ interface ISearchConfig {
982
1208
  /**
983
- * Requests the MODEL may make (the `web_fetch` tool). Off unless set: with it off there is no
984
- * way to fetch. `true` = any public host over https; an object narrows or widens that (allow /
985
- * deny lists, ...) - see `IEgressPolicy`. A browser cannot pin DNS: prefer an `allow` list, or a
986
- * `fetch` that goes through a server-side safe fetch. Not the provider's own calls, MCP servers
987
- * or tools you pass yourself - those are your configuration, not the model's.
1209
+ * A search engine of your own: `(query, { maxResults, freshness, signal }) => results`. Its
1210
+ * requests are yours (like a tool you pass); its results are cleaned, capped and filtered like
1211
+ * an adapter's. Exactly one of `engine` / `provider`.
988
1212
  */
989
- egress?: boolean | IEgressPolicy;
990
- /** Host tools the executor may call (an AI SDK ToolSet; use defineTool). */
991
- tools?: AgentToolSet;
992
- /** Whitelist: only these tool names from `tools` are mounted (default: all). */
993
- availableTools?: string[];
994
- /** Blacklist: these tool names are removed after the whitelist is applied. */
995
- excludedTools?: string[];
996
- /** Force native/prompted tool-calling; 'auto' picks per model (default 'auto'). */
997
- toolMode?: ToolMode;
998
- /** How the executor sees the tool catalogue (default 'auto'). */
999
- toolSelectionStrategy?: ToolSelectionStrategy;
1000
- /** Catalogue size above which 'auto' switches to 'search' (default 40). */
1001
- toolSearchThreshold?: number;
1002
- /** Consent policy for tool calls: autopilot, ask before writes, ask always, read-only. */
1003
- toolApproval?: ToolApprovalConfig;
1004
- /** Reusable instruction bundles (SKILL.md) the planner/executor can pull in. */
1005
- skills?: Skill[];
1213
+ engine?: SearchEngine;
1214
+ /** A built-in adapter: 'brave' | 'tavily' | 'searxng'. */
1215
+ provider?: SearchProvider;
1006
1216
  /**
1007
- * Let the agent write down lessons as skills (`save_skill` / `forget_skill`) for the rest of the
1008
- * session: `true` keeps them in memory; `{ store: new VfsSkillStore(vfs) }` keeps them in the
1009
- * file system across sessions. Off by default. Knowledge only - see `learning.ts`.
1217
+ * Where the provider's API key is kept in the agent's `CredentialStore`. Read at each call and
1218
+ * sent in a header to that API only; never in a URL, an event, a log line, an error or a result.
1010
1219
  */
1011
- learning?: boolean | LearningConfig;
1012
- /** Prepended to every phase's system prompt. */
1013
- systemPrompt?: string;
1014
- /** Override any phase prompt builder. */
1015
- prompts?: Partial<Prompts>;
1016
- /** Serialize the host's current world state into prompt context (grounding). */
1017
- describeState?: () => string | Promise<string>;
1220
+ credentialRef?: string;
1018
1221
  /**
1019
- * Persist the transcript (e.g. new IndexedDBStore()). The last few messages
1020
- * are also read back into the planner prompt, so follow-up goals can refer
1021
- * to earlier turns.
1222
+ * Where the API lives. Required for 'searxng' (your instance); for the others it replaces the
1223
+ * public endpoint (a gateway of yours that holds the key - `credentialRef` is then optional).
1022
1224
  */
1023
- memory?: ContextStore;
1024
- sessionId?: string;
1225
+ baseURL?: string;
1226
+ /** Results per call when the model does not say (default 5, at most 10). */
1227
+ maxResults?: number;
1025
1228
  /**
1026
- * Checkpoint runs so a reload or a crashed tab does not lose finished work:
1027
- * `new IndexedDBRunStore()` survives a reload, `new MemoryRunStore()` does not.
1028
- * `run(goal, { resumeFromRunId })` then continues from the last checkpoint —
1029
- * see `RunSnapshot` for exactly what is, and is not, kept.
1229
+ * Let the SEARCH API itself be on a private / loopback address or an internal-looking name (a
1230
+ * self-hosted SearXNG). It widens nothing else: the request can still reach only that one host.
1030
1231
  */
1031
- persistence?: RunPersistence;
1032
- /** Hard cap on executed steps incl. replans (default 8). */
1033
- maxIterations?: number;
1034
- /** Cap on tool-calling rounds inside one executor call, both modes (default 4). */
1035
- maxStepsPerTask?: number;
1036
- /** Cap on replanner "revise" decisions per run (default 2). */
1037
- maxRevisions?: number;
1038
- /** Cap on tool calls per run (default: unlimited). */
1039
- maxToolCalls?: number;
1040
- /** Cap on the steps of one plan (default 8). */
1041
- maxPlanSteps?: number;
1042
- /** Per-call timeout so a hang can't freeze a run (default 120000). */
1043
- chatTimeoutMs?: number;
1044
- /** Legacy per-phase output caps; `limits.perCall` wins when both are set. */
1045
- budgets?: PhaseBudgets;
1046
- /** Run-level token budgets (input / output / thinking / total) + per-call output caps. */
1047
- limits?: TokenLimits;
1048
- temperature?: number;
1049
- /** Thinking for every stage: true, a level ('low'…'xhigh'), or { level, budgetTokens }. */
1050
- thinking?: ThinkingSetting;
1051
- /** Per-stage thinking; a stage entry wins over `thinking`. */
1052
- stageThinking?: Partial<Record<ThinkingStage, ThinkingSetting>>;
1232
+ allowPrivateNetwork?: boolean;
1233
+ /** Whole request to the search API, in ms. Default 15_000. */
1234
+ timeoutMs?: number;
1053
1235
  /**
1054
- * Whether the model accepts images. Default: inferred (`supportsImages`) —
1055
- * local/prompted models are text-only; unknown models are tried and a
1056
- * refusal is reported as ImagesNotSupportedError.
1236
+ * How the consent gate sees a search. Default true (read-only: the only host reached is the one
1237
+ * named here). false = it asks like a write - a query is text that leaves for a third party.
1057
1238
  */
1058
- vision?: boolean;
1059
- /** Per-kind override of what the model takes as attachments (`images` wins over `vision`). */
1060
- inputs?: {
1061
- images?: boolean;
1062
- pdf?: boolean;
1063
- files?: boolean;
1064
- };
1065
- /** Provider prompt caching (default true): stable system prefixes + Anthropic breakpoints. */
1066
- promptCaching?: PromptCachingSetting;
1067
- /** Context compaction (auto + manual `agent.compact()`); see CompactionConfig. */
1068
- compaction?: CompactionConfig;
1069
- /** Master switch for the replan phase (default true). */
1070
- replan?: boolean;
1071
- /** What triggers the replanner when it is on (default 'failure'). */
1072
- replanAfter?: ReplanTrigger;
1073
- /** Write a final natural-language summary (default true). */
1074
- synthesize?: boolean;
1075
- /**
1076
- * Legacy: compress stored history past this many chars after each run
1077
- * (0 = off). Used only when `compaction` is not set.
1078
- */
1079
- compressAfterChars?: number;
1080
- /** Verbosity: 'silent' | 'error' | 'warn' (default) | 'info' | 'debug'. */
1081
- logLevel?: LogLevel;
1082
- /** Console-like sink the logs go to (default: the global console). */
1083
- logger?: AgentLoggerSink;
1239
+ readOnly?: boolean;
1240
+ /** The fetch the adapter uses (default `globalThis.fetch`). Still bound to the search policy. */
1241
+ fetch?: typeof fetch;
1084
1242
  }
1085
- interface ResolvedConfig {
1086
- clientName: string;
1087
- sessionId: string;
1088
- toolMode: ToolMode;
1089
- toolSelectionStrategy: ToolSelectionStrategy;
1090
- toolSearchThreshold: number;
1091
- maxIterations: number;
1092
- maxStepsPerTask: number;
1093
- maxRevisions: number;
1094
- maxToolCalls: number;
1095
- maxPlanSteps: number;
1096
- chatTimeoutMs: number;
1097
- /** Effective per-call output caps (limits.perCall over budgets). */
1098
- budgets: Required<PhaseBudgets> & {
1099
- compaction: number;
1100
- };
1101
- limits: TokenLimits;
1102
- temperature: number | undefined;
1103
- replan: boolean;
1104
- replanAfter: ReplanTrigger;
1105
- synthesize: boolean;
1106
- compressAfterChars: number;
1107
- compaction: ResolvedCompaction;
1108
- logLevel: LogLevel;
1243
+ interface IWebSearchOptions {
1244
+ search: ISearchConfig;
1245
+ /** `config.egress`, when the agent has it: its deny list is inherited, and results the model could not fetch under it are left out. */
1246
+ egress?: boolean | IEgressPolicy;
1247
+ /** Where `search.credentialRef` is looked up (`config.credentials`). */
1248
+ credentials?: CredentialStore;
1249
+ /** A fetch of your own for the adapter's request (already bound to a policy). */
1250
+ fetch?: GuardedFetch;
1109
1251
  }
1110
1252
  /**
1111
- * The effective per-call output caps: what the host set (`limits.perCall`, then the legacy
1112
- * `budgets`) wins; every other phase gets its share of the window.
1253
+ * The policy the adapter's one request is made under. It is NOT the model's egress policy with a
1254
+ * host added: the allow list is exactly the search API's host, scheme and port, so the tool
1255
+ * cannot be steered anywhere else (a redirect is never followed), and the host's deny list
1256
+ * still wins.
1113
1257
  */
1114
- declare const resolveBudgets: (c: BrowserAgentConfig, contextWindowTokens: number) => ResolvedConfig["budgets"];
1115
- declare const resolveConfig: (c: BrowserAgentConfig) => ResolvedConfig;
1258
+ declare const searchEgressPolicy: (search: ISearchConfig, egress?: boolean | IEgressPolicy) => IEgressPolicy;
1259
+ /**
1260
+ * `web_search({ query })`: a short list of `{ title, url, snippet, date? }`. The adapter's
1261
+ * request goes through the guarded fetch under `searchEgressPolicy`; what comes back is
1262
+ * third-party text and is cleaned, capped and - when the agent has an egress policy - filtered
1263
+ * to what `web_fetch` could open, so a search is not a way to read around the allow / deny lists.
1264
+ */
1265
+ declare const createWebSearchTool: (options: IWebSearchOptions) => AgentTool;
1266
+ /** The tools `config.search` turns on (none when it is off). */
1267
+ declare const createSearchTools: (search: ISearchConfig | undefined, egress?: boolean | IEgressPolicy, credentials?: CredentialStore) => AgentToolSet | undefined;
1268
+
1269
+ interface IDecisionOption {
1270
+ id: string;
1271
+ description?: string;
1272
+ }
1273
+ interface IDecisionQuestion {
1274
+ id: string;
1275
+ prompt: string;
1276
+ options: readonly IDecisionOption[];
1277
+ context?: string;
1278
+ }
1279
+ interface IDecisionCallOptions {
1280
+ abortSignal?: AbortSignal;
1281
+ }
1282
+ interface IDecisionAnswer {
1283
+ choice: string;
1284
+ confidence: number;
1285
+ usage?: {
1286
+ inputTokens?: number;
1287
+ outputTokens?: number;
1288
+ };
1289
+ }
1290
+ interface IDecisionModel {
1291
+ readonly name?: string;
1292
+ decide: (question: IDecisionQuestion, options: IDecisionCallOptions) => Promise<IDecisionAnswer>;
1293
+ }
1294
+ interface IDecisionConfig {
1295
+ confidenceThreshold?: number;
1296
+ timeoutMs?: number;
1297
+ replan?: boolean;
1298
+ route?: boolean;
1299
+ }
1300
+ declare const DEFAULT_DECISION_CONFIDENCE_THRESHOLD = 0.8;
1301
+ declare const DEFAULT_DECISION_TIMEOUT_MS = 5000;
1302
+ type DecisionPoint = 'replan' | 'route';
1303
+ type DecisionFallbackReason = 'low-confidence' | 'invalid-choice' | 'invalid-confidence' | 'error' | 'timeout' | 'needs-model';
1304
+ interface IDecisionOutcome {
1305
+ accepted: boolean;
1306
+ choice?: string;
1307
+ confidence?: number;
1308
+ threshold: number;
1309
+ reason?: DecisionFallbackReason;
1310
+ error?: string;
1311
+ durationMs: number;
1312
+ usage?: {
1313
+ inputTokens?: number;
1314
+ outputTokens?: number;
1315
+ };
1316
+ }
1317
+ interface IDecisionEvent {
1318
+ type: 'decision';
1319
+ point: DecisionPoint;
1320
+ accepted: boolean;
1321
+ choice?: string;
1322
+ confidence?: number;
1323
+ threshold: number;
1324
+ reason?: DecisionFallbackReason;
1325
+ error?: string;
1326
+ durationMs: number;
1327
+ model?: string;
1328
+ }
1329
+ declare const askDecisionModel: (model: IDecisionModel, question: IDecisionQuestion, config?: IDecisionConfig, signal?: AbortSignal) => Promise<IDecisionOutcome>;
1330
+ interface IAiSdkDecisionOptions {
1331
+ name?: string;
1332
+ maxRetries?: number;
1333
+ headers?: Record<string, string>;
1334
+ }
1335
+ declare const decisionModelFromAiSdk: (model: Experimental_DecisionModel, options?: IAiSdkDecisionOptions) => IDecisionModel;
1336
+
1337
+ interface PipelineDefinition {
1338
+ version: 1;
1339
+ name?: string;
1340
+ entry: string;
1341
+ nodes: PipelineNode[];
1342
+ edges: PipelineEdge[];
1343
+ limits?: {
1344
+ maxNodeVisits?: number;
1345
+ maxRuns?: number;
1346
+ };
1347
+ }
1348
+ interface PipelineNode {
1349
+ id: string;
1350
+ name?: string;
1351
+ instructions?: string;
1352
+ model?: string;
1353
+ skills?: string[];
1354
+ tools?: string[];
1355
+ mcpServers?: string[];
1356
+ routes?: PipelineRoute[];
1357
+ join?: 'all' | 'any';
1358
+ settings?: Record<string, unknown>;
1359
+ position?: {
1360
+ x: number;
1361
+ y: number;
1362
+ };
1363
+ }
1364
+ interface PipelineRoute {
1365
+ label: string;
1366
+ description?: string;
1367
+ }
1368
+ type PipelineCondition = {
1369
+ kind: 'always';
1370
+ } | {
1371
+ kind: 'contains';
1372
+ text: string;
1373
+ caseSensitive?: boolean;
1374
+ } | {
1375
+ kind: 'matches';
1376
+ pattern: string;
1377
+ flags?: string;
1378
+ } | {
1379
+ kind: 'route';
1380
+ label: string;
1381
+ } | {
1382
+ kind: 'otherwise';
1383
+ };
1384
+ interface PipelineEdge {
1385
+ id?: string;
1386
+ from: string;
1387
+ to: string;
1388
+ when?: PipelineCondition;
1389
+ }
1390
+ declare const PIPELINE_LIMITS: {
1391
+ readonly maxNodeVisits: 3;
1392
+ readonly maxRuns: 25;
1393
+ readonly maxNodeVisitsCeiling: 100;
1394
+ readonly maxRunsCeiling: 1000;
1395
+ readonly maxNodes: 200;
1396
+ readonly maxEdges: 1000;
1397
+ readonly maxRoutes: 20;
1398
+ readonly maxPatternLength: 500;
1399
+ readonly maxPatternProgram: 1000;
1400
+ readonly conditionInputChars: 50000;
1401
+ };
1402
+ interface PipelineUsage {
1403
+ inputTokens: number;
1404
+ outputTokens: number;
1405
+ totalTokens: number;
1406
+ reasoningTokens?: number;
1407
+ cachedInputTokens?: number;
1408
+ cacheWriteTokens?: number;
1409
+ }
1410
+ interface PipelineNodeSource {
1411
+ nodeId: string;
1412
+ name?: string;
1413
+ text: string;
1414
+ }
1415
+ interface PipelineNodeInput {
1416
+ request: string;
1417
+ from: PipelineNodeSource[];
1418
+ visit: number;
1419
+ }
1420
+ interface PipelineNodeOutput {
1421
+ text: string;
1422
+ usage?: PipelineUsage;
1423
+ route?: string;
1424
+ }
1425
+ interface PipelineNodeContext<E = never> {
1426
+ signal: AbortSignal;
1427
+ pipeline: PipelineDefinition;
1428
+ emit: (event: E) => void;
1429
+ }
1430
+ type PipelineNodeRunner<E = never> = (node: PipelineNode, input: PipelineNodeInput, ctx: PipelineNodeContext<E>) => Promise<PipelineNodeOutput>;
1431
+ type PipelineStop = 'maxRuns' | 'maxNodeVisits' | 'aborted';
1432
+ type PipelineEvent = {
1433
+ type: 'pipeline.started';
1434
+ pipeline?: string;
1435
+ } | {
1436
+ type: 'pipeline.node.started';
1437
+ nodeId: string;
1438
+ visit: number;
1439
+ from: string[];
1440
+ } | {
1441
+ type: 'pipeline.node.finished';
1442
+ nodeId: string;
1443
+ visit: number;
1444
+ text: string;
1445
+ route?: string;
1446
+ usage?: PipelineUsage;
1447
+ } | {
1448
+ type: 'pipeline.node.failed';
1449
+ nodeId: string;
1450
+ visit: number;
1451
+ error: string;
1452
+ } | {
1453
+ type: 'pipeline.node.skipped';
1454
+ nodeId: string;
1455
+ from: string[];
1456
+ reason: 'maxRuns' | 'maxNodeVisits';
1457
+ } | {
1458
+ type: 'pipeline.edge';
1459
+ from: string;
1460
+ to: string;
1461
+ edgeId: string;
1462
+ visit: number;
1463
+ fired: boolean;
1464
+ } | {
1465
+ type: 'pipeline.finished';
1466
+ stoppedBy?: PipelineStop;
1467
+ runs: number;
1468
+ };
1469
+ type PipelineTraceEntry = {
1470
+ type: 'node';
1471
+ nodeId: string;
1472
+ visit: number;
1473
+ wave: number;
1474
+ from: string[];
1475
+ text: string;
1476
+ route?: string;
1477
+ usage?: PipelineUsage;
1478
+ } | {
1479
+ type: 'edge';
1480
+ from: string;
1481
+ to: string;
1482
+ edgeId: string;
1483
+ visit: number;
1484
+ fired: boolean;
1485
+ } | {
1486
+ type: 'dropped';
1487
+ nodeId: string;
1488
+ from: string[];
1489
+ reason: 'maxRuns' | 'maxNodeVisits';
1490
+ };
1491
+ interface PipelineResult {
1492
+ text: string;
1493
+ outputs: Record<string, {
1494
+ visit: number;
1495
+ text: string;
1496
+ route?: string;
1497
+ }[]>;
1498
+ trace: PipelineTraceEntry[];
1499
+ usage: PipelineUsage;
1500
+ stoppedBy?: PipelineStop;
1501
+ runs: number;
1502
+ }
1503
+ interface PipelineIssue {
1504
+ code: string;
1505
+ message: string;
1506
+ nodeId?: string;
1507
+ edgeId?: string;
1508
+ edgeIndex?: number;
1509
+ }
1510
+ interface PipelineValidation {
1511
+ ok: boolean;
1512
+ errors: PipelineIssue[];
1513
+ warnings: PipelineIssue[];
1514
+ }
1515
+ declare class PipelineValidationError extends Error {
1516
+ errors: PipelineIssue[];
1517
+ constructor(errors: PipelineIssue[]);
1518
+ }
1519
+ declare class PipelineNodeError extends Error {
1520
+ nodeId: string;
1521
+ visit: number;
1522
+ constructor(nodeId: string, visit: number, cause: unknown);
1523
+ }
1524
+ declare const testPipelineCondition: (when: PipelineCondition | undefined, output: {
1525
+ text: string;
1526
+ route?: string;
1527
+ }, matcher?: (text: string) => boolean) => boolean;
1528
+ declare const normalizePipeline: (definition: PipelineDefinition) => PipelineDefinition;
1529
+ declare const validatePipeline: (definition: PipelineDefinition) => PipelineValidation;
1530
+ declare const renderPipelineNodeInput: (input: PipelineNodeInput) => string;
1116
1531
 
1117
1532
  type ReplanMode = 'continue' | 'revise' | 'finish';
1118
1533
  type Phase = 'plan' | 'execute' | 'replan' | 'synthesize';
1119
- /** Phases a `usage` event can be charged to: the four stages plus compaction and subagents. */
1120
- type UsagePhase = Phase | 'compact' | 'subagent';
1534
+ /**
1535
+ * Phases a `usage` event can be charged to: the four stages plus compaction and subagents;
1536
+ * `decision` - a call to `config.decisionModel` (`usage.decisionCalls`, plus the tokens its API
1537
+ * reported); and 'media' - a call to an image / speech / transcription model (`config.media`),
1538
+ * whose `usage` carries the media fields and zero tokens.
1539
+ */
1540
+ type UsagePhase = Phase | 'compact' | 'subagent' | 'decision' | 'media';
1121
1541
  /**
1122
1542
  * Everything the agent does is streamed as a typed event so any UI (or none)
1123
1543
  * can render progress. The final answer arrives as a `final` event; there is no
@@ -1125,7 +1545,7 @@ type UsagePhase = Phase | 'compact' | 'subagent';
1125
1545
  * event taxonomy (no persistence/otel events), plus `model.load` for WebLLM
1126
1546
  * weight-download progress.
1127
1547
  */
1128
- type AgentEvent =
1548
+ type AgentEventBody =
1129
1549
  /**
1130
1550
  * `runId` names the run for `persistence` / `resumeFromRunId`. `resumed` is set when it
1131
1551
  * continues a checkpointed run: the steps already done and the ones still to come.
@@ -1156,11 +1576,31 @@ type AgentEvent =
1156
1576
  type: 'plan.revised';
1157
1577
  plan: IPlan;
1158
1578
  reason: string;
1159
- } | {
1579
+ }
1580
+ /**
1581
+ * `tier` / `model` / `tierReason`: only when `config.executorTiers` is on - the tier the step
1582
+ * starts on, its model id, and why that tier (see `TierReason`).
1583
+ */
1584
+ | {
1160
1585
  type: 'step.start';
1161
1586
  step: IPlanStep;
1162
1587
  index: number;
1163
1588
  total: number;
1589
+ tier?: ModelTier;
1590
+ model?: string;
1591
+ tierReason?: TierReason;
1592
+ }
1593
+ /**
1594
+ * The step failed on `from` and is retried on the stronger tier `to` (`config.escalation`);
1595
+ * `model` is the model id of `to`. Fires between the step's start and its completion.
1596
+ */
1597
+ | {
1598
+ type: 'step.escalated';
1599
+ step: IPlanStep;
1600
+ from: ModelTier;
1601
+ to: ModelTier;
1602
+ model: string;
1603
+ reason: EscalationReason;
1164
1604
  } | {
1165
1605
  type: 'step.text-delta';
1166
1606
  step: IPlanStep;
@@ -1187,13 +1627,26 @@ type AgentEvent =
1187
1627
  step: IPlanStep;
1188
1628
  result: IStepResult;
1189
1629
  }
1190
- /** `byUser`: the replanner ran because the user sent a message (`RunControl.send`), not because a step failed. */
1630
+ /**
1631
+ * `byUser`: the replanner ran because the user sent a message (`RunControl.send`), not because a
1632
+ * step failed. `failed`: the replanner call itself failed (unparsable output, the provider
1633
+ * down) and `mode: 'continue'` is the fallback, not the model's decision — the failure is the
1634
+ * `error` event (phase 'replan') just before this one. `confidence`: `config.decisionModel`
1635
+ * made this decision (the replanner was not called) - the probability it gave its choice.
1636
+ */
1191
1637
  | {
1192
1638
  type: 'replan.decision';
1193
1639
  mode: ReplanMode;
1194
1640
  reason: string;
1195
1641
  byUser?: boolean;
1196
- } | {
1642
+ failed?: true;
1643
+ confidence?: number;
1644
+ }
1645
+ /**
1646
+ * `config.decisionModel` was asked a question: its answer was used (`accepted`), or the
1647
+ * ordinary model call ran and `reason` says why.
1648
+ */
1649
+ | IDecisionEvent | {
1197
1650
  type: 'final.text-delta';
1198
1651
  delta: string;
1199
1652
  }
@@ -1251,6 +1704,33 @@ type AgentEvent =
1251
1704
  type: 'skill.forgotten';
1252
1705
  name: string;
1253
1706
  }
1707
+ /**
1708
+ * A media tool (`config.media`) wrote a file to the virtual file system: `path` is where (read
1709
+ * it with `vfs.readDataUrl(path)` to show the picture or play the audio), `mediaType` what its
1710
+ * bytes are, `bytes` its size. The bytes themselves are never in an event.
1711
+ */
1712
+ | {
1713
+ type: 'media.generated';
1714
+ kind: 'image' | 'speech';
1715
+ path: string;
1716
+ mediaType: string;
1717
+ bytes: number;
1718
+ model: string;
1719
+ step?: IPlanStep;
1720
+ }
1721
+ /**
1722
+ * An audio file was transcribed: one the user attached to the run ('attachment') or one the
1723
+ * model asked about ('tool'). `text` is what the model reads of it (cleaned and capped).
1724
+ */
1725
+ | {
1726
+ type: 'media.transcribed';
1727
+ source: 'attachment' | 'tool';
1728
+ name: string;
1729
+ text: string;
1730
+ language?: string;
1731
+ durationInSeconds?: number;
1732
+ model: string;
1733
+ }
1254
1734
  /** find_tools activated more tools (large-catalogue search mode). */
1255
1735
  | {
1256
1736
  type: 'tools.discovered';
@@ -1266,6 +1746,11 @@ type AgentEvent =
1266
1746
  input: unknown;
1267
1747
  readOnly: boolean;
1268
1748
  step?: IPlanStep;
1749
+ /** Set when a helper the model started is asking (see `ToolApprovalRequest.subagent`). */
1750
+ subagent?: {
1751
+ id: string;
1752
+ depth: number;
1753
+ };
1269
1754
  }
1270
1755
  /** A consent decision: from the user, or `automatic` (policy denial). */
1271
1756
  | {
@@ -1276,71 +1761,652 @@ type AgentEvent =
1276
1761
  reason?: string;
1277
1762
  automatic: boolean;
1278
1763
  }
1279
- /** `profile` is set when the parent chose one of the subagent's named profiles for this call. */
1764
+ /**
1765
+ * `profile` is set when the parent chose one of the subagent's named profiles for this call.
1766
+ * The tree: `parentId` is the id of the subagent that made the call, or the `runId` of the run
1767
+ * when the run itself made it; `depth` is 1 for the run's own subagents, 2 for theirs, ...
1768
+ * `dynamic` marks a helper the model started with `spawn_subagent` (`subagents.dynamic`):
1769
+ * `role` is what the model wrote for it, `tools` the tool names it was given.
1770
+ */
1280
1771
  | {
1281
1772
  type: 'subagent.start';
1282
1773
  id: string;
1283
1774
  name: string;
1284
1775
  task: string;
1285
1776
  profile?: string;
1777
+ parentId?: string;
1778
+ depth?: number;
1779
+ dynamic?: true;
1780
+ role?: string;
1781
+ tools?: string[];
1782
+ }
1783
+ /** An event of a running subagent, forwarded verbatim. */
1784
+ | {
1785
+ type: 'subagent.event';
1786
+ id: string;
1787
+ name: string;
1788
+ event: AgentEvent;
1789
+ } | {
1790
+ type: 'subagent.complete';
1791
+ id: string;
1792
+ name: string;
1793
+ text: string;
1794
+ usage: IUsage;
1795
+ }
1796
+ /**
1797
+ * `stopped` is set when the user stopped this subagent (`RunControl.stopSubagent`), as opposed
1798
+ * to it failing. `usage`: what a dynamic helper had spent when it failed (already charged to
1799
+ * the parent).
1800
+ */
1801
+ | {
1802
+ type: 'subagent.error';
1803
+ id: string;
1804
+ name: string;
1805
+ error: string;
1806
+ stopped?: boolean;
1807
+ usage?: IUsage;
1808
+ }
1809
+ /**
1810
+ * A request of the `web_fetch` tool, or of `web_search` to its search API, allowed or refused
1811
+ * by the egress policy. `url` is origin and path only (a query string can carry a secret).
1812
+ */
1813
+ | {
1814
+ type: 'egress.request';
1815
+ url: string;
1816
+ allowed: boolean;
1817
+ status?: number;
1818
+ reason?: string;
1819
+ }
1820
+ /** A message sent with `RunControl.send` is waiting for the next boundary. */
1821
+ | {
1822
+ type: 'message.queued';
1823
+ id: string;
1824
+ text: string;
1825
+ }
1826
+ /**
1827
+ * The message reached the model. `round` = between tool-calling rounds inside a step, so
1828
+ * the rest of that step can act on it (the replanner weighs it at the end of the step);
1829
+ * `step` = at a step boundary, where it forces the replanner to look at the plan;
1830
+ * `final` = just before the answer is written.
1831
+ */
1832
+ | {
1833
+ type: 'message.delivered';
1834
+ id: string;
1835
+ text: string;
1836
+ at: 'round' | 'step' | 'final';
1837
+ } | {
1838
+ type: 'stopped';
1839
+ } | {
1840
+ type: 'error';
1841
+ phase: Phase | 'run';
1842
+ error: string;
1843
+ }
1844
+ /** A pipeline's own events (`createPipeline`): the run, each node visit, each edge decision. */
1845
+ | PipelineEvent;
1846
+ /**
1847
+ * `nodeId` / `visit` are set on the events a pipeline forwards from a node's agent (and on the
1848
+ * `pipeline.node.*` events themselves).
1849
+ */
1850
+ type AgentEvent = AgentEventBody & {
1851
+ nodeId?: string;
1852
+ visit?: number;
1853
+ };
1854
+ type AgentEventHandler = (event: AgentEvent) => void;
1855
+
1856
+ /**
1857
+ * Attachments sent with a run: images, PDFs and other files the provider can
1858
+ * read, given as bytes / base64 / a data URL — or as an http(s) URL, which
1859
+ * providers that accept links (Gemini, Claude, OpenAI) fetch themselves and the
1860
+ * AI SDK downloads for the rest (from the browser: subject to CORS).
1861
+ */
1862
+ interface RunFile {
1863
+ /** Base64 (no prefix), a data URL ("data:image/png;base64,…"), raw bytes, or an http(s) URL. */
1864
+ data: string | Uint8Array | URL;
1865
+ /** e.g. "image/png", "application/pdf" — read from a data URL when omitted. */
1866
+ mediaType?: string;
1867
+ /** Shown in the transcript, in memory and in errors. */
1868
+ name?: string;
1869
+ }
1870
+ /** An image attachment (same shape; kept as its own name for clarity). */
1871
+ type RunImage = RunFile;
1872
+ /** The kinds of attachment the agent reasons about separately. */
1873
+ type AttachmentKind = 'image' | 'pdf' | 'file';
1874
+ /** The media type of an attachment (declared, from a data URL, or from a URL's extension). */
1875
+ declare const mediaTypeOf: (f: RunFile) => string | undefined;
1876
+ declare const attachmentKind: (f: RunFile) => AttachmentKind;
1877
+ /** Raised when attachments are sent to a model that cannot take them. */
1878
+ declare class AttachmentsNotSupportedError extends Error {
1879
+ readonly kind: AttachmentKind;
1880
+ constructor(model: string, kind: AttachmentKind, detail?: string);
1881
+ toJSON(): string;
1882
+ }
1883
+ /** The image flavour of {@link AttachmentsNotSupportedError}. */
1884
+ declare class ImagesNotSupportedError extends AttachmentsNotSupportedError {
1885
+ constructor(model: string, detail?: string);
1886
+ }
1887
+ /**
1888
+ * An AI SDK file part (images included — the v7 SDK deprecates the separate
1889
+ * image part). An http(s) URL is passed as a URL: providers that accept links
1890
+ * fetch it themselves, and the SDK downloads it for the rest.
1891
+ */
1892
+ declare const toFilePart: (f: RunFile) => FilePart;
1893
+ /** Back-compat name. */
1894
+ declare const toImagePart: (f: RunFile) => FilePart;
1895
+ /** Does a provider error look like a refusal of attachment input? */
1896
+ declare const isAttachmentRefusal: (err: unknown) => boolean;
1897
+ /** Back-compat name. */
1898
+ declare const isImageRefusal: (err: unknown) => boolean;
1899
+
1900
+ /**
1901
+ * A media model as a spec: a full `ProviderModelSpec`, or a partial one that inherits the
1902
+ * provider, key reference and endpoint of `config.model` and names only the media model. The key
1903
+ * is never written here: `credentialRef` names it in the agent's `CredentialStore`.
1904
+ */
1905
+ type IMediaModelSpec = Omit<ProviderModelSpec, 'apiKey'> | (Omit<StageOverride, 'apiKey'> & {
1906
+ model: string;
1907
+ });
1908
+ /**
1909
+ * A ready AI SDK model object (e.g. `openai.image('gpt-image-1')`). A bare string is not taken:
1910
+ * it would mean the SDK's global gateway, a provider nobody configured here.
1911
+ */
1912
+ type MediaImageModel = Exclude<ImageModel, string>;
1913
+ type MediaSpeechModel = Exclude<SpeechModel, string>;
1914
+ type MediaTranscriptionModel = Exclude<TranscriptionModel, string>;
1915
+ /**
1916
+ * `config.media`: three optional modalities as tools, each mounted only when its model is set -
1917
+ * `generate_image`, `generate_speech`, `transcribe_audio` - and the transcription of audio the
1918
+ * user attaches to a run. Browser sibling of the server's `IMediaConfig` (same names), except
1919
+ * that generated files go to a virtual file system instead of a directory.
1920
+ */
1921
+ interface IMediaConfig {
1922
+ /** Mounts `generate_image` (a prompt becomes an image file in the workspace). */
1923
+ imageModel?: MediaImageModel | IMediaModelSpec;
1924
+ /** Mounts `generate_speech` (text becomes an audio file in the workspace). */
1925
+ speechModel?: MediaSpeechModel | IMediaModelSpec;
1926
+ /**
1927
+ * Audio attached to a run (`run(goal, { files })`) is transcribed once and the model reads the
1928
+ * text; with a file system it also mounts `transcribe_audio` (an audio file of the workspace).
1929
+ */
1930
+ transcriptionModel?: MediaTranscriptionModel | IMediaModelSpec;
1931
+ /**
1932
+ * Media calls one run may make, attachments included. Default 8 (`MEDIA_DEFAULT_MAX_CALLS`);
1933
+ * 0 = no cap. `maxToolCalls` counts the tool calls as well.
1934
+ */
1935
+ maxCalls?: number;
1936
+ /** One call to a media model, in ms. Default 120 000. */
1937
+ timeoutMs?: number;
1938
+ /**
1939
+ * Where generated files are written and where `transcribe_audio` reads. Default: the file
1940
+ * system of the mounted file tools (`createFileTools(vfs)`). An image or a speech model without
1941
+ * either is a configuration error: the bytes must not go to the language model.
1942
+ */
1943
+ files?: VirtualFileSystem;
1944
+ /** The folder of that file system generated files go to. Default '/media'. */
1945
+ folder?: string;
1946
+ /** The voice of `generate_speech` when the model names none (provider-specific id). */
1947
+ voice?: string;
1948
+ /** The audio format asked of the speech model ('mp3', 'wav', ...). Default: the provider's. */
1949
+ speechFormat?: string;
1950
+ /**
1951
+ * Transcribe audio attachments instead of sending them to the language model (default true).
1952
+ * Set false for a model that listens to audio itself and should get the file.
1953
+ */
1954
+ transcribeAttachments?: boolean;
1955
+ }
1956
+ /** What `generate_image` / `generate_speech` return: where the file is, never its bytes. */
1957
+ interface IMediaFile {
1958
+ path: string;
1959
+ mediaType: string;
1960
+ bytes: number;
1961
+ }
1962
+ /** What `transcribe_audio` returns. */
1963
+ interface ITranscription {
1964
+ path: string;
1965
+ text: string;
1966
+ language?: string;
1967
+ durationInSeconds?: number;
1968
+ truncated?: true;
1969
+ untrusted: true;
1970
+ }
1971
+ /** What a media call can reach of the run that made it (the tool's run context, or the runner). */
1972
+ interface IMediaRun {
1973
+ emit?: (event: AgentEvent) => void;
1974
+ step?: IPlanStep;
1975
+ signal?: AbortSignal;
1976
+ /** Charge the call to the run (phase 'media'). */
1977
+ addUsage?: (usage: IUsage, phase?: 'media') => void;
1978
+ /** The run's usage so far: the cap counts the media calls in it (a resumed run's included). */
1979
+ usage?: () => IUsage;
1980
+ runId?: string;
1981
+ }
1982
+ interface IMedia {
1983
+ /** The tools the configured models switch on (maybe none). */
1984
+ tools: AgentToolSet;
1985
+ /** True when audio attachments are transcribed (a transcription model, not switched off). */
1986
+ transcribes: boolean;
1987
+ /**
1988
+ * Transcribe the audio among a run's attachments: the goal with the transcripts under it, and
1989
+ * the attachments that are left for the language model.
1990
+ */
1991
+ attach: (goal: string, files: RunFile[], run: IMediaRun) => Promise<{
1992
+ goal: string;
1993
+ rest: RunFile[];
1994
+ }>;
1995
+ }
1996
+ interface IMediaOptions {
1997
+ media: IMediaConfig | undefined;
1998
+ /** `config.model`: a partial media spec inherits its provider, key reference and endpoint. */
1999
+ base?: ModelInput;
2000
+ credentials?: CredentialStore;
2001
+ clientName?: string;
2002
+ /** The agent's host tools: the file system of mounted file tools is the default workspace. */
2003
+ tools?: AgentToolSet;
2004
+ }
2005
+ /**
2006
+ * Build what `config.media` switches on. Undefined when it names no model: no tool, no prompt
2007
+ * text, nothing loaded.
2008
+ */
2009
+ declare const createMedia: (o: IMediaOptions) => Promise<IMedia | undefined>;
2010
+
2011
+ /**
2012
+ * `config.decisionModel` as a spec: a hosted decision API the agent calls itself, with the
2013
+ * user's key. The key is never written here: `credentialRef` names it in the agent's
2014
+ * `CredentialStore`. The request goes through the guarded fetch under `decisionEgressPolicy` -
2015
+ * it can reach that API's host and nothing else.
2016
+ *
2017
+ * Only APIs that answer a page are listed. Google's Decisions API does (its preflight allows any
2018
+ * origin and the `x-goog-api-key` header). TypeSafe's own API refuses cross-origin calls
2019
+ * ("Disallowed CORS origin"): from a browser, reach Jev through a gateway of yours and pass an
2020
+ * `IDecisionModel` (see docs/capabilities.md).
2021
+ */
2022
+ interface IDecisionModelSpec {
2023
+ /** 'google': the Gemini Decisions API, through the optional peer `@ai-sdk/google`. */
2024
+ providerType: 'google';
2025
+ /** e.g. 'gemini-decision-1'. */
2026
+ model: string;
2027
+ /** Where the API key is kept in the agent's `CredentialStore`. */
2028
+ credentialRef?: string;
2029
+ /** Replaces the public endpoint (a gateway of yours that holds the key: `credentialRef` is then optional). */
2030
+ baseURL?: string;
2031
+ /** Extra request headers (e.g. a gateway's own). */
2032
+ headers?: Record<string, string>;
2033
+ /** Let the API itself be on a private / loopback address (a local gateway). Widens nothing else. */
2034
+ allowPrivateNetwork?: boolean;
2035
+ /** The fetch under the guard (default `globalThis.fetch`). */
2036
+ fetch?: typeof fetch;
2037
+ }
2038
+ declare const DECISION_PROVIDERS: readonly ["google"];
2039
+ /**
2040
+ * The policy the decision call is made under: exactly the API's host, scheme and port, POST only,
2041
+ * no redirect. It is not the model's `egress` policy and takes nothing from it.
2042
+ */
2043
+ declare const decisionEgressPolicy: (spec: IDecisionModelSpec) => IEgressPolicy;
2044
+ /**
2045
+ * `config.decisionModel` -> the model the agent asks, or undefined when the feature is off. An
2046
+ * `IDecisionModel` passes through untouched (its requests are the host's, like a tool's).
2047
+ */
2048
+ declare const resolveDecisionModel: (input: IDecisionModel | IDecisionModelSpec | undefined, credentials?: CredentialStore) => Promise<IDecisionModel | undefined>;
2049
+
2050
+ /**
2051
+ * Tool consent. Every tool call passes a gate that decides allow / ask / deny:
2052
+ *
2053
+ * - `autopilot` — run everything (default; explicit `rules` still apply);
2054
+ * - `ask-writes` — run read-only tools, ask before anything that may change state;
2055
+ * - `ask-all` — ask before every call;
2056
+ * - `read-only` — run read-only tools, refuse the rest without asking.
2057
+ *
2058
+ * A tool is read-only when its MCP annotations say so (`readOnlyHint`) or the
2059
+ * host marked it (`defineTool({ readOnly: true })` / `markReadOnly`). Unknown =
2060
+ * may write: the safe assumption.
2061
+ */
2062
+ type ToolApprovalMode = 'autopilot' | 'ask-writes' | 'ask-all' | 'read-only';
2063
+ type ToolPermission = 'allow' | 'ask' | 'deny';
2064
+ declare const TOOL_APPROVAL_MODES: readonly ToolApprovalMode[];
2065
+ interface ToolApprovalRequest {
2066
+ /** Unique per request — echo it back from a UI. */
2067
+ id: string;
2068
+ toolName: string;
2069
+ input: unknown;
2070
+ readOnly: boolean;
2071
+ step?: IPlanStep;
2072
+ /**
2073
+ * Set when the call comes from a helper the model started (`subagents.dynamic`), not from the
2074
+ * run itself: the helper's id (as in its `subagent.start` event) and its depth.
2075
+ */
2076
+ subagent?: {
2077
+ id: string;
2078
+ depth: number;
2079
+ };
2080
+ }
2081
+ /**
2082
+ * `true`/`false`, or an object. `remember: true` on an approval allows this
2083
+ * tool for the rest of the agent's life ("always allow").
2084
+ */
2085
+ type ToolApprovalDecision = boolean | {
2086
+ approved: boolean;
2087
+ reason?: string;
2088
+ remember?: boolean;
2089
+ };
2090
+ interface ToolApprovalConfig {
2091
+ /** Default policy (default 'autopilot'). */
2092
+ mode?: ToolApprovalMode;
2093
+ /**
2094
+ * Per-tool overrides by exact name or `*` glob, e.g. `{ 'github__delete_*': 'deny' }`.
2095
+ * They win over the mode — an explicit 'ask' still asks under autopilot.
2096
+ */
2097
+ rules?: Record<string, ToolPermission>;
2098
+ /** Resolves an approval request (a UI prompt, a policy service, …). */
2099
+ onRequest?: (req: ToolApprovalRequest) => ToolApprovalDecision | Promise<ToolApprovalDecision>;
2100
+ /** No decision within this many ms → deny. Default: wait indefinitely. */
2101
+ timeoutMs?: number;
2102
+ }
2103
+ /** Raised by a denied tool call; recorded as a failed call the replanner sees. */
2104
+ declare class ToolDeniedError extends Error {
2105
+ constructor(reason?: string);
2106
+ toJSON(): string;
2107
+ }
2108
+ /** Mark a tool as read-only so `ask-writes` / `read-only` let it through. Returns it. */
2109
+ declare const markReadOnly: <T extends object>(tool: T, readOnly?: boolean) => T;
2110
+ declare const isReadOnlyTool: (tool: Tool | undefined) => boolean;
2111
+ /** The most specific matching rule: an exact name, else the longest glob. Pure. */
2112
+ declare const matchRule: (rules: Record<string, ToolPermission> | undefined, toolName: string) => ToolPermission | undefined;
2113
+ /**
2114
+ * What the gate does for one call, before any human is involved. Order:
2115
+ * remembered "always allow" → most specific rule → mode default. Pure.
2116
+ */
2117
+ declare const decideToolPermission: (opts: {
2118
+ toolName: string;
2119
+ readOnly: boolean;
2120
+ mode: ToolApprovalMode;
2121
+ rules?: Record<string, ToolPermission>;
2122
+ remembered?: ReadonlySet<string>;
2123
+ }) => ToolPermission;
2124
+
2125
+ /** Force a tool-calling strategy, or let the agent pick per model ('auto'). */
2126
+ type ToolMode = 'auto' | 'native' | 'prompted';
2127
+ /**
2128
+ * When to consult the replanner after an executed step (given `replan` is on):
2129
+ * 'failure' — after a blocked step or a failed tool call (default);
2130
+ * 'always' — after every step, so the replanner can react to problems the host
2131
+ * surfaces via `describeState` (one extra model call per step);
2132
+ * predicate — decides per step result; closes over host state if needed, and
2133
+ * falls back to 'failure' behaviour if it throws.
2134
+ */
2135
+ type ReplanTrigger = 'failure' | 'always' | ((result: IStepResult) => boolean | Promise<boolean>);
2136
+ /**
2137
+ * 'all' — the executor sees the full ToolSet on every step.
2138
+ * 'plan-narrowed' — the executor sees only a step's suggestedTools (the planner
2139
+ * must populate them). Empty means a reasoning-only step.
2140
+ * 'search' — for large catalogues: the executor starts with the step's
2141
+ * suggestedTools plus a `find_tools` meta-tool that activates
2142
+ * more on demand; the planner sees a condensed catalogue.
2143
+ * 'auto' — 'all' up to `toolSearchThreshold` tools, 'search' above (default).
2144
+ */
2145
+ type ToolSelectionStrategy = 'all' | 'plan-narrowed' | 'search' | 'auto';
2146
+ /** Per-phase generation budgets (max output tokens). */
2147
+ interface PhaseBudgets {
2148
+ planner?: number;
2149
+ executor?: number;
2150
+ replanner?: number;
2151
+ synthesizer?: number;
2152
+ }
2153
+ interface BrowserAgentConfig {
2154
+ /** The default (executor) model: a ready AI SDK model, or a ProviderModelSpec to resolve. */
2155
+ model: ModelInput;
2156
+ /** Optional per-stage model overrides. A partial override inherits base provider/creds. */
2157
+ planner?: StageInput;
2158
+ synthesizer?: StageInput;
2159
+ /**
2160
+ * Executor models by tier. Off unless `light` or `strong` is set: with neither, nothing about a
2161
+ * run changes. Each is a stage input like `planner` (a model, a spec, or a partial override of
2162
+ * the base); `standard` is `model` unless overridden here. With tiers on, the planner marks
2163
+ * every step with a `complexity` and the executor runs it on that tier's model (low -> light,
2164
+ * medium -> standard, high -> strong); a tier that is not configured falls back to the nearest
2165
+ * configured one (the stronger of two equally near). Every step is fitted to the SMALLEST
2166
+ * window among the models in play (a local model's is read from it; state a cloud model's in
2167
+ * `compaction.contextWindowTokens`).
2168
+ */
2169
+ executorTiers?: Partial<Record<ModelTier, StageInput>>;
2170
+ /**
2171
+ * When a step fails in a way a stronger model could fix (a blocker, no result, tool arguments
2172
+ * that keep failing to parse, output cut by the cap, a failed model call), retry it on the next
2173
+ * stronger configured tier BEFORE the replanner is consulted. The retry continues the step: it
2174
+ * is shown what the first attempt already did, and a write that already succeeded is not
2175
+ * executed again. Never on a stop, refused credentials (401 / 403), a rate limit (429), a spent
2176
+ * budget or a tool the user denied. Default: on when `executorTiers` is on (`false` turns it
2177
+ * off); without tiers it does nothing.
2178
+ */
2179
+ escalation?: boolean | EscalationConfig;
2180
+ /** Fetches API keys for ProviderModelSpec models. Default: none (inline keys only). */
2181
+ credentials?: CredentialStore;
2182
+ /** Propagated to the openai-compatible provider name and the MCP client. */
2183
+ clientName?: string;
2184
+ /**
2185
+ * Requests the MODEL may make (the `web_fetch` tool). Off unless set: with it off there is no
2186
+ * way to fetch. `true` = any public host over https; an object narrows or widens that (allow /
2187
+ * deny lists, ...) - see `IEgressPolicy`. A browser cannot pin DNS: prefer an `allow` list, or a
2188
+ * `fetch` that goes through a server-side safe fetch. Not the provider's own calls, MCP servers
2189
+ * or tools you pass yourself - those are your configuration, not the model's.
2190
+ */
2191
+ egress?: boolean | IEgressPolicy;
2192
+ /**
2193
+ * Let the model SEARCH the web (the `web_search` tool: a short list of title / url / snippet).
2194
+ * Off unless set. The library ships no key: name a hosted search API (`provider` +
2195
+ * `credentialRef` - the key stays in `credentials`, never here - or a SearXNG `baseURL`) or
2196
+ * pass a function (`engine`). The adapter's request reaches that API's host only, through the
2197
+ * guarded fetch; with `egress` set, results the model could not fetch are left out. Works
2198
+ * without `egress` (then there is no `web_fetch` to open a link). The API must allow
2199
+ * cross-origin calls from a page - see `ISearchConfig`.
2200
+ */
2201
+ search?: ISearchConfig;
2202
+ /**
2203
+ * Image generation, speech and transcription, each as a tool that exists only when its model
2204
+ * is set: `imageModel` -> `generate_image`, `speechModel` -> `generate_speech`,
2205
+ * `transcriptionModel` -> audio attachments transcribed once (the model reads the text) and,
2206
+ * with a file system, `transcribe_audio`. Off unless set. Generated files are written to the
2207
+ * virtual file system (`media.files`, else the one of the mounted file tools) and the model
2208
+ * gets a path, never the bytes. Each call is a write for tool approval, counts in
2209
+ * `usage.mediaCalls`, and a run may make `media.maxCalls` of them (default 8). Prompts, spoken text
2210
+ * and audio leave for the provider of that model; a key is named by `credentialRef`, never
2211
+ * written here. See `IMediaConfig`.
2212
+ */
2213
+ media?: IMediaConfig;
2214
+ /**
2215
+ * A decision model: a small, fast model that answers a closed question with one option and a
2216
+ * probability instead of writing text. Off unless set. Where it is confident it replaces the
2217
+ * replanner's continue / finish call and a pipeline node's route call; below
2218
+ * `decision.confidenceThreshold`, on an error, a timeout or an answer that is not an option,
2219
+ * the ordinary model call runs exactly as without it. Never consulted for tool approval or
2220
+ * egress. Either an object with `decide` (yours), or a spec of a hosted decision API a page
2221
+ * can call (`{ providerType: 'google', model: 'gemini-decision-1', credentialRef }` - the key
2222
+ * stays in `credentials`, never here).
2223
+ */
2224
+ decisionModel?: IDecisionModel | IDecisionModelSpec;
2225
+ /** The threshold (default 0.8), the timeout (default 5000 ms) and which questions it is asked. */
2226
+ decision?: IDecisionConfig;
2227
+ /**
2228
+ * Let the agent RUN JavaScript it wrote (the `run_js` tool) and read the output. Off unless
2229
+ * set: with it off the tool does not exist and the engine is never loaded. `true` = the
2230
+ * defaults, on the page's thread; an object sets the limits and - recommended - a `worker`
2231
+ * factory, so the guest runs in a Web Worker that is terminated at the deadline. The guest
2232
+ * runs in QuickJS compiled to WebAssembly (the optional peer `quickjs-emscripten`): no network,
2233
+ * no DOM, no page globals. When the agent has file tools (`createFileTools`) the guest can
2234
+ * import / require workspace files and use `fs` through the same file system and the same
2235
+ * consent rules (`files: false` switches that off). A run is a write for tool approval.
2236
+ */
2237
+ sandbox?: boolean | SandboxConfig;
2238
+ /**
2239
+ * Subagents the MODEL starts itself. `dynamic: true` (or an object of limits) mounts the
2240
+ * `spawn_subagent` tool: the model gives a sub-task, an optional role and optionally a subset of
2241
+ * its own tools by name; a helper agent runs the normal loop on it and its answer is the tool
2242
+ * result. Off unless set: with it off the tool does not exist and no prompt mentions it. A
2243
+ * helper can only have LESS than the run that starts it (its tools, a share of what is left of
2244
+ * its budgets, the same models, approval mode and rules); its spend counts against this run's
2245
+ * limits. Subagents the HOST defines are tools (`createSubagentTool`) and need no switch. See
2246
+ * `IDynamicSubagentsConfig` and docs/capabilities.md.
2247
+ */
2248
+ subagents?: ISubagentsConfig;
2249
+ /** Host tools the executor may call (an AI SDK ToolSet; use defineTool). */
2250
+ tools?: AgentToolSet;
2251
+ /** Whitelist: only these tool names from `tools` are mounted (default: all). */
2252
+ availableTools?: string[];
2253
+ /** Blacklist: these tool names are removed after the whitelist is applied. */
2254
+ excludedTools?: string[];
2255
+ /** Force native/prompted tool-calling; 'auto' picks per model (default 'auto'). */
2256
+ toolMode?: ToolMode;
2257
+ /** How the executor sees the tool catalogue (default 'auto'). */
2258
+ toolSelectionStrategy?: ToolSelectionStrategy;
2259
+ /** Catalogue size above which 'auto' switches to 'search' (default 40). */
2260
+ toolSearchThreshold?: number;
2261
+ /** Consent policy for tool calls: autopilot, ask before writes, ask always, read-only. */
2262
+ toolApproval?: ToolApprovalConfig;
2263
+ /** Reusable instruction bundles (SKILL.md) the planner/executor can pull in. */
2264
+ skills?: Skill[];
2265
+ /**
2266
+ * Let the agent write down lessons as skills (`save_skill` / `forget_skill`) for the rest of the
2267
+ * session: `true` keeps them in memory; `{ store: new VfsSkillStore(vfs) }` keeps them in the
2268
+ * file system across sessions. Off by default. Knowledge only - see `learning.ts`.
2269
+ */
2270
+ learning?: boolean | LearningConfig;
2271
+ /**
2272
+ * Show the model the `instructions` an MCP server returned in its `initialize` result (read from
2273
+ * the tools `connectMcpHttp` mounted): planner and executor system prompts, under a preamble
2274
+ * that marks them as third-party text, capped per server and in total. Default true. Set false
2275
+ * for servers you do not trust to write into a system prompt (see docs/security.md).
2276
+ */
2277
+ mcpInstructions?: boolean;
2278
+ /** Prepended to every phase's system prompt. */
2279
+ systemPrompt?: string;
2280
+ /** Override any phase prompt builder. */
2281
+ prompts?: Partial<Prompts>;
2282
+ /** Serialize the host's current world state into prompt context (grounding). */
2283
+ describeState?: () => string | Promise<string>;
2284
+ /**
2285
+ * Persist the transcript (e.g. new IndexedDBStore()). The last few messages
2286
+ * are also read back into the planner prompt, so follow-up goals can refer
2287
+ * to earlier turns.
2288
+ */
2289
+ memory?: ContextStore;
2290
+ sessionId?: string;
2291
+ /**
2292
+ * Checkpoint runs so a reload or a crashed tab does not lose finished work:
2293
+ * `new IndexedDBRunStore()` survives a reload, `new MemoryRunStore()` does not.
2294
+ * `run(goal, { resumeFromRunId })` then continues from the last checkpoint —
2295
+ * see `RunSnapshot` for exactly what is, and is not, kept.
2296
+ */
2297
+ persistence?: RunPersistence;
2298
+ /** Hard cap on executed steps incl. replans (default 8). */
2299
+ maxIterations?: number;
2300
+ /** Cap on tool-calling rounds inside one executor call, both modes (default 4). */
2301
+ maxStepsPerTask?: number;
2302
+ /** Cap on replanner "revise" decisions per run (default 2). */
2303
+ maxRevisions?: number;
2304
+ /** Cap on tool calls per run (default: unlimited). */
2305
+ maxToolCalls?: number;
2306
+ /** Cap on the steps of one plan (default 8). */
2307
+ maxPlanSteps?: number;
2308
+ /** Per-call timeout so a hang can't freeze a run (default 120000). */
2309
+ chatTimeoutMs?: number;
2310
+ /** Legacy per-phase output caps; `limits.perCall` wins when both are set. */
2311
+ budgets?: PhaseBudgets;
2312
+ /** Run-level token budgets (input / output / thinking / total) + per-call output caps. */
2313
+ limits?: TokenLimits;
2314
+ temperature?: number;
2315
+ /** Thinking for every stage: true, a level ('low'…'xhigh'), or { level, budgetTokens }. */
2316
+ thinking?: ThinkingSetting;
2317
+ /** Per-stage thinking; a stage entry wins over `thinking`. */
2318
+ stageThinking?: Partial<Record<ThinkingStage, ThinkingSetting>>;
2319
+ /**
2320
+ * Whether the model accepts images. Default: inferred (`supportsImages`) —
2321
+ * local/prompted models are text-only; unknown models are tried and a
2322
+ * refusal is reported as ImagesNotSupportedError.
2323
+ */
2324
+ vision?: boolean;
2325
+ /** Per-kind override of what the model takes as attachments (`images` wins over `vision`). */
2326
+ inputs?: {
2327
+ images?: boolean;
2328
+ pdf?: boolean;
2329
+ files?: boolean;
2330
+ };
2331
+ /** Provider prompt caching (default true): stable system prefixes + Anthropic breakpoints. */
2332
+ promptCaching?: PromptCachingSetting;
2333
+ /** Context compaction (auto + manual `agent.compact()`); see CompactionConfig. */
2334
+ compaction?: CompactionConfig;
2335
+ /** Master switch for the replan phase (default true). */
2336
+ replan?: boolean;
2337
+ /** What triggers the replanner when it is on (default 'failure'). */
2338
+ replanAfter?: ReplanTrigger;
2339
+ /** Write a final natural-language summary (default true). */
2340
+ synthesize?: boolean;
2341
+ /**
2342
+ * Legacy: compress stored history past this many chars after each run
2343
+ * (0 = off). Used only when `compaction` is not set.
2344
+ */
2345
+ compressAfterChars?: number;
2346
+ /** Verbosity: 'silent' | 'error' | 'warn' (default) | 'info' | 'debug'. */
2347
+ logLevel?: LogLevel;
2348
+ /** Console-like sink the logs go to (default: the global console). */
2349
+ logger?: AgentLoggerSink;
1286
2350
  }
1287
- /** An event of a running subagent, forwarded verbatim. */
1288
- | {
1289
- type: 'subagent.event';
1290
- id: string;
1291
- name: string;
1292
- event: AgentEvent;
1293
- } | {
1294
- type: 'subagent.complete';
1295
- id: string;
1296
- name: string;
1297
- text: string;
1298
- usage: IUsage;
2351
+ interface ResolvedConfig {
2352
+ clientName: string;
2353
+ sessionId: string;
2354
+ toolMode: ToolMode;
2355
+ toolSelectionStrategy: ToolSelectionStrategy;
2356
+ toolSearchThreshold: number;
2357
+ maxIterations: number;
2358
+ maxStepsPerTask: number;
2359
+ maxRevisions: number;
2360
+ maxToolCalls: number;
2361
+ maxPlanSteps: number;
2362
+ chatTimeoutMs: number;
2363
+ /**
2364
+ * Effective per-call output caps (limits.perCall over budgets, else a share of the window).
2365
+ * `0` = no cap for that stage: the host turned it off, or the stage thinks (see
2366
+ * `stageOutputCap`).
2367
+ */
2368
+ budgets: Required<PhaseBudgets> & {
2369
+ compaction: number;
2370
+ };
2371
+ limits: TokenLimits;
2372
+ temperature: number | undefined;
2373
+ replan: boolean;
2374
+ replanAfter: ReplanTrigger;
2375
+ synthesize: boolean;
2376
+ compressAfterChars: number;
2377
+ compaction: ResolvedCompaction;
2378
+ logLevel: LogLevel;
1299
2379
  }
1300
- /** `stopped` is set when the user stopped this subagent (`RunControl.stopSubagent`), as opposed to it failing. */
1301
- | {
1302
- type: 'subagent.error';
1303
- id: string;
1304
- name: string;
1305
- error: string;
1306
- stopped?: boolean;
2380
+ /** The output cap of one call of a stage, and where it came from. */
2381
+ interface OutputCap {
2382
+ /** The cap in force; undefined = none (the provider's own maximum applies). */
2383
+ tokens?: number;
2384
+ /** true when it came from the window, false when the host set it (or turned it off with 0). */
2385
+ derived: boolean;
1307
2386
  }
1308
2387
  /**
1309
- * A request of the `web_fetch` tool, allowed or refused by the egress policy. `url` is origin and
1310
- * path only (a query string can carry a secret).
2388
+ * The output cap of one call of `stage` — the same rules as the Node sibling's `stageOutputCap`.
2389
+ * What the host set (`limits.perCall`, then the legacy `budgets`) wins, and `0` is an explicit
2390
+ * "no cap". Otherwise a share of the context window — except for a stage that thinks: on OpenAI
2391
+ * and Gemini the reasoning counts against the cap, so a default sized for the answer alone would
2392
+ * leave a thinking model no room to write it (or to finish a tool call's arguments). A stage that
2393
+ * thinks keeps the provider's own limit unless the host sets one.
1311
2394
  */
1312
- | {
1313
- type: 'egress.request';
1314
- url: string;
1315
- allowed: boolean;
1316
- status?: number;
1317
- reason?: string;
1318
- }
1319
- /** A message sent with `RunControl.send` is waiting for the next boundary. */
1320
- | {
1321
- type: 'message.queued';
1322
- id: string;
1323
- text: string;
1324
- }
2395
+ declare const stageOutputCap: (c: BrowserAgentConfig, stage: ThinkingStage, contextWindowTokens: number) => OutputCap;
1325
2396
  /**
1326
- * The message reached the model. `round` = between tool-calling rounds inside a step, so
1327
- * the rest of that step can act on it (the replanner weighs it at the end of the step);
1328
- * `step` = at a step boundary, where it forces the replanner to look at the plan;
1329
- * `final` = just before the answer is written.
2397
+ * The notice for a call the output cap cut off (`finishReason: 'length'`), else undefined. A
2398
+ * truncated answer is silent otherwise — the model just stops, and a tool call whose arguments
2399
+ * were cut fails to parse — and a default cap makes that a thing a host can hit without ever
2400
+ * having set a limit.
1330
2401
  */
1331
- | {
1332
- type: 'message.delivered';
1333
- id: string;
1334
- text: string;
1335
- at: 'round' | 'step' | 'final';
1336
- } | {
1337
- type: 'stopped';
1338
- } | {
1339
- type: 'error';
1340
- phase: Phase | 'run';
1341
- error: string;
1342
- };
1343
- type AgentEventHandler = (event: AgentEvent) => void;
2402
+ declare const outputCapNotice: (c: BrowserAgentConfig, stage: ThinkingStage, contextWindowTokens: number, finishReason: string | undefined) => string | undefined;
2403
+ /**
2404
+ * The effective per-call output caps: what the host set (`limits.perCall`, then the legacy
2405
+ * `budgets`) wins; every other phase gets its share of the window, and a stage that thinks gets
2406
+ * none. `0` in the result means "no cap" (see `stageOutputCap`).
2407
+ */
2408
+ declare const resolveBudgets: (c: BrowserAgentConfig, contextWindowTokens: number) => ResolvedConfig["budgets"];
2409
+ declare const resolveConfig: (c: BrowserAgentConfig) => ResolvedConfig;
1344
2410
 
1345
2411
  /**
1346
2412
  * Tool search for large catalogues. Several MCP servers easily add up to
@@ -1412,6 +2478,13 @@ interface SubagentInfo {
1412
2478
  /** The profile the parent chose for this call, when it chose one. */
1413
2479
  profile?: string;
1414
2480
  startedAt: number;
2481
+ /** The subagent that started it; absent when the run itself did. */
2482
+ parentId?: string;
2483
+ /** 1 for the run's own subagents, 2 for theirs, ... (set for helpers the model started). */
2484
+ depth?: number;
2485
+ /** Set for a helper the model started with spawn_subagent: the role it was given, if any. */
2486
+ dynamic?: true;
2487
+ role?: string;
1415
2488
  }
1416
2489
  interface RunControl {
1417
2490
  /**
@@ -1457,59 +2530,119 @@ interface RunControlPort {
1457
2530
  }
1458
2531
  declare const createRunControl: () => RunControl;
1459
2532
 
2533
+ declare const MODEL_TIERS: readonly ModelTier[];
2534
+ /**
2535
+ * The tier a step runs on. The planner's complexity names the tier it wants (low -> light,
2536
+ * medium -> standard, high -> strong); a step the planner did not mark runs on `standard`.
2537
+ * A tier the host did not configure falls back to the NEAREST configured one, and of two equally
2538
+ * near the STRONGER: a step is never handed to a model weaker than it has to be. `standard` is
2539
+ * always configured (it is the agent's own model), so in practice a missing `light` or `strong`
2540
+ * means `standard` - the rule is general so that it stays true if that ever changes.
2541
+ */
2542
+ declare const pickTier: (complexity: StepComplexity | undefined, configured: ReadonlySet<ModelTier>) => {
2543
+ tier: ModelTier;
2544
+ reason: TierReason;
2545
+ };
2546
+ declare const nextStrongerTier: (tier: ModelTier, configured: ReadonlySet<ModelTier>) => ModelTier | undefined;
2547
+ interface IResolvedEscalation {
2548
+ enabled: boolean;
2549
+ maxPerStep: number;
2550
+ maxPerRun: number;
2551
+ }
1460
2552
  /**
1461
- * Attachments sent with a run: images, PDFs and other files the provider can
1462
- * read, given as bytes / base64 / a data URL — or as an http(s) URL, which
1463
- * providers that accept links (Gemini, Claude, OpenAI) fetch themselves and the
1464
- * AI SDK downloads for the rest (from the browser: subject to CORS).
2553
+ * Escalation is ON by default once tiers are configured, and cannot be on without them. A host
2554
+ * that routes easy steps to a light model has accepted that the planner's rating may be wrong;
2555
+ * without escalation a mis-rated step fails outright and the replanner (another paid call) has
2556
+ * to plan around a failure that a model the host already configured would not have had. The cost
2557
+ * is bounded: one retry per step and three per run unless the host says otherwise.
1465
2558
  */
1466
- interface RunFile {
1467
- /** Base64 (no prefix), a data URL ("data:image/png;base64,…"), raw bytes, or an http(s) URL. */
1468
- data: string | Uint8Array | URL;
1469
- /** e.g. "image/png", "application/pdf" — read from a data URL when omitted. */
1470
- mediaType?: string;
1471
- /** Shown in the transcript, in memory and in errors. */
1472
- name?: string;
2559
+ declare const resolveEscalation: (setting: boolean | EscalationConfig | undefined, tiersActive: boolean) => IResolvedEscalation;
2560
+ interface IAttemptOutcome {
2561
+ toolCalls: IStepResult['toolCalls'];
2562
+ blocked: boolean;
2563
+ empty: boolean;
2564
+ cut: boolean;
2565
+ stopped: boolean;
1473
2566
  }
1474
- /** An image attachment (same shape; kept as its own name for clarity). */
1475
- type RunImage = RunFile;
1476
- /** The kinds of attachment the agent reasons about separately. */
1477
- type AttachmentKind = 'image' | 'pdf' | 'file';
1478
- /** The media type of an attachment (declared, from a data URL, or from a URL's extension). */
1479
- declare const mediaTypeOf: (f: RunFile) => string | undefined;
1480
- declare const attachmentKind: (f: RunFile) => AttachmentKind;
1481
- /** Raised when attachments are sent to a model that cannot take them. */
1482
- declare class AttachmentsNotSupportedError extends Error {
1483
- readonly kind: AttachmentKind;
1484
- constructor(model: string, kind: AttachmentKind, detail?: string);
1485
- toJSON(): string;
2567
+ /**
2568
+ * Why an attempt that RETURNED should be retried on a stronger model, or undefined when it should
2569
+ * not. Never for an attempt a budget stopped, or one in which the user (or the approval policy)
2570
+ * denied a tool: those are not the model's failures.
2571
+ */
2572
+ declare const escalationReasonOf: (o: IAttemptOutcome) => EscalationReason | undefined;
2573
+ /**
2574
+ * Whether an attempt that THREW may be retried on a stronger model. Not a stop or a timeout (the
2575
+ * call was cut, not wrong), not refused credentials (401 / 403: the next call fails the same way
2576
+ * and the host must hear about it), not a rate limit (429: that is for retry and backoff, and a
2577
+ * bigger model on the same account is the last thing to send), not a denial or a spent budget.
2578
+ */
2579
+ declare const isEscalatableError: (err: unknown) => boolean;
2580
+ interface IEarlierAttempt {
2581
+ tier: ModelTier;
2582
+ reason: EscalationReason;
2583
+ summary: string;
2584
+ toolCalls: IStepResult['toolCalls'];
1486
2585
  }
1487
- /** The image flavour of {@link AttachmentsNotSupportedError}. */
1488
- declare class ImagesNotSupportedError extends AttachmentsNotSupportedError {
1489
- constructor(model: string, detail?: string);
2586
+ /**
2587
+ * The writes of the step in flight, kept while it may be escalated. A stronger model continuing
2588
+ * the step is TOLD what was already done; this is what makes it true even if it does not listen:
2589
+ * a call to a tool that is not read-only, with the same arguments as a call that already
2590
+ * succeeded in an EARLIER attempt at this step, is not executed again - it gets the earlier
2591
+ * result back. Within one attempt nothing changes (a model may repeat a call there as it always
2592
+ * could), and read-only tools are never held back.
2593
+ */
2594
+ interface IStepWrites {
2595
+ attempt: number;
2596
+ done: Map<string, {
2597
+ attempt: number;
2598
+ output: unknown;
2599
+ }>;
1490
2600
  }
2601
+ 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:]";
1491
2602
  /**
1492
- * An AI SDK file part (images included — the v7 SDK deprecates the separate
1493
- * image part). An http(s) URL is passed as a URL: providers that accept links
1494
- * fetch it themselves, and the SDK downloads it for the rest.
2603
+ * Whether a tool call's `output` (in a `step.tool-result` event or a step's `toolCalls`) is the
2604
+ * answer to a write that was NOT run again: the same call already succeeded in an earlier attempt
2605
+ * at the step, and the model was handed that result under `REPLAY_NOTE`. For a UI that marks such
2606
+ * a call instead of showing it as a second execution.
1495
2607
  */
1496
- declare const toFilePart: (f: RunFile) => FilePart;
1497
- /** Back-compat name. */
1498
- declare const toImagePart: (f: RunFile) => FilePart;
1499
- /** Does a provider error look like a refusal of attachment input? */
1500
- declare const isAttachmentRefusal: (err: unknown) => boolean;
1501
- /** Back-compat name. */
1502
- declare const isImageRefusal: (err: unknown) => boolean;
2608
+ declare const isReplayedToolOutput: (output: unknown) => boolean;
1503
2609
 
1504
2610
  /** The effective tool-selection strategy of a run ('auto' already resolved). */
1505
2611
  type EffectiveToolStrategy = 'all' | 'plan-narrowed' | 'search';
2612
+ /** One executor tier of an agent with `config.executorTiers`. */
2613
+ interface ExecutorTier {
2614
+ model: LanguageModel;
2615
+ /** The tier's own tool-mode: a local light model is prompted, a cloud strong one native. */
2616
+ mode: ToolCallMode;
2617
+ /** Model id, for the events. */
2618
+ id: string;
2619
+ /** The window the tier's output cap is a share of (never below the window the run is fitted to). */
2620
+ windowTokens: number;
2621
+ /** The tier's per-call output cap (0 = none), by the same rules as `budgets.executor`. */
2622
+ outputCap: number;
2623
+ }
2624
+ /** The executor models by tier. `standard` is always there (it is `executorModel`). */
2625
+ interface ExecutorTiers {
2626
+ byTier: Partial<Record<ModelTier, ExecutorTier>>;
2627
+ configured: ReadonlySet<ModelTier>;
2628
+ escalation: IResolvedEscalation;
2629
+ }
1506
2630
  /** Everything the phase functions (planner/executor/replanner/synthesizer) share. */
1507
2631
  interface AgentContext {
1508
2632
  config: ResolvedConfig;
1509
2633
  raw: BrowserAgentConfig;
1510
2634
  plannerModel: LanguageModel;
1511
2635
  executorModel: LanguageModel;
2636
+ /**
2637
+ * Set only when `config.executorTiers` names a light or a strong model: the planner then rates
2638
+ * steps and the executor runs each on its tier. Absent = one executor model, as ever.
2639
+ */
2640
+ tiers?: ExecutorTiers;
2641
+ /** The window the executor's output cap was judged against, when it is not the run's (a tier's). */
2642
+ executorWindowTokens?: number;
1512
2643
  synthesizerModel: LanguageModel;
2644
+ /** `config.decisionModel`, resolved. Absent = the feature is off. */
2645
+ decisionModel?: IDecisionModel;
1513
2646
  /** Tool-mode for the planner/replanner (from the planner model). */
1514
2647
  plannerMode: ToolCallMode;
1515
2648
  /** Tool-mode for the executor (from the executor model). */
@@ -1544,6 +2677,26 @@ interface AgentContext {
1544
2677
  nudge: boolean;
1545
2678
  tools: string[];
1546
2679
  };
2680
+ /**
2681
+ * Set when `config.sandbox` is on and `run_js` is mounted: the sentences the stage prompts
2682
+ * carry (what the tool is, and that code is never reported as run without it).
2683
+ */
2684
+ sandbox?: {
2685
+ planner: string;
2686
+ executor: string;
2687
+ synthesizer: string;
2688
+ };
2689
+ /**
2690
+ * Set while `spawn_subagent` is among the tools (`config.subagents.dynamic`): the planner's and
2691
+ * the executor's prompts say when a helper is worth it.
2692
+ */
2693
+ subagents?: true;
2694
+ /**
2695
+ * The rendered instructions of the MCP servers whose tools are mounted (`renderMcpInstructions`);
2696
+ * absent when none sent any or `config.mcpInstructions` is false. Built once, when the agent is
2697
+ * created, so it is the same text in every call of every run.
2698
+ */
2699
+ mcpInstructions?: string;
1547
2700
  /** Tools find_tools activated during this run (search mode). */
1548
2701
  discovered?: () => string[];
1549
2702
  /** Built-in tool names (find_tools, skill tools) — always callable. */
@@ -1685,11 +2838,15 @@ interface Agent {
1685
2838
  pdf: boolean | undefined;
1686
2839
  files: boolean | undefined;
1687
2840
  };
2841
+ /** `config.decisionModel`, resolved (a spec built into a model). Absent when the feature is off. */
2842
+ readonly decisionModel?: IDecisionModel;
1688
2843
  /** The resolved models, for hosts that want to reuse them (e.g. warm-up). */
1689
2844
  readonly models: {
1690
2845
  planner: LanguageModel;
1691
2846
  executor: LanguageModel;
1692
2847
  synthesizer: LanguageModel;
2848
+ /** The executor models by tier, when `config.executorTiers` is on (`standard` is `executor`). */
2849
+ tiers?: Partial<Record<ModelTier, LanguageModel>>;
1693
2850
  };
1694
2851
  }
1695
2852
  /**
@@ -1700,7 +2857,7 @@ interface Agent {
1700
2857
  declare const createAgent: (config: BrowserAgentConfig) => Promise<Agent>;
1701
2858
 
1702
2859
  /**
1703
- * Structured-output schemas for the native path (generateObject). Kept free of
2860
+ * Structured-output schemas for the native path (`generateStructured`). Kept free of
1704
2861
  * `.max()`/`.min()` constraints — some providers reject or mis-handle them in
1705
2862
  * JSON-schema mode; we cap/clean in code instead (see parse.ts normalizeSteps).
1706
2863
  */
@@ -1709,6 +2866,21 @@ declare const PlanStepSchema: z.ZodObject<{
1709
2866
  expectedOutcome: z.ZodOptional<z.ZodString>;
1710
2867
  suggestedTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
1711
2868
  }, z.core.$strip>;
2869
+ /**
2870
+ * The plan step of an agent with `config.executorTiers`: it also carries the planner's rating. A
2871
+ * SEPARATE schema, so an agent without tiers sends exactly the schema it always did. Optional (a
2872
+ * model that leaves it out still gives a valid plan; the step then runs on `standard`).
2873
+ */
2874
+ declare const TieredPlanStepSchema: z.ZodObject<{
2875
+ description: z.ZodString;
2876
+ expectedOutcome: z.ZodOptional<z.ZodString>;
2877
+ suggestedTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
2878
+ complexity: z.ZodOptional<z.ZodEnum<{
2879
+ low: "low";
2880
+ medium: "medium";
2881
+ high: "high";
2882
+ }>>;
2883
+ }, z.core.$strip>;
1712
2884
  declare const PlanSchema: z.ZodObject<{
1713
2885
  thought: z.ZodString;
1714
2886
  steps: z.ZodArray<z.ZodObject<{
@@ -1718,6 +2890,20 @@ declare const PlanSchema: z.ZodObject<{
1718
2890
  }, z.core.$strip>>;
1719
2891
  skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
1720
2892
  }, z.core.$strip>;
2893
+ declare const TieredPlanSchema: z.ZodObject<{
2894
+ thought: z.ZodString;
2895
+ skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
2896
+ steps: z.ZodArray<z.ZodObject<{
2897
+ description: z.ZodString;
2898
+ expectedOutcome: z.ZodOptional<z.ZodString>;
2899
+ suggestedTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
2900
+ complexity: z.ZodOptional<z.ZodEnum<{
2901
+ low: "low";
2902
+ medium: "medium";
2903
+ high: "high";
2904
+ }>>;
2905
+ }, z.core.$strip>>;
2906
+ }, z.core.$strip>;
1721
2907
  declare const ReplanSchema: z.ZodObject<{
1722
2908
  decision: z.ZodEnum<{
1723
2909
  continue: "continue";
@@ -1737,7 +2923,7 @@ interface PlanOutcome {
1737
2923
  skills: string[];
1738
2924
  }
1739
2925
  /**
1740
- * Build the initial plan. Native mode uses generateObject(PlanSchema); prompted
2926
+ * Build the initial plan. Native mode uses generateStructured(PlanSchema); prompted
1741
2927
  * mode salvages `{ reply, plan }` from plain text. Native failures (a weak model
1742
2928
  * that can't satisfy the schema) fall back to the prompted parse rather than
1743
2929
  * throwing, so the run degrades gracefully. An empty `steps` list signals the
@@ -1757,11 +2943,27 @@ declare const splitBlocker: (raw: string) => {
1757
2943
  summary: string;
1758
2944
  blocked: boolean;
1759
2945
  };
2946
+ /**
2947
+ * One attempt at a step on a given tier (`config.executorTiers` / escalation). Without it the
2948
+ * step runs on `ctx.executorModel`, exactly as before tiers existed.
2949
+ */
2950
+ interface StepAttempt {
2951
+ tier?: ModelTier;
2952
+ /** The attempts weaker tiers already made at this step: shown to the model so it continues. */
2953
+ earlier?: IEarlierAttempt[];
2954
+ /**
2955
+ * Every tool call the attempt makes is also pushed here as it completes, so a caller still has
2956
+ * them when the attempt THROWS (the calls happened either way).
2957
+ */
2958
+ calls?: IToolCall[];
2959
+ }
1760
2960
  /** Execute one plan step: run the tool loop (native or prompted) and emit events. */
1761
- declare const executeStep: (ctx: AgentContext, goal: string, step: IPlanStep, index: number, total: number, done: string[]) => Promise<{
2961
+ declare const executeStep: (base: AgentContext, goal: string, step: IPlanStep, index: number, total: number, done: string[], attempt?: StepAttempt) => Promise<{
1762
2962
  result: IStepResult;
1763
2963
  usage: IUsage;
1764
2964
  stoppedByBudget?: boolean;
2965
+ /** How the attempt ended, as far as escalation needs to know. */
2966
+ outcome: IAttemptOutcome;
1765
2967
  }>;
1766
2968
  /**
1767
2969
  * The replanner runs when a step was blocked or a tool call failed and stayed
@@ -1830,12 +3032,27 @@ interface ReplanOutcome {
1830
3032
  /** Replacement remaining steps (descriptions) when decision is 'revise'. */
1831
3033
  plan: string[];
1832
3034
  usage: IUsage;
3035
+ /**
3036
+ * Set when the replanner call itself failed (the structured attempt AND the prompted
3037
+ * fallback): `decision: 'continue'` is then the fallback, not the model's decision.
3038
+ */
3039
+ failed?: true;
3040
+ /** The failure, when `failed`. */
3041
+ error?: string;
3042
+ /**
3043
+ * Set when `config.decisionModel` made the decision (the replanner was not called): the
3044
+ * probability it gave its choice.
3045
+ */
3046
+ confidence?: number;
1833
3047
  }
1834
3048
  /**
1835
3049
  * Decide whether to continue, revise the remaining plan, or finish, after a
1836
- * blocked/failed step. Native mode uses generateObject(ReplanSchema); prompted
3050
+ * blocked/failed step. Native mode uses generateStructured(ReplanSchema); prompted
1837
3051
  * mode salvages the decision from text. Any failure degrades to 'continue' so a
1838
- * flaky replanner never aborts the run.
3052
+ * flaky replanner never aborts the run or throws away the steps already done — but not
3053
+ * silently: the outcome is marked `failed` (the runner reports it as an `error` event of
3054
+ * phase 'replan' and `replan.decision { failed: true }`), and what the failed attempts cost
3055
+ * is in `usage`. An abort is a stop, not a failure: it is thrown.
1839
3056
  */
1840
3057
  declare const decideReplan: (ctx: AgentContext, goal: string, done: string[], remaining: string[],
1841
3058
  /** How many of the user's latest messages (`ctx.userUpdates()`) the plan has not been weighed against yet. */
@@ -1855,6 +3072,68 @@ findings?: string[]) => Promise<{
1855
3072
  usage: IUsage;
1856
3073
  }>;
1857
3074
 
3075
+ /**
3076
+ * A pipeline: a graph of agents with conditions and loops, described in plain JSON. The graph
3077
+ * engine (validation, conditions, scheduling) is `engine.ts`, the same file as the Node
3078
+ * sibling's; this file is the adapter that runs a node with this package's createAgent.
3079
+ */
3080
+ interface PipelineOptions {
3081
+ /** The seam: run a node yourself. When given, the pipeline knows nothing about agents. */
3082
+ runNode?: PipelineNodeRunner<AgentEvent>;
3083
+ /**
3084
+ * Otherwise: the agent config of a node. One agent is created per node, on its first visit,
3085
+ * and kept until `pipeline.close()`.
3086
+ */
3087
+ resolveNode?: (node: PipelineNode) => BrowserAgentConfig | Promise<BrowserAgentConfig>;
3088
+ }
3089
+ interface PipelineRunOptions {
3090
+ input: string;
3091
+ signal?: AbortSignal;
3092
+ /** The pipeline.* events, and every node agent's own events with `nodeId` and `visit` added. */
3093
+ onEvent?: AgentEventHandler;
3094
+ }
3095
+ interface Pipeline {
3096
+ /** A copy of the validated definition. */
3097
+ definition: PipelineDefinition;
3098
+ /**
3099
+ * Rejects with PipelineNodeError when a node fails. An aborted `signal` resolves with what the
3100
+ * run has and `stoppedBy: 'aborted'` (as agent.run resolves with `stopped`).
3101
+ */
3102
+ run: (options: PipelineRunOptions) => Promise<PipelineResult>;
3103
+ /** Drop the node agents. The pipeline can run again: agents are created anew. */
3104
+ close: () => Promise<void>;
3105
+ }
3106
+ declare const createPipeline: (definition: PipelineDefinition, options: PipelineOptions) => Pipeline;
3107
+ interface NodeResolverOptions {
3108
+ /**
3109
+ * The config every node starts from. With `memory`, each node gets a session of its own,
3110
+ * `<base sessionId>:<node id>`, unless `configure` sets another.
3111
+ */
3112
+ base: BrowserAgentConfig;
3113
+ /**
3114
+ * What the names in a node may refer to. A name that is not registered fails the node: a
3115
+ * definition cannot reach anything the host did not put here.
3116
+ */
3117
+ models?: Record<string, ModelInput>;
3118
+ skills?: Record<string, Skill>;
3119
+ /** Named groups of tools. */
3120
+ tools?: Record<string, AgentToolSet>;
3121
+ /** Connected MCP servers (`connectMcpHttp` from `./mcp`), or any object with their `tools`. */
3122
+ mcpServers?: Record<string, {
3123
+ tools: AgentToolSet;
3124
+ }>;
3125
+ /**
3126
+ * The last word on a node's config - the place to read `node.settings`, which is never
3127
+ * applied by itself (it comes from the definition, and a definition is not trusted).
3128
+ */
3129
+ configure?: (config: BrowserAgentConfig, node: PipelineNode) => BrowserAgentConfig | Promise<BrowserAgentConfig>;
3130
+ }
3131
+ /**
3132
+ * Build a `resolveNode` from registries: a node's `model`, `skills`, `tools` and `mcpServers`
3133
+ * names are looked up and added to `base`.
3134
+ */
3135
+ declare const nodeResolver: (options: NodeResolverOptions) => NonNullable<PipelineOptions["resolveNode"]>;
3136
+
1858
3137
  /**
1859
3138
  * The wire protocol between a parent agent and a subagent running in a Web
1860
3139
  * Worker. Every message is structured-cloneable; anything that is not (an
@@ -2038,6 +3317,13 @@ interface FileToolsOptions {
2038
3317
  /** Cap on the text fs_read returns (default 50 000 chars; the rest is cut with a marker). */
2039
3318
  maxReadChars?: number;
2040
3319
  }
3320
+ /** What one of these tools does, and on which file system (read by `config.sandbox`). */
3321
+ interface FileToolBinding {
3322
+ vfs: VirtualFileSystem;
3323
+ op: 'list' | 'read' | 'write' | 'delete';
3324
+ }
3325
+ /** The file-system binding of a tool made by `createFileTools` (undefined for any other tool). */
3326
+ declare const fileToolBindingOf: (t: unknown) => FileToolBinding | undefined;
2041
3327
  /**
2042
3328
  * Tools that give the agent the virtual file system: list, read, write and
2043
3329
  * delete. Listing and reading are marked read-only, so the `ask-writes`
@@ -2061,6 +3347,15 @@ declare const resolveStage: (base: ModelInput, override: StageInput | undefined,
2061
3347
  * optional-peer package and fetching the API key from the CredentialStore.
2062
3348
  */
2063
3349
  declare const buildModelFromStage: (resolved: ResolvedStage, credentials?: CredentialStore, clientName?: string) => Promise<LanguageModel>;
3350
+ /** The media models of a provider (`config.media`), by the names every AI SDK provider carries. */
3351
+ type MediaModelKind = 'image' | 'speech' | 'transcription';
3352
+ /**
3353
+ * The same provider factory as `buildModelFromStage` (same package, key from the
3354
+ * CredentialStore, baseURL, headers, options), asked for an image / speech / transcription
3355
+ * model instead of a language model. A provider that has none of that kind says so here, when
3356
+ * the agent is created, not at the first call.
3357
+ */
3358
+ declare const buildMediaModelFromSpec: (spec: ProviderModelSpec, kind: MediaModelKind, credentials?: CredentialStore, clientName?: string) => Promise<unknown>;
2064
3359
  /** Resolve a single ModelInput straight to a LanguageModel (no per-stage layering). */
2065
3360
  declare const resolveModel: (input: ModelInput, credentials?: CredentialStore, clientName?: string) => Promise<LanguageModel>;
2066
3361
 
@@ -2203,7 +3498,7 @@ declare const contextOverflowOf: (err: unknown, model: unknown) => ContextWindow
2203
3498
 
2204
3499
  /** Whether native tool-calling is reliable enough to be the default for a provider. */
2205
3500
  declare const supportsNativeTools: (p: ProviderType) => boolean;
2206
- /** Whether native structured output (generateObject) is the default for a provider. */
3501
+ /** Whether native structured output (`generateStructured`) is the default for a provider. */
2207
3502
  declare const supportsStructuredOutput: (p: ProviderType) => boolean;
2208
3503
  /**
2209
3504
  * Whether calling this provider straight from a browser origin with a BYOK key
@@ -2301,13 +3596,32 @@ interface GenerateOptions {
2301
3596
  declare const generate: (model: LanguageModel, opts?: GenerateOptions) => ReturnType<typeof generateText>;
2302
3597
  /** Streaming text generation. Returns the AI SDK `streamText` result (`.textStream`, `.fullStream`). */
2303
3598
  declare const stream: (model: LanguageModel, opts?: GenerateOptions) => ReturnType<typeof streamText>;
2304
- /**
2305
- * Structured output constrained to a Zod schema, via the AI SDK's
2306
- * `generateObject`. Cloud models and WebLLM both support this; tiny local
2307
- * models can be unreliable — the agent's prompted mode is the fallback.
2308
- * Returns the AI SDK result (`.object`, `.usage`).
3599
+ type TextResult = Awaited<ReturnType<typeof generateText>>;
3600
+ /** What `generateStructured` returns: the validated object and the call's metadata. */
3601
+ interface StructuredResult<OBJECT> {
3602
+ object: OBJECT;
3603
+ /** The raw text the object was parsed from. */
3604
+ text: string;
3605
+ usage: TextResult['usage'];
3606
+ finishReason: TextResult['finishReason'];
3607
+ warnings: TextResult['warnings'];
3608
+ request: TextResult['request'];
3609
+ response: TextResult['response'];
3610
+ providerMetadata: TextResult['providerMetadata'];
3611
+ }
3612
+ /**
3613
+ * Structured output constrained to a Zod schema: the AI SDK's `generateText` with
3614
+ * `Output.object` (v7's replacement for the deprecated `generateObject` — the same request, a
3615
+ * JSON response format carrying the schema). Cloud models and WebLLM both support this; tiny
3616
+ * local models can be unreliable — the agent's prompted mode is the fallback.
3617
+ *
3618
+ * Returns `.object` and `.usage` (plus `.text`, `.finishReason`, `.warnings`, `.request`,
3619
+ * `.response`, `.providerMetadata`). An answer that is not the object — unparsable, off the
3620
+ * schema, or no text at all — throws `NoObjectGeneratedError` carrying the `usage` and the
3621
+ * `finishReason` of the attempt, so the spend of a failed attempt can still be counted
3622
+ * (`usageOfError`).
2309
3623
  */
2310
- declare const generateStructured: <OBJECT>(model: LanguageModel, schema: ZodType<OBJECT>, opts?: GenerateOptions) => Promise<ai.GenerateObjectResult<(OBJECT extends string ? "enum" : "object") extends infer T ? T extends (OBJECT extends string ? "enum" : "object") ? T extends "array" ? OBJECT[] : OBJECT : never : never>>;
3624
+ declare const generateStructured: <OBJECT>(model: LanguageModel, schema: ZodType<OBJECT>, opts?: GenerateOptions) => Promise<StructuredResult<OBJECT>>;
2311
3625
 
2312
3626
  /**
2313
3627
  * Context editing inside one tool loop — what Anthropic's
@@ -2400,6 +3714,8 @@ interface ToolLoopResult {
2400
3714
  usage: IUsage;
2401
3715
  /** True when `shouldStop` cut the call short. */
2402
3716
  stoppedByBudget?: boolean;
3717
+ /** How the LAST model call ended ('stop', 'length' when `maxOutputTokens` cut it off, …). */
3718
+ finishReason?: string;
2403
3719
  }
2404
3720
  /**
2405
3721
  * Run tool-calling in whichever mode the model needs, returning a normalised
@@ -2461,6 +3777,50 @@ declare const defineTool: <INPUT = unknown, OUTPUT = unknown>(config: Tool<INPUT
2461
3777
  readOnly?: boolean;
2462
3778
  }) => AgentTool;
2463
3779
 
3780
+ declare const GENERATE_IMAGE_TOOL = "generate_image";
3781
+ declare const GENERATE_SPEECH_TOOL = "generate_speech";
3782
+ declare const TRANSCRIBE_AUDIO_TOOL = "transcribe_audio";
3783
+ type MediaKind = 'image' | 'speech' | 'transcription';
3784
+ declare const MEDIA_DEFAULT_MAX_CALLS = 8;
3785
+ declare const MEDIA_TIMEOUT_MS = 120000;
3786
+ declare const MEDIA_MAX_IMAGE_BYTES: number;
3787
+ declare const MEDIA_MAX_SPEECH_BYTES: number;
3788
+ declare const MEDIA_MAX_AUDIO_INPUT_BYTES: number;
3789
+ declare const MEDIA_MAX_PROMPT_CHARS = 4000;
3790
+ declare const MEDIA_MAX_SPEECH_CHARS = 4000;
3791
+ declare const MEDIA_MAX_TRANSCRIPT_CHARS = 20000;
3792
+ declare const MEDIA_MAX_ATTACHED_AUDIO = 4;
3793
+ declare const MEDIA_FOLDER = "media";
3794
+ declare class MediaError extends Error {
3795
+ constructor(message: string);
3796
+ toJSON(): string;
3797
+ }
3798
+ declare class MediaBudgetError extends MediaError {
3799
+ constructor(cap: number);
3800
+ }
3801
+ declare const MEDIA_IMAGE_TYPES: Readonly<Record<string, string>>;
3802
+ declare const MEDIA_AUDIO_TYPES: Readonly<Record<string, string>>;
3803
+ declare const sniffMediaType: (bytes: Uint8Array) => string | undefined;
3804
+ interface IAcceptedMedia {
3805
+ mediaType: string;
3806
+ ext: string;
3807
+ }
3808
+ declare const acceptMedia: (family: "image" | "audio", bytes: Uint8Array, maxBytes: number, what: string) => IAcceptedMedia;
3809
+ interface IMediaUsage {
3810
+ mediaCalls: number;
3811
+ imagesGenerated: number;
3812
+ speechCharacters: number;
3813
+ transcriptionSeconds: number;
3814
+ }
3815
+ declare const mediaUsageOf: (usage: Partial<IMediaUsage> | undefined) => IMediaUsage | undefined;
3816
+ interface ITranscriptBlock {
3817
+ name: string;
3818
+ text: string;
3819
+ language?: string;
3820
+ durationInSeconds?: number;
3821
+ }
3822
+ declare const wrapTranscript: (block: ITranscriptBlock) => string;
3823
+
2464
3824
  /**
2465
3825
  * Render a ToolSet into a plain-text catalogue for the prompted/salvage path:
2466
3826
  * `- name(hint): description`. The hint comes from `defineTool({ promptHint })`
@@ -2490,6 +3850,29 @@ declare const dispatch: (action: RawAction, tools: ToolSet, ctx?: DispatchContex
2490
3850
  */
2491
3851
  declare const selectToolMode: (model: LanguageModel, mode?: ToolMode) => "native" | "prompted";
2492
3852
 
3853
+ /** Where a run stands among the helpers the model starts. Reaches the tool as `agentRun.spawn`. */
3854
+ interface SpawnRun {
3855
+ /** The helper's id; absent for the run the host started. */
3856
+ id?: string;
3857
+ /** 0 for the host's run, 1 for its helpers, ... */
3858
+ depth: number;
3859
+ root: {
3860
+ spawned: number;
3861
+ };
3862
+ /** This run's helpers that are running: what each may still spend of this run's budgets. */
3863
+ running: ISpawnReservation[];
3864
+ /** At most `maxConcurrent` helpers of this run at once. */
3865
+ acquire: (signal?: AbortSignal) => Promise<() => void>;
3866
+ /** The run's usage so far. */
3867
+ usage: () => IUsage;
3868
+ /** Its counted tool calls so far. */
3869
+ toolCalls: () => number;
3870
+ /** Count one tool call on this run and every run above it; throws ToolBudgetError. */
3871
+ countCall: () => void;
3872
+ /** The writes of the step in flight, while it may be escalated (see `tiers.ts`). */
3873
+ stepWrites: () => IStepWrites | undefined;
3874
+ }
3875
+
2493
3876
  /**
2494
3877
  * What a tool's `execute` can reach of the run that called it, passed as
2495
3878
  * `options.agentRun`. Subagent tools use it to stream nested events and to
@@ -2500,8 +3883,13 @@ interface ToolRunContext {
2500
3883
  /** The plan step being executed, when there is one. */
2501
3884
  step?: IPlanStep;
2502
3885
  signal?: AbortSignal;
2503
- /** Add tokens spent on the parent's behalf (e.g. by a subagent) to the run. */
2504
- addUsage: (usage: IUsage) => void;
3886
+ /**
3887
+ * Add what was spent on the parent's behalf to the run: a subagent's tokens (the default
3888
+ * phase, 'subagent'), or a media model's call (phase 'media').
3889
+ */
3890
+ addUsage: (usage: IUsage, phase?: UsagePhase) => void;
3891
+ /** The run's usage so far (media tools read their per-run call count from it). */
3892
+ usage?: () => IUsage;
2505
3893
  /**
2506
3894
  * Run the agent's consent gate for a call made on its behalf (e.g. a host
2507
3895
  * tool a subagent calls). Resolves when allowed, throws ToolDeniedError.
@@ -2513,6 +3901,8 @@ interface ToolRunContext {
2513
3901
  runId?: string;
2514
3902
  /** Pages web_fetch read in this run (origin + path), kept as provenance for any lesson the run writes. */
2515
3903
  fetched?: string[];
3904
+ /** Internal - what the built-in `spawn_subagent` tool reads of the run (`subagents.dynamic`). */
3905
+ spawn?: SpawnRun;
2516
3906
  }
2517
3907
  /** Read the run context the agent passes to a tool's execute (undefined outside a run). */
2518
3908
  declare const toolRunContextOf: (options: unknown) => ToolRunContext | undefined;
@@ -2609,5 +3999,5 @@ declare class IndexedDBRunStore implements RunPersistence {
2609
3999
  clear(): Promise<void>;
2610
4000
  }
2611
4001
 
2612
- export { AgentTool, AgentToolSet, AttachmentsNotSupportedError, ContextWindowExceededError, DEFAULT_COMPACTION_THRESHOLD_RATIO, EgressError, FILES_STORE, FIND_TOOLS_NAME, FORGET_SKILL_TOOL, ImagesNotSupportedError, IndexedDBRunStore, IndexedDBStore, KEYS_STORE, MemoryCredentialStore, MemoryRunStore, MemorySkillStore, MemoryStore, PlanSchema, PlanStepSchema, RUNS_STORE, ReplanSchema, SAVE_SKILL_TOOL, SECRETS_STORE, SESSIONS_STORE, SKILL_TOOL_NAMES, TOOL_APPROVAL_MODES, TOOL_SEARCH_WINDOW_SHARE, ToolBudgetError, ToolDeniedError, VaultCredentialStore, VaultOptions, VfsSkillStore, VirtualFileSystem, WEBLLM_DEFAULT_CONTEXT_WINDOW, WEB_FETCH_TOOL, attachmentKind, buildModelFromStage, bytesToBase64, checkEgressUrl, checkLimits, classifyAddress, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createEgressTools, createFileTools, createFindToolsTool, createGuardedFetch, createLearning, createLogger, createPlan, createRunControl, createSkillTools, createSubagentTool, createToolResultClearer, createWebFetchTool, createWebLLMModel, decideReplan, decideToolPermission, decryptJSON, defaultPrompts, defineSkill, defineTool, directBrowserOk, dispatch, encryptJSON, messageTokens as estimateMessagesTokens, estimateTokens, executeStep, findSecret, fitCompactionToWindow, generate, generateStructured, getOrCreateVaultKey, hostMatches, htmlToText, isAttachmentRefusal, isDirectModel, isImageRefusal, isProviderSpec, isReadOnlyTool, isTextMime, isWebGPUAvailable, learnedPreamble, limitModelOutput, loadSkillFromUrl, looksLikeJson, markReadOnly, matchRule, mediaTypeOf, mergeProviderOptions, mimeFromPath, normalizePath, normalizeSkillName, normalizeSteps, normalizeUsage, openAgentWebDB, parseExecutorResponse, parsePlainText, parsePlannerResponse, parseReplannerResponse, parseSkillMarkdown, preloadWebLLMModel, renderActiveSkills, renderCatalog, renderSearchCatalog, renderSkillIndex, replanWanted, resolveBudgets, resolveCaching, resolveCompaction, resolveConfig, resolveEgressPolicy, resolveModel, resolveResume, resolveStage, resolveThinking, runToolLoop, schemaHintOf, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, splitBlocker, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow };
2613
- export type { Agent, AgentContext, AgentEvent, AgentEventHandler, AgentLogger, AgentLoggerSink, AgentWebDBOptions, AttachmentKind, BrowserAgentConfig, ClearedInfo, CompactOptions, CompactResult, CompactionConfig, CompressOptions, ContextStore, CredentialStore, EffectiveToolStrategy, EgressErrorCode, EncryptedBlob, ExecutorPromptContext, ExecutorResult, FileToolsOptions, GenerateOptions, GuardedFetch, IEgressPolicy, IPlan, IPlanStep, IResolvedEgressPolicy, IStepResult, IToolCall, IUsage, IWebFetchOptions, IndexedDBRunStoreOptions, IndexedDBStoreOptions, Learning, LearningConfig, LimitBreach, LimitKind, LoadSkillOptions, LogLevel, MessageEndpoint, ModelInput, ParentToWorker, Phase, PhaseBudgets, PlanShape, PlannerPromptContext, PlannerResult, PromptCachingSetting, PromptParts, Prompts, ProviderModelSpec, ProviderOptionsMap, ProviderType, ProxiedToolSpec, RawAction, ReplanDecision, ReplanMode, ReplanShape, ReplanTrigger, ReplannerPromptContext, ReplannerResult, ResolvedCaching, ResolvedCompaction, ResolvedConfig, ResolvedStage, ResolvedThinking, RunControl, RunFile, RunImage, RunOptions, RunPersistence, RunResult, RunSnapshot, RunStatus, RunStoreOptions, SaveSkillInput, SearchToolsOptions, ServeSubagentOptions, Skill, SkillOrigin, SkillStore, StageInput, StageOverride, StoredMessage, SubagentInfo, SubagentProfile, SubagentToolOptions, SubagentWorkerConfig, SynthesizerPromptContext, ThinkingConfig, ThinkingLevel, ThinkingSetting, ThinkingStage, TokenLimits, ToolApprovalConfig, ToolApprovalDecision, ToolApprovalMode, ToolApprovalRequest, ToolCallMode, ToolCatalogEntry, ToolLoopCallbacks, ToolLoopOptions, ToolLoopResult, ToolMode, ToolPermission, ToolResultClearing, ToolRunContext, ToolSelectionStrategy, UsagePhase, VfsListener, VirtualFile, VirtualFileInfo, VirtualFileSystemOptions, WebLLMAppConfigLike, WebLLMModelOptions, WorkerLike, WorkerToParent };
4002
+ export { AgentTool, AgentToolSet, AttachmentsNotSupportedError, ContextWindowExceededError, DECISION_PROVIDERS, DEFAULT_COMPACTION_THRESHOLD_RATIO, DEFAULT_DECISION_CONFIDENCE_THRESHOLD, DEFAULT_DECISION_TIMEOUT_MS, EgressError, FILES_STORE, FIND_TOOLS_NAME, FORGET_SKILL_TOOL, GENERATE_IMAGE_TOOL, GENERATE_SPEECH_TOOL, ImagesNotSupportedError, IndexedDBRunStore, IndexedDBStore, KEYS_STORE, 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, MODEL_TIERS, MediaBudgetError, MediaError, MemoryCredentialStore, MemoryRunStore, MemorySkillStore, MemoryStore, PIPELINE_LIMITS, PipelineNodeError, PipelineValidationError, PlanSchema, PlanStepSchema, REPLAY_NOTE, RUNS_STORE, ReplanSchema, 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, SECRETS_STORE, SESSIONS_STORE, SKILL_TOOL_NAMES, SPAWN_INPUT_SCHEMA, SPAWN_SUBAGENT_TOOL, SUBAGENT_DEFAULTS, SUBAGENT_MAX_DEPTH_LIMIT, SubagentSpawnError, TOOL_APPROVAL_MODES, TOOL_SEARCH_WINDOW_SHARE, TRANSCRIBE_AUDIO_TOOL, TieredPlanSchema, TieredPlanStepSchema, ToolBudgetError, ToolDeniedError, VaultCredentialStore, VaultOptions, VfsSkillStore, VirtualFileSystem, WEBLLM_DEFAULT_CONTEXT_WINDOW, WEB_FETCH_TOOL, WEB_SEARCH_TOOL, acceptMedia, adoptSubagentEvent, askDecisionModel, attachmentKind, buildMediaModelFromSpec, buildModelFromStage, buildSearchRequest, bytesToBase64, checkEgressUrl, checkLimits, classifyAddress, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createEgressTools, createFileTools, createFindToolsTool, createGuardedFetch, createLearning, createLogger, createMedia, createPipeline, createPlan, createRunControl, createSearchTools, createSkillTools, createSubagentTool, createToolResultClearer, createWebFetchTool, createWebLLMModel, createWebSearchTool, decideReplan, decideToolPermission, decisionEgressPolicy, decisionModelFromAiSdk, decryptJSON, defaultPrompts, defineSkill, defineTool, directBrowserOk, dispatch, encryptJSON, escalationReasonOf, messageTokens as estimateMessagesTokens, estimateTokens, executeStep, fileToolBindingOf, findSecret, fitCompactionToWindow, generate, generateStructured, getOrCreateVaultKey, hostMatches, htmlToText, isAttachmentRefusal, isDirectModel, isEscalatableError, isImageRefusal, isProviderSpec, isReadOnlyTool, isReplayedToolOutput, isTextMime, isWebGPUAvailable, learnedPreamble, limitModelOutput, loadSkillFromUrl, looksLikeJson, markReadOnly, matchRule, mediaTypeOf, mediaUsageOf, mergeProviderOptions, mimeFromPath, nextStrongerTier, nodeResolver, normalizePath, normalizePipeline, normalizeSkillName, normalizeSteps, normalizeUsage, openAgentWebDB, outputCapNotice, parseExecutorResponse, parsePlainText, parsePlannerResponse, parseReplannerResponse, parseSearchResponse, parseSkillMarkdown, pickTier, preloadWebLLMModel, renderActiveSkills, renderCatalog, renderPipelineNodeInput, renderSearchCatalog, renderSkillIndex, replanWanted, resolveBudgets, resolveCaching, resolveCompaction, resolveConfig, resolveDecisionModel, resolveDynamicSubagents, resolveEgressPolicy, resolveEscalation, resolveModel, resolveResume, resolveStage, resolveThinking, runToolLoop, sanitizeSearchResults, schemaHintOf, searchEgressPolicy, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, sniffMediaType, splitBlocker, stageOutputCap, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, testPipelineCondition, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, validatePipeline, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow, wrapTranscript };
4003
+ export type { Agent, AgentContext, AgentEvent, AgentEventHandler, AgentLogger, AgentLoggerSink, AgentWebDBOptions, AttachmentKind, BrowserAgentConfig, ClearedInfo, CompactOptions, CompactResult, CompactionConfig, CompressOptions, ContextStore, CredentialStore, DecisionFallbackReason, DecisionPoint, EffectiveToolStrategy, EgressErrorCode, EncryptedBlob, EscalationConfig, EscalationReason, ExecutorPromptContext, ExecutorResult, FileToolBinding, FileToolsOptions, GenerateOptions, GuardedFetch, IAiSdkDecisionOptions, IDecisionAnswer, IDecisionCallOptions, IDecisionConfig, IDecisionEvent, IDecisionModel, IDecisionModelSpec, IDecisionOption, IDecisionOutcome, IDecisionQuestion, IDynamicSubagentsConfig, IEgressPolicy, IMedia, IMediaConfig, IMediaFile, IMediaModelSpec, IMediaOptions, IMediaRun, IMediaUsage, IPlan, IPlanStep, IResolvedDynamicSubagents, IResolvedEgressPolicy, ISandboxConfig, ISandboxError, ISandboxLimits, ISandboxResult, ISanitizedSearch, ISearchConfig, ISearchOptions, ISearchRequest, ISearchResult, IStepEscalation, IStepResult, ISubagentsConfig, IToolCall, ITranscription, IUsage, IWebFetchOptions, IWebSearchOptions, IndexedDBRunStoreOptions, IndexedDBStoreOptions, Learning, LearningConfig, LimitBreach, LimitKind, LoadSkillOptions, LogLevel, MediaImageModel, MediaKind, MediaModelKind, MediaSpeechModel, MediaTranscriptionModel, MessageEndpoint, ModelInput, ModelTier, NodeResolverOptions, OutputCap, ParentToWorker, Phase, PhaseBudgets, Pipeline, PipelineCondition, PipelineDefinition, PipelineEdge, PipelineEvent, PipelineIssue, PipelineNode, PipelineNodeContext, PipelineNodeInput, PipelineNodeOutput, PipelineNodeRunner, PipelineNodeSource, PipelineOptions, PipelineResult, PipelineRoute, PipelineRunOptions, PipelineStop, PipelineTraceEntry, PipelineUsage, PipelineValidation, PlanShape, PlannerPromptContext, PlannerResult, PromptCachingSetting, PromptParts, Prompts, ProviderModelSpec, ProviderOptionsMap, ProviderType, ProxiedToolSpec, RawAction, ReplanDecision, ReplanMode, ReplanShape, ReplanTrigger, ReplannerPromptContext, ReplannerResult, ResolvedCaching, ResolvedCompaction, ResolvedConfig, ResolvedStage, ResolvedThinking, RunControl, RunFile, RunImage, RunOptions, RunPersistence, RunResult, RunSnapshot, RunStatus, RunStoreOptions, SandboxConfig, SandboxWorkerLike, SaveSkillInput, SearchEngine, SearchFreshness, SearchProvider, SearchToolsOptions, ServeSubagentOptions, Skill, SkillOrigin, SkillStore, StageInput, StageOverride, StepComplexity, StoredMessage, StructuredResult, SubagentDefaultTools, SubagentInfo, SubagentProfile, SubagentToolOptions, SubagentWorkerConfig, SynthesizerPromptContext, ThinkingConfig, ThinkingLevel, ThinkingSetting, ThinkingStage, TierReason, TokenLimits, ToolApprovalConfig, ToolApprovalDecision, ToolApprovalMode, ToolApprovalRequest, ToolCallMode, ToolCatalogEntry, ToolLoopCallbacks, ToolLoopOptions, ToolLoopResult, ToolMode, ToolPermission, ToolResultClearing, ToolRunContext, ToolSelectionStrategy, UsagePhase, VfsListener, VirtualFile, VirtualFileInfo, VirtualFileSystemOptions, WebLLMAppConfigLike, WebLLMModelOptions, WorkerLike, WorkerToParent };