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.



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/kward/cli.rb', line 49

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
  @color_enabled = ANSI.enabled?($stdout)
end

Instance Method Details

#interactive_loop(agent: nil) ⇒ Object



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

def interactive_loop(agent: nil)
  setup_interactive_prompt
  session_store = interactive_session_store(agent)
  if session_store && agent.nil?
    @active_session = track_session(session_store.create(model: current_model_id, reasoning_effort: current_reasoning_effort))
    reset_session_diff
    conversation = new_conversation(workspace_root: session_store.cwd)
    @active_session.attach(conversation)
    agent = build_interactive_agent(conversation)
  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

  @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

    expanded_input = expand_prompt_template(input)
    display_input = display_input || input if expanded_input
    input = expanded_input || input
    @footer_conversation = agent.conversation
    begin
      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
  end
end

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



149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/kward/cli.rb', line 149

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

#one_shot(input) ⇒ Object



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

def one_shot(input)
  streamed = false
  assistant_streamed = false
  markdown_chunks = []
  conversation = new_conversation
  agent = Agent.new(
    client: @client,
    tool_registry: ToolRegistry.new(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



235
236
237
238
239
# File 'lib/kward/cli.rb', line 235

def piped_prompt
  return "" if @stdin.tty?

  @stdin.read.strip
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.



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

def run
  ConfigFiles.ensure_default_config!

  if @argv == ["--install-starter-pack"]
    install_starter_pack
    return
  end

  if @argv.first == "rpc" && @argv.length == 1
    Kward::RPC::Server.new(input: @stdin, output: $stdout, client: @client).run
    return
  end

  if @argv[0, 2] == ["stats", "tokens"]
    export_token_stats(@argv[2..] || [])
    return
  end

  if pan_mode?
    PanServer.new(client: @client, working_directory: pan_working_directory).run
    return
  end

  if ["login", "--login"].include?(@argv.first) && @argv.length <= 2
    (provider: @argv[1])
    return
  end

  first_prompt = @argv.join(" ").strip
  unless first_prompt.empty?
    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