feat: dsh-geek2api 0.1.0, a Geek2API route for DeepSeek Harness

Derived from dsh-packycode-api 1.1.7 (MIT) and rebuilt for the Geek2API
(sub2api) gateway: multi-endpoint failover, /v1/usage balances with wallet
dedupe, per-key coverage from /v1/models, sub2api failure wording, a Claude
runtime switch (HTTP or local CLI), and Claude/GPT web search backends.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
大阔andClaude Opus 5.5 committed 2026-10-15 00:50:06 +08:00
commit ed5154c042
94 files changed
+28617

No files matched your search

+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env node
/**
* Real official Claude CLI + built plan bridge, using a local fake gateway.
* No real credentials, quota, DSH instance or project files are involved.
*
* node scripts/cli-plan-check.mjs [--binary /path/to/claude]
*
* Verifies stdio ExitPlanMode, simultaneous plans, private file fallback,
* no-plan returns, actual plan-mode denials, MCP search and resource cleanup.
*/
import assert from 'node:assert/strict'
import { spawn } from 'node:child_process'
import { realpathSync } from 'node:fs'
import { access, mkdir, mkdtemp, readFile, realpath, rm, utimes, writeFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import { dirname, join, sep } from 'node:path'
import { createClaudeRunner, createClaudeSearchBridge, findClaudeBinary } from '../lib/index.js'
const args = process.argv.slice(2)
const binary = findClaudeBinary(args.includes('--binary') ? args[args.indexOf('--binary') + 1] : '')
const directory = await mkdtemp(join(tmpdir(), 'geek2api-cli-plan-check-'))
const ownedDirectory = await realpath(directory)
const configDir = join(directory, 'config')
const cases = new Map()
const failures = []
let searchCalls = 0
for (const id of ['a', 'b', 'file-only', 'no-plan', 'blocked']) {
const cwd = join(directory, id)
await mkdir(cwd)
cases.set(id, { id, cwd, calls: 0, controls: 0, exitControls: 0, errors: [], plan: `# Plan ${id}\n\nPreserve constraint ${id.toUpperCase()}_SENTINEL_426.` })
}
await mkdir(join(configDir, 'plans'), { recursive: true })
const savedSettings = JSON.stringify({ permissions: { allow: ['ExitPlanMode'], deny: ['WebFetch'] } })
await writeFile(join(configDir, 'settings.json'), savedSettings)
const stale = join(configDir, 'plans', 'unrelated.md')
await writeFile(stale, '# Unrelated\n\nThis is not the current request.')
// Even a misleading future mtime in the shared directory must not be evidence.
const future = new Date(Date.now() + 120_000)
await utimes(stale, future, future)
function texts(body) {
return [...(Array.isArray(body.system) ? body.system : []), ...(body.messages ?? []).flatMap(message => typeof message.content === 'string' ? [{ text: message.content }] : message.content ?? [])]
.filter(part => typeof part?.text === 'string').map(part => part.text).join('\n')
}
function privatePlanPath(state, body) {
assert.ok(state.planDirectory, `${state.id}: no private plansDirectory was passed`)
const root = realpathSync(state.planDirectory)
for (const match of texts(body).matchAll(/(?:[A-Za-z]:[\\/]|\/)[^\s<>"'`]+\.md/gu)) {
try {
const parent = realpathSync(dirname(match[0]))
if (parent === root || parent.startsWith(`${root}${sep}`)) return match[0]
} catch { /* not this run's plan file */ }
}
const exitSchema = (body.tools ?? []).find(tool => tool.name === 'ExitPlanMode')?.input_schema
const pathParents = [...texts(body).matchAll(/(?:[A-Za-z]:[\\/]|\/)[^\s<>"'`]+\.md/gu)].map(match => dirname(match[0]))
throw new Error(`${state.id}: official CLI did not announce a private plan file; candidate directories=${JSON.stringify(pathParents)}; public ExitPlanMode schema=${JSON.stringify(exitSchema)}`)
}
function respond(res, body, content) {
const tool = content.type === 'tool_use'
const message = { id: 'msg_plan_fixture', type: 'message', role: 'assistant', model: body.model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 1 } }
if (!body.stream) {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(JSON.stringify({ ...message, content: [content], stop_reason: tool ? 'tool_use' : 'end_turn' }))
return
}
res.writeHead(200, { 'content-type': 'text/event-stream' })
const event = (type, data) => res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`)
event('message_start', { message })
event('content_block_start', { index: 0, content_block: tool ? { ...content, input: {} } : { type: 'text', text: '' } })
event('content_block_delta', { index: 0, delta: tool ? { type: 'input_json_delta', partial_json: JSON.stringify(content.input) } : { type: 'text_delta', text: content.text } })
event('content_block_stop', { index: 0 })
event('message_delta', { delta: { stop_reason: tool ? 'tool_use' : 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } })
event('message_stop', {})
res.end()
}
const server = createServer((req, res) => {
let raw = ''
req.on('data', chunk => { raw += chunk })
req.on('end', () => {
let body
try { body = JSON.parse(raw) } catch { body = {} }
if (!req.url.startsWith('/v1/messages') || req.url.includes('count_tokens')) {
res.writeHead(req.url.includes('count_tokens') ? 200 : 404, { 'content-type': 'application/json' })
res.end(req.url.includes('count_tokens') ? '{"input_tokens":1}' : '{}')
return
}
try {
if (!(body.tools ?? []).some(tool => tool.name === 'Write')) return respond(res, body, { type: 'text', text: 'Auxiliary fixture answer.' })
const marker = /PLAN_FIXTURE:([a-z-]+)/u.exec(texts(body))?.[1]
const state = cases.get(marker)
assert.ok(state, 'a model turn lost its fixture marker')
assert.ok((body.tools ?? []).some(tool => tool.name === 'ExitPlanMode'), `${marker}: ExitPlanMode is missing from the real CLI catalog`)
assert.ok(!(body.tools ?? []).some(tool => tool.name === 'WebSearch'), `${marker}: native WebSearch must stay disabled`)
assert.ok((body.system ?? []).some(part => part.text?.startsWith("You are Claude Code, Anthropic's official CLI")), 'official identity changed')
const step = state.calls++
const tool = (name, input) => ({ type: 'tool_use', id: `fixture_${marker}_${step}`, name, input })
if (marker === 'blocked') return respond(res, body, step < 12 ? tool('Write', { file_path: join(state.cwd, 'must-not-exist.txt'), content: 'must remain blocked' }) : { type: 'text', text: 'Unexpectedly exceeded the denial budget.' })
if (marker === 'no-plan') return respond(res, body, { type: 'text', text: 'Read-only exploration; no plan was written.' })
const search = (body.tools ?? []).find(item => /^mcp__geek2api_search_[a-f0-9]+__web_search$/u.test(item.name ?? ''))
if (marker === 'a' && step === 0) {
assert.ok(search, 'plan mode lost its read-only search bridge')
return respond(res, body, tool(search.name, { query: 'plan fixture', max_results: 1 }))
}
const writeStep = marker === 'a' ? 1 : 0
if (step === writeStep) {
state.file = privatePlanPath(state, body)
return respond(res, body, tool('Write', { file_path: state.file, content: state.plan }))
}
if (marker === 'file-only') return respond(res, body, { type: 'text', text: 'The private plan was written; returning without ExitPlanMode.' })
return respond(res, body, tool('ExitPlanMode', { allowedPrompts: [] }))
} catch (error) {
failures.push(String(error.message))
respond(res, body, { type: 'text', text: 'Fixture assertion failed.' })
}
})
})
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
const runner = createClaudeRunner({
binary,
configDir,
resolveCredential: async () => ({ baseUrl: `http://127.0.0.1:${server.address().port}`, token: 'fixture-only-not-a-real-credential', label: 'local plan fixture' }),
timeoutMs: 90_000,
createSearchBridge: ({ signal }) => createClaudeSearchBridge({
signal,
search: async () => {
searchCalls++
return { content: 'Local mocked search.', sources: [{ url: 'https://example.com/fixture', title: 'Fixture source' }] }
},
}),
spawnImpl: (program, argv, options) => {
const state = [...cases.values()].find(item => item.cwd === options.cwd)
assert.ok(state, 'unknown fixture workspace')
assert.equal(argv[argv.indexOf('--permission-prompt-tool') + 1], 'stdio', 'permission callbacks are not routed over stdio')
assert.equal(options.env.CLAUDE_CONFIG_DIR, configDir, 'per-run plans must not change the credential/config home')
const settings = JSON.parse(argv[argv.indexOf('--settings') + 1])
state.planDirectory = settings.plansDirectory
assert.ok(typeof state.planDirectory === 'string' && state.planDirectory !== '')
const child = spawn(program, argv, options)
let buffer = ''
child.stdout.on('data', chunk => {
buffer += chunk
let index
while ((index = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, index)
buffer = buffer.slice(index + 1)
try {
const frame = JSON.parse(line)
if (frame.type === 'control_request') {
state.controls++
if (frame.request?.tool_name === 'ExitPlanMode') state.exitControls++
}
} catch { /* the runner owns stream parsing */ }
}
})
return child
},
})
async function run(id) {
const state = cases.get(id)
const events = []
for await (const event of runner.stream({ prompt: `PLAN_FIXTURE:${id}\nExplore read-only and hand the plan to DSH.`, model: 'claude-opus-5-5', mode: 'plan', cwd: state.cwd })) {
events.push(event)
if (event.type === 'tool-error') state.errors.push(event.text)
}
return events
}
try {
const parallel = await Promise.all(['a', 'b'].map(run))
assert.deepEqual(failures, [], 'the real CLI fixture failed before plan submission')
for (const [index, id] of ['a', 'b'].entries()) {
assert.deepEqual(cases.get(id).errors, [], `${id}: a permitted plan operation failed`)
assert.equal(parallel[index].find(event => event.type === 'plan')?.plan, cases.get(id).plan, `${id}: received another run's plan`)
assert.equal(cases.get(id).exitControls, 1, `${id}: native ExitPlanMode never reached the host control handler`)
}
assert.notEqual(cases.get('a').planDirectory, cases.get('b').planDirectory)
assert.equal(searchCalls, 1)
console.log('PASS: real stdio ExitPlanMode; concurrent plan ownership; plan-mode MCP search')
const fallback = await run('file-only')
assert.deepEqual(cases.get('file-only').errors, [])
assert.equal(fallback.find(event => event.type === 'plan')?.plan, cases.get('file-only').plan)
const noPlan = await run('no-plan')
assert.equal(noPlan.some(event => event.type === 'plan'), false, 'a no-plan return picked up an unrelated file')
console.log('PASS: private file fallback; no stale/shared-plan pickup')
await assert.rejects(run('blocked'), /too many denied permission prompts/u)
await assert.rejects(access(join(cases.get('blocked').cwd, 'must-not-exist.txt')), error => error.code === 'ENOENT')
assert.ok(cases.get('blocked').calls <= 9, 'actual CLI permission denials exceeded the bounded budget')
assert.deepEqual(failures, [])
assert.equal(await readFile(join(configDir, 'settings.json'), 'utf8'), savedSettings, 'existing permission settings were modified')
for (const state of cases.values()) await assert.rejects(access(state.planDirectory), error => error.code === 'ENOENT')
console.log('PASS: actual CLI denial budget; no project writes; private plan resources cleaned')
console.log('Claude responses and search were local fixtures, not live Claude upstream or desktop DSH integration.')
} finally {
await runner.close()
server.closeAllConnections()
await new Promise(resolve => server.close(resolve))
assert.equal(await realpath(directory), ownedDirectory)
assert.ok(ownedDirectory.startsWith(`${await realpath(tmpdir())}${sep}geek2api-cli-plan-check-`))
// Delete only this script's verified private fixture directory.
await rm(ownedDirectory, { recursive: true, force: true })
}
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env node
/**
* Real official CLI → built MCP bridge → search check, without requiring a
* Claude-group key. A local fake Anthropic gateway requests the MCP search
* tool and records that native WebSearch/server tools never appear. The CLI
* itself is real, including its MCP transport and permission handling.
*
* node scripts/cli-search-check.mjs
* node scripts/cli-search-check.mjs --live --backend claude
* node scripts/cli-search-check.mjs --live --backend gpt
* node scripts/cli-search-check.mjs --binary /path/to/claude
*
* Default: mocked search, no quota. --live: ONE real search through the
* selected Geek2API backend in read-only mode using the same stored key as
* live-check.mjs; edit/full are still mocked. No DSH is started, and no real
* key is given to the CLI or fake gateway or written into MCP configuration.
*/
import assert from 'node:assert/strict'
import { createServer } from 'node:http'
import { readFile, mkdtemp, realpath, rm } from 'node:fs/promises'
import { homedir, tmpdir } from 'node:os'
import { join } from 'node:path'
import { createClaudeRunner, createClaudeSearchBridge, createGeek2APISearchProvider, createHostPool, findClaudeBinary, Geek2APIKeyRing } from '../lib/index.js'
const args = process.argv.slice(2)
const option = (name, fallback) => args.includes(name) ? args[args.indexOf(name) + 1] : fallback
const backend = option('--backend', 'claude')
if (!['claude', 'gpt'].includes(backend)) throw new Error('backend must be claude or gpt')
const live = args.includes('--live')
const binary = findClaudeBinary(option('--binary', ''))
// This store is host-only; the real key never reaches the child process.
let record
const credentials = { readRecord: async () => record, modifyRecord: async (_id, mutate) => { record = await mutate(record); return record } }
const ring = new Geek2APIKeyRing(credentials)
let secret
if (live) {
const text = await readFile(join(homedir(), '.dsh', '.credentials.yaml'), 'utf8')
const match = /^\s*GEEK2API_API_KEY:\s*(.+)$/mu.exec(text)
if (match === null) throw new Error('Store a Geek2API key in DSH before using --live')
secret = match[1].trim().replace(/^['"]|['"]$/gu, '')
await ring.add(secret, 'CLI MCP live check')
}
const provider = createGeek2APISearchProvider({ ring, hosts: createHostPool(), backend: () => backend, resolveSessionId: () => 'dsh-cli-mcp-live-check' })
const directory = await mkdtemp(join(tmpdir(), 'geek2api-cli-mcp-check-'))
const ownedDirectory = await realpath(directory)
let mode
let mainCalls = 0
let searchCalls = 0
let nativeSearchCalls = 0
let currentToolName
const requests = []
const server = createServer((req, res) => {
let raw = ''
req.on('data', chunk => { raw += chunk })
req.on('end', () => {
let body
try { body = JSON.parse(raw) } catch { body = {} }
if (!req.url.startsWith('/v1/messages') || req.url.includes('count_tokens')) {
res.writeHead(req.url.includes('count_tokens') ? 200 : 404, { 'content-type': 'application/json' })
return res.end(req.url.includes('count_tokens') ? '{"input_tokens":1}' : '{}')
}
if ((body.tools ?? []).some(t => t.type?.startsWith('web_search'))) {
nativeSearchCalls++
res.writeHead(403, { 'content-type': 'application/json' })
return res.end(JSON.stringify({ type: 'error', error: { type: 'permission_error', message: 'Mock gateway refuses Claude native search child calls' } }))
}
if (body.max_tokens !== 1) mainCalls++
const tool = (body.tools ?? []).find(t => /^mcp__geek2api_search_[a-f0-9]+__web_search$/u.test(t.name ?? ''))
requests.push({ mode, hasBridge: Boolean(tool), hasNativeSearch: (body.tools ?? []).some(t => t.name === 'WebSearch'), officialIdentity: Array.isArray(body.system) && body.system.some(b => b.text?.startsWith('You are Claude Code, Anthropic\'s official CLI')) })
const callSearch = mainCalls === 1 && body.max_tokens !== 1 && tool !== undefined
if (tool !== undefined) currentToolName = tool.name
const result = callSearch
? { type: 'tool_use', id: 'tool_mcp_check', name: tool.name, input: { query: 'latest Node.js release', max_results: 2 } }
: { type: 'text', text: tool === undefined ? 'bridge missing' : 'MCP search completed.' }
const stop = callSearch ? 'tool_use' : 'end_turn'
const message = { id: 'msg_mcp_check', type: 'message', role: 'assistant', model: body.model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 1 } }
if (!body.stream) {
res.writeHead(200, { 'content-type': 'application/json' })
return res.end(JSON.stringify({ ...message, content: [result], stop_reason: stop }))
}
res.writeHead(200, { 'content-type': 'text/event-stream' })
const event = (type, data) => res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`)
event('message_start', { message })
event('content_block_start', { index: 0, content_block: callSearch ? { ...result, input: {} } : { type: 'text', text: '' } })
event('content_block_delta', { index: 0, delta: callSearch ? { type: 'input_json_delta', partial_json: JSON.stringify(result.input) } : { type: 'text_delta', text: result.text } })
event('content_block_stop', { index: 0 })
event('message_delta', { delta: { stop_reason: stop, stop_sequence: null }, usage: { output_tokens: 1 } })
event('message_stop', {})
res.end()
})
})
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
const baseUrl = `http://127.0.0.1:${server.address().port}`
try {
for (const variant of ['read-only', 'edit', 'full']) {
mode = variant
mainCalls = 0
const before = searchCalls
let configPath
const useLiveSearch = live && mode === 'read-only'
const runner = createClaudeRunner({
binary,
configDir: join(directory, `config-${mode}`),
resolveCredential: async () => ({ baseUrl, token: 'sk-dummy-cli-not-a-real-key', label: 'mock Claude gateway' }),
createSearchBridge: async ({ signal }) => {
const bridge = await createClaudeSearchBridge({
signal,
backend: () => backend,
sanitize: text => secret === undefined ? text : text.split(secret).join('[redacted]'),
search: async (request, searchSignal) => {
searchCalls++
let result
try {
result = useLiveSearch ? await provider.search(request, searchSignal) : { content: 'Mock search result', sources: [{ url: 'https://nodejs.org/en/blog/release', title: 'Node.js releases' }] }
} catch (error) {
// Diagnostics stay in this host-side test only; remove the stored
// key even if a gateway/transport happens to echo it.
const detail = String(error?.message ?? error)
console.error(` ${backend} backend failure (${error?.code ?? 'error'}): ${secret === undefined ? detail.slice(0, 300) : detail.split(secret).join('[redacted]').slice(0, 300)}`)
throw error
}
assert.ok(result.sources.length > 0, 'the selected search backend returned no sources')
console.log(` ${useLiveSearch ? `live ${backend}` : 'mock search'}: ${result.sources.length} sources`)
return result
},
})
configPath = bridge.configPath
return bridge
},
timeoutMs: 120_000,
})
const errors = []
try {
for await (const event of runner.stream({ prompt: 'Search the web using the provided Geek2API MCP tool and cite the sources. Do not use shell commands or other tools.', mode, model: 'claude-opus-5-5', cwd: directory })) {
if (event.type === 'tool-error') errors.push(event.text)
}
assert.equal(searchCalls - before, 1, `${mode}: actual CLI never called MCP search`)
assert.deepEqual(errors, [], `${mode}: actual MCP/permission error`)
assert.ok(requests.filter(r => r.mode === mode).every(r => !r.hasNativeSearch && r.officialIdentity), `${mode}: native search present or CLI identity replaced`)
await assert.rejects(readFile(configPath), e => e.code === 'ENOENT')
console.log(`${mode}: real CLI MCP call OK; native WebSearch absent; official identity preserved; config cleaned (${currentToolName})`)
} finally { await runner.close() }
}
assert.equal(nativeSearchCalls, 0)
console.log('PASS: no Claude native-search subrequest was made. Claude model responses above were mocked, not live.')
} finally {
server.closeAllConnections()
await new Promise(resolve => server.close(resolve))
// Only delete the private directory this script created and verified.
assert.equal(await realpath(directory), ownedDirectory)
await rm(directory, { recursive: true, force: true })
}
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env node
/**
* Live check for the built plugin.
*
* Drives the *built* host bundle against the real Geek2API gateway with the
* key already stored in the DSH credentials file, through the same route the
* plugin registers (`createRouteAdapter` over a key chooser and group reader):
* it reads the balance and the key's groups, streams one answer per HTTP
* model, rehearses rotation with a deliberately invalid key in front of the
* real one, and reports how the host adapter classifies a key rejection — the
* classification the harness's retry policy reads.
*
* It prints no key material, only a masked tail. Run it from the repository
* root after `pnpm run build`:
*
* node scripts/live-check.mjs [--with-cli] [--with-search] [--with-vision] [--key-label LABEL]
*
* `--with-cli` also runs each CLI-backed Claude model through the local
* Claude Code CLI; `--with-search` runs one web search per backend. Both
* spend more quota than the default run.
* `--with-vision` checks DeepSeek with two color images through the host's
* attachment service seam; the prompt does not disclose the colors.
*/
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { readStoredKey } from './stored-key.mjs'
import { createVisionFixture } from './vision-fixture.mjs'
import {
CLI_BACKED_MODEL_IDS,
CLAUDE_CLI_MODES,
Geek2APIKeyRing,
SEARCH_BACKENDS,
createBalanceReader,
createClaudeCliAdapter,
createClaudeRunner,
createGroupReader,
createKeyChooser,
createGeek2APIRpc,
createGeek2APISearchProvider,
createHostPool,
createRouteAdapter,
} from '../lib/index.js'
const PROVIDER = 'geek2api'
const SESSION_ID = 'live-check-session'
const HOSTS = createHostPool()
const HTTP_MODELS = ['deepseek-v4.1-flash', 'gpt-6.1-sol', 'gpt-6-astra', 'grok-4.6', 'claude-opus-5-5', 'gemini-3.8-flash', 'glm-5.3']
/** In-memory stand-in for the DSH credential-record service. */
function fakeCredentials() {
let record
let chain = Promise.resolve()
return {
async readRecord() {
return record
},
modifyRecord(_key, mutate) {
const run = chain.then(async () => {
const next = await mutate(record)
if (next !== undefined) record = next
return record
})
chain = run.then(() => undefined, () => undefined)
return run
},
}
}
const logger = {
warn: (format, ...args) => console.log(` ! ${format}`, ...args),
info: (format, ...args) => console.log(` · ${format}`, ...args),
}
/** A group reader with no evidence, so key choice falls back to ring order. */
const NO_GROUPS = Object.freeze({
read: async () => ({ keys: [], descriptions: {}, requirements: {}, fetchedAt: Date.now() }),
hasReading: () => true,
covers: () => undefined,
groupsOf: () => undefined,
requiredGroups: () => undefined,
})
/** The plugin's composition, around one ring. */
async function routeWith(entries, { groupReader, resolveAttachments } = {}) {
const ring = new Geek2APIKeyRing(fakeCredentials())
for (const [key, label] of entries) await ring.add(key, label)
const groups = groupReader ?? createGroupReader({ listKeys: () => ring.secrets(), hosts: HOSTS })
const keys = createKeyChooser({ ring, groups, logger })
const adapter = createRouteAdapter({ ring, keys, hosts: HOSTS, fallbackSessionId: SESSION_ID, resolveAttachments })
return { ring, groups, keys, adapter }
}
/** One turn through an adapter; the finish reason and the streamed text. */
async function turn(adapter, model, text = 'Reply with exactly: ok', { image } = {}) {
const prepared = await adapter.prepareCall(PROVIDER, model)
let answer = ''
let finish
for await (const chunk of prepared.stream({
provider: PROVIDER,
model,
sessionId: SESSION_ID,
reasoningEffort: 'high',
maxTokens: 2048,
messages: [createUserMessage({ content: [{ type: 'text', text }, ...(image === undefined ? [] : [image])], source: { kind: 'user' } })],
})) {
if (chunk.type === 'text-delta') answer += chunk.text
if (chunk.type === 'finish') finish = chunk.reason
}
return { answer: answer.trim(), finish }
}
const describe = ({ answer, finish }) => (finish?.kind === 'stop'
? `→ ${answer.slice(0, 60)}`
: `→ FAILED: ${String(finish?.failure?.message ?? 'no finish').slice(0, 140)}`)
async function main() {
const labelIndex = process.argv.indexOf('--key-label')
const label = labelIndex < 0 ? undefined : process.argv[labelIndex + 1]
if (labelIndex >= 0 && (label === undefined || label.startsWith('--'))) throw new Error('--key-label needs a key label')
const key = await readStoredKey({ label })
const mask = text => String(text).split(key).join(`…${key.slice(-4)}`)
console.log(`stored key: …${key.slice(-4)} (${key.length} chars)\n`)
let visionFixture
const route = await routeWith([[key, 'live-check']], { resolveAttachments: () => visionFixture?.attachments })
console.log('1) balance')
const balance = createBalanceReader({ listKeys: () => route.ring.secrets(), hosts: HOSTS })
const value = await balance.read()
const row = value.keys[0]
console.log(` account: remaining $${value.account.remainingUsd} of $${value.account.hardLimitUsd} (used $${value.account.totalUsageUsd})`)
console.log(` key "${row.label}": available $${row.usage?.availableUsd} / limit $${row.usage?.limitUsd} (${row.usage?.resetPeriod ?? 'no period'})${row.error === undefined ? '' : ` ERROR ${row.error}`}\n`)
console.log('2) groups')
const groups = await route.groups.read()
const entry = groups.keys[0]
console.log(` groups: ${entry.groups?.join(', ') ?? `unread (${entry.error})`}`)
console.log(` reaches: ${Object.entries(entry.coverage).map(([id, ok]) => `${ok ? '✓' : '✗'} ${id}`).join(' ')}`)
console.log(` projection carries key material: ${JSON.stringify(groups).includes(key) ? 'YES (bug)' : 'no'}\n`)
console.log('3) one answer per HTTP model, through the registered route')
for (const id of HTTP_MODELS) {
console.log(` ${id.padEnd(16)} ${mask(describe(await turn(route.adapter, id)))}`)
}
console.log('\n4) an invalid key in front of the real one')
const passOver = await routeWith([['sk-invalid-live-check-0001', 'deliberately invalid'], [key, 'real key']])
console.log(` with group evidence (the reader saw the gateway reject it): ${mask(describe(await turn(passOver.adapter, 'deepseek-v4.1-flash')))}`)
console.log(' without group evidence, the rotation itself:')
const rotation = await routeWith([['sk-invalid-live-check-0001', 'deliberately invalid'], [key, 'real key']], { groupReader: NO_GROUPS })
for (let attempt = 1; attempt <= 2; attempt += 1) {
const active = await rotation.ring.activeKey()
console.log(` attempt ${attempt}: using "${active.label}" ${mask(describe(await turn(rotation.adapter, 'deepseek-v4.1-flash')))}`)
// The rotation lands asynchronously after the failed stream.
await new Promise(resolve => setTimeout(resolve, 200))
}
const state = await rotation.ring.list()
console.log(` ring now: ${state.keys.map(item => `${item.label}=${item.disabled ? `disabled(${item.disabledReason})` : 'usable'}`).join(', ')}`)
console.log('\n5) how the host adapter classifies a rejected key (what the retry policy reads)')
const rejected = await routeWith([['sk-invalid-live-check-0002', 'rejected by the gateway']])
const { finish } = await turn(rejected.adapter, 'deepseek-v4.1-flash')
console.log(` finish: ${mask(JSON.stringify(finish)?.slice(0, 200))}`)
if (process.argv.includes('--with-cli')) {
console.log('\n6) the model-shaped bridge: choosing a Claude model runs the CLI')
const bridged = createClaudeCliAdapter({
inner: route.adapter,
runner: createClaudeRunner({
resolveCredential: async ({ model } = {}) => {
const choice = await route.keys.forRun(model ?? 'claude-opus-5-5')
const { key: token, ...described } = choice
return { ...described, baseUrl: HOSTS.current(), token }
},
}),
resolveMode: () => 'read-only',
resolveCwd: () => process.cwd(),
})
for (const id of CLI_BACKED_MODEL_IDS) {
const started = Date.now()
const result = await turn(bridged, id, 'Reply with exactly: cli-bridge-ok')
console.log(` ${id.padEnd(18)} ${mask(describe(result))} (${Math.round((Date.now() - started) / 1000)}s)`)
}
} else {
console.log('\n6) model-shaped bridge skipped (pass --with-cli to run the real CLI)')
console.log(` CLI-backed models: ${CLI_BACKED_MODEL_IDS.join(', ')} · modes: ${Object.keys(CLAUDE_CLI_MODES).join(', ')}`)
}
if (process.argv.includes('--with-search')) {
console.log('\n7) one web search per backend')
for (const backend of SEARCH_BACKENDS) {
const provider = createGeek2APISearchProvider({ ring: route.ring, hosts: HOSTS, backend: () => backend, covers: route.keys.covers, onKeyFailure: route.keys.onKeyFailure })
const started = Date.now()
try {
const found = await provider.search({ query: 'latest Node.js release', maxResults: 8 })
console.log(` ${backend.padEnd(9)} → ${found.sources.length} sources in ${((Date.now() - started) / 1000).toFixed(1)}s; first: ${found.sources[0]?.url ?? '—'}`)
} catch (error) {
console.log(` ${backend.padEnd(9)} → ${error.code}: ${mask(error.message).slice(0, 200)}`)
}
}
} else {
console.log('\n7) web search skipped (pass --with-search to run one search per backend)')
}
console.log('\n8) what the settings panel receives over RPC')
const rpcRing = new Geek2APIKeyRing(fakeCredentials())
const handler = createGeek2APIRpc({
ring: rpcRing,
balance: createBalanceReader({ listKeys: () => rpcRing.secrets(), hosts: HOSTS }),
groups: createGroupReader({ listKeys: () => rpcRing.secrets(), hosts: HOSTS }),
hosts: HOSTS,
preference: { writable: false, set: async () => {} },
})
const added = await handler('keys/add', { key, label: 'rpc check' })
console.log(` keys/add ok=${added.ok}; status=${JSON.stringify(added.value.keys)}`)
const projection = await handler('balance')
const active = projection.value.keys.find(item => item.id === projection.value.activeId)
console.log(` activeId=${projection.value.activeId} label=${active?.label} available=$${active?.usage?.availableUsd} reset=${active?.usage?.resetPeriod}`)
const groupProjection = await handler('groups')
console.log(` groups ok=${groupProjection.ok}: ${groupProjection.value?.keys?.[0]?.groups?.join(', ')}`)
console.log(` projections carry key material: ${JSON.stringify([projection, groupProjection]).includes(key) ? 'YES (bug)' : 'no'}`)
if (process.argv.includes('--with-vision')) {
console.log('\n9) DeepSeek identifies images through the registered route')
for (const color of ['red', 'blue']) {
visionFixture = createVisionFixture(color)
const result = await turn(route.adapter, 'deepseek-v4.1-flash',
'What is the dominant color in this image? Reply with exactly one lowercase English color word.',
{ image: visionFixture.block })
console.log(` ${color} image ${mask(describe(result))}`)
if (result.finish?.kind !== 'stop' || result.answer.toLowerCase() !== color || visionFixture.reads.length !== 1) {
throw new Error(`DeepSeek vision check failed for the ${color} image`)
}
}
}
}
await main()
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env node
/**
* Multi-key smoke check for the built plugin.
*
* Loads several keys from a JSON file (`{ "label": "sk-…" }`), never printing
* more than a masked tail, and drives the built host bundle against the real
* gateway through the plugin's own composition: host pool, key ring, group
* reader, key chooser, and route adapter. It reads each key's balance and
* model coverage, then streams one short answer per catalog model on whatever
* key the chooser picks for it.
*
* node scripts/smoke.mjs <keys.json> [model …]
*/
import { readFile } from 'node:fs/promises'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import {
GEEK2API_MODEL_IDS,
Geek2APIKeyRing,
createBalanceReader,
createGroupReader,
createHostPool,
createKeyChooser,
createRouteAdapter,
} from '../lib/index.js'
const PROVIDER = 'geek2api'
const SESSION_ID = 'smoke-session'
function fakeCredentials() {
let record
let chain = Promise.resolve()
return {
async readRecord() {
return record
},
modifyRecord(_key, mutate) {
const run = chain.then(async () => {
const next = await mutate(record)
if (next !== undefined) record = next
return record
})
chain = run.then(() => undefined, () => undefined)
return run
},
}
}
const used = []
const logger = {
warn: (format, ...args) => console.log(` ! ${format}`, ...args),
info: (format, ...args) => used.push([format, ...args]),
}
async function turn(adapter, model) {
const prepared = await adapter.prepareCall(PROVIDER, model)
let answer = ''
let finish
const started = Date.now()
for await (const chunk of prepared.stream({
provider: PROVIDER,
model,
sessionId: SESSION_ID,
reasoningEffort: 'low',
maxTokens: 1024,
messages: [createUserMessage({ content: [{ type: 'text', text: 'Reply with exactly: ok' }], source: { kind: 'user' } })],
})) {
if (chunk.type === 'text-delta') answer += chunk.text
if (chunk.type === 'finish') finish = chunk.reason
}
return { answer: answer.trim(), finish, ms: Date.now() - started }
}
async function main() {
const [file, ...models] = process.argv.slice(2)
if (file === undefined) throw new Error('usage: node scripts/smoke.mjs <keys.json> [model …]')
const keys = JSON.parse(await readFile(file, 'utf8'))
const hosts = createHostPool({ logger })
await hosts.probe({ force: true })
console.log('hosts:', hosts.status().map(entry => `${entry.host.replace('https://', '')}${entry.latencyMs === undefined ? ' ✕' : ` ${entry.latencyMs}ms`}`).join(', '))
const ring = new Geek2APIKeyRing(fakeCredentials())
for (const [label, key] of Object.entries(keys)) await ring.add(key, label)
const groups = createGroupReader({ listKeys: () => ring.secrets(), hosts })
const balance = createBalanceReader({ listKeys: () => ring.secrets(), hosts })
const chooser = createKeyChooser({ ring, groups, logger })
const adapter = createRouteAdapter({ ring, keys: chooser, hosts, fallbackSessionId: SESSION_ID })
const [reading, money] = await Promise.all([groups.read({ force: true }), balance.read({ force: true })])
const state = await ring.list()
for (const entry of state.keys) {
const g = reading.keys.find(item => item.id === entry.id)
const b = money.keys.find(item => item.id === entry.id)
const reach = Object.entries(g?.coverage ?? {}).filter(([, ok]) => ok).map(([id]) => id)
const usage = b?.usage
console.log(`key ${entry.label}: ${usage === undefined ? `balance ✕ ${b?.error ?? ''}` : `${usage.mode} $${usage.availableUsd ?? '?'} today $${usage.todayUsd ?? '?'}`}`
+ ` | groups ${g?.groups?.join(',') ?? '—'} | reaches ${reach.join(', ') || (g?.error ?? 'none')}`)
}
for (const model of models.length > 0 ? models : GEEK2API_MODEL_IDS) {
used.length = 0
try {
const result = await turn(adapter, model)
const via = used.find(item => String(item[0]).includes('this request uses key'))
const keyLabel = via === undefined ? state.keys.find(entry => entry.active)?.label : state.keys.find(entry => entry.id === via[3])?.label
console.log(`${model.padEnd(28)} ${result.finish?.kind === 'stop' ? `ok "${result.answer.slice(0, 40)}"` : `FAIL ${String(result.finish?.failure?.message ?? 'no finish').slice(0, 220)}`} [key ${keyLabel}, ${result.ms}ms]`)
} catch (error) {
console.log(`${model.padEnd(28)} THREW ${String(error?.message ?? error).slice(0, 220)}`)
}
}
}
main().catch(error => {
console.error(error)
process.exitCode = 1
})
+34
View File
@@ -0,0 +1,34 @@
/** Read only the plugin-owned key record; never use a reference or ambient key. */
import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { parseDocument } from 'yaml'
import { Geek2APIKeyRing } from '../lib/index.js'
export async function readStoredKey({
filePath = join(process.env.DSH_HOME || join(homedir(), '.dsh'), '.credentials.yaml'),
label,
} = {}) {
let record
try {
const doc = parseDocument(readFileSync(filePath, 'utf8'), { prettyErrors: false, logLevel: 'silent' })
if (doc.errors.length) throw new Error('invalid credential document')
record = doc.toJS()?.records?.['geek2api/keys']
} catch {
// YAML diagnostics can quote source lines containing secrets.
throw new Error('Geek2API plugin credentials could not be read safely')
}
const ring = new Geek2APIKeyRing({
readRecord: async id => id === 'geek2api/keys' ? record : undefined,
modifyRecord: async () => { throw new Error('Geek2API live checks cannot change stored credentials') },
})
if (label !== undefined) {
const matches = (await ring.secrets()).filter(entry => entry.label === label && !entry.disabled)
if (matches.length !== 1) throw new Error('Geek2API live check needs one usable key with that label')
return matches[0].key
}
const active = await ring.activeKey()
if (active === undefined) throw new Error('Geek2API live check needs a usable key added under Settings → Geek2API')
return active.key
}
+30
View File
@@ -0,0 +1,30 @@
import { createHash } from 'node:crypto'
/** Plain 512×512 PNGs; no filename or prompt reveals their color to the model. */
const PNGS = Object.freeze({
red: 'iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAIAAAB7GkOtAAAHmklEQVR4nO3OQQ0AMBAEofVvupUxjyNBAHsbAAf1AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AIPEBCh87xVEsvp4AAAAASUVORK5CYII=',
blue: 'iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAIAAAB7GkOtAAAHmklEQVR4nO3OQQ0AMBAEofVvupUxjyNBANseACf1AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AINEPAEj0AwAS/QCARD8AIPABkog7xbCQ11cAAAAASUVORK5CYII=',
})
/** The durable attachment service seam consumed by the real host adapter. */
export function createVisionFixture(color) {
if (!Object.hasOwn(PNGS, color)) throw new Error('Unknown vision fixture')
const data = Buffer.from(PNGS[color], 'base64')
const attachment = Object.freeze({
attachmentId: `sha256:${createHash('sha256').update(data).digest('hex')}`,
mediaType: 'image/png', bytes: data.length, width: 512, height: 512,
})
const reads = []
return {
data,
block: { type: 'image', attachment },
reads,
attachments: {
async readImageRequest(ref) {
if (ref.attachmentId !== attachment.attachmentId) throw new Error('Unknown image attachment')
reads.push(ref.attachmentId)
return { data, mediaType: attachment.mediaType, bytes: data.length, width: 512, height: 512 }
},
},
}
}