@openchamber/web 1.13.3 → 1.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/bin/cli-output.js +0 -7
  2. package/bin/cli.js +132 -5548
  3. package/bin/cli.test.js +674 -0
  4. package/bin/lib/DOCUMENTATION.md +121 -0
  5. package/bin/lib/cli-args.js +726 -0
  6. package/bin/lib/cli-errors.js +18 -0
  7. package/bin/lib/cli-executables.js +54 -0
  8. package/bin/lib/cli-http.js +215 -0
  9. package/bin/lib/cli-lifecycle.js +421 -0
  10. package/bin/lib/cli-log-files.js +93 -0
  11. package/bin/lib/cli-network.js +153 -0
  12. package/bin/lib/cli-paths.js +111 -0
  13. package/bin/lib/cli-ports.js +51 -0
  14. package/bin/lib/cli-process.js +292 -0
  15. package/bin/lib/cli-startup.js +370 -0
  16. package/bin/lib/cli-tunnel-capabilities.js +9 -0
  17. package/bin/lib/cli-tunnel-profiles.js +366 -0
  18. package/bin/lib/cli-tunnel-utils.js +300 -0
  19. package/bin/lib/commands-connect-url.js +173 -0
  20. package/bin/lib/commands-lifecycle.js +396 -0
  21. package/bin/lib/commands-logs.js +110 -0
  22. package/bin/lib/commands-serve.js +396 -0
  23. package/bin/lib/commands-startup.js +64 -0
  24. package/bin/lib/commands-status.js +114 -0
  25. package/bin/lib/commands-tunnel.js +1757 -0
  26. package/bin/lib/commands-update.js +141 -0
  27. package/dist/assets/{DiagramView-BmHROYsX.js → DiagramView-BAoYIAGR.js} +1 -1
  28. package/dist/assets/{MarkdownRendererImpl-DiJE-v5Q.js → MarkdownRendererImpl-B0NE4mIY.js} +3 -3
  29. package/dist/assets/MultiRunWindow-BT4kt6aB.js +1 -0
  30. package/dist/assets/NewWorktreeDialog-Bx-zQyBp.js +167 -0
  31. package/dist/assets/{OnboardingScreen-DpBF8dKJ.js → OnboardingScreen-CbJOPUxm.js} +1 -1
  32. package/dist/assets/{SessionSwitcherDropdown-1xaHUxPK.js → SessionSwitcherDropdown-BbUzUNEi.js} +1 -1
  33. package/dist/assets/{SettingsWindow-ChwLyQAe.js → SettingsWindow-CSb8eo8p.js} +1 -1
  34. package/dist/assets/{TerminalView-DGEBNuAp.js → TerminalView-ME5MOz7S.js} +1 -1
  35. package/dist/assets/es-Bk-yR0w-.js +15 -0
  36. package/dist/assets/fr-f1ibV7QU.js +13 -0
  37. package/dist/assets/index-B82A6jBD.css +1 -0
  38. package/dist/assets/index-BsXkdBYx.js +3 -0
  39. package/dist/assets/ja-D9mS3zWP.js +15 -0
  40. package/dist/assets/ko-Cpl1IA3D.js +15 -0
  41. package/dist/assets/{main-fm_8J7Lk.js → main-D6eC2bnV.js} +2 -2
  42. package/dist/assets/main-fsOGbLGZ.js +214 -0
  43. package/dist/assets/miniChat-DKGU29GZ.js +2 -0
  44. package/dist/assets/mobile-YHQHMYWC.js +2 -0
  45. package/dist/assets/pl-CYke_fxL.js +15 -0
  46. package/dist/assets/pt-BR-Clb6Z8up.js +15 -0
  47. package/dist/assets/renderElectronMiniChatApp-3vxeddJO.js +2 -0
  48. package/dist/assets/{renderMobileApp-6s0G1iIJ.js → renderMobileApp-BrvLHYCY.js} +5 -5
  49. package/dist/assets/uk-CXn8cxXa.js +15 -0
  50. package/dist/assets/{useAppFontEffects-CV5C5O0r.js → useAppFontEffects-b7bqtGFf.js} +124 -119
  51. package/dist/assets/{vendor-.bun-CC_Xso_s.js → vendor-.bun-By2L9XvG.js} +1 -1
  52. package/dist/assets/zh-CN-BRwwlEdG.js +15 -0
  53. package/dist/assets/zh-TW-D5pg5Z8l.js +15 -0
  54. package/dist/index.html +4 -4
  55. package/dist/mini-chat.html +4 -4
  56. package/dist/mobile.html +4 -4
  57. package/package.json +1 -1
  58. package/server/lib/cloudflare-tunnel.js +2 -2
  59. package/server/lib/event-stream/global-hub.js +1 -1
  60. package/server/lib/event-stream/index.js +0 -12
  61. package/server/lib/event-stream/runtime.js +1 -1
  62. package/server/lib/git/service.js +18 -0
  63. package/server/lib/git/service.test.js +48 -0
  64. package/server/lib/notifications/index.js +1 -4
  65. package/server/lib/opencode/agents.js +0 -6
  66. package/server/lib/opencode/commands.js +0 -5
  67. package/server/lib/opencode/config-entity-routes.js +39 -21
  68. package/server/lib/opencode/feature-routes-runtime.js +27 -62
  69. package/server/lib/opencode/lifecycle.js +13 -1
  70. package/server/lib/opencode/npm-registry.js +3 -3
  71. package/server/lib/opencode/proxy.js +3 -3
  72. package/server/lib/opencode/shared.js +0 -6
  73. package/server/lib/opencode/skills.js +0 -2
  74. package/server/lib/opencode/snippets.js +0 -2
  75. package/server/lib/package-manager.js +5 -5
  76. package/server/lib/projects/project-config.js +0 -8
  77. package/server/lib/quota/DOCUMENTATION.md +3 -1
  78. package/server/lib/quota/providers/claude.js +1 -1
  79. package/server/lib/quota/providers/codex.js +1 -1
  80. package/server/lib/quota/providers/copilot.js +1 -1
  81. package/server/lib/quota/providers/cursor.js +1 -1
  82. package/server/lib/quota/providers/google/auth.js +2 -2
  83. package/server/lib/quota/providers/google/index.js +0 -27
  84. package/server/lib/quota/providers/google/transforms.js +1 -1
  85. package/server/lib/quota/providers/index.js +1 -1
  86. package/server/lib/quota/providers/kimi.js +1 -1
  87. package/server/lib/quota/providers/minimax-cn-coding-plan.js +1 -1
  88. package/server/lib/quota/providers/minimax-coding-plan.js +1 -1
  89. package/server/lib/quota/providers/nanogpt.js +1 -1
  90. package/server/lib/quota/providers/ollama-cloud.js +1 -1
  91. package/server/lib/quota/providers/openai.js +4 -4
  92. package/server/lib/quota/providers/openrouter.js +1 -1
  93. package/server/lib/quota/providers/wafer.js +1 -1
  94. package/server/lib/quota/providers/zai.js +1 -1
  95. package/server/lib/quota/providers/zhipuai-coding-plan.js +1 -1
  96. package/server/lib/skills-catalog/cache.js +0 -4
  97. package/server/lib/skills-catalog/clawdhub/api.js +0 -32
  98. package/server/lib/skills-catalog/clawdhub/scan.js +0 -52
  99. package/server/lib/skills-catalog/curated-sources.js +1 -1
  100. package/server/lib/skills-catalog/source.js +5 -0
  101. package/server/lib/terminal/runtime.js +11 -9
  102. package/server/lib/text/summarization.js +1 -1
  103. package/server/lib/tunnels/providers/ngrok.js +1 -1
  104. package/server/lib/tunnels/types.js +2 -2
  105. package/dist/assets/MultiRunWindow-yZoCT7F7.js +0 -1
  106. package/dist/assets/NewWorktreeDialog-CTMiE7Xd.js +0 -167
  107. package/dist/assets/es-CTE-E8we.js +0 -15
  108. package/dist/assets/fr-TVkZpyEo.js +0 -13
  109. package/dist/assets/index-B4pCDMbq.css +0 -1
  110. package/dist/assets/index-D9uMvTQF.js +0 -3
  111. package/dist/assets/ko-D_UCJIIL.js +0 -15
  112. package/dist/assets/main-eAd3a6tx.js +0 -214
  113. package/dist/assets/miniChat-Bbjg31IC.js +0 -2
  114. package/dist/assets/mobile-B3_j_DsB.js +0 -2
  115. package/dist/assets/pl-nDEkk-GZ.js +0 -15
  116. package/dist/assets/pt-BR-B_g2RcgU.js +0 -15
  117. package/dist/assets/renderElectronMiniChatApp-CB13zs6N.js +0 -2
  118. package/dist/assets/uk-CWLhnPGW.js +0 -15
  119. package/dist/assets/zh-CN-BFxe1b5m.js +0 -15
  120. package/dist/assets/zh-TW-n-d-xbGV.js +0 -15
  121. package/server/lib/opencode/index.js +0 -95
  122. package/server/lib/quota/providers/interface.js +0 -55
  123. package/server/lib/skills-catalog/clawdhub/index.js +0 -30
  124. package/server/lib/skills-catalog/index.js +0 -42
  125. package/server/lib/terminal/index.js +0 -31
