kward 0.85.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 (151) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +130 -0
  3. data/CONTRIBUTING.md +1 -1
  4. data/Gemfile.lock +6 -2
  5. data/README.md +3 -3
  6. data/Rakefile +3 -0
  7. data/doc/agent-tools.md +11 -0
  8. data/doc/api.md +4 -1
  9. data/doc/composer.md +4 -3
  10. data/doc/configuration.md +60 -11
  11. data/doc/extensibility.md +2 -0
  12. data/doc/getting-started.md +3 -3
  13. data/doc/git.md +1 -1
  14. data/doc/memory.md +1 -1
  15. data/doc/plugins.md +40 -5
  16. data/doc/providers.md +10 -4
  17. data/doc/rpc.md +125 -7
  18. data/doc/session-management.md +36 -1
  19. data/doc/shell.md +643 -27
  20. data/doc/tabs.md +2 -1
  21. data/doc/troubleshooting.md +1 -1
  22. data/doc/usage.md +21 -11
  23. data/examples/plugins/openrouter_proxy/README.md +103 -0
  24. data/examples/plugins/openrouter_proxy/fake_embeddings.rb +85 -0
  25. data/examples/plugins/openrouter_proxy/plugin.rb +7 -0
  26. data/examples/plugins/openrouter_proxy/protocol.rb +202 -0
  27. data/examples/plugins/openrouter_proxy/server.rb +186 -0
  28. data/examples/plugins/space_invaders.rb +0 -1
  29. data/exe/kward +2 -2
  30. data/exe/kwsh +7 -0
  31. data/kward.gemspec +3 -1
  32. data/lib/kward/agent.rb +43 -9
  33. data/lib/kward/cli/commands.rb +41 -11
  34. data/lib/kward/cli/interactive_turn.rb +10 -0
  35. data/lib/kward/cli/plugins.rb +5 -1
  36. data/lib/kward/cli/prompt_interface.rb +4 -1
  37. data/lib/kward/cli/rendering.rb +21 -28
  38. data/lib/kward/cli/runtime_helpers.rb +52 -34
  39. data/lib/kward/cli/settings/model.rb +1 -12
  40. data/lib/kward/cli/tabs.rb +91 -18
  41. data/lib/kward/cli/tool_summaries.rb +2 -0
  42. data/lib/kward/cli/transcript_formatter.rb +3 -10
  43. data/lib/kward/cli/worktrees.rb +1 -0
  44. data/lib/kward/cli.rb +56 -7
  45. data/lib/kward/config/core.rb +16 -5
  46. data/lib/kward/config/extensions.rb +3 -0
  47. data/lib/kward/config/paths.rb +11 -0
  48. data/lib/kward/config/settings.rb +7 -0
  49. data/lib/kward/conversation.rb +11 -1
  50. data/lib/kward/entrypoint.rb +14 -0
  51. data/lib/kward/events.rb +2 -0
  52. data/lib/kward/generated_images.rb +237 -0
  53. data/lib/kward/model/catalog.rb +6 -3
  54. data/lib/kward/model/client.rb +105 -36
  55. data/lib/kward/model/codex_images.rb +83 -0
  56. data/lib/kward/model/copilot_models.rb +8 -4
  57. data/lib/kward/model/model_info.rb +27 -9
  58. data/lib/kward/model/openrouter_model_cache.rb +4 -2
  59. data/lib/kward/model/payloads.rb +6 -5
  60. data/lib/kward/model/sources.rb +3 -1
  61. data/lib/kward/model/stream_parser.rb +4 -7
  62. data/lib/kward/pan/index.html.erb +8 -1
  63. data/lib/kward/pan/server.rb +13 -1
  64. data/lib/kward/plugins/codex_responses.rb +73 -0
  65. data/lib/kward/plugins/host.rb +16 -0
  66. data/lib/kward/plugins/http_server.rb +83 -0
  67. data/lib/kward/plugins/registry.rb +39 -0
  68. data/lib/kward/prompt_interface/composer_controller.rb +0 -1
  69. data/lib/kward/prompt_interface/composer_renderer.rb +159 -72
  70. data/lib/kward/prompt_interface/editor/controller.rb +1 -1
  71. data/lib/kward/prompt_interface/editor/renderer.rb +10 -7
  72. data/lib/kward/prompt_interface/file_overlay.rb +3 -3
  73. data/lib/kward/prompt_interface/generated_image_preview.rb +162 -0
  74. data/lib/kward/prompt_interface/git_prompt.rb +18 -11
  75. data/lib/kward/prompt_interface/interactive/renderer.rb +1 -1
  76. data/lib/kward/prompt_interface/interactive/state.rb +18 -20
  77. data/lib/kward/prompt_interface/key_handler.rb +108 -25
  78. data/lib/kward/prompt_interface/layout.rb +11 -1
  79. data/lib/kward/prompt_interface/overlay_renderer.rb +25 -8
  80. data/lib/kward/prompt_interface/project_browser.rb +27 -54
  81. data/lib/kward/prompt_interface/prompt_renderer.rb +27 -35
  82. data/lib/kward/prompt_interface/question_prompt.rb +19 -28
  83. data/lib/kward/prompt_interface/runtime_state.rb +31 -9
  84. data/lib/kward/prompt_interface/screen.rb +24 -21
  85. data/lib/kward/prompt_interface/selection_prompt.rb +8 -8
  86. data/lib/kward/prompt_interface/slash_overlay.rb +1 -1
  87. data/lib/kward/prompt_interface/transcript_renderer.rb +7 -6
  88. data/lib/kward/prompt_interface.rb +109 -39
  89. data/lib/kward/prompts.rb +7 -1
  90. data/lib/kward/pty/adaptive_output_sink.rb +38 -4
  91. data/lib/kward/pty/interactive_runner.rb +20 -28
  92. data/lib/kward/pty/transcript_normalizer.rb +65 -21
  93. data/lib/kward/rpc/config_manager.rb +3 -0
  94. data/lib/kward/rpc/server.rb +27 -5
  95. data/lib/kward/rpc/session_manager.rb +62 -17
  96. data/lib/kward/rpc/transcript_normalizer.rb +11 -7
  97. data/lib/kward/sessions/store.rb +30 -3
  98. data/lib/kward/shell/kwsh.rb +27 -7
  99. data/lib/kward/shell/kwshrc.rb +11 -2
  100. data/lib/kward/shell/native_arithmetic.rb +255 -0
  101. data/lib/kward/shell/native_arrays.rb +102 -0
  102. data/lib/kward/shell/native_braces.rb +96 -0
  103. data/lib/kward/shell/native_builtins.rb +476 -0
  104. data/lib/kward/shell/native_completion.rb +169 -0
  105. data/lib/kward/shell/native_condition.rb +75 -0
  106. data/lib/kward/shell/native_directory.rb +116 -0
  107. data/lib/kward/shell/native_exec_state.rb +73 -0
  108. data/lib/kward/shell/native_expansion.rb +252 -0
  109. data/lib/kward/shell/native_fields.rb +62 -0
  110. data/lib/kward/shell/native_glob.rb +96 -0
  111. data/lib/kward/shell/native_history.rb +242 -0
  112. data/lib/kward/shell/native_interactive.rb +164 -0
  113. data/lib/kward/shell/native_invocation.rb +42 -0
  114. data/lib/kward/shell/native_jobs.rb +250 -0
  115. data/lib/kward/shell/native_line_editor.rb +382 -0
  116. data/lib/kward/shell/native_line_terminal.rb +286 -0
  117. data/lib/kward/shell/native_locale.rb +109 -0
  118. data/lib/kward/shell/native_locals.rb +57 -0
  119. data/lib/kward/shell/native_pattern.rb +200 -0
  120. data/lib/kward/shell/native_process.rb +279 -0
  121. data/lib/kward/shell/native_program.rb +40 -0
  122. data/lib/kward/shell/native_programmable_completion.rb +115 -0
  123. data/lib/kward/shell/native_prompt_format.rb +89 -0
  124. data/lib/kward/shell/native_runtime.rb +964 -0
  125. data/lib/kward/shell/native_substitution.rb +110 -0
  126. data/lib/kward/shell/native_syntax.rb +946 -0
  127. data/lib/kward/shell/native_traps.rb +196 -0
  128. data/lib/kward/shell/native_vi.rb +407 -0
  129. data/lib/kward/shell/native_vi_terminal.rb +19 -0
  130. data/lib/kward/shell/native_worker.rb +82 -0
  131. data/lib/kward/shell/persistent_session.rb +184 -190
  132. data/lib/kward/shell/prompt.rb +14 -0
  133. data/lib/kward/shell/prompt_agent.rb +17 -0
  134. data/lib/kward/shell/script_runner.rb +244 -0
  135. data/lib/kward/shell/standalone_agent.rb +31 -0
  136. data/lib/kward/shell/standalone_link.rb +78 -0
  137. data/lib/kward/shell/standalone_terminal.rb +287 -0
  138. data/lib/kward/terminal/keys.rb +22 -1
  139. data/lib/kward/terminal/locale_text.rb +29 -0
  140. data/lib/kward/terminal/sequences.rb +45 -4
  141. data/lib/kward/tools/datetime.rb +85 -0
  142. data/lib/kward/tools/generate_image.rb +36 -0
  143. data/lib/kward/tools/registry.rb +35 -9
  144. data/lib/kward/tools/tool_call.rb +3 -1
  145. data/lib/kward/transcripts/markdown_transcript.rb +8 -0
  146. data/lib/kward/transcripts/turn_summary_formatter.rb +93 -0
  147. data/lib/kward/transport/gateway.rb +2 -1
  148. data/lib/kward/turn_summary.rb +68 -0
  149. data/lib/kward/version.rb +1 -1
  150. data/lib/main.rb +6 -3
  151. metadata +84 -1
