@zerogpu/browser-extension-sdk 0.5.1 → 0.6.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 (55) hide show
  1. package/README.md +99 -41
  2. package/bin/browser-extension-sdk.mjs +23 -0
  3. package/bin/cli.mjs +781 -0
  4. package/bin/herogpu.mjs +6 -0
  5. package/bin/zerogpu.mjs +6 -585
  6. package/dist/assets/herogpu-assets.json +21 -0
  7. package/dist/assets/herogpu-worker.js +1 -0
  8. package/dist/assets/zerogpu-assets.json +2 -2
  9. package/dist/assets/zerogpu-worker.js +1 -1
  10. package/dist/extension/herogpu-background.js +1 -0
  11. package/dist/extension/herogpu-offscreen.js +1 -0
  12. package/dist/extension/herogpu-settings-link.js +1 -0
  13. package/dist/extension/zerogpu-background.js +1 -1
  14. package/dist/extension/zerogpu-offscreen.js +1 -1
  15. package/dist/extension/zerogpu-settings-link.js +1 -1
  16. package/dist/herogpu-browser-sdk.cjs +1 -0
  17. package/dist/herogpu-browser-sdk.esm.js +1 -0
  18. package/dist/herogpu-browser-sdk.umd.js +1 -0
  19. package/dist/herogpu-worker.js +1 -0
  20. package/dist/loader.js +1 -1
  21. package/dist/manifest.json +5 -5
  22. package/dist/types/appinference/store.d.ts +6 -2
  23. package/dist/types/appinference/types.d.ts +29 -10
  24. package/dist/types/branding.d.ts +27 -0
  25. package/dist/types/config/types.d.ts +1 -1
  26. package/dist/types/extension/background.d.ts +68 -19
  27. package/dist/types/extension/consent.d.ts +61 -10
  28. package/dist/types/extension/offscreen.d.ts +64 -23
  29. package/dist/types/extension/settings-link.d.ts +12 -1
  30. package/dist/types/inference/runtime-locator.d.ts +1 -1
  31. package/dist/types/inference/worker-host.d.ts +1 -1
  32. package/dist/types/loader.d.ts +15 -3
  33. package/dist/types/public-api.d.ts +16 -10
  34. package/dist/types/runtime/app-identity.d.ts +2 -2
  35. package/dist/types/runtime/app-inference.d.ts +1 -1
  36. package/dist/types/runtime/custom-params.d.ts +1 -1
  37. package/dist/types/runtime/host-api.d.ts +2 -1
  38. package/dist/types/runtime/init-guard.d.ts +2 -1
  39. package/dist/types/runtime/tracking-script.d.ts +1 -1
  40. package/dist/types/storage/adopted-key.d.ts +23 -0
  41. package/dist/types/storage/cached-model.d.ts +4 -1
  42. package/dist/types/storage/model-store.d.ts +6 -0
  43. package/dist/types/transport/protocol.d.ts +1 -1
  44. package/dist/v/herogpu-browser-sdk.a957716b164a.umd.js +1 -0
  45. package/dist/v/zerogpu-browser-sdk.a957716b164a.umd.js +1 -0
  46. package/dist/zerogpu-browser-sdk.cjs +1 -1
  47. package/dist/zerogpu-browser-sdk.esm.js +1 -1
  48. package/dist/zerogpu-browser-sdk.umd.js +1 -1
  49. package/dist/zerogpu-worker.js +1 -1
  50. package/docs/app-side-inference.md +55 -45
  51. package/docs/auto-update-loader.md +33 -19
  52. package/docs/extension-developer-guide.md +158 -75
  53. package/docs/multi-model-support.md +14 -14
  54. package/package.json +13 -10
  55. package/dist/v/zerogpu-browser-sdk.686affbdf19f.umd.js +0 -1