@@ -0,0 +1,18 @@
1
+ const EXIT_CODE = {
2
+ SUCCESS: 0,
3
+ GENERAL_ERROR: 1,
4
+ USAGE_ERROR: 2,
5
+ MISSING_DEPENDENCY: 3,
6
+ AUTH_CONFIG_ERROR: 4,
7
+ NETWORK_RUNTIME_ERROR: 5,
8
+ };
9
+
10
+ class TunnelCliError extends Error {
11
+ constructor(message, exitCode = EXIT_CODE.GENERAL_ERROR) {
12
+ super(message);
13
+ this.name = 'TunnelCliError';
14
+ this.exitCode = exitCode;
15
+ }
16
+ }
17
+
18
+ export { EXIT_CODE, TunnelCliError };
@@ -0,0 +1,54 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ const WINDOWS_EXTENSIONS = process.platform === 'win32'
5
+ ? (process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM')
6
+ .split(';')
7
+ .map((ext) => ext.trim().toLowerCase())
8
+ .filter(Boolean)
9
+ .map((ext) => (ext.startsWith('.') ? ext : `.${ext}`))
10
+ : [''];
11
+
12
+ function isExecutable(filePath) {
13
+ try {
14
+ const stats = fs.statSync(filePath);
15
+ if (!stats.isFile()) {
16
+ return false;
17
+ }
18
+ if (process.platform === 'win32') {
19
+ return true;
20
+ }
21
+ fs.accessSync(filePath, fs.constants.X_OK);
22
+ return true;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ function resolveExplicitBinary(candidate) {
29
+ if (!candidate) {
30
+ return null;
31
+ }
32
+ if (candidate.includes(path.sep) || path.isAbsolute(candidate)) {
33
+ const resolved = path.isAbsolute(candidate) ? candidate : path.resolve(candidate);
34
+ return isExecutable(resolved) ? resolved : null;
35
+ }
36
+ return null;
37
+ }
38
+
39
+ function searchPathFor(command) {
40
+ const pathValue = process.env.PATH || '';
41
+ const segments = pathValue.split(path.delimiter).filter(Boolean);
42
+ for (const dir of segments) {
43
+ for (const ext of WINDOWS_EXTENSIONS) {
44
+ const fileName = process.platform === 'win32' ? `${command}${ext}` : command;
45
+ const candidate = path.join(dir, fileName);
46
+ if (isExecutable(candidate)) {
47
+ return candidate;
48
+ }
49
+ }
50
+ }
51
+ return null;
52
+ }
53
+
54
+ export { resolveExplicitBinary, searchPathFor };
@@ -0,0 +1,215 @@
1
+ import { buildLocalUrl } from './cli-network.js';
2
+ import { getInstanceFilePath, readInstanceOptions } from './cli-process.js';
3
+
4
+ const UI_SESSION_COOKIE_NAME = 'oc_ui_session';
5
+
6
+ function extractUiSessionCookie(response) {
7
+ const setCookie = response?.headers?.get?.('set-cookie');
8
+ if (typeof setCookie !== 'string' || setCookie.length === 0) {
9
+ return null;
10
+ }
11
+ const match = setCookie.match(new RegExp(`(?:^|,\\s*)(${UI_SESSION_COOKIE_NAME}=[^;]+)`));
12
+ return match?.[1] || null;
13
+ }
14
+
15
+ async function resolveUiPasswordForPort(port, options = {}) {
16
+ if (typeof options.uiPassword === 'string' && options.uiPassword.trim().length > 0) {
17
+ return options.uiPassword;
18
+ }
19
+ const instanceOptions = readInstanceOptions(await getInstanceFilePath(port));
20
+ return typeof instanceOptions?.uiPassword === 'string' && instanceOptions.uiPassword.trim().length > 0
21
+ ? instanceOptions.uiPassword
22
+ : null;
23
+ }
24
+
25
+ async function createUiSessionCookie(port, password, timeoutMs) {
26
+ if (typeof password !== 'string' || password.length === 0) {
27
+ return null;
28
+ }
29
+ const controller = new AbortController();
30
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
31
+ try {
32
+ const response = await fetch(buildLocalUrl(port, '/auth/session'), {
33
+ method: 'POST',
34
+ headers: {
35
+ Accept: 'application/json',
36
+ 'Content-Type': 'application/json',
37
+ },
38
+ body: JSON.stringify({ password }),
39
+ signal: controller.signal,
40
+ });
41
+ if (!response.ok) {
42
+ return null;
43
+ }
44
+ return extractUiSessionCookie(response);
45
+ } catch {
46
+ return null;
47
+ } finally {
48
+ clearTimeout(timeout);
49
+ }
50
+ }
51
+
52
+ async function requestServerShutdown(port, hostOverride) {
53
+ if (!Number.isFinite(port) || port <= 0) return false;
54
+ const controller = new AbortController();
55
+ const timeout = setTimeout(() => controller.abort(), 1500);
56
+ try {
57
+ const resp = await fetch(buildLocalUrl(port, '/api/system/shutdown', hostOverride), {
58
+ method: 'POST',
59
+ signal: controller.signal,
60
+ });
61
+ return resp.ok;
62
+ } catch {
63
+ return false;
64
+ } finally {
65
+ clearTimeout(timeout);
66
+ }
67
+ }
68
+
69
+ async function requestJson(port, endpoint, options = {}) {
70
+ const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0
71
+ ? Math.trunc(options.timeoutMs)
72
+ : 4000;
73
+ const fetchOptions = { ...options };
74
+ delete fetchOptions.timeoutMs;
75
+ delete fetchOptions.uiPassword;
76
+
77
+ const controller = new AbortController();
78
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
79
+ try {
80
+ const requestUrl = buildLocalUrl(port, endpoint);
81
+ const requestHeaders = {
82
+ Accept: 'application/json',
83
+ ...(fetchOptions.body ? { 'Content-Type': 'application/json' } : {}),
84
+ ...(fetchOptions.headers || {}),
85
+ };
86
+ const response = await fetch(requestUrl, {
87
+ ...fetchOptions,
88
+ headers: requestHeaders,
89
+ signal: controller.signal,
90
+ });
91
+ const body = await response.json().catch(() => null);
92
+ if (response.status === 401 && body?.error === 'UI authentication required') {
93
+ const uiPassword = await resolveUiPasswordForPort(port, options);
94
+ const cookie = await createUiSessionCookie(port, uiPassword, timeoutMs);
95
+ if (cookie) {
96
+ const retryResponse = await fetch(requestUrl, {
97
+ ...fetchOptions,
98
+ headers: {
99
+ ...requestHeaders,
100
+ Cookie: cookie,
101
+ },
102
+ signal: controller.signal,
103
+ });
104
+ const retryBody = await retryResponse.json().catch(() => null);
105
+ return { response: retryResponse, body: retryBody };
106
+ }
107
+ }
108
+ return { response, body };
109
+ } catch (error) {
110
+ if (error && (error.name === 'AbortError' || error.code === 'ABORT_ERR')) {
111
+ throw new Error(`Request to ${endpoint} timed out after ${timeoutMs}ms.`);
112
+ }
113
+ throw error;
114
+ } finally {
115
+ clearTimeout(timeout);
116
+ }
117
+ }
118
+
119
+ async function isServerHealthReady(port, timeoutMs = 1000) {
120
+ if (!Number.isFinite(port) || port <= 0) {
121
+ return false;
122
+ }
123
+ const requestTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : 1000;
124
+ const controller = new AbortController();
125
+ const timeout = setTimeout(() => controller.abort(), requestTimeout);
126
+ try {
127
+ const response = await fetch(buildLocalUrl(port, '/health'), {
128
+ headers: { Accept: 'text/plain' },
129
+ signal: controller.signal,
130
+ });
131
+ return response.ok;
132
+ } catch {
133
+ return false;
134
+ } finally {
135
+ clearTimeout(timeout);
136
+ }
137
+ }
138
+
139
+ async function waitForServerHealth(port, {
140
+ timeoutMs = 60000,
141
+ intervalMs = 250,
142
+ onTick,
143
+ } = {}) {
144
+ const start = Date.now();
145
+ const deadline = start + timeoutMs;
146
+ while (Date.now() < deadline) {
147
+ const elapsedMs = Date.now() - start;
148
+ if (typeof onTick === 'function') {
149
+ onTick({ elapsedMs, timeoutMs });
150
+ }
151
+ if (await isServerHealthReady(port, Math.min(1000, intervalMs * 2))) {
152
+ if (typeof onTick === 'function') {
153
+ onTick({ elapsedMs: Math.min(Date.now() - start, timeoutMs), timeoutMs, complete: true });
154
+ }
155
+ return true;
156
+ }
157
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
158
+ }
159
+ if (typeof onTick === 'function') {
160
+ onTick({ elapsedMs: timeoutMs, timeoutMs, timedOut: true });
161
+ }
162
+ return false;
163
+ }
164
+
165
+
166
+ async function fetchTunnelProvidersFromPort(port, fetchImpl = globalThis.fetch) {
167
+ if (!Number.isFinite(port) || port <= 0 || typeof fetchImpl !== 'function') {
168
+ return null;
169
+ }
170
+ try {
171
+ const response = await fetchImpl(buildLocalUrl(port, '/api/openchamber/tunnel/providers'));
172
+ if (!response.ok) return null;
173
+ const body = await response.json().catch(() => null);
174
+ if (!body || !Array.isArray(body.providers)) return null;
175
+ return body.providers;
176
+ } catch {
177
+ return null;
178
+ }
179
+ }
180
+
181
+ async function fetchSystemInfoFromPort(port, fetchImpl = globalThis.fetch, hostOverride) {
182
+ if (!Number.isFinite(port) || port <= 0 || typeof fetchImpl !== 'function') {
183
+ return null;
184
+ }
185
+
186
+ const controller = new AbortController();
187
+ const timeout = setTimeout(() => controller.abort(), 1500);
188
+ try {
189
+ const response = await fetchImpl(buildLocalUrl(port, '/api/system/info', hostOverride), {
190
+ headers: { Accept: 'application/json' },
191
+ signal: controller.signal,
192
+ });
193
+ if (!response.ok) return null;
194
+ const body = await response.json().catch(() => null);
195
+ if (!body || typeof body.runtime !== 'string') return null;
196
+
197
+ return {
198
+ runtime: body.runtime,
199
+ pid: Number.isFinite(body.pid) ? body.pid : null,
200
+ };
201
+ } catch {
202
+ return null;
203
+ } finally {
204
+ clearTimeout(timeout);
205
+ }
206
+ }
207
+
208
+
209
+ export {
210
+ requestServerShutdown,
211
+ requestJson,
212
+ isServerHealthReady,
213
+ fetchTunnelProvidersFromPort,
214
+ fetchSystemInfoFromPort,
215
+ };
@@ -0,0 +1,421 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { DEFAULT_PORT } from './cli-args.js';
4
+ import { getRunDir, readDesktopLocalPortFromSettings } from './cli-paths.js';
5
+ import { resolveApiHost, buildLocalUrl } from './cli-network.js';
6
+ import { fetchTunnelProvidersFromPort, fetchSystemInfoFromPort, isServerHealthReady } from './cli-http.js';
7
+ import { isPortAvailable } from './cli-ports.js';
8
+ import {
9
+ getPidFilePath,
10
+ getInstanceFilePath,
11
+ readPidFile,
12
+ removePidFile,
13
+ readInstanceOptions,
14
+ removeInstanceFile,
15
+ getOpenchamberProcessState,
16
+ hasOpenchamberRuntimeInfo,
17
+ } from './cli-process.js';
18
+ import { DEFAULT_TUNNEL_PROVIDER_CAPABILITIES } from './cli-tunnel-capabilities.js';
19
+
20
+ function createLivePortInstance(port, info, host) {
21
+ if (!hasOpenchamberRuntimeInfo(info)) return null;
22
+ return {
23
+ port,
24
+ pid: Number.isFinite(info.pid) ? info.pid : null,
25
+ pidFilePath: path.join(getRunDir(), `openchamber-${port}.pid`),
26
+ instanceFilePath: path.join(getRunDir(), `openchamber-${port}.json`),
27
+ mtime: 0,
28
+ startedAt: 0,
29
+ launchMode: 'daemon',
30
+ runtime: info.runtime,
31
+ source: 'probe',
32
+ host: typeof host === 'string' && host.length > 0 ? host : undefined,
33
+ };
34
+ }
35
+
36
+ function normalizeProbeHost(host) {
37
+ return typeof host === 'string' && host.trim().length > 0 ? host.trim() : undefined;
38
+ }
39
+
40
+ function isWildcardProbeHost(host) {
41
+ const normalized = normalizeProbeHost(host);
42
+ return normalized === '0.0.0.0' || normalized === '::' || normalized === '[::]';
43
+ }
44
+
45
+ function isLoopbackProbeHost(host) {
46
+ const normalized = normalizeProbeHost(host);
47
+ return normalized === '127.0.0.1' || normalized === 'localhost' || normalized === '::1' || normalized === '[::1]';
48
+ }
49
+
50
+ function isConcreteProbeHost(host) {
51
+ const normalized = normalizeProbeHost(host);
52
+ return Boolean(normalized && !isWildcardProbeHost(normalized) && !isLoopbackProbeHost(normalized));
53
+ }
54
+
55
+ function getSystemInfoProbeHosts(...hosts) {
56
+ const out = [];
57
+ const hasConcreteAuthoritativeHost = hosts.some(isConcreteProbeHost);
58
+ const pushHost = (host, requiresPidMatch = false) => {
59
+ const normalized = normalizeProbeHost(host);
60
+ const key = resolveApiHost(normalized);
61
+ if (!out.some((entry) => resolveApiHost(entry.host) === key)) {
62
+ out.push({ host: normalized, requiresPidMatch });
63
+ }
64
+ };
65
+
66
+ for (const host of hosts) {
67
+ if (normalizeProbeHost(host)) {
68
+ pushHost(host, false);
69
+ }
70
+ }
71
+
72
+ pushHost(undefined, hasConcreteAuthoritativeHost);
73
+ pushHost('127.0.0.1', hasConcreteAuthoritativeHost);
74
+ return out;
75
+ }
76
+
77
+ async function fetchSystemInfoFromPortCandidates(port, fetchImpl, hosts, expectedPid) {
78
+ for (const { host, requiresPidMatch } of hosts) {
79
+ const info = await fetchSystemInfoFromPort(port, fetchImpl, host);
80
+ if (hasOpenchamberRuntimeInfo(info)) {
81
+ if (requiresPidMatch && info.pid !== expectedPid) {
82
+ continue;
83
+ }
84
+ return { info, host };
85
+ }
86
+ }
87
+ return { info: null, host: null };
88
+ }
89
+
90
+ async function resolveDoctorPortStatuses(options = {}) {
91
+ const runningEntries = await discoverRunningInstances();
92
+ const desktopEntry = await discoverDesktopInstance();
93
+ const statuses = [];
94
+
95
+ if (options.explicitPort) {
96
+ const requestedPort = options.port;
97
+ const runningMatch = runningEntries.find((entry) => entry.port === requestedPort);
98
+ if (runningMatch) {
99
+ statuses.push({
100
+ port: requestedPort,
101
+ available: true,
102
+ status: 'success',
103
+ line: `port ${requestedPort} available for tunneling`,
104
+ detail: 'Double-check this same port is configured in your provider dashboard/config.',
105
+ });
106
+ return { statuses, availableEntries: [runningMatch] };
107
+ }
108
+
109
+ if (desktopEntry && desktopEntry.port === requestedPort) {
110
+ statuses.push({
111
+ port: requestedPort,
112
+ available: false,
113
+ status: 'warning',
114
+ line: `port ${requestedPort} not available (desktop runtime)`,
115
+ detail: 'Use a CLI instance port from `openchamber serve` for tunneling.',
116
+ });
117
+ return { statuses, availableEntries: [] };
118
+ }
119
+
120
+ statuses.push({
121
+ port: requestedPort,
122
+ available: false,
123
+ status: 'error',
124
+ line: `port ${requestedPort} not available (no running instance)`,
125
+ detail: `Start one with \`openchamber serve --port ${requestedPort}\`.`,
126
+ });
127
+ return { statuses, availableEntries: [] };
128
+ }
129
+
130
+ for (const entry of runningEntries) {
131
+ statuses.push({
132
+ port: entry.port,
133
+ available: true,
134
+ status: 'success',
135
+ line: `port ${entry.port} available for tunneling`,
136
+ detail: 'Double-check this same port is configured in your provider dashboard/config.',
137
+ });
138
+ }
139
+
140
+ if (desktopEntry && !runningEntries.some((entry) => entry.port === desktopEntry.port)) {
141
+ statuses.push({
142
+ port: desktopEntry.port,
143
+ available: false,
144
+ status: 'warning',
145
+ line: `port ${desktopEntry.port} not available (desktop runtime)`,
146
+ detail: 'Use a CLI instance port from `openchamber serve` for tunneling.',
147
+ });
148
+ }
149
+
150
+ if (runningEntries.length === 0) {
151
+ statuses.push({
152
+ port: null,
153
+ available: false,
154
+ status: 'warning',
155
+ line: 'no CLI ports available for tunneling',
156
+ detail: 'Start one with `openchamber serve`.',
157
+ });
158
+ }
159
+
160
+ return { statuses, availableEntries: runningEntries };
161
+ }
162
+
163
+ async function discoverRunningInstances(options = {}) {
164
+ const instances = [];
165
+ const runDir = getRunDir();
166
+ const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : globalThis.fetch;
167
+ const getProcessState = typeof options.getOpenchamberProcessState === 'function'
168
+ ? options.getOpenchamberProcessState
169
+ : (pid) => getOpenchamberProcessState(pid, options);
170
+ try {
171
+ const files = fs.readdirSync(runDir);
172
+ const pidFiles = files.filter((file) => file.startsWith('openchamber-') && file.endsWith('.pid'));
173
+ for (const file of pidFiles) {
174
+ const port = parseInt(file.replace('openchamber-', '').replace('.pid', ''), 10);
175
+ if (!Number.isFinite(port) || port <= 0) continue;
176
+ const pidFilePath = path.join(runDir, file);
177
+ const pid = readPidFile(pidFilePath);
178
+ if (!pid) {
179
+ removePidFile(pidFilePath);
180
+ removeInstanceFile(path.join(runDir, `openchamber-${port}.json`));
181
+ continue;
182
+ }
183
+
184
+ const instanceFilePath = path.join(runDir, `openchamber-${port}.json`);
185
+ const storedOptions = readInstanceOptions(instanceFilePath);
186
+ const processState = getProcessState(pid);
187
+ if (processState === 'dead') {
188
+ removePidFile(pidFilePath);
189
+ removeInstanceFile(instanceFilePath);
190
+ continue;
191
+ }
192
+
193
+ // A live PID-file is only the right instance if the recorded port also
194
+ // confirms OpenChamber. Cmdline identity alone can match a recycled PID
195
+ // from another OpenChamber process on a different port. Try all plausible
196
+ // hosts first; if matched/unknown identity still can't be confirmed, keep
197
+ // the registry files but don't claim the instance is running.
198
+ const { info: liveInfo, host: confirmedHost } = await fetchSystemInfoFromPortCandidates(
199
+ port,
200
+ fetchImpl,
201
+ getSystemInfoProbeHosts(storedOptions?.host, options.host),
202
+ pid,
203
+ );
204
+ const livePid = Number.isFinite(liveInfo?.pid) ? liveInfo.pid : null;
205
+ if (!hasOpenchamberRuntimeInfo(liveInfo)) {
206
+ if (processState === 'mismatched') {
207
+ removePidFile(pidFilePath);
208
+ removeInstanceFile(instanceFilePath);
209
+ }
210
+ continue;
211
+ }
212
+
213
+ if (liveInfo.runtime === 'desktop') {
214
+ removePidFile(pidFilePath);
215
+ removeInstanceFile(instanceFilePath);
216
+ continue;
217
+ }
218
+
219
+ let mtime = 0;
220
+ let startedAt = 0;
221
+ try {
222
+ mtime = fs.statSync(pidFilePath).mtimeMs;
223
+ } catch {
224
+ }
225
+ if (Number.isFinite(storedOptions?.startedAt)) {
226
+ startedAt = storedOptions.startedAt;
227
+ }
228
+ const launchMode = storedOptions?.launchMode === 'foreground' ? 'foreground' : 'daemon';
229
+ instances.push({
230
+ port,
231
+ pid: livePid || (processState === 'matched' ? pid : null),
232
+ pidFilePath,
233
+ instanceFilePath,
234
+ mtime,
235
+ startedAt,
236
+ launchMode,
237
+ runtime: liveInfo.runtime,
238
+ source: 'registry+probe',
239
+ host: typeof confirmedHost === 'string' && confirmedHost.length > 0
240
+ ? confirmedHost
241
+ : (typeof storedOptions?.host === 'string' && storedOptions.host.length > 0 ? storedOptions.host : undefined),
242
+ });
243
+ }
244
+ } catch {
245
+ }
246
+ instances.sort((a, b) => a.port - b.port);
247
+ return instances;
248
+ }
249
+
250
+ async function discoverOpenChamberInstanceOnPort(port, options = {}) {
251
+ if (!Number.isFinite(port) || port <= 0) return null;
252
+ const runningInstances = Array.isArray(options.runningInstances)
253
+ ? options.runningInstances
254
+ : await discoverRunningInstances(options);
255
+ const registryMatch = runningInstances.find((entry) => entry.port === port);
256
+ if (registryMatch) return registryMatch;
257
+
258
+ const info = await fetchSystemInfoFromPort(
259
+ port,
260
+ typeof options.fetchImpl === 'function' ? options.fetchImpl : globalThis.fetch,
261
+ options.host,
262
+ );
263
+ if (info?.runtime === 'desktop' && !isDesktopRuntimeForPort(info, port)) {
264
+ return null;
265
+ }
266
+ return createLivePortInstance(port, info, options.host);
267
+ }
268
+
269
+ async function discoverLifecycleInstances(options = {}, deps = {}) {
270
+ const runningInstances = await discoverRunningInstances({ ...deps, host: options.host });
271
+ if (!options.explicitPort) {
272
+ return runningInstances;
273
+ }
274
+ const found = runningInstances.find((entry) => entry.port === options.port);
275
+ if (found) return [found];
276
+ const liveInstance = await discoverOpenChamberInstanceOnPort(options.port, {
277
+ ...deps,
278
+ host: options.host,
279
+ runningInstances,
280
+ });
281
+ return liveInstance ? [liveInstance] : [];
282
+ }
283
+
284
+ async function discoverUnconfirmedRegistryInstanceOnPort(port, options = {}) {
285
+ if (!Number.isFinite(port) || port <= 0) return null;
286
+
287
+ const pidFilePath = await getPidFilePath(port);
288
+ const pid = readPidFile(pidFilePath);
289
+ if (!pid) return null;
290
+
291
+ const instanceFilePath = await getInstanceFilePath(port);
292
+ const storedOptions = readInstanceOptions(instanceFilePath);
293
+ const processState = getOpenchamberProcessState(pid);
294
+ if (processState === 'dead') {
295
+ removePidFile(pidFilePath);
296
+ removeInstanceFile(instanceFilePath);
297
+ return null;
298
+ }
299
+
300
+ if (processState !== 'matched') {
301
+ return null;
302
+ }
303
+
304
+ const host = storedOptions?.host || options.host;
305
+ if (await isPortAvailable(port, host)) {
306
+ removePidFile(pidFilePath);
307
+ removeInstanceFile(instanceFilePath);
308
+ return null;
309
+ }
310
+
311
+ return {
312
+ port,
313
+ pid,
314
+ pidFilePath,
315
+ instanceFilePath,
316
+ mtime: 0,
317
+ startedAt: Number.isFinite(storedOptions?.startedAt) ? storedOptions.startedAt : 0,
318
+ launchMode: storedOptions?.launchMode === 'foreground' ? 'foreground' : 'daemon',
319
+ runtime: 'cli',
320
+ source: 'registry-unconfirmed',
321
+ host: typeof host === 'string' && host.length > 0 ? host : undefined,
322
+ };
323
+ }
324
+
325
+ function getLatestInstance(instances) {
326
+ if (!instances.length) return null;
327
+ return [...instances].sort((a, b) => {
328
+ const startedDelta = (b.startedAt || 0) - (a.startedAt || 0);
329
+ if (startedDelta !== 0) return startedDelta;
330
+ const mtimeDelta = (b.mtime || 0) - (a.mtime || 0);
331
+ if (mtimeDelta !== 0) return mtimeDelta;
332
+ return b.port - a.port;
333
+ })[0];
334
+ }
335
+
336
+ function isDesktopRuntimeForPort(info, port) {
337
+ if (info?.runtime !== 'desktop') {
338
+ return false;
339
+ }
340
+ const desktopPort = readDesktopLocalPortFromSettings();
341
+ return !desktopPort || desktopPort === port;
342
+ }
343
+
344
+ async function inspectTunnelAttachability(port, { requireHealthy = true } = {}) {
345
+ const info = await fetchSystemInfoFromPort(port);
346
+ if (!info || typeof info.runtime !== 'string') {
347
+ return { attachable: false, reason: 'unreachable' };
348
+ }
349
+ if (isDesktopRuntimeForPort(info, port)) {
350
+ return { attachable: false, reason: 'desktop', info };
351
+ }
352
+ if (requireHealthy) {
353
+ const healthy = await isServerHealthReady(port, 1200);
354
+ if (!healthy) {
355
+ return { attachable: false, reason: 'unhealthy', info };
356
+ }
357
+ }
358
+ return { attachable: true, reason: 'ok', info };
359
+ }
360
+
361
+ async function discoverDesktopInstance(fetchImpl = globalThis.fetch) {
362
+ const port = readDesktopLocalPortFromSettings();
363
+ if (!port) {
364
+ return null;
365
+ }
366
+
367
+ const info = await fetchSystemInfoFromPort(port, fetchImpl);
368
+ if (!info || info.runtime !== 'desktop') {
369
+ return null;
370
+ }
371
+
372
+ return {
373
+ port,
374
+ pid: info.pid,
375
+ runtime: info.runtime,
376
+ };
377
+ }
378
+
379
+ async function resolveTunnelProviders(options = {}, deps = {}) {
380
+ const readPorts = typeof deps.readPorts === 'function'
381
+ ? deps.readPorts
382
+ : async () => (await discoverRunningInstances()).map((entry) => entry.port);
383
+ const fetchImpl = typeof deps.fetchImpl === 'function' ? deps.fetchImpl : globalThis.fetch;
384
+
385
+ const candidatePorts = [];
386
+ if (Number.isFinite(options.port) && options.port > 0) {
387
+ candidatePorts.push(options.port);
388
+ }
389
+
390
+ const discoveredPorts = await Promise.resolve(readPorts());
391
+ if (Array.isArray(discoveredPorts)) {
392
+ candidatePorts.push(...discoveredPorts);
393
+ }
394
+
395
+ if (!candidatePorts.includes(DEFAULT_PORT)) {
396
+ candidatePorts.push(DEFAULT_PORT);
397
+ }
398
+
399
+ for (const port of candidatePorts) {
400
+ const providers = await fetchTunnelProvidersFromPort(port, fetchImpl);
401
+ if (providers) {
402
+ return { providers, source: `api:${port}` };
403
+ }
404
+ }
405
+
406
+ return { providers: DEFAULT_TUNNEL_PROVIDER_CAPABILITIES, source: 'fallback' };
407
+ }
408
+
409
+
410
+ export {
411
+ resolveDoctorPortStatuses,
412
+ discoverRunningInstances,
413
+ discoverOpenChamberInstanceOnPort,
414
+ discoverLifecycleInstances,
415
+ discoverUnconfirmedRegistryInstanceOnPort,
416
+ getLatestInstance,
417
+ isDesktopRuntimeForPort,
418
+ inspectTunnelAttachability,
419
+ discoverDesktopInstance,
420
+ resolveTunnelProviders,
421
+ };