planx 19.139.0 → 19.140.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/layout.main.mjs CHANGED
@@ -50,7 +50,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
50
50
  `)}var qi={up(e,t){e.curRow=Math.max(0,e.curRow-t)},down(e,t){e.curRow+=t,e.ensureRow(e.curRow)},forward(e,t){e.curCol+=t},back(e,t){e.curCol=Math.max(0,e.curCol-t)},toColumn(e,t){e.curCol=Math.max(0,t)},position(e,t,r){e.curRow=Math.max(0,t),e.curCol=Math.max(0,r),e.ensureRow(e.curRow)},prevLine(e,t){e.curRow=Math.max(0,e.curRow-t),e.curCol=0},nextLine(e,t){e.curRow+=t,e.ensureRow(e.curRow),e.curCol=0},verticalAbsolute(e,t){e.curRow=Math.max(0,t),e.ensureRow(e.curRow)}};var Ht={getViewportTop(e){return Math.max(0,e.chars.length-e._viewportRows)},absToVpRel(e,t){return t-Ht.getViewportTop(e)},vpRelToAbs(e,t){return Ht.getViewportTop(e)+t},curVpRel(e){return Ht.absToVpRel(e,e.curRow)},isCursorAtScrollTop(e){return Ht.curVpRel(e)===e._scrollTop},isCursorAtScrollBottom(e){return e._scrollBottom<9999&&Ht.curVpRel(e)===e._scrollBottom},vpToAbsSticky(e,t){let r=Ht.vpRelToAbs(e,t-1),n=e._stickyCupAbsRow.get(t);return n!==void 0&&n>=Ht.getViewportTop(e)&&n<e.chars.length?n:(e._stickyCupAbsRow.set(t,r),r)}};var Rte=Object.freeze({}),EQe=1e4,MQe=EQe-1,Cm=class{constructor(){this.chars=[[]],this.stys=[[]],this.curRow=0,this.curCol=0,this._st=Rte,this._rowAnsiCache=[],this._pendingEsc="",this._altMode=!1,this._savedMain=null,this._scrollTop=0,this._scrollBottom=MQe,this._cursorVisible=!0,this._tabStops=new Set,this._inSyncUpdate=!1,this._applicationCursorKeyMode=!1,this._bracketedPasteMode=!1,this._savedCursorPos=null,this._stickyCupAbsRow=new Map,this._cursorStyle=0,this._viewportRows=40,this._viewportCols=80,this._parseStyles=Rte,this._encoders=new Set,this._feedListeners=new Set}isInSyncUpdate(){return this._inSyncUpdate}isApplicationCursorKeyMode(){return this._applicationCursorKeyMode}isBracketedPasteMode(){return this._bracketedPasteMode}getCursorStyle(){return this._cursorStyle}get viewportRows(){return this._viewportRows}get cursorRow(){return this.curRow}get cursorCol(){return this.curCol}get viewportTopRow(){return this.getViewportTop()}getViewportTop(){return Ht.getViewportTop(this)}setViewportSize(t,r){nte(this,t,r)}setStyles(t){this._st=Object.freeze(t)}absToVpRel(t){return Ht.absToVpRel(this,t)}vpRelToAbs(t){return Ht.vpRelToAbs(this,t)}get curVpRel(){return Ht.curVpRel(this)}get isCursorAtScrollTop(){return Ht.isCursorAtScrollTop(this)}get isCursorAtScrollBottom(){return Ht.isCursorAtScrollBottom(this)}vpToAbsSticky(t){return Ht.vpToAbsSticky(this,t)}markRowDirty(t){this._rowAnsiCache[t]=void 0}markAllDirty(){this._rowAnsiCache.length=0}ensureRow(t){for(;this.chars.length<=t;)this.chars.push([]),this.stys.push([])}saveCursorPos(){bte(this)}restoreCursorPos(){Ste(this)}writeChar(t){ote(this,t)}writeRun(t,r,n){ate(this,t,r,n)}writeText(t){ste(this,t)}newline(){ute(this)}carriageReturn(){this.curCol=0}clearLine(t){cte(this,t)}eraseInDisplay(t){Jee(this,t)}toSegments(){return ete(this)}feed(t){Kee(this,t);for(let r of this._feedListeners)try{r()}catch{}}onFeed(t){return this._feedListeners.add(t),()=>{this._feedListeners.delete(t)}}cursorUp(t){qi.up(this,t)}cursorDown(t){qi.down(this,t)}cursorForward(t){qi.forward(this,t)}cursorBack(t){qi.back(this,t)}cursorToColumn(t){qi.toColumn(this,t)}cursorPosition(t,r){qi.position(this,t,r)}cursorPrevLine(t){qi.prevLine(this,t)}cursorNextLine(t){qi.nextLine(this,t)}verticalPositionAbsolute(t){qi.verticalAbsolute(this,t)}scrollRegionUp(){lte(this)}scrollRegionDown(){dte(this)}feedText(t,r,n){fte(this,t,r,n)}reverseIndex(){Ite(this)}index(){wte(this)}nextLine(){this.newline()}reset(){Ate(this)}insertLines(t){pte(this,t)}deleteLines(t){hte(this,t)}insertChars(t){mte(this,t)}deleteChars(t){yte(this,t)}eraseChars(t){_te(this,t)}tabStop(){vte(this)}nextTabStop(t){return Ote(this,t)}enterAltScreen(){tte(this)}exitAltScreen(){rte(this)}trimScrollbackIfOver(){xte(this)}serializeRow(t){return Cte(this,t)}rowsAsAnsi(){return O3(this)}getScreenAnsi(){return Pte(this)}getViewportSnapshot(){return $te(this)}getScrollbackAnsi(t){return Nte(this,t)}getViewportScrollback(t){return Dte(this,t)}_registerEncoder(t){this._encoders.add(t)}_unregisterEncoder(t){this._encoders.delete(t)}_emitPassthroughCsi(t){for(let r of this._encoders)r._onPassthroughCsi(t)}_emitPendingResetScreen(){for(let t of this._encoders)t._onPendingResetScreen()}_emitPendingSyncWrap(){for(let t of this._encoders)t._onPendingSyncWrap()}_emitSnapshotInvalidated(){for(let t of this._encoders)t._onSnapshotInvalidated()}_captureSnapshot(){return Ete(this)}_computeDelta(t,r){return Gee(this,t,r)}};var Fte="\x1B[0m\x1B[H\x1B[2J\x1B[3J";function qte(e,t){let r=e.cursorRow,n=e.cursorCol,i=e.viewportRows,o=e.getScrollbackAnsi(t);if(o.length===0)return Fte;let a=o.split(`
