@dudko.dev/agent-web 0.0.42 → 0.0.44

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 (40) hide show
  1. package/README.md +150 -4
  2. package/dist/agent-web.js +155 -155
  3. package/dist/agent-web.js.map +1 -1
  4. package/dist/{chunk-DAREMCXF.js → chunk-236RCVAZ.js} +40 -8
  5. package/dist/chunk-236RCVAZ.js.map +1 -0
  6. package/dist/{chunk-2MLHZ6LQ.js → chunk-Y4MIIBPB.js} +2 -2
  7. package/dist/{chunk-ZSZSSJS4.js → chunk-Y6CD3WOK.js} +176 -10
  8. package/dist/chunk-Y6CD3WOK.js.map +1 -0
  9. package/dist/{chunk-YPCHD6DV.js → chunk-YGWIOO27.js} +31 -12
  10. package/dist/chunk-YGWIOO27.js.map +1 -0
  11. package/dist/index.cjs +1248 -108
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +1777 -1643
  14. package/dist/index.d.ts +1777 -1643
  15. package/dist/index.js +996 -89
  16. package/dist/index.js.map +1 -1
  17. package/dist/mcp.cjs +136 -5
  18. package/dist/mcp.cjs.map +1 -1
  19. package/dist/mcp.d.cts +5 -2
  20. package/dist/mcp.d.ts +5 -2
  21. package/dist/mcp.js +19 -8
  22. package/dist/mcp.js.map +1 -1
  23. package/dist/pipeline-engine.cjs +1130 -0
  24. package/dist/pipeline-engine.cjs.map +1 -0
  25. package/dist/pipeline-engine.d.cts +226 -0
  26. package/dist/pipeline-engine.d.ts +226 -0
  27. package/dist/pipeline-engine.js +1094 -0
  28. package/dist/pipeline-engine.js.map +1 -0
  29. package/dist/{sandbox-3VRX47UY.js → sandbox-7CGSIIIZ.js} +4 -4
  30. package/dist/sandbox-worker.cjs +30 -11
  31. package/dist/sandbox-worker.cjs.map +1 -1
  32. package/dist/sandbox-worker.js +1 -1
  33. package/dist/{elicitation-DS-84_bF.d.cts → vault-Mar2CY0J.d.cts} +526 -526
  34. package/dist/{elicitation-DS-84_bF.d.ts → vault-Mar2CY0J.d.ts} +526 -526
  35. package/package.json +13 -3
  36. package/dist/chunk-DAREMCXF.js.map +0 -1
  37. package/dist/chunk-YPCHD6DV.js.map +0 -1
  38. package/dist/chunk-ZSZSSJS4.js.map +0 -1
  39. /package/dist/{chunk-2MLHZ6LQ.js.map → chunk-Y4MIIBPB.js.map} +0 -0
  40. /package/dist/{sandbox-3VRX47UY.js.map → sandbox-7CGSIIIZ.js.map} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { LanguageModel, ToolSet, Experimental_DecisionModel, Tool, FilePart, ImageModel, SpeechModel, TranscriptionModel, SystemModelMessage, ModelMessage, generateText, streamText } from 'ai';
2
- import { V as VaultOptions, M as McpSkillSource, a as McpSkillConsent, b as McpSkillGrants, c as McpSkillRunConsent, d as McpSkillConsentView, e as McpSkillSnapshotMemory, f as McpElicitationSchema, g as McpElicitationReason, h as McpAppToolResult } from './elicitation-DS-84_bF.js';
3
- export { I as IndexedDBVault, i as MCP_APPS_EXTENSION, j as MCP_APP_MAX_HTML_CHARS, k as MCP_APP_MAX_RESULT_CHARS, l as MCP_APP_MIME_TYPE, m as MCP_SKILLS_EXTENSION, n as MCP_SKILLS_MAX_PER_SERVER, o as MCP_SKILLS_MAX_TOTAL, p as MCP_SKILL_BODY_MAX_CHARS, q as MCP_SKILL_CONSENTS, r as MCP_SKILL_CONSENT_DEFAULT, s as MCP_SKILL_DESCRIPTION_MAX_CHARS, t as MCP_SKILL_DIRECTORY_ENTRIES_MAX, u as MCP_SKILL_FILE_MAX_CHARS, v as MCP_SKILL_MAX_RESOURCES, w as MCP_SKILL_MAX_TOTAL_BYTES, x as MCP_SKILL_SNAPSHOTS_MAX_BYTES, y as MCP_SKILL_SNAPSHOT_MAX_DEPTH, z as MCP_SKILL_SNAPSHOT_MAX_DIRECTORIES, A as MCP_SKILL_URI_MAX_CHARS, B as McpAppCsp, C as McpAppPermissions, D as McpAppResource, E as McpAppVisibility, F as McpElicitationFieldSchema, G as McpSkillsOptions, H as McpSkillsSetting, S as SkillDirectoryListing, J as mcpAppOrigin, K as mcpSkillEntryRefusal, L as mcpSkillPreamble, N as mcpSkillUriRefusal } from './elicitation-DS-84_bF.js';
1
+ import { LanguageModel, Experimental_DecisionModel, Tool, ToolSet, FilePart, ImageModel, SpeechModel, TranscriptionModel, SystemModelMessage, ModelMessage, generateText, streamText } from 'ai';
2
+ import { M as McpSkillConsentView, a as McpElicitationSchema, b as McpElicitationReason, c as McpAppToolResult, V as VaultOptions, d as McpSkillSource, e as McpSkillConsent, f as McpSkillGrants, g as McpSkillRunConsent, h as McpSkillSnapshotMemory } from './vault-Mar2CY0J.js';
3
+ export { I as IndexedDBVault, i as MCP_APPS_EXTENSION, j as MCP_APP_MAX_HTML_CHARS, k as MCP_APP_MAX_RESULT_CHARS, l as MCP_APP_MIME_TYPE, m as MCP_SKILLS_EXTENSION, n as MCP_SKILLS_MAX_PER_SERVER, o as MCP_SKILLS_MAX_TOTAL, p as MCP_SKILL_BODY_MAX_CHARS, q as MCP_SKILL_CONSENTS, r as MCP_SKILL_CONSENT_DEFAULT, s as MCP_SKILL_DESCRIPTION_MAX_CHARS, t as MCP_SKILL_DIRECTORY_ENTRIES_MAX, u as MCP_SKILL_FILE_MAX_CHARS, v as MCP_SKILL_MAX_RESOURCES, w as MCP_SKILL_MAX_TOTAL_BYTES, x as MCP_SKILL_SNAPSHOTS_MAX_BYTES, y as MCP_SKILL_SNAPSHOT_MAX_DEPTH, z as MCP_SKILL_SNAPSHOT_MAX_DIRECTORIES, A as MCP_SKILL_URI_MAX_CHARS, B as McpAppCsp, C as McpAppPermissions, D as McpAppResource, E as McpAppVisibility, F as McpElicitationFieldSchema, G as McpSkillsOptions, H as McpSkillsSetting, S as SkillDirectoryListing, J as mcpAppOrigin, K as mcpSkillEntryRefusal, L as mcpSkillPreamble, N as mcpSkillUriRefusal } from './vault-Mar2CY0J.js';
4
+ import { PipelineEvent, PipelineNode, PipelineDefinition, PipelineResult, PipelineNodeRunner } from './pipeline-engine.js';
5
+ export { PIPELINE_LIMITS, PIPELINE_ROUTER_SYSTEM, PipelineAbortBehaviour, PipelineCondition, PipelineEdge, PipelineGraphRunOptions, PipelineIssue, PipelineNodeContext, PipelineNodeError, PipelineNodeEvent, PipelineNodeInput, PipelineNodeOutput, PipelineNodeSource, PipelinePlan, PipelineRoute, PipelineStop, PipelineTraceEntry, PipelineUsage, PipelineValidation, PipelineValidationError, matchPipelineRoute, normalizePipeline, preparePipeline, renderPipelineNodeInput, renderPipelineRoutePrompt, runPipelineGraph, testPipelineCondition, validatePipeline } from './pipeline-engine.js';
4
6
  import { A as AgentToolSet, a as AgentTool } from './types-DwSMj_Xs.js';
5
7
  export { p as promptHintOf } from './types-DwSMj_Xs.js';
6
8
  import { z, ZodType } from 'zod';