@@ -2,6 +2,7 @@
2
2
  module Kward
3
3
  # Terminal input key byte sequences grouped by semantic key.
4
4
  module TerminalKeys
5
+ ESCAPE = "\e".freeze
5
6
  CTRL_SPACE = "\x00".freeze
6
7
  CTRL_A = "\x01".freeze
7
8
  CTRL_B = "\x02".freeze
@@ -9,6 +10,7 @@ module Kward
9
10
  CTRL_D = "\x04".freeze
10
11
  CTRL_E = "\x05".freeze
11
12
  CTRL_F = "\x06".freeze
13
+ CTRL_G = "\x07".freeze
12
14
  CTRL_H = "\x08".freeze
13
15
  CTRL_J = "\x0A".freeze
14
16
  CTRL_K = "\x0B".freeze
@@ -26,6 +28,7 @@ module Kward
26
28
  CTRL_Y = "\x19".freeze
27
29
  CTRL_Z = "\x1A".freeze
28
30
  CTRL_PERIOD = "\x1E".freeze
31
+ CTRL_UNDERSCORE = "\x1F".freeze
29
32
 
30
33
  RETURN = ["\n", "\r"].freeze
31
34
  BACKSPACE = ["\b", "\x7F"].freeze
@@ -46,6 +49,12 @@ module Kward
46
49
  CTRL_SHIFT_TAB = ["\e[9;6u", "\e[27;6;9~", "\e[1;6I", "\e[1;6Z"].freeze
