@dudko.dev/agent-web-react 0.0.12 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { DependencyList, ReactNode, RefObject, ComponentType, CSSProperties } from 'react';
3
- import { IPlan, IPlanStep, IUsage, ReplanMode, AgentEvent, RunFile, RunResult, Agent, ToolApprovalMode, CompactResult, AgentEventHandler, BrowserAgentConfig, VirtualFileInfo, VirtualFileSystem, CredentialStore, AgentToolSet, WebLLMModelOptions, createWebLLMModel } from '@dudko.dev/agent-web';
3
+ import { IPlan, IPlanStep, IUsage, ReplanMode, AgentEvent, RunFile, RunResult, Agent, ToolApprovalMode, CompactResult, AgentEventHandler, BrowserAgentConfig, VirtualFileInfo, VirtualFileSystem, CredentialStore, AgentToolSet, createWebLLMModel, WebLLMModelOptions } from '@dudko.dev/agent-web';
4
4
  export { Agent, AgentEvent, AgentEventHandler, AgentLoggerSink, AgentTool, AgentToolSet, AttachmentsNotSupportedError, BrowserAgentConfig, CompactResult, CompactionConfig, CredentialStore, FileToolsOptions, IPlan, IPlanStep, IStepResult, IToolCall, IUsage, ImagesNotSupportedError, IndexedDBStore, LogLevel, MemoryCredentialStore, MemoryStore, ModelInput, ProviderModelSpec, ProviderType, RunFile, RunOptions, RunResult, Skill, SubagentToolOptions, SubagentWorkerConfig, ThinkingLevel, ThinkingSetting, TokenLimits, ToolApprovalConfig, ToolApprovalMode, ToolApprovalRequest, VaultCredentialStore, VirtualFile, VirtualFileInfo, VirtualFileSystem, createAgent, createFileTools, createSubagentTool, createWebLLMModel, defineSkill, defineTool, isWebGPUAvailable, loadSkillFromUrl, markReadOnly, parseSkillMarkdown, preloadWebLLMModel, serveSubagentWorker, supportsImages, supportsPdf, unloadWebLLMModel } from '@dudko.dev/agent-web';
5
5
 
6
6
  /** Why a run stopped early (a `budget.exceeded` event). */