@@ -114,10 +116,13 @@ interface IStepResult {
114
116
  * checkpointed — it runs again from its start. For a read that is free; for a
115
117
  * write it may apply twice, so a tool with side effects should be idempotent (or
116
118
  * the host should keep the consent gate on). Attachments (images, files) are not
117
- * stored — pass them again to `run()` when resuming.
119
+ * stored — pass them again to `run()` when resuming. The same holds for a run that is
120
+ * stopped or fails in the middle of a step: its closing snapshot is the run at that step's
121
+ * start (the step still in `remaining`, not counted in `iterations`).
118
122
  *
119
123
  * Persistence is observability, not a correctness boundary: a hook that throws is
120
- * logged and the run carries on.
124
+ * logged and the run carries on. The one exception is `onRunResume`: a resume whose attempt
125
+ * cannot be put on record is refused (see `recordResume`).
121
126
  */
122
127
  type RunStatus = 'executing' | 'complete' | 'failed' | 'cancelled';
123
128
  /** Everything needed to continue a run from the end of an iteration. */
@@ -172,6 +177,13 @@ interface RunSnapshot {
172
177
  escalations?: number;
173
178
  /** Helpers the model started so far (counts against `subagents.dynamic.maxChildren` on resume). */
174
179
  subagentsSpawned?: number;
180
+ /**
181
+ * The attempt that wrote the snapshot: 1 for the run as first started, one more for every
182
+ * resume - the `attempt` of its events. A resume records its attempt BEFORE any of its events
183
+ * (`onRunResume`), so a crash at any point never lets two attempts share a number. Absent on a
184
+ * snapshot written before the field existed: read as 1.
185
+ */
186
+ attempt?: number;
175
187
  /** Final answer (status `complete`). */
176
188
  text?: string;
177
189
  /** What ended the run (status `failed`). */
@@ -185,6 +197,14 @@ interface RunPersistence {
185
197
  onStepComplete?: (snapshot: RunSnapshot) => void | Promise<void>;
186
198
  /** The run resolved: `complete`, `failed` (it threw) or `cancelled` (it was stopped). */
187
199
  onRunComplete?: (snapshot: RunSnapshot) => void | Promise<void>;
200
+ /**
201
+ * A resume is starting: the loaded snapshot with the NEW `attempt` (status `executing`),
202
+ * written before the resumed run emits anything, so that a crash before its first checkpoint
203
+ * still leaves the attempt on record. Without it the same write goes to `onStepComplete`.
204
+ * Unlike the other write hooks this one is NOT best-effort: a throw fails the resume (nothing
205
+ * ran) - an attempt that is not on record would be reused by the next resume.
206
+ */
207
+ onRunResume?: (snapshot: RunSnapshot) => void | Promise<void>;
188
208
  /**
189
209
  * What `run(goal, { resumeFromRunId })` reads. Return `null` when there is none.
190
210
  * An implementation that does not want to support resume can leave it out.
@@ -326,6 +346,13 @@ interface StoredMessage {
326
346
  }
327
347
  /** Persists an agent session's transcript. Swap in any backend. */
328
348
  interface ContextStore {
349
+ /**
350
+ * Set when the origin's tabs share this store (`IndexedDBStore`: its IndexedDB database): a run
351
+ * of a session then holds the session's lock across tabs (`sessionLock`) and relays itself to
352
+ * the other tabs (`watchSession`) under this name. Absent (an in-memory store): each tab has
353
+ * its own sessions, and nothing is locked or relayed.
354
+ */
355
+ readonly dbName?: string;
329
356
  load(sessionId: string): Promise<StoredMessage[]>;
330
357
  append(sessionId: string, message: StoredMessage): Promise<void>;
331
358
  replace(sessionId: string, messages: StoredMessage[]): Promise<void>;
@@ -452,1756 +479,1798 @@ declare const compactSteps: (done: string[], model: LanguageModel, opts: Compres
452
479
  thresholdTokens: number;
453
480
  }) => Promise<string[]>;
454
481
 
455
- /**
456
- * Leveled logging for the agent. The host passes a console-like sink and a
457
- * level; everything below the level is a no-op. Default: 'warn' onto the
458
- * global console — silent in normal operation, but salvage fallbacks, empty
459
- * plans, degraded tool modes and failed tool calls stay visible.
460
- *
461
- * Set `logLevel: 'debug'` to see every phase's raw model output, parsed
462
- * results and tool dispatches — the first thing to reach for when the agent
463
- * "says it did something but nothing happened".
464
- */
465
- type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug';
466
- /** Console-compatible sink (pass `console`, or your own collector). */
467
- interface AgentLoggerSink {
468
- error(...args: unknown[]): void;
469
- warn(...args: unknown[]): void;
470
- info(...args: unknown[]): void;
471
- debug(...args: unknown[]): void;
482
+ interface IDecisionOption {
483
+ id: string;
484
+ description?: string;
472
485
  }
473
- interface AgentLogger extends AgentLoggerSink {
474
- readonly level: LogLevel;
486
+ interface IDecisionQuestion {
487
+ id: string;
488
+ prompt: string;
489
+ options: readonly IDecisionOption[];
490
+ context?: string;
475
491
  }
476
- declare const createLogger: (level?: LogLevel, sink?: AgentLoggerSink) => AgentLogger;
477
-
478
- /**
479
- * Providers the browser registry can resolve from a spec. This is deliberately
480
- * a browser-safe subset of the Node sibling's list: Amazon Bedrock (SigV4
481
- * signing), Google Vertex (ADC via google-auth-library) and Cloudflare
482
- * (Worker bindings / process.env) are Node-only and omitted; Azure folds into
483
- * `openai-compatible`. `web-llm` is the local WebGPU pseudo-provider (no API
484
- * key). Any other runtime — Chrome/Edge built-in AI, a custom LanguageModel —
485
- * is passed to the agent directly and never touches this registry.
486
- */
487
- type ProviderType = 'openai' | 'anthropic' | 'google' | 'openai-compatible' | 'xai' | 'deepseek' | 'gateway' | 'web-llm';
488
- /** A model described by provider + id, resolved through the registry (+ vault). */
489
- interface ProviderModelSpec {
490
- providerType: ProviderType;
491
- /** Model id, e.g. "gpt-4o-mini", "claude-haiku-4-5", "Llama-3.2-3B-Instruct-q4f16_1-MLC". */
492
- model: string;
493
- /** Provider endpoint override. Required for `openai-compatible`; a proxy URL for the rest. */
494
- baseURL?: string;
495
- /** Id under which the API key is stored in the CredentialStore / vault. Preferred. */
496
- credentialRef?: string;
497
- /**
498
- * Dev-only inline API key. Prefer `credentialRef` so the key lives encrypted
499
- * in the vault, not on a long-lived config object. Using this logs a warning.
500
- */
501
- apiKey?: string;
502
- /** Extra request headers merged into the provider factory (e.g. a proxy auth header). */
503
- headers?: Record<string, string>;
504
- /** Escape hatch spread into the SDK factory after baseURL / apiKey / headers. */
505
- providerOptions?: Record<string, unknown>;
492
+ interface IDecisionCallOptions {
493
+ abortSignal?: AbortSignal;
506
494
  }
507
- /**
508
- * A per-stage override that inherits the base provider + credentials and
509
- * changes only the fields it sets (typically just `model`). Distinguished from
510
- * a full ProviderModelSpec by the absence of `providerType`.
511
- */
512
- interface StageOverride {
495
+ interface IDecisionAnswer {
496
+ choice: string;
497
+ confidence: number;
498
+ usage?: {
499
+ inputTokens?: number;
500
+ outputTokens?: number;
501
+ };
502
+ }
503
+ interface IDecisionModel {
504
+ readonly name?: string;
505
+ decide: (question: IDecisionQuestion, options: IDecisionCallOptions) => Promise<IDecisionAnswer>;
506
+ }
507
+ interface IDecisionConfig {
508
+ confidenceThreshold?: number;
509
+ timeoutMs?: number;
510
+ replan?: boolean;
511
+ route?: boolean;
512
+ }
513
+ declare const DEFAULT_DECISION_CONFIDENCE_THRESHOLD = 0.8;
514
+ declare const DEFAULT_DECISION_TIMEOUT_MS = 5000;
515
+ type DecisionPoint = 'replan' | 'route';
516
+ type DecisionFallbackReason = 'low-confidence' | 'invalid-choice' | 'invalid-confidence' | 'error' | 'timeout' | 'needs-model';
517
+ interface IDecisionOutcome {
518
+ accepted: boolean;
519
+ choice?: string;
520
+ confidence?: number;
521
+ threshold: number;
522
+ reason?: DecisionFallbackReason;
523
+ error?: string;
524
+ durationMs: number;
525
+ usage?: {
526
+ inputTokens?: number;
527
+ outputTokens?: number;
528
+ };
529
+ }
530
+ interface IDecisionEvent {
531
+ type: 'decision';
532
+ point: DecisionPoint;
533
+ accepted: boolean;
534
+ choice?: string;
535
+ confidence?: number;
536
+ threshold: number;
537
+ reason?: DecisionFallbackReason;
538
+ error?: string;
539
+ durationMs: number;
513
540
  model?: string;
514
- baseURL?: string;
515
- credentialRef?: string;
516
- apiKey?: string;
541
+ }
542
+ declare const askDecisionModel: (model: IDecisionModel, question: IDecisionQuestion, config?: IDecisionConfig, signal?: AbortSignal) => Promise<IDecisionOutcome>;
543
+ interface IAiSdkDecisionOptions {
544
+ name?: string;
545
+ maxRetries?: number;
517
546
  headers?: Record<string, string>;
518
- providerOptions?: Record<string, unknown>;
519
547
  }
520
- /** What a caller hands us for a model: a ready AI SDK model, or a spec to resolve. */
521
- type ModelInput = LanguageModel | ProviderModelSpec;
522
- /** A model input, plus the partial-override form usable for per-stage layering. */
523
- type StageInput = ModelInput | StageOverride;
524
- /** Outcome of resolving one stage: either a ready model, or a fully-resolved spec. */
525
- type ResolvedStage = {
526
- type: 'direct';
527
- model: LanguageModel;
528
- } | {
529
- type: 'spec';
530
- spec: ProviderModelSpec;
531
- };
532
- /** True for a ready AI SDK model: a gateway model-id string or a LanguageModelV* object. */
533
- declare const isDirectModel: (m: unknown) => m is LanguageModel;
534
- /** True for a full provider spec (carries the `providerType` discriminator). */
535
- declare const isProviderSpec: (m: unknown) => m is ProviderModelSpec;
548
+ declare const decisionModelFromAiSdk: (model: Experimental_DecisionModel, options?: IAiSdkDecisionOptions) => IDecisionModel;
536
549
 
537
550
  /**
538
- * Default phase prompts. Each builder returns `{ system, prompt }` strings.
539
- * Because the agent runs in two tool-modes, the builders switch on `ctx.mode`:
540
- *
541
- * - `native` — the model calls tools / emits schema-constrained JSON via the
542
- * AI SDK, so the prompts describe the task and let the SDK enforce structure.
543
- * - `prompted` — weak local models can't do that reliably, so the prompts spell
544
- * out an exact JSON shape and (for the executor) include a tool catalogue;
545
- * the output is salvaged by parse.ts.
546
- *
547
- * Layout matters for prompt caching: the SYSTEM part holds only what is stable
548
- * for a whole run (role, skills, the planner's tool catalogue), the user
549
- * prompt holds everything that changes (goal, state, history, progress), so a
550
- * provider's prefix cache can reuse the system part across calls.
551
+ * Tool consent. Every tool call passes a gate that decides allow / ask / deny:
551
552
  *
552
- * The agent is autonomous by design: it plans tool use for anything the tools
553
- * can do or look up, never asks the user for confirmation (consent is the
554
- * host's `toolApproval` policy), and states assumptions instead of asking.
553
+ * - `autopilot` — run everything (default; explicit `rules` still apply);
554
+ * - `ask-writes` — run read-only tools, ask before anything that may change state;
555
+ * - `ask-all` — ask before every call;
556
+ * - `read-only` — run read-only tools, refuse the rest without asking.
555
557
  *
556
- * Override any builder via `BrowserAgentConfig.prompts`.
558
+ * A tool is read-only when its MCP annotations say so (`readOnlyHint`) or the
559
+ * host marked it (`defineTool({ readOnly: true })` / `markReadOnly`). Unknown =
560
+ * may write: the safe assumption.
557
561
  */
558
- type ToolCallMode = 'native' | 'prompted';
559
- interface PromptParts {
560
- system: string;
561
- prompt: string;
562
+ type ToolApprovalMode = 'autopilot' | 'ask-writes' | 'ask-all' | 'read-only';
563
+ type ToolPermission = 'allow' | 'ask' | 'deny';
564
+ declare const TOOL_APPROVAL_MODES: readonly ToolApprovalMode[];
565
+ interface ToolApprovalRequest {
566
+ /** Unique per request — echo it back from a UI. */
567
+ id: string;
568
+ toolName: string;
569
+ input: unknown;
570
+ readOnly: boolean;
571
+ step?: IPlanStep;
572
+ /**
573
+ * Set when the call comes from a helper the model started (`subagents.dynamic`), not from the
574
+ * run itself: the helper's id (as in its `subagent.start` event) and its depth.
575
+ */
576
+ subagent?: {
577
+ id: string;
578
+ depth: number;
579
+ };
580
+ /**
581
+ * Set when the call comes from an MCP App (`Agent.approveAppToolCall`), not from the model:
582
+ * a UI says so ("The app “travel” wants to run …"). `toolName` above is then the name the
583
+ * agent's rules match (`server__tool`), `app.tool` the server's own name for it.
584
+ */
585
+ app?: ToolApprovalApp;
586
+ /**
587
+ * Set when the call runs code (`run_js`, or a tool marked with `markCodeExecution`) while the
588
+ * run acts on skills an MCP server served: those skills, by name. Such a call is ALWAYS asked,
589
+ * whatever the mode, a rule or an earlier "always allow" say (the Skills extension: a server's
590
+ * skill must not lead to code running here without a person's approval).
591
+ */
592
+ mcpSkills?: string[];
593
+ /**
594
+ * Set when the request is not about a tool call but about an MCP server's skill that is about
595
+ * to enter the model's context (`load_skill`, the planner's pick, a resumed run; `skills` on a
596
+ * server, consent `'ask'` / `'once-per-skill'`): the server, the skill, its description and
597
+ * size and the very text the model would read - the SERVER's words, to show as plain text.
598
+ * `toolName` is `'load_skill'`. Approve to let it in (`remember: true` = every skill of that
599
+ * server for the agent's life, nested ones excepted), deny to keep it out. Asked whatever the
600
+ * approval mode and the rules say.
601
+ */
602
+ skill?: McpSkillConsentView;
562
603
  }
563
- interface PlannerPromptContext {
564
- goal: string;
565
- state?: string;
566
- toolCatalog: string;
567
- mode: ToolCallMode;
568
- /** Prior session messages (oldest first), for resolving references to earlier turns. */
569
- history?: {
570
- role: string;
571
- content: string;
572
- }[];
573
- /** "- name: description" index of the configured skills, when any. */
574
- skills?: string;
575
- /** The catalogue is condensed and the executor can search the rest (large catalogues). */
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;
604
+ /** Who asks when an MCP App asks (see `ToolApprovalRequest.app`). */
605
+ interface ToolApprovalApp {
606
+ /** The MCP server the app came from (its tools are the only ones it may call). */
607
+ server: string;
608
+ /** The tool's own name on that server. */
609
+ tool: string;
610
+ /** The app's `ui://` resource. */
611
+ resourceUri: string;
583
612
  }
584
- interface ExecutorPromptContext {
585
- goal: string;
586
- state?: string;
587
- step: string;
588
- index: number;
589
- total: number;
590
- toolCatalog: string;
591
- /** Earlier steps of this run, each with its outcome and key data. */
592
- done: string[];
593
- mode: ToolCallMode;
594
- /** "- name: description" index of the configured skills, when any. */
595
- skills?: string;
596
- /** Full instructions of the skills active in this run. */
597
- activeSkills?: string;
598
- /** The executor can call find_tools to activate more tools. */
599
- searchMode?: boolean;
600
- /** What the user said while the run was going (`RunControl.send`), oldest first. */
601
- updates?: string[];
602
- /** Set when `config.learning` is on (and not muted): the executor is told to keep a notebook. */
603
- learning?: {
604
- fetch: boolean;
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;
610
- }
611
- interface ReplannerPromptContext {
612
- goal: string;
613
- state?: string;
614
- done: string[];
615
- remaining: string[];
616
- mode: ToolCallMode;
617
- activeSkills?: string;
618
- /** What the user said while the run was going, oldest first. */
619
- updates?: string[];
620
- /** How many of `updates` (the last ones) the plan has not been weighed against yet. */
621
- newUpdates?: number;
622
- /** Set when `config.executorTiers` is on: the steps of a revised plan are rated too. */
623
- tiers?: boolean;
624
- }
625
- interface SynthesizerPromptContext {
626
- goal: string;
627
- state?: string;
628
- done: string[];
629
- /** Excerpts of what the tools returned, for answering with real data. */
630
- findings?: string[];
631
- activeSkills?: string;
632
- /** What the user said while the run was going, oldest first. */
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;
636
- }
637
- interface Prompts {
638
- planner(ctx: PlannerPromptContext): PromptParts;
639
- executor(ctx: ExecutorPromptContext): PromptParts;
640
- replanner(ctx: ReplannerPromptContext): PromptParts;
641
- synthesizer(ctx: SynthesizerPromptContext): PromptParts;
613
+ /** What the gate hands `onRequest` beside the request. */
614
+ interface ToolApprovalContext {
615
+ /**
616
+ * Aborted when the question ends WITHOUT your answer: no decision within `timeoutMs`
617
+ * (`signal.reason` is an Error named 'TimeoutError'), the run was stopped ('AbortError'), or
618
+ * the handler failed. Take the prompt down then: an answer given later is ignored. Never
619
+ * aborted once you have answered.
620
+ */
621
+ signal: AbortSignal;
642
622
  }
643
- declare const defaultPrompts: Prompts;
644
- /** Prepend a host-supplied systemPrompt to a phase system prompt, if present. */
645
- declare const withSystem: (base: string, extra?: string) => string;
646
-
647
623
  /**
648
- * The seam the provider registry uses to fetch API keys at model-build time.
649
- * Swap in any backend: the encrypted vault (default), an in-memory map (tests /
650
- * SSR), or a `fetch` to your own short-lived-token endpoint.
624
+ * `true`/`false`, or an object. `remember: true` on an approval allows this
625
+ * tool for the rest of the agent's life ("always allow").
651
626
  */
652
- interface CredentialStore {
653
- getApiKey(ref: string): Promise<string | undefined>;
654
- setApiKey(ref: string, key: string): Promise<void>;
655
- deleteApiKey(ref: string): Promise<void>;
656
- }
657
- /** Default CredentialStore: encrypted, IndexedDB-backed (see IndexedDBVault). */
658
- declare class VaultCredentialStore implements CredentialStore {
659
- private readonly vault;
660
- constructor(opts?: VaultOptions);
661
- getApiKey(ref: string): Promise<string | undefined>;
662
- setApiKey(ref: string, key: string): Promise<void>;
663
- deleteApiKey(ref: string): Promise<void>;
627
+ type ToolApprovalDecision = boolean | {
628
+ approved: boolean;
629
+ reason?: string;
630
+ remember?: boolean;
631
+ };
632
+ interface ToolApprovalConfig {
633
+ /** Default policy (default 'autopilot'). */
634
+ mode?: ToolApprovalMode;
635
+ /**
636
+ * Per-tool overrides by exact name or `*` glob, e.g. `{ 'github__delete_*': 'deny' }`.
637
+ * They win over the mode — an explicit 'ask' still asks under autopilot.
638
+ */
639
+ rules?: Record<string, ToolPermission>;
640
+ /** Resolves an approval request (a UI prompt, a policy service, …). */
641
+ onRequest?: (req: ToolApprovalRequest, ctx: ToolApprovalContext) => ToolApprovalDecision | Promise<ToolApprovalDecision>;
642
+ /**
643
+ * No decision within this many ms → deny. Default 300 000 ({@link TOOL_APPROVAL_TIMEOUT_MS}).
644
+ * `0` or `Infinity`: no bound - the question waits until the run is stopped; so does a value
645
+ * above 2^31 - 1 (about 24.8 days, the most a timer holds). Negative or NaN: `createAgent`
646
+ * throws. The only bound on the wait: the step's `chatTimeoutMs` (and a subagent's
647
+ * `timeoutMs`) stop while a person decides.
648
+ */
649
+ timeoutMs?: number;
664
650
  }
665
- /** Non-persistent CredentialStore for tests / SSR / ephemeral sessions. */
666
- declare class MemoryCredentialStore implements CredentialStore {
667
- private readonly map;
668
- constructor(initial?: Record<string, string>);
669
- getApiKey(ref: string): Promise<string | undefined>;
670
- setApiKey(ref: string, key: string): Promise<void>;
671
- deleteApiKey(ref: string): Promise<void>;
651
+ /** How long a question waits for a decision when `toolApproval.timeoutMs` is not set: 5 minutes. */
652
+ declare const TOOL_APPROVAL_TIMEOUT_MS = 300000;
653
+ /** Raised by a denied tool call; recorded as a failed call the replanner sees. */
654
+ declare class ToolDeniedError extends Error {
655
+ constructor(reason?: string);
656
+ toJSON(): string;
672
657
  }
673
-
658
+ /** Mark a tool as read-only so `ask-writes` / `read-only` let it through. Returns it. */
659
+ declare const markReadOnly: <T extends object>(tool: T, readOnly?: boolean) => T;
674
660
  /**
675
- * A small virtual file system for the browser — the agent's (and the user's)
676
- * workspace: attachments the user drops in, reports the agent writes, images
677
- * pasted into the chat. Persistent in IndexedDB by default, in-memory on
678
- * request (tests, private mode). Paths are POSIX-like and always absolute
679
- * ("/notes/todo.md"); there are no real directories — a "directory" is a path
680
- * prefix.
661
+ * Mark a tool as one that runs code (the sandbox's `run_js` is): while a run acts on an MCP
662
+ * server's skill, every call of it is asked (`decideToolPermission`).
681
663
  */
682
- interface VirtualFile {
683
- path: string;
684
- /** Text, or base64 for binary content (see `encoding`). */
685
- content: string;
686
- encoding: 'utf8' | 'base64';
687
- mimeType: string;
688
- /** Size of the decoded content in bytes. */
689
- size: number;
690
- updatedAt: number;
691
- }
692
- /** A listing entry (no content). */
693
- type VirtualFileInfo = Omit<VirtualFile, 'content'>;
694
- interface VirtualFileSystemOptions {
695
- /** Keep files in memory only (default false: IndexedDB). */
696
- memory?: boolean;
697
- /** IndexedDB database name, forwarded to the shared owner (default 'agent-web'). */
698
- dbName?: string;
699
- /** Isolates several file systems in one database (default 'default'). */
700
- namespace?: string;
701
- /** Refuse a single file larger than this many bytes (default 10 MB). */
702
- maxFileBytes?: number;
703
- }
704
- type VfsListener = (change: {
705
- type: 'write' | 'delete';
706
- path: string;
707
- }) => void;
708
- /** A best-effort MIME type from a file name. */
709
- declare const mimeFromPath: (path: string) => string;
710
- /** True for MIME types the agent can read as text. */
711
- declare const isTextMime: (mime: string) => boolean;
664
+ declare const markCodeExecution: <T extends object>(tool: T, codeExecution?: boolean) => T;
665
+ declare const isCodeExecutionTool: (tool: unknown) => boolean;
666
+ declare const isReadOnlyTool: (tool: Tool | undefined) => boolean;
667
+ /** The most specific matching rule: an exact name, else the longest glob. Pure. */
668
+ declare const matchRule: (rules: Record<string, ToolPermission> | undefined, toolName: string) => ToolPermission | undefined;
712
669
  /**
713
- * Normalise a path: absolute, forward slashes, no "." / ".." / empty segments.
714
- * Throws on a path that escapes the root.
670
+ * What the gate does for one call, before any human is involved. Order:
671
+ * remembered "always allow" → most specific rule → mode default. Pure.
672
+ * Then one rule that only ever tightens: a call that runs code (`codeExecution`) while the run
673
+ * acts on an MCP server's skill (`mcpSkills`) is asked when it would have been allowed - by the
674
+ * mode, a rule or an "always allow" alike. A deny stays a deny.
715
675
  */
716
- declare const normalizePath: (input: string) => string;
717
- /** Base64 of bytes, chunked so a large file can't blow the call stack. */
718
- declare const bytesToBase64: (bytes: Uint8Array) => string;
719
- declare class VirtualFileSystem {
720
- private readonly memory?;
721
- private readonly dbName?;
722
- private readonly ns;
723
- private readonly maxFileBytes;
724
- private readonly listeners;
725
- constructor(opts?: VirtualFileSystemOptions);
726
- private key;
727
- /** Subscribe to writes and deletes (e.g. to refresh a file list). Returns an unsubscribe. */
728
- onChange(listener: VfsListener): () => void;
729
- private notify;
730
- write(path: string, content: string | Uint8Array, opts?: {
731
- mimeType?: string;
732
- encoding?: VirtualFile['encoding'];
733
- }): Promise<VirtualFileInfo>;
734
- /** Store a data URL ("data:image/png;base64,…") as a file. */
735
- writeDataUrl(path: string, dataUrl: string): Promise<VirtualFileInfo>;
736
- read(path: string): Promise<VirtualFile | undefined>;
737
- /** The file as a data URL (for <img src>, downloads). */
738
- readDataUrl(path: string): Promise<string | undefined>;
739
- delete(path: string): Promise<boolean>;
740
- /** Files under a prefix ("/" = all), sorted by path. */
741
- list(prefix?: string): Promise<VirtualFileInfo[]>;
742
- /** Remove every file (of this namespace). */
743
- clear(): Promise<void>;
744
- }
676
+ declare const decideToolPermission: (opts: {
677
+ toolName: string;
678
+ readOnly: boolean;
679
+ mode: ToolApprovalMode;
680
+ rules?: Record<string, ToolPermission>;
681
+ remembered?: ReadonlySet<string>;
682
+ codeExecution?: boolean;
683
+ mcpSkills?: readonly string[];
684
+ }) => ToolPermission;
745
685
 
686
+ type ReplanMode = 'continue' | 'revise' | 'finish';
687
+ type Phase = 'plan' | 'execute' | 'replan' | 'synthesize';
746
688
  /**
747
- * Skills — reusable instruction bundles in the agentskills.io shape
748
- * (`SKILL.md` with `name`/`description` frontmatter, a markdown body, optional
749
- * bundled text files). Progressive disclosure: only the one-line index sits in
750
- * the prompts; a skill's full instructions enter the context when the planner
751
- * selects it or the executor loads it with `load_skill`.
689
+ * Phases a `usage` event can be charged to: the four stages plus compaction and subagents;
690
+ * `decision` - a call to `config.decisionModel` (`usage.decisionCalls`, plus the tokens its API
691
+ * reported); 'media' - a call to an image / speech / transcription model (`config.media`),
692
+ * whose `usage` carries the media fields and zero tokens; and 'search' - a `web_search` through
693
+ * the google provider (`config.search`): the grounding call is a model call, and these are the
694
+ * tokens its API reported.
752
695
  */
753
- interface Skill {
754
- /** Stable id: lowercase letters, digits and dashes, 1–64 chars. */
755
- name: string;
756
- /** When to use it — the only part always shown to the model. */
757
- description: string;
758
- /** Full instructions (the markdown body of SKILL.md). */
759
- content: string;
760
- /** Bundled text resources, addressed by skill-relative POSIX paths. */
761
- files?: {
762
- path: string;
763
- content: string;
764
- }[];
765
- /** Set on a skill the AGENT wrote (`config.learning`); absent on the host's own. */
766
- origin?: SkillOrigin;
767
- /**
768
- * Set on a skill an MCP server serves (`skills: true` on its config): which server, and the URI
769
- * of its SKILL.md. Third-party text: loaded on demand, under a preamble that says so.
770
- */
771
- mcp?: McpSkillOrigin;
772
- }
773
- /** Where an MCP server's skill comes from: the server's key in the connection, its SKILL.md URI. */
774
- interface McpSkillOrigin {
775
- server: string;
776
- uri: string;
777
- }
778
- /** Where a learned skill came from. */
779
- interface SkillOrigin {
780
- kind: 'learned';
781
- /** Epoch ms of the last write. */
782
- at: number;
783
- /** 1 for a new lesson, +1 each time the agent rewrites it. */
784
- revision: number;
785
- runId?: string;
786
- /** What the model said it consulted (URLs without query strings, doc names). */
787
- sources?: string[];
788
- /** Pages web_fetch read during the run that wrote it - recorded by the harness, not the model. */
789
- fetched?: string[];
790
- }
791
- /** Names of the built-in skill tools (reserved when skills are configured). */
792
- declare const SKILL_TOOL_NAMES: readonly ["load_skill", "read_skill_file"];
793
- /** Validate a skill definition and return it (throws a precise error). */
794
- declare const defineSkill: (skill: Skill) => Skill;
696
+ /** `'app'`: a completion an MCP App asked for (`Agent.sampleForApp`), outside any run. */
697
+ type UsagePhase = Phase | 'compact' | 'subagent' | 'decision' | 'media' | 'search' | 'app';
795
698
  /**
796
- * Parse a SKILL.md document into a {@link Skill}. Frontmatter must provide
797
- * `name` and `description`; the markdown body becomes `content`.
699
+ * Everything the agent does is streamed as a typed event so any UI (or none)
700
+ * can render progress. The final answer arrives as a `final` event; there is no
701
+ * built-in rendering. This is a browser-focused subset of the Node sibling's
702
+ * event taxonomy (no persistence/otel events), plus `model.load` for WebLLM
703
+ * weight-download progress.
798
704
  */
799
- declare const parseSkillMarkdown: (markdown: string, files?: {
800
- path: string;
801
- content: string;
802
- }[]) => Skill;
803
- interface LoadSkillOptions {
804
- /** Bundled files to fetch, relative to the SKILL.md URL. */
805
- files?: string[];
806
- fetch?: typeof fetch;
705
+ type AgentEventBody =
706
+ /**
707
+ * `runId` names the run for `persistence` / `resumeFromRunId`. `resumed` is set when it
708
+ * continues a checkpointed run: the steps already done and the ones still to come.
709
+ */
710
+ {
711
+ type: 'run.start';
712
+ goal: string;
713
+ runId?: string;
714
+ resumed?: {
715
+ completedSteps: number;
716
+ remainingSteps: number;
717
+ };
718
+ } | {
719
+ type: 'model.load';
720
+ progress: number;
721
+ text: string;
722
+ } | {
723
+ type: 'plan.thought-delta';
724
+ delta: string;
725
+ } | {
726
+ type: 'plan.step-added';
727
+ step: IPlanStep;
728
+ index: number;
729
+ } | {
730
+ type: 'plan.created';
731
+ plan: IPlan;
732
+ } | {
733
+ type: 'plan.revised';
734
+ plan: IPlan;
735
+ reason: string;
807
736
  }
808
- /** Fetch a SKILL.md (and optionally its bundled files) over HTTP. */
809
- declare const loadSkillFromUrl: (url: string, opts?: LoadSkillOptions) => Promise<Skill>;
810
737
  /**
811
- * How a learned skill is introduced wherever its text is shown to the model: as a note of the
812
- * agent's own, subordinate to the user - never as an instruction.
738
+ * `tier` / `model` / `tierReason`: only when `config.executorTiers` is on - the tier the step
739
+ * starts on, its model id, and why that tier (see `TierReason`).
813
740
  */
814
- declare const learnedPreamble: (skill: Skill) => string;
815
- /** What the person answered (`askMcpSkillConsent`). */
816
- interface McpSkillAnswer {
817
- approved: boolean;
818
- /** "Always for this server". */
819
- remember?: boolean;
820
- reason?: string;
821
- /** Who answered: a person, nobody (no handler), or nobody in time / the handler failed. */
822
- by: 'person' | 'no-handler' | 'no-answer';
741
+ | {
742
+ type: 'step.start';
743
+ step: IPlanStep;
744
+ index: number;
745
+ total: number;
746
+ tier?: ModelTier;
747
+ model?: string;
748
+ tierReason?: TierReason;
823
749
  }
824
750
  /**
825
- * What a run hands the MCP skill paths so that a person can be asked: the agent's policy, the
826
- * session's grants (shared with helpers), the run's own record, and the question itself.
751
+ * The step failed on `from` and is retried on the stronger tier `to` (`config.escalation`);
752
+ * `model` is the model id of `to`. Fires between the step's start and its completion.
827
753
  */
828
- interface McpSkillConsentScope {
829
- agentConsent?: McpSkillConsent;
830
- grants: McpSkillGrants;
831
- run: McpSkillRunConsent;
832
- ask: (input: unknown, skill: McpSkillConsentView, signal?: AbortSignal) => Promise<McpSkillAnswer>;
754
+ | {
755
+ type: 'step.escalated';
756
+ step: IPlanStep;
757
+ from: ModelTier;
758
+ to: ModelTier;
759
+ model: string;
760
+ reason: EscalationReason;
761
+ } | {
762
+ type: 'step.text-delta';
763
+ step: IPlanStep;
764
+ delta: string;
765
+ }
766
+ /** The executor model's streamed thoughts (thinking enabled + provider support). */
767
+ | {
768
+ type: 'step.reasoning-delta';
769
+ step: IPlanStep;
770
+ delta: string;
771
+ } | {
772
+ type: 'step.tool-call';
773
+ step: IPlanStep;
774
+ name: string;
775
+ input: unknown;
776
+ } | {
777
+ type: 'step.tool-result';
778
+ step: IPlanStep;
779
+ name: string;
780
+ output: unknown;
781
+ ok: boolean;
782
+ } | {
783
+ type: 'step.complete';
784
+ step: IPlanStep;
785
+ result: IStepResult;
833
786
  }
834
787
  /**
835
- * How a skill's text is introduced to the model: a lesson as the agent's own note, an MCP
836
- * server's skill as third-party knowledge; the host's skills as they are.
788
+ * `byUser`: the replanner ran because the user sent a message (`RunControl.send`), not because a
789
+ * step failed. `failed`: the replanner call itself failed (unparsable output, the provider
790
+ * down) and `mode: 'continue'` is the fallback, not the model's decision — the failure is the
791
+ * `error` event (phase 'replan') just before this one. `confidence`: `config.decisionModel`
792
+ * made this decision (the replanner was not called) - the probability it gave its choice.
837
793
  */
838
- declare const skillPreamble: (skill: Skill) => string;
839
- /** "- name: description" lines for the prompts. */
840
- declare const renderSkillIndex: (skills: Skill[]) => string;
841
- /** The full instructions of the active skills, within a total character budget. */
842
- declare const renderActiveSkills: (skills: Skill[]) => string;
843
- /** What `createSkillTools` needs of the MCP servers whose skills are on (`skills` on a server). */
844
- interface SkillToolsMcp {
845
- /**
846
- * The servers' skill sources (`collectMcpSkillSources`), fixed for the agent: they are named in
847
- * load_skill's description (run-stable), which then takes `{ server, uri }` too.
848
- */
849
- sources: readonly McpSkillSource[];
850
- /** The run's consent scope: a person is asked through the agent's approval gate. */
851
- scope?: McpSkillConsentScope;
852
- /** What the agent's snapshots of generated skills hold (a skill added by URI counts there). */
853
- memory?: McpSkillSnapshotMemory;
794
+ | {
795
+ type: 'replan.decision';
796
+ mode: ReplanMode;
797
+ reason: string;
798
+ byUser?: boolean;
799
+ failed?: true;
800
+ confidence?: number;
854
801
  }
855
802
  /**
856
- * The built-in `load_skill` / `read_skill_file` tools. `onLoad` fires when a
857
- * skill is loaded so the runner can keep it active for later steps. With `mcp`, an MCP server's
858
- * skill enters the context only once the person let it in (`acquireMcpSkill`), and a skill a
859
- * server names by URI can be loaded with `{ server, uri }`.
803
+ * `config.decisionModel` was asked a question: its answer was used (`accepted`), or the
804
+ * ordinary model call ran and `reason` says why.
860
805
  */
861
- declare const createSkillTools: (skills: Skill[], onLoad?: (skill: Skill) => void, mcp?: SkillToolsMcp) => ToolSet;
862
-
863
- declare const SAVE_SKILL_TOOL = "save_skill";
864
- declare const FORGET_SKILL_TOOL = "forget_skill";
865
- /** Where learned skills are kept. {@link MemorySkillStore} and {@link VfsSkillStore} are provided. */
866
- interface SkillStore {
867
- list(): Skill[] | Promise<Skill[]>;
868
- save(skill: Skill): void | Promise<void>;
869
- /** false when there was nothing to remove. */
870
- remove(name: string): boolean | Promise<boolean>;
806
+ | IDecisionEvent | {
807
+ type: 'final.text-delta';
808
+ delta: string;
871
809
  }
872
- interface LearningConfig {
873
- /** Where lessons are kept. Default: in memory, for the life of the agent (the open session). */
874
- store?: SkillStore;
875
- /** At most this many lessons (default 50). */
876
- maxSkills?: number;
877
- /** At most this many characters of instructions per lesson (default 6000). */
878
- maxSkillChars?: number;
879
- /** false keeps the tools but drops the executor guidance to write lessons down (default true). */
880
- nudge?: boolean;
810
+ /** The synthesizer's streamed thoughts. */
811
+ | {
812
+ type: 'final.reasoning-delta';
813
+ delta: string;
814
+ } | {
815
+ type: 'final';
816
+ text: string;
817
+ } | {
818
+ type: 'usage';
819
+ phase: UsagePhase;
820
+ usage: IUsage;
821
+ } | {
822
+ type: 'retry';
823
+ phase: Phase;
824
+ attempt: number;
825
+ error: string;
881
826
  }
882
- /** What a credential looks like, or undefined. */
883
- declare const findSecret: (text: string) => string | undefined;
884
- /** "My Trick_1" -> "my-trick-1"; undefined when nothing usable is left. */
885
- declare const normalizeSkillName: (raw: string) => string | undefined;
886
- /** Lives as long as the agent: the "open session". */
887
- declare class MemorySkillStore implements SkillStore {
888
- private readonly skills;
889
- list(): Skill[];
890
- save(skill: Skill): void;
891
- remove(name: string): boolean;
827
+ /** A run-level limit was reached; the run stops executing and writes its answer. */
828
+ | {
829
+ type: 'budget.exceeded';
830
+ kind: LimitKind;
831
+ tokens: number;
832
+ cap: number;
892
833
  }
893
- /**
894
- * `<dir>/<name>/SKILL.md` in the agent's virtual file system (IndexedDB, or memory): the user can
895
- * see and edit lessons in the files panel like any file. A sidecar `.origin.json` says where each
896
- * came from. Default dir `/skills`.
897
- */
898
- declare class VfsSkillStore implements SkillStore {
899
- private readonly vfs;
900
- private readonly dir;
901
- constructor(vfs: VirtualFileSystem, dir?: string);
902
- list(): Promise<Skill[]>;
903
- save(skill: Skill): Promise<void>;
904
- remove(name: string): Promise<boolean>;
834
+ /** Older context was summarised to fit the window. */
835
+ | {
836
+ type: 'context.compacted';
837
+ /** history = stored transcript; trace = the run's done steps; tool-results = stale results inside a step's tool loop. */
838
+ scope: 'history' | 'trace' | 'tool-results';
839
+ beforeTokens: number;
840
+ afterTokens: number;
905
841
  }
906
- interface Learning {
907
- /** The tools the model learns with (normal tools: gated, counted). */
908
- tools: AgentToolSet;
909
- /** The agent's own skills (not the host's). */
910
- learned: () => Skill[];
911
- /** Forget one of them. false when there is no such learned skill. */
912
- forget: (name: string, emit?: (event: {
913
- type: 'skill.forgotten';
914
- name: string;
915
- }) => void) => Promise<boolean>;
842
+ /** A skill's instructions entered the context (picked by the planner, or loaded by a tool call). */
843
+ /** `server`: the MCP server the skill came from (a skill served with `skills: true`). */
844
+ | {
845
+ type: 'skill.activated';
846
+ name: string;
847
+ by: 'plan' | 'tool';
848
+ server?: string;
916
849
  }
917
- interface SaveSkillInput {
850
+ /** The agent wrote a lesson down as a skill (`config.learning`). */
851
+ | {
852
+ type: 'skill.learned';
918
853
  name: string;
919
854
  description: string;
920
- instructions: string;
921
- sources?: string[];
855
+ /** true when it rewrote an earlier lesson of the same name. */
856
+ update: boolean;
857
+ chars: number;
858
+ /** What it consulted: the sources it named, then the pages web_fetch read in the run. */
859
+ sources: string[];
860
+ }
861
+ /** A lesson was deleted (by the agent's forget_skill, or the host's forgetSkill). */
862
+ | {
863
+ type: 'skill.forgotten';
864
+ name: string;
922
865
  }
923
866
  /**
924
- * Wires learning to the agent's LIVE skill list (`skills` is mutated in place, so every prompt
925
- * that renders the index sees a new lesson at once).
867
+ * A media tool (`config.media`) wrote a file to the virtual file system: `path` is where (read
868
+ * it with `vfs.readDataUrl(path)` to show the picture or play the audio), `mediaType` what its
869
+ * bytes are, `bytes` its size. The bytes themselves are never in an event.
926
870
  */
927
- declare const createLearning: (cfg: LearningConfig, skills: Skill[], warn: (message: string) => void) => Promise<Learning>;
928
-
929
- interface ISandboxConfig {
930
- timeoutMs?: number;
931
- memoryLimitBytes?: number;
932
- maxOutputChars?: number;
933
- maxCodeChars?: number;
934
- files?: boolean;
935
- }
936
- interface ISandboxLimits {
937
- timeoutMs: number;
938
- memoryLimitBytes: number;
939
- maxOutputChars: number;
940
- maxCodeChars: number;
871
+ | {
872
+ type: 'media.generated';
873
+ kind: 'image' | 'speech';
874
+ path: string;
875
+ mediaType: string;
876
+ bytes: number;
877
+ model: string;
878
+ step?: IPlanStep;
941
879
  }
942
- interface ISandboxError {
943
- name: string;
944
- message: string;
945
- stack?: string;
880
+ /**
881
+ * A file tool (`createFileTools`: `fs_write`) or the sandbox's `fs.writeFile` wrote a file to
882
+ * the virtual file system during the run: `path` is where, `mediaType` its MIME type, `bytes`
883
+ * its size. The content is never in an event - read it with `vfs.read(path)`. Emitted once per
884
+ * successful write; a write that was refused or failed emits nothing.
885
+ */
886
+ | {
887
+ type: 'file.written';
888
+ path: string;
889
+ mediaType: string;
890
+ bytes: number;
891
+ step?: IPlanStep;
946
892
  }
947
- interface ISandboxResult {
948
- ok: boolean;
949
- stdout: string;
950
- result?: unknown;
951
- error?: ISandboxError;
952
- truncated: boolean;
953
- durationMs: number;
893
+ /** A file tool (`fs_delete`) deleted a file that existed. */
894
+ | {
895
+ type: 'file.deleted';
896
+ path: string;
897
+ step?: IPlanStep;
954
898
  }
955
-
956
899
  /**
957
- * `config.sandbox`: the `run_js` tool - the model's code runs in QuickJS compiled to
958
- * WebAssembly (the optional peer `quickjs-emscripten`), never in the page's own JavaScript
959
- * engine. This module is loaded only when the sandbox is switched on.
960
- *
961
- * Where the guest runs:
962
- * - `worker` given: in a Web Worker that is terminated when the run is over or over time (the
963
- * hard stop). One worker per run. The worker module is `@dudko.dev/agent-web/sandbox-worker`.
964
- * - no `worker`: on the page's thread, stopped by the engine's interrupt handler only. A single
965
- * long native call in the guest then blocks the page until it returns - prefer a worker.
900
+ * An audio file was transcribed: one the user attached to the run ('attachment') or one the
901
+ * model asked about ('tool'). `text` is what the model reads of it (cleaned and capped).
966
902
  */
967
- /** A worker as the sandbox uses it: a real `Worker`, or a `MessagePort` in tests. */
968
- interface SandboxWorkerLike {
969
- postMessage(message: unknown): void;
970
- addEventListener(type: string, listener: (ev: any) => void): void;
971
- terminate?(): void;
903
+ | {
904
+ type: 'media.transcribed';
905
+ source: 'attachment' | 'tool';
906
+ name: string;
907
+ text: string;
908
+ language?: string;
909
+ durationInSeconds?: number;
910
+ model: string;
972
911
  }
973
- interface SandboxConfig extends ISandboxConfig {
912
+ /** find_tools activated more tools (large-catalogue search mode). */
913
+ | {
914
+ type: 'tools.discovered';
915
+ step?: IPlanStep;
916
+ query: string;
917
+ names: string[];
918
+ }
919
+ /** A tool call is waiting for the user's consent (see `toolApproval`). */
920
+ | {
921
+ type: 'tool.approval-requested';
922
+ id: string;
923
+ name: string;
924
+ input: unknown;
925
+ readOnly: boolean;
926
+ step?: IPlanStep;
927
+ /** Set when a helper the model started is asking (see `ToolApprovalRequest.subagent`). */
928
+ subagent?: {
929
+ id: string;
930
+ depth: number;
931
+ };
974
932
  /**
975
- * Builds a fresh Worker for one run, e.g.
976
- * `() => new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' })`
977
- * (Vite: `import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'`). Without it
978
- * the guest runs on the page's thread - isolated all the same, but only softly interruptible.
933
+ * Set when an MCP App asks (`Agent.approveAppToolCall`), not the model: the app's server,
934
+ * the tool's own name there and the app's `ui://` resource (see `ToolApprovalRequest.app`).
979
935
  */
980
- worker?: () => SandboxWorkerLike;
936
+ app?: ToolApprovalApp;
937
+ /** See `ToolApprovalRequest.mcpSkills`. */
938
+ mcpSkills?: string[];
981
939
  /**
982
- * Loads the engine for the page-thread fallback, e.g. `() => import('quickjs-emscripten')`, so
983
- * that your bundler resolves it. Default: a runtime `import('quickjs-emscripten')` (Node, or a
984
- * page with an import map). Not used when `worker` is given.
940
+ * Set when the request is about an MCP server's skill about to enter the model's context,
941
+ * not a tool call (see `ToolApprovalRequest.skill`): the server's words, as plain text.
985
942
  */
986
- engine?: () => Promise<unknown>;
943
+ skill?: McpSkillConsentView;
987
944
  }
988
-
989
- declare const SPAWN_SUBAGENT_TOOL = "spawn_subagent";
990
- type SubagentDefaultTools = 'read-only' | 'all';
991
- interface IDynamicSubagentsConfig {
992
- maxDepth?: number;
993
- maxChildren?: number;
994
- maxConcurrent?: number;
995
- budgetShare?: number;
996
- minTokens?: number;
997
- timeoutMs?: number;
998
- defaultTools?: SubagentDefaultTools;
945
+ /** A consent decision: from the user, or `automatic` (policy denial). */
946
+ | {
947
+ type: 'tool.approval-resolved';
948
+ id: string;
949
+ name: string;
950
+ approved: boolean;
951
+ reason?: string;
952
+ automatic: boolean;
999
953
  }
1000
- interface ISubagentsConfig {
1001
- dynamic?: boolean | IDynamicSubagentsConfig;
954
+ /**
955
+ * An MCP server asked the user for input during a tool call (the connection's `onElicitation`
956
+ * is being called). `message`, `requestedSchema` and `url` are the SERVER's text: cleaned and
957
+ * capped, for a UI to show - never instructions.
958
+ */
959
+ | {
960
+ type: 'mcp.elicitation-requested';
961
+ id: string;
962
+ server: string;
963
+ /** The tool call that asks: the tool's name as the model called it. */
964
+ tool: string;
965
+ mode: 'form' | 'url';
966
+ message: string;
967
+ requestedSchema?: McpElicitationSchema;
968
+ url?: string;
969
+ step?: IPlanStep;
970
+ /** Set when a helper (a subagent) is the one whose call asks. */
971
+ subagent?: {
972
+ id: string;
973
+ depth: number;
974
+ };
975
+ }
976
+ /**
977
+ * The question was answered. Never carries a value the user entered: `fields` are the NAMES
978
+ * of the fields an accepted form was answered with. `automatic`: nobody decided (a guard, a
979
+ * cap, a timeout, a failed handler, a stopped run) - `reason` says which, the tool call
980
+ * fails, and no `mcp.elicitation-requested` may have preceded it.
981
+ */
982
+ | {
983
+ type: 'mcp.elicitation-answered';
984
+ id: string;
985
+ server: string;
986
+ tool: string;
987
+ action: 'accept' | 'decline' | 'cancel';
988
+ automatic: boolean;
989
+ reason?: McpElicitationReason;
990
+ fields?: string[];
991
+ }
992
+ /**
993
+ * A tool that declares an MCP App (`_meta.ui.resourceUri`) returned a result, on a connection
994
+ * made with `apps: true` (`./mcp`): a UI can show the app next to the call. `tool` is the name
995
+ * the model called, `toolName` the server's own; `input` the call's arguments; `result` what
996
+ * the app is given (`content`, `structuredContent`, `isError`, `_meta`), absent when it was
997
+ * larger than `MCP_APP_MAX_RESULT_CHARS`. The app's HTML is never in an event: read it with
998
+ * the connection's `apps.readUiResource(server, resourceUri)`.
999
+ */
1000
+ | {
1001
+ type: 'mcp.app';
1002
+ id: string;
1003
+ server: string;
1004
+ tool: string;
1005
+ toolName: string;
1006
+ resourceUri: string;
1007
+ input: Record<string, unknown>;
1008
+ result?: McpAppToolResult;
1009
+ step?: IPlanStep;
1010
+ }
1011
+ /**
1012
+ * `profile` is set when the parent chose one of the subagent's named profiles for this call.
1013
+ * The tree: `parentId` is the id of the subagent that made the call, or the `runId` of the run
1014
+ * when the run itself made it; `depth` is 1 for the run's own subagents, 2 for theirs, ...
1015
+ * `dynamic` marks a helper the model started with `spawn_subagent` (`subagents.dynamic`):
1016
+ * `role` is what the model wrote for it, `tools` the tool names it was given.
1017
+ */
1018
+ | {
1019
+ type: 'subagent.start';
1020
+ id: string;
1021
+ name: string;
1022
+ task: string;
1023
+ profile?: string;
1024
+ parentId?: string;
1025
+ depth?: number;
1026
+ dynamic?: true;
1027
+ role?: string;
1028
+ tools?: string[];
1002
1029
  }
1003
- interface IResolvedDynamicSubagents {
1004
- maxDepth: number;
1005
- maxChildren: number;
1006
- maxConcurrent: number;
1007
- budgetShare: number;
1008
- minTokens: number;
1009
- timeoutMs: number;
1010
- defaultTools: SubagentDefaultTools;
1030
+ /** An event of a running subagent, forwarded verbatim. */
1031
+ | {
1032
+ type: 'subagent.event';
1033
+ id: string;
1034
+ name: string;
1035
+ event: AgentEvent;
1036
+ } | {
1037
+ type: 'subagent.complete';
1038
+ id: string;
1039
+ name: string;
1040
+ text: string;
1041
+ usage: IUsage;
1011
1042
  }
1012
- declare const SUBAGENT_DEFAULTS: IResolvedDynamicSubagents;
1013
- declare const SUBAGENT_MAX_DEPTH_LIMIT = 4;
1014
1043
  /**
1015
- * The effective settings, or undefined when the feature is off (nothing is mounted, nothing is
1016
- * added to a prompt). A bad value is a configuration error, thrown when the agent is created.
1044
+ * `stopped` is set when the user stopped this subagent (`RunControl.stopSubagent`), as opposed
1045
+ * to it failing. `usage`: what a dynamic helper had spent when it failed (already charged to
1046
+ * the parent).
1017
1047
  */
1018
- declare const resolveDynamicSubagents: (subagents: ISubagentsConfig | undefined) => IResolvedDynamicSubagents | undefined;
1048
+ | {
1049
+ type: 'subagent.error';
1050
+ id: string;
1051
+ name: string;
1052
+ error: string;
1053
+ stopped?: boolean;
1054
+ usage?: IUsage;
1055
+ }
1019
1056
  /**
1020
- * A spawn that was refused: the model reads the message as the tool's error and can correct the
1021
- * call or carry on without a helper.
1057
+ * A request of the `web_fetch` tool, or of `web_search` to its search API, allowed or refused
1058
+ * by the egress policy. `url` is origin and path only (a query string can carry a secret).
1022
1059
  */
1023
- declare class SubagentSpawnError extends Error {
1024
- constructor(message: string);
1025
- toJSON(): string;
1060
+ | {
1061
+ type: 'egress.request';
1062
+ url: string;
1063
+ allowed: boolean;
1064
+ status?: number;
1065
+ reason?: string;
1026
1066
  }
1027
- declare const SPAWN_INPUT_SCHEMA: {
1028
- readonly type: "object";
1029
- readonly properties: {
1030
- readonly task: {
1031
- readonly type: "string";
1032
- 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.";
1033
- };
1034
- readonly role: {
1035
- readonly type: "string";
1036
- 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\").";
1037
- };
1038
- readonly tools: {
1039
- readonly type: "array";
1040
- readonly items: {
1041
- readonly type: "string";
1042
- };
1043
- 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.";
1044
- };
1045
- };
1046
- readonly required: readonly ["task"];
1047
- readonly additionalProperties: false;
1048
- };
1049
- interface ISpawnTokenLimits {
1050
- maxInputTokens?: number;
1051
- maxOutputTokens?: number;
1052
- maxReasoningTokens?: number;
1053
- maxTotalTokens?: number;
1067
+ /** A message sent with `RunControl.send` is waiting for the next boundary. */
1068
+ /** `origin: 'another-tab'`: another tab of the site sent it (the session relay), not this host. */
1069
+ | {
1070
+ type: 'message.queued';
1071
+ id: string;
1072
+ text: string;
1073
+ origin?: 'another-tab';
1054
1074
  }
1055
- interface ISpawnUsage {
1056
- inputTokens: number;
1057
- outputTokens: number;
1058
- totalTokens: number;
1059
- reasoningTokens?: number;
1075
+ /**
1076
+ * The message reached the model. `round` = between tool-calling rounds inside a step, so
1077
+ * the rest of that step can act on it (the replanner weighs it at the end of the step);
1078
+ * `step` = at a step boundary, where it forces the replanner to look at the plan;
1079
+ * `final` = just before the answer is written.
1080
+ */
1081
+ | {
1082
+ type: 'message.delivered';
1083
+ id: string;
1084
+ text: string;
1085
+ at: 'round' | 'step' | 'final';
1086
+ origin?: 'another-tab';
1060
1087
  }
1061
- interface ISpawnReservation {
1062
- limits: ISpawnTokenLimits;
1063
- maxToolCalls?: number;
1064
- usage: () => ISpawnUsage;
1065
- toolCalls: () => number;
1088
+ /**
1089
+ * `sessionLock: 'wait'`: the run's session is running already - in another tab of the origin
1090
+ * (`another-tab`), or in another run of this tab (`this-tab`) - and this run waits for it. It
1091
+ * has not started: nothing of the session was read. Comes before `run.start`, without `seq` /
1092
+ * `attempt` (the run is not a run yet). Stopping the run ends the wait (`stopped`, no
1093
+ * `run.start`).
1094
+ */
1095
+ | {
1096
+ type: 'session.busy';
1097
+ sessionId: string;
1098
+ heldBy: SessionHolder;
1099
+ }
1100
+ /** The wait is over: the run has the session and starts (`waitedMs` it waited). Unnumbered too. */
1101
+ | {
1102
+ type: 'session.acquired';
1103
+ sessionId: string;
1104
+ waitedMs: number;
1105
+ } | {
1106
+ type: 'stopped';
1107
+ } | {
1108
+ type: 'error';
1109
+ phase: Phase | 'run';
1110
+ error: string;
1066
1111
  }
1112
+ /** A pipeline's own events (`createPipeline`): the run, each node visit, each edge decision. */
1113
+ | PipelineEvent;
1067
1114
  /**
1068
- * A child's event on its way up through the subagent `parentId` (the `subagent.event` envelope is
1069
- * added by the caller). A `subagent.start` is emitted with `depth: 1` and the id of the run that
1070
- * made the call as `parentId`; each subagent it passes through on the way up adds one level, and
1071
- * the first one - its real parent - puts its own id in `parentId`. So at the top of the stream
1072
- * every start carries its true depth and parent, whatever mix of static and dynamic subagents,
1073
- * threads and workers is below.
1115
+ * `seq` / `attempt` order a run's events, across crashes and resumes: `attempt` is 1 for a fresh
1116
+ * run and one more for every resume, `seq` counts the events of one attempt from 1. Ordered by
1117
+ * (attempt, seq) the events of a run are a total order. Delivery is at-least-once: the step a
1118
+ * crash interrupted runs again under the next attempt, so its events come again with that
1119
+ * attempt's numbers. A `subagent.event` envelope is numbered in the parent run; the child event
1120
+ * inside keeps its own numbers. Events outside a run (a pipeline's own `pipeline.*` events,
1121
+ * `approveAppToolCall`, `sampleForApp`, and what a run says while it waits for its session -
1122
+ * `session.busy`, `session.acquired`, a `stopped` that ended the wait) carry none.
1123
+ *
1124
+ * `nodeId` / `visit` are set on the events a pipeline forwards from a node's agent (and on the
1125
+ * `pipeline.node.*` events themselves).
1074
1126
  */
1075
- declare const adoptSubagentEvent: <E extends {
1076
- type: string;
1077
- }>(event: E, parentId: string) => E;
1127
+ type AgentEvent = AgentEventBody & {
1128
+ seq?: number;
1129
+ attempt?: number;
1130
+ nodeId?: string;
1131
+ visit?: number;
1132
+ };
1133
+ type AgentEventHandler = (event: AgentEvent) => void;
1078
1134
 
1079
- 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';
1080
- declare class EgressError extends Error {
1081
- readonly code: EgressErrorCode;
1082
- constructor(code: EgressErrorCode, message: string);
1083
- toJSON(): string;
1135
+ /**
1136
+ * Steering a run that is already going.
1137
+ *
1138
+ * `run()` takes one goal and returns when the run is over, so a host that wants to
1139
+ * say something mid-run — "actually use the staging database" — or stop one
1140
+ * subagent out of several has nothing to call. A `RunControl` is the handle: create
1141
+ * one, pass it as `run(goal, { control })`, and use it from anywhere while the run
1142
+ * is in flight.
1143
+ *
1144
+ * A message is not interrupt. The run never cuts a tool call short (it may be a
1145
+ * write): the message is held until the next boundary — the next tool-calling round
1146
+ * inside a step, or the end of the step — and is then shown to the model. At a step
1147
+ * boundary it also forces the replanner to look at the plan again, because a plan
1148
+ * made before the user spoke may no longer be the right one.
1149
+ */
1150
+ /** One running subagent, as the host sees it. */
1151
+ interface SubagentInfo {
1152
+ id: string;
1153
+ /** The subagent tool's `name`. */
1154
+ name: string;
1155
+ task: string;
1156
+ /** The profile the parent chose for this call, when it chose one. */
1157
+ profile?: string;
1158
+ startedAt: number;
1159
+ /** The subagent that started it; absent when the run itself did. */
1160
+ parentId?: string;
1161
+ /** 1 for the run's own subagents, 2 for theirs, ... (set for helpers the model started). */
1162
+ depth?: number;
1163
+ /** Set for a helper the model started with spawn_subagent: the role it was given, if any. */
1164
+ dynamic?: true;
1165
+ role?: string;
1084
1166
  }
1085
- interface IEgressPolicy {
1086
- /** Hosts the agent may reach; empty/absent = any host that passes the other checks. "example.com" (that host only), "*.example.com" (its subdomains, not the apex), an IP or a CIDR for IP-literal URLs. */
1087
- allow?: string[];
1088
- /** Always refused; wins over `allow`. Same patterns. */
1089
- deny?: string[];
1090
- /** Allow IP literals and internal-looking names in private ranges (default false). Metadata endpoints stay refused. */
1091
- allowPrivateNetwork?: boolean;
1092
- /** Default ['https']. */
1093
- protocols?: ('https' | 'http')[];
1094
- /** Default [443] (and 80 once 'http' is allowed). */
1095
- ports?: number[];
1096
- /** Default ['GET']. */
1097
- methods?: string[];
1098
- /** Follow redirects, judging only the final URL after the fact (default false: a redirect fails the request). */
1099
- followRedirects?: boolean;
1100
- /** Cap on the body, in bytes. Default 2_000_000. */
1101
- maxResponseBytes?: number;
1102
- /** Whole request, in ms. Default 15_000. */
1103
- timeoutMs?: number;
1104
- /** The fetch to use (default `globalThis.fetch`). Point it at a gateway to get server-side protection. */
1105
- fetch?: typeof fetch;
1167
+ interface RunControl {
1168
+ /**
1169
+ * Queue a message for the run. `false` when there is nothing to deliver it to — the text
1170
+ * is empty, or the run has already finished (send it as a new run instead).
1171
+ *
1172
+ * Accepted does not mean delivered: a message that arrives after the last boundary
1173
+ * (while the answer is being written) comes back in `RunResult.undelivered`, so the
1174
+ * host can send it next.
1175
+ */
1176
+ send(text: string): boolean;
1177
+ /**
1178
+ * Messages sent and not yet delivered. Once the run is over: the ones it never got to show
1179
+ * the model (the same list as `RunResult.undelivered`, which a run that threw cannot return).
1180
+ */
1181
+ pending(): string[];
1182
+ /** The subagents running under this run right now (a snapshot; `subagent.*` events are the stream). */
1183
+ subagents(): SubagentInfo[];
1184
+ /**
1185
+ * Stop ONE running subagent. Its delegation fails with a message the parent model can
1186
+ * route around, and the run carries on — unlike aborting the run, which stops everything.
1187
+ * `false` when no subagent with that id is running.
1188
+ */
1189
+ stopSubagent(id: string): boolean;
1106
1190
  }
1107
- interface IResolvedEgressPolicy {
1108
- allow: string[];
1109
- deny: string[];
1110
- allowPrivateNetwork: boolean;
1111
- protocols: ('https' | 'http')[];
1112
- ports: number[];
1113
- methods: string[];
1114
- followRedirects: boolean;
1115
- maxResponseBytes: number;
1116
- timeoutMs: number;
1117
- fetch: typeof fetch;
1191
+ interface QueuedMessage {
1192
+ id: string;
1193
+ text: string;
1194
+ /** Set when another tab of the site sent it (the session relay), not this tab's host. */
1195
+ origin?: 'another-tab';
1196
+ }
1197
+ /** What the runner and the subagent tool use; deliberately not part of the public surface. */
1198
+ interface RunControlPort {
1199
+ /** The run starts reading: from now on `send` announces itself. */
1200
+ attach(emit: (event: AgentEvent) => void): void;
1201
+ /**
1202
+ * The run is over: whatever is still queued is returned, for the host to send as a
1203
+ * follow-up. It stays readable through `pending()` until the control serves another run.
1204
+ */
1205
+ detach(): string[];
1206
+ /** Take every queued message, oldest first. */
1207
+ drain(): QueuedMessage[];
1208
+ /** A subagent started under this run; returns what unregisters it. */
1209
+ registerSubagent(info: SubagentInfo, stop: () => void): () => void;
1210
+ /** `send`, for a message another tab sent (the session relay): marked as such on its events. */
1211
+ sendFrom(text: string, origin: 'another-tab'): boolean;
1212
+ }
1213
+ declare const createRunControl: () => RunControl;
1214
+
1215
+ /**
1216
+ * One session, one runner - and a run that other tabs can watch and steer.
1217
+ *
1218
+ * A run of a session whose memory the origin's tabs share (`IndexedDBStore`) holds a Web Lock
1219
+ * named after the database and the session for its whole duration: a second run of the same
1220
+ * session - in another tab, or in this one - waits for it (`sessionLock: 'wait'`), or fails at
1221
+ * once (`'fail'`). The browser releases a lock when its tab closes or crashes.
1222
+ *
1223
+ * The tab that holds the lock RELAYS the run on a channel named the same way: its events
1224
+ * (clipped, see `slimEvent`), its state (running / idle), and a replay of what happened so far for
1225
+ * a tab that joins late. It answers two requests from the other tabs: a message for the run
1226
+ * (through the run's `RunControl`) and stop. Nothing else crosses: a tool approval is answered
1227
+ * only in the tab that runs the tool (docs/security.md says why). `watchSession` is the other
1228
+ * tabs' end.
1229
+ *
1230
+ * Every message is untrusted input - any page of the origin can post on the channel: the shape is
1231
+ * checked, sizes are capped, an unknown type is ignored.
1232
+ */
1233
+ type SessionLockMode = 'wait' | 'fail' | 'off';
1234
+ declare const SESSION_LOCK_MODES: readonly SessionLockMode[];
1235
+ /** Who holds a session's lock: another tab of the origin, or another run in this tab. */
1236
+ type SessionHolder = 'another-tab' | 'this-tab';
1237
+ /** `sessionLock: 'fail'`: the session is already running. Nothing of the run happened. */
1238
+ declare class SessionBusyError extends Error {
1239
+ readonly sessionId: string;
1240
+ readonly heldBy: SessionHolder;
1241
+ constructor(sessionId: string, heldBy: SessionHolder);
1242
+ }
1243
+ /** A string of a relayed event longer than this is clipped. */
1244
+ declare const RELAY_MAX_STRING = 8000;
1245
+ /** A message sent from another tab is refused above this length. */
1246
+ declare const RELAY_MAX_SEND_CHARS = 32000;
1247
+ /** At most this many messages from other tabs per run. */
1248
+ declare const RELAY_MAX_SENDS = 50;
1249
+ /**
1250
+ * Full replays answered per second; past that a watcher gets an empty one and follows from now
1251
+ * (a flood of `hello`s cannot make the running tab copy its buffer over and over).
1252
+ */
1253
+ declare const RELAY_MAX_REPLAYS_PER_SECOND = 8;
1254
+ /** A session as another tab sees it. */
1255
+ interface SessionRunState {
1256
+ /** A run of the session is going in another tab. */
1257
+ running: boolean;
1258
+ /** The run being watched (or the last one seen). */
1259
+ runId?: string;
1260
+ /**
1261
+ * How the last run seen ended: `done`, `stopped`, or `gone` - its tab closed or crashed before
1262
+ * it said it was over (the browser freed the session's lock).
1263
+ */
1264
+ ended?: 'done' | 'stopped' | 'gone';
1265
+ /** The replay this tab joined with left out older events (a long run). */
1266
+ truncated?: boolean;
1118
1267
  }
1119
- declare const resolveEgressPolicy: (policy?: IEgressPolicy) => IResolvedEgressPolicy;
1120
- type AddressClass = 'public' | 'private' | 'never';
1121
- declare const classifyAddress: (address: string) => AddressClass;
1122
- declare const hostMatches: (host: string, pattern: string) => boolean;
1123
- declare const checkEgressUrl: (url: URL, policy: IResolvedEgressPolicy, method?: string) => void;
1124
- declare const htmlToText: (html: string) => {
1125
- title?: string;
1126
- text: string;
1127
- };
1128
- type GuardedFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
1129
- /** A `fetch` bound to a policy. */
1130
- declare const createGuardedFetch: (policy?: IEgressPolicy) => GuardedFetch;
1131
- declare const WEB_FETCH_TOOL = "web_fetch";
1132
- interface IWebFetchOptions {
1133
- policy?: IEgressPolicy;
1134
- fetch?: GuardedFetch;
1268
+ interface WatchSessionOptions {
1269
+ /** The session to watch: the agent's `sessionId` (a chat id). */
1270
+ sessionId: string;
1271
+ /** The database of the session's memory (`IndexedDBStore`'s `dbName`; default `'agent-web'`). */
1272
+ dbName?: string;
1273
+ /**
1274
+ * The run's events as they happen in the other tab, from its `run.start` (a tab that joins
1275
+ * late gets what happened so far first). Clipped: strings to `RELAY_MAX_STRING` characters.
1276
+ */
1277
+ onEvent?: (event: AgentEvent) => void;
1278
+ /** Called whenever `state` changes. */
1279
+ onState?: (state: SessionRunState) => void;
1280
+ }
1281
+ interface SessionWatch {
1282
+ readonly state: SessionRunState;
1283
+ /**
1284
+ * Say something to the run in the other tab: it reaches the model at the run's next boundary,
1285
+ * as `RunControl.send` does there. Resolves true when that tab took it; false when nothing
1286
+ * runs, the run has no `control`, the text is empty or over `RELAY_MAX_SEND_CHARS`, the run
1287
+ * already took `RELAY_MAX_SENDS`, or no answer came.
1288
+ */
1289
+ send(text: string): Promise<boolean>;
1290
+ /** Stop the run in the other tab. Resolves true when that tab took the request. */
1291
+ stop(): Promise<boolean>;
1292
+ /** Stop watching. */
1293
+ close(): void;
1135
1294
  }
1136
1295
  /**
1137
- * `web_fetch({ url })`: read one page or API response. Every request goes through the egress
1138
- * policy; a refusal comes back as a tool error that says why. Read-only for the consent gate
1139
- * only when the policy names the hosts it may reach - an open GET is a channel to leak data
1140
- * through the URL, so it asks like a write.
1296
+ * Watch a session that may be running in ANOTHER tab of the origin: its run's events and state,
1297
+ * and a way to send it a message or stop it. A run in this tab is not seen here - its own
1298
+ * `onEvent` has it. Needs BroadcastChannel (without it the state stays idle and `send` / `stop`
1299
+ * resolve false); a tab that closes mid-run is noticed through the session's lock (Web Locks).
1141
1300
  */
1142
- declare const createWebFetchTool: (options?: IWebFetchOptions) => AgentTool;
1143
- /** The tools `config.egress` turns on (none when it is off). */
1144
- declare const createEgressTools: (egress: boolean | IEgressPolicy | undefined) => AgentToolSet | undefined;
1301
+ declare const watchSession: (options: WatchSessionOptions) => SessionWatch;
1145
1302
 
1146
1303
  /**
1147
- * What the `web_search` tools of the two agent packages share: the result shape and its caps, how
1148
- * a search engine's answer is cleaned before a model reads it, and the one built-in provider
1149
- * (Google Search through Gemini grounding) as a pure request builder and response parser (one
1150
- * HTTP call). Pure, no imports, no clock: the request itself is made by each package's own safe
1151
- * fetch.
1304
+ * Leveled logging for the agent. The host passes a console-like sink and a
1305
+ * level; everything below the level is a no-op. Default: 'warn' onto the
1306
+ * global console — silent in normal operation, but salvage fallbacks, empty
1307
+ * plans, degraded tool modes and failed tool calls stay visible.
1152
1308
  *
1153
- * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/web-search-shared.ts`) and
1154
- * `@dudko.dev/agent-web` (`src/tools/web-search-shared.ts`): change both. The Node package's
1155
- * `tests/web-search-shared.test.ts` compares the two files and tests every cap and guard here.
1309
+ * Set `logLevel: 'debug'` to see every phase's raw model output, parsed
1310
+ * results and tool dispatches — the first thing to reach for when the agent
1311
+ * "says it did something but nothing happened".
1156
1312
  */
1157
- declare const WEB_SEARCH_TOOL = "web_search";
1158
- /** Results returned when neither the host nor the model says how many. */
1159
- declare const SEARCH_DEFAULT_MAX_RESULTS = 5;
1160
- /** The most results one call returns, whatever the host or the model asks for. */
1161
- declare const SEARCH_MAX_RESULTS = 10;
1162
- /** The longest query sent to a search engine, in characters. */
1163
- declare const SEARCH_MAX_QUERY_CHARS = 400;
1164
- /** The most of a result's title a model sees. */
1165
- declare const SEARCH_MAX_TITLE_CHARS = 200;
1166
- /** A result whose URL is longer than this is dropped (a cut URL is another URL). */
1167
- declare const SEARCH_MAX_URL_CHARS = 2000;
1168
- /** The most of a result's snippet a model sees. */
1169
- declare const SEARCH_MAX_SNIPPET_CHARS = 500;
1170
- /** The most all results of one call take together (titles, URLs, snippets, dates). */
1171
- declare const SEARCH_MAX_TOTAL_CHARS = 6000;
1172
- /** One search result, as the model sees it. Third-party text: data, never instructions. */
1173
- interface ISearchResult {
1174
- title: string;
1175
- url: string;
1176
- snippet: string;
1177
- /** When the page was published or last changed, as the engine reported it. */
1178
- date?: string;
1313
+ type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug';
1314
+ /** Console-compatible sink (pass `console`, or your own collector). */
1315
+ interface AgentLoggerSink {
1316
+ error(...args: unknown[]): void;
1317
+ warn(...args: unknown[]): void;
1318
+ info(...args: unknown[]): void;
1319
+ debug(...args: unknown[]): void;
1179
1320
  }
1180
- type SearchFreshness = 'day' | 'week' | 'month' | 'year';
1181
- /** What a search engine function is called with, next to the query. */
1182
- interface ISearchOptions {
1183
- /** How many results are wanted (1..SEARCH_MAX_RESULTS); more are cut. */
1184
- maxResults: number;
1185
- /** Only results from the last day / week / month / year, when the model asked for it. */
1186
- freshness?: SearchFreshness;
1187
- /** Aborted when the run is stopped. */
1188
- signal?: AbortSignal;
1321
+ interface AgentLogger extends AgentLoggerSink {
1322
+ readonly level: LogLevel;
1189
1323
  }
1324
+ declare const createLogger: (level?: LogLevel, sink?: AgentLoggerSink) => AgentLogger;
1325
+
1190
1326
  /**
1191
- * A search engine of the host's own: any function that answers a query with results. What it
1192
- * returns is treated like a built-in adapter's answer - cleaned, capped and filtered.
1327
+ * Providers the browser registry can resolve from a spec. This is deliberately
1328
+ * a browser-safe subset of the Node sibling's list: Amazon Bedrock (SigV4
1329
+ * signing), Google Vertex (ADC via google-auth-library) and Cloudflare
1330
+ * (Worker bindings / process.env) are Node-only and omitted; Azure folds into
1331
+ * `openai-compatible`. `web-llm` is the local WebGPU pseudo-provider (no API
1332
+ * key). Any other runtime — Chrome/Edge built-in AI, a custom LanguageModel —
1333
+ * is passed to the agent directly and never touches this registry.
1193
1334
  */
1194
- type SearchEngine = (query: string, options: ISearchOptions) => Promise<ISearchResult[]>;
1335
+ type ProviderType = 'openai' | 'anthropic' | 'google' | 'openai-compatible' | 'xai' | 'deepseek' | 'gateway' | 'web-llm';
1336
+ /** A model described by provider + id, resolved through the registry (+ vault). */
1337
+ interface ProviderModelSpec {
1338
+ providerType: ProviderType;
1339
+ /** Model id, e.g. "gpt-4o-mini", "claude-haiku-4-5", "Llama-3.2-3B-Instruct-q4f16_1-MLC". */
1340
+ model: string;
1341
+ /** Provider endpoint override. Required for `openai-compatible`; a proxy URL for the rest. */
1342
+ baseURL?: string;
1343
+ /** Id under which the API key is stored in the CredentialStore / vault. Preferred. */
1344
+ credentialRef?: string;
1345
+ /**
1346
+ * Dev-only inline API key. Prefer `credentialRef` so the key lives encrypted
1347
+ * in the vault, not on a long-lived config object. Using this logs a warning.
1348
+ */
1349
+ apiKey?: string;
1350
+ /** Extra request headers merged into the provider factory (e.g. a proxy auth header). */
1351
+ headers?: Record<string, string>;
1352
+ /** Escape hatch spread into the SDK factory after baseURL / apiKey / headers. */
1353
+ providerOptions?: Record<string, unknown>;
1354
+ }
1195
1355
  /**
1196
- * The built-in provider. One: Google Search through the Gemini API's grounding (`google_search`),
1197
- * which needs a Gemini (Google AI Studio) key and nothing else. Any other search API is the
1198
- * host's `engine` function.
1356
+ * A per-stage override that inherits the base provider + credentials and
1357
+ * changes only the fields it sets (typically just `model`). Distinguished from
1358
+ * a full ProviderModelSpec by the absence of `providerType`.
1199
1359
  */
1200
- type SearchProvider = 'google';
1201
- declare const SEARCH_PROVIDERS: readonly SearchProvider[];
1202
- /** Where the provider's API lives (a `baseURL` of the host - a gateway - replaces it). */
1203
- declare const SEARCH_API_BASE_URL: Record<SearchProvider, string>;
1360
+ interface StageOverride {
1361
+ model?: string;
1362
+ baseURL?: string;
1363
+ credentialRef?: string;
1364
+ apiKey?: string;
1365
+ headers?: Record<string, string>;
1366
+ providerOptions?: Record<string, unknown>;
1367
+ }
1368
+ /** What a caller hands us for a model: a ready AI SDK model, or a spec to resolve. */
1369
+ type ModelInput = LanguageModel | ProviderModelSpec;
1370
+ /** A model input, plus the partial-override form usable for per-stage layering. */
1371
+ type StageInput = ModelInput | StageOverride;
1372
+ /** Outcome of resolving one stage: either a ready model, or a fully-resolved spec. */
1373
+ type ResolvedStage = {
1374
+ type: 'direct';
1375
+ model: LanguageModel;
1376
+ } | {
1377
+ type: 'spec';
1378
+ spec: ProviderModelSpec;
1379
+ };
1380
+ /** True for a ready AI SDK model: a gateway model-id string or a LanguageModelV* object. */
1381
+ declare const isDirectModel: (m: unknown) => m is LanguageModel;
1382
+ /** True for a full provider spec (carries the `providerType` discriminator). */
1383
+ declare const isProviderSpec: (m: unknown) => m is ProviderModelSpec;
1384
+
1204
1385
  /**
1205
- * The model the grounding call is made with when the host names none: the cheapest one that
1206
- * answered a free-tier key with grounding on the day it was measured (2026-11-26).
1386
+ * Default phase prompts. Each builder returns `{ system, prompt }` strings.
1387
+ * Because the agent runs in two tool-modes, the builders switch on `ctx.mode`:
1388
+ *
1389
+ * - `native` — the model calls tools / emits schema-constrained JSON via the
1390
+ * AI SDK, so the prompts describe the task and let the SDK enforce structure.
1391
+ * - `prompted` — weak local models can't do that reliably, so the prompts spell
1392
+ * out an exact JSON shape and (for the executor) include a tool catalogue;
1393
+ * the output is salvaged by parse.ts.
1394
+ *
1395
+ * Layout matters for prompt caching: the SYSTEM part holds only what is stable
1396
+ * for a whole run (role, skills, the planner's tool catalogue), the user
1397
+ * prompt holds everything that changes (goal, state, history, progress), so a
1398
+ * provider's prefix cache can reuse the system part across calls.
1399
+ *
1400
+ * The agent is autonomous by design: it plans tool use for anything the tools
1401
+ * can do or look up, never asks the user for confirmation (consent is the
1402
+ * host's `toolApproval` policy), and states assumptions instead of asking.
1403
+ *
1404
+ * Override any builder via `BrowserAgentConfig.prompts`.
1207
1405
  */
1208
- declare const SEARCH_GOOGLE_DEFAULT_MODEL = "gemini-2.5-flash-lite";
1209
- /** The most of the grounding model's answer a model sees as `summary`. */
1210
- declare const SEARCH_MAX_SUMMARY_CHARS = 1000;
1211
- /** Said in every result of the google provider: what its URLs and its text are. */
1212
- declare const SEARCH_GOOGLE_NOTE: string;
1213
- /** One HTTP call to a search API. The key, if any, is in `headers` only - never in the URL. */
1214
- interface ISearchRequest {
1215
- url: string;
1216
- method: 'GET' | 'POST';
1217
- headers: Record<string, string>;
1218
- body?: string;
1406
+ type ToolCallMode = 'native' | 'prompted';
1407
+ interface PromptParts {
1408
+ system: string;
1409
+ prompt: string;
1219
1410
  }
1220
- interface ISearchRequestInput {
1221
- provider: SearchProvider;
1222
- query: string;
1223
- maxResults: number;
1224
- freshness?: SearchFreshness;
1225
- apiKey?: string;
1226
- baseURL?: string;
1227
- /** The Gemini model that makes the grounding call (default SEARCH_GOOGLE_DEFAULT_MODEL). */
1228
- model?: string;
1229
- /** The current time in ms, for `freshness` (this file reads no clock). */
1230
- now?: number;
1411
+ interface PlannerPromptContext {
1412
+ goal: string;
1413
+ state?: string;
1414
+ toolCatalog: string;
1415
+ mode: ToolCallMode;
1416
+ /** Prior session messages (oldest first), for resolving references to earlier turns. */
1417
+ history?: {
1418
+ role: string;
1419
+ content: string;
1420
+ }[];
1421
+ /** "- name: description" index of the configured skills, when any. */
1422
+ skills?: string;
1423
+ /** The catalogue is condensed and the executor can search the rest (large catalogues). */
1424
+ searchMode?: boolean;
1425
+ /** Set when `config.sandbox` is on: when to plan a `run_js` step. */
1426
+ sandbox?: string;
1427
+ /** Set while `spawn_subagent` is callable (`subagents.dynamic`): when a helper is worth a step. */
1428
+ subagents?: string;
1429
+ /** Set when `config.executorTiers` is on: the planner rates every step's complexity. */
1430
+ tiers?: boolean;
1431
+ }
1432
+ interface ExecutorPromptContext {
1433
+ goal: string;
1434
+ state?: string;
1435
+ step: string;
1436
+ index: number;
1437
+ total: number;
1438
+ toolCatalog: string;
1439
+ /** Earlier steps of this run, each with its outcome and key data. */
1440
+ done: string[];
1441
+ mode: ToolCallMode;
1442
+ /** "- name: description" index of the configured skills, when any. */
1443
+ skills?: string;
1444
+ /** Full instructions of the skills active in this run. */
1445
+ activeSkills?: string;
1446
+ /** The executor can call find_tools to activate more tools. */
1447
+ searchMode?: boolean;
1448
+ /** What the user said while the run was going (`RunControl.send`), oldest first. */
1449
+ updates?: string[];
1450
+ /** Set when `config.learning` is on (and not muted): the executor is told to keep a notebook. */
1451
+ learning?: {
1452
+ fetch: boolean;
1453
+ };
1454
+ /** Set when `config.sandbox` is on: what `run_js` is, and never to report code as run without it. */
1455
+ sandbox?: string;
1456
+ /** Set while `spawn_subagent` is callable (`subagents.dynamic`): when to hand work to a helper. */
1457
+ subagents?: string;
1458
+ }
1459
+ interface ReplannerPromptContext {
1460
+ goal: string;
1461
+ state?: string;
1462
+ done: string[];
1463
+ remaining: string[];
1464
+ mode: ToolCallMode;
1465
+ activeSkills?: string;
1466
+ /** What the user said while the run was going, oldest first. */
1467
+ updates?: string[];
1468
+ /** How many of `updates` (the last ones) the plan has not been weighed against yet. */
1469
+ newUpdates?: number;
1470
+ /** Set when `config.executorTiers` is on: the steps of a revised plan are rated too. */
1471
+ tiers?: boolean;
1231
1472
  }
1232
- /** What a search spent in model tokens, as the API reported it. */
1233
- interface ISearchUsage {
1234
- inputTokens: number;
1235
- outputTokens: number;
1236
- totalTokens: number;
1237
- reasoningTokens: number;
1473
+ interface SynthesizerPromptContext {
1474
+ goal: string;
1475
+ state?: string;
1476
+ done: string[];
1477
+ /** Excerpts of what the tools returned, for answering with real data. */
1478
+ findings?: string[];
1479
+ activeSkills?: string;
1480
+ /** What the user said while the run was going, oldest first. */
1481
+ updates?: string[];
1482
+ /** Set when `config.sandbox` is on: the output of code is reported only when `run_js` returned it. */
1483
+ sandbox?: string;
1238
1484
  }
1239
- /** A provider's answer, parsed: raw third-party values until `sanitizeSearchResults`. */
1240
- interface ISearchAnswer {
1241
- results: unknown[];
1242
- /** The grounding model's whole answer (raw). */
1243
- summary?: unknown;
1244
- /** Absent when the API reported none. */
1245
- usage?: ISearchUsage;
1485
+ interface Prompts {
1486
+ planner(ctx: PlannerPromptContext): PromptParts;
1487
+ executor(ctx: ExecutorPromptContext): PromptParts;
1488
+ replanner(ctx: ReplannerPromptContext): PromptParts;
1489
+ synthesizer(ctx: SynthesizerPromptContext): PromptParts;
1246
1490
  }
1491
+ declare const defaultPrompts: Prompts;
1492
+ /** Prepend a host-supplied systemPrompt to a phase system prompt, if present. */
1493
+ declare const withSystem: (base: string, extra?: string) => string;
1494
+
1247
1495
  /**
1248
- * The request for one query, per the Gemini API's public documentation:
1249
- * POST {base}/v1beta/models/{model}:generateContent header x-goog-api-key
1250
- * { systemInstruction, contents: [the query], tools: [{ google_search }], generationConfig }
1251
- * The query is the only text of the conversation in it. The API has no result count: the list
1252
- * is cut on the way back.
1253
- */
1254
- declare const buildSearchRequest: (input: ISearchRequestInput) => ISearchRequest;
1255
- /**
1256
- * What a grounded answer holds, mapped to results of `{ title, url, snippet }` and nothing else,
1257
- * the model's answer, and what the call spent. A source is a `groundingChunks[].web` (`uri` is a
1258
- * Google redirect link, `title` the site's name); its snippet is the pieces of the answer that
1259
- * `groundingSupports` attribute to it (fragments as the API cut them, joined with an ellipsis). Still raw third-party values: `sanitizeSearchResults` is
1260
- * what makes them safe to show.
1261
- */
1262
- declare const parseSearchResponse: (provider: SearchProvider, json: unknown) => ISearchAnswer;
1263
- /**
1264
- * What a failed call says to the model: the provider, the model, the status, the API's own error
1265
- * code word and what it usually means. Never the error's text: that is third-party text, and may
1266
- * echo what was sent. `body` is the parsed error body, if there was one.
1496
+ * The seam the provider registry uses to fetch API keys at model-build time.
1497
+ * Swap in any backend: the encrypted vault (default), an in-memory map (tests /
1498
+ * SSR), or a `fetch` to your own short-lived-token endpoint.
1267
1499
  */
1268
- declare const searchStatusMessage: (provider: SearchProvider, status: number, model?: string, body?: unknown) => string;
1269
- interface ISanitizedSearch {
1270
- results: ISearchResult[];
1271
- /** Results dropped because the host's egress policy does not let the model reach them. */
1272
- filtered: number;
1273
- /** True when results were left out for a cap (the count, or the total size). */
1274
- truncated: boolean;
1500
+ interface CredentialStore {
1501
+ getApiKey(ref: string): Promise<string | undefined>;
1502
+ setApiKey(ref: string, key: string): Promise<void>;
1503
+ deleteApiKey(ref: string): Promise<void>;
1275
1504
  }
1276
1505
  /**
1277
- * What a model sees of an engine's answer. `raw` is whatever came back - nothing about it is
1278
- * trusted: a result needs a valid http(s) URL, every field is cleaned and capped, duplicates go,
1279
- * `accepts` (the egress policy; it is also handed the result's raw title) drops links the model
1280
- * could not fetch, and the list stops at `maxResults` and at SEARCH_MAX_TOTAL_CHARS.
1506
+ * Default CredentialStore: encrypted, IndexedDB-backed (see IndexedDBVault). Every tab of the
1507
+ * origin shares it: a key stored or removed tells the other tabs that SOMETHING changed (a
1508
+ * `credentials` notice: no ref, never a key - see `onStorageChange`).
1281
1509
  */
1282
- declare const sanitizeSearchResults: (raw: unknown, options?: {
1283
- maxResults?: number;
1284
- accepts?: (url: URL, title: unknown) => boolean;
1285
- }) => ISanitizedSearch;
1286
- /** What `web_search` returns to the model. */
1287
- interface ISearchToolResult {
1288
- query: string;
1289
- results: ISearchResult[];
1290
- /** The google provider, when no source came with a snippet: the grounding model's answer, cut. */
1291
- summary?: string;
1292
- /** The google provider: what its URLs and its text are. */
1293
- note?: string;
1294
- filtered?: number;
1295
- truncated?: true;
1296
- untrusted: true;
1510
+ declare class VaultCredentialStore implements CredentialStore {
1511
+ /** The database the vault lives in, and the name its change notices go out under. */
1512
+ readonly dbName: string;
1513
+ private readonly vault;
1514
+ private readonly tab;
1515
+ constructor(opts?: VaultOptions);
1516
+ getApiKey(ref: string): Promise<string | undefined>;
1517
+ setApiKey(ref: string, key: string): Promise<void>;
1518
+ deleteApiKey(ref: string): Promise<void>;
1519
+ }
1520
+ /** Non-persistent CredentialStore for tests / SSR / ephemeral sessions. */
1521
+ declare class MemoryCredentialStore implements CredentialStore {
1522
+ private readonly map;
1523
+ constructor(initial?: Record<string, string>);
1524
+ getApiKey(ref: string): Promise<string | undefined>;
1525
+ setApiKey(ref: string, key: string): Promise<void>;
1526
+ deleteApiKey(ref: string): Promise<void>;
1297
1527
  }
1528
+
1298
1529
  /**
1299
- * The tool's result, from the cleaned list and - for the google provider - the parsed answer.
1300
- * The model's `summary` is attached only when there are sources, none of them carries a snippet
1301
- * and none was filtered out: a summary cannot be cut to the sources that remain.
1530
+ * A small virtual file system for the browser — the agent's (and the user's)
1531
+ * workspace: attachments the user drops in, reports the agent writes, images
1532
+ * pasted into the chat. Persistent in IndexedDB by default, in-memory on
1533
+ * request (tests, private mode). Paths are POSIX-like and always absolute
1534
+ * ("/notes/todo.md"); there are no real directories — a "directory" is a path
1535
+ * prefix.
1302
1536
  */
1303
- declare const searchToolResult: (query: string, clean: ISanitizedSearch, answer?: ISearchAnswer) => ISearchToolResult;
1304
-
1537
+ interface VirtualFile {
1538
+ path: string;
1539
+ /** Text, or base64 for binary content (see `encoding`). */
1540
+ content: string;
1541
+ encoding: 'utf8' | 'base64';
1542
+ mimeType: string;
1543
+ /** Size of the decoded content in bytes. */
1544
+ size: number;
1545
+ updatedAt: number;
1546
+ }
1547
+ /** A listing entry (no content). */
1548
+ type VirtualFileInfo = Omit<VirtualFile, 'content'>;
1549
+ interface VirtualFileSystemOptions {
1550
+ /** Keep files in memory only (default false: IndexedDB). */
1551
+ memory?: boolean;
1552
+ /** IndexedDB database name, forwarded to the shared owner (default 'agent-web'). */
1553
+ dbName?: string;
1554
+ /** Isolates several file systems in one database (default 'default'). */
1555
+ namespace?: string;
1556
+ /** Refuse a single file larger than this many bytes (default 10 MB). */
1557
+ maxFileBytes?: number;
1558
+ }
1559
+ type VfsListener = (change: {
1560
+ type: 'write' | 'delete';
1561
+ path: string;
1562
+ }) => void;
1563
+ /** A best-effort MIME type from a file name. */
1564
+ declare const mimeFromPath: (path: string) => string;
1565
+ /** True for MIME types the agent can read as text. */
1566
+ declare const isTextMime: (mime: string) => boolean;
1305
1567
  /**
1306
- * `config.search`: the `web_search` tool, the companion of `web_fetch`. Off unless set. The
1307
- * library ships no key: the host passes a search engine of its own (a function - any search API)
1308
- * or names the one built-in provider, Google Search through Gemini grounding. Browser sibling of
1309
- * the server's `ISearchConfig` - same names - except that a key is never written here:
1310
- * `credentialRef` names it in the `CredentialStore` the agent was given (`config.credentials`).
1311
- *
1312
- * The Gemini API answers a page directly (CORS). See docs/capabilities.md.
1568
+ * Normalise a path: absolute, forward slashes, no "." / ".." / empty segments.
1569
+ * Throws on a path that escapes the root.
1313
1570
  */
1314
- interface ISearchConfig {
1315
- /**
1316
- * A search engine of your own: `(query, { maxResults, freshness, signal }) => results`. Its
1317
- * requests are yours (like a tool you pass); its results are cleaned, capped and filtered like
1318
- * the provider's. Exactly one of `engine` / `provider`.
1319
- */
1320
- engine?: SearchEngine;
1321
- /**
1322
- * The built-in provider: 'google' - Google Search through the Gemini API's grounding. One
1323
- * generateContent call per search with the `google_search` tool: it needs a Gemini (Google AI
1324
- * Studio) key and nothing else, and it spends that model's tokens (counted in the run's usage,
1325
- * phase 'search'). Result URLs are Google redirect links, snippets the model's own summary.
1326
- */
1327
- provider?: SearchProvider;
1328
- /**
1329
- * Where the Gemini API key is kept in the agent's `CredentialStore` (it can be the ref of a
1330
- * Gemini model's own key). Read at each call and sent in a header to that API only; never in a
1331
- * URL, an event, a log line, an error or a result.
1332
- */
1333
- credentialRef?: string;
1334
- /** The Gemini model that makes the grounding call. Default 'gemini-2.5-flash-lite'. */
1335
- model?: string;
1571
+ declare const normalizePath: (input: string) => string;
1572
+ /** Base64 of bytes, chunked so a large file can't blow the call stack. */
1573
+ declare const bytesToBase64: (bytes: Uint8Array) => string;
1574
+ declare class VirtualFileSystem {
1336
1575
  /**
1337
- * Replaces the public endpoint (a gateway of yours that holds the key - `credentialRef` is
1338
- * then optional).
1576
+ * The IndexedDB database the files live in - and the name the other tabs hear of a change
1577
+ * under (`files` notices, see `onStorageChange`). Undefined for an in-memory file system:
1578
+ * nothing of it is shared.
1339
1579
  */
1340
- baseURL?: string;
1341
- /** Results per call when the model does not say (default 5, at most 10). */
1342
- maxResults?: number;
1580
+ readonly dbName: string | undefined;
1581
+ /** Isolates several file systems in one database: a `files` notice carries it. */
1582
+ readonly namespace: string;
1583
+ private readonly memory?;
1584
+ private readonly ns;
1585
+ private readonly maxFileBytes;
1586
+ private readonly listeners;
1587
+ private readonly tab;
1588
+ constructor(opts?: VirtualFileSystemOptions);
1589
+ private key;
1590
+ /** After a write committed: the other tabs hear which file (never its content). */
1591
+ private announce;
1343
1592
  /**
1344
- * Let the SEARCH API itself be on a private / loopback address or an internal-looking name (a
1345
- * gateway of yours). It widens nothing else: the request can still reach only that one host.
1593
+ * Subscribe to writes and deletes made through THIS file system (e.g. to refresh a file list).
1594
+ * Another tab's changes come as `files` notices (`onStorageChange(vfs.dbName, ...)`). Returns
1595
+ * an unsubscribe.
1346
1596
  */
1347
- allowPrivateNetwork?: boolean;
1348
- /** Whole request to the search API, in ms. Default 15_000. */
1349
- timeoutMs?: number;
1597
+ onChange(listener: VfsListener): () => void;
1598
+ private notify;
1599
+ write(path: string, content: string | Uint8Array, opts?: {
1600
+ mimeType?: string;
1601
+ encoding?: VirtualFile['encoding'];
1602
+ }): Promise<VirtualFileInfo>;
1603
+ /** Store a data URL ("data:image/png;base64,…") as a file. */
1604
+ writeDataUrl(path: string, dataUrl: string): Promise<VirtualFileInfo>;
1605
+ read(path: string): Promise<VirtualFile | undefined>;
1606
+ /** The file as a data URL (for <img src>, downloads). */
1607
+ readDataUrl(path: string): Promise<string | undefined>;
1608
+ delete(path: string): Promise<boolean>;
1609
+ /** Files under a prefix ("/" = all), sorted by path. */
1610
+ list(prefix?: string): Promise<VirtualFileInfo[]>;
1611
+ /** Remove every file (of this namespace). */
1612
+ clear(): Promise<void>;
1613
+ }
1614
+
1615
+ /**
1616
+ * Skills — reusable instruction bundles in the agentskills.io shape
1617
+ * (`SKILL.md` with `name`/`description` frontmatter, a markdown body, optional
1618
+ * bundled text files). Progressive disclosure: only the one-line index sits in
1619
+ * the prompts; a skill's full instructions enter the context when the planner
1620
+ * selects it or the executor loads it with `load_skill`.
1621
+ */
1622
+ interface Skill {
1623
+ /** Stable id: lowercase letters, digits and dashes, 1–64 chars. */
1624
+ name: string;
1625
+ /** When to use it — the only part always shown to the model. */
1626
+ description: string;
1627
+ /** Full instructions (the markdown body of SKILL.md). */
1628
+ content: string;
1629
+ /** Bundled text resources, addressed by skill-relative POSIX paths. */
1630
+ files?: {
1631
+ path: string;
1632
+ content: string;
1633
+ }[];
1634
+ /** Set on a skill the AGENT wrote (`config.learning`); absent on the host's own. */
1635
+ origin?: SkillOrigin;
1350
1636
  /**
1351
- * How the consent gate sees a search. Default true (read-only: the only host reached is the one
1352
- * named here). false = it asks like a write - a query is text that leaves for a third party.
1637
+ * Set on a skill an MCP server serves (`skills: true` on its config): which server, and the URI
1638
+ * of its SKILL.md. Third-party text: loaded on demand, under a preamble that says so.
1353
1639
  */
1354
- readOnly?: boolean;
1355
- /** The fetch the adapter uses (default `globalThis.fetch`). Still bound to the search policy. */
1356
- fetch?: typeof fetch;
1640
+ mcp?: McpSkillOrigin;
1641
+ }
1642
+ /** Where an MCP server's skill comes from: the server's key in the connection, its SKILL.md URI. */
1643
+ interface McpSkillOrigin {
1644
+ server: string;
1645
+ uri: string;
1357
1646
  }
1358
- interface IWebSearchOptions {
1359
- search: ISearchConfig;
1360
- /** `config.egress`, when the agent has it: its deny list is inherited, and results the model could not fetch under it are left out. */
1361
- egress?: boolean | IEgressPolicy;
1362
- /** Where `search.credentialRef` is looked up (`config.credentials`). */
1363
- credentials?: CredentialStore;
1364
- /** A fetch of your own for the adapter's request (already bound to a policy). */
1365
- fetch?: GuardedFetch;
1647
+ /** Where a learned skill came from. */
1648
+ interface SkillOrigin {
1649
+ kind: 'learned';
1650
+ /** Epoch ms of the last write. */
1651
+ at: number;
1652
+ /** 1 for a new lesson, +1 each time the agent rewrites it. */
1653
+ revision: number;
1654
+ runId?: string;
1655
+ /** What the model said it consulted (URLs without query strings, doc names). */
1656
+ sources?: string[];
1657
+ /** Pages web_fetch read during the run that wrote it - recorded by the harness, not the model. */
1658
+ fetched?: string[];
1366
1659
  }
1660
+ /** Names of the built-in skill tools (reserved when skills are configured). */
1661
+ declare const SKILL_TOOL_NAMES: readonly ["load_skill", "read_skill_file"];
1662
+ /** Validate a skill definition and return it (throws a precise error). */
1663
+ declare const defineSkill: (skill: Skill) => Skill;
1367
1664
  /**
1368
- * The policy the adapter's one request is made under. It is NOT the model's egress policy with a
1369
- * host added: the allow list is exactly the search API's host, scheme and port, so the tool
1370
- * cannot be steered anywhere else (a redirect is never followed), and the host's deny list
1371
- * still wins.
1665
+ * Parse a SKILL.md document into a {@link Skill}. Frontmatter must provide
1666
+ * `name` and `description`; the markdown body becomes `content`.
1372
1667
  */
1373
- declare const searchEgressPolicy: (search: ISearchConfig, egress?: boolean | IEgressPolicy) => IEgressPolicy;
1668
+ declare const parseSkillMarkdown: (markdown: string, files?: {
1669
+ path: string;
1670
+ content: string;
1671
+ }[]) => Skill;
1672
+ interface LoadSkillOptions {
1673
+ /** Bundled files to fetch, relative to the SKILL.md URL. */
1674
+ files?: string[];
1675
+ fetch?: typeof fetch;
1676
+ }
1677
+ /** Fetch a SKILL.md (and optionally its bundled files) over HTTP. */
1678
+ declare const loadSkillFromUrl: (url: string, opts?: LoadSkillOptions) => Promise<Skill>;
1374
1679
  /**
1375
- * `web_search({ query })`: a short list of `{ title, url, snippet, date? }`. The adapter's
1376
- * request goes through the guarded fetch under `searchEgressPolicy`; what comes back is
1377
- * third-party text and is cleaned, capped and - when the agent has an egress policy - filtered
1378
- * to what `web_fetch` could open, so a search is not a way to read around the allow / deny lists.
1379
- *
1380
- * The google provider's links are Google redirect links: the filter can judge only that host
1381
- * (plus the site the API names, which is enough to drop a denied site and never to allow one).
1382
- * Nothing here follows them. `web_fetch` opens one only under `egress.followRedirects` (the
1383
- * guarded fetch then judges where it ended) and, from a page, only through an `egress.fetch`
1384
- * of the host's: the redirect host sends no CORS headers.
1680
+ * How a learned skill is introduced wherever its text is shown to the model: as a note of the
1681
+ * agent's own, subordinate to the user - never as an instruction.
1385
1682
  */
1386
- declare const createWebSearchTool: (options: IWebSearchOptions) => AgentTool;
1387
- /** The tools `config.search` turns on (none when it is off). */
1388
- declare const createSearchTools: (search: ISearchConfig | undefined, egress?: boolean | IEgressPolicy, credentials?: CredentialStore) => AgentToolSet | undefined;
1389
-
1390
- interface IDecisionOption {
1391
- id: string;
1392
- description?: string;
1683
+ declare const learnedPreamble: (skill: Skill) => string;
1684
+ /** What the person answered (`askMcpSkillConsent`). */
1685
+ interface McpSkillAnswer {
1686
+ approved: boolean;
1687
+ /** "Always for this server". */
1688
+ remember?: boolean;
1689
+ reason?: string;
1690
+ /** Who answered: a person, nobody (no handler), or nobody in time / the handler failed. */
1691
+ by: 'person' | 'no-handler' | 'no-answer';
1393
1692
  }
1394
- interface IDecisionQuestion {
1395
- id: string;
1396
- prompt: string;
1397
- options: readonly IDecisionOption[];
1398
- context?: string;
1693
+ /**
1694
+ * What a run hands the MCP skill paths so that a person can be asked: the agent's policy, the
1695
+ * session's grants (shared with helpers), the run's own record, and the question itself.
1696
+ */
1697
+ interface McpSkillConsentScope {
1698
+ agentConsent?: McpSkillConsent;
1699
+ grants: McpSkillGrants;
1700
+ run: McpSkillRunConsent;
1701
+ ask: (input: unknown, skill: McpSkillConsentView, signal?: AbortSignal) => Promise<McpSkillAnswer>;
1399
1702
  }
1400
- interface IDecisionCallOptions {
1401
- abortSignal?: AbortSignal;
1703
+ /**
1704
+ * How a skill's text is introduced to the model: a lesson as the agent's own note, an MCP
1705
+ * server's skill as third-party knowledge; the host's skills as they are.
1706
+ */
1707
+ declare const skillPreamble: (skill: Skill) => string;
1708
+ /** "- name: description" lines for the prompts. */
1709
+ declare const renderSkillIndex: (skills: Skill[]) => string;
1710
+ /** The full instructions of the active skills, within a total character budget. */
1711
+ declare const renderActiveSkills: (skills: Skill[]) => string;
1712
+ /** What `createSkillTools` needs of the MCP servers whose skills are on (`skills` on a server). */
1713
+ interface SkillToolsMcp {
1714
+ /**
1715
+ * The servers' skill sources (`collectMcpSkillSources`), fixed for the agent: they are named in
1716
+ * load_skill's description (run-stable), which then takes `{ server, uri }` too.
1717
+ */
1718
+ sources: readonly McpSkillSource[];
1719
+ /** The run's consent scope: a person is asked through the agent's approval gate. */
1720
+ scope?: McpSkillConsentScope;
1721
+ /** What the agent's snapshots of generated skills hold (a skill added by URI counts there). */
1722
+ memory?: McpSkillSnapshotMemory;
1402
1723
  }
1403
- interface IDecisionAnswer {
1404
- choice: string;
1405
- confidence: number;
1406
- usage?: {
1407
- inputTokens?: number;
1408
- outputTokens?: number;
1409
- };
1724
+ /**
1725
+ * The built-in `load_skill` / `read_skill_file` tools. `onLoad` fires when a
1726
+ * skill is loaded so the runner can keep it active for later steps. With `mcp`, an MCP server's
1727
+ * skill enters the context only once the person let it in (`acquireMcpSkill`), and a skill a
1728
+ * server names by URI can be loaded with `{ server, uri }`.
1729
+ */
1730
+ declare const createSkillTools: (skills: Skill[], onLoad?: (skill: Skill) => void, mcp?: SkillToolsMcp) => ToolSet;
1731
+
1732
+ declare const SAVE_SKILL_TOOL = "save_skill";
1733
+ declare const FORGET_SKILL_TOOL = "forget_skill";
1734
+ /** Where learned skills are kept. {@link MemorySkillStore} and {@link VfsSkillStore} are provided. */
1735
+ interface SkillStore {
1736
+ list(): Skill[] | Promise<Skill[]>;
1737
+ save(skill: Skill): void | Promise<void>;
1738
+ /** false when there was nothing to remove. */
1739
+ remove(name: string): boolean | Promise<boolean>;
1740
+ /**
1741
+ * Set when the origin's tabs share the store (`VfsSkillStore` on an IndexedDB file system): the
1742
+ * database its `skills` notices go out under, so another tab knows to re-read its lessons
1743
+ * (`agent.reloadLearnedSkills()`). Absent: the store is this tab's alone.
1744
+ */
1745
+ readonly dbName?: string;
1410
1746
  }
1411
- interface IDecisionModel {
1412
- readonly name?: string;
1413
- decide: (question: IDecisionQuestion, options: IDecisionCallOptions) => Promise<IDecisionAnswer>;
1747
+ interface LearningConfig {
1748
+ /** Where lessons are kept. Default: in memory, for the life of the agent (the open session). */
1749
+ store?: SkillStore;
1750
+ /** At most this many lessons (default 50). */
1751
+ maxSkills?: number;
1752
+ /** At most this many characters of instructions per lesson (default 6000). */
1753
+ maxSkillChars?: number;
1754
+ /** false keeps the tools but drops the executor guidance to write lessons down (default true). */
1755
+ nudge?: boolean;
1414
1756
  }
1415
- interface IDecisionConfig {
1416
- confidenceThreshold?: number;
1417
- timeoutMs?: number;
1418
- replan?: boolean;
1419
- route?: boolean;
1757
+ /** What a credential looks like, or undefined. */
1758
+ declare const findSecret: (text: string) => string | undefined;
1759
+ /** "My Trick_1" -> "my-trick-1"; undefined when nothing usable is left. */
1760
+ declare const normalizeSkillName: (raw: string) => string | undefined;
1761
+ /** Lives as long as the agent: the "open session". */
1762
+ declare class MemorySkillStore implements SkillStore {
1763
+ private readonly skills;
1764
+ list(): Skill[];
1765
+ save(skill: Skill): void;
1766
+ remove(name: string): boolean;
1420
1767
  }
1421
- declare const DEFAULT_DECISION_CONFIDENCE_THRESHOLD = 0.8;
1422
- declare const DEFAULT_DECISION_TIMEOUT_MS = 5000;
1423
- type DecisionPoint = 'replan' | 'route';
1424
- type DecisionFallbackReason = 'low-confidence' | 'invalid-choice' | 'invalid-confidence' | 'error' | 'timeout' | 'needs-model';
1425
- interface IDecisionOutcome {
1426
- accepted: boolean;
1427
- choice?: string;
1428
- confidence?: number;
1429
- threshold: number;
1430
- reason?: DecisionFallbackReason;
1431
- error?: string;
1432
- durationMs: number;
1433
- usage?: {
1434
- inputTokens?: number;
1435
- outputTokens?: number;
1436
- };
1768
+ /**
1769
+ * `<dir>/<name>/SKILL.md` in the agent's virtual file system (IndexedDB, or memory): the user can
1770
+ * see and edit lessons in the files panel like any file. A sidecar `.origin.json` says where each
1771
+ * came from. Default dir `/skills`.
1772
+ */
1773
+ declare class VfsSkillStore implements SkillStore {
1774
+ private readonly vfs;
1775
+ private readonly dir;
1776
+ private readonly tab;
1777
+ constructor(vfs: VirtualFileSystem, dir?: string);
1778
+ /** The file system's database (undefined in memory): where its `skills` notices go out. */
1779
+ get dbName(): string | undefined;
1780
+ /** The other tabs hear which lesson, in which folder - never its text. */
1781
+ private announce;
1782
+ list(): Promise<Skill[]>;
1783
+ save(skill: Skill): Promise<void>;
1784
+ remove(name: string): Promise<boolean>;
1437
1785
  }
1438
- interface IDecisionEvent {
1439
- type: 'decision';
1440
- point: DecisionPoint;
1441
- accepted: boolean;
1442
- choice?: string;
1443
- confidence?: number;
1444
- threshold: number;
1445
- reason?: DecisionFallbackReason;
1446
- error?: string;
1447
- durationMs: number;
1448
- model?: string;
1786
+ interface Learning {
1787
+ /** The tools the model learns with (normal tools: gated, counted). */
1788
+ tools: AgentToolSet;
1789
+ /** The agent's own skills (not the host's). */
1790
+ learned: () => Skill[];
1791
+ /** Forget one of them. false when there is no such learned skill. */
1792
+ forget: (name: string, emit?: (event: {
1793
+ type: 'skill.forgotten';
1794
+ name: string;
1795
+ }) => void) => Promise<boolean>;
1796
+ /**
1797
+ * Read the store again (another tab wrote to it): the agent's own lessons are added, replaced
1798
+ * or dropped to match it; a host's skill is never touched. Returns the lessons.
1799
+ */
1800
+ reload: () => Promise<Skill[]>;
1449
1801
  }
1450
- declare const askDecisionModel: (model: IDecisionModel, question: IDecisionQuestion, config?: IDecisionConfig, signal?: AbortSignal) => Promise<IDecisionOutcome>;
1451
- interface IAiSdkDecisionOptions {
1452
- name?: string;
1453
- maxRetries?: number;
1454
- headers?: Record<string, string>;
1802
+ interface SaveSkillInput {
1803
+ name: string;
1804
+ description: string;
1805
+ instructions: string;
1806
+ sources?: string[];
1455
1807
  }
1456
- declare const decisionModelFromAiSdk: (model: Experimental_DecisionModel, options?: IAiSdkDecisionOptions) => IDecisionModel;
1808
+ /**
1809
+ * Wires learning to the agent's LIVE skill list (`skills` is mutated in place, so every prompt
1810
+ * that renders the index sees a new lesson at once).
1811
+ */
1812
+ declare const createLearning: (cfg: LearningConfig, skills: Skill[], warn: (message: string) => void) => Promise<Learning>;
1457
1813
 
1458
- interface PipelineDefinition {
1459
- version: 1;
1460
- name?: string;
1461
- entry: string;
1462
- nodes: PipelineNode[];
1463
- edges: PipelineEdge[];
1464
- limits?: {
1465
- maxNodeVisits?: number;
1466
- maxRuns?: number;
1467
- };
1468
- }
1469
- interface PipelineNode {
1470
- id: string;
1471
- name?: string;
1472
- instructions?: string;
1473
- model?: string;
1474
- skills?: string[];
1475
- tools?: string[];
1476
- mcpServers?: string[];
1477
- routes?: PipelineRoute[];
1478
- join?: 'all' | 'any';
1479
- settings?: Record<string, unknown>;
1480
- position?: {
1481
- x: number;
1482
- y: number;
1483
- };
1484
- }
1485
- interface PipelineRoute {
1486
- label: string;
1487
- description?: string;
1488
- }
1489
- type PipelineCondition = {
1490
- kind: 'always';
1491
- } | {
1492
- kind: 'contains';
1493
- text: string;
1494
- caseSensitive?: boolean;
1495
- } | {
1496
- kind: 'matches';
1497
- pattern: string;
1498
- flags?: string;
1499
- } | {
1500
- kind: 'route';
1501
- label: string;
1502
- } | {
1503
- kind: 'otherwise';
1504
- };
1505
- interface PipelineEdge {
1506
- id?: string;
1507
- from: string;
1508
- to: string;
1509
- when?: PipelineCondition;
1510
- }
1511
- declare const PIPELINE_LIMITS: {
1512
- readonly maxNodeVisits: 3;
1513
- readonly maxRuns: 25;
1514
- readonly maxNodeVisitsCeiling: 100;
1515
- readonly maxRunsCeiling: 1000;
1516
- readonly maxNodes: 200;
1517
- readonly maxEdges: 1000;
1518
- readonly maxRoutes: 20;
1519
- readonly maxPatternLength: 500;
1520
- readonly maxPatternProgram: 1000;
1521
- readonly conditionInputChars: 50000;
1522
- };
1523
- interface PipelineUsage {
1524
- inputTokens: number;
1525
- outputTokens: number;
1526
- totalTokens: number;
1527
- reasoningTokens?: number;
1528
- cachedInputTokens?: number;
1529
- cacheWriteTokens?: number;
1530
- }
1531
- interface PipelineNodeSource {
1532
- nodeId: string;
1533
- name?: string;
1534
- text: string;
1535
- }
1536
- interface PipelineNodeInput {
1537
- request: string;
1538
- from: PipelineNodeSource[];
1539
- visit: number;
1814
+ interface ISandboxConfig {
1815
+ timeoutMs?: number;
1816
+ memoryLimitBytes?: number;
1817
+ maxOutputChars?: number;
1818
+ maxCodeChars?: number;
1819
+ files?: boolean;
1540
1820
  }
1541
- interface PipelineNodeOutput {
1542
- text: string;
1543
- usage?: PipelineUsage;
1544
- route?: string;
1821
+ interface ISandboxLimits {
1822
+ timeoutMs: number;
1823
+ memoryLimitBytes: number;
1824
+ maxOutputChars: number;
1825
+ maxCodeChars: number;
1545
1826
  }
1546
- interface PipelineNodeContext<E = never> {
1547
- signal: AbortSignal;
1548
- pipeline: PipelineDefinition;
1549
- emit: (event: E) => void;
1550
- }
1551
- type PipelineNodeRunner<E = never> = (node: PipelineNode, input: PipelineNodeInput, ctx: PipelineNodeContext<E>) => Promise<PipelineNodeOutput>;
1552
- type PipelineStop = 'maxRuns' | 'maxNodeVisits' | 'aborted';
1553
- type PipelineEvent = {
1554
- type: 'pipeline.started';
1555
- pipeline?: string;
1556
- } | {
1557
- type: 'pipeline.node.started';
1558
- nodeId: string;
1559
- visit: number;
1560
- from: string[];
1561
- } | {
1562
- type: 'pipeline.node.finished';
1563
- nodeId: string;
1564
- visit: number;
1565
- text: string;
1566
- route?: string;
1567
- usage?: PipelineUsage;
1568
- } | {
1569
- type: 'pipeline.node.failed';
1570
- nodeId: string;
1571
- visit: number;
1572
- error: string;
1573
- } | {
1574
- type: 'pipeline.node.skipped';
1575
- nodeId: string;
1576
- from: string[];
1577
- reason: 'maxRuns' | 'maxNodeVisits';
1578
- } | {
1579
- type: 'pipeline.edge';
1580
- from: string;
1581
- to: string;
1582
- edgeId: string;
1583
- visit: number;
1584
- fired: boolean;
1585
- } | {
1586
- type: 'pipeline.finished';
1587
- stoppedBy?: PipelineStop;
1588
- runs: number;
1589
- };
1590
- type PipelineTraceEntry = {
1591
- type: 'node';
1592
- nodeId: string;
1593
- visit: number;
1594
- wave: number;
1595
- from: string[];
1596
- text: string;
1597
- route?: string;
1598
- usage?: PipelineUsage;
1599
- } | {
1600
- type: 'edge';
1601
- from: string;
1602
- to: string;
1603
- edgeId: string;
1604
- visit: number;
1605
- fired: boolean;
1606
- } | {
1607
- type: 'dropped';
1608
- nodeId: string;
1609
- from: string[];
1610
- reason: 'maxRuns' | 'maxNodeVisits';
1611
- };
1612
- interface PipelineResult {
1613
- text: string;
1614
- outputs: Record<string, {
1615
- visit: number;
1616
- text: string;
1617
- route?: string;
1618
- }[]>;
1619
- trace: PipelineTraceEntry[];
1620
- usage: PipelineUsage;
1621
- stoppedBy?: PipelineStop;
1622
- runs: number;
1623
- }
1624
- interface PipelineIssue {
1625
- code: string;
1827
+ interface ISandboxError {
1828
+ name: string;
1626
1829
  message: string;
1627
- nodeId?: string;
1628
- edgeId?: string;
1629
- edgeIndex?: number;
1830
+ stack?: string;
1630
1831
  }
1631
- interface PipelineValidation {
1832
+ interface ISandboxResult {
1632
1833
  ok: boolean;
1633
- errors: PipelineIssue[];
1634
- warnings: PipelineIssue[];
1635
- }
1636
- declare class PipelineValidationError extends Error {
1637
- errors: PipelineIssue[];
1638
- constructor(errors: PipelineIssue[]);
1639
- }
1640
- declare class PipelineNodeError extends Error {
1641
- nodeId: string;
1642
- visit: number;
1643
- constructor(nodeId: string, visit: number, cause: unknown);
1834
+ stdout: string;
1835
+ result?: unknown;
1836
+ error?: ISandboxError;
1837
+ truncated: boolean;
1838
+ durationMs: number;
1644
1839
  }
1645
- declare const testPipelineCondition: (when: PipelineCondition | undefined, output: {
1646
- text: string;
1647
- route?: string;
1648
- }, matcher?: (text: string) => boolean) => boolean;
1649
- declare const normalizePipeline: (definition: PipelineDefinition) => PipelineDefinition;
1650
- declare const validatePipeline: (definition: PipelineDefinition) => PipelineValidation;
1651
- declare const renderPipelineNodeInput: (input: PipelineNodeInput) => string;
1652
1840
 
1653
1841
  /**
1654
- * Tool consent. Every tool call passes a gate that decides allow / ask / deny:
1655
- *
1656
- * - `autopilot` — run everything (default; explicit `rules` still apply);
1657
- * - `ask-writes` — run read-only tools, ask before anything that may change state;
1658
- * - `ask-all` — ask before every call;
1659
- * - `read-only` — run read-only tools, refuse the rest without asking.
1842
+ * `config.sandbox`: the `run_js` tool - the model's code runs in QuickJS compiled to
1843
+ * WebAssembly (the optional peer `quickjs-emscripten`), never in the page's own JavaScript
1844
+ * engine. This module is loaded only when the sandbox is switched on.
1660
1845
  *
1661
- * A tool is read-only when its MCP annotations say so (`readOnlyHint`) or the
1662
- * host marked it (`defineTool({ readOnly: true })` / `markReadOnly`). Unknown =
1663
- * may write: the safe assumption.
1846
+ * Where the guest runs:
1847
+ * - `worker` given: in a Web Worker that is terminated when the run is over or over time (the
1848
+ * hard stop). One worker per run. The worker module is `@dudko.dev/agent-web/sandbox-worker`.
1849
+ * - no `worker`: on the page's thread, stopped by the engine's interrupt handler only. A single
1850
+ * long native call in the guest then blocks the page until it returns - prefer a worker.
1664
1851
  */
1665
- type ToolApprovalMode = 'autopilot' | 'ask-writes' | 'ask-all' | 'read-only';
1666
- type ToolPermission = 'allow' | 'ask' | 'deny';
1667
- declare const TOOL_APPROVAL_MODES: readonly ToolApprovalMode[];
1668
- interface ToolApprovalRequest {
1669
- /** Unique per request — echo it back from a UI. */
1670
- id: string;
1671
- toolName: string;
1672
- input: unknown;
1673
- readOnly: boolean;
1674
- step?: IPlanStep;
1675
- /**
1676
- * Set when the call comes from a helper the model started (`subagents.dynamic`), not from the
1677
- * run itself: the helper's id (as in its `subagent.start` event) and its depth.
1678
- */
1679
- subagent?: {
1680
- id: string;
1681
- depth: number;
1682
- };
1683
- /**
1684
- * Set when the call comes from an MCP App (`Agent.approveAppToolCall`), not from the model:
1685
- * a UI says so ("The app “travel” wants to run …"). `toolName` above is then the name the
1686
- * agent's rules match (`server__tool`), `app.tool` the server's own name for it.
1687
- */
1688
- app?: ToolApprovalApp;
1689
- /**
1690
- * Set when the call runs code (`run_js`, or a tool marked with `markCodeExecution`) while the
1691
- * run acts on skills an MCP server served: those skills, by name. Such a call is ALWAYS asked,
1692
- * whatever the mode, a rule or an earlier "always allow" say (the Skills extension: a server's
1693
- * skill must not lead to code running here without a person's approval).
1694
- */
1695
- mcpSkills?: string[];
1696
- /**
1697
- * Set when the request is not about a tool call but about an MCP server's skill that is about
1698
- * to enter the model's context (`load_skill`, the planner's pick, a resumed run; `skills` on a
1699
- * server, consent `'ask'` / `'once-per-skill'`): the server, the skill, its description and
1700
- * size and the very text the model would read - the SERVER's words, to show as plain text.
1701
- * `toolName` is `'load_skill'`. Approve to let it in (`remember: true` = every skill of that
1702
- * server for the agent's life, nested ones excepted), deny to keep it out. Asked whatever the
1703
- * approval mode and the rules say.
1704
- */
1705
- skill?: McpSkillConsentView;
1706
- }
1707
- /** Who asks when an MCP App asks (see `ToolApprovalRequest.app`). */
1708
- interface ToolApprovalApp {
1709
- /** The MCP server the app came from (its tools are the only ones it may call). */
1710
- server: string;
1711
- /** The tool's own name on that server. */
1712
- tool: string;
1713
- /** The app's `ui://` resource. */
1714
- resourceUri: string;
1715
- }
1716
- /** What the gate hands `onRequest` beside the request. */
1717
- interface ToolApprovalContext {
1718
- /**
1719
- * Aborted when the question ends WITHOUT your answer: no decision within `timeoutMs`
1720
- * (`signal.reason` is an Error named 'TimeoutError'), the run was stopped ('AbortError'), or
1721
- * the handler failed. Take the prompt down then: an answer given later is ignored. Never
1722
- * aborted once you have answered.
1723
- */
1724
- signal: AbortSignal;
1852
+ /** A worker as the sandbox uses it: a real `Worker`, or a `MessagePort` in tests. */
1853
+ interface SandboxWorkerLike {
1854
+ postMessage(message: unknown): void;
1855
+ addEventListener(type: string, listener: (ev: any) => void): void;
1856
+ terminate?(): void;
1725
1857
  }
1726
- /**
1727
- * `true`/`false`, or an object. `remember: true` on an approval allows this
1728
- * tool for the rest of the agent's life ("always allow").
1729
- */
1730
- type ToolApprovalDecision = boolean | {
1731
- approved: boolean;
1732
- reason?: string;
1733
- remember?: boolean;
1734
- };
1735
- interface ToolApprovalConfig {
1736
- /** Default policy (default 'autopilot'). */
1737
- mode?: ToolApprovalMode;
1858
+ interface SandboxConfig extends ISandboxConfig {
1738
1859
  /**
1739
- * Per-tool overrides by exact name or `*` glob, e.g. `{ 'github__delete_*': 'deny' }`.
1740
- * They win over the mode — an explicit 'ask' still asks under autopilot.
1860
+ * Builds a fresh Worker for one run, e.g.
1861
+ * `() => new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' })`
1862
+ * (Vite: `import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'`). Without it
1863
+ * the guest runs on the page's thread - isolated all the same, but only softly interruptible.
1741
1864
  */
1742
- rules?: Record<string, ToolPermission>;
1743
- /** Resolves an approval request (a UI prompt, a policy service, …). */
1744
- onRequest?: (req: ToolApprovalRequest, ctx: ToolApprovalContext) => ToolApprovalDecision | Promise<ToolApprovalDecision>;
1865
+ worker?: () => SandboxWorkerLike;
1745
1866
  /**
1746
- * No decision within this many ms → deny. Default 300 000 ({@link TOOL_APPROVAL_TIMEOUT_MS}).
1747
- * `0` or `Infinity`: no bound - the question waits until the run is stopped; so does a value
1748
- * above 2^31 - 1 (about 24.8 days, the most a timer holds). Negative or NaN: `createAgent`
1749
- * throws. The only bound on the wait: the step's `chatTimeoutMs` (and a subagent's
1750
- * `timeoutMs`) stop while a person decides.
1867
+ * Loads the engine for the page-thread fallback, e.g. `() => import('quickjs-emscripten')`, so
1868
+ * that your bundler resolves it. Default: a runtime `import('quickjs-emscripten')` (Node, or a
1869
+ * page with an import map). Not used when `worker` is given.
1751
1870
  */
1871
+ engine?: () => Promise<unknown>;
1872
+ }
1873
+
1874
+ declare const SPAWN_SUBAGENT_TOOL = "spawn_subagent";
1875
+ type SubagentDefaultTools = 'read-only' | 'all';
1876
+ interface IDynamicSubagentsConfig {
1877
+ maxDepth?: number;
1878
+ maxChildren?: number;
1879
+ maxConcurrent?: number;
1880
+ budgetShare?: number;
1881
+ minTokens?: number;
1752
1882
  timeoutMs?: number;
1883
+ defaultTools?: SubagentDefaultTools;
1753
1884
  }
1754
- /** How long a question waits for a decision when `toolApproval.timeoutMs` is not set: 5 minutes. */
1755
- declare const TOOL_APPROVAL_TIMEOUT_MS = 300000;
1756
- /** Raised by a denied tool call; recorded as a failed call the replanner sees. */
1757
- declare class ToolDeniedError extends Error {
1758
- constructor(reason?: string);
1759
- toJSON(): string;
1885
+ interface ISubagentsConfig {
1886
+ dynamic?: boolean | IDynamicSubagentsConfig;
1760
1887
  }
1761
- /** Mark a tool as read-only so `ask-writes` / `read-only` let it through. Returns it. */
1762
- declare const markReadOnly: <T extends object>(tool: T, readOnly?: boolean) => T;
1763
- /**
1764
- * Mark a tool as one that runs code (the sandbox's `run_js` is): while a run acts on an MCP
1765
- * server's skill, every call of it is asked (`decideToolPermission`).
1766
- */
1767
- declare const markCodeExecution: <T extends object>(tool: T, codeExecution?: boolean) => T;
1768
- declare const isCodeExecutionTool: (tool: unknown) => boolean;
1769
- declare const isReadOnlyTool: (tool: Tool | undefined) => boolean;
1770
- /** The most specific matching rule: an exact name, else the longest glob. Pure. */
1771
- declare const matchRule: (rules: Record<string, ToolPermission> | undefined, toolName: string) => ToolPermission | undefined;
1772
- /**
1773
- * What the gate does for one call, before any human is involved. Order:
1774
- * remembered "always allow" → most specific rule → mode default. Pure.
1775
- * Then one rule that only ever tightens: a call that runs code (`codeExecution`) while the run
1776
- * acts on an MCP server's skill (`mcpSkills`) is asked when it would have been allowed - by the
1777
- * mode, a rule or an "always allow" alike. A deny stays a deny.
1778
- */
1779
- declare const decideToolPermission: (opts: {
1780
- toolName: string;
1781
- readOnly: boolean;
1782
- mode: ToolApprovalMode;
1783
- rules?: Record<string, ToolPermission>;
1784
- remembered?: ReadonlySet<string>;
1785
- codeExecution?: boolean;
1786
- mcpSkills?: readonly string[];
1787
- }) => ToolPermission;
1788
-
1789
- type ReplanMode = 'continue' | 'revise' | 'finish';
1790
- type Phase = 'plan' | 'execute' | 'replan' | 'synthesize';
1791
- /**
1792
- * Phases a `usage` event can be charged to: the four stages plus compaction and subagents;
1793
- * `decision` - a call to `config.decisionModel` (`usage.decisionCalls`, plus the tokens its API
1794
- * reported); 'media' - a call to an image / speech / transcription model (`config.media`),
1795
- * whose `usage` carries the media fields and zero tokens; and 'search' - a `web_search` through
1796
- * the google provider (`config.search`): the grounding call is a model call, and these are the
1797
- * tokens its API reported.
1798
- */
1799
- /** `'app'`: a completion an MCP App asked for (`Agent.sampleForApp`), outside any run. */
1800
- type UsagePhase = Phase | 'compact' | 'subagent' | 'decision' | 'media' | 'search' | 'app';
1801
- /**
1802
- * Everything the agent does is streamed as a typed event so any UI (or none)
1803
- * can render progress. The final answer arrives as a `final` event; there is no
1804
- * built-in rendering. This is a browser-focused subset of the Node sibling's
1805
- * event taxonomy (no persistence/otel events), plus `model.load` for WebLLM
1806
- * weight-download progress.
1807
- */
1808
- type AgentEventBody =
1809
- /**
1810
- * `runId` names the run for `persistence` / `resumeFromRunId`. `resumed` is set when it
1811
- * continues a checkpointed run: the steps already done and the ones still to come.
1812
- */
1813
- {
1814
- type: 'run.start';
1815
- goal: string;
1816
- runId?: string;
1817
- resumed?: {
1818
- completedSteps: number;
1819
- remainingSteps: number;
1820
- };
1821
- } | {
1822
- type: 'model.load';
1823
- progress: number;
1824
- text: string;
1825
- } | {
1826
- type: 'plan.thought-delta';
1827
- delta: string;
1828
- } | {
1829
- type: 'plan.step-added';
1830
- step: IPlanStep;
1831
- index: number;
1832
- } | {
1833
- type: 'plan.created';
1834
- plan: IPlan;
1835
- } | {
1836
- type: 'plan.revised';
1837
- plan: IPlan;
1838
- reason: string;
1888
+ interface IResolvedDynamicSubagents {
1889
+ maxDepth: number;
1890
+ maxChildren: number;
1891
+ maxConcurrent: number;
1892
+ budgetShare: number;
1893
+ minTokens: number;
1894
+ timeoutMs: number;
1895
+ defaultTools: SubagentDefaultTools;
1839
1896
  }
1897
+ declare const SUBAGENT_DEFAULTS: IResolvedDynamicSubagents;
1898
+ declare const SUBAGENT_MAX_DEPTH_LIMIT = 4;
1840
1899
  /**
1841
- * `tier` / `model` / `tierReason`: only when `config.executorTiers` is on - the tier the step
1842
- * starts on, its model id, and why that tier (see `TierReason`).
1900
+ * The effective settings, or undefined when the feature is off (nothing is mounted, nothing is
1901
+ * added to a prompt). A bad value is a configuration error, thrown when the agent is created.
1843
1902
  */
1844
- | {
1845
- type: 'step.start';
1846
- step: IPlanStep;
1847
- index: number;
1848
- total: number;
1849
- tier?: ModelTier;
1850
- model?: string;
1851
- tierReason?: TierReason;
1852
- }
1903
+ declare const resolveDynamicSubagents: (subagents: ISubagentsConfig | undefined) => IResolvedDynamicSubagents | undefined;
1853
1904
  /**
1854
- * The step failed on `from` and is retried on the stronger tier `to` (`config.escalation`);
1855
- * `model` is the model id of `to`. Fires between the step's start and its completion.
1905
+ * A spawn that was refused: the model reads the message as the tool's error and can correct the
1906
+ * call or carry on without a helper.
1856
1907
  */
1857
- | {
1858
- type: 'step.escalated';
1859
- step: IPlanStep;
1860
- from: ModelTier;
1861
- to: ModelTier;
1862
- model: string;
1863
- reason: EscalationReason;
1864
- } | {
1865
- type: 'step.text-delta';
1866
- step: IPlanStep;
1867
- delta: string;
1908
+ declare class SubagentSpawnError extends Error {
1909
+ constructor(message: string);
1910
+ toJSON(): string;
1868
1911
  }
1869
- /** The executor model's streamed thoughts (thinking enabled + provider support). */
1870
- | {
1871
- type: 'step.reasoning-delta';
1872
- step: IPlanStep;
1873
- delta: string;
1874
- } | {
1875
- type: 'step.tool-call';
1876
- step: IPlanStep;
1877
- name: string;
1878
- input: unknown;
1879
- } | {
1880
- type: 'step.tool-result';
1881
- step: IPlanStep;
1882
- name: string;
1883
- output: unknown;
1884
- ok: boolean;
1885
- } | {
1886
- type: 'step.complete';
1887
- step: IPlanStep;
1888
- result: IStepResult;
1912
+ declare const SPAWN_INPUT_SCHEMA: {
1913
+ readonly type: "object";
1914
+ readonly properties: {
1915
+ readonly task: {
1916
+ readonly type: "string";
1917
+ 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.";
1918
+ };
1919
+ readonly role: {
1920
+ readonly type: "string";
1921
+ 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\").";
1922
+ };
1923
+ readonly tools: {
1924
+ readonly type: "array";
1925
+ readonly items: {
1926
+ readonly type: "string";
1927
+ };
1928
+ 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.";
1929
+ };
1930
+ };
1931
+ readonly required: string[];
1932
+ readonly additionalProperties: false;
1933
+ };
1934
+ interface ISpawnTokenLimits {
1935
+ maxInputTokens?: number;
1936
+ maxOutputTokens?: number;
1937
+ maxReasoningTokens?: number;
1938
+ maxTotalTokens?: number;
1889
1939
  }
1890
- /**
1891
- * `byUser`: the replanner ran because the user sent a message (`RunControl.send`), not because a
1892
- * step failed. `failed`: the replanner call itself failed (unparsable output, the provider
1893
- * down) and `mode: 'continue'` is the fallback, not the model's decision — the failure is the
1894
- * `error` event (phase 'replan') just before this one. `confidence`: `config.decisionModel`
1895
- * made this decision (the replanner was not called) - the probability it gave its choice.
1896
- */
1897
- | {
1898
- type: 'replan.decision';
1899
- mode: ReplanMode;
1900
- reason: string;
1901
- byUser?: boolean;
1902
- failed?: true;
1903
- confidence?: number;
1940
+ interface ISpawnUsage {
1941
+ inputTokens: number;
1942
+ outputTokens: number;
1943
+ totalTokens: number;
1944
+ reasoningTokens?: number;
1945
+ }
1946
+ interface ISpawnReservation {
1947
+ limits: ISpawnTokenLimits;
1948
+ maxToolCalls?: number;
1949
+ usage: () => ISpawnUsage;
1950
+ toolCalls: () => number;
1904
1951
  }
1905
1952
  /**
1906
- * `config.decisionModel` was asked a question: its answer was used (`accepted`), or the
1907
- * ordinary model call ran and `reason` says why.
1953
+ * A child's event on its way up through the subagent `parentId` (the `subagent.event` envelope is
1954
+ * added by the caller). A `subagent.start` is emitted with `depth: 1` and the id of the run that
1955
+ * made the call as `parentId`; each subagent it passes through on the way up adds one level, and
1956
+ * the first one - its real parent - puts its own id in `parentId`. So at the top of the stream
1957
+ * every start carries its true depth and parent, whatever mix of static and dynamic subagents,
1958
+ * threads and workers is below.
1908
1959
  */
1909
- | IDecisionEvent | {
1910
- type: 'final.text-delta';
1911
- delta: string;
1912
- }
1913
- /** The synthesizer's streamed thoughts. */
1914
- | {
1915
- type: 'final.reasoning-delta';
1916
- delta: string;
1917
- } | {
1918
- type: 'final';
1919
- text: string;
1920
- } | {
1921
- type: 'usage';
1922
- phase: UsagePhase;
1923
- usage: IUsage;
1924
- } | {
1925
- type: 'retry';
1926
- phase: Phase;
1927
- attempt: number;
1928
- error: string;
1960
+ declare const adoptSubagentEvent: <E extends {
1961
+ type: string;
1962
+ }>(event: E, parentId: string) => E;
1963
+
1964
+ 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';
1965
+ declare class EgressError extends Error {
1966
+ readonly code: EgressErrorCode;
1967
+ constructor(code: EgressErrorCode, message: string);
1968
+ toJSON(): string;
1929
1969
  }
1930
- /** A run-level limit was reached; the run stops executing and writes its answer. */
1931
- | {
1932
- type: 'budget.exceeded';
1933
- kind: LimitKind;
1934
- tokens: number;
1935
- cap: number;
1970
+ interface IEgressPolicy {
1971
+ /** Hosts the agent may reach; empty/absent = any host that passes the other checks. "example.com" (that host only), "*.example.com" (its subdomains, not the apex), an IP or a CIDR for IP-literal URLs. */
1972
+ allow?: string[];
1973
+ /** Always refused; wins over `allow`. Same patterns. */
1974
+ deny?: string[];
1975
+ /** Allow IP literals and internal-looking names in private ranges (default false). Metadata endpoints stay refused. */
1976
+ allowPrivateNetwork?: boolean;
1977
+ /** Default ['https']. */
1978
+ protocols?: ('https' | 'http')[];
1979
+ /** Default [443] (and 80 once 'http' is allowed). */
1980
+ ports?: number[];
1981
+ /** Default ['GET']. */
1982
+ methods?: string[];
1983
+ /** Follow redirects, judging only the final URL after the fact (default false: a redirect fails the request). */
1984
+ followRedirects?: boolean;
1985
+ /** Cap on the body, in bytes. Default 2_000_000. */
1986
+ maxResponseBytes?: number;
1987
+ /** Whole request, in ms. Default 15_000. */
1988
+ timeoutMs?: number;
1989
+ /** The fetch to use (default `globalThis.fetch`). Point it at a gateway to get server-side protection. */
1990
+ fetch?: typeof fetch;
1936
1991
  }
1937
- /** Older context was summarised to fit the window. */
1938
- | {
1939
- type: 'context.compacted';
1940
- /** history = stored transcript; trace = the run's done steps; tool-results = stale results inside a step's tool loop. */
1941
- scope: 'history' | 'trace' | 'tool-results';
1942
- beforeTokens: number;
1943
- afterTokens: number;
1992
+ interface IResolvedEgressPolicy {
1993
+ allow: string[];
1994
+ deny: string[];
1995
+ allowPrivateNetwork: boolean;
1996
+ protocols: ('https' | 'http')[];
1997
+ ports: number[];
1998
+ methods: string[];
1999
+ followRedirects: boolean;
2000
+ maxResponseBytes: number;
2001
+ timeoutMs: number;
2002
+ fetch: typeof fetch;
1944
2003
  }
1945
- /** A skill's instructions entered the context (picked by the planner, or loaded by a tool call). */
1946
- /** `server`: the MCP server the skill came from (a skill served with `skills: true`). */
1947
- | {
1948
- type: 'skill.activated';
1949
- name: string;
1950
- by: 'plan' | 'tool';
1951
- server?: string;
2004
+ declare const resolveEgressPolicy: (policy?: IEgressPolicy) => IResolvedEgressPolicy;
2005
+ type AddressClass = 'public' | 'private' | 'never';
2006
+ declare const classifyAddress: (address: string) => AddressClass;
2007
+ declare const hostMatches: (host: string, pattern: string) => boolean;
2008
+ declare const checkEgressUrl: (url: URL, policy: IResolvedEgressPolicy, method?: string) => void;
2009
+ declare const htmlToText: (html: string) => {
2010
+ title?: string;
2011
+ text: string;
2012
+ };
2013
+ type GuardedFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
2014
+ /** A `fetch` bound to a policy. */
2015
+ declare const createGuardedFetch: (policy?: IEgressPolicy) => GuardedFetch;
2016
+ declare const WEB_FETCH_TOOL = "web_fetch";
2017
+ interface IWebFetchOptions {
2018
+ policy?: IEgressPolicy;
2019
+ fetch?: GuardedFetch;
1952
2020
  }
1953
- /** The agent wrote a lesson down as a skill (`config.learning`). */
1954
- | {
1955
- type: 'skill.learned';
1956
- name: string;
1957
- description: string;
1958
- /** true when it rewrote an earlier lesson of the same name. */
1959
- update: boolean;
1960
- chars: number;
1961
- /** What it consulted: the sources it named, then the pages web_fetch read in the run. */
1962
- sources: string[];
2021
+ /**
2022
+ * `web_fetch({ url })`: read one page or API response. Every request goes through the egress
2023
+ * policy; a refusal comes back as a tool error that says why. Read-only for the consent gate
2024
+ * only when the policy names the hosts it may reach - an open GET is a channel to leak data
2025
+ * through the URL, so it asks like a write.
2026
+ */
2027
+ declare const createWebFetchTool: (options?: IWebFetchOptions) => AgentTool;
2028
+ /** The tools `config.egress` turns on (none when it is off). */
2029
+ declare const createEgressTools: (egress: boolean | IEgressPolicy | undefined) => AgentToolSet | undefined;
2030
+
2031
+ /**
2032
+ * What the `web_search` tools of the two agent packages share: the result shape and its caps, how
2033
+ * a search engine's answer is cleaned before a model reads it, and the one built-in provider
2034
+ * (Google Search through Gemini grounding) as a pure request builder and response parser (one
2035
+ * HTTP call). Pure, no imports, no clock: the request itself is made by each package's own safe
2036
+ * fetch.
2037
+ *
2038
+ * This file is a COPY, byte for byte, in `@dudko.dev/agent` (`src/web-search-shared.ts`) and
2039
+ * `@dudko.dev/agent-web` (`src/tools/web-search-shared.ts`): change both. The Node package's
2040
+ * `tests/web-search-shared.test.ts` compares the two files and tests every cap and guard here.
2041
+ */
2042
+ declare const WEB_SEARCH_TOOL = "web_search";
2043
+ /** Results returned when neither the host nor the model says how many. */
2044
+ declare const SEARCH_DEFAULT_MAX_RESULTS = 5;
2045
+ /** The most results one call returns, whatever the host or the model asks for. */
2046
+ declare const SEARCH_MAX_RESULTS = 10;
2047
+ /** The longest query sent to a search engine, in characters. */
2048
+ declare const SEARCH_MAX_QUERY_CHARS = 400;
2049
+ /** The most of a result's title a model sees. */
2050
+ declare const SEARCH_MAX_TITLE_CHARS = 200;
2051
+ /** A result whose URL is longer than this is dropped (a cut URL is another URL). */
2052
+ declare const SEARCH_MAX_URL_CHARS = 2000;
2053
+ /** The most of a result's snippet a model sees. */
2054
+ declare const SEARCH_MAX_SNIPPET_CHARS = 500;
2055
+ /** The most all results of one call take together (titles, URLs, snippets, dates). */
2056
+ declare const SEARCH_MAX_TOTAL_CHARS = 6000;
2057
+ /** One search result, as the model sees it. Third-party text: data, never instructions. */
2058
+ interface ISearchResult {
2059
+ title: string;
2060
+ url: string;
2061
+ snippet: string;
2062
+ /** When the page was published or last changed, as the engine reported it. */
2063
+ date?: string;
1963
2064
  }
1964
- /** A lesson was deleted (by the agent's forget_skill, or the host's forgetSkill). */
1965
- | {
1966
- type: 'skill.forgotten';
1967
- name: string;
2065
+ type SearchFreshness = 'day' | 'week' | 'month' | 'year';
2066
+ /** What a search engine function is called with, next to the query. */
2067
+ interface ISearchOptions {
2068
+ /** How many results are wanted (1..SEARCH_MAX_RESULTS); more are cut. */
2069
+ maxResults: number;
2070
+ /** Only results from the last day / week / month / year, when the model asked for it. */
2071
+ freshness?: SearchFreshness;
2072
+ /** Aborted when the run is stopped. */
2073
+ signal?: AbortSignal;
1968
2074
  }
1969
2075
  /**
1970
- * A media tool (`config.media`) wrote a file to the virtual file system: `path` is where (read
1971
- * it with `vfs.readDataUrl(path)` to show the picture or play the audio), `mediaType` what its
1972
- * bytes are, `bytes` its size. The bytes themselves are never in an event.
2076
+ * A search engine of the host's own: any function that answers a query with results. What it
2077
+ * returns is treated like a built-in adapter's answer - cleaned, capped and filtered.
1973
2078
  */
1974
- | {
1975
- type: 'media.generated';
1976
- kind: 'image' | 'speech';
1977
- path: string;
1978
- mediaType: string;
1979
- bytes: number;
1980
- model: string;
1981
- step?: IPlanStep;
1982
- }
2079
+ type SearchEngine = (query: string, options: ISearchOptions) => Promise<ISearchResult[]>;
1983
2080
  /**
1984
- * A file tool (`createFileTools`: `fs_write`) or the sandbox's `fs.writeFile` wrote a file to
1985
- * the virtual file system during the run: `path` is where, `mediaType` its MIME type, `bytes`
1986
- * its size. The content is never in an event - read it with `vfs.read(path)`. Emitted once per
1987
- * successful write; a write that was refused or failed emits nothing.
2081
+ * The built-in provider. One: Google Search through the Gemini API's grounding (`google_search`),
2082
+ * which needs a Gemini (Google AI Studio) key and nothing else. Any other search API is the
2083
+ * host's `engine` function.
1988
2084
  */
1989
- | {
1990
- type: 'file.written';
1991
- path: string;
1992
- mediaType: string;
1993
- bytes: number;
1994
- step?: IPlanStep;
1995
- }
1996
- /** A file tool (`fs_delete`) deleted a file that existed. */
1997
- | {
1998
- type: 'file.deleted';
1999
- path: string;
2000
- step?: IPlanStep;
2001
- }
2085
+ type SearchProvider = 'google';
2086
+ declare const SEARCH_PROVIDERS: readonly SearchProvider[];
2087
+ /** Where the provider's API lives (a `baseURL` of the host - a gateway - replaces it). */
2088
+ declare const SEARCH_API_BASE_URL: Record<SearchProvider, string>;
2002
2089
  /**
2003
- * An audio file was transcribed: one the user attached to the run ('attachment') or one the
2004
- * model asked about ('tool'). `text` is what the model reads of it (cleaned and capped).
2090
+ * The model the grounding call is made with when the host names none: the cheapest one that
2091
+ * answered a free-tier key with grounding on the day it was measured (2026-11-26).
2005
2092
  */
2006
- | {
2007
- type: 'media.transcribed';
2008
- source: 'attachment' | 'tool';
2009
- name: string;
2010
- text: string;
2011
- language?: string;
2012
- durationInSeconds?: number;
2013
- model: string;
2093
+ declare const SEARCH_GOOGLE_DEFAULT_MODEL = "gemini-2.5-flash-lite";
2094
+ /** The most of the grounding model's answer a model sees as `summary`. */
2095
+ declare const SEARCH_MAX_SUMMARY_CHARS = 1000;
2096
+ /** Said in every result of the google provider: what its URLs and its text are. */
2097
+ declare const SEARCH_GOOGLE_NOTE: string;
2098
+ /** One HTTP call to a search API. The key, if any, is in `headers` only - never in the URL. */
2099
+ interface ISearchRequest {
2100
+ url: string;
2101
+ method: 'GET' | 'POST';
2102
+ headers: Record<string, string>;
2103
+ body?: string;
2014
2104
  }
2015
- /** find_tools activated more tools (large-catalogue search mode). */
2016
- | {
2017
- type: 'tools.discovered';
2018
- step?: IPlanStep;
2105
+ interface ISearchRequestInput {
2106
+ provider: SearchProvider;
2019
2107
  query: string;
2020
- names: string[];
2108
+ maxResults: number;
2109
+ freshness?: SearchFreshness;
2110
+ apiKey?: string;
2111
+ baseURL?: string;
2112
+ /** The Gemini model that makes the grounding call (default SEARCH_GOOGLE_DEFAULT_MODEL). */
2113
+ model?: string;
2114
+ /** The current time in ms, for `freshness` (this file reads no clock). */
2115
+ now?: number;
2021
2116
  }
2022
- /** A tool call is waiting for the user's consent (see `toolApproval`). */
2023
- | {
2024
- type: 'tool.approval-requested';
2025
- id: string;
2026
- name: string;
2027
- input: unknown;
2028
- readOnly: boolean;
2029
- step?: IPlanStep;
2030
- /** Set when a helper the model started is asking (see `ToolApprovalRequest.subagent`). */
2031
- subagent?: {
2032
- id: string;
2033
- depth: number;
2034
- };
2035
- /**
2036
- * Set when an MCP App asks (`Agent.approveAppToolCall`), not the model: the app's server,
2037
- * the tool's own name there and the app's `ui://` resource (see `ToolApprovalRequest.app`).
2038
- */
2039
- app?: ToolApprovalApp;
2040
- /** See `ToolApprovalRequest.mcpSkills`. */
2041
- mcpSkills?: string[];
2042
- /**
2043
- * Set when the request is about an MCP server's skill about to enter the model's context,
2044
- * not a tool call (see `ToolApprovalRequest.skill`): the server's words, as plain text.
2045
- */
2046
- skill?: McpSkillConsentView;
2117
+ /** What a search spent in model tokens, as the API reported it. */
2118
+ interface ISearchUsage {
2119
+ inputTokens: number;
2120
+ outputTokens: number;
2121
+ totalTokens: number;
2122
+ reasoningTokens: number;
2047
2123
  }
2048
- /** A consent decision: from the user, or `automatic` (policy denial). */
2049
- | {
2050
- type: 'tool.approval-resolved';
2051
- id: string;
2052
- name: string;
2053
- approved: boolean;
2054
- reason?: string;
2055
- automatic: boolean;
2124
+ /** A provider's answer, parsed: raw third-party values until `sanitizeSearchResults`. */
2125
+ interface ISearchAnswer {
2126
+ results: unknown[];
2127
+ /** The grounding model's whole answer (raw). */
2128
+ summary?: unknown;
2129
+ /** Absent when the API reported none. */
2130
+ usage?: ISearchUsage;
2056
2131
  }
2057
2132
  /**
2058
- * An MCP server asked the user for input during a tool call (the connection's `onElicitation`
2059
- * is being called). `message`, `requestedSchema` and `url` are the SERVER's text: cleaned and
2060
- * capped, for a UI to show - never instructions.
2133
+ * The request for one query, per the Gemini API's public documentation:
2134
+ * POST {base}/v1beta/models/{model}:generateContent header x-goog-api-key
2135
+ * { systemInstruction, contents: [the query], tools: [{ google_search }], generationConfig }
2136
+ * The query is the only text of the conversation in it. The API has no result count: the list
2137
+ * is cut on the way back.
2061
2138
  */
2062
- | {
2063
- type: 'mcp.elicitation-requested';
2064
- id: string;
2065
- server: string;
2066
- /** The tool call that asks: the tool's name as the model called it. */
2067
- tool: string;
2068
- mode: 'form' | 'url';
2069
- message: string;
2070
- requestedSchema?: McpElicitationSchema;
2071
- url?: string;
2072
- step?: IPlanStep;
2073
- /** Set when a helper (a subagent) is the one whose call asks. */
2074
- subagent?: {
2075
- id: string;
2076
- depth: number;
2077
- };
2078
- }
2139
+ declare const buildSearchRequest: (input: ISearchRequestInput) => ISearchRequest;
2079
2140
  /**
2080
- * The question was answered. Never carries a value the user entered: `fields` are the NAMES
2081
- * of the fields an accepted form was answered with. `automatic`: nobody decided (a guard, a
2082
- * cap, a timeout, a failed handler, a stopped run) - `reason` says which, the tool call
2083
- * fails, and no `mcp.elicitation-requested` may have preceded it.
2141
+ * What a grounded answer holds, mapped to results of `{ title, url, snippet }` and nothing else,
2142
+ * the model's answer, and what the call spent. A source is a `groundingChunks[].web` (`uri` is a
2143
+ * Google redirect link, `title` the site's name); its snippet is the pieces of the answer that
2144
+ * `groundingSupports` attribute to it (fragments as the API cut them, joined with an ellipsis). Still raw third-party values: `sanitizeSearchResults` is
2145
+ * what makes them safe to show.
2084
2146
  */
2085
- | {
2086
- type: 'mcp.elicitation-answered';
2087
- id: string;
2088
- server: string;
2089
- tool: string;
2090
- action: 'accept' | 'decline' | 'cancel';
2091
- automatic: boolean;
2092
- reason?: McpElicitationReason;
2093
- fields?: string[];
2094
- }
2147
+ declare const parseSearchResponse: (provider: SearchProvider, json: unknown) => ISearchAnswer;
2095
2148
  /**
2096
- * A tool that declares an MCP App (`_meta.ui.resourceUri`) returned a result, on a connection
2097
- * made with `apps: true` (`./mcp`): a UI can show the app next to the call. `tool` is the name
2098
- * the model called, `toolName` the server's own; `input` the call's arguments; `result` what
2099
- * the app is given (`content`, `structuredContent`, `isError`, `_meta`), absent when it was
2100
- * larger than `MCP_APP_MAX_RESULT_CHARS`. The app's HTML is never in an event: read it with
2101
- * the connection's `apps.readUiResource(server, resourceUri)`.
2149
+ * What a failed call says to the model: the provider, the model, the status, the API's own error
2150
+ * code word and what it usually means. Never the error's text: that is third-party text, and may
2151
+ * echo what was sent. `body` is the parsed error body, if there was one.
2102
2152
  */
2103
- | {
2104
- type: 'mcp.app';
2105
- id: string;
2106
- server: string;
2107
- tool: string;
2108
- toolName: string;
2109
- resourceUri: string;
2110
- input: Record<string, unknown>;
2111
- result?: McpAppToolResult;
2112
- step?: IPlanStep;
2153
+ declare const searchStatusMessage: (provider: SearchProvider, status: number, model?: string, body?: unknown) => string;
2154
+ interface ISanitizedSearch {
2155
+ results: ISearchResult[];
2156
+ /** Results dropped because the host's egress policy does not let the model reach them. */
2157
+ filtered: number;
2158
+ /** True when results were left out for a cap (the count, or the total size). */
2159
+ truncated: boolean;
2113
2160
  }
2114
2161
  /**
2115
- * `profile` is set when the parent chose one of the subagent's named profiles for this call.
2116
- * The tree: `parentId` is the id of the subagent that made the call, or the `runId` of the run
2117
- * when the run itself made it; `depth` is 1 for the run's own subagents, 2 for theirs, ...
2118
- * `dynamic` marks a helper the model started with `spawn_subagent` (`subagents.dynamic`):
2119
- * `role` is what the model wrote for it, `tools` the tool names it was given.
2162
+ * What a model sees of an engine's answer. `raw` is whatever came back - nothing about it is
2163
+ * trusted: a result needs a valid http(s) URL, every field is cleaned and capped, duplicates go,
2164
+ * `accepts` (the egress policy; it is also handed the result's raw title) drops links the model
2165
+ * could not fetch, and the list stops at `maxResults` and at SEARCH_MAX_TOTAL_CHARS.
2120
2166
  */
2121
- | {
2122
- type: 'subagent.start';
2123
- id: string;
2124
- name: string;
2125
- task: string;
2126
- profile?: string;
2127
- parentId?: string;
2128
- depth?: number;
2129
- dynamic?: true;
2130
- role?: string;
2131
- tools?: string[];
2132
- }
2133
- /** An event of a running subagent, forwarded verbatim. */
2134
- | {
2135
- type: 'subagent.event';
2136
- id: string;
2137
- name: string;
2138
- event: AgentEvent;
2139
- } | {
2140
- type: 'subagent.complete';
2141
- id: string;
2142
- name: string;
2143
- text: string;
2144
- usage: IUsage;
2167
+ declare const sanitizeSearchResults: (raw: unknown, options?: {
2168
+ maxResults?: number;
2169
+ accepts?: (url: URL, title: unknown) => boolean;
2170
+ }) => ISanitizedSearch;
2171
+ /** What `web_search` returns to the model. */
2172
+ interface ISearchToolResult {
2173
+ query: string;
2174
+ results: ISearchResult[];
2175
+ /** The google provider, when no source came with a snippet: the grounding model's answer, cut. */
2176
+ summary?: string;
2177
+ /** The google provider: what its URLs and its text are. */
2178
+ note?: string;
2179
+ filtered?: number;
2180
+ truncated?: true;
2181
+ untrusted: true;
2145
2182
  }
2146
2183
  /**
2147
- * `stopped` is set when the user stopped this subagent (`RunControl.stopSubagent`), as opposed
2148
- * to it failing. `usage`: what a dynamic helper had spent when it failed (already charged to
2149
- * the parent).
2184
+ * The tool's result, from the cleaned list and - for the google provider - the parsed answer.
2185
+ * The model's `summary` is attached only when there are sources, none of them carries a snippet
2186
+ * and none was filtered out: a summary cannot be cut to the sources that remain.
2150
2187
  */
2151
- | {
2152
- type: 'subagent.error';
2153
- id: string;
2154
- name: string;
2155
- error: string;
2156
- stopped?: boolean;
2157
- usage?: IUsage;
2158
- }
2188
+ declare const searchToolResult: (query: string, clean: ISanitizedSearch, answer?: ISearchAnswer) => ISearchToolResult;
2189
+
2159
2190
  /**
2160
- * A request of the `web_fetch` tool, or of `web_search` to its search API, allowed or refused
2161
- * by the egress policy. `url` is origin and path only (a query string can carry a secret).
2191
+ * `config.search`: the `web_search` tool, the companion of `web_fetch`. Off unless set. The
2192
+ * library ships no key: the host passes a search engine of its own (a function - any search API)
2193
+ * or names the one built-in provider, Google Search through Gemini grounding. Browser sibling of
2194
+ * the server's `ISearchConfig` - same names - except that a key is never written here:
2195
+ * `credentialRef` names it in the `CredentialStore` the agent was given (`config.credentials`).
2196
+ *
2197
+ * The Gemini API answers a page directly (CORS). See docs/capabilities.md.
2162
2198
  */
2163
- | {
2164
- type: 'egress.request';
2165
- url: string;
2166
- allowed: boolean;
2167
- status?: number;
2168
- reason?: string;
2199
+ interface ISearchConfig {
2200
+ /**
2201
+ * A search engine of your own: `(query, { maxResults, freshness, signal }) => results`. Its
2202
+ * requests are yours (like a tool you pass); its results are cleaned, capped and filtered like
2203
+ * the provider's. Exactly one of `engine` / `provider`.
2204
+ */
2205
+ engine?: SearchEngine;
2206
+ /**
2207
+ * The built-in provider: 'google' - Google Search through the Gemini API's grounding. One
2208
+ * generateContent call per search with the `google_search` tool: it needs a Gemini (Google AI
2209
+ * Studio) key and nothing else, and it spends that model's tokens (counted in the run's usage,
2210
+ * phase 'search'). Result URLs are Google redirect links, snippets the model's own summary.
2211
+ */
2212
+ provider?: SearchProvider;
2213
+ /**
2214
+ * Where the Gemini API key is kept in the agent's `CredentialStore` (it can be the ref of a
2215
+ * Gemini model's own key). Read at each call and sent in a header to that API only; never in a
2216
+ * URL, an event, a log line, an error or a result.
2217
+ */
2218
+ credentialRef?: string;
2219
+ /** The Gemini model that makes the grounding call. Default 'gemini-2.5-flash-lite'. */
2220
+ model?: string;
2221
+ /**
2222
+ * Replaces the public endpoint (a gateway of yours that holds the key - `credentialRef` is
2223
+ * then optional).
2224
+ */
2225
+ baseURL?: string;
2226
+ /** Results per call when the model does not say (default 5, at most 10). */
2227
+ maxResults?: number;
2228
+ /**
2229
+ * Let the SEARCH API itself be on a private / loopback address or an internal-looking name (a
2230
+ * gateway of yours). It widens nothing else: the request can still reach only that one host.
2231
+ */
2232
+ allowPrivateNetwork?: boolean;
2233
+ /** Whole request to the search API, in ms. Default 15_000. */
2234
+ timeoutMs?: number;
2235
+ /**
2236
+ * How the consent gate sees a search. Default true (read-only: the only host reached is the one
2237
+ * named here). false = it asks like a write - a query is text that leaves for a third party.
2238
+ */
2239
+ readOnly?: boolean;
2240
+ /** The fetch the adapter uses (default `globalThis.fetch`). Still bound to the search policy. */
2241
+ fetch?: typeof fetch;
2169
2242
  }
2170
- /** A message sent with `RunControl.send` is waiting for the next boundary. */
2171
- | {
2172
- type: 'message.queued';
2173
- id: string;
2174
- text: string;
2243
+ interface IWebSearchOptions {
2244
+ search: ISearchConfig;
2245
+ /** `config.egress`, when the agent has it: its deny list is inherited, and results the model could not fetch under it are left out. */
2246
+ egress?: boolean | IEgressPolicy;
2247
+ /** Where `search.credentialRef` is looked up (`config.credentials`). */
2248
+ credentials?: CredentialStore;
2249
+ /** A fetch of your own for the adapter's request (already bound to a policy). */
2250
+ fetch?: GuardedFetch;
2175
2251
  }
2176
2252
  /**
2177
- * The message reached the model. `round` = between tool-calling rounds inside a step, so
2178
- * the rest of that step can act on it (the replanner weighs it at the end of the step);
2179
- * `step` = at a step boundary, where it forces the replanner to look at the plan;
2180
- * `final` = just before the answer is written.
2253
+ * The policy the adapter's one request is made under. It is NOT the model's egress policy with a
2254
+ * host added: the allow list is exactly the search API's host, scheme and port, so the tool
2255
+ * cannot be steered anywhere else (a redirect is never followed), and the host's deny list
2256
+ * still wins.
2181
2257
  */
2182
- | {
2183
- type: 'message.delivered';
2184
- id: string;
2185
- text: string;
2186
- at: 'round' | 'step' | 'final';
2187
- } | {
2188
- type: 'stopped';
2189
- } | {
2190
- type: 'error';
2191
- phase: Phase | 'run';
2192
- error: string;
2193
- }
2194
- /** A pipeline's own events (`createPipeline`): the run, each node visit, each edge decision. */
2195
- | PipelineEvent;
2258
+ declare const searchEgressPolicy: (search: ISearchConfig, egress?: boolean | IEgressPolicy) => IEgressPolicy;
2196
2259
  /**
2197
- * `nodeId` / `visit` are set on the events a pipeline forwards from a node's agent (and on the
2198
- * `pipeline.node.*` events themselves).
2260
+ * `web_search({ query })`: a short list of `{ title, url, snippet, date? }`. The adapter's
2261
+ * request goes through the guarded fetch under `searchEgressPolicy`; what comes back is
2262
+ * third-party text and is cleaned, capped and - when the agent has an egress policy - filtered
2263
+ * to what `web_fetch` could open, so a search is not a way to read around the allow / deny lists.
2264
+ *
2265
+ * The google provider's links are Google redirect links: the filter can judge only that host
2266
+ * (plus the site the API names, which is enough to drop a denied site and never to allow one).
2267
+ * Nothing here follows them. `web_fetch` opens one only under `egress.followRedirects` (the
2268
+ * guarded fetch then judges where it ended) and, from a page, only through an `egress.fetch`
2269
+ * of the host's: the redirect host sends no CORS headers.
2199
2270
  */
2200
- type AgentEvent = AgentEventBody & {
2201
- nodeId?: string;
2202
- visit?: number;
2203
- };
2204
- type AgentEventHandler = (event: AgentEvent) => void;
2271
+ declare const createWebSearchTool: (options: IWebSearchOptions) => AgentTool;
2272
+ /** The tools `config.search` turns on (none when it is off). */
2273
+ declare const createSearchTools: (search: ISearchConfig | undefined, egress?: boolean | IEgressPolicy, credentials?: CredentialStore) => AgentToolSet | undefined;
2205
2274
 
2206
2275
  /**
2207
2276
  * Attachments sent with a run: images, PDFs and other files the provider can
@@ -2727,6 +2796,33 @@ interface BrowserAgentConfig {
2727
2796
  * see `RunSnapshot` for exactly what is, and is not, kept.
2728
2797
  */
2729
2798
  persistence?: RunPersistence;
2799
+ /**
2800
+ * One session, one runner across the origin's tabs. With a `memory` the tabs share
2801
+ * (`IndexedDBStore` - its `dbName`), a run holds the session's Web Lock for its whole duration,
2802
+ * and the tab holding it relays the run to the other tabs (`watchSession`). A second run of the
2803
+ * same session - in another tab, or in this one:
2804
+ * - `'wait'` (default): waits for the first to end - `session.busy` says so (and where it runs),
2805
+ * `session.acquired` when it may go; it reads the session's memory only then. Stopping the run
2806
+ * ends the wait.
2807
+ * - `'fail'`: `run()` throws `SessionBusyError` at once; nothing of the run happens.
2808
+ * - `'off'`: no lock and no relay - two tabs may run one session at once (the last write wins).
2809
+ *
2810
+ * Without a shared `memory` (an in-memory store, or none) nothing is locked. Without
2811
+ * `navigator.locks` nothing is locked either (one warning). A subagent of the run that uses the
2812
+ * same session runs under the run's hold. See docs/capabilities.md, "Several tabs".
2813
+ */
2814
+ sessionLock?: SessionLockMode;
2815
+ /**
2816
+ * What the tab that holds a session's lock offers the site's other tabs (`watchSession`).
2817
+ * Default `{ control: true }`: the run is relayed - its events, once a tab asks (nothing is
2818
+ * posted before), and a replay for a tab that joins late - and another tab may send it a message
2819
+ * (marked `origin: 'another-tab'` on `message.queued` / `message.delivered`) or stop it, through
2820
+ * the run's `control` (a run without one takes no message). `{ control: false }`: watched, never
2821
+ * steered. `false`: the lock only, nothing relayed. See docs/security.md, "Several tabs".
2822
+ */
2823
+ sessionRelay?: false | {
2824
+ control?: boolean;
2825
+ };
2730
2826
  /** Hard cap on executed steps incl. replans (default 8). */
2731
2827
  maxIterations?: number;
2732
2828
  /** Cap on tool-calling rounds inside one executor call, both modes (default 4). */
@@ -2892,82 +2988,6 @@ declare const renderSearchCatalog: (catalog: ToolCatalogEntry[], budget?: number
2892
2988
  */
2893
2989
  declare const createFindToolsTool: (catalog: () => ToolCatalogEntry[], onFound: (query: string, names: string[]) => void, hintOf?: (name: string) => string | undefined) => Tool;
2894
2990
 
2895
- /**
2896
- * Steering a run that is already going.
2897
- *
2898
- * `run()` takes one goal and returns when the run is over, so a host that wants to
2899
- * say something mid-run — "actually use the staging database" — or stop one
2900
- * subagent out of several has nothing to call. A `RunControl` is the handle: create
2901
- * one, pass it as `run(goal, { control })`, and use it from anywhere while the run
2902
- * is in flight.
2903
- *
2904
- * A message is not interrupt. The run never cuts a tool call short (it may be a
2905
- * write): the message is held until the next boundary — the next tool-calling round
2906
- * inside a step, or the end of the step — and is then shown to the model. At a step
2907
- * boundary it also forces the replanner to look at the plan again, because a plan
2908
- * made before the user spoke may no longer be the right one.
2909
- */
2910
- /** One running subagent, as the host sees it. */
2911
- interface SubagentInfo {
2912
- id: string;
2913
- /** The subagent tool's `name`. */
2914
- name: string;
2915
- task: string;
2916
- /** The profile the parent chose for this call, when it chose one. */
2917
- profile?: string;
2918
- startedAt: number;
2919
- /** The subagent that started it; absent when the run itself did. */
2920
- parentId?: string;
2921
- /** 1 for the run's own subagents, 2 for theirs, ... (set for helpers the model started). */
2922
- depth?: number;
2923
- /** Set for a helper the model started with spawn_subagent: the role it was given, if any. */
2924
- dynamic?: true;
2925
- role?: string;
2926
- }
2927
- interface RunControl {
2928
- /**
2929
- * Queue a message for the run. `false` when there is nothing to deliver it to — the text
2930
- * is empty, or the run has already finished (send it as a new run instead).
2931
- *
2932
- * Accepted does not mean delivered: a message that arrives after the last boundary
2933
- * (while the answer is being written) comes back in `RunResult.undelivered`, so the
2934
- * host can send it next.
2935
- */
2936
- send(text: string): boolean;
2937
- /**
2938
- * Messages sent and not yet delivered. Once the run is over: the ones it never got to show
2939
- * the model (the same list as `RunResult.undelivered`, which a run that threw cannot return).
2940
- */
2941
- pending(): string[];
2942
- /** The subagents running under this run right now (a snapshot; `subagent.*` events are the stream). */
2943
- subagents(): SubagentInfo[];
2944
- /**
2945
- * Stop ONE running subagent. Its delegation fails with a message the parent model can
2946
- * route around, and the run carries on — unlike aborting the run, which stops everything.
2947
- * `false` when no subagent with that id is running.
2948
- */
2949
- stopSubagent(id: string): boolean;
2950
- }
2951
- interface QueuedMessage {
2952
- id: string;
2953
- text: string;
2954
- }
2955
- /** What the runner and the subagent tool use; deliberately not part of the public surface. */
2956
- interface RunControlPort {
2957
- /** The run starts reading: from now on `send` announces itself. */
2958
- attach(emit: (event: AgentEvent) => void): void;
2959
- /**
2960
- * The run is over: whatever is still queued is returned, for the host to send as a
2961
- * follow-up. It stays readable through `pending()` until the control serves another run.
2962
- */
2963
- detach(): string[];
2964
- /** Take every queued message, oldest first. */
2965
- drain(): QueuedMessage[];
2966
- /** A subagent started under this run; returns what unregisters it. */
2967
- registerSubagent(info: SubagentInfo, stop: () => void): () => void;
2968
- }
2969
- declare const createRunControl: () => RunControl;
2970
-
2971
2991
  declare const MODEL_TIERS: readonly ModelTier[];
2972
2992
  /**
2973
2993
  * The tier a step runs on. The planner's complexity names the tier it wants (low -> light,
@@ -3204,6 +3224,14 @@ interface RunOptions {
3204
3224
  * planning again. Attachments are not stored: pass them again if the run needs them.
3205
3225
  */
3206
3226
  resumeFromRunId?: string;
3227
+ /**
3228
+ * A fresh run's id, in place of a random one: a host that keys runs by ids of its own (a
3229
+ * session and a turn) gives one, so that a retry finds the same run. 1-128 letters, digits,
3230
+ * `_` or `-`, as every run id. Refused - thrown before anything of the run - together with
3231
+ * `resumeFromRunId`, and when `persistence.loadRun` has a snapshot for it (resume that run
3232
+ * instead): a run on record is never written over.
3233
+ */
3234
+ runId?: string;
3207
3235
  /**
3208
3236
  * Steer the run while it goes: `control.send(text)` puts a message in front of the model
3209
3237
  * at the next boundary, `control.stopSubagent(id)` stops one subagent. Make it with
@@ -3253,6 +3281,11 @@ interface CompactOptions {
3253
3281
  signal?: AbortSignal;
3254
3282
  /** Compact even when below the threshold (default true for a manual call). */
3255
3283
  force?: boolean;
3284
+ /**
3285
+ * With a session lock (`sessionLock`, a shared `memory`): wait for a run of the session that is
3286
+ * going (default true; `signal` ends the wait), or `false` - throw `SessionBusyError` at once.
3287
+ */
3288
+ wait?: boolean;
3256
3289
  }
3257
3290
  interface CompactResult {
3258
3291
  compacted: boolean;
@@ -3302,6 +3335,13 @@ interface Agent {
3302
3335
  * Pass `onEvent` to receive the `skill.forgotten` event.
3303
3336
  */
3304
3337
  forgetSkill(name: string, onEvent?: (event: AgentEvent) => void): Promise<boolean>;
3338
+ /**
3339
+ * Read the lessons' store again - another tab wrote to it (a `skills` notice, see
3340
+ * `onStorageChange`): the agent's own lessons are added, replaced or dropped to match it; a
3341
+ * host's skill is never touched. Resolves with the lessons (`listLearnedSkills()`). Without
3342
+ * `config.learning`: an empty list.
3343
+ */
3344
+ reloadLearnedSkills(): Promise<Skill[]>;
3305
3345
  /**
3306
3346
  * Ask this agent's consent gate about a tool call an MCP App wants to make (`./mcp` with
3307
3347
  * `apps: true`: the app's `tools/call`), not the model. The same `toolApproval` - its rules,
@@ -3608,7 +3648,9 @@ findings?: string[]) => Promise<{
3608
3648
  /**
3609
3649
  * A pipeline: a graph of agents with conditions and loops, described in plain JSON. The graph
3610
3650
  * engine (validation, conditions, scheduling) is `engine.ts`, the same file as the Node
3611
- * sibling's; this file is the adapter that runs a node with this package's createAgent.
3651
+ * sibling's; this file is the adapter that runs a node with this package's createAgent, and the
3652
+ * route call after it (`pickPipelineRoute`, public for hosts that run the graph themselves with
3653
+ * `runPipelineGraph`).
3612
3654
  */
3613
3655
  interface PipelineOptions {
3614
3656
  /** The seam: run a node yourself. When given, the pipeline knows nothing about agents. */
@@ -3636,6 +3678,33 @@ interface Pipeline {
3636
3678
  /** Drop the node agents. The pipeline can run again: agents are created anew. */
3637
3679
  close: () => Promise<void>;
3638
3680
  }
3681
+ interface PipelineRouteOptions {
3682
+ /**
3683
+ * The node's agent: its planner model picks the route (structured output, then plain text), its
3684
+ * decision model (`config.decisionModel`, resolved) is asked first.
3685
+ */
3686
+ agent: Agent;
3687
+ /** The config that agent was built from: the budget, temperature, timeout and `decision`. */
3688
+ config: BrowserAgentConfig;
3689
+ signal?: AbortSignal;
3690
+ /** A decision model's `usage` and `decision` events. A handler that throws breaks nothing. */
3691
+ onEvent?: AgentEventHandler;
3692
+ }
3693
+ interface PipelineRouteResult {
3694
+ /** One of the node's labels, or undefined: no route. */
3695
+ route?: string;
3696
+ /** What the call cost, a failed attempt and a decision model's question included. */
3697
+ usage: IUsage;
3698
+ }
3699
+ /**
3700
+ * The route call createPipeline makes after a node with routes answered, as a function of its
3701
+ * own: a host that runs the graph itself (`runPipelineGraph`) calls it wherever the node ran, with
3702
+ * the node's answer. The node's decision model first, when it is confident of a label; otherwise
3703
+ * the node's planner model (structured output, then plain text). An answer that is not one of the
3704
+ * labels, or a call that fails, is no route (`route` undefined); an abort rejects with an
3705
+ * AbortError. A node without routes costs nothing.
3706
+ */
3707
+ declare const pickPipelineRoute: (node: PipelineNode, text: string, options: PipelineRouteOptions) => Promise<PipelineRouteResult>;
3639
3708
  declare const createPipeline: (definition: PipelineDefinition, options: PipelineOptions) => Pipeline;
3640
3709
  interface NodeResolverOptions {
3641
3710
  /**
@@ -4478,6 +4547,11 @@ interface ToolRunContext {
4478
4547
  * starts inherits it.
4479
4548
  */
4480
4549
  mcpSkills?: () => string[];
4550
+ /**
4551
+ * Internal - the session locks the run holds (its own and its callers', `sessionLock`): an
4552
+ * in-process subagent runs under them rather than wait for its own parent.
4553
+ */
4554
+ sessionLocks?: () => readonly string[];
4481
4555
  }
4482
4556
  /** Read the run context the agent passes to a tool's execute (undefined outside a run). */
4483
4557
  declare const toolRunContextOf: (options: unknown) => ToolRunContext | undefined;
@@ -4502,9 +4576,15 @@ interface IndexedDBStoreOptions {
4502
4576
  * IndexedDB-backed transcript store — one record (message array) per session,
4503
4577
  * in the shared `sessions` object store (see storage/db.ts). Also exposes
4504
4578
  * session utilities: list and delete.
4579
+ *
4580
+ * Shared by every tab of the origin: a run of a session holds the session's lock while it goes
4581
+ * (`sessionLock`), and each committed write tells the other tabs which session changed (a
4582
+ * `session` notice, see `onStorageChange`).
4505
4583
  */
4506
4584
  declare class IndexedDBStore implements ContextStore {
4507
- private readonly dbName?;
4585
+ /** The database it lives in - and the name its tabs share it under (`sessionLock`, notices). */
4586
+ readonly dbName: string;
4587
+ private readonly tab;
4508
4588
  constructor(opts?: IndexedDBStoreOptions);
4509
4589
  load(sessionId: string): Promise<StoredMessage[]>;
4510
4590
  replace(sessionId: string, messages: StoredMessage[]): Promise<void>;
@@ -4532,6 +4612,8 @@ declare class MemoryRunStore implements RunPersistence {
4532
4612
  constructor(opts?: RunStoreOptions);
4533
4613
  onRunStart(snapshot: RunSnapshot): void;
4534
4614
  onStepComplete(snapshot: RunSnapshot): void;
4615
+ /** A resume started: its attempt is on record before any of its events. */
4616
+ onRunResume(snapshot: RunSnapshot): void;
4535
4617
  onRunComplete(snapshot: RunSnapshot): void;
4536
4618
  loadRun(runId: string): RunSnapshot | null;
4537
4619
  /** Runs that can still be resumed (executing, stopped or failed), newest first. */
@@ -4558,12 +4640,16 @@ interface IndexedDBRunStoreOptions extends RunStoreOptions {
4558
4640
  * ```
4559
4641
  */
4560
4642
  declare class IndexedDBRunStore implements RunPersistence {
4561
- private readonly dbName?;
4643
+ /** The database it lives in, and the name its change notices (`runs`) go out under. */
4644
+ readonly dbName: string;
4562
4645
  private readonly keepCompleted;
4646
+ private readonly tab;
4563
4647
  constructor(opts?: IndexedDBRunStoreOptions);
4564
4648
  private put;
4565
4649
  onRunStart(snapshot: RunSnapshot): Promise<void>;
4566
4650
  onStepComplete(snapshot: RunSnapshot): Promise<void>;
4651
+ /** A resume started: its attempt is on record before any of its events. */
4652
+ onRunResume(snapshot: RunSnapshot): Promise<void>;
4567
4653
  onRunComplete(snapshot: RunSnapshot): Promise<void>;
4568
4654
  loadRun(runId: string): Promise<RunSnapshot | null>;
4569
4655
  /** Runs that can still be resumed (executing, stopped or failed), newest first. */
@@ -4574,5 +4660,53 @@ declare class IndexedDBRunStore implements RunPersistence {
4574
4660
  clear(): Promise<void>;
4575
4661
  }
4576
4662
 
4577
- export { APP_SAMPLING_MAX_IMAGES, APP_SAMPLING_MAX_IMAGE_BYTES, APP_SAMPLING_MAX_INPUT_CHARS, APP_SAMPLING_MAX_MESSAGES, APP_SAMPLING_MAX_SYSTEM_CHARS, APP_SAMPLING_MAX_TOKENS, APP_SAMPLING_PER_APP, APP_SAMPLING_PER_MINUTE, APP_SAMPLING_REASONING_TOKENS, APP_SAMPLING_RPC_CODES, AgentTool, AgentToolSet, AppSamplingError, 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, McpAppToolResult, McpElicitationReason, McpElicitationSchema, McpSkillConsent, McpSkillConsentView, 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_GOOGLE_DEFAULT_MODEL, SEARCH_GOOGLE_NOTE, SEARCH_MAX_QUERY_CHARS, SEARCH_MAX_RESULTS, SEARCH_MAX_SNIPPET_CHARS, SEARCH_MAX_SUMMARY_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_APPROVAL_TIMEOUT_MS, 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, appSamplingRequestOf, appSamplingText, askDecisionModel, attachmentKind, buildMediaModelFromSpec, buildModelFromStage, buildSearchRequest, bytesToBase64, checkEgressUrl, checkLimits, classifyAddress, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createAppSamplingLimiter, 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, isCodeExecutionTool, isDirectModel, isEscalatableError, isImageRefusal, isProviderSpec, isReadOnlyTool, isReplayedToolOutput, isTextMime, isWebGPUAvailable, learnedPreamble, limitModelOutput, loadSkillFromUrl, looksLikeJson, markCodeExecution, 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, resolveAppSampling, resolveBudgets, resolveCaching, resolveCompaction, resolveConfig, resolveDecisionModel, resolveDynamicSubagents, resolveEgressPolicy, resolveEscalation, resolveModel, resolveResume, resolveStage, resolveThinking, runToolLoop, sanitizeSearchResults, schemaHintOf, searchEgressPolicy, searchStatusMessage, searchToolResult, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, skillPreamble, sniffMediaType, splitBlocker, stageOutputCap, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, testPipelineCondition, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, validatePipeline, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow, wrapTranscript };
4578
- export type { Agent, AgentContext, AgentEvent, AgentEventHandler, AgentLogger, AgentLoggerSink, AgentWebDBOptions, AppSamplingErrorCode, AppSamplingImage, AppSamplingMessage, AppSamplingOptions, AppSamplingRequest, AppSamplingResult, AppSamplingSettings, AppSamplingView, AppToolCallRequest, 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, ISearchAnswer, ISearchConfig, ISearchOptions, ISearchRequest, ISearchResult, ISearchToolResult, ISearchUsage, IStepEscalation, IStepResult, ISubagentsConfig, IToolCall, ITranscription, IUsage, IWebFetchOptions, IWebSearchOptions, IndexedDBRunStoreOptions, IndexedDBStoreOptions, Learning, LearningConfig, LimitBreach, LimitKind, LoadSkillOptions, LogLevel, McpSkillOrigin, 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, ToolApprovalApp, ToolApprovalConfig, ToolApprovalContext, ToolApprovalDecision, ToolApprovalMode, ToolApprovalRequest, ToolCallMode, ToolCatalogEntry, ToolLoopCallbacks, ToolLoopOptions, ToolLoopResult, ToolMode, ToolPermission, ToolResultClearing, ToolRunContext, ToolSelectionStrategy, UsagePhase, VfsListener, VirtualFile, VirtualFileInfo, VirtualFileSystemOptions, WebLLMAppConfigLike, WebLLMModelOptions, WorkerLike, WorkerToParent };
4663
+ /**
4664
+ * Change notices: after a write to IndexedDB COMMITS, the store that made it tells the other tabs
4665
+ * of the origin "this changed" - never what it changed to. A notice carries the kind of store, the
4666
+ * operation and at most a name (a path, a session id); never a value, a file's content, a message,
4667
+ * a key. A tab that hears one reads the store again if it shows that data.
4668
+ *
4669
+ * One channel per database name (`dbName`), so two apps on one origin with different databases
4670
+ * never hear each other. A tab does not hear its own notices. Nothing is sent from an in-memory
4671
+ * store (nothing is shared), and nothing anywhere without BroadcastChannel.
4672
+ */
4673
+ /**
4674
+ * The stores that announce their writes:
4675
+ * - `credentials` - `VaultCredentialStore` (an API key stored or removed). No `key`.
4676
+ * - `oauth` - `VaultOAuthStorage` (an MCP server's OAuth record). No `key`.
4677
+ * - `files` - `VirtualFileSystem`: `key` = the path, `namespace` = the file system's namespace.
4678
+ * - `session` - `IndexedDBStore` (the agent's memory): `key` = the session id.
4679
+ * - `runs` - `IndexedDBRunStore` (checkpoints): `key` = the run id.
4680
+ * - `skills` - `VfsSkillStore` (the agent's lessons): `key` = the lesson's name, `namespace` =
4681
+ * the store's folder.
4682
+ * - `chats` - the React package's `ChatHistoryStore`: `key` = the chat id.
4683
+ */
4684
+ type StorageChangeKind = 'credentials' | 'oauth' | 'files' | 'session' | 'runs' | 'skills' | 'chats';
4685
+ /** `put` = written (created or replaced), `delete` = one removed, `clear` = all of them removed. */
4686
+ type StorageChangeOp = 'put' | 'delete' | 'clear';
4687
+ interface StorageChange {
4688
+ kind: StorageChangeKind;
4689
+ op: StorageChangeOp;
4690
+ /** Which one (see `StorageChangeKind`); absent for `clear` and for the kinds that carry none. */
4691
+ key?: string;
4692
+ /** `files`: the file system's namespace; `skills`: the store's folder. */
4693
+ namespace?: string;
4694
+ }
4695
+ declare const STORAGE_CHANGE_KINDS: readonly StorageChangeKind[];
4696
+ /**
4697
+ * Tell the other tabs that a store in database `dbName` changed - for a store of your own on
4698
+ * IndexedDB (the built-in ones post their own). Call it AFTER the write committed. Never put a
4699
+ * value in it: a notice says which, not what. A no-op without `dbName` or BroadcastChannel; a
4700
+ * notice of the wrong shape is dropped.
4701
+ */
4702
+ declare const postStorageChange: (dbName: string | undefined, change: StorageChange) => void;
4703
+ /**
4704
+ * Hear the OTHER tabs' notices for database `dbName` (default database of the built-in stores:
4705
+ * `'agent-web'`; the React package's chat history: `'agent-web-react'`). This tab's own writes
4706
+ * are not reported - you made them. Returns the unsubscribe. A no-op (and a no-op unsubscribe)
4707
+ * without `dbName` or BroadcastChannel.
4708
+ */
4709
+ declare const onStorageChange: (dbName: string | undefined, listener: (change: StorageChange) => void) => (() => void);
4710
+
4711
+ export { APP_SAMPLING_MAX_IMAGES, APP_SAMPLING_MAX_IMAGE_BYTES, APP_SAMPLING_MAX_INPUT_CHARS, APP_SAMPLING_MAX_MESSAGES, APP_SAMPLING_MAX_SYSTEM_CHARS, APP_SAMPLING_MAX_TOKENS, APP_SAMPLING_PER_APP, APP_SAMPLING_PER_MINUTE, APP_SAMPLING_REASONING_TOKENS, APP_SAMPLING_RPC_CODES, AgentTool, AgentToolSet, AppSamplingError, 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, McpAppToolResult, McpElicitationReason, McpElicitationSchema, McpSkillConsent, McpSkillConsentView, MediaBudgetError, MediaError, MemoryCredentialStore, MemoryRunStore, MemorySkillStore, MemoryStore, PipelineDefinition, PipelineEvent, PipelineNode, PipelineNodeRunner, PipelineResult, PlanSchema, PlanStepSchema, RELAY_MAX_REPLAYS_PER_SECOND, RELAY_MAX_SENDS, RELAY_MAX_SEND_CHARS, RELAY_MAX_STRING, REPLAY_NOTE, RUNS_STORE, ReplanSchema, SAVE_SKILL_TOOL, SEARCH_API_BASE_URL, SEARCH_DEFAULT_MAX_RESULTS, SEARCH_GOOGLE_DEFAULT_MODEL, SEARCH_GOOGLE_NOTE, SEARCH_MAX_QUERY_CHARS, SEARCH_MAX_RESULTS, SEARCH_MAX_SNIPPET_CHARS, SEARCH_MAX_SUMMARY_CHARS, SEARCH_MAX_TITLE_CHARS, SEARCH_MAX_TOTAL_CHARS, SEARCH_MAX_URL_CHARS, SEARCH_PROVIDERS, SECRETS_STORE, SESSIONS_STORE, SESSION_LOCK_MODES, SKILL_TOOL_NAMES, SPAWN_INPUT_SCHEMA, SPAWN_SUBAGENT_TOOL, STORAGE_CHANGE_KINDS, SUBAGENT_DEFAULTS, SUBAGENT_MAX_DEPTH_LIMIT, SessionBusyError, SubagentSpawnError, TOOL_APPROVAL_MODES, TOOL_APPROVAL_TIMEOUT_MS, 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, appSamplingRequestOf, appSamplingText, askDecisionModel, attachmentKind, buildMediaModelFromSpec, buildModelFromStage, buildSearchRequest, bytesToBase64, checkEgressUrl, checkLimits, classifyAddress, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createAppSamplingLimiter, 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, isCodeExecutionTool, isDirectModel, isEscalatableError, isImageRefusal, isProviderSpec, isReadOnlyTool, isReplayedToolOutput, isTextMime, isWebGPUAvailable, learnedPreamble, limitModelOutput, loadSkillFromUrl, looksLikeJson, markCodeExecution, markReadOnly, matchRule, mediaTypeOf, mediaUsageOf, mergeProviderOptions, mimeFromPath, nextStrongerTier, nodeResolver, normalizePath, normalizeSkillName, normalizeSteps, normalizeUsage, onStorageChange, openAgentWebDB, outputCapNotice, parseExecutorResponse, parsePlainText, parsePlannerResponse, parseReplannerResponse, parseSearchResponse, parseSkillMarkdown, pickPipelineRoute, pickTier, postStorageChange, preloadWebLLMModel, renderActiveSkills, renderCatalog, renderSearchCatalog, renderSkillIndex, replanWanted, resolveAppSampling, resolveBudgets, resolveCaching, resolveCompaction, resolveConfig, resolveDecisionModel, resolveDynamicSubagents, resolveEgressPolicy, resolveEscalation, resolveModel, resolveResume, resolveStage, resolveThinking, runToolLoop, sanitizeSearchResults, schemaHintOf, searchEgressPolicy, searchStatusMessage, searchToolResult, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, skillPreamble, sniffMediaType, splitBlocker, stageOutputCap, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, watchSession, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow, wrapTranscript };
4712
+ export type { Agent, AgentContext, AgentEvent, AgentEventHandler, AgentLogger, AgentLoggerSink, AgentWebDBOptions, AppSamplingErrorCode, AppSamplingImage, AppSamplingMessage, AppSamplingOptions, AppSamplingRequest, AppSamplingResult, AppSamplingSettings, AppSamplingView, AppToolCallRequest, 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, ISearchAnswer, ISearchConfig, ISearchOptions, ISearchRequest, ISearchResult, ISearchToolResult, ISearchUsage, IStepEscalation, IStepResult, ISubagentsConfig, IToolCall, ITranscription, IUsage, IWebFetchOptions, IWebSearchOptions, IndexedDBRunStoreOptions, IndexedDBStoreOptions, Learning, LearningConfig, LimitBreach, LimitKind, LoadSkillOptions, LogLevel, McpSkillOrigin, MediaImageModel, MediaKind, MediaModelKind, MediaSpeechModel, MediaTranscriptionModel, MessageEndpoint, ModelInput, ModelTier, NodeResolverOptions, OutputCap, ParentToWorker, Phase, PhaseBudgets, Pipeline, PipelineOptions, PipelineRouteOptions, PipelineRouteResult, PipelineRunOptions, 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, SessionHolder, SessionLockMode, SessionRunState, SessionWatch, Skill, SkillOrigin, SkillStore, StageInput, StageOverride, StepComplexity, StorageChange, StorageChangeKind, StorageChangeOp, StoredMessage, StructuredResult, SubagentDefaultTools, SubagentInfo, SubagentProfile, SubagentToolOptions, SubagentWorkerConfig, SynthesizerPromptContext, ThinkingConfig, ThinkingLevel, ThinkingSetting, ThinkingStage, TierReason, TokenLimits, ToolApprovalApp, ToolApprovalConfig, ToolApprovalContext, ToolApprovalDecision, ToolApprovalMode, ToolApprovalRequest, ToolCallMode, ToolCatalogEntry, ToolLoopCallbacks, ToolLoopOptions, ToolLoopResult, ToolMode, ToolPermission, ToolResultClearing, ToolRunContext, ToolSelectionStrategy, UsagePhase, VfsListener, VirtualFile, VirtualFileInfo, VirtualFileSystemOptions, WatchSessionOptions, WebLLMAppConfigLike, WebLLMModelOptions, WorkerLike, WorkerToParent };