kward 0.84.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 (245) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +164 -0
  3. data/CONTRIBUTING.md +1 -1
  4. data/Gemfile.lock +6 -2
  5. data/README.md +5 -5
  6. data/Rakefile +3 -0
  7. data/doc/agent-tools.md +24 -1
  8. data/doc/api.md +20 -2
  9. data/doc/composer.md +5 -4
  10. data/doc/configuration.md +86 -14
  11. data/doc/extensibility.md +4 -1
  12. data/doc/getting-started.md +3 -3
  13. data/doc/git.md +4 -2
  14. data/doc/memory.md +1 -1
  15. data/doc/pan.md +6 -0
  16. data/doc/permissions.md +4 -4
  17. data/doc/plugins.md +504 -20
  18. data/doc/providers.md +10 -4
  19. data/doc/rpc.md +279 -23
  20. data/doc/sandboxing.md +11 -5
  21. data/doc/security.md +7 -1
  22. data/doc/session-management.md +41 -5
  23. data/doc/shell.md +643 -27
  24. data/doc/tabs.md +8 -3
  25. data/doc/transports.md +15 -0
  26. data/doc/troubleshooting.md +1 -1
  27. data/doc/usage.md +25 -12
  28. data/doc/workspace-tools.md +9 -0
  29. data/examples/plugins/openrouter_proxy/README.md +103 -0
  30. data/examples/plugins/openrouter_proxy/fake_embeddings.rb +85 -0
  31. data/examples/plugins/openrouter_proxy/plugin.rb +7 -0
  32. data/examples/plugins/openrouter_proxy/protocol.rb +202 -0
  33. data/examples/plugins/openrouter_proxy/server.rb +186 -0
  34. data/examples/plugins/space_invaders.rb +1 -2
  35. data/examples/plugins/stardate_footer.rb +2 -2
  36. data/examples/plugins/telegram/plugin.rb +1 -1
  37. data/exe/kward +2 -2
  38. data/exe/kwsh +7 -0
  39. data/kward.gemspec +3 -1
  40. data/lib/kward/agent.rb +66 -19
  41. data/lib/kward/cli/commands.rb +41 -11
  42. data/lib/kward/cli/compaction.rb +9 -3
  43. data/lib/kward/cli/interactive_turn.rb +10 -0
  44. data/lib/kward/cli/plugins.rb +85 -12
  45. data/lib/kward/cli/prompt_interface.rb +29 -6
  46. data/lib/kward/cli/rendering.rb +24 -28
  47. data/lib/kward/cli/runtime_helpers.rb +168 -56
  48. data/lib/kward/cli/sessions.rb +9 -5
  49. data/lib/kward/cli/settings/menus.rb +745 -0
  50. data/lib/kward/cli/settings/model.rb +316 -0
  51. data/lib/kward/cli/settings.rb +6 -1055
  52. data/lib/kward/cli/slash_commands.rb +45 -4
  53. data/lib/kward/cli/tabs.rb +257 -44
  54. data/lib/kward/cli/tool_summaries.rb +2 -0
  55. data/lib/kward/{cli_transcript_formatter.rb → cli/transcript_formatter.rb} +6 -13
  56. data/lib/kward/cli/worktrees.rb +66 -2
  57. data/lib/kward/cli.rb +82 -31
  58. data/lib/kward/compactor.rb +18 -7
  59. data/lib/kward/config/core.rb +400 -0
  60. data/lib/kward/config/extensions.rb +99 -0
  61. data/lib/kward/config/paths.rb +11 -0
  62. data/lib/kward/config/prompts.rb +313 -0
  63. data/lib/kward/config/settings.rb +257 -0
  64. data/lib/kward/config_files.rb +14 -1008
  65. data/lib/kward/conversation.rb +41 -2
  66. data/lib/kward/entrypoint.rb +14 -0
  67. data/lib/kward/events.rb +2 -0
  68. data/lib/kward/generated_images.rb +237 -0
  69. data/lib/kward/image_attachments.rb +1 -1
  70. data/lib/kward/model/catalog.rb +6 -3
  71. data/lib/kward/model/client.rb +107 -38
  72. data/lib/kward/model/codex_images.rb +83 -0
  73. data/lib/kward/model/copilot_models.rb +10 -6
  74. data/lib/kward/model/model_info.rb +42 -7
  75. data/lib/kward/{openrouter_model_cache.rb → model/openrouter_model_cache.rb} +7 -5
  76. data/lib/kward/model/payloads.rb +18 -8
  77. data/lib/kward/model/sources.rb +3 -1
  78. data/lib/kward/model/stream_parser.rb +4 -7
  79. data/lib/kward/model/typesafe_client.rb +78 -0
  80. data/lib/kward/pan/index.html.erb +8 -1
  81. data/lib/kward/pan/server.rb +23 -8
  82. data/lib/kward/permissions/policy.rb +6 -2
  83. data/lib/kward/plugin_registry.rb +2 -659
  84. data/lib/kward/plugins/actions.rb +453 -0
  85. data/lib/kward/plugins/chat_contract.rb +121 -0
  86. data/lib/kward/{plugin_chat_runtime.rb → plugins/chat_runtime.rb} +62 -18
  87. data/lib/kward/plugins/codex_responses.rb +73 -0
  88. data/lib/kward/plugins/host.rb +248 -0
  89. data/lib/kward/plugins/http_server.rb +83 -0
  90. data/lib/kward/plugins/registry.rb +1229 -0
  91. data/lib/kward/plugins/resources.rb +206 -0
  92. data/lib/kward/plugins/turn_request.rb +36 -0
  93. data/lib/kward/plugins/ui.rb +219 -0
  94. data/lib/kward/prompt_interface/composer_controller.rb +0 -1
  95. data/lib/kward/prompt_interface/composer_renderer.rb +160 -73
  96. data/lib/kward/prompt_interface/composer_state.rb +1 -1
  97. data/lib/kward/prompt_interface/editor/controller.rb +2 -2
  98. data/lib/kward/prompt_interface/editor/renderer.rb +10 -7
  99. data/lib/kward/prompt_interface/editor/runner.rb +1 -1
  100. data/lib/kward/prompt_interface/editor/state.rb +1 -1
  101. data/lib/kward/prompt_interface/file_overlay.rb +3 -3
  102. data/lib/kward/prompt_interface/generated_image_preview.rb +162 -0
  103. data/lib/kward/prompt_interface/git_prompt.rb +18 -11
  104. data/lib/kward/prompt_interface/interactive/renderer.rb +1 -1
  105. data/lib/kward/prompt_interface/interactive/state.rb +18 -20
  106. data/lib/kward/prompt_interface/key_handler.rb +108 -25
  107. data/lib/kward/prompt_interface/layout.rb +11 -1
  108. data/lib/kward/prompt_interface/overlay_renderer.rb +26 -9
  109. data/lib/kward/prompt_interface/plugin_ui_requests.rb +82 -0
  110. data/lib/kward/prompt_interface/project_browser.rb +27 -54
  111. data/lib/kward/prompt_interface/prompt_renderer.rb +27 -35
  112. data/lib/kward/prompt_interface/question_prompt.rb +19 -28
  113. data/lib/kward/prompt_interface/runtime_state.rb +37 -10
  114. data/lib/kward/prompt_interface/screen.rb +30 -20
  115. data/lib/kward/prompt_interface/selection_prompt.rb +8 -8
  116. data/lib/kward/prompt_interface/slash_overlay.rb +1 -1
  117. data/lib/kward/prompt_interface/transcript_renderer.rb +7 -6
  118. data/lib/kward/prompt_interface.rb +149 -30
  119. data/lib/kward/prompts/commands.rb +2 -1
  120. data/lib/kward/prompts.rb +7 -1
  121. data/lib/kward/{adaptive_pty_output_sink.rb → pty/adaptive_output_sink.rb} +39 -5
  122. data/lib/kward/{interactive_pty_runner.rb → pty/interactive_runner.rb} +22 -30
  123. data/lib/kward/{local_command_runner.rb → pty/local_command_runner.rb} +1 -1
  124. data/lib/kward/{local_pty_command_runner.rb → pty/local_pty_runner.rb} +3 -9
  125. data/lib/kward/{pty_output_sink.rb → pty/output_sink.rb} +9 -4
  126. data/lib/kward/pty/transcript_normalizer.rb +137 -0
  127. data/lib/kward/rpc/config_manager.rb +3 -0
  128. data/lib/kward/rpc/plugin_chat_manager.rb +30 -10
  129. data/lib/kward/rpc/prompt_bridge.rb +25 -0
  130. data/lib/kward/rpc/server.rb +118 -17
  131. data/lib/kward/rpc/session_manager.rb +208 -60
  132. data/lib/kward/rpc/session_tree_rows.rb +2 -2
  133. data/lib/kward/rpc/tool_metadata.rb +1 -1
  134. data/lib/kward/rpc/transcript_normalizer.rb +11 -7
  135. data/lib/kward/sandbox/command_runner.rb +1 -1
  136. data/lib/kward/{session_catalog.rb → sessions/catalog.rb} +1 -1
  137. data/lib/kward/{session_store.rb → sessions/store.rb} +39 -12
  138. data/lib/kward/{session_tree_nodes.rb → sessions/tree_nodes.rb} +3 -3
  139. data/lib/kward/{session_tree_renderer.rb → sessions/tree_renderer.rb} +4 -4
  140. data/lib/kward/{session_tree_tool_display.rb → sessions/tree_tool_display.rb} +1 -1
  141. data/lib/kward/{kwsh.rb → shell/kwsh.rb} +30 -10
  142. data/lib/kward/{kwshrc.rb → shell/kwshrc.rb} +11 -2
  143. data/lib/kward/shell/native_arithmetic.rb +255 -0
  144. data/lib/kward/shell/native_arrays.rb +102 -0
  145. data/lib/kward/shell/native_braces.rb +96 -0
  146. data/lib/kward/shell/native_builtins.rb +476 -0
  147. data/lib/kward/shell/native_completion.rb +169 -0
  148. data/lib/kward/shell/native_condition.rb +75 -0
  149. data/lib/kward/shell/native_directory.rb +116 -0
  150. data/lib/kward/shell/native_exec_state.rb +73 -0
  151. data/lib/kward/shell/native_expansion.rb +252 -0
  152. data/lib/kward/shell/native_fields.rb +62 -0
  153. data/lib/kward/shell/native_glob.rb +96 -0
  154. data/lib/kward/shell/native_history.rb +242 -0
  155. data/lib/kward/shell/native_interactive.rb +164 -0
  156. data/lib/kward/shell/native_invocation.rb +42 -0
  157. data/lib/kward/shell/native_jobs.rb +250 -0
  158. data/lib/kward/shell/native_line_editor.rb +382 -0
  159. data/lib/kward/shell/native_line_terminal.rb +286 -0
  160. data/lib/kward/shell/native_locale.rb +109 -0
  161. data/lib/kward/shell/native_locals.rb +57 -0
  162. data/lib/kward/shell/native_pattern.rb +200 -0
  163. data/lib/kward/shell/native_process.rb +279 -0
  164. data/lib/kward/shell/native_program.rb +40 -0
  165. data/lib/kward/shell/native_programmable_completion.rb +115 -0
  166. data/lib/kward/shell/native_prompt_format.rb +89 -0
  167. data/lib/kward/shell/native_runtime.rb +964 -0
  168. data/lib/kward/shell/native_substitution.rb +110 -0
  169. data/lib/kward/shell/native_syntax.rb +946 -0
  170. data/lib/kward/shell/native_traps.rb +196 -0
  171. data/lib/kward/shell/native_vi.rb +407 -0
  172. data/lib/kward/shell/native_vi_terminal.rb +19 -0
  173. data/lib/kward/shell/native_worker.rb +82 -0
  174. data/lib/kward/{persistent_shell_session.rb → shell/persistent_session.rb} +187 -193
  175. data/lib/kward/shell/prompt.rb +66 -0
  176. data/lib/kward/shell/prompt_agent.rb +17 -0
  177. data/lib/kward/{shell_prompt_session.rb → shell/prompt_session.rb} +1 -1
  178. data/lib/kward/shell/script_runner.rb +244 -0
  179. data/lib/kward/shell/standalone_agent.rb +31 -0
  180. data/lib/kward/shell/standalone_link.rb +78 -0
  181. data/lib/kward/shell/standalone_terminal.rb +287 -0
  182. data/lib/kward/skills/trust_store.rb +1 -1
  183. data/lib/kward/tabs/driver.rb +194 -0
  184. data/lib/kward/{tab_store.rb → tabs/store.rb} +2 -2
  185. data/lib/kward/{clipboard.rb → terminal/clipboard.rb} +1 -1
  186. data/lib/kward/{terminal_image_support.rb → terminal/image_support.rb} +1 -1
  187. data/lib/kward/{terminal_keys.rb → terminal/keys.rb} +22 -1
  188. data/lib/kward/terminal/locale_text.rb +29 -0
  189. data/lib/kward/{terminal_sequences.rb → terminal/sequences.rb} +45 -4
  190. data/lib/kward/tools/base.rb +18 -0
  191. data/lib/kward/tools/context_for_task.rb +15 -6
  192. data/lib/kward/tools/datetime.rb +85 -0
  193. data/lib/kward/tools/edit_file.rb +9 -6
  194. data/lib/kward/tools/generate_image.rb +36 -0
  195. data/lib/kward/tools/git_commit.rb +13 -7
  196. data/lib/kward/tools/list_directory.rb +4 -4
  197. data/lib/kward/tools/plugin_tool.rb +41 -0
  198. data/lib/kward/tools/prepare_shell_command.rb +1 -1
  199. data/lib/kward/tools/read_file.rb +7 -6
  200. data/lib/kward/tools/registry.rb +130 -21
  201. data/lib/kward/tools/run_shell_command.rb +10 -8
  202. data/lib/kward/tools/search/code.rb +1 -1
  203. data/lib/kward/tools/summarize_file_structure.rb +5 -5
  204. data/lib/kward/tools/tool_call.rb +4 -1
  205. data/lib/kward/tools/typesafe_evaluate.rb +81 -0
  206. data/lib/kward/tools/workspace_targets.rb +58 -0
  207. data/lib/kward/tools/write_file.rb +9 -6
  208. data/lib/kward/{export_path.rb → transcripts/export_path.rb} +1 -1
  209. data/lib/kward/{markdown_transcript.rb → transcripts/markdown_transcript.rb} +10 -2
  210. data/lib/kward/transcripts/turn_summary_formatter.rb +93 -0
  211. data/lib/kward/transport/contracts.rb +200 -0
  212. data/lib/kward/transport/gateway.rb +81 -36
  213. data/lib/kward/transport/plugin_chat_gateway.rb +3 -2
  214. data/lib/kward/transport.rb +1 -200
  215. data/lib/kward/turn_summary.rb +68 -0
  216. data/lib/kward/version.rb +1 -1
  217. data/lib/kward/{workspace_factory.rb → workspace/factory.rb} +2 -2
  218. data/lib/kward/{git_worktree_manager.rb → workspace/git_worktree_manager.rb} +28 -0
  219. data/lib/kward/{workspace.rb → workspace/workspace.rb} +3 -3
  220. data/lib/main.rb +6 -3
  221. data/templates/default/fulldoc/html/css/kward.css +125 -0
  222. data/templates/default/fulldoc/html/images/kward_screen_1.png +0 -0
  223. data/templates/default/fulldoc/html/setup.rb +1 -1
  224. data/templates/default/layout/html/layout.erb +16 -4
  225. metadata +150 -48
  226. data/lib/kward/pty_transcript_normalizer.rb +0 -93
  227. data/lib/kward/shell_prompt.rb +0 -52
  228. data/lib/kward/tab_driver.rb +0 -90
  229. data/templates/default/fulldoc/html/images/kward_workflow.svg +0 -52
  230. /data/lib/kward/{editor_prompt.rb → cli/editor_prompt.rb} +0 -0
  231. /data/lib/kward/{editor_prompt_session.rb → cli/editor_prompt_session.rb} +0 -0
  232. /data/lib/kward/{diff_view_mode.rb → prompt_interface/editor/diff_view_mode.rb} +0 -0
  233. /data/lib/kward/{editor_mode.rb → prompt_interface/editor/editor_mode.rb} +0 -0
  234. /data/lib/kward/{markdown_code_block.rb → prompt_interface/editor/markdown_code_block.rb} +0 -0
  235. /data/lib/kward/{scratchpad_languages.rb → prompt_interface/editor/scratchpad_languages.rb} +0 -0
  236. /data/lib/kward/{scratchpad_runner.rb → prompt_interface/editor/scratchpad_runner.rb} +0 -0
  237. /data/lib/kward/{detached_run.rb → pty/detached_run.rb} +0 -0
  238. /data/lib/kward/{session_diff.rb → sessions/diff.rb} +0 -0
  239. /data/lib/kward/{session_naming.rb → sessions/naming.rb} +0 -0
  240. /data/lib/kward/{session_trash.rb → sessions/trash.rb} +0 -0
  241. /data/lib/kward/{ansi.rb → terminal/ansi.rb} +0 -0
  242. /data/lib/kward/{terminal_text.rb → terminal/text.rb} +0 -0
  243. /data/lib/kward/{transcript_export.rb → transcripts/transcript_export.rb} +0 -0
  244. /data/lib/kward/{project_files.rb → workspace/files.rb} +0 -0
  245. /data/lib/kward/{path_guard.rb → workspace/path_guard.rb} +0 -0
