nuwax-file-server 1.4.2 → 1.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/appConfig/index.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/env.development +4 -0
- package/dist/env.production +4 -0
- package/dist/routes/computerRoutes.js +1 -1
- package/dist/server.js +1 -1
- package/dist/utils/common/agentStoreUtils.js +2 -2
- package/dist/utils/computer/computerFileUtils.js +2 -2
- package/dist/utils/computer/computerUtils.js +12 -12
- package/dist/utils/computer/fsBrowserUtils.js +1 -0
- package/dist/utils/computer/workspaceContext.js +1 -0
- package/package.json +1 -1
package/dist/appConfig/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import E from"path";import n from"fs";import I from"os";import{fileURLToPath as T}from"url";import o from"dotenv";const L=E.dirname(T(import.meta.url));o.config();function p(){const e=process.env.LOG_BASE_DIR,_=E.join(I.tmpdir(),"nuwax-file-server","project_logs");if(!e)return _;try{return n.mkdirSync(e,{recursive:!0}),e}catch{try{n.mkdirSync(_,{recursive:!0})}catch{}return _}}const r=process.env.NODE_ENV||"development";function
|
|
1
|
+
import E from"path";import n from"fs";import I from"os";import{fileURLToPath as T}from"url";import o from"dotenv";const L=E.dirname(T(import.meta.url));o.config();function p(){const e=process.env.LOG_BASE_DIR,_=E.join(I.tmpdir(),"nuwax-file-server","project_logs");if(!e)return _;try{return n.mkdirSync(e,{recursive:!0}),e}catch{try{n.mkdirSync(_,{recursive:!0})}catch{}return _}}const r=process.env.NODE_ENV||"development";function R(e){const _=E.join(L,"..",`env.${e}`);if(n.existsSync(_))o.config({path:_}),console.log(`Environment configuration file env.${e} loaded`);else{const s=`Environment configuration file env.${e} does not exist, please create the corresponding environment configuration file and try again`;throw console.error(s),new Error(s)}}R(r);const O={NODE_ENV:r,PORT:parseInt(process.env.PORT),DEPLOYMENT_MODE:process.env.DEPLOYMENT_MODE||"docker-compose",FAST_RESTART_ENABLED:process.env.FAST_RESTART_ENABLED?.toLowerCase()==="true",INIT_PROJECT_NAME_REACT:process.env.INIT_PROJECT_NAME_REACT||"react-vite-template",INIT_PROJECT_NAME_VUE3:process.env.INIT_PROJECT_NAME_VUE3||"vue3-vite-template",INIT_PROJECT_DIR:process.env.INIT_PROJECT_DIR,PROJECT_SOURCE_DIR:process.env.PROJECT_SOURCE_DIR,DIST_TARGET_DIR:process.env.DIST_TARGET_DIR,UPLOAD_PROJECT_DIR:process.env.UPLOAD_PROJECT_DIR,MAX_BUILD_CONCURRENCY:process.env.MAX_BUILD_CONCURRENCY?parseInt(process.env.MAX_BUILD_CONCURRENCY,10):void 0,MAX_INLINE_FILE_SIZE_BYTES:process.env.MAX_INLINE_FILE_SIZE_BYTES?parseInt(process.env.MAX_INLINE_FILE_SIZE_BYTES,10):void 0,UPLOAD_MAX_FILE_SIZE_BYTES:process.env.UPLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_MAX_FILE_SIZE_BYTES,10):void 0,UPLOAD_ALLOWED_EXTENSIONS:process.env.UPLOAD_ALLOWED_EXTENSIONS?process.env.UPLOAD_ALLOWED_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],UPLOAD_SINGLE_FILE_SIZE_BYTES:process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES,10):void 0,DOWNLOAD_MAX_FILE_SIZE_BYTES:process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES,10):void 0,REQUEST_BODY_LIMIT:process.env.REQUEST_BODY_LIMIT,TRAVERSE_EXCLUDE_DIRS:process.env.TRAVERSE_EXCLUDE_DIRS?process.env.TRAVERSE_EXCLUDE_DIRS.split(",").map(e=>e.trim()).filter(Boolean):[],BACKUP_TRAVERSE_EXCLUDE_FILES:process.env.BACKUP_TRAVERSE_EXCLUDE_FILES?process.env.BACKUP_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],CONTENT_TRAVERSE_EXCLUDE_FILES:process.env.CONTENT_TRAVERSE_EXCLUDE_FILES?process.env.CONTENT_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],INLINE_IMAGE_EXTENSIONS:process.env.INLINE_IMAGE_EXTENSIONS?process.env.INLINE_IMAGE_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],TOP_LEVEL_NOISE_PATTERNS:process.env.TOP_LEVEL_NOISE_PATTERNS?process.env.TOP_LEVEL_NOISE_PATTERNS.split(",").map(e=>e.trim()).filter(Boolean):[],LOG_BASE_DIR:p(),LOG_LEVEL:process.env.LOG_LEVEL?process.env.LOG_LEVEL.toLowerCase():void 0,LOG_PREFIX_API:process.env.LOG_PREFIX_API,LOG_PREFIX_BUILD:process.env.LOG_PREFIX_BUILD,LOG_CONSOLE_ENABLED:typeof process.env.LOG_CONSOLE_ENABLED=="string"?process.env.LOG_CONSOLE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_ENABLED:typeof process.env.LOG_CACHE_ENABLED=="string"?process.env.LOG_CACHE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_DURATION:process.env.LOG_CACHE_DURATION?parseInt(process.env.LOG_CACHE_DURATION,10):void 0,LOG_CACHE_MAX_ENTRIES:process.env.LOG_CACHE_MAX_ENTRIES?parseInt(process.env.LOG_CACHE_MAX_ENTRIES,10):void 0,LOG_CACHE_MAX_FILE_SIZE:process.env.LOG_CACHE_MAX_FILE_SIZE?parseInt(process.env.LOG_CACHE_MAX_FILE_SIZE,10):void 0,DEV_SERVER_PORT_TIMEOUT:process.env.DEV_SERVER_PORT_TIMEOUT?parseInt(process.env.DEV_SERVER_PORT_TIMEOUT,10):void 0,DEV_SERVER_STOP_TIMEOUT:process.env.DEV_SERVER_STOP_TIMEOUT?parseInt(process.env.DEV_SERVER_STOP_TIMEOUT,10):void 0,DEV_SERVER_STOP_CHECK_INTERVAL:process.env.DEV_SERVER_STOP_CHECK_INTERVAL?parseInt(process.env.DEV_SERVER_STOP_CHECK_INTERVAL,10):void 0,DEV_SERVER_STOP_MAX_ATTEMPTS:process.env.DEV_SERVER_STOP_MAX_ATTEMPTS?parseInt(process.env.DEV_SERVER_STOP_MAX_ATTEMPTS,10):void 0,COMPUTER_WORKSPACE_DIR:process.env.COMPUTER_WORKSPACE_DIR,COMPUTER_LOG_DIR:process.env.COMPUTER_LOG_DIR,USERAPP_WORKSPACE_DIR:process.env.USERAPP_WORKSPACE_DIR,USERAPP_LOG_DIR:process.env.USERAPP_LOG_DIR,CLI_SERVICE_NAME:"nuwax-file-server",CLI_PID_DIR:process.env.CLI_PID_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server"):E.join("/tmp","nuwax-file-server")),CLI_PID_FILE:"server.pid",CLI_STOP_TIMEOUT:process.env.CLI_STOP_TIMEOUT?parseInt(process.env.CLI_STOP_TIMEOUT,10):3e4,CLI_CHECK_INTERVAL:process.env.CLI_CHECK_INTERVAL?parseInt(process.env.CLI_CHECK_INTERVAL,10):500,CLI_LOG_DIR:process.env.CLI_LOG_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server","logs"):E.join("/tmp","nuwax-file-server","logs")),CLI_IS_WINDOWS:process.platform==="win32",GIT_DEFAULT_AUTHOR_NAME:process.env.GIT_DEFAULT_AUTHOR_NAME||"Nuwax File Server",GIT_DEFAULT_AUTHOR_EMAIL:process.env.GIT_DEFAULT_AUTHOR_EMAIL||"git@nuwax.local",GIT_AUTO_GITIGNORE:process.env.GIT_AUTO_GITIGNORE?.toLowerCase()!=="false",GIT_GITIGNORE_ENTRIES:process.env.GIT_GITIGNORE_ENTRIES?process.env.GIT_GITIGNORE_ENTRIES.split("|").map(e=>e.trim()).filter(Boolean):["node_modules/",".pnpm-store/","dist/","build/",".idea/",".vscode/",".DS_Store",".npmrc",".agents/",".claude/",".opencode/",".codex/",".tmp/",".logs/","pnpm-lock.yaml","yarn.lock","package-lock.json"],GIT_ENABLED:process.env.GIT_ENABLED?.toLowerCase()==="true",GIT_USE_NATIVE:process.env.GIT_USE_NATIVE?.toLowerCase()!=="false",BASH_PATH:process.env.BASH_PATH||"",ZIP_WORKSPACE_EXCLUDE:process.env.ZIP_WORKSPACE_EXCLUDE?process.env.ZIP_WORKSPACE_EXCLUDE.split(",").map(e=>e.trim()).filter(Boolean):[".git",".tmp",".claude",".agents",".codex",".opencode",".logs",".npmrc","__pycache__","node_modules","dist","pnpm-lock.yaml","yarn.lock","package-lock.json"]};export default O;
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.4.2",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
|
|
2
|
+
import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.4.3",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
|
package/dist/env.development
CHANGED
|
@@ -89,6 +89,10 @@ COMPUTER_WORKSPACE_DIR=/app/computer-project-workspace
|
|
|
89
89
|
# computer 日志目录
|
|
90
90
|
COMPUTER_LOG_DIR=/app/logs/computer_logs
|
|
91
91
|
|
|
92
|
+
# userapp 工作目录
|
|
93
|
+
USERAPP_WORKSPACE_DIR=/home/user
|
|
94
|
+
USERAPP_LOG_DIR=/home/user/logs
|
|
95
|
+
|
|
92
96
|
# Git 版本管理配置
|
|
93
97
|
GIT_DEFAULT_AUTHOR_NAME=Nuwax File Server
|
|
94
98
|
GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
|
package/dist/env.production
CHANGED
|
@@ -89,6 +89,10 @@ COMPUTER_WORKSPACE_DIR=/app/computer-project-workspace
|
|
|
89
89
|
# computer 日志目录
|
|
90
90
|
COMPUTER_LOG_DIR=/app/logs/computer_logs
|
|
91
91
|
|
|
92
|
+
# userapp 工作目录
|
|
93
|
+
USERAPP_WORKSPACE_DIR=/home/user
|
|
94
|
+
USERAPP_LOG_DIR=/home/user/logs
|
|
95
|
+
|
|
92
96
|
# Git 版本管理配置
|
|
93
97
|
GIT_DEFAULT_AUTHOR_NAME=Nuwax File Server
|
|
94
98
|
GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import E from"express";import z from"multer";import y from"fs";import j from"path";import{ValidationError as A,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as d}from"../utils/log/logUtils.js";import b from"../appConfig/index.js";import{createWorkspace as C,pushSkillsToWorkspace as O,initProjectTemplate as x,installProjectDependencies as v,executeCommand as q,deleteWorkspace as M,zipWorkspace as R,buildAgentPackage as H,cleanupBuildArtifacts as _}from"../utils/computer/computerUtils.js";import{getFileList as B,resolveExistingFile as L,searchFiles as W,updateFiles as J,uploadFile as V,uploadFiles as G,generateFile as K,downloadAllFiles as Z,getLatestLogs as X,importProject as Y}from"../utils/computer/computerFileUtils.js";const S=E.Router(),g=z({storage:z.diskStorage({destination:(s,r,t)=>{try{const e=b.COMPUTER_WORKSPACE_DIR;if(!e)return t(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const a=s.body?.userId||"unknown",o=s.body?.cId||"unknown",i=j.join(e,String(a),String(o),".tmp");y.existsSync(i)||y.mkdirSync(i,{recursive:!0}),t(null,i)}catch(e){t(e)}},filename:(s,r,t)=>{const e=j.extname(r.originalname)||".zip",a=j.basename(r.originalname,e),o=`${Date.now()}_${Math.round(Math.random()*1e6)}`;t(null,`${a}_${o}${e}`)}}),limits:{fileSize:b.UPLOAD_MAX_FILE_SIZE_BYTES}});function Q(s,r,t,e){if(s&&s.name==="MulterError"||s&&(s.name==="ValidationError"||s instanceof A))return e(s);e(s)}const ee=[{path:"/create-workspace",method:"post",middleware:g.single("file"),handler:c(async(s,r)=>{const{userId:t,cId:e}=s.body||{},a=s.file||null,o=`computer:${t}:${e}`;d(o,"INFO","Create workspace request",{userId:t,cId:e,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await C(t,e,a);r.status(200).json({success:!0,...i})})},{path:"/create-workspace-v2",method:"post",middleware:g.single("file"),handler:c(async(s,r)=>{const{userId:t,cId:e,agentId:a,skillUrls:o,skillUrlMap:i,skillNames:l,updateSkillNames:n,mcpServersConfig:u,hooksConfig:p,permissionsConfig:f,hookScripts:m}=s.body||{},w=s.file||null,D=`computer:${t}:${e}`;let k=o;if(typeof o=="string")try{k=JSON.parse(o)}catch{k=[o]}let I=i;if(typeof i=="string")try{I=JSON.parse(i)}catch{I=null}let N=l;if(typeof l=="string")try{const h=JSON.parse(l);N=Array.isArray(h)?h:[l]}catch{N=l.split(",").map(h=>h.trim()).filter(Boolean)}let $=n;if(typeof n=="string")try{const h=JSON.parse(n);$=Array.isArray(h)?h:[n]}catch{$=n.split(",").map(h=>h.trim()).filter(Boolean)}let F=m;if(typeof m=="string")try{F=JSON.parse(m)}catch{F=null}const P=Array.isArray(k)?k.length:0,U=I&&typeof I=="object"&&!Array.isArray(I)?Object.keys(I).length:0;d(D,"INFO","Create workspace v2 request",{userId:t,cId:e,agentId:a,hasFile:!!w,fileName:w?.originalname,fileSize:w?.size,skillUrlsCount:P,skillUrlMapCount:U,skillNamesCount:Array.isArray(N)?N.length:0,updateSkillNamesCount:Array.isArray($)?$.length:0,hasMcpServersConfig:!!u,hasHooksConfig:!!p,hasPermissionsConfig:!!f,hookScriptsCount:Array.isArray(F)?F.length:0});const T=await C(t,e,w,k,u,f,p,F,a,N,$,I);r.status(200).json({success:!0,...T})})},{path:"/push-skills-to-workspace",method:"post",middleware:g.single("file"),handler:c(async(s,r)=>{const{userId:t,cId:e}=s.body||{},a=s.file||null,o=`computer:${t}:${e}`;d(o,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:t,cId:e,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await O(t,e,a);r.status(200).json({success:!0,...i})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:g.single("file"),handler:c(async(s,r)=>{const{userId:t,cId:e,agentId:a,skillUrls:o}=s.body||{},i=s.file||null,l=`computer:${t}:${e}`;let n=o;if(typeof o=="string")try{const p=JSON.parse(o);n=Array.isArray(p)?p:[o]}catch{n=[o]}d(l,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:t,cId:e,agentId:a,hasFile:!!i,fileName:i?.originalname,fileSize:i?.size,skillUrlsCount:Array.isArray(n)?n.length:0});const u=await O(t,e,i,n,a);r.status(200).json({success:!0,...u})})},{path:"/get-file-list",method:"get",handler:c(async(s,r)=>{const{userId:t,cId:e,proxyPath:a,customTargetDir:o,relativePath:i,recursive:l}=s.query,n=await B(t,e,a,o,i,l);r.status(200).json({success:!0,...n})})},{path:"/resolve-file",method:"get",handler:c(async(s,r)=>{const{userId:t,cId:e,proxyPath:a,customTargetDir:o,filePath:i}=s.query,l=await L(t,e,i,a,o);r.status(200).json({success:!0,...l})})},{path:"/search-files",method:"get",handler:c(async(s,r)=>{const{userId:t,cId:e,proxyPath:a,customTargetDir:o,relativePath:i,kw:l,limit:n,maxVisit:u,timeoutMs:p}=s.query,f=await W(t,e,a,l,o,i,n,u,p);r.status(200).json({success:!0,...f})})},{path:"/files-update",method:"post",handler:c(async(s,r)=>{const{userId:t,cId:e,files:a,customTargetDir:o}=s.body||{},i=`computer:${t}:${e}`;d(i,"INFO","Files update",{userId:t,cId:e,filesCount:a?a.length:0}),a&&Array.isArray(a)&&a.forEach(n=>{if(n&&typeof n.contents=="string"&&n.contents)try{n.contents=decodeURIComponent(n.contents)}catch(u){d(i,"WARN","Decode file content failed",{fileName:n.name,error:u.message})}});const l=await J(t,e,a,o);r.status(200).json(l)})},{path:"/upload-file",method:"post",middleware:g.single("file"),handler:c(async(s,r)=>{const{userId:t,cId:e,filePath:a,customTargetDir:o}=s.body||{},i=s.file,l=`computer:${t}:${e}`;d(l,"INFO","Upload single file",{userId:t,cId:e,filePath:a});const u={buffer:await y.promises.readFile(i.path),originalname:i.originalname,mimetype:i.mimetype,size:i.size};try{const p=await V(t,e,u,a,o);r.status(200).json(p)}finally{y.existsSync(i.path)&&await y.promises.unlink(i.path)}})},{path:"/generate-file",method:"post",handler:c(async(s,r)=>{const{userId:t,cId:e,fileName:a,content:o,customTargetDir:i}=s.body||{},l=`computer:${t}:${e}`;d(l,"INFO","Generate file request",{userId:t,cId:e,fileName:a,contentLength:typeof o=="string"?o.length:0});const n=await K(t,e,a,o,i);r.status(200).json(n)})},{path:"/import-project",method:"post",middleware:g.single("file"),handler:c(async(s,r)=>{const{userId:t,cId:e,customTargetDir:a}=s.body||{},o=s.file,i=`computer:${t}:${e}`;if(d(i,"INFO","Import project request",{userId:t,cId:e,fileName:o?.originalname,fileSize:o?.size}),!o)throw new A("file is required",{field:"file"});const l=await Y(t,e,o,a);r.status(200).json(l)})},{path:"/upload-files",method:"post",middleware:g.array("files"),handler:c(async(s,r)=>{const{userId:t,cId:e,filePaths:a,customTargetDir:o}=s.body||{},i=s.files||[],l=`computer:${t}:${e}`,n=Array.isArray(a)?a:typeof a=="string"?[a]:a;d(l,"INFO","Batch upload files request",{userId:t,cId:e,filesCount:i.length,filePathsCount:Array.isArray(n)?n.length:0});const u=[],p=[];try{for(const m of i){p.push(m.path);const w=await y.promises.readFile(m.path);u.push({buffer:w,originalname:m.originalname,mimetype:m.mimetype,size:m.size})}const f=await G(t,e,u,n,o);r.status(200).json(f)}finally{for(const f of p)if(y.existsSync(f))try{await y.promises.unlink(f)}catch(m){d(l,"WARN","Clean temporary file failed",{tempPath:f,error:m.message})}}})},{path:"/install-project",method:"post",handler:c(async(s,r)=>{const{userId:t,cId:e,programmingLanguage:a}=s.body||{},o=`computer:${t}:${e}`;d(o,"INFO","Install project request",{userId:t,cId:e,programmingLanguage:a});const i=await v(t,e,a);r.status(200).json({success:!0,...i})})},{path:"/init-project-template",method:"post",middleware:g.single("file"),handler:c(async(s,r)=>{const{userId:t,cId:e,enableGit:a}=s.body||{},o=s.file||null,i=`computer:${t}:${e}`;d(i,"INFO","Init project template request",{userId:t,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size,enableGit:a});const l=await x(t,e,o,a);r.status(200).json({success:!0,...l})})},{path:"/download-all-files",method:"get",handler:c(async(s,r)=>{const{userId:t,cId:e,customTargetDir:a}=s.query||{},o=`computer:${t}:${e}`;d(o,"INFO","Download all files request",{userId:t,cId:e});const{archive:i,zipFileName:l}=await Z(t,e,a);r.setHeader("Content-Type","application/zip");const n=encodeURIComponent(l);r.setHeader("Content-Disposition",`attachment; filename="${n}"; filename*=UTF-8''${n}`),i.on("error",u=>{r.destroy(u)}),i.pipe(r),i.finalize()})},{path:"/execute-command",method:"post",handler:c(async(s,r)=>{const{userId:t,cId:e,command:a}=s.body||{},o=`computer:${t}:${e}`;d(o,"INFO","Execute command request",{userId:t,cId:e,command:a});const i=await q(t,e,a);r.status(200).json({success:!0,...i})})},{path:"/delete-workspace",method:"post",handler:c(async(s,r)=>{const{userId:t,cId:e}=s.body||{},a=`computer:${t}:${e}`;d(a,"INFO","Delete workspace request",{userId:t,cId:e});const o=await M(t,e);r.status(200).json({success:!0,...o})})},{path:"/get-logs",method:"get",handler:c(async(s,r)=>{const{userId:t,cId:e,tailLines:a}=s.query,o=a?parseInt(a,10):200,i=Number.isFinite(o)&&o>0?o:200,l=await X(t,e,i);r.status(200).json(l)})},{path:"/zip-workspace",method:"post",handler:c(async(s,r)=>{const{userId:t,cId:e,excludeDirs:a}=s.body||{},o=`computer:${t}:${e}`;d(o,"INFO","Zip workspace request",{userId:t,cId:e,hasExcludeDirs:!!a});const{archive:i,zipFileName:l}=await R(t,e,a||null);r.setHeader("Content-Type","application/zip");const n=encodeURIComponent(l);r.setHeader("Content-Disposition",`attachment; filename="${n}"; filename*=UTF-8''${n}`),i.on("error",u=>{r.destroy(u)}),i.pipe(r),i.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(s,r)=>{const{userId:t,cId:e,agentId:a,version:o}=s.body||{},i=`computer:${t}:${e}`;d(i,"INFO","Build agent package request",{userId:t,cId:e,agentId:a,version:o});const l=await H(t,e,a,o);r.status(200).json({success:!0,...l})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(s,r)=>{const{userId:t,cId:e}=s.body||{},a=`computer:${t}:${e}`;d(a,"INFO","Cleanup build artifacts request",{userId:t,cId:e});const o=await _(t,e);r.status(200).json({success:!0,...o})})}];ee.forEach(s=>{if(s.middleware)S[s.method](s.path,s.middleware,s.handler);else if(s.customHandler){const r=[];s.handler&&r.push(s.handler),s.decodeMiddleware&&r.push(s.decodeMiddleware),r.push(Q),r.push(s.customHandler),S[s.method](s.path,...r)}else S[s.method](s.path,s.handler)});export default S;
|
|
1
|
+
import x from"express";import v from"multer";import g from"fs";import A from"path";import{ValidationError as b,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import z from"../appConfig/index.js";import{createWorkspace as P,pushSkillsToWorkspace as O,initProjectTemplate as R,installProjectDependencies as _,executeCommand as M,deleteWorkspace as H,zipWorkspace as L,buildAgentPackage as W,cleanupBuildArtifacts as B}from"../utils/computer/computerUtils.js";import{getFileList as J,resolveExistingFile as K,searchFiles as V,updateFiles as G,uploadFile as Z,uploadFiles as X,generateFile as Y,downloadAllFiles as Q,getLatestLogs as q,importProject as ee}from"../utils/computer/computerFileUtils.js";import{resolveServiceContext as p}from"../utils/computer/workspaceContext.js";import{listFsRoots as te,listFsChildren as se}from"../utils/computer/fsBrowserUtils.js";const j=x.Router(),I=v({storage:v.diskStorage({destination:(e,i,s)=>{try{const t=typeof e.headers["x-service-type"]=="string"?e.headers["x-service-type"].trim().toLowerCase():"",a=typeof e.headers["x-app-id"]=="string"?e.headers["x-app-id"].trim():"";let o;if(t==="userapp"&&a){const n=z.USERAPP_WORKSPACE_DIR;if(!n)return s(new Error("USERAPP_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));o=A.join(n,String(a),".tmp")}else{const n=z.COMPUTER_WORKSPACE_DIR;if(!n)return s(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const r=e.body?.userId||"unknown",l=e.body?.cId||"unknown";o=A.join(n,String(r),String(l),".tmp")}g.existsSync(o)||g.mkdirSync(o,{recursive:!0}),s(null,o)}catch(t){s(t)}},filename:(e,i,s)=>{const t=A.extname(i.originalname)||".zip",a=A.basename(i.originalname,t),o=`${Date.now()}_${Math.round(Math.random()*1e6)}`;s(null,`${a}_${o}${t}`)}}),limits:{fileSize:z.UPLOAD_MAX_FILE_SIZE_BYTES}});function ae(e,i,s,t){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof b))return t(e);t(e)}const oe=[{path:"/create-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,i)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=p(e),n=`computer:${s}:${t}`;u(n,"INFO","Create workspace request",{userId:s,cId:t,serviceType:o.serviceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const r=await P(s,t,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,o);i.status(200).json({success:!0,...r})})},{path:"/create-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,i)=>{const{userId:s,cId:t,agentId:a,skillUrls:o,skillUrlMap:n,skillNames:r,updateSkillNames:l,mcpServersConfig:d,hooksConfig:f,permissionsConfig:m,hookScripts:h}=e.body||{},k=e.file||null,C=p(e),T=`computer:${s}:${t}`;let N=o;if(typeof o=="string")try{N=JSON.parse(o)}catch{N=[o]}let w=n;if(typeof n=="string")try{w=JSON.parse(n)}catch{w=null}let S=r;if(typeof r=="string")try{const y=JSON.parse(r);S=Array.isArray(y)?y:[r]}catch{S=r.split(",").map(y=>y.trim()).filter(Boolean)}let F=l;if(typeof l=="string")try{const y=JSON.parse(l);F=Array.isArray(y)?y:[l]}catch{F=l.split(",").map(y=>y.trim()).filter(Boolean)}let $=h;if(typeof h=="string")try{$=JSON.parse(h)}catch{$=null}const D=Array.isArray(N)?N.length:0,E=w&&typeof w=="object"&&!Array.isArray(w)?Object.keys(w).length:0;u(T,"INFO","Create workspace v2 request",{userId:s,cId:t,agentId:a,serviceType:C.serviceType,appId:C.appId,hasFile:!!k,fileName:k?.originalname,fileSize:k?.size,skillUrlsCount:D,skillUrlMapCount:E,skillNamesCount:Array.isArray(S)?S.length:0,updateSkillNamesCount:Array.isArray(F)?F.length:0,hasMcpServersConfig:!!d,hasHooksConfig:!!f,hasPermissionsConfig:!!m,hookScriptsCount:Array.isArray($)?$.length:0});const U=await P(s,t,k,N,d,m,f,$,a,S,F,w,C);i.status(200).json({success:!0,...U})})},{path:"/push-skills-to-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,i)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=p(e),n=`computer:${s}:${t}`;u(n,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:s,cId:t,serviceType:o.serviceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const r=await O(s,t,a,void 0,void 0,o);i.status(200).json({success:!0,...r})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,i)=>{const{userId:s,cId:t,agentId:a,skillUrls:o}=e.body||{},n=e.file||null,r=p(e),l=`computer:${s}:${t}`;let d=o;if(typeof o=="string")try{const m=JSON.parse(o);d=Array.isArray(m)?m:[o]}catch{d=[o]}u(l,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:s,cId:t,agentId:a,serviceType:r.serviceType,appId:r.appId,hasFile:!!n,fileName:n?.originalname,fileSize:n?.size,skillUrlsCount:Array.isArray(d)?d.length:0});const f=await O(s,t,n,d,a,r);i.status(200).json({success:!0,...f})})},{path:"/fs/roots",method:"get",handler:c(async(e,i)=>{const s=await te();i.status(200).json({success:!0,...s})})},{path:"/fs/children",method:"get",handler:c(async(e,i)=>{const{path:s}=e.query,t=await se(s);i.status(200).json({success:!0,...t})})},{path:"/get-file-list",method:"get",handler:c(async(e,i)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:n,recursive:r}=e.query,l=await J(s,t,a,o,n,r,p(e));i.status(200).json({success:!0,...l})})},{path:"/resolve-file",method:"get",handler:c(async(e,i)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,filePath:n}=e.query,r=await K(s,t,n,a,o,p(e));i.status(200).json({success:!0,...r})})},{path:"/search-files",method:"get",handler:c(async(e,i)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:n,kw:r,limit:l,maxVisit:d,timeoutMs:f}=e.query,m=await V(s,t,a,r,o,n,l,d,f,p(e));i.status(200).json({success:!0,...m})})},{path:"/files-update",method:"post",handler:c(async(e,i)=>{const{userId:s,cId:t,files:a,customTargetDir:o}=e.body||{},n=`computer:${s}:${t}`;u(n,"INFO","Files update",{userId:s,cId:t,filesCount:a?a.length:0}),a&&Array.isArray(a)&&a.forEach(l=>{if(l&&typeof l.contents=="string"&&l.contents)try{l.contents=decodeURIComponent(l.contents)}catch(d){u(n,"WARN","Decode file content failed",{fileName:l.name,error:d.message})}});const r=await G(s,t,a,o,p(e));i.status(200).json(r)})},{path:"/upload-file",method:"post",middleware:I.single("file"),handler:c(async(e,i)=>{const{userId:s,cId:t,filePath:a,customTargetDir:o}=e.body||{},n=e.file,r=`computer:${s}:${t}`;u(r,"INFO","Upload single file",{userId:s,cId:t,filePath:a});const d={buffer:await g.promises.readFile(n.path),originalname:n.originalname,mimetype:n.mimetype,size:n.size};try{const f=await Z(s,t,d,a,o,p(e));i.status(200).json(f)}finally{g.existsSync(n.path)&&await g.promises.unlink(n.path)}})},{path:"/generate-file",method:"post",handler:c(async(e,i)=>{const{userId:s,cId:t,fileName:a,content:o,customTargetDir:n}=e.body||{},r=`computer:${s}:${t}`;u(r,"INFO","Generate file request",{userId:s,cId:t,fileName:a,contentLength:typeof o=="string"?o.length:0});const l=await Y(s,t,a,o,n,p(e));i.status(200).json(l)})},{path:"/import-project",method:"post",middleware:I.single("file"),handler:c(async(e,i)=>{const{userId:s,cId:t,customTargetDir:a}=e.body||{},o=e.file,n=`computer:${s}:${t}`;if(u(n,"INFO","Import project request",{userId:s,cId:t,fileName:o?.originalname,fileSize:o?.size}),!o)throw new b("file is required",{field:"file"});const r=await ee(s,t,o,a,p(e));i.status(200).json(r)})},{path:"/upload-files",method:"post",middleware:I.array("files"),handler:c(async(e,i)=>{const{userId:s,cId:t,filePaths:a,customTargetDir:o}=e.body||{},n=e.files||[],r=`computer:${s}:${t}`,l=Array.isArray(a)?a:typeof a=="string"?[a]:a;u(r,"INFO","Batch upload files request",{userId:s,cId:t,filesCount:n.length,filePathsCount:Array.isArray(l)?l.length:0});const d=[],f=[];try{for(const h of n){f.push(h.path);const k=await g.promises.readFile(h.path);d.push({buffer:k,originalname:h.originalname,mimetype:h.mimetype,size:h.size})}const m=await X(s,t,d,l,o,p(e));i.status(200).json(m)}finally{for(const m of f)if(g.existsSync(m))try{await g.promises.unlink(m)}catch(h){u(r,"WARN","Clean temporary file failed",{tempPath:m,error:h.message})}}})},{path:"/install-project",method:"post",handler:c(async(e,i)=>{const{userId:s,cId:t,programmingLanguage:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Install project request",{userId:s,cId:t,programmingLanguage:a});const n=await _(s,t,a,p(e));i.status(200).json({success:!0,...n})})},{path:"/init-project-template",method:"post",middleware:I.single("file"),handler:c(async(e,i)=>{const{userId:s,cId:t,enableGit:a}=e.body||{},o=e.file||null,n=`computer:${s}:${t}`;u(n,"INFO","Init project template request",{userId:s,cId:t,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size,enableGit:a});const r=await R(s,t,o,a,p(e));i.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:c(async(e,i)=>{const{userId:s,cId:t,customTargetDir:a}=e.query||{},o=`computer:${s}:${t}`;u(o,"INFO","Download all files request",{userId:s,cId:t});const{archive:n,zipFileName:r}=await Q(s,t,a,p(e));i.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);i.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",d=>{i.destroy(d)}),n.pipe(i),n.finalize()})},{path:"/execute-command",method:"post",handler:c(async(e,i)=>{const{userId:s,cId:t,command:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Execute command request",{userId:s,cId:t,command:a});const n=await M(s,t,a,p(e));i.status(200).json({success:!0,...n})})},{path:"/delete-workspace",method:"post",handler:c(async(e,i)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Delete workspace request",{userId:s,cId:t});const o=await H(s,t,p(e));i.status(200).json({success:!0,...o})})},{path:"/get-logs",method:"get",handler:c(async(e,i)=>{const{userId:s,cId:t,tailLines:a}=e.query,o=a?parseInt(a,10):200,n=Number.isFinite(o)&&o>0?o:200,r=await q(s,t,n,p(e));i.status(200).json(r)})},{path:"/zip-workspace",method:"post",handler:c(async(e,i)=>{const{userId:s,cId:t,excludeDirs:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Zip workspace request",{userId:s,cId:t,hasExcludeDirs:!!a});const{archive:n,zipFileName:r}=await L(s,t,a||null,p(e));i.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);i.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",d=>{i.destroy(d)}),n.pipe(i),n.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(e,i)=>{const{userId:s,cId:t,agentId:a,version:o}=e.body||{},n=`computer:${s}:${t}`;u(n,"INFO","Build agent package request",{userId:s,cId:t,agentId:a,version:o});const r=await W(s,t,a,o,p(e));i.status(200).json({success:!0,...r})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(e,i)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Cleanup build artifacts request",{userId:s,cId:t});const o=await B(s,t,p(e));i.status(200).json({success:!0,...o})})}];oe.forEach(e=>{if(e.middleware)j[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const i=[];e.handler&&i.push(e.handler),e.decodeMiddleware&&i.push(e.decodeMiddleware),i.push(ae),i.push(e.customHandler),j[e.method](e.path,...i)}else j[e.method](e.path,e.handler)});export default j;
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import A from"express";import"json-bigint";import C from"swagger-ui-express";import R from"./config/swagger.js";import
|
|
1
|
+
import A from"express";import"json-bigint";import C from"swagger-ui-express";import R from"./config/swagger.js";import a from"./appConfig/index.js";import{log as c,logger as S}from"./utils/log/logUtils.js";import w from"./utils/log/logCacheManager.js";import{errorHandler as P,notFoundHandler as y}from"./utils/error/errorHandler.js";import N from"./routes/router.js";import{cleanupInitProjectOnStartup as D}from"./utils/project/initProjectCleanupUtils.js";import{resolveServiceContext as H,resolveWorkspaceDir as F}from"./utils/computer/workspaceContext.js";import{startScheduler as v,stopScheduler as x}from"./scheduler/pnpmPruneScheduler.js";import f from"path";const o=A();o.use(A.json({limit:a.REQUEST_BODY_LIMIT,reviver:(t,e)=>typeof e=="number"&&!Number.isSafeInteger(e)?e.toString():e})),o.use(A.urlencoded({extended:!0,limit:a.REQUEST_BODY_LIMIT})),o.use(S);const T=t=>{let e=t;try{for(;;){const n=decodeURIComponent(e);if(n===e)break;e=n}}catch{}return e};o.use("/api/page/static/:projectId",(t,e,n)=>{const{projectId:d}=t.params;let s=t.path||"/";if(!d||s==="/")return e.status(404).send("Not Found");const r=t.headers.origin,l=r||"*";if(e.header("Access-Control-Allow-Origin",l),e.header("Access-Control-Allow-Methods","HEAD,GET,POST,PUT,DELETE,OPTIONS"),e.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Fragment"),e.header("Access-Control-Expose-Headers","Content-Type"),r&&(e.header("Access-Control-Allow-Credentials","true"),e.header("Vary","Origin")),t.method==="OPTIONS")return e.sendStatus(200);s=s.replace(/^\/+/,"");const u=T(s),p=f.join(a.PROJECT_SOURCE_DIR,d,u),i={"Access-Control-Allow-Origin":l,"Access-Control-Allow-Methods":"HEAD,GET,POST,PUT,DELETE,OPTIONS","Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Fragment"};return r&&(i["Access-Control-Allow-Credentials"]="true",i.Vary="Origin"),e.sendFile(p,{dotfiles:"allow",headers:i},h=>{if(h)return n()})}),o.use("/api/computer/static/:userId/:cId",(t,e,n)=>{const{userId:d,cId:s}=t.params;let r=t.path||"/";if(!d||!s||r==="/")return e.status(404).send("Not Found");const l=t.headers.origin,u=l||"*";if(e.header("Access-Control-Allow-Origin",u),e.header("Access-Control-Allow-Methods","HEAD,GET,POST,PUT,DELETE,OPTIONS"),e.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Range, If-Range"),e.header("Access-Control-Expose-Headers","Content-Type, Content-Length, Content-Range, Accept-Ranges, ETag, Last-Modified"),l&&(e.header("Access-Control-Allow-Credentials","true"),e.header("Vary","Origin")),t.method==="OPTIONS")return e.sendStatus(200);r=r.replace(/^\/+/,"");const p=T(r),{customTargetDir:i}=t.query,h=H(t),E=i&&i.trim()?f.join(i,p):f.join(F(h,d,s),p),m={"Access-Control-Allow-Origin":u,"Access-Control-Allow-Methods":"HEAD,GET,POST,PUT,DELETE,OPTIONS","Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Range, If-Range","Access-Control-Expose-Headers":"Content-Type, Content-Length, Content-Range, Accept-Ranges, ETag, Last-Modified"};return l&&(m["Access-Control-Allow-Credentials"]="true",m.Vary="Origin"),e.sendFile(E,{dotfiles:"allow",headers:m},I=>{if(I)return n()})}),o.use("/api-docs",C.serve,C.setup(R,{customCss:".swagger-ui .topbar { display: none }",customSiteTitle:"nuwax-file-server API Documentation"})),o.use(N),o.use(y),o.use(P);const g=o.listen(a.PORT,async()=>{c("default","INFO",`Server is running on port ${a.PORT} (${a.NODE_ENV} mode)`),await D(a);try{v()}catch(t){c("default","ERROR",`pnpm prune scheduled task failed to start: ${t.message}`)}});g.timeout=6e5,g.keepAliveTimeout=61e4,g.headersTimeout=62e4;const O=t=>{c("default","INFO",`Received ${t} signal, preparing graceful exit...`),x();try{w.destroy(),c("default","INFO","Log cache manager cleared")}catch(e){c("default","ERROR",`Failed to clear log cache manager: ${e.message}`)}g.close(()=>{c("default","INFO","Server closed"),process.exit(0)}),setTimeout(()=>{c("default","ERROR","Force exit (timeout)"),process.exit(1)},3e4)};process.on("SIGTERM",()=>O("SIGTERM")),process.on("SIGINT",()=>O("SIGINT"));
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import r from"fs";import
|
|
2
|
-
`,"utf8")}async function
|
|
1
|
+
import r from"fs";import a from"path";import"../../appConfig/index.js";import{log as m}from"../log/logUtils.js";import{ValidationError as l}from"../error/errorHandler.js";import{resolveWorkspaceRoot as S}from"../computer/workspaceContext.js";const p=".dynamic_add.lock",k=".sync.lock",h=5*60*1e3;function y(e,t,o=null){const i=S(o);if(!i)throw new l("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return o?.isUserApp?a.join(i,".agent-store",String(t)):a.join(i,String(e),".agent-store",String(t))}async function A(e,t,o,i=null){const s=y(e,t,i);if(i?.isUserApp&&!r.existsSync(a.dirname(s)))throw new l(`userapp agent-store mount does not exist: ${a.dirname(s)}`,{field:"USERAPP_WORKSPACE_DIR"});const n=a.join(s,"skills"),c=a.join(s,"agents");return await r.promises.mkdir(n,{recursive:!0}),await r.promises.mkdir(c,{recursive:!0}),m(o||"agent-store","DEBUG","Agent store dirs ready",{agentStorePath:s,skillsDir:n,agentsDir:c}),{agentStorePath:s,skillsDir:n,agentsDir:c}}async function E(e,t){await r.promises.mkdir(e,{recursive:!0});const o=a.join(e,k);try{const i=await r.promises.open(o,"wx");return await i.writeFile(`${process.pid}:${Date.now()}`),await i.close(),{acquired:!0,lockPath:o}}catch(i){if(i&&i.code==="EEXIST"){try{const s=await r.promises.stat(o),n=Date.now()-s.mtimeMs;if(n>h){await r.promises.rm(o,{force:!0});const c=await r.promises.open(o,"wx");return await c.writeFile(`${process.pid}:${Date.now()}`),await c.close(),m(t||"agent-store","WARN","Stole stale agent store lock",{lockPath:o,ageMs:n}),{acquired:!0,lockPath:o}}}catch(s){m(t||"agent-store","WARN","Check agent store lock failed",{lockPath:o,error:s.message})}return m(t||"agent-store","INFO","Skip agent store update, lock held by another request",{lockPath:o}),{acquired:!1,lockPath:o}}throw i}}async function R(e,t){if(e)try{await r.promises.rm(e,{force:!0})}catch(o){m(t||"agent-store","WARN","Release agent store lock failed",{lockPath:e,error:o.message})}}function d(e){const t=a.join(e,p);return r.existsSync(t)&&r.statSync(t).isFile()}async function g(e){await r.promises.mkdir(e,{recursive:!0});const t=a.join(e,p);await r.promises.writeFile(t,`${Date.now()}
|
|
2
|
+
`,"utf8")}async function v(e,t,o){const i=new Set((Array.isArray(t)?t:[]).map(u=>String(u||"").trim()).filter(Boolean));if(!r.existsSync(e))return{removed:[],keptDynamic:[]};const s=[],n=[],c=await r.promises.readdir(e,{withFileTypes:!0});for(const u of c){if(!u.isDirectory()||i.has(u.name))continue;const w=a.join(e,u.name);if(d(w)){n.push(u.name);continue}await r.promises.rm(w,{recursive:!0,force:!0}),s.push(u.name)}return m(o||"agent-store","INFO","Prune agent skills completed",{skillsDir:e,keepCount:i.size,removed:s,keptDynamic:n}),{removed:s,keptDynamic:n}}async function C(e,t,o,i={}){const{asDynamic:s=!1}=i,n=a.join(t,o);try{await r.promises.lstat(n),await r.promises.rm(n,{recursive:!0,force:!0})}catch{}if(await r.promises.mkdir(t,{recursive:!0}),await f(e,n),s)await g(n);else{const c=a.join(n,p);r.existsSync(c)&&await r.promises.rm(c,{force:!0})}return n}async function f(e,t){try{await r.promises.rename(e,t)}catch(o){if(o&&o.code==="EXDEV"){await r.promises.cp(e,t,{recursive:!0}),await r.promises.rm(e,{recursive:!0,force:!0});return}throw o}}async function _(e,t){await r.promises.rm(t,{recursive:!0,force:!0}),await r.promises.mkdir(a.dirname(t),{recursive:!0}),e&&r.existsSync(e)?await f(e,t):await r.promises.mkdir(t,{recursive:!0})}function P(e,t){if(!e||!t)return!1;try{return r.statSync(a.join(e,t)).isDirectory()}catch{return!1}}export{p as DYNAMIC_ADD_LOCK,y as getAgentStorePath,A as ensureAgentStoreDirs,E as tryAcquireAgentStoreLock,R as releaseAgentStoreLock,d as hasDynamicAddLock,g as ensureDynamicAddLock,v as pruneAgentSkills,C as installSkillDir,_ as replaceAgentsDir,f as moveOrCopyDirectory,P as agentSkillExists};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import o from"fs";import l from"path";import te from"archiver";import P from"../../appConfig/index.js";import{log as u}from"../log/logUtils.js";import{ValidationError as y,SystemError as z,FileError as ue}from"../error/errorHandler.js";import{extractZip as de}from"../common/zipUtils.js";import{moveDirectory as pe,movePath as H}from"../common/fileSystemUtils.js";const M=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),he=100*1024*1024,V=P.DOWNLOAD_MAX_FILE_SIZE_BYTES||he;async function we(t,s,e,c,i){const r=[],h=await o.promises.readdir(t,{withFileTypes:!0});h.sort((n,f)=>n.isDirectory()&&!f.isDirectory()?-1:!n.isDirectory()&&f.isDirectory()?1:n.name.toLowerCase().localeCompare(f.name.toLowerCase()));for(const n of h){const f=l.join(t,n.name);if(n.name.startsWith(".")&&n.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(n.name)||n.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(n.name))continue;const m=l.relative(s,f).replace(/\\/g,"/");if(n.isDirectory()){r.push({name:m,isDir:!0});continue}try{r.push({name:m,isDir:!1,fileProxyUrl:X(c,m,i),isLink:n.isSymbolicLink()})}catch(a){u(e,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${f}`,{error:a.message})}}return r}async function re(t,s,e,c,i){const r=[],h=await o.promises.readdir(t,{withFileTypes:!0});h.sort((n,f)=>n.isDirectory()&&!f.isDirectory()?-1:!n.isDirectory()&&f.isDirectory()?1:n.name.toLowerCase().localeCompare(f.name.toLowerCase()));for(const n of h){const f=l.join(t,n.name);if(!(n.name.startsWith(".")&&n.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(n.name))&&!(n.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(n.name)))if(n.isDirectory()){const m=await re(f,s,e,c,i);if(m.length===0){const a=s||t,p=l.relative(a,f).replace(/\\/g,"/");r.push({name:p,isDir:!0})}else r.push(...m)}else try{const m=s||t,a=l.relative(m,f).replace(/\\/g,"/");r.push({name:a,isDir:!1,fileProxyUrl:X(c,a,i),isLink:n.isSymbolicLink()})}catch(m){u(e,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${f}`,{error:m.message})}}return r}function ie(t,s){const e=(s==null?"":String(s)).trim();if(!e||e==="."||e==="/")return l.resolve(t);const c=l.normalize(e).replace(/^[\/\\]+/,"");if(!c||c===".")return l.resolve(t);if(l.isAbsolute(e)||c.split(l.sep).includes(".."))throw new y("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:s});const i=l.resolve(t),r=l.resolve(t,c);if(r!==i&&!r.startsWith(i+l.sep))throw new y("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:s});return r}function se(t,s){const e=(s==null?"":String(s)).trim();if(!e)return null;const c=l.resolve(t);let i;if(l.isAbsolute(e))i=l.resolve(e);else{const h=l.normalize(e).replace(/^[\/\\]+/,"");if(!h||h==="."||h.split(l.sep).includes(".."))return null;i=l.resolve(t,h)}if(i!==c&&!i.startsWith(c+l.sep))return null;const r=l.relative(c,i).replace(/\\/g,"/");return!r||r.startsWith("..")?null:{absPath:i,name:r}}function X(t,s,e){if(!t||!s)return null;const c=s.split("/").map(r=>encodeURIComponent(r)).join("/");let i=`${t}/${c}`;return e&&(i+=`?customTargetDir=${encodeURIComponent(e)}`),i}async function ge(t,s,e,c,i){if(!t)throw new y("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!s)throw new y("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!e||!String(e).trim())throw new y("filePath \u4E0D\u80FD\u4E3A\u7A7A",{field:"filePath"});const r=String(t),h=String(s),n=P.COMPUTER_WORKSPACE_DIR,f=i&&i.trim()?i.trim():null,w=f||l.join(n,r,h);if(!o.existsSync(w))return{exists:!1};let m=se(w,e);if(!m){const a=String(e).trim().replace(/^[\/\\]+/,"");a&&a!==String(e).trim()&&(m=se(w,a))}if(!m)return{exists:!1};try{if(!(await o.promises.stat(m.absPath)).isFile())return{exists:!1}}catch{return{exists:!1}}return{exists:!0,name:m.name,fileProxyUrl:X(c,m.name,f)}}async function ne(t,s,e,c,i=""){const r=await o.promises.readdir(l.join(t,i),{withFileTypes:!0});let h=0;for(const n of r){const f=i?l.join(i,n.name):n.name,w=f.split(l.sep).filter(Boolean);if(w.some(g=>g.startsWith(".")))continue;const m=w[w.length-1];if(s.includes(m)||w.some(g=>e.includes(g)))continue;const a=l.join(t,f);let p;try{p=await o.promises.lstat(a)}catch(g){u(c,"WARN","Error occurred when getting file stats, skipping",{filePath:f.replace(/\\/g,"/"),error:g.message});continue}p.isSymbolicLink()||p.nlink>1||(p.isDirectory()?h+=await ne(t,s,e,c,f):p.isFile()&&(h+=p.size))}return h}async function ye(t,s,e,c,i,r){const h=Date.now(),n=`computer:${t}:${s}`,f=P.COMPUTER_WORKSPACE_DIR,w=!(r===!1||r==="false");if(!t)throw new y("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!s)throw new y("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const m=String(t),a=String(s),p=c&&c.trim()?c.trim():null,g=p||l.join(f,m,a);if(!o.existsSync(g))return u(n,"INFO","Directory does not exist, returning empty list",{targetDir:g,userId:m,cId:a}),{files:[],recursive:w};const d=ie(g,i);if(!o.existsSync(d))return u(n,"INFO","List path does not exist, returning empty list",{targetDir:g,listDir:d,relativePath:i||"",userId:m,cId:a}),{files:[],recursive:w};if(!(await o.promises.stat(d)).isDirectory())throw new y("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:i});u(n,"DEBUG","Start getting user file list",{targetDir:g,listDir:d,relativePath:i||"",recursive:w,userId:m,cId:a});try{const E=w?await re(d,g,n,e,p):await we(d,g,n,e,p);return u(n,"INFO","User file list obtained successfully",{fileCount:E.length,targetDir:g,listDir:d,relativePath:i||"",recursive:w,userId:m,cId:a,elapsedMs:Date.now()-h}),{files:E,recursive:w}}catch(E){throw E instanceof y?E:(u(n,"ERROR","Failed to get user file list",{targetDir:g,listDir:d,relativePath:i||"",recursive:w,userId:m,cId:a,error:E.message,elapsedMs:Date.now()-h}),new z(`Failed to get file list: ${E.message}`,{targetDir:g,originalError:E.message}))}}const Re=5e3;function J(t,s){const e=Number.parseInt(t,10);if(!Number.isFinite(e)||e<=0)throw new y(`${s} \u5FC5\u987B\u4E3A\u6B63\u6574\u6570`,{field:s,value:t});return e}function oe(t,s,e){return e?s.toLowerCase().includes(e)?!0:t.toLowerCase().includes(e):!1}function ae(t,s,e){return!!(t.name.startsWith(".")&&t.name!==".gitignore"||s.includes(t.name)||t.isDirectory()&&e.includes(t.name))}function ce(t,s,e,c){for(let i=s;i<t.length;i++)if(!ae(t[i],e,c))return!0;return!1}function le(t,s){return Date.now()-t>=s}async function Ee(t,s,e,c,i,r,h,n,f){const w=Date.now(),m=`computer:${t}:${s}`,a=P.COMPUTER_WORKSPACE_DIR;if(!t)throw new y("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!s)throw new y("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const p=(c==null?"":String(c)).trim();if(!p)throw new y("kw \u4E0D\u80FD\u4E3A\u7A7A",{field:"kw"});const g=J(h,"limit"),d=J(n,"maxVisit"),R=J(f,"timeoutMs"),E=p.toLowerCase(),S=String(t),v=String(s),I=i&&i.trim()?i.trim():null,D=I||l.join(a,S,v);if(!o.existsSync(D))return{files:[],truncated:!1,visited:0};const F=ie(D,r);if(!o.existsSync(F))return{files:[],truncated:!1,visited:0};if(!(await o.promises.stat(F)).isDirectory())throw new y("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:r});const A=l.relative(D,F).replace(/\\/g,"/"),G=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],K=P.TRAVERSE_EXCLUDE_DIRS||[],C=[],q=new Set;let W=0,Z=!1,O=!1;const _=[A],T=()=>W>=d||le(w,R);for(;_.length>0;){if(T()){O=!0;break}if(C.length>=g){_.length>0&&(O=!0);break}const x=_.shift();if(q.has(x))continue;q.add(x);const U=x?l.join(D,x):D;let L;try{L=await o.promises.readdir(U,{withFileTypes:!0})}catch(k){u(m,"WARN","search readdir failed",{dirRel:x,error:k.message});continue}L.sort((k,b)=>k.isDirectory()&&!b.isDirectory()?-1:!k.isDirectory()&&b.isDirectory()?1:k.name.toLowerCase().localeCompare(b.name.toLowerCase()));const Y=[];let j=!1,B=!1;for(let k=0;k<L.length;k++){const b=L[k];if(ae(b,G,K))continue;if(T()){O=!0,j=!0,B=!0;break}W+=1;const ee=l.join(U,b.name),$=l.relative(D,ee).replace(/\\/g,"/");if(b.isDirectory()){if(Y.push($),C.length<g&&oe($,b.name,E)&&(C.push({name:$,isDir:!0}),C.length>=g)){j=!0,B=ce(L,k+1,G,K);break}continue}try{if(C.length<g&&oe($,b.name,E)&&(C.push({name:$,isDir:!1,fileProxyUrl:X(e,$,I),isLink:b.isSymbolicLink()}),C.length>=g)){j=!0,B=ce(L,k+1,G,K);break}}catch(fe){u(m,"WARN",`search \u5904\u7406\u6587\u4EF6\u5931\u8D25: ${ee}`,{error:fe.message})}}if(j||T()){(T()||B||Y.length>0||_.length>0)&&(O=!0);continue}for(const k of Y){if(T()){O=!0;break}if(_.length>=Re){O=!0;break}if(W+_.length>=d){O=!0;break}q.has(k)||_.push(k)}}return C.sort((x,U)=>x.isDir!==U.isDir?x.isDir?-1:1:String(x.name).localeCompare(String(U.name))),Z=O||_.length>0||W>=d||le(w,R),u(m,"INFO","File search completed",{kw:p,matchCount:C.length,visited:W,truncated:Z,relativePath:r||"",elapsedMs:Date.now()-w}),{files:C,truncated:Z,visited:W}}async function Se(t,s,e,c){const i=Date.now(),r=`computer:${t}:${s}`,h=P.COMPUTER_WORKSPACE_DIR;if(!t)throw new y("userId cannot be empty",{field:"userId"});if(!s)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(e))throw new y("files must be an array",{field:"files"});const n=String(t),f=String(s),w=c&&c.trim()?c.trim():null,m=w||l.join(h,n,f);o.existsSync(m)||o.mkdirSync(m,{recursive:!0});for(let a=0;a<e.length;a++){const p=e[a];if(!p||typeof p.operation!="string")throw new y(`files[${a}].operation cannot be empty`,{field:`files[${a}].operation`});if(!p.name||typeof p.name!="string")throw new y(`files[${a}].name cannot be empty`,{field:`files[${a}].name`});const g=p.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(g))throw new y(`files[${a}].operation must be one of create, delete, rename or modify`,{field:`files[${a}].operation`});if(g==="rename"&&!p.renameFrom)throw new y(`files[${a}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${a}].renameFrom`});if(g==="modify"&&p.isDir!==!0&&typeof p.contents!="string")throw new y(`files[${a}].contents must be a string (modify operation requires)`,{field:`files[${a}].contents`})}u(r,"DEBUG","Start updating user files",{userId:n,cId:f,filesCount:e.length});try{for(const a of e){const p=a.operation.toLowerCase(),g=a.name,d=l.normalize(g).replace(/^[\/\\]+/,""),R=l.join(m,d),E=l.resolve(R),S=l.resolve(m);if(!E.startsWith(S+l.sep)&&E!==S){u(r,"WARN","File path is not secure, skipping",{filePath:d,resolvedPath:E});continue}switch(p){case"create":{if(a.isDir===!0){if(o.existsSync(R)){if((await o.promises.stat(R)).isFile())throw new y("Cannot create directory, file with the same name already exists",{filePath:d});u(r,"INFO","Directory already exists, skipping creation",{filePath:d});break}await o.promises.mkdir(R,{recursive:!0}),u(r,"INFO","Directory created successfully",{filePath:d});break}if(o.existsSync(R)){if((await o.promises.stat(R)).isDirectory())throw new y("Cannot create file, directory with the same name already exists",{filePath:d});u(r,"INFO","File already exists, skipping creation",{filePath:d});break}await o.promises.mkdir(l.dirname(R),{recursive:!0});const v=a.contents||"";await o.promises.writeFile(R,v,"utf8"),u(r,"INFO","File created successfully",{filePath:d});break}case"delete":{o.existsSync(R)?(await o.promises.stat(R)).isDirectory()?(await o.promises.rm(R,{recursive:!0,force:!0}),u(r,"INFO","Directory deleted successfully",{filePath:d})):(await o.promises.unlink(R),u(r,"INFO","File deleted successfully",{filePath:d})):u(r,"WARN","The file or directory to be deleted does not exist",{filePath:d});break}case"rename":{const v=a.renameFrom;if(!v||typeof v!="string"){u(r,"WARN","Rename operation missing renameFrom",{filePath:d});break}const I=l.normalize(v).replace(/^[\/\\]+/,""),D=l.join(m,I),F=l.resolve(D);if(!F.startsWith(S+l.sep)&&F!==S){u(r,"WARN","Source path is not secure, skipping rename",{sourcePath:I,targetPath:d});break}if(o.existsSync(D)){const A=(await o.promises.stat(D)).isDirectory();await o.promises.mkdir(l.dirname(R),{recursive:!0}),await o.promises.rename(D,R),u(r,"INFO",A?"Directory renamed successfully":"File renamed successfully",{sourcePath:I,targetPath:d})}else u(r,"WARN","The file or directory to be renamed does not exist",{sourcePath:I});break}case"modify":{if(!o.existsSync(R)){u(r,"WARN","The file to be modified does not exist",{filePath:d});break}if((await o.promises.stat(R)).isDirectory()){u(r,"INFO","The target is a directory, skipping modification",{filePath:d});break}const I=typeof a.contents=="string"?a.contents:"";if(await o.promises.readFile(R,"utf8")===I){u(r,"INFO","File content has no changes, skipping write",{filePath:d});break}await o.promises.writeFile(R,I,"utf8"),u(r,"INFO","File modified successfully",{filePath:d});break}default:{u(r,"WARN","Unsupported operation type",{operation:p,filePath:d});break}}}return u(r,"INFO","User files updated successfully",{userId:n,cId:f,filesCount:e.length,elapsedMs:Date.now()-i}),{success:!0,message:"User files updated successfully",userId:n,cId:f,filesCount:e.length}}catch(a){throw u(r,"ERROR","User files updated failed",{userId:n,cId:f,error:a.message,elapsedMs:Date.now()-i}),new z(`User files updated failed: ${a.message}`,{userId:n,cId:f,originalError:a.message})}}async function Q(t,s,e,c,i){const r=Date.now(),h=`computer:${t}:${s}`,n=P.COMPUTER_WORKSPACE_DIR;if(!t)throw new y("userId cannot be empty",{field:"userId"});if(!s)throw new y("cId cannot be empty",{field:"cId"});if(!e)throw new y("file cannot be empty",{field:"file"});if(!c||typeof c!="string")throw new y("filePath cannot be empty",{field:"filePath"});const f=String(t),w=String(s),m=i&&i.trim()?i.trim():null,a=m||l.join(n,f,w);o.existsSync(a)||o.mkdirSync(a,{recursive:!0});const p=l.normalize(c).replace(/^[\/\\]+/,""),g=l.join(a,p),d=l.resolve(g),R=l.resolve(a);if(!d.startsWith(R+l.sep)&&d!==R)throw new y("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:c,resolvedPath:d});try{if(await o.promises.mkdir(l.dirname(g),{recursive:!0}),e.buffer)await o.promises.writeFile(g,e.buffer);else if(typeof e.contents=="string")await o.promises.writeFile(g,e.contents,"utf8");else throw new y("File content format is incorrect",{field:"file",hasBuffer:!!e.buffer,hasContents:typeof e.contents});return u(h,"INFO","File uploaded successfully",{userId:f,cId:w,filePath:p,targetPath:d,fileSize:e.buffer?e.buffer.length:e.contents?e.contents.length:0,elapsedMs:Date.now()-r}),{success:!0,message:"File uploaded successfully",fileSize:e.buffer?e.buffer.length:e.contents?e.contents.length:0}}catch(E){throw u(h,"ERROR","File upload failed",{userId:f,cId:w,filePath:p,error:E.message,elapsedMs:Date.now()-r}),new z(`File upload failed: ${E.message}`,{userId:f,cId:w,filePath:p,originalError:E.message})}}async function Ie(t,s,e,c,i){const r=Date.now(),h=`computer:${t}:${s}`;if(!t)throw new y("userId cannot be empty",{field:"userId"});if(!s)throw new y("cId cannot be empty",{field:"cId"});if(!Array.isArray(e))throw new y("files must be an array",{field:"files"});if(!Array.isArray(c))throw new y("filePaths must be an array",{field:"filePaths"});if(e.length!==c.length)throw new y(`File count (${e.length}) does not match path count (${c.length})`,{field:"filePaths"});u(h,"DEBUG","Start batch uploading files",{userId:t,cId:s,filesCount:e.length});const n=[];try{for(let m=0;m<e.length;m++){const a=e[m],p=c[m];if(!a){u(h,"WARN","Empty file object encountered in batch upload, skipping",{index:m,filePath:p}),n.push({success:!1,filePath:p,error:"Empty file object"});continue}if(!p||typeof p!="string"){u(h,"WARN","Invalid file path in batch upload, skipping",{index:m,originalname:a.originalname}),n.push({success:!1,filePath:p||"",originalname:a.originalname,error:"Invalid file path"});continue}try{const g=await Q(t,s,a,p,i);n.push({success:!0,filePath:p,originalname:a.originalname,...g})}catch(g){u(h,"ERROR","Single file upload failed in batch upload",{filePath:p,originalname:a.originalname,error:g.message}),n.push({success:!1,filePath:p,originalname:a.originalname,error:g.message})}}const f=n.filter(m=>m.success).length,w=n.filter(m=>!m.success).length;return u(h,"INFO","Batch upload files completed",{userId:t,cId:s,totalCount:e.length,successCount:f,failCount:w,elapsedMs:Date.now()-r}),{success:!0,message:"Batch upload completed",totalCount:e.length,successCount:f,failCount:w,results:n}}catch(f){throw u(h,"ERROR","Batch upload files failed",{userId:t,cId:s,error:f.message,elapsedMs:Date.now()-r}),new z(`Batch upload files failed: ${f.message}`,{userId:t,cId:s,originalError:f.message})}}async function Fe(t,s,e){const c=Date.now(),i=`computer:${t}:${s}`,r=P.COMPUTER_WORKSPACE_DIR;if(!t)throw new y("userId cannot be empty",{field:"userId"});if(!s)throw new y("cId cannot be empty",{field:"cId"});if(!r)throw new z("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const h=String(t),n=String(s),f=e&&e.trim()?e.trim():null,w=f||l.join(r,h,n);if(!o.existsSync(w)){const R=`${h}_${n}.zip`;u(i,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:w,userId:h,cId:n,zipFileName:R});const E=te("zip",{zlib:{level:9}});return E.append(null,{name:`${h}_${n}/`,type:"directory"}),E.on("warning",S=>{if(S.code==="ENOENT")u(i,"WARN","Encountered file problem when creating empty zip",{message:S.message,code:S.code});else throw u(i,"ERROR","Encountered warning when creating empty zip",{message:S.message,code:S.code}),S}),E.on("error",S=>{u(i,"ERROR","Failed to create empty zip",{message:S.message})}),{archive:E,zipFileName:R}}const m=`${h}_${n}.zip`;u(i,"DEBUG","Start creating workspace directory zip",{targetDir:w,zipFileName:m});const a=te("zip",{zlib:{level:9}}),p=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],g=P.TRAVERSE_EXCLUDE_DIRS||[],d=await ne(w,p,g,i);if(d>V){const R=V/1024/1024,E=(d/1024/1024).toFixed(2);throw u(i,"WARN","Download rejected due to oversized workspace",{targetDir:w,downloadableSize:d,maxSizeBytes:V}),new y(`Download failed: total file size ${E}MB exceeds limit ${R}MB`,{field:"downloadSize",downloadableSize:d,maxSizeBytes:V})}return a.directory(w,`${h}_${n}`,R=>{const E=R.name||"",S=E.split(/[\/\\]/).filter(Boolean);if(S.some(I=>I.startsWith(".")))return!1;const v=S[S.length-1];if(p.includes(v)||S.some(I=>g.includes(I)))return!1;try{const I=l.join(w,E),D=o.lstatSync(I);if(D.isSymbolicLink()||D.nlink>1)return!1}catch(I){return u(i,"WARN","Error occurred when detecting link file, skipping",{filePath:E,error:I.message}),!1}return R}),a.on("warning",R=>{if(R.code==="ENOENT")u(i,"WARN","Encountered file problem when creating zip",{message:R.message,code:R.code});else throw u(i,"ERROR","Encountered warning when creating zip",{message:R.message,code:R.code}),R}),a.on("error",R=>{u(i,"ERROR","Failed to create zip",{message:R.message,elapsedMs:Date.now()-c})}),a.on("end",()=>{u(i,"INFO","Workspace directory zip created successfully",{targetDir:w,zipFileName:m,elapsedMs:Date.now()-c})}),{archive:a,zipFileName:m}}async function De(t,s,e=200){const c=Date.now(),i=`computer:${t}:${s}`;if(!t)throw new y("userId cannot be empty",{field:"userId"});if(!s)throw new y("cId cannot be empty",{field:"cId"});const r=String(t),h=String(s),n=P.COMPUTER_WORKSPACE_DIR;if(!n)return u(i,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};const f=l.join(n,r,h,".logs");if(!o.existsSync(f))return u(i,"DEBUG","Log directory does not exist",{logDir:f}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const m=(await o.promises.readdir(f,{withFileTypes:!0})).filter(F=>F.isFile()).map(F=>F.name);if(m.length===0)return u(i,"DEBUG","No log file found",{logDir:f}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const a=[];for(const F of m){const N=l.join(f,F),A=await o.promises.stat(N);a.push({name:F,fullPath:N,mtime:A.mtimeMs,size:A.size})}a.sort((F,N)=>N.mtime-F.mtime);const p=a[0],d=(await o.promises.readFile(p.fullPath,"utf8")).split(`
|
|
2
|
-
`).filter(
|
|
1
|
+
import c from"fs";import d from"path";import re from"archiver";import P from"../../appConfig/index.js";import{log as u}from"../log/logUtils.js";import{ValidationError as E,SystemError as O,FileError as pe}from"../error/errorHandler.js";import{extractZip as he}from"../common/zipUtils.js";import{moveDirectory as we,movePath as J}from"../common/fileSystemUtils.js";import{resolveLogDir as ge,resolveWorkspaceDir as _,resolveWorkspaceRoot as ie}from"./workspaceContext.js";const j=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),ye=100*1024*1024,X=P.DOWNLOAD_MAX_FILE_SIZE_BYTES||ye;async function Ee(t,i,e,l,a){const o=[],m=await c.promises.readdir(t,{withFileTypes:!0});m.sort((s,n)=>s.isDirectory()&&!n.isDirectory()?-1:!s.isDirectory()&&n.isDirectory()?1:s.name.toLowerCase().localeCompare(n.name.toLowerCase()));for(const s of m){const n=d.join(t,s.name);if(s.name.startsWith(".")&&s.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(s.name)||s.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(s.name))continue;const f=d.relative(i,n).replace(/\\/g,"/");if(s.isDirectory()){o.push({name:f,isDir:!0});continue}try{o.push({name:f,isDir:!1,fileProxyUrl:G(l,f,a),isLink:s.isSymbolicLink()})}catch(r){u(e,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${n}`,{error:r.message})}}return o}async function se(t,i,e,l,a){const o=[],m=await c.promises.readdir(t,{withFileTypes:!0});m.sort((s,n)=>s.isDirectory()&&!n.isDirectory()?-1:!s.isDirectory()&&n.isDirectory()?1:s.name.toLowerCase().localeCompare(n.name.toLowerCase()));for(const s of m){const n=d.join(t,s.name);if(!(s.name.startsWith(".")&&s.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(s.name))&&!(s.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(s.name)))if(s.isDirectory()){const f=await se(n,i,e,l,a);if(f.length===0){const r=i||t,h=d.relative(r,n).replace(/\\/g,"/");o.push({name:h,isDir:!0})}else o.push(...f)}else try{const f=i||t,r=d.relative(f,n).replace(/\\/g,"/");o.push({name:r,isDir:!1,fileProxyUrl:G(l,r,a),isLink:s.isSymbolicLink()})}catch(f){u(e,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${n}`,{error:f.message})}}return o}function ne(t,i){const e=(i==null?"":String(i)).trim();if(!e||e==="."||e==="/")return d.resolve(t);const l=d.normalize(e).replace(/^[\/\\]+/,"");if(!l||l===".")return d.resolve(t);if(d.isAbsolute(e)||l.split(d.sep).includes(".."))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:i});const a=d.resolve(t),o=d.resolve(t,l);if(o!==a&&!o.startsWith(a+d.sep))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:i});return o}function oe(t,i){const e=(i==null?"":String(i)).trim();if(!e)return null;const l=d.resolve(t);let a;if(d.isAbsolute(e))a=d.resolve(e);else{const m=d.normalize(e).replace(/^[\/\\]+/,"");if(!m||m==="."||m.split(d.sep).includes(".."))return null;a=d.resolve(t,m)}if(a!==l&&!a.startsWith(l+d.sep))return null;const o=d.relative(l,a).replace(/\\/g,"/");return!o||o.startsWith("..")?null:{absPath:a,name:o}}function G(t,i,e){if(!t||!i)return null;const l=i.split("/").map(o=>encodeURIComponent(o)).join("/");let a=`${t}/${l}`;return e&&(a+=`?customTargetDir=${encodeURIComponent(e)}`),a}async function Se(t,i,e,l,a,o=null){if(!t)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!e||!String(e).trim())throw new E("filePath \u4E0D\u80FD\u4E3A\u7A7A",{field:"filePath"});const m=String(t),s=String(i),n=a&&a.trim()?a.trim():null,y=n||_(o,m,s);if(!c.existsSync(y))return{exists:!1};let f=oe(y,e);if(!f){const r=String(e).trim().replace(/^[\/\\]+/,"");r&&r!==String(e).trim()&&(f=oe(y,r))}if(!f)return{exists:!1};try{if(!(await c.promises.stat(f.absPath)).isFile())return{exists:!1}}catch{return{exists:!1}}return{exists:!0,name:f.name,fileProxyUrl:G(l,f.name,n)}}async function ae(t,i,e,l,a=""){const o=await c.promises.readdir(d.join(t,a),{withFileTypes:!0});let m=0;for(const s of o){const n=a?d.join(a,s.name):s.name,y=n.split(d.sep).filter(Boolean);if(y.some(w=>w.startsWith(".")))continue;const f=y[y.length-1];if(i.includes(f)||y.some(w=>e.includes(w)))continue;const r=d.join(t,n);let h;try{h=await c.promises.lstat(r)}catch(w){u(l,"WARN","Error occurred when getting file stats, skipping",{filePath:n.replace(/\\/g,"/"),error:w.message});continue}h.isSymbolicLink()||h.nlink>1||(h.isDirectory()?m+=await ae(t,i,e,l,n):h.isFile()&&(m+=h.size))}return m}async function Re(t,i,e,l,a,o,m=null){const s=Date.now(),n=`computer:${t}:${i}`,y=!(o===!1||o==="false");if(!t)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const f=String(t),r=String(i),h=l&&l.trim()?l.trim():null,w=h||_(m,f,r);if(!c.existsSync(w))return u(n,"INFO","Directory does not exist, returning empty list",{targetDir:w,userId:f,cId:r}),{files:[],recursive:y};const p=ne(w,a);if(!c.existsSync(p))return u(n,"INFO","List path does not exist, returning empty list",{targetDir:w,listDir:p,relativePath:a||"",userId:f,cId:r}),{files:[],recursive:y};if(!(await c.promises.stat(p)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:a});u(n,"DEBUG","Start getting user file list",{targetDir:w,listDir:p,relativePath:a||"",recursive:y,userId:f,cId:r});try{const S=y?await se(p,w,n,e,h):await Ee(p,w,n,e,h);return u(n,"INFO","User file list obtained successfully",{fileCount:S.length,targetDir:w,listDir:p,relativePath:a||"",recursive:y,userId:f,cId:r,elapsedMs:Date.now()-s}),{files:S,recursive:y}}catch(S){throw S instanceof E?S:(u(n,"ERROR","Failed to get user file list",{targetDir:w,listDir:p,relativePath:a||"",recursive:y,userId:f,cId:r,error:S.message,elapsedMs:Date.now()-s}),new O(`Failed to get file list: ${S.message}`,{targetDir:w,originalError:S.message}))}}const Fe=5e3;function Q(t,i){const e=Number.parseInt(t,10);if(!Number.isFinite(e)||e<=0)throw new E(`${i} \u5FC5\u987B\u4E3A\u6B63\u6574\u6570`,{field:i,value:t});return e}function ce(t,i,e){return e?i.toLowerCase().includes(e)?!0:t.toLowerCase().includes(e):!1}function le(t,i,e){return!!(t.name.startsWith(".")&&t.name!==".gitignore"||i.includes(t.name)||t.isDirectory()&&e.includes(t.name))}function me(t,i,e,l){for(let a=i;a<t.length;a++)if(!le(t[a],e,l))return!0;return!1}function ue(t,i){return Date.now()-t>=i}async function De(t,i,e,l,a,o,m,s,n,y=null){const f=Date.now(),r=`computer:${t}:${i}`;if(!t)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const h=(l==null?"":String(l)).trim();if(!h)throw new E("kw \u4E0D\u80FD\u4E3A\u7A7A",{field:"kw"});const w=Q(m,"limit"),p=Q(s,"maxVisit"),g=Q(n,"timeoutMs"),S=h.toLowerCase(),I=String(t),R=String(i),v=a&&a.trim()?a.trim():null,F=v||_(y,I,R);if(!c.existsSync(F))return{files:[],truncated:!1,visited:0};const D=ne(F,o);if(!c.existsSync(D))return{files:[],truncated:!1,visited:0};if(!(await c.promises.stat(D)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:o});const $=d.relative(F,D).replace(/\\/g,"/"),q=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],Z=P.TRAVERSE_EXCLUDE_DIRS||[],b=[],K=new Set;let A=0,Y=!1,C=!1;const L=[$],U=()=>A>=p||ue(f,g);for(;L.length>0;){if(U()){C=!0;break}if(b.length>=w){L.length>0&&(C=!0);break}const N=L.shift();if(K.has(N))continue;K.add(N);const M=N?d.join(F,N):F;let W;try{W=await c.promises.readdir(M,{withFileTypes:!0})}catch(k){u(r,"WARN","search readdir failed",{dirRel:N,error:k.message});continue}W.sort((k,x)=>k.isDirectory()&&!x.isDirectory()?-1:!k.isDirectory()&&x.isDirectory()?1:k.name.toLowerCase().localeCompare(x.name.toLowerCase()));const H=[];let B=!1,V=!1;for(let k=0;k<W.length;k++){const x=W[k];if(le(x,q,Z))continue;if(U()){C=!0,B=!0,V=!0;break}A+=1;const te=d.join(M,x.name),T=d.relative(F,te).replace(/\\/g,"/");if(x.isDirectory()){if(H.push(T),b.length<w&&ce(T,x.name,S)&&(b.push({name:T,isDir:!0}),b.length>=w)){B=!0,V=me(W,k+1,q,Z);break}continue}try{if(b.length<w&&ce(T,x.name,S)&&(b.push({name:T,isDir:!1,fileProxyUrl:G(e,T,v),isLink:x.isSymbolicLink()}),b.length>=w)){B=!0,V=me(W,k+1,q,Z);break}}catch(de){u(r,"WARN",`search \u5904\u7406\u6587\u4EF6\u5931\u8D25: ${te}`,{error:de.message})}}if(B||U()){(U()||V||H.length>0||L.length>0)&&(C=!0);continue}for(const k of H){if(U()){C=!0;break}if(L.length>=Fe){C=!0;break}if(A+L.length>=p){C=!0;break}K.has(k)||L.push(k)}}return b.sort((N,M)=>N.isDir!==M.isDir?N.isDir?-1:1:String(N.name).localeCompare(String(M.name))),Y=C||L.length>0||A>=p||ue(f,g),u(r,"INFO","File search completed",{kw:h,matchCount:b.length,visited:A,truncated:Y,relativePath:o||"",elapsedMs:Date.now()-f}),{files:b,truncated:Y,visited:A}}async function Ie(t,i,e,l,a=null){const o=Date.now(),m=`computer:${t}:${i}`;if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(e))throw new E("files must be an array",{field:"files"});const s=String(t),n=String(i),y=l&&l.trim()?l.trim():null,f=y||_(a,s,n);c.existsSync(f)||c.mkdirSync(f,{recursive:!0});for(let r=0;r<e.length;r++){const h=e[r];if(!h||typeof h.operation!="string")throw new E(`files[${r}].operation cannot be empty`,{field:`files[${r}].operation`});if(!h.name||typeof h.name!="string")throw new E(`files[${r}].name cannot be empty`,{field:`files[${r}].name`});const w=h.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(w))throw new E(`files[${r}].operation must be one of create, delete, rename or modify`,{field:`files[${r}].operation`});if(w==="rename"&&!h.renameFrom)throw new E(`files[${r}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${r}].renameFrom`});if(w==="modify"&&h.isDir!==!0&&typeof h.contents!="string")throw new E(`files[${r}].contents must be a string (modify operation requires)`,{field:`files[${r}].contents`})}u(m,"DEBUG","Start updating user files",{userId:s,cId:n,filesCount:e.length});try{for(const r of e){const h=r.operation.toLowerCase(),w=r.name,p=d.normalize(w).replace(/^[\/\\]+/,""),g=d.join(f,p),S=d.resolve(g),I=d.resolve(f);if(!S.startsWith(I+d.sep)&&S!==I){u(m,"WARN","File path is not secure, skipping",{filePath:p,resolvedPath:S});continue}switch(h){case"create":{if(r.isDir===!0){if(c.existsSync(g)){if((await c.promises.stat(g)).isFile())throw new E("Cannot create directory, file with the same name already exists",{filePath:p});u(m,"INFO","Directory already exists, skipping creation",{filePath:p});break}await c.promises.mkdir(g,{recursive:!0}),u(m,"INFO","Directory created successfully",{filePath:p});break}if(c.existsSync(g)){if((await c.promises.stat(g)).isDirectory())throw new E("Cannot create file, directory with the same name already exists",{filePath:p});u(m,"INFO","File already exists, skipping creation",{filePath:p});break}await c.promises.mkdir(d.dirname(g),{recursive:!0});const R=r.contents||"";await c.promises.writeFile(g,R,"utf8"),u(m,"INFO","File created successfully",{filePath:p});break}case"delete":{c.existsSync(g)?(await c.promises.stat(g)).isDirectory()?(await c.promises.rm(g,{recursive:!0,force:!0}),u(m,"INFO","Directory deleted successfully",{filePath:p})):(await c.promises.unlink(g),u(m,"INFO","File deleted successfully",{filePath:p})):u(m,"WARN","The file or directory to be deleted does not exist",{filePath:p});break}case"rename":{const R=r.renameFrom;if(!R||typeof R!="string"){u(m,"WARN","Rename operation missing renameFrom",{filePath:p});break}const v=d.normalize(R).replace(/^[\/\\]+/,""),F=d.join(f,v),D=d.resolve(F);if(!D.startsWith(I+d.sep)&&D!==I){u(m,"WARN","Source path is not secure, skipping rename",{sourcePath:v,targetPath:p});break}if(c.existsSync(F)){const $=(await c.promises.stat(F)).isDirectory();await c.promises.mkdir(d.dirname(g),{recursive:!0}),await c.promises.rename(F,g),u(m,"INFO",$?"Directory renamed successfully":"File renamed successfully",{sourcePath:v,targetPath:p})}else u(m,"WARN","The file or directory to be renamed does not exist",{sourcePath:v});break}case"modify":{if(!c.existsSync(g)){u(m,"WARN","The file to be modified does not exist",{filePath:p});break}if((await c.promises.stat(g)).isDirectory()){u(m,"INFO","The target is a directory, skipping modification",{filePath:p});break}const v=typeof r.contents=="string"?r.contents:"";if(await c.promises.readFile(g,"utf8")===v){u(m,"INFO","File content has no changes, skipping write",{filePath:p});break}await c.promises.writeFile(g,v,"utf8"),u(m,"INFO","File modified successfully",{filePath:p});break}default:{u(m,"WARN","Unsupported operation type",{operation:h,filePath:p});break}}}return u(m,"INFO","User files updated successfully",{userId:s,cId:n,filesCount:e.length,elapsedMs:Date.now()-o}),{success:!0,message:"User files updated successfully",userId:s,cId:n,filesCount:e.length}}catch(r){throw u(m,"ERROR","User files updated failed",{userId:s,cId:n,error:r.message,elapsedMs:Date.now()-o}),new O(`User files updated failed: ${r.message}`,{userId:s,cId:n,originalError:r.message})}}async function ee(t,i,e,l,a,o=null){const m=Date.now(),s=`computer:${t}:${i}`;if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!e)throw new E("file cannot be empty",{field:"file"});if(!l||typeof l!="string")throw new E("filePath cannot be empty",{field:"filePath"});const n=String(t),y=String(i),f=a&&a.trim()?a.trim():null,r=f||_(o,n,y);c.existsSync(r)||c.mkdirSync(r,{recursive:!0});const h=d.normalize(l).replace(/^[\/\\]+/,""),w=d.join(r,h),p=d.resolve(w),g=d.resolve(r);if(!p.startsWith(g+d.sep)&&p!==g)throw new E("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:l,resolvedPath:p});try{if(await c.promises.mkdir(d.dirname(w),{recursive:!0}),e.buffer)await c.promises.writeFile(w,e.buffer);else if(typeof e.contents=="string")await c.promises.writeFile(w,e.contents,"utf8");else throw new E("File content format is incorrect",{field:"file",hasBuffer:!!e.buffer,hasContents:typeof e.contents});return u(s,"INFO","File uploaded successfully",{userId:n,cId:y,filePath:h,targetPath:p,fileSize:e.buffer?e.buffer.length:e.contents?e.contents.length:0,elapsedMs:Date.now()-m}),{success:!0,message:"File uploaded successfully",fileSize:e.buffer?e.buffer.length:e.contents?e.contents.length:0}}catch(S){throw u(s,"ERROR","File upload failed",{userId:n,cId:y,filePath:h,error:S.message,elapsedMs:Date.now()-m}),new O(`File upload failed: ${S.message}`,{userId:n,cId:y,filePath:h,originalError:S.message})}}async function ve(t,i,e,l,a,o=null){const m=Date.now(),s=`computer:${t}:${i}`;if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(e))throw new E("files must be an array",{field:"files"});if(!Array.isArray(l))throw new E("filePaths must be an array",{field:"filePaths"});if(e.length!==l.length)throw new E(`File count (${e.length}) does not match path count (${l.length})`,{field:"filePaths"});u(s,"DEBUG","Start batch uploading files",{userId:t,cId:i,filesCount:e.length});const n=[];try{for(let r=0;r<e.length;r++){const h=e[r],w=l[r];if(!h){u(s,"WARN","Empty file object encountered in batch upload, skipping",{index:r,filePath:w}),n.push({success:!1,filePath:w,error:"Empty file object"});continue}if(!w||typeof w!="string"){u(s,"WARN","Invalid file path in batch upload, skipping",{index:r,originalname:h.originalname}),n.push({success:!1,filePath:w||"",originalname:h.originalname,error:"Invalid file path"});continue}try{const p=await ee(t,i,h,w,a,o);n.push({success:!0,filePath:w,originalname:h.originalname,...p})}catch(p){u(s,"ERROR","Single file upload failed in batch upload",{filePath:w,originalname:h.originalname,error:p.message}),n.push({success:!1,filePath:w,originalname:h.originalname,error:p.message})}}const y=n.filter(r=>r.success).length,f=n.filter(r=>!r.success).length;return u(s,"INFO","Batch upload files completed",{userId:t,cId:i,totalCount:e.length,successCount:y,failCount:f,elapsedMs:Date.now()-m}),{success:!0,message:"Batch upload completed",totalCount:e.length,successCount:y,failCount:f,results:n}}catch(y){throw u(s,"ERROR","Batch upload files failed",{userId:t,cId:i,error:y.message,elapsedMs:Date.now()-m}),new O(`Batch upload files failed: ${y.message}`,{userId:t,cId:i,originalError:y.message})}}async function ke(t,i,e,l=null){const a=Date.now(),o=`computer:${t}:${i}`,m=ie(l);if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!m&&!l?.workspaceDir)throw new O("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const s=String(t),n=String(i),y=e&&e.trim()?e.trim():null,f=y||_(l,s,n);if(!c.existsSync(f)){const S=`${s}_${n}.zip`;u(o,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:f,userId:s,cId:n,zipFileName:S});const I=re("zip",{zlib:{level:9}});return I.append(null,{name:`${s}_${n}/`,type:"directory"}),I.on("warning",R=>{if(R.code==="ENOENT")u(o,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw u(o,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),I.on("error",R=>{u(o,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:I,zipFileName:S}}const r=`${s}_${n}.zip`;u(o,"DEBUG","Start creating workspace directory zip",{targetDir:f,zipFileName:r});const h=re("zip",{zlib:{level:9}}),w=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],p=P.TRAVERSE_EXCLUDE_DIRS||[],g=await ae(f,w,p,o);if(g>X){const S=X/1024/1024,I=(g/1024/1024).toFixed(2);throw u(o,"WARN","Download rejected due to oversized workspace",{targetDir:f,downloadableSize:g,maxSizeBytes:X}),new E(`Download failed: total file size ${I}MB exceeds limit ${S}MB`,{field:"downloadSize",downloadableSize:g,maxSizeBytes:X})}return h.directory(f,`${s}_${n}`,S=>{const I=S.name||"",R=I.split(/[\/\\]/).filter(Boolean);if(R.some(F=>F.startsWith(".")))return!1;const v=R[R.length-1];if(w.includes(v)||R.some(F=>p.includes(F)))return!1;try{const F=d.join(f,I),D=c.lstatSync(F);if(D.isSymbolicLink()||D.nlink>1)return!1}catch(F){return u(o,"WARN","Error occurred when detecting link file, skipping",{filePath:I,error:F.message}),!1}return S}),h.on("warning",S=>{if(S.code==="ENOENT")u(o,"WARN","Encountered file problem when creating zip",{message:S.message,code:S.code});else throw u(o,"ERROR","Encountered warning when creating zip",{message:S.message,code:S.code}),S}),h.on("error",S=>{u(o,"ERROR","Failed to create zip",{message:S.message,elapsedMs:Date.now()-a})}),h.on("end",()=>{u(o,"INFO","Workspace directory zip created successfully",{targetDir:f,zipFileName:r,elapsedMs:Date.now()-a})}),{archive:h,zipFileName:r}}async function be(t,i,e=200,l=null){const a=Date.now(),o=`computer:${t}:${i}`;if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});const m=String(t),s=String(i),n=ge(l,m,s);if(!n)return u(o,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};if(!c.existsSync(n))return u(o,"DEBUG","Log directory does not exist",{logDir:n}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const f=(await c.promises.readdir(n,{withFileTypes:!0})).filter(D=>D.isFile()).map(D=>D.name);if(f.length===0)return u(o,"DEBUG","No log file found",{logDir:n}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const r=[];for(const D of f){const z=d.join(n,D),$=await c.promises.stat(z);r.push({name:D,fullPath:z,mtime:$.mtimeMs,size:$.size})}r.sort((D,z)=>z.mtime-D.mtime);const h=r[0],p=(await c.promises.readFile(h.fullPath,"utf8")).split(`
|
|
2
|
+
`).filter(D=>D.length>0),g=p.length,S=Math.max(1,e),I=Math.max(0,g-S),R=I+1,F=p.slice(I).map((D,z)=>({line:R+z,content:D}));return u(o,"DEBUG","Get latest logs",{fileName:h.name,fileSize:h.size,totalLines:g,returnedLines:F.length,elapsedMs:Date.now()-a}),{success:!0,message:"Get log successfully",logs:F,totalLines:g,startIndex:R,logFileName:h.name}}async function fe(t,i){try{const l=(await c.promises.readdir(t,{withFileTypes:!0})).filter(s=>!s.name.startsWith(".")&&s.name!=="node_modules");if(l.length!==1||!l[0].isDirectory())return;const a=d.join(t,l[0].name),o=d.join(t,`..tmp_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{await c.promises.rename(a,o)}catch(s){if(s.code==="EXDEV")await c.promises.cp(a,o,{recursive:!0}),await c.promises.rm(a,{recursive:!0,force:!0});else throw s}const m=await c.promises.readdir(o);for(const s of m){const n=d.join(o,s),y=d.join(t,s);try{await c.promises.rename(n,y)}catch(f){if(f.code==="EXDEV")(await c.promises.lstat(n)).isDirectory()?await we(n,y):(await c.promises.copyFile(n,y),await c.promises.unlink(n));else throw f}}await c.promises.rm(o,{recursive:!0,force:!0}),u(i,"INFO","Removed single top-level directory from imported zip",{removedDir:l[0].name})}catch(e){u(i,"WARN","Failed to remove top-level directory from imported zip, continuing",{error:e.message})}}async function xe(t,i){if(!c.existsSync(t)){await c.promises.mkdir(t,{recursive:!0});return}const e=await c.promises.readdir(t,{withFileTypes:!0});for(const l of e){if(j.has(l.name))continue;const a=d.join(t,l.name);await c.promises.rm(a,{recursive:!0,force:!0}),u(i,"DEBUG","Removed workspace entry during import",{name:l.name})}}async function Ne(t,i,e){if(await c.promises.mkdir(i,{recursive:!0}),!c.existsSync(t)){await c.promises.mkdir(t,{recursive:!0});return}const l=await c.promises.readdir(t,{withFileTypes:!0});for(const a of l){if(j.has(a.name))continue;const o=d.join(t,a.name),m=d.join(i,a.name);await J(o,m),u(e,"DEBUG","Backed up workspace entry before import",{name:a.name})}}async function Pe(t,i,e){if(!c.existsSync(t))return;const l=await c.promises.readdir(t,{withFileTypes:!0});for(const a of l){if(j.has(a.name))continue;const o=d.join(t,a.name),m=d.join(i,a.name);await J(o,m)}u(e,"INFO","Workspace restored from backup after import failure")}async function ze(t,i,e){const l=await c.promises.readdir(t,{withFileTypes:!0}),a=[];try{for(const o of l){if(j.has(o.name)){u(e,"INFO","Skipping preserved entry from imported zip",{name:o.name});continue}const m=d.join(t,o.name),s=d.join(i,o.name);await J(m,s),a.push(o.name)}}catch(o){throw o.mergedEntries=a,o}}async function Ce(t,i,e,l,a=null){const o=Date.now(),m=`computer:${t}:${i}`,s=ie(a);if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!e||!e.path)throw new E("file is required",{field:"file"});if(!s&&!a?.workspaceDir)throw new O("COMPUTER_WORKSPACE_DIR is not configured");if(d.extname(e.originalname||e.filename||"").toLowerCase()!==".zip")throw new E("Only zip files are supported",{field:"file",originalName:e.originalname});const y=String(t),f=String(i),r=l&&l.trim()?l.trim():_(a,y,f),h=d.join(r,".tmp"),w=d.join(h,`import_project_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);let p=null;u(m,"INFO","Start importing project from zip",{userId:y,cId:f,targetDir:r,fileName:e.originalname});try{await c.promises.mkdir(r,{recursive:!0}),await c.promises.mkdir(h,{recursive:!0}),await c.promises.mkdir(w,{recursive:!0}),await he(e.path,w),await fe(w,m),p=d.join(h,`import_backup_${Date.now()}_${Math.round(Math.random()*1e6)}`),await Ne(r,p,m);try{await ze(w,r,m)}catch(g){throw u(m,"ERROR","Merge imported project failed, restoring workspace",{error:g.message,mergedEntries:g.mergedEntries||[]}),await xe(r,m),await Pe(p,r,m),g}return c.existsSync(p)&&(await c.promises.rm(p,{recursive:!0,force:!0}),p=null),u(m,"INFO","Project imported successfully",{userId:y,cId:f,targetDir:r,elapsedMs:Date.now()-o}),{success:!0,message:"Project imported successfully",userId:y,cId:f,targetDir:r}}catch(g){throw u(m,"ERROR","Failed to import project",{userId:y,cId:f,targetDir:r,error:g.message,elapsedMs:Date.now()-o}),g instanceof E||g instanceof O||g instanceof pe?g:new O(`Failed to import project: ${g.message}`,{userId:y,cId:f,originalError:g.message})}finally{if(c.existsSync(w))try{await c.promises.rm(w,{recursive:!0,force:!0})}catch(g){u(m,"WARN","Failed to clean import extract directory",{extractRoot:w,error:g.message})}if(p&&c.existsSync(p))try{await c.promises.rm(p,{recursive:!0,force:!0})}catch(g){u(m,"WARN","Failed to clean import backup directory",{backupDir:p,error:g.message})}if(e?.path&&c.existsSync(e.path))try{await c.promises.unlink(e.path)}catch(g){u(m,"WARN","Failed to clean uploaded zip file",{tempZipPath:e.path,error:g.message})}}}async function Le(t,i,e,l,a,o=null){const m=`computer:${t}:${i}`;if(!e||typeof e!="string"||!e.trim())throw new E("fileName cannot be empty",{field:"fileName"});if(l!=null&&typeof l!="string")throw new E("content must be a string",{field:"content"});const s=e.trim(),n=l??"";return u(m,"INFO","Generate file from text content",{userId:t,cId:i,fileName:s,contentLength:n.length}),{...await ee(t,i,{contents:n,originalname:d.basename(s),size:Buffer.byteLength(n,"utf8")},s,a,o),message:"File generated successfully",fileName:s}}export{Re as getFileList,Se as resolveExistingFile,De as searchFiles,Ie as updateFiles,ee as uploadFile,ve as uploadFiles,Le as generateFile,ke as downloadAllFiles,be as getLatestLogs,Ce as importProject,j as IMPORT_PROJECT_PRESERVED_ENTRIES,fe as removeTopLevelDir};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import n from"fs";import o from"path";import{exec as Pe}from"child_process";import je from"cross-spawn";import Ee from"archiver";import X from"../../appConfig/index.js";import{extractZip as J}from"../common/zipUtils.js";import{ValidationError as m,SystemError as U,FileError as Q}from"../error/errorHandler.js";import{log as r}from"../log/logUtils.js";import{createPnpmNpmrc as Fe}from"../common/npmrcUtils.js";import{ensurePrimaryAgentDirs as fe,syncAgents as ce,linkWorkspaceToAgentStore as we,isWorkspaceSkillsSymlinked as Ae}from"../common/AgentWorkspaceUtils.js";import{ensureAgentStoreDirs as he,tryAcquireAgentStoreLock as pe,releaseAgentStoreLock as ge,pruneAgentSkills as Oe,installSkillDir as te,replaceAgentsDir as $e,agentSkillExists as ze}from"../common/agentStoreUtils.js";import{writeAgentHookConfigs as ke}from"./hookConfigUtils.js";function se(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>typeof t=="string"?t.trim():t&&typeof t=="object"&&typeof t.url=="string"?t.url.trim():"").filter(Boolean);if(typeof e=="object")return Object.values(e).map(t=>typeof t=="string"?t.trim():"").filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);return se(i)}catch{}return[t]}return[]}function ye(e){if(!e)return[];if(Array.isArray(e)){const t=[];for(const i of e)if(typeof i=="string"&&i.trim())t.push({name:null,url:i.trim()});else if(i&&typeof i=="object"){const a=typeof i.url=="string"?i.url.trim():"",s=i.name!=null?String(i.name).trim():"";a&&t.push({name:s||null,url:a})}return t}if(typeof e=="object")return Object.entries(e).map(([t,i])=>({name:String(t||"").trim()||null,url:typeof i=="string"?i.trim():""})).filter(t=>t.url);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{return ye(JSON.parse(t))}catch{return[{name:null,url:t}]}}return[]}function ve(e){if(!e)return{};let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return{}}if(!t||typeof t!="object"||Array.isArray(t))return{};const i={};for(const[a,s]of Object.entries(t)){const l=String(a||"").trim(),c=typeof s=="string"?s.trim():"";l&&c&&(i[l]=c)}return i}function Se(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>String(t||"").trim()).filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);if(Array.isArray(i))return i.map(a=>String(a||"").trim()).filter(Boolean)}catch{}return t.split(",").map(i=>i.trim()).filter(Boolean)}return[]}async function ae(e,t,i){let a;try{a=await fetch(e)}catch(d){throw new Q(`Failed to download skill zip from url: ${e}`,{url:e,reason:d.message})}if(!a.ok)throw new Q(`Failed to download skill zip from url: ${e}`,{url:e,status:a.status,statusText:a.statusText});const s=a.headers.get("content-type")||"";s&&!s.includes("zip")&&!s.includes("octet-stream")&&r(i,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:s});const l=await a.arrayBuffer(),c=Buffer.from(l);await n.promises.writeFile(t,c)}async function q(e="computer"){const t=X.COMPUTER_WORKSPACE_DIR;if(!t)throw new m("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return n.existsSync(t)||(await n.promises.mkdir(t,{recursive:!0}),r(e,"INFO","Created user workspace root directory",{workspaceRoot:t})),t}async function I(e,t){const i=o.join(e,t);if(n.existsSync(i)&&(await n.promises.lstat(i)).isDirectory())return i;const a=await n.promises.readdir(e,{withFileTypes:!0});for(const s of a){if(!s.isDirectory())continue;const l=o.join(e,s.name),c=o.join(l,t);if(n.existsSync(c)&&(await n.promises.lstat(c)).isDirectory())return c}return null}async function mt(e){return I(e,"skills")}const Me=".dynamic_add.lock";function We(e){const t=o.join(e,Me);return n.existsSync(t)&&n.statSync(t).isFile()}async function H(e){n.existsSync(e)&&await n.promises.rm(e,{recursive:!0,force:!0})}async function V(e,t){try{await n.promises.rename(e,t)}catch(i){if(i.code==="EXDEV"){async function a(s,l){if((await n.promises.lstat(s)).isDirectory()){await n.promises.mkdir(l,{recursive:!0});const d=await n.promises.readdir(s);for(const p of d)await a(o.join(s,p),o.join(l,p))}else await n.promises.copyFile(s,l)}await a(e,t),await n.promises.rm(e,{recursive:!0,force:!0})}else throw i}}async function de(e){const i=(await n.promises.readdir(e,{withFileTypes:!0})).filter(s=>s.isDirectory()&&!s.name.startsWith("."));return i.find(s=>s.name==="skills")?(await n.promises.readdir(o.join(e,"skills"),{withFileTypes:!0})).filter(l=>l.isDirectory()&&!l.name.startsWith(".")).map(l=>({name:l.name,sourcePath:o.join(e,"skills",l.name)})):i.map(s=>({name:s.name,sourcePath:o.join(e,s.name)}))}const ie=8;async function ne(e,t,i){if(!e||e.length===0)return;const a=Math.max(1,Math.min(t,e.length));let s=0;await Promise.all(Array.from({length:a},async()=>{for(;;){const l=s++;if(l>=e.length)return;await i(e[l],l)}}))}async function be(e){const{userId:t,cId:i,agentId:a,file:s,skillUrls:l,skillUrlMap:c,skillNames:d,updateSkillNames:p,mcpServersConfig:D,permissionsConfig:x,hooksConfig:f,hookScripts:g}=e,u=Date.now(),h=`computer:${t}:${i}`,W=ve(c),_=ye(l),A=Se(d),k=p!=null,z=new Set(Se(p)),b=[],y=[],R=new Set,O=new Set;let E=null,v=!1;if(!t)throw new m("userId cannot be empty",{field:"userId"});if(!i)throw new m("cId cannot be empty",{field:"cId"});if(!a)throw new m("agentId cannot be empty",{field:"agentId"});const C=await q(h),S=o.join(C,String(t),String(i)),j=o.join(S,".tmp");await n.promises.mkdir(S,{recursive:!0}),await n.promises.mkdir(j,{recursive:!0});const{agentStorePath:N,skillsDir:T,agentsDir:ee}=await he(t,a,h),M=F=>!F||!k||z.has(F)?!0:!ze(T,F),G=async(F,P,B)=>{const K=o.join(j,`skill_url_${Date.now()}_${B}_${Math.round(Math.random()*1e6)}.zip`);b.push(K);const Z=o.join(j,`skill_url_extract_${Date.now()}_${B}_${Math.round(Math.random()*1e6)}`);y.push(Z),await n.promises.mkdir(Z,{recursive:!0}),r(h,"INFO","Start download skill zip from url",{userId:t,cId:i,agentId:a,skillName:P,skillUrl:F}),await ae(F,K,h),await J(K,Z);const L=await de(Z);if(L.length===0){r(h,"WARN","No skill dir found in downloaded zip",{skillUrl:F,destName:P});return}let w=P?L.find($=>$.name===P):null;if(!w&&L.length===1&&(w=L[0]),P&&w){if(!M(P)){O.add(P);return}await te(w.sourcePath,T,P,{asDynamic:!1}),R.add(P),r(h,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:F,skillName:P,zipDirName:w.name});return}for(const $ of L){if(!M($.name)){O.add($.name);continue}await te($.sourcePath,T,$.name,{asDynamic:!1}),R.add($.name),r(h,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:F,skillName:$.name})}};await ke(S,{mcpServersConfig:D,hooksConfig:f,permissionsConfig:x,hookScripts:g},h);try{const F=await pe(N,h);if(!F.acquired)v=!0;else{E=F.lockPath;const B=Date.now();let K=null;if(s){if(!s.path)throw new m("Uploaded file has no valid path",{field:"file.path"});if(o.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:s.originalname});const w=o.join(j,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);y.push(w),await n.promises.mkdir(w,{recursive:!0}),await J(s.path,w);const $=await I(w,"skills");if($){const le=(await n.promises.readdir($,{withFileTypes:!0})).filter(Y=>Y.isDirectory());await ne(le,ie,async Y=>{if(!M(Y.name)){O.add(Y.name);return}await te(o.join($,Y.name),T,Y.name,{asDynamic:!1}),R.add(Y.name)})}K=await I(w,"agents")}const Z=Object.entries(W);if(Z.length>0){const L=[];for(const[w,$]of Z){if(!M(w)){O.add(w),r(h,"INFO","Skip download skill zip (already in agent store)",{userId:t,cId:i,agentId:a,skillName:w,skillUrl:$});continue}L.push({skillName:w,skillUrl:$})}await ne(L,ie,async(w,$)=>{await G(w.skillUrl,w.skillName,$)})}else{const L=[];for(let w=0;w<_.length;w++){const{name:$,url:le}=_[w];if($&&!M($)){O.add($);continue}L.push({skillUrl:le,hintedName:$,index:w})}await ne(L,ie,async w=>{await G(w.skillUrl,w.hintedName,w.index)})}await $e(K,ee),await Oe(T,A,h),r(h,"INFO","Agent store resources prepared",{userId:t,cId:i,agentId:a,selectiveInstall:k,updatedSkills:Array.from(R),skippedSkills:Array.from(O),updateSkillNames:Array.from(z),keepSkillNames:A,skillUrlMapCount:Z.length,prepareElapsedMs:Date.now()-B})}const P=await we(S,T,ee,h);return r(h,"INFO","Workspace created successfully (agent store)",{userId:t,cId:i,agentId:a,agentStorePath:N,updatedSkills:Array.from(R),skippedSkills:Array.from(O),skippedStoreUpdate:v,linkElapsedMs:P?.elapsedMs,elapsedMs:Date.now()-u}),{message:v?"Workspace linked to agent store (store update skipped, lock held)":"Workspace created successfully, linked to agent store",workspaceRoot:C,agentStorePath:N,updatedSkills:Array.from(R),skippedSkills:Array.from(O),skippedStoreUpdate:v}}catch(F){throw r(h,"ERROR","Failed to create workspace with agent store",{userId:t,cId:i,agentId:a,error:F.message,elapsedMs:Date.now()-u}),F instanceof m||F instanceof Q||F instanceof U?F:new U(`Failed to create workspace: ${F.message}`,{userId:t,cId:i,agentId:a})}finally{await ge(E,h);const F=Date.now();for(const P of y)try{n.existsSync(P)&&await n.promises.rm(P,{recursive:!0,force:!0})}catch(B){r(h,"WARN","Failed to clean up temporary extracted zip",{error:B.message})}for(const P of b)try{n.existsSync(P)&&await n.promises.unlink(P)}catch(B){r(h,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:P,error:B.message})}try{s&&s.path&&n.existsSync(s.path)&&await n.promises.unlink(s.path)}catch(P){r(h,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:P.message})}r(h,"INFO","Workspace temp cleanup completed",{userId:t,cId:i,agentId:a,elapsedMs:Date.now()-F,totalElapsedMs:Date.now()-u})}}async function Ce(e,t,i,a,s,l,c,d,p,D,x,f){if(p!=null&&String(p).trim()!=="")return be({userId:e,cId:t,agentId:p,file:i,skillUrls:a,skillUrlMap:f,skillNames:D,updateSkillNames:x,mcpServersConfig:s,permissionsConfig:l,hooksConfig:c,hookScripts:d});const g=Date.now(),u=`computer:${e}:${t}`,h=se(a),W=[],_=[],A=new Set;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});const k=await q(u),z=o.join(k,String(e),String(t),".tmp"),b=o.join(k,String(e),String(t)),{skillsDir:y,agentsDir:R,agentTypes:O}=await fe(b);n.existsSync(b)||await n.promises.mkdir(b,{recursive:!0});const E=o.join(z,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(n.existsSync(y)){const j=(await n.promises.readdir(y,{withFileTypes:!0})).filter(N=>N.isDirectory()&&We(o.join(y,N.name)));if(j.length>0){await n.promises.mkdir(E,{recursive:!0});for(const N of j){const T=o.join(y,N.name),ee=o.join(E,N.name);await V(T,ee)}r(u,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:j.map(N=>N.name)})}}if(await H(y),await H(R),await n.promises.mkdir(y,{recursive:!0}),await n.promises.mkdir(R,{recursive:!0}),n.existsSync(E)){const S=await n.promises.readdir(E,{withFileTypes:!0});for(const j of S)if(j.isDirectory()){const N=o.join(E,j.name),T=o.join(y,j.name);await V(N,T)}await H(E)}const v=n.existsSync(y),C=n.existsSync(R);if(r(u,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:y,targetAgentsDir:R,agentTypes:O,skillsExists:v,agentsExists:C}),await ke(b,{mcpServersConfig:s,hooksConfig:c,permissionsConfig:l,hookScripts:d},u),!i&&h.length===0){const S=await ce(b,u);return r(u,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:k,skillsDir:null,agentsDir:null,agentTypes:O,syncAgentsElapsedMs:S?.elapsedMs,elapsedMs:Date.now()-g}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:k}}if(i){if(!i.path)throw new m("Uploaded file has no valid path",{field:"file.path"});if(o.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:i.originalname})}r(u,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:k,hasUploadedZip:!!i,skillUrlsCount:h.length});try{n.existsSync(z)||await n.promises.mkdir(z,{recursive:!0});const S=[];if(i){const M=o.join(z,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);_.push(M),await n.promises.mkdir(M,{recursive:!0}),r(u,"DEBUG","Start extracting uploaded zip file",{extractRoot:M}),await J(i.path,M),r(u,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:M});const G=await I(M,"skills"),F=await I(M,"agents");if(G){await n.promises.mkdir(y,{recursive:!0});const P=await n.promises.readdir(G,{withFileTypes:!0});for(const B of P){if(!B.isDirectory())continue;const K=o.join(G,B.name),Z=o.join(y,B.name);n.existsSync(Z)&&await H(Z),await V(K,Z),A.add(B.name)}S.push("skills"),r(u,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetSkillsDir:y,agentTypes:O})}else r(u,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:M});F?(await H(R),await V(F,R),S.push("agents"),r(u,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetAgentsDir:R,agentTypes:O})):r(u,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:M})}for(let M=0;M<h.length;M+=1){const G=h[M],F=o.join(z,`skill_url_${Date.now()}_${M}_${Math.round(Math.random()*1e6)}.zip`);W.push(F);const P=o.join(z,`skill_url_extract_${Date.now()}_${M}_${Math.round(Math.random()*1e6)}`);_.push(P),await n.promises.mkdir(P,{recursive:!0}),r(u,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:G}),await ae(G,F,u),r(u,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:G,downloadedZipPath:F}),await J(F,P);const K=(await n.promises.readdir(P,{withFileTypes:!0})).filter(w=>w.isDirectory()&&!w.name.startsWith(".")),L=K.find(w=>w.name==="skills")?(await n.promises.readdir(o.join(P,"skills"),{withFileTypes:!0})).filter(w=>w.isDirectory()&&!w.name.startsWith(".")).map(w=>({name:w.name,sourcePath:o.join(P,"skills",w.name)})):K.map(w=>({name:w.name,sourcePath:o.join(P,w.name)}));if(L.length===0){r(u,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:G,extractRoot:P});continue}await n.promises.mkdir(y,{recursive:!0});for(const w of L){const $=o.join(y,w.name);n.existsSync($)&&await H($),await V(w.sourcePath,$),A.add(w.name),r(u,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:G,skillName:w.name,destSkillPath:$})}S.includes("skills")||S.push("skills")}S.length===0&&r(u,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!i,skillUrlsCount:h.length});const j=Array.from(A),N=S.length>0?`Workspace created successfully, ${S.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)",T=Date.now()-g;r(u,"INFO","Workspace resources prepared",{userId:e,cId:t,updatedDirs:S,updatedSkills:j,agentTypes:O,prepareElapsedMs:T});const ee=await ce(b,u);return r(u,"INFO",N,{userId:e,cId:t,updatedDirs:S,updatedSkills:j,agentTypes:O,prepareElapsedMs:T,syncAgentsElapsedMs:ee?.elapsedMs,elapsedMs:Date.now()-g}),{message:N,workspaceRoot:k,updatedSkills:j}}catch(S){throw r(u,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:S.message,elapsedMs:Date.now()-g}),S instanceof m||S instanceof Q||S instanceof U?S:new U(`Failed to create workspace: ${S.message}`,{userId:e,cId:t})}finally{const S=Date.now();try{for(const j of _)n.existsSync(j)&&await n.promises.rm(j,{recursive:!0,force:!0})}catch(j){r(u,"WARN","Failed to clean up temporary extracted zip",{error:j.message})}for(const j of W)try{n.existsSync(j)&&await n.promises.unlink(j)}catch(N){r(u,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:j,error:N.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(j){r(u,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:j.message})}r(u,"INFO","Workspace temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-S,totalElapsedMs:Date.now()-g})}}async function Te(e,t,i,a,s){const l=Date.now(),c=`computer:${e}:${t}`,d=se(s),p=[],D=[],x=new Set;let f=null;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i)throw new m("agentId cannot be empty",{field:"agentId"});if(!a&&d.length===0)throw new m("file or skillUrls cannot both be empty",{field:"file|skillUrls"});const g=await q(c),u=o.join(g,String(e),String(t)),h=o.join(u,".tmp");await n.promises.mkdir(u,{recursive:!0}),await n.promises.mkdir(h,{recursive:!0});const{agentStorePath:W,skillsDir:_,agentsDir:A}=await he(e,i,c);try{let k=await pe(W,c);if(!k.acquired)for(let R=1;R<=5&&!k.acquired;R++)await new Promise(O=>setTimeout(O,200*R)),k=await pe(W,c);if(!k.acquired)throw new U("Agent store is busy, please retry",{userId:e,cId:t,agentId:i});if(f=k.lockPath,a){if(!a.path)throw new m("Uploaded file has no valid path",{field:"file.path"});const R=o.join(h,`push_skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);D.push(R),await n.promises.mkdir(R,{recursive:!0}),await J(a.path,R);const O=await de(R),E=await I(R,"skills"),v=E?(await n.promises.readdir(E,{withFileTypes:!0})).filter(C=>C.isDirectory()).map(C=>({name:C.name,sourcePath:o.join(E,C.name)})):O;await ne(v,ie,async C=>{await te(C.sourcePath,_,C.name,{asDynamic:!0}),x.add(C.name)})}await ne(d,ie,async(R,O)=>{const E=o.join(h,`push_skill_url_${Date.now()}_${O}_${Math.round(Math.random()*1e6)}.zip`);p.push(E);const v=o.join(h,`push_skill_url_extract_${Date.now()}_${O}_${Math.round(Math.random()*1e6)}`);D.push(v),await n.promises.mkdir(v,{recursive:!0}),await ae(R,E,c),await J(E,v);const C=await de(v);for(const S of C)await te(S.sourcePath,_,S.name,{asDynamic:!0}),x.add(S.name)});const z=await we(u,_,A,c),b=Array.from(x),y=b.length>0?`Pushed ${b.length} skills to agent store: ${b.join(", ")}`:"No valid skill directories found in file or skillUrls";return r(c,"INFO",y,{userId:e,cId:t,agentId:i,updatedSkills:b,linkElapsedMs:z?.elapsedMs,elapsedMs:Date.now()-l}),{message:y,workspaceRoot:g,agentStorePath:W,updatedSkills:b}}catch(k){throw r(c,"ERROR","Failed to push skills to agent store",{userId:e,cId:t,agentId:i,error:k.message,elapsedMs:Date.now()-l}),k instanceof m||k instanceof Q||k instanceof U?k:new U(`Failed to push skill to workspace: ${k.message}`,{userId:e,cId:t,agentId:i})}finally{await ge(f,c);for(const k of D)try{n.existsSync(k)&&await n.promises.rm(k,{recursive:!0,force:!0})}catch(z){r(c,"WARN","Failed to clean up temporary extracted zip",{error:z.message})}for(const k of p)try{n.existsSync(k)&&await n.promises.unlink(k)}catch(z){r(c,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:k,error:z.message})}try{a&&a.path&&n.existsSync(a.path)&&await n.promises.unlink(a.path)}catch(k){r(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:a?.path,error:k.message})}}}async function Le(e,t,i,a,s){if(s!=null&&String(s).trim()!==""){const _=X.COMPUTER_WORKSPACE_DIR,A=_?o.join(_,String(e),String(t)):null;if(Ae(A))return Te(e,t,s,i,a);r(`computer:${e}:${t}`,"INFO","Push skills: agentId present but workspace not symlinked, use legacy path",{userId:e,cId:t,agentId:s,userWorkspaceRoot:A})}const c=Date.now(),d=`computer:${e}:${t}`,p=se(a),D=[],x=[];if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i&&p.length===0)throw new m("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(i){if(!i.path)throw new m("Uploaded file has no valid path",{field:"file.path"});if(o.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:i?.originalname})}const f=await q(d),g=o.join(f,String(e),String(t),".tmp"),u=o.join(f,String(e),String(t)),{skillsDir:h,agentTypes:W}=await fe(u);try{n.existsSync(u)||await n.promises.mkdir(u,{recursive:!0}),n.existsSync(h)||await n.promises.mkdir(h,{recursive:!0}),n.existsSync(g)||await n.promises.mkdir(g,{recursive:!0});const _=[],A=new Set;if(i){const y=o.join(g,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);x.push(y),await n.promises.mkdir(y,{recursive:!0}),r(d,"DEBUG","Start extracting skill zip file",{extractRoot:y}),await J(i.path,y),r(d,"DEBUG","Skill zip file extracted successfully",{extractRoot:y});const R=await I(y,"skills");if(!R)r(d,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:y});else{const E=(await n.promises.readdir(R,{withFileTypes:!0})).filter(v=>v.isDirectory()&&!v.name.startsWith("."));if(E.length===0)r(d,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:R});else for(const v of E){const C=o.join(R,v.name),S=o.join(h,v.name);n.existsSync(S)&&await H(S),await V(C,S),A.add(v.name),r(d,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:v.name,destSkillPath:S})}}}for(let y=0;y<p.length;y+=1){const R=p[y],O=o.join(g,`skill_push_url_${Date.now()}_${y}_${Math.round(Math.random()*1e6)}.zip`);D.push(O);const E=o.join(g,`skill_push_url_extract_${Date.now()}_${y}_${Math.round(Math.random()*1e6)}`);x.push(E),await n.promises.mkdir(E,{recursive:!0}),r(d,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:R}),await ae(R,O,d),await J(O,E);const C=(await n.promises.readdir(E,{withFileTypes:!0})).filter(N=>N.isDirectory()&&!N.name.startsWith(".")),j=C.find(N=>N.name==="skills")?(await n.promises.readdir(o.join(E,"skills"),{withFileTypes:!0})).filter(N=>N.isDirectory()&&!N.name.startsWith(".")).map(N=>({name:N.name,sourcePath:o.join(E,"skills",N.name)})):C.map(N=>({name:N.name,sourcePath:o.join(E,N.name)}));if(j.length===0){r(d,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:R,extractRoot:E});continue}for(const N of j){const T=o.join(h,N.name);n.existsSync(T)&&await H(T),await V(N.sourcePath,T),A.add(N.name),r(d,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:R,skillName:N.name,destSkillPath:T})}}for(const y of A)_.push(y);const k=_.length>0?`Pushed ${_.length} skills: ${_.join(", ")}`:"No valid skill directories found in file or skillUrls",z=Date.now()-c;r(d,"INFO","Push skills resources prepared",{userId:e,cId:t,updatedSkills:_,agentTypes:W,prepareElapsedMs:z});const b=await ce(u,d);return r(d,"INFO",k,{userId:e,cId:t,updatedSkills:_,agentTypes:W,prepareElapsedMs:z,syncAgentsElapsedMs:b?.elapsedMs,elapsedMs:Date.now()-c}),{message:k,workspaceRoot:f,updatedSkills:_}}catch(_){throw r(d,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:_.message,elapsedMs:Date.now()-c}),_ instanceof m||_ instanceof Q||_ instanceof U?_:new U(`Failed to push skill to workspace: ${_.message}`,{userId:e,cId:t})}finally{const _=Date.now();try{for(const A of x)n.existsSync(A)&&await n.promises.rm(A,{recursive:!0,force:!0})}catch(A){r(d,"WARN","Failed to clean up temporary extracted zip",{error:A.message})}for(const A of D)try{n.existsSync(A)&&await n.promises.unlink(A)}catch(k){r(d,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:A,error:k.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(A){r(d,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:A.message})}r(d,"INFO","Push skills temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-_,totalElapsedMs:Date.now()-c})}}async function Be(e,t,i,a){const s=Date.now(),l=`computer:${e}:${t}`;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i||!i.path)throw new m("file is required",{field:"file"});if(o.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:i.originalname});const d=await q(l),p=o.join(d,String(e),String(t)),D=o.join(p,".tmp"),x=o.join(D,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{n.existsSync(p)||await n.promises.mkdir(p,{recursive:!0}),n.existsSync(D)||await n.promises.mkdir(D,{recursive:!0}),await n.promises.mkdir(x,{recursive:!0}),r(l,"DEBUG","Start extracting template zip file",{extractRoot:x}),await J(i.path,x),r(l,"DEBUG","Template zip file extracted successfully",{extractRoot:x});const f=await n.promises.readdir(x,{withFileTypes:!0});for(const g of f){const u=o.join(x,g.name),h=o.join(p,g.name);if(g.isDirectory())await V(u,h);else{const W=o.dirname(h);n.existsSync(W)||await n.promises.mkdir(W,{recursive:!0}),await n.promises.copyFile(u,h)}}if(r(l,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:p,fileCount:f.length}),X.GIT_ENABLED&&(a==="true"||a===!0)){const g=await import("../../service/gitService.js");await g.default.init({workspaceType:"taskAgent",userId:e,cId:t}),await g.default.commit({workspaceType:"taskAgent",userId:e,cId:t,message:"Initial commit"}),r(l,"INFO","Git init and initial commit done",{userId:e,cId:t})}return r(l,"INFO","Init project template completed",{userId:e,cId:t,targetDir:p,elapsedMs:Date.now()-s}),{message:"Project template initialized successfully",workspaceRoot:p}}catch(f){throw r(l,"ERROR","Failed to init project template",{userId:e,cId:t,error:f.message,elapsedMs:Date.now()-s}),f instanceof m||f instanceof Q||f instanceof U?f:new U(`Failed to init project template: ${f.message}`,{userId:e,cId:t})}finally{try{n.existsSync(x)&&await n.promises.rm(x,{recursive:!0,force:!0})}catch(f){r(l,"WARN","Failed to clean up temporary extracted zip",{error:f.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(f){r(l,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:f.message})}}}async function Ue(e,t,i){if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i||typeof i!="string"||!i.trim())throw new m("command cannot be empty",{field:"command"});const a=await q("computer"),s=o.join(a,String(e),String(t));if(!n.existsSync(s))throw new m("workspace directory does not exist",{field:"workDir",workDir:s});const l=`computer:${e}:${t}`;r(l,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:s,command:i});const c=10*60*1e3,d={cwd:s,timeout:c,maxBuffer:50*1024*1024};return X.BASH_PATH&&(d.shell=X.BASH_PATH),new Promise((p,D)=>{Pe(i,d,(x,f,g)=>{const u=x?x.killed?-1:x.code||1:0,h=x&&x.killed?(g||"")+`
|
|
2
|
-
Command timed out after ${
|
|
3
|
-
Failed to spawn ${e}: ${
|
|
4
|
-
Process killed by signal ${D} (timeout after ${
|
|
5
|
-
`);for(const
|
|
6
|
-
`,"utf8"),r(t,"INFO","Removed conflicting pnpm built dependency settings from package.json",{projectDir:e,removedKeys:
|
|
7
|
-
`),
|
|
8
|
-
`),"utf8"),r(t,"INFO","Removed conflicting pnpm built dependency settings from pnpm-workspace.yaml",{projectDir:e,removedKeys:
|
|
9
|
-
`).filter(
|
|
10
|
-
`);return i!==t&&await n.promises.writeFile(e,i,"utf8"),i}async function
|
|
1
|
+
import n from"fs";import c from"path";import{exec as Ee}from"child_process";import je from"cross-spawn";import Ae from"archiver";import Q from"../../appConfig/index.js";import{extractZip as H}from"../common/zipUtils.js";import{ValidationError as d,SystemError as Z,FileError as I}from"../error/errorHandler.js";import{log as r}from"../log/logUtils.js";import{createPnpmNpmrc as Oe}from"../common/npmrcUtils.js";import{ensurePrimaryAgentDirs as he,syncAgents as de,linkWorkspaceToAgentStore as ke,isWorkspaceSkillsSymlinked as $e}from"../common/AgentWorkspaceUtils.js";import{ensureAgentStoreDirs as ye,tryAcquireAgentStoreLock as ue,releaseAgentStoreLock as ge,pruneAgentSkills as ze,installSkillDir as ie,replaceAgentsDir as Me,agentSkillExists as ve}from"../common/agentStoreUtils.js";import{writeAgentHookConfigs as Se}from"./hookConfigUtils.js";import{ensureWorkspaceDir as J,resolveWorkspaceDir as We,resolveWorkspaceRoot as se}from"./workspaceContext.js";function re(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>typeof t=="string"?t.trim():t&&typeof t=="object"&&typeof t.url=="string"?t.url.trim():"").filter(Boolean);if(typeof e=="object")return Object.values(e).map(t=>typeof t=="string"?t.trim():"").filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);return re(i)}catch{}return[t]}return[]}function De(e){if(!e)return[];if(Array.isArray(e)){const t=[];for(const i of e)if(typeof i=="string"&&i.trim())t.push({name:null,url:i.trim()});else if(i&&typeof i=="object"){const s=typeof i.url=="string"?i.url.trim():"",a=i.name!=null?String(i.name).trim():"";s&&t.push({name:a||null,url:s})}return t}if(typeof e=="object")return Object.entries(e).map(([t,i])=>({name:String(t||"").trim()||null,url:typeof i=="string"?i.trim():""})).filter(t=>t.url);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{return De(JSON.parse(t))}catch{return[{name:null,url:t}]}}return[]}function be(e){if(!e)return{};let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return{}}if(!t||typeof t!="object"||Array.isArray(t))return{};const i={};for(const[s,a]of Object.entries(t)){const o=String(s||"").trim(),p=typeof a=="string"?a.trim():"";o&&p&&(i[o]=p)}return i}function xe(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>String(t||"").trim()).filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);if(Array.isArray(i))return i.map(s=>String(s||"").trim()).filter(Boolean)}catch{}return t.split(",").map(i=>i.trim()).filter(Boolean)}return[]}async function oe(e,t,i){let s;try{s=await fetch(e)}catch(u){throw new I(`Failed to download skill zip from url: ${e}`,{url:e,reason:u.message})}if(!s.ok)throw new I(`Failed to download skill zip from url: ${e}`,{url:e,status:s.status,statusText:s.statusText});const a=s.headers.get("content-type")||"";a&&!a.includes("zip")&&!a.includes("octet-stream")&&r(i,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:a});const o=await s.arrayBuffer(),p=Buffer.from(o);await n.promises.writeFile(t,p)}async function ee(e,t){const i=c.join(e,t);if(n.existsSync(i)&&(await n.promises.lstat(i)).isDirectory())return i;const s=await n.promises.readdir(e,{withFileTypes:!0});for(const a of s){if(!a.isDirectory())continue;const o=c.join(e,a.name),p=c.join(o,t);if(n.existsSync(p)&&(await n.promises.lstat(p)).isDirectory())return p}return null}async function kt(e){return ee(e,"skills")}const Te=".dynamic_add.lock";function Ce(e){const t=c.join(e,Te);return n.existsSync(t)&&n.statSync(t).isFile()}async function V(e){n.existsSync(e)&&await n.promises.rm(e,{recursive:!0,force:!0})}async function Y(e,t){try{await n.promises.rename(e,t)}catch(i){if(i.code==="EXDEV"){async function s(a,o){if((await n.promises.lstat(a)).isDirectory()){await n.promises.mkdir(o,{recursive:!0});const u=await n.promises.readdir(a);for(const l of u)await s(c.join(a,l),c.join(o,l))}else await n.promises.copyFile(a,o)}await s(e,t),await n.promises.rm(e,{recursive:!0,force:!0})}else throw i}}async function me(e){const i=(await n.promises.readdir(e,{withFileTypes:!0})).filter(a=>a.isDirectory()&&!a.name.startsWith("."));return i.find(a=>a.name==="skills")?(await n.promises.readdir(c.join(e,"skills"),{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).map(o=>({name:o.name,sourcePath:c.join(e,"skills",o.name)})):i.map(a=>({name:a.name,sourcePath:c.join(e,a.name)}))}const ne=8;async function ae(e,t,i){if(!e||e.length===0)return;const s=Math.max(1,Math.min(t,e.length));let a=0;await Promise.all(Array.from({length:s},async()=>{for(;;){const o=a++;if(o>=e.length)return;await i(e[o],o)}}))}async function Le(e){const{userId:t,cId:i,agentId:s,file:a,skillUrls:o,skillUrlMap:p,skillNames:u,updateSkillNames:l,mcpServersConfig:D,permissionsConfig:x,hooksConfig:f,hookScripts:y,service:F}=e,m=Date.now(),h=`computer:${t}:${i}`,L=be(p),_=De(o),z=xe(u),k=l!=null,M=new Set(xe(l)),b=[],g=[],R=new Set,O=new Set;let j=null,v=!1;if(!t)throw new d("userId cannot be empty",{field:"userId"});if(!i)throw new d("cId cannot be empty",{field:"cId"});if(!s)throw new d("agentId cannot be empty",{field:"agentId"});const T=se(F),S=await J(F,t,i,h),E=c.join(S,".tmp");await n.promises.mkdir(S,{recursive:!0}),await n.promises.mkdir(E,{recursive:!0});const{agentStorePath:N,skillsDir:C,agentsDir:te}=await ye(t,s,h,F),W=A=>!A||!k||M.has(A)?!0:!ve(C,A),q=async(A,P,U)=>{const K=c.join(E,`skill_url_${Date.now()}_${U}_${Math.round(Math.random()*1e6)}.zip`);b.push(K);const G=c.join(E,`skill_url_extract_${Date.now()}_${U}_${Math.round(Math.random()*1e6)}`);g.push(G),await n.promises.mkdir(G,{recursive:!0}),r(h,"INFO","Start download skill zip from url",{userId:t,cId:i,agentId:s,skillName:P,skillUrl:A}),await oe(A,K,h),await H(K,G);const B=await me(G);if(B.length===0){r(h,"WARN","No skill dir found in downloaded zip",{skillUrl:A,destName:P});return}let w=P?B.find($=>$.name===P):null;if(!w&&B.length===1&&(w=B[0]),P&&w){if(!W(P)){O.add(P);return}await ie(w.sourcePath,C,P,{asDynamic:!1}),R.add(P),r(h,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:s,skillUrl:A,skillName:P,zipDirName:w.name});return}for(const $ of B){if(!W($.name)){O.add($.name);continue}await ie($.sourcePath,C,$.name,{asDynamic:!1}),R.add($.name),r(h,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:s,skillUrl:A,skillName:$.name})}};await Se(S,{mcpServersConfig:D,hooksConfig:f,permissionsConfig:x,hookScripts:y},h);try{const A=await ue(N,h);if(!A.acquired)v=!0;else{j=A.lockPath;const U=Date.now();let K=null;if(a){if(!a.path)throw new d("Uploaded file has no valid path",{field:"file.path"});if(c.extname(a.originalname||a.filename||"").toLowerCase()!==".zip")throw new d("Only zip files are supported",{field:"file",originalName:a.originalname});const w=c.join(E,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);g.push(w),await n.promises.mkdir(w,{recursive:!0}),await H(a.path,w);const $=await ee(w,"skills");if($){const pe=(await n.promises.readdir($,{withFileTypes:!0})).filter(X=>X.isDirectory());await ae(pe,ne,async X=>{if(!W(X.name)){O.add(X.name);return}await ie(c.join($,X.name),C,X.name,{asDynamic:!1}),R.add(X.name)})}K=await ee(w,"agents")}const G=Object.entries(L);if(G.length>0){const B=[];for(const[w,$]of G){if(!W(w)){O.add(w),r(h,"INFO","Skip download skill zip (already in agent store)",{userId:t,cId:i,agentId:s,skillName:w,skillUrl:$});continue}B.push({skillName:w,skillUrl:$})}await ae(B,ne,async(w,$)=>{await q(w.skillUrl,w.skillName,$)})}else{const B=[];for(let w=0;w<_.length;w++){const{name:$,url:pe}=_[w];if($&&!W($)){O.add($);continue}B.push({skillUrl:pe,hintedName:$,index:w})}await ae(B,ne,async w=>{await q(w.skillUrl,w.hintedName,w.index)})}await Me(K,te),await ze(C,z,h),r(h,"INFO","Agent store resources prepared",{userId:t,cId:i,agentId:s,selectiveInstall:k,updatedSkills:Array.from(R),skippedSkills:Array.from(O),updateSkillNames:Array.from(M),keepSkillNames:z,skillUrlMapCount:G.length,prepareElapsedMs:Date.now()-U})}const P=await ke(S,C,te,h);return r(h,"INFO","Workspace created successfully (agent store)",{userId:t,cId:i,agentId:s,agentStorePath:N,updatedSkills:Array.from(R),skippedSkills:Array.from(O),skippedStoreUpdate:v,linkElapsedMs:P?.elapsedMs,elapsedMs:Date.now()-m}),{message:v?"Workspace linked to agent store (store update skipped, lock held)":"Workspace created successfully, linked to agent store",workspaceRoot:T,agentStorePath:N,updatedSkills:Array.from(R),skippedSkills:Array.from(O),skippedStoreUpdate:v}}catch(A){throw r(h,"ERROR","Failed to create workspace with agent store",{userId:t,cId:i,agentId:s,error:A.message,elapsedMs:Date.now()-m}),A instanceof d||A instanceof I||A instanceof Z?A:new Z(`Failed to create workspace: ${A.message}`,{userId:t,cId:i,agentId:s})}finally{await ge(j,h);const A=Date.now();for(const P of g)try{n.existsSync(P)&&await n.promises.rm(P,{recursive:!0,force:!0})}catch(U){r(h,"WARN","Failed to clean up temporary extracted zip",{error:U.message})}for(const P of b)try{n.existsSync(P)&&await n.promises.unlink(P)}catch(U){r(h,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:P,error:U.message})}try{a&&a.path&&n.existsSync(a.path)&&await n.promises.unlink(a.path)}catch(P){r(h,"WARN","Failed to clean up uploaded zip file",{tempZipPath:a?.path,error:P.message})}r(h,"INFO","Workspace temp cleanup completed",{userId:t,cId:i,agentId:s,elapsedMs:Date.now()-A,totalElapsedMs:Date.now()-m})}}async function Be(e,t,i,s,a,o,p,u,l,D,x,f,y=null){if(l!=null&&String(l).trim()!=="")return Le({userId:e,cId:t,agentId:l,file:i,skillUrls:s,skillUrlMap:f,skillNames:D,updateSkillNames:x,mcpServersConfig:a,permissionsConfig:o,hooksConfig:p,hookScripts:u,service:y});const F=Date.now(),m=`computer:${e}:${t}`,h=re(s),L=[],_=[],z=new Set;if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});const k=se(y),M=await J(y,e,t,m),b=c.join(M,".tmp"),{skillsDir:g,agentsDir:R,agentTypes:O}=await he(M);n.existsSync(M)||await n.promises.mkdir(M,{recursive:!0});const j=c.join(b,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(n.existsSync(g)){const E=(await n.promises.readdir(g,{withFileTypes:!0})).filter(N=>N.isDirectory()&&Ce(c.join(g,N.name)));if(E.length>0){await n.promises.mkdir(j,{recursive:!0});for(const N of E){const C=c.join(g,N.name),te=c.join(j,N.name);await Y(C,te)}r(m,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:E.map(N=>N.name)})}}if(await V(g),await V(R),await n.promises.mkdir(g,{recursive:!0}),await n.promises.mkdir(R,{recursive:!0}),n.existsSync(j)){const S=await n.promises.readdir(j,{withFileTypes:!0});for(const E of S)if(E.isDirectory()){const N=c.join(j,E.name),C=c.join(g,E.name);await Y(N,C)}await V(j)}const v=n.existsSync(g),T=n.existsSync(R);if(r(m,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:g,targetAgentsDir:R,agentTypes:O,skillsExists:v,agentsExists:T}),await Se(M,{mcpServersConfig:a,hooksConfig:p,permissionsConfig:o,hookScripts:u},m),!i&&h.length===0){const S=await de(M,m);return r(m,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:k,skillsDir:null,agentsDir:null,agentTypes:O,syncAgentsElapsedMs:S?.elapsedMs,elapsedMs:Date.now()-F}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:k}}if(i){if(!i.path)throw new d("Uploaded file has no valid path",{field:"file.path"});if(c.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new d("Only zip files are supported",{field:"file",originalName:i.originalname})}r(m,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:k,hasUploadedZip:!!i,skillUrlsCount:h.length});try{n.existsSync(b)||await n.promises.mkdir(b,{recursive:!0});const S=[];if(i){const W=c.join(b,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);_.push(W),await n.promises.mkdir(W,{recursive:!0}),r(m,"DEBUG","Start extracting uploaded zip file",{extractRoot:W}),await H(i.path,W),r(m,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:W});const q=await ee(W,"skills"),A=await ee(W,"agents");if(q){await n.promises.mkdir(g,{recursive:!0});const P=await n.promises.readdir(q,{withFileTypes:!0});for(const U of P){if(!U.isDirectory())continue;const K=c.join(q,U.name),G=c.join(g,U.name);n.existsSync(G)&&await V(G),await Y(K,G),z.add(U.name)}S.push("skills"),r(m,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetSkillsDir:g,agentTypes:O})}else r(m,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:W});A?(await V(R),await Y(A,R),S.push("agents"),r(m,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetAgentsDir:R,agentTypes:O})):r(m,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:W})}for(let W=0;W<h.length;W+=1){const q=h[W],A=c.join(b,`skill_url_${Date.now()}_${W}_${Math.round(Math.random()*1e6)}.zip`);L.push(A);const P=c.join(b,`skill_url_extract_${Date.now()}_${W}_${Math.round(Math.random()*1e6)}`);_.push(P),await n.promises.mkdir(P,{recursive:!0}),r(m,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:q}),await oe(q,A,m),r(m,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:q,downloadedZipPath:A}),await H(A,P);const K=(await n.promises.readdir(P,{withFileTypes:!0})).filter(w=>w.isDirectory()&&!w.name.startsWith(".")),B=K.find(w=>w.name==="skills")?(await n.promises.readdir(c.join(P,"skills"),{withFileTypes:!0})).filter(w=>w.isDirectory()&&!w.name.startsWith(".")).map(w=>({name:w.name,sourcePath:c.join(P,"skills",w.name)})):K.map(w=>({name:w.name,sourcePath:c.join(P,w.name)}));if(B.length===0){r(m,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:q,extractRoot:P});continue}await n.promises.mkdir(g,{recursive:!0});for(const w of B){const $=c.join(g,w.name);n.existsSync($)&&await V($),await Y(w.sourcePath,$),z.add(w.name),r(m,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:q,skillName:w.name,destSkillPath:$})}S.includes("skills")||S.push("skills")}S.length===0&&r(m,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!i,skillUrlsCount:h.length});const E=Array.from(z),N=S.length>0?`Workspace created successfully, ${S.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)",C=Date.now()-F;r(m,"INFO","Workspace resources prepared",{userId:e,cId:t,updatedDirs:S,updatedSkills:E,agentTypes:O,prepareElapsedMs:C});const te=await de(M,m);return r(m,"INFO",N,{userId:e,cId:t,updatedDirs:S,updatedSkills:E,agentTypes:O,prepareElapsedMs:C,syncAgentsElapsedMs:te?.elapsedMs,elapsedMs:Date.now()-F}),{message:N,workspaceRoot:k,updatedSkills:E}}catch(S){throw r(m,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:S.message,elapsedMs:Date.now()-F}),S instanceof d||S instanceof I||S instanceof Z?S:new Z(`Failed to create workspace: ${S.message}`,{userId:e,cId:t})}finally{const S=Date.now();try{for(const E of _)n.existsSync(E)&&await n.promises.rm(E,{recursive:!0,force:!0})}catch(E){r(m,"WARN","Failed to clean up temporary extracted zip",{error:E.message})}for(const E of L)try{n.existsSync(E)&&await n.promises.unlink(E)}catch(N){r(m,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:E,error:N.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(E){r(m,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:E.message})}r(m,"INFO","Workspace temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-S,totalElapsedMs:Date.now()-F})}}async function Ue(e,t,i,s,a,o=null){const p=Date.now(),u=`computer:${e}:${t}`,l=re(a),D=[],x=[],f=new Set;let y=null;if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});if(!i)throw new d("agentId cannot be empty",{field:"agentId"});if(!s&&l.length===0)throw new d("file or skillUrls cannot both be empty",{field:"file|skillUrls"});const F=se(o),m=await J(o,e,t,u),h=c.join(m,".tmp");await n.promises.mkdir(m,{recursive:!0}),await n.promises.mkdir(h,{recursive:!0});const{agentStorePath:L,skillsDir:_,agentsDir:z}=await ye(e,i,u,o);try{let k=await ue(L,u);if(!k.acquired)for(let R=1;R<=5&&!k.acquired;R++)await new Promise(O=>setTimeout(O,200*R)),k=await ue(L,u);if(!k.acquired)throw new Z("Agent store is busy, please retry",{userId:e,cId:t,agentId:i});if(y=k.lockPath,s){if(!s.path)throw new d("Uploaded file has no valid path",{field:"file.path"});const R=c.join(h,`push_skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);x.push(R),await n.promises.mkdir(R,{recursive:!0}),await H(s.path,R);const O=await me(R),j=await ee(R,"skills"),v=j?(await n.promises.readdir(j,{withFileTypes:!0})).filter(T=>T.isDirectory()).map(T=>({name:T.name,sourcePath:c.join(j,T.name)})):O;await ae(v,ne,async T=>{await ie(T.sourcePath,_,T.name,{asDynamic:!0}),f.add(T.name)})}await ae(l,ne,async(R,O)=>{const j=c.join(h,`push_skill_url_${Date.now()}_${O}_${Math.round(Math.random()*1e6)}.zip`);D.push(j);const v=c.join(h,`push_skill_url_extract_${Date.now()}_${O}_${Math.round(Math.random()*1e6)}`);x.push(v),await n.promises.mkdir(v,{recursive:!0}),await oe(R,j,u),await H(j,v);const T=await me(v);for(const S of T)await ie(S.sourcePath,_,S.name,{asDynamic:!0}),f.add(S.name)});const M=await ke(m,_,z,u),b=Array.from(f),g=b.length>0?`Pushed ${b.length} skills to agent store: ${b.join(", ")}`:"No valid skill directories found in file or skillUrls";return r(u,"INFO",g,{userId:e,cId:t,agentId:i,updatedSkills:b,linkElapsedMs:M?.elapsedMs,elapsedMs:Date.now()-p}),{message:g,workspaceRoot:F,agentStorePath:L,updatedSkills:b}}catch(k){throw r(u,"ERROR","Failed to push skills to agent store",{userId:e,cId:t,agentId:i,error:k.message,elapsedMs:Date.now()-p}),k instanceof d||k instanceof I||k instanceof Z?k:new Z(`Failed to push skill to workspace: ${k.message}`,{userId:e,cId:t,agentId:i})}finally{await ge(y,u);for(const k of x)try{n.existsSync(k)&&await n.promises.rm(k,{recursive:!0,force:!0})}catch(M){r(u,"WARN","Failed to clean up temporary extracted zip",{error:M.message})}for(const k of D)try{n.existsSync(k)&&await n.promises.unlink(k)}catch(M){r(u,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:k,error:M.message})}try{s&&s.path&&n.existsSync(s.path)&&await n.promises.unlink(s.path)}catch(k){r(u,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:k.message})}}}async function Ze(e,t,i,s,a,o=null){if(a!=null&&String(a).trim()!==""){let _=null;if(o?.isUserApp?_=We(o,e,t):Q.COMPUTER_WORKSPACE_DIR&&(_=c.join(Q.COMPUTER_WORKSPACE_DIR,String(e),String(t))),$e(_))return Ue(e,t,a,i,s,o);r(`computer:${e}:${t}`,"INFO","Push skills: agentId present but workspace not symlinked, use legacy path",{userId:e,cId:t,agentId:a,userWorkspaceRoot:_})}const u=Date.now(),l=`computer:${e}:${t}`,D=re(s),x=[],f=[];if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});if(!i&&D.length===0)throw new d("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(i){if(!i.path)throw new d("Uploaded file has no valid path",{field:"file.path"});if(c.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new d("Only zip files are supported",{field:"file",originalName:i?.originalname})}const y=se(o),F=await J(o,e,t,l),m=c.join(F,".tmp"),{skillsDir:h,agentTypes:L}=await he(F);try{n.existsSync(F)||await n.promises.mkdir(F,{recursive:!0}),n.existsSync(h)||await n.promises.mkdir(h,{recursive:!0}),n.existsSync(m)||await n.promises.mkdir(m,{recursive:!0});const _=[],z=new Set;if(i){const g=c.join(m,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);f.push(g),await n.promises.mkdir(g,{recursive:!0}),r(l,"DEBUG","Start extracting skill zip file",{extractRoot:g}),await H(i.path,g),r(l,"DEBUG","Skill zip file extracted successfully",{extractRoot:g});const R=await ee(g,"skills");if(!R)r(l,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:g});else{const j=(await n.promises.readdir(R,{withFileTypes:!0})).filter(v=>v.isDirectory()&&!v.name.startsWith("."));if(j.length===0)r(l,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:R});else for(const v of j){const T=c.join(R,v.name),S=c.join(h,v.name);n.existsSync(S)&&await V(S),await Y(T,S),z.add(v.name),r(l,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:v.name,destSkillPath:S})}}}for(let g=0;g<D.length;g+=1){const R=D[g],O=c.join(m,`skill_push_url_${Date.now()}_${g}_${Math.round(Math.random()*1e6)}.zip`);x.push(O);const j=c.join(m,`skill_push_url_extract_${Date.now()}_${g}_${Math.round(Math.random()*1e6)}`);f.push(j),await n.promises.mkdir(j,{recursive:!0}),r(l,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:R}),await oe(R,O,l),await H(O,j);const T=(await n.promises.readdir(j,{withFileTypes:!0})).filter(N=>N.isDirectory()&&!N.name.startsWith(".")),E=T.find(N=>N.name==="skills")?(await n.promises.readdir(c.join(j,"skills"),{withFileTypes:!0})).filter(N=>N.isDirectory()&&!N.name.startsWith(".")).map(N=>({name:N.name,sourcePath:c.join(j,"skills",N.name)})):T.map(N=>({name:N.name,sourcePath:c.join(j,N.name)}));if(E.length===0){r(l,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:R,extractRoot:j});continue}for(const N of E){const C=c.join(h,N.name);n.existsSync(C)&&await V(C),await Y(N.sourcePath,C),z.add(N.name),r(l,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:R,skillName:N.name,destSkillPath:C})}}for(const g of z)_.push(g);const k=_.length>0?`Pushed ${_.length} skills: ${_.join(", ")}`:"No valid skill directories found in file or skillUrls",M=Date.now()-u;r(l,"INFO","Push skills resources prepared",{userId:e,cId:t,updatedSkills:_,agentTypes:L,prepareElapsedMs:M});const b=await de(F,l);return r(l,"INFO",k,{userId:e,cId:t,updatedSkills:_,agentTypes:L,prepareElapsedMs:M,syncAgentsElapsedMs:b?.elapsedMs,elapsedMs:Date.now()-u}),{message:k,workspaceRoot:y,updatedSkills:_}}catch(_){throw r(l,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:_.message,elapsedMs:Date.now()-u}),_ instanceof d||_ instanceof I||_ instanceof Z?_:new Z(`Failed to push skill to workspace: ${_.message}`,{userId:e,cId:t})}finally{const _=Date.now();try{for(const z of f)n.existsSync(z)&&await n.promises.rm(z,{recursive:!0,force:!0})}catch(z){r(l,"WARN","Failed to clean up temporary extracted zip",{error:z.message})}for(const z of x)try{n.existsSync(z)&&await n.promises.unlink(z)}catch(k){r(l,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:z,error:k.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(z){r(l,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:z.message})}r(l,"INFO","Push skills temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-_,totalElapsedMs:Date.now()-u})}}async function Ge(e,t,i,s,a=null){const o=Date.now(),p=`computer:${e}:${t}`;if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});if(!i||!i.path)throw new d("file is required",{field:"file"});if(c.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new d("Only zip files are supported",{field:"file",originalName:i.originalname});const l=await J(a,e,t,p),D=c.join(l,".tmp"),x=c.join(D,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{n.existsSync(l)||await n.promises.mkdir(l,{recursive:!0}),n.existsSync(D)||await n.promises.mkdir(D,{recursive:!0}),await n.promises.mkdir(x,{recursive:!0}),r(p,"DEBUG","Start extracting template zip file",{extractRoot:x}),await H(i.path,x),r(p,"DEBUG","Template zip file extracted successfully",{extractRoot:x});const f=await n.promises.readdir(x,{withFileTypes:!0});for(const y of f){const F=c.join(x,y.name),m=c.join(l,y.name);if(y.isDirectory())await Y(F,m);else{const h=c.dirname(m);n.existsSync(h)||await n.promises.mkdir(h,{recursive:!0}),await n.promises.copyFile(F,m)}}if(r(p,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:l,fileCount:f.length}),Q.GIT_ENABLED&&(s==="true"||s===!0)){const y=await import("../../service/gitService.js");await y.default.init({workspaceType:"taskAgent",userId:e,cId:t}),await y.default.commit({workspaceType:"taskAgent",userId:e,cId:t,message:"Initial commit"}),r(p,"INFO","Git init and initial commit done",{userId:e,cId:t})}return r(p,"INFO","Init project template completed",{userId:e,cId:t,targetDir:l,elapsedMs:Date.now()-o}),{message:"Project template initialized successfully",workspaceRoot:l}}catch(f){throw r(p,"ERROR","Failed to init project template",{userId:e,cId:t,error:f.message,elapsedMs:Date.now()-o}),f instanceof d||f instanceof I||f instanceof Z?f:new Z(`Failed to init project template: ${f.message}`,{userId:e,cId:t})}finally{try{n.existsSync(x)&&await n.promises.rm(x,{recursive:!0,force:!0})}catch(f){r(p,"WARN","Failed to clean up temporary extracted zip",{error:f.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(f){r(p,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:f.message})}}}async function qe(e,t,i,s=null){if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});if(!i||typeof i!="string"||!i.trim())throw new d("command cannot be empty",{field:"command"});const a=await J(s,e,t,"computer");if(!n.existsSync(a))throw new d("workspace directory does not exist",{field:"workDir",workDir:a});const o=`computer:${e}:${t}`;r(o,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:a,command:i});const p=10*60*1e3,u={cwd:a,timeout:p,maxBuffer:50*1024*1024};return Q.BASH_PATH&&(u.shell=Q.BASH_PATH),new Promise((l,D)=>{Ee(i,u,(x,f,y)=>{const F=x?x.killed?-1:x.code||1:0,m=x&&x.killed?(y||"")+`
|
|
2
|
+
Command timed out after ${p/1e3}s`:y||"";r(o,"INFO","Execute command completed",{userId:e,cId:t,exitCode:F,killed:x?x.killed:!1,stdoutLength:f?f.length:0,stderrLength:m.length}),l({stdout:f||"",stderr:m,exitCode:F})})})}async function Ke(e,t,i,s=null){const a=`computer:${e}:${t}`;if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});const o=await J(s,e,t,a);if(!n.existsSync(o))throw new d("workspace directory does not exist",{field:"workDir",workDir:o});const p=Q.ZIP_WORKSPACE_EXCLUDE||[],u=Array.isArray(i)?i:[],l=new Set([...p,...u]),D=`${e}_${t}.zip`,x=Date.now();r(a,"INFO","Zip workspace request",{userId:e,cId:t,targetDir:o,excludeDirs:[...l]});const f=Ae("zip",{zlib:{level:9}});return f.directory(o,!1,y=>{const F=y.name||"";if(F.split(/[\/\\]/).filter(Boolean).some(h=>l.has(h)))return!1;try{const h=c.join(o,F);if(n.lstatSync(h).isSymbolicLink())return!1}catch{return!1}return y}),f.on("warning",y=>{y.code==="ENOENT"?r(a,"WARN","Encountered file problem when creating zip",{message:y.message,code:y.code}):r(a,"ERROR","Encountered warning when creating zip",{message:y.message,code:y.code})}),f.on("error",y=>{r(a,"ERROR","Failed to create zip",{message:y.message,elapsedMs:Date.now()-x})}),f.on("end",()=>{r(a,"INFO","Workspace zip created successfully",{targetDir:o,zipFileName:D,elapsedMs:Date.now()-x})}),{archive:f,zipFileName:D}}const fe=new Set([...Q.ZIP_WORKSPACE_EXCLUDE||[],"dist-packages"]);function le(e){let t;try{t=n.readdirSync(e,{withFileTypes:!0})}catch{return null}const i=c.join(e,"scripts","package-platforms.mjs");if(n.existsSync(i))return e;for(const s of t)if(s.isDirectory()&&!fe.has(s.name)){const a=le(c.join(e,s.name));if(a)return a}return null}function ce(e,t,i,s=10*60*1e3){return new Promise(a=>{const o=je(e,t,{...i,timeout:s});let p="",u="";o.stdout?.on("data",l=>{p+=l.toString()}),o.stderr?.on("data",l=>{u+=l.toString()}),o.on("error",l=>{a({stdout:p,stderr:u+`
|
|
3
|
+
Failed to spawn ${e}: ${l.message}`,exitCode:1})}),o.on("close",(l,D)=>{a(l===null&&D?{stdout:p,stderr:u+`
|
|
4
|
+
Process killed by signal ${D} (timeout after ${s/1e3}s)`,exitCode:-1}:{stdout:p,stderr:u,exitCode:l??1})})})}function Je(e){if(!e)return null;let t=e;t.endsWith(".tar.gz")?t=t.slice(0,-7):t.endsWith(".tar.bz2")?t=t.slice(0,-8):(t.endsWith(".tgz")||t.endsWith(".zip"))&&(t=t.slice(0,-4));const i=t.split("-");if(i.length<4)return null;let s=-1;for(let a=i.length-1;a>=2;a--)if(/^\d+\.\d+\.\d+$/.test(i[a])){s=a;break}return s<3?null:i.slice(2,s).join("-")}async function He(e,t,i,s,a=null){const o=`computer:${e}:${t}`;if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});if(!i)throw new d("agentId cannot be empty",{field:"agentId"});if(!s)throw new d("version cannot be empty",{field:"version"});const p=await J(a,e,t,o);if(!n.existsSync(p))throw new d("workspace directory does not exist",{field:"workDir",workDir:p});r(o,"INFO","Build agent package request",{userId:e,cId:t,agentId:i,version:s});const u=le(p);if(!u)throw new d("package-platforms.mjs not found in workspace",{field:"script"});r(o,"INFO","Found package script",{projectDir:u});const l=await Pe(u,o);if(r(o,"INFO","pnpm install completed",{exitCode:l.exitCode,stderrLength:l.stderr.length}),l.exitCode!==0)throw r(o,"ERROR","pnpm install failed",{stderr:l.stderr}),new Z(`pnpm install failed: ${l.stderr}`);const D=c.join(u,"dist-packages"),x=["scripts/package-platforms.mjs",`agent-${i}`,s,D,"--print-artifacts"],f=await ce("node",x,{cwd:u,env:we()});if(r(o,"INFO","Build completed",{exitCode:f.exitCode,stdoutLength:f.stdout.length}),f.exitCode!==0)throw r(o,"ERROR","Build failed",{stderr:f.stderr}),new Z(`Build failed: ${f.stderr}`);const y=[".tar.gz",".tar.bz2",".zip",".tgz"],F=[],m=f.stdout.split(`
|
|
5
|
+
`);for(const h of m){const L=h.trim();if(!L)continue;const _=L.toLowerCase();if(!y.some(g=>_.endsWith(g)))continue;const z=c.resolve(u,L);let k=c.relative(p,z);k=k.split(c.sep).join("/");const M=c.basename(L),b=Je(M);F.push({path:k,fileName:M,platform:b||""})}return r(o,"INFO","Build agent package completed",{artifactsCount:F.length,artifacts:F}),{artifacts:F}}async function Ve(e,t,i=null){const s=`computer:${e}:${t}`;if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});const a=await J(i,e,t,s);if(!n.existsSync(a))return r(s,"WARN","Workspace not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const o=le(a);if(!o)return r(s,"WARN","package-platforms.mjs not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const p=c.join(o,"dist-packages");return n.existsSync(p)?(n.rmSync(p,{recursive:!0,force:!0}),r(s,"INFO","Cleaned dist-packages",{distPackagesDir:p}),{cleaned:!0}):(r(s,"INFO","dist-packages not found, nothing to clean",{distPackagesDir:p}),{cleaned:!1})}async function Ye(e,t,i=null){const s=`computer:${e}:${t}`;if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});const a=i?.workspaceDir?i.workspaceDir:await J(i,e,t,s);return n.existsSync(a)?(await n.promises.rm(a,{recursive:!0,force:!0}),r(s,"INFO","Workspace deleted",{userId:e,cId:t,targetDir:a})):r(s,"WARN","Workspace not found, skip delete",{userId:e,cId:t,targetDir:a}),{deleted:!0}}function Ne(e){const t=c.join(e,"package.json");if(n.existsSync(t))return e;let i;try{i=n.readdirSync(e,{withFileTypes:!0})}catch{return null}for(const s of i)if(s.isDirectory()&&!fe.has(s.name)&&s.name!=="node_modules"){const a=Ne(c.join(e,s.name));if(a)return a}return null}const Re=["neverBuiltDependencies","onlyBuiltDependencies","ignoredBuiltDependencies"],Xe=["NPM_CONFIG_NEVER_BUILT_DEPENDENCIES","npm_config_never_built_dependencies","NPM_CONFIG_ONLY_BUILT_DEPENDENCIES","npm_config_only_built_dependencies","NPM_CONFIG_IGNORED_BUILT_DEPENDENCIES","npm_config_ignored_built_dependencies"];async function Qe(e,t){const i=c.join(e,"package.json");if(!n.existsSync(i))return;const s=await n.promises.readFile(i,"utf8");let a;try{a=JSON.parse(s)}catch{r(t,"WARN","Skip sanitizing package.json: invalid JSON",{projectDir:e});return}if(!a.pnpm||typeof a.pnpm!="object")return;const o=Re.filter(p=>p in a.pnpm);if(o.length!==0){for(const p of o)delete a.pnpm[p];Object.keys(a.pnpm).length===0&&delete a.pnpm,await n.promises.writeFile(i,`${JSON.stringify(a,null,2)}
|
|
6
|
+
`,"utf8"),r(t,"INFO","Removed conflicting pnpm built dependency settings from package.json",{projectDir:e,removedKeys:o})}}async function Ie(e,t){const i=c.join(e,"pnpm-workspace.yaml");if(!n.existsSync(i))return;const a=(await n.promises.readFile(i,"utf8")).split(`
|
|
7
|
+
`),o=[];let p=-1,u=[];for(const l of a){const D=l.trimStart(),x=l.length-D.length,f=Re.find(y=>new RegExp(`^${y}:\\s*(.*)$`).test(D));if(f){u.push(f);const y=D.slice(f.length+1).trim();(!y||y==="|"||y===">")&&(p=x);continue}if(p>=0){if(D===""||x>p)continue;p=-1}o.push(l)}u.length!==0&&(await n.promises.writeFile(i,o.join(`
|
|
8
|
+
`),"utf8"),r(t,"INFO","Removed conflicting pnpm built dependency settings from pnpm-workspace.yaml",{projectDir:e,removedKeys:u}))}async function _e(e){if(!n.existsSync(e))return"";const t=await n.promises.readFile(e,"utf8"),i=t.split(`
|
|
9
|
+
`).filter(s=>!/^\s*(never-built-dependencies|only-built-dependencies|ignored-built-dependencies)\b/.test(s)).join(`
|
|
10
|
+
`);return i!==t&&await n.promises.writeFile(e,i,"utf8"),i}async function et(e,t){await Qe(e,t),await Ie(e,t),await _e(c.join(e,".npmrc"))}async function tt(e,t){await Oe(e,t),await et(e,t);const i=c.join(e,".npmrc");let s=await _e(i);const a=[];if(/dangerously-allow-all-builds\s*=/.test(s)||a.push("dangerously-allow-all-builds=true"),/production\s*=/.test(s)||a.push("production=false"),/confirm-modules-purge\s*=/.test(s)||a.push("confirm-modules-purge=false"),a.length>0){const o=s&&!s.endsWith(`
|
|
11
11
|
`)?`
|
|
12
|
-
`:"";await n.promises.writeFile(i,`${
|
|
12
|
+
`:"";await n.promises.writeFile(i,`${s}${o}${a.join(`
|
|
13
13
|
`)}
|
|
14
|
-
`,"utf8"),r(t,"INFO","Updated .npmrc for pnpm install",{projectDir:e,additions:
|
|
14
|
+
`,"utf8"),r(t,"INFO","Updated .npmrc for pnpm install",{projectDir:e,additions:a})}}function we(){const e={...process.env};delete e.CI,delete e.NPM_CONFIG_PRODUCTION,delete e.npm_config_production;for(const t of Xe)delete e[t];return e.NODE_ENV="development",e.NPM_CONFIG_PRODUCTION="false",e}async function Pe(e,t){await tt(e,t);const i=we();return ce("pnpm",["install","--prefer-offline","--config.production=false","--config.confirmModulesPurge=false","--config.dangerouslyAllowAllBuilds=true"],{cwd:e,env:i})}function Fe(e){const t=c.join(e,"pyproject.toml"),i=c.join(e,"requirements.txt");if(n.existsSync(t)||n.existsSync(i))return e;let s;try{s=n.readdirSync(e,{withFileTypes:!0})}catch{return null}for(const a of s)if(a.isDirectory()&&!fe.has(a.name)&&a.name!==".venv"&&a.name!=="venv"&&a.name!=="__pycache__"){const o=Fe(c.join(e,a.name));if(o)return o}return null}async function it(e,t,i,s=null){const a=`computer:${e}:${t}`,o=String(i||"").trim().toLowerCase();if(!e)throw new d("userId cannot be empty",{field:"userId"});if(!t)throw new d("cId cannot be empty",{field:"cId"});if(!o)throw new d("programmingLanguage cannot be empty",{field:"programmingLanguage"});const p=await J(s,e,t,a);if(!n.existsSync(p))throw new d("workspace directory does not exist",{field:"workDir",workDir:p});r(a,"INFO","Install project dependencies request",{userId:e,cId:t,programmingLanguage:o});const u=we();let l=null,D=null;if(o==="typescript"||o==="ts"){if(l=le(p)||Ne(p),!l)throw new d("TypeScript project not found in workspace",{field:"projectDir"});D=await Pe(l,a)}else if(o==="python"||o==="py"){if(l=Fe(p),!l)throw new d("Python project not found in workspace",{field:"projectDir"});const x=c.join(l,"pyproject.toml"),f=c.join(l,"requirements.txt");if(n.existsSync(x))D=await ce("pip",["install","-e","."],{cwd:l,env:u});else if(n.existsSync(f))D=await ce("pip",["install","-r","requirements.txt"],{cwd:l,env:u});else throw new d("No pyproject.toml or requirements.txt found in workspace",{field:"projectDir"})}else throw new d("Unsupported programmingLanguage",{field:"programmingLanguage",programmingLanguage:o});if(r(a,"INFO","Project dependencies install completed",{projectDir:l,programmingLanguage:o,exitCode:D.exitCode,stderrLength:D.stderr.length}),D.exitCode!==0)throw r(a,"ERROR","Project dependencies install failed",{projectDir:l,programmingLanguage:o,stderr:D.stderr}),new Z(`Project dependencies install failed: ${D.stderr||D.stdout}`);return{message:"Project dependencies installed successfully",projectDir:l,programmingLanguage:o}}export{Be as createWorkspace,Ze as pushSkillsToWorkspace,Ge as initProjectTemplate,qe as executeCommand,Ye as deleteWorkspace,Ke as zipWorkspace,He as buildAgentPackage,Ve as cleanupBuildArtifacts,it as installProjectDependencies};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import o from"fs";import p from"os";import n from"path";import{ValidationError as a}from"../error/errorHandler.js";function c(e){const i=e.startsWith("\\\\")||e.startsWith("//");let r=String(e).replace(/\\/g,"/").replace(/\/{2,}/g,"/");return i&&(r="/"+r),r}export async function listFsRoots(){const e=c(p.homedir()),i=[];if(process.platform==="win32")for(let r=65;r<=90;r++){const t=String.fromCharCode(r)+":/";try{await o.promises.stat(t),i.push({name:t,path:t,isDir:!0})}catch{}}else i.push({name:"/",path:"/",isDir:!0});return{roots:i,home:e}}export async function listFsChildren(e){if(!e||typeof e!="string"||e.includes("\0"))throw new a("path is required",{field:"path"});if(!n.isAbsolute(e))throw new a("path must be absolute",{field:"path"});let i;try{i=await o.promises.readdir(e,{withFileTypes:!0})}catch(t){throw new a(`cannot read directory (${t.code||t.message})`,{field:"path"})}const r=[];for(const t of i){let s=t.isDirectory();const m=t.isSymbolicLink();if(m)try{s=(await o.promises.stat(n.join(e,t.name))).isDirectory()}catch{}r.push({name:t.name,path:c(n.join(e,t.name)),isDir:s,isSymlink:m})}return r.sort((t,s)=>Number(s.isDir)-Number(t.isDir)||t.name.localeCompare(s.name,void 0,{sensitivity:"base",numeric:!0})),{path:c(e),entries:r}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import c from"fs";import p from"path";import a from"../../appConfig/index.js";import{log as f}from"../log/logUtils.js";import{ValidationError as i}from"../error/errorHandler.js";export const SERVICE_TYPE={USERAPP:"userapp",PAGEAPP:"pageapp",GENERAL:"general"};export function resolveServiceContext(r){const e=r.headers&&typeof r.headers["x-service-type"]=="string"?r.headers["x-service-type"].trim().toLowerCase():"",t=(r.body?.serviceType??r.query?.serviceType??"").toString().trim().toLowerCase(),s=e||t||SERVICE_TYPE.GENERAL,o=typeof r.headers?.["x-app-id"]=="string"&&r.headers["x-app-id"].trim()||(r.body?.appId??r.query?.appId??"").toString().trim()||null||null;if(s===SERVICE_TYPE.USERAPP&&!o)throw new i("appId is required for userapp workspace",{field:"appId"});if(s===SERVICE_TYPE.USERAPP&&!l(o))throw new i("appId contains illegal path segments",{field:"appId"});const u=typeof r.headers?.["x-workspace-dir"]=="string"&&r.headers["x-workspace-dir"].trim()||(r.body?.workspaceDir??r.query?.workspaceDir??"").toString().trim()||null,d=u?R(u):null;return{serviceType:s,appId:o,workspaceDir:d,isUserApp:s===SERVICE_TYPE.USERAPP}}function l(r){return!!r&&!/[\/\\\0]/.test(r)&&r!=="."&&r!==".."}function R(r){let e=String(r).trim();if(e.length>512)throw new i("workspaceDir length exceeds 512",{field:"workspaceDir"});if(/[\0\x00-\x1f\x7f]/.test(e))throw new i("workspaceDir contains illegal characters",{field:"workspaceDir"});if(e=P(e),!e.startsWith("/")&&!/^[A-Za-z]:\/.*/.test(e))throw new i("workspaceDir must be an absolute path (POSIX /a/b, Windows C:/a/b or UNC //server/share/a/b)",{field:"workspaceDir"});if(e.split("/").some(t=>t==="."||t===".."))throw new i("workspaceDir must not contain dot segments",{field:"workspaceDir"});return e}function P(r){const e=r.startsWith("//")||r.startsWith("\\\\");let t=r.replace(/\\/g,"/").replace(/\/{2,}/g,"/");return e&&(t="/"+t),/^[a-z]:\//.test(t)&&(t=t.charAt(0).toUpperCase()+t.slice(1)),t}function w(r,e){if(!r)throw new i(`${e} configuration does not exist`,{field:e});return r}export function resolveWorkspaceRoot(r){return r?.isUserApp?w(a.USERAPP_WORKSPACE_DIR,"USERAPP_WORKSPACE_DIR"):a.COMPUTER_WORKSPACE_DIR}export function resolveWorkspaceDir(r,e,t){return r?.workspaceDir?r.workspaceDir:r?.isUserApp?p.join(resolveWorkspaceRoot(r),String(r.appId)):p.join(a.COMPUTER_WORKSPACE_DIR,String(e),String(t))}export async function ensureWorkspaceDir(r,e,t,s="computer"){if(r?.workspaceDir){const o=r.workspaceDir;return c.existsSync(o)||(await c.promises.mkdir(o,{recursive:!0}),f(s,"INFO","Created bound workspace directory",{boundDir:o})),o}const n=resolveWorkspaceRoot(r);if(!n)throw new i("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});if(c.existsSync(n)||(await c.promises.mkdir(n,{recursive:!0}),f(s,"INFO","Created user workspace root directory",{workspaceRoot:n})),r?.isUserApp){const o=p.join(n,String(r.appId));if(!c.existsSync(o))throw new i(`userapp workspace mount does not exist: ${o}`,{field:"USERAPP_WORKSPACE_DIR"});return o}return p.join(n,String(e),String(t))}export function resolveLogDir(r,e,t){return r?.isUserApp?w(a.USERAPP_LOG_DIR,"USERAPP_LOG_DIR"):r?.workspaceDir?p.join(r.workspaceDir,".logs"):a.COMPUTER_WORKSPACE_DIR?p.join(a.COMPUTER_WORKSPACE_DIR,String(e),String(t),".logs"):null}
|
package/package.json
CHANGED