nuwax-file-server 1.6.3 → 1.6.5
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/README.md +1 -0
- package/dist/appConfig/index.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/env.development +4 -9
- package/dist/env.production +3 -3
- package/dist/routes/computerRoutes.js +1 -1
- package/dist/utils/common/AgentWorkspaceUtils.js +1 -1
- package/dist/utils/common/agentStoreUtils.js +2 -2
- package/dist/utils/computer/computerFileUtils.js +1 -1
- package/dist/utils/computer/computerUtils.js +7 -7
- package/dist/utils/computer/hookConfigUtils.js +4 -4
- package/dist/utils/computer/workspaceContext.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -125,6 +125,7 @@ nuwax-file-server start --env production --port 60000 \
|
|
|
125
125
|
| `LOG_BASE_DIR` | Log directory root |
|
|
126
126
|
| `COMPUTER_WORKSPACE_DIR` | “Computer” workspace |
|
|
127
127
|
| `COMPUTER_LOG_DIR` | “Computer” logs |
|
|
128
|
+
| `RCODER_AGENT_BOUND_USER_ID` | Owner of a per-agent volume; non-empty switches the computer workspace to the single-user layout |
|
|
128
129
|
|
|
129
130
|
More options and scenarios: [Environment variables](./docs/ENV.md)
|
|
130
131
|
|
package/dist/appConfig/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import E from"path";import n from"fs";import
|
|
1
|
+
import E from"path";import n from"fs";import T from"os";import{fileURLToPath as R}from"url";import r from"dotenv";const L=E.dirname(R(import.meta.url));r.config();function O(){const e=process.env.LOG_BASE_DIR,_=E.join(T.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 o=process.env.NODE_ENV||"development";function p(e){const _=E.join(L,"..",`env.${e}`);if(n.existsSync(_))r.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)}}p(o);const I={NODE_ENV:o,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:O(),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,RCODER_AGENT_BOUND_USER_ID:(process.env.RCODER_AGENT_BOUND_USER_ID||"").trim(),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/",".nuwax-harness/",".agent-store/",".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",".nuwax-harness",".opencode",".agent-store",".logs",".npmrc","__pycache__","node_modules","dist","pnpm-lock.yaml","yarn.lock","package-lock.json"]};export function validateConfig(e){if(e.RCODER_AGENT_BOUND_USER_ID&&!e.COMPUTER_WORKSPACE_DIR)throw new Error("RCODER_AGENT_BOUND_USER_ID is set but COMPUTER_WORKSPACE_DIR is empty: the single-user volume view needs the workspace root")}try{validateConfig(I)}catch(e){throw console.error(`Invalid configuration: ${e.message}`),e}export default I;
|
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.6.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();
|
|
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.6.5",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
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
# 开发环境配置
|
|
2
|
-
NODE_ENV=
|
|
2
|
+
NODE_ENV=dev
|
|
3
3
|
PORT=60000
|
|
4
4
|
|
|
5
|
-
# 部署模式: docker-compose (默认) 或 k8s
|
|
6
|
-
# docker-compose: 使用 symlink + 模板缓存(本地磁盘 node_modules,启动快)
|
|
7
|
-
# k8s: 不使用 symlink,node_modules 直接放 JuiceFS(多节点共享)
|
|
8
|
-
# DEPLOYMENT_MODE=docker-compose
|
|
9
|
-
|
|
10
5
|
# 日志配置
|
|
11
6
|
LOG_BASE_DIR=/app/logs/project_logs
|
|
12
7
|
LOG_LEVEL=debug
|
|
@@ -48,7 +43,7 @@ DOWNLOAD_MAX_FILE_SIZE_BYTES=5368709120
|
|
|
48
43
|
REQUEST_BODY_LIMIT=2000mb
|
|
49
44
|
|
|
50
45
|
# 目录遍历排除(返回内容、归档等)
|
|
51
|
-
TRAVERSE_EXCLUDE_DIRS=dist,node_modules,.pnpm-store,__MACOSX,.attachments,.git,.agents,.
|
|
46
|
+
TRAVERSE_EXCLUDE_DIRS=dist,node_modules,.pnpm-store,__MACOSX,.attachments,.git,.agents,.nuwax-harness,.opencode,.logs
|
|
52
47
|
|
|
53
48
|
# 归档遍历排除文件
|
|
54
49
|
BACKUP_TRAVERSE_EXCLUDE_FILES=pnpm-lock.yaml,yarn.lock,package-lock.json
|
|
@@ -97,7 +92,7 @@ USERAPP_LOG_DIR=/home/user/logs
|
|
|
97
92
|
GIT_DEFAULT_AUTHOR_NAME=Nuwax File Server
|
|
98
93
|
GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
|
|
99
94
|
GIT_AUTO_GITIGNORE=true
|
|
100
|
-
GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.npmrc|.agents/|.claude/|.opencode/|.
|
|
95
|
+
GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.npmrc|.agents/|.claude/|.opencode/|.nuwax-harness/|.tmp/|.logs/|pnpm-lock.yaml|yarn.lock|package-lock.json
|
|
101
96
|
GIT_ENABLED=true
|
|
102
97
|
GIT_USE_NATIVE=true
|
|
103
98
|
|
|
@@ -105,4 +100,4 @@ GIT_USE_NATIVE=true
|
|
|
105
100
|
BASH_PATH=
|
|
106
101
|
|
|
107
102
|
# zip-workspace 打包时排除的路径片段(逗号分隔,目录或文件名均可)
|
|
108
|
-
ZIP_WORKSPACE_EXCLUDE=.git,.tmp,.claude,.agents,.
|
|
103
|
+
ZIP_WORKSPACE_EXCLUDE=.git,.tmp,.claude,.agents,.nuwax-harness,.opencode,.logs,.npmrc,__pycache__,node_modules,dist,pnpm-lock.yaml,yarn.lock,package-lock.json
|
package/dist/env.production
CHANGED
|
@@ -48,7 +48,7 @@ DOWNLOAD_MAX_FILE_SIZE_BYTES=5368709120
|
|
|
48
48
|
REQUEST_BODY_LIMIT=2000mb
|
|
49
49
|
|
|
50
50
|
# 目录遍历排除(返回内容、归档等)
|
|
51
|
-
TRAVERSE_EXCLUDE_DIRS=dist,node_modules,.pnpm-store,__MACOSX,.attachments,.git,.agents,.
|
|
51
|
+
TRAVERSE_EXCLUDE_DIRS=dist,node_modules,.pnpm-store,__MACOSX,.attachments,.git,.agents,.nuwax-harness,.opencode,.logs
|
|
52
52
|
|
|
53
53
|
# 归档遍历排除文件
|
|
54
54
|
BACKUP_TRAVERSE_EXCLUDE_FILES=pnpm-lock.yaml,yarn.lock,package-lock.json
|
|
@@ -97,7 +97,7 @@ USERAPP_LOG_DIR=/home/user/logs
|
|
|
97
97
|
GIT_DEFAULT_AUTHOR_NAME=Nuwax File Server
|
|
98
98
|
GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
|
|
99
99
|
GIT_AUTO_GITIGNORE=true
|
|
100
|
-
GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.npmrc|.agents/|.claude/|.opencode/|.
|
|
100
|
+
GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|dist-packages/|build/|.idea/|.vscode/|.DS_Store|.npmrc|.agents/|.claude/|.opencode/|.nuwax-harness/|.tmp/|.logs/|pnpm-lock.yaml|yarn.lock|package-lock.json
|
|
101
101
|
GIT_ENABLED=true
|
|
102
102
|
GIT_USE_NATIVE=true
|
|
103
103
|
|
|
@@ -105,4 +105,4 @@ GIT_USE_NATIVE=true
|
|
|
105
105
|
BASH_PATH=
|
|
106
106
|
|
|
107
107
|
# zip-workspace 打包时排除的路径片段(逗号分隔,目录或文件名均可)
|
|
108
|
-
ZIP_WORKSPACE_EXCLUDE=.git,.tmp,.claude,.agents,.
|
|
108
|
+
ZIP_WORKSPACE_EXCLUDE=.git,.tmp,.claude,.agents,.nuwax-harness,.opencode,.logs,.npmrc,__pycache__,node_modules,dist,pnpm-lock.yaml,yarn.lock,package-lock.json
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import v from"express";import z from"multer";import g from"fs";import j from"path";import{ValidationError as P,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import b from"../appConfig/index.js";import{createWorkspace as D,pushSkillsToWorkspace as T,initProjectTemplate as R,installProjectDependencies as M,executeCommand as _,deleteWorkspace as B,zipWorkspace as H,buildAgentPackage as L,cleanupBuildArtifacts as W}from"../utils/computer/computerUtils.js";import{getFileList as J,getFileMeta as K,resolveExistingFile as V,searchFiles as G,updateFiles as Z,uploadFile as X,uploadFiles as Y,generateFile as Q,downloadAllFiles as q,getLatestLogs as ee,importProject as te}from"../utils/computer/computerFileUtils.js";import{resolveServiceContext as p}from"../utils/computer/workspaceContext.js";import{listFsRoots as se,listFsChildren as ae,createFsDirectory as oe,renameFsDirectory as re}from"../utils/computer/fsBrowserUtils.js";import{trackMulterTempPath as ne,cleanupMulterFiles as ie}from"../utils/common/multerCleanup.js";const A=v.Router();A.use(ie);const I=z({storage:z.diskStorage({destination:(e,r,s)=>{try{const t=typeof e.headers["x-workspace-type"]=="string"?e.headers["x-workspace-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=b.USERAPP_WORKSPACE_DIR;if(!n)return s(new Error("USERAPP_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));o=j.join(n,String(a),".tmp")}else{const n=b.COMPUTER_WORKSPACE_DIR;if(!n)return s(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const i=e.body?.userId||"unknown",l=e.body?.cId||"unknown";o=j.join(n,String(i),String(l),".tmp")}g.existsSync(o)||g.mkdirSync(o,{recursive:!0}),e._multerUploadDir=o,s(null,o)}catch(t){s(t)}},filename:(e,r,s)=>{const t=j.extname(r.originalname)||".zip",a=j.basename(r.originalname,t),o=`${Date.now()}_${Math.round(Math.random()*1e6)}`,n=`${a}_${o}${t}`;e._multerUploadDir&&ne(e,j.join(e._multerUploadDir,n)),s(null,n)}}),limits:{fileSize:b.UPLOAD_MAX_FILE_SIZE_BYTES}});function le(e,r,s,t){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof P))return t(e);t(e)}const ce=[{path:"/create-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{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,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await D(s,t,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,o);r.status(200).json({success:!0,...i})})},{path:"/create-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{const{userId:s,cId:t,agentId:a,skillUrls:o,skillUrlMap:n,skillNames:i,updateSkillNames:l,mcpServersConfig:d,hooksConfig:f,permissionsConfig:m,hookScripts:h}=e.body||{},k=e.file||null,C=p(e),O=`computer:${s}:${t}`;let F=o;if(typeof o=="string")try{F=JSON.parse(o)}catch{F=[o]}let w=n;if(typeof n=="string")try{w=JSON.parse(n)}catch{w=null}let N=i;if(typeof i=="string")try{const y=JSON.parse(i);N=Array.isArray(y)?y:[i]}catch{N=i.split(",").map(y=>y.trim()).filter(Boolean)}let S=l;if(typeof l=="string")try{const y=JSON.parse(l);S=Array.isArray(y)?y:[l]}catch{S=l.split(",").map(y=>y.trim()).filter(Boolean)}let $=h;if(typeof h=="string")try{$=JSON.parse(h)}catch{$=null}const U=Array.isArray(F)?F.length:0,x=w&&typeof w=="object"&&!Array.isArray(w)?Object.keys(w).length:0;u(O,"INFO","Create workspace v2 request",{userId:s,cId:t,agentId:a,workspaceType:C.workspaceType,appId:C.appId,hasFile:!!k,fileName:k?.originalname,fileSize:k?.size,skillUrlsCount:U,skillUrlMapCount:x,skillNamesCount:Array.isArray(N)?N.length:0,updateSkillNamesCount:Array.isArray(S)?S.length:0,hasMcpServersConfig:!!d,hasHooksConfig:!!f,hasPermissionsConfig:!!m,hookScriptsCount:Array.isArray($)?$.length:0});const E=await D(s,t,k,F,d,m,f,$,a,N,S,w,C);r.status(200).json({success:!0,...E})})},{path:"/push-skills-to-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{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,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await T(s,t,a,void 0,void 0,o);r.status(200).json({success:!0,...i})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{const{userId:s,cId:t,agentId:a,skillUrls:o}=e.body||{},n=e.file||null,i=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,workspaceType:i.workspaceType,appId:i.appId,hasFile:!!n,fileName:n?.originalname,fileSize:n?.size,skillUrlsCount:Array.isArray(d)?d.length:0});const f=await T(s,t,n,d,a,i);r.status(200).json({success:!0,...f})})},{path:"/fs/roots",method:"get",handler:c(async(e,r)=>{const s=await se();r.status(200).json({success:!0,...s})})},{path:"/fs/children",method:"get",handler:c(async(e,r)=>{const{path:s}=e.query,t=await ae(s);r.status(200).json({success:!0,...t})})},{path:"/fs/mkdir",method:"post",handler:c(async(e,r)=>{const{parentPath:s,dirName:t}=e.body||{},a=await oe(s,t);r.status(200).json({success:!0,...a})})},{path:"/fs/rename",method:"post",handler:c(async(e,r)=>{const{path:s,newName:t}=e.body||{},a=await re(s,t);r.status(200).json({success:!0,...a})})},{path:"/get-file-list",method:"get",handler:c(async(e,r)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:n,recursive:i,depth:l,type:d,limit:f}=e.query,m=await J(s,t,a,o,n,i,l,d,f,p(e));r.status(200).json({success:!0,...m})})},{path:"/resolve-file",method:"get",handler:c(async(e,r)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,filePath:n}=e.query,i=await V(s,t,n,a,o,p(e));r.status(200).json({success:!0,...i})})},{path:"/get-file-meta",method:"post",handler:c(async(e,r)=>{const{userId:s,cId:t,customTargetDir:a,filePaths:o,fileMetaMaxBatch:n}=e.body||{},i=await K(s,t,o,a,p(e),n);r.status(200).json({success:!0,...i})})},{path:"/search-files",method:"get",handler:c(async(e,r)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:n,type:i,kw:l,limit:d,maxVisit:f,timeoutMs:m}=e.query,h=await G(s,t,a,l,o,n,i,d,f,m,p(e));r.status(200).json({success:!0,...h})})},{path:"/files-update",method:"post",handler:c(async(e,r)=>{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 i=await Z(s,t,a,o,p(e));r.status(200).json(i)})},{path:"/upload-file",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{const{userId:s,cId:t,filePath:a,customTargetDir:o}=e.body||{},n=e.file,i=`computer:${s}:${t}`;u(i,"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 X(s,t,d,a,o,p(e));r.status(200).json(f)}finally{g.existsSync(n.path)&&await g.promises.unlink(n.path)}})},{path:"/generate-file",method:"post",handler:c(async(e,r)=>{const{userId:s,cId:t,fileName:a,content:o,customTargetDir:n}=e.body||{},i=`computer:${s}:${t}`;u(i,"INFO","Generate file request",{userId:s,cId:t,fileName:a,contentLength:typeof o=="string"?o.length:0});const l=await Q(s,t,a,o,n,p(e));r.status(200).json(l)})},{path:"/import-project",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{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 P("file is required",{field:"file"});const i=await te(s,t,o,a,p(e));r.status(200).json(i)})},{path:"/upload-files",method:"post",middleware:I.array("files"),handler:c(async(e,r)=>{const{userId:s,cId:t,filePaths:a,customTargetDir:o}=e.body||{},n=e.files||[],i=`computer:${s}:${t}`,l=Array.isArray(a)?a:typeof a=="string"?[a]:a;u(i,"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 Y(s,t,d,l,o,p(e));r.status(200).json(m)}finally{for(const m of f)if(g.existsSync(m))try{await g.promises.unlink(m)}catch(h){u(i,"WARN","Clean temporary file failed",{tempPath:m,error:h.message})}}})},{path:"/install-project",method:"post",handler:c(async(e,r)=>{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 M(s,t,a,p(e));r.status(200).json({success:!0,...n})})},{path:"/init-project-template",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{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 i=await R(s,t,o,a,p(e));r.status(200).json({success:!0,...i})})},{path:"/download-all-files",method:"get",handler:c(async(e,r)=>{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:i}=await q(s,t,a,p(e));r.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);r.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",d=>{r.destroy(d)}),n.pipe(r),n.finalize()})},{path:"/execute-command",method:"post",handler:c(async(e,r)=>{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 _(s,t,a,p(e));r.status(200).json({success:!0,...n})})},{path:"/delete-workspace",method:"post",handler:c(async(e,r)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Delete workspace request",{userId:s,cId:t});const o=await B(s,t,p(e));r.status(200).json({success:!0,...o})})},{path:"/get-logs",method:"get",handler:c(async(e,r)=>{const{userId:s,cId:t,tailLines:a}=e.query,o=a?parseInt(a,10):200,n=Number.isFinite(o)&&o>0?o:200,i=await ee(s,t,n,p(e));r.status(200).json(i)})},{path:"/zip-workspace",method:"post",handler:c(async(e,r)=>{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:i}=await H(s,t,a||null,p(e));r.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);r.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",d=>{r.destroy(d)}),n.pipe(r),n.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(e,r)=>{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 i=await L(s,t,a,o,p(e));r.status(200).json({success:!0,...i})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(e,r)=>{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 W(s,t,p(e));r.status(200).json({success:!0,...o})})}];ce.forEach(e=>{if(e.middleware)A[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const r=[];e.handler&&r.push(e.handler),e.decodeMiddleware&&r.push(e.decodeMiddleware),r.push(le),r.push(e.customHandler),A[e.method](e.path,...r)}else A[e.method](e.path,e.handler)});export default A;
|
|
1
|
+
import v from"express";import z from"multer";import g from"fs";import F from"path";import{ValidationError as P,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import b from"../appConfig/index.js";import{createWorkspace as D,pushSkillsToWorkspace as T,initProjectTemplate as R,installProjectDependencies as M,executeCommand as _,deleteWorkspace as B,zipWorkspace as H,buildAgentPackage as L,cleanupBuildArtifacts as W}from"../utils/computer/computerUtils.js";import{getFileList as J,getFileMeta as K,resolveExistingFile as V,searchFiles as G,updateFiles as Z,uploadFile as X,uploadFiles as Y,generateFile as Q,downloadAllFiles as q,getLatestLogs as ee,importProject as te}from"../utils/computer/computerFileUtils.js";import{isSingleUserVolume as se,resolveServiceContext as p}from"../utils/computer/workspaceContext.js";import{listFsRoots as ae,listFsChildren as oe,createFsDirectory as re,renameFsDirectory as ne}from"../utils/computer/fsBrowserUtils.js";import{trackMulterTempPath as ie,cleanupMulterFiles as le}from"../utils/common/multerCleanup.js";const A=v.Router();A.use(le);const I=z({storage:z.diskStorage({destination:(e,r,s)=>{try{const t=typeof e.headers["x-workspace-type"]=="string"?e.headers["x-workspace-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=b.USERAPP_WORKSPACE_DIR;if(!n)return s(new Error("USERAPP_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));o=F.join(n,String(a),".tmp")}else{const n=b.COMPUTER_WORKSPACE_DIR;if(!n)return s(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const i=e.body?.userId||"unknown",l=e.body?.cId||"unknown";o=se()?F.join(n,String(l),".tmp"):F.join(n,String(i),String(l),".tmp")}g.existsSync(o)||g.mkdirSync(o,{recursive:!0}),e._multerUploadDir=o,s(null,o)}catch(t){s(t)}},filename:(e,r,s)=>{const t=F.extname(r.originalname)||".zip",a=F.basename(r.originalname,t),o=`${Date.now()}_${Math.round(Math.random()*1e6)}`,n=`${a}_${o}${t}`;e._multerUploadDir&&ie(e,F.join(e._multerUploadDir,n)),s(null,n)}}),limits:{fileSize:b.UPLOAD_MAX_FILE_SIZE_BYTES}});function ce(e,r,s,t){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof P))return t(e);t(e)}const de=[{path:"/create-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{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,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await D(s,t,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,o);r.status(200).json({success:!0,...i})})},{path:"/create-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{const{userId:s,cId:t,agentId:a,skillUrls:o,skillUrlMap:n,skillNames:i,updateSkillNames:l,mcpServersConfig:d,hooksConfig:f,permissionsConfig:m,hookScripts:h}=e.body||{},k=e.file||null,C=p(e),O=`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=i;if(typeof i=="string")try{const y=JSON.parse(i);S=Array.isArray(y)?y:[i]}catch{S=i.split(",").map(y=>y.trim()).filter(Boolean)}let $=l;if(typeof l=="string")try{const y=JSON.parse(l);$=Array.isArray(y)?y:[l]}catch{$=l.split(",").map(y=>y.trim()).filter(Boolean)}let j=h;if(typeof h=="string")try{j=JSON.parse(h)}catch{j=null}const U=Array.isArray(N)?N.length:0,x=w&&typeof w=="object"&&!Array.isArray(w)?Object.keys(w).length:0;u(O,"INFO","Create workspace v2 request",{userId:s,cId:t,agentId:a,workspaceType:C.workspaceType,appId:C.appId,hasFile:!!k,fileName:k?.originalname,fileSize:k?.size,skillUrlsCount:U,skillUrlMapCount:x,skillNamesCount:Array.isArray(S)?S.length:0,updateSkillNamesCount:Array.isArray($)?$.length:0,hasMcpServersConfig:!!d,hasHooksConfig:!!f,hasPermissionsConfig:!!m,hookScriptsCount:Array.isArray(j)?j.length:0});const E=await D(s,t,k,N,d,m,f,j,a,S,$,w,C);r.status(200).json({success:!0,...E})})},{path:"/push-skills-to-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{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,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await T(s,t,a,void 0,void 0,o);r.status(200).json({success:!0,...i})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{const{userId:s,cId:t,agentId:a,skillUrls:o}=e.body||{},n=e.file||null,i=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,workspaceType:i.workspaceType,appId:i.appId,hasFile:!!n,fileName:n?.originalname,fileSize:n?.size,skillUrlsCount:Array.isArray(d)?d.length:0});const f=await T(s,t,n,d,a,i);r.status(200).json({success:!0,...f})})},{path:"/fs/roots",method:"get",handler:c(async(e,r)=>{const s=await ae();r.status(200).json({success:!0,...s})})},{path:"/fs/children",method:"get",handler:c(async(e,r)=>{const{path:s}=e.query,t=await oe(s);r.status(200).json({success:!0,...t})})},{path:"/fs/mkdir",method:"post",handler:c(async(e,r)=>{const{parentPath:s,dirName:t}=e.body||{},a=await re(s,t);r.status(200).json({success:!0,...a})})},{path:"/fs/rename",method:"post",handler:c(async(e,r)=>{const{path:s,newName:t}=e.body||{},a=await ne(s,t);r.status(200).json({success:!0,...a})})},{path:"/get-file-list",method:"get",handler:c(async(e,r)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:n,recursive:i,depth:l,type:d,limit:f}=e.query,m=await J(s,t,a,o,n,i,l,d,f,p(e));r.status(200).json({success:!0,...m})})},{path:"/resolve-file",method:"get",handler:c(async(e,r)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,filePath:n}=e.query,i=await V(s,t,n,a,o,p(e));r.status(200).json({success:!0,...i})})},{path:"/get-file-meta",method:"post",handler:c(async(e,r)=>{const{userId:s,cId:t,customTargetDir:a,filePaths:o,fileMetaMaxBatch:n}=e.body||{},i=await K(s,t,o,a,p(e),n);r.status(200).json({success:!0,...i})})},{path:"/search-files",method:"get",handler:c(async(e,r)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:n,type:i,kw:l,limit:d,maxVisit:f,timeoutMs:m}=e.query,h=await G(s,t,a,l,o,n,i,d,f,m,p(e));r.status(200).json({success:!0,...h})})},{path:"/files-update",method:"post",handler:c(async(e,r)=>{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 i=await Z(s,t,a,o,p(e));r.status(200).json(i)})},{path:"/upload-file",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{const{userId:s,cId:t,filePath:a,customTargetDir:o}=e.body||{},n=e.file,i=`computer:${s}:${t}`;u(i,"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 X(s,t,d,a,o,p(e));r.status(200).json(f)}finally{g.existsSync(n.path)&&await g.promises.unlink(n.path)}})},{path:"/generate-file",method:"post",handler:c(async(e,r)=>{const{userId:s,cId:t,fileName:a,content:o,customTargetDir:n}=e.body||{},i=`computer:${s}:${t}`;u(i,"INFO","Generate file request",{userId:s,cId:t,fileName:a,contentLength:typeof o=="string"?o.length:0});const l=await Q(s,t,a,o,n,p(e));r.status(200).json(l)})},{path:"/import-project",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{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 P("file is required",{field:"file"});const i=await te(s,t,o,a,p(e));r.status(200).json(i)})},{path:"/upload-files",method:"post",middleware:I.array("files"),handler:c(async(e,r)=>{const{userId:s,cId:t,filePaths:a,customTargetDir:o}=e.body||{},n=e.files||[],i=`computer:${s}:${t}`,l=Array.isArray(a)?a:typeof a=="string"?[a]:a;u(i,"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 Y(s,t,d,l,o,p(e));r.status(200).json(m)}finally{for(const m of f)if(g.existsSync(m))try{await g.promises.unlink(m)}catch(h){u(i,"WARN","Clean temporary file failed",{tempPath:m,error:h.message})}}})},{path:"/install-project",method:"post",handler:c(async(e,r)=>{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 M(s,t,a,p(e));r.status(200).json({success:!0,...n})})},{path:"/init-project-template",method:"post",middleware:I.single("file"),handler:c(async(e,r)=>{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 i=await R(s,t,o,a,p(e));r.status(200).json({success:!0,...i})})},{path:"/download-all-files",method:"get",handler:c(async(e,r)=>{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:i}=await q(s,t,a,p(e));r.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);r.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",d=>{r.destroy(d)}),n.pipe(r),n.finalize()})},{path:"/execute-command",method:"post",handler:c(async(e,r)=>{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 _(s,t,a,p(e));r.status(200).json({success:!0,...n})})},{path:"/delete-workspace",method:"post",handler:c(async(e,r)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Delete workspace request",{userId:s,cId:t});const o=await B(s,t,p(e));r.status(200).json({success:!0,...o})})},{path:"/get-logs",method:"get",handler:c(async(e,r)=>{const{userId:s,cId:t,tailLines:a}=e.query,o=a?parseInt(a,10):200,n=Number.isFinite(o)&&o>0?o:200,i=await ee(s,t,n,p(e));r.status(200).json(i)})},{path:"/zip-workspace",method:"post",handler:c(async(e,r)=>{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:i}=await H(s,t,a||null,p(e));r.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);r.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),n.on("error",d=>{r.destroy(d)}),n.pipe(r),n.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(e,r)=>{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 i=await L(s,t,a,o,p(e));r.status(200).json({success:!0,...i})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(e,r)=>{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 W(s,t,p(e));r.status(200).json({success:!0,...o})})}];de.forEach(e=>{if(e.middleware)A[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const r=[];e.handler&&r.push(e.handler),e.decodeMiddleware&&r.push(e.decodeMiddleware),r.push(ce),r.push(e.customHandler),A[e.method](e.path,...r)}else A[e.method](e.path,e.handler)});export default A;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import l from"fs";import i from"path";import{log as y}from"../log/logUtils.js";const
|
|
1
|
+
import l from"fs";import i from"path";import{log as y}from"../log/logUtils.js";const w={agents:".agents",claudecode:".claude",opencode:".opencode",nuwaxHarness:".nuwax-harness"},m=Object.keys(w),g="agents",k=8;function N(t){let e=0;const n=[];return{async acquire(){if(e<t){e+=1;return}await new Promise(s=>{n.push(s)})},release(){const s=n.shift();if(s){s();return}e=Math.max(0,e-1)}}}const j=N(k);async function f(t){try{await l.promises.lstat(t)}catch{return}await l.promises.rm(t,{recursive:!0,force:!0})}async function c(t){l.existsSync(t)||await l.promises.mkdir(t,{recursive:!0})}async function E(t,e){await j.acquire();let n=!1;try{if((await l.promises.lstat(t)).isDirectory()){await c(e);const r=await l.promises.readdir(t);j.release(),n=!0,await Promise.all(r.map(a=>E(i.join(t,a),i.join(e,a))));return}await c(i.dirname(e)),await l.promises.copyFile(t,e)}finally{n||j.release()}}async function d(t,e){if(!l.existsSync(t))return;await c(e);const n=await l.promises.readdir(t,{withFileTypes:!0});await Promise.all(n.map(s=>E(i.join(t,s.name),i.join(e,s.name))))}async function T(t){const e=i.join(t,w[g]),n=i.join(e,"skills"),s=i.join(e,"agents");return await c(e),await c(n),await c(s),{rootDir:e,skillsDir:n,agentsDir:s,agentTypes:m}}async function A(t,e,n){await c(i.dirname(t)),await c(e),await f(t);const s=i.resolve(e);if(process.platform==="win32")try{await l.promises.symlink(s,t,"junction"),y(n||"symlink","DEBUG","Created dir junction (windows)",{linkPath:t,targetPath:s,type:"junction"});return}catch(o){y(n||"symlink","WARN","Windows junction failed, try dir symlink",{linkPath:t,targetPath:s,error:o.message}),await f(t),await l.promises.symlink(s,t,"dir"),y(n||"symlink","DEBUG","Created dir symlink (windows)",{linkPath:t,targetPath:s,type:"dir"});return}let a=i.relative(i.dirname(t),s);if(a=a.split(i.sep).join("/"),!a||i.isAbsolute(a))throw new Error(`Cannot create relative symlink from ${t} to ${e} (got: ${a||"<empty>"})`);await l.promises.symlink(a,t),y(n||"symlink","DEBUG","Created dir symlink",{linkPath:t,targetPath:s,relativeTarget:a,type:"symlink"})}async function D(t,e,n,s){const r=s||"materialize-copy";for(const p of m){const u=i.join(t,w[p]);await f(i.join(u,"skills")),await f(i.join(u,"agents"))}const a=await T(t);await f(a.skillsDir),await f(a.agentsDir),await c(a.skillsDir),await c(a.agentsDir),await d(e,a.skillsDir),await d(n,a.agentsDir);const o=await S(t,r);return y(r,"INFO","Materialized agent store by copy (legacy mode)",{workspaceRoot:t,agentSkillsDir:e,agentAgentsDir:n,syncElapsedMs:o?.elapsedMs}),o}async function M(t,e,n,s){const r=Date.now(),a=s||i.basename(t)||"linkWorkspace";y(a,"INFO","Start linkWorkspaceToAgentStore",{workspaceRoot:t,agentSkillsDir:e,agentAgentsDir:n,platform:process.platform});try{for(const p of m){const u=i.join(t,w[p]);await c(u),await A(i.join(u,"skills"),e,a),await A(i.join(u,"agents"),n,a)}const o=Date.now()-r;return y(a,"INFO","linkWorkspaceToAgentStore completed",{workspaceRoot:t,agentTypes:m,mode:"symlink",elapsedMs:o}),{agentTypes:m,elapsedMs:o,mode:"symlink"}}catch(o){y(a,"WARN","Link to agent store failed, fallback to copy mode",{workspaceRoot:t,platform:process.platform,error:o.message});const p=await D(t,e,n,a),u=Date.now()-r;return y(a,"INFO","linkWorkspaceToAgentStore completed (copy fallback)",{workspaceRoot:t,agentTypes:m,mode:"copy-fallback",elapsedMs:u,syncElapsedMs:p?.elapsedMs}),{agentTypes:m,elapsedMs:u,mode:"copy-fallback",syncElapsedMs:p?.elapsedMs}}}async function C(t,e,n,s){const r=i.join(t,w[e]),a=i.join(r,"skills"),o=i.join(r,"agents");await c(r),await f(a),await f(o),await c(a),await c(o),await Promise.all([d(n.skillsDir,a),d(n.agentsDir,o)]),y(s,"DEBUG","syncAgents target completed",{agentType:e,targetRoot:r})}async function S(t,e){const n=Date.now(),s=e||i.basename(t)||"syncAgents",r=m.filter(p=>p!==g);y(s,"INFO","Start syncAgents",{workspaceRoot:t,targetAgentTypes:r,concurrency:k});const a=await T(t);await Promise.all(r.map(p=>C(t,p,a,s)));const o=Date.now()-n;return y(s,"INFO","syncAgents completed",{workspaceRoot:t,agentTypes:m,elapsedMs:o}),{agentTypes:m,elapsedMs:o}}function O(t){if(!t)return!1;const e=i.join(t,w[g],"skills");try{return l.lstatSync(e).isSymbolicLink()}catch{return!1}}export{w as AGENT_ROOT_MAP,m as ALL_AGENT_TYPES,T as ensurePrimaryAgentDirs,S as syncAgents,M as linkWorkspaceToAgentStore,A as forceDirSymlink,d as copyDirContents,O as isWorkspaceSkillsSymlinked};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
`,"utf8")}async function
|
|
1
|
+
import o from"fs";import i from"path";import"../../appConfig/index.js";import{log as p}from"../log/logUtils.js";import{ValidationError as y}from"../error/errorHandler.js";import{computerUserRoot as d,resolveWorkspaceRoot as g}from"../computer/workspaceContext.js";const m=".dynamic_add.lock",A=".sync.lock",R=5*60*1e3,f="manifest.json";function S(t,e=null){return e?.isUserApp&&e?.appId?e.workspacePath?i.join(e.workspacePath,".agent-store"):i.join(g(e),".agent-store",String(e.appId)):e?.isNormalProject&&e?.appId?i.join(d(t),".agent-store",`np-${e.appId}`):null}function k(t,e,r=null){const s=S(t,r);if(r?.isUserApp&&s)return i.join(s,String(e));if(!g(r))throw new y("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return i.join(d(t),".agent-store",String(e))}async function E(t){try{const e=await o.promises.readFile(i.join(t,f),"utf8"),r=JSON.parse(e);return r&&typeof r=="object"&&typeof r.agents=="object"?r:{agents:{}}}catch{return{agents:{}}}}async function P(t,e){await o.promises.mkdir(t,{recursive:!0});const r=i.join(t,`${f}.${process.pid}.${Date.now()}.tmp`);await o.promises.writeFile(r,JSON.stringify(e,null,2),"utf8"),await o.promises.rename(r,i.join(t,f))}function _(t,e){const r={};for(const[s,a]of Object.entries(t.agents||{}))for(const n of a?.[e]||[])(r[n]=r[n]||[]).push(s);return r}async function C(t,e,r,s=null){const a=k(t,e,s);if(s?.isUserApp){const u=i.dirname(i.dirname(a));if(!o.existsSync(u))throw new y(`userapp agent-store mount does not exist: ${u}`,{field:"USERAPP_WORKSPACE_DIR"})}const n=i.join(a,"skills"),c=i.join(a,"agents");return await o.promises.mkdir(n,{recursive:!0}),await o.promises.mkdir(c,{recursive:!0}),p(r||"agent-store","DEBUG","Agent store dirs ready",{agentStorePath:a,skillsDir:n,agentsDir:c}),{agentStorePath:a,skillsDir:n,agentsDir:c}}async function O(t,e){await o.promises.mkdir(t,{recursive:!0});const r=i.join(t,A);try{const s=await o.promises.open(r,"wx");return await s.writeFile(`${process.pid}:${Date.now()}`),await s.close(),{acquired:!0,lockPath:r}}catch(s){if(s&&s.code==="EEXIST"){try{const a=await o.promises.stat(r),n=Date.now()-a.mtimeMs;if(n>R){await o.promises.rm(r,{force:!0});const c=await o.promises.open(r,"wx");return await c.writeFile(`${process.pid}:${Date.now()}`),await c.close(),p(e||"agent-store","WARN","Stole stale agent store lock",{lockPath:r,ageMs:n}),{acquired:!0,lockPath:r}}}catch(a){p(e||"agent-store","WARN","Check agent store lock failed",{lockPath:r,error:a.message})}return p(e||"agent-store","INFO","Skip agent store update, lock held by another request",{lockPath:r}),{acquired:!1,lockPath:r}}throw s}}async function D(t,e){if(t)try{await o.promises.rm(t,{force:!0})}catch(r){p(e||"agent-store","WARN","Release agent store lock failed",{lockPath:t,error:r.message})}}function h(t){const e=i.join(t,m);return o.existsSync(e)&&o.statSync(e).isFile()}async function j(t){await o.promises.mkdir(t,{recursive:!0});const e=i.join(t,m);await o.promises.writeFile(e,`${Date.now()}
|
|
2
|
+
`,"utf8")}async function x(t,e,r){const s=new Set((Array.isArray(e)?e:[]).map(u=>String(u||"").trim()).filter(Boolean));if(!o.existsSync(t))return{removed:[],keptDynamic:[]};const a=[],n=[],c=await o.promises.readdir(t,{withFileTypes:!0});for(const u of c){if(!u.isDirectory()||s.has(u.name))continue;const l=i.join(t,u.name);if(h(l)){n.push(u.name);continue}await o.promises.rm(l,{recursive:!0,force:!0}),a.push(u.name)}return p(r||"agent-store","INFO","Prune agent skills completed",{skillsDir:t,keepCount:s.size,removed:a,keptDynamic:n}),{removed:a,keptDynamic:n}}async function F(t,e,r,s={}){const{asDynamic:a=!1}=s,n=i.join(e,r);try{await o.promises.lstat(n),await o.promises.rm(n,{recursive:!0,force:!0})}catch{}if(await o.promises.mkdir(e,{recursive:!0}),await w(t,n),a)await j(n);else{const c=i.join(n,m);o.existsSync(c)&&await o.promises.rm(c,{force:!0})}return n}async function w(t,e){try{await o.promises.rename(t,e)}catch(r){if(r&&r.code==="EXDEV"){await o.promises.cp(t,e,{recursive:!0}),await o.promises.rm(t,{recursive:!0,force:!0});return}throw r}}async function N(t,e){await o.promises.rm(e,{recursive:!0,force:!0}),await o.promises.mkdir(i.dirname(e),{recursive:!0}),t&&o.existsSync(t)?await w(t,e):await o.promises.mkdir(e,{recursive:!0})}function I(t,e){if(!t||!e)return!1;try{return o.statSync(i.join(t,e)).isDirectory()}catch{return!1}}export{m as DYNAMIC_ADD_LOCK,k as getAgentStorePath,S as getProjectStoreRoot,E as readManifest,P as writeManifest,_ as reverseRefs,C as ensureAgentStoreDirs,O as tryAcquireAgentStoreLock,D as releaseAgentStoreLock,h as hasDynamicAddLock,j as ensureDynamicAddLock,x as pruneAgentSkills,F as installSkillDir,N as replaceAgentsDir,w as moveOrCopyDirectory,I as agentSkillExists};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import c from"fs";import h from"path";import fe from"archiver";import{lookup as Ce}from"mime-types";import P from"../../appConfig/index.js";import{log as f}from"../log/logUtils.js";import{ValidationError as E,SystemError as z,FileError as Pe}from"../error/errorHandler.js";import{extractZip as _e}from"../common/zipUtils.js";import{moveDirectory as Le,movePath as oe}from"../common/fileSystemUtils.js";import{resolveLogDir as Ae,resolveWorkspaceDir as O,resolveWorkspaceRoot as me}from"./workspaceContext.js";const B=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),Te=5*1024*1024*1024,H=P.DOWNLOAD_MAX_FILE_SIZE_BYTES||Te;function q(e){return h.sep==="\\"?e.replace(/\\/g,"/"):e}function de(e,r){return q(h.relative(e,r))}function pe(e,r){return e?`${e}/${r}`:r}function Z(e){return e!=null&&e.limit!=null&&e.pushed>=e.limit}function K(e){e!=null&&(e.pushed+=1)}async function he(e,r,t,i,o,a={}){const{typeFilter:s=null,limitState:d=null,levelsLeft:m=1}=a,w=[],g=await c.promises.readdir(e,{withFileTypes:!0});g.sort((l,y)=>l.isDirectory()&&!y.isDirectory()?-1:!l.isDirectory()&&y.isDirectory()?1:l.name.toLowerCase().localeCompare(y.name.toLowerCase()));const n=de(r,e);for(const l of g){if(Z(d))break;if(l.name.startsWith(".")&&l.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(l.name)||l.isDirectory()&&Ee(l.name))continue;const u=pe(n,l.name);if(l.isDirectory()){if(s!=="file"&&(w.push({name:u,isDir:!0}),K(d)),m>1&&!Z(d))try{const p=await he(h.join(e,l.name),r,t,i,o,{typeFilter:s,limitState:d,levelsLeft:m-1});w.push(...p)}catch(p){f(t,"WARN",`Depth descent failed, skip subtree: ${u}`,{error:p.message})}continue}if(s!=="dir"&&!(l.isSymbolicLink()&&await ge(r,h.join(e,l.name))))try{w.push({name:u,isDir:!1,fileProxyUrl:Q(i,u,o),isLink:l.isSymbolicLink()}),K(d)}catch(p){f(t,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${e}/${l.name}`,{error:p.message})}}return w}async function we(e,r,t,i,o="",a={}){const{typeFilter:s=null,limitState:d=null}=a,m=a.rootDir||e,w=[],g=await c.promises.readdir(e,{withFileTypes:!0});g.sort((n,l)=>n.isDirectory()&&!l.isDirectory()?-1:!n.isDirectory()&&l.isDirectory()?1:n.name.toLowerCase().localeCompare(l.name.toLowerCase()));for(const n of g){if(Z(d))break;const l=h.join(e,n.name);if(n.name.startsWith(".")&&n.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(n.name)||n.isDirectory()&&Ee(n.name)||n.isSymbolicLink()&&await ge(m,l))continue;const u=pe(o,n.name);if(n.isDirectory()){s!=="file"&&!Z(d)&&(w.push({name:u,isDir:!0}),K(d));try{const p=await we(l,r,t,i,u,a);w.push(...p.entries)}catch(p){f(r,"WARN",`Depth descent failed, skip subtree: ${u}`,{error:p.message})}continue}if(s!=="dir")try{w.push({name:u,isDir:!1,fileProxyUrl:Q(t,u,i),isLink:n.isSymbolicLink()}),K(d)}catch(p){f(r,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${l}`,{error:p.message})}}return{entries:w}}const Y=process.platform==="win32"?/^[\/\\]+/:/^\/+/;async function X(e,r){try{const t=await c.promises.realpath(e),i=await c.promises.realpath(r);return i!==t&&!i.startsWith(t+h.sep)}catch{return!1}}async function ge(e,r){try{const t=await c.promises.realpath(e),i=await c.promises.realpath(r);return i!==t&&!i.startsWith(t+h.sep)}catch{return!0}}const ye=process.platform==="win32"?new Set((P.TRAVERSE_EXCLUDE_DIRS||[]).map(e=>String(e).toLowerCase())):new Set(P.TRAVERSE_EXCLUDE_DIRS||[]);function Ee(e){return process.platform==="win32"?ye.has(e.toLowerCase()):ye.has(e)}function Se(e,r){const t=r==null?"":String(r),i=t.trim();if(!i||i==="."||i==="/")return h.resolve(e);const o=h.normalize(t).replace(Y,"");if(!o||o===".")return h.resolve(e);if(h.isAbsolute(t)||o.split(h.sep).includes(".."))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:r});const a=h.resolve(e),s=h.resolve(e,o);if(s!==a&&!s.startsWith(a+h.sep))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:r});return s}function J(e,r){const t=r==null?"":String(r);if(!t.trim())return null;const i=h.resolve(e);let o;if(h.isAbsolute(t))o=h.resolve(t);else{const s=h.normalize(t).replace(Y,"");if(!s||s==="."||s.split(h.sep).includes(".."))return null;o=h.resolve(e,s)}if(o!==i&&!o.startsWith(i+h.sep))return null;const a=q(h.relative(i,o));return!a||a.startsWith("..")?null:{absPath:o,name:a}}function Q(e,r,t){if(!e||!r)return null;const i=r.split("/").map(a=>encodeURIComponent(a)).join("/");let o=`${e}/${i}`;return t&&(o+=`?customTargetDir=${encodeURIComponent(t)}`),o}async function ze(e,r,t,i,o,a=null){if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!t||!String(t).trim())throw new E("filePath \u4E0D\u80FD\u4E3A\u7A7A",{field:"filePath"});const s=String(e),d=String(r),m=o&&o.trim()?o.trim():null,w=m||O(a,s,d);if(!c.existsSync(w))return{exists:!1};let g=J(w,t);if(!g&&String(t).startsWith("/")){const n=String(t).replace(Y,"");n&&(g=J(w,n))}if(!g)return{exists:!1};try{if(await X(w,g.absPath))return{exists:!1};if(!(await c.promises.stat(g.absPath)).isFile())return{exists:!1}}catch{return{exists:!1}}return{exists:!0,name:g.name,fileProxyUrl:Q(i,g.name,m)}}const Oe=100,$e=1e3,Me=8,Re=1e3;function We(e){return h.extname(e).replace(/^\./,"").toLowerCase()||""}async function Ue(e,r,t){const i=new Array(e.length),o=Math.max(1,Math.min(r,e.length));let a=0;return await Promise.all(Array.from({length:o},async()=>{for(;;){const s=a++;if(s>=e.length)return;i[s]=await t(e[s],s)}})),i}function je(e){return!(e.startsWith(".")&&e!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(e)||P.TRAVERSE_EXCLUDE_DIRS.includes(e))}async function Be(e){const r=await c.promises.opendir(e);let t=0;for await(const i of r)if(je(i.name)&&(t+=1,t>=Re))return Re;return t}function ae(e,r){return{path:e,isDir:null,isLink:null,size:null,mtimeMs:null,extension:null,mimeType:null,linkTarget:null,childCount:null,...r?{error:r}:{}}}async function Xe(e,r,t){const i=r==null?"":String(r);let o=i.trim()?J(e,i):null;if(!o&&i.startsWith("/")){const a=i.replace(Y,"");a&&(o=J(e,a))}if(!o||await X(e,o.absPath))return ae(i,"illegal path");try{const a=await c.promises.lstat(o.absPath),s=a.isDirectory(),d=a.isSymbolicLink(),m={path:i,isDir:s,isLink:d,size:s?null:a.size,mtimeMs:a.mtimeMs,extension:s?null:We(i),mimeType:s?null:Ce(i)||"application/octet-stream",linkTarget:null,childCount:null};if(d)try{m.linkTarget=await c.promises.readlink(o.absPath)}catch(w){f(t,"WARN","Readlink failed, linkTarget set to null",{filePath:i,error:w.message})}if(s)try{m.childCount=await Be(o.absPath)}catch(w){f(t,"WARN","Count directory entries failed, childCount set to null",{filePath:i,error:w.message})}return m}catch(a){return ae(i,a.code||a.message)}}async function Ve(e,r,t,i,o=null,a=null){const s=Date.now(),d=`computer:${e}:${r}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!Array.isArray(t)||t.length===0)throw new E("filePaths \u5FC5\u987B\u4E3A\u975E\u7A7A\u6570\u7EC4",{field:"filePaths"});const m=Number.parseInt(a,10),w=Number.isFinite(m)&&m>0?Math.min(m,$e):Oe;if(t.length>w)throw new E(`filePaths \u5355\u6B21\u6700\u591A ${w} \u6761`,{field:"filePaths",count:t.length});const g=String(e),n=String(r),y=(i==null?"":String(i).trim())||null,u=y||O(o,g,n);if(!c.existsSync(u))return f(d,"INFO","Target directory does not exist, returning empty metas",{targetDir:u,userId:g,cId:n}),{metas:[]};const p=await Ue(t,Me,S=>Xe(u,S,d));return f(d,"INFO","File metadata queried",{targetDir:u,count:p.length,failed:p.filter(S=>S.error).length,customTargetDir:y,userId:g,cId:n,elapsedMs:Date.now()-s}),{metas:p}}async function Ie(e,r,t,i,o=""){const a=await c.promises.readdir(h.join(e,o),{withFileTypes:!0});let s=0;for(const d of a){const m=o?h.join(o,d.name):d.name,w=m.split(h.sep).filter(Boolean);if(w.some(y=>y.startsWith(".")))continue;const g=w[w.length-1];if(r.includes(g)||w.some(y=>t.includes(y)))continue;const n=h.join(e,m);let l;try{l=await c.promises.lstat(n)}catch(y){f(i,"WARN","Error occurred when getting file stats, skipping",{filePath:m.replace(/\\/g,"/"),error:y.message});continue}l.isSymbolicLink()||l.nlink>1||(l.isDirectory()?s+=await Ie(e,r,t,i,m):l.isFile()&&(s+=l.size))}return s}async function Ge(e,r,t,i,o,a,s,d,m,w=null){const g=Date.now(),n=`computer:${e}:${r}`,l=!(a===!1||a==="false");if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const y=d==null?"":String(d).trim().toLowerCase();let u=null;if(y&&y!=="all")if(y==="file")u="file";else if(y==="dir"||y==="directory")u="dir";else throw new E("type \u4EC5\u652F\u6301 file/dir/all",{field:"type",value:d});const p=D=>/^\d+$/.test(String(D))?parseInt(String(D),10):NaN;let S=null;if(m!=null&&m!==""){const D=p(m);if(!Number.isInteger(D)||D<0)throw new E("limit \u5FC5\u987B\u4E3A\u975E\u8D1F\u6574\u6570",{field:"limit",value:m});S=D}let F=null;if(!l&&s!=null&&s!==""){const D=p(s);if(!Number.isInteger(D)||D<1||D>10)throw new E("depth \u9700\u4E3A 1-10 \u7684\u6574\u6570",{field:"depth",value:s});F=D}const R=String(e),b=String(r),v=i&&i.trim()?i.trim():null,I=v||O(w,R,b);if(!c.existsSync(I))return f(n,"INFO","Directory does not exist, returning empty list",{targetDir:I,userId:R,cId:b}),{files:[],recursive:l,depth:F,type:u||"all",limit:S};const k=Se(I,o);if(await X(I,k))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:o});if(!c.existsSync(k))return f(n,"INFO","List path does not exist, returning empty list",{targetDir:I,listDir:k,relativePath:o||"",userId:R,cId:b}),{files:[],recursive:l,depth:F,type:u||"all",limit:S};if(!(await c.promises.stat(k)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:o});f(n,"DEBUG","Start getting user file list",{targetDir:I,listDir:k,relativePath:o||"",recursive:l,userId:R,cId:b});try{const D={typeFilter:u,limitState:{limit:S,pushed:0},levelsLeft:!l&&F!=null?F:1},ee=l?(await we(k,n,t,v,de(I,k),{...D,rootDir:I})).entries:await he(k,I,n,t,v,D);return f(n,"INFO","User file list obtained successfully",{fileCount:ee.length,targetDir:I,listDir:k,relativePath:o||"",recursive:l,depth:F,type:u||"all",limit:S,userId:R,cId:b,elapsedMs:Date.now()-g}),{files:ee,recursive:l,depth:F,type:u||"all",limit:S}}catch(D){throw D instanceof E?D:(f(n,"ERROR","Failed to get user file list",{targetDir:I,listDir:k,relativePath:o||"",recursive:l,userId:R,cId:b,error:D.message,elapsedMs:Date.now()-g}),new z(`Failed to get file list: ${D.message}`,{targetDir:I,originalError:D.message}))}}const He=5e3;function le(e,r){const t=Number.parseInt(e,10);if(!Number.isFinite(t)||t<=0)throw new E(`${r} \u5FC5\u987B\u4E3A\u6B63\u6574\u6570`,{field:r,value:e});return t}function Fe(e,r,t){return t?r.toLowerCase().includes(t)?!0:e.toLowerCase().includes(t):!1}const qe=new Set([".git",".svn",".hg","node_modules","__pycache__",".venv","venv","virtualenv",".mypy_cache",".pytest_cache",".ruff_cache",".cache",".tmp"]),Ze=new Set([".DS_Store","Thumbs.db","desktop.ini"]);function De(e,r,t){return!!(Ze.has(e.name)||r.includes(e.name)||e.isDirectory()&&(qe.has(e.name)||t.includes(e.name)))}function ve(e,r,t,i){for(let o=r;o<e.length;o++)if(!De(e[o],t,i))return!0;return!1}function be(e,r){return Date.now()-e>=r}async function Ke(e,r,t,i,o,a,s,d,m,w,g=null){const n=Date.now(),l=`computer:${e}:${r}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const y=(i==null?"":String(i)).trim();if(!y)throw new E("kw \u4E0D\u80FD\u4E3A\u7A7A",{field:"kw"});const u=le(d,"limit"),p=le(m,"maxVisit"),S=le(w,"timeoutMs"),F=y.toLowerCase(),R=(()=>{const N=s==null?"":String(s).trim().toLowerCase();return N==="file"?"file":N==="dir"||N==="directory"?"dir":null})(),b=N=>R==null||R==="dir"===N,v=String(e),I=String(r),k=o&&o.trim()?o.trim():null,C=k||O(g,v,I);if(!c.existsSync(C))return{files:[],truncated:!1,visited:0};const D=Se(C,a);if(!c.existsSync(D))return{files:[],truncated:!1,visited:0};if(await X(C,D))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:a});if(!(await c.promises.stat(D)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:a});const Ne=q(h.relative(C,D)),te=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],re=P.TRAVERSE_EXCLUDE_DIRS||[],_=[],ie=new Set;let $=0,ne=!1,A=!1;const T=[Ne],U=()=>$>=p||be(n,S);for(;T.length>0;){if(U()){A=!0;break}if(_.length>=u){T.length>0&&(A=!0);break}const N=T.shift();if(ie.has(N))continue;ie.add(N);const j=N?h.join(C,N):C;let M;try{M=await c.promises.readdir(j,{withFileTypes:!0})}catch(x){f(l,"WARN","search readdir failed",{dirRel:N,error:x.message});continue}M.sort((x,L)=>x.isDirectory()&&!L.isDirectory()?-1:!x.isDirectory()&&L.isDirectory()?1:x.name.toLowerCase().localeCompare(L.name.toLowerCase()));const se=[];let V=!1,G=!1;for(let x=0;x<M.length;x++){const L=M[x];if(De(L,te,re))continue;if(U()){A=!0,V=!0,G=!0;break}$+=1;const ue=h.join(j,L.name),W=q(h.relative(C,ue));if(L.isDirectory()){if(se.push(W),b(!0)&&_.length<u&&Fe(W,L.name,F)&&(_.push({name:W,isDir:!0}),_.length>=u)){V=!0,G=ve(M,x+1,te,re);break}continue}try{if(b(!1)&&_.length<u&&Fe(W,L.name,F)&&(_.push({name:W,isDir:!1,fileProxyUrl:Q(t,W,k),isLink:L.isSymbolicLink()}),_.length>=u)){V=!0,G=ve(M,x+1,te,re);break}}catch(xe){f(l,"WARN",`search \u5904\u7406\u6587\u4EF6\u5931\u8D25: ${ue}`,{error:xe.message})}}if(V||U()){(U()||G||se.length>0||T.length>0)&&(A=!0);continue}for(const x of se){if(U()){A=!0;break}if(T.length>=He){A=!0;break}if($+T.length>=p){A=!0;break}ie.has(x)||T.push(x)}}return _.sort((N,j)=>N.isDir!==j.isDir?N.isDir?-1:1:String(N.name).localeCompare(String(j.name))),ne=A||T.length>0||$>=p||be(n,S),f(l,"INFO","File search completed",{kw:y,matchCount:_.length,visited:$,truncated:ne,relativePath:a||"",elapsedMs:Date.now()-n}),{files:_,truncated:ne,visited:$}}async function Ye(e,r,t,i,o=null){const a=Date.now(),s=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});const d=String(e),m=String(r),w=i&&i.trim()?i.trim():null,g=w||O(o,d,m);c.existsSync(g)||c.mkdirSync(g,{recursive:!0});for(let n=0;n<t.length;n++){const l=t[n];if(!l||typeof l.operation!="string")throw new E(`files[${n}].operation cannot be empty`,{field:`files[${n}].operation`});if(!l.name||typeof l.name!="string")throw new E(`files[${n}].name cannot be empty`,{field:`files[${n}].name`});const y=l.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(y))throw new E(`files[${n}].operation must be one of create, delete, rename or modify`,{field:`files[${n}].operation`});if(y==="rename"&&!l.renameFrom)throw new E(`files[${n}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${n}].renameFrom`});if(y==="modify"&&l.isDir!==!0&&typeof l.contents!="string")throw new E(`files[${n}].contents must be a string (modify operation requires)`,{field:`files[${n}].contents`})}f(s,"DEBUG","Start updating user files",{userId:d,cId:m,filesCount:t.length});try{for(const n of t){const l=n.operation.toLowerCase(),y=n.name,u=h.normalize(y).replace(/^[\/\\]+/,""),p=h.join(g,u),S=h.resolve(p),F=h.resolve(g);if(!S.startsWith(F+h.sep)&&S!==F){f(s,"WARN","File path is not secure, skipping",{filePath:u,resolvedPath:S});continue}switch(l){case"create":{if(n.isDir===!0){if(c.existsSync(p)){if((await c.promises.stat(p)).isFile())throw new E("Cannot create directory, file with the same name already exists",{filePath:u});f(s,"INFO","Directory already exists, skipping creation",{filePath:u});break}await c.promises.mkdir(p,{recursive:!0}),f(s,"INFO","Directory created successfully",{filePath:u});break}if(c.existsSync(p)){if((await c.promises.stat(p)).isDirectory())throw new E("Cannot create file, directory with the same name already exists",{filePath:u});f(s,"INFO","File already exists, skipping creation",{filePath:u});break}await c.promises.mkdir(h.dirname(p),{recursive:!0});const R=n.contents||"";await c.promises.writeFile(p,R,"utf8"),f(s,"INFO","File created successfully",{filePath:u});break}case"delete":{c.existsSync(p)?(await c.promises.stat(p)).isDirectory()?(await c.promises.rm(p,{recursive:!0,force:!0}),f(s,"INFO","Directory deleted successfully",{filePath:u})):(await c.promises.unlink(p),f(s,"INFO","File deleted successfully",{filePath:u})):f(s,"WARN","The file or directory to be deleted does not exist",{filePath:u});break}case"rename":{const R=n.renameFrom;if(!R||typeof R!="string"){f(s,"WARN","Rename operation missing renameFrom",{filePath:u});break}const b=h.normalize(R).replace(/^[\/\\]+/,""),v=h.join(g,b),I=h.resolve(v);if(!I.startsWith(F+h.sep)&&I!==F){f(s,"WARN","Source path is not secure, skipping rename",{sourcePath:b,targetPath:u});break}if(c.existsSync(v)){const C=(await c.promises.stat(v)).isDirectory();await c.promises.mkdir(h.dirname(p),{recursive:!0}),await c.promises.rename(v,p),f(s,"INFO",C?"Directory renamed successfully":"File renamed successfully",{sourcePath:b,targetPath:u})}else f(s,"WARN","The file or directory to be renamed does not exist",{sourcePath:b});break}case"modify":{if(!c.existsSync(p)){f(s,"WARN","The file to be modified does not exist",{filePath:u});break}if((await c.promises.stat(p)).isDirectory()){f(s,"INFO","The target is a directory, skipping modification",{filePath:u});break}const b=typeof n.contents=="string"?n.contents:"";if(await c.promises.readFile(p,"utf8")===b){f(s,"INFO","File content has no changes, skipping write",{filePath:u});break}await c.promises.writeFile(p,b,"utf8"),f(s,"INFO","File modified successfully",{filePath:u});break}default:{f(s,"WARN","Unsupported operation type",{operation:l,filePath:u});break}}}return f(s,"INFO","User files updated successfully",{userId:d,cId:m,filesCount:t.length,elapsedMs:Date.now()-a}),{success:!0,message:"User files updated successfully",userId:d,cId:m,filesCount:t.length}}catch(n){throw f(s,"ERROR","User files updated failed",{userId:d,cId:m,error:n.message,elapsedMs:Date.now()-a}),new z(`User files updated failed: ${n.message}`,{userId:d,cId:m,originalError:n.message})}}async function ce(e,r,t,i,o,a=null){const s=Date.now(),d=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!t)throw new E("file cannot be empty",{field:"file"});if(!i||typeof i!="string")throw new E("filePath cannot be empty",{field:"filePath"});const m=String(e),w=String(r),g=o&&o.trim()?o.trim():null,n=g||O(a,m,w);c.existsSync(n)||c.mkdirSync(n,{recursive:!0});const l=h.normalize(i).replace(/^[\/\\]+/,""),y=h.join(n,l),u=h.resolve(y),p=h.resolve(n);if(!u.startsWith(p+h.sep)&&u!==p)throw new E("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:i,resolvedPath:u});try{if(await c.promises.mkdir(h.dirname(y),{recursive:!0}),t.buffer)await c.promises.writeFile(y,t.buffer);else if(typeof t.contents=="string")await c.promises.writeFile(y,t.contents,"utf8");else throw new E("File content format is incorrect",{field:"file",hasBuffer:!!t.buffer,hasContents:typeof t.contents});return f(d,"INFO","File uploaded successfully",{userId:m,cId:w,filePath:l,targetPath:u,fileSize:t.buffer?t.buffer.length:t.contents?Buffer.byteLength(t.contents,"utf8"):0,elapsedMs:Date.now()-s}),{success:!0,message:"File uploaded successfully",fileSize:t.buffer?t.buffer.length:t.contents?Buffer.byteLength(t.contents,"utf8"):0}}catch(S){throw f(d,"ERROR","File upload failed",{userId:m,cId:w,filePath:l,error:S.message,elapsedMs:Date.now()-s}),new z(`File upload failed: ${S.message}`,{userId:m,cId:w,filePath:l,originalError:S.message})}}async function Je(e,r,t,i,o,a=null){const s=Date.now(),d=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});if(!Array.isArray(i))throw new E("filePaths must be an array",{field:"filePaths"});if(t.length!==i.length)throw new E(`File count (${t.length}) does not match path count (${i.length})`,{field:"filePaths"});f(d,"DEBUG","Start batch uploading files",{userId:e,cId:r,filesCount:t.length});const m=[];try{for(let n=0;n<t.length;n++){const l=t[n],y=i[n];if(!l){f(d,"WARN","Empty file object encountered in batch upload, skipping",{index:n,filePath:y}),m.push({success:!1,filePath:y,error:"Empty file object"});continue}if(!y||typeof y!="string"){f(d,"WARN","Invalid file path in batch upload, skipping",{index:n,originalname:l.originalname}),m.push({success:!1,filePath:y||"",originalname:l.originalname,error:"Invalid file path"});continue}try{const u=await ce(e,r,l,y,o,a);m.push({success:!0,filePath:y,originalname:l.originalname,...u})}catch(u){f(d,"ERROR","Single file upload failed in batch upload",{filePath:y,originalname:l.originalname,error:u.message}),m.push({success:!1,filePath:y,originalname:l.originalname,error:u.message})}}const w=m.filter(n=>n.success).length,g=m.filter(n=>!n.success).length;return f(d,"INFO","Batch upload files completed",{userId:e,cId:r,totalCount:t.length,successCount:w,failCount:g,elapsedMs:Date.now()-s}),{success:!0,message:"Batch upload completed",totalCount:t.length,successCount:w,failCount:g,results:m}}catch(w){throw f(d,"ERROR","Batch upload files failed",{userId:e,cId:r,error:w.message,elapsedMs:Date.now()-s}),new z(`Batch upload files failed: ${w.message}`,{userId:e,cId:r,originalError:w.message})}}async function Qe(e,r,t,i=null){const o=Date.now(),a=`computer:${e}:${r}`,s=me(i);if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!s&&!i?.workspacePath)throw new z("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const d=String(e),m=String(r),w=t&&t.trim()?t.trim():null,g=w||O(i,d,m);if(!c.existsSync(g)){const S=`${d}_${m}.zip`;f(a,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:g,userId:d,cId:m,zipFileName:S});const F=fe("zip",{zlib:{level:9}});return F.append(null,{name:`${d}_${m}/`,type:"directory"}),F.on("warning",R=>{if(R.code==="ENOENT")f(a,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw f(a,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),F.on("error",R=>{f(a,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:F,zipFileName:S}}const n=`${d}_${m}.zip`;f(a,"DEBUG","Start creating workspace directory zip",{targetDir:g,zipFileName:n});const l=fe("zip",{zlib:{level:9}}),y=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],u=P.TRAVERSE_EXCLUDE_DIRS||[],p=await Ie(g,y,u,a);if(p>H){const S=H/1024/1024,F=(p/1024/1024).toFixed(2);throw f(a,"WARN","Download rejected due to oversized workspace",{targetDir:g,downloadableSize:p,maxSizeBytes:H}),new E(`Download failed: total file size ${F}MB exceeds limit ${S}MB`,{field:"downloadSize",downloadableSize:p,maxSizeBytes:H})}return l.directory(g,`${d}_${m}`,S=>{const F=S.name||"",R=F.split(/[\/\\]/).filter(Boolean);if(R.some(v=>v.startsWith(".")))return!1;const b=R[R.length-1];if(y.includes(b)||R.some(v=>u.includes(v)))return!1;try{const v=h.join(g,F),I=c.lstatSync(v);if(I.isSymbolicLink()||I.nlink>1)return!1}catch(v){return f(a,"WARN","Error occurred when detecting link file, skipping",{filePath:F,error:v.message}),!1}return S}),l.on("warning",S=>{if(S.code==="ENOENT")f(a,"WARN","Encountered file problem when creating zip",{message:S.message,code:S.code});else throw f(a,"ERROR","Encountered warning when creating zip",{message:S.message,code:S.code}),S}),l.on("error",S=>{f(a,"ERROR","Failed to create zip",{message:S.message,elapsedMs:Date.now()-o})}),l.on("end",()=>{f(a,"INFO","Workspace directory zip created successfully",{targetDir:g,zipFileName:n,elapsedMs:Date.now()-o})}),{archive:l,zipFileName:n}}async function et(e,r,t=200,i=null){const o=Date.now(),a=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});const s=String(e),d=String(r),m=Ae(i,s,d);if(!m)return f(a,"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(m))return f(a,"DEBUG","Log directory does not exist",{logDir:m}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const g=(await c.promises.readdir(m,{withFileTypes:!0})).filter(I=>I.isFile()).map(I=>I.name);if(g.length===0)return f(a,"DEBUG","No log file found",{logDir:m}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const n=[];for(const I of g){const k=h.join(m,I),C=await c.promises.stat(k);n.push({name:I,fullPath:k,mtime:C.mtimeMs,size:C.size})}n.sort((I,k)=>k.mtime-I.mtime);const l=n[0],u=(await c.promises.readFile(l.fullPath,"utf8")).split(`
|
|
1
|
+
import c from"fs";import h from"path";import fe from"archiver";import{lookup as Ce}from"mime-types";import P from"../../appConfig/index.js";import{log as f}from"../log/logUtils.js";import{ValidationError as E,SystemError as z,FileError as Pe}from"../error/errorHandler.js";import{extractZip as _e}from"../common/zipUtils.js";import{moveDirectory as Le,movePath as oe}from"../common/fileSystemUtils.js";import{resolveLogDir as Ae,resolveWorkspaceDir as O,resolveWorkspaceRoot as me}from"./workspaceContext.js";const B=new Set([".git",".agents",".claude",".nuwax-harness",".opencode",".tmp",".logs"]),Te=5*1024*1024*1024,H=P.DOWNLOAD_MAX_FILE_SIZE_BYTES||Te;function q(e){return h.sep==="\\"?e.replace(/\\/g,"/"):e}function de(e,r){return q(h.relative(e,r))}function pe(e,r){return e?`${e}/${r}`:r}function Z(e){return e!=null&&e.limit!=null&&e.pushed>=e.limit}function K(e){e!=null&&(e.pushed+=1)}async function he(e,r,t,i,o,a={}){const{typeFilter:s=null,limitState:d=null,levelsLeft:m=1}=a,w=[],g=await c.promises.readdir(e,{withFileTypes:!0});g.sort((l,y)=>l.isDirectory()&&!y.isDirectory()?-1:!l.isDirectory()&&y.isDirectory()?1:l.name.toLowerCase().localeCompare(y.name.toLowerCase()));const n=de(r,e);for(const l of g){if(Z(d))break;if(l.name.startsWith(".")&&l.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(l.name)||l.isDirectory()&&Ee(l.name))continue;const u=pe(n,l.name);if(l.isDirectory()){if(s!=="file"&&(w.push({name:u,isDir:!0}),K(d)),m>1&&!Z(d))try{const p=await he(h.join(e,l.name),r,t,i,o,{typeFilter:s,limitState:d,levelsLeft:m-1});w.push(...p)}catch(p){f(t,"WARN",`Depth descent failed, skip subtree: ${u}`,{error:p.message})}continue}if(s!=="dir"&&!(l.isSymbolicLink()&&await ge(r,h.join(e,l.name))))try{w.push({name:u,isDir:!1,fileProxyUrl:Q(i,u,o),isLink:l.isSymbolicLink()}),K(d)}catch(p){f(t,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${e}/${l.name}`,{error:p.message})}}return w}async function we(e,r,t,i,o="",a={}){const{typeFilter:s=null,limitState:d=null}=a,m=a.rootDir||e,w=[],g=await c.promises.readdir(e,{withFileTypes:!0});g.sort((n,l)=>n.isDirectory()&&!l.isDirectory()?-1:!n.isDirectory()&&l.isDirectory()?1:n.name.toLowerCase().localeCompare(l.name.toLowerCase()));for(const n of g){if(Z(d))break;const l=h.join(e,n.name);if(n.name.startsWith(".")&&n.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(n.name)||n.isDirectory()&&Ee(n.name)||n.isSymbolicLink()&&await ge(m,l))continue;const u=pe(o,n.name);if(n.isDirectory()){s!=="file"&&!Z(d)&&(w.push({name:u,isDir:!0}),K(d));try{const p=await we(l,r,t,i,u,a);w.push(...p.entries)}catch(p){f(r,"WARN",`Depth descent failed, skip subtree: ${u}`,{error:p.message})}continue}if(s!=="dir")try{w.push({name:u,isDir:!1,fileProxyUrl:Q(t,u,i),isLink:n.isSymbolicLink()}),K(d)}catch(p){f(r,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${l}`,{error:p.message})}}return{entries:w}}const Y=process.platform==="win32"?/^[\/\\]+/:/^\/+/;async function X(e,r){try{const t=await c.promises.realpath(e),i=await c.promises.realpath(r);return i!==t&&!i.startsWith(t+h.sep)}catch{return!1}}async function ge(e,r){try{const t=await c.promises.realpath(e),i=await c.promises.realpath(r);return i!==t&&!i.startsWith(t+h.sep)}catch{return!0}}const ye=process.platform==="win32"?new Set((P.TRAVERSE_EXCLUDE_DIRS||[]).map(e=>String(e).toLowerCase())):new Set(P.TRAVERSE_EXCLUDE_DIRS||[]);function Ee(e){return process.platform==="win32"?ye.has(e.toLowerCase()):ye.has(e)}function Se(e,r){const t=r==null?"":String(r),i=t.trim();if(!i||i==="."||i==="/")return h.resolve(e);const o=h.normalize(t).replace(Y,"");if(!o||o===".")return h.resolve(e);if(h.isAbsolute(t)||o.split(h.sep).includes(".."))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:r});const a=h.resolve(e),s=h.resolve(e,o);if(s!==a&&!s.startsWith(a+h.sep))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:r});return s}function J(e,r){const t=r==null?"":String(r);if(!t.trim())return null;const i=h.resolve(e);let o;if(h.isAbsolute(t))o=h.resolve(t);else{const s=h.normalize(t).replace(Y,"");if(!s||s==="."||s.split(h.sep).includes(".."))return null;o=h.resolve(e,s)}if(o!==i&&!o.startsWith(i+h.sep))return null;const a=q(h.relative(i,o));return!a||a.startsWith("..")?null:{absPath:o,name:a}}function Q(e,r,t){if(!e||!r)return null;const i=r.split("/").map(a=>encodeURIComponent(a)).join("/");let o=`${e}/${i}`;return t&&(o+=`?customTargetDir=${encodeURIComponent(t)}`),o}async function ze(e,r,t,i,o,a=null){if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!t||!String(t).trim())throw new E("filePath \u4E0D\u80FD\u4E3A\u7A7A",{field:"filePath"});const s=String(e),d=String(r),m=o&&o.trim()?o.trim():null,w=m||O(a,s,d);if(!c.existsSync(w))return{exists:!1};let g=J(w,t);if(!g&&String(t).startsWith("/")){const n=String(t).replace(Y,"");n&&(g=J(w,n))}if(!g)return{exists:!1};try{if(await X(w,g.absPath))return{exists:!1};if(!(await c.promises.stat(g.absPath)).isFile())return{exists:!1}}catch{return{exists:!1}}return{exists:!0,name:g.name,fileProxyUrl:Q(i,g.name,m)}}const Oe=100,$e=1e3,Me=8,Re=1e3;function We(e){return h.extname(e).replace(/^\./,"").toLowerCase()||""}async function Ue(e,r,t){const i=new Array(e.length),o=Math.max(1,Math.min(r,e.length));let a=0;return await Promise.all(Array.from({length:o},async()=>{for(;;){const s=a++;if(s>=e.length)return;i[s]=await t(e[s],s)}})),i}function je(e){return!(e.startsWith(".")&&e!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(e)||P.TRAVERSE_EXCLUDE_DIRS.includes(e))}async function Be(e){const r=await c.promises.opendir(e);let t=0;for await(const i of r)if(je(i.name)&&(t+=1,t>=Re))return Re;return t}function ae(e,r){return{path:e,isDir:null,isLink:null,size:null,mtimeMs:null,extension:null,mimeType:null,linkTarget:null,childCount:null,...r?{error:r}:{}}}async function Xe(e,r,t){const i=r==null?"":String(r);let o=i.trim()?J(e,i):null;if(!o&&i.startsWith("/")){const a=i.replace(Y,"");a&&(o=J(e,a))}if(!o||await X(e,o.absPath))return ae(i,"illegal path");try{const a=await c.promises.lstat(o.absPath),s=a.isDirectory(),d=a.isSymbolicLink(),m={path:i,isDir:s,isLink:d,size:s?null:a.size,mtimeMs:a.mtimeMs,extension:s?null:We(i),mimeType:s?null:Ce(i)||"application/octet-stream",linkTarget:null,childCount:null};if(d)try{m.linkTarget=await c.promises.readlink(o.absPath)}catch(w){f(t,"WARN","Readlink failed, linkTarget set to null",{filePath:i,error:w.message})}if(s)try{m.childCount=await Be(o.absPath)}catch(w){f(t,"WARN","Count directory entries failed, childCount set to null",{filePath:i,error:w.message})}return m}catch(a){return ae(i,a.code||a.message)}}async function Ve(e,r,t,i,o=null,a=null){const s=Date.now(),d=`computer:${e}:${r}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!Array.isArray(t)||t.length===0)throw new E("filePaths \u5FC5\u987B\u4E3A\u975E\u7A7A\u6570\u7EC4",{field:"filePaths"});const m=Number.parseInt(a,10),w=Number.isFinite(m)&&m>0?Math.min(m,$e):Oe;if(t.length>w)throw new E(`filePaths \u5355\u6B21\u6700\u591A ${w} \u6761`,{field:"filePaths",count:t.length});const g=String(e),n=String(r),y=(i==null?"":String(i).trim())||null,u=y||O(o,g,n);if(!c.existsSync(u))return f(d,"INFO","Target directory does not exist, returning empty metas",{targetDir:u,userId:g,cId:n}),{metas:[]};const p=await Ue(t,Me,S=>Xe(u,S,d));return f(d,"INFO","File metadata queried",{targetDir:u,count:p.length,failed:p.filter(S=>S.error).length,customTargetDir:y,userId:g,cId:n,elapsedMs:Date.now()-s}),{metas:p}}async function Ie(e,r,t,i,o=""){const a=await c.promises.readdir(h.join(e,o),{withFileTypes:!0});let s=0;for(const d of a){const m=o?h.join(o,d.name):d.name,w=m.split(h.sep).filter(Boolean);if(w.some(y=>y.startsWith(".")))continue;const g=w[w.length-1];if(r.includes(g)||w.some(y=>t.includes(y)))continue;const n=h.join(e,m);let l;try{l=await c.promises.lstat(n)}catch(y){f(i,"WARN","Error occurred when getting file stats, skipping",{filePath:m.replace(/\\/g,"/"),error:y.message});continue}l.isSymbolicLink()||l.nlink>1||(l.isDirectory()?s+=await Ie(e,r,t,i,m):l.isFile()&&(s+=l.size))}return s}async function Ge(e,r,t,i,o,a,s,d,m,w=null){const g=Date.now(),n=`computer:${e}:${r}`,l=!(a===!1||a==="false");if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const y=d==null?"":String(d).trim().toLowerCase();let u=null;if(y&&y!=="all")if(y==="file")u="file";else if(y==="dir"||y==="directory")u="dir";else throw new E("type \u4EC5\u652F\u6301 file/dir/all",{field:"type",value:d});const p=D=>/^\d+$/.test(String(D))?parseInt(String(D),10):NaN;let S=null;if(m!=null&&m!==""){const D=p(m);if(!Number.isInteger(D)||D<0)throw new E("limit \u5FC5\u987B\u4E3A\u975E\u8D1F\u6574\u6570",{field:"limit",value:m});S=D}let F=null;if(!l&&s!=null&&s!==""){const D=p(s);if(!Number.isInteger(D)||D<1||D>10)throw new E("depth \u9700\u4E3A 1-10 \u7684\u6574\u6570",{field:"depth",value:s});F=D}const R=String(e),b=String(r),v=i&&i.trim()?i.trim():null,I=v||O(w,R,b);if(!c.existsSync(I))return f(n,"INFO","Directory does not exist, returning empty list",{targetDir:I,userId:R,cId:b}),{files:[],recursive:l,depth:F,type:u||"all",limit:S};const k=Se(I,o);if(await X(I,k))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:o});if(!c.existsSync(k))return f(n,"INFO","List path does not exist, returning empty list",{targetDir:I,listDir:k,relativePath:o||"",userId:R,cId:b}),{files:[],recursive:l,depth:F,type:u||"all",limit:S};if(!(await c.promises.stat(k)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:o});f(n,"DEBUG","Start getting user file list",{targetDir:I,listDir:k,relativePath:o||"",recursive:l,userId:R,cId:b});try{const D={typeFilter:u,limitState:{limit:S,pushed:0},levelsLeft:!l&&F!=null?F:1},ee=l?(await we(k,n,t,v,de(I,k),{...D,rootDir:I})).entries:await he(k,I,n,t,v,D);return f(n,"INFO","User file list obtained successfully",{fileCount:ee.length,targetDir:I,listDir:k,relativePath:o||"",recursive:l,depth:F,type:u||"all",limit:S,userId:R,cId:b,elapsedMs:Date.now()-g}),{files:ee,recursive:l,depth:F,type:u||"all",limit:S}}catch(D){throw D instanceof E?D:(f(n,"ERROR","Failed to get user file list",{targetDir:I,listDir:k,relativePath:o||"",recursive:l,userId:R,cId:b,error:D.message,elapsedMs:Date.now()-g}),new z(`Failed to get file list: ${D.message}`,{targetDir:I,originalError:D.message}))}}const He=5e3;function le(e,r){const t=Number.parseInt(e,10);if(!Number.isFinite(t)||t<=0)throw new E(`${r} \u5FC5\u987B\u4E3A\u6B63\u6574\u6570`,{field:r,value:e});return t}function Fe(e,r,t){return t?r.toLowerCase().includes(t)?!0:e.toLowerCase().includes(t):!1}const qe=new Set([".git",".svn",".hg","node_modules","__pycache__",".venv","venv","virtualenv",".mypy_cache",".pytest_cache",".ruff_cache",".cache",".tmp"]),Ze=new Set([".DS_Store","Thumbs.db","desktop.ini"]);function De(e,r,t){return!!(Ze.has(e.name)||r.includes(e.name)||e.isDirectory()&&(qe.has(e.name)||t.includes(e.name)))}function ve(e,r,t,i){for(let o=r;o<e.length;o++)if(!De(e[o],t,i))return!0;return!1}function be(e,r){return Date.now()-e>=r}async function Ke(e,r,t,i,o,a,s,d,m,w,g=null){const n=Date.now(),l=`computer:${e}:${r}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const y=(i==null?"":String(i)).trim();if(!y)throw new E("kw \u4E0D\u80FD\u4E3A\u7A7A",{field:"kw"});const u=le(d,"limit"),p=le(m,"maxVisit"),S=le(w,"timeoutMs"),F=y.toLowerCase(),R=(()=>{const N=s==null?"":String(s).trim().toLowerCase();return N==="file"?"file":N==="dir"||N==="directory"?"dir":null})(),b=N=>R==null||R==="dir"===N,v=String(e),I=String(r),k=o&&o.trim()?o.trim():null,C=k||O(g,v,I);if(!c.existsSync(C))return{files:[],truncated:!1,visited:0};const D=Se(C,a);if(!c.existsSync(D))return{files:[],truncated:!1,visited:0};if(await X(C,D))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:a});if(!(await c.promises.stat(D)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:a});const Ne=q(h.relative(C,D)),te=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],re=P.TRAVERSE_EXCLUDE_DIRS||[],_=[],ie=new Set;let $=0,ne=!1,A=!1;const T=[Ne],U=()=>$>=p||be(n,S);for(;T.length>0;){if(U()){A=!0;break}if(_.length>=u){T.length>0&&(A=!0);break}const N=T.shift();if(ie.has(N))continue;ie.add(N);const j=N?h.join(C,N):C;let M;try{M=await c.promises.readdir(j,{withFileTypes:!0})}catch(x){f(l,"WARN","search readdir failed",{dirRel:N,error:x.message});continue}M.sort((x,L)=>x.isDirectory()&&!L.isDirectory()?-1:!x.isDirectory()&&L.isDirectory()?1:x.name.toLowerCase().localeCompare(L.name.toLowerCase()));const se=[];let V=!1,G=!1;for(let x=0;x<M.length;x++){const L=M[x];if(De(L,te,re))continue;if(U()){A=!0,V=!0,G=!0;break}$+=1;const ue=h.join(j,L.name),W=q(h.relative(C,ue));if(L.isDirectory()){if(se.push(W),b(!0)&&_.length<u&&Fe(W,L.name,F)&&(_.push({name:W,isDir:!0}),_.length>=u)){V=!0,G=ve(M,x+1,te,re);break}continue}try{if(b(!1)&&_.length<u&&Fe(W,L.name,F)&&(_.push({name:W,isDir:!1,fileProxyUrl:Q(t,W,k),isLink:L.isSymbolicLink()}),_.length>=u)){V=!0,G=ve(M,x+1,te,re);break}}catch(xe){f(l,"WARN",`search \u5904\u7406\u6587\u4EF6\u5931\u8D25: ${ue}`,{error:xe.message})}}if(V||U()){(U()||G||se.length>0||T.length>0)&&(A=!0);continue}for(const x of se){if(U()){A=!0;break}if(T.length>=He){A=!0;break}if($+T.length>=p){A=!0;break}ie.has(x)||T.push(x)}}return _.sort((N,j)=>N.isDir!==j.isDir?N.isDir?-1:1:String(N.name).localeCompare(String(j.name))),ne=A||T.length>0||$>=p||be(n,S),f(l,"INFO","File search completed",{kw:y,matchCount:_.length,visited:$,truncated:ne,relativePath:a||"",elapsedMs:Date.now()-n}),{files:_,truncated:ne,visited:$}}async function Ye(e,r,t,i,o=null){const a=Date.now(),s=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});const d=String(e),m=String(r),w=i&&i.trim()?i.trim():null,g=w||O(o,d,m);c.existsSync(g)||c.mkdirSync(g,{recursive:!0});for(let n=0;n<t.length;n++){const l=t[n];if(!l||typeof l.operation!="string")throw new E(`files[${n}].operation cannot be empty`,{field:`files[${n}].operation`});if(!l.name||typeof l.name!="string")throw new E(`files[${n}].name cannot be empty`,{field:`files[${n}].name`});const y=l.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(y))throw new E(`files[${n}].operation must be one of create, delete, rename or modify`,{field:`files[${n}].operation`});if(y==="rename"&&!l.renameFrom)throw new E(`files[${n}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${n}].renameFrom`});if(y==="modify"&&l.isDir!==!0&&typeof l.contents!="string")throw new E(`files[${n}].contents must be a string (modify operation requires)`,{field:`files[${n}].contents`})}f(s,"DEBUG","Start updating user files",{userId:d,cId:m,filesCount:t.length});try{for(const n of t){const l=n.operation.toLowerCase(),y=n.name,u=h.normalize(y).replace(/^[\/\\]+/,""),p=h.join(g,u),S=h.resolve(p),F=h.resolve(g);if(!S.startsWith(F+h.sep)&&S!==F){f(s,"WARN","File path is not secure, skipping",{filePath:u,resolvedPath:S});continue}switch(l){case"create":{if(n.isDir===!0){if(c.existsSync(p)){if((await c.promises.stat(p)).isFile())throw new E("Cannot create directory, file with the same name already exists",{filePath:u});f(s,"INFO","Directory already exists, skipping creation",{filePath:u});break}await c.promises.mkdir(p,{recursive:!0}),f(s,"INFO","Directory created successfully",{filePath:u});break}if(c.existsSync(p)){if((await c.promises.stat(p)).isDirectory())throw new E("Cannot create file, directory with the same name already exists",{filePath:u});f(s,"INFO","File already exists, skipping creation",{filePath:u});break}await c.promises.mkdir(h.dirname(p),{recursive:!0});const R=n.contents||"";await c.promises.writeFile(p,R,"utf8"),f(s,"INFO","File created successfully",{filePath:u});break}case"delete":{c.existsSync(p)?(await c.promises.stat(p)).isDirectory()?(await c.promises.rm(p,{recursive:!0,force:!0}),f(s,"INFO","Directory deleted successfully",{filePath:u})):(await c.promises.unlink(p),f(s,"INFO","File deleted successfully",{filePath:u})):f(s,"WARN","The file or directory to be deleted does not exist",{filePath:u});break}case"rename":{const R=n.renameFrom;if(!R||typeof R!="string"){f(s,"WARN","Rename operation missing renameFrom",{filePath:u});break}const b=h.normalize(R).replace(/^[\/\\]+/,""),v=h.join(g,b),I=h.resolve(v);if(!I.startsWith(F+h.sep)&&I!==F){f(s,"WARN","Source path is not secure, skipping rename",{sourcePath:b,targetPath:u});break}if(c.existsSync(v)){const C=(await c.promises.stat(v)).isDirectory();await c.promises.mkdir(h.dirname(p),{recursive:!0}),await c.promises.rename(v,p),f(s,"INFO",C?"Directory renamed successfully":"File renamed successfully",{sourcePath:b,targetPath:u})}else f(s,"WARN","The file or directory to be renamed does not exist",{sourcePath:b});break}case"modify":{if(!c.existsSync(p)){f(s,"WARN","The file to be modified does not exist",{filePath:u});break}if((await c.promises.stat(p)).isDirectory()){f(s,"INFO","The target is a directory, skipping modification",{filePath:u});break}const b=typeof n.contents=="string"?n.contents:"";if(await c.promises.readFile(p,"utf8")===b){f(s,"INFO","File content has no changes, skipping write",{filePath:u});break}await c.promises.writeFile(p,b,"utf8"),f(s,"INFO","File modified successfully",{filePath:u});break}default:{f(s,"WARN","Unsupported operation type",{operation:l,filePath:u});break}}}return f(s,"INFO","User files updated successfully",{userId:d,cId:m,filesCount:t.length,elapsedMs:Date.now()-a}),{success:!0,message:"User files updated successfully",userId:d,cId:m,filesCount:t.length}}catch(n){throw f(s,"ERROR","User files updated failed",{userId:d,cId:m,error:n.message,elapsedMs:Date.now()-a}),new z(`User files updated failed: ${n.message}`,{userId:d,cId:m,originalError:n.message})}}async function ce(e,r,t,i,o,a=null){const s=Date.now(),d=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!t)throw new E("file cannot be empty",{field:"file"});if(!i||typeof i!="string")throw new E("filePath cannot be empty",{field:"filePath"});const m=String(e),w=String(r),g=o&&o.trim()?o.trim():null,n=g||O(a,m,w);c.existsSync(n)||c.mkdirSync(n,{recursive:!0});const l=h.normalize(i).replace(/^[\/\\]+/,""),y=h.join(n,l),u=h.resolve(y),p=h.resolve(n);if(!u.startsWith(p+h.sep)&&u!==p)throw new E("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:i,resolvedPath:u});try{if(await c.promises.mkdir(h.dirname(y),{recursive:!0}),t.buffer)await c.promises.writeFile(y,t.buffer);else if(typeof t.contents=="string")await c.promises.writeFile(y,t.contents,"utf8");else throw new E("File content format is incorrect",{field:"file",hasBuffer:!!t.buffer,hasContents:typeof t.contents});return f(d,"INFO","File uploaded successfully",{userId:m,cId:w,filePath:l,targetPath:u,fileSize:t.buffer?t.buffer.length:t.contents?Buffer.byteLength(t.contents,"utf8"):0,elapsedMs:Date.now()-s}),{success:!0,message:"File uploaded successfully",fileSize:t.buffer?t.buffer.length:t.contents?Buffer.byteLength(t.contents,"utf8"):0}}catch(S){throw f(d,"ERROR","File upload failed",{userId:m,cId:w,filePath:l,error:S.message,elapsedMs:Date.now()-s}),new z(`File upload failed: ${S.message}`,{userId:m,cId:w,filePath:l,originalError:S.message})}}async function Je(e,r,t,i,o,a=null){const s=Date.now(),d=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});if(!Array.isArray(i))throw new E("filePaths must be an array",{field:"filePaths"});if(t.length!==i.length)throw new E(`File count (${t.length}) does not match path count (${i.length})`,{field:"filePaths"});f(d,"DEBUG","Start batch uploading files",{userId:e,cId:r,filesCount:t.length});const m=[];try{for(let n=0;n<t.length;n++){const l=t[n],y=i[n];if(!l){f(d,"WARN","Empty file object encountered in batch upload, skipping",{index:n,filePath:y}),m.push({success:!1,filePath:y,error:"Empty file object"});continue}if(!y||typeof y!="string"){f(d,"WARN","Invalid file path in batch upload, skipping",{index:n,originalname:l.originalname}),m.push({success:!1,filePath:y||"",originalname:l.originalname,error:"Invalid file path"});continue}try{const u=await ce(e,r,l,y,o,a);m.push({success:!0,filePath:y,originalname:l.originalname,...u})}catch(u){f(d,"ERROR","Single file upload failed in batch upload",{filePath:y,originalname:l.originalname,error:u.message}),m.push({success:!1,filePath:y,originalname:l.originalname,error:u.message})}}const w=m.filter(n=>n.success).length,g=m.filter(n=>!n.success).length;return f(d,"INFO","Batch upload files completed",{userId:e,cId:r,totalCount:t.length,successCount:w,failCount:g,elapsedMs:Date.now()-s}),{success:!0,message:"Batch upload completed",totalCount:t.length,successCount:w,failCount:g,results:m}}catch(w){throw f(d,"ERROR","Batch upload files failed",{userId:e,cId:r,error:w.message,elapsedMs:Date.now()-s}),new z(`Batch upload files failed: ${w.message}`,{userId:e,cId:r,originalError:w.message})}}async function Qe(e,r,t,i=null){const o=Date.now(),a=`computer:${e}:${r}`,s=me(i);if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!s&&!i?.workspacePath)throw new z("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const d=String(e),m=String(r),w=t&&t.trim()?t.trim():null,g=w||O(i,d,m);if(!c.existsSync(g)){const S=`${d}_${m}.zip`;f(a,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:g,userId:d,cId:m,zipFileName:S});const F=fe("zip",{zlib:{level:9}});return F.append(null,{name:`${d}_${m}/`,type:"directory"}),F.on("warning",R=>{if(R.code==="ENOENT")f(a,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw f(a,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),F.on("error",R=>{f(a,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:F,zipFileName:S}}const n=`${d}_${m}.zip`;f(a,"DEBUG","Start creating workspace directory zip",{targetDir:g,zipFileName:n});const l=fe("zip",{zlib:{level:9}}),y=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],u=P.TRAVERSE_EXCLUDE_DIRS||[],p=await Ie(g,y,u,a);if(p>H){const S=H/1024/1024,F=(p/1024/1024).toFixed(2);throw f(a,"WARN","Download rejected due to oversized workspace",{targetDir:g,downloadableSize:p,maxSizeBytes:H}),new E(`Download failed: total file size ${F}MB exceeds limit ${S}MB`,{field:"downloadSize",downloadableSize:p,maxSizeBytes:H})}return l.directory(g,`${d}_${m}`,S=>{const F=S.name||"",R=F.split(/[\/\\]/).filter(Boolean);if(R.some(v=>v.startsWith(".")))return!1;const b=R[R.length-1];if(y.includes(b)||R.some(v=>u.includes(v)))return!1;try{const v=h.join(g,F),I=c.lstatSync(v);if(I.isSymbolicLink()||I.nlink>1)return!1}catch(v){return f(a,"WARN","Error occurred when detecting link file, skipping",{filePath:F,error:v.message}),!1}return S}),l.on("warning",S=>{if(S.code==="ENOENT")f(a,"WARN","Encountered file problem when creating zip",{message:S.message,code:S.code});else throw f(a,"ERROR","Encountered warning when creating zip",{message:S.message,code:S.code}),S}),l.on("error",S=>{f(a,"ERROR","Failed to create zip",{message:S.message,elapsedMs:Date.now()-o})}),l.on("end",()=>{f(a,"INFO","Workspace directory zip created successfully",{targetDir:g,zipFileName:n,elapsedMs:Date.now()-o})}),{archive:l,zipFileName:n}}async function et(e,r,t=200,i=null){const o=Date.now(),a=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});const s=String(e),d=String(r),m=Ae(i,s,d);if(!m)return f(a,"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(m))return f(a,"DEBUG","Log directory does not exist",{logDir:m}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const g=(await c.promises.readdir(m,{withFileTypes:!0})).filter(I=>I.isFile()).map(I=>I.name);if(g.length===0)return f(a,"DEBUG","No log file found",{logDir:m}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const n=[];for(const I of g){const k=h.join(m,I),C=await c.promises.stat(k);n.push({name:I,fullPath:k,mtime:C.mtimeMs,size:C.size})}n.sort((I,k)=>k.mtime-I.mtime);const l=n[0],u=(await c.promises.readFile(l.fullPath,"utf8")).split(`
|
|
2
2
|
`).filter(I=>I.length>0),p=u.length,S=Math.max(1,t),F=Math.max(0,p-S),R=F+1,v=u.slice(F).map((I,k)=>({line:R+k,content:I}));return f(a,"DEBUG","Get latest logs",{fileName:l.name,fileSize:l.size,totalLines:p,returnedLines:v.length,elapsedMs:Date.now()-o}),{success:!0,message:"Get log successfully",logs:v,totalLines:p,startIndex:R,logFileName:l.name}}async function ke(e,r){try{const i=(await c.promises.readdir(e,{withFileTypes:!0})).filter(d=>!d.name.startsWith(".")&&d.name!=="node_modules");if(i.length!==1||!i[0].isDirectory())return;const o=h.join(e,i[0].name),a=h.join(e,`..tmp_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{await c.promises.rename(o,a)}catch(d){if(d.code==="EXDEV")await c.promises.cp(o,a,{recursive:!0}),await c.promises.rm(o,{recursive:!0,force:!0});else throw d}const s=await c.promises.readdir(a);for(const d of s){const m=h.join(a,d),w=h.join(e,d);try{await c.promises.rename(m,w)}catch(g){if(g.code==="EXDEV")(await c.promises.lstat(m)).isDirectory()?await Le(m,w):(await c.promises.copyFile(m,w),await c.promises.unlink(m));else throw g}}await c.promises.rm(a,{recursive:!0,force:!0}),f(r,"INFO","Removed single top-level directory from imported zip",{removedDir:i[0].name})}catch(t){f(r,"WARN","Failed to remove top-level directory from imported zip, continuing",{error:t.message})}}async function tt(e,r){if(!c.existsSync(e)){await c.promises.mkdir(e,{recursive:!0});return}const t=await c.promises.readdir(e,{withFileTypes:!0});for(const i of t){if(B.has(i.name))continue;const o=h.join(e,i.name);await c.promises.rm(o,{recursive:!0,force:!0}),f(r,"DEBUG","Removed workspace entry during import",{name:i.name})}}async function rt(e,r,t){if(await c.promises.mkdir(r,{recursive:!0}),!c.existsSync(e)){await c.promises.mkdir(e,{recursive:!0});return}const i=await c.promises.readdir(e,{withFileTypes:!0});for(const o of i){if(B.has(o.name))continue;const a=h.join(e,o.name),s=h.join(r,o.name);await oe(a,s),f(t,"DEBUG","Backed up workspace entry before import",{name:o.name})}}async function it(e,r,t){if(!c.existsSync(e))return;const i=await c.promises.readdir(e,{withFileTypes:!0});for(const o of i){if(B.has(o.name))continue;const a=h.join(e,o.name),s=h.join(r,o.name);await oe(a,s)}f(t,"INFO","Workspace restored from backup after import failure")}async function nt(e,r,t){const i=await c.promises.readdir(e,{withFileTypes:!0}),o=[];try{for(const a of i){if(B.has(a.name)){f(t,"INFO","Skipping preserved entry from imported zip",{name:a.name});continue}const s=h.join(e,a.name),d=h.join(r,a.name);await oe(s,d),o.push(a.name)}}catch(a){throw a.mergedEntries=o,a}}async function st(e,r,t,i,o=null){const a=Date.now(),s=`computer:${e}:${r}`,d=me(o);if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!t||!t.path)throw new E("file is required",{field:"file"});if(!d&&!o?.workspacePath)throw new z("COMPUTER_WORKSPACE_DIR is not configured");if(h.extname(t.originalname||t.filename||"").toLowerCase()!==".zip")throw new E("Only zip files are supported",{field:"file",originalName:t.originalname});const w=String(e),g=String(r),n=i&&i.trim()?i.trim():O(o,w,g),l=h.join(n,".tmp"),y=h.join(l,`import_project_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);let u=null;f(s,"INFO","Start importing project from zip",{userId:w,cId:g,targetDir:n,fileName:t.originalname});try{await c.promises.mkdir(n,{recursive:!0}),await c.promises.mkdir(l,{recursive:!0}),await c.promises.mkdir(y,{recursive:!0}),await _e(t.path,y),await ke(y,s),u=h.join(l,`import_backup_${Date.now()}_${Math.round(Math.random()*1e6)}`),await rt(n,u,s);try{await nt(y,n,s)}catch(p){throw f(s,"ERROR","Merge imported project failed, restoring workspace",{error:p.message,mergedEntries:p.mergedEntries||[]}),await tt(n,s),await it(u,n,s),p}return c.existsSync(u)&&(await c.promises.rm(u,{recursive:!0,force:!0}),u=null),f(s,"INFO","Project imported successfully",{userId:w,cId:g,targetDir:n,elapsedMs:Date.now()-a}),{success:!0,message:"Project imported successfully",userId:w,cId:g,targetDir:n}}catch(p){throw f(s,"ERROR","Failed to import project",{userId:w,cId:g,targetDir:n,error:p.message,elapsedMs:Date.now()-a}),p instanceof E||p instanceof z||p instanceof Pe?p:new z(`Failed to import project: ${p.message}`,{userId:w,cId:g,originalError:p.message})}finally{if(c.existsSync(y))try{await c.promises.rm(y,{recursive:!0,force:!0})}catch(p){f(s,"WARN","Failed to clean import extract directory",{extractRoot:y,error:p.message})}if(u&&c.existsSync(u))try{await c.promises.rm(u,{recursive:!0,force:!0})}catch(p){f(s,"WARN","Failed to clean import backup directory",{backupDir:u,error:p.message})}if(t?.path&&c.existsSync(t.path))try{await c.promises.unlink(t.path)}catch(p){f(s,"WARN","Failed to clean uploaded zip file",{tempZipPath:t.path,error:p.message})}}}async function ot(e,r,t,i,o,a=null){const s=`computer:${e}:${r}`;if(!t||typeof t!="string"||!t.trim())throw new E("fileName cannot be empty",{field:"fileName"});if(i!=null&&typeof i!="string")throw new E("content must be a string",{field:"content"});const d=t.trim(),m=i??"";return f(s,"INFO","Generate file from text content",{userId:e,cId:r,fileName:d,contentLength:m.length}),{...await ce(e,r,{contents:m,originalname:h.basename(d),size:Buffer.byteLength(m,"utf8")},d,o,a),message:"File generated successfully",fileName:d}}export{X as escapesRoot,Ge as getFileList,Ve as getFileMeta,ze as resolveExistingFile,Ke as searchFiles,Ye as updateFiles,ce as uploadFile,Je as uploadFiles,ot as generateFile,Qe as downloadAllFiles,et as getLatestLogs,st as importProject,B as IMPORT_PROJECT_PRESERVED_ENTRIES,ke as removeTopLevelDir};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import n from"fs";import l from"path";import{exec as ve}from"child_process";import Me from"cross-spawn";import We from"archiver";import te from"../../appConfig/index.js";import{extractZip as Y}from"../common/zipUtils.js";import{ValidationError as f,SystemError as K,FileError as ie}from"../error/errorHandler.js";import{log as r}from"../log/logUtils.js";import{createPnpmNpmrc as Te}from"../common/npmrcUtils.js";import{ensurePrimaryAgentDirs as ge,syncAgents as fe,linkWorkspaceToAgentStore as Se,forceDirSymlink as Ce,copyDirContents as Le,isWorkspaceSkillsSymlinked as Be}from"../common/AgentWorkspaceUtils.js";import{getProjectStoreRoot as Ue,getAgentStorePath as De,readManifest as Ze,writeManifest as Ge,reverseRefs as Ke,ensureAgentStoreDirs as xe,tryAcquireAgentStoreLock as we,releaseAgentStoreLock as Ne,pruneAgentSkills as qe,installSkillDir as se,replaceAgentsDir as Ve,agentSkillExists as Je}from"../common/agentStoreUtils.js";import{writeAgentHookConfigs as Re}from"./hookConfigUtils.js";import{ensureWorkspaceDir as H,resolveWorkspaceDir as He,resolveWorkspaceRoot as oe}from"./workspaceContext.js";function le(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 le(i)}catch{}return[t]}return[]}async function je(e,t,i){try{return await Ce(e,t,i),!0}catch(a){return r(i,"WARN","Skill view dir link unavailable, fallback to copy",{linkPath:e,targetDir:t,platform:process.platform,error:a.message}),!1}}async function Ye(e,t,i){const a=process.platform==="win32"?l.resolve(t):l.relative(l.dirname(e),t).split(l.sep).join("/");try{return await n.promises.symlink(a,e,"file"),!0}catch(s){return r(i,"WARN","Skill view file link unavailable, fallback to copy",{linkPath:e,targetFile:t,platform:process.platform,error:s.message}),!1}}async function Ee(e,t,i,a,s,o={}){const p=Ue(e,a);if(!p||!i)return!1;const{skillNames:u=null,subagentNames:c=null}=o,N=l.join(p,".view.lock");await n.promises.mkdir(p,{recursive:!0});const _=Date.now()+3e4;let w=!1;for(;Date.now()<_&&!w;)try{await n.promises.writeFile(N,String(Date.now()),{flag:"wx"}),w=!0}catch(y){if(y.code!=="EEXIST")throw y;try{const D=await n.promises.stat(N);if(Date.now()-D.mtimeMs>5*60*1e3){await n.promises.rm(N,{force:!0});continue}}catch{}await new Promise(D=>setTimeout(D,200))}if(!w)throw new K("Agent skill view is busy, please retry");try{const y=await Ze(p),D=y.agents[String(i)]||{skills:[],subagents:[]};u&&(D.skills=[...new Set(u.map(g=>String(g||"").trim()).filter(Boolean))]),c&&(D.subagents=[...new Set(c.map(g=>String(g||"").trim()).filter(Boolean))]),y.agents[String(i)]=D,await Ge(p,y);const h=[".agents",".claude",".opencode",".codex"],d=[];for(const g of h)for(const $ of["skills","agents"]){const k=l.join(t,g,$);if(await n.promises.mkdir(l.dirname(k),{recursive:!0}),g===".agents")try{(await n.promises.lstat(k)).isSymbolicLink()&&await n.promises.rm(k,{recursive:!0,force:!0})}catch{}else{const b=l.join(t,".agents",$),T=process.platform==="win32"?l.resolve(b):"../.agents/"+$;let S=!1;try{S=(await n.promises.lstat(k)).isSymbolicLink()&&n.readlinkSync(k)===T}catch{}S||(await n.promises.rm(k,{recursive:!0,force:!0}),await je(k,b,s)||d.push([b,k]));continue}await n.promises.mkdir(k,{recursive:!0})}const B=async(g,$,k)=>{k==="skills"||(await n.promises.lstat(g)).isDirectory()?(d.length>0||!await je($,g,s))&&await Le(g,$):await Ye($,g,s)||await n.promises.copyFile(g,$)},A=l.join(t,".agents");for(const g of["skills","agents"]){const k=Ke(y,g==="skills"?"skills":"subagents"),b=l.join(A,g),T=n.existsSync(b)?await n.promises.readdir(b):[],S=new Set(Object.keys(k));for(const R of T){const x=l.join(b,R);pe(x)||S.has(R)||(await n.promises.rm(x,{recursive:!0,force:!0}),r(s,"INFO","Skill view entry removed (no agent references it)",{kind:g,name:R}))}for(const[R,x]of Object.entries(k)){const P=l.join(b,R);if(pe(P))continue;const v=[...new Set([String(i),...x.map(String)])];let W=null;for(const E of v){const C=l.join(De(e,E,a),g,R);if(n.existsSync(C)){W=C;break}}if(!W){await n.promises.rm(P,{recursive:!0,force:!0});continue}const m=process.platform==="win32"?l.resolve(W):l.relative(b,W).split(l.sep).join("/");let j=!1;try{j=!(await n.promises.lstat(P)).isSymbolicLink()||n.readlinkSync(P)!==m}catch{j=!0}j&&(await n.promises.rm(P,{recursive:!0,force:!0}),await B(W,P,g))}if(g==="skills"){const R=[...new Set([String(i),...Object.keys(y.agents||{})])];for(const x of R){const P=l.join(De(e,x,a),"skills");let v=[];try{v=await n.promises.readdir(P,{withFileTypes:!0})}catch{continue}for(const W of v){if(!W.isDirectory())continue;const m=l.join(P,W.name);if(!pe(m))continue;const j=l.join(b,W.name);n.existsSync(j)||(await B(m,j,g),r(s,"INFO","Dynamic skill linked into view",{owner:x,name:W.name}))}}}}for(const[g,$]of d)await n.promises.rm($,{recursive:!0,force:!0}),await n.promises.cp(g,$,{recursive:!0,dereference:!0,force:!0});return r(s,"INFO","Shared skill view synced",{userWorkspaceRoot:t,projectStoreRoot:p,agentId:i,skills:D.skills,subagents:D.subagents,copyFallbackDirs:d.length}),!0}finally{await n.promises.rm(N,{force:!0})}}function _e(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 _e(JSON.parse(t))}catch{return[{name:null,url:t}]}}return[]}function Xe(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 o=String(a||"").trim(),p=typeof s=="string"?s.trim():"";o&&p&&(i[o]=p)}return i}function Pe(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 ce(e,t,i){let a;try{a=await fetch(e)}catch(u){throw new ie(`Failed to download skill zip from url: ${e}`,{url:e,reason:u.message})}if(!a.ok)throw new ie(`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 o=await a.arrayBuffer(),p=Buffer.from(o);await n.promises.writeFile(t,p)}async function ne(e,t){const i=l.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 o=l.join(e,s.name),p=l.join(o,t);if(n.existsSync(p)&&(await n.promises.lstat(p)).isDirectory())return p}return null}async function At(e){return ne(e,"skills")}const Qe=".dynamic_add.lock";function pe(e){const t=l.join(e,Qe);return n.existsSync(t)&&n.statSync(t).isFile()}async function X(e){n.existsSync(e)&&await n.promises.rm(e,{recursive:!0,force:!0})}async function Q(e,t){try{await n.promises.rename(e,t)}catch(i){if(i.code==="EXDEV"){async function a(s,o){if((await n.promises.lstat(s)).isDirectory()){await n.promises.mkdir(o,{recursive:!0});const u=await n.promises.readdir(s);for(const c of u)await a(l.join(s,c),l.join(o,c))}else await n.promises.copyFile(s,o)}await a(e,t),await n.promises.rm(e,{recursive:!0,force:!0})}else throw i}}async function he(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(l.join(e,"skills"),{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).map(o=>({name:o.name,sourcePath:l.join(e,"skills",o.name)})):i.map(s=>({name:s.name,sourcePath:l.join(e,s.name)}))}const ae=8;async function re(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 o=s++;if(o>=e.length)return;await i(e[o],o)}}))}async function Ie(e){const{userId:t,cId:i,agentId:a,file:s,skillUrls:o,skillUrlMap:p,skillNames:u,updateSkillNames:c,mcpServersConfig:N,permissionsConfig:_,hooksConfig:w,hookScripts:y,service:D}=e,h=Date.now(),d=`computer:${t}:${i}`,B=Xe(p),A=_e(o),g=Pe(u),$=c!=null,k=new Set(Pe(c)),b=[],T=[],S=new Set,R=new Set,x=[];let P=null,v=!1;if(!t)throw new f("userId cannot be empty",{field:"userId"});if(!i)throw new f("cId cannot be empty",{field:"cId"});if(!a)throw new f("agentId cannot be empty",{field:"agentId"});const W=oe(D),m=await H(D,t,i,d),j=l.join(m,".tmp");await n.promises.mkdir(m,{recursive:!0}),await n.promises.mkdir(j,{recursive:!0});const{agentStorePath:E,skillsDir:C,agentsDir:I}=await xe(t,a,d,D),L=O=>!O||!$||k.has(O)?!0:!Je(C,O),Z=async(O,F,G)=>{const V=l.join(j,`skill_url_${Date.now()}_${G}_${Math.round(Math.random()*1e6)}.zip`);b.push(V);const q=l.join(j,`skill_url_extract_${Date.now()}_${G}_${Math.round(Math.random()*1e6)}`);T.push(q),await n.promises.mkdir(q,{recursive:!0});try{r(d,"INFO","Start download skill zip from url",{userId:t,cId:i,agentId:a,skillName:F,skillUrl:O}),await ce(O,V,d),await Y(V,q)}catch(U){r(d,"ERROR","Download/extract skill zip failed, skip this skill",{userId:t,cId:i,agentId:a,skillName:F,skillUrl:O,error:U.message}),x.push({name:F||null,url:O,reason:`Download/extract skill zip failed: ${U.message}`});return}try{const U=await he(q);if(U.length===0){r(d,"WARN","No skill dir found in downloaded zip",{skillUrl:O,destName:F}),x.push({name:F||null,url:O,reason:"No skill directory found in downloaded zip"});return}let M=F?U.find(z=>z.name===F):null;if(!M&&U.length===1&&(M=U[0]),F&&M){if(!L(F)){R.add(F);return}await se(M.sourcePath,C,F,{asDynamic:!1}),S.add(F),r(d,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:O,skillName:F,zipDirName:M.name});return}for(const z of U){if(!L(z.name)){R.add(z.name);continue}await se(z.sourcePath,C,z.name,{asDynamic:!1}),S.add(z.name),r(d,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:O,skillName:z.name})}}catch(U){r(d,"ERROR","Install skill from url failed, skip this skill",{userId:t,cId:i,agentId:a,skillName:F,skillUrl:O,error:U.message}),x.push({name:F||null,url:O,reason:`Install skill failed: ${U.message}`})}};await Re(m,{mcpServersConfig:N,hooksConfig:w,permissionsConfig:_,hookScripts:y},d);try{const O=await we(E,d);if(!O.acquired)v=!0;else{P=O.lockPath;const V=Date.now();let q=null;if(s){if(!s.path)throw new f("Uploaded file has no valid path",{field:"file.path"});if(l.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:s.originalname});const z=l.join(j,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);T.push(z),await n.promises.mkdir(z,{recursive:!0}),await Y(s.path,z);const J=await ne(z,"skills");if(J){const me=(await n.promises.readdir(J,{withFileTypes:!0})).filter(ee=>ee.isDirectory());await re(me,ae,async ee=>{if(!L(ee.name)){R.add(ee.name);return}await se(l.join(J,ee.name),C,ee.name,{asDynamic:!1}),S.add(ee.name)})}q=await ne(z,"agents")}const U=Object.entries(B);if(U.length>0){const M=[];for(const[z,J]of U){if(!L(z)){R.add(z),r(d,"INFO","Skip download skill zip (already in agent store)",{userId:t,cId:i,agentId:a,skillName:z,skillUrl:J});continue}M.push({skillName:z,skillUrl:J})}await re(M,ae,async(z,J)=>{await Z(z.skillUrl,z.skillName,J)})}else{const M=[];for(let z=0;z<A.length;z++){const{name:J,url:me}=A[z];if(J&&!L(J)){R.add(J);continue}M.push({skillUrl:me,hintedName:J,index:z})}await re(M,ae,async z=>{await Z(z.skillUrl,z.hintedName,z.index)})}await Ve(q,I),await qe(C,g,d),r(d,"INFO","Agent store resources prepared",{userId:t,cId:i,agentId:a,selectiveInstall:$,updatedSkills:Array.from(S),skippedSkills:Array.from(R),updateSkillNames:Array.from(k),keepSkillNames:g,skillUrlMapCount:U.length,prepareElapsedMs:Date.now()-V})}let F=null,G=!1;if(D&&(D.isUserApp||D.isNormalProject)&&D.appId){let V=null;try{V=(await n.promises.readdir(I,{withFileTypes:!0})).map(q=>q.name)}catch{}G=await Ee(t,m,a,D,d,{skillNames:u?g:null,subagentNames:V})}return G||(F=await Se(m,C,I,d)),r(d,"INFO","Workspace created successfully (agent store)",{userId:t,cId:i,agentId:a,agentStorePath:E,updatedSkills:Array.from(S),skippedSkills:Array.from(R),failedSkills:x,skippedStoreUpdate:v,linkElapsedMs:F?.elapsedMs,elapsedMs:Date.now()-h}),{message:v?"Workspace linked to agent store (store update skipped, lock held)":"Workspace created successfully, linked to agent store",workspaceRoot:W,agentStorePath:E,updatedSkills:Array.from(S),skippedSkills:Array.from(R),failedSkills:x,skippedStoreUpdate:v}}catch(O){throw r(d,"ERROR","Failed to create workspace with agent store",{userId:t,cId:i,agentId:a,error:O.message,elapsedMs:Date.now()-h}),O instanceof f||O instanceof ie||O instanceof K?O:new K(`Failed to create workspace: ${O.message}`,{userId:t,cId:i,agentId:a})}finally{await Ne(P,d);const O=Date.now();for(const F of T)try{n.existsSync(F)&&await n.promises.rm(F,{recursive:!0,force:!0})}catch(G){r(d,"WARN","Failed to clean up temporary extracted zip",{error:G.message})}for(const F of b)try{n.existsSync(F)&&await n.promises.unlink(F)}catch(G){r(d,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:F,error:G.message})}try{s&&s.path&&n.existsSync(s.path)&&await n.promises.unlink(s.path)}catch(F){r(d,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:F.message})}r(d,"INFO","Workspace temp cleanup completed",{userId:t,cId:i,agentId:a,elapsedMs:Date.now()-O,totalElapsedMs:Date.now()-h})}}async function et(e,t,i,a,s,o,p,u,c,N,_,w,y=null){if(c!=null&&String(c).trim()!=="")return Ie({userId:e,cId:t,agentId:c,file:i,skillUrls:a,skillUrlMap:w,skillNames:N,updateSkillNames:_,mcpServersConfig:s,permissionsConfig:o,hooksConfig:p,hookScripts:u,service:y});const D=Date.now(),h=`computer:${e}:${t}`,d=le(a),B=[],A=[],g=new Set,$=[];if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});const k=oe(y),b=await H(y,e,t,h),T=l.join(b,".tmp"),{skillsDir:S,agentsDir:R,agentTypes:x}=await ge(b);n.existsSync(b)||await n.promises.mkdir(b,{recursive:!0});const P=l.join(T,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(n.existsSync(S)){const j=(await n.promises.readdir(S,{withFileTypes:!0})).filter(E=>E.isDirectory()&&pe(l.join(S,E.name)));if(j.length>0){await n.promises.mkdir(P,{recursive:!0});for(const E of j){const C=l.join(S,E.name),I=l.join(P,E.name);await Q(C,I)}r(h,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:j.map(E=>E.name)})}}if(await X(S),await X(R),await n.promises.mkdir(S,{recursive:!0}),await n.promises.mkdir(R,{recursive:!0}),n.existsSync(P)){const m=await n.promises.readdir(P,{withFileTypes:!0});for(const j of m)if(j.isDirectory()){const E=l.join(P,j.name),C=l.join(S,j.name);await Q(E,C)}await X(P)}const v=n.existsSync(S),W=n.existsSync(R);if(r(h,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:S,targetAgentsDir:R,agentTypes:x,skillsExists:v,agentsExists:W}),await Re(b,{mcpServersConfig:s,hooksConfig:p,permissionsConfig:o,hookScripts:u},h),!i&&d.length===0){const m=await fe(b,h);return r(h,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:k,skillsDir:null,agentsDir:null,agentTypes:x,syncAgentsElapsedMs:m?.elapsedMs,elapsedMs:Date.now()-D}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:k}}if(i){if(!i.path)throw new f("Uploaded file has no valid path",{field:"file.path"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:i.originalname})}r(h,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:k,hasUploadedZip:!!i,skillUrlsCount:d.length});try{n.existsSync(T)||await n.promises.mkdir(T,{recursive:!0});const m=[];if(i){const L=l.join(T,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);A.push(L),await n.promises.mkdir(L,{recursive:!0}),r(h,"DEBUG","Start extracting uploaded zip file",{extractRoot:L}),await Y(i.path,L),r(h,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:L});const Z=await ne(L,"skills"),O=await ne(L,"agents");if(Z){await n.promises.mkdir(S,{recursive:!0});const F=await n.promises.readdir(Z,{withFileTypes:!0});for(const G of F){if(!G.isDirectory())continue;const V=l.join(Z,G.name),q=l.join(S,G.name);n.existsSync(q)&&await X(q),await Q(V,q),g.add(G.name)}m.push("skills"),r(h,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetSkillsDir:S,agentTypes:x})}else r(h,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:L});O?(await X(R),await Q(O,R),m.push("agents"),r(h,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetAgentsDir:R,agentTypes:x})):r(h,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:L})}for(let L=0;L<d.length;L+=1){const Z=d[L];try{const O=l.join(T,`skill_url_${Date.now()}_${L}_${Math.round(Math.random()*1e6)}.zip`);B.push(O);const F=l.join(T,`skill_url_extract_${Date.now()}_${L}_${Math.round(Math.random()*1e6)}`);A.push(F),await n.promises.mkdir(F,{recursive:!0}),r(h,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:Z}),await ce(Z,O,h),r(h,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:Z,downloadedZipPath:O}),await Y(O,F);const V=(await n.promises.readdir(F,{withFileTypes:!0})).filter(M=>M.isDirectory()&&!M.name.startsWith(".")),U=V.find(M=>M.name==="skills")?(await n.promises.readdir(l.join(F,"skills"),{withFileTypes:!0})).filter(M=>M.isDirectory()&&!M.name.startsWith(".")).map(M=>({name:M.name,sourcePath:l.join(F,"skills",M.name)})):V.map(M=>({name:M.name,sourcePath:l.join(F,M.name)}));if(U.length===0){r(h,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:Z,extractRoot:F}),$.push({name:null,url:Z,reason:"No skill directory found in downloaded zip"});continue}await n.promises.mkdir(S,{recursive:!0});for(const M of U){const z=l.join(S,M.name);n.existsSync(z)&&await X(z),await Q(M.sourcePath,z),g.add(M.name),r(h,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:Z,skillName:M.name,destSkillPath:z})}}catch(O){r(h,"ERROR","Download/extract skill zip failed, skip this skill",{userId:e,cId:t,skillUrl:Z,error:O.message}),$.push({name:null,url:Z,reason:`Download/extract skill zip failed: ${O.message}`})}m.includes("skills")||m.push("skills")}m.length===0&&r(h,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!i,skillUrlsCount:d.length});const j=Array.from(g),E=m.length>0?`Workspace created successfully, ${m.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)",C=Date.now()-D;r(h,"INFO","Workspace resources prepared",{userId:e,cId:t,updatedDirs:m,updatedSkills:j,agentTypes:x,prepareElapsedMs:C});const I=await fe(b,h);return r(h,"INFO",E,{userId:e,cId:t,updatedDirs:m,updatedSkills:j,agentTypes:x,prepareElapsedMs:C,syncAgentsElapsedMs:I?.elapsedMs,elapsedMs:Date.now()-D}),{message:E,workspaceRoot:k,updatedSkills:j,failedSkills:$}}catch(m){throw r(h,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:m.message,elapsedMs:Date.now()-D}),m instanceof f||m instanceof ie||m instanceof K?m:new K(`Failed to create workspace: ${m.message}`,{userId:e,cId:t})}finally{const m=Date.now();try{for(const j of A)n.existsSync(j)&&await n.promises.rm(j,{recursive:!0,force:!0})}catch(j){r(h,"WARN","Failed to clean up temporary extracted zip",{error:j.message})}for(const j of B)try{n.existsSync(j)&&await n.promises.unlink(j)}catch(E){r(h,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:j,error:E.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(j){r(h,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:j.message})}r(h,"INFO","Workspace temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-m,totalElapsedMs:Date.now()-D})}}async function Fe(e,t,i,a,s,o=null){const p=Date.now(),u=`computer:${e}:${t}`,c=le(s),N=[],_=[],w=new Set,y=[];let D=null;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i)throw new f("agentId cannot be empty",{field:"agentId"});if(!a&&c.length===0)throw new f("file or skillUrls cannot both be empty",{field:"file|skillUrls"});const h=oe(o),d=await H(o,e,t,u),B=l.join(d,".tmp");await n.promises.mkdir(d,{recursive:!0}),await n.promises.mkdir(B,{recursive:!0});const{agentStorePath:A,skillsDir:g,agentsDir:$}=await xe(e,i,u,o);try{let k=await we(A,u);if(!k.acquired)for(let x=1;x<=5&&!k.acquired;x++)await new Promise(P=>setTimeout(P,200*x)),k=await we(A,u);if(!k.acquired)throw new K("Agent store is busy, please retry",{userId:e,cId:t,agentId:i});if(D=k.lockPath,a){if(!a.path)throw new f("Uploaded file has no valid path",{field:"file.path"});const x=l.join(B,`push_skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);_.push(x),await n.promises.mkdir(x,{recursive:!0}),await Y(a.path,x);const P=await he(x),v=await ne(x,"skills"),W=v?(await n.promises.readdir(v,{withFileTypes:!0})).filter(m=>m.isDirectory()).map(m=>({name:m.name,sourcePath:l.join(v,m.name)})):P;await re(W,ae,async m=>{await se(m.sourcePath,g,m.name,{asDynamic:!0}),w.add(m.name)})}await re(c,ae,async(x,P)=>{try{const v=l.join(B,`push_skill_url_${Date.now()}_${P}_${Math.round(Math.random()*1e6)}.zip`);N.push(v);const W=l.join(B,`push_skill_url_extract_${Date.now()}_${P}_${Math.round(Math.random()*1e6)}`);_.push(W),await n.promises.mkdir(W,{recursive:!0}),await ce(x,v,u),await Y(v,W);const m=await he(W);if(m.length===0){r(u,"WARN","No skill dir found in downloaded zip",{skillUrl:x}),y.push({name:null,url:x,reason:"No skill directory found in downloaded zip"});return}for(const j of m)await se(j.sourcePath,g,j.name,{asDynamic:!0}),w.add(j.name)}catch(v){r(u,"ERROR","Download/extract/install skill zip failed, skip this skill",{userId:e,cId:t,agentId:i,skillUrl:x,error:v.message}),y.push({name:null,url:x,reason:`Download/extract/install skill zip failed: ${v.message}`})}});let b=null,T=!1;o&&(o.isUserApp||o.isNormalProject)&&o.appId&&(T=await Ee(e,d,i,o,u,{})),T||(b=await Se(d,g,$,u));const S=Array.from(w),R=S.length>0?`Pushed ${S.length} skills to agent store: ${S.join(", ")}`:"No valid skill directories found in file or skillUrls";return r(u,"INFO",R,{userId:e,cId:t,agentId:i,updatedSkills:S,linkElapsedMs:b?.elapsedMs,elapsedMs:Date.now()-p}),{message:R,workspaceRoot:h,agentStorePath:A,updatedSkills:S,failedSkills:y}}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 f||k instanceof ie||k instanceof K?k:new K(`Failed to push skill to workspace: ${k.message}`,{userId:e,cId:t,agentId:i})}finally{await Ne(D,u);for(const k of _)try{n.existsSync(k)&&await n.promises.rm(k,{recursive:!0,force:!0})}catch(b){r(u,"WARN","Failed to clean up temporary extracted zip",{error:b.message})}for(const k of N)try{n.existsSync(k)&&await n.promises.unlink(k)}catch(b){r(u,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:k,error:b.message})}try{a&&a.path&&n.existsSync(a.path)&&await n.promises.unlink(a.path)}catch(k){r(u,"WARN","Failed to clean up uploaded zip file",{tempZipPath:a?.path,error:k.message})}}}async function tt(e,t,i,a,s,o=null){if(s!=null&&String(s).trim()!==""){if(o&&(o.isUserApp||o.isNormalProject)&&o.appId)return Fe(e,t,s,i,a,o);let A=null;if(o?.isUserApp?A=He(o,e,t):te.COMPUTER_WORKSPACE_DIR&&(A=l.join(te.COMPUTER_WORKSPACE_DIR,String(e),String(t))),Be(A))return Fe(e,t,s,i,a,o);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 u=Date.now(),c=`computer:${e}:${t}`,N=le(a),_=[],w=[];if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i&&N.length===0)throw new f("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(i){if(!i.path)throw new f("Uploaded file has no valid path",{field:"file.path"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:i?.originalname})}const y=oe(o),D=await H(o,e,t,c),h=l.join(D,".tmp"),{skillsDir:d,agentTypes:B}=await ge(D);try{n.existsSync(D)||await n.promises.mkdir(D,{recursive:!0}),n.existsSync(d)||await n.promises.mkdir(d,{recursive:!0}),n.existsSync(h)||await n.promises.mkdir(h,{recursive:!0});const A=[],g=new Set,$=[];if(i){const S=l.join(h,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);w.push(S),await n.promises.mkdir(S,{recursive:!0}),r(c,"DEBUG","Start extracting skill zip file",{extractRoot:S}),await Y(i.path,S),r(c,"DEBUG","Skill zip file extracted successfully",{extractRoot:S});const R=await ne(S,"skills");if(!R)r(c,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:S});else{const P=(await n.promises.readdir(R,{withFileTypes:!0})).filter(v=>v.isDirectory()&&!v.name.startsWith("."));if(P.length===0)r(c,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:R});else for(const v of P){const W=l.join(R,v.name),m=l.join(d,v.name);n.existsSync(m)&&await X(m),await Q(W,m),g.add(v.name),r(c,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:v.name,destSkillPath:m})}}}for(let S=0;S<N.length;S+=1){const R=N[S];try{const x=l.join(h,`skill_push_url_${Date.now()}_${S}_${Math.round(Math.random()*1e6)}.zip`);_.push(x);const P=l.join(h,`skill_push_url_extract_${Date.now()}_${S}_${Math.round(Math.random()*1e6)}`);w.push(P),await n.promises.mkdir(P,{recursive:!0}),r(c,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:R}),await ce(R,x,c),await Y(x,P);const W=(await n.promises.readdir(P,{withFileTypes:!0})).filter(E=>E.isDirectory()&&!E.name.startsWith(".")),j=W.find(E=>E.name==="skills")?(await n.promises.readdir(l.join(P,"skills"),{withFileTypes:!0})).filter(E=>E.isDirectory()&&!E.name.startsWith(".")).map(E=>({name:E.name,sourcePath:l.join(P,"skills",E.name)})):W.map(E=>({name:E.name,sourcePath:l.join(P,E.name)}));if(j.length===0){r(c,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:R,extractRoot:P}),$.push({name:null,url:R,reason:"No skill directory found in downloaded zip"});continue}for(const E of j){const C=l.join(d,E.name);n.existsSync(C)&&await X(C),await Q(E.sourcePath,C),g.add(E.name),r(c,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:R,skillName:E.name,destSkillPath:C})}}catch(x){r(c,"ERROR","Download/extract skill zip failed, skip this skill",{userId:e,cId:t,skillUrl:R,error:x.message}),$.push({name:null,url:R,reason:`Download/extract skill zip failed: ${x.message}`})}}for(const S of g)A.push(S);const k=A.length>0?`Pushed ${A.length} skills: ${A.join(", ")}`:"No valid skill directories found in file or skillUrls",b=Date.now()-u;r(c,"INFO","Push skills resources prepared",{userId:e,cId:t,updatedSkills:A,agentTypes:B,prepareElapsedMs:b});const T=await fe(D,c);return r(c,"INFO",k,{userId:e,cId:t,updatedSkills:A,agentTypes:B,prepareElapsedMs:b,syncAgentsElapsedMs:T?.elapsedMs,elapsedMs:Date.now()-u}),{message:k,workspaceRoot:y,updatedSkills:A,failedSkills:$}}catch(A){throw r(c,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:A.message,elapsedMs:Date.now()-u}),A instanceof f||A instanceof ie||A instanceof K?A:new K(`Failed to push skill to workspace: ${A.message}`,{userId:e,cId:t})}finally{const A=Date.now();try{for(const g of w)n.existsSync(g)&&await n.promises.rm(g,{recursive:!0,force:!0})}catch(g){r(c,"WARN","Failed to clean up temporary extracted zip",{error:g.message})}for(const g of _)try{n.existsSync(g)&&await n.promises.unlink(g)}catch($){r(c,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:g,error:$.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(g){r(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:g.message})}r(c,"INFO","Push skills temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-A,totalElapsedMs:Date.now()-u})}}const it=new Set([".tmp"]);async function nt(e,t,i,a,s=null){const o=Date.now(),p=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i||!i.path)throw new f("file is required",{field:"file"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:i.originalname});const c=await H(s,e,t,p),N=l.join(c,".tmp"),_=l.join(N,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{n.existsSync(c)||await n.promises.mkdir(c,{recursive:!0}),n.existsSync(N)||await n.promises.mkdir(N,{recursive:!0}),await n.promises.mkdir(_,{recursive:!0}),r(p,"DEBUG","Start extracting template zip file",{extractRoot:_}),await Y(i.path,_),r(p,"DEBUG","Template zip file extracted successfully",{extractRoot:_});const w=await n.promises.readdir(_,{withFileTypes:!0});for(const y of w){if(it.has(y.name)){r(p,"WARN","Skip reserved workspace entry in template zip",{name:y.name});continue}const D=l.join(_,y.name),h=l.join(c,y.name);if(y.isDirectory())await Q(D,h);else{const d=l.dirname(h);n.existsSync(d)||await n.promises.mkdir(d,{recursive:!0}),await n.promises.copyFile(D,h)}}if(r(p,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:c,fileCount:w.length}),te.GIT_ENABLED&&(a==="true"||a===!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:c,elapsedMs:Date.now()-o}),{message:"Project template initialized successfully",workspaceRoot:c}}catch(w){throw r(p,"ERROR","Failed to init project template",{userId:e,cId:t,error:w.message,elapsedMs:Date.now()-o}),w instanceof f||w instanceof ie||w instanceof K?w:new K(`Failed to init project template: ${w.message}`,{userId:e,cId:t})}finally{try{n.existsSync(_)&&await n.promises.rm(_,{recursive:!0,force:!0})}catch(w){r(p,"WARN","Failed to clean up temporary extracted zip",{error:w.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(w){r(p,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:w.message})}}}async function st(e,t,i,a=null){if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i||typeof i!="string"||!i.trim())throw new f("command cannot be empty",{field:"command"});const s=await H(a,e,t,"computer");if(!n.existsSync(s))throw new f("workspace directory does not exist",{field:"workDir",workDir:s});const o=`computer:${e}:${t}`;r(o,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:s,command:i});const p=10*60*1e3,u={cwd:s,timeout:p,maxBuffer:50*1024*1024};return te.BASH_PATH&&(u.shell=te.BASH_PATH),new Promise((c,N)=>{ve(i,u,(_,w,y)=>{const D=_?_.killed?-1:_.code||1:0,h=_&&_.killed?(y||"")+`
|
|
2
|
-
Command timed out after ${p/1e3}s`:y||"";r(o,"INFO","Execute command completed",{userId:e,cId:t,exitCode:D,killed:_?_.killed:!1,stdoutLength:w?w.length:0,stderrLength:h.length}),c({stdout:w||"",stderr:h,exitCode:D})})})}async function
|
|
1
|
+
import n from"fs";import l from"path";import{exec as ve}from"child_process";import Me from"cross-spawn";import We from"archiver";import ne from"../../appConfig/index.js";import{extractZip as Y}from"../common/zipUtils.js";import{ValidationError as f,SystemError as K,FileError as te}from"../error/errorHandler.js";import{log as r}from"../log/logUtils.js";import{createPnpmNpmrc as Te}from"../common/npmrcUtils.js";import{ensurePrimaryAgentDirs as ge,syncAgents as fe,linkWorkspaceToAgentStore as Se,forceDirSymlink as Ce,copyDirContents as Le,isWorkspaceSkillsSymlinked as Be}from"../common/AgentWorkspaceUtils.js";import{getProjectStoreRoot as Ue,getAgentStorePath as De,readManifest as Ze,writeManifest as Ge,reverseRefs as Ke,ensureAgentStoreDirs as xe,tryAcquireAgentStoreLock as we,releaseAgentStoreLock as Ne,pruneAgentSkills as qe,installSkillDir as se,replaceAgentsDir as Ve,agentSkillExists as Je}from"../common/agentStoreUtils.js";import{writeAgentHookConfigs as Re}from"./hookConfigUtils.js";import{computerUserRoot as He,ensureWorkspaceDir as H,resolveWorkspaceDir as Ye,resolveWorkspaceRoot as oe}from"./workspaceContext.js";function le(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 le(i)}catch{}return[t]}return[]}async function je(e,t,i){try{return await Ce(e,t,i),!0}catch(a){return r(i,"WARN","Skill view dir link unavailable, fallback to copy",{linkPath:e,targetDir:t,platform:process.platform,error:a.message}),!1}}async function Xe(e,t,i){const a=process.platform==="win32"?l.resolve(t):l.relative(l.dirname(e),t).split(l.sep).join("/");try{return await n.promises.symlink(a,e,"file"),!0}catch(s){return r(i,"WARN","Skill view file link unavailable, fallback to copy",{linkPath:e,targetFile:t,platform:process.platform,error:s.message}),!1}}async function Ee(e,t,i,a,s,o={}){const p=Ue(e,a);if(!p||!i)return!1;const{skillNames:u=null,subagentNames:c=null}=o,N=l.join(p,".view.lock");await n.promises.mkdir(p,{recursive:!0});const _=Date.now()+3e4;let w=!1;for(;Date.now()<_&&!w;)try{await n.promises.writeFile(N,String(Date.now()),{flag:"wx"}),w=!0}catch(y){if(y.code!=="EEXIST")throw y;try{const D=await n.promises.stat(N);if(Date.now()-D.mtimeMs>5*60*1e3){await n.promises.rm(N,{force:!0});continue}}catch{}await new Promise(D=>setTimeout(D,200))}if(!w)throw new K("Agent skill view is busy, please retry");try{const y=await Ze(p),D=y.agents[String(i)]||{skills:[],subagents:[]};u&&(D.skills=[...new Set(u.map(g=>String(g||"").trim()).filter(Boolean))]),c&&(D.subagents=[...new Set(c.map(g=>String(g||"").trim()).filter(Boolean))]),y.agents[String(i)]=D,await Ge(p,y);const h=[".agents",".claude",".opencode",".nuwax-harness"],d=[];for(const g of h)for(const $ of["skills","agents"]){const k=l.join(t,g,$);if(await n.promises.mkdir(l.dirname(k),{recursive:!0}),g===".agents")try{(await n.promises.lstat(k)).isSymbolicLink()&&await n.promises.rm(k,{recursive:!0,force:!0})}catch{}else{const b=l.join(t,".agents",$),T=process.platform==="win32"?l.resolve(b):"../.agents/"+$;let S=!1;try{S=(await n.promises.lstat(k)).isSymbolicLink()&&n.readlinkSync(k)===T}catch{}S||(await n.promises.rm(k,{recursive:!0,force:!0}),await je(k,b,s)||d.push([b,k]));continue}await n.promises.mkdir(k,{recursive:!0})}const B=async(g,$,k)=>{k==="skills"||(await n.promises.lstat(g)).isDirectory()?(d.length>0||!await je($,g,s))&&await Le(g,$):await Xe($,g,s)||await n.promises.copyFile(g,$)},A=l.join(t,".agents");for(const g of["skills","agents"]){const k=Ke(y,g==="skills"?"skills":"subagents"),b=l.join(A,g),T=n.existsSync(b)?await n.promises.readdir(b):[],S=new Set(Object.keys(k));for(const R of T){const x=l.join(b,R);pe(x)||S.has(R)||(await n.promises.rm(x,{recursive:!0,force:!0}),r(s,"INFO","Skill view entry removed (no agent references it)",{kind:g,name:R}))}for(const[R,x]of Object.entries(k)){const P=l.join(b,R);if(pe(P))continue;const v=[...new Set([String(i),...x.map(String)])];let W=null;for(const E of v){const C=l.join(De(e,E,a),g,R);if(n.existsSync(C)){W=C;break}}if(!W){await n.promises.rm(P,{recursive:!0,force:!0});continue}const m=process.platform==="win32"?l.resolve(W):l.relative(b,W).split(l.sep).join("/");let j=!1;try{j=!(await n.promises.lstat(P)).isSymbolicLink()||n.readlinkSync(P)!==m}catch{j=!0}j&&(await n.promises.rm(P,{recursive:!0,force:!0}),await B(W,P,g))}if(g==="skills"){const R=[...new Set([String(i),...Object.keys(y.agents||{})])];for(const x of R){const P=l.join(De(e,x,a),"skills");let v=[];try{v=await n.promises.readdir(P,{withFileTypes:!0})}catch{continue}for(const W of v){if(!W.isDirectory())continue;const m=l.join(P,W.name);if(!pe(m))continue;const j=l.join(b,W.name);n.existsSync(j)||(await B(m,j,g),r(s,"INFO","Dynamic skill linked into view",{owner:x,name:W.name}))}}}}for(const[g,$]of d)await n.promises.rm($,{recursive:!0,force:!0}),await n.promises.cp(g,$,{recursive:!0,dereference:!0,force:!0});return r(s,"INFO","Shared skill view synced",{userWorkspaceRoot:t,projectStoreRoot:p,agentId:i,skills:D.skills,subagents:D.subagents,copyFallbackDirs:d.length}),!0}finally{await n.promises.rm(N,{force:!0})}}function _e(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 _e(JSON.parse(t))}catch{return[{name:null,url:t}]}}return[]}function Qe(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 o=String(a||"").trim(),p=typeof s=="string"?s.trim():"";o&&p&&(i[o]=p)}return i}function Pe(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 ce(e,t,i){let a;try{a=await fetch(e)}catch(u){throw new te(`Failed to download skill zip from url: ${e}`,{url:e,reason:u.message})}if(!a.ok)throw new te(`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 o=await a.arrayBuffer(),p=Buffer.from(o);await n.promises.writeFile(t,p)}async function ie(e,t){const i=l.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 o=l.join(e,s.name),p=l.join(o,t);if(n.existsSync(p)&&(await n.promises.lstat(p)).isDirectory())return p}return null}async function Ot(e){return ie(e,"skills")}const Ie=".dynamic_add.lock";function pe(e){const t=l.join(e,Ie);return n.existsSync(t)&&n.statSync(t).isFile()}async function X(e){n.existsSync(e)&&await n.promises.rm(e,{recursive:!0,force:!0})}async function Q(e,t){try{await n.promises.rename(e,t)}catch(i){if(i.code==="EXDEV"){async function a(s,o){if((await n.promises.lstat(s)).isDirectory()){await n.promises.mkdir(o,{recursive:!0});const u=await n.promises.readdir(s);for(const c of u)await a(l.join(s,c),l.join(o,c))}else await n.promises.copyFile(s,o)}await a(e,t),await n.promises.rm(e,{recursive:!0,force:!0})}else throw i}}async function he(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(l.join(e,"skills"),{withFileTypes:!0})).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).map(o=>({name:o.name,sourcePath:l.join(e,"skills",o.name)})):i.map(s=>({name:s.name,sourcePath:l.join(e,s.name)}))}const ae=8;async function re(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 o=s++;if(o>=e.length)return;await i(e[o],o)}}))}async function et(e){const{userId:t,cId:i,agentId:a,file:s,skillUrls:o,skillUrlMap:p,skillNames:u,updateSkillNames:c,mcpServersConfig:N,permissionsConfig:_,hooksConfig:w,hookScripts:y,service:D}=e,h=Date.now(),d=`computer:${t}:${i}`,B=Qe(p),A=_e(o),g=Pe(u),$=c!=null,k=new Set(Pe(c)),b=[],T=[],S=new Set,R=new Set,x=[];let P=null,v=!1;if(!t)throw new f("userId cannot be empty",{field:"userId"});if(!i)throw new f("cId cannot be empty",{field:"cId"});if(!a)throw new f("agentId cannot be empty",{field:"agentId"});const W=oe(D),m=await H(D,t,i,d),j=l.join(m,".tmp");await n.promises.mkdir(m,{recursive:!0}),await n.promises.mkdir(j,{recursive:!0});const{agentStorePath:E,skillsDir:C,agentsDir:I}=await xe(t,a,d,D),L=O=>!O||!$||k.has(O)?!0:!Je(C,O),Z=async(O,F,G)=>{const V=l.join(j,`skill_url_${Date.now()}_${G}_${Math.round(Math.random()*1e6)}.zip`);b.push(V);const q=l.join(j,`skill_url_extract_${Date.now()}_${G}_${Math.round(Math.random()*1e6)}`);T.push(q),await n.promises.mkdir(q,{recursive:!0});try{r(d,"INFO","Start download skill zip from url",{userId:t,cId:i,agentId:a,skillName:F,skillUrl:O}),await ce(O,V,d),await Y(V,q)}catch(U){r(d,"ERROR","Download/extract skill zip failed, skip this skill",{userId:t,cId:i,agentId:a,skillName:F,skillUrl:O,error:U.message}),x.push({name:F||null,url:O,reason:`Download/extract skill zip failed: ${U.message}`});return}try{const U=await he(q);if(U.length===0){r(d,"WARN","No skill dir found in downloaded zip",{skillUrl:O,destName:F}),x.push({name:F||null,url:O,reason:"No skill directory found in downloaded zip"});return}let M=F?U.find(z=>z.name===F):null;if(!M&&U.length===1&&(M=U[0]),F&&M){if(!L(F)){R.add(F);return}await se(M.sourcePath,C,F,{asDynamic:!1}),S.add(F),r(d,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:O,skillName:F,zipDirName:M.name});return}for(const z of U){if(!L(z.name)){R.add(z.name);continue}await se(z.sourcePath,C,z.name,{asDynamic:!1}),S.add(z.name),r(d,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:O,skillName:z.name})}}catch(U){r(d,"ERROR","Install skill from url failed, skip this skill",{userId:t,cId:i,agentId:a,skillName:F,skillUrl:O,error:U.message}),x.push({name:F||null,url:O,reason:`Install skill failed: ${U.message}`})}};await Re(m,{mcpServersConfig:N,hooksConfig:w,permissionsConfig:_,hookScripts:y},d);try{const O=await we(E,d);if(!O.acquired)v=!0;else{P=O.lockPath;const V=Date.now();let q=null;if(s){if(!s.path)throw new f("Uploaded file has no valid path",{field:"file.path"});if(l.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:s.originalname});const z=l.join(j,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);T.push(z),await n.promises.mkdir(z,{recursive:!0}),await Y(s.path,z);const J=await ie(z,"skills");if(J){const me=(await n.promises.readdir(J,{withFileTypes:!0})).filter(ee=>ee.isDirectory());await re(me,ae,async ee=>{if(!L(ee.name)){R.add(ee.name);return}await se(l.join(J,ee.name),C,ee.name,{asDynamic:!1}),S.add(ee.name)})}q=await ie(z,"agents")}const U=Object.entries(B);if(U.length>0){const M=[];for(const[z,J]of U){if(!L(z)){R.add(z),r(d,"INFO","Skip download skill zip (already in agent store)",{userId:t,cId:i,agentId:a,skillName:z,skillUrl:J});continue}M.push({skillName:z,skillUrl:J})}await re(M,ae,async(z,J)=>{await Z(z.skillUrl,z.skillName,J)})}else{const M=[];for(let z=0;z<A.length;z++){const{name:J,url:me}=A[z];if(J&&!L(J)){R.add(J);continue}M.push({skillUrl:me,hintedName:J,index:z})}await re(M,ae,async z=>{await Z(z.skillUrl,z.hintedName,z.index)})}await Ve(q,I),await qe(C,g,d),r(d,"INFO","Agent store resources prepared",{userId:t,cId:i,agentId:a,selectiveInstall:$,updatedSkills:Array.from(S),skippedSkills:Array.from(R),updateSkillNames:Array.from(k),keepSkillNames:g,skillUrlMapCount:U.length,prepareElapsedMs:Date.now()-V})}let F=null,G=!1;if(D&&(D.isUserApp||D.isNormalProject)&&D.appId){let V=null;try{V=(await n.promises.readdir(I,{withFileTypes:!0})).map(q=>q.name)}catch{}G=await Ee(t,m,a,D,d,{skillNames:u?g:null,subagentNames:V})}return G||(F=await Se(m,C,I,d)),r(d,"INFO","Workspace created successfully (agent store)",{userId:t,cId:i,agentId:a,agentStorePath:E,updatedSkills:Array.from(S),skippedSkills:Array.from(R),failedSkills:x,skippedStoreUpdate:v,linkElapsedMs:F?.elapsedMs,elapsedMs:Date.now()-h}),{message:v?"Workspace linked to agent store (store update skipped, lock held)":"Workspace created successfully, linked to agent store",workspaceRoot:W,agentStorePath:E,updatedSkills:Array.from(S),skippedSkills:Array.from(R),failedSkills:x,skippedStoreUpdate:v}}catch(O){throw r(d,"ERROR","Failed to create workspace with agent store",{userId:t,cId:i,agentId:a,error:O.message,elapsedMs:Date.now()-h}),O instanceof f||O instanceof te||O instanceof K?O:new K(`Failed to create workspace: ${O.message}`,{userId:t,cId:i,agentId:a})}finally{await Ne(P,d);const O=Date.now();for(const F of T)try{n.existsSync(F)&&await n.promises.rm(F,{recursive:!0,force:!0})}catch(G){r(d,"WARN","Failed to clean up temporary extracted zip",{error:G.message})}for(const F of b)try{n.existsSync(F)&&await n.promises.unlink(F)}catch(G){r(d,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:F,error:G.message})}try{s&&s.path&&n.existsSync(s.path)&&await n.promises.unlink(s.path)}catch(F){r(d,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:F.message})}r(d,"INFO","Workspace temp cleanup completed",{userId:t,cId:i,agentId:a,elapsedMs:Date.now()-O,totalElapsedMs:Date.now()-h})}}async function tt(e,t,i,a,s,o,p,u,c,N,_,w,y=null){if(c!=null&&String(c).trim()!=="")return et({userId:e,cId:t,agentId:c,file:i,skillUrls:a,skillUrlMap:w,skillNames:N,updateSkillNames:_,mcpServersConfig:s,permissionsConfig:o,hooksConfig:p,hookScripts:u,service:y});const D=Date.now(),h=`computer:${e}:${t}`,d=le(a),B=[],A=[],g=new Set,$=[];if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});const k=oe(y),b=await H(y,e,t,h),T=l.join(b,".tmp"),{skillsDir:S,agentsDir:R,agentTypes:x}=await ge(b);n.existsSync(b)||await n.promises.mkdir(b,{recursive:!0});const P=l.join(T,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(n.existsSync(S)){const j=(await n.promises.readdir(S,{withFileTypes:!0})).filter(E=>E.isDirectory()&&pe(l.join(S,E.name)));if(j.length>0){await n.promises.mkdir(P,{recursive:!0});for(const E of j){const C=l.join(S,E.name),I=l.join(P,E.name);await Q(C,I)}r(h,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:j.map(E=>E.name)})}}if(await X(S),await X(R),await n.promises.mkdir(S,{recursive:!0}),await n.promises.mkdir(R,{recursive:!0}),n.existsSync(P)){const m=await n.promises.readdir(P,{withFileTypes:!0});for(const j of m)if(j.isDirectory()){const E=l.join(P,j.name),C=l.join(S,j.name);await Q(E,C)}await X(P)}const v=n.existsSync(S),W=n.existsSync(R);if(r(h,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:S,targetAgentsDir:R,agentTypes:x,skillsExists:v,agentsExists:W}),await Re(b,{mcpServersConfig:s,hooksConfig:p,permissionsConfig:o,hookScripts:u},h),!i&&d.length===0){const m=await fe(b,h);return r(h,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:k,skillsDir:null,agentsDir:null,agentTypes:x,syncAgentsElapsedMs:m?.elapsedMs,elapsedMs:Date.now()-D}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:k}}if(i){if(!i.path)throw new f("Uploaded file has no valid path",{field:"file.path"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:i.originalname})}r(h,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:k,hasUploadedZip:!!i,skillUrlsCount:d.length});try{n.existsSync(T)||await n.promises.mkdir(T,{recursive:!0});const m=[];if(i){const L=l.join(T,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);A.push(L),await n.promises.mkdir(L,{recursive:!0}),r(h,"DEBUG","Start extracting uploaded zip file",{extractRoot:L}),await Y(i.path,L),r(h,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:L});const Z=await ie(L,"skills"),O=await ie(L,"agents");if(Z){await n.promises.mkdir(S,{recursive:!0});const F=await n.promises.readdir(Z,{withFileTypes:!0});for(const G of F){if(!G.isDirectory())continue;const V=l.join(Z,G.name),q=l.join(S,G.name);n.existsSync(q)&&await X(q),await Q(V,q),g.add(G.name)}m.push("skills"),r(h,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetSkillsDir:S,agentTypes:x})}else r(h,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:L});O?(await X(R),await Q(O,R),m.push("agents"),r(h,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetAgentsDir:R,agentTypes:x})):r(h,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:L})}for(let L=0;L<d.length;L+=1){const Z=d[L];try{const O=l.join(T,`skill_url_${Date.now()}_${L}_${Math.round(Math.random()*1e6)}.zip`);B.push(O);const F=l.join(T,`skill_url_extract_${Date.now()}_${L}_${Math.round(Math.random()*1e6)}`);A.push(F),await n.promises.mkdir(F,{recursive:!0}),r(h,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:Z}),await ce(Z,O,h),r(h,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:Z,downloadedZipPath:O}),await Y(O,F);const V=(await n.promises.readdir(F,{withFileTypes:!0})).filter(M=>M.isDirectory()&&!M.name.startsWith(".")),U=V.find(M=>M.name==="skills")?(await n.promises.readdir(l.join(F,"skills"),{withFileTypes:!0})).filter(M=>M.isDirectory()&&!M.name.startsWith(".")).map(M=>({name:M.name,sourcePath:l.join(F,"skills",M.name)})):V.map(M=>({name:M.name,sourcePath:l.join(F,M.name)}));if(U.length===0){r(h,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:Z,extractRoot:F}),$.push({name:null,url:Z,reason:"No skill directory found in downloaded zip"});continue}await n.promises.mkdir(S,{recursive:!0});for(const M of U){const z=l.join(S,M.name);n.existsSync(z)&&await X(z),await Q(M.sourcePath,z),g.add(M.name),r(h,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:Z,skillName:M.name,destSkillPath:z})}}catch(O){r(h,"ERROR","Download/extract skill zip failed, skip this skill",{userId:e,cId:t,skillUrl:Z,error:O.message}),$.push({name:null,url:Z,reason:`Download/extract skill zip failed: ${O.message}`})}m.includes("skills")||m.push("skills")}m.length===0&&r(h,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!i,skillUrlsCount:d.length});const j=Array.from(g),E=m.length>0?`Workspace created successfully, ${m.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)",C=Date.now()-D;r(h,"INFO","Workspace resources prepared",{userId:e,cId:t,updatedDirs:m,updatedSkills:j,agentTypes:x,prepareElapsedMs:C});const I=await fe(b,h);return r(h,"INFO",E,{userId:e,cId:t,updatedDirs:m,updatedSkills:j,agentTypes:x,prepareElapsedMs:C,syncAgentsElapsedMs:I?.elapsedMs,elapsedMs:Date.now()-D}),{message:E,workspaceRoot:k,updatedSkills:j,failedSkills:$}}catch(m){throw r(h,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:m.message,elapsedMs:Date.now()-D}),m instanceof f||m instanceof te||m instanceof K?m:new K(`Failed to create workspace: ${m.message}`,{userId:e,cId:t})}finally{const m=Date.now();try{for(const j of A)n.existsSync(j)&&await n.promises.rm(j,{recursive:!0,force:!0})}catch(j){r(h,"WARN","Failed to clean up temporary extracted zip",{error:j.message})}for(const j of B)try{n.existsSync(j)&&await n.promises.unlink(j)}catch(E){r(h,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:j,error:E.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(j){r(h,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:j.message})}r(h,"INFO","Workspace temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-m,totalElapsedMs:Date.now()-D})}}async function Fe(e,t,i,a,s,o=null){const p=Date.now(),u=`computer:${e}:${t}`,c=le(s),N=[],_=[],w=new Set,y=[];let D=null;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i)throw new f("agentId cannot be empty",{field:"agentId"});if(!a&&c.length===0)throw new f("file or skillUrls cannot both be empty",{field:"file|skillUrls"});const h=oe(o),d=await H(o,e,t,u),B=l.join(d,".tmp");await n.promises.mkdir(d,{recursive:!0}),await n.promises.mkdir(B,{recursive:!0});const{agentStorePath:A,skillsDir:g,agentsDir:$}=await xe(e,i,u,o);try{let k=await we(A,u);if(!k.acquired)for(let x=1;x<=5&&!k.acquired;x++)await new Promise(P=>setTimeout(P,200*x)),k=await we(A,u);if(!k.acquired)throw new K("Agent store is busy, please retry",{userId:e,cId:t,agentId:i});if(D=k.lockPath,a){if(!a.path)throw new f("Uploaded file has no valid path",{field:"file.path"});const x=l.join(B,`push_skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);_.push(x),await n.promises.mkdir(x,{recursive:!0}),await Y(a.path,x);const P=await he(x),v=await ie(x,"skills"),W=v?(await n.promises.readdir(v,{withFileTypes:!0})).filter(m=>m.isDirectory()).map(m=>({name:m.name,sourcePath:l.join(v,m.name)})):P;await re(W,ae,async m=>{await se(m.sourcePath,g,m.name,{asDynamic:!0}),w.add(m.name)})}await re(c,ae,async(x,P)=>{try{const v=l.join(B,`push_skill_url_${Date.now()}_${P}_${Math.round(Math.random()*1e6)}.zip`);N.push(v);const W=l.join(B,`push_skill_url_extract_${Date.now()}_${P}_${Math.round(Math.random()*1e6)}`);_.push(W),await n.promises.mkdir(W,{recursive:!0}),await ce(x,v,u),await Y(v,W);const m=await he(W);if(m.length===0){r(u,"WARN","No skill dir found in downloaded zip",{skillUrl:x}),y.push({name:null,url:x,reason:"No skill directory found in downloaded zip"});return}for(const j of m)await se(j.sourcePath,g,j.name,{asDynamic:!0}),w.add(j.name)}catch(v){r(u,"ERROR","Download/extract/install skill zip failed, skip this skill",{userId:e,cId:t,agentId:i,skillUrl:x,error:v.message}),y.push({name:null,url:x,reason:`Download/extract/install skill zip failed: ${v.message}`})}});let b=null,T=!1;o&&(o.isUserApp||o.isNormalProject)&&o.appId&&(T=await Ee(e,d,i,o,u,{})),T||(b=await Se(d,g,$,u));const S=Array.from(w),R=S.length>0?`Pushed ${S.length} skills to agent store: ${S.join(", ")}`:"No valid skill directories found in file or skillUrls";return r(u,"INFO",R,{userId:e,cId:t,agentId:i,updatedSkills:S,linkElapsedMs:b?.elapsedMs,elapsedMs:Date.now()-p}),{message:R,workspaceRoot:h,agentStorePath:A,updatedSkills:S,failedSkills:y}}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 f||k instanceof te||k instanceof K?k:new K(`Failed to push skill to workspace: ${k.message}`,{userId:e,cId:t,agentId:i})}finally{await Ne(D,u);for(const k of _)try{n.existsSync(k)&&await n.promises.rm(k,{recursive:!0,force:!0})}catch(b){r(u,"WARN","Failed to clean up temporary extracted zip",{error:b.message})}for(const k of N)try{n.existsSync(k)&&await n.promises.unlink(k)}catch(b){r(u,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:k,error:b.message})}try{a&&a.path&&n.existsSync(a.path)&&await n.promises.unlink(a.path)}catch(k){r(u,"WARN","Failed to clean up uploaded zip file",{tempZipPath:a?.path,error:k.message})}}}async function it(e,t,i,a,s,o=null){if(s!=null&&String(s).trim()!==""){if(o&&(o.isUserApp||o.isNormalProject)&&o.appId)return Fe(e,t,s,i,a,o);let A=null;if(o?.isUserApp?A=Ye(o,e,t):ne.COMPUTER_WORKSPACE_DIR&&(A=l.join(He(e),String(t))),Be(A))return Fe(e,t,s,i,a,o);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 u=Date.now(),c=`computer:${e}:${t}`,N=le(a),_=[],w=[];if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i&&N.length===0)throw new f("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(i){if(!i.path)throw new f("Uploaded file has no valid path",{field:"file.path"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:i?.originalname})}const y=oe(o),D=await H(o,e,t,c),h=l.join(D,".tmp"),{skillsDir:d,agentTypes:B}=await ge(D);try{n.existsSync(D)||await n.promises.mkdir(D,{recursive:!0}),n.existsSync(d)||await n.promises.mkdir(d,{recursive:!0}),n.existsSync(h)||await n.promises.mkdir(h,{recursive:!0});const A=[],g=new Set,$=[];if(i){const S=l.join(h,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);w.push(S),await n.promises.mkdir(S,{recursive:!0}),r(c,"DEBUG","Start extracting skill zip file",{extractRoot:S}),await Y(i.path,S),r(c,"DEBUG","Skill zip file extracted successfully",{extractRoot:S});const R=await ie(S,"skills");if(!R)r(c,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:S});else{const P=(await n.promises.readdir(R,{withFileTypes:!0})).filter(v=>v.isDirectory()&&!v.name.startsWith("."));if(P.length===0)r(c,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:R});else for(const v of P){const W=l.join(R,v.name),m=l.join(d,v.name);n.existsSync(m)&&await X(m),await Q(W,m),g.add(v.name),r(c,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:v.name,destSkillPath:m})}}}for(let S=0;S<N.length;S+=1){const R=N[S];try{const x=l.join(h,`skill_push_url_${Date.now()}_${S}_${Math.round(Math.random()*1e6)}.zip`);_.push(x);const P=l.join(h,`skill_push_url_extract_${Date.now()}_${S}_${Math.round(Math.random()*1e6)}`);w.push(P),await n.promises.mkdir(P,{recursive:!0}),r(c,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:R}),await ce(R,x,c),await Y(x,P);const W=(await n.promises.readdir(P,{withFileTypes:!0})).filter(E=>E.isDirectory()&&!E.name.startsWith(".")),j=W.find(E=>E.name==="skills")?(await n.promises.readdir(l.join(P,"skills"),{withFileTypes:!0})).filter(E=>E.isDirectory()&&!E.name.startsWith(".")).map(E=>({name:E.name,sourcePath:l.join(P,"skills",E.name)})):W.map(E=>({name:E.name,sourcePath:l.join(P,E.name)}));if(j.length===0){r(c,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:R,extractRoot:P}),$.push({name:null,url:R,reason:"No skill directory found in downloaded zip"});continue}for(const E of j){const C=l.join(d,E.name);n.existsSync(C)&&await X(C),await Q(E.sourcePath,C),g.add(E.name),r(c,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:R,skillName:E.name,destSkillPath:C})}}catch(x){r(c,"ERROR","Download/extract skill zip failed, skip this skill",{userId:e,cId:t,skillUrl:R,error:x.message}),$.push({name:null,url:R,reason:`Download/extract skill zip failed: ${x.message}`})}}for(const S of g)A.push(S);const k=A.length>0?`Pushed ${A.length} skills: ${A.join(", ")}`:"No valid skill directories found in file or skillUrls",b=Date.now()-u;r(c,"INFO","Push skills resources prepared",{userId:e,cId:t,updatedSkills:A,agentTypes:B,prepareElapsedMs:b});const T=await fe(D,c);return r(c,"INFO",k,{userId:e,cId:t,updatedSkills:A,agentTypes:B,prepareElapsedMs:b,syncAgentsElapsedMs:T?.elapsedMs,elapsedMs:Date.now()-u}),{message:k,workspaceRoot:y,updatedSkills:A,failedSkills:$}}catch(A){throw r(c,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:A.message,elapsedMs:Date.now()-u}),A instanceof f||A instanceof te||A instanceof K?A:new K(`Failed to push skill to workspace: ${A.message}`,{userId:e,cId:t})}finally{const A=Date.now();try{for(const g of w)n.existsSync(g)&&await n.promises.rm(g,{recursive:!0,force:!0})}catch(g){r(c,"WARN","Failed to clean up temporary extracted zip",{error:g.message})}for(const g of _)try{n.existsSync(g)&&await n.promises.unlink(g)}catch($){r(c,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:g,error:$.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(g){r(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:g.message})}r(c,"INFO","Push skills temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-A,totalElapsedMs:Date.now()-u})}}const nt=new Set([".tmp"]);async function st(e,t,i,a,s=null){const o=Date.now(),p=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i||!i.path)throw new f("file is required",{field:"file"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:i.originalname});const c=await H(s,e,t,p),N=l.join(c,".tmp"),_=l.join(N,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{n.existsSync(c)||await n.promises.mkdir(c,{recursive:!0}),n.existsSync(N)||await n.promises.mkdir(N,{recursive:!0}),await n.promises.mkdir(_,{recursive:!0}),r(p,"DEBUG","Start extracting template zip file",{extractRoot:_}),await Y(i.path,_),r(p,"DEBUG","Template zip file extracted successfully",{extractRoot:_});const w=await n.promises.readdir(_,{withFileTypes:!0});for(const y of w){if(nt.has(y.name)){r(p,"WARN","Skip reserved workspace entry in template zip",{name:y.name});continue}const D=l.join(_,y.name),h=l.join(c,y.name);if(y.isDirectory())await Q(D,h);else{const d=l.dirname(h);n.existsSync(d)||await n.promises.mkdir(d,{recursive:!0}),await n.promises.copyFile(D,h)}}if(r(p,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:c,fileCount:w.length}),ne.GIT_ENABLED&&(a==="true"||a===!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:c,elapsedMs:Date.now()-o}),{message:"Project template initialized successfully",workspaceRoot:c}}catch(w){throw r(p,"ERROR","Failed to init project template",{userId:e,cId:t,error:w.message,elapsedMs:Date.now()-o}),w instanceof f||w instanceof te||w instanceof K?w:new K(`Failed to init project template: ${w.message}`,{userId:e,cId:t})}finally{try{n.existsSync(_)&&await n.promises.rm(_,{recursive:!0,force:!0})}catch(w){r(p,"WARN","Failed to clean up temporary extracted zip",{error:w.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(w){r(p,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:w.message})}}}async function at(e,t,i,a=null){if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i||typeof i!="string"||!i.trim())throw new f("command cannot be empty",{field:"command"});const s=await H(a,e,t,"computer");if(!n.existsSync(s))throw new f("workspace directory does not exist",{field:"workDir",workDir:s});const o=`computer:${e}:${t}`;r(o,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:s,command:i});const p=10*60*1e3,u={cwd:s,timeout:p,maxBuffer:50*1024*1024};return ne.BASH_PATH&&(u.shell=ne.BASH_PATH),new Promise((c,N)=>{ve(i,u,(_,w,y)=>{const D=_?_.killed?-1:_.code||1:0,h=_&&_.killed?(y||"")+`
|
|
2
|
+
Command timed out after ${p/1e3}s`:y||"";r(o,"INFO","Execute command completed",{userId:e,cId:t,exitCode:D,killed:_?_.killed:!1,stdoutLength:w?w.length:0,stderrLength:h.length}),c({stdout:w||"",stderr:h,exitCode:D})})})}async function rt(e,t,i,a=null){const s=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});const o=await H(a,e,t,s);if(!n.existsSync(o))throw new f("workspace directory does not exist",{field:"workDir",workDir:o});const p=ne.ZIP_WORKSPACE_EXCLUDE||[],u=Array.isArray(i)?i:[],c=new Set([...p,...u]),N=`${e}_${t}.zip`,_=Date.now();r(s,"INFO","Zip workspace request",{userId:e,cId:t,targetDir:o,excludeDirs:[...c]});const w=We("zip",{zlib:{level:9}});return w.directory(o,!1,y=>{const D=y.name||"";if(D.split(/[\/\\]/).filter(Boolean).some(d=>c.has(d)))return!1;try{const d=l.join(o,D);if(n.lstatSync(d).isSymbolicLink())return!1}catch{return!1}return y}),w.on("warning",y=>{y.code==="ENOENT"?r(s,"WARN","Encountered file problem when creating zip",{message:y.message,code:y.code}):r(s,"ERROR","Encountered warning when creating zip",{message:y.message,code:y.code})}),w.on("error",y=>{r(s,"ERROR","Failed to create zip",{message:y.message,elapsedMs:Date.now()-_})}),w.on("end",()=>{r(s,"INFO","Workspace zip created successfully",{targetDir:o,zipFileName:N,elapsedMs:Date.now()-_})}),{archive:w,zipFileName:N}}const ke=new Set([...ne.ZIP_WORKSPACE_EXCLUDE||[],"dist-packages"]);function ue(e){let t;try{t=n.readdirSync(e,{withFileTypes:!0})}catch{return null}const i=l.join(e,"scripts","package-platforms.mjs");if(n.existsSync(i))return e;for(const a of t)if(a.isDirectory()&&!ke.has(a.name)){const s=ue(l.join(e,a.name));if(s)return s}return null}function de(e,t,i,a=10*60*1e3){return new Promise(s=>{const o=Me(e,t,{...i,timeout:a});let p="",u="";o.stdout?.on("data",c=>{p+=c.toString()}),o.stderr?.on("data",c=>{u+=c.toString()}),o.on("error",c=>{s({stdout:p,stderr:u+`
|
|
3
3
|
Failed to spawn ${e}: ${c.message}`,exitCode:1})}),o.on("close",(c,N)=>{s(c===null&&N?{stdout:p,stderr:u+`
|
|
4
|
-
Process killed by signal ${N} (timeout after ${a/1e3}s)`,exitCode:-1}:{stdout:p,stderr:u,exitCode:c??1})})})}function
|
|
5
|
-
`);for(const d of h){const B=d.trim();if(!B)continue;const A=B.toLowerCase();if(!y.some(T=>A.endsWith(T)))continue;const g=l.resolve(u,B);let $=l.relative(p,g);$=$.split(l.sep).join("/");const k=l.basename(B),b=
|
|
6
|
-
`,"utf8"),r(t,"INFO","Removed conflicting pnpm built dependency settings from package.json",{projectDir:e,removedKeys:o})}}async function
|
|
4
|
+
Process killed by signal ${N} (timeout after ${a/1e3}s)`,exitCode:-1}:{stdout:p,stderr:u,exitCode:c??1})})})}function ot(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 a=-1;for(let s=i.length-1;s>=2;s--)if(/^\d+\.\d+\.\d+$/.test(i[s])){a=s;break}return a<3?null:i.slice(2,a).join("-")}async function lt(e,t,i,a,s=null){const o=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i)throw new f("agentId cannot be empty",{field:"agentId"});if(!a)throw new f("version cannot be empty",{field:"version"});const p=await H(s,e,t,o);if(!n.existsSync(p))throw new f("workspace directory does not exist",{field:"workDir",workDir:p});r(o,"INFO","Build agent package request",{userId:e,cId:t,agentId:i,version:a});const u=ue(p);if(!u)throw new f("package-platforms.mjs not found in workspace",{field:"script"});r(o,"INFO","Found package script",{projectDir:u});const c=await be(u,o);if(r(o,"INFO","pnpm install completed",{exitCode:c.exitCode,stderrLength:c.stderr.length}),c.exitCode!==0)throw r(o,"ERROR","pnpm install failed",{stderr:c.stderr}),new K(`pnpm install failed: ${c.stderr}`);const N=l.join(u,"dist-packages"),_=["scripts/package-platforms.mjs",`agent-${i}`,a,N,"--print-artifacts"],w=await de("node",_,{cwd:u,env:ye()});if(r(o,"INFO","Build completed",{exitCode:w.exitCode,stdoutLength:w.stdout.length}),w.exitCode!==0)throw r(o,"ERROR","Build failed",{stderr:w.stderr}),new K(`Build failed: ${w.stderr}`);const y=[".tar.gz",".tar.bz2",".zip",".tgz"],D=[],h=w.stdout.split(`
|
|
5
|
+
`);for(const d of h){const B=d.trim();if(!B)continue;const A=B.toLowerCase();if(!y.some(T=>A.endsWith(T)))continue;const g=l.resolve(u,B);let $=l.relative(p,g);$=$.split(l.sep).join("/");const k=l.basename(B),b=ot(k);D.push({path:$,fileName:k,platform:b||""})}return r(o,"INFO","Build agent package completed",{artifactsCount:D.length,artifacts:D}),{artifacts:D}}async function ct(e,t,i=null){const a=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});const s=await H(i,e,t,a);if(!n.existsSync(s))return r(a,"WARN","Workspace not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const o=ue(s);if(!o)return r(a,"WARN","package-platforms.mjs not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const p=l.join(o,"dist-packages");return n.existsSync(p)?(n.rmSync(p,{recursive:!0,force:!0}),r(a,"INFO","Cleaned dist-packages",{distPackagesDir:p}),{cleaned:!0}):(r(a,"INFO","dist-packages not found, nothing to clean",{distPackagesDir:p}),{cleaned:!1})}async function pt(e,t,i=null){const a=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});const s=i?.workspacePath?i.workspacePath:await H(i,e,t,a);return n.existsSync(s)?(await n.promises.rm(s,{recursive:!0,force:!0}),r(a,"INFO","Workspace deleted",{userId:e,cId:t,targetDir:s})):r(a,"WARN","Workspace not found, skip delete",{userId:e,cId:t,targetDir:s}),{deleted:!0}}function Ae(e){const t=l.join(e,"package.json");if(n.existsSync(t))return e;let i;try{i=n.readdirSync(e,{withFileTypes:!0})}catch{return null}for(const a of i)if(a.isDirectory()&&!ke.has(a.name)&&a.name!=="node_modules"){const s=Ae(l.join(e,a.name));if(s)return s}return null}const Oe=["neverBuiltDependencies","onlyBuiltDependencies","ignoredBuiltDependencies"],ut=["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 dt(e,t){const i=l.join(e,"package.json");if(!n.existsSync(i))return;const a=await n.promises.readFile(i,"utf8");let s;try{s=JSON.parse(a)}catch{r(t,"WARN","Skip sanitizing package.json: invalid JSON",{projectDir:e});return}if(!s.pnpm||typeof s.pnpm!="object")return;const o=Oe.filter(p=>p in s.pnpm);if(o.length!==0){for(const p of o)delete s.pnpm[p];Object.keys(s.pnpm).length===0&&delete s.pnpm,await n.promises.writeFile(i,`${JSON.stringify(s,null,2)}
|
|
6
|
+
`,"utf8"),r(t,"INFO","Removed conflicting pnpm built dependency settings from package.json",{projectDir:e,removedKeys:o})}}async function mt(e,t){const i=l.join(e,"pnpm-workspace.yaml");if(!n.existsSync(i))return;const s=(await n.promises.readFile(i,"utf8")).split(`
|
|
7
7
|
`),o=[];let p=-1,u=[];for(const c of s){const N=c.trimStart(),_=c.length-N.length,w=Oe.find(y=>new RegExp(`^${y}:\\s*(.*)$`).test(N));if(w){u.push(w);const y=N.slice(w.length+1).trim();(!y||y==="|"||y===">")&&(p=_);continue}if(p>=0){if(N===""||_>p)continue;p=-1}o.push(c)}u.length!==0&&(await n.promises.writeFile(i,o.join(`
|
|
8
8
|
`),"utf8"),r(t,"INFO","Removed conflicting pnpm built dependency settings from pnpm-workspace.yaml",{projectDir:e,removedKeys:u}))}async function ze(e){if(!n.existsSync(e))return"";const t=await n.promises.readFile(e,"utf8"),i=t.split(`
|
|
9
9
|
`).filter(a=>!/^\s*(never-built-dependencies|only-built-dependencies|ignored-built-dependencies)\b/.test(a)).join(`
|
|
10
|
-
`);return i!==t&&await n.promises.writeFile(e,i,"utf8"),i}async function
|
|
10
|
+
`);return i!==t&&await n.promises.writeFile(e,i,"utf8"),i}async function ft(e,t){await dt(e,t),await mt(e,t),await ze(l.join(e,".npmrc"))}async function wt(e,t){await Te(e,t),await ft(e,t);const i=l.join(e,".npmrc");let a=await ze(i);const s=[];if(/dangerously-allow-all-builds\s*=/.test(a)||s.push("dangerously-allow-all-builds=true"),/production\s*=/.test(a)||s.push("production=false"),/confirm-modules-purge\s*=/.test(a)||s.push("confirm-modules-purge=false"),s.length>0){const o=a&&!a.endsWith(`
|
|
11
11
|
`)?`
|
|
12
12
|
`:"";await n.promises.writeFile(i,`${a}${o}${s.join(`
|
|
13
13
|
`)}
|
|
14
|
-
`,"utf8"),r(t,"INFO","Updated .npmrc for pnpm install",{projectDir:e,additions:s})}}function ye(){const e={...process.env};delete e.CI,delete e.NPM_CONFIG_PRODUCTION,delete e.npm_config_production;for(const t of
|
|
14
|
+
`,"utf8"),r(t,"INFO","Updated .npmrc for pnpm install",{projectDir:e,additions:s})}}function ye(){const e={...process.env};delete e.CI,delete e.NPM_CONFIG_PRODUCTION,delete e.npm_config_production;for(const t of ut)delete e[t];return e.NODE_ENV="development",e.NPM_CONFIG_PRODUCTION="false",e}async function be(e,t){await wt(e,t);const i=ye();return de("pnpm",["install","--prefer-offline","--config.production=false","--config.confirmModulesPurge=false","--config.dangerouslyAllowAllBuilds=true"],{cwd:e,env:i})}function $e(e){const t=l.join(e,"pyproject.toml"),i=l.join(e,"requirements.txt");if(n.existsSync(t)||n.existsSync(i))return e;let a;try{a=n.readdirSync(e,{withFileTypes:!0})}catch{return null}for(const s of a)if(s.isDirectory()&&!ke.has(s.name)&&s.name!==".venv"&&s.name!=="venv"&&s.name!=="__pycache__"){const o=$e(l.join(e,s.name));if(o)return o}return null}async function ht(e,t,i,a=null){const s=`computer:${e}:${t}`,o=String(i||"").trim().toLowerCase();if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!o)throw new f("programmingLanguage cannot be empty",{field:"programmingLanguage"});const p=await H(a,e,t,s);if(!n.existsSync(p))throw new f("workspace directory does not exist",{field:"workDir",workDir:p});r(s,"INFO","Install project dependencies request",{userId:e,cId:t,programmingLanguage:o});const u=ye();let c=null,N=null;if(o==="typescript"||o==="ts"){if(c=ue(p)||Ae(p),!c)throw new f("TypeScript project not found in workspace",{field:"projectDir"});N=await be(c,s)}else if(o==="python"||o==="py"){if(c=$e(p),!c)throw new f("Python project not found in workspace",{field:"projectDir"});const _=l.join(c,"pyproject.toml"),w=l.join(c,"requirements.txt");if(n.existsSync(_))N=await de("pip",["install","-e","."],{cwd:c,env:u});else if(n.existsSync(w))N=await de("pip",["install","-r","requirements.txt"],{cwd:c,env:u});else throw new f("No pyproject.toml or requirements.txt found in workspace",{field:"projectDir"})}else throw new f("Unsupported programmingLanguage",{field:"programmingLanguage",programmingLanguage:o});if(r(s,"INFO","Project dependencies install completed",{projectDir:c,programmingLanguage:o,exitCode:N.exitCode,stderrLength:N.stderr.length}),N.exitCode!==0)throw r(s,"ERROR","Project dependencies install failed",{projectDir:c,programmingLanguage:o,stderr:N.stderr}),new K(`Project dependencies install failed: ${N.stderr||N.stdout}`);return{message:"Project dependencies installed successfully",projectDir:c,programmingLanguage:o}}export{tt as createWorkspace,it as pushSkillsToWorkspace,st as initProjectTemplate,at as executeCommand,pt as deleteWorkspace,rt as zipWorkspace,lt as buildAgentPackage,ct as cleanupBuildArtifacts,ht as installProjectDependencies};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
1
|
+
import r from"fs";import o from"path";import{fileURLToPath as V}from"url";import{log as l}from"../log/logUtils.js";const T=o.dirname(V(import.meta.url)),K=o.join(T,"../../assets/opencode-hooks-plugin"),X=o.join(T,"../../assets/opencode-platform-env-plugin"),C=new Set(["SessionStart","SubagentStart","SubagentStop","PreToolUse","PermissionRequest","PostToolUse","PreCompact","PostCompact","UserPromptSubmit","Stop"]),H="opencode-hooks-plugin.js",N="opencode-hooks-plugin",x="opencode-platform-env-plugin.js",Y="hooks/platform-env.sh";function M(e,t=30){const n=Number(e);return Number.isFinite(n)&&n>0?n:t}function Z(e){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e))return e;if(typeof e=="string"){const t=e.trim();if(!t)return null;try{const n=JSON.parse(t);return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}catch{return null}}return null}function U(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t={};for(const[n,c]of Object.entries(e)){if(!Array.isArray(c))continue;const i=[];for(const s of c){if(!s||typeof s!="object")continue;const p=[],a=Array.isArray(s.hooks)?s.hooks:[];for(const f of a){const m=Z(f);m&&p.push(m)}p.length!==0&&i.push({...s,hooks:p})}i.length>0&&(t[n]=i)}return Object.keys(t).length>0?t:null}function q(e){return F(e).hooksMap}function F(e){if(e==null||!String(e).trim())return{attempted:!1,hooksMap:null,error:null};try{const t=JSON.parse(e);return{attempted:!0,hooksMap:U(t),error:null}}catch(t){return{attempted:!0,hooksMap:null,error:t instanceof Error?t.message:String(t)}}}function B(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function D(e){return String(e).replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,"${$1}")}const Q=/git rev-parse --show-toplevel/;function L(e){const t=e.trim();return!t||Q.test(t)||/[|;&`<>$()]/.test(t)||/^(bash|sh|zsh|dash|python3?|node|npm|npx|curl|wget|echo|env|cd|export|test|\[)\s+/i.test(t)?!1:!!(t.startsWith("/")||t.includes("/")||/\.(sh|bash|py|js|mjs|cjs|ts|pl|rb)$/i.test(t)||/^[\w.-]+\.sh$/i.test(t))}function G(e){const t=e.trim();if(!L(t))return t;if(t.startsWith("/"))return`bash "${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;const n=t.replace(/^\.\//,""),c=".nuwax-harness/hooks/";if(n.startsWith(c)){const s=n.slice(c.length);if(s&&!s.includes("/"))return E(s)}return/^[\w.-]+\.sh$/i.test(n)?E(n):`bash "$(git rev-parse --show-toplevel 2>/dev/null || pwd)/${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ee(e){if(!e||typeof e!="object")return['-H "Content-Type: application/json"'];const t=[],n=Object.entries(e);n.some(([i])=>i.toLowerCase()==="content-type")||t.push('-H "Content-Type: application/json"');for(const[i,s]of n){if(s==null)continue;const p=String(i).replace(/\\/g,"\\\\").replace(/"/g,'\\"'),a=D(s).replace(/\\/g,"\\\\").replace(/"/g,'\\"');t.push(`-H "${p}: ${a}"`)}return t}function W(e,t,n){return`#!/usr/bin/env bash
|
|
2
2
|
set -euo pipefail
|
|
3
3
|
curl -fsS -X POST ${ee(n).join(" ")} --data-binary @- --max-time ${t} ${B(e)}
|
|
4
|
-
`}function E(e){return`bash "$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.
|
|
5
|
-
`)}async function
|
|
6
|
-
`;return await
|
|
4
|
+
`}function E(e){return`bash "$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.nuwax-harness/hooks/${e}"`}async function v(e,t,n={}){const c=o.dirname(e);await r.promises.mkdir(c,{recursive:!0});const i=o.join(c,`.${o.basename(e)}.${process.pid}.${Date.now()}.tmp`);await r.promises.writeFile(i,t,"utf-8"),n.mode!=null&&await r.promises.chmod(i,n.mode),await r.promises.rename(i,e)}async function R(e,t){await v(e,`${JSON.stringify(t,null,2)}
|
|
5
|
+
`)}async function z(e,t,n){const c={};let i=0;for(const[s,p]of Object.entries(e)){if(!C.has(s)){l(n,"WARN","Skipping unsupported nuwax-harness hook event",{eventName:s});continue}const a=[];for(const f of p){if(!f||typeof f!="object")continue;const m=[],w=Array.isArray(f.hooks)?f.hooks:[];for(const u of w){if(!u||typeof u!="object")continue;const g=u.type;if(g==="command"&&typeof u.command=="string"&&u.command.trim()){m.push({...u,type:"command",command:G(u.command)});continue}if(g==="http"&&typeof u.url=="string"&&u.url.trim()){const y=M(u.timeout,30),h=`http-hook-${i++}.sh`,O=o.join(t,h),P=u.headers&&typeof u.headers=="object"&&!Array.isArray(u.headers)?u.headers:void 0;await r.promises.mkdir(t,{recursive:!0}),await v(O,W(u.url.trim(),y,P),{mode:493}),m.push({type:"command",command:E(h),timeout:y,...u.statusMessage?{statusMessage:u.statusMessage}:{}});continue}if(g==="prompt"||g==="agent"){l(n,"WARN","nuwax-harness skips non-command hook handler",{eventName:s,type:g});continue}l(n,"WARN","nuwax-harness skips unknown hook handler",{eventName:s,type:g})}m.length>0&&a.push({...f,hooks:m})}a.length>0&&(c[s]=a)}return Object.keys(c).length>0?c:null}async function J(e,t){const n=o.join(K,"dist");if(!r.existsSync(n))return l(t,"WARN","opencode-hooks-plugin assets missing, skipping OpenCode plugin install",{sourceDistDir:n}),!1;await r.promises.mkdir(e,{recursive:!0});const c=o.join(e,N,"dist");await r.promises.mkdir(c,{recursive:!0});const i=await r.promises.readdir(n);for(const a of i)a.endsWith(".js")&&await r.promises.copyFile(o.join(n,a),o.join(c,a));const s=o.join(e,H),p=`export { default } from "./${N}/dist/index.js";
|
|
6
|
+
`;return await v(s,p),l(t,"INFO","Installed opencode-hooks-plugin into .opencode/plugins",{entryFile:H}),!0}function I(e){return Array.isArray(e)?e.some(t=>t&&t.path===Y):!1}async function $(e,t){const n=o.join(X,"platform-env-plugin.js");return r.existsSync(n)?(await r.promises.mkdir(e,{recursive:!0}),await r.promises.copyFile(n,o.join(e,x)),l(t,"INFO","Installed opencode-platform-env-plugin into .opencode/plugins",{entryFile:x}),!0):(l(t,"WARN","opencode-platform-env-plugin assets missing, skipping install",{sourceFile:n}),!1)}async function te(e){if(!r.existsSync(e))return{settings:{},corrupt:!1};try{const t=await r.promises.readFile(e,"utf-8"),n=JSON.parse(t);return n&&typeof n=="object"&&!Array.isArray(n)?{settings:n,corrupt:!1}:{settings:{},corrupt:!0}}catch{return{settings:{},corrupt:!0}}}async function ne(e,t,n){if(!Array.isArray(t)||t.length===0)return;const c=o.join(e,"hooks");await r.promises.mkdir(c,{recursive:!0});for(const i of t){if(!i||!i.path||i.content==null)continue;const s=o.normalize(i.path);if(s.startsWith("..")||o.isAbsolute(s)){l(n,"WARN","Hook script path contains traversal, skipping",{path:i.path});continue}const p=o.join(e,s),a=o.dirname(p);await r.promises.mkdir(a,{recursive:!0}),await v(p,i.content,{mode:493}),l(n,"INFO","Written hook script",{path:i.path})}}async function _(e){const t=[o.join(e,".nuwax-harness","hooks.json"),o.join(e,".nuwax-harness","hooks"),o.join(e,".opencode","plugins",H),o.join(e,".opencode","plugins",N),o.join(e,".opencode","plugins",x),o.join(e,".claude","hooks")];for(const n of t)r.existsSync(n)&&await r.promises.rm(n,{recursive:!0,force:!0})}async function se(e){const t=[o.join(e,".mcp.json"),o.join(e,".claude","settings.json")];for(const n of t)r.existsSync(n)&&await r.promises.rm(n,{recursive:!0,force:!0});await _(e)}async function oe(e,t,n,c=!1){const i=o.join(e,".tmp",`hook-staging-${Date.now()}-${process.pid}`),s=o.join(i,"nuwax-harness"),p=o.join(s,"hooks"),a=o.join(i,"opencode","plugins");await r.promises.mkdir(p,{recursive:!0});const f=await z(t,p,n),m=await J(a,n),w=c?await $(a,n):!1;return{stagingRoot:i,nuwaxHarnessStagingRoot:s,nuwaxHarnessHooks:f,pluginInstalled:m,platformEnvPluginInstalled:w}}async function re(e,t,n){const c=o.join(e,".nuwax-harness"),i=o.join(c,"hooks"),s=o.join(e,".opencode","plugins");await _(e),await r.promises.mkdir(c,{recursive:!0});const p=o.join(t.nuwaxHarnessStagingRoot,"hooks");if(r.existsSync(p)&&await r.promises.rename(p,i),t.nuwaxHarnessHooks&&(await R(o.join(c,"hooks.json"),{hooks:t.nuwaxHarnessHooks}),l(n,"INFO","Written .nuwax-harness/hooks.json",{events:Object.keys(t.nuwaxHarnessHooks)})),t.pluginInstalled){await r.promises.mkdir(s,{recursive:!0});const a=o.join(t.stagingRoot,"opencode","plugins",H),f=o.join(t.stagingRoot,"opencode","plugins",N);r.existsSync(a)&&await r.promises.copyFile(a,o.join(s,H)),r.existsSync(f)&&await r.promises.cp(f,o.join(s,N),{recursive:!0,force:!0})}if(t.platformEnvPluginInstalled){await r.promises.mkdir(s,{recursive:!0});const a=o.join(t.stagingRoot,"opencode","plugins",x);r.existsSync(a)&&await r.promises.copyFile(a,o.join(s,x))}}async function ie(e,{mcpServersConfig:t,hooksConfig:n,permissionsConfig:c,hookScripts:i},s){const p=!!(t&&t.trim()),a=F(n),f=!!(c&&c.trim()),m=Array.isArray(i)&&i.length>0;a.attempted&&a.error&&l(s,"ERROR","Invalid hooksConfig, keeping existing hook configs",{error:a.error});let w=null,u=!1;if(p)try{w=JSON.parse(t),u=!0}catch(d){l(s,"WARN","Failed to parse mcpServersConfig, keeping existing .mcp.json",{error:d.message})}let g=null,y=!1;if(f)try{g=JSON.parse(c),y=!0}catch(d){l(s,"WARN","Failed to parse permissionsConfig, keeping existing permissions",{error:d.message})}const h=a.attempted&&!a.error,O=m,P=I(i);if(!u&&!h&&!y&&!O)return;const b=o.join(e,".claude"),j=o.join(b,"settings.json");let k=null;try{if(await r.promises.mkdir(b,{recursive:!0}),h&&a.hooksMap&&(k=await oe(e,a.hooksMap,s,P)),u&&(await R(o.join(e,".mcp.json"),{mcpServers:w}),l(s,"INFO","Written .mcp.json to workspace root")),h&&a.hooksMap&&k?await re(e,k,s):h&&!a.hooksMap&&await _(e),h||y){const{settings:d,corrupt:S}=await te(j);if(S&&!h)l(s,"WARN","Corrupt .claude/settings.json, skipping settings update",{settingsPath:j});else{y&&S&&l(s,"WARN","Corrupt .claude/settings.json, rewriting hooks without preserving old fields",{settingsPath:j});const A=S?{}:{...d};h&&(a.hooksMap?A.hooks=a.hooksMap:delete A.hooks),y&&!S&&(A.permissions=g),Object.keys(A).length>0?(await R(j,A),l(s,"INFO","Written .claude/settings.json",{keys:Object.keys(A)})):r.existsSync(j)&&await r.promises.rm(j,{force:!0})}}if(O){const d=o.join(b,"hooks");r.existsSync(d)&&await r.promises.rm(d,{recursive:!0,force:!0}),await ne(b,i,s);const S=o.join(e,".opencode","plugins");P&&await $(S,s)}}catch(d){l(s,"ERROR","Failed to write agent hook configs, keeping previous files when possible",{error:d.message})}finally{k?.stagingRoot&&r.existsSync(k.stagingRoot)&&await r.promises.rm(k.stagingRoot,{recursive:!0,force:!0})}}export{q as parseHooksConfigString,F as parseHooksConfigWithStatus,U as normalizeHooksMap,z as transformHooksForNuwaxHarness,W as buildHttpWrapperScript,E as buildNuwaxHarnessHookCommand,G as normalizeNuwaxHarnessCommand,L as isLikelyScriptPath,D as toBashEnvExpandable,M as parseTimeoutSeconds,v as writeFileAtomic,R as writeJsonFileAtomic,J as installOpencodeHooksPlugin,$ as installOpencodePlatformEnvPlugin,I as hasPlatformEnvScript,se as clearAgentHookConfigs,_ as clearHookArtifacts,ie as writeAgentHookConfigs,C as NUWAX_HARNESS_HOOK_EVENTS};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import p from"fs";import u from"path";import i from"../../appConfig/index.js";import{log as l}from"../log/logUtils.js";import{ValidationError as n}from"../error/errorHandler.js";export const WORKSPACE_TYPE={USERAPP:"userApp",PAGEAPP:"pageApp",NORMAL_PROJECT:"normalProject",TASK_AGENT:"taskAgent"};export function resolveServiceContext(r){const t=r.headers&&typeof r.headers["x-workspace-type"]=="string"?r.headers["x-workspace-type"].trim():"",e=(r.body?.workspaceType??r.query?.workspaceType??"").toString().trim(),s=m=>{const A=m.toLowerCase();return Object.values(WORKSPACE_TYPE).find(k=>k.toLowerCase()===A)||""},a=s(t),c=s(e);if(!a&&!c&&(t||e))throw new n("workspaceType must be one of userApp, pageApp, normalProject, taskAgent",{field:"workspaceType"});const o=a||c||WORKSPACE_TYPE.TASK_AGENT,f=typeof r.headers?.["x-app-id"]=="string"&&r.headers["x-app-id"].trim()||(r.body?.appId??r.query?.appId??"").toString().trim()||null||null,w=o===WORKSPACE_TYPE.USERAPP,d=o===WORKSPACE_TYPE.NORMAL_PROJECT;if(w&&!f)throw new n("appId is required for userapp workspace",{field:"appId"});if(d&&!f)throw new n("appId(projectId) is required for normalProject workspace",{field:"appId"});if(w&&!S(f))throw new n("appId contains illegal path segments",{field:"appId"});const P=typeof r.headers?.["x-workspace-path"]=="string"&&r.headers["x-workspace-path"].trim()||(r.body?.workspacePath??r.query?.workspacePath??"").toString().trim()||null,R=P?E(P):null;return{workspaceType:o,appId:f,workspacePath:R,isUserApp:w,isNormalProject:d}}function S(r){return!!r&&!/[\/\\\0]/.test(r)&&r!=="."&&r!==".."}function E(r){let t=String(r).trim();if(t.length>512)throw new n("workspacePath length exceeds 512",{field:"workspacePath"});if(/[\0\x00-\x1f\x7f]/.test(t))throw new n("workspacePath contains illegal characters",{field:"workspacePath"});if(t=_(t),!t.startsWith("/")&&!/^[A-Za-z]:\/.*/.test(t))throw new n("workspacePath must be an absolute path (POSIX /a/b, Windows C:/a/b or UNC //server/share/a/b)",{field:"workspacePath"});if(t.split("/").some(e=>e==="."||e===".."))throw new n("workspacePath must not contain dot segments",{field:"workspacePath"});return t}function _(r){const t=r.startsWith("//")||r.startsWith("\\\\");let e=r.replace(/\\/g,"/").replace(/\/{2,}/g,"/");return t&&(e="/"+e),/^[a-z]:\//.test(e)&&(e=e.charAt(0).toUpperCase()+e.slice(1)),e}function h(r,t){if(!r)throw new n(`${t} configuration does not exist`,{field:t});return r}export function resolveWorkspaceRoot(r){return r?.isUserApp?h(i.USERAPP_WORKSPACE_DIR,"USERAPP_WORKSPACE_DIR"):i.COMPUTER_WORKSPACE_DIR}export function isSingleUserVolume(){return!!i.RCODER_AGENT_BOUND_USER_ID}export function computerUserRoot(r){const t=i.RCODER_AGENT_BOUND_USER_ID;if(t){if(String(r)!==t)throw new n(`userId '${r}' does not match the volume owner`,{field:"userId"});return i.COMPUTER_WORKSPACE_DIR}return u.join(i.COMPUTER_WORKSPACE_DIR,String(r))}export function resolveWorkspaceDir(r,t,e){if(r?.workspacePath)return r.workspacePath;if(r?.isUserApp)return u.join(resolveWorkspaceRoot(r),String(r.appId));const s=computerUserRoot(t);return r?.isNormalProject?u.join(s,"normalProject",String(r.appId)):u.join(s,String(e))}export async function ensureWorkspaceDir(r,t,e,s="computer"){if(r?.workspacePath){const o=r.workspacePath;return p.existsSync(o)||(await p.promises.mkdir(o,{recursive:!0}),l(s,"INFO","Created bound workspace directory",{boundDir:o})),o}const a=resolveWorkspaceRoot(r);if(!a)throw new n("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});if(p.existsSync(a)||(await p.promises.mkdir(a,{recursive:!0}),l(s,"INFO","Created user workspace root directory",{workspaceRoot:a})),r?.isUserApp){const o=u.join(a,String(r.appId));if(!p.existsSync(o))throw new n(`userapp workspace mount does not exist: ${o}`,{field:"USERAPP_WORKSPACE_DIR"});return o}const c=resolveWorkspaceDir(r,t,e);return p.existsSync(c)||await p.promises.mkdir(c,{recursive:!0}),c}export function resolveLogDir(r,t,e){return r?.isUserApp?h(i.USERAPP_LOG_DIR,"USERAPP_LOG_DIR"):i.COMPUTER_WORKSPACE_DIR?u.join(resolveWorkspaceDir(r,t,e),".logs"):null}
|
package/package.json
CHANGED