@shogo-ai/worker 2.0.20 → 2.1.1

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 (2) hide show
  1. package/dist/cli.mjs +31 -31
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -1,30 +1,30 @@
1
- import{createRequire as y$}from"node:module";var A$=Object.defineProperty;var N$=($)=>$;function B$($,X){this[$]=N$.bind(null,X)}var F$=($,X)=>{for(var Y in X)A$($,Y,{get:X[Y],enumerable:!0,configurable:!0,set:B$.bind(X,Y)})};var T$=($,X)=>()=>($&&(X=$($=0)),X);var y0=y$(import.meta.url);var U2={};F$(U2,{runGit:()=>y,isGitRepo:()=>Y0,gitIsAvailable:()=>E0,gitFetchUnshallow:()=>O0,gitFetchAndReset:()=>X0,commitAndPush:()=>Y6,cloneProject:()=>v0,buildGitUrl:()=>$0});import{spawn as s$,execFile as t$}from"node:child_process";import{existsSync as R0}from"node:fs";import{join as b0}from"node:path";import{promisify as $6}from"node:util";async function E0($=!1){if(t!==null&&!$)return t;try{await X6("git",["--version"],{timeout:3000}),t=!0}catch{t=!1}return t}function $0($,X){return`${$.replace(/\/+$/,"")}/api/projects/${X}/git`}function y($,X={}){let{cwd:Y,env:Z,timeoutMs:z=300000,logger:J}=X;return new Promise((K,V)=>{let H=s$("git",$,{cwd:Y,env:{...process.env,...Z},stdio:["ignore","pipe","pipe"]}),q="",Q="",G=[],k=[];H.stdout.setEncoding("utf-8"),H.stderr.setEncoding("utf-8"),H.stdout.on("data",(W)=>{if(G.push(W),J)J.log(W.trimEnd())}),H.stderr.on("data",(W)=>{if(k.push(W),J)J.warn(W.trimEnd())});let C=setTimeout(()=>{try{H.kill("SIGKILL")}catch{}V(Error(`git ${$[0]} timed out after ${z}ms`))},z);H.on("error",(W)=>{clearTimeout(C),V(W)}),H.on("close",(W)=>{clearTimeout(C),q=G.join(""),Q=k.join("");let L=W??-1;if(L===0)K({stdout:q,stderr:Q,exitCode:L});else{let O=Error(`git ${$[0]} exited with code ${L}: ${Q.slice(0,500)}`);O.exitCode=L,O.stdout=q,O.stderr=Q,V(O)}})})}async function v0($){let{apiUrl:X,apiKey:Y,projectId:Z,localDir:z,shallow:J=!0,logger:K,timeoutMs:V}=$;if(R0(b0(z,".git")))throw Error(`cloneProject: ${z}/.git already exists; use gitFetchAndReset instead`);let H=$0(X,Z),q=["-c",`http.extraHeader=Authorization: Bearer ${Y}`,"clone"];if(J)q.push("--depth=1");return q.push(H,z),await y(q,{logger:K,timeoutMs:V}),{commitSha:(await y(["rev-parse","HEAD"],{cwd:z,logger:K,timeoutMs:1e4})).stdout.trim()}}async function X0($){let{apiUrl:X,apiKey:Y,projectId:Z,localDir:z,branch:J="HEAD",logger:K,timeoutMs:V}=$,H=$0(X,Z),q=["-c",`http.extraHeader=Authorization: Bearer ${Y}`];return await y([...q,"fetch",H,J],{cwd:z,logger:K,timeoutMs:V}),await y(["reset","--hard","FETCH_HEAD"],{cwd:z,logger:K,timeoutMs:V}),{commitSha:(await y(["rev-parse","HEAD"],{cwd:z,logger:K,timeoutMs:1e4})).stdout.trim()}}async function O0($){let{apiUrl:X,apiKey:Y,projectId:Z,localDir:z,logger:J,timeoutMs:K}=$,V=$0(X,Z),H=["-c",`http.extraHeader=Authorization: Bearer ${Y}`];if(R0(b0(z,".git","shallow")))await y([...H,"fetch","--unshallow",V],{cwd:z,logger:J,timeoutMs:K})}async function Y6($){let{apiUrl:X,apiKey:Y,projectId:Z,localDir:z,message:J,branch:K="HEAD",authorEmail:V,authorName:H,logger:q,timeoutMs:Q}=$,G=$0(X,Z),k={};if(V)k.GIT_AUTHOR_EMAIL=V,k.GIT_COMMITTER_EMAIL=V;if(H)k.GIT_AUTHOR_NAME=H,k.GIT_COMMITTER_NAME=H;await y(["add","-A"],{cwd:z,env:k,logger:q,timeoutMs:Q});let C=!1;try{await y(["diff","--cached","--quiet"],{cwd:z,env:k,logger:q,timeoutMs:Q})}catch{C=!0}if(!C)return{committed:!1};await y(["commit","-m",J,"--no-verify","--trailer",`Co-authored-by: ${H||process.env.SHOGO_AGENT_GIT_NAME||"Shogo Agent"} <${V||process.env.SHOGO_AGENT_GIT_EMAIL||"agent@shogo.ai"}>`],{cwd:z,env:k,logger:q,timeoutMs:Q});let L=(await y(["rev-parse","HEAD"],{cwd:z,env:k,logger:q,timeoutMs:1e4})).stdout.trim(),O=["-c",`http.extraHeader=Authorization: Bearer ${Y}`];return await y([...O,"push",G,K],{cwd:z,env:k,logger:q,timeoutMs:Q}),{committed:!0,commitSha:L}}function Y0($){return R0(b0($,".git"))}var X6,t=null;var w0=T$(()=>{X6=$6(t$)});import{Command as i1}from"commander";import L$ from"picocolors";import w from"picocolors";import{existsSync as h6}from"node:fs";import{readFileSync as x$,writeFileSync as M$,existsSync as D$,chmodSync as P$}from"node:fs";import{hostname as S$}from"node:os";import{homedir as _$}from"node:os";import{join as x}from"node:path";import{mkdirSync as V0}from"node:fs";var h=x(_$(),".shogo"),j=x(h,"config.json"),e1=x(h,"credentials.json"),o=x(h,"device-id"),l=x(h,"worker.pid"),_0=x(h,"logs"),q0=x(_0,"worker.log"),H0=x(_0,"worker.err.log"),r=x(h,"runtime"),S=x(r,process.platform==="win32"?"agent-runtime.exe":"agent-runtime"),e=x(r,"version.json"),Q0=x(h,"projects");function g($,X=Q0){return x(X,$)}function m(){V0(h,{recursive:!0,mode:448}),V0(_0,{recursive:!0,mode:448})}function s0(){m(),V0(r,{recursive:!0,mode:448})}function t0($=Q0){m(),V0($,{recursive:!0,mode:448})}var x0={cloudUrl:"https://studio.shogo.ai",port:8002,projectsDir:Q0};function I(){if(!D$(j))return{};try{return JSON.parse(x$(j,"utf-8"))}catch($){throw Error(`Corrupt config at ${j}: ${$.message}`)}}function s($){m(),M$(j,JSON.stringify($,null,2),{mode:384}),P$(j,384)}function $2($,X){return{...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))}}function R($={}){let X=I(),Y={apiKey:process.env.SHOGO_API_KEY,cloudUrl:process.env.SHOGO_CLOUD_URL,name:process.env.SHOGO_INSTANCE_NAME,workerDir:process.env.SHOGO_WORKER_DIR,port:process.env.PORT?parseInt(process.env.PORT,10):void 0,projectsDir:process.env.SHOGO_PROJECTS_DIR},Z=$2($2(X,Y),$);if(!Z.apiKey)throw Error("No API key. Run `shogo login` or pass --api-key / set SHOGO_API_KEY.");return{apiKey:Z.apiKey,cloudUrl:Z.cloudUrl??x0.cloudUrl,name:Z.name??S$(),workerDir:Z.workerDir??process.cwd(),port:Z.port??x0.port,projectsDir:Z.projectsDir??x0.projectsDir}}import{spawn as R$}from"node:child_process";import{existsSync as b$,openSync as X2,readFileSync as E$,unlinkSync as v$,writeFileSync as h$}from"node:fs";function G0(){if(!b$(l))return null;let $=E$(l,"utf-8").trim(),X=parseInt($,10);return Number.isFinite(X)?X:null}function W0($){try{return process.kill($,0),!0}catch{return!1}}function M0(){try{v$(l)}catch{}}function Y2($){m();let X=G0();if(X&&W0(X))throw Error(`Worker already running (pid=${X}). Run \`shogo worker stop\` first.`);if(X)M0();let Y=$.inheritStdio?["ignore","inherit","inherit"]:["ignore",X2(q0,"a"),X2(H0,"a")],Z=R$($.runner,[$.entry],{cwd:$.cwd,env:$.env,detached:!!$.detach,stdio:Y});if(!Z.pid)throw Error("Failed to spawn worker process.");if(h$(l,String(Z.pid),{mode:384}),$.detach)Z.unref();return{pid:Z.pid,child:Z}}function Z2($="SIGTERM"){let X=G0();if(!X)return{killedPid:null};if(!W0(X))return M0(),{killedPid:null};try{process.kill(X,$)}catch{}return M0(),{killedPid:X}}import M from"picocolors";import{existsSync as m$}from"node:fs";import{request as j$}from"node:http";function J2($,X=process.env){let Y=(J)=>J&&J.trim().length>0?J.trim():void 0,Z=Y($);if(Z)return{url:z2(Z),source:"flag"};let z=[["HTTPS_PROXY",X.HTTPS_PROXY],["https_proxy",X.https_proxy],["HTTP_PROXY",X.HTTP_PROXY],["http_proxy",X.http_proxy]];for(let[J,K]of z){let V=Y(K);if(V)return{url:z2(V),source:J}}return null}function z2($){if(/^https?:\/\//i.test($))return $;return`http://${$}`}function D0($,X){if(!X)return $;return{...$,HTTPS_PROXY:$.HTTPS_PROXY??X.url,https_proxy:$.https_proxy??X.url,HTTP_PROXY:$.HTTP_PROXY??X.url,http_proxy:$.http_proxy??X.url}}async function K2($,X="api.shogo.ai",Y=5000){return new Promise((Z)=>{let z=!1,J=(K)=>{if(z)return;z=!0,Z(K)};try{let K=new URL($.url),V=K.hostname,H=K.port?parseInt(K.port,10):K.protocol==="https:"?443:80,q=j$({method:"CONNECT",host:V,port:H,path:`${X}:443`,timeout:Y});q.on("connect",(Q)=>{q.destroy();let G=Q.statusCode??0;if(G===200)J({ok:!0,detail:`CONNECT ${X}:443 → 200 (via ${V}:${H})`});else if(G===407)J({ok:!1,detail:`407 Proxy Authentication Required — check credentials in ${$.source}`});else J({ok:!1,detail:`CONNECT → HTTP ${G}`})}),q.on("timeout",()=>{q.destroy(),J({ok:!1,detail:`timeout after ${Y}ms`})}),q.on("error",(Q)=>{let G=Q.code?` (${Q.code})`:"";J({ok:!1,detail:`${Q.message}${G}`})}),q.end()}catch(K){J({ok:!1,detail:K?.message??"unknown error"})}})}function V2($){let X;try{X=new URL($)}catch{return[]}let Y=X.host,Z=X.protocol.replace(":","")||"https",z=X.hostname.split("."),J=z.length>=2?z.slice(-2).join("."):X.hostname;return[{url:`${Z}://${Y}`,host:Y,purpose:"control",criticality:"fatal"},{url:`${Z}://api-direct.${J}`,host:`api-direct.${J}`,purpose:"tunnel-direct",criticality:"graceful"},{url:`${Z}://artifacts.${J}`,host:`artifacts.${J}`,purpose:"artifacts",criticality:"graceful"}]}var I$=5000;async function u$($,X){try{let Y=new AbortController,Z=setTimeout(()=>Y.abort(),X),z=await fetch(`${$.replace(/\/$/,"")}/health`,{signal:Y.signal}).catch(()=>null);if(clearTimeout(Z),!z)return{ok:!1,detail:"no response (firewall? DNS?)"};return{ok:!0,detail:`HTTP ${z.status}`}}catch(Y){return{ok:!1,detail:Y?.message??"unknown error"}}}var q2=($)=>{let X=[{name:"Runtime (node >= 20)",criticality:"fatal",async run(){let[Z]=process.versions.node.split(".").map(Number);return(Z??0)>=20?{ok:!0,detail:`node v${process.versions.node}`}:{ok:!1,detail:`node v${process.versions.node} — need >=20`}}},{name:"Worker directory exists",criticality:"fatal",async run(){return m$($.workerDir)?{ok:!0,detail:$.workerDir}:{ok:!1,detail:`${$.workerDir} does not exist`}}}];if($.proxy)X.push({name:`Proxy reachable (${f$($.proxy.url)})`,criticality:"fatal",async run(){return K2($.proxy)}});let Y=V2($.cloudUrl);for(let Z of Y)X.push({name:`Reach ${Z.host}${Z.purpose!=="control"?M.dim(` (${Z.purpose})`):""}`,criticality:Z.criticality,run:()=>u$(Z.url,I$)});return X.push({name:"API key valid",criticality:"fatal",async run(){try{let Z=await fetch(`${$.cloudUrl}/api/instances/heartbeat`,{method:"POST",headers:{"content-type":"application/json","x-api-key":$.apiKey},body:JSON.stringify({hostname:"preflight",name:"preflight",os:"preflight",arch:"preflight",metadata:{preflight:!0}})});if(Z.status===401||Z.status===403)return{ok:!1,detail:`HTTP ${Z.status} — key rejected`};return Z.ok?{ok:!0,detail:`HTTP ${Z.status}`}:{ok:!1,detail:`HTTP ${Z.status}`}}catch(Z){return{ok:!1,detail:Z?.message??"unknown error"}}}}),X};function f$($){try{return new URL($).host}catch{return $}}async function H2($){console.log(M.bold(`
1
+ import{createRequire as br}from"node:module";var vr=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(o){r=[o]}if(r)throw r[0];return t};var Pe=br(import.meta.url);import{spawn as Vr,execFile as Yr}from"node:child_process";import{existsSync as _e}from"node:fs";import{join as Ae}from"node:path";import{promisify as Xr}from"node:util";async function wt(e=!1){if(ee!==null&&!e)return ee;try{await zr("git",["--version"],{timeout:3000}),ee=!0}catch{ee=!1}return ee}function de(e,t){return`${e.replace(/\/+$/,"")}/api/projects/${t}/git`}function P(e,t={}){let{cwd:r,env:o,timeoutMs:n=300000,logger:i}=t;return new Promise((s,a)=>{let c=Vr("git",e,{cwd:r,env:{...process.env,...o},stdio:["ignore","pipe","pipe"]}),l="",u="",p=[],m=[];c.stdout.setEncoding("utf-8"),c.stderr.setEncoding("utf-8"),c.stdout.on("data",(d)=>{if(p.push(d),i)i.log(d.trimEnd())}),c.stderr.on("data",(d)=>{if(m.push(d),i)i.warn(d.trimEnd())});let f=setTimeout(()=>{try{c.kill("SIGKILL")}catch{}a(Error(`git ${e[0]} timed out after ${n}ms`))},n);c.on("error",(d)=>{clearTimeout(f),a(d)}),c.on("close",(d)=>{clearTimeout(f),l=p.join(""),u=m.join("");let w=d??-1;if(w===0)s({stdout:l,stderr:u,exitCode:w});else{let h=Error(`git ${e[0]} exited with code ${w}: ${u.slice(0,500)}`);h.exitCode=w,h.stdout=l,h.stderr=u,a(h)}})})}async function yt(e){let{apiUrl:t,apiKey:r,projectId:o,localDir:n,shallow:i=!0,logger:s,timeoutMs:a}=e;if(_e(Ae(n,".git")))throw Error(`cloneProject: ${n}/.git already exists; use gitFetchAndReset instead`);let c=de(t,o),l=["-c",`http.extraHeader=Authorization: Bearer ${r}`,"clone"];if(i)l.push("--depth=1");return l.push(c,n),await P(l,{logger:s,timeoutMs:a}),{commitSha:(await P(["rev-parse","HEAD"],{cwd:n,logger:s,timeoutMs:1e4})).stdout.trim()}}async function me(e){let{apiUrl:t,apiKey:r,projectId:o,localDir:n,branch:i="HEAD",logger:s,timeoutMs:a}=e,c=de(t,o),l=["-c",`http.extraHeader=Authorization: Bearer ${r}`];return await P([...l,"fetch",c,i],{cwd:n,logger:s,timeoutMs:a}),await P(["reset","--hard","FETCH_HEAD"],{cwd:n,logger:s,timeoutMs:a}),{commitSha:(await P(["rev-parse","HEAD"],{cwd:n,logger:s,timeoutMs:1e4})).stdout.trim()}}async function Oe(e){let{apiUrl:t,apiKey:r,projectId:o,localDir:n,logger:i,timeoutMs:s}=e,a=de(t,o),c=["-c",`http.extraHeader=Authorization: Bearer ${r}`];if(_e(Ae(n,".git","shallow")))await P([...c,"fetch","--unshallow",a],{cwd:n,logger:i,timeoutMs:s})}async function Qr(e){let{apiUrl:t,apiKey:r,projectId:o,localDir:n,message:i,branch:s="HEAD",authorEmail:a,authorName:c,logger:l,timeoutMs:u}=e,p=de(t,o),m={};if(a)m.GIT_AUTHOR_EMAIL=a,m.GIT_COMMITTER_EMAIL=a;if(c)m.GIT_AUTHOR_NAME=c,m.GIT_COMMITTER_NAME=c;await P(["add","-A"],{cwd:n,env:m,logger:l,timeoutMs:u});let f=!1;try{await P(["diff","--cached","--quiet"],{cwd:n,env:m,logger:l,timeoutMs:u})}catch{f=!0}if(!f)return{committed:!1};await P(["commit","-m",i,"--no-verify","--trailer",`Co-authored-by: ${c||process.env.SHOGO_AGENT_GIT_NAME||"Shogo Agent"} <${a||process.env.SHOGO_AGENT_GIT_EMAIL||"agent@shogo.ai"}>`],{cwd:n,env:m,logger:l,timeoutMs:u});let w=(await P(["rev-parse","HEAD"],{cwd:n,env:m,logger:l,timeoutMs:1e4})).stdout.trim(),h=["-c",`http.extraHeader=Authorization: Bearer ${r}`];return await P([...h,"push",p,s],{cwd:n,env:m,logger:l,timeoutMs:u}),{committed:!0,commitSha:w}}function he(e){return _e(Ae(e,".git"))}var zr,ee=null;var ge=vr(()=>{zr=Xr(Yr)});import{Command as Hn}from"commander";import wr from"picocolors";import g from"picocolors";import{existsSync as Ao}from"node:fs";import{readFileSync as kr,writeFileSync as Rr,existsSync as Pr,chmodSync as $r}from"node:fs";import{hostname as Tr}from"node:os";import{homedir as Sr}from"node:os";import{join as E}from"node:path";import{mkdirSync as ie}from"node:fs";var U=E(Sr(),".shogo"),W=E(U,"config.json"),Yn=E(U,"credentials.json"),Y=E(U,"device-id"),X=E(U,"worker.pid"),$e=E(U,"logs"),se=E($e,"worker.log"),ae=E($e,"worker.err.log"),z=E(U,"runtime"),_=E(z,process.platform==="win32"?"agent-runtime.exe":"agent-runtime"),Q=E(z,"version.json"),le=E(U,"projects");function B(e,t=le){return E(t,e)}function N(){ie(U,{recursive:!0,mode:448}),ie($e,{recursive:!0,mode:448})}function ze(){N(),ie(z,{recursive:!0,mode:448})}function Qe(e=le){N(),ie(e,{recursive:!0,mode:448})}var Te={cloudUrl:"https://studio.shogo.ai",port:8002,projectsDir:le};function j(){if(!Pr(W))return{};try{return JSON.parse(kr(W,"utf-8"))}catch(e){throw Error(`Corrupt config at ${W}: ${e.message}`)}}function Z(e){N(),Rr(W,JSON.stringify(e,null,2),{mode:384}),$r(W,384)}function Ze(e,t){return{...e,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))}}function A(e={}){let t=j(),r={apiKey:process.env.SHOGO_API_KEY,cloudUrl:process.env.SHOGO_CLOUD_URL,name:process.env.SHOGO_INSTANCE_NAME,workerDir:process.env.SHOGO_WORKER_DIR,port:process.env.PORT?parseInt(process.env.PORT,10):void 0,projectsDir:process.env.SHOGO_PROJECTS_DIR},o=Ze(Ze(t,r),e);if(!o.apiKey)throw Error("No API key. Run `shogo login` or pass --api-key / set SHOGO_API_KEY.");return{apiKey:o.apiKey,cloudUrl:o.cloudUrl??Te.cloudUrl,name:o.name??Tr(),workerDir:o.workerDir??process.cwd(),port:o.port??Te.port,projectsDir:o.projectsDir??Te.projectsDir}}import{spawn as Er}from"node:child_process";import{existsSync as Ir,openSync as et,readFileSync as xr,unlinkSync as Cr,writeFileSync as _r}from"node:fs";function ce(){if(!Ir(X))return null;let e=xr(X,"utf-8").trim(),t=parseInt(e,10);return Number.isFinite(t)?t:null}function ue(e){try{return process.kill(e,0),!0}catch{return!1}}function Ee(){try{Cr(X)}catch{}}function tt(e){N();let t=ce();if(t&&ue(t))throw Error(`Worker already running (pid=${t}). Run \`shogo worker stop\` first.`);if(t)Ee();let r=e.inheritStdio?["ignore","inherit","inherit"]:["ignore",et(se,"a"),et(ae,"a")],o=Er(e.runner,[e.entry],{cwd:e.cwd,env:e.env,detached:!!e.detach,stdio:r});if(!o.pid)throw Error("Failed to spawn worker process.");if(_r(X,String(o.pid),{mode:384}),e.detach)o.unref();return{pid:o.pid,child:o}}function rt(e="SIGTERM"){let t=ce();if(!t)return{killedPid:null};if(!ue(t))return Ee(),{killedPid:null};try{process.kill(t,e)}catch{}return Ee(),{killedPid:t}}import I from"picocolors";import{existsSync as Or}from"node:fs";import{request as Ar}from"node:http";function nt(e,t=process.env){let r=(i)=>i&&i.trim().length>0?i.trim():void 0,o=r(e);if(o)return{url:ot(o),source:"flag"};let n=[["HTTPS_PROXY",t.HTTPS_PROXY],["https_proxy",t.https_proxy],["HTTP_PROXY",t.HTTP_PROXY],["http_proxy",t.http_proxy]];for(let[i,s]of n){let a=r(s);if(a)return{url:ot(a),source:i}}return null}function ot(e){if(/^https?:\/\//i.test(e))return e;return`http://${e}`}function Ie(e,t){if(!t)return e;return{...e,HTTPS_PROXY:e.HTTPS_PROXY??t.url,https_proxy:e.https_proxy??t.url,HTTP_PROXY:e.HTTP_PROXY??t.url,http_proxy:e.http_proxy??t.url}}async function it(e,t="api.shogo.ai",r=5000){return new Promise((o)=>{let n=!1,i=(s)=>{if(n)return;n=!0,o(s)};try{let s=new URL(e.url),a=s.hostname,c=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80,l=Ar({method:"CONNECT",host:a,port:c,path:`${t}:443`,timeout:r});l.on("connect",(u)=>{l.destroy();let p=u.statusCode??0;if(p===200)i({ok:!0,detail:`CONNECT ${t}:443 → 200 (via ${a}:${c})`});else if(p===407)i({ok:!1,detail:`407 Proxy Authentication Required — check credentials in ${e.source}`});else i({ok:!1,detail:`CONNECT → HTTP ${p}`})}),l.on("timeout",()=>{l.destroy(),i({ok:!1,detail:`timeout after ${r}ms`})}),l.on("error",(u)=>{let p=u.code?` (${u.code})`:"";i({ok:!1,detail:`${u.message}${p}`})}),l.end()}catch(s){i({ok:!1,detail:s?.message??"unknown error"})}})}function st(e){let t;try{t=new URL(e)}catch{return[]}let r=t.host,o=t.protocol.replace(":","")||"https",n=t.hostname.split("."),i=n.length>=2?n.slice(-2).join("."):t.hostname;return[{url:`${o}://${r}`,host:r,purpose:"control",criticality:"fatal"},{url:`${o}://api-direct.${i}`,host:`api-direct.${i}`,purpose:"tunnel-direct",criticality:"graceful"},{url:`${o}://artifacts.${i}`,host:`artifacts.${i}`,purpose:"artifacts",criticality:"graceful"}]}var Mr=5000;async function Dr(e,t){try{let r=new AbortController,o=setTimeout(()=>r.abort(),t),n=await fetch(`${e.replace(/\/$/,"")}/health`,{signal:r.signal}).catch(()=>null);if(clearTimeout(o),!n)return{ok:!1,detail:"no response (firewall? DNS?)"};return{ok:!0,detail:`HTTP ${n.status}`}}catch(r){return{ok:!1,detail:r?.message??"unknown error"}}}var at=(e)=>{let t=[{name:"Runtime (node >= 20)",criticality:"fatal",async run(){let[o]=process.versions.node.split(".").map(Number);return(o??0)>=20?{ok:!0,detail:`node v${process.versions.node}`}:{ok:!1,detail:`node v${process.versions.node} — need >=20`}}},{name:"Worker directory exists",criticality:"fatal",async run(){return Or(e.workerDir)?{ok:!0,detail:e.workerDir}:{ok:!1,detail:`${e.workerDir} does not exist`}}}];if(e.proxy)t.push({name:`Proxy reachable (${Ur(e.proxy.url)})`,criticality:"fatal",async run(){return it(e.proxy)}});let r=st(e.cloudUrl);for(let o of r)t.push({name:`Reach ${o.host}${o.purpose!=="control"?I.dim(` (${o.purpose})`):""}`,criticality:o.criticality,run:()=>Dr(o.url,Mr)});return t.push({name:"API key valid",criticality:"fatal",async run(){try{let o=await fetch(`${e.cloudUrl}/api/instances/heartbeat`,{method:"POST",headers:{"content-type":"application/json","x-api-key":e.apiKey},body:JSON.stringify({hostname:"preflight",name:"preflight",os:"preflight",arch:"preflight",metadata:{preflight:!0}})});if(o.status===401||o.status===403)return{ok:!1,detail:`HTTP ${o.status} — key rejected`};return o.ok?{ok:!0,detail:`HTTP ${o.status}`}:{ok:!1,detail:`HTTP ${o.status}`}}catch(o){return{ok:!1,detail:o?.message??"unknown error"}}}}),t};function Ur(e){try{return new URL(e).host}catch{return e}}async function lt(e){console.log(I.bold(`
2
2
  Shogo Worker — Preflight
3
- `));let X=!1,Y=0;for(let Z of $){process.stdout.write(` ${M.dim("...")} ${Z.name}`);let z=await Z.run();if(process.stdout.write("\r"),z.ok)console.log(` ${M.green("✓")} ${Z.name}${z.detail?M.dim(` — ${z.detail}`):""}`);else if(Z.criticality==="graceful")console.log(` ${M.yellow("◦")} ${Z.name}${z.detail?M.dim(` — ${z.detail}`):""}${M.yellow(" (optional — worker will still start)")}`),Y++;else console.log(` ${M.red("✗")} ${Z.name}${z.detail?M.dim(` — ${z.detail}`):""}`),X=!0}if(!X&&Y===0)console.log(M.green(`
3
+ `));let t=!1,r=0;for(let o of e){process.stdout.write(` ${I.dim("...")} ${o.name}`);let n=await o.run();if(process.stdout.write("\r"),n.ok)console.log(` ${I.green("✓")} ${o.name}${n.detail?I.dim(` — ${n.detail}`):""}`);else if(o.criticality==="graceful")console.log(` ${I.yellow("◦")} ${o.name}${n.detail?I.dim(` — ${n.detail}`):""}${I.yellow(" (optional — worker will still start)")}`),r++;else console.log(` ${I.red("✗")} ${o.name}${n.detail?I.dim(` — ${n.detail}`):""}`),t=!0}if(!t&&r===0)console.log(I.green(`
4
4
  All checks passed.
5
- `));else if(!X)console.log(M.yellow(`
6
- Starting with ${Y} optional host(s) blocked. See docs/my-machines-networking.md.
7
- `));else console.log(M.red(`
5
+ `));else if(!t)console.log(I.yellow(`
6
+ Starting with ${r} optional host(s) blocked. See docs/my-machines-networking.md.
7
+ `));else console.log(I.red(`
8
8
  Preflight failed — fix blocking issues before starting.
9
- `));return!X}import{accessSync as n$,constants as d$,existsSync as g$}from"node:fs";import{delimiter as i$,join as p$}from"node:path";function u($={}){let X=$.env??process.env,Y=c$($);for(let J of Y)if(G2(J.path))return J;let Z=$.systemBinName??Q2(),z=a$(Z,X.PATH);if(z)return{path:z,source:"path"};return null}function c$($){let X=$.env??process.env,Y=[];if($.flag&&$.flag.trim())Y.push({path:$.flag.trim(),source:"flag"});let Z=X.SHOGO_AGENT_RUNTIME_BIN?.trim();if(Z)Y.push({path:Z,source:"env"});return Y.push({path:S,source:"home"}),Y}function Q2(){return process.platform==="win32"?"shogo-agent-runtime.exe":"shogo-agent-runtime"}function G2($){if(!g$($))return!1;try{if(process.platform==="win32")return!0;return n$($,d$.X_OK),!0}catch{return!1}}function a$($,X){if(!X)return null;for(let Y of X.split(i$)){if(!Y)continue;let Z=p$(Y,$);if(G2(Z))return Z}return null}function n($={}){let X=$.env??process.env,Y=[];if(Y.push("Error: agent-runtime binary not found."),Y.push(""),Y.push("Looked in (priority order):"),$.flag)Y.push(` --runtime-bin ${$.flag}`);if(X.SHOGO_AGENT_RUNTIME_BIN)Y.push(` $SHOGO_AGENT_RUNTIME_BIN = ${X.SHOGO_AGENT_RUNTIME_BIN}`);return Y.push(` ${S} (default install location)`),Y.push(` ${Q2()} on $PATH`),Y.push(""),Y.push("Fix:"),Y.push(" - Run `shogo runtime install` to download the latest binary, or"),Y.push(" - Pass `--runtime-bin <path>` to point at an existing build."),Y.join(`
10
- `)}import{spawn as Q6,spawnSync as G6}from"node:child_process";import{createHmac as S2,randomBytes as W6}from"node:crypto";import{existsSync as h0,mkdirSync as N2,readdirSync as R2}from"node:fs";import{createConnection as k6}from"node:net";import{tmpdir as O6}from"node:os";import{dirname as w6,join as p}from"node:path";import{spawnSync as P0}from"node:child_process";import{existsSync as o$,mkdirSync as l$,writeFileSync as k0}from"node:fs";import{join as i}from"node:path";var W2=1e5;function k2($){let X=parseInt($.RUNTIME_MEMORY_MB||"",10);if(!Number.isFinite(X)||X<=0)return null;let Y=parseInt($.RUNTIME_CPU_PERCENT||"0",10),Z=Number.isFinite(Y)&&Y>0?Y:0,z=parseInt($.RUNTIME_TASKS_MAX||"",10),J=Number.isFinite(z)&&z>0?z:4096;return{memoryMB:X,cpuPercent:Z,tasksMax:J}}function O2($,X){let Z=`--max-old-space-size=${Math.max(256,Math.floor(X*0.75))}`,z=$.NODE_OPTIONS?.trim();if(z){if(/--max-old-space-size=/.test(z))return;$.NODE_OPTIONS=`${z} ${Z}`}else $.NODE_OPTIONS=Z}function r$(){if(process.platform!=="linux")return!1;try{return P0("systemd-run",["--version"],{stdio:"ignore",timeout:3000}).status===0}catch{return!1}}function w2($){let{command:X,args:Y,limits:Z,scopeName:z,logger:J}=$;if(process.platform!=="linux"||!r$())return{command:X,args:Y,wrapped:!1};let K=["-p",`MemoryMax=${Z.memoryMB}M`,"-p",`MemoryHigh=${Math.max(128,Math.floor(Z.memoryMB*0.9))}M`,"-p",`TasksMax=${Z.tasksMax}`];if(Z.cpuPercent>0)K.push("-p",`CPUQuota=${Z.cpuPercent}%`);let V=["--user","--scope","--quiet","--collect",`--unit=${z}`,...K,"--",X,...Y];return J?.log(`[resource-limits] wrapping spawn in systemd scope ${z} (MemoryMax=${Z.memoryMB}M)`),{command:"systemd-run",args:V,wrapped:!0}}function C2($){let{pid:X,limits:Y,logger:Z}=$;if(process.platform!=="linux")return!1;let z="/sys/fs/cgroup";if(!o$(i(z,"cgroup.controllers")))return!1;let J=i(z,"shogo",`rt-${X}`);try{if(l$(J,{recursive:!0}),k0(i(J,"memory.max"),String(Y.memoryMB*1024*1024)),Y.cpuPercent>0){let K=Math.floor(Y.cpuPercent/100*W2);k0(i(J,"cpu.max"),`${K} ${W2}`)}try{k0(i(J,"pids.max"),String(Y.tasksMax))}catch{}return k0(i(J,"cgroup.procs"),String(X)),Z?.log(`[resource-limits] attached pid ${X} to cgroup ${J} (memory.max=${Y.memoryMB}M)`),!0}catch(K){return Z?.warn(`[resource-limits] direct cgroup attach failed for pid ${X}: ${K?.message??K}`),!1}}function L2($){let{pid:X,limits:Y,logger:Z}=$;if(process.platform!=="win32")return!1;let z=process.env.SHOGO_WINJOB_HELPER||"@shogo/winjob";try{let J=y0(z);if(typeof J.limitProcess!=="function")return!1;let K=J.limitProcess(X,{memoryBytes:Y.memoryMB*1024*1024,killOnClose:!0});if(K)Z?.log(`[resource-limits] attached pid ${X} to Job Object (${Y.memoryMB}M)`);return K}catch{return!1}}function e$($,X=process.platform){try{if(X==="win32"){let J=`$ErrorActionPreference='SilentlyContinue';$root=${$};$all=Get-CimInstance Win32_Process;$seen=@{};$stack=New-Object System.Collections.Stack;$stack.Push($root);$sum=0;while($stack.Count -gt 0){$id=$stack.Pop();if($seen[$id]){continue};$seen[$id]=$true;foreach($p in $all){if($p.ProcessId -eq $id){$sum+=$p.WorkingSetSize};if($p.ParentProcessId -eq $id){$stack.Push($p.ProcessId)}}};[math]::Floor($sum/1024)`,K=P0("powershell.exe",["-NoProfile","-NonInteractive","-Command",J],{encoding:"utf-8",timeout:1e4,windowsHide:!0});if(K.status!==0||!K.stdout)return null;let V=parseInt(K.stdout.trim(),10);return Number.isFinite(V)?V:null}let Y=P0("ps",["-o","rss=","-g",String($)],{encoding:"utf-8",timeout:5000});if(Y.status!==0||!Y.stdout)return null;let Z=0,z=!1;for(let J of Y.stdout.split(`
11
- `)){let K=parseInt(J.trim(),10);if(Number.isFinite(K))Z+=K,z=!0}return z?Z:null}catch{return null}}class S0{timer=null;consecutive=0;fired=!1;pid;ceilingMB;platform;intervalMs;strikes;logger;onBreach;constructor($){this.pid=$.pid,this.ceilingMB=$.ceilingMB,this.platform=$.platform??process.platform,this.intervalMs=$.intervalMs??parseInt(process.env.RUNTIME_RSS_WATCHDOG_MS||"15000",10),this.strikes=$.strikes??parseInt(process.env.RUNTIME_RSS_WATCHDOG_STRIKES||"2",10),this.logger=$.logger,this.onBreach=$.onBreach}start(){if(this.timer)return;this.timer=setInterval(()=>this.sample(),Math.max(2000,this.intervalMs));try{this.timer.unref?.()}catch{}}stop(){if(this.timer)clearInterval(this.timer),this.timer=null}sample(){if(this.fired)return;let $=e$(this.pid,this.platform);if($==null){this.consecutive=0;return}let X=Math.floor($/1024);if(X<=this.ceilingMB){this.consecutive=0;return}if(this.consecutive+=1,this.logger?.warn(`[resource-limits] pid ${this.pid} RSS ${X}MB over ceiling ${this.ceilingMB}MB (strike ${this.consecutive}/${this.strikes})`),this.consecutive>=this.strikes)this.fired=!0,this.stop(),this.onBreach(X)}}import{CloudFileTransport as j0}from"@shogo-ai/sdk/cloud-file-transport";import{killViteWatchFromPidfile as B2}from"@shogo-ai/sdk/vite-watch";import{watch as A2,statSync as Z6}from"node:fs";import{relative as DX,sep as z6,posix as J6}from"node:path";var K6=1500,V6=new Set(["node_modules",".git","dist","build",".vite",".cache"]),q6=[".shogo/"];function H6($){if(!$)return!0;return $.split("/").some((X)=>V6.has(X))}class Z0{rootDir;transport;debounceMs;logger;onFlush;mode;git;commitAndPush;watcher=null;pending=new Set;timer=null;flushing=!1;stopped=!1;constructor($){if(this.rootDir=$.rootDir,this.transport=$.transport,this.debounceMs=$.debounceMs??K6,this.logger=$.logger??console,this.onFlush=$.onFlush,this.mode=$.mode??"files",this.mode==="git"&&!$.git)throw Error('CloudSyncWatcher: mode: "git" requires the `git` option block');this.git=$.git,this.commitAndPush=$.commitAndPush??(async(X)=>{return(await Promise.resolve().then(() => (w0(),U2))).commitAndPush(X)})}start(){if(this.watcher)return;if(this.stopped)throw Error("CloudSyncWatcher: already stopped, build a fresh instance");try{this.watcher=A2(this.rootDir,{recursive:!0},($,X)=>{if(!X)return;this.handleEvent(String(X))})}catch($){this.logger.warn(`[CloudSyncWatcher] recursive watch failed (${$?.message??$}); falling back to root-only watch.`),this.watcher=A2(this.rootDir,(X,Y)=>{if(!Y)return;this.handleEvent(String(Y))})}}async stop(){if(this.stopped)return;if(this.stopped=!0,this.timer)clearTimeout(this.timer),this.timer=null;if(this.watcher){try{this.watcher.close()}catch{}this.watcher=null}if(this.pending.size>0)await this.flush()}handleEvent($){if(this.stopped)return;let X=$.split(z6).join(J6.sep);if(H6(X))return;try{let Y=`${this.rootDir}/${X}`;if(Z6(Y).isDirectory())return}catch{return}this.pending.add(X),this.scheduleFlush()}scheduleFlush(){if(this.timer)return;this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.debounceMs)}async flush(){if(this.flushing){this.scheduleFlush();return}if(this.pending.size===0)return;this.flushing=!0;let $=Array.from(this.pending);this.pending.clear();try{if(this.mode==="git")await this.flushGit($);else await this.flushFiles($)}catch(X){this.logger.error(`[CloudSyncWatcher] flush failed: ${X?.message??X}`);for(let Y of $)this.pending.add(Y);this.scheduleFlush()}finally{this.flushing=!1}}async flushFiles($){if($.length===0)return;let X=await this.transport.uploadFiles($);if(this.onFlush?.({uploaded:$,errors:X.errors.length}),X.errors.length>0)for(let Y of X.errors)this.logger.warn(`[CloudSyncWatcher] upload ${Y.path}: ${Y.message}`)}async flushGit($){if(!this.git)throw Error("CloudSyncWatcher: missing git options");let X=[],Y=[];for(let J of $)if(q6.some((K)=>J===K.slice(0,-1)||J.startsWith(K)))X.push(J);else Y.push(J);if(X.length>0){let J=await this.transport.uploadFiles(X);if(J.errors.length>0)for(let K of J.errors)this.logger.warn(`[CloudSyncWatcher] upload ${K.path}: ${K.message}`)}let Z=!1,z;if(Y.length>0){let J=`auto: ${new Date().toISOString()}`;try{let K=await this.commitAndPush({apiUrl:this.git.apiUrl,apiKey:this.git.apiKey,projectId:this.git.projectId,localDir:this.rootDir,message:J,branch:this.git.branch,authorEmail:this.git.authorEmail,authorName:this.git.authorName,logger:this.logger});Z=K.committed,z=K.commitSha}catch(K){throw K}}this.onFlush?.({uploaded:$,errors:0,committed:Z,commitSha:z})}}w0();var m0=37100,I0=37900,F2=1,C6=2,C0=16,L6=900000,U6=30000,A6=1000,N6=60000,T2=8,y2=300000,_2=3600000,B6=8,F6=120000,T6=900000,y6=60000,_6=500,x6=30000,x2=25000,M6=5000,D6=500,P6=process.env.SHOGO_PERF_LOG==="1";function L0($,X,Y,Z){if(!P6)return;console.log(`[shogo-perf] ${JSON.stringify({perf:"open",source:"worker",phase:$,projectId:X,openAttemptId:Y,atMs:Date.now(),...Z})}`)}var S6=($)=>({command:$,args:[]}),u0=null;function b2(){if(!u0)u0=W6(32).toString("hex");return u0}function M2($){return S2("sha256",b2()).update(`runtime:${$}`).digest("hex")}function R6($){return S2("sha256",b2()).update(`webhook:${$}`).digest("hex")}function D2($){let X=$.indexOf("?");if(X===-1)return{pathname:$,search:""};return{pathname:$.slice(0,X),search:$.slice(X)}}function P2($){try{return R2($).length===0}catch{return!0}}function f0($,X,Y){let Z=[];switch(Z.push(`Cannot spawn agent-runtime for project ${$}: no workspace directory available.`),Z.push(""),X){case"no-auto-pull-config":Z.push(" Reason: WorkerRuntimeManager was constructed without an `autoPull` config and no caller-provided `projectDir` was found on disk."),Z.push(" This usually means a programmatic embedder forgot to wire up enrichSpawnConfig "+"or autoPull. CLI users should not see this — please file a bug.");break;case"no-projects-dir":Z.push(" Reason: auto-pull is configured but `projectsDir` is empty. The worker needs a persistent root directory under which it can store cloned project workspaces.");break;case"auto-pull-disabled":Z.push(` Reason: auto-pull was disabled (--no-auto-pull) and the expected pre-pulled workspace at ${Y} is missing or empty.`);break}return Z.push(""),Z.push(" How to fix (pick one):"),Z.push(" 1. Re-enable auto-pull (default). Drop the --no-auto-pull flag and restart"),Z.push(" the worker. The first inbound request for this project will clone its"),Z.push(" workspace from Shogo Cloud into <projectsDir>/<projectId>/."),Z.push(""),Z.push(" 2. Pre-pull manually with `shogo project pull <projectId>` before starting"),Z.push(" the worker. Use this when you want full control over when the clone runs"),Z.push(" (slow links, scheduled maintenance windows, etc.)."),Z.push(""),Z.push(" 3. Point the worker at an existing workspace by setting either:"),Z.push(" --projects-dir <path> (per-invocation flag)"),Z.push(" SHOGO_PROJECTS_DIR=<path> (env var, persists across restarts)"),Z.push(" shogo config set projectsDir <path>"),Z.push(" Whichever path you pick must contain a subdirectory named after the "),Z.push(` project id (e.g. <path>/${$}/) populated with the project's source.`),Z.push(""),Z.push(" Docs: https://shogo.ai/docs/self-hosted-worker#workspace-seeding"),Z.join(`
12
- `)}class n0{opts;log;runtimes=new Map;usedPorts=new Set;spawnCommand;resolved=null;stopped=!1;resolvedLimits=void 0;watchers=new Map;pulledProjects=new Set;syncModes=new Map;constructor($={}){this.opts=$,this.log=$.logger??console,this.spawnCommand=$.spawnCommand??S6,this.sweepOrphanedViteWatches()}resolveBinary(){if(!this.resolved)this.resolved=this.opts.resolveBin?this.opts.resolveBin():u({flag:this.opts.runtimeBin,env:this.opts.env});return this.resolved}async resolveLocalUrl($,X){let{pathname:Y,search:Z}=D2($);if(!(Y.startsWith("/agent/")||Y==="/agent"))return null;if(!X){let K=this.getActiveProjects();if(K.length!==1)return null;X=K[0]}let z=await this.spawnConfigFor(X);if(!z)return this.log.warn(`[WorkerRuntimeManager] No spawn config for ${X} — set defaultSpawnConfig or enrichSpawnConfig`),null;let J=await this.ensureRunning(X,z);if(!J.agentPort)return null;return this.touch(X),`http://127.0.0.1:${J.agentPort}${Y}${Z}`}deriveRuntimeToken($){return M2($)}describeRejection($,X){let{pathname:Y}=D2($);if(!(Y.startsWith("/agent/")||Y==="/agent"))return{code:"CLI_WORKER_HAS_NO_DATA_API",message:`cli-worker only serves /agent/* paths; tried: ${Y}`};return{code:"CLI_WORKER_NO_PROJECT_FOR_PATH",message:`cli-worker received an /agent path without a single active project; projectId=${X??"none"}, path=${Y}`}}async spawnConfigFor($){let X=this.opts.defaultSpawnConfig;if(!X)return null;if(this.opts.enrichSpawnConfig)try{return await this.opts.enrichSpawnConfig($,X)}catch(Y){this.log.warn(`[WorkerRuntimeManager] enrichSpawnConfig failed for ${$}: ${Y?.message??Y}`)}return X}async ensureRunning($,X){if(this.stopped)throw Error("WorkerRuntimeManager is stopped");let Y=this.runtimes.get($);if(Y?.status==="failed"){let J=this.breakerCooldownMs(Y.breakerTrips),K=Date.now()-Y.lastFailureAt;if(K>=J)this.log.log(`[WorkerRuntimeManager] auto-heal: ${$} cooldown elapsed (${Math.round(K/1000)}s since trip #${Y.breakerTrips}) — `+"clearing circuit breaker and attempting a fresh spawn"),this.healBreaker(Y);else{let V=J-K;throw Error(`[WorkerRuntimeManager] cannot ensureRunning(${$}): ${Y.lastError??"runtime is in failed state"} Will auto-retry in ~${Math.ceil(V/1000)}s; call resetFailure(${$}) to retry immediately, or stop(${$}) to give up.`)}}X=await this.maybeAutoPull($,X);let Z=this.runtimes.get($);if(Z?.status==="running")return this.touch($),this.snapshot(Z);if(Z?.startPromise){let J=await Z.startPromise;return this.snapshot(J)}let z=Z??this.makeSlot($,X);if(!Z)this.runtimes.set($,z);z.spawnConfig=X,z.startPromise=this.doStart(z);try{let J=await z.startPromise;return this.enforceMaxRuntimes($),this.snapshot(J)}finally{z.startPromise=null}}enforceMaxRuntimes($){let X=this.opts.maxRuntimes;if(X==null||!Number.isFinite(X)||X<=0)return;let Y=Date.now(),Z=Array.from(this.runtimes.values()).filter((K)=>K.status==="running");if(Z.length<=X)return;let z=Z.filter((K)=>K.projectId!==$&&Y-K.lastUsedAt>=U6).sort((K,V)=>K.lastUsedAt-V.lastUsedAt),J=Z.length-X;for(let K of z){if(J<=0)break;let V=Y-K.lastUsedAt;this.log.log(`[WorkerRuntimeManager] maxRuntimes=${X} exceeded (${Z.length} running) — `+`LRU-evicting ${K.projectId} (idle ${Math.round(V/1000)}s)`),this.stop(K.projectId,"SIGTERM","lru-evict").catch((H)=>{this.log.warn(`[WorkerRuntimeManager] maxRuntimes eviction of ${K.projectId} failed: ${H?.message??H}`)}),J--}if(J>0)this.log.log(`[WorkerRuntimeManager] maxRuntimes=${X} still exceeded by ${J} after eviction pass — `+"remaining over-cap slots are mid-stream; will retry on next spawn / idle reap")}async ensurePulled($,X){return this.maybeAutoPull($,X)}async maybeAutoPull($,X){let Y=this.opts.autoPull;if(X.projectDir&&h0(X.projectDir))return X;if(!Y)throw Error(f0($,"no-auto-pull-config",null));if(!Y.projectsDir)throw Error(f0($,"no-projects-dir",null));if(!Y.enabled){let K=p(Y.projectsDir,$);if(h0(K)&&!P2(K))return{...X,projectDir:K};throw Error(f0($,"auto-pull-disabled",K))}if(this.pulledProjects.has($))return{...X,projectDir:p(Y.projectsDir,$)};let Z=p(Y.projectsDir,$),z=Y.logger??this.log,J={cloneProject:Y.gitOps?.cloneProject??v0,gitIsAvailable:Y.gitOps?.gitIsAvailable??E0,isGitRepo:Y.gitOps?.isGitRepo??Y0};this.pulledProjects.add($);try{N2(Z,{recursive:!0});let K=P2(Z),V=J.isGitRepo(Z),Q=(Y.useGit!==!1?await J.gitIsAvailable():!1)&&(K||V)?"git":"files";if(this.syncModes.set($,Q),Q==="git"){if(K){z.log(`[WorkerRuntimeManager] auto-pull: git clone project ${$} into ${Z}`);try{let G=await J.cloneProject({apiUrl:X.cloudUrl,apiKey:X.apiKey,projectId:$,localDir:Z,shallow:!0,logger:z});z.log(`[WorkerRuntimeManager] auto-pull: ${$} cloned at ${G.commitSha.slice(0,8)}`)}catch(G){z.warn(`[WorkerRuntimeManager] auto-pull: git clone failed for ${$} (${G?.message??G}); falling back to CloudFileTransport.downloadAll`),this.syncModes.set($,"files"),await this.fileTransportClone($,Z,X,z)}}else if(V)z.log(`[WorkerRuntimeManager] auto-pull: ${$} already has .git/; skipping clone`);if(this.syncModes.get($)==="git")await this.topUpShogoState($,Z,X,z)}else if(K)await this.fileTransportClone($,Z,X,z);else z.log(`[WorkerRuntimeManager] auto-pull: ${$} workspace already populated; skipping clone`);if(Y.watch!==!1&&!this.watchers.has($))try{let G=new j0({apiUrl:X.cloudUrl,apiKey:X.apiKey,projectId:$,localDir:Z}),k=this.syncModes.get($)??"files",C=new Z0({rootDir:Z,transport:G,logger:z,mode:k,git:k==="git"?{apiUrl:X.cloudUrl,apiKey:X.apiKey,projectId:$}:void 0});C.start(),this.watchers.set($,C)}catch(G){z.warn(`[WorkerRuntimeManager] auto-pull: watcher start failed for ${$}: ${G?.message??G}`)}}catch(K){z.warn(`[WorkerRuntimeManager] auto-pull: failed for ${$} — runtime will fall back to template defaults. `+`(${K?.message??K})`)}return{...X,projectDir:Z}}async fileTransportClone($,X,Y,Z){Z.log(`[WorkerRuntimeManager] auto-pull: file-transport clone of ${$} into ${X}`);let J=await new j0({apiUrl:Y.cloudUrl,apiKey:Y.apiKey,projectId:$,localDir:X}).downloadAll();Z.log(`[WorkerRuntimeManager] auto-pull: ${$} downloaded ${J.downloaded} files (${J.errors.length} errors)`)}async topUpShogoState($,X,Y,Z){try{let z=new j0({apiUrl:Y.cloudUrl,apiKey:Y.apiKey,projectId:$,localDir:X}),K=(await z.listManifest()).filter((H)=>H.path===".shogo"||H.path.startsWith(".shogo/"));if(K.length===0)return;let V=await z.downloadFiles(K);Z.log(`[WorkerRuntimeManager] auto-pull: ${$} .shogo/ top-up downloaded ${V.downloaded} files (${V.errors.length} errors)`)}catch(z){Z.warn(`[WorkerRuntimeManager] auto-pull: .shogo top-up failed for ${$}: ${z?.message??z}`)}}shouldDeferToCloudSync($){return!!this.opts.autoPull?.enabled&&this.pulledProjects.has($)}status($){let X=this.runtimes.get($);return X?this.snapshot(X):null}getActiveProjects(){return Array.from(this.runtimes.keys()).filter(($)=>{let X=this.runtimes.get($);return X&&(X.status==="running"||X.status==="starting"||X.status==="restarting")})}touch($){let X=this.runtimes.get($);if(!X)return;X.lastUsedAt=Date.now(),this.armIdleTimer(X)}async stop($,X="SIGTERM",Y="stop"){let Z=this.runtimes.get($);if(!Z)return;if(Z.status="stopping",Z.restartTimer)clearTimeout(Z.restartTimer),Z.restartTimer=null;if(Z.idleTimer)clearTimeout(Z.idleTimer),Z.idleTimer=null;if(Z.graceTimer)clearTimeout(Z.graceTimer),Z.graceTimer=null;if(Z.limitWatchdog)Z.limitWatchdog.stop(),Z.limitWatchdog=null;if(Z.proc){this.killProcessGroup(Z,X),this.killViteWatch(Z);try{Z.proc.kill(X)}catch{}await this.waitForExit(Z.proc,5000),this.killProcessGroup(Z,"SIGKILL"),this.killViteWatch(Z)}Z.pid=null,this.releasePort(Z.agentPort),this.runtimes.delete($),this.notifyGone($,{reason:Y})}notifyGone($,X){let Y=this.opts.onRuntimeGone;if(!Y)return;try{Y($,X)}catch(Z){this.log.warn(`[WorkerRuntimeManager] onRuntimeGone(${$}) threw: ${Z?.message??Z}`)}}resetFailure($){let X=this.runtimes.get($);if(!X||X.status!=="failed")return!1;if(X.restartTimer)clearTimeout(X.restartTimer),X.restartTimer=null;if(X.idleTimer)clearTimeout(X.idleTimer),X.idleTimer=null;if(X.graceTimer)clearTimeout(X.graceTimer),X.graceTimer=null;if(X.limitWatchdog)X.limitWatchdog.stop(),X.limitWatchdog=null;return this.runtimes.delete($),this.log.log(`[WorkerRuntimeManager] resetFailure: ${$} cleared, next ensureRunning will respawn`),!0}breakerCooldownMs($){let X=Math.max(0,$-1),Y=F6*Math.pow(2,X);return Math.min(Y,T6)}healBreaker($){$.status="stopped",$.consecutiveFailures=0}async stopAll($="SIGTERM"){this.stopped=!0;let X=Array.from(this.watchers.keys());await Promise.all(X.map(async(Z)=>{let z=this.watchers.get(Z);if(this.watchers.delete(Z),z)try{await z.stop()}catch(J){this.log.warn(`[WorkerRuntimeManager] watcher stop ${Z}: ${J?.message??J}`)}}));let Y=Array.from(this.runtimes.keys());await Promise.all(Y.map((Z)=>this.stop(Z,$).catch((z)=>{this.log.error(`[WorkerRuntimeManager] Failed to stop ${Z}: ${z?.message??z}`)})))}makeSlot($,X){return{projectId:$,agentPort:0,apiServerPort:0,status:"starting",proc:null,pid:null,startedAt:0,lastStdoutAt:0,lastUsedAt:Date.now(),restarts:0,consecutiveFailures:0,lastFailureAt:0,breakerTrips:0,restartTimestamps:[],graceTimer:null,restartTimer:null,idleTimer:null,limitWatchdog:null,spawnConfig:X,startPromise:null}}async doStart($){let X=this.resolveBinary();if(!X)throw $.status="error",$.lastError="agent-runtime binary not found (run `shogo runtime install`)",Error($.lastError);if(!$.agentPort)$.agentPort=await this.allocatePort(),$.apiServerPort=$.agentPort+F2;let Y=this.buildEnv($,X.path),Z=this.resolveCwd($),z=this.spawnCommand(X.path),J=this.resolveLimits(),K=z.command,V=z.args,H=!1;if(J){let W=w2({command:z.command,args:z.args,limits:J,scopeName:`shogo-rt-${$.projectId.slice(0,8)}-${Date.now().toString(36)}`,logger:this.log});K=W.command,V=W.args,H=W.wrapped}this.log.log(`[WorkerRuntimeManager] Spawning agent-runtime for ${$.projectId} via ${K} ${V.join(" ")} (port=${$.agentPort}, source=${X.source}${J?`, memCeil=${J.memoryMB}M`:""})`);let q=process.platform!=="win32",Q=Q6(K,V,{cwd:Z,env:Y,detached:q,stdio:["ignore","pipe","pipe"]});if(q)try{Q.unref()}catch{}$.proc=Q,$.pid=Q.pid??null,$.status="starting",$.startedAt=Date.now();let G=$.spawnConfig.extraEnv?.SHOGO_OPEN_ID;if(L0("agent-spawned",$.projectId,G,{pid:$.pid,command:K,args:V,source:X.source}),J)try{this.applyPostSpawnLimits($,J,H)}catch(W){this.log.warn(`[WorkerRuntimeManager] failed to apply resource limits for ${$.projectId}: ${W?.message??W}`)}$.lastStdoutAt=$.startedAt,Q.on("error",(W)=>{$.lastError=W?.message??String(W),this.log.error(`[WorkerRuntimeManager] spawn error for ${$.projectId}: ${$.lastError}`)}),Q.on("exit",(W,L)=>{this.handleExit($,W,L)});let k=`[runtime:${$.projectId.slice(0,8)}]`,C=!0;Q.stdout?.on("data",(W)=>{if($.lastStdoutAt=Date.now(),C)C=!1,L0("agent-first-output",$.projectId,G,{elapsedMs:Date.now()-($.startedAt??Date.now())});for(let L of W.toString().trimEnd().split(`
13
- `))if(L)this.log.log(`${k} ${L}`)}),Q.stderr?.on("data",(W)=>{if($.lastStdoutAt=Date.now(),C)C=!1,L0("agent-first-output",$.projectId,G,{elapsedMs:Date.now()-($.startedAt??Date.now()),stream:"stderr"});for(let L of W.toString().trimEnd().split(`
14
- `))if(L)this.log.error(`${k} ${L}`)});try{return await this.waitForHealth($,x6),L0("agent-health-ready",$.projectId,G,{elapsedMs:Date.now()-($.startedAt??Date.now()),agentPort:$.agentPort}),$.status="running",$.lastUsedAt=Date.now(),this.armIdleTimer($),this.armGraceTimer($),$}catch(W){$.status="error",$.lastError=W?.message??String(W),this.killProcessGroup($,"SIGTERM"),this.killViteWatch($);try{Q.kill("SIGTERM")}catch{}throw this.releasePort($.agentPort),$.agentPort=0,$.apiServerPort=0,W}}resolveLimits(){if(this.resolvedLimits===void 0)this.resolvedLimits=k2(this.opts.env??process.env);return this.resolvedLimits}applyPostSpawnLimits($,X,Y){let Z=$.pid;if(!Z)return;if(process.platform==="linux"){if(Y)return;if(C2({pid:Z,limits:X,logger:this.log}))return}else if(process.platform==="win32"){if(L2({pid:Z,limits:X,logger:this.log}))return}$.limitWatchdog=new S0({pid:Z,ceilingMB:X.memoryMB,logger:this.log,onBreach:(z)=>this.handleLimitBreach($,z,X.memoryMB)}),$.limitWatchdog.start()}handleLimitBreach($,X,Y){if(this.log.warn(`[WorkerRuntimeManager] runtime ${$.projectId} exceeded memory ceiling (${X}MB > ${Y}MB) — restarting`),$.lastError=`memory ceiling exceeded (${X}MB > ${Y}MB)`,$.limitWatchdog)$.limitWatchdog.stop(),$.limitWatchdog=null;this.killProcessGroup($,"SIGTERM"),this.killViteWatch($);try{$.proc?.kill("SIGTERM")}catch{}let Z=setTimeout(()=>{this.killProcessGroup($,"SIGKILL"),this.killViteWatch($)},5000);try{Z.unref?.()}catch{}}killProcessGroup($,X){if(!$.pid)return;if(process.platform==="win32"){try{G6("taskkill",["/F","/T","/PID",String($.pid)],{stdio:"ignore",windowsHide:!0})}catch{}return}try{process.kill(-$.pid,X)}catch{}}armGraceTimer($){if($.graceTimer)clearTimeout($.graceTimer),$.graceTimer=null;$.graceTimer=setTimeout(()=>{if($.graceTimer=null,$.consecutiveFailures>0)$.consecutiveFailures=0;$.breakerTrips=0,$.restartTimestamps=[]},y6);try{$.graceTimer.unref?.()}catch{}}buildEnv($,X){let Y=$.spawnConfig,Z={...this.opts.env??process.env,PROJECT_ID:$.projectId,PORT:String($.agentPort),API_SERVER_PORT:String($.apiServerPort),SKILL_SERVER_PORT:String($.apiServerPort),WORKSPACE_API_PORT_BASE:String($.agentPort+C6),NODE_ENV:"production",STARTUP_TIME:String(Date.now()),SHOGO_CLOUD_URL:Y.cloudUrl,SHOGO_API_URL:Y.cloudUrl,SHOGO_API_KEY:Y.apiKey,RUNTIME_AUTH_SECRET:M2($.projectId),WEBHOOK_TOKEN:R6($.projectId)};if(Y.projectDir)Z.PROJECT_DIR=Y.projectDir,Z.WORKSPACE_DIR=Y.projectDir;if(this.shouldDeferToCloudSync($.projectId))Z.SHOGO_CLOUD_SYNC="1";if(Y.aiProxyUrl)Z.AI_PROXY_URL=Y.aiProxyUrl;if(Y.aiProxyToken)Z.AI_PROXY_TOKEN=Y.aiProxyToken;if(Y.techStackId)Z.TECH_STACK_ID=Y.techStackId;if(Y.name)Z.AGENT_NAME=Y.name;if(Y.workspaceId)Z.WORKSPACE_ID=Y.workspaceId;if(!Z.TREE_SITTER_WASM_DIR)Z.TREE_SITTER_WASM_DIR=p(w6(X),"tree-sitter-wasm");if(Y.extraEnv)Object.assign(Z,Y.extraEnv);let z=this.resolveLimits();if(z)O2(Z,z.memoryMB);return Z}killViteWatch($){let X=$.spawnConfig.projectDir;if(!X)return;try{B2(X,{logger:this.log})}catch(Y){this.log.warn(`[WorkerRuntimeManager] Vite watch cleanup for ${$.projectId} failed: ${Y?.message??Y}`)}}sweepOrphanedViteWatches(){let $=this.opts.autoPull?.projectsDir;if(!$)return;let X;try{X=R2($,{withFileTypes:!0})}catch{return}for(let Y of X){if(!Y.isDirectory()||this.runtimes.has(Y.name))continue;let Z=p($,Y.name);try{let z=B2(Z,{logger:this.log});if(z)this.log.log(`[WorkerRuntimeManager] Reaped orphaned Vite watch for ${Y.name} (pid=${z.pid})`)}catch(z){this.log.warn(`[WorkerRuntimeManager] Vite watch startup sweep failed for ${Y.name}: ${z?.message??z}`)}}}resolveCwd($){let X=$.spawnConfig;if(X.projectDir&&h0(X.projectDir))return X.projectDir;let Y=this.opts.runtimeWorkDir??p(O6(),"shogo-runtime",$.projectId);return N2(Y,{recursive:!0}),Y}handleExit($,X,Y){let Z=Y===null&&X===0;if(this.log.log(`[WorkerRuntimeManager] runtime ${$.projectId} exited (code=${X}, signal=${Y})`),$.proc=null,$.graceTimer)clearTimeout($.graceTimer),$.graceTimer=null;if($.limitWatchdog)$.limitWatchdog.stop(),$.limitWatchdog=null;if(this.killViteWatch($),$.status==="stopping"||this.stopped){$.status="stopped",$.pid=null,this.releasePort($.agentPort),$.agentPort=0,$.apiServerPort=0;return}if(Z){$.status="stopped",$.pid=null,this.releasePort($.agentPort),$.agentPort=0,$.apiServerPort=0,this.runtimes.delete($.projectId),this.notifyGone($.projectId,{reason:"exited",code:X,signal:Y});return}this.killProcessGroup($,"SIGKILL"),this.killViteWatch($),$.pid=null;let z=Date.now(),J=z-$.lastFailureAt<=y2;$.consecutiveFailures=J?$.consecutiveFailures+1:1,$.lastFailureAt=z,$.restarts+=1,$.lastError=`exited code=${X} signal=${Y}`,$.restartTimestamps.push(z),$.restartTimestamps=$.restartTimestamps.filter((q)=>z-q<=_2);let K=$.consecutiveFailures>=T2,V=$.restartTimestamps.length>=B6;if(K||V){$.status="failed",$.breakerTrips+=1;let q=this.breakerCooldownMs($.breakerTrips),Q=K?`${$.consecutiveFailures} consecutive non-clean exits within ${Math.round(y2/1000)}s`:`${$.restartTimestamps.length} non-clean exits within the last ${Math.round(_2/60000)}m (slow-bleed loop — gaps between crashes kept clearing the tight-loop window)`;if($.lastError=`Circuit breaker tripped (trip #${$.breakerTrips}): ${Q} (last: code=${X} signal=${Y}). Most recent on macOS is jetsam OOM (signal=SIGKILL with code=null); the previous incarnation's vite/tsserver/preview-manager children were reaped to prevent further RSS growth. Will auto-retry in ~${Math.round(q/1000)}s; call resetFailure(${$.projectId}) to retry immediately, or stop(${$.projectId}) to give up.`,this.releasePort($.agentPort),$.agentPort=0,$.apiServerPort=0,$.restartTimer)clearTimeout($.restartTimer),$.restartTimer=null;if($.idleTimer)clearTimeout($.idleTimer),$.idleTimer=null;this.log.error(`[WorkerRuntimeManager] ${$.lastError}`),this.notifyGone($.projectId,{reason:"failed",code:X,signal:Y});return}let H=this.restartBackoffMs($.restarts);if($.status="restarting",this.log.warn(`[WorkerRuntimeManager] restarting ${$.projectId} in ${Math.round(H/1000)}s (restart #${$.restarts}, consecutive failures ${$.consecutiveFailures}/${T2})`),$.restartTimer)clearTimeout($.restartTimer);$.restartTimer=setTimeout(()=>{if($.restartTimer=null,$.status==="failed"||this.stopped)return;$.startPromise=this.doStart($).then((q)=>{return $.startPromise=null,q}).catch((q)=>{return $.startPromise=null,this.log.error(`[WorkerRuntimeManager] restart of ${$.projectId} failed: ${q?.message??q}`),$})},H);try{$.restartTimer.unref?.()}catch{}}restartBackoffMs($){let X=Math.min(A6*Math.pow(2,Math.max(0,$-1)),N6),Y=X*0.2*Math.random();return X+Y}armIdleTimer($){if($.idleTimer)clearTimeout($.idleTimer),$.idleTimer=null;let X=this.opts.idleMs??L6;if(!Number.isFinite(X)||X<=0)return;$.idleTimer=setTimeout(()=>{let Y=Date.now()-$.lastUsedAt;if(Y<X){this.armIdleTimer($);return}this.log.log(`[WorkerRuntimeManager] idle-evicting ${$.projectId} after ${Math.round(Y/1000)}s`),this.stop($.projectId,"SIGTERM","idle-evict").catch((Z)=>{this.log.warn(`[WorkerRuntimeManager] idle stop failed: ${Z?.message??Z}`)})},X)}async allocatePort(){let $=I0-m0,X=Math.min($,50);for(let Y=0;Y<X;Y++){let Z=m0+Math.floor(Math.random()*$);if(Z+C0-1>I0)continue;let z=!0;for(let V=0;V<C0;V++)if(this.usedPorts.has(Z+V)){z=!1;break}if(!z)continue;let J=await this.isPortListening(Z),K=await this.isPortListening(Z+F2);if(J||K)continue;for(let V=0;V<C0;V++)this.usedPorts.add(Z+V);return Z}throw Error(`Cannot allocate port in range ${m0}-${I0} after ${X} attempts`)}releasePort($){if(!$)return;for(let X=0;X<C0;X++)this.usedPorts.delete($+X)}async isPortListening($){let X=new AbortController,Y=setTimeout(()=>X.abort(),250);try{return await fetch(`http://127.0.0.1:${$}/`,{method:"HEAD",signal:X.signal}),clearTimeout(Y),!0}catch{return clearTimeout(Y),!1}}tcpProbe($){return new Promise((X)=>{let Y=!1,Z=(J)=>{if(Y)return;Y=!0;try{z.destroy()}catch{}X(J)},z=k6({host:"127.0.0.1",port:$});z.setTimeout(D6),z.once("connect",()=>Z(!0)),z.once("error",()=>Z(!1)),z.once("timeout",()=>Z(!1))})}async waitForHealth($,X){let{agentPort:Y,proc:Z}=$;if(!Z)throw Error(`waitForHealth: slot ${$.projectId} has no spawned process`);let z=Date.now(),J=z+X,K=null,V=!1,H=0,q=0,Q=0,G=0,k=z;while(Date.now()<J){if(G++,Z.exitCode!==null||Z.signalCode!=null||Z.killed)throw Error(`agent-runtime exited (code=${Z.exitCode}, signal=${Z.signalCode}) before becoming healthy on port ${Y}`);q++;let C=new AbortController,W=setTimeout(()=>C.abort(),1500);try{let O=await fetch(`http://127.0.0.1:${Y}/health`,{method:"GET",signal:C.signal});if(clearTimeout(W),O.ok){this.log.log(`[WorkerRuntimeManager] /health ready for ${$.projectId} on port ${Y} (HTTP ${O.status} after ${Date.now()-z}ms, ${G} iter, ${q} http)`);return}K=`HTTP /health returned ${O.status}`}catch(O){clearTimeout(W);let T=O?.name??"Error",a=O?.code??O?.cause?.code;K=`HTTP /health failed: ${T}${a?`(${a})`:""}: ${O?.message??O}`}if(Q++,V=await this.tcpProbe(Y),V){H=Date.now();let O=Date.now()-$.lastStdoutAt;if(O>=x2)throw Error(`agent-runtime wedged on port ${Y}: TCP listening but stdout silent for ${O}ms (> ${x2}ms window); ${q} /health attempts, last error: ${K??"n/a"}`)}let L=Date.now();if(L-k>=M6){let O=L-z,T=L-$.lastStdoutAt,a=H>0?L-H:null;this.log.log(`[WorkerRuntimeManager] still waiting for /health on ${$.projectId} port ${Y} (${(O/1000).toFixed(1)}s elapsed, tcpListening=${V}${a!=null?`(${a}ms ago)`:""}, lastStdout=${T}ms ago, ${q} http, ${Q} tcp, lastError=${K??"n/a"})`),k=L}await new Promise((O)=>setTimeout(O,_6))}if(Z.exitCode!==null||Z.signalCode!=null||Z.killed)throw Error(`agent-runtime exited (code=${Z.exitCode}, signal=${Z.signalCode}) before becoming healthy on port ${Y}`);throw Error(`Timeout waiting for agent-runtime /health on port ${Y} after ${G} iter (httpAttempts=${q}, tcpAttempts=${Q}, tcpListening=${V}, lastError=${K??"n/a"})`)}async waitForExit($,X){if($.exitCode!==null||$.signalCode!=null||$.killed)return;await new Promise((Y)=>{let Z=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}Y()},X);$.once("exit",()=>{clearTimeout(Z),Y()})})}snapshot($){return{projectId:$.projectId,status:$.status,agentPort:$.agentPort||void 0,apiServerPort:$.apiServerPort||void 0,pid:$.proc?.pid,startedAt:$.startedAt||void 0,lastUsedAt:$.lastUsedAt,restarts:$.restarts,lastError:$.lastError}}}import{hostname as d0,platform as g0,arch as i0}from"node:os";function d(){if(typeof __SHOGO_WORKER_VERSION__==="string"&&__SHOGO_WORKER_VERSION__.length>0)return`shogo-cli/${__SHOGO_WORKER_VERSION__}`;return"shogo-cli/unknown"}class j2 extends Error{code="TUNNEL_WS_HEADERS_UNSUPPORTED";constructor(){super("Tunnel WebSocket auth requires a runtime with WebSocket header support (Bun or Node >= 21). Current runtime does not support WebSocket constructor headers.");this.name="TunnelWebSocketHeaderSupportError"}}var z0=60,U0=300,p0=3,b6=p0,E6=1800000,v6=25000,E2=1000,v2=60000,h2=3;class c0{opts;log;pollTimer=null;ws=null;wsIdleTimer=null;heartbeatTimer=null;stopped=!1;currentPollInterval=z0;wsReconnectAttempt=0;lastHeartbeatError=null;consecutiveAuthFailures=0;consecutiveAuthSuccesses=0;serverPublishedWsUrl=null;activeAbortControllers=new Map;constructor($){this.opts=$,this.log=$.logger??console}start(){if(!this.opts.apiKey){this.log.log("[WorkerTunnel] No API key set, skipping tunnel");return}this.stopped=!1,this.wsReconnectAttempt=0,this.currentPollInterval=z0,this.log.log("[WorkerTunnel] Starting heartbeat polling to Shogo Cloud..."),this.heartbeatLoop()}stop(){if(this.stopped=!0,this.pollTimer)clearTimeout(this.pollTimer),this.pollTimer=null;this.cleanupWs(),this.log.log("[WorkerTunnel] Tunnel stopped")}isConnected(){if(this.ws!==null&&this.ws.readyState===WebSocket.OPEN)return!0;return!this.stopped&&!!this.opts.apiKey&&this.lastHeartbeatError===null&&this.pollTimer!==null}getCloudUrl(){return this.opts.cloudUrl.replace(/\/$/,"")}getWsBaseUrl(){let $=(this.opts.wsUrlOverride||process.env.SHOGO_TUNNEL_WS_URL||"").trim();if($)return $.replace(/\/$/,"");if(this.serverPublishedWsUrl)return this.serverPublishedWsUrl.replace(/\/$/,"");return this.getCloudUrl().replace(/^http/,"ws")}buildWsUrl(){return`${this.getWsBaseUrl()}/api/instances/ws`}supportsWebSocketConstructorHeaders($=globalThis){if(typeof $.Bun<"u"||typeof $.process?.versions?.bun==="string")return!0;let X=$.process?.versions?.node;if(X){if(parseInt(X.split(".")[0]??"0",10)>=21)return!0}return!1}createTunnelWebSocket($,X,Y=globalThis){if(!this.supportsWebSocketConstructorHeaders(Y))throw new j2;return new WebSocket($,X)}getReconnectDelayMs(){let $=Math.min(E2*Math.pow(2,this.wsReconnectAttempt),v2),X=$*0.2*Math.random();return $+X}async collectMetadata(){let $={hostname:d0(),os:g0(),arch:i0(),uptime:process.uptime(),protocolVersion:h2,tunnelStatus:this.ws?.readyState===WebSocket.OPEN?"connected":"polling",kind:this.opts.kind??"cli-worker"};try{let X=this.opts.resolver.getActiveProjects();$.activeProjects=X.length,$.projects=X.map((Y)=>{let Z=this.opts.resolver.status(Y);return{projectId:Y,status:Z?.status??"unknown",agentPort:Z?.agentPort}})}catch{$.activeProjects=0}return $}async sendHeartbeat(){let $=this.getCloudUrl(),X=await this.collectMetadata(),Y=d0(),Z=this.opts.name??Y,z=await fetch(`${$}/api/instances/heartbeat`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":d(),"x-api-key":this.opts.apiKey,"x-shogo-kind":this.opts.kind??"cli-worker"},body:JSON.stringify({hostname:Y,name:Z,os:g0(),arch:i0(),kind:this.opts.kind??"cli-worker",metadata:X})});if(!z.ok)throw Error(`Heartbeat failed: HTTP ${z.status}`);let J=await z.json();if(typeof J.wsUrl==="string"&&J.wsUrl.length>0){if(J.wsUrl!==this.serverPublishedWsUrl)this.log.log(`[WorkerTunnel] Cloud advertised tunnel WS URL: ${J.wsUrl}`);this.serverPublishedWsUrl=J.wsUrl}return J}scheduleNextPoll($){if(this.stopped)return;if(this.pollTimer)clearTimeout(this.pollTimer);let X=($??this.currentPollInterval)*1000;this.pollTimer=setTimeout(()=>void this.heartbeatLoop(),X)}async heartbeatLoop(){if(this.stopped)return;if(this.ws&&this.ws.readyState===WebSocket.OPEN){this.scheduleNextPoll(this.currentPollInterval);return}try{let $=await this.sendHeartbeat(),X=$.nextPollIn||z0;if(this.consecutiveAuthFailures>=p0){if(this.consecutiveAuthSuccesses++,this.consecutiveAuthSuccesses<b6){this.currentPollInterval=U0,this.scheduleNextPoll();return}}if(this.currentPollInterval=X,this.lastHeartbeatError)this.log.log("[WorkerTunnel] Heartbeat recovered"),this.lastHeartbeatError=null;if(this.consecutiveAuthFailures=0,this.consecutiveAuthSuccesses=0,$.wsRequested&&!this.ws){this.log.log("[WorkerTunnel] Cloud requested WebSocket — connecting..."),this.connectWs();return}}catch($){let X=$?.message??String($);if(/HTTP 40[13]\b/.test(X))this.consecutiveAuthFailures++,this.consecutiveAuthSuccesses=0;else this.consecutiveAuthFailures=0,this.consecutiveAuthSuccesses=0;if(X!==this.lastHeartbeatError)this.log.error(`[WorkerTunnel] Heartbeat error: ${X}`),this.lastHeartbeatError=X;if(this.consecutiveAuthFailures>=p0){let Z=`tunnel saw ${this.consecutiveAuthFailures} consecutive auth failures from Shogo Cloud`;try{this.opts.onAuthRevoked?.(Z)}catch(z){this.log.warn(`[WorkerTunnel] onAuthRevoked threw: ${z?.message??z}`)}if(this.currentPollInterval!==U0)this.log.warn(`[WorkerTunnel] ${this.consecutiveAuthFailures} consecutive auth failures — `+`backing off to ${U0}s. Re-authenticate with \`shogo login\`.`);this.currentPollInterval=U0}else this.currentPollInterval=z0}this.scheduleNextPoll()}async handleRequest($){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;this.resetWsIdleTimer();let X=new AbortController;this.activeAbortControllers.set($.requestId,X);try{let Y=await this.resolveLocalUrl($.path,$.projectId);if(!Y){let K=this.opts.resolver.describeRejection?this.opts.resolver.describeRejection($.path,$.projectId):{code:"NO_LOCAL_RUNTIME",message:`no local runtime available for path: ${$.path}`};this.sendFrame({type:"response",requestId:$.requestId,status:502,headers:{"content-type":"application/json"},body:JSON.stringify({code:K.code,message:K.message,path:$.path})});return}let Z={...$.headers??{}};if($.projectId&&($.path.startsWith("/agent/")||$.path==="/agent")){let K=this.opts.resolver.deriveRuntimeToken($.projectId);if(K)Z["x-runtime-token"]=K}let z={method:$.method,headers:Z,signal:X.signal};if($.body&&$.method!=="GET"&&$.method!=="HEAD")z.body=$.body;let J=await fetch(Y,z);if($.stream){let K=J.body?.getReader();if(!K){this.sendFrame({type:"stream-error",requestId:$.requestId,error:"No response body for stream"});return}let V=new TextDecoder;try{while(!0){let{done:H,value:q}=await K.read();if(H)break;if(this.ws?.readyState!==WebSocket.OPEN)break;this.sendFrame({type:"stream-chunk",requestId:$.requestId,data:V.decode(q,{stream:!0})})}if(this.ws?.readyState===WebSocket.OPEN)this.sendFrame({type:"stream-end",requestId:$.requestId})}catch(H){if(H?.name!=="AbortError"&&this.ws?.readyState===WebSocket.OPEN)this.sendFrame({type:"stream-error",requestId:$.requestId,error:H?.message??String(H)})}}else{let K=await J.text(),V={};J.headers.forEach((H,q)=>{V[q]=H}),this.sendFrame({type:"response",requestId:$.requestId,status:J.status,headers:V,body:K})}}catch(Y){if(Y?.name==="AbortError")return;if(this.ws?.readyState!==WebSocket.OPEN)return;let Z=$.stream?{type:"stream-error",requestId:$.requestId,error:Y?.message??String(Y)}:{type:"response",requestId:$.requestId,status:502,body:JSON.stringify({error:Y?.message??String(Y)})};this.sendFrame(Z)}finally{this.activeAbortControllers.delete($.requestId)}}async resolveLocalUrl($,X){return this.opts.resolver.resolveLocalUrl($,X)}sendFrame($){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;try{this.ws.send(JSON.stringify($))}catch(X){this.log.warn(`[WorkerTunnel] Frame send failed: ${X?.message??X}`)}}resetWsIdleTimer(){if(this.wsIdleTimer)clearTimeout(this.wsIdleTimer);this.wsIdleTimer=setTimeout(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){this.log.log("[WorkerTunnel] WebSocket idle timeout — closing, returning to polling");try{this.ws.close(1000,"Idle timeout")}catch{}}},E6)}startWsHeartbeat(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer);this.heartbeatTimer=setInterval(async()=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;try{let $=await this.collectMetadata();this.sendFrame({type:"heartbeat",metadata:$})}catch{}},v6)}connectWs(){if(this.stopped||this.ws)return;let $=this.buildWsUrl(),X=d0(),Y=g0(),Z=i0(),z=this.opts.name??X;this.log.log(`[WorkerTunnel] Opening WebSocket to ${$} (hostname=${X})`);let J={headers:{Authorization:`Bearer ${this.opts.apiKey}`,"User-Agent":d(),"x-shogo-hostname":X,"x-shogo-name":z,"x-shogo-os":Y,"x-shogo-arch":Z,"x-shogo-kind":this.opts.kind??"cli-worker"}},K;try{K=this.createTunnelWebSocket($,J)}catch(V){this.log.error(`[WorkerTunnel] WebSocket creation failed: ${V?.message??V}`),this.ws=null,this.scheduleNextPoll(5);return}this.ws=K,K.onopen=()=>{this.log.log("[WorkerTunnel] WebSocket connected — session active"),this.wsReconnectAttempt=0,this.startWsHeartbeat(),this.resetWsIdleTimer()},K.onmessage=(V)=>{let H;try{let q=typeof V.data==="string"?V.data:V.data.toString();H=JSON.parse(q)}catch{return}if(H.type==="ping"){this.sendFrame({type:"pong"}),this.resetWsIdleTimer();return}if(H.type==="cancel"){let q=this.activeAbortControllers.get(H.requestId);if(q)q.abort();return}if(H.type==="request"){this.handleRequest(H).catch((q)=>{this.log.error(`[WorkerTunnel] Error handling request: ${q?.message??q}`)});return}},K.onclose=(V)=>{if(this.log.log(`[WorkerTunnel] WebSocket closed: code=${V.code} reason=${V.reason||"none"}`),this.cleanupWs(),this.stopped)return;if(V.code===1000||V.code===4000)this.scheduleNextPoll(this.currentPollInterval);else{this.wsReconnectAttempt++;let H=this.getReconnectDelayMs();this.log.log(`[WorkerTunnel] Reconnecting in ${Math.round(H/1000)}s (attempt ${this.wsReconnectAttempt})`),this.scheduleNextPoll(Math.ceil(H/1000))}},K.onerror=(V)=>{this.log.error("[WorkerTunnel] WebSocket error:",V?.message??"unknown")}}cleanupWs(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer),this.heartbeatTimer=null;if(this.wsIdleTimer)clearTimeout(this.wsIdleTimer),this.wsIdleTimer=null;for(let[,$]of this.activeAbortControllers)try{$.abort()}catch{}this.activeAbortControllers.clear(),this.ws=null}_testing(){let $=this;return{sendHeartbeat:()=>$.sendHeartbeat(),heartbeatLoop:()=>$.heartbeatLoop(),connectWs:()=>$.connectWs(),cleanupWs:()=>$.cleanupWs(),handleRequest:(X)=>$.handleRequest(X),installFakeWs:(X)=>{$.ws=X},getCloudUrl:()=>$.getCloudUrl(),getWsBaseUrl:()=>$.getWsBaseUrl(),buildWsUrl:()=>$.buildWsUrl(),getReconnectDelayMs:()=>$.getReconnectDelayMs(),supportsWebSocketConstructorHeaders:(X)=>$.supportsWebSocketConstructorHeaders(X),createTunnelWebSocket:(X,Y,Z)=>$.createTunnelWebSocket(X,Y,Z),DEFAULT_POLL_INTERVAL_S:z0,BACKOFF_BASE_MS:E2,BACKOFF_MAX_MS:v2,TUNNEL_PROTOCOL_VERSION:h2,get currentPollInterval(){return $.currentPollInterval},set currentPollInterval(X){$.currentPollInterval=X},get wsReconnectAttempt(){return $.wsReconnectAttempt},set wsReconnectAttempt(X){$.wsReconnectAttempt=X},get ws(){return $.ws},get stopped(){return $.stopped},get serverPublishedWsUrl(){return $.serverPublishedWsUrl},set serverPublishedWsUrl(X){$.serverPublishedWsUrl=X}}}}async function m2($){let X=R({name:$.name,workerDir:$.workerDir,apiKey:$.apiKey,cloudUrl:$.cloudUrl,port:$.port?parseInt($.port,10):void 0,projectsDir:$.projectsDir}),Y=J2($.proxy);if(!$.foreground)return j6({cfg:X,proxy:Y,flags:$});let Z=u({flag:$.runtimeBin});if(!Z)console.error(w.red(n({flag:$.runtimeBin}))),process.exit(1);if(D0(process.env,Y),$.debug){if(!await H2(q2({cloudUrl:X.cloudUrl,apiKey:X.apiKey,workerDir:X.workerDir,proxy:Y})))process.exit(1)}let z=!$.noAutoPull,J=!$.noGit;if(console.log(w.bold(`
15
- Shogo Worker — Starting`)),console.log(w.dim(" name ")+X.name),console.log(w.dim(" worker-dir ")+X.workerDir),console.log(w.dim(" cloud ")+X.cloudUrl),console.log(w.dim(" runtime ")+`${Z.path} ${w.dim(`(via ${Z.source})`)}`),console.log(w.dim(" auto-pull ")+(z?w.green("on")+w.dim(` → ${X.projectsDir}`):w.yellow("off"))),console.log(w.dim(" sync mode ")+(J?w.green("git")+w.dim(" (falls back to file transport if git is missing)"):w.yellow("files-only"))),$.project)console.log(w.dim(" project ")+$.project);if(Y)console.log(w.dim(" proxy ")+`${Y.url} ${w.dim(`(from ${Y.source})`)}`);console.log("");let K=`${X.cloudUrl.replace(/\/+$/,"")}/api/ai/v1`,V={cloudUrl:X.cloudUrl,apiKey:X.apiKey,aiProxyUrl:K,aiProxyToken:X.apiKey},H=new n0({runtimeBin:$.runtimeBin,defaultSpawnConfig:V,autoPull:{enabled:z,projectsDir:X.projectsDir,watch:!0,useGit:J}});if(!H.resolveBinary())console.error(w.red(n({flag:$.runtimeBin}))),process.exit(1);let q=new c0({apiKey:X.apiKey,cloudUrl:X.cloudUrl,name:X.name,kind:"cli-worker",resolver:H,onAuthRevoked:(k)=>{console.error(w.red(`✗ Cloud auth revoked: ${k}`)),console.error(w.dim(" Run `shogo login` to re-authenticate; this worker will keep polling at the auth-failure backoff until then."))}}),Q=!1,G=async(k)=>{if(Q)return;Q=!0,console.log(w.dim(`
16
- Received ${k} — shutting down...`));try{q.stop()}catch{}try{await H.stopAll()}catch(C){console.warn(w.yellow(`stopAll: ${C?.message??C}`))}process.exit(0)};process.once("SIGINT",()=>void G("SIGINT")),process.once("SIGTERM",()=>void G("SIGTERM")),process.once("SIGHUP",()=>void G("SIGHUP")),q.start(),console.log(w.green("✓ Worker running. Ctrl-C to stop.")),await new Promise(()=>{})}function j6({cfg:$,proxy:X,flags:Y}){let{entry:Z,runner:z}=I6(),J=D0({...process.env,SHOGO_API_KEY:$.apiKey,SHOGO_CLOUD_URL:$.cloudUrl,SHOGO_INSTANCE_NAME:$.name,SHOGO_WORKER_DIR:$.workerDir,SHOGO_LOCAL_MODE:"true",PORT:String($.port)},X),K=m6(Y),{pid:V}=Y2({entry:Z,runner:z,env:{...J,SHOGO_DETACHED_ARGS:K.join(" ")},cwd:$.workerDir,detach:!0,inheritStdio:!1});console.log(w.bold(`
17
- Shogo Worker — Started`)),console.log(w.dim(" pid: ")+V),console.log(w.dim(" name: ")+$.name),console.log(w.dim(" logs: ")+"~/.shogo/logs/worker.log"),console.log(w.dim(" stop: ")+"shogo worker stop")}function m6($){let X=["worker","start","--foreground"];if($.name)X.push("--name",$.name);if($.workerDir)X.push("--worker-dir",$.workerDir);if($.apiKey)X.push("--api-key",$.apiKey);if($.cloudUrl)X.push("--cloud-url",$.cloudUrl);if($.port)X.push("--port",$.port);if($.proxy)X.push("--proxy",$.proxy);if($.project)X.push("--project",$.project);if($.runtimeBin)X.push("--runtime-bin",$.runtimeBin);if($.debug)X.push("--debug");if($.noAutoPull)X.push("--no-auto-pull");if($.projectsDir)X.push("--projects-dir",$.projectsDir);if($.noGit)X.push("--no-git");return X}function I6(){let $=process.execPath,X=/\bbun(?:-[^/\\]*)?$/.test($)||typeof globalThis.Bun<"u",Y=process.argv[1];if(Y&&h6(Y)){let z=/\.ts$/.test(Y);return{entry:Y,runner:X?"bun":z?"tsx":"node"}}return{entry:new URL("../../bin/shogo.mjs",import.meta.url).pathname,runner:X?"bun":"node"}}import I2 from"picocolors";async function u2(){let{killedPid:$}=Z2("SIGTERM");if($===null){console.log(I2.dim("No worker running."));return}console.log(I2.green(`✓ Worker stopped (pid=${$}).`))}import v from"picocolors";async function f2(){let $=G0();if(!$){console.log(v.yellow("● stopped")+v.dim(" (no pid file)"));return}if(!W0($)){console.log(v.red("● dead")+v.dim(` (stale pid ${$})`));return}let X=I();if(console.log(v.green("● running")+v.dim(` (pid ${$})`)),X.name)console.log(v.dim(" name: ")+X.name);if(X.cloudUrl)console.log(v.dim(" cloud: ")+X.cloudUrl);if(X.workerDir)console.log(v.dim(" dir: ")+X.workerDir)}import{spawn as u6}from"node:child_process";import{existsSync as f6,statSync as n6}from"node:fs";import n2 from"picocolors";async function d2($){let X=$.err?H0:q0;if(!f6(X)){console.log(n2.dim("No logs yet."));return}let Y=$.follow?["-F","-n","200",X]:["-n","200",X];if(u6("tail",Y,{stdio:"inherit"}).on("exit",(z)=>process.exit(z??0)),!$.follow){if(n6(X).size===0)console.log(n2.dim("(log file is empty)"))}}import _ from"picocolors";import{spawn as d6}from"node:child_process";import{hostname as g6,platform as i6,arch as p6}from"node:os";import f from"picocolors";class D extends Error{kind;constructor($,X){super($);this.kind=X;this.name="CloudLoginError"}}async function g2($){let X=$.cloudUrl.replace(/\/$/,""),Y=$.client??"cli",Z=$.deviceName??g6(),z=$.devicePlatform??`${i6()}-${p6()}`,J=$.appVersion??o6(),K=$.log??((O)=>console.log(O)),V=$.fetchImpl??fetch,H=await V(`${X}/api/cli/login/start`,{method:"POST",headers:{"content-type":"application/json","user-agent":d()},body:JSON.stringify({deviceId:$.deviceId,deviceName:Z,devicePlatform:z,deviceAppVersion:J,workspaceId:$.workspaceId,client:Y}),signal:AbortSignal.timeout(1e4)}).catch((O)=>{throw new D(`Cannot reach Shogo Cloud at ${X}: ${O?.message??O}`,"transport")});if(!H.ok){let O=await H.text().catch(()=>"");throw new D(`Cloud rejected /api/cli/login/start (HTTP ${H.status}): ${O||"no body"}`,"transport")}let q=await H.json().catch(()=>({}));if(!q?.ok||!q.state||!q.authUrl)throw new D(`Cloud returned a malformed start response: ${q?.error??JSON.stringify(q)}`,"transport");let Q=c6($.pollIntervalMs??q.pollIntervalMs),G=$.timeoutMs??q.expiresInMs,k=Date.now()+G;if(K(""),K(f.bold("Sign in to Shogo Cloud")),K(f.dim(" cloud: ")+X),K(f.dim(" device: ")+`${Z} (${z})`),K(f.dim(" user code: ")+f.cyan(q.userCode)),K(""),K(" Open this URL in your browser to approve:"),K(" "+f.cyan(q.authUrl)),K(""),$.openBrowser!==!1)if(typeof $.openBrowser==="function")try{await $.openBrowser(q.authUrl)}catch{}else l6(q.authUrl).catch(()=>{});K(f.dim("Waiting for approval..."));let C=$.installSignalHandlers??!0,W=()=>{L.abort()},L=new AbortController;if($.abortSignal)if($.abortSignal.aborted)L.abort();else $.abortSignal.addEventListener("abort",()=>L.abort(),{once:!0});if(C)process.once("SIGINT",W),process.once("SIGTERM",W);try{while(!0){if(L.signal.aborted)throw new D("Aborted by caller.","cancelled");if(Date.now()>=k)throw new D(`Timed out after ${Math.round(G/1000)}s waiting for approval.`,"timeout");let O=await V(`${X}/api/cli/login/poll?state=${encodeURIComponent(q.state)}`,{method:"GET",headers:{accept:"application/json","user-agent":d()},signal:AbortSignal.timeout(1e4)}).catch((T)=>{return K(f.dim(` (poll error: ${T?.message??T} — retrying)`)),null});if(O&&O.ok){let T=await O.json().catch(()=>({}));if(T?.status==="approved"&&T.key)return{key:T.key,email:T.email??null,workspace:T.workspace??null,deviceId:T.deviceId??$.deviceId};if(T?.status==="denied")throw new D("Sign-in was denied in the browser.","denied");if(T?.status==="expired")throw new D("Sign-in request expired before it was approved.","expired")}await a6(Q,L.signal)}}finally{if(C)process.removeListener("SIGINT",W),process.removeListener("SIGTERM",W)}}function c6($){if(!Number.isFinite($)||$<=0)return 2000;return Math.min(Math.max($,1000),1e4)}function a6($,X){return new Promise((Y,Z)=>{if(X?.aborted)return Z(new D("Aborted by caller.","cancelled"));let z=setTimeout(()=>{X?.removeEventListener("abort",J),Y()},$),J=()=>{clearTimeout(z),Z(new D("Aborted by caller.","cancelled"))};X?.addEventListener("abort",J,{once:!0})})}function o6(){return d()}function l6($){return new Promise((X)=>{let Y=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",Z=process.platform==="win32"?["/c","start",'""',$]:[$];try{let z=d6(Y,Z,{stdio:"ignore",detached:!0});z.on("error",()=>X()),z.unref(),X()}catch{X()}})}import{readFileSync as r6,writeFileSync as e6,existsSync as s6,chmodSync as t6}from"node:fs";import{randomUUID as $1}from"node:crypto";function i2(){if(s6(o)){let X=r6(o,"utf-8").trim();if(X)return X}m();let $=$1();return e6(o,$,{mode:384}),t6(o,384),$}var X1="https://studio.shogo.ai";async function p2($){let X=I(),Y=($.cloudUrl||X.cloudUrl||X1).replace(/\/$/,""),Z=$.apiKey||process.env.SHOGO_API_KEY;if(Z){await Y1({key:Z,cloudUrl:Y,cfg:X,name:$.name});return}let z=i2(),J;try{J=await g2({cloudUrl:Y,deviceId:z,deviceName:$.name,workspaceId:$.workspace,openBrowser:!$.noBrowser})}catch(K){if(K instanceof D){if(console.error(_.red(`✗ ${K.message}`)),K.kind==="transport")console.error(_.dim(" If your network blocks browsers, run with --api-key <key> instead."));process.exit(1)}throw K}if(X.apiKey=J.key,X.cloudUrl=Y,$.name)X.name=$.name;if(s(X),console.log(""),console.log(_.green("✓ Signed in to Shogo Cloud")),J.workspace)console.log(_.dim(" workspace: ")+J.workspace);if(J.email)console.log(_.dim(" email: ")+J.email);console.log(_.dim(" saved to: ")+"~/.shogo/config.json"),console.log(""),console.log(_.dim(" next: ")+"shogo worker start")}async function Y1({key:$,cloudUrl:X,cfg:Y,name:Z}){if(!/^shogo_sk_/.test($))console.error(_.red('✗ API key should start with "shogo_sk_". Copy it verbatim from the API Keys page.')),process.exit(1);let z;try{let J=await fetch(`${X}/api/api-keys/validate`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:$}),signal:AbortSignal.timeout(1e4)});if(z=await J.json().catch(()=>({})),!J.ok||!z?.valid)console.error(_.red(`✗ ${z?.error||`Cloud rejected the key (HTTP ${J.status}).`}`)),process.exit(1)}catch(J){console.error(_.red(`✗ Cannot reach Shogo Cloud at ${X}: ${J?.message??J}`)),process.exit(1)}if(Y.apiKey=$,Y.cloudUrl=X,Z)Y.name=Z;if(s(Y),console.log(_.green("✓ API key saved to ~/.shogo/config.json")),z.workspace?.name)console.log(_.dim(" workspace: ")+z.workspace.name);if(z.user?.email)console.log(_.dim(" email: ")+z.user.email);console.log(_.dim(" next: ")+"shogo worker start")}import J0 from"picocolors";async function c2(){let $=I();if(Object.keys($).length===0){console.log(J0.dim("(no config — run `shogo login` or `shogo config set`)"));return}let X={...$,apiKey:$.apiKey?`***${$.apiKey.slice(-4)}`:void 0};console.log(J0.dim(`file: ${j}`)),console.log(JSON.stringify(X,null,2))}async function a2($,X){let Y=["apiKey","cloudUrl","name","workerDir","port"];if(!Y.includes($))console.error(J0.red(`Unknown key: ${$}`)),console.error(J0.dim(`Allowed: ${Y.join(", ")}`)),process.exit(1);let Z=I();Z[$]=$==="port"?parseInt(X,10):X,s(Z),console.log(J0.green(`✓ ${$} set`))}import N from"picocolors";import{spawn as Z1}from"node:child_process";import{createHash as z1}from"node:crypto";import{createWriteStream as J1,existsSync as K0,mkdirSync as a0,readFileSync as r2,renameSync as o2,rmSync as o0,writeFileSync as K1}from"node:fs";import{tmpdir as V1}from"node:os";import{dirname as q1,join as A0}from"node:path";import{Readable as H1}from"node:stream";import{pipeline as Q1}from"node:stream/promises";var G1="https://github.com/shogo-labs/shogo-ai/releases/download";function e2(){let{platform:$,arch:X}=process,Y;if($==="darwin")Y="darwin";else if($==="linux")Y="linux";else if($==="win32")Y="windows";else throw Error(`Unsupported platform: ${$}`);let Z;if(X==="arm64")Z="arm64";else if(X==="x64")Z="x64";else throw Error(`Unsupported arch: ${X} (need arm64 or x64)`);return`${Y}-${Z}`}function N0(){if(!K0(e))return null;try{let $=r2(e,"utf-8");return JSON.parse($)}catch{return null}}async function W1($,X){let Y=X.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/releases\/download/);if(!Y)throw Error(`Cannot auto-resolve latest version from non-GitHub baseUrl '${X}'. Pass --version explicitly.`);let Z=Y[1],z=Y[2];if($==="stable"){let Q=`https://api.github.com/repos/${Z}/${z}/releases/latest`,G=await fetch(Q,{headers:{Accept:"application/vnd.github+json"}});if(!G.ok)throw Error(`GitHub API ${G.status} for ${Q}`);let k=await G.json();if(!k.tag_name)throw Error("GitHub API did not return tag_name");return l2(k.tag_name)}let J=`https://api.github.com/repos/${Z}/${z}/releases?per_page=30`,K=await fetch(J,{headers:{Accept:"application/vnd.github+json"}});if(!K.ok)throw Error(`GitHub API ${K.status} for ${J}`);let V=await K.json(),H=$==="beta"?"-beta":"-nightly",q=V.find((Q)=>Q.prerelease&&/^v\d+\.\d+\.\d+-/.test(Q.tag_name)&&Q.tag_name.includes(H));if(!q)throw Error(`No ${$} runtime release found`);return l2(q.tag_name)}function l2($){if(!/^v\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test($))throw Error(`Unexpected app tag '${$}' (expected vX.Y.Z[-prerelease])`);return $.slice(1)}function k1($,X,Y){let Z=`shogo-agent-runtime-${X}.tar.gz`,z=`v${$}`,J=`${Y.replace(/\/$/,"")}/${z}/${Z}`;return{tarball:J,sha256:`${J}.sha256`,assetName:Z}}async function O1($,X){let Y=await fetch($,{redirect:"follow"});if(!Y.ok)throw Error(`Download failed: HTTP ${Y.status} for ${$}`);if(!Y.body)throw Error(`Download failed: empty body for ${$}`);await Q1(H1.fromWeb(Y.body),J1(X))}async function w1($){let X=await fetch($,{redirect:"follow"});if(!X.ok)throw Error(`SHA256 sidecar fetch failed: HTTP ${X.status} for ${$}`);let Z=(await X.text()).trim().split(/\s+/)[0];if(!/^[0-9a-f]{64}$/i.test(Z))throw Error(`SHA256 sidecar at ${$} did not contain a 64-char hex digest`);return Z.toLowerCase()}function C1($){let X=r2($);return z1("sha256").update(X).digest("hex")}async function L1($,X){await new Promise((Y,Z)=>{let z=Z1("tar",["-xzf",$,"-C",X],{stdio:["ignore","pipe","pipe"]}),J="";z.stderr.on("data",(K)=>{J+=K.toString()}),z.on("error",Z),z.on("exit",(K)=>{if(K===0)Y();else Z(Error(`tar exited ${K}: ${J.trim()}`))})})}function U1($,X){s0();let Y=q1(X);if(!K0(Y))a0(Y,{recursive:!0,mode:448});let Z=`${X}.next`;if(K0(Z))o0(Z,{force:!0});o2($,Z);try{if(process.platform!=="win32"){let{chmodSync:z}=y0("node:fs");z(Z,493)}}catch{}if(K0(X))o0(X,{force:!0});o2(Z,X)}async function s2($={}){let X=$.logger??console,Y=$.channel??"stable",Z=$.baseUrl??process.env.SHOGO_RUNTIME_RELEASES_URL??G1,z=$.target??e2(),J=$.version;if(!J)X.log(`[runtime install] Resolving latest ${Y} version...`),J=await W1(Y,Z),X.log(`[runtime install] Latest ${Y} = ${J}`);let K=N0();if(K&&K.version===J&&K.target===z&&!$.force)return X.log(`[runtime install] ${J} (${z}) already installed at ${S} — pass --force to reinstall`),{version:J,target:z,binPath:S,source:K.source,sha256:K.sha256,channel:Y};let V=k1(J,z,Z);X.log(`[runtime install] Downloading ${V.tarball}`);let H=A0(V1(),`shogo-runtime-install-${process.pid}-${Date.now()}`);a0(H,{recursive:!0});try{let q=A0(H,V.assetName);await O1(V.tarball,q),X.log("[runtime install] Verifying SHA-256...");let Q=await w1(V.sha256),G=C1(q);if(G!==Q)throw Error(`SHA-256 mismatch for ${V.assetName}
18
- expected: ${Q}
19
- actual: ${G}`);let k=A0(H,"extract");a0(k,{recursive:!0}),await L1(q,k);let C=A0(k,"agent-runtime");if(!K0(C))throw Error(`Tarball ${V.assetName} did not contain ./agent-runtime`);U1(C,S);let W={version:J,target:z,installedAt:new Date().toISOString(),channel:Y,source:V.tarball,sha256:G};return K1(e,JSON.stringify(W,null,2)+`
20
- `,{mode:384}),X.log(`[runtime install] Installed agent-runtime ${J} (${z}) to ${S}`),{version:J,target:z,binPath:S,source:V.tarball,sha256:G,channel:Y}}finally{try{o0(H,{recursive:!0,force:!0})}catch{}}}function t2(){return{runtimeDir:r,runtimeBin:S,versionFile:e}}async function l0($={}){let X=await s2({channel:$.channel,version:$.version,baseUrl:$.baseUrl,force:$.force});console.log(),console.log(N.green("✓"),`agent-runtime ${N.bold(X.version)} installed (${X.target})`),console.log(` ${N.dim("path: ")} ${X.binPath}`),console.log(` ${N.dim("source: ")} ${X.source}`),console.log(` ${N.dim("sha256: ")} ${X.sha256}`),console.log(` ${N.dim("channel: ")} ${X.channel}`)}function $$(){let $=N0();if(!$){console.log(N.yellow("No agent-runtime installed.")),console.log(`Run ${N.cyan("shogo runtime install")} to download the latest.`),process.exitCode=1;return}console.log(`${N.bold("agent-runtime")} ${$.version}`),console.log(` ${N.dim("target: ")} ${$.target}`),console.log(` ${N.dim("channel: ")} ${$.channel}`),console.log(` ${N.dim("installed at:")} ${$.installedAt}`),console.log(` ${N.dim("source: ")} ${$.source}`)}function X$(){let $=u(),X=t2();if(!$){console.log(N.yellow("agent-runtime binary not found on this machine.")),console.log(),console.log(N.dim("Default install path:"),X.runtimeBin),console.log(),console.log(n()),process.exitCode=1;return}if(console.log($.path),process.env.SHOGO_DEBUG||process.env.VERBOSE)console.log(N.dim(` (resolved via: ${$.source})`))}async function Y$($={}){let X=N0(),Y=$.channel??X?.channel??"stable";if(X)console.log(`${N.dim("current:")} ${X.version} (${X.target}, ${X.channel})`);else console.log(N.dim("No existing install — installing fresh..."));await l0({channel:Y,baseUrl:$.baseUrl,force:!0})}import{existsSync as A1,mkdirSync as N1}from"node:fs";import{resolve as B1}from"node:path";import U from"picocolors";import{CloudFileTransport as F1}from"@shogo-ai/sdk/cloud-file-transport";async function Z$($,X){if(!$)throw Error("projectId is required");let Y=R({apiKey:X.apiKey,cloudUrl:X.cloudUrl});t0(Y.projectsDir);let Z=B1(X.into??g($,Y.projectsDir));if(!A1(Z))N1(Z,{recursive:!0});let z=X.include?.split(",").map((V)=>V.trim()).filter(Boolean);if(console.log(U.bold(`
21
- shogo project pull ${U.cyan($)}`)),console.log(U.dim(" cloud ")+Y.cloudUrl),console.log(U.dim(" into ")+Z),z?.length)console.log(U.dim(" include ")+z.join(", "));console.log("");let J=new F1({apiUrl:Y.cloudUrl,apiKey:Y.apiKey,projectId:$,localDir:Z,include:z,onProgress:T1()}),K=await J.downloadAll();if(y1("Pull",K),X.watch){console.log(U.bold(`
22
- Watching for local changes...`));let V=new Z0({rootDir:Z,transport:J,onFlush:({uploaded:Q,errors:G})=>{let k=Q.length===1?Q[0]:`${Q.length} files`,C=G>0?U.red(` (${G} errors)`):"";console.log(U.dim(` ↑ ${k}${C}`))}});V.start();let H=!1,q=async(Q)=>{if(H)return;H=!0,console.log(U.dim(`
23
- Received ${Q} — flushing pending uploads...`));try{await V.stop()}catch(G){console.warn(U.yellow(`watcher.stop: ${G?.message??G}`))}process.exit(0)};process.once("SIGINT",()=>void q("SIGINT")),process.once("SIGTERM",()=>void q("SIGTERM")),process.once("SIGHUP",()=>void q("SIGHUP")),await new Promise(()=>{})}}function T1(){return($)=>{let X=$.kind==="download"?"↓":$.kind==="upload"?"↑":$.kind==="delete"?"✗":"·",Y=$.total>0?` ${$.index+1}/${$.total}`:"",Z=$.bytes!=null?U.dim(` (${_1($.bytes)})`):"";console.log(U.dim(` ${X}${Y} ${$.path}${Z}`))}}function y1($,X){let Y=X.errors.length===0,Z=Y?U.green(`✓ ${$} complete`):U.red(`✗ ${$} completed with errors`);if(console.log(`
24
- ${Z}`),console.log(U.dim(" downloaded: ")+X.downloaded),X.uploaded)console.log(U.dim(" uploaded: ")+X.uploaded);if(X.deleted)console.log(U.dim(" deleted: ")+X.deleted);if(X.skipped)console.log(U.dim(" skipped: ")+X.skipped);if(!Y){console.log(U.dim(" errors: ")+X.errors.length);for(let z of X.errors.slice(0,5))console.log(U.dim(" ")+U.red(`${z.path}: ${z.message}`));if(X.errors.length>5)console.log(U.dim(` ... and ${X.errors.length-5} more`))}}function _1($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;return`${($/1024/1024).toFixed(2)}MB`}import{existsSync as x1}from"node:fs";import{resolve as M1}from"node:path";import B from"picocolors";import{CloudFileTransport as D1}from"@shogo-ai/sdk/cloud-file-transport";async function z$($,X){if(!$)throw Error("projectId is required");let Y=R({apiKey:X.apiKey,cloudUrl:X.cloudUrl}),Z=M1(X.from??g($,Y.projectsDir));if(!x1(Z))throw Error(`Source directory does not exist: ${Z}`);let z=X.include?.split(",").map((V)=>V.trim()).filter(Boolean);if(console.log(B.bold(`
25
- shogo project push ${B.cyan($)}`)),console.log(B.dim(" cloud ")+Y.cloudUrl),console.log(B.dim(" from ")+Z),z?.length)console.log(B.dim(" include ")+z.join(", "));if(X.deleteRemote)console.log(B.yellow(" --delete-remote: remote files not present locally will be DELETED"));console.log("");let K=await new D1({apiUrl:Y.cloudUrl,apiKey:Y.apiKey,projectId:$,localDir:Z,include:z,onProgress:(V)=>{let H=V.kind==="upload"?"↑":V.kind==="delete"?"✗":"·",q=V.total>0?` ${V.index+1}/${V.total}`:"",Q=V.bytes!=null?B.dim(` (${S1(V.bytes)})`):"";console.log(B.dim(` ${H}${q} ${V.path}${Q}`))}}).uploadAll({deleteRemote:X.deleteRemote});P1("Push",K)}function P1($,X){let Y=X.errors.length===0,Z=Y?B.green(`✓ ${$} complete`):B.red(`✗ ${$} completed with errors`);if(console.log(`
26
- ${Z}`),console.log(B.dim(" uploaded: ")+X.uploaded),X.deleted)console.log(B.dim(" deleted: ")+X.deleted);if(!Y){console.log(B.dim(" errors: ")+X.errors.length);for(let z of X.errors.slice(0,5))console.log(B.dim(" ")+B.red(`${z.path}: ${z.message}`));if(X.errors.length>5)console.log(B.dim(` ... and ${X.errors.length-5} more`))}}function S1($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;return`${($/1024/1024).toFixed(2)}MB`}import{existsSync as R1}from"node:fs";import{resolve as b1}from"node:path";import b from"picocolors";w0();async function J$($,X){if(!$)throw Error("projectId is required");let Y=R({apiKey:X.apiKey,cloudUrl:X.cloudUrl}),Z=b1(X.into??g($,Y.projectsDir));if(!R1(Z))throw Error(`Local project dir does not exist: ${Z} — run \`shogo project pull\` first`);if(!Y0(Z))throw Error(`${Z} is not a git repo. \`shogo project checkout\` requires the git sync path; run \`shogo project pull\` after installing git, or use \`shogo project pull --include\` for file-only restore.`);if(console.log(b.bold(`
27
- shogo project checkout ${b.cyan($)}`)),console.log(b.dim(" cloud ")+Y.cloudUrl),console.log(b.dim(" local ")+Z),X.at)console.log(b.dim(" at ")+X.at);if(console.log(""),X.unshallow)console.log(b.dim("Unshallowing repo (this may take a moment)...")),await O0({apiUrl:Y.cloudUrl,apiKey:Y.apiKey,projectId:$,localDir:Z});if(!X.at){let J=await X0({apiUrl:Y.cloudUrl,apiKey:Y.apiKey,projectId:$,localDir:Z});console.log(b.green(`✓ Reset to ${J.commitSha.slice(0,8)} (remote HEAD)`));return}let z;try{z=(await y(["rev-parse","--verify",`${X.at}^{commit}`],{cwd:Z})).stdout.trim()}catch{z=await E1(Y.cloudUrl,Y.apiKey,$,X.at),console.log(b.dim(` resolved checkpoint "${X.at}" → ${z.slice(0,8)}`))}try{await X0({apiUrl:Y.cloudUrl,apiKey:Y.apiKey,projectId:$,localDir:Z,branch:z})}catch{if(!X.unshallow)console.log(b.yellow(" fetch failed; unshallowing and retrying...")),await O0({apiUrl:Y.cloudUrl,apiKey:Y.apiKey,projectId:$,localDir:Z}),await X0({apiUrl:Y.cloudUrl,apiKey:Y.apiKey,projectId:$,localDir:Z,branch:z});else throw Error(`Cannot reach commit ${z} in local clone`)}await y(["reset","--hard",z],{cwd:Z}),console.log(b.green(`✓ Checked out ${z.slice(0,8)}`))}async function E1($,X,Y,Z){let z=`${$.replace(/\/+$/,"")}/api/projects/${encodeURIComponent(Y)}/checkpoints?limit=100`,J=await fetch(z,{headers:{Authorization:`Bearer ${X}`}});if(!J.ok)throw Error(`Failed to list checkpoints: HTTP ${J.status}`);let K=await J.json(),V=Z.toLowerCase(),H=K.checkpoints.find((q)=>{if(q.name&&q.name.toLowerCase()===V)return!0;if(q.commitSha.startsWith(Z))return!0;if(q.commitMessage&&q.commitMessage.toLowerCase().includes(V))return!0;return!1});if(!H)throw Error(`No checkpoint matches "${Z}" (searched ${K.checkpoints.length} most recent)`);return H.commitSha}import{createInterface as I1}from"node:readline";import A from"picocolors";import{execFileSync as V$}from"node:child_process";import{existsSync as c,copyFileSync as K$}from"node:fs";import P from"node:path";import{homedir as q$,platform as H$}from"node:os";function Q$($,X,Y){let z=V$($,["-e",Y],{env:{...process.env,DBP:X},encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5000}).trim();if(!z)throw Error(`bun script returned empty output for ${X}`);return JSON.parse(z)}function B0($,X){if(!c(X))return[];return Q$($,X,`
9
+ `));return!t}import{accessSync as Wr,constants as Nr,existsSync as jr}from"node:fs";import{delimiter as Fr,join as Lr}from"node:path";function F(e={}){let t=e.env??process.env,r=Hr(e);for(let i of r)if(ut(i.path))return i;let o=e.systemBinName??ct(),n=Gr(o,t.PATH);if(n)return{path:n,source:"path"};return null}function Hr(e){let t=e.env??process.env,r=[];if(e.flag&&e.flag.trim())r.push({path:e.flag.trim(),source:"flag"});let o=t.SHOGO_AGENT_RUNTIME_BIN?.trim();if(o)r.push({path:o,source:"env"});return r.push({path:_,source:"home"}),r}function ct(){return process.platform==="win32"?"shogo-agent-runtime.exe":"shogo-agent-runtime"}function ut(e){if(!jr(e))return!1;try{if(process.platform==="win32")return!0;return Wr(e,Nr.X_OK),!0}catch{return!1}}function Gr(e,t){if(!t)return null;for(let r of t.split(Fr)){if(!r)continue;let o=Lr(r,e);if(ut(o))return o}return null}function H(e={}){let t=e.env??process.env,r=[];if(r.push("Error: agent-runtime binary not found."),r.push(""),r.push("Looked in (priority order):"),e.flag)r.push(` --runtime-bin ${e.flag}`);if(t.SHOGO_AGENT_RUNTIME_BIN)r.push(` $SHOGO_AGENT_RUNTIME_BIN = ${t.SHOGO_AGENT_RUNTIME_BIN}`);return r.push(` ${_} (default install location)`),r.push(` ${ct()} on $PATH`),r.push(""),r.push("Fix:"),r.push(" - Run `shogo runtime install` to download the latest binary, or"),r.push(" - Pass `--runtime-bin <path>` to point at an existing build."),r.join(`
10
+ `)}import{spawn as so,spawnSync as ao}from"node:child_process";import{createHmac as Ct,randomBytes as lo}from"node:crypto";import{existsSync as Me,mkdirSync as bt,readdirSync as _t}from"node:fs";import{createConnection as co}from"node:net";import{tmpdir as uo}from"node:os";import{dirname as po,join as q}from"node:path";import{spawnSync as xe}from"node:child_process";import{existsSync as Br,mkdirSync as Kr,writeFileSync as pe}from"node:fs";import{join as K}from"node:path";var pt=1e5;function dt(e){let t=parseInt(e.RUNTIME_MEMORY_MB||"",10);if(!Number.isFinite(t)||t<=0)return null;let r=parseInt(e.RUNTIME_CPU_PERCENT||"0",10),o=Number.isFinite(r)&&r>0?r:0,n=parseInt(e.RUNTIME_TASKS_MAX||"",10),i=Number.isFinite(n)&&n>0?n:4096;return{memoryMB:t,cpuPercent:o,tasksMax:i}}function mt(e,t){let o=`--max-old-space-size=${Math.max(256,Math.floor(t*0.75))}`,n=e.NODE_OPTIONS?.trim();if(n){if(/--max-old-space-size=/.test(n))return;e.NODE_OPTIONS=`${n} ${o}`}else e.NODE_OPTIONS=o}function qr(){if(process.platform!=="linux")return!1;try{return xe("systemd-run",["--version"],{stdio:"ignore",timeout:3000}).status===0}catch{return!1}}function ht(e){let{command:t,args:r,limits:o,scopeName:n,logger:i}=e;if(process.platform!=="linux"||!qr())return{command:t,args:r,wrapped:!1};let s=["-p",`MemoryMax=${o.memoryMB}M`,"-p",`MemoryHigh=${Math.max(128,Math.floor(o.memoryMB*0.9))}M`,"-p",`TasksMax=${o.tasksMax}`];if(o.cpuPercent>0)s.push("-p",`CPUQuota=${o.cpuPercent}%`);let a=["--user","--scope","--quiet","--collect",`--unit=${n}`,...s,"--",t,...r];return i?.log(`[resource-limits] wrapping spawn in systemd scope ${n} (MemoryMax=${o.memoryMB}M)`),{command:"systemd-run",args:a,wrapped:!0}}function gt(e){let{pid:t,limits:r,logger:o}=e;if(process.platform!=="linux")return!1;let n="/sys/fs/cgroup";if(!Br(K(n,"cgroup.controllers")))return!1;let i=K(n,"shogo",`rt-${t}`);try{if(Kr(i,{recursive:!0}),pe(K(i,"memory.max"),String(r.memoryMB*1024*1024)),r.cpuPercent>0){let s=Math.floor(r.cpuPercent/100*pt);pe(K(i,"cpu.max"),`${s} ${pt}`)}try{pe(K(i,"pids.max"),String(r.tasksMax))}catch{}return pe(K(i,"cgroup.procs"),String(t)),o?.log(`[resource-limits] attached pid ${t} to cgroup ${i} (memory.max=${r.memoryMB}M)`),!0}catch(s){return o?.warn(`[resource-limits] direct cgroup attach failed for pid ${t}: ${s?.message??s}`),!1}}function ft(e){let{pid:t,limits:r,logger:o}=e;if(process.platform!=="win32")return!1;let n=process.env.SHOGO_WINJOB_HELPER||"@shogo/winjob";try{let i=Pe(n);if(typeof i.limitProcess!=="function")return!1;let s=i.limitProcess(t,{memoryBytes:r.memoryMB*1024*1024,killOnClose:!0});if(s)o?.log(`[resource-limits] attached pid ${t} to Job Object (${r.memoryMB}M)`);return s}catch{return!1}}function Jr(e,t=process.platform){try{if(t==="win32"){let i=`$ErrorActionPreference='SilentlyContinue';$root=${e};$all=Get-CimInstance Win32_Process;$seen=@{};$stack=New-Object System.Collections.Stack;$stack.Push($root);$sum=0;while($stack.Count -gt 0){$id=$stack.Pop();if($seen[$id]){continue};$seen[$id]=$true;foreach($p in $all){if($p.ProcessId -eq $id){$sum+=$p.WorkingSetSize};if($p.ParentProcessId -eq $id){$stack.Push($p.ProcessId)}}};[math]::Floor($sum/1024)`,s=xe("powershell.exe",["-NoProfile","-NonInteractive","-Command",i],{encoding:"utf-8",timeout:1e4,windowsHide:!0});if(s.status!==0||!s.stdout)return null;let a=parseInt(s.stdout.trim(),10);return Number.isFinite(a)?a:null}let r=xe("ps",["-o","rss=","-g",String(e)],{encoding:"utf-8",timeout:5000});if(r.status!==0||!r.stdout)return null;let o=0,n=!1;for(let i of r.stdout.split(`
11
+ `)){let s=parseInt(i.trim(),10);if(Number.isFinite(s))o+=s,n=!0}return n?o:null}catch{return null}}class Ce{timer=null;consecutive=0;fired=!1;pid;ceilingMB;platform;intervalMs;strikes;logger;onBreach;constructor(e){this.pid=e.pid,this.ceilingMB=e.ceilingMB,this.platform=e.platform??process.platform,this.intervalMs=e.intervalMs??parseInt(process.env.RUNTIME_RSS_WATCHDOG_MS||"15000",10),this.strikes=e.strikes??parseInt(process.env.RUNTIME_RSS_WATCHDOG_STRIKES||"2",10),this.logger=e.logger,this.onBreach=e.onBreach}start(){if(this.timer)return;this.timer=setInterval(()=>this.sample(),Math.max(2000,this.intervalMs));try{this.timer.unref?.()}catch{}}stop(){if(this.timer)clearInterval(this.timer),this.timer=null}sample(){if(this.fired)return;let e=Jr(this.pid,this.platform);if(e==null){this.consecutive=0;return}let t=Math.floor(e/1024);if(t<=this.ceilingMB){this.consecutive=0;return}if(this.consecutive+=1,this.logger?.warn(`[resource-limits] pid ${this.pid} RSS ${t}MB over ceiling ${this.ceilingMB}MB (strike ${this.consecutive}/${this.strikes})`),this.consecutive>=this.strikes)this.fired=!0,this.stop(),this.onBreach(t)}}import{CloudFileTransport as De}from"@shogo-ai/sdk/cloud-file-transport";import{killViteWatchFromPidfile as St}from"@shogo-ai/sdk/vite-watch";import{watch as vt,statSync as Zr}from"node:fs";import{relative as Ei,sep as eo,posix as to}from"node:path";var ro=1500,oo=new Set(["node_modules",".git","dist","build",".vite",".cache"]),no=[".shogo/"];function io(e){if(!e)return!0;return e.split("/").some((t)=>oo.has(t))}class te{rootDir;transport;debounceMs;logger;onFlush;mode;git;commitAndPush;watcher=null;pending=new Set;timer=null;flushing=!1;stopped=!1;constructor(e){if(this.rootDir=e.rootDir,this.transport=e.transport,this.debounceMs=e.debounceMs??ro,this.logger=e.logger??console,this.onFlush=e.onFlush,this.mode=e.mode??"files",this.mode==="git"&&!e.git)throw Error('CloudSyncWatcher: mode: "git" requires the `git` option block');this.git=e.git,this.commitAndPush=e.commitAndPush??(async(t)=>{let r=await Promise.resolve().then(() => (ge(),{}));return Qr(t)})}start(){if(this.watcher)return;if(this.stopped)throw Error("CloudSyncWatcher: already stopped, build a fresh instance");try{this.watcher=vt(this.rootDir,{recursive:!0},(e,t)=>{if(!t)return;this.handleEvent(String(t))})}catch(e){this.logger.warn(`[CloudSyncWatcher] recursive watch failed (${e?.message??e}); falling back to root-only watch.`),this.watcher=vt(this.rootDir,(t,r)=>{if(!r)return;this.handleEvent(String(r))})}}async stop(){if(this.stopped)return;if(this.stopped=!0,this.timer)clearTimeout(this.timer),this.timer=null;if(this.watcher){try{this.watcher.close()}catch{}this.watcher=null}if(this.pending.size>0)await this.flush()}handleEvent(e){if(this.stopped)return;let t=e.split(eo).join(to.sep);if(io(t))return;try{let r=`${this.rootDir}/${t}`;if(Zr(r).isDirectory())return}catch{return}this.pending.add(t),this.scheduleFlush()}scheduleFlush(){if(this.timer)return;this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.debounceMs)}async flush(){if(this.flushing){this.scheduleFlush();return}if(this.pending.size===0)return;this.flushing=!0;let e=Array.from(this.pending);this.pending.clear();try{if(this.mode==="git")await this.flushGit(e);else await this.flushFiles(e)}catch(t){this.logger.error(`[CloudSyncWatcher] flush failed: ${t?.message??t}`);for(let r of e)this.pending.add(r);this.scheduleFlush()}finally{this.flushing=!1}}async flushFiles(e){if(e.length===0)return;let t=await this.transport.uploadFiles(e);if(this.onFlush?.({uploaded:e,errors:t.errors.length}),t.errors.length>0)for(let r of t.errors)this.logger.warn(`[CloudSyncWatcher] upload ${r.path}: ${r.message}`)}async flushGit(e){if(!this.git)throw Error("CloudSyncWatcher: missing git options");let t=[],r=[];for(let i of e)if(no.some((s)=>i===s.slice(0,-1)||i.startsWith(s)))t.push(i);else r.push(i);if(t.length>0){let i=await this.transport.uploadFiles(t);if(i.errors.length>0)for(let s of i.errors)this.logger.warn(`[CloudSyncWatcher] upload ${s.path}: ${s.message}`)}let o=!1,n;if(r.length>0){let i=`auto: ${new Date().toISOString()}`;try{let s=await this.commitAndPush({apiUrl:this.git.apiUrl,apiKey:this.git.apiKey,projectId:this.git.projectId,localDir:this.rootDir,message:i,branch:this.git.branch,authorEmail:this.git.authorEmail,authorName:this.git.authorName,logger:this.logger});o=s.committed,n=s.commitSha}catch(s){throw s}}this.onFlush?.({uploaded:e,errors:0,committed:o,commitSha:n})}}ge();var Ue=37100,We=37900,kt=1,mo=2,fe=16,ho=900000,go=30000,fo=1000,wo=60000,Rt=8,Pt=300000,$t=3600000,yo=8,vo=120000,bo=900000,So=60000,ko=500,Ro=30000,Tt=25000,Po=5000,$o=500,To=process.env.SHOGO_PERF_LOG==="1";function we(e,t,r,o){if(!To)return;console.log(`[shogo-perf] ${JSON.stringify({perf:"open",source:"worker",phase:e,projectId:t,openAttemptId:r,atMs:Date.now(),...o})}`)}var Eo=(e)=>({command:e,args:[]}),Ne=null;function At(){if(!Ne)Ne=lo(32).toString("hex");return Ne}function Et(e){return Ct("sha256",At()).update(`runtime:${e}`).digest("hex")}function Io(e){return Ct("sha256",At()).update(`webhook:${e}`).digest("hex")}function It(e){let t=e.indexOf("?");if(t===-1)return{pathname:e,search:""};return{pathname:e.slice(0,t),search:e.slice(t)}}function xt(e){try{return _t(e).length===0}catch{return!0}}function je(e,t,r){let o=[];switch(o.push(`Cannot spawn agent-runtime for project ${e}: no workspace directory available.`),o.push(""),t){case"no-auto-pull-config":o.push(" Reason: WorkerRuntimeManager was constructed without an `autoPull` config and no caller-provided `projectDir` was found on disk."),o.push(" This usually means a programmatic embedder forgot to wire up enrichSpawnConfig "+"or autoPull. CLI users should not see this — please file a bug.");break;case"no-projects-dir":o.push(" Reason: auto-pull is configured but `projectsDir` is empty. The worker needs a persistent root directory under which it can store cloned project workspaces.");break;case"auto-pull-disabled":o.push(` Reason: auto-pull was disabled (--no-auto-pull) and the expected pre-pulled workspace at ${r} is missing or empty.`);break}return o.push(""),o.push(" How to fix (pick one):"),o.push(" 1. Re-enable auto-pull (default). Drop the --no-auto-pull flag and restart"),o.push(" the worker. The first inbound request for this project will clone its"),o.push(" workspace from Shogo Cloud into <projectsDir>/<projectId>/."),o.push(""),o.push(" 2. Pre-pull manually with `shogo project pull <projectId>` before starting"),o.push(" the worker. Use this when you want full control over when the clone runs"),o.push(" (slow links, scheduled maintenance windows, etc.)."),o.push(""),o.push(" 3. Point the worker at an existing workspace by setting either:"),o.push(" --projects-dir <path> (per-invocation flag)"),o.push(" SHOGO_PROJECTS_DIR=<path> (env var, persists across restarts)"),o.push(" shogo config set projectsDir <path>"),o.push(" Whichever path you pick must contain a subdirectory named after the "),o.push(` project id (e.g. <path>/${e}/) populated with the project's source.`),o.push(""),o.push(" Docs: https://shogo.ai/docs/self-hosted-worker#workspace-seeding"),o.join(`
12
+ `)}class Fe{opts;log;runtimes=new Map;usedPorts=new Set;spawnCommand;resolved=null;stopped=!1;resolvedLimits=void 0;watchers=new Map;pulledProjects=new Set;syncModes=new Map;constructor(e={}){this.opts=e,this.log=e.logger??console,this.spawnCommand=e.spawnCommand??Eo,this.sweepOrphanedViteWatches()}resolveBinary(){if(!this.resolved)this.resolved=this.opts.resolveBin?this.opts.resolveBin():F({flag:this.opts.runtimeBin,env:this.opts.env});return this.resolved}async resolveLocalUrl(e,t){let{pathname:r,search:o}=It(e);if(!(r.startsWith("/agent/")||r==="/agent"))return null;if(!t){let s=this.getActiveProjects();if(s.length!==1)return null;t=s[0]}let n=await this.spawnConfigFor(t);if(!n)return this.log.warn(`[WorkerRuntimeManager] No spawn config for ${t} — set defaultSpawnConfig or enrichSpawnConfig`),null;let i=await this.ensureRunning(t,n);if(!i.agentPort)return null;return this.touch(t),`http://127.0.0.1:${i.agentPort}${r}${o}`}deriveRuntimeToken(e){return Et(e)}describeRejection(e,t){let{pathname:r}=It(e);if(!(r.startsWith("/agent/")||r==="/agent"))return{code:"CLI_WORKER_HAS_NO_DATA_API",message:`cli-worker only serves /agent/* paths; tried: ${r}`};return{code:"CLI_WORKER_NO_PROJECT_FOR_PATH",message:`cli-worker received an /agent path without a single active project; projectId=${t??"none"}, path=${r}`}}async spawnConfigFor(e){let t=this.opts.defaultSpawnConfig;if(!t)return null;if(this.opts.enrichSpawnConfig)try{return await this.opts.enrichSpawnConfig(e,t)}catch(r){this.log.warn(`[WorkerRuntimeManager] enrichSpawnConfig failed for ${e}: ${r?.message??r}`)}return t}async ensureRunning(e,t){if(this.stopped)throw Error("WorkerRuntimeManager is stopped");let r=this.runtimes.get(e);if(r?.status==="failed"){let i=this.breakerCooldownMs(r.breakerTrips),s=Date.now()-r.lastFailureAt;if(s>=i)this.log.log(`[WorkerRuntimeManager] auto-heal: ${e} cooldown elapsed (${Math.round(s/1000)}s since trip #${r.breakerTrips}) — `+"clearing circuit breaker and attempting a fresh spawn"),this.healBreaker(r);else{let a=i-s;throw Error(`[WorkerRuntimeManager] cannot ensureRunning(${e}): ${r.lastError??"runtime is in failed state"} Will auto-retry in ~${Math.ceil(a/1000)}s; call resetFailure(${e}) to retry immediately, or stop(${e}) to give up.`)}}t=await this.maybeAutoPull(e,t);let o=this.runtimes.get(e);if(o?.status==="running")return this.touch(e),this.snapshot(o);if(o?.startPromise){let i=await o.startPromise;return this.snapshot(i)}let n=o??this.makeSlot(e,t);if(!o)this.runtimes.set(e,n);n.spawnConfig=t,n.startPromise=this.doStart(n);try{let i=await n.startPromise;return this.enforceMaxRuntimes(e),this.snapshot(i)}finally{n.startPromise=null}}enforceMaxRuntimes(e){let t=this.opts.maxRuntimes;if(t==null||!Number.isFinite(t)||t<=0)return;let r=Date.now(),o=Array.from(this.runtimes.values()).filter((s)=>s.status==="running");if(o.length<=t)return;let n=o.filter((s)=>s.projectId!==e&&r-s.lastUsedAt>=go).sort((s,a)=>s.lastUsedAt-a.lastUsedAt),i=o.length-t;for(let s of n){if(i<=0)break;let a=r-s.lastUsedAt;this.log.log(`[WorkerRuntimeManager] maxRuntimes=${t} exceeded (${o.length} running) — `+`LRU-evicting ${s.projectId} (idle ${Math.round(a/1000)}s)`),this.stop(s.projectId,"SIGTERM","lru-evict").catch((c)=>{this.log.warn(`[WorkerRuntimeManager] maxRuntimes eviction of ${s.projectId} failed: ${c?.message??c}`)}),i--}if(i>0)this.log.log(`[WorkerRuntimeManager] maxRuntimes=${t} still exceeded by ${i} after eviction pass — `+"remaining over-cap slots are mid-stream; will retry on next spawn / idle reap")}async ensurePulled(e,t){return this.maybeAutoPull(e,t)}async maybeAutoPull(e,t){let r=this.opts.autoPull;if(t.projectDir&&Me(t.projectDir))return t;if(!r)throw Error(je(e,"no-auto-pull-config",null));if(!r.projectsDir)throw Error(je(e,"no-projects-dir",null));if(!r.enabled){let s=q(r.projectsDir,e);if(Me(s)&&!xt(s))return{...t,projectDir:s};throw Error(je(e,"auto-pull-disabled",s))}if(this.pulledProjects.has(e))return{...t,projectDir:q(r.projectsDir,e)};let o=q(r.projectsDir,e),n=r.logger??this.log,i={cloneProject:r.gitOps?.cloneProject??yt,gitIsAvailable:r.gitOps?.gitIsAvailable??wt,isGitRepo:r.gitOps?.isGitRepo??he};this.pulledProjects.add(e);try{bt(o,{recursive:!0});let s=xt(o),a=i.isGitRepo(o),u=(r.useGit!==!1?await i.gitIsAvailable():!1)&&(s||a)?"git":"files";if(this.syncModes.set(e,u),u==="git"){if(s){n.log(`[WorkerRuntimeManager] auto-pull: git clone project ${e} into ${o}`);try{let p=await i.cloneProject({apiUrl:t.cloudUrl,apiKey:t.apiKey,projectId:e,localDir:o,shallow:!0,logger:n});n.log(`[WorkerRuntimeManager] auto-pull: ${e} cloned at ${p.commitSha.slice(0,8)}`)}catch(p){n.warn(`[WorkerRuntimeManager] auto-pull: git clone failed for ${e} (${p?.message??p}); falling back to CloudFileTransport.downloadAll`),this.syncModes.set(e,"files"),await this.fileTransportClone(e,o,t,n)}}else if(a)n.log(`[WorkerRuntimeManager] auto-pull: ${e} already has .git/; skipping clone`);if(this.syncModes.get(e)==="git")await this.topUpShogoState(e,o,t,n)}else if(s)await this.fileTransportClone(e,o,t,n);else n.log(`[WorkerRuntimeManager] auto-pull: ${e} workspace already populated; skipping clone`);if(r.watch!==!1&&!this.watchers.has(e))try{let p=new De({apiUrl:t.cloudUrl,apiKey:t.apiKey,projectId:e,localDir:o}),m=this.syncModes.get(e)??"files",f=new te({rootDir:o,transport:p,logger:n,mode:m,git:m==="git"?{apiUrl:t.cloudUrl,apiKey:t.apiKey,projectId:e}:void 0});f.start(),this.watchers.set(e,f)}catch(p){n.warn(`[WorkerRuntimeManager] auto-pull: watcher start failed for ${e}: ${p?.message??p}`)}}catch(s){n.warn(`[WorkerRuntimeManager] auto-pull: failed for ${e} — runtime will fall back to template defaults. `+`(${s?.message??s})`)}return{...t,projectDir:o}}async fileTransportClone(e,t,r,o){o.log(`[WorkerRuntimeManager] auto-pull: file-transport clone of ${e} into ${t}`);let i=await new De({apiUrl:r.cloudUrl,apiKey:r.apiKey,projectId:e,localDir:t}).downloadAll();o.log(`[WorkerRuntimeManager] auto-pull: ${e} downloaded ${i.downloaded} files (${i.errors.length} errors)`)}async topUpShogoState(e,t,r,o){try{let n=new De({apiUrl:r.cloudUrl,apiKey:r.apiKey,projectId:e,localDir:t}),s=(await n.listManifest()).filter((c)=>c.path===".shogo"||c.path.startsWith(".shogo/"));if(s.length===0)return;let a=await n.downloadFiles(s);o.log(`[WorkerRuntimeManager] auto-pull: ${e} .shogo/ top-up downloaded ${a.downloaded} files (${a.errors.length} errors)`)}catch(n){o.warn(`[WorkerRuntimeManager] auto-pull: .shogo top-up failed for ${e}: ${n?.message??n}`)}}shouldDeferToCloudSync(e){return!!this.opts.autoPull?.enabled&&this.pulledProjects.has(e)}status(e){let t=this.runtimes.get(e);return t?this.snapshot(t):null}getActiveProjects(){return Array.from(this.runtimes.keys()).filter((e)=>{let t=this.runtimes.get(e);return t&&(t.status==="running"||t.status==="starting"||t.status==="restarting")})}touch(e){let t=this.runtimes.get(e);if(!t)return;t.lastUsedAt=Date.now(),this.armIdleTimer(t)}async stop(e,t="SIGTERM",r="stop"){let o=this.runtimes.get(e);if(!o)return;if(o.status="stopping",o.restartTimer)clearTimeout(o.restartTimer),o.restartTimer=null;if(o.idleTimer)clearTimeout(o.idleTimer),o.idleTimer=null;if(o.graceTimer)clearTimeout(o.graceTimer),o.graceTimer=null;if(o.limitWatchdog)o.limitWatchdog.stop(),o.limitWatchdog=null;if(o.proc){this.killProcessGroup(o,t),this.killViteWatch(o);try{o.proc.kill(t)}catch{}await this.waitForExit(o.proc,5000),this.killProcessGroup(o,"SIGKILL"),this.killViteWatch(o)}o.pid=null,this.releasePort(o.agentPort),this.runtimes.delete(e),this.notifyGone(e,{reason:r})}notifyGone(e,t){let r=this.opts.onRuntimeGone;if(!r)return;try{r(e,t)}catch(o){this.log.warn(`[WorkerRuntimeManager] onRuntimeGone(${e}) threw: ${o?.message??o}`)}}resetFailure(e){let t=this.runtimes.get(e);if(!t||t.status!=="failed")return!1;if(t.restartTimer)clearTimeout(t.restartTimer),t.restartTimer=null;if(t.idleTimer)clearTimeout(t.idleTimer),t.idleTimer=null;if(t.graceTimer)clearTimeout(t.graceTimer),t.graceTimer=null;if(t.limitWatchdog)t.limitWatchdog.stop(),t.limitWatchdog=null;return this.runtimes.delete(e),this.log.log(`[WorkerRuntimeManager] resetFailure: ${e} cleared, next ensureRunning will respawn`),!0}breakerCooldownMs(e){let t=Math.max(0,e-1),r=vo*Math.pow(2,t);return Math.min(r,bo)}healBreaker(e){e.status="stopped",e.consecutiveFailures=0}async stopAll(e="SIGTERM"){this.stopped=!0;let t=Array.from(this.watchers.keys());await Promise.all(t.map(async(o)=>{let n=this.watchers.get(o);if(this.watchers.delete(o),n)try{await n.stop()}catch(i){this.log.warn(`[WorkerRuntimeManager] watcher stop ${o}: ${i?.message??i}`)}}));let r=Array.from(this.runtimes.keys());await Promise.all(r.map((o)=>this.stop(o,e).catch((n)=>{this.log.error(`[WorkerRuntimeManager] Failed to stop ${o}: ${n?.message??n}`)})))}makeSlot(e,t){return{projectId:e,agentPort:0,apiServerPort:0,status:"starting",proc:null,pid:null,startedAt:0,lastStdoutAt:0,lastUsedAt:Date.now(),restarts:0,consecutiveFailures:0,lastFailureAt:0,breakerTrips:0,restartTimestamps:[],graceTimer:null,restartTimer:null,idleTimer:null,limitWatchdog:null,spawnConfig:t,startPromise:null}}async doStart(e){let t=this.resolveBinary();if(!t)throw e.status="error",e.lastError="agent-runtime binary not found (run `shogo runtime install`)",Error(e.lastError);if(!e.agentPort)e.agentPort=await this.allocatePort(),e.apiServerPort=e.agentPort+kt;let r=this.buildEnv(e,t.path),o=this.resolveCwd(e),n=this.spawnCommand(t.path),i=this.resolveLimits(),{command:s,args:a}=n,c=!1;if(i){let d=ht({command:n.command,args:n.args,limits:i,scopeName:`shogo-rt-${e.projectId.slice(0,8)}-${Date.now().toString(36)}`,logger:this.log});s=d.command,a=d.args,c=d.wrapped}this.log.log(`[WorkerRuntimeManager] Spawning agent-runtime for ${e.projectId} via ${s} ${a.join(" ")} (port=${e.agentPort}, source=${t.source}${i?`, memCeil=${i.memoryMB}M`:""})`);let l=process.platform!=="win32",u=so(s,a,{cwd:o,env:r,detached:l,stdio:["ignore","pipe","pipe"]});if(l)try{u.unref()}catch{}e.proc=u,e.pid=u.pid??null,e.status="starting",e.startedAt=Date.now();let p=e.spawnConfig.extraEnv?.SHOGO_OPEN_ID;if(we("agent-spawned",e.projectId,p,{pid:e.pid,command:s,args:a,source:t.source}),i)try{this.applyPostSpawnLimits(e,i,c)}catch(d){this.log.warn(`[WorkerRuntimeManager] failed to apply resource limits for ${e.projectId}: ${d?.message??d}`)}e.lastStdoutAt=e.startedAt,u.on("error",(d)=>{e.lastError=d?.message??String(d),this.log.error(`[WorkerRuntimeManager] spawn error for ${e.projectId}: ${e.lastError}`)}),u.on("exit",(d,w)=>{this.handleExit(e,d,w)});let m=`[runtime:${e.projectId.slice(0,8)}]`,f=!0;u.stdout?.on("data",(d)=>{if(e.lastStdoutAt=Date.now(),f)f=!1,we("agent-first-output",e.projectId,p,{elapsedMs:Date.now()-(e.startedAt??Date.now())});for(let w of d.toString().trimEnd().split(`
13
+ `))if(w)this.log.log(`${m} ${w}`)}),u.stderr?.on("data",(d)=>{if(e.lastStdoutAt=Date.now(),f)f=!1,we("agent-first-output",e.projectId,p,{elapsedMs:Date.now()-(e.startedAt??Date.now()),stream:"stderr"});for(let w of d.toString().trimEnd().split(`
14
+ `))if(w)this.log.error(`${m} ${w}`)});try{return await this.waitForHealth(e,Ro),we("agent-health-ready",e.projectId,p,{elapsedMs:Date.now()-(e.startedAt??Date.now()),agentPort:e.agentPort}),e.status="running",e.lastUsedAt=Date.now(),this.armIdleTimer(e),this.armGraceTimer(e),e}catch(d){e.status="error",e.lastError=d?.message??String(d),this.killProcessGroup(e,"SIGTERM"),this.killViteWatch(e);try{u.kill("SIGTERM")}catch{}throw this.releasePort(e.agentPort),e.agentPort=0,e.apiServerPort=0,d}}resolveLimits(){if(this.resolvedLimits===void 0)this.resolvedLimits=dt(this.opts.env??process.env);return this.resolvedLimits}applyPostSpawnLimits(e,t,r){let o=e.pid;if(!o)return;if(process.platform==="linux"){if(r)return;if(gt({pid:o,limits:t,logger:this.log}))return}else if(process.platform==="win32"){if(ft({pid:o,limits:t,logger:this.log}))return}e.limitWatchdog=new Ce({pid:o,ceilingMB:t.memoryMB,logger:this.log,onBreach:(n)=>this.handleLimitBreach(e,n,t.memoryMB)}),e.limitWatchdog.start()}handleLimitBreach(e,t,r){if(this.log.warn(`[WorkerRuntimeManager] runtime ${e.projectId} exceeded memory ceiling (${t}MB > ${r}MB) — restarting`),e.lastError=`memory ceiling exceeded (${t}MB > ${r}MB)`,e.limitWatchdog)e.limitWatchdog.stop(),e.limitWatchdog=null;this.killProcessGroup(e,"SIGTERM"),this.killViteWatch(e);try{e.proc?.kill("SIGTERM")}catch{}let o=setTimeout(()=>{this.killProcessGroup(e,"SIGKILL"),this.killViteWatch(e)},5000);try{o.unref?.()}catch{}}killProcessGroup(e,t){if(!e.pid)return;if(process.platform==="win32"){try{ao("taskkill",["/F","/T","/PID",String(e.pid)],{stdio:"ignore",windowsHide:!0})}catch{}return}try{process.kill(-e.pid,t)}catch{}}armGraceTimer(e){if(e.graceTimer)clearTimeout(e.graceTimer),e.graceTimer=null;e.graceTimer=setTimeout(()=>{if(e.graceTimer=null,e.consecutiveFailures>0)e.consecutiveFailures=0;e.breakerTrips=0,e.restartTimestamps=[]},So);try{e.graceTimer.unref?.()}catch{}}buildEnv(e,t){let r=e.spawnConfig,o={...this.opts.env??process.env,PROJECT_ID:e.projectId,PORT:String(e.agentPort),API_SERVER_PORT:String(e.apiServerPort),SKILL_SERVER_PORT:String(e.apiServerPort),WORKSPACE_API_PORT_BASE:String(e.agentPort+mo),NODE_ENV:"production",STARTUP_TIME:String(Date.now()),SHOGO_CLOUD_URL:r.cloudUrl,SHOGO_API_URL:r.cloudUrl,SHOGO_API_KEY:r.apiKey,RUNTIME_AUTH_SECRET:Et(e.projectId),WEBHOOK_TOKEN:Io(e.projectId)};if(r.projectDir)o.PROJECT_DIR=r.projectDir,o.WORKSPACE_DIR=r.projectDir;if(this.shouldDeferToCloudSync(e.projectId))o.SHOGO_CLOUD_SYNC="1";if(r.aiProxyUrl)o.AI_PROXY_URL=r.aiProxyUrl;if(r.aiProxyToken)o.AI_PROXY_TOKEN=r.aiProxyToken;if(r.techStackId)o.TECH_STACK_ID=r.techStackId;if(r.name)o.AGENT_NAME=r.name;if(r.workspaceId)o.WORKSPACE_ID=r.workspaceId;if(!o.TREE_SITTER_WASM_DIR)o.TREE_SITTER_WASM_DIR=q(po(t),"tree-sitter-wasm");if(r.extraEnv)Object.assign(o,r.extraEnv);let n=this.resolveLimits();if(n)mt(o,n.memoryMB);return o}killViteWatch(e){let t=e.spawnConfig.projectDir;if(!t)return;try{St(t,{logger:this.log})}catch(r){this.log.warn(`[WorkerRuntimeManager] Vite watch cleanup for ${e.projectId} failed: ${r?.message??r}`)}}sweepOrphanedViteWatches(){let e=this.opts.autoPull?.projectsDir;if(!e)return;let t;try{t=_t(e,{withFileTypes:!0})}catch{return}for(let r of t){if(!r.isDirectory()||this.runtimes.has(r.name))continue;let o=q(e,r.name);try{let n=St(o,{logger:this.log});if(n)this.log.log(`[WorkerRuntimeManager] Reaped orphaned Vite watch for ${r.name} (pid=${n.pid})`)}catch(n){this.log.warn(`[WorkerRuntimeManager] Vite watch startup sweep failed for ${r.name}: ${n?.message??n}`)}}}resolveCwd(e){let t=e.spawnConfig;if(t.projectDir&&Me(t.projectDir))return t.projectDir;let r=this.opts.runtimeWorkDir??q(uo(),"shogo-runtime",e.projectId);return bt(r,{recursive:!0}),r}handleExit(e,t,r){let o=r===null&&t===0;if(this.log.log(`[WorkerRuntimeManager] runtime ${e.projectId} exited (code=${t}, signal=${r})`),e.proc=null,e.graceTimer)clearTimeout(e.graceTimer),e.graceTimer=null;if(e.limitWatchdog)e.limitWatchdog.stop(),e.limitWatchdog=null;if(this.killViteWatch(e),e.status==="stopping"||this.stopped){e.status="stopped",e.pid=null,this.releasePort(e.agentPort),e.agentPort=0,e.apiServerPort=0;return}if(o){e.status="stopped",e.pid=null,this.releasePort(e.agentPort),e.agentPort=0,e.apiServerPort=0,this.runtimes.delete(e.projectId),this.notifyGone(e.projectId,{reason:"exited",code:t,signal:r});return}this.killProcessGroup(e,"SIGKILL"),this.killViteWatch(e),e.pid=null;let n=Date.now(),i=n-e.lastFailureAt<=Pt;e.consecutiveFailures=i?e.consecutiveFailures+1:1,e.lastFailureAt=n,e.restarts+=1,e.lastError=`exited code=${t} signal=${r}`,e.restartTimestamps.push(n),e.restartTimestamps=e.restartTimestamps.filter((l)=>n-l<=$t);let s=e.consecutiveFailures>=Rt,a=e.restartTimestamps.length>=yo;if(s||a){e.status="failed",e.breakerTrips+=1;let l=this.breakerCooldownMs(e.breakerTrips),u=s?`${e.consecutiveFailures} consecutive non-clean exits within ${Math.round(Pt/1000)}s`:`${e.restartTimestamps.length} non-clean exits within the last ${Math.round($t/60000)}m (slow-bleed loop — gaps between crashes kept clearing the tight-loop window)`;if(e.lastError=`Circuit breaker tripped (trip #${e.breakerTrips}): ${u} (last: code=${t} signal=${r}). Most recent on macOS is jetsam OOM (signal=SIGKILL with code=null); the previous incarnation's vite/tsserver/preview-manager children were reaped to prevent further RSS growth. Will auto-retry in ~${Math.round(l/1000)}s; call resetFailure(${e.projectId}) to retry immediately, or stop(${e.projectId}) to give up.`,this.releasePort(e.agentPort),e.agentPort=0,e.apiServerPort=0,e.restartTimer)clearTimeout(e.restartTimer),e.restartTimer=null;if(e.idleTimer)clearTimeout(e.idleTimer),e.idleTimer=null;this.log.error(`[WorkerRuntimeManager] ${e.lastError}`),this.notifyGone(e.projectId,{reason:"failed",code:t,signal:r});return}let c=this.restartBackoffMs(e.restarts);if(e.status="restarting",this.log.warn(`[WorkerRuntimeManager] restarting ${e.projectId} in ${Math.round(c/1000)}s (restart #${e.restarts}, consecutive failures ${e.consecutiveFailures}/${Rt})`),e.restartTimer)clearTimeout(e.restartTimer);e.restartTimer=setTimeout(()=>{if(e.restartTimer=null,e.status==="failed"||this.stopped)return;e.startPromise=this.doStart(e).then((l)=>(e.startPromise=null,l)).catch((l)=>(e.startPromise=null,this.log.error(`[WorkerRuntimeManager] restart of ${e.projectId} failed: ${l?.message??l}`),e))},c);try{e.restartTimer.unref?.()}catch{}}restartBackoffMs(e){let t=Math.min(fo*Math.pow(2,Math.max(0,e-1)),wo),r=t*0.2*Math.random();return t+r}armIdleTimer(e){if(e.idleTimer)clearTimeout(e.idleTimer),e.idleTimer=null;let t=this.opts.idleMs??ho;if(!Number.isFinite(t)||t<=0)return;e.idleTimer=setTimeout(()=>{let r=Date.now()-e.lastUsedAt;if(r<t){this.armIdleTimer(e);return}this.log.log(`[WorkerRuntimeManager] idle-evicting ${e.projectId} after ${Math.round(r/1000)}s`),this.stop(e.projectId,"SIGTERM","idle-evict").catch((o)=>{this.log.warn(`[WorkerRuntimeManager] idle stop failed: ${o?.message??o}`)})},t)}async allocatePort(){let e=We-Ue,t=Math.min(e,50);for(let r=0;r<t;r++){let o=Ue+Math.floor(Math.random()*e);if(o+fe-1>We)continue;let n=!0;for(let a=0;a<fe;a++)if(this.usedPorts.has(o+a)){n=!1;break}if(!n)continue;let i=await this.isPortListening(o),s=await this.isPortListening(o+kt);if(i||s)continue;for(let a=0;a<fe;a++)this.usedPorts.add(o+a);return o}throw Error(`Cannot allocate port in range ${Ue}-${We} after ${t} attempts`)}releasePort(e){if(!e)return;for(let t=0;t<fe;t++)this.usedPorts.delete(e+t)}async isPortListening(e){let t=new AbortController,r=setTimeout(()=>t.abort(),250);try{return await fetch(`http://127.0.0.1:${e}/`,{method:"HEAD",signal:t.signal}),clearTimeout(r),!0}catch{return clearTimeout(r),!1}}tcpProbe(e){return new Promise((t)=>{let r=!1,o=(i)=>{if(r)return;r=!0;try{n.destroy()}catch{}t(i)},n=co({host:"127.0.0.1",port:e});n.setTimeout($o),n.once("connect",()=>o(!0)),n.once("error",()=>o(!1)),n.once("timeout",()=>o(!1))})}async waitForHealth(e,t){let{agentPort:r,proc:o}=e;if(!o)throw Error(`waitForHealth: slot ${e.projectId} has no spawned process`);let n=Date.now(),i=n+t,s=null,a=!1,c=0,l=0,u=0,p=0,m=n;while(Date.now()<i){if(p++,o.exitCode!==null||o.signalCode!=null||o.killed)throw Error(`agent-runtime exited (code=${o.exitCode}, signal=${o.signalCode}) before becoming healthy on port ${r}`);l++;let f=new AbortController,d=setTimeout(()=>f.abort(),1500);try{let h=await fetch(`http://127.0.0.1:${r}/health`,{method:"GET",signal:f.signal});if(clearTimeout(d),h.ok){this.log.log(`[WorkerRuntimeManager] /health ready for ${e.projectId} on port ${r} (HTTP ${h.status} after ${Date.now()-n}ms, ${p} iter, ${l} http)`);return}s=`HTTP /health returned ${h.status}`}catch(h){clearTimeout(d);let R=h?.name??"Error",V=h?.code??h?.cause?.code;s=`HTTP /health failed: ${R}${V?`(${V})`:""}: ${h?.message??h}`}if(u++,a=await this.tcpProbe(r),a){c=Date.now();let h=Date.now()-e.lastStdoutAt;if(h>=Tt)throw Error(`agent-runtime wedged on port ${r}: TCP listening but stdout silent for ${h}ms (> ${Tt}ms window); ${l} /health attempts, last error: ${s??"n/a"}`)}let w=Date.now();if(w-m>=Po){let h=w-n,R=w-e.lastStdoutAt,V=c>0?w-c:null;this.log.log(`[WorkerRuntimeManager] still waiting for /health on ${e.projectId} port ${r} (${(h/1000).toFixed(1)}s elapsed, tcpListening=${a}${V!=null?`(${V}ms ago)`:""}, lastStdout=${R}ms ago, ${l} http, ${u} tcp, lastError=${s??"n/a"})`),m=w}await new Promise((h)=>setTimeout(h,ko))}if(o.exitCode!==null||o.signalCode!=null||o.killed)throw Error(`agent-runtime exited (code=${o.exitCode}, signal=${o.signalCode}) before becoming healthy on port ${r}`);throw Error(`Timeout waiting for agent-runtime /health on port ${r} after ${p} iter (httpAttempts=${l}, tcpAttempts=${u}, tcpListening=${a}, lastError=${s??"n/a"})`)}async waitForExit(e,t){if(e.exitCode!==null||e.signalCode!=null||e.killed)return;await new Promise((r)=>{let o=setTimeout(()=>{try{e.kill("SIGKILL")}catch{}r()},t);e.once("exit",()=>{clearTimeout(o),r()})})}snapshot(e){return{projectId:e.projectId,status:e.status,agentPort:e.agentPort||void 0,apiServerPort:e.apiServerPort||void 0,pid:e.proc?.pid,startedAt:e.startedAt||void 0,lastUsedAt:e.lastUsedAt,restarts:e.restarts,lastError:e.lastError}}}import{hostname as Le,platform as He,arch as Ge}from"node:os";function G(){if(typeof __SHOGO_WORKER_VERSION__==="string"&&__SHOGO_WORKER_VERSION__.length>0)return`shogo-cli/${__SHOGO_WORKER_VERSION__}`;return"shogo-cli/unknown"}class Ut extends Error{code="TUNNEL_WS_HEADERS_UNSUPPORTED";constructor(){super("Tunnel WebSocket auth requires a runtime with WebSocket header support (Bun or Node >= 21). Current runtime does not support WebSocket constructor headers.");this.name="TunnelWebSocketHeaderSupportError"}}var re=60,ye=300,Be=3,xo=Be,Co=1800000,_o=25000,Ot=1000,Mt=60000,Dt=3;class Ke{opts;log;pollTimer=null;ws=null;wsIdleTimer=null;heartbeatTimer=null;stopped=!1;currentPollInterval=re;wsReconnectAttempt=0;lastHeartbeatError=null;consecutiveAuthFailures=0;consecutiveAuthSuccesses=0;serverPublishedWsUrl=null;activeAbortControllers=new Map;constructor(e){this.opts=e,this.log=e.logger??console}start(){if(!this.opts.apiKey){this.log.log("[WorkerTunnel] No API key set, skipping tunnel");return}this.stopped=!1,this.wsReconnectAttempt=0,this.currentPollInterval=re,this.log.log("[WorkerTunnel] Starting heartbeat polling to Shogo Cloud..."),this.heartbeatLoop()}stop(){if(this.stopped=!0,this.pollTimer)clearTimeout(this.pollTimer),this.pollTimer=null;this.cleanupWs(),this.log.log("[WorkerTunnel] Tunnel stopped")}isConnected(){if(this.ws!==null&&this.ws.readyState===WebSocket.OPEN)return!0;return!this.stopped&&!!this.opts.apiKey&&this.lastHeartbeatError===null&&this.pollTimer!==null}getCloudUrl(){return this.opts.cloudUrl.replace(/\/$/,"")}getWsBaseUrl(){let e=(this.opts.wsUrlOverride||process.env.SHOGO_TUNNEL_WS_URL||"").trim();if(e)return e.replace(/\/$/,"");if(this.serverPublishedWsUrl)return this.serverPublishedWsUrl.replace(/\/$/,"");return this.getCloudUrl().replace(/^http/,"ws")}buildWsUrl(){return`${this.getWsBaseUrl()}/api/instances/ws`}supportsWebSocketConstructorHeaders(e=globalThis){if(typeof e.Bun<"u"||typeof e.process?.versions?.bun==="string")return!0;let t=e.process?.versions?.node;if(t){if(parseInt(t.split(".")[0]??"0",10)>=21)return!0}return!1}createTunnelWebSocket(e,t,r=globalThis){if(!this.supportsWebSocketConstructorHeaders(r))throw new Ut;return new WebSocket(e,t)}getReconnectDelayMs(){let e=Math.min(Ot*Math.pow(2,this.wsReconnectAttempt),Mt),t=e*0.2*Math.random();return e+t}async collectMetadata(){let e={hostname:Le(),os:He(),arch:Ge(),uptime:process.uptime(),protocolVersion:Dt,tunnelStatus:this.ws?.readyState===WebSocket.OPEN?"connected":"polling",kind:this.opts.kind??"cli-worker"};try{let t=this.opts.resolver.getActiveProjects();e.activeProjects=t.length,e.projects=t.map((r)=>{let o=this.opts.resolver.status(r);return{projectId:r,status:o?.status??"unknown",agentPort:o?.agentPort}})}catch{e.activeProjects=0}return e}async sendHeartbeat(){let e=this.getCloudUrl(),t=await this.collectMetadata(),r=Le(),o=this.opts.name??r,n=await fetch(`${e}/api/instances/heartbeat`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":G(),"x-api-key":this.opts.apiKey,"x-shogo-kind":this.opts.kind??"cli-worker"},body:JSON.stringify({hostname:r,name:o,os:He(),arch:Ge(),kind:this.opts.kind??"cli-worker",metadata:t})});if(!n.ok)throw Error(`Heartbeat failed: HTTP ${n.status}`);let i=await n.json();if(typeof i.wsUrl==="string"&&i.wsUrl.length>0){if(i.wsUrl!==this.serverPublishedWsUrl)this.log.log(`[WorkerTunnel] Cloud advertised tunnel WS URL: ${i.wsUrl}`);this.serverPublishedWsUrl=i.wsUrl}return i}scheduleNextPoll(e){if(this.stopped)return;if(this.pollTimer)clearTimeout(this.pollTimer);let t=(e??this.currentPollInterval)*1000;this.pollTimer=setTimeout(()=>void this.heartbeatLoop(),t)}async heartbeatLoop(){if(this.stopped)return;if(this.ws&&this.ws.readyState===WebSocket.OPEN){this.scheduleNextPoll(this.currentPollInterval);return}try{let e=await this.sendHeartbeat(),t=e.nextPollIn||re;if(this.consecutiveAuthFailures>=Be){if(this.consecutiveAuthSuccesses++,this.consecutiveAuthSuccesses<xo){this.currentPollInterval=ye,this.scheduleNextPoll();return}}if(this.currentPollInterval=t,this.lastHeartbeatError)this.log.log("[WorkerTunnel] Heartbeat recovered"),this.lastHeartbeatError=null;if(this.consecutiveAuthFailures=0,this.consecutiveAuthSuccesses=0,e.wsRequested&&!this.ws){this.log.log("[WorkerTunnel] Cloud requested WebSocket — connecting..."),this.connectWs();return}}catch(e){let t=e?.message??String(e);if(/HTTP 40[13]\b/.test(t))this.consecutiveAuthFailures++,this.consecutiveAuthSuccesses=0;else this.consecutiveAuthFailures=0,this.consecutiveAuthSuccesses=0;if(t!==this.lastHeartbeatError)this.log.error(`[WorkerTunnel] Heartbeat error: ${t}`),this.lastHeartbeatError=t;if(this.consecutiveAuthFailures>=Be){let o=`tunnel saw ${this.consecutiveAuthFailures} consecutive auth failures from Shogo Cloud`;try{this.opts.onAuthRevoked?.(o)}catch(n){this.log.warn(`[WorkerTunnel] onAuthRevoked threw: ${n?.message??n}`)}if(this.currentPollInterval!==ye)this.log.warn(`[WorkerTunnel] ${this.consecutiveAuthFailures} consecutive auth failures — `+`backing off to ${ye}s. Re-authenticate with \`shogo login\`.`);this.currentPollInterval=ye}else this.currentPollInterval=re}this.scheduleNextPoll()}async handleRequest(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;this.resetWsIdleTimer();let t=new AbortController;this.activeAbortControllers.set(e.requestId,t);try{let r=await this.resolveLocalUrl(e.path,e.projectId);if(!r){let s=this.opts.resolver.describeRejection?this.opts.resolver.describeRejection(e.path,e.projectId):{code:"NO_LOCAL_RUNTIME",message:`no local runtime available for path: ${e.path}`};this.sendFrame({type:"response",requestId:e.requestId,status:502,headers:{"content-type":"application/json"},body:JSON.stringify({code:s.code,message:s.message,path:e.path})});return}let o={...e.headers??{}};if(e.projectId&&(e.path.startsWith("/agent/")||e.path==="/agent")){let s=this.opts.resolver.deriveRuntimeToken(e.projectId);if(s)o["x-runtime-token"]=s}let n={method:e.method,headers:o,signal:t.signal};if(e.body&&e.method!=="GET"&&e.method!=="HEAD")n.body=e.body;let i=await fetch(r,n);if(e.stream){let s=i.body?.getReader();if(!s){this.sendFrame({type:"stream-error",requestId:e.requestId,error:"No response body for stream"});return}let a=new TextDecoder;try{while(!0){let{done:c,value:l}=await s.read();if(c)break;if(this.ws?.readyState!==WebSocket.OPEN)break;this.sendFrame({type:"stream-chunk",requestId:e.requestId,data:a.decode(l,{stream:!0})})}if(this.ws?.readyState===WebSocket.OPEN)this.sendFrame({type:"stream-end",requestId:e.requestId})}catch(c){if(c?.name!=="AbortError"&&this.ws?.readyState===WebSocket.OPEN)this.sendFrame({type:"stream-error",requestId:e.requestId,error:c?.message??String(c)})}}else{let s=await i.text(),a={};i.headers.forEach((c,l)=>{a[l]=c}),this.sendFrame({type:"response",requestId:e.requestId,status:i.status,headers:a,body:s})}}catch(r){if(r?.name==="AbortError")return;if(this.ws?.readyState!==WebSocket.OPEN)return;let o=e.stream?{type:"stream-error",requestId:e.requestId,error:r?.message??String(r)}:{type:"response",requestId:e.requestId,status:502,body:JSON.stringify({error:r?.message??String(r)})};this.sendFrame(o)}finally{this.activeAbortControllers.delete(e.requestId)}}async resolveLocalUrl(e,t){return this.opts.resolver.resolveLocalUrl(e,t)}sendFrame(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;try{this.ws.send(JSON.stringify(e))}catch(t){this.log.warn(`[WorkerTunnel] Frame send failed: ${t?.message??t}`)}}resetWsIdleTimer(){if(this.wsIdleTimer)clearTimeout(this.wsIdleTimer);this.wsIdleTimer=setTimeout(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){this.log.log("[WorkerTunnel] WebSocket idle timeout — closing, returning to polling");try{this.ws.close(1000,"Idle timeout")}catch{}}},Co)}startWsHeartbeat(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer);this.heartbeatTimer=setInterval(async()=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;try{let e=await this.collectMetadata();this.sendFrame({type:"heartbeat",metadata:e})}catch{}},_o)}connectWs(){if(this.stopped||this.ws)return;let e=this.buildWsUrl(),t=Le(),r=He(),o=Ge(),n=this.opts.name??t;this.log.log(`[WorkerTunnel] Opening WebSocket to ${e} (hostname=${t})`);let i={headers:{Authorization:`Bearer ${this.opts.apiKey}`,"User-Agent":G(),"x-shogo-hostname":t,"x-shogo-name":n,"x-shogo-os":r,"x-shogo-arch":o,"x-shogo-kind":this.opts.kind??"cli-worker"}},s;try{s=this.createTunnelWebSocket(e,i)}catch(a){this.log.error(`[WorkerTunnel] WebSocket creation failed: ${a?.message??a}`),this.ws=null,this.scheduleNextPoll(5);return}this.ws=s,s.onopen=()=>{this.log.log("[WorkerTunnel] WebSocket connected — session active"),this.wsReconnectAttempt=0,this.startWsHeartbeat(),this.resetWsIdleTimer()},s.onmessage=(a)=>{let c;try{let l=typeof a.data==="string"?a.data:a.data.toString();c=JSON.parse(l)}catch{return}if(c.type==="ping"){this.sendFrame({type:"pong"}),this.resetWsIdleTimer();return}if(c.type==="cancel"){let l=this.activeAbortControllers.get(c.requestId);if(l)l.abort();return}if(c.type==="request"){this.handleRequest(c).catch((l)=>{this.log.error(`[WorkerTunnel] Error handling request: ${l?.message??l}`)});return}},s.onclose=(a)=>{if(this.log.log(`[WorkerTunnel] WebSocket closed: code=${a.code} reason=${a.reason||"none"}`),this.cleanupWs(),this.stopped)return;if(a.code===1000||a.code===4000)this.scheduleNextPoll(this.currentPollInterval);else{this.wsReconnectAttempt++;let c=this.getReconnectDelayMs();this.log.log(`[WorkerTunnel] Reconnecting in ${Math.round(c/1000)}s (attempt ${this.wsReconnectAttempt})`),this.scheduleNextPoll(Math.ceil(c/1000))}},s.onerror=(a)=>{this.log.error("[WorkerTunnel] WebSocket error:",a?.message??"unknown")}}cleanupWs(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer),this.heartbeatTimer=null;if(this.wsIdleTimer)clearTimeout(this.wsIdleTimer),this.wsIdleTimer=null;for(let[,e]of this.activeAbortControllers)try{e.abort()}catch{}this.activeAbortControllers.clear(),this.ws=null}_testing(){let e=this;return{sendHeartbeat:()=>e.sendHeartbeat(),heartbeatLoop:()=>e.heartbeatLoop(),connectWs:()=>e.connectWs(),cleanupWs:()=>e.cleanupWs(),handleRequest:(t)=>e.handleRequest(t),installFakeWs:(t)=>{e.ws=t},getCloudUrl:()=>e.getCloudUrl(),getWsBaseUrl:()=>e.getWsBaseUrl(),buildWsUrl:()=>e.buildWsUrl(),getReconnectDelayMs:()=>e.getReconnectDelayMs(),supportsWebSocketConstructorHeaders:(t)=>e.supportsWebSocketConstructorHeaders(t),createTunnelWebSocket:(t,r,o)=>e.createTunnelWebSocket(t,r,o),DEFAULT_POLL_INTERVAL_S:re,BACKOFF_BASE_MS:Ot,BACKOFF_MAX_MS:Mt,TUNNEL_PROTOCOL_VERSION:Dt,get currentPollInterval(){return e.currentPollInterval},set currentPollInterval(t){e.currentPollInterval=t},get wsReconnectAttempt(){return e.wsReconnectAttempt},set wsReconnectAttempt(t){e.wsReconnectAttempt=t},get ws(){return e.ws},get stopped(){return e.stopped},get serverPublishedWsUrl(){return e.serverPublishedWsUrl},set serverPublishedWsUrl(t){e.serverPublishedWsUrl=t}}}}async function Wt(e){let t=A({name:e.name,workerDir:e.workerDir,apiKey:e.apiKey,cloudUrl:e.cloudUrl,port:e.port?parseInt(e.port,10):void 0,projectsDir:e.projectsDir}),r=nt(e.proxy);if(!e.foreground)return Oo({cfg:t,proxy:r,flags:e});let o=F({flag:e.runtimeBin});if(!o)console.error(g.red(H({flag:e.runtimeBin}))),process.exit(1);if(Ie(process.env,r),e.debug){if(!await lt(at({cloudUrl:t.cloudUrl,apiKey:t.apiKey,workerDir:t.workerDir,proxy:r})))process.exit(1)}let n=!e.noAutoPull,i=!e.noGit;if(console.log(g.bold(`
15
+ Shogo Worker — Starting`)),console.log(g.dim(" name ")+t.name),console.log(g.dim(" worker-dir ")+t.workerDir),console.log(g.dim(" cloud ")+t.cloudUrl),console.log(g.dim(" runtime ")+`${o.path} ${g.dim(`(via ${o.source})`)}`),console.log(g.dim(" auto-pull ")+(n?g.green("on")+g.dim(` → ${t.projectsDir}`):g.yellow("off"))),console.log(g.dim(" sync mode ")+(i?g.green("git")+g.dim(" (falls back to file transport if git is missing)"):g.yellow("files-only"))),e.project)console.log(g.dim(" project ")+e.project);if(r)console.log(g.dim(" proxy ")+`${r.url} ${g.dim(`(from ${r.source})`)}`);console.log("");let s=`${t.cloudUrl.replace(/\/+$/,"")}/api/ai/v1`,a={cloudUrl:t.cloudUrl,apiKey:t.apiKey,aiProxyUrl:s,aiProxyToken:t.apiKey},c=new Fe({runtimeBin:e.runtimeBin,defaultSpawnConfig:a,autoPull:{enabled:n,projectsDir:t.projectsDir,watch:!0,useGit:i}});if(!c.resolveBinary())console.error(g.red(H({flag:e.runtimeBin}))),process.exit(1);let l=new Ke({apiKey:t.apiKey,cloudUrl:t.cloudUrl,name:t.name,kind:"cli-worker",resolver:c,onAuthRevoked:(m)=>{console.error(g.red(`✗ Cloud auth revoked: ${m}`)),console.error(g.dim(" Run `shogo login` to re-authenticate; this worker will keep polling at the auth-failure backoff until then."))}}),u=!1,p=async(m)=>{if(u)return;u=!0,console.log(g.dim(`
16
+ Received ${m} — shutting down...`));try{l.stop()}catch{}try{await c.stopAll()}catch(f){console.warn(g.yellow(`stopAll: ${f?.message??f}`))}process.exit(0)};process.once("SIGINT",()=>void p("SIGINT")),process.once("SIGTERM",()=>void p("SIGTERM")),process.once("SIGHUP",()=>void p("SIGHUP")),l.start(),console.log(g.green("✓ Worker running. Ctrl-C to stop.")),await new Promise(()=>{})}function Oo({cfg:e,proxy:t,flags:r}){let{entry:o,runner:n}=Do(),i=Ie({...process.env,SHOGO_API_KEY:e.apiKey,SHOGO_CLOUD_URL:e.cloudUrl,SHOGO_INSTANCE_NAME:e.name,SHOGO_WORKER_DIR:e.workerDir,SHOGO_LOCAL_MODE:"true",PORT:String(e.port)},t),s=Mo(r),{pid:a}=tt({entry:o,runner:n,env:{...i,SHOGO_DETACHED_ARGS:s.join(" ")},cwd:e.workerDir,detach:!0,inheritStdio:!1});console.log(g.bold(`
17
+ Shogo Worker — Started`)),console.log(g.dim(" pid: ")+a),console.log(g.dim(" name: ")+e.name),console.log(g.dim(" logs: ")+"~/.shogo/logs/worker.log"),console.log(g.dim(" stop: ")+"shogo worker stop")}function Mo(e){let t=["worker","start","--foreground"];if(e.name)t.push("--name",e.name);if(e.workerDir)t.push("--worker-dir",e.workerDir);if(e.apiKey)t.push("--api-key",e.apiKey);if(e.cloudUrl)t.push("--cloud-url",e.cloudUrl);if(e.port)t.push("--port",e.port);if(e.proxy)t.push("--proxy",e.proxy);if(e.project)t.push("--project",e.project);if(e.runtimeBin)t.push("--runtime-bin",e.runtimeBin);if(e.debug)t.push("--debug");if(e.noAutoPull)t.push("--no-auto-pull");if(e.projectsDir)t.push("--projects-dir",e.projectsDir);if(e.noGit)t.push("--no-git");return t}function Do(){let e=process.execPath,t=/\bbun(?:-[^/\\]*)?$/.test(e)||typeof globalThis.Bun<"u",r=process.argv[1];if(r&&Ao(r)){let n=/\.ts$/.test(r);return{entry:r,runner:t?"bun":n?"tsx":"node"}}return{entry:new URL("../../bin/shogo.mjs",import.meta.url).pathname,runner:t?"bun":"node"}}import Nt from"picocolors";async function jt(){let{killedPid:e}=rt("SIGTERM");if(e===null){console.log(Nt.dim("No worker running."));return}console.log(Nt.green(`✓ Worker stopped (pid=${e}).`))}import D from"picocolors";async function Ft(){let e=ce();if(!e){console.log(D.yellow("● stopped")+D.dim(" (no pid file)"));return}if(!ue(e)){console.log(D.red("● dead")+D.dim(` (stale pid ${e})`));return}let t=j();if(console.log(D.green("● running")+D.dim(` (pid ${e})`)),t.name)console.log(D.dim(" name: ")+t.name);if(t.cloudUrl)console.log(D.dim(" cloud: ")+t.cloudUrl);if(t.workerDir)console.log(D.dim(" dir: ")+t.workerDir)}import{spawn as Uo}from"node:child_process";import{existsSync as Wo,statSync as No}from"node:fs";import Lt from"picocolors";async function Ht(e){let t=e.err?ae:se;if(!Wo(t)){console.log(Lt.dim("No logs yet."));return}let r=e.follow?["-F","-n","200",t]:["-n","200",t];if(Uo("tail",r,{stdio:"inherit"}).on("exit",(n)=>process.exit(n??0)),!e.follow){if(No(t).size===0)console.log(Lt.dim("(log file is empty)"))}}import T from"picocolors";import{spawn as jo}from"node:child_process";import{hostname as Fo,platform as Lo,arch as Ho}from"node:os";import L from"picocolors";class x extends Error{kind;constructor(e,t){super(e);this.kind=t;this.name="CloudLoginError"}}async function Gt(e){let t=e.cloudUrl.replace(/\/$/,""),r=e.client??"cli",o=e.deviceName??Fo(),n=e.devicePlatform??`${Lo()}-${Ho()}`,i=e.appVersion??Ko(),s=e.log??((h)=>console.log(h)),a=e.fetchImpl??fetch,c=await a(`${t}/api/cli/login/start`,{method:"POST",headers:{"content-type":"application/json","user-agent":G()},body:JSON.stringify({deviceId:e.deviceId,deviceName:o,devicePlatform:n,deviceAppVersion:i,workspaceId:e.workspaceId,client:r}),signal:AbortSignal.timeout(1e4)}).catch((h)=>{throw new x(`Cannot reach Shogo Cloud at ${t}: ${h?.message??h}`,"transport")});if(!c.ok){let h=await c.text().catch(()=>"");throw new x(`Cloud rejected /api/cli/login/start (HTTP ${c.status}): ${h||"no body"}`,"transport")}let l=await c.json().catch(()=>({}));if(!l?.ok||!l.state||!l.authUrl)throw new x(`Cloud returned a malformed start response: ${l?.error??JSON.stringify(l)}`,"transport");let u=Go(e.pollIntervalMs??l.pollIntervalMs),p=e.timeoutMs??l.expiresInMs,m=Date.now()+p;if(s(""),s(L.bold("Sign in to Shogo Cloud")),s(L.dim(" cloud: ")+t),s(L.dim(" device: ")+`${o} (${n})`),s(L.dim(" user code: ")+L.cyan(l.userCode)),s(""),s(" Open this URL in your browser to approve:"),s(" "+L.cyan(l.authUrl)),s(""),e.openBrowser!==!1)if(typeof e.openBrowser==="function")try{await e.openBrowser(l.authUrl)}catch{}else qo(l.authUrl).catch(()=>{});s(L.dim("Waiting for approval..."));let f=e.installSignalHandlers??!0,d=()=>{w.abort()},w=new AbortController;if(e.abortSignal)if(e.abortSignal.aborted)w.abort();else e.abortSignal.addEventListener("abort",()=>w.abort(),{once:!0});if(f)process.once("SIGINT",d),process.once("SIGTERM",d);try{while(!0){if(w.signal.aborted)throw new x("Aborted by caller.","cancelled");if(Date.now()>=m)throw new x(`Timed out after ${Math.round(p/1000)}s waiting for approval.`,"timeout");let h=await a(`${t}/api/cli/login/poll?state=${encodeURIComponent(l.state)}`,{method:"GET",headers:{accept:"application/json","user-agent":G()},signal:AbortSignal.timeout(1e4)}).catch((R)=>(s(L.dim(` (poll error: ${R?.message??R} — retrying)`)),null));if(h&&h.ok){let R=await h.json().catch(()=>({}));if(R?.status==="approved"&&R.key)return{key:R.key,email:R.email??null,workspace:R.workspace??null,deviceId:R.deviceId??e.deviceId};if(R?.status==="denied")throw new x("Sign-in was denied in the browser.","denied");if(R?.status==="expired")throw new x("Sign-in request expired before it was approved.","expired")}await Bo(u,w.signal)}}finally{if(f)process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d)}}function Go(e){if(!Number.isFinite(e)||e<=0)return 2000;return Math.min(Math.max(e,1000),1e4)}function Bo(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(new x("Aborted by caller.","cancelled"));let n=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(n),o(new x("Aborted by caller.","cancelled"))};t?.addEventListener("abort",i,{once:!0})})}function Ko(){return G()}function qo(e){return new Promise((t)=>{let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",o=process.platform==="win32"?["/c","start",'""',e]:[e];try{let n=jo(r,o,{stdio:"ignore",detached:!0});n.on("error",()=>t()),n.unref(),t()}catch{t()}})}import{readFileSync as Jo,writeFileSync as Vo,existsSync as Yo,chmodSync as Xo}from"node:fs";import{randomUUID as zo}from"node:crypto";function Bt(){if(Yo(Y)){let t=Jo(Y,"utf-8").trim();if(t)return t}N();let e=zo();return Vo(Y,e,{mode:384}),Xo(Y,384),e}var Qo="https://studio.shogo.ai";async function Kt(e){let t=j(),r=(e.cloudUrl||t.cloudUrl||Qo).replace(/\/$/,""),o=e.apiKey||process.env.SHOGO_API_KEY;if(o){await Zo({key:o,cloudUrl:r,cfg:t,name:e.name});return}let n=Bt(),i;try{i=await Gt({cloudUrl:r,deviceId:n,deviceName:e.name,workspaceId:e.workspace,openBrowser:!e.noBrowser})}catch(s){if(s instanceof x){if(console.error(T.red(`✗ ${s.message}`)),s.kind==="transport")console.error(T.dim(" If your network blocks browsers, run with --api-key <key> instead."));process.exit(1)}throw s}if(t.apiKey=i.key,t.cloudUrl=r,e.name)t.name=e.name;if(Z(t),console.log(""),console.log(T.green("✓ Signed in to Shogo Cloud")),i.workspace)console.log(T.dim(" workspace: ")+i.workspace);if(i.email)console.log(T.dim(" email: ")+i.email);console.log(T.dim(" saved to: ")+"~/.shogo/config.json"),console.log(""),console.log(T.dim(" next: ")+"shogo worker start")}async function Zo({key:e,cloudUrl:t,cfg:r,name:o}){if(!/^shogo_sk_/.test(e))console.error(T.red('✗ API key should start with "shogo_sk_". Copy it verbatim from the API Keys page.')),process.exit(1);let n;try{let i=await fetch(`${t}/api/api-keys/validate`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(1e4)});if(n=await i.json().catch(()=>({})),!i.ok||!n?.valid)console.error(T.red(`✗ ${n?.error||`Cloud rejected the key (HTTP ${i.status}).`}`)),process.exit(1)}catch(i){console.error(T.red(`✗ Cannot reach Shogo Cloud at ${t}: ${i?.message??i}`)),process.exit(1)}if(r.apiKey=e,r.cloudUrl=t,o)r.name=o;if(Z(r),console.log(T.green("✓ API key saved to ~/.shogo/config.json")),n.workspace?.name)console.log(T.dim(" workspace: ")+n.workspace.name);if(n.user?.email)console.log(T.dim(" email: ")+n.user.email);console.log(T.dim(" next: ")+"shogo worker start")}import oe from"picocolors";async function qt(){let e=j();if(Object.keys(e).length===0){console.log(oe.dim("(no config — run `shogo login` or `shogo config set`)"));return}let t={...e,apiKey:e.apiKey?`***${e.apiKey.slice(-4)}`:void 0};console.log(oe.dim(`file: ${W}`)),console.log(JSON.stringify(t,null,2))}async function Jt(e,t){let r=["apiKey","cloudUrl","name","workerDir","port"];if(!r.includes(e))console.error(oe.red(`Unknown key: ${e}`)),console.error(oe.dim(`Allowed: ${r.join(", ")}`)),process.exit(1);let o=j();o[e]=e==="port"?parseInt(t,10):t,Z(o),console.log(oe.green(`✓ ${e} set`))}import b from"picocolors";import{spawn as en}from"node:child_process";import{createHash as tn}from"node:crypto";import{createWriteStream as rn,existsSync as ne,mkdirSync as qe,readFileSync as Xt,renameSync as Vt,rmSync as Je,writeFileSync as on}from"node:fs";import{tmpdir as nn}from"node:os";import{dirname as sn,join as ve}from"node:path";import{Readable as an}from"node:stream";import{pipeline as ln}from"node:stream/promises";var cn="https://github.com/shogo-labs/shogo-ai/releases/download";function zt(){let e=process.platform,t=process.arch,r;if(e==="darwin")r="darwin";else if(e==="linux")r="linux";else if(e==="win32")r="windows";else throw Error(`Unsupported platform: ${e}`);let o;if(t==="arm64")o="arm64";else if(t==="x64")o="x64";else throw Error(`Unsupported arch: ${t} (need arm64 or x64)`);return`${r}-${o}`}function be(){if(!ne(Q))return null;try{let e=Xt(Q,"utf-8");return JSON.parse(e)}catch{return null}}async function un(e,t){let r=t.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/releases\/download/);if(!r)throw Error(`Cannot auto-resolve latest version from non-GitHub baseUrl '${t}'. Pass --version explicitly.`);let o=r[1],n=r[2];if(e==="stable"){let u=`https://api.github.com/repos/${o}/${n}/releases/latest`,p=await fetch(u,{headers:{Accept:"application/vnd.github+json"}});if(!p.ok)throw Error(`GitHub API ${p.status} for ${u}`);let m=await p.json();if(!m.tag_name)throw Error("GitHub API did not return tag_name");return Yt(m.tag_name)}let i=`https://api.github.com/repos/${o}/${n}/releases?per_page=30`,s=await fetch(i,{headers:{Accept:"application/vnd.github+json"}});if(!s.ok)throw Error(`GitHub API ${s.status} for ${i}`);let a=await s.json(),c=e==="beta"?"-beta":"-nightly",l=a.find((u)=>u.prerelease&&/^v\d+\.\d+\.\d+-/.test(u.tag_name)&&u.tag_name.includes(c));if(!l)throw Error(`No ${e} runtime release found`);return Yt(l.tag_name)}function Yt(e){if(!/^v\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(e))throw Error(`Unexpected app tag '${e}' (expected vX.Y.Z[-prerelease])`);return e.slice(1)}function pn(e,t,r){let o=`shogo-agent-runtime-${t}.tar.gz`,n=`v${e}`,i=`${r.replace(/\/$/,"")}/${n}/${o}`;return{tarball:i,sha256:`${i}.sha256`,assetName:o}}async function dn(e,t){let r=await fetch(e,{redirect:"follow"});if(!r.ok)throw Error(`Download failed: HTTP ${r.status} for ${e}`);if(!r.body)throw Error(`Download failed: empty body for ${e}`);await ln(an.fromWeb(r.body),rn(t))}async function mn(e){let t=await fetch(e,{redirect:"follow"});if(!t.ok)throw Error(`SHA256 sidecar fetch failed: HTTP ${t.status} for ${e}`);let o=(await t.text()).trim().split(/\s+/)[0];if(!/^[0-9a-f]{64}$/i.test(o))throw Error(`SHA256 sidecar at ${e} did not contain a 64-char hex digest`);return o.toLowerCase()}function hn(e){let t=Xt(e);return tn("sha256").update(t).digest("hex")}async function gn(e,t){await new Promise((r,o)=>{let n=en("tar",["-xzf",e,"-C",t],{stdio:["ignore","pipe","pipe"]}),i="";n.stderr.on("data",(s)=>{i+=s.toString()}),n.on("error",o),n.on("exit",(s)=>{if(s===0)r();else o(Error(`tar exited ${s}: ${i.trim()}`))})})}function fn(e,t){ze();let r=sn(t);if(!ne(r))qe(r,{recursive:!0,mode:448});let o=`${t}.next`;if(ne(o))Je(o,{force:!0});Vt(e,o);try{if(process.platform!=="win32"){let{chmodSync:n}=Pe("node:fs");n(o,493)}}catch{}if(ne(t))Je(t,{force:!0});Vt(o,t)}async function Qt(e={}){let t=e.logger??console,r=e.channel??"stable",o=e.baseUrl??process.env.SHOGO_RUNTIME_RELEASES_URL??cn,n=e.target??zt(),i=e.version;if(!i)t.log(`[runtime install] Resolving latest ${r} version...`),i=await un(r,o),t.log(`[runtime install] Latest ${r} = ${i}`);let s=be();if(s&&s.version===i&&s.target===n&&!e.force)return t.log(`[runtime install] ${i} (${n}) already installed at ${_} — pass --force to reinstall`),{version:i,target:n,binPath:_,source:s.source,sha256:s.sha256,channel:r};let a=pn(i,n,o);t.log(`[runtime install] Downloading ${a.tarball}`);let c=ve(nn(),`shogo-runtime-install-${process.pid}-${Date.now()}`);qe(c,{recursive:!0});try{let l=ve(c,a.assetName);await dn(a.tarball,l),t.log("[runtime install] Verifying SHA-256...");let u=await mn(a.sha256),p=hn(l);if(p!==u)throw Error(`SHA-256 mismatch for ${a.assetName}
18
+ expected: ${u}
19
+ actual: ${p}`);let m=ve(c,"extract");qe(m,{recursive:!0}),await gn(l,m);let f=ve(m,"agent-runtime");if(!ne(f))throw Error(`Tarball ${a.assetName} did not contain ./agent-runtime`);fn(f,_);let d={version:i,target:n,installedAt:new Date().toISOString(),channel:r,source:a.tarball,sha256:p};return on(Q,JSON.stringify(d,null,2)+`
20
+ `,{mode:384}),t.log(`[runtime install] Installed agent-runtime ${i} (${n}) to ${_}`),{version:i,target:n,binPath:_,source:a.tarball,sha256:p,channel:r}}finally{try{Je(c,{recursive:!0,force:!0})}catch{}}}function Zt(){return{runtimeDir:z,runtimeBin:_,versionFile:Q}}async function Ve(e={}){let t=await Qt({channel:e.channel,version:e.version,baseUrl:e.baseUrl,force:e.force});console.log(),console.log(b.green("✓"),`agent-runtime ${b.bold(t.version)} installed (${t.target})`),console.log(` ${b.dim("path: ")} ${t.binPath}`),console.log(` ${b.dim("source: ")} ${t.source}`),console.log(` ${b.dim("sha256: ")} ${t.sha256}`),console.log(` ${b.dim("channel: ")} ${t.channel}`)}function er(){let e=be();if(!e){console.log(b.yellow("No agent-runtime installed.")),console.log(`Run ${b.cyan("shogo runtime install")} to download the latest.`),process.exitCode=1;return}console.log(`${b.bold("agent-runtime")} ${e.version}`),console.log(` ${b.dim("target: ")} ${e.target}`),console.log(` ${b.dim("channel: ")} ${e.channel}`),console.log(` ${b.dim("installed at:")} ${e.installedAt}`),console.log(` ${b.dim("source: ")} ${e.source}`)}function tr(){let e=F(),t=Zt();if(!e){console.log(b.yellow("agent-runtime binary not found on this machine.")),console.log(),console.log(b.dim("Default install path:"),t.runtimeBin),console.log(),console.log(H()),process.exitCode=1;return}if(console.log(e.path),process.env.SHOGO_DEBUG||process.env.VERBOSE)console.log(b.dim(` (resolved via: ${e.source})`))}async function rr(e={}){let t=be(),r=e.channel??t?.channel??"stable";if(t)console.log(`${b.dim("current:")} ${t.version} (${t.target}, ${t.channel})`);else console.log(b.dim("No existing install — installing fresh..."));await Ve({channel:r,baseUrl:e.baseUrl,force:!0})}import{existsSync as wn,mkdirSync as yn}from"node:fs";import{resolve as vn}from"node:path";import y from"picocolors";import{CloudFileTransport as bn}from"@shogo-ai/sdk/cloud-file-transport";async function or(e,t){if(!e)throw Error("projectId is required");let r=A({apiKey:t.apiKey,cloudUrl:t.cloudUrl});Qe(r.projectsDir);let o=vn(t.into??B(e,r.projectsDir));if(!wn(o))yn(o,{recursive:!0});let n=t.include?.split(",").map((a)=>a.trim()).filter(Boolean);if(console.log(y.bold(`
21
+ shogo project pull ${y.cyan(e)}`)),console.log(y.dim(" cloud ")+r.cloudUrl),console.log(y.dim(" into ")+o),n?.length)console.log(y.dim(" include ")+n.join(", "));console.log("");let i=new bn({apiUrl:r.cloudUrl,apiKey:r.apiKey,projectId:e,localDir:o,include:n,onProgress:Sn()}),s=await i.downloadAll();if(kn("Pull",s),t.watch){console.log(y.bold(`
22
+ Watching for local changes...`));let a=new te({rootDir:o,transport:i,onFlush:({uploaded:u,errors:p})=>{let m=u.length===1?u[0]:`${u.length} files`,f=p>0?y.red(` (${p} errors)`):"";console.log(y.dim(` ↑ ${m}${f}`))}});a.start();let c=!1,l=async(u)=>{if(c)return;c=!0,console.log(y.dim(`
23
+ Received ${u} — flushing pending uploads...`));try{await a.stop()}catch(p){console.warn(y.yellow(`watcher.stop: ${p?.message??p}`))}process.exit(0)};process.once("SIGINT",()=>void l("SIGINT")),process.once("SIGTERM",()=>void l("SIGTERM")),process.once("SIGHUP",()=>void l("SIGHUP")),await new Promise(()=>{})}}function Sn(){return(e)=>{let t=e.kind==="download"?"↓":e.kind==="upload"?"↑":e.kind==="delete"?"✗":"·",r=e.total>0?` ${e.index+1}/${e.total}`:"",o=e.bytes!=null?y.dim(` (${Rn(e.bytes)})`):"";console.log(y.dim(` ${t}${r} ${e.path}${o}`))}}function kn(e,t){let r=t.errors.length===0,o=r?y.green(`✓ ${e} complete`):y.red(`✗ ${e} completed with errors`);if(console.log(`
24
+ ${o}`),console.log(y.dim(" downloaded: ")+t.downloaded),t.uploaded)console.log(y.dim(" uploaded: ")+t.uploaded);if(t.deleted)console.log(y.dim(" deleted: ")+t.deleted);if(t.skipped)console.log(y.dim(" skipped: ")+t.skipped);if(!r){console.log(y.dim(" errors: ")+t.errors.length);for(let n of t.errors.slice(0,5))console.log(y.dim(" ")+y.red(`${n.path}: ${n.message}`));if(t.errors.length>5)console.log(y.dim(` ... and ${t.errors.length-5} more`))}}function Rn(e){if(e<1024)return`${e}B`;if(e<1048576)return`${(e/1024).toFixed(1)}KB`;return`${(e/1024/1024).toFixed(2)}MB`}import{existsSync as Pn}from"node:fs";import{resolve as $n}from"node:path";import S from"picocolors";import{CloudFileTransport as Tn}from"@shogo-ai/sdk/cloud-file-transport";async function nr(e,t){if(!e)throw Error("projectId is required");let r=A({apiKey:t.apiKey,cloudUrl:t.cloudUrl}),o=$n(t.from??B(e,r.projectsDir));if(!Pn(o))throw Error(`Source directory does not exist: ${o}`);let n=t.include?.split(",").map((a)=>a.trim()).filter(Boolean);if(console.log(S.bold(`
25
+ shogo project push ${S.cyan(e)}`)),console.log(S.dim(" cloud ")+r.cloudUrl),console.log(S.dim(" from ")+o),n?.length)console.log(S.dim(" include ")+n.join(", "));if(t.deleteRemote)console.log(S.yellow(" --delete-remote: remote files not present locally will be DELETED"));console.log("");let s=await new Tn({apiUrl:r.cloudUrl,apiKey:r.apiKey,projectId:e,localDir:o,include:n,onProgress:(a)=>{let c=a.kind==="upload"?"↑":a.kind==="delete"?"✗":"·",l=a.total>0?` ${a.index+1}/${a.total}`:"",u=a.bytes!=null?S.dim(` (${In(a.bytes)})`):"";console.log(S.dim(` ${c}${l} ${a.path}${u}`))}}).uploadAll({deleteRemote:t.deleteRemote});En("Push",s)}function En(e,t){let r=t.errors.length===0,o=r?S.green(`✓ ${e} complete`):S.red(`✗ ${e} completed with errors`);if(console.log(`
26
+ ${o}`),console.log(S.dim(" uploaded: ")+t.uploaded),t.deleted)console.log(S.dim(" deleted: ")+t.deleted);if(!r){console.log(S.dim(" errors: ")+t.errors.length);for(let n of t.errors.slice(0,5))console.log(S.dim(" ")+S.red(`${n.path}: ${n.message}`));if(t.errors.length>5)console.log(S.dim(` ... and ${t.errors.length-5} more`))}}function In(e){if(e<1024)return`${e}B`;if(e<1048576)return`${(e/1024).toFixed(1)}KB`;return`${(e/1024/1024).toFixed(2)}MB`}import{existsSync as xn}from"node:fs";import{resolve as Cn}from"node:path";import O from"picocolors";ge();async function ir(e,t){if(!e)throw Error("projectId is required");let r=A({apiKey:t.apiKey,cloudUrl:t.cloudUrl}),o=Cn(t.into??B(e,r.projectsDir));if(!xn(o))throw Error(`Local project dir does not exist: ${o} — run \`shogo project pull\` first`);if(!he(o))throw Error(`${o} is not a git repo. \`shogo project checkout\` requires the git sync path; run \`shogo project pull\` after installing git, or use \`shogo project pull --include\` for file-only restore.`);if(console.log(O.bold(`
27
+ shogo project checkout ${O.cyan(e)}`)),console.log(O.dim(" cloud ")+r.cloudUrl),console.log(O.dim(" local ")+o),t.at)console.log(O.dim(" at ")+t.at);if(console.log(""),t.unshallow)console.log(O.dim("Unshallowing repo (this may take a moment)...")),await Oe({apiUrl:r.cloudUrl,apiKey:r.apiKey,projectId:e,localDir:o});if(!t.at){let i=await me({apiUrl:r.cloudUrl,apiKey:r.apiKey,projectId:e,localDir:o});console.log(O.green(`✓ Reset to ${i.commitSha.slice(0,8)} (remote HEAD)`));return}let n;try{n=(await P(["rev-parse","--verify",`${t.at}^{commit}`],{cwd:o})).stdout.trim()}catch{n=await _n(r.cloudUrl,r.apiKey,e,t.at),console.log(O.dim(` resolved checkpoint "${t.at}" → ${n.slice(0,8)}`))}try{await me({apiUrl:r.cloudUrl,apiKey:r.apiKey,projectId:e,localDir:o,branch:n})}catch{if(!t.unshallow)console.log(O.yellow(" fetch failed; unshallowing and retrying...")),await Oe({apiUrl:r.cloudUrl,apiKey:r.apiKey,projectId:e,localDir:o}),await me({apiUrl:r.cloudUrl,apiKey:r.apiKey,projectId:e,localDir:o,branch:n});else throw Error(`Cannot reach commit ${n} in local clone`)}await P(["reset","--hard",n],{cwd:o}),console.log(O.green(`✓ Checked out ${n.slice(0,8)}`))}async function _n(e,t,r,o){let n=`${e.replace(/\/+$/,"")}/api/projects/${encodeURIComponent(r)}/checkpoints?limit=100`,i=await fetch(n,{headers:{Authorization:`Bearer ${t}`}});if(!i.ok)throw Error(`Failed to list checkpoints: HTTP ${i.status}`);let s=await i.json(),a=o.toLowerCase(),c=s.checkpoints.find((l)=>{if(l.name&&l.name.toLowerCase()===a)return!0;if(l.commitSha.startsWith(o))return!0;if(l.commitMessage&&l.commitMessage.toLowerCase().includes(a))return!0;return!1});if(!c)throw Error(`No checkpoint matches "${o}" (searched ${s.checkpoints.length} most recent)`);return c.commitSha}import{createInterface as Un}from"node:readline";import v from"picocolors";import{execFileSync as ar}from"node:child_process";import{existsSync as J,copyFileSync as sr}from"node:fs";import C from"node:path";import{homedir as lr,platform as cr}from"node:os";function ur(e,t,r){let n=ar(e,["-e",r],{env:{...process.env,DBP:t},encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5000}).trim();if(!n)throw Error(`bun script returned empty output for ${t}`);return JSON.parse(n)}function Se(e,t){if(!J(t))return[];return ur(e,t,`
28
28
  import { Database } from 'bun:sqlite';
29
29
  try {
30
30
  const db = new Database(process.env.DBP, { readonly: true });
@@ -38,9 +38,9 @@ shogo project checkout ${b.cyan($)}`)),console.log(b.dim(" cloud ")+Y.cloudUrl
38
38
  console.error(String(e?.stack || e));
39
39
  process.exit(2);
40
40
  }
41
- `)}function v1($){if(!c($))throw Error(`Database does not exist at ${$} — refusing to back up nothing`);let X=P.dirname($),Y=P.basename($),Z=new Date().toISOString().replace(/[:.]/g,"-"),z=P.join(X,`${Y}.bak-${Z}`);K$($,z);for(let J of["-wal","-shm"]){let K=`${$}${J}`;if(c(K))K$(K,`${z}${J}`)}return z}function h1($,X,Y){if(Y.length===0)return 0;if(!c(X))throw Error(`Cannot repair: database does not exist at ${X}`);let z=`
41
+ `)}function An(e){if(!J(e))throw Error(`Database does not exist at ${e} — refusing to back up nothing`);let t=C.dirname(e),r=C.basename(e),o=new Date().toISOString().replace(/[:.]/g,"-"),n=C.join(t,`${r}.bak-${o}`);sr(e,n);for(let i of["-wal","-shm"]){let s=`${e}${i}`;if(J(s))sr(s,`${n}${i}`)}return n}function On(e,t,r){if(r.length===0)return 0;if(!J(t))throw Error(`Cannot repair: database does not exist at ${t}`);let n=`
42
42
  import { Database } from 'bun:sqlite';
43
- const names = ${JSON.stringify(Y)};
43
+ const names = ${JSON.stringify(r)};
44
44
  if (!Array.isArray(names) || names.some(n => typeof n !== 'string')) {
45
45
  console.error('Invalid migration name list');
46
46
  process.exit(2);
@@ -57,8 +57,8 @@ shogo project checkout ${b.cyan($)}`)),console.log(b.dim(" cloud ")+Y.cloudUrl
57
57
  console.error(String(e?.stack || e));
58
58
  process.exit(3);
59
59
  }
60
- `;return Q$($,X,z).deleted}function G$($){let X=$.log??(()=>{}),{bunPath:Y,dbPath:Z}=$;if(!c(Z))return{status:"no-database",detected:[],cleared:[],remaining:[],message:`No database found at ${Z}. Nothing to repair — launch Shogo once to create it.`};let z=B0(Y,Z);if(z.length===0)return{status:"healthy",detected:[],cleared:[],remaining:[],message:"No failed migrations detected — the local database looks healthy."};X(`Found ${z.length} failed migration(s): ${z.map((G)=>G.name).join(", ")}`);let J;if(!$.skipBackup)J=v1(Z),X(`Backed up database to ${J}`);let K=z.map((G)=>G.name),V=h1(Y,Z,K);X(`Cleared ${V} failed migration row(s).`);let H=B0(Y,Z),q=H.length===0?"repaired":"failed",Q=q==="repaired"?"Cleared the failed migration record. Relaunch Shogo to re-apply migrations cleanly.":`Repair incomplete — ${H.length} migration(s) still failed: ${H.map((G)=>G.name).join(", ")}.`;return{status:q,detected:z,backupPath:J,cleared:K.slice(0,V),remaining:H,message:Q}}function j1(){let $=q$(),X=H$(),Y;if(X==="darwin")Y=P.join($,"Library","Application Support");else if(X==="win32")Y=process.env.APPDATA??P.join($,"AppData","Roaming");else Y=process.env.XDG_CONFIG_HOME??P.join($,".config");return P.join(Y,"Shogo","data")}function W$(){return P.join(j1(),"shogo.db")}function m1(){let $=H$(),X=$==="win32"?"bun.exe":"bun",Y=q$(),Z=[];if($==="darwin")Z.push(P.join("/Applications","Shogo.app","Contents","Resources","bun",X),P.join(Y,"Applications","Shogo.app","Contents","Resources","bun",X));else if($==="linux")Z.push(P.join("/opt","Shogo","resources","bun",X),P.join("/usr","lib","shogo","resources","bun",X));return Z}function r0($){try{return V$($,["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function k$($){if($)return r0($)?$:null;if(process.versions.bun&&process.execPath)return process.execPath;for(let X of m1())if(c(X)&&r0(X))return X;if(r0("bun"))return"bun";return null}function u1($){for(let X of $){let Y=Number.isFinite(X.startedAt)?new Date(X.startedAt).toISOString():"unknown time",Z=(X.errorExcerpt??"").split(`
61
- `)[0]?.trim();if(console.log(` ${A.yellow("•")} ${A.bold(X.name)} ${A.dim(`(attempted ${Y})`)}`),Z)console.log(` ${A.dim(Z)}`)}}async function f1($){if(!process.stdin.isTTY)return console.log(A.dim("(stdin is not a TTY — re-run with --yes to repair non-interactively)")),!1;let X=I1({input:process.stdin,output:process.stdout});try{let Y=await new Promise((Z)=>X.question($,Z));return/^y(es)?$/i.test(Y.trim())}finally{X.close()}}async function O$($={}){let X=$.db??W$(),Y=k$($.bun);if(!Y)throw Error("Could not find a usable `bun` binary (needed to inspect the SQLite database).\n"+" • Install Bun (https://bun.sh) so `bun` is on your PATH, or\n"+` • pass --bun <path> pointing at the bun shipped inside the Shogo app
62
- `+" (e.g. /Applications/Shogo.app/Contents/Resources/bun/bun on macOS).");console.log(A.dim(`Database: ${X}`)),console.log(A.dim(`Bun: ${Y}`)),console.log();let Z=B0(Y,X);if(Z.length===0){console.log(A.green("✓ No failed migrations detected — your local database looks healthy."));return}if(console.log(A.red(`✗ Found ${Z.length} failed migration(s):`)),u1(Z),console.log(),$.check){console.log(A.dim("Run `shogo doctor` (without --check) to back up the database and clear these records.")),process.exitCode=1;return}if(!$.yes){let J=$.backup===!1?A.red("This will NOT create a backup (--no-backup)."):"Your database will be backed up to a .bak-<timestamp> file first.";if(console.log(J),!await f1(A.bold("Clear these failed migration records and repair? [y/N] "))){console.log(A.dim("Aborted — no changes made.")),process.exitCode=1;return}console.log()}let z=G$({bunPath:Y,dbPath:X,skipBackup:$.backup===!1,log:(J)=>console.log(A.dim(` ${J}`))});if(console.log(),z.status==="repaired"){if(console.log(A.green(`✓ ${z.message}`)),z.backupPath)console.log(A.dim(` Backup: ${z.backupPath}`));console.log(A.bold(`
63
- → Relaunch the Shogo app to finish applying migrations.`))}else{if(console.log(A.red(`✗ ${z.message}`)),z.backupPath)console.log(A.dim(` Backup: ${z.backupPath}`));process.exitCode=1}}import{spawn as n1}from"node:child_process";import{resolve as d1}from"node:path";import w$ from"picocolors";function g1($){let{flags:X,config:Y,runtime:Z}=$,z=X.cwd?d1(X.cwd):process.cwd(),J=["interactive"];if(X.print!==void 0)J.push("-p",X.print);if(X.noTui)J.push("--no-tui");let K=Y.cloudUrl.replace(/\/$/,""),V={...$.baseEnv??process.env,SHOGO_INTERACTIVE:"1",SHOGO_INTERACTIVE_CWD:z,PROJECT_DIR:z,WORKSPACE_DIR:z,SHOGO_API_URL:K,SHOGO_CLOUD_URL:K,SHOGO_API_KEY:Y.apiKey,AI_PROXY_URL:`${K}/api/ai/v1`,AI_PROXY_TOKEN:Y.apiKey,NODE_ENV:"production"};if(X.model)V.SHOGO_MODEL=X.model;if(X.print!==void 0)V.SHOGO_PRINT_PROMPT=X.print;return{bin:Z.path,args:J,env:V,cwd:z}}async function C$($={}){let X=R({apiKey:$.apiKey,cloudUrl:$.cloudUrl}),Y=u({flag:$.runtimeBin});if(!Y)console.error(w$.red(n({flag:$.runtimeBin}))),process.exit(1);let Z=g1({flags:$,config:{apiKey:X.apiKey,cloudUrl:X.cloudUrl},runtime:Y}),z=await new Promise((J)=>{let K=n1(Z.bin,Z.args,{cwd:Z.cwd,env:Z.env,stdio:"inherit"});K.on("error",(V)=>{console.error(w$.red(`✗ Failed to launch agent-runtime: ${V.message}`)),J(1)}),K.on("exit",(V)=>J(V??0))});process.exit(z)}var p1="0.1.0",E=new i1;E.name("shogo").description("Shogo Cloud Agent Worker — run Shogo agents on your own machine.").version(p1);E.command("login").description("Pair this machine with Shogo Cloud (browser device flow, or --api-key for CI)").option("--api-key <key>","CI escape hatch — skip the browser flow and use a key directly").option("--cloud-url <url>","Shogo Cloud URL (default: https://studio.shogo.ai)").option("--name <name>","Device label shown in the dashboard (default: hostname)").option("--workspace <id>","Pre-select a workspace on the bridge picker").option("--no-browser","Do not auto-open the browser; print the URL instead").action(($)=>F(()=>p2($)));var F0=E.command("worker").description("Manage the local worker process");F0.command("start").description("Start the worker and pair with Shogo Cloud").option("--name <name>","Instance name shown in the dashboard (default: hostname)").option("--worker-dir <path>","Working directory for the worker (default: $PWD)").option("--api-key <key>","API key (overrides config/env)").option("--cloud-url <url>","Shogo Cloud URL").option("--port <port>","Local HTTP port for the embedded API").option("--proxy <url>","HTTPS proxy (overrides HTTPS_PROXY env)").option("--project <id>","Pin to a single project (default: multi-project on demand)").option("--runtime-bin <path>","Override the agent-runtime binary path").option("--debug","Run preflight checks before starting").option("--foreground","Run in foreground (don't detach)").option("--no-auto-pull","Disable auto-clone of project workspaces on first request").option("--projects-dir <path>","Root directory for cloned project workspaces (default: ~/.shogo/projects)").option("--no-git","Force the file-transport sync path even when git is available").action(($)=>F(()=>m2($)));F0.command("stop").description("Stop the running worker").action(()=>F(u2));F0.command("status").description("Show worker status").action(()=>F(f2));F0.command("logs").description("Tail worker logs from ~/.shogo/logs/worker.log").option("-f, --follow","Follow the log (tail -F)").option("--err","Show stderr log instead").action(($)=>F(()=>d2($)));var T0=E.command("runtime").description("Install / inspect the local agent-runtime binary");T0.command("install").description("Download + verify the agent-runtime tarball into ~/.shogo/runtime/").option("--channel <channel>","stable | beta | nightly (default: stable)").option("--version <version>","install a specific version (e.g. 0.1.0)").option("--base-url <url>","override release base URL (default: GitHub Releases)").option("--force","reinstall even if the same version is already on disk").action(($)=>F(()=>l0($)));T0.command("version").description("Print the installed agent-runtime version").action(()=>F(()=>$$()));T0.command("where").description("Print the resolved agent-runtime binary path").action(()=>F(()=>X$()));T0.command("update").description("Update agent-runtime to the latest in its channel").option("--channel <channel>","override channel (defaults to whatever is installed)").option("--base-url <url>","override release base URL").action(($)=>F(()=>Y$($)));var U$=E.command("config").description("Inspect or modify ~/.shogo/config.json");U$.command("show").description("Print current config (API key masked)").action(()=>F(c2));U$.command("set <key> <value>").description("Set apiKey / cloudUrl / name / workerDir / port / projectsDir").action(($,X)=>F(()=>a2($,X)));var e0=E.command("project").description("Clone/sync project workspaces between Shogo Cloud and this machine");e0.command("pull <projectId>").description("Clone a project from Shogo Cloud into ~/.shogo/projects/<projectId>/").option("--into <dir>","Destination directory (default: ~/.shogo/projects/<projectId>)").option("--watch","After pull, watch the local dir and push edits back to cloud").option("--include <patterns>",'Comma-separated glob patterns (e.g. "src/**,*.md")').option("--api-key <key>","Override API key for this run").option("--cloud-url <url>","Override Shogo Cloud URL for this run").action(($,X)=>F(()=>Z$($,X)));e0.command("push <projectId>").description("Upload local workspace edits back to Shogo Cloud").option("--from <dir>","Source directory (default: ~/.shogo/projects/<projectId>)").option("--delete-remote","Mirror local deletions to cloud (DESTRUCTIVE)").option("--include <patterns>","Comma-separated glob patterns").option("--api-key <key>","Override API key for this run").option("--cloud-url <url>","Override Shogo Cloud URL for this run").action(($,X)=>F(()=>z$($,X)));e0.command("checkout <projectId>").description("Roll the local workspace to a specific git checkpoint (SHA or named checkpoint)").option("--at <ref>","Target SHA or checkpoint name (default: remote HEAD)").option("--unshallow","Fetch full history before checking out (needed for old SHAs)").option("--into <dir>","Local dir override (default: ~/.shogo/projects/<projectId>)").option("--api-key <key>","Override API key for this run").option("--cloud-url <url>","Override Shogo Cloud URL for this run").action(($,X)=>F(()=>J$($,X)));E.command("doctor").description("Diagnose & repair a wedged local Shogo database (clears failed migrations so the app can reboot)").option("--check","Detect only — never modify the database").option("--yes","Repair without the confirmation prompt").option("--db <path>","Path to shogo.db (default: the desktop app's local database)").option("--bun <path>","Path to a bun binary (default: bundled/PATH bun)").option("--no-backup","Skip the pre-repair database backup (discouraged)").action(($)=>F(()=>O$($)));E.command("chat",{isDefault:!0}).description("Start the interactive coding agent in the current directory").argument("[prompt...]","Optional one-shot prompt (runs non-interactively, like -p)").option("-p, --print <prompt>","Headless one-shot: run a single turn and print the result").option("--model <model>","Model id to use for new turns").option("--cwd <dir>","Working directory to operate in (default: $PWD)").option("--runtime-bin <path>","Override the agent-runtime binary path").option("--no-tui","Disable the rich TUI; use a plain readline renderer").option("--api-key <key>","Override API key for this run").option("--cloud-url <url>","Override Shogo Cloud URL for this run").action(($,X)=>F(()=>C$({print:X.print??($.length?$.join(" "):void 0),model:X.model,cwd:X.cwd,runtimeBin:X.runtimeBin,noTui:X.tui===!1,apiKey:X.apiKey,cloudUrl:X.cloudUrl})));E.showHelpAfterError(L$.dim(`
64
- (use --help for usage)`));E.parseAsync(process.argv);async function F($){try{await $()}catch(X){if(console.error(L$.red(`✗ ${X?.message??X}`)),process.env.SHOGO_DEBUG)console.error(X?.stack);process.exit(1)}}
60
+ `;return ur(e,t,n).deleted}function pr(e){let t=e.log??(()=>{}),{bunPath:r,dbPath:o}=e;if(!J(o))return{status:"no-database",detected:[],cleared:[],remaining:[],message:`No database found at ${o}. Nothing to repair — launch Shogo once to create it.`};let n=Se(r,o);if(n.length===0)return{status:"healthy",detected:[],cleared:[],remaining:[],message:"No failed migrations detected — the local database looks healthy."};t(`Found ${n.length} failed migration(s): ${n.map((p)=>p.name).join(", ")}`);let i;if(!e.skipBackup)i=An(o),t(`Backed up database to ${i}`);let s=n.map((p)=>p.name),a=On(r,o,s);t(`Cleared ${a} failed migration row(s).`);let c=Se(r,o),l=c.length===0?"repaired":"failed",u=l==="repaired"?"Cleared the failed migration record. Relaunch Shogo to re-apply migrations cleanly.":`Repair incomplete — ${c.length} migration(s) still failed: ${c.map((p)=>p.name).join(", ")}.`;return{status:l,detected:n,backupPath:i,cleared:s.slice(0,a),remaining:c,message:u}}function Mn(){let e=lr(),t=cr(),r;if(t==="darwin")r=C.join(e,"Library","Application Support");else if(t==="win32")r=process.env.APPDATA??C.join(e,"AppData","Roaming");else r=process.env.XDG_CONFIG_HOME??C.join(e,".config");return C.join(r,"Shogo","data")}function dr(){return C.join(Mn(),"shogo.db")}function Dn(){let e=cr(),t=e==="win32"?"bun.exe":"bun",r=lr(),o=[];if(e==="darwin")o.push(C.join("/Applications","Shogo.app","Contents","Resources","bun",t),C.join(r,"Applications","Shogo.app","Contents","Resources","bun",t));else if(e==="linux")o.push(C.join("/opt","Shogo","resources","bun",t),C.join("/usr","lib","shogo","resources","bun",t));return o}function Ye(e){try{return ar(e,["--version"],{stdio:"ignore",timeout:5000}),!0}catch{return!1}}function mr(e){if(e)return Ye(e)?e:null;if(process.versions.bun&&process.execPath)return process.execPath;for(let t of Dn())if(J(t)&&Ye(t))return t;if(Ye("bun"))return"bun";return null}function Wn(e){for(let t of e){let r=Number.isFinite(t.startedAt)?new Date(t.startedAt).toISOString():"unknown time",o=(t.errorExcerpt??"").split(`
61
+ `)[0]?.trim();if(console.log(` ${v.yellow("•")} ${v.bold(t.name)} ${v.dim(`(attempted ${r})`)}`),o)console.log(` ${v.dim(o)}`)}}async function Nn(e){if(!process.stdin.isTTY)return console.log(v.dim("(stdin is not a TTY — re-run with --yes to repair non-interactively)")),!1;let t=Un({input:process.stdin,output:process.stdout});try{let r=await new Promise((o)=>t.question(e,o));return/^y(es)?$/i.test(r.trim())}finally{t.close()}}async function hr(e={}){let t=e.db??dr(),r=mr(e.bun);if(!r)throw Error("Could not find a usable `bun` binary (needed to inspect the SQLite database).\n"+" • Install Bun (https://bun.sh) so `bun` is on your PATH, or\n"+` • pass --bun <path> pointing at the bun shipped inside the Shogo app
62
+ `+" (e.g. /Applications/Shogo.app/Contents/Resources/bun/bun on macOS).");console.log(v.dim(`Database: ${t}`)),console.log(v.dim(`Bun: ${r}`)),console.log();let o=Se(r,t);if(o.length===0){console.log(v.green("✓ No failed migrations detected — your local database looks healthy."));return}if(console.log(v.red(`✗ Found ${o.length} failed migration(s):`)),Wn(o),console.log(),e.check){console.log(v.dim("Run `shogo doctor` (without --check) to back up the database and clear these records.")),process.exitCode=1;return}if(!e.yes){let i=e.backup===!1?v.red("This will NOT create a backup (--no-backup)."):"Your database will be backed up to a .bak-<timestamp> file first.";if(console.log(i),!await Nn(v.bold("Clear these failed migration records and repair? [y/N] "))){console.log(v.dim("Aborted — no changes made.")),process.exitCode=1;return}console.log()}let n=pr({bunPath:r,dbPath:t,skipBackup:e.backup===!1,log:(i)=>console.log(v.dim(` ${i}`))});if(console.log(),n.status==="repaired"){if(console.log(v.green(`✓ ${n.message}`)),n.backupPath)console.log(v.dim(` Backup: ${n.backupPath}`));console.log(v.bold(`
63
+ → Relaunch the Shogo app to finish applying migrations.`))}else{if(console.log(v.red(`✗ ${n.message}`)),n.backupPath)console.log(v.dim(` Backup: ${n.backupPath}`));process.exitCode=1}}import{spawn as jn}from"node:child_process";import{resolve as Fn}from"node:path";import gr from"picocolors";function Ln(e){let{flags:t,config:r,runtime:o}=e,n=t.cwd?Fn(t.cwd):process.cwd(),i=["interactive"];if(t.print!==void 0)i.push("-p",t.print);if(t.noTui)i.push("--no-tui");let s=r.cloudUrl.replace(/\/$/,""),a={...e.baseEnv??process.env,SHOGO_INTERACTIVE:"1",SHOGO_INTERACTIVE_CWD:n,PROJECT_DIR:n,WORKSPACE_DIR:n,SHOGO_API_URL:s,SHOGO_CLOUD_URL:s,SHOGO_API_KEY:r.apiKey,AI_PROXY_URL:`${s}/api/ai/v1`,AI_PROXY_TOKEN:r.apiKey,NODE_ENV:"production"};if(t.model)a.SHOGO_MODEL=t.model;if(t.print!==void 0)a.SHOGO_PRINT_PROMPT=t.print;return{bin:o.path,args:i,env:a,cwd:n}}async function fr(e={}){let t=A({apiKey:e.apiKey,cloudUrl:e.cloudUrl}),r=F({flag:e.runtimeBin});if(!r)console.error(gr.red(H({flag:e.runtimeBin}))),process.exit(1);let o=Ln({flags:e,config:{apiKey:t.apiKey,cloudUrl:t.cloudUrl},runtime:r}),n=await new Promise((i)=>{let s=jn(o.bin,o.args,{cwd:o.cwd,env:o.env,stdio:"inherit"});s.on("error",(a)=>{console.error(gr.red(`✗ Failed to launch agent-runtime: ${a.message}`)),i(1)}),s.on("exit",(a)=>i(a??0))});process.exit(n)}var Gn="0.1.0",M=new Hn;M.name("shogo").description("Shogo Cloud Agent Worker — run Shogo agents on your own machine.").version(Gn);M.command("login").description("Pair this machine with Shogo Cloud (browser device flow, or --api-key for CI)").option("--api-key <key>","CI escape hatch — skip the browser flow and use a key directly").option("--cloud-url <url>","Shogo Cloud URL (default: https://studio.shogo.ai)").option("--name <name>","Device label shown in the dashboard (default: hostname)").option("--workspace <id>","Pre-select a workspace on the bridge picker").option("--no-browser","Do not auto-open the browser; print the URL instead").action((e)=>k(()=>Kt(e)));var ke=M.command("worker").description("Manage the local worker process");ke.command("start").description("Start the worker and pair with Shogo Cloud").option("--name <name>","Instance name shown in the dashboard (default: hostname)").option("--worker-dir <path>","Working directory for the worker (default: $PWD)").option("--api-key <key>","API key (overrides config/env)").option("--cloud-url <url>","Shogo Cloud URL").option("--port <port>","Local HTTP port for the embedded API").option("--proxy <url>","HTTPS proxy (overrides HTTPS_PROXY env)").option("--project <id>","Pin to a single project (default: multi-project on demand)").option("--runtime-bin <path>","Override the agent-runtime binary path").option("--debug","Run preflight checks before starting").option("--foreground","Run in foreground (don't detach)").option("--no-auto-pull","Disable auto-clone of project workspaces on first request").option("--projects-dir <path>","Root directory for cloned project workspaces (default: ~/.shogo/projects)").option("--no-git","Force the file-transport sync path even when git is available").action((e)=>k(()=>Wt(e)));ke.command("stop").description("Stop the running worker").action(()=>k(jt));ke.command("status").description("Show worker status").action(()=>k(Ft));ke.command("logs").description("Tail worker logs from ~/.shogo/logs/worker.log").option("-f, --follow","Follow the log (tail -F)").option("--err","Show stderr log instead").action((e)=>k(()=>Ht(e)));var Re=M.command("runtime").description("Install / inspect the local agent-runtime binary");Re.command("install").description("Download + verify the agent-runtime tarball into ~/.shogo/runtime/").option("--channel <channel>","stable | beta | nightly (default: stable)").option("--version <version>","install a specific version (e.g. 0.1.0)").option("--base-url <url>","override release base URL (default: GitHub Releases)").option("--force","reinstall even if the same version is already on disk").action((e)=>k(()=>Ve(e)));Re.command("version").description("Print the installed agent-runtime version").action(()=>k(()=>er()));Re.command("where").description("Print the resolved agent-runtime binary path").action(()=>k(()=>tr()));Re.command("update").description("Update agent-runtime to the latest in its channel").option("--channel <channel>","override channel (defaults to whatever is installed)").option("--base-url <url>","override release base URL").action((e)=>k(()=>rr(e)));var yr=M.command("config").description("Inspect or modify ~/.shogo/config.json");yr.command("show").description("Print current config (API key masked)").action(()=>k(qt));yr.command("set <key> <value>").description("Set apiKey / cloudUrl / name / workerDir / port / projectsDir").action((e,t)=>k(()=>Jt(e,t)));var Xe=M.command("project").description("Clone/sync project workspaces between Shogo Cloud and this machine");Xe.command("pull <projectId>").description("Clone a project from Shogo Cloud into ~/.shogo/projects/<projectId>/").option("--into <dir>","Destination directory (default: ~/.shogo/projects/<projectId>)").option("--watch","After pull, watch the local dir and push edits back to cloud").option("--include <patterns>",'Comma-separated glob patterns (e.g. "src/**,*.md")').option("--api-key <key>","Override API key for this run").option("--cloud-url <url>","Override Shogo Cloud URL for this run").action((e,t)=>k(()=>or(e,t)));Xe.command("push <projectId>").description("Upload local workspace edits back to Shogo Cloud").option("--from <dir>","Source directory (default: ~/.shogo/projects/<projectId>)").option("--delete-remote","Mirror local deletions to cloud (DESTRUCTIVE)").option("--include <patterns>","Comma-separated glob patterns").option("--api-key <key>","Override API key for this run").option("--cloud-url <url>","Override Shogo Cloud URL for this run").action((e,t)=>k(()=>nr(e,t)));Xe.command("checkout <projectId>").description("Roll the local workspace to a specific git checkpoint (SHA or named checkpoint)").option("--at <ref>","Target SHA or checkpoint name (default: remote HEAD)").option("--unshallow","Fetch full history before checking out (needed for old SHAs)").option("--into <dir>","Local dir override (default: ~/.shogo/projects/<projectId>)").option("--api-key <key>","Override API key for this run").option("--cloud-url <url>","Override Shogo Cloud URL for this run").action((e,t)=>k(()=>ir(e,t)));M.command("doctor").description("Diagnose & repair a wedged local Shogo database (clears failed migrations so the app can reboot)").option("--check","Detect only — never modify the database").option("--yes","Repair without the confirmation prompt").option("--db <path>","Path to shogo.db (default: the desktop app's local database)").option("--bun <path>","Path to a bun binary (default: bundled/PATH bun)").option("--no-backup","Skip the pre-repair database backup (discouraged)").action((e)=>k(()=>hr(e)));M.command("chat",{isDefault:!0}).description("Start the interactive coding agent in the current directory").argument("[prompt...]","Optional one-shot prompt (runs non-interactively, like -p)").option("-p, --print <prompt>","Headless one-shot: run a single turn and print the result").option("--model <model>","Model id to use for new turns").option("--cwd <dir>","Working directory to operate in (default: $PWD)").option("--runtime-bin <path>","Override the agent-runtime binary path").option("--no-tui","Disable the rich TUI; use a plain readline renderer").option("--api-key <key>","Override API key for this run").option("--cloud-url <url>","Override Shogo Cloud URL for this run").action((e,t)=>k(()=>fr({print:t.print??(e.length?e.join(" "):void 0),model:t.model,cwd:t.cwd,runtimeBin:t.runtimeBin,noTui:t.tui===!1,apiKey:t.apiKey,cloudUrl:t.cloudUrl})));M.showHelpAfterError(wr.dim(`
64
+ (use --help for usage)`));M.parseAsync(process.argv);async function k(e){try{await e()}catch(t){if(console.error(wr.red(`✗ ${t?.message??t}`)),process.env.SHOGO_DEBUG)console.error(t?.stack);process.exit(1)}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shogo-ai/worker",
3
- "version": "2.0.20",
3
+ "version": "2.1.1",
4
4
  "description": "Shogo Cloud Agent Worker — run Shogo agents on your own machine (laptop, devbox, CI).",
5
5
  "license": "MIT",
6
6
  "author": "Shogo Technologies, Inc.",