fix(assistant): retain repair budget for unspecified model caps
This commit is contained in:
1 parent
5a5e166437
commit
506e6fbfad
2 files changed
+2
-1
No files matched your search
@@ -16,7 +16,7 @@ class ProviderRegistry{
|
||||
save(input){return this.store.transaction(()=>{if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!['id','version','name','preset','protocol','apiBase','enabled','apiKey','hasApiKey','models'].includes(k)))throw fail('供应商配置格式不正确。');const old=input.id?this.read(input.id):null;if(input.version!==(old?.version??0))throw fail('供应商配置已更新,请刷新后重试。',409);if(!old&&this.store.db.prepare('SELECT COUNT(*) AS n FROM assistant_providers').get().n>=30)throw fail('最多配置 30 个供应商。',409);const name=text(input.name,'供应商名称');if(!PRESETS.some(p=>p.id===input.preset)||!PROTOCOLS.includes(input.protocol)||typeof input.enabled!=='boolean')throw fail('请选择有效供应商、协议与启用状态。');const apiBase=endpoint(input.apiBase);if(typeof input.apiKey!=='string'||input.apiKey.length>4096||/[\x00-\x1f\x7f]/.test(input.apiKey))throw fail('请输入有效模型密钥。');if(!input.apiKey&&old?.apiKey&&(apiBase!==old.apiBase||input.protocol!==old.protocol))throw fail('更换协议或 API 地址后请重新填写密钥。');this.write({id:old?.id||crypto.randomUUID(),version:(old?.version??0)+1,name,preset:input.preset,protocol:input.protocol,apiBase,enabled:input.enabled,apiKey:input.apiKey||old?.apiKey||'',models:modelRows(input.models)});const defaults=this.defaults();this.writeDefaults({...defaults,version:defaults.version+1});return this.list();});}
|
||||
chooseDefault(input){return this.store.transaction(()=>{const defaults=this.defaults();if(!input||input.version!==defaults.version)throw fail('供应商目录已更新,请刷新后重试。',409);const selected=this.resolve(input);this.writeDefaults({...defaults,version:defaults.version+1,defaultSelection:{providerId:selected.providerId,modelId:selected.model}});return this.list();});}
|
||||
remove(id,input){return this.store.transaction(()=>{const row=this.read(id);if(!input||input.version!==row.version)throw fail('供应商配置已更新,请刷新后重试。',409);this.store.db.prepare('DELETE FROM assistant_providers WHERE id=?').run(id);const defaults=this.defaults();this.writeDefaults({...defaults,version:defaults.version+1,...(id==='deepseek'?{legacyVersion:Math.max(defaults.legacyVersion||0,row.version)}:{}),defaultSelection:defaults.defaultSelection?.providerId===id?null:defaults.defaultSelection});return this.list();});}
|
||||
resolve(selection){const selected=selection===undefined?this.defaults().defaultSelection:selection;if(!selected||typeof selected.providerId!=='string'||typeof selected.modelId!=='string')throw fail('请选择可用模型。',409);const row=this.read(selected.providerId),model=row.models.find(m=>m.id===selected.modelId);if(!row.enabled||!row.apiKey||!model)throw fail('所选供应商或模型不可用,请重新选择。',409);return {providerId:row.id,providerName:row.name,providerVersion:row.version,preset:row.preset,protocol:row.protocol,apiBase:row.apiBase,apiKey:row.apiKey,model:model.id,modelName:model.name,contextWindow:model.contextWindow||131072,maxTokens:model.maxTokens||8192};}
|
||||
resolve(selection){const selected=selection===undefined?this.defaults().defaultSelection:selection;if(!selected||typeof selected.providerId!=='string'||typeof selected.modelId!=='string')throw fail('请选择可用模型。',409);const row=this.read(selected.providerId),model=row.models.find(m=>m.id===selected.modelId);if(!row.enabled||!row.apiKey||!model)throw fail('所选供应商或模型不可用,请重新选择。',409);return {providerId:row.id,providerName:row.name,providerVersion:row.version,preset:row.preset,protocol:row.protocol,apiBase:row.apiBase,apiKey:row.apiKey,model:model.id,modelName:model.name,contextWindow:model.contextWindow||131072,maxTokens:model.maxTokens||Math.min(model.contextWindow||131072,32768)};}
|
||||
syncLegacy(settings){return this.store.transaction(()=>{const defaults=this.defaults();let old;try{old=this.read('deepseek');}catch(e){if(e.status!==409)throw e;}if(!old&&this.store.db.prepare('SELECT COUNT(*) AS n FROM assistant_providers').get().n>=30)throw fail('最多配置 30 个供应商。',409);const apiBase=settings.apiBase||'https://api.deepseek.com/anthropic',model=settings.model||'deepseek-flash';const next={id:'deepseek',version:Math.max(old?.version||0,defaults.legacyVersion||0)+1,name:old?.name||'DeepSeek',preset:'deepseek',protocol:'anthropic-messages',apiBase,apiKey:settings.apiKey||'',enabled:old?.enabled??true,models:[{id:model,name:model}]};this.write(next);this.writeDefaults({...defaults,version:defaults.version+1,legacyMigrated:true,legacyVersion:next.version,defaultSelection:!defaults.legacyMigrated||defaults.defaultSelection?.providerId==='deepseek'?{providerId:'deepseek',modelId:model}:defaults.defaultSelection});return this.list();});}
|
||||
async discover(id,{version,signal}={}){const row=this.read(id);if(version!==row.version)throw fail('供应商配置已更新,请刷新后重试。',409);if(!row.apiKey)throw fail('请先保存供应商密钥。',409);const url=new URL(endpoint(row.apiBase));if(row.preset==='deepseek'&&row.protocol==='anthropic-messages'&&url.pathname.endsWith('/anthropic'))url.pathname=url.pathname.slice(0,-10)||'/';url.pathname=url.pathname.replace(/\/$/,'')+(row.protocol==='anthropic-messages'&&!url.pathname.endsWith('/v1')&&row.preset!=='deepseek'?'/v1':'')+'/models';const headers=row.protocol==='anthropic-messages'&&row.preset!=='deepseek'?{'x-api-key':row.apiKey,'anthropic-version':'2023-06-01'}:{authorization:'Bearer '+row.apiKey};let response,reader;const timeout=AbortSignal.timeout(10000),combined=signal?AbortSignal.any([signal,timeout]):timeout;try{response=await fetch(url,{method:'GET',headers,signal:combined,redirect:'error'});reader=response.body?.getReader();if(!response.ok||Number(response.headers.get('content-length')||0)>1024*1024)throw fail('模型目录请求失败或响应过大。',502);if(!reader)throw fail('模型目录响应为空。',502);const chunks=[];let size=0;while(true){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>1024*1024)throw fail('模型目录响应过大。',502);chunks.push(value);}const data=JSON.parse(Buffer.concat(chunks).toString('utf8'));if(!Array.isArray(data.data)||!data.data.length||data.data.length>100)throw fail('模型目录格式不支持,请手动配置模型。',502);const models=modelRows(data.data.map(m=>({id:m.id,name:m.name||m.display_name||m.id,...(m.context_window||m.contextWindow?{contextWindow:m.context_window||m.contextWindow}:{}),...(m.max_tokens||m.maxTokens?{maxTokens:m.max_tokens||m.maxTokens}:{})})));if(this.read(id).version!==version)throw fail('获取期间供应商配置已更新,请刷新后重试。',409);return {providerId:id,version,models};}catch(e){if(e.status)throw e;if(signal?.aborted)throw fail('已取消获取模型目录。',499);if(timeout.aborted)throw fail('获取模型目录超时。',504);throw fail('模型目录请求失败或格式不支持。',502);}finally{try{await reader?.cancel();}catch{}}}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),http=require('node:http');
|
||||
const adapter=()=>require('../../src/modules/assistant/dsh-runtime.cjs');
|
||||
const config=(patch={})=>({providerId:'fixture',preset:'custom',protocol:'openai-completions',providerName:'Fixture',apiBase:'https://example.test/v1',apiKey:'TEST_KEY',model:'fixture-model',contextWindow:32768,maxTokens:1024,timeoutSeconds:30,allowActions:false,...patch});
|
||||
test('resolved unspecified model capacity retains repair budget and clamps small contexts',async t=>{const dir=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-provider-capacity-')),{AssistantStore}=require('../../src/modules/assistant/store.cjs'),{ProviderRegistry}=require('../../src/modules/assistant/providers.cjs'),store=new AssistantStore(dir);t.after(async()=>{store.close();await fs.rm(dir,{recursive:true,force:true});});store.secretSettings=()=>({apiBase:'https://api.deepseek.com/anthropic',model:'migrated-legacy',apiKey:'LOCAL_LEGACY_KEY'});store.db.exec('DELETE FROM assistant_providers;DELETE FROM assistant_provider_defaults');const registry=new ProviderRegistry(store),legacy=registry.resolve(),{profilePatch}=adapter(),official=repairMode=>JSON.parse(profilePatch({...legacy,timeoutSeconds:30,repairMode}))[0].insert.find(p=>p.id==='llm-deepseek').config;assert.equal(legacy.maxTokens,32768);assert.equal(official(false).maxTokens,8192);assert.equal(official(true).maxTokens,32768);const row=registry.save({version:0,name:'Native',preset:'custom',protocol:'openai-completions',apiBase:'https://example.test/v1',apiKey:'LOCAL_NATIVE_KEY',enabled:true,models:[{id:'unbounded'},{id:'small',contextWindow:4096},{id:'explicit',contextWindow:65536,maxTokens:1024}]}).providers.find(p=>p.id!=='deepseek');for(const [modelId,capacity] of [['unbounded',32768],['small',4096],['explicit',1024]]){const selected=registry.resolve({providerId:row.id,modelId});assert.equal(selected.maxTokens,capacity);const native=JSON.parse(profilePatch({...selected,timeoutSeconds:30,repairMode:true}))[0].insert.find(p=>p.id==='llm-selected').config.providers['order-assistant-selected'];assert.equal(native.models[0].maxTokens,capacity);}});
|
||||
test('selected DeepSeek official adapter honors configured caps while old config keeps legacy defaults',()=>{const {profilePatch}=adapter(),selected=JSON.parse(profilePatch(config({preset:'deepseek',protocol:'anthropic-messages'})))[0].insert.find(p=>p.id==='llm-deepseek').config;assert.equal(selected.maxTokens,1024);assert.equal(selected.defaultContextWindow,32768);const old=JSON.parse(profilePatch({apiBase:'https://api.deepseek.com/anthropic',model:'legacy',timeoutSeconds:30}))[0].insert.find(p=>p.id==='llm-deepseek').config;assert.equal(old.maxTokens,8192);assert.equal(old.defaultContextWindow,131072);});
|
||||
test('selected profiles mount only chosen native protocol with private explicit credential',()=>{const {profilePatch,environment}=adapter();for(const protocol of ['openai-completions','openai-responses','anthropic-messages']){const selected=config({protocol}),patch=profilePatch(selected);assert.match(patch,/dsh-llm-pi-ai/);assert.doesNotMatch(patch,/TEST_KEY|dsh-llm-deepseek-api-key|oauth|authorization/i);const rows=JSON.parse(patch)[0].insert,provider=rows.find(p=>p.name==='@deepseek-ai/dsh-llm-pi-ai').config.providers;assert.deepEqual(Object.keys(provider),['order-assistant-selected']);assert.equal(provider['order-assistant-selected'].api,protocol);assert.equal(provider['order-assistant-selected'].models.length,1);assert.equal(provider['order-assistant-selected'].models[0].maxTokens,1024);const env=environment('C:/isolated','TEST_KEY',selected);assert.equal(env.ORDER_ASSISTANT_API_KEY,'TEST_KEY');assert.equal(env.DEEPSEEK_API_KEY,undefined);assert.equal(env.OPENAI_API_KEY,undefined);}assert.match(profilePatch(config({preset:'deepseek',protocol:'anthropic-messages'})),/dsh-llm-deepseek-api-key/);});
|
||||
const output='{"reply":"local provider works","actions":[]}';
|
||||
|
||||
Reference in new issue
Block a user