scout-ai 2.1.0 → 2.2.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 (186) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +133 -58
  3. data/README.md +2 -1
  4. data/VERSION +1 -1
  5. data/doc/Improvements.md +490 -148
  6. data/doc/Model.md +53 -10
  7. data/doc/StartHere.md +44 -19
  8. data/doc/developer/Architecture.md +25 -6
  9. data/doc/developer/Backends.md +207 -48
  10. data/doc/developer/ChatLifecycle.md +121 -20
  11. data/doc/developer/DelegationInternals.md +319 -33
  12. data/doc/developer/DesignPrinciples.md +205 -16
  13. data/doc/developer/PathEngine.md +628 -0
  14. data/doc/developer/PromptProcessing.md +332 -82
  15. data/doc/developer/Provenance.md +388 -40
  16. data/doc/developer/Sandbox.md +213 -0
  17. data/doc/user/BuildingAgents.md +130 -18
  18. data/doc/user/Cookbook.md +29 -8
  19. data/doc/user/CoreConcepts.md +7 -6
  20. data/doc/user/Delegation.md +166 -15
  21. data/doc/user/GettingStarted.md +20 -16
  22. data/doc/user/ManagingContext.md +155 -17
  23. data/doc/user/MultiAgentWorkflows.md +105 -15
  24. data/doc/user/Python.md +11 -1
  25. data/doc/user/RunningInference.md +90 -47
  26. data/doc/user/ToolCalling.md +134 -29
  27. data/doc/user/WritingChats.md +56 -27
  28. data/lib/scout/llm/agent/attach.rb +13 -17
  29. data/lib/scout/llm/agent/chat.rb +32 -0
  30. data/lib/scout/llm/agent/construction.rb +64 -0
  31. data/lib/scout/llm/agent/conversation.rb +304 -0
  32. data/lib/scout/llm/agent/delegate.rb +56 -238
  33. data/lib/scout/llm/agent/path/edit.rb +230 -0
  34. data/lib/scout/llm/agent/path/patch.rb +252 -0
  35. data/lib/scout/llm/agent/path/workflow_kinds.rb +175 -0
  36. data/lib/scout/llm/agent/path.rb +1777 -0
  37. data/lib/scout/llm/agent/save.rb +11 -9
  38. data/lib/scout/llm/agent/workflow.rb +77 -16
  39. data/lib/scout/llm/agent.rb +147 -31
  40. data/lib/scout/llm/ask.rb +28 -17
  41. data/lib/scout/llm/backends/anthropic.rb +1 -1
  42. data/lib/scout/llm/backends/bedrock.rb +3 -2
  43. data/lib/scout/llm/backends/default.rb +127 -34
  44. data/lib/scout/llm/backends/glm.rb +28 -1
  45. data/lib/scout/llm/backends/huggingface.rb +1 -1
  46. data/lib/scout/llm/backends/ollama.rb +1 -1
  47. data/lib/scout/llm/backends/openai.rb +7 -6
  48. data/lib/scout/llm/backends/openwebui.rb +14 -7
  49. data/lib/scout/llm/backends/relay.rb +8 -2
  50. data/lib/scout/llm/chat/agent_meta.rb +24 -60
  51. data/lib/scout/llm/chat/parse.rb +1 -1
  52. data/lib/scout/llm/chat/process/files.rb +10 -0
  53. data/lib/scout/llm/chat/process/meta.rb +5 -7
  54. data/lib/scout/llm/chat/process/tools.rb +104 -49
  55. data/lib/scout/llm/chat/prompt/epoch_tool_compactation.rb +355 -0
  56. data/lib/scout/llm/chat/prompt/inbox.rb +188 -0
  57. data/lib/scout/llm/chat/prompt/shorten_tools.rb +797 -13
  58. data/lib/scout/llm/chat/prompt/shorten_tools_epoch.rb +1 -365
  59. data/lib/scout/llm/chat/prompt/shorten_tools_epoch_increment.rb +1 -0
  60. data/lib/scout/llm/chat/prompt.rb +24 -10
  61. data/lib/scout/llm/chat/provenance/live.rb +1080 -0
  62. data/lib/scout/llm/chat/provenance/tokens.rb +386 -0
  63. data/lib/scout/llm/chat/provenance.rb +343 -676
  64. data/lib/scout/llm/chat.rb +8 -2
  65. data/lib/scout/llm/embed.rb +15 -3
  66. data/lib/scout/llm/image.rb +4 -1
  67. data/lib/scout/llm/mcp.rb +4 -2
  68. data/lib/scout/llm/request_context.rb +234 -0
  69. data/lib/scout/llm/sandbox.rb +263 -0
  70. data/lib/scout/llm/tools/call.rb +163 -42
  71. data/lib/scout/llm/tools/definition.rb +48 -0
  72. data/lib/scout/llm/tools/knowledge_base.rb +1 -0
  73. data/lib/scout/llm/tools/mcp.rb +50 -43
  74. data/lib/scout/llm/tools/workflow.rb +90 -20
  75. data/lib/scout/llm/tools.rb +14 -41
  76. data/lib/scout/model/decision/base.rb +43 -0
  77. data/lib/scout/model/decision/jev.rb +161 -0
  78. data/lib/scout/model/python/torch.rb +1 -1
  79. data/research/clear-tools-inherit.md +171 -0
  80. data/research/path-engine-dc1-dc2-dc3-fixes.md +279 -0
  81. data/research/path-kind-chat-role.md +96 -0
  82. data/research/path-kind-contract-fixes-engine.md +307 -0
  83. data/research/scout-ai-runtime-availability.md +65 -0
  84. data/research/subsys/README.md +127 -0
  85. data/research/subsys/agent-delegation.md +201 -0
  86. data/research/subsys/agent-society.md +275 -0
  87. data/research/subsys/agentworkflow.md +233 -0
  88. data/research/subsys/backends.md +221 -0
  89. data/research/subsys/chat.md +314 -0
  90. data/research/subsys/embed-image.md +244 -0
  91. data/research/subsys/entry-cli.md +253 -0
  92. data/research/subsys/model-ml.md +326 -0
  93. data/research/subsys/provenance.md +290 -0
  94. data/research/subsys/tools.md +334 -0
  95. data/scout-ai.gemspec +71 -27
  96. data/scout_commands/agent/ask +8 -7
  97. data/scout_commands/llm/abridged +40 -0
  98. data/scout_commands/llm/ask +9 -9
  99. data/scout_commands/llm/md +2 -0
  100. data/scout_commands/llm/prov +724 -59
  101. data/scout_commands/llm/word +4 -0
  102. data/share/word/reference.docx +0 -0
  103. data/test/integration/scout/model/decision/test_jev.rb +144 -0
  104. data/test/scout/llm/agent/test_attach.rb +117 -0
  105. data/test/scout/llm/agent/test_conversation.rb +407 -0
  106. data/test/scout/llm/agent/test_delegate.rb +209 -0
  107. data/test/scout/llm/agent/test_path.rb +1812 -0
  108. data/test/scout/llm/agent/test_path_edit.rb +908 -0
  109. data/test/scout/llm/agent/test_path_errors.rb +390 -0
  110. data/test/scout/llm/agent/test_path_filesystem.rb +532 -0
  111. data/test/scout/llm/agent/test_path_patch.rb +233 -0
  112. data/test/scout/llm/agent/test_path_promotion.rb +386 -0
  113. data/test/scout/llm/agent/test_path_workflow_integration.rb +665 -0
  114. data/test/scout/llm/agent/test_save.rb +70 -15
  115. data/test/scout/llm/agent/test_workflow.rb +130 -4
  116. data/test/scout/llm/backends/test_anthropic.rb +4 -4
  117. data/test/scout/llm/backends/test_bedrock.rb +4 -4
  118. data/test/scout/llm/backends/test_format_other.rb +43 -0
  119. data/test/scout/llm/backends/test_ollama.rb +2 -2
  120. data/test/scout/llm/backends/test_openwebui.rb +12 -8
  121. data/test/scout/llm/backends/test_reasoning.rb +114 -0
  122. data/test/scout/llm/chat/agent_meta_fixtures.rb +28 -27
  123. data/test/scout/llm/chat/prompt/test_epoch_tool_compactation.rb +612 -0
  124. data/test/scout/llm/chat/prov_plot_fixtures.rb +131 -0
  125. data/test/scout/llm/chat/test_agent_meta.rb +40 -80
  126. data/test/scout/llm/chat/test_agent_meta_provenance.rb +67 -28
  127. data/test/scout/llm/chat/test_agent_meta_tokens.rb +59 -8
  128. data/test/scout/llm/chat/test_agent_view.rb +178 -0
  129. data/test/scout/llm/chat/test_live_report.rb +282 -0
  130. data/test/scout/llm/chat/test_live_workload.rb +193 -0
  131. data/test/scout/llm/chat/test_parse.rb +32 -2
  132. data/test/scout/llm/chat/test_prompt.rb +411 -0
  133. data/test/scout/llm/chat/test_prov_cli.rb +310 -15
  134. data/test/scout/llm/chat/test_prov_cli_live.rb +152 -0
  135. data/test/scout/llm/chat/test_prov_plot.rb +213 -0
  136. data/test/scout/llm/chat/test_prov_timeline.rb +355 -0
  137. data/test/scout/llm/chat/test_provenance.rb +67 -22
  138. data/test/scout/llm/chat/test_provenance_index.rb +479 -0
  139. data/test/scout/llm/chat/test_society_view.rb +159 -0
  140. data/test/scout/llm/test_agent.rb +1 -1
  141. data/test/scout/llm/test_embed.rb +103 -1
  142. data/test/scout/llm/test_request_context.rb +299 -0
  143. data/test/scout/llm/test_sandbox.rb +249 -0
  144. data/test/scout/llm/tools/test_agent_pairing.rb +150 -0
  145. data/test/scout/llm/tools/test_call_delegation_conflict.rb +316 -0
  146. data/test/scout/llm/tools/test_definition.rb +332 -0
  147. data/test/scout/llm/tools/test_jobs_file.rb +211 -0
  148. data/test/scout/llm/tools/test_mcp.rb +37 -8
  149. data/test/scout/llm/tools/test_workflow.rb +45 -1
  150. data/test/scout/model/decision/test_jev.rb +453 -0
  151. data/test/scout/model/python/huggingface/causal/test_next_token.rb +7 -10
  152. data/test/scout/model/python/huggingface/test_causal.rb +11 -2
  153. data/test/scout/model/python/huggingface/test_classification.rb +5 -3
  154. data/test/scout/model/python/test_availability.rb +116 -0
  155. data/test/scout/model/python/test_torch.rb +54 -2
  156. data/test/support/availability.rb +72 -174
  157. data/test/support/fake_clients.rb +18 -9
  158. data/test/support/fixtures.rb +75 -6
  159. data/test/support/mock_backend.rb +9 -1
  160. data/test/support/test_fixtures.rb +156 -0
  161. data/test/test_helper.rb +14 -4
  162. metadata +70 -26
  163. data/research/ChatAnalyst-required-changes.md +0 -167
  164. data/research/agent-delegation-analysis.md +0 -810
  165. data/research/agent-meta-provenance-integration-plan.md +0 -622
  166. data/research/agent-workflow-analysis.md +0 -1120
  167. data/research/backends-analysis.md +0 -836
  168. data/research/chat-core-analysis.md +0 -946
  169. data/research/chatanalyst-provenance/00-baseline.md +0 -30
  170. data/research/chatanalyst-provenance/01-repo-map.md +0 -60
  171. data/research/chatanalyst-provenance/02-event-reconstruction.md +0 -55
  172. data/research/chatanalyst-provenance/03-duplication-evidence.md +0 -45
  173. data/research/chatanalyst-provenance/04-tooling-root-cause.md +0 -57
  174. data/research/chatanalyst-provenance/05-fix-plan.md +0 -46
  175. data/research/chatanalyst-provenance/07-critic-review.md +0 -25
  176. data/research/chatanalyst-provenance/final-report.md +0 -45
  177. data/research/chatanalyst-provenance/resumption.md +0 -37
  178. data/research/coding-philosophy-analysis.md +0 -928
  179. data/research/commands-analysis.md +0 -947
  180. data/research/multi-agent-patterns-analysis.md +0 -853
  181. data/research/prompt-strategies-analysis.md +0 -630
  182. data/research/prov-verbosity-fix-notes.md +0 -77
  183. data/research/provenance-analysis.md +0 -469
  184. data/research/provenance-continuation-accounting.md +0 -255
  185. data/research/synthesis-report.md +0 -487
  186. data/research/tools-system-analysis.md +0 -779
