@openchamber/web 1.13.3 → 1.13.5

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 (129) hide show
  1. package/bin/cli-output.js +2 -7
  2. package/bin/cli-output.test.js +36 -0
  3. package/bin/cli.js +132 -5548
  4. package/bin/cli.test.js +686 -0
  5. package/bin/lib/DOCUMENTATION.md +121 -0
  6. package/bin/lib/cli-args.js +726 -0
  7. package/bin/lib/cli-errors.js +18 -0
  8. package/bin/lib/cli-executables.js +54 -0
  9. package/bin/lib/cli-http.js +216 -0
  10. package/bin/lib/cli-lifecycle.js +421 -0
  11. package/bin/lib/cli-log-files.js +93 -0
  12. package/bin/lib/cli-network.js +154 -0
  13. package/bin/lib/cli-paths.js +113 -0
  14. package/bin/lib/cli-ports.js +51 -0
  15. package/bin/lib/cli-process.js +292 -0
  16. package/bin/lib/cli-startup.js +370 -0
  17. package/bin/lib/cli-tunnel-capabilities.js +9 -0
  18. package/bin/lib/cli-tunnel-profiles.js +366 -0
  19. package/bin/lib/cli-tunnel-utils.js +300 -0
  20. package/bin/lib/commands-connect-url.js +173 -0
  21. package/bin/lib/commands-lifecycle.js +396 -0
  22. package/bin/lib/commands-logs.js +110 -0
  23. package/bin/lib/commands-serve.js +396 -0
  24. package/bin/lib/commands-startup.js +64 -0
  25. package/bin/lib/commands-status.js +114 -0
  26. package/bin/lib/commands-tunnel.js +1761 -0
  27. package/bin/lib/commands-update.js +141 -0
  28. package/dist/assets/{DiagramView-BmHROYsX.js → DiagramView-Bbj-QI7h.js} +1 -1
  29. package/dist/assets/{MarkdownRendererImpl-DiJE-v5Q.js → MarkdownRendererImpl-BNr_9Jsb.js} +3 -3
  30. package/dist/assets/MultiRunWindow-DMMu53kw.js +1 -0
  31. package/dist/assets/NewWorktreeDialog-5TYBoMMA.js +167 -0
  32. package/dist/assets/{OnboardingScreen-DpBF8dKJ.js → OnboardingScreen-BucKVBD7.js} +1 -1
  33. package/dist/assets/{SessionSwitcherDropdown-1xaHUxPK.js → SessionSwitcherDropdown-B6kvduse.js} +1 -1
  34. package/dist/assets/{SettingsWindow-ChwLyQAe.js → SettingsWindow-BEfDro9b.js} +1 -1
  35. package/dist/assets/{TerminalView-DGEBNuAp.js → TerminalView-CMdqMpTy.js} +1 -1
  36. package/dist/assets/es-Bk-yR0w-.js +15 -0
  37. package/dist/assets/fr-f1ibV7QU.js +13 -0
  38. package/dist/assets/index-B82A6jBD.css +1 -0
  39. package/dist/assets/index-BsXkdBYx.js +3 -0
  40. package/dist/assets/ja-D9mS3zWP.js +15 -0
  41. package/dist/assets/ko-Cpl1IA3D.js +15 -0
  42. package/dist/assets/main-DOdUrt3s.js +214 -0
  43. package/dist/assets/{main-fm_8J7Lk.js → main-KEVf2Yak.js} +2 -2
  44. package/dist/assets/miniChat-Nlzqr3Df.js +2 -0
  45. package/dist/assets/mobile-BIhOFhia.js +2 -0
  46. package/dist/assets/pl-CYke_fxL.js +15 -0
  47. package/dist/assets/pt-BR-Clb6Z8up.js +15 -0
  48. package/dist/assets/renderElectronMiniChatApp-Cb1iUq8M.js +2 -0
  49. package/dist/assets/{renderMobileApp-6s0G1iIJ.js → renderMobileApp-7chEBHPK.js} +5 -5
  50. package/dist/assets/uk-CXn8cxXa.js +15 -0
  51. package/dist/assets/{useAppFontEffects-CV5C5O0r.js → useAppFontEffects-Bd0ks39c.js} +124 -119
  52. package/dist/assets/{vendor-.bun-CC_Xso_s.js → vendor-.bun-By2L9XvG.js} +1 -1
  53. package/dist/assets/zh-CN-BRwwlEdG.js +15 -0
  54. package/dist/assets/zh-TW-D5pg5Z8l.js +15 -0
  55. package/dist/index.html +4 -4
  56. package/dist/mini-chat.html +4 -4
  57. package/dist/mobile.html +4 -4
  58. package/package.json +1 -1
  59. package/server/lib/cloudflare-tunnel.js +2 -2
  60. package/server/lib/event-stream/global-hub.js +1 -1
  61. package/server/lib/event-stream/index.js +0 -12
  62. package/server/lib/event-stream/runtime.js +1 -1
  63. package/server/lib/git/routes.test.js +4 -4
  64. package/server/lib/git/service.js +18 -0
  65. package/server/lib/git/service.test.js +48 -0
  66. package/server/lib/github/routes.js +1 -0
  67. package/server/lib/notifications/index.js +1 -4
  68. package/server/lib/opencode/agents.js +0 -6
  69. package/server/lib/opencode/commands.js +0 -5
  70. package/server/lib/opencode/config-entity-routes.js +39 -21
  71. package/server/lib/opencode/feature-routes-runtime.js +27 -62
  72. package/server/lib/opencode/lifecycle.js +13 -1
  73. package/server/lib/opencode/npm-registry.js +3 -3
  74. package/server/lib/opencode/proxy.js +3 -3
  75. package/server/lib/opencode/shared.js +0 -6
  76. package/server/lib/opencode/skills.js +0 -2
  77. package/server/lib/opencode/snippets.js +0 -2
  78. package/server/lib/package-manager.js +4 -4
  79. package/server/lib/package-manager.test.js +8 -1
  80. package/server/lib/projects/project-config.js +0 -8
  81. package/server/lib/quota/DOCUMENTATION.md +3 -1
  82. package/server/lib/quota/providers/claude.js +1 -1
  83. package/server/lib/quota/providers/codex.js +1 -1
  84. package/server/lib/quota/providers/copilot.js +1 -1
  85. package/server/lib/quota/providers/cursor.js +1 -1
  86. package/server/lib/quota/providers/google/auth.js +2 -2
  87. package/server/lib/quota/providers/google/index.js +14 -33
  88. package/server/lib/quota/providers/google/transforms.js +1 -1
  89. package/server/lib/quota/providers/index.js +4 -4
  90. package/server/lib/quota/providers/index.test.js +17 -0
  91. package/server/lib/quota/providers/kimi.js +1 -1
  92. package/server/lib/quota/providers/minimax-cn-coding-plan.js +1 -1
  93. package/server/lib/quota/providers/minimax-coding-plan.js +1 -1
  94. package/server/lib/quota/providers/nanogpt.js +1 -1
  95. package/server/lib/quota/providers/ollama-cloud.js +1 -1
  96. package/server/lib/quota/providers/openai.js +4 -4
  97. package/server/lib/quota/providers/openrouter.js +1 -1
  98. package/server/lib/quota/providers/wafer.js +1 -1
  99. package/server/lib/quota/providers/zai.js +1 -1
  100. package/server/lib/quota/providers/zhipuai-coding-plan.js +1 -1
  101. package/server/lib/skills-catalog/cache.js +0 -4
  102. package/server/lib/skills-catalog/clawdhub/api.js +0 -32
  103. package/server/lib/skills-catalog/clawdhub/scan.js +0 -52
  104. package/server/lib/skills-catalog/curated-sources.js +1 -1
  105. package/server/lib/skills-catalog/source.js +5 -0
  106. package/server/lib/terminal/runtime.js +11 -9
  107. package/server/lib/text/summarization.js +1 -1
  108. package/server/lib/tunnels/types.js +2 -2
  109. package/dist/assets/MultiRunWindow-yZoCT7F7.js +0 -1
  110. package/dist/assets/NewWorktreeDialog-CTMiE7Xd.js +0 -167
  111. package/dist/assets/es-CTE-E8we.js +0 -15
  112. package/dist/assets/fr-TVkZpyEo.js +0 -13
  113. package/dist/assets/index-B4pCDMbq.css +0 -1
  114. package/dist/assets/index-D9uMvTQF.js +0 -3
  115. package/dist/assets/ko-D_UCJIIL.js +0 -15
  116. package/dist/assets/main-eAd3a6tx.js +0 -214
  117. package/dist/assets/miniChat-Bbjg31IC.js +0 -2
  118. package/dist/assets/mobile-B3_j_DsB.js +0 -2
  119. package/dist/assets/pl-nDEkk-GZ.js +0 -15
  120. package/dist/assets/pt-BR-B_g2RcgU.js +0 -15
  121. package/dist/assets/renderElectronMiniChatApp-CB13zs6N.js +0 -2
  122. package/dist/assets/uk-CWLhnPGW.js +0 -15
  123. package/dist/assets/zh-CN-BFxe1b5m.js +0 -15
  124. package/dist/assets/zh-TW-n-d-xbGV.js +0 -15
  125. package/server/lib/opencode/index.js +0 -95
  126. package/server/lib/quota/providers/interface.js +0 -55
  127. package/server/lib/skills-catalog/clawdhub/index.js +0 -30
  128. package/server/lib/skills-catalog/index.js +0 -42
  129. package/server/lib/terminal/index.js +0 -31
