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,186 @@
1
+ require "json"
2
+ require "thread"
3
+ require_relative "protocol"
4
+ require_relative "fake_embeddings"
5
+
6
+ module Kward
7
+ module OpenRouterProxy
8
+ class Server
9
+ ENDPOINT_PATH = "/api/v1/chat/completions"
10
+ EMBEDDINGS_ENDPOINT_PATH = "/api/v1/embeddings"
11
+ DEFAULT_PORT = 4000
12
+ DEFAULT_MAX_BODY_BYTES = 1_048_576
13
+ MAX_NONSTREAM_EVENTS = 100_000
14
+
15
+ def initialize(host:, codex: host.codex_responses, output: $stderr)
16
+ @host = host
17
+ @codex = codex
18
+ @output = output
19
+ @config = host.config
20
+ model_map = @config.fetch("model_map", {})
21
+ raise ArgumentError, "Configure at least one proxy model mapping" unless model_map.is_a?(Hash) && !model_map.empty?
22
+
23
+ @protocol = Protocol.new(model_map: model_map)
24
+ @fake_embeddings = FakeEmbeddings.new(models: @config.fetch("fake_embedding_models", {}))
25
+ @api_key = host.secret("api_key")
26
+ raise ArgumentError, "Configure the proxy api_key secret before starting" if @api_key.to_s.empty?
27
+ end
28
+
29
+ def run
30
+ listener = @host.http_server(
31
+ host: "127.0.0.1",
32
+ port: integer_config("port", DEFAULT_PORT, min: 0, max: 65_535),
33
+ max_body_bytes: integer_config("max_body_bytes", DEFAULT_MAX_BODY_BYTES, min: 1024, max: 16_777_216)
34
+ ) { |request, response| handle(request, response) }
35
+ listener.start
36
+ @output.puts("OpenRouter-compatible proxy listening at http://127.0.0.1:#{listener.port}/api/v1")
37
+ listener.wait
38
+ ensure
39
+ listener&.stop
40
+ end
41
+
42
+ def handle(request, response)
43
+ return unauthorized(response) unless authorized?(request)
44
+ unless [ENDPOINT_PATH, EMBEDDINGS_ENDPOINT_PATH].include?(request.path)
45
+ return write_error(response, 404, "Not found", "not_found")
46
+ end
47
+ return write_error(response, 405, "Method not allowed", "method_not_allowed") unless request.request_method == "POST"
48
+ return write_error(response, 415, "Content-Type must be application/json", "invalid_content_type") unless request["content-type"].to_s.downcase.start_with?("application/json")
49
+
50
+ payload = JSON.parse(request.body.to_s)
51
+ return write_json(response, 200, @fake_embeddings.create(payload)) if request.path == EMBEDDINGS_ENDPOINT_PATH
52
+
53
+ parsed = @protocol.parse_request(payload)
54
+ parsed.stream ? handle_stream(parsed, response) : handle_nonstream(parsed, response)
55
+ rescue JSON::ParserError
56
+ write_error(response, 400, "Invalid JSON request body", "invalid_json")
57
+ rescue RequestError => error
58
+ write_error(response, error.status, error.message, error.status >= 500 ? "upstream_error" : "invalid_request")
59
+ rescue PluginCodexResponses::AuthenticationError
60
+ write_error(response, 503, "Kward Codex authentication is unavailable", "upstream_authentication_error")
61
+ rescue PluginCodexResponses::RequestError => error
62
+ write_error(response, 502, error.message, "upstream_error")
63
+ rescue Cancellation::CancelledError
64
+ nil
65
+ rescue StandardError
66
+ write_error(response, 502, "Codex request failed", "upstream_error")
67
+ end
68
+
69
+ private
70
+
71
+ def handle_nonstream(request, response)
72
+ events = []
73
+ @codex.stream(**@protocol.responses_request(request), max_output_tokens: request.max_output_tokens) do |event|
74
+ events << event
75
+ raise RequestError.new("Codex response exceeded the event limit", status: 502) if events.length > MAX_NONSTREAM_EVENTS
76
+ end
77
+ write_json(response, 200, @protocol.chat_completion(request, events))
78
+ end
79
+
80
+ def handle_stream(request, response)
81
+ state = @protocol.stream_state(request)
82
+ cancellation = Cancellation.new
83
+ events = SizedQueue.new(16)
84
+ worker = Thread.new do
85
+ @codex.stream(**@protocol.responses_request(request), max_output_tokens: request.max_output_tokens, cancellation: cancellation) do |event|
86
+ enqueue_stream_event(events, [:event, event], cancellation)
87
+ end
88
+ enqueue_stream_event(events, [:done, nil], cancellation)
89
+ rescue StandardError => error
90
+ enqueue_stream_event(events, [:error, error], cancellation) unless cancellation.cancelled?
91
+ end
92
+ worker.report_on_exception = false
93
+
94
+ first = events.pop
95
+ if first.first == :error
96
+ worker.join
97
+ raise first.last
98
+ end
99
+
100
+ response.status = 200
101
+ response["Content-Type"] = "text/event-stream"
102
+ response["Cache-Control"] = "no-cache"
103
+ response["X-Accel-Buffering"] = "no"
104
+ response.chunked = true
105
+ response.body = proc do |output|
106
+ output.write(sse(@protocol.stream_start_chunk(state)))
107
+ done = false
108
+ current = first
109
+ until done
110
+ kind, event = current
111
+ case kind
112
+ when :event
113
+ chunks = @protocol.stream_chunks(state, event)
114
+ chunks.each { |chunk| output.write(sse(chunk)) }
115
+ done = state[:terminal]
116
+ when :done
117
+ done = true
118
+ when :error
119
+ state[:failed] = true
120
+ output.write(sse(@protocol.stream_chunks(state, "type" => "response.failed").first))
121
+ done = true
122
+ end
123
+ current = events.pop unless done
124
+ end
125
+ output.write("data: [DONE]\n\n") unless state[:failed]
126
+ ensure
127
+ cancellation.cancel! unless state[:terminal]
128
+ worker.join(2)
129
+ end
130
+ end
131
+
132
+ def enqueue_stream_event(queue, event, cancellation)
133
+ loop do
134
+ cancellation.raise_if_cancelled!
135
+ queue.push(event, true)
136
+ return
137
+ rescue ThreadError
138
+ sleep 0.01
139
+ end
140
+ end
141
+
142
+ def authorized?(request)
143
+ authorization = request["authorization"].to_s
144
+ return false unless authorization.start_with?("Bearer ")
145
+
146
+ secure_compare(authorization.delete_prefix("Bearer "), @api_key)
147
+ end
148
+
149
+ def secure_compare(left, right)
150
+ return false unless left.bytesize == right.bytesize
151
+
152
+ left.bytes.zip(right.bytes).reduce(0) { |difference, (a, b)| difference | (a ^ b) }.zero?
153
+ end
154
+
155
+ def unauthorized(response)
156
+ response["WWW-Authenticate"] = 'Bearer realm="Kward OpenRouter proxy"'
157
+ write_error(response, 401, "Unauthorized", "invalid_api_key")
158
+ end
159
+
160
+ def write_json(response, status, payload)
161
+ response.status = status
162
+ response["Content-Type"] = "application/json"
163
+ response["Cache-Control"] = "no-store"
164
+ response.body = JSON.generate(payload)
165
+ end
166
+
167
+ def write_error(response, status, message, code)
168
+ write_json(response, status, { error: { message: message, type: "invalid_request_error", code: code } })
169
+ end
170
+
171
+ def sse(chunk)
172
+ "data: #{JSON.generate(chunk)}\n\n"
173
+ end
174
+
175
+ def integer_config(key, default, min:, max:)
176
+ value = @config.fetch(key, default)
177
+ integer = Integer(value)
178
+ raise ArgumentError, "Proxy config #{key} must be between #{min} and #{max}" unless integer.between?(min, max)
179
+
180
+ integer
181
+ rescue ArgumentError, TypeError
182
+ raise ArgumentError, "Proxy config #{key} must be an integer between #{min} and #{max}"
183
+ end
184
+ end
185
+ end
186
+ end
@@ -10,12 +10,11 @@
10
10
  # ←/→ Move