@@ -98,7 +98,9 @@ module LLM
98
98
 
99
99
  parameters = parameters.except(:previous_response_id) if FalseClass === parameters[:previous_response_id]
100
100
  parameters = parameters.except(:previous_response_id) if parameters[:previous_response] == 'false'
101
- client.responses.create(parameters: parameters.except(:previous_response))
101
+ Misc.insist([0.5, 2, 10, 60]) do
102
+ client.responses.create(parameters: parameters.except(:previous_response))
103
+ end
102
104
  end
103
105
 
104
106
  #{{{ FORMAT
@@ -207,7 +209,12 @@ module LLM
207
209
  when 'previous_response_id'
208
210
  nil
209
211
  else
210
- message
212
+ # ScoutCoder: format_messages output IS the provider request payload.
213
+ # Parsed/produced non-tool messages carry only {role, content} today,
214
+ # but strategy-injected bookkeeping flags (e.g. the compaction record's
215
+ # `compacted: true`) must never reach the wire: forward a copy with
216
+ # the two standard fields only, like format_tool_call/output rebuilds.
217
+ IndiferentHash.setup({ role: message[:role], content: message[:content] })
211
218
  end
212
219
  end
213
220
 
@@ -320,8 +327,6 @@ module LLM
320
327
  tools.merge!(LLM.tools messages)
