-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathcli-tools.ts
More file actions
executable file
·1431 lines (1216 loc) · 44.7 KB
/
Copy pathcli-tools.ts
File metadata and controls
executable file
·1431 lines (1216 loc) · 44.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bun
import { parseArgs } from 'util';
import { StorageManager } from './storage.js';
import { ProcessMonitor } from './process-monitor.js';
import {
ProcessRunnerConfig,
ProcessInfo,
MonitoringOptions,
LogStoreOptions as LogStoreOptionsType,
ErrorStoreOptions as ErrorStoreOptionsType,
LogFilter,
LogCursor,
LogLevel,
StoredError,
StoredLog,
SimpleError,
Result,
DEFAULT_MONITORING_OPTIONS,
DEFAULT_STORAGE_OPTIONS,
DEFAULT_LOG_STORE_OPTIONS,
getDataDirectory,
getErrorDbPath,
getLogDbPath
} from './types.js';
// Instance ID validation pattern - alphanumeric with dashes and underscores
const INSTANCE_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
const MAX_INSTANCE_ID_LENGTH = 64;
/**
* Validate instance ID format to prevent path traversal and other issues
*/
function validateInstanceId(id: string): void {
if (!id || id.length === 0) {
throw new Error('Instance ID is required');
}
if (id.length > MAX_INSTANCE_ID_LENGTH) {
throw new Error(`Instance ID must be ${MAX_INSTANCE_ID_LENGTH} characters or less`);
}
if (!INSTANCE_ID_PATTERN.test(id)) {
throw new Error('Instance ID must start with alphanumeric and contain only alphanumeric, dash, or underscore');
}
}
/**
* Safely parse integer argument with validation
*/
function parseIntArg(args: Record<string, unknown>, key: string): number | undefined {
const value = args[key];
if (value === undefined || value === null) {
return undefined;
}
const parsed = parseInt(String(value), 10);
if (isNaN(parsed)) {
throw new Error(`Invalid integer value for --${key}: ${value}`);
}
return parsed;
}
class SafeJSON {
static stringify(data: unknown, space?: number): string {
try {
const seen = new WeakSet();
const json = JSON.stringify(data, (_key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular Reference]';
}
seen.add(value);
}
return value;
}, space);
return json;
} catch {
// Fallback for any stringify errors
return JSON.stringify({
error: 'Failed to serialize data',
type: typeof data,
string: String(data).substring(0, 200)
}, null, space);
}
}
static parse(text: string): unknown {
try {
return JSON.parse(text);
} catch {
// Return error object for failed parsing
return {
success: false,
error: 'Invalid JSON format',
rawText: text.substring(0, 200)
};
}
}
}
class SafeCleanup {
/**
* Safely close storage manager.
* Storage.close() is synchronous, so we just wrap it in try-catch.
*/
static closeStorage(storage: StorageManager | null): void {
if (!storage) return;
try {
storage.close();
} catch (error) {
console.warn('Storage close error:', error);
// Don't throw - we're in cleanup
}
}
}
class OutputFormatter {
static formatOutput(data: unknown, format: 'json' | 'table' | 'raw' = 'json'): void {
switch (format) {
case 'json':
console.log(SafeJSON.stringify(data, 2));
break;
case 'raw':
if (typeof data === 'string') {
console.log(data);
} else {
console.log(String(data));
}
break;
case 'table':
// Table formatting is handled by specific formatters
console.log(SafeJSON.stringify(data, 2));
break;
}
}
static formatError(error: string, additionalData?: Record<string, unknown>): void {
const errorResponse = {
success: false,
error,
...additionalData
};
console.log(SafeJSON.stringify(errorResponse, 2));
}
static formatSuccess(message: string, data?: unknown): void {
const successResponse: Record<string, unknown> = {
success: true,
message
};
if (data) {
successResponse.data = data;
}
console.log(SafeJSON.stringify(successResponse, 2));
}
static printErrorsTable(errors: readonly StoredError[]): void {
if (errors.length === 0) {
console.log('No errors found.');
return;
}
console.log('Timestamp'.padEnd(20) + 'Level'.padEnd(10) + 'Message');
console.log('-'.repeat(80));
for (const error of errors) {
const timestamp = new Date(error.timestamp).toISOString().slice(0, 16).replace('T', ' ');
const level = `L${error.level}`.padEnd(9);
const message = error.message.length > 50 ? error.message.substring(0, 47) + '...' : error.message;
console.log(`${timestamp} ${level} ${message}`);
if (error.occurrenceCount > 1) {
console.log(''.padEnd(30) + `(occurred ${error.occurrenceCount} times)`);
}
}
}
static printLogsTable(logs: readonly StoredLog[]): void {
if (logs.length === 0) {
console.log('No logs found.');
return;
}
console.log('Timestamp'.padEnd(20) + 'Level'.padEnd(8) + 'Stream'.padEnd(8) + 'Source'.padEnd(15) + 'Message');
console.log('-'.repeat(100));
for (const log of logs) {
const timestamp = new Date(log.timestamp).toISOString().slice(0, 16).replace('T', ' ');
const level = log.level.padEnd(7);
const stream = log.stream.padEnd(7);
const source = (log.source || 'unknown').padEnd(14);
const message = log.message.length > 50 ? log.message.substring(0, 47) + '...' : log.message;
console.log(`${timestamp} ${level} ${stream} ${source} ${message}`);
}
}
}
class ProcessCommands {
private static activeRunners = new Map<string, ProcessRunner>();
static async start(options: {
instanceId: string;
command: string;
args: string[];
cwd?: string;
port?: string;
healthCheckInterval?: number;
maxRestarts?: number;
restartDelay?: number;
maxErrors?: number;
retentionDays?: number;
logRetentionHours?: number;
}): Promise<void> {
try {
// Check if already running
if (this.activeRunners.has(options.instanceId)) {
OutputFormatter.formatError(`Process ${options.instanceId} is already running`);
process.exit(1);
}
// Set PORT environment variable if provided
if (options.port) {
process.env.PORT = options.port;
}
// Build configuration
const envVars: Record<string, string> = {};
if (options.port) {
envVars.PORT = options.port;
}
const expectedPort = options.port ? Number.parseInt(options.port, 10) : undefined;
const hasExpectedPort = Number.isFinite(expectedPort);
// Default behavior for port-bound dev servers (e.g. Vite):
// - Probe every 10s
// - Retry for ~2 minutes (12 * 10s)
const defaultHealthCheckInterval = hasExpectedPort ? 10000 : DEFAULT_MONITORING_OPTIONS.healthCheckInterval;
const defaultRestartDelay = hasExpectedPort ? 1000 : DEFAULT_MONITORING_OPTIONS.restartDelay;
const defaultMaxRestarts = hasExpectedPort ? 120 : DEFAULT_MONITORING_OPTIONS.maxRestarts;
const monitoring: MonitoringOptions = {
...DEFAULT_MONITORING_OPTIONS,
expectedPort: hasExpectedPort ? expectedPort : undefined,
healthCheckInterval: options.healthCheckInterval ?? defaultHealthCheckInterval,
maxRestarts: options.maxRestarts ?? defaultMaxRestarts,
restartDelay: options.restartDelay ?? defaultRestartDelay,
env: envVars
};
const errorStorage: ErrorStoreOptionsType = {
...DEFAULT_STORAGE_OPTIONS,
maxErrors: options.maxErrors ?? DEFAULT_STORAGE_OPTIONS.maxErrors,
retentionDays: options.retentionDays ?? DEFAULT_STORAGE_OPTIONS.retentionDays
};
const logStorage: LogStoreOptionsType = {
...DEFAULT_LOG_STORE_OPTIONS,
retentionHours: options.logRetentionHours ?? DEFAULT_LOG_STORE_OPTIONS.retentionHours
};
const config: ProcessRunnerConfig = {
instanceId: options.instanceId,
command: options.command,
args: options.args,
cwd: options.cwd || process.cwd(),
monitoring,
storage: {
error: errorStorage,
log: logStorage
}
};
console.log('Starting Process Monitor:');
console.log(` Instance ID: ${options.instanceId}`);
console.log(` Command: ${options.command} ${options.args.join(' ')}`);
console.log(` Working Directory: ${config.cwd}`);
console.log(` Max Restarts: ${monitoring.maxRestarts}`);
console.log(` Restart Delay: ${monitoring.restartDelay}ms`);
console.log(` Health Check Interval: ${monitoring.healthCheckInterval ?? DEFAULT_MONITORING_OPTIONS.healthCheckInterval}ms`);
if (monitoring.expectedPort) {
console.log(` Expected Port: ${monitoring.expectedPort}`);
}
// Create and start ProcessRunner with storage options
const runner = new ProcessRunner(config, {
error: errorStorage,
log: logStorage
});
const startResult = await runner.start();
if (!startResult.success && 'error' in startResult) {
OutputFormatter.formatError(`Failed to start process: ${startResult.error.message}`);
process.exit(1);
}
// Store active runner
this.activeRunners.set(options.instanceId, runner);
if (startResult.success) {
console.log(`Process monitoring started successfully. PID: ${startResult.data.pid}`);
console.log('Process is active. Press Ctrl+C to stop.');
}
// Setup periodic status reporting
const statusInterval = setInterval(() => {
const processInfo = runner.getProcessInfo();
if (processInfo && processInfo.startTime) {
const uptime = Math.floor((Date.now() - processInfo.startTime.getTime()) / 1000);
console.log(`[STATUS] Process ${processInfo.id} running for ${uptime}s (restarts: ${processInfo.restartCount})`);
} else if (processInfo) {
console.log(`[STATUS] Process ${processInfo.id} running (restarts: ${processInfo.restartCount})`);
}
}, 60000); // Every minute
// Setup graceful shutdown with race condition protection
let isShuttingDown = false;
const gracefulShutdown = async (signal: string) => {
if (isShuttingDown) {
console.log(`\nAlready shutting down, ignoring ${signal}`);
return;
}
isShuttingDown = true;
console.log(`\nReceived ${signal}. Initiating graceful shutdown...`);
clearInterval(statusInterval);
try {
await runner.stop();
this.activeRunners.delete(options.instanceId);
console.log('Graceful shutdown completed');
} catch (shutdownError) {
console.error('Error during shutdown:', shutdownError);
}
process.exit(0);
};
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('SIGHUP', () => gracefulShutdown('SIGHUP'));
// Keep alive (process will exit via signal handlers)
await new Promise(() => {}); // Never resolves
} catch (error) {
OutputFormatter.formatError(`Process start failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
process.exit(1);
}
}
static async stop(options: { instanceId: string; force?: boolean }): Promise<void> {
try {
const runner = this.activeRunners.get(options.instanceId);
if (!runner) {
OutputFormatter.formatError(`Process ${options.instanceId} is not running`);
process.exit(1);
}
if (runner) {
const stopResult = await runner.stop(options.force);
if (!stopResult.success && 'error' in stopResult) {
OutputFormatter.formatError(`Failed to stop process: ${stopResult.error.message}`);
process.exit(1);
}
this.activeRunners.delete(options.instanceId);
OutputFormatter.formatSuccess(`Process ${options.instanceId} stopped successfully`);
}
} catch (error) {
OutputFormatter.formatError(`Process stop failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
process.exit(1);
}
}
static async status(options: { instanceId?: string }): Promise<void> {
try {
if (options.instanceId) {
const runner = this.activeRunners.get(options.instanceId);
if (!runner) {
OutputFormatter.formatError(`Process ${options.instanceId} is not running`);
return;
}
const stats = runner.getStats();
OutputFormatter.formatOutput({
success: true,
instanceId: options.instanceId,
status: 'running',
...stats
});
} else {
// List all active processes
const processes = Array.from(this.activeRunners.entries()).map(([instanceId, runner]) => ({
instanceId,
stats: runner.getStats()
}));
OutputFormatter.formatOutput({
success: true,
activeProcesses: processes.length,
processes
});
}
} catch (error) {
OutputFormatter.formatError(`Status check failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
class ProcessRunner {
private config: ProcessRunnerConfig;
private storage: StorageManager;
private monitor?: ProcessMonitor;
private isRunning = false;
constructor(config: ProcessRunnerConfig, storageOptions?: { error?: ErrorStoreOptionsType; log?: LogStoreOptionsType }) {
this.config = config;
const options = storageOptions || config.storage || {};
this.storage = new StorageManager(undefined, undefined, options);
}
async start(): Promise<Result<ProcessInfo>> {
try {
if (this.isRunning) {
return { success: false, error: new Error('ProcessRunner is already running') };
}
const processInfo: ProcessInfo = {
id: `proc-${this.config.instanceId}-${Date.now()}`,
instanceId: this.config.instanceId,
command: this.config.command,
args: this.config.args,
cwd: this.config.cwd,
status: 'starting',
startTime: new Date(),
restartCount: 0
};
this.monitor = new ProcessMonitor(processInfo, this.storage, this.config.monitoring);
this.setupMonitorEventHandlers();
const startResult = await this.monitor.start();
if (!startResult.success) {
return startResult;
}
this.isRunning = true;
return startResult;
} catch (error) {
return {
success: false,
error: error instanceof Error ? error : new Error('Unknown error starting ProcessRunner')
};
}
}
async stop(force = false): Promise<Result<boolean>> {
try {
if (!this.isRunning || !this.monitor) {
return { success: true, data: true };
}
const stopResult = await this.monitor.stop();
this.isRunning = false;
await this.monitor.cleanup();
this.monitor = undefined;
this.storage.close();
// Convert Result<void> to Result<boolean>
if (stopResult.success) {
return { success: true, data: true };
} else if ('error' in stopResult) {
return { success: false, error: stopResult.error };
} else {
return { success: false, error: new Error('Unknown error stopping process') };
}
} catch (error) {
return {
success: false,
error: error instanceof Error ? error : new Error('Unknown error stopping ProcessRunner')
};
}
}
getProcessInfo(): ProcessInfo | null {
return this.monitor?.getProcessInfo() || null;
}
getStats(): Record<string, unknown> {
if (!this.monitor) {
return { error: 'Monitor not initialized' };
}
const processInfo = this.monitor.getProcessInfo();
return {
processId: processInfo.id,
instanceId: processInfo.instanceId,
pid: processInfo.pid,
status: processInfo.status,
startTime: processInfo.startTime,
restartCount: processInfo.restartCount,
config: {
instanceId: this.config.instanceId,
command: this.config.command,
args: this.config.args,
cwd: this.config.cwd
}
};
}
private setupMonitorEventHandlers(): void {
if (!this.monitor) return;
this.monitor.on('process_started', (event) => {
console.log(`[${event.timestamp.toISOString()}] Process started: PID ${event.pid}`);
});
this.monitor.on('process_stopped', (event) => {
console.log(`[${event.timestamp.toISOString()}] Process stopped: ${event.reason}`);
});
this.monitor.on('error_detected', (event) => {
const { error } = event;
console.error(`[${event.timestamp.toISOString()}] Error detected [Level ${error.level}]: ${error.message}`);
});
this.monitor.on('process_crashed', (event) => {
console.error(`[${event.timestamp.toISOString()}] Process crashed: Exit code ${event.exitCode}, Signal: ${event.signal}`);
if (event.willRestart) {
console.log('Process will be restarted automatically');
}
});
}
}
class ErrorCommands {
static async list(options: {
instanceId: string;
minLevel?: number;
maxLevel?: number;
since?: string;
until?: string;
limit?: number;
offset?: number;
format?: 'json' | 'table' | 'raw';
dbPath?: string;
reset?: boolean;
}): Promise<void> {
let storage: StorageManager | null = null;
try {
storage = new StorageManager(options.dbPath);
const result = storage.getErrors(options.instanceId);
if (!result.success && 'error' in result) {
throw result.error;
}
let filteredErrors = result.data;
// Apply filters
if (options.minLevel !== undefined) {
filteredErrors = filteredErrors.filter(error =>
error.level >= options.minLevel!
);
}
if (options.maxLevel !== undefined) {
filteredErrors = filteredErrors.filter(error =>
error.level <= options.maxLevel!
);
}
if (options.since) {
const sinceDate = new Date(options.since);
filteredErrors = filteredErrors.filter(error =>
new Date(error.timestamp) >= sinceDate
);
}
if (options.until) {
const untilDate = new Date(options.until);
filteredErrors = filteredErrors.filter(error =>
new Date(error.timestamp) <= untilDate
);
}
// Apply pagination
const offset = options.offset || 0;
const limit = options.limit || 100;
const paginatedErrors = filteredErrors.slice(offset, offset + limit);
const response = {
success: true,
errors: paginatedErrors,
summary: {
totalErrors: filteredErrors.length,
errorsByLevel: this.countByField(filteredErrors, 'level'),
hasMore: offset + paginatedErrors.length < filteredErrors.length
}
};
let resetInfo: { clearedCount: number } | undefined;
if (options.reset) {
if (!storage) {
throw new Error('Storage not initialized for reset operation');
}
const clearResult = storage.clearErrors(options.instanceId);
if (!clearResult.success) {
if ('error' in clearResult) {
throw clearResult.error;
}
throw new Error('Failed to clear errors');
}
resetInfo = { clearedCount: clearResult.data.clearedCount };
}
if (options.format === 'table') {
OutputFormatter.printErrorsTable(paginatedErrors);
if (resetInfo) {
console.log(`\nCleared ${resetInfo.clearedCount} stored errors.`);
}
} else {
const outputPayload = resetInfo ? { ...response, reset: resetInfo } : response;
OutputFormatter.formatOutput(outputPayload, options.format);
}
// Explicit exit after successful execution
process.exit(0);
} catch (error) {
try {
OutputFormatter.formatError(
error instanceof Error ? error.message : String(error),
{ instanceId: options.instanceId }
);
} catch (formatError) {
// Fallback if formatting fails
console.error(SafeJSON.stringify({ success: false, error: String(error) }));
}
process.exit(1);
} finally {
// Single cleanup point - close storage only once
SafeCleanup.closeStorage(storage);
}
}
static async stats(options: { instanceId: string; dbPath?: string }): Promise<void> {
const storage = new StorageManager(options.dbPath);
try {
const result = storage.getErrorSummary(options.instanceId);
if (!result.success && 'error' in result) {
throw result.error;
}
const response = {
success: true,
instanceId: options.instanceId,
...result.data
};
OutputFormatter.formatOutput(response);
// Explicit exit after successful execution
process.exit(0);
} catch (error) {
OutputFormatter.formatError(
error instanceof Error ? error.message : String(error),
{ instanceId: options.instanceId }
);
process.exit(1);
} finally {
SafeCleanup.closeStorage(storage);
}
}
static async clear(options: { instanceId: string; confirm: boolean; dbPath?: string }): Promise<void> {
if (!options.confirm) {
OutputFormatter.formatError('--confirm flag required to clear errors');
process.exit(1);
}
const storage = new StorageManager(options.dbPath);
try {
const result = storage.clearErrors(options.instanceId);
if (!result.success && 'error' in result) {
throw result.error;
}
const response = {
success: true,
message: `Cleared ${result.data.clearedCount} errors for instance ${options.instanceId}`,
clearedCount: result.data.clearedCount
};
OutputFormatter.formatOutput(response);
// Explicit exit after successful execution
process.exit(0);
} catch (error) {
OutputFormatter.formatError(
error instanceof Error ? error.message : String(error),
{ instanceId: options.instanceId }
);
process.exit(1);
} finally {
SafeCleanup.closeStorage(storage);
}
}
private static countByField(errors: readonly StoredError[], field: keyof StoredError): Record<string, number> {
const counts: Record<string, number> = {};
for (const error of errors) {
const value = String(error[field]);
counts[value] = (counts[value] || 0) + 1;
}
return counts;
}
}
class LogCommands {
static async list(options: {
instanceId: string;
levels?: LogLevel[];
streams?: ('stdout' | 'stderr')[];
since?: string;
until?: string;
limit?: number;
offset?: number;
format?: 'json' | 'table' | 'raw';
dbPath?: string;
}): Promise<void> {
const storage = new StorageManager(undefined, options.dbPath);
try {
const filter: LogFilter = {
instanceId: options.instanceId,
levels: options.levels,
streams: options.streams,
since: options.since ? new Date(options.since) : undefined,
until: options.until ? new Date(options.until) : undefined,
limit: options.limit || 100,
offset: options.offset || 0,
sortOrder: 'desc'
};
const result = storage.getLogs(filter);
if (!result.success && 'error' in result) {
throw result.error;
}
const response = result.data;
if (options.format === 'table') {
OutputFormatter.printLogsTable(response.logs);
} else if (options.format === 'raw') {
response.logs.forEach(log => console.log(log.message));
} else {
OutputFormatter.formatOutput(response, options.format);
}
// Explicit exit after successful execution
process.exit(0);
} catch (error) {
OutputFormatter.formatError(
error instanceof Error ? error.message : String(error),
{ instanceId: options.instanceId }
);
process.exit(1);
} finally {
SafeCleanup.closeStorage(storage);
}
}
static async get(options: {
instanceId: string;
format?: 'json' | 'raw';
reset?: boolean;
durationSeconds?: number;
}): Promise<void> {
try {
const { promises: fs } = require('fs');
const { join } = require('path');
const { randomUUID } = require('crypto');
const logFilePath = join(getDataDirectory(), `${options.instanceId}-process.log`);
const lockFilePath = `${logFilePath}.lock`;
const tempPath = `${logFilePath}.tmp.${randomUUID()}.${process.pid}`;
let logs = '';
const LOCK_STALE_MS = 30000; // Must match FileLock in process-monitor.ts
const MAX_RETRIES = 10;
const RETRY_DELAY_MS = 50;
// File-based locking coordinated with SimpleLogManager
const acquireLock = async (): Promise<boolean> => {
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
try {
await fs.writeFile(lockFilePath, `${process.pid}:${Date.now()}`, { flag: 'wx' });
return true;
} catch (error: unknown) {
const fsError = error as { code?: string };
if (fsError?.code === 'EEXIST') {
// Lock exists - check if stale
try {
const content = await fs.readFile(lockFilePath, 'utf8');
const [, timestamp] = content.split(':');
const lockTime = parseInt(timestamp, 10);
if (Date.now() - lockTime > LOCK_STALE_MS) {
// Stale lock - remove and retry
await fs.unlink(lockFilePath).catch(() => {});
continue;
}
} catch {
// Can't read lock file - try again
}
// Wait and retry
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS + Math.random() * RETRY_DELAY_MS));
} else {
return false;
}
}
}
return false;
};
const releaseLock = async (): Promise<void> => {
try {
await fs.unlink(lockFilePath);
} catch {
// Ignore lock release errors
}
};
const lockAcquired = await acquireLock();
if (!lockAcquired) {
throw new Error('Could not acquire file lock for log operation');
}
try {
if (options.reset) {
// Reset mode: Atomic operation to read and clear the file
try {
await fs.rename(logFilePath, tempPath);
// Create new empty log file immediately
await fs.writeFile(logFilePath, '', 'utf8').catch(() => {});
// Read from temp file and clean up
try {
logs = await fs.readFile(tempPath, 'utf8');
await fs.unlink(tempPath).catch(() => {}); // Clean up temp file
} catch {
// If we can't read temp file, at least clean it up
await fs.unlink(tempPath).catch(() => {});
logs = '';
}
} catch (error: unknown) {
// File doesn't exist yet, return empty
const fsError = error as { code?: string };
if (fsError?.code === 'ENOENT') {
logs = '';
} else {
throw error;
}
}
} else {
// Read-only mode: Just read the file without resetting
try {
logs = await fs.readFile(logFilePath, 'utf8');
} catch (error: unknown) {
// File doesn't exist yet, return empty
const fsError = error as { code?: string };
if (fsError?.code === 'ENOENT') {
logs = '';
} else {
throw error;
}
}
}
} finally {
await releaseLock();
}
// Filter logs by duration if specified
if (options.durationSeconds && options.durationSeconds > 0) {
logs = LogCommands.filterLogsByDuration(logs, options.durationSeconds);
}
if (options.format === 'raw') {
console.log(logs);
} else {
const response = {
success: true,
logs: logs,
instanceId: options.instanceId
};
OutputFormatter.formatOutput(response, options.format);
}
// Explicit exit after successful execution
process.exit(0);
} catch (error) {
OutputFormatter.formatError(
error instanceof Error ? error.message : String(error),
{ instanceId: options.instanceId }
);
process.exit(1);
}
}
/**
* Filter logs by duration (keep only logs newer than X seconds ago)
* Log format: [2025-10-17T05:30:24.985Z] [stdout] content
*/
static filterLogsByDuration(logs: string, durationSeconds: number): string {
if (!logs || logs.trim().length === 0) {
return logs;
}
const lines = logs.split('\n');
const now = Date.now();
const cutoffTime = now - (durationSeconds * 1000);
const filteredLines = lines.filter(line => {
// Match log format: [ISO_TIMESTAMP] [stream] content
const timestampMatch = line.match(/^\[([^\]]+)\]/);
if (!timestampMatch) {
// If no timestamp, keep the line (might be continuation of previous log)
return true;
}
try {
const timestamp = new Date(timestampMatch[1]).getTime();
return timestamp >= cutoffTime;
} catch (error) {
// If timestamp parsing fails, keep the line
return true;
}
});
return filteredLines.join('\n');
}
static async stats(options: { instanceId: string; dbPath?: string }): Promise<void> {
const storage = new StorageManager(undefined, options.dbPath);
try {
const result = storage.getLogStats(options.instanceId);
if (!result.success && 'error' in result) {
throw result.error;
}
const response = {
success: true,
instanceId: options.instanceId,
...result.data
};
OutputFormatter.formatOutput(response);
// Explicit exit after successful execution
process.exit(0);
} catch (error) {
OutputFormatter.formatError(
error instanceof Error ? error.message : String(error),
{ instanceId: options.instanceId }
);
process.exit(1);
} finally {
SafeCleanup.closeStorage(storage);
}
}
static async clear(options: { instanceId: string; confirm: boolean; dbPath?: string }): Promise<void> {
if (!options.confirm) {
OutputFormatter.formatError('--confirm flag required to clear logs');
process.exit(1);
}
const storage = new StorageManager(undefined, options.dbPath);
try {
const result = storage.clearLogs(options.instanceId);