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,304 @@
1
+ module LLM
2
+ class Agent
3
+
4
+ SOCIAL_INHERIT_MODES = %w[none tools conversation clear_tools].freeze
5
+ SOCIAL_AGENT_NAME = /\A[a-z_.-]+\z/i
6
+ SOCIAL_CONVERSATION_NAME = /\A[a-z0-9][a-z0-9_.-]*\z/i
7
+ SOCIAL_PRIVATE_OPTIONS = %i[
8
+ agent client current_meta format messages no_ask_override previous_response_id
9
+ process return_messages tool_choice tools
10
+ ].freeze
11
+
12
+ attr_accessor :society, :chats
13
+
14
+ # Open (or resume) one specialist conversation.
15
+ #
16
+ # This is the single conversation-open pipeline shared by every
17
+ # delegation entry point (`ask_agent`, `load_chat`, and the `ask` tool
18
+ # exposed by `socialize`). It runs five steps, in order:
19
+ #
20
+ # 1. Resolve the specialist: a pre-built `template:` wins when given;
21
+ # otherwise `load_agent(name, options)` normalizes/validates the name
22
+ # and returns the one immutable template cached in `@society`.
23
+ # 2. Seed: clone the template (`clone_social_agent`) and build the
24
+ # initial chat exactly as `start_social_chat` does: copy of the
25
+ # specialist's own start_chat, then the inherited context selected by
26
+ # `inherit` (none = empty, tools = caller task tooling, conversation =
27
+ # caller task conversation; clear_tools seeds like conversation and,
28
+ # on continuation in `ask_conversation`, additionally drops earlier
29
+ # tool-call traces from the model context), then the `preamble:`
30
+ # messages, then `agent.start(initial_chat)`. With `adopt: :current` the template's
31
+ # own progress (current_chat minus its start_chat) is folded in right
32
+ # after the start_chat copy, before the inherited context.
33
+ # 3. Anchor: `agent.save_file = anchor || society_save_file(name,
34
+ # conversation)`, assigned at creation so auto-save and restart
35
+ # snapshots apply from the first round.
36
+ # 4. Register: `@chats[social_chat_key(name, conversation)] ||= agent`.
37
+ # Identity is scoped per specialist; `inherit` is only used when the
38
+ # conversation is first created.
39
+ # 5. Restart: when the conversation already exists and `restart:` is
40
+ # true, re-branch it in place (keep start_chat, drop what follows);
41
+ # no new key is minted.
42
+ #
43
+ # `job:` is reserved for later workflow anchoring and is accepted and
44
+ # ignored for now.
45
+ def open_conversation(name, conversation: 'default', inherit: 'tools',
46
+ options: {}, preamble: nil, anchor: nil,
47
+ restart: false, template: nil, adopt: nil, job: nil)
48
+ agent_name = normalize_social_agent_name(name)
49
+ conversation = normalize_social_conversation_name(conversation)
50
+ inherit = normalize_social_inherit(inherit)
51
+ adopt = normalize_social_adopt(adopt)
52
+
53
+ @chats ||= {}
54
+ key = social_chat_key(agent_name, conversation)
55
+
56
+ agent = @chats[key]
57
+
58
+ if agent
59
+ # Restart an existing conversation in place: Agent#start snapshots
60
+ # the prior chat (when a save_file is configured) and re-branches
61
+ # from start_chat, dropping everything that followed it.
62
+ agent.start if restart
63
+ return agent
64
+ end
65
+
66
+ # The construction primitive receives the anchor before start, so the
67
+ # first branch has the same save/restart behavior as later rounds.
68
+ agent = start_social_chat(agent_name, options, inherit, template: template,
69
+ preamble: preamble, adopt: adopt,
70
+ anchor: anchor || society_save_file(agent_name, conversation))
71
+
72
+ @chats[key] ||= agent
73
+ end
74
+
75
+ # Ask one specialist with a plain-text prompt, opening (or resuming) the
76
+ # conversation first. `conversation: nil` is the one-shot form: it maps
77
+ # to the 'default' slot AFTER normalization, exactly like `ask_agent`.
78
+ # The prompt must be a String; role-looking text cannot smuggle control
79
+ # messages because the prompt is appended with Agent#user.
80
+ def ask_conversation(name, prompt, conversation: nil, inherit: 'tools',
81
+ options: {}, preamble: nil, anchor: nil,
82
+ restart: false, template: nil, adopt: nil, job: nil)
83
+ raise ParameterException, 'The delegated prompt must be a String' unless String === prompt
84
+
85
+ conversation = 'default' if conversation.nil?
86
+
87
+ # Whether the conversation slot already holds a live agent: the
88
+ # continuation branch. `open_conversation` consults `inherit` only
89
+ # at creation, so the clear_tools marker (a context-only policy on
90
+ # the EXISTING chat) is appended here, immediately before the new
91
+ # user prompt. See research/clear-tools-inherit.md rules 2/4/5.
92
+ existing = conversation_agent(social_chat_key(name, conversation))
93
+
94
+ agent = open_conversation(name, conversation: conversation, inherit: inherit,
95
+ options: options, preamble: preamble,
96
+ anchor: anchor, restart: restart,
97
+ template: template, adopt: adopt,
98
+ job: job)
99
+
100
+ # The clear_tools marker is context-only policy on the EXISTING chat,
101
+ # so it applies to a plain continuation only: creation and restart
102
+ # have no earlier bouts to clear (rule 5).
103
+ if existing && !restart
104
+ agent.current_chat.message :clear_tools, true if inherit == 'clear_tools'
105
+ elsif inherit == 'clear_tools'
106
+ Log.low "Inheritance policy 'clear_tools' has no continuation to clear; seeding conversation '#{conversation}' like 'conversation'"
107
+ end
108
+
109
+ agent.request_context = IndiferentHash.add_defaults(agent.request_context || {}, self.request_context || {})
110
+ agent.user(prompt)
111
+
112
+ agent
113
+ end
114
+
115
+ # The live conversation registered under a society key
116
+ # (`social_chat_key(name, conversation)` => `"<name>/<conversation>"`).
117
+ # Returns nil when no such conversation is open. Delegation callers that
118
+ # hold their own agent object can use this to reach the conversation
119
+ # holder that actually advanced: the pipeline clones instead of mutating
120
+ # the passed object.
121
+ def conversation_agent(key)
122
+ (@chats || {})[key]
123
+ end
124
+
125
+ private
126
+
127
+ # --- name/policy normalization -------------------------------------------
128
+
129
+ def normalize_social_agent_name(agent_name)
130
+ agent_name = agent_name.to_s if Symbol === agent_name
131
+ unless String === agent_name && SOCIAL_AGENT_NAME.match?(agent_name)
132
+ raise ParameterException,
133
+ 'Agent name must contain only letters, dots, underscores, or hyphens'
134
+ end
135
+ agent_name
136
+ end
137
+
138
+ def normalize_social_conversation_name(conversation)
139
+ conversation = conversation.to_s if Symbol === conversation
140
+ unless String === conversation && SOCIAL_CONVERSATION_NAME.match?(conversation)
141
+ raise ParameterException,
142
+ 'Conversation identifier must start with a letter or number and contain only letters, numbers, dots, underscores, or hyphens'
143
+ end
144
+ conversation
145
+ end
146
+
147
+ def normalize_social_inherit(inherit)
148
+ inherit = inherit.to_s
149
+ return inherit if SOCIAL_INHERIT_MODES.include?(inherit)
150
+
151
+ raise ParameterException,
152
+ "Unknown inheritance policy #{inherit.inspect}; expected one of #{SOCIAL_INHERIT_MODES * ', '}"
153
+ end
154
+
155
+ # `adopt:` is nil (nothing is folded in) or :current (the template's own
156
+ # progress becomes part of the seed).
157
+ def normalize_social_adopt(adopt)
158
+ return nil if adopt.nil?
159
+ return :current if adopt == :current || adopt.to_s == 'current'
160
+
161
+ raise ParameterException,
162
+ "Unknown adoption policy #{adopt.inspect}; expected nil or :current"
163
+ end
164
+
165
+ # --- society caches ------------------------------------------------------
166
+
167
+ def social_chat_key(agent_name, conversation)
168
+ "#{agent_name}/#{conversation}"
169
+ end
170
+
171
+ def society_save_file(agent_name, conversation)
172
+ # ScoutCoder: the society directory is derived with the CANONICAL rule
173
+ # (Agent.society_dir_for / Agent#society_dir), never by string
174
+ # substitution here. An earlier version did
175
+ # `save_file.sub(/\.chat/, '.society')`: the sub had no anchor, so it
176
+ # replaced the FIRST '.chat' occurrence and a CLI-shaped save_file like
177
+ # `cli.chat.files/agent.chat` turned into
178
+ # `cli.society.files/agent.chat/...`, growing a second `.files` tree
179
+ # instead of `cli.chat.files/agent.society/...`.
180
+ # society_dir_for is the single source of truth for the root
181
+ # (name-derived) rule; society_dir adds the location rule for nested
182
+ # chats.
183
+ #
184
+ # save.rb simply does not auto-save without a save_file; mirror that
185
+ # here instead of raising on nil (a society conversation started by an
186
+ # agent with no save_file just never persists).
187
+ return nil if save_file.nil?
188
+
189
+ File.join(society_dir(save_file), agent_name.to_s, conversation.to_s, SOCIETY_CHAT_FILE)
190
+ end
191
+
192
+ # Provider session state and executable Ruby tool objects belong to the
193
+ # caller. Model/backend defaults may flow to specialists, but capabilities
194
+ # are inherited only through the specialist start_chat or an explicit
195
+ # declarative inheritance policy.
196
+ def social_agent_options(options)
197
+ defaults = IndiferentHash.setup(social_duplicate(other_options || {}))
198
+ supplied = IndiferentHash.setup(social_duplicate(options || {}))
199
+ merged = defaults.merge(supplied)
200
+ SOCIAL_PRIVATE_OPTIONS.each { |name| merged.delete(name) }
201
+ merged
202
+ end
203
+
204
+ def social_duplicate(value)
205
+ Construction.duplicate(value)
206
+ end
207
+
208
+ def social_chat_copy(chat)
209
+ Construction.chat_copy(chat)
210
+ end
211
+
212
+ def clone_social_agent(template)
213
+ Construction.clone_agent(template)
214
+ end
215
+
216
+ # Seed one specialist conversation. `template:` (a pre-built Agent)
217
+ # bypasses `load_agent`; `preamble:` messages are followed after the
218
+ # inherited context and before `start`.
219
+ def start_social_chat(agent_name, options, inherit, template: nil, preamble: nil,
220
+ adopt: nil, anchor: nil)
221
+ template ||= load_agent(agent_name, options)
222
+ initial_chat = social_chat_copy(template.start_chat)
223
+ initial_chat.follow(social_context_delta(template)) if adopt == :current
224
+ initial_chat.follow(social_inherited_context(inherit))
225
+ initial_chat.follow(preamble) if preamble
226
+ Construction.build(template, seed: initial_chat, anchor: anchor)
227
+ end
228
+
229
+ # Delta of one agent's current chat over its own start_chat: what that
230
+ # agent has actually said and done since it began. In the usual
231
+ # Agent#start branch, start-chat messages are the same Hash objects in
232
+ # both arrays, which lets us remove the policy exactly even if Agent#ask
233
+ # has removed control roles. The prefix fallback covers chats adopted
234
+ # from an equivalent, separately parsed Chat.
235
+ #
236
+ # ONE rule serves both seeding directions: the caller context
237
+ # (social_caller_context) and the adopted template progress
238
+ # (`adopt: :current`).
239
+ def social_context_delta(an_agent)
240
+ current = an_agent.current_chat || []
241
+ base = an_agent.start_chat || []
242
+ base_ids = base.each_with_object({}) { |message, ids| ids[message.object_id] = true }
243
+
244
+ context = if current.any? { |message| base_ids[message.object_id] }
245
+ current.reject { |message| base_ids[message.object_id] }
246
+ else
247
+ prefix = 0
248
+ limit = [current.length, base.length].min
249
+ prefix += 1 while prefix < limit && current[prefix] == base[prefix]
250
+ current.drop(prefix)
251
+ end
252
+
253
+ social_chat_copy(context)
254
+ end
255
+
256
+ def social_caller_context
257
+ social_context_delta(self)
258
+ end
259
+
260
+ def social_inherited_context(inherit)
261
+ case inherit
262
+ when 'none'
263
+ Chat.setup([])
264
+ when 'tools'
265
+ #tooling = social_caller_context.tooling
266
+ tooling = self.current_chat.tooling
267
+ social_chat_copy(tooling)
268
+ when 'conversation', 'clear_tools'
269
+ social_caller_context
270
+ end
271
+ end
272
+
273
+ # Accept the former `chat` argument when a stored tool call is replayed, but
274
+ # do not advertise it in the schema. New calls keep conversation identity
275
+ # and inheritance as independent concepts.
276
+ def social_tool_parameters(parameters)
277
+ parameters = IndiferentHash.setup((parameters || {}).dup)
278
+ agent_name = parameters[:agent]
279
+ prompt = parameters[:prompt]
280
+ conversation = parameters[:conversation]
281
+ inherit = parameters[:inherit]
282
+
283
+ if parameters.include?(:chat)
284
+ raise ParameterException, 'Use either conversation or the legacy chat argument, not both' if conversation
285
+
286
+ legacy_chat = parameters[:chat]
287
+ case legacy_chat.to_s
288
+ when 'current'
289
+ conversation = 'current'
290
+ inherit ||= 'conversation'
291
+ when '', 'none', 'false'
292
+ conversation = nil
293
+ inherit ||= 'none'
294
+ else
295
+ conversation = legacy_chat
296
+ inherit ||= 'tools'
297
+ end
298
+ end
299
+
300
+ inherit ||= 'tools'
301
+ [agent_name, prompt, conversation, inherit]
302
+ end
303
+ end
304
+ end
@@ -1,18 +1,10 @@
1
1
  module LLM