@@ -0,0 +1,964 @@
1
+ require "shellwords"
2
+ require "set"
3
+ require "tempfile"
4
+ require_relative "native_syntax"
5
+ require_relative "native_process"
6
+ require_relative "native_directory"
7
+ require_relative "native_expansion"
8
+ require_relative "native_substitution"
9
+ require_relative "native_builtins"
10
+ require_relative "native_history"
11
+ require_relative "native_interactive"
12
+ require_relative "native_arrays"
13
+ require_relative "native_locals"
14
+ require_relative "native_programmable_completion"
15
+ require_relative "native_jobs"
16
+ require_relative "native_traps"
17
+ require_relative "native_program"
18
+
19
+ module Kward
20
+ module NativeShell
21
+ class ExecutionError < StandardError; end
22
+ class InvalidSignal < ExecutionError; end
23
+
24
+ class Flow < StandardError
25
+ attr_reader :kind, :status
26
+ attr_accessor :levels
27
+
28
+ def initialize(kind, status, levels: 1)
29
+ @levels = levels
30
+ @kind = kind
31
+ @status = status
32
+ super(kind.to_s)
33
+ end
34
+ end
35
+
36
+ # Owns native shell state. External commands are always spawned with argv,
37
+ # never a command string, and executable text has no implicit sh fallback.
38
+ class Runtime
39
+ include Expansion
40
+ include Substitution
41
+ include Builtins
42
+ include HistoryCommands
43
+ include Interactive
44
+ include Condition
45
+ include Arrays
46
+ include Locals
47
+ include ProgrammableCompletion
48
+ include Jobs
49
+ include Traps
50
+
51
+ UNSUPPORTED = %w[typeset builtin].freeze
52
+ SPECIAL = %w[export readonly eval . source unset exit return break continue shift set exec trap times :].freeze
53
+ BUILTINS = (SPECIAL + %w[true false cd pwd alias unalias read getopts command shopt local declare complete compgen umask ulimit kwsh jobs fg bg wait kill hash type which fc]).freeze
54
+
55
+ attr_reader :variables, :aliases, :status, :exited
56
+
57
+ def initialize(cwd: Dir.pwd, env: ENV.to_h, aliases: {}, arguments: [], name: "kwsh", interactive: false, replace_process: false, descriptors: {}, own_descriptors: false, hosted: interactive, directory: nil, process_owned: false)
58
+ @directory = directory ? directory.dup : Directory.new(cwd)
59
+ @cwd = File.expand_path(cwd)
60
+ @cwd = initial_directory(env["PWD"]) unless hosted
61
+ @variables = env.dup
62
+ @variables["PWD"] = @cwd
63
+ @exported = Set.new(@variables.keys)
64
+ @variables["PPID"] = Process.ppid.to_s
65
+ @variables["OPTIND"] = "1"
66
+ @variables["IFS"] = Fields::DEFAULT_IFS
67
+ @variables["LINENO"] = "1"
68
+ @line_tracking = true
69
+ @aliases = aliases.dup
70
+ @arguments = arguments
71
+ @name = name
72
+ @shell_pid = Process.pid
73
+ @process_owned = process_owned
74
+ @functions = {}
75
+ @local_scopes = []
76
+ @completion_functions = {}
77
+ @command_hash = {}
78
+ @arrays = {}
79
+ @readonly = Set.new
80
+ @source_depth = 0
81
+ @eval_depth = 0
82
+ @globstar = false
83
+ @options = Set.new(interactive ? ["monitor"] : [])
84
+ @jobs = {}
85
+ @entry_ignored = Set.new(NativeProcess.ignored_signals.map { |name| Signal.list.key(Signal.list.fetch(name)) })
86
+ # Keep the shell's own job-control ignores from becoming job defaults,
87
+ # even when the launcher already ignored these signals.
88
+ @entry_ignored.subtract(%w[TSTP TTIN TTOU]) if interactive || hosted
89
+ @traps = @entry_ignored.to_h { |name| [name, ""] }
90
+ @pending_signals = []
91
+ @persistent_descriptors = descriptors.dup
92
+ @owned_descriptors = own_descriptors ? descriptors.values.compact.uniq : []
93
+ @active_streams = []
94
+ @replace_process = replace_process
95
+ @interactive = interactive
96
+ @hosted = hosted
97
+ @umask = File.umask
98
+ @status = 0
99
+ @exited = false
100
+ @loop_depth = 0
101
+ @function_depth = 0
102
+ end
103
+
104
+ def cwd
105
+ @directory.same?(@cwd) ? @cwd : @directory.physical_path
106
+ rescue SystemCallError
107
+ @cwd
108
+ end
109
+
110
+ def environment
111
+ @variables.select { |key, _| @exported.include?(key) && !@arrays.key?(key) }
112
+ end
113
+
114
+ def run(source, input: $stdin, output: $stdout, error: $stderr)
115
+ run_input(StringIO.new(source), input: input, output: output, error: error)
116
+ end
117
+
118
+ def run_input(source, input: $stdin, output: $stdout, error: $stderr)
119
+ @base_streams = { 0 => input, 1 => output, 2 => error }.merge(@persistent_descriptors)
120
+ with_signal_handlers { evaluate_program(source, @base_streams) }
121
+ rescue Flow => flow
122
+ if %i[exit abort].include?(flow.kind)
123
+ @exited = true if flow.kind == :exit
124
+ @status = flow.status
125
+ else
126
+ error&.puts("kwsh: #{flow.kind}: not in a valid context")
127
+ @status = 2
128
+ end
129
+ rescue SyntaxError, ExpansionError, ExecutionError, SystemCallError, IOError, ArgumentError => e
130
+ error&.puts("kwsh: #{e.message}")
131
+ @exited = true unless interactive_scope?
132
+ @status = 2
133
+ rescue Interrupt
134
+ @status = 130
135
+ end
136
+
137
+ # ENV and interactive prompts require parameter expansion, not evaluation
138
+ # of arbitrary command text or command substitutions from the environment.
139
+ def interrupt_input
140
+ @status = 130
141
+ end
142
+
143
+ def expand_parameters(value)
144
+ word = Lexer.new(value).heredoc_word
145
+ validate_parameter_text(word)
146
+ scalar(word)
147
+ end
148
+
149
+ def with_pager_suppressed
150
+ previous = @variables["GIT_PAGER"]
151
+ exported = @exported.include?("GIT_PAGER")
152
+ @variables["GIT_PAGER"] = "cat"
153
+ @exported.add("GIT_PAGER")
154
+ yield
155
+ ensure
156
+ previous ? @variables["GIT_PAGER"] = previous : @variables.delete("GIT_PAGER")
157
+ @exported.delete("GIT_PAGER") unless exported
158
+ end
159
+
160
+ private
161
+
162
+ def close_resources
163
+ @owned_descriptors.each { |io| io.close unless io.closed? }
164
+ @owned_descriptors.clear
165
+ ensure
166
+ close_directory
167
+ end
168
+
169
+ def close_directory
170
+ @directory.close
171
+ end
172
+
173
+ def initial_directory(inherited)
174
+ # Validate against the runtime's directory, never the host process cwd.
175
+ if inherited&.start_with?("/") && inherited.split("/").none? { |part| part == "." || part == ".." } && @directory.same?(inherited)
176
+ return inherited
177
+ end
178
+ @directory.physical_path
179
+ rescue SystemCallError
180
+ # POSIX leaves PWD unspecified when the physical path cannot be found.
181
+ @cwd
182
+ end
183
+
184
+ def validate_parameter_text(word)
185
+ word.parts.each do |part|
186
+ next if part.kind == :literal
187
+ raise ExpansionError, "only parameter expansion is supported in ENV and prompts" unless part.kind == :parameter
188
+ parameter = part.text
189
+ if parameter.is_a?(Parameter)
190
+ raise ExpansionError, "array references are not supported in ENV and prompts" unless parameter.name.is_a?(String)
191
+ validate_parameter_text(parameter.word) if parameter.word
192
+ elsif !parameter.is_a?(String)
193
+ raise ExpansionError, "array references are not supported in ENV and prompts"
194
+ end
195
+ end
196
+ end
197
+
198
+ def interactive_scope?
199
+ @interactive && !@job_child
200
+ end
201
+
202
+ def command_error(error, streams, fatal: false)
203
+ streams[2]&.puts("kwsh: #{error.message}")
204
+ raise Flow.new(interactive_scope? ? :abort : :exit, 2) if fatal
205
+ 2
206
+ end
207
+
208
+ def evaluate_program(input, streams)
209
+ result = @status
210
+ Program.each(input, aliases: @aliases, on_read: ->(byte) { streams[2]&.write(byte) if @options.include?("verbose") }) do |tree|
211
+ result = evaluate(tree, streams) unless tree.values.first.empty?
212
+ end
213
+ @status = result
214
+ end
215
+
216
+ def evaluate(node, streams, ignored: false)
217
+ @active_streams << streams
218
+ previous_ignore = @ignore_failure
219
+ previous_streams = @streams
220
+ previous_description = @command_description
221
+ @command_description = node.source if node.source
222
+ @variables["LINENO"] = node.line.to_s if @line_tracking && node.line
223
+ @ignore_failure = previous_ignore || ignored
224
+ return 0 if @options.include?("noexec") && !@interactive
225
+ @streams = streams
226
+ @status = case node.kind
227
+ when :background
228
+ start_job(node.values.first, streams, background: true)
229
+ when :sequence
230
+ result = 0
231
+ node.values.first.each { |command| result = evaluate(command, streams) }
232
+ result
233
+ when :and_or
234
+ first, rest = node.values
235
+ result = evaluate(first, streams, ignored: true)
236
+ rest.each_with_index do |(operator, command), index|
237
+ result = evaluate(command, streams, ignored: index < rest.length - 1) if operator == "&&" ? result.zero? : !result.zero?
238
+ end
239
+ result
240
+ when :local_array
241
+ local_array(*node.values)
242
+ when :declare_array
243
+ mode, name, words = node.values
244
+ declare_array([mode, name])
245
+ array_assignment(name, words)
246
+ when :array_assign
247
+ array_assignment(*node.values)
248
+ when :test
249
+ condition_value(node.values.first) ? 0 : 1
250
+ when :arithmetic
251
+ expression = node.values.first
252
+ expression.strip.empty? || arithmetic_value(expression).to_i.zero? ? 1 : 0
253
+ when :arithmetic_for
254
+ (initial, condition, update), body = node.values
255
+ arithmetic_value(initial) unless initial.strip.empty?
256
+ loop_commands do
257
+ result = 0
258
+ while condition.strip.empty? || !arithmetic_value(condition).to_i.zero?
259
+ result = loop_body(body, streams)
260
+ arithmetic_value(update) unless update.strip.empty?
261
+ end
262
+ result
263
+ end
264
+ when :subshell
265
+ subshell(node.values.first, streams)
266
+ when :pipeline
267
+ if @options.include?("monitor") && !@job_child && foreground_process?(node)
268
+ start_job(node, streams, background: false)
269
+ else
270
+ pipeline(*node.values, streams)
271
+ end
272
+ when :simple
273
+ simple(*node.values, streams)
274
+ when :external
275
+ external(node.values.first, streams)
276
+ when :script
277
+ script(node.values.first, streams)
278
+ when :redirect
279
+ command, redirects = node.values
280
+ with_redirects(redirects, streams) { |redirected| evaluate(command, redirected) }
281
+ when :if
282
+ condition, yes, no = node.values
283
+ evaluate(evaluate(condition, streams, ignored: true).zero? ? yes : no, streams)
284
+ when :case
285
+ subject, clauses = node.values
286
+ value = scalar(subject)
287
+ result = 0
288
+ falling_through = false
289
+ clauses.each do |patterns, body, fallthrough|
290
+ next unless falling_through || patterns.any? { |word| matches_pattern?(pattern(word), value) }
291
+ result = evaluate(body, streams)
292
+ break unless fallthrough
293
+ falling_through = true
294
+ end
295
+ result
296
+ when :for
297
+ name, words, body = node.values
298
+ values = words ? words.flat_map { |word| expand(word) } : @arguments.dup
299
+ loop_commands do
300
+ result = 0
301
+ values.each do |value|
302
+ assign(name, value)
303
+ result = loop_body(body, streams)
304
+ end
305
+ result
306
+ end
307
+ when :loop
308
+ kind, condition, body = node.values
309
+ loop_commands do
310
+ result = 0
311
+ while evaluate(condition, streams, ignored: true).zero? == (kind == "while")
312
+ result = loop_body(body, streams)
313
+ end
314
+ result
315
+ end
316
+ when :function
317
+ name, body = node.values
318
+ @functions[name] = body
319
+ remember_function_commands(body) if @options.include?("hashall")
320
+ 0
321
+ end
322
+ failed_command = %i[simple subshell test arithmetic redirect].include?(node.kind) ||
323
+ node.kind == :pipeline && node.values.first.length > 1
324
+ negated = node.kind == :pipeline && node.values.last
325
+ run_pending_traps(streams)
326
+ raise Flow.new(:exit, @status) if failed_command && !negated && @options.include?("errexit") && !@ignore_failure && !@status.zero?
327
+ @status
328
+ ensure
329
+ @streams = previous_streams
330
+ @command_description = previous_description
331
+ @ignore_failure = previous_ignore
332
+ @active_streams.pop
333
+ release_descriptors
334
+ end
335
+
336
+ def loop_commands
337
+ @loop_depth += 1
338
+ yield
339
+ rescue Flow => flow
340
+ raise unless flow.kind == :break
341
+ flow.levels -= 1
342
+ raise if flow.levels.positive?
343
+ 0
344
+ ensure
345
+ @loop_depth -= 1
346
+ end
347
+
348
+ def loop_body(body, streams)
349
+ evaluate(body, streams)
350
+ rescue Flow => flow
351
+ raise unless flow.kind == :continue
352
+ flow.levels -= 1
353
+ raise if flow.levels.positive?
354
+ 0
355
+ end
356
+
357
+ def pipeline(commands, negate, streams)
358
+ previous_ignore = @ignore_failure
359
+ @ignore_failure ||= negate
360
+ result = if commands.length == 1
361
+ evaluate(commands.first, streams)
362
+ else
363
+ run_pipeline(commands, streams)
364
+ end
365
+ negate ? (result.zero? ? 1 : 0) : result
366
+ ensure
367
+ @ignore_failure = previous_ignore
368
+ end
369
+
370
+ def run_pipeline(commands, streams)
371
+ streams.values.compact.uniq.each(&:flush)
372
+ pipes = Array.new(commands.length - 1) { IO.pipe }
373
+ pids = []
374
+ commands.each_with_index do |command, index|
375
+ pids << Process.fork do
376
+ reset_child_state
377
+ selected = streams.merge(
378
+ 0 => index.zero? ? streams[0] : pipes[index - 1][0],
379
+ 1 => index == commands.length - 1 ? streams[1] : pipes[index][1]
380
+ )
381
+ pipes.flatten.each { |io| io.close unless selected.value?(io) }
382
+ begin
383
+ exit_status = with_signal_handlers { evaluate(command, selected, ignored: index < commands.length - 1) }
384
+ rescue Flow => flow
385
+ exit_status = flow.status
386
+ rescue StandardError => e
387
+ selected[2]&.puts("kwsh: #{e.message}")
388
+ exit_status = 2
389
+ end
390
+ wait_builtin([], selected) if @hosted && !@jobs.empty?
391
+ @status = exit_status
392
+ finish(input: selected[0], output: selected[1], error: selected[2])
393
+ selected.values.compact.each { |io| io.flush rescue nil }
394
+ exit!(@status)
395
+ end
396
+ end
397
+ pipes.flatten.each(&:close)
398
+ statuses = []
399
+ until pids.empty?
400
+ statuses << wait(pids.first)
401
+ pids.shift
402
+ end
403
+ @options.include?("pipefail") ? statuses.reverse.find { |status| !status.zero? } || 0 : statuses.last
404
+ ensure
405
+ pipes&.flatten&.each { |io| io.close unless io.closed? }
406
+ pids&.each { |pid| terminate(pid) }
407
+ end
408
+
409
+ def simple(words, redirects, streams)
410
+ previous_substitutions = @process_substitutions
411
+ @process_substitutions = []
412
+ @substitution_status = nil
413
+ assignments = []
414
+ assigning = false
415
+ words = words.dup
416
+ assignments << words.shift.assignment while words.first&.assignment
417
+ declaration_index = 0
418
+ while words[declaration_index]&.literal == "command"
419
+ declaration_index += 1
420
+ declaration_index += 1 while words[declaration_index]&.literal&.match?(/\A(?:-p+|--)\z/)
421
+ end
422
+ declaration_utility = %w[export readonly local].include?(words[declaration_index]&.literal)
423
+ arguments = words.each_with_index.flat_map do |word, index|
424
+ declaration = declaration_utility && index > declaration_index && word.assignment
425
+ expand(word, assignment: !!declaration)
426
+ end
427
+ persistent = SPECIAL.include?(arguments.first)
428
+ with_redirects(redirects, streams, fatal: persistent) do |redirected|
429
+ if arguments.empty?
430
+ assigning = true
431
+ trace("", redirected) if assignments.empty?
432
+ assignments.each { |key, value| assign_word(key, value, redirected) }
433
+ next @substitution_status || 0
434
+ end
435
+ raise ExecutionError, "array prefix assignments require an assignment-only command" if assignments.any? { |key, _| key.is_a?(Reference) || @arrays.key?(key) }
436
+ name = arguments.first
437
+ saved = assignments.to_h { |key, _| [key, [@variables[key], @exported.include?(key)]] }
438
+ begin
439
+ assigning = true
440
+ assignments.each do |key, value|
441
+ assign_word(key, value, redirected)
442
+ @exported.add(key) if !persistent || name == "exec"
443
+ end
444
+ assigning = false
445
+ trace(Shellwords.join(arguments), redirected)
446
+ dispatch(arguments, redirected)
447
+ rescue ExecutionError, SystemCallError, IOError, ArgumentError => e
448
+ command_error(e, redirected, fatal: assigning || persistent)
449
+ ensure
450
+ unless persistent
451
+ saved.each do |key, (value, exported)|
452
+ value ? @variables[key] = value : @variables.delete(key)
453
+ exported ? @exported.add(key) : @exported.delete(key)
454
+ end
455
+ end
456
+ end
457
+ end
458
+ rescue ExecutionError, SystemCallError, IOError, ArgumentError => e
459
+ command_error(e, streams, fatal: assigning || persistent)
460
+ ensure
461
+ resources = @process_substitutions
462
+ @process_substitutions = previous_substitutions
463
+ finish_substitutions(resources) if resources
464
+ end
465
+
466
+ def dispatch(arguments, streams, functions: true)
467
+ name, *args = arguments
468
+ if functions && @functions.key?(name) && !SPECIAL.include?(name)
469
+ return call_function(name, args, streams)
470
+ end
471
+ raise ExecutionError, "#{name}: not supported by native kwsh" if UNSUPPORTED.include?(name)
472
+
473
+ case name
474
+ when ":", "true" then 0
475
+ when "false" then 1
476
+ when "cd" then change_directory(args, streams)
477
+ when "pwd"
478
+ flags = builtin_flags(args, "LP", "pwd")
479
+ raise ExecutionError, "pwd: unexpected operand" unless args.empty?
480
+ logical = flags.last != "P" && @cwd.split("/").none? { |part| part == "." || part == ".." } && @directory.same?(@cwd)
481
+ write_line(streams, logical ? @cwd : @directory.physical_path)
482
+ 0
483
+ when "export" then export(args, streams)
484
+ when "read" then read_variables(args, streams)
485
+ when "readonly" then readonly(args, streams)
486
+ when "declare" then declare_array(args)
487
+ when "local" then local_builtin(args)
488
+ when "complete" then complete_builtin(args)
489
+ when "compgen" then compgen_builtin(args, streams)
490
+ when "umask" then umask_builtin(args, streams)
491
+ when "ulimit" then ulimit_builtin(args, streams)
492
+ when "shopt" then shopt(args, streams)
493
+ when "command" then command_builtin(args, streams)
494
+ when "type"
495
+ raise ExecutionError, "type: expected a name" if args.empty?
496
+ command_builtin(["-V", "--", *args], streams)
497
+ when "which" then which_builtin(args, streams)
498
+ when "hash" then hash_builtin(args, streams)
499
+ when "fc" then fc_builtin(args, streams)
500
+ when "times" then times_builtin(args, streams)
501
+ when "getopts" then getopts(args, streams)
502
+ when "jobs" then jobs_builtin(args, streams)
503
+ when "wait" then wait_builtin(args, streams)
504
+ when "fg" then resume_job(args, streams, foreground: true)
505
+ when "bg" then resume_job(args, streams, foreground: false)
506
+ when "kill" then kill_builtin(args, streams)
507
+ when "trap" then trap_builtin(args, streams)
508
+ when "exec" then exec_builtin(args, streams)
509
+ when ".", "source" then source_script(name, args, streams)
510
+ when "eval"
511
+ raise ExecutionError, "eval nesting exceeds 100 levels" if @eval_depth >= 100
512
+ @eval_depth += 1
513
+ begin
514
+ evaluate_program(StringIO.new(args.join(" ")), streams)
515
+ ensure
516
+ @eval_depth -= 1
517
+ end
518
+ when "unset"
519
+ flags = builtin_flags(args, "fv", "unset")
520
+ raise ExecutionError, "unset: -f and -v are mutually exclusive" if flags.uniq.length > 1
521
+ functions_only = flags.include?("f")
522
+ args.each do |key|
523
+ if !functions_only && (match = key.match(/\A([A-Za-z_][A-Za-z0-9_]*)\[(.*)\]\z/m))
524
+ name, subscript = match.captures
525
+ raise ExecutionError, "#{name}: readonly variable" if @readonly.include?(name)
526
+ array = @arrays[name]
527
+ next unless array
528
+ if %w[@ *].include?(subscript) && !array.associative
529
+ @arrays.delete(name)
530
+ else
531
+ reference = Reference.new(name: name, subscript: Word.new(parts: [Part.new(kind: :literal, text: subscript, quoted: true)]))
532
+ array.values.delete(array_index(reference, array))
533
+ end
534
+ next
535
+ end
536
+ validate_name(key)
537
+ if functions_only
538
+ @functions.delete(key)
539
+ else
540
+ raise ExecutionError, "#{key}: readonly variable" if @readonly.include?(key)
541
+ @variables.delete(key)
542
+ @line_tracking = false if key == "LINENO"
543
+ @command_hash.clear if key == "PATH"
544
+ @arrays.delete(key)
545
+ @exported.delete(key)
546
+ end
547
+ end
548
+ 0
549
+ when "alias" then alias_command(args, streams)
550
+ when "unalias"
551
+ flags = builtin_flags(args, "a", "unalias")
552
+ if flags.include?("a")
553
+ @aliases.clear
554
+ else
555
+ raise ExecutionError, "unalias: expected an alias name" if args.empty?
556
+ missing = args.reject { |name_to_remove| @aliases.delete(name_to_remove) }
557
+ raise ExecutionError, "unalias: not found: #{missing.join(' ')}" unless missing.empty?
558
+ end
559
+ 0
560
+ when "set" then set_options(args, streams)
561
+ when "shift"
562
+ raise ExecutionError, "shift: expected one nonnegative count" if args.length > 1 || args.first && !args.first.match?(/\A\d+\z/)
563
+ count = args.empty? ? 1 : args.first.to_i
564
+ return 1 if count > @arguments.length
565
+ @arguments = @arguments.drop(count)
566
+ 0
567
+ when "break", "continue"
568
+ raise ExecutionError, "#{name}: expected a positive count" if args.length > 1 || args.first && !args.first.match?(/\A[1-9][0-9]*\z/)
569
+ levels = args.empty? ? 1 : [args.first.to_i, @loop_depth].min
570
+ raise ExecutionError, "#{name}: not in a loop" if @loop_depth.zero?
571
+ raise Flow.new(name.to_sym, 0, levels: levels)
572
+ when "return", "exit"
573
+ raise ExecutionError, "return: not in a function" if name == "return" && @function_depth.zero? && @source_depth.zero?
574
+ raise ExecutionError, "#{name}: expected numeric status" if args.length > 1 || args.first && !args.first.match?(/\A[+-]?\d+\z/)
575
+ raise Flow.new(name.to_sym, args.empty? ? @status : args.first.to_i % 256)
576
+ when "kwsh" then script(args, streams)
577
+ else external(arguments, streams)
578
+ end
579
+ end
580
+
581
+ def call_function(name, args, streams)
582
+ raise ExecutionError, "function nesting exceeds 100 levels" if @function_depth >= 100
583
+ previous = @arguments
584
+ @arguments = args
585
+ @function_depth += 1
586
+ @local_scopes << {}
587
+ begin
588
+ evaluate(@functions.fetch(name), streams)
589
+ rescue Flow => flow
590
+ raise unless flow.kind == :return
591
+ flow.status
592
+ ensure
593
+ restore_locals(@local_scopes.pop)
594
+ @arguments = previous
595
+ @function_depth -= 1
596
+ end
597
+ end
598
+
599
+ def script(args, streams)
600
+ if @options.include?("monitor") && !@job_child
601
+ return start_job(Node.new(kind: :script, values: [args], source: @command_description), streams, background: false)
602
+ end
603
+ raise ExecutionError, "Usage: kwsh <file> [arguments...]" if args.empty?
604
+ source = @directory.open_file(args.first, &:read)
605
+ streams.values.compact.uniq.each(&:flush)
606
+ pid = Process.fork do
607
+ reset_child_state
608
+ File.umask(@umask)
609
+ runtime = self.class.new(cwd: cwd, directory: @directory, env: environment, arguments: args.drop(1), name: args.first,
610
+ interactive: @hosted, hosted: @hosted, descriptors: streams.reject { |fd, _| fd < 3 }, process_owned: true)
611
+ runtime.send(:reset_child_state, job_group: @owned_job_group)
612
+ runtime.run(source, input: streams[0], output: streams[1], error: streams[2])
613
+ runtime.send(:wait_builtin, [], streams) if @hosted
614
+ status = runtime.finish(input: streams[0], output: streams[1], error: streams[2])
615
+ streams.values.compact.uniq.each(&:flush)
616
+ exit!(status)
617
+ end
618
+ result = wait(pid)
619
+ pid = nil
620
+ result
621
+ ensure
622
+ terminate(pid) if pid
623
+ end
624
+
625
+ def assign_word(key, word, streams)
626
+ value = expand(word, assignment: true).join
627
+ if @options.include?("xtrace") && key.is_a?(String)
628
+ trace("#{key}=#{Shellwords.escape(value)}", streams)
629
+ end
630
+ assign(key, value)
631
+ end
632
+
633
+ def assign(key, value)
634
+ return array_store(key, value) if key.is_a?(Reference)
635
+ validate_name(key)
636
+ raise ExecutionError, "#{key}: readonly variable" if @readonly.include?(key)
637
+ @line_tracking = false if key == "LINENO"
638
+ @command_hash.clear if key == "PATH"
639
+ @getopts_index = nil if key == "OPTIND" && value == "1" && !@getopts_running
640
+ @exported.add(key) if @options.include?("allexport")
641
+ if @arrays.key?(key)
642
+ array = @arrays[key]
643
+ array.values[array.associative ? "0" : 0] = value
644
+ else
645
+ @variables[key] = value
646
+ end
647
+ end
648
+
649
+ def validate_name(key)
650
+ raise ExecutionError, "invalid variable name: #{key}" unless key.match?(/\A[A-Za-z_][A-Za-z0-9_]*\z/)
651
+ end
652
+
653
+ def export(args, streams)
654
+ flags = builtin_flags(args, "p", "export")
655
+ if args.empty? || flags.include?("p")
656
+ @exported.sort.each do |key|
657
+ value = @variables.key?(key) ? "=#{Shellwords.escape(@variables[key])}" : ""
658
+ write_line(streams, "export #{key}#{value}")
659
+ end
660
+ else
661
+ args.each do |argument|
662
+ key, value = argument.split("=", 2)
663
+ validate_name(key)
664
+ assign(key, value) if value
665
+ @exported.add(key)
666
+ end
667
+ end
668
+ 0
669
+ end
670
+
671
+ def alias_command(args, streams)
672
+ builtin_flags(args, "", "alias")
673
+ if args.empty?
674
+ @aliases.sort.each { |key, value| write_line(streams, "#{key}=#{Shellwords.escape(value)}") }
675
+ else
676
+ args.each do |argument|
677
+ key, value = argument.split("=", 2)
678
+ unless key.match?(/\A[A-Za-z0-9_!%,@-]+\z/)
679
+ raise ExecutionError, "invalid alias name: #{key}"
680
+ end
681
+ if value
682
+ @aliases[key] = value
683
+ elsif @aliases.key?(key)
684
+ write_line(streams, "#{key}=#{Shellwords.escape(@aliases[key])}")
685
+ else
686
+ raise ExecutionError, "alias: not found: #{key}"
687
+ end
688
+ end
689
+ end
690
+ 0
691
+ end
692
+
693
+ def change_directory(args, streams)
694
+ flags = builtin_flags(args, "LPe", "cd")
695
+ physical = flags.reverse.find { |flag| flag == "L" || flag == "P" } == "P"
696
+ raise ExecutionError, "cd: too many arguments" if args.length > 1
697
+ target = args.first || @variables["HOME"]
698
+ target = @variables["OLDPWD"] if target == "-"
699
+ raise ExecutionError, "cd: directory is not set" if target.to_s.empty?
700
+ prefix = nil
701
+ unless target.start_with?("/", "./", "../") || %w[. ..].include?(target) || args.first == "-"
702
+ prefix = @variables.fetch("CDPATH", "").split(":", -1).find do |directory|
703
+ candidate = @directory.resolve(File.join(directory.empty? ? "." : directory, target))
704
+ File.directory?(candidate)
705
+ end
706
+ end
707
+ target = File.join(prefix, target) if prefix && !prefix.empty?
708
+ path = physical ? target : logical_directory(target)
709
+ base = cwd
710
+ operand = if !physical && path == base
711
+ "."
712
+ elsif !physical && path.start_with?(base.delete_suffix("/") + "/")
713
+ path.delete_prefix(base.delete_suffix("/") + "/")
714
+ else
715
+ path
716
+ end
717
+ replacement = Directory.new(operand, base: @directory)
718
+ status = 0
719
+ if physical
720
+ begin
721
+ path = replacement.physical_path
722
+ rescue SystemCallError => e
723
+ # The descriptor is valid even when its physical name is unavailable.
724
+ path = target.start_with?("/") ? target : File.join(cwd, target)
725
+ if flags.include?("e")
726
+ streams[2]&.puts("kwsh: cd: #{e.message}")
727
+ status = 1
728
+ end
729
+ end
730
+ end
731
+ @variables["OLDPWD"] = @cwd
732
+ previous = @directory
733
+ @directory = replacement
734
+ replacement = nil
735
+ previous.close
736
+ @cwd = path
737
+ @variables["PWD"] = @cwd
738
+ @exported.merge(%w[PWD OLDPWD])
739
+ @command_hash.clear
740
+ write_line(streams, @cwd) if args.first == "-" || prefix && !prefix.empty?
741
+ status
742
+ rescue Errno::ENOENT, Errno::ENOTDIR
743
+ raise ExecutionError, "cd: no such directory: #{target}"
744
+ rescue Errno::EACCES
745
+ raise ExecutionError, "cd: permission denied: #{target}"
746
+ ensure
747
+ replacement&.close
748
+ end
749
+
750
+ def logical_directory(target)
751
+ path = target.start_with?("/") ? target : File.join(cwd, target)
752
+ components = []
753
+ path.split("/").each do |component|
754
+ next if component.empty? || component == "."
755
+ if component == ".."
756
+ unless components.empty?
757
+ preceding = "/#{components.join('/')}"
758
+ raise ExecutionError, "cd: not a directory: #{preceding}" unless File.directory?(preceding)
759
+ components.pop
760
+ end
761
+ else
762
+ components << component
763
+ end
764
+ end
765
+ "/#{components.join('/')}"
766
+ end
767
+
768
+ def read_variables(args, streams)
769
+ raw = false
770
+ delimiter = "\n"
771
+ array_name = nil
772
+ while args.first&.start_with?("-") && args.first != "-"
773
+ option = args.shift
774
+ break if option == "--"
775
+ flags = option.delete_prefix("-")
776
+ until flags.empty?
777
+ flag = flags.slice!(0)
778
+ case flag
779
+ when "r" then raw = true
780
+ when "a"
781
+ array_name = flags.empty? ? args.shift : flags
782
+ raise ExecutionError, "read: -a requires an array name" unless array_name
783
+ flags = ""
784
+ when "d"
785
+ value = flags.empty? ? args.shift : flags
786
+ raise ExecutionError, "read: -d requires a delimiter" unless value
787
+ delimiter = value.empty? ? "\0" : value.byteslice(0, 1)
788
+ flags = ""
789
+ else raise ExecutionError, "read: unsupported option -#{flag}"
790
+ end
791
+ end
792
+ end
793
+ raise ExecutionError, "read: expected a variable name" if args.empty? && !array_name
794
+ raise ExecutionError, "read: -a cannot be combined with variable operands" if array_name && !args.empty?
795
+ validate_name(array_name) if array_name
796
+ args.each { |name| validate_name(name) }
797
+ input = streams[0]
798
+ raise IOError, "standard input is closed" unless input
799
+ text = +"".b
800
+ complete = false
801
+ while (byte = read_byte(input))
802
+ if byte == delimiter
803
+ complete = true
804
+ break
805
+ elsif byte == "\\" && !raw
806
+ escaped = read_byte(input)
807
+ break unless escaped
808
+ if escaped == "\n"
809
+ streams[2]&.write(prompt_text("PS2", error: streams[2])) if input.tty? && interactive_scope?
810
+ next
811
+ end
812
+ text << byte << escaped
813
+ else
814
+ text << byte
815
+ end
816
+ end
817
+ text.force_encoding(input.external_encoding || Encoding.default_external)
818
+ characters = []
819
+ source = text.each_char
820
+ loop do
821
+ character = source.next
822
+ if character == "\\" && !raw
823
+ characters.concat(Fields.characters(source.next, quoted: true))
824
+ else
825
+ characters.concat(Fields.characters(character, split: true))
826
+ end
827
+ end
828
+ ranges = Fields.ranges(characters, ifs, limit: array_name ? nil : args.length - 1)
829
+ if array_name
830
+ declare_array(["-a", array_name])
831
+ @arrays[array_name].values = ranges.each_with_index.to_h { |range, index| [index, Fields.value(characters[range])] }
832
+ else
833
+ args.each_with_index do |name, index|
834
+ assign(name, ranges[index] ? Fields.value(characters[ranges[index]]) : "")
835
+ end
836
+ end
837
+ complete ? 0 : 1
838
+ end
839
+
840
+ # Never read ahead: the next command may inherit this descriptor directly.
841
+ def read_byte(input)
842
+ input.readpartial(1)
843
+ rescue EOFError
844
+ nil
845
+ end
846
+
847
+ def write_line(streams, text)
848
+ raise IOError, "standard output is closed" unless streams[1]
849
+ streams[1].puts(text)
850
+ end
851
+
852
+ def with_redirects(redirects, streams, fatal: false)
853
+ redirected = streams.dup
854
+ opened = []
855
+ redirects.each do |descriptor, operator, word|
856
+ if word.is_a?(HereDocument)
857
+ file = Tempfile.new("kwsh-heredoc")
858
+ file.unlink
859
+ opened << file
860
+ file.write(scalar(word.word))
861
+ file.rewind
862
+ redirected[descriptor] = file
863
+ next
864
+ end
865
+ # POSIX redirection words do not undergo field splitting or pathname
866
+ # expansion (interactive pathname expansion is optional).
867
+ target = scalar(word)
868
+ if %w[>& <&].include?(operator)
869
+ raise ExecutionError, "redirection requires descriptor 0 through 9, or -" unless target.match?(/\A[0-9-]\z/)
870
+ raise ExecutionError, "bad file descriptor: #{target}" if target != "-" && !redirected[target.to_i]
871
+ redirected[descriptor] = target == "-" ? nil : redirected[target.to_i]
872
+ else
873
+ mode = { "<" => "r", ">" => "w", ">|" => "w", ">>" => "a", "<>" => File::RDWR | File::CREAT }.fetch(operator)
874
+ if operator == ">" && @options.include?("noclobber")
875
+ path = @directory.resolve(target)
876
+ mode = File::WRONLY | File::CREAT | File::EXCL if !File.exist?(path) || File.file?(path)
877
+ end
878
+ previous_mask = File.umask(@umask)
879
+ begin
880
+ file = @directory.open_file(target, mode)
881
+ ensure
882
+ File.umask(previous_mask)
883
+ end
884
+ file.sync = true
885
+ opened << file
886
+ redirected[descriptor] = file
887
+ end
888
+ end
889
+ executing = true
890
+ yield redirected
891
+ rescue ExecutionError, SystemCallError, IOError, ArgumentError => e
892
+ raise if executing
893
+ command_error(e, redirected, fatal: fatal)
894
+ ensure
895
+ opened&.each(&:close)
896
+ end
897
+
898
+ def executable_path(name)
899
+ if name.include?("/")
900
+ @directory.resolve(name)
901
+ else
902
+ current_path = begin
903
+ @directory.access_path
904
+ rescue SystemCallError
905
+ nil
906
+ end
907
+ path_key = [@variables["PATH"], current_path]
908
+ if @hash_path != path_key
909
+ @command_hash.clear
910
+ @hash_path = path_key
911
+ end
912
+ cached = @command_hash[name]
913
+ return cached if cached && File.file?(cached) && File.executable?(cached)
914
+ @command_hash.delete(name)
915
+ candidates = @variables.fetch("PATH", "/usr/bin:/bin").split(":", -1).filter_map do |directory|
916
+ @directory.resolve(File.join(directory.empty? ? "." : directory, name))
917
+ rescue Errno::ENOENT, Errno::EACCES
918
+ nil
919
+ end
920
+ candidates.find { |path| File.file?(path) && File.executable?(path) } || candidates.find { |path| File.exist?(path) }
921
+ end
922
+ end
923
+
924
+ def external(arguments, streams)
925
+ if @options.include?("monitor") && !@job_child
926
+ return start_job(Node.new(kind: :external, values: [arguments], source: @command_description), streams, background: false)
927
+ end
928
+ name = arguments.first
929
+ executable = executable_path(name)
930
+ unless executable
931
+ streams[2]&.puts("kwsh: #{name}: command not found")
932
+ return 127
933
+ end
934
+ pid = NativeProcess.spawn(executable, arguments, environment, cwd: @directory, streams: streams, mask: @umask, hosted: @hosted, signals: child_signal_dispositions)
935
+ result = wait(pid)
936
+ pid = nil
937
+ result
938
+ ensure
939
+ terminate(pid) if pid
940
+ end
941
+
942
+ def wait(pid)
943
+ loop do
944
+ status = NativeProcess.wait(pid)
945
+ if status.stopped?
946
+ # Programs such as pagers can suspend themselves, not the entire
947
+ # group. Surface that stop through the native job supervisor.
948
+ Process.kill(status.stopsig, -@owned_job_group) if @owned_job_group == Process.getpgrp
949
+ next
950
+ end
951
+ return status.exitstatus || 128 + status.termsig if status.exited? || status.signaled?
952
+ end
953
+ end
954
+
955
+ def terminate(pid)
956
+ Process.kill("TERM", pid)
957
+ Process.kill("KILL", pid)
958
+ Process.wait(pid)
959
+ rescue Errno::ESRCH, Errno::ECHILD
960
+ nil
961
+ end
962
+ end
963
+ end
964
+ end