Core regression / Python core, intervention UI and release configuration (push) Successful in 4m35s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 3m54s
Core regression / JavaScript syntax (pull_request) Successful in 4s
269 lines
16 KiB
JavaScript
269 lines
16 KiB
JavaScript
/** Application-owned composition around the unmodified official Harness web UI. */
|
|
import {createRequire} from 'node:module';
|
|
import {fileURLToPath} from 'node:url';
|
|
import {mkdir, writeFile, readFile, cp, rename} from 'node:fs/promises';
|
|
import {createHash,randomUUID} from 'node:crypto';
|
|
import {isDeepStrictEqual} from 'node:util';
|
|
import path from 'node:path';
|
|
import {createInterface} from 'node:readline';
|
|
|
|
export const TASK_TOOLS=['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute','dx_task_operations'];
|
|
export const FILE_TOOLS=['read','read_image','write','edit','glob','grep','working_directory','extract_zip'];
|
|
|
|
const root = path.dirname(fileURLToPath(import.meta.url));
|
|
const require = createRequire(import.meta.url);
|
|
export const VERSION = '0.2.1-rc.5';
|
|
export const DISABLED = [
|
|
'desktop-product-telemetry','product-analytics','session-telemetry-otel',
|
|
];
|
|
|
|
export function overlay() {
|
|
const rows = DISABLED.map(id => ({id, disabled:true}));
|
|
rows.push({id:'agent-preset-registry',config:{default:'standard'}});
|
|
rows.push({id:'ui-settings-general',config:{welcomeNoticeVersion:'2026-09-28.1'}});
|
|
rows.push({id:'ui-settings-models',config:{credentialOnboarding:false}});
|
|
rows.push({id:'web-runtime',config:{openBrowser:false,printUrl:false,surfaceContext:false}});
|
|
rows.push({id:'sandbox-policy',config:{mode:process.env.DSH_PERMISSION_MODE??'workspace-write',workspaceRoot:process.env.DX_DSH_WORKSPACE}});
|
|
rows.push({insert:[
|
|
{id:'dx-task',name:'@dx/dsh-task'},
|
|
]});
|
|
if (process.env.DSH_API_BASE && process.env.DSH_MODEL && process.env.DSH_API_KEY) {
|
|
const models=process.env.DX_DSH_MODELS ? JSON.parse(process.env.DX_DSH_MODELS) : [process.env.DSH_MODEL];
|
|
rows.push({id:'llm-pi-ai',config:{providers:{dx:{displayName:'任务中心模型',api:'openai-completions',
|
|
baseURL:process.env.DSH_API_BASE,apiKeyEnv:'DSH_API_KEY',models:models.map(model=>typeof model==='string'?{id:model}:model),timeoutMs:600000}}}});
|
|
rows.push({id:'agent-default-model',config:{provider:'dx',model:process.env.DSH_MODEL}});
|
|
}
|
|
return rows;
|
|
}
|
|
|
|
async function replaceJson(filename,value) {
|
|
const temporary=filename+'.'+randomUUID()+'.tmp';
|
|
const {unlink}=await import('node:fs/promises');
|
|
try{await writeFile(temporary,JSON.stringify(value,null,2));await rename(temporary,filename);}
|
|
finally{await unlink(temporary).catch(error=>{if(error.code!=='ENOENT')throw error;});}
|
|
}
|
|
|
|
async function readOptionalModelMetadata(filename) {
|
|
let text;
|
|
try{text=await readFile(filename,'utf8');}catch(error){if(error.code==='ENOENT')return;throw error;}
|
|
try{return require('js-yaml').load(text);}catch{
|
|
// YAML parser errors can quote the line containing a credential.
|
|
throw Error('Cannot parse stored model metadata: '+path.basename(filename));
|
|
}
|
|
}
|
|
|
|
function modelEntry(rows,id) {
|
|
const entries=rows.filter(row=>row.id===id);
|
|
if(entries.length>1)throw Error('Duplicate '+id+' prevents verifying model binding; startup refused.');
|
|
return entries[0];
|
|
}
|
|
|
|
export function refreshApplicationModels(rows,application,{legacy=false,storedHostKey=false,previousApplication=[],boundDx}={}) {
|
|
const route=application.find(row=>row.id==='llm-pi-ai');
|
|
let current=route?.config.providers.dx;
|
|
if(current&&boundDx?.baseURL===current.baseURL&&boundDx.api===current.api&&boundDx.apiKeyEnv===current.apiKeyEnv){
|
|
// Native model settings own reasoning, context capacity and custom models.
|
|
const models=new Map((boundDx.models??[]).map(model=>[model.id,model]));
|
|
for(const model of current.models)models.set(model.id,{...models.get(model.id),...model});
|
|
current=route.config.providers.dx={...boundDx,...current,models:[...models.values()]};
|
|
}
|
|
let userLlm=rows.filter(row=>row.id==='llm-pi-ai'&&row.config).at(-1);
|
|
if(current&&storedHostKey&&!boundDx){
|
|
// A generated policy alone cannot prove which endpoint a saved key belongs
|
|
// to. Never attach an unbound local credential to today's host endpoint.
|
|
throw Error('Stored DSH_API_KEY has no provider binding; configure a native provider with its own credential reference before starting DSH.');
|
|
}
|
|
if(!userLlm&¤t){
|
|
userLlm={id:'llm-pi-ai',config:{providers:{dx:current}}};
|
|
rows=[...rows,userLlm];
|
|
}
|
|
const prior=boundDx;
|
|
if(storedHostKey&&prior?.apiKeyEnv==='DSH_API_KEY'&&!rows.some(row=>row.id==='agent-default-model')){
|
|
const saved=previousApplication.find(row=>row.id==='agent-default-model')?.config;
|
|
const config=saved?.provider==='dx'&&prior.models?.some(model=>model.id===saved.model)
|
|
?saved:{provider:'dx',model:prior.models[0].id};
|
|
rows=[...rows,{id:'agent-default-model',config}];
|
|
}
|
|
// A native provider with its own credential reference (or deliberately no
|
|
// credential) owns its complete route. Only an environment-sourced
|
|
// DSH_API_KEY belongs to the host; a saved native key owns its user route.
|
|
const managed=prior===undefined||(prior.apiKeyEnv==='DSH_API_KEY'&&!storedHostKey);
|
|
return rows.flatMap(row=>{
|
|
if(row.id==='agent-default-model'&&row.config?.provider==='dx'&&managed
|
|
&&(legacy||!current?.models.some(model=>model.id===row.config.model)))return [];
|
|
if(row.id!=='llm-pi-ai'||!row.config)return [row];
|
|
const providers={...row.config.providers};
|
|
if(providers.dx===undefined||(providers.dx.apiKeyEnv==='DSH_API_KEY'&&!storedHostKey)){
|
|
if(current)providers.dx=current;else delete providers.dx;
|
|
}
|
|
// Harness replaces an entire plugin config, rather than deep-merging it.
|
|
// Keep the host route beside custom routes in any overriding user row.
|
|
return [{...row,config:{...row.config,providers}}];
|
|
});
|
|
}
|
|
|
|
/** Keep installed Standard behavior under the preset ID stored by older sessions. */
|
|
export async function standardCompatibilityPatch(filename) {
|
|
const {loadOverlayPatches}=await import('@deepseek-ai/dsh-app-boot');
|
|
const patches=loadOverlayPatches('dx-dsh',filename);
|
|
const matches=patches.flatMap(row=>row.insert??[]).filter(row=>row.id==='preset-standard');
|
|
if(matches.length!==1||matches[0].name!=='@deepseek-ai/dsh-agent-preset'||matches[0].config?.id!=='standard')
|
|
throw Error('Official Standard preset structure changed; cannot preserve legacy sessions.');
|
|
matches[0].id='preset-dx-task';
|
|
matches[0].config.id='dx-task';
|
|
return patches;
|
|
}
|
|
|
|
export async function prepareProfileDirectory(dir) {
|
|
// The official settings page writes the user patch. Application defaults
|
|
// belong to a bundle below it. Only host-owned model routes are refreshed;
|
|
// independent native providers and their credential references remain intact.
|
|
await mkdir(dir,{recursive:true});
|
|
const application=overlay();
|
|
const userPatch=path.join(dir,'cordis.patch.yml');
|
|
const previousApplication=await readOptionalModelMetadata(path.join(dir,'node_modules/@dx/dsh-policy/cordis.patch.yml'))??[];
|
|
const policyDir=path.join(dir,'node_modules','@dx','dsh-policy');
|
|
await mkdir(policyDir,{recursive:true});
|
|
await cp(path.join(root,'task-plugin'),path.join(dir,'node_modules','@dx','dsh-task'),{recursive:true});
|
|
// Old sessions retain their preset ID while loading the installed native composition.
|
|
await replaceJson(path.join(policyDir,'standard-compat.patch.yml'),
|
|
await standardCompatibilityPatch(require.resolve('@deepseek-ai/dsh-web-app/presets/standard.patch.yml')));
|
|
await replaceJson(path.join(policyDir,'package.json'),{name:'@dx/dsh-policy',version:VERSION,
|
|
private:true,dsh:{bundle:{patch:['./cordis.patch.yml','./standard-compat.patch.yml']}}});
|
|
await replaceJson(path.join(policyDir,'cordis.patch.yml'),application);
|
|
await replaceJson(path.join(dir,'package.json'),{private:true,type:'module',
|
|
dependencies:{'@dx/dsh-task':'file:'+path.join(root,'task-plugin'),'@dx/dsh-policy':'file:'+policyDir},
|
|
dsh:{profile:{bundles:['@deepseek-ai/dsh-base','@deepseek-ai/dsh-web-app','@dx/dsh-policy']}}});
|
|
const {loadProfileDirectory,composeEntries}=await import('@deepseek-ai/dsh-app-boot');
|
|
const profile=loadProfileDirectory('dx-dsh',dir,require.resolve('@deepseek-ai/dsh/package.json'),{userLayer:false});
|
|
const layers=profile.layers.map(layer=>layer.patches);
|
|
// Remove only the generated host route when testing whether a user binding
|
|
// actually applies. Use Harness semantics, including name assertions/inserts.
|
|
const withoutHost=profile.layers.map(layer=>layer.packageName==='@dx/dsh-policy'
|
|
?layer.patches.filter(row=>row.id!=='llm-pi-ai'):layer.patches);
|
|
let hostCredentialBinding;
|
|
const refresh=async(rows,legacy=false)=>{
|
|
const effective=composeEntries([...layers,rows]);
|
|
const credentials=modelEntry(effective,'credentials');
|
|
modelEntry(effective,'llm-pi-ai');modelEntry(effective,'agent-default-model');
|
|
let storedHostKey=false,savedKey;
|
|
if(credentials?.disabled!==true){
|
|
if(credentials?.name!=='@deepseek-ai/dsh-credentials-local')
|
|
throw Error('Cannot verify the configured model credential provider; startup refused.');
|
|
const {resolveDshHome}=await import('@deepseek-ai/dsh-home-paths');
|
|
const config=credentials.config??{};
|
|
const home=resolveDshHome(config.dshHome,{DSH_HOME:path.resolve(dir,'../..')});
|
|
const stored=await readOptionalModelMetadata(path.resolve(config.path??path.join(home,'.credentials.yaml')));
|
|
savedKey=stored?.version===undefined?stored?.DSH_API_KEY:stored?.refs?.DSH_API_KEY;
|
|
storedHostKey=typeof savedKey==='string'&&savedKey.length>0;
|
|
}
|
|
const boundDx=modelEntry(composeEntries([...withoutHost,rows]),'llm-pi-ai')?.config?.providers?.dx;
|
|
const next=refreshApplicationModels(rows,application,{legacy,storedHostKey,previousApplication,boundDx});
|
|
const actual=modelEntry(composeEntries([...layers,next]),'llm-pi-ai')?.config?.providers?.dx;
|
|
if(storedHostKey&&actual?.apiKeyEnv==='DSH_API_KEY'
|
|
&&(!boundDx||!isDeepStrictEqual(actual,boundDx)))
|
|
throw Error('Stored DSH_API_KEY has no provider binding after Harness composition; startup refused.');
|
|
if(!storedHostKey&&actual?.apiKeyEnv==='DSH_API_KEY'
|
|
&&!isDeepStrictEqual(actual,application.find(row=>row.id==='llm-pi-ai')?.config.providers.dx))
|
|
throw Error('Application model route did not match the current provider; startup refused.');
|
|
if(actual?.apiKeyEnv==='DSH_API_KEY')hostCredentialBinding={source:storedHostKey?'file':'env',
|
|
digest:createHash('sha256').update((storedHostKey?savedKey:process.env.DSH_API_KEY)??'').digest('hex')};
|
|
return next;
|
|
};
|
|
let prior;
|
|
try{prior=await readFile(userPatch,'utf8');}catch(error){if(error.code!=='ENOENT')throw error;}
|
|
if(prior!==undefined){
|
|
const {load}=require('js-yaml');
|
|
const rows=load(prior);
|
|
const legacy=Array.isArray(rows)&&rows.some(row=>Array.isArray(row?.insert)
|
|
&&row.insert.some(entry=>entry.id==='dx-task'&&entry.name==='@dx/dsh-task')
|
|
&&row.insert.some(entry=>entry.id==='preset-dx-task'));
|
|
const editable=new Set(['llm-pi-ai','llm-deepseek','agent-default-model']);
|
|
const userRows=legacy?rows.filter(row=>editable.has(row?.id)&&row.config):rows;
|
|
const next=Array.isArray(userRows)?await refresh(userRows,legacy):userRows;
|
|
if(legacy||JSON.stringify(next)!==JSON.stringify(rows)){
|
|
const digest=createHash('sha256').update(prior).digest('hex');
|
|
const backup=userPatch+(legacy?'.legacy-':'.models-')+digest+'.bak';
|
|
try{await writeFile(backup,prior,{flag:'wx'});}catch(error){
|
|
if(error.code!=='EEXIST'||await readFile(backup,'utf8')!==prior)throw error;
|
|
}
|
|
await replaceJson(userPatch,next);
|
|
}
|
|
}else if(application.some(row=>row.id==='llm-pi-ai')){
|
|
const next=await refresh([]);
|
|
await replaceJson(userPatch,next);
|
|
}
|
|
return {hostCredentialBinding};
|
|
}
|
|
|
|
export async function bootRuntime({announce=true} = {}) {
|
|
const installed = require('@deepseek-ai/dsh/package.json');
|
|
if (installed.version !== VERSION) throw Error('Unsupported Harness version: ' + installed.version);
|
|
const frontend = path.dirname(require.resolve('@deepseek-ai/dsh-web-frontend/package.json'));
|
|
await readFile(path.join(frontend,'dist/index.html'));
|
|
await readFile(path.join(root,'task-plugin/host.mjs'));
|
|
await readFile(path.join(root,'task-plugin/client.js'));
|
|
if (process.argv.includes('--doctor')) {
|
|
console.log(JSON.stringify({status:'ready',version:VERSION,frontend:'official',
|
|
tools:[...TASK_TOOLS,...FILE_TOOLS],presets:'official',fileTools:true,genericShell:true,node:process.version}));
|
|
return;
|
|
}
|
|
if (!process.env.DX_DSH_HOME || !process.env.DX_DSH_CONTEXT_FILE) throw Error('Task center context is required');
|
|
process.env.DSH_HOME = process.env.DX_DSH_HOME;
|
|
process.env.DSH_TELEMETRY_DISABLED = '1';
|
|
process.env.DX_DSH_WORKSPACE = path.join(process.env.DX_DSH_HOME,'workspace');
|
|
await mkdir(process.env.DX_DSH_WORKSPACE,{recursive:true});
|
|
const dir = path.join(process.env.DX_DSH_HOME,'profiles','dx-task');
|
|
const modelBinding=await prepareProfileDirectory(dir);
|
|
const {runProfile, INSTALL_ANCHOR} = await import('@deepseek-ai/dsh/profile-boot');
|
|
const {loadProfileDirectory,composeEntries} = await import('@deepseek-ai/dsh-app-boot');
|
|
const {createLaunchEnvironmentSnapshot} = await import('@deepseek-ai/dsh-launch-environment');
|
|
const profile = loadProfileDirectory('dx-dsh',dir,INSTALL_ANCHOR);
|
|
if (process.argv.includes('--inspect-profile')) {
|
|
const rows = composeEntries([...profile.layers.map(x=>x.patches),profile.patches]);
|
|
console.log(JSON.stringify({version:VERSION,enabled:rows.filter(x=>x.disabled!==true).map(x=>({id:x.id,name:x.name})),
|
|
presets:rows.filter(x=>x.id.startsWith('preset-') && x.disabled!==true).map(x=>x.config.id)}));
|
|
return;
|
|
}
|
|
const {ctx,shutdown} = await runProfile({profile:'dx-task',resolvedProfile:{profile,installAnchor:INSTALL_ANCHOR},
|
|
patchFiles:[],args:['--no-open','--host','127.0.0.1','--port','0'],
|
|
environment:createLaunchEnvironmentSnapshot([{source:'process',values:process.env}])});
|
|
await ctx.loader.await();
|
|
// Check the mounted service as well as its composition: an unexpected
|
|
// credential source must fail before exposing the runtime to the desktop.
|
|
if(modelBinding.hostCredentialBinding){
|
|
const actual=ctx.get('credentials')?await ctx.credentials.resolve('DSH_API_KEY')
|
|
:{source:'env',value:process.env.DSH_API_KEY};
|
|
if(actual?.source!==modelBinding.hostCredentialBinding.source||typeof actual?.value!=='string'
|
|
||createHash('sha256').update(actual.value).digest('hex')!==modelBinding.hostCredentialBinding.digest){
|
|
await shutdown.shutdown(1);
|
|
throw Error('Host model credential source changed during startup; startup refused.');
|
|
}
|
|
}
|
|
const names=ctx.tools.schemas().map(tool=>tool.name);
|
|
if(!TASK_TOOLS.every(name=>names.includes(name))) {
|
|
await shutdown.shutdown(1);
|
|
throw Error('The task-center plugin did not initialize.');
|
|
}
|
|
const base = `http://127.0.0.1:${ctx.webServer.port}/`;
|
|
if (announce) console.log('DX_DSH_READY '+JSON.stringify({url:ctx.connection.authenticatedUrl(base),version:VERSION}));
|
|
if (process.env.DX_DSH_PARENT_PIPE === '1') {
|
|
createInterface({input:process.stdin}).on('line',line=>{
|
|
if(line.length>100000)return;
|
|
try{
|
|
const command=JSON.parse(line);
|
|
if(command.type==='diagnose')ctx.emit('dx/diagnose-request',command);
|
|
else if(command.type==='diagnose_cancel')ctx.emit('dx/diagnose-cancel',command);
|
|
else if(command.type==='task_creation_result')ctx.emit('dx/task-creation-result',command);
|
|
else if(command.type==='task_lifecycle_result')ctx.emit('dx/task-lifecycle-result',command);
|
|
}catch{}
|
|
});
|
|
process.stdin.on('end',()=>void shutdown.shutdown(0));
|
|
}
|
|
return {ctx,shutdown};
|
|
}
|
|
|
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
bootRuntime().catch(error=>{console.error(error.stack || error.message);process.exitCode=1;});
|
|
}
|