47
50
  SHIFT_ENTER = ["\e[13;2u", "\e[13;2~", "\e[27;2;13~", "\e\r", "\e\n"].freeze
48
51
 
52
+ ALT_B = ["\eb", "\eB"].freeze
53
+ ALT_D = ["\ed", "\eD"].freeze
54
+ ALT_F = ["\ef", "\eF"].freeze
55
+ ALT_Y = ["\ey", "\eY"].freeze
56
+ ALT_LAST_WORD = ["\e.", "\e_"].freeze
57
+ ALT_BACKSPACE = ["\e\b", "\e\x7F"].freeze
49
58
  ALT_LEFT = ["\e[1;3D", "\e[3D"].freeze
50
59
  ALT_RIGHT = ["\e[1;3C", "\e[3C"].freeze
51
60
  ALT_UP = ["\e[1;3A", "\e[3A"].freeze
@@ -70,12 +79,15 @@ module Kward
70
79
  CTRL_SHIFT_UP = ["\e[1;6A", "\e[6A"].freeze
71
80
  CTRL_SHIFT_DOWN = ["\e[1;6B", "\e[6B"].freeze
72
81
 
82
+ CTRL_N_MODIFY_OTHER_KEYS = "\e[27;5;110~".freeze
73
83
  CTRL_T_CSI_U = "\e[116;5u".freeze
84
+ CTRL_SHIFT_T_CSI_U = ["\e[116;6u", "\e[84;6u"].freeze
74
85
  CTRL_W_CSI_U = "\e[119;5u".freeze