@@ -0,0 +1,173 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import crypto from 'crypto';
5
+ import { EXIT_CODE, TunnelCliError } from './cli-errors.js';
6
+ import {
7
+ assertSafeBrowserPort,
8
+ resolveConfiguredBindHost,
9
+ buildLocalUrl,
10
+ detectLanIPv4Address,
11
+ formatHostForUrl,
12
+ } from './cli-network.js';
13
+ import { discoverRunningInstances } from './cli-lifecycle.js';
14
+ import { getInstanceFilePath, readInstanceOptions } from './cli-process.js';
15
+ import { createRemoteClientAuthRuntime } from '../../server/lib/client-auth/remote-clients.js';
16
+ import {
17
+ intro as clackIntro,
18
+ outro as clackOutro,
19
+ log as clackLog,
20
+ isJsonMode,
21
+ isQuietMode,
22
+ printJson,
23
+ logStatus,
24
+ } from '../cli-output.js';
25
+
26
+ const REMOTE_CLIENTS_FILE_NAME = 'remote-clients.json';
27
+
28
+ async function resolveConnectUrlServerUrl(options) {
29
+ let hostOverride = options.host;
30
+ if (typeof hostOverride !== 'string' && !process.env.OPENCHAMBER_HOST) {
31
+ const storedOptions = readInstanceOptions(await getInstanceFilePath(options.port));
32
+ if (typeof storedOptions?.host === 'string' && storedOptions.host.trim()) {
33
+ hostOverride = storedOptions.host.trim();
34
+ }
35
+ }
36
+
37
+ const bindHost = resolveConfiguredBindHost(hostOverride);
38
+ if (!isWildcardBindHost(bindHost)) {
39
+ return {
40
+ serverUrl: buildLocalUrl(options.port, '/', hostOverride).replace(/\/+$/, ''),
41
+ source: 'configured-host',
42
+ };
43
+ }
44
+
45
+ const lanAddress = await detectLanIPv4Address();
46
+ if (!lanAddress) {
47
+ return {
48
+ serverUrl: buildLocalUrl(options.port, '/').replace(/\/+$/, ''),
49
+ source: 'loopback-fallback',
50
+ };
51
+ }
52
+
53
+ return {
54
+ serverUrl: `http://${formatHostForUrl(lanAddress)}:${options.port}`,
55
+ source: 'lan-detected',
56
+ };
57
+ }
58
+
59
+ function isWildcardBindHost(host) {
60
+ return host === '0.0.0.0' || host === '::' || host === '[::]';
61
+ }
62
+
63
+ function normalizeServerUrlForConnection(value) {
64
+ const trimmed = typeof value === 'string' ? value.trim() : '';
65
+ if (!trimmed) return null;
66
+ try {
67
+ const parsed = new URL(trimmed);
68
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
69
+ return null;
70
+ }
71
+ parsed.hash = '';
72
+ return parsed.toString().replace(/\/+$/, '');
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+
78
+ function getOpenChamberDataDir() {
79
+ return process.env.OPENCHAMBER_DATA_DIR
80
+ ? path.resolve(process.env.OPENCHAMBER_DATA_DIR)
81
+ : path.join(os.homedir(), '.config', 'openchamber');
82
+ }
83
+
84
+ function buildClientConnectionPayload({ serverUrl, token, label }) {
85
+ const params = new URLSearchParams();
86
+ params.set('v', '1');
87
+ params.set('server', serverUrl.trim().replace(/\/+$/, ''));
88
+ params.set('token', token.trim());
89
+ if (label?.trim()) params.set('label', label.trim());
90
+ return `openchamber://connect?${params.toString()}`;
91
+ }
92
+
93
+ async function displayTunnelQrCode(url) {
94
+ try {
95
+ const qrcode = await import('qrcode-terminal');
96
+ console.log('\n📱 Scan this QR code to access the tunnel:\n');
97
+ qrcode.default.generate(url, { small: true });
98
+ console.log('');
99
+ } catch (error) {
100
+ console.warn(`Warning: Could not generate QR code: ${error.message}`);
101
+ }
102
+ }
103
+
104
+ function createConnectUrlCommand({ serveCommand }) {
105
+ return async function connectUrlCommand(options = {}) {
106
+ assertSafeBrowserPort(options.port, { context: 'OpenChamber connect-url' });
107
+ const explicitServerUrl = options.server ? normalizeServerUrlForConnection(options.server) : null;
108
+ if (options.server && !explicitServerUrl) {
109
+ throw new TunnelCliError('Invalid --server URL. Use an http:// or https:// URL.', EXIT_CODE.USAGE_ERROR);
110
+ }
111
+
112
+ const running = await discoverRunningInstances();
113
+ const serverState = running.some((entry) => entry.port === options.port)
114
+ ? { port: options.port, autoStarted: false }
115
+ : await (async () => {
116
+ await serveCommand({
117
+ port: options.port,
118
+ explicitPort: true,
119
+ host: options.host,
120
+ uiPassword: options.uiPassword,
121
+ apiOnly: options.apiOnly,
122
+ suppressUnsafePortWarning: true,
123
+ suppressUiPasswordWarning: true,
124
+ suppressStartupSummary: true,
125
+ suppressQuietOutput: true,
126
+ });
127
+ return { port: options.port, autoStarted: true };
128
+ })();
129
+
130
+ const resolvedServerUrl = explicitServerUrl
131
+ ? { serverUrl: explicitServerUrl, source: 'explicit' }
132
+ : await resolveConnectUrlServerUrl(options);
133
+ const serverUrl = resolvedServerUrl.serverUrl;
134
+ const label = options.name || `OpenChamber ${serverUrl}`;
135
+ const runtime = createRemoteClientAuthRuntime({
136
+ fsPromises: fs.promises,
137
+ path,
138
+ crypto,
139
+ storePath: path.join(getOpenChamberDataDir(), REMOTE_CLIENTS_FILE_NAME),
140
+ });
141
+ const result = await runtime.createClient({ label });
142
+ const connectUrl = buildClientConnectionPayload({ serverUrl, token: result.token, label });
143
+
144
+ if (isJsonMode(options)) {
145
+ printJson({ serverUrl, connectUrl, token: result.token, client: result.client, autoStarted: serverState.autoStarted });
146
+ return;
147
+ }
148
+
149
+ if (isQuietMode(options)) {
150
+ process.stdout.write(`${connectUrl}\n`);
151
+ return;
152
+ }
153
+
154
+ clackIntro('OpenChamber connect URL');
155
+ if (serverState.autoStarted) {
156
+ logStatus('success', `started OpenChamber on port ${options.port}`);
157
+ }
158
+ logStatus('success', connectUrl);
159
+ clackLog.info(`Server URL: ${serverUrl}`);
160
+ if (resolvedServerUrl.source === 'lan-detected') {
161
+ clackLog.info('Detected a LAN address because OpenChamber is bound to all interfaces. Use --server to override it.');
162
+ } else if (resolvedServerUrl.source === 'loopback-fallback') {
163
+ clackLog.warn('OpenChamber is bound to all interfaces, but no LAN address was detected. Use --server to provide a reachable URL.');
164
+ }
165
+ clackLog.info('Copy this connection link into another OpenChamber client. The token is shown only once.');
166
+ if (options.qr === true) {
167
+ await displayTunnelQrCode(connectUrl);
168
+ }
169
+ clackOutro('connect URL generated');
170
+ };
171
+ }
172
+
173
+ export { createConnectUrlCommand };
@@ -0,0 +1,396 @@
1
+ import { EXIT_CODE, TunnelCliError } from './cli-errors.js';
2
+ import { requestServerShutdown } from './cli-http.js';
3
+ import { isPortAvailable } from './cli-ports.js';
4
+ import {
5
+ discoverLifecycleInstances,
6
+ discoverUnconfirmedRegistryInstanceOnPort,
7
+ } from './cli-lifecycle.js';
8
+ import {
9
+ readInstanceOptions,
10
+ removePidFile,
11
+ removeInstanceFile,
12
+ isProcessRunning,
13
+ stopInstanceProcess,
14
+ } from './cli-process.js';
15
+ import {
16
+ intro as clackIntro,
17
+ outro as clackOutro,
18
+ isJsonMode,
19
+ isQuietMode,
20
+ shouldRenderHumanOutput,
21
+ createSpinner,
22
+ printJson,
23
+ logStatus,
24
+ } from '../cli-output.js';
25
+
26
+ async function stopCommand(options) {
27
+ const showOutput = shouldRenderHumanOutput(options);
28
+ const suppressQuietOutput = options?.suppressQuietOutput === true;
29
+ const jsonResults = [];
30
+ const printQuietStopResults = () => {
31
+ if (suppressQuietOutput) return;
32
+ if (!isQuietMode(options) || isJsonMode(options)) return;
33
+ if (jsonResults.length === 0) {
34
+ process.stdout.write('none\n');
35
+ return;
36
+ }
37
+ for (const result of jsonResults) {
38
+ if (result.stopped) {
39
+ process.stdout.write(`stopped ${result.port}\n`);
40
+ } else {
41
+ const reason = result.reason || 'failed';
42
+ process.stderr.write(`failed ${result.port} ${reason}\n`);
43
+ }
44
+ }
45
+ };
46
+ const finish = (text) => {
47
+ if (!showOutput) return;
48
+ clackOutro(text);
49
+ };
50
+
51
+ if (showOutput) {
52
+ clackIntro('OpenChamber Stop');
53
+ }
54
+
55
+ let runningInstances = await discoverLifecycleInstances(options);
56
+ if (options.explicitPort) {
57
+ if (runningInstances.length === 0) {
58
+ const unconfirmedInstance = await discoverUnconfirmedRegistryInstanceOnPort(options.port, options);
59
+ if (unconfirmedInstance) {
60
+ runningInstances = [unconfirmedInstance];
61
+ }
62
+ }
63
+
64
+ if (runningInstances.length === 0) {
65
+ jsonResults.push({ port: options.port, stopped: false, reason: 'not-found' });
66
+ if (isJsonMode(options)) {
67
+ printJson({ stoppedCount: 0, results: jsonResults });
68
+ }
69
+ if (showOutput) {
70
+ logStatus('info', `no OpenChamber instance found on port ${options.port}`);
71
+ finish('nothing to stop');
72
+ }
73
+ printQuietStopResults();
74
+ return;
75
+ }
76
+
77
+ const explicitInstance = runningInstances[0];
78
+ if (explicitInstance.runtime === 'desktop') {
79
+ jsonResults.push({ port: options.port, runtime: 'desktop', stopped: false, reason: 'desktop-managed' });
80
+ if (isJsonMode(options)) {
81
+ printJson({ stoppedCount: 0, results: jsonResults, messages: [{ level: 'warning', code: 'DESKTOP_MANAGED_PORT', message: `Port ${options.port} is managed by OpenChamber Desktop and cannot be stopped with this command.` }] });
82
+ }
83
+ if (showOutput) {
84
+ logStatus('warning', `port ${options.port} is managed by OpenChamber Desktop`, 'cannot be stopped with this command');
85
+ finish('no changes applied');
86
+ }
87
+ printQuietStopResults();
88
+ return;
89
+ }
90
+
91
+ if (explicitInstance.source === 'probe') {
92
+ const unmanagedStopSpin = showOutput ? createSpinner(options) : null;
93
+ if (showOutput && !unmanagedStopSpin) {
94
+ logStatus('info', `found unmanaged OpenChamber instance on port ${options.port}`, 'attempting shutdown');
95
+ }
96
+ unmanagedStopSpin?.start(`Stopping unmanaged OpenChamber on port ${options.port}...`);
97
+ const requested = await requestServerShutdown(options.port, options.host);
98
+
99
+ if (Number.isFinite(explicitInstance.pid) && isProcessRunning(explicitInstance.pid)) {
100
+ await stopInstanceProcess(explicitInstance.pid, {
101
+ shutdownWaitMs: requested ? 5000 : 0,
102
+ gracefulTimeoutMs: 2500,
103
+ forceTimeoutMs: 3000,
104
+ }).catch(() => false);
105
+ }
106
+
107
+ const stopped = await isPortAvailable(options.port, options.host);
108
+ if (stopped) {
109
+ unmanagedStopSpin?.stop(`Stopped unmanaged OpenChamber on port ${options.port}`);
110
+ jsonResults.push({ port: options.port, runtime: 'unmanaged', stopped: true });
111
+ if (isJsonMode(options)) {
112
+ printJson({ stoppedCount: 1, results: jsonResults });
113
+ }
114
+ if (showOutput && !unmanagedStopSpin) {
115
+ logStatus('success', `stopped OpenChamber on port ${options.port}`);
116
+ finish('stop complete');
117
+ }
118
+ printQuietStopResults();
119
+ } else if (requested) {
120
+ unmanagedStopSpin?.stop(`Shutdown requested on port ${options.port} (still occupied)`);
121
+ jsonResults.push({ port: options.port, runtime: 'unmanaged', stopped: false, reason: 'shutdown-requested-port-busy' });
122
+ if (isJsonMode(options)) {
123
+ printJson({
124
+ status: 'warning',
125
+ stoppedCount: 0,
126
+ results: jsonResults,
127
+ messages: [{ level: 'warning', code: 'SHUTDOWN_PARTIAL', message: `Shutdown was requested for port ${options.port}, but the port is still occupied.` }],
128
+ });
129
+ }
130
+ if (showOutput && !unmanagedStopSpin) {
131
+ logStatus('warning', `shutdown requested on port ${options.port}`, 'port is still occupied');
132
+ finish('partial stop');
133
+ }
134
+ printQuietStopResults();
135
+ } else {
136
+ unmanagedStopSpin?.error(`Could not stop OpenChamber on port ${options.port}`);
137
+ jsonResults.push({ port: options.port, runtime: 'unmanaged', stopped: false, reason: 'stop-failed' });
138
+ if (isJsonMode(options)) {
139
+ printJson({
140
+ status: 'error',
141
+ stoppedCount: 0,
142
+ results: jsonResults,
143
+ messages: [{ level: 'error', code: 'STOP_FAILED', message: `Could not stop OpenChamber on port ${options.port}.` }],
144
+ });
145
+ }
146
+ if (showOutput && !unmanagedStopSpin) {
147
+ logStatus('error', `could not stop OpenChamber on port ${options.port}`);
148
+ finish('failed');
149
+ }
150
+ printQuietStopResults();
151
+ }
152
+ return;
153
+ }
154
+
155
+ if (explicitInstance.source === 'registry-unconfirmed') {
156
+ const unconfirmedStopSpin = showOutput ? createSpinner(options) : null;
157
+ if (showOutput && !unconfirmedStopSpin) {
158
+ logStatus('info', `found unconfirmed OpenChamber pid ${explicitInstance.pid} on port ${options.port}`, 'HTTP shutdown endpoint is unreachable; stopping by PID');
159
+ }
160
+ unconfirmedStopSpin?.start(`Stopping unconfirmed OpenChamber on port ${options.port}...`);
161
+ const stopped = await stopInstanceProcess(explicitInstance.pid, {
162
+ shutdownWaitMs: 0,
163
+ gracefulTimeoutMs: 2500,
164
+ forceTimeoutMs: 3000,
165
+ }).catch(() => false);
166
+
167
+ if (stopped || !isProcessRunning(explicitInstance.pid)) {
168
+ removePidFile(explicitInstance.pidFilePath);
169
+ removeInstanceFile(explicitInstance.instanceFilePath);
170
+ unconfirmedStopSpin?.stop(`Stopped OpenChamber PID ${explicitInstance.pid}`);
171
+ jsonResults.push({ port: options.port, pid: explicitInstance.pid, runtime: 'unconfirmed', stopped: true });
172
+ if (isJsonMode(options)) {
173
+ printJson({ stoppedCount: 1, results: jsonResults });
174
+ }
175
+ if (showOutput && !unconfirmedStopSpin) {
176
+ logStatus('success', `stopped pid ${explicitInstance.pid}`);
177
+ finish('stop complete');
178
+ }
179
+ printQuietStopResults();
180
+ return;
181
+ }
182
+
183
+ unconfirmedStopSpin?.error(`Could not stop OpenChamber PID ${explicitInstance.pid}`);
184
+ jsonResults.push({ port: options.port, pid: explicitInstance.pid, runtime: 'unconfirmed', stopped: false, reason: 'stop-failed' });
185
+ if (isJsonMode(options)) {
186
+ printJson({
187
+ status: 'error',
188
+ stoppedCount: 0,
189
+ results: jsonResults,
190
+ messages: [{ level: 'error', code: 'STOP_FAILED', message: `Could not stop OpenChamber PID ${explicitInstance.pid}.` }],
191
+ });
192
+ }
193
+ if (showOutput && !unconfirmedStopSpin) {
194
+ logStatus('error', `could not stop pid ${explicitInstance.pid}`);
195
+ finish('failed');
196
+ }
197
+ printQuietStopResults();
198
+ return;
199
+ }
200
+ } else if (runningInstances.length === 0) {
201
+ if (isJsonMode(options)) {
202
+ printJson({ stoppedCount: 0, results: jsonResults });
203
+ }
204
+ if (showOutput) {
205
+ logStatus('info', 'No running OpenChamber instances found');
206
+ finish('nothing to stop');
207
+ }
208
+ printQuietStopResults();
209
+ return;
210
+ }
211
+
212
+ for (const instance of runningInstances) {
213
+ const stopSpin = showOutput ? createSpinner(options) : null;
214
+ if (showOutput && !stopSpin) {
215
+ logStatus('info', `stopping port ${instance.port} (PID: ${instance.pid})`);
216
+ }
217
+ stopSpin?.start(`Stopping OpenChamber on port ${instance.port}...`);
218
+ try {
219
+ const requested = await requestServerShutdown(instance.port, instance.host || options.host);
220
+ const stopped = await stopInstanceProcess(instance.pid, {
221
+ shutdownWaitMs: requested ? 5000 : 0,
222
+ gracefulTimeoutMs: 2500,
223
+ forceTimeoutMs: 3000,
224
+ });
225
+ if (!stopped && isProcessRunning(instance.pid)) {
226
+ throw new Error(`Timed out stopping pid ${instance.pid}`);
227
+ }
228
+ removePidFile(instance.pidFilePath);
229
+ removeInstanceFile(instance.instanceFilePath);
230
+ stopSpin?.stop(`Stopped OpenChamber on port ${instance.port}`);
231
+ jsonResults.push({ port: instance.port, pid: instance.pid, stopped: true });
232
+ if (showOutput && !stopSpin) {
233
+ logStatus('success', `stopped port ${instance.port}`);
234
+ }
235
+ } catch (error) {
236
+ stopSpin?.error(`Failed to stop OpenChamber on port ${instance.port}`);
237
+ jsonResults.push({ port: instance.port, pid: instance.pid, stopped: false, reason: error instanceof Error ? error.message : String(error) });
238
+ if (showOutput) {
239
+ logStatus('error', `error stopping port ${instance.port}`, error.message);
240
+ } else if (!isJsonMode(options) && !isQuietMode(options)) {
241
+ console.error(`Error stopping port ${instance.port}: ${error.message}`);
242
+ }
243
+ }
244
+ }
245
+
246
+ if (isJsonMode(options)) {
247
+ const stoppedCount = jsonResults.filter((entry) => entry.stopped).length;
248
+ const hasFailure = jsonResults.some((entry) => !entry.stopped);
249
+ printJson({
250
+ status: hasFailure ? 'warning' : 'ok',
251
+ stoppedCount,
252
+ results: jsonResults,
253
+ });
254
+ return;
255
+ }
256
+
257
+ finish(`${runningInstances.length} instance(s)`);
258
+ printQuietStopResults();
259
+ }
260
+
261
+ async function restartCommand(options, serveCommand) {
262
+ const commandContext = this && typeof this === 'object' ? this : {};
263
+ const runStop = typeof commandContext.stop === 'function'
264
+ ? commandContext.stop.bind(commandContext)
265
+ : stopCommand;
266
+ const runServe = typeof commandContext.serve === 'function'
267
+ ? commandContext.serve.bind(commandContext)
268
+ : serveCommand;
269
+ const showOutput = shouldRenderHumanOutput(options);
270
+ const restarted = [];
271
+
272
+ if (showOutput) {
273
+ clackIntro('OpenChamber Restart');
274
+ }
275
+
276
+ let runningInstances = await discoverLifecycleInstances(options);
277
+ if (runningInstances.length === 0) {
278
+ if (isJsonMode(options)) {
279
+ printJson({ restartedCount: 0, results: restarted });
280
+ }
281
+ if (showOutput) {
282
+ logStatus('info', 'No running OpenChamber instances to restart');
283
+ clackOutro('nothing to restart');
284
+ } else if (isQuietMode(options)) {
285
+ process.stdout.write('restarted 0\n');
286
+ }
287
+ return;
288
+ }
289
+
290
+ for (const instance of runningInstances) {
291
+ if (instance.runtime === 'desktop') {
292
+ const message = `Port ${instance.port} is managed by OpenChamber Desktop and cannot be restarted with this command.`;
293
+ if (isJsonMode(options)) {
294
+ printJson({
295
+ status: 'warning',
296
+ restartedCount: 0,
297
+ results: [{ fromPort: instance.port, runtime: 'desktop', ok: false, reason: 'desktop-managed' }],
298
+ messages: [{ level: 'warning', code: 'DESKTOP_MANAGED_PORT', message }],
299
+ });
300
+ return;
301
+ }
302
+ if (showOutput) {
303
+ logStatus('warning', `port ${instance.port} is managed by OpenChamber Desktop`, 'cannot be restarted with this command');
304
+ clackOutro('no changes applied');
305
+ } else if (isQuietMode(options)) {
306
+ process.stdout.write('restarted 0\n');
307
+ }
308
+ return;
309
+ }
310
+
311
+ const storedOptions = instance.instanceFilePath
312
+ ? (readInstanceOptions(instance.instanceFilePath) || { port: instance.port })
313
+ : { port: instance.port };
314
+ const instanceHost = storedOptions.host || instance.host || options.host;
315
+ const launchMode = instance.launchMode || 'daemon';
316
+ const isForeground = launchMode === 'foreground';
317
+
318
+ const restartPort = options.explicitPort ? options.port : instance.port;
319
+
320
+ const restartSpin = showOutput ? createSpinner(options) : null;
321
+ if (showOutput && !restartSpin) {
322
+ logStatus('info', `restarting port ${instance.port}`, `mode: ${launchMode}`);
323
+ }
324
+ restartSpin?.start(`Restarting OpenChamber on port ${instance.port}...`);
325
+ try {
326
+ await runStop({
327
+ explicitPort: true,
328
+ port: instance.port,
329
+ host: instanceHost,
330
+ quiet: true,
331
+ suppressQuietOutput: true,
332
+ });
333
+
334
+ // Foreground instances are managed by a process manager (systemd,
335
+ // Docker, etc.) that will restart them automatically after stop.
336
+ // Do not call serve() here — just record the stop as a successful
337
+ // restart and let the process manager handle the actual restart.
338
+ if (isForeground) {
339
+ restarted.push({ fromPort: instance.port, toPort: restartPort, launchMode, ok: true });
340
+ restartSpin?.stop(`Stopped foreground instance on port ${instance.port} (process manager will restart)`);
341
+ if (showOutput && !restartSpin) {
342
+ logStatus('success', `port ${instance.port} stopped`, 'process manager will restart');
343
+ }
344
+ continue;
345
+ }
346
+
347
+ await new Promise((resolve) => setTimeout(resolve, 500));
348
+
349
+ const restartedPort = await runServe({
350
+ port: restartPort,
351
+ host: instanceHost,
352
+ explicitPort: true,
353
+ uiPassword: options.explicitUiPassword ? options.uiPassword : (storedOptions.uiPassword || options.uiPassword),
354
+ apiOnly: storedOptions.apiOnly === true || options.apiOnly === true,
355
+ suppressStartupSummary: true,
356
+ quiet: true,
357
+ suppressUiPasswordWarning: true,
358
+ suppressQuietOutput: true,
359
+ });
360
+ restarted.push({ fromPort: instance.port, toPort: restartedPort, launchMode, ok: true });
361
+ restartSpin?.stop(`Restarted OpenChamber on port ${restartedPort}`);
362
+ if (showOutput && !restartSpin) {
363
+ logStatus('success', `port ${restartedPort} restarted`, `mode: ${launchMode}`);
364
+ }
365
+ } catch (error) {
366
+ const message = error instanceof Error ? error.message : String(error);
367
+ restartSpin?.error(`Failed to restart OpenChamber on port ${instance.port}`);
368
+ if (showOutput && !restartSpin) {
369
+ logStatus('error', `failed to restart port ${instance.port}`, message);
370
+ }
371
+ throw error;
372
+ }
373
+ }
374
+
375
+ if (isJsonMode(options)) {
376
+ printJson({ restartedCount: restarted.length, results: restarted.map((r) => ({ ...r, launchMode: r.launchMode })) });
377
+ return;
378
+ }
379
+
380
+ if (showOutput) {
381
+ clackOutro(`${runningInstances.length} instance(s) restarted`);
382
+ } else if (isQuietMode(options)) {
383
+ process.stdout.write(`restarted ${restarted.length}\n`);
384
+ }
385
+ }
386
+
387
+ function createLifecycleCommands({ serveCommand }) {
388
+ return {
389
+ stop: stopCommand,
390
+ restart(options) {
391
+ return restartCommand.call(this, options, serveCommand);
392
+ },
393
+ };
394
+ }
395
+
396
+ export { createLifecycleCommands };
@@ -0,0 +1,110 @@
1
+ import { getLogFilePath } from './cli-paths.js';
2
+ import { readTailLines, followFile } from './cli-log-files.js';
3
+ import { discoverRunningInstances, getLatestInstance } from './cli-lifecycle.js';
4
+ import {
5
+ intro as clackIntro,
6
+ outro as clackOutro,
7
+ isJsonMode,
8
+ shouldRenderHumanOutput,
9
+ printJson,
10
+ logStatus,
11
+ } from '../cli-output.js';
12
+
13
+ async function logsCommand(options) {
14
+ const showFrames = shouldRenderHumanOutput(options);
15
+ const shouldPrefixLines = options.all || !showFrames;
16
+ let targets = [];
17
+ const running = await discoverRunningInstances();
18
+
19
+ if (options.all) {
20
+ targets = running;
21
+ if (targets.length === 0) {
22
+ throw new Error('No running OpenChamber instance found.');
23
+ }
24
+ } else if (options.explicitPort) {
25
+ const found = running.find((entry) => entry.port === options.port);
26
+ if (!found) {
27
+ throw new Error(`No running OpenChamber instance found on port ${options.port}.`);
28
+ }
29
+ targets = [found];
30
+ } else {
31
+ const latest = getLatestInstance(running);
32
+ if (!latest) {
33
+ throw new Error('No running OpenChamber instance found.');
34
+ }
35
+ targets = [latest];
36
+ if (shouldRenderHumanOutput(options)) {
37
+ logStatus('info', `no port specified; using latest started instance on port ${latest.port}`);
38
+ }
39
+ }
40
+
41
+ if (isJsonMode(options)) {
42
+ if (options.follow) {
43
+ throw new Error('`openchamber logs --json` requires `--no-follow` for deterministic JSON output.');
44
+ }
45
+ const entries = targets.map((target) => {
46
+ const logPath = getLogFilePath(target.port);
47
+ return {
48
+ port: target.port,
49
+ logPath,
50
+ lines: readTailLines(logPath, options.lines),
51
+ };
52
+ });
53
+ printJson({ entries });
54
+ return;
55
+ }
56
+
57
+ if (showFrames) {
58
+ clackIntro('OpenChamber Logs');
59
+ }
60
+
61
+ for (const target of targets) {
62
+ const logPath = getLogFilePath(target.port);
63
+ const lines = readTailLines(logPath, options.lines);
64
+ if (showFrames) {
65
+ logStatus('info', `port ${target.port}`, logPath);
66
+ }
67
+
68
+ for (const line of lines) {
69
+ if (shouldPrefixLines) {
70
+ console.log(`[${target.port}] ${line}`);
71
+ } else {
72
+ console.log(line);
73
+ }
74
+ }
75
+ }
76
+
77
+ if (showFrames) {
78
+ clackOutro(options.follow ? 'following (Ctrl+C to stop)' : 'tail complete');
79
+ }
80
+
81
+ if (!options.follow) {
82
+ return;
83
+ }
84
+
85
+ const unsubs = targets.map((target) => {
86
+ const logPath = getLogFilePath(target.port);
87
+ return followFile(logPath, (line) => {
88
+ if (shouldPrefixLines) {
89
+ console.log(`[${target.port}] ${line}`);
90
+ } else {
91
+ console.log(line);
92
+ }
93
+ });
94
+ });
95
+
96
+ await new Promise((resolve) => {
97
+ const onSignal = () => {
98
+ for (const unsub of unsubs) {
99
+ unsub();
100
+ }
101
+ process.off('SIGINT', onSignal);
102
+ process.off('SIGTERM', onSignal);
103
+ resolve();
104
+ };
105
+ process.on('SIGINT', onSignal);
106
+ process.on('SIGTERM', onSignal);
107
+ });
108
+ }
109
+
110
+ export { logsCommand };