aia 2.0.0.0.pre.alpha → 2.0.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 (236) hide show
  1. checksums.yaml +4 -4
  2. data/.version +1 -1
  3. data/CHANGELOG.md +151 -228
  4. data/README.md +42 -19
  5. data/bin/aia +8 -3
  6. data/lib/aia/aia_completion.bash +2 -3
  7. data/lib/aia/aia_completion.fish +6 -5
  8. data/lib/aia/aia_completion.zsh +2 -3
  9. data/lib/aia/chat_loop.rb +24 -66
  10. data/lib/aia/config/cli_parser.rb +164 -123
  11. data/lib/aia/config/defaults.yml +12 -39
  12. data/lib/aia/config/mcp_parser.rb +42 -40
  13. data/lib/aia/config/model_spec.rb +8 -14
  14. data/lib/aia/config/validator.rb +144 -156
  15. data/lib/aia/config/value_caster.rb +76 -0
  16. data/lib/aia/config.rb +72 -54
  17. data/lib/aia/content_extractor.rb +2 -0
  18. data/lib/aia/cost_calculator.rb +1 -0
  19. data/lib/aia/crew.rb +29 -19
  20. data/lib/aia/debate_handler.rb +45 -20
  21. data/lib/aia/delegate_handler.rb +7 -3
  22. data/lib/aia/directive.rb +10 -8
  23. data/lib/aia/directives/configuration_directives.rb +164 -109
  24. data/lib/aia/directives/context_directives.rb +55 -40
  25. data/lib/aia/directives/execution_directives.rb +25 -25
  26. data/lib/aia/directives/model_directives.rb +112 -195
  27. data/lib/aia/directives/trakflow_directives.rb +27 -9
  28. data/lib/aia/directives/utility_directives.rb +86 -87
  29. data/lib/aia/directives/web_and_file_directives.rb +83 -63
  30. data/lib/aia/fact_asserter.rb +3 -3
  31. data/lib/aia/history_transfer.rb +64 -24
  32. data/lib/aia/layered_orchestrator.rb +66 -43
  33. data/lib/aia/logger.rb +27 -62
  34. data/lib/aia/mcp_config_normalizer.rb +27 -14
  35. data/lib/aia/mcp_connection_manager.rb +193 -186
  36. data/lib/aia/mcp_discovery.rb +43 -15
  37. data/lib/aia/mcp_grouper.rb +2 -1
  38. data/lib/aia/mcp_server_config.rb +48 -0
  39. data/lib/aia/mcp_utility.rb +28 -20
  40. data/lib/aia/mention_router.rb +22 -52
  41. data/lib/aia/modality_query.rb +36 -0
  42. data/lib/aia/model_alias_registry.rb +11 -11
  43. data/lib/aia/model_registry.rb +75 -0
  44. data/lib/aia/network_builder.rb +17 -11
  45. data/lib/aia/network_memory_manager.rb +6 -6
  46. data/lib/aia/patches/ruby_llm_streaming_error.rb +21 -4
  47. data/lib/aia/patches/ruby_llm_tool_param_compat.rb +18 -0
  48. data/lib/aia/pipeline_orchestrator.rb +88 -45
  49. data/lib/aia/plugin_monitor.rb +9 -6
  50. data/lib/aia/prompt_decomposer.rb +6 -4
  51. data/lib/aia/prompt_handler.rb +90 -69
  52. data/lib/aia/provider_registry.rb +105 -0
  53. data/lib/aia/robot_builder.rb +1 -1
  54. data/lib/aia/robot_factory.rb +77 -69
  55. data/lib/aia/robot_namer.rb +2 -8
  56. data/lib/aia/robot_sync.rb +79 -0
  57. data/lib/aia/role_catalog.rb +89 -0
  58. data/lib/aia/session.rb +32 -14
  59. data/lib/aia/session_tracker.rb +39 -41
  60. data/lib/aia/similarity_scorer.rb +5 -3
  61. data/lib/aia/skill_utils.rb +60 -19
  62. data/lib/aia/spawn_handler.rb +16 -4
  63. data/lib/aia/spawn_spec_parser.rb +6 -7
  64. data/lib/aia/special_mode_handler.rb +80 -57
  65. data/lib/aia/speech.rb +103 -0
  66. data/lib/aia/startup_coordinator.rb +17 -91
  67. data/lib/aia/streaming_runner.rb +16 -5
  68. data/lib/aia/system_prompt_assembler.rb +20 -15
  69. data/lib/aia/task_board.rb +60 -0
  70. data/lib/aia/task_coordinator.rb +10 -5
  71. data/lib/aia/timing.rb +15 -0
  72. data/lib/aia/tool_approver.rb +205 -0
  73. data/lib/aia/tool_filter.rb +1 -9
  74. data/lib/aia/tool_filter_strategy.rb +39 -25
  75. data/lib/aia/tool_introspection.rb +25 -0
  76. data/lib/aia/tool_loader.rb +71 -31
  77. data/lib/aia/tool_utility.rb +6 -5
  78. data/lib/aia/tools/delegate_to_foreman_tool.rb +6 -4
  79. data/lib/aia/tools/recruit_robot_tool.rb +12 -12
  80. data/lib/aia/tools/reskill_robot_tool.rb +7 -7
  81. data/lib/aia/tools/task_board_tool.rb +17 -16
  82. data/lib/aia/trakflow_bridge.rb +19 -11
  83. data/lib/aia/turn_state.rb +32 -8
  84. data/lib/aia/ui_presenter.rb +83 -59
  85. data/lib/aia/utility.rb +8 -24
  86. data/lib/aia/variable_input_collector.rb +1 -3
  87. data/lib/aia/verification_network.rb +10 -12
  88. data/lib/aia.rb +49 -8
  89. metadata +27 -162
  90. data/.better-commits.json +0 -150
  91. data/.config/tocer/configuration.yml +0 -6
  92. data/.envrc +0 -15
  93. data/.loki +0 -231
  94. data/.quality/flay_baseline.txt +0 -1
  95. data/.quality/flog_baseline.txt +0 -29
  96. data/.quality/reek_baseline.txt +0 -80
  97. data/.rubocop.yml +0 -116
  98. data/COMMITS.md +0 -196
  99. data/IMPLEMENTATION_PLAN.md +0 -506
  100. data/Rakefile +0 -160
  101. data/architecture_review.md +0 -314
  102. data/docs/AGENTS.md +0 -40
  103. data/docs/advanced-prompting.md +0 -814
  104. data/docs/assets/images/aia.png +0 -0
  105. data/docs/cli-reference.md +0 -1241
  106. data/docs/configuration.md +0 -747
  107. data/docs/contributing.md +0 -386
  108. data/docs/directives-reference.md +0 -1145
  109. data/docs/examples/index.md +0 -277
  110. data/docs/examples/mcp/index.md +0 -475
  111. data/docs/examples/prompts/analysis/index.md +0 -78
  112. data/docs/examples/prompts/automation/index.md +0 -109
  113. data/docs/examples/prompts/development/index.md +0 -125
  114. data/docs/examples/prompts/index.md +0 -333
  115. data/docs/examples/prompts/learning/index.md +0 -127
  116. data/docs/examples/prompts/writing/index.md +0 -62
  117. data/docs/examples/tools/index.md +0 -282
  118. data/docs/faq.md +0 -578
  119. data/docs/guides/available-models.md +0 -366
  120. data/docs/guides/basic-usage.md +0 -478
  121. data/docs/guides/chat.md +0 -680
  122. data/docs/guides/crew.md +0 -239
  123. data/docs/guides/executable-prompts.md +0 -331
  124. data/docs/guides/first-prompt.md +0 -454
  125. data/docs/guides/getting-started.md +0 -455
  126. data/docs/guides/image-generation.md +0 -507
  127. data/docs/guides/index.md +0 -48
  128. data/docs/guides/local-models.md +0 -306
  129. data/docs/guides/migrate-prompts.md +0 -335
  130. data/docs/guides/models.md +0 -1017
  131. data/docs/guides/shared-tools.md +0 -254
  132. data/docs/guides/tools.md +0 -831
  133. data/docs/index.md +0 -259
  134. data/docs/installation.md +0 -274
  135. data/docs/mcp-integration.md +0 -603
  136. data/docs/prompt_management.md +0 -665
  137. data/docs/security.md +0 -674
  138. data/docs/special_projects_guide.md +0 -386
  139. data/docs/tools-and-mcp-examples.md +0 -1211
  140. data/docs/workflows-and-pipelines.md +0 -636
  141. data/examples/.gitignore +0 -2
  142. data/examples/00_setup_aia.sh +0 -111
  143. data/examples/01_basic_usage.sh +0 -23
  144. data/examples/02_frontmatter.sh +0 -33
  145. data/examples/03_shell_integration.sh +0 -55
  146. data/examples/04_erb_templating.sh +0 -56
  147. data/examples/05_shell_then_erb.sh +0 -38
  148. data/examples/06_prompt_chaining.sh +0 -59
  149. data/examples/07_pipeline.sh +0 -46
  150. data/examples/08_context_files.sh +0 -43
  151. data/examples/09_roles.sh +0 -67
  152. data/examples/10_stdin_piping.sh +0 -49
  153. data/examples/11_multi_model.sh +0 -65
  154. data/examples/12_token_usage.sh +0 -52
  155. data/examples/13_cost_tracking.sh +0 -68
  156. data/examples/14_output_file.sh +0 -91
  157. data/examples/15_parameters.sh +0 -68
  158. data/examples/16_directives.sh +0 -113
  159. data/examples/17_require_and_conditionals.sh +0 -68
  160. data/examples/18_tools.sh +0 -61
  161. data/examples/19_local_tools.sh +0 -34
  162. data/examples/20_mcp_servers.sh +0 -102
  163. data/examples/21_executable_prompts.sh +0 -78
  164. data/examples/22_chat_mode.sh +0 -217
  165. data/examples/23_verify.sh +0 -139
  166. data/examples/24_decompose.sh +0 -139
  167. data/examples/25_spawn.sh +0 -139
  168. data/examples/26_debate.sh +0 -97
  169. data/examples/27_mention_routing.sh +0 -157
  170. data/examples/28_model_switching.sh +0 -106
  171. data/examples/29_agent_harness.sh +0 -177
  172. data/examples/README.md +0 -321
  173. data/examples/advanced_multi_robot_capabilities_without_examples.md +0 -106
  174. data/examples/aia_config.yml +0 -22
  175. data/examples/aia_config_orchestrator.yml +0 -45
  176. data/examples/aia_config_with_mcp.yml +0 -21
  177. data/examples/common.sh +0 -39
  178. data/examples/context/project_goals.md +0 -6
  179. data/examples/context/tech_stack.md +0 -7
  180. data/examples/directives/timestamp_directive.rb +0 -22
  181. data/examples/mcp/filesystem.json +0 -9
  182. data/examples/prompts_dir/analyze.md +0 -2
  183. data/examples/prompts_dir/brainstorm.md +0 -2
  184. data/examples/prompts_dir/conditional.md +0 -17
  185. data/examples/prompts_dir/creative.md +0 -4
  186. data/examples/prompts_dir/erbinfo.md +0 -5
  187. data/examples/prompts_dir/erbinfo_raw.md +0 -8
  188. data/examples/prompts_dir/evaluate.md +0 -2
  189. data/examples/prompts_dir/explain_joke.md +0 -1
  190. data/examples/prompts_dir/explain_recursion.md +0 -1
  191. data/examples/prompts_dir/fun_fact +0 -3
  192. data/examples/prompts_dir/greeting.md +0 -8
  193. data/examples/prompts_dir/greeting_required.md +0 -7
  194. data/examples/prompts_dir/hello.md +0 -1
  195. data/examples/prompts_dir/includes/ruby_facts.md +0 -4
  196. data/examples/prompts_dir/limerick.md +0 -1
  197. data/examples/prompts_dir/list_with_mcp.md +0 -3
  198. data/examples/prompts_dir/pick_best.md +0 -2
  199. data/examples/prompts_dir/project_summary +0 -12
  200. data/examples/prompts_dir/quiz_with_include.md +0 -6
  201. data/examples/prompts_dir/require_demo.md +0 -5
  202. data/examples/prompts_dir/roles/formal.md +0 -3
  203. data/examples/prompts_dir/roles/orchestrator.md +0 -21
  204. data/examples/prompts_dir/roles/pirate.md +0 -3
  205. data/examples/prompts_dir/shell_then_erb.md +0 -6
  206. data/examples/prompts_dir/sort_compare.md +0 -2
  207. data/examples/prompts_dir/summarize_context.md +0 -2
  208. data/examples/prompts_dir/sysinfo.md +0 -5
  209. data/examples/prompts_dir/sysinfo_raw.md +0 -8
  210. data/examples/prompts_dir/tagline.md +0 -1
  211. data/examples/prompts_dir/tell_joke.md +0 -1
  212. data/examples/prompts_dir/tell_joke_with_next.md +0 -4
  213. data/examples/prompts_dir/use_local_tool.md +0 -8
  214. data/examples/prompts_dir/use_tools.md +0 -8
  215. data/examples/prompts_dir/weather.md +0 -2
  216. data/examples/prompts_dir/whats_new.md +0 -2
  217. data/examples/prompts_dir/with_timestamp.md +0 -5
  218. data/examples/requirements/sinatra_taskflow_app.md +0 -139
  219. data/examples/rules/01_classify_ruby.rb +0 -16
  220. data/examples/rules/02_prefer_claude_for_code.rb +0 -19
  221. data/examples/rules/03_gate_prompt_length.rb +0 -19
  222. data/examples/rules/04_tool_selection.rb +0 -41
  223. data/examples/rules/README.md +0 -30
  224. data/examples/run_all.sh +0 -294
  225. data/examples/tools/word_count_tool.rb +0 -30
  226. data/lib/AGENTS.md +0 -57
  227. data/lib/aia/model_switch_handler.rb +0 -100
  228. data/mcp_servers/README.md +0 -110
  229. data/mcp_servers/apple-mcp.json +0 -8
  230. data/mcp_servers/filesystem.json +0 -9
  231. data/mcp_servers/mcp_server_chart.json +0 -11
  232. data/mcp_servers/playwright_one.json +0 -8
  233. data/mcp_servers/playwright_server_definition.json +0 -9
  234. data/mcp_servers/playwright_two.json +0 -8
  235. data/mcp_servers/tavily_mcp_server.json +0 -8
  236. data/mkdocs.yml +0 -169
