import { createHash } from 'node:crypto'; import type { LocalProvider, PromptCacheContext } from '../types.js'; import { cacheCapabilities } from './cacheCapabilities.js'; type Item = Record; type Entry = { id: string; until: number; items: string[] }; type Prepared = { body: string; complete?: (response: Item) => void; stale?: () => void; }; const entries = new Map(); const warming = new Map>(); const hash = (x: unknown) => createHash('sha256').update(JSON.stringify(x)).digest('base64url'); const now = () => Math.floor(Date.now() / 1000); function remember(key: string, e: Entry) { entries.delete(key); entries.set(key, e); if (entries.size > 64) entries.delete(entries.keys().next().value!); } // Accept only output that can be represented completely by toResponsesInput. // A hidden reasoning item, refusal, annotation or unsupported tool ends reuse. function canonicalOutput(output: unknown): Item[] | undefined { if (!Array.isArray(output) || !output.length) return; const result: Item[] = []; for (const item of output) { if (item?.status && item.status !== 'completed') return; if ( item?.type === 'function_call' && ['call_id', 'name', 'arguments'].every((k) => typeof item[k] === 'string') ) { result.push({ type: 'function_call', call_id: item.call_id, name: item.name, arguments: item.arguments, }); } else if ( item?.type === 'message' && item.role === 'assistant' && item.content?.length === 1 ) { const c = item.content[0]; if ( c?.type !== 'output_text' || typeof c.text !== 'string' || c.annotations?.length ) return; result.push({ role: 'assistant', content: [{ type: 'output_text', text: c.text }], }); } else return; } return result; } /** No response IDs or material on disk. A restart, policy change or prefix mismatch * starts afresh from the host's authoritative full request. */ export async function prepareArkRequest( provider: LocalProvider, url: string, original: string, ctx: PromptCacheContext | undefined, prewarm: (body: string) => Promise, mode = process.env.MINIMAL_AGENT_ARK_CACHE, signal?: AbortSignal, forkBrief?: string, ): Promise { const full = { body: original }; if ( (mode !== 'prefix' && mode !== 'session') || !ctx?.scopeKey || provider.promptCache?.mode === 'disabled' || !cacheCapabilities(provider).arkSession || url !== 'https://ark.cn-beijing.volces.com/api/v3/responses' ) return full; if (mode === 'session' && ctx.role === 'fork' && !ctx.traceLane) return full; const { input, ...options } = JSON.parse(original); if ( !Array.isArray(input) || !input.length || input.length > 2048 || options.text || options.instructions ) return full; const fingerprints = input.map(hash); const optionsKey = [ mode, url, provider.apiKey, ctx.scopeKey, ctx.role ?? 'main', options, ]; const expires = now() + 300; const start = { ...options, store: true, caching: { type: 'enabled' }, expire_at: expires, }; const continuation = (entry: Entry) => { const { tools, tool_choice, ...inherited } = start; return JSON.stringify({ ...inherited, expire_at: entry.until, previous_response_id: entry.id, input: input.slice(entry.items.length), }); }; function entry( response: Item, items: string[], limit: number, ): Entry | undefined { if ( typeof response.id !== 'string' || !response.id || response.status !== 'completed' ) return; const until = typeof response.expire_at === 'number' ? Math.min(response.expire_at, limit) : limit; if (!(until > now() + 2)) return; return { id: response.id, until, items }; } let prefix = 0; if (mode === 'prefix') { while ( input[prefix]?.role === 'system' && typeof input[prefix].content === 'string' ) prefix++; if ( prefix === 1 && forkBrief && input[prefix]?.role === 'user' && input[prefix].content === forkBrief ) prefix++; if ( !prefix || prefix === input.length || input.slice(0, prefix).reduce((n, m) => n + m.content.length, 0) < 2048 ) return full; } const key = hash([ ...optionsKey, mode === 'prefix' ? fingerprints.slice(0, prefix) : (ctx.traceLane ?? ''), ]); let saved = entries.get(key); if (saved && saved.until <= now() + 2) { entries.delete(key); saved = undefined; } if (mode === 'prefix' && !saved) { signal?.throwIfAborted(); let flight = warming.get(key); if (!flight) { if (warming.size >= 16) return full; flight = prewarm( JSON.stringify({ ...start, caching: { type: 'enabled', prefix: true }, stream: false, input: input.slice(0, prefix), }), ) .then((r) => { const e = r.usage && (r.usage as Item).output_tokens === 0 ? entry(r, fingerprints.slice(0, prefix), expires) : undefined; if (e) remember(key, e); return e; }) // Prewarming is optional. An owner transport failure (including its // cancellation) is a cache miss, not a failed inference for every waiter. .catch(() => undefined) .finally(() => warming.delete(key)); warming.set(key, flight); } // An independently cancelled sibling need not wait for the owner's POST. if (!signal) saved = await flight; else { let abort!: () => void; try { saved = await Promise.race([ flight, new Promise((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort(); }), ]); } finally { signal.removeEventListener('abort', abort); } } signal?.throwIfAborted(); if (!saved) return full; } const matches = saved && saved.items.length < input.length && saved.items.every((x, i) => x === fingerprints[i]); const prior = saved; return { body: matches ? continuation(saved!) : JSON.stringify({ ...start, input }), ...(matches ? { stale: () => { if (entries.get(key) === prior) entries.delete(key); }, } : {}), ...(mode === 'session' ? { complete: (response: Item) => { const output = canonicalOutput(response.output); const e = output && entry( response, [...fingerprints, ...output.map(hash)], matches ? prior!.until : expires, ); if (e && e.items.length <= 2048) remember(key, e); }, } : {}), }; } export function isStaleArkResponse(status: number, body: string) { if (![400, 404, 410].includes(status)) return false; return ( /previous_response_id|previous response|response[_ ](?:id|not_found)/i.test( body, ) && /expired|not[_ ]found|does not exist|无效|过期|不存在/i.test(body) ); }