@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,35 @@
1
+ /**
2
+ * Where the model runtimes come from.
3
+ *
4
+ * Web pages import transformers.js (and, through it, the ONNX Runtime wasm)
5
+ * from the CDN. A Chrome MV3 offscreen document may not load remote code, so
6
+ * it points everything at the files `npx zerogpu vendor` copied into the
7
+ * extension. Whatever the surface configures here is handed to the inference
8
+ * worker at boot, so both threads resolve the identical files.
9
+ */
10
+ export declare const TRANSFORMERS_CDN = "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";
11
+ export interface ModelRuntimeLocator {
12
+ /** ESM bundle of transformers.js to import. */
13
+ transformersUrl: string;
14
+ /** Directory holding the ORT wasm binaries; probed ahead of the built-in candidates when set. */
15
+ wasmPaths?: string;
16
+ /** Pin ORT to one wasm thread (offscreen documents are never cross-origin isolated). */
17
+ forceSingleThread?: boolean;
18
+ /**
19
+ * Script URL of the inference worker. Absent → the worker source inlined in
20
+ * this bundle is spawned from a blob: URL (MV3 forbids blob: workers, so the
21
+ * offscreen kit sets the vendored file here).
22
+ */
23
+ workerUrl?: string;
24
+ /**
25
+ * Origin whose `/onnx-wasm/` is probed for the wasm binaries. Defaults to the
26
+ * current global's own origin; the worker is told the page's, since a blob:
27
+ * worker cannot rely on its own location.
28
+ */
29
+ pageOrigin?: string;
30
+ }
31
+ /** Merges the given fields; `undefined` values leave the current setting alone. */
32
+ export declare const configureModelRuntime: (overrides: Partial<ModelRuntimeLocator>) => void;
33
+ export declare const getModelRuntimeLocator: () => ModelRuntimeLocator;
34
+ /** Test hook. */
35
+ export declare const __resetModelRuntimeLocator: () => void;
@@ -0,0 +1,64 @@
1
+ import { ModelExecutor } from '../adapters/types';
2
+ import { SlmConfig } from '../config/types';
3
+ import { WasmGuardrails } from '../runtime/guardrails';
4
+ import { WorkerBootConfig, WorkerFramework } from './worker-protocol';
5
+ /** A worker that has not answered its boot handshake by then is broken. */
6
+ export declare const WORKER_BOOT_TIMEOUT_MS = 20000;
7
+ /**
8
+ * A failure of the worker itself (spawn, boot, crash) — never of a model. The
9
+ * execution strategy answers these by loading on the main thread instead.
10
+ */
11
+ export declare class InferenceWorkerError extends Error {
12
+ readonly code: string;
13
+ constructor(code: string, detail?: string);
14
+ }
15
+ /** True for errors the main thread should answer by re-loading locally. */
16
+ export declare const isInferenceWorkerInfrastructureError: (error: unknown) => boolean;
17
+ export declare const inferenceWorkerErrorCode: (error: unknown) => string;
18
+ /** The slice of the Worker interface the client drives (fakeable in tests). */
19
+ export interface WorkerLike {
20
+ postMessage(message: unknown): void;
21
+ terminate(): void;
22
+ onmessage: ((event: MessageEvent) => void) | null;
23
+ onerror: ((event: ErrorEvent) => void) | null;
24
+ onmessageerror?: ((event: MessageEvent) => void) | null;
25
+ }
26
+ export interface InferenceWorkerClientOptions {
27
+ spawn: () => WorkerLike;
28
+ bootConfig: () => WorkerBootConfig;
29
+ bootTimeoutMs?: number;
30
+ /** The worker died after booting; `modelIds` had been loaded into it. */
31
+ onCrash?: (error: InferenceWorkerError, modelIds: string[]) => void;
32
+ }
33
+ /**
34
+ * Main-thread side of the inference worker: spawns it lazily, runs the boot
35
+ * handshake, correlates requests with results and relays the worker's log
36
+ * lines into this thread's logger. One client hosts any number of loaded
37
+ * models (handles); the worker is terminated when the last one is disposed.
38
+ */
39
+ export declare class InferenceWorkerClient {
40
+ private readonly options;
41
+ private worker;
42
+ private ready;
43
+ private booted;
44
+ private dead;
45
+ private nextId;
46
+ private handleSeq;
47
+ private readonly pending;
48
+ /** handle → modelId, for crash attribution. */
49
+ private readonly loaded;
50
+ constructor(options: InferenceWorkerClientOptions);
51
+ isAlive(): boolean;
52
+ loadedCount(): number;
53
+ load(framework: WorkerFramework, slm: SlmConfig, cachedFiles: Record<string, Blob>, wasm: WasmGuardrails): Promise<{
54
+ executor: ModelExecutor;
55
+ downloadedFiles: Record<string, Blob>;
56
+ }>;
57
+ /** Stops the worker; in-flight requests reject with `reason`. */
58
+ terminate(reason?: InferenceWorkerError): void;
59
+ private boot;
60
+ private request;
61
+ private dispatch;
62
+ private crash;
63
+ private rejectAll;
64
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ import { ExecutorLoader } from '../adapters/types';
2
+ import { WorkerFramework } from './worker-protocol';
3
+ /**
4
+ * Worker-side host: answers the main thread's protocol by loading executors
5
+ * through the same loaders the main thread would use, and relays this
6
+ * realm's log lines back over the channel (the page's logger is the single
7
+ * console sink). Runs inside `dist/zerogpu-worker.js` (see worker-entry.ts).
8
+ */
9
+ /** The slice of DedicatedWorkerGlobalScope the host needs (fakeable in tests). */
10
+ export interface WorkerScopeLike {
11
+ postMessage(message: unknown): void;
12
+ onmessage: ((event: MessageEvent) => void) | null;
13
+ }
14
+ export declare const startInferenceWorkerHost: (scope: WorkerScopeLike, loaders: Partial<Record<WorkerFramework, ExecutorLoader>>) => void;
@@ -0,0 +1,80 @@
1
+ import { SlmConfig } from '../config/types';
2
+ import { InferenceInput, TaskSample } from '../adapters/types';
3
+ import { WasmGuardrails } from '../runtime/guardrails';
4
+ import { LogLevel, SafeFields } from '../utils/logger';
5
+ import { ModelRuntimeLocator } from './runtime-locator';
6
+ /**
7
+ * Main thread ⇄ inference worker protocol. Every request carries an `id` the
8
+ * worker echoes in exactly one `result`. Model files travel as Blobs (handles,
9
+ * not copies) in both directions: the main thread keeps the IndexedDB cache
10
+ * and hands cached files in; the worker hands whatever it downloaded back for
11
+ * persisting.
12
+ */
13
+ export declare const INFERENCE_WORKER_PROTOCOL = 1;
14
+ /** Frameworks whose executors the worker can host (GGUF/wllama runs its own worker). */
15
+ export type WorkerFramework = 'ONNX' | 'Transformers';
16
+ export interface WorkerBootConfig {
17
+ protocol: number;
18
+ logging: {
19
+ enabled: boolean;
20
+ };
21
+ runtime: ModelRuntimeLocator;
22
+ }
23
+ export interface WorkerLoadResult {
24
+ loadModelMs: number;
25
+ downloadedFiles: Record<string, Blob>;
26
+ }
27
+ export type MainToWorkerMessage = {
28
+ type: 'init';
29
+ id: number;
30
+ config: WorkerBootConfig;
31
+ } | {
32
+ type: 'load';
33
+ id: number;
34
+ handle: string;
35
+ framework: WorkerFramework;
36
+ slm: SlmConfig;
37
+ cachedFiles: Record<string, Blob>;
38
+ wasm: WasmGuardrails;
39
+ } | {
40
+ type: 'infer';
41
+ id: number;
42
+ handle: string;
43
+ input: InferenceInput;
44
+ } | {
45
+ type: 'sample';
46
+ id: number;
47
+ handle: string;
48
+ sample: TaskSample;
49
+ } | {
50
+ type: 'dispose';
51
+ id: number;
52
+ handle: string;
53
+ };
54
+ export interface WorkerErrorShape {
55
+ name: string;
56
+ message: string;
57
+ /** Set for environment failures the main thread should fall back on. */
58
+ code?: string;
59
+ }
60
+ export type WorkerToMainMessage = {
61
+ type: 'ready';
62
+ protocol: number;
63
+ } | {
64
+ type: 'result';
65
+ id: number;
66
+ ok: true;
67
+ value: unknown;
68
+ } | {
69
+ type: 'result';
70
+ id: number;
71
+ ok: false;
72
+ error: WorkerErrorShape;
73
+ } | {
74
+ type: 'log';
75
+ level: LogLevel;
76
+ message: string;
77
+ fields?: SafeFields;
78
+ };
79
+ /** The transformers.js import failed inside the worker: retry the load on the main thread. */
80
+ export declare const WORKER_RUNTIME_UNAVAILABLE = "transformers_runtime_load_failed";
@@ -0,0 +1 @@
1
+ export declare const getInlineWorkerSource: () => string | null;
@@ -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,13 +31,19 @@ export interface ResolvedGuardrails {
25
31
  maxInputTokens: number;
26
32
  /** Warm-up latency budget in ms; 0 = success-only readiness gating. */
27
33
  sampleLatencyBudgetMs: number;
28
- wasm: {
29
- maxThreads: number;
30
- proxyWorker: boolean;
31
- };
34
+ /** Most cached models; 0 = unbounded. */
35
+ maxCachedModels: number;
36
+ wasm: WasmGuardrails;
37
+ }
38
+ /** Served `guardrails.wasm`, resolved. Handed to the inference worker per load. */
39
+ export interface WasmGuardrails {
40
+ maxThreads: number;
41
+ proxyWorker: boolean;
32
42
  }
33
43
  /** Devices that report no memory are treated as modest 2 GB devices (same as the server). */
34
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;
35
47
  /**
36
48
  * Same chars-per-token heuristic the registry's dispatch input guard uses —
37
49
  * both sides only need the order of magnitude to agree.
@@ -54,12 +66,18 @@ export declare const estimateInputTokens: (text: string) => number;
54
66
  /** True when a served cap exists and the input exceeds it (0/absent cap = no gate). */
55
67
  export declare const inputExceedsTokenCap: (text: string, capTokens?: number) => boolean;
56
68
  export interface WasmEnvironmentProbe {
57
- /** window.crossOriginIsolated && SharedArrayBuffer usable. */
69
+ /** crossOriginIsolated && SharedArrayBuffer usable (the page's status is inherited by its workers). */
58
70
  isolated: boolean;
59
71
  /** navigator.hardwareConcurrency (0/absent → treated as 1). */
60
72
  cores: number;
61
73
  /** typeof Worker === 'function'. */
62
74
  workerAvailable: boolean;
75
+ /**
76
+ * A document exists, i.e. this is the main thread. ORT's proxy is the
77
+ * main-thread→worker hop, so it means nothing inside the inference worker
78
+ * (ORT itself ignores it there). Absent → true.
79
+ */
80
+ inDocument?: boolean;
63
81
  }
64
82
  /**
65
83
  * ONNX wasm execution settings for this environment + served config:
@@ -67,10 +85,15 @@ export interface WasmEnvironmentProbe {
67
85
  * cross-origin-isolated pages (COOP/COEP on the loader). When available, use
68
86
  * min(hardwareConcurrency − 1, served maxThreads) — one core is left for the
69
87
  * page. Not isolated → 1, exactly the long-standing behavior.
70
- * - proxy: worker execution is opt-in via `guardrails.wasm.proxyWorker` (per
71
- * surface, after verifying the target WebView), and only where Worker exists.
88
+ * - proxy: ORT's own wasm proxy worker is opt-in via `guardrails.wasm
89
+ * .proxyWorker`, only where Worker exists, and only on the main thread. It
90
+ * predates the SDK's inference worker (inference/execution.ts), which is the
91
+ * default and hosts ORT entirely; the proxy still applies when a host forces
92
+ * main-thread mode.
93
+ *
94
+ * `wasm` defaults to the served block; the worker passes the one it was handed.
72
95
  */
73
- export declare const resolveWasmSettings: (probe?: WasmEnvironmentProbe) => {
96
+ export declare const resolveWasmSettings: (probe?: WasmEnvironmentProbe, wasm?: WasmGuardrails) => {
74
97
  numThreads: number;
75
98
  proxy: boolean;
76
99
  };
@@ -5,17 +5,29 @@
5
5
  * consumers get the same signals as `zerogpu:*` window events.
6
6
  */
7
7
  export type SdkLifecycleStatus = 'starting' | 'running' | 'degraded' | 'shutdown' | 'error';
8
- export type HostEventName = 'degraded' | 'recovered' | 'shutdown';
8
+ export type HostEventName = 'degraded' | 'recovered' | 'shutdown'
9
+ /** The device now holds `modelId` for the network and for local calls. */
10
+ | 'activeModelChanged'
11
+ /** The app's chosen model was not kept; the device holds the default. */
12
+ | 'modelChoiceRefused';
9
13
  export interface HostEventDetail {
10
14
  code?: string;
11
15
  message?: string;
16
+ modelId?: string;
17
+ reason?: string;
18
+ /** On a guardrail `shutdown`: the SDK restarts itself after this many ms. */
19
+ restartInMs?: number;
12
20
  }
13
21
  type HostEventListener = (detail: HostEventDetail) => void;
22
+ export declare const setGuardrailStopped: (stopped: boolean) => void;
23
+ export declare const isGuardrailStopped: () => boolean;
14
24
  export declare const getLifecycleStatus: () => SdkLifecycleStatus;
15
25
  export declare const setLifecycleStatus: (status: SdkLifecycleStatus) => void;
16
26
  export declare const isShutdown: () => boolean;
17
27
  /** Degraded and shutting-down SDKs finish in-flight work but accept nothing new. */
18
28
  export declare const isTaskGateActive: () => boolean;
29
+ /** Test-only. */
30
+ export declare const __resetHostApi: () => void;
19
31
  export declare const onHostEvent: (name: HostEventName, listener: HostEventListener) => (() => void);
20
32
  export declare const emitHostEvent: (name: HostEventName, detail?: HostEventDetail) => void;
21
33
  export {};
@@ -53,6 +53,13 @@ export declare const beginInitAttempt: (now?: number) => InitGuardDecision;
53
53
  export declare const markInitSuccess: () => void;
54
54
  /** Written before every dangerous step so an unclean death is attributable. */
55
55
  export declare const setInitPhase: (phase: InitPhase, modelId?: string, modelVersion?: string) => void;
56
+ /**
57
+ * A dangerous step ended in a handled failure (the download or load failed and
58
+ * the SDK is moving on): the marker must not survive, or the next boot would
59
+ * read it as a death mid-step, count a crash, and after two blocklist the
60
+ * model for a day (the "never reconnects after a load failure" gotcha).
61
+ */
62
+ export declare const clearInitPhase: () => void;
56
63
  /** The graceful shutdown sequence ran — the next boot must not count a crash. */
57
64
  export declare const markCleanShutdown: (code: string) => void;
58
65
  /** Blocklisted models are refused before any I/O (breaker, Layer 4). */
@@ -0,0 +1,12 @@
1
+ import { SdkConfig } from '../config/types';
2
+ /**
3
+ * What `startLifecycle` was started with. Kept apart from the lifecycle module
4
+ * so the modules that restart it later (a model switch, a guardrail restart)
5
+ * can hold the options without importing the lifecycle itself.
6
+ */
7
+ export interface LifecycleOptions {
8
+ config: SdkConfig;
9
+ appUserId?: string;
10
+ edgeOperatorKey?: string;
11
+ deviceId?: string;
12
+ }
@@ -1,10 +1,23 @@
1
- import { SdkConfig } from '../config/types';
2
1
  import { SampleTestResult } from '../adapters/types';
3
- export interface LifecycleOptions {
4
- config: SdkConfig;
5
- appUserId?: string;
6
- edgeOperatorKey?: string;
7
- deviceId?: string;
8
- }
2
+ import { LifecycleOptions } from './lifecycle-options';
3
+ export type { LifecycleOptions } from './lifecycle-options';
9
4
  export declare function warmUpFailed(sample: Pick<SampleTestResult, 'ok' | 'error' | 'processingTimeMs'>, latencyBudgetMs?: number): boolean;
10
- export declare const startLifecycle: ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }: LifecycleOptions) => Promise<void>;
5
+ /**
6
+ * The warm-up gate (design §2, rule 6) re-registers at once after a model it
7
+ * cannot run, so the registry walks on. Bounded per page: after this many in a
8
+ * row the slow refusal cadence applies, so a broken list cannot loop.
9
+ */
10
+ export declare const MAX_UNFIT_REREGISTERS = 4;
11
+ /**
12
+ * Runs the lifecycle again, keeping the loop alive on transient failures
13
+ * (register/network/model errors). Auth failures and crash-loop cool-downs
14
+ * return cleanly from startLifecycle without throwing. A pending switch
15
+ * cannot wait out a transient failure: it ends with the failure's code while
16
+ * the choice stays remembered for the retry.
17
+ */
18
+ export declare const runLifecycleNow: (options: LifecycleOptions, reason: string) => void;
19
+ /** Download and network failures pass; a model the runtime cannot load does not. */
20
+ export declare const isTransientLoadFailure: (message: string) => boolean;
21
+ export declare const startLifecycle: (options: LifecycleOptions) => Promise<void>;
22
+ /** Test-only. */
23
+ export declare const __resetLifecycleState: () => void;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The one way to run the lifecycle again from outside it. The lifecycle
3
+ * registers itself here at module load; a model switch and a guardrail
4
+ * restart ask through it, so neither module imports the lifecycle (which
5
+ * imports both of them).
6
+ */
7
+ type RestartHandler = (reason: string) => void;
8
+ export declare const setLifecycleRestartHandler: (next: RestartHandler | null) => void;
9
+ /** Runs the lifecycle again with the options it was last started with. No-op before the first start. */
10
+ export declare const requestLifecycleRestart: (reason: string) => boolean;
11
+ export {};
@@ -1,2 +1,15 @@
1
1
  import { ServerTaskBatchMessage } from '../transport/protocol';