11
11
  # Space Fire
12
12
  # Q / Esc Quit
13
- # Ctrl+C Force quit (handled by Kward)
14
13
  #
15
14
  # The game renders colored sprites and particle-burst explosions inside the
16
15
  # composer canvas region using the interactive mode API.
17
16
 
18
- Kward.plugin do |plugin|
17
+ Kward.plugin(id: "com.kward.example.space-invaders", version: "1.0.0", api: 1) do |plugin|
19
18
  plugin.interactive_command "invaders", rows: 18, fps: 30, description: "Space Invaders arcade game" do |ui, ctx|
20
19
  game = SpaceInvadersGame.new(width: ui.width, height: ui.height)
21
20
  ui.on_tick { |ui| game.tick(ui) }
@@ -1,6 +1,6 @@
1
1
  # Displays the current Federation stardate in Kward's interactive footer.
2
- Kward.plugin do |plugin|
3
- plugin.footer do |_ctx|
2
+ Kward.plugin(id: "com.kward.example.stardate-footer", version: "1.0.0", api: 1) do |plugin|
3
+ plugin.status "stardate", priority: :low do |_ctx|
4
4
  now = Time.now.utc
5
5
  reference = Time.utc(1987, 7, 15)
6
6
  stardate = 41_000 + ((now - reference) / (365.25 * 24 * 60 * 60) * 1_000)
