@myrialabs/clopen 0.3.4 → 0.3.6

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.
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Static curl binary management.
3
+ *
4
+ * Some install scripts clopen runs (notably OpenCode's) invoke `curl`
5
+ * internally. When the host system lacks curl and cannot install it
6
+ * non-interactively (e.g. Linux without root), clopen falls back to
7
+ * downloading a verified static curl binary from the stunnel/static-curl
8
+ * project into ~/.clopen/bin/curl and prepends that directory to PATH
9
+ * when spawning the install subprocess.
10
+ *
11
+ * Supply-chain hardening:
12
+ * - Version + SHA256 for each arch is pinned in source. If the remote
13
+ * asset ever changes the hash mismatch aborts the download and the
14
+ * cached/final file is never touched.
15
+ * - stunnel/static-curl is a reproducible-build project maintained by
16
+ * the stunnel team. Release: https://github.com/stunnel/static-curl
17
+ */
18
+
19
+ import { existsSync, readdirSync, mkdirSync, chmodSync, renameSync } from 'node:fs';
20
+ import { join, dirname } from 'node:path';
21
+ import { XzReadableStream } from 'xz-decompress';
22
+ import { debug } from '$shared/utils/logger';
23
+ import { getClopenDir } from '$backend/utils/paths';
24
+ import { resolveBinary } from '$backend/utils/cli';
25
+
26
+ export const STATIC_CURL_VERSION = '8.19.0';
27
+
28
+ export interface StaticCurlAsset {
29
+ /** Key like "linux-x86_64-glibc". */
30
+ archKey: string;
31
+ url: string;
32
+ sha256: string;
33
+ version: string;
34
+ }
35
+
36
+ function makeAsset(archKey: string, sha256: string): StaticCurlAsset {
37
+ return {
38
+ archKey,
39
+ url: `https://github.com/stunnel/static-curl/releases/download/${STATIC_CURL_VERSION}/curl-${archKey}-${STATIC_CURL_VERSION}.tar.xz`,
40
+ sha256,
41
+ version: STATIC_CURL_VERSION
42
+ };
43
+ }
44
+
45
+ // Hashes verified by downloading each archive and computing shasum -a 256
46
+ // against stunnel/static-curl 8.19.0 release on 2026-04-23.
47
+ const PINNED_ASSETS: Record<string, StaticCurlAsset> = {
48
+ 'linux-x86_64-glibc': makeAsset('linux-x86_64-glibc', '9c70e3ac08a6d8e211a891fe2fc871a9cd3314c291adb5bb1a38e7355ce98ff7'),
49
+ 'linux-x86_64-musl': makeAsset('linux-x86_64-musl', '477cf25c53e438b5293610faadf4b932009973c08e8be3a283afa25189aa85da'),
50
+ 'linux-aarch64-glibc': makeAsset('linux-aarch64-glibc', '46873008eae6b7eb586aa56ce8787bdb8c1eccb52faf7055b32b6470c1b84cd6'),
51
+ 'linux-aarch64-musl': makeAsset('linux-aarch64-musl', '592b12257e97de01f73f681800b6f7ba43347e5880100cca4d33c6fec3eb286b'),
52
+ 'linux-armv7-glibc': makeAsset('linux-armv7-glibc', 'fae4fd7f25c8a8744f53d5b5c8cefe3bed924d9e028165eac4fef8bd6b77e51b'),
53
+ 'linux-armv7-musl': makeAsset('linux-armv7-musl', 'eb0d2ab30f849bda6c56aa098cf7512720721476a4e4449515c91d117c1454e1')
54
+ };
55
+
56
+ function detectLibc(): 'glibc' | 'musl' {
57
+ // Alpine ships a sentinel file; other musl-based distros expose the
58
+ // musl dynamic loader at well-known locations.
59
+ if (existsSync('/etc/alpine-release')) return 'musl';
60
+ for (const dir of ['/lib', '/usr/lib', '/lib64', '/usr/lib64']) {
61
+ try {
62
+ if (readdirSync(dir).some((f) => f.startsWith('ld-musl-'))) return 'musl';
63
+ } catch {
64
+ // Directory missing — not fatal, try the next.
65
+ }
66
+ }
67
+ return 'glibc';
68
+ }
69
+
70
+ function detectArchKey(): string | null {
71
+ if (process.platform !== 'linux') return null;
72
+ const libc = detectLibc();
73
+ let arch: string;
74
+ switch (process.arch) {
75
+ case 'x64': arch = 'x86_64'; break;
76
+ case 'arm64': arch = 'aarch64'; break;
77
+ case 'arm': arch = 'armv7'; break;
78
+ default: return null;
79
+ }
80
+ return `linux-${arch}-${libc}`;
81
+ }
82
+
83
+ /**
84
+ * Resolve the pinned asset metadata for the current platform/arch, or
85
+ * null when this platform is not covered (macOS, Windows, exotic arches).
86
+ */
87
+ export function resolveStaticCurlAsset(): StaticCurlAsset | null {
88
+ const key = detectArchKey();
89
+ if (!key) return null;
90
+ return PINNED_ASSETS[key] ?? null;
91
+ }
92
+
93
+ export function getStaticCurlPath(): string {
94
+ return join(getClopenDir(), 'bin', 'curl');
95
+ }
96
+
97
+ export function hasCachedStaticCurl(): boolean {
98
+ return existsSync(getStaticCurlPath());
99
+ }
100
+
101
+ function sha256(bytes: Uint8Array): string {
102
+ const hasher = new Bun.CryptoHasher('sha256');
103
+ hasher.update(bytes);
104
+ return hasher.digest('hex');
105
+ }
106
+
107
+ function parseTarOctal(bytes: Uint8Array): number {
108
+ let end = bytes.length;
109
+ for (let i = 0; i < bytes.length; i++) {
110
+ if (bytes[i] === 0 || bytes[i] === 0x20) {
111
+ end = i;
112
+ break;
113
+ }
114
+ }
115
+ const str = new TextDecoder().decode(bytes.subarray(0, end)).trim();
116
+ return str === '' ? 0 : parseInt(str, 8);
117
+ }
118
+
119
+ /**
120
+ * Minimal POSIX tar reader: walks header blocks and returns the first
121
+ * regular file whose name matches. Sufficient for static-curl archives
122
+ * which contain `curl` at the root with a short name.
123
+ */
124
+ function findFileInTar(tarBytes: Uint8Array, filename: string): Uint8Array | null {
125
+ const decoder = new TextDecoder();
126
+ let offset = 0;
127
+ while (offset + 512 <= tarBytes.length) {
128
+ const header = tarBytes.subarray(offset, offset + 512);
129
+ let allZero = true;
130
+ for (let i = 0; i < 512; i++) {
131
+ if (header[i] !== 0) { allZero = false; break; }
132
+ }
133
+ if (allZero) return null;
134
+
135
+ const nameBytes = header.subarray(0, 100);
136
+ const nameEnd = nameBytes.indexOf(0);
137
+ const name = decoder.decode(nameEnd >= 0 ? nameBytes.subarray(0, nameEnd) : nameBytes);
138
+ const size = parseTarOctal(header.subarray(124, 136));
139
+ const typeflag = header[156];
140
+ const isRegularFile = typeflag === 0 || typeflag === 0x30; // '\0' or '0'
141
+
142
+ offset += 512;
143
+ if (isRegularFile && name === filename) {
144
+ return tarBytes.subarray(offset, offset + size);
145
+ }
146
+ offset += Math.ceil(size / 512) * 512;
147
+ }
148
+ return null;
149
+ }
150
+
151
+ async function decompressXz(xzBytes: Uint8Array): Promise<Uint8Array> {
152
+ const input = new ReadableStream<Uint8Array>({
153
+ start(controller) {
154
+ controller.enqueue(xzBytes);
155
+ controller.close();
156
+ }
157
+ });
158
+ const decompressed = new Response(new XzReadableStream(input));
159
+ return new Uint8Array(await decompressed.arrayBuffer());
160
+ }
161
+
162
+ export type CurlProgressPhase = 'cached' | 'fetching' | 'verifying' | 'extracting' | 'done';
163
+
164
+ export interface CurlProgressEvent {
165
+ phase: CurlProgressPhase;
166
+ message: string;
167
+ }
168
+
169
+ /**
170
+ * Ensure curl is available for a subprocess. Returns the directory that
171
+ * should be prepended to PATH (null when the system already has curl and
172
+ * no action is required).
173
+ *
174
+ * Throws if the platform has no pinned static curl, if the download
175
+ * fails, or if SHA256 verification fails. Never leaves a partially
176
+ * extracted file at the final path.
177
+ */
178
+ export async function ensureCurlAvailable(
179
+ onProgress: (event: CurlProgressEvent) => void
180
+ ): Promise<string | null> {
181
+ if (resolveBinary('curl')) return null;
182
+
183
+ const asset = resolveStaticCurlAsset();
184
+ if (!asset) {
185
+ throw new Error(`No static curl binary available for ${process.platform}/${process.arch}`);
186
+ }
187
+
188
+ const finalPath = getStaticCurlPath();
189
+ const binDir = dirname(finalPath);
190
+
191
+ if (hasCachedStaticCurl()) {
192
+ onProgress({ phase: 'cached', message: `using cached curl at ${finalPath}` });
193
+ return binDir;
194
+ }
195
+
196
+ mkdirSync(binDir, { recursive: true });
197
+
198
+ onProgress({ phase: 'fetching', message: `downloading ${asset.url}` });
199
+ const response = await fetch(asset.url, { redirect: 'follow' });
200
+ if (!response.ok) {
201
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
202
+ }
203
+ const archiveBytes = new Uint8Array(await response.arrayBuffer());
204
+
205
+ onProgress({ phase: 'verifying', message: `verifying SHA256 ${asset.sha256}` });
206
+ const actualSha = sha256(archiveBytes);
207
+ if (actualSha !== asset.sha256) {
208
+ throw new Error(`SHA256 mismatch: expected ${asset.sha256}, got ${actualSha}`);
209
+ }
210
+
211
+ onProgress({ phase: 'extracting', message: `extracting curl to ${binDir}` });
212
+ const tarBytes = await decompressXz(archiveBytes);
213
+ const curlBytes = findFileInTar(tarBytes, 'curl');
214
+ if (!curlBytes) {
215
+ throw new Error('curl binary not found in archive');
216
+ }
217
+
218
+ // Write via a sibling tmp path then rename, so finalPath is always
219
+ // either absent or a complete, valid binary.
220
+ const tmpPath = `${finalPath}.tmp-${process.pid}`;
221
+ await Bun.write(tmpPath, curlBytes);
222
+ chmodSync(tmpPath, 0o755);
223
+ renameSync(tmpPath, finalPath);
224
+
225
+ onProgress({ phase: 'done', message: `curl installed at ${finalPath}` });
226
+ debug.log('path', `static-curl: installed ${asset.archKey} v${asset.version} at ${finalPath}`);
227
+ return binDir;
228
+ }
@@ -66,7 +66,7 @@ export const wsRouter = createRouter()
66
66
  // AI Engine Management
67
67
  .merge(engineRouter)
68
68
 
69
- // System Tools (install Git, Claude Code, OpenCode, Chrome binaries)
69
+ // System Tools (install Git, Claude Code, OpenCode, Chromium binaries)
70
70
  .merge(systemToolsRouter);
71
71
 
72
72
  // Export API type for frontend type-safe access
@@ -23,7 +23,7 @@ const TOOL_UNION = t.Union([
23
23
  t.Literal('git'),
24
24
  t.Literal('claude'),
25
25
  t.Literal('opencode'),
26
- t.Literal('chrome')
26
+ t.Literal('chromium')
27
27
  ]);
28
28
 
29
29
  const STATUS_UNION = t.Union([
@@ -2,7 +2,7 @@
2
2
  * System Tool Status Handlers
3
3
  *
4
4
  * Reports installation status for each managed tool (git, claude,
5
- * opencode, chrome). The corresponding recipe is bundled so the
5
+ * opencode, chromium). The corresponding recipe is bundled so the
6
6
  * frontend can render the install button state and manual fallback
7
7
  * without a second round-trip.
8
8
  */
@@ -17,7 +17,7 @@ const TOOL_UNION = t.Union([
17
17
  t.Literal('git'),
18
18
  t.Literal('claude'),
19
19
  t.Literal('opencode'),
20
- t.Literal('chrome')
20
+ t.Literal('chromium')
21
21
  ]);
22
22
 
23
23
  const RECIPE_SCHEMA = t.Object({
@@ -30,6 +30,12 @@ const RECIPE_SCHEMA = t.Object({
30
30
  label: t.String(),
31
31
  command: t.String(),
32
32
  docs: t.Optional(t.String())
33
+ })),
34
+ pendingCurlDownload: t.Optional(t.Object({
35
+ version: t.String(),
36
+ url: t.String(),
37
+ sha256: t.String(),
38
+ archKey: t.String()
33
39
  }))
34
40
  });
35
41
 
@@ -60,14 +66,15 @@ const ACTIVE_SESSION_SCHEMA = t.Union([
60
66
  })
61
67
  ]);
