@zerogpu/browser-extension-sdk 0.4.0-dev.202609241547.g4addd51 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +99 -0
  2. package/bin/zerogpu.mjs +10 -1
  3. package/dist/assets/zerogpu-assets.json +4 -3
  4. package/dist/assets/zerogpu-worker.js +1 -0
  5. package/dist/extension/zerogpu-background.js +1 -1
  6. package/dist/extension/zerogpu-offscreen.js +1 -1
  7. package/dist/loader.js +1 -1
  8. package/dist/manifest.json +6 -6
  9. package/dist/types/adapters/cached-load.d.ts +19 -0
  10. package/dist/types/adapters/kinds.d.ts +8 -0
  11. package/dist/types/adapters/onnx/adapter.d.ts +5 -10
  12. package/dist/types/adapters/onnx/executor.d.ts +41 -0
  13. package/dist/types/adapters/onnx/runtime.d.ts +28 -11
  14. package/dist/types/adapters/transformers/adapter.d.ts +5 -7
  15. package/dist/types/adapters/transformers/executor.d.ts +10 -0
  16. package/dist/types/adapters/types.d.ts +38 -1
  17. package/dist/types/appinference/eligible.d.ts +12 -0
  18. package/dist/types/appinference/store.d.ts +42 -0
  19. package/dist/types/appinference/types.d.ts +118 -0
  20. package/dist/types/config/types.d.ts +19 -0
  21. package/dist/types/device/telemetry.d.ts +6 -0
  22. package/dist/types/extension/background.d.ts +36 -0
  23. package/dist/types/extension/offscreen.d.ts +34 -5
  24. package/dist/types/inference/execution.d.ts +33 -0
  25. package/dist/types/inference/runtime-locator.d.ts +35 -0
  26. package/dist/types/inference/worker-client.d.ts +64 -0
  27. package/dist/types/inference/worker-entry.d.ts +1 -0
  28. package/dist/types/inference/worker-host.d.ts +14 -0
  29. package/dist/types/inference/worker-protocol.d.ts +80 -0
  30. package/dist/types/inference/worker-source.d.ts +1 -0
  31. package/dist/types/loader.d.ts +1 -0
  32. package/dist/types/public-api.d.ts +41 -7
  33. package/dist/types/runtime/app-identity.d.ts +24 -0
  34. package/dist/types/runtime/app-inference.d.ts +60 -0
  35. package/dist/types/runtime/guardrails.d.ts +31 -8
  36. package/dist/types/runtime/host-api.d.ts +13 -1
  37. package/dist/types/runtime/init-guard.d.ts +7 -0
  38. package/dist/types/runtime/lifecycle-options.d.ts +12 -0
  39. package/dist/types/runtime/lifecycle.d.ts +21 -8
  40. package/dist/types/runtime/restart.d.ts +11 -0
  41. package/dist/types/runtime/router.d.ts +13 -0
  42. package/dist/types/runtime/sdk-state.d.ts +24 -0
  43. package/dist/types/runtime/shutdown.d.ts +21 -3
  44. package/dist/types/storage/cached-model.d.ts +31 -2
  45. package/dist/types/telemetry/event-reporter.d.ts +1 -0
  46. package/dist/types/transport/http.d.ts +67 -0
  47. package/dist/types/utils/logger.d.ts +10 -2
  48. package/dist/v/zerogpu-browser-sdk.5f140942519b.umd.js +1 -0
  49. package/dist/zerogpu-browser-sdk.cjs +1 -1
  50. package/dist/zerogpu-browser-sdk.esm.js +1 -1
  51. package/dist/zerogpu-browser-sdk.umd.js +1 -1
  52. package/dist/zerogpu-worker.js +1 -0
  53. package/docs/APP_INFERENCE_E2E_2026-11-06_DEV.md +855 -0
  54. package/docs/app-side-inference.md +537 -0
  55. package/docs/extension-developer-guide.md +36 -1
  56. package/docs/multi-model-support.md +5 -1
  57. package/package.json +2 -1
  58. package/dist/v/zerogpu-browser-sdk.2a8813959ec2.umd.js +0 -1
