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
@@ -1,11 +1,11 @@
1
1
  require "digest"
2
2
  require "securerandom"
3
3
  require "thread"
4
- require_relative "cancellation"
5
- require_relative "events"
6
- require_relative "plugin_registry"
7
- require_relative "tab_driver"
8
- require_relative "tools/tool_call"
4
+ require_relative "../cancellation"
5
+ require_relative "../events"
6
+ require_relative "registry"
7
+ require_relative "../tabs/driver"
8
+ require_relative "../tools/tool_call"
9
9
 
10
10
  # Frontend-neutral runtime for trusted plugin-owned conversational drivers.
11
11
  module Kward
@@ -21,6 +21,7 @@ module Kward
21
21
  :id,
22
22
  :type,
23
23
  :driver,
24
+ :host,
24
25
  :queue,
25
26
  :worker,
26
27
  :running_turn_id,
@@ -55,6 +56,7 @@ module Kward
55
56
  @turns = {}
56
57
  @event_listeners = []
57
58
  @mutex = Mutex.new
59
+ @shutdown = false
58
60
  end
59
61
 
60
62
  def supported_types(surface: :rpc)
@@ -79,7 +81,7 @@ module Kward
79
81
  type = supported_types(surface: surface).find { |entry| entry.id == type_id.to_s }
80
82
  raise ArgumentError, "Unknown #{surface} plugin chat: #{type_id}" unless type
81
83
 
82
- chat_for(type, scope_key: scope_key, descriptor: descriptor, workspace_root: workspace_root)
84
+ chat_for(type, surface: surface, scope_key: scope_key, descriptor: descriptor, workspace_root: workspace_root)
83
85
  end
84
86
 
85
87
  def chat(chat_id)
@@ -138,20 +140,31 @@ module Kward
138
140
  end
139
141
 
140
142
  def shutdown
141
- chats = @mutex.synchronize { @chats.values.dup }
143
+ chats = @mutex.synchronize do
144
+ return nil if @shutdown
145
+
146
+ @shutdown = true
147
+ @chats.values.dup
148
+ end
149
+ @mutex.synchronize { @turns.values.dup }.each { |turn| turn.cancellation.cancel! }
142
150
  chats.each do |chat|
143
151
  chat.queue << WORKER_STOP if chat.worker&.alive?
144
152
  chat.worker&.join(0.2)
153
+ close_chat(chat)
145
154
  end
155
+ @plugin_registry&.shutdown! unless @plugin_registry_provider
146
156
  nil
147
157
  end
148
158
 
149
159
  # Converts normalized image attachment hashes into the input shape accepted
150
160
  # by plugin chat drivers. RPC and transport frontends can normalize their
151
161
  # own boundary formats before calling this helper.
152
- def input_with_attachments(input, attachments)
162
+ def input_with_attachments(input, attachments, capabilities: PluginChatCapabilities.legacy)
153
163
  attachments = Array(attachments)
154
164
  return input.to_s if attachments.empty?
165
+ if capabilities.declared? && !capabilities.allows_attachment?(:image)
166
+ raise ArgumentError, "plugin chat does not allow image attachments"
167
+ end
155
168
 
156
169
  [{ type: "text", text: input.to_s }] + attachments.map do |attachment|