62
68
 
63
- function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chrome', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
69
+ function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'chromium', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
64
70
  return {
65
71
  tool,
66
72
  autoInstallable: recipe.autoInstallable,
67
73
  unavailableReason: recipe.unavailableReason,
68
74
  displayCommand: recipe.displayCommand,
69
75
  missingPrereqs: recipe.missingPrereqs,
70
- manualInstructions: recipe.manualInstructions
76
+ manualInstructions: recipe.manualInstructions,
77
+ pendingCurlDownload: recipe.pendingCurlDownload
71
78
  };
72
79
  }
73
80
 
@@ -102,7 +109,7 @@ export const systemToolsStatusHandler = createRouter()
102
109
  })
103
110
  }, async () => {
104
111
  debug.log('path', 'system-tools:status-all');
105
- const ids = ['git', 'claude', 'opencode', 'chrome'] as const;
112
+ const ids = ['git', 'claude', 'opencode', 'chromium'] as const;
106
113
  const tools = await Promise.all(ids.map(async (id) => {
107
114
  const [status, recipe] = await Promise.all([
108
115
  getToolStatus(id),
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-Be2TrEVr.js","assets/main-C184xHqk.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-Be2TrEVr.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-Be2TrEVr.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-Be2TrEVr.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-Be2TrEVr.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-Be2TrEVr.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-cQx6vfxB.js","assets/main-B3tMwjjU.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-cQx6vfxB.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-cQx6vfxB.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-cQx6vfxB.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-cQx6vfxB.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-cQx6vfxB.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};