2
2
  class Agent
3
3
 
4
- SOCIAL_INHERIT_MODES = %w[none tools conversation].freeze
5
- SOCIAL_AGENT_NAME = /\A[a-z_.-]+\z/i
6
- SOCIAL_CONVERSATION_NAME = /\A[a-z0-9][a-z0-9_.-]*\z/i
7
- SOCIAL_PRIVATE_OPTIONS = %i[
8
- agent client current_meta format messages no_ask_override previous_response_id
9
- process return_messages tool_choice tools
10
- ].freeze
11
-
12
- attr_accessor :society, :chats
13
-
14
4
  # Load one immutable template per specialist. Conversations clone this
15
5
  # template so that their current chats and start chats remain independent.
6
+ # This is the template-resolution step of Agent#open_conversation; it is
7
+ # kept public because callers (and tests) use it directly.
16
8
  def load_agent(agent_name, options = {})
17
9
  agent_name = normalize_social_agent_name(agent_name)
18
10
  @society ||= {}
@@ -26,18 +18,8 @@ module LLM
26
18
  # scoped by specialist, so Worker/work_A and Critic/work_A cannot collide.
27
19
  # `inherit` is only used when the conversation is first created.
28
20
  def load_chat(agent_name, options = {}, conversation = nil, inherit: 'tools')