@@ -0,0 +1,19 @@
1
+ import { SlmConfig } from '../config/types';
2
+ import { AdapterCapability, AdapterLoadOptions, AdapterLoadResult, ExecutorLoader } from './types';
3
+ /**
4
+ * The main-thread half of a transformers.js-backed adapter: the IndexedDB
5
+ * model cache around an executor. Reads the cached files, lets the executor
6
+ * load (downloading what is missing — on whichever thread the execution
7
+ * strategy picked), then persists the downloads and computes the metrics.
8
+ * The cache format and its best-effort semantics are exactly those of the
9
+ * former per-adapter loaders.
10
+ */
11
+ export interface CachedAdapterSpec {
12
+ /** Prefix of the failure log line, e.g. `[SLM][loadOnnxAdapter]`. */
13
+ logLabel: string;
14
+ capability: (slm: SlmConfig) => AdapterCapability;
15
+ loadExecutor: ExecutorLoader;
16
+ /** Adapter-specific diagnostics on a failed load, before the generic error line. */
17
+ onLoadError?: (error: unknown, slm: SlmConfig) => void;
18
+ }
19
+ export declare const loadAdapterWithCache: (slm: SlmConfig, options: AdapterLoadOptions | undefined, spec: CachedAdapterSpec) => Promise<AdapterLoadResult>;
@@ -14,6 +14,14 @@ export declare const INFERENCE_KINDS: {
14
14
  readonly ZERO_SHOT_CLASSIFICATION: "zero_shot_classification";
15
15
  /** Decoder-only generation (GGUF via wllama) → `{ text }`. */
16
16
  readonly DECODER_GENERATION: "decoder_generation";
17
+ /** Per-token labels (NER, PII) merged into spans → `{ entities, tokens }`. */
18
+ readonly TOKEN_CLASSIFICATION: "token_classification";
19
+ /** Extractive QA over `{ question, context }` → `{ answer, score, start, end }`. */
20
+ readonly QUESTION_ANSWERING: "question_answering";
21
+ /** Mean-pooled, unit-length sentence vector → `{ embedding }`. */
22
+ readonly TEXT_EMBEDDING: "text_embedding";
23
+ /** Masked-token prediction → `{ predictions, text }`. */
24
+ readonly FILL_MASK: "fill_mask";
17
25
  };
18
26
  export type InferenceKind = (typeof INFERENCE_KINDS)[keyof typeof INFERENCE_KINDS];
19
27
  /** Trimmed, lower-cased kind, or undefined when absent/blank. */
@@ -1,15 +1,10 @@
1
1
  import { SlmConfig } from '../../config/types';
2
2
  import { AdapterLoadOptions, AdapterLoadResult } from '../types';
3
- import { INFERENCE_KINDS } from '../kinds';
3
+ export { DEFAULT_SEQ2SEQ_MAX_NEW_TOKENS, resolveOnnxRunner, resolvePipelineTask } from './executor';
4
+ export type { OnnxRunner } from './executor';
4
5
  /**
5
- * Which runner serves a recipe. A supported `inferenceKind` decides, whatever
6
- * the taskType; without one (or with a kind this adapter does not implement)
7
- * the historical taskType mapping applies — `'task'`.
6
+ * ONNX adapter: the model cache (main thread) around the ONNX executor, which
7
+ * the execution strategy runs in the inference worker by default and on the
8
+ * main thread when the host forces it or no Worker is available.
8
9
  */
9
- export type OnnxRunner = typeof INFERENCE_KINDS.SEQUENCE_CLASSIFICATION | typeof INFERENCE_KINDS.SEQ2SEQ_GENERATION | typeof INFERENCE_KINDS.ZERO_SHOT_CLASSIFICATION | 'task';
10
- export declare const resolveOnnxRunner: (config: Pick<SlmConfig, "inferenceKind">) => OnnxRunner;
11
- /** transformers.js pipeline task a pipeline-backed runner loads. */
12
- export declare const resolvePipelineTask: (config: Pick<SlmConfig, "inferenceKind" | "taskType">) => string;
13
- /** seq2seq default when generation_config.json declares no max_new_tokens. */
14
- export declare const DEFAULT_SEQ2SEQ_MAX_NEW_TOKENS = 48;
15
10
  export declare const loadOnnxAdapter: (slm: SlmConfig, options?: AdapterLoadOptions) => Promise<AdapterLoadResult>;