@@ -726,45 +726,66 @@ interface UseMcpServersReturn {
726
726
  */
727
727
  declare const useMcpServers: (options?: UseMcpServersOptions) => UseMcpServersReturn;
728
728
 
729
- /** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */
730
- type WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>;
729
+ /** An AI SDK `LanguageModel` (the type, via the core — no `ai` import here). */
730
+ type LanguageModel = Awaited<ReturnType<typeof createWebLLMModel>>;
731
+ /** Download / initialisation progress of a local model. */
732
+ interface LocalModelProgress {
733
+ /** 0..1. */
734
+ progress: number;
735
+ /** Human-readable status from the runtime. */
736
+ text: string;
737
+ }
738
+ /** What `create` and `warmUp` are given. */
739
+ interface LocalModelLoadContext {
740
+ /** Report progress; the hook shows it for the load in flight only. */
741
+ onProgress: (report: LocalModelProgress) => void;
742
+ /** The window to load the model with, when the host asked for one. */
743
+ contextWindowTokens?: number;
744
+ }
731
745
  /**
732
- * Builds a WebLLM-backed `LanguageModel`. Defaults to the core's
733
- * {@link createWebLLMModel}; override it via {@link UseWebLLMModelOptions.create}.
746
+ * How to run one kind of on-device model — WebLLM, the browser's built-in
747
+ * model (`@browser-ai/core`), transformers.js (`@browser-ai/transformers-js`),
748
+ * or your own. Only `create` is required.
734
749
  */
735
- type WebLLMModelFactory = (modelId: string, options?: WebLLMModelOptions) => Promise<WebLLMModel>;
736
- interface UseWebLLMModelOptions extends WebLLMModelOptions {
750
+ interface LocalModelEngine<M extends LanguageModel = LanguageModel> {
751
+ /** Build the model (cheap: the download starts in `warmUp`). */
752
+ create: (modelId: string, ctx: LocalModelLoadContext) => Promise<M>;
737
753
  /**
738
- * Override how the model is built. **Bundled browser apps (Vite, Next, …)
739
- * usually need this**: the core builds WebLLM via `await import('@browser-ai/
740
- * web-llm')`, and a bundler frequently stubs that dynamic import to an empty
741
- * module — the failure surfaces as `webLLM is not a function`. Pass a factory
742
- * that imports `webLLM` statically so the bundler includes it:
743
- *
744
- * ```ts
745
- * import { webLLM } from '@browser-ai/web-llm'
746
- * const create = (id, opts) => Promise.resolve(webLLM(id, opts))
747
- * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })
748
- * ```
749
- *
750
- * Defaults to `createWebLLMModel` from `@dudko.dev/agent-web`.
754
+ * Download the weights and initialise now, so `ready` means "ready to chat"
755
+ * and the progress shows during the load (default: nothing — the runtime
756
+ * then loads on the first message).
751
757
  */
752
- create?: WebLLMModelFactory;
758
+ warmUp?: (model: M, ctx: LocalModelLoadContext) => Promise<void>;
759
+ /** Free the model's memory (default: nothing). */
760
+ unload?: (model: M) => Promise<void>;
761
+ /** Whether this browser can run it at all (default true). */
762
+ supported?: () => boolean;
763
+ /** The error a load reports when `supported()` is false. */
764
+ unsupportedMessage?: string;
765
+ /** The model's context window once loaded, when the runtime says. */
766
+ contextWindowOf?: (model: M) => number | undefined;
767
+ }
768
+ interface UseLocalModelOptions {
769
+ /**
770
+ * The window to load the model with (WebLLM loads with 4096 unless told
771
+ * otherwise). A different window is a different load.
772
+ */
773
+ contextWindowTokens?: number;
753
774
  }
754
- interface UseWebLLMModelReturn {
775
+ interface UseLocalModelReturn<M extends LanguageModel = LanguageModel> {
755
776
  /**
756
777
  * The built model, once **this** `modelId` is loaded — pass to
757
778
  * `createAgent({ model })`. Undefined right after the id changes, until the
758
779
  * new one is loaded.
759
780
  */
760
- model: WebLLMModel | undefined;
781
+ model: M | undefined;
761
782
  /**
762
783
  * Download and initialize the current `modelId`. Resolves with the model
763
784
  * already loaded for it, if any. Loading another id first frees the previous
764
- * model's GPU memory (one engine per hook); call again after an error to retry.
785
+ * model's memory (one model per hook); call again after an error to retry.
765
786
  */
766
- load: () => Promise<WebLLMModel | undefined>;
767
- /** Free the loaded model's GPU memory (and drop a load in flight). */
787
+ load: () => Promise<M | undefined>;
788
+ /** Free the loaded model's memory (and drop a load in flight). */
768
789
  unload: () => Promise<void>;
769
790
  /** The id of the model held in memory, whichever id is current. */
770
791
  loadedModelId: string | undefined;
@@ -772,21 +793,80 @@ interface UseWebLLMModelReturn {
772
793
  loading: boolean;
773
794
  /** Load progress of the current `modelId`, 0..1. */
774
795
  progress: number;
775
- /** Human-readable progress text from WebLLM. */
796
+ /** Human-readable progress text from the runtime. */
776
797
  text: string;
777
798
  /** Why the current `modelId` failed to load. */
778
799
  error: string | undefined;
779
- /** Whether WebGPU is available (required for local models). */
800
+ /** Whether this browser can run the engine. */
780
801
  supported: boolean;
781
802
  /** True once the current `modelId` is ready. */
782
803
  ready: boolean;
804
+ /** The loaded model's context window, in tokens, when the runtime says. */
805
+ contextWindow: number | undefined;
806
+ }
807
+ /**
808
+ * Load an on-device model and track its download — for any local runtime,
809
+ * described by an {@link LocalModelEngine}. Nothing downloads until you call
810
+ * `load()` (models are large), so you can gate it behind a user action.
811
+ *
812
+ * Everything it reports is about the **current** `modelId`: switch the id and
813
+ * `model` / `ready` / `progress` / `error` describe the new one (not loaded
814
+ * yet), while the previous model stays in memory — switching back is instant.
815
+ * Loading the new id frees the previous one first, so two models never hold
816
+ * memory at once; `unload()` frees it on demand. A load superseded by another
817
+ * frees its model; a second `load()` of the same id shares the download.
818
+ *
819
+ * ```tsx
820
+ * import { browserAI, doesBrowserSupportBrowserAI } from '@browser-ai/core'
821
+ * const nano: LocalModelEngine = {
822
+ * create: async () => browserAI('text', { expectedInputs: [{ type: 'image' }] }),
823
+ * warmUp: async (m, { onProgress }) => {
824
+ * await m.createSessionWithProgress((p) => onProgress({ progress: p, text: 'Downloading' }))
825
+ * },
826
+ * supported: doesBrowserSupportBrowserAI,
827
+ * contextWindowOf: (m) => m.getContextWindow(),
828
+ * }
829
+ * const local = useLocalModel('gemini-nano', nano)
830
+ * ```
831
+ *
832
+ * {@link useWebLLMModel} is this hook with the WebLLM engine.
833
+ */
834
+ declare const useLocalModel: <M extends LanguageModel = LanguageModel>(modelId: string, engine: LocalModelEngine<M>, options?: UseLocalModelOptions) => UseLocalModelReturn<M>;
835
+
836
+ /** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */
837
+ type WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>;
838
+ /**
839
+ * Builds a WebLLM-backed `LanguageModel`. Defaults to the core's
840
+ * {@link createWebLLMModel}; override it via {@link UseWebLLMModelOptions.create}.
841
+ */
842
+ type WebLLMModelFactory = (modelId: string, options?: WebLLMModelOptions) => Promise<WebLLMModel>;
843
+ interface UseWebLLMModelOptions extends WebLLMModelOptions {
844
+ /**
845
+ * Override how the model is built. **Bundled browser apps (Vite, Next, …)
846
+ * usually need this**: the core builds WebLLM via `await import('@browser-ai/
847
+ * web-llm')`, and a bundler frequently stubs that dynamic import to an empty
848
+ * module — the failure surfaces as `webLLM is not a function`. Pass a factory
849
+ * that imports `webLLM` statically so the bundler includes it:
850
+ *
851
+ * ```ts
852
+ * import { webLLM } from '@browser-ai/web-llm'
853
+ * const create = (id, opts) => Promise.resolve(webLLM(id, opts))
854
+ * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })
855
+ * ```
856
+ *
857
+ * Defaults to `createWebLLMModel` from `@dudko.dev/agent-web`.
858
+ */
859
+ create?: WebLLMModelFactory;
783
860
  }
861
+ /** What {@link useWebLLMModel} returns — {@link UseLocalModelReturn} for a WebLLM model. */
862
+ type UseWebLLMModelReturn = UseLocalModelReturn<WebLLMModel>;
784
863
  /**
785
- * Load a local WebGPU model with WebLLM and track its download progress.
786
- * Nothing downloads until you call `load()` (models are large), so you can
787
- * gate it behind a user action. `load()` eagerly initializes the engine (via
788
- * the core's `preloadWebLLMModel`), so `ready` means "ready to chat" and
789
- * progress fills during the load rather than silently on the first message.
864
+ * Load a local WebGPU model with WebLLM and track its download progress —
865
+ * {@link useLocalModel} with the WebLLM engine. Nothing downloads until you
866
+ * call `load()` (models are large), so you can gate it behind a user action.
867
+ * `load()` eagerly initializes the engine (via the core's
868
+ * `preloadWebLLMModel`), so `ready` means "ready to chat" and progress fills
869
+ * during the load rather than silently on the first message.
790
870
  *
791
871
  * Everything it reports is about the **current** `modelId`: switch the id and
792
872
  * `model` / `ready` / `progress` / `error` describe the new one (not loaded
@@ -794,6 +874,10 @@ interface UseWebLLMModelReturn {
794
874
  * Loading the new id frees the previous one first, so two models never hold
795
875
  * GPU memory at once; `unload()` frees it on demand.
796
876
  *
877
+ * WebLLM loads its models with a 4096-token window; pass `contextWindowTokens`
878
+ * to load with more (Qwen3, Llama 3.x take far more — it costs KV-cache VRAM,
879
+ * not a new download). A different window is a different load.
880
+ *
797
881
  * ```tsx
798
882
  * import { webLLM } from '@browser-ai/web-llm' // your app's optional peer
799
883
  * const create = (id: string, opts?: WebLLMModelOptions) => Promise.resolve(webLLM(id, opts))
@@ -804,6 +888,12 @@ interface UseWebLLMModelReturn {
804
888
  * ```
805
889
  */
806
890
  declare const useWebLLMModel: (modelId: string, options?: UseWebLLMModelOptions) => UseWebLLMModelReturn;
891
+ /**
892
+ * The WebLLM {@link LocalModelEngine}: what {@link useWebLLMModel} runs, for
893
+ * hosts that switch between local runtimes with one {@link useLocalModel}
894
+ * (pass the window to that hook's `contextWindowTokens`).
895
+ */
896
+ declare const createWebLLMEngine: (options?: UseWebLLMModelOptions) => LocalModelEngine<WebLLMModel>;
807
897
 
808
898
  /**
809
899
  * Pure helpers behind `<AgentComposer>`: slash commands, attachments, notices
@@ -1578,4 +1668,4 @@ interface ApiKeyFormProps {
1578
1668
  */
1579
1669
  declare const ApiKeyForm: ({ credentials, credentialRef, label, placeholder, onChange, className, }: ApiKeyFormProps) => react.JSX.Element;
1580
1670
 
1581
- export { type AgentAction, AgentChat, type AgentChatClassNames, type AgentChatComponents, type AgentChatProps, type AgentChatSlots, AgentComposer, type AgentComposerProps, type AgentLabels, type AgentLabelsOverride, AgentLabelsProvider, type AgentLabelsProviderProps, AgentProvider, type AgentProviderProps, type AgentStatus, type AgentUiState, ApiKeyForm, type ApiKeyFormProps, ApprovalModeSwitch, type ApprovalModeSwitchProps, type ApprovalView, type ApproveOptions, AttachmentView, type BudgetView, type ChatAttachment, ChatHistoryList, type ChatHistoryListProps, ChatHistoryStore, type ChatHistoryStoreOptions, type ChatMessage, type ChatRecord, type ChatSummary, type CompactionView, Composer, type ComposerAttachment, type ComposerModelChip, type ComposerNotice, type ComposerProps, type ComposerThinkingChip, type ConnectedMcp, ContextMeter, type ContextMeterProps, type ConvertedFile, type DownscaleOptions, FilesPanel, type FilesPanelProps, type McpAuthMode, type McpCatalogEntry, type McpConnectOptions, type McpModule, type McpOAuthCallback, type McpServerResult, type McpServerSpec, type McpServerView, type McpStatus, MessageList, type MessageListProps, ModelLoadBar, type ModelLoadBarProps, type ModelLoadState, type NoticeTexts, PlanView, type PlanViewProps, type RenderToolCall, type ReplanState, type RunGoalOptions, type SlashCommand, type SpeechRecognizerLike, StepList, type StepListProps, type StepView, SubagentRow, type SubagentView, ToolApprovalPrompt, type ToolApprovalPromptProps, ToolCallRow, type ToolCallRowProps, type ToolCallView, UsageBadge, type UsageBadgeProps, type UseAgentOptions, type UseAgentReturn, type UseChatHistoryOptions, type UseChatHistoryReturn, type UseCredentialsReturn, type UseMcpOptions, type UseMcpReturn, type UseMcpServersOptions, type UseMcpServersReturn, type UseSpeechToTextOptions, type UseSpeechToTextReturn, type UseVirtualFilesReturn, type UseWebLLMModelOptions, type UseWebLLMModelReturn, type WebLLMModelFactory, agentStateReducer, attachmentKindOf, attachmentRefusal, chatTitle, claimOAuthCallback, createInitialAgentState, defaultLabels, describeMcpResult, downscaleImage, filterCommands, formatElapsed, isUnauthorizedError, mergeLabels, newChatId, noticesOf, parseSlash, readCallbackParams, stripOAuthParams, usageLine, useAgent, useAgentContext, useChatHistory, useCredentials, useLabels, useMcp, useMcpServers, useOptionalAgentContext, useSpeechToText, useVirtualFiles, useWebLLMModel, withAttachments };
1671
+ export { type AgentAction, AgentChat, type AgentChatClassNames, type AgentChatComponents, type AgentChatProps, type AgentChatSlots, AgentComposer, type AgentComposerProps, type AgentLabels, type AgentLabelsOverride, AgentLabelsProvider, type AgentLabelsProviderProps, AgentProvider, type AgentProviderProps, type AgentStatus, type AgentUiState, ApiKeyForm, type ApiKeyFormProps, ApprovalModeSwitch, type ApprovalModeSwitchProps, type ApprovalView, type ApproveOptions, AttachmentView, type BudgetView, type ChatAttachment, ChatHistoryList, type ChatHistoryListProps, ChatHistoryStore, type ChatHistoryStoreOptions, type ChatMessage, type ChatRecord, type ChatSummary, type CompactionView, Composer, type ComposerAttachment, type ComposerModelChip, type ComposerNotice, type ComposerProps, type ComposerThinkingChip, type ConnectedMcp, ContextMeter, type ContextMeterProps, type ConvertedFile, type DownscaleOptions, FilesPanel, type FilesPanelProps, type LocalModelEngine, type LocalModelLoadContext, type LocalModelProgress, type McpAuthMode, type McpCatalogEntry, type McpConnectOptions, type McpModule, type McpOAuthCallback, type McpServerResult, type McpServerSpec, type McpServerView, type McpStatus, MessageList, type MessageListProps, ModelLoadBar, type ModelLoadBarProps, type ModelLoadState, type NoticeTexts, PlanView, type PlanViewProps, type RenderToolCall, type ReplanState, type RunGoalOptions, type SlashCommand, type SpeechRecognizerLike, StepList, type StepListProps, type StepView, SubagentRow, type SubagentView, ToolApprovalPrompt, type ToolApprovalPromptProps, ToolCallRow, type ToolCallRowProps, type ToolCallView, UsageBadge, type UsageBadgeProps, type UseAgentOptions, type UseAgentReturn, type UseChatHistoryOptions, type UseChatHistoryReturn, type UseCredentialsReturn, type UseLocalModelOptions, type UseLocalModelReturn, type UseMcpOptions, type UseMcpReturn, type UseMcpServersOptions, type UseMcpServersReturn, type UseSpeechToTextOptions, type UseSpeechToTextReturn, type UseVirtualFilesReturn, type UseWebLLMModelOptions, type UseWebLLMModelReturn, type WebLLMModelFactory, agentStateReducer, attachmentKindOf, attachmentRefusal, chatTitle, claimOAuthCallback, createInitialAgentState, createWebLLMEngine, defaultLabels, describeMcpResult, downscaleImage, filterCommands, formatElapsed, isUnauthorizedError, mergeLabels, newChatId, noticesOf, parseSlash, readCallbackParams, stripOAuthParams, usageLine, useAgent, useAgentContext, useChatHistory, useCredentials, useLabels, useLocalModel, useMcp, useMcpServers, useOptionalAgentContext, useSpeechToText, useVirtualFiles, useWebLLMModel, withAttachments };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { DependencyList, ReactNode, RefObject, ComponentType, CSSProperties } from 'react';
3
- import { IPlan, IPlanStep, IUsage, ReplanMode, AgentEvent, RunFile, RunResult, Agent, ToolApprovalMode, CompactResult, AgentEventHandler, BrowserAgentConfig, VirtualFileInfo, VirtualFileSystem, CredentialStore, AgentToolSet, WebLLMModelOptions, createWebLLMModel } from '@dudko.dev/agent-web';
3
+ import { IPlan, IPlanStep, IUsage, ReplanMode, AgentEvent, RunFile, RunResult, Agent, ToolApprovalMode, CompactResult, AgentEventHandler, BrowserAgentConfig, VirtualFileInfo, VirtualFileSystem, CredentialStore, AgentToolSet, createWebLLMModel, WebLLMModelOptions } from '@dudko.dev/agent-web';
4
4
  export { Agent, AgentEvent, AgentEventHandler, AgentLoggerSink, AgentTool, AgentToolSet, AttachmentsNotSupportedError, BrowserAgentConfig, CompactResult, CompactionConfig, CredentialStore, FileToolsOptions, IPlan, IPlanStep, IStepResult, IToolCall, IUsage, ImagesNotSupportedError, IndexedDBStore, LogLevel, MemoryCredentialStore, MemoryStore, ModelInput, ProviderModelSpec, ProviderType, RunFile, RunOptions, RunResult, Skill, SubagentToolOptions, SubagentWorkerConfig, ThinkingLevel, ThinkingSetting, TokenLimits, ToolApprovalConfig, ToolApprovalMode, ToolApprovalRequest, VaultCredentialStore, VirtualFile, VirtualFileInfo, VirtualFileSystem, createAgent, createFileTools, createSubagentTool, createWebLLMModel, defineSkill, defineTool, isWebGPUAvailable, loadSkillFromUrl, markReadOnly, parseSkillMarkdown, preloadWebLLMModel, serveSubagentWorker, supportsImages, supportsPdf, unloadWebLLMModel } from '@dudko.dev/agent-web';
5
5
 
6
6
  /** Why a run stopped early (a `budget.exceeded` event). */
@@ -726,45 +726,66 @@ interface UseMcpServersReturn {
726
726
  */
727
727
  declare const useMcpServers: (options?: UseMcpServersOptions) => UseMcpServersReturn;
728
728
 
729
- /** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */
730
- type WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>;
729
+ /** An AI SDK `LanguageModel` (the type, via the core — no `ai` import here). */
730
+ type LanguageModel = Awaited<ReturnType<typeof createWebLLMModel>>;
731
+ /** Download / initialisation progress of a local model. */
732
+ interface LocalModelProgress {
733
+ /** 0..1. */
734
+ progress: number;
735
+ /** Human-readable status from the runtime. */
736
+ text: string;
737
+ }
738
+ /** What `create` and `warmUp` are given. */
739
+ interface LocalModelLoadContext {
740
+ /** Report progress; the hook shows it for the load in flight only. */
741
+ onProgress: (report: LocalModelProgress) => void;
742
+ /** The window to load the model with, when the host asked for one. */
743
+ contextWindowTokens?: number;
744
+ }
731
745
  /**
732
- * Builds a WebLLM-backed `LanguageModel`. Defaults to the core's
733
- * {@link createWebLLMModel}; override it via {@link UseWebLLMModelOptions.create}.
746
+ * How to run one kind of on-device model — WebLLM, the browser's built-in
747
+ * model (`@browser-ai/core`), transformers.js (`@browser-ai/transformers-js`),
748
+ * or your own. Only `create` is required.
734
749
  */
735
- type WebLLMModelFactory = (modelId: string, options?: WebLLMModelOptions) => Promise<WebLLMModel>;
736
- interface UseWebLLMModelOptions extends WebLLMModelOptions {
750
+ interface LocalModelEngine<M extends LanguageModel = LanguageModel> {
751
+ /** Build the model (cheap: the download starts in `warmUp`). */
752
+ create: (modelId: string, ctx: LocalModelLoadContext) => Promise<M>;
737
753
  /**
738
- * Override how the model is built. **Bundled browser apps (Vite, Next, …)
739
- * usually need this**: the core builds WebLLM via `await import('@browser-ai/
740
- * web-llm')`, and a bundler frequently stubs that dynamic import to an empty
741
- * module — the failure surfaces as `webLLM is not a function`. Pass a factory
742
- * that imports `webLLM` statically so the bundler includes it:
743
- *
744
- * ```ts
745
- * import { webLLM } from '@browser-ai/web-llm'
746
- * const create = (id, opts) => Promise.resolve(webLLM(id, opts))
747
- * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })
748
- * ```
749
- *
750
- * Defaults to `createWebLLMModel` from `@dudko.dev/agent-web`.
754
+ * Download the weights and initialise now, so `ready` means "ready to chat"
755
+ * and the progress shows during the load (default: nothing — the runtime
756
+ * then loads on the first message).
751
757
  */
752
- create?: WebLLMModelFactory;
758
+ warmUp?: (model: M, ctx: LocalModelLoadContext) => Promise<void>;
759
+ /** Free the model's memory (default: nothing). */
760
+ unload?: (model: M) => Promise<void>;
761
+ /** Whether this browser can run it at all (default true). */
762
+ supported?: () => boolean;
763
+ /** The error a load reports when `supported()` is false. */
764
+ unsupportedMessage?: string;
765
+ /** The model's context window once loaded, when the runtime says. */
766
+ contextWindowOf?: (model: M) => number | undefined;
767
+ }
768
+ interface UseLocalModelOptions {
769
+ /**
770
+ * The window to load the model with (WebLLM loads with 4096 unless told
771
+ * otherwise). A different window is a different load.
772
+ */
773
+ contextWindowTokens?: number;
753
774
  }
754
- interface UseWebLLMModelReturn {
775
+ interface UseLocalModelReturn<M extends LanguageModel = LanguageModel> {
755
776
  /**
756
777
  * The built model, once **this** `modelId` is loaded — pass to
757
778
  * `createAgent({ model })`. Undefined right after the id changes, until the
758
779
  * new one is loaded.
759
780
  */
760
- model: WebLLMModel | undefined;
781
+ model: M | undefined;
761
782
  /**
762
783
  * Download and initialize the current `modelId`. Resolves with the model
763
784
  * already loaded for it, if any. Loading another id first frees the previous
764
- * model's GPU memory (one engine per hook); call again after an error to retry.
785
+ * model's memory (one model per hook); call again after an error to retry.
765
786
  */
766
- load: () => Promise<WebLLMModel | undefined>;
767
- /** Free the loaded model's GPU memory (and drop a load in flight). */
787
+ load: () => Promise<M | undefined>;
788
+ /** Free the loaded model's memory (and drop a load in flight). */
768
789
  unload: () => Promise<void>;
769
790
  /** The id of the model held in memory, whichever id is current. */
770
791
  loadedModelId: string | undefined;
@@ -772,21 +793,80 @@ interface UseWebLLMModelReturn {
772
793
  loading: boolean;
773
794
  /** Load progress of the current `modelId`, 0..1. */
774
795
  progress: number;
775
- /** Human-readable progress text from WebLLM. */
796
+ /** Human-readable progress text from the runtime. */
776
797
  text: string;
777
798
  /** Why the current `modelId` failed to load. */
778
799
  error: string | undefined;
779
- /** Whether WebGPU is available (required for local models). */
800
+ /** Whether this browser can run the engine. */
780
801
  supported: boolean;
781
802
  /** True once the current `modelId` is ready. */
782
803
  ready: boolean;
804
+ /** The loaded model's context window, in tokens, when the runtime says. */
805
+ contextWindow: number | undefined;
806
+ }
807
+ /**
808
+ * Load an on-device model and track its download — for any local runtime,
809
+ * described by an {@link LocalModelEngine}. Nothing downloads until you call
810
+ * `load()` (models are large), so you can gate it behind a user action.
811
+ *
812
+ * Everything it reports is about the **current** `modelId`: switch the id and
813
+ * `model` / `ready` / `progress` / `error` describe the new one (not loaded
814
+ * yet), while the previous model stays in memory — switching back is instant.
815
+ * Loading the new id frees the previous one first, so two models never hold
816
+ * memory at once; `unload()` frees it on demand. A load superseded by another
817
+ * frees its model; a second `load()` of the same id shares the download.
818
+ *
819
+ * ```tsx
820
+ * import { browserAI, doesBrowserSupportBrowserAI } from '@browser-ai/core'
821
+ * const nano: LocalModelEngine = {
822
+ * create: async () => browserAI('text', { expectedInputs: [{ type: 'image' }] }),
823
+ * warmUp: async (m, { onProgress }) => {
824
+ * await m.createSessionWithProgress((p) => onProgress({ progress: p, text: 'Downloading' }))
825
+ * },
826
+ * supported: doesBrowserSupportBrowserAI,
827
+ * contextWindowOf: (m) => m.getContextWindow(),
828
+ * }
829
+ * const local = useLocalModel('gemini-nano', nano)
830
+ * ```
831
+ *
832
+ * {@link useWebLLMModel} is this hook with the WebLLM engine.
833
+ */
834
+ declare const useLocalModel: <M extends LanguageModel = LanguageModel>(modelId: string, engine: LocalModelEngine<M>, options?: UseLocalModelOptions) => UseLocalModelReturn<M>;
835
+
836
+ /** The AI SDK `LanguageModel` a WebLLM build produces (resolved via agent-web). */
837
+ type WebLLMModel = Awaited<ReturnType<typeof createWebLLMModel>>;
838
+ /**
839
+ * Builds a WebLLM-backed `LanguageModel`. Defaults to the core's
840
+ * {@link createWebLLMModel}; override it via {@link UseWebLLMModelOptions.create}.
841
+ */
842
+ type WebLLMModelFactory = (modelId: string, options?: WebLLMModelOptions) => Promise<WebLLMModel>;
843
+ interface UseWebLLMModelOptions extends WebLLMModelOptions {
844
+ /**
845
+ * Override how the model is built. **Bundled browser apps (Vite, Next, …)
846
+ * usually need this**: the core builds WebLLM via `await import('@browser-ai/
847
+ * web-llm')`, and a bundler frequently stubs that dynamic import to an empty
848
+ * module — the failure surfaces as `webLLM is not a function`. Pass a factory
849
+ * that imports `webLLM` statically so the bundler includes it:
850
+ *
851
+ * ```ts
852
+ * import { webLLM } from '@browser-ai/web-llm'
853
+ * const create = (id, opts) => Promise.resolve(webLLM(id, opts))
854
+ * const local = useWebLLMModel('Qwen2.5-1.5B-Instruct-q4f16_1-MLC', { create })
855
+ * ```
856
+ *
857
+ * Defaults to `createWebLLMModel` from `@dudko.dev/agent-web`.
858
+ */
859
+ create?: WebLLMModelFactory;
783
860
  }
861
+ /** What {@link useWebLLMModel} returns — {@link UseLocalModelReturn} for a WebLLM model. */
862
+ type UseWebLLMModelReturn = UseLocalModelReturn<WebLLMModel>;
784
863
  /**
785
- * Load a local WebGPU model with WebLLM and track its download progress.
786
- * Nothing downloads until you call `load()` (models are large), so you can
787
- * gate it behind a user action. `load()` eagerly initializes the engine (via
788
- * the core's `preloadWebLLMModel`), so `ready` means "ready to chat" and
789
- * progress fills during the load rather than silently on the first message.
864
+ * Load a local WebGPU model with WebLLM and track its download progress —
865
+ * {@link useLocalModel} with the WebLLM engine. Nothing downloads until you
866
+ * call `load()` (models are large), so you can gate it behind a user action.
867
+ * `load()` eagerly initializes the engine (via the core's
868
+ * `preloadWebLLMModel`), so `ready` means "ready to chat" and progress fills
869
+ * during the load rather than silently on the first message.
790
870
  *
791
871
  * Everything it reports is about the **current** `modelId`: switch the id and
792
872
  * `model` / `ready` / `progress` / `error` describe the new one (not loaded
@@ -794,6 +874,10 @@ interface UseWebLLMModelReturn {
794
874
  * Loading the new id frees the previous one first, so two models never hold
795
875
  * GPU memory at once; `unload()` frees it on demand.
796
876
  *
877
+ * WebLLM loads its models with a 4096-token window; pass `contextWindowTokens`
878
+ * to load with more (Qwen3, Llama 3.x take far more — it costs KV-cache VRAM,
879
+ * not a new download). A different window is a different load.
880
+ *
797
881
  * ```tsx
798
882
  * import { webLLM } from '@browser-ai/web-llm' // your app's optional peer
799
883
  * const create = (id: string, opts?: WebLLMModelOptions) => Promise.resolve(webLLM(id, opts))
@@ -804,6 +888,12 @@ interface UseWebLLMModelReturn {
804
888
  * ```
805
889
  */
806
890
  declare const useWebLLMModel: (modelId: string, options?: UseWebLLMModelOptions) => UseWebLLMModelReturn;
891
+ /**
892
+ * The WebLLM {@link LocalModelEngine}: what {@link useWebLLMModel} runs, for
893
+ * hosts that switch between local runtimes with one {@link useLocalModel}
894
+ * (pass the window to that hook's `contextWindowTokens`).
895
+ */
896
+ declare const createWebLLMEngine: (options?: UseWebLLMModelOptions) => LocalModelEngine<WebLLMModel>;
807
897
 
808
898
  /**
809
899
  * Pure helpers behind `<AgentComposer>`: slash commands, attachments, notices
@@ -1578,4 +1668,4 @@ interface ApiKeyFormProps {
1578
1668
  */
1579
1669
  declare const ApiKeyForm: ({ credentials, credentialRef, label, placeholder, onChange, className, }: ApiKeyFormProps) => react.JSX.Element;
1580
1670
 
1581
- export { type AgentAction, AgentChat, type AgentChatClassNames, type AgentChatComponents, type AgentChatProps, type AgentChatSlots, AgentComposer, type AgentComposerProps, type AgentLabels, type AgentLabelsOverride, AgentLabelsProvider, type AgentLabelsProviderProps, AgentProvider, type AgentProviderProps, type AgentStatus, type AgentUiState, ApiKeyForm, type ApiKeyFormProps, ApprovalModeSwitch, type ApprovalModeSwitchProps, type ApprovalView, type ApproveOptions, AttachmentView, type BudgetView, type ChatAttachment, ChatHistoryList, type ChatHistoryListProps, ChatHistoryStore, type ChatHistoryStoreOptions, type ChatMessage, type ChatRecord, type ChatSummary, type CompactionView, Composer, type ComposerAttachment, type ComposerModelChip, type ComposerNotice, type ComposerProps, type ComposerThinkingChip, type ConnectedMcp, ContextMeter, type ContextMeterProps, type ConvertedFile, type DownscaleOptions, FilesPanel, type FilesPanelProps, type McpAuthMode, type McpCatalogEntry, type McpConnectOptions, type McpModule, type McpOAuthCallback, type McpServerResult, type McpServerSpec, type McpServerView, type McpStatus, MessageList, type MessageListProps, ModelLoadBar, type ModelLoadBarProps, type ModelLoadState, type NoticeTexts, PlanView, type PlanViewProps, type RenderToolCall, type ReplanState, type RunGoalOptions, type SlashCommand, type SpeechRecognizerLike, StepList, type StepListProps, type StepView, SubagentRow, type SubagentView, ToolApprovalPrompt, type ToolApprovalPromptProps, ToolCallRow, type ToolCallRowProps, type ToolCallView, UsageBadge, type UsageBadgeProps, type UseAgentOptions, type UseAgentReturn, type UseChatHistoryOptions, type UseChatHistoryReturn, type UseCredentialsReturn, type UseMcpOptions, type UseMcpReturn, type UseMcpServersOptions, type UseMcpServersReturn, type UseSpeechToTextOptions, type UseSpeechToTextReturn, type UseVirtualFilesReturn, type UseWebLLMModelOptions, type UseWebLLMModelReturn, type WebLLMModelFactory, agentStateReducer, attachmentKindOf, attachmentRefusal, chatTitle, claimOAuthCallback, createInitialAgentState, defaultLabels, describeMcpResult, downscaleImage, filterCommands, formatElapsed, isUnauthorizedError, mergeLabels, newChatId, noticesOf, parseSlash, readCallbackParams, stripOAuthParams, usageLine, useAgent, useAgentContext, useChatHistory, useCredentials, useLabels, useMcp, useMcpServers, useOptionalAgentContext, useSpeechToText, useVirtualFiles, useWebLLMModel, withAttachments };
1671
+ export { type AgentAction, AgentChat, type AgentChatClassNames, type AgentChatComponents, type AgentChatProps, type AgentChatSlots, AgentComposer, type AgentComposerProps, type AgentLabels, type AgentLabelsOverride, AgentLabelsProvider, type AgentLabelsProviderProps, AgentProvider, type AgentProviderProps, type AgentStatus, type AgentUiState, ApiKeyForm, type ApiKeyFormProps, ApprovalModeSwitch, type ApprovalModeSwitchProps, type ApprovalView, type ApproveOptions, AttachmentView, type BudgetView, type ChatAttachment, ChatHistoryList, type ChatHistoryListProps, ChatHistoryStore, type ChatHistoryStoreOptions, type ChatMessage, type ChatRecord, type ChatSummary, type CompactionView, Composer, type ComposerAttachment, type ComposerModelChip, type ComposerNotice, type ComposerProps, type ComposerThinkingChip, type ConnectedMcp, ContextMeter, type ContextMeterProps, type ConvertedFile, type DownscaleOptions, FilesPanel, type FilesPanelProps, type LocalModelEngine, type LocalModelLoadContext, type LocalModelProgress, type McpAuthMode, type McpCatalogEntry, type McpConnectOptions, type McpModule, type McpOAuthCallback, type McpServerResult, type McpServerSpec, type McpServerView, type McpStatus, MessageList, type MessageListProps, ModelLoadBar, type ModelLoadBarProps, type ModelLoadState, type NoticeTexts, PlanView, type PlanViewProps, type RenderToolCall, type ReplanState, type RunGoalOptions, type SlashCommand, type SpeechRecognizerLike, StepList, type StepListProps, type StepView, SubagentRow, type SubagentView, ToolApprovalPrompt, type ToolApprovalPromptProps, ToolCallRow, type ToolCallRowProps, type ToolCallView, UsageBadge, type UsageBadgeProps, type UseAgentOptions, type UseAgentReturn, type UseChatHistoryOptions, type UseChatHistoryReturn, type UseCredentialsReturn, type UseLocalModelOptions, type UseLocalModelReturn, type UseMcpOptions, type UseMcpReturn, type UseMcpServersOptions, type UseMcpServersReturn, type UseSpeechToTextOptions, type UseSpeechToTextReturn, type UseVirtualFilesReturn, type UseWebLLMModelOptions, type UseWebLLMModelReturn, type WebLLMModelFactory, agentStateReducer, attachmentKindOf, attachmentRefusal, chatTitle, claimOAuthCallback, createInitialAgentState, createWebLLMEngine, defaultLabels, describeMcpResult, downscaleImage, filterCommands, formatElapsed, isUnauthorizedError, mergeLabels, newChatId, noticesOf, parseSlash, readCallbackParams, stripOAuthParams, usageLine, useAgent, useAgentContext, useChatHistory, useCredentials, useLabels, useLocalModel, useMcp, useMcpServers, useOptionalAgentContext, useSpeechToText, useVirtualFiles, useWebLLMModel, withAttachments };