scout-ai 2.0.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 (185) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +135 -55
  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 +320 -34
  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 +402 -44
  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 +64 -0
  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 +79 -17
  39. data/lib/scout/llm/agent.rb +151 -27
  40. data/lib/scout/llm/ask.rb +37 -27
  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 +131 -32
  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 -52
  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 +352 -626
  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 +72 -26
  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 +845 -80
  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 +109 -22
  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 +200 -28
  127. data/test/scout/llm/chat/test_agent_meta_tokens.rb +112 -7
  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 +708 -13
  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 +71 -25
  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/synthesis-report.md +0 -487
  185. data/research/tools-system-analysis.md +0 -779
@@ -0,0 +1,233 @@
1
+ # 06 - AgentWorkflow mixin and job binding
2
+
3
+ > Investigation, not normative documentation. Verified behavior of the
4
+ > `AgentWorkflow` mixin, its seven helpers, `Workflow#chat_task`, the
5
+ > `Workflow.require_workflow` agent fallback and the job bindings they
6
+ > create. There is no dedicated developer page; the architecture table row
7
+ > in `doc/developer/Architecture.md` is the only maintained description.
8
+ > User-level context: `doc/user/MultiAgentWorkflows.md`,
9
+ > `doc/user/BuildingAgents.md`, `doc/developer/DelegationInternals.md`.
10
+
11
+ ## Scope
12
+
13
+ `lib/scout/llm/agent/workflow.rb` (184 lines) and the `LLM::Agent#job`
14
+ accessor it declares. Delegation *semantics* are owned by
15
+ `research/subsys/agent-delegation.md`.
16
+
17
+ ## Verified behavior
18
+
19
+ ### Layout and loading
20
+
21
+ ```
22
+ lib/scout/llm/agent/workflow.rb
23
+ 3 module AgentWorkflow; extend Workflow
24
+ 6-14 helper :chat
25
+ 16-18 helper :options
26
+ 20-22 helper :agent_options
27
+ 24-32 helper :tooling
28
+ 34-36 helper :tooling_intro
29
+ 38-110 helper :agent
30
+ 112-131 helper :log_agent
31
+ 134-162 module Workflow#chat_task
32
+ 164-166 alias require_workflow_old require_workflow
33
+ 168-177 def self.require_workflow(name, ...) - agent fallback
34
+ 182-184 class LLM::Agent; attr_accessor :job
35
+ ```
36
+
37
+ `AgentWorkflow` is required last in `lib/scout/llm/agent.rb`, so loading
38
+ scout-ai always applies the `Workflow` patch and the `job` accessor.
39
+
40
+ ### The seven helpers
41
+
42
+ | helper | behaviour |
43
+ |---|---|
44
+ | `chat` | memoized `@chat`; seeded from `recursive_inputs[:chat]`, `Chat.parse` for Strings, `[]` when nil, then `Chat.setup` |
45
+ | `options` | memoized `LLM.options(self.chat)` - the chat-embedded options |
46
+ | `agent_options` | `IndiferentHash.setup(options.except(:agent, :chat))` - strips the `agent`/`chat` keys before `LLM.load_agent` |
47
+ | `tooling` | memoized; **destructively extracts** the `tool`, `kb`, `mcp`, `introduce` roles out of `self.chat` via `Chat#remove_role` (which `reject!`s the receiver) and returns their concatenation |
48
+ | `tooling_intro` | `self.tooling.select { role == 'introduce' }` - the non-destructive half |
49
+ | `agent` | job binding at creation time (below) |
50
+ | `log_agent` | end-of-task sweep (below) |
51
+
52
+ Because `tooling` mutates `self.chat`, calling it (directly or through the
53
+ `agent` helper's default) permanently removes those messages from the job's
54
+ chat view. `tooling_intro` is the read-only half intended for specialists.
55
+
56
+ ### `Workflow#chat_task`
57
+
58
+ Defines one input `[:chat, :text, "Chat in Scout-AI chat-file format"]` and a
59
+ task of **type `:chat`** (extension `.chat`). The type is what makes
60
+ `Workflow::TYPE_EXTENSIONS[:chat]` meaningful: the job's persist path goes
61
+ through the chat driver, whose save arm computes `current_chat - start_chat`
62
+ for an `LLM::Agent` content.
63
+
64
+ Inside the task:
65
+
66
+ - `Chat.allow_path files_dir` whitelists the files dir before the block runs;
67
+ there is no eager `mkdir` - the directory appears lazily when the save
68
+ machinery writes into it.
69
+ - The user block is run via `self.instance_exec(&block)` with **no
70
+ arguments**; the wrapper's `|chat|` parameter is never forwarded, so blocks
71
+ declaring parameters get nil/empty and must read the chat through the
72
+ `chat` helper.
73
+ - Every successful result gets exactly one leading `meta: job=<short path>`
74
+ marker via `Chat.project`.
75
+
76
+ Return-value contract:
77
+
78
+ | block returns | outcome |
79
+ |---|---|
80
+ | `LLM::Agent` | if `current_chat` does not already end in an assistant message -> `agent.chat(return_messages: true)` (a real inference round); if it does -> no inference, result is the delta `current_chat - start_chat`. Either way `log_agent(agent)` runs and the delta is projected. |
81
+ | `Hash` | wrapped as `[hash]` |
82
+ | `Array` / `Chat` | used directly, roles preserved |
83
+ | `String` / `Integer` / `nil` | `Chat.project` fails with a `TypeError` (`no implicit conversion of Symbol into Integer`) and the job ends in `error` status |
84
+ | `raise ScoutException` | rescued: the result is an assistant message whose content is JSON `{exception: {...}, job: <short_path>}`; job status `done` |
85
+ | `raise` anything else | propagates; job `error` status |
86
+
87
+ When the block raises, `log_agent` never runs - a mid-round-created child
88
+ conversation survives only through its creation-time anchor.
89
+
90
+ ### The `agent` helper
91
+
92
+ ```ruby
93
+ helper :agent do |name = nil, chat: nil, options: nil, tooling: nil,
94
+ job_path_message: true, files: nil, **kwargs|
95
+ ```
96
+
97
+ 1. `options` defaults to `self.options`, `tooling` to `self.tooling`; extra
98
+ kwargs are merged over them with `IndiferentHash.add_defaults`.
99
+ 2. `agent = LLM.load_agent(name, agent_options(options))`. The named form
100
+ resolves through the five agent roots; an explicit *path* form returns
101
+ `true` from `Kernel#load`, not an Agent.
102
+ 3. **`agent.job = self`** - the Step is wired onto the agent *before* the
103
+ first chat/start call, so per-round auto-save, restart snapshots and
104
+ mid-round socialization all see a real parent anchor.
105
+ 4. `agent.start_chat.follow tooling` unless empty - the extracted tooling
106
+ seeds the new agent's start chat.
107
+ 5. `agent.save_file = LLM::Agent.canonical_chat_file(files_dir, name)` ->
108
+ `<job>.files/<name || 'agent'>.chat`.
109
+ 6. `job_path_message: true` (default) appends a system message
110
+ `Your current working directory is <Dir.pwd>. You are working through an
111
+ ask job with path <path> and files_dir <files_dir>.` With `false` the
112
+ message is absent. The code marks it "useful in multi-step inference
113
+ workflows but which may interfere with cache mechanisms".
114
+ 7. When the job `dependencies.any?`, a second system message lists
115
+ `rec_dependencies.collect(&:path)` - with the code's own misspelling
116
+ **"depencencies"**.
117
+ 8. `files:` - each path is tried as `file(path)` (under the job's files dir)
118
+ then as the raw path; existing ones are attached with
119
+ `agent.start_chat.file`. Plain Strings break
120
+ (`undefined method 'find' for String`); `Path.setup(...)` objects are the
121
+ supported form.
122
+ 9. With a non-empty `chat`: `other_jobs = chat.jobs`; any -> system message
123
+ `There are other jobs found in this chat:` plus the list. The chat is then
124
+ `reject!`-filtered of recycled prompts - messages starting with
125
+ `You have been assigned`, `This workflow job has the following`,
126
+ `There are other jobs found in this chat` - and followed into
127
+ `start_chat`.
128
+ 10. The helper body runs in the **job process** (fork); a test must read the
129
+ persisted `<job>.files/<name>.chat` after `produce` - in-process
130
+ instrumentation around `job.produce` never sees these lines.
131
+
132
+ ### `log_agent`
133
+
134
+ - `agent.save_file = LLM::Agent.canonical_chat_file(files_dir, agent_name)
135
+ if agent.save_file.nil?` - it only fills a missing anchor, never overrides
136
+ the one the `agent` helper assigned. `agent_name` defaults to `'agent'` and
137
+ "names the file, never a directory".
138
+ - `agent.save` - delegates to the Agent save machinery so every path
139
+ (`chat_task` jobs, CLI, plain `agent.save`) writes the identical canonical
140
+ layout: this agent's full chat at `<files_dir>/<name>.chat` and nested
141
+ conversations under `<files_dir>/<name>.society/<agent>/<conversation>/agent.chat`.
142
+ - `update_info :dependencies, dependencies.collect { |d| d.path.find }` -
143
+ rewrites the job info's dependency list with resolved paths, fixing
144
+ dependencies created *during* the block.
145
+ - returns the agent.
146
+
147
+ ### `Workflow.require_workflow` agent fallback
148
+
149
+ Patched onto `module Workflow` itself: on failure of the normal
150
+ `require_workflow`, it tries `LLM.load_agent(name).workflow` and re-raises
151
+ the original error if that also fails.
152
+
153
+ - Only the **named** form works: `LLM.load_agent(name)` returns an Agent
154
+ whose `#workflow` accessor holds the loaded module; the path form returns
155
+ `true` and the fallback then fails with the original workflow error.
156
+ - The returned module is a *fresh* object per call (`fallback_same_object`
157
+ false), distinct from the `@@agent_workflow` cache entry of a prior
158
+ `load_agent` call - whether anything relies on module identity across
159
+ those two entry points is unexplored.
160
+ - Purpose: agent directories (`Agent/<Name>` with `agent.rb`, `workflow.rb`,
161
+ `python/`) can be `require_workflow`-ed as if they were workflows;
162
+ `agent.rb` is `load`ed for side effects, `workflow.rb` goes through
163
+ `Workflow.require_workflow_file`, and a python agent directory through
164
+ `PythonWorkflow.load_directory`.
165
+
166
+ ### `LLM::Agent#job`
167
+
168
+ Declared both in `agent/workflow.rb:182-184` and in `lib/scout/llm/agent.rb`'s
169
+ accessor list. It is what lets `Agent#chat` route through `workflow.job(...)`
170
+ when a workflow with a matching task is attached.
171
+
172
+ ## Sharp edges and known issues
173
+
174
+ - **`tooling` is destructive** (F20, open): it extracts tool/kb/mcp/introduce
175
+ roles out of the job chat permanently. Undocumented; explains why
176
+ `tooling_intro` exists.
177
+ - **The "depencencies" misspelling is load-bearing** (F20, open): the
178
+ dependencies system message literally says "depencencies" and the recycle
179
+ filter matches that same misspelled prefix - fixing the spelling would
180
+ break the filter.
181
+ - **`chat_task` non-message returns fail opaquely** (open): a `String`/
182
+ `Integer`/`nil` return surfaces as a `TypeError` deep inside
183
+ `Chat.project`. A coercion or clearer error would be a cheap DX win.
184
+ - **MultiAgentWorkflows.md's first snippet would fail** (F20, open): it shows
185
+ `extend Workflow` + bare `chat_task` whose block calls `self.agent(...)`;
186
+ `self.agent` needs `include AgentWorkflow`. `chat_task` itself is patched
187
+ onto `Workflow`, so the task *registers* without the mixin, but the block
188
+ then cannot use the helpers.
189
+ - **No dedicated developer doc** for the mixin (F20, open): the architecture
190
+ row names only `chat_task`, `helper :agent` and `helper :log_agent`,
191
+ omitting `chat`/`options`/`agent_options`/`tooling`/`tooling_intro` and the
192
+ `require_workflow` patch.
193
+ - **Mix in with `include_workflow`, not `include`** (F20, open):
194
+ `include AgentWorkflow` alone does not copy the helper blocks into the
195
+ module's helpers hash (helpers are class-level state), so `Workflow#job`
196
+ would extend the Step with an empty `step_module` and `log_agent` would be
197
+ missing at run time. Documented verbatim in
198
+ `test/scout/llm/agent/test_workflow.rb:50-53`.
199
+
200
+ ## Open questions
201
+
202
+ - Whether anything relies on module identity between
203
+ `Workflow.require_workflow`'s fallback result and the `@@agent_workflow`
204
+ cache entry of a `load_agent` call for the same name.
205
+ - The `agent` helper's `files:` branch calls `file(path)` (job-relative)
206
+ before the raw path; the precedence is verified only by inspection.
207
+ - Documenting `tooling`'s destructive mutation next to `tooling_intro`.
208
+
209
+ ## Evidence
210
+
211
+ Provenance: derived from the 2026-09-10/11 Cortex subsystem studies, probed
212
+ against this checkout at HEAD `a992a33` plus the uncommitted 2026-09-11 fix
213
+ sweep (attach/MCP/embed/torch); no fix in this sweep touches this subsystem.
214
+
215
+ - Code: `lib/scout/llm/agent/workflow.rb` (all line references above);
216
+ `lib/scout/llm/agent.rb:174-232`; `lib/scout/llm/chat/persist.rb`;
217
+ `lib/scout/llm/chat/annotation.rb:150-155` (`remove_role`);
218
+ `lib/scout/llm/chat/process/meta.rb:408` (`Chat.project`);
219
+ scout-gear `lib/scout/workflow/definition.rb` (`Workflow::TYPE_EXTENSIONS`,
220
+ `include_workflow`).
221
+ - Tests read: `test/scout/llm/agent/test_workflow.rb` (the mixin/step_module
222
+ hazard and the socialize-then-ScoutException path are documented in its
223
+ comments).
224
+ - Probe receipts (Cortex artifacts `probe/agentworkflow_{surface,chat_task,
225
+ agent_helper}.rb`, run with `ruby -Ilib` from the repo root, asserting on
226
+ the persisted job files because the helper body runs in the job fork):
227
+ helper inventory and `Workflow` patch surface; `chat_task` task shape and
228
+ the full return-value table; block arity; `agent` helper keyword surface
229
+ and `job_path_message` on/off; the dependencies message and the
230
+ "depencencies" spelling; `files:` with Path vs String; the other-jobs
231
+ message and the three recycled prefixes; `log_agent` fallback anchor;
232
+ `require_workflow` fallback mechanics; `include` vs `include_workflow`
233
+ helper lists.
@@ -0,0 +1,221 @@
1
+ # 04 - LLM backend layer and inference loop
2
+
3
+ > Investigation, not normative documentation. Verified behavior of the
4
+ > backend registry, selection, the shared inference/tool loop and the
5
+ > per-provider adapters. Normative reference: `doc/developer/Backends.md`,
6
+ > `doc/user/RunningInference.md`.
7
+
8
+ ## Scope
9
+
10
+ `lib/scout/llm/backends/` (`default.rb` plus `openai`, `anthropic`,
11
+ `responses`, `vllm`, `openwebui`, `ollama`, `huggingface`, `relay`, `bedrock`,
12
+ `glm`), the dispatch layers `lib/scout/llm/ask.rb` and
13
+ `lib/scout/llm/embed.rb`, and the tool-loop glue in
14
+ `lib/scout/llm/tools/call.rb`.
15
+
16
+ ## Verified behavior
17
+
18
+ ### Registry and selection
19
+
20
+ `LLM.ask` resolves backend/endpoint in this order:
21
+
22
+ 1. `options[:endpoint]`; options are defaulted from
23
+ `Scout.etc.AI[<endpoint>].yaml` when that file exists. A non-empty
24
+ endpoint with no yaml raises `RuntimeError: Endpoint not found <name>`
25
+ **after** the ask is logged. Endpoint yaml keys are merged as *defaults*
26
+ (they never override explicit options) and may carry `backend`, `url`,
27
+ `key`, `model`, `provider`, ...
28
+ 2. `options[:backend]` (explicit) is used directly.
29
+ 3. Else `Scout::Config.get(:backend, :ask, :llm, env: 'ASK_BACKEND,LLM_BACKEND')`
30
+ with **default `:responses`** (ask.rb:71) - the default backend is the
31
+ OpenAI Responses API, not Chat Completions.
32
+ 4. The `case backend` ladder hard-codes `:openai`, `:anthropic`,
33
+ `:responses`, `:ollama`, `:vllm`, `:openwebui`, `:huggingface`, `:relay`,
34
+ `:bedrock`, `:glm`, each `require_relative`d lazily.
35
+ 5. Anything else -> `LLM::BACKENDS[backend]` runtime registry, else
36
+ `RuntimeError: Unknown backend: <name>`. `LLM::BACKENDS` starts empty in
37
+ library code (the test helper registers `:mock`) and is the plugin seam
38
+ through `LLM.register_backend(name, mod)`. There is **no** dynamic
39
+ `const_get` module resolution (F13).
40
+
41
+ **Model resolution is shared, not per-provider** (F13 config hazard):
42
+ `client_options` (default.rb:42-47) pulls `Scout::Config.get(:model, :url,
43
+ :key, ...)` with a single `tag: self::TAG` token and
44
+ `default_model: self::DEFAULT_MODEL`, so a `model` set for one backend leaks
45
+ to all of them through the `key:model` token unless the endpoint yaml pins it
46
+ per backend. Endpoint yaml files are the intended isolation mechanism.
47
+
48
+ `LLM.embed` mirrors the shape with `:openai`/`:responses` both mapping to
49
+ `LLM::OpenAI.embed`, plus `:ollama`, `:openwebui`, `:huggingface`, `:relay`;
50
+ default backend symbol `:embed`; registry fallback otherwise. There is no
51
+ `:anthropic`, `:vllm`, `:bedrock`, `:glm` branch in embed (see the
52
+ embed-image study).
53
+
54
+ ### The shared loop
55
+
56
+ `Backend::ClassMethods#ask` (default.rb:482-570) is a `while` over `query()`
57
+ results:
58
+
59
+ ```
60
+ prepare_client -> messages = Chat.chat(prompt) -> relay upload if options[:relay]
61
+ loop:
62
+ prompt = Chat.prepare_prompt(messages, prompt_strategies, save_file:)
63
+ formatted_prompt = format_messages(prompt)
64
+ tools = tools(formatted_prompt, options)
65
+ response = query(client, formatted_prompt, tools, parameters)
66
+ messages += output; if output contains function_call -> chain_tools(...)
67
+ ```
68
+
69
+ - One tool-calling round emits `function_call` (assistant-side request),
70
+ `function_call_output`, then the next `assistant` message, and issues one
71
+ client call per round. There is **no hard round counter**: the loop ends
72
+ when `query()` returns no tool calls, or when the prompt-strategy
73
+ compaction drops the tool outputs.
74
+ - `chain_tools` (default.rb:342-390) re-enters `ask` with
75
+ `messages + output` and re-merges the loop-scoped options
76
+ (`prompt_strategies`, `save_file`, `relay`, `client`, `current_meta`) on
77
+ each re-entry, so the prompt is re-prepared every round.
78
+ - Responses-API threading: with `backend: responses` and
79
+ `previous_response` not disabled, round N+1's request carries the previous
80
+ round's response id, and the final message list ends with a synthetic
81
+ `previous_response_id` message. `LLM.ask` additionally clears vs cleans
82
+ `previous_response_id` messages depending on whether
83
+ `backend == :responses && previous_response != false` (ask.rb:53-58).
84
+ - Error path: a `query()` raise propagates raw. **There is no retry/backoff
85
+ at the backend layer** for openai/anthropic/responses/vllm; the only retry
86
+ constructs are OpenWebUI's `Misc.insist` around the HTTP post (~4 small
87
+ retries) and the optional user-supplied `Agent#process_exception` hook,
88
+ which may `retry`.
89
+ - Relay mode: `options[:relay]` inside `Backend#ask` short-circuits to
90
+ `upload_messages`/`gather_response` (scp round-trips to
91
+ `<server>:.scout/var/query/`), while the standalone `LLM::Relay.ask` scps
92
+ options+question to `<server>:.scout/var/ask/` and polls
93
+ `reply/<id>.json`. Both are fire-and-poll, not streaming.
94
+ - Ask-level caching: the dispatch is wrapped in
95
+ `Persist.persist(endpoint, :json, prefix: "LLM ask", other:
96
+ options.merge(messages:), persist:, dir: Scout.var.cache.ask)` with
97
+ **persist defaulting to true** (env `ASK_PERSIST,LLM_PERSIST,PERSIST`).
98
+ The cache key includes the whole options hash plus the messages, so a
99
+ change of `model` or `tools` changes the key; `persist: false` bypasses.
100
+ `SCOUT_NO_ASK_CACHE` gates the cache (test usage).
101
+
102
+ ### Provider adapters
103
+
104
+ Composition pattern: each adapter is
105
+ `class << self; prepend XMethods; include Backend::ClassMethods; end`, with
106
+ MRO `XMethods -> (parent Methods) -> Backend::ClassMethods`.
107
+ `OpenWebUIMethods` *includes* `OpenAIMethods`; `VLLMMethods` includes
108
+ `ResponsesMethods`; `GLMAIMethods` is prepended over `OpenAIMethods`.
109
+
110
+ | backend | essentials |
111
+ |---|---|
112
+ | OpenAI (chat completions) | client `OpenAI::Client.new(api_version: 'v1', access_token:, uri_base:, request_timeout: 1200)`. Tool defs nested `{type: :function, function: {...}}`. `format_tool_call` -> assistant `tool_calls`; tool output -> `{role: 'tool', tool_call_id}`. Usage `pt/ct/tt` from `prompt_tokens/completion_tokens/total_tokens`, `cct/cwt` from the `*_details` sub-hashes. `process_response` raises on API error bodies. |
113
+ | Anthropic (messages) | client `Anthropic::Client.new(api_key:, base_url:)`; `extra_options` forces `max_tokens` default **1000**. Tool defs **flat** `name/description/input_schema` (parameters renamed), `type: 'function'` rewritten to `type: 'custom'`. Tool output is a **user-role content-block** message `{role: 'user', content: [{type: 'tool_result', tool_use_id:, content:}]}`. Usage `input_tokens/output_tokens` -> `pt/ct`, `cache_read_input_tokens` -> `cct`, `cache_creation_input_tokens` -> `cwt`, `tt` computed. `process_response` iterates content blocks: `text` -> assistant; `reasoning` and `web_search_call` skipped; unknown types raise. `embed_query` raises `'Anthropic does not offer embeddings'`. |
114
+ | Responses (default) | no overrides at all - the whole behaviour is `Backend::ClassMethods` on `client.responses.create(parameters:)` with `previous_response_id` threading. `DEFAULT_MODEL = 'gpt-5-nano'`. Tool calls arrive as `output[].type == 'function_call' | 'mcp_call'`. Usage `input_tokens/output_tokens/total_tokens`, `cct` from `input_tokens_details.cached_tokens`, `rt` from `output_tokens_details.reasoning_tokens`. |
115
+ | vLLM | includes `ResponsesMethods`; the only override is `parse_tool_call`, which strips a `channel<word>` fragment from the tool name (regex `[^a-zA-Z_]+channel[^a-zA-Z_]+[a-zA-Z_]+`) to undo vLLM name mangling. |
116
+ | OpenWebUI | `client()` returns a plain Hash spec, not an SDK client; `query()` posts `parameters.to_json` with `Authorization: Bearer <key>` + `Content-Type: application/json` to `<url>/chat/completions` via `RestClient.post`, `verify_ssl: false`, propagating `timeout/read_timeout/open_timeout` (default 12000). Wrapped in `Misc.insist`. Tool defs reuse the OpenAI shape; `parse_tool_call` synthesizes `id = name + '_' + Misc.digest(arguments)` when absent. |
117
+ | Ollama | client `Ollama.new(credentials: {address: url, bearer_token: key})` - the localhost:11434 default comes from the gem, not scout-ai. `query` sets `parameters[:stream] = false` explicitly (the only explicit stream token in the subsystem). Responses arrive as an Array of chunks; `process_response` flattens them and skips empty assistant messages. `update_meta` is overridden to return `{}` (no usage) and `reasoning` to nil - an override **must** return a Hash because `ask` assigns `meta['timestamp']` into it. `embed_query` posts to `api/embed`. |
118
+ | Huggingface | no client SDK: `prepare_client` builds a `CausalModel` through scout's python support, pulling `MODEL_OPTION_KEYS` (task/checkpoint/chat_template/generation_kwargs/tokenizer_args/trust_remote_code/torch_dtype/device_map/...) from options or `HUGGINGFACE_MODEL`/`HF_MODEL`. `DEFAULT_MODEL = nil`. `query` calls `client.chat(messages, formatted_tools, parameters)` and converts PyCall objects with `ScoutPython.dict2hash`. It has the **only** custom `tools()` override: it consumes `options[:tools]` (Array of provider definitions -> name-keyed Hash) and strips `role: 'tool'` messages carrying `tool_call_id`/`name` before deriving definitions from directives. |
119
+ | Relay | no provider: `ask` scps a JSON options file to a server and polls for the reply. No embed, no tool loop, no usage tracking. |
120
+ | Bedrock | **does not use the shared loop**. Standalone `ask` with its own while-loop, building either `type: :messages` (system messages concatenated into a `system:` parameter, only user messages kept) or `type: :prompt` (system+user concatenated into a single `prompt:` string), invoking `client.invoke_model(model_id:, body:)`, unwrapping `content[].tool_calls` and looping until no tool calls remain. Returns the joined text of `content[].text`, **not** a message list. Credentials via `LLM.get_url_config`/`AWS_REGION`/`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, model via `BEDROCK_MODEL_ID` (embed `BEDROCK_EMBED_MODEL_ID`, default `amazon.titan-embed-text-v1`). Because it bypasses `Backend::ClassMethods`, it gets none of the shared machinery: no meta/usage messages, no prompt strategies, no `save_file` threading. |
121
+ | GLM | prepends `GLMAIMethods` over `OpenAIMethods`; `format_other` adds `image` (base64 `image_url`), `pdf` (`input_file` with `file_data`/`file_url`), `websearch` (`{role: 'tool', content: {type: 'web_search_preview'}}`) and drops `previous_response_id` roles. `DEFAULT_MODEL = 'glm-turbo'`. Dispatched from `LLM.ask` but **not** from `LLM.embed`. |
122
+
123
+ ### Tool-call dispatch
124
+
125
+ `LLM.process_calls` (tools/call.rb) is called from each backend's
126
+ `process_response` with normalized `{arguments:, id:, name:}` hashes; the
127
+ registry lookup is `obj, definition = tools[function_name]`, and definition
128
+ `parameters.defaults` are merged into the arguments (see the tools study for
129
+ the override direction). Step results are batched through `Workflow.produce`
130
+ with the transient `.jobs` sidecar; `LLM::Agent` results are run in parallel
131
+ and paired by position. String content longer than `LLM.max_content_length`
132
+ (config `max_content_length`, tokens `:llm_tools,:tools,:llm,:ask`, default
133
+ **100_000**) is replaced by an exception payload with a fingerprint of the
134
+ content (tools/call.rb:10, 257-258).
135
+
136
+ ## Sharp edges and known issues
137
+
138
+ - **No retry/backoff despite doc claims** (F8, open): `doc/developer/Backends.md`
139
+ documents exponential backoff on transient errors; a `query` raise
140
+ propagates raw.
141
+ - **No streaming despite doc claims** (F9, open): `stream_results` appears
142
+ nowhere in lib/; the only stream token is ollama's `stream: false`.
143
+ `doc/user/RunningInference.md`'s "streaming is available but not enabled
144
+ by default" is likewise unsupported.
145
+ - **Unknown-backend module resolution does not exist** (F13, open): only
146
+ `LLM.register_backend` into `LLM::BACKENDS` works; the documented
147
+ `:my_backend` -> `LLM::MyBackend` resolution is absent.
148
+ - **Model config cross-talk** (F13, open): a `model` set for one backend
149
+ leaks to all via the shared `key:model` token unless endpoint yaml pins it.
150
+ - **Documented backend list incomplete** (F13, open): openwebui, huggingface,
151
+ relay, bedrock, glm are missing from Backends.md's table.
152
+ - **Stale loop bound** (F14, open): Backends.md's "MAX_TOOL_CALLS (40) via
153
+ `shorten_tools`" - the default strategy is
154
+ `shorten_tools_epoch_increment` (threshold 50 / keep 20 / cap 80), and the
155
+ strategy bounds *context size*, it is not a hard round limit.
156
+ - **Ollama localhost default is the gem's** (doc nuance): scout-ai passes
157
+ `address: url` verbatim and would pass nil without the ollama-ai gem's
158
+ `DEFAULT_ADDRESS`.
159
+ - **Bedrock is not a normal backend** (doc nuance): presenting it alongside
160
+ the others hides that it shares none of `Backend::ClassMethods`.
161
+ - **`parameters.defaults` stripping is mostly dead code** (F21, open):
162
+ `openai.rb:53` deletes at the *wrapper* level where `:parameters` is nil
163
+ (parameters live under `function:` after wrapping), so the scout-specific
164
+ subschema reaches the provider. Only huggingface digs correctly
165
+ (`definition.dig(:function, :parameters).delete(:defaults)`); ollama and
166
+ anthropic never strip it.
167
+ - **Embedding dispatch asymmetry**: no anthropic/vllm/bedrock/glm branch;
168
+ `:responses` aliases OpenAI; the registry fallback covers only registered
169
+ plugins. Dead/broken branches are catalogued in the embed-image study (F11).
170
+ - **`_s` session counters** observed starting from large values in probes
171
+ (shared process-level state); the exact reset semantics of `_s` vs `_c`
172
+ were not traced to their accumulation site.
173
+
174
+ ## Open questions
175
+
176
+ - Why `LLM.embed` omits bedrock/glm/anthropic branches while `LLM.ask`
177
+ dispatches them - `LLM::Bedrock.embed` is fully implemented but only
178
+ reachable by direct call. Oversight or deliberate?
179
+ - The relay paths differ (`Backend#ask` uses `.scout/var/query/`,
180
+ `LLM::Relay.ask` uses `.scout/var/ask/`); is one dead, or must a relay
181
+ server serve both?
182
+ - Huggingface's bespoke `tools()` override diverges from every other backend;
183
+ whether `tool:`/`kb:`/`association:` directives behave identically there
184
+ was verified only for the shared path.
185
+ - Whether any test exercises the glm `format_other` pdf/file handling (no glm
186
+ test file exists under `test/scout/llm/backends/`).
187
+ - Whether any provider rejects the `input_image` default shape on
188
+ Chat-Completions-only deployments (needs a live backend call).
189
+
190
+ ## Evidence
191
+
192
+ Provenance: derived from the 2026-09-10/11 Cortex subsystem studies, probed
193
+ against this checkout at HEAD `a992a33` plus the uncommitted 2026-09-11 fix
194
+ sweep (attach/MCP/embed/torch). The `LLM.embed` endpoint-YAML fix (F5) in
195
+ that sweep changed embed.rb only; the ask/image dispatch described here is
196
+ unchanged by it.
197
+
198
+ - Code: `lib/scout/llm/ask.rb:26-116` (resolution, cache, dispatch),
199
+ `:53-58` (previous_response_id clear/clean), `:71` (default `:responses`);
200
+ `lib/scout/llm/backends/default.rb:35-47` (client/client_options),
201
+ `:91-102` (responses query), `:155-235` (encode/format_other/tools
202
+ formatting), `:273-341` (format_messages, tools, messages),
203
+ `:342-390` (chain_tools), `:415-448` (update_meta), `:482-570` (ask loop),
204
+ `:584-617` (meta append, final output), `:619-637` (image, embed_query,
205
+ embed); `backends/{openai,anthropic,responses,vllm,openwebui,ollama,
206
+ huggingface,relay,bedrock,glm}.rb`; `lib/scout/llm/tools/call.rb:8-11,48+`;
207
+ `lib/scout/llm/embed.rb`.
208
+ - Tests: `test/scout/llm/backends/test_openwebui.rb` (headers),
209
+ `test/scout/llm/test_ask.rb`.
210
+ - Probe receipts (Cortex Observations, all offline via the
211
+ `Observation/probe` property): `scout_ai_backends_registry` (selection,
212
+ registry, plugin backends, endpoint yaml merge, error conditions),
213
+ `scout_ai_backends_loop` (shared loop, rounds, `chain_tools` re-merge,
214
+ error path, cache, max_content_length), `scout_ai_backends_adapters`
215
+ (client construction, tool-def mapping per provider, MRO, model
216
+ cross-talk), `scout_ai_backends_usage_meta` (usage normalization, ollama
217
+ override, vllm mangle), `scout_ai_backends_openwebui_cache` (request
218
+ construction against a local HTTP stub, ask-level cache semantics).
219
+ Durable claims derived from them: Cortex `claims/scout_ai_backend_selection.md`,
220
+ `claims/scout_ai_no_streaming_no_retry.md`,
221
+ `claims/scout_ai_epoch_compaction_defaults.md`.