75
86
  CTRL_NUMBER_TAB_PATTERN = /\A\e\[((?:49)|(?:5[0-7]));5u\z/.freeze
76
87
  TAB_ACTION_SEQUENCES = (
77
88
  CTRL_TAB +
78
89
  CTRL_SHIFT_TAB +
90
+ CTRL_SHIFT_T_CSI_U +
79
91
  [CTRL_T, CTRL_T_CSI_U, CTRL_W_CSI_U] +
80
92
  (49..57).map { |code| "\e[#{code};5u" } +
81
93
  ["\et", "\eT"] +
@@ -84,7 +96,16 @@ module Kward
84
96
  (1..9).map { |number| "\e#{number}" }
85
97
  ).freeze
86
98
 
87
- CSI_U_PATTERN = /\A\e\[(\d+)((?:;[\d:]*)*)u/.freeze
99
+ CSI_U_MODIFIER_KEY_CODES = (57441..57454).freeze
100
+ CSI_U_PATTERN = /\A\e\[(\d+)(?::[\d:]*)?((?:;[\d:]*)*)u/.freeze
101
+ CSI_SEQUENCE_PATTERN = /\A\e\[[0-?]*[ -\/]*[@-~]/.freeze
102
+ CSI_PREFIX_PATTERN = /\A\e\[[0-?]*[ -\/]*\z/.freeze
103
+ MODIFY_OTHER_KEYS_PATTERN = /\A\e\[27;(\d+);(\d+)~\z/.freeze
104
+ HANDOFF_ESCAPE_DELAY = 0.03
105
+ LEGACY_CTRL_CODES = { 32 => 0, 50 => 0, 51 => 27, 52 => 28, 53 => 29, 54 => 30, 55 => 31,
106
+ 56 => 127, 47 => 31, 63 => 127, 64 => 0, 91 => 27, 92 => 28, 93 => 29,
107
+ 94 => 30, 95 => 31, 126 => 30 }.freeze
108
+ MAX_HANDOFF_SEQUENCE_BYTES = 4096
88
109
  MODIFIED_CURSOR_PATTERN = /\A\e\[(\d+);(\d+)([CDFH])\z/.freeze
89
110
  MODIFIED_DELETE_PATTERN = /\A\e\[3;(\d+)~\z/.freeze
90
111
  UP_PATTERN = /\A\e\[[0-9;:]*A\z/.freeze
@@ -0,0 +1,29 @@
1
+ require "fiddle"
2
+
3
+ module Kward
4
+ module TerminalText
5
+ # Standalone native shells use a scoped libc locale rather than the TUI's
6
+ # Unicode gem. Call only inside NativeShell::Locale.with; never setlocale.
7
+ LOCALE_WCWIDTH = Fiddle::Function.new(Fiddle::Handle::DEFAULT["wcwidth"], [Fiddle::TYPE_INT], Fiddle::TYPE_INT)
8
+
9
+ def self.locale_cells(text)
10
+ text.each_char.map do |character|
11
+ begin
12
+ codepoint = character.encode(Encoding::UTF_8).ord
13
+ width = LOCALE_WCWIDTH.call(codepoint)
14
+ if codepoint < 32 || codepoint == 127
15
+ ["^#{(codepoint ^ 64).chr}", 2]
16
+ elsif width >= 0
17
+ [character, width]
18
+ else
19
+ escaped = "\\u{#{codepoint.to_s(16)}}"
20
+ [escaped, escaped.length]
21
+ end
22
+ rescue EncodingError
23
+ escaped = character.bytes.map { |byte| format('\\x%02x', byte) }.join
24
+ [escaped, escaped.length]
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -1,11 +1,24 @@
1
- require "base64"
2
-
3
1
  # Namespace for the Kward CLI agent runtime.
4
2
  module Kward
5
3
  # Terminal control escape sequence builders.
6
4
  module TerminalSequences
5
+ ALERT = "\a".freeze
6
+ CARRIAGE_RETURN = "\r".freeze
7
+ ERASE_LINE_END = "\e[K".freeze
8
+ CLEAR_VISIBLE_SCREEN = "\e[2J\e[H".freeze
9
+ ALTERNATE_SCREEN_ENTER = "\e[?1049h".freeze
10
+ ALTERNATE_SCREEN_LEAVE = "\e[?1049l".freeze
7
11
  KEYBOARD_PROTOCOL_ENABLE = "\e[>25u".freeze
8
12
  KEYBOARD_PROTOCOL_RESTORE = "\e[<u".freeze
13
+ KEYBOARD_PROTOCOL_SET = "\e[=25u".freeze
14
+ # Cancel incomplete controls before restoring the composer's terminal baseline.
15
+ CONTROL_SEQUENCE_CANCEL = "\x18\e\\".freeze
16
+ COMPOSER_MODES_RESTORE = (
17
+ "\e[?2026l\e[?1049l\e[?1047l\e[?47l" +
18
+ "\e[?1l\e>\e[?1004l\e[>4;0m" +
19
+ "\e[?1000l\e[?1002l\e[?1003l\e[?1005l\e[?1006l\e[?1015l" +
20
+ "\e[?6l\e[?7h\e[4l"
21
+ ).freeze
9
22
  BRACKETED_PASTE_ENABLE = "\e[?2004h".freeze
10
23
  BRACKETED_PASTE_RESTORE = "\e[?2004l".freeze
11
24
  BRACKETED_PASTE_START = "\e[200~".freeze
@@ -22,8 +35,28 @@ module Kward
22
35
  SGR_INVERSE = "\e[7m".freeze
23
36
  SGR_INVERSE_OFF = "\e[27m".freeze
24
37
 
38
+ KITTY_GRAPHICS_PREFIX = "\e_G".freeze
39
+ KITTY_GRAPHICS_COMMAND = /\A\e_G(?:[A-Za-z]=[A-Za-z0-9+-]+(?:,[A-Za-z]=[A-Za-z0-9+-]+)*)?(?:;[A-Za-z0-9+\/=]*)?\e\\\z/.freeze
40
+ DEVICE_QUERY = /\A\e\[(?:>?0?c|>0?q|\?u|[56]n|\?6n|1[468]t)\z/.freeze
41
+
25
42
  module_function
26
43
 
44
+ def keyboard_mode_mutation?(sequence)
45
+ sequence.match?(/\A\e\[[><=][0-9;]*u\z/) ||
46
+ sequence.match?(/\A\e\[>4(?:;[0-9]*)?m\z/)
47
+ end
48
+
49
+ def keyboard_mode_reset?(sequence)
50
+ return true if sequence == "\ec" || sequence == "\e[!p"
51
+
52
+ match = sequence.match(/\A\e\[\?([0-9;]+)[hl]\z/)
53
+ match && (match[1].split(";") & %w[47 1047 1049]).any?
54
+ end
55
+
56
+ def sgr(*codes)
57
+ "\e[#{codes.join(';')}m"
58
+ end
59
+
27
60
  def scroll_region(top, bottom)
28
61
  "\e[#{top};#{bottom}r"
29
62
  end
@@ -36,12 +69,20 @@ module Kward
36
69
  "\e[#{row};#{col}H"
37
70
  end
38
71
 
72
+ def move_up(rows)
73
+ "\e[#{rows}A"
74
+ end
75
+
76
+ def move_down(rows)
77
+ "\e[#{rows}B"
78
+ end
79
+
39
80
  def move_to_column(column)
40
81
  "\e[#{column}G"
41
82
  end
42
83
 
43
84
  def osc52(text)
44
- "\e]52;c;#{Base64.strict_encode64(text.to_s)}\a"
85
+ "\e]52;c;#{[text.to_s].pack("m0")}\a"
45
86
  end
46
87
 
47
88
  def kitty_graphics(data, image_id:, columns: nil, rows: nil, move_cursor: true)
@@ -78,7 +119,7 @@ module Kward
78
119
  params = ["inline=1", "preserveAspectRatio=1"]
79
120
  params << "width=#{width}" if width
80
121
  params << "height=#{height}" if height
81
- params << "name=#{Base64.strict_encode64(File.basename(name))}" if name
122
+ params << "name=#{[File.basename(name)].pack("m0")}" if name
82
123
  "\e]1337;File=#{params.join(";")}:#{data}\a"
83
124
  end
84
125
  end
@@ -0,0 +1,85 @@
1
+ require "time"
2
+ require_relative "base"
3
+
4
+ # Namespace for the Kward CLI agent runtime.
5
+ module Kward
6
+ # Model-callable date and time utilities.
7
+ module Tools
8
+ class DateTime < Base
9
+ OFFSET_PATTERN = /\A(?:Z|[+-](?:0\d|1[0-4]):[0-5]\d)\z/.freeze
10
+ TIMESTAMP_OFFSET_PATTERN = /(?:Z|[+-]\d{2}:?\d{2})\z/i.freeze
11
+
12
+ def initialize
13
+ super(
14
+ "datetime",
15
+ "Get the current date and time, or add signed whole seconds to an ISO 8601 timestamp. Current time uses the host's local timezone unless a UTC offset is supplied. Arithmetic preserves the timestamp's offset; offsets do not include daylight-saving rules.",
16
+ properties: {
17
+ operation: {
18
+ type: "string",
19
+ enum: %w[current_time add_seconds],
20
+ description: "Operation to perform."
21
+ },
22
+ timezone_offset: {
23
+ type: "string",
24
+ description: "Optional UTC offset for current_time, formatted as +HH:MM, -HH:MM, or Z."
25
+ },
26
+ timestamp: {
27
+ type: "string",
28
+ description: "ISO 8601 timestamp with an explicit UTC offset, required for add_seconds."
29
+ },
30
+ seconds: {
31
+ type: "integer",
32
+ description: "Signed whole number of seconds to add, required for add_seconds."
33
+ }
34
+ },
35
+ required: ["operation"]
36
+ )
37
+ end
38
+
39
+ def call(args, _conversation, cancellation: nil)
40
+ cancellation&.raise_if_cancelled!
41
+
42
+ case argument(args, :operation)
43
+ when "current_time"
44
+ current_time(args)
45
+ when "add_seconds"
46
+ add_seconds(args)
47
+ else
48
+ "Error: operation must be current_time or add_seconds"
49
+ end
50
+ rescue ArgumentError, RangeError, TypeError => e
51
+ "Error: #{e.message}"
52
+ end
53
+
54
+ private
55
+
56
+ def current_time(args)
57
+ offset = argument(args, :timezone_offset)
58
+ time = Time.now
59
+ time = time.getlocal(validated_offset(offset)) unless offset.nil?
60
+ "Current date/time: #{time.iso8601}"
61
+ end
62
+
63
+ def add_seconds(args)
64
+ timestamp = argument(args, :timestamp)
65
+ seconds = argument(args, :seconds)
66
+ unless timestamp.is_a?(String) && TIMESTAMP_OFFSET_PATTERN.match?(timestamp)
67
+ raise ArgumentError, "timestamp must be an ISO 8601 string with a UTC offset"
68
+ end
69
+ raise ArgumentError, "seconds must be an integer" unless seconds.is_a?(Integer)
70
+
71
+ "Result: #{(Time.iso8601(timestamp) + seconds).iso8601}"
72
+ end
73
+
74
+ def validated_offset(offset)
75
+ outside_iso_range = offset.is_a?(String) &&
76
+ offset.start_with?("+14:", "-14:") && offset[-2, 2] != "00"
77
+ unless offset.is_a?(String) && OFFSET_PATTERN.match?(offset) && !outside_iso_range
78
+ raise ArgumentError, "timezone_offset must be Z or an offset between -14:00 and +14:00"
79
+ end
80
+
81
+ offset == "Z" ? "+00:00" : offset
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,36 @@
1
+ require_relative "base"
2
+ require_relative "../model/codex_images"
3
+ require_relative "../generated_images"
4
+
5
+ module Kward
6
+ module Tools
7
+ # Generates a preview, never a workspace file. The frontend owns export.
8
+ class GenerateImage < Base
9
+ NAME = "generate_image".freeze
10
+ MAX_PROMPT_BYTES = 16_384
11
+
12
+ def initialize(client:, images:)
13
+ super(NAME, "Generate one PNG when the user asks to create an image. Describe what to draw, not a destination. Kward presents the preview and the user decides whether and where to save it.",
14
+ properties: { "prompt" => { type: "string", description: "What to draw." } }, required: ["prompt"])
15
+ @client = client
16
+ @images = images
17
+ end
18
+
19
+ def call(args, conversation, cancellation: nil, provider: nil, turn_id: nil)
20
+ prompt = args["prompt"] || args[:prompt]
21
+ unless prompt.is_a?(String) && !prompt.strip.empty? && prompt.bytesize <= MAX_PROMPT_BYTES
22
+ return "Error: provide a non-empty image prompt of at most #{MAX_PROMPT_BYTES} bytes."
23
+ end
24
+ return "Error: image generation requires a Codex turn." unless provider == "Codex"
25
+
26
+ bytes = @client.generate_codex_image(prompt, turn_id: turn_id, cancellation: cancellation)
27
+ cancellation&.raise_if_cancelled!
28
+ image = @images.add(conversation, bytes, cancellation: cancellation)
29
+ yield image if block_given?
30
+ "Image generated. The preview is ready for the user to save or discard. No project file was written."
31
+ rescue CodexImages::Error, GeneratedImages::Error => e
32
+ "Error: #{e.message}"
33
+ end
34
+ end
35
+ end
36
+ end
@@ -5,10 +5,12 @@ require_relative "ask_user_question"
5
5
  require_relative "code_search"
6
6
  require_relative "context_budget_stats"
7
7
  require_relative "context_for_task"
8
+ require_relative "datetime"
8
9
  require_relative "edit_file"
9
10
  require_relative "fetch_content"
10
11
  require_relative "fetch_raw"
11
12
  require_relative "git_commit"
13
+ require_relative "generate_image"
12
14
  require_relative "list_directory"
13
15
  require_relative "mcp_tool"
14
16
  require_relative "plugin_tool"
@@ -82,6 +84,7 @@ module Kward
82
84
 
83
85
  BUILTIN_TOOL_NAMES = (CORE_TOOL_NAMES + %w[
84
86
  git_commit
87
+ generate_image
85
88
  web_search
86
89
  fetch_content
87
90
  fetch_raw
@@ -91,6 +94,7 @@ module Kward
91
94
  open_editor
92
95
  prepare_shell_command
93
96
  typesafe_evaluate
97
+ datetime
94
98
  ]).freeze
95
99
 
96
100
  # Tool schemas advertised to the model for the current frontend and config.
@@ -111,7 +115,7 @@ module Kward
111
115
  # @param skills [Array<ConfigFiles::Skill>, nil] override discovered skills
112
116
  # @param ask_user_question_enabled [Boolean, nil] override question exposure
113
117
  # @param plugin_tools [Array<PluginRegistry::Tool>] trusted plugin tool registrations
114
- def initialize(workspace: Workspace.new, workspace_targets: nil, prompt: nil, web_search: WebSearch.new, web_fetch: WebFetch.new, code_search: CodeSearch.new, web_search_enabled: nil, skills: nil, ask_user_question_enabled: nil, allowed_tool_names: nil, editor_prompt_session: nil, tool_output_compactor: ToolOutputCompactor.new, telemetry_logger: TelemetryLogger.new, context_budget_meter: nil, mcp_clients: nil, plugin_tools: [], typesafe_client: TypeSafeClient.new, tool_approval: nil, approval_for_allowed_tools: false, permission_policy: nil, hook_manager: nil, hook_context: nil, git_committer: nil)
118
+ def initialize(workspace: Workspace.new, workspace_targets: nil, prompt: nil, web_search: WebSearch.new, web_fetch: WebFetch.new, code_search: CodeSearch.new, web_search_enabled: nil, skills: nil, ask_user_question_enabled: nil, allowed_tool_names: nil, editor_prompt_session: nil, tool_output_compactor: ToolOutputCompactor.new, telemetry_logger: TelemetryLogger.new, context_budget_meter: nil, mcp_clients: nil, plugin_tools: [], typesafe_client: TypeSafeClient.new, tool_approval: nil, approval_for_allowed_tools: false, permission_policy: nil, hook_manager: nil, hook_context: nil, git_committer: nil, image_client: nil, generated_images: nil)
115
119
  @workspace = workspace
116
120
  @workspace_targets = workspace_targets || Tools::WorkspaceTargets.new(active: workspace)
117
121
  @prompt = prompt
@@ -135,6 +139,8 @@ module Kward
135
139
  @hook_manager = hook_manager
136
140
  @hook_context = hook_context
137
141
  @git_committer = git_committer
142
+ @generated_images = generated_images
143
+ @image_tool = Tools::GenerateImage.new(client: image_client, images: generated_images) if generated_images && image_client.respond_to?(:generate_codex_image)
138
144
  @mcp_clients = if mcp_clients
139
145
  mcp_clients
140
146
  elsif @allowed_tool_names
@@ -196,11 +202,12 @@ module Kward
196
202
  # @param tool_call [Hash] model tool call payload
197
203
  # @param conversation [Conversation] active conversation
198
204
  # @return [String] tool output content appended to the conversation
199
- def dispatch(tool_call, conversation, cancellation: nil)
205
+ def dispatch(tool_call, conversation, cancellation: nil, image_context: nil, &image_ready)
200
206
  cancellation&.raise_if_cancelled!
201
207
  name = ToolCall.name(tool_call)
202
208
  args = ToolCall.arguments(tool_call)
203
209
  tool = @tools[name]
210
+ execute = -> { execute_tool_with_hooks(tool, name, args, tool_call, conversation, cancellation, image_context: image_context, &image_ready) }
204
211
 
205
212
  original_content = if tool
206
213
  before_tool = run_hook("tool_call_before", conversation, payload: tool_payload(name, args, tool_call))
@@ -220,16 +227,16 @@ module Kward
220
227
  approval = permission_approval_result(tool_call, name, args, cancellation)
221
228
  if approval == :allow_for_session
222
229
  @permission_policy.allow_for_session!(name)
223
- execute_tool_with_hooks(tool, name, args, tool_call, conversation, cancellation)
230
+ execute.call
224
231
  elsif approval == true
225
- execute_tool_with_hooks(tool, name, args, tool_call, conversation, cancellation)
232
+ execute.call
226
233
  else
227
234
  approval_denied_content(approval, name)
228
235
  end
229
236
  elsif @approval_for_allowed_tools && tool_approval_denied?(tool_call, name, args, cancellation)
230
237
  "Declined: tool execution denied by user: #{name}"
231
238
  else
232
- execute_tool_with_hooks(tool, name, args, tool_call, conversation, cancellation)
239
+ execute.call
233
240
  end
234
241
  end
235
242
  else
@@ -266,6 +273,18 @@ module Kward
266
273
  # @param name [String, #to_s] exposed tool name
267
274
  # @return [Hash] source, display name, and optional MCP identity
268
275
  # @api public
276
+ def schemas_for(provider)
277
+ return @schemas if provider.to_s.casecmp?("codex")
278
+
279
+ @schemas.reject { |schema| ToolCall.name(schema) == Tools::GenerateImage::NAME }
280
+ end
281
+
282
+ def discard_generated_image(conversation, id)
283
+ @generated_images.discard(conversation, id)
284
+ rescue GeneratedImages::Error
285
+ nil
286
+ end
287
+
269
288
  def metadata_for(name)
270
289
  tool = @tools[name.to_s]
271
290
  return unknown_tool_metadata(name) unless tool
@@ -369,11 +388,15 @@ module Kward
369
388
  )
370
389
  end
371
390
 
372
- def execute_tool_with_hooks(tool, name, args, tool_call, conversation, cancellation)
391
+ def execute_tool_with_hooks(tool, name, args, tool_call, conversation, cancellation, image_context:, &image_ready)
373
392
  args = run_shell_before_hooks(name, args, tool_call, conversation, cancellation)
374
393
  run_file_change_before_hooks(name, args, tool_call, conversation, cancellation)
375
394
  run_mcp_before_hooks(name, args, tool_call, conversation, cancellation)
376
- content = tool.call(args, conversation, cancellation: cancellation)
395
+ content = if tool.is_a?(Tools::GenerateImage)
396
+ tool.call(args, conversation, cancellation: cancellation, **(image_context || {}), &image_ready)
397
+ else
398
+ tool.call(args, conversation, cancellation: cancellation)
399
+ end
377
400
  run_mcp_after_hooks(name, args, content, conversation)
378
401
  run_shell_after_hooks(name, args, content, conversation)
379
402
  run_file_change_after_hooks(name, args, content, conversation)
@@ -580,7 +603,7 @@ module Kward
580
603
  end
581
604
 
582
605
  def build_schema_tools
583
- tools = @tools.values_at(*CORE_TOOL_NAMES)
606
+ tools = @tools.values_at(*CORE_TOOL_NAMES, Tools::GenerateImage::NAME)
584
607
  tools << @tools["replace_editor_buffer"] if @tools["replace_editor_buffer"]
585
608
  tools << @tools["open_editor"] if @tools["open_editor"]
586
609
  tools << @tools["prepare_shell_command"] if @tools["prepare_shell_command"]
@@ -588,6 +611,7 @@ module Kward
588
611
  tools.concat(@tools.values_at("web_search", "fetch_content", "fetch_raw")) if web_search_available?
589
612
  tools.concat(@tools.values.select { |tool| tool.is_a?(Tools::MCPTool) })
590
613
  tools.concat(@tools.values.select { |tool| tool.is_a?(Tools::PluginTool) })
614
+ tools << @tools["datetime"] if @tools["datetime"]
591
615
  tools << @tools["typesafe_evaluate"] if @tools["typesafe_evaluate"]
592
616
  tools << @tools["read_skill"] if skills_available?
593
617
  tools << @tools["ask_user_question"] if ask_user_question_available?
@@ -596,6 +620,7 @@ module Kward
596
620
 
597
621
  def all_tools
598
622
  tools = core_tools
623
+ tools << @image_tool if @image_tool
599
624
  tools << Tools::GitCommit.new(committer: @git_committer, workspace_targets: @workspace_targets) if @git_committer
600
625
  (tools + [
601
626
  (Tools::TypeSafeEvaluate.new(client: @typesafe_client) if @typesafe_client&.available?),
@@ -603,7 +628,8 @@ module Kward
603
628
  Tools::FetchContent.new(web_fetch: @web_fetch),
604
629
  Tools::FetchRaw.new(web_fetch: @web_fetch),
605
630
  Tools::ReadSkill.new(skills: discovered_skills),
606
- Tools::AskUserQuestion.new(prompt: @prompt)
631
+ Tools::AskUserQuestion.new(prompt: @prompt),
632
+ Tools::DateTime.new
607
633
  ]).compact + mcp_tool_values + plugin_tool_values
608
634
  end
609
635
 
@@ -24,11 +24,13 @@ module Kward
24
24
  "web_search" => "web_search",
25
25
  "fetch_content" => "fetch_content",
26
26
  "fetch_raw" => "fetch_raw",
27
+ "generate_image" => "generate_image",
27
28
  "git_commit" => "git_commit",
28
29
  "read_skill" => "read_skill",
29
30
  "ask_user_question" => "ask_user_question",
30
31
  "open_editor" => "open_editor",
31
- "typesafe_evaluate" => "typesafe_evaluate"
32
+ "typesafe_evaluate" => "typesafe_evaluate",
33
+ "datetime" => "datetime"
32
34
  }.freeze
33
35
 
34
36
  module_function
@@ -1,5 +1,7 @@
1
1
  require_relative "../message_access"
2
2
  require_relative "../message_text"
3
+ require_relative "../config_files"
4
+ require_relative "turn_summary_formatter"
3
5
 
4
6
  # Namespace for the Kward CLI agent runtime.
5
7
  module Kward
@@ -11,6 +13,7 @@ module Kward
11
13
 
12
14
  def render
13
15
  lines = ["# Kward Session", ""]
16
+ stats_mode = ConfigFiles.transcript_turn_stats
14
17
  @conversation.messages.each do |message|
15
18
  role = MessageAccess.role(message)
16
19
  next if role == "system"
@@ -21,6 +24,11 @@ module Kward
21
24
  lines << ""
22
25
  lines << markdown_content(message_markdown_content(message, role))
23
26
  lines << ""
27
+ stats = TurnSummaryFormatter.render(MessageAccess.value(message, :turn_summary), mode: stats_mode)
28
+ unless stats.empty?
29
+ lines.concat(stats.lines.map { |line| "> #{line.chomp}" })
30
+ lines << ""
31
+ end
24
32
  end
25
33
  lines.join("\n")
26
34
  end
@@ -0,0 +1,93 @@
1
+ require_relative "../message_access"
2
+ require_relative "../terminal/text"
3
+
4
+ module Kward
5
+ # Shared plain-text presentation for terminal and exported turn summaries.
6
+ class TurnSummaryFormatter
7
+ def self.render(summary, mode: "compact", width: nil)
8
+ return "" unless summary.is_a?(Hash) && mode != "off"
9
+
10
+ new(summary).render(mode: mode, width: width)
11
+ end
12
+
13
+ def initialize(summary)
14
+ @summary = summary
15
+ end
16
+
17
+ def render(mode:, width:)
18
+ status = { "completed" => "Completed", "failed" => "Failed", "canceled" => "Cancelled" }.fetch(value(:status), "Finished")
19
+ parts = [status, format("%.1fs", value(:elapsedMs).to_f / 1_000), token_text]
20
+ parts << count_text(value(:modelRequests), "model request") if mode == "detailed"
21
+ parts << count_text(value(:toolCalls), "tool call")
22
+ lines = [fit(parts, width)]
23
+ if mode == "detailed" && usage.is_a?(Hash)
24
+ details = [
25
+ token_detail(:input_tokens, "Input"),
26
+ cached_detail,
27
+ token_detail(:output_tokens, "Output"),
28
+ token_detail(:reasoning_tokens, "Reasoning"),
29
+ token_detail(:cache_write_tokens, "Cache writes")
30
+ ].compact
31
+ lines << fit(details, width) unless details.empty?
32
+ end
33
+ lines.join("\n")
34
+ end
35
+
36
+ private
37
+
38
+ def value(key)
39
+ MessageAccess.value(@summary, key)
40
+ end
41
+
42
+ def usage
43
+ value(:usage)
44
+ end
45
+
46
+ def token_text
47
+ total = MessageAccess.value(usage, :total_tokens)
48
+ return "tokens unavailable" if value(:usageStatus) == "unavailable" || total.nil?
49
+
50
+ label = "#{number(total)} tokens"
51
+ label = "~#{label}" if MessageAccess.value(usage, :estimated)
52
+ label += " (partial)" if value(:usageStatus) == "partial"
53
+ label
54
+ end
55
+
56
+ def token_detail(field, label)
57
+ count = MessageAccess.value(usage, field)
58
+ return if count.nil?
59
+
60
+ text = "#{label} #{number(count)}"
61
+ partial_field?(field) ? "#{text} (partial)" : text
62
+ end
63
+
64
+ def partial_field?(field)
65
+ Array(MessageAccess.value(usage, :partial_fields)).include?(field.to_s)
66
+ end
67
+
68
+ def cached_detail
69
+ text = token_detail(:cache_read_tokens, "Cached")
70
+ return unless text
71
+
72
+ input = MessageAccess.value(usage, :input_tokens).to_f
73
+ cached = MessageAccess.value(usage, :cache_read_tokens).to_f
74
+ if value(:usageStatus) == "complete" && !partial_field?(:input_tokens) && !partial_field?(:cache_read_tokens) && input.positive? && cached <= input
75
+ text += format(" (%.0f%%)", 100 * cached / input)
76
+ end
77
+ text
78
+ end
79
+
80
+ def number(value)
81
+ value.to_f >= 1_000 ? format("%.1fk", value.to_f / 1_000) : value.to_i.to_s
82
+ end
83
+
84
+ def count_text(count, noun)
85
+ "#{count.to_i} #{noun}#{count.to_i == 1 ? '' : 's'}"
86
+ end
87
+
88
+ def fit(parts, width)
89
+ parts.pop while width && parts.length > 1 && TerminalText.width(parts.join(" · ")) > width
90
+ parts.join(" · ")
91
+ end
92
+ end
93
+ end
@@ -52,7 +52,8 @@ module Kward
52
52
  attachments: normalize_attachments(attachments, execution_profile: execution_profile),
53
53
  options: profile_options(options, execution_profile),
54
54
  streaming_behavior: streaming_behavior,
55
- execution_profile: execution_profile
55
+ execution_profile: execution_profile,
56
+ image_previews: false
56
57
  )
57
58
  { id: payload.fetch(:id), session_id: payload.fetch(:sessionId) }
58
59
  end
@@ -0,0 +1,68 @@
1
+ require_relative "message_access"
2
+
3
+ module Kward
4
+ # Collects reported usage for the main agent loop, independently of compaction
5
+ # and other auxiliary model calls. Missing usage is never treated as zero.
6
+ class TurnSummary
7
+ TOKEN_FIELDS = %w[input_tokens output_tokens total_tokens cache_read_tokens cache_write_tokens reasoning_tokens].freeze
8
+
9
+ def initialize
10
+ @model_requests = 0
11
+ @tool_calls = 0
12
+ @reported_requests = 0
13
+ @usage = {}
14
+ @field_requests = Hash.new(0)
15
+ @estimated = false
16
+ @retried = false
17
+ end
18
+
19
+ def model_request
20
+ @model_requests += 1
21
+ end
22
+
23
+ def tool_call
24
+ @tool_calls += 1
25
+ end
26
+
27
+ def retry
28
+ @retried = true
29
+ end
30
+
31
+ def record(message)
32
+ usage = MessageAccess.value(message, :usage)
33
+ return unless usage.is_a?(Hash)
34
+
35
+ total = MessageAccess.value(usage, :total_tokens)
36
+ @reported_requests += 1 if total.is_a?(Numeric) && total >= 0
37
+ TOKEN_FIELDS.each do |field|
38
+ value = MessageAccess.value(usage, field.to_sym)
39
+ next unless value.is_a?(Numeric) && value >= 0
40
+
41
+ @usage[field] = @usage.fetch(field, 0) + value
42
+ @field_requests[field] += 1
43
+ end
44
+ @estimated ||= MessageAccess.value(usage, :estimated) == true
45
+ end
46
+
47
+ def finish(status:, elapsed_ms:)
48
+ usage_status = if @reported_requests.zero?
49
+ "unavailable"
50
+ elsif @reported_requests == @model_requests && !@retried
51
+ "complete"
52
+ else
53
+ "partial"
54
+ end
55
+ usage = @usage.merge("estimated" => @estimated)
56
+ partial_fields = @usage.keys.reject { |field| @field_requests[field] == @model_requests && !@retried }
57
+ usage["partial_fields"] = partial_fields unless partial_fields.empty?
58
+ {
59
+ "status" => status,
60
+ "elapsedMs" => elapsed_ms,
61
+ "modelRequests" => @model_requests,
62
+ "toolCalls" => @tool_calls,
63
+ "usageStatus" => usage_status,
64
+ "usage" => @usage.empty? ? nil : usage
65
+ }
66
+ end
67
+ end
68
+ end