2
+ /** True while a network task or an app call holds (or waits for) the engine. */
3
+ export declare const isEngineBusy: () => boolean;
4
+ /** Resolves once nothing holds the engine (a switch waits for the in-flight task this way). */
5
+ export declare const awaitEngineIdle: () => Promise<void>;
6
+ /** While set, network batches are answered busy: the session is being torn down for a switch. */
7
+ export declare const setSwitchingGate: (on: boolean) => void;
8
+ /** Runs an app call ahead of network work: waits only for the task in flight. */
9
+ export declare const runForApp: <T>(block: () => Promise<T>) => Promise<{
10
+ value: T;
11
+ queueWaitMs: number;
12
+ }>;
13
+ /** Test-only. */
14
+ export declare const __resetRouterState: () => void;
2
15
  export declare const handleIncomingMessage: (msg: ServerTaskBatchMessage) => Promise<void>;
@@ -3,6 +3,14 @@ import { DeviceInfo } from '../device/types';
3
3
  import { ModelAdapter, TaskSample } from '../adapters/types';
4
4
  import { ConnectionStatus } from '../transport/status';
5
5
  import { WebSocketClient } from '../transport/websocket';
6
+ import { LifecycleOptions } from './lifecycle-options';
7
+ /**
8
+ * Where the lifecycle is, for the host-facing contribution state: `idle`
9
+ * (not started / stopped), `registering` (register in flight or a retry
10
+ * pending), `declined` (the registry refused the device), `preparing`
11
+ * (download / load / warm-up), `running` (session open).
12
+ */
13
+ export type LifecyclePhase = 'idle' | 'registering' | 'declined' | 'preparing' | 'running';
6
14
  export interface AssignedModelInfo {
7
15
  modelId: string;
8
16
  modelVersion?: string;
@@ -42,6 +50,11 @@ export interface SdkState {
42
50
  status: ConnectionStatus;
43
51
  ws?: WebSocketClient;
44
52
  registrationSettings?: RegistrationSettings | null;
53
+ phase?: LifecyclePhase;
54
+ declinedReason?: string | null;
55
+ lifecycleOptions?: LifecycleOptions;
56
+ /** The registry acknowledged this session's hello: the device is listed under its model. */
57
+ sessionAcked?: boolean;
45
58
  }
46
59
  export declare const setConfig: (config: SdkConfig) => void;
47
60
  export declare const setDeviceContext: (deviceId: string, deviceInfo: DeviceInfo) => void;
@@ -54,8 +67,19 @@ export declare const setSample: (sample?: TaskSample) => void;
54
67
  export declare const setCachedModelId: (cachedModelId?: string | null) => void;
55
68
  export declare const setSessionKey: (sessionKey?: string) => void;
56
69
  export declare const setWebSocket: (ws?: WebSocketClient) => void;
70
+ export declare const setSessionAcked: (acked: boolean) => void;
71
+ export declare const isSessionAcked: () => boolean;
57
72
  export declare const getWebSocket: () => WebSocketClient | undefined;
58
73
  export declare const setRegistrationSettings: (settings?: RegistrationSettings | null) => void;
59
74
  export declare const getRegistrationSettings: () => RegistrationSettings | null;
60
75
  export declare const setStatus: (status: ConnectionStatus) => void;
61
76
  export declare const getState: () => SdkState;
77
+ /** Like getState, null before init instead of throwing. */
78
+ export declare const tryGetState: () => SdkState | null;
79
+ export declare const setPhase: (phase: LifecyclePhase, declinedReason?: string | null) => void;
80
+ export declare const getPhase: () => LifecyclePhase;
81
+ export declare const getDeclinedReason: () => string | null;
82
+ export declare const setLifecycleOptions: (options: LifecycleOptions | undefined) => void;
83
+ export declare const getLifecycleOptions: () => LifecycleOptions | undefined;
84
+ /** Test-only: forget everything (a fresh page). */
85
+ export declare const __resetSdkState: () => void;
@@ -9,14 +9,32 @@ export declare const CLOSE_GUARDRAIL = 4002;
9
9
  export declare const sendStatusUpdate: (status: "idle" | "error") => void;
10
10
  export interface ShutdownOptions {
11
11
  reason: string;
12
- /** True for guardrail-triggered shutdowns: close 4002 + guardrail.shutdown. */
12
+ /** True for guardrail-triggered shutdowns: close 4002 + guardrail.shutdown, then a scheduled restart. */
13
13
  guardrail?: boolean;
14
14
  }
15
+ /**
16
+ * How long a guardrail-stopped SDK waits before it comes back: 1 min, then
17
+ * 5, then 15, then every 30 — the ladder bounds a device that keeps failing
18
+ * without ever leaving it dead for the page's lifetime (ZGA-677: a laptop
19
+ * that woke from sleep into a RangeError stayed offline until the extension
20
+ * was reloaded; 53 of 69 production devices with a 4002 close on 2026-10-28
21
+ * never came back). A run that stays healthy for HEALTHY_RUN_RESET_MS resets
22
+ * the ladder.
23
+ */
24
+ export declare const GUARDRAIL_RESTART_DELAYS_MS: readonly number[];
25
+ export declare const HEALTHY_RUN_RESET_MS: number;
26
+ export declare const nextGuardrailRestartDelayMs: (now?: number) => number;
15
27
  /**
16
28
  * The ordered shutdown sequence (GRACEFUL_SHUTDOWN_IMPLEMENTATION.md §5):
17
29
  * mark terminal + kill the re-register loop → gate input → tell the server →
18
30
  * report + beacon-flush → free memory largest-first → mark the exit clean →
19
- * notify the host. Every step individually guarded; target ≤ 1 s. Terminal:
20
- * `startLifecycle` refuses to run again until the page restarts the SDK.
31
+ * notify the host. Every step individually guarded; target ≤ 1 s.
32
+ *
33
+ * A host stop is terminal: `startLifecycle` refuses to run again until the
34
+ * page restarts the SDK. A guardrail stop is not: the runtime is freed the
35
+ * same way (the inference worker goes with its last model), and the SDK
36
+ * registers again after the ladder's delay with a fresh one.
21
37
  */
22
38
  export declare const runShutdownSequence: ({ reason, guardrail }: ShutdownOptions) => Promise<void>;
39
+ /** Test-only. */
40
+ export declare const __resetGuardrailRestartLadder: () => void;