@dudko.dev/agent-web-react 0.0.11 β†’ 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/README.md CHANGED
@@ -21,7 +21,9 @@ app with a single hook and (optionally) a set of pre-styled components:
21
21
  `useVirtualFiles`, `useSpeechToText`, `useMcpServers`.
22
22
  - πŸ”‘ **`useCredentials`** β€” store BYOK API keys **encrypted at rest**
23
23
  (WebCrypto + IndexedDB).
24
- - πŸ–₯️ **`useWebLLMModel`** β€” load a local WebGPU model with download progress.
24
+ - πŸ–₯️ **`useWebLLMModel`** / **`useLocalModel`** β€” load an on-device model (WebLLM,
25
+ the browser's built-in model, transformers.js, or your own runtime) with
26
+ download progress, switching and unloading.
25
27
  - πŸŽ›οΈ **Headless-first** β€” the eventβ†’UI logic is a pure, exported reducer
26
28
  (`agentStateReducer`); the components are optional sugar on top.
27
29
 
@@ -223,6 +225,54 @@ function LocalAgent() {
223
225
  > not silently on the first message) and `ready` flips only once the model can
224
226
  > actually answer. The `create` option is what makes it work under a bundler β€”
225
227
  > see below.
228
+ >
229
+ > Change the `modelId` and everything the hook reports β€” `model`, `ready`,
230
+ > `loading`, `progress`, `error` β€” is about the new one, which is not loaded
231
+ > yet. The previous model stays in memory (`loadedModelId`; switching back is
232
+ > instant) until the new one is loaded β€” that frees it first, so two models
233
+ > never share the GPU β€” or until `unload()`.
234
+ >
235
+ > **Context window.** WebLLM loads its models with a 4096-token window, far
236
+ > below what Qwen3 or Llama 3.x were trained on. Pass `contextWindowTokens` to
237
+ > load with more (it costs KV-cache VRAM, not a new download); your `create`
238
+ > factory receives it and applies it with the core's `withWebLLMContextWindow`
239
+ > (see the demo's `providers.ts`). `local.contextWindow` is the window the model
240
+ > was loaded with, and the agent fits its runs into it on its own β€” compaction,
241
+ > tool lists and tool results are sized from it.
242
+ >
243
+ > **Vision.** `Phi-3.5-vision-instruct-q4f16_1-MLC` takes images (paste, drop
244
+ > or attach them) β€” a multimodal model that never sends them anywhere.
245
+
246
+ ### Any on-device runtime β€” `useLocalModel`
247
+
248
+ `useWebLLMModel` is `useLocalModel` with the WebLLM engine. Describe another
249
+ runtime as an engine β€” `create`, and optionally `warmUp` (download now, with
250
+ progress), `unload`, `supported`, `contextWindowOf` β€” and the hook gives the
251
+ same `load` / `unload` / progress / switching:
252
+
253
+ ```tsx
254
+ import { useLocalModel, createWebLLMEngine, type LocalModelEngine } from '@dudko.dev/agent-web-react'
255
+
256
+ const builtIn: LocalModelEngine = {
257
+ create: async () => (await import('@browser-ai/core')).browserAI('text', {
258
+ expectedInputs: [{ type: 'text' }, { type: 'image' }],
259
+ }),
260
+ warmUp: async (m, { onProgress }) => {
261
+ await m.createSessionWithProgress((p) => onProgress({ progress: p, text: 'Downloading' }))
262
+ },
263
+ supported: () => 'LanguageModel' in globalThis, // Chrome's Prompt API
264
+ contextWindowOf: (m) => m.getContextWindow(),
265
+ }
266
+ const webllm = createWebLLMEngine({ create: createLocalModel })
267
+
268
+ // One hook, any runtime: switching frees the previous model with its own engine.
269
+ const local = useLocalModel(option.model, option.builtIn ? builtIn : webllm, {
270
+ contextWindowTokens: option.contextWindow,
271
+ })
272
+ ```
273
+
274
+ The demo runs WebLLM, Chrome's Gemini Nano and transformers.js this way β€” see
275
+ [`demo/src/local-engines.ts`](demo/src/local-engines.ts).
226
276
 
227
277
  ## Models in a bundler (Vite, Next, CRA)
228
278
 
package/dist/index.cjs CHANGED
@@ -66,6 +66,7 @@ __export(src_exports, {
66
66
  createFileTools: () => import_agent_web4.createFileTools,
67
67
  createInitialAgentState: () => createInitialAgentState,
68
68
  createSubagentTool: () => import_agent_web4.createSubagentTool,
69
+ createWebLLMEngine: () => createWebLLMEngine,
69
70
  createWebLLMModel: () => import_agent_web4.createWebLLMModel,
70
71
  defaultLabels: () => defaultLabels,
71
72
  defineSkill: () => import_agent_web4.defineSkill,
@@ -96,6 +97,7 @@ __export(src_exports, {
96
97
  useChatHistory: () => useChatHistory,
97
98
  useCredentials: () => useCredentials,
98
99
  useLabels: () => useLabels,
100
+ useLocalModel: () => useLocalModel,
99
101
  useMcp: () => useMcp,
100
102
  useMcpServers: () => useMcpServers,
101
103
  useOptionalAgentContext: () => useOptionalAgentContext,
@@ -605,13 +607,18 @@ var useAgent = (config, options = {}) => {
605
607
  if (configMode !== modeRef.current) setApprovalMode(configMode);
606
608
  }, [configMode, setApprovalMode]);
607
609
  const reload = (0, import_react.useCallback)(() => setGeneration((g) => g + 1), []);
610
+ const buildStatusRef = (0, import_react.useRef)({ status: "idle" });
611
+ const setBuildStatus = (0, import_react.useCallback)((next) => {
612
+ buildStatusRef.current = next;
613
+ if (!abortRef.current) dispatch({ type: "status", ...next });
614
+ }, []);
608
615
  const { autoStart, deps } = options;
609
616
  (0, import_react.useEffect)(() => {
610
617
  agentRef.current = void 0;
611
618
  const cfg = configRef.current;
612
619
  const shouldBuild = (autoStart !== false || generation > 0) && Boolean(cfg.model);
613
620
  if (!shouldBuild) {
614
- dispatch({ type: "status", status: "idle" });
621
+ setBuildStatus({ status: "idle" });
615
622
  return;
616
623
  }
617
624
  const routeApprovals = optionsRef.current.approvals !== false && !cfg.toolApproval?.onRequest;
@@ -620,15 +627,15 @@ var useAgent = (config, options = {}) => {
620
627
  toolApproval: { ...cfg.toolApproval, mode: modeRef.current, onRequest: uiOnRequest }
621
628
  } : cfg;
622
629
  let cancelled = false;
623
- dispatch({ type: "status", status: "initializing" });
630
+ setBuildStatus({ status: "initializing" });
624
631
  (0, import_agent_web.createAgent)(built).then((agent) => {
625
632
  if (cancelled) return;
626
633
  agent.setToolApprovalMode(modeRef.current);
627
634
  agentRef.current = agent;
628
- dispatch({ type: "status", status: "ready" });
635
+ setBuildStatus({ status: "ready" });
629
636
  }).catch((err) => {
630
637
  if (cancelled) return;
631
- dispatch({ type: "status", status: "error", error: errMessage(err) });
638
+ setBuildStatus({ status: "error", error: errMessage(err) });
632
639
  });
633
640
  return () => {
634
641
  cancelled = true;
@@ -680,7 +687,7 @@ var useAgent = (config, options = {}) => {
680
687
  } finally {
681
688
  abortRef.current = void 0;
682
689
  settleAll({ approved: false, reason: "the run ended" });
683
- dispatch({ type: "status", status: "ready" });
690
+ dispatch({ type: "status", ...buildStatusRef.current });
684
691
  }
685
692
  },
686
693
  [settleAll]
@@ -1713,58 +1720,144 @@ var useMcpServers = (options = {}) => {
1713
1720
  };
1714
1721
 
1715
1722
  // src/hooks/use-webllm-model.ts
1716
- var import_react8 = require("react");
1717
1723
  var import_agent_web3 = require("@dudko.dev/agent-web");
1718
- var useWebLLMModel = (modelId, options) => {
1719
- const [model, setModel] = (0, import_react8.useState)(void 0);
1720
- const [loading, setLoading] = (0, import_react8.useState)(false);
1721
- const [progress, setProgress] = (0, import_react8.useState)(0);
1722
- const [text, setText] = (0, import_react8.useState)("");
1723
- const [error, setError] = (0, import_react8.useState)(void 0);
1724
- const optionsRef = (0, import_react8.useRef)(options);
1725
- optionsRef.current = options;
1726
- const load = (0, import_react8.useCallback)(async () => {
1727
- if (!(0, import_agent_web3.isWebGPUAvailable)()) {
1728
- setError("WebGPU is not available in this browser.");
1729
- return void 0;
1730
- }
1731
- setLoading(true);
1732
- setError(void 0);
1733
- setProgress(0);
1734
- setText("");
1724
+
1725
+ // src/hooks/use-local-model.ts
1726
+ var import_react8 = require("react");
1727
+ var keyOf = (id, tokens) => tokens ? `${id}@${tokens}` : id;
1728
+ var useLocalModel = (modelId, engine, options) => {
1729
+ const [loaded, setLoaded] = (0, import_react8.useState)(void 0);
1730
+ const [pending, setPending] = (0, import_react8.useState)();
1731
+ const [failure, setFailure] = (0, import_react8.useState)();
1732
+ const engineRef = (0, import_react8.useRef)(engine);
1733
+ engineRef.current = engine;
1734
+ const loadedRef = (0, import_react8.useRef)(void 0);
1735
+ const inflightRef = (0, import_react8.useRef)(
1736
+ void 0
1737
+ );
1738
+ const windowTokens = options?.contextWindowTokens;
1739
+ const key = keyOf(modelId, windowTokens);
1740
+ const seqRef = (0, import_react8.useRef)(0);
1741
+ const setHeld = (next) => {
1742
+ loadedRef.current = next;
1743
+ setLoaded(next);
1744
+ };
1745
+ const freeWith = (eng, model2) => async () => {
1735
1746
  try {
1736
- const { create = import_agent_web3.createWebLLMModel, ...modelOptions } = optionsRef.current ?? {};
1737
- const built = await create(modelId, {
1738
- ...modelOptions,
1739
- // Drive preload here (below) so download progress is reported the same
1740
- // way whether `create` is the core's `createWebLLMModel` or an injected
1741
- // factory (e.g. a statically-imported `webLLM`, needed under bundlers).
1742
- preload: false,
1743
- initProgressCallback: (report) => {
1744
- setProgress(report.progress);
1745
- setText(report.text);
1746
- modelOptions.initProgressCallback?.(report);
1747
- }
1747
+ await eng.unload?.(model2);
1748
+ } catch {
1749
+ }
1750
+ };
1751
+ const load = (0, import_react8.useCallback)(() => {
1752
+ const id = modelId;
1753
+ if (loadedRef.current?.key === key) return Promise.resolve(loadedRef.current.model);
1754
+ if (inflightRef.current?.key === key) return inflightRef.current.promise;
1755
+ const eng = engineRef.current;
1756
+ if (eng.supported && !eng.supported()) {
1757
+ setFailure({
1758
+ key,
1759
+ message: eng.unsupportedMessage ?? "This browser cannot run this model."
1748
1760
  });
1749
- await (0, import_agent_web3.preloadWebLLMModel)(built);
1750
- setModel(built);
1751
- return built;
1752
- } catch (err) {
1753
- setError(errMessage(err));
1754
- return void 0;
1755
- } finally {
1756
- setLoading(false);
1761
+ return Promise.resolve(void 0);
1757
1762
  }
1758
- }, [modelId]);
1763
+ const seq = ++seqRef.current;
1764
+ const current = () => seq === seqRef.current;
1765
+ const ctx = {
1766
+ onProgress: (report) => {
1767
+ if (current()) setPending({ key, progress: report.progress, text: report.text });
1768
+ },
1769
+ ...windowTokens ? { contextWindowTokens: windowTokens } : {}
1770
+ };
1771
+ const promise = (async () => {
1772
+ setPending({ key, progress: 0, text: "" });
1773
+ setFailure(void 0);
1774
+ let built;
1775
+ try {
1776
+ const previous = loadedRef.current;
1777
+ if (previous) {
1778
+ setHeld(void 0);
1779
+ await previous.free();
1780
+ }
1781
+ built = await eng.create(id, ctx);
1782
+ await eng.warmUp?.(built, ctx);
1783
+ if (!current()) {
1784
+ await freeWith(eng, built)();
1785
+ return void 0;
1786
+ }
1787
+ setHeld({ id, key, model: built, free: freeWith(eng, built) });
1788
+ return built;
1789
+ } catch (err) {
1790
+ if (built) await freeWith(eng, built)();
1791
+ if (current()) setFailure({ key, message: errMessage(err) });
1792
+ return void 0;
1793
+ } finally {
1794
+ if (current()) {
1795
+ inflightRef.current = void 0;
1796
+ setPending(void 0);
1797
+ }
1798
+ }
1799
+ })();
1800
+ inflightRef.current = { key, promise };
1801
+ return promise;
1802
+ }, [modelId, key]);
1803
+ const unload = (0, import_react8.useCallback)(async () => {
1804
+ seqRef.current++;
1805
+ inflightRef.current = void 0;
1806
+ setPending(void 0);
1807
+ const previous = loadedRef.current;
1808
+ setHeld(void 0);
1809
+ if (previous) await previous.free();
1810
+ }, []);
1811
+ const model = loaded?.key === key ? loaded.model : void 0;
1812
+ const progressing = pending?.key === key ? pending : void 0;
1759
1813
  return {
1760
1814
  model,
1761
1815
  load,
1762
- loading,
1763
- progress,
1764
- text,
1765
- error,
1766
- supported: (0, import_agent_web3.isWebGPUAvailable)(),
1767
- ready: model !== void 0
1816
+ unload,
1817
+ loadedModelId: loaded?.id,
1818
+ loading: progressing !== void 0,
1819
+ progress: progressing?.progress ?? 0,
1820
+ text: progressing?.text ?? "",
1821
+ error: failure?.key === key ? failure.message : void 0,
1822
+ supported: engine.supported ? engine.supported() : true,
1823
+ ready: model !== void 0,
1824
+ contextWindow: model ? engine.contextWindowOf?.(model) : void 0
1825
+ };
1826
+ };
1827
+
1828
+ // src/hooks/use-webllm-model.ts
1829
+ var useWebLLMModel = (modelId, options) => useLocalModel(modelId, createWebLLMEngine(options), {
1830
+ contextWindowTokens: options?.contextWindowTokens
1831
+ });
1832
+ var createWebLLMEngine = (options) => {
1833
+ const {
1834
+ create = import_agent_web3.createWebLLMModel,
1835
+ contextWindowTokens: _perLoad,
1836
+ ...modelOptions
1837
+ } = options ?? {};
1838
+ return {
1839
+ create: (id, ctx) => create(id, {
1840
+ ...modelOptions,
1841
+ ...ctx.contextWindowTokens ? { contextWindowTokens: ctx.contextWindowTokens } : {},
1842
+ // Drive preload in warmUp (below) so download progress is reported the
1843
+ // same way whether `create` is the core's `createWebLLMModel` or an
1844
+ // injected factory (e.g. a statically-imported `webLLM`, needed under
1845
+ // bundlers).
1846
+ preload: false,
1847
+ initProgressCallback: (report) => {
1848
+ ctx.onProgress({ progress: report.progress, text: report.text });
1849
+ modelOptions.initProgressCallback?.(report);
1850
+ }
1851
+ }),
1852
+ // Download the weights + init the engine now via the core's helper (a
1853
+ // 1-token warm-up). WebLLM builds are otherwise lazy β€” the ~GB download
1854
+ // would only start on the first `run()`, long after we told the UI the
1855
+ // model is "ready". Fast + idempotent once the weights are cached.
1856
+ warmUp: (model) => (0, import_agent_web3.preloadWebLLMModel)(model),
1857
+ unload: import_agent_web3.unloadWebLLMModel,
1858
+ supported: import_agent_web3.isWebGPUAvailable,
1859
+ unsupportedMessage: "WebGPU is not available in this browser.",
1860
+ contextWindowOf: import_agent_web3.webLLMContextWindow
1768
1861
  };
1769
1862
  };
1770
1863
 
@@ -1948,7 +2041,13 @@ var defaultLabels = {
1948
2041
  readOnly: "Only read; refuse changes",
1949
2042
  think: (levels) => `Set thinking: ${levels}`
1950
2043
  },
1951
- thinkingLevels: { off: "Default", low: "Low", medium: "Medium", high: "High" },
2044
+ thinkingLevels: {
2045
+ off: "Default",
2046
+ none: "No thinking",
2047
+ low: "Low",
2048
+ medium: "Medium",
2049
+ high: "High"
2050
+ },
1952
2051
  filesEmpty: "No files yet. Attachments and files the agent writes appear here.",
1953
2052
  upload: "Upload",
1954
2053
  download: "Download",
@@ -2135,6 +2234,7 @@ var DownloadIcon = ({ size, className }) => /* @__PURE__ */ (0, import_jsx_runti
2135
2234
  var import_jsx_runtime4 = require("react/jsx-runtime");
2136
2235
  var thinkingDefaults = (l) => [
2137
2236
  { id: "off", label: l.thinkingLevels.off },
2237
+ { id: "none", label: l.thinkingLevels.none },
2138
2238
  { id: "low", label: l.thinkingLevels.low },
2139
2239
  { id: "medium", label: l.thinkingLevels.medium },
2140
2240
  { id: "high", label: l.thinkingLevels.high }
@@ -4019,6 +4119,7 @@ var import_agent_web4 = require("@dudko.dev/agent-web");
4019
4119
  createFileTools,
4020
4120
  createInitialAgentState,
4021
4121
  createSubagentTool,
4122
+ createWebLLMEngine,
4022
4123
  createWebLLMModel,
4023
4124
  defaultLabels,
4024
4125
  defineSkill,
@@ -4049,6 +4150,7 @@ var import_agent_web4 = require("@dudko.dev/agent-web");
4049
4150
  useChatHistory,
4050
4151
  useCredentials,
4051
4152
  useLabels,
4153
+ useLocalModel,
4052
4154
  useMcp,
4053
4155
  useMcpServers,
4054
4156
  useOptionalAgentContext,