@zerogpu/browser-extension-sdk 0.4.0 → 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 (46) hide show
  1. package/README.md +75 -0
  2. package/bin/zerogpu.mjs +6 -0
  3. package/dist/assets/zerogpu-assets.json +2 -2
  4. package/dist/assets/zerogpu-worker.js +1 -1
  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 +5 -5
  9. package/dist/types/adapters/kinds.d.ts +8 -0
  10. package/dist/types/adapters/onnx/executor.d.ts +26 -1
  11. package/dist/types/adapters/onnx/runtime.d.ts +10 -4
  12. package/dist/types/adapters/types.d.ts +15 -1
  13. package/dist/types/appinference/eligible.d.ts +12 -0
  14. package/dist/types/appinference/store.d.ts +42 -0
  15. package/dist/types/appinference/types.d.ts +118 -0
  16. package/dist/types/config/types.d.ts +1 -0
  17. package/dist/types/device/telemetry.d.ts +6 -0
  18. package/dist/types/extension/background.d.ts +36 -0
  19. package/dist/types/extension/offscreen.d.ts +25 -3
  20. package/dist/types/loader.d.ts +1 -0
  21. package/dist/types/public-api.d.ts +41 -7
  22. package/dist/types/runtime/app-identity.d.ts +24 -0
  23. package/dist/types/runtime/app-inference.d.ts +60 -0
  24. package/dist/types/runtime/guardrails.d.ts +10 -0
  25. package/dist/types/runtime/host-api.d.ts +13 -1
  26. package/dist/types/runtime/init-guard.d.ts +7 -0
  27. package/dist/types/runtime/lifecycle-options.d.ts +12 -0
  28. package/dist/types/runtime/lifecycle.d.ts +21 -8
  29. package/dist/types/runtime/restart.d.ts +11 -0
  30. package/dist/types/runtime/router.d.ts +13 -0
  31. package/dist/types/runtime/sdk-state.d.ts +24 -0
  32. package/dist/types/runtime/shutdown.d.ts +21 -3
  33. package/dist/types/storage/cached-model.d.ts +31 -2
  34. package/dist/types/telemetry/event-reporter.d.ts +1 -0
  35. package/dist/types/transport/http.d.ts +67 -0
  36. package/dist/v/zerogpu-browser-sdk.5f140942519b.umd.js +1 -0
  37. package/dist/zerogpu-browser-sdk.cjs +1 -1
  38. package/dist/zerogpu-browser-sdk.esm.js +1 -1
  39. package/dist/zerogpu-browser-sdk.umd.js +1 -1
  40. package/dist/zerogpu-worker.js +1 -1
  41. package/docs/APP_INFERENCE_E2E_2026-11-06_DEV.md +855 -0
  42. package/docs/app-side-inference.md +537 -0
  43. package/docs/extension-developer-guide.md +31 -0
  44. package/docs/multi-model-support.md +5 -1
  45. package/package.json +2 -1
  46. package/dist/v/zerogpu-browser-sdk.87efe0d8c5ba.umd.js +0 -1
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.4.0+e28b948",
2
+ "version": "0.5.0+36fc495",
3
3
  "channel": "official",
4
- "buildId": "87efe0d8c5ba",
5
- "coreBundleUrl": "v/zerogpu-browser-sdk.87efe0d8c5ba.umd.js",
6
- "integrity": "sha384-v3mksHAoiLfZompmjvXQvRKPbDHorRoRWLyunS9zTGYjcLbxsCVHKOXB3yFZvI2c",
7
- "builtAt": "2026-09-25T16:45:31.348Z"
4
+ "buildId": "5f140942519b",
5
+ "coreBundleUrl": "v/zerogpu-browser-sdk.5f140942519b.umd.js",
6
+ "integrity": "sha384-UzvQA0Lm14Fa7MiwmMv3MOKo7W23nhtJI/t4ERmFCacqXzjeQ7OYOod6XuCYM45G",
7
+ "builtAt": "2026-11-10T14:39:58.034Z"
8
8
  }
