@oussema_mili/test-pkg-123 1.1.43 → 1.1.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli-commands.js CHANGED
@@ -754,7 +754,7 @@ function setupCLICommands(program, startServerFunction) {
754
754
 
755
755
  console.log("");
756
756
 
757
- // Agent running status - check daemon first, then fallback to port check
757
+ // Agent running status - only trust daemon state
758
758
  const daemonStatus = getDaemonStatus();
759
759
  if (daemonStatus.running) {
760
760
  console.log(
@@ -766,15 +766,10 @@ function setupCLICommands(program, startServerFunction) {
766
766
  chalk.gray(` Uptime: ${formatDaemonUptime(daemonStatus.uptime)}`),
767
767
  );
768
768
  } else {
769
- const isRunning = await checkAgentRunning(WS_PORT);
770
- if (isRunning) {
771
- console.log(chalk.green(`Agent: Running (port ${WS_PORT})`));
772
- } else {
773
- console.log(chalk.yellow("Agent: Not Running"));
774
- console.log(
775
- chalk.gray(' Run "fenwave service start" to start the agent'),
776
- );
777
- }
769
+ console.log(chalk.yellow("Agent: Not Running"));
770
+ console.log(
771
+ chalk.gray(' Run "fenwave service start" to start the agent'),
772
+ );
778
773
  }
779
774
 
780
775
  console.log("");
@@ -1887,29 +1882,7 @@ function setupCLICommands(program, startServerFunction) {
1887
1882
  formatDaemonUptime(daemonStatus.uptime),
1888
1883
  );
1889
1884
  } else {
1890
- // Fallback to checking port
1891
- const isAgentRunning = await checkAgentRunning(WS_PORT);
1892
- if (isAgentRunning) {
1893
- try {
1894
- const agentStartTime = await agentStore.loadAgentStartTime();
1895
- if (agentStartTime) {
1896
- const currentTime = Date.now();
1897
- const agentUptimeMs = currentTime - agentStartTime.getTime();
1898
- console.log(chalk.blue("Uptime:"), formatUptime(agentUptimeMs));
1899
- } else {
1900
- console.log(chalk.blue("Uptime:"), "0 seconds");
1901
- }
1902
- } catch (error) {
1903
- console.log(chalk.blue("Uptime:"), "0 seconds");
1904
- }
1905
- } else {
1906
- console.log(chalk.blue("Status:"), chalk.red("Agent Not Running"));
1907
- try {
1908
- await agentStore.clearAgentInfo();
1909
- } catch (error) {
1910
- // Ignore cleanup errors
1911
- }
1912
- }
1885
+ console.log(chalk.blue("Status:"), chalk.red("Agent Not Running"));
1913
1886
  }
1914
1887
  process.exit(0);
1915
1888
  } catch (error) {
@@ -4,7 +4,7 @@ import path from 'path';
4
4
  import chalk from 'chalk';
5
5
  import { loadConfig, DEFAULT_WS_PORT, DEFAULT_CONTAINER_PORT } from './store/configStore.js';
6
6
  import { getDaemonState } from './store/daemonStore.js';
7
- import { findAvailableContainerPort } from './utils/portUtils.js';
7
+ import { findAvailableContainerPort, isPortAvailable } from './utils/portUtils.js';
8
8
 
9
9
  // Load static configuration (ports are resolved dynamically)
10
10
  const config = loadConfig();
@@ -176,13 +176,24 @@ class ContainerManager {
176
176
  // If containerPort is 0, find an available port
177
177
  if (APP_PORT === 0) {
178
178
  try {
179
- APP_PORT = await findAvailableContainerPort(DEFAULT_CONTAINER_PORT);
179
+ APP_PORT = await findAvailableContainerPort(DEFAULT_CONTAINER_PORT, 100, [WS_PORT]);
180
180
  console.log(chalk.blue(`📍 Auto-assigned container port: ${APP_PORT}`));
181
181
  } catch (error) {
182
182
  throw new Error(`Failed to find available container port: ${error.message}`);
183
183
  }
184
184
  }
185
185
 
186
+ // If the desired container port conflicts with the WebSocket port or is unavailable, pick another port
187
+ if (APP_PORT === WS_PORT || !(await isPortAvailable(APP_PORT))) {
188
+ try {
189
+ const newPort = await findAvailableContainerPort(DEFAULT_CONTAINER_PORT, 100, [WS_PORT]);
190
+ console.log(chalk.yellow(`⚠️ Port ${APP_PORT} is unavailable. Using ${newPort} instead.`));
191
+ APP_PORT = newPort;
192
+ } catch (err) {
193
+ throw new Error(`Failed to resolve container port conflict: ${err.message}`);
194
+ }
195
+ }
196
+
186
197
  // Check Docker availability
187
198
  const dockerAvailable = await this.checkDockerAvailable();
188
199
  if (!dockerAvailable) {
@@ -313,21 +313,6 @@ export async function runAgent(options = {}) {
313
313
  // Initialize registry store
314
314
  await registryStore.initialize();
315
315
 
316
- // Start container with dynamic ports
317
- log('Starting container...');
318
- let actualContainerPort = preferredContainerPort;
319
- try {
320
- actualContainerPort = await containerManager.startContainer({
321
- wsPort: actualPort,
322
- containerPort: preferredContainerPort,
323
- });
324
- log(`Container started successfully on port ${actualContainerPort}`);
325
- } catch (containerError) {
326
- log(`Failed to start container: ${containerError.message}`, 'warn');
327
- log('Starting agent without container...');
328
- actualContainerPort = preferredContainerPort || DEFAULT_CONTAINER_PORT;
329
- }
330
-
331
316
  // Create HTTP server with download endpoint handler
332
317
  const agentId = uuidv4();
333
318
  const existingWsToken = readWsToken();
@@ -401,14 +386,14 @@ export async function runAgent(options = {}) {
401
386
  // Initialize agent start time
402
387
  await initializeAgentStartTime();
403
388
 
404
- // Save daemon state
389
+ // Save daemon pid and preliminary state (containerPort updated after container start)
405
390
  saveDaemonPid(process.pid);
406
391
  saveDaemonState({
407
392
  pid: process.pid,
408
393
  port: actualPort,
409
- containerPort: actualContainerPort,
394
+ containerPort: null,
410
395
  startTime: new Date().toISOString(),
411
- status: 'running',
396
+ status: 'starting',
412
397
  userEntityRef: session.userEntityRef,
413
398
  isDaemon,
414
399
  });
@@ -442,10 +427,30 @@ export async function runAgent(options = {}) {
442
427
  pollInterval,
443
428
  };
444
429
 
430
+ // Now that WebSocket is bound, start container (so it cannot take the WS port)
431
+ log('Starting container (after WebSocket bind)...');
432
+ let actualContainerPort = preferredContainerPort;
433
+ try {
434
+ actualContainerPort = await containerManager.startContainer({
435
+ wsPort: actualPort,
436
+ containerPort: preferredContainerPort,
437
+ });
438
+ log(`Container started successfully on port ${actualContainerPort}`);
439
+ } catch (containerError) {
440
+ log(`Failed to start container: ${containerError.message}`, 'warn');
441
+ log('Continuing without container...');
442
+ actualContainerPort = preferredContainerPort || DEFAULT_CONTAINER_PORT;
443
+ }
444
+
445
+ // Update daemon state now that containerPort is known
446
+ updateDaemonState({
447
+ port: actualPort,
448
+ containerPort: actualContainerPort,
449
+ status: 'running',
450
+ });
451
+
445
452
  // Display startup info
446
- console.log(
447
- chalk.green('\n' + '='.repeat(66))
448
- );
453
+ console.log(chalk.green('\n' + '='.repeat(66)));
449
454
  console.log(chalk.green(' Fenwave Agent Started Successfully'));
450
455
  console.log(chalk.green('='.repeat(66) + '\n'));
451
456
  console.log(chalk.white(' Fenwave DevApp Dashboard:'));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oussema_mili/test-pkg-123",
3
- "version": "1.1.43",
3
+ "version": "1.1.45",
4
4
  "description": "Fenwave Docker Agent and CLI",
5
5
  "keywords": [
6
6
  "fenwave",
@@ -62,8 +62,15 @@ export async function isPortInUse(port) {
62
62
  * @param {number} maxAttempts - Maximum number of ports to try (default: 10)
63
63
  * @returns {Promise<number>} Available port number
64
64
  */
65
- export async function findAvailableContainerPort(startPort = DEFAULT_CONTAINER_PORT, maxAttempts = 10) {
66
- return findAvailablePort(startPort, maxAttempts);
65
+ export async function findAvailableContainerPort(startPort = DEFAULT_CONTAINER_PORT, maxAttempts = 100, excludePorts = []) {
66
+ for (let i = 0; i < maxAttempts; i++) {
67
+ const port = startPort + i;
68
+ if (excludePorts && excludePorts.includes(port)) continue;
69
+ if (await isPortAvailable(port)) {
70
+ return port;
71
+ }
72
+ }
73
+ throw new Error(`No available container port found in range ${startPort}-${startPort + maxAttempts - 1}`);
67
74
  }
68
75
 
69
76
  /**