-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.ts
More file actions
544 lines (481 loc) · 21.2 KB
/
cli.ts
File metadata and controls
544 lines (481 loc) · 21.2 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
#!/usr/bin/env tsx
/**
* JTAG CLI - Command Line Interface for JTAG System
*
* Translates command line arguments to JTAGClient calls and handles responses.
* This is the main entry point that ./jtag forwards to.
*/
import { JTAGClientServer } from './system/core/client/server/JTAGClientServer';
import type { JTAGClientConnectOptions } from './system/core/client/shared/JTAGClient';
import { EntryPointAdapter } from './system/core/entry-points/EntryPointAdapter';
import { systemOrchestrator } from './system/orchestration/SystemOrchestrator';
import { loadInstanceConfigForContext } from './system/shared/BrowserSafeConfig.js';
import { COMMANDS } from './shared/generated-command-constants';
import { DATA_COMMANDS } from './commands/data/shared/DataCommandConstants';
import { FILE_COMMANDS } from './commands/file/shared/FileCommandConstants';
import { USER_COMMANDS } from './commands/shared/SystemCommandConstants';
import { CODE_COMMANDS } from './commands/development/code/shared/CodeCommandConstants';
import * as fs from 'fs';
import * as path from 'path';
// Check for verbose flag EARLY to control module initialization logging
if (process.argv.includes('--verbose')) {
process.env.JTAG_VERBOSE = '1';
}
// CRITICAL: Initialize SecretManager to load config.env into process.env SYNCHRONOUSLY
// ServerConfig needs HTTP_PORT and WS_PORT from process.env
// Use require() to avoid bundling SecretManager in browser builds
if (typeof require !== 'undefined' && typeof process !== 'undefined') {
const { SecretManager } = require('./system/secrets/SecretManager');
SecretManager.getInstance().initializeSync();
}
// Load config once at startup
const instanceConfig = loadInstanceConfigForContext();
/**
* Get or create a persistent session ID for CLI continuity
* This ensures all CLI commands in a session use the same browser session
*/
function getPersistentSessionId(): string | undefined {
try {
// Use the same path resolution as the instance config
const exampleDir = instanceConfig.paths.directory;
const sessionFile = path.join(exampleDir, '.continuum', 'jtag', 'cli-session-id.txt');
// Check if we have a stored session ID
if (fs.existsSync(sessionFile)) {
const storedSessionId = fs.readFileSync(sessionFile, 'utf8').trim();
// Validate session ID format (must be valid UUID)
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (!uuidRegex.test(storedSessionId)) {
console.log(`❌ Invalid session ID format in persistence file: ${storedSessionId}`);
fs.unlinkSync(sessionFile);
return undefined;
}
// Verify the session directory still exists (session is active)
const sessionDir = path.join(exampleDir, '.continuum', 'jtag', 'sessions', 'user', storedSessionId);
if (fs.existsSync(sessionDir)) {
return storedSessionId;
} else {
// Session directory gone, remove stale session ID
fs.unlinkSync(sessionFile);
}
}
return undefined; // No valid existing session
} catch (error) {
// If anything fails, just let the system create a new session
return undefined;
}
}
/**
* Store the session ID for future CLI commands
*/
function storePersistentSessionId(sessionId: string): void {
try {
// Use the same path resolution as the instance config
const exampleDir = instanceConfig.paths.directory;
const sessionFile = path.join(exampleDir, '.continuum', 'jtag', 'cli-session-id.txt');
console.log(`🗂️ Storing session file at: ${sessionFile}`);
fs.mkdirSync(path.dirname(sessionFile), { recursive: true });
fs.writeFileSync(sessionFile, sessionId);
console.log(`✅ Session ID stored successfully`);
} catch (error) {
console.log(`❌ Failed to store session ID: ${error}`);
}
}
async function main() {
try {
// Parse command line arguments
const args = process.argv.slice(2);
const restartFlag = args.includes('--restart');
const commandArgs = args.filter(arg => arg !== '--restart');
if (commandArgs.length === 0) {
console.log('Usage: ./jtag <command> [options]');
console.log('Commands: screenshot, navigate, click, type, etc.');
console.log('Try: ./jtag help');
process.exit(1);
}
const [command, ...rawParams] = commandArgs;
// Parse parameters into object format
// ParsedValue supports primitives, arrays (for repeated flags), and objects (for complex params)
type ParsedValue = string | boolean | number | null | ParsedValue[] | { [key: string]: ParsedValue };
const params: Record<string, ParsedValue> = {};
let i = 0;
while (i < rawParams.length) {
const arg = rawParams[i];
if (arg && arg.startsWith('--')) {
const argWithoutDashes = arg.replace(/^--/, '');
// Handle --key=value format
if (argWithoutDashes.includes('=')) {
const [key, ...valueParts] = argWithoutDashes.split('=');
const value = valueParts.join('='); // Handle values that contain =
// SERDE-STYLE JSON PARSING: Try to parse as JSON primitives
let parsedValue: any = value;
// Always try JSON.parse for known JSON types
if (value === 'true' || value === 'false' || value === 'null' ||
value.startsWith('{') || value.startsWith('[') ||
/^-?\d+(\.\d+)?$/.test(value)) { // Numbers (int or float)
try {
parsedValue = JSON.parse(value);
} catch (e) {
// Keep as string if JSON parsing fails
parsedValue = value;
}
}
// 🔧 NATURAL-IDIOMS: Accumulate repeated flags into arrays
if (params[key] !== undefined) {
// Key already exists - convert to array if needed
if (!Array.isArray(params[key])) {
params[key] = [params[key]];
}
params[key].push(parsedValue);
} else {
// First occurrence - store as-is
params[key] = parsedValue;
}
i++;
}
// Handle --key value format
else {
const key = argWithoutDashes;
const value = rawParams[i + 1];
if (value !== undefined && !value.startsWith('--')) {
// SERDE-STYLE JSON PARSING: Try to parse as JSON primitives
let parsedValue: any = value;
// Always try JSON.parse for known JSON types
if (value === 'true' || value === 'false' || value === 'null' ||
value.startsWith('{') || value.startsWith('[') ||
/^-?\d+(\.\d+)?$/.test(value)) { // Numbers (int or float)
try {
parsedValue = JSON.parse(value);
} catch (e) {
// Keep as string if JSON parsing fails
parsedValue = value;
}
}
// 🔧 NATURAL-IDIOMS: Accumulate repeated flags into arrays
if (params[key] !== undefined) {
// Key already exists - convert to array if needed
if (!Array.isArray(params[key])) {
params[key] = [params[key]];
}
params[key].push(parsedValue);
} else {
// First occurrence - store as-is
params[key] = parsedValue;
}
i += 2;
} else {
// Boolean flag
params[key] = true;
i++;
}
}
} else if (arg && arg.includes('=') && !arg.startsWith('-')) {
// Handle key=value format WITHOUT -- prefix (e.g., commandName=screenshot)
const [key, ...valueParts] = arg.split('=');
const value = valueParts.join('='); // Handle values that contain =
// SERDE-STYLE JSON PARSING: Try to parse as JSON primitives
let parsedValue: any = value;
// Always try JSON.parse for known JSON types
if (value === 'true' || value === 'false' || value === 'null' ||
value.startsWith('{') || value.startsWith('[') ||
/^-?\d+(\.\d+)?$/.test(value)) { // Numbers (int or float)
try {
parsedValue = JSON.parse(value);
} catch (e) {
// Keep as string if JSON parsing fails
parsedValue = value;
}
}
params[key] = parsedValue;
i++;
} else {
// Handle positional arguments - add them to a general array
if (!params._positional || !Array.isArray(params._positional)) {
params._positional = [];
}
(params._positional as ParsedValue[]).push(arg);
i++;
}
}
// Handle positional arguments for single-parameter commands
// This allows `./jtag help screenshot` instead of `./jtag help commandName=screenshot`
const positional = params._positional;
if (Array.isArray(positional) && positional.length > 0) {
// Map of commands to their primary parameter name
const singleParamCommands: Record<string, string> = {
'help': 'commandName',
[CODE_COMMANDS.READ]: 'path',
[CODE_COMMANDS.FIND]: 'pattern',
[FILE_COMMANDS.LOAD]: 'path',
[FILE_COMMANDS.SAVE]: 'path',
[DATA_COMMANDS.READ]: 'id',
[DATA_COMMANDS.DELETE]: 'id',
[USER_COMMANDS.CREATE]: 'uniqueId',
// Add more single-param commands as needed
};
const primaryParam = singleParamCommands[command];
if (primaryParam && !params[primaryParam]) {
// Use first positional arg as the primary parameter
params[primaryParam] = positional[0] as ParsedValue;
// Remove from positional array
params._positional = positional.slice(1);
if ((params._positional as ParsedValue[]).length === 0) {
delete params._positional;
}
}
}
// INTELLIGENT ENTRY POINT: Adapts behavior based on detected agent type
type OutputFormat = 'json' | 'human' | 'auto' | 'compact' | 'ai-friendly';
const formatValue = params.format as string | undefined;
const validFormats: OutputFormat[] = ['json', 'human', 'auto', 'compact', 'ai-friendly'];
const format: OutputFormat = (formatValue && validFormats.includes(formatValue as OutputFormat))
? formatValue as OutputFormat
: 'auto';
const entryPoint = new EntryPointAdapter({
verbose: params.verbose as boolean | undefined,
quiet: params.quiet as boolean | undefined,
format,
showAgentInfo: !params.quiet
});
// Get agent context and behavior
const agentContext = entryPoint.getAgentContext();
const behavior = entryPoint.getBehavior();
// Set environment variable for modules to check verbose mode
if (behavior.logLevel === 'verbose') {
process.env.JTAG_VERBOSE = '1';
}
// Suppress ALL output unless verbose mode
const originalStdoutWrite = process.stdout.write;
const originalStderrWrite = process.stderr.write;
if (behavior.logLevel !== 'verbose') {
process.stdout.write = () => true;
process.stderr.write = () => true;
} else {
console.log(`🔧 DEBUG PARAMS:`, JSON.stringify(params, null, 2));
entryPoint.logAgentDetection();
}
// Add environment routing parameter for exec commands
if (command === 'exec' && params.environment) {
// Keep environment param for routing within the system
// Don't delete it - let the system route to the appropriate exec command
}
// Session persistence: reuse existing session unless --new-session flag
let sessionId: string | undefined;
if (!params['new-session'] && command !== COMMANDS.SESSION_CREATE) {
sessionId = getPersistentSessionId();
if (behavior.logLevel === 'verbose') {
console.log(`🔄 Session persistence: ${sessionId ? `reusing ${sessionId}` : 'creating new session'}`);
}
}
const clientOptions: JTAGClientConnectOptions = {
targetEnvironment: 'server',
transportType: 'websocket',
serverUrl: `ws://localhost:${instanceConfig.ports.websocket_server}`,
enableFallback: false,
sessionId: sessionId, // Use persistent session if available
context: {
...agentContext,
cli: {
command,
args: commandArgs,
timestamp: new Date().toISOString()
}
}
};
// Pure client - no server startup, just connect to existing server
if (behavior.logLevel === 'verbose') {
console.log('🔗 CLI connecting to existing server...');
}
let client;
try {
const result = await JTAGClientServer.connect(clientOptions);
client = result.client;
} catch (err) {
// Type guard for proper error handling
const connectionError = err instanceof Error ? err : new Error(String(err));
// Restore output streams first
process.stdout.write = originalStdoutWrite;
process.stderr.write = originalStderrWrite;
const isConnectionRefused = connectionError.message.includes('ECONNREFUSED') ||
connectionError.message.includes('connect') ||
(err && typeof err === 'object' && 'code' in err && (err as {code?: string}).code === 'ECONNREFUSED');
if (behavior.logLevel === 'verbose') {
console.log('='.repeat(60));
console.log('\x1b[31mERROR: Connection failed - ' + connectionError.message + '\x1b[0m');
console.log('='.repeat(60));
if (isConnectionRefused) {
console.error('🔍 PROBLEM: No JTAG system is currently running');
console.error('✅ IMMEDIATE ACTION: Run "npm start" and wait 60 seconds');
} else {
console.error('🔍 Connection details:', connectionError.message);
console.error('🔍 Error code:', (connectionError as Error & {code?: string}).code || 'unknown');
}
} else {
// Clean JSON error for connection failures - send to stderr
console.error(JSON.stringify({
success: false,
error: isConnectionRefused ?
'No JTAG system running - run "npm start" and wait 60 seconds' :
connectionError.message,
timestamp: new Date().toISOString(),
hint: "Use --verbose for detailed output"
}, null, 2));
}
process.exit(1);
}
// Store session ID for persistence (will reuse browser session)
if (behavior.logLevel === 'verbose') {
console.log(`🔍 Session storage check: client.sessionId=${client.sessionId}, sessionId=${sessionId}`);
}
if (client.sessionId && !sessionId) {
// Only store if we didn't already have one (new session created)
if (behavior.logLevel === 'verbose') {
console.log(`💾 Storing new session ID for persistence: ${client.sessionId}`);
}
storePersistentSessionId(client.sessionId);
} else if (behavior.logLevel === 'verbose') {
console.log(`⏭️ Skipping session storage - already had existing session or no client sessionId`);
}
// Execute command with command-specific timeout
try {
// AI commands need longer timeout due to queue + generation time
// Genome commands can take longer for training operations
// Interface commands (screenshot) may need to wait for html2canvas rendering
// Inference commands (inference/generate) need time for local model generation
const isAICommand = command.startsWith('ai/');
const isGenomeCommand = command.startsWith('genome/');
const isInterfaceCommand = command.startsWith('interface/');
const isInferenceCommand = command.startsWith('inference/');
const timeoutMs = isGenomeCommand ? 300000 : (isAICommand || isInferenceCommand) ? 60000 : isInterfaceCommand ? 60000 : 10000; // 5min for genome, 60s for AI/inference/interface, 10s for others
const timeoutSeconds = timeoutMs / 1000;
const commandTimeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error(`Command '${command}' timed out after ${timeoutSeconds} seconds`)), timeoutMs)
);
// Special parameter transformation for exec command
if (command === 'exec') {
// Transform CLI params to ExecCommandParams structure
if (params.file) {
// File-based execution
params.code = {
type: 'file',
path: params.file
};
delete params.file;
} else if (params.code && typeof params.code === 'string') {
// Inline code execution
params.code = {
type: 'inline',
language: params.language || 'javascript',
source: params.code
};
}
// Clean up CLI-specific params
delete params.language;
}
// Special parameter transformation for screenshot command
if (command === 'screenshot') {
// Ensure options is an object
if (!params.options || typeof params.options !== 'object' || Array.isArray(params.options)) {
params.options = {};
}
const options = params.options as { [key: string]: ParsedValue };
// Convert comma-separated presets to array
if (params.presets && typeof params.presets === 'string') {
options.presets = params.presets.split(',').map((p: string) => p.trim());
delete params.presets;
}
// Convert comma-separated resolutions to array (if provided as JSON string)
if (params.resolutions && typeof params.resolutions === 'string') {
try {
options.resolutions = JSON.parse(params.resolutions);
delete params.resolutions;
} catch (e) {
console.warn(`⚠️ Invalid resolutions JSON: ${params.resolutions}`);
}
}
}
const commandExecution = (client as any).commands[command](params);
const result = await Promise.race([commandExecution, commandTimeout]);
// Extract just the essential result, removing wrapper layers
let cleanOutput = result;
// Navigate to the innermost commandResult (the actual result)
while (cleanOutput && typeof cleanOutput === 'object' && 'commandResult' in cleanOutput) {
cleanOutput = cleanOutput.commandResult;
}
// Remove context and other wrapper fields, keep only the actual result
if (cleanOutput && typeof cleanOutput === 'object') {
const { context, sessionId, ...actualResult } = cleanOutput;
// If no meaningful data remains after stripping context/sessionId, keep success field
const hasData = Object.keys(actualResult).filter(key => key !== 'success').length > 0;
if (!hasData && 'success' in cleanOutput) {
cleanOutput = { success: cleanOutput.success };
} else {
cleanOutput = actualResult;
}
}
// Session persistence: only destroy session if explicitly requested
if (params['new-session'] || command.startsWith('session/')) {
// Explicit session management - disconnect fully
await client.disconnect();
} else {
// Session persistence - disconnect transport only, keep session alive
// The session remains active in the browser for next CLI call
const transport = (client as any).getSystemTransport();
if (transport) {
await transport.disconnect();
if (behavior.logLevel === 'verbose') {
console.log('✅ JTAGClient: Transport disconnected (session preserved)');
}
}
}
// Restore output streams and send final result
process.stdout.write = originalStdoutWrite;
process.stderr.write = originalStderrWrite;
// Output final result only - choose between verbose and clean
if (behavior.logLevel === 'verbose') {
console.log('='.repeat(60));
console.log('COMMAND RESULT:');
console.log(JSON.stringify(result, null, 2));
console.log('='.repeat(60));
} else {
console.log(JSON.stringify(cleanOutput, null, 2));
}
process.exit(result?.success ? 0 : 1);
} catch (err) {
const cmdError = err instanceof Error ? err : new Error(String(err));
if (behavior.logLevel === 'verbose') {
console.log('='.repeat(60));
console.log('\x1b[31mERROR: ' + cmdError.message + '\x1b[0m');
console.log('='.repeat(60));
if (cmdError.message.includes('timeout')) {
console.error('🔍 Debug: Check system logs: npm run signal:errors');
}
} else {
// Clean JSON error output for non-verbose mode
console.error(JSON.stringify({
error: cmdError.message,
hint: "For more detailed output, use --verbose flag"
}, null, 2));
}
// Cleanup client connection even on command failure
if (client) {
await client.disconnect();
}
// Restore output streams and send error result
process.stdout.write = originalStdoutWrite;
process.stderr.write = originalStderrWrite;
// Output error result to stderr
console.error(JSON.stringify({
success: false,
error: cmdError.message,
timestamp: new Date().toISOString(),
hint: behavior.logLevel !== 'verbose' ? "Use --verbose for detailed output" : undefined
}, null, 2));
process.exit(1);
}
} catch (error) {
console.error('❌ CLI Error:', error);
process.exit(1);
}
}
// Run the CLI
main().catch(console.error);