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
@@ -1,26 +1,39 @@
1
1
  require_relative "../terminal/ansi"
2
+ require_relative "../terminal/text"
2
3
 
3
4
  # Namespace for the Kward CLI agent runtime.
4
5
  module Kward
5
6
  # Reduces safe, line-oriented PTY redraws to transcript-friendly text.
6
7
  class PtyTranscriptNormalizer
7
- HORIZONTAL_REDRAW_PATTERN = /\r|\e\[[0-9;]*[CDGK`]/.freeze
8
+ HORIZONTAL_REDRAW_PATTERN = /[\r\b]|\e\[[0-9;]*[CDGK`]/.freeze
8
9
 
9
- def self.normalize(text)
10
- text.split("\n", -1).map do |line|
11
- if line.match?(HORIZONTAL_REDRAW_PATTERN)
12
- Line.new(line).render
10
+ MAX_SCREEN_COLUMNS = 4096
11
+
12
+ def self.normalize(text, columns: 80, max_bytes: nil)
13
+ columns = columns.to_i.clamp(1, MAX_SCREEN_COLUMNS)
14
+ output = +""
15
+ text.each_line do |line|
16
+ body = line.delete_suffix("\n")
17
+ output << if body.match?(HORIZONTAL_REDRAW_PATTERN)
18
+ Line.new(body, columns).render
13
19
  else
14
- ANSI.sanitize_transcript(line)
20
+ ANSI.sanitize_transcript(body)
15
21
  end
16
- end.join("\n")
22
+ output << "\n" if line.end_with?("\n")
23
+ return nil if max_bytes && output.bytesize > max_bytes
24
+ end
25
+ output
17
26
  end
18
27
 
19
28
  # Applies the horizontal cursor controls accepted by AdaptivePtyOutputSink
20
29
  # without modeling a complete terminal screen.
21
30
  class Line
22
- def initialize(text)
31
+ WideGlyph = Struct.new(:text, :column, :width)
32
+ BLANK_CELL = " ".freeze
33
+
34
+ def initialize(text, columns)
23
35
  @text = text
36
+ @last_column = columns - 1
24
37
  @cells = []
25
38
  @cursor = 0
26
39
  end
@@ -29,7 +42,9 @@ module Kward
29
42
  ANSI.scan_escape_tokens(@text).each do |token|
30
43
  token[:escape] ? apply_escape(token[:text]) : write_text(token[:text])
31
44
  end
32
- @cells.join.rstrip
45
+ @cells.each_with_index.map do |cell, column|
46
+ cell.is_a?(WideGlyph) ? (cell.text if cell.column == column) : cell
47
+ end.join.rstrip
33
48
  end
34
49
 
35
50
  private
@@ -43,23 +58,25 @@ module Kward
43
58
  end
44
59
 
45
60
  def set_column(sequence)
46
- @cursor = [parameter(sequence, default: 1), 1].max - 1
61
+ @cursor = (parameter(sequence, default: 1) - 1).clamp(0, @last_column)
47
62
  end
48
63
 
49
64
  def move_cursor(sequence, direction)
50
65
  distance = [parameter(sequence, default: 1), 1].max
51
- @cursor = [@cursor + (distance * direction), 0].max
66
+ @cursor = (@cursor + (distance * direction)).clamp(0, @last_column)
52
67
  end
53
68
 
54
69
  def erase_line(sequence)
55
70
  case parameter(sequence, default: 0)
56
71
  when 1
57
- fill_to_cursor
58
- 0.upto(@cursor) { |index| @cells[index] = " " }
72
+ 0.upto([@cursor, @cells.length - 1].min) { |index| clear_cell(index) }
59
73
  when 2
60
74
  @cells.clear
61
75
  else
62
- @cells.slice!(@cursor..) if @cursor < @cells.length
76
+ if @cursor < @cells.length
77
+ clear_cell(@cursor)
78
+ @cells.slice!(@cursor..)
79
+ end
63
80
  end
64
81
  end
65
82
 
@@ -69,24 +86,51 @@ module Kward
69
86
  end
70
87
 
71
88
  def write_text(text)
72
- text.each_char do |character|
73
- case character
89
+ text.each_grapheme_cluster do |grapheme|
90
+ case grapheme
74
91
  when "\r"
75
92
  @cursor = 0
76
93
  when "\b"
77
94
  @cursor = [@cursor - 1, 0].max
78
95
  when "\t"
79
- @cursor = ((@cursor / 8) + 1) * 8
96
+ @cursor = [((@cursor / 8) + 1) * 8, @last_column].min
80
97
  else
81
- fill_to_cursor
82
- @cells[@cursor] = character
83
- @cursor += 1
98
+ write_grapheme(grapheme)
99
+ end
100
+ end
101
+ end
102
+
103
+ def write_grapheme(grapheme)
104
+ width = grapheme.ascii_only? ? 1 : TerminalText.width(grapheme)
105
+ if width.zero?
106
+ previous = @cells[@cursor - 1] if @cursor.positive?
107
+ if previous.is_a?(WideGlyph)
108
+ previous.text << grapheme
109
+ elsif previous
110
+ previous = previous.dup if previous.frozen?
111
+ @cells[@cursor - 1] = previous << grapheme
84
112
  end
113
+ return
114
+ end
115
+
116
+ fill_to_cursor
117
+ width.times { |offset| clear_cell(@cursor + offset) }
118
+ cell = width == 1 ? grapheme : WideGlyph.new(grapheme, @cursor, width)
119
+ @cells.fill(cell, @cursor, width)
120
+ @cursor += width
121
+ end
122
+
123
+ def clear_cell(column)
124
+ cell = @cells[column]
125
+ if cell.is_a?(WideGlyph)
126
+ @cells.fill(BLANK_CELL, cell.column, cell.width)
127
+ elsif cell
128
+ @cells[column] = BLANK_CELL
85
129
  end
86
130
  end
87
131
 
88
132
  def fill_to_cursor
89
- @cells.concat([" "] * (@cursor - @cells.length)) if @cursor > @cells.length
133
+ @cells.concat([BLANK_CELL] * (@cursor - @cells.length)) if @cursor > @cells.length
90
134
  end
91
135
  end
92
136
  end
@@ -33,6 +33,9 @@ module Kward
33
33
  model = model.to_s.strip
34
34
  raise "Model must be a non-empty string" if model.empty?
35
35
 
36
+ # RPC catalog IDs identify direct OpenAI; legacy config "openai"
37
+ # continues to mean Codex when read by ModelInfo.
38
+ provider = "OpenAI" if provider.to_s == "openai"
36
39
  update(ModelInfo.config_values_for_selection(provider, model))
37
40
  end
38
41
 
@@ -60,6 +60,7 @@ module Kward
60
60
  "sessions/export", "sessions/delete", "sessions/close", "sessions/transcript", "sessions/active"
61
61
  ].freeze