@@ -1,6 +1,6 @@
1
1
  require_relative "telegram_transport"
2
2
 
3
- Kward.plugin do |plugin|
3
+ Kward.plugin(id: "com.kward.telegram", version: "1.0.0", api: 1) do |plugin|
4
4
  capabilities = {
5
5
  inbound: %i[text],
6
6
  outbound: %i[text],
data/exe/kward CHANGED
@@ -2,6 +2,6 @@
2
2
 
3
3
  $LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
4
4
 
5
- require "kward"
5
+ require "kward/entrypoint"
6
6
 
7
- Kward::CLI.new.run
7
+ Kward::Entrypoint.run
data/exe/kwsh ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ $LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
4
+
5
+ require "kward/shell/script_runner"
6
+
7
+ Kward::NativeShell::NativeProcess.standalone(ARGV, name: $0)
data/kward.gemspec CHANGED
@@ -24,10 +24,11 @@ Gem::Specification.new do |spec|
24
24
  end
25
25
  end
26
26
  spec.bindir = "exe"
27
- spec.executables = ["kward"]
27
+ spec.executables = ["kward", "kwsh"]
28
28
  spec.require_paths = ["lib"]
29
29
 
30
30
  spec.add_dependency "base64"
31
+ spec.add_dependency "fiddle"
31
32
  spec.add_dependency "nokogiri"
32
33
  spec.add_dependency "tiktoken_ruby"
33
34
  spec.add_dependency "tty-cursor"
@@ -35,4 +36,5 @@ Gem::Specification.new do |spec|
35
36
  spec.add_dependency "tty-reader"
36
37
  spec.add_dependency "tty-screen"
37
38
  spec.add_dependency "unicode-display_width"
39
+ spec.add_dependency "webrick"
38
40
  end
data/lib/kward/agent.rb CHANGED
@@ -1,9 +1,12 @@
1
+ require "securerandom"
1
2
  require_relative "cancellation"
2
3
  require_relative "model/chat_invocation"
3
4
  require_relative "compactor"
4
5
  require_relative "model/context_overflow"
5
6
  require_relative "conversation"
7
+ require_relative "plugins/turn_request"
6
8
  require_relative "events"
9
+ require_relative "turn_summary"
7
10
  require_relative "deep_copy"
8
11
  require_relative "hooks"
9
12
  require_relative "message_access"
@@ -41,9 +44,9 @@ module Kward
41
44
 
42
45
  attr_reader :conversation, :tool_registry
43
46
 
44
- # Adds a user message, compacts context when needed, and runs the turn.
47
+ # Adds user input or scopes a plugin system request, then runs a normal turn.
45
48
  #
46
- # @param input [String] text sent to the model
49
+ # @param input [String, PluginTurnRequest] user text or host-staged system instructions
47
50
  # @param display_input [String, nil] alternate text kept for transcripts
48
51
  # @yieldparam event [Object] streamed turn event for frontends
49
52
  # @return [String] final assistant answer
@@ -51,26 +54,47 @@ module Kward
51
54
  started_at = @telemetry_logger.monotonic_now
52
55
  status = "completed"
53
56
  error = nil
57
+ summary = TurnSummary.new
58
+ turn_started = false
54
59
  cancellation&.raise_if_cancelled!
55
- turn_start = run_hook("turn_start", payload: { input: input, display_input: display_input })
60
+ system_turn = input if input.is_a?(PluginTurnRequest)
61
+ display_input ||= system_turn.to_s if system_turn
62
+ input = system_turn.system if system_turn
63
+ turn_start = run_hook("turn_start", payload: { input: input, display_input: display_input, input_role: system_turn ? "system" : "user" })
56
64
  return hook_denied_answer(turn_start) if turn_start.denied?
57
65
 
58
66
  input = turn_start.payload[:input] || turn_start.payload["input"] || input
59
67
  display_input = turn_start.payload[:display_input] || turn_start.payload["display_input"] || display_input
60
- @conversation.refresh_system_message_if_workspace_agents_changed!
61
- @conversation.append_user(input, display_content: display_input)
62
- run_hook("turn_context_build_before", payload: { message_count: @conversation.messages.length })
63
- auto_compact_if_needed
64
- run_hook("turn_context_build_after", payload: { message_count: @conversation.messages.length })
65
- answer = run_turn(on_reasoning_delta: on_reasoning_delta, on_retry: on_retry, cancellation: cancellation, steering: steering, options: options, tool_registry: tool_registry, &block)
66
- run_hook("turn_end", payload: { input: input, answer: answer })
67
- answer
68
+ if system_turn
69
+ system_turn = PluginTurnRequest.new(system: input, command: system_turn.command, plugin_id: system_turn.plugin_id, id: system_turn.id)
70
+ end
71
+ @conversation.with_system_turn(system_turn) do
72
+ @conversation.refresh_system_message_if_workspace_agents_changed!
73
+ if system_turn
74
+ @conversation.append_system_turn(system_turn)
75
+ else
76
+ @conversation.append_user(input, display_content: display_input)
77
+ end
78
+ turn_started = true
79
+ run_hook("turn_context_build_before", payload: { message_count: @conversation.messages.length })
80
+ auto_compact_if_needed
81
+ run_hook("turn_context_build_after", payload: { message_count: @conversation.messages.length })
82
+ answer = run_turn(on_reasoning_delta: on_reasoning_delta, on_retry: on_retry, cancellation: cancellation, steering: steering, options: options, tool_registry: tool_registry, summary: summary, &block)
83
+ run_hook("turn_end", payload: { input: input, answer: answer })
84
+ answer
85
+ end
68
86
  rescue StandardError => e
69
- status = "failed"
87
+ status = e.is_a?(Cancellation::CancelledError) ? "canceled" : "failed"
70
88
  error = e
71
89
  raise e
72
90
  ensure
73
- log_turn(duration_ms: @telemetry_logger.duration_ms(started_at), status: status, error: error)
91
+ elapsed_ms = @telemetry_logger.duration_ms(started_at)
92
+ log_turn(duration_ms: elapsed_ms, status: status, error: error)
93
+ if turn_started
94
+ result = summary.finish(status: status, elapsed_ms: elapsed_ms)
95
+ @conversation.finish_turn(result)
96
+ block&.call(Events::TurnSummary.new(summary: result))
97
+ end
74
98
  end
75
99
 
76
100
  # Runs model calls until the assistant returns an answer without pending
@@ -78,16 +102,18 @@ module Kward
78
102
  #
79
103
  # @yieldparam event [Object] streamed turn event for frontends
80
104
  # @return [String] final assistant answer
81
- def run_turn(on_reasoning_delta: nil, on_retry: nil, cancellation: nil, steering: nil, options: {}, tool_registry: nil)
105
+ def run_turn(on_reasoning_delta: nil, on_retry: nil, cancellation: nil, steering: nil, options: {}, tool_registry: nil, summary: nil)
82
106
  overflow_retried = false
107
+ image_turn_id = SecureRandom.uuid
83
108
  steering_state = build_steering_state(steering) do |event|
84
109
  yield event if block_given?
85
110
  end
111
+ registry = tool_registry || @tool_registry
86
112
  loop do
87
113
  cancellation&.raise_if_cancelled!
88
114
  auto_compact_if_needed
89
115
  begin
90
- message = chat(on_reasoning_delta: on_reasoning_delta, on_retry: on_retry, cancellation: cancellation, steering: steering, options: options, tool_registry: tool_registry) do |event|
116
+ message = chat(on_reasoning_delta: on_reasoning_delta, on_retry: on_retry, cancellation: cancellation, steering: steering, options: options, tool_registry: tool_registry, summary: summary) do |event|
91
117
  yield event if block_given?
92
118
  end
93
119
  rescue StandardError => e
@@ -113,14 +139,22 @@ module Kward
113
139
  end
114
140
 
115
141
  tool_calls.each do |tool_call|
142
+ image = nil
143
+ image_published = false
116
144
  cancellation&.raise_if_cancelled!
145
+ summary&.tool_call
117
146
  yield Events::ToolCall.new(tool_call: tool_call) if block_given?
118
147
  tool_started_at = @telemetry_logger.monotonic_now
119
148
  content = nil
120
149
  status = "completed"
121
150
  error = nil
122
151
  begin
123
- content = (tool_registry || @tool_registry).dispatch(tool_call, @conversation, cancellation: cancellation)
152
+ if ToolCall.name(tool_call) == Tools::GenerateImage::NAME && registry.respond_to?(:discard_generated_image)
153
+ provider = message["provider"] || message[:provider]
154
+ content = registry.dispatch(tool_call, @conversation, cancellation: cancellation, image_context: { provider: provider, turn_id: image_turn_id }) { |preview| image = preview }
155
+ else
156
+ content = registry.dispatch(tool_call, @conversation, cancellation: cancellation)
157
+ end
124
158
  rescue StandardError => e
125
159
  status = "failed"
126
160
  error = e
@@ -133,7 +167,14 @@ module Kward
133
167
  elapsed_ms = @telemetry_logger.duration_ms(tool_started_at)
134
168
  yield Events::ToolUpdate.new(tool_call: tool_call, content: content, elapsed_ms: elapsed_ms)
135
169
  yield Events::ToolResult.new(tool_call: tool_call, content: content)
170
+ if image
171
+ cancellation&.raise_if_cancelled!
172
+ yield Events::ImageReady.new(tool_call: tool_call, image: image)
173
+ image_published = true
174
+ end
136
175
  end
176
+ ensure
177
+ registry.discard_generated_image(@conversation, image.id) if image && !image_published
137
178
  end
138
179
  steered_after_tools = append_steering_events(steering_state)
139
180
  yield Events::SteeringApplied.new(count: steered_after_tools) if block_given? && steered_after_tools.positive?
@@ -216,7 +257,7 @@ module Kward
216
257
  @warning_sink ? @warning_sink.call(message) : warn(message)
217
258
  end
218
259
 
219
- def chat(on_reasoning_delta: nil, on_retry: nil, cancellation: nil, steering: nil, options: {}, tool_registry: nil)
260
+ def chat(on_reasoning_delta: nil, on_retry: nil, cancellation: nil, steering: nil, options: {}, tool_registry: nil, summary: nil)
220
261
  reasoning_delta = lambda do |delta|
221
262
  cancellation&.raise_if_cancelled!
222
263
  on_reasoning_delta&.call(delta)
@@ -232,15 +273,19 @@ module Kward
232
273
  end
233
274
  retry_callback = lambda do |retry_info|
234
275
  cancellation&.raise_if_cancelled!
276
+ summary&.retry
235
277
  event = Events::Retry.new(**retry_info)
236
278
  on_retry&.call(event)
237
279
  yield event if block_given?
238
280
  end
239
281
  registry = tool_registry || @tool_registry
282
+ provider = options[:provider] || @conversation.provider
283
+ schema_provider = provider || (@client.current_provider if @client.respond_to?(:current_provider))
284
+ schemas = registry.respond_to?(:schemas_for) ? registry.schemas_for(schema_provider) : registry.schemas
240
285
  request = {
241
286
  messages: @conversation.context_messages,
242
- tools: registry.schemas,
243
- provider: options[:provider] || @conversation.provider,
287
+ tools: schemas,
288
+ provider: provider,
244
289
  model: options[:model] || @conversation.model,
245
290
  reasoning: options[:reasoning] || @conversation.reasoning_effort,
246
291
  provider_required: @strict_provider
@@ -250,6 +295,7 @@ module Kward
250
295
  return { "role" => "assistant", "content" => hook_denied_answer(before) } if before.denied?
251
296
 
252
297
  run_hook("turn_model_request_before", payload: request)
298
+ summary&.model_request
253
299
  response = ChatInvocation.call(
254
300
  @client,
255
301
  request[:messages] || request["messages"],
@@ -267,6 +313,7 @@ module Kward
267
313
  provider_required: request[:provider_required] || request["provider_required"]
268
314
  }
269
315
  )
316
+ summary&.record(response)
270
317
  run_hook("model_response_after_parse", payload: { message: response })
271
318
  run_hook("turn_model_response_complete", payload: { message: response })
272
319
  response
@@ -19,7 +19,7 @@ module Kward
19
19
  end
20
20
 
21
21
  def one_shot_prompt_argument
22
- prompt = @argv.join(" ").strip
22
+ prompt = (@argv.first == "prompt" ? @argv[1..] : []).join(" ").strip
23
23
  prompt.empty? ? nil : prompt
24
24
  end
25
25
 
@@ -53,7 +53,7 @@ module Kward
53
53
  lines << heading.call("Examples")
54
54
  lines.concat help_examples.map { |example| " #{colored(example, :green, :bold)}" }
55
55
  lines << ""
56
- lines << "Command names take precedence. Anything else is sent as a one-shot prompt."
56
+ lines << "Use `kward prompt <text>` to run a one-shot prompt. Unknown commands are not sent to the model."
57
57
  @prompt.say lines.join("\n")
58
58
  end
59
59
 
@@ -66,9 +66,10 @@ module Kward
66
66
  ["kward init", "Install starter prompts and PRINCIPLES.md"]
67
67
  ],
