import type * as plugins from './plugins.js'; /** * A thinking signature carries what the model needs to continue from its own reasoning: the provider * metadata of the reasoning part (for OpenAI, the reasoning item id and its encrypted content) and the scope * it was written in. A client hands thinking blocks back unchanged, so the signature is how that metadata * returns to the model on the next request. The client holds it, so it is authenticated: an HMAC-SHA256 under * the host's key covers the prefix and the payload, `flexharness:.`, both base64url. */ const signaturePrefix = 'flexharness:'; interface IThinkingSignaturePayload { scope: string; metadata: plugins.SharedV4ProviderMetadata; } const toBase64Url = (bytesArg: Uint8Array): string => { let binary = ''; for (let offset = 0; offset < bytesArg.length; offset += 0x8000) { binary += String.fromCharCode(...bytesArg.subarray(offset, offset + 0x8000)); } return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/u, ''); }; const fromBase64Url = (textArg: string): Uint8Array => { const binary = atob(textArg.replace(/-/g, '+').replace(/_/g, '/')); const bytes = new Uint8Array(binary.length); for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); return bytes; }; /** Decoded bytes, or `undefined` for text that is not base64url. */ const readBase64Url = (textArg: string): Uint8Array | undefined => { try { return fromBase64Url(textArg); } catch { return undefined; } }; /** The shortest signature key accepted: the output length of SHA-256. */ const minimumSignatureKeyBytes = 32; /** Writes and verifies thinking signatures under one host key. */ export class ThinkingSignatures { private readonly keyBytes: Uint8Array; private key: Promise | undefined; constructor(keyArg: Uint8Array) { if (keyArg.byteLength < minimumSignatureKeyBytes) { throw new RangeError( `signatureKey has ${keyArg.byteLength} bytes; a thinking signature key needs at least ${minimumSignatureKeyBytes}.`, ); } // A copy, so a host that later reuses its buffer does not change the key. this.keyBytes = new Uint8Array(keyArg); } private hmacKey(): Promise { this.key ??= crypto.subtle.importKey('raw', this.keyBytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']); return this.key; } public async sign(scopeArg: string, metadataArg: plugins.SharedV4ProviderMetadata): Promise { const payload: IThinkingSignaturePayload = { scope: scopeArg, metadata: metadataArg }; const signed = `${signaturePrefix}${toBase64Url(new TextEncoder().encode(JSON.stringify(payload)))}`; const mac = await crypto.subtle.sign('HMAC', await this.hmacKey(), new TextEncoder().encode(signed)); return `${signed}.${toBase64Url(new Uint8Array(mac))}`; } /** * The provider options a signature returns to the model, or `undefined` for a signature this key did not * write, one that was changed, or one of another scope. */ public async verify(signatureArg: string, scopeArg: string): Promise { const separator = signatureArg.lastIndexOf('.'); if (!signatureArg.startsWith(signaturePrefix) || separator < signaturePrefix.length) return undefined; const signed = signatureArg.slice(0, separator); const mac = readBase64Url(signatureArg.slice(separator + 1)); if (!mac || !await crypto.subtle.verify('HMAC', await this.hmacKey(), mac, new TextEncoder().encode(signed))) { return undefined; } // Authentic, so this service wrote the payload in the shape `sign` gives it. const payload = JSON.parse(new TextDecoder().decode(fromBase64Url(signed.slice(signaturePrefix.length)))) as IThinkingSignaturePayload; return payload.scope === scopeArg ? payload.metadata : undefined; } } /** The metadata of a reasoning part, from its start and its end; the end states what the start could not. */ export const mergeReasoningMetadata = ( startArg: plugins.SharedV4ProviderMetadata | undefined, endArg: plugins.SharedV4ProviderMetadata | undefined, ): plugins.SharedV4ProviderMetadata => { const merged: plugins.SharedV4ProviderMetadata = {}; for (const source of [startArg, endArg]) { for (const [provider, values] of Object.entries(source ?? {})) { const current = merged[provider] ?? {}; const next: plugins.JSONObject = { ...current }; for (const [key, value] of Object.entries(values)) { if (value !== null && value !== undefined) next[key] = value; else if (!(key in next)) next[key] = value; } merged[provider] = next; } } return merged; };