@crewx/sdk 0.9.0-rc.164 → 0.9.0-rc.166

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.
Files changed (47) hide show
  1. package/dist/app/app.d.ts +10 -0
  2. package/dist/app/entry.d.ts +2 -0
  3. package/dist/app/index.d.ts +6 -0
  4. package/dist/app/index.js +12 -10
  5. package/dist/app/job-bridge.child.d.ts +1 -0
  6. package/dist/app/job-bridge.d.ts +67 -0
  7. package/dist/app/job-bridge.drain.child.d.ts +1 -0
  8. package/dist/app/job-bridge.example.d.ts +11 -0
  9. package/dist/app/job-contract.d.ts +40 -0
  10. package/dist/app/job-wire.d.ts +149 -0
  11. package/dist/app/runtime.d.ts +2 -0
  12. package/dist/app-artifact-policy/check.d.ts +2 -0
  13. package/dist/app-artifact-policy/contract.d.ts +54 -0
  14. package/dist/app-artifact-policy/helper.d.ts +15 -0
  15. package/dist/app-artifact-policy/index.d.ts +3 -0
  16. package/dist/app-artifact-policy/index.js +18 -0
  17. package/dist/app-artifact-policy/paths.d.ts +24 -0
  18. package/dist/app-artifact-policy/scan.d.ts +47 -0
  19. package/dist/desktop/index.js +3 -3
  20. package/dist/esm/app/index.js +12 -10
  21. package/dist/esm/app-artifact-policy/index.js +18 -0
  22. package/dist/esm/desktop/index.js +3 -3
  23. package/dist/esm/index.js +234 -232
  24. package/dist/esm/plugins/index.js +27 -27
  25. package/dist/esm/process/index.js +1 -1
  26. package/dist/esm/publish/index.js +2 -2
  27. package/dist/esm/repository/index.js +30 -30
  28. package/dist/esm/skills/index.js +2 -2
  29. package/dist/index.browser.d.ts +4 -0
  30. package/dist/index.browser.js +4 -4
  31. package/dist/index.d.ts +10 -2
  32. package/dist/index.js +240 -238
  33. package/dist/mcp-app/app-job-bridge.d.ts +30 -0
  34. package/dist/mcp-app/app-job-bridge.example.d.ts +36 -0
  35. package/dist/mcp-app/app-job.d.ts +168 -0
  36. package/dist/mcp-app/index.d.ts +4 -0
  37. package/dist/mcp-app/skill-backend.d.ts +7 -1
  38. package/dist/plugins/index.js +20 -20
  39. package/dist/process/index.d.ts +2 -2
  40. package/dist/process/index.js +1 -1
  41. package/dist/process/process-control.d.ts +19 -0
  42. package/dist/publish/index.js +2 -2
  43. package/dist/repository/index.js +37 -37
  44. package/dist/skills/index.js +2 -2
  45. package/dist/ui-instance/types.d.ts +6 -0
  46. package/dist/ui-plugin/types.d.ts +4 -1
  47. package/package.json +7 -1