68
68
  "Work" => [
69
- ["kward \"PROMPT\"", "Run a one-shot prompt"],
70
- ["kward --filter \"INSTRUCTION\"", "Filter standard input"],
69
+ ["kward prompt \"PROMPT\"", "Run a one-shot prompt"],
70
+ ["kward filter \"INSTRUCTION\"", "Filter standard input"],
71
71
  ["kward edit <filename>", "Open a file in the integrated editor"],
72
+ ["kward shell", "Start a standalone shell; use ? to ask the agent"],
72
73
  ["kward sysprompt [--raw]", "Inspect the effective system prompt"]
73
74
  ],
74
75
  "Manage" => [
@@ -94,8 +95,8 @@ module Kward
94
95
  [
95
96
  ["--working-directory=PATH", "Run Kward from PATH"],
96
97
  ["--mode=MODE", "Execution mode: auto, chat, oneshot, filter"],
97
- ["--filter", "Shortcut for --mode filter"],
98
98
  ["--skip-config", "Ignore the main config file for this run"],
99
+ ["--ignore-local-instructions", "Ignore workspace AGENTS.md files and project skills for this run"],
99
100
  ["--help, -h", "Show help"],
100
101
  ["--version, -v", "Show the installed version"]
101
102
  ]
@@ -104,9 +105,9 @@ module Kward
104
105
  def help_examples
105
106
  [
106
107
  "kward",
107
- "kward \"Explain this project\"",
108
- "git diff | kward \"Summarize the main changes\"",
109
- "echo Hello | kward --filter \"Translate to German\"",
108
+ "kward prompt \"Explain this project\"",
109
+ "git diff | kward prompt \"Summarize the main changes\"",
110
+ "echo Hello | kward filter \"Translate to German\"",
110
111
  "kward login openrouter",
111
112
  "kward edit lib/main.rb",
112
113
  "kward stats tokens today --bucket hour"
@@ -144,6 +145,16 @@ module Kward
144
145
  description: "Show or clear saved provider credentials without printing secrets.",
145
146
  examples: ["kward auth status", "kward auth status --all", "kward auth logout"]
146
147
  },
148
+ "filter" => {
149
+ usage: "kward filter <instruction>",
150
+ description: "Filter standard input according to an instruction.",
151
+ examples: ["echo Hello | kward filter \"Translate to German\""]
152
+ },
153
+ "prompt" => {
154
+ usage: "kward prompt <text>",
155
+ description: "Run a one-shot prompt.",
156
+ examples: ["kward prompt \"Explain this project\"", "git diff | kward prompt \"Review this diff\""]
157
+ },
147
158
  "init" => {
148
159
  usage: "kward init",
149
160
  description: "Install starter prompts and base PRINCIPLES.md into your config directory.",
@@ -169,6 +180,11 @@ module Kward
169
180
  description: "Open a file in the integrated editor.",
170
181
  examples: ["kward edit lib/main.rb", "kward edit ~/notes/todo.md"]
171
182
  },
183
+ "shell" => {
184
+ usage: "kward shell [-i] [shell-options] [-c command [name [args...]] | -s [args...] | file [args...]]",
185
+ description: "Run native kwsh directly in your terminal or read commands from a file or standard input. The agent loads only when you use ? in an interactive terminal; no composer is started.",
186
+ examples: ["kward shell", "kward shell -o vi", "kward shell -c 'printf \"%s\\n\" \"$PWD\"'"]
187
+ },
172
188
  "sysprompt" => {
173
189
  usage: "kward sysprompt [--raw]",
174
190
  description: "Inspect the effective system prompt for a new conversation in the current workspace.",
@@ -257,8 +273,8 @@ module Kward
257
273
  break
258
274
  when "--skip-config"
259
275
  @skip_config = true
260
- when "--filter"
261
- @requested_mode = "filter"
276
+ when "--ignore-local-instructions"
277
+ @ignore_local_instructions = true
262
278
  when "--mode"
263
279
  index += 1
264
280
  raise ArgumentError, "Missing value for --mode" if index >= arguments.length
@@ -278,7 +294,21 @@ module Kward
278
294
  end
279
295
  index += 1
280
296
  end
281
- remaining
297
+ ConfigFiles.skip_config = @skip_config
298
+ extract_plugin_startup_options(remaining)
299
+ end
300
+
301
+ def extract_plugin_startup_options(arguments)
302
+ return arguments if @prompt_delimited || arguments.none? { |argument| argument.start_with?("--") }
303
+
304
+ registry = discover_plugin_registry
305
+ arguments.reject do |argument|
306
+ next false unless registry.startup_option_for(argument)
307
+ raise ArgumentError, "Only one plugin startup option may be selected" if @startup_option_name
308
+
309
+ @startup_option_name = argument
310
+ true
311
+ end
282
312
  end
283
313
 
284
314
  def normalized_execution_mode(value)
@@ -6,7 +6,7 @@ module Kward
6
6
  module CompactionCommands
7
7
  private
8
8
 
9
- def compact_context(agent, argument)
9
+ def compact_context(agent, argument, cancellation: nil)
10
10
  before = run_lifecycle_hook("session_compact_before", conversation: agent.conversation, payload: { instructions: argument.to_s })
11
11
  if before.denied? || before.approval_required?
12
12
  runtime_output("Declined: #{before.decision.message || "session compaction denied"}")
@@ -17,16 +17,22 @@ module Kward
17
17
  conversation: agent.conversation,
18
18
  client: @client,
19
19
  tool_result_summarizer: lambda { |tool_call, content| tool_result_summary(tool_call, content) }
20
- ).compact(custom_instructions: argument)
20
+ ).compact(custom_instructions: argument, cancellation: cancellation)
21
21
  run_lifecycle_hook("session_compact_after", conversation: agent.conversation, payload: { old_message_count: result.old_message_count, new_message_count: result.new_message_count })
