@myrialabs/clopen 0.2.20 → 0.2.22

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.
@@ -6,14 +6,16 @@
6
6
  *
7
7
  * Strategy:
8
8
  * 1. Check DB for previously stored server URL → health-check → reuse if alive
9
- * 2. Otherwise spawn `opencode serve` with port 0 (OS-assigned) and persist URL
9
+ * 2. Otherwise spawn `opencode serve` via Bun.spawn (port 0, OS-assigned) and persist URL
10
10
  * 3. On every ensureClient() call, verify the server is still alive.
11
11
  * If it died mid-session, automatically recover through the same flow.
12
12
  */
13
13
 
14
14
  import type { OpencodeClient } from '@opencode-ai/sdk';
15
+ import type { Subprocess } from 'bun';
15
16
  import { getOpenCodeMcpConfig } from '../../../mcp';
16
17
  import { settingsQueries } from '../../../database/queries';
18
+ import { resolveCommand } from '../../../ws/engine/utils';
17
19
  import { debug } from '$shared/utils/logger';
18
20
 
19
21
  const OPENCODE_HOST = '127.0.0.1';
@@ -21,6 +23,7 @@ const DB_KEY = 'opencode.server.url';
21
23
  const HEALTH_TIMEOUT = 1500;
22
24
  const SERVER_START_TIMEOUT = 30_000; // 30s — generous for slow devices
23
25
 
26
+ let serverProc: Subprocess | null = null;
24
27
  let serverHandle: { url: string; close(): void } | null = null;
25
28
  let client: OpencodeClient | null = null;
26
29
  let initPromise: Promise<void> | null = null;
@@ -31,6 +34,7 @@ function clearClientState(): void {
31
34
  client = null;
32
35
  ready = false;
33
36
  serverHandle = null;
37
+ serverProc = null;
34
38
  ownsProcess = false;
35
39
  }
36
40
 
@@ -113,8 +117,9 @@ async function init(): Promise<void> {
113
117
  settingsQueries.delete(DB_KEY);
114
118
  }
115
119
 
116
- // 2. Spawn a new server — port 0 lets opencode pick an OS-assigned port
117
- const { createOpencode } = await import('@opencode-ai/sdk');
120
+ // 2. Spawn a new server via Bun.spawn — uses same binary resolution as detectCLI
121
+ const command = await resolveCommand('opencode');
122
+ const args = [command, 'serve', `--hostname=${OPENCODE_HOST}`, '--port=0'];
118
123
 
119
124
  // Build MCP config — but only inject if the MCP endpoint is actually reachable.
120
125
  // The opencode binary may initialize MCP connections synchronously before printing
@@ -137,25 +142,81 @@ async function init(): Promise<void> {
137
142
  }
138
143
  }
139
144
 