@@ -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. */
@@ -6,11 +6,36 @@ import { INFERENCE_KINDS } from '../kinds';
6
6
  * the taskType; without one (or with a kind this adapter does not implement)
7
7
  * the historical taskType mapping applies — `'task'`.
8
8
  */
9
- export type OnnxRunner = typeof INFERENCE_KINDS.SEQUENCE_CLASSIFICATION | typeof INFERENCE_KINDS.SEQ2SEQ_GENERATION | typeof INFERENCE_KINDS.ZERO_SHOT_CLASSIFICATION | 'task';
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
10
  export declare const resolveOnnxRunner: (config: Pick<SlmConfig, "inferenceKind">) => OnnxRunner;
11
11
  /** transformers.js pipeline task a pipeline-backed runner loads. */
12
12
  export declare const resolvePipelineTask: (config: Pick<SlmConfig, "inferenceKind" | "taskType">) => string;
13
13
  /** seq2seq default when generation_config.json declares no max_new_tokens. */
14
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
+ };
15
40
  /** Loads an ONNX model on the calling thread and returns its runner. */
16
41
  export declare const createOnnxExecutor: ExecutorLoader;
@@ -79,12 +79,18 @@ export declare const transformersGlobals: () => TransformersGlobals;
79
79
  export declare const pickTransformersLib: (mod: unknown) => TransformersLib | undefined;
80
80
  export declare const requireTransformersLib: () => TransformersLib;
81
81
  /**
82
- * transformers.js 2.x throws "Browser cache is not available in this
83
- * environment" when `caches` is undefined (non-secure contexts, some WebViews),
84
- * turning a missing optional cache into a load failure. Turn its Cache API
85
- * 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).
86
90
  */
87
91
  export declare const disableBrowserCacheIfUnavailable: (env: TransformersEnv | undefined) => void;
92
+ /** Cache names transformers.js used for its own copies before 0.5.0. */
93
+ export declare const LEGACY_TRANSFORMERS_CACHE_NAME = "transformers-cache";
88
94
  /**
89
95
  * Imports transformers.js from wherever the runtime locator points (CDN by
90
96
  * default, the vendored copy under MV3) and publishes its exports on this
@@ -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;
@@ -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;
@@ -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 {
@@ -54,6 +54,11 @@ export interface OffscreenInitOptions {
54
54
  * `zerogpu:setCustomParams` last only as long as this document.
55
55
  */
56
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;
57
62
  /** Advanced: deep config overrides merged last. */
58
63
  overrides?: ConfigOverrides;
59
64
  }