29
- agent_name = normalize_social_agent_name(agent_name)
30
- conversation = normalize_social_conversation_name(conversation)
31
- inherit = normalize_social_inherit(inherit)
32
-
33
- @chats ||= {}
34
- key = social_chat_key(agent_name, conversation)
35
- @chats[key] ||= begin
36
- agent = start_social_chat(agent_name, options, inherit)
37
- agent.save_file = society_save_file(agent_name, conversation)
38
- agent
39
- end
40
-
21
+ open_conversation(agent_name, conversation: conversation, inherit: inherit,
22
+ options: options)
41
23
  end
42
24
 
43
25
  # Ask a specialist using a plain-text prompt.
@@ -55,21 +37,8 @@ module LLM
55
37
  # Delegated prompts must instead be appended with Agent#user so role-looking
56
38
  # text such as "tool:" cannot turn into a control message or grant tools.
57
39
  def ask_agent(agent_name, prompt, conversation: nil, inherit: 'tools', options: {})
58
- raise ParameterException, 'The delegated prompt must be a String' unless String === prompt
59
-
60
- agent_name = normalize_social_agent_name(agent_name)
61
- inherit = normalize_social_inherit(inherit)
62
-
63
- agent = if conversation.nil?
64
- load_chat(agent_name, options, 'default', inherit: inherit)
65
- else
66
- conversation = normalize_social_conversation_name(conversation)
67
- load_chat(agent_name, options, conversation, inherit: inherit)
68
- end
69
-
70
- agent.user(prompt)
71
-
72
- agent
40
+ ask_conversation(agent_name, prompt, conversation: conversation,
41
+ inherit: inherit, options: options)
73
42
  end