140
- // No retry — SDK does not kill the child process on timeout, so retrying
141
- // would leave zombie `opencode serve` processes running in the background.
142
- // 30s timeout is generous enough for slow devices.
143
- const result = await createOpencode({
144
- hostname: OPENCODE_HOST,
145
- port: 0,
146
- timeout: SERVER_START_TIMEOUT,
147
- ...(Object.keys(mcpConfig).length > 0 && {
148
- config: { mcp: mcpConfig },
149
- }),
145
+ const configContent = Object.keys(mcpConfig).length > 0
146
+ ? JSON.stringify({ mcp: mcpConfig })
147
+ : '{}';
148
+
149
+ debug.log('engine', `Spawning: ${args.join(' ')}`);
150
+
151
+ const proc = Bun.spawn(args, {
152
+ stdout: 'pipe',
153
+ stderr: 'pipe',
154
+ env: {
155
+ ...process.env,
156
+ OPENCODE_CONFIG_CONTENT: configContent,
157
+ },
158
+ });
159
+
160
+ // Parse server URL from stdout — opencode prints "opencode server listening on <url>"
161
+ const url = await new Promise<string>((resolve, reject) => {
162
+ const timeout = setTimeout(() => {
163
+ proc.kill();
164
+ reject(new Error(`Timeout waiting for opencode server to start after ${SERVER_START_TIMEOUT}ms`));
165
+ }, SERVER_START_TIMEOUT);
166
+
167
+ let output = '';
168
+
169
+ const readStream = async (stream: ReadableStream<Uint8Array>, label: string) => {
170
+ const reader = stream.getReader();
171
+ const decoder = new TextDecoder();
172
+ try {
173
+ while (true) {
174
+ const { done, value } = await reader.read();
175
+ if (done) break;
176
+ const chunk = decoder.decode(value, { stream: true });
177
+ output += chunk;
178
+
179
+ if (label === 'stdout') {
180
+ for (const line of output.split('\n')) {
181
+ if (line.startsWith('opencode server listening')) {
182
+ const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
183
+ if (match) {
184
+ clearTimeout(timeout);
185
+ resolve(match[1]);
186
+ return;
187
+ }
188
+ }
189
+ }
190
+ }
191
+ }
192
+ } catch {
193
+ // stream closed
194
+ }
195
+ };
196
+
197
+ readStream(proc.stdout as ReadableStream<Uint8Array>, 'stdout');
198
+ readStream(proc.stderr as ReadableStream<Uint8Array>, 'stderr');
199
+
200
+ proc.exited.then((code) => {
201
+ clearTimeout(timeout);
202
+ let msg = `opencode server exited with code ${code}`;
203
+ if (output.trim()) msg += `\nServer output: ${output}`;
204
+ reject(new Error(msg));
205
+ });
150
206
  });
151
207
 
152
- serverHandle = result.server;
153
- client = result.client;
208
+ serverProc = proc;
209
+ const { createOpencodeClient } = await import('@opencode-ai/sdk');
210
+ client = createOpencodeClient({ baseUrl: url });
211
+ serverHandle = {
212
+ url,
213
+ close() { proc.kill(); },
214
+ };
154
215
  ownsProcess = true;
155
216
  ready = true;
156
217
 
157
- settingsQueries.set(DB_KEY, result.server.url);
158
- debug.log('engine', `Open Code client ready (server: ${result.server.url})`);
218
+ settingsQueries.set(DB_KEY, url);
219
+ debug.log('engine', `Open Code client ready (server: ${url})`);
159
220
  }
160
221
 
161
222
  export function getClient(): OpencodeClient | null {
@@ -5,7 +5,7 @@
5
5
  * Converts Open Code messages/events → SDKMessage (Claude format)
6
6
  * so stream-manager and frontend remain unchanged.
7
7
  *
8
- * Server lifecycle is managed by ./server.ts (bun-pty spawn).
8
+ * Server lifecycle is managed by ./server.ts (Bun.spawn).
9
9
  * This file only contains the OpenCodeEngine class (per-project instance).
10
10
  */
11
11
 
package/bin/clopen.ts CHANGED
@@ -359,10 +359,8 @@ async function clearAllData() {
359
359
  // ============================================================
360
360
 
361
361
  async function setupEnvironment() {
362
- if (!existsSync(ENV_FILE)) {
363
- if (existsSync(ENV_EXAMPLE)) {
364
- copyFileSync(ENV_EXAMPLE, ENV_FILE);
365
- }
362
+ if (existsSync(ENV_EXAMPLE)) {
363
+ copyFileSync(ENV_EXAMPLE, ENV_FILE);
366
364
  }
367
365
  }
368
366
 
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-D1IISCsM.js","assets/main-DzSwlujO.css"])))=>i.map(i=>d[i]);
2
- import{t as c,a as h,d,b as m,c as S,_ as p,o as P}from"./main-D1IISCsM.js";class v{projectContexts=new Map;currentProjectId=null;constructor(){}getOrCreateProjectContext(e,s){let t=this.projectContexts.get(e);return t||(t={projectId:e,projectPath:s,sessionIds:[],activeSessionId:null,lastActiveAt:new Date,sessionOutputs:new Map,sessionCommandHistories:new Map},this.projectContexts.set(e,t),this.persistContexts()),t}async switchToProject(e,s){this.currentProjectId&&this.currentProjectId!==e&&(await this.saveCurrentProjectState(),await this.hideProjectTerminalSessions(this.currentProjectId));const t=this.getOrCreateProjectContext(e,s);this.currentProjectId!==e&&c.clearAllSessions(),t.sessionIds.length===0?await this.createProjectTerminalSessions(e,s):await this.showProjectTerminalSessions(t),this.currentProjectId=e,t.lastActiveAt=new Date,this.persistContexts(),await this.checkAndRestoreActiveStreams(e)}async createProjectTerminalSessions(e,s){const t=this.getOrCreateProjectContext(e,s),n=await h.listProjectSessions(e);if(n.length>0){d.log("terminal",`Found ${n.length} existing PTY sessions for project ${e}`),n.sort((r,l)=>r.sessionId.localeCompare(l.sessionId));for(const r of n){const l=r.sessionId.split("-"),f=l[l.length-1]||"1",I={id:r.sessionId,name:`Terminal ${f}`,directory:r.cwd||s,lines:[],commandHistory:[],isActive:!1,createdAt:new Date(r.createdAt),lastUsedAt:new Date(r.lastActivityAt),shellType:"Unknown",terminalBuffer:void 0,projectId:e,projectPath:s};c.addSession(I),m.createSession(r.sessionId,e,s,r.cwd||s),t.sessionIds.push(r.sessionId);const u=r.sessionId.match(/terminal-(\d+)/);u&&c.updateNextSessionId(parseInt(u[1],10)+1)}let o=n[0].sessionId;if(typeof sessionStorage<"u")try{const r=sessionStorage.getItem(`terminal-active-session-${e}`);r&&t.sessionIds.includes(r)&&(o=r)}catch{}t.activeSessionId=o,c.switchToSession(t.activeSessionId),this.persistContexts();return}const i=c.createNewSession(s,s,e),a=c.getSession(i);a&&(a.directory=s),m.createSession(i,e,s,s),t.sessionIds.push(i),t.activeSessionId=i,c.switchToSession(i),this.persistContexts()}async hideProjectTerminalSessions(e){const s=this.projectContexts.get(e);if(s){for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}for(const t of s.sessionIds)h.cleanupListeners(t);c.clearAllSessions()}}async showProjectTerminalSessions(e){c.clearAllSessions();const{terminalPersistenceManager:s}=await p(async()=>{const{terminalPersistenceManager:n}=await import("./main-D1IISCsM.js").then(i=>i.p);return{terminalPersistenceManager:n}},__vite__mapDeps([0,1])),t=s.getAllActiveStreams();if(e.sessionIds.length>0)for(const n of e.sessionIds){const i=n.split("-"),a=i[i.length-1]||"1",o={id:n,name:`Terminal ${a}`,directory:e.projectPath,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};let r=!1,l=null;for(const u of t)if(u.projectId===e.projectId){const g=u.sessionId.split("-");if(g[g.length-1]===a){r=!0,l=u;break}}o.lines=[];const f=e.sessionCommandHistories.get(n);f&&(o.commandHistory=f);const I=m.getSession(n);if(I&&(f&&(I.commandHistory=f),o.directory=e.projectPath,(r||I.isExecuting)&&(c.setExecutingState(n,!0),l&&(I.isExecuting=!0,I.streamId=l.streamId,I.lastCommand=l.command))),c.addSession(o),!I||I.projectId!==e.projectId){const u=m.createSession(n,e.projectId,e.projectPath,e.projectPath);r&&l&&(u.isExecuting=!0,u.streamId=l.streamId,u.lastCommand=l.command)}else m.updateSession(n,{projectId:e.projectId,projectPath:e.projectPath,workingDirectory:e.projectPath})}else{const n=c.createNewSession(e.projectPath,e.projectPath,e.projectId);m.createSession(n,e.projectId,e.projectPath,e.projectPath),e.sessionIds.push(n),e.activeSessionId=n}e.activeSessionId&&e.sessionIds.includes(e.activeSessionId)?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId)),this.persistContexts()}async restoreProjectTerminalSessions(e){for(const s of e.sessionIds){const t=c.getSession(s),n=m.getSession(s);if(!t)if(n)this.restoreSessionToStore(n);else{const i=c.createNewSession(e.projectPath,e.projectPath,e.projectId),a=e.sessionIds.indexOf(s);a!==-1&&(e.sessionIds[a]=i),m.updateSession(i,{projectId:e.projectId,projectPath:e.projectPath}),e.activeSessionId===s&&(e.activeSessionId=i)}}e.activeSessionId?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId))}restoreSessionToStore(e,s){const t=e.projectPath||e.workingDirectory,n=e.id.split("-"),i=n[n.length-1]||"1",a={id:e.id,name:`Terminal ${i}`,directory:t,lines:[],commandHistory:e.commandHistory||[],isActive:!1,createdAt:e.createdAt||new Date,lastUsedAt:e.lastUsedAt||new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};if(s&&s.sessionOutputs.has(e.id)){const o=s.sessionOutputs.get(e.id);o&&(a.lines=o.map(r=>({content:r.content,type:r.type,timestamp:r.timestamp})))}c.addSession(a)}async saveCurrentProjectState(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!e)return;const s=c.activeSessionId;s&&(e.activeSessionId=s);for(const t of e.sessionIds){const n=c.getSession(t);if(n){const i=n.lines.map(o=>({content:o.content,type:o.type,timestamp:o.timestamp||new Date}));e.sessionOutputs.set(t,i);let a=0;for(const o of n.lines)(o.type==="output"||o.type==="error")&&a++;e.sessionOutputs.set(`${t}-metadata`,{outputCount:a}),n.commandHistory&&n.commandHistory.length>0&&e.sessionCommandHistories.set(t,n.commandHistory),m.updateSession(t,{commandHistory:n.commandHistory,workingDirectory:n.directory,projectId:this.currentProjectId,projectPath:e.projectPath})}}this.persistContexts()}saveAllProjectStates(){this.currentProjectId&&this.saveCurrentProjectState();for(const[e,s]of this.projectContexts.entries())if(e!==this.currentProjectId)for(const t of s.sessionIds){const n=m.getSession(t);n&&n.commandHistory&&s.sessionCommandHistories.set(t,n.commandHistory)}this.persistContexts()}addTerminalToCurrentProject(e,s){const t=e||this.currentProjectId;if(!t)return null;let n=this.projectContexts.get(t);if(!n&&s&&(n=this.getOrCreateProjectContext(t,s)),!n)return null;e&&e!==this.currentProjectId&&(this.currentProjectId=e);const i=c.createNewSession(n.projectPath,n.projectPath,t),a=c.getSession(i);return a&&(a.directory=n.projectPath),m.createSession(i,t,n.projectPath,n.projectPath),n.sessionIds.push(i),n.activeSessionId=i,this.persistContexts(),i}async removeTerminalFromCurrentProject(e){if(!this.currentProjectId)return!1;const s=this.projectContexts.get(this.currentProjectId);return!s||s.sessionIds.length<=1?!1:(s.sessionIds=s.sessionIds.filter(t=>t!==e),s.activeSessionId===e&&s.sessionIds.length>0&&(s.activeSessionId=s.sessionIds[0]),await c.closeSession(e),m.removeSession(e),this.persistContexts(),!0)}removeSessionFromContext(e){d.log("terminal",`🗑️ [projectManager] Removing session from context: ${e}`);for(const[s,t]of this.projectContexts.entries()){const n=t.sessionIds.indexOf(e);if(n!==-1){d.log("terminal",`🗑️ [projectManager] Found session in project: ${s}`),d.log("terminal",`🗑️ [projectManager] Sessions before: ${t.sessionIds.join(", ")}`),t.sessionIds.splice(n,1),t.sessionOutputs.delete(e),t.sessionOutputs.delete(`${e}-metadata`),t.sessionCommandHistories.delete(e),t.activeSessionId===e&&(t.activeSessionId=t.sessionIds[0]||null,d.log("terminal",`🗑️ [projectManager] Updated activeSessionId to: ${t.activeSessionId}`)),d.log("terminal",`🗑️ [projectManager] Sessions after: ${t.sessionIds.join(", ")}`),m.removeSession(e),this.persistContexts(),d.log("terminal","🗑️ [projectManager] Context persisted");return}}d.log("terminal","🗑️ [projectManager] Session not found in any project context")}getProjectSessions(e){return this.projectContexts.get(e)?.sessionIds||[]}hasRunningTerminals(e){const s=this.projectContexts.get(e);return s?s.sessionIds.some(t=>m.getSession(t)?.isExecuting||!1):!1}getTerminalCount(e){return this.projectContexts.get(e)?.sessionIds.length||0}persistContexts(){for(const[e,s]of this.projectContexts.entries())for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}}loadPersistedContexts(){}clearAll(){this.projectContexts.clear(),this.currentProjectId=null}initialize(){typeof window>"u"||this.setupCollaborativeListeners()}setupCollaborativeListeners(){p(async()=>{const{default:e}=await import("./main-D1IISCsM.js").then(s=>s.w);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{e.on("terminal:tab-created",s=>{if(d.log("terminal",`📥 Received terminal:tab-created: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already exists locally, skipping`);return}if(c.getSession(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already in store, skipping`);return}d.log("terminal",`➕ Adding remote terminal tab: ${s.sessionId}`);const i=s.sessionId.split("-"),a=i[i.length-1]||"1",o={id:s.sessionId,name:`Terminal ${a}`,directory:s.currentDirectory,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:this.currentProjectId,projectPath:t.projectPath};c.addSession(o),t.sessionIds.push(s.sessionId),m.createSession(s.sessionId,this.currentProjectId,t.projectPath,s.currentDirectory);const r=s.sessionId.match(/terminal-(\d+)/);r&&c.updateNextSessionId(parseInt(r[1],10)+1)}),e.on("terminal:tab-closed",s=>{if(d.log("terminal",`📥 Received terminal:tab-closed: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(!t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} not in our context, skipping`);return}if(!c.getSession(s.sessionId)){this.removeSessionFromContext(s.sessionId);return}d.log("terminal",`➖ Removing remote terminal tab: ${s.sessionId}`),this.removeSessionFromContext(s.sessionId),c.removeSessionFromStore(s.sessionId)}),d.log("terminal","✅ Terminal collaborative listeners registered")}),P(()=>{this.validateSessionsAfterReconnect()})}async validateSessionsAfterReconnect(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!(!e||e.sessionIds.length===0)){d.log("terminal","Validating terminal sessions after reconnect...");try{const s=await h.listProjectSessions(this.currentProjectId),t=new Set(s.map(i=>i.sessionId)),n=e.sessionIds.filter(i=>!t.has(i));if(n.length===0){d.log("terminal","All terminal sessions still alive after reconnect");return}d.log("terminal",`Found ${n.length} dead terminal session(s) after reconnect, cleaning up`);for(const i of n)this.removeSessionFromContext(i),c.removeSessionFromStore(i),h.cleanupListeners(i);e.sessionIds.length===0&&(d.log("terminal","All terminal sessions dead after reconnect, creating new session"),await this.createProjectTerminalSessions(this.currentProjectId,e.projectPath))}catch(s){d.error("terminal","Failed to validate terminal sessions after reconnect:",s)}}}getProjectIndicator(e){const s=this.projectContexts.get(e);if(!s)return{hasTerminals:!1,runningCount:0,totalCount:0};let t=0;const n=new Set;for(const o of s.sessionIds)if(m.getSession(o)?.isExecuting){const l=o.split("-"),f=l[l.length-1];n.add(f),t++}const i=S.getAllActiveStreams(),a=new Set;for(const o of i)if(!a.has(o.streamId)&&o.projectId===e){const r=o.sessionId.split("-"),l=r[r.length-1];n.has(l)||s.sessionIds.some(I=>{const u=I.split("-");return u[u.length-1]===l})&&(n.add(l),t++),a.add(o.streamId)}return{hasTerminals:s.sessionIds.length>0,runningCount:t,totalCount:s.sessionIds.length}}async checkAndRestoreActiveStreams(e){if(typeof window>"u")return;const s=this.projectContexts.get(e);if(!s)return;const{terminalPersistenceManager:t}=await p(async()=>{const{terminalPersistenceManager:a}=await import("./main-D1IISCsM.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-D1IISCsM.js").then(o=>o.i);return{backgroundTerminalService:a}},__vite__mapDeps([0,1])),i=t.getAllActiveStreams();for(const a of i)if(a.projectId===e){const o=a.sessionId.split("-"),r=o[o.length-1];for(const l of s.sessionIds){const f=l.split("-");if(f[f.length-1]===r&&m.getSession(l)){m.startExecution(l,a.command,a.streamId),c.setExecutingState(l,!0);break}}}}}const j=new v,T=Object.freeze(Object.defineProperty({__proto__:null,terminalProjectManager:j},Symbol.toStringTag,{value:"Module"})),A=Object.freeze(Object.defineProperty({__proto__:null,terminalPersistenceManager:S,terminalProjectManager:j,terminalService:h,terminalSessionManager:m},Symbol.toStringTag,{value:"Module"}));export{A as i,T as p};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-CtNvgvwE.js","assets/main-DmshCkFM.css"])))=>i.map(i=>d[i]);
2
+ import{t as c,a as h,d,b as m,c as S,_ as p,o as P}from"./main-CtNvgvwE.js";class v{projectContexts=new Map;currentProjectId=null;constructor(){}getOrCreateProjectContext(e,s){let t=this.projectContexts.get(e);return t||(t={projectId:e,projectPath:s,sessionIds:[],activeSessionId:null,lastActiveAt:new Date,sessionOutputs:new Map,sessionCommandHistories:new Map},this.projectContexts.set(e,t),this.persistContexts()),t}async switchToProject(e,s){this.currentProjectId&&this.currentProjectId!==e&&(await this.saveCurrentProjectState(),await this.hideProjectTerminalSessions(this.currentProjectId));const t=this.getOrCreateProjectContext(e,s);this.currentProjectId!==e&&c.clearAllSessions(),t.sessionIds.length===0?await this.createProjectTerminalSessions(e,s):await this.showProjectTerminalSessions(t),this.currentProjectId=e,t.lastActiveAt=new Date,this.persistContexts(),await this.checkAndRestoreActiveStreams(e)}async createProjectTerminalSessions(e,s){const t=this.getOrCreateProjectContext(e,s),n=await h.listProjectSessions(e);if(n.length>0){d.log("terminal",`Found ${n.length} existing PTY sessions for project ${e}`),n.sort((r,l)=>r.sessionId.localeCompare(l.sessionId));for(const r of n){const l=r.sessionId.split("-"),f=l[l.length-1]||"1",I={id:r.sessionId,name:`Terminal ${f}`,directory:r.cwd||s,lines:[],commandHistory:[],isActive:!1,createdAt:new Date(r.createdAt),lastUsedAt:new Date(r.lastActivityAt),shellType:"Unknown",terminalBuffer:void 0,projectId:e,projectPath:s};c.addSession(I),m.createSession(r.sessionId,e,s,r.cwd||s),t.sessionIds.push(r.sessionId);const u=r.sessionId.match(/terminal-(\d+)/);u&&c.updateNextSessionId(parseInt(u[1],10)+1)}let o=n[0].sessionId;if(typeof sessionStorage<"u")try{const r=sessionStorage.getItem(`terminal-active-session-${e}`);r&&t.sessionIds.includes(r)&&(o=r)}catch{}t.activeSessionId=o,c.switchToSession(t.activeSessionId),this.persistContexts();return}const i=c.createNewSession(s,s,e),a=c.getSession(i);a&&(a.directory=s),m.createSession(i,e,s,s),t.sessionIds.push(i),t.activeSessionId=i,c.switchToSession(i),this.persistContexts()}async hideProjectTerminalSessions(e){const s=this.projectContexts.get(e);if(s){for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}for(const t of s.sessionIds)h.cleanupListeners(t);c.clearAllSessions()}}async showProjectTerminalSessions(e){c.clearAllSessions();const{terminalPersistenceManager:s}=await p(async()=>{const{terminalPersistenceManager:n}=await import("./main-CtNvgvwE.js").then(i=>i.p);return{terminalPersistenceManager:n}},__vite__mapDeps([0,1])),t=s.getAllActiveStreams();if(e.sessionIds.length>0)for(const n of e.sessionIds){const i=n.split("-"),a=i[i.length-1]||"1",o={id:n,name:`Terminal ${a}`,directory:e.projectPath,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};let r=!1,l=null;for(const u of t)if(u.projectId===e.projectId){const g=u.sessionId.split("-");if(g[g.length-1]===a){r=!0,l=u;break}}o.lines=[];const f=e.sessionCommandHistories.get(n);f&&(o.commandHistory=f);const I=m.getSession(n);if(I&&(f&&(I.commandHistory=f),o.directory=e.projectPath,(r||I.isExecuting)&&(c.setExecutingState(n,!0),l&&(I.isExecuting=!0,I.streamId=l.streamId,I.lastCommand=l.command))),c.addSession(o),!I||I.projectId!==e.projectId){const u=m.createSession(n,e.projectId,e.projectPath,e.projectPath);r&&l&&(u.isExecuting=!0,u.streamId=l.streamId,u.lastCommand=l.command)}else m.updateSession(n,{projectId:e.projectId,projectPath:e.projectPath,workingDirectory:e.projectPath})}else{const n=c.createNewSession(e.projectPath,e.projectPath,e.projectId);m.createSession(n,e.projectId,e.projectPath,e.projectPath),e.sessionIds.push(n),e.activeSessionId=n}e.activeSessionId&&e.sessionIds.includes(e.activeSessionId)?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId)),this.persistContexts()}async restoreProjectTerminalSessions(e){for(const s of e.sessionIds){const t=c.getSession(s),n=m.getSession(s);if(!t)if(n)this.restoreSessionToStore(n);else{const i=c.createNewSession(e.projectPath,e.projectPath,e.projectId),a=e.sessionIds.indexOf(s);a!==-1&&(e.sessionIds[a]=i),m.updateSession(i,{projectId:e.projectId,projectPath:e.projectPath}),e.activeSessionId===s&&(e.activeSessionId=i)}}e.activeSessionId?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId))}restoreSessionToStore(e,s){const t=e.projectPath||e.workingDirectory,n=e.id.split("-"),i=n[n.length-1]||"1",a={id:e.id,name:`Terminal ${i}`,directory:t,lines:[],commandHistory:e.commandHistory||[],isActive:!1,createdAt:e.createdAt||new Date,lastUsedAt:e.lastUsedAt||new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};if(s&&s.sessionOutputs.has(e.id)){const o=s.sessionOutputs.get(e.id);o&&(a.lines=o.map(r=>({content:r.content,type:r.type,timestamp:r.timestamp})))}c.addSession(a)}async saveCurrentProjectState(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!e)return;const s=c.activeSessionId;s&&(e.activeSessionId=s);for(const t of e.sessionIds){const n=c.getSession(t);if(n){const i=n.lines.map(o=>({content:o.content,type:o.type,timestamp:o.timestamp||new Date}));e.sessionOutputs.set(t,i);let a=0;for(const o of n.lines)(o.type==="output"||o.type==="error")&&a++;e.sessionOutputs.set(`${t}-metadata`,{outputCount:a}),n.commandHistory&&n.commandHistory.length>0&&e.sessionCommandHistories.set(t,n.commandHistory),m.updateSession(t,{commandHistory:n.commandHistory,workingDirectory:n.directory,projectId:this.currentProjectId,projectPath:e.projectPath})}}this.persistContexts()}saveAllProjectStates(){this.currentProjectId&&this.saveCurrentProjectState();for(const[e,s]of this.projectContexts.entries())if(e!==this.currentProjectId)for(const t of s.sessionIds){const n=m.getSession(t);n&&n.commandHistory&&s.sessionCommandHistories.set(t,n.commandHistory)}this.persistContexts()}addTerminalToCurrentProject(e,s){const t=e||this.currentProjectId;if(!t)return null;let n=this.projectContexts.get(t);if(!n&&s&&(n=this.getOrCreateProjectContext(t,s)),!n)return null;e&&e!==this.currentProjectId&&(this.currentProjectId=e);const i=c.createNewSession(n.projectPath,n.projectPath,t),a=c.getSession(i);return a&&(a.directory=n.projectPath),m.createSession(i,t,n.projectPath,n.projectPath),n.sessionIds.push(i),n.activeSessionId=i,this.persistContexts(),i}async removeTerminalFromCurrentProject(e){if(!this.currentProjectId)return!1;const s=this.projectContexts.get(this.currentProjectId);return!s||s.sessionIds.length<=1?!1:(s.sessionIds=s.sessionIds.filter(t=>t!==e),s.activeSessionId===e&&s.sessionIds.length>0&&(s.activeSessionId=s.sessionIds[0]),await c.closeSession(e),m.removeSession(e),this.persistContexts(),!0)}removeSessionFromContext(e){d.log("terminal",`🗑️ [projectManager] Removing session from context: ${e}`);for(const[s,t]of this.projectContexts.entries()){const n=t.sessionIds.indexOf(e);if(n!==-1){d.log("terminal",`🗑️ [projectManager] Found session in project: ${s}`),d.log("terminal",`🗑️ [projectManager] Sessions before: ${t.sessionIds.join(", ")}`),t.sessionIds.splice(n,1),t.sessionOutputs.delete(e),t.sessionOutputs.delete(`${e}-metadata`),t.sessionCommandHistories.delete(e),t.activeSessionId===e&&(t.activeSessionId=t.sessionIds[0]||null,d.log("terminal",`🗑️ [projectManager] Updated activeSessionId to: ${t.activeSessionId}`)),d.log("terminal",`🗑️ [projectManager] Sessions after: ${t.sessionIds.join(", ")}`),m.removeSession(e),this.persistContexts(),d.log("terminal","🗑️ [projectManager] Context persisted");return}}d.log("terminal","🗑️ [projectManager] Session not found in any project context")}getProjectSessions(e){return this.projectContexts.get(e)?.sessionIds||[]}hasRunningTerminals(e){const s=this.projectContexts.get(e);return s?s.sessionIds.some(t=>m.getSession(t)?.isExecuting||!1):!1}getTerminalCount(e){return this.projectContexts.get(e)?.sessionIds.length||0}persistContexts(){for(const[e,s]of this.projectContexts.entries())for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}}loadPersistedContexts(){}clearAll(){this.projectContexts.clear(),this.currentProjectId=null}initialize(){typeof window>"u"||this.setupCollaborativeListeners()}setupCollaborativeListeners(){p(async()=>{const{default:e}=await import("./main-CtNvgvwE.js").then(s=>s.w);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{e.on("terminal:tab-created",s=>{if(d.log("terminal",`📥 Received terminal:tab-created: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already exists locally, skipping`);return}if(c.getSession(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already in store, skipping`);return}d.log("terminal",`➕ Adding remote terminal tab: ${s.sessionId}`);const i=s.sessionId.split("-"),a=i[i.length-1]||"1",o={id:s.sessionId,name:`Terminal ${a}`,directory:s.currentDirectory,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:this.currentProjectId,projectPath:t.projectPath};c.addSession(o),t.sessionIds.push(s.sessionId),m.createSession(s.sessionId,this.currentProjectId,t.projectPath,s.currentDirectory);const r=s.sessionId.match(/terminal-(\d+)/);r&&c.updateNextSessionId(parseInt(r[1],10)+1)}),e.on("terminal:tab-closed",s=>{if(d.log("terminal",`📥 Received terminal:tab-closed: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(!t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} not in our context, skipping`);return}if(!c.getSession(s.sessionId)){this.removeSessionFromContext(s.sessionId);return}d.log("terminal",`➖ Removing remote terminal tab: ${s.sessionId}`),this.removeSessionFromContext(s.sessionId),c.removeSessionFromStore(s.sessionId)}),d.log("terminal","✅ Terminal collaborative listeners registered")}),P(()=>{this.validateSessionsAfterReconnect()})}async validateSessionsAfterReconnect(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!(!e||e.sessionIds.length===0)){d.log("terminal","Validating terminal sessions after reconnect...");try{const s=await h.listProjectSessions(this.currentProjectId),t=new Set(s.map(i=>i.sessionId)),n=e.sessionIds.filter(i=>!t.has(i));if(n.length===0){d.log("terminal","All terminal sessions still alive after reconnect");return}d.log("terminal",`Found ${n.length} dead terminal session(s) after reconnect, cleaning up`);for(const i of n)this.removeSessionFromContext(i),c.removeSessionFromStore(i),h.cleanupListeners(i);e.sessionIds.length===0&&(d.log("terminal","All terminal sessions dead after reconnect, creating new session"),await this.createProjectTerminalSessions(this.currentProjectId,e.projectPath))}catch(s){d.error("terminal","Failed to validate terminal sessions after reconnect:",s)}}}getProjectIndicator(e){const s=this.projectContexts.get(e);if(!s)return{hasTerminals:!1,runningCount:0,totalCount:0};let t=0;const n=new Set;for(const o of s.sessionIds)if(m.getSession(o)?.isExecuting){const l=o.split("-"),f=l[l.length-1];n.add(f),t++}const i=S.getAllActiveStreams(),a=new Set;for(const o of i)if(!a.has(o.streamId)&&o.projectId===e){const r=o.sessionId.split("-"),l=r[r.length-1];n.has(l)||s.sessionIds.some(I=>{const u=I.split("-");return u[u.length-1]===l})&&(n.add(l),t++),a.add(o.streamId)}return{hasTerminals:s.sessionIds.length>0,runningCount:t,totalCount:s.sessionIds.length}}async checkAndRestoreActiveStreams(e){if(typeof window>"u")return;const s=this.projectContexts.get(e);if(!s)return;const{terminalPersistenceManager:t}=await p(async()=>{const{terminalPersistenceManager:a}=await import("./main-CtNvgvwE.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-CtNvgvwE.js").then(o=>o.i);return{backgroundTerminalService:a}},__vite__mapDeps([0,1])),i=t.getAllActiveStreams();for(const a of i)if(a.projectId===e){const o=a.sessionId.split("-"),r=o[o.length-1];for(const l of s.sessionIds){const f=l.split("-");if(f[f.length-1]===r&&m.getSession(l)){m.startExecution(l,a.command,a.streamId),c.setExecutingState(l,!0);break}}}}}const j=new v,T=Object.freeze(Object.defineProperty({__proto__:null,terminalProjectManager:j},Symbol.toStringTag,{value:"Module"})),A=Object.freeze(Object.defineProperty({__proto__:null,terminalPersistenceManager:S,terminalProjectManager:j,terminalService:h,terminalSessionManager:m},Symbol.toStringTag,{value:"Module"}));export{A as i,T as p};