package/bin/cli.mjs ADDED
@@ -0,0 +1,781 @@
1
+ /**
2
+ * herogpu — CLI for integrating the herogpu SDK into a Chrome (MV3) extension.
3
+ *
4
+ * npx herogpu vendor [outDir] Copy the SDK + model runtimes into the extension
5
+ * (default: vendor/herogpu), and add the opt-out
6
+ * origins to manifest.json if they are missing.
7
+ * Run this in your build.
8
+ * npx herogpu init [--dir .] Vendor + scaffold offscreen/background glue and
9
+ * patch manifest.json. For a brand-new extension.
10
+ * npx herogpu doctor [--dir .] Check manifest + that vendored assets are in sync.
11
+ *
12
+ * MV3 forbids remotely-hosted code, so everything must live inside the extension
13
+ * package; `vendor` is the one step that puts the runtime files in place.
14
+ *
15
+ * Two commands, one implementation. The package installs this CLI as `herogpu`
16
+ * and, as up to 0.5.1, as `zerogpu` (bin/herogpu.mjs and bin/zerogpu.mjs, which
17
+ * only say which name was typed). The name matters in exactly one place: which
18
+ * vendored layout a command writes when the extension has none yet.
19
+ *
20
+ * vendor/herogpu/herogpu-*.js what `herogpu` writes
21
+ * vendor/zerogpu/zerogpu-*.js what 0.5.1 wrote, and what `zerogpu` still writes
22
+ *
23
+ * An extension that already has one of the two keeps it, whichever command
24
+ * runs: its files are updated in place under the names its own code imports.
25
+ * See `resolveLayouts`.
26
+ */
27
+ import {
28
+ cpSync,
29
+ existsSync,
30
+ mkdirSync,
31
+ readFileSync,
32
+ readdirSync,
33
+ statSync,
34
+ writeFileSync
35
+ } from 'node:fs';
36
+ import path from 'node:path';
37
+ import { fileURLToPath } from 'node:url';
38
+
39
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
40
+ const pkgRoot = path.resolve(__dirname, '..');
41
+ const distDir = path.join(pkgRoot, 'dist');
42
+ const distAssets = path.join(distDir, 'assets');
43
+ const distExtension = path.join(distDir, 'extension');
44
+
45
+ // The package is published under two names with the same contents; messages
46
+ // that name it read the name it was actually installed as.
47
+ const pkgName = (() => {
48
+ try {
49
+ return JSON.parse(readFileSync(path.join(pkgRoot, 'package.json'), 'utf8')).name || 'the SDK package';
50
+ } catch {
51
+ return 'the SDK package';
52
+ }
53
+ })();
54
+
55
+ /**
56
+ * The two vendored layouts. `name` is the folder under vendor/ and the file
57
+ * prefix; `api` is how the scaffolded glue spells the SDK's names, so an
58
+ * extension on the 0.5.1 layout gets glue that reads like the code it has.
59
+ */
60
+ const LAYOUTS = {
61
+ herogpu: { name: 'herogpu', api: 'HeroGpu' },
62
+ zerogpu: { name: 'zerogpu', api: 'ZeroGpu' }
63
+ };
64
+ const layoutDir = (layout) => path.join('vendor', layout.name);
65
+
66
+ // The files that carry the brand in their name. dist/ holds each under its
67
+ // herogpu name; a layout's copy is named with the layout's own prefix.
68
+ // (The inference worker must be a real file: MV3 refuses blob: workers.)
69
+ const BRANDED_FILES = [
70
+ { from: path.join(distExtension, 'herogpu-offscreen.js'), as: 'offscreen.js' },
71
+ { from: path.join(distExtension, 'herogpu-background.js'), as: 'background.js' },
72
+ { from: path.join(distExtension, 'herogpu-settings-link.js'), as: 'settings-link.js' },
73
+ { from: path.join(distAssets, 'herogpu-worker.js'), as: 'worker.js' }
74
+ ];
75
+ const assetsManifestName = (layout) => `${layout.name}-assets.json`;
76
+ const isBrandedName = (name) => /^(herogpu|zerogpu)-/.test(name);
77
+
78
+ const HOST_PERMISSIONS = ['<all_urls>'];
79
+ const REQUIRED_CSP = "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'";
80
+
81
+ // Sites allowed to reach the extension via chrome.runtime.sendMessage, i.e.
82
+ // the hosted end-user settings page where a user can turn sharing off: served
83
+ // from zerogpu.ai today, and from herogpu.com once it moves. Both are written,
84
+ // so an extension built now keeps its opt-out link working after the move.
85
+ // Must stay in step with DEFAULT_ALLOWED_ORIGINS in src/extension/background.ts.
86
+ const EXTERNALLY_CONNECTABLE_MATCHES = ['https://*.herogpu.com/*', 'https://*.zerogpu.ai/*'];
87
+ const SDK_DOMAINS = ['herogpu.com', 'zerogpu.ai'];
88
+ const mentionsSdkDomain = (value) => SDK_DOMAINS.some((domain) => String(value).includes(domain));
89
+
90
+ // Where the hosted settings page is served today (HEROGPU_SETTINGS_BASE_URL in
91
+ // src/extension/consent.ts is the value the SDK uses; this one is only printed).
92
+ const SETTINGS_PAGE_URL = 'https://zerogpu.ai/extension-settings';
93
+
94
+ // Set by runCli: 'herogpu' or 'zerogpu', the command name that was typed.
95
+ let invokedAs = 'herogpu';
96
+
97
+ const c = {
98
+ ok: (s) => `\x1b[32m${s}\x1b[0m`,
99
+ warn: (s) => `\x1b[33m${s}\x1b[0m`,
100
+ err: (s) => `\x1b[31m${s}\x1b[0m`,
101
+ dim: (s) => `\x1b[2m${s}\x1b[0m`
102
+ };
103
+
104
+ const log = (...a) => console.log(...a);
105
+ const die = (msg) => {
106
+ console.error(c.err(`✗ ${msg}`));
107
+ process.exit(1);
108
+ };
109
+
110
+ const parseFlags = (argv) => {
111
+ const flags = {};
112
+ const positional = [];
113
+ for (let i = 0; i < argv.length; i += 1) {
114
+ const arg = argv[i];
115
+ if (arg.startsWith('--')) {
116
+ const key = arg.slice(2);
117
+ const next = argv[i + 1];
118
+ if (next && !next.startsWith('--')) {
119
+ flags[key] = next;
120
+ i += 1;
121
+ } else {
122
+ flags[key] = true;
123
+ }
124
+ } else {
125
+ positional.push(arg);
126
+ }
127
+ }
128
+ return { flags, positional };
129
+ };
130
+
131
+ const ensureDistPresent = () => {
132
+ if (!existsSync(distAssets) || BRANDED_FILES.some((file) => !existsSync(file.from))) {
133
+ die(`Built SDK assets not found. Reinstall ${pkgName} (its dist/ ships the runtime).`);
134
+ }
135
+ };
136
+
137
+ // --- which layout --------------------------------------------------------------
138
+
139
+ /** Source and markup files at the top of the extension: where the vendored files get imported. */
140
+ const SOURCE_FILE = /\.(m?js|cjs|ts|html?)$/i;
141
+ const MAX_SCANNED_BYTES = 2 * 1024 * 1024;
142
+
143
+ /**
144
+ * The layouts the extension's own code refers to, read from its top-level
145
+ * scripts and pages (plus the service worker the manifest names). This is what
146
+ * identifies an existing integration in a clean checkout, where vendor/ is a
147
+ * build output and does not exist yet: `import "./vendor/zerogpu/zerogpu-offscreen.js"`
148
+ * says which files the build has to produce.
149
+ */
150
+ const referencedLayouts = (root) => {
151
+ const files = new Set();
152
+ try {
153
+ for (const entry of readdirSync(root)) {
154
+ if (SOURCE_FILE.test(entry)) files.add(path.join(root, entry));
155
+ }
156
+ } catch {
157
+ return [];
158
+ }
159
+ try {
160
+ const manifest = JSON.parse(readFileSync(path.join(root, 'manifest.json'), 'utf8'));
161
+ const worker = manifest?.background?.service_worker;
162
+ if (typeof worker === 'string') files.add(path.join(root, worker));
163
+ } catch {
164
+ // no manifest, or not JSON: the top-level files are all there is to read
165
+ }
166
+
167
+ const found = new Set();
168
+ for (const file of files) {
169
+ let text;
170
+ try {
171
+ if (!statSync(file).isFile() || statSync(file).size > MAX_SCANNED_BYTES) continue;
172
+ text = readFileSync(file, 'utf8');
173
+ } catch {
174
+ continue;
175
+ }
176
+ for (const layout of Object.values(LAYOUTS)) {
177
+ const pattern = new RegExp(`vendor[\\\\/]${layout.name}[\\\\/]|\\b${layout.name}-(offscreen|background|settings-link)\\.js`);
178
+ if (pattern.test(text)) found.add(layout.name);
179
+ }
180
+ }
181
+ return Object.values(LAYOUTS).filter((layout) => found.has(layout.name));
182
+ };
183
+
184
+ /**
185
+ * Which layout(s) to write into `root`. "Adopt what exists":
186
+ *
187
+ * 1. A vendor/herogpu or vendor/zerogpu folder that is already there is
188
+ * refreshed in place (both, if both are there).
189
+ * 2. So is the layout the extension's own code imports from (see
190
+ * `referencedLayouts`), also when its folder is not there yet: an
191
+ * extension whose imports were moved to vendor/herogpu while the old
192
+ * vendor/zerogpu folder is still in the checkout gets the files it loads.
193
+ * 3. Otherwise the extension has no integration yet, and the command's own
194
+ * name decides: `herogpu` writes vendor/herogpu, `zerogpu` writes
195
+ * vendor/zerogpu exactly as 0.5.1 did, so a build script or a guide written
196
+ * for that release produces the files it expects.
197
+ */
198
+ const resolveLayouts = (root) => {
199
+ const present = Object.values(LAYOUTS).filter((layout) => existsSync(path.join(root, layoutDir(layout))));
200
+ const referenced = referencedLayouts(root);
201
+ const wanted = Object.values(LAYOUTS).filter((layout) => present.includes(layout) || referenced.includes(layout));
202
+ if (wanted.length > 0) return wanted;
203
+ return [LAYOUTS[invokedAs]];
204
+ };
205
+
206
+ /**
207
+ * File naming for `vendor <outDir>`, where the folder is given: the names
208
+ * already in it, else what the folder is called, else what the extension's
209
+ * code imports, else the command's own name.
210
+ */
211
+ const resolveNamingForDir = (target, root) => {
212
+ const present = Object.values(LAYOUTS).filter(
213
+ (layout) =>
214
+ existsSync(path.join(target, assetsManifestName(layout))) ||
215
+ existsSync(path.join(target, `${layout.name}-offscreen.js`))
216
+ );
217
+ if (present.length > 0) return present;
218
+ const byFolderName = LAYOUTS[path.basename(target)];
219
+ if (byFolderName) return [byFolderName];
220
+ const referenced = referencedLayouts(root);
221
+ if (referenced.length > 0) return referenced;
222
+ return [LAYOUTS[invokedAs]];
223
+ };
224
+
225
+ // --- manifest helpers (shared by vendor + init) -------------------------------
226
+
227
+ const uniqueMerge = (existing, additions) => {
228
+ const out = Array.isArray(existing) ? [...existing] : [];
229
+ for (const item of additions) {
230
+ if (!out.includes(item)) out.push(item);
231
+ }
232
+ return out;
233
+ };
234
+
235
+ /**
236
+ * Merge the settings-page origins into `externally_connectable.matches`.
237
+ * Merged, never replaced — a host may already allow its own site, and its `ids`
238
+ * entry is left alone. Returns whether anything actually changed, so a caller
239
+ * that runs on every build can leave a correct manifest untouched.
240
+ *
241
+ * Creating the key is not a neutral act. Chrome reads an absent
242
+ * `externally_connectable` as "every extension may connect, no web page may";
243
+ * once the key exists, an unspecified `ids` means "no extension may". So adding
244
+ * only `matches` to a manifest that had no key would quietly revoke
245
+ * extension-to-extension messaging the host still has today. `ids: ["*"]`
246
+ * records what was already in force rather than granting anything new.
247
+ *
248
+ * A host that declared the key itself has already made that choice — even as an
249
+ * empty object — so `ids` is never added to one that exists.
250
+ */
251
+ const ensureExternallyConnectable = (manifest) => {
252
+ const declared = manifest.externally_connectable;
253
+ const existing = declared?.matches;
254
+ const merged = uniqueMerge(existing, EXTERNALLY_CONNECTABLE_MATCHES);
255
+ if (Array.isArray(existing) && merged.length === existing.length) return false;
256
+ if (!declared) {
257
+ manifest.externally_connectable = { matches: merged, ids: ['*'] };
258
+ return true;
259
+ }
260
+ declared.matches = merged;
261
+ return true;
262
+ };
263
+
264
+ /**
265
+ * The file's own indentation, so rewriting it produces a one-line diff instead
266
+ * of reformatting a manifest the host may keep at 4 spaces or tabs.
267
+ */
268
+ const detectIndent = (raw) => {
269
+ const match = raw.match(/\n([ \t]+)"/);
270
+ if (!match) return 2;
271
+ return match[1].includes('\t') ? '\t' : match[1].length;
272
+ };
273
+
274
+ /**
275
+ * The file's own line ending, for the same reason as the indentation: a manifest
276
+ * kept at CRLF must come back CRLF, or the one-key diff becomes a whole-file one.
277
+ * `JSON.stringify` only ever emits `\n`, and a newline inside a JSON string is
278
+ * escaped rather than literal, so rewriting every `\n` is safe.
279
+ */
280
+ const detectEol = (raw) => (raw.includes('\r\n') ? '\r\n' : '\n');
281
+
282
+ // --- vendor ------------------------------------------------------------------
283
+
284
+ /**
285
+ * Add the settings-page origins to the extension's manifest if one is missing.
286
+ *
287
+ * `vendor` is a build step, so this writes only when the entry is actually
288
+ * absent: once added, every later build is a no-op that never touches the file.
289
+ * It is here rather than in `init` alone because `init` runs once, at scaffold
290
+ * time — every extension integrated before the opt-out shipped would otherwise
291
+ * keep a manifest that silently makes the opt-out link a dead end.
292
+ */
293
+ const patchExternallyConnectable = (root) => {
294
+ const file = path.join(root, 'manifest.json');
295
+ // Vendoring from a build directory is legitimate, and there is no way to guess
296
+ // where the real manifest lives. `doctor` is what reports the gap in that case.
297
+ if (!existsSync(file)) return;
298
+
299
+ const raw = readFileSync(file, 'utf8');
300
+ let manifest;
301
+ try {
302
+ manifest = JSON.parse(raw);
303
+ } catch {
304
+ log(c.warn('! manifest.json is not valid JSON — left unchanged.'));
305
+ return;
306
+ }
307
+
308
+ const before = [...(manifest.externally_connectable?.matches ?? [])];
309
+ if (!ensureExternallyConnectable(manifest)) return;
310
+ const added = manifest.externally_connectable.matches.filter((match) => !before.includes(match));
311
+
312
+ const eol = detectEol(raw);
313
+ const body = JSON.stringify(manifest, null, detectIndent(raw)).replace(/\n/g, eol);
314
+ writeFileSync(file, body + (raw.endsWith('\n') ? eol : ''));
315
+ log(c.ok(`✓ Added ${added.join(', ')} to manifest.json`));
316
+ log(c.dim(' externally_connectable — without it the herogpu settings page cannot'));
317
+ log(c.dim(' reach this extension, so end users have no way to opt out.'));
318
+ };
319
+
320
+ /**
321
+ * Put one layout's files into `target`: the branded files under the layout's
322
+ * prefix, the layout's assets manifest, and the unbranded runtime assets.
323
+ * Nothing of the other layout's naming is written, and nothing is removed.
324
+ */
325
+ const vendorInto = (target, layout) => {
326
+ mkdirSync(target, { recursive: true });
327
+
328
+ // The offscreen host bundle (contains the SDK itself), the service-worker
329
+ // consent bridge (tiny; no SDK runtime inside), the settings link, the worker.
330
+ for (const file of BRANDED_FILES) {
331
+ cpSync(file.from, path.join(target, `${layout.name}-${file.as}`));
332
+ }
333
+ cpSync(path.join(distAssets, assetsManifestName(layout)), path.join(target, assetsManifestName(layout)));
334
+ // All pinned runtime assets whose names carry no brand (transformers + ONNX
335
+ // wasm, wllama + wasm). The branded ones were placed above, under one name.
336
+ cpSync(distAssets, target, {
337
+ recursive: true,
338
+ filter: (source) => path.dirname(source) !== distAssets || !isBrandedName(path.basename(source))
339
+ });
340
+
341
+ const manifest = readAssetsManifest(target, layout);
342
+ const rel = path.relative(process.cwd(), target) || '.';
343
+ log(c.ok(`✓ Vendored herogpu runtime into ${rel}`));
344
+ if (manifest) {
345
+ log(
346
+ c.dim(
347
+ ` sdk ${manifest.sdkVersion} · transformers ${manifest.transformersVersion} · wllama ${manifest.wllamaVersion}`
348
+ )
349
+ );
350
+ }
351
+ };
352
+
353
+ /**
354
+ * `vendor [outDir]`. With no folder given, the extension's layout is resolved
355
+ * and written to its own vendor/ folder; with one, the files go there, named
356
+ * the way that folder (or the extension's code) already names them. Returns
357
+ * the layouts written, the first being the one new glue should be written for.
358
+ */
359
+ const vendor = (outDir, manifestRoot = process.cwd()) => {
360
+ ensureDistPresent();
361
+ let layouts;
362
+ if (outDir) {
363
+ const target = path.resolve(process.cwd(), outDir);
364
+ layouts = resolveNamingForDir(target, manifestRoot);
365
+ for (const layout of layouts) vendorInto(target, layout);
366
+ } else {
367
+ layouts = resolveLayouts(manifestRoot);
368
+ for (const layout of layouts) vendorInto(path.join(manifestRoot, layoutDir(layout)), layout);
369
+ }
370
+ patchExternallyConnectable(manifestRoot);
371
+ return layouts;
372
+ };
373
+
374
+ const readAssetsManifest = (dir, layout) => {
375
+ const file = path.join(dir, assetsManifestName(layout));
376
+ if (!existsSync(file)) return null;
377
+ try {
378
+ return JSON.parse(readFileSync(file, 'utf8'));
379
+ } catch {
380
+ return null;
381
+ }
382
+ };
383
+
384
+ // --- init (scaffold) ---------------------------------------------------------
385
+
386
+ // The glue is written for one layout: its folder and file names, and the SDK
387
+ // names spelled the way that layout's own code spells them (`initHeroGpuOffscreen`
388
+ // in vendor/herogpu, `initZeroGpuOffscreen` next to a 0.5.1 integration; both
389
+ // are the same functions).
390
+
391
+ const OFFSCREEN_HTML = `<!DOCTYPE html>
392
+ <html>
393
+ <head><meta charset="utf-8" /><title>herogpu offscreen</title></head>
394
+ <body>
395
+ <script type="module" src="offscreen.js"></script>
396
+ </body>
397
+ </html>
398
+ `;
399
+
400
+ const offscreenJs = ({ name, api }) => `import { init${api}Offscreen } from "./vendor/${name}/${name}-offscreen.js";
401
+
402
+ // The offscreen document is where the SDK runs (it needs window/DOM + workers).
403
+ // It registers the device and starts automatically as soon as this document loads.
404
+ init${api}Offscreen({
405
+ edgeOperatorKey: "REPLACE_WITH_YOUR_OPERATOR_KEY",
406
+ enableConsoleLogs: true
407
+ });
408
+ `;
409
+
410
+ const backgroundJs = ({ name, api }) => `// herogpu service worker. Owns the offscreen document where the SDK runs, and
411
+ // gates it on the end user's choice: while they are opted out, the document is
412
+ // never created, so the decision survives browser restarts. Merge into your
413
+ // existing service worker if you already have one.
414
+ importScripts("vendor/${name}/${name}-background.js");
415
+
416
+ // Installs the consent bridge: it answers the herogpu-hosted settings page
417
+ // (via externally_connectable), answers your own popup/options page, reacts to
418
+ // storage changes, and starts the SDK on install/startup only if opted in.
419
+ ${api}Background.register${api}ConsentBridge({
420
+ offscreenPath: "offscreen.html"
421
+ });
422
+
423
+ // Read or change the choice from your own UI:
424
+ // await ${api}Background.get${api}Consent() -> { optedIn, updatedAt, source }
425
+ // await ${api}Background.set${api}Consent(false) -> stops the SDK now
426
+ // ${api}Background.build${api}SettingsUrl({ extensionId: chrome.runtime.id })
427
+ //
428
+ // Use the model the device holds in your own extension (app-side inference, 0.5.0):
429
+ // await ${api}Background.get${api}EligibleModels() -> every model of the list, judged for this device
430
+ // await ${api}Background.switch${api}Model(modelId) -> { granted, activeModelId, reason? }
431
+ // await ${api}Background.run${api}Local({ text }) -> { response, modelId, location: "device", … }
432
+ // ${api}Background.on${api}Event(({ event, detail }) => {})
433
+ `;
434
+
435
+ const optionsHtml = ({ name }) => `<!DOCTYPE html>
436
+ <html>
437
+ <head>
438
+ <meta charset="utf-8" />
439
+ <title>Settings</title>
440
+ <style>
441
+ body { font-family: system-ui, sans-serif; margin: 2rem; max-width: 34rem; line-height: 1.5; }
442
+ .row { display: flex; align-items: flex-start; gap: .75rem; margin-top: 1.5rem; }
443
+ .muted { color: #666; font-size: .875rem; }
444
+ .error { color: #b3261e; font-weight: 500; }
445
+ </style>
446
+ </head>
447
+ <body>
448
+ <h1>Resource sharing</h1>
449
+ <p class="muted">
450
+ This app can use some of your device's free or spare resources, such as
451
+ unused computing power and network bandwidth. You can turn this off at any
452
+ time.
453
+ </p>
454
+ <div class="row">
455
+ <input type="checkbox" id="${name}-opt-in" />
456
+ <label for="${name}-opt-in">Allow this app to use my device's spare resources</label>
457
+ </div>
458
+ <p class="muted" id="${name}-status"></p>
459
+ <script src="options.js"></script>
460
+ </body>
461
+ </html>
462
+ `;
463
+
464
+ const optionsJs = ({ name }) => `// Reads and writes the herogpu consent flag through the service-worker bridge.
465
+ const box = document.getElementById("${name}-opt-in");
466
+ const status = document.getElementById("${name}-status");
467
+
468
+ // The last state the service worker confirmed, and which request confirmed it.
469
+ // A failed write puts the box back to this, instead of leaving the user's click
470
+ // standing as though it had saved.
471
+ let stored = null;
472
+ let storedSeq = 0;
473
+
474
+ // The bridge answers each request on its own: a read is a storage lookup, a
475
+ // write also waits for the offscreen document to start or stop. So the initial
476
+ // read can land after a write the user has already made. Only the newest
477
+ // request is allowed to paint; an older answer is stale by definition.
478
+ let latest = 0;
479
+
480
+ const request = (message, done) => {
481
+ const seq = ++latest;
482
+ chrome.runtime.sendMessage(message, (res) => {
483
+ // Read lastError either way — left unread, Chrome logs it as unchecked. It
484
+ // is also the only signal when the service worker never answers at all.
485
+ const error = chrome.runtime.lastError?.message;
486
+ // Too stale to paint is not too stale to be true. A write that landed while
487
+ // a newer one was in flight is still the freshest word on what is actually
488
+ // stored, and dropping it would leave a later failure restoring the box to
489
+ // a state two toggles old. Only an older answer than the one already
490
+ // recorded is discarded.
491
+ if (res?.ok && seq > storedSeq) {
492
+ stored = res.consent;
493
+ storedSeq = seq;
494
+ }
495
+ if (seq === latest) done(res, error);
496
+ });
497
+ };
498
+
499
+ const setStatus = (text, isError) => {
500
+ status.textContent = text;
501
+ status.classList.toggle("error", !!isError);
502
+ };
503
+
504
+ const render = (consent) => {
505
+ box.indeterminate = false;
506
+ box.checked = !!consent?.optedIn;
507
+ setStatus(
508
+ consent?.updatedAt
509
+ ? \`Last changed \${new Date(consent.updatedAt).toLocaleString()}.\`
510
+ : "",
511
+ false
512
+ );
513
+ };
514
+
515
+ // Nothing was stored, so the SDK is still doing whatever it was doing before the
516
+ // click. Show that, and never a bare unchecked box — that would claim sharing is
517
+ // off while it is running.
518
+ const restore = (message) => {
519
+ if (stored) {
520
+ box.indeterminate = false;
521
+ box.checked = !!stored.optedIn;
522
+ } else {
523
+ box.indeterminate = true;
524
+ }
525
+ setStatus(message, true);
526
+ };
527
+
528
+ request({ type: "${name}:getConsent" }, (res, error) => {
529
+ if (res?.ok) {
530
+ render(res.consent);
531
+ return;
532
+ }
533
+ restore(error || res?.error || "Could not read your current setting.");
534
+ });
535
+
536
+ box.addEventListener("change", () => {
537
+ request({ type: "${name}:setConsent", optedIn: box.checked }, (res, error) => {
538
+ if (res?.ok) {
539
+ render(res.consent);
540
+ return;
541
+ }
542
+ restore(error || res?.error || "Could not save your choice — sharing is unchanged.");
543
+ });
544
+ });
545
+ `;
546
+
547
+ const patchManifest = (dir) => {
548
+ const file = path.join(dir, 'manifest.json');
549
+ if (!existsSync(file)) {
550
+ log(c.warn(' ! manifest.json not found — skipping manifest patch.'));
551
+ return;
552
+ }
553
+ const manifest = JSON.parse(readFileSync(file, 'utf8'));
554
+ manifest.permissions = uniqueMerge(manifest.permissions, ['offscreen', 'storage']);
555
+ manifest.host_permissions = uniqueMerge(manifest.host_permissions, HOST_PERMISSIONS);
556
+ manifest.content_security_policy = manifest.content_security_policy || {};
557
+ if (!manifest.content_security_policy.extension_pages) {
558
+ manifest.content_security_policy.extension_pages = REQUIRED_CSP;
559
+ }
560
+ if (!manifest.background) {
561
+ manifest.background = { service_worker: 'background.js' };
562
+ }
563
+ // Lets the herogpu-hosted settings page message this extension so an end user
564
+ // can turn sharing off. No content script and no extra host permission needed.
565
+ ensureExternallyConnectable(manifest);
566
+ if (!manifest.options_page && !manifest.options_ui) {
567
+ manifest.options_ui = { page: 'options.html', open_in_tab: true };
568
+ }
569
+ writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n');
570
+ log(c.ok('✓ Patched manifest.json (permissions, CSP, host permissions)'));
571
+ };
572
+
573
+ const scaffoldFile = (dir, name, contents) => {
574
+ const file = path.join(dir, name);
575
+ if (existsSync(file)) {
576
+ log(c.dim(` • ${name} exists — left unchanged`));
577
+ return;
578
+ }
579
+ writeFileSync(file, contents);
580
+ log(c.ok(`✓ Created ${name}`));
581
+ };
582
+
583
+ const init = (dir) => {
584
+ const root = path.resolve(process.cwd(), dir || '.');
585
+ if (!existsSync(root)) die(`Directory not found: ${root}`);
586
+ // A fresh extension gets the command's own layout; one that already has a
587
+ // layout keeps it, and any glue file it is still missing is written to match.
588
+ const [layout] = vendor(undefined, root);
589
+ scaffoldFile(root, 'offscreen.html', OFFSCREEN_HTML);
590
+ scaffoldFile(root, 'offscreen.js', offscreenJs(layout));
591
+ scaffoldFile(root, 'background.js', backgroundJs(layout));
592
+ scaffoldFile(root, 'options.html', optionsHtml(layout));
593
+ scaffoldFile(root, 'options.js', optionsJs(layout));
594
+ patchManifest(root);
595
+ log('');
596
+ log(c.ok('herogpu integrated.') + ' Next:');
597
+ log(' 1. Put your operator key in offscreen.js (REPLACE_WITH_YOUR_OPERATOR_KEY).');
598
+ log(' 2. Load the extension unpacked — it registers automatically on startup.');
599
+ log(' 3. Re-run ' + c.dim(`npx ${invokedAs} vendor`) + ' in your build to stay up to date.');
600
+ log(' 4. Give users the opt-out link (options.html ships one, or link them to');
601
+ log(' ' + c.dim(`${SETTINGS_PAGE_URL}?browser=chrome&extension_id=<your id>`) + ').');
602
+ };
603
+
604
+ // --- doctor ------------------------------------------------------------------
605
+
606
+ /**
607
+ * A mention is not a call. Block comments and whole-line `//` comments are
608
+ * dropped first, so a commented-out invocation — the shape someone leaves
609
+ * behind while debugging — is not read as wired up. Mid-line `//` is left
610
+ * alone: stripping it would eat the `//` of any URL in a string literal.
611
+ */
612
+ const callsConsentBridge = (source) => {
613
+ const code = source
614
+ .replace(/\/\*[\s\S]*?\*\//g, '')
615
+ .split('\n')
616
+ .filter((line) => !/^\s*\/\//.test(line))
617
+ .join('\n');
618
+ // The bridge is one function with two names; calling either wires it.
619
+ return /register(Hero|Zero)GpuConsentBridge\s*\(/.test(code);
620
+ };
621
+ const mentionsConsentBridge = (source) => /register(Hero|Zero)GpuConsentBridge/.test(source);
622
+
623
+ const doctor = (dir) => {
624
+ const root = path.resolve(process.cwd(), dir || '.');
625
+ let problems = 0;
626
+
627
+ const installed = readAssetsManifest(distAssets, LAYOUTS.herogpu);
628
+ // Either layout is a healthy integration: vendor/herogpu, or the
629
+ // vendor/zerogpu one an extension integrated with 0.5.1 keeps.
630
+ const vendoredLayouts = Object.values(LAYOUTS)
631
+ .map((layout) => {
632
+ const vendorDir = path.join(root, layoutDir(layout));
633
+ return { layout, vendorDir, vendored: readAssetsManifest(vendorDir, layout) };
634
+ })
635
+ .filter((entry) => entry.vendored);
636
+
637
+ if (vendoredLayouts.length === 0) {
638
+ log(c.err(`✗ No vendored assets found. Run: npx ${invokedAs} vendor`));
639
+ problems += 1;
640
+ }
641
+ for (const { layout, vendorDir, vendored } of vendoredLayouts) {
642
+ for (const f of vendored.files || []) {
643
+ if (!existsSync(path.join(vendorDir, f))) {
644
+ log(c.err(`✗ Missing vendored file: ${layoutDir(layout).replace(/\\/g, '/')}/${f}`));
645
+ problems += 1;
646
+ }
647
+ }
648
+ if (installed && vendored.sdkVersion !== installed.sdkVersion) {
649
+ log(
650
+ c.warn(
651
+ `! Vendored SDK ${vendored.sdkVersion} differs from installed ${installed.sdkVersion}. Run: npx ${invokedAs} vendor`
652
+ )
653
+ );
654
+ problems += 1;
655
+ } else if (installed) {
656
+ log(c.ok(`✓ Vendored assets in sync (sdk ${vendored.sdkVersion}, ${layoutDir(layout).replace(/\\/g, '/')})`));
657
+ }
658
+ }
659
+
660
+ const manifestFile = path.join(root, 'manifest.json');
661
+ let manifest = null;
662
+ if (!existsSync(manifestFile)) {
663
+ log(c.warn('! manifest.json not found.'));
664
+ } else {
665
+ manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
666
+ const csp = manifest.content_security_policy?.extension_pages || '';
667
+ if (!csp.includes("'wasm-unsafe-eval'")) {
668
+ log(c.err("✗ CSP extension_pages missing 'wasm-unsafe-eval'"));
669
+ problems += 1;
670
+ }
671
+ if (!(manifest.permissions || []).includes('offscreen')) {
672
+ log(c.err('✗ manifest permissions missing "offscreen"'));
673
+ problems += 1;
674
+ }
675
+ const hosts = [
676
+ ...(manifest.host_permissions || []),
677
+ ...(manifest.optional_host_permissions || [])
678
+ ];
679
+ // The device registry answers on herogpu.com (this build's default) and on
680
+ // zerogpu.ai (the default up to 0.5.1); a permission for either is accepted.
681
+ if (!hosts.some((h) => h === '<all_urls>' || mentionsSdkDomain(h))) {
682
+ log(c.warn('! No herogpu.com host permission found (register/WS may be blocked).'));
683
+ }
684
+ // Without this the hosted settings page cannot reach the extension, so an
685
+ // end user has no way to opt out from the web. An entry for either site
686
+ // passes; `vendor` adds whichever one is missing.
687
+ const connectable = manifest.externally_connectable?.matches || [];
688
+ if (!connectable.some((m) => mentionsSdkDomain(m))) {
689
+ log(
690
+ c.err(
691
+ '✗ manifest externally_connectable.matches missing a herogpu.com / zerogpu.ai entry (end users cannot opt out from the settings page)'
692
+ )
693
+ );
694
+ problems += 1;
695
+ } else {
696
+ const settingsHost = new URL(SETTINGS_PAGE_URL).hostname;
697
+ if (!connectable.some((m) => String(m).includes(settingsHost))) {
698
+ log(
699
+ c.warn(
700
+ `! manifest externally_connectable.matches has no ${settingsHost} entry, and the settings page is served from there today. Run: npx ${invokedAs} vendor`
701
+ )
702
+ );
703
+ }
704
+ }
705
+ }
706
+
707
+ // Check the worker the manifest actually loads. An extension that already had
708
+ // a service worker keeps its own path, and that merged file — not a root
709
+ // background.js — is where the bridge has to be registered.
710
+ const workerPath = manifest?.background?.service_worker || 'background.js';
711
+ const backgroundFile = path.join(root, workerPath);
712
+ if (!existsSync(backgroundFile)) {
713
+ log(c.err(`✗ Service worker not found: ${workerPath}`));
714
+ problems += 1;
715
+ } else {
716
+ const background = readFileSync(backgroundFile, 'utf8');
717
+ if (!callsConsentBridge(background)) {
718
+ // Say which of the two it is — "does not call" reads like a doctor bug to
719
+ // someone who can see the name right there in their file.
720
+ const commentedOut = mentionsConsentBridge(background);
721
+ log(
722
+ c.warn(
723
+ `! ${workerPath} ${
724
+ commentedOut
725
+ ? 'mentions the consent bridge (registerHeroGpuConsentBridge) but never calls it'
726
+ : 'does not call registerHeroGpuConsentBridge'
727
+ } — the SDK will start regardless of the user's choice.`
728
+ )
729
+ );
730
+ problems += 1;
731
+ }
732
+ }
733
+
734
+ if (problems === 0) {
735
+ log(c.ok('✓ herogpu integration looks healthy.'));
736
+ } else {
737
+ process.exitCode = 1;
738
+ }
739
+ };
740
+
741
+ // --- main --------------------------------------------------------------------
742
+
743
+ /**
744
+ * Run the CLI. `commandName` is the name it was started under, as given by the
745
+ * bin file that was run: 'herogpu', or 'zerogpu' for the earlier name.
746
+ */
747
+ export const runCli = (commandName = 'herogpu') => {
748
+ invokedAs = LAYOUTS[commandName] ? commandName : 'herogpu';
749
+ const [command, ...rest] = process.argv.slice(2);
750
+ const { flags, positional } = parseFlags(rest);
751
+ switch (command) {
752
+ case 'vendor':
753
+ vendor(positional[0]);
754
+ break;
755
+ case 'init':
756
+ init(flags.dir);
757
+ break;
758
+ case 'doctor':
759
+ doctor(flags.dir);
760
+ break;
761
+ case undefined:
762
+ case 'help':
763
+ case '--help':
764
+ case '-h':
765
+ log(`${invokedAs} — integrate the herogpu SDK into a Chrome (MV3) extension
766
+
767
+ Usage:
768
+ npx ${invokedAs} vendor [outDir] Copy SDK + model runtimes into the extension
769
+ (default: vendor/${invokedAs}) + add the opt-out origins
770
+ to manifest.json. Run this in your build.
771
+ npx ${invokedAs} init [--dir .] Vendor + scaffold offscreen/background + patch manifest
772
+ npx ${invokedAs} doctor [--dir .] Verify the integration is wired and in sync
773
+
774
+ An extension that already has vendor/herogpu or vendor/zerogpu keeps that
775
+ folder and its file names; the files are updated in place.
776
+ `);
777
+ break;
778
+ default:
779
+ die(`Unknown command: ${command}. Run "npx ${invokedAs} help".`);
780
+ }
781
+ };