321
328
  tools.merge!(LLM.associations messages)
322
329
 
323
- Log.medium "Tools: #{Log.fingerprint tools.keys}" if tools
324
-
325
330
  tools
326
331
  end
327
332
 
@@ -380,7 +385,8 @@ module LLM
380
385
  end
381
386
  end.compact
382
387
 
383
- tool_call_outputs = LLM.process_calls(tools, tool_calls, &block)
388
+ save_file = options[:save_file]
389
+ tool_call_outputs = LLM.process_calls(tools, tool_calls, save_file: save_file, request_context: options[:request_context], &block)
384
390
 
385
391
  output = response['output'].collect do |output|
386
392
  case output['type']
@@ -431,6 +437,7 @@ module LLM
431
437
  # distinguish two genuinely repeated, otherwise identical inferences.
432
438
  meta['inference_id'] = SecureRandom.uuid
433
439
  meta['provider_response_id'] = response['id'] if response['id']
440
+ meta['model'] = response['model'] if response['model']
434
441
  tokens.each do |name, value|
435
442
  session_name = name + '_s'
436
443
  Thread.current[session_name] = Thread.current[session_name].to_i + value.to_i
@@ -447,13 +454,46 @@ module LLM
447
454
  end
448
455
 
449
456
  def reasoning(response, current_meta = nil)
