Skip to content
Kward Search API index

Class: Kward::PersistentShellSession

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

Overview

Owns one native kwsh interpreter process and serializes user and agent commands. The PTY owns terminal input/output; a private socket carries interpreter requests and authoritative shell state.

Defined Under Namespace

Classes: CommandInterrupted, InteractiveResult

Constant Summary collapse

Result =
Kwsh::Result
READ_SIZE =
4_096
STARTUP_TIMEOUT_SECONDS =
5
STATEFUL_COMMANDS =
%w[alias cd export pwd unset unalias .].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cwd: Dir.pwd, env: ENV.to_h, shell: Kwsh::DEFAULT_SHELL, configured_env: {}, aliases: {}, timeout_seconds: Kwsh::DEFAULT_TIMEOUT_SECONDS, max_output_bytes: Kwsh::DEFAULT_MAX_OUTPUT_BYTES, window_size_provider: nil) ⇒ PersistentShellSession

Returns a new instance of PersistentShellSession.



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
# File 'lib/kward/shell/persistent_session.rb', line 69

def initialize(cwd: Dir.pwd, env: ENV.to_h, shell: Kwsh::DEFAULT_SHELL, configured_env: {}, aliases: {}, timeout_seconds: Kwsh::DEFAULT_TIMEOUT_SECONDS, max_output_bytes: Kwsh::DEFAULT_MAX_OUTPUT_BYTES, window_size_provider: nil)
  @cwd = File.expand_path(cwd.to_s.empty? ? Dir.pwd : cwd.to_s)
  @base_env = env.to_h.transform_keys(&:to_s).transform_values(&:to_s)
  @configured_env = configured_env.to_h.transform_keys(&:to_s).transform_values(&:to_s)
  @aliases = aliases.to_h.transform_keys(&:to_s).transform_values(&:to_s)
  @shell = shell.to_s.empty? ? Kwsh::DEFAULT_SHELL : shell.to_s
  @timeout_seconds = timeout_seconds.to_i.positive? ? timeout_seconds.to_i : Kwsh::DEFAULT_TIMEOUT_SECONDS
  @max_output_bytes = max_output_bytes.to_i.positive? ? max_output_bytes.to_i : Kwsh::DEFAULT_MAX_OUTPUT_BYTES
  @window_size_provider = window_size_provider
  @last_command = nil
  @last_result = nil
  @command_mutex = Mutex.new
  @write_mutex = Mutex.new
  @marker_counter = 0
  @marker_prefix = "__KWARD_SHELL_#{SecureRandom.hex(16)}_"
  @closed = false
  @routing_shell = build_routing_shell
  @env = @routing_shell.child_env

  start_process
  initialize_protocol
rescue StandardError
  close
  raise
end

Instance Attribute Details

#cwd ⇒ Object (readonly)

Returns the value of attribute cwd.



37
38
39
# File 'lib/kward/shell/persistent_session.rb', line 37

def cwd
  @cwd
end

#last_command ⇒ Object (readonly)

Returns the value of attribute last_command.



37
38
39
# File 'lib/kward/shell/persistent_session.rb', line 37

def last_command
  @last_command
end

#timeout_seconds ⇒ Object (readonly)

Returns the value of attribute timeout_seconds.



37
38
39
# File 'lib/kward/shell/persistent_session.rb', line 37

def timeout_seconds
  @timeout_seconds
end

Instance Method Details

#child_env(interactive: false) ⇒ Object



99
100
101
# File 'lib/kward/shell/persistent_session.rb', line 99

def child_env(interactive: false)
  @env.dup
end

#close ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/kward/shell/persistent_session.rb', line 222

def close
  return if @closed

  @closed = true
  begin
    terminate_process_group(@pid) if @pid
  ensure
    @write_mutex.synchronize do
      @reader&.close unless @reader&.closed?
      @writer&.close unless @writer&.closed?
      @control&.close unless @control&.closed?
    end
    @process_thread&.join(0.5)
    @process_thread&.kill if @process_thread&.alive?
    @pid = nil
  end
rescue StandardError
  nil
end

#command_shell ⇒ Object



95
96
97
# File 'lib/kward/shell/persistent_session.rb', line 95

def command_shell
  @shell
end

#complete(input, cursor) ⇒ Object



204
205
206
# File 'lib/kward/shell/persistent_session.rb', line 204

def complete(input, cursor)
  completion_shell.complete(input, cursor)
end

#compose_input(line) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/kward/shell/persistent_session.rb', line 47

def compose_input(line)
  return line if !@pending_source && line.start_with?("?")

  source = @pending_source ? "#{@pending_source}\n#{line}" : line
  if incomplete_input?(source)
    @pending_source = source
    nil
  else
    @pending_source = nil
    source
  end
end

#context_snapshot(max_output_bytes: Kwsh::CONTEXT_OUTPUT_BYTES) ⇒ Object

Returns bounded shell state for an explicit shell-agent prompt.



195
196
197
198
199
200
201
202
# File 'lib/kward/shell/persistent_session.rb', line 195

def context_snapshot(max_output_bytes: Kwsh::CONTEXT_OUTPUT_BYTES)
  {
    cwd: @cwd,
    last_command: @last_command,
    exit_status: @last_result&.exit_status,
    last_output: context_output(@last_result&.output, max_output_bytes)
  }
end

#editor_command_result(command, display_command: command) ⇒ Object



216
217
218
219
220
# File 'lib/kward/shell/persistent_session.rb', line 216