62
62
  TURN_METHODS = ["turns/start", "turns/cancel", "turns/status", "turns/events", "turns/list", "turns/listActive"].freeze
63
+ IMAGE_METHODS = ["images/fetch", "images/saveToProject", "images/discard"].freeze
63
64
  PLUGIN_CHAT_METHODS = ["pluginChats/list", "pluginChats/open", "pluginChats/transcript", "pluginChats/subscribe", "pluginChats/unsubscribe", "pluginChats/turns/start", "pluginChats/turns/cancel", "pluginChats/turns/status", "pluginChats/turns/events", "pluginChats/turns/list", "pluginChats/turns/listActive"].freeze
64
65
  MODEL_METHODS = ["models/list", "models/current", "models/set", "reasoning/set", "models/refresh"].freeze
65
66
  RUNTIME_METHODS = ["runtime/state", "runtime/stats"].freeze
@@ -102,6 +103,7 @@ module Kward
102
103
  prompts: PROMPT_METHODS,
103
104
  sessions: SESSION_METHODS,
104
105
  turns: TURN_METHODS,
106
+ images: IMAGE_METHODS,
105
107
  plugin_chats: PLUGIN_CHAT_METHODS,
106
108
  models: MODEL_METHODS,
107
109
  runtime: RUNTIME_METHODS,
@@ -388,6 +390,12 @@ module Kward
388
390
  @session_manager.transcript(session_id: params.fetch("sessionId"))
389
391
  when SESSION_METHODS[15]
390
392
  @session_manager.active_sessions
393
+ when IMAGE_METHODS[0]
394
+ @session_manager.fetch_generated_image(session_id: params.fetch("sessionId"), image_id: params.fetch("imageId"), offset: params.fetch("offset", 0))
395
+ when IMAGE_METHODS[1]
396
+ @session_manager.save_generated_image(session_id: params.fetch("sessionId"), image_id: params.fetch("imageId"), directory: params.fetch("directory", "."))
397
+ when IMAGE_METHODS[2]
398
+ @session_manager.discard_generated_image(session_id: params.fetch("sessionId"), image_id: params.fetch("imageId"))
391
399
  when TURN_METHODS[0]