74
43
 
75
44
  # Expose a deliberately narrow `ask` tool to this agent. The model can send
@@ -106,50 +75,78 @@ module LLM
106
75
  conversation: {
107
76
  type: 'string',
108
77
  pattern: '^[A-Za-z0-9][A-Za-z0-9_.-]*$',
109
- description: 'Optional conversation or chat identifier; reuse it with the same agent to continue that conversation across several calls'
78
+ description: 'Optional conversation or chat identifier; reuse it with the same agent to continue that conversation across several rounds. Two asks of the same round onto one conversation (two nameless asks share the default) conflict: the whole delegation batch of that round returns errors'
110
79
  },
111
80
  inherit: {
112
81
  type: 'string',
113
82
  enum: SOCIAL_INHERIT_MODES,
114
83
  default: 'tools',
115
- description: "Context copied only when starting the call or named conversation: 'none' uses only the specialist start_chat, 'tools' also copies caller task tooling, and 'conversation' copies the caller task conversation"
84
+ description: "Context copied only when starting the call or named conversation: 'none' uses only the specialist start_chat, 'tools' also copies caller task tooling, and 'conversation' copies the caller task conversation; 'clear_tools' copies the caller conversation too and, when continuing an existing conversation, drops earlier tool-call traces from the model context only (the stored chat keeps them)"
116
85
  }
