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,1229 @@
1
+ require_relative "../config_files"
2
+ require_relative "../deep_copy"
3
+ require_relative "../hooks"
4
+ require_relative "../transport"
5
+ require_relative "actions"
6
+ require_relative "chat_contract"
7
+ require_relative "host"
8
+ require_relative "ui"
9
+ require_relative "turn_request"
10
+
11
+ # Namespace for the Kward CLI agent runtime.
12
+ module Kward
13
+ # Loads trusted user plugin files and provides the plugin DSL.
14
+ #
15
+ # Plugins live in the user plugin directory, run as local Ruby code, and can
16
+ # register slash commands, namespaced actions, model-callable tools, lifecycle
17
+ # callbacks, composable status renderers, prompt context, and live
18
+ # transcript-event observers for CLI and RPC frontends.
19
+ #
20
+ # This registry is intentionally trust-based, not a sandbox. Keep plugin loading
21
+ # restricted to `ConfigFiles.plugin_paths`, keep workspace-local code out of the
22
+ # load path, and expose immutable transcript views so plugins can observe state
23
+ # without corrupting active conversations.
24
+ class PluginRegistry
25
+ PLUGIN_API_VERSION = "1"
26
+ COMMAND_NAME_PATTERN = /\A[A-Za-z0-9][A-Za-z0-9_-]*\z/.freeze
27
+
28
+ # Public registration types retained under the registry namespace.
29
+ Command = PluginCommand
30
+ Action = PluginAction
31
+
32
+ # Registered model-callable tool exposed through each normal agent tool
33
+ # registry. The handler receives parsed arguments and a runtime context.
34
+ Tool = Struct.new(:name, :description, :schema, :path, :handler, keyword_init: true)
35
+
36
+ # A plugin-owned top-level mode selected by a declared CLI switch.
37
+ StartupOption = Struct.new(:name, :description, :plugin_id, :path, :handler, keyword_init: true)
38
+
39
+ STATUS_PRIORITIES = { low: 0, normal: 1, high: 2 }.freeze
40
+ STATUS_SEPARATOR = " · "
41
+
42
+ # Registered footer/status contribution. Display order is independent from
43
+ # priority: order places segments, while priority decides which segments are
44
+ # removed first when the terminal is narrow.
45
+ Status = Struct.new(:id, :order, :priority, :path, :renderer, :sequence, keyword_init: true)
46
+
47
+ # Rendered, frontend-neutral status contribution.
48
+ StatusSegment = Struct.new(:id, :text, :tooltip, :priority, :order, keyword_init: true) do
49
+ def to_h
50
+ { id: id, text: text, tooltip: tooltip, priority: priority.to_s, order: order }.compact
51
+ end
52
+ end
53
+
54
+ # Registered interactive command that takes over the composer region with a
55
+ # Kward-driven render and input loop. Like a slash command but with canvas
56
+ # rendering capabilities for games, dashboards, viewers, and similar uses.
57
+ InteractiveCommand = Struct.new(:name, :description, :argument_hint, :rows, :fps, :path, :handler, keyword_init: true) do
58
+ def entry
59
+ { name: name, description: description, argument_hint: argument_hint }
60
+ end
61
+ end
62
+
63
+ # Registered plugin-owned tab runtime. Its factory receives a
64
+ # `PluginTabHost` and its persisted descriptor, then returns a driver.
65
+ TabType = Struct.new(:id, :name, :title, :singleton, :rpc, :transport, :local, :transcript_events, :capabilities, :plugin_id, :path, :handler, keyword_init: true)
66
+
67
+ # Registered external transport. The factory receives a transport host and
68
+ # configuration when the transport is started, not while plugins load.
69
+ TransportType = Struct.new(:id, :name, :capabilities, :execution_profile, :path, :handler, keyword_init: true)
70
+
71
+ # Read-only event passed to plugin transcript observers.
72
+ TranscriptEvent = Struct.new(:type, :payload, keyword_init: true) do
73
+ def to_h
74
+ { type: type, payload: payload }
75
+ end
76
+ end
77
+
78
+ # Registered lifecycle hook handler.
79
+ HookHandler = Struct.new(:event, :id, :description, :path, :order, :match, :failure_policy, :handler, keyword_init: true)
80
+
81
+ # Plugin-runtime callback invoked when an identified plugin starts, reloads,
82
+ # or shuts down.
83
+ LifecycleHandler = Struct.new(:event, :host, :path, :handler, keyword_init: true)
84
+
85
+ # Read-only transcript view exposed to plugin code.
86
+ class Transcript
87
+ # Creates an object for trusted plugin loading and dispatch.
88
+ def initialize(conversation)
89
+ @conversation = conversation
90
+ end
91
+
92
+ # Returns a deep-frozen copy of the active conversation messages.
93
+ #
94
+ # @return [Array<Hash>] immutable transcript message data
95
+ def messages
96
+ DeepCopy.freeze(DeepCopy.dup(@conversation.messages))
97
+ end
98
+ end
99
+
100
+ # Runtime context passed to plugin commands, tools, footers, prompt context
101
+ # renderers, hooks, and transcript event handlers.
102
+ class Context
103
+ attr_reader :args, :workspace_root, :cancellation, :ui, :requested_turn
104
+
105
+ # Creates an object for trusted plugin loading and dispatch.
106
+ def initialize(conversation:, args: "", session: nil, workspace_root: Dir.pwd, say_callback: nil, cancellation: nil, ui: nil, tool_ui: nil, turn_command: nil)
107
+ @conversation = conversation
108
+ @args = args.is_a?(Hash) ? DeepCopy.freeze(DeepCopy.dup(args)) : args.to_s
109
+ @session = session
110
+ @workspace_root = workspace_root
111
+ @say_callback = say_callback
112
+ @cancellation = cancellation
113
+ @ui = (ui || PluginUI.new(say_callback: say_callback)).with_cancellation(cancellation)
114
+ @tool_ui = tool_ui
115
+ @turn_command = turn_command
116
+ end
117
+
118
+ # Whether this command runs on a host that can execute a session turn.
119
+ def turn_requests_supported?
120
+ !@turn_command.nil?
121
+ end
122
+
123
+ # Stages one turn for dispatch after the command successfully returns.
124
+ # Available only to asynchronous, session-backed plugin commands.
125
+ # @return [nil]
126
+ def request_turn(system:)
127
+ raise ArgumentError, "Model turn requests are unavailable here; use a session command through the TUI or RPC turns/start" unless turn_requests_supported?
128
+ @cancellation&.raise_if_cancelled!
129
+ raise ArgumentError, "Only one model turn may be requested per command" if @requested_turn
130
+
131
+ @requested_turn = PluginTurnRequest.new(system: system, command: @turn_command.name, plugin_id: @turn_command.plugin_id)
132
+ nil
133
+ end
134
+
135
+ # @return [Transcript] read-only transcript wrapper
136
+ def transcript
137
+ Transcript.new(@conversation)
138
+ end
139
+
140
+ # Emits command output to the active frontend when available.
141
+ #
142
+ # @param message [#to_s] message to display
143
+ # @return [nil]
144
+ def say(message)
145
+ @say_callback&.call(message.to_s)
146
+ nil
147
+ end
148
+
149
+ # @return [String, nil] active session identifier
150
+ def session_id
151
+ @session&.id
152
+ end
153
+
154
+ # @return [String, nil] human-readable active session name
155
+ def session_name
156
+ @session&.name
157
+ end
158
+
159
+ # @return [String, nil] saved active session path
160
+ def session_path
161
+ @session&.path
162
+ end
163
+
164
+ # Requests that the conversation rebuild its system message after plugin
165
+ # state changes that affect prompt context.
166
+ #
167
+ # @return [nil]
168
+ def refresh_system_message!
169
+ @conversation.refresh_system_message! if @conversation.respond_to?(:refresh_system_message!)
170
+ nil
171
+ end
172
+
173
+ # Builds a structured result for a typed command or plugin action.
174
+ #
175
+ # @param message [#to_s, nil] optional user-facing result text
176
+ # @param data [Object, nil] optional JSON-compatible machine-readable data
177
+ # @return [PluginResult]
178
+ def result(message: nil, data: nil)
179
+ PluginResult.new(message: message, data: data)
180
+ end
181
+
182
+ # Returns whether the active plugin operation has been cancelled.
183
+ # Contexts without a cancellable operation return false.
184
+ def cancelled?
185
+ @cancellation&.cancelled? == true
186
+ end
187
+
188
+ # Builds a fresh context for one model-callable plugin tool invocation.
189
+ # @api private
190
+ def for_tool(conversation:, cancellation: nil)
191
+ self.class.new(
192
+ conversation: conversation,
193
+ session: @session,
194
+ workspace_root: @workspace_root,
195
+ say_callback: @say_callback,
196
+ cancellation: cancellation,
197
+ ui: @tool_ui || @ui
198
+ )
199
+ end
200
+
201
+ # Allows the current lifecycle event to continue.
202
+ # @return [Hooks::Decision]
203
+ def allow(message = nil, metadata: nil)
204
+ Hooks::Decision.allow(message, metadata: metadata)
205
+ end
206
+
207
+ # Denies the current lifecycle event.
208
+ # @return [Hooks::Decision]
209
+ def deny(message = nil, metadata: nil)
210
+ Hooks::Decision.deny(message, metadata: metadata)
211
+ end
212
+
213
+ # Requests frontend approval for the current lifecycle event.
214
+ # @return [Hooks::Decision]
215
+ def ask(message = nil, metadata: nil)
216
+ Hooks::Decision.ask(message, metadata: metadata)
217
+ end
218
+
219
+ # Continues with an event-specific payload replacement.
220
+ # @param payload [Hash] replacement fields supported by the event
221
+ # @return [Hooks::Decision]
222
+ def modify(payload, message: nil, metadata: nil)
223
+ Hooks::Decision.modify(payload, message: message, metadata: metadata)
224
+ end
225
+
226
+ # Allows the event while recording a warning.
227
+ # @return [Hooks::Decision]
228
+ def warn(message = nil, metadata: nil)
229
+ Hooks::Decision.warn(message, metadata: metadata)
230
+ end
231
+
232
+ # Requests a retry when the current event supports it.
233
+ # @return [Hooks::Decision]
234
+ def retry(message = nil, payload: nil, metadata: nil)
235
+ Hooks::Decision.retry(message, payload: payload, metadata: metadata)
236
+ end
237
+
238
+ # Defers the event when the current workflow supports it.
239
+ # @return [Hooks::Decision]
240
+ def defer(message = nil, payload: nil, metadata: nil)
241
+ Hooks::Decision.defer(message, payload: payload, metadata: metadata)
242
+ end
243
+ end
244
+
245
+ # Public DSL object yielded by `Kward.plugin` blocks.
246
+ #
247
+ # Plugin files normally interact with this object only through a block:
248
+ #
249
+ # @example Register a plugin command
250
+ # Kward.plugin do |plugin|
251
+ # plugin.command "hello", description: "Say hello" do |args, ctx|
252
+ # name = args.strip.empty? ? "there" : args.strip
253
+ # ctx.say "Hello, #{name}."
254
+ # end
255
+ # end
256
+ #
257
+ # @api public
258
+ class DSL
259
+ # Creates an object for trusted plugin loading and dispatch.
260
+ def initialize(registry, path, host: nil)
261
+ @registry = registry
262
+ @path = path
263
+ @host = host
264
+ end
265
+
266
+ # Shared metadata, configuration, storage, secrets, and logging services.
267
+ # Legacy plugins without declared identity return nil.
268
+ #
269
+ # @return [PluginHost, nil]
270
+ attr_reader :host
271
+
272
+ # Registers a slash command.
273
+ #
274
+ # The command is available in the interactive CLI and through the RPC
275
+ # command bridge. Command names do not include the leading `/`.
276
+ #
277
+ # @param name [String, #to_s] command name without the leading slash
278
+ # @param description [String] short text shown in command listings
279
+ # @param argument_hint [String] optional usage hint for arguments
280
+ # @param schema [Hash, nil] strict object JSON Schema for typed arguments
281
+ # @param positionals [Array<String, Symbol>] schema properties filled by positional text
282
+ # @yieldparam args [String, Hash] raw text for legacy commands or parsed typed arguments
283
+ # @yieldparam ctx [Context] plugin execution context
284
+ # @return [void]
285
+ # @api public
286
+ def command(name, description: "", argument_hint: "", schema: nil, positionals: [], &block)
287
+ @registry.register_command(
288
+ name,
289
+ description: description,
290
+ argument_hint: argument_hint,
291
+ schema: schema,
292
+ positionals: positionals,
293
+ plugin_id: @host&.id,
294
+ path: @path,
295
+ &block
296
+ )
297
+ end
298
+
299
+ # Registers a namespaced typed action for trusted RPC clients.
300
+ # Identified plugin metadata is required so the action has a stable ID.
301
+ #
302
+ # @param name [String, #to_s] action name within the plugin namespace
303
+ # @param description [String] short client-facing description
304
+ # @param schema [Hash] strict object JSON Schema for typed arguments
305
+ # @yieldparam args [Hash] validated action arguments
306
+ # @yieldparam ctx [Context] plugin execution context
307
+ # @return [void]
308
+ # @api public
309
+ def action(name, description:, schema: { type: "object", properties: {} }, &block)
310
+ raise ArgumentError, "Plugin actions require stable plugin identity" unless @host
311
+
312
+ @registry.register_action(name, plugin_id: @host.id, description: description, schema: schema, path: @path, &block)
313
+ end
314
+
315
+ # Registers a model-callable tool for normal Kward agent turns.
316
+ #
317
+ # Tool arguments are described with a strict object JSON Schema. The
318
+ # handler must return model-facing text and receives the normal plugin
319
+ # context with the active cancellation token.
320
+ #
321
+ # @param name [String, #to_s] function name exposed to the model
322
+ # @param description [String] model-facing description of the operation
323
+ # @param schema [Hash] object JSON Schema for parsed tool arguments
324
+ # @yieldparam args [Hash] parsed model-provided arguments
325
+ # @yieldparam ctx [Context] plugin execution context
326
+ # @return [void]
327
+ # @api public
328
+ def tool(name, description:, schema: { type: "object", properties: {} }, &block)
329
+ @registry.register_tool(name, description: description, schema: schema, path: @path, &block)
330
+ end
331
+
332
+ # Registers a callback invoked after plugin loading when the runtime is
333
+ # ready to start owned background work.
334
+ #
335
+ # @yieldparam host [PluginHost] identified plugin host and resource owner
336
+ # @return [void]
337
+ # @api public
338
+ def on_start(&block)
339
+ register_lifecycle(:start, &block)
340
+ end
341
+
342
+ # Registers a callback invoked on the old plugin instance immediately
343
+ # before its resources are cleaned up during reload.
344
+ #
345
+ # @yieldparam host [PluginHost] identified plugin host and resource owner
346
+ # @return [void]
347
+ # @api public
348
+ def on_reload(&block)
349
+ register_lifecycle(:reload, &block)
350
+ end
351
+
352
+ # Registers a callback invoked immediately before plugin resources are
353
+ # cleaned up during process shutdown.
354
+ #
355
+ # @yieldparam host [PluginHost] identified plugin host and resource owner
356
+ # @return [void]
357
+ # @api public
358
+ def on_shutdown(&block)
359
+ register_lifecycle(:shutdown, &block)
360
+ end
361
+
362
+ # Registers a legacy footer contribution. Multiple plugin footers are
363
+ # composed rather than replacing one another. Identified plugins should
364
+ # prefer {#status} so clients receive a descriptive stable segment ID.
365
+ #
366
+ # @yieldparam ctx [Context] plugin execution context
367
+ # @return [void]
368
+ # @api public
369
+ def footer(&block)
370
+ @registry.register_footer(plugin_id: @host&.id, path: @path, &block)
371
+ end
372
+
373
+ # Registers a composable status contribution.
374
+ #
375
+ # The renderer may return a string, nil to hide the segment, or a hash with
376
+ # `text` and optional `tooltip`. Lower order values render first. On narrow
377
+ # terminals low-priority segments are removed before normal- and
378
+ # high-priority segments.
379
+ #
380
+ # @param name [String, #to_s] stable name within the plugin namespace
381
+ # @param order [Integer] display order; lower values render first
382
+ # @param priority [Symbol, String] `low`, `normal`, or `high`
383
+ # @yieldparam ctx [Context] plugin execution context
384
+ # @return [void]
385
+ # @api public
386
+ def status(name, order: 100, priority: :normal, &block)
387
+ raise ArgumentError, "Plugin status contributions require stable plugin identity" unless @host
388
+
389
+ @registry.register_status(
390
+ name,
391
+ plugin_id: @host.id,
392
+ order: order,
393
+ priority: priority,
394
+ path: @path,
395
+ &block
396
+ )
397
+ end
398
+
399
+ # Registers a live transcript event observer.
400
+ #
401
+ # Observer errors are caught and reported as warnings so a plugin cannot
402
+ # crash the active turn by raising from an event handler.
403
+ #
404
+ # @yieldparam event [TranscriptEvent] normalized transcript event
405
+ # @yieldparam ctx [Context] plugin execution context
406
+ # @return [void]
407
+ # @api public
408
+ def on_transcript_event(&block)
409
+ @registry.register_transcript_event(path: @path, &block)
410
+ end
411
+
412
+ # Registers a lifecycle hook handler.
413
+ #
414
+ # Hooks are deterministic runtime callbacks around Kward lifecycle events.
415
+ # They can return a {Hooks::Decision}, a decision hash, a decision string,
416
+ # or nil to allow the operation.
417
+ #
418
+ # @param event [String, #to_s] lifecycle event name
419
+ # @param id [String, nil] stable hook identifier for logs and diagnostics
420
+ # @param description [String] short human-readable purpose
421
+ # @param order [Integer] lower values run first
422
+ # @param match [Hash, nil] optional event selector
423
+ # @yieldparam event [Hooks::Event] immutable lifecycle event
424
+ # @yieldparam ctx [Context] plugin execution context and decision helpers
425
+ # @return [void]
426
+ # @api public
427
+ def hook(event, id: nil, description: "", order: 100, match: nil, failure_policy: nil, &block)
428
+ @registry.register_hook(event, id: id, description: description, order: order, match: match, failure_policy: failure_policy, path: @path, &block)
429
+ end
430
+
431
+ # Registers prompt context text injected into future system prompts.
432
+ #
433
+ # Keep this text short and never include secrets. The returned string can
434
+ # be sent to the active model as part of Kward's system instructions.
435
+ #
436
+ # @yieldparam ctx [Context] plugin execution context
437
+ # @return [void]
438
+ # @api public
439
+ def prompt_context(&block)
440
+ @registry.register_prompt_context(path: @path, &block)
441
+ end
442
+
443
+ # Registers an interactive command that takes over the composer region with
444
+ # a Kward-driven render and input loop. The handler receives an
445
+ # interactive controller object with a canvas API for drawing colored
446
+ # cells and reading keys. Useful for games, dashboards, and viewers.
447
+ #
448
+ # @param name [String, #to_s] command name without the leading slash
449
+ # @param rows [Integer] fixed canvas height in terminal rows
450
+ # @param fps [Numeric] frame rate for tick callbacks (1-120, default 30)
451
+ # @param description [String] short text shown in command listings
452
+ # @param argument_hint [String] optional usage hint for arguments
453
+ # @yieldparam ui [Object] interactive controller with canvas and key API
454
+ # @yieldparam ctx [Context] plugin execution context
455
+ # @return [void]
456
+ # @api public
457
+ def interactive_command(name, rows:, fps: 30, description: "", argument_hint: "", &block)
458
+ @registry.register_interactive_command(name, rows: rows, fps: fps, description: description, argument_hint: argument_hint, path: @path, &block)
459
+ end
460
+
461
+ # Registers a plugin-owned chat type. `id` is a durable identifier used
462
+ # in persisted tab layouts and transport chat handles and must not change.
463
+ # The factory receives a `PluginTabHost` and a descriptor hash.
464
+ #
465
+ # @param name [String] command name used by `/tab open <name>`
466
+ # @param id [String] stable persisted tab type identifier
467
+ # @param title [String] default tab label
468
+ # @param singleton [Symbol] `:global` for one shared plugin runtime
469
+ # @param rpc [Boolean] expose this chat through trusted local RPC
470
+ # @param transport [Boolean] allow external transport adapters to target this chat
471
+ # @param local [Boolean] expose this chat as an interactive local tab
472
+ # @param transcript_events [Boolean] allow global transcript observers to receive this tab's events
473
+ # @param api [Integer, nil] versioned plugin-chat contract API
474
+ # @param capabilities [Hash, nil] explicit attachments, steering, and transcript-paging support
475
+ # @yieldparam host [PluginTabHost] supported host dependencies
476
+ # @yieldparam descriptor [Hash] persisted tab descriptor
477
+ # @return [void]
478
+ # @api public
479
+ def tab_type(name, id:, title: nil, singleton: nil, rpc: false, transport: false, local: true, transcript_events: false, api: nil, capabilities: nil, &block)
480
+ @registry.register_tab_type(
481
+ name,
482
+ id: id,
483
+ title: title,
484
+ singleton: singleton,
485
+ rpc: rpc,
486
+ transport: transport,
487
+ local: local,
488
+ transcript_events: transcript_events,
489
+ api: api,
490
+ capabilities: capabilities,
491
+ plugin_id: @host&.id,
492
+ path: @path,
493
+ &block
494
+ )
495
+ end
496
+
497
+ # Registers an external messaging or event transport. The factory is
498
+ # called when the transport runtime starts.
499
+ #
500
+ # @param name [String] human-readable transport name
501
+ # @param id [String] stable transport identifier
502
+ # @param capabilities [Hash, Transport::Capabilities] supported features
503
+ # @yieldparam host [Object] transport host
504
+ # @yieldparam config [Object] transport configuration
505
+ # @return [void]
506
+ # @api public
507
+ def transport(name, id:, capabilities: nil, execution_profile: nil, &block)
508
+ @registry.register_transport(name, id: id, capabilities: capabilities, execution_profile: execution_profile, path: @path, &block)
509
+ end
510
+
511
+ # Registers a no-argument top-level CLI mode for an identified plugin.
512
+ # The handler runs only when the user selects this option.
513
+ def startup_option(name, description:, &block)
514
+ raise ArgumentError, "Plugin startup options require stable plugin identity" unless @host
515
+
516
+ @registry.register_startup_option(name, description: description, plugin_id: @host.id, path: @path, &block)
517
+ end
518
+
519
+ private
520
+
521
+ def register_lifecycle(event, &block)
522
+ raise ArgumentError, "Plugin lifecycle callbacks require stable plugin identity" unless @host
523
+
524
+ @registry.register_lifecycle(event, host: @host, path: @path, &block)
525
+ end
526
+ end
527
+
528
+ # Mutable singleton guard used while loading trusted plugin files.
529
+ class << self
530
+ attr_accessor :loading_registry, :loading_path
531
+
532
+ def load(paths: nil, reserved_commands: [], warning_sink: nil)
533
+ warning_sink ||= ConfigFiles.warning_sink
534
+ paths ||= ConfigFiles.plugin_paths(warning_sink: warning_sink)
535
+ registry = new(reserved_commands: reserved_commands, warning_sink: warning_sink)
536
+ paths.each { |path| registry.load_file(path) }
537
+ registry
538
+ end
539
+ end
540
+
541
+ # Creates an object for trusted plugin loading and dispatch.
542
+ def initialize(reserved_commands: [], warning_sink: nil)
543
+ @reserved_commands = reserved_commands.map(&:to_s)
544
+ @warning_sink = warning_sink
545
+ @plugins = {}
546
+ @commands = {}
547
+ @actions = {}
548
+ @tools = {}
549
+ @interactive_commands = {}
550
+ @tab_types = {}
551
+ @tab_types_by_id = {}
552
+ @transports = {}
553
+ @transports_by_id = {}
554
+ @startup_options = {}
555
+ @statuses = {}
556
+ @status_sequence = 0
557
+ @footer_path = nil
558
+ @transcript_event_handlers = []
559
+ @prompt_context_renderers = []
560
+ @hook_handlers = []
561
+ @lifecycle_handlers = { start: [], reload: [], shutdown: [] }
562
+ @lifecycle_state = :loaded
563
+ @lifecycle_mutex = Mutex.new
564
+ @paths = []
565
+ end
566
+
567
+ # @return [String, nil] most recent plugin file to register legacy footer output
568
+ attr_reader :footer_path
569
+
570
+ # @return [Array<String>] plugin files successfully loaded by this registry
571
+ attr_reader :paths
572
+
573
+ # @return [Array<PluginHost>] identified plugins loaded by this registry
574
+ def plugins
575
+ @plugins.values
576
+ end
577
+
578
+ def plugin_for(id)
579
+ @plugins[id.to_s]
580
+ end
581
+
582
+ def commands
583
+ @commands.values
584
+ end
585
+
586
+ def command_for(name)
587
+ @commands[name.to_s]
588
+ end
589
+
590
+ def actions
591
+ @actions.values
592
+ end
593
+
594
+ def action_for(id)
595
+ @actions[id.to_s]
596
+ end
597
+
598
+ def tools
599
+ @tools.values
600
+ end
601
+
602
+ def tool_for(name)
603
+ @tools[name.to_s]
604
+ end
605
+
606
+ def interactive_commands
607
+ @interactive_commands.values
608
+ end
609
+
610
+ def interactive_command_for(name)
611
+ @interactive_commands[name.to_s]
612
+ end
613
+
614
+ def tab_types
615
+ @tab_types.values
616
+ end
617
+
618
+ def tab_type_for(name)
619
+ @tab_types[name.to_s]
620
+ end
621
+
622
+ def tab_type_for_id(id)
623
+ @tab_types_by_id[id.to_s]
624
+ end
625
+
626
+ def transport_tab_types
627
+ @tab_types.values.select(&:transport)
628
+ end
629
+
630
+ def transports
631
+ @transports.values
632
+ end
633
+
634
+ def transport_for(name)
635
+ @transports[name.to_s]
636
+ end
637
+
638
+ def transport_for_id(id)
639
+ @transports_by_id[id.to_s]
640
+ end
641
+
642
+ def startup_options
643
+ @startup_options.values.dup
644
+ end
645
+
646
+ def startup_option_for(name)
647
+ @startup_options[name.to_s]
648
+ end
649
+
650
+ def run_startup_option(name)
651
+ option = startup_option_for(name) || raise(ArgumentError, "Unknown plugin startup option: #{name}")
652
+ start!
653
+ option.handler.call(plugin_for(option.plugin_id))
654
+ end
655
+
656
+ def status?
657
+ !@statuses.empty?
658
+ end
659
+
660
+ # Backward-compatible aggregate footer renderer.
661
+ def footer_renderer
662
+ return nil unless status?
663
+
664
+ lambda do |context|
665
+ compose_status(status_segments(context))
666
+ end
667
+ end
668
+
669
+ # Evaluates every status renderer independently and returns display-ordered
670
+ # frontend-neutral segments. A broken renderer cannot hide healthy segments.
671
+ def status_segments(context)
672
+ @statuses.values.sort_by { |status| [status.order, status.sequence] }.filter_map do |status|
673
+ normalize_status_segment(status, status.renderer.call(context))
674
+ rescue StandardError => e
675
+ emit_warning "Warning: Kward plugin status #{status.id} error in #{status.path}: #{e.message}"
676
+ nil
677
+ end
678
+ end
679
+
680
+ # Composes already-rendered segments. When max_width is supplied, complete
681
+ # low-priority segments are removed first; the caller remains responsible
682
+ # for truncating a final oversized segment according to frontend rules.
683
+ def compose_status(segments, max_width: nil, &measure)
684
+ visible = Array(segments).dup
685
+ return "" if visible.empty? || (!max_width.nil? && max_width.to_i <= 0)
686
+
687
+ measure ||= ->(text) { text.to_s.length }
688
+ width = max_width&.to_i
689
+ while width && visible.length > 1 && measure.call(status_text(visible)) > width
690
+ remove_lowest_priority_segment!(visible)
691
+ end
692
+ status_text(visible)
693
+ end
694
+
695
+ def transcript_event_handlers
696
+ @transcript_event_handlers.map { |entry| entry[:handler] }
697
+ end
698
+
699
+ def prompt_context_renderers
700
+ @prompt_context_renderers.map { |entry| entry[:renderer] }
701
+ end
702
+
703
+ def hook_handlers
704
+ @hook_handlers.dup
705
+ end
706
+
707
+ # Activates identified plugins and invokes their start callbacks once.
708
+ def start!
709
+ transition_lifecycle!(:loaded, :active) do
710
+ @plugins.each_value(&:activate!)
711
+ run_lifecycle_callbacks(:start)
712
+ end
713
+ self
714
+ end
715
+
716
+ # Invokes reload callbacks on the old registry and cleans up all resources.
717
+ def reload!(timeout: PluginResources::DEFAULT_SHUTDOWN_TIMEOUT)
718
+ stop_lifecycle!(:reload, timeout: timeout)
719
+ end
720
+
721
+ # Invokes shutdown callbacks and cleans up all resources.
722
+ def shutdown!(timeout: PluginResources::DEFAULT_SHUTDOWN_TIMEOUT)
723
+ stop_lifecycle!(:shutdown, timeout: timeout)
724
+ end
725
+
726
+ def hook_manager
727
+ manager = Hooks::Manager.new
728
+ @hook_handlers.each do |hook|
729
+ manager.register(hook.event, id: hook.id, source: hook.path, order: hook.order, match: hook.match, failure_policy: hook.failure_policy) do |event, context|
730
+ hook.handler.call(event, context)
731
+ end
732
+ end
733
+ manager
734
+ end
735
+
736
+ def prompt_context(context)
737
+ parts = []
738
+ @prompt_context_renderers.each do |entry|
739
+ rendered = entry[:renderer].call(context)
740
+ parts << rendered.to_s unless rendered.to_s.empty?
741
+ rescue StandardError => e
742
+ emit_warning "Warning: Kward plugin prompt context error in #{entry[:path]}: #{e.message}"
743
+ end
744
+ parts.empty? ? nil : parts.join("\n\n")
745
+ end
746
+
747
+ def notify_transcript_event(event, context)
748
+ transcript_event = transcript_event_for(event)
749
+ return unless transcript_event
750
+
751
+ @transcript_event_handlers.each do |entry|
752
+ entry[:handler].call(transcript_event, context)
753
+ rescue StandardError => e
754
+ emit_warning "Warning: Kward plugin transcript event error in #{entry[:path]}: #{e.message}"
755
+ end
756
+ nil
757
+ end
758
+
759
+ def load_file(path)
760
+ previous_registry = self.class.loading_registry
761
+ previous_path = self.class.loading_path
762
+ self.class.loading_registry = self
763
+ self.class.loading_path = path
764
+ Kernel.load(path, true)
765
+ @paths << path
766
+ rescue StandardError => e
767
+ emit_warning "Warning: skipping Kward plugin #{path}: #{e.message}"
768
+ ensure
769
+ self.class.loading_registry = previous_registry
770
+ self.class.loading_path = previous_path
771
+ end
772
+
773
+ def evaluate(path: nil, id: nil, version: nil, api: nil, &block)
774
+ host = register_plugin_identity(id: id, version: version, api: api, path: path)
775
+ dsl = DSL.new(self, path, host: host)
776
+ block.arity == 1 ? block.call(dsl) : dsl.instance_eval(&block)
777
+ self
778
+ end
779
+
780
+ def register_plugin_identity(id:, version:, api:, path: nil)
781
+ values = [id, version, api]
782
+ return nil if values.all?(&:nil?)
783
+ raise ArgumentError, "Plugin id, version, and api are required together" if values.any?(&:nil?)
784
+
785
+ id = id.to_s
786
+ api = api.to_s
787
+ raise ArgumentError, "Unsupported Kward plugin API #{api.inspect} for #{id}; supported API: #{PLUGIN_API_VERSION}" unless api == PLUGIN_API_VERSION
788
+ raise ArgumentError, "Duplicate Kward plugin id: #{id}" if @plugins.key?(id)
789
+
790
+ @plugins[id] = PluginHost.new(
791
+ id: id,
792
+ version: version,
793
+ api_version: api,
794
+ source_path: path,
795
+ warning_sink: method(:emit_warning)
796
+ )
797
+ end
798
+
799
+ def register_command(name, description: "", argument_hint: "", schema: nil, positionals: [], plugin_id: nil, path: nil, &handler)
800
+ name = name.to_s
801
+ raise "Plugin command name is invalid: #{name}" unless name.match?(COMMAND_NAME_PATTERN)
802
+ raise "Plugin command /#{name} requires a handler" unless handler
803
+ raise ArgumentError, "Plugin command /#{name} positionals require a schema" if schema.nil? && !Array(positionals).empty?
804
+
805
+ if @reserved_commands.include?(name)
806
+ emit_warning "Warning: skipping Kward plugin command /#{name}: reserved command"
807
+ return nil
808
+ end
809
+ if @commands.key?(name)
810
+ emit_warning "Warning: skipping duplicate Kward plugin command /#{name}: #{path}"
811
+ return nil
812
+ end
813
+
814
+ @commands[name] = Command.new(
815
+ name: name,
816
+ description: description.to_s,
817
+ argument_hint: argument_hint.to_s,
818
+ schema: schema,
819
+ positionals: positionals,
820
+ plugin_id: plugin_id,
821
+ path: path,
822
+ handler: handler
823
+ )
824
+ end
825
+
826
+ def register_action(name, plugin_id:, description:, schema:, path: nil, &handler)
827
+ name = name.to_s
828
+ raise "Plugin action name is invalid: #{name}" unless name.match?(COMMAND_NAME_PATTERN)
829
+ raise "Plugin action #{plugin_id}/#{name} requires a description" if description.to_s.strip.empty?
830
+ raise "Plugin action #{plugin_id}/#{name} requires a handler" unless handler
831
+
832
+ id = "#{plugin_id}/#{name}"
833
+ if @actions.key?(id)
834
+ emit_warning "Warning: skipping duplicate Kward plugin action #{id}: #{path}"
835
+ return nil
836
+ end
837
+
838
+ @actions[id] = Action.new(
839
+ name: name,
840
+ plugin_id: plugin_id,
841
+ description: description.to_s,
842
+ schema: schema,
843
+ path: path,
844
+ handler: handler
845
+ )
846
+ end
847
+
848
+ def register_tool(name, description:, schema:, path: nil, &handler)
849
+ name = name.to_s
850
+ raise "Plugin tool name is invalid: #{name}" unless name.match?(COMMAND_NAME_PATTERN)
851
+ raise "Plugin tool #{name} requires a description" if description.to_s.strip.empty?
852
+ raise "Plugin tool #{name} requires a handler" unless handler
853
+
854
+ if @tools.key?(name)
855
+ emit_warning "Warning: skipping duplicate Kward plugin tool #{name}: #{path}"
856
+ return nil
857
+ end
858
+
859
+ @tools[name] = Tool.new(
860
+ name: name,
861
+ description: description.to_s,
862
+ schema: normalize_tool_schema(name, schema),
863
+ path: path,
864
+ handler: handler
865
+ )
866
+ end
867
+
868
+ def register_interactive_command(name, rows:, fps: 30, description: "", argument_hint: "", path: nil, &handler)
869
+ name = name.to_s
870
+ raise "Interactive command name is invalid: #{name}" unless name.match?(COMMAND_NAME_PATTERN)
871
+ raise "Interactive command /#{name} requires a handler" unless handler
872
+
873
+ if @reserved_commands.include?(name) || @commands.key?(name)
874
+ emit_warning "Warning: skipping Kward interactive command /#{name}: reserved command"
875
+ return nil
876
+ end
877
+ if @interactive_commands.key?(name)
878
+ emit_warning "Warning: skipping duplicate Kward interactive command /#{name}: #{path}"
879
+ return nil
880
+ end
881
+
882
+ @interactive_commands[name] = InteractiveCommand.new(
883
+ name: name,
884
+ description: description.to_s,
885
+ argument_hint: argument_hint.to_s,
886
+ rows: [[rows.to_i, 1].max, 1].max,
887
+ fps: [[fps.to_f, 1].max, 120].min,
888
+ path: path,
889
+ handler: handler
890
+ )
891
+ end
892
+
893
+ def register_tab_type(name, id:, title: nil, singleton: nil, rpc: false, transport: false, local: true, transcript_events: false, api: nil, capabilities: nil, plugin_id: nil, path: nil, &handler)
894
+ name = name.to_s
895
+ id = id.to_s
896
+ raise "Plugin tab type name is invalid: #{name}" unless name.match?(COMMAND_NAME_PATTERN)
897
+ raise "Plugin tab type id is required" if id.empty?
898
+ raise "Plugin tab type #{name} requires a handler" unless handler
899
+
900
+ if @tab_types.key?(name) || @tab_types_by_id.key?(id)
901
+ emit_warning "Warning: skipping duplicate Kward plugin tab type #{id}: #{path}"
902
+ return nil
903
+ end
904
+
905
+ tab_type = TabType.new(
906
+ id: id,
907
+ name: name,
908
+ title: title.to_s.empty? ? name.capitalize : title.to_s,
909
+ singleton: singleton&.to_sym,
910
+ rpc: rpc == true,
911
+ transport: transport == true,
912
+ local: local == true,
913
+ transcript_events: transcript_events == true,
914
+ capabilities: PluginChatCapabilities.build(api: api, capabilities: capabilities),
915
+ plugin_id: plugin_id,
916
+ path: path,
917
+ handler: handler
918
+ )
919
+ @tab_types[name] = tab_type
920
+ @tab_types_by_id[id] = tab_type
921
+ end
922
+
923
+ def register_startup_option(name, description:, plugin_id:, path: nil, &handler)
924
+ name = name.to_s
925
+ raise "Plugin startup option must look like --name: #{name}" unless name.match?(/\A--[a-z][a-z0-9-]*\z/)
926
+ raise "Plugin startup option requires a handler: #{name}" unless handler
927
+
928
+ if @startup_options.key?(name)
929
+ emit_warning "Warning: skipping duplicate Kward plugin startup option #{name}: #{path}"
930
+ return nil
931
+ end
932
+
933
+ @startup_options[name] = StartupOption.new(name: name, description: description.to_s, plugin_id: plugin_id, path: path, handler: handler)
934
+ end
935
+
936
+ def register_transport(name, id:, capabilities: nil, execution_profile: nil, path: nil, &handler)
937
+ name = name.to_s
938
+ id = id.to_s
939
+ raise "Plugin transport name is invalid: #{name}" unless name.match?(COMMAND_NAME_PATTERN)
940
+ raise "Plugin transport id is required" if id.empty?
941
+ raise "Plugin transport #{name} requires a handler" unless handler
942
+
943
+ if @transports.key?(name) || @transports_by_id.key?(id)
944
+ emit_warning "Warning: skipping duplicate Kward plugin transport #{id}: #{path}"
945
+ return nil
946
+ end
947
+
948
+ capabilities = normalize_transport_capabilities(capabilities)
949
+ execution_profile = normalize_execution_profile(execution_profile)
950
+ transport = TransportType.new(id: id, name: name, capabilities: capabilities, execution_profile: execution_profile, path: path, handler: handler)
951
+ @transports[name] = transport
952
+ @transports_by_id[id] = transport
953
+ end
954
+
955
+ def register_footer(plugin_id: nil, path: nil, &renderer)
956
+ raise "Plugin footer requires a renderer" unless renderer
957
+
958
+ id = if plugin_id
959
+ "#{plugin_id}/footer"
960
+ else
961
+ available_legacy_status_id("legacy/#{legacy_status_source(path)}")
962
+ end
963
+ @status_sequence += 1 unless @statuses.key?(id)
964
+ @statuses[id] = Status.new(
965
+ id: id,
966
+ order: 100,
967
+ priority: :normal,
968
+ path: path,
969
+ renderer: renderer,
970
+ sequence: @statuses[id]&.sequence || @status_sequence
971
+ )
972
+ @footer_path = path
973
+ end
974
+
975
+ def register_status(name, plugin_id:, order: 100, priority: :normal, path: nil, &renderer)
976
+ name = name.to_s
977
+ raise "Plugin status name is invalid: #{name}" unless name.match?(COMMAND_NAME_PATTERN)
978
+ raise "Plugin status #{plugin_id}/#{name} requires a renderer" unless renderer
979
+
980
+ id = "#{plugin_id}/#{name}"
981
+ if @statuses.key?(id)
982
+ emit_warning "Warning: skipping duplicate Kward plugin status #{id}: #{path}"
983
+ return nil
984
+ end
985
+
986
+ order = Integer(order)
987
+ priority = normalize_status_priority(priority)
988
+ @status_sequence += 1
989
+ @statuses[id] = Status.new(
990
+ id: id,
991
+ order: order,
992
+ priority: priority,
993
+ path: path,
994
+ renderer: renderer,
995
+ sequence: @status_sequence
996
+ )
997
+ end
998
+
999
+ def emit_warning(message)
1000
+ @warning_sink ? @warning_sink.call(message) : warn(message)
1001
+ end
1002
+
1003
+ def register_transcript_event(path: nil, &handler)
1004
+ raise "Plugin transcript event requires a handler" unless handler
1005
+
1006
+ @transcript_event_handlers << { path: path, handler: handler }
1007
+ end
1008
+
1009
+ def register_prompt_context(path: nil, &renderer)
1010
+ raise "Plugin prompt context requires a renderer" unless renderer
1011
+
1012
+ @prompt_context_renderers << { path: path, renderer: renderer }
1013
+ end
1014
+
1015
+ def register_lifecycle(event, host:, path: nil, &handler)
1016
+ event = event.to_sym
1017
+ raise ArgumentError, "Unknown plugin lifecycle event: #{event}" unless @lifecycle_handlers.key?(event)
1018
+ raise ArgumentError, "Plugin lifecycle #{event} requires a handler" unless handler
1019
+
1020
+ @lifecycle_handlers[event] << LifecycleHandler.new(event: event, host: host, path: path, handler: handler)
1021
+ end
1022
+
1023
+ def register_hook(event, id: nil, description: "", order: 100, match: nil, failure_policy: nil, path: nil, &handler)
1024
+ event = event.to_s
1025
+ raise "Plugin hook event is required" if event.empty?
1026
+ raise "Plugin hook #{event} requires a handler" unless handler
1027
+
1028
+ @hook_handlers << HookHandler.new(
1029
+ event: event,
1030
+ id: id&.to_s || "#{File.basename(path.to_s.empty? ? "plugin" : path)}:#{event}:#{@hook_handlers.length + 1}",
1031
+ description: description.to_s,
1032
+ path: path,
1033
+ order: order.to_i,
1034
+ match: match,
1035
+ failure_policy: failure_policy,
1036
+ handler: handler
1037
+ )
1038
+ end
1039
+
1040
+ private
1041
+
1042
+ def normalize_status_priority(priority)
1043
+ value = priority.to_s.to_sym
1044
+ return value if STATUS_PRIORITIES.key?(value)
1045
+
1046
+ raise ArgumentError, "Plugin status priority must be low, normal, or high"
1047
+ end
1048
+
1049
+ def normalize_status_segment(status, value)
1050
+ attributes = value.is_a?(Hash) ? value : { text: value }
1051
+ text = status_value(attributes, :text).to_s.gsub(/\s+/, " ").strip
1052
+ return nil if text.empty?
1053
+
1054
+ tooltip = status_value(attributes, :tooltip)
1055
+ tooltip = tooltip.to_s.gsub(/\s+/, " ").strip unless tooltip.nil?
1056
+ tooltip = nil if tooltip.to_s.empty?
1057
+ StatusSegment.new(
1058
+ id: status.id.dup.freeze,
1059
+ text: text.freeze,
1060
+ tooltip: tooltip&.freeze,
1061
+ priority: status.priority,
1062
+ order: status.order
1063
+ ).freeze
1064
+ end
1065
+
1066
+ def status_value(attributes, key)
1067
+ attributes.key?(key) ? attributes[key] : attributes[key.to_s]
1068
+ end
1069
+
1070
+ def status_text(segments)
1071
+ segments.map(&:text).join(STATUS_SEPARATOR)
1072
+ end
1073
+
1074
+ def remove_lowest_priority_segment!(segments)
1075
+ lowest_priority = segments.map { |segment| STATUS_PRIORITIES.fetch(segment.priority) }.min
1076
+ index = segments.each_index.select do |candidate|
1077
+ STATUS_PRIORITIES.fetch(segments[candidate].priority) == lowest_priority
1078
+ end.max_by { |candidate| [segments[candidate].order, candidate] }
1079
+ segments.delete_at(index)
1080
+ end
1081
+
1082
+ def available_legacy_status_id(base_id)
1083
+ return base_id unless @statuses.key?(base_id)
1084
+
1085
+ suffix = 2
1086
+ suffix += 1 while @statuses.key?("#{base_id}##{suffix}")
1087
+ "#{base_id}##{suffix}"
1088
+ end
1089
+
1090
+ def legacy_status_source(path)
1091
+ source = path.to_s
1092
+ return "plugin" if source.empty?
1093
+
1094
+ basename = File.basename(source)
1095
+ basename == "plugin.rb" ? File.basename(File.dirname(source)) : File.basename(source, ".rb")
1096
+ end
1097
+
1098
+ def transition_lifecycle!(from, to)
1099
+ should_run = @lifecycle_mutex.synchronize do
1100
+ next false unless @lifecycle_state == from
1101
+
1102
+ @lifecycle_state = to
1103
+ true
1104
+ end
1105
+ yield if should_run
1106
+ end
1107
+
1108
+ def stop_lifecycle!(event, timeout:)
1109
+ transition_lifecycle!(:active, :stopped) do
1110
+ run_lifecycle_callbacks(event)
1111
+ @plugins.each_value { |host| host.shutdown(timeout: timeout) }
1112
+ end
1113
+ self
1114
+ end
1115
+
1116
+ def run_lifecycle_callbacks(event)
1117
+ @lifecycle_handlers.fetch(event).each do |entry|
1118
+ entry.handler.arity.zero? ? entry.handler.call : entry.handler.call(entry.host)
1119
+ rescue StandardError => e
1120
+ emit_warning "Warning: Kward plugin #{event} error in #{entry.path}: #{e.message}"
1121
+ end
1122
+ end
1123
+
1124
+ def normalize_tool_schema(name, schema)
1125
+ raise ArgumentError, "Plugin tool #{name} schema must be an object" unless schema.is_a?(Hash)
1126
+
1127
+ parameters = schema.each_with_object({}) { |(key, value), result| result[key.to_sym] = DeepCopy.dup(value) }
1128
+ type = parameters.fetch(:type, "object").to_s
1129
+ raise ArgumentError, "Plugin tool #{name} schema type must be object" unless type == "object"
1130
+
1131
+ properties = parameters.fetch(:properties, {})
1132
+ required = parameters.fetch(:required, [])
1133
+ raise ArgumentError, "Plugin tool #{name} schema properties must be an object" unless properties.is_a?(Hash)
1134
+ raise ArgumentError, "Plugin tool #{name} schema required must be an array" unless required.is_a?(Array)
1135
+ if parameters[:additionalProperties] == true
1136
+ raise ArgumentError, "Plugin tool #{name} schema cannot allow additional properties"
1137
+ end
1138
+
1139
+ property_names = properties.keys.map(&:to_s)
1140
+ required = required.map(&:to_s).uniq.sort
1141
+ unknown_required = required - property_names
1142
+ unless unknown_required.empty?
1143
+ raise ArgumentError, "Plugin tool #{name} schema requires unknown properties: #{unknown_required.join(', ')}"
1144
+ end
1145
+
1146
+ parameters[:type] = "object"
1147
+ parameters[:properties] = properties.keys.sort_by(&:to_s).each_with_object({}) do |key, result|
1148
+ result[key] = properties[key]
1149
+ end
1150
+ parameters[:required] = required
1151
+ parameters[:additionalProperties] = false
1152
+ DeepCopy.freeze(parameters)
1153
+ end
1154
+
1155
+ def normalize_execution_profile(profile)
1156
+ return nil if profile.nil?
1157
+ return profile if profile.is_a?(Transport::ExecutionProfile)
1158
+ raise ArgumentError, "Plugin transport execution_profile must be a Transport::ExecutionProfile"
1159
+ end
1160
+
1161
+ def normalize_transport_capabilities(capabilities)
1162
+ return Transport.capabilities if capabilities.nil?
1163
+ return capabilities if capabilities.is_a?(Transport::Capabilities)
1164
+ raise ArgumentError, "Plugin transport capabilities must be a hash or Transport::Capabilities" unless capabilities.is_a?(Hash)
1165
+
1166
+ Transport.capabilities(**capabilities.transform_keys(&:to_sym))
1167
+ end
1168
+
1169
+ def transcript_event_for(event)
1170
+ case event.class.name
1171
+ when "Kward::Events::ReasoningDelta"
1172
+ transcript_event("reasoning_delta", delta: event.delta)
1173
+ when "Kward::Events::ReasoningBoundary"
1174
+ transcript_event("reasoning_boundary")
1175
+ when "Kward::Events::AssistantDelta"
1176
+ transcript_event("assistant_delta", delta: event.delta)
1177
+ when "Kward::Events::AssistantMessage"
1178
+ transcript_event("assistant_message", message: event.message)
1179
+ when "Kward::Events::Retry"
1180
+ transcript_event(
1181
+ "model_retry",
1182
+ provider: event.provider,
1183
+ model: event.model,
1184
+ attempt: event.attempt,
1185
+ max_attempts: event.max_attempts,
1186
+ delay_seconds: event.delay_seconds,
1187
+ error: event.error,
1188
+ request_bytes: event.request_bytes
1189
+ )
1190
+ when "Kward::Events::Steering"
1191
+ transcript_event("turn_steered", input: event.input, created_at: event.created_at)
1192
+ when "Kward::Events::ToolCall"
1193
+ transcript_event("tool_call", tool_call: event.tool_call)
1194
+ when "Kward::Events::ToolResult"
1195
+ transcript_event("tool_result", tool_call: event.tool_call, content: event.content)
1196
+ when "Kward::Events::Answer"
1197
+ transcript_event("answer", content: event.content)
1198
+ end
1199
+ end
1200
+
1201
+ def transcript_event(type, payload = {})
1202
+ TranscriptEvent.new(
1203
+ type: type,
1204
+ payload: DeepCopy.freeze(DeepCopy.dup(payload))
1205
+ ).freeze
1206
+ end
1207
+ end
1208
+
1209
+ # Registers a trusted local plugin.
1210
+ #
1211
+ # This method is intended for Ruby files loaded from the user plugin
1212
+ # directory. It raises if called outside plugin loading so workspace code
1213
+ # cannot silently mutate Kward's runtime by merely being required.
1214
+ #
1215
+ # @param id [String, nil] stable reverse-domain-style plugin identifier
1216
+ # @param version [String, nil] plugin release version
1217
+ # @param api [String, Integer, nil] Kward plugin API version
1218
+ # @yieldparam plugin [PluginRegistry::DSL] plugin registration DSL
1219
+ # @return [Object, nil] the plugin block result
1220
+ # @api public
1221
+ def self.plugin(id: nil, version: nil, api: nil, &block)
1222
+ registry = PluginRegistry.loading_registry
1223
+ raise "Kward.plugin can only be called while loading a plugin" unless registry
1224
+
1225
+ host = registry.register_plugin_identity(id: id, version: version, api: api, path: PluginRegistry.loading_path)
1226
+ dsl = PluginRegistry::DSL.new(registry, PluginRegistry.loading_path, host: host)
1227
+ block.arity == 1 ? block.call(dsl) : dsl.instance_eval(&block)
1228
+ end
1229
+ end