450
- begin
451
- reasoning_content = response.dig('choices', 0, 'message', 'reasoning_content')
452
- reasoning_content = reasoning_content.gsub("\n", ' ') if String === reasoning_content
453
- Log.medium "Reasoning:\n" + Log.color(:cyan, reasoning_content) if reasoning_content
454
- reasoning_content
455
- rescue
457
+ return unless Hash === response
458
+
459
+ readable = lambda { |value| String === value && !value.strip.empty? }
460
+ parts = []
461
+
462
+ if Array === response['output']
463
+ response['output'].each do |item|
464
+ next unless Hash === item && item['type'] == 'reasoning'
465
+ next unless Array === item['summary']
466
+
467
+ item['summary'].each do |summary|
468
+ next unless Hash === summary && summary['type'] == 'summary_text'
469
+ parts << summary['text'] if readable.call(summary['text'])
470
+ end
471
+ end
472
+ elsif Array === response['choices']
473
+ choice = response['choices'].first
474
+ message = choice['message'] if Hash === choice
475
+ return unless Hash === message
476
+
477
+ # Prefer the plain field so duplicated reasoning_details are not
478
+ # displayed twice. Keep the legacy reasoning_content spelling.
479
+ text = [message['reasoning_content'], message['reasoning']].find(&readable)
480
+ if text
481
+ parts << text
482
+ elsif Array === message['reasoning_details']
483
+ message['reasoning_details'].each do |detail|
484
+ next unless Hash === detail
485
+ text = case detail['type']
486
+ when 'reasoning.summary' then detail['summary']
487
+ when 'reasoning.text' then detail['text']
488
+ end
489
+ parts << text if readable.call(text)
490
+ end
491
+ end
456
492
  end
493
+
494
+ return if parts.empty?
495
+
496
+ parts.join("\n").gsub("\n", ' ')
457
497
  end
458
498
 
459
499
 
@@ -478,30 +518,64 @@ module LLM
478
518
  end
479
519
  end
480
520
 
521
+ def save_to_file(messages, options, save_file, exception: nil)
522
+ Open.write save_file Chat.print(messages) if exception
523
+ Open.write save_file + ".options", options.except(:messages, :tools).to_json
524
+ Open.write save_file + ".meta", current_meta.to_json
525
+ Log.warn "Messages and options saved in #{save_file}"
526
+ e.extend LLM::Backend::BackendException
527
+ e.chat tmpfile
528
+ end
529
+
481
530
  def ask(question, options = {}, &block)
482
531
  original_options = options.dup
532
+ request_context = options.delete(:request_context)
483
533
 
484
- return_messages, log_response, current_meta, relay, process, prompt_strategies, save_file = IndiferentHash.process_options options,
485
- :return_messages, :log_response, :current_meta, :relay, :process, :prompt_strategies, :save_file,
534
+ return_messages, return_response, return_tool_calls, log_response, current_meta, relay, process, prompt_strategies, save_file = IndiferentHash.process_options options,
535
+ :return_messages, :return_response, :return_tool_calls, :log_response, :current_meta, :relay, :process, :prompt_strategies, :save_file,
486
536
  return_messages: false, log_response: true
487
537
 
488
538
  messages = self.messages question, options
489
539
 