117
86
  }
118
87
 
119
88
  description = <<-EOF
120
89
  Ask another agent and receive only its text answer. Omit `conversation` for an
121
90
  independent one-shot call. Set `conversation` to a name and reuse the same name
122
- with the same agent for follow-up turns. `inherit` controls only how a new call
123
- or named conversation is initialized; follow-up turns retain their own history.
124
- The specialist's own start_chat is always applied first.
91
+ with the same agent for follow-up turns. `inherit` controls how a new call or
92
+ named conversation is initialized, and follow-up turns retain their own
93
+ history, except `inherit: 'clear_tools'`, which also acts when continuing a
94
+ named conversation: it drops that conversation's earlier tool-call traces from
95
+ the model context only (the stored chat keeps them). The specialist's own
96
+ start_chat is always applied first.
125
97
  EOF
126
98
 
127
- function = {
128
- name: task_name,
129
- description: description,
130
- parameters: {
131
- type: 'object',
132
- properties: properties,
133
- required: [:agent, :prompt],
134
- additionalProperties: false
135
- }
136
- }
137
-
138
- definition = IndiferentHash.setup(function.merge(type: 'function', function: function))
99
+ definition = LLM.tool_definition(task_name, description, properties,
100
+ required: [:agent, :prompt])
139
101
  @other_options[:tools][task_name] = [block, definition]
140
102
  end
141
103
 
104
+ # Delegate work to a specialist through a `hand_off_to_<name>` tool.
105
+ #
106
+ # `agent` may be any object that answers `user` (duck-typed); only
107
+ # LLM::Agent instances can go through the conversation pipeline.
108
+ #
109
+ # Registration: an LLM::Agent passed here is pre-registered in
110
+ # `@society[name] ||= agent`. @society is ALSO socialize's template
111
+ # cache, so a pre-registered live agent becomes the template for that
112
+ # name; the clone copies only its start_chat (plus any adopted delta),
113
+ # so drift between the two objects is contained to their chats.
142
114
  def delegate(agent, name, description, task_name = nil, &block)
143
115
  @other_options[:tools] ||= {}
144
116
  task_name = "hand_off_to_#{name}".to_sym if task_name.nil?
117
+ @society ||= {}
118
+ @society[name] ||= agent if LLM::Agent === agent
145
119
 
146
120
  block ||= Proc.new do |_name, parameters|
147
121
  message = parameters[:message]
148
122
  new_conversation = parameters[:new_conversation]
149
123
  Log.medium "Delegated to #{agent}: " + Log.fingerprint(message)
