import {mkdir,mkdtemp,writeFile,realpath,rm} from 'node:fs/promises'; import path from 'node:path'; import {Worker} from 'node:worker_threads'; import {defineTool} from '@deepseek-ai/dsh-tools'; export const fileToolNames=['read','read_image','glob','grep','working_directory','extract_zip']; const pending=[]; let running=0; function startPending(){ while(running<2&&pending.length){ const job=pending.shift(); if(job.signal.aborted){job.abort();continue;} running++; try{ const bytes=Uint8Array.from(job.bytes); job.worker=new Worker(new URL('./zip-worker.mjs',import.meta.url),{ workerData:{bytes,fflateUrl:import.meta.resolve('fflate')},transferList:[bytes.buffer],env:{},execArgv:[]}); let result,failure; job.worker.once('message',value=>{result=value;}); job.worker.once('error',error=>{failure=error;}); job.worker.once('exit',code=>{ running--;job.signal.removeEventListener('abort',job.abort); if(job.signal.aborted)job.reject(job.signal.reason??Error('ZIP extraction cancelled')); else if(failure||result?.error||code!==0||!result?.entries) job.reject(failure??Error(result?.error??'ZIP worker exited without a result')); else job.resolve(result.entries); startPending(); }); }catch(error){ running--;job.signal.removeEventListener('abort',job.abort);job.reject(error); } } } function decompress(bytes,signal){ signal.throwIfAborted(); return new Promise((resolve,reject)=>{ const job={bytes,signal,resolve,reject}; job.abort=()=>{ if(job.worker){void job.worker.terminate();return;} const index=pending.indexOf(job);if(index>=0)pending.splice(index,1); reject(signal.reason??Error('ZIP extraction cancelled')); }; signal.addEventListener('abort',job.abort,{once:true});pending.push(job);startPending(); }); } export function registerFileTools(ctx){ ctx.tools.register(defineTool({name:'extract_zip', description:'Extract a local or uploaded ZIP archive into a new folder, returning its absolute path and file names. Relative paths use the conversation working directory. output_directory optionally selects an existing parent folder; defaults to the conversation working directory. Never overwrites existing files. Read the returned paths to inspect extracted content. ZIP only; encrypted archives are unsupported.', parameters:{file_path:{type:'string',required:true},output_directory:{type:'string'}}, output:{schema:{type:'object',additionalProperties:true},render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]}, execute:async(args,exec)=>{ if(typeof args.file_path!=='string'||!args.file_path.trim())throw Error('file_path is required'); const cwd=exec.agent?ctx.workingDirectory.get(exec.agent.session):process.env.DX_DSH_WORKSPACE; const target=await ctx.fs.resolve(args.file_path,{cwd,signal:exec.signal}); const bytes=await ctx.fs.readBytes(target,exec.signal,64*1024*1024); const files=await decompress(bytes,exec.signal); exec.signal.throwIfAborted(); const parent=await realpath(path.resolve(cwd,args.output_directory||'.')); const directory=await mkdtemp(path.join(parent,'dsh-extracted-')); try{ for(const [name,data] of files){ exec.signal.throwIfAborted(); const output=path.resolve(directory,name.replaceAll('\\','/')); const relative=path.relative(directory,output); if(relative.startsWith('..')||path.isAbsolute(relative))throw Error('Unsafe ZIP entry path'); if(name.endsWith('/'))await mkdir(output,{recursive:true}); else{await mkdir(path.dirname(output),{recursive:true});await writeFile(output,data,{flag:'wx'});} } return {directory,files:files.slice(0,200).map(([name])=>name),total_entries:files.length,truncated:files.length>200}; }catch(error){ // Only this invocation's newly created temporary output is removed. if(path.dirname(directory)===parent&&path.basename(directory).startsWith('dsh-extracted-')) await rm(directory,{recursive:true,force:true}); throw error; } }})); }