def editor_command_result(command, display_command: command)
  token = NativeShell::Lexer.new(command).next_token&.value
  return unless token.is_a?(NativeShell::Word) && token.literal
  @routing_shell.editor_command_result(command, display_command: display_command)
end

#exited? ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/kward/shell/persistent_session.rb', line 39

def exited?
  @native_exited == true
end

#expand_alias(command, interactive: false) ⇒ Object



208
209
210
211
212
213
214
# File 'lib/kward/shell/persistent_session.rb', line 208

def expand_alias(command, interactive: false)
  token = NativeShell::Lexer.new(command).next_token&.value
  return command unless token.is_a?(NativeShell::Word) && token.literal
  @routing_shell.expand_alias(command, interactive: interactive)
rescue NativeShell::SyntaxError
  command
end

#incomplete_input?(source) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
63
64
65
66
67
# File 'lib/kward/shell/persistent_session.rb', line 60

def incomplete_input?(source)
  NativeShell::Parser.parse(source.sub(/\A\s*(?:capture|pty)\s+/, ""), aliases: @aliases || {})
  false
rescue NativeShell::IncompleteInput
  true
rescue NativeShell::SyntaxError
  false
end

#input_prompt_label ⇒ Object



43
44
45
# File 'lib/kward/shell/persistent_session.rb', line 43

def input_prompt_label
  @pending_source ? "Shell ... >" : prompt_label
end

#prompt_label ⇒ Object



103
104
105
# File 'lib/kward/shell/persistent_session.rb', line 103

def prompt_label
  "Shell #{display_cwd} $"
end

#record_interactive_result(output:, exit_status:) ⇒ Object

Records the safe output captured after an interactive terminal handoff.



188
189
190
191
192
# File 'lib/kward/shell/persistent_session.rb', line 188

def record_interactive_result(output:, exit_status:)
  return unless @last_command

  @last_result = Result.new(output: ANSI.sanitize_transcript(output.to_s), exit_status: exit_status)
end

#run(input, cancellation: nil, &block) ⇒ Object



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
# File 'lib/kward/shell/persistent_session.rb', line 107

def run(input, cancellation: nil, &block)
  command = input.to_s.strip
  return Result.new(output: "", exit_status: 0) if command.empty?

  expanded_command = expand_alias(command)
  native_command = command
  syntax_command = command
  if expanded_command.match?(/\A\s*(?:capture|pty)(?:\s|\z)/)
    syntax_command = expanded_command.sub(/\A\s*(?:capture|pty)\s+/, "")
  end
  tree = NativeShell::Parser.parse(syntax_command, aliases: @aliases)
  words = routing_words(expanded_command, tree)
  result = if tree.values.first.empty?
    Result.new(output: "", exit_status: 0)
  elsif words.first == "clear"
    Result.new(output: "", exit_status: 0, clear: true)
  elsif %w[exit logout].include?(words.first)
    execute_command(expanded_command.sub(/\Alogout\b/, "exit"), display_command: command, cancellation: cancellation, &block)
  elsif words.first == "capture"
    capture_result(command, expanded_command, cancellation: cancellation, &block)
  elsif words.first == "pty"
    interactive_result(command, expanded_command)
  elsif words.first == "source"
    source_result(command, words)
  elsif words.any? && (editor_result = editor_command_result(command))
    editor_result
  elsif stateful_command?(words)
    execute_command(native_command, display_command: command, cancellation: cancellation, &block)
  else
    Result.new(output: command_echo(command), exit_status: 0, interactive_command: native_command)
  end
  remember_result(command, result)
  result
rescue NativeShell::SyntaxError
  # Let the interpreter record the failure too, so the next $? is correct.
  result = execute_command(syntax_command, display_command: command, cancellation: cancellation, &block)
  remember_result(command, result)
  result
rescue ArgumentError => e
  result = Result.new(output: "#{command_echo(command)}kwsh: #{e.message}\n", exit_status: 2)
  remember_result(command, result)
  result
end

#run_for_agent(input, timeout_seconds: nil, cancellation: nil) ⇒ Object

Runs a command for the shell assistant without handing it the terminal.



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/kward/shell/persistent_session.rb', line 152

def run_for_agent(input, timeout_seconds: nil, cancellation: nil)
  command = input.to_s.strip
  return run(command, cancellation: cancellation) if command.empty?

  result = run(command, cancellation: cancellation)
  return result unless result.interactive_command

  result = execute_command(
    result.interactive_command,
    display_command: command,
    timeout_seconds: timeout_seconds,
    cancellation: cancellation,
    suppress_git_pager: true
  )
  remember_result(command, result)
  result
end

#run_interactive(command, input:, sink:, tab_action_handler: nil, on_detach: nil) ⇒ Object

Runs an external command through the same persistent shell process while the caller owns the terminal.



172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/kward/shell/persistent_session.rb', line 172

def run_interactive(command, input:, sink:, tab_action_handler: nil, on_detach: nil)
  protocol = with_raw_input(input) do
    execute_protocol(command, input: input, sink: sink, tab_action_handler: tab_action_handler, on_detach: on_detach)
  end
  update_cwd(protocol[:cwd]) unless protocol[:background]
  InteractiveResult.new(
    exit_status: protocol[:status] || 1,
    input_forwarded: protocol[:input_forwarded],
    tab_action: protocol[:tab_action],
    background: protocol[:background]
  )
ensure
  sink.finish if sink.respond_to?(:finish)
end