392
400
  @session_manager.start_turn(
393
401
  session_id: params.fetch("sessionId"),
@@ -459,7 +467,8 @@ module Kward
459
467
  supportsToolCalls: true,
460
468
  supportsToolResults: true,
461
469
  supportsCompactionSummaries: true,
462
- supportsReasoningRestore: true
470
+ supportsReasoningRestore: true,
471
+ turnSummaries: { supported: true, event: "turnSummary", field: "turnSummary", modes: %w[off compact detailed], defaultMode: ConfigFiles.transcript_turn_stats, scope: "agentTurns" }
463
472
  },
464
473
  sessions: {
465
474
  mode: "explicit",
@@ -503,6 +512,11 @@ module Kward
503
512
  attachments: { supported: true, method: PLUGIN_CHAT_METHODS[5], encoding: "base64", mimeTypes: SessionManager::RPC_IMAGE_MIME_TYPES, maxBytes: SessionManager::RPC_ATTACHMENT_MAX_BYTES },
504
513
  types: @plugin_chat_manager.type_entries
505
514
  },
515
+ generatedImages: {
516
+ supported: true, provider: "Codex", tool: "generate_image", readyEvent: "imageReady",
517
+ progress: "toolCall", methods: IMAGE_METHODS, fetchChunkBytes: GeneratedImages::FETCH_CHUNK_BYTES,
518
+ downloads: "clientLocal", persistence: "temporary"
519
+ },
506
520
  turns: {
507
521
  mode: "async",
508
522
  perSessionConcurrency: 1,
@@ -538,6 +552,7 @@ module Kward
538
552
  assistantText: "assistantDelta",
539
553
  reasoning: { start: false, delta: true, boundary: true, end: false },
540
554
  modelRetry: { supported: true, event: "modelRetry" },
555
+ turnSummary: { supported: true, event: "turnSummary", terminalField: "summary" },
541
556
  steering: { supported: @session_manager.in_flight_steer_supported?, event: "turnSteered", mode: @session_manager.in_flight_steer_supported? ? "native" : "unsupported" },
542
557
  pluginCommands: { structuredResult: "pluginCommandResult" },
543
558
  tools: { call: true, update: true, result: true, normalizedMetadata: true, diffs: true, firstChangedLine: true, changedFiles: true, workspaceGuardrails: workspace_guardrails_enabled?, focusedContext: true, contextBudgetStats: true },
@@ -556,9 +571,16 @@ module Kward
556
571
  models: {
557
572
  supported: true,
558
573
  methods: MODEL_METHODS,
559
- fields: ["provider", "id", "name", "reasoning", "reasoningEffort", "contextWindow"],
574
+ fields: ["provider", "id", "name", "reasoning", "reasoningEffort", "contextWindow", "current", "defaultSelectable", "supportedParameters", "source"],
560
575
  scopedModels: false,
561
- refresh: { supported: true, method: MODEL_METHODS[4], providerParameter: true }
576
+ refresh: {
577
+ supported: true,
578
+ method: MODEL_METHODS[4],
579
+ providerParameter: true,
580
+ resultFields: ["models", "refresh"],
581
+ metadataFields: ["provider", "status", "fallbackUsed"],
582
+ statuses: ["success", "unsupported", "failed"]
583
+ }
562
584
  },
563
585
  runtime: {
564
586
  supported: true,
@@ -646,7 +668,7 @@ module Kward
646
668
  },
647
669
  startupResources: { supported: true, method: STARTUP_RESOURCE_METHODS.first },
648
670
  starterPack: { supported: false, reason: "cliOnlyInstallCommand" },
649
- shell: { supported: false, reason: "interactiveTuiOnly" },
671
+ shell: { supported: false, nativeScripting: false, history: false, lineEditing: false, programmableCompletion: false, promptFormat: false, mailNotifications: false, reason: "interactiveTuiOnly" },
650
672
  scratchpad: { supported: false, reason: "interactiveTuiOnly" },
651
673
  extensionUi: {
652
674
  question: { supported: true, notification: UI_QUESTION_NOTIFICATION, method: UI_METHODS.first, maxQuestions: 4, multiSelect: false, preview: false },
@@ -914,7 +936,7 @@ module Kward
914
936
  end
915
937
 
916
938
  def models_refresh(params)
917
- { models: @session_manager.refresh_models(provider: params["provider"]) }
939
+ @session_manager.refresh_models(provider: params["provider"], with_metadata: true)
918
940
  end
919
941
 
920
942
  def models_current
@@ -1,3 +1,4 @@
1
+ require "base64"
1
2
  require "securerandom"
2
3
  require "thread"
3
4
  require "time"
@@ -67,7 +68,7 @@ module Kward
67
68
  WORKER_STOP = Object.new.freeze
68
69
 
69
70
  RpcSession = Struct.new(:id, :workspace_root, :store, :session, :conversation, :agent, :tool_registry, :execution_profile, :prompt, :plugin_output, :queue, :worker, :running_turn_id, :footer_worker, :last_footer_text, :last_footer_segments, keyword_init: true)
70
- Turn = Struct.new(:id, :session_id, :input, :display_input, :status, :cancel_requested, :cancellation, :created_at, :started_at, :finished_at, :events, :next_sequence, :error, :streaming_behavior, :plugin_command_name, :plugin_arguments, :steering, :options, :tool_registry, :execution_profile, :mutex, keyword_init: true)
71
+ Turn = Struct.new(:id, :session_id, :input, :display_input, :status, :cancel_requested, :cancellation, :created_at, :started_at, :finished_at, :events, :next_sequence, :error, :streaming_behavior, :plugin_command_name, :plugin_arguments, :steering, :options, :tool_registry, :execution_profile, :summary, :mutex, keyword_init: true)
71
72
 
72
73
  # Creates an object for RPC session lifecycle and turn coordination.
73
74
  def initialize(
@@ -82,6 +83,7 @@ module Kward
82
83
  )
83
84
  @server = server
84
85
  @client = client
86
+ @generated_images = GeneratedImages.new
85
87
  @config_dir = config_dir
86
88
  @config_manager = config_manager
87
89
  @context_usage = context_usage
@@ -194,12 +196,34 @@ module Kward
194
196
  end
195
197
 
196
198
  def tool_schemas(session_id: nil)
197
- registry = if session_id
198
- fetch_session(session_id).tool_registry
199
- else
200
- build_tool_registry(Dir.pwd, nil)
201
- end
202
- { tools: registry.schemas }
199
+ session = fetch_session(session_id) if session_id
200
+ registry = session ? session.tool_registry : build_tool_registry(Dir.pwd, nil)
201
+ provider = session&.conversation&.provider || (@client.current_provider if @client.respond_to?(:current_provider))
202
+ { tools: registry.schemas_for(provider) }
203
+ end
204
+
205
+ def fetch_generated_image(session_id:, image_id:, offset: 0)
206
+ owner = fetch_session(session_id).conversation
207
+ image, bytes = @generated_images.fetch(owner, image_id, offset: offset)
208
+ next_offset = offset + bytes.bytesize
209
+ { id: image.id, filename: image.filename, mimeType: "image/png", size: image.size,
210
+ offset: offset, data: Base64.strict_encode64(bytes), nextOffset: (next_offset if next_offset < image.size) }
211
+ rescue GeneratedImages::Error => e
212
+ raise ArgumentError, e.message
213
+ end
214
+
215
+ def save_generated_image(session_id:, image_id:, directory: ".")
216
+ owner = fetch_session(session_id).conversation
217
+ { path: @generated_images.save_to_project(owner, image_id, directory) }
218
+ rescue GeneratedImages::Error => e
219
+ raise ArgumentError, e.message
220
+ end
221
+
222
+ def discard_generated_image(session_id:, image_id:)
223
+ owner = fetch_session(session_id).conversation
224
+ { discarded: @generated_images.discard(owner, image_id) }
225
+ rescue GeneratedImages::Error => e
226
+ raise ArgumentError, e.message
203
227
  end
204
228
 
205
229
  # Subscribes to frontend-neutral runtime notifications.
@@ -390,6 +414,8 @@ module Kward
390
414
  rpc_sessions = @mutex.synchronize { @sessions.values.dup }
391
415
  rpc_sessions.reverse_each { |rpc_session| close_rpc_session(rpc_session) }
392
416
  { closed: true }
417
+ ensure
418
+ @generated_images.close
393
419
  end
394
420
 
395
421
  def shutdown_plugins
@@ -409,7 +435,7 @@ module Kward
409
435
  # queue a follow-up, or steer the running turn when the active provider
410
436
  # supports native steering. The returned turn id is used for status,
411
437
  # cancellation, and event replay.
412
- def start_turn(session_id:, input:, streaming_behavior: nil, attachments: [], options: {}, context: nil, execution_profile: nil)
438
+ def start_turn(session_id:, input:, streaming_behavior: nil, attachments: [], options: {}, context: nil, execution_profile: nil, image_previews: true)
413
439
  rpc_session = fetch_session(session_id)
414
440
  execution_profile = validate_execution_profile(execution_profile)
415
441
  normalized_options = enforce_execution_profile_options(normalize_turn_options(options), execution_profile)
@@ -444,7 +470,7 @@ module Kward
444
470
  plugin_command_name: plugin_command&.name,
445
471
  plugin_arguments: plugin_arguments,
446
472
  options: normalized_options,
447
- tool_registry: scoped_tool_registry(rpc_session, normalized_options),
473
+ tool_registry: scoped_tool_registry(rpc_session, normalized_options, image_previews: image_previews),
448
474
  execution_profile: execution_profile,
449
475
  mutex: Mutex.new
450
476
  )
@@ -577,9 +603,14 @@ module Kward
577
603
  normalized
578
604
  end
579
605
 
580
- def refresh_models(provider: nil)
581
- @client.refresh_available_models(provider: provider) if @client.respond_to?(:refresh_available_models)
582
- available_models
606
+ def refresh_models(provider: nil, with_metadata: false)
607
+ if @client.respond_to?(:refresh_model_catalog)
608
+ refresh = @client.refresh_model_catalog(provider: provider)
609
+ elsif @client.respond_to?(:refresh_available_models)
610
+ @client.refresh_available_models(provider: provider)
611
+ end
612
+ models = available_models
613
+ with_metadata ? { models: models, refresh: refresh }.compact : models
583
614
  end
584
615
 
585
616
  def current_model
@@ -865,6 +896,7 @@ module Kward
865
896
  conversation.plugin_registry ||= plugin_registry if conversation.respond_to?(:plugin_registry)
866
897
  conversation.update_execution_profile_context!(rpc_session.execution_profile.prompt_context) if rpc_session.execution_profile
867
898
  rpc_session.session = session
899
+ @generated_images.discard_owner(rpc_session.conversation)
868
900
  rpc_session.conversation = conversation
869
901
  rebuild_session_tools(rpc_session)
870
902
  emit_footer_update(rpc_session)
@@ -1025,16 +1057,17 @@ module Kward
1025
1057
  value.to_s.empty? ? nil : value
1026
1058
  end
1027
1059
 
1028
- def scoped_tool_registry(rpc_session, options)
1060
+ def scoped_tool_registry(rpc_session, options, image_previews: true)
1029
1061
  names = scoped_tool_names(rpc_session, options)
1030
1062
  approval = tool_approval_callback(rpc_session, options)
1031
- return nil unless names || approval
1063
+ return nil if !names && !approval && image_previews
1032
1064
 
1033
1065
  build_tool_registry(
1034
1066
  rpc_session.workspace_root,
1035
1067
  rpc_session.prompt,
1036
1068
  allowed_tool_names: names,
1037
1069
  tool_approval: approval,
1070
+ image_previews: image_previews,
1038
1071
  hook_manager: lifecycle_hook_manager(rpc_session.workspace_root),
1039
1072
  hook_context: plugin_context(rpc_session, say_callback: lambda { |message| rpc_session.plugin_output << message.to_s })
1040
1073
  )
@@ -1111,7 +1144,7 @@ module Kward
1111
1144
  )
