Class: Kward::CLI
- Inherits:
-
Object
show all
- Includes:
- CLI::AuthCommands, CLI::Commands, CLI::CompactionCommands, CLI::Doctor, CLI::GitCommands, CLI::HookCommands, CLI::InteractiveTurn, CLI::MemoryCommands, CLI::OpenRouterCommands, CLI::Plugins, CLI::ProjectSkills, CLI::ProjectSkillsCommands, CLI::PromptInterfaceSupport, CLI::Rendering, CLI::RuntimeHelpers, CLI::Sessions, CLI::Settings, CLI::SlashCommands, CLI::Stats, CLI::Sysprompt, CLI::Tabs, CLI::ToolSummaries, CLI::Transports, CLI::Worktrees
- Defined in:
- lib/kward/cli.rb,
lib/kward/cli/git.rb,
lib/kward/cli/tabs.rb,
lib/kward/cli/stats.rb,
lib/kward/cli/doctor.rb,
lib/kward/cli/plugins.rb,
lib/kward/cli/commands.rb,
lib/kward/cli/sessions.rb,
lib/kward/cli/settings.rb,
lib/kward/cli/rendering.rb,
lib/kward/cli/sysprompt.rb,
lib/kward/cli/worktrees.rb,
lib/kward/cli/compaction.rb,
lib/kward/cli/transports.rb,
lib/kward/cli/auth_commands.rb,
lib/kward/cli/hook_commands.rb,
lib/kward/cli/project_skills.rb,
lib/kward/cli/slash_commands.rb,
lib/kward/cli/tool_summaries.rb,
lib/kward/cli/memory_commands.rb,
lib/kward/cli/runtime_helpers.rb,
lib/kward/cli/interactive_turn.rb,
lib/kward/cli/prompt_interface.rb,
lib/kward/cli/openrouter_commands.rb,
lib/kward/cli/project_skills_commands.rb
Overview
Command-line frontend that coordinates terminal interaction, sessions, tools, and model turns.
Defined Under Namespace
Modules: AuthCommands, Commands, CompactionCommands, Doctor, GitCommands, HookCommands, InteractiveTurn, MemoryCommands, OpenRouterCommands, Plugins, ProjectSkills, ProjectSkillsCommands, PromptInterfaceSupport, Rendering, RuntimeHelpers, Sessions, Settings, SlashCommands, Stats, Sysprompt, Tabs, ToolSummaries, Transports, Worktrees
Constant Summary
collapse
- RESTORED_TOOL_OUTPUT_LIMIT =
2_000
- INTERACTIVE_TOOL_OUTPUT_LINE_LIMIT =
10
- STREAM_RENDER_INTERVAL =
0.025
- INTERACTIVE_EVENT_DRAIN_LIMIT =
12
- BUILTIN_SLASH_COMMANDS =
PromptCommands::BUILTIN_COMMANDS
- BUILTIN_SLASH_COMMAND_NAMES =
PromptCommands::BUILTIN_RESERVED_COMMAND_NAMES
Instance Method Summary
collapse
-
#apply_filter_system_prompt(conversation) ⇒ Object
-
#authentication_error_message(error) ⇒ Object
-
#config_error_message(error) ⇒ Object
-
#debug_errors? ⇒ Boolean
-
#dispatch ⇒ Object
-
#edit_file_command(path) ⇒ Object
-
#ensure_client! ⇒ Object
-
#filter_prompt(instruction:, input:) ⇒ Object
-
#filter_system_prompt ⇒ Object
-
#initialize(argv: ARGV, stdin: STDIN, prompt: TTY::Prompt.new, client: nil, session_store: nil, context_usage: ContextUsage.new) ⇒ CLI
constructor
-
#interactive_loop(agent: nil) ⇒ Object
-
#one_shot(input, filter: false) ⇒ Object
-
#piped_prompt ⇒ Object
-
#read_stdin_input ⇒ Object
-
#resolved_execution_mode(first_prompt:, stdin_input:) ⇒ Object
-
#run ⇒ void
Dispatches command-line modes, including RPC, login, stats export, Pan mode, one-shot prompts, and interactive chat.
-
#run_prompt_or_interactive ⇒ Object
-
#runtime_error_message(error) ⇒ Object
Constructor Details
#initialize(argv: ARGV, stdin: STDIN, prompt: TTY::Prompt.new, client: nil, session_store: nil, context_usage: ContextUsage.new) ⇒ CLI
Returns a new instance of CLI.
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
# File 'lib/kward/cli.rb', line 124
def initialize(argv: ARGV, stdin: STDIN, prompt: TTY::Prompt.new, client: nil, session_store: nil, context_usage: ContextUsage.new)
@argv = argv
@stdin = stdin
@prompt = prompt
@client = client
@session_store = session_store
@context_usage = context_usage
@active_session = nil
@session_diff = SessionDiff.new
@cleanup_sessions = []
@plugin_registry = nil
@working_directory = nil
@prompt_delimited = false
@requested_mode = "auto"
@skip_config = false
@pending_reasoning_config = nil
@pending_reasoning_config_mutex = Mutex.new
@color_enabled = ANSI.enabled?($stdout)
end
|
Instance Method Details
#apply_filter_system_prompt(conversation) ⇒ Object
467
468
469
470
471
|
# File 'lib/kward/cli.rb', line 467
def apply_filter_system_prompt(conversation)
return unless conversation.system_message
conversation.system_message[:content] = [conversation.system_message[:content], filter_system_prompt].compact.join("\n\n")
end
|
#authentication_error_message(error) ⇒ Object
197
198
199
200
201
202
203
204
205
|
# File 'lib/kward/cli.rb', line 197
def authentication_error_message(error)
<<~MESSAGE.rstrip
Authentication required
#{error.message}
Run `kward doctor` to inspect your setup.
MESSAGE
end
|
#config_error_message(error) ⇒ Object
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
|
# File 'lib/kward/cli.rb', line 177
def config_error_message(error)
<<~MESSAGE.rstrip
Invalid Kward config #{error.format}.
File:
#{error.path}
Parser error:
#{error.detail}
Kward cannot safely continue with this config.
Repair it with:
kward edit #{error.path}
Emergency fallback:
kward --skip-config doctor
MESSAGE
end
|
#debug_errors? ⇒ Boolean
217
218
219
|
# File 'lib/kward/cli.rb', line 217
def debug_errors?
ENV["KWARD_DEBUG"] == "1"
end
|
#dispatch ⇒ Object
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
|
# File 'lib/kward/cli.rb', line 221
def dispatch
if @prompt_delimited
ConfigFiles.ensure_default_config!
run_prompt_or_interactive
return
end
if help_command?
print_command_help(@argv[1])
return
end
raise ArgumentError, command_usage("help") if ["help", "--help", "-h"].include?(@argv.first)
if version_command?
print_version
return
end
raise ArgumentError, command_usage("version") if ["version", "--version", "-v"].include?(@argv.first)
ConfigFiles.ensure_default_config!
if @argv.first == "init"
if help_option_arguments?(@argv[1..] || [])
print_command_help("init")
return
end
raise ArgumentError, command_usage("init") unless @argv.length == 1
install_starter_pack
return
end
if @argv.first == "auth"
handle_auth_command(@argv[1..] || [])
return
end
if @argv.first == "doctor"
if help_option_arguments?(@argv[1..] || [])
print_command_help("doctor")
return
end
raise ArgumentError, command_usage("doctor") unless @argv.length == 1
ensure_client!
exit 1 unless print_doctor
return
end
if @argv.first == "hooks"
if help_option_arguments?(@argv[1..] || [])
print_command_help("hooks")
return
end
handle_hooks_command((@argv[1..] || []).join(" "), command_line: true)
return
end
if @argv.first == "skills"
if help_option_arguments?(@argv[1..] || [])
print_command_help("skills")
return
end
handle_project_skills_cli_command(@argv[1..] || [])
return
end
if @argv.first == "edit"
if help_option_arguments?(@argv[1..] || [])
print_command_help("edit")
return
end
raise ArgumentError, command_usage("edit") unless @argv.length == 2
edit_file_command(@argv[1])
return
end
if @argv.first == "sysprompt"
if help_option_arguments?(@argv[1..] || [])
print_command_help("sysprompt")
return
end
ensure_client!
print_sysprompt(@argv[1..] || [])
return
end
if @argv.first == "transport"
if help_option_arguments?(@argv[1..] || [])
print_command_help("transport")
return
end
handle_transport_command(@argv[1..] || [])
return
end
if @argv.first == "rpc"
if help_option_arguments?(@argv[1..] || [])
print_command_help("rpc")
return
end
raise ArgumentError, command_usage("rpc") unless @argv.length == 1
ensure_client!
Kward::RPC::Server.new(input: @stdin, output: $stdout, client: @client).run
return
end
if @argv.first == "stats"
if @argv[1] == "tokens" && help_option_arguments?(@argv[2..] || [])
print_command_help("stats")
return
end
raise ArgumentError, command_usage("stats") unless @argv[1] == "tokens"
export_token_stats(@argv[2..] || [])
return
end
if @argv.first == "openrouter"
if help_option_arguments?(@argv[1..] || [])
print_command_help("openrouter")
return
end
ensure_client!
handle_openrouter_command(@argv[1..] || [])
return
end
if pan_mode?
if help_option_arguments?(@argv[1..] || [])
print_command_help("pan")
return
end
raise ArgumentError, command_usage("pan") unless @argv.length == 1
ensure_client!
PanServer.new(client: @client, working_directory: current_workspace_root).run
return
end
if ["login", "--login"].include?(@argv.first)
if help_option_arguments?(@argv[1..] || [])
print_command_help("login")
return
end
raise ArgumentError, command_usage("login") unless @argv.length <= 2
login(provider: @argv[1])
return
end
run_prompt_or_interactive
end
|
#edit_file_command(path) ⇒ Object
382
383
384
385
386
387
388
389
390
391
392
|
# File 'lib/kward/cli.rb', line 382
def edit_file_command(path)
setup_interactive_prompt
unless @prompt.respond_to?(:edit_file)
raise ArgumentError, "The integrated editor requires an interactive terminal."
end
@prompt.edit_file(path, base_dir: Dir.pwd, allow_new: true)
ensure
@prompt.close if @prompt.respond_to?(:close) && prompt_interface?
clear_interactive_warning_sink if respond_to?(:clear_interactive_warning_sink, true)
end
|
#ensure_client! ⇒ Object
173
174
175
|
# File 'lib/kward/cli.rb', line 173
def ensure_client!
@client ||= Client.new
end
|
#filter_prompt(instruction:, input:) ⇒ Object
457
458
459
460
461
462
463
464
465
|
# File 'lib/kward/cli.rb', line 457
def filter_prompt(instruction:, input:)
<<~PROMPT
Instruction:
#{instruction}
Input:
#{input}
PROMPT
end
|
#filter_system_prompt ⇒ Object
473
474
475
476
477
478
479
480
481
482
483
484
485
|
# File 'lib/kward/cli.rb', line 473
def filter_system_prompt
<<~PROMPT.strip
You are being used as a command-line text filter.
Transform the provided input according to the user's instruction.
Return only the transformed output.
Do not include explanations, introductions, summaries, Markdown fences, or commentary.
Do not say what you changed.
Preserve the input format unless the instruction requires changing it.
If the input is code, data, markup, or configuration, output only the resulting code/data/markup/configuration.
PROMPT
end
|
#interactive_loop(agent: nil) ⇒ Object
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
|
# File 'lib/kward/cli.rb', line 487
def interactive_loop(agent: nil)
setup_interactive_prompt(defer_warnings: true)
prepare_interactive_project_skills
session_store = interactive_session_store(agent)
@resumed_last_session = false
if session_store && @prompt.respond_to?(:update_tabs)
agent = setup_interactive_tabs(session_store, agent)
elsif session_store && agent.nil?
agent = resume_last_session(session_store) || build_new_session_agent(session_store)
elsif session_store
@active_session = track_session(session_store.create(provider: current_model_provider, model: current_model_id, reasoning_effort: current_reasoning_effort))
reset_session_diff
@active_session.attach(agent.conversation)
else
agent ||= build_interactive_agent(new_conversation)
end
update_assistant_prompt(agent.conversation)
@footer_conversation = agent.conversation
print_visual_banner unless @resumed_last_session || @restored_tabs
render_resumed_last_session_transcript(agent.conversation) if @resumed_last_session
enable_interactive_warnings if respond_to?(:enable_interactive_warnings, true)
@pending_inputs = []
install_bang_completion_provider(agent)
loop do
service_background_tab_runs if respond_to?(:service_background_tab_runs, true)
if @pending_inputs.empty? && active_tab&.shell && !active_tab.local_busy?
run_kwsh_loop(active_tab.shell, tab: active_tab, history: build_kwsh_history(active_tab.agent))
end
input = @pending_inputs.shift || (active_tab ? poll_active_tab_input : @prompt.ask("You>"))
if input.is_a?(Hash) && input[:editor_prompt]
pending_inputs = run_editor_prompt_turn(input[:editor_prompt], active_tab&.agent || agent)
pending_inputs.reverse_each { |pending_input| @pending_inputs.unshift(pending_input) }
next
end
if input.is_a?(Hash) && input[:tab_action]
tab_result = handle_tab_action(input, session_store)
break if tab_result == PromptInterface::EXIT_INPUT
agent = active_tab.agent if active_tab&.agent
next
end
if input.is_a?(Hash) && input[:reasoning_action]
next if active_tab && plugin_tab?
conversation = active_tab ? active_tab.agent.conversation : agent.conversation
cycle_reasoning(conversation, direction: input[:reasoning_action], persist: :debounced)
agent = active_tab.agent if active_tab&.agent
next
end
next if input == :tab_idle
break if input.nil?
display_input = submitted_display_input(input)
command_input = display_input.nil? ? input : display_input
command = command_input.strip
next if command.empty? && input.strip.empty?
if command.empty?
handled = false
else
selected_input = selected_slash_command_input(command_input)
if selected_input
input = selected_input
command = input.strip
display_input = input if display_input
end
break if ["/exit", "/quit"].include?(command)
if active_tab && plugin_tab? && command.start_with?("/")
unless plugin_tab_command_allowed?(command)
runtime_output("#{command.split.first} is unavailable in this plugin tab.")
next
end
if active_tab.driver.respond_to?(:handle_command) && active_tab.driver.handles_command?(command)
output = active_tab.driver.handle_command(command)
runtime_output(output) unless output.to_s.empty?
next
end
end
handled, replacement_agent = handle_local_slash_command(command, agent, session_store)
if replacement_agent?(replacement_agent)
agent = active_tab ? replace_active_tab_agent(replacement_agent) : replacement_agent
elsif active_tab&.agent
agent = active_tab.agent
end
end
next if handled
if shell_command_input?(command_input)
shell_result = handle_interactive_shell_command(command_input, agent)
next if shell_result == true || shell_result == :tab_action
end
flush_pending_reasoning_config(conversation: active_tab.agent.conversation) if active_tab&.agent
flush_pending_reasoning_config(conversation: agent.conversation) unless active_tab
expanded_input = expand_prompt_template(input)
display_input = display_input || input if expanded_input
input = expanded_input || input
@footer_conversation = active_tab.agent.conversation if active_tab&.agent
@footer_conversation = agent.conversation unless active_tab
begin
@rewind_return_leaf_id = nil
auto_name_active_session(display_input || input) unless active_tab && plugin_tab?
if active_tab
submit_tab_input(active_tab, input, display_input: display_input)
pending_inputs = []
else
pending_inputs = run_interactive_turn(agent, input, display_input: display_input)
agent = @busy_replacement_agent if replacement_agent?(@busy_replacement_agent)
@busy_replacement_agent = nil
end
pending_inputs.reverse_each { |pending_input| @pending_inputs.unshift(pending_input) }
rescue StandardError => e
runtime_output("Error: #{e.message}")
end
end
flush_pending_reasoning_config(conversation: active_tab.agent.conversation) if active_tab&.agent
flush_pending_reasoning_config(conversation: agent.conversation) unless active_tab
active_tab&.agent&.conversation || agent.conversation
rescue Interrupt
flush_pending_reasoning_config(conversation: active_tab.agent.conversation) if active_tab&.agent
flush_pending_reasoning_config(conversation: agent&.conversation) unless active_tab
runtime_output("Goodbye.")
active_tab&.agent&.conversation || agent&.conversation
ensure
clear_bang_completion_provider
begin
stop_tabs if respond_to?(:stop_tabs, true)
@prompt.close if prompt_interface?
ensure
clear_interactive_warning_sink if respond_to?(:clear_interactive_warning_sink, true)
cleanup_unused_sessions
remember_active_session(session_store)
end
end
|
#one_shot(input, filter: false) ⇒ Object
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
|
# File 'lib/kward/cli.rb', line 414
def one_shot(input, filter: false)
streamed = false
assistant_streamed = false
markdown_chunks = []
conversation = new_conversation
apply_filter_system_prompt(conversation) if filter
hook_manager = lifecycle_hook_manager(conversation)
hook_context = lifecycle_hook_context(conversation)
agent = Agent.new(
client: @client,
tool_registry: ToolRegistry.new(
workspace: configured_workspace,
prompt: @prompt,
hook_manager: hook_manager,
hook_context: hook_context
),
conversation: conversation,
hook_manager: hook_manager,
hook_context: hook_context
)
answer = if filter
agent.ask(input)
else
agent.ask(input) do |event|
result = render_blocking_turn_event(event, markdown_chunks)
streamed = true if result
assistant_streamed = true if result == :assistant_streamed
end
end
flush_markdown_deltas(markdown_chunks) if streamed
return answer if filter
assistant_streamed ? "" : render_markdown_transcript(answer)
end
|
#piped_prompt ⇒ Object
624
625
626
|
# File 'lib/kward/cli.rb', line 624
def piped_prompt
read_stdin_input.to_s.strip
end
|
628
629
630
631
632
|
# File 'lib/kward/cli.rb', line 628
def read_stdin_input
return nil if @stdin.tty?
@stdin.read
end
|
#resolved_execution_mode(first_prompt:, stdin_input:) ⇒ Object
449
450
451
452
453
454
455
|
# File 'lib/kward/cli.rb', line 449
def resolved_execution_mode(first_prompt:, stdin_input:)
return @requested_mode unless @requested_mode == "auto"
return "chat" if stdin_input.nil? && first_prompt.nil?
return "filter" if !stdin_input.nil? && first_prompt
"oneshot"
end
|
#run ⇒ void
This method returns an undefined value.
Dispatches command-line modes, including RPC, login, stats export, Pan
mode, one-shot prompts, and interactive chat.
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
|
# File 'lib/kward/cli.rb', line 148
def run
@argv = (@argv)
ConfigFiles.skip_config = @skip_config
with_working_directory { dispatch }
rescue ConfigFiles::ConfigError => e
warn config_error_message(e)
exit 1
rescue ArgumentError => e
warn e.message
warn "Run `kward help` for available commands."
exit 1
rescue Client::AuthenticationError => e
raise if debug_errors?
warn authentication_error_message(e)
exit 1
rescue StandardError => e
raise if debug_errors?
warn runtime_error_message(e)
exit 1
ensure
ConfigFiles.skip_config = false
end
|
#run_prompt_or_interactive ⇒ Object
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
|
# File 'lib/kward/cli.rb', line 394
def run_prompt_or_interactive
ensure_client!
stdin_input = read_stdin_input
first_prompt = one_shot_prompt_argument
case resolved_execution_mode(first_prompt: first_prompt, stdin_input: stdin_input)
when "chat"
interactive_loop
when "filter"
raise ArgumentError, "Filter mode requires stdin input." if stdin_input.nil?
answer = one_shot(filter_prompt(instruction: first_prompt, input: stdin_input), filter: true)
puts answer unless answer.empty?
when "oneshot"
input = first_prompt || stdin_input.to_s.strip
answer = one_shot(input)
puts answer unless answer.empty?
end
end
|
#runtime_error_message(error) ⇒ Object
207
208
209
210
211
212
213
214
215
|
# File 'lib/kward/cli.rb', line 207
def runtime_error_message(error)
<<~MESSAGE.rstrip
Kward could not complete the request.
#{error.message}
Set KWARD_DEBUG=1 to show a backtrace.
MESSAGE
end
|