@@ -1,3 +1,3 @@
1
- 'use strict';var p=require('path'),crypto=require('crypto'),fs=require('fs'),os=require('os'),child_process=require('child_process'),string_decoder=require('string_decoder'),module$1=require('module');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var p__namespace=/*#__PURE__*/_interopNamespace(p);var B=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var m=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var q={existsSync:e=>fs.existsSync(e),readFileSync:e=>fs.readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(fs.readFileSync(e)),writeFileSync:(e,t)=>fs.writeFileSync(e,t,"utf8"),mkdirSync:e=>{fs.mkdirSync(e,{recursive:true});},unlinkSync:e=>{fs.unlinkSync(e);}},Y=os.homedir;function N(e){return typeof e!="string"?void 0:e.trim()||void 0}function O(e){return N(e)?.toLowerCase()??""}function b(e){try{return fs.statSync(e).isFile()}catch{return false}}function Ke(e,t){if(e===t)return true;let n=p__namespace.default.relative(e,t);return n!==""&&!n.startsWith("..")&&!p__namespace.default.isAbsolute(n)}function je(e,t){if(p__namespace.default.basename(e)!==".bin")return false;let n=p__namespace.default.dirname(e);if(p__namespace.default.basename(n)!=="node_modules")return false;let r=p__namespace.default.dirname(n);return Ke(r,t)}function Q(e,t={}){if(e.includes("/")||e.includes("\\")||p__namespace.default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,o=p__namespace.default.resolve(t.cwd??process.cwd()),c=(t.resolution??"global_first")==="global_first",s=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=s.split(i).map(u=>u.trim()).filter(Boolean),l=p__namespace.default.extname(e).length>0,d=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",f=n==="win32"?l?[""]:d.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let P=p__namespace.default.resolve(o,u);if(!(c&&je(P,o)))for(let h of f){let C=O(h),g=h.toUpperCase();for(let w of [h,C,g]){let y=p__namespace.default.join(P,`${e}${w}`);if(b(y))return y}}}return e}function ze(e){if(!b(e))return null;try{let t=fs.readFileSync(e,"utf8"),n=p__namespace.default.dirname(e),r=[];for(let i of t.matchAll(/"([^"\r\n]*)"/g)){let d=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!d)continue;let f=d.replace(/[\\/]+/g,p__namespace.default.sep).replace(/^[\\/]+/,""),u=p__namespace.default.resolve(n,f);b(u)&&r.push(u);}let o=[],c=new Map;for(let i of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,p__namespace.default.sep).replace(/^[\\/]+/,"");c.set(a,p__namespace.default.resolve(n,l));}for(let i of t.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&b(l)&&o.push(l);}let s=i=>i.find(a=>{let l=O(p__namespace.default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return s(o)??s(r)}catch{return null}}function qe(e,t){if(typeof t=="string")return N(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?N(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?N(n):void 0;if(r)return r}return null}function Ye(e,t){if(!t)return null;let n=p__namespace.default.dirname(e),r=[p__namespace.default.resolve(n,"..",t),p__namespace.default.resolve(n,"node_modules",t)];for(let o of r){let c=p__namespace.default.join(o,"package.json");if(b(c))try{let s=JSON.parse(fs.readFileSync(c,"utf8")),i=qe(t,s.bin);if(!i)continue;let a=p__namespace.default.resolve(o,i);if(b(a))return a}catch{}}return null}function Qe(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.execPath??process.execPath,o=e.cwd,c=e.resolution;if(t!=="win32")return {command:Q(e.command,{cwd:o,env:n,platform:t,resolution:c}),leadingArgv:[],resolution:"direct"};let s=Q(e.command,{cwd:o,env:n,platform:t,resolution:c}),i=O(p__namespace.default.extname(s));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[s],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=ze(s)??Ye(s,e.packageName);return a?O(p__namespace.default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:s,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:s,leadingArgv:[],resolution:"direct",windowsHide:true}}function Ze(e){if(e.candidate.resolution!=="unresolved-wrapper")return {command:e.candidate.command,leadingArgv:e.candidate.leadingArgv,resolution:e.candidate.resolution,windowsHide:e.candidate.windowsHide};throw new Error(`${p__namespace.default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function ee(e){let t=Qe(e);return Ze({candidate:t})}function te(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var D="\uFFFD",$=8,re=1e3,tt=new Map([[437,"ibm437"],[720,"ibm720"],[737,"ibm737"],[775,"ibm775"],[850,"ibm850"],[852,"ibm852"],[855,"ibm855"],[857,"ibm857"],[858,"ibm858"],[862,"ibm862"],[864,"ibm864"],[932,"shift_jis"],[936,"gb18030"],[949,"euc-kr"],[950,"big5"],[866,"ibm866"],[869,"ibm869"],[1250,"windows-1250"],[1251,"windows-1251"],[1252,"windows-1252"],[1253,"windows-1253"],[1254,"windows-1254"],[1255,"windows-1255"],[1256,"windows-1256"],[1257,"windows-1257"],[1258,"windows-1258"]]),T;function U(e){let t=0;for(let n of e)n===D&&(t+=1);return t}function H(e,t){return U(t)<U(e)?t:e}function nt(e){let t=e.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!t)return null;let n=Number(t[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function rt(e){if(e!==65001)return tt.get(e)}function ot(e){let t=rt(e);if(!t)return null;try{return new TextDecoder(t)}catch{return null}}function st(){return new Promise(e=>{let t=false,n,r=o=>{t||(t=true,n&&clearTimeout(n),e(o));};n=setTimeout(()=>r(null),re),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:re,windowsHide:!0},(c,s)=>{if(c){r(null);return}r(nt(String(s)));}).once("error",()=>r(null));}catch{r(null);}})}function ie(){return process.platform!=="win32"?Promise.resolve(null):(T||(T=st(),T.then(e=>{},()=>{})),T)}function it(){process.platform==="win32"&&ie();}function se(e,t){if(t.length>=$)return t.subarray(t.length-$);let n=$-t.length,r=e.length>n?e.subarray(e.length-n):e;return Buffer.concat([r,t])}var k=class{platform;detectCodePage;utf8Decoder=new string_decoder.StringDecoder("utf8");codePage;fallbackDecoder;replayTail=Buffer.alloc(0);pendingUtf8="";pendingFallback="";pendingBytes=Buffer.alloc(0);queue=Promise.resolve();ended=false;constructor(t={}){this.platform=t.platform??process.platform,this.detectCodePage=t.detectCodePage??ie,this.codePage=t.codePage;}write(t){let n=Buffer.from(t);return this.enqueue(()=>this.decodeChunk(n))}end(){return this.enqueue(()=>this.finish())}enqueue(t){let n=this.queue.then(t);return this.queue=n.then(()=>{},()=>{}),n}clearPendingCandidate(){this.pendingUtf8="",this.pendingFallback="",this.pendingBytes=Buffer.alloc(0);}async resolveCodePage(){if(this.codePage!==void 0)return this.codePage;try{this.codePage=await this.detectCodePage();}catch{this.codePage=null;}return this.codePage}async getFallbackDecoder(){if(this.fallbackDecoder!==void 0)return this.fallbackDecoder;let t=await this.resolveCodePage();return this.fallbackDecoder=t===null?null:ot(t),this.fallbackDecoder}async decodeChunk(t){if(this.ended)return "";let n=this.utf8Decoder.write(t),r=n.includes(D);if(r&&(this.utf8Decoder=new string_decoder.StringDecoder("utf8")),this.platform!=="win32")return n;if(this.fallbackDecoder){let a=this.fallbackDecoder.decode(t,{stream:true}),l=se(this.pendingBytes,t);if(r){let d=this.pendingUtf8+n,f=this.pendingFallback+a;return this.clearPendingCandidate(),H(d,f)}if(U(a)>0){let d=this.pendingUtf8+n;return this.clearPendingCandidate(),this.fallbackDecoder=void 0,this.replayTail=l,d}if(this.pendingUtf8||this.pendingFallback){if(this.pendingUtf8+=n,this.pendingFallback+=a,this.pendingBytes=l,n.length===0||a.length===0)return "";let d=this.pendingUtf8;return this.clearPendingCandidate(),d}return n.length===0&&a.length>0?(this.pendingUtf8=n,this.pendingFallback=a,this.pendingBytes=l,""):n}let o=this.replayTail;if(this.fallbackDecoder===void 0&&(this.replayTail=se(this.replayTail,t)),!r)return n;let c=this.fallbackDecoder===void 0,s=await this.getFallbackDecoder();if(!s)return this.replayTail=Buffer.alloc(0),n;c&&o.length>0&&s.decode(o,{stream:true}),this.replayTail=Buffer.alloc(0);let i=s.decode(t,{stream:true});return H(n,i)}async finish(){if(this.ended)return "";this.ended=true;let t=this.utf8Decoder.end();if(this.platform!=="win32")return t;if(this.fallbackDecoder===void 0&&t.includes(D)){let c=await this.getFallbackDecoder();c&&this.replayTail.length>0&&(c.decode(this.replayTail,{stream:true}),this.replayTail=Buffer.alloc(0));}let n=this.pendingUtf8+t,r=this.fallbackDecoder?.decode()??"",o=this.pendingFallback+r;return this.clearPendingCandidate(),n.includes(D)?H(n,o):n}};it();var ae=3e3;var ct=2e3,lt=25,ut=100;function ue(e){return e instanceof Error?e:e===void 0?void 0:new Error(String(e))}function ce(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function dt(e){return Number.isSafeInteger(e)&&e>0}function ft(e,t){return new Promise(n=>{let r;try{r=child_process.spawn(e,t,{windowsHide:!0});}catch(l){n({status:null,stdout:"",stderr:"",error:ue(l)});return}let o="",c="",s=false,i,a=setTimeout(()=>{try{r.kill();}catch{}i({status:null,stdout:o,stderr:c,error:new Error(`Command timed out after ${ae}ms`)});},ae);i=l=>{s||(s=true,clearTimeout(a),n(l));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",l=>{o+=String(l);}),r.stderr?.on("data",l=>{c+=String(l);}),r.once("error",l=>{i({status:null,stdout:o,stderr:c,error:l});}),r.once("close",l=>{i({status:l,stdout:o,stderr:c});});})}async function pt(e,t,n){return n.runCommandAsync?n.runCommandAsync(e,t):n.runCommand?n.runCommand(e,t):ft(e,t)}function mt(e){return new Promise(t=>{setTimeout(t,Math.max(0,e));})}function ht(){return new Promise(e=>{setImmediate(e);})}function A(e,t=process.kill){try{return t(e,0),"alive"}catch(n){return ce(n)==="ESRCH"?"not_found":ce(n)==="EPERM"?"alive":"unknown"}}function gt(e,t){let n=A(-e,t),r=A(e,t);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function de(e,t,n,r){let o=Math.max(0,n),c=Math.max(1,r.pollIntervalMs??lt),s=Date.now()+o,i,a=o===0,l=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(d=>{i=setTimeout(d,o);});l.then(()=>{a=true;});try{for(await ht();;){let d=gt(e,t);if(d==="not_found")return d;let f=s-Date.now();if(a||f<=0)return d;await Promise.race([l,mt(Math.min(c,f))]);}}finally{i!==void 0&&clearTimeout(i);}}async function le(e,t,n,r,o){let c=await de(e,t,o.hardConfirmMs??ut,{...o,sleep:void 0});return c==="not_found"?n?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r}:c==="alive"?{status:"failed",pid:e,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:e,method:r,error:"Unable to verify process termination"}}async function fe(e,t={}){let n=t.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=u=>({status:"failed",pid:e,method:r,error:u});if(!dt(e))return o("Invalid process ID");let c=t.kill??process.kill,s=A(e,c);if(s==="not_found")return {status:"not_found",pid:e,method:r};if(s!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let u;try{u=await pt("taskkill",["/PID",String(e),"/T","/F"],t);}catch(h){u={status:null,stdout:"",stderr:"",error:ue(h)};}let P=A(e,c);return P==="not_found"?u.status===0&&!u.error?{status:"terminated",pid:e,method:r}:{status:"not_found",pid:e,method:r}:o(P==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let i,a=t.signal??"SIGKILL";try{c(-e,a);}catch(u){i=u;}if(a==="SIGKILL")return le(e,c,i,r,t);if(await de(e,c,t.graceMs??ct,t)==="not_found")return i?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r};let d;try{c(-e,"SIGKILL");}catch(u){d=u;}let f=await le(e,c,d,r,t);return f.status==="terminated"?f:f.status==="not_found"?i?f:{status:"terminated",pid:e,method:r}:o(f.error??"Process termination failed")}var wt=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];function Pt(e,t){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&(t.includes(r)||(n[r]=o));return n}function pe(e){return Pt(e,wt)}var me=3e4;function he(e){if(typeof e.pid!="number"){try{e.kill();}catch{}return}fe(e.pid,{signal:"SIGKILL"}).then(t=>{if(t.status==="failed")try{e.kill("SIGKILL");}catch{}},()=>{try{e.kill("SIGKILL");}catch{}});}var ge=(e,t,n={})=>new Promise((r,o)=>{let c=pe(n.env??process.env),s=process.platform,i;try{let w=ee({command:e,platform:s,env:c,cwd:n.cwd,allowShellFallback:!1});i=te(w,t);}catch(w){o(w instanceof Error?w:new Error(String(w)));return}let a=child_process.spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:s!=="win32"}),l="",d="",f=false,u=new k({platform:s}),P=new k({platform:s}),h=Promise.resolve(),C=Promise.resolve(),g=setTimeout(()=>{f||(f=true,he(a),o(new Error(`Command timed out after ${n.timeoutMs??me}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??me);a.stdout?.on("data",w=>{h=h.then(async()=>{l+=await u.write(w);});}),a.stderr?.on("data",w=>{C=C.then(async()=>{d+=await P.write(w);});}),a.on("error",w=>{f||(f=true,clearTimeout(g),o(w));}),a.on("close",w=>{f||(async()=>{await Promise.all([h,C]);let[y,$e]=await Promise.all([u.end(),P.end()]);f||(l+=y,d+=$e,f=true,clearTimeout(g),r({code:w??0,stdout:l,stderr:d}));})().catch(y=>{f||(f=true,clearTimeout(g),o(y instanceof Error?y:new Error(String(y))));});});});function yt(){try{return (typeof B=="function"?B:module$1.createRequire(__filename)).resolve("@crewx/sdk/package.json")}catch{return null}}function vt(){let e=[yt(),p.join(__dirname,"../../package.json"),p.join(__dirname,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(fs.readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var Pe=vt();var E=p__namespace.win32;function V(e){return E.join(e,".crewx")}function Ee(e){return E.join(V(e),"shortcut.json")}function Ce(e){return E.join(V(e),"launcher.json")}function ye(e){return E.join(V(e),"bin","crewx-launcher.cmd")}function ve(e){return E.join(e,"CrewX.lnk")}function X(e,t){return E.normalize(e).toLowerCase()===E.normalize(t).toLowerCase()}var Rt="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function Re(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Rt],{env:e.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let t=e.env.USERPROFILE||e.env.Userprofile||e.homedir();return t?{dir:E.join(t,"Desktop"),source:"fallback"}:null}function G(e,t){let n=E.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?E.resolve(r).toLowerCase()!==n:true).join(";")}function be(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function bt(e,t){let n=a=>{let[l,...d]=a.split("-"),f=d.join("-")||void 0;return {parts:(l??"").split(".").map(P=>Number.parseInt(P,10)||0),pre:f}},r=n(e),o=n(t),c=Math.max(r.parts.length,o.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,d=o.parts[a]??0;if(l!==d)return l<d?-1:1}if(r.pre===o.pre)return 0;if(!r.pre&&o.pre)return 1;if(r.pre&&!o.pre)return -1;let s=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(o.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(s)&&!Number.isNaN(i)&&s!==i?s<i?-1:1:r.pre<o.pre?-1:r.pre>o.pre?1:0}function _(e,t){return bt(e,t)<0}var _e=p__namespace.win32,xe=1;function Ie(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??xe,shortcutPath:n.shortcutPath,version:n.version,iconHash:typeof n.iconHash=="string"?n.iconHash:void 0,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function W(e,t,n){let r={schema:xe,...n,updatedAt:new Date().toISOString()};e.mkdirSync(_e.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function M(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function Le(e,t,n){e.mkdirSync(_e.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var kt=p__namespace.win32,x=1;function _t(e){return e.replace(/%/g,"%%")}function xt(e){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",e.bakedBinPath?`set "CREWX_FALLBACK_BIN=${_t(e.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
2
- `)}function Oe(e){let t=M(e.fs,e.launcherManifestPath),n=!!t&&t.schema>=x&&e.fs.existsSync(e.wrapperPath),r=n&&!t.binPath&&!!e.bakedBinPath;if(n&&!r)return {wrapperPath:e.wrapperPath,wrote:false,schema:t.schema};let c=xt({bakedBinPath:e.bakedBinPath});try{e.fs.mkdirSync(kt.dirname(e.wrapperPath)),e.fs.writeFileSync(e.wrapperPath,c),Le(e.fs,e.launcherManifestPath,{schema:x,binPath:e.bakedBinPath,updatedAt:new Date().toISOString()});}catch(s){throw s instanceof m?s:new m("WRITE_DENIED",`Could not write launcher wrapper: ${s instanceof Error?s.message:String(s)}`)}return {wrapperPath:e.wrapperPath,wrote:true,schema:x}}var It=["$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","$sc.TargetPath = $env:CREWX_LNK_TARGET","if ($env:CREWX_LNK_WORKDIR) { $sc.WorkingDirectory = $env:CREWX_LNK_WORKDIR }","$sc.WindowStyle = 7","if ($env:CREWX_LNK_ICON) { $sc.IconLocation = $env:CREWX_LNK_ICON }","$sc.Save()"].join("; "),Lt=["[Console]::OutputEncoding = [System.Text.Encoding]::UTF8","$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","[PSCustomObject]@{ TargetPath = $sc.TargetPath; WorkingDirectory = $sc.WorkingDirectory; IconLocation = $sc.IconLocation } | ConvertTo-Json -Compress"].join("; ");async function Te(e){let t={...e.env,CREWX_LNK_PATH:e.shortcutPath,CREWX_LNK_TARGET:e.targetPath,CREWX_LNK_WORKDIR:e.workingDirectory??"",CREWX_LNK_ICON:e.iconPath??""},n;try{n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",It],{env:t});}catch(r){throw new m("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new m("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function De(e){let t=e.trim(),n=t.lastIndexOf(",");return n!==-1&&/^-?\d+$/.test(t.slice(n+1).trim())&&(t=t.slice(0,n).trim()),t.length>=2&&t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1).trim()),t}async function Ae(e){try{let t={...e.env,CREWX_LNK_PATH:e.shortcutPath},n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Lt],{env:t});if(n.code!==0||!n.stdout.trim())return null;let r=JSON.parse(n.stdout.trim());return {targetPath:r.TargetPath??"",workingDirectory:r.WorkingDirectory??"",iconLocation:r.IconLocation??""}}catch{return null}}var K=p__namespace.win32;async function I(e){let t=G(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r;try{r=await e.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let o;try{o=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=o.dependencies?.crewx;if(!c?.version)return {installed:false};let s;try{let a=await e.run("npm",["prefix","-g"],{env:n});a.code===0&&(s=a.stdout.trim()||void 0);}catch{}let i=s?K.join(s,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:s}}var Nt=/EACCES|EPERM|EROFS/,Ot=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,Tt=/^\d+\.\d+\.\d+/;function Dt(e){return !!e&&e!=="0.0.0"&&Tt.test(e)}var J=10*6e4;async function Me(e){if(!Dt(e.targetVersion))throw new m("GLOBAL_INSTALL_FAILED",`RUNNING_VERSION_UNKNOWN: cannot reliably determine the running crewx version to install (got ${JSON.stringify(e.targetVersion)}); refusing to fall back to crewx@latest`);if(e.currentInfo?.installed&&e.currentInfo.version&&!_(e.currentInfo.version,e.targetVersion))return {info:e.currentInfo};let t=G(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r=`crewx@${e.targetVersion}`;e.onProgress?.({phase:"global-install",message:`Installing crewx globally (npm install -g ${r})`});let o;try{o=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:J});}catch(s){throw new m("NPM_UNAVAILABLE",`Could not run npm: ${s instanceof Error?s.message:String(s)}`)}if(o.code===0)return {info:await I({env:n,cwd:e.cwd,run:e.run})};let c=`${o.stdout}
3
- ${o.stderr}`;if(Nt.test(c)){e.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let s=e.env.LOCALAPPDATA||K.join(e.env.USERPROFILE??"","AppData","Local"),i={...n,npm_config_prefix:K.join(s,"crewx","npm")},a;try{a=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:i,timeoutMs:J});}catch(l){throw new m("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${l instanceof Error?l.message:String(l)}`)}if(a.code===0)return {info:await I({env:i,cwd:e.cwd,run:e.run})};throw new m("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${a.stderr||a.stdout}`)}if(Ot.test(c)){if(!e.installRoot)throw new m("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");e.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${e.installRoot}`});let s;try{s=await e.run("npm",["install","-g",e.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:J});}catch(i){throw new m("GLOBAL_INSTALL_FAILED",`Offline install failed: ${i instanceof Error?i.message:String(i)}`)}if(s.code===0)return {info:await I({env:n,cwd:e.cwd,run:e.run})};throw new m("GLOBAL_INSTALL_FAILED",`Offline install failed: ${s.stderr||s.stdout}`)}throw new m("GLOBAL_INSTALL_FAILED",c.trim()||`npm install -g ${r} failed`)}function Wt(e){return e.run??ge}function Mt(e){return e.fs??q}async function F(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.homedir??Y,o=Wt(e),c=Mt(e),s=e.runningVersion??Pe,i=e.cwd??process.cwd(),a=r(),l=Ee(a),d=Ce(a),f=ye(a),u=null;t==="win32"&&(u=await Re({env:n,homedir:r,run:o}));let P=u?ve(u.dir):null;return {platform:t,env:n,homedir:r,run:o,fs:c,runningVersion:s,cwd:i,installRoot:e.installRoot,shortcutManifestPath:l,launcherManifestPath:d,wrapperPath:f,desktop:u,shortcutPath:P}}function Fe(e){return e?p__namespace.win32.normalize(e).toLowerCase().endsWith(`${p__namespace.win32.sep}bin${p__namespace.win32.sep}crewx.ico`):false}function j(e,t){let n=e.readBinaryFileSync;if(n)try{return crypto.createHash("sha256").update(n(t)).digest("hex")}catch{return}}async function Ft(e){try{await e.run("ie4uinit.exe",["-show"],{env:e.env});}catch{}}async function v(e){if(e.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:e.runningVersion,errors:[],manifest:null,iconStale:false};let t=[];e.desktop||t.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=Ie(e.fs,e.shortcutManifestPath),r=M(e.fs,e.launcherManifestPath),o=await I({env:e.env,cwd:e.cwd,run:e.run}),c=e.shortcutPath?e.fs.existsSync(e.shortcutPath):false,s,i=false,a,l;if(!c)s=n?.declined?"declined":"not-installed";else {let d=!!n?.owned&&!!e.shortcutPath&&n.shortcutPath===e.shortcutPath,f=false,u=e.shortcutPath?await Ae({run:e.run,env:e.env,shortcutPath:e.shortcutPath}):null;if(d||(u&&X(u.targetPath,e.wrapperPath)?d=true:u&&be(u.targetPath)&&(f=true)),f)s="foreign",t.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!d)s="foreign";else if(n?.version&&_(e.runningVersion,n.version))s="superseded",t.push(`SUPERSEDED: running version ${e.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let P=!r||r.schema<x||!e.fs.existsSync(e.wrapperPath);if(u){let h=De(u.iconLocation);if(!(!!h&&e.fs.existsSync(h)))i=true;else {a=h;let g=Be(o,e.fs);g?X(h,g)?(l=j(e.fs,h),i=!l||n?.iconHash!==l):i=true:Fe(h)?(l=j(e.fs,h),i=!l||n?.iconHash!==l):i=true;}}s=P||i?"stale":"installed";}}return {supported:true,state:s,shortcutPath:e.shortcutPath??void 0,desktopDir:e.desktop?.dir,desktopSource:e.desktop?.source,wrapperPath:e.wrapperPath,wrapperSchema:r?.schema,globalCrewx:o.installed?o:{installed:false},runningVersion:e.runningVersion,errors:t,manifest:n,iconStale:i,iconPath:a,iconHash:l}}function Be(e,t){if(!e?.installed||!e.prefix)return;let n=p__namespace.win32.join(e.prefix,"node_modules","crewx","bin","crewx.ico");return t.existsSync(n)?n:void 0}function R(e){let{manifest:t,iconStale:n,iconPath:r,iconHash:o,...c}=e;return c}async function Bt(e={}){let t=await F(e),n=await v(t);return R(n)}async function $t(e={}){let t=await F(e);e.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await v(t),r=R(n);if(!r.supported)return {...r,changed:false,installedGlobal:false};if(r.state==="superseded")return {...r,changed:false,installedGlobal:false};if(r.state==="foreign"){if(n.errors.some(g=>g.startsWith("NSIS_PRESENT")))throw new m("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!e.force)throw new m("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!t.desktop||!t.shortcutPath)throw new m("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let o=false,c=false,s=r.globalCrewx,i=[],a=n.manifest?.iconHash,l=false;if(!!s?.installed&&!!s.version&&_(s.version,t.runningVersion)||!s?.installed&&r.state!=="installed"){let g=await Me({env:t.env,cwd:t.cwd,run:t.run,targetVersion:t.runningVersion,currentInfo:s??void 0,installRoot:t.installRoot,onProgress:e.onProgress});s=g.info,c=g.info.installed,o=true,c||i.push(`GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@${t.runningVersion} exited successfully but a follow-up check could not confirm the global install`);}if(e.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),Oe({fs:t.fs,wrapperPath:t.wrapperPath,launcherManifestPath:t.launcherManifestPath,bakedBinPath:s?.binPath}).wrote&&(o=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let g=Be(s,t.fs)??(n.iconPath&&Fe(n.iconPath)&&t.fs.existsSync(n.iconPath)?n.iconPath:void 0);if(n.iconStale&&!g)throw new m("ICON_UNAVAILABLE",`Could not locate the global CrewX icon (bin\\crewx.ico) to repair the desktop shortcut at ${t.shortcutPath}; the existing shortcut was left untouched`);e.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await Te({run:t.run,env:t.env,shortcutPath:t.shortcutPath,targetPath:t.wrapperPath,iconPath:g}),o=true,l=n.iconStale;let w=g?j(t.fs,g):void 0;w&&(a=w);}o&&W(t.fs,t.shortcutManifestPath,{shortcutPath:t.shortcutPath,version:t.runningVersion,owned:true,declined:false,desktopSource:t.desktop.source,iconHash:a}),l&&await Ft(t);let h=await v(t),C=R(h);return {...C,errors:[...C.errors,...i],changed:o,installedGlobal:c}}async function Ht(e={}){let t=await F(e),n=await v(t),r=R(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&t.shortcutPath)try{t.fs.unlinkSync(t.shortcutPath);}catch{}W(t.fs,t.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0,iconHash:void 0});let o=await v(t);return R(o)}async function Ut(e={}){let t=await F(e),n=await v(t),r=R(n);if(!r.supported)return r;W(t.fs,t.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource,iconHash:n.manifest?.iconHash});let o=await v(t);return R(o)}exports.ShortcutError=m;exports.dismissShortcutNotice=Ut;exports.getShortcutStatus=Bt;exports.installShortcut=$t;exports.killProcessTree=he;exports.uninstallShortcut=Ht;
1
+ 'use strict';var p=require('path'),crypto=require('crypto'),fs=require('fs'),os=require('os'),child_process=require('child_process'),string_decoder=require('string_decoder'),module$1=require('module');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var p__namespace=/*#__PURE__*/_interopNamespace(p);var F=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var m=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var q={existsSync:e=>fs.existsSync(e),readFileSync:e=>fs.readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(fs.readFileSync(e)),writeFileSync:(e,t)=>fs.writeFileSync(e,t,"utf8"),mkdirSync:e=>{fs.mkdirSync(e,{recursive:true});},unlinkSync:e=>{fs.unlinkSync(e);}},Y=os.homedir;function L(e){return typeof e!="string"?void 0:e.trim()||void 0}function N(e){return L(e)?.toLowerCase()??""}function _(e){try{return fs.statSync(e).isFile()}catch{return false}}function Je(e,t){if(e===t)return true;let n=p__namespace.default.relative(e,t);return n!==""&&!n.startsWith("..")&&!p__namespace.default.isAbsolute(n)}function je(e,t){if(p__namespace.default.basename(e)!==".bin")return false;let n=p__namespace.default.dirname(e);if(p__namespace.default.basename(n)!=="node_modules")return false;let r=p__namespace.default.dirname(n);return Je(r,t)}function Q(e,t={}){if(e.includes("/")||e.includes("\\")||p__namespace.default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,o=p__namespace.default.resolve(t.cwd??process.cwd()),c=(t.resolution??"global_first")==="global_first",s=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=s.split(i).map(u=>u.trim()).filter(Boolean),l=p__namespace.default.extname(e).length>0,d=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",f=n==="win32"?l?[""]:d.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let P=p__namespace.default.resolve(o,u);if(!(c&&je(P,o)))for(let h of f){let y=N(h),w=h.toUpperCase();for(let g of [h,y,w]){let C=p__namespace.default.join(P,`${e}${g}`);if(_(C))return C}}}return e}function ze(e){if(!_(e))return null;try{let t=fs.readFileSync(e,"utf8"),n=p__namespace.default.dirname(e),r=[];for(let i of t.matchAll(/"([^"\r\n]*)"/g)){let d=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!d)continue;let f=d.replace(/[\\/]+/g,p__namespace.default.sep).replace(/^[\\/]+/,""),u=p__namespace.default.resolve(n,f);_(u)&&r.push(u);}let o=[],c=new Map;for(let i of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,p__namespace.default.sep).replace(/^[\\/]+/,"");c.set(a,p__namespace.default.resolve(n,l));}for(let i of t.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&_(l)&&o.push(l);}let s=i=>i.find(a=>{let l=N(p__namespace.default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return s(o)??s(r)}catch{return null}}function qe(e,t){if(typeof t=="string")return L(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?L(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?L(n):void 0;if(r)return r}return null}function Ye(e,t){if(!t)return null;let n=p__namespace.default.dirname(e),r=[p__namespace.default.resolve(n,"..",t),p__namespace.default.resolve(n,"node_modules",t)];for(let o of r){let c=p__namespace.default.join(o,"package.json");if(_(c))try{let s=JSON.parse(fs.readFileSync(c,"utf8")),i=qe(t,s.bin);if(!i)continue;let a=p__namespace.default.resolve(o,i);if(_(a))return a}catch{}}return null}function Qe(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.execPath??process.execPath,o=e.cwd,c=e.resolution;if(t!=="win32")return {command:Q(e.command,{cwd:o,env:n,platform:t,resolution:c}),leadingArgv:[],resolution:"direct"};let s=Q(e.command,{cwd:o,env:n,platform:t,resolution:c}),i=N(p__namespace.default.extname(s));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[s],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=ze(s)??Ye(s,e.packageName);return a?N(p__namespace.default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:s,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:s,leadingArgv:[],resolution:"direct",windowsHide:true}}function Ze(e){if(e.candidate.resolution!=="unresolved-wrapper")return {command:e.candidate.command,leadingArgv:e.candidate.leadingArgv,resolution:e.candidate.resolution,windowsHide:e.candidate.windowsHide};throw new Error(`${p__namespace.default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function ee(e){let t=Qe(e);return Ze({candidate:t})}function te(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var D="\uFFFD",B=8,re=1e3,tt=new Map([[437,"ibm437"],[720,"ibm720"],[737,"ibm737"],[775,"ibm775"],[850,"ibm850"],[852,"ibm852"],[855,"ibm855"],[857,"ibm857"],[858,"ibm858"],[862,"ibm862"],[864,"ibm864"],[932,"shift_jis"],[936,"gb18030"],[949,"euc-kr"],[950,"big5"],[866,"ibm866"],[869,"ibm869"],[1250,"windows-1250"],[1251,"windows-1251"],[1252,"windows-1252"],[1253,"windows-1253"],[1254,"windows-1254"],[1255,"windows-1255"],[1256,"windows-1256"],[1257,"windows-1257"],[1258,"windows-1258"]]),T;function H(e){let t=0;for(let n of e)n===D&&(t+=1);return t}function $(e,t){return H(t)<H(e)?t:e}function nt(e){let t=e.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!t)return null;let n=Number(t[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function rt(e){if(e!==65001)return tt.get(e)}function ot(e){let t=rt(e);if(!t)return null;try{return new TextDecoder(t)}catch{return null}}function st(){return new Promise(e=>{let t=false,n,r=o=>{t||(t=true,n&&clearTimeout(n),e(o));};n=setTimeout(()=>r(null),re),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:re,windowsHide:!0},(c,s)=>{if(c){r(null);return}r(nt(String(s)));}).once("error",()=>r(null));}catch{r(null);}})}function ie(){return process.platform!=="win32"?Promise.resolve(null):(T||(T=st(),T.then(e=>{},()=>{})),T)}function it(){process.platform==="win32"&&ie();}function se(e,t){if(t.length>=B)return t.subarray(t.length-B);let n=B-t.length,r=e.length>n?e.subarray(e.length-n):e;return Buffer.concat([r,t])}var b=class{platform;detectCodePage;utf8Decoder=new string_decoder.StringDecoder("utf8");codePage;fallbackDecoder;replayTail=Buffer.alloc(0);pendingUtf8="";pendingFallback="";pendingBytes=Buffer.alloc(0);queue=Promise.resolve();ended=false;constructor(t={}){this.platform=t.platform??process.platform,this.detectCodePage=t.detectCodePage??ie,this.codePage=t.codePage;}write(t){let n=Buffer.from(t);return this.enqueue(()=>this.decodeChunk(n))}end(){return this.enqueue(()=>this.finish())}enqueue(t){let n=this.queue.then(t);return this.queue=n.then(()=>{},()=>{}),n}clearPendingCandidate(){this.pendingUtf8="",this.pendingFallback="",this.pendingBytes=Buffer.alloc(0);}async resolveCodePage(){if(this.codePage!==void 0)return this.codePage;try{this.codePage=await this.detectCodePage();}catch{this.codePage=null;}return this.codePage}async getFallbackDecoder(){if(this.fallbackDecoder!==void 0)return this.fallbackDecoder;let t=await this.resolveCodePage();return this.fallbackDecoder=t===null?null:ot(t),this.fallbackDecoder}async decodeChunk(t){if(this.ended)return "";let n=this.utf8Decoder.write(t),r=n.includes(D);if(r&&(this.utf8Decoder=new string_decoder.StringDecoder("utf8")),this.platform!=="win32")return n;if(this.fallbackDecoder){let a=this.fallbackDecoder.decode(t,{stream:true}),l=se(this.pendingBytes,t);if(r){let d=this.pendingUtf8+n,f=this.pendingFallback+a;return this.clearPendingCandidate(),$(d,f)}if(H(a)>0){let d=this.pendingUtf8+n;return this.clearPendingCandidate(),this.fallbackDecoder=void 0,this.replayTail=l,d}if(this.pendingUtf8||this.pendingFallback){if(this.pendingUtf8+=n,this.pendingFallback+=a,this.pendingBytes=l,n.length===0||a.length===0)return "";let d=this.pendingUtf8;return this.clearPendingCandidate(),d}return n.length===0&&a.length>0?(this.pendingUtf8=n,this.pendingFallback=a,this.pendingBytes=l,""):n}let o=this.replayTail;if(this.fallbackDecoder===void 0&&(this.replayTail=se(this.replayTail,t)),!r)return n;let c=this.fallbackDecoder===void 0,s=await this.getFallbackDecoder();if(!s)return this.replayTail=Buffer.alloc(0),n;c&&o.length>0&&s.decode(o,{stream:true}),this.replayTail=Buffer.alloc(0);let i=s.decode(t,{stream:true});return $(n,i)}async finish(){if(this.ended)return "";this.ended=true;let t=this.utf8Decoder.end();if(this.platform!=="win32")return t;if(this.fallbackDecoder===void 0&&t.includes(D)){let c=await this.getFallbackDecoder();c&&this.replayTail.length>0&&(c.decode(this.replayTail,{stream:true}),this.replayTail=Buffer.alloc(0));}let n=this.pendingUtf8+t,r=this.fallbackDecoder?.decode()??"",o=this.pendingFallback+r;return this.clearPendingCandidate(),n.includes(D)?$(n,o):n}};it();var ae=3e3;var ct=2e3,lt=25,ut=100;function ue(e){return e instanceof Error?e:e===void 0?void 0:new Error(String(e))}function ce(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function dt(e){return Number.isSafeInteger(e)&&e>0}function ft(e,t){return new Promise(n=>{let r;try{r=child_process.spawn(e,t,{windowsHide:!0});}catch(l){n({status:null,stdout:"",stderr:"",error:ue(l)});return}let o="",c="",s=false,i,a=setTimeout(()=>{try{r.kill();}catch{}i({status:null,stdout:o,stderr:c,error:new Error(`Command timed out after ${ae}ms`)});},ae);i=l=>{s||(s=true,clearTimeout(a),n(l));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",l=>{o+=String(l);}),r.stderr?.on("data",l=>{c+=String(l);}),r.once("error",l=>{i({status:null,stdout:o,stderr:c,error:l});}),r.once("close",l=>{i({status:l,stdout:o,stderr:c});});})}async function pt(e,t,n){return n.runCommandAsync?n.runCommandAsync(e,t):n.runCommand?n.runCommand(e,t):ft(e,t)}function mt(e){return new Promise(t=>{setTimeout(t,Math.max(0,e));})}function ht(){return new Promise(e=>{setImmediate(e);})}function A(e,t=process.kill){try{return t(e,0),"alive"}catch(n){return ce(n)==="ESRCH"?"not_found":ce(n)==="EPERM"?"alive":"unknown"}}function wt(e,t){let n=A(-e,t),r=A(e,t);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function de(e,t,n,r){let o=Math.max(0,n),c=Math.max(1,r.pollIntervalMs??lt),s=Date.now()+o,i,a=o===0,l=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(d=>{i=setTimeout(d,o);});l.then(()=>{a=true;});try{for(await ht();;){let d=wt(e,t);if(d==="not_found")return d;let f=s-Date.now();if(a||f<=0)return d;await Promise.race([l,mt(Math.min(c,f))]);}}finally{i!==void 0&&clearTimeout(i);}}async function le(e,t,n,r,o){let c=await de(e,t,o.hardConfirmMs??ut,{...o,sleep:void 0});return c==="not_found"?n?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r}:c==="alive"?{status:"failed",pid:e,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:e,method:r,error:"Unable to verify process termination"}}async function fe(e,t={}){let n=t.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=u=>({status:"failed",pid:e,method:r,error:u});if(!dt(e))return o("Invalid process ID");let c=t.kill??process.kill,s=A(e,c);if(s==="not_found")return {status:"not_found",pid:e,method:r};if(s!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let u;try{u=await pt("taskkill",["/PID",String(e),"/T","/F"],t);}catch(h){u={status:null,stdout:"",stderr:"",error:ue(h)};}let P=A(e,c);return P==="not_found"?u.status===0&&!u.error?{status:"terminated",pid:e,method:r}:{status:"not_found",pid:e,method:r}:o(P==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let i,a=t.signal??"SIGKILL";try{c(-e,a);}catch(u){i=u;}if(a==="SIGKILL")return le(e,c,i,r,t);if(await de(e,c,t.graceMs??ct,t)==="not_found")return i?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r};let d;try{c(-e,"SIGKILL");}catch(u){d=u;}let f=await le(e,c,d,r,t);return f.status==="terminated"?f:f.status==="not_found"?i?f:{status:"terminated",pid:e,method:r}:o(f.error??"Process termination failed")}var gt=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];function Pt(e,t){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&(t.includes(r)||(n[r]=o));return n}function pe(e){return Pt(e,gt)}var me=3e4;function he(e){if(typeof e.pid!="number"){try{e.kill();}catch{}return}fe(e.pid,{signal:"SIGKILL"}).then(t=>{if(t.status==="failed")try{e.kill("SIGKILL");}catch{}},()=>{try{e.kill("SIGKILL");}catch{}});}var we=(e,t,n={})=>new Promise((r,o)=>{let c=pe(n.env??process.env),s=process.platform,i;try{let g=ee({command:e,platform:s,env:c,cwd:n.cwd,allowShellFallback:!1});i=te(g,t);}catch(g){o(g instanceof Error?g:new Error(String(g)));return}let a=child_process.spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:s!=="win32"}),l="",d="",f=false,u=new b({platform:s}),P=new b({platform:s}),h=Promise.resolve(),y=Promise.resolve(),w=setTimeout(()=>{f||(f=true,he(a),o(new Error(`Command timed out after ${n.timeoutMs??me}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??me);a.stdout?.on("data",g=>{h=h.then(async()=>{l+=await u.write(g);});}),a.stderr?.on("data",g=>{y=y.then(async()=>{d+=await P.write(g);});}),a.on("error",g=>{f||(f=true,clearTimeout(w),o(g));}),a.on("close",g=>{f||(async()=>{await Promise.all([h,y]);let[C,Be]=await Promise.all([u.end(),P.end()]);f||(l+=C,d+=Be,f=true,clearTimeout(w),r({code:g??0,stdout:l,stderr:d}));})().catch(C=>{f||(f=true,clearTimeout(w),o(C instanceof Error?C:new Error(String(C))));});});});function Ct(){try{return (typeof F=="function"?F:module$1.createRequire(__filename)).resolve("@crewx/sdk/package.json")}catch{return null}}function Rt(){let e=[Ct(),p.join(__dirname,"../../package.json"),p.join(__dirname,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(fs.readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var Pe=Rt();var E=p__namespace.win32;function U(e){return E.join(e,".crewx")}function Ee(e){return E.join(U(e),"shortcut.json")}function ye(e){return E.join(U(e),"launcher.json")}function Ce(e){return E.join(U(e),"bin","crewx-launcher.cmd")}function Re(e){return E.join(e,"CrewX.lnk")}function V(e,t){return E.normalize(e).toLowerCase()===E.normalize(t).toLowerCase()}var vt="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function ve(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",vt],{env:e.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let t=e.env.USERPROFILE||e.env.Userprofile||e.homedir();return t?{dir:E.join(t,"Desktop"),source:"fallback"}:null}function X(e,t){let n=E.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?E.resolve(r).toLowerCase()!==n:true).join(";")}function _e(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function _t(e,t){let n=a=>{let[l,...d]=a.split("-"),f=d.join("-")||void 0;return {parts:(l??"").split(".").map(P=>Number.parseInt(P,10)||0),pre:f}},r=n(e),o=n(t),c=Math.max(r.parts.length,o.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,d=o.parts[a]??0;if(l!==d)return l<d?-1:1}if(r.pre===o.pre)return 0;if(!r.pre&&o.pre)return 1;if(r.pre&&!o.pre)return -1;let s=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(o.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(s)&&!Number.isNaN(i)&&s!==i?s<i?-1:1:r.pre<o.pre?-1:r.pre>o.pre?1:0}function k(e,t){return _t(e,t)<0}var ke=p__namespace.win32,Oe=1;function xe(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??Oe,shortcutPath:n.shortcutPath,version:n.version,iconHash:typeof n.iconHash=="string"?n.iconHash:void 0,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function W(e,t,n){let r={schema:Oe,...n,updatedAt:new Date().toISOString()};e.mkdirSync(ke.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function M(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function Ie(e,t,n){e.mkdirSync(ke.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var bt=p__namespace.win32,O=1;function kt(e){return e.replace(/%/g,"%%")}function Ot(e){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",e.bakedBinPath?`set "CREWX_FALLBACK_BIN=${kt(e.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
2
+ `)}function Ne(e){let t=M(e.fs,e.launcherManifestPath),n=!!t&&t.schema>=O&&e.fs.existsSync(e.wrapperPath),r=n&&!t.binPath&&!!e.bakedBinPath;if(n&&!r)return {wrapperPath:e.wrapperPath,wrote:false,schema:t.schema};let c=Ot({bakedBinPath:e.bakedBinPath});try{e.fs.mkdirSync(bt.dirname(e.wrapperPath)),e.fs.writeFileSync(e.wrapperPath,c),Ie(e.fs,e.launcherManifestPath,{schema:O,binPath:e.bakedBinPath,updatedAt:new Date().toISOString()});}catch(s){throw s instanceof m?s:new m("WRITE_DENIED",`Could not write launcher wrapper: ${s instanceof Error?s.message:String(s)}`)}return {wrapperPath:e.wrapperPath,wrote:true,schema:O}}var xt=["$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","$sc.TargetPath = $env:CREWX_LNK_TARGET","if ($env:CREWX_LNK_WORKDIR) { $sc.WorkingDirectory = $env:CREWX_LNK_WORKDIR }","$sc.WindowStyle = 7","if ($env:CREWX_LNK_ICON) { $sc.IconLocation = $env:CREWX_LNK_ICON }","$sc.Save()"].join("; "),It=["[Console]::OutputEncoding = [System.Text.Encoding]::UTF8","$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","[PSCustomObject]@{ TargetPath = $sc.TargetPath; WorkingDirectory = $sc.WorkingDirectory; IconLocation = $sc.IconLocation } | ConvertTo-Json -Compress"].join("; ");async function Te(e){let t={...e.env,CREWX_LNK_PATH:e.shortcutPath,CREWX_LNK_TARGET:e.targetPath,CREWX_LNK_WORKDIR:e.workingDirectory??"",CREWX_LNK_ICON:e.iconPath??""},n;try{n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",xt],{env:t});}catch(r){throw new m("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new m("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function De(e){let t=e.trim(),n=t.lastIndexOf(",");return n!==-1&&/^-?\d+$/.test(t.slice(n+1).trim())&&(t=t.slice(0,n).trim()),t.length>=2&&t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1).trim()),t}async function Ae(e){try{let t={...e.env,CREWX_LNK_PATH:e.shortcutPath},n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",It],{env:t});if(n.code!==0||!n.stdout.trim())return null;let r=JSON.parse(n.stdout.trim());return {targetPath:r.TargetPath??"",workingDirectory:r.WorkingDirectory??"",iconLocation:r.IconLocation??""}}catch{return null}}var J=p__namespace.win32;async function x(e){let t=X(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r;try{r=await e.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let o;try{o=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=o.dependencies?.crewx;if(!c?.version)return {installed:false};let s;try{let a=await e.run("npm",["prefix","-g"],{env:n});a.code===0&&(s=a.stdout.trim()||void 0);}catch{}let i=s?J.join(s,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:s}}var Lt=/EACCES|EPERM|EROFS/,Nt=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,Tt=/^\d+\.\d+\.\d+/;function Dt(e){return !!e&&e!=="0.0.0"&&Tt.test(e)}var K=10*6e4;async function Me(e){if(!Dt(e.targetVersion))throw new m("GLOBAL_INSTALL_FAILED",`RUNNING_VERSION_UNKNOWN: cannot reliably determine the running crewx version to install (got ${JSON.stringify(e.targetVersion)}); refusing to fall back to crewx@latest`);if(e.currentInfo?.installed&&e.currentInfo.version&&!k(e.currentInfo.version,e.targetVersion))return {info:e.currentInfo};let t=X(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r=`crewx@${e.targetVersion}`;e.onProgress?.({phase:"global-install",message:`Installing crewx globally (npm install -g ${r})`});let o;try{o=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:K});}catch(s){throw new m("NPM_UNAVAILABLE",`Could not run npm: ${s instanceof Error?s.message:String(s)}`)}if(o.code===0)return {info:await x({env:n,cwd:e.cwd,run:e.run})};let c=`${o.stdout}
3
+ ${o.stderr}`;if(Lt.test(c)){e.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let s=e.env.LOCALAPPDATA||J.join(e.env.USERPROFILE??"","AppData","Local"),i={...n,npm_config_prefix:J.join(s,"crewx","npm")},a;try{a=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:i,timeoutMs:K});}catch(l){throw new m("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${l instanceof Error?l.message:String(l)}`)}if(a.code===0)return {info:await x({env:i,cwd:e.cwd,run:e.run})};throw new m("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${a.stderr||a.stdout}`)}if(Nt.test(c)){if(!e.installRoot)throw new m("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");e.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${e.installRoot}`});let s;try{s=await e.run("npm",["install","-g",e.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:K});}catch(i){throw new m("GLOBAL_INSTALL_FAILED",`Offline install failed: ${i instanceof Error?i.message:String(i)}`)}if(s.code===0)return {info:await x({env:n,cwd:e.cwd,run:e.run})};throw new m("GLOBAL_INSTALL_FAILED",`Offline install failed: ${s.stderr||s.stdout}`)}throw new m("GLOBAL_INSTALL_FAILED",c.trim()||`npm install -g ${r} failed`)}function Wt(e){return e.run??we}function Mt(e){return e.fs??q}async function G(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.homedir??Y,o=Wt(e),c=Mt(e),s=e.runningVersion??Pe,i=e.cwd??process.cwd(),a=r(),l=Ee(a),d=ye(a),f=Ce(a),u=null;t==="win32"&&(u=await ve({env:n,homedir:r,run:o}));let P=u?Re(u.dir):null;return {platform:t,env:n,homedir:r,run:o,fs:c,runningVersion:s,cwd:i,installRoot:e.installRoot,shortcutManifestPath:l,launcherManifestPath:d,wrapperPath:f,desktop:u,shortcutPath:P}}function Ge(e){return e?p__namespace.win32.normalize(e).toLowerCase().endsWith(`${p__namespace.win32.sep}bin${p__namespace.win32.sep}crewx.ico`):false}function j(e,t){let n=e.readBinaryFileSync;if(n)try{return crypto.createHash("sha256").update(n(t)).digest("hex")}catch{return}}async function Gt(e){try{await e.run("ie4uinit.exe",["-show"],{env:e.env});}catch{}}async function R(e){if(e.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:e.runningVersion,errors:[],manifest:null,iconStale:false};let t=[];e.desktop||t.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=xe(e.fs,e.shortcutManifestPath),r=M(e.fs,e.launcherManifestPath),o=await x({env:e.env,cwd:e.cwd,run:e.run}),c=e.shortcutPath?e.fs.existsSync(e.shortcutPath):false,s,i=false,a,l;if(!c)s=n?.declined?"declined":"not-installed";else {let d=!!n?.owned&&!!e.shortcutPath&&n.shortcutPath===e.shortcutPath,f=false,u=e.shortcutPath?await Ae({run:e.run,env:e.env,shortcutPath:e.shortcutPath}):null;if(d||(u&&V(u.targetPath,e.wrapperPath)?d=true:u&&_e(u.targetPath)&&(f=true)),f)s="foreign",t.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!d)s="foreign";else if(n?.version&&k(e.runningVersion,n.version))s="superseded",t.push(`SUPERSEDED: running version ${e.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let P=!r||r.schema<O||!e.fs.existsSync(e.wrapperPath);if(u){let h=De(u.iconLocation);if(!(!!h&&e.fs.existsSync(h)))i=true;else {a=h;let w=Fe(o,e.fs);w?V(h,w)?(l=j(e.fs,h),i=!l||n?.iconHash!==l):i=true:Ge(h)?(l=j(e.fs,h),i=!l||n?.iconHash!==l):i=true;}}s=P||i?"stale":"installed";}}return {supported:true,state:s,shortcutPath:e.shortcutPath??void 0,desktopDir:e.desktop?.dir,desktopSource:e.desktop?.source,wrapperPath:e.wrapperPath,wrapperSchema:r?.schema,globalCrewx:o.installed?o:{installed:false},runningVersion:e.runningVersion,errors:t,manifest:n,iconStale:i,iconPath:a,iconHash:l}}function Fe(e,t){if(!e?.installed||!e.prefix)return;let n=p__namespace.win32.join(e.prefix,"node_modules","crewx","bin","crewx.ico");return t.existsSync(n)?n:void 0}function v(e){let{manifest:t,iconStale:n,iconPath:r,iconHash:o,...c}=e;return c}async function Ft(e={}){let t=await G(e),n=await R(t);return v(n)}async function Bt(e={}){let t=await G(e);e.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await R(t),r=v(n);if(!r.supported)return {...r,changed:false,installedGlobal:false};if(r.state==="superseded")return {...r,changed:false,installedGlobal:false};if(r.state==="foreign"){if(n.errors.some(w=>w.startsWith("NSIS_PRESENT")))throw new m("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!e.force)throw new m("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!t.desktop||!t.shortcutPath)throw new m("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let o=false,c=false,s=r.globalCrewx,i=[],a=n.manifest?.iconHash,l=false;if(!!s?.installed&&!!s.version&&k(s.version,t.runningVersion)||!s?.installed&&r.state!=="installed"){let w=await Me({env:t.env,cwd:t.cwd,run:t.run,targetVersion:t.runningVersion,currentInfo:s??void 0,installRoot:t.installRoot,onProgress:e.onProgress});s=w.info,c=w.info.installed,o=true,c||i.push(`GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@${t.runningVersion} exited successfully but a follow-up check could not confirm the global install`);}if(e.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),Ne({fs:t.fs,wrapperPath:t.wrapperPath,launcherManifestPath:t.launcherManifestPath,bakedBinPath:s?.binPath}).wrote&&(o=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let w=Fe(s,t.fs)??(n.iconPath&&Ge(n.iconPath)&&t.fs.existsSync(n.iconPath)?n.iconPath:void 0);if(n.iconStale&&!w)throw new m("ICON_UNAVAILABLE",`Could not locate the global CrewX icon (bin\\crewx.ico) to repair the desktop shortcut at ${t.shortcutPath}; the existing shortcut was left untouched`);e.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await Te({run:t.run,env:t.env,shortcutPath:t.shortcutPath,targetPath:t.wrapperPath,iconPath:w}),o=true,l=n.iconStale;let g=w?j(t.fs,w):void 0;g&&(a=g);}o&&W(t.fs,t.shortcutManifestPath,{shortcutPath:t.shortcutPath,version:t.runningVersion,owned:true,declined:false,desktopSource:t.desktop.source,iconHash:a}),l&&await Gt(t);let h=await R(t),y=v(h);return {...y,errors:[...y.errors,...i],changed:o,installedGlobal:c}}async function $t(e={}){let t=await G(e),n=await R(t),r=v(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&t.shortcutPath)try{t.fs.unlinkSync(t.shortcutPath);}catch{}W(t.fs,t.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0,iconHash:void 0});let o=await R(t);return v(o)}async function Ht(e={}){let t=await G(e),n=await R(t),r=v(n);if(!r.supported)return r;W(t.fs,t.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource,iconHash:n.manifest?.iconHash});let o=await R(t);return v(o)}exports.ShortcutError=m;exports.dismissShortcutNotice=Ht;exports.getShortcutStatus=Ft;exports.installShortcut=Bt;exports.killProcessTree=he;exports.uninstallShortcut=$t;
@@ -1,10 +1,12 @@
1
- import {format,inspect}from'util';import {readSync}from'fs';import {createHash}from'crypto';import {Console}from'console';import {Writable}from'stream';var x=["text/plain","application/json"];var U=[5,15,30,60],P=Object.freeze({min:15e3,max:6e5,default:3e5}),be=1,W="schedule:",Ie="schedule",Re="exit 78",ie=["standby","disabled","draining","degraded"],Ne=["cron","cron_manual","app_enable"],De=/^[A-Z][A-Z0-9_]{0,63}$/u;function ae(e){return typeof e=="string"&&De.test(e)}var re=["status","everyMinutes","lastStartedAt","lastFinishedAt","lastOutcome","lastErrorCode","nextRunAt","periodic","periodicReason"],xe=["unset","on","off"],Pe=["available","unavailable"],z=64,ke=128;function se(e){return U.includes(e)}function Y(e){return Number.isSafeInteger(e)&&e>=P.min&&e<=P.max}function de(e){return ie.includes(e)}function ue(e){if(!Ue(e)||Object.keys(e).length!==re.length||!re.every(o=>Object.hasOwn(e,o))||typeof e.status!="string"||!xe.includes(e.status)||!se(e.everyMinutes)||!v(e.lastStartedAt,z)||!v(e.lastFinishedAt,z)||!v(e.lastOutcome,ke)||!v(e.nextRunAt,z)||e.lastErrorCode!==null&&!ae(e.lastErrorCode)||typeof e.periodic!="string"||!Pe.includes(e.periodic))return;let t=e.periodic;if(!(t==="available"?e.periodicReason!==null:!de(e.periodicReason))&&!(e.nextRunAt!==null&&(e.status!=="on"||t!=="available")))return Object.freeze({status:e.status,everyMinutes:e.everyMinutes,lastStartedAt:e.lastStartedAt,lastFinishedAt:e.lastFinishedAt,lastOutcome:e.lastOutcome,lastErrorCode:e.lastErrorCode,nextRunAt:e.nextRunAt,periodic:t,periodicReason:e.periodicReason})}function v(e,n){return e===null||typeof e=="string"&&e.length>0&&e.length<=n}function Ue(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var ce=Symbol;ce.metadata===void 0&&Object.defineProperty(Symbol,"metadata",{configurable:false,value:Symbol.for("Symbol.metadata")});var Le=ce.metadata,L=Symbol.for("crewx.app.tool-metadata"),l=class extends Error{code;detail;outcome;constructor(n,t=null,o){super(n),this.name="AppError",this.code=n,this.detail=t,this.outcome=Q(o?.outcome);}};function Q(e){return e==="rejected"?"rejected":"failed"}var G=class{static devtools=process.env.CREWX_APP_DEV==="1"?Object.freeze({log:true}):void 0;currentState;stateWasSet=false;answerBody;answerRange;callContext;callSchedule;scheduleDirective;workspaceRoot;constructor(n={workspaceRoot:process.cwd()}){this.currentState=n.state??{},this.workspaceRoot=n.workspaceRoot,this.callContext=n.context===void 0?void 0:Xe(n.context),this.callSchedule=n.schedule===void 0?void 0:Object.freeze({...n.schedule});}get schedule(){return this.callSchedule}requestSchedule(n){if(typeof n!="boolean")throw new TypeError("requestSchedule needs true or false");if(this.callSchedule===void 0)throw new l("SCHEDULE_UNSUPPORTED","this App has no schedule on this Host");let t=this.callContext?.actor;if(t==="schedule")throw new l("SCHEDULE_UNSUPPORTED","a scheduled run cannot change its own schedule",{outcome:"rejected"});if(n&&t!=="user")throw new l("SCHEDULE_ENABLE_DENIED","only the person at the screen can turn a schedule on",{outcome:"rejected"});this.scheduleDirective=Object.freeze({enabled:n});}get didRequestSchedule(){return this.scheduleDirective}get context(){if(this.callContext===void 0)throw new TypeError("this.context is only set when the Host runs the action; pass options.context when you construct the App in a test");return this.callContext}get state(){return this.currentState}get didSetState(){return this.stateWasSet}setState(n){this.currentState=n,this.stateWasSet=true;}get didSetContent(){return this.answerBody!==void 0}get producedContent(){return this.answerBody===void 0?void 0:{body:this.answerBody,...this.answerRange===void 0?{}:{range:this.answerRange}}}setContent(n,t){if(typeof n!="string"&&!(n instanceof Uint8Array))throw new TypeError("setContent needs a string or a Uint8Array");if(t!==void 0&&!Je(t))throw new TypeError("setContent range must be { startLine, lineCount, totalLines }, three integers of at least 1");this.answerBody=typeof n=="string"?new TextEncoder().encode(n):new Uint8Array(n),this.answerRange=t===void 0?void 0:{startLine:t.startLine,lineCount:t.lineCount,totalLines:t.totalLines};}emptyState(){return {}}validate(n,t,o){}mapError(n){return {code:"EXECUTION_FAILED",detail:null}}errorState(n,t,o){return {...T(o.state)?o.state:{},error:{code:n,detail:t}}}};function je(e){return function(n,t){if(t.static||t.private||t.kind!=="method")throw new TypeError("@Tool can decorate public instance methods only");let o=t.metadata;if(!o)throw new TypeError("standard decorator metadata is unavailable");let i=Object.hasOwn(o,L)?o[L]:[];if(i.some(u=>u.methodName===String(t.name)))throw new TypeError(`@Tool is declared more than once for ${String(t.name)}`);let r=e.content===void 0?void 0:Fe(e.name,e.content),s=e.schedule===void 0?void 0:ve(e);if(s!==void 0&&i.some(u=>u.options.schedule!==void 0))throw new TypeError(`@Tool ${e.name}: an App declares at most one scheduled action`);o[L]=[...i,{methodName:String(t.name),options:Object.freeze({...e,...r===void 0?{}:{content:r},...s===void 0?{}:{schedule:s}})}];}}function j(e){let n=e[Le],t=n&&Object.hasOwn(n,L)?n[L]:[],o=new Map(t.map(r=>[r.methodName,r])),i=Object.getOwnPropertyNames(e.prototype).map(r=>o.get(r)).filter(r=>r!==void 0);if(i.length!==t.length)throw new TypeError("a @Tool method is missing from the App prototype");return i}function le(e){return j(e).some(({options:n})=>n.schedule!==void 0)}function pe(e){let n=e.definition,t=j(e),o=new Set;return t.map(({options:i})=>{if(o.has(i.name))throw new TypeError(`duplicate @Tool name: ${i.name}`);return o.add(i.name),{actionId:i.name,...i.dataInputs===void 0?{}:{dataInputs:[...i.dataInputs]},confirmation:i.confirmation??"none",capability:i.capability??"app.read",mutation:i.mutation??true,inputSchema:i.inputSchema,...i.content===void 0?{}:{content:He(i.content)},...i.schedule===void 0?{}:{schedule:{...i.schedule}},resultProjection:i.resultProjection??{allow:[...n.stateProjection.allow]},_meta:{description:i.description}}})}function Me(e,n){if(n.length===0)throw new TypeError("backendCommand must name the skill command");let t=pe(e).map(({_meta:o,...i})=>({...i,backend:{type:"skill",command:[...n]},_meta:o}));return {...e.definition,actions:t}}function Fe(e,n){let t=r=>{throw new TypeError(`@Tool ${e}: content ${r}`)},o=(r,s,u)=>{if(!T(u))return t(`${r} must be an object`);for(let a of Object.keys(u))if(a==="mediaType"){if(!x.includes(u[a]))return t(`${r}.mediaType must be one of ${x.join(", ")}`)}else if(a===s){if(typeof u[a]!="boolean")return t(`${r}.${a} must be true or false`)}else return t(`${r} has the unknown key "${a}"`);return Object.hasOwn(u,"mediaType")?Object.freeze({...u}):t(`${r}.mediaType is required`)};if(!T(n))return t("must be an object");let i={};for(let r of Object.keys(n))if(r==="in")i[r]=o("in","required",n[r]);else if(r==="out")i[r]=o("out","range",n[r]);else return t(`has the unknown key "${r}"; use "in" and/or "out"`);return Object.keys(i).length===0?t('needs "in" and/or "out"'):Object.freeze(i)}function ve(e){let n=o=>{throw new TypeError(`@Tool ${e.name}: schedule ${o}`)},t=e.schedule;if(!T(t))return n("must be an object");for(let o of Object.keys(t))if(o!=="everyMinutes"&&o!=="timeoutMs")return n(`has the unknown key "${o}"`);return U.includes(t.everyMinutes)?t.timeoutMs!==void 0&&!Y(t.timeoutMs)?n(`timeoutMs must be an integer from ${P.min} to ${P.max}`):e.content!==void 0?n("cannot be combined with content"):e.dataInputs!==void 0?n("cannot be combined with dataInputs"):e.confirmation!==void 0&&e.confirmation!=="none"?n("cannot require a native confirmation"):Object.freeze({everyMinutes:t.everyMinutes,...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs}}):n(`everyMinutes must be one of ${U.join(", ")}`)}function Xe(e){return Object.freeze({instanceId:e.instanceId,threadId:e.threadId,actor:e.actor,requestId:e.requestId,nowMs:e.nowMs})}function He(e){let n={};for(let[t,o]of Object.entries(e))n[t]={...o};return n}function Je(e){return T(e)&&["startLine","lineCount","totalLines"].every(n=>Number.isSafeInteger(e[n])&&e[n]>=1)}function T(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var qe=/^[A-Za-z0-9._:-]{1,128}$/u,Ke=/[\u0000-\u001f\u007f\u2028\u2029]/u,$e=512;function Z(e=process.env){let n=fe(e.CREWX_APP_INSTANCE_ID),t=e.CREWX_APP_REQUEST_ID,o=e.CREWX_APP_ACTOR_KIND,i=e.CREWX_APP_NOW_MS;if(n===void 0||typeof t!="string"||!qe.test(t)||o!=="user"&&o!=="agent"&&o!=="schedule"||typeof i!="string"||!/^\d{1,16}$/u.test(i))return;let r=Number(i);if(!Number.isSafeInteger(r))return;let s=e.CREWX_THREAD_ID===void 0?null:fe(e.CREWX_THREAD_ID);if(s!==void 0&&!(o==="schedule"&&(s!==null||!n.startsWith(W))))return Object.freeze({instanceId:n,threadId:s,actor:o,requestId:t,nowMs:r})}function fe(e){if(!(typeof e!="string"||e.length===0||Ke.test(e)))return new TextEncoder().encode(e).byteLength<=$e?e:void 0}var Be="dist/tools.json",Ve=1,ze="dist/main.mjs";var ye=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];function We(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!ye.some(o=>o===t)||n.has(t))return false;n.add(t);}return true}var X=2,H=2097152;var k=2*1024*1024,J=2e4;function ee(e){return createHash("sha256").update(e).digest("hex")}function q(e){if(e.byteLength===0)return 0;let n=0;for(let t of e)t===10&&(n+=1);return e[e.byteLength-1]!==10&&(n+=1),n}var Qe=H+1+k,Ze=64*1024,en=10,K={kind:"invalid"};function nn(e,n){try{let t=[],o=0;for(;;){let s=new Uint8Array(Ze),u=readSync(e,s,0,s.length,null);if(u===0)break;if(o+=u,o>n)return;t.push(s.subarray(0,u));}let i=new Uint8Array(o),r=0;for(let s of t)i.set(s,r),r+=s.byteLength;return i}catch{return}}function $(e){return tn(nn(e,Qe))}function tn(e){if(e===void 0)return K;let n=e.indexOf(en);if(e.byteLength<=H){let o=un(Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"));if(o.ok&&!(n>=0&&I(o.value)&&o.value.schemaVersion===X))return {kind:"v1",value:o.value}}if(n<=0||n>H)return K;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.subarray(0,n)));}catch{return K}return !I(t)||t.schemaVersion!==X?K:{kind:"v2",header:t,body:e.subarray(n+1)}}var on="actionId,content,input,schemaVersion,state",rn="bytes,lines,mediaType,sha256",an="mediaType,range",sn=/^[a-f0-9]{64}$/u,dn=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function Ae(e,n){let t=a=>({code:a,outcome:"rejected"});if(M(e)!==on||e.schemaVersion!==X||typeof e.actionId!="string"||!I(e.input)||!I(e.state)||!I(e.content)||M(e.content)!=="in,out")return {code:"INPUT_INVALID",outcome:"failed"};let o=e.content,i,r=o.in;if(r===null){if(n.byteLength!==0)return t(n.byteLength>k?"CONTENT_TOO_LARGE":"CONTENT_DIGEST_MISMATCH")}else {if(!I(r)||M(r)!==rn||!me(r.mediaType)||!Ee(r.bytes,k)||!Ee(r.lines,J)||typeof r.sha256!="string"||!sn.test(r.sha256)||n.byteLength!==r.bytes)return t(n.byteLength>k?"CONTENT_TOO_LARGE":"CONTENT_DIGEST_MISMATCH");if(ee(n)!==r.sha256||q(n)!==r.lines)return t("CONTENT_DIGEST_MISMATCH");let a;try{a=dn.decode(n);}catch{return t("CONTENT_ENCODING_INVALID")}i={mediaType:r.mediaType,text:a};}let s,u=o.out;if(u!==null){if(!I(u)||M(u)!==an||!me(u.mediaType))return t("CONTENT_SOURCE_UNSUPPORTED");let a=u.range;if(a!==null&&!cn(a))return t("CONTENT_SOURCE_UNSUPPORTED");s={mediaType:u.mediaType,...a===null?{}:{range:{startLine:a.startLine,lineCount:a.lineCount}}};}return {actionId:e.actionId,input:e.input,state:e.state,content:{...i===void 0?{}:{in:i},...s===void 0?{}:{out:s}}}}function Se(e){return Object.hasOwn(e,"code")}function he(e,n){let t=o=>({code:o,outcome:"rejected"});if(e?.in===void 0){if(n.in!==void 0)return t("CONTENT_SOURCE_UNSUPPORTED")}else if(n.in===void 0){if(e.in.required===true)return t("CONTENT_REQUIRED")}else if(n.in.mediaType!==e.in.mediaType)return t("CONTENT_SOURCE_UNSUPPORTED");if(e?.out===void 0){if(n.out!==void 0)return t("CONTENT_SOURCE_UNSUPPORTED")}else {if(n.out===void 0)return t("CONTENT_REQUIRED");if(n.out.mediaType!==e.out.mediaType||n.out.range!==void 0&&e.out.range!==true)return t("CONTENT_SOURCE_UNSUPPORTED")}}function B(e,n){let{content:t,...o}=e,i=n===void 0?o:{...o,content:{bytes:n.body.byteLength,lines:q(n.body),sha256:ee(n.body),...n.range===void 0?{}:{range:n.range}}},r=new TextEncoder().encode(`${JSON.stringify(i)}
2
- `);if(n===void 0)return r;let s=new Uint8Array(r.byteLength+n.body.byteLength);return s.set(r,0),s.set(n.body,r.byteLength),s}function Te(e){if(e.body.byteLength>k||q(e.body)>J)return {code:"CONTENT_TOO_LARGE",outcome:"failed"}}function un(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}function M(e){return Object.keys(e).sort().join(",")}function I(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function me(e){return typeof e=="string"&&x.includes(e)}function Ee(e,n){return Number.isSafeInteger(e)&&e>=0&&e<=n}function cn(e){return I(e)&&M(e)==="lineCount,startLine"&&Number.isSafeInteger(e.startLine)&&e.startLine>=1&&Number.isSafeInteger(e.lineCount)&&e.lineCount>=1&&e.lineCount<=J}var pn=1;async function fn(e,n,t=process.env.CREWX_WORKSPACE_ROOT??process.cwd(),o){return (await Oe(e,n,t,void 0,true,void 0,o)).response}async function Oe(e,n,t,o,i=true,r,s){let u=r!==void 0,a=T(n)?n:void 0,E=a?.input,A=a?.state,d=new e({state:T(A)?A:{},workspaceRoot:t,...s===void 0?{}:{context:s}}),h=T(E)?E:{},S=T(A)?A:d.emptyState(),f={},y=a!==void 0&&Object.hasOwn(a,"schedule"),C;try{let m;if(u){if(a===void 0||y)throw new l("INPUT_INVALID");let p=Ae(a,r);if(Se(p))throw new l(p.code,null,{outcome:p.outcome});(({actionId:m,input:h,state:S}=p)),f=p.content;}else {let p=y&&a!==void 0?ue(a.schedule):void 0;if(!a||Object.keys(a).length!==(y?5:4)||!["schemaVersion","actionId","input","state"].every(we=>Object.hasOwn(a,we))||a.schemaVersion!==pn||typeof a.actionId!="string"||!T(E)||!T(A)||y&&p===void 0)throw new l("INPUT_INVALID");m=a.actionId,h=E,S=A,C=p;}d=new e({state:S,workspaceRoot:t,...s===void 0?{}:{context:s},...C===void 0?{}:{schedule:C}}),await d.validate(m,h,S);let c=j(e).find(({options:p})=>p.name===m);if(!c)throw new l("INPUT_INVALID");if(C!==void 0&&(c.options.content!==void 0||!le(e)))throw new l("INPUT_INVALID");let w=d[c.methodName];if(typeof w!="function")throw new l("EXECUTION_FAILED");let _=he(c.options.content,f);if(_)throw new l(_.code,null,{outcome:_.outcome});let F=Object.freeze({...f.in===void 0?{}:{in:Object.freeze({text:f.in.text})},...f.out===void 0?{}:{out:Object.freeze(f.out.range===void 0?{}:{range:Object.freeze({...f.out.range})})}}),D=()=>w.call(d,h,F),R=i?await mn(D):await D();if(R!==void 0&&!T(R))throw new l("EXECUTION_FAILED");let b;if(f.out!==void 0){if(b=d.producedContent,b===void 0)throw new l("EXECUTION_FAILED","content.out was requested but setContent was never called");let p=Te(b);if(p)throw new l(p.code,null,{outcome:p.outcome})}else if(d.didSetContent)throw new l("EXECUTION_FAILED","setContent was called but the request asked for no content.out");let N=d.didRequestSchedule;return {response:{...d.didSetState?{state:d.state}:{},...R===void 0?{}:{result:R},...N===void 0?{}:{schedule:{enabled:N.enabled}}},...b===void 0?{}:{answer:b}}}catch(m){let c,w=m,_=m instanceof l?m:void 0;if(_)c={code:_.code,detail:_.detail,outcome:_.outcome};else try{c=d.mapError(m);}catch(p){c={code:"EXECUTION_FAILED",detail:null},w=p;}let F=An(c?.code),D=F?c.code:"EXECUTION_FAILED",R=typeof c?.detail=="string"?c.detail:null,b=F?Q(c.outcome):"failed",N;try{N=d.errorState(D,R,{input:h,state:S});}catch(p){w=new AggregateError([w,p],"App error handling failed"),N=d.emptyState();}return o?.(D,w,{outcome:b,detail:R,expected:_!==void 0&&w===_}),{response:{outcome:b,errorCode:D,state:T(N)?N:d.emptyState()}}}}async function yn(e,n={}){let t=n.output??process.stdout,o,i;if(n.preloadedInput!==void 0)o=n.preloadedInput.value,i=n.preloadedInput.body;else {let d=$(n.inputFd??0);d.kind==="v1"?o=d.value:d.kind==="v2"&&(o=d.header,i=d.body);}let r=i!==void 0,s=n.context??Z(),u=false,a=(d,h,S)=>{u=true,n.onFailure?.(d,h,S);},E;try{E=await Oe(e,o,process.env.CREWX_WORKSPACE_ROOT??process.cwd(),a,n.consoleManaged!==!0,i,s);}catch(d){a("EXECUTION_FAILED",d),E={response:Ce(n.emptyState)};}En(E.response)&&!u&&a(E.response.errorCode,void 0,{outcome:E.response.outcome,detail:null,expected:false});let A;try{let d=(n.sanitize??_e)(E.response);A=r?B(d,E.answer):`${JSON.stringify(d)}
3
- `;}catch(d){a("EXECUTION_FAILED",d);let h=Ce(n.emptyState);try{let S=(n.sanitize??_e)(h);A=r?B(S):`${JSON.stringify(S)}
4
- `;}catch(S){a("EXECUTION_FAILED",S),A=r?B(h):`${JSON.stringify(h)}
5
- `;}}t.write(A);}async function mn(e){let n=["log","info","debug"],t=new Map;for(let o of n)t.set(o,console[o]),console[o]=(...i)=>process.stderr.write(`${format(...i)}
6
- `);try{return await e()}finally{for(let o of n)console[o]=t.get(o);}}function Ce(e={}){return {outcome:"failed",errorCode:"EXECUTION_FAILED",state:{...e,error:{code:"EXECUTION_FAILED",detail:null}}}}function En(e){return (e.outcome==="failed"||e.outcome==="rejected")&&typeof e.errorCode=="string"}function An(e){return typeof e=="string"&&/^[A-Z][A-Z0-9_]{0,127}$/u.test(e)}function _e(e){return e}var ne={depth:null,maxArrayLength:null,maxStringLength:null},oe=class extends Writable{#e="buffer";#n=[];_write(n,t,o){if(this.#e==="buffer"){this.#n.push(typeof n=="string"?n:Uint8Array.from(n)),o();return}if(this.#e==="discard"){o();return}process.stderr.write(n,o);}flushToStderr(){this.#e="stderr";for(let n of this.#n)process.stderr.write(n);this.#n=[];}discard(){this.#e="discard",this.#n=[];}};async function Tn(e,n={}){let t=process.stdout,o=t.write.bind(t),i=new oe,r=new Console({stdout:i,stderr:i,inspectOptions:{...ne}});globalThis.console=r;let s=false,u="-",a="-",E,A=false,d,h;try{let y=_n(n.inputFd??0);u=On(y.value),a=V(process.env.CREWX_APP_REQUEST_ID),E=new Date().toISOString();try{d=await e();}catch(c){A=!0,h=c;}let C=d?.default;if(!A&&C?.devtools?.log===!0?(Object.assign(inspect.defaultOptions,ne),S(E),i.flushToStderr()):i.discard(),A){f("EXECUTION_FAILED",h),te(o,n,f);return}try{if(typeof d?.runSkillApp!="function")throw new TypeError("App module does not export runSkillApp");let c={sanitize:n.sanitize,emptyState:n.emptyState??Cn(C),preloadedInput:y.body===void 0?{value:y.value}:{value:y.value,body:y.body},onFailure:f,consoleManaged:!0,output:{write:o}};await d.runSkillApp(C,c);}catch(c){f("EXECUTION_FAILED",c),te(o,n,f);}}catch(y){f("EXECUTION_FAILED",y),te(o,n,f);}finally{process.exitCode=0;}function S(y){s||(process.stderr.write(`[crewx-app] ${y??new Date().toISOString()} ${V(u)} req=${a}
7
- `),s=true);}function f(y,C,m){S();let c=m?.expected===true&&m.detail?` ${V(m.detail)}`:"";process.stderr.write(`[crewx-app] ${m?.outcome??"failed"} ${V(y)}${c}
8
- `),C!==void 0&&m?.expected!==true&&process.stderr.write(`${inspect(C,ne)}
9
- `);}}function Cn(e){if(typeof e=="function")try{let t=new e({workspaceRoot:process.cwd()}).emptyState();return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function _n(e){let n=$(e);return n.kind==="v1"?{value:n.value}:n.kind==="v2"?{value:n.header,body:n.body}:{value:void 0}}function On(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.actionId=="string"?e.actionId:"-"}function V(e){return typeof e!="string"||e.length===0?"-":e.replace(/[\u0000-\u001f\u007f\u2028\u2029]/gu,"_")}function te(e,n,t){let o={code:"EXECUTION_FAILED",detail:null},r={outcome:"failed",errorCode:"EXECUTION_FAILED",state:n.emptyState!==null&&typeof n.emptyState=="object"&&!Array.isArray(n.emptyState)?{...n.emptyState,error:o}:{error:o}},s=r;try{s=(n.sanitize??gn)(r);}catch(u){t("EXECUTION_FAILED",u);}e(`${JSON.stringify(s)}
10
- `);}function gn(e){return e}export{Ie as APP_SCHEDULE_ACTOR_KIND,Re as APP_SCHEDULE_INERT_COMMAND,W as APP_SCHEDULE_INSTANCE_PREFIX,U as APP_SCHEDULE_INTERVALS_MINUTES,be as APP_SCHEDULE_MAX_PER_APP,ie as APP_SCHEDULE_PERIODIC_REASONS,P as APP_SCHEDULE_TIMEOUT_MS,Be as APP_TOOLS_FILE,Ve as APP_TOOLS_SCHEMA_VERSION,ze as APP_TOOL_ENTRY,l as AppError,G as CrewXApp,Ne as SCHEDULE_TRIGGERS,ye as SKILL_BACKEND_ENV_NAMES,je as Tool,fn as executeAppRequest,Me as generateManifest,pe as generateToolDeclarations,j as getToolDeclarations,ae as isAppScheduleCode,se as isAppScheduleIntervalMinutes,de as isAppSchedulePeriodicReason,Y as isAppScheduleTimeoutMs,We as isSkillBackendEnv,Z as readAppContext,Tn as runAppEntry,yn as runSkillApp};
1
+ import {format,inspect}from'util';import {readSync}from'fs';import {randomUUID,createHash}from'crypto';import {Socket}from'net';import {Console}from'console';import {Writable}from'stream';var x=["text/plain","application/json"];var H=[5,15,30,60],k=Object.freeze({min:15e3,max:6e5,default:3e5}),En=1,be="schedule:",On="schedule",gn="exit 78",qe=["standby","disabled","draining","degraded"],Sn=["cron","cron_manual","app_enable"],Tn=/^[A-Z][A-Z0-9_]{0,63}$/u;function He(n){return typeof n=="string"&&Tn.test(n)}var Fe=["status","everyMinutes","lastStartedAt","lastFinishedAt","lastOutcome","lastErrorCode","nextRunAt","periodic","periodicReason"],Rn=["unset","on","off"],In=["available","unavailable"],Ae=64,Pn=128;function Xe(n){return H.includes(n)}function me(n){return Number.isSafeInteger(n)&&n>=k.min&&n<=k.max}function Ge(n){return qe.includes(n)}function Ve(n){if(!wn(n)||Object.keys(n).length!==Fe.length||!Fe.every(o=>Object.hasOwn(n,o))||typeof n.status!="string"||!Rn.includes(n.status)||!Xe(n.everyMinutes)||!Q(n.lastStartedAt,Ae)||!Q(n.lastFinishedAt,Ae)||!Q(n.lastOutcome,Pn)||!Q(n.nextRunAt,Ae)||n.lastErrorCode!==null&&!He(n.lastErrorCode)||typeof n.periodic!="string"||!In.includes(n.periodic))return;let t=n.periodic;if(!(t==="available"?n.periodicReason!==null:!Ge(n.periodicReason))&&!(n.nextRunAt!==null&&(n.status!=="on"||t!=="available")))return Object.freeze({status:n.status,everyMinutes:n.everyMinutes,lastStartedAt:n.lastStartedAt,lastFinishedAt:n.lastFinishedAt,lastOutcome:n.lastOutcome,lastErrorCode:n.lastErrorCode,nextRunAt:n.nextRunAt,periodic:t,periodicReason:n.periodicReason})}function Q(n,e){return n===null||typeof n=="string"&&n.length>0&&n.length<=e}function wn(n){if(n===null||typeof n!="object"||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var j=Object.freeze({min:6e4,max:18e5,default:6e5}),Cn=Object.freeze({min:1e3,max:12e4,default:3e4}),Jn=1,$e="crewx/appJobs",ze=1,_e=["starting","running","stopping","finished"],he=["succeeded","failed","timed_out","cancelled","shutdown","interrupted"],Z=["cancelled","timed_out","shutdown"],Ee=["manual","schedule"],Dn=/^[a-z][a-z0-9_]{0,63}$/u,Nn=/^[A-Z][A-Z0-9_]{0,63}$/u,ee=["start","status","cancel"],Oe=["APP_JOB_NOT_DECLARED","APP_JOB_NOT_AUTHORIZED","APP_JOB_SELF_START","APP_JOB_OWNER_INVALID","APP_JOB_DEFINITION_INVALID","APP_JOB_DEFINITION_CHANGED","APP_JOB_DEADLINE_INVALID","APP_JOB_SHUTTING_DOWN","APP_JOB_OWNER_MISMATCH","APP_JOB_STALE_HANDLE","APP_JOB_NOT_ACTIVE","APP_JOB_NOT_GRANTED"],ge="APP_JOB_RUN_REQUIRED";function Se(n){return Number.isSafeInteger(n)&&n>=j.min&&n<=j.max}function L(n){return typeof n=="string"&&Nn.test(n)}function B(n){return typeof n=="string"&&Dn.test(n)}function X(n){return ee.includes(n)}function xn(n){return n?.some(({name:e,version:t})=>e===$e&&t===ze)===true}var We=Symbol;We.metadata===void 0&&Object.defineProperty(Symbol,"metadata",{configurable:false,value:Symbol.for("Symbol.metadata")});var kn=We.metadata,G=Symbol.for("crewx.app.tool-metadata"),l=class extends Error{code;detail;outcome;constructor(e,t=null,o){super(e),this.name="AppError",this.code=e,this.detail=t,this.outcome=Re(o?.outcome);}};function Re(n){return n==="rejected"?"rejected":"failed"}var Te=class{static devtools=process.env.CREWX_APP_DEV==="1"?Object.freeze({log:true}):void 0;currentState;stateWasSet=false;answerBody;answerRange;callContext;callSchedule;callJobs;callJobRun;scheduleDirective;workspaceRoot;constructor(e={workspaceRoot:process.cwd()}){this.currentState=e.state??{},this.workspaceRoot=e.workspaceRoot,this.callContext=e.context===void 0?void 0:Fn(e.context),this.callSchedule=e.schedule===void 0?void 0:Object.freeze({...e.schedule}),this.callJobs=e.jobs,this.callJobRun=e.jobRun;}get jobs(){return this.callJobs}get jobRun(){return this.callJobRun}get schedule(){return this.callSchedule}requestSchedule(e){if(typeof e!="boolean")throw new TypeError("requestSchedule needs true or false");if(this.callSchedule===void 0)throw new l("SCHEDULE_UNSUPPORTED","this App has no schedule on this Host");let t=this.callContext?.actor;if(t==="schedule")throw new l("SCHEDULE_UNSUPPORTED","a scheduled run cannot change its own schedule",{outcome:"rejected"});if(e&&t!=="user")throw new l("SCHEDULE_ENABLE_DENIED","only the person at the screen can turn a schedule on",{outcome:"rejected"});this.scheduleDirective=Object.freeze({enabled:e});}get didRequestSchedule(){return this.scheduleDirective}get context(){if(this.callContext===void 0)throw new TypeError("this.context is only set when the Host runs the action; pass options.context when you construct the App in a test");return this.callContext}get state(){return this.currentState}get didSetState(){return this.stateWasSet}setState(e){this.currentState=e,this.stateWasSet=true;}get didSetContent(){return this.answerBody!==void 0}get producedContent(){return this.answerBody===void 0?void 0:{body:this.answerBody,...this.answerRange===void 0?{}:{range:this.answerRange}}}setContent(e,t){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new TypeError("setContent needs a string or a Uint8Array");if(t!==void 0&&!Hn(t))throw new TypeError("setContent range must be { startLine, lineCount, totalLines }, three integers of at least 1");this.answerBody=typeof e=="string"?new TextEncoder().encode(e):new Uint8Array(e),this.answerRange=t===void 0?void 0:{startLine:t.startLine,lineCount:t.lineCount,totalLines:t.totalLines};}emptyState(){return {}}validate(e,t,o){}mapError(e){return {code:"EXECUTION_FAILED",detail:null}}errorState(e,t,o){return {...h(o.state)?o.state:{},error:{code:e,detail:t}}}};function jn(n){return function(e,t){if(t.static||t.private||t.kind!=="method")throw new TypeError("@Tool can decorate public instance methods only");let o=t.metadata;if(!o)throw new TypeError("standard decorator metadata is unavailable");let r=Object.hasOwn(o,G)?o[G]:[];if(r.some(u=>u.methodName===String(t.name)))throw new TypeError(`@Tool is declared more than once for ${String(t.name)}`);let s=n.content===void 0?void 0:Bn(n.name,n.content),i=n.schedule===void 0?void 0:Un(n);if(i!==void 0&&r.some(u=>u.options.schedule!==void 0))throw new TypeError(`@Tool ${n.name}: an App declares at most one scheduled action`);let a=n.job===void 0?void 0:vn(n);if(a!==void 0&&r.some(u=>u.options.job!==void 0))throw new TypeError(`@Tool ${n.name}: an App declares at most one job action`);let p=n.jobAccess===void 0?void 0:Mn(n);o[G]=[...r,{methodName:String(t.name),options:Object.freeze({...n,...s===void 0?{}:{content:s},...i===void 0?{}:{schedule:i},...a===void 0?{}:{job:a},...p===void 0?{}:{jobAccess:p}})}];}}function V(n){let e=n[kn],t=e&&Object.hasOwn(e,G)?e[G]:[],o=new Map(t.map(s=>[s.methodName,s])),r=Object.getOwnPropertyNames(n.prototype).map(s=>o.get(s)).filter(s=>s!==void 0);if(r.length!==t.length)throw new TypeError("a @Tool method is missing from the App prototype");return r}function Ke(n){return V(n).some(({options:e})=>e.schedule!==void 0)}function Ye(n){let e=n.definition,t=V(n),o=new Set;return t.map(({options:r})=>{if(o.has(r.name))throw new TypeError(`duplicate @Tool name: ${r.name}`);return o.add(r.name),{actionId:r.name,...r.dataInputs===void 0?{}:{dataInputs:[...r.dataInputs]},confirmation:r.confirmation??"none",capability:r.capability??"app.read",mutation:r.mutation??true,inputSchema:r.inputSchema,...r.content===void 0?{}:{content:qn(r.content)},...r.schedule===void 0?{}:{schedule:{...r.schedule}},...r.job===void 0?{}:{job:{...r.job}},...r.jobAccess===void 0?{}:{jobAccess:[...r.jobAccess]},resultProjection:r.resultProjection??{allow:[...e.stateProjection.allow]},_meta:{description:r.description}}})}function Ln(n,e){if(e.length===0)throw new TypeError("backendCommand must name the skill command");let t=Ye(n).map(({_meta:o,...r})=>({...r,backend:{type:"skill",command:[...e]},_meta:o}));return {...n.definition,actions:t}}function Bn(n,e){let t=s=>{throw new TypeError(`@Tool ${n}: content ${s}`)},o=(s,i,a)=>{if(!h(a))return t(`${s} must be an object`);for(let p of Object.keys(a))if(p==="mediaType"){if(!x.includes(a[p]))return t(`${s}.mediaType must be one of ${x.join(", ")}`)}else if(p===i){if(typeof a[p]!="boolean")return t(`${s}.${p} must be true or false`)}else return t(`${s} has the unknown key "${p}"`);return Object.hasOwn(a,"mediaType")?Object.freeze({...a}):t(`${s}.mediaType is required`)};if(!h(e))return t("must be an object");let r={};for(let s of Object.keys(e))if(s==="in")r[s]=o("in","required",e[s]);else if(s==="out")r[s]=o("out","range",e[s]);else return t(`has the unknown key "${s}"; use "in" and/or "out"`);return Object.keys(r).length===0?t('needs "in" and/or "out"'):Object.freeze(r)}function Un(n){let e=o=>{throw new TypeError(`@Tool ${n.name}: schedule ${o}`)},t=n.schedule;if(!h(t))return e("must be an object");for(let o of Object.keys(t))if(o!=="everyMinutes"&&o!=="timeoutMs")return e(`has the unknown key "${o}"`);return H.includes(t.everyMinutes)?t.timeoutMs!==void 0&&!me(t.timeoutMs)?e(`timeoutMs must be an integer from ${k.min} to ${k.max}`):n.content!==void 0?e("cannot be combined with content"):n.dataInputs!==void 0?e("cannot be combined with dataInputs"):n.confirmation!==void 0&&n.confirmation!=="none"?e("cannot require a native confirmation"):Object.freeze({everyMinutes:t.everyMinutes,...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs}}):e(`everyMinutes must be one of ${H.join(", ")}`)}function vn(n){let e=o=>{throw new TypeError(`@Tool ${n.name}: job ${o}`)},t=n.job;if(!h(t))return e("must be an object");for(let o of Object.keys(t))if(o!=="deadlineMs")return e(`has the unknown key "${o}"`);return t.deadlineMs!==void 0&&!Se(t.deadlineMs)?e(`deadlineMs must be an integer from ${j.min} to ${j.max}`):n.content!==void 0?e("cannot be combined with content"):n.dataInputs!==void 0?e("cannot be combined with dataInputs"):n.confirmation!==void 0&&n.confirmation!=="none"?e("cannot require a native confirmation"):n.schedule!==void 0?e("cannot be the scheduled action too"):n.jobAccess!==void 0?e("cannot also be a control action: a run does not control itself"):Object.freeze({...t.deadlineMs===void 0?{}:{deadlineMs:t.deadlineMs}})}function Mn(n){let e=o=>{throw new TypeError(`@Tool ${n.name}: jobAccess ${o}`)},t=n.jobAccess;return !Array.isArray(t)||t.length===0?e("must list at least one operation"):new Set(t).size!==t.length?e("must not repeat an operation"):t.every(X)?n.job!==void 0?e("cannot be set on the job action, which runs the job and cannot control it"):n.content!==void 0?e("cannot be combined with content"):Object.freeze([...t]):e("names an unknown operation")}function Fn(n){return Object.freeze({instanceId:n.instanceId,threadId:n.threadId,actor:n.actor,requestId:n.requestId,nowMs:n.nowMs})}function qn(n){let e={};for(let[t,o]of Object.entries(n))e[t]={...o};return e}function Hn(n){return h(n)&&["startLine","lineCount","totalLines"].every(e=>Number.isSafeInteger(n[e])&&n[e]>=1)}function h(n){if(n===null||typeof n!="object"||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Xn=/^[A-Za-z0-9._:-]{1,128}$/u,Gn=/[\u0000-\u001f\u007f\u2028\u2029]/u,Vn=512;function Ie(n=process.env){let e=Qe(n.CREWX_APP_INSTANCE_ID),t=n.CREWX_APP_REQUEST_ID,o=n.CREWX_APP_ACTOR_KIND,r=n.CREWX_APP_NOW_MS;if(e===void 0||typeof t!="string"||!Xn.test(t)||o!=="user"&&o!=="agent"&&o!=="schedule"||typeof r!="string"||!/^\d{1,16}$/u.test(r))return;let s=Number(r);if(!Number.isSafeInteger(s))return;let i=n.CREWX_THREAD_ID===void 0?null:Qe(n.CREWX_THREAD_ID);if(i!==void 0&&!(o==="schedule"&&(i!==null||!e.startsWith(be))))return Object.freeze({instanceId:e,threadId:i,actor:o,requestId:t,nowMs:s})}function Qe(n){if(!(typeof n!="string"||n.length===0||Gn.test(n)))return new TextEncoder().encode(n).byteLength<=Vn?n:void 0}var $n="dist/tools.json",zn=1,Wn="dist/main.mjs";var Ze=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];function Kn(n){if(!Array.isArray(n)||n.length===0)return false;let e=new Set;for(let t of n){if(!Ze.some(o=>o===t)||e.has(t))return false;e.add(t);}return true}var ne=2,te=2097152;var U=2*1024*1024,oe=2e4;function Pe(n){return createHash("sha256").update(n).digest("hex")}function re(n){if(n.byteLength===0)return 0;let e=0;for(let t of n)t===10&&(e+=1);return n[n.byteLength-1]!==10&&(e+=1),e}var Zn=te+1+U,et=64*1024,nt=10,ie={kind:"invalid"};function tt(n,e){try{let t=[],o=0;for(;;){let i=new Uint8Array(et),a=readSync(n,i,0,i.length,null);if(a===0)break;if(o+=a,o>e)return;t.push(i.subarray(0,a));}let r=new Uint8Array(o),s=0;for(let i of t)r.set(i,s),s+=i.byteLength;return r}catch{return}}function se(n){return ot(tt(n,Zn))}function ot(n){if(n===void 0)return ie;let e=n.indexOf(nt);if(n.byteLength<=te){let o=ut(Buffer.from(n.buffer,n.byteOffset,n.byteLength).toString("utf8"));if(o.ok&&!(e>=0&&D(o.value)&&o.value.schemaVersion===ne))return {kind:"v1",value:o.value}}if(e<=0||e>te)return ie;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.subarray(0,e)));}catch{return ie}return !D(t)||t.schemaVersion!==ne?ie:{kind:"v2",header:t,body:n.subarray(e+1)}}var rt="actionId,content,input,schemaVersion,state",it="bytes,lines,mediaType,sha256",st="mediaType,range",at=/^[a-f0-9]{64}$/u,dt=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function tn(n,e){let t=p=>({code:p,outcome:"rejected"});if($(n)!==rt||n.schemaVersion!==ne||typeof n.actionId!="string"||!D(n.input)||!D(n.state)||!D(n.content)||$(n.content)!=="in,out")return {code:"INPUT_INVALID",outcome:"failed"};let o=n.content,r,s=o.in;if(s===null){if(e.byteLength!==0)return t(e.byteLength>U?"CONTENT_TOO_LARGE":"CONTENT_DIGEST_MISMATCH")}else {if(!D(s)||$(s)!==it||!en(s.mediaType)||!nn(s.bytes,U)||!nn(s.lines,oe)||typeof s.sha256!="string"||!at.test(s.sha256)||e.byteLength!==s.bytes)return t(e.byteLength>U?"CONTENT_TOO_LARGE":"CONTENT_DIGEST_MISMATCH");if(Pe(e)!==s.sha256||re(e)!==s.lines)return t("CONTENT_DIGEST_MISMATCH");let p;try{p=dt.decode(e);}catch{return t("CONTENT_ENCODING_INVALID")}r={mediaType:s.mediaType,text:p};}let i,a=o.out;if(a!==null){if(!D(a)||$(a)!==st||!en(a.mediaType))return t("CONTENT_SOURCE_UNSUPPORTED");let p=a.range;if(p!==null&&!pt(p))return t("CONTENT_SOURCE_UNSUPPORTED");i={mediaType:a.mediaType,...p===null?{}:{range:{startLine:p.startLine,lineCount:p.lineCount}}};}return {actionId:n.actionId,input:n.input,state:n.state,content:{...r===void 0?{}:{in:r},...i===void 0?{}:{out:i}}}}function on(n){return Object.hasOwn(n,"code")}function rn(n,e){let t=o=>({code:o,outcome:"rejected"});if(n?.in===void 0){if(e.in!==void 0)return t("CONTENT_SOURCE_UNSUPPORTED")}else if(e.in===void 0){if(n.in.required===true)return t("CONTENT_REQUIRED")}else if(e.in.mediaType!==n.in.mediaType)return t("CONTENT_SOURCE_UNSUPPORTED");if(n?.out===void 0){if(e.out!==void 0)return t("CONTENT_SOURCE_UNSUPPORTED")}else {if(e.out===void 0)return t("CONTENT_REQUIRED");if(e.out.mediaType!==n.out.mediaType||e.out.range!==void 0&&n.out.range!==true)return t("CONTENT_SOURCE_UNSUPPORTED")}}function ae(n,e){let{content:t,...o}=n,r=e===void 0?o:{...o,content:{bytes:e.body.byteLength,lines:re(e.body),sha256:Pe(e.body),...e.range===void 0?{}:{range:e.range}}},s=new TextEncoder().encode(`${JSON.stringify(r)}
2
+ `);if(e===void 0)return s;let i=new Uint8Array(s.byteLength+e.body.byteLength);return i.set(s,0),i.set(e.body,s.byteLength),i}function sn(n){if(n.body.byteLength>U||re(n.body)>oe)return {code:"CONTENT_TOO_LARGE",outcome:"failed"}}function ut(n){try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}}function $(n){return Object.keys(n).sort().join(",")}function D(n){if(n===null||typeof n!="object"||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function en(n){return typeof n=="string"&&x.includes(n)}function nn(n,e){return Number.isSafeInteger(n)&&n>=0&&n<=e}function pt(n){return D(n)&&$(n)==="lineCount,startLine"&&Number.isSafeInteger(n.startLine)&&n.startLine>=1&&Number.isSafeInteger(n.lineCount)&&n.lineCount>=1&&n.lineCount<=oe}var dn="CREWX_APP_JOB_CHANNEL",T=1,z=4096,Je=1e4,De=5e3,Ne=512,we=Object.freeze({min:3,max:16}),lt=["APP_JOB_BRIDGE_UNAVAILABLE","APP_JOB_BRIDGE_INVALID","APP_JOB_BRIDGE_TIMEOUT","APP_JOB_BRIDGE_CLOSED"],K=/^[A-Za-z0-9._:-]{1,128}$/u,ct=64,un=2147483647,W=class{#e="";#n=false;push(e){let t=[],o=e;for(;;){let r=o.indexOf(`
3
+ `);if(r===-1)return this.#n||(this.#e+=o,v(this.#e)>z&&(t.push({kind:"oversized"}),this.#e="",this.#n=true)),t;let s=o.slice(0,r);if(o=o.slice(r+1),this.#n){this.#n=false;continue}let i=this.#e+s;this.#e="",t.push(v(i)>z?{kind:"oversized"}:{kind:"line",line:i});}}};function pe(n){let e=JSON.stringify(n);if(v(e)>z)throw new TypeError("App job bridge message is over the line bound");return e}function ft(n){let e=le(n);if(e===void 0||e.v!==T||!pn(e.requestId)||!ln(e.seq))return;let t={v:T,requestId:e.requestId,seq:e.seq};switch(e.op){case "start":return _(e,["v","op","requestId","seq"],[])?{...t,op:"start"}:void 0;case "status":{if(!_(e,["v","op","requestId","seq"],["handle"]))return;if(e.handle===void 0)return {...t,op:"status"};let o=Ce(e.handle);return o===void 0?void 0:{...t,op:"status",handle:o}}case "cancel":{if(!_(e,["v","op","requestId","seq","handle"],[]))return;let o=Ce(e.handle);return o===void 0?void 0:{...t,op:"cancel",handle:o}}default:return}}function xe(n){let e=le(n);if(e===void 0||e.v!==T||!pn(e.requestId)||!ln(e.seq))return;let t={v:T,requestId:e.requestId,seq:e.seq};if(e.ok===false)return _(e,["v","requestId","seq","ok","code"],[])&&Oe.includes(e.code)?{...t,ok:false,code:e.code}:void 0;if(e.ok===true)switch(e.op){case "start":{if(!_(e,["v","requestId","seq","ok","op","outcome","job"],[]))return;let o=de(e.job),r=e.outcome;return o===void 0||r!=="started"&&r!=="attached"?void 0:{...t,ok:true,op:"start",outcome:r,job:o}}case "status":{if(!_(e,["v","requestId","seq","ok","op","job"],[]))return;if(e.job===null)return {...t,ok:true,op:"status",job:null};let o=de(e.job);return o===void 0?void 0:{...t,ok:true,op:"status",job:o}}case "cancel":{if(!_(e,["v","requestId","seq","ok","op","outcome","job"],[]))return;let o=de(e.job);return o===void 0||e.outcome!=="stopping"?void 0:{...t,ok:true,op:"cancel",outcome:"stopping",job:o}}default:return}}function yt(n){let e=le(n);if(e===void 0||e.v!==T||typeof e.runId!="string"||!K.test(e.runId)||!fe(e.generation))return;let t={v:T,runId:e.runId,generation:e.generation};switch(e.kind){case "heartbeat":return _(e,["v","kind","runId","generation"],[])?{...t,kind:"heartbeat"}:void 0;case "completed":return _(e,["v","kind","runId","generation"],[])?{...t,kind:"completed"}:void 0;case "progress":{if(!_(e,["v","kind","runId","generation","phase"],["completed","total","resumable"]))return;let{completed:o,total:r,resumable:s}=e;return !B(e.phase)||o!==void 0&&!ue(o)||r!==void 0&&!ue(r)||o!==void 0&&r!==void 0&&o>r||s!==void 0&&typeof s!="boolean"?void 0:{...t,kind:"progress",phase:e.phase,...o===void 0?{}:{completed:o},...r===void 0?{}:{total:r},...s===void 0?{}:{resumable:s}}}case "failed":return _(e,["v","kind","runId","generation","code","recoverable"],[])&&L(e.code)&&typeof e.recoverable=="boolean"?{...t,kind:"failed",code:e.code,recoverable:e.recoverable}:void 0;default:return}}function ke(n){let e=le(n);if(!(e===void 0||!_(e,["v","kind","runId","generation","reason"],[])||e.v!==T||e.kind!=="stop"||typeof e.runId!="string"||!K.test(e.runId)||!fe(e.generation)||!Z.includes(e.reason)))return {v:T,kind:"stop",runId:e.runId,generation:e.generation,reason:e.reason}}function je(n){let e=ce(n)?n:void 0;if(!(e===void 0||e.v!==T||!_t(e.fd))){if(e.role==="control"){let t=e.operations;return !_(e,["v","role","fd","operations"],[])||!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||!t.every(X)?void 0:{v:1,role:"control",fd:e.fd,operations:[...t]}}if(e.role==="run")return !_(e,["v","role","fd","runId","generation"],[])||typeof e.runId!="string"||!K.test(e.runId)||!fe(e.generation)?void 0:{v:1,role:"run",fd:e.fd,runId:e.runId,generation:e.generation}}}function Le(n){let e=n[dn];if(typeof e!="string"||v(e)>Ne)return;let t;try{t=JSON.parse(e);}catch{return}return je(t)}function At(n){let e=je(JSON.parse(JSON.stringify(n)));if(e===void 0)throw new TypeError("App job channel descriptor is invalid");let t=JSON.stringify(e);if(v(t)>Ne)throw new TypeError("App job channel descriptor is over its bound");return Object.freeze({CREWX_APP_JOB_CHANNEL:t})}function bt(n){return n==="schedule"?"schedule":"manual"}function mt(n){return de(n)}function de(n){let e=ce(n)?n:void 0;if(e===void 0||!_(e,["handle","state","stopReason","trigger","outcome","phase","completed","total","resumable","lastHeartbeatAt","startedAt","finishedAt","errorCode","recoverable"],[]))return;let t=Ce(e.handle),o=e.stopReason,r=e.outcome,s=e.phase,i=e.errorCode,a=e.recoverable;if(!(t===void 0||!_e.includes(e.state)||!(o===null||Z.includes(o))||o!==null&&e.state!=="stopping"||!Ee.includes(e.trigger)||!(r===null||he.includes(r))||!(s===null||B(s))||!(e.completed===null||ue(e.completed))||!(e.total===null||ue(e.total))||typeof e.resumable!="boolean"||!an(e.lastHeartbeatAt)||!cn(e.startedAt)||!an(e.finishedAt)||!(i===null||L(i))||!(a===null||typeof a=="boolean")))return {handle:t,state:e.state,stopReason:o,trigger:e.trigger,outcome:r,phase:s,completed:e.completed,total:e.total,resumable:e.resumable,lastHeartbeatAt:e.lastHeartbeatAt,startedAt:e.startedAt,finishedAt:e.finishedAt,errorCode:i,recoverable:a}}function Ce(n){if(!(!ce(n)||!_(n,["runId","generation"],[]))&&!(typeof n.runId!="string"||!K.test(n.runId)||!fe(n.generation)))return {runId:n.runId,generation:n.generation}}function le(n){if(v(n)>z)return;let e;try{e=JSON.parse(n);}catch{return}return ce(e)?e:void 0}function _(n,e,t){let o=new Set([...e,...t]);return Object.keys(n).every(r=>o.has(r))&&e.every(r=>Object.hasOwn(n,r))}function ce(n){if(n===null||typeof n!="object"||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function pn(n){return typeof n=="string"&&K.test(n)}function ln(n){return Number.isSafeInteger(n)&&n>=1&&n<=un}function fe(n){return Number.isSafeInteger(n)&&n>=1&&n<=un}function _t(n){return Number.isSafeInteger(n)&&n>=we.min&&n<=we.max}function ue(n){return Number.isSafeInteger(n)&&n>=0}function cn(n){return typeof n=="string"&&n.length>0&&n.length<=ct}function an(n){return n===null||cn(n)}function v(n){return new TextEncoder().encode(n).byteLength}var Ot=2147483647,M=class{#e;#n;#p;#y=randomUUID();#A=new W;#r=new Map;#s=new Set;#t;#l=0;#o=false;#c=false;#a=false;#d=null;constructor(e){this.#e=e.channel,this.#n=e.open??yn,this.#p=e.replyTimeoutMs??Je;}jobsFor(e){let t=this.#e;if(t.role!=="control"||e===void 0)return;let o=t.operations,r=ee.filter(i=>e.includes(i)&&o.includes(i));if(r.length===0)return;let s=i=>{if(!r.includes(i))throw new l("APP_JOB_NOT_GRANTED",null,{outcome:"rejected"})};return Object.freeze({granted:Object.freeze(r),start:async()=>{s("start");let i=await this.#u("start",{});if(i.ok===false)return {kind:"refused",code:i.code};if(i.op!=="start")throw new l("APP_JOB_BRIDGE_INVALID",null,{outcome:"failed"});return {kind:i.outcome,job:i.job}},status:async i=>{s("status");let a=await this.#u("status",i===void 0?{}:{handle:i});if(a.ok===false)return {kind:"refused",code:a.code};if(a.op!=="status")throw new l("APP_JOB_BRIDGE_INVALID",null,{outcome:"failed"});return {kind:"status",job:a.job}},cancel:async i=>{s("cancel");let a=await this.#u("cancel",{handle:i});if(a.ok===false)return {kind:"refused",code:a.code};if(a.op!=="cancel")throw new l("APP_JOB_BRIDGE_INVALID",null,{outcome:"failed"});return {kind:"stopping",job:a.job}}})}runFor(e){let t=this.#e;if(t.role!=="run"||!e)return;try{this.#f();}catch{return}let o={v:T,runId:t.runId,generation:t.generation},r=()=>this.#d,s=i=>{this.#o||this.#c||this.#t===void 0||this.#t.write(pe({...o,...i}));};return Object.freeze({handle:Object.freeze({runId:t.runId,generation:t.generation}),get stopRequested(){return r()!==null},get stopReason(){return r()},progress:i=>{if(!B(i.phase))throw new TypeError("progress phase must be a lower snake case name");if(i.completed!==void 0&&!fn(i.completed))throw new TypeError("progress completed must be a count");if(i.total!==void 0&&!fn(i.total))throw new TypeError("progress total must be a count");if(i.completed!==void 0&&i.total!==void 0&&i.completed>i.total)throw new TypeError("progress completed cannot exceed total");if(i.resumable!==void 0&&typeof i.resumable!="boolean")throw new TypeError("progress resumable must be boolean");this.#a||s({kind:"progress",phase:i.phase,...i.completed===void 0?{}:{completed:i.completed},...i.total===void 0?{}:{total:i.total},...i.resumable===void 0?{}:{resumable:i.resumable}});},heartbeat:()=>{this.#a||s({kind:"heartbeat"});},complete:()=>{s({kind:"completed"}),this.#a=true;},fail:(i,a)=>{if(!L(i))throw new TypeError("fail code must be an upper snake case code");if(typeof a!="boolean")throw new TypeError("fail recoverable must be boolean");s({kind:"failed",code:i,recoverable:a}),this.#a=true;},onStop:i=>{let a=r();return a!==null?(i(a),()=>{}):(this.#s.add(i),()=>{this.#s.delete(i);})}})}close(){this.#i("APP_JOB_BRIDGE_CLOSED");}async drain(e=De){if(this.#o)return;this.#c=true;let t=this.#t,o;try{if(t!==void 0){let r;try{r=t.drain();}catch{r=Promise.resolve();}await Promise.race([r.catch(()=>{}),new Promise(s=>{o=setTimeout(s,e);})]);}}finally{clearTimeout(o),this.close();}}#u(e,t){let o=this.#f(),r=this.#l+1;if(r>Ot)throw new l("APP_JOB_BRIDGE_CLOSED",null,{outcome:"failed"});this.#l=r;let s=`${this.#y}.${r}`,i=pe({v:T,op:e,requestId:s,seq:r,...t});return new Promise((a,p)=>{let u=setTimeout(()=>this.#i("APP_JOB_BRIDGE_TIMEOUT"),this.#p);this.#r.set(r,{op:e,requestId:s,resolve:a,reject:p,timer:u}),o.write(i);})}#f(){if(this.#o)throw new l("APP_JOB_BRIDGE_CLOSED",null,{outcome:"failed"});if(this.#t!==void 0)return this.#t;let e;try{e=this.#n(this.#e.fd);}catch{throw new l("APP_JOB_BRIDGE_UNAVAILABLE",null,{outcome:"failed"})}return e.onData(t=>this.#b(t)),e.onEnd(()=>this.#i("APP_JOB_BRIDGE_CLOSED")),this.#t=e,e}#b(e){for(let t of this.#A.push(e)){if(this.#o)return;if(this.#e.role==="run")t.kind==="line"&&this.#_(t.line);else if(t.kind==="oversized"){this.#i("APP_JOB_BRIDGE_INVALID");return}else this.#m(t.line);}}#m(e){let t=xe(e),o=t===void 0?void 0:this.#r.get(t.seq);if(t===void 0||o===void 0||o.requestId!==t.requestId||t.ok&&t.op!==o.op){this.#i("APP_JOB_BRIDGE_INVALID");return}clearTimeout(o.timer),this.#r.delete(t.seq),o.resolve(t);}#_(e){let t=this.#e;if(t.role!=="run")return;let o=ke(e);if(!(o===void 0||o.runId!==t.runId||o.generation!==t.generation)&&this.#d===null){this.#d=o.reason;for(let r of [...this.#s])try{r(o.reason);}catch{}}}#i(e){if(this.#o)return;this.#o=true;let t=[...this.#r.values()];this.#r.clear();for(let r of t)clearTimeout(r.timer),r.reject(new l(e,null,{outcome:"failed"}));this.#s.clear();let o=this.#t;this.#t=void 0,o?.close();}};function yn(n){let e=new Socket({fd:n,readable:true,writable:true});return e.setEncoding("utf8"),e.on("error",()=>{}),{write:t=>{e.write(`${t}
4
+ `);},drain:()=>new Promise(t=>{if(e.destroyed){t();return}e.write("",()=>t());}),onData:t=>{e.on("data",t);},onEnd:t=>{e.on("close",t);},close:()=>{e.destroy();}}}function fn(n){return Number.isSafeInteger(n)&&n>=0}var St=1;async function Tt(n,e,t=process.env.CREWX_WORKSPACE_ROOT??process.cwd(),o){return (await mn(n,e,t,void 0,true,void 0,o)).response}async function mn(n,e,t,o,r=true,s,i,a){let p=s!==void 0,u=h(e)?e:void 0,b=u?.input,m=u?.state,d=new n({state:h(m)?m:{},workspaceRoot:t,...i===void 0?{}:{context:i}}),E=h(b)?b:{},c=h(m)?m:d.emptyState(),f={},R=u!==void 0&&Object.hasOwn(u,"schedule"),I;try{let A;if(p){if(u===void 0||R)throw new l("INPUT_INVALID");let O=tn(u,s);if(on(O))throw new l(O.code,null,{outcome:O.outcome});(({actionId:A,input:E,state:c}=O)),f=O.content;}else {let O=R&&u!==void 0?Ve(u.schedule):void 0;if(!u||Object.keys(u).length!==(R?5:4)||!["schemaVersion","actionId","input","state"].every(hn=>Object.hasOwn(u,hn))||u.schemaVersion!==St||typeof u.actionId!="string"||!h(b)||!h(m)||R&&O===void 0)throw new l("INPUT_INVALID");A=u.actionId,E=b,c=m,I=O;}let y=V(n).find(({options:O})=>O.name===A),J=y===void 0?void 0:a?.jobsFor(y.options.jobAccess),P=y===void 0?void 0:a?.runFor(y.options.job!==void 0);if(d=new n({state:c,workspaceRoot:t,...i===void 0?{}:{context:i},...I===void 0?{}:{schedule:I},...J===void 0?{}:{jobs:J},...P===void 0?{}:{jobRun:P}}),await d.validate(A,E,c),!y)throw new l("INPUT_INVALID");if(I!==void 0&&(y.options.content!==void 0||!Ke(n)))throw new l("INPUT_INVALID");let F=d[y.methodName];if(typeof F!="function")throw new l("EXECUTION_FAILED");let N=rn(y.options.content,f);if(N)throw new l(N.code,null,{outcome:N.outcome});if(y.options.job!==void 0&&P===void 0)throw new l(ge,null,{outcome:"rejected"});let Y=Object.freeze({...f.in===void 0?{}:{in:Object.freeze({text:f.in.text})},...f.out===void 0?{}:{out:Object.freeze(f.out.range===void 0?{}:{range:Object.freeze({...f.out.range})})}}),q=()=>F.call(d,E,Y),w=r?await wt(q):await q();if(w!==void 0&&!h(w))throw new l("EXECUTION_FAILED");let C;if(f.out!==void 0){if(C=d.producedContent,C===void 0)throw new l("EXECUTION_FAILED","content.out was requested but setContent was never called");let O=sn(C);if(O)throw new l(O.code,null,{outcome:O.outcome})}else if(d.didSetContent)throw new l("EXECUTION_FAILED","setContent was called but the request asked for no content.out");let Me=d.didRequestSchedule;return {response:{...d.didSetState?{state:d.state}:{},...w===void 0?{}:{result:w},...Me===void 0?{}:{schedule:{enabled:Me.enabled}}},...C===void 0?{}:{answer:C}}}catch(A){let y,J=A,P=A instanceof l?A:void 0;if(P)y={code:P.code,detail:P.detail,outcome:P.outcome};else try{y=d.mapError(A);}catch(C){y={code:"EXECUTION_FAILED",detail:null},J=C;}let F=Jt(y?.code),N=F?y.code:"EXECUTION_FAILED",Y=typeof y?.detail=="string"?y.detail:null,q=F?Re(y.outcome):"failed",w;try{w=d.errorState(N,Y,{input:E,state:c});}catch(C){J=new AggregateError([J,C],"App error handling failed"),w=d.emptyState();}return o?.(N,J,{outcome:q,detail:Y,expected:P!==void 0&&J===P}),{response:{outcome:q,errorCode:N,state:h(w)?w:d.emptyState()}}}}async function Rt(n,e={}){let t=It(e.jobBridge);try{await Pt(n,e,t);}finally{await t?.drain();}}function It(n){if(n===null)return;if(n!==void 0)return new M(n);let e=Le(process.env);return e===void 0?void 0:new M({channel:e})}async function Pt(n,e,t){let o=e.output??process.stdout,r,s;if(e.preloadedInput!==void 0)r=e.preloadedInput.value,s=e.preloadedInput.body;else {let d=se(e.inputFd??0);d.kind==="v1"?r=d.value:d.kind==="v2"&&(r=d.header,s=d.body);}let i=s!==void 0,a=e.context??Ie(),p=false,u=(d,E,c)=>{p=true,e.onFailure?.(d,E,c);},b;try{b=await mn(n,r,process.env.CREWX_WORKSPACE_ROOT??process.cwd(),u,e.consoleManaged!==!0,s,a,t);}catch(d){u("EXECUTION_FAILED",d),b={response:An(e.emptyState)};}Ct(b.response)&&!p&&u(b.response.errorCode,void 0,{outcome:b.response.outcome,detail:null,expected:false});let m;try{let d=(e.sanitize??bn)(b.response);m=i?ae(d,b.answer):`${JSON.stringify(d)}
5
+ `;}catch(d){u("EXECUTION_FAILED",d);let E=An(e.emptyState);try{let c=(e.sanitize??bn)(E);m=i?ae(c):`${JSON.stringify(c)}
6
+ `;}catch(c){u("EXECUTION_FAILED",c),m=i?ae(E):`${JSON.stringify(E)}
7
+ `;}}o.write(m);}async function wt(n){let e=["log","info","debug"],t=new Map;for(let o of e)t.set(o,console[o]),console[o]=(...r)=>process.stderr.write(`${format(...r)}
8
+ `);try{return await n()}finally{for(let o of e)console[o]=t.get(o);}}function An(n={}){return {outcome:"failed",errorCode:"EXECUTION_FAILED",state:{...n,error:{code:"EXECUTION_FAILED",detail:null}}}}function Ct(n){return (n.outcome==="failed"||n.outcome==="rejected")&&typeof n.errorCode=="string"}function Jt(n){return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,127}$/u.test(n)}function bn(n){return n}var Be={depth:null,maxArrayLength:null,maxStringLength:null},ve=class extends Writable{#e="buffer";#n=[];_write(e,t,o){if(this.#e==="buffer"){this.#n.push(typeof e=="string"?e:Uint8Array.from(e)),o();return}if(this.#e==="discard"){o();return}process.stderr.write(e,o);}flushToStderr(){this.#e="stderr";for(let e of this.#n)process.stderr.write(e);this.#n=[];}discard(){this.#e="discard",this.#n=[];}};async function xt(n,e={}){let t=process.stdout,o=t.write.bind(t),r=new ve,s=new Console({stdout:r,stderr:r,inspectOptions:{...Be}});globalThis.console=s;let i=false,a="-",p="-",u,b=false,m,d;try{let f=jt(e.inputFd??0);a=Lt(f.value),p=ye(process.env.CREWX_APP_REQUEST_ID),u=new Date().toISOString();try{m=await n();}catch(A){b=!0,d=A;}let R=m?.default;if(!b&&R?.devtools?.log===!0?(Object.assign(inspect.defaultOptions,Be),E(u),r.flushToStderr()):r.discard(),b){c("EXECUTION_FAILED",d),Ue(o,e,c);return}try{if(typeof m?.runSkillApp!="function")throw new TypeError("App module does not export runSkillApp");let A={sanitize:e.sanitize,emptyState:e.emptyState??kt(R),preloadedInput:f.body===void 0?{value:f.value}:{value:f.value,body:f.body},onFailure:c,consoleManaged:!0,output:{write:o},jobBridge:e.jobBridge};await m.runSkillApp(R,A);}catch(A){c("EXECUTION_FAILED",A),Ue(o,e,c);}}catch(f){c("EXECUTION_FAILED",f),Ue(o,e,c);}finally{process.exitCode=0;}function E(f){i||(process.stderr.write(`[crewx-app] ${f??new Date().toISOString()} ${ye(a)} req=${p}
9
+ `),i=true);}function c(f,R,I){E();let A=I?.expected===true&&I.detail?` ${ye(I.detail)}`:"";process.stderr.write(`[crewx-app] ${I?.outcome??"failed"} ${ye(f)}${A}
10
+ `),R!==void 0&&I?.expected!==true&&process.stderr.write(`${inspect(R,Be)}
11
+ `);}}function kt(n){if(typeof n=="function")try{let t=new n({workspaceRoot:process.cwd()}).emptyState();return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function jt(n){let e=se(n);return e.kind==="v1"?{value:e.value}:e.kind==="v2"?{value:e.header,body:e.body}:{value:void 0}}function Lt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&typeof n.actionId=="string"?n.actionId:"-"}function ye(n){return typeof n!="string"||n.length===0?"-":n.replace(/[\u0000-\u001f\u007f\u2028\u2029]/gu,"_")}function Ue(n,e,t){let o={code:"EXECUTION_FAILED",detail:null},s={outcome:"failed",errorCode:"EXECUTION_FAILED",state:e.emptyState!==null&&typeof e.emptyState=="object"&&!Array.isArray(e.emptyState)?{...e.emptyState,error:o}:{error:o}},i=s;try{i=(e.sanitize??Bt)(s);}catch(a){t("EXECUTION_FAILED",a);}n(`${JSON.stringify(i)}
12
+ `);}function Bt(n){return n}export{Ne as APP_JOB_BRIDGE_CHANNEL_MAX_BYTES,De as APP_JOB_BRIDGE_DRAIN_TIMEOUT_MS,dn as APP_JOB_BRIDGE_ENV,lt as APP_JOB_BRIDGE_ERROR_CODES,we as APP_JOB_BRIDGE_FD,z as APP_JOB_BRIDGE_MAX_LINE_BYTES,Je as APP_JOB_BRIDGE_REPLY_TIMEOUT_MS,T as APP_JOB_BRIDGE_VERSION,$e as APP_JOB_CAPABILITY,ze as APP_JOB_CAPABILITY_VERSION,j as APP_JOB_DEADLINE_MS,Jn as APP_JOB_MAX_PER_APP,ee as APP_JOB_OPERATIONS,he as APP_JOB_OUTCOMES,Oe as APP_JOB_REFUSAL_CODES,ge as APP_JOB_RUN_REQUIRED,_e as APP_JOB_STATES,Cn as APP_JOB_STOP_GRACE_MS,Z as APP_JOB_STOP_REASONS,Ee as APP_JOB_TRIGGERS,On as APP_SCHEDULE_ACTOR_KIND,gn as APP_SCHEDULE_INERT_COMMAND,be as APP_SCHEDULE_INSTANCE_PREFIX,H as APP_SCHEDULE_INTERVALS_MINUTES,En as APP_SCHEDULE_MAX_PER_APP,qe as APP_SCHEDULE_PERIODIC_REASONS,k as APP_SCHEDULE_TIMEOUT_MS,$n as APP_TOOLS_FILE,zn as APP_TOOLS_SCHEMA_VERSION,Wn as APP_TOOL_ENTRY,l as AppError,M as AppJobBridge,W as AppJobLineReader,Te as CrewXApp,Sn as SCHEDULE_TRIGGERS,Ze as SKILL_BACKEND_ENV_NAMES,jn as Tool,bt as appJobTriggerForActor,At as buildAppJobChannelEnvironment,pe as encodeAppJobLine,Tt as executeAppRequest,Ln as generateManifest,Ye as generateToolDeclarations,V as getToolDeclarations,xn as hasAppJobCapability,L as isAppJobCode,Se as isAppJobDeadlineMs,X as isAppJobOperation,B as isAppJobPhase,He as isAppScheduleCode,Xe as isAppScheduleIntervalMinutes,Ge as isAppSchedulePeriodicReason,me as isAppScheduleTimeoutMs,Kn as isSkillBackendEnv,yn as openInheritedAppJobTransport,je as parseAppJobChannel,xe as parseAppJobControlReply,ft as parseAppJobControlRequest,ke as parseAppJobRunPush,yt as parseAppJobRunReport,mt as parseAppJobView,Ie as readAppContext,Le as readAppJobChannel,xt as runAppEntry,Rt as runSkillApp};