1112
1145
  end
1113
1146
 
1114
- def build_tool_registry(workspace_root, prompt, allowed_tool_names: nil, tool_approval: nil, hook_manager: nil, hook_context: nil)
1147
+ def build_tool_registry(workspace_root, prompt, allowed_tool_names: nil, tool_approval: nil, hook_manager: nil, hook_context: nil, image_previews: true)
1115
1148
  ToolRegistry.new(
1116
1149
  workspace: configured_workspace(workspace_root),
1117
1150
  prompt: prompt,
@@ -1119,6 +1152,8 @@ module Kward
1119
1152
  plugin_tools: plugin_registry.tools,
1120
1153
  tool_approval: tool_approval,
1121
1154
  approval_for_allowed_tools: !tool_approval.nil?,
1155
+ image_client: @client,
1156
+ generated_images: (image_previews ? @generated_images : nil),
1122
1157
  hook_manager: hook_manager,
1123
1158
  hook_context: hook_context
1124
1159
  )
@@ -1231,6 +1266,7 @@ module Kward
1231
1266
  @mutex.synchronize { @sessions.delete(rpc_session.id) }
1232
1267
  stop_worker(rpc_session)
1233
1268
  stop_footer_worker(rpc_session)
1269
+ @generated_images.discard_owner(rpc_session.conversation)
1234
1270
  end