22
22
  runtime_output("Compacted context: #{result.old_message_count} messages -> #{result.new_message_count} messages.")
23
- render_transcript_block("Assistant", result.summary)
23
+ result.summary
24
24
  rescue Compactor::NothingToCompact, Compactor::AlreadyCompacted, Compactor::EmptySummary => e
25
25
  runtime_output(e.message)
26
+ rescue Cancellation::CancelledError
27
+ raise
26
28
  rescue StandardError => e
27
29
  runtime_output("Compaction error: #{e.message}")
28
30
  end
29
31
 
32
+ def render_compaction_summary(summary)
33
+ render_transcript_block("Assistant", summary)
34
+ end
35
+
30
36
  end
31
37
  end
32
38
  end
@@ -142,6 +142,9 @@ module Kward
142
142
  auto_summarize_memory(agent.conversation) if agent.respond_to?(:conversation) && !suppress_transcript && queued_inputs.empty? && !cancelled
143
143
  queued_inputs
144
144
  ensure
145
+ if stream_state && !suppress_transcript && !busy_replacement_agent?
146
+ print_turn_summary(stream_state.delete(:turn_summary))
147
+ end
145
148
  @prompt.finish_busy_input if @prompt.respond_to?(:finish_busy_input)
146
149
  if @prompt.respond_to?(:show_completion) && !busy_replacement_agent?