51
51
  `),s=Math.min(a.length,r+1),u=a.slice(0,s),c=u.slice(-i).map(A=>A.replace(/\s+$/,"")),l=0;for(;c.length>1&&c[0]==="";)c.shift(),l++;let f=c,p=u.length-f.length,h=r-p,y=Math.max(1,Math.min(h+1,f.length+1)),_=h>=0&&h<f.length?`\x1B[${y};${n+1}H\x1B[K`:`\x1B[${y};${n+1}H`,w=f.map((A,N)=>`\x1B[${N+1};1H${A}\x1B[K`).join("");return Fte+w+_}var TQe=5e3,x3=class{constructor(t,r){this.queryService=t,this.messages$=r}handleData(t,r){let n=this.queryService.sessionMap()[t];if(!n){console.warn(`[PtyDataHandler] output dropped: session missing in sessionMap sessionId=${t} dataLen=${r.length}`);return}this.updateOutputBuffer(n,r),this.messages$.next({type:"session:server:pty-manager:session-data",sessionId:t,data:r})}handleExit(t,r,n){this.processExit(t,r,n)}destroy(){}processExit(t,r,n){let i=this.queryService.sessionMap()[t];i&&(i.status="terminated",this.queryService.removeSession(t),this.messages$.next({type:"session:server:pty-manager:session-exit",sessionId:t,exitCode:r,signal:n}))}updateOutputBuffer(t,r){this.ensureGrid(t).feed(this.augmentClearWithScrollback(r))}augmentClearWithScrollback(t){return t.replace(/(?<!\x1b\[3J)\x1b\[2J(?!\x1b\[3J)/g,"\x1B[3J\x1B[2J")}ensureGrid(t){let r=t.grid;if(r)return r;let n=new Cm;return t.grid=n,Object.defineProperty(t,"outputBuffer",{get(){return qte(n,TQe)},set(i){},enumerable:!0,configurable:!0}),n}};import{existsSync as CQe,realpathSync as PQe}from"fs";import Ox from"path";function jte(){let e=process.argv[1];if(e)try{let t=Ox.dirname(PQe(e)),r=Ox.join(t,"tmux-shim");return CQe(Ox.join(r,"tmux"))?r:void 0}catch{return}}async function Lte(){return(await import("node-pty")).spawn}function kte(e){let t={...e.parentEnv,...e.optionsEnv??{},PATH:[e.shim,e.systemPath].filter(Boolean).join(":"),TERM:"xterm-256color",COLORTERM:"truecolor",FORCE_COLOR:"1",PLANX_SESSION_NAME:e.name,PLANX_SESSION_ID:e.id,...e.parentId?{PLANX_PARENT_SESSION_ID:e.parentId}:{},PLANX_SERVER_ID:e.serverId,PLANX_SERVER_NAME:e.serverName,...e.shim?{PLANX_TMUX_SHIM_DIR:e.shim}:{},...e.transportPortFile?{PLANX_TRANSPORT_PORT_FILE:e.transportPortFile}:{}};return delete t.TMUX,delete t.TMUX_PANE,e.transportPortFile||delete t.PLANX_TRANSPORT_PORT_FILE,t}var NQe=500,DQe=500,RQe=25,E3=class{constructor(t,r,n=i8,i=a8){this.config=t,this.queryService=r,this.escalateKillFn=n,this.resolvePgidFn=i,this.ptyMap=new Map,this.exitedSessions=new Set,this.messages$=new Bte.ReplaySubject(50),this._shimResolved=!1,this.dataHandler=new x3(this.queryService,this.messages$)}ensureGrid(t){return this.dataHandler.ensureGrid(t)}get shimDir(){return this._shimResolved||(this._shimDir=jte(),this._shimResolved=!0),this._shimDir}async createSession(t){if(this.queryService.sessionMap()[t.id])throw new Error(`Session already exists: ${t.id}`);if(t.parentId&&!this.queryService.getSession(t.parentId))throw new Error(`Parent session not found: ${t.parentId}`);let r=this.config.shell??($Qe.platform()==="win32"?"powershell.exe":"/bin/zsh"),n=t.command?["-c",t.command]:["-i","-l"],i={id:t.id,name:t.name,parentId:t.parentId,cwd:t.cwd,env:t.env,createdAt:new Date,lastAccessedAt:new Date,updatedAt:new Date,status:"active",command:t.command||r};this.queryService.updateSession(i);let o=this.queryService.resolveEnv(i),a=this.queryService.resolveCwd(i);try{console.error(`DIAG_SPAWNPTY_BEFORE id=${t.id} shell=${r} ts=${Date.now()}`)}catch{}let s=await this.spawnPty(t.id,t.name,r,n,{cwd:a,env:o});try{console.error(`DIAG_SPAWNPTY_AFTER pid=${JSON.stringify(s.pid)} pidType=${typeof s.pid} ptyKeys=${Object.keys(s).join(",").slice(0,200)} ts=${Date.now()}`)}catch{}i.pid=s.pid;try{console.error(`DIAG_SPAWNPTY_ASSIGNED session.pid=${JSON.stringify(i.pid)} session.status=${JSON.stringify(i.status)} sessionKeys=${Object.keys(i).join(",")} ts=${Date.now()}`)}catch{}return this.queryService.updateSession(i),this.ptyMap.set(t.id,s),this.messages$.next({type:"session:server:pty-manager:session-created",sessionId:t.id,parentSessionId:t.parentId}),i}async spawnPty(t,r,n,i,o){let a=this.queryService.getSession(t)?.parentId,s=this.shimDir,u=await Lte(),c=kte({parentEnv:this.config.parentEnv??{},optionsEnv:o?.env,shim:s,systemPath:this.config.systemPath??"",id:t,name:r,parentId:a,serverId:this.config.serverId,serverName:this.config.serverName,transportPortFile:this.config.transportPortFile}),l=u(n,i,{name:"xterm-256color",cols:80,rows:30,cwd:o?.cwd??process.cwd(),env:c});l.onData(p=>this.dataHandler.handleData(t,p)),l.onExit(({exitCode:p,signal:h})=>{this.exitedSessions.add(t),this.dataHandler.handleExit(t,p??-1,h??0)});let f=this.queryService.getSession(t);return f&&(f.promptBootstrapped=!0),setTimeout(()=>{try{l.write(`
52
52
  `)}catch{}},100),l}async destroySession(t){for(let n of this.queryService.getChildSessions(t))await this.destroySession(n.id);let r=this.ptyMap.get(t);if(r?.pid&&!this.exitedSessions.has(t)){let n=this.resolvePgidFn(r.pid)===r.pid;await this.escalateKillFn(r.pid,{killFn:(i,o)=>process.kill(n?-i:i,o),termTimeoutMs:NQe,killTimeoutMs:DQe,pollMs:RQe})}this.queryService.removeSession(t),this.ptyMap.delete(t),this.exitedSessions.delete(t),this.messages$.next({type:"session:server:pty-manager:session-exit",sessionId:t})}async destroyAllSessions(){let t=Object.keys(this.queryService.sessionMap()),r=0,n=[];for(let i of t)try{await this.destroySession(i),r++}catch(o){n.push(`${i}: ${o.message}`)}return{deletedCount:r,errors:n}}};var Ute="\0@machina/silent\0",M3=class{constructor(t){this.queryService=t}attach(t,r){let n=this.queryService.getSession(t);if(!n)throw new Error(`session(${t}) not found.`);n.lastAccessedAt=new Date,n.status="active";let i=r.get(t);return!n.promptBootstrapped&&(n.outputBuffer?.length??0)<50&&i&&(n.promptBootstrapped=!0,setTimeout(()=>i.write(`
53
- `),100)),n}input(t,r,n){let i=this.queryService.getSession(t);if(!i)throw new Error("Session not found");let o=n.get(t);if(r&&!o&&console.warn(`[PtyIoService] input dropped: pty missing in ptyMap sessionId=${t} knownPtyIds=${[...n.keys()].join(",")}`),r&&o){if(r.startsWith(Ute)){let a=r.slice(Ute.length);o.write(`\x1B[8m${a}\x1B[0m\x1B[2K\r`)}else o.write(r);i.lastAccessedAt=new Date}}resize(t,r,n,i){let o=this.queryService.getSession(t);if(!o)throw new Error("Session not found");let a=i.get(t);if(!r||!n||!a||a.cols===r&&a.rows===n)return;a.resize(r,n);let s=o.grid;s&&s.setViewportSize(n,r)}renameSession(t,r){let n=this.queryService.sessionMap()[t];if(!n){let i=Object.keys(this.queryService.sessionMap());throw new Error(`Session not found: ${t}. Available: ${i.join(", ")||"none"}`)}return this.queryService.updateSession({...n,name:r,updatedAt:new Date}),this.queryService.getSession(t)}};var sf=Ft(Q_());var xx=class{isProcessRunning(t){return o8(t)}isPtyValid(t){return!!(t.pid&&t.pid!==void 0)}},T3=class{constructor(t,r,n=()=>[]){this.getSession=t,this.destroySession=r,this.listSessions=n,this.destroy$=new sf.ReplaySubject(1),this.validator=new xx}start(){this.subscription=(0,sf.interval)(3e4).pipe((0,sf.takeUntil)(this.destroy$)).subscribe(()=>this.performHealthCheck())}stop(){this.destroy$.next(),this.subscription?.unsubscribe()}async performHealthCheck(){for(let t of this.listSessions())await this.checkSessionHealth(t)}async checkSessionHealth(t){return this.validator.isPtyValid(t)?this.validator.isProcessRunning(t.pid)?!0:(await this.destroySession(t.id),!1):(await this.onUnhealthySession(t.id),!1)}async onUnhealthySession(t){let r=this.getSession(t);r&&(r.status="terminated",await this.destroySession(t))}};var Pm=class{constructor(t){this.queryService=new fg,this.factoryService=new E3(t,this.queryService),this.ioService=new M3(this.queryService),this.healthCheckService=new T3(r=>this.queryService.getSession(r),r=>this.factoryService.destroySession(r),()=>this.queryService.listSessions()),this.sessions$=this.queryService.sessions$,this.messages$=this.factoryService.messages$}createSession(t){return this.factoryService.createSession(t)}destroySession(t){return this.factoryService.destroySession(t)}destroyAllSessions(){return this.factoryService.destroyAllSessions()}listSessions(){return this.queryService.listSessions()}getSession(t){return this.queryService.getSession(t)}getChildSessions(t){return this.queryService.getChildSessions(t)}getPty(t){return this.factoryService.ptyMap.get(t)}getScrollback(t,r){let n=this.queryService.getSession(t);if(!n)return"";let i=n.grid;return i?i.getScrollbackAnsi(r):""}ensureGrid(t){let r=this.queryService.getSession(t);return r?this.factoryService.ensureGrid(r):null}attach(t){return this.ioService.attach(t,this.factoryService.ptyMap)}input(t,r){this.ioService.input(t,r,this.factoryService.ptyMap)}resize(t,r,n){this.ioService.resize(t,r,n,this.factoryService.ptyMap)}renameSession(t,r){let n=this.ioService.renameSession(t,r);return this.messages$.next({type:"session:server:pty-manager:session-renamed",sessionId:t,name:r}),n}start(){this.healthCheckService.start()}async stop(){this.healthCheckService.stop(),await this.factoryService.destroyAllSessions()}};var pc=null,FQe=null,Vte=null;async function Hte(){return Vte?await Vte():null}var qQe=new Map,jQe=null;function Wte(e,t){jQe?.(e,t)}function Gte(e,t){return pc||(FQe=e,pc=t??new Pm(e),t||pc.start(),pc)}function ot(){if(!pc)throw new Error("PtyManagerService not initialized. Call initContext() first.");return pc}function Zte(){return qQe}function Yte(e){let t=e;"keepAliveTimeout"in t&&(t.keepAliveTimeout=3e4),"requestTimeout"in t&&(t.requestTimeout=0),"headersTimeout"in t&&(t.headersTimeout=0),"timeout"in t&&(t.timeout=0)}import LQe from"os";function uf(){return{serverId:process.env.PLANX_SERVER_ID??"local",serverName:process.env.PLANX_SERVER_NAME??"local",shell:process.env.SHELL??(LQe.platform()==="win32"?"powershell.exe":"/bin/zsh"),systemPath:process.env.PATH??"",parentEnv:process.env,transportPortFile:process.env.PLANX_TRANSPORT_PORT_FILE??null,sessionPort:(()=>{let e=parseInt(process.env.PLANX_SESSION_PORT??"",10);return isNaN(e)?null:e})(),wtPort:(()=>{let e=parseInt(process.env.PLANX_SESSION_WT_PORT??"",10);return isNaN(e)||e<=0?null:e})(),port:(()=>{let e=parseInt(process.env.PORT??"",10);return isNaN(e)||e<=0?null:e})()}}function Ms(e){return{id:e.id,name:e.name,pid:e.pid??null,command:e.command,parentId:e.parentId,createdAt:e.createdAt.toISOString(),lastAccessedAt:e.lastAccessedAt.toISOString(),status:e.status}}import{randomUUID as BQe}from"crypto";var kQe=["\u82F1\u6570","\u304B\u306A","Eisu","Kana"];function Kte(e){return kQe.includes(e)}var zte={Enter:"\r",Escape:"\x1B",Tab:" ",Space:" ",BSpace:"\x7F",Backspace:"\x7F",DC:"\x1B[3~",Delete:"\x1B[3~",Up:"\x1B[A",Down:"\x1B[B",Right:"\x1B[C",Left:"\x1B[D",Home:"\x1B[H",End:"\x1B[F",PageUp:"\x1B[5~",PageDown:"\x1B[6~",Insert:"\x1B[2~",F1:"\x1BOP",F2:"\x1BOQ",F3:"\x1BOR",F4:"\x1BOS",F5:"\x1B[15~",F6:"\x1B[17~",F7:"\x1B[18~",F8:"\x1B[19~",F9:"\x1B[20~",F10:"\x1B[21~",F11:"\x1B[23~",F12:"\x1B[24~"};function Jte(e){if(/^C-(.+)$/i.test(e)){let t=e.slice(2).toLowerCase();return t.length===1&&t>="a"&&t<="z"?String.fromCharCode(t.charCodeAt(0)-96):t==="space"||t==="@"?"\0":t==="["?"\x1B":t==="\\"?"":t==="]"?"":t==="^"?"":t==="_"?"":e}return/^M-(.+)$/i.test(e)?"\x1B"+e.slice(2):/^[A-Z]/.test(e)&&e.length>1&&zte[e]?zte[e]:e}var UQe=ee.object({id:ee.string().optional(),name:ee.string().optional(),command:ee.string().optional(),parentId:ee.string().optional(),cwd:ee.string().optional(),env:ee.record(ee.string()).optional()}),VQe=ee.object({name:ee.string().optional(),status:ee.literal("detached").optional(),cols:ee.number().optional(),rows:ee.number().optional()}).refine(e=>e.name!==void 0||e.status!==void 0||e.cols!==void 0&&e.rows!==void 0,{message:"name / status / {cols,rows} \u306E\u3044\u305A\u308C\u304B\u304C\u5FC5\u8981"}),HQe=ee.object({data:ee.string()}),WQe=ee.object({keys:ee.array(ee.string()),literal:ee.boolean().optional()});async function Ex(e){try{return await e.req.json()}catch{return null}}function Xte(){let e=new qt;return e.post("/sessions",async t=>{let r=UQe.safeParse(await Ex(t));if(!r.success)return t.json({error:{code:"INVALID_BODY",message:r.error.message}},400);let n=r.data,i=n.id??BQe(),o=await ot().createSession({id:i,name:n.name??i.slice(0,8),command:n.command,parentId:n.parentId,cwd:n.cwd,env:n.env});return t.json(Ms(o),201)}),e.patch("/sessions/:id",async t=>{let r=t.req.param("id"),n=VQe.safeParse(await Ex(t));if(!n.success)return t.json({error:{code:"INVALID_BODY",message:n.error.message}},400);let i=ot().getSession(r);if(!i)return t.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);let{name:o,status:a,cols:s,rows:u}=n.data;s!==void 0&&u!==void 0&&ot().resize(r,s,u),a==="detached"&&(i.status="detached"),o!==void 0&&ot().renameSession(r,o);let c=ot().getSession(r);return t.json(Ms(c??i))}),e.delete("/sessions/:id",async t=>{let r=t.req.param("id");return await ot().destroySession(r),t.json({success:!0,id:r})}),e.post("/sessions/:id/input",async t=>{let r=t.req.param("id"),n=await Ex(t),i=HQe.safeParse(n),o=i.success?null:WQe.safeParse(n);if(!i.success&&!o?.success)return t.json({error:{code:"INVALID_BODY",message:"body \u306F {data} \u307E\u305F\u306F {keys, literal?}"}},400);if(!ot().getSession(r))return t.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);if(i.success)return ot().input(r,i.data.data),t.json({success:!0,id:r});let{keys:a,literal:s}=o.success?o.data:{keys:[],literal:!1},u=a.filter(c=>!Kte(c)).map(c=>s?c:Jte(c)).join("");return u.length>0&&ot().input(r,u),t.json({success:!0,id:r})}),e}var GQe=ee.object({peerId:ee.string(),fps:ee.number()});function Qte(){let e=new qt;return e.put("/sessions/:id/stream-config",async t=>{let r=t.req.param("id"),n=null;try{n=await t.req.json()}catch{}let i=GQe.safeParse(n);if(!i.success)return t.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let{peerId:o,fps:a}=i.data,s=`${o}\0${r}`;return Zte().set(s,{fps:a}),Wte(r,a),t.json({success:!0,id:r})}),e.get("/system/wt-config",async t=>t.json(await Hte())),e}function C3(e){let t=e.intervalMs??25e3,r=e.now??(()=>Date.now()),n=new TextEncoder,i=!1,o=setInterval(()=>{if(!i)try{e.enqueue(n.encode(`: heartbeat ${r()}
53
+ `),100)),n}input(t,r,n){let i=this.queryService.getSession(t);if(!i)throw new Error("Session not found");let o=n.get(t);if(r&&!o&&console.warn(`[PtyIoService] input dropped: pty missing in ptyMap sessionId=${t} knownPtyIds=${[...n.keys()].join(",")}`),r&&o){if(r.startsWith(Ute)){let a=r.slice(Ute.length);o.write(`\x1B[8m${a}\x1B[0m\x1B[2K\r`)}else o.write(r);i.lastAccessedAt=new Date}}resize(t,r,n,i){let o=this.queryService.getSession(t);if(!o)throw new Error("Session not found");let a=i.get(t);if(!r||!n||!a||a.cols===r&&a.rows===n)return;a.resize(r,n);let s=o.grid;s&&s.setViewportSize(n,r)}renameSession(t,r){let n=this.queryService.sessionMap()[t];if(!n){let i=Object.keys(this.queryService.sessionMap());throw new Error(`Session not found: ${t}. Available: ${i.join(", ")||"none"}`)}return this.queryService.updateSession({...n,name:r,updatedAt:new Date}),this.queryService.getSession(t)}};var sf=Ft(Q_());var xx=class{isProcessRunning(t){return o8(t)}isPtyValid(t){return!!(t.pid&&t.pid!==void 0)}},T3=class{constructor(t,r,n=()=>[]){this.getSession=t,this.destroySession=r,this.listSessions=n,this.destroy$=new sf.ReplaySubject(1),this.validator=new xx}start(){this.subscription=(0,sf.interval)(3e4).pipe((0,sf.takeUntil)(this.destroy$)).subscribe(()=>this.performHealthCheck())}stop(){this.destroy$.next(),this.subscription?.unsubscribe()}async performHealthCheck(){for(let t of this.listSessions())await this.checkSessionHealth(t)}async checkSessionHealth(t){return this.validator.isPtyValid(t)?this.validator.isProcessRunning(t.pid)?!0:(await this.destroySession(t.id),!1):(await this.onUnhealthySession(t.id),!1)}async onUnhealthySession(t){let r=this.getSession(t);r&&(r.status="terminated",await this.destroySession(t))}};var Pm=class{constructor(t){this.queryService=new fg,this.factoryService=new E3(t,this.queryService),this.ioService=new M3(this.queryService),this.healthCheckService=new T3(r=>this.queryService.getSession(r),r=>this.factoryService.destroySession(r),()=>this.queryService.listSessions()),this.sessions$=this.queryService.sessions$,this.messages$=this.factoryService.messages$}createSession(t){return this.factoryService.createSession(t)}destroySession(t){return this.factoryService.destroySession(t)}destroyAllSessions(){return this.factoryService.destroyAllSessions()}listSessions(){return this.queryService.listSessions()}getSession(t){return this.queryService.getSession(t)}getChildSessions(t){return this.queryService.getChildSessions(t)}getPty(t){return this.factoryService.ptyMap.get(t)}getScrollback(t,r){let n=this.queryService.getSession(t);if(!n)return"";let i=n.grid;return i?i.getScrollbackAnsi(r):""}ensureGrid(t){let r=this.queryService.getSession(t);return r?this.factoryService.ensureGrid(r):null}attach(t){return this.ioService.attach(t,this.factoryService.ptyMap)}input(t,r){this.ioService.input(t,r,this.factoryService.ptyMap)}resize(t,r,n){this.ioService.resize(t,r,n,this.factoryService.ptyMap)}renameSession(t,r){let n=this.ioService.renameSession(t,r);return this.messages$.next({type:"session:server:pty-manager:session-renamed",sessionId:t,name:r}),n}start(){this.healthCheckService.start()}async stop(){this.healthCheckService.stop(),await this.factoryService.destroyAllSessions()}};var pc=null,FQe=null,Vte=null;async function Hte(){return Vte?await Vte():null}var qQe=new Map,jQe=null;function Wte(e,t){jQe?.(e,t)}function Gte(e,t){return pc||(FQe=e,pc=t??new Pm(e),t||pc.start(),pc)}function ot(){if(!pc)throw new Error("PtyManagerService not initialized. Call initContext() first.");return pc}function Zte(){return qQe}function Yte(e){let t=e;"keepAliveTimeout"in t&&(t.keepAliveTimeout=3e4),"requestTimeout"in t&&(t.requestTimeout=0),"headersTimeout"in t&&(t.headersTimeout=0),"timeout"in t&&(t.timeout=0)}import LQe from"os";function uf(){return{serverId:process.env.PLANX_SERVER_ID??"local",serverName:process.env.PLANX_SERVER_NAME??"local",shell:process.env.SHELL??(LQe.platform()==="win32"?"powershell.exe":"/bin/zsh"),systemPath:process.env.PATH??"",parentEnv:process.env,transportPortFile:process.env.PLANX_TRANSPORT_PORT_FILE??null,sessionPort:(()=>{let e=parseInt(process.env.PLANX_SESSION_PORT??"",10);return isNaN(e)?null:e})(),wtPort:(()=>{let e=parseInt(process.env.PLANX_SESSION_WT_PORT??"",10);return isNaN(e)||e<=0?null:e})(),port:(()=>{let e=parseInt(process.env.PORT??"",10);return isNaN(e)||e<=0?null:e})()}}function Ms(e){return{id:e.id,name:e.name,pid:e.pid??null,command:e.command,parentId:e.parentId,createdAt:e.createdAt.toISOString(),lastAccessedAt:e.lastAccessedAt.toISOString(),status:e.status}}import{randomUUID as BQe}from"crypto";var kQe=["\u82F1\u6570","\u304B\u306A","Eisu","Kana"];function Kte(e){return kQe.includes(e)}var zte={Enter:"\r",Escape:"\x1B",Tab:" ",Space:" ",BSpace:"\x7F",Backspace:"\x7F",DC:"\x1B[3~",Delete:"\x1B[3~",Up:"\x1B[A",Down:"\x1B[B",Right:"\x1B[C",Left:"\x1B[D",Home:"\x1B[H",End:"\x1B[F",PageUp:"\x1B[5~",PageDown:"\x1B[6~",Insert:"\x1B[2~",F1:"\x1BOP",F2:"\x1BOQ",F3:"\x1BOR",F4:"\x1BOS",F5:"\x1B[15~",F6:"\x1B[17~",F7:"\x1B[18~",F8:"\x1B[19~",F9:"\x1B[20~",F10:"\x1B[21~",F11:"\x1B[23~",F12:"\x1B[24~"};function Jte(e){if(/^C-(.+)$/i.test(e)){let t=e.slice(2).toLowerCase();return t.length===1&&t>="a"&&t<="z"?String.fromCharCode(t.charCodeAt(0)-96):t==="space"||t==="@"?"\0":t==="["?"\x1B":t==="\\"?"":t==="]"?"":t==="^"?"":t==="_"?"":e}return/^M-(.+)$/i.test(e)?"\x1B"+e.slice(2):/^[A-Z]/.test(e)&&e.length>1&&zte[e]?zte[e]:e}var UQe=ee.object({id:ee.string().optional(),name:ee.string().optional(),command:ee.string().optional(),parentId:ee.string().optional(),cwd:ee.string().optional(),env:ee.record(ee.string(),ee.string()).optional()}),VQe=ee.object({name:ee.string().optional(),status:ee.literal("detached").optional(),cols:ee.number().optional(),rows:ee.number().optional()}).refine(e=>e.name!==void 0||e.status!==void 0||e.cols!==void 0&&e.rows!==void 0,{message:"name / status / {cols,rows} \u306E\u3044\u305A\u308C\u304B\u304C\u5FC5\u8981"}),HQe=ee.object({data:ee.string()}),WQe=ee.object({keys:ee.array(ee.string()),literal:ee.boolean().optional()});async function Ex(e){try{return await e.req.json()}catch{return null}}function Xte(){let e=new qt;return e.post("/sessions",async t=>{let r=UQe.safeParse(await Ex(t));if(!r.success)return t.json({error:{code:"INVALID_BODY",message:r.error.message}},400);let n=r.data,i=n.id??BQe(),o=await ot().createSession({id:i,name:n.name??i.slice(0,8),command:n.command,parentId:n.parentId,cwd:n.cwd,env:n.env});return t.json(Ms(o),201)}),e.patch("/sessions/:id",async t=>{let r=t.req.param("id"),n=VQe.safeParse(await Ex(t));if(!n.success)return t.json({error:{code:"INVALID_BODY",message:n.error.message}},400);let i=ot().getSession(r);if(!i)return t.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);let{name:o,status:a,cols:s,rows:u}=n.data;s!==void 0&&u!==void 0&&ot().resize(r,s,u),a==="detached"&&(i.status="detached"),o!==void 0&&ot().renameSession(r,o);let c=ot().getSession(r);return t.json(Ms(c??i))}),e.delete("/sessions/:id",async t=>{let r=t.req.param("id");return await ot().destroySession(r),t.json({success:!0,id:r})}),e.post("/sessions/:id/input",async t=>{let r=t.req.param("id"),n=await Ex(t),i=HQe.safeParse(n),o=i.success?null:WQe.safeParse(n);if(!i.success&&!o?.success)return t.json({error:{code:"INVALID_BODY",message:"body \u306F {data} \u307E\u305F\u306F {keys, literal?}"}},400);if(!ot().getSession(r))return t.json({error:{code:"SESSION_NOT_FOUND",message:`Session not found: ${r}`}},404);if(i.success)return ot().input(r,i.data.data),t.json({success:!0,id:r});let{keys:a,literal:s}=o.success?o.data:{keys:[],literal:!1},u=a.filter(c=>!Kte(c)).map(c=>s?c:Jte(c)).join("");return u.length>0&&ot().input(r,u),t.json({success:!0,id:r})}),e}var GQe=ee.object({peerId:ee.string(),fps:ee.number()});function Qte(){let e=new qt;return e.put("/sessions/:id/stream-config",async t=>{let r=t.req.param("id"),n=null;try{n=await t.req.json()}catch{}let i=GQe.safeParse(n);if(!i.success)return t.json({error:{code:"INVALID_BODY",message:i.error.message}},400);let{peerId:o,fps:a}=i.data,s=`${o}\0${r}`;return Zte().set(s,{fps:a}),Wte(r,a),t.json({success:!0,id:r})}),e.get("/system/wt-config",async t=>t.json(await Hte())),e}function C3(e){let t=e.intervalMs??25e3,r=e.now??(()=>Date.now()),n=new TextEncoder,i=!1,o=setInterval(()=>{if(!i)try{e.enqueue(n.encode(`: heartbeat ${r()}
54
54
 
55
55
  `))}catch{a()}},t),a=()=>{i||(i=!0,clearInterval(o))};return e.signal&&(e.signal.aborted?a():e.signal.addEventListener("abort",a,{once:!0})),a}function ere(e){let t=new TextEncoder,r;try{r=e.req.raw.signal}catch{r=void 0}let n=!1,i=null,o=null,a=()=>{n=!0;try{i?.unsubscribe()}catch{}try{o?.()}catch{}},s=new ReadableStream({start(u){u.enqueue(t.encode(`: sse-init
56
56