157
170
  {
@@ -166,30 +179,49 @@ module Kward
166
179
  private
167
180
 
168
181
  def plugin_registry
169
- return @plugin_registry_provider.call if @plugin_registry_provider
170
-
171
- @plugin_registry ||= PluginRegistry.load
182
+ registry = @plugin_registry_provider ? @plugin_registry_provider.call : (@plugin_registry ||= PluginRegistry.load)
183
+ registry.start!
184
+ registry
172
185
  end
173
186
 
174
- def chat_for(type, scope_key:, descriptor:, workspace_root:)
187
+ def chat_for(type, surface:, scope_key:, descriptor:, workspace_root:)
188
+ surface = surface.to_sym
189
+ host_surface = type.rpc && type.transport ? :shared : surface
175
190
  scope_key = normalize_scope_key(scope_key)
191
+ scope_key = "global" if type.singleton == :global && type.capabilities.declared?
176
192
  chat_id = chat_id_for(type, scope_key)
177
193
  @mutex.synchronize do
178
194
  @chats[chat_id] ||= begin
179
195
  descriptor = {
180
196
  "kind" => "plugin",
181
- "plugin_tab_type" => type.id,
182
- "label" => type.title,
183
- "scope_key" => scope_key
197
+ "label" => type.title
184
198
  }.merge(descriptor.transform_keys(&:to_s))
185
- host = PluginTabHost.new(client: @client, workspace_root: workspace_root)
186
- driver = type.handler.call(host, descriptor)
187
- raise "Plugin chat #{type.id.inspect} did not return a tab driver." unless driver
199
+ descriptor["plugin_tab_type"] = type.id
200
+ descriptor["scope_key"] = scope_key
201
+ host = PluginTabHost.new(
202
+ client: @client,
203
+ workspace_root: workspace_root,
204
+ plugin_host: type.plugin_id && plugin_registry.plugin_for(type.plugin_id),
205
+ type_id: type.id,
206
+ surface: host_surface,
207
+ scope_key: scope_key,
208
+ capabilities: type.capabilities
209
+ )
210
+ begin
211
+ driver = type.handler.call(host, descriptor)
212
+ raise "Plugin chat #{type.id.inspect} did not return a tab driver." unless driver
213
+
214
+ type.capabilities.validate_driver!(driver)
215
+ rescue StandardError
216
+ host.shutdown
217
+ raise
218
+ end
188
219
 
189
220
  Chat.new(
190
221
  id: chat_id,
191
222
  type: type,
192
223
  driver: driver,
224
+ host: host,
193
225
  queue: Queue.new,
194
226
  scope_key: scope_key,
195
227
  descriptor: descriptor,
@@ -199,6 +231,18 @@ module Kward
199
231
  end
200
232
  end
201
233
 
234
+ def close_chat(chat)
235
+ if chat.driver.respond_to?(:close)
236
+ chat.driver.close
237
+ elsif chat.driver.respond_to?(:shutdown)
238
+ chat.driver.shutdown
239
+ end
240
+ rescue StandardError => e
241
+ ConfigFiles.emit_warning("Warning: Kward plugin chat cleanup error: #{e.message}")
242
+ ensure
243
+ chat.host.shutdown
244
+ end
245
+
202
246
  def normalize_scope_key(scope_key)
203
247
  value = scope_key.to_s
204
248
  value.empty? ? "default" : value
@@ -0,0 +1,73 @@
1
+ require "securerandom"
2
+ require_relative "../model/client"
3
+
4
+ module Kward
5
+ # Adapts Kward's normal Codex provider stream to the plugin Responses event
6
+ # contract without exposing the configured credentials.
7
+ class PluginCodexResponses
8
+ class AuthenticationError < StandardError; end
9
+
10
+ class RequestError < StandardError
11
+ attr_reader :status
12
+
13
+ def initialize(status)
14
+ @status = status.to_i
15
+ super("Codex request failed (HTTP #{@status})")
16
+ end
17
+ end
18
+
19
+ def initialize(client: Kward::Client.new)
20
+ @client = client
21
+ end
22
+
23
+ # Streams Kward Codex events using the normal configured Codex credentials
24
+ # and endpoint, translating them to Responses-shaped events for plugins.
25
+ def stream(model:, input:, instructions: nil, text: nil, max_output_tokens: nil, cancellation: nil)
26
+ messages = input_messages(input, instructions)
27
+ output_text = +""
28
+ emit_text = lambda do |delta|
29
+ next unless delta.is_a?(String) && !delta.empty?
30
+
31
+ output_text << delta
32
+ yield "type" => "response.output_text.delta", "delta" => delta
33
+ end
34
+
35
+ result = @client.chat(
36
+ messages,
37
+ provider: "codex",
38
+ provider_required: true,
39
+ model: model,
40
+ max_tokens: max_output_tokens,
41
+ text_format: text,
42
+ cancellation: cancellation,
43
+ on_assistant_delta: emit_text
44
+ )
45
+ emit_text.call(result["content"]) if output_text.empty? && result["content"].is_a?(String)
46
+ yield "type" => "response.completed", "response" => { "id" => "codex-#{SecureRandom.hex(12)}", "usage" => result["usage"] }
47
+ nil
48
+ rescue Kward::Client::AuthenticationError => error
49
+ raise AuthenticationError, error.message
50
+ rescue Kward::Client::RequestError => error
51
+ raise RequestError, error.code
52
+ end
53
+
54
+ private
55
+
56
+ def input_messages(input, instructions)
57
+ raise ArgumentError, "Codex input must be an array of messages" unless input.is_a?(Array)
58
+
59
+ messages = []
60
+ messages << { role: "system", content: instructions } if instructions.is_a?(String) && !instructions.empty?
61
+ input.each_with_index do |item, index|
62
+ role = item["role"] || item[:role] if item.is_a?(Hash)
63
+ content = item.key?("content") ? item["content"] : item[:content] if item.is_a?(Hash)
64
+ unless %w[user assistant].include?(role) && content.is_a?(String)
65
+ raise ArgumentError, "Codex input message #{index} must have a supported role and string content"
66
+ end
67
+
68
+ messages << { role: role, content: content }
69
+ end
70
+ messages
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,248 @@
1
+ require "digest"
2
+ require "json"
3
+ require "logger"
4
+ require "thread"
5
+ require_relative "../config_files"
6
+ require_relative "../deep_copy"
7
+ require_relative "../private_file"
8
+ require_relative "resources"
9
+ require_relative "http_server"
10
+ require_relative "codex_responses"
11
+
12
+ # Namespace for the Kward CLI agent runtime.
13
+ module Kward
14
+ # Private JSON-backed key/value storage scoped to one stable plugin ID.
15
+ class PluginStore
16
+ KEY_PATTERN = /\A[A-Za-z0-9][A-Za-z0-9:._-]*\z/.freeze
17
+
18
+ attr_reader :plugin_id
19
+
20
+ def initialize(plugin_id, root: ConfigFiles.config_dir)
21
+ @plugin_id = validate_key(plugin_id, "plugin id")
22
+ @path = File.join(File.expand_path(root), "plugin_state", @plugin_id, "state.json")
23
+ @mutex = Mutex.new
24
+ @values = load_state
25
+ end
26
+
27
+ def get(key)
28
+ key = validate_key(key, "storage key")
29
+ @mutex.synchronize { copy(@values[key]) }
30
+ end
31
+
32
+ def put(key, value)
33
+ key = validate_key(key, "storage key")
34
+ @mutex.synchronize do
35
+ @values[key] = copy(value)
36
+ persist
37
+ end
38
+ value
39
+ end
40
+
41
+ def delete(key)
42
+ key = validate_key(key, "storage key")
43
+ @mutex.synchronize do
44
+ present = @values.key?(key)
45
+ value = @values.delete(key)
46
+ persist if present
47
+ copy(value)
48
+ end
49
+ end
50
+
51
+ # Returns a view whose keys cannot overlap another plugin-owned scope.
52
+ def scoped(namespace)
53
+ PluginScopedStore.new(self, namespace)
54
+ end
55
+
56
+ private
57
+
58
+ def load_state
59
+ return {} unless File.file?(@path)
60
+
61
+ state = JSON.parse(File.read(@path))
62
+ values = state.fetch("values", {})
63
+ raise JSON::ParserError, "plugin state values must be a JSON object" unless values.is_a?(Hash)
64
+
65
+ values
66
+ rescue JSON::ParserError => e
67
+ raise "Invalid plugin state #{@path}: #{e.message}"
68
+ end
69
+
70
+ def persist
71
+ PrivateFile.write_json(@path, "values" => @values)
72
+ end
73
+
74
+ def validate_key(value, name)
75
+ value = value.to_s
76
+ raise ArgumentError, "#{name} is required" unless value.match?(KEY_PATTERN)
77
+
78
+ value
79
+ end
80
+
81
+ def copy(value)
82
+ return nil if value.nil?
83
+
84
+ DeepCopy.dup(value)
85
+ end
86
+ end
87
+
88
+ # Namespaced view over an identified plugin's durable storage.
89
+ class PluginScopedStore
90
+ attr_reader :namespace
91
+
92
+ def initialize(storage, namespace)
93
+ @storage = storage
94
+ @namespace = namespace.to_s
95
+ raise ArgumentError, "plugin storage namespace is required" if @namespace.empty?
96
+
97
+ @prefix = "scope.#{Digest::SHA256.hexdigest(@namespace)[0, 24]}"
98
+ end
99
+
100
+ def get(key)
101
+ @storage.get(scoped_key(key))
102
+ end
103
+
104
+ def put(key, value)
105
+ @storage.put(scoped_key(key), value)
106
+ end
107
+
108
+ def delete(key)
109
+ @storage.delete(scoped_key(key))
110
+ end
111
+
112
+ private
113
+
114
+ def scoped_key(key)
115
+ key = key.to_s
116
+ raise ArgumentError, "storage key is required" unless key.match?(PluginStore::KEY_PATTERN)
117
+
118
+ "#{@prefix}.#{key}"
119
+ end
120
+ end
121
+
122
+ # Shared immutable metadata and managed services for one identified plugin.
123
+ class PluginHost
124
+ ID_PATTERN = /\A[A-Za-z0-9][A-Za-z0-9._-]*\z/.freeze
125
+
126
+ class LogDevice
127
+ def write(message)
128
+ ConfigFiles.emit_warning(message.to_s.chomp)
129
+ end
130
+
131
+ def close
132
+ nil
133
+ end
134
+ end
135
+ private_constant :LogDevice
136
+
137
+ attr_reader :id, :version, :api_version, :source_path, :config, :storage, :logger
138
+
139
+ def initialize(id:, version:, api_version:, source_path: nil, config: nil, storage: nil, logger: nil, env: ENV, storage_root: ConfigFiles.config_dir, warning_sink: nil)
140
+ @id = validate_id(id).freeze
141
+ @version = validate_value(version, "plugin version").freeze
142
+ @api_version = validate_value(api_version, "plugin API version").freeze
143
+ @source_path = source_path&.to_s&.freeze
144
+ @config = freeze_config(config.nil? ? configured_values : config)
145
+ @storage = storage || PluginStore.new(@id, root: storage_root)
146
+ @logger = logger || default_logger
147
+ @env = env
148
+ @resources = PluginResources.new(name: "Kward plugin #{id}", warning_sink: warning_sink)
149
+ end
150
+
151
+ # Starts cooperative background work owned by this plugin. The block may
152
+ # accept a cancellation token and must stop cooperatively when cancelled.
153
+ #
154
+ # @return [PluginTask]
155
+ def background(name: nil, cancellation: nil, &block)
156
+ @resources.background(name: name, cancellation: cancellation, &block)
157
+ end
158
+
159
+ # Streams Responses-shaped events through Kward's normal Codex provider
160
+ # client without exposing the configured credentials to plugin code.
161
+ def codex_responses
162
+ @codex_responses ||= PluginCodexResponses.new
163
+ end
164
+
165
+ # Creates a loopback-only HTTP listener owned by this plugin. The listener
166
+ # is stopped automatically during plugin reload or shutdown.
167
+ def http_server(host: "127.0.0.1", port: 0, max_body_bytes: PluginHTTPServer::DEFAULT_MAX_BODY_BYTES, request_timeout: PluginHTTPServer::DEFAULT_REQUEST_TIMEOUT, max_clients: 8, &handler)
168
+ server = PluginHTTPServer.new(host: host, port: port, max_body_bytes: max_body_bytes, request_timeout: request_timeout, max_clients: max_clients, &handler)
169
+ on_cleanup(server) { |resource| resource.stop }
170
+ server
171
+ end
172
+
173
+ # Registers idempotent cleanup for a subscription or other plugin resource.
174
+ # The returned disposable may be invoked early; otherwise Kward invokes it
175
+ # during plugin reload or shutdown.
176
+ #
177
+ # @return [PluginDisposable]
178
+ def on_cleanup(resource = nil, &block)
179
+ @resources.on_cleanup(resource, &block)
180
+ end
181
+
182
+ alias manage on_cleanup
183
+
184
+ # Activates managed runtime services after plugin loading completes.
185
+ # @api private
186
+ def activate!
187
+ @resources.activate!
188
+ self
189
+ end
190
+
191
+ # Cancels background work and invokes registered cleanup callbacks.
192
+ # @api private
193
+ def shutdown(timeout: PluginResources::DEFAULT_SHUTDOWN_TIMEOUT)
194
+ @resources.shutdown(timeout: timeout)
195
+ self
196
+ end
197
+
198
+ # Reads a secret from private plugin config, an explicit environment
199
+ # variable, or the plugin's conventional KWARD_PLUGIN_* variable.
200
+ def secret(key, env: nil)
201
+ key = validate_value(key, "secret key")
202
+ value = config[key]
203
+ value = @env[env.to_s] if value.nil? && env
204
+ value = @env[default_secret_env_name(key)] if value.nil?
205
+ value.to_s unless value.nil?
206
+ end
207
+
208
+ # Returns public metadata suitable for diagnostics and capability reports.
209
+ def to_h
210
+ { id: id, version: version, api_version: api_version }.freeze
211
+ end
212
+
213
+ private
214
+
215
+ def configured_values
216
+ ConfigFiles.plugin_config(@id)
217
+ end
218
+
219
+ def freeze_config(value)
220
+ raise ArgumentError, "Kward plugin config for #{@id} must be an object" unless value.is_a?(Hash)
221
+
222
+ DeepCopy.freeze(DeepCopy.dup(value))
223
+ end
224
+
225
+ def validate_id(value)
226
+ value = value.to_s
227
+ raise ArgumentError, "plugin id is invalid: #{value}" unless value.match?(ID_PATTERN)
228
+
229
+ value
230
+ end
231
+
232
+ def validate_value(value, name)
233
+ value = value.to_s
234
+ raise ArgumentError, "#{name} is required" if value.empty?
235
+
236
+ value
237
+ end
238
+
239
+ def default_secret_env_name(key)
240
+ parts = [id, key].map { |part| part.gsub(/[^A-Za-z0-9]/, "_").upcase }
241
+ "KWARD_PLUGIN_#{parts.join("_")}"
242
+ end
243
+
244
+ def default_logger
245
+ Logger.new(LogDevice.new).tap { |logger| logger.progname = "Kward plugin #{id}" }
246
+ end
247
+ end
248
+ end
@@ -0,0 +1,83 @@
1
+ require "ipaddr"
2
+ require "webrick"
3
+
4
+ module Kward
5
+ # Small, plugin-owned HTTP listener constrained to loopback.
6
+ class PluginHTTPServer
7
+ DEFAULT_MAX_BODY_BYTES = 1_048_576
8
+ DEFAULT_REQUEST_TIMEOUT = 30
9
+
10
+ attr_reader :host, :requested_port
11
+
12
+ def initialize(host: "127.0.0.1", port: 0, max_body_bytes: DEFAULT_MAX_BODY_BYTES, request_timeout: DEFAULT_REQUEST_TIMEOUT, max_clients: 8, &handler)
13
+ raise ArgumentError, "Plugin HTTP server requires a handler" unless handler
14
+ raise ArgumentError, "Plugin HTTP server must bind to loopback" unless IPAddr.new(host).loopback?
15
+ raise ArgumentError, "Plugin HTTP server port must be between 0 and 65535" unless Integer(port).between?(0, 65_535)
16
+ raise ArgumentError, "Plugin HTTP server body limit must be positive" unless Integer(max_body_bytes).positive?
17
+ raise ArgumentError, "Plugin HTTP server request timeout must be positive" unless Float(request_timeout).positive?
18
+ raise ArgumentError, "Plugin HTTP server client limit must be positive" unless Integer(max_clients).positive?
19
+
20
+ @host = host
21
+ @requested_port = Integer(port)
22
+ @handler = handler
23
+ @server = WEBrick::HTTPServer.new(
24
+ BindAddress: host,
25
+ Port: @requested_port,
26
+ MaxReqBytes: Integer(max_body_bytes),
27
+ RequestTimeout: Float(request_timeout),
28
+ MaxClients: Integer(max_clients),
29
+ AccessLog: [],
30
+ Logger: WEBrick::Log.new(File::NULL)
31
+ )
32
+ @thread = nil
33
+ @mutex = Mutex.new
34
+ end
35
+
36
+ def start
37
+ @mutex.synchronize do
38
+ return self if @thread&.alive?
39
+
40
+ @server.mount_proc("/") { |request, response| @handler.call(request, response) }
41
+ @thread = Thread.new { @server.start }
42
+ @thread.report_on_exception = false
43
+ end
44
+ wait_until_ready
45
+ self
46
+ end
47
+
48
+ def wait
49
+ @thread&.join
50
+ end
51
+
52
+ def stop
53
+ thread = @mutex.synchronize do
54
+ current = @thread
55
+ @server.shutdown if current&.alive?
56
+ @thread = nil
57
+ current
58
+ end
59
+ thread&.join(2)
60
+ self
61
+ end
62
+
63
+ def port
64
+ @port || requested_port
65
+ end
66
+
67
+ private
68
+
69
+ def wait_until_ready
70
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2
71
+ loop do
72
+ if @server.status == :Running
73
+ @port = @server.listeners.first&.addr&.[](1) || requested_port
74
+ return
75
+ end
76
+ raise @thread.value unless @thread.alive?
77
+ raise "Plugin HTTP server did not start" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
78
+
79
+ sleep 0.01
80
+ end
81
+ end
82
+ end
83
+ end