@@ -0,0 +1,41 @@
1
+ import { SlmConfig } from '../../config/types';
2
+ import { ExecutorLoader } from '../types';
3
+ import { INFERENCE_KINDS } from '../kinds';
4
+ /**
5
+ * Which runner serves a recipe. A supported `inferenceKind` decides, whatever
6
+ * the taskType; without one (or with a kind this adapter does not implement)
7
+ * the historical taskType mapping applies — `'task'`.
8
+ */
9
+ export type OnnxRunner = typeof INFERENCE_KINDS.SEQUENCE_CLASSIFICATION | typeof INFERENCE_KINDS.SEQ2SEQ_GENERATION | typeof INFERENCE_KINDS.ZERO_SHOT_CLASSIFICATION | typeof INFERENCE_KINDS.TOKEN_CLASSIFICATION | typeof INFERENCE_KINDS.QUESTION_ANSWERING | typeof INFERENCE_KINDS.TEXT_EMBEDDING | typeof INFERENCE_KINDS.FILL_MASK | 'task';
10
+ export declare const resolveOnnxRunner: (config: Pick<SlmConfig, "inferenceKind">) => OnnxRunner;
11
+ /** transformers.js pipeline task a pipeline-backed runner loads. */
12
+ export declare const resolvePipelineTask: (config: Pick<SlmConfig, "inferenceKind" | "taskType">) => string;
13
+ /** seq2seq default when generation_config.json declares no max_new_tokens. */
14
+ export declare const DEFAULT_SEQ2SEQ_MAX_NEW_TOKENS = 48;
15
+ /** fill_mask predictions returned when the input names no `top_k`. */
16
+ export declare const DEFAULT_FILL_MASK_TOP_K = 5;
17
+ export interface TokenEntity {
18
+ label: string;
19
+ text: string;
20
+ /** Character offsets in the input, or -1 when the span could not be located. */
21
+ start: number;
22
+ end: number;
23
+ score: number;
24
+ }
25
+ export interface TokenLabel {
26
+ token: string;
27
+ label: string;
28
+ score: number;
29
+ }
30
+ /**
31
+ * Merges transformers.js word pieces into labelled spans — BIO prefixes become
32
+ * one entity, `##` continuations rejoin their word — with character offsets
33
+ * found by walking the input left to right (the 2.x pipeline reports none).
34
+ * Output contract shared with Android: `{ entities, tokens }`.
35
+ */
36
+ export declare const tokenClassificationOutput: (text: string, raw: unknown) => {
37
+ entities: TokenEntity[];
38
+ tokens: TokenLabel[];
39
+ };
40
+ /** Loads an ONNX model on the calling thread and returns its runner. */
41
+ export declare const createOnnxExecutor: ExecutorLoader;
@@ -1,3 +1,5 @@
1
+ import { TRANSFORMERS_CDN } from '../../inference/runtime-locator';
2
+ export { TRANSFORMERS_CDN };
1
3
  /**
2
4
  * transformers.js is loaded at runtime from a CDN (or a vendored copy under
3
5
  * MV3) and ships no types we can import, so these describe only the surface
@@ -61,24 +63,39 @@ export interface TransformersLib {
61
63
  };
62
64
  Tensor: new (type: string, data: BigInt64Array, dims: number[]) => unknown;
63
65
  }
64
- declare global {
65
- interface Window {
66
- TransformersPipeline?: (task: string, modelPath: string, options?: Record<string, unknown>) => Promise<TransformersPipelineFn>;
67
- TransformersEnv?: TransformersEnv;
68
- TransformersLib?: TransformersLib;
69
- }
66
+ export type TransformersPipelineFactory = (task: string, modelPath: string, options?: Record<string, unknown>) => Promise<TransformersPipelineFn>;
67
+ /**
68
+ * The transformers.js exports, published on the global object of whichever
69
+ * thread loaded the runtime — the page, or the inference worker. Always read
70
+ * through {@link transformersGlobals}: the worker has no `window`.
71
+ */
72
+ export interface TransformersGlobals {
73
+ TransformersPipeline?: TransformersPipelineFactory;
74
+ TransformersEnv?: TransformersEnv;
75
+ TransformersLib?: TransformersLib;
70
76
  }
77
+ export declare const transformersGlobals: () => TransformersGlobals;
71
78
  /** Picks the {@link TransformersLib} exports off an imported transformers.js module. */
72
79
  export declare const pickTransformersLib: (mod: unknown) => TransformersLib | undefined;
73
80
  export declare const requireTransformersLib: () => TransformersLib;
74
81
  /**
75
- * transformers.js 2.x throws "Browser cache is not available in this
76
- * environment" when `caches` is undefined (non-secure contexts, some WebViews),
77
- * turning a missing optional cache into a load failure. Turn its Cache API
78
- * layer off there. The SDK's own IndexedDB store stays best-effort either way.
82
+ * The SDK's IndexedDB store is the one model cache: every file transformers.js
83
+ * asks for goes through the SDK's fetch hook, which serves cached files and
84
+ * persists downloads. transformers.js's own Cache API layer is turned off —
85
+ * until 0.5.0 it kept a second copy of every file (keyed under its remote host,
86
+ * so the SDK's eviction never found it), which doubled the disk footprint and
87
+ * served evicted models back without the SDK knowing. It also throws "Browser
88
+ * cache is not available in this environment" where `caches` is undefined
89
+ * (non-secure contexts, some WebViews).
79
90
  */
80
91
  export declare const disableBrowserCacheIfUnavailable: (env: TransformersEnv | undefined) => void;
81
- export declare const TRANSFORMERS_CDN = "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";
92
+ /** Cache names transformers.js used for its own copies before 0.5.0. */
93
+ export declare const LEGACY_TRANSFORMERS_CACHE_NAME = "transformers-cache";
94
+ /**
95
+ * Imports transformers.js from wherever the runtime locator points (CDN by
96
+ * default, the vendored copy under MV3) and publishes its exports on this
97
+ * thread's global. Idempotent; a failed import is retried on the next call.
98
+ */
82
99
  export declare const ensureTransformersRuntime: () => Promise<void>;
83
100
  export declare const sanitizeBaseUrl: (url: string) => string;
84
101
  export declare const isHttpUrl: (value: string) => boolean;
@@ -1,10 +1,8 @@
1
1
  import { SlmConfig } from '../../config/types';
2
2
  import { AdapterLoadOptions, AdapterLoadResult } from '../types';
3
- export interface ExtractedEntity {
4
- text: string;
5
- label: string;
6
- score: number;
7
- start: number;
8
- end: number;
9
- }
3
+ export type { ExtractedEntity } from './executor';
4
+ /**
5
+ * Transformers (token-classification) adapter: the model cache around the
6
+ * executor, which runs in the inference worker by default.
7
+ */
10
8
  export declare const loadTransformersAdapter: (slm: SlmConfig, options?: AdapterLoadOptions) => Promise<AdapterLoadResult>;