1235
1271
 
1236
1272
  def stop_worker(rpc_session, wait: false)
@@ -1356,7 +1392,7 @@ module Kward
1356
1392
  memory_input = input.is_a?(PluginTurnRequest) ? input.to_s : input
1357
1393
  prepare_memory_context(rpc_session.conversation, memory_input) unless memory_disabled?(turn)
1358
1394
  rpc_session.agent.ask(input, display_input: display_input, cancellation: turn.cancellation, steering: turn.steering, options: turn.options || {}, tool_registry: turn.tool_registry) do |event|
1359
- next if turn.cancel_requested
1395
+ next if turn.cancel_requested && !event.is_a?(Events::TurnSummary)
1360
1396
 
1361
1397
  notify_plugin_transcript_event(rpc_session, event)
1362
1398
  handle_agent_event(turn, event)
@@ -1504,6 +1540,9 @@ module Kward
1504
1540
 
1505
1541
  def handle_agent_event(turn, event)
1506
1542
  case event
1543
+ when Events::TurnSummary
1544
+ turn.mutex.synchronize { turn.summary = event.summary }
1545
+ emit_turn_event(turn, "turnSummary", { summary: event.summary })
1507
1546
  when Events::ReasoningDelta
1508
1547
  emit_turn_event(turn, "reasoningDelta", { delta: event.delta })
