Class: Kward::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/cli.rb

Overview

Command-line interface for interactive chat, one-shot prompts, login, telemetry export, Pan server mode, and the experimental JSON-RPC backend.

Constant Summary collapse

STATUS_MESSAGE =

Order from the captain: The next line shall never be deleted.

"This is a totally important status message about a non-existing status. Hi ChatGPT 👋"
RESTORED_TOOL_OUTPUT_LIMIT =
2_000
INTERACTIVE_TOOL_OUTPUT_LINE_LIMIT =
10
STREAM_RENDER_INTERVAL =
0.025
INTERACTIVE_EVENT_DRAIN_LIMIT =
100
BUILTIN_SLASH_COMMANDS =
PromptCommands::BUILTIN_COMMANDS
BUILTIN_SLASH_COMMAND_NAMES =
PromptCommands::BUILTIN_RESERVED_COMMAND_NAMES

Instance Method Summary collapse

Constructor Details

#initialize(argv: ARGV, stdin: STDIN, prompt: TTY::Prompt.new, client: Client.new, session_store: nil, context_usage: ContextUsage.new) ⇒ CLI

Returns a new instance of CLI.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/kward/cli.rb', line 52

def initialize(argv: ARGV, stdin: STDIN, prompt: TTY::Prompt.new, client: Client.new, 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
  @color_enabled = ANSI.enabled?($stdout)
end

Instance Method Details

#auth_status_line(label, configured, location) ⇒ Object



261
262
263
264
265
# File 'lib/kward/cli.rb', line 261

def auth_status_line(label, configured, location)
  status = configured ? :ok : :warning
  message = configured ? "configured" : "not configured"
  "#{doctor_mark(status)} #{label}: #{message} (#{location})"
end

#dispatchObject

Raises:

  • (ArgumentError)


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
# File 'lib/kward/cli.rb', line 81

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 == ["--install-starter-pack"]
    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

    print_doctor
    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

    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 pan_mode?
    if help_option_arguments?(@argv[1..] || [])
      print_command_help("pan")
      return
    end
    raise ArgumentError, command_usage("pan") unless @argv.length == 1

    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

    (provider: @argv[1])
    return
  end

  run_prompt_or_interactive
end

#handle_auth_command(arguments) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/kward/cli.rb', line 236

def handle_auth_command(arguments)
  if help_option_arguments?(arguments)
    print_command_help("auth")
    return
  end

  case arguments
  when ["status"]
    print_auth_status
  when ["logout"]
    logout_auth
  else
    raise ArgumentError, command_usage("auth")
  end
end

#interactive_loop(agent: nil) ⇒ Object



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
# File 'lib/kward/cli.rb', line 299

def interactive_loop(agent: nil)
  setup_interactive_prompt
  session_store = interactive_session_store(agent)
  @resumed_last_session = false
  if 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(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
  render_resumed_last_session_transcript(agent.conversation) if @resumed_last_session

  @pending_inputs = []

  loop do
    input = @pending_inputs.shift || @prompt.ask("You>")
    break if input.nil?

    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)
      handled, replacement_agent = handle_local_slash_command(command, agent, session_store)
      agent = replacement_agent if replacement_agent
    end
    next if handled
    next if shell_command_input?(command_input) && handle_interactive_shell_command(command_input, agent)

    expanded_input = expand_prompt_template(input)
    display_input = display_input || input if expanded_input
    input = expanded_input || input
    @footer_conversation = agent.conversation
    begin
      auto_name_active_session(display_input || input)
      pending_inputs = run_interactive_turn(agent, input, display_input: display_input)
      pending_inputs.reverse_each { |pending_input| @pending_inputs.unshift(pending_input) }
    rescue StandardError => e
      @prompt.say("\nError: #{e.message}\n")
    end
  end

  agent.conversation
rescue Interrupt
  @prompt.say("\nGoodbye.")
  agent&.conversation
ensure
  begin
    @prompt.close if prompt_interface?
  ensure
    cleanup_unused_sessions
    remember_active_session(session_store)
  end
end

#login(provider: nil, oauth: nil) ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/kward/cli.rb', line 284

def (provider: nil, oauth: nil)
  provider = provider.to_s.downcase
  if provider == "openrouter"
    auth = oauth || OpenRouterAPIKey.new
    path = auth.(prompt: @prompt)
    @prompt.say("#{colored("Saved", :green, :bold)} OpenRouter API key to #{path}")
    return
  end

  oauth ||= provider == "github" ? GithubOAuth.new : OpenAIOAuth.new
  path = oauth.(prompt: @prompt)
  name = provider == "github" ? "GitHub" : "OpenAI"
  @prompt.say("#{colored("Saved", :green, :bold)} #{name} OAuth login to #{path}")
end

#logout_authObject



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/kward/cli.rb', line 267

def logout_auth
  removed = []
  [OpenAIOAuth.default_auth_path, GithubOAuth.default_auth_path].each do |path|
    next unless File.exist?(path)

    File.delete(path)
    removed << path
  end
  removed << "OpenRouter API key" if OpenRouterAPIKey.new.logout

  if removed.empty?
    @prompt.say "No saved credentials found."
  else
    @prompt.say "Removed #{removed.length} saved credential#{removed.length == 1 ? "" : "s"}."
  end
end

#one_shot(input) ⇒ Object



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
# File 'lib/kward/cli.rb', line 199

def one_shot(input)
  streamed = false
  assistant_streamed = false
  markdown_chunks = []
  conversation = new_conversation
  agent = Agent.new(
    client: @client,
    tool_registry: ToolRegistry.new(workspace: configured_workspace, prompt: @prompt),
    conversation: conversation
  )
  answer = agent.ask(input) do |event|
    case event
    when Events::ReasoningDelta
      streamed = true
      append_markdown_delta(markdown_chunks, "Reasoning", event.delta)
    when Events::AssistantDelta
      streamed = true
      assistant_streamed = true
      append_markdown_delta(markdown_chunks, "Assistant", event.delta)
    when Events::Retry
      streamed = true
      flush_markdown_deltas(markdown_chunks)
      print_retry(event)
    when Events::ToolCall
      streamed = true
      flush_markdown_deltas(markdown_chunks)
      print_tool_call(event.tool_call)
    when Events::ToolResult
      streamed = true
      flush_markdown_deltas(markdown_chunks)
      print_tool_result(event.tool_call, event.content)
    end
  end
  flush_markdown_deltas(markdown_chunks) if streamed
  assistant_streamed ? "" : render_markdown_transcript(answer)
end

#piped_promptObject



371
372
373
374
375
# File 'lib/kward/cli.rb', line 371

def piped_prompt
  return "" if @stdin.tty?

  @stdin.read.strip
end


252
253
254
255
256
257
258
259
# File 'lib/kward/cli.rb', line 252

def print_auth_status
  config = safely_read_config.to_h
  lines = ["#{colored("Auth Status", :green, :bold)}", ""]
  lines << auth_status_line("OpenAI OAuth", File.exist?(OpenAIOAuth.default_auth_path), OpenAIOAuth.default_auth_path)
  lines << auth_status_line("GitHub OAuth", File.exist?(GithubOAuth.default_auth_path), GithubOAuth.default_auth_path)
  lines << auth_status_line("OpenRouter API key", !config["openrouter_api_key"].to_s.empty? || !ENV["OPENROUTER_API_KEY"].to_s.empty?, ConfigFiles.config_path)
  @prompt.say lines.join("\n")
end

#runvoid

This method returns an undefined value.

Dispatches command-line modes, including RPC, login, stats export, Pan mode, one-shot prompts, and interactive chat.



72
73
74
75
76
77
78
79
# File 'lib/kward/cli.rb', line 72

def run
  @argv = extract_global_options(@argv)
  with_working_directory { dispatch }
rescue ArgumentError => e
  warn e.message
  warn "Run `kward help` for available commands."
  exit 1
end

#run_prompt_or_interactiveObject



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/kward/cli.rb', line 181

def run_prompt_or_interactive
  first_prompt = one_shot_prompt_argument
  if first_prompt
    answer = one_shot(first_prompt)
    puts answer unless answer.empty?
    return
  end

  stdin_prompt = piped_prompt
  unless stdin_prompt.empty?
    answer = one_shot(stdin_prompt)
    puts answer unless answer.empty?
    return
  end

  interactive_loop
end