150
- agent.start if new_conversation
151
- agent.user message
152
- agent
124
+
125
+ begin
126
+ if LLM::Agent === agent
127
+ # The conversation slot is derived from the delegated name and
128
+ # sanitized like a society conversation key, so any name that can
129
+ # name a tool can name a conversation (save.rb's conservative
130
+ # `[^a-zA-Z0-9_-]` sanitizer, never a raise).
131
+ slot = name.to_s.gsub(/[^a-zA-Z0-9_-]/, '_')
132
+ slot = '_' if slot.empty?
133
+ slot = '_' + slot unless slot =~ /\A[a-z0-9]/i
134
+
135
+ ask_conversation(name, message,
136
+ conversation: slot,
137
+ inherit: 'none',
138
+ template: agent,
139
+ adopt: :current,
140
+ restart: new_conversation)
141
+ else
142
+ # Duck-typed objects keep the legacy direct-mutation behavior
143
+ agent.start if new_conversation
144
+ agent.user message
145
+ agent
146
+ end
147
+ rescue ScoutException => e
148
+ e
149
+ end
153
150
  end
154
151
 
155
152
  properties = {
@@ -164,189 +161,10 @@ The specialist's own start_chat is always applied first.
164
161
  }
165
162
  }
166
163
 
167
- required_inputs = [:message]
168
-
169
- function = {
170
- name: task_name,
171
- description: description,
172
- parameters: {
173
- type: "object",
174
- properties: properties,
175
- required: required_inputs
176
- }
177
- }
178
-
179
- definition = IndiferentHash.setup function.merge(type: 'function', function: function)
164
+ definition = LLM.tool_definition(task_name, description, properties,
165
+ required: [:message])
180
166
 
181
167
  @other_options[:tools][task_name] = [block, definition]
182
168
  end