@@ -10,6 +10,17 @@ module AIA
10
10
  id.to_s.start_with?('/', './', '../', '~/')
11
11
  end
12
12
 
13
+ # The file a prompt ID names. A path-based ID ("./x", "~/p/x.md") is
14
+ # expanded, gaining +extname+ when it has none; any other ID is
15
+ # relative to +dir+.
16
+ def prompt_file_path(prompt_id, dir:, extname:)
17
+ id = prompt_id.to_s
18
+ return File.join(dir, "#{id}#{extname}") unless path_based_id?(id)
19
+
20
+ expanded = File.expand_path(id)
21
+ File.extname(expanded).empty? ? "#{expanded}#{extname}" : expanded
22
+ end
23
+
13
24
  def parse_front_matter(path)
14
25
  return {} unless File.exist?(path)
15
26
  content = File.read(path)
@@ -22,11 +33,26 @@ module AIA
22
33
  {}
23
34
  end
24
35
 
36
+ # File extensions a skill given as a file path may have.
37
+ SKILL_EXTENSIONS = %w[.md .markdown].freeze
38
+
39
+ # Whether +path+ names a file that can't be a skill (not markdown).
40
+ def non_markdown_skill_file?(path)
41
+ File.file?(path) && !SKILL_EXTENSIONS.include?(File.extname(path).downcase)
42
+ end
43
+
44
+ # The warning for a skill path that names a non-markdown file.
45
+ def non_markdown_skill_message(skill_id)
46
+ "Skill '#{skill_id}' is not a markdown file (#{SKILL_EXTENSIONS.join(' or ')})"
47
+ end
48
+
49
+ # A skill directory or markdown file. Path IDs may name either; a file
50
+ # must be markdown. Named skills are looked up in +base_dir+ only.
25
51
  def find_skill_dir(skill_name, base_dir)
26
52
  if path_based_id?(skill_name)
27
53
  expanded = File.expand_path(skill_name)
28
54
  return expanded if Dir.exist?(expanded)
29
- return expanded if File.file?(expanded)
55
+ return expanded if File.file?(expanded) && !non_markdown_skill_file?(expanded)
30
56
  return nil
31
57
  end
32
58
 
@@ -116,7 +142,6 @@ module AIA
116
142
  def load_skills_content(skill_ids, skills_base_dir)
117
143
  ids = Array(skill_ids).reject { |s| s.nil? || s.strip.empty? }
118
144
  return nil if ids.empty?
119
- return nil unless skills_base_dir && Dir.exist?(skills_base_dir)
120
145
 
121
146
  contents = ids.filter_map { |id| load_single_skill_content(id, skills_base_dir) }
122
147
  contents.empty? ? nil : contents.join("\n\n")
@@ -129,26 +154,42 @@ module AIA
129
154
  # @param skills_base_dir [String] base directory for named skills
130
155
  # @return [String, nil] skill body text, or nil on error
131
156
  def load_single_skill_content(skill_id, skills_base_dir)
157
+ problem = skill_load_problem(skill_id, skills_base_dir)
158
+ return skill_warning(problem) if problem
159
+
132
160
  skill_dir = find_skill_dir(skill_id, skills_base_dir)
133
- unless skill_dir
134
- $stderr.puts "Warning: Skill '#{skill_id}' not found in #{skills_base_dir}"
135
- return nil
136
- end
161
+ return skill_warning("Skill '#{skill_id}' not found in #{skills_base_dir}") unless skill_dir
137
162
 
138
- raw = if File.file?(skill_dir)
139
- File.read(skill_dir)
140
- else
141
- skill_path = File.join(skill_dir, 'SKILL.md')
142
- unless File.exist?(skill_path)
143
- $stderr.puts "Warning: SKILL.md not found in #{skill_dir}"
144
- return nil
145
- end
146
- File.read(skill_path)
147
- end
148
-
149
- skill_body(raw)
163
+ raw = read_skill_source(skill_dir)
164
+ raw && skill_body(raw)
150
165
  rescue StandardError => e
151
- $stderr.puts "Warning: Could not load skill '#{skill_id}': #{e.message}"
166
+ skill_warning("Could not load skill '#{skill_id}': #{e.message}")
167
+ end
168
+
169
+ # Why +skill_id+ can't be loaded before looking for it, or nil.
170
+ def skill_load_problem(skill_id, skills_base_dir)
171
+ path_id = path_based_id?(skill_id)
172
+ unless path_id || (skills_base_dir && Dir.exist?(skills_base_dir))
173
+ return "Skill '#{skill_id}' not loaded: skills directory #{skills_base_dir.inspect} does not exist"
174
+ end
175
+ return "#{non_markdown_skill_message(skill_id)}; not loaded" if path_id && non_markdown_skill_file?(File.expand_path(skill_id))
176
+
177
+ nil
178
+ end
179
+
180
+ # The raw text of a found skill: the file itself, or the folder's SKILL.md.
181
+ def read_skill_source(skill_dir)
182
+ return File.read(skill_dir) if File.file?(skill_dir)
183
+
184
+ skill_path = File.join(skill_dir, 'SKILL.md')
185
+ return File.read(skill_path) if File.exist?(skill_path)
186
+
187
+ skill_warning("SKILL.md not found in #{skill_dir}")
188
+ end
189
+
190
+ # Print a skill warning; returns nil so callers can `return skill_warning(...)`.
191
+ def skill_warning(message)
192
+ $stderr.puts "Warning: #{message}"
152
193
  nil
153
194
  end
154
195
 
@@ -43,7 +43,11 @@ module AIA
43
43
  # Spawn or reuse specialist (evict oldest when cache is full)
44
44
  specialist = @spawned[role] ||= begin
45
45
  evict_oldest! if @spawned.size >= MAX_CACHE_SIZE
46
- primary.spawn(name: role, system_prompt: instruction, **spawn_opts)
46
+ primary.spawn(
47
+ name: role, system_prompt: instruction,
48
+ **chief_tool_opts(primary),
49
+ **ToolApprover.options(AIA.config), **spawn_opts
50
+ )
47
51
  end
48
52
 
49
53
  @ui_presenter.display_info("Specialist '#{role}' responding...")
@@ -79,9 +83,7 @@ module AIA
79
83
  # @return [Array(String, String, Hash)] [role, instruction, spawn_opts]
80
84
  def resolve_specialist(context, primary, prompt)
81
85
  if (spec = context.spawn_spec)
82
- role = spec[:name]
83
- instruction = spec[:system_prompt] || "You are #{role}."
84
- [role, instruction, model_opts(spec)]
86
+ [spec[:name], Crew.compose_system_prompt(spec), model_opts(spec)]
85
87
  elsif (type = context.specialist_type)
86
88
  [type, "You are a #{type} specialist. Answer precisely within your domain of expertise.", {}]
87
89
  else
@@ -102,6 +104,16 @@ module AIA
102
104
  { model: spec[:model], provider: spec[:provider] }
103
105
  end
104
106
 
107
+ # The chief's local tools and MCP servers, so a specialist can do the
108
+ # same work. Empty sets are left out.
109
+ #
110
+ # @return [Hash]
111
+ def chief_tool_opts(primary)
112
+ tools = Crew.chief_local_tools(primary)
113
+ opts = tools.empty? ? {} : { local_tools: tools }
114
+ opts.merge(Crew.chief_mcp(primary))
115
+ end
116
+
105
117
  def evict_oldest!
106
118
  @spawned.delete(@spawned.keys.first)
107
119
  end
@@ -8,10 +8,10 @@ module AIA
8
8
  #
9
9
  # <name> <provider/model> <system prompt...>
10
10
  #
11
- # The second token is parsed as a model via {ModelSpec}, so
12
- # "ollama/qwen3.6:latest" yields model "qwen3.6:latest" + provider "ollama"
13
- # (and "lms/..." maps to the openai provider). Use "-" or "inherit" as the
14
- # model token to keep the parent robot's model and provider.
11
+ # The second token is parsed as a model via {ModelSpec}, so a
12
+ # "<provider>/<model>" spec yields the model plus its RubyLLM provider for
13
+ # any provider RubyLLM knows (see {ProviderRegistry}). Use "-" or "inherit"
14
+ # as the model token to keep the parent robot's model and provider.
15
15
  #
16
16
  # Any token of the form "skill:<id>" (anywhere after the name) is pulled out
17
17
  # as a skill assignment and returned in :skills; "skill:a,b" lists several.
@@ -57,9 +57,8 @@ module AIA
57
57
  def self.parse_model(token)
58
58
  return [nil, nil] if token.nil? || INHERIT_TOKENS.include?(token.downcase)
59
59
 
60
- spec = ModelSpec.new(name: token)
61
- provider = spec.provider == 'lms' ? 'openai' : spec.provider
62
- [spec.name, provider]
60
+ spec = ModelSpec.new(name: token)
61
+ [spec.name, RobotFactory.resolve_provider(spec)]
63
62
  end
64
63
  end
65
64
  end
@@ -14,26 +14,24 @@ module AIA
14
14
  class SpecialModeHandler
15
15
  include ContentExtractor
16
16
 
17
- # Special-mode dispatch table. Each row is triggered by a TurnState flag and
17
+ # Special-mode dispatch table. Each row is triggered by a TurnState mode and
18
18
  # runs either a bespoke method (`run:`) or, for the uniform "sub-handler
19
19
  # returns content" family, the shared #run_sub_handler (`sub:`). Adding a
20
20
  # mode means adding a row here plus (for a bespoke mode) its handle_* method
21
21
  # — never editing #handle.
22
22
  MODES = [
23
- { flag: :force_verify, run: :handle_verification },
24
- { flag: :force_decompose, run: :handle_decomposition },
25
- { flag: :force_concurrent_mcp, run: :handle_concurrent_mcp },
26
- { flag: :force_debate, sub: { handler: :debate_handler, label: 'Debate' } },
27
- { flag: :force_delegate, sub: { handler: :delegate_handler, label: 'Delegation' } },
28
- { flag: :force_spawn, sub: { handler: :spawn_handler, label: 'Spawn',
29
- context: lambda { |prompt, ts|
30
- type = ts.spawn_type
31
- spec = ts.spawn_spec
32
- ts.spawn_type = nil
33
- ts.spawn_spec = nil
34
- { prompt: prompt, specialist_type: type, spawn_spec: spec }
35
- } } },
36
- { flag: :force_orchestrate, run: :handle_orchestration }
23
+ { mode: :verify, run: :handle_verification },
24
+ { mode: :decompose, run: :handle_decomposition },
25
+ { mode: :concurrent_mcp, run: :handle_concurrent_mcp },
26
+ # live: the handler already displayed its output turn by turn, so the
27
+ # returned transcript is only saved (--output), not displayed again.
28
+ { mode: :debate, sub: { handler: :debate_handler, label: 'Debate', live: true } },
29
+ { mode: :delegate, sub: { handler: :delegate_handler, label: 'Delegation' } },
30
+ { mode: :spawn, sub: { handler: :spawn_handler, label: 'Spawn',
31
+ context: lambda { |prompt, taken|
32
+ { prompt: prompt, specialist_type: taken[:spawn_type], spawn_spec: taken[:spawn_spec] }
33
+ } } },
34
+ { mode: :orchestrate, run: :handle_orchestration }
37
35
  ].freeze
38
36
 
39
37
  # Memoized sub-handler accessors, used to propagate a robot swap.
@@ -66,15 +64,14 @@ module AIA
66
64
  # @param prompt [String] the user prompt
67
65
  # @return [Boolean]
68
66
  def handle(prompt)
69
- turn_state = AIA.turn_state
70
- mode = MODES.find { |m| turn_state.public_send(m[:flag]) }
71
- return false unless mode
67
+ taken = AIA.turn_state.consume!
68
+ return false unless taken
72
69
 
73
- turn_state.public_send(:"#{mode[:flag]}=", false)
74
- if mode[:sub]
75
- run_sub_handler(mode[:sub], prompt, turn_state)
70
+ row = MODES.find { |m| m[:mode] == taken[:mode] }
71
+ if row[:sub]
72
+ run_sub_handler(row[:sub], prompt, taken)
76
73
  else
77
- send(mode[:run], prompt)
74
+ send(row[:run], prompt)
78
75
  end
79
76
  end
80
77
 
@@ -83,12 +80,12 @@ module AIA
83
80
  # Run a "sub-handler returns content" mode: debate / delegate / spawn share
84
81
  # this exact shape, differing only by handler, label, and (spawn) an extra
85
82
  # context field built by spec[:context].
86
- def run_sub_handler(spec, prompt, turn_state)
87
- ctx_args = spec[:context] ? spec[:context].call(prompt, turn_state) : { prompt: prompt }
83
+ def run_sub_handler(spec, prompt, taken)
84
+ ctx_args = spec[:context] ? spec[:context].call(prompt, taken) : { prompt: prompt }
88
85
  content = send(spec[:handler]).handle(HandlerContext.new(**ctx_args))
89
86
  return false unless content
90
87
 
91
- display_and_save(content)
88
+ spec[:live] ? save_live_output(content) : display_and_save(content)
92
89
  true
93
90
  rescue StandardError => e
94
91
  @ui_presenter.display_info("#{spec[:label]} failed: #{e.message}. Falling back to normal mode.")
@@ -109,30 +106,63 @@ module AIA
109
106
  false
110
107
  end
111
108
 
112
- # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
109
+ # :reek:TooManyStatements -- benchmark-instrumented pipeline: decompose, concurrent fan-out, synthesis, reporting
113
110
  def handle_decomposition(prompt)
114
111
  require_relative 'prompt_decomposer'
115
- total_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
112
+ total_t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
116
113
 
117
114
  @ui_presenter.display_info("Decomposing prompt into sub-tasks...")
118
- decomposer = PromptDecomposer.new(@robot)
119
- decompose_t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
120
- subtasks = decomposer.decompose(prompt)
121
- decompose_dur = Process.clock_gettime(Process::CLOCK_MONOTONIC) - decompose_t0
115
+ decomposer = PromptDecomposer.new(@robot)
116
+ subtasks, decompose_dur = Timing.timed { decomposer.decompose(prompt) }
122
117
 
123
118
  if subtasks.empty?
124
119
  @ui_presenter.display_info("Prompt cannot be meaningfully decomposed. Running normally.")
125
120
  return false
126
121
  end
127
122
 
123
+ announce_subtasks(subtasks)
124
+
125
+ results, timings, raw_subtasks, parallel_wall = run_and_time_subtasks(subtasks)
126
+
127
+ raise DecomposeError, "All sub-tasks failed" if results.all?(&:nil?)
128
+
129
+ @ui_presenter.display_info("Synthesizing results...")
130
+ final, synth_dur = Timing.timed { decomposer.synthesize(prompt, results.compact) }
131
+
132
+ total_wall = Process.clock_gettime(Process::CLOCK_MONOTONIC) - total_t0
133
+
134
+ display_decompose_benchmark(decompose_dur: decompose_dur, timings: timings,
135
+ synth_dur: synth_dur, parallel_wall: parallel_wall,
136
+ total_wall: total_wall)
137
+ display_decompose_token_metrics(raw_subtasks, final, total_wall)
138
+
139
+ present_result(final, prompt: prompt, ui_presenter: @ui_presenter, tracker: @tracker)
140
+ true
141
+ rescue StandardError => e
142
+ @ui_presenter.display_info("Decomposition failed: #{e.message}. Falling back to normal mode.")
143
+ false
144
+ end
145
+
146
+ def announce_subtasks(subtasks)
128
147
  @ui_presenter.display_info("Decomposed into #{subtasks.size} sub-tasks:")
129
148
  subtasks.each_with_index { |t, i| @ui_presenter.display_info(" #{i + 1}. #{t}") }
149
+ end
130
150
 
131
- timings = Array.new(subtasks.size, 0.0)
132
- raw_subtasks = Array.new(subtasks.size)
133
- wall_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
151
+ # Fan out sub-tasks concurrently, capturing per-task and wall-clock timing.
152
+ # Returns [results, timings, raw_subtasks, parallel_wall].
153
+ def run_and_time_subtasks(subtasks)
154
+ timings = Array.new(subtasks.size, 0.0)
155
+ raw_subtasks = Array.new(subtasks.size)
156
+ results, parallel_wall = Timing.timed { run_subtasks_concurrently(subtasks, timings, raw_subtasks) }
157
+ [results, timings, raw_subtasks, parallel_wall]
158
+ end
134
159
 
135
- results = Sync do
160
+ # Run all sub-tasks concurrently, recording per-task timing and raw results
161
+ # into the caller-supplied arrays. Returns extracted contents (nil per failure).
162
+ # :reek:DuplicateMethodCall -- clock_gettime is read at task start and again at each outcome; each read must be "now"
163
+ # :reek:TooManyStatements -- async fan-out with per-task timing capture on both success and failure paths
164
+ def run_subtasks_concurrently(subtasks, timings, raw_subtasks)
165
+ Sync do
136
166
  barrier = Async::Barrier.new
137
167
  tasks = subtasks.each_with_index.map do |task, i|
138
168
  barrier.async do
@@ -151,21 +181,13 @@ module AIA
151
181
  barrier.wait
152
182
  tasks.map(&:wait)
153
183
  end
154
- # rubocop:enable Metrics/AbcSize, Metrics/MethodLength
184
+ end
155
185
 
156
- parallel_wall = Process.clock_gettime(Process::CLOCK_MONOTONIC) - wall_start
186
+ # Print the decomposition benchmark table.
187
+ def display_decompose_benchmark(decompose_dur:, timings:, synth_dur:, parallel_wall:, total_wall:)
157
188
  serial_est = timings.sum
158
189
  parallel_speedup = serial_est / parallel_wall
159
190
 
160
- raise DecomposeError, "All sub-tasks failed" if results.all?(&:nil?)
161
-
162
- @ui_presenter.display_info("Synthesizing results...")
163
- synth_t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
164
- final = decomposer.synthesize(prompt, results.compact)
165
- synth_dur = Process.clock_gettime(Process::CLOCK_MONOTONIC) - synth_t0
166
-
167
- total_wall = Process.clock_gettime(Process::CLOCK_MONOTONIC) - total_start
168
-
169
191
  lines = ["", "Benchmark:"]
170
192
  lines << " Decompose probe : #{format('%.2f', decompose_dur)}s"
171
193
  timings.each_with_index { |t, i| lines << " Sub-task #{i + 1} : #{format('%.2f', t)}s" }
@@ -175,21 +197,15 @@ module AIA
175
197
  lines << " Sub-tasks concurrent : #{format('%.2f', parallel_wall)}s (#{format('%.1f', parallel_speedup)}x parallel speedup)"
176
198
  lines << " Total flow wall time : #{format('%.2f', total_wall)}s (compare against --tokens Time for a normal run)"
177
199
  @ui_presenter.display_info(lines.join("\n"))
178
-
179
- display_decompose_token_metrics(raw_subtasks, final, total_wall)
180
-
181
- present_result(final, prompt: prompt, ui_presenter: @ui_presenter, tracker: @tracker)
182
- true
183
- rescue StandardError => e
184
- @ui_presenter.display_info("Decomposition failed: #{e.message}. Falling back to normal mode.")
185
- false
186
200
  end
187
201
 
202
+ # :reek:TooManyStatements -- ordered eligibility gates (server count, discovery, grouping) before the network run
188
203
  def handle_concurrent_mcp(prompt)
189
- return false unless (AIA.config.mcp_servers || []).size > 1
204
+ cfg = AIA.config
205
+ return false unless (cfg.mcp_servers || []).size > 1
190
206
 
191
207
  discovery = MCPDiscovery.new
192
- relevant = discovery.discover(AIA.config)
208
+ relevant = discovery.discover(cfg)
193
209
  return false if relevant.size <= 1
194
210
 
195
211
  grouper = MCPGrouper.new
@@ -198,7 +214,7 @@ module AIA
198
214
 
199
215
  @ui_presenter.display_info("Running concurrent MCP across #{groups.size} server groups...")
200
216
 
201
- network = RobotFactory.build_concurrent_mcp_network(AIA.config, groups)
217
+ network = RobotFactory.build_concurrent_mcp_network(cfg, groups)
202
218
  result = @ui_presenter.with_spinner("Processing (concurrent)") { network.run(message: prompt) }
203
219
  extract_content(result)
204
220
 
@@ -268,8 +284,15 @@ module AIA
268
284
  @ui_presenter.display_separator
269
285
  end
270
286
 
287
+ # For a handler that displayed its output as it went: save, don't repeat.
288
+ def save_live_output(content)
289
+ output_to_file(content)
290
+ @ui_presenter.display_separator
291
+ end
292
+
271
293
  # Aggregate token counts from all sub-task raw results plus the synthesis
272
294
  # result and display a combined metrics table. Only runs when --tokens is set.
295
+ # :reek:TooManyStatements -- sums token usage across sub-task results plus synthesis, then prints the metrics block
273
296
  def display_decompose_token_metrics(raw_subtasks, synthesis_result, total_elapsed)
274
297
  return unless AIA.config.flags.tokens
275
298
 
data/lib/aia/speech.rb ADDED
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ # lib/aia/speech.rb
4
+ #
5
+ # Shared text-to-speech behavior. Interactive handlers (ChatLoop,
6
+ # MentionRouter) include it: ContentExtractor duck-calls #speak on any
7
+ # includer that responds to it, and #speak only talks when --speak is on.
8
+ # The /say directive calls Speech.speak_text directly.
9
+
10
+ require 'shellwords'
11
+
12
+ module AIA
13
+ module Speech
14
+ # Players tried in order when audio.player is not set.
15
+ PLAYERS = [
16
+ %w[afplay],
17
+ %w[mpv --no-video --really-quiet],
18
+ %w[ffplay -nodisp -autoexit -loglevel quiet],
19
+ %w[mpg123 -q]
20
+ ].freeze
21
+
22
+ module_function
23
+
24
+ # Speak +text+ with the configured speak command (audio.speak_command,
25
+ # default macOS `say`), whether or not --speak is on.
26
+ #
27
+ # @param text [String]
28
+ # :reek:TooManyStatements -- two-stage TTS pipeline (convert, then play) with spinner and tempfile cleanup
29
+ def speak_text(text)
30
+ audio = AIA.config.audio
31
+ command = audio.speak_command || 'say'
32
+ env = {}
33
+ env['SPEECH_MODEL'] = audio.speech_model if audio.speech_model
34
+
35
+ if command == 'say'
36
+ # Local TTS: say converts and plays in one step
37
+ run_with_spinner("Speaking...") { system(env, *say_command(audio.voice, text)) }
38
+ else
39
+ speak_with_script(env, command, text)
40
+ end
41
+ rescue StandardError => e
42
+ $stderr.puts "Warning: Speech failed: #{e.message}"
43
+ end
44
+
45
+ # The macOS `say` argument list, with -v VOICE when a voice is set.
46
+ def say_command(voice, text)
47
+ voice.nil? || voice.to_s.strip.empty? ? ['say', text] : ['say', '-v', voice, text]
48
+ end
49
+
50
+ # Custom TTS script: convert text to an audio file (AIA passes the
51
+ # output path as $2), then play the file.
52
+ def speak_with_script(env, command, text)
53
+ require 'tempfile'
54
+ tmpfile = Tempfile.new(['aia-tts-', '.mp3'])
55
+ tmpfile.close
56
+ path = tmpfile.path
57
+ run_with_spinner("Converting to audio...") { system(env, command, text, path) }
58
+ play(path) if File.size?(path)
59
+ ensure
60
+ tmpfile&.unlink
61
+ end
62
+
63
+ # Play an audio file with audio.player, or the first known player found.
64
+ def play(path)
65
+ player = player_command(AIA.config.audio.player)
66
+ unless player
67
+ $stderr.puts "Warning: No audio player found. Set audio.player (for example `mpv`)."
68
+ return
69
+ end
70
+
71
+ run_with_spinner("Speaking...") { system(*player, path) }
72
+ end
73
+
74
+ # The player command as an argument list: the configured one (split like
75
+ # a shell would), or the first of PLAYERS on the PATH.
76
+ def player_command(configured)
77
+ return Shellwords.split(configured.to_s) unless configured.to_s.strip.empty?
78
+
79
+ PLAYERS.find { on_path?(it.first) }
80
+ end
81
+
82
+ def on_path?(program)
83
+ ENV['PATH'].to_s.split(File::PATH_SEPARATOR).any? { File.executable?(File.join(it, program)) }
84
+ end
85
+
86
+ def run_with_spinner(message)
87
+ spinner = TTY::Spinner.new("[:spinner] #{message}", format: :bouncing_ball, output: $stderr)
88
+ spinner.auto_spin
89
+ begin
90
+ yield
91
+ ensure
92
+ spinner.stop
93
+ end
94
+ end
95
+
96
+ # Speak a response when --speak is on.
97
+ def speak(content)
98
+ return unless AIA.speak?
99
+
100
+ Speech.speak_text(content.to_s)
101
+ end
102
+ end
103
+ end
@@ -2,9 +2,11 @@
2
2
 
3
3
  # lib/aia/startup_coordinator.rb
4
4
  #
5
- # Handles all session startup tasks: MCP connection, tool loading,
6
- # filter initialization, task coordination, and bus attachment.
7
- # Extracted from Session to give Session a single responsibility.
5
+ # Handles the session startup tasks that need the built robot: tool loading,
6
+ # filter initialization, task coordination, and bus attachment. MCP servers
7
+ # are connected before the robot is built (MCPConnectionManager.start) so
8
+ # every robot is handed the live servers. Extracted from Session to give
9
+ # Session a single responsibility.
8
10
 
9
11
  require "fileutils"
10
12
  require "tty-spinner"
@@ -12,20 +14,19 @@ require "tty-spinner"
12
14
  module AIA
13
15
  class StartupCoordinator
14
16
  attr_reader :filters, :mcp_manager
17
+ attr_writer :robot
15
18
 
16
- def initialize(robot:, ui_presenter:)
19
+ def initialize(robot:, ui_presenter:, mcp_manager: nil)
17
20
  @robot = robot
18
21
  @ui = ui_presenter
19
22
  @filters = {}
20
- @mcp_manager = nil
23
+ @mcp_manager = mcp_manager
21
24
  end
22
25
 
23
26
  # Run all startup coordination tasks.
24
27
  #
25
28
  # @param config [AIA::Config]
26
29
  def run(config)
27
- connect_mcp_servers(config)
28
-
29
30
  tools = all_available_tools(config)
30
31
 
31
32
  spinner = TTY::Spinner.new(" [:spinner] Initializing tool filters...", format: :dots)
@@ -33,79 +34,20 @@ module AIA
33
34
  @filters = ToolFilterRegistry.build_from_config(config, tools)
34
35
  spinner.success
35
36
 
36
- initialize_task_coordinator if trakflow_available?
37
-
38
37
  attach_bus_if_network
39
38
  end
40
39
 
41
- private
42
-
43
- # Connect ALL configured MCP servers eagerly at startup, then absorb any
44
- # MCP clients registered via --require (e.g., shared_tools/mcp/* files).
45
- # Uses MCPDiscovery to determine which servers to connect (respects
46
- # --mcp-use, --mcp-skip, and KBS mcp_activate decisions), then normalizes
47
- # each server config via MCPConfigNormalizer before handing off to
48
- # MCPConnectionManager.
49
- def connect_mcp_servers(config)
50
- return if config.flags.no_mcp
51
-
52
- discovered = MCPDiscovery.new.discover(config)
53
- validate_mcp_use_names(config, discovered) if Array(config.mcp_use).any?
54
-
55
- # Prefer the robot's pre-built mcp_config (already normalized) when
56
- # present, but always apply --mcp-skip so that flag is honoured.
57
- # Fall back to the MCPDiscovery result (which includes both filters).
58
- servers = if @robot.respond_to?(:mcp_config) && @robot.mcp_config.is_a?(Array)
59
- skip_list = Array(config.mcp_skip)
60
- @robot.mcp_config.reject { |s| skip_list.include?(AIA::Utility.server_name(s)) }
61
- else
62
- discovered.map { |s| MCPConfigNormalizer.normalize(s) }
63
- end
40
+ # Load the task-board tools. Call this before the robot is built, since
41
+ # the robot collects its tools when it is built. The board itself
42
+ # (TaskBoard) starts only when something records a task.
43
+ def prepare_task_board
44
+ return unless TaskBoard.gem_available?
64
45
 
65
- @mcp_manager = MCPConnectionManager.new
66
- @mcp_manager.connect_all(servers) if servers.is_a?(Array) && servers.any?
67
- @mcp_manager.absorb_ruby_llm_mcp_clients
68
- return unless @mcp_manager.connected?
69
-
70
- @mcp_manager.update_config
71
- @mcp_manager.inject_into(@robot) if @mcp_manager.any_tools?
72
- end
73
-
74
- # Initialize TaskCoordinator, auto-creating the TrakFlow project if needed.
75
- def initialize_task_coordinator
76
- require_relative 'task_coordinator'
77
- require_relative 'trakflow_bridge'
78
46
  require_relative 'tools/task_board_tool'
79
47
  require_relative 'tools/delegate_to_foreman_tool'
80
-
81
- ensure_trakflow_initialized unless TrakFlow.initialized?
82
-
83
- AIA.task_coordinator = TaskCoordinator.new
84
- rescue StandardError => e
85
- AIA.debug_warn("TaskCoordinator initialization failed (non-fatal): #{e.message}", exc: e)
86
48
  end
87
49
 
88
- # Return true if the trak_flow gem is available; false if it cannot be loaded.
89
- def trakflow_available?
90
- defined?(TrakFlow) || begin
91
- require 'trak_flow'
92
- true
93
- rescue LoadError
94
- false
95
- end
96
- end
97
-
98
- # Bootstrap a TrakFlow project so the task board is always available.
99
- # Uses the default database path (~/.config/trak_flow/tf.db).
100
- def ensure_trakflow_initialized
101
- trakflow_dir = TrakFlow.trak_flow_dir
102
- FileUtils.mkdir_p(trakflow_dir)
103
-
104
- db = TrakFlow::Storage::Database.new
105
- db.connect
106
-
107
- TrakFlow.reset_root!
108
- end
50
+ private
109
51
 
110
52
  # Attach a shared TypedBus to multi-model networks.
111
53
  def attach_bus_if_network
@@ -116,20 +58,6 @@ module AIA
116
58
  AIA.debug_warn("Bus attachment failed (non-fatal): #{e.message}", exc: e)
117
59
  end
118
60
 
119
- # Warn when --mcp-use names don't match any configured server.
120
- # Helps users catch typos before a silent empty-tools session.
121
- def validate_mcp_use_names(config, discovered_servers)
122
- requested = Array(config.mcp_use)
123
- available = Array(config.mcp_servers).map { |s| AIA::Utility.server_name(s) }
124
- found = discovered_servers.map { |s| AIA::Utility.server_name(s) }
125
- missing = requested - found
126
-
127
- return if missing.empty?
128
-
129
- $stderr.puts "WARNING: --mcp-use specified server(s) not found in config: #{missing.join(', ')}"
130
- $stderr.puts " Available servers: #{available.join(', ')}" if available.any?
131
- end
132
-
133
61
  # Collect all tools available to the robot: local + MCP.
134
62
  def all_available_tools(config)
135
63
  local = Array(config.loaded_tools)
@@ -137,13 +65,11 @@ module AIA
137
65
  local + mcp
138
66
  end
139
67
 
140
- # Retrieve MCP tools from the connection manager.
141
- # MCPConnectionManager builds RobotLab::Tool instances via connect_one and
142
- # absorb_ruby_llm_mcp_clients — those are what get injected into the robot
143
- # and what robot_lab filters by name. RubyLLM::MCP.clients is a different
144
- # registry and does not contain the tools connected here.
68
+ # MCP tools (RubyLLM::MCP::Tool) from the connection manager — the
69
+ # servers every robot is built with.
145
70
  def collect_mcp_tools
146
71
  return [] unless @mcp_manager
72
+
147
73
  @mcp_manager.connected_tools
148
74
  end
149
75
  end