147
150
  completion = if cancelled
@@ -213,6 +216,8 @@ module Kward
213
216
 
214
217
  def handle_interactive_event(event, markdown_chunks, stream_state)
215
218
  case event
219
+ when Events::TurnSummary
220
+ stream_state[:turn_summary] = event.summary
216
221
  when Events::ReasoningDelta
217
222
  stream_state[:streamed] = true
218
223
  update_busy_activity("reasoning")
@@ -384,7 +389,9 @@ module Kward
384
389
  def run_blocking_interactive_turn(agent, input, display_input: nil, tool_registry: nil, suppress_transcript: false, on_complete: nil)
385
390
  streamed = false
386
391
  markdown_chunks = []
392
+ summary = nil
387
393
  answer = agent.ask(input, **agent_display_options(display_input, tool_registry: tool_registry)) do |event|
394
+ summary = event.summary if event.is_a?(Events::TurnSummary)
388
395
  streamed = true if !suppress_transcript && render_blocking_turn_event(event, markdown_chunks, tool_line_limit: INTERACTIVE_TOOL_OUTPUT_LINE_LIMIT)
389
396
  end
390
397
  flush_markdown_deltas(markdown_chunks) if streamed
@@ -393,6 +400,9 @@ module Kward
393
400
  auto_summarize_memory(agent.conversation) if agent.respond_to?(:conversation) && !suppress_transcript
394
401
  on_complete&.call(successful: true, cancelled: false, error: nil, answer: answer)
395
402
  []
403
+ ensure
404
+ flush_markdown_deltas(markdown_chunks) if markdown_chunks && !suppress_transcript
405
+ print_turn_summary(summary) unless suppress_transcript
396
406
  end
397
407
 
398
408
  def agent_display_options(display_input, tool_registry: nil)