@@ -0,0 +1,10 @@
1
+ import { ExecutorLoader } from '../types';
2
+ export interface ExtractedEntity {
3
+ text: string;
4
+ label: string;
5
+ score: number;
6
+ start: number;
7
+ end: number;
8
+ }
9
+ /** Loads a token-classification model on the calling thread and returns its runner. */
10
+ export declare const createTransformersExecutor: ExecutorLoader;
@@ -26,8 +26,12 @@ export interface InferenceInput {
26
26
  schema?: unknown;
27
27
  mask?: string;
28
28
  maxNewTokens?: number;
29
- /** sequence_classification: how many top labels to return (default 50). */
29
+ /** sequence_classification / fill_mask: how many top labels or predictions to return. */
30
30
  topK?: number;
31
+ top_k?: number;
32
+ /** question_answering: the question; the passage is `context` (or `text`). */
33
+ question?: string;
34
+ context?: string;
31
35
  type?: string;
32
36
  [key: string]: unknown;
33
37
  }
@@ -41,6 +45,12 @@ export interface SampleTestResult {
41
45
  error: boolean;
42
46
  errorMessage?: string;
43
47
  }
48
+ /**
49
+ * The warm-up sample the catalog serves for a model. Opaque beyond `text`:
50
+ * a kind may need more (`question` for extractive QA, `maxNewTokens` for
51
+ * generation), and the executor hands the whole bag to the same input path a
52
+ * task uses.
53
+ */
44
54
  export interface TaskSample {
45
55
  text: string;
46
56
  categories?: string[];
@@ -50,6 +60,10 @@ export interface TaskSample {
50
60
  schema?: unknown;
51
61
  mask?: string;
52
62
  usecase?: string;
63
+ question?: string;
64
+ context?: string;
65
+ maxNewTokens?: number;
66
+ [key: string]: unknown;
53
67
  }
54
68
  export interface ModelAdapter {
55
69
  readonly config: SlmConfig;
@@ -59,6 +73,29 @@ export interface ModelAdapter {
59
73
  runSample(sample: TaskSample): Promise<SampleTestResult>;
60
74
  dispose?(): Promise<void>;
61
75
  }
76
+ /**
77
+ * A loaded model that runs — the thread-agnostic core of an adapter. The
78
+ * model cache (IndexedDB), load metrics and registry bookkeeping stay on the
79
+ * main thread and wrap an executor whether it lives there or in the inference
80
+ * worker (see inference/execution.ts).
81
+ */
82
+ export interface ModelExecutor {
83
+ readonly loadModelMs: number;
84
+ runInference(input: InferenceInput): Promise<InferenceOutput>;
85
+ runSample(sample: TaskSample): Promise<SampleTestResult>;
86
+ dispose?(): Promise<void>;
87
+ }
88
+ /** Called for every model file the runtime had to fetch (cache key → bytes). */
89
+ export type FileDownloadedCallback = (filename: string, blob: Blob) => void;
90
+ export interface ExecutorContext {
91
+ /** Served wasm guardrails, when the caller resolves them elsewhere (the worker). */
92
+ wasm?: {
93
+ maxThreads: number;
94
+ proxyWorker: boolean;
95
+ };
96
+ }
97
+ /** Instantiates a model from its cached files, downloading whatever is missing. */
98
+ export type ExecutorLoader = (slm: SlmConfig, cachedFiles: Record<string, Blob>, onFileDownloaded: FileDownloadedCallback, context?: ExecutorContext) => Promise<ModelExecutor>;
62
99
  export interface AdapterLoadOptions {
63
100
  allowDownload?: boolean;
64
101
  }
@@ -0,0 +1,12 @@
1
+ import { EligibleModelLine } from '../transport/http';
2
+ import { EligibleModel } from './types';
3
+ /**
4
+ * Merges the registry's judgement with what only the device knows (design
5
+ * §2.2): whether the files are in the cache, and whether the model is the
6
+ * active one. The registry already folds this device's unfit marks into its
7
+ * verdict (`device_unfit`), since they ride on the request.
8
+ */
9
+ export declare const mergeEligibleModels: (lines: EligibleModelLine[], downloaded: Array<{
10
+ modelId: string;
11
+ modelVersion?: string;
12
+ }>, activeModelId: string | null) => EligibleModel[];
@@ -0,0 +1,42 @@
1
+ /**
2
+ * What the app-side protocol remembers across page loads, in localStorage
3
+ * (with an in-memory fallback where storage is blocked):
4
+ *
5
+ * - the app's **chosen model** (design §2.3): sent as `requestedModelId` with
6
+ * every register until the app switches again, clears it, or the registry
7
+ * refuses it;
8
+ * - the **unfit marks** (design §2, rule 6): models whose warm-up failed on this
9
+ * device, sent as `unfitModels` with every register and the eligible call so
10
+ * the registry walks past them. A mark is scoped to the catalog version and
11
+ * the SDK version that produced it, so a re-published model or a newer SDK
12
+ * gets another try; the app can also forget a mark explicitly.
13
+ */
14
+ export interface UnfitMark {
15
+ modelId: string;
16
+ modelVersion: string;
17
+ reason: string;
18
+ sdkVersion: string;
19
+ at: number;
20
+ }
21
+ /** The wire shape the registry reads (`unfitModels` on register and eligible). */
22
+ export interface UnfitModelRef {
23
+ modelId: string;
24
+ modelVersion?: string;
25
+ reason?: string;
26
+ }
27
+ export declare const KEY_CHOSEN_MODEL = "zerogpu_app_inference_chosen_model";
28
+ export declare const KEY_UNFIT_MODELS = "zerogpu_app_inference_unfit_models";
29
+ /** The registry reads at most 16 marks; keep the newest 16. */
30
+ export declare const MAX_UNFIT_MARKS = 16;
31
+ export declare const getChosenModelId: () => string | null;
32
+ export declare const chooseModel: (modelId: string) => void;
33
+ export declare const clearChosenModel: () => void;
34
+ /** The live marks: this SDK version's verdicts, one per model. */
35
+ export declare const unfitMarks: (sdkVersion: string) => UnfitMark[];
36
+ /** The marks as the registry wants them. */
37
+ export declare const unfitModelRefs: (sdkVersion: string) => UnfitModelRef[];
38
+ export declare const unfitMark: (modelId: string, sdkVersion: string) => UnfitMark | undefined;
39
+ export declare const markModelUnfit: (modelId: string, modelVersion: string, reason: string, sdkVersion: string, now?: number) => void;
40
+ export declare const forgetUnfitModel: (modelId: string) => void;
41
+ /** Test hook. */
42
+ export declare const __resetAppInferenceStore: () => void;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * App-side inference, phase 1 (device-registry docs/SDK_APP_INFERENCE_DESIGN.md §2),
3
+ * the browser / Chrome-extension shape of what the Android SDK ships in 0.4.0.
4
+ *
5
+ * The model this device holds for the ZeroGPU network can also serve the host
6
+ * app, and the app may choose which eligible model that is. This module is the
7
+ * host-facing vocabulary of that protocol: the eligible list, the outcome of a
8
+ * switch, a local result, the contribution state and the typed errors.
9
+ */
10
+ /** Where the device stands in the network; local inference runs only in `contributing`. */
11
+ export type ContributionState =
12
+ /** The SDK is not started, was stopped by the host, or is waiting out a guardrail restart. */
13
+ 'stopped'
14
+ /** Register in flight, or waiting for the next attempt. */
15
+ | 'registering'
16
+ /** The registry declined this device (admission rules, or no model fits). */
17
+ | 'declined'
18
+ /** Downloading, loading or warming up the assigned model. */
19
+ | 'preparing'
20
+ /** The app asked for another model; the previous flow is being torn down. */
21
+ | 'switching'
22
+ /** Memory pressure: nothing runs until the device recovers (`recovered` event). */
23
+ | 'degraded'
24
+ /** Registered, model loaded, session open: tasks run, local calls run. */
25
+ | 'contributing';
26
+ export declare const CONTRIBUTION_STATES: readonly ContributionState[];
27
+ /** One line of `eligibleModels()`. */
28
+ export interface EligibleModel {
29
+ modelId: string;
30
+ modelVersion: string;
31
+ displayName?: string;
32
+ taskType?: string;
33
+ /** The on-device pipeline (e.g. `zero_shot_classification`): what a local call's input must look like. */
34
+ inferenceKind?: string;
35
+ /** `onnx` or `gguf`. */
36
+ inferenceFramework?: string;
37
+ /** Download size in bytes, when the catalog knows it. */
38
+ sizeBytes?: number;
39
+ /** The model's own cap from the catalog. No fleet cap applies to local calls. */
40
+ maxTokens?: number;
41
+ /** Judged by the registry with the same rules it applies at register time. */
42
+ eligible: boolean;
43
+ /**
44
+ * Why not, when not eligible: `model_too_large_for_memory`, `low_battery`,
45
+ * `guardrail_blocked`, `sdk_too_old`, or `device_unfit` when this device
46
+ * tried the model and its warm-up failed (the reason is in `detail`).
47
+ */
48
+ reason?: string;
49
+ rule?: string;
50
+ detail: Record<string, string>;
51
+ /** The files are in this device's cache: switching to it is a reload, not a download. */
52
+ downloaded: boolean;
53
+ /** The model the device holds right now; local calls run on it. */
54
+ active: boolean;
55
+ }
56
+ /** What `switchModel()` ends in. */
57
+ export interface SwitchOutcome {
58
+ requestedModelId: string;
59
+ /** The model the device holds now: the requested one, or the default when the request was refused. */
60
+ activeModelId: string | null;
61
+ granted: boolean;
62
+ /** Why the request was refused, when it was: a registry reason, or `warmup_failed:<reason>` when it failed here. */
63
+ reason?: string;
64
+ }
65
+ /** The answer of one local call. */
66
+ export interface LocalInferenceResult {
67
+ /** The adapter's output for the model's inference kind, verbatim (same shape as a network task result). */
68
+ response: unknown;
69
+ modelId: string;
70
+ modelVersion: string;
71
+ /** Always `device` in phase 1. */
72
+ location: 'device';
73
+ /** `onnx`, `gguf` or `transformers`. */
74
+ runtime?: string;
75
+ /** Time spent behind an in-flight network task before this call ran. */
76
+ queueWaitMs: number;
77
+ processingMs: number;
78
+ }
79
+ /** Every error of the app-side API carries a short `code` the host can branch on. */
80
+ export declare class ZeroGpuError extends Error {
81
+ readonly code: string;
82
+ readonly cause?: unknown;
83
+ constructor(code: string, message: string, cause?: unknown);
84
+ }
85
+ /** The device is not contributing right now, so there is no model to run on. */
86
+ export declare class NotContributingError extends ZeroGpuError {
87
+ readonly state: ContributionState;
88
+ /** The registry's reason when `state` is `declined`. */
89
+ readonly registryReason?: string;
90
+ constructor(state: ContributionState, registryReason?: string);
91
+ }
92
+ /** The model is not on the eligible list, or is listed as not eligible. */
93
+ export declare class ModelNotEligibleError extends ZeroGpuError {
94
+ readonly modelId: string;
95
+ readonly reason: string;
96
+ constructor(modelId: string, reason: string);
97
+ }
98
+ /** The model ran and failed (the adapter threw). */
99
+ export declare class LocalInferenceFailedError extends ZeroGpuError {
100
+ constructor(message: string, cause?: unknown);
101
+ }
102
+ export declare const isZeroGpuError: (value: unknown) => value is ZeroGpuError;
103
+ /**
104
+ * Wire shape of an error crossing a message boundary (the Chrome extension's
105
+ * offscreen document answers its host over `chrome.runtime` messages).
106
+ */
107
+ export interface SerializedZeroGpuError {
108
+ code: string;
109
+ message: string;
110
+ name: string;
111
+ state?: ContributionState;
112
+ registryReason?: string;
113
+ modelId?: string;
114
+ reason?: string;
115
+ }
116
+ export declare const serializeZeroGpuError: (error: unknown) => SerializedZeroGpuError;
117
+ /** Rebuilds the typed error on the receiving side of a message boundary. */
118
+ export declare const deserializeZeroGpuError: (shape: SerializedZeroGpuError) => ZeroGpuError;
@@ -41,6 +41,7 @@ export interface GuardrailSettings {
41
41
  unknownMemoryGb?: number;
42
42
  maxMemoryBudgetMb?: number;
43
43
  maxInputTokens?: number;
44
+ maxCachedModels?: number;
44
45
  sampleLatencyBudgetMs?: number;
45
46
  wasm?: {
46
47
  maxThreads?: number;
@@ -71,8 +72,26 @@ export interface TelemetryConfig {
71
72
  cameraData?: boolean;
72
73
  events: boolean;
73
74
  }
75
+ export interface InferenceConfig {
76
+ /**
77
+ * Run model download, session creation and every inference for ONNX-backed
78
+ * models in a dedicated Worker so the host page's main thread never blocks
79
+ * (default: true). `false` forces the historical main-thread mode, e.g. for
80
+ * an environment known to lack Workers. When a Worker cannot be created or
81
+ * boot at runtime the SDK falls back to the main thread by itself and
82
+ * reports it once (`guardrail.pressure_warning` / `inference_worker_unavailable`).
83
+ */
84
+ worker: boolean;
85
+ /**
86
+ * Same-origin URL of the SDK's worker script (`dist/zerogpu-worker.js`) for
87
+ * hosts whose Content-Security-Policy forbids `blob:` workers. Absent → the
88
+ * worker source bundled into the SDK is spawned from a blob: URL.
89
+ */
90
+ workerUrl?: string;
91
+ }
74
92
  export interface SdkConfig {
75
93
  sdkVersion: string;
76
94
  orchestrator: OrchestratorConfig;
77
95
  telemetry: TelemetryConfig;
96
+ inference: InferenceConfig;
78
97
  }
@@ -7,4 +7,10 @@ import { TelemetryConfig } from '../config/types';
7
7
  * the fabricated navigator.storage.estimate() answers of embedded WebViews.
8
8
  */
9
9
  export declare const isTelegramWebAppContext: () => boolean;
10
+ /**
11
+ * The fields that change while a page lives — battery, connection — re-read
12
+ * without the prompts the full collection may raise (geolocation). The
13
+ * eligible-models call sends the registry what register would send now.
14
+ */
15
+ export declare const refreshVolatileDeviceInfo: (info: DeviceInfo) => Promise<DeviceInfo>;
10
16
  export declare const collectDeviceInfo: (config: TelemetryConfig, appUserId?: string, sdkDeviceId?: string) => Promise<DeviceInfo>;
@@ -19,6 +19,7 @@
19
19
  */
20
20
  import { ZeroGpuConsent } from './consent';
21
21
  import type { CustomParams } from '../runtime/custom-params';
22
+ import { type ContributionState, type EligibleModel, type LocalInferenceResult, type SwitchOutcome } from '../appinference/types';
22
23
  /** The three messages the bridge answers. Nothing here can start inference,
23
24
  * read device data, or reach the model store — by design. */
24
25
  export declare const ZEROGPU_BRIDGE_MESSAGES: {
@@ -62,6 +63,39 @@ export declare const stopZeroGpuOffscreen: (options?: ConsentBridgeOptions) => P
62
63
  * `customParams` to `initZeroGpuOffscreen` as well.
63
64
  */
64
65
  export declare const setZeroGpuCustomParams: (customParams: CustomParams, options?: ConsentBridgeOptions) => Promise<boolean>;
66
+ export interface ZeroGpuContribution {
67
+ contributionState: ContributionState;
68
+ activeModelId: string | null;
69
+ status: string;
70
+ /** This device's id at the registry, or null before the SDK registered. */
71
+ deviceId: string | null;
72
+ }
73
+ /** Where the SDK stands right now; `stopped` when the offscreen document is not running. */
74
+ export declare const getZeroGpuContribution: (options?: ConsentBridgeOptions) => Promise<ZeroGpuContribution>;
75
+ /** Every model of the chrome-extension list, judged for this device. */
76
+ export declare const getZeroGpuEligibleModels: (options?: ConsentBridgeOptions) => Promise<EligibleModel[]>;
77
+ /** Switch the device to `modelId`; resolves when it contributes again (download included). */
78
+ export declare const switchZeroGpuModel: (modelId: string, options?: ConsentBridgeOptions) => Promise<SwitchOutcome>;
79
+ /** Run the active model on `input` (the shape of the model's inference kind). */
80
+ export declare const runZeroGpuLocal: (input: Record<string, unknown>, options?: ConsentBridgeOptions) => Promise<LocalInferenceResult>;
81
+ export declare const clearZeroGpuModelChoice: (options?: ConsentBridgeOptions) => Promise<boolean>;
82
+ export declare const forgetZeroGpuUnfitModel: (modelId: string, options?: ConsentBridgeOptions) => Promise<boolean>;
83
+ export interface ZeroGpuEvent {
84
+ event: 'activeModelChanged' | 'modelChoiceRefused' | 'degraded' | 'recovered' | 'shutdown';
85
+ detail: {
86
+ code?: string;
87
+ message?: string;
88
+ modelId?: string;
89
+ reason?: string;
90
+ restartInMs?: number;
91
+ };
92
+ }
93
+ /**
94
+ * Follow the SDK's host events from any extension context (the offscreen
95
+ * document broadcasts them). Returns nothing to unsubscribe with: extension
96
+ * listeners live as long as their context.
97
+ */
98
+ export declare const onZeroGpuEvent: (listener: (event: ZeroGpuEvent) => void) => void;
65
99
  /** Start or stop to match the stored decision. Safe to call repeatedly. */
66
100
  export declare const applyZeroGpuConsent: (consent: ZeroGpuConsent, options?: ConsentBridgeOptions) => Promise<void>;
67
101
  /** Start only if the user is opted in — for `onInstalled` / `onStartup`. */
@@ -79,3 +113,5 @@ export declare const registerZeroGpuConsentBridge: (options?: ConsentBridgeOptio
79
113
  export { ZEROGPU_CONSENT_KEY, DEFAULT_CONSENT, getZeroGpuConsent, isZeroGpuOptedIn, setZeroGpuConsent, onZeroGpuConsentChanged, buildZeroGpuSettingsUrl, ZEROGPU_SETTINGS_BASE_URL } from './consent';
80
114
  export type { ZeroGpuConsent, ZeroGpuConsentSource } from './consent';
81
115
  export type { CustomParams } from '../runtime/custom-params';
116
+ export { LocalInferenceFailedError, ModelNotEligibleError, NotContributingError, ZeroGpuError, isZeroGpuError } from '../appinference/types';
117
+ export type { ContributionState, EligibleModel, LocalInferenceResult, SwitchOutcome, SerializedZeroGpuError } from '../appinference/types';
@@ -10,7 +10,7 @@
10
10
  * `vendor/zerogpu/`); this bundle (`dist/extension/zerogpu-offscreen.js`) is one
11
11
  * of the vendored files and already contains the SDK itself.
12
12
  */
13
- import { setCustomParams } from '../public-api';
13
+ import { getZeroGpuSdk, setCustomParams } from '../public-api';
14
14
  import { CustomParams } from '../runtime/custom-params';
15
15
  import { ConfigOverrides } from '../config/env';
16
16
  export interface OffscreenInitOptions {
@@ -41,29 +41,55 @@ export interface OffscreenInitOptions {
41
41
  trackingRunnerUrl?: string | false;
42
42
  /** Enable verbose SDK console logging (default false). */
43
43
  enableConsoleLogs?: boolean;
44
+ /**
45
+ * Run model loading and inference in the SDK's inference worker (the
46
+ * vendored `zerogpu-worker.js`) rather than on the offscreen document's own
47
+ * thread. Default true; the SDK falls back to the document's thread by
48
+ * itself if the worker cannot start. Set false to force that mode.
49
+ */
50
+ inferenceWorker?: boolean;
44
51
  /**
45
52
  * Operator macros (`cust_param1`..`cust_param3`). Values set here survive the
46
53
  * document being recreated; values sent later with
47
54
  * `zerogpu:setCustomParams` last only as long as this document.
48
55
  */
49
56
  customParams?: CustomParams;
57
+ /** This extension's ZeroGPU app ID, from the ZeroGPU dashboard. */
58
+ appId?: string;
59
+ appName?: string;
60
+ /** Defaults to the extension ID (`chrome.runtime.id`). */
61
+ externalAppId?: string;
50
62
  /** Advanced: deep config overrides merged last. */
51
63
  overrides?: ConfigOverrides;
52
64
  }
53
65
  /**
54
- * Pre-load the vendored model runtimes (so the SDK never reaches the CDN) and
55
- * initialize the ZeroGPU SDK. Safe to call more than once; the SDK ignores
66
+ * Point the SDK at the vendored model runtimes (so it never reaches the CDN)
67
+ * and initialize the ZeroGPU SDK. Safe to call more than once; the SDK ignores
56
68
  * repeated init.
57
69
  */
58
70
  export declare const initZeroGpuOffscreen: (options?: OffscreenInitOptions) => Promise<void>;
59
- export { setCustomParams };
71
+ export { setCustomParams, getZeroGpuSdk };
60
72
  export type { CustomParams };
73
+ export type { ZeroGpuSdkHandle } from '../public-api';
74
+ export type { ContributionState, EligibleModel, LocalInferenceResult, SwitchOutcome, SerializedZeroGpuError } from '../appinference/types';
61
75
  export declare const ZEROGPU_OFFSCREEN_MESSAGES: {
62
76
  readonly forceInit: "zerogpu:forceInit";
63
77
  readonly getStatus: "zerogpu:getStatus";
64
78
  readonly disable: "zerogpu:disable";
65
79
  readonly setCustomParams: "zerogpu:setCustomParams";
80
+ readonly getContribution: "zerogpu:getContribution";
81
+ readonly eligibleModels: "zerogpu:eligibleModels";
82
+ readonly switchModel: "zerogpu:switchModel";
83
+ readonly runLocal: "zerogpu:runLocal";
84
+ readonly clearModelChoice: "zerogpu:clearModelChoice";
85
+ readonly forgetUnfitModel: "zerogpu:forgetUnfitModel";
66
86
  };
87
+ /**
88
+ * Host events, broadcast to every extension context as
89
+ * `{ type: 'zerogpu:event', event, detail }` so a popup or the service worker
90
+ * can follow the SDK without polling. Best effort: no receiver is not an error.
91
+ */
92
+ export declare const ZEROGPU_EVENT_MESSAGE = "zerogpu:event";
67
93
  export interface ZeroGpuOffscreenState {
68
94
  status: 'idle' | 'initializing' | 'running' | 'error';
69
95
  initialized: boolean;
@@ -74,7 +100,10 @@ export interface ZeroGpuOffscreenState {
74
100
  orchestratorBaseUrl?: string;
75
101
  }
76
102
  /**
77
- * Wire the offscreen document to the standard popup/background debug protocol.
103
+ * Wire the offscreen document to the standard popup/background protocol
104
+ * (`initZeroGpuOffscreen` does this itself; calling it again is a no-op).
78
105
  * Returns the live state object (also queryable via zerogpu:getStatus).
79
106
  */
80
107
  export declare const registerZeroGpuOffscreenMessaging: (options?: OffscreenInitOptions) => ZeroGpuOffscreenState;
108
+ /** Test-only: forget the registered listener state (a new chrome stub gets a new listener). */
109
+ export declare const __resetOffscreenMessaging: () => void;
@@ -0,0 +1,33 @@
1
+ import { ExecutorLoader } from '../adapters/types';
2
+ import { InferenceConfig } from '../config/types';
3
+ import { WorkerLike } from './worker-client';
4
+ import { WorkerFramework } from './worker-protocol';
5
+ /**
6
+ * Execution strategy for transformers.js-backed models.
7
+ *
8
+ * Default: model download, session creation and every inference run in the
9
+ * SDK's dedicated inference worker, so the host page's main thread never
10
+ * blocks (ONNX session creation alone froze it for 1–2 s per model, and a
11
+ * seq2seq generation for hundreds of ms per request). `inference.worker:
12
+ * false` forces the historical main-thread mode. When a worker cannot be
13
+ * created, fails to boot, or dies, the SDK falls back to the main thread for
14
+ * the rest of the session and reports it once as a warning.
15
+ */
16
+ export type InferenceExecutionMode = 'worker' | 'main-thread';
17
+ export declare const setInferenceExecutionConfig: (next: Partial<InferenceConfig> | undefined) => void;
18
+ /** Where the next transformers.js-backed model will load. */
19
+ export declare const getInferenceExecutionMode: () => InferenceExecutionMode;
20
+ /** The reason main-thread mode was entered this session, if it was. */
21
+ export declare const getInferenceWorkerFallback: () => {
22
+ code: string;
23
+ message: string;
24
+ } | null;
25
+ /**
26
+ * Wraps a thread-agnostic executor loader: the worker when it is wanted and
27
+ * available, the given (main-thread) loader otherwise. A model-level failure
28
+ * in the worker surfaces as-is — the main thread would fail the same way.
29
+ */
30
+ export declare const resolveExecutorLoader: (framework: WorkerFramework, local: ExecutorLoader) => ExecutorLoader;
31
+ /** Test hooks. */
32
+ export declare const __setInferenceWorkerSpawn: (spawn: (() => WorkerLike) | null) => void;
33
+ export declare const __resetInferenceExecution: () => void;