nuwax-file-server 1.4.1 → 1.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.4.1",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
|
|
2
|
+
import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.4.2",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import l from"fs";import i from"path";import{log as y}from"../log/logUtils.js";const d={agents:".agents",claudecode:".claude",opencode:".opencode",codex:".codex"},m=Object.keys(d),g="agents",k=
|
|
1
|
+
import l from"fs";import i from"path";import{log as y}from"../log/logUtils.js";const d={agents:".agents",claudecode:".claude",opencode:".opencode",codex:".codex"},m=Object.keys(d),g="agents",k=8;function N(t){let e=0;const n=[];return{async acquire(){if(e<t){e+=1;return}await new Promise(s=>{n.push(s)})},release(){const s=n.shift();if(s){s();return}e=Math.max(0,e-1)}}}const j=N(k);async function f(t){try{await l.promises.lstat(t)}catch{return}await l.promises.rm(t,{recursive:!0,force:!0})}async function c(t){l.existsSync(t)||await l.promises.mkdir(t,{recursive:!0})}async function E(t,e){await j.acquire();let n=!1;try{if((await l.promises.lstat(t)).isDirectory()){await c(e);const r=await l.promises.readdir(t);j.release(),n=!0,await Promise.all(r.map(a=>E(i.join(t,a),i.join(e,a))));return}await c(i.dirname(e)),await l.promises.copyFile(t,e)}finally{n||j.release()}}async function w(t,e){if(!l.existsSync(t))return;await c(e);const n=await l.promises.readdir(t,{withFileTypes:!0});await Promise.all(n.map(s=>E(i.join(t,s.name),i.join(e,s.name))))}async function T(t){const e=i.join(t,d[g]),n=i.join(e,"skills"),s=i.join(e,"agents");return await c(e),await c(n),await c(s),{rootDir:e,skillsDir:n,agentsDir:s,agentTypes:m}}async function A(t,e,n){await c(i.dirname(t)),await c(e),await f(t);const s=i.resolve(e);if(process.platform==="win32")try{await l.promises.symlink(s,t,"junction"),y(n||"symlink","DEBUG","Created dir junction (windows)",{linkPath:t,targetPath:s,type:"junction"});return}catch(o){y(n||"symlink","WARN","Windows junction failed, try dir symlink",{linkPath:t,targetPath:s,error:o.message}),await f(t),await l.promises.symlink(s,t,"dir"),y(n||"symlink","DEBUG","Created dir symlink (windows)",{linkPath:t,targetPath:s,type:"dir"});return}let a=i.relative(i.dirname(t),s);if(a=a.split(i.sep).join("/"),!a||i.isAbsolute(a))throw new Error(`Cannot create relative symlink from ${t} to ${e} (got: ${a||"<empty>"})`);await l.promises.symlink(a,t),y(n||"symlink","DEBUG","Created dir symlink",{linkPath:t,targetPath:s,relativeTarget:a,type:"symlink"})}async function D(t,e,n,s){const r=s||"materialize-copy";for(const p of m){const u=i.join(t,d[p]);await f(i.join(u,"skills")),await f(i.join(u,"agents"))}const a=await T(t);await f(a.skillsDir),await f(a.agentsDir),await c(a.skillsDir),await c(a.agentsDir),await w(e,a.skillsDir),await w(n,a.agentsDir);const o=await S(t,r);return y(r,"INFO","Materialized agent store by copy (legacy mode)",{workspaceRoot:t,agentSkillsDir:e,agentAgentsDir:n,syncElapsedMs:o?.elapsedMs}),o}async function M(t,e,n,s){const r=Date.now(),a=s||i.basename(t)||"linkWorkspace";y(a,"INFO","Start linkWorkspaceToAgentStore",{workspaceRoot:t,agentSkillsDir:e,agentAgentsDir:n,platform:process.platform});try{for(const p of m){const u=i.join(t,d[p]);await c(u),await A(i.join(u,"skills"),e,a),await A(i.join(u,"agents"),n,a)}const o=Date.now()-r;return y(a,"INFO","linkWorkspaceToAgentStore completed",{workspaceRoot:t,agentTypes:m,mode:"symlink",elapsedMs:o}),{agentTypes:m,elapsedMs:o,mode:"symlink"}}catch(o){y(a,"WARN","Link to agent store failed, fallback to copy mode",{workspaceRoot:t,platform:process.platform,error:o.message});const p=await D(t,e,n,a),u=Date.now()-r;return y(a,"INFO","linkWorkspaceToAgentStore completed (copy fallback)",{workspaceRoot:t,agentTypes:m,mode:"copy-fallback",elapsedMs:u,syncElapsedMs:p?.elapsedMs}),{agentTypes:m,elapsedMs:u,mode:"copy-fallback",syncElapsedMs:p?.elapsedMs}}}async function C(t,e,n,s){const r=i.join(t,d[e]),a=i.join(r,"skills"),o=i.join(r,"agents");await c(r),await f(a),await f(o),await c(a),await c(o),await Promise.all([w(n.skillsDir,a),w(n.agentsDir,o)]),y(s,"DEBUG","syncAgents target completed",{agentType:e,targetRoot:r})}async function S(t,e){const n=Date.now(),s=e||i.basename(t)||"syncAgents",r=m.filter(p=>p!==g);y(s,"INFO","Start syncAgents",{workspaceRoot:t,targetAgentTypes:r,concurrency:k});const a=await T(t);await Promise.all(r.map(p=>C(t,p,a,s)));const o=Date.now()-n;return y(s,"INFO","syncAgents completed",{workspaceRoot:t,agentTypes:m,elapsedMs:o}),{agentTypes:m,elapsedMs:o}}function O(t){if(!t)return!1;const e=i.join(t,d[g],"skills");try{return l.lstatSync(e).isSymbolicLink()}catch{return!1}}export{d as AGENT_ROOT_MAP,m as ALL_AGENT_TYPES,T as ensurePrimaryAgentDirs,S as syncAgents,M as linkWorkspaceToAgentStore,A as forceDirSymlink,O as isWorkspaceSkillsSymlinked};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import n from"fs";import o from"path";import{exec as Pe}from"child_process";import je from"cross-spawn";import Ee from"archiver";import X from"../../appConfig/index.js";import{extractZip as J}from"../common/zipUtils.js";import{ValidationError as m,SystemError as U,FileError as Q}from"../error/errorHandler.js";import{log as r}from"../log/logUtils.js";import{createPnpmNpmrc as Fe}from"../common/npmrcUtils.js";import{ensurePrimaryAgentDirs as fe,syncAgents as ce,linkWorkspaceToAgentStore as we,isWorkspaceSkillsSymlinked as Ae}from"../common/AgentWorkspaceUtils.js";import{ensureAgentStoreDirs as he,tryAcquireAgentStoreLock as pe,releaseAgentStoreLock as ge,pruneAgentSkills as Oe,installSkillDir as te,replaceAgentsDir as $e,agentSkillExists as ze}from"../common/agentStoreUtils.js";import{writeAgentHookConfigs as ke}from"./hookConfigUtils.js";function se(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>typeof t=="string"?t.trim():t&&typeof t=="object"&&typeof t.url=="string"?t.url.trim():"").filter(Boolean);if(typeof e=="object")return Object.values(e).map(t=>typeof t=="string"?t.trim():"").filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);return se(i)}catch{}return[t]}return[]}function ye(e){if(!e)return[];if(Array.isArray(e)){const t=[];for(const i of e)if(typeof i=="string"&&i.trim())t.push({name:null,url:i.trim()});else if(i&&typeof i=="object"){const a=typeof i.url=="string"?i.url.trim():"",s=i.name!=null?String(i.name).trim():"";a&&t.push({name:s||null,url:a})}return t}if(typeof e=="object")return Object.entries(e).map(([t,i])=>({name:String(t||"").trim()||null,url:typeof i=="string"?i.trim():""})).filter(t=>t.url);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{return ye(JSON.parse(t))}catch{return[{name:null,url:t}]}}return[]}function ve(e){if(!e)return{};let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return{}}if(!t||typeof t!="object"||Array.isArray(t))return{};const i={};for(const[a,s]of Object.entries(t)){const l=String(a||"").trim(),c=typeof s=="string"?s.trim():"";l&&c&&(i[l]=c)}return i}function Se(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>String(t||"").trim()).filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);if(Array.isArray(i))return i.map(a=>String(a||"").trim()).filter(Boolean)}catch{}return t.split(",").map(i=>i.trim()).filter(Boolean)}return[]}async function ae(e,t,i){let a;try{a=await fetch(e)}catch(d){throw new Q(`Failed to download skill zip from url: ${e}`,{url:e,reason:d.message})}if(!a.ok)throw new Q(`Failed to download skill zip from url: ${e}`,{url:e,status:a.status,statusText:a.statusText});const s=a.headers.get("content-type")||"";s&&!s.includes("zip")&&!s.includes("octet-stream")&&r(i,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:s});const l=await a.arrayBuffer(),c=Buffer.from(l);await n.promises.writeFile(t,c)}async function q(e="computer"){const t=X.COMPUTER_WORKSPACE_DIR;if(!t)throw new m("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return n.existsSync(t)||(await n.promises.mkdir(t,{recursive:!0}),r(e,"INFO","Created user workspace root directory",{workspaceRoot:t})),t}async function I(e,t){const i=o.join(e,t);if(n.existsSync(i)&&(await n.promises.lstat(i)).isDirectory())return i;const a=await n.promises.readdir(e,{withFileTypes:!0});for(const s of a){if(!s.isDirectory())continue;const l=o.join(e,s.name),c=o.join(l,t);if(n.existsSync(c)&&(await n.promises.lstat(c)).isDirectory())return c}return null}async function mt(e){return I(e,"skills")}const Me=".dynamic_add.lock";function We(e){const t=o.join(e,Me);return n.existsSync(t)&&n.statSync(t).isFile()}async function H(e){n.existsSync(e)&&await n.promises.rm(e,{recursive:!0,force:!0})}async function V(e,t){try{await n.promises.rename(e,t)}catch(i){if(i.code==="EXDEV"){async function a(s,l){if((await n.promises.lstat(s)).isDirectory()){await n.promises.mkdir(l,{recursive:!0});const d=await n.promises.readdir(s);for(const p of d)await a(o.join(s,p),o.join(l,p))}else await n.promises.copyFile(s,l)}await a(e,t),await n.promises.rm(e,{recursive:!0,force:!0})}else throw i}}async function de(e){const i=(await n.promises.readdir(e,{withFileTypes:!0})).filter(s=>s.isDirectory()&&!s.name.startsWith("."));return i.find(s=>s.name==="skills")?(await n.promises.readdir(o.join(e,"skills"),{withFileTypes:!0})).filter(l=>l.isDirectory()&&!l.name.startsWith(".")).map(l=>({name:l.name,sourcePath:o.join(e,"skills",l.name)})):i.map(s=>({name:s.name,sourcePath:o.join(e,s.name)}))}const ie=16;async function ne(e,t,i){if(!e||e.length===0)return;const a=Math.max(1,Math.min(t,e.length));let s=0;await Promise.all(Array.from({length:a},async()=>{for(;;){const l=s++;if(l>=e.length)return;await i(e[l],l)}}))}async function be(e){const{userId:t,cId:i,agentId:a,file:s,skillUrls:l,skillUrlMap:c,skillNames:d,updateSkillNames:p,mcpServersConfig:D,permissionsConfig:x,hooksConfig:f,hookScripts:g}=e,u=Date.now(),h=`computer:${t}:${i}`,W=ve(c),_=ye(l),A=Se(d),k=p!=null,z=new Set(Se(p)),b=[],y=[],R=new Set,O=new Set;let E=null,v=!1;if(!t)throw new m("userId cannot be empty",{field:"userId"});if(!i)throw new m("cId cannot be empty",{field:"cId"});if(!a)throw new m("agentId cannot be empty",{field:"agentId"});const C=await q(h),S=o.join(C,String(t),String(i)),j=o.join(S,".tmp");await n.promises.mkdir(S,{recursive:!0}),await n.promises.mkdir(j,{recursive:!0});const{agentStorePath:N,skillsDir:T,agentsDir:ee}=await he(t,a,h),M=F=>!F||!k||z.has(F)?!0:!ze(T,F),G=async(F,P,B)=>{const K=o.join(j,`skill_url_${Date.now()}_${B}_${Math.round(Math.random()*1e6)}.zip`);b.push(K);const Z=o.join(j,`skill_url_extract_${Date.now()}_${B}_${Math.round(Math.random()*1e6)}`);y.push(Z),await n.promises.mkdir(Z,{recursive:!0}),r(h,"INFO","Start download skill zip from url",{userId:t,cId:i,agentId:a,skillName:P,skillUrl:F}),await ae(F,K,h),await J(K,Z);const L=await de(Z);if(L.length===0){r(h,"WARN","No skill dir found in downloaded zip",{skillUrl:F,destName:P});return}let w=P?L.find($=>$.name===P):null;if(!w&&L.length===1&&(w=L[0]),P&&w){if(!M(P)){O.add(P);return}await te(w.sourcePath,T,P,{asDynamic:!1}),R.add(P),r(h,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:F,skillName:P,zipDirName:w.name});return}for(const $ of L){if(!M($.name)){O.add($.name);continue}await te($.sourcePath,T,$.name,{asDynamic:!1}),R.add($.name),r(h,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:F,skillName:$.name})}};await ke(S,{mcpServersConfig:D,hooksConfig:f,permissionsConfig:x,hookScripts:g},h);try{const F=await pe(N,h);if(!F.acquired)v=!0;else{E=F.lockPath;const B=Date.now();let K=null;if(s){if(!s.path)throw new m("Uploaded file has no valid path",{field:"file.path"});if(o.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:s.originalname});const w=o.join(j,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);y.push(w),await n.promises.mkdir(w,{recursive:!0}),await J(s.path,w);const $=await I(w,"skills");if($){const le=(await n.promises.readdir($,{withFileTypes:!0})).filter(Y=>Y.isDirectory());await ne(le,ie,async Y=>{if(!M(Y.name)){O.add(Y.name);return}await te(o.join($,Y.name),T,Y.name,{asDynamic:!1}),R.add(Y.name)})}K=await I(w,"agents")}const Z=Object.entries(W);if(Z.length>0){const L=[];for(const[w,$]of Z){if(!M(w)){O.add(w),r(h,"INFO","Skip download skill zip (already in agent store)",{userId:t,cId:i,agentId:a,skillName:w,skillUrl:$});continue}L.push({skillName:w,skillUrl:$})}await ne(L,ie,async(w,$)=>{await G(w.skillUrl,w.skillName,$)})}else{const L=[];for(let w=0;w<_.length;w++){const{name:$,url:le}=_[w];if($&&!M($)){O.add($);continue}L.push({skillUrl:le,hintedName:$,index:w})}await ne(L,ie,async w=>{await G(w.skillUrl,w.hintedName,w.index)})}await $e(K,ee),await Oe(T,A,h),r(h,"INFO","Agent store resources prepared",{userId:t,cId:i,agentId:a,selectiveInstall:k,updatedSkills:Array.from(R),skippedSkills:Array.from(O),updateSkillNames:Array.from(z),keepSkillNames:A,skillUrlMapCount:Z.length,prepareElapsedMs:Date.now()-B})}const P=await we(S,T,ee,h);return r(h,"INFO","Workspace created successfully (agent store)",{userId:t,cId:i,agentId:a,agentStorePath:N,updatedSkills:Array.from(R),skippedSkills:Array.from(O),skippedStoreUpdate:v,linkElapsedMs:P?.elapsedMs,elapsedMs:Date.now()-u}),{message:v?"Workspace linked to agent store (store update skipped, lock held)":"Workspace created successfully, linked to agent store",workspaceRoot:C,agentStorePath:N,updatedSkills:Array.from(R),skippedSkills:Array.from(O),skippedStoreUpdate:v}}catch(F){throw r(h,"ERROR","Failed to create workspace with agent store",{userId:t,cId:i,agentId:a,error:F.message,elapsedMs:Date.now()-u}),F instanceof m||F instanceof Q||F instanceof U?F:new U(`Failed to create workspace: ${F.message}`,{userId:t,cId:i,agentId:a})}finally{await ge(E,h);const F=Date.now();for(const P of y)try{n.existsSync(P)&&await n.promises.rm(P,{recursive:!0,force:!0})}catch(B){r(h,"WARN","Failed to clean up temporary extracted zip",{error:B.message})}for(const P of b)try{n.existsSync(P)&&await n.promises.unlink(P)}catch(B){r(h,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:P,error:B.message})}try{s&&s.path&&n.existsSync(s.path)&&await n.promises.unlink(s.path)}catch(P){r(h,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:P.message})}r(h,"INFO","Workspace temp cleanup completed",{userId:t,cId:i,agentId:a,elapsedMs:Date.now()-F,totalElapsedMs:Date.now()-u})}}async function Ce(e,t,i,a,s,l,c,d,p,D,x,f){if(p!=null&&String(p).trim()!=="")return be({userId:e,cId:t,agentId:p,file:i,skillUrls:a,skillUrlMap:f,skillNames:D,updateSkillNames:x,mcpServersConfig:s,permissionsConfig:l,hooksConfig:c,hookScripts:d});const g=Date.now(),u=`computer:${e}:${t}`,h=se(a),W=[],_=[],A=new Set;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});const k=await q(u),z=o.join(k,String(e),String(t),".tmp"),b=o.join(k,String(e),String(t)),{skillsDir:y,agentsDir:R,agentTypes:O}=await fe(b);n.existsSync(b)||await n.promises.mkdir(b,{recursive:!0});const E=o.join(z,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(n.existsSync(y)){const j=(await n.promises.readdir(y,{withFileTypes:!0})).filter(N=>N.isDirectory()&&We(o.join(y,N.name)));if(j.length>0){await n.promises.mkdir(E,{recursive:!0});for(const N of j){const T=o.join(y,N.name),ee=o.join(E,N.name);await V(T,ee)}r(u,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:j.map(N=>N.name)})}}if(await H(y),await H(R),await n.promises.mkdir(y,{recursive:!0}),await n.promises.mkdir(R,{recursive:!0}),n.existsSync(E)){const S=await n.promises.readdir(E,{withFileTypes:!0});for(const j of S)if(j.isDirectory()){const N=o.join(E,j.name),T=o.join(y,j.name);await V(N,T)}await H(E)}const v=n.existsSync(y),C=n.existsSync(R);if(r(u,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:y,targetAgentsDir:R,agentTypes:O,skillsExists:v,agentsExists:C}),await ke(b,{mcpServersConfig:s,hooksConfig:c,permissionsConfig:l,hookScripts:d},u),!i&&h.length===0){const S=await ce(b,u);return r(u,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:k,skillsDir:null,agentsDir:null,agentTypes:O,syncAgentsElapsedMs:S?.elapsedMs,elapsedMs:Date.now()-g}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:k}}if(i){if(!i.path)throw new m("Uploaded file has no valid path",{field:"file.path"});if(o.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:i.originalname})}r(u,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:k,hasUploadedZip:!!i,skillUrlsCount:h.length});try{n.existsSync(z)||await n.promises.mkdir(z,{recursive:!0});const S=[];if(i){const M=o.join(z,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);_.push(M),await n.promises.mkdir(M,{recursive:!0}),r(u,"DEBUG","Start extracting uploaded zip file",{extractRoot:M}),await J(i.path,M),r(u,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:M});const G=await I(M,"skills"),F=await I(M,"agents");if(G){await n.promises.mkdir(y,{recursive:!0});const P=await n.promises.readdir(G,{withFileTypes:!0});for(const B of P){if(!B.isDirectory())continue;const K=o.join(G,B.name),Z=o.join(y,B.name);n.existsSync(Z)&&await H(Z),await V(K,Z),A.add(B.name)}S.push("skills"),r(u,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetSkillsDir:y,agentTypes:O})}else r(u,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:M});F?(await H(R),await V(F,R),S.push("agents"),r(u,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetAgentsDir:R,agentTypes:O})):r(u,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:M})}for(let M=0;M<h.length;M+=1){const G=h[M],F=o.join(z,`skill_url_${Date.now()}_${M}_${Math.round(Math.random()*1e6)}.zip`);W.push(F);const P=o.join(z,`skill_url_extract_${Date.now()}_${M}_${Math.round(Math.random()*1e6)}`);_.push(P),await n.promises.mkdir(P,{recursive:!0}),r(u,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:G}),await ae(G,F,u),r(u,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:G,downloadedZipPath:F}),await J(F,P);const K=(await n.promises.readdir(P,{withFileTypes:!0})).filter(w=>w.isDirectory()&&!w.name.startsWith(".")),L=K.find(w=>w.name==="skills")?(await n.promises.readdir(o.join(P,"skills"),{withFileTypes:!0})).filter(w=>w.isDirectory()&&!w.name.startsWith(".")).map(w=>({name:w.name,sourcePath:o.join(P,"skills",w.name)})):K.map(w=>({name:w.name,sourcePath:o.join(P,w.name)}));if(L.length===0){r(u,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:G,extractRoot:P});continue}await n.promises.mkdir(y,{recursive:!0});for(const w of L){const $=o.join(y,w.name);n.existsSync($)&&await H($),await V(w.sourcePath,$),A.add(w.name),r(u,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:G,skillName:w.name,destSkillPath:$})}S.includes("skills")||S.push("skills")}S.length===0&&r(u,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!i,skillUrlsCount:h.length});const j=Array.from(A),N=S.length>0?`Workspace created successfully, ${S.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)",T=Date.now()-g;r(u,"INFO","Workspace resources prepared",{userId:e,cId:t,updatedDirs:S,updatedSkills:j,agentTypes:O,prepareElapsedMs:T});const ee=await ce(b,u);return r(u,"INFO",N,{userId:e,cId:t,updatedDirs:S,updatedSkills:j,agentTypes:O,prepareElapsedMs:T,syncAgentsElapsedMs:ee?.elapsedMs,elapsedMs:Date.now()-g}),{message:N,workspaceRoot:k,updatedSkills:j}}catch(S){throw r(u,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:S.message,elapsedMs:Date.now()-g}),S instanceof m||S instanceof Q||S instanceof U?S:new U(`Failed to create workspace: ${S.message}`,{userId:e,cId:t})}finally{const S=Date.now();try{for(const j of _)n.existsSync(j)&&await n.promises.rm(j,{recursive:!0,force:!0})}catch(j){r(u,"WARN","Failed to clean up temporary extracted zip",{error:j.message})}for(const j of W)try{n.existsSync(j)&&await n.promises.unlink(j)}catch(N){r(u,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:j,error:N.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(j){r(u,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:j.message})}r(u,"INFO","Workspace temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-S,totalElapsedMs:Date.now()-g})}}async function Te(e,t,i,a,s){const l=Date.now(),c=`computer:${e}:${t}`,d=se(s),p=[],D=[],x=new Set;let f=null;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i)throw new m("agentId cannot be empty",{field:"agentId"});if(!a&&d.length===0)throw new m("file or skillUrls cannot both be empty",{field:"file|skillUrls"});const g=await q(c),u=o.join(g,String(e),String(t)),h=o.join(u,".tmp");await n.promises.mkdir(u,{recursive:!0}),await n.promises.mkdir(h,{recursive:!0});const{agentStorePath:W,skillsDir:_,agentsDir:A}=await he(e,i,c);try{let k=await pe(W,c);if(!k.acquired)for(let R=1;R<=5&&!k.acquired;R++)await new Promise(O=>setTimeout(O,200*R)),k=await pe(W,c);if(!k.acquired)throw new U("Agent store is busy, please retry",{userId:e,cId:t,agentId:i});if(f=k.lockPath,a){if(!a.path)throw new m("Uploaded file has no valid path",{field:"file.path"});const R=o.join(h,`push_skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);D.push(R),await n.promises.mkdir(R,{recursive:!0}),await J(a.path,R);const O=await de(R),E=await I(R,"skills"),v=E?(await n.promises.readdir(E,{withFileTypes:!0})).filter(C=>C.isDirectory()).map(C=>({name:C.name,sourcePath:o.join(E,C.name)})):O;await ne(v,ie,async C=>{await te(C.sourcePath,_,C.name,{asDynamic:!0}),x.add(C.name)})}await ne(d,ie,async(R,O)=>{const E=o.join(h,`push_skill_url_${Date.now()}_${O}_${Math.round(Math.random()*1e6)}.zip`);p.push(E);const v=o.join(h,`push_skill_url_extract_${Date.now()}_${O}_${Math.round(Math.random()*1e6)}`);D.push(v),await n.promises.mkdir(v,{recursive:!0}),await ae(R,E,c),await J(E,v);const C=await de(v);for(const S of C)await te(S.sourcePath,_,S.name,{asDynamic:!0}),x.add(S.name)});const z=await we(u,_,A,c),b=Array.from(x),y=b.length>0?`Pushed ${b.length} skills to agent store: ${b.join(", ")}`:"No valid skill directories found in file or skillUrls";return r(c,"INFO",y,{userId:e,cId:t,agentId:i,updatedSkills:b,linkElapsedMs:z?.elapsedMs,elapsedMs:Date.now()-l}),{message:y,workspaceRoot:g,agentStorePath:W,updatedSkills:b}}catch(k){throw r(c,"ERROR","Failed to push skills to agent store",{userId:e,cId:t,agentId:i,error:k.message,elapsedMs:Date.now()-l}),k instanceof m||k instanceof Q||k instanceof U?k:new U(`Failed to push skill to workspace: ${k.message}`,{userId:e,cId:t,agentId:i})}finally{await ge(f,c);for(const k of D)try{n.existsSync(k)&&await n.promises.rm(k,{recursive:!0,force:!0})}catch(z){r(c,"WARN","Failed to clean up temporary extracted zip",{error:z.message})}for(const k of p)try{n.existsSync(k)&&await n.promises.unlink(k)}catch(z){r(c,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:k,error:z.message})}try{a&&a.path&&n.existsSync(a.path)&&await n.promises.unlink(a.path)}catch(k){r(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:a?.path,error:k.message})}}}async function Le(e,t,i,a,s){if(s!=null&&String(s).trim()!==""){const _=X.COMPUTER_WORKSPACE_DIR,A=_?o.join(_,String(e),String(t)):null;if(Ae(A))return Te(e,t,s,i,a);r(`computer:${e}:${t}`,"INFO","Push skills: agentId present but workspace not symlinked, use legacy path",{userId:e,cId:t,agentId:s,userWorkspaceRoot:A})}const c=Date.now(),d=`computer:${e}:${t}`,p=se(a),D=[],x=[];if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i&&p.length===0)throw new m("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(i){if(!i.path)throw new m("Uploaded file has no valid path",{field:"file.path"});if(o.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:i?.originalname})}const f=await q(d),g=o.join(f,String(e),String(t),".tmp"),u=o.join(f,String(e),String(t)),{skillsDir:h,agentTypes:W}=await fe(u);try{n.existsSync(u)||await n.promises.mkdir(u,{recursive:!0}),n.existsSync(h)||await n.promises.mkdir(h,{recursive:!0}),n.existsSync(g)||await n.promises.mkdir(g,{recursive:!0});const _=[],A=new Set;if(i){const y=o.join(g,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);x.push(y),await n.promises.mkdir(y,{recursive:!0}),r(d,"DEBUG","Start extracting skill zip file",{extractRoot:y}),await J(i.path,y),r(d,"DEBUG","Skill zip file extracted successfully",{extractRoot:y});const R=await I(y,"skills");if(!R)r(d,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:y});else{const E=(await n.promises.readdir(R,{withFileTypes:!0})).filter(v=>v.isDirectory()&&!v.name.startsWith("."));if(E.length===0)r(d,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:R});else for(const v of E){const C=o.join(R,v.name),S=o.join(h,v.name);n.existsSync(S)&&await H(S),await V(C,S),A.add(v.name),r(d,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:v.name,destSkillPath:S})}}}for(let y=0;y<p.length;y+=1){const R=p[y],O=o.join(g,`skill_push_url_${Date.now()}_${y}_${Math.round(Math.random()*1e6)}.zip`);D.push(O);const E=o.join(g,`skill_push_url_extract_${Date.now()}_${y}_${Math.round(Math.random()*1e6)}`);x.push(E),await n.promises.mkdir(E,{recursive:!0}),r(d,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:R}),await ae(R,O,d),await J(O,E);const C=(await n.promises.readdir(E,{withFileTypes:!0})).filter(N=>N.isDirectory()&&!N.name.startsWith(".")),j=C.find(N=>N.name==="skills")?(await n.promises.readdir(o.join(E,"skills"),{withFileTypes:!0})).filter(N=>N.isDirectory()&&!N.name.startsWith(".")).map(N=>({name:N.name,sourcePath:o.join(E,"skills",N.name)})):C.map(N=>({name:N.name,sourcePath:o.join(E,N.name)}));if(j.length===0){r(d,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:R,extractRoot:E});continue}for(const N of j){const T=o.join(h,N.name);n.existsSync(T)&&await H(T),await V(N.sourcePath,T),A.add(N.name),r(d,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:R,skillName:N.name,destSkillPath:T})}}for(const y of A)_.push(y);const k=_.length>0?`Pushed ${_.length} skills: ${_.join(", ")}`:"No valid skill directories found in file or skillUrls",z=Date.now()-c;r(d,"INFO","Push skills resources prepared",{userId:e,cId:t,updatedSkills:_,agentTypes:W,prepareElapsedMs:z});const b=await ce(u,d);return r(d,"INFO",k,{userId:e,cId:t,updatedSkills:_,agentTypes:W,prepareElapsedMs:z,syncAgentsElapsedMs:b?.elapsedMs,elapsedMs:Date.now()-c}),{message:k,workspaceRoot:f,updatedSkills:_}}catch(_){throw r(d,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:_.message,elapsedMs:Date.now()-c}),_ instanceof m||_ instanceof Q||_ instanceof U?_:new U(`Failed to push skill to workspace: ${_.message}`,{userId:e,cId:t})}finally{const _=Date.now();try{for(const A of x)n.existsSync(A)&&await n.promises.rm(A,{recursive:!0,force:!0})}catch(A){r(d,"WARN","Failed to clean up temporary extracted zip",{error:A.message})}for(const A of D)try{n.existsSync(A)&&await n.promises.unlink(A)}catch(k){r(d,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:A,error:k.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(A){r(d,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:A.message})}r(d,"INFO","Push skills temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-_,totalElapsedMs:Date.now()-c})}}async function Be(e,t,i,a){const s=Date.now(),l=`computer:${e}:${t}`;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i||!i.path)throw new m("file is required",{field:"file"});if(o.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:i.originalname});const d=await q(l),p=o.join(d,String(e),String(t)),D=o.join(p,".tmp"),x=o.join(D,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{n.existsSync(p)||await n.promises.mkdir(p,{recursive:!0}),n.existsSync(D)||await n.promises.mkdir(D,{recursive:!0}),await n.promises.mkdir(x,{recursive:!0}),r(l,"DEBUG","Start extracting template zip file",{extractRoot:x}),await J(i.path,x),r(l,"DEBUG","Template zip file extracted successfully",{extractRoot:x});const f=await n.promises.readdir(x,{withFileTypes:!0});for(const g of f){const u=o.join(x,g.name),h=o.join(p,g.name);if(g.isDirectory())await V(u,h);else{const W=o.dirname(h);n.existsSync(W)||await n.promises.mkdir(W,{recursive:!0}),await n.promises.copyFile(u,h)}}if(r(l,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:p,fileCount:f.length}),X.GIT_ENABLED&&(a==="true"||a===!0)){const g=await import("../../service/gitService.js");await g.default.init({workspaceType:"taskAgent",userId:e,cId:t}),await g.default.commit({workspaceType:"taskAgent",userId:e,cId:t,message:"Initial commit"}),r(l,"INFO","Git init and initial commit done",{userId:e,cId:t})}return r(l,"INFO","Init project template completed",{userId:e,cId:t,targetDir:p,elapsedMs:Date.now()-s}),{message:"Project template initialized successfully",workspaceRoot:p}}catch(f){throw r(l,"ERROR","Failed to init project template",{userId:e,cId:t,error:f.message,elapsedMs:Date.now()-s}),f instanceof m||f instanceof Q||f instanceof U?f:new U(`Failed to init project template: ${f.message}`,{userId:e,cId:t})}finally{try{n.existsSync(x)&&await n.promises.rm(x,{recursive:!0,force:!0})}catch(f){r(l,"WARN","Failed to clean up temporary extracted zip",{error:f.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(f){r(l,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:f.message})}}}async function Ue(e,t,i){if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i||typeof i!="string"||!i.trim())throw new m("command cannot be empty",{field:"command"});const a=await q("computer"),s=o.join(a,String(e),String(t));if(!n.existsSync(s))throw new m("workspace directory does not exist",{field:"workDir",workDir:s});const l=`computer:${e}:${t}`;r(l,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:s,command:i});const c=10*60*1e3,d={cwd:s,timeout:c,maxBuffer:50*1024*1024};return X.BASH_PATH&&(d.shell=X.BASH_PATH),new Promise((p,D)=>{Pe(i,d,(x,f,g)=>{const u=x?x.killed?-1:x.code||1:0,h=x&&x.killed?(g||"")+`
|
|
1
|
+
import n from"fs";import o from"path";import{exec as Pe}from"child_process";import je from"cross-spawn";import Ee from"archiver";import X from"../../appConfig/index.js";import{extractZip as J}from"../common/zipUtils.js";import{ValidationError as m,SystemError as U,FileError as Q}from"../error/errorHandler.js";import{log as r}from"../log/logUtils.js";import{createPnpmNpmrc as Fe}from"../common/npmrcUtils.js";import{ensurePrimaryAgentDirs as fe,syncAgents as ce,linkWorkspaceToAgentStore as we,isWorkspaceSkillsSymlinked as Ae}from"../common/AgentWorkspaceUtils.js";import{ensureAgentStoreDirs as he,tryAcquireAgentStoreLock as pe,releaseAgentStoreLock as ge,pruneAgentSkills as Oe,installSkillDir as te,replaceAgentsDir as $e,agentSkillExists as ze}from"../common/agentStoreUtils.js";import{writeAgentHookConfigs as ke}from"./hookConfigUtils.js";function se(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>typeof t=="string"?t.trim():t&&typeof t=="object"&&typeof t.url=="string"?t.url.trim():"").filter(Boolean);if(typeof e=="object")return Object.values(e).map(t=>typeof t=="string"?t.trim():"").filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);return se(i)}catch{}return[t]}return[]}function ye(e){if(!e)return[];if(Array.isArray(e)){const t=[];for(const i of e)if(typeof i=="string"&&i.trim())t.push({name:null,url:i.trim()});else if(i&&typeof i=="object"){const a=typeof i.url=="string"?i.url.trim():"",s=i.name!=null?String(i.name).trim():"";a&&t.push({name:s||null,url:a})}return t}if(typeof e=="object")return Object.entries(e).map(([t,i])=>({name:String(t||"").trim()||null,url:typeof i=="string"?i.trim():""})).filter(t=>t.url);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{return ye(JSON.parse(t))}catch{return[{name:null,url:t}]}}return[]}function ve(e){if(!e)return{};let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return{}}if(!t||typeof t!="object"||Array.isArray(t))return{};const i={};for(const[a,s]of Object.entries(t)){const l=String(a||"").trim(),c=typeof s=="string"?s.trim():"";l&&c&&(i[l]=c)}return i}function Se(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>String(t||"").trim()).filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);if(Array.isArray(i))return i.map(a=>String(a||"").trim()).filter(Boolean)}catch{}return t.split(",").map(i=>i.trim()).filter(Boolean)}return[]}async function ae(e,t,i){let a;try{a=await fetch(e)}catch(d){throw new Q(`Failed to download skill zip from url: ${e}`,{url:e,reason:d.message})}if(!a.ok)throw new Q(`Failed to download skill zip from url: ${e}`,{url:e,status:a.status,statusText:a.statusText});const s=a.headers.get("content-type")||"";s&&!s.includes("zip")&&!s.includes("octet-stream")&&r(i,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:s});const l=await a.arrayBuffer(),c=Buffer.from(l);await n.promises.writeFile(t,c)}async function q(e="computer"){const t=X.COMPUTER_WORKSPACE_DIR;if(!t)throw new m("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return n.existsSync(t)||(await n.promises.mkdir(t,{recursive:!0}),r(e,"INFO","Created user workspace root directory",{workspaceRoot:t})),t}async function I(e,t){const i=o.join(e,t);if(n.existsSync(i)&&(await n.promises.lstat(i)).isDirectory())return i;const a=await n.promises.readdir(e,{withFileTypes:!0});for(const s of a){if(!s.isDirectory())continue;const l=o.join(e,s.name),c=o.join(l,t);if(n.existsSync(c)&&(await n.promises.lstat(c)).isDirectory())return c}return null}async function mt(e){return I(e,"skills")}const Me=".dynamic_add.lock";function We(e){const t=o.join(e,Me);return n.existsSync(t)&&n.statSync(t).isFile()}async function H(e){n.existsSync(e)&&await n.promises.rm(e,{recursive:!0,force:!0})}async function V(e,t){try{await n.promises.rename(e,t)}catch(i){if(i.code==="EXDEV"){async function a(s,l){if((await n.promises.lstat(s)).isDirectory()){await n.promises.mkdir(l,{recursive:!0});const d=await n.promises.readdir(s);for(const p of d)await a(o.join(s,p),o.join(l,p))}else await n.promises.copyFile(s,l)}await a(e,t),await n.promises.rm(e,{recursive:!0,force:!0})}else throw i}}async function de(e){const i=(await n.promises.readdir(e,{withFileTypes:!0})).filter(s=>s.isDirectory()&&!s.name.startsWith("."));return i.find(s=>s.name==="skills")?(await n.promises.readdir(o.join(e,"skills"),{withFileTypes:!0})).filter(l=>l.isDirectory()&&!l.name.startsWith(".")).map(l=>({name:l.name,sourcePath:o.join(e,"skills",l.name)})):i.map(s=>({name:s.name,sourcePath:o.join(e,s.name)}))}const ie=8;async function ne(e,t,i){if(!e||e.length===0)return;const a=Math.max(1,Math.min(t,e.length));let s=0;await Promise.all(Array.from({length:a},async()=>{for(;;){const l=s++;if(l>=e.length)return;await i(e[l],l)}}))}async function be(e){const{userId:t,cId:i,agentId:a,file:s,skillUrls:l,skillUrlMap:c,skillNames:d,updateSkillNames:p,mcpServersConfig:D,permissionsConfig:x,hooksConfig:f,hookScripts:g}=e,u=Date.now(),h=`computer:${t}:${i}`,W=ve(c),_=ye(l),A=Se(d),k=p!=null,z=new Set(Se(p)),b=[],y=[],R=new Set,O=new Set;let E=null,v=!1;if(!t)throw new m("userId cannot be empty",{field:"userId"});if(!i)throw new m("cId cannot be empty",{field:"cId"});if(!a)throw new m("agentId cannot be empty",{field:"agentId"});const C=await q(h),S=o.join(C,String(t),String(i)),j=o.join(S,".tmp");await n.promises.mkdir(S,{recursive:!0}),await n.promises.mkdir(j,{recursive:!0});const{agentStorePath:N,skillsDir:T,agentsDir:ee}=await he(t,a,h),M=F=>!F||!k||z.has(F)?!0:!ze(T,F),G=async(F,P,B)=>{const K=o.join(j,`skill_url_${Date.now()}_${B}_${Math.round(Math.random()*1e6)}.zip`);b.push(K);const Z=o.join(j,`skill_url_extract_${Date.now()}_${B}_${Math.round(Math.random()*1e6)}`);y.push(Z),await n.promises.mkdir(Z,{recursive:!0}),r(h,"INFO","Start download skill zip from url",{userId:t,cId:i,agentId:a,skillName:P,skillUrl:F}),await ae(F,K,h),await J(K,Z);const L=await de(Z);if(L.length===0){r(h,"WARN","No skill dir found in downloaded zip",{skillUrl:F,destName:P});return}let w=P?L.find($=>$.name===P):null;if(!w&&L.length===1&&(w=L[0]),P&&w){if(!M(P)){O.add(P);return}await te(w.sourcePath,T,P,{asDynamic:!1}),R.add(P),r(h,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:F,skillName:P,zipDirName:w.name});return}for(const $ of L){if(!M($.name)){O.add($.name);continue}await te($.sourcePath,T,$.name,{asDynamic:!1}),R.add($.name),r(h,"INFO","Skill from url updated to agent store",{userId:t,cId:i,agentId:a,skillUrl:F,skillName:$.name})}};await ke(S,{mcpServersConfig:D,hooksConfig:f,permissionsConfig:x,hookScripts:g},h);try{const F=await pe(N,h);if(!F.acquired)v=!0;else{E=F.lockPath;const B=Date.now();let K=null;if(s){if(!s.path)throw new m("Uploaded file has no valid path",{field:"file.path"});if(o.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:s.originalname});const w=o.join(j,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);y.push(w),await n.promises.mkdir(w,{recursive:!0}),await J(s.path,w);const $=await I(w,"skills");if($){const le=(await n.promises.readdir($,{withFileTypes:!0})).filter(Y=>Y.isDirectory());await ne(le,ie,async Y=>{if(!M(Y.name)){O.add(Y.name);return}await te(o.join($,Y.name),T,Y.name,{asDynamic:!1}),R.add(Y.name)})}K=await I(w,"agents")}const Z=Object.entries(W);if(Z.length>0){const L=[];for(const[w,$]of Z){if(!M(w)){O.add(w),r(h,"INFO","Skip download skill zip (already in agent store)",{userId:t,cId:i,agentId:a,skillName:w,skillUrl:$});continue}L.push({skillName:w,skillUrl:$})}await ne(L,ie,async(w,$)=>{await G(w.skillUrl,w.skillName,$)})}else{const L=[];for(let w=0;w<_.length;w++){const{name:$,url:le}=_[w];if($&&!M($)){O.add($);continue}L.push({skillUrl:le,hintedName:$,index:w})}await ne(L,ie,async w=>{await G(w.skillUrl,w.hintedName,w.index)})}await $e(K,ee),await Oe(T,A,h),r(h,"INFO","Agent store resources prepared",{userId:t,cId:i,agentId:a,selectiveInstall:k,updatedSkills:Array.from(R),skippedSkills:Array.from(O),updateSkillNames:Array.from(z),keepSkillNames:A,skillUrlMapCount:Z.length,prepareElapsedMs:Date.now()-B})}const P=await we(S,T,ee,h);return r(h,"INFO","Workspace created successfully (agent store)",{userId:t,cId:i,agentId:a,agentStorePath:N,updatedSkills:Array.from(R),skippedSkills:Array.from(O),skippedStoreUpdate:v,linkElapsedMs:P?.elapsedMs,elapsedMs:Date.now()-u}),{message:v?"Workspace linked to agent store (store update skipped, lock held)":"Workspace created successfully, linked to agent store",workspaceRoot:C,agentStorePath:N,updatedSkills:Array.from(R),skippedSkills:Array.from(O),skippedStoreUpdate:v}}catch(F){throw r(h,"ERROR","Failed to create workspace with agent store",{userId:t,cId:i,agentId:a,error:F.message,elapsedMs:Date.now()-u}),F instanceof m||F instanceof Q||F instanceof U?F:new U(`Failed to create workspace: ${F.message}`,{userId:t,cId:i,agentId:a})}finally{await ge(E,h);const F=Date.now();for(const P of y)try{n.existsSync(P)&&await n.promises.rm(P,{recursive:!0,force:!0})}catch(B){r(h,"WARN","Failed to clean up temporary extracted zip",{error:B.message})}for(const P of b)try{n.existsSync(P)&&await n.promises.unlink(P)}catch(B){r(h,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:P,error:B.message})}try{s&&s.path&&n.existsSync(s.path)&&await n.promises.unlink(s.path)}catch(P){r(h,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:P.message})}r(h,"INFO","Workspace temp cleanup completed",{userId:t,cId:i,agentId:a,elapsedMs:Date.now()-F,totalElapsedMs:Date.now()-u})}}async function Ce(e,t,i,a,s,l,c,d,p,D,x,f){if(p!=null&&String(p).trim()!=="")return be({userId:e,cId:t,agentId:p,file:i,skillUrls:a,skillUrlMap:f,skillNames:D,updateSkillNames:x,mcpServersConfig:s,permissionsConfig:l,hooksConfig:c,hookScripts:d});const g=Date.now(),u=`computer:${e}:${t}`,h=se(a),W=[],_=[],A=new Set;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});const k=await q(u),z=o.join(k,String(e),String(t),".tmp"),b=o.join(k,String(e),String(t)),{skillsDir:y,agentsDir:R,agentTypes:O}=await fe(b);n.existsSync(b)||await n.promises.mkdir(b,{recursive:!0});const E=o.join(z,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(n.existsSync(y)){const j=(await n.promises.readdir(y,{withFileTypes:!0})).filter(N=>N.isDirectory()&&We(o.join(y,N.name)));if(j.length>0){await n.promises.mkdir(E,{recursive:!0});for(const N of j){const T=o.join(y,N.name),ee=o.join(E,N.name);await V(T,ee)}r(u,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:j.map(N=>N.name)})}}if(await H(y),await H(R),await n.promises.mkdir(y,{recursive:!0}),await n.promises.mkdir(R,{recursive:!0}),n.existsSync(E)){const S=await n.promises.readdir(E,{withFileTypes:!0});for(const j of S)if(j.isDirectory()){const N=o.join(E,j.name),T=o.join(y,j.name);await V(N,T)}await H(E)}const v=n.existsSync(y),C=n.existsSync(R);if(r(u,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:y,targetAgentsDir:R,agentTypes:O,skillsExists:v,agentsExists:C}),await ke(b,{mcpServersConfig:s,hooksConfig:c,permissionsConfig:l,hookScripts:d},u),!i&&h.length===0){const S=await ce(b,u);return r(u,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:k,skillsDir:null,agentsDir:null,agentTypes:O,syncAgentsElapsedMs:S?.elapsedMs,elapsedMs:Date.now()-g}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:k}}if(i){if(!i.path)throw new m("Uploaded file has no valid path",{field:"file.path"});if(o.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:i.originalname})}r(u,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:k,hasUploadedZip:!!i,skillUrlsCount:h.length});try{n.existsSync(z)||await n.promises.mkdir(z,{recursive:!0});const S=[];if(i){const M=o.join(z,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);_.push(M),await n.promises.mkdir(M,{recursive:!0}),r(u,"DEBUG","Start extracting uploaded zip file",{extractRoot:M}),await J(i.path,M),r(u,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:M});const G=await I(M,"skills"),F=await I(M,"agents");if(G){await n.promises.mkdir(y,{recursive:!0});const P=await n.promises.readdir(G,{withFileTypes:!0});for(const B of P){if(!B.isDirectory())continue;const K=o.join(G,B.name),Z=o.join(y,B.name);n.existsSync(Z)&&await H(Z),await V(K,Z),A.add(B.name)}S.push("skills"),r(u,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetSkillsDir:y,agentTypes:O})}else r(u,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:M});F?(await H(R),await V(F,R),S.push("agents"),r(u,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:k,targetAgentsDir:R,agentTypes:O})):r(u,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:M})}for(let M=0;M<h.length;M+=1){const G=h[M],F=o.join(z,`skill_url_${Date.now()}_${M}_${Math.round(Math.random()*1e6)}.zip`);W.push(F);const P=o.join(z,`skill_url_extract_${Date.now()}_${M}_${Math.round(Math.random()*1e6)}`);_.push(P),await n.promises.mkdir(P,{recursive:!0}),r(u,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:G}),await ae(G,F,u),r(u,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:G,downloadedZipPath:F}),await J(F,P);const K=(await n.promises.readdir(P,{withFileTypes:!0})).filter(w=>w.isDirectory()&&!w.name.startsWith(".")),L=K.find(w=>w.name==="skills")?(await n.promises.readdir(o.join(P,"skills"),{withFileTypes:!0})).filter(w=>w.isDirectory()&&!w.name.startsWith(".")).map(w=>({name:w.name,sourcePath:o.join(P,"skills",w.name)})):K.map(w=>({name:w.name,sourcePath:o.join(P,w.name)}));if(L.length===0){r(u,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:G,extractRoot:P});continue}await n.promises.mkdir(y,{recursive:!0});for(const w of L){const $=o.join(y,w.name);n.existsSync($)&&await H($),await V(w.sourcePath,$),A.add(w.name),r(u,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:G,skillName:w.name,destSkillPath:$})}S.includes("skills")||S.push("skills")}S.length===0&&r(u,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!i,skillUrlsCount:h.length});const j=Array.from(A),N=S.length>0?`Workspace created successfully, ${S.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)",T=Date.now()-g;r(u,"INFO","Workspace resources prepared",{userId:e,cId:t,updatedDirs:S,updatedSkills:j,agentTypes:O,prepareElapsedMs:T});const ee=await ce(b,u);return r(u,"INFO",N,{userId:e,cId:t,updatedDirs:S,updatedSkills:j,agentTypes:O,prepareElapsedMs:T,syncAgentsElapsedMs:ee?.elapsedMs,elapsedMs:Date.now()-g}),{message:N,workspaceRoot:k,updatedSkills:j}}catch(S){throw r(u,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:S.message,elapsedMs:Date.now()-g}),S instanceof m||S instanceof Q||S instanceof U?S:new U(`Failed to create workspace: ${S.message}`,{userId:e,cId:t})}finally{const S=Date.now();try{for(const j of _)n.existsSync(j)&&await n.promises.rm(j,{recursive:!0,force:!0})}catch(j){r(u,"WARN","Failed to clean up temporary extracted zip",{error:j.message})}for(const j of W)try{n.existsSync(j)&&await n.promises.unlink(j)}catch(N){r(u,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:j,error:N.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(j){r(u,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:j.message})}r(u,"INFO","Workspace temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-S,totalElapsedMs:Date.now()-g})}}async function Te(e,t,i,a,s){const l=Date.now(),c=`computer:${e}:${t}`,d=se(s),p=[],D=[],x=new Set;let f=null;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i)throw new m("agentId cannot be empty",{field:"agentId"});if(!a&&d.length===0)throw new m("file or skillUrls cannot both be empty",{field:"file|skillUrls"});const g=await q(c),u=o.join(g,String(e),String(t)),h=o.join(u,".tmp");await n.promises.mkdir(u,{recursive:!0}),await n.promises.mkdir(h,{recursive:!0});const{agentStorePath:W,skillsDir:_,agentsDir:A}=await he(e,i,c);try{let k=await pe(W,c);if(!k.acquired)for(let R=1;R<=5&&!k.acquired;R++)await new Promise(O=>setTimeout(O,200*R)),k=await pe(W,c);if(!k.acquired)throw new U("Agent store is busy, please retry",{userId:e,cId:t,agentId:i});if(f=k.lockPath,a){if(!a.path)throw new m("Uploaded file has no valid path",{field:"file.path"});const R=o.join(h,`push_skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);D.push(R),await n.promises.mkdir(R,{recursive:!0}),await J(a.path,R);const O=await de(R),E=await I(R,"skills"),v=E?(await n.promises.readdir(E,{withFileTypes:!0})).filter(C=>C.isDirectory()).map(C=>({name:C.name,sourcePath:o.join(E,C.name)})):O;await ne(v,ie,async C=>{await te(C.sourcePath,_,C.name,{asDynamic:!0}),x.add(C.name)})}await ne(d,ie,async(R,O)=>{const E=o.join(h,`push_skill_url_${Date.now()}_${O}_${Math.round(Math.random()*1e6)}.zip`);p.push(E);const v=o.join(h,`push_skill_url_extract_${Date.now()}_${O}_${Math.round(Math.random()*1e6)}`);D.push(v),await n.promises.mkdir(v,{recursive:!0}),await ae(R,E,c),await J(E,v);const C=await de(v);for(const S of C)await te(S.sourcePath,_,S.name,{asDynamic:!0}),x.add(S.name)});const z=await we(u,_,A,c),b=Array.from(x),y=b.length>0?`Pushed ${b.length} skills to agent store: ${b.join(", ")}`:"No valid skill directories found in file or skillUrls";return r(c,"INFO",y,{userId:e,cId:t,agentId:i,updatedSkills:b,linkElapsedMs:z?.elapsedMs,elapsedMs:Date.now()-l}),{message:y,workspaceRoot:g,agentStorePath:W,updatedSkills:b}}catch(k){throw r(c,"ERROR","Failed to push skills to agent store",{userId:e,cId:t,agentId:i,error:k.message,elapsedMs:Date.now()-l}),k instanceof m||k instanceof Q||k instanceof U?k:new U(`Failed to push skill to workspace: ${k.message}`,{userId:e,cId:t,agentId:i})}finally{await ge(f,c);for(const k of D)try{n.existsSync(k)&&await n.promises.rm(k,{recursive:!0,force:!0})}catch(z){r(c,"WARN","Failed to clean up temporary extracted zip",{error:z.message})}for(const k of p)try{n.existsSync(k)&&await n.promises.unlink(k)}catch(z){r(c,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:k,error:z.message})}try{a&&a.path&&n.existsSync(a.path)&&await n.promises.unlink(a.path)}catch(k){r(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:a?.path,error:k.message})}}}async function Le(e,t,i,a,s){if(s!=null&&String(s).trim()!==""){const _=X.COMPUTER_WORKSPACE_DIR,A=_?o.join(_,String(e),String(t)):null;if(Ae(A))return Te(e,t,s,i,a);r(`computer:${e}:${t}`,"INFO","Push skills: agentId present but workspace not symlinked, use legacy path",{userId:e,cId:t,agentId:s,userWorkspaceRoot:A})}const c=Date.now(),d=`computer:${e}:${t}`,p=se(a),D=[],x=[];if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i&&p.length===0)throw new m("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(i){if(!i.path)throw new m("Uploaded file has no valid path",{field:"file.path"});if(o.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:i?.originalname})}const f=await q(d),g=o.join(f,String(e),String(t),".tmp"),u=o.join(f,String(e),String(t)),{skillsDir:h,agentTypes:W}=await fe(u);try{n.existsSync(u)||await n.promises.mkdir(u,{recursive:!0}),n.existsSync(h)||await n.promises.mkdir(h,{recursive:!0}),n.existsSync(g)||await n.promises.mkdir(g,{recursive:!0});const _=[],A=new Set;if(i){const y=o.join(g,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);x.push(y),await n.promises.mkdir(y,{recursive:!0}),r(d,"DEBUG","Start extracting skill zip file",{extractRoot:y}),await J(i.path,y),r(d,"DEBUG","Skill zip file extracted successfully",{extractRoot:y});const R=await I(y,"skills");if(!R)r(d,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:y});else{const E=(await n.promises.readdir(R,{withFileTypes:!0})).filter(v=>v.isDirectory()&&!v.name.startsWith("."));if(E.length===0)r(d,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:R});else for(const v of E){const C=o.join(R,v.name),S=o.join(h,v.name);n.existsSync(S)&&await H(S),await V(C,S),A.add(v.name),r(d,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:v.name,destSkillPath:S})}}}for(let y=0;y<p.length;y+=1){const R=p[y],O=o.join(g,`skill_push_url_${Date.now()}_${y}_${Math.round(Math.random()*1e6)}.zip`);D.push(O);const E=o.join(g,`skill_push_url_extract_${Date.now()}_${y}_${Math.round(Math.random()*1e6)}`);x.push(E),await n.promises.mkdir(E,{recursive:!0}),r(d,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:R}),await ae(R,O,d),await J(O,E);const C=(await n.promises.readdir(E,{withFileTypes:!0})).filter(N=>N.isDirectory()&&!N.name.startsWith(".")),j=C.find(N=>N.name==="skills")?(await n.promises.readdir(o.join(E,"skills"),{withFileTypes:!0})).filter(N=>N.isDirectory()&&!N.name.startsWith(".")).map(N=>({name:N.name,sourcePath:o.join(E,"skills",N.name)})):C.map(N=>({name:N.name,sourcePath:o.join(E,N.name)}));if(j.length===0){r(d,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:R,extractRoot:E});continue}for(const N of j){const T=o.join(h,N.name);n.existsSync(T)&&await H(T),await V(N.sourcePath,T),A.add(N.name),r(d,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:R,skillName:N.name,destSkillPath:T})}}for(const y of A)_.push(y);const k=_.length>0?`Pushed ${_.length} skills: ${_.join(", ")}`:"No valid skill directories found in file or skillUrls",z=Date.now()-c;r(d,"INFO","Push skills resources prepared",{userId:e,cId:t,updatedSkills:_,agentTypes:W,prepareElapsedMs:z});const b=await ce(u,d);return r(d,"INFO",k,{userId:e,cId:t,updatedSkills:_,agentTypes:W,prepareElapsedMs:z,syncAgentsElapsedMs:b?.elapsedMs,elapsedMs:Date.now()-c}),{message:k,workspaceRoot:f,updatedSkills:_}}catch(_){throw r(d,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:_.message,elapsedMs:Date.now()-c}),_ instanceof m||_ instanceof Q||_ instanceof U?_:new U(`Failed to push skill to workspace: ${_.message}`,{userId:e,cId:t})}finally{const _=Date.now();try{for(const A of x)n.existsSync(A)&&await n.promises.rm(A,{recursive:!0,force:!0})}catch(A){r(d,"WARN","Failed to clean up temporary extracted zip",{error:A.message})}for(const A of D)try{n.existsSync(A)&&await n.promises.unlink(A)}catch(k){r(d,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:A,error:k.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(A){r(d,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:A.message})}r(d,"INFO","Push skills temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-_,totalElapsedMs:Date.now()-c})}}async function Be(e,t,i,a){const s=Date.now(),l=`computer:${e}:${t}`;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i||!i.path)throw new m("file is required",{field:"file"});if(o.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new m("Only zip files are supported",{field:"file",originalName:i.originalname});const d=await q(l),p=o.join(d,String(e),String(t)),D=o.join(p,".tmp"),x=o.join(D,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{n.existsSync(p)||await n.promises.mkdir(p,{recursive:!0}),n.existsSync(D)||await n.promises.mkdir(D,{recursive:!0}),await n.promises.mkdir(x,{recursive:!0}),r(l,"DEBUG","Start extracting template zip file",{extractRoot:x}),await J(i.path,x),r(l,"DEBUG","Template zip file extracted successfully",{extractRoot:x});const f=await n.promises.readdir(x,{withFileTypes:!0});for(const g of f){const u=o.join(x,g.name),h=o.join(p,g.name);if(g.isDirectory())await V(u,h);else{const W=o.dirname(h);n.existsSync(W)||await n.promises.mkdir(W,{recursive:!0}),await n.promises.copyFile(u,h)}}if(r(l,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:p,fileCount:f.length}),X.GIT_ENABLED&&(a==="true"||a===!0)){const g=await import("../../service/gitService.js");await g.default.init({workspaceType:"taskAgent",userId:e,cId:t}),await g.default.commit({workspaceType:"taskAgent",userId:e,cId:t,message:"Initial commit"}),r(l,"INFO","Git init and initial commit done",{userId:e,cId:t})}return r(l,"INFO","Init project template completed",{userId:e,cId:t,targetDir:p,elapsedMs:Date.now()-s}),{message:"Project template initialized successfully",workspaceRoot:p}}catch(f){throw r(l,"ERROR","Failed to init project template",{userId:e,cId:t,error:f.message,elapsedMs:Date.now()-s}),f instanceof m||f instanceof Q||f instanceof U?f:new U(`Failed to init project template: ${f.message}`,{userId:e,cId:t})}finally{try{n.existsSync(x)&&await n.promises.rm(x,{recursive:!0,force:!0})}catch(f){r(l,"WARN","Failed to clean up temporary extracted zip",{error:f.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(f){r(l,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:f.message})}}}async function Ue(e,t,i){if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i||typeof i!="string"||!i.trim())throw new m("command cannot be empty",{field:"command"});const a=await q("computer"),s=o.join(a,String(e),String(t));if(!n.existsSync(s))throw new m("workspace directory does not exist",{field:"workDir",workDir:s});const l=`computer:${e}:${t}`;r(l,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:s,command:i});const c=10*60*1e3,d={cwd:s,timeout:c,maxBuffer:50*1024*1024};return X.BASH_PATH&&(d.shell=X.BASH_PATH),new Promise((p,D)=>{Pe(i,d,(x,f,g)=>{const u=x?x.killed?-1:x.code||1:0,h=x&&x.killed?(g||"")+`
|
|
2
2
|
Command timed out after ${c/1e3}s`:g||"";r(l,"INFO","Execute command completed",{userId:e,cId:t,exitCode:u,killed:x?x.killed:!1,stdoutLength:f?f.length:0,stderrLength:h.length}),p({stdout:f||"",stderr:h,exitCode:u})})})}async function Ze(e,t,i){const a=`computer:${e}:${t}`;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});const s=await q(a),l=o.join(s,String(e),String(t));if(!n.existsSync(l))throw new m("workspace directory does not exist",{field:"workDir",workDir:l});const c=X.ZIP_WORKSPACE_EXCLUDE||[],d=Array.isArray(i)?i:[],p=new Set([...c,...d]),D=`${e}_${t}.zip`,x=Date.now();r(a,"INFO","Zip workspace request",{userId:e,cId:t,targetDir:l,excludeDirs:[...p]});const f=Ee("zip",{zlib:{level:9}});return f.directory(l,!1,g=>{const u=g.name||"";if(u.split(/[\/\\]/).filter(Boolean).some(W=>p.has(W)))return!1;try{const W=o.join(l,u);if(n.lstatSync(W).isSymbolicLink())return!1}catch{return!1}return g}),f.on("warning",g=>{g.code==="ENOENT"?r(a,"WARN","Encountered file problem when creating zip",{message:g.message,code:g.code}):r(a,"ERROR","Encountered warning when creating zip",{message:g.message,code:g.code})}),f.on("error",g=>{r(a,"ERROR","Failed to create zip",{message:g.message,elapsedMs:Date.now()-x})}),f.on("end",()=>{r(a,"INFO","Workspace zip created successfully",{targetDir:l,zipFileName:D,elapsedMs:Date.now()-x})}),{archive:f,zipFileName:D}}const ue=new Set([...X.ZIP_WORKSPACE_EXCLUDE||[],"dist-packages"]);function re(e){let t;try{t=n.readdirSync(e,{withFileTypes:!0})}catch{return null}const i=o.join(e,"scripts","package-platforms.mjs");if(n.existsSync(i))return e;for(const a of t)if(a.isDirectory()&&!ue.has(a.name)){const s=re(o.join(e,a.name));if(s)return s}return null}function oe(e,t,i,a=10*60*1e3){return new Promise(s=>{const l=je(e,t,{...i,timeout:a});let c="",d="";l.stdout?.on("data",p=>{c+=p.toString()}),l.stderr?.on("data",p=>{d+=p.toString()}),l.on("error",p=>{s({stdout:c,stderr:d+`
|
|
3
3
|
Failed to spawn ${e}: ${p.message}`,exitCode:1})}),l.on("close",(p,D)=>{s(p===null&&D?{stdout:c,stderr:d+`
|
|
4
4
|
Process killed by signal ${D} (timeout after ${a/1e3}s)`,exitCode:-1}:{stdout:c,stderr:d,exitCode:p??1})})})}function Ge(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 Ke(e,t,i,a){const s=`computer:${e}:${t}`;if(!e)throw new m("userId cannot be empty",{field:"userId"});if(!t)throw new m("cId cannot be empty",{field:"cId"});if(!i)throw new m("agentId cannot be empty",{field:"agentId"});if(!a)throw new m("version cannot be empty",{field:"version"});const l=await q(s),c=o.join(l,String(e),String(t));if(!n.existsSync(c))throw new m("workspace directory does not exist",{field:"workDir",workDir:c});r(s,"INFO","Build agent package request",{userId:e,cId:t,agentId:i,version:a});const d=re(c);if(!d)throw new m("package-platforms.mjs not found in workspace",{field:"script"});r(s,"INFO","Found package script",{projectDir:d});const p=await Ne(d,s);if(r(s,"INFO","pnpm install completed",{exitCode:p.exitCode,stderrLength:p.stderr.length}),p.exitCode!==0)throw r(s,"ERROR","pnpm install failed",{stderr:p.stderr}),new U(`pnpm install failed: ${p.stderr}`);const D=o.join(d,"dist-packages"),x=["scripts/package-platforms.mjs",`agent-${i}`,a,D,"--print-artifacts"],f=await oe("node",x,{cwd:d,env:me()});if(r(s,"INFO","Build completed",{exitCode:f.exitCode,stdoutLength:f.stdout.length}),f.exitCode!==0)throw r(s,"ERROR","Build failed",{stderr:f.stderr}),new U(`Build failed: ${f.stderr}`);const g=[".tar.gz",".tar.bz2",".zip",".tgz"],u=[],h=f.stdout.split(`
|
package/package.json
CHANGED