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,17 @@
1
+ module Kward
2
+ # Shared shell-agent model selection and scoped per-session tools.
3
+ module ShellPromptAgent
4
+ def self.build(client:, registry:, workspace_root:, provider:, model:, reasoning_effort:, config: ConfigFiles.read_config)
5
+ configured_provider = ConfigFiles.shell_agent_provider(config)
6
+ conversation = Conversation.new(
7
+ system_message: ShellPrompt.system_message,
8
+ workspace_root: workspace_root,
9
+ provider: configured_provider || provider,
10
+ model: ConfigFiles.shell_agent_model(config) || (configured_provider ? nil : model),
11
+ reasoning_effort: ConfigFiles.shell_agent_reasoning_effort(config) || (configured_provider ? nil : reasoning_effort)
12
+ )
13
+ Agent.new(client: client, tool_registry: registry, conversation: conversation,
14
+ strict_provider: !configured_provider.nil?, warning_sink: ConfigFiles.warning_sink)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,244 @@
1
+ require_relative "native_runtime"
2
+ require_relative "native_invocation"
3
+ require_relative "native_vi_terminal"
4
+ require_relative "native_line_editor"
5
+ require_relative "kwshrc"
6
+
7
+ module Kward
8
+ module NativeShell
9
+ # Interpreter entrypoint. Optional shell-agent requests go to the launcher.
10
+ module ScriptRunner
11
+ module_function
12
+
13
+ def run(arguments, input: $stdin, output: $stdout, error: $stderr, name: nil, descriptors: {}, own_descriptors: false, hosted: false, process_owned: false, program: "kwsh", edit_lines: false, load_rc: false, shell_link: nil)
14
+ invocation = Invocation.parse(arguments)
15
+ if invocation.help
16
+ output.puts("Usage: #{program} [-i] [shell-options] [-c command [name [args...]] | -s [args...] | file [args...]]")
17
+ return 0
18
+ end
19
+ options, args, file, command, command_name = invocation.deconstruct
20
+ name ||= command_name || file || $0
21
+ interactive = invocation.interactive || !hosted && invocation.prompt?(input, error)
22
+ env = ENV.to_h
23
+ runtime = Runtime.new(arguments: args, name: name, replace_process: !hosted, env: env,
24
+ interactive: interactive || hosted, hosted: hosted, descriptors: descriptors, own_descriptors: own_descriptors, process_owned: process_owned)
25
+ runtime.send(:reset_child_state, job_group: Process.getpgrp) if hosted
26
+ runtime.with_signals do
27
+ unless options.empty?
28
+ status = runtime.run("\\set #{Shellwords.join(options)}", input: input, output: output, error: error)
29
+ return status unless status.zero?
30
+ end
31
+ if interactive
32
+ load_kwshrc(runtime, input: input, output: output, error: error) if load_rc && !hosted
33
+ load_startup(runtime, input: input, output: output, error: error, value: env.fetch("ENV", "")) unless runtime.exited
34
+ end
35
+ unless runtime.exited
36
+ if command
37
+ runtime.run(command, input: input, output: output, error: error)
38
+ elsif file
39
+ File.open(file) do |source|
40
+ if interactive
41
+ run_interactive(runtime, source, input: input, output: output, error: error, edit_lines: edit_lines && !hosted)
42
+ else
43
+ runtime.run_input(source, input: input, output: output, error: error)
44
+ end
45
+ end
46
+ elsif interactive
47
+ run_interactive(runtime, input, input: input, output: output, error: error, edit_lines: edit_lines && !hosted, shell_link: shell_link)
48
+ else
49
+ runtime.run_input(input, input: input, output: output, error: error)
50
+ end
51
+ end
52
+ runtime.send(:wait_builtin, [], { 0 => input, 1 => output, 2 => error }.merge(descriptors)) if hosted
53
+ runtime.finish(input: input, output: output, error: error)
54
+ end
55
+ rescue ArgumentError, SystemCallError => e
56
+ error.puts("kwsh: #{e.message}")
57
+ 2
58
+ ensure
59
+ runtime&.send(:close_resources)
60
+ descriptors.values.compact.uniq.each { |io| io.close unless io.closed? } if own_descriptors
61
+ end
62
+
63
+ def load_kwshrc(runtime, input:, output:, error:)
64
+ return unless matching_identity?
65
+
66
+ Kwshrc.paths.each do |path|
67
+ break if runtime.exited
68
+ next unless File.file?(path)
69
+
70
+ runtime.run("\\. #{Shellwords.escape(path)}", input: input, output: output, error: error)
71
+ end
72
+ end
73
+
74
+ def matching_identity?
75
+ Process.uid == Process.euid && Process.gid == Process.egid
76
+ end
77
+
78
+ def load_startup(runtime, input:, output:, error:, value: runtime.variables.fetch("ENV", ""))
79
+ return unless matching_identity?
80
+ path = runtime.expand_parameters(value)
81
+ return if path.empty? || !File.file?(File.expand_path(path, runtime.cwd))
82
+ runtime.run("\\. #{Shellwords.escape(path)}", input: input, output: output, error: error)
83
+ rescue ExpansionError, ExecutionError => e
84
+ error.puts("kwsh: ENV: #{e.message}")
85
+ end
86
+
87
+ def run_interactive(runtime, source_input, input:, output:, error:, edit_lines:, shell_link: nil)
88
+ source = +"".b
89
+ draft = nil
90
+ history_controls = edit_lines && source_input.tty? && error.tty?
91
+ terminals = { vi: ViTerminal.new(runtime) }
92
+ terminals[:line] = LineTerminal.new(runtime, LineEditor.new(runtime), bracketed_paste: true) if edit_lines
93
+ runtime.with_signals do
94
+ until runtime.exited
95
+ begin
96
+ line = runtime.with_prompt_input do
97
+ runtime.notify_jobs(error: error, force: source.empty?)
98
+ prompt = source.empty? ? "PS1" : "PS2"
99
+ runtime.check_mail(error) if source.empty?
100
+ text = runtime.prompt_text(prompt, error: error, formatted: edit_lines)
101
+ read_prompt_line(runtime, source_input, terminals, prompt: text, input: input, output: output, error: error, draft: draft)
102
+ end
103
+ draft = nil
104
+ edited = false
105
+ if line.is_a?(ViEditor::Result)
106
+ if line.external
107
+ edited = true
108
+ line = runtime.vi_edit(line.text, input: input, output: output, error: error)
109
+ unless line
110
+ source.clear
111
+ next
112
+ end
113
+ else
114
+ line = line.text
115
+ end
116
+ end
117
+ unless line
118
+ if source_input.tty? && runtime.option_enabled?("ignoreeof") && !runtime.exited
119
+ error.puts("kwsh: use exit to leave the shell")
120
+ next
121
+ end
122
+ runtime.run(source, input: input, output: output, error: error) unless source.empty? || runtime.exited
123
+ break
124
+ end
125
+ if history_controls && source.empty? && handle_history_control(line, runtime.history, shell_link, output)
126
+ next
127
+ end
128
+ if shell_link && source.empty? && line.start_with?("?")
129
+ if runtime.history.paused?
130
+ error.puts("Shell agent unavailable while history is paused. Use history resume first.")
131
+ next
132
+ end
133
+ instruction = line.delete_prefix("?").strip
134
+ if instruction.empty?
135
+ error.puts("Shell prompt instruction required after ?")
136
+ else
137
+ draft = shell_link.ask(instruction, runtime, input: input, output: output, error: error) do
138
+ prompt = runtime.prompt_text("PS1", error: error, formatted: edit_lines)
139
+ render_plain_prompt(runtime, prompt, literal: true)
140
+ end
141
+ end
142
+ next
143
+ end
144
+ source << line
145
+ text = source.dup.force_encoding(Encoding::UTF_8)
146
+ text.force_encoding(Encoding::BINARY) unless text.valid_encoding?
147
+ capture = shell_link && !runtime.history.paused? && !text.strip.empty?
148
+ begin
149
+ Parser.parse(text, aliases: runtime.aliases, eof: edited)
150
+ rescue IncompleteInput
151
+ next
152
+ rescue SyntaxError
153
+ # Runtime owns the diagnostic, status, and interactive recovery.
154
+ end
155
+ runtime.with_history_entry(text) do
156
+ shell_link.begin_command(text, input: input) if capture
157
+ runtime.run(text, input: input, output: output, error: error)
158
+ shell_link.finish_command(runtime.status) if capture
159
+ end
160
+ source.clear
161
+ rescue Interrupt
162
+ runtime.interrupt_input
163
+ source.clear
164
+ error.puts
165
+ end
166
+ end
167
+ end
168
+ end
169
+
170
+ def handle_history_control(line, history, shell_link, output)
171
+ case line.strip
172
+ when "history pause"
173
+ shell_link&.clear_context
174
+ history.paused = true
175
+ when "history resume"
176
+ history.paused = false
177
+ when "history status"
178
+ output.puts(history.paused? ? "Shell history is paused." : "Shell history is recording.")
179
+ else
180
+ return false
181
+ end
182
+ true
183
+ end
184
+
185
+ def read_prompt_line(runtime, source, terminals, prompt:, input:, output:, error:, draft: nil)
186
+ if source.tty? && error.tty? && runtime.variables["TERM"] != "dumb"
187
+ style = runtime.option_enabled?("vi") ? :vi : :line
188
+ if (terminal = terminals[style])
189
+ begin
190
+ return terminal.read(source, prompt: prompt, input: input, output: output, error: error, draft: draft)
191
+ rescue ExecutionError, SystemCallError, IOError => e
192
+ terminals.delete(style)
193
+ error.puts("kwsh: line editing disabled: #{e.message}")
194
+ end
195
+ end
196
+ end
197
+ error.puts("Prepared shell command:\n#{draft}") if draft
198
+ error.write(render_plain_prompt(runtime, prompt))
199
+ error.flush
200
+ read_line(source, runtime, input: input, output: output, error: error)
201
+ end
202
+
203
+ def render_plain_prompt(runtime, prompt, literal: false)
204
+ return prompt unless literal || prompt.is_a?(PromptFormat)
205
+
206
+ render = ->(locale) do
207
+ if prompt.is_a?(PromptFormat)
208
+ prompt.render(prompt.cells(locale.encoding))
209
+ else
210
+ TerminalText.locale_cells(prompt).map(&:first).join
211
+ end
212
+ end
213
+ Locale.with(runtime.variables, &render)
214
+ rescue ExecutionError
215
+ Locale.with({}, &render)
216
+ end
217
+
218
+ def read_line(source, runtime, input:, output:, error:)
219
+ line = +"".b
220
+ loop do
221
+ if source.is_a?(IO) && !IO.select([source], nil, nil, 0.1)
222
+ runtime.poll_signals(input: input, output: output, error: error)
223
+ runtime.notify_jobs(error: error)
224
+ return nil if runtime.exited
225
+ next
226
+ end
227
+ byte = source.readpartial(1)
228
+ line << byte
229
+ return line if byte == "\n"
230
+ end
231
+ rescue EOFError
232
+ return line unless line.empty?
233
+ return unless runtime.option_enabled?("ignoreeof") && !source.tty? && !runtime.exited
234
+ # A FIFO may acquire another writer, or a file may grow. Keep the
235
+ # interactive option's meaning without repeatedly printing prompts.
236
+ sleep 0.1
237
+ runtime.poll_signals(input: input, output: output, error: error)
238
+ runtime.notify_jobs(error: error)
239
+ retry unless runtime.exited
240
+ nil
241
+ end
242
+ end
243
+ end
244
+ end
@@ -0,0 +1,31 @@
1
+ require_relative "../../kward"
2
+ require_relative "prompt_agent"
3
+
4
+ module Kward
5
+ # Lazy, in-memory shell conversation with no chat composer or tab startup.
6
+ class StandaloneAgent
7
+ def initialize(client: Client.new)
8
+ @client = client
9
+ end
10
+
11
+ def ask(instruction, shell, cancellation:)
12
+ @agent ||= build_agent(shell.cwd)
13
+ session = ShellPromptSession.new(shell)
14
+ registry = @agent.tool_registry.for_shell_prompt(session)
15
+ answer = @agent.ask(ShellPrompt.input(instruction, session.context), display_input: "? #{instruction}",
16
+ tool_registry: registry, cancellation: cancellation)
17
+ [answer, session.prepared_command]
18
+ end
19
+
20
+ private
21
+
22
+ def build_agent(cwd)
23
+ config = ConfigFiles.read_config
24
+ workspace = WorkspaceFactory.build(root: cwd, guardrails: ConfigFiles.workspace_guardrails_enabled?(config), config: config)
25
+ registry = ToolRegistry.new(workspace: workspace, mcp_clients: [])
26
+ ShellPromptAgent.build(client: @client, registry: registry, workspace_root: cwd, config: config,
27
+ provider: @client.current_provider, model: @client.current_model,
28
+ reasoning_effort: @client.current_reasoning_effort)
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,78 @@
1
+ require "json"
2
+ require "socket"
3
+
4
+ module Kward
5
+ module NativeShell
6
+ # Interpreter side of the private launcher channel. Terminal bytes are
7
+ # never interpreted as protocol messages.
8
+ class StandaloneLink
9
+ def initialize(descriptor)
10
+ @channel = UNIXSocket.for_fd(descriptor)
11
+ @channel.close_on_exec = true
12
+ @channel.sync = true
13
+ $stdout.sync = $stderr.sync = true
14
+ request("ready")
15
+ end
16
+
17
+ def begin_command(command, input:)
18
+ request("begin", command: utf8(command), input_pending: !!IO.select([input], nil, nil, 0))
19
+ end
20
+
21
+ def finish_command(status)
22
+ request("finish", status: status)
23
+ end
24
+
25
+ def clear_context
26
+ request("clear_context")
27
+ end
28
+
29
+ def ask(instruction, runtime, input:, output:, error:)
30
+ send_message("ask", instruction: utf8(instruction), cwd: utf8(runtime.cwd))
31
+ loop do
32
+ message = receive
33
+ case message.fetch("type")
34
+ when "run"
35
+ command = message.fetch("command")
36
+ status = runtime.run_shell_agent_command(command, timeout: message.fetch("timeout"), output: output, error: error) do
37
+ echo_command(command, prompt: yield, terminal: error)
38
+ request("running") # Wait for the launcher to drain the echo and start capture.
39
+ end
40
+ send_message("result", status: status, cwd: utf8(runtime.cwd))
41
+ when "answer"
42
+ input.iflush
43
+ answer = message.fetch("text")
44
+ output.puts(answer) unless answer.empty?
45
+ return message["draft"] unless runtime.exited
46
+ return nil
47
+ end
48
+ end
49
+ end
50
+
51
+ private
52
+
53
+ def echo_command(command, prompt:, terminal:)
54
+ display = command.gsub(/[[:cntrl:]&&[^\n\t]]/) { |character| character.dump[1...-1] }
55
+ terminal.write(prompt.b, display.b)
56
+ terminal.write("\n") unless display.end_with?("\n")
57
+ terminal.flush
58
+ end
59
+
60
+ def utf8(value)
61
+ value.to_s.dup.force_encoding(Encoding::UTF_8).scrub
62
+ end
63
+
64
+ def request(type, **data)
65
+ send_message(type, **data)
66
+ receive
67
+ end
68
+
69
+ def send_message(type, **data)
70
+ @channel.puts(JSON.generate(data.merge(type: type)))
71
+ end
72
+
73
+ def receive
74
+ JSON.parse(@channel.readline)
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,287 @@
1
+ require "io/console"
2
+ require "pty"
3
+ require "json"
4
+ require "socket"
5
+ require_relative "../terminal/ansi"
6
+ require_relative "../terminal/keys"
7
+ require_relative "../pty/adaptive_output_sink"
8
+ require_relative "../pty/transcript_normalizer"
9
+ require_relative "../cancellation"
10
+
11
+ module Kward
12
+ module NativeShell
13
+ # The inner PTY is the shell's controlling terminal; the launcher only
14
+ # relays bytes, resizes it, and retains a bounded pre-input snapshot.
15
+ class StandaloneTerminal
16
+ CHANNEL_FD = 30
17
+ CAPTURE_BYTES = 32_000
18
+ CHUNK_BYTES = 16_384
19
+ POLL_SECONDS = 0.05
20
+
21
+ def run(ruby_arguments, descriptors)
22
+ @lock = Mutex.new
23
+ @pending_input = +"".b
24
+ @null = File.open(File::NULL, "w")
25
+ @channel, child = UNIXSocket.pair
26
+ @channel.sync = true
27
+ @reader, @writer, @pid = PTY.spawn(terminal_defaults, *ruby_arguments, descriptors.merge(CHANNEL_FD => child))
28
+ child.close
29
+ @writer.sync = true
30
+ @reader.console_mode = $stdin.console_mode
31
+ resize
32
+ handlers = %w[HUP TERM INT].to_h do |signal|
33
+ [signal, Signal.trap(signal) { @signal = signal }]
34
+ end
35
+ $stdin.raw(intr: false) do
36
+ server = Thread.new { serve }
37
+ server.report_on_exception = false
38
+ begin
39
+ relay
40
+ ensure
41
+ @channel.shutdown rescue nil
42
+ server.kill
43
+ server.join
44
+ end
45
+ end
46
+ @reader.close
47
+ @writer.close
48
+ reap_child
49
+ @status&.exitstatus || (@status&.termsig && 128 + @status.termsig) || 1
50
+ ensure
51
+ handlers&.each { |signal, handler| Signal.trap(signal, handler) }
52
+ [@reader, @writer, @channel, child, @null].compact.each { |io| io.close unless io.closed? }
53
+ reap_child
54
+ end
55
+
56
+ private
57
+
58
+ def terminal_defaults
59
+ defaults = color_defaults
60
+ # Git's default LESS=FRX disables alternate-screen restoration (-X).
61
+ defaults["LESS"] = "FR" unless ENV.key?("LESS") || ENV["TERM"] == "dumb"
62
+ defaults
63
+ end
64
+
65
+ def color_defaults
66
+ return {} if ENV["TERM"] == "dumb" || !ANSI.enabled?
67
+
68
+ defaults = {}
69
+ defaults["CLICOLOR"] = "1" unless ENV.key?("CLICOLOR")
70
+ defaults["COLORTERM"] = "truecolor" unless ENV.key?("COLORTERM")
71
+ defaults["TERM"] = "xterm-256color" if ENV["TERM"].to_s.empty?
72
+ defaults
73
+ end
74
+
75
+ def relay
76
+ loop do
77
+ resize
78
+ if @signal
79
+ Process.kill(@signal, @pid) rescue nil
80
+ break if @signal == "HUP"
81
+ @signal = nil
82
+ end
83
+ readers = [@reader]
84
+ readers << $stdin if @pending_input.bytesize < CHUNK_BYTES
85
+ writers = [@writer] unless @pending_input.empty?
86
+ ready = IO.select(readers, writers, nil, POLL_SECONDS)
87
+ @lock.synchronize { drain_output(1) } if ready&.first&.include?(@reader)
88
+ forward_input if ready&.first&.include?($stdin)
89
+ @lock.synchronize { flush_input } if ready&.[](1)&.include?(@writer)
90
+ _, @status = Process.waitpid2(@pid, Process::WNOHANG)
91
+ break if @status
92
+ end
93
+ rescue EOFError, Errno::EIO, Errno::EPIPE
94
+ # Closing the PTY or its real terminal ends the relay.
95
+ ensure
96
+ @lock.synchronize { drain_output } rescue nil
97
+ end
98
+
99
+ def reap_child
100
+ return unless @pid && !@status
101
+
102
+ # EOF from a fast exec can precede its wait status. Give it a chance
103
+ # to exit normally before falling back to cleanup after terminal loss.
104
+ 10.times do
105
+ _, @status = Process.waitpid2(@pid, Process::WNOHANG)
106
+ return if @status
107
+ sleep 0.01
108
+ end
109
+ Process.kill("KILL", @pid)
110
+ _, @status = Process.waitpid2(@pid)
111
+ rescue Errno::ESRCH, Errno::ECHILD
112
+ nil
113
+ end
114
+
115
+ def resize
116
+ size = $stdin.winsize
117
+ return if size == @size || size.any?(&:zero?)
118
+
119
+ @reader.winsize = size
120
+ @size = size
121
+ rescue Errno::EIO
122
+ nil
123
+ end
124
+
125
+ def forward_input
126
+ bytes = $stdin.read_nonblock(CHUNK_BYTES, exception: false)
127
+ raise EOFError unless bytes
128
+ return if bytes == :wait_readable
129
+
130
+ cancellation, running = @lock.synchronize do
131
+ if @cancellation
132
+ [@cancellation, @agent_running]
133
+ else
134
+ drain_output
135
+ @capture&.input_forwarded
136
+ @pending_input << bytes
137
+ [nil, nil]
138
+ end
139
+ end
140
+ return unless cancellation && bytes.include?(TerminalKeys::CTRL_C)
141
+
142
+ cancellation.cancel!
143
+ Process.kill("INT", @pid) if running
144
+ end
145
+
146
+ def flush_input
147
+ return if @pending_input.empty?
148
+
149
+ # A full slave input queue must not block relaying command output.
150
+ length = @writer.write_nonblock(@pending_input, exception: false)
151
+ @pending_input = @pending_input.byteslice(length..) if length.is_a?(Integer)
152
+ end
153
+
154
+ def drain_output(limit = 64)
155
+ limit.times do
156
+ chunk = @reader.read_nonblock(CHUNK_BYTES, exception: false)
157
+ break unless chunk.is_a?(String)
158
+
159
+ write_terminal(chunk)
160
+ @capture&.write(chunk)
161
+ end
162
+ rescue Errno::EIO
163
+ nil
164
+ end
165
+
166
+ def write_terminal(bytes)
167
+ $stdout.write(bytes)
168
+ $stdout.flush
169
+ @at_line_start = bytes.end_with?("\n")
170
+ end
171
+
172
+ def start_capture
173
+ @capture = AdaptivePtyOutputSink.new(output: @null, on_exclusive: -> {}, max_capture_bytes: CAPTURE_BYTES)
174
+ end
175
+
176
+ def stop_capture
177
+ drain_output
178
+ sink, @capture = @capture, nil
179
+ sink.finish
180
+ return "" unless sink.transcript_safe? && !sink.preserve_terminal_view?
181
+
182
+ raw = ANSI.normalize_transcript_encoding(sink.captured_output).gsub("\r\n", "\n")
183
+ PtyTranscriptNormalizer.normalize(raw, columns: @size&.last || 80, max_bytes: CAPTURE_BYTES).to_s
184
+ end
185
+
186
+ def serve
187
+ while (line = @channel.gets)
188
+ message = JSON.parse(line)
189
+ case message.fetch("type")
190
+ when "ready"
191
+ respond("ok")
192
+ when "begin"
193
+ @lock.synchronize do
194
+ drain_output
195
+ @last_command = message.fetch("command")
196
+ start_capture
197
+ @capture.input_forwarded if message["input_pending"] || !@pending_input.empty?
198
+ end
199
+ respond("ok")
200
+ when "finish"
201
+ @lock.synchronize do
202
+ @last_output = stop_capture
203
+ @status_of_command = message.fetch("status")
204
+ end
205
+ respond("ok")
206
+ when "clear_context"
207
+ @lock.synchronize { @capture = @last_command = @last_output = @status_of_command = nil }
208
+ respond("ok")
209
+ when "ask" then answer(message)
210
+ end
211
+ end
212
+ rescue EOFError, Errno::EPIPE, IOError
213
+ nil
214
+ ensure
215
+ @channel.shutdown rescue nil
216
+ end
217
+
218
+ def answer(message)
219
+ @cwd = message.fetch("cwd")
220
+ @lock.synchronize do
221
+ @pending_input = +"".b
222
+ @cancellation = Cancellation.new
223
+ end
224
+ require_relative "standalone_agent"
225
+ @agent ||= StandaloneAgent.new
226
+ text, draft = @agent.ask(message.fetch("instruction"), self, cancellation: @cancellation)
227
+ @cancellation.raise_if_cancelled!
228
+ finish_answer(ANSI.sanitize_transcript(text), draft: draft)
229
+ rescue Cancellation::CancelledError
230
+ finish_answer("Canceled.")
231
+ rescue LoadError, StandardError => e
232
+ finish_answer(ANSI.sanitize_transcript("Shell agent: #{e.message}"))
233
+ end
234
+
235
+ def finish_answer(text, draft: nil)
236
+ @lock.synchronize do
237
+ @cancellation = nil
238
+ respond("answer", text: text, draft: draft)
239
+ end
240
+ end
241
+
242
+ def respond(type, **data)
243
+ @channel.puts(JSON.generate(data.merge(type: type)))
244
+ end
245
+
246
+ public
247
+
248
+ attr_reader :cwd
249
+
250
+ def context_snapshot
251
+ { cwd: @cwd, last_command: @last_command, last_output: @last_output, exit_status: @status_of_command }
252
+ end
253
+
254
+ def timeout_seconds
255
+ Kwsh::DEFAULT_TIMEOUT_SECONDS
256
+ end
257
+
258
+ def run_for_agent(command, timeout_seconds: nil, cancellation: nil)
259
+ cancellation&.raise_if_cancelled!
260
+ respond("run", command: command, timeout: timeout_seconds || self.timeout_seconds)
261
+ JSON.parse(@channel.readline).fetch("type") == "running" or raise IOError, "Shell agent command did not start"
262
+ @lock.synchronize do
263
+ drain_output
264
+ start_capture
265
+ @agent_running = true
266
+ respond("ok")
267
+ end
268
+ Process.kill("INT", @pid) if cancellation&.cancelled?
269
+ result = JSON.parse(@channel.readline)
270
+ @cwd = result.fetch("cwd")
271
+ output = @lock.synchronize do
272
+ captured = stop_capture
273
+ write_terminal("\r\n") unless @at_line_start
274
+ captured
275
+ end
276
+ @last_command, @last_output, @status_of_command = command, output, result.fetch("status")
277
+ cancellation&.raise_if_cancelled!
278
+ Kwsh::Result.new(output: output, exit_status: @status_of_command)
279
+ ensure
280
+ @lock.synchronize do
281
+ @agent_running = false
282
+ @capture = nil
283
+ end
284
+ end
285
+ end
286
+ end
287
+ end