nuwax-file-server 1.6.4 → 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/routes/computerRoutes.js +1 -1
- package/dist/utils/common/agentStoreUtils.js +2 -2
- package/dist/utils/computer/computerUtils.js +7 -7
- 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.4",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();
|
|
@@ -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,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,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",".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 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 +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