@dudko.dev/agent-web 0.0.28 → 0.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -46,6 +46,102 @@ interface IStepResult {
46
46
  blocked: boolean;
47
47
  }
48
48
 
49
+ /**
50
+ * Run persistence: checkpoints a run so that a page reload, a crashed tab or a
51
+ * killed worker does not lose the work already done. Same hook names as the Node
52
+ * sibling (`@dudko.dev/agent`), where this contract originated.
53
+ *
54
+ * WHAT A CHECKPOINT IS. One is written when the plan is in hand (`onRunStart`)
55
+ * and again at the end of every iteration of the step loop (`onStepComplete`),
56
+ * so it always names a boundary: the steps finished so far, the steps still to
57
+ * run, and the counters. Resuming picks up exactly there — the planner does not
58
+ * run again and a finished step is not repeated.
59
+ *
60
+ * WHAT IT IS NOT. A step that was in flight when the page died is NOT
61
+ * checkpointed — it runs again from its start. For a read that is free; for a
62
+ * write it may apply twice, so a tool with side effects should be idempotent (or
63
+ * the host should keep the consent gate on). Attachments (images, files) are not
64
+ * stored — pass them again to `run()` when resuming.
65
+ *
66
+ * Persistence is observability, not a correctness boundary: a hook that throws is
67
+ * logged and the run carries on.
68
+ */
69
+ type RunStatus = 'executing' | 'complete' | 'failed' | 'cancelled';
70
+ /** Everything needed to continue a run from the end of an iteration. */
71
+ interface RunSnapshot {
72
+ runId: string;
73
+ startedAt: number;
74
+ /**
75
+ * `executing` is the only non-terminal status the runtime writes. The others are
76
+ * written once, when the run resolves; `failed` and `cancelled` can still be
77
+ * resumed (a stopped run is not a lost one), `complete` cannot.
78
+ */
79
+ status: RunStatus;
80
+ /** The goal as first given: a resumed run uses THIS one, whatever `run()` is passed. */
81
+ goal: string;
82
+ /** The session the run belongs to; a resumed run keeps it. */
83
+ sessionId: string;
84
+ /** The plan as first created (a `revise` later changes `remaining`, not this). */
85
+ plan: IPlan;
86
+ /** Steps still to run, after any `revise`. */
87
+ remaining: IPlanStep[];
88
+ /** Finished steps, as the run's trace. */
89
+ trace: IStepResult[];
90
+ /** The step log later steps and the answer are written from. */
91
+ done: string[];
92
+ /** Tool findings the synthesizer is given. */
93
+ findings: string[];
94
+ usage: IUsage;
95
+ /** Steps executed so far (the cap `maxIterations` counts these — across a crash). */
96
+ iterations: number;
97
+ /** Replanner `revise` decisions so far (`maxRevisions`). */
98
+ revisions: number;
99
+ /** Successful tool calls so far (`maxToolCalls`). */
100
+ toolCalls: number;
101
+ /** Tool calls that went through: `RunResult.applied`. */
102
+ applied: number;
103
+ /** Skills whose instructions are active. */
104
+ skills: string[];
105
+ /** Tools activated through `find_tools`, in order. */
106
+ discovered: string[];
107
+ /** How many images/files the run was given (their bytes are not kept). */
108
+ attachments: number;
109
+ /**
110
+ * What the user said while the run was going (`RunControl.send`), in order, and whether the
111
+ * replanner has already weighed each. A resumed run keeps them: otherwise it would forget a
112
+ * correction the user had already made.
113
+ */
114
+ userUpdates?: {
115
+ text: string;
116
+ reconciled: boolean;
117
+ }[];
118
+ /** Final answer (status `complete`). */
119
+ text?: string;
120
+ /** What ended the run (status `failed`). */
121
+ error?: string;
122
+ completedAt?: number;
123
+ }
124
+ interface RunPersistence {
125
+ /** The plan is in hand and the loop is about to start. Not called again on resume. */
126
+ onRunStart?: (snapshot: RunSnapshot) => void | Promise<void>;
127
+ /** An iteration finished: a checkpoint to resume from. */
128
+ onStepComplete?: (snapshot: RunSnapshot) => void | Promise<void>;
129
+ /** The run resolved: `complete`, `failed` (it threw) or `cancelled` (it was stopped). */
130
+ onRunComplete?: (snapshot: RunSnapshot) => void | Promise<void>;
131
+ /**
132
+ * What `run(goal, { resumeFromRunId })` reads. Return `null` when there is none.
133
+ * An implementation that does not want to support resume can leave it out.
134
+ */
135
+ loadRun?: (runId: string) => RunSnapshot | null | Promise<RunSnapshot | null>;
136
+ }
137
+ /**
138
+ * Load and validate the snapshot a `resumeFromRunId` names. Throws a message the
139
+ * caller can act on for: no `loadRun`, no such run, a store that answers with a
140
+ * different run, a run that already completed, a snapshot with nothing left to do.
141
+ * Persistence is host-controlled, so what `loadRun` returns is not trusted.
142
+ */
143
+ declare const resolveResume: (persistence: RunPersistence | undefined, resumeFromRunId: string | undefined) => Promise<RunSnapshot | undefined>;
144
+
49
145
  /**
50
146
  * Thinking (a.k.a. reasoning) activation, portable across providers.
51
147
  *
@@ -406,6 +502,12 @@ interface ExecutorPromptContext {
406
502
  activeSkills?: string;
407
503
  /** The executor can call find_tools to activate more tools. */
408
504
  searchMode?: boolean;
505
+ /** What the user said while the run was going (`RunControl.send`), oldest first. */
506
+ updates?: string[];
507
+ /** Set when `config.learning` is on (and not muted): the executor is told to keep a notebook. */
508
+ learning?: {
509
+ fetch: boolean;
510
+ };
409
511
  }
