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:
commit
ed5154c042
94 files changed
+28617
No files matched your search
@@ -0,0 +1,224 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { createBalanceReader, parseKeyUsage } from '../src/balance.js'
|
||||
import { fixedHostPool } from './helpers.mjs'
|
||||
|
||||
/** The wallet shape sub2api's `/v1/usage` answers for a balance-mode key. */
|
||||
const WALLET_USAGE = {
|
||||
mode: 'unrestricted',
|
||||
isValid: true,
|
||||
planName: '钱包余额',
|
||||
remaining: 42.5,
|
||||
unit: 'USD',
|
||||
balance: 42.5,
|
||||
usage: {
|
||||
today: { requests: 3, actual_cost: 0.12 },
|
||||
total: { requests: 90, actual_cost: 17.25 },
|
||||
},
|
||||
}
|
||||
|
||||
test('parses the wallet shape: the shared balance, with lifetime and today spend', () => {
|
||||
const usage = parseKeyUsage(WALLET_USAGE)
|
||||
assert.equal(usage.mode, 'wallet')
|
||||
assert.equal(usage.unlimitedQuota, false)
|
||||
assert.equal(usage.availableUsd, 42.5)
|
||||
assert.equal(usage.usedUsd, 17.25)
|
||||
assert.equal(usage.todayUsd, 0.12)
|
||||
assert.equal(usage.todayRequests, 3)
|
||||
assert.equal(usage.planName, '钱包余额')
|
||||
assert.equal('limitUsd' in usage, false)
|
||||
})
|
||||
|
||||
test('parses the subscription shape, limited by its tightest period', () => {
|
||||
const usage = parseKeyUsage({
|
||||
mode: 'unrestricted',
|
||||
isValid: true,
|
||||
planName: 'Plus(GPT)',
|
||||
remaining: 3,
|
||||
subscription: {
|
||||
daily_usage_usd: 7,
|
||||
daily_limit_usd: 10,
|
||||
weekly_usage_usd: 20,
|
||||
weekly_limit_usd: 50,
|
||||
monthly_usage_usd: 20,
|
||||
monthly_limit_usd: null,
|
||||
expires_at: '2026-11-01T00:00:00Z',
|
||||
},
|
||||
})
|
||||
assert.equal(usage.mode, 'subscription')
|
||||
assert.equal(usage.planName, 'Plus(GPT)')
|
||||
assert.equal(usage.resetPeriod, 'daily')
|
||||
assert.equal(usage.limitUsd, 10)
|
||||
assert.equal(usage.usedUsd, 7)
|
||||
assert.equal(usage.availableUsd, 3)
|
||||
assert.equal(usage.expiresAt, Date.parse('2026-11-01T00:00:00Z'))
|
||||
assert.equal(usage.unlimitedQuota, false)
|
||||
|
||||
const unlimited = parseKeyUsage({ mode: 'unrestricted', remaining: 0, subscription: {} })
|
||||
assert.equal(unlimited.unlimitedQuota, true)
|
||||
})
|
||||
|
||||
test('parses the key-quota shape with its rate windows and expiry', () => {
|
||||
const usage = parseKeyUsage({
|
||||
mode: 'quota_limited',
|
||||
isValid: true,
|
||||
status: 'active',
|
||||
quota: { limit: 500, used: 125.5, remaining: 374.5, unit: 'USD' },
|
||||
remaining: 374.5,
|
||||
rate_limits: [{ window: '5h', limit: 20, used: 5, remaining: 15, reset_at: '2026-10-14T12:00:00Z' }],
|
||||
expires_at: '2027-01-01T00:00:00Z',
|
||||
})
|
||||
assert.equal(usage.mode, 'quota')
|
||||
assert.equal(usage.limitUsd, 500)
|
||||
assert.equal(usage.usedUsd, 125.5)
|
||||
assert.equal(usage.availableUsd, 374.5)
|
||||
assert.equal('status' in usage, false, 'an active status is not worth reporting')
|
||||
assert.deepEqual(usage.rateLimits, [{ window: '5h', limitUsd: 20, usedUsd: 5, remainingUsd: 15, resetAt: Date.parse('2026-10-14T12:00:00Z') }])
|
||||
assert.equal(usage.expiresAt, Date.parse('2027-01-01T00:00:00Z'))
|
||||
|
||||
const exhausted = parseKeyUsage({ mode: 'quota_limited', isValid: true, status: 'quota_exhausted' })
|
||||
assert.equal(exhausted.status, 'quota_exhausted')
|
||||
assert.equal(exhausted.unlimitedQuota, true, 'a rate-limit-only key has no total cap')
|
||||
})
|
||||
|
||||
test('an unknown shape is unrecognized', () => {
|
||||
assert.equal(parseKeyUsage({ nothing: true }), undefined)
|
||||
assert.equal(parseKeyUsage(null), undefined)
|
||||
assert.equal(parseKeyUsage({ mode: 'unrestricted' }), undefined)
|
||||
})
|
||||
|
||||
test('carries the account reference and key name when the gateway reports them', () => {
|
||||
const usage = parseKeyUsage({ ...WALLET_USAGE, account_ref: 'acct-7', key: { name: 'laptop' } })
|
||||
assert.equal(usage.accountRef, 'acct-7')
|
||||
assert.equal(usage.keyName, 'laptop')
|
||||
})
|
||||
|
||||
function jsonResponse(payload, status = 200) {
|
||||
return { ok: status >= 200 && status < 300, status, json: async () => payload }
|
||||
}
|
||||
|
||||
function routedFetch(routes) {
|
||||
const calls = []
|
||||
const fetchImpl = async (url, options) => {
|
||||
calls.push(url)
|
||||
const route = routes.find(candidate => url.startsWith(candidate.prefix))
|
||||
if (route === undefined) throw new Error(`unrouted ${url}`)
|
||||
if (typeof route.reply === 'function') return route.reply(url, options)
|
||||
return jsonResponse(route.reply, route.status ?? 200)
|
||||
}
|
||||
return { fetchImpl, calls }
|
||||
}
|
||||
|
||||
const KEYS = [{ id: 'a', label: 'primary', key: 'sk-aaaaaaaaaaaaaaaa', disabled: false }]
|
||||
|
||||
test('reads each key from /v1/usage on the preferred host with its own bearer token', async () => {
|
||||
const seen = []
|
||||
const { fetchImpl, calls } = routedFetch([{
|
||||
prefix: 'https://h1.example/v1/usage',
|
||||
reply: (_url, options) => {
|
||||
seen.push(options.headers.Authorization)
|
||||
assert.equal(options.redirect, 'error')
|
||||
return jsonResponse(WALLET_USAGE)
|
||||
},
|
||||
}])
|
||||
const reader = createBalanceReader({ listKeys: async () => KEYS, hosts: await fixedHostPool(), fetchImpl })
|
||||
const value = await reader.read()
|
||||
assert.equal(value.keys[0].usage.availableUsd, 42.5)
|
||||
assert.deepEqual(calls, ['https://h1.example/v1/usage?lite=1'])
|
||||
assert.deepEqual(seen, ['Bearer sk-aaaaaaaaaaaaaaaa'])
|
||||
assert.ok(Array.isArray(value.hosts))
|
||||
})
|
||||
|
||||
test('a host that never answers is set aside and the next host serves the read', async () => {
|
||||
const dnsFailure = Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error('getaddrinfo ENOTFOUND h1.example'), { code: 'ENOTFOUND' }) })
|
||||
const { fetchImpl, calls } = routedFetch([
|
||||
{ prefix: 'https://h1.example/', reply: () => { throw dnsFailure } },
|
||||
{ prefix: 'https://h2.example/v1/usage', reply: WALLET_USAGE },
|
||||
])
|
||||
const hosts = await fixedHostPool()
|
||||
const reader = createBalanceReader({ listKeys: async () => KEYS, hosts, fetchImpl })
|
||||
assert.equal((await reader.read()).keys[0].usage.availableUsd, 42.5)
|
||||
assert.deepEqual(calls, ['https://h1.example/v1/usage?lite=1', 'https://h2.example/v1/usage?lite=1'])
|
||||
assert.equal(hosts.order()[0], 'https://h2.example')
|
||||
})
|
||||
|
||||
test('a rejected key reports its own error, with the gateway message, without failing the read', async () => {
|
||||
const keys = [...KEYS, { id: 'b', label: 'second', key: 'sk-bbbbbbbbbbbbbbbb', disabled: false }]
|
||||
const { fetchImpl, calls } = routedFetch([{
|
||||
prefix: 'https://h1.example/v1/usage',
|
||||
reply: (_url, options) => (String(options.headers.Authorization).includes('sk-a')
|
||||
? jsonResponse({ error: { message: 'Invalid API key' } }, 401)
|
||||
: jsonResponse({ error: { message: 'API Key 所属分组已删除' } }, 403)),
|
||||
}])
|
||||
const reader = createBalanceReader({ listKeys: async () => keys, hosts: await fixedHostPool(), fetchImpl })
|
||||
const value = await reader.read()
|
||||
assert.equal(value.keys[0].usage, undefined)
|
||||
assert.match(value.keys[0].error, /rejected \(401\): Invalid API key/u)
|
||||
assert.match(value.keys[1].error, /refused this key \(403\): API Key 所属分组已删除/u)
|
||||
assert.equal(calls.length, 2, 'an HTTP refusal is an answer, not a reason to try another host')
|
||||
})
|
||||
|
||||
test('an unrecognized payload is reported per key', async () => {
|
||||
const { fetchImpl } = routedFetch([{ prefix: 'https://h1.example/v1/usage', reply: { hello: 1 } }])
|
||||
const reader = createBalanceReader({ listKeys: async () => KEYS, hosts: await fixedHostPool(), fetchImpl })
|
||||
assert.match((await reader.read()).keys[0].error, /unrecognized usage payload/u)
|
||||
})
|
||||
|
||||
test('a read without keys returns an empty list', async () => {
|
||||
const reader = createBalanceReader({ listKeys: async () => [], hosts: await fixedHostPool(), fetchImpl: routedFetch([]).fetchImpl })
|
||||
assert.deepEqual((await reader.read()).keys, [])
|
||||
})
|
||||
|
||||
test('caches a read, shares one in flight, and forgets on invalidate', async () => {
|
||||
let calls = 0
|
||||
const { fetchImpl } = routedFetch([{
|
||||
prefix: 'https://h1.example/v1/usage',
|
||||
reply: () => {
|
||||
calls += 1
|
||||
return jsonResponse(WALLET_USAGE)
|
||||
},
|
||||
}])
|
||||
const reader = createBalanceReader({ listKeys: async () => KEYS, hosts: await fixedHostPool(), fetchImpl, now: () => 1000 })
|
||||
const [first, second] = await Promise.all([reader.read(), reader.read()])
|
||||
assert.equal(calls, 1)
|
||||
assert.equal(first.fetchedAt, second.fetchedAt)
|
||||
await reader.read()
|
||||
assert.equal(calls, 1)
|
||||
reader.invalidate()
|
||||
await reader.read()
|
||||
assert.equal(calls, 2)
|
||||
})
|
||||
|
||||
test('a failed read keeps the last balance each key reported, marked stale', async () => {
|
||||
let up = true
|
||||
let clock = 1_000
|
||||
const { fetchImpl } = routedFetch([{
|
||||
prefix: 'https://h',
|
||||
reply: () => (up ? jsonResponse(WALLET_USAGE) : jsonResponse({ error: 'busy' }, 429)),
|
||||
}])
|
||||
let keys = KEYS
|
||||
const reader = createBalanceReader({ listKeys: async () => keys, hosts: await fixedHostPool(), fetchImpl, now: () => clock })
|
||||
const first = await reader.read()
|
||||
assert.equal(first.keys[0].stale, undefined)
|
||||
|
||||
up = false
|
||||
clock = 99_000
|
||||
const second = await reader.read({ force: true })
|
||||
assert.equal(second.keys[0].usage.availableUsd, 42.5, 'the last good balance stays visible')
|
||||
assert.equal(second.keys[0].stale.fetchedAt, 1_000)
|
||||
assert.match(second.keys[0].stale.error, /429/u)
|
||||
assert.equal(second.keys[0].error, undefined)
|
||||
|
||||
// A key that is no longer stored takes its last balance with it.
|
||||
keys = [{ id: 'b', label: 'other', key: 'sk-bbbbbbbbbbbbbbbb', disabled: false }]
|
||||
const third = await reader.read({ force: true })
|
||||
assert.equal(third.keys[0].usage, undefined)
|
||||
assert.equal(third.keys[0].stale, undefined)
|
||||
assert.ok(third.keys[0].error)
|
||||
})
|
||||
|
||||
test('requires a key listing and a host pool', () => {
|
||||
assert.throws(() => createBalanceReader({ hosts: {} }), /listKeys/u)
|
||||
assert.throws(() => createBalanceReader({ listKeys: async () => [] }), /host pool/u)
|
||||
})
|
||||
@@ -0,0 +1,110 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { getSupportedThinkingLevels } from '@earendil-works/pi-ai'
|
||||
|
||||
import { GEEK2API_MODELS, GEEK2API_MODEL_IDS, modelForHost } from '../src/catalog.js'
|
||||
import { DEFAULT_API_HOST, DEFAULT_REASONING_LEVEL, PROVIDER } from '../src/constants.js'
|
||||
|
||||
const byId = id => GEEK2API_MODELS.find(model => model.id === id)
|
||||
const CLAUDE = ['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-4-5-20251001']
|
||||
const RESPONSES = ['gpt-6.1-sol', 'gpt-6-astra', 'gpt-6-luna', 'grok-4.6', 'grok-4.7']
|
||||
const COMPLETIONS = ['deepseek-v4.1-flash', 'deepseek-v4-pro', 'gemini-3.8-flash', 'glm-5.3', 'kimi-k3']
|
||||
|
||||
test('ships the Geek2API catalog, every model on this route', () => {
|
||||
assert.deepEqual([...GEEK2API_MODEL_IDS], [
|
||||
'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-4-5-20251001',
|
||||
'gpt-6.1-sol', 'gpt-6-astra', 'gpt-6-luna',
|
||||
'deepseek-v4.1-flash', 'deepseek-v4-pro',
|
||||
'grok-4.6', 'grok-4.7',
|
||||
'gemini-3.8-flash', 'glm-5.3', 'kimi-k3',
|
||||
])
|
||||
assert.equal(new Set(GEEK2API_MODEL_IDS).size, GEEK2API_MODEL_IDS.length)
|
||||
for (const model of GEEK2API_MODELS) {
|
||||
assert.equal(model.provider, PROVIDER)
|
||||
assert.ok(model.input.includes('text'), model.id)
|
||||
assert.ok(model.contextWindow > 0 && model.maxTokens > 0, model.id)
|
||||
}
|
||||
})
|
||||
|
||||
test('declares image input only where the model takes it', () => {
|
||||
for (const id of ['deepseek-v4-pro', 'glm-5.3']) assert.deepEqual([...byId(id).input], ['text'], id)
|
||||
for (const id of [...CLAUDE, ...RESPONSES, 'deepseek-v4.1-flash', 'gemini-3.8-flash', 'kimi-k3']) {
|
||||
assert.deepEqual([...byId(id).input], ['text', 'image'], id)
|
||||
}
|
||||
})
|
||||
|
||||
test('pins each model to the protocol and base URL the gateway serves', () => {
|
||||
// Anthropic traffic carries no /v1: the Anthropic client appends /v1/messages.
|
||||
for (const id of CLAUDE) {
|
||||
assert.equal(byId(id).api, 'anthropic-messages', id)
|
||||
assert.equal(byId(id).baseUrl, DEFAULT_API_HOST, id)
|
||||
}
|
||||
// OpenAI-style traffic carries /v1 and never an endpoint path.
|
||||
for (const id of RESPONSES) {
|
||||
assert.equal(byId(id).api, 'openai-responses', id)
|
||||
assert.equal(byId(id).baseUrl, `${DEFAULT_API_HOST}/v1`, id)
|
||||
}
|
||||
for (const id of COMPLETIONS) {
|
||||
assert.equal(byId(id).api, 'openai-completions', id)
|
||||
assert.equal(byId(id).baseUrl, `${DEFAULT_API_HOST}/v1`, id)
|
||||
}
|
||||
assert.equal(byId('gpt-6-astra').contextWindow, 1_050_000)
|
||||
assert.equal(byId('grok-4.7').contextWindow, 500_000)
|
||||
assert.equal(byId('grok-4.7').compat.supportsLongCacheRetention, false)
|
||||
assert.equal(byId('grok-4.6').compat.supportsLongCacheRetention, false)
|
||||
})
|
||||
|
||||
test("offers each vendor's documented effort levels", () => {
|
||||
for (const id of ['deepseek-v4.1-flash', 'deepseek-v4-pro']) {
|
||||
assert.deepEqual(getSupportedThinkingLevels(byId(id)), ['off', 'low', 'high', 'max'], id)
|
||||
}
|
||||
for (const id of ['gpt-6.1-sol', 'gpt-6-astra', 'gpt-6-luna', 'claude-opus-5-5', 'claude-sonnet-5-5']) {
|
||||
assert.deepEqual(getSupportedThinkingLevels(byId(id)), ['low', 'medium', 'high', 'xhigh', 'max'], id)
|
||||
}
|
||||
assert.deepEqual(getSupportedThinkingLevels(byId('claude-haiku-4-5-20251001')), ['low', 'medium', 'high'])
|
||||
for (const id of ['grok-4.6', 'grok-4.7']) {
|
||||
assert.deepEqual(getSupportedThinkingLevels(byId(id)), ['low', 'medium', 'high', 'xhigh'], id)
|
||||
}
|
||||
// The gateway passes no reasoning control through for these: only `off`.
|
||||
for (const id of ['gemini-3.8-flash', 'glm-5.3', 'kimi-k3']) {
|
||||
assert.equal(byId(id).reasoning, false, id)
|
||||
assert.deepEqual(getSupportedThinkingLevels(byId(id)), ['off'], id)
|
||||
}
|
||||
})
|
||||
|
||||
test('every reasoning model accepts the route default effort', () => {
|
||||
for (const model of GEEK2API_MODELS.filter(item => item.reasoning)) {
|
||||
assert.ok(getSupportedThinkingLevels(model).includes(DEFAULT_REASONING_LEVEL), `${model.id} must support ${DEFAULT_REASONING_LEVEL}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('declares the wire dialect each protocol needs', () => {
|
||||
for (const id of ['deepseek-v4.1-flash', 'deepseek-v4-pro']) {
|
||||
assert.equal(byId(id).compat.thinkingFormat, 'deepseek', id)
|
||||
assert.equal(byId(id).compat.maxTokensField, 'max_tokens', id)
|
||||
assert.equal(byId(id).compat.requiresReasoningContentOnAssistantMessages, true, id)
|
||||
}
|
||||
// Claude 5.x always thinks adaptively and rejects temperature.
|
||||
for (const id of ['claude-opus-5-5', 'claude-sonnet-5-5']) {
|
||||
assert.equal(byId(id).compat.forceAdaptiveThinking, true, id)
|
||||
assert.equal(byId(id).compat.supportsTemperature, false, id)
|
||||
}
|
||||
assert.equal(byId('claude-haiku-4-5-20251001').compat, undefined)
|
||||
assert.equal(byId('gpt-6.1-sol').compat, undefined)
|
||||
for (const id of ['gemini-3.8-flash', 'glm-5.3', 'kimi-k3']) {
|
||||
assert.equal(byId(id).compat.supportsDeveloperRole, false, id)
|
||||
}
|
||||
})
|
||||
|
||||
test('modelForHost re-roots the base URL and keeps its path', () => {
|
||||
const gpt = byId('gpt-6.1-sol')
|
||||
const claude = byId('claude-opus-5-5')
|
||||
assert.equal(modelForHost(gpt, 'https://hk2.geek2api.com').baseUrl, 'https://hk2.geek2api.com/v1')
|
||||
assert.equal(modelForHost(claude, 'https://hk2.geek2api.com').baseUrl, 'https://hk2.geek2api.com')
|
||||
assert.equal(modelForHost(gpt, 'https://hk2.geek2api.com').id, 'gpt-6.1-sol')
|
||||
assert.equal(gpt.baseUrl, `${DEFAULT_API_HOST}/v1`, 'the catalog entry is untouched')
|
||||
assert.equal(modelForHost(gpt, DEFAULT_API_HOST), gpt, 'same host returns the entry itself')
|
||||
assert.equal(modelForHost(gpt, undefined), gpt)
|
||||
assert.equal(modelForHost(undefined, 'https://x.example'), undefined)
|
||||
})
|
||||
@@ -0,0 +1,720 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
buildDelegatedContent,
|
||||
CLI_BACKED_MODEL_IDS,
|
||||
CLI_IMAGE_LIMITS,
|
||||
createClaudeCliAdapter,
|
||||
delegationInstructions,
|
||||
renderDelegatedPrompt,
|
||||
TITLE_MODEL_ID,
|
||||
TITLE_MODEL_ROUTES,
|
||||
} from '../src/claude-adapter.js'
|
||||
|
||||
/** The reasoning note every delegated turn opens with, before the CLI is up. */
|
||||
const LAUNCH = '▸ 启动 Claude Code CLI…\n'
|
||||
const LAUNCH_CHUNKS = [
|
||||
{ type: 'block-start', index: 0, blockType: 'reasoning' },
|
||||
{ type: 'reasoning-delta', index: 0, text: LAUNCH },
|
||||
]
|
||||
|
||||
/** An inner adapter that records what it was asked for. */
|
||||
function innerAdapter({ model = { id: 'gpt-6.1-sol' } } = {}) {
|
||||
const calls = []
|
||||
return {
|
||||
calls,
|
||||
providerInfo: provider => ({ id: provider, displayName: 'Geek2API' }),
|
||||
providerRetryPolicy: () => ({ mode: 'normal', maxRetries: 20, retryableCodes: [] }),
|
||||
listModels: async () => [model],
|
||||
resolveModel: async (_provider, id) => ({ ...model, id }),
|
||||
prepareCall: async (_provider, id) => {
|
||||
calls.push({ kind: 'inner-prepare', id })
|
||||
return { model: { ...model, id }, stream: () => (async function* () { yield { type: 'text-delta', index: 0, text: 'inner' } })() }
|
||||
},
|
||||
stream: () => (async function* () { yield { type: 'text-delta', index: 0, text: 'inner' } })(),
|
||||
}
|
||||
}
|
||||
|
||||
/** A runner that replays a scripted event list. */
|
||||
function stubRunner(events, { onCall } = {}) {
|
||||
const calls = []
|
||||
return {
|
||||
calls,
|
||||
async *stream(options) {
|
||||
calls.push(options)
|
||||
onCall?.(options)
|
||||
for (const event of events) yield event
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function consume(iterable) {
|
||||
const chunks = []
|
||||
for await (const chunk of iterable) chunks.push(chunk)
|
||||
return chunks
|
||||
}
|
||||
|
||||
test('the Claude runtime decides per call whether a Claude model runs through the CLI', async () => {
|
||||
const inner = innerAdapter()
|
||||
const runner = stubRunner([{ type: 'text', text: 'cli' }, { type: 'result', result: { result: 'cli', inputTokens: 1, outputTokens: 2 } }])
|
||||
let runtime = 'http'
|
||||
const adapter = createClaudeCliAdapter({
|
||||
inner,
|
||||
runner,
|
||||
isCliModel: id => runtime === 'cli' && CLI_BACKED_MODEL_IDS.includes(id),
|
||||
resolveMode: () => 'edit',
|
||||
resolveCwd: () => '/work',
|
||||
})
|
||||
assert.deepEqual([...CLI_BACKED_MODEL_IDS], ['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-4-5-20251001'])
|
||||
assert.equal(TITLE_MODEL_ID, 'claude-haiku-4-5-20251001')
|
||||
|
||||
const http = await adapter.prepareCall('geek2api', 'claude-opus-5-5')
|
||||
assert.deepEqual(await consume(http.stream({ model: 'claude-opus-5-5' })), [{ type: 'text-delta', index: 0, text: 'inner' }])
|
||||
assert.equal(runner.calls.length, 0, 'HTTP runtime keeps Claude on the pi-ai path')
|
||||
|
||||
runtime = 'cli'
|
||||
await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))
|
||||
assert.equal(runner.calls.length, 1, 'the CLI runtime takes over without rebuilding the adapter')
|
||||
await consume(adapter.stream({ provider: 'geek2api', model: 'gpt-6.1-sol', messages: [] }))
|
||||
assert.equal(runner.calls.length, 1, 'other models never leave the pi-ai path')
|
||||
})
|
||||
|
||||
test('only the CLI-backed ids leave the pi-ai path', async () => {
|
||||
const inner = innerAdapter()
|
||||
const runner = stubRunner([{ type: 'text', text: 'cli' }, { type: 'result', result: { result: 'cli', inputTokens: 1, outputTokens: 2 } }])
|
||||
const adapter = createClaudeCliAdapter({ inner, runner, modelIds: CLI_BACKED_MODEL_IDS, resolveMode: () => 'edit', resolveCwd: () => '/work' })
|
||||
|
||||
const passthrough = await adapter.prepareCall('geek2api', 'gpt-6.1-sol')
|
||||
assert.deepEqual(await consume(passthrough.stream({ model: 'gpt-6.1-sol' })), [{ type: 'text-delta', index: 0, text: 'inner' }])
|
||||
assert.deepEqual(inner.calls, [{ kind: 'inner-prepare', id: 'gpt-6.1-sol' }])
|
||||
assert.equal(runner.calls.length, 0)
|
||||
|
||||
const delegated = await adapter.prepareCall('geek2api', 'claude-opus-5-5')
|
||||
assert.equal(delegated.model.id, 'claude-opus-5-5')
|
||||
assert.equal(runner.calls.length, 0, 'the CLI starts only when the stream is consumed')
|
||||
await consume(delegated.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))
|
||||
assert.equal(runner.calls.length, 1)
|
||||
assert.equal(runner.calls[0].mode, 'edit')
|
||||
assert.equal(runner.calls[0].cwd, '/work')
|
||||
assert.equal(runner.calls[0].model, 'claude-opus-5-5')
|
||||
})
|
||||
|
||||
test('a delegated turn streams the CLI text and finishes clean', async () => {
|
||||
const runner = stubRunner([
|
||||
{ type: 'text', text: 'Hel' },
|
||||
{ type: 'text', text: 'lo' },
|
||||
{ type: 'result', result: { result: 'Hello', inputTokens: 3, outputTokens: 4 } },
|
||||
])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner, resolveMode: () => 'read-only' })
|
||||
const chunks = await consume(adapter.stream({
|
||||
provider: 'geek2api',
|
||||
model: 'claude-opus-5-5',
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }],
|
||||
}))
|
||||
assert.deepEqual(chunks, [
|
||||
...LAUNCH_CHUNKS,
|
||||
{ type: 'block-end', index: 0, block: { type: 'reasoning', text: LAUNCH } },
|
||||
{ type: 'block-start', index: 1, blockType: 'text' },
|
||||
{ type: 'text-delta', index: 1, text: 'Hel' },
|
||||
{ type: 'text-delta', index: 1, text: 'lo' },
|
||||
{ type: 'block-end', index: 1, block: { type: 'text', text: 'Hello' } },
|
||||
{ type: 'usage', usage: { inputTokens: 3, outputTokens: 4, cacheReadTokens: 0, cacheWriteTokens: 0 } },
|
||||
{ type: 'finish', reason: { kind: 'stop' } },
|
||||
])
|
||||
})
|
||||
|
||||
test('thinking and tool activity stream live as reasoning, the answer as text', async () => {
|
||||
const runner = stubRunner([
|
||||
{ type: 'block', kind: 'reasoning' },
|
||||
{ type: 'reasoning', text: '先看仓库' },
|
||||
{ type: 'tool', id: 't1', summary: 'Bash · git status' },
|
||||
{ type: 'tool', id: 't1', summary: 'Bash · git status' },
|
||||
{ type: 'tool-error', id: 't1', text: 'not a git repository' },
|
||||
{ type: 'block', kind: 'text' },
|
||||
{ type: 'text', text: '第一段' },
|
||||
{ type: 'block', kind: 'text' },
|
||||
{ type: 'text', text: '第二段' },
|
||||
{ type: 'result', result: { result: '', inputTokens: 0, outputTokens: 9 } },
|
||||
])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner })
|
||||
const chunks = await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))
|
||||
const ends = chunks.filter(chunk => chunk.type === 'block-end').map(chunk => chunk.block)
|
||||
assert.deepEqual(ends, [
|
||||
{ type: 'reasoning', text: LAUNCH },
|
||||
{ type: 'reasoning', text: '先看仓库\n▸ Bash · git status\n ✗ not a git repository\n' },
|
||||
{ type: 'text', text: '第一段' },
|
||||
{ type: 'text', text: '第二段' },
|
||||
])
|
||||
// Every delta addresses an open block of its own type.
|
||||
const open = new Map()
|
||||
for (const chunk of chunks) {
|
||||
if (chunk.type === 'block-start') open.set(chunk.index, chunk.blockType)
|
||||
if (chunk.type === 'block-end') open.delete(chunk.index)
|
||||
if (chunk.type === 'text-delta') assert.equal(open.get(chunk.index), 'text')
|
||||
if (chunk.type === 'reasoning-delta') assert.equal(open.get(chunk.index), 'reasoning')
|
||||
}
|
||||
assert.equal(open.size, 0)
|
||||
})
|
||||
|
||||
test('usage reports the last request as context and keeps cache hits', async () => {
|
||||
const runner = stubRunner([
|
||||
{ type: 'request-usage', usage: { inputTokens: 2, cacheReadTokens: 29_246, cacheWriteTokens: 13_634 } },
|
||||
{ type: 'text', text: 'a' },
|
||||
{ type: 'request-usage', usage: { inputTokens: 2, cacheReadTokens: 43_323, cacheWriteTokens: 385 } },
|
||||
{ type: 'result', result: { result: 'a', inputTokens: 4, outputTokens: 357, cacheReadTokens: 72_569, cacheWriteTokens: 14_019 } },
|
||||
])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner })
|
||||
const chunks = await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))
|
||||
assert.deepEqual(chunks.find(chunk => chunk.type === 'usage').usage, {
|
||||
inputTokens: 2,
|
||||
outputTokens: 357,
|
||||
cacheReadTokens: 43_323,
|
||||
cacheWriteTokens: 385,
|
||||
})
|
||||
})
|
||||
|
||||
test('usage falls back to the CLI totals when no request was observed', async () => {
|
||||
const runner = stubRunner([
|
||||
{ type: 'result', result: { result: '', inputTokens: 4, outputTokens: 5, cacheReadTokens: 6, cacheWriteTokens: 7 } },
|
||||
])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner })
|
||||
const chunks = await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))
|
||||
assert.deepEqual(chunks.find(chunk => chunk.type === 'usage').usage, {
|
||||
inputTokens: 4,
|
||||
outputTokens: 5,
|
||||
cacheReadTokens: 6,
|
||||
cacheWriteTokens: 7,
|
||||
})
|
||||
})
|
||||
|
||||
test('a delegated turn reports a CLI failure without blaming a key', async () => {
|
||||
const runner = {
|
||||
// eslint-disable-next-line require-yield
|
||||
async *stream() {
|
||||
throw new Error('Claude Code CLI failed: Failed to authenticate. API Error: 401 无效的令牌')
|
||||
},
|
||||
}
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner })
|
||||
const chunks = await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))
|
||||
assert.deepEqual(chunks.slice(0, -1), [...LAUNCH_CHUNKS, { type: 'block-end', index: 0, block: { type: 'reasoning', text: LAUNCH } }])
|
||||
const finish = chunks.at(-1)
|
||||
assert.equal(finish.type, 'finish')
|
||||
assert.equal(finish.reason.kind, 'error')
|
||||
assert.equal(finish.reason.failure.code, 'PI_AI_ERROR')
|
||||
assert.match(finish.reason.failure.message, /401 无效的令牌/u)
|
||||
})
|
||||
|
||||
/** The reasoning text a turn's chunks carry. */
|
||||
const reasoningOf = chunks => chunks.filter(chunk => chunk.type === 'reasoning-delta').map(chunk => chunk.text).join('')
|
||||
|
||||
test('every CLI turn names the key it used, and a key passed over for its groups is said so', async () => {
|
||||
const plain = createClaudeCliAdapter({
|
||||
inner: innerAdapter(),
|
||||
runner: stubRunner([{ type: 'key', label: 'cc', model: 'claude-opus-5-5', groups: ['cc'] }, { type: 'result', result: { result: '', inputTokens: 0, outputTokens: 0 } }]),
|
||||
})
|
||||
assert.match(reasoningOf(await consume(plain.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))), /▸ 使用 Key「cc」(分组:cc)/u)
|
||||
|
||||
const switched = createClaudeCliAdapter({
|
||||
inner: innerAdapter(),
|
||||
runner: stubRunner([{ type: 'key', label: 'cc', switchedFrom: 'no-cc', model: 'claude-opus-5-5', groups: ['cc'] }, { type: 'result', result: { result: '', inputTokens: 0, outputTokens: 0 } }]),
|
||||
})
|
||||
assert.match(reasoningOf(await consume(switched.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))), /当前 Key「no-cc」的分组不能用 claude-opus-5-5,本轮改用 Key「cc」/u)
|
||||
|
||||
const uncovered = createClaudeCliAdapter({
|
||||
inner: innerAdapter(),
|
||||
runner: stubRunner([{ type: 'key', label: 'no-cc', uncovered: true, model: 'claude-opus-5-5', required: ['cc', 'cc-sale'] }, { type: 'result', result: { result: '', inputTokens: 0, outputTokens: 0 } }]),
|
||||
})
|
||||
assert.match(reasoningOf(await consume(uncovered.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))), /已存的 Key 都没有能用 claude-opus-5-5 的分组(需要 cc \/ cc-sale)/u)
|
||||
})
|
||||
|
||||
test('an official-CLI refusal from a key without a Claude group blames the key, not the CLI', async () => {
|
||||
const refusal = 'Claude Code CLI failed: Failed to authenticate. API Error: 403 {"error":{"type":"geek2api_<nil>","message":"Request blocked: this endpoint only accepts requests from the official Claude Code CLI. (request id: r1)"}}'
|
||||
const runnerWith = key => ({
|
||||
async *stream() {
|
||||
yield { type: 'key', ...key }
|
||||
throw new Error(refusal)
|
||||
},
|
||||
})
|
||||
const failureOf = async key => {
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner: runnerWith(key) })
|
||||
return (await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))).at(-1).reason.failure.message
|
||||
}
|
||||
const byGroup = await failureOf({ label: 'no-cc', model: 'claude-opus-5-5', groups: ['codex', 'deepseek-officially'], required: ['cc', 'cc-sale'], covers: false })
|
||||
assert.match(byGroup, /Key「no-cc」所在分组(codex、deepseek-officially)不包含能用 claude-opus-5-5 的分组(cc \/ cc-sale)/u)
|
||||
assert.match(byGroup, /不需要更新 CLI/u)
|
||||
assert.doesNotMatch(byGroup, /\b403\b/u)
|
||||
assert.match(byGroup, /request id: r1/u)
|
||||
|
||||
// The other way Geek2API refuses such a key: a routing miss, not a client check.
|
||||
const routingMiss = async () => {
|
||||
const adapter = createClaudeCliAdapter({
|
||||
inner: innerAdapter(),
|
||||
runner: {
|
||||
async *stream() {
|
||||
yield { type: 'key', label: 'no-cc', model: 'claude-opus-5-5', groups: ['codex'], required: ['cc'], covers: false }
|
||||
throw new Error('Claude Code CLI failed: API Error: 400 当前令牌未覆盖供应商 "Anthropic"(模型=claude-opus-5-5,已选分组=[codex]) (request id: r2)')
|
||||
},
|
||||
},
|
||||
})
|
||||
return (await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))).at(-1).reason.failure.message
|
||||
}
|
||||
const miss = await routingMiss()
|
||||
assert.match(miss, /Key「no-cc」所在分组(codex)不包含能用 claude-opus-5-5 的分组(cc)/u)
|
||||
assert.doesNotMatch(miss, /\b400\b/u)
|
||||
|
||||
// Geek2API's own routing miss names no groups: a run whose key was never
|
||||
// read says so, and still blames the key rather than the CLI.
|
||||
const unknownAdapter = createClaudeCliAdapter({
|
||||
inner: innerAdapter(),
|
||||
runner: {
|
||||
async *stream() {
|
||||
yield { type: 'key', id: 'k1', label: 'fresh', model: 'claude-opus-5-5' }
|
||||
throw new Error("Claude Code CLI failed: API Error: 400 {\"error\":{\"message\":\"Model 'claude-opus-5-5' is not available. Use GET /v1/models to see supported models.\"}}")
|
||||
},
|
||||
},
|
||||
})
|
||||
const fromText = (await consume(unknownAdapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))).at(-1).reason.failure.message
|
||||
assert.match(fromText, /Key「fresh」所在分组(未读到)不包含能用 claude-opus-5-5 的分组(Claude 分组)/u)
|
||||
assert.match(fromText, /不需要更新 CLI/u)
|
||||
|
||||
// The 403 wording names no groups: a fresh reading decides.
|
||||
const asked = []
|
||||
const refreshed = createClaudeCliAdapter({
|
||||
inner: innerAdapter(),
|
||||
runner: runnerWith({ id: 'k1', label: 'fresh', model: 'claude-opus-5-5' }),
|
||||
explainKey: async key => {
|
||||
asked.push(key.id)
|
||||
return { ...key, groups: ['codex'], required: ['cc'], covers: false }
|
||||
},
|
||||
})
|
||||
const byReading = (await consume(refreshed.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))).at(-1).reason.failure.message
|
||||
assert.deepEqual(asked, ['k1'])
|
||||
assert.match(byReading, /Key「fresh」所在分组(codex)不包含能用 claude-opus-5-5 的分组(cc)/u)
|
||||
|
||||
// A key whose groups do cover Claude: the CLI explanation stands, naming the key.
|
||||
const byClient = await failureOf({ label: 'cc', model: 'claude-opus-5-5', groups: ['cc'], covers: true })
|
||||
assert.match(byClient, /认为它不是官方 Claude Code CLI 发出的/u)
|
||||
assert.match(byClient, /本轮使用 Key「cc」,分组:cc/u)
|
||||
})
|
||||
|
||||
test('the request signal reaches the CLI so a cancelled turn kills it', async () => {
|
||||
const runner = stubRunner([{ type: 'result', result: { result: 'x', inputTokens: 0, outputTokens: 0 } }])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner })
|
||||
const controller = new AbortController()
|
||||
await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [], signal: controller.signal }))
|
||||
assert.equal(runner.calls[0].signal, controller.signal)
|
||||
})
|
||||
|
||||
test('a session title runs on the small model, read-only, outside the workspace', async () => {
|
||||
const runner = stubRunner([{ type: 'text', text: '修复登录' }, { type: 'result', result: { result: '修复登录', inputTokens: 1, outputTokens: 2 } }])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner, resolveMode: () => 'full', resolveCwd: () => '/work' })
|
||||
const chunks = await consume(adapter.stream({
|
||||
provider: 'geek2api',
|
||||
model: 'claude-opus-5-5',
|
||||
purpose: 'session-title',
|
||||
system: 'Return only the title.',
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: '登录页报错了' }] }],
|
||||
}))
|
||||
assert.equal(chunks.at(-1).reason.kind, 'stop')
|
||||
// A title is read back as text: no progress notes in it.
|
||||
assert.equal(chunks.some(chunk => chunk.type === 'reasoning-delta'), false)
|
||||
assert.equal(runner.calls.length, 1)
|
||||
const call = runner.calls[0]
|
||||
assert.equal(call.model, TITLE_MODEL_ID)
|
||||
assert.equal(call.mode, 'read-only')
|
||||
assert.equal(call.enableSearch, false, 'titles allocate no MCP server or search approval')
|
||||
assert.notEqual(call.cwd, '/work')
|
||||
assert.equal(call.appendSystemPrompt, 'Return only the title.')
|
||||
assert.equal(call.prompt, '登录页报错了')
|
||||
})
|
||||
|
||||
test('a submitted plan becomes one exit_plan_mode call and not assistant text', async () => {
|
||||
const runner = stubRunner([
|
||||
{ type: 'reasoning', text: 'looked around' },
|
||||
{ type: 'plan', plan: '# Ship\n\nDo it.' },
|
||||
{ type: 'result', result: { result: '# Ship\n\nDo it.', inputTokens: 2, outputTokens: 3, mode: 'plan' } },
|
||||
])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner, resolveMode: () => 'plan', resolveCwd: () => '/work' })
|
||||
const chunks = await consume(adapter.stream({
|
||||
provider: 'geek2api',
|
||||
model: 'claude-opus-5-5',
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: 'plan the change' }] }],
|
||||
tools: [{ name: 'exit_plan_mode' }],
|
||||
}))
|
||||
const tool = chunks.find(chunk => chunk.type === 'block-end' && chunk.block?.type === 'tool-call')
|
||||
assert.equal(tool.block.name, 'exit_plan_mode')
|
||||
assert.equal(JSON.parse(tool.block.arguments).plan, '# Ship\n\nDo it.')
|
||||
assert.equal(chunks.at(-1).reason.kind, 'tool-calls')
|
||||
assert.equal(chunks.some(chunk => chunk.type === 'text-delta'), false)
|
||||
assert.match(runner.calls[0].appendSystemPrompt, /ExitPlanMode/u)
|
||||
assert.equal(runner.calls[0].appendSystemPrompt.includes('直接输出最终结果'), false)
|
||||
assert.equal(runner.calls[0].mode, 'plan')
|
||||
})
|
||||
|
||||
test('a session title stays read-only while the session is in plan mode', async () => {
|
||||
const runner = stubRunner([{ type: 'result', result: { result: 'title', inputTokens: 1, outputTokens: 1 } }])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner, resolveMode: () => 'plan', resolveCwd: () => '/work' })
|
||||
await consume(adapter.stream({
|
||||
provider: 'geek2api',
|
||||
model: 'claude-opus-5-5',
|
||||
purpose: 'session-title',
|
||||
system: 'Return only the title.',
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: '登录页报错了' }] }],
|
||||
}))
|
||||
assert.equal(runner.calls[0].mode, 'read-only')
|
||||
assert.equal(runner.calls[0].appendSystemPrompt, 'Return only the title.')
|
||||
})
|
||||
|
||||
test('every CLI-backed model is routed to the CLI with its own id', async () => {
|
||||
for (const id of CLI_BACKED_MODEL_IDS) {
|
||||
const runner = stubRunner([{ type: 'result', result: { result: '', inputTokens: 0, outputTokens: 0 } }])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner })
|
||||
await consume(adapter.stream({ provider: 'geek2api', model: id, messages: [] }))
|
||||
assert.equal(runner.calls[0].model, id)
|
||||
}
|
||||
})
|
||||
|
||||
test('a delegated prompt drops the harness system prompt and marks what it cannot carry', () => {
|
||||
const request = {
|
||||
system: '补充:回答用中文',
|
||||
messages: [
|
||||
{ role: 'system', content: [{ type: 'text', text: 'DSH 系统提示:你有 bash 工具……' }] },
|
||||
{ role: 'user', content: [{ type: 'text', text: '看看这个文件' }, { type: 'image', source: {} }] },
|
||||
{ role: 'assistant', content: [{ type: 'text', text: '好' }, { type: 'tool-call', name: 'read' }] },
|
||||
{ role: 'user', content: [{ type: 'tool-result', toolCallId: 't', content: [{ type: 'text', text: '文件内容 abc' }] }] },
|
||||
],
|
||||
}
|
||||
const prompt = renderDelegatedPrompt(request)
|
||||
// The CLI has its own system prompt and its own tools.
|
||||
assert.equal(prompt.includes('DSH 系统提示'), false)
|
||||
assert.match(prompt, /用户:看看这个文件/u)
|
||||
assert.match(prompt, /\[图片\]/u)
|
||||
assert.match(prompt, /\[调用工具 read\]/u)
|
||||
assert.match(prompt, /助手:好/u)
|
||||
// A structured tool result keeps its text.
|
||||
assert.match(prompt, /\[工具结果\]\n文件内容 abc/u)
|
||||
// The delegation itself travels as appended system instructions.
|
||||
const instructions = delegationInstructions(request, '/work/repo')
|
||||
assert.match(instructions, /委派给 Claude Code/u)
|
||||
assert.match(instructions, /工作目录:\/work\/repo/u)
|
||||
assert.match(instructions, /补充:回答用中文/u)
|
||||
assert.equal(prompt.includes('工作目录'), false)
|
||||
const planning = delegationInstructions(request, '/work/repo', { plan: true })
|
||||
assert.match(planning, /ExitPlanMode/u)
|
||||
assert.equal(planning.includes('直接输出最终结果'), false)
|
||||
})
|
||||
|
||||
test('a long conversation is trimmed to its most recent turns', () => {
|
||||
const messages = []
|
||||
for (let i = 0; i < 200; i += 1) messages.push({ role: 'user', content: [{ type: 'text', text: `第 ${i} 轮 ` + 'x'.repeat(500) }] })
|
||||
const prompt = renderDelegatedPrompt({ messages }, '/work')
|
||||
assert.ok(prompt.length < 52_000, `prompt length ${prompt.length}`)
|
||||
assert.match(prompt, /较早对话已截断/u)
|
||||
assert.match(prompt, /第 199 轮/u)
|
||||
assert.equal(prompt.includes('第 0 轮'), false)
|
||||
})
|
||||
|
||||
/** An attachment store with two images and one file, recording its reads. */
|
||||
function fakeAttachments({ failId } = {}) {
|
||||
const reads = []
|
||||
return {
|
||||
reads,
|
||||
imageHostPath: ref => `/home/u/.dsh/attachments/${ref.attachmentId.slice(7, 9)}/${ref.attachmentId.slice(7)}`,
|
||||
fileHostPath: ref => `/home/u/.dsh/files/${ref.name}`,
|
||||
async readImageRequest(ref, policy) {
|
||||
reads.push({ id: ref.attachmentId, policy })
|
||||
if (ref.attachmentId === failId) throw new Error('integrity check failed')
|
||||
return { data: new Uint8Array(ref.bytes), mediaType: 'image/png', width: 64, height: 32, bytes: ref.bytes }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const imageRef = (hex, bytes = 30, name) => ({
|
||||
attachmentId: `sha256:${hex.repeat(64 / hex.length)}`,
|
||||
mediaType: 'image/jpeg',
|
||||
bytes,
|
||||
width: 640,
|
||||
height: 320,
|
||||
...(name === undefined ? {} : { name }),
|
||||
})
|
||||
|
||||
test('a delegated turn sends its images as image blocks, in place, with their read-only copies', async () => {
|
||||
const attachments = fakeAttachments()
|
||||
const first = imageRef('a1', 30, 'shot.png')
|
||||
const second = imageRef('b2', 60)
|
||||
const content = await buildDelegatedContent({
|
||||
messages: [
|
||||
{ role: 'user', content: [{ type: 'text', text: '看第一张' }, { type: 'image', attachment: first }] },
|
||||
{ role: 'assistant', content: [{ type: 'text', text: '红色方块' }] },
|
||||
{ role: 'user', content: [{ type: 'image', attachment: second }, { type: 'text', text: '和这张比呢' }, { type: 'file', attachment: { attachmentId: 'sha256:ff', name: 'notes.md', bytes: 5 } }] },
|
||||
],
|
||||
}, { attachments })
|
||||
assert.deepEqual(content.map(block => block.type), ['text', 'image', 'text', 'image', 'text'])
|
||||
assert.match(content[0].text, /^用户:看第一张\n\[图片 shot\.png(64x32px);只读副本:\/home\/u\/\.dsh\/attachments\/a1\/a1a1/u)
|
||||
assert.deepEqual(content[1].source, { type: 'base64', media_type: 'image/png', data: Buffer.from(new Uint8Array(30)).toString('base64') })
|
||||
assert.match(content[2].text, /助手:红色方块\n\n用户:\[图片 b2b2b2b2(64x32px)/u)
|
||||
assert.match(content[4].text, /和这张比呢\n\[文件 notes\.md;只读副本:\/home\/u\/\.dsh\/files\/notes\.md\]/u)
|
||||
// Each image is read as the same request version the HTTP route sends.
|
||||
assert.deepEqual(attachments.reads[0].policy, { maxPixels: CLI_IMAGE_LIMITS.maxPixels, maxBytes: CLI_IMAGE_LIMITS.maxBytesPerImage })
|
||||
})
|
||||
|
||||
test('the oldest images give way to the bounds, and an unreadable one is described instead', async () => {
|
||||
const attachments = fakeAttachments({ failId: imageRef('c3').attachmentId })
|
||||
const content = await buildDelegatedContent({
|
||||
messages: [
|
||||
{ role: 'user', content: [{ type: 'image', attachment: imageRef('a1', 30) }, { type: 'text', text: '旧图' }] },
|
||||
{ role: 'user', content: [{ type: 'image', attachment: imageRef('b2', 30) }, { type: 'image', attachment: imageRef('c3', 30) }, { type: 'text', text: '新图' }] },
|
||||
],
|
||||
}, { attachments, limits: { ...CLI_IMAGE_LIMITS, maxImages: 1 } })
|
||||
const text = content.filter(block => block.type === 'text').map(block => block.text).join('')
|
||||
assert.equal(content.filter(block => block.type === 'image').length, 1)
|
||||
assert.match(text, /\[图片 a1a1a1a1:超出本回合的图片上限,未随消息附上,需要时请用 Read 工具读取;只读副本:/u)
|
||||
assert.match(text, /\[图片 c3c3c3c3:读取失败,未随消息附上/u)
|
||||
assert.match(text, /\[图片 b2b2b2b2(64x32px)/u)
|
||||
})
|
||||
|
||||
test('without an attachment store the images are named, not dropped silently', async () => {
|
||||
const content = await buildDelegatedContent({
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: '看图' }, { type: 'image', attachment: imageRef('a1') }] }],
|
||||
}, { attachments: undefined })
|
||||
assert.deepEqual(content, [{ type: 'text', text: '用户:看图\n[图片 a1a1a1a1:当前运行环境无法读取附件]' }])
|
||||
})
|
||||
|
||||
test('the adapter hands the CLI content blocks, the delegation instructions, and the store it was given', async () => {
|
||||
const runner = stubRunner([{ type: 'result', result: { result: 'ok', inputTokens: 0, outputTokens: 0 } }])
|
||||
const attachments = fakeAttachments()
|
||||
const adapter = createClaudeCliAdapter({
|
||||
inner: innerAdapter(),
|
||||
runner,
|
||||
resolveMode: () => 'edit',
|
||||
resolveCwd: () => '/work',
|
||||
resolveAttachments: () => attachments,
|
||||
})
|
||||
await consume(adapter.stream({
|
||||
provider: 'geek2api',
|
||||
model: 'claude-sonnet-5-5',
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: '这是什么' }, { type: 'image', attachment: imageRef('a1') }] }],
|
||||
}))
|
||||
const call = runner.calls[0]
|
||||
assert.equal(call.prompt, undefined)
|
||||
assert.deepEqual(call.content.map(block => block.type), ['text', 'image'])
|
||||
assert.match(call.appendSystemPrompt, /委派给 Claude Code/u)
|
||||
assert.match(call.appendSystemPrompt, /工作目录:\/work/u)
|
||||
})
|
||||
|
||||
test('the CLI starting and its own retries show up live in the reasoning block', async () => {
|
||||
const runner = stubRunner([
|
||||
{ type: 'started', version: '2.1.295', model: 'claude-sonnet-5-5' },
|
||||
{ type: 'retry', attempt: 1, maxRetries: 10, delayMs: 1240, status: 503, error: 'server_error' },
|
||||
{ type: 'retry', attempt: 2, maxRetries: 10, delayMs: 2500, status: 429, error: '' },
|
||||
{ type: 'text', text: '好了' },
|
||||
{ type: 'result', result: { result: '好了', inputTokens: 0, outputTokens: 1 } },
|
||||
])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner })
|
||||
const chunks = await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))
|
||||
const reasoning = chunks.find(chunk => chunk.type === 'block-end' && chunk.block.type === 'reasoning').block.text
|
||||
assert.equal(reasoning, [
|
||||
LAUNCH,
|
||||
'▸ Claude Code CLI 已启动(2.1.295 · claude-sonnet-5-5)\n',
|
||||
' ↻ 网关返回 HTTP 503(server_error),CLI 自动重试 1/10,1.2 秒后\n',
|
||||
' ↻ 网关返回 HTTP 429,CLI 自动重试 2/10,2.5 秒后\n',
|
||||
].join(''))
|
||||
assert.equal(chunks.at(-1).reason.kind, 'stop')
|
||||
})
|
||||
|
||||
/** A runner that reports some retries and then fails with `message`. */
|
||||
function failingRunner(message, retries = 0) {
|
||||
return {
|
||||
async *stream() {
|
||||
for (let attempt = 1; attempt <= retries; attempt += 1) yield { type: 'retry', attempt, maxRetries: 10, status: 503 }
|
||||
throw new Error(message)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test('a busy gateway is named as such once the CLI has given up retrying', async () => {
|
||||
const raw = 'Claude Code CLI failed: API Error: 503 {"error":{"type":"geek2api_concurrency_queue_full","message":"账号并发排队已满,请稍后重试。(Per-account wait queues are full. Please retry shortly.) (request id: 01M4QQ)"},"type":"geek2api_error"}'
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner: failingRunner(raw, 10) })
|
||||
const finish = (await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))).at(-1)
|
||||
assert.equal(finish.reason.failure.code, 'PI_AI_ERROR')
|
||||
assert.match(finish.reason.failure.message, /Claude 上游暂时繁忙/u)
|
||||
assert.match(finish.reason.failure.message, /已自动重试 10 次/u)
|
||||
assert.match(finish.reason.failure.message, /geek2api_concurrency_queue_full/u)
|
||||
assert.match(finish.reason.failure.message, /request id: 01M4QQ/u)
|
||||
})
|
||||
|
||||
test('a client-policy refusal of the CLI keeps the gateway words but drops the auth status', async () => {
|
||||
const raw = 'Claude Code CLI failed: Failed to authenticate. API Error: 403 {"error":{"type":"geek2api_<nil>","message":"Request blocked: this endpoint only accepts requests from the official Claude Code CLI. (request id: 01M4QNSF)"}}'
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner: failingRunner(raw) })
|
||||
const message = (await consume(adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', messages: [] }))).at(-1).reason.failure.message
|
||||
assert.match(message, /不是 API Key 失效/u)
|
||||
assert.match(message, /request id: 01M4QNSF/u)
|
||||
assert.equal(/\b403\b/u.test(message), false)
|
||||
})
|
||||
|
||||
/** An inner adapter that records which model each prepared call and dispatch used. */
|
||||
function routingInner() {
|
||||
const seen = []
|
||||
const streamFor = prepared => options => (async function* () {
|
||||
seen.push({ prepared, dispatched: options.model, purpose: options.purpose })
|
||||
yield { type: 'text-delta', index: 0, text: `from ${options.model}` }
|
||||
})()
|
||||
return {
|
||||
seen,
|
||||
providerInfo: provider => ({ id: provider }),
|
||||
listModels: async () => [],
|
||||
resolveModel: async (_provider, id) => ({ id }),
|
||||
prepareCall: async (_provider, id) => ({ model: { id }, stream: streamFor(id) }),
|
||||
stream: options => streamFor('unprepared')(options),
|
||||
}
|
||||
}
|
||||
|
||||
test('a gpt-6-astra session title runs on gpt-6.1-sol; its turns stay on Astra', async () => {
|
||||
assert.deepEqual({ ...TITLE_MODEL_ROUTES }, { 'gpt-6-astra': 'gpt-6.1-sol' })
|
||||
const inner = routingInner()
|
||||
const adapter = createClaudeCliAdapter({ inner, runner: stubRunner([]) })
|
||||
|
||||
// The prepared path, which the LLM service uses: the model shown stays Astra.
|
||||
const prepared = await adapter.prepareCall('geek2api', 'gpt-6-astra')
|
||||
assert.equal(prepared.model.id, 'gpt-6-astra')
|
||||
const title = await consume(prepared.stream({ provider: 'geek2api', model: 'gpt-6-astra', purpose: 'session-title', messages: [] }))
|
||||
assert.deepEqual(title, [{ type: 'text-delta', index: 0, text: 'from gpt-6.1-sol' }])
|
||||
assert.deepEqual(inner.seen.at(-1), { prepared: 'gpt-6.1-sol', dispatched: 'gpt-6.1-sol', purpose: 'session-title' })
|
||||
|
||||
const turn = await adapter.prepareCall('geek2api', 'gpt-6-astra')
|
||||
await consume(turn.stream({ provider: 'geek2api', model: 'gpt-6-astra', messages: [] }))
|
||||
assert.deepEqual(inner.seen.at(-1), { prepared: 'gpt-6-astra', dispatched: 'gpt-6-astra', purpose: undefined })
|
||||
|
||||
// The direct path reroutes the same way.
|
||||
await consume(adapter.stream({ provider: 'geek2api', model: 'gpt-6-astra', purpose: 'session-title', messages: [] }))
|
||||
assert.deepEqual(inner.seen.at(-1), { prepared: 'gpt-6.1-sol', dispatched: 'gpt-6.1-sol', purpose: 'session-title' })
|
||||
})
|
||||
|
||||
test('models without a title route keep titling themselves', async () => {
|
||||
const inner = routingInner()
|
||||
const adapter = createClaudeCliAdapter({ inner, runner: stubRunner([]) })
|
||||
for (const model of ['gpt-6.1-sol', 'deepseek-v4.1-flash']) {
|
||||
const prepared = await adapter.prepareCall('geek2api', model)
|
||||
await consume(prepared.stream({ provider: 'geek2api', model, purpose: 'session-title', messages: [] }))
|
||||
assert.deepEqual(inner.seen.at(-1), { prepared: model, dispatched: model, purpose: 'session-title' })
|
||||
}
|
||||
})
|
||||
|
||||
const planCall = (plan, id = 'plan-review', extra = {}) => ({ type: 'tool-call', id, name: 'exit_plan_mode', arguments: JSON.stringify({ plan, ...extra }) })
|
||||
const reviewResult = (text, id = 'plan-review', isError = false) => ({ type: 'tool-result', toolCallId: id, isError, content: [{ type: 'text', text }] })
|
||||
|
||||
const planAdapter = plan => createClaudeCliAdapter({
|
||||
inner: innerAdapter(),
|
||||
runner: stubRunner([{ type: 'plan', plan }, { type: 'result', result: { result: plan, inputTokens: 1, outputTokens: 2 } }]),
|
||||
resolveMode: () => 'plan',
|
||||
})
|
||||
|
||||
test('plan review chooses the current request catalog, including PTC and both modes', async () => {
|
||||
for (const [tools, expected] of [
|
||||
[[{ name: 'exit_plan_mode' }], 'exit_plan_mode'],
|
||||
[[{ name: 'run_code' }], 'run_code'],
|
||||
[[{ name: 'exit_plan_mode' }, { name: 'run_code' }], 'exit_plan_mode'],
|
||||
]) {
|
||||
const plan = '# Review\n\nDo not publish or reveal credentials.'
|
||||
const chunks = await consume(planAdapter(plan).stream({ model: 'claude-opus-5-5', messages: [], tools }))
|
||||
const call = chunks.find(chunk => chunk.type === 'block-end' && chunk.block.type === 'tool-call').block
|
||||
assert.equal(call.name, expected)
|
||||
const args = JSON.parse(call.arguments)
|
||||
if (expected === 'run_code') {
|
||||
assert.equal(args.code, `return await tools.exit_plan_mode(${JSON.stringify({ plan })})`)
|
||||
assert.equal(args.description, 'Present completed plan for user review')
|
||||
assert.deepEqual(Object.keys(args).sort(), ['code', 'description'])
|
||||
} else assert.deepEqual(args, { plan })
|
||||
}
|
||||
})
|
||||
|
||||
test('missing review capabilities fail closed without an unknown native tool call', async () => {
|
||||
const empty = await consume(planAdapter(' \n ').stream({ model: 'claude-opus-5-5', messages: [], tools: [{ name: 'exit_plan_mode' }] }))
|
||||
assert.equal(empty.some(chunk => chunk.block?.type === 'tool-call'), false)
|
||||
assert.match(empty.at(-1).reason.failure.message, /empty plan/u)
|
||||
for (const tools of [undefined, [], [{ name: 'read' }]]) {
|
||||
const chunks = await consume(planAdapter('# Review\n\nNo implementation yet.').stream({ model: 'claude-opus-5-5', messages: [], tools }))
|
||||
assert.equal(chunks.some(chunk => chunk.block?.type === 'tool-call'), false)
|
||||
assert.equal(chunks.at(-1).reason.kind, 'error')
|
||||
assert.match(chunks.at(-1).reason.failure.message, /neither exit_plan_mode nor run_code/u)
|
||||
}
|
||||
})
|
||||
|
||||
test('durable plans and review feedback bypass the general 8k block cap, not the 48k prompt budget', async () => {
|
||||
const plan = '# Safe implementation\n\n' + 'p'.repeat(9_000) + '\nNever commit, publish, or discard user changes.'
|
||||
const feedback = 'The user chose to keep planning; their feedback: ' + 'f'.repeat(9_000) + '\nAdd a migration rollback.'
|
||||
const messages = [
|
||||
{ role: 'assistant', content: [planCall(plan, 'plan-review', { apiKey: 'SECRET-PLAN-METADATA' })] },
|
||||
{ role: 'user', content: [reviewResult(feedback, 'plan-review', true)] },
|
||||
...Array.from({ length: 90 }, () => ({ role: 'user', content: [{ type: 'text', text: 'noise'.repeat(300) }] })),
|
||||
{ role: 'assistant', content: [{ type: 'tool-call', name: 'credential_tool', arguments: JSON.stringify({ token: 'SECRET-UNRELATED-TOOL' }) }] },
|
||||
{ role: 'user', content: [{ type: 'text', text: 'Revise the draft, keeping all original constraints.' }] },
|
||||
]
|
||||
const prompt = renderDelegatedPrompt(JSON.parse(JSON.stringify({ messages })))
|
||||
assert.ok(prompt.includes(plan), 'all original plan constraints survive a fork/resume-shaped serialization and old-turn trimming')
|
||||
assert.ok(prompt.includes(feedback), 'review feedback is carried whole')
|
||||
assert.match(prompt, /Revise the draft/u)
|
||||
assert.match(prompt, /未批准\/失败/u)
|
||||
assert.doesNotMatch(prompt, /SECRET-/u)
|
||||
assert.match(prompt, /较早对话已截断/u)
|
||||
assert.ok(prompt.length < 48_100)
|
||||
const content = await buildDelegatedContent({ messages })
|
||||
assert.ok(content.map(block => block.text ?? '').join('').includes(plan))
|
||||
})
|
||||
|
||||
test('only the exact persisted PTC plan-review program is decoded; arbitrary programs and tool secrets stay private', () => {
|
||||
const plan = '# PTC review\n\nKeep user data intact.'
|
||||
const safe = { type: 'tool-call', id: 'ptc-review', name: 'run_code', arguments: JSON.stringify({ code: `return await tools.exit_plan_mode(${JSON.stringify({ plan })})`, description: 'Review' }) }
|
||||
const request = { messages: [
|
||||
{ role: 'assistant', content: [safe] },
|
||||
{ role: 'user', content: [reviewResult('{"approved":true}', 'ptc-review')] },
|
||||
{ role: 'assistant', content: [{ type: 'tool-call', name: 'run_code', arguments: JSON.stringify({ code: `return await tools.exit_plan_mode(${JSON.stringify({ plan: 'SECRET-OTHER-PROGRAM', token: 'SECRET-TOKEN' })})` }) }] },
|
||||
{ role: 'user', content: [{ type: 'text', text: 'Proceed with the approved plan.' }] },
|
||||
] }
|
||||
const prompt = renderDelegatedPrompt(request)
|
||||
assert.ok(prompt.includes(plan))
|
||||
assert.match(prompt, /"approved":true/u)
|
||||
assert.doesNotMatch(prompt, /SECRET-/u)
|
||||
assert.equal(renderDelegatedPrompt({ messages: [{ role: 'assistant', content: [{ ...safe, arguments: JSON.stringify({ code: `return await tools.exit_plan_mode({"plan":"SECRET-EXTRA-STATEMENT"}); evil()` }) }] }] }).includes('SECRET-'), false)
|
||||
})
|
||||
|
||||
test('the latest revised plan supersedes an older draft when recent chat is trimmed', () => {
|
||||
const revised = '# Revised\n\nNo production writes; use a staging fixture.'
|
||||
const prompt = renderDelegatedPrompt({ messages: [
|
||||
{ role: 'assistant', content: [planCall('# Obsolete\n\nOLD-DRAFT', 'old')] },
|
||||
{ role: 'user', content: [reviewResult('Keep planning', 'old', true)] },
|
||||
{ role: 'assistant', content: [planCall(revised, 'new')] },
|
||||
{ role: 'user', content: [reviewResult('Plan approved', 'new')] },
|
||||
...Array.from({ length: 60 }, () => ({ role: 'user', content: [{ type: 'text', text: 'x'.repeat(1_000) }] })),
|
||||
{ role: 'user', content: [{ type: 'text', text: 'Continue' }] },
|
||||
] })
|
||||
assert.ok(prompt.includes(revised))
|
||||
assert.match(prompt, /Plan approved/u)
|
||||
assert.doesNotMatch(prompt, /OLD-DRAFT/u)
|
||||
})
|
||||
|
||||
test('oversize plans fail before review, and oversize durable context fails before spawning a new CLI', async () => {
|
||||
const huge = '# Oversize\n\n' + 'x'.repeat(48_000)
|
||||
const emitted = await consume(planAdapter(huge).stream({ model: 'claude-opus-5-5', messages: [], tools: [{ name: 'run_code' }] }))
|
||||
assert.equal(emitted.some(chunk => chunk.block?.type === 'tool-call'), false)
|
||||
assert.match(emitted.at(-1).reason.failure.message, /48,000.*before review/u)
|
||||
const runner = stubRunner([])
|
||||
const adapter = createClaudeCliAdapter({ inner: innerAdapter(), runner })
|
||||
const options = { model: 'claude-opus-5-5', messages: [
|
||||
{ role: 'assistant', content: [planCall('# Approved\n\n' + 'x'.repeat(40_000))] },
|
||||
{ role: 'user', content: [reviewResult('Plan approved')] },
|
||||
{ role: 'user', content: [{ type: 'text', text: 'Keep this additional constraint: ' + 'y'.repeat(9_000) }] },
|
||||
] }
|
||||
assert.throws(() => renderDelegatedPrompt(options), /48,000.*not truncated/u)
|
||||
const chunks = await consume(adapter.stream(options))
|
||||
assert.equal(runner.calls.length, 0)
|
||||
assert.equal(chunks.at(-1).reason.kind, 'error')
|
||||
assert.match(chunks.at(-1).reason.failure.message, /48,000.*not truncated/u)
|
||||
})
|
||||
|
||||
test('ordinary tool results keep their existing 8k cap', () => {
|
||||
const prompt = renderDelegatedPrompt({ messages: [{ role: 'user', content: [reviewResult('x'.repeat(8_000) + 'TRUNCATE-ME', 'ordinary-tool')] }] })
|
||||
assert.equal(prompt.includes('TRUNCATE-ME'), false)
|
||||
assert.equal(prompt.includes('x'.repeat(8_000)), true)
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,218 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { createToolResultMessage } from '@deepseek-ai/dsh-llm'
|
||||
import { defineTool, ToolRuntime } from '@deepseek-ai/dsh-tools'
|
||||
|
||||
import { createClaudeCliAdapter } from '../src/claude-adapter.js'
|
||||
import { createClaudeCodeTool } from '../src/claude-tool.js'
|
||||
import { planModeForSession, planModeForToolExecution } from '../src/permission.js'
|
||||
|
||||
const APPROVED = 'Plan approved — plan mode exited; carry out the plan starting with your next step.'
|
||||
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor
|
||||
|
||||
/**
|
||||
* Use the shipped ToolRuntime, including its real catalog collapse, run_code
|
||||
* bridge, nested dispatch, schema validation, and durable PTC logs. Only the
|
||||
* program substrate and user review are deterministic in-process fixtures;
|
||||
* neither native nor PTC tool dispatch is stubbed.
|
||||
*/
|
||||
function host(mode, choices = [{ approved: true }]) {
|
||||
const ctx = new Context()
|
||||
const events = []
|
||||
const state = { active: true }
|
||||
const session = {
|
||||
id: `host-${mode}`,
|
||||
header: { cwd: '/test-workspace' },
|
||||
append(type, data) { events.push({ type, data }); return { seq: events.length } },
|
||||
}
|
||||
const agent = { session }
|
||||
const reviews = []
|
||||
ctx.provide('systemPrompt', { tools() {}, section() {}, getSectionOrder: () => 1 })
|
||||
ctx.provide('codeRuntime', {
|
||||
language: 'typescript',
|
||||
async run({ program, bindings, signal }) {
|
||||
assert.equal(bindings.length, 1)
|
||||
assert.equal(bindings[0].global, 'tools', 'use the actual host binding namespace')
|
||||
signal.throwIfAborted()
|
||||
try {
|
||||
const value = await new AsyncFunction('tools', program)(bindings[0].functions)
|
||||
return { logs: [], value }
|
||||
} catch (error) {
|
||||
return { logs: [], error: { kind: 'program', message: error.message } }
|
||||
}
|
||||
},
|
||||
})
|
||||
ctx.provide('planMode', { get: target => {
|
||||
assert.equal(target.session, session)
|
||||
return { ...state }
|
||||
} })
|
||||
ctx.provide('agents', { currentInitiator: () => agent })
|
||||
ctx.provide('sessionProjections', { stateOf: target => (target === session ? { active: state.active } : undefined) })
|
||||
const tools = new ToolRuntime(ctx, { mode })
|
||||
tools.register(defineTool({
|
||||
name: 'exit_plan_mode',
|
||||
description: 'Present the completed plan for user review.',
|
||||
parameters: { plan: { type: 'string', required: true } },
|
||||
output: {
|
||||
schema: { type: 'object', additionalProperties: false, properties: { approved: { type: 'boolean', const: true, required: true } } },
|
||||
render: () => [{ type: 'text', text: APPROVED }],
|
||||
},
|
||||
async execute(args, exec) {
|
||||
assert.equal(exec.agent, agent)
|
||||
assert.equal(state.active, true, 'review requires logged plan mode')
|
||||
reviews.push(args.plan)
|
||||
const choice = choices.shift()
|
||||
assert.ok(choice, 'a scripted user review exists')
|
||||
if (!choice.approved) throw new Error(`The user chose to keep planning; their feedback: ${choice.feedback}`)
|
||||
state.pending = false
|
||||
return { approved: true }
|
||||
},
|
||||
}))
|
||||
const signal = new AbortController().signal
|
||||
return {
|
||||
ctx, tools, session, agent, state, reviews, events,
|
||||
execute: block => tools.execute({ callId: block.id, name: block.name, arguments: JSON.parse(block.arguments), agent, signal }),
|
||||
boundary() {
|
||||
if (typeof state.pending !== 'boolean') return
|
||||
state.active = state.pending
|
||||
delete state.pending
|
||||
session.append('plan/mode', { active: state.active })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function runnerFor(events) {
|
||||
const calls = []
|
||||
return { calls, async *stream(options) { calls.push(options); yield* events } }
|
||||
}
|
||||
|
||||
/** A new adapter per call proves the carried plan is not an in-memory cache. */
|
||||
async function delegatedTurn(harness, messages, plan) {
|
||||
const runner = runnerFor(plan === undefined
|
||||
? [{ type: 'text', text: 'Done' }, { type: 'result', result: { inputTokens: 1, outputTokens: 1 } }]
|
||||
: [{ type: 'plan', plan }, { type: 'result', result: { result: plan, inputTokens: 1, outputTokens: 1 } }])
|
||||
const inner = { providerInfo: () => ({}), resolveModel: async (_provider, id) => ({ id }) }
|
||||
const adapter = createClaudeCliAdapter({ inner, runner, resolveMode: () => planModeForSession(harness.ctx, harness.session) ? 'plan' : 'full' })
|
||||
const chunks = []
|
||||
// Resume/fork reconstructs this request from persisted blocks, not JS object identity.
|
||||
for await (const chunk of adapter.stream({
|
||||
provider: 'geek2api', model: 'claude-opus-5-5', messages: JSON.parse(JSON.stringify(messages)),
|
||||
tools: harness.tools.wireSchemas(harness.agent).schemas,
|
||||
})) chunks.push(chunk)
|
||||
assert.notEqual(chunks.at(-1).reason.kind, 'error', JSON.stringify(chunks.at(-1)))
|
||||
const blocks = chunks.filter(chunk => chunk.type === 'block-end').map(chunk => chunk.block)
|
||||
return { runner, blocks, call: blocks.find(block => block.type === 'tool-call') }
|
||||
}
|
||||
|
||||
function persistReview(messages, turn, result) {
|
||||
messages.push({ role: 'assistant', content: turn.blocks })
|
||||
messages.push(createToolResultMessage({ callId: turn.call.id, content: result.content, isError: result.isError }))
|
||||
}
|
||||
|
||||
const contentText = call => call.content.filter(block => block.type === 'text').map(block => block.text).join('')
|
||||
|
||||
for (const mode of ['native', 'ptc']) {
|
||||
test(`real ${mode} ToolRuntime reviews a plan and a fresh CLI receives all approved constraints`, async () => {
|
||||
const harness = host(mode)
|
||||
const plan = '# Approved plan\n\n' + 'detail '.repeat(1_300) + '\nNever publish, never expose keys, preserve unrelated changes.'
|
||||
const messages = [{ role: 'user', content: [{ type: 'text', text: 'Prepare a safe implementation plan.' }] }]
|
||||
const first = await delegatedTurn(harness, messages, plan)
|
||||
assert.equal(first.call.name, mode === 'ptc' ? 'run_code' : 'exit_plan_mode')
|
||||
assert.equal(first.runner.calls[0].mode, 'plan')
|
||||
const result = await harness.execute(first.call)
|
||||
assert.equal(result.isError, false, JSON.stringify(result))
|
||||
assert.deepEqual(harness.reviews, [plan])
|
||||
assert.equal(harness.state.active, true)
|
||||
assert.equal(harness.state.pending, false)
|
||||
assert.equal(result.additionalContexts?.length ?? 0, 0, 'real host review does not defer the plan into context')
|
||||
assert.equal(result.content.some(block => block.text?.includes(plan)), false, 'review result contains approval only, not the plan')
|
||||
persistReview(messages, first, result)
|
||||
// Older plan turns cannot be dropped even if enough later chat fills the ordinary budget.
|
||||
messages.push(...Array.from({ length: 65 }, () => ({ role: 'user', content: [{ type: 'text', text: 'unrelated '.repeat(100) }] })))
|
||||
messages.push({ role: 'user', content: [{ type: 'text', text: 'Continue the approved plan.' }] })
|
||||
harness.boundary()
|
||||
const second = await delegatedTurn(harness, messages)
|
||||
const prompt = contentText(second.runner.calls[0])
|
||||
assert.equal(second.runner.calls[0].mode, 'full')
|
||||
assert.ok(prompt.includes(plan), 'approved constraints are complete, including the tail after 8k')
|
||||
assert.match(prompt, mode === 'ptc' ? /"approved": true/u : /Plan approved/u)
|
||||
assert.match(prompt, /Continue the approved plan/u)
|
||||
if (mode === 'ptc') {
|
||||
const dispatch = harness.events.find(event => event.type === 'tool/ptc-dispatch')
|
||||
assert.equal(dispatch.data.name, 'exit_plan_mode')
|
||||
assert.deepEqual(dispatch.data.arguments, { plan })
|
||||
assert.equal(dispatch.data.isError, false)
|
||||
}
|
||||
})
|
||||
|
||||
test(`real ${mode} review rejection carries its original draft into revision, then approved revision into execution`, async () => {
|
||||
const harness = host(mode, [{ approved: false, feedback: 'Keep all data read-only and add rollback tests.' }, { approved: true }])
|
||||
const draft = '# Initial draft\n\nInvestigate auth; never log credentials; do not publish.'
|
||||
const revised = '# Revised draft\n\nKeep data read-only; add rollback tests; never log credentials; do not publish.'
|
||||
const messages = [{ role: 'user', content: [{ type: 'text', text: 'Plan the auth change.' }] }]
|
||||
const first = await delegatedTurn(harness, messages, draft)
|
||||
const rejected = await harness.execute(first.call)
|
||||
assert.equal(rejected.isError, true)
|
||||
assert.match(rejected.content[0].text, /Keep all data read-only and add rollback tests/u)
|
||||
assert.equal(harness.state.active, true)
|
||||
persistReview(messages, first, rejected)
|
||||
const second = await delegatedTurn(harness, messages, revised)
|
||||
const revisePrompt = contentText(second.runner.calls[0])
|
||||
assert.equal(second.runner.calls[0].mode, 'plan')
|
||||
assert.ok(revisePrompt.includes(draft), 'the rejected first draft is still available to the fresh CLI')
|
||||
assert.match(revisePrompt, /Keep all data read-only and add rollback tests/u)
|
||||
const approved = await harness.execute(second.call)
|
||||
assert.equal(approved.isError, false, JSON.stringify(approved))
|
||||
persistReview(messages, second, approved)
|
||||
harness.boundary()
|
||||
const third = await delegatedTurn(harness, messages)
|
||||
assert.equal(third.runner.calls[0].mode, 'full')
|
||||
assert.ok(contentText(third.runner.calls[0]).includes(revised))
|
||||
assert.deepEqual(harness.reviews, [draft, revised])
|
||||
})
|
||||
}
|
||||
|
||||
test('real PTC collapse rejects a direct native review while the adapter selects the successful bridge', async () => {
|
||||
const harness = host('ptc')
|
||||
const denied = await harness.execute({ type: 'tool-call', id: 'native-under-ptc', name: 'exit_plan_mode', arguments: JSON.stringify({ plan: '# Not reachable directly' }) })
|
||||
assert.equal(denied.isError, true)
|
||||
assert.equal(denied.error.info.code, 'UNKNOWN_TOOL')
|
||||
assert.equal(harness.reviews.length, 0)
|
||||
const generated = await delegatedTurn(harness, [{ role: 'user', content: [{ type: 'text', text: 'Plan safely.' }] }], '# Reachable through PTC\n\nRead only.')
|
||||
const reviewed = await harness.execute(generated.call)
|
||||
assert.equal(reviewed.isError, false, JSON.stringify(reviewed))
|
||||
assert.equal(harness.reviews.length, 1)
|
||||
})
|
||||
|
||||
test('real native ToolRuntime keeps tools at logged plan state through exit/entry pending transitions', async () => {
|
||||
const harness = host('native')
|
||||
const modes = []
|
||||
harness.tools.register(createClaudeCodeTool({
|
||||
modeCeiling: () => 'full',
|
||||
planActive: (session, agent) => planModeForToolExecution(harness.ctx, session, agent),
|
||||
runner: { async run(options) {
|
||||
modes.push(options.mode)
|
||||
return { result: options.mode === 'plan' ? '# Read-only delegated plan' : 'Implemented', model: 'test', mode: options.mode, costUsd: 0, durationMs: 1 }
|
||||
} },
|
||||
}))
|
||||
const approved = await harness.execute({ id: 'approval', name: 'exit_plan_mode', arguments: JSON.stringify({ plan: '# Reviewed plan\n\nImplement only from the next step.' }) })
|
||||
assert.equal(approved.isError, false)
|
||||
const runTool = async id => {
|
||||
const result = await harness.execute({ id, name: 'claude_code', arguments: JSON.stringify({ prompt: 'Implement safely', mode: 'full' }) })
|
||||
assert.equal(result.isError, false, JSON.stringify(result))
|
||||
}
|
||||
await runTool('same-batch')
|
||||
assert.equal(modes.at(-1), 'plan', 'pending=false, active=true must still plan')
|
||||
harness.boundary()
|
||||
await runTool('after-accepted-boundary')
|
||||
assert.equal(modes.at(-1), 'full', 'committed inactive restores the permission ceiling')
|
||||
harness.state.pending = true
|
||||
await runTool('pending-entry-current-batch')
|
||||
assert.equal(modes.at(-1), 'full', 'pending=true alone cannot change current batch permissions')
|
||||
harness.boundary()
|
||||
await runTool('after-entry-boundary')
|
||||
assert.equal(modes.at(-1), 'plan')
|
||||
assert.deepEqual(modes, ['plan', 'full', 'full', 'plan'])
|
||||
})
|
||||
@@ -0,0 +1,329 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
CLAUDE_MISSING_MESSAGE,
|
||||
claudeBinaryCandidates,
|
||||
createClaudeRunner,
|
||||
locateClaudeBinary,
|
||||
resolveSpawnCommand,
|
||||
} from '../src/claude-cli.js'
|
||||
import {
|
||||
CLAUDE_INSTALL_COMMAND,
|
||||
createClaudeCliManager,
|
||||
explainNpmFailure,
|
||||
locateNpm,
|
||||
parseClaudeVersion,
|
||||
} from '../src/claude-install.js'
|
||||
import { searchPath, withProgramDirOnPath } from '../src/locate.js'
|
||||
import { createGeek2APIRpc } from '../src/rpc.js'
|
||||
|
||||
/** A file system made of the listed paths. */
|
||||
const filesystem = paths => {
|
||||
const set = new Set(paths)
|
||||
return { set, exists: candidate => set.has(candidate) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A spawn stand-in: `respond(command, args, options)` returns what the child
|
||||
* prints and how it exits, or `{ error }` for a program that cannot start.
|
||||
*/
|
||||
function scriptedSpawn(respond) {
|
||||
const calls = []
|
||||
const spawnImpl = (command, args, options) => {
|
||||
calls.push({ command, args, options })
|
||||
const child = new EventEmitter()
|
||||
child.stdout = new EventEmitter()
|
||||
child.stderr = new EventEmitter()
|
||||
child.exitCode = null
|
||||
child.signalCode = null
|
||||
child.kill = () => true
|
||||
const outcome = respond(command, args, options) ?? {}
|
||||
queueMicrotask(() => {
|
||||
if (outcome.error !== undefined) {
|
||||
child.emit('error', outcome.error)
|
||||
return
|
||||
}
|
||||
outcome.effect?.()
|
||||
if (outcome.stdout) child.stdout.emit('data', outcome.stdout)
|
||||
if (outcome.stderr) child.stderr.emit('data', outcome.stderr)
|
||||
child.exitCode = outcome.code ?? 0
|
||||
child.emit('close', outcome.code ?? 0, null)
|
||||
})
|
||||
return child
|
||||
}
|
||||
return { spawnImpl, calls }
|
||||
}
|
||||
|
||||
const MAC = { platform: 'darwin', home: '/Users/u', readdir: () => [] }
|
||||
const WIN = {
|
||||
platform: 'win32',
|
||||
home: 'C:\\Users\\u',
|
||||
env: { APPDATA: 'C:\\Users\\u\\AppData\\Roaming', Path: 'C:\\Windows\\system32;C:\\Program Files\\nodejs' },
|
||||
}
|
||||
|
||||
/** The launcher npm's cmd-shim writes for a JavaScript bin. */
|
||||
const JS_SHIM = `@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\\node.exe" (
|
||||
SET "_prog=%dp0%\\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js" %*
|
||||
`
|
||||
|
||||
test('reads the version claude --version prints', () => {
|
||||
assert.equal(parseClaudeVersion('2.1.3 (Claude Code)\n'), '2.1.3')
|
||||
assert.equal(parseClaudeVersion('1.0.0-beta.2 (Claude Code)'), '1.0.0-beta.2')
|
||||
assert.equal(parseClaudeVersion('command not found'), undefined)
|
||||
assert.equal(parseClaudeVersion(undefined), undefined)
|
||||
})
|
||||
|
||||
test('finds the CLI where each platform installs it', () => {
|
||||
// macOS: the native installer wins over an nvm-installed npm copy.
|
||||
const mac = filesystem(['/Users/u/.local/bin/claude', '/Users/u/.nvm/versions/node/v22.1.0/bin/claude'])
|
||||
assert.equal(locateClaudeBinary({ ...MAC, env: {}, exists: mac.exists }), '/Users/u/.local/bin/claude')
|
||||
// nvm versions are tried newest first.
|
||||
const nvm = filesystem(['/Users/u/.nvm/versions/node/v9.0.0/bin/claude', '/Users/u/.nvm/versions/node/v20.3.1/bin/claude'])
|
||||
assert.equal(
|
||||
locateClaudeBinary({ ...MAC, env: {}, exists: nvm.exists, readdir: () => ['v9.0.0', 'v20.3.1', 'not-a-version'] }),
|
||||
'/Users/u/.nvm/versions/node/v20.3.1/bin/claude',
|
||||
)
|
||||
// Windows: npm's launcher under %APPDATA%\npm.
|
||||
const win = filesystem(['C:\\Users\\u\\AppData\\Roaming\\npm\\claude.cmd'])
|
||||
assert.equal(locateClaudeBinary({ ...WIN, exists: win.exists }), 'C:\\Users\\u\\AppData\\Roaming\\npm\\claude.cmd')
|
||||
assert.ok(claudeBinaryCandidates(WIN).includes('C:\\Users\\u\\.local\\bin\\claude.exe'))
|
||||
// Nothing installed anywhere.
|
||||
assert.equal(locateClaudeBinary({ ...MAC, env: { PATH: '/usr/bin' }, exists: () => false }), undefined)
|
||||
})
|
||||
|
||||
test('PATH is searched with the platform rules, including Windows Path spelling', () => {
|
||||
const win = filesystem(['D:\\tools\\claude.exe'])
|
||||
assert.equal(searchPath(['claude.exe', 'claude.cmd'], { platform: 'win32', env: { Path: 'C:\\x;"D:\\tools"' }, exists: win.exists }), 'D:\\tools\\claude.exe')
|
||||
const mac = filesystem(['/opt/bin/claude'])
|
||||
assert.equal(locateClaudeBinary({ ...MAC, env: { PATH: '/usr/bin:/opt/bin' }, exists: mac.exists }), '/opt/bin/claude')
|
||||
})
|
||||
|
||||
test('a configured path wins when it exists and reports absence when it does not', () => {
|
||||
const fs = filesystem(['/custom/claude', '/Users/u/.local/bin/claude'])
|
||||
assert.equal(locateClaudeBinary({ ...MAC, explicit: '/custom/claude', env: {}, exists: fs.exists }), '/custom/claude')
|
||||
assert.equal(locateClaudeBinary({ ...MAC, explicit: '/missing/claude', env: {}, exists: fs.exists }), undefined)
|
||||
})
|
||||
|
||||
test('a Windows npm launcher is started through the program it forwards to, never a shell', () => {
|
||||
const shim = 'C:\\Users\\u\\AppData\\Roaming\\npm\\claude.cmd'
|
||||
const cli = 'C:\\Users\\u\\AppData\\Roaming\\npm\\node_modules\\@anthropic-ai\\claude-code\\cli.js'
|
||||
const fs = filesystem([shim, cli])
|
||||
assert.deepEqual(resolveSpawnCommand(shim, { platform: 'win32', exists: fs.exists, readFile: () => JS_SHIM }), { command: 'node', args: [cli] })
|
||||
|
||||
// A node.exe beside the launcher is the one npm itself would use.
|
||||
fs.set.add('C:\\Users\\u\\AppData\\Roaming\\npm\\node.exe')
|
||||
assert.equal(resolveSpawnCommand(shim, { platform: 'win32', exists: fs.exists, readFile: () => JS_SHIM }).command, 'C:\\Users\\u\\AppData\\Roaming\\npm\\node.exe')
|
||||
|
||||
// A package that ships a native binary: the launcher points at the .exe.
|
||||
const exe = 'C:\\Users\\u\\AppData\\Roaming\\npm\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe'
|
||||
fs.set.add(exe)
|
||||
const nativeShim = '@ECHO off\r\n"%~dp0\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe" %*\r\n'
|
||||
assert.deepEqual(resolveSpawnCommand(shim, { platform: 'win32', exists: fs.exists, readFile: () => nativeShim }), { command: exe, args: [] })
|
||||
|
||||
// A launcher whose program is gone asks for a reinstall instead of failing obscurely.
|
||||
assert.throws(() => resolveSpawnCommand(shim, { platform: 'win32', exists: candidate => candidate === shim, readFile: () => JS_SHIM }), /reinstall/u)
|
||||
|
||||
// Everything else starts as is.
|
||||
assert.deepEqual(resolveSpawnCommand('C:\\Users\\u\\.local\\bin\\claude.exe', { platform: 'win32' }), { command: 'C:\\Users\\u\\.local\\bin\\claude.exe', args: [] })
|
||||
assert.deepEqual(resolveSpawnCommand('/usr/local/bin/claude', { platform: 'darwin' }), { command: '/usr/local/bin/claude', args: [] })
|
||||
})
|
||||
|
||||
test('the program directory joins PATH so a node launcher finds node', () => {
|
||||
assert.equal(withProgramDirOnPath({ PATH: '/usr/bin' }, '/opt/homebrew/bin/claude', 'darwin').PATH, '/opt/homebrew/bin:/usr/bin')
|
||||
assert.equal(withProgramDirOnPath({ PATH: '/opt/homebrew/bin' }, '/opt/homebrew/bin/claude', 'darwin').PATH, '/opt/homebrew/bin')
|
||||
assert.equal(withProgramDirOnPath({ Path: 'C:\\Windows' }, 'C:\\npm\\npm.cmd', 'win32').Path, 'C:\\npm;C:\\Windows')
|
||||
assert.equal(withProgramDirOnPath({ PATH: '/usr/bin' }, 'claude', 'darwin').PATH, '/usr/bin')
|
||||
})
|
||||
|
||||
test('finds npm on PATH first, then beside the host Node and in the usual places', () => {
|
||||
const fs = filesystem(['/usr/bin/npm', '/opt/homebrew/bin/npm'])
|
||||
assert.equal(locateNpm({ ...MAC, env: { PATH: '/usr/bin' }, execPath: '/x/node', exists: fs.exists }), '/usr/bin/npm')
|
||||
assert.equal(locateNpm({ ...MAC, env: { PATH: '' }, execPath: '/x/node', exists: fs.exists }), '/opt/homebrew/bin/npm')
|
||||
const win = filesystem(['C:\\Program Files\\nodejs\\npm.cmd'])
|
||||
assert.equal(locateNpm({ ...WIN, env: { Path: 'C:\\Windows' }, execPath: 'C:\\app\\dsh.exe', exists: win.exists }), 'C:\\Program Files\\nodejs\\npm.cmd')
|
||||
assert.equal(locateNpm({ ...MAC, env: {}, execPath: '/x/node', exists: () => false }), undefined)
|
||||
})
|
||||
|
||||
test('an npm failure is classified so the panel can say what to do', () => {
|
||||
assert.equal(explainNpmFailure({ code: 243, stderr: 'npm error code EACCES\nnpm error syscall mkdir' }).code, 'permission')
|
||||
assert.equal(explainNpmFailure({ code: 1, stderr: 'npm error code EPERM' }).code, 'permission')
|
||||
assert.equal(explainNpmFailure({ code: 1, stderr: 'npm error code ENOTFOUND' }).code, 'network')
|
||||
assert.equal(explainNpmFailure({ code: null, error: new Error('timed out after 900s') }).code, 'timeout')
|
||||
const other = explainNpmFailure({ code: 7, stderr: '' })
|
||||
assert.deepEqual(other, { code: 'failed', detail: 'npm exited with code 7' })
|
||||
})
|
||||
|
||||
test('detects an installed CLI and its version', async () => {
|
||||
const fs = filesystem(['/Users/u/.local/bin/claude'])
|
||||
const { spawnImpl, calls } = scriptedSpawn(() => ({ stdout: '2.1.3 (Claude Code)\n' }))
|
||||
const cli = createClaudeCliManager({ ...MAC, env: { PATH: '/usr/bin' }, exists: fs.exists, spawnImpl, configDir: '/tmp/cfg' })
|
||||
const status = await cli.status()
|
||||
assert.equal(status.installed, true)
|
||||
assert.equal(status.version, '2.1.3')
|
||||
assert.equal(status.path, '/Users/u/.local/bin/claude')
|
||||
assert.equal(status.command, CLAUDE_INSTALL_COMMAND)
|
||||
assert.equal(status.install.state, 'idle')
|
||||
assert.deepEqual(calls[0].args, ['--version'])
|
||||
// The probe runs in the plugin's isolated config home, never the user's.
|
||||
assert.equal(calls[0].options.env.CLAUDE_CONFIG_DIR, '/tmp/cfg')
|
||||
assert.equal(calls[0].options.shell, undefined)
|
||||
|
||||
// A cached read does not spawn again; a forced one does.
|
||||
await cli.status()
|
||||
assert.equal(calls.length, 1)
|
||||
await cli.status({ force: true })
|
||||
assert.equal(calls.length, 2)
|
||||
assert.equal(await cli.binary(), '/Users/u/.local/bin/claude')
|
||||
})
|
||||
|
||||
test('a CLI that is found but cannot run is reported with its output', async () => {
|
||||
const fs = filesystem(['/Users/u/.local/bin/claude'])
|
||||
const { spawnImpl } = scriptedSpawn(() => ({ code: 127, stderr: 'env: node: No such file or directory' }))
|
||||
const cli = createClaudeCliManager({ ...MAC, env: {}, exists: fs.exists, spawnImpl })
|
||||
const status = await cli.status()
|
||||
assert.equal(status.installed, true)
|
||||
assert.equal(status.version, undefined)
|
||||
assert.match(status.error, /env: node/u)
|
||||
})
|
||||
|
||||
test('without a CLI anywhere it asks npm for its global bin before giving up', async () => {
|
||||
const fs = filesystem(['/usr/bin/npm', '/Users/u/.npm-prefix/bin/claude'])
|
||||
const { spawnImpl, calls } = scriptedSpawn((command, args) => {
|
||||
if (command === '/usr/bin/npm' && args.join(' ') === 'prefix -g') return { stdout: '/Users/u/.npm-prefix\n' }
|
||||
if (args[0] === '--version') return { stdout: '2.0.0 (Claude Code)' }
|
||||
return { code: 1 }
|
||||
})
|
||||
const cli = createClaudeCliManager({ ...MAC, env: { PATH: '/usr/bin' }, exists: fs.exists, spawnImpl })
|
||||
const status = await cli.status()
|
||||
assert.equal(status.path, '/Users/u/.npm-prefix/bin/claude')
|
||||
assert.equal(status.version, '2.0.0')
|
||||
// npm runs with its own directory on PATH so its `env node` resolves.
|
||||
assert.match(calls[0].options.env.PATH, /^\/usr\/bin/u)
|
||||
|
||||
fs.set.delete('/Users/u/.npm-prefix/bin/claude')
|
||||
const missing = await cli.status({ force: true })
|
||||
assert.equal(missing.installed, false)
|
||||
assert.equal(await cli.binary(), 'claude', 'the runner then reports the CLI as missing')
|
||||
})
|
||||
|
||||
test('installs with npm install -g and detects the result', async () => {
|
||||
const fs = filesystem(['/usr/bin/npm'])
|
||||
const { spawnImpl, calls } = scriptedSpawn((command, args) => {
|
||||
if (args.join(' ') === 'prefix -g') return { stdout: '/usr\n' }
|
||||
if (args.join(' ') === 'install -g @anthropic-ai/claude-code') {
|
||||
return { effect: () => fs.set.add('/usr/bin/claude'), stdout: 'added 3 packages in 4s\n' }
|
||||
}
|
||||
if (args[0] === '--version') return { stdout: '2.1.3 (Claude Code)\n' }
|
||||
return { code: 1 }
|
||||
})
|
||||
const cli = createClaudeCliManager({ ...MAC, env: { PATH: '/usr/bin' }, exists: fs.exists, spawnImpl })
|
||||
assert.equal((await cli.status()).installed, false)
|
||||
|
||||
const started = cli.install()
|
||||
assert.equal(started.state, 'running')
|
||||
assert.equal(cli.install().state, 'running', 'a second click joins the install in flight')
|
||||
assert.equal((await cli.status()).install.state, 'running')
|
||||
await cli.settled()
|
||||
|
||||
const status = await cli.status()
|
||||
assert.equal(status.install.state, 'succeeded')
|
||||
assert.equal(status.installed, true)
|
||||
assert.equal(status.version, '2.1.3')
|
||||
assert.equal(calls.filter(call => call.args.join(' ') === 'install -g @anthropic-ai/claude-code').length, 1)
|
||||
assert.equal(calls.find(call => call.args[0] === 'install').options.shell, false)
|
||||
})
|
||||
|
||||
test('on Windows npm runs through its .cmd launcher with constant arguments', async () => {
|
||||
const npm = 'C:\\Program Files\\nodejs\\npm.cmd'
|
||||
const fs = filesystem([npm])
|
||||
const { spawnImpl, calls } = scriptedSpawn(() => ({ code: 1, stderr: 'npm error code EPERM\nnpm error syscall rename' }))
|
||||
const cli = createClaudeCliManager({ ...WIN, execPath: 'C:\\app\\dsh.exe', exists: fs.exists, spawnImpl })
|
||||
cli.install()
|
||||
await cli.settled()
|
||||
const call = calls.find(entry => entry.args[0] === 'install')
|
||||
assert.equal(call.command, `"${npm}"`)
|
||||
assert.deepEqual(call.args, ['install', '-g', '@anthropic-ai/claude-code'])
|
||||
assert.equal(call.options.shell, true)
|
||||
const status = await cli.status()
|
||||
assert.equal(status.platform, 'win32')
|
||||
assert.equal(status.install.state, 'failed')
|
||||
assert.equal(status.install.code, 'permission')
|
||||
assert.match(status.install.detail, /EPERM/u)
|
||||
})
|
||||
|
||||
test('without npm the install fails at once and says why', async () => {
|
||||
const { spawnImpl, calls } = scriptedSpawn(() => ({ code: 1 }))
|
||||
const cli = createClaudeCliManager({ ...MAC, env: { PATH: '' }, execPath: '/x/node', exists: () => false, spawnImpl })
|
||||
const result = cli.install()
|
||||
assert.equal(result.state, 'failed')
|
||||
assert.equal(result.code, 'npm-missing')
|
||||
assert.equal(calls.length, 0)
|
||||
})
|
||||
|
||||
test('a runner whose CLI is missing says to install it', async () => {
|
||||
const { spawnImpl } = scriptedSpawn(() => ({ error: Object.assign(new Error('spawn claude ENOENT'), { code: 'ENOENT' }) }))
|
||||
const runner = createClaudeRunner({
|
||||
binary: async () => 'claude',
|
||||
resolveCredential: async () => ({ baseUrl: 'https://hk.geek2api.com', token: 'sk-k' }),
|
||||
spawnImpl,
|
||||
})
|
||||
await assert.rejects(() => runner.run({ prompt: 'x' }), error => error.message === CLAUDE_MISSING_MESSAGE)
|
||||
})
|
||||
|
||||
test('a runner on Windows starts the program behind the npm launcher', async () => {
|
||||
const shim = 'C:\\npm\\claude.cmd'
|
||||
const { spawnImpl, calls } = scriptedSpawn(() => ({ stdout: `${JSON.stringify({ is_error: false, result: 'ok' })}\n` }))
|
||||
const runner = createClaudeRunner({
|
||||
binary: async () => shim,
|
||||
resolveCredential: async () => ({ baseUrl: 'https://hk.geek2api.com', token: 'sk-k' }),
|
||||
spawnImpl,
|
||||
platform: 'win32',
|
||||
})
|
||||
// The real launcher is read from disk; this one does not exist, so the
|
||||
// runner refuses before spawning instead of handing argv to cmd.exe.
|
||||
await assert.rejects(() => runner.run({ prompt: 'x' }), /reinstall/u)
|
||||
assert.equal(calls.length, 0)
|
||||
})
|
||||
|
||||
test('the RPC surface reports and starts the CLI install', async () => {
|
||||
const seen = []
|
||||
const claudeCli = {
|
||||
status: async options => {
|
||||
seen.push(['status', options])
|
||||
return { installed: false, command: CLAUDE_INSTALL_COMMAND, install: { state: seen.some(([kind]) => kind === 'install') ? 'running' : 'idle' } }
|
||||
},
|
||||
install: () => {
|
||||
seen.push(['install'])
|
||||
return { state: 'running' }
|
||||
},
|
||||
}
|
||||
const handler = createGeek2APIRpc({ ring: {}, balance: {}, hosts: () => ({}), preference: {}, claudeCli })
|
||||
const status = await handler('claude-cli/status', { force: true })
|
||||
assert.equal(status.ok, true)
|
||||
assert.equal(status.value.installed, false)
|
||||
assert.deepEqual(seen[0], ['status', { force: true }])
|
||||
const installed = await handler('claude-cli/install', {})
|
||||
assert.equal(installed.value.install.state, 'running')
|
||||
|
||||
const without = createGeek2APIRpc({ ring: {}, balance: {}, hosts: () => ({}), preference: {} })
|
||||
const refused = await without('claude-cli/status', {})
|
||||
assert.equal(refused.ok, false)
|
||||
assert.match(refused.error.message, /unavailable/u)
|
||||
})
|
||||
@@ -0,0 +1,294 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { createServer, request as httpRequest } from 'node:http'
|
||||
import { dirname } from 'node:path'
|
||||
import test from 'node:test'
|
||||
|
||||
import { createClaudeSearchBridge, MCP_SEARCH_TOOL } from '../src/claude-search-mcp.js'
|
||||
import { createClaudeRunner } from '../src/claude-cli.js'
|
||||
|
||||
const SOURCE = { url: 'https://nodejs.org/en/blog/release', title: 'Node.js releases', snippet: 'release notes' }
|
||||
const SEARCH_RESULT = { content: 'Latest release notes.', sources: [SOURCE], truncated: false }
|
||||
|
||||
async function bridgeFixture(t, options = {}) {
|
||||
const bridge = await createClaudeSearchBridge({ search: async () => SEARCH_RESULT, ...options })
|
||||
t.after(() => bridge.close())
|
||||
const config = JSON.parse(await readFile(bridge.configPath, 'utf8'))
|
||||
const [name, server] = Object.entries(config.mcpServers)[0]
|
||||
let id = 0
|
||||
const send = async (message, extra = {}) => {
|
||||
const response = await fetch(server.url, {
|
||||
method: 'POST',
|
||||
headers: { ...server.headers, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...extra.headers },
|
||||
body: typeof message === 'string' ? message : JSON.stringify(message),
|
||||
...extra,
|
||||
...(extra.headers === undefined ? {} : { headers: { ...server.headers, 'Content-Type': 'application/json', ...extra.headers } }),
|
||||
})
|
||||
const raw = await response.text()
|
||||
return { status: response.status, body: raw === '' ? undefined : JSON.parse(raw) }
|
||||
}
|
||||
const rpc = (method, params, extra) => send({ jsonrpc: '2.0', id: ++id, method, ...(params === undefined ? {} : { params }) }, extra)
|
||||
const search = (args = { query: 'Node.js release' }, extra) => rpc('tools/call', { name: MCP_SEARCH_TOOL, arguments: args }, extra)
|
||||
return { bridge, config, server, name, send, rpc, search }
|
||||
}
|
||||
|
||||
const waitFor = (promise, limit = 1000) => Promise.race([promise, new Promise((_resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('test wait timed out')), limit)
|
||||
timer.unref()
|
||||
})])
|
||||
|
||||
/** Send chunked data without a Content-Length header. */
|
||||
function chunked(url, headers, parts) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = httpRequest(url, { method: 'POST', headers }, response => {
|
||||
response.resume()
|
||||
response.on('end', () => resolve(response.statusCode))
|
||||
})
|
||||
request.on('error', reject)
|
||||
for (const part of parts) request.write(part)
|
||||
request.end()
|
||||
})
|
||||
}
|
||||
|
||||
test('private per-run config exposes one authenticated loopback HTTP search server, never an API key', async t => {
|
||||
const fx = await bridgeFixture(t)
|
||||
assert.match(fx.name, /^geek2api_search_[a-f0-9]{12}$/u)
|
||||
assert.equal(fx.bridge.toolName, `mcp__${fx.name}__web_search`)
|
||||
assert.match(fx.server.url, /^http:\/\/127\.0\.0\.1:\d+\/mcp$/u)
|
||||
assert.equal(fx.server.type, 'http')
|
||||
assert.match(fx.server.headers.Authorization, /^Bearer [a-f0-9]{64}$/u)
|
||||
assert.doesNotMatch(JSON.stringify(fx.config), /ANTHROPIC_|GEEK2API_API_KEY|cf\.api\.fan/u)
|
||||
assert.doesNotMatch(fx.bridge.instructions, /127\.0\.0\.1|Bearer/u)
|
||||
if (process.platform !== 'win32') {
|
||||
assert.equal((await stat(fx.bridge.configPath)).mode & 0o777, 0o600)
|
||||
assert.equal((await stat(dirname(fx.bridge.configPath))).mode & 0o777, 0o700)
|
||||
}
|
||||
const init = await fx.rpc('initialize', { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'test', version: '1' } })
|
||||
assert.equal(init.body.result.protocolVersion, '2025-06-18')
|
||||
assert.deepEqual(init.body.result.capabilities, { tools: {} })
|
||||
assert.equal((await fx.send({ jsonrpc: '2.0', method: 'notifications/initialized' })).status, 202)
|
||||
assert.deepEqual((await fx.rpc('ping')).body.result, {})
|
||||
const list = (await fx.rpc('tools/list')).body.result.tools
|
||||
assert.equal(list.length, 1)
|
||||
assert.equal(list[0].name, 'web_search')
|
||||
assert.equal(list[0].annotations.readOnlyHint, true)
|
||||
assert.equal(list[0].inputSchema.additionalProperties, false)
|
||||
assert.doesNotMatch(JSON.stringify(list), new RegExp(fx.server.headers.Authorization.slice(7), 'u'))
|
||||
// A newer CLI's discover probe cleanly falls back to legacy initialize.
|
||||
assert.equal((await fx.rpc('server/discover')).body.error.code, -32601)
|
||||
})
|
||||
|
||||
test('authenticated search returns bounded source projections and an untrusted-data notice, using a live backend choice', async t => {
|
||||
let backend = 'claude'
|
||||
const calls = []
|
||||
const fx = await bridgeFixture(t, {
|
||||
backend: () => backend,
|
||||
search: async (request, signal) => { calls.push({ request, signal, backend }); return { ...SEARCH_RESULT, sources: [SOURCE, { ...SOURCE, url: 'https://example.org/' }] } },
|
||||
})
|
||||
const result = (await fx.search({ query: ' Node release ', max_results: 1 })).body.result
|
||||
assert.equal(result.isError, undefined)
|
||||
assert.match(result.content[0].text, /^External web content follows/u)
|
||||
const value = JSON.parse(result.content[0].text.split('\n\n')[1])
|
||||
assert.deepEqual(value.sources, [SOURCE])
|
||||
assert.equal(value.backend, 'claude')
|
||||
assert.equal(value.truncated, true)
|
||||
assert.deepEqual(calls[0].request, { query: 'Node release', maxResults: 1 })
|
||||
assert.ok(calls[0].signal instanceof AbortSignal)
|
||||
backend = 'gpt'
|
||||
assert.equal(JSON.parse((await fx.search()).body.result.content[0].text.split('\n\n')[1]).backend, 'gpt')
|
||||
assert.equal(calls[1].backend, 'gpt')
|
||||
})
|
||||
|
||||
test('bad capability, foreign Host/Origin, other paths, and unsupported HTTP methods never invoke search', async t => {
|
||||
let calls = 0
|
||||
const fx = await bridgeFixture(t, { search: async () => { calls++; return SEARCH_RESULT } })
|
||||
assert.equal((await fx.search(undefined, { headers: { Authorization: 'Bearer wrong' } })).status, 401)
|
||||
// undici normalizes Host to the target; use raw HTTP to test rebinding.
|
||||
assert.equal(await chunked(fx.server.url, { ...fx.server.headers, Host: 'attacker.example', 'Content-Type': 'application/json' }, [JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })]), 403)
|
||||
assert.equal((await fx.search(undefined, { headers: { Origin: 'https://attacker.example' } })).status, 403)
|
||||
const get = await fetch(fx.server.url, { headers: fx.server.headers })
|
||||
assert.equal(get.status, 405)
|
||||
assert.equal(get.headers.get('allow'), 'POST')
|
||||
const del = await fetch(fx.server.url, { method: 'DELETE', headers: fx.server.headers })
|
||||
assert.equal(del.status, 405)
|
||||
assert.equal((await fetch(fx.server.url.replace('/mcp', '/other'), { method: 'POST', headers: fx.server.headers })).status, 404)
|
||||
assert.equal(calls, 0)
|
||||
})
|
||||
|
||||
test('malformed/batch JSON-RPC, unknown tools, and model-supplied backend/host/key fields are refused', async t => {
|
||||
let calls = 0
|
||||
const fx = await bridgeFixture(t, { search: async () => { calls++; return SEARCH_RESULT } })
|
||||
assert.equal((await fx.send('not JSON')).body.error.code, -32700)
|
||||
assert.equal((await fx.send([])).body.error.code, -32600)
|
||||
for (const params of [42, null, false, 'scalar']) assert.equal((await fx.rpc('ping', params)).body.error.code, -32600)
|
||||
assert.equal((await fx.send({ jsonrpc: '2.0', id: {}, method: 'ping' })).body.error.code, -32600)
|
||||
assert.equal((await fx.rpc('tools/call', { name: 'shell', arguments: { command: 'echo secret' } })).body.error.code, -32602)
|
||||
for (const args of [null, {}, { query: '' }, { query: 'q'.repeat(2001) }, { query: 'q', backend: 'gpt' }, { query: 'q', host: 'https://attacker/' }, { query: 'q', key: 'x' }, { query: 'q', sessionId: 'attacker' }, { query: 'q', max_results: 9 }, { query: 'q', max_results: 1.1 }]) {
|
||||
assert.equal((await fx.search(args)).body.error.code, -32602)
|
||||
}
|
||||
assert.equal((await fx.send({ jsonrpc: '2.0', method: 'tools/call', params: { name: 'web_search', arguments: { query: 'q' } } })).status, 400)
|
||||
assert.equal(calls, 0)
|
||||
})
|
||||
|
||||
test('declared and chunked oversized bodies are rejected before paid work', async t => {
|
||||
let calls = 0
|
||||
const fx = await bridgeFixture(t, { search: async () => { calls++; return SEARCH_RESULT } })
|
||||
const oversized = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'web_search', arguments: { query: 'x'.repeat(20_000) } } })
|
||||
assert.equal((await fx.send(oversized)).status, 413)
|
||||
assert.equal(await chunked(fx.server.url, { ...fx.server.headers, 'Content-Type': 'application/json' }, [oversized.slice(0, 8000), oversized.slice(8000)]), 413)
|
||||
assert.equal((await fx.search(undefined, { headers: { 'Content-Type': 'text/plain' } })).status, 415)
|
||||
assert.equal(calls, 0)
|
||||
})
|
||||
|
||||
test('tool errors are explicit and sanitized; source and summary output is bounded and host-redacted', async t => {
|
||||
let fail = true
|
||||
const secret = 'sk-host-only-not-in-mcp-output'
|
||||
const fx = await bridgeFixture(t, {
|
||||
sanitize: text => text.split(secret).join('[redacted]'),
|
||||
search: async () => {
|
||||
if (fail) throw new Error(`remote echoed ${secret}`)
|
||||
return { content: `${secret}${'x'.repeat(6000)}`, sources: [{ ...SOURCE, title: secret, snippet: 's'.repeat(800) }, { url: 'file:///etc/passwd' }, { url: 'https://user:password@example.com/' }] }
|
||||
},
|
||||
})
|
||||
const error = (await fx.search()).body.result
|
||||
assert.equal(error.isError, true)
|
||||
assert.doesNotMatch(JSON.stringify(error), /sk-host-only|remote echoed/u)
|
||||
fail = false
|
||||
const success = (await fx.search()).body.result
|
||||
assert.doesNotMatch(JSON.stringify(success), /sk-host-only/u)
|
||||
const projection = JSON.parse(success.content[0].text.split('\n\n')[1])
|
||||
assert.equal(projection.sources.length, 1)
|
||||
assert.ok(projection.summary.length <= 4000)
|
||||
assert.ok(projection.sources[0].snippet.length <= 500)
|
||||
})
|
||||
|
||||
test('per-run call budget and concurrency caps bound searches but allow cancellation control traffic', async t => {
|
||||
let release
|
||||
const slow = new Promise(resolve => { release = resolve })
|
||||
let calls = 0
|
||||
const fx = await bridgeFixture(t, { maxCalls: 2, search: async () => { calls++; await slow; return SEARCH_RESULT } })
|
||||
const first = fx.search()
|
||||
const second = fx.search()
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
const capped = (await fx.search()).body.result
|
||||
assert.equal(capped.isError, true)
|
||||
assert.match(capped.content[0].text, /budget|already running/u)
|
||||
assert.equal((await fx.send({ jsonrpc: '2.0', method: 'notifications/initialized' })).status, 202)
|
||||
release()
|
||||
assert.equal((await first).body.result.isError, undefined)
|
||||
assert.equal((await second).body.result.isError, undefined)
|
||||
assert.equal(calls, 2)
|
||||
assert.equal((await fx.search()).body.result.isError, true)
|
||||
})
|
||||
|
||||
test('notifications/cancelled and the end-to-end deadline abort providers without leaking errors', async t => {
|
||||
const signals = []
|
||||
let started
|
||||
let start = new Promise(resolve => { started = resolve })
|
||||
const fx = await bridgeFixture(t, { timeoutMs: 60, search: async (_request, signal) => { signals.push(signal); started(); return new Promise(() => {}) } })
|
||||
const pending = fx.send({ jsonrpc: '2.0', id: 'cancel-me', method: 'tools/call', params: { name: 'web_search', arguments: { query: 'q' } } })
|
||||
await waitFor(start)
|
||||
const cancelled = await fx.send({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: 'cancel-me' } })
|
||||
assert.equal(cancelled.status, 202)
|
||||
assert.equal((await pending).body.result.isError, true)
|
||||
assert.equal(signals[0].aborted, true)
|
||||
start = new Promise(resolve => { started = resolve })
|
||||
const timedOut = fx.search()
|
||||
await waitFor(start)
|
||||
const outcome = await waitFor(timedOut)
|
||||
assert.equal(outcome.body.result.isError, true)
|
||||
assert.equal(signals[1].aborted, true)
|
||||
})
|
||||
|
||||
test('HTTP disconnect aborts one search and close revokes capability, cancels work, and deletes config idempotently', async t => {
|
||||
let started
|
||||
const ready = new Promise(resolve => { started = resolve })
|
||||
let signal
|
||||
const fx = await bridgeFixture(t, { search: async (_args, abort) => { signal = abort; started(); return new Promise(() => {}) } })
|
||||
const caller = new AbortController()
|
||||
const pending = fx.search(undefined, { signal: caller.signal }).catch(() => undefined)
|
||||
await waitFor(ready)
|
||||
caller.abort()
|
||||
await pending
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
assert.equal(signal.aborted, true)
|
||||
const path = fx.bridge.configPath
|
||||
await fx.bridge.close()
|
||||
await fx.bridge.close()
|
||||
await assert.rejects(readFile(path), error => error.code === 'ENOENT')
|
||||
await assert.rejects(fetch(fx.server.url, { headers: fx.server.headers }))
|
||||
})
|
||||
|
||||
test('callback fallback hostname titles and long URLs obey output bounds', async t => {
|
||||
const fx = await bridgeFixture(t, { search: async () => ({ sources: [
|
||||
{ url: `https://${'a'.repeat(3000)}.example/` },
|
||||
{ url: `https://${'b'.repeat(10_000)}.example/` },
|
||||
] }) })
|
||||
const value = JSON.parse((await fx.search()).body.result.content[0].text.split('\n\n')[1])
|
||||
assert.equal(value.sources.length, 1)
|
||||
assert.ok(value.sources[0].title.length <= 200)
|
||||
assert.ok(value.sources[0].url.length <= 4000)
|
||||
})
|
||||
|
||||
test('abort during each filesystem setup phase revokes the real listener immediately and unload owns late cleanup', async t => {
|
||||
for (const phase of ['mkdtemp', 'realpath', 'writeFile']) {
|
||||
const controller = new AbortController()
|
||||
let entered
|
||||
let release
|
||||
const ready = new Promise(resolve => { entered = resolve })
|
||||
const blocked = new Promise(resolve => { release = resolve })
|
||||
t.after(() => release())
|
||||
const fs = { mkdtemp, realpath, rm, writeFile }
|
||||
const original = fs[phase]
|
||||
let once = false
|
||||
let directory
|
||||
let server
|
||||
fs[phase] = async (...args) => {
|
||||
if (phase === 'writeFile') {
|
||||
// Simulate a filesystem operation that cannot honour cancellation.
|
||||
args[2] = { ...args[2], signal: undefined }
|
||||
}
|
||||
const value = phase === 'writeFile' ? undefined : await original(...args)
|
||||
if (phase === 'mkdtemp') directory = value
|
||||
else if (phase === 'realpath') directory = args[0]
|
||||
else directory = dirname(args[0])
|
||||
if (!once) { once = true; entered(); await blocked }
|
||||
if (phase === 'writeFile') await original(...args)
|
||||
return value
|
||||
}
|
||||
const runner = createClaudeRunner({
|
||||
resolveCredential: async () => ({ baseUrl: 'https://gw.example', token: 'sk-local-only-dummy' }),
|
||||
createSearchBridge: ({ signal }) => createClaudeSearchBridge({ search: async () => SEARCH_RESULT, signal, fs, serverFactory: listener => { server = createServer(listener); return server } }),
|
||||
spawnImpl: () => assert.fail('cancelled setup must not spawn'),
|
||||
})
|
||||
const pending = runner.run({ prompt: 'x', signal: controller.signal })
|
||||
pending.catch(() => undefined)
|
||||
await waitFor(ready)
|
||||
assert.equal(server.listening, true)
|
||||
controller.abort()
|
||||
await assert.rejects(pending, /aborted/u)
|
||||
assert.equal(server.listening, false, `${phase}: listener closed before filesystem completion`)
|
||||
let unloaded = false
|
||||
const unloading = runner.close().then(() => { unloaded = true })
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
assert.equal(unloaded, false, `${phase}: unload must still own the pending factory`)
|
||||
release()
|
||||
await waitFor(unloading)
|
||||
await assert.rejects(stat(directory), error => error.code === 'ENOENT')
|
||||
}
|
||||
})
|
||||
|
||||
test('concurrent bridges have independent capabilities, preferences, and lifetimes; run abort closes its bridge', async t => {
|
||||
const controller = new AbortController()
|
||||
const one = await bridgeFixture(t, { backend: () => 'claude', signal: controller.signal })
|
||||
const two = await bridgeFixture(t, { backend: () => 'gpt' })
|
||||
assert.notEqual(one.server.url, two.server.url)
|
||||
assert.notEqual(one.server.headers.Authorization, two.server.headers.Authorization)
|
||||
assert.equal((await one.search(undefined, { headers: two.server.headers })).status, 401)
|
||||
controller.abort()
|
||||
await one.bridge.close()
|
||||
assert.equal((await two.search()).body.result.isError, undefined)
|
||||
const value = JSON.parse((await two.search()).body.result.content[0].text.split('\n\n')[1])
|
||||
assert.equal(value.backend, 'gpt')
|
||||
await assert.rejects(createClaudeSearchBridge({ search: async () => SEARCH_RESULT, signal: controller.signal }), /aborted/u)
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
|
||||
import { apply } from '../src/index.js'
|
||||
import { fakeCredentials } from './helpers.mjs'
|
||||
|
||||
const RELAY_KEY = 'sk-plugin-only-mcp-relay-key-0001'
|
||||
|
||||
/** A CLI stand-in that actually calls the advertised MCP HTTP tool. */
|
||||
async function fakeCli(directory) {
|
||||
const record = join(directory, 'invocations.jsonl')
|
||||
const cli = join(directory, 'claude')
|
||||
await writeFile(cli, `#!/usr/bin/env node
|
||||
const { readFileSync, appendFileSync } = require('node:fs')
|
||||
const args = process.argv.slice(2)
|
||||
if (args.includes('--version')) { console.log('2.1.295 (Claude Code)'); process.exit(0) }
|
||||
process.stdin.resume()
|
||||
process.stdin.on('end', async () => {
|
||||
try {
|
||||
const path = args[args.indexOf('--mcp-config') + 1]
|
||||
let result = 'title without search'
|
||||
let tool
|
||||
if (args.includes('--mcp-config')) {
|
||||
const config = JSON.parse(readFileSync(path, 'utf8'))
|
||||
const [name, server] = Object.entries(config.mcpServers)[0]
|
||||
tool = 'mcp__' + name + '__web_search'
|
||||
const rpc = async (id, method, params) => {
|
||||
const response = await fetch(server.url, { method: 'POST', headers: { ...server.headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id, method, params }) })
|
||||
return response.json()
|
||||
}
|
||||
await rpc(1, 'initialize', { protocolVersion: '2025-11-25' })
|
||||
const list = await rpc(2, 'tools/list', {})
|
||||
if (list.result.tools[0].name !== 'web_search') throw new Error('wrong tool')
|
||||
const reply = await rpc(3, 'tools/call', { name: 'web_search', arguments: { query: 'latest Node.js release', max_results: 1 } })
|
||||
result = reply.result.content[0].text
|
||||
}
|
||||
appendFileSync(${JSON.stringify(record)}, JSON.stringify({ path: args.includes('--mcp-config') ? path : null, tool, args }) + '\\n')
|
||||
console.log(JSON.stringify({ type: 'stream_event', event: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: result } } }))
|
||||
console.log(JSON.stringify({ type: 'result', is_error: false, result, usage: { input_tokens: 1, output_tokens: 1 } }))
|
||||
} catch {
|
||||
console.log(JSON.stringify({ type: 'result', is_error: true, result: 'mock CLI MCP test failed' }))
|
||||
process.exitCode = 1
|
||||
}
|
||||
})
|
||||
`)
|
||||
await chmod(cli, 0o755)
|
||||
return { cli, record }
|
||||
}
|
||||
|
||||
function context() {
|
||||
const seen = { disposers: [] }
|
||||
const ctx = {
|
||||
credentials: fakeCredentials(),
|
||||
logger: { warn: () => {}, info: () => {} },
|
||||
llm: { registerAdapter: (_providers, adapter) => { seen.adapter = adapter; return () => {} }, registerConfigurableProviders: () => () => {} },
|
||||
// No web service: the CLI bridge must remain self-contained in headless profiles.
|
||||
get: name => name === 'agents' ? { currentInitiator: () => ({ session: { id: 'originating-dsh-session', requestContext: () => ({ provider: 'geek2api' }) } }) } : undefined,
|
||||
inject(names, callback) {
|
||||
if (names.includes('settings')) return callback({ settings: {
|
||||
installSection(_owner, _ns, _schema, base, hooks) { seen.current = { ...base }; hooks.setSource(() => seen.current) },
|
||||
update: async (_ns, patch) => { Object.assign(seen.current, patch) },
|
||||
} })
|
||||
if (names.includes('connection')) return callback({ effect: ctx.effect, connection: { rpc: { handle: (_channel, handler) => { seen.handler = handler; return () => {} } } } })
|
||||
if (names.includes('tools')) return callback({ tools: { register: () => () => {} } })
|
||||
},
|
||||
effect(callback) { const disposer = callback(); if (typeof disposer === 'function') seen.disposers.push(disposer); return disposer },
|
||||
}
|
||||
return { ctx, seen }
|
||||
}
|
||||
|
||||
const turn = async (adapter, purpose) => {
|
||||
const chunks = []
|
||||
for await (const chunk of adapter.stream({ provider: 'geek2api', model: 'claude-opus-5-5', purpose, messages: [{ role: 'user', content: [{ type: 'text', text: 'Search for a Node.js release' }] }] })) chunks.push(chunk)
|
||||
return chunks
|
||||
}
|
||||
|
||||
test('CLI MCP uses the selected backend even with DSH routing off and no web service, preserves session and redacts keys', async t => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'geek2api-mcp-wiring-'))
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
const { cli, record } = await fakeCli(dir)
|
||||
const { ctx, seen } = context()
|
||||
const original = globalThis.fetch
|
||||
const requests = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
if (String(url).endsWith('/health')) return Response.json({ status: 'ok' })
|
||||
const body = JSON.parse(init.body)
|
||||
const headers = new Headers(init.headers)
|
||||
requests.push({ url, body, key: headers.get('x-api-key') ?? headers.get('authorization')?.replace(/^Bearer /u, '') })
|
||||
if (url.endsWith('/messages')) return Response.json({ content: [
|
||||
{ type: 'web_search_tool_result', content: [{ type: 'web_search_result', url: 'https://nodejs.org/', title: 'Node.js' }] },
|
||||
{ type: 'text', text: `Public summary; remote echoed ${RELAY_KEY}` },
|
||||
] })
|
||||
if (url.endsWith('/responses')) return Response.json({ output: [
|
||||
{ type: 'web_search_call', action: { type: 'search', sources: [{ url: 'https://nodejs.org/' }] } },
|
||||
{ type: 'message', content: [{ type: 'output_text', text: 'GPT result', annotations: [{ type: 'url_citation', url: 'https://nodejs.org/', title: 'Node.js' }] }] },
|
||||
] })
|
||||
throw new Error('unexpected external request')
|
||||
}
|
||||
t.after(() => { globalThis.fetch = original })
|
||||
apply(ctx, { claudeCliPath: cli, claudeCliCwd: dir, claudeCliMode: 'read-only', claudeRuntime: 'cli' })
|
||||
t.after(async () => { for (const dispose of seen.disposers) await dispose() })
|
||||
await seen.handler('keys/add', { key: RELAY_KEY, label: 'relay' })
|
||||
assert.equal((await seen.handler('search/status')).value.searchProvider, 'default')
|
||||
assert.equal((await seen.handler('search/status')).value.available, false)
|
||||
|
||||
const ds = await turn(seen.adapter)
|
||||
assert.equal(ds.at(-1).reason.kind, 'stop')
|
||||
const dsText = ds.filter(c => c.type === 'text-delta').map(c => c.text).join('')
|
||||
assert.match(dsText, /Public summary/u)
|
||||
assert.doesNotMatch(dsText, /sk-plugin-only/u)
|
||||
assert.match(ds.filter(c => c.type === 'reasoning-delta').map(c => c.text).join(''), /Geek2API Claude(MCP/u)
|
||||
assert.equal(requests[0].body.model, 'claude-haiku-4-5-20251001')
|
||||
assert.equal(requests[0].key, RELAY_KEY)
|
||||
|
||||
await seen.handler('search/update', { searchBackend: 'gpt' })
|
||||
const gpt = await turn(seen.adapter)
|
||||
assert.equal(gpt.at(-1).reason.kind, 'stop')
|
||||
assert.equal(requests[1].body.model, 'gpt-6.1-sol')
|
||||
assert.equal(requests[1].body.prompt_cache_key, 'originating-dsh-session', 'captured before MCP HTTP callback loses agent scope')
|
||||
assert.equal(requests[1].key, RELAY_KEY)
|
||||
assert.match(gpt.filter(c => c.type === 'reasoning-delta').map(c => c.text).join(''), /Geek2API GPT(MCP/u)
|
||||
|
||||
await turn(seen.adapter, 'session-title')
|
||||
assert.equal(requests.length, 2, 'titles issue no search')
|
||||
const invocations = (await readFile(record, 'utf8')).trim().split('\n').map(JSON.parse)
|
||||
for (const invocation of invocations.slice(0, 2)) {
|
||||
assert.ok(invocation.args.includes(invocation.tool))
|
||||
assert.equal(invocation.args.includes('--dangerously-skip-permissions'), false)
|
||||
assert.equal(invocation.args[invocation.args.indexOf('--disallowedTools') + 1], 'WebSearch')
|
||||
await assert.rejects(readFile(invocation.path), error => error.code === 'ENOENT')
|
||||
assert.doesNotMatch(JSON.stringify(invocation), /sk-plugin-only/u)
|
||||
}
|
||||
assert.equal(invocations[2].path, null)
|
||||
assert.equal(invocations[2].args[invocations[2].args.indexOf('--disallowedTools') + 1], 'WebSearch')
|
||||
})
|
||||
@@ -0,0 +1,245 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
|
||||
import { apply } from '../src/index.js'
|
||||
import { fakeCredentials, singleKeyRecord } from './helpers.mjs'
|
||||
|
||||
/**
|
||||
* A stand-in for the `claude` binary: it records the argv and the environment
|
||||
* it was given, then prints the JSON payload the real CLI prints.
|
||||
*/
|
||||
function writeStubCli(dir) {
|
||||
const record = join(dir, 'invocation.json')
|
||||
const script = join(dir, 'claude-stub.mjs')
|
||||
writeFileSync(script, `#!/usr/bin/env node
|
||||
import { writeFileSync } from 'node:fs'
|
||||
let stdin = ''
|
||||
process.stdin.setEncoding('utf8')
|
||||
process.stdin.on('data', chunk => { stdin += chunk })
|
||||
process.stdin.on('end', () => {
|
||||
writeFileSync(${JSON.stringify(record)}, JSON.stringify({
|
||||
argv: process.argv.slice(2),
|
||||
stdin,
|
||||
baseUrl: process.env.ANTHROPIC_BASE_URL,
|
||||
token: process.env.ANTHROPIC_AUTH_TOKEN,
|
||||
configDir: process.env.CLAUDE_CONFIG_DIR,
|
||||
apiKey: process.env.ANTHROPIC_API_KEY ?? null,
|
||||
cwd: process.cwd(),
|
||||
}))
|
||||
process.stdout.write(JSON.stringify({
|
||||
is_error: false,
|
||||
result: 'stub-answer',
|
||||
duration_ms: 1234,
|
||||
total_cost_usd: 0.5,
|
||||
usage: { input_tokens: 3, output_tokens: 4 },
|
||||
}) + '\\n')
|
||||
})
|
||||
`)
|
||||
chmodSync(script, 0o755)
|
||||
return { script, record }
|
||||
}
|
||||
|
||||
function contextWithTools(credentials, dir) {
|
||||
const registered = { tools: [], effects: [], injected: [] }
|
||||
const ctx = {
|
||||
credentials,
|
||||
attachments: undefined,
|
||||
logger: { warn: () => {} },
|
||||
llm: { registerAdapter: () => () => {}, registerConfigurableProviders: () => () => {} },
|
||||
get: () => undefined,
|
||||
inject(services, callback) {
|
||||
registered.injected.push(services)
|
||||
if (services.includes('settings')) return callback({ settings: { installSection: () => {} } })
|
||||
if (services.includes('connection')) return callback({ effect: ctx.effect, connection: { rpc: { handle: () => () => {} } } })
|
||||
if (services.includes('tools')) {
|
||||
return callback({
|
||||
tools: {
|
||||
register(definition) {
|
||||
registered.tools.push(definition)
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return callback(ctx)
|
||||
},
|
||||
effect(callback) {
|
||||
const disposer = callback()
|
||||
return typeof disposer === 'function' ? disposer : () => {}
|
||||
},
|
||||
configDir: dir,
|
||||
}
|
||||
return { ctx, registered }
|
||||
}
|
||||
|
||||
test('the registered tool runs the CLI with the plugin endpoint, key, and session workspace', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'geek2api-cli-'))
|
||||
const { script, record } = writeStubCli(dir)
|
||||
const workspace = join(dir, 'workspace')
|
||||
mkdirSync(workspace, { recursive: true })
|
||||
const { ctx, registered } = contextWithTools(fakeCredentials({ record: singleKeyRecord('sk-stub-tool-key-0001') }), dir)
|
||||
apply(ctx, { claudeCliPath: script, apiHosts: ['https://cf.example'] })
|
||||
|
||||
assert.equal(registered.tools.length, 1)
|
||||
const tool = registered.tools[0]
|
||||
const value = await tool.execute(
|
||||
{ prompt: 'summarize the repo', mode: 'read-only' },
|
||||
{ signal: undefined, agent: { session: { header: { cwd: workspace } } } },
|
||||
)
|
||||
|
||||
assert.equal(value.result, 'stub-answer')
|
||||
assert.equal(value.costUsd, 0.5)
|
||||
assert.equal(value.durationMs, 1234)
|
||||
assert.equal(value.mode, 'read-only')
|
||||
|
||||
const seen = JSON.parse(readFileSync(record, 'utf8'))
|
||||
// The plugin's endpoint and key reach the child, not the user's ~/.claude.
|
||||
assert.equal(seen.baseUrl, 'https://cf.example')
|
||||
assert.equal(seen.token, 'sk-stub-tool-key-0001')
|
||||
assert.equal(seen.apiKey, null)
|
||||
assert.match(seen.configDir, /geek2api-claude-cli/u)
|
||||
// The default working directory is the session workspace.
|
||||
assert.equal(seen.cwd, realpathSync(workspace))
|
||||
// The task arrives on stdin; argv carries the switches and the delegation note.
|
||||
assert.equal(seen.stdin, 'summarize the repo')
|
||||
assert.equal(seen.argv.includes('summarize the repo'), false)
|
||||
assert.deepEqual(seen.argv.slice(0, 4), ['-p', '--output-format', 'json', '--append-system-prompt'])
|
||||
assert.match(seen.argv[4], /claude_code tool/u)
|
||||
assert.deepEqual(seen.argv.slice(5, 9), ['--allowedTools', 'Read', 'Grep', 'Glob'])
|
||||
assert.match(seen.argv[9], /^mcp__geek2api_search_[a-f0-9]+__web_search$/u)
|
||||
assert.deepEqual(seen.argv.slice(10, 13), ['--disallowedTools', 'WebSearch', '--mcp-config'])
|
||||
assert.match(seen.argv[14] ?? seen.argv[13], /mcp\.json$/u)
|
||||
assert.equal(seen.argv.includes('--strict-mcp-config'), false)
|
||||
assert.equal(seen.argv.some(arg => arg.includes('sk-stub-tool-key-0001')), false)
|
||||
|
||||
// A rendered result carries the answer plus the CLI's accounting.
|
||||
const [block] = tool.output.render({}, value)
|
||||
assert.match(block.text, /stub-answer/u)
|
||||
assert.match(block.text, /read-only/u)
|
||||
assert.match(block.text, /\$0\.5000/u)
|
||||
})
|
||||
|
||||
test('a call without a usable key fails before spawning anything', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'geek2api-cli-'))
|
||||
const { script } = writeStubCli(dir)
|
||||
const { ctx, registered } = contextWithTools(fakeCredentials({ record: singleKeyRecord(undefined) }), dir)
|
||||
apply(ctx, { claudeCliPath: script })
|
||||
await assert.rejects(
|
||||
() => registered.tools[0].execute({ prompt: 'x' }, { agent: { session: { header: { cwd: dir } } } }),
|
||||
/needs a usable Geek2API API key/u,
|
||||
)
|
||||
})
|
||||
|
||||
test('an explicit cwd resolves against the session workspace', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'geek2api-cli-'))
|
||||
const { script, record } = writeStubCli(dir)
|
||||
const workspace = join(dir, 'workspace')
|
||||
mkdirSync(join(workspace, 'sub'), { recursive: true })
|
||||
const { ctx, registered } = contextWithTools(fakeCredentials({ record: singleKeyRecord('sk-stub-tool-key-0002') }), dir)
|
||||
apply(ctx, { claudeCliPath: script })
|
||||
await registered.tools[0].execute(
|
||||
{ prompt: 'work there', mode: 'full', cwd: 'sub' },
|
||||
{ agent: { session: { header: { cwd: workspace } } } },
|
||||
)
|
||||
const seen = JSON.parse(readFileSync(record, 'utf8'))
|
||||
assert.equal(seen.cwd, realpathSync(join(workspace, 'sub')))
|
||||
assert.equal(seen.argv.includes('--dangerously-skip-permissions'), true)
|
||||
})
|
||||
|
||||
/** Host permission services as the base bundle provides them. */
|
||||
function permissionServices(sandbox, approval) {
|
||||
return name => ({
|
||||
sandboxPolicy: { resolve: () => ({ mode: sandbox }) },
|
||||
approval: { effectivePolicy: () => approval },
|
||||
})[name]
|
||||
}
|
||||
|
||||
test('without any plugin setting the CLI follows the session permission preset', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'geek2api-cli-'))
|
||||
const { script, record } = writeStubCli(dir)
|
||||
const { ctx, registered } = contextWithTools(fakeCredentials({ record: singleKeyRecord('sk-stub-tool-key-0003') }), dir)
|
||||
ctx.get = permissionServices('danger-full-access', 'never')
|
||||
apply(ctx, { claudeCliPath: script })
|
||||
const exec = { agent: { session: { header: { cwd: dir } } } }
|
||||
|
||||
const value = await registered.tools[0].execute({ prompt: 'run the tests' }, exec)
|
||||
assert.equal(value.mode, 'full')
|
||||
assert.equal(JSON.parse(readFileSync(record, 'utf8')).argv.includes('--dangerously-skip-permissions'), true)
|
||||
|
||||
ctx.get = permissionServices('workspace-write', 'ask')
|
||||
const capped = await registered.tools[0].execute({ prompt: 'run the tests', mode: 'full' }, exec)
|
||||
assert.equal(capped.mode, 'edit', 'a sandboxed session caps a wider request')
|
||||
})
|
||||
|
||||
test('logged DSH plan mode still forces planning while approved exit is pending', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'geek2api-cli-'))
|
||||
const record = join(dir, 'invocation.json')
|
||||
const script = join(dir, 'claude-plan.mjs')
|
||||
writeFileSync(script, `#!/usr/bin/env node
|
||||
import { writeFileSync } from 'node:fs'
|
||||
let stdin = ''
|
||||
let answered = false
|
||||
process.stdin.setEncoding('utf8')
|
||||
process.stdin.on('data', chunk => {
|
||||
stdin += chunk
|
||||
if (!answered && stdin.includes('\\n')) {
|
||||
answered = true
|
||||
writeFileSync(${JSON.stringify(record)}, JSON.stringify({ argv: process.argv.slice(2), stdin }))
|
||||
process.stdout.write(JSON.stringify({
|
||||
type: 'result', is_error: false, result: '# From cli\\n\\nsteps',
|
||||
duration_ms: 10, total_cost_usd: 0, usage: { input_tokens: 1, output_tokens: 1 },
|
||||
}) + '\\n')
|
||||
}
|
||||
})
|
||||
process.stdin.on('end', () => process.exit(0))
|
||||
`)
|
||||
chmodSync(script, 0o755)
|
||||
const session = { id: 's-plan', header: { cwd: dir } }
|
||||
const { ctx, registered } = contextWithTools(fakeCredentials({ record: singleKeyRecord('sk-stub-tool-key-0005') }), dir)
|
||||
const permissions = permissionServices('danger-full-access', 'never')
|
||||
ctx.get = name => {
|
||||
if (name === 'agents') return { currentInitiator: () => ({ session }) }
|
||||
if (name === 'planMode') return { get: () => ({ active: true, pending: false }) }
|
||||
return permissions(name)
|
||||
}
|
||||
apply(ctx, { claudeCliPath: script, claudeCliMode: 'full' })
|
||||
const value = await registered.tools[0].execute(
|
||||
{ prompt: 'ship it', mode: 'full' },
|
||||
{ agent: { session } },
|
||||
)
|
||||
assert.equal(value.mode, 'plan')
|
||||
assert.match(value.result, /# From cli/u)
|
||||
const seen = JSON.parse(readFileSync(record, 'utf8'))
|
||||
assert.equal(seen.argv[seen.argv.indexOf('--permission-mode') + 1], 'plan')
|
||||
assert.equal(seen.argv.includes('--dangerously-skip-permissions'), false)
|
||||
assert.match(seen.argv.join('\n'), /ExitPlanMode/u)
|
||||
})
|
||||
|
||||
test('a pending plan entry leaves executing tools at the current full ceiling until the next boundary', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'geek2api-cli-'))
|
||||
const { script } = writeStubCli(dir)
|
||||
const session = { id: 's-pending-entry', header: { cwd: dir } }
|
||||
const { ctx, registered } = contextWithTools(fakeCredentials({ record: singleKeyRecord('sk-stub-tool-key-pending') }), dir)
|
||||
const permissions = permissionServices('danger-full-access', 'never')
|
||||
ctx.get = name => {
|
||||
if (name === 'agents') return { currentInitiator: () => ({ session }) }
|
||||
if (name === 'planMode') return { get: () => ({ active: false, pending: true }) }
|
||||
return permissions(name)
|
||||
}
|
||||
apply(ctx, { claudeCliPath: script })
|
||||
const value = await registered.tools[0].execute({ prompt: 'Current batch task', mode: 'full' }, { agent: { session } })
|
||||
assert.equal(value.mode, 'full')
|
||||
})
|
||||
|
||||
test('an explicit plugin mode still wins over the session preset', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'geek2api-cli-'))
|
||||
const { script } = writeStubCli(dir)
|
||||
const { ctx, registered } = contextWithTools(fakeCredentials({ record: singleKeyRecord('sk-stub-tool-key-0004') }), dir)
|
||||
ctx.get = permissionServices('danger-full-access', 'never')
|
||||
apply(ctx, { claudeCliPath: script, claudeCliMode: 'read-only' })
|
||||
const value = await registered.tools[0].execute({ prompt: 'x' }, { agent: { session: { header: { cwd: dir } } } })
|
||||
assert.equal(value.mode, 'read-only')
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync, existsSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import path from 'node:path'
|
||||
import test from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const bundlePath = path.join(root, 'lib', 'client.js')
|
||||
const manifest = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'))
|
||||
|
||||
/** Every member the bundle may ask for, tolerant of React's surface. */
|
||||
function stubRequire(id) {
|
||||
if (id === 'react' || id === 'react/jsx-runtime') {
|
||||
return new Proxy({}, { get: () => () => ({}) })
|
||||
}
|
||||
throw new Error(`client bundle required an undeclared module: ${id}`)
|
||||
}
|
||||
|
||||
test('the client bundle carries the loader wrapper and exports apply/inject', { skip: existsSync(bundlePath) ? false : 'lib/client.js is not built yet' }, () => {
|
||||
const source = readFileSync(bundlePath, 'utf8')
|
||||
const loads = []
|
||||
const sandbox = {
|
||||
window: { __ModuleLoader__: { load: spec => loads.push(spec) } },
|
||||
console,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
setInterval,
|
||||
clearInterval,
|
||||
}
|
||||
vm.createContext(sandbox)
|
||||
vm.runInContext(source, sandbox)
|
||||
|
||||
assert.equal(loads.length, 1)
|
||||
const spec = loads[0]
|
||||
// The loader keys the bundle by package name; a mismatch makes it invisible.
|
||||
assert.equal(spec.id, manifest.name)
|
||||
assert.equal(typeof spec.factory, 'function')
|
||||
const exports = spec.factory(stubRequire)
|
||||
assert.equal(typeof exports.apply, 'function')
|
||||
assert.deepEqual([...exports.inject], ['slots', 'locale', 'connection', 'modelDirectories'])
|
||||
})
|
||||
|
||||
test('every channel call carries a payload object', () => {
|
||||
// The connection envelope requires `payload`; `JSON.stringify` drops an
|
||||
// `undefined` field, so a call without one is refused as an invalid
|
||||
// client-request message. Both callers must default it, because call sites
|
||||
// legitimately write `call('status')`.
|
||||
const source = readFileSync(path.join(root, 'src', 'client.jsx'), 'utf8')
|
||||
const copy = readFileSync(path.join(root, 'src', 'client-copy.js'), 'utf8')
|
||||
const helpers = [...source.matchAll(/\(endpoint, payload([^)]*)\) => rpc\.call\(/gu)]
|
||||
assert.equal(helpers.length, 1, 'one caller serves the settings panel and the composer')
|
||||
assert.match(helpers[0][1], /=\s*\{\}/u)
|
||||
assert.equal(source.match(/rpc\.call\(/gu)?.length, 1, 'nothing reaches the channel around the caller')
|
||||
assert.match(source, /plugin\/update/u)
|
||||
assert.match(copy, /更新插件/u)
|
||||
})
|
||||
|
||||
test('the balance card does not show the account-level billing line', () => {
|
||||
// Geek2API's account billing counts every token on the account, including
|
||||
// keys not stored here, so it reads as a wrong total beside the key sums.
|
||||
const source = readFileSync(path.join(root, 'src', 'client.jsx'), 'utf8')
|
||||
assert.doesNotMatch(source, /balance\?\.account\b/u)
|
||||
assert.doesNotMatch(source, /siteAccount|含同账号/u)
|
||||
// One card lists the keys and their balances, so its empty-state note
|
||||
// renders once rather than once per list.
|
||||
assert.equal(source.match(/t\('empty'\)/gu)?.length, 1)
|
||||
})
|
||||
|
||||
test('the panel styles itself only with host design tokens that exist', () => {
|
||||
const style = readFileSync(path.join(root, 'src', 'client-style.js'), 'utf8')
|
||||
// Tokens the host never defined left controls unstyled before.
|
||||
assert.doesNotMatch(style, /--dsw-alias-border-default|--dsw-alias-state-warning-primary/u)
|
||||
assert.match(style, /--dsw-alias-settings-card-fill/u)
|
||||
})
|
||||
|
||||
test('both languages carry the same copy keys', async () => {
|
||||
const { zh, en } = await import('../src/client-copy.js')
|
||||
assert.deepEqual(Object.keys(en).sort(), Object.keys(zh).sort())
|
||||
})
|
||||
|
||||
test('the package declares the client surface the loader requires', () => {
|
||||
assert.equal(manifest.dsh.client.platform, 'web')
|
||||
assert.deepEqual(manifest.exports['./client'], './lib/client.js')
|
||||
assert.equal(manifest.dsh.bundle.patch, './cordis.patch.yml')
|
||||
for (const declared of manifest.dsh.client.inject) {
|
||||
assert.ok(
|
||||
manifest.peerDependencies[declared] !== undefined || declared.startsWith('@deepseek-ai/dsh-client-'),
|
||||
`${declared} must be a declared peer`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('the shipped patch registers only this plugin, without rewriting Connection', () => {
|
||||
const patch = readFileSync(path.join(root, 'cordis.patch.yml'), 'utf8')
|
||||
const ids = [...patch.matchAll(/^\s*- id:\s*(\S+)\s*$/gmu)].map(match => match[1])
|
||||
assert.deepEqual(ids, ['geek2api'])
|
||||
assert.match(patch, new RegExp(`name: '${manifest.name}'`, 'u'))
|
||||
assert.doesNotMatch(patch, /@deepseek-ai\/dsh-client-connection/u)
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
|
||||
import { createVisionFixture } from '../scripts/vision-fixture.mjs'
|
||||
import { Geek2APIKeyRing } from '../src/key-ring.js'
|
||||
import { createHostPool } from '../src/hosts.js'
|
||||
import { createRouteAdapter } from '../src/route.js'
|
||||
import { fakeCredentials, stubHostPool } from './helpers.mjs'
|
||||
|
||||
test('DeepSeek images reach Chat Completions through the registered host route', async t => {
|
||||
const fixture = createVisionFixture('red')
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add('sk-fixture-only-not-a-real-key', 'fixture')
|
||||
const adapter = createRouteAdapter({
|
||||
ring,
|
||||
keys: {
|
||||
active: () => ring.activeKey(),
|
||||
forRequest: (_model, key) => key,
|
||||
onKeyFailure: () => assert.fail('the fixture key must not be rejected'),
|
||||
},
|
||||
hosts: stubHostPool(createHostPool, ['https://hk2.geek2api.com', 'https://hk.geek2api.com']),
|
||||
fallbackSessionId: 'vision-fixture',
|
||||
resolveAttachments: () => fixture.attachments,
|
||||
})
|
||||
const requests = []
|
||||
t.mock.method(globalThis, 'fetch', async (input, init) => {
|
||||
const request = new Request(input, init)
|
||||
requests.push({ url: request.url, body: await request.json() })
|
||||
const events = [
|
||||
{ id: 'fixture', object: 'chat.completion.chunk', created: 1, model: 'deepseek-v4.1-flash', choices: [{ index: 0, delta: { role: 'assistant', content: 'red' }, finish_reason: null }] },
|
||||
{ id: 'fixture', object: 'chat.completion.chunk', created: 1, model: 'deepseek-v4.1-flash', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
|
||||
]
|
||||
return new Response(events.map(event => `data: ${JSON.stringify(event)}\n\n`).join('') + 'data: [DONE]\n\n', {
|
||||
headers: { 'Content-Type': 'text/event-stream' },
|
||||
})
|
||||
})
|
||||
const prepared = await adapter.prepareCall('geek2api', 'deepseek-v4.1-flash')
|
||||
const chunks = []
|
||||
for await (const chunk of prepared.stream({
|
||||
provider: 'geek2api', model: 'deepseek-v4.1-flash', sessionId: 'vision-fixture',
|
||||
reasoningEffort: 'off', maxTokens: 128,
|
||||
messages: [createUserMessage({
|
||||
content: [{ type: 'text', text: 'Describe this image.' }, fixture.block],
|
||||
source: { kind: 'user' },
|
||||
})],
|
||||
})) chunks.push(chunk)
|
||||
|
||||
assert.equal(chunks.find(chunk => chunk.type === 'finish')?.reason.kind, 'stop')
|
||||
assert.equal(chunks.filter(chunk => chunk.type === 'text-delta').map(chunk => chunk.text).join(''), 'red')
|
||||
assert.deepEqual(fixture.reads, [fixture.block.attachment.attachmentId])
|
||||
assert.equal(requests.length, 1)
|
||||
// The pool's preferred host serves the request, under the catalog's /v1 path.
|
||||
assert.equal(requests[0].url, 'https://hk2.geek2api.com/v1/chat/completions')
|
||||
assert.equal(requests[0].body.model, 'deepseek-v4.1-flash')
|
||||
const content = requests[0].body.messages.find(message => message.role === 'user').content
|
||||
assert.deepEqual(content[0], { type: 'text', text: 'Describe this image.' })
|
||||
// The host also adds a text description of the request preview. What
|
||||
// matters here is that it preserves the pixels rather than only that text.
|
||||
assert.deepEqual(content.filter(block => block.type === 'image_url'), [
|
||||
{ type: 'image_url', image_url: { url: `data:image/png;base64,${fixture.data.toString('base64')}` } },
|
||||
])
|
||||
})
|
||||
@@ -0,0 +1,144 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { isQuotaExceededError } from '@deepseek-ai/dsh-llm'
|
||||
|
||||
import {
|
||||
CLIENT_POLICY_FAILURE,
|
||||
INVALID_KEY_FAILURE,
|
||||
QUOTA_FAILURE,
|
||||
classifyCapacity,
|
||||
classifyClientPolicy,
|
||||
classifyCoverage,
|
||||
classifyGatewayFailure,
|
||||
explainUncoveredModel,
|
||||
explainClientPolicyFailure,
|
||||
explainCliCapacityFailure,
|
||||
normalizeFailureMessage,
|
||||
} from '../src/failures.js'
|
||||
|
||||
const AUTH_STATUS = /\b(?:401|403)\b/u
|
||||
/** Every wording the harness routes somewhere other than a plain failure. */
|
||||
const OTHER_CLASSES = [
|
||||
/\b(?:401|403)\b/u,
|
||||
/\b429\b|rate.?limit/iu,
|
||||
/\b413\b|payload too large|request body too large/iu,
|
||||
/\b400\b|invalid.?request/iu,
|
||||
/\b5\d\d\b/u,
|
||||
/\btime(?:d)?\s*out\b|timeout/iu,
|
||||
/stream ended (?:before|without)\b/iu,
|
||||
/\b(?:network|connection|socket|fetch)\b|\bECONN[A-Z]+\b|\bterminated\b|premature close/iu,
|
||||
]
|
||||
|
||||
test('recognizes an exhausted key from the gateway wording', () => {
|
||||
assert.equal(classifyGatewayFailure('402 {"error":{"message":"当前令牌额度已用完"}}'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('insufficient quota'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('余额不足,请充值'), QUOTA_FAILURE)
|
||||
})
|
||||
|
||||
test('recognizes a rejected key from its status or wording', () => {
|
||||
assert.equal(classifyGatewayFailure('401 {"error":{"message":"无效的令牌"}}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('invalid api key'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('api key is invalid'), INVALID_KEY_FAILURE)
|
||||
})
|
||||
|
||||
test('leaves transient gateway faults to the key it already used', () => {
|
||||
const channelFault = '400 {"error":{"code":"model_not_found","message":"当前令牌未覆盖供应商 \\"Anthropic\\"(模型=claude-opus-5-5)"}}'
|
||||
assert.equal(classifyGatewayFailure(channelFault), undefined)
|
||||
assert.equal(classifyGatewayFailure('503 {"error":{"message":"分组 cc-sale 下模型 claude-opus-5-5 无可用渠道"}}'), undefined)
|
||||
assert.equal(classifyGatewayFailure(''), undefined)
|
||||
assert.equal(classifyGatewayFailure(undefined), undefined)
|
||||
})
|
||||
|
||||
test('a normalized quota failure lands in the harness quota category', () => {
|
||||
const raw = '403 {"error":{"message":"当前令牌额度已用完 (request id: 01M4)"}}'
|
||||
const kind = classifyGatewayFailure(raw)
|
||||
assert.equal(kind, QUOTA_FAILURE)
|
||||
const normalized = normalizeFailureMessage(raw, kind)
|
||||
assert.equal(isQuotaExceededError(normalized), true)
|
||||
// The gateway's 403 must not send this into the auth category first.
|
||||
assert.equal(AUTH_STATUS.test(normalized), false)
|
||||
// The gateway's own sentence survives, so the user sees what happened.
|
||||
assert.match(normalized, /当前令牌额度已用完/u)
|
||||
assert.match(normalized, /trying the next key/u)
|
||||
})
|
||||
|
||||
test('a normalized key rejection lands in the harness auth category', () => {
|
||||
const raw = '{"error":{"message":"无效的令牌 (request id: 01M4)"}}'
|
||||
const kind = classifyGatewayFailure(raw)
|
||||
assert.equal(kind, INVALID_KEY_FAILURE)
|
||||
const normalized = normalizeFailureMessage(raw, kind)
|
||||
assert.equal(AUTH_STATUS.test(normalized), true)
|
||||
assert.equal(isQuotaExceededError(normalized), false)
|
||||
assert.match(normalized, /invalid_authentication/u)
|
||||
})
|
||||
|
||||
test('a client-policy refusal is never blamed on the key', () => {
|
||||
const claude = '403 {"error":{"type":"geek2api_api_error","message":"This API endpoint is only accessible via the official Claude CLI (request id: 01M4Q6FJ05BX8Z4SWZ01RXSNSS)"}}'
|
||||
const codex = '403 {"error":{"message":"我们检测到您的客户端存在异常,请使用标准 Codex 客户端请求,请避免任何基于我方 API 二次分发的 API 转接接入。"}}'
|
||||
for (const raw of [claude, codex]) {
|
||||
assert.equal(classifyClientPolicy(raw), true)
|
||||
// Not a key fault: nothing may disable or rotate a key for this.
|
||||
assert.equal(classifyGatewayFailure(raw), undefined)
|
||||
}
|
||||
})
|
||||
|
||||
test('the policy explanation reaches the user instead of an API-key error', () => {
|
||||
const raw = '403 {"error":{"message":"This API endpoint is only accessible via the official Claude CLI"}}'
|
||||
const normalized = normalizeFailureMessage(raw, CLIENT_POLICY_FAILURE)
|
||||
assert.equal(normalized, explainClientPolicyFailure())
|
||||
assert.match(normalized, /这不是 API Key 失效/u)
|
||||
assert.match(normalized, /Claude 运行方式/u)
|
||||
// It must not read as any category the retry policy re-runs.
|
||||
assert.equal(isQuotaExceededError(normalized), false)
|
||||
for (const pattern of OTHER_CLASSES) {
|
||||
assert.equal(pattern.test(normalized), false, `${pattern} must not match the policy sentence`)
|
||||
}
|
||||
})
|
||||
|
||||
test('the upstream wording for a Claude Code-only route is a client-policy refusal, not a key fault', () => {
|
||||
const raw = '403 {"error":{"type":"geek2api_<nil>","message":"Request blocked: this endpoint only accepts requests from the official Claude Code CLI. (request id: x)"}}'
|
||||
assert.equal(classifyClientPolicy(raw), true)
|
||||
assert.equal(classifyGatewayFailure(raw), undefined)
|
||||
})
|
||||
|
||||
test('a busy gateway is told apart from key, quota, and client faults', () => {
|
||||
assert.equal(classifyCapacity('API Error: 503 {"error":{"type":"geek2api_concurrency_queue_full","message":"账号并发排队已满,请稍后重试。"}}'), true)
|
||||
assert.equal(classifyCapacity('API Error: 429 rate_limit_error'), true)
|
||||
assert.equal(classifyCapacity('API Error: 529 overloaded_error'), true)
|
||||
assert.equal(classifyCapacity('API Error: 401 无效的令牌'), false)
|
||||
assert.equal(classifyCapacity('Request blocked: official Claude Code CLI only'), false)
|
||||
const text = explainCliCapacityFailure('Claude Code CLI failed: API Error: 503 queue full', 10)
|
||||
assert.match(text, /已自动重试 10 次/u)
|
||||
assert.match(text, /Gateway said: API Error: 503 queue full$/u)
|
||||
assert.equal(explainCliCapacityFailure('x', 0).includes('已自动重试'), false)
|
||||
})
|
||||
|
||||
test('classifies the sub2api gateway wording', () => {
|
||||
// Key faults that move the ring along.
|
||||
assert.equal(classifyGatewayFailure('401 {"code":"INVALID_API_KEY","message":"Invalid API key"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('401 {"code":"API_KEY_DISABLED","message":"API key is disabled"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"API_KEY_EXPIRED","message":"API key 已过期"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"message":"API Key 所属分组已删除"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"GROUP_NOT_ALLOWED","message":"API Key 所属专属分组不再允许当前用户使用"}'), INVALID_KEY_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"INSUFFICIENT_BALANCE","message":"余额不足,请充值"}'), QUOTA_FAILURE)
|
||||
assert.equal(classifyGatewayFailure('403 {"code":"SUBSCRIPTION_NOT_FOUND","message":"No active subscription found for this group"}'), QUOTA_FAILURE)
|
||||
|
||||
// A model the key's group does not serve is coverage, never a key fault.
|
||||
const missing = `400 {"error":{"message":"Model 'kimi-k3' is not available. Use GET /v1/models to see supported models.","type":"invalid_request_error"}}`
|
||||
assert.equal(classifyGatewayFailure(missing), undefined)
|
||||
assert.equal(classifyCoverage(missing), true)
|
||||
assert.equal(classifyCoverage('503 No available accounts'), true)
|
||||
assert.equal(classifyCoverage('Model is not allowed'), true)
|
||||
assert.equal(classifyCoverage('500 upstream exploded'), false)
|
||||
})
|
||||
|
||||
test('an uncovered model is explained without any wording the harness retries', () => {
|
||||
const raw = `400 {"error":{"message":"Model 'kimi-k3' is not available. Use GET /v1/models to see supported models."}}`
|
||||
const explained = explainUncoveredModel('kimi-k3', raw)
|
||||
assert.match(explained, /你保存的 Key 都不能使用 kimi-k3/u)
|
||||
assert.match(explained, /is not available/u, 'the gateway words are kept')
|
||||
assert.equal(isQuotaExceededError(explained), false)
|
||||
assert.doesNotMatch(explained, /\b(?:400|401|403)\b/u)
|
||||
assert.match(explainUncoveredModel(undefined, ''), /所选模型/u)
|
||||
})
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
// Give the 0.2 host its matching dependency graph without changing the
|
||||
// plugin's 0.1.5 development host or installing any DSH application/profile.
|
||||
export { Context } from '@deepseek-ai/cordis'
|
||||
export { HostConnectionService, serverResponseSchema } from '@deepseek-ai/dsh-client-connection'
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "geek2api-host-v020-fixture",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": "./index.js",
|
||||
"dependencies": {
|
||||
"@deepseek-ai/cordis": "4.0.4",
|
||||
"@deepseek-ai/dsh-brand": "0.2.0-rc.2",
|
||||
"@deepseek-ai/dsh-client-connection": "0.2.0-rc.2",
|
||||
"@deepseek-ai/dsh-invariants": "0.2.0-rc.2",
|
||||
"@deepseek-ai/dsh-scope": "0.2.0-rc.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { DEFAULT_API_HOST } from '../src/constants.js'
|
||||
import { createGeek2APIProvider } from '../src/provider.js'
|
||||
|
||||
/** An actual Responses SSE stream, parsed by pi-ai's real OpenAI SDK path. */
|
||||
function responseStream() {
|
||||
const item = { type: 'message', id: 'msg_fixture', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'ok', annotations: [] }] }
|
||||
const events = [
|
||||
{ type: 'response.created', response: { id: 'resp_fixture', status: 'in_progress', output: [] } },
|
||||
{ type: 'response.output_item.added', output_index: 0, item: { ...item, status: 'in_progress', content: [] } },
|
||||
{ type: 'response.content_part.added', output_index: 0, content_index: 0, item_id: item.id, part: { type: 'output_text', text: '', annotations: [] } },
|
||||
{ type: 'response.output_text.delta', output_index: 0, content_index: 0, item_id: item.id, delta: 'ok' },
|
||||
{ type: 'response.output_item.done', output_index: 0, item },
|
||||
{ type: 'response.completed', response: { id: 'resp_fixture', status: 'completed', output: [item], usage: { input_tokens: 8, output_tokens: 2, total_tokens: 10 } } },
|
||||
]
|
||||
return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join('') + 'data: [DONE]\n\n', {
|
||||
headers: { 'Content-Type': 'text/event-stream' },
|
||||
})
|
||||
}
|
||||
|
||||
test('Grok uses Responses and its four efforts without the cache key this gateway rejects', async () => {
|
||||
const provider = createGeek2APIProvider()
|
||||
const model = provider.getModels().find(model => model.id === 'grok-4.7')
|
||||
for (const reasoning of ['low', 'medium', 'high', 'xhigh']) {
|
||||
const requests = []
|
||||
const stream = provider.streamSimple(model, { messages: [{ role: 'user', content: 'Reply with ok', timestamp: 1 }] }, {
|
||||
apiKey: 'sk-fixture-only-not-a-real-key', reasoning,
|
||||
sessionId: 'grok-fixture-session', cacheRetention: 'long', maxTokens: 2048,
|
||||
fetch: async (url, init) => {
|
||||
requests.push({ url: String(url), key: new Headers(init.headers).get('authorization'), body: JSON.parse(init.body) })
|
||||
if (requests.at(-1).body.prompt_cache_key !== undefined) {
|
||||
return Response.json({ error: { message: 'Incorrect API key provided', type: 'geek2api_invalid-argument', code: 'invalid-argument' } }, { status: 400 })
|
||||
}
|
||||
return responseStream()
|
||||
},
|
||||
})
|
||||
const chunks = []
|
||||
for await (const chunk of stream) chunks.push(chunk)
|
||||
const result = await stream.result()
|
||||
assert.equal(result.stopReason, 'stop', result.errorMessage)
|
||||
assert.equal(chunks.filter(chunk => chunk.type === 'text_delta').map(chunk => chunk.delta).join(''), 'ok')
|
||||
assert.equal(requests.length, 1)
|
||||
assert.equal(requests[0].url, `${DEFAULT_API_HOST}/v1/responses`)
|
||||
assert.equal(requests[0].key, 'Bearer sk-fixture-only-not-a-real-key')
|
||||
assert.equal(requests[0].body.model, 'grok-4.7')
|
||||
assert.equal(requests[0].body.reasoning.effort, reasoning)
|
||||
assert.equal(requests[0].body.prompt_cache_key, undefined, 'the gateway refuses Grok when this field is present')
|
||||
assert.equal(requests[0].body.prompt_cache_retention, undefined, 'Grok must not receive OpenAI 24h retention')
|
||||
assert.equal(requests[0].body.max_output_tokens, 2048)
|
||||
assert.ok(requests[0].body.include.includes('reasoning.encrypted_content'))
|
||||
}
|
||||
})
|
||||
|
||||
test('GPT keeps the session cache key its gateway route requires', async () => {
|
||||
const provider = createGeek2APIProvider()
|
||||
const model = provider.getModels().find(model => model.id === 'gpt-6.1-sol')
|
||||
let payload
|
||||
const stream = provider.streamSimple(model, { messages: [{ role: 'user', content: 'Reply with ok', timestamp: 1 }] }, {
|
||||
apiKey: 'sk-fixture-only-not-a-real-key', sessionId: 'gpt-session', reasoning: 'high',
|
||||
fetch: async (_url, init) => { payload = JSON.parse(init.body); return responseStream() },
|
||||
})
|
||||
await stream.result()
|
||||
assert.equal(payload.prompt_cache_key, 'gpt-session')
|
||||
})
|
||||
|
||||
test('a future non-GPT Responses model also defaults to omitting the GPT cache key', async () => {
|
||||
const provider = createGeek2APIProvider()
|
||||
// A descriptor from another family catches a Grok-only special case.
|
||||
const model = { ...provider.getModels().find(model => model.id === 'grok-4.7'), id: 'another-responses-model', name: 'Another model' }
|
||||
let payload
|
||||
const stream = provider.streamSimple(model, { messages: [{ role: 'user', content: 'Reply with ok', timestamp: 1 }] }, {
|
||||
apiKey: 'sk-fixture-only-not-a-real-key', sessionId: 'other-session', reasoning: 'high',
|
||||
fetch: async (_url, init) => { payload = JSON.parse(init.body); return responseStream() },
|
||||
})
|
||||
assert.equal((await stream.result()).stopReason, 'stop')
|
||||
assert.equal(payload.prompt_cache_key, undefined)
|
||||
})
|
||||
@@ -0,0 +1,150 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { GEEK2API_MODEL_IDS } from '../src/catalog.js'
|
||||
import { catalogCoverage, createGroupReader, parseKeyGroups, pickKeyForModel } from '../src/groups.js'
|
||||
import { fixedHostPool } from './helpers.mjs'
|
||||
|
||||
test('the key groups are read from /v1/usage when the gateway names them', () => {
|
||||
assert.deepEqual(parseKeyGroups({ key: { groups: [{ name: '稳定Claude', platform: 'anthropic' }, { name: 'CodeX' }] } }), ['稳定Claude', 'CodeX'])
|
||||
assert.deepEqual(parseKeyGroups({ key: { groups: ['a', 'a', ' b '] } }), ['a', 'b'])
|
||||
assert.deepEqual(parseKeyGroups({ key: { group: { name: 'Gemini' } } }), ['Gemini'])
|
||||
assert.deepEqual(parseKeyGroups({ key: { group: 'Grok' } }), ['Grok'])
|
||||
assert.equal(parseKeyGroups({ mode: 'unrestricted' }), undefined)
|
||||
assert.equal(parseKeyGroups({ key: { groups: [] } }), undefined)
|
||||
})
|
||||
|
||||
test('coverage is the model list itself, and unknown without one', () => {
|
||||
const coverage = catalogCoverage(new Set(['claude-opus-5-5', 'gpt-4o']))
|
||||
assert.equal(coverage['claude-opus-5-5'], true)
|
||||
assert.equal(coverage['gpt-6.1-sol'], false)
|
||||
assert.deepEqual(Object.keys(coverage), [...GEEK2API_MODEL_IDS])
|
||||
assert.deepEqual(catalogCoverage(undefined), {})
|
||||
})
|
||||
|
||||
function jsonResponse(payload, status = 200) {
|
||||
const body = JSON.stringify(payload)
|
||||
return { ok: status >= 200 && status < 300, status, json: async () => JSON.parse(body), text: async () => body }
|
||||
}
|
||||
|
||||
const MODELS = { 'sk-claude': ['claude-opus-5-5', 'claude-haiku-4-5-20251001', 'claude-3-old'], 'sk-gpt': ['gpt-6.1-sol', 'gpt-6-astra'] }
|
||||
|
||||
function gateway({ usage = {}, models = MODELS, refuse = {} } = {}) {
|
||||
const calls = []
|
||||
const fetchImpl = async (url, options) => {
|
||||
const key = String(options.headers.Authorization).replace('Bearer ', '')
|
||||
calls.push({ url, key })
|
||||
assert.equal(options.redirect, 'error')
|
||||
if (refuse[key] !== undefined) return jsonResponse({ error: { message: refuse[key].message } }, refuse[key].status)
|
||||
if (url.endsWith('/v1/models')) return jsonResponse({ object: 'list', data: (models[key] ?? []).map(id => ({ id, type: 'model' })) })
|
||||
if (url.endsWith('/v1/usage?lite=1')) return jsonResponse({ mode: 'unrestricted', balance: 1, ...(usage[key] ?? {}) })
|
||||
throw new Error(`unrouted ${url}`)
|
||||
}
|
||||
return { fetchImpl, calls }
|
||||
}
|
||||
|
||||
const KEYS = [
|
||||
{ id: 'c', label: 'claude', key: 'sk-claude', disabled: false },
|
||||
{ id: 'g', label: 'gpt', key: 'sk-gpt', disabled: false },
|
||||
]
|
||||
|
||||
test('each key reports its reachable catalog models and groups, with no key material', async () => {
|
||||
const { fetchImpl, calls } = gateway({ usage: { 'sk-claude': { key: { groups: [{ name: '稳定Claude' }] } } } })
|
||||
const reader = createGroupReader({ listKeys: async () => KEYS, hosts: await fixedHostPool(), fetchImpl })
|
||||
const value = await reader.read()
|
||||
assert.equal(value.keys[0].coverage['claude-opus-5-5'], true)
|
||||
assert.equal(value.keys[0].coverage['gpt-6.1-sol'], false)
|
||||
assert.deepEqual(value.keys[0].groups, ['稳定Claude'])
|
||||
assert.equal(value.keys[0].extraModels, 1)
|
||||
assert.equal(value.keys[1].groups, undefined)
|
||||
assert.equal(value.keys[1].coverage['gpt-6-astra'], true)
|
||||
assert.doesNotMatch(JSON.stringify(value), /sk-/u)
|
||||
assert.ok(calls.every(call => call.url.startsWith('https://h1.example/')))
|
||||
|
||||
assert.equal(reader.covers('c', 'claude-opus-5-5'), true)
|
||||
assert.equal(reader.covers('c', 'gpt-6.1-sol'), false)
|
||||
assert.equal(reader.covers('nobody', 'gpt-6.1-sol'), undefined)
|
||||
assert.deepEqual(reader.groupsOf('c'), ['稳定Claude'])
|
||||
assert.equal(reader.requiredGroups('claude-opus-5-5'), undefined)
|
||||
assert.equal(reader.hasReading(), true)
|
||||
})
|
||||
|
||||
test('a key the gateway rejects (401, or a deleted group) reaches nothing', async () => {
|
||||
const { fetchImpl } = gateway({
|
||||
refuse: {
|
||||
'sk-claude': { status: 401, message: 'Invalid API key' },
|
||||
'sk-gpt': { status: 403, message: 'API Key 所属分组已删除' },
|
||||
},
|
||||
})
|
||||
const reader = createGroupReader({ listKeys: async () => KEYS, hosts: await fixedHostPool(), fetchImpl })
|
||||
const value = await reader.read()
|
||||
for (const entry of value.keys) {
|
||||
assert.equal(entry.rejected, true)
|
||||
assert.ok(Object.values(entry.coverage).every(reach => reach === false))
|
||||
}
|
||||
})
|
||||
|
||||
test('another refusal of the model list is a failed read, not evidence', async () => {
|
||||
const { fetchImpl } = gateway({ refuse: { 'sk-gpt': { status: 403, message: '余额不足,请充值' } } })
|
||||
const reader = createGroupReader({ listKeys: async () => KEYS, hosts: await fixedHostPool(), fetchImpl })
|
||||
const value = await reader.read()
|
||||
assert.equal(value.keys[1].rejected, undefined)
|
||||
assert.deepEqual(value.keys[1].coverage, {})
|
||||
assert.match(value.keys[1].error, /HTTP 403 for the model list: 余额不足/u)
|
||||
assert.equal(reader.covers('g', 'gpt-6.1-sol'), undefined)
|
||||
})
|
||||
|
||||
test('a failed read keeps the last good reading, marked stale; the groups are optional', async () => {
|
||||
let down = false
|
||||
let usageDown = false
|
||||
const inner = gateway()
|
||||
const fetchImpl = async (url, options) => {
|
||||
if (down) return jsonResponse({ error: { message: 'busy' } }, 503)
|
||||
if (usageDown && url.includes('/v1/usage')) return jsonResponse({ error: { message: 'busy' } }, 503)
|
||||
return inner.fetchImpl(url, options)
|
||||
}
|
||||
let clock = 1
|
||||
const reader = createGroupReader({ listKeys: async () => KEYS, hosts: await fixedHostPool(), fetchImpl, now: () => clock })
|
||||
usageDown = true
|
||||
const first = await reader.read()
|
||||
assert.equal(first.keys[0].coverage['claude-opus-5-5'], true, 'the model list alone is enough')
|
||||
assert.equal(first.keys[0].groups, undefined)
|
||||
|
||||
down = true
|
||||
clock = 5
|
||||
const second = await reader.read({ force: true })
|
||||
assert.equal(second.keys[0].coverage['claude-opus-5-5'], true)
|
||||
assert.equal(second.keys[0].stale.fetchedAt, 1)
|
||||
assert.match(second.keys[0].stale.error, /503/u)
|
||||
})
|
||||
|
||||
test('requires a key listing and a host pool', () => {
|
||||
assert.throws(() => createGroupReader({ hosts: {} }), /listKeys/u)
|
||||
assert.throws(() => createGroupReader({ listKeys: async () => [] }), /host pool/u)
|
||||
})
|
||||
|
||||
test('a key is passed over only on evidence, and the active pointer is never moved', () => {
|
||||
const usable = [
|
||||
{ id: 'a', label: 'A', key: 'ka' },
|
||||
{ id: 'b', label: 'B', key: 'kb' },
|
||||
{ id: 'c', label: 'C', key: 'kc' },
|
||||
]
|
||||
const evidence = { 'a:claude': false, 'b:claude': undefined, 'c:claude': true, 'a:gpt': true }
|
||||
const covers = (id, model) => evidence[`${id}:${model}`]
|
||||
// The active key serves what it is not known to be excluded from.
|
||||
assert.deepEqual(pickKeyForModel('gpt', usable[0], usable, covers), usable[0])
|
||||
assert.deepEqual(pickKeyForModel('unknown', usable[0], usable, covers), usable[0])
|
||||
// Known excluded: the next key that surely can, ahead of one that may.
|
||||
assert.deepEqual(pickKeyForModel('claude', usable[0], usable, covers), { id: 'c', label: 'C', key: 'kc', switchedFrom: { id: 'a', label: 'A' } })
|
||||
// With no sure key, one with no evidence either way.
|
||||
evidence['c:claude'] = false
|
||||
assert.equal(pickKeyForModel('claude', usable[0], usable, covers).id, 'b')
|
||||
// With nothing better, the active key, marked uncovered.
|
||||
evidence['b:claude'] = false
|
||||
assert.deepEqual(pickKeyForModel('claude', usable[0], usable, covers), { ...usable[0], uncovered: true })
|
||||
// Ring order starts after the active key.
|
||||
evidence['a:claude'] = true
|
||||
evidence['c:claude'] = true
|
||||
assert.equal(pickKeyForModel('claude', usable[1], usable, covers).id, 'c')
|
||||
assert.equal(pickKeyForModel('claude', undefined, usable, covers), undefined)
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Test doubles shared across the suite.
|
||||
*/
|
||||
|
||||
/**
|
||||
* An in-memory DSH credential-record service with the real one's semantics
|
||||
* at the seam the key ring uses: reads answer the committed record, and
|
||||
* modifications are serialized read-decide-replace operations.
|
||||
* @param options - an optional record to start from.
|
||||
* @returns `{ readRecord, modifyRecord, payload }`; `payload()` is a
|
||||
* test-only view of the stored grant payload.
|
||||
*/
|
||||
export function fakeCredentials({ record: initial } = {}) {
|
||||
let record = initial
|
||||
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
|
||||
},
|
||||
payload() {
|
||||
return record?.payload
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A key-ring record holding one key, as the ring itself would store it.
|
||||
* @param key - the key material.
|
||||
* @returns the credential record.
|
||||
*/
|
||||
export function singleKeyRecord(key) {
|
||||
return { kind: 'grant', payload: { version: 1, activeId: 'k1', keys: [{ id: 'k1', label: 'stub', key, addedAt: 1 }] } }
|
||||
}
|
||||
|
||||
/**
|
||||
* A real host pool over fixed hosts whose `/health` probes always answer, so
|
||||
* the order is the configured one and probes never reach a reader's fetch.
|
||||
* @param hosts - the configured origins.
|
||||
* @param options - extra pool options.
|
||||
* @returns the pool.
|
||||
*/
|
||||
export async function fixedHostPool(hosts = ['https://h1.example', 'https://h2.example'], options = {}) {
|
||||
const { createHostPool } = await import('../src/hosts.js')
|
||||
return createHostPool({
|
||||
listHosts: () => hosts,
|
||||
fetchImpl: async () => ({ ok: true, status: 200, json: async () => ({ status: 'ok' }) }),
|
||||
probeIntervalMs: 1e12,
|
||||
...options,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The same pool, synchronously, for code that composes it at once.
|
||||
* @param createHostPool - the pool factory (import it from the module under test).
|
||||
* @param hosts - the configured origins.
|
||||
* @returns the pool.
|
||||
*/
|
||||
export function stubHostPool(createHostPool, hosts = ['https://h1.example', 'https://h2.example']) {
|
||||
return createHostPool({
|
||||
listHosts: () => hosts,
|
||||
fetchImpl: async () => ({ ok: true, status: 200, json: async () => ({ status: 'ok' }) }),
|
||||
probeIntervalMs: 1e12,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { DEFAULT_API_HOSTS } from '../src/constants.js'
|
||||
import { createHostPool, isTransportFailure, normalizeHost, normalizeHostList } from '../src/hosts.js'
|
||||
import { TransportError } from '../src/request.js'
|
||||
|
||||
const HOSTS = ['https://a.example', 'https://b.example', 'https://c.example']
|
||||
|
||||
/** A /health fetch with a scripted latency (ms) or failure per host. */
|
||||
function healthFetch(plan, clock) {
|
||||
const calls = []
|
||||
const fetchImpl = async url => {
|
||||
const host = new URL(url).origin
|
||||
calls.push(url)
|
||||
const step = plan[host]
|
||||
if (step === 'down') throw Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNREFUSED' } })
|
||||
if (step === 502) return { ok: false, status: 502 }
|
||||
clock.t += step ?? 0
|
||||
return { ok: true, status: 200 }
|
||||
}
|
||||
return { fetchImpl, calls }
|
||||
}
|
||||
|
||||
const transport = () => new TransportError(Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNRESET' } }), { aborted: false, timedOut: false, timeoutMs: 1000 })
|
||||
|
||||
test('normalizes host lists, keeping order and falling back to the defaults', () => {
|
||||
assert.equal(normalizeHost(' https://x.example/ ', 'f'), 'https://x.example')
|
||||
assert.equal(normalizeHost('ftp://x.example', 'f'), 'f')
|
||||
assert.deepEqual(normalizeHostList(['https://b.example/', 'nonsense', 'https://a.example', 'https://b.example']), ['https://b.example', 'https://a.example'])
|
||||
assert.deepEqual(normalizeHostList('https://a.example\nhttps://b.example, https://c.example'), HOSTS)
|
||||
assert.deepEqual(normalizeHostList([]), [...DEFAULT_API_HOSTS])
|
||||
assert.deepEqual(normalizeHostList(undefined), [...DEFAULT_API_HOSTS])
|
||||
})
|
||||
|
||||
test('the defaults are Geek2API entry points only', () => {
|
||||
assert.ok(DEFAULT_API_HOSTS.length >= 2)
|
||||
for (const host of DEFAULT_API_HOSTS) assert.match(host, /^https:\/\/[a-z0-9]+\.geek2api\.com$/u)
|
||||
})
|
||||
|
||||
test('only failures that never reached the host count as transport failures', () => {
|
||||
assert.equal(isTransportFailure(transport()), true)
|
||||
assert.equal(isTransportFailure(new TransportError(new Error('x'), { aborted: true, timedOut: false, timeoutMs: 1 })), false, 'the caller cancelling is not the host failing')
|
||||
assert.equal(isTransportFailure(new Error('fetch failed')), true)
|
||||
assert.equal(isTransportFailure('Connection error.'), true)
|
||||
assert.equal(isTransportFailure(new Error('this API key was rejected (401)')), false)
|
||||
assert.equal(isTransportFailure(new Error('400 Model is not available')), false)
|
||||
})
|
||||
|
||||
test('before any probe the configured order stands', () => {
|
||||
const pool = createHostPool({ listHosts: () => HOSTS, fetchImpl: async () => { throw new Error('no probe expected') }, probeIntervalMs: 1e12 })
|
||||
assert.deepEqual(pool.order(), HOSTS)
|
||||
})
|
||||
|
||||
test('a probe ranks reachable hosts by latency, unreachable ones after them', async () => {
|
||||
const clock = { t: 0 }
|
||||
const { fetchImpl } = healthFetch({ 'https://a.example': 'down', 'https://b.example': 90, 'https://c.example': 20 }, clock)
|
||||
// Each probe measures its own round trip on the shared clock.
|
||||
const pool = createHostPool({ listHosts: () => HOSTS, fetchImpl, now: () => clock.t })
|
||||
await pool.probe({ force: true })
|
||||
const order = pool.order()
|
||||
assert.equal(order.at(-1), 'https://a.example')
|
||||
assert.deepEqual(new Set(order.slice(0, 2)), new Set(['https://b.example', 'https://c.example']))
|
||||
const status = pool.status()
|
||||
assert.equal(status.find(entry => entry.host === 'https://a.example').latencyMs, undefined)
|
||||
assert.equal(status.filter(entry => entry.current).length, 1)
|
||||
})
|
||||
|
||||
test('a 5xx from the edge counts as down; any other answer as up', async () => {
|
||||
const clock = { t: 0 }
|
||||
const { fetchImpl } = healthFetch({ 'https://a.example': 502, 'https://b.example': 5, 'https://c.example': 5 }, clock)
|
||||
const pool = createHostPool({ listHosts: () => HOSTS, fetchImpl, now: () => clock.t })
|
||||
await pool.probe({ force: true })
|
||||
assert.equal(pool.order().at(-1), 'https://a.example')
|
||||
})
|
||||
|
||||
test('probes are single-flight and skipped while the ranking is fresh', async () => {
|
||||
let calls = 0
|
||||
let release
|
||||
const gate = new Promise(resolve => { release = resolve })
|
||||
const fetchImpl = async () => {
|
||||
calls += 1
|
||||
await gate
|
||||
return { ok: true, status: 200 }
|
||||
}
|
||||
let clock = 1
|
||||
const pool = createHostPool({ listHosts: () => HOSTS, fetchImpl, now: () => clock, probeIntervalMs: 1000 })
|
||||
const first = pool.probe()
|
||||
const second = pool.probe()
|
||||
release()
|
||||
await Promise.all([first, second])
|
||||
assert.equal(calls, HOSTS.length, 'one probe of each host')
|
||||
await pool.probe()
|
||||
assert.equal(calls, HOSTS.length, 'fresh ranking is kept')
|
||||
clock = 5000
|
||||
await pool.probe()
|
||||
assert.equal(calls, HOSTS.length * 2)
|
||||
await pool.probe({ force: true })
|
||||
assert.equal(calls, HOSTS.length * 3)
|
||||
})
|
||||
|
||||
test('a failed host cools down at the back of the order, then returns', () => {
|
||||
let clock = 0
|
||||
const pool = createHostPool({ listHosts: () => HOSTS, fetchImpl: async () => ({ ok: true, status: 200 }), now: () => clock, cooldownMs: 1000, probeIntervalMs: 1e12 })
|
||||
pool.fail('https://a.example', 'reset')
|
||||
assert.deepEqual(pool.order(), ['https://b.example', 'https://c.example', 'https://a.example'])
|
||||
assert.ok(pool.status().find(entry => entry.host === 'https://a.example').coolingUntil > 0)
|
||||
clock = 1001
|
||||
assert.equal(pool.order()[0], 'https://a.example')
|
||||
pool.fail('https://unknown.example')
|
||||
assert.deepEqual(pool.order(), HOSTS, 'a host outside the list is ignored')
|
||||
})
|
||||
|
||||
test('withFailover moves on only after transport failures', async () => {
|
||||
const pool = createHostPool({ listHosts: () => HOSTS, fetchImpl: async () => ({ ok: true, status: 200 }), now: () => 1, probeIntervalMs: 1e12 })
|
||||
// A ranking exists, so no background probe races the failover below.
|
||||
await pool.probe()
|
||||
const tried = []
|
||||
const value = await pool.withFailover(async host => {
|
||||
tried.push(host)
|
||||
if (host === 'https://a.example') throw transport()
|
||||
return `answered by ${host}`
|
||||
})
|
||||
assert.equal(value, 'answered by https://b.example')
|
||||
assert.deepEqual(tried, ['https://a.example', 'https://b.example'])
|
||||
assert.equal(pool.order()[0], 'https://b.example', 'the failing host is now behind')
|
||||
|
||||
// An answer from the gateway, however unwelcome, is the answer.
|
||||
const refused = []
|
||||
await assert.rejects(pool.withFailover(async host => {
|
||||
refused.push(host)
|
||||
throw new Error('this API key was rejected (401)')
|
||||
}), /rejected \(401\)/u)
|
||||
assert.equal(refused.length, 1)
|
||||
|
||||
await assert.rejects(pool.withFailover(async () => { throw transport() }), /no Geek2API host answered/u)
|
||||
})
|
||||
|
||||
test('withFailover honours cancellation', async () => {
|
||||
const pool = createHostPool({ listHosts: () => HOSTS, fetchImpl: async () => ({ ok: true, status: 200 }), probeIntervalMs: 1e12 })
|
||||
const controller = new AbortController()
|
||||
controller.abort(new Error('stop'))
|
||||
await assert.rejects(pool.withFailover(async () => 'x', { signal: controller.signal }), /stop/u)
|
||||
})
|
||||
|
||||
test('the host list is read per call, so a settings change applies at once', () => {
|
||||
let list = HOSTS
|
||||
const pool = createHostPool({ listHosts: () => list, fetchImpl: async () => ({ ok: true, status: 200 }), probeIntervalMs: 1e12 })
|
||||
assert.equal(pool.current(), 'https://a.example')
|
||||
list = ['https://z.example']
|
||||
assert.equal(pool.current(), 'https://z.example')
|
||||
assert.deepEqual(pool.hosts(), ['https://z.example'])
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
|
||||
import { apply } from '../src/index.js'
|
||||
import { fakeCredentials } from './helpers.mjs'
|
||||
|
||||
const KEY_CODEX = 'sk-codex-only-key-AAAA'
|
||||
const KEY_DEEPSEEK = 'sk-deepseek-key-BBBB'
|
||||
const KEY_CLAUDE = 'sk-claude-code-key-CCCC'
|
||||
const GROUPS = { [KEY_CODEX]: ['codex'], [KEY_DEEPSEEK]: ['deepseek'], [KEY_CLAUDE]: ['cc'] }
|
||||
/** What each key's `/v1/models` lists: exactly what its group serves. */
|
||||
const MODELS = {
|
||||
[KEY_CODEX]: ['gpt-6.1-sol', 'gpt-6-astra'],
|
||||
[KEY_DEEPSEEK]: ['deepseek-v4.1-flash'],
|
||||
[KEY_CLAUDE]: ['claude-opus-5-5', 'claude-haiku-4-5-20251001'],
|
||||
}
|
||||
|
||||
const sse = chunks => new Response(chunks.map(chunk => `data: ${JSON.stringify(chunk)}\n\n`).join('') + 'data: [DONE]\n\n', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/event-stream' },
|
||||
})
|
||||
|
||||
/**
|
||||
* A stand-in Geek2API gateway on `fetch`: health, each key's model list and
|
||||
* groups, and a streaming chat completion that records the key it was sent.
|
||||
*/
|
||||
function fakeGateway() {
|
||||
const chatKeys = []
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = async (input, init = {}) => {
|
||||
const url = typeof input === 'string' ? input : input.url
|
||||
const headers = new Headers(init.headers ?? (typeof input === 'string' ? undefined : input.headers))
|
||||
const key = headers.get('authorization')?.replace(/^Bearer /u, '')
|
||||
if (url.endsWith('/health')) return Response.json({ status: 'ok' })
|
||||
if (url.endsWith('/v1/models')) return Response.json({ object: 'list', data: (MODELS[key] ?? []).map(id => ({ id, type: 'model' })) })
|
||||
if (url.includes('/v1/usage')) return Response.json({ mode: 'unrestricted', balance: 10, key: { name: 'k', groups: (GROUPS[key] ?? []).map(name => ({ name })) } })
|
||||
if (url.endsWith('/v1/chat/completions')) {
|
||||
const body = JSON.parse(typeof init.body === 'string' ? init.body : await new Response(init.body).text())
|
||||
chatKeys.push(key)
|
||||
return sse([
|
||||
{ id: 'c1', object: 'chat.completion.chunk', created: 1, model: body.model, choices: [{ index: 0, delta: { role: 'assistant', content: 'ok' }, finish_reason: null }] },
|
||||
{ id: 'c1', object: 'chat.completion.chunk', created: 1, model: body.model, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } },
|
||||
])
|
||||
}
|
||||
return new Response('{}', { status: 404 })
|
||||
}
|
||||
return { chatKeys, restore: () => { globalThis.fetch = original } }
|
||||
}
|
||||
|
||||
function context() {
|
||||
const seen = {}
|
||||
const ctx = {
|
||||
credentials: fakeCredentials(),
|
||||
logger: { warn: () => {}, info: () => {} },
|
||||
llm: {
|
||||
registerAdapter: (_providers, adapter) => { seen.adapter = adapter; return () => {} },
|
||||
registerConfigurableProviders: () => () => {},
|
||||
},
|
||||
get: () => undefined,
|
||||
inject(names, callback) {
|
||||
if (names.includes('connection')) return callback({ effect: ctx.effect, connection: { rpc: { handle: (_c, handler) => { seen.handler = handler; return () => {} } } } })
|
||||
if (names.includes('tools')) return callback({ tools: { register: () => () => {} } })
|
||||
return undefined
|
||||
},
|
||||
effect(callback) {
|
||||
const disposer = callback()
|
||||
return typeof disposer === 'function' ? disposer : () => {}
|
||||
},
|
||||
}
|
||||
return { ctx, seen }
|
||||
}
|
||||
|
||||
const turn = async (adapter, model) => {
|
||||
const prepared = await adapter.prepareCall('geek2api', model)
|
||||
const chunks = []
|
||||
for await (const chunk of prepared.stream({
|
||||
provider: 'geek2api',
|
||||
model,
|
||||
sessionId: 'session-1',
|
||||
reasoningEffort: 'high',
|
||||
messages: [createUserMessage({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } })],
|
||||
})) chunks.push(chunk)
|
||||
return chunks
|
||||
}
|
||||
|
||||
test('an HTTP turn runs on a key whose groups reach its model, without moving the active key', async t => {
|
||||
const gateway = fakeGateway()
|
||||
t.after(gateway.restore)
|
||||
const { ctx, seen } = context()
|
||||
apply(ctx, {})
|
||||
await seen.handler('keys/add', { key: KEY_CODEX, label: 'codex' })
|
||||
await seen.handler('keys/add', { key: KEY_DEEPSEEK, label: 'deepseek' })
|
||||
|
||||
const chunks = await turn(seen.adapter, 'deepseek-v4.1-flash')
|
||||
assert.equal(chunks.at(-1).type, 'finish')
|
||||
assert.equal(chunks.at(-1).reason.kind, 'stop')
|
||||
// The active key (codex) does not list DeepSeek; the DeepSeek key served it.
|
||||
assert.deepEqual(gateway.chatKeys, [KEY_DEEPSEEK])
|
||||
const status = await seen.handler('status', {})
|
||||
assert.equal(status.value.keys.find(key => key.active).label, 'codex')
|
||||
|
||||
// The panel's group projection names both keys' groups, and no key.
|
||||
const groups = await seen.handler('groups', {})
|
||||
assert.equal(groups.ok, true)
|
||||
assert.deepEqual(groups.value.keys.map(key => key.groups), [['codex'], ['deepseek']])
|
||||
assert.equal(groups.value.keys[1].coverage['deepseek-v4.1-flash'], true)
|
||||
assert.equal(groups.value.keys[0].coverage['deepseek-v4.1-flash'], false)
|
||||
assert.doesNotMatch(JSON.stringify(groups), /sk-(codex|deepseek)/u)
|
||||
})
|
||||
|
||||
test('a Claude CLI turn after "use this key" runs on that key, and otherwise on one with a Claude group', async t => {
|
||||
const gateway = fakeGateway()
|
||||
t.after(gateway.restore)
|
||||
const dir = await mkdtemp(join(tmpdir(), 'geek2api-key-choice-'))
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
// A stand-in CLI: records the key it was started with, prints one result.
|
||||
const out = join(dir, 'keys.log')
|
||||
const cli = join(dir, 'claude')
|
||||
await writeFile(cli, `#!/usr/bin/env node
|
||||
const { appendFileSync } = require('node:fs')
|
||||
appendFileSync(${JSON.stringify(out)}, process.env.ANTHROPIC_AUTH_TOKEN.slice(-4) + '\\n')
|
||||
process.stdin.resume()
|
||||
process.stdin.on('end', () => {
|
||||
console.log(JSON.stringify({ type: 'result', subtype: 'success', is_error: false, result: 'ok', usage: { input_tokens: 1, output_tokens: 1 } }))
|
||||
})
|
||||
`)
|
||||
await chmod(cli, 0o755)
|
||||
|
||||
const { ctx, seen } = context()
|
||||
apply(ctx, { claudeCliPath: cli, claudeCliMode: 'read-only', claudeCliCwd: dir, claudeRuntime: 'cli' })
|
||||
await seen.handler('keys/add', { key: KEY_CODEX, label: 'codex' })
|
||||
await seen.handler('keys/add', { key: KEY_CLAUDE, label: 'claude' })
|
||||
|
||||
// Active key without a Claude group: the run uses the cc key and says so.
|
||||
const passedOver = await turn(seen.adapter, 'claude-opus-5-5')
|
||||
const notes = passedOver.filter(chunk => chunk.type === 'reasoning-delta').map(chunk => chunk.text).join('')
|
||||
assert.match(notes, /当前 Key「codex」的分组不能用 claude-opus-5-5,本轮改用 Key「claude」(分组:cc)/u)
|
||||
|
||||
// "Use this key" on the cc key: the very next run uses it, named plainly.
|
||||
const status = await seen.handler('status', {})
|
||||
await seen.handler('keys/select', { id: status.value.keys.find(key => key.label === 'claude').id })
|
||||
const selected = await turn(seen.adapter, 'claude-opus-5-5')
|
||||
assert.match(selected.filter(chunk => chunk.type === 'reasoning-delta').map(chunk => chunk.text).join(''), /▸ 使用 Key「claude」(分组:cc)/u)
|
||||
|
||||
assert.deepEqual((await readFile(out, 'utf8')).trim().split('\n'), ['CCCC', 'CCCC'])
|
||||
})
|
||||
@@ -0,0 +1,156 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { Geek2APIKeyRing, assertApiKey } from '../src/key-ring.js'
|
||||
import { fakeCredentials } from './helpers.mjs'
|
||||
|
||||
/** Minimal credential-record service: one in-memory record, serialized writes. */
|
||||
const KEY_A = 'sk-aaaaaaaaaaaaaaaaaaaa'
|
||||
const KEY_B = 'sk-bbbbbbbbbbbbbbbbbbbb'
|
||||
const KEY_C = 'sk-cccccccccccccccccccc'
|
||||
|
||||
test('rejects keys the gateway could not carry in a header', () => {
|
||||
assert.equal(assertApiKey(' sk-abcdefgh12345678 '), 'sk-abcdefgh12345678')
|
||||
assert.throws(() => assertApiKey('short'), /printable ASCII/u)
|
||||
assert.throws(() => assertApiKey('sk-with space in it'), /printable ASCII/u)
|
||||
assert.throws(() => assertApiKey(''), /printable ASCII/u)
|
||||
})
|
||||
|
||||
test('adds keys in order and keeps the first one active', async () => {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add(KEY_A, 'primary')
|
||||
await ring.add(KEY_B)
|
||||
const state = await ring.list()
|
||||
assert.equal(state.keys.length, 2)
|
||||
assert.equal(state.keys[0].label, 'primary')
|
||||
assert.equal(state.keys[1].label, 'Key 2')
|
||||
assert.equal(state.activeId, state.keys[0].id)
|
||||
assert.equal((await ring.activeKey()).key, KEY_A)
|
||||
// The projection never carries key material.
|
||||
assert.equal(JSON.stringify(state).includes('sk-'), false)
|
||||
})
|
||||
|
||||
test('refuses a duplicate key', async () => {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add(KEY_A)
|
||||
await assert.rejects(() => ring.add(KEY_A), /already stored/u)
|
||||
})
|
||||
|
||||
test('disabling the active key moves to the next usable one', async () => {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add(KEY_A)
|
||||
await ring.add(KEY_B)
|
||||
await ring.add(KEY_C)
|
||||
const [a, b] = (await ring.list()).keys
|
||||
|
||||
await ring.disable(a.id, 'quota')
|
||||
assert.equal((await ring.activeKey()).key, KEY_B)
|
||||
const afterFirst = await ring.list()
|
||||
assert.equal(afterFirst.keys[0].disabled, true)
|
||||
assert.equal(afterFirst.keys[0].disabledReason, 'quota')
|
||||
|
||||
await ring.disable(b.id, 'invalid-key')
|
||||
assert.equal((await ring.activeKey()).key, KEY_C)
|
||||
|
||||
// Re-enabling a key makes it eligible again without stealing the pointer.
|
||||
await ring.enable(a.id)
|
||||
assert.equal((await ring.activeKey()).key, KEY_C)
|
||||
})
|
||||
|
||||
test('every key disabled leaves no usable key instead of a silent fallback', async () => {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add(KEY_A)
|
||||
const [a] = (await ring.list()).keys
|
||||
await ring.disable(a.id, 'quota')
|
||||
assert.equal(await ring.activeKey(), undefined)
|
||||
})
|
||||
|
||||
test('select, remove, and removeAll keep the ring consistent', async () => {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add(KEY_A)
|
||||
await ring.add(KEY_B)
|
||||
const [a, b] = (await ring.list()).keys
|
||||
|
||||
await ring.select(b.id)
|
||||
assert.equal((await ring.list()).activeId, b.id)
|
||||
assert.equal((await ring.activeKey()).key, KEY_B)
|
||||
|
||||
await ring.remove(b.id)
|
||||
const afterRemove = await ring.list()
|
||||
assert.equal(afterRemove.keys.length, 1)
|
||||
assert.equal(afterRemove.activeId, a.id)
|
||||
|
||||
await ring.removeAll()
|
||||
assert.deepEqual(await ring.list(), { activeId: undefined, keys: [] })
|
||||
await assert.rejects(() => ring.select('missing'), /Unknown Geek2API key/u)
|
||||
})
|
||||
|
||||
test('tolerates a hand-edited record instead of failing the route', async () => {
|
||||
const credentials = fakeCredentials()
|
||||
const ring = new Geek2APIKeyRing(credentials)
|
||||
await ring.add(KEY_A)
|
||||
const payload = credentials.payload()
|
||||
// A record whose activeId names no stored key still serves the first key.
|
||||
await credentials.modifyRecord('ignored', async () => ({
|
||||
kind: 'grant',
|
||||
payload: { ...payload, activeId: 'gone' },
|
||||
}))
|
||||
assert.equal((await ring.activeKey()).key, KEY_A)
|
||||
})
|
||||
|
||||
test('secrets() is host-side material and marks disabled keys', async () => {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add(KEY_A)
|
||||
const [a] = (await ring.list()).keys
|
||||
await ring.disable(a.id, 'quota')
|
||||
const secrets = await ring.secrets()
|
||||
assert.equal(secrets.length, 1)
|
||||
assert.equal(secrets[0].key, KEY_A)
|
||||
assert.equal(secrets[0].disabled, true)
|
||||
})
|
||||
|
||||
test('a default label never collides after a removal', async () => {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add(KEY_A)
|
||||
await ring.add(KEY_B)
|
||||
const [first] = (await ring.list()).keys
|
||||
await ring.remove(first.id)
|
||||
// The ring shrank to one key, but "Key 2" is taken: the next name must not repeat it.
|
||||
await ring.add(KEY_C)
|
||||
const labels = (await ring.list()).keys.map(candidate => candidate.label)
|
||||
assert.deepEqual(labels, ['Key 2', 'Key 3'])
|
||||
assert.equal(new Set(labels).size, labels.length)
|
||||
})
|
||||
|
||||
test('an explicit label is kept verbatim and may repeat', async () => {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add(KEY_A, '战魂铭人-张洋凡')
|
||||
await ring.add(KEY_B, '战魂铭人-张洋凡')
|
||||
const labels = (await ring.list()).keys.map(candidate => candidate.label)
|
||||
assert.deepEqual(labels, ['战魂铭人-张洋凡', '战魂铭人-张洋凡'])
|
||||
})
|
||||
|
||||
test('rename replaces a label, keeps the key and active pointer, and trims', async () => {
|
||||
const credentials = fakeCredentials()
|
||||
const ring = new Geek2APIKeyRing(credentials)
|
||||
await ring.add(KEY_A)
|
||||
await ring.add(KEY_B)
|
||||
const [first, second] = (await ring.list()).keys
|
||||
const state = await ring.rename(second.id, ' 备用 Key ')
|
||||
assert.deepEqual(state.keys.map(candidate => candidate.label), [first.label, '备用 Key'])
|
||||
assert.equal(state.activeId, first.id)
|
||||
assert.equal(credentials.payload().keys[1].key, KEY_B)
|
||||
assert.equal((await ring.rename(first.id, 'x'.repeat(80))).keys[0].label.length, 60)
|
||||
})
|
||||
|
||||
test('rename keeps a disabled mark and rejects an empty name or an unknown id', async () => {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add(KEY_A)
|
||||
const [a] = (await ring.list()).keys
|
||||
await ring.disable(a.id, 'quota')
|
||||
const [renamed] = (await ring.rename(a.id, 'main')).keys
|
||||
assert.equal(renamed.disabled, true)
|
||||
assert.equal(renamed.disabledReason, 'quota')
|
||||
await assert.rejects(ring.rename(a.id, ' '), /cannot be empty/)
|
||||
await assert.rejects(ring.rename('nope', 'x'), /Unknown Geek2API key/)
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { stringify } from 'yaml'
|
||||
|
||||
import { readStoredKey } from '../scripts/stored-key.mjs'
|
||||
|
||||
async function file(t, record, extra = {}) {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'geek2api-live-key-'))
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
const path = join(dir, 'credentials.yaml')
|
||||
await writeFile(path, stringify({ version: 2, records: { 'geek2api/keys': record }, ...extra }), { mode: 0o600 })
|
||||
return path
|
||||
}
|
||||
|
||||
const grant = keys => ({ kind: 'grant', payload: { version: 1, activeId: 'second', keys } })
|
||||
const KEYS = [
|
||||
{ id: 'first', label: 'First', key: 'sk-fixture-first', addedAt: 1 },
|
||||
{ id: 'second', label: 'Grok', key: 'sk-fixture-second', addedAt: 2 },
|
||||
]
|
||||
|
||||
test('live checks use the plugin-owned active key and do not change the credential file', async t => {
|
||||
const filePath = await file(t, grant(KEYS), { refs: { GEEK2API_API_KEY: 'sk-fixture-unrelated-reference' } })
|
||||
const before = await readFile(filePath, 'utf8')
|
||||
assert.equal(await readStoredKey({ filePath }), 'sk-fixture-second')
|
||||
assert.equal(await readStoredKey({ filePath, label: 'First' }), 'sk-fixture-first')
|
||||
assert.equal(await readFile(filePath, 'utf8'), before)
|
||||
})
|
||||
|
||||
test('live checks refuse missing, disabled and ambiguous labels', async t => {
|
||||
const filePath = await file(t, grant([{ ...KEYS[0], disabledAt: 3 }, KEYS[1], { ...KEYS[1], id: 'duplicate' }]))
|
||||
for (const label of ['First', 'Missing', 'Grok']) {
|
||||
await assert.rejects(() => readStoredKey({ filePath, label }), /one usable key/u)
|
||||
}
|
||||
})
|
||||
|
||||
test('a reference, legacy entry or unrelated record never substitutes for a missing plugin key', async t => {
|
||||
const filePath = await file(t, undefined, {
|
||||
GEEK2API_API_KEY: 'sk-fixture-legacy',
|
||||
refs: { GEEK2API_API_KEY: 'sk-fixture-reference' },
|
||||
records: { 'another-plugin/keys': grant(KEYS) },
|
||||
})
|
||||
await assert.rejects(() => readStoredKey({ filePath }), /added under Settings/u)
|
||||
})
|
||||
|
||||
test('a YAML parse error never returns its secret-bearing source line', async t => {
|
||||
const filePath = await file(t, grant(KEYS))
|
||||
await writeFile(filePath, 'secret: "sk-fixture-private-unclosed\n')
|
||||
await assert.rejects(() => readStoredKey({ filePath }), error => {
|
||||
assert.equal(error.message, 'Geek2API plugin credentials could not be read safely')
|
||||
assert.equal(String(error).includes('sk-fixture'), false)
|
||||
return true
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { LlmRuntime } from '@deepseek-ai/dsh-llm'
|
||||
|
||||
import { GEEK2API_MODEL_IDS } from '../src/catalog.js'
|
||||
import { apply, Config } from '../src/index.js'
|
||||
import { createModelSelectionController, readHiddenModels } from '../src/model-selection.js'
|
||||
import { fieldValue } from '../src/preferences.js'
|
||||
import { createRouteAdapter } from '../src/route.js'
|
||||
import { fakeCredentials } from './helpers.mjs'
|
||||
|
||||
/** Exercise both real settings seams and the registered model adapter/RPC. */
|
||||
function host({ generation = '0.2', writable = true, failWrite = false, initial = {} } = {}) {
|
||||
let values = { ...initial }
|
||||
const seen = { updates: [], notifications: 0, handler: undefined, adapter: undefined, listeners: new Map() }
|
||||
let hooks
|
||||
const settings = {
|
||||
writable,
|
||||
async update(id, patch) {
|
||||
assert.equal(id, 'geek2api')
|
||||
if (failWrite) throw new Error('fixture: storage failed')
|
||||
seen.updates.push(patch)
|
||||
values = { ...values, ...patch }
|
||||
if (generation === '0.1') hooks.onChange()
|
||||
else seen.listeners.get('loader/volatile-update')?.()
|
||||
},
|
||||
configure: () => () => {},
|
||||
}
|
||||
if (generation === '0.1') {
|
||||
settings.installSection = (_ctx, _ns, _schema, source, callbacks) => {
|
||||
values = { ...source, ...values }
|
||||
hooks = callbacks
|
||||
hooks.setSource(() => values)
|
||||
}
|
||||
}
|
||||
const ctx = {
|
||||
credentials: fakeCredentials(),
|
||||
logger: { warn() {} },
|
||||
fiber: { entry: { options: { id: 'geek2api' } } },
|
||||
llm: {
|
||||
registerAdapter(_providers, adapter) {
|
||||
seen.adapter = adapter
|
||||
const handle = () => {}
|
||||
handle.replace = providers => {
|
||||
assert.deepEqual(providers, ['geek2api'])
|
||||
seen.notifications += 1
|
||||
}
|
||||
return handle
|
||||
},
|
||||
registerConfigurableProviders: () => () => {},
|
||||
},
|
||||
get: () => undefined,
|
||||
on(event, callback) { seen.listeners.set(event, callback) },
|
||||
inject(names, callback) {
|
||||
if (names.includes('settings')) return callback({ settings, effect: ctx.effect })
|
||||
if (names.includes('connection')) return callback({ effect: ctx.effect, connection: { rpc: { handle(_channel, handler) { seen.handler = handler; return () => {} } } } })
|
||||
// These fixtures intentionally mount no search or CLI tool service.
|
||||
},
|
||||
effect(callback) { return callback() },
|
||||
}
|
||||
const config = generation === '0.2' ? { hiddenModels: { get: () => values.hiddenModels } } : {}
|
||||
apply(ctx, config)
|
||||
return {
|
||||
seen,
|
||||
changeHidden(ids) { values = { ...values, hiddenModels: ids }; seen.listeners.get('loader/volatile-update')() },
|
||||
reapply: () => host({ generation, initial: values }),
|
||||
}
|
||||
}
|
||||
|
||||
test('model preferences are volatile, default to all models and expose only public descriptors', async () => {
|
||||
assert.equal(Config.dict.hiddenModels.meta.volatile, true)
|
||||
assert.deepEqual(fieldValue(new Config({}).hiddenModels), [])
|
||||
const { seen } = host()
|
||||
const reply = await seen.handler('models/status')
|
||||
assert.equal(reply.ok, true)
|
||||
assert.equal(reply.value.writable, true)
|
||||
assert.deepEqual(reply.value.models.map(model => model.id), [...GEEK2API_MODEL_IDS])
|
||||
assert.ok(reply.value.models.every(model => model.selected))
|
||||
assert.deepEqual(Object.keys(reply.value.models[0]).sort(), ['id', 'name', 'selected'])
|
||||
assert.deepEqual((await seen.adapter.listModels('geek2api')).map(model => model.id), [...GEEK2API_MODEL_IDS])
|
||||
})
|
||||
|
||||
for (const generation of ['0.1', '0.2']) {
|
||||
test(`DSH ${generation}: checkboxes persist, refresh the picker, and survive plugin reconstruction`, async () => {
|
||||
const env = host({ generation })
|
||||
const { seen } = env
|
||||
const reply = await seen.handler('models/update', { selectedIds: ['grok-4.7', 'deepseek-v4.1-flash', 'grok-4.7'] })
|
||||
assert.equal(reply.ok, true)
|
||||
assert.deepEqual(reply.value.models.filter(model => model.selected).map(model => model.id), ['deepseek-v4.1-flash', 'grok-4.7'])
|
||||
assert.deepEqual(seen.updates, [{ hiddenModels: GEEK2API_MODEL_IDS.filter(id => !['deepseek-v4.1-flash', 'grok-4.7'].includes(id)) }])
|
||||
assert.equal(seen.notifications, 1, 'one registry refresh, even when the settings hook fires during the write')
|
||||
assert.deepEqual((await seen.adapter.listModels('geek2api')).map(model => model.id), ['deepseek-v4.1-flash', 'grok-4.7'])
|
||||
assert.deepEqual((await env.reapply().seen.adapter.listModels('geek2api')).map(model => model.id), ['deepseek-v4.1-flash', 'grok-4.7'])
|
||||
|
||||
// Resolution and preparation use the full catalog for existing sessions.
|
||||
const hidden = await seen.adapter.resolveModel('geek2api', 'gpt-6.1-sol')
|
||||
assert.equal(hidden.id, 'gpt-6.1-sol')
|
||||
assert.equal((await seen.adapter.prepareCall('geek2api', 'gpt-6.1-sol')).model.id, 'gpt-6.1-sol')
|
||||
assert.equal((await seen.adapter.resolveModel('geek2api', 'claude-opus-5-5')).id, 'claude-opus-5-5')
|
||||
|
||||
await seen.handler('models/update', { selectedIds: [] })
|
||||
assert.deepEqual(await seen.adapter.listModels('geek2api'), [], 'Select none must not revert to all')
|
||||
const all = await seen.handler('models/update', { selectedIds: [...GEEK2API_MODEL_IDS] })
|
||||
assert.ok(all.value.models.every(model => model.selected))
|
||||
assert.deepEqual(seen.updates.at(-1), { hiddenModels: [] })
|
||||
assert.equal(seen.notifications, 3)
|
||||
})
|
||||
}
|
||||
|
||||
test('a volatile edit elsewhere refreshes only once, without changing other settings', async () => {
|
||||
const { seen, changeHidden } = host()
|
||||
changeHidden(['gpt-6-astra', 'deepseek-v4.1-flash'])
|
||||
assert.equal(seen.notifications, 1)
|
||||
changeHidden(['deepseek-v4.1-flash', 'gpt-6-astra', 'deepseek-v4.1-flash', 'future-model'])
|
||||
assert.equal(seen.notifications, 1, 'order, duplicates and unknown exclusions do not change the picker')
|
||||
assert.deepEqual(seen.updates, [])
|
||||
assert.ok((await seen.adapter.listModels('geek2api')).some(model => model.id === 'grok-4.7'), 'new models default to selected')
|
||||
})
|
||||
|
||||
test('unsupported selections are refused without writing preferences', async () => {
|
||||
const { seen } = host()
|
||||
for (const selectedIds of [undefined, null, 'grok-4.7', ['unknown'], [1], ['grok-4.7', {}]]) {
|
||||
const reply = await seen.handler('models/update', { selectedIds })
|
||||
assert.equal(reply.ok, false)
|
||||
assert.match(reply.error.message, /not supported/u)
|
||||
assert.equal(typeof reply.error.code, 'string')
|
||||
assert.deepEqual(reply.error.details, {})
|
||||
}
|
||||
assert.deepEqual(seen.updates, [])
|
||||
assert.equal(seen.notifications, 0)
|
||||
})
|
||||
|
||||
for (const generation of ['0.1', '0.2']) {
|
||||
test(`DSH ${generation}: read-only and failed saves keep the previous selection`, async () => {
|
||||
for (const options of [{ writable: false }, { failWrite: true }]) {
|
||||
const { seen } = host({ generation, ...options })
|
||||
const before = await seen.handler('models/status')
|
||||
assert.equal(before.value.writable, options.writable !== false)
|
||||
const failure = await seen.handler('models/update', { selectedIds: [] })
|
||||
assert.equal(failure.ok, false)
|
||||
assert.equal(typeof failure.error.code, 'string')
|
||||
assert.deepEqual(failure.error.details, {})
|
||||
assert.deepEqual((await seen.handler('models/status')).value.models, before.value.models)
|
||||
assert.deepEqual(seen.updates, [])
|
||||
assert.equal(seen.notifications, 0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
test('legacy, missing and invalid preference values keep the default; volatile exclusions are read', () => {
|
||||
for (const preference of [undefined, {}, { hiddenModels: null }, { hiddenModels: 'grok-4.7' }, { hiddenModels: ['retired-model'] }]) {
|
||||
assert.deepEqual(readHiddenModels(preference), [])
|
||||
}
|
||||
assert.deepEqual(readHiddenModels({ hiddenModels: { get: () => ['grok-4.7', 'unknown'] } }), ['grok-4.7'])
|
||||
})
|
||||
|
||||
test('the actual DSH LLM registry refreshes discovery atomically and keeps a prepared call usable', async () => {
|
||||
const ctx = new Context()
|
||||
const llm = new LlmRuntime(ctx)
|
||||
let preferences = {}
|
||||
let registration
|
||||
let notifications = 0
|
||||
ctx.on('llm/adapters-updated', () => { notifications += 1 })
|
||||
const selection = createModelSelectionController({
|
||||
readPreference: () => preferences,
|
||||
writePreference: async patch => { preferences = { ...preferences, ...patch } },
|
||||
isWritable: () => true,
|
||||
onChange: () => registration.replace(['geek2api']),
|
||||
})
|
||||
const adapter = createRouteAdapter({ ring: {}, keys: {}, isModelVisible: selection.isVisible })
|
||||
registration = llm.registerAdapter(['geek2api'], adapter)
|
||||
const prepared = await adapter.prepareCall('geek2api', 'deepseek-v4.1-flash')
|
||||
const before = notifications
|
||||
await selection.update({ selectedIds: [] })
|
||||
assert.equal(notifications, before + 1)
|
||||
assert.deepEqual(await llm.listModels('geek2api'), [])
|
||||
assert.equal((await adapter.resolveModel('geek2api', 'deepseek-v4.1-flash')).id, 'deepseek-v4.1-flash')
|
||||
assert.equal(prepared.model.id, 'deepseek-v4.1-flash')
|
||||
assert.equal(typeof prepared.stream, 'function')
|
||||
await selection.update({ selectedIds: ['grok-4.7'] })
|
||||
assert.deepEqual((await llm.listModels('geek2api')).map(model => model.id), ['grok-4.7'])
|
||||
registration()
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { capClaudeMode, claudeModeFor, claudeModeForSession, planModeForSession, planModeForToolExecution } from '../src/permission.js'
|
||||
|
||||
test('each permission preset maps to the CLI mode it allows', () => {
|
||||
assert.equal(claudeModeFor('read-only', 'ask'), 'read-only')
|
||||
assert.equal(claudeModeFor('workspace-write', 'ask'), 'edit')
|
||||
assert.equal(claudeModeFor('danger-full-access', 'never'), 'full')
|
||||
// The CLI cannot ask the harness user, so a session that still asks keeps its checks.
|
||||
assert.equal(claudeModeFor('danger-full-access', 'ask'), 'edit')
|
||||
assert.equal(claudeModeFor(undefined, 'never'), undefined)
|
||||
})
|
||||
|
||||
test('a session mode is read from the host permission services', () => {
|
||||
const session = { id: 's1' }
|
||||
const seen = []
|
||||
const ctx = {
|
||||
get: name => ({
|
||||
sandboxPolicy: { resolve: request => (seen.push(request.session), { mode: 'danger-full-access' }) },
|
||||
approval: { effectivePolicy: target => (seen.push(target), 'never') },
|
||||
})[name],
|
||||
}
|
||||
assert.equal(claudeModeForSession(ctx, session), 'full')
|
||||
assert.deepEqual(seen, [session, session])
|
||||
assert.equal(claudeModeForSession(ctx, undefined), undefined)
|
||||
assert.equal(claudeModeForSession({ get: () => undefined }, session), undefined)
|
||||
assert.equal(claudeModeForSession({ get: () => { throw new Error('inactive') } }, session), undefined)
|
||||
})
|
||||
|
||||
test('plan mode follows the in-flight selection, then the logged projection', () => {
|
||||
const session = { id: 's1' }
|
||||
const other = { id: 's2' }
|
||||
const ctx = {
|
||||
get: name => ({
|
||||
agents: { currentInitiator: () => ({ session }) },
|
||||
planMode: { get: agent => (agent.session === session ? { active: false, pending: true } : { active: false }) },
|
||||
sessionProjections: { stateOf: (target, key) => (target === other && key === 'plan' ? { active: true } : { active: false }) },
|
||||
})[name],
|
||||
}
|
||||
assert.equal(planModeForSession(ctx, session), true, 'pending wins over logged active')
|
||||
ctx.get = name => ({
|
||||
agents: { currentInitiator: () => ({ session: other }) },
|
||||
planMode: { get: () => ({ active: true }) },
|
||||
sessionProjections: { stateOf: (target, key) => (target === session && key === 'plan' ? { active: true } : undefined) },
|
||||
})[name]
|
||||
assert.equal(planModeForSession(ctx, session), true, 'a different initiator falls back to this session\'s projection')
|
||||
assert.equal(planModeForSession({ get: () => undefined }, session), false)
|
||||
assert.equal(planModeForSession({ get: () => { throw new Error('inactive') } }, session), false)
|
||||
assert.equal(planModeForSession(ctx, undefined), false)
|
||||
})
|
||||
|
||||
test('request selection and executing tools read different sides of an uncommitted transition', () => {
|
||||
const session = { id: 'same-batch' }
|
||||
const agent = { session }
|
||||
let state = { active: true, pending: false }
|
||||
const ctx = { get: name => ({
|
||||
agents: { currentInitiator: () => agent },
|
||||
planMode: { get: () => state },
|
||||
sessionProjections: { stateOf: () => ({ active: state.active }) },
|
||||
})[name] }
|
||||
assert.equal(planModeForSession(ctx, session), false, 'the next proposed model request uses selected exit')
|
||||
assert.equal(planModeForToolExecution(ctx, session, agent), true, 'approval does not authorize remaining batch tools')
|
||||
state = { active: false }
|
||||
assert.equal(planModeForSession(ctx, session), false)
|
||||
assert.equal(planModeForToolExecution(ctx, session, agent), false, 'accepted pre-step boundary commits exit')
|
||||
state = { active: false, pending: true }
|
||||
assert.equal(planModeForSession(ctx, session), true, 'the next proposed request uses selected entry')
|
||||
assert.equal(planModeForToolExecution(ctx, session, agent), false, 'pending entry leaves current batch at its existing mode')
|
||||
state = { active: true }
|
||||
assert.equal(planModeForToolExecution(ctx, session, agent), true, 'accepted pre-step boundary commits entry')
|
||||
})
|
||||
|
||||
test('executing tools use their explicit calling agent or logged projection, never another initiator pending state', () => {
|
||||
const session = { id: 'tool-session' }
|
||||
const caller = { session }
|
||||
const other = { session: { id: 'different-session' } }
|
||||
const seen = []
|
||||
const ctx = { get: name => ({
|
||||
agents: { currentInitiator: () => other },
|
||||
planMode: { get: agent => (seen.push(agent), { active: true, pending: false }) },
|
||||
sessionProjections: { stateOf: (target, key) => ({ active: target === session && key === 'plan' }) },
|
||||
})[name] }
|
||||
assert.equal(planModeForToolExecution(ctx, session, caller), true)
|
||||
assert.deepEqual(seen, [caller])
|
||||
assert.equal(planModeForToolExecution(ctx, session), true, 'projection is the fallback for a different initiator')
|
||||
assert.equal(planModeForToolExecution({ get: () => undefined }, session, caller), false)
|
||||
assert.equal(planModeForToolExecution({ get: () => { throw new Error('inactive') } }, session, caller), false)
|
||||
assert.equal(planModeForToolExecution(ctx, undefined), false)
|
||||
})
|
||||
|
||||
test('a requested mode never exceeds the session ceiling', () => {
|
||||
assert.equal(capClaudeMode('full', 'edit'), 'edit')
|
||||
assert.equal(capClaudeMode('read-only', 'full'), 'read-only')
|
||||
assert.equal(capClaudeMode(undefined, 'full'), 'full')
|
||||
assert.equal(capClaudeMode('full', undefined), 'full')
|
||||
assert.equal(capClaudeMode(undefined, undefined), undefined)
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { GEEK2API_MODEL_IDS } from '../src/catalog.js'
|
||||
import { DEFAULT_API_HOSTS } from '../src/constants.js'
|
||||
import { apply, inject, name } from '../src/index.js'
|
||||
import { fakeCredentials } from './helpers.mjs'
|
||||
|
||||
/**
|
||||
* A context that records what the plugin registers. Every service this plugin
|
||||
* injects is present, so a wiring mistake in `apply()` fails here rather than
|
||||
* at the user's next boot.
|
||||
*/
|
||||
function stubContext() {
|
||||
const registered = { adapters: [], directories: [], rpc: [], effects: [], tools: [] }
|
||||
const ctx = {
|
||||
credentials: fakeCredentials(),
|
||||
injected: [],
|
||||
injectedOptions: [],
|
||||
attachments: undefined,
|
||||
logger: { warn: () => {} },
|
||||
llm: {
|
||||
registerAdapter(providers, adapter) {
|
||||
registered.adapters.push({ providers, adapter })
|
||||
return () => {}
|
||||
},
|
||||
registerConfigurableProviders(entries) {
|
||||
registered.directories.push(entries)
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
connection: {
|
||||
rpc: {
|
||||
handle(channel, handler) {
|
||||
registered.rpc.push({ channel, handler })
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
},
|
||||
tools: {
|
||||
register(definition) {
|
||||
registered.tools.push(definition)
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
get: () => undefined,
|
||||
inject(services, callback) {
|
||||
ctx.injected.push(services)
|
||||
callback(ctx)
|
||||
},
|
||||
effect(callback, label) {
|
||||
registered.effects.push(label)
|
||||
const disposer = callback()
|
||||
return typeof disposer === 'function' ? disposer : () => {}
|
||||
},
|
||||
}
|
||||
return { ctx, registered }
|
||||
}
|
||||
|
||||
test('registers one route and one directory entry, and defers the browser surface', async () => {
|
||||
const { ctx, registered } = stubContext()
|
||||
apply(ctx)
|
||||
|
||||
assert.equal(name, 'geek2api')
|
||||
// A profile without a browser surface must still boot: only the route is mandatory.
|
||||
assert.deepEqual(inject, ['llm', 'credentials'])
|
||||
|
||||
assert.equal(registered.adapters.length, 1)
|
||||
assert.deepEqual(registered.adapters[0].providers, ['geek2api'])
|
||||
const models = await registered.adapters[0].adapter.listModels('geek2api')
|
||||
assert.deepEqual(models.map(model => model.id), [...GEEK2API_MODEL_IDS])
|
||||
|
||||
assert.deepEqual(registered.directories[0], [{
|
||||
provider: 'geek2api',
|
||||
displayName: 'Geek2API',
|
||||
settingsNs: 'geek2api',
|
||||
settingsPath: [],
|
||||
}])
|
||||
|
||||
// Every optional surface is requested through ctx.inject, never injected.
|
||||
// `webServer` rides with `connection`: channel registration writes through
|
||||
// `owner.webServer`, so a scope holding only `connection` cannot register.
|
||||
// `web` carries the search providers; a profile without it still boots.
|
||||
assert.deepEqual(ctx.injected, [['settings'], ['web'], ['connection', 'webServer'], ['tools']])
|
||||
assert.equal(registered.rpc.length, 1)
|
||||
assert.equal(registered.rpc[0].channel, '/geek2api')
|
||||
assert.ok(registered.effects.some(label => label.includes('loopback')))
|
||||
|
||||
// The Claude Code bridge registers one tool with a bounded schema.
|
||||
assert.equal(registered.tools.length, 1)
|
||||
const tool = registered.tools[0]
|
||||
assert.equal(tool.name, 'claude_code')
|
||||
// defineTool converts the field spec into JSON Schema before registration.
|
||||
assert.deepEqual(Object.keys(tool.parameters.properties), ['prompt', 'mode', 'model', 'cwd'])
|
||||
assert.deepEqual(tool.parameters.required, ['prompt'])
|
||||
assert.deepEqual([...tool.parameters.properties.mode.enum], ['read-only', 'edit', 'full'])
|
||||
assert.equal(typeof tool.execute, 'function')
|
||||
})
|
||||
|
||||
test('a profile without a connection service still registers the route', () => {
|
||||
const { ctx, registered } = stubContext()
|
||||
// The connection service never appears, exactly as in a headless profile.
|
||||
ctx.inject = (services, callback) => {
|
||||
ctx.injected.push(services)
|
||||
if (services.includes('connection')) return
|
||||
callback(ctx)
|
||||
}
|
||||
apply(ctx)
|
||||
assert.equal(registered.adapters.length, 1)
|
||||
assert.deepEqual(registered.rpc, [])
|
||||
})
|
||||
|
||||
test('the RPC surface refuses key material and answers status without one', async () => {
|
||||
const { ctx, registered } = stubContext()
|
||||
apply(ctx)
|
||||
const handler = registered.rpc[0].handler
|
||||
|
||||
const status = await handler('status')
|
||||
assert.equal(status.ok, true)
|
||||
assert.deepEqual(status.value.keys, [])
|
||||
assert.equal(status.value.activeId, undefined)
|
||||
// Every default entry point is listed, the first one preferred before any probe.
|
||||
assert.deepEqual(status.value.hosts.map(entry => entry.host), [...DEFAULT_API_HOSTS])
|
||||
assert.equal(status.value.hosts[0].current, true)
|
||||
assert.deepEqual(status.value.defaults, { apiHosts: [...DEFAULT_API_HOSTS] })
|
||||
assert.equal(status.value.claudeRuntime, 'http', 'Claude runs over HTTP unless the profile asks for the CLI')
|
||||
// Without a settings service nothing is writable, and the RPC says so.
|
||||
assert.equal(status.value.writable, false)
|
||||
const runtime = await handler('claude-runtime/update', { runtime: 'cli' })
|
||||
assert.equal(runtime.ok, false)
|
||||
assert.match(runtime.error.message, /not writable/u)
|
||||
|
||||
const added = await handler('keys/add', { key: 'sk-abcdefgh12345678', label: 'first' })
|
||||
assert.equal(added.ok, true)
|
||||
assert.equal(added.value.keys.length, 1)
|
||||
assert.equal(added.value.keys[0].label, 'first')
|
||||
assert.equal(JSON.stringify(added.value).includes('sk-abcdefgh'), false)
|
||||
|
||||
const listed = await handler('keys/status')
|
||||
assert.equal(listed.ok, false)
|
||||
assert.match(listed.error.message, /Unknown Geek2API endpoint/u)
|
||||
|
||||
const rejected = await handler('keys/add', { key: 'nope' })
|
||||
assert.equal(rejected.ok, false)
|
||||
assert.match(rejected.error.message, /printable ASCII/u)
|
||||
})
|
||||
@@ -0,0 +1,361 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, mkdir, symlink, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
compareSemver,
|
||||
createGeek2APIPluginManager,
|
||||
NPM_REGISTRY_LATEST_URL,
|
||||
PACKAGE_NAME,
|
||||
parseSemver,
|
||||
resolvePnpm,
|
||||
} from '../src/plugin-version.js'
|
||||
import { createGeek2APIRpc } from '../src/rpc.js'
|
||||
|
||||
const writeManifest = async (path, manifest) => {
|
||||
await mkdir(join(path, '..'), { recursive: true })
|
||||
await writeFile(path, JSON.stringify(manifest))
|
||||
}
|
||||
|
||||
/** Fake DSH home whose `web` profile installed the package from the registry. */
|
||||
async function npmInstall(root, version = '1.0.3') {
|
||||
const installedDir = join(root, 'profiles', 'web', 'node_modules', PACKAGE_NAME)
|
||||
await writeManifest(join(root, 'profiles', 'web', 'package.json'), {
|
||||
dependencies: { [PACKAGE_NAME]: version },
|
||||
})
|
||||
await writeManifest(join(installedDir, 'package.json'), { name: PACKAGE_NAME, version })
|
||||
return pathToFileURL(join(installedDir, 'package.json'))
|
||||
}
|
||||
|
||||
/** Fake DSH home whose `web` profile links a local checkout. */
|
||||
async function linkInstall(root, version = '1.0.3') {
|
||||
const checkout = join(root, 'checkout')
|
||||
await writeManifest(join(checkout, 'package.json'), { name: PACKAGE_NAME, version })
|
||||
await writeManifest(join(root, 'profiles', 'web', 'package.json'), {
|
||||
dependencies: { [PACKAGE_NAME]: 'link:../../checkout' },
|
||||
})
|
||||
const modules = join(root, 'profiles', 'web', 'node_modules')
|
||||
await mkdir(modules, { recursive: true })
|
||||
await symlink(checkout, join(modules, PACKAGE_NAME), 'dir')
|
||||
return pathToFileURL(join(checkout, 'package.json'))
|
||||
}
|
||||
|
||||
const registryOk = version => async () => ({ ok: true, status: 200, async json() { return { version } } })
|
||||
|
||||
const rpc = pluginManager => createGeek2APIRpc({
|
||||
ring: {},
|
||||
balance: {},
|
||||
hosts: () => ({}),
|
||||
preference: {},
|
||||
pluginManager,
|
||||
})
|
||||
|
||||
test('semver parsing and comparison drive the update badge', () => {
|
||||
assert.deepEqual(parseSemver(' 1.0.3 '), { major: 1, minor: 0, patch: 3, pre: undefined })
|
||||
assert.equal(parseSemver('v1.0.3'), undefined)
|
||||
assert.equal(parseSemver('1.0'), undefined)
|
||||
assert.equal(compareSemver('1.0.3', '1.0.4'), -1)
|
||||
assert.equal(compareSemver('1.0.4', '1.0.3'), 1)
|
||||
assert.equal(compareSemver('1.0.0', '1.0.0-rc.1'), 1)
|
||||
assert.equal(compareSemver('not-a-version', '1.0.3'), undefined)
|
||||
})
|
||||
|
||||
test('version check asks the registry for an uncompressed document', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-encoding-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root, '1.0.3')
|
||||
const original = globalThis.fetch
|
||||
let acceptEncoding
|
||||
globalThis.fetch = async (_url, init) => {
|
||||
acceptEncoding = new Headers(init?.headers).get('accept-encoding')
|
||||
if (acceptEncoding !== 'identity') {
|
||||
return { ok: true, status: 200, async json() { throw new SyntaxError('gzip body') } }
|
||||
}
|
||||
return { ok: true, status: 200, async json() { return { version: '1.0.3' } } }
|
||||
}
|
||||
try {
|
||||
const value = await createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
}).read({ force: true })
|
||||
assert.equal(acceptEncoding, 'identity')
|
||||
assert.equal(value.latest, '1.0.3')
|
||||
assert.equal(value.updateAvailable, false)
|
||||
} finally {
|
||||
globalThis.fetch = original
|
||||
}
|
||||
})
|
||||
|
||||
test('version read combines own manifest, registry latest, and the owning npm profile', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-npm-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root)
|
||||
let requests = 0
|
||||
let observed
|
||||
let clock = 1000
|
||||
const manager = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
now: () => clock,
|
||||
fetchImpl: (url, init) => {
|
||||
requests += 1
|
||||
observed = { url, redirect: init.redirect }
|
||||
return registryOk('1.0.4')()
|
||||
},
|
||||
})
|
||||
const first = await manager.read()
|
||||
assert.deepEqual(first, {
|
||||
current: '1.0.3',
|
||||
latest: '1.0.4',
|
||||
updateAvailable: true,
|
||||
install: { kind: 'npm', profile: 'web' },
|
||||
fetchedAt: 1000,
|
||||
})
|
||||
assert.deepEqual(observed, { url: NPM_REGISTRY_LATEST_URL, redirect: 'error' })
|
||||
await manager.read()
|
||||
assert.equal(requests, 1, 'fresh cached reads stay off the network')
|
||||
await manager.read({ force: true })
|
||||
assert.equal(requests, 2)
|
||||
})
|
||||
|
||||
test('registry failures and malformed payloads surface one sanitized error', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-down-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root)
|
||||
const failing = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
fetchImpl: async () => ({ ok: false, status: 500 }),
|
||||
})
|
||||
await assert.rejects(() => failing.read(), /^Error: Geek2API plugin version check failed$/u)
|
||||
const malformed = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
fetchImpl: async () => ({ ok: true, status: 200, async json() { return { version: 'not-a-version' } } }),
|
||||
})
|
||||
await assert.rejects(() => malformed.read(), /^Error: Geek2API plugin version check failed$/u)
|
||||
})
|
||||
|
||||
test('linked checkouts are reported but never updated in place', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-link-'))
|
||||
const ownPackageJsonUrl = await linkInstall(root)
|
||||
const manager = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
fetchImpl: registryOk('1.0.4'),
|
||||
runCommand: async () => {
|
||||
throw new Error('runCommand must not run for linked installs')
|
||||
},
|
||||
})
|
||||
const info = await manager.read()
|
||||
assert.equal(info.install.kind, 'link')
|
||||
assert.equal(info.install.profile, 'web')
|
||||
assert.equal(info.updateAvailable, true)
|
||||
await assert.rejects(() => manager.update(), /^Error: Geek2API plugin is installed from a local checkout$/u)
|
||||
})
|
||||
|
||||
/** A fake desktop runtime: argv carries the host entry, the dsh runtime, and bundled pnpm. */
|
||||
async function desktopRuntime(root) {
|
||||
const runtimeDir = join(root, 'resources', 'app.asar', 'dsh')
|
||||
const hostEntry = join(runtimeDir, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'index.js')
|
||||
const pnpm = join(root, 'resources', 'runtime', 'pnpm', 'bin', 'pnpm.mjs')
|
||||
await writeManifest(join(runtimeDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json'), {
|
||||
name: '@deepseek-ai/dsh',
|
||||
version: '0.1.7-rc.2',
|
||||
})
|
||||
await writeManifest(hostEntry, { name: '@deepseek-ai/dsh-desktop-host', version: '0.1.7-rc.2' })
|
||||
await writeManifest(pnpm, { name: 'pnpm', version: '11.7.0' })
|
||||
return {
|
||||
runtimeDir,
|
||||
hostEntry,
|
||||
pnpm,
|
||||
argv: [
|
||||
join(root, 'DeepSeek Harness'),
|
||||
hostEntry,
|
||||
runtimeDir,
|
||||
join(root, 'profiles', 'desktop'),
|
||||
join(root, 'resources', 'runtime', 'primary-runtime'),
|
||||
pnpm,
|
||||
join(root, 'resources', 'runtime', 'bin'),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
const installRecorder = async ({ args, cwd }) => {
|
||||
await writeManifest(join(cwd, 'node_modules', PACKAGE_NAME, 'package.json'), {
|
||||
name: PACKAGE_NAME,
|
||||
version: args.at(-1).split('@').at(-1),
|
||||
})
|
||||
return { code: 0, stdout: '', stderr: '' }
|
||||
}
|
||||
|
||||
test('update installs the exact version into the owning profile, pinned and age-free', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-update-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root)
|
||||
const calls = []
|
||||
let registryRequests = 0
|
||||
const manager = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
execPath: '/node',
|
||||
argv: ['/node', '/dsh/bin.js'],
|
||||
fetchImpl: () => {
|
||||
registryRequests += 1
|
||||
return registryOk('1.0.4')()
|
||||
},
|
||||
runCommand: async (call, options) => {
|
||||
calls.push(call)
|
||||
return installRecorder(call, options)
|
||||
},
|
||||
})
|
||||
const updated = await manager.update()
|
||||
assert.deepEqual(updated, { version: '1.0.4', profile: 'web' })
|
||||
assert.equal(calls[0].command, 'pnpm')
|
||||
assert.deepEqual(calls[0].args, [
|
||||
'add', '--save-exact', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@1.0.4`,
|
||||
])
|
||||
assert.equal(calls[0].cwd, join(root, 'profiles', 'web'))
|
||||
await manager.read()
|
||||
assert.equal(registryRequests, 2, 'a successful update invalidates the cached version')
|
||||
})
|
||||
|
||||
test('desktop hosts install with the bundled pnpm, never by launching the desktop host again', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-desktop-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root, '1.0.3')
|
||||
const runtime = await desktopRuntime(root)
|
||||
assert.equal(resolvePnpm({ argv: runtime.argv }), runtime.pnpm)
|
||||
const calls = []
|
||||
const manager = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
execPath: '/Applications/DeepSeek Harness',
|
||||
argv: runtime.argv,
|
||||
fetchImpl: registryOk('1.0.4'),
|
||||
runCommand: async (call, options) => {
|
||||
calls.push(call)
|
||||
return installRecorder(call, options)
|
||||
},
|
||||
})
|
||||
assert.deepEqual(await manager.update(), { version: '1.0.4', profile: 'web' })
|
||||
const [call] = calls
|
||||
assert.equal(call.command, '/Applications/DeepSeek Harness')
|
||||
assert.deepEqual(call.args, [
|
||||
runtime.pnpm, 'add', '--save-exact', '--config.minimumReleaseAge=0', `${PACKAGE_NAME}@1.0.4`,
|
||||
])
|
||||
const flattened = JSON.stringify(call)
|
||||
assert.equal(flattened.includes(runtime.hostEntry), false)
|
||||
assert.equal(flattened.includes('plugin'), false)
|
||||
})
|
||||
|
||||
test('an update that installs nothing is a failure, not a reported success', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-verify-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root, '1.0.3')
|
||||
const manager = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
fetchImpl: registryOk('1.0.4'),
|
||||
settleDelayMs: 1,
|
||||
runCommand: async () => ({ code: 0, stdout: '', stderr: '' }),
|
||||
})
|
||||
await assert.rejects(
|
||||
() => manager.update(),
|
||||
/^Error: Geek2API plugin update did not install the requested version$/u,
|
||||
)
|
||||
})
|
||||
|
||||
test('the package-manager resolver trusts only real pnpm entries and owned runtime roots', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-resolve-'))
|
||||
const runtime = await desktopRuntime(root)
|
||||
const elsewhere = await mkdtemp(join(tmpdir(), 'geek2api-version-resolve-other-'))
|
||||
const otherPnpm = join(elsewhere, 'resources', 'pnpm', 'bin', 'pnpm.mjs')
|
||||
|
||||
assert.equal(resolvePnpm({ argv: runtime.argv }), runtime.pnpm)
|
||||
assert.equal(resolvePnpm({ argv: ['/node', '--expose-internals', '/dsh/bin.js'] }), undefined)
|
||||
assert.equal(resolvePnpm({ argv: ['/node', runtime.hostEntry] }), undefined)
|
||||
assert.equal(resolvePnpm({ argv: ['/node', '/somewhere/pnpm-not-really'] }), undefined)
|
||||
assert.equal(resolvePnpm({ argv: ['/node', join(root, 'missing', 'pnpm.mjs')] }), undefined)
|
||||
|
||||
await writeManifest(otherPnpm, { name: 'pnpm', version: '11.7.0' })
|
||||
const runtimeDir = join(elsewhere, 'resources', 'runtime')
|
||||
await writeManifest(join(runtimeDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json'), {
|
||||
name: '@deepseek-ai/dsh',
|
||||
version: '0.1.7-rc.2',
|
||||
})
|
||||
assert.equal(
|
||||
resolvePnpm({ argv: ['/node', join(elsewhere, 'index.js'), runtimeDir] }),
|
||||
otherPnpm,
|
||||
)
|
||||
})
|
||||
|
||||
test('update failures stay generic and unknown installs refuse to guess a profile', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'geek2api-version-fail-'))
|
||||
const ownPackageJsonUrl = await npmInstall(root)
|
||||
const failing = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: root },
|
||||
ownPackageJsonUrl,
|
||||
fetchImpl: registryOk('1.0.4'),
|
||||
runCommand: async () => ({ code: 1, stdout: '', stderr: 'pnpm exploded with secret-ish output' }),
|
||||
})
|
||||
await assert.rejects(
|
||||
() => failing.update(),
|
||||
error => error.message === 'Geek2API plugin update failed' && !error.message.includes('secret-ish'),
|
||||
)
|
||||
|
||||
const emptyHome = await mkdtemp(join(tmpdir(), 'geek2api-version-none-'))
|
||||
const stray = join(emptyHome, 'elsewhere', 'package.json')
|
||||
await writeManifest(stray, { name: PACKAGE_NAME, version: '1.0.3' })
|
||||
const unknown = createGeek2APIPluginManager({
|
||||
env: { DSH_HOME: emptyHome },
|
||||
ownPackageJsonUrl: pathToFileURL(stray),
|
||||
fetchImpl: registryOk('1.0.4'),
|
||||
})
|
||||
const info = await unknown.read()
|
||||
assert.deepEqual(info.install, { kind: 'unknown' })
|
||||
await assert.rejects(() => unknown.update(), /^Error: Geek2API plugin update could not find the owning profile$/u)
|
||||
})
|
||||
|
||||
test('loopback RPC exposes version and update endpoints with sanitized errors', async () => {
|
||||
const projection = {
|
||||
current: '1.0.3',
|
||||
latest: '1.0.4',
|
||||
updateAvailable: true,
|
||||
install: { kind: 'npm', profile: 'web' },
|
||||
fetchedAt: 1000,
|
||||
}
|
||||
const forced = []
|
||||
const handler = rpc({
|
||||
async read({ force } = {}) {
|
||||
forced.push(force)
|
||||
return projection
|
||||
},
|
||||
async update() {
|
||||
return { version: '1.0.4', profile: 'web' }
|
||||
},
|
||||
})
|
||||
assert.deepEqual(await handler('plugin/version', {}), { ok: true, value: projection })
|
||||
await handler('plugin/version', { force: true })
|
||||
assert.deepEqual(forced, [false, true])
|
||||
assert.deepEqual(await handler('plugin/update', {}), {
|
||||
ok: true,
|
||||
value: { version: '1.0.4', profile: 'web' },
|
||||
})
|
||||
|
||||
const failing = rpc({
|
||||
async read() { throw new Error('Geek2API plugin version check failed') },
|
||||
async update() { throw new Error('pnpm leaked internals') },
|
||||
})
|
||||
assert.deepEqual(await failing('plugin/version', {}), {
|
||||
ok: false,
|
||||
error: { code: 'geek2api/request-failed', message: 'Geek2API plugin version check failed', details: {} },
|
||||
})
|
||||
assert.deepEqual(await failing('plugin/update', {}), {
|
||||
ok: false,
|
||||
error: { code: 'geek2api/request-failed', message: 'Geek2API request failed', details: {} },
|
||||
})
|
||||
|
||||
const missing = rpc(undefined)
|
||||
assert.deepEqual(await missing('plugin/version', {}), {
|
||||
ok: false,
|
||||
error: { code: 'geek2api/request-failed', message: 'Geek2API plugin version is unavailable', details: {} },
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,230 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { isQuotaExceededError } from '@deepseek-ai/dsh-llm'
|
||||
|
||||
import { GEEK2API_MODEL_IDS } from '../src/catalog.js'
|
||||
import { DISPLAY_NAME, PROVIDER } from '../src/constants.js'
|
||||
import { createGeek2APIProvider, guardKeyRotation } from '../src/provider.js'
|
||||
|
||||
/** A pi-ai shaped stream: an async iterable plus `.result()`. */
|
||||
function fakeStream(items, { throwAt } = {}) {
|
||||
const stream = {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const [index, item] of items.entries()) {
|
||||
if (throwAt === index) throw new Error(throwAt === 0 && items.length === 0 ? 'transport' : 'boom')
|
||||
yield item
|
||||
}
|
||||
if (throwAt !== undefined && throwAt >= items.length) throw new Error('late boom')
|
||||
},
|
||||
result: async () => ({ ok: true }),
|
||||
}
|
||||
return stream
|
||||
}
|
||||
|
||||
test('builds one route carrying all three protocols', () => {
|
||||
const provider = createGeek2APIProvider()
|
||||
assert.equal(provider.id, PROVIDER)
|
||||
assert.equal(provider.name, DISPLAY_NAME)
|
||||
assert.deepEqual(provider.getModels().map(model => model.id), [...GEEK2API_MODEL_IDS])
|
||||
assert.equal(typeof provider.stream, 'function')
|
||||
assert.equal(typeof provider.streamSimple, 'function')
|
||||
})
|
||||
|
||||
test('a terminal quota event moves the ring and is rewritten for the classifier', async () => {
|
||||
const failures = []
|
||||
const event = {
|
||||
type: 'error',
|
||||
error: { errorMessage: '403 {"error":{"message":"当前令牌额度已用完"}}' },
|
||||
}
|
||||
const guarded = guardKeyRotation(fakeStream([event]), {
|
||||
key: 'sk-aaaaaaaaaaaaaaaa',
|
||||
onKeyFailure: (...args) => failures.push(args),
|
||||
})
|
||||
const received = []
|
||||
for await (const item of guarded) received.push(item)
|
||||
|
||||
assert.equal(failures.length, 1)
|
||||
assert.equal(failures[0][0], 'quota')
|
||||
assert.equal(failures[0][2], 'sk-aaaaaaaaaaaaaaaa')
|
||||
assert.equal(isQuotaExceededError(received[0].error.errorMessage), true)
|
||||
// The wrapper keeps `result()` and every other member reachable.
|
||||
assert.deepEqual(await guarded.result(), { ok: true })
|
||||
})
|
||||
|
||||
test('a rejected key reported as a terminal event normalizes to auth', async () => {
|
||||
const failures = []
|
||||
const guarded = guardKeyRotation(fakeStream([
|
||||
{ type: 'done', message: { errorMessage: '401 {"error":{"message":"无效的令牌"}}' } },
|
||||
]), { key: 'sk-bbbbbbbbbbbbbbbbbb', onKeyFailure: (...args) => failures.push(args) })
|
||||
const received = []
|
||||
for await (const item of guarded) received.push(item)
|
||||
assert.equal(failures[0][0], 'invalid-key')
|
||||
assert.match(received[0].message.errorMessage, /\b401\b/u)
|
||||
})
|
||||
|
||||
test('a pre-chunk transport failure is attributed and rewritten when it is a key fault', async () => {
|
||||
const failures = []
|
||||
const guarded = guardKeyRotation(fakeStream([], { throwAt: 0 }), {
|
||||
key: 'sk-cccccccccccccccccccc',
|
||||
onKeyFailure: (...args) => failures.push(args),
|
||||
})
|
||||
await assert.rejects(async () => {
|
||||
for await (const _item of guarded) void _item
|
||||
}, /boom/u)
|
||||
// A generic failure names no key condition, so nothing rotates.
|
||||
assert.deepEqual(failures, [])
|
||||
})
|
||||
|
||||
test('a mid-stream failure never blames the key', async () => {
|
||||
const failures = []
|
||||
const guarded = guardKeyRotation(fakeStream([{ type: 'text', text: 'hi' }], { throwAt: 1 }), {
|
||||
key: 'sk-dddddddddddddddddddd',
|
||||
onKeyFailure: (...args) => failures.push(args),
|
||||
})
|
||||
await assert.rejects(async () => {
|
||||
for await (const _item of guarded) void _item
|
||||
}, /late boom/u)
|
||||
assert.deepEqual(failures, [])
|
||||
})
|
||||
|
||||
test('an unrelated stream passes through untouched', () => {
|
||||
assert.equal(guardKeyRotation(null), null)
|
||||
assert.equal(guardKeyRotation('nope'), 'nope')
|
||||
})
|
||||
|
||||
test('a client-policy refusal is explained without touching the key ring', async () => {
|
||||
const failures = []
|
||||
const policy = '403 {"error":{"type":"geek2api_api_error","message":"This API endpoint is only accessible via the official Claude CLI (request id: 01M4Q6FJ0)"}}'
|
||||
const guarded = guardKeyRotation(fakeStream([{ type: 'error', error: { errorMessage: policy } }]), {
|
||||
key: 'sk-eeeeeeeeeeeeeeeeeeee',
|
||||
onKeyFailure: (...args) => failures.push(args),
|
||||
})
|
||||
const received = []
|
||||
for await (const item of guarded) received.push(item)
|
||||
assert.deepEqual(failures, [], 'no key may be disabled for a client-policy refusal')
|
||||
assert.match(received[0].error.errorMessage, /这不是 API Key 失效/u)
|
||||
assert.equal(isQuotaExceededError(received[0].error.errorMessage), false)
|
||||
})
|
||||
|
||||
test('a thrown client-policy refusal is explained too', async () => {
|
||||
const failures = []
|
||||
const guarded = guardKeyRotation(fakeStream([], { throwAt: 0 }), {
|
||||
key: 'sk-ffffffffffffffffffff',
|
||||
onKeyFailure: (...args) => failures.push(args),
|
||||
})
|
||||
// Replace the transport failure with the policy error for this case.
|
||||
const policyStream = {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
throw new Error('403 {"error":{"message":"This API endpoint is only accessible via the official Claude CLI"}}')
|
||||
},
|
||||
}
|
||||
const guardedPolicy = guardKeyRotation(policyStream, {
|
||||
key: 'sk-ffffffffffffffffffff',
|
||||
onKeyFailure: (...args) => failures.push(args),
|
||||
})
|
||||
await assert.rejects(async () => {
|
||||
for await (const _item of guardedPolicy) void _item
|
||||
}, /这不是 API Key 失效/u)
|
||||
assert.deepEqual(failures, [])
|
||||
// The original key-fault path is unchanged for a generic failure.
|
||||
await assert.rejects(async () => {
|
||||
for await (const _item of guarded) void _item
|
||||
}, /boom/u)
|
||||
})
|
||||
|
||||
/** A stream that throws `error` at `index` (after yielding the items before it). */
|
||||
function throwingStream(items, index, error) {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const [at, item] of items.entries()) {
|
||||
if (at === index) throw error
|
||||
yield item
|
||||
}
|
||||
if (index >= items.length) throw error
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const transportError = () => Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }) })
|
||||
|
||||
test('a request that never reached the host reports the host, not the key', async () => {
|
||||
const hostFailures = []
|
||||
const keyFailures = []
|
||||
const guarded = guardKeyRotation(throwingStream([], 0, transportError()), {
|
||||
key: 'sk-hostfault000000000',
|
||||
onKeyFailure: (...args) => keyFailures.push(args),
|
||||
onHostFailure: reason => hostFailures.push(reason),
|
||||
})
|
||||
await assert.rejects(async () => {
|
||||
for await (const _item of guarded) void _item
|
||||
}, /fetch failed/u)
|
||||
assert.equal(hostFailures.length, 1)
|
||||
assert.deepEqual(keyFailures, [])
|
||||
})
|
||||
|
||||
test('a terminal transport error event before any answer reports the host', async () => {
|
||||
const hostFailures = []
|
||||
const guarded = guardKeyRotation(fakeStream([{ type: 'error', error: { errorMessage: 'Connection error.' } }]), {
|
||||
onHostFailure: reason => hostFailures.push(reason),
|
||||
})
|
||||
for await (const _item of guarded) void _item
|
||||
assert.deepEqual(hostFailures, ['Connection error.'])
|
||||
})
|
||||
|
||||
test('a host that already answered is never set aside for a later break', async () => {
|
||||
const hostFailures = []
|
||||
const answered = guardKeyRotation(throwingStream([{ type: 'text_delta', delta: 'hi' }], 1, transportError()), {
|
||||
onHostFailure: reason => hostFailures.push(reason),
|
||||
})
|
||||
await assert.rejects(async () => {
|
||||
for await (const _item of answered) void _item
|
||||
}, /fetch failed/u)
|
||||
const afterChunk = guardKeyRotation(fakeStream([
|
||||
{ type: 'text_delta', delta: 'hi' },
|
||||
{ type: 'error', error: { errorMessage: 'Connection error.' } },
|
||||
]), { onHostFailure: reason => hostFailures.push(reason) })
|
||||
for await (const _item of afterChunk) void _item
|
||||
assert.deepEqual(hostFailures, [])
|
||||
})
|
||||
|
||||
test('an HTTP refusal is the gateway answering: the host stays', async () => {
|
||||
const hostFailures = []
|
||||
const guarded = guardKeyRotation(fakeStream([{ type: 'error', error: { errorMessage: '503 Upstream service temporarily unavailable' } }]), {
|
||||
onHostFailure: reason => hostFailures.push(reason),
|
||||
})
|
||||
for await (const _item of guarded) void _item
|
||||
assert.deepEqual(hostFailures, [])
|
||||
})
|
||||
|
||||
test('a model no stored key reaches is explained in place of the raw refusal', async () => {
|
||||
const keyFailures = []
|
||||
const raw = `400 {"error":{"message":"Model 'kimi-k3' is not available. Use GET /v1/models to see supported models."}}`
|
||||
const guarded = guardKeyRotation(fakeStream([{ type: 'error', error: { errorMessage: raw } }]), {
|
||||
key: 'sk-uncovered0000000000',
|
||||
modelId: 'kimi-k3',
|
||||
onKeyFailure: (...args) => keyFailures.push(args),
|
||||
})
|
||||
const received = []
|
||||
for await (const item of guarded) received.push(item)
|
||||
assert.match(received[0].error.errorMessage, /你保存的 Key 都不能使用 kimi-k3/u)
|
||||
assert.deepEqual(keyFailures, [], 'coverage is not a key fault')
|
||||
})
|
||||
|
||||
test('sub2api key faults move the ring: invalid, disabled, deleted group, and empty balance', async () => {
|
||||
const cases = [
|
||||
['401 {"error":{"message":"Invalid API key"}}', 'invalid-key'],
|
||||
['401 {"error":{"message":"API key is disabled"}}', 'invalid-key'],
|
||||
['403 {"error":{"message":"API Key 所属分组已删除"}}', 'invalid-key'],
|
||||
['403 {"error":{"message":"余额不足,请充值"}}', 'quota'],
|
||||
]
|
||||
for (const [message, kind] of cases) {
|
||||
const failures = []
|
||||
const guarded = guardKeyRotation(fakeStream([{ type: 'error', error: { errorMessage: message } }]), {
|
||||
key: 'sk-fault000000000000',
|
||||
onKeyFailure: (...args) => failures.push(args),
|
||||
})
|
||||
for await (const _item of guarded) void _item
|
||||
assert.equal(failures[0]?.[0], kind, message)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
|
||||
async function preflight(exchangeStatus) {
|
||||
const workflow = await readFile(new URL('../.github/workflows/publish.yml', import.meta.url), 'utf8')
|
||||
const step = workflow.split('- name: Show the OIDC identity npm will match')[1]?.split('- name: Publish')[0]
|
||||
const code = /node <<'EOF'\n([\s\S]*?)\n\s*EOF/u.exec(step ?? '')?.[1]
|
||||
assert.ok(code, 'the trusted-publisher preflight must contain its actual Node program')
|
||||
const lines = []
|
||||
const calls = []
|
||||
const token = `fixture-secret-${'x'.repeat(2_000)}`
|
||||
const claims = {
|
||||
repository: 'BaronCyrus/dsh-geek2api',
|
||||
repository_owner: 'BaronCyrus',
|
||||
workflow: 'Publish',
|
||||
workflow_ref: 'BaronCyrus/dsh-geek2api/.github/workflows/publish.yml@refs/heads/main',
|
||||
ref: 'refs/heads/main',
|
||||
aud: 'npm:registry.npmjs.org',
|
||||
iss: 'https://token.actions.githubusercontent.com',
|
||||
}
|
||||
const oidc = `header.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.signature`
|
||||
const promise = runInNewContext(code, {
|
||||
URL,
|
||||
Buffer,
|
||||
console: { log: value => lines.push(String(value)), error: value => lines.push(String(value)) },
|
||||
process: {
|
||||
env: { ACTIONS_ID_TOKEN_REQUEST_URL: 'https://actions.example/oidc?existing=true', ACTIONS_ID_TOKEN_REQUEST_TOKEN: 'fixture-request-capability' },
|
||||
exit: code => { throw new Error(`EXIT_${code}`) },
|
||||
},
|
||||
fetch: async (url, options) => {
|
||||
calls.push({ url: String(url), options })
|
||||
if (calls.length === 1) return { ok: true, json: async () => ({ value: oidc }) }
|
||||
assert.equal(String(url), 'https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/dsh-geek2api')
|
||||
assert.equal(options.method, 'POST')
|
||||
assert.equal(options.headers.Authorization, `Bearer ${oidc}`)
|
||||
return { ok: exchangeStatus >= 200 && exchangeStatus < 300, status: exchangeStatus, arrayBuffer: async () => Buffer.from(JSON.stringify({ token })) }
|
||||
},
|
||||
})
|
||||
return { promise, lines, calls, token }
|
||||
}
|
||||
|
||||
test('publisher preflight prints safe identity claims, never an exchange credential or its truncated prefix', async () => {
|
||||
const run = await preflight(200)
|
||||
await run.promise
|
||||
assert.ok(run.lines.includes('repository=BaronCyrus/dsh-geek2api'))
|
||||
assert.ok(run.lines.includes('environment='))
|
||||
assert.ok(run.lines.includes('exchange_status=200'))
|
||||
assert.equal(new URL(run.calls[0].url).searchParams.get('audience'), 'npm:registry.npmjs.org')
|
||||
assert.equal(run.lines.join('\n').includes(run.token.slice(0, 50)), false)
|
||||
assert.equal(run.lines.join('\n').includes('fixture-request-capability'), false)
|
||||
})
|
||||
|
||||
test('publisher preflight accepts the real registry exchange Created response', async () => {
|
||||
const run = await preflight(201)
|
||||
await run.promise
|
||||
assert.ok(run.lines.includes('exchange_status=201'))
|
||||
assert.equal(run.lines.join('\n').includes(run.token.slice(0, 50)), false)
|
||||
})
|
||||
|
||||
test('tag publication uses the verified versioned tarball, not a separately packed workspace', async () => {
|
||||
const workflow = await readFile(new URL('../.github/workflows/publish.yml', import.meta.url), 'utf8')
|
||||
assert.ok(workflow.includes('run: pnpm pack --pack-destination .artifacts'))
|
||||
assert.ok(workflow.includes('artifact=".artifacts/dsh-geek2api-${version:?}.tgz"'))
|
||||
assert.ok(workflow.includes('npm publish "${artifact:?}" --access public'))
|
||||
assert.ok(workflow.includes('if [ ! -f "$artifact" ]; then'))
|
||||
})
|
||||
|
||||
test('publisher preflight fails closed when npm rejects the configured publisher', async () => {
|
||||
const run = await preflight(403)
|
||||
await assert.rejects(run.promise, /EXIT_1/u)
|
||||
assert.ok(run.lines.includes('exchange_status=403'))
|
||||
assert.equal(run.lines.join('\n').includes(run.token.slice(0, 50)), false)
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile, realpath, stat } from 'node:fs/promises'
|
||||
import { isAbsolute, relative, resolve, sep } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const read = (path, encoding = 'utf8') => readFile(new URL(`../${path}`, import.meta.url), encoding)
|
||||
|
||||
test('plugin card icon is declared, packaged, and within the host byte limit', async () => {
|
||||
const manifest = JSON.parse(await read('package.json'))
|
||||
assert.equal(manifest.icon, './icon-geek2api.webp', 'DSH reads the top-level icon field')
|
||||
assert.equal(manifest.exports['./package.json'], './package.json', 'DSH must resolve the exported manifest')
|
||||
|
||||
const root = await realpath(fileURLToPath(new URL('../', import.meta.url)))
|
||||
const iconPath = await realpath(resolve(root, manifest.icon))
|
||||
const local = relative(root, iconPath)
|
||||
assert.ok(!isAbsolute(local) && local !== '..' && !local.startsWith(`..${sep}`), 'icon must remain inside the package')
|
||||
assert.ok((await stat(iconPath)).isFile(), 'icon must be a regular file')
|
||||
assert.ok(manifest.files.includes(manifest.icon.slice(2)), 'publish files must include the icon')
|
||||
|
||||
const bytes = await readFile(iconPath)
|
||||
assert.ok(bytes.length > 0 && bytes.length <= 256 * 1024, 'DSH admits icon files of at most 256 KiB')
|
||||
assert.equal(bytes.toString('ascii', 0, 4), 'RIFF')
|
||||
assert.equal(bytes.toString('ascii', 8, 12), 'WEBP')
|
||||
assert.equal(bytes.readUInt32LE(4) + 8, bytes.length, 'WebP container must be complete')
|
||||
})
|
||||
|
||||
test('release package includes the README mascot', async () => {
|
||||
const manifest = JSON.parse(await read('package.json'))
|
||||
const mascot = 'docs/assets/dsh-geek2api-mascot.png'
|
||||
assert.ok(manifest.files.includes(mascot), 'publish files must include the README mascot')
|
||||
assert.ok((await read(mascot, null)).length > 0, 'mascot must exist and be nonempty')
|
||||
for (const path of ['README.md', 'README.en.md']) {
|
||||
assert.ok((await read(path)).includes(mascot))
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,182 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai'
|
||||
|
||||
import { GEEK2API_MODEL_IDS } from '../src/catalog.js'
|
||||
import { DEFAULT_REASONING_LEVEL, DISPLAY_NAME, PROVIDER } from '../src/constants.js'
|
||||
import { createGeek2APIProfile } from '../src/index.js'
|
||||
import { createGeek2APIProvider } from '../src/provider.js'
|
||||
|
||||
/**
|
||||
* The route composed exactly as `apply()` composes it, driven through the real
|
||||
* host adapter. Resolution and call preparation must work without reading a
|
||||
* credential or opening a model stream.
|
||||
*/
|
||||
function route({ reads = [] } = {}) {
|
||||
const provider = createGeek2APIProvider()
|
||||
const profile = createGeek2APIProfile(provider)
|
||||
const profiles = new Map([[PROVIDER, profile]])
|
||||
const adapter = new PiAiAdapter({
|
||||
profiles: () => profiles,
|
||||
resolveApiKey: async () => {
|
||||
reads.push('credential')
|
||||
return 'sk-test-not-a-real-key'
|
||||
},
|
||||
auth: Object.freeze({
|
||||
credentials: {
|
||||
async read() { return undefined },
|
||||
async list() { return [] },
|
||||
async modify() { throw new Error('unused') },
|
||||
async delete() { throw new Error('unused') },
|
||||
},
|
||||
authContext: Object.freeze({ env: async () => undefined, fileExists: async () => false }),
|
||||
}),
|
||||
})
|
||||
return { adapter, profile, reads }
|
||||
}
|
||||
|
||||
test('the real adapter advertises the route under its display name', async () => {
|
||||
const { adapter, reads } = route()
|
||||
assert.deepEqual(adapter.providerInfo(PROVIDER), { id: PROVIDER, name: DISPLAY_NAME })
|
||||
const models = await adapter.listModels(PROVIDER)
|
||||
assert.deepEqual(models.map(model => model.id), [...GEEK2API_MODEL_IDS])
|
||||
// Catalog reads never touch a credential.
|
||||
assert.deepEqual(reads, [])
|
||||
})
|
||||
|
||||
test('resolved metadata carries context, modalities, and the vendor efforts', async () => {
|
||||
const { adapter } = route()
|
||||
const claude = await adapter.resolveModel(PROVIDER, 'claude-opus-5-5')
|
||||
assert.equal(claude.context.contextWindow, 1_000_000)
|
||||
assert.deepEqual([...claude.inputModalities], ['text', 'image'])
|
||||
assert.deepEqual(claude.reasoning.efforts.map(effort => effort.id), ['low', 'medium', 'high', 'xhigh', 'max'])
|
||||
assert.equal(claude.reasoning.defaultEffort, DEFAULT_REASONING_LEVEL)
|
||||
assert.equal(claude.defaultMaxTokens, undefined)
|
||||
|
||||
const deepseek = await adapter.resolveModel(PROVIDER, 'deepseek-v4.1-flash')
|
||||
assert.deepEqual(deepseek.reasoning.efforts.map(effort => effort.id), ['off', 'low', 'high', 'max'])
|
||||
assert.deepEqual([...deepseek.inputModalities], ['text', 'image'])
|
||||
|
||||
// A model without a reasoning control still resolves, offering no effort
|
||||
// the upstream would reject.
|
||||
const gemini = await adapter.resolveModel(PROVIDER, 'gemini-3.8-flash')
|
||||
assert.equal(gemini.reasoning?.defaultEffort, undefined)
|
||||
assert.ok(!(gemini.reasoning?.efforts ?? []).some(effort => effort.id === DEFAULT_REASONING_LEVEL))
|
||||
})
|
||||
|
||||
test('preparing a call returns the model and a stream, without opening one', async () => {
|
||||
const { adapter, reads } = route()
|
||||
const prepared = await adapter.prepareCall(PROVIDER, 'gpt-6.1-sol')
|
||||
assert.equal(prepared.model.id, 'gpt-6.1-sol')
|
||||
assert.equal(typeof prepared.stream, 'function')
|
||||
assert.deepEqual(reads, [])
|
||||
})
|
||||
|
||||
test('the profile carries the retry policy that makes rotation reachable', () => {
|
||||
const { profile } = route()
|
||||
assert.equal(profile.reasoning, DEFAULT_REASONING_LEVEL)
|
||||
assert.equal(profile.retryPolicy.mode, 'normal')
|
||||
// One route serves every model, so this budget applies to all of them.
|
||||
assert.equal(profile.retryPolicy.maxRetries, 20)
|
||||
for (const code of ['QUOTA', 'AUTH', 'SERVER', 'TRANSPORT', 'TIMEOUT', 'RATE_LIMIT']) {
|
||||
assert.ok(profile.retryPolicy.retryableCodes.includes(code), `${code} must be retryable`)
|
||||
}
|
||||
// This gateway's 400 means it ("Model 'x' is not available"): no retry helps.
|
||||
assert.equal(profile.retryPolicy.retryableCodes.includes('INVALID_REQUEST'), false)
|
||||
assert.ok(profile.modelErrors instanceof Map)
|
||||
assert.ok(profile.configuredMaxTokens instanceof Map)
|
||||
})
|
||||
|
||||
const sseCompletion = model => new Response([
|
||||
{ id: 'c1', object: 'chat.completion.chunk', created: 1, model, choices: [{ index: 0, delta: { role: 'assistant', content: 'ok' }, finish_reason: null }] },
|
||||
{ id: 'c1', object: 'chat.completion.chunk', created: 1, model, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
|
||||
].map(event => `data: ${JSON.stringify(event)}\n\n`).join('') + 'data: [DONE]\n\n', { headers: { 'Content-Type': 'text/event-stream' } })
|
||||
|
||||
async function routeAdapter(hosts) {
|
||||
const { Geek2APIKeyRing } = await import('../src/key-ring.js')
|
||||
const { createRouteAdapter } = await import('../src/route.js')
|
||||
const { fakeCredentials } = await import('./helpers.mjs')
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
await ring.add('sk-fixture-only-not-a-real-key', 'fixture')
|
||||
const failures = []
|
||||
const adapter = createRouteAdapter({
|
||||
ring,
|
||||
hosts,
|
||||
keys: { active: () => ring.activeKey(), forRequest: (_model, key) => key, onKeyFailure: (...args) => failures.push(args) },
|
||||
fallbackSessionId: 'route-fixture',
|
||||
})
|
||||
return { adapter, failures }
|
||||
}
|
||||
|
||||
async function runTurn(adapter, model, extra = {}) {
|
||||
const { createUserMessage } = await import('@deepseek-ai/dsh-llm')
|
||||
const prepared = await adapter.prepareCall(PROVIDER, model)
|
||||
const chunks = []
|
||||
for await (const chunk of prepared.stream({
|
||||
provider: PROVIDER, model, sessionId: 'route-fixture', maxTokens: 64,
|
||||
messages: [createUserMessage({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } })],
|
||||
...extra,
|
||||
})) chunks.push(chunk)
|
||||
return chunks.at(-1)
|
||||
}
|
||||
|
||||
test('a model without reasoning is asked for `off`, so the route default effort cannot fail it', async t => {
|
||||
const { createHostPool } = await import('../src/hosts.js')
|
||||
const { stubHostPool } = await import('./helpers.mjs')
|
||||
const requests = []
|
||||
t.mock.method(globalThis, 'fetch', async (input, init) => {
|
||||
const request = new Request(input, init)
|
||||
requests.push({ url: request.url, body: await request.json() })
|
||||
return sseCompletion('gemini-3.8-flash')
|
||||
})
|
||||
const { adapter } = await routeAdapter(stubHostPool(createHostPool))
|
||||
// No effort named: the profile default ('high') would be refused for this model.
|
||||
assert.equal((await runTurn(adapter, 'gemini-3.8-flash')).reason.kind, 'stop')
|
||||
// Even an explicit effort from a stale session is turned into `off`.
|
||||
assert.equal((await runTurn(adapter, 'glm-5.3', { reasoningEffort: 'high' })).reason.kind, 'stop')
|
||||
assert.equal(requests.length, 2)
|
||||
for (const { body } of requests) {
|
||||
assert.equal(body.reasoning_effort, undefined)
|
||||
assert.equal(body.thinking, undefined)
|
||||
}
|
||||
assert.equal(requests[0].url, 'https://h1.example/v1/chat/completions')
|
||||
})
|
||||
|
||||
test('a request that never reached its host sets the host aside; the retry lands on the next one', async t => {
|
||||
const { createHostPool } = await import('../src/hosts.js')
|
||||
const { stubHostPool } = await import('./helpers.mjs')
|
||||
const urls = []
|
||||
t.mock.method(globalThis, 'fetch', async (input, init) => {
|
||||
const request = new Request(input, init)
|
||||
urls.push(request.url)
|
||||
if (request.url.startsWith('https://h1.example/')) {
|
||||
throw Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }) })
|
||||
}
|
||||
return sseCompletion('deepseek-v4.1-flash')
|
||||
})
|
||||
const hosts = stubHostPool(createHostPool)
|
||||
const { adapter, failures } = await routeAdapter(hosts)
|
||||
const first = await runTurn(adapter, 'deepseek-v4.1-flash', { reasoningEffort: 'off' })
|
||||
assert.equal(first.reason.kind, 'error')
|
||||
assert.deepEqual(failures, [], 'a transport failure never blames the key')
|
||||
assert.equal(hosts.order()[0], 'https://h2.example')
|
||||
const second = await runTurn(adapter, 'deepseek-v4.1-flash', { reasoningEffort: 'off' })
|
||||
assert.equal(second.reason.kind, 'stop')
|
||||
assert.ok(urls[0].startsWith('https://h1.example/'))
|
||||
assert.equal(urls.at(-1), 'https://h2.example/v1/chat/completions')
|
||||
})
|
||||
|
||||
test('a model no stored key can use is explained, without blaming or retrying the key', async t => {
|
||||
const { createHostPool } = await import('../src/hosts.js')
|
||||
const { stubHostPool } = await import('./helpers.mjs')
|
||||
t.mock.method(globalThis, 'fetch', async () => Response.json(
|
||||
{ error: { message: "Model 'kimi-k3' is not available. Use GET /v1/models to see supported models.", type: 'invalid_request_error' } },
|
||||
{ status: 400 },
|
||||
))
|
||||
const { adapter, failures } = await routeAdapter(stubHostPool(createHostPool))
|
||||
const finish = await runTurn(adapter, 'kimi-k3')
|
||||
assert.equal(finish.reason.kind, 'error')
|
||||
assert.match(finish.reason.failure.message, /你保存的 Key 都不能使用 kimi-k3/u)
|
||||
assert.deepEqual(failures, [])
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { Geek2APIKeyRing } from '../src/key-ring.js'
|
||||
import { createGeek2APIRpc } from '../src/rpc.js'
|
||||
import { createSearchController } from '../src/search-controller.js'
|
||||
import { createHostPool } from '../src/hosts.js'
|
||||
import { fakeCredentials, stubHostPool } from './helpers.mjs'
|
||||
import { Config } from '../src/index.js'
|
||||
|
||||
test('search settings declare volatile fields accepted by DSH 0.2', () => {
|
||||
for (const field of ['searchProvider', 'searchBackend', 'hiddenModels', 'apiHosts', 'claudeRuntime']) {
|
||||
assert.equal(Config.dict[field].meta.volatile, true, `${field}: DSH 0.2 otherwise rejects settings.update with no volatile fields`)
|
||||
}
|
||||
})
|
||||
|
||||
/** DSH 0.2 Connection's failure contract, after a JSON wire round trip. */
|
||||
function connectionFailure(result) {
|
||||
const wire = JSON.parse(JSON.stringify(result))
|
||||
assert.equal(wire.ok, false)
|
||||
assert.equal(typeof wire.error.code, 'string', 'DSH requires error.code; otherwise invalid server-response failure')
|
||||
assert.equal(typeof wire.error.message, 'string')
|
||||
assert.deepEqual(wire.error.details, {}, 'DSH requires error.details; diagnostics must carry no secrets')
|
||||
return wire.error
|
||||
}
|
||||
|
||||
test('a failed Auto search setting is a valid Connection failure, preserving its safe explanation', async () => {
|
||||
const search = createSearchController({
|
||||
ring: new Geek2APIKeyRing(fakeCredentials()),
|
||||
hosts: stubHostPool(createHostPool),
|
||||
readPreference: () => ({}),
|
||||
isWritable: () => true,
|
||||
writePreference: async () => { throw new Error('storage fixture refused the write') },
|
||||
})
|
||||
const rpc = createGeek2APIRpc({ search })
|
||||
const error = connectionFailure(await rpc('search/update', { searchProvider: 'auto' }))
|
||||
assert.equal(error.message, 'Geek2API could not save the web search preference')
|
||||
})
|
||||
|
||||
test('unknown endpoints and unavailable services also satisfy the Connection failure contract', async () => {
|
||||
const rpc = createGeek2APIRpc({})
|
||||
for (const endpoint of ['unknown', 'search/status', 'models/status', 'plugin/version', 'status']) {
|
||||
connectionFailure(await rpc(endpoint))
|
||||
}
|
||||
})
|
||||
|
||||
test('an unexpected storage failure never places upstream diagnostics in the envelope', async () => {
|
||||
const secret = 'sk-fixture-secret-not-a-real-key'
|
||||
const rpc = createGeek2APIRpc({ ring: { list: async () => { throw new Error(secret) } } })
|
||||
const result = await rpc('status')
|
||||
assert.equal(connectionFailure(result).message, 'Geek2API request failed')
|
||||
assert.equal(JSON.stringify(result).includes(secret), false)
|
||||
})
|
||||
@@ -0,0 +1,147 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { createServer, request as httpRequest } from 'node:http'
|
||||
import test from 'node:test'
|
||||
|
||||
import { Context as LegacyContext } from '@deepseek-ai/cordis'
|
||||
import { HostConnectionService as LegacyConnection, serverResponseSchema as legacyResponse } from '@deepseek-ai/dsh-client-connection'
|
||||
import { Context as CurrentContext, HostConnectionService as CurrentConnection, serverResponseSchema as currentResponse } from 'geek2api-host-v020-fixture'
|
||||
|
||||
import * as geek2api from '../src/index.js'
|
||||
import { fakeCredentials } from './helpers.mjs'
|
||||
|
||||
const hosts = [
|
||||
{ name: 'DSH 0.1.5', Context: LegacyContext, Connection: LegacyConnection, responseSchema: legacyResponse },
|
||||
{ name: 'DSH 0.2.0-rc.2', Context: CurrentContext, Connection: CurrentConnection, responseSchema: currentResponse },
|
||||
]
|
||||
const COOKIE = 'fixture-session=authenticated'
|
||||
|
||||
/**
|
||||
* Connection is the shipped service, with its real injection checks,
|
||||
* Host/Origin admission, HTTP bridge and RPC envelope parser. Only the
|
||||
* webserver's prefix dispatch and browser-session identity are fixtures.
|
||||
* Services live in sibling fibers, as they do in Loader: providing webServer
|
||||
* on the root would accidentally authorize reads without an inject.
|
||||
*/
|
||||
async function runningHost(t, { Context, Connection }, { withWebServer = true } = {}) {
|
||||
const ctx = new Context()
|
||||
const routes = new Map()
|
||||
let connectionStarts = 0
|
||||
await ctx.plugin({ name: 'existing-model-and-credential-services', apply(owner) {
|
||||
owner.provide('credentials', fakeCredentials())
|
||||
owner.provide('llm', { registerAdapter: () => () => {}, registerConfigurableProviders: () => () => {} })
|
||||
} })
|
||||
const webPlugin = { name: 'existing-web-server', apply(owner) {
|
||||
owner.provide('webServer', {
|
||||
register(route) {
|
||||
assert.equal(routes.has(route.path), false, `duplicate route ${route.path}`)
|
||||
routes.set(route.path, route)
|
||||
return () => { routes.delete(route.path) }
|
||||
},
|
||||
})
|
||||
} }
|
||||
let webFiber = withWebServer ? await ctx.plugin(webPlugin) : undefined
|
||||
const connectionFiber = await ctx.plugin({ name: 'existing-connection', inject: ['credentials'], apply(owner) {
|
||||
connectionStarts += 1
|
||||
new Connection(owner, [], { isAuthenticated: request => request.headers.cookie === COOKIE })
|
||||
} })
|
||||
const server = createServer((req, res) => {
|
||||
const route = [...routes.values()].find(route => req.url.startsWith(`${route.path}/`))
|
||||
if (route === undefined) { res.writeHead(req.method === 'POST' ? 405 : 404); res.end(); return }
|
||||
Promise.resolve(route.handler(req, res)).catch(() => { res.writeHead(500); res.end() })
|
||||
})
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
|
||||
t.after(async () => {
|
||||
await ctx.fiber.dispose()
|
||||
await new Promise(resolve => { server.close(resolve); server.closeAllConnections() })
|
||||
})
|
||||
const base = `http://127.0.0.1:${server.address().port}`
|
||||
const settled = async () => Promise.allSettled([...ctx.registry.values()]
|
||||
.flatMap(runtime => [...runtime.fibers].map(fiber => fiber.await())))
|
||||
// node:http permits the hostile Host header needed to exercise rebinding
|
||||
// rejection; Fetch can replace that forbidden header with the URL's host.
|
||||
const request = (method = 'status', { payload = null, headers = {}, cookie = true, body } = {}) => new Promise((resolve, reject) => {
|
||||
const outgoing = httpRequest(`${base}/geek2api/${method}`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...(cookie ? { cookie: COOKIE } : {}), ...headers },
|
||||
}, incoming => {
|
||||
const chunks = []
|
||||
incoming.on('data', chunk => chunks.push(chunk))
|
||||
incoming.on('error', reject)
|
||||
incoming.on('end', () => resolve(new Response(Buffer.concat(chunks), { status: incoming.statusCode })))
|
||||
})
|
||||
outgoing.on('error', reject)
|
||||
outgoing.setTimeout(5000, () => outgoing.destroy(new Error('fixture request timed out')))
|
||||
outgoing.end(JSON.stringify(body ?? { type: 'client-request', rpcId: 'fixture-request', method, payload }))
|
||||
})
|
||||
return {
|
||||
ctx, routes, base, request, settled,
|
||||
async install() { const fiber = await ctx.plugin(geek2api); await settled(); return fiber },
|
||||
async removeWebServer() { await webFiber.dispose(); await settled() },
|
||||
async addWebServer() { webFiber = await ctx.plugin(webPlugin); await settled() },
|
||||
assertUnrestarted() {
|
||||
assert.equal(connectionStarts, 1)
|
||||
assert.equal(connectionFiber.state, 2)
|
||||
assert.equal(server.listening, true)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
for (const host of hosts) {
|
||||
test(`${host.name}: first hot install serves every settings channel without restarting`, async t => {
|
||||
const env = await runningHost(t, host)
|
||||
assert.equal((await env.request()).status, 405, 'there is no plugin before first install')
|
||||
const fiber = await env.install()
|
||||
assert.equal(fiber.state, 2, 'the plugin itself loaded')
|
||||
for (const method of ['status', 'search/status', 'models/status']) {
|
||||
const response = await env.request(method)
|
||||
assert.equal(response.status, 200, `${method} must be available immediately after install`)
|
||||
const parsed = host.responseSchema.parse(await response.json())
|
||||
assert.equal(parsed.rpcId, 'fixture-request')
|
||||
assert.equal(parsed.result.ok, true, method)
|
||||
}
|
||||
// Check the other cards without spawning the CLI or querying npm. Native
|
||||
// envelope rejection proves these paths reached Connection, not a 405.
|
||||
for (const method of ['claude-cli/status', 'plugin/version']) {
|
||||
const response = await env.request(method, { body: {} })
|
||||
assert.equal(response.status, 200, method)
|
||||
assert.equal(host.responseSchema.parse(await response.json()).result.error.code, 'gateway/bad-request')
|
||||
}
|
||||
env.assertUnrestarted()
|
||||
await fiber.dispose()
|
||||
assert.equal((await env.request()).status, 405, 'uninstall removes this plugin route')
|
||||
assert.equal(env.routes.size, 0)
|
||||
env.assertUnrestarted()
|
||||
const reinstalled = await env.install()
|
||||
assert.equal((await env.request()).status, 200, 'reinstall must not collide with a leaked route')
|
||||
env.assertUnrestarted()
|
||||
await reinstalled.dispose()
|
||||
})
|
||||
|
||||
test(`${host.name}: hot-installed RPC preserves browser auth and Host/Origin fences`, async t => {
|
||||
const env = await runningHost(t, host)
|
||||
await env.install()
|
||||
assert.equal((await env.request('status', { cookie: false })).status, 401)
|
||||
for (const headers of [
|
||||
{ host: 'evil.invalid' },
|
||||
{ origin: 'http://evil.invalid' },
|
||||
{ 'sec-fetch-site': 'cross-site' },
|
||||
]) assert.equal((await env.request('status', { headers })).status, 403, JSON.stringify(headers))
|
||||
assert.equal((await env.request('status', { headers: { origin: env.base } })).status, 200)
|
||||
env.assertUnrestarted()
|
||||
})
|
||||
|
||||
test(`${host.name}: RPC follows optional webServer availability and cleans up its own scope`, async t => {
|
||||
const env = await runningHost(t, host, { withWebServer: false })
|
||||
const plugin = await env.install()
|
||||
assert.equal(plugin.state, 2)
|
||||
assert.equal(env.routes.size, 0)
|
||||
await env.addWebServer()
|
||||
assert.equal((await env.request()).status, 200)
|
||||
await env.removeWebServer()
|
||||
assert.equal(env.routes.size, 0, 'losing the injected webServer must remove its RPC route')
|
||||
assert.equal(plugin.state, 2, 'the model route remains loaded')
|
||||
await env.addWebServer()
|
||||
assert.equal((await env.request()).status, 200)
|
||||
env.assertUnrestarted()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
|
||||
import { BLOCK_BEGIN, BLOCK_END, createSearchComposition } from '../src/search-composition.js'
|
||||
|
||||
const BASE = { searchProvider: 'deepseek-official', fetchProvider: 'http' }
|
||||
|
||||
async function scratch(content) {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'geek2api-search-'))
|
||||
const path = join(dir, 'cordis.patch.yml')
|
||||
if (content !== undefined) await writeFile(path, content)
|
||||
return { dir, path }
|
||||
}
|
||||
|
||||
function compose(path, base = () => BASE, extra = {}) {
|
||||
return createSearchComposition({ resolvePatchPath: async () => path, readBaseConfig: base, ...extra })
|
||||
}
|
||||
|
||||
const USER_PATCH = [
|
||||
'# Your patch layer for this dsh profile.',
|
||||
'- id: kimi-subscription',
|
||||
' name: dsh-kimi-subscription',
|
||||
' config:',
|
||||
' searchProvider: auto',
|
||||
'- id: permission',
|
||||
' config:',
|
||||
' defaultPreset: danger-full-access',
|
||||
'',
|
||||
].join('\n')
|
||||
|
||||
test('apply appends one marked web entry and leaves every other line alone', async t => {
|
||||
const { dir, path } = await scratch(USER_PATCH)
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
const composition = compose(path)
|
||||
|
||||
const first = await composition.apply('geek2api-auto')
|
||||
assert.deepEqual(first, { changed: true, fallback: 'deepseek-official' })
|
||||
const written = await readFile(path, 'utf8')
|
||||
assert.ok(written.startsWith(USER_PATCH), 'the user patch is kept byte for byte')
|
||||
assert.equal(written.slice(USER_PATCH.length), [
|
||||
BLOCK_BEGIN,
|
||||
'# fallback: deepseek-official',
|
||||
'- id: web',
|
||||
' config:',
|
||||
// A profile patch replaces the whole matched config, so the other web
|
||||
// fields are restated.
|
||||
' fetchProvider: http',
|
||||
' searchProvider: geek2api-auto',
|
||||
BLOCK_END,
|
||||
'',
|
||||
].join('\n'))
|
||||
|
||||
// Applying the same selection again does not touch the file.
|
||||
assert.deepEqual(await composition.apply('geek2api-auto'), { changed: false, fallback: 'deepseek-official' })
|
||||
assert.deepEqual(await composition.read(), { present: true, provider: 'geek2api-auto', fallback: 'deepseek-official' })
|
||||
})
|
||||
|
||||
test('a later selection rewrites the entry in place and keeps the recorded fallback', async t => {
|
||||
const { dir, path } = await scratch(USER_PATCH)
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
let base = { ...BASE, searchProvider: 'kimi-subscription' }
|
||||
const composition = compose(path, () => base)
|
||||
await composition.apply('geek2api-auto')
|
||||
|
||||
// A sibling plugin appends its own entry after ours; after the reload the
|
||||
// web base names this plugin's provider.
|
||||
const sibling = '# >>> other plugin\n- id: web\n config:\n searchProvider: other\n# <<< other plugin\n'
|
||||
await writeFile(path, `${await readFile(path, 'utf8')}${sibling}`)
|
||||
base = { ...BASE, searchProvider: 'geek2api-auto' }
|
||||
|
||||
const outcome = await composition.apply('geek2api')
|
||||
assert.deepEqual(outcome, { changed: true, fallback: 'kimi-subscription' })
|
||||
const written = await readFile(path, 'utf8')
|
||||
assert.ok(written.endsWith(sibling), 'our entry did not move behind the sibling')
|
||||
assert.match(written, /# fallback: kimi-subscription\n- id: web\n {2}config:\n {4}fetchProvider: http\n {4}searchProvider: geek2api\n/u)
|
||||
})
|
||||
|
||||
test('without an entry, a base that already names this plugin falls back to DSH search', async t => {
|
||||
const { dir, path } = await scratch('[]\n')
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
const composition = compose(path, () => ({ searchProvider: 'geek2api-auto', fetchProvider: 'http' }))
|
||||
const outcome = await composition.apply('geek2api')
|
||||
assert.equal(outcome.fallback, 'deepseek-official')
|
||||
const written = await readFile(path, 'utf8')
|
||||
// The empty-list placeholder gives way to the entry.
|
||||
assert.doesNotMatch(written, /^\[\]$/mu)
|
||||
assert.ok(written.startsWith(BLOCK_BEGIN))
|
||||
})
|
||||
|
||||
test('remove restores the file, down to an empty list when nothing else remains', async t => {
|
||||
const { dir, path } = await scratch(USER_PATCH)
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
const composition = compose(path)
|
||||
await composition.apply('geek2api-auto')
|
||||
assert.deepEqual(await composition.remove(), { changed: true })
|
||||
assert.equal(await readFile(path, 'utf8'), USER_PATCH)
|
||||
assert.deepEqual(await composition.remove(), { changed: false })
|
||||
assert.deepEqual(await composition.read(), { present: false })
|
||||
|
||||
const lone = await scratch('[]\n')
|
||||
t.after(() => rm(lone.dir, { recursive: true, force: true }))
|
||||
const only = compose(lone.path)
|
||||
await only.apply('geek2api')
|
||||
await only.remove()
|
||||
assert.equal(await readFile(lone.path, 'utf8'), '[]\n')
|
||||
})
|
||||
|
||||
test('an entry another writer moved inside the markers survives removal', async t => {
|
||||
// A YAML round trip keeps the end marker as a trailing comment, so a row
|
||||
// appended later can land between our item and the marker.
|
||||
const content = [
|
||||
'- id: permission',
|
||||
' config:',
|
||||
' defaultPreset: danger-full-access',
|
||||
BLOCK_BEGIN,
|
||||
'# fallback: deepseek-official',
|
||||
'- id: web',
|
||||
' config:',
|
||||
' fetchProvider: http',
|
||||
' searchProvider: geek2api-auto',
|
||||
'- id: codex-subscription',
|
||||
' name: dsh-codex-subscription',
|
||||
' config:',
|
||||
' searchProvider: auto',
|
||||
BLOCK_END,
|
||||
'',
|
||||
].join('\n')
|
||||
const { dir, path } = await scratch(content)
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
await compose(path).remove()
|
||||
assert.equal(await readFile(path, 'utf8'), [
|
||||
'- id: permission',
|
||||
' config:',
|
||||
' defaultPreset: danger-full-access',
|
||||
'- id: codex-subscription',
|
||||
' name: dsh-codex-subscription',
|
||||
' config:',
|
||||
' searchProvider: auto',
|
||||
'',
|
||||
].join('\n'))
|
||||
})
|
||||
|
||||
test('after a YAML rewrite drifts the end marker, one apply restores it and the next changes nothing', async t => {
|
||||
// What DSH's config editor (yaml parseDocument → String) produced when it
|
||||
// appended a row after ours: the marker became a trailing comment.
|
||||
const drifted = [
|
||||
'- id: kimi-subscription',
|
||||
' config:',
|
||||
' searchProvider: default',
|
||||
BLOCK_BEGIN,
|
||||
'# fallback: deepseek-official',
|
||||
'- id: web',
|
||||
' config:',
|
||||
' fetchProvider: http',
|
||||
' searchProvider: geek2api-auto',
|
||||
'- id: geek2api',
|
||||
' name: dsh-geek2api',
|
||||
' config:',
|
||||
' searchProvider: auto',
|
||||
'',
|
||||
BLOCK_END,
|
||||
'',
|
||||
].join('\n')
|
||||
const { dir, path } = await scratch(drifted)
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
const composition = compose(path)
|
||||
assert.equal((await composition.apply('geek2api-auto')).changed, true)
|
||||
assert.equal(await readFile(path, 'utf8'), [
|
||||
'- id: kimi-subscription',
|
||||
' config:',
|
||||
' searchProvider: default',
|
||||
BLOCK_BEGIN,
|
||||
'# fallback: deepseek-official',
|
||||
'- id: web',
|
||||
' config:',
|
||||
' fetchProvider: http',
|
||||
' searchProvider: geek2api-auto',
|
||||
BLOCK_END,
|
||||
'- id: geek2api',
|
||||
' name: dsh-geek2api',
|
||||
' config:',
|
||||
' searchProvider: auto',
|
||||
'',
|
||||
].join('\n'))
|
||||
assert.equal((await composition.apply('geek2api-auto')).changed, false)
|
||||
})
|
||||
|
||||
test('a missing file is created, CRLF files keep CRLF, and a flow list is refused', async t => {
|
||||
const missing = await scratch()
|
||||
t.after(() => rm(missing.dir, { recursive: true, force: true }))
|
||||
await compose(missing.path).apply('geek2api-auto')
|
||||
assert.ok((await readFile(missing.path, 'utf8')).startsWith(BLOCK_BEGIN))
|
||||
|
||||
const crlf = await scratch('- id: permission\r\n config:\r\n defaultPreset: read-only\r\n')
|
||||
t.after(() => rm(crlf.dir, { recursive: true, force: true }))
|
||||
await compose(crlf.path).apply('geek2api')
|
||||
const text = await readFile(crlf.path, 'utf8')
|
||||
assert.equal(text.split('\r\n').length - 1, text.split('\n').length - 1, 'every line ends in CRLF')
|
||||
|
||||
const flow = await scratch('[{ id: permission, config: { defaultPreset: read-only } }]\n')
|
||||
t.after(() => rm(flow.dir, { recursive: true, force: true }))
|
||||
await assert.rejects(compose(flow.path).apply('geek2api'), /not a plain YAML list/u)
|
||||
assert.equal(await readFile(flow.path, 'utf8'), '[{ id: permission, config: { defaultPreset: read-only } }]\n')
|
||||
})
|
||||
|
||||
test('only this plugin\'s providers can be applied, and writes run inside the exclusive section', async t => {
|
||||
const { dir, path } = await scratch('[]\n')
|
||||
t.after(() => rm(dir, { recursive: true, force: true }))
|
||||
let exclusive = 0
|
||||
const composition = compose(path, () => BASE, {
|
||||
runExclusive: async run => {
|
||||
exclusive += 1
|
||||
return run()
|
||||
},
|
||||
})
|
||||
await assert.rejects(composition.apply('deepseek-official'), /cannot select/u)
|
||||
await composition.apply('geek2api')
|
||||
// Confirming an entry that already matches, or removing one that is not
|
||||
// there, never takes the lock: every web restart does one of the two.
|
||||
await composition.apply('geek2api')
|
||||
await composition.remove()
|
||||
await composition.remove()
|
||||
assert.equal(exclusive, 2)
|
||||
|
||||
const unlocated = createSearchComposition({ resolvePatchPath: async () => undefined, readBaseConfig: () => BASE })
|
||||
await assert.rejects(unlocated.apply('geek2api'), /could not find the profile patch file/u)
|
||||
})
|
||||
@@ -0,0 +1,272 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
|
||||
import { DEFAULT_API_HOST } from '../src/constants.js'
|
||||
import { apply, Config } from '../src/index.js'
|
||||
import { fakeCredentials } from './helpers.mjs'
|
||||
import { fieldValue } from '../src/preferences.js'
|
||||
|
||||
const USER_PATCH = '- id: permission\n config:\n defaultPreset: danger-full-access\n'
|
||||
|
||||
/**
|
||||
* A context shaped like the DSH host at the seams the search wiring touches:
|
||||
* the web service registry, the Loader's web entry, the running profile's
|
||||
* patch path, the initiating agent, and one of the two settings generations.
|
||||
*/
|
||||
async function makeContext({ settings: generation = '0.2' } = {}) {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'geek2api-wiring-'))
|
||||
const patchPath = join(dir, 'cordis.patch.yml')
|
||||
await writeFile(patchPath, USER_PATCH)
|
||||
|
||||
const values = { searchProvider: 'default', searchBackend: 'claude' }
|
||||
const seen = { updates: [], configured: [], listeners: new Map(), handler: undefined, section: undefined }
|
||||
const providers = new Map()
|
||||
const dshSearch = { id: 'deepseek-official', available: () => true, search: async () => ({ sources: [{ url: 'https://dsh.example/' }], truncated: false }) }
|
||||
providers.set(dshSearch.id, dshSearch)
|
||||
const web = {
|
||||
searchProviders: providers,
|
||||
registerSearchProvider(provider) {
|
||||
if (providers.has(provider.id)) throw new Error(`duplicate ${provider.id}`)
|
||||
providers.set(provider.id, provider)
|
||||
return () => providers.delete(provider.id)
|
||||
},
|
||||
}
|
||||
const webEntry = {
|
||||
options: { id: 'web', config: { searchProvider: 'deepseek-official', fetchProvider: 'http' } },
|
||||
fiber: { config: { searchProvider: 'codex-subscription-auto', fetchProvider: 'http' } },
|
||||
}
|
||||
let modelProvider = 'geek2api'
|
||||
const session = { id: 'session-1', requestContext: () => ({ provider: modelProvider }) }
|
||||
const services = {
|
||||
profileContext: { patchPath },
|
||||
loader: { entries: () => [webEntry] },
|
||||
agents: { currentInitiator: () => ({ session }) },
|
||||
}
|
||||
|
||||
let settings
|
||||
if (generation === '0.2') {
|
||||
settings = {
|
||||
writable: true,
|
||||
async update(id, patch) {
|
||||
seen.updates.push({ id, patch })
|
||||
Object.assign(values, patch)
|
||||
},
|
||||
configure(presentation, owner) {
|
||||
seen.configured.push({ presentation, owner })
|
||||
return () => {}
|
||||
},
|
||||
}
|
||||
} else {
|
||||
let section
|
||||
settings = {
|
||||
installSection(_owner, ns, _schema, entry, hooks) {
|
||||
section = { ...entry }
|
||||
seen.section = { ns, hooks }
|
||||
hooks.setSource(() => section)
|
||||
},
|
||||
async update(ns, patch) {
|
||||
seen.updates.push({ id: ns, patch })
|
||||
section = { ...section, ...patch }
|
||||
seen.section.hooks.onChange()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const fiber = { entry: { options: { id: 'geek2api' } } }
|
||||
const ctx = {
|
||||
credentials: fakeCredentials(),
|
||||
attachments: undefined,
|
||||
logger: { warn: () => {} },
|
||||
fiber,
|
||||
llm: { registerAdapter: () => () => {}, registerConfigurableProviders: () => () => {} },
|
||||
get: name => services[name],
|
||||
on(event, callback) {
|
||||
seen.listeners.set(event, callback)
|
||||
return () => {}
|
||||
},
|
||||
inject(names, callback) {
|
||||
if (names.includes('settings')) return callback({ settings, effect: ctx.effect })
|
||||
if (names.includes('web')) return callback({ web, effect: ctx.effect })
|
||||
if (names.includes('tools')) return callback({ tools: { register: () => () => {} } })
|
||||
if (names.includes('connection')) {
|
||||
return callback({ effect: ctx.effect, connection: { rpc: { handle: (_channel, handler) => { seen.handler = handler; return () => {} } } } })
|
||||
}
|
||||
return callback(ctx)
|
||||
},
|
||||
effect(callback) {
|
||||
const disposer = callback()
|
||||
return typeof disposer === 'function' ? disposer : () => {}
|
||||
},
|
||||
}
|
||||
// DSH 0.2 hands volatile fields over as live references.
|
||||
const config = generation === '0.2'
|
||||
? { searchProvider: { get: () => values.searchProvider }, searchBackend: { get: () => values.searchBackend } }
|
||||
: {}
|
||||
return {
|
||||
ctx,
|
||||
config,
|
||||
seen,
|
||||
providers,
|
||||
values,
|
||||
patchPath,
|
||||
setModelProvider: value => { modelProvider = value },
|
||||
cleanup: () => rm(dir, { recursive: true, force: true }),
|
||||
}
|
||||
}
|
||||
|
||||
/** Let the reconcile chain started by a registration settle. */
|
||||
const settle = () => new Promise(resolve => { setTimeout(resolve, 20) })
|
||||
|
||||
test('the search preference fields are part of the plugin Config', () => {
|
||||
const resolved = new Config({})
|
||||
assert.equal(fieldValue(resolved.searchProvider), 'default')
|
||||
assert.equal(fieldValue(resolved.searchBackend), 'claude')
|
||||
assert.throws(() => new Config({ searchProvider: 'everything' }))
|
||||
})
|
||||
|
||||
test('DSH 0.2: both providers register, and the panel switches routing through the profile patch', async t => {
|
||||
const env = await makeContext({ settings: '0.2' })
|
||||
t.after(env.cleanup)
|
||||
apply(env.ctx, env.config)
|
||||
await settle()
|
||||
|
||||
assert.ok(env.providers.has('geek2api'))
|
||||
assert.ok(env.providers.has('geek2api-auto'))
|
||||
// The Geek2API panel is the editor; the generated page is hidden for this fiber.
|
||||
assert.deepEqual(env.seen.configured, [{ presentation: { auto: false }, owner: env.ctx.fiber }])
|
||||
assert.equal(typeof env.seen.listeners.get('loader/volatile-update'), 'function')
|
||||
|
||||
const initial = await env.seen.handler('search/status', {})
|
||||
assert.equal(initial.ok, true)
|
||||
assert.equal(initial.value.searchProvider, 'default')
|
||||
assert.equal(initial.value.searchBackend, 'claude')
|
||||
assert.equal(initial.value.writable, true)
|
||||
assert.equal(initial.value.available, true)
|
||||
assert.deepEqual(initial.value.effective, { base: 'deepseek-official', runtime: 'codex-subscription-auto' })
|
||||
assert.deepEqual(initial.value.models, { claude: 'claude-haiku-4-5-20251001', gpt: 'gpt-6.1-sol' })
|
||||
assert.equal(await readFile(env.patchPath, 'utf8'), USER_PATCH, 'the default selection writes nothing')
|
||||
|
||||
const auto = await env.seen.handler('search/update', { searchProvider: 'auto' })
|
||||
assert.equal(auto.ok, true)
|
||||
// DSH 0.2 writes a volatile field of the plugin's own row.
|
||||
assert.deepEqual(env.seen.updates, [{ id: 'geek2api', patch: { searchProvider: 'auto' } }])
|
||||
assert.equal(auto.value.searchProvider, 'auto')
|
||||
assert.deepEqual(auto.value.applied, { state: 'applied', fallback: 'deepseek-official' })
|
||||
const patched = await readFile(env.patchPath, 'utf8')
|
||||
assert.ok(patched.startsWith(USER_PATCH))
|
||||
assert.match(patched, /- id: web\n {2}config:\n {4}fetchProvider: http\n {4}searchProvider: geek2api-auto\n/u)
|
||||
|
||||
const backend = await env.seen.handler('search/update', { searchBackend: 'gpt' })
|
||||
assert.equal(backend.value.searchBackend, 'gpt')
|
||||
const refused = await env.seen.handler('search/update', { searchBackend: 'bing' })
|
||||
assert.equal(refused.ok, false)
|
||||
assert.match(refused.error.message, /not supported/u)
|
||||
|
||||
const back = await env.seen.handler('search/update', { searchProvider: 'default' })
|
||||
assert.deepEqual(back.value.applied, { state: 'removed' })
|
||||
assert.equal(await readFile(env.patchPath, 'utf8'), USER_PATCH)
|
||||
})
|
||||
|
||||
test('DSH 0.2: a volatile change made elsewhere is followed without a restart', async t => {
|
||||
const env = await makeContext({ settings: '0.2' })
|
||||
t.after(env.cleanup)
|
||||
apply(env.ctx, env.config)
|
||||
await settle()
|
||||
env.values.searchProvider = 'geek2api'
|
||||
env.seen.listeners.get('loader/volatile-update')([['searchProvider']])
|
||||
await settle()
|
||||
assert.match(await readFile(env.patchPath, 'utf8'), /searchProvider: geek2api\n/u)
|
||||
})
|
||||
|
||||
test('DSH 0.1.5: the preference lives in the installed section and its change hook reconciles', async t => {
|
||||
const env = await makeContext({ settings: '0.1' })
|
||||
t.after(env.cleanup)
|
||||
apply(env.ctx, {})
|
||||
await settle()
|
||||
assert.equal(env.seen.section.ns, 'geek2api')
|
||||
const updated = await env.seen.handler('search/update', { searchProvider: 'geek2api', searchBackend: 'gpt' })
|
||||
assert.equal(updated.ok, true)
|
||||
assert.deepEqual(env.seen.updates, [{ id: 'geek2api', patch: { searchProvider: 'geek2api', searchBackend: 'gpt' } }])
|
||||
assert.equal(updated.value.searchProvider, 'geek2api')
|
||||
assert.equal(updated.value.searchBackend, 'gpt')
|
||||
assert.match(await readFile(env.patchPath, 'utf8'), /searchProvider: geek2api\n/u)
|
||||
})
|
||||
|
||||
test('the registered providers search with ring keys and route by the initiating model', async t => {
|
||||
const env = await makeContext({ settings: '0.2' })
|
||||
t.after(env.cleanup)
|
||||
apply(env.ctx, env.config)
|
||||
await settle()
|
||||
const added = await env.seen.handler('keys/add', { key: 'sk-search-key-0001', label: 'search' })
|
||||
assert.equal(added.ok, true)
|
||||
|
||||
const original = globalThis.fetch
|
||||
const requests = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
// Every probe answers alike, so the configured order decides the host.
|
||||
if (String(url).endsWith('/health')) return { ok: false, status: 503 }
|
||||
requests.push({ url, key: new Headers(init.headers).get('x-api-key') })
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
content: [
|
||||
{ type: 'web_search_tool_result', content: [{ type: 'web_search_result', url: 'https://geek2api.example/', title: 'Geek2API result' }] },
|
||||
{ type: 'text', text: 'summary' },
|
||||
],
|
||||
}),
|
||||
}
|
||||
}
|
||||
t.after(() => { globalThis.fetch = original })
|
||||
|
||||
const direct = await env.providers.get('geek2api').search({ query: 'q' })
|
||||
assert.equal(direct.sources[0].url, 'https://geek2api.example/')
|
||||
assert.deepEqual(requests, [{ url: `${DEFAULT_API_HOST}/v1/messages`, key: 'sk-search-key-0001' }])
|
||||
|
||||
const auto = env.providers.get('geek2api-auto')
|
||||
assert.equal((await auto.search({ query: 'q' })).sources[0].url, 'https://geek2api.example/')
|
||||
env.setModelProvider('anthropic')
|
||||
assert.equal((await auto.search({ query: 'q' })).sources[0].url, 'https://dsh.example/')
|
||||
assert.equal(requests.length, 2, 'the non-Geek2API request never reached the gateway')
|
||||
})
|
||||
|
||||
test('patch writes run inside DSH\'s reload lock, and unlocked when that lock refuses to nest', async t => {
|
||||
const env = await makeContext({ settings: '0.2' })
|
||||
t.after(env.cleanup)
|
||||
let nested = false
|
||||
let locked = 0
|
||||
env.ctx.get = (original => name => (name === 'hmr'
|
||||
? {
|
||||
async runExclusive(operation) {
|
||||
if (nested) throw new Error('HMR transactions cannot be nested')
|
||||
locked += 1
|
||||
return operation()
|
||||
},
|
||||
}
|
||||
: original(name)))(env.ctx.get)
|
||||
apply(env.ctx, env.config)
|
||||
await settle()
|
||||
const before = locked
|
||||
await env.seen.handler('search/update', { searchProvider: 'auto' })
|
||||
assert.equal(locked, before + 1)
|
||||
assert.match(await readFile(env.patchPath, 'utf8'), /searchProvider: geek2api-auto\n/u)
|
||||
|
||||
nested = true
|
||||
const updated = await env.seen.handler('search/update', { searchProvider: 'geek2api' })
|
||||
assert.equal(updated.value.applied.state, 'applied')
|
||||
assert.match(await readFile(env.patchPath, 'utf8'), /searchProvider: geek2api\n/u)
|
||||
})
|
||||
|
||||
test('a profile without the web service keeps its route and reports search unavailable', async t => {
|
||||
const env = await makeContext({ settings: '0.2' })
|
||||
t.after(env.cleanup)
|
||||
const inject = env.ctx.inject
|
||||
env.ctx.inject = (names, callback) => (names.includes('web') ? undefined : inject(names, callback))
|
||||
apply(env.ctx, env.config)
|
||||
const status = await env.seen.handler('search/status', {})
|
||||
assert.equal(status.value.available, false)
|
||||
assert.equal(env.providers.has('geek2api'), false)
|
||||
})
|
||||
@@ -0,0 +1,393 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { Geek2APIKeyRing } from '../src/key-ring.js'
|
||||
import {
|
||||
buildSearchRequest,
|
||||
createGeek2APIAutoSearchProvider,
|
||||
createGeek2APISearchProvider,
|
||||
DEFAULT_SEARCH_BACKEND,
|
||||
GEEK2API_AUTO_SEARCH_PROVIDER_ID,
|
||||
GEEK2API_SEARCH_PROVIDER_ID,
|
||||
parseMessagesSearchResponse,
|
||||
parseResponsesSearchResponse,
|
||||
WebError,
|
||||
} from '../src/search.js'
|
||||
import { createHostPool } from '../src/hosts.js'
|
||||
import { fakeCredentials, stubHostPool } from './helpers.mjs'
|
||||
|
||||
async function ringWith(...keys) {
|
||||
const ring = new Geek2APIKeyRing(fakeCredentials())
|
||||
for (const [index, key] of keys.entries()) await ring.add(key, `k${index + 1}`)
|
||||
return ring
|
||||
}
|
||||
|
||||
const json = (status, body) => ({
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: async () => body,
|
||||
text: async () => JSON.stringify(body),
|
||||
})
|
||||
|
||||
/** The block shape `claude-haiku-4-5-20251001` answered with through Geek2API's `/v1/messages`. */
|
||||
const MESSAGES_ANSWER = {
|
||||
type: 'message',
|
||||
role: 'assistant',
|
||||
model: 'claude-haiku-4-5-20251001',
|
||||
content: [
|
||||
{ type: 'thinking', thinking: '…', signature: 'sig' },
|
||||
{ type: 'server_tool_use', id: 'srv_1', name: 'web_search', input: { query: 'DeepSeek Harness desktop app' } },
|
||||
{
|
||||
type: 'web_search_tool_result',
|
||||
tool_use_id: 'srv_1',
|
||||
content: [
|
||||
{ type: 'web_search_result', title: 'DeepSeek Harness Desktop Preview', url: 'https://eu.36kr.com/en/p/3998199345500040#1', encrypted_content: 'x'.repeat(64), page_age: null },
|
||||
{ type: 'web_search_result', title: '下载 DeepSeek', url: 'https://www.deepseek.com/download/', encrypted_content: 'y', page_age: 'June 1, 2026' },
|
||||
{ type: 'web_search_result', title: 'duplicate', url: 'https://www.deepseek.com/download/', encrypted_content: 'z' },
|
||||
{ type: 'web_search_result', title: 'not http', url: 'javascript:alert(1)' },
|
||||
],
|
||||
},
|
||||
{ type: 'thinking', thinking: '…', signature: 'sig' },
|
||||
{ type: 'text', text: 'The desktop preview ', citations: [] },
|
||||
{ type: 'text', text: 'launched.', citations: [{ type: 'web_search_result_location', url: 'https://www.deepseek.com/download/', title: '下载 DeepSeek', cited_text: 'Download the DeepSeek Harness desktop app.' }] },
|
||||
],
|
||||
usage: { input_tokens: 8920, output_tokens: 891, server_tool_use: { web_search_requests: 1 } },
|
||||
}
|
||||
|
||||
/** The item shape `gpt-6.1-sol` answered with through Geek2API's `/v1/responses`. */
|
||||
const RESPONSES_ANSWER = {
|
||||
output: [
|
||||
{ type: 'message', content: [{ type: 'output_text', text: 'I’ll check Node.js’s release announcements.', annotations: [] }] },
|
||||
{ type: 'web_search_call', status: 'completed', action: { type: 'search', query: 'latest Node.js release', sources: [{ type: 'url', url: 'https://nodejs.org/en/blog' }, { type: 'url', url: 'https://github.com/nodejs/node/releases' }] } },
|
||||
{ type: 'web_search_call', status: 'completed', action: { type: 'open_page', url: 'https://nodejs.org/en/blog/release/v26.11.1' } },
|
||||
{
|
||||
type: 'message',
|
||||
content: [{
|
||||
type: 'output_text',
|
||||
text: 'Node.js 26.11.1 (Current), announced October 7, 2026 — https://nodejs.org/en/blog/release/v26.11.1 ([nodejs.org](https://nodejs.org/en/blog/release/v26.11.1))',
|
||||
annotations: [{ type: 'url_citation', url: 'https://nodejs.org/en/blog/release/v26.11.1', title: 'Node.js — Node.js 26.11.1 (Current)', start_index: 100, end_index: 160 }],
|
||||
}],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
test('a Messages answer maps its result blocks to sources and its text to content', () => {
|
||||
const result = parseMessagesSearchResponse(MESSAGES_ANSWER)
|
||||
assert.deepEqual(result.sources, [
|
||||
{ url: 'https://eu.36kr.com/en/p/3998199345500040#1', title: 'DeepSeek Harness Desktop Preview' },
|
||||
{ url: 'https://www.deepseek.com/download/', title: '下载 DeepSeek', snippet: 'Download the DeepSeek Harness desktop app.', publishedAt: 'June 1, 2026' },
|
||||
])
|
||||
assert.equal(result.content, 'The desktop preview launched.')
|
||||
assert.equal(result.truncated, false)
|
||||
// Encrypted page content never reaches the result.
|
||||
assert.doesNotMatch(JSON.stringify(result), /encrypted|xxxx/u)
|
||||
})
|
||||
|
||||
test('a Messages answer without a search block is an error, not prose scraping', () => {
|
||||
assert.throws(
|
||||
() => parseMessagesSearchResponse({ content: [{ type: 'text', text: 'see https://example.com' }] }),
|
||||
error => error instanceof WebError && error.code === 'WEB_PROVIDER_ERROR' && /did not run a web search/u.test(error.message),
|
||||
)
|
||||
assert.throws(
|
||||
() => parseMessagesSearchResponse({ content: [{ type: 'web_search_tool_result', content: { type: 'web_search_tool_result_error', error_code: 'max_uses_exceeded' } }] }),
|
||||
/max_uses_exceeded/u,
|
||||
)
|
||||
})
|
||||
|
||||
test('a Responses answer lists cited sources first, then the URLs its search actions saw', () => {
|
||||
const result = parseResponsesSearchResponse(RESPONSES_ANSWER)
|
||||
assert.deepEqual(result.sources.map(source => source.url), [
|
||||
'https://nodejs.org/en/blog/release/v26.11.1',
|
||||
'https://nodejs.org/en/blog',
|
||||
'https://github.com/nodejs/node/releases',
|
||||
])
|
||||
assert.equal(result.sources[0].title, 'Node.js — Node.js 26.11.1 (Current)')
|
||||
// A URL without a title is labelled with its host.
|
||||
assert.equal(result.sources[1].title, 'nodejs.org')
|
||||
// The final message is the answer; the preamble is not.
|
||||
assert.match(result.content, /^Node\.js 26\.11\.1 \(Current\)/u)
|
||||
assert.throws(() => parseResponsesSearchResponse({ output: [RESPONSES_ANSWER.output[3]] }), /did not run a web search/u)
|
||||
})
|
||||
|
||||
test('each backend builds its own protocol request against the configured host', () => {
|
||||
const claude = buildSearchRequest('claude', { apiHost: 'https://gw.example', query: 'q', sessionId: 's1' })
|
||||
assert.equal(claude.url, 'https://gw.example/v1/messages')
|
||||
assert.deepEqual(claude.headers('sk-1'), { 'x-api-key': 'sk-1', 'anthropic-version': '2023-06-01' })
|
||||
assert.equal(claude.body.model, 'claude-haiku-4-5-20251001')
|
||||
assert.deepEqual(claude.body.tools, [{ type: 'web_search_20250305', name: 'web_search', max_uses: 3 }])
|
||||
assert.match(claude.body.messages[0].content, /^Perform a web search for the query: q/u)
|
||||
|
||||
const gpt = buildSearchRequest('gpt', { apiHost: 'https://gw.example', query: 'q', sessionId: 's1' })
|
||||
assert.equal(gpt.url, 'https://gw.example/v1/responses')
|
||||
assert.deepEqual(gpt.headers('sk-1'), { authorization: 'Bearer sk-1' })
|
||||
assert.equal(gpt.body.model, 'gpt-6.1-sol')
|
||||
assert.deepEqual(gpt.body.tools, [{ type: 'web_search' }])
|
||||
assert.equal(gpt.body.tool_choice, 'required')
|
||||
assert.equal(gpt.body.store, false)
|
||||
assert.equal(gpt.body.prompt_cache_key, 's1')
|
||||
// The Codex group refuses a bare string input on some channels.
|
||||
assert.ok(Array.isArray(gpt.body.input))
|
||||
|
||||
assert.equal(DEFAULT_SEARCH_BACKEND, 'claude')
|
||||
assert.throws(() => buildSearchRequest('bing', { apiHost: 'https://gw.example', query: 'q' }), /not supported/u)
|
||||
})
|
||||
|
||||
test('a search authenticates with the active ring key only and refuses redirects', async () => {
|
||||
const ring = await ringWith('sk-first-key-0001', 'sk-second-key-0002')
|
||||
const calls = []
|
||||
const provider = createGeek2APISearchProvider({
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
fetchImpl: async (url, init) => {
|
||||
calls.push({ url, init })
|
||||
return json(200, MESSAGES_ANSWER)
|
||||
},
|
||||
})
|
||||
assert.equal(provider.id, GEEK2API_SEARCH_PROVIDER_ID)
|
||||
assert.equal(provider.available(), true)
|
||||
const result = await provider.search({ query: 'DeepSeek Harness', maxResults: 5 })
|
||||
assert.equal(result.sources.length, 2)
|
||||
assert.equal(calls.length, 1)
|
||||
assert.equal(calls[0].url, 'https://gw.example/v1/messages')
|
||||
assert.equal(calls[0].init.redirect, 'error')
|
||||
assert.equal(calls[0].init.headers['x-api-key'], 'sk-first-key-0001')
|
||||
assert.ok(calls[0].init.signal instanceof AbortSignal)
|
||||
})
|
||||
|
||||
test('the backend preference is read per search', async () => {
|
||||
const ring = await ringWith('sk-first-key-0001')
|
||||
let backend = 'claude'
|
||||
const urls = []
|
||||
const provider = createGeek2APISearchProvider({
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
backend: () => backend,
|
||||
fetchImpl: async url => {
|
||||
urls.push(url)
|
||||
return json(200, url.endsWith('/responses') ? RESPONSES_ANSWER : MESSAGES_ANSWER)
|
||||
},
|
||||
})
|
||||
await provider.search({ query: 'a' })
|
||||
backend = 'gpt'
|
||||
await provider.search({ query: 'b' })
|
||||
backend = 'unknown'
|
||||
await provider.search({ query: 'c' })
|
||||
assert.deepEqual(urls, ['https://gw.example/v1/messages', 'https://gw.example/v1/responses', 'https://gw.example/v1/messages'])
|
||||
})
|
||||
|
||||
test('an exhausted key moves aside through the shared sink and the next key answers', async () => {
|
||||
const ring = await ringWith('sk-first-key-0001', 'sk-second-key-0002')
|
||||
const failures = []
|
||||
const used = []
|
||||
const provider = createGeek2APISearchProvider({
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
onKeyFailure: (kind, message, key, id) => {
|
||||
failures.push({ kind, key, id })
|
||||
void ring.disable(id, kind)
|
||||
},
|
||||
fetchImpl: async (_url, init) => {
|
||||
used.push(init.headers['x-api-key'])
|
||||
return init.headers['x-api-key'] === 'sk-first-key-0001'
|
||||
? json(403, { code: 'INSUFFICIENT_BALANCE', message: '余额不足,请充值' })
|
||||
: json(200, MESSAGES_ANSWER)
|
||||
},
|
||||
})
|
||||
const result = await provider.search({ query: 'q' })
|
||||
assert.equal(result.sources.length, 2)
|
||||
assert.deepEqual(used, ['sk-first-key-0001', 'sk-second-key-0002'])
|
||||
assert.equal(failures.length, 1)
|
||||
assert.equal(failures[0].kind, 'quota')
|
||||
assert.equal(failures[0].key, 'sk-first-key-0001')
|
||||
assert.equal(typeof failures[0].id, 'string')
|
||||
})
|
||||
|
||||
test('a key whose group does not cover the search model is skipped but never disabled', async () => {
|
||||
const ring = await ringWith('sk-first-key-0001', 'sk-second-key-0002')
|
||||
const failures = []
|
||||
let calls = 0
|
||||
const provider = createGeek2APISearchProvider({
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
backend: () => 'gpt',
|
||||
onKeyFailure: kind => failures.push(kind),
|
||||
fetchImpl: async () => {
|
||||
calls += 1
|
||||
return json(400, { error: { message: "Model 'gpt-6.1-sol' is not available. Use GET /v1/models to see supported models.", type: 'invalid_request_error' } })
|
||||
},
|
||||
})
|
||||
await assert.rejects(provider.search({ query: 'q' }), error => {
|
||||
assert.equal(error.code, 'WEB_PROVIDER_ERROR')
|
||||
assert.match(error.message, /no stored API key's group covers gpt-6\.1-sol/u)
|
||||
assert.match(error.message, /Switch the search backend to "claude"/u)
|
||||
return true
|
||||
})
|
||||
assert.equal(calls, 2)
|
||||
assert.deepEqual(failures, [])
|
||||
assert.equal((await ring.list()).keys.every(key => !key.disabled), true)
|
||||
})
|
||||
|
||||
test('a client-policy refusal is explained and blames no key', async () => {
|
||||
const ring = await ringWith('sk-first-key-0001')
|
||||
const failures = []
|
||||
const provider = createGeek2APISearchProvider({
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
onKeyFailure: kind => failures.push(kind),
|
||||
fetchImpl: async () => json(403, { error: { message: '请使用标准 codex 客户端' } }),
|
||||
})
|
||||
await assert.rejects(provider.search({ query: 'q' }), /拒绝了这个客户端/u)
|
||||
assert.deepEqual(failures, [])
|
||||
})
|
||||
|
||||
test('other failures name the status and never echo the key', async () => {
|
||||
const ring = await ringWith('sk-secret-key-123456')
|
||||
const provider = createGeek2APISearchProvider({
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
fetchImpl: async () => json(500, { error: { message: 'upstream exploded for sk-secret-key-123456' } }),
|
||||
})
|
||||
await assert.rejects(provider.search({ query: 'q' }), error => {
|
||||
assert.equal(error.code, 'WEB_PROVIDER_ERROR')
|
||||
assert.match(error.message, /HTTP 500/u)
|
||||
assert.doesNotMatch(error.message, /sk-secret-key-123456/u)
|
||||
assert.match(error.message, /…3456/u)
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
test('no stored key, an empty query, and a cancelled search fail with their own codes', async () => {
|
||||
const empty = createGeek2APISearchProvider({
|
||||
ring: await ringWith(),
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
fetchImpl: async () => assert.fail('no request without a key'),
|
||||
})
|
||||
await assert.rejects(empty.search({ query: 'q' }), error => error.code === 'WEB_PROVIDER_CREDENTIAL_MISSING' && /Settings → Geek2API/u.test(error.message))
|
||||
await assert.rejects(empty.search({ query: ' ' }), /non-empty query/u)
|
||||
|
||||
const ring = await ringWith('sk-first-key-0001')
|
||||
let started
|
||||
const fetching = new Promise(resolve => { started = resolve })
|
||||
const slow = createGeek2APISearchProvider({
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
// Like fetch: an already-aborted signal rejects at once, a later abort rejects then.
|
||||
fetchImpl: (_url, init) => new Promise((_resolve, reject) => {
|
||||
const abort = () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))
|
||||
if (init.signal.aborted) return abort()
|
||||
init.signal.addEventListener('abort', abort)
|
||||
started()
|
||||
}),
|
||||
})
|
||||
const controller = new AbortController()
|
||||
const pending = slow.search({ query: 'q' }, controller.signal)
|
||||
await fetching
|
||||
controller.abort()
|
||||
await assert.rejects(pending, error => error.code === 'WEB_ABORTED')
|
||||
// Cancelled while the key was still being resolved: no request goes out.
|
||||
const early = new AbortController()
|
||||
const beforeFetch = slow.search({ query: 'q' }, early.signal)
|
||||
early.abort()
|
||||
await assert.rejects(beforeFetch, error => error.code === 'WEB_ABORTED')
|
||||
const aborted = new AbortController()
|
||||
aborted.abort()
|
||||
await assert.rejects(slow.search({ query: 'q' }, aborted.signal), error => error.code === 'WEB_ABORTED')
|
||||
})
|
||||
|
||||
test('a request that never answers is bounded by the search timeout', async t => {
|
||||
// AbortSignal.timeout does not keep the event loop alive, and this fake
|
||||
// fetch holds nothing open; in a host process something always does. Node
|
||||
// 22's runner would otherwise see an idle loop and cancel the file.
|
||||
const keepAlive = setInterval(() => {}, 1_000)
|
||||
t.after(() => clearInterval(keepAlive))
|
||||
const ring = await ringWith('sk-first-key-0001')
|
||||
const provider = createGeek2APISearchProvider({
|
||||
ring,
|
||||
hosts: stubHostPool(createHostPool, ['https://gw.example']),
|
||||
timeoutMs: 20,
|
||||
fetchImpl: (_url, init) => new Promise((_resolve, reject) => {
|
||||
const abort = () => reject(Object.assign(new Error('timed out'), { name: 'TimeoutError' }))
|
||||
if (init.signal.aborted) return abort()
|
||||
init.signal.addEventListener('abort', abort)
|
||||
}),
|
||||
})
|
||||
await assert.rejects(provider.search({ query: 'q' }), error => error.code === 'WEB_PROVIDER_ERROR' && /no answer within/u.test(error.message))
|
||||
})
|
||||
|
||||
test('a host that never answers is set aside and the same key searches on the next host', async () => {
|
||||
const ring = await ringWith('sk-first-key-0001')
|
||||
const hosts = stubHostPool(createHostPool, ['https://down.example', 'https://gw.example'])
|
||||
const failures = []
|
||||
const urls = []
|
||||
const provider = createGeek2APISearchProvider({
|
||||
ring,
|
||||
hosts,
|
||||
onKeyFailure: kind => failures.push(kind),
|
||||
fetchImpl: async url => {
|
||||
urls.push(url)
|
||||
if (url.startsWith('https://down.example/')) throw Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNREFUSED' } })
|
||||
return json(200, MESSAGES_ANSWER)
|
||||
},
|
||||
})
|
||||
const result = await provider.search({ query: 'q' })
|
||||
assert.equal(result.sources.length, 2)
|
||||
assert.deepEqual(urls, ['https://down.example/v1/messages', 'https://gw.example/v1/messages'])
|
||||
assert.deepEqual(failures, [], 'the key is not at fault')
|
||||
assert.equal(hosts.order()[0], 'https://gw.example')
|
||||
})
|
||||
|
||||
function stubProvider(id, answer) {
|
||||
const seen = []
|
||||
return {
|
||||
id,
|
||||
seen,
|
||||
available: () => true,
|
||||
async search(request) {
|
||||
seen.push(request.query)
|
||||
return typeof answer === 'function' ? answer(request) : answer
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test('auto search serves Geek2API sessions itself and hands every other request to the fallback', async () => {
|
||||
const geek2api = stubProvider(GEEK2API_SEARCH_PROVIDER_ID, { sources: [{ url: 'https://p.example' }], truncated: false })
|
||||
const fallback = stubProvider('kimi-subscription', { sources: [{ url: 'https://k.example' }], truncated: false })
|
||||
let modelProvider = 'geek2api'
|
||||
const auto = createGeek2APIAutoSearchProvider({
|
||||
geek2api,
|
||||
resolveModelProvider: () => modelProvider,
|
||||
resolveProvider: id => (id === fallback.id ? fallback : undefined),
|
||||
resolveFallbackId: () => 'kimi-subscription',
|
||||
})
|
||||
assert.equal(auto.id, GEEK2API_AUTO_SEARCH_PROVIDER_ID)
|
||||
assert.equal((await auto.search({ query: 'one' })).sources[0].url, 'https://p.example')
|
||||
modelProvider = 'anthropic'
|
||||
assert.equal((await auto.search({ query: 'two' })).sources[0].url, 'https://k.example')
|
||||
assert.deepEqual(geek2api.seen, ['one'])
|
||||
assert.deepEqual(fallback.seen, ['two'])
|
||||
})
|
||||
|
||||
test('auto search never falls back to itself, and a router that loops back reaches DSH search', async () => {
|
||||
const geek2api = stubProvider(GEEK2API_SEARCH_PROVIDER_ID, { sources: [], truncated: false })
|
||||
const dsh = stubProvider('deepseek-official', { sources: [{ url: 'https://d.example' }], truncated: false })
|
||||
const providers = new Map([[dsh.id, dsh]])
|
||||
let auto
|
||||
// A foreign router whose own fallback is the web row's base — this plugin.
|
||||
const router = stubProvider('kimi-subscription-auto', request => auto.search(request))
|
||||
providers.set(router.id, router)
|
||||
let fallbackId = GEEK2API_AUTO_SEARCH_PROVIDER_ID
|
||||
auto = createGeek2APIAutoSearchProvider({
|
||||
geek2api,
|
||||
resolveModelProvider: () => 'anthropic',
|
||||
resolveProvider: id => providers.get(id),
|
||||
resolveFallbackId: () => fallbackId,
|
||||
})
|
||||
assert.equal((await auto.search({ query: 'self' })).sources[0].url, 'https://d.example')
|
||||
fallbackId = 'kimi-subscription-auto'
|
||||
assert.equal((await auto.search({ query: 'loop' })).sources[0].url, 'https://d.example')
|
||||
assert.deepEqual(router.seen, ['loop'])
|
||||
assert.deepEqual(dsh.seen, ['self', 'loop'])
|
||||
|
||||
fallbackId = 'missing-provider'
|
||||
await assert.rejects(auto.search({ query: 'x' }), error => error.code === 'WEB_PROVIDER_UNAVAILABLE' && /missing-provider/u.test(error.message))
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { createDeltaRedactor, redactSecrets } from '../src/secret-redactor.js'
|
||||
|
||||
test('redaction covers raw and JSON-escaped quote/backslash keys', () => {
|
||||
const key = 'sk-private-"quoted"-\\backslash'
|
||||
assert.equal(redactSecrets(`value ${key}`, [key]), 'value [redacted]')
|
||||
const serialized = redactSecrets(JSON.stringify({ summary: `echo ${key}`, title: key }), [key])
|
||||
assert.deepEqual(JSON.parse(serialized), { summary: 'echo [redacted]', title: '[redacted]' })
|
||||
})
|
||||
|
||||
test('every possible delta split of a secret and its escaped form redacts before emission', () => {
|
||||
const key = 'sk-private-"quoted"-\\backslash'
|
||||
for (const value of [key, JSON.stringify(key).slice(1, -1)]) {
|
||||
for (let split = 1; split < value.length; split++) {
|
||||
const redactor = createDeltaRedactor([key])
|
||||
const result = redactor.write(`说明 ${value.slice(0, split)}`) + redactor.write(`${value.slice(split)} done`) + redactor.flush()
|
||||
assert.equal(result, '说明 [redacted] done')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('character-by-character credentials/capabilities and block-boundary prefixes cannot reconstruct a secret', () => {
|
||||
const key = 'sk-test-only-streamed-secret'
|
||||
const cap = 'deadbeef1234567890abcdef'
|
||||
const redactor = createDeltaRedactor([key, cap])
|
||||
let result = ''
|
||||
for (const char of `one ${key} two ${cap}.`) result += redactor.write(char)
|
||||
result += redactor.flush()
|
||||
assert.equal(result, 'one [redacted] two [redacted].')
|
||||
const boundary = createDeltaRedactor([key])
|
||||
const across = boundary.write(key.slice(0, 5)) + boundary.flush({ boundary: true }) + boundary.write(key.slice(5)) + boundary.flush()
|
||||
assert.equal(across.includes(key), false)
|
||||
})
|
||||
|
||||
test('ordinary streaming text and incomplete end-of-output prefixes remain unchanged', () => {
|
||||
const redactor = createDeltaRedactor(['sk-sensitive-value'])
|
||||
const input = ['你好 ', 'plain ', 'source', 's']
|
||||
const output = input.map(s => redactor.write(s)).join('') + redactor.flush()
|
||||
assert.equal(output, input.join(''))
|
||||
})
|
||||
@@ -0,0 +1,139 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { DEFAULT_API_HOSTS } from '../src/constants.js'
|
||||
import { apply } from '../src/index.js'
|
||||
import { fakeCredentials } from './helpers.mjs'
|
||||
|
||||
/**
|
||||
* A context whose settings and connection services behave like the real ones
|
||||
* at the two seams this plugin uses: a section install that hands back a live
|
||||
* source, and a loopback RPC registration.
|
||||
*/
|
||||
function makeContext({ installSection = true, update = true } = {}) {
|
||||
const seen = { installed: undefined, updates: [], handler: undefined, adapters: [], injected: [] }
|
||||
const ctx = {
|
||||
credentials: fakeCredentials(),
|
||||
attachments: undefined,
|
||||
logger: { warn: () => {} },
|
||||
llm: {
|
||||
registerAdapter(providers, adapter) {
|
||||
seen.adapters.push({ providers, adapter })
|
||||
return () => {}
|
||||
},
|
||||
registerConfigurableProviders() {
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
get: () => undefined,
|
||||
inject(services, callback) {
|
||||
seen.injected.push(services)
|
||||
if (services.includes('settings')) {
|
||||
const settings = {
|
||||
installSection(owner, ns, schema, entry, hooks) {
|
||||
if (!installSection) throw new Error('this profile mounts no settings provider')
|
||||
seen.installed = { owner, ns, schema, entry, hooks }
|
||||
},
|
||||
}
|
||||
if (update) {
|
||||
settings.update = async (ns, patch) => {
|
||||
seen.updates.push({ ns, patch })
|
||||
}
|
||||
}
|
||||
return callback({ settings })
|
||||
}
|
||||
if (services.includes('tools')) {
|
||||
return callback({ tools: { register: () => () => {} } })
|
||||
}
|
||||
if (services.includes('connection')) {
|
||||
return callback({
|
||||
effect: ctx.effect,
|
||||
connection: {
|
||||
rpc: {
|
||||
handle(channel, handler) {
|
||||
seen.handler = handler
|
||||
seen.channel = channel
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return callback(ctx)
|
||||
},
|
||||
effect(callback) {
|
||||
const disposer = callback()
|
||||
return typeof disposer === 'function' ? disposer : () => {}
|
||||
},
|
||||
}
|
||||
return { ctx, seen }
|
||||
}
|
||||
|
||||
test('installs its settings section under its own namespace', () => {
|
||||
const { ctx, seen } = makeContext()
|
||||
apply(ctx)
|
||||
assert.equal(seen.installed.ns, 'geek2api')
|
||||
assert.ok('apiHosts' in seen.installed.entry)
|
||||
assert.ok('claudeRuntime' in seen.installed.entry)
|
||||
assert.equal(typeof seen.installed.hooks.setSource, 'function')
|
||||
assert.equal(typeof seen.installed.hooks.onChange, 'function')
|
||||
})
|
||||
|
||||
test('the settings source drives the host list and Claude runtime, and writes go back to it', async t => {
|
||||
// Probes answer alike, so the configured order decides; no real network.
|
||||
t.mock.method(globalThis, 'fetch', async () => new Response('{}', { status: 503 }))
|
||||
const { ctx, seen } = makeContext()
|
||||
apply(ctx)
|
||||
|
||||
const before = await seen.handler('status')
|
||||
assert.deepEqual(before.value.hosts.map(entry => entry.host), [...DEFAULT_API_HOSTS])
|
||||
assert.equal(before.value.claudeRuntime, 'http')
|
||||
assert.equal(before.value.writable, true)
|
||||
|
||||
// The real service hands back a getter; a plain value must work too.
|
||||
let current = { apiHosts: ['https://gateway.example/', 'nonsense', 'https://second.example'], claudeRuntime: 'cli' }
|
||||
seen.installed.hooks.setSource(() => current)
|
||||
const after = await seen.handler('status')
|
||||
assert.deepEqual(after.value.hosts.map(entry => entry.host), ['https://gateway.example', 'https://second.example'])
|
||||
assert.equal(after.value.claudeRuntime, 'cli')
|
||||
|
||||
// Unusable entries are dropped and the order kept; an empty list restores the defaults.
|
||||
const updated = await seen.handler('hosts/update', { apiHosts: ['https://other.example//', 'not a url', 'https://b.example'] })
|
||||
assert.equal(updated.ok, true)
|
||||
assert.deepEqual(seen.updates[0], { ns: 'geek2api', patch: { apiHosts: ['https://other.example', 'https://b.example'] } })
|
||||
await seen.handler('hosts/update', { apiHosts: [] })
|
||||
assert.deepEqual(seen.updates[1].patch, { apiHosts: [...DEFAULT_API_HOSTS] })
|
||||
|
||||
const runtime = await seen.handler('claude-runtime/update', { runtime: 'http' })
|
||||
assert.equal(runtime.ok, true)
|
||||
assert.deepEqual(seen.updates[2].patch, { claudeRuntime: 'http' })
|
||||
const bogus = await seen.handler('claude-runtime/update', { runtime: 'shell' })
|
||||
assert.equal(bogus.ok, false)
|
||||
assert.match(bogus.error.message, /not supported/u)
|
||||
|
||||
const probed = await seen.handler('hosts/probe', {})
|
||||
assert.equal(probed.ok, true)
|
||||
assert.ok(probed.value.hosts.every(entry => entry.latencyMs === undefined), 'a 5xx probe is not a latency')
|
||||
|
||||
// ...and the section's change hook is wired to drop the caches.
|
||||
seen.installed.hooks.onChange()
|
||||
})
|
||||
|
||||
test('a runtime whose settings service cannot write keeps the read-only posture', async () => {
|
||||
const { ctx, seen } = makeContext({ update: false })
|
||||
apply(ctx)
|
||||
const status = await seen.handler('status')
|
||||
assert.equal(status.value.writable, false)
|
||||
const refused = await seen.handler('hosts/update', { apiHosts: ['https://x.example'] })
|
||||
assert.equal(refused.ok, false)
|
||||
assert.match(refused.error.message, /not writable/u)
|
||||
})
|
||||
|
||||
test('a profile without a settings provider still serves its route', () => {
|
||||
const { ctx, seen } = makeContext({ installSection: false })
|
||||
apply(ctx)
|
||||
assert.equal(seen.installed, undefined)
|
||||
assert.equal(seen.adapters.length, 1)
|
||||
assert.deepEqual(seen.injected, [['settings'], ['web'], ['connection', 'webServer'], ['tools']])
|
||||
assert.equal(seen.channel, '/geek2api')
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { sumBalances } from '../src/totals.js'
|
||||
|
||||
test('adds the per-key quotas a balance read returned', () => {
|
||||
const rows = [
|
||||
{ id: 'a', usage: { mode: 'quota', availableUsd: 499.07, usedUsd: 0.93, limitUsd: 500 } },
|
||||
{ id: 'b', usage: { mode: 'subscription', planName: 'Plus', availableUsd: 500, usedUsd: 0, limitUsd: 500, resetPeriod: 'monthly' } },
|
||||
]
|
||||
const totals = sumBalances(rows)
|
||||
assert.equal(totals.counted, 2)
|
||||
assert.equal(Math.round(totals.remainingUsd * 100) / 100, 999.07)
|
||||
assert.equal(Math.round(totals.usedUsd * 100) / 100, 0.93)
|
||||
assert.equal(totals.limitUsd, 1000)
|
||||
assert.equal(totals.unread, 0)
|
||||
assert.equal(totals.unlimited, 0)
|
||||
})
|
||||
|
||||
test('counts only what it can read and reports the rest', () => {
|
||||
const rows = [
|
||||
{ id: 'a', usage: { availableUsd: 10, usedUsd: 1, limitUsd: 11 } },
|
||||
{ id: 'b', error: 'this API key was rejected (401)' },
|
||||
]
|
||||
const totals = sumBalances(rows)
|
||||
assert.equal(totals.keys, 2)
|
||||
assert.equal(totals.counted, 1)
|
||||
assert.equal(totals.unread, 1)
|
||||
assert.equal(totals.remainingUsd, 10)
|
||||
assert.equal(totals.limitUsd, 11)
|
||||
})
|
||||
|
||||
test('an unlimited key is reported instead of inflating a limit', () => {
|
||||
const totals = sumBalances([
|
||||
{ id: 'a', usage: { availableUsd: 100, usedUsd: 5, limitUsd: 105 } },
|
||||
{ id: 'b', usage: { unlimitedQuota: true, availableUsd: 0, usedUsd: 0 } },
|
||||
])
|
||||
assert.equal(totals.limitUsd, 105)
|
||||
assert.equal(totals.unlimited, 1)
|
||||
})
|
||||
|
||||
test('a key without a period limit contributes only what it reports', () => {
|
||||
const totals = sumBalances([{ id: 'a', usage: { availableUsd: 2, usedUsd: 1 } }])
|
||||
assert.equal(totals.remainingUsd, 2)
|
||||
assert.equal(totals.limitUsd, 0)
|
||||
})
|
||||
|
||||
test('an empty or malformed row list totals to zero', () => {
|
||||
assert.deepEqual(sumBalances([]), { keys: 0, counted: 0, unread: 0, unlimited: 0, shared: 0, remainingUsd: 0, usedUsd: 0, limitUsd: 0 })
|
||||
assert.equal(sumBalances(undefined).keys, 0)
|
||||
assert.equal(sumBalances([null, 7]).keys, 2)
|
||||
assert.equal(sumBalances([null, 7]).counted, 0)
|
||||
})
|
||||
|
||||
test('keys of one account share a wallet that is counted once, by account reference', () => {
|
||||
const totals = sumBalances([
|
||||
{ id: 'a', usage: { mode: 'wallet', accountRef: 'acct-1', availableUsd: 40, usedUsd: 3 } },
|
||||
{ id: 'b', usage: { mode: 'wallet', accountRef: 'acct-1', availableUsd: 40, usedUsd: 9 } },
|
||||
{ id: 'c', usage: { mode: 'wallet', accountRef: 'acct-2', availableUsd: 40, usedUsd: 1 } },
|
||||
])
|
||||
assert.equal(totals.counted, 3)
|
||||
assert.equal(totals.shared, 1)
|
||||
assert.equal(totals.remainingUsd, 80, 'two accounts, even with equal balances')
|
||||
assert.equal(totals.usedUsd, 4)
|
||||
})
|
||||
|
||||
test('without an account reference, wallets with the same balance are the same wallet', () => {
|
||||
const totals = sumBalances([
|
||||
{ id: 'a', usage: { mode: 'wallet', availableUsd: 4226.232196 } },
|
||||
{ id: 'b', usage: { mode: 'wallet', availableUsd: 4226.232196 } },
|
||||
{ id: 'c', usage: { mode: 'wallet', availableUsd: 12.5 } },
|
||||
{ id: 'd', usage: { mode: 'quota', availableUsd: 4226.232196, limitUsd: 5000 } },
|
||||
])
|
||||
assert.equal(totals.shared, 1)
|
||||
assert.equal(Math.round((totals.remainingUsd) * 1e6) / 1e6, Math.round((4226.232196 * 2 + 12.5) * 1e6) / 1e6, 'a key quota is its own money')
|
||||
assert.equal(totals.limitUsd, 5000)
|
||||
})
|
||||
Reference in new issue
Block a user