kward 0.85.0 → 0.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +130 -0
  3. data/CONTRIBUTING.md +1 -1
  4. data/Gemfile.lock +6 -2
  5. data/README.md +3 -3
  6. data/Rakefile +3 -0
  7. data/doc/agent-tools.md +11 -0
  8. data/doc/api.md +4 -1
  9. data/doc/composer.md +4 -3
  10. data/doc/configuration.md +60 -11
  11. data/doc/extensibility.md +2 -0
  12. data/doc/getting-started.md +3 -3
  13. data/doc/git.md +1 -1
  14. data/doc/memory.md +1 -1
  15. data/doc/plugins.md +40 -5
  16. data/doc/providers.md +10 -4
  17. data/doc/rpc.md +125 -7
  18. data/doc/session-management.md +36 -1
  19. data/doc/shell.md +643 -27
  20. data/doc/tabs.md +2 -1
  21. data/doc/troubleshooting.md +1 -1
  22. data/doc/usage.md +21 -11
  23. data/examples/plugins/openrouter_proxy/README.md +103 -0
  24. data/examples/plugins/openrouter_proxy/fake_embeddings.rb +85 -0
  25. data/examples/plugins/openrouter_proxy/plugin.rb +7 -0
  26. data/examples/plugins/openrouter_proxy/protocol.rb +202 -0
  27. data/examples/plugins/openrouter_proxy/server.rb +186 -0
  28. data/examples/plugins/space_invaders.rb +0 -1
  29. data/exe/kward +2 -2
  30. data/exe/kwsh +7 -0
  31. data/kward.gemspec +3 -1
  32. data/lib/kward/agent.rb +43 -9
  33. data/lib/kward/cli/commands.rb +41 -11
  34. data/lib/kward/cli/interactive_turn.rb +10 -0
  35. data/lib/kward/cli/plugins.rb +5 -1
  36. data/lib/kward/cli/prompt_interface.rb +4 -1
  37. data/lib/kward/cli/rendering.rb +21 -28
  38. data/lib/kward/cli/runtime_helpers.rb +52 -34
  39. data/lib/kward/cli/settings/model.rb +1 -12
  40. data/lib/kward/cli/tabs.rb +91 -18
  41. data/lib/kward/cli/tool_summaries.rb +2 -0
  42. data/lib/kward/cli/transcript_formatter.rb +3 -10
  43. data/lib/kward/cli/worktrees.rb +1 -0
  44. data/lib/kward/cli.rb +56 -7
  45. data/lib/kward/config/core.rb +16 -5
  46. data/lib/kward/config/extensions.rb +3 -0
  47. data/lib/kward/config/paths.rb +11 -0
  48. data/lib/kward/config/settings.rb +7 -0
  49. data/lib/kward/conversation.rb +11 -1
  50. data/lib/kward/entrypoint.rb +14 -0
  51. data/lib/kward/events.rb +2 -0
  52. data/lib/kward/generated_images.rb +237 -0
  53. data/lib/kward/model/catalog.rb +6 -3
  54. data/lib/kward/model/client.rb +105 -36
  55. data/lib/kward/model/codex_images.rb +83 -0
  56. data/lib/kward/model/copilot_models.rb +8 -4
  57. data/lib/kward/model/model_info.rb +27 -9
  58. data/lib/kward/model/openrouter_model_cache.rb +4 -2
  59. data/lib/kward/model/payloads.rb +6 -5
  60. data/lib/kward/model/sources.rb +3 -1
  61. data/lib/kward/model/stream_parser.rb +4 -7
  62. data/lib/kward/pan/index.html.erb +8 -1
  63. data/lib/kward/pan/server.rb +13 -1
  64. data/lib/kward/plugins/codex_responses.rb +73 -0
  65. data/lib/kward/plugins/host.rb +16 -0
  66. data/lib/kward/plugins/http_server.rb +83 -0
  67. data/lib/kward/plugins/registry.rb +39 -0
  68. data/lib/kward/prompt_interface/composer_controller.rb +0 -1
  69. data/lib/kward/prompt_interface/composer_renderer.rb +159 -72
  70. data/lib/kward/prompt_interface/editor/controller.rb +1 -1
  71. data/lib/kward/prompt_interface/editor/renderer.rb +10 -7
  72. data/lib/kward/prompt_interface/file_overlay.rb +3 -3
  73. data/lib/kward/prompt_interface/generated_image_preview.rb +162 -0
  74. data/lib/kward/prompt_interface/git_prompt.rb +18 -11
  75. data/lib/kward/prompt_interface/interactive/renderer.rb +1 -1
  76. data/lib/kward/prompt_interface/interactive/state.rb +18 -20
  77. data/lib/kward/prompt_interface/key_handler.rb +108 -25
  78. data/lib/kward/prompt_interface/layout.rb +11 -1
  79. data/lib/kward/prompt_interface/overlay_renderer.rb +25 -8
  80. data/lib/kward/prompt_interface/project_browser.rb +27 -54
  81. data/lib/kward/prompt_interface/prompt_renderer.rb +27 -35
  82. data/lib/kward/prompt_interface/question_prompt.rb +19 -28
  83. data/lib/kward/prompt_interface/runtime_state.rb +31 -9
  84. data/lib/kward/prompt_interface/screen.rb +24 -21
  85. data/lib/kward/prompt_interface/selection_prompt.rb +8 -8
  86. data/lib/kward/prompt_interface/slash_overlay.rb +1 -1
  87. data/lib/kward/prompt_interface/transcript_renderer.rb +7 -6
  88. data/lib/kward/prompt_interface.rb +109 -39
  89. data/lib/kward/prompts.rb +7 -1
  90. data/lib/kward/pty/adaptive_output_sink.rb +38 -4
  91. data/lib/kward/pty/interactive_runner.rb +20 -28
  92. data/lib/kward/pty/transcript_normalizer.rb +65 -21
  93. data/lib/kward/rpc/config_manager.rb +3 -0
  94. data/lib/kward/rpc/server.rb +27 -5
  95. data/lib/kward/rpc/session_manager.rb +62 -17
  96. data/lib/kward/rpc/transcript_normalizer.rb +11 -7
  97. data/lib/kward/sessions/store.rb +30 -3
  98. data/lib/kward/shell/kwsh.rb +27 -7
  99. data/lib/kward/shell/kwshrc.rb +11 -2
  100. data/lib/kward/shell/native_arithmetic.rb +255 -0
  101. data/lib/kward/shell/native_arrays.rb +102 -0
  102. data/lib/kward/shell/native_braces.rb +96 -0
  103. data/lib/kward/shell/native_builtins.rb +476 -0
  104. data/lib/kward/shell/native_completion.rb +169 -0
  105. data/lib/kward/shell/native_condition.rb +75 -0
  106. data/lib/kward/shell/native_directory.rb +116 -0
  107. data/lib/kward/shell/native_exec_state.rb +73 -0
  108. data/lib/kward/shell/native_expansion.rb +252 -0
  109. data/lib/kward/shell/native_fields.rb +62 -0
  110. data/lib/kward/shell/native_glob.rb +96 -0
  111. data/lib/kward/shell/native_history.rb +242 -0
  112. data/lib/kward/shell/native_interactive.rb +164 -0
  113. data/lib/kward/shell/native_invocation.rb +42 -0
  114. data/lib/kward/shell/native_jobs.rb +250 -0
  115. data/lib/kward/shell/native_line_editor.rb +382 -0
  116. data/lib/kward/shell/native_line_terminal.rb +286 -0
  117. data/lib/kward/shell/native_locale.rb +109 -0
  118. data/lib/kward/shell/native_locals.rb +57 -0
  119. data/lib/kward/shell/native_pattern.rb +200 -0
  120. data/lib/kward/shell/native_process.rb +279 -0
  121. data/lib/kward/shell/native_program.rb +40 -0
  122. data/lib/kward/shell/native_programmable_completion.rb +115 -0
  123. data/lib/kward/shell/native_prompt_format.rb +89 -0
  124. data/lib/kward/shell/native_runtime.rb +964 -0
  125. data/lib/kward/shell/native_substitution.rb +110 -0
  126. data/lib/kward/shell/native_syntax.rb +946 -0
  127. data/lib/kward/shell/native_traps.rb +196 -0
  128. data/lib/kward/shell/native_vi.rb +407 -0
  129. data/lib/kward/shell/native_vi_terminal.rb +19 -0
  130. data/lib/kward/shell/native_worker.rb +82 -0
  131. data/lib/kward/shell/persistent_session.rb +184 -190
  132. data/lib/kward/shell/prompt.rb +14 -0
  133. data/lib/kward/shell/prompt_agent.rb +17 -0
  134. data/lib/kward/shell/script_runner.rb +244 -0
  135. data/lib/kward/shell/standalone_agent.rb +31 -0
  136. data/lib/kward/shell/standalone_link.rb +78 -0
  137. data/lib/kward/shell/standalone_terminal.rb +287 -0
  138. data/lib/kward/terminal/keys.rb +22 -1
  139. data/lib/kward/terminal/locale_text.rb +29 -0
  140. data/lib/kward/terminal/sequences.rb +45 -4
  141. data/lib/kward/tools/datetime.rb +85 -0
  142. data/lib/kward/tools/generate_image.rb +36 -0
  143. data/lib/kward/tools/registry.rb +35 -9
  144. data/lib/kward/tools/tool_call.rb +3 -1
  145. data/lib/kward/transcripts/markdown_transcript.rb +8 -0
  146. data/lib/kward/transcripts/turn_summary_formatter.rb +93 -0
  147. data/lib/kward/transport/gateway.rb +2 -1
  148. data/lib/kward/turn_summary.rb +68 -0
  149. data/lib/kward/version.rb +1 -1
  150. data/lib/main.rb +6 -3
  151. metadata +84 -1