540
+ # {{{ Infer role and conversation from save_file
541
+ if String === save_file
542
+ parts = save_file.split(/\.files\//)
543
+ agent_chat_file = parts.pop
544
+ main_chat_file = parts * '.files/'
545
+ if Open.exists?(main_chat_file+'.info')
546
+ main_chat_job = Step.load(main_chat_file)
547
+ job_name = main_chat_job.clean_name == 'Default' ? main_chat_file.split('_').last[0..5] : main_chat_job.clean_name
548
+ main_chat_file = [[main_chat_job.workflow, main_chat_job.task_name].compact.collect{|p| p.to_s}*'/', job_name].compact * ' '
549
+ else
550
+ main_chat_file = File.basename(main_chat_file)
551
+ end
552
+
553
+ parts = agent_chat_file.split('/').reject{|p| p.end_with?('.society') }.reject{|p| p == 'agent.chat' }
554
+ agent_chat_file = parts * '/'
555
+
556
+ tag = [main_chat_file, agent_chat_file].compact * ' '
557
+ pre_message = Log.color(:blue, tag + ' ')
558
+ else
559
+ pre_message = ''
560
+ end
561
+
562
+ prompt = Chat.prepare_prompt(messages, prompt_strategies, save_file: save_file)
563
+ formatted_prompt = format_messages(prompt)
564
+ tools = tools(formatted_prompt, options)
565
+ Log.medium pre_message + "Tools: #{Log.fingerprint tools.keys}" if tools
566
+
567
+ request_context = RequestContext.augment(request_context, backend: (self::TAG rescue nil), model: options[:model])
568
+
569
+ # {{{ Send job package to remote server for processing
490
570
  if relay
491
- id = upload_messages(relay, messages, options)
571
+ id = upload_messages(relay, formatted_prompt, options)
492
572
  response = gather_response(relay, id)
493
573
  IndiferentHash.setup(response)
494
- formatted_prompt = format_messages(messages)
495
- tools = tools(formatted_prompt, options)
496
574
  else
497
-
498
575
  client = prepare_client options, messages
499
- prompt = Chat.prepare_prompt(messages, prompt_strategies)
500
- formatted_prompt = format_messages(prompt)
501
- tools = tools(formatted_prompt, options)
502
576
 
503
577
  response = begin
504
- Log.medium "Calling #{self}: #{Log.fingerprint(options.except(:tools))}}"
578
+ Log.medium pre_message + "Calling #{self}: #{Log.fingerprint(options.except(:tools))}}"
505
579
  query(client, formatted_prompt, tools, options)
506
580
  rescue Exception => e
507
581
  Log.debug 'Asking error. Options: ' + "\n" + JSON.pretty_generate(options.except(:tools))
@@ -530,24 +604,34 @@ module LLM
530
604
  return response
531
605
  end
532
606
 
533
- Log.debug "Response: #{Log.fingerprint response}"
607
+ Log.debug pre_message + "Response: #{Log.fingerprint response}"
534
608
 
535
609
  raise 'No response' if response.nil?
536
610
 
537
611
  reasoning = reasoning response
612
+ Log.medium pre_message + "Reasoning:\n" + Log.color(:cyan, reasoning) if reasoning
613
+
614
+ if log_response
615
+ meta = self.update_meta response, current_meta
616
+ meta['reas'] = reasoning if reasoning
617
+ meta['timestamp'] = timestamp
618
+ messages_with_meta = Chat.setup(messages + [{role: :meta, content: Chat.serialize_meta(meta)}])
619
+ end
620
+
538
621
 
539
622
  output = begin
540
- process_response messages, response, tools, options, &block
623
+ return response if return_response
624
+ process_response messages, response, tools, options.merge(save_file: save_file, request_context: request_context), &block
541
625
  rescue Exception => e
542
626
 
543
- Log.debug 'Processing response error. Options: ' + "\n" + JSON.pretty_generate(options.except(:tools))
627
+ Log.debug pre_message + 'Processing response error. Options: ' + "\n" + JSON.pretty_generate(options.except(:tools))
544
628
  begin
545
629
  tmpfile = TmpFile.tmp_file
546
630
  previous_response_id_error = options.delete
547
631
  if previous_response_id_error
548
632
  message.unshift IndiferentHash.setup({role: :previous_response_id, content: previous_response_id_error})
549
633
  end
550
- Open.write save_file + ".error", Chat.print(messages) if save_file
634
+ Open.write save_file + ".error", Chat.print(messages_with_meta) if save_file
551
635
  Open.write tmpfile + ".chat", Chat.print(messages)
552
636
  Open.write tmpfile + ".options", options.except(:messages, :tools).to_json
553
637
  Open.write tmpfile + ".meta", current_meta.to_json
@@ -558,16 +642,18 @@ module LLM
558
642
  end
559
643
  raise e
560
644
  ensure
561
- Open.write save_file, Chat.print(messages) if save_file
645
+ Open.write save_file, Chat.print(messages_with_meta) if save_file
562
646
  end
563
647
 
564
- if log_response
565
- meta = self.update_meta response, current_meta
566
- meta['reas'] = reasoning if reasoning
567
- meta['timestamp'] = timestamp
568
- end
569
648
 
570
- output = chain_tools messages, output, tools, options.merge(client: client, tools: tools, log_response: log_response, current_meta: meta, relay: relay, save_file: save_file)
649
+ return output if return_tool_calls
650
+ # ScoutCoder: IndiferentHash.process_options deletes the keys it
651
+ # extracts, so anything pulled out of `options` at the top of `ask`
652
+ # that must still hold on tool-call re-entry (here prompt_strategies,
653
+ # like save_file, relay, client, current_meta) has to be re-merged
654
+ # into the options passed to chain_tools; otherwise the recursive
655
+ # `ask` re-reads a nil and silently falls back to defaults.
656
+ output = chain_tools messages, output, tools, options.merge(client: client, tools: tools, log_response: log_response, current_meta: meta, relay: relay, save_file: save_file, prompt_strategies: prompt_strategies, request_context: request_context)
571
657
 
572
658
  if log_response && meta && meta.any?
573
659
  # The meta is about to become the first message of a segment that
@@ -609,16 +695,23 @@ module LLM
609
695
  end
610
696
 
611
697
  def image(question, options = {}, &block)
612
- messages = ask(question, options.merge({tools: [{type: 'image_generation'}], return_messages: true}), &block)
698
+ messages = self.messages question, options
699
+
700
+ parameters = IndiferentHash.pull_keys options, :image
613
701
 
702
+ client = prepare_client options, messages
703
+
704
+ options[:prompt] = messages.last[:content]
705
+ response = client.images.generate(parameters: options)
614
706
  base64_image = begin
615
- messages.select{|info| info[:role] == 'image' }.first['content']['result']
707
+ response.dig('data', 0, 'b64_json')
616
708
  rescue
617
709
  Log.warn 'Image error: ' + "\n" + JSON.pretty_generate(messages)
618
710
  raise $!
619
711
  end
620
712
  end
621
713
 
714
+
622
715
  def embed_query(client, text, parameters = {})
623
716
  parameters[:text] = text
624
717
  response = client.embeddings(parameters: parameters)
@@ -40,11 +40,38 @@ module LLM
40
40
  when 'previous_response_id'
41
41
  nil
42
42
  else
43
- message
43
+ # ScoutCoder: keep the wire payload key-clean; see the matching branch
44
+ # in Backend::ClassMethods#format_other (default.rb).
45
+ IndiferentHash.setup({ role: message[:role], content: message[:content] })
44
46
  end
45
47
  end
48
+
49
+ def image(question, options = {}, &block)
50
+ messages = self.messages question, options
51
+
52
+ parameters = IndiferentHash.pull_keys options, :image
53
+
54
+ client = prepare_client options.merge(model: 'glm-image'), messages
55
+
56
+ parameters = {
57
+ model: options[:model],
58
+ prompt: messages.last[:content],
59
+ size: '1280x1280',
60
+ quality: 'hd'
61
+ }.merge(parameters)
62
+
63
+ messages = client.images.generate(parameters: parameters)
64
+ base64_image = begin
65
+ messages.select{|info| info[:role] == 'image' }.first['content']['result']
66
+ rescue
67
+ Log.warn 'Image error: ' + "\n" + JSON.pretty_generate(messages)
68
+ raise $!
69
+ end
70
+ end
71
+
46
72
  end
47
73
 
74
+
48
75
  module GLM
49
76
  TAG = 'glm'
50
77
  DEFAULT_MODEL = 'glm-turbo'
@@ -156,7 +156,7 @@ module LLM
156
156
  end.compact
157
157
 
158
158
  if tool_calls.any?
159
- output.concat LLM.process_calls(tools, tool_calls, &block)
159
+ output.concat LLM.process_calls(tools, tool_calls, save_file: options[:save_file], request_context: options[:request_context], &block)
160
160
  elsif output.empty?
161
161
  output << IndiferentHash.setup(role: :assistant, content: '') if message.include?(:content)
162
162
  end
@@ -69,7 +69,7 @@ module LLM
69
69
 
70
70
  if tool_calls && tool_calls.any?
71
71
  tool_calls = tool_calls.collect { |tool_call| parse_tool_call(tool_call) }
72
- LLM.process_calls tools, tool_calls, &block
72
+ LLM.process_calls tools, tool_calls, save_file: options[:save_file], request_context: options[:request_context], &block
73
73
  else
74
74
  [message]
75
75
  end
@@ -13,11 +13,8 @@ module LLM
13
13
  parameters[:messages] = messages
14
14
  parameters[:tools] = format_tool_definitions(tools) if tools && tools.any?
15
15
 
16
- begin
16
+ Misc.insist([0.5, 2, 10, 60]) do
17
17
  client.chat(parameters: parameters)
18
- rescue
19
- Log.debug 'Input parameters: ' + "\n" + JSON.pretty_generate(parameters)
20
- raise $!
21
18
  end
22
19
  end
23
20
 
@@ -53,7 +50,11 @@ module LLM
53
50
  end
54
51
 
55
52
  def format_tool_output(message, last_id = nil)
56
- info = JSON.parse(message[:content])
53
+ info = begin
54
+ JSON.parse(message[:content])
55
+ rescue
56
+ {error: 'Error parsing tool output', message: $!.message}
57
+ end
57
58
  id = info.delete('call_id') || info.dig('id') || last_id
58
59
  info['role'] = 'tool'
59
60
  info['tool_call_id'] = id
@@ -91,7 +92,7 @@ module LLM
91
92
 
92
93
  if tool_calls && tool_calls.any?
93
94
  tool_calls = tool_calls.collect { |tool_call| parse_tool_call(tool_call) }
94
- LLM.process_calls(tools, tool_calls, &block)
95
+ LLM.process_calls(tools, tool_calls, save_file: options[:save_file], request_context: options[:request_context], &block)
95
96
  else
96
97
  [IndiferentHash.setup(message)]
97
98
  end
@@ -39,16 +39,23 @@ module LLM
39
39
  parameters[:model] ||= model
40
40
  parameters[:tools] = format_tool_definitions(tools) if tools && tools.any?
41
41
  parameters[:messages] = messages
42
- parameters[:verify_ssl] = false
43
- parameters[:timeout] = timeout.to_i if timeout
44
- parameters[:read_timeout] = timeout.to_i if timeout
45
- parameters[:open_timeout] = timeout.to_i if timeout
46
42
 
47
- headers = IndiferentHash.setup({ 'Authorization' => "Bearer #{key}", 'Content-Type' => 'application/json' })
48
- Misc.insist do
43
+ headers = IndiferentHash.setup({ 'Authorization' => "Bearer #{key}", 'Content-Type' => 'application/json'})
44
+ Misc.insist([0.5, 2, 10, 60]) do
49
45
  response = case method.to_sym
50
46
  when :post
51
- RestClient.post(url, parameters.to_json, headers)
47
+ request_options = {
48
+ method: :post,
49
+ url: url,
50
+ payload: parameters.to_json,
51
+ headers: headers
52
+ }
53
+
54
+ request_options[:timeout] = timeout.to_i if timeout
55
+ request_options[:open_timeout] = timeout.to_i if timeout
56
+ request_options[:read_timeout] = timeout.to_i if timeout
57
+ request_options[:verify_ssl] = false
58
+ RestClient::Request.execute(**request_options)
52
59
  else
53
60
  raise 'Get not supported'
54
61
  end
@@ -1,5 +1,6 @@
1
1
  require 'scout'
2
2
  require_relative '../chat'
3
+ require_relative '../request_context'
3
4
 
4
5
  module LLM
5
6
  module Relay
@@ -25,8 +26,13 @@ module LLM
25
26
  server = IndiferentHash.process_options options, :server
26
27
  server ||= Scout::Config.get :server, :ask_relay, :relay, :ask, env: 'ASK_ENDPOINT,LLM_ENDPOINT', default: :openai
27
28
 
28
- options[:question] = question
29
- TmpFile.with_file(options.to_json) do |file|
29
+ # Relay is an external JSON transport. Context is an explicit,
30
+ # optional field in that envelope and is projected before crossing
31
+ # the boundary.
32
+ request_context = RequestContext.project(options.delete(:request_context)) if options.key?(:request_context)
33
+ payload = options.merge(question: question)
34
+ payload[:request_context] = request_context if request_context
35
+ TmpFile.with_file(payload.to_json) do |file|
30
36
  id = upload(server, file)
31
37
  gather(server, id)
32
38
  end
@@ -28,23 +28,17 @@ module Chat
28
28
  # provenance analysis: plain Arrays and Hashes in and out, no wrapper
29
29
  # classes, no mutation of the inspected chat.
30
30
  #
31
- # Two receipt formats are accepted (the envelope is generic: any tool
32
- # output may carry one, so nothing here special-cases a tool name such as
33
- # `ask`):
31
+ # The envelope is generic: any tool output may carry one, so nothing here
32
+ # special-cases a tool name such as `ask`.
34
33
  #
35
- # meta (current): {"meta": [{"pt": 10, "inference_id": "w1"}, ...]}
34
+ # {"meta": [{"pt": 10, "inference_id": "w1"}, ...]}
36
35
  # Entries are ALREADY-DESERIALIZED field Hashes (no role/content
37
36
  # wrapper, no re-parsing). Evidence addresses use the [:meta, index]
38
37
  # suffix, mirroring the persisted key. raw_message is nil.
39
38
  #
40
- # agent_meta (legacy): {"agent_meta": [{"role": "meta", "content": "pt=10 ..."}, ...]}
41
- # Serialized meta messages; each content String is parsed with
42
- # Chat.parse_meta. Evidence addresses keep the [:agent_meta, index]
43
- # suffix and raw_message is {role: 'meta', content: <String>} so old
44
- # data stays addressable exactly as it always was.
45
- #
46
- # When both keys are present in one envelope the `meta` key wins (current
47
- # writer emits exactly one of the two).
39
+ # The legacy `agent_meta` key (serialized meta messages) is no longer
40
+ # accepted: envelopes carrying it are simply not receipts and produce no
41
+ # evidence at all.
48
42
 
49
43
  # One Hash per valid agent_meta entry found across the paired tool outputs
50
44
  # of the chat. Pairing is delegated to Chat.tool_calls; raw text is never
@@ -57,13 +51,11 @@ module Chat
57
51
  # meta: <IndiferentHash of meta fields>,
58
52
  # source: <String path or nil>,
59
53
  # output_address: <as returned by Chat.tool_calls>,
60
- # evidence_address: <output_address + [:agent_meta, index]> (legacy
61
- # entries; current-format entries use [:meta, index]),
54
+ # evidence_address: <output_address + [:meta, index]>,
62
55
  # call_id: ...,
63
56
  # tool_name: ...,
64
57
  # agent_meta_index: ...,
65
- # raw_message: {role: "meta", content: "..."} (legacy; nil for
66
- # current-format entries, which are born deserialized)
58
+ # raw_message: nil (entries are born deserialized)
67
59
  # }
68
60
  #
69
61
  # Malformed data is skipped. When the caller supplies an Array through the
@@ -71,8 +63,7 @@ module Chat
71
63
  #
72
64
  # {
73
65
  # origin: :agent_meta,
74
- # reason: :not_an_array | :not_a_hash | :invalid_role |
75
- # :invalid_content | :unparseable_meta | :empty_meta,
66
+ # reason: :not_an_array | :not_a_hash | :empty_meta,
76
67
  # source:, output_address:, evidence_address:,
77
68
  # call_id:, tool_name:,
78
69
  # agent_meta_index: (nil when the whole receipt value is malformed),
@@ -80,28 +71,23 @@ module Chat
80
71
  # raw_entry: <the malformed item as found>
81
72
  # }
82
73
  #
83
- # :empty_meta applies to current-format entries (deserialized field Hash
84
- # with no fields). Malformed receipt data is never silently reinterpreted
74
+ # :empty_meta applies to deserialized field Hashes with no fields.
75
+ # Malformed receipt data is never silently reinterpreted as provenance.
85
76
  # as provenance.
86
77
  def self.agent_meta_evidence(chat, source: nil, warnings: nil)
87
78
  tool_calls(chat, source: source).flat_map do |call|
88
79
  output_info = call[:output_info]
89
80
  next [] unless Hash === output_info
90
81
 
91
- # Key presence, not truthiness: an explicit `meta: false` or
92
- # `agent_meta: nil` is a present-but-malformed receipt and must warn,
93
- # while an absent key simply has no receipt at all.
94
- has_meta = output_info.key?('meta') || output_info.key?(:meta)
95
- has_agent_meta = output_info.key?('agent_meta') || output_info.key?(:agent_meta)
96
- next [] unless has_meta || has_agent_meta
82
+ # Key presence, not truthiness: an explicit `meta: false` or `meta:
83
+ # nil` is a present-but-malformed receipt and must warn, while an
84
+ # absent key simply has no receipt at all. The legacy `agent_meta` key
85
+ # is not accepted; envelopes carrying only it are not receipts.
86
+ next [] unless output_info.key?('meta') || output_info.key?(:meta)
97
87
 
98
- # Current writer emits exactly one of the two; when both are present
99
- # the current `meta` key wins and the legacy one is ignored.
100
- format = has_meta ? :meta : :agent_meta
101
88
  agent_meta = output_info['meta']
102
89
  agent_meta = output_info[:meta] if agent_meta.nil? && output_info.key?(:meta)
103
- agent_meta = output_info['agent_meta'] if format == :agent_meta && agent_meta.nil?
104
- agent_meta = output_info[:agent_meta] if format == :agent_meta && agent_meta.nil?
90
+ format = :meta
105
91
 
106
92
  add_warning = lambda do |reason, index, raw_entry|
107
93
  return unless Array === warnings
@@ -138,43 +124,21 @@ module Chat
138
124
  next nil
139
125
  end
140
126
 
141
- meta, raw_message =
142
- if format == :meta
143
- # Current format: entries are already-deserialized field Hashes.
144
- # No role/content wrapper and no re-parse; an entry with no
145
- # fields carries no evidence and is warned about.
146
- fields = IndiferentHash.setup(entry.dup)
147
- [fields, nil]
148
- else
149
- # Legacy format: serialized {role: 'meta', content: 'k=v ...'}
150
- # meta messages.
151
- role = entry['role'] || entry[:role]
152
- content = entry['content'] || entry[:content]
153
-
154
- if role.to_s != 'meta'
155
- add_warning.call(:invalid_role, index, entry)
156
- next nil
157
- end
158
-
159
- unless String === content
160
- add_warning.call(:invalid_content, index, entry)
161
- next nil
162
- end
163
-
164
- [parse_meta(content), { role: role, content: content }]
165
- end
127
+ # Entries are already-deserialized field Hashes. No role/content
128
+ # wrapper and no re-parse; an entry with no fields carries no
129
+ # evidence and is warned about.
130
+ meta = IndiferentHash.setup(entry.dup)
131
+ raw_message = nil
166
132
 
167
133
  if meta.empty?
168
- reason = format == :meta ? :empty_meta : :unparseable_meta
169
- add_warning.call(reason, index, entry)
134
+ add_warning.call(:empty_meta, index, entry)
170
135
  next nil
171
136
  end
172
137
 
173
138
  output_address = call[:output_address]
174
139
  # Without a source, Chat.tool_calls reports a bare message index; the
175
140
  # receipt address keeps the key-mirroring suffix so it stays truthful
176
- # to the persisted envelope ([:meta, index] for current data,
177
- # [:agent_meta, index] for legacy data).
141
+ # to the persisted envelope ([:meta, index]).
178
142
  evidence_address = if Array === output_address
179
143
  output_address + [format, index]
180
144
  else
@@ -153,7 +153,7 @@ module Chat
153
153
  if %w(option previous_response_id function_call function_call_output meta).include? message[:role].to_s
154
154
  message[:role].to_s + ": " + message[:content].to_s
155
155
  else
156
- re = Regexp.new(/^([a-z]+:)(\s)/ms)
156
+ re = Regexp.new(/^([a-z0-9_]+:)/ms)
157
157
  re = Regexp.new(re.source.encode(message[:content].to_s.encoding), re.options)
158
158
  message[:role].to_s + ":\n\n" +
159
159
  message[:content].to_s.gsub(re, '\\\\\1\2')
@@ -102,6 +102,16 @@ module Chat
102
102
  path = message[:content].to_s.strip
103
103
  Chat.allow_read_path(path)
104
104
  nil
105
+ elsif message[:role] == 'allow_job'
106
+ path = message[:content].to_s.strip
107
+ step = Step.load path
108
+ Chat.allow_job(step)
109
+ nil
110
+ elsif message[:role] == 'allow_read_job'
111
+ path = message[:content].to_s.strip
112
+ step = Step.load path
113
+ Chat.allow_read_job(step)
114
+ nil
105
115
  else
106
116
  message
107
117
  end
@@ -219,17 +219,15 @@ module Chat
219
219
  jobs.flat_map { |job| Chat.job_chat_files(job) }.uniq
220
220
  end
221
221
 
222
- # ScoutCoder: DUAL-LAYOUT filter (see Chat::DIRECT_LOG_CHAT_GLOBS). Agent
223
- # chats are the NEW layout files living under the job's own files dir
224
- # (.files/<name>.chat and .files/<name>.society/**, which no longer have a
225
- # log/ component) plus the LEGACY .files/log/ tree written by older
226
- # scout-ai. Other jobs' second-order .files trees are excluded by requiring
227
- # the file to be under THIS job's files dir.
222
+ # Filter (see Chat::DIRECT_LOG_CHAT_GLOBS). Agent chats live under the
223
+ # job's own files dir (.files/<name>.chat and .files/<name>.society/**).
224
+ # Other jobs' second-order .files trees are excluded by requiring the file
225
+ # to be under THIS job's files dir.
228
226
  def job_agent_chat_files
229
227
  jobs.flat_map do |job|
230
228
  job_files = job.path.to_s + '.files'
231
229
  Chat.provenance_chat_files(job, root_type: :job).select do |file|
232
- file.include?('.files/log/') || file.start_with?(job_files + '/')
230
+ file.start_with?(job_files + '/')
233
231
  end
234
232
  end.uniq
235
233
  end