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,62 @@
1
+ module Kward
2
+ module NativeShell
3
+ # Shared field splitting for word expansion and read. Quote provenance stays
4
+ # attached to characters; literal text is never split merely because it is IFS.
5
+ module Fields
6
+ Character = Struct.new(:text, :quoted, :split, keyword_init: true)
7
+ DEFAULT_IFS = " \t\n".freeze
8
+
9
+ def self.characters(value, quoted: false, split: false)
10
+ result = value.each_char.map { |text| Character.new(text: text, quoted: quoted, split: split) }
11
+ result << Character.new(text: "", quoted: true, split: false) if value.empty? && quoted
12
+ result
13
+ end
14
+
15
+ def self.separator?(character, ifs)
16
+ character && character.split && !character.text.empty? && ifs.include?(character.text)
17
+ end
18
+
19
+ def self.whitespace?(character, ifs)
20
+ separator?(character, ifs) && DEFAULT_IFS.include?(character.text)
21
+ end
22
+
23
+ # Ranges retain original separators for read's final, unsplit variable.
24
+ def self.ranges(characters, ifs, limit: nil)
25
+ result = []
26
+ index = 0
27
+ index += 1 while whitespace?(characters[index], ifs)
28
+ while index < characters.length
29
+ start = index
30
+ if limit && result.length >= limit
31
+ finish = characters.length
32
+ finish -= 1 while finish > start && whitespace?(characters[finish - 1], ifs)
33
+ result << (start...finish) if finish > start
34
+ break
35
+ end
36
+ index += 1 while index < characters.length && !separator?(characters[index], ifs)
37
+ result << (start...index)
38
+ if whitespace?(characters[index], ifs)
39
+ index += 1 while whitespace?(characters[index], ifs)
40
+ index += 1 if separator?(characters[index], ifs)
41
+ elsif separator?(characters[index], ifs)
42
+ index += 1
43
+ end
44
+ index += 1 while whitespace?(characters[index], ifs)
45
+ end
46
+ result
47
+ end
48
+
49
+ def self.value(characters)
50
+ characters.map(&:text).join
51
+ end
52
+
53
+ def self.pattern(characters, glob: false)
54
+ characters.map do |character|
55
+ next character.text unless character.quoted || glob
56
+ special = character.quoted ? /[\\*?\[\]{}!^\-]/ : /[{}]/
57
+ character.text.gsub(special) { |text| "\\#{text}" }
58
+ end.join
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,96 @@
1
+ module Kward
2
+ module NativeShell
3
+ # Path traversal uses the same bounded pattern matcher as case and trimming.
4
+ # Recursive ** never follows symlinked directories or visits hidden entries.
5
+ class Glob
6
+ MAX_ENTRIES = 100_000
7
+ MAX_DEPTH = 100
8
+
9
+ def initialize(pattern, cwd:, locale:, globstar: false)
10
+ @parts = pattern.split("/", -1)
11
+ @absolute = pattern.start_with?("/")
12
+ @parts.shift if @absolute
13
+ @root = @absolute ? "/" : cwd
14
+ @locale = locale
15
+ @globstar = globstar
16
+ @matches = []
17
+ @visited = 0
18
+ end
19
+
20
+ def matches
21
+ root = @root
22
+ prefix = +(@absolute ? "/" : "")
23
+ index = 0
24
+ if root.respond_to?(:access_path)
25
+ # Resolve literal directory prefixes through the retained descriptor,
26
+ # including ../patterns when the current directory has been removed.
27
+ while index < @parts.length - 1 && !Pattern.new(@parts[index], locale: @locale).wildcards?
28
+ prefix << @parts[index].gsub(/\\(.)/m, '\1') << "/"
29
+ index += 1
30
+ end
31
+ opened = Directory.new(prefix, base: root) unless prefix.empty?
32
+ root = (opened || root).access_path
33
+ end
34
+ walk(root, prefix, index, index)
35
+ @matches.uniq.sort { |left, right| @locale.compare(left, right) }
36
+ rescue Errno::ENOENT, Errno::ENOTDIR, Errno::EACCES
37
+ []
38
+ ensure
39
+ opened&.close
40
+ end
41
+
42
+ private
43
+
44
+ def entries(directory)
45
+ Dir.each_child(directory).each_with_object([]) do |name, result|
46
+ @visited += 1
47
+ raise ExpansionError, "pathname expansion exceeds #{MAX_ENTRIES} entries" if @visited > MAX_ENTRIES
48
+ result << name
49
+ end
50
+ rescue Errno::ENOENT, Errno::ENOTDIR, Errno::EACCES
51
+ []
52
+ end
53
+
54
+ def walk(directory, prefix, index, depth, expanding: false)
55
+ raise ExpansionError, "pathname expansion exceeds #{MAX_DEPTH} directory levels" if depth > MAX_DEPTH
56
+ part = @parts[index]
57
+ if part == ""
58
+ if index == @parts.length - 1
59
+ @matches << prefix unless prefix.empty?
60
+ else
61
+ walk(directory, prefix + "/", index + 1, depth)
62
+ end
63
+ return
64
+ end
65
+ recursive = @globstar && part == "**"
66
+ if recursive
67
+ if index == @parts.length - 1
68
+ @matches << prefix unless prefix.empty? || expanding
69
+ else
70
+ walk(directory, prefix, index + 1, depth)
71
+ end
72
+ end
73
+ matcher = Pattern.new(part, locale: @locale)
74
+ names = matcher.wildcards? ? entries(directory) : [part.gsub(/\\(.)/m, '\1')]
75
+ names.each do |name|
76
+ next if name.start_with?(".") && !part.start_with?(".", "\\.")
77
+ next unless matcher.match?(name)
78
+ path = File.join(directory, name)
79
+ next unless File.exist?(path) || File.symlink?(path)
80
+ if index == @parts.length - 1
81
+ @matches << prefix + name
82
+ elsif File.directory?(path)
83
+ walk(path, prefix + name + "/", index + 1, depth + 1) unless recursive
84
+ end
85
+ if recursive && File.directory?(path)
86
+ if File.symlink?(path)
87
+ @matches << prefix + name + "/" if @parts[(index + 1)..] == [""]
88
+ else
89
+ walk(path, prefix + name + "/", index, depth + 1, expanding: true)
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,242 @@
1
+ require "json"
2
+ require "tmpdir"
3
+ require "tempfile"
4
+
5
+ module Kward
6
+ module NativeShell
7
+ # Standalone command history. No implicit disk storage; unsafe/unavailable
8
+ # HISTFILE paths fall back to memory without altering their permissions.
9
+ class History
10
+ attr_reader :entries, :next_number
11
+
12
+ def initialize(variables, directory:)
13
+ size = variables["HISTSIZE"]
14
+ @size = size&.match?(/\A[0-9]+\z/) ? size.to_i : 512
15
+ @entries = []
16
+ @next_number = 1
17
+ @owner = Process.pid
18
+ path = variables["HISTFILE"]
19
+ @path = directory.resolve(path) if path && !path.empty?
20
+ refresh
21
+ rescue SystemCallError, IOError, ArgumentError
22
+ @path = nil
23
+ end
24
+
25
+ def paused?
26
+ @paused == true
27
+ end
28
+
29
+ def paused=(paused)
30
+ discard_pending if paused
31
+ @paused = paused
32
+ end
33
+
34
+ def with_entry(text)
35
+ return yield if paused?
36
+
37
+ @pending = text unless text.strip.empty?
38
+ yield
39
+ ensure
40
+ commit_pending
41
+ end
42
+
43
+ def commit_pending
44
+ pending, @pending = @pending, nil
45
+ add(pending) if pending
46
+ end
47
+
48
+ def discard_pending
49
+ @pending = nil
50
+ end
51
+
52
+ def add(text)
53
+ return if paused? || text.strip.empty?
54
+ text = text.chomp
55
+ saved = with_lock do
56
+ entries = read_entries
57
+ number = [@next_number, entries.last&.first.to_i + 1].max
58
+ entries = (entries << [number, text]).last(@size)
59
+ persist(entries)
60
+ update_entries(entries, number + 1)
61
+ end
62
+ update_entries((@entries + [[@next_number, text]]).last(@size), @next_number + 1) unless saved
63
+ end
64
+
65
+ def refresh
66
+ with_lock do
67
+ entries = read_entries
68
+ update_entries(entries.last(@size), entries.last&.first.to_i + 1)
69
+ end
70
+ end
71
+
72
+ def select(first, last, listing:)
73
+ raise ExecutionError, "fc: history is empty" if @entries.empty?
74
+ first ||= listing ? "-16" : "-1"
75
+ last ||= listing ? "-1" : first
76
+ from = index(first, range: listing || first != last)
77
+ to = index(last, range: listing || first != last)
78
+ selected = @entries[[from, to].min..[from, to].max]
79
+ from > to ? selected.reverse : selected
80
+ end
81
+
82
+ private
83
+
84
+ def index(value, range:)
85
+ index = if value.match?(/\A-[0-9]+\z/)
86
+ @entries.length + value.to_i
87
+ elsif value.match?(/\A\+?[0-9]+\z/)
88
+ @entries.index { |number, _| number == value.to_i } || (value.to_i < @entries.first[0] ? -1 : @entries.length)
89
+ else
90
+ @entries.rindex { |_, text| text.start_with?(value) }
91
+ end
92
+ raise ExecutionError, "fc: history entry not found: #{value}" unless index && (range || index.between?(0, @entries.length - 1))
93
+ index.clamp(0, @entries.length - 1)
94
+ end
95
+
96
+ def with_lock
97
+ return unless @path && Process.pid == @owner
98
+
99
+ flags = File::RDWR | File::CREAT | File::NOFOLLOW | File::NONBLOCK
100
+ File.open("#{@path}.lock", flags, 0600) do |lock|
101
+ validate_file(lock)
102
+ lock.flock(File::LOCK_EX)
103
+ yield
104
+ end
105
+ rescue SystemCallError, IOError, ArgumentError, JSON::ParserError
106
+ @path = nil
107
+ end
108
+
109
+ def validate_file(file)
110
+ stat = file.stat
111
+ return if stat.file? && stat.uid == Process.uid && stat.nlink == 1 && (stat.mode & 0777) == 0600
112
+
113
+ raise IOError, "unsafe history file"
114
+ end
115
+
116
+ def read_entries
117
+ entries = []
118
+ File.open(@path, File::RDONLY | File::NOFOLLOW | File::NONBLOCK) do |file|
119
+ validate_file(file)
120
+ file.each_line do |line|
121
+ entry = JSON.parse(line)
122
+ if entry.is_a?(Array) && entry[1].is_a?(Hash) && entry[1].keys == ["bytes"] && entry[1]["bytes"].is_a?(String)
123
+ entry[1] = entry[1]["bytes"].unpack1("m0")
124
+ end
125
+ unless entry.is_a?(Array) && entry.size == 2 && entry[0].is_a?(Integer) && entry[0] > entries.last&.first.to_i && entry[1].is_a?(String)
126
+ raise ArgumentError, "invalid history"
127
+ end
128
+ entries << entry
129
+ end
130
+ end
131
+ entries
132
+ rescue Errno::ENOENT
133
+ []
134
+ end
135
+
136
+ def persist(entries)
137
+ limit = Process.getrlimit(:FSIZE).first
138
+ bytes = 0
139
+ Tempfile.create(".kwsh-history-", File.dirname(@path)) do |file|
140
+ file.binmode
141
+ entries.each do |number, text|
142
+ value = text.dup.force_encoding(Encoding::UTF_8)
143
+ value = { "bytes" => [text].pack("m0") } unless value.valid_encoding?
144
+ record = JSON.generate([number, value]) + "\n"
145
+ bytes += record.bytesize
146
+ # The kernel can send SIGXFSZ before a write raises EFBIG.
147
+ raise IOError, "history exceeds the file size limit" if limit != Process::RLIM_INFINITY && bytes > limit
148
+ file.write(record)
149
+ end
150
+ file.fsync
151
+ File.rename(file.path, @path)
152
+ end
153
+ end
154
+
155
+ def update_entries(entries, next_number)
156
+ @entries = entries
157
+ @next_number = [@next_number, next_number].max
158
+ end
159
+
160
+ end
161
+
162
+ module HistoryCommands
163
+ def history
164
+ raise ExecutionError, "fc: native history is standalone-only; hosted input owns its history" if @hosted
165
+ @history ||= History.new(@variables, directory: @directory)
166
+ end
167
+
168
+ def with_history_entry(text)
169
+ return yield if @hosted
170
+ history.with_entry(text) { yield }
171
+ end
172
+
173
+ private
174
+
175
+ def fc_builtin(args, streams)
176
+ flags = []
177
+ editor = nil
178
+ while args.first&.start_with?("-") && !args.first.match?(/\A-[0-9]+\z/)
179
+ option = args.shift
180
+ break if option == "--"
181
+ chars = option.delete_prefix("-").chars
182
+ until chars.empty?
183
+ flag = chars.shift
184
+ raise ExecutionError, "fc: unsupported option -#{flag}" unless "elnrs".include?(flag)
185
+ flags << flag
186
+ if flag == "e"
187
+ editor = chars.empty? ? args.shift : chars.join
188
+ raise ExecutionError, "fc: -e requires an editor" unless editor
189
+ chars.clear
190
+ end
191
+ end
192
+ end
193
+ listing = flags.include?("l")
194
+ direct = flags.include?("s")
195
+ raise ExecutionError, "fc: incompatible options" if direct && (flags - ["s"]).any? || listing && editor || flags.include?("n") && !listing
196
+ substitution = args.shift.split("=", 2) if direct && args.first&.include?("=")
197
+ raise ExecutionError, "fc: too many operands" if args.length > (direct ? 1 : 2)
198
+ selected = history.select(args[0], args[1], listing: listing)
199
+ selected.reverse! if flags.include?("r")
200
+ if listing
201
+ selected.each do |number, text|
202
+ lines = text.lines(chomp: true)
203
+ write_line(streams, "#{flags.include?('n') ? '' : number}\t#{lines.shift}")
204
+ lines.each { |line| write_line(streams, "\t#{line}") }
205
+ end
206
+ return 0
207
+ end
208
+ history.discard_pending
209
+ source = selected.map(&:last).join("\n") + "\n"
210
+ if direct
211
+ source = source.sub(substitution[0]) { substitution[1] } if substitution
212
+ else
213
+ editor ||= expand_parameters(@variables.fetch("FCEDIT", ""))
214
+ editor = "ed" if editor.empty?
215
+ result, source = edit_history(source, editor, streams)
216
+ return result unless result.zero?
217
+ end
218
+ raise ExecutionError, "fc nesting exceeds 100 levels" if @eval_depth >= 100
219
+ @eval_depth += 1
220
+ begin
221
+ history.add(source)
222
+ evaluate_program(StringIO.new(source), streams)
223
+ ensure
224
+ @eval_depth -= 1
225
+ end
226
+ end
227
+
228
+ def edit_history(source, editor, streams)
229
+ Dir.mktmpdir("kwsh-fc-") do |directory|
230
+ path = File.join(directory, "command")
231
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0600) { |file| file.chmod(0600); file.write(source) }
232
+ result = external([editor, path], streams)
233
+ return [result, nil] unless result.zero?
234
+ File.open(path, File::RDONLY | File::NOFOLLOW | File::NONBLOCK) do |file|
235
+ raise ExecutionError, "fc: editor did not leave a private regular file" unless file.stat.file? && file.stat.uid == Process.uid && file.stat.nlink == 1 && (file.stat.mode & 077) == 0
236
+ [0, file.read]
237
+ end
238
+ end
239
+ end
240
+ end
241
+ end
242
+ end
@@ -0,0 +1,164 @@
1
+ require_relative "native_completion"
2
+ require_relative "native_prompt_format"
3
+ require_relative "../terminal/ansi"
4
+
5
+ module Kward
6
+ module NativeShell
7
+ # Prompt-time state only. Hosted shells keep their composer and notifications.
8
+ module Interactive
9
+ class AgentCommandTimeout < StandardError; end
10
+
11
+ def run_shell_agent_command(command, timeout:, output:, error:)
12
+ require "timeout"
13
+ @shell_agent_command = true
14
+ previous = Signal.trap("INT") { raise Interrupt }
15
+ File.open(File::NULL) do |input|
16
+ Timeout.timeout(timeout, AgentCommandTimeout) do
17
+ yield
18
+ with_pager_suppressed { run(command, input: input, output: output, error: error) }
19
+ end
20
+ end
21
+ rescue AgentCommandTimeout
22
+ error.puts("kwsh: shell agent command timed out")
23
+ @status = 124
24
+ rescue Interrupt
25
+ @status = 130
26
+ ensure
27
+ Signal.trap("INT", previous) if previous
28
+ @shell_agent_command = false
29
+ end
30
+
31
+ def option_enabled?(name)
32
+ @options.include?(name)
33
+ end
34
+
35
+ def complete_line(text, cursor, cancel: nil)
36
+ return if @hosted
37
+
38
+ commands = self.class::BUILTINS + @aliases.keys + @functions.keys
39
+ Completion.new(directory: @directory, variables: @variables, commands: commands).complete(text, cursor) do |words|
40
+ programmed_candidates(words, cancel: cancel) unless @job_child || @history&.paused?
41
+ end
42
+ end
43
+
44
+ def vi_expansions(text, full:)
45
+ previous_streams, previous_substitutions = @streams, @process_substitutions
46
+ previous_status = @status
47
+ @process_substitutions = []
48
+ pattern = text.match?(/[*?\[]/) ? text : text + "*"
49
+ @streams = @base_streams || { 0 => $stdin, 1 => $stdout, 2 => $stderr }
50
+ matches = if full
51
+ tokens = Lexer.new(pattern).tokens
52
+ raise ExecutionError, "vi expansion requires one shell word" unless tokens.one? && tokens.first.value.is_a?(Word)
53
+ expand(tokens.first.value)
54
+ else
55
+ Locale.with(@variables) { |locale| Glob.new(pattern, cwd: @directory, locale: locale, globstar: @globstar).matches }
56
+ end
57
+ matches.map { |path| File.directory?(@directory.resolve(path)) && !path.end_with?("/") ? path + "/" : path }
58
+ ensure
59
+ resources = @process_substitutions
60
+ @streams, @process_substitutions = previous_streams, previous_substitutions
61
+ @status = previous_status
62
+ finish_substitutions(resources) if resources
63
+ end
64
+
65
+ def vi_input_error(exception, error:)
66
+ @options.delete("vi")
67
+ @status = 2
68
+ error.puts("kwsh: vi disabled: #{exception.message}")
69
+ end
70
+
71
+ def vi_edit(source, input:, output:, error:)
72
+ result, text = edit_history(source, "vi", { 0 => input, 1 => output, 2 => error }.merge(@persistent_descriptors))
73
+ @status = result
74
+ text if result.zero?
75
+ rescue ExecutionError, SystemCallError, IOError, ArgumentError => e
76
+ error.puts("kwsh: vi: #{e.message}")
77
+ @status = 2
78
+ nil
79
+ end
80
+
81
+ def prompt_text(name, error:, formatted: false)
82
+ default = { "PS1" => "$ ", "PS2" => "> ", "PS4" => "+ " }.fetch(name)
83
+ prefix = formatted && name != "PS4" && history.paused? ? "[private] " : ""
84
+ if formatted && name == "PS1" && @variables.key?("PROMPT")
85
+ color = error.tty? && @variables["TERM"] != "dumb" && ANSI.enabled?(error, env: @variables)
86
+ return PromptFormat.new(@variables.fetch("PROMPT"), directory: cwd, home: @variables["HOME"], status: @status, color: color, prefix: prefix)
87
+ end
88
+
89
+ value = expand_parameters(@variables.fetch(name, default))
90
+ value = value.gsub(/!!|!/) { |mark| mark == "!!" ? "!" : history.next_number.to_s } if name == "PS1" && !@hosted
91
+ prefix + value
92
+ rescue SyntaxError, ExpansionError, ExecutionError => e
93
+ error&.puts("kwsh: #{name}: #{e.message}")
94
+ prefix.to_s + default
95
+ end
96
+
97
+ def check_mail(error, now: Process.clock_gettime(Process::CLOCK_MONOTONIC))
98
+ return if @hosted
99
+ @mail ||= MailNotifications.new
100
+ @mail.check(@variables, @directory, now: now) do |message|
101
+ error&.puts(expand_parameters(message))
102
+ rescue SyntaxError, ExpansionError, ExecutionError => e
103
+ error&.puts("kwsh: MAILPATH: #{e.message}")
104
+ end
105
+ end
106
+
107
+ private
108
+
109
+ def trace(text, streams)
110
+ return unless @options.include?("xtrace")
111
+ streams[2]&.puts("#{prompt_text('PS4', error: streams[2])}#{text}")
112
+ end
113
+ end
114
+
115
+ class MailNotifications
116
+ def initialize
117
+ @seen = {}
118
+ end
119
+
120
+ def check(variables, directory, now:)
121
+ interval = variables.fetch("MAILCHECK", "600")
122
+ interval = interval.match?(/\A[0-9]+\z/) ? interval.to_i : 600
123
+ return if @checked && now - @checked < interval
124
+ @checked = now
125
+ paths = variables.key?("MAILPATH") ? variables["MAILPATH"].split(":") : [variables["MAIL"]].compact
126
+ current = {}
127
+ paths.each do |entry|
128
+ path, message = parse(entry)
129
+ next if path.empty?
130
+ key = nil
131
+ begin
132
+ key = directory.resolve(path)
133
+ modified = File.stat(key).mtime
134
+ rescue SystemCallError, IOError, ArgumentError
135
+ key ||= path
136
+ modified = nil
137
+ end
138
+ yield(message || "you have mail") if @seen.key?(key) && modified && modified != @seen[key]
139
+ current[key] = modified
140
+ end
141
+ @seen = current
142
+ end
143
+
144
+ private
145
+
146
+ def parse(entry)
147
+ path = +""
148
+ index = 0
149
+ while index < entry.length
150
+ if entry[index, 2] == '\\%'
151
+ path << "%"
152
+ index += 2
153
+ elsif entry[index] == "%"
154
+ return [path, entry[(index + 1)..]]
155
+ else
156
+ path << entry[index]
157
+ index += 1
158
+ end
159
+ end
160
+ [path, nil]
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,42 @@
1
+ module Kward
2
+ module NativeShell
3
+ Invocation = Struct.new(:options, :arguments, :file, :command, :command_name, :interactive, :help, keyword_init: true) do
4
+ def self.parse(arguments)
5
+ args = arguments.dup
6
+ options = []
7
+ mode = nil
8
+ interactive = false
9
+ while args.first&.start_with?("-", "+") && args.first != "-"
10
+ option = args.shift
11
+ break if option == "--"
12
+ if option == "--help"
13
+ return new(help: true)
14
+ end
15
+ option[1..].each_char do |flag|
16
+ case flag
17
+ when "c", "s"
18
+ raise ArgumentError, "-c and -s are mutually exclusive" if mode && mode != flag
19
+ raise ArgumentError, "+#{flag} is not supported" if option.start_with?("+")
20
+ mode = flag
21
+ when "i" then interactive = option.start_with?("-")
22
+ when "o"
23
+ raise ArgumentError, "#{option} requires an option name" if args.empty?
24
+ options.concat(["#{option[0]}o", args.shift])
25
+ else options << "#{option[0]}#{flag}"
26
+ end
27
+ end
28
+ end
29
+ args.shift if args.first == "-"
30
+ command = args.shift if mode == "c"
31
+ raise ArgumentError, "-c requires a command" if mode == "c" && !command
32
+ file = args.shift unless mode || args.empty?
33
+ command_name = args.shift if mode == "c"
34
+ new(options: options, arguments: args, file: file, command: command, command_name: command_name, interactive: interactive)
35
+ end
36
+
37
+ def prompt?(input, error)
38
+ !help && !command && !file && input.tty? && error.tty?
39
+ end
40
+ end
41
+ end
42
+ end