183
-
184
- private
185
-
186
- def normalize_social_agent_name(agent_name)
187
- agent_name = agent_name.to_s if Symbol === agent_name
188
- unless String === agent_name && SOCIAL_AGENT_NAME.match?(agent_name)
189
- raise ParameterException,
190
- 'Agent name must contain only letters, dots, underscores, or hyphens'
191
- end
192
- agent_name
193
- end
194
-
195
- def normalize_social_conversation_name(conversation)
196
- conversation = conversation.to_s if Symbol === conversation
197
- unless String === conversation && SOCIAL_CONVERSATION_NAME.match?(conversation)
198
- raise ParameterException,
199
- 'Conversation identifier must start with a letter or number and contain only letters, numbers, dots, underscores, or hyphens'
200
- end
201
- conversation
202
- end
203
-
204
- def normalize_social_inherit(inherit)
205
- inherit = inherit.to_s
206
- return inherit if SOCIAL_INHERIT_MODES.include?(inherit)
207
-
208
- raise ParameterException,
209
- "Unknown inheritance policy #{inherit.inspect}; expected one of #{SOCIAL_INHERIT_MODES * ', '}"
210
- end
211
-
212
- def social_chat_key(agent_name, conversation)
213
- "#{agent_name}/#{conversation}"
214
- end
215
-
216
- def society_save_file(agent_name, conversation)
217
- # ScoutCoder: the society directory is derived with the CANONICAL rule
218
- # (Agent.society_dir_for / Agent#society_dir), never by string
219
- # substitution here. An earlier version did
220
- # `save_file.sub(/\.chat/, '.society')`: the sub had no anchor, so it
221
- # replaced the FIRST '.chat' occurrence and a CLI-shaped save_file like
222
- # `cli.chat.files/agent.chat` turned into
223
- # `cli.society.files/agent.chat/...`, growing a second `.files` tree
224
- # instead of `cli.chat.files/agent.society/...`.
225
- # society_dir_for is the single source of truth for the root
226
- # (name-derived) rule; society_dir adds the location rule for nested
227
- # chats.
228
- #
229
- # save.rb simply does not auto-save without a save_file; mirror that
230
- # here instead of raising on nil (a society conversation started by an
231
- # agent with no save_file just never persists).
232
- return nil if save_file.nil?
233
-
234
- File.join(society_dir(save_file), agent_name.to_s, conversation.to_s, SOCIETY_CHAT_FILE)
235
- end
236
-
237
- # Provider session state and executable Ruby tool objects belong to the
238
- # caller. Model/backend defaults may flow to specialists, but capabilities
239
- # are inherited only through the specialist start_chat or an explicit
240
- # declarative inheritance policy.
241
- def social_agent_options(options)
242
- defaults = IndiferentHash.setup(social_duplicate(other_options || {}))
243
- supplied = IndiferentHash.setup(social_duplicate(options || {}))
244
- merged = defaults.merge(supplied)
245
- SOCIAL_PRIVATE_OPTIONS.each { |name| merged.delete(name) }
246
- merged
247
- end
248
-
249
- def social_duplicate(value)
250
- case value
251
- when Hash
252
- value.each_with_object({}) do |(key, item), copy|
253
- copy[social_duplicate(key)] = social_duplicate(item)
254
- end
255
- when Array
256
- value.collect { |item| social_duplicate(item) }
257
- when String
258
- value.dup
259
- else
260
- value
261
- end
262
- end
263
-
264
- def social_chat_copy(chat)
265
- Chat.setup(social_duplicate(chat || []))
266
- end
267
-
268
- def clone_social_agent(template)
269
- agent = template.clone
270
- agent.start_chat = social_chat_copy(template.start_chat)
271
- agent.other_options = IndiferentHash.setup(social_duplicate(template.other_options || {}))
272
- agent.society = nil
273
- agent.chats = nil
274
- agent.instance_variable_set(:@current_chat, nil)
275
- agent
276
- end
277
-
278
- def start_social_chat(agent_name, options, inherit)
279
- template = load_agent(agent_name, options)
280
- agent = clone_social_agent(template)
281
- initial_chat = social_chat_copy(agent.start_chat)
282
- initial_chat.follow(social_inherited_context(inherit))
283
- agent.start(initial_chat)
284
- agent
285
- end
286
-
287
- # In the usual Agent#start branch, start-chat messages are the same Hash
288
- # objects in both arrays, which lets us remove the caller agent's policy
289
- # exactly even if Agent#ask has removed control roles. The prefix fallback
290
- # covers callers that adopted an equivalent, separately parsed Chat.
291
- def social_caller_context
292
- current = current_chat || []
293
- base = start_chat || []
294
- base_ids = base.each_with_object({}) { |message, ids| ids[message.object_id] = true }
295
-
296
- context = if current.any? { |message| base_ids[message.object_id] }
297
- current.reject { |message| base_ids[message.object_id] }
298
- else
299
- prefix = 0
300
- limit = [current.length, base.length].min
301
- prefix += 1 while prefix < limit && current[prefix] == base[prefix]
302
- current.drop(prefix)
303
- end
304
-
305
- social_chat_copy(context)
306
- end
307
-
308
- def social_inherited_context(inherit)
309
- case inherit
310
- when 'none'
311
- Chat.setup([])
312
- when 'tools'
313
- #tooling = social_caller_context.tooling
314
- tooling = self.current_chat.tooling
315
- social_chat_copy(tooling)
316
- when 'conversation'
317
- social_caller_context
318
- end
319
- end
320
-
321
- # Accept the former `chat` argument when a stored tool call is replayed, but
322
- # do not advertise it in the schema. New calls keep conversation identity
323
- # and inheritance as independent concepts.
324
- def social_tool_parameters(parameters)
325
- parameters = IndiferentHash.setup((parameters || {}).dup)
326
- agent_name = parameters[:agent]
327
- prompt = parameters[:prompt]
328
- conversation = parameters[:conversation]
329
- inherit = parameters[:inherit]
330
-
331
- if parameters.include?(:chat)
332
- raise ParameterException, 'Use either conversation or the legacy chat argument, not both' if conversation
333
-
334
- legacy_chat = parameters[:chat]
335
- case legacy_chat.to_s
336
- when 'current'
337
- conversation = 'current'
338
- inherit ||= 'conversation'
339
- when '', 'none', 'false'
340
- conversation = nil
341
- inherit ||= 'none'
342
- else
343
- conversation = legacy_chat
344
- inherit ||= 'tools'
345
- end
346
- end
347
-
348
- inherit ||= 'tools'
349
- [agent_name, prompt, conversation, inherit]
350
- end
351
169
  end
352
170
  end