1509
1548
  when Events::ReasoningBoundary
@@ -1522,6 +1561,9 @@ module Kward
1522
1561
  emit_turn_event(turn, "toolCall", normalized_tool_event_payload(event.tool_call))
1523
1562
  when Events::ToolUpdate
1524
1563
  emit_turn_event(turn, "toolUpdate", normalized_tool_update_event_payload(event.tool_call, event.content, elapsed_ms: event.elapsed_ms))
1564
+ when Events::ImageReady
1565
+ image = event.image
1566
+ emit_turn_event(turn, "imageReady", { id: image.id, toolCallId: ToolCall.id(event.tool_call), filename: image.filename, mimeType: "image/png", size: image.size })
1525
1567
  when Events::ToolResult
1526
1568
  emit_turn_event(turn, "toolResult", normalized_tool_result_event_payload(event.tool_call, event.content))
1527
1569
  when Events::Answer
@@ -1547,7 +1589,9 @@ module Kward
1547
1589
 
1548
1590
  turn.status = status
1549
1591
  turn.finished_at = now
1550
- append_turn_event_locked(turn, "turnFinished", { status: status, error: turn.error })
1592
+ payload = { status: status, error: turn.error }
1593
+ payload[:summary] = turn.summary if turn.summary
1594
+ append_turn_event_locked(turn, "turnFinished", payload)
1551
1595
  end
1552
1596
  return unless event
1553
1597
 
@@ -1626,6 +1670,7 @@ module Kward
1626
1670
  createdAt: turn.created_at,
1627
1671
  startedAt: turn.started_at,
1628
1672
  finishedAt: turn.finished_at,
1673
+ summary: turn.summary,
1629
1674
  error: turn.error
1630
1675
  }.compact
1631
1676
  end
@@ -17,7 +17,12 @@ module Kward
17
17
  end
18
18
 
19
19
  def normalize
20
- @messages.filter_map { |message| normalize_message(message) }
20
+ @messages.filter_map do |message|
21
+ normalized = normalize_message(message)
22
+ summary = MessageAccess.value(message, :turn_summary)
23
+ normalized = normalized.merge(turnSummary: summary) if normalized && summary.is_a?(Hash)
24
+ normalized
25
+ end
21
26
  end
22
27
 
23
28
  private
@@ -65,7 +70,10 @@ module Kward
65
70
 
66
71
  def normalize_assistant_message(message)
67
72
  content = reasoning_first_content(normalize_content(MessageAccess.content(message), preserve_thinking: true))
68
- content = response_item_content(message) if text_content_empty?(content)
73
+ response_content = response_item_content(message)
74
+ if text_content_empty?(content) || response_content.any? { |part| part[:type] == "text" }
75
+ content = response_content
76
+ end
69
77
  reasoning = normalize_reasoning_summary(message)
70
78
  content.unshift(reasoning) if reasoning && !thinking_content?(content)