@@ -63,14 +68,28 @@ export interface OffscreenInitOptions {
63
68
  * repeated init.
64
69
  */
65
70
  export declare const initZeroGpuOffscreen: (options?: OffscreenInitOptions) => Promise<void>;
66
- export { setCustomParams };
71
+ export { setCustomParams, getZeroGpuSdk };
67
72
  export type { CustomParams };
73
+ export type { ZeroGpuSdkHandle } from '../public-api';
74
+ export type { ContributionState, EligibleModel, LocalInferenceResult, SwitchOutcome, SerializedZeroGpuError } from '../appinference/types';
68
75
  export declare const ZEROGPU_OFFSCREEN_MESSAGES: {
69
76
  readonly forceInit: "zerogpu:forceInit";
70
77
  readonly getStatus: "zerogpu:getStatus";
71
78
  readonly disable: "zerogpu:disable";
72
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";
73
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";
74
93
  export interface ZeroGpuOffscreenState {
75
94
  status: 'idle' | 'initializing' | 'running' | 'error';
76
95
  initialized: boolean;
@@ -81,7 +100,10 @@ export interface ZeroGpuOffscreenState {
81
100
  orchestratorBaseUrl?: string;
82
101
  }
83
102
  /**
84
- * 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).
85
105
  * Returns the live state object (also queryable via zerogpu:getStatus).
86
106
  */
87
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;
@@ -21,6 +21,7 @@
21
21
  */
22
22
  type LoaderApiMethod = (...args: unknown[]) => unknown;
23
23
  interface ZeroGpuGlobal {
24
+ getZeroGpuSdk?: LoaderApiMethod;
24
25
  ready?: Promise<void>;
25
26
  initZeroGpuSdk?: LoaderApiMethod;
26
27
  [method: string]: LoaderApiMethod | Promise<void> | undefined;
@@ -1,9 +1,12 @@
1
1
  import { ConfigOverrides } from './config/env';
2
- import { HostEventName, SdkLifecycleStatus } from './runtime/host-api';
2
+ import { HostEventDetail, HostEventName, SdkLifecycleStatus } from './runtime/host-api';
3
3
  import { ResourcePolicy } from './runtime/guardrails';
4
4
  import { CustomParams } from './runtime/custom-params';
5
+ import { InferenceInput } from './adapters/types';
6
+ import { ContributionState, EligibleModel, LocalInferenceResult, SwitchOutcome } from './appinference/types';
7
+ import { AppIdentity } from './runtime/app-identity';
5
8
  import './adapters';
6
- export interface InitOptions {
9
+ export interface InitOptions extends AppIdentity {
7
10
  overrides?: ConfigOverrides;
8
11
  appUserId?: string;
9
12
  edgeOperatorKey?: string;
@@ -27,17 +30,42 @@ export interface InitOptions {
27
30
  /**
28
31
  * Host-facing handle. `status` reflects the guardrail lifecycle
29
32
  * (starting → running ⇄ degraded → shutdown, or error); `on` subscribes to
30
- * `degraded` / `recovered` / `shutdown`; `shutdown()` runs the ordered
33
+ * `degraded` / `recovered` / `shutdown` and, since 0.5.0, to
34
+ * `activeModelChanged` / `modelChoiceRefused`; `shutdown()` runs the ordered
31
35
  * graceful shutdown (terminal until the page restarts the SDK).
36
+ *
37
+ * App-side inference (0.5.0): the model this device holds for the ZeroGPU
38
+ * network can also serve the host page, and the page may choose which
39
+ * eligible model that is. `eligibleModels`, `switchModel` and `runLocal`
40
+ * work only while `contributionState` is `contributing`.
32
41
  */
33
42
  export interface ZeroGpuSdkHandle {
34
43
  readonly status: SdkLifecycleStatus;
35
- on(event: HostEventName, listener: (detail: {
36
- code?: string;
37
- message?: string;
38
- }) => void): () => void;
44
+ on(event: HostEventName, listener: (detail: HostEventDetail) => void): () => void;
39
45
  shutdown(): Promise<void>;
46
+ /** Where the device stands; local calls run only in `contributing`. */
47
+ readonly contributionState: ContributionState;
48
+ /** The model the device holds right now, or null. */
49
+ readonly activeModelId: string | null;
50
+ /** This device's id at the registry (what support and the dashboards show), or null before init. */
51
+ readonly deviceId: string | null;
52
+ /** Every model of this surface's list, judged for this device. Never downloads. */
53
+ eligibleModels(): Promise<EligibleModel[]>;
54
+ /** Re-register asking for the model; download, warm up, reconnect. Remembered across page loads. */
55
+ switchModel(modelId: string): Promise<SwitchOutcome>;
56
+ /** Run the active model, ahead of network tasks. */
57
+ runLocal(input: InferenceInput): Promise<LocalInferenceResult>;
58
+ /** Back to the default assignment on the next register. */
59
+ clearModelChoice(): void;
60
+ /** Let a model that failed its warm-up here be tried again. */
61
+ forgetUnfitModel(modelId: string): void;
40
62
  }
63
+ /**
64
+ * The handle without holding the one `initZeroGpuSdk` returned — for pages
65
+ * that let the script tag start the SDK (`data-edge-operator-key`). Before
66
+ * `initZeroGpuSdk` ran, the app-side calls answer `not_contributing_stopped`.
67
+ */
68
+ export declare const getZeroGpuSdk: () => ZeroGpuSdkHandle;
41
69
  /**
42
70
  * Never rejects: the SDK is a guest in someone else's app, and a failed init
43
71
  * must degrade to "SDK not running" — observable via `handle.status` and the
@@ -53,3 +81,9 @@ export declare const initZeroGpuSdk: (options?: InitOptions) => Promise<ZeroGpuS
53
81
  */
54
82
  export declare const setCustomParams: (params: CustomParams) => void;
55
83
  export type { CustomParams, CustParamSlot } from './runtime/custom-params';
84
+ export type { HostEventName, HostEventDetail, SdkLifecycleStatus } from './runtime/host-api';
85
+ export type { ResourcePolicy } from './runtime/guardrails';
86
+ export type { InferenceInput } from './adapters/types';
87
+ export type { ContributionState, EligibleModel, LocalInferenceResult, SwitchOutcome, SerializedZeroGpuError } from './appinference/types';
88
+ export { CONTRIBUTION_STATES, LocalInferenceFailedError, ModelNotEligibleError, NotContributingError, ZeroGpuError, isZeroGpuError } from './appinference/types';
89
+ export type { AppIdentity } from './runtime/app-identity';
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The host application's ZeroGPU identity, sent at register so the inference
3
+ * this device serves is attributed to the app. Optional throughout: an unset
4
+ * value is simply left off the register body.
5
+ */
6
+ export interface AppIdentity {
7
+ /** The app's ZeroGPU app ID, from the ZeroGPU dashboard. */
8
+ appId?: string;
9
+ appName?: string;
10
+ /**
11
+ * The app's native platform ID. Defaults to the extension ID inside a
12
+ * Chrome extension; elsewhere (e.g. a Telegram Mini App's bot username) the
13
+ * host supplies it.
14
+ */
15
+ externalAppId?: string;
16
+ }
17
+ export interface RegisterAppIdentity {
18
+ app_id?: string;
19
+ app_name?: string;
20
+ external_app_id?: string;
21
+ }
22
+ export declare const setAppIdentity: (next: AppIdentity | undefined) => void;
23
+ /** The flat register-body fields; the registry validates them and stores null for anything missing. */
24
+ export declare const getRegisterAppIdentity: () => RegisterAppIdentity;
@@ -0,0 +1,60 @@
1
+ import { InferenceInput } from '../adapters/types';
2
+ import { ContributionState, EligibleModel, LocalInferenceResult, SwitchOutcome } from '../appinference/types';
3
+ /** The model the device holds right now (loaded for the network and for local calls), or null. */
4
+ export declare const getActiveModelId: () => string | null;
5
+ /** Where the device stands; local calls run only in `contributing`. */
6
+ export declare const getContributionState: () => ContributionState;
7
+ /**
8
+ * Which models this device is eligible for (design §2.2): every model of the
9
+ * sdk type's list, judged by the registry with the same rules it applies at
10
+ * register time, plus what only the device knows — downloaded, active. A
11
+ * snapshot: battery and connection change, so ask again before showing it,
12
+ * and the registry stays the authority at switch time. Never downloads.
13
+ */
14
+ export declare const eligibleModels: () => Promise<EligibleModel[]>;
15
+ /**
16
+ * Switches the device to `modelId` (design §2.3): checked against the latest
17
+ * eligible list, then the current flow shuts down (the in-flight network task
18
+ * finishes, the session closes normally, the model unloads), the device
19
+ * registers again asking for the model, downloads it if it is not cached,
20
+ * warms it up, and reconnects. The choice is remembered across page loads
21
+ * until the next switch, `clearModelChoice`, or a refusal.
22
+ *
23
+ * Resolves once the device is contributing again: `granted` with the model
24
+ * active, or not granted with the default model active and the reason.
25
+ * Throws `ModelNotEligibleError` when the identifier is not on the list or not
26
+ * eligible (nothing changes), and `NotContributingError` when the device
27
+ * cannot contribute now.
28
+ */
29
+ export declare const switchModel: (modelId: string) => Promise<SwitchOutcome>;
30
+ /** Forgets the app's chosen model; the next register takes the default assignment. */
31
+ export declare const clearModelChoice: () => void;
32
+ /**
33
+ * Forgets this device's "failed warm-up" mark on `modelId` so it can be tried
34
+ * again. A mark also clears itself for a new catalog version of the model and
35
+ * for a new SDK version.
36
+ */
37
+ export declare const forgetUnfitModel: (modelId: string) => void;
38
+ /**
39
+ * Runs `input` on the active model (design §2.4). No model parameter, no
40
+ * fleet rules: the input bag is what the model's inference kind takes (the
41
+ * same shape as a network task), it may use as much as the model's own catalog
42
+ * cap accepts, and the call runs until the model is done. It goes to the front
43
+ * of the queue: an in-flight network task finishes first, network tasks
44
+ * arriving meanwhile are answered busy, and this runs next.
45
+ *
46
+ * Throws `NotContributingError` outside `contributing`, `ZeroGpuError`
47
+ * (`input_too_large`) when the text exceeds the model's catalog cap, and
48
+ * `LocalInferenceFailedError` when the model fails on the input.
49
+ */
50
+ export declare const runLocal: (input: InferenceInput) => Promise<LocalInferenceResult>;
51
+ /** A chosen model the registry refused, or that failed here: clear the choice, tell the app. */
52
+ export declare const noteChoiceRefused: (modelId: string, reason: string) => void;
53
+ /** The device contributes again: the pending switch ends (granted, or the default with the reason). */
54
+ export declare const completePendingSwitch: (activeModelId: string | null) => void;
55
+ export declare const failPendingSwitch: (error: Error) => void;
56
+ export declare const isSwitchPending: () => boolean;
57
+ /** After the first register and after every switch; not repeated on reconnects that keep the model. */
58
+ export declare const announceActiveModel: (modelId: string) => void;
59
+ /** Test hook. */
60
+ export declare const __resetAppInference: () => void;
@@ -9,6 +9,12 @@ import { RegistrationSettings, WatchdogSettings } from '../config/types';
9
9
  export interface ResourcePolicy {
10
10
  maxModelBytes?: number;
11
11
  memoryBudgetFraction?: number;
12
+ /**
13
+ * Most models kept in the download cache (least recently used evicted first,
14
+ * the active one never). Overrides the served `guardrails.maxCachedModels`
15
+ * (default 3). Zero disables the cap.
16
+ */
17
+ maxCachedModels?: number;
12
18
  /** Lab use only; logged loudly. Turns off preflight + watchdog entirely. */
13
19
  disableGuardrails?: boolean;
14
20
  }
@@ -25,6 +31,8 @@ export interface ResolvedGuardrails {
25
31
  maxInputTokens: number;
26
32
  /** Warm-up latency budget in ms; 0 = success-only readiness gating. */
27
33
  sampleLatencyBudgetMs: number;
34
+ /** Most cached models; 0 = unbounded. */
35
+ maxCachedModels: number;
28
36
  wasm: WasmGuardrails;
29
37
  }
30
38
  /** Served `guardrails.wasm`, resolved. Handed to the inference worker per load. */
@@ -34,6 +42,8 @@ export interface WasmGuardrails {
34
42
  }
35
43
  /** Devices that report no memory are treated as modest 2 GB devices (same as the server). */
36
44
  export declare const UNKNOWN_DEVICE_MEMORY_GB = 2;
45
+ /** Models kept in the download cache when neither the host nor the registry says. */
46
+ export declare const DEFAULT_MAX_CACHED_MODELS = 3;
37
47
  /**
38
48
  * Same chars-per-token heuristic the registry's dispatch input guard uses —
39
49
  * both sides only need the order of magnitude to agree.