@@ -0,0 +1,382 @@
1
+ require_relative "../terminal/keys"
2
+ require_relative "../terminal/sequences"
3
+ require_relative "native_locale"
4
+ require_relative "native_syntax"
5
+
6
+ module Kward
7
+ module NativeShell
8
+ # Non-modal edit state. The terminal adapter owns byte reads and redraws.
9
+ class LineEditor
10
+ # Keep path and flag punctuation in words, like the default Zsh Emacs keymap.
11
+ WORD_CHARACTERS = "[:alnum:]#{Regexp.escape('*?_-.[]~=/&;!#$%^(){}<>')}".freeze
12
+ WORD_START = /\G[#{WORD_CHARACTERS}]*[^#{WORD_CHARACTERS}]*/
13
+ WORD_END = /\G[^#{WORD_CHARACTERS}]*[#{WORD_CHARACTERS}]*/
14
+
15
+ HISTORY_SEARCH_KEYS = [TerminalKeys::CTRL_R, TerminalKeys::CTRL_S].freeze
16
+ CUT_LIMIT = 8
17
+ UNDO_LIMIT = 100
18
+
19
+ def initialize(runtime)
20
+ @runtime = runtime
21
+ @cuts = []
22
+ end
23
+
24
+ def encoding
25
+ @locale.encoding
26
+ end
27
+
28
+ def read(get:, paste:, changed:, alert:, clear:, erase:, kill:, eof:, interrupt:, suggestions: false, draft: nil, completion_cancel: nil)
29
+ Locale.with(@runtime.variables) do |locale|
30
+ @locale = locale
31
+ @line = draft.to_s.b.force_encoding(encoding).scrub
32
+ @position = @line.length
33
+ @history = @runtime.history
34
+ @cuts.clear if @private_edit != @history.paused?
35
+ @private_edit = @history.paused?
36
+ suggestions &&= !@private_edit
37
+ @history.refresh
38
+ @entries = @history.entries
39
+ @index = @entries.length
40
+ @history_prefix = nil
41
+ @vertical_column = nil
42
+ @menu = nil
43
+ @last_tab = false
44
+ @continued_cut = false
45
+ @undo = []
46
+ @last_yank = nil
47
+ loop do
48
+ suggestion = suggestion_for_draft if suggestions
49
+ draw(changed, suggestion)
50
+ key = get.call
51
+ return nil unless key
52
+ raise Interrupt if key == interrupt
53
+ next if @menu && handle_menu(key)
54
+ if HISTORY_SEARCH_KEYS.include?(key) && ![erase, kill, eof].include?(key)
55
+ @last_tab = @continued_cut = false
56
+ @last_yank = nil
57
+ refresh_history if @index == @entries.length
58
+ @history_prefix = nil
59
+ key = search_history(key, get: get, changed: changed, alert: alert, clear: clear, erase: erase, interrupt: interrupt)
60
+ return nil unless key
61
+ next if key == :cancel_search
62
+ end
63
+ if TerminalKeys::RETURN.include?(key)
64
+ draw(changed, nil) if suggestion
65
+ return @line + "\n"
66
+ end
67
+ return nil if key == eof && @line.empty?
68
+
69
+ @vertical_column = nil unless (TerminalKeys::UP + TerminalKeys::DOWN).include?(key)
70
+ @last_tab = false unless TerminalKeys::TAB.include?(key)
71
+ @last_yank = nil unless TerminalKeys::ALT_Y.include?(key)
72
+ consecutive_cut = @continued_cut
73
+ @continued_cut = false
74
+ case key
75
+ when *TerminalKeys::TAB then complete(alert, completion_cancel)
76
+ when *TerminalKeys::UP then move_vertical(-1)
77
+ when *TerminalKeys::DOWN then move_vertical(1)
78
+ when TerminalKeys::CTRL_P then recall(-1)
79
+ when TerminalKeys::CTRL_N then recall(1)
80
+ when *TerminalKeys::LEFT, TerminalKeys::CTRL_B then @position = [@position - 1, 0].max
81
+ when *TerminalKeys::RIGHT
82
+ suggestion ? insert(suggestion) : move_right
83
+ when TerminalKeys::CTRL_F then move_right
84
+ when *TerminalKeys::HOME, TerminalKeys::CTRL_A then @position = line_start
85
+ when *TerminalKeys::END_KEY, TerminalKeys::CTRL_E then @position = line_end
86
+ when erase, *TerminalKeys::BACKSPACE
87
+ replace(@position - 1, 1) if @position.positive?
88
+ when kill then cut(0, @line.length)
89
+ when eof, *TerminalKeys::DELETE then replace(@position, 1) if @position < @line.length
90
+ when *TerminalKeys::ALT_LEFT, *TerminalKeys::ALT_B then @position = previous_word
91
+ when *TerminalKeys::ALT_RIGHT, *TerminalKeys::ALT_F then @position = @line.match(WORD_START, @position).end(0)
92
+ when TerminalKeys::CTRL_K then cut(@position, kill_line_end, consecutive_cut)
93
+ when TerminalKeys::CTRL_W, *TerminalKeys::ALT_BACKSPACE then cut(previous_word, @position, consecutive_cut)
94
+ when *TerminalKeys::ALT_D then cut(@position, @line.match(WORD_END, @position).end(0), consecutive_cut)
95
+ when TerminalKeys::CTRL_Y then yank(0)
96
+ when *TerminalKeys::ALT_Y then yank_pop
97
+ when *TerminalKeys::ALT_LAST_WORD then insert_last_word(alert)
98
+ when TerminalKeys::CTRL_L then clear.call
99
+ when TerminalKeys::CTRL_T, TerminalKeys::CTRL_T_CSI_U then transpose
100
+ when TerminalKeys::CTRL_UNDERSCORE then undo
101
+ when *TerminalKeys::SHIFT_ENTER then insert("\n")
102
+ when TerminalSequences::BRACKETED_PASTE_START
103
+ text = paste.call
104
+ return nil unless text
105
+ insert(text)
106
+ else
107
+ insert(key) if printable_key?(key)
108
+ end
109
+ rescue EncodingError, ExpansionError
110
+ alert.call
111
+ end
112
+ end
113
+ ensure
114
+ @locale = @line = @draft = @entries = @undo = @last_yank = @history_prefix = @menu = nil
115
+ end
116
+
117
+ private
118
+
119
+ def complete(alert, cancel)
120
+ completion = @runtime.complete_line(@line, @position, cancel: cancel)
121
+ return alert.call unless completion
122
+
123
+ if @line[completion.range] != completion.replacement
124
+ replace(completion.range.begin, completion.range.size, @locale.text(completion.replacement))
125
+ elsif @last_tab && completion.candidates.length > 1
126
+ @menu = completion
127
+ @menu_index = 0
128
+ else
129
+ alert.call
130
+ end
131
+ @last_tab = true
132
+ end
133
+
134
+ def draw(changed, suggestion)
135
+ return changed.call(@line, @position, suggestion: suggestion) unless @menu
136
+
137
+ text = @line.dup
138
+ choice = @locale.text(@menu.choices.fetch(@menu_index))
139
+ text[@menu.choice_range] = choice
140
+ changed.call(text, @menu.choice_range.begin + choice.length, menu: [@menu.candidates, @menu_index])
141
+ end
142
+
143
+ def suggestion_for_draft
144
+ return if @menu || @line.empty? || @line.include?("\n") || @position != @line.length || @index != @entries.length
145
+
146
+ @entries.reverse_each do |_, entry|
147
+ next unless entry.b.start_with?(@line.b)
148
+
149
+ text = @locale.text(entry)
150
+ next unless text.valid_encoding? && text.length > @position && !text.match?(/[[:cntrl:]]/)
151
+
152
+ return text[@position..]
153
+ end
154
+ nil
155
+ end
156
+
157
+ def move_right
158
+ @position += 1 if @position < @line.length
159
+ end
160
+
161
+ def handle_menu(key)
162
+ case key
163
+ when *TerminalKeys::TAB, *TerminalKeys::SHIFT_TAB
164
+ direction = TerminalKeys::TAB.include?(key) ? 1 : -1
165
+ @menu_index = (@menu_index + direction) % @menu.choices.length
166
+ return true
167
+ when TerminalKeys::ESCAPE
168
+ @menu = nil
169
+ @last_tab = false
170
+ return true
171
+ end
172
+
173
+ replace(@menu.choice_range.begin, @menu.choice_range.size, @locale.text(@menu.choices.fetch(@menu_index)))
174
+ @menu = nil
175
+ @last_tab = false
176
+ TerminalKeys::RETURN.include?(key)
177
+ end
178
+
179
+ def previous_word
180
+ @position - @line[0, @position].reverse.match(WORD_END).end(0)
181
+ end
182
+
183
+ def line_start(position = @position)
184
+ (@line[0...position].rindex("\n") || -1) + 1
185
+ end
186
+
187
+ def line_end(position = @position)
188
+ @line.index("\n", position) || @line.length
189
+ end
190
+
191
+ def kill_line_end
192
+ finish = line_end
193
+ finish == @position && finish < @line.length ? finish + 1 : finish
194
+ end
195
+
196
+ def move_vertical(direction)
197
+ start = line_start
198
+ finish = line_end
199
+ return recall(direction, prefix: true) unless @line.include?("\n")
200
+ return if direction.negative? ? start.zero? : finish == @line.length
201
+
202
+ @vertical_column ||= @position - start
203
+ target = direction.negative? ? line_start(start - 1) : finish + 1
204
+ @position = [target + @vertical_column, line_end(target)].min
205
+ end
206
+
207
+ def cut(start, finish, consecutive = false)
208
+ return if start == finish
209
+
210
+ text = @line[start...finish]
211
+ if consecutive
212
+ @cuts[0] = start < @position ? text + @cuts.first : @cuts.first + text
213
+ else
214
+ @cuts.unshift(text)
215
+ @cuts.pop if @cuts.length > CUT_LIMIT
216
+ end
217
+ replace(start, finish - start)
218
+ @continued_cut = true
219
+ end
220
+
221
+ def yank(index, start = @position, length = 0)
222
+ return if @cuts.empty?
223
+
224
+ text = @locale.text(@cuts.fetch(index)).scrub
225
+ replace(start, length, text)
226
+ @last_yank = [index, start, text.length]
227
+ end
228
+
229
+ def yank_pop
230
+ return unless @last_yank && @cuts.length > 1
231
+
232
+ index, start, length = @last_yank
233
+ yank((index + 1) % @cuts.length, start, length)
234
+ end
235
+
236
+ def insert_last_word(alert)
237
+ return alert.call unless @index.positive?
238
+
239
+ word = Lexer.new(history_text(@index - 1)).tokens.reverse_each.find { |token| token.value.is_a?(Word) }
240
+ word ? insert(word.source) : alert.call
241
+ rescue SyntaxError
242
+ alert.call
243
+ end
244
+
245
+ def transpose
246
+ right = @position
247
+ right -= 1 if right == @line.length || @line[right] == "\n"
248
+ return unless right.positive?
249
+
250
+ pair = @line[right - 1, 2]
251
+ replace(right - 1, 2, pair.reverse) unless pair.include?("\n")
252
+ end
253
+
254
+ def insert(text)
255
+ replace(@position, 0, @locale.text(text))
256
+ end
257
+
258
+ def replace(start, length, text = "")
259
+ removed = @line[start, length]
260
+ if removed != text
261
+ @history_prefix = nil
262
+ @undo << [start, text.length, removed, @position]
263
+ @undo.shift if @undo.length > UNDO_LIMIT
264
+ @line[start, length] = text
265
+ end
266
+ @position = start + text.length
267
+ end
268
+
269
+ def undo
270
+ change = @undo.pop
271
+ return unless change
272
+
273
+ start, length, text, cursor = change
274
+ @history_prefix = nil
275
+ @line[start, length] = text
276
+ @position = cursor
277
+ end
278
+
279
+ def printable_key?(key)
280
+ key.length == 1 && key.ord >= 32 && key.ord != 127
281
+ end
282
+
283
+ def refresh_history
284
+ @history.refresh
285
+ @entries = @history.entries
286
+ @index = @entries.length
287
+ end
288
+
289
+ def recall(direction, prefix: false)
290
+ if @index == @entries.length
291
+ return if direction.positive?
292
+
293
+ refresh_history
294
+ end
295
+ @history_prefix = prefix ? (@history_prefix || @line.dup) : nil
296
+ index = @index + direction
297
+ while index.between?(0, @entries.length)
298
+ if index == @entries.length || !@history_prefix || history_text(index).start_with?(@history_prefix)
299
+ select_history(index)
300
+ @history_prefix = nil if index == @entries.length
301
+ return
302
+ end
303
+ index += direction
304
+ end
305
+ end
306
+
307
+ def search_history(key, get:, changed:, alert:, clear:, erase:, interrupt:)
308
+ query = "".force_encoding(encoding)
309
+ direction = history_direction(key)
310
+ anchor = @index
311
+ index = nil
312
+ failed = false
313
+ loop do
314
+ label = direction.negative? ? "reverse-i-search" : "forward-i-search"
315
+ label = "failed #{label}" if failed
316
+ prefix = "(#{label}: #{query}"
317
+ changed.call(prefix + "): " + (index ? history_text(index) : ""), prefix.length)
318
+ key = get.call
319
+ return nil unless key
320
+ raise Interrupt if key == interrupt
321
+
322
+ match = nil
323
+ case key
324
+ when TerminalKeys::CTRL_G, TerminalKeys::ESCAPE then return :cancel_search
325
+ when TerminalKeys::CTRL_L
326
+ clear.call
327
+ next
328
+ when *HISTORY_SEARCH_KEYS
329
+ direction = history_direction(key)
330
+ match = history_match(query, index ? index + direction : anchor, direction)
331
+ anchor = match if match
332
+ when erase, *TerminalKeys::BACKSPACE
333
+ query.chop!
334
+ index = nil if query.empty?
335
+ match = history_match(query, anchor, direction) unless query.empty?
336
+ else
337
+ if printable_key?(key)
338
+ query << key
339
+ match = history_match(query, anchor, direction)
340
+ elsif TerminalKeys::RETURN.include?(key) && (!index || failed)
341
+ alert.call
342
+ next
343
+ else
344
+ select_history(index) if index && !failed
345
+ return key
346
+ end
347
+ end
348
+ index = match if match
349
+ failed = match.nil? && !query.empty?
350
+ end
351
+ end
352
+
353
+ def history_direction(key)
354
+ key == TerminalKeys::CTRL_R ? -1 : 1
355
+ end
356
+
357
+ def history_match(query, start, direction)
358
+ fold = query == query.downcase
359
+ start = @entries.length - 1 if direction.negative? && start == @entries.length
360
+ while start.between?(0, @entries.length - 1)
361
+ text = history_text(start)
362
+ text = text.downcase if fold
363
+ return start if text.include?(query)
364
+ start += direction
365
+ end
366
+ nil
367
+ end
368
+
369
+ def select_history(index)
370
+ @draft = @line.dup if @index == @entries.length
371
+ @line = index == @entries.length ? @draft.dup : history_text(index)
372
+ @index = index
373
+ @position = @line.length
374
+ @undo.clear
375
+ end
376
+
377
+ def history_text(index)
378
+ @locale.text(@entries.fetch(index).last).scrub
379
+ end
380
+ end
381
+ end
382
+ end
@@ -0,0 +1,286 @@
1
+ require "io/console"
2
+ require_relative "../terminal/keys"
3
+ require_relative "../terminal/ansi"
4
+ require_relative "../terminal/sequences"
5
+ require_relative "../terminal/locale_text"
6
+ require_relative "native_prompt_format"
7
+
8
+ module Kward
9
+ module NativeShell
10
+ # Raw terminal ownership is scoped to reading one standalone edit line.
11
+ # Byte reads never consume a following command's stdin.
12
+ class LineTerminal
13
+ GET_ATTRIBUTES = Fiddle::Function.new(Fiddle::Handle::DEFAULT["tcgetattr"], [Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT)
14
+
15
+ MAX_ESCAPE_BYTES = 32
16
+ MAX_PASTE_BYTES = 1_048_576
17
+ META_KEYS = (TerminalKeys::ALT_B + TerminalKeys::ALT_D + TerminalKeys::ALT_F +
18
+ TerminalKeys::ALT_BACKSPACE + TerminalKeys::ALT_LAST_WORD + TerminalKeys::ALT_Y).freeze
19
+
20
+ def initialize(runtime, editor, bracketed_paste: false)
21
+ @runtime = runtime
22
+ @editor = editor
23
+ @bracketed_paste = bracketed_paste
24
+ end
25
+
26
+ def read(source, prompt:, input:, output:, error:, draft: nil)
27
+ @source, @prompt, @error = source, prompt, error
28
+ @streams = { input: input, output: output, error: error }
29
+ @left = @frame_rows = @cursor_row = @draft_top = 0
30
+ @active_line = nil
31
+ @completion_byte = nil
32
+ controls = control_characters(source)
33
+ callbacks = { get: method(:character), changed: method(:redraw), alert: method(:alert) }
34
+ if @bracketed_paste
35
+ callbacks.merge!(get: method(:key), paste: method(:read_paste), clear: method(:clear_screen),
36
+ completion_cancel: -> { cancel_completion?(controls.fetch(:interrupt)) },
37
+ suggestions: ANSI.enabled?(error, env: @runtime.variables) && @runtime.variables["KWSH_AUTOSUGGEST"] != "0")
38
+ end
39
+ result = source.raw(intr: false) do
40
+ begin
41
+ write(TerminalSequences::BRACKETED_PASTE_ENABLE) if @bracketed_paste
42
+ @editor.read(**callbacks, **controls, draft: draft)
43
+ ensure
44
+ if @bracketed_paste
45
+ finish_frame
46
+ write(TerminalSequences::BRACKETED_PASTE_RESTORE)
47
+ end
48
+ end
49
+ end
50
+ error.puts
51
+ result
52
+ ensure
53
+ @source = @error = @streams = @prompt = @prompt_cells = nil
54
+ end
55
+
56
+ private
57
+
58
+ def control_characters(source)
59
+ attributes = "\0" * 256
60
+ raise SystemCallError.new("tcgetattr", Fiddle.last_error) if GET_ATTRIBUTES.call(source.fileno, attributes) < 0
61
+ offset, erase, kill, eof, interrupt = Locale::DARWIN ? [32, 3, 5, 0, 8] : [17, 2, 3, 4, 0]
62
+ { erase: attributes.byteslice(offset + erase, 1), kill: attributes.byteslice(offset + kill, 1), eof: attributes.byteslice(offset + eof, 1), interrupt: attributes.byteslice(offset + interrupt, 1) }
63
+ end
64
+
65
+ def character(timeout: nil)
66
+ text = +"".b
67
+ while (byte = read_byte(timeout: timeout))
68
+ text << byte
69
+ value = text.dup.force_encoding(@editor.encoding)
70
+ return value if value.valid_encoding?
71
+ raise ExecutionError, "invalid terminal character" if text.bytesize >= 8
72
+ end
73
+ nil
74
+ end
75
+
76
+ # Decode CSI/SS3 and Meta keys only for the non-modal editor. Vi receives
77
+ # a bare Escape immediately. Never look past the final byte of a key.
78
+ def key
79
+ first = character
80
+ return first unless first == TerminalKeys::ESCAPE
81
+
82
+ prefix = escape_character
83
+ return first unless prefix
84
+
85
+ sequence = first + prefix
86
+ return sequence if META_KEYS.include?(sequence)
87
+ return prefix unless prefix == "[" || prefix == "O"
88
+
89
+ while sequence.bytesize < MAX_ESCAPE_BYTES && (byte = escape_character)
90
+ # Preserve Enter and control characters even after a truncated key.
91
+ return byte if byte.ord < 32 || byte.ord == 127
92
+ sequence << byte
93
+ return sequence if prefix == "O" || sequence.match?(TerminalKeys::CSI_SEQUENCE_PATTERN)
94
+ break unless sequence.match?(TerminalKeys::CSI_PREFIX_PATTERN)
95
+ end
96
+ first
97
+ end
98
+
99
+ def escape_character
100
+ character(timeout: TerminalKeys::HANDOFF_ESCAPE_DELAY)
101
+ end
102
+
103
+ def read_paste
104
+ ending = TerminalSequences::BRACKETED_PASTE_END.b
105
+ text = +"".b
106
+ oversized = false
107
+ while (byte = read_byte)
108
+ text << byte
109
+ if text.end_with?(ending)
110
+ text = text.byteslice(0, text.bytesize - ending.bytesize).force_encoding(@editor.encoding)
111
+ return text.gsub(/\r\n?/, "\n") unless oversized || !text.valid_encoding? || text.bytesize > MAX_PASTE_BYTES
112
+ alert
113
+ return ""
114
+ end
115
+ # Keep scanning for the terminator even when rejecting the payload.
116
+ if text.bytesize > MAX_PASTE_BYTES + ending.bytesize || (oversized && text.bytesize > ending.bytesize)
117
+ oversized = true
118
+ text = text.byteslice(-ending.bytesize, ending.bytesize)
119
+ end
120
+ end
121
+ nil
122
+ end
123
+
124
+ def cancel_completion?(interrupt)
125
+ return true if @completion_byte
126
+ return false unless IO.select([@source], nil, nil, 0)
127
+
128
+ byte = @source.readpartial(1)
129
+ @completion_byte = byte unless byte == interrupt
130
+ true
131
+ rescue EOFError
132
+ true
133
+ end
134
+
135
+ def read_byte(timeout: nil)
136
+ if @completion_byte
137
+ byte, @completion_byte = @completion_byte, nil
138
+ return byte
139
+ end
140
+ loop do
141
+ return @source.readpartial(1) if IO.select([@source], nil, nil, timeout || 0.1)
142
+ return if timeout
143
+
144
+ @runtime.poll_signals(**@streams)
145
+ return if @runtime.exited
146
+ end
147
+ rescue EOFError
148
+ nil
149
+ end
150
+
151
+ def clear_screen
152
+ @frame_rows = @cursor_row = 0
153
+ write(TerminalSequences::CLEAR_VISIBLE_SCREEN)
154
+ end
155
+
156
+ def alert
157
+ write(TerminalSequences::ALERT)
158
+ end
159
+
160
+ def write(text)
161
+ @error.write(text)
162
+ @error.flush
163
+ end
164
+
165
+ def redraw(text, position, menu: nil, suggestion: nil)
166
+ unless position
167
+ @error.write("\r\n")
168
+ text.lines(chomp: true).each { |line| @error.write(TerminalText.locale_cells(line).map(&:first).join + "\r\n") }
169
+ @error.flush
170
+ return
171
+ end
172
+ height, columns = @source.winsize
173
+ height = 24 unless height.positive?
174
+ columns = 80 if columns < 4
175
+ return redraw_single_line(text, position, columns) unless @bracketed_paste
176
+
177
+ menu_lines = menu_rows(menu, columns, [height - 1, 6].min)
178
+ rows, cursor, column = draft_rows(text, position, columns, height - menu_lines.length, suggestion: suggestion)
179
+ render_frame(rows, menu_lines, cursor, column, height)
180
+ end
181
+
182
+ def redraw_single_line(text, position, columns)
183
+ row, column = format_row(text, position, columns, prompt: true)
184
+ write("\r" + row + TerminalSequences::ERASE_LINE_END + TerminalSequences.move_to_column(column))
185
+ end
186
+
187
+ def draft_rows(text, position, columns, limit, suggestion:)
188
+ before = text[0...position]
189
+ index = before.count("\n")
190
+ offset = position - (before.rindex("\n") || -1) - 1
191
+ lines = text.split("\n", -1)
192
+ lines = [""] if lines.empty?
193
+ first_visible = [index - limit + 1, 0].max
194
+ last_visible = [index, [lines.length - limit, 0].max].min
195
+ @draft_top = @draft_top.clamp(first_visible, last_visible)
196
+ @left = 0 if @active_line != index
197
+ @active_line = index
198
+ column = nil
199
+ rows = lines[@draft_top, limit].map.with_index(@draft_top) do |line, number|
200
+ row, cursor_column = format_row(line, number == index ? offset : nil, columns, prompt: number.zero?, suggestion: suggestion)
201
+ column = cursor_column if number == index
202
+ row
203
+ end
204
+ [rows, index - @draft_top, column]
205
+ end
206
+
207
+ def format_row(text, position, columns, prompt:, suggestion: nil)
208
+ prefix = prompt ? fit(prompt_cells_for_redraw, columns / 2) : []
209
+ prompt_text = prompt && @prompt.is_a?(PromptFormat) ? @prompt.render(prefix) : prefix.map(&:first).join
210
+ width = prefix.sum(&:last)
211
+ available = [columns - width - 1, 1].max
212
+ cells = TerminalText.locale_cells(text)
213
+ left = 0
214
+ column = nil
215
+ if position
216
+ left = [@left, position].min
217
+ consumed = cells[left...position].sum(&:last)
218
+ while left < position && consumed >= available
219
+ consumed -= cells[left].last
220
+ left += 1
221
+ end
222
+ @left = left
223
+ column = width + consumed + 1
224
+ end
225
+ visible = fit(cells[left..], available)
226
+ row = prompt_text + visible.map(&:first).join
227
+ if suggestion
228
+ tail = fit(TerminalText.locale_cells(suggestion), available - visible.sum(&:last)).map(&:first).join
229
+ row += ANSI.colorize(tail, :dim, enabled: true) unless tail.empty?
230
+ end
231
+ [row, column]
232
+ end
233
+
234
+ def menu_rows(menu, columns, limit)
235
+ return [] unless menu && limit.positive?
236
+
237
+ candidates, selected = menu
238
+ count = [candidates.length, limit].min
239
+ start = selected.clamp(0, candidates.length - count)
240
+ candidates[start, count].map.with_index(start) do |candidate, index|
241
+ text = (index == selected ? "> " : " ") + candidate
242
+ fit(TerminalText.locale_cells(text), columns - 1).map(&:first).join
243
+ end
244
+ end
245
+
246
+ def render_frame(draft_rows, menu_lines, cursor, column, height)
247
+ rows = draft_rows + menu_lines
248
+ count = [rows.length, [@frame_rows, height].min].max
249
+ output = @cursor_row.positive? ? +TerminalSequences.move_up([@cursor_row, height - 1].min) : +""
250
+ count.times do |index|
251
+ output << (index.zero? ? "\r" : "\r\n") << rows[index].to_s << TerminalSequences::ERASE_LINE_END
252
+ end
253
+ up = count - cursor - 1
254
+ output << TerminalSequences.move_up(up) if up.positive?
255
+ output << TerminalSequences.move_to_column(column)
256
+ @frame_rows, @cursor_row, @draft_rows = rows.length, cursor, draft_rows.length
257
+ write(output)
258
+ end
259
+
260
+ def finish_frame
261
+ return if @frame_rows.zero?
262
+
263
+ output = +""
264
+ below = @draft_rows - @cursor_row - 1
265
+ output << TerminalSequences.move_down(below) if below.positive?
266
+ extra = @frame_rows - @draft_rows
267
+ extra.times { output << "\r\n" << TerminalSequences::ERASE_LINE_END }
268
+ output << TerminalSequences.move_up(extra) if extra.positive?
269
+ write(output) unless output.empty?
270
+ end
271
+
272
+ def prompt_cells_for_redraw
273
+ @prompt_cells ||= if @prompt.is_a?(PromptFormat)
274
+ @prompt.cells(@editor.encoding)
275
+ else
276
+ TerminalText.locale_cells(@prompt)
277
+ end
278
+ end
279
+
280
+ def fit(cells, limit)
281
+ used = 0
282
+ cells.take_while { |_, width| (used += width) <= limit }
283
+ end
284
+ end
285
+ end
286
+ end