410
512
  interface ReplannerPromptContext {
411
513
  goal: string;
@@ -414,6 +516,10 @@ interface ReplannerPromptContext {
414
516
  remaining: string[];
415
517
  mode: ToolCallMode;
416
518
  activeSkills?: string;
519
+ /** What the user said while the run was going, oldest first. */
520
+ updates?: string[];
521
+ /** How many of `updates` (the last ones) the plan has not been weighed against yet. */
522
+ newUpdates?: number;
417
523
  }
418
524
  interface SynthesizerPromptContext {
419
525
  goal: string;
@@ -422,6 +528,8 @@ interface SynthesizerPromptContext {
422
528
  /** Excerpts of what the tools returned, for answering with real data. */
423
529
  findings?: string[];
424
530
  activeSkills?: string;
531
+ /** What the user said while the run was going, oldest first. */
532
+ updates?: string[];
425
533
  }
426
534
  interface Prompts {
427
535
  planner(ctx: PlannerPromptContext): PromptParts;
@@ -460,6 +568,78 @@ declare class MemoryCredentialStore implements CredentialStore {
460
568
  deleteApiKey(ref: string): Promise<void>;
461
569
  }
462
570
 
571
+ /**
572
+ * A small virtual file system for the browser — the agent's (and the user's)
573
+ * workspace: attachments the user drops in, reports the agent writes, images
574
+ * pasted into the chat. Persistent in IndexedDB by default, in-memory on
575
+ * request (tests, private mode). Paths are POSIX-like and always absolute
576
+ * ("/notes/todo.md"); there are no real directories — a "directory" is a path
577
+ * prefix.
578
+ */
579
+ interface VirtualFile {
580
+ path: string;
581
+ /** Text, or base64 for binary content (see `encoding`). */
582
+ content: string;
583
+ encoding: 'utf8' | 'base64';
584
+ mimeType: string;
585
+ /** Size of the decoded content in bytes. */
586
+ size: number;
587
+ updatedAt: number;
588
+ }
589
+ /** A listing entry (no content). */
590
+ type VirtualFileInfo = Omit<VirtualFile, 'content'>;
591
+ interface VirtualFileSystemOptions {
592
+ /** Keep files in memory only (default false: IndexedDB). */
593
+ memory?: boolean;
594
+ /** IndexedDB database name, forwarded to the shared owner (default 'agent-web'). */
595
+ dbName?: string;
596
+ /** Isolates several file systems in one database (default 'default'). */
597
+ namespace?: string;
598
+ /** Refuse a single file larger than this many bytes (default 10 MB). */
599
+ maxFileBytes?: number;
600
+ }
601
+ type VfsListener = (change: {
602
+ type: 'write' | 'delete';
603
+ path: string;
604
+ }) => void;
605
+ /** A best-effort MIME type from a file name. */
606
+ declare const mimeFromPath: (path: string) => string;
607
+ /** True for MIME types the agent can read as text. */
608
+ declare const isTextMime: (mime: string) => boolean;
609
+ /**
610
+ * Normalise a path: absolute, forward slashes, no "." / ".." / empty segments.
611
+ * Throws on a path that escapes the root.
612
+ */
613
+ declare const normalizePath: (input: string) => string;
614
+ /** Base64 of bytes, chunked so a large file can't blow the call stack. */
615
+ declare const bytesToBase64: (bytes: Uint8Array) => string;
616
+ declare class VirtualFileSystem {
617
+ private readonly memory?;
618
+ private readonly dbName?;
619
+ private readonly ns;
620
+ private readonly maxFileBytes;
621
+ private readonly listeners;
622
+ constructor(opts?: VirtualFileSystemOptions);
623
+ private key;
624
+ /** Subscribe to writes and deletes (e.g. to refresh a file list). Returns an unsubscribe. */
625
+ onChange(listener: VfsListener): () => void;
626
+ private notify;
627
+ write(path: string, content: string | Uint8Array, opts?: {
628
+ mimeType?: string;
629
+ encoding?: VirtualFile['encoding'];
630
+ }): Promise<VirtualFileInfo>;
631
+ /** Store a data URL ("data:image/png;base64,…") as a file. */
632
+ writeDataUrl(path: string, dataUrl: string): Promise<VirtualFileInfo>;
633
+ read(path: string): Promise<VirtualFile | undefined>;
634
+ /** The file as a data URL (for <img src>, downloads). */
635
+ readDataUrl(path: string): Promise<string | undefined>;
636
+ delete(path: string): Promise<boolean>;
637
+ /** Files under a prefix ("/" = all), sorted by path. */
638
+ list(prefix?: string): Promise<VirtualFileInfo[]>;
639
+ /** Remove every file (of this namespace). */
640
+ clear(): Promise<void>;
641
+ }
642
+
463
643
  /**
464
644
  * Skills — reusable instruction bundles in the agentskills.io shape
465
645
  * (`SKILL.md` with `name`/`description` frontmatter, a markdown body, optional
@@ -479,6 +659,21 @@ interface Skill {
479
659
  path: string;
480
660
  content: string;
481
661
  }[];
662
+ /** Set on a skill the AGENT wrote (`config.learning`); absent on the host's own. */
663
+ origin?: SkillOrigin;
664
+ }
665
+ /** Where a learned skill came from. */
666
+ interface SkillOrigin {
667
+ kind: 'learned';
668
+ /** Epoch ms of the last write. */
669
+ at: number;
670
+ /** 1 for a new lesson, +1 each time the agent rewrites it. */
671
+ revision: number;
672
+ runId?: string;
673
+ /** What the model said it consulted (URLs without query strings, doc names). */
674
+ sources?: string[];
675
+ /** Pages web_fetch read during the run that wrote it - recorded by the harness, not the model. */
676
+ fetched?: string[];
482
677
  }
483
678
  /** Names of the built-in skill tools (reserved when skills are configured). */
484
679
  declare const SKILL_TOOL_NAMES: readonly ["load_skill", "read_skill_file"];
@@ -499,6 +694,11 @@ interface LoadSkillOptions {
499
694
  }
500
695
  /** Fetch a SKILL.md (and optionally its bundled files) over HTTP. */
501
696
  declare const loadSkillFromUrl: (url: string, opts?: LoadSkillOptions) => Promise<Skill>;
697
+ /**
698
+ * How a learned skill is introduced wherever its text is shown to the model: as a note of the
699
+ * agent's own, subordinate to the user - never as an instruction.
700
+ */
701
+ declare const learnedPreamble: (skill: Skill) => string;
502
702
  /** "- name: description" lines for the prompts. */
503
703
  declare const renderSkillIndex: (skills: Skill[]) => string;
504
704
  /** The full instructions of the active skills, within a total character budget. */
@@ -509,6 +709,139 @@ declare const renderActiveSkills: (skills: Skill[]) => string;
509
709
  */
510
710
  declare const createSkillTools: (skills: Skill[], onLoad?: (skill: Skill) => void) => ToolSet;
511
711
 
712
+ declare const SAVE_SKILL_TOOL = "save_skill";
713
+ declare const FORGET_SKILL_TOOL = "forget_skill";
714
+ /** Where learned skills are kept. {@link MemorySkillStore} and {@link VfsSkillStore} are provided. */
715
+ interface SkillStore {
716
+ list(): Skill[] | Promise<Skill[]>;
717
+ save(skill: Skill): void | Promise<void>;
718
+ /** false when there was nothing to remove. */
719
+ remove(name: string): boolean | Promise<boolean>;
720
+ }
721
+ interface LearningConfig {
722
+ /** Where lessons are kept. Default: in memory, for the life of the agent (the open session). */
723
+ store?: SkillStore;
724
+ /** At most this many lessons (default 50). */
725
+ maxSkills?: number;
726
+ /** At most this many characters of instructions per lesson (default 6000). */
727
+ maxSkillChars?: number;
728
+ /** false keeps the tools but drops the executor guidance to write lessons down (default true). */
729
+ nudge?: boolean;
730
+ }
731
+ /** What a credential looks like, or undefined. */
732
+ declare const findSecret: (text: string) => string | undefined;
733
+ /** "My Trick_1" -> "my-trick-1"; undefined when nothing usable is left. */
734
+ declare const normalizeSkillName: (raw: string) => string | undefined;
735
+ /** Lives as long as the agent: the "open session". */
736
+ declare class MemorySkillStore implements SkillStore {
737
+ private readonly skills;
738
+ list(): Skill[];
739
+ save(skill: Skill): void;
740
+ remove(name: string): boolean;
741
+ }
742
+ /**
743
+ * `<dir>/<name>/SKILL.md` in the agent's virtual file system (IndexedDB, or memory): the user can
744
+ * see and edit lessons in the files panel like any file. A sidecar `.origin.json` says where each
745
+ * came from. Default dir `/skills`.
746
+ */
747
+ declare class VfsSkillStore implements SkillStore {
748
+ private readonly vfs;
749
+ private readonly dir;
750
+ constructor(vfs: VirtualFileSystem, dir?: string);
751
+ list(): Promise<Skill[]>;
752
+ save(skill: Skill): Promise<void>;
753
+ remove(name: string): Promise<boolean>;
754
+ }
755
+ interface Learning {
756
+ /** The tools the model learns with (normal tools: gated, counted). */
757
+ tools: AgentToolSet;
758
+ /** The agent's own skills (not the host's). */
759
+ learned: () => Skill[];
760
+ /** Forget one of them. false when there is no such learned skill. */
761
+ forget: (name: string, emit?: (event: {
762
+ type: 'skill.forgotten';
763
+ name: string;
764
+ }) => void) => Promise<boolean>;
765
+ }
766
+ interface SaveSkillInput {
767
+ name: string;
768
+ description: string;
769
+ instructions: string;
770
+ sources?: string[];
771
+ }
772
+ /**
773
+ * Wires learning to the agent's LIVE skill list (`skills` is mutated in place, so every prompt
774
+ * that renders the index sees a new lesson at once).
775
+ */
776
+ declare const createLearning: (cfg: LearningConfig, skills: Skill[], warn: (message: string) => void) => Promise<Learning>;
777
+
778
+ 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';
779
+ declare class EgressError extends Error {
780
+ readonly code: EgressErrorCode;
781
+ constructor(code: EgressErrorCode, message: string);
782
+ toJSON(): string;
783
+ }
784
+ interface IEgressPolicy {
785
+ /** 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. */
786
+ allow?: string[];
787
+ /** Always refused; wins over `allow`. Same patterns. */
788
+ deny?: string[];
789
+ /** Allow IP literals and internal-looking names in private ranges (default false). Metadata endpoints stay refused. */
790
+ allowPrivateNetwork?: boolean;
791
+ /** Default ['https']. */
792
+ protocols?: ('https' | 'http')[];
793
+ /** Default [443] (and 80 once 'http' is allowed). */
794
+ ports?: number[];
795
+ /** Default ['GET']. */
796
+ methods?: string[];
797
+ /** Follow redirects, judging only the final URL after the fact (default false: a redirect fails the request). */
798
+ followRedirects?: boolean;
799
+ /** Cap on the body, in bytes. Default 2_000_000. */
800
+ maxResponseBytes?: number;
801
+ /** Whole request, in ms. Default 15_000. */
802
+ timeoutMs?: number;
803
+ /** The fetch to use (default `globalThis.fetch`). Point it at a gateway to get server-side protection. */
804
+ fetch?: typeof fetch;
805
+ }
806
+ interface IResolvedEgressPolicy {
807
+ allow: string[];
808
+ deny: string[];
809
+ allowPrivateNetwork: boolean;
810
+ protocols: ('https' | 'http')[];
811
+ ports: number[];
812
+ methods: string[];
813
+ followRedirects: boolean;
814
+ maxResponseBytes: number;
815
+ timeoutMs: number;
816
+ fetch: typeof fetch;
817
+ }
818
+ declare const resolveEgressPolicy: (policy?: IEgressPolicy) => IResolvedEgressPolicy;
819
+ type AddressClass = 'public' | 'private' | 'never';
820
+ declare const classifyAddress: (address: string) => AddressClass;
821
+ declare const hostMatches: (host: string, pattern: string) => boolean;
822
+ declare const checkEgressUrl: (url: URL, policy: IResolvedEgressPolicy, method?: string) => void;
823
+ declare const htmlToText: (html: string) => {
824
+ title?: string;
825
+ text: string;
826
+ };
827
+ type GuardedFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
828
+ /** A `fetch` bound to a policy. */
829
+ declare const createGuardedFetch: (policy?: IEgressPolicy) => GuardedFetch;
830
+ declare const WEB_FETCH_TOOL = "web_fetch";
831
+ interface IWebFetchOptions {
832
+ policy?: IEgressPolicy;
833
+ fetch?: GuardedFetch;
834
+ }
835
+ /**
836
+ * `web_fetch({ url })`: read one page or API response. Every request goes through the egress
837
+ * policy; a refusal comes back as a tool error that says why. Read-only for the consent gate
838
+ * only when the policy names the hosts it may reach - an open GET is a channel to leak data
839
+ * through the URL, so it asks like a write.
840
+ */
841
+ declare const createWebFetchTool: (options?: IWebFetchOptions) => AgentTool;
842
+ /** The tools `config.egress` turns on (none when it is off). */
843
+ declare const createEgressTools: (egress: boolean | IEgressPolicy | undefined) => AgentToolSet | undefined;
844
+
512
845
  /**
513
846
  * Tool consent. Every tool call passes a gate that decides allow / ask / deny:
514
847
  *
@@ -614,6 +947,14 @@ interface BrowserAgentConfig {
614
947
  credentials?: CredentialStore;
615
948
  /** Propagated to the openai-compatible provider name and the MCP client. */
616
949
  clientName?: string;
950
+ /**
951
+ * Requests the MODEL may make (the `web_fetch` tool). Off unless set: with it off there is no
952
+ * way to fetch. `true` = any public host over https; an object narrows or widens that (allow /
953
+ * deny lists, ...) - see `IEgressPolicy`. A browser cannot pin DNS: prefer an `allow` list, or a
954
+ * `fetch` that goes through a server-side safe fetch. Not the provider's own calls, MCP servers
955
+ * or tools you pass yourself - those are your configuration, not the model's.
956
+ */
957
+ egress?: boolean | IEgressPolicy;
617
958
  /** Host tools the executor may call (an AI SDK ToolSet; use defineTool). */
618
959
  tools?: AgentToolSet;
619
960
  /** Whitelist: only these tool names from `tools` are mounted (default: all). */
@@ -630,6 +971,12 @@ interface BrowserAgentConfig {
630
971
  toolApproval?: ToolApprovalConfig;
631
972
  /** Reusable instruction bundles (SKILL.md) the planner/executor can pull in. */
632
973
  skills?: Skill[];
974
+ /**
975
+ * Let the agent write down lessons as skills (`save_skill` / `forget_skill`) for the rest of the
976
+ * session: `true` keeps them in memory; `{ store: new VfsSkillStore(vfs) }` keeps them in the
977
+ * file system across sessions. Off by default. Knowledge only - see `learning.ts`.
978
+ */
979
+ learning?: boolean | LearningConfig;
633
980
  /** Prepended to every phase's system prompt. */
634
981
  systemPrompt?: string;
635
982
  /** Override any phase prompt builder. */
@@ -643,6 +990,13 @@ interface BrowserAgentConfig {
643
990
  */
644
991
  memory?: ContextStore;
645
992
  sessionId?: string;
993
+ /**
994
+ * Checkpoint runs so a reload or a crashed tab does not lose finished work:
995
+ * `new IndexedDBRunStore()` survives a reload, `new MemoryRunStore()` does not.
996
+ * `run(goal, { resumeFromRunId })` then continues from the last checkpoint —
997
+ * see `RunSnapshot` for exactly what is, and is not, kept.
998
+ */
999
+ persistence?: RunPersistence;
646
1000
  /** Hard cap on executed steps incl. replans (default 8). */
647
1001
  maxIterations?: number;
648
1002
  /** Cap on tool-calling rounds inside one executor call, both modes (default 4). */
@@ -734,9 +1088,19 @@ type UsagePhase = Phase | 'compact' | 'subagent';
734
1088
  * event taxonomy (no persistence/otel events), plus `model.load` for WebLLM
735
1089
  * weight-download progress.
736
1090
  */
737
- type AgentEvent = {
1091
+ type AgentEvent =
1092
+ /**
1093
+ * `runId` names the run for `persistence` / `resumeFromRunId`. `resumed` is set when it
1094
+ * continues a checkpointed run: the steps already done and the ones still to come.
1095
+ */
1096
+ {
738
1097
  type: 'run.start';
739
1098
  goal: string;
1099
+ runId?: string;
1100
+ resumed?: {
1101
+ completedSteps: number;
1102
+ remainingSteps: number;
1103
+ };
740
1104
  } | {
741
1105
  type: 'model.load';
742
1106
  progress: number;
@@ -785,10 +1149,13 @@ type AgentEvent = {
785
1149
  type: 'step.complete';
786
1150
  step: IPlanStep;
787
1151
  result: IStepResult;
788
- } | {
1152
+ }
1153
+ /** `byUser`: the replanner ran because the user sent a message (`RunControl.send`), not because a step failed. */
1154
+ | {
789
1155
  type: 'replan.decision';
790
1156
  mode: ReplanMode;
791
1157
  reason: string;
1158
+ byUser?: boolean;
792
1159
  } | {
793
1160
  type: 'final.text-delta';
794
1161
  delta: string;
@@ -831,6 +1198,22 @@ type AgentEvent = {
831
1198
  name: string;
832
1199
  by: 'plan' | 'tool';
833
1200
  }
1201
+ /** The agent wrote a lesson down as a skill (`config.learning`). */
1202
+ | {
1203
+ type: 'skill.learned';
1204
+ name: string;
1205
+ description: string;
1206
+ /** true when it rewrote an earlier lesson of the same name. */
1207
+ update: boolean;
1208
+ chars: number;
1209
+ /** What it consulted: the sources it named, then the pages web_fetch read in the run. */
1210
+ sources: string[];
1211
+ }
1212
+ /** A lesson was deleted (by the agent's forget_skill, or the host's forgetSkill). */
1213
+ | {
1214
+ type: 'skill.forgotten';
1215
+ name: string;
1216
+ }
834
1217
  /** find_tools activated more tools (large-catalogue search mode). */
835
1218
  | {
836
1219
  type: 'tools.discovered';
@@ -855,11 +1238,14 @@ type AgentEvent = {
855
1238
  approved: boolean;
856
1239
  reason?: string;
857
1240
  automatic: boolean;
858
- } | {
1241
+ }
1242
+ /** `profile` is set when the parent chose one of the subagent's named profiles for this call. */
1243
+ | {
859
1244
  type: 'subagent.start';
860
1245
  id: string;
861
1246
  name: string;
862
1247
  task: string;
1248
+ profile?: string;
863
1249
  }
864
1250
  /** An event of a running subagent, forwarded verbatim. */
865
1251
  | {
@@ -873,11 +1259,42 @@ type AgentEvent = {
873
1259
  name: string;
874
1260
  text: string;
875
1261
  usage: IUsage;
876
- } | {
1262
+ }
1263
+ /** `stopped` is set when the user stopped this subagent (`RunControl.stopSubagent`), as opposed to it failing. */
1264
+ | {
877
1265
  type: 'subagent.error';
878
1266
  id: string;
879
1267
  name: string;
880
1268
  error: string;
1269
+ stopped?: boolean;
1270
+ }
1271
+ /** A message sent with `RunControl.send` is waiting for the next boundary. */
1272
+ /**
1273
+ * A request of the `web_fetch` tool, allowed or refused by the egress policy. `url` is origin and
1274
+ * path only (a query string can carry a secret).
1275
+ */
1276
+ | {
1277
+ type: 'egress.request';
1278
+ url: string;
1279
+ allowed: boolean;
1280
+ status?: number;
1281
+ reason?: string;
1282
+ } | {
1283
+ type: 'message.queued';
1284
+ id: string;
1285
+ text: string;
1286
+ }
1287
+ /**
1288
+ * The message reached the model. `round` = between tool-calling rounds inside a step, so
1289
+ * the rest of that step can act on it (the replanner weighs it at the end of the step);
1290
+ * `step` = at a step boundary, where it forces the replanner to look at the plan;
1291
+ * `final` = just before the answer is written.
1292
+ */
1293
+ | {
1294
+ type: 'message.delivered';
1295
+ id: string;
1296
+ text: string;
1297
+ at: 'round' | 'step' | 'final';
881
1298
  } | {
882
1299
  type: 'stopped';
883
1300
  } | {
@@ -933,6 +1350,75 @@ declare const renderSearchCatalog: (catalog: ToolCatalogEntry[], budget?: number
933
1350
  */
934
1351
  declare const createFindToolsTool: (catalog: () => ToolCatalogEntry[], onFound: (query: string, names: string[]) => void, hintOf?: (name: string) => string | undefined) => Tool;
935
1352
 
1353
+ /**
1354
+ * Steering a run that is already going.
1355
+ *
1356
+ * `run()` takes one goal and returns when the run is over, so a host that wants to
1357
+ * say something mid-run — "actually use the staging database" — or stop one
1358
+ * subagent out of several has nothing to call. A `RunControl` is the handle: create
1359
+ * one, pass it as `run(goal, { control })`, and use it from anywhere while the run
1360
+ * is in flight.
1361
+ *
1362
+ * A message is not interrupt. The run never cuts a tool call short (it may be a
1363
+ * write): the message is held until the next boundary — the next tool-calling round
1364
+ * inside a step, or the end of the step — and is then shown to the model. At a step
1365
+ * boundary it also forces the replanner to look at the plan again, because a plan
1366
+ * made before the user spoke may no longer be the right one.
1367
+ */
1368
+ /** One running subagent, as the host sees it. */
1369
+ interface SubagentInfo {
1370
+ id: string;
1371
+ /** The subagent tool's `name`. */
1372
+ name: string;
1373
+ task: string;
1374
+ /** The profile the parent chose for this call, when it chose one. */
1375
+ profile?: string;
1376
+ startedAt: number;
1377
+ }
1378
+ interface RunControl {
1379
+ /**
1380
+ * Queue a message for the run. `false` when there is nothing to deliver it to — the text
1381
+ * is empty, or the run has already finished (send it as a new run instead).
1382
+ *
1383
+ * Accepted does not mean delivered: a message that arrives after the last boundary
1384
+ * (while the answer is being written) comes back in `RunResult.undelivered`, so the
1385
+ * host can send it next.
1386
+ */
1387
+ send(text: string): boolean;
1388
+ /**
1389
+ * Messages sent and not yet delivered. Once the run is over: the ones it never got to show
1390
+ * the model (the same list as `RunResult.undelivered`, which a run that threw cannot return).
1391
+ */
1392
+ pending(): string[];
1393
+ /** The subagents running under this run right now (a snapshot; `subagent.*` events are the stream). */
1394
+ subagents(): SubagentInfo[];
1395
+ /**
1396
+ * Stop ONE running subagent. Its delegation fails with a message the parent model can
1397
+ * route around, and the run carries on — unlike aborting the run, which stops everything.
1398
+ * `false` when no subagent with that id is running.
1399
+ */
1400
+ stopSubagent(id: string): boolean;
1401
+ }
1402
+ interface QueuedMessage {
1403
+ id: string;
1404
+ text: string;
1405
+ }
1406
+ /** What the runner and the subagent tool use; deliberately not part of the public surface. */
1407
+ interface RunControlPort {
1408
+ /** The run starts reading: from now on `send` announces itself. */
1409
+ attach(emit: (event: AgentEvent) => void): void;
1410
+ /**
1411
+ * The run is over: whatever is still queued is returned, for the host to send as a
1412
+ * follow-up. It stays readable through `pending()` until the control serves another run.
1413
+ */
1414
+ detach(): string[];
1415
+ /** Take every queued message, oldest first. */
1416
+ drain(): QueuedMessage[];
1417
+ /** A subagent started under this run; returns what unregisters it. */
1418
+ registerSubagent(info: SubagentInfo, stop: () => void): () => void;
1419
+ }
1420
+ declare const createRunControl: () => RunControl;
1421
+
936
1422
  /**
937
1423
  * Attachments sent with a run: images, PDFs and other files the provider can
938
1424
  * read, given as bytes / base64 / a data URL — or as an http(s) URL, which
@@ -1011,6 +1497,15 @@ interface AgentContext {
1011
1497
  skills?: Skill[];
1012
1498
  /** Skills whose instructions are in play for this run. */
1013
1499
  activeSkills?: () => Skill[];
1500
+ /**
1501
+ * Set when `config.learning` is on: whether the executor is told to write lessons down, and the
1502
+ * notebook's tool names - callable in every step whatever the strategy narrows to (they are
1503
+ * still wrapped and gated like any other tool).
1504
+ */
1505
+ learning?: {
1506
+ nudge: boolean;
1507
+ tools: string[];
1508
+ };
1014
1509
  /** Tools find_tools activated during this run (search mode). */
1015
1510
  discovered?: () => string[];
1016
1511
  /** Built-in tool names (find_tools, skill tools) — always callable. */
@@ -1025,6 +1520,13 @@ interface AgentContext {
1025
1520
  setCurrentStep?: (step: IPlanStep | undefined) => void;
1026
1521
  /** Images / PDFs / files the user sent with this run's goal. */
1027
1522
  images?: RunFile[];
1523
+ /** Everything the user said while the run was going (`RunControl.send`), oldest first. */
1524
+ userUpdates?: () => string[];
1525
+ /**
1526
+ * Take what the user said since the last boundary, for delivery INSIDE a step (between
1527
+ * tool-calling rounds): records it, announces it, and returns the texts.
1528
+ */
1529
+ takeRoundUpdates?: () => string[];
1028
1530
  }
1029
1531
 
1030
1532
  interface RunOptions {
@@ -1032,6 +1534,18 @@ interface RunOptions {
1032
1534
  signal?: AbortSignal;
1033
1535
  /** Override the config's sessionId for this run. */
1034
1536
  sessionId?: string;
1537
+ /**
1538
+ * Continue a checkpointed run instead of starting one (needs `persistence.loadRun`). The
1539
+ * saved goal, plan, finished steps and counters win — whatever `goal` is passed, and without
1540
+ * planning again. Attachments are not stored: pass them again if the run needs them.
1541
+ */
1542
+ resumeFromRunId?: string;
1543
+ /**
1544
+ * Steer the run while it goes: `control.send(text)` puts a message in front of the model
1545
+ * at the next boundary, `control.stopSubagent(id)` stops one subagent. Make it with
1546
+ * `createRunControl()`; one control per run.
1547
+ */
1548
+ control?: RunControl;
1035
1549
  /**
1036
1550
  * Images sent with the goal (pasted screenshots, photos). They reach the
1037
1551
  * planner, the executor and the synthesizer of a vision-capable model; a
@@ -1047,6 +1561,8 @@ interface RunOptions {
1047
1561
  files?: RunFile[];
1048
1562
  }
1049
1563
  interface RunResult {
1564
+ /** Names this run for `persistence` / `resumeFromRunId`. */
1565
+ runId: string;
1050
1566
  goal: string;
1051
1567
  final: string;
1052
1568
  plan: IPlan;
@@ -1060,6 +1576,12 @@ interface RunResult {
1060
1576
  skills: string[];
1061
1577
  /** The limit that stopped the run early, if any. */
1062
1578
  budgetExceeded?: LimitBreach;
1579
+ /**
1580
+ * Set when the run was given a `control`: the messages sent with it that the run never got
1581
+ * to show the model (they arrived while the answer was being written, or after the run was
1582
+ * stopped or ended). Send them as the next run. Empty when everything was delivered.
1583
+ */
1584
+ undelivered?: string[];
1063
1585
  }
1064
1586
  interface CompactOptions {
1065
1587
  /** Session to compact (default: the config's sessionId). */
@@ -1093,11 +1615,19 @@ interface Agent {
1093
1615
  * more than the model's own (read from local WebLLM models).
1094
1616
  */
1095
1617
  readonly contextWindowTokens: number;
1096
- /** Configured skills (name + description). */
1618
+ /** Skills (name + description) - the host's, and the agent's own lessons, marked `learned`. Live. */
1097
1619
  readonly skills: {
1098
1620
  name: string;
1099
1621
  description: string;
1622
+ learned?: true;
1100
1623
  }[];
1624
+ /** The agent's own lessons (`config.learning`), with where each came from. Empty without it. */
1625
+ listLearnedSkills(): Skill[];
1626
+ /**
1627
+ * Delete one of the agent's own lessons (a stale one). false when there is no such lesson.
1628
+ * Pass `onEvent` to receive the `skill.forgotten` event.
1629
+ */
1630
+ forgetSkill(name: string, onEvent?: (event: AgentEvent) => void): Promise<boolean>;
1101
1631
  /**
1102
1632
  * What the executor model can take, per attachment kind: true / false, or
1103
1633
  * undefined when unknown (the run tries, and a provider refusal becomes a
@@ -1260,7 +1790,9 @@ interface ReplanOutcome {
1260
1790
  * mode salvages the decision from text. Any failure degrades to 'continue' so a
1261
1791
  * flaky replanner never aborts the run.
1262
1792
  */
1263
- declare const decideReplan: (ctx: AgentContext, goal: string, done: string[], remaining: string[]) => Promise<ReplanOutcome>;
1793
+ declare const decideReplan: (ctx: AgentContext, goal: string, done: string[], remaining: string[],
1794
+ /** How many of the user's latest messages (`ctx.userUpdates()`) the plan has not been weighed against yet. */
1795
+ newUpdates?: number) => Promise<ReplanOutcome>;
1264
1796
 
1265
1797
  /**
1266
1798
  * Write the final natural-language answer of the run, streaming it as
@@ -1345,6 +1877,22 @@ type SubagentWorkerConfig = Pick<BrowserAgentConfig, 'clientName' | 'systemPromp
1345
1877
  rules?: Record<string, 'allow' | 'deny'>;
1346
1878
  };
1347
1879
  };
1880
+ /**
1881
+ * A named way to run the same subagent. Its fields are laid OVER the base
1882
+ * `config` / `workerConfig`, field by field and shallow: a profile's `limits`
1883
+ * replaces the base's `limits`, it is not merged into it. The PARENT model picks
1884
+ * one per call with the optional `profile` argument; the host decides what each
1885
+ * name means — a cheap model for a quick lookup, a strong one with thinking for
1886
+ * a hard question, a different system prompt, a narrower tool set.
1887
+ */
1888
+ interface SubagentProfile {
1889
+ /** When to pick this profile — shown to the parent model, which chooses by it. */
1890
+ description: string;
1891
+ /** In-process subagent: fields laid over `config` (model, thinking, limits, systemPrompt, tools …). */
1892
+ config?: Partial<BrowserAgentConfig>;
1893
+ /** Worker subagent: fields laid over `workerConfig`. */
1894
+ workerConfig?: Partial<SubagentWorkerConfig>;
1895
+ }
1348
1896
  interface SubagentToolOptions {
1349
1897
  /** Label for events and logs (the tool's KEY in your ToolSet is up to you). */
1350
1898
  name: string;
@@ -1379,6 +1927,14 @@ interface SubagentToolOptions {
1379
1927
  outputMaxChars?: number;
1380
1928
  /** Mark the tool read-only for the parent's consent gate (default false). */
1381
1929
  readOnly?: boolean;
1930
+ /**
1931
+ * Named variants the parent model chooses between per call. The tool gains an
1932
+ * optional `profile` argument (one of these names); leaving it out runs the base
1933
+ * config. The child's context is still just `task` — a profile that changes
1934
+ * `systemPrompt`, `skills` or `tools` is how a child gets a different one.
1935
+ * Without profiles the tool is exactly what it was.
1936
+ */
1937
+ profiles?: Record<string, SubagentProfile>;
1382
1938
  }
1383
1939
  /**
1384
1940
  * Expose a subagent as a tool: the parent delegates `{ task }`, the child runs
@@ -1427,78 +1983,6 @@ interface ServeSubagentOptions {
1427
1983
  */
1428
1984
  declare const serveSubagentWorker: (opts?: ServeSubagentOptions) => void;
1429
1985
 
1430
- /**
1431
- * A small virtual file system for the browser — the agent's (and the user's)
1432
- * workspace: attachments the user drops in, reports the agent writes, images
1433
- * pasted into the chat. Persistent in IndexedDB by default, in-memory on
1434
- * request (tests, private mode). Paths are POSIX-like and always absolute
1435
- * ("/notes/todo.md"); there are no real directories — a "directory" is a path
1436
- * prefix.
1437
- */
1438
- interface VirtualFile {
1439
- path: string;
1440
- /** Text, or base64 for binary content (see `encoding`). */
1441
- content: string;
1442
- encoding: 'utf8' | 'base64';
1443
- mimeType: string;
1444
- /** Size of the decoded content in bytes. */
1445
- size: number;
1446
- updatedAt: number;
1447
- }
1448
- /** A listing entry (no content). */
1449
- type VirtualFileInfo = Omit<VirtualFile, 'content'>;
1450
- interface VirtualFileSystemOptions {
1451
- /** Keep files in memory only (default false: IndexedDB). */
1452
- memory?: boolean;
1453
- /** IndexedDB database name, forwarded to the shared owner (default 'agent-web'). */
1454
- dbName?: string;
1455
- /** Isolates several file systems in one database (default 'default'). */
1456
- namespace?: string;
1457
- /** Refuse a single file larger than this many bytes (default 10 MB). */
1458
- maxFileBytes?: number;
1459
- }
1460
- type VfsListener = (change: {
1461
- type: 'write' | 'delete';
1462
- path: string;
1463
- }) => void;
1464
- /** A best-effort MIME type from a file name. */
1465
- declare const mimeFromPath: (path: string) => string;
1466
- /** True for MIME types the agent can read as text. */
1467
- declare const isTextMime: (mime: string) => boolean;
1468
- /**
1469
- * Normalise a path: absolute, forward slashes, no "." / ".." / empty segments.
1470
- * Throws on a path that escapes the root.
1471
- */
1472
- declare const normalizePath: (input: string) => string;
1473
- /** Base64 of bytes, chunked so a large file can't blow the call stack. */
1474
- declare const bytesToBase64: (bytes: Uint8Array) => string;
1475
- declare class VirtualFileSystem {
1476
- private readonly memory?;
1477
- private readonly dbName?;
1478
- private readonly ns;
1479
- private readonly maxFileBytes;
1480
- private readonly listeners;
1481
- constructor(opts?: VirtualFileSystemOptions);
1482
- private key;
1483
- /** Subscribe to writes and deletes (e.g. to refresh a file list). Returns an unsubscribe. */
1484
- onChange(listener: VfsListener): () => void;
1485
- private notify;
1486
- write(path: string, content: string | Uint8Array, opts?: {
1487
- mimeType?: string;
1488
- encoding?: VirtualFile['encoding'];
1489
- }): Promise<VirtualFileInfo>;
1490
- /** Store a data URL ("data:image/png;base64,…") as a file. */
1491
- writeDataUrl(path: string, dataUrl: string): Promise<VirtualFileInfo>;
1492
- read(path: string): Promise<VirtualFile | undefined>;
1493
- /** The file as a data URL (for <img src>, downloads). */
1494
- readDataUrl(path: string): Promise<string | undefined>;
1495
- delete(path: string): Promise<boolean>;
1496
- /** Files under a prefix ("/" = all), sorted by path. */
1497
- list(prefix?: string): Promise<VirtualFileInfo[]>;
1498
- /** Remove every file (of this namespace). */
1499
- clear(): Promise<void>;
1500
- }
1501
-
1502
1986
  interface FileToolsOptions {
1503
1987
  /** Tool-name prefix (default 'fs_' → fs_list, fs_read, fs_write, fs_delete). */
1504
1988
  prefix?: string;
@@ -1734,6 +2218,7 @@ declare const KEYS_STORE = "keys";
1734
2218
  declare const SECRETS_STORE = "secrets";
1735
2219
  declare const SESSIONS_STORE = "sessions";
1736
2220
  declare const FILES_STORE = "files";
2221
+ declare const RUNS_STORE = "runs";
1737
2222
  /**
1738
2223
  * The single owner of the IndexedDB database. Every persistent store — the
1739
2224
  * non-extractable crypto key, encrypted secrets, and session transcripts —
@@ -1853,6 +2338,13 @@ interface ToolLoopOptions {
1853
2338
  caching?: ResolvedCaching;
1854
2339
  /** Clear the oldest tool results once the loop's context grows past a threshold. */
1855
2340
  clearToolResults?: ToolResultClearing;
2341
+ /**
2342
+ * Called at every round boundary — after a round's tool results, right before the model
2343
+ * is called again — for what the user said in the meantime. A non-empty answer is shown to
2344
+ * the model as a new user turn (so it can act on it within this call). Never called before
2345
+ * the first round, and not at all once the model has stopped calling tools.
2346
+ */
2347
+ takeUpdates?: () => string[];
1856
2348
  callbacks?: ToolLoopCallbacks;
1857
2349
  }
1858
2350
  interface ToolLoopResult {
@@ -1969,6 +2461,12 @@ interface ToolRunContext {
1969
2461
  * tool a subagent calls). Resolves when allowed, throws ToolDeniedError.
1970
2462
  */
1971
2463
  approve: (toolName: string, input: unknown, readOnly: boolean) => Promise<void>;
2464
+ /** The run's control, when the host passed one: subagents register here so they can be listed and stopped. */
2465
+ control?: RunControlPort;
2466
+ /** The run's id (for provenance). */
2467
+ runId?: string;
2468
+ /** Pages web_fetch read in this run (origin + path), kept as provenance for any lesson the run writes. */
2469
+ fetched?: string[];
1972
2470
  }
1973
2471
  /** Read the run context the agent passes to a tool's execute (undefined outside a run). */
1974
2472
  declare const toolRunContextOf: (options: unknown) => ToolRunContext | undefined;
@@ -2005,5 +2503,65 @@ declare class IndexedDBStore implements ContextStore {
2005
2503
  listSessions(): Promise<string[]>;
2006
2504
  }
2007
2505
 
2008
- export { AgentTool, AgentToolSet, AttachmentsNotSupportedError, ContextWindowExceededError, FILES_STORE, FIND_TOOLS_NAME, ImagesNotSupportedError, IndexedDBStore, KEYS_STORE, MemoryCredentialStore, MemoryStore, PlanSchema, PlanStepSchema, ReplanSchema, SECRETS_STORE, SESSIONS_STORE, SKILL_TOOL_NAMES, TOOL_APPROVAL_MODES, TOOL_SEARCH_WINDOW_SHARE, ToolBudgetError, ToolDeniedError, VaultCredentialStore, VaultOptions, VirtualFileSystem, WEBLLM_DEFAULT_CONTEXT_WINDOW, attachmentKind, buildModelFromStage, bytesToBase64, checkLimits, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createFileTools, createFindToolsTool, createLogger, createPlan, createSkillTools, createSubagentTool, createToolResultClearer, createWebLLMModel, decideReplan, decideToolPermission, decryptJSON, defaultPrompts, defineSkill, defineTool, directBrowserOk, dispatch, encryptJSON, messageTokens as estimateMessagesTokens, estimateTokens, executeStep, fitCompactionToWindow, generate, generateStructured, getOrCreateVaultKey, isAttachmentRefusal, isDirectModel, isImageRefusal, isProviderSpec, isReadOnlyTool, isTextMime, isWebGPUAvailable, limitModelOutput, loadSkillFromUrl, looksLikeJson, markReadOnly, matchRule, mediaTypeOf, mergeProviderOptions, mimeFromPath, normalizePath, normalizeSteps, normalizeUsage, openAgentWebDB, parseExecutorResponse, parsePlainText, parsePlannerResponse, parseReplannerResponse, parseSkillMarkdown, preloadWebLLMModel, renderActiveSkills, renderCatalog, renderSearchCatalog, renderSkillIndex, replanWanted, resolveCaching, resolveCompaction, resolveConfig, resolveModel, resolveStage, resolveThinking, runToolLoop, schemaHintOf, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, splitBlocker, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow };
2009
- export type { Agent, AgentContext, AgentEvent, AgentEventHandler, AgentLogger, AgentLoggerSink, AgentWebDBOptions, AttachmentKind, BrowserAgentConfig, ClearedInfo, CompactOptions, CompactResult, CompactionConfig, CompressOptions, ContextStore, CredentialStore, EffectiveToolStrategy, EncryptedBlob, ExecutorPromptContext, ExecutorResult, FileToolsOptions, GenerateOptions, IPlan, IPlanStep, IStepResult, IToolCall, IUsage, IndexedDBStoreOptions, LimitBreach, LimitKind, LoadSkillOptions, LogLevel, MessageEndpoint, ModelInput, ParentToWorker, Phase, PhaseBudgets, PlanShape, PlannerPromptContext, PlannerResult, PromptCachingSetting, PromptParts, Prompts, ProviderModelSpec, ProviderOptionsMap, ProviderType, ProxiedToolSpec, RawAction, ReplanDecision, ReplanMode, ReplanShape, ReplanTrigger, ReplannerPromptContext, ReplannerResult, ResolvedCaching, ResolvedCompaction, ResolvedConfig, ResolvedStage, ResolvedThinking, RunFile, RunImage, RunOptions, RunResult, SearchToolsOptions, ServeSubagentOptions, Skill, StageInput, StageOverride, StoredMessage, SubagentToolOptions, SubagentWorkerConfig, SynthesizerPromptContext, ThinkingConfig, ThinkingLevel, ThinkingSetting, ThinkingStage, TokenLimits, ToolApprovalConfig, ToolApprovalDecision, ToolApprovalMode, ToolApprovalRequest, ToolCallMode, ToolCatalogEntry, ToolLoopCallbacks, ToolLoopOptions, ToolLoopResult, ToolMode, ToolPermission, ToolResultClearing, ToolRunContext, ToolSelectionStrategy, UsagePhase, VfsListener, VirtualFile, VirtualFileInfo, VirtualFileSystemOptions, WebLLMAppConfigLike, WebLLMModelOptions, WorkerLike, WorkerToParent };
2506
+ interface RunStoreOptions {
2507
+ /**
2508
+ * Keep the snapshot of a run that completed (default false). A completed run has
2509
+ * nothing to resume, and its transcript lives in the session store, so keeping it
2510
+ * only grows the database — but a host that wants an audit trail can.
2511
+ */
2512
+ keepCompleted?: boolean;
2513
+ }
2514
+ /**
2515
+ * Checkpoints in memory: enough to resume within one page's life (a stopped run, a
2516
+ * failed step) and for tests, but a reload loses them — use `IndexedDBRunStore` for that.
2517
+ */
2518
+ declare class MemoryRunStore implements RunPersistence {
2519
+ private readonly runs;
2520
+ private readonly keepCompleted;
2521
+ constructor(opts?: RunStoreOptions);
2522
+ onRunStart(snapshot: RunSnapshot): void;
2523
+ onStepComplete(snapshot: RunSnapshot): void;
2524
+ onRunComplete(snapshot: RunSnapshot): void;
2525
+ loadRun(runId: string): RunSnapshot | null;
2526
+ /** Runs that can still be resumed (executing, stopped or failed), newest first. */
2527
+ resumable(sessionId?: string): RunSnapshot[];
2528
+ /** The most recent run that can be resumed — what to offer after a reload. */
2529
+ latestResumable(sessionId?: string): RunSnapshot | undefined;
2530
+ delete(runId: string): void;
2531
+ clear(): void;
2532
+ }
2533
+ interface IndexedDBRunStoreOptions extends RunStoreOptions {
2534
+ /** Database name, forwarded to the shared IDB owner (default 'agent-web'). */
2535
+ dbName?: string;
2536
+ }
2537
+ /**
2538
+ * Checkpoints in IndexedDB — one record per run, in the shared `runs` object store
2539
+ * (see storage/db.ts) — so a reload or a crashed tab can resume where it stopped:
2540
+ *
2541
+ * ```ts
2542
+ * const runs = new IndexedDBRunStore()
2543
+ * const agent = await createAgent({ model, persistence: runs })
2544
+ * // after a reload:
2545
+ * const unfinished = await runs.latestResumable(sessionId)
2546
+ * if (unfinished) await agent.run('', { resumeFromRunId: unfinished.runId })
2547
+ * ```
2548
+ */
2549
+ declare class IndexedDBRunStore implements RunPersistence {
2550
+ private readonly dbName?;
2551
+ private readonly keepCompleted;
2552
+ constructor(opts?: IndexedDBRunStoreOptions);
2553
+ private put;
2554
+ onRunStart(snapshot: RunSnapshot): Promise<void>;
2555
+ onStepComplete(snapshot: RunSnapshot): Promise<void>;
2556
+ onRunComplete(snapshot: RunSnapshot): Promise<void>;
2557
+ loadRun(runId: string): Promise<RunSnapshot | null>;
2558
+ /** Runs that can still be resumed (executing, stopped or failed), newest first. */
2559
+ resumable(sessionId?: string): Promise<RunSnapshot[]>;
2560
+ /** The most recent run that can be resumed — what to offer after a reload. */
2561
+ latestResumable(sessionId?: string): Promise<RunSnapshot | undefined>;
2562
+ delete(runId: string): Promise<void>;
2563
+ clear(): Promise<void>;
2564
+ }
2565
+
2566
+ export { AgentTool, AgentToolSet, AttachmentsNotSupportedError, ContextWindowExceededError, EgressError, FILES_STORE, FIND_TOOLS_NAME, FORGET_SKILL_TOOL, ImagesNotSupportedError, IndexedDBRunStore, IndexedDBStore, KEYS_STORE, MemoryCredentialStore, MemoryRunStore, MemorySkillStore, MemoryStore, PlanSchema, PlanStepSchema, RUNS_STORE, ReplanSchema, SAVE_SKILL_TOOL, SECRETS_STORE, SESSIONS_STORE, SKILL_TOOL_NAMES, TOOL_APPROVAL_MODES, TOOL_SEARCH_WINDOW_SHARE, ToolBudgetError, ToolDeniedError, VaultCredentialStore, VaultOptions, VfsSkillStore, VirtualFileSystem, WEBLLM_DEFAULT_CONTEXT_WINDOW, WEB_FETCH_TOOL, attachmentKind, buildModelFromStage, bytesToBase64, checkEgressUrl, checkLimits, classifyAddress, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createEgressTools, createFileTools, createFindToolsTool, createGuardedFetch, createLearning, createLogger, createPlan, createRunControl, createSkillTools, createSubagentTool, createToolResultClearer, createWebFetchTool, createWebLLMModel, decideReplan, decideToolPermission, decryptJSON, defaultPrompts, defineSkill, defineTool, directBrowserOk, dispatch, encryptJSON, messageTokens as estimateMessagesTokens, estimateTokens, executeStep, findSecret, fitCompactionToWindow, generate, generateStructured, getOrCreateVaultKey, hostMatches, htmlToText, isAttachmentRefusal, isDirectModel, isImageRefusal, isProviderSpec, isReadOnlyTool, isTextMime, isWebGPUAvailable, learnedPreamble, limitModelOutput, loadSkillFromUrl, looksLikeJson, markReadOnly, matchRule, mediaTypeOf, mergeProviderOptions, mimeFromPath, normalizePath, normalizeSkillName, normalizeSteps, normalizeUsage, openAgentWebDB, parseExecutorResponse, parsePlainText, parsePlannerResponse, parseReplannerResponse, parseSkillMarkdown, preloadWebLLMModel, renderActiveSkills, renderCatalog, renderSearchCatalog, renderSkillIndex, replanWanted, resolveCaching, resolveCompaction, resolveConfig, resolveEgressPolicy, resolveModel, resolveResume, resolveStage, resolveThinking, runToolLoop, schemaHintOf, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, splitBlocker, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow };
2567
+ export type { Agent, AgentContext, AgentEvent, AgentEventHandler, AgentLogger, AgentLoggerSink, AgentWebDBOptions, AttachmentKind, BrowserAgentConfig, ClearedInfo, CompactOptions, CompactResult, CompactionConfig, CompressOptions, ContextStore, CredentialStore, EffectiveToolStrategy, EgressErrorCode, EncryptedBlob, ExecutorPromptContext, ExecutorResult, FileToolsOptions, GenerateOptions, GuardedFetch, IEgressPolicy, IPlan, IPlanStep, IResolvedEgressPolicy, IStepResult, IToolCall, IUsage, IWebFetchOptions, IndexedDBRunStoreOptions, IndexedDBStoreOptions, Learning, LearningConfig, LimitBreach, LimitKind, LoadSkillOptions, LogLevel, MessageEndpoint, ModelInput, ParentToWorker, Phase, PhaseBudgets, PlanShape, PlannerPromptContext, PlannerResult, PromptCachingSetting, PromptParts, Prompts, ProviderModelSpec, ProviderOptionsMap, ProviderType, ProxiedToolSpec, RawAction, ReplanDecision, ReplanMode, ReplanShape, ReplanTrigger, ReplannerPromptContext, ReplannerResult, ResolvedCaching, ResolvedCompaction, ResolvedConfig, ResolvedStage, ResolvedThinking, RunControl, RunFile, RunImage, RunOptions, RunPersistence, RunResult, RunSnapshot, RunStatus, RunStoreOptions, SaveSkillInput, SearchToolsOptions, ServeSubagentOptions, Skill, SkillOrigin, SkillStore, StageInput, StageOverride, StoredMessage, SubagentInfo, SubagentProfile, SubagentToolOptions, SubagentWorkerConfig, SynthesizerPromptContext, ThinkingConfig, ThinkingLevel, ThinkingSetting, ThinkingStage, TokenLimits, ToolApprovalConfig, ToolApprovalDecision, ToolApprovalMode, ToolApprovalRequest, ToolCallMode, ToolCatalogEntry, ToolLoopCallbacks, ToolLoopOptions, ToolLoopResult, ToolMode, ToolPermission, ToolResultClearing, ToolRunContext, ToolSelectionStrategy, UsagePhase, VfsListener, VirtualFile, VirtualFileInfo, VirtualFileSystemOptions, WebLLMAppConfigLike, WebLLMModelOptions, WorkerLike, WorkerToParent };