import type { VisionManifest } from './vision.ts'; export interface VisionInstallProgress { completed: number; total: number; detail?: string; } export interface InstalledVision { manifest: VisionManifest; readShard(name: string): Promise; } async function sha256Hex(bytes: Uint8Array): Promise { const digest = await crypto.subtle.digest('SHA-256', bytes as unknown as BufferSource); return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join(''); } async function readFile(directory: FileSystemDirectoryHandle, name: string): Promise { try { const handle = await directory.getFileHandle(name); return new Uint8Array(await (await handle.getFile()).arrayBuffer()); } catch { return null; } } async function writeFile(directory: FileSystemDirectoryHandle, name: string, bytes: Uint8Array): Promise { const handle = await directory.getFileHandle(name, { create: true }); const writable = await handle.createWritable({ keepExistingData: false }); await writable.write(bytes as unknown as FileSystemWriteChunkType); await writable.close(); } function validateManifest(value: unknown): VisionManifest { if (!value || typeof value !== 'object') throw new Error('invalid vision manifest'); const candidate = value as Partial; if (candidate.format !== 'botpsy-vision-package' || candidate.schemaVersion !== 1) { throw new Error('unsupported vision package format'); } if (!candidate.config || !Array.isArray(candidate.tensors) || !Array.isArray(candidate.shards)) { throw new Error('incomplete vision manifest'); } if (!candidate.source || typeof candidate.source.safetensorsSha256 !== 'string') { throw new Error('vision manifest is missing its source identity'); } return candidate as VisionManifest; } export class VisionInstaller { private readonly rootPromise: Promise; private constructor() { this.rootPromise = navigator.storage.getDirectory(); } static async open(): Promise { if (typeof navigator.storage?.getDirectory !== 'function') throw new Error('OPFS is unavailable'); return new VisionInstaller(); } async install( manifestUrl: string, onProgress?: (progress: VisionInstallProgress) => void, ): Promise { const lock = await navigator.locks.request('botpsy-vision-install', { mode: 'exclusive' }, async () => { const response = await fetch(manifestUrl, { cache: 'no-cache' }); if (!response.ok) throw new Error(`vision manifest fetch failed: ${response.status}`); const manifest = validateManifest(await response.json()); const root = await this.rootPromise; const directory = await root.getDirectoryHandle( `botpsy-vision-${manifest.source.safetensorsSha256}`, { create: true }, ); const total = manifest.shards.reduce((sum, shard) => sum + shard.byteLength, 0); let completed = 0; const baseUrl = new URL('.', new URL(manifestUrl, self.location.href)); for (const shard of manifest.shards) { let bytes = await readFile(directory, shard.name); if (bytes?.byteLength === shard.byteLength) { const hash = await sha256Hex(bytes); if (hash !== shard.sha256) bytes = null; } else { bytes = null; } if (!bytes) { const shardResponse = await fetch(new URL(shard.name, baseUrl)); if (!shardResponse.ok) throw new Error(`vision shard fetch failed: ${shardResponse.status}`); bytes = new Uint8Array(await shardResponse.arrayBuffer()); if (bytes.byteLength !== shard.byteLength) throw new Error(`vision shard ${shard.name} length mismatch`); const hash = await sha256Hex(bytes); if (hash !== shard.sha256) throw new Error(`vision shard ${shard.name} hash mismatch`); await writeFile(directory, shard.name, bytes); } completed += shard.byteLength; onProgress?.({ completed, total, detail: shard.name }); } return { manifest, readShard: async (name: string): Promise => { const bytes = await readFile(directory, name); if (!bytes) throw new Error(`vision shard ${name} is missing`); return bytes; }, } satisfies InstalledVision; }); if (!lock) throw new Error('vision installation lock was not acquired'); return lock; } }