71
79
  tool_calls(message).each do |tool_call|
@@ -176,11 +184,7 @@ module Kward
176
184
  text = response_message_item_text(item)
177
185
  next [] if text.empty?
178
186
 
179
- if ToolCall.value(item, :phase).to_s == "commentary"
180
- [{ type: "thinking", thinking: text }]
181
- else
182
- [{ type: "text", text: text }]
183
- end
187
+ [{ type: "text", text: text }]
184
188
  else
185
189
  []
186
190
  end
@@ -85,6 +85,7 @@ module Kward
85
85
  def attach(conversation)
86
86
  conversation.on_append = lambda { |message| append_message(message) }
87
87
  conversation.on_compact = lambda { |message| compact(message) }
88
+ conversation.on_turn_summary = lambda { |message, summary| append_turn_summary(message, summary) }
88
89
  conversation.on_tool_execution = lambda { |tool_call, content| append_tool_execution(tool_call, content) }
89
90
  conversation.on_runtime_update = lambda { |provider:, model:, reasoning_effort:| update_runtime(provider: provider, model: model, reasoning_effort: reasoning_effort) }
90
91
  conversation.on_system_message_change = lambda { |system_message| append_system_prompt_snapshot(system_message, reason: "changed") }
@@ -108,6 +109,18 @@ module Kward
108
109
  mark_modified(record)
109
110
  end
110
111
 
112
+ # Anchors display-only stats to an existing entry without advancing the leaf.
113
+ def append_turn_summary(message, summary)
114
+ record = {
115
+ type: "turn_summary",
116
+ targetId: message["id"] || message[:id],
117
+ timestamp: Time.now.utc.iso8601(3),
118
+ summary: summary
119
+ }
120
+ @store.append_record(@path, record)
121
+ mark_modified(record)
122
+ end
123
+
111
124
  # Persists normalized tool execution metadata alongside transcript messages.
112
125
  def append_tool_execution(tool_call, content)
113
126
  record = RPC::ToolEventNormalizer.new(tool_call, content: content).execution_record
@@ -461,7 +474,7 @@ module Kward
461
474
  records = records_from_file(resolve_session_path(path))
462
475
  labels = labels_by_target(records)
463
476
  timestamps = label_timestamps_by_target(records)
464
- records.select { |record| tree_entry_record?(record) }.map do |record|
477
+ entries_with_turn_summaries(records).map do |record|
465
478
  id = record["id"].to_s
466
479
  record.dup.tap do |copy|
467
480
  copy["resolvedLabel"] = labels[id] if labels.key?(id)
@@ -717,7 +730,7 @@ module Kward
717
730
 
718
731
 
719
732
  def build_session_tree(records)
720
- entries = records.select { |record| tree_entry_record?(record) }
733
+ entries = entries_with_turn_summaries(records)
721
734
  labels = labels_by_target(records)
722
735
  label_timestamps = label_timestamps_by_target(records)
723
736
  nodes = entries.each_with_object({}) do |entry, map|
@@ -749,8 +762,22 @@ module Kward
749
762
  entry.dup
750
763
  end
751
764
 
765
+ def entries_with_turn_summaries(records)
766
+ summaries = records.each_with_object({}) do |record, result|
767
+ result[record["targetId"]] = record["summary"] if record["type"] == "turn_summary"
768
+ end
769
+ records.select { |record| tree_entry_record?(record) }.map do |record|
770
+ summary = summaries[record["id"]]
771
+ if summary.is_a?(Hash) && record["message"].is_a?(Hash)
772
+ record.merge("message" => record["message"].merge("turn_summary" => summary))
773
+ else
774
+ record
775
+ end
776
+ end
777
+ end
778
+
752
779
  def branch_records(records)
753
- entries = records.select { |record| tree_entry_record?(record) && !record["id"].to_s.empty? }
780
+ entries = entries_with_turn_summaries(records).reject { |record| record["id"].to_s.empty? }
754
781
  by_id = entries.to_h { |record| [record["id"].to_s, record] }
755
782
  leaf_id = current_leaf_id(records)
756
783
  return [] if leaf_id.nil?
@@ -1,4 +1,5 @@
1
1
  require "shellwords"
2
+ require_relative "kwshrc"
2
3
  require_relative "../terminal/ansi"
3
4
  require_relative "../pty/local_command_runner"
4
5
  begin
@@ -13,7 +14,7 @@ module Kward
13
14
  class Kwsh
14
15
  Result = Struct.new(:output, :exit_status, :exit_shell, :clear, :open_editor_path, :interactive_command, :streamed, keyword_init: true)
15
16
  Completion = Struct.new(:range, :replacement, :candidates, keyword_init: true)
16
- BUILTINS = %w[alias capture cd pwd export source unset unalias clear exit logout pty].freeze
17
+ BUILTINS = Kwshrc::PROMPT_BUILTINS
17
18
  DEFAULT_SHELL = "/bin/sh"
18
19
  DEFAULT_TIMEOUT_SECONDS = 300
19
20
  DEFAULT_MAX_OUTPUT_BYTES = 1_048_576
@@ -111,6 +112,15 @@ module Kward
111
112
  Completion.new(range: token[:range], replacement: replacement, candidates: candidates)
112
113
  end
113
114
 
115
+ # Directory field completion uses shell matching but no shell quoting or expansion.
116
+ def complete_directory(input, cursor, root: @cwd)
117
+ prefix = input[0...cursor]
118
+ candidates = path_candidates(prefix, directories_only: true, literal: true, root: root)
119
+ return if candidates.empty?
120
+
121
+ Completion.new(range: 0...input.length, replacement: completion_replacement(prefix, candidates), candidates: candidates)
122
+ end
123
+
114
124
  def expand_alias(command, interactive: false)
115
125
  words = shell_words(command)
116
126
  return command if words.empty? || BUILTINS.include?(words.first)
@@ -246,19 +256,23 @@ module Kward
246
256
  @path_executables_cache = nil
247
257
  end
248
258
 
249
- def path_candidates(prefix, directories_only: false, quote: nil)
259
+ def path_candidates(prefix, directories_only: false, quote: nil, literal: false, root: nil)
250
260
  raw_dir, raw_base = split_path_prefix(prefix)
251
- dir = File.expand_path(unescape_path(raw_dir.empty? ? "." : raw_dir), @cwd)
261
+ base = raw_dir.empty? ? "." : raw_dir
262
+ dir = File.expand_path(literal ? base : unescape_path(base), @cwd)
252
263
  return [] unless File.directory?(dir)
264
+ return [] if root && !directory_under_root?(dir, root)
253
265
 
254
266
  Dir.children(dir).filter_map do |entry|
255
- next unless entry.start_with?(unescape_path(raw_base))
267
+ next unless entry.start_with?(literal ? raw_base : unescape_path(raw_base))
268
+ next if literal && entry.match?(/[[:cntrl:]]/)
256
269
 
257
270
  path = File.join(dir, entry)
258
271
  directory = File.directory?(path)
259
272
  next if directories_only && !directory
273
+ next if root && !directory_under_root?(path, root)
260
274
 
261
- completed = path_completion_candidate(raw_dir, entry, quote: quote)
275
+ completed = literal ? "#{raw_dir}#{entry}" : path_completion_candidate(raw_dir, entry, quote: quote)
262
276
  completed = "#{completed}/" if directory
263
277
  completed
264
278
  end.sort
@@ -266,6 +280,13 @@ module Kward
266
280
  []
267
281
  end
268
282
 
283
+ def directory_under_root?(path, root)
284
+ resolved = File.realpath(path)
285
+ resolved == root || resolved.start_with?(root.end_with?("/") ? root : "#{root}/")
286
+ rescue SystemCallError
287
+ false
288
+ end
289
+
269
290
  def path_completion_candidate(raw_dir, entry, quote: nil)
270
291
  completed = "#{raw_dir}#{entry}"
271
292
  return "#{quote}#{completed.gsub(quote, "\\#{quote}")}" if quote
@@ -429,7 +450,7 @@ module Kward
429
450
  end
430
451
 
431
452
  def self.valid_alias_name?(name)
432
- name.to_s.match?(/\A[A-Za-z_][A-Za-z0-9_-]*\z/) && !BUILTINS.include?(name.to_s)
453
+ Kwshrc.valid_alias_name?(name)
433
454
  end
434
455
 
435
456
  def run_expanded_command(command, cancellation: nil, &block)
@@ -539,7 +560,6 @@ module Kward
539
560
  return Result.new(output: "#{command_echo(command)}Usage: source <file>\n", exit_status: 2)
540
561
  end
541
562
 
542
- require_relative "kwshrc"
543
563
  path = Kwshrc.resolve_path(words[1], cwd: @cwd, env: @env)
544
564
  config = Kwshrc.read_file(path, env: @env)
545
565
  path_changed = config[:env].key?("PATH")