-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·1228 lines (1082 loc) · 38.3 KB
/
cli.js
File metadata and controls
executable file
·1228 lines (1082 loc) · 38.3 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 node
import 'dotenv/config'
import { createInterface } from 'readline'
import { existsSync, readFileSync, writeFileSync } from 'fs'
import { fileURLToPath } from 'url'
import path from 'path'
import { execSync } from 'child_process'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const CONFIG_PATH = path.join(__dirname, 'config.js')
const rl = createInterface({
input: process.stdin,
output: process.stdout
})
const prompt = (q) => new Promise(resolve => rl.question(q, resolve))
const colors = {
reset: '\x1b[0m',
bold: '\x1b[1m',
dim: '\x1b[2m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
cyan: '\x1b[36m',
red: '\x1b[31m'
}
function print(msg, color = '') {
console.log(color + msg + colors.reset)
}
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))
async function animateLines(text, delayMs = 40) {
const lines = text.split('\n')
for (const line of lines) {
console.log(line)
await sleep(delayMs)
}
}
async function printHeader() {
console.log('')
try {
let logo1 = execSync('npx oh-my-logo "SECURE" --filled --color --palette-colors "#FF0000,#FF0000"', {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
})
logo1 = logo1.replace(/\x1b\[0m\x1b\[\?25h\x1b\[K[\s\n]*/g, '\n').trimEnd()
let logo2 = execSync('npx oh-my-logo "OPENCLAW" --filled --color --palette-colors "#FF0000,#FF0000"', {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
})
logo2 = logo2.replace(/\x1b\[0m\x1b\[\?25h\x1b\[K[\s\n]*/g, '\n').trimEnd()
await animateLines(logo1, 60)
await animateLines(logo2, 60)
} catch (err) {
print(' SECURE-OPENCLAW CLI', colors.red + colors.bold)
}
await sleep(60)
print(' Built with Composio', colors.red)
await sleep(60)
console.log('')
}
async function getConfiguredProvider() {
try {
// Read directly from file to get current value (import() caches modules)
const content = readFileSync(CONFIG_PATH, 'utf-8')
const match = content.match(/provider:\s*'([^']*)'/)
return match ? match[1] : 'claude'
} catch {
return 'claude'
}
}
async function mainMenu() {
await printHeader()
const defaultProvider = await getConfiguredProvider()
print(` Provider: ${defaultProvider}`, colors.dim)
console.log('')
const menuLines = [
[colors.bold, 'What would you like to do?\n'],
[colors.red, ' 1) Terminal chat'],
[colors.green, ' 2) Start gateway'],
[colors.blue, ' 3) Setup adapters'],
[colors.yellow, ' 4) Show current config'],
[colors.cyan, ' 5) Test connection'],
[colors.green, ' 6) Change provider'],
[colors.dim, ' 7) Exit\n'],
]
for (const [color, text] of menuLines) {
print(text, color)
await sleep(60)
}
const choice = await prompt('Enter choice (1-7): ')
switch (choice.trim()) {
case '1':
await terminalChat()
break
case '2':
await startGateway()
break
case '3':
await setupWizard()
break
case '4':
showConfig()
await mainMenu()
break
case '5':
await testConnection()
break
case '6':
await changeProvider()
break
case '7':
print('\nGoodbye!\n', colors.red)
rl.close()
process.exit(0)
default:
print('\nInvalid choice, try again.\n', colors.red)
await mainMenu()
}
}
async function changeProvider() {
const currentProvider = await getConfiguredProvider()
print('\n🔄 Change Provider\n', colors.green + colors.bold)
print(` Current: ${currentProvider}\n`, colors.dim)
const providerLines = [
[colors.red, ' 1) Claude Agent SDK'],
[colors.green, ' 2) Opencode'],
[colors.dim, ''],
]
for (const [color, text] of providerLines) {
print(text, color)
await sleep(40)
}
const choice = await prompt('Enter choice (1-2): ')
let newProvider
switch (choice.trim()) {
case '1':
newProvider = 'claude'
break
case '2':
newProvider = 'opencode'
break
default:
print('\nNo change.\n', colors.dim)
await mainMenu()
return
}
if (newProvider === currentProvider) {
print(`\nAlready using ${newProvider}.\n`, colors.dim)
} else {
// Update config file
try {
let content = readFileSync(CONFIG_PATH, 'utf-8')
content = content.replace(
/provider:\s*'[^']*'/,
`provider: '${newProvider}'`
)
writeFileSync(CONFIG_PATH, content)
print(`\n✅ Provider changed to: ${newProvider}\n`, colors.green)
} catch (err) {
print('\nFailed to update config: ' + err.message, colors.red)
}
}
await mainMenu()
}
async function startGateway() {
print('\n🚀 Starting Secure OpenClaw Gateway...\n', colors.green)
rl.close()
// Dynamic import to start the gateway
await import('./gateway.js')
}
// ── Spinner for loading states ──────────────────────────────────────
const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
function createSpinner(label) {
let frame = 0
let interval = null
let currentLabel = label
let onOwnLine = false
return {
start(text) {
if (text) currentLabel = text
frame = 0
onOwnLine = false
interval = setInterval(() => {
const f = spinnerFrames[frame % spinnerFrames.length]
if (!onOwnLine) {
process.stdout.write('\n')
onOwnLine = true
}
process.stdout.write(`\r\x1b[K ${colors.red}${f}${colors.reset} ${colors.dim}${currentLabel}${colors.reset}`)
frame++
}, 80)
},
update(text) {
currentLabel = text
},
stop() {
if (interval) {
clearInterval(interval)
interval = null
process.stdout.write('\r\x1b[K')
if (onOwnLine) {
process.stdout.write('\x1b[A\x1b[999C') // move up to tool line, cursor to end
onOwnLine = false
}
}
}
}
}
// ── Input bar rendering ─────────────────────────────────────────────
function drawInputBar(inputText, cols) {
const w = Math.min(cols, 120)
const top = ' ╭' + '─'.repeat(w - 6) + '╮'
const bottom = ' ╰' + '─'.repeat(w - 6) + '╯'
const prefix = ' │ '
const suffix = ' │'
const innerW = w - prefix.length - suffix.length - 1
// Word-wrap input text into lines
const lines = []
if (!inputText) {
lines.push('')
} else {
const raw = inputText.split('\n')
for (const r of raw) {
if (r.length <= innerW) {
lines.push(r)
} else {
for (let i = 0; i < r.length; i += innerW) {
lines.push(r.substring(i, i + innerW))
}
}
}
}
process.stdout.write(colors.dim + top + colors.reset + '\n')
for (const line of lines) {
const pad = ' '.repeat(Math.max(0, innerW - line.length))
process.stdout.write(colors.dim + prefix + colors.reset + line + pad + colors.dim + suffix + colors.reset + '\n')
}
process.stdout.write(colors.dim + bottom + colors.reset)
// Move cursor back into the box (last content line, after text)
const lastLine = lines[lines.length - 1]
const upCount = 1 // move up past the bottom border
process.stdout.write(`\x1b[${upCount}A`) // move up
process.stdout.write(`\r\x1b[${prefix.length + lastLine.length}C`) // move to end of text
}
// ── Status bar ──────────────────────────────────────────────────────
function drawStatusBar(status, cols) {
const w = Math.min(cols, 120)
const left = ` ${status}`
const pad = ' '.repeat(Math.max(0, w - left.length))
console.log(colors.dim + left + pad + colors.reset)
}
async function terminalChat() {
print('\nStarting Terminal Chat...\n', colors.red)
// Use provider from config
const selectedProvider = await getConfiguredProvider()
print(`Using provider: ${selectedProvider}\n`, colors.cyan)
print('Initializing agent with all MCP servers...', colors.dim)
try {
// Import required modules
const { default: ClaudeAgent } = await import('./agent/claude-agent.js')
const { default: config } = await import('./config.js')
const { Composio } = await import('@composio/core')
// Initialize MCP servers
const mcpServers = {}
// Initialize Composio
try {
const composio = new Composio()
const session = await composio.create(config.agentId || 'secure-openclaw-terminal')
mcpServers.composio = {
type: 'http',
url: session.mcp.url,
headers: session.mcp.headers
}
print(' ✅ Composio ready', colors.green)
} catch (err) {
print(' ⚠️ Composio: ' + err.message, colors.yellow)
}
// Create agent with selected provider
const agent = new ClaudeAgent({
allowedTools: config.agent?.allowedTools || ['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep'],
maxTurns: config.agent?.maxTurns || 50,
provider: selectedProvider,
opencode: config.agent?.opencode || {}
})
// Pre-initialize provider (connect/start server before user types)
if (agent.provider.initialize) {
try {
await agent.provider.initialize()
print(' ✅ Provider ready', colors.green)
} catch (err) {
print(' ⚠️ Provider: ' + err.message, colors.yellow)
}
}
// Handle cron job executions in terminal
agent.cronScheduler.on('execute', async ({ jobId, message, invokeAgent }) => {
process.stdout.write('\n\n')
console.log(colors.yellow + '⏰ [Scheduled] ' + colors.reset + colors.cyan + message + colors.reset)
console.log(colors.dim + ` (job: ${jobId})${invokeAgent ? ' [invoking agent]' : ''}` + colors.reset)
try {
execSync('afplay /System/Library/Sounds/Glass.aiff &', { stdio: 'ignore' })
const escapedMsg = message.replace(/"/g, '\\"').replace(/'/g, "'\"'\"'")
execSync(`osascript -e 'display notification "${escapedMsg}" with title "OpenClaw" sound name "Glass"'`, { stdio: 'ignore' })
} catch (e) {
process.stdout.write('\x07')
}
if (invokeAgent) {
try {
let cronFirstText = true
for await (const chunk of agent.run({
message,
sessionKey,
platform: 'terminal',
mcpServers
})) {
if (chunk.type === 'text' && chunk.content) {
let text = chunk.content
if (cronFirstText) {
text = text.replace(/^[\s\n\r]+/, '')
if (!text) continue
process.stdout.write(colors.cyan + '\n OpenClaw: ' + colors.reset + text)
cronFirstText = false
} else {
process.stdout.write(text)
}
} else if (chunk.type === 'tool_use') {
process.stdout.write(colors.yellow + `\n 🔧 ${chunk.name}` + colors.reset)
} else if (chunk.type === 'tool_result') {
process.stdout.write(colors.dim + ' ✓' + colors.reset)
}
}
console.log('')
} catch (err) {
console.log(colors.red + '\nError: ' + err.message + colors.reset)
}
}
})
print('\nChat started! Type "exit" or "quit" to end.\n', colors.red + colors.bold)
const cols = process.stdout.columns || 80
drawStatusBar(`[${selectedProvider}] Ready — /model to switch`, cols)
print('', '')
const sessionKey = `terminal:${Date.now()}`
const spinner = createSpinner('Thinking...')
// ── Pending approval resolver (set during canUseTool) ───────
let pendingApprovalResolve = null
/**
* canUseTool callback for terminal — stops spinner, prints prompt,
* waits for user input, then returns allow/deny.
*/
const canUseTool = async (toolName, input, options) => {
spinner.stop()
// Handle AskUserQuestion — format as numbered options
if (toolName === 'AskUserQuestion') {
const questions = input.questions || []
console.log('')
for (const q of questions) {
console.log(colors.yellow + ' ? ' + colors.reset + q.question)
if (q.options) {
q.options.forEach((opt, i) => {
const desc = opt.description ? colors.dim + ' — ' + opt.description + colors.reset : ''
console.log(` ${colors.cyan}${i + 1})${colors.reset} ${opt.label}${desc}`)
})
}
}
process.stdout.write('\n' + colors.dim + ' Your choice: ' + colors.reset)
const reply = await new Promise(resolve => {
pendingApprovalResolve = resolve
})
pendingApprovalResolve = null
const firstQuestion = questions[0]
const num = parseInt(reply.trim())
if (firstQuestion?.options && num >= 1 && num <= firstQuestion.options.length) {
const selected = firstQuestion.options[num - 1]
spinner.start('Thinking...')
return {
behavior: 'allow',
updatedInput: {
...input,
questions: [{ ...firstQuestion, answer: selected.label }]
}
}
}
spinner.start('Thinking...')
return {
behavior: 'allow',
updatedInput: {
...input,
questions: [{ ...firstQuestion, answer: reply.trim() }]
}
}
}
// Standard tool approval
console.log('')
console.log(colors.yellow + ' ⚠ Tool approval needed: ' + colors.reset + colors.bold + toolName + colors.reset)
if (options.decisionReason) {
console.log(colors.dim + ' ' + options.decisionReason + colors.reset)
}
const inputStr = JSON.stringify(input, null, 2)
if (inputStr.length < 500) {
const lines = inputStr.split('\n')
for (const l of lines) {
console.log(colors.dim + ' ' + l + colors.reset)
}
}
process.stdout.write('\n' + colors.dim + ' Allow? (y/n): ' + colors.reset)
const reply = await new Promise(resolve => {
pendingApprovalResolve = resolve
})
pendingApprovalResolve = null
const answer = reply.trim().toLowerCase()
if (answer === 'y' || answer === 'yes') {
console.log(colors.green + ' ✓ Allowed' + colors.reset)
spinner.start('Thinking...')
return { behavior: 'allow', updatedInput: input }
}
console.log(colors.red + ' ✗ Denied' + colors.reset)
spinner.start('Thinking...')
return { behavior: 'deny', message: reply.trim() || 'User denied the action.' }
}
// ── Raw input mode ──────────────────────────────────────────
rl.close() // Close readline, we'll handle input directly
let inputBuffer = ''
const stdin = process.stdin
stdin.setRawMode(true)
stdin.resume()
stdin.setEncoding('utf8')
let isRunning = false
let wasInterrupted = false
let pendingModelSelect = null // resolve function for model keypress
let inputBarLineCount = 0
let cursorInInputBar = false
function countInputLines(text, innerW) {
if (!text) return 1
const width = Math.max(innerW, 1)
let lines = 0
const raw = text.split('\n')
for (const r of raw) {
lines += Math.max(1, Math.ceil(r.length / width))
}
return lines
}
function clearInputBar() {
if (!cursorInInputBar || inputBarLineCount <= 0) return
const up = Math.max(0, inputBarLineCount - 2) // from last content line to top border
if (up > 0) process.stdout.write(`\x1b[${up}A`)
for (let i = 0; i < inputBarLineCount; i++) {
process.stdout.write('\x1b[2K')
if (i < inputBarLineCount - 1) process.stdout.write('\x1b[B')
}
if (inputBarLineCount > 1) {
process.stdout.write(`\x1b[${inputBarLineCount - 1}A`)
}
process.stdout.write('\r')
cursorInInputBar = false
}
function redrawInput() {
const c = process.stdout.columns || 80
// Erase old box lines (only safe when cursor is still inside the box)
if (cursorInInputBar && inputBarLineCount > 0) {
clearInputBar()
}
drawInputBar(inputBuffer || '', c)
// Count lines the box occupies (top + content lines + bottom)
const innerW = Math.min(c, 120) - 7
const contentLines = countInputLines(inputBuffer, innerW)
inputBarLineCount = 2 + contentLines // top + content + bottom
cursorInInputBar = true
}
// Initial draw
const c0 = process.stdout.columns || 80
drawInputBar('', c0)
inputBarLineCount = 3
cursorInInputBar = true
async function handleSubmit(text) {
if (!text.trim()) {
redrawInput()
return
}
if (['exit', 'quit', '/exit', '/quit'].includes(text.trim().toLowerCase())) {
stdin.setRawMode(false)
stdin.pause()
print('\n\nGoodbye!\n', colors.red)
agent.stopCron()
process.exit(0)
}
// /model command
if (text.trim().toLowerCase() === '/model') {
cursorInInputBar = false
inputBuffer = ''
console.log('\n')
const models = agent.provider.getAvailableModels()
const current = agent.provider.getModel()
print(` Current model: ${current || '(default)'}`, colors.dim)
print(` Provider: ${agent.providerName}\n`, colors.dim)
for (let i = 0; i < models.length; i++) {
const marker = models[i].id === current ? ' ←' : ''
print(` ${i + 1}) ${models[i].label} (${models[i].id})${marker}`, colors.cyan)
}
process.stdout.write('\n' + colors.dim + ' Select model (1-' + models.length + '): ' + colors.reset)
// Wait for a single keypress in raw mode
const modelChoice = await new Promise(resolve => {
pendingModelSelect = resolve
})
pendingModelSelect = null
const idx = parseInt(modelChoice) - 1
if (idx >= 0 && idx < models.length) {
agent.provider.setModel(models[idx].id)
print(`\n\n Model set to: ${models[idx].label}\n`, colors.green)
} else {
print('\n\n No change.\n', colors.dim)
}
const c = process.stdout.columns || 80
drawStatusBar(`[${selectedProvider}] [${agent.provider.getModel() || 'default'}] Ready`, c)
inputBarLineCount = 0
redrawInput()
return
}
cursorInInputBar = false
isRunning = true
wasInterrupted = false
inputBuffer = ''
// Print user message
console.log('\n')
console.log(colors.bold + ' You: ' + colors.reset + text)
console.log('')
// Start spinner
spinner.start('Thinking...')
try {
let isFirstText = true
let isFirstThinking = true
let lastWasToolUse = false
let curCol = 0
for await (const chunk of agent.run({
message: text,
sessionKey,
platform: 'terminal',
mcpServers,
canUseTool
})) {
if (chunk.type === 'tool_use') {
spinner.stop()
// Ensure fresh line before tool block
console.log('')
console.log(colors.dim + ' ┌─ ' + colors.yellow + chunk.name + colors.reset)
// Show args
if (chunk.input && Object.keys(chunk.input).length > 0) {
const args = JSON.stringify(chunk.input, null, 2)
.split('\n')
.map(l => colors.dim + ' │ ' + colors.reset + l)
.join('\n')
console.log(args)
}
spinner.start(`${chunk.name} (tool output)`)
lastWasToolUse = true
isFirstText = true
curCol = 0
} else if (chunk.type === 'tool_result' && lastWasToolUse) {
spinner.stop()
// Show result (truncated)
const result = typeof chunk.result === 'string' ? chunk.result : JSON.stringify(chunk.result, null, 2)
if (result) {
const lines = result.split('\n')
const maxLines = 4
const show = lines.length > maxLines ? lines.slice(0, maxLines) : lines
for (const l of show) {
console.log(colors.dim + ' │ ' + l.slice(0, 120) + colors.reset)
}
if (lines.length > maxLines) {
console.log(colors.dim + ` │ ... (${lines.length - maxLines} more lines)` + colors.reset)
}
}
console.log(colors.dim + ' └─ ' + colors.green + 'done' + colors.reset)
lastWasToolUse = false
spinner.start('Thinking...')
} else if (chunk.type === 'text' && chunk.content) {
spinner.stop()
const padStr = ' '
const padLen = 2
const termWidth = process.stdout.columns || 80
const maxCol = termWidth - 1
// Reasoning tokens (thinking) — show in red
if (chunk.isReasoning) {
if (isFirstThinking) {
console.log('')
console.log(colors.red + ' Thinking:' + colors.reset)
process.stdout.write(padStr)
curCol = padLen
isFirstThinking = false
}
for (const ch of chunk.content) {
if (ch === '\n') {
process.stdout.write('\n' + padStr)
curCol = padLen
} else {
if (curCol >= maxCol) {
process.stdout.write('\n' + padStr)
curCol = padLen
}
process.stdout.write(colors.red + ch + colors.reset)
curCol++
}
}
continue
}
let text = chunk.content
if (isFirstText) {
text = text.replace(/^[\s\n\r]+/, '')
if (!text) continue
console.log('')
console.log(colors.cyan + ' OpenClaw:' + colors.reset)
process.stdout.write(padStr)
curCol = padLen
isFirstText = false
lastWasToolUse = false
}
// Write text char by char, wrapping at terminal width
for (const ch of text) {
if (ch === '\n') {
process.stdout.write('\n' + padStr)
curCol = padLen
} else {
if (curCol >= maxCol) {
process.stdout.write('\n' + padStr)
curCol = padLen
}
process.stdout.write(ch)
curCol++
}
}
}
}
spinner.stop()
if (!wasInterrupted) console.log('\n')
} catch (err) {
spinner.stop()
if (!wasInterrupted) {
print('\n Error: ' + err.message, colors.red)
console.log('')
}
}
// Skip redraw if Ctrl+C already handled it
if (wasInterrupted) {
isRunning = false
return
}
isRunning = false
// Redraw status + input bar
const c = process.stdout.columns || 80
const modelLabel = agent.provider.getModel() ? ` [${agent.provider.getModel()}]` : ''
cursorInInputBar = false
inputBuffer = ''
drawStatusBar(`[${selectedProvider}]${modelLabel} Ready — /model to switch`, c)
redrawInput()
}
// Handle raw keystrokes
let ctrlCCount = 0
let ctrlCTimer = null
let approvalInputBuffer = ''
stdin.on('data', (key) => {
// Ctrl+C
if (key === '\x03') {
// Cancel pending approval
if (pendingApprovalResolve) {
approvalInputBuffer = ''
pendingApprovalResolve('')
return
}
// Cancel model selection
if (pendingModelSelect) {
pendingModelSelect('')
return
}
if (isRunning) {
// Abort the running agent
spinner.stop()
wasInterrupted = true
agent.abort(sessionKey)
process.stdout.write('\n' + colors.red + ' Interrupted.' + colors.reset + '\n\n')
isRunning = false
const c = process.stdout.columns || 80
const modelLabel = agent.provider.getModel() ? ` [${agent.provider.getModel()}]` : ''
cursorInInputBar = false
inputBuffer = ''
drawStatusBar(`[${selectedProvider}]${modelLabel} Ready — /model to switch`, c)
redrawInput()
ctrlCCount = 0
return
}
// Not running: double Ctrl+C to exit
ctrlCCount++
if (ctrlCCount >= 2) {
stdin.setRawMode(false)
stdin.pause()
print('\n\nGoodbye!\n', colors.red)
agent.stopCron()
process.exit(0)
}
clearInputBar()
process.stdout.write('\n' + colors.dim + ' Press Ctrl+C again to exit' + colors.reset + '\n')
redrawInput()
clearTimeout(ctrlCTimer)
ctrlCTimer = setTimeout(() => { ctrlCCount = 0 }, 1500)
return
}
ctrlCCount = 0
// Approval input mode — capture text and resolve on Enter
if (pendingApprovalResolve) {
if (key === '\r' || key === '\n') {
process.stdout.write('\n')
const text = approvalInputBuffer
approvalInputBuffer = ''
pendingApprovalResolve(text)
} else if (key === '\x7f' || key === '\b') {
if (approvalInputBuffer.length > 0) {
approvalInputBuffer = approvalInputBuffer.slice(0, -1)
process.stdout.write('\b \b')
}
} else if (!key.startsWith('\x1b')) {
approvalInputBuffer += key
process.stdout.write(key)
}
return
}
if (isRunning) return // Ignore other input while agent is running
// Model selection mode — capture single digit keypress
if (pendingModelSelect) {
if (key >= '1' && key <= '9') {
process.stdout.write(key)
pendingModelSelect(key)
} else if (key === '\x1b' || key === '\r' || key === '\n') {
// Escape or Enter without selection — cancel
pendingModelSelect('')
}
return
}
// Enter - submit
if (key === '\r' || key === '\n') {
clearInputBar()
handleSubmit(inputBuffer)
return
}
// Backspace
if (key === '\x7f' || key === '\b') {
if (inputBuffer.length > 0) {
inputBuffer = inputBuffer.slice(0, -1)
redrawInput()
}
return
}
// Escape sequences (arrow keys, etc.) — ignore
if (key.startsWith('\x1b')) return
// Regular character
inputBuffer += key
redrawInput()
})
} catch (err) {
print('\nFailed to start chat: ' + err.message, colors.red)
process.exit(1)
}
}
function showConfig() {
print('\n📋 Current Configuration:\n', colors.yellow)
try {
// Read and display config
const configContent = readFileSync(CONFIG_PATH, 'utf-8')
// Parse out the config object (simple extraction)
const lines = configContent.split('\n')
for (const line of lines) {
if (line.includes('enabled:')) {
const enabled = line.includes('true')
const platform = getPlatformFromContext(lines, lines.indexOf(line))
print(` ${platform}: ${enabled ? '✅ Enabled' : '❌ Disabled'}`, enabled ? colors.green : colors.dim)
}
}
console.log('')
} catch (err) {
print('Could not read config: ' + err.message, colors.red)
}
}
function getPlatformFromContext(lines, index) {
for (let i = index; i >= 0; i--) {
if (lines[i].includes('whatsapp:')) return 'WhatsApp'
if (lines[i].includes('telegram:')) return 'Telegram'
if (lines[i].includes('signal:')) return 'Signal'
if (lines[i].includes('imessage:')) return 'iMessage'
}
return 'Unknown'
}
async function setupWizard() {
print('\n🔧 Adapter Setup Wizard\n', colors.blue)
print('Which adapter would you like to configure?\n')
print(' 1) WhatsApp (scan QR code)')
print(' 2) Telegram (bot token)')
print(' 3) Signal (signal-cli)')
print(' 4) iMessage (macOS only)')
print(' 5) Back to main menu\n')
const choice = await prompt('Enter choice (1-5): ')
switch (choice.trim()) {
case '1':
await setupWhatsApp()
break
case '2':
await setupTelegram()
break
case '3':
await setupSignal()
break
case '4':
await setupiMessage()
break
case '5':
await mainMenu()
return
default:
print('\nInvalid choice.\n', colors.red)
}
await setupWizard()
}
async function setupWhatsApp() {
print('\n📱 WhatsApp Setup\n', colors.green)
// Check if already authenticated
const waAuthPath = path.join(__dirname, 'auth_whatsapp')
if (existsSync(waAuthPath)) {
print('✅ WhatsApp is already authenticated!\n', colors.green)
const reauth = await prompt('Re-authenticate (scan new QR)? (y/n): ')
if (reauth.toLowerCase() === 'y') {
print('\nRemoving old session...', colors.dim)
const fs = await import('fs')
fs.rmSync(waAuthPath, { recursive: true, force: true })
} else {
await updateConfig('whatsapp', { enabled: true })
print('\n✅ WhatsApp enabled!\n', colors.green)
return
}
}
const enable = await prompt('Enable and authenticate WhatsApp now? (y/n): ')
if (enable.toLowerCase() !== 'y') {
await updateConfig('whatsapp', { enabled: false })
print('\n❌ WhatsApp disabled.\n', colors.dim)
return
}
print('\n🔄 Starting WhatsApp authentication...\n', colors.cyan)
print('A QR code will appear below. Scan it with:', colors.dim)
print(' WhatsApp > Settings > Linked Devices > Link a Device\n', colors.dim)
try {
// Import and start WhatsApp adapter just for auth
const { default: WhatsAppAdapter } = await import('./adapters/whatsapp.js')
const adapter = new WhatsAppAdapter({ enabled: true, allowedDMs: ['*'], allowedGroups: [], respondToMentionsOnly: true })
// Wait for connection
await new Promise((resolve, reject) => {
let connected = false
let timeout = null
// Monitor the socket for connection
const checkConnection = setInterval(() => {
if (adapter.sock?.user?.id) {
connected = true
clearInterval(checkConnection)
clearTimeout(timeout)
resolve()
}
}, 1000)
// Start the adapter
adapter.start().catch(reject)
// Timeout after 2 minutes
timeout = setTimeout(() => {
clearInterval(checkConnection)
if (!connected) {
adapter.stop().catch(() => {})
reject(new Error('Authentication timed out. Please try again.'))
}
}, 120000)
})
print('\n✅ WhatsApp authenticated successfully!\n', colors.green + colors.bold)
// Stop the adapter (gateway will start fresh)
await adapter.stop()
print('Group Message Settings:\n', colors.cyan)
print(' 1) Respond in all groups (when @mentioned)', colors.green)
print(' 2) DMs only (ignore all groups)', colors.dim)
print(' 3) Specific groups only\n')
const groupChoice = await prompt('Select group setting (1-3): ')
let allowedGroups = []
if (groupChoice.trim() === '1') {
allowedGroups = ['*']
print('\n✅ Will respond in all groups when @mentioned\n', colors.green)
} else if (groupChoice.trim() === '3') {
print('\nEnter group JIDs (comma-separated). Find these by sending a message in the group.\n', colors.dim)
const groups = await prompt('Group JIDs: ')
allowedGroups = groups.split(',').map(g => g.trim()).filter(Boolean)
print(`\n✅ Will respond in ${allowedGroups.length} specific group(s)\n`, colors.green)
} else {
print('\n✅ DMs only - groups disabled\n', colors.dim)