phronomy 0.37.0 → 0.38.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 (211) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +87 -0
  3. data/README.md +24 -2
  4. data/SECURITY.md +1 -1
  5. data/docs/architecture/agent-approval-recovery.md +320 -0
  6. data/docs/architecture/agent-child-approval-recovery.md +387 -0
  7. data/docs/architecture/agent-child-execution-recovery.md +425 -0
  8. data/docs/architecture/agent-dispatch-recovery.md +308 -0
  9. data/docs/architecture/agent-terminal-persistence-evidence.md +360 -0
  10. data/docs/architecture/agent-terminal-recovery.md +298 -0
  11. data/docs/architecture/agent-terminal-submission-recovery.md +275 -0
  12. data/docs/architecture/agent-tool-child-lifetime.md +29 -0
  13. data/docs/architecture/agent-transition-ownership.md +24 -0
  14. data/docs/architecture/backend-groups.md +6 -0
  15. data/docs/architecture/detached-outcome-proof-projection.md +576 -0
  16. data/docs/architecture/execution-abstraction-review.md +5 -0
  17. data/docs/architecture/handoff-dispatch-recovery.md +205 -0
  18. data/docs/architecture/handoff-initial-terminal-application.md +321 -0
  19. data/docs/architecture/initial-preparation-recovery.md +308 -0
  20. data/docs/architecture/multi-agent-handoff.md +17 -0
  21. data/docs/architecture/native-outcome-preparation.md +715 -0
  22. data/docs/architecture/native-parent-dispatch-recovery.md +460 -0
  23. data/docs/architecture/native-parent-outcome-recovery.md +644 -0
  24. data/docs/architecture/parent-child-terminal-acknowledgement.md +297 -0
  25. data/docs/architecture/r8-unit12.md +6 -3
  26. data/docs/architecture/r8-unit4.md +11 -2
  27. data/docs/architecture/recovery-physical-attempt.md +88 -0
  28. data/docs/architecture/recovery-submission-custody.md +247 -0
  29. data/docs/architecture/retained-attempts.md +229 -0
  30. data/docs/architecture/retained-outcome-materialization.md +636 -0
  31. data/docs/architecture/retained-outcome-publication.md +506 -0
  32. data/docs/architecture/storage-execution-boundaries.md +1 -1
  33. data/docs/architecture/structured-output-and-scope.md +15 -0
  34. data/docs/architecture/synchronous-participant-application.md +397 -0
  35. data/docs/architecture/synchronous-participant-contract.md +195 -0
  36. data/docs/architecture/team-admission-rejection.md +91 -0
  37. data/docs/architecture/team-cancellation-delivery.md +245 -0
  38. data/docs/architecture/team-child-retirement.md +104 -0
  39. data/docs/architecture/tracing.md +26 -0
  40. data/docs/architecture/workflow-terminal-ownership-design.md +25 -9
  41. data/docs/architecture/workflow-terminal-reconciliation.md +221 -0
  42. data/docs/architecture.md +16 -9
  43. data/docs/decisions/025-process-local-agent-ownership-and-runtime-admission.md +8 -0
  44. data/docs/features.md +3 -3
  45. data/docs/mcp-client.md +138 -5
  46. data/docs/migrations/orchestrator-subagent-dispatch.md +89 -0
  47. data/docs/migrations/vector-async-clients.md +18 -3
  48. data/docs/persistence-backends.md +30 -4
  49. data/docs/runtime-and-concurrency.md +235 -11
  50. data/lib/phronomy/agent/admission.rb +37 -17
  51. data/lib/phronomy/agent/api/agent.rb +25 -0
  52. data/lib/phronomy/agent/approval_recovery.rb +30 -0
  53. data/lib/phronomy/agent/approval_recovery_api.rb +61 -0
  54. data/lib/phronomy/agent/approval_recovery_error.rb +39 -0
  55. data/lib/phronomy/agent/approval_recovery_result.rb +94 -0
  56. data/lib/phronomy/agent/async_event_api.rb +22 -5
  57. data/lib/phronomy/agent/base.rb +76 -48
  58. data/lib/phronomy/agent/context_preparation.rb +10 -8
  59. data/lib/phronomy/agent/dispatch_recovery.rb +29 -0
  60. data/lib/phronomy/agent/dispatch_recovery_api.rb +84 -0
  61. data/lib/phronomy/agent/dispatch_recovery_error.rb +36 -0
  62. data/lib/phronomy/agent/dispatch_recovery_result.rb +93 -0
  63. data/lib/phronomy/agent/execution/agent_invocation.rb +11 -3
  64. data/lib/phronomy/agent/execution/approval_continuation_plan.rb +131 -0
  65. data/lib/phronomy/agent/execution/approval_parent_evidence.rb +116 -0
  66. data/lib/phronomy/agent/execution/approval_persistence_evidence.rb +111 -0
  67. data/lib/phronomy/agent/execution/approval_recovery_operation.rb +496 -0
  68. data/lib/phronomy/agent/execution/approval_resume_commit.rb +174 -10
  69. data/lib/phronomy/agent/execution/dispatch_continuation_delivery.rb +96 -0
  70. data/lib/phronomy/agent/execution/dispatch_persistence_evidence.rb +147 -0
  71. data/lib/phronomy/agent/execution/dispatch_preparation.rb +63 -7
  72. data/lib/phronomy/agent/execution/dispatch_recovery_operation.rb +495 -0
  73. data/lib/phronomy/agent/execution/execution_coordinator.rb +724 -158
  74. data/lib/phronomy/agent/execution/execution_outcome_committer.rb +312 -39
  75. data/lib/phronomy/agent/execution/execution_registry.rb +508 -13
  76. data/lib/phronomy/agent/execution/initial_persistence_evidence.rb +269 -0
  77. data/lib/phronomy/agent/execution/initial_preparation.rb +132 -40
  78. data/lib/phronomy/agent/execution/initial_preparation_recovery_operation.rb +513 -0
  79. data/lib/phronomy/agent/execution/invocation_transitions.rb +3 -0
  80. data/lib/phronomy/agent/execution/outcome_planning.rb +108 -0
  81. data/lib/phronomy/agent/execution/outcome_preparation.rb +81 -0
  82. data/lib/phronomy/agent/execution/outcome_recovery_operation.rb +609 -0
  83. data/lib/phronomy/agent/execution/outcome_text_projection.rb +73 -0
  84. data/lib/phronomy/agent/execution/outcome_write_plan.rb +48 -0
  85. data/lib/phronomy/agent/execution/runtime_record_encoder.rb +7 -4
  86. data/lib/phronomy/agent/execution/terminal_persistence_evidence.rb +280 -0
  87. data/lib/phronomy/agent/execution/terminal_recovery_operation.rb +38 -0
  88. data/lib/phronomy/agent/execution_change.rb +138 -26
  89. data/lib/phronomy/agent/execution_environment.rb +29 -0
  90. data/lib/phronomy/agent/execution_rejected_error.rb +34 -0
  91. data/lib/phronomy/agent/initial_preparation_recovery.rb +32 -0
  92. data/lib/phronomy/agent/initial_preparation_recovery_api.rb +85 -0
  93. data/lib/phronomy/agent/initial_preparation_recovery_error.rb +41 -0
  94. data/lib/phronomy/agent/initial_preparation_recovery_result.rb +115 -0
  95. data/lib/phronomy/agent/lifecycle/hosted_approval_context.rb +86 -0
  96. data/lib/phronomy/agent/lifecycle/hosted_invocation.rb +42 -10
  97. data/lib/phronomy/agent/lifecycle/identity_write.rb +101 -0
  98. data/lib/phronomy/agent/lifecycle/lifetime_api.rb +28 -0
  99. data/lib/phronomy/agent/lifecycle/ownership_registry.rb +136 -70
  100. data/lib/phronomy/agent/lifecycle/scope.rb +3 -3
  101. data/lib/phronomy/agent/outcome_recovery.rb +47 -0
  102. data/lib/phronomy/agent/outcome_recovery_api.rb +114 -0
  103. data/lib/phronomy/agent/outcome_recovery_error.rb +36 -0
  104. data/lib/phronomy/agent/outcome_recovery_result.rb +92 -0
  105. data/lib/phronomy/agent/output_contract.rb +16 -6
  106. data/lib/phronomy/agent/persistence/identity_receipt_repository.rb +61 -0
  107. data/lib/phronomy/agent/persistence/records.rb +2 -0
  108. data/lib/phronomy/agent/persistence/storage_schema.rb +2 -0
  109. data/lib/phronomy/agent/recovery/invocation_restorer.rb +8 -5
  110. data/lib/phronomy/agent/recovery/recovery_coordinator/continuation.rb +6 -4
  111. data/lib/phronomy/agent/recovery/recovery_coordinator/installation.rb +21 -43
  112. data/lib/phronomy/agent/recovery/recovery_coordinator.rb +19 -6
  113. data/lib/phronomy/agent/runtime_binding/engine_environment.rb +12 -0
  114. data/lib/phronomy/agent/state_writer.rb +4 -3
  115. data/lib/phronomy/agent/store.rb +7 -1
  116. data/lib/phronomy/agent/terminal_recovery.rb +41 -0
  117. data/lib/phronomy/agent/terminal_recovery_api.rb +101 -0
  118. data/lib/phronomy/agent/terminal_recovery_error.rb +36 -0
  119. data/lib/phronomy/agent/terminal_recovery_result.rb +67 -0
  120. data/lib/phronomy/agent/tool_execution/tool_approval_request.rb +25 -1
  121. data/lib/phronomy/common/values/serializable.rb +37 -4
  122. data/lib/phronomy/engine/concurrency/offload_pool.rb +32 -4
  123. data/lib/phronomy/engine/concurrency/pool_registry.rb +6 -0
  124. data/lib/phronomy/engine/event_loop.rb +161 -11
  125. data/lib/phronomy/engine/execution_binding.rb +4 -2
  126. data/lib/phronomy/engine/execution_receiver_binding.rb +5 -0
  127. data/lib/phronomy/engine/runtime/shutdown_result.rb +21 -0
  128. data/lib/phronomy/engine/runtime/timer_queue.rb +7 -2
  129. data/lib/phronomy/engine/runtime.rb +119 -15
  130. data/lib/phronomy/execution/attempt_completion.rb +91 -0
  131. data/lib/phronomy/execution/concurrency/cancellation_token.rb +7 -2
  132. data/lib/phronomy/execution/concurrency/physical_completion_task.rb +7 -2
  133. data/lib/phronomy/execution/execution.rb +17 -2
  134. data/lib/phronomy/execution/execution_receiver.rb +27 -0
  135. data/lib/phronomy/execution/execution_retirement.rb +30 -0
  136. data/lib/phronomy/execution/invocation_controls.rb +2 -2
  137. data/lib/phronomy/execution/retained_attempts.rb +179 -0
  138. data/lib/phronomy/execution/stopped_terminal_custody.rb +99 -0
  139. data/lib/phronomy/llm_adapter/response.rb +7 -1
  140. data/lib/phronomy/multi_agent/admission_registry.rb +6 -0
  141. data/lib/phronomy/multi_agent/durable_subagent_coordinator.rb +175 -39
  142. data/lib/phronomy/multi_agent/handoff_dispatch_evidence.rb +176 -0
  143. data/lib/phronomy/multi_agent/handoff_finalization_error.rb +33 -0
  144. data/lib/phronomy/multi_agent/handoff_history_release.rb +80 -0
  145. data/lib/phronomy/multi_agent/handoff_participant.rb +31 -6
  146. data/lib/phronomy/multi_agent/handoff_runner.rb +195 -21
  147. data/lib/phronomy/multi_agent/handoff_terminal_finalization.rb +176 -0
  148. data/lib/phronomy/multi_agent/native_approval_evidence.rb +26 -0
  149. data/lib/phronomy/multi_agent/native_child_authority.rb +135 -0
  150. data/lib/phronomy/multi_agent/native_dispatch_evidence.rb +43 -0
  151. data/lib/phronomy/multi_agent/native_outcome_evidence.rb +46 -0
  152. data/lib/phronomy/multi_agent/native_persistence_plan.rb +93 -0
  153. data/lib/phronomy/multi_agent/orchestrator.rb +28 -52
  154. data/lib/phronomy/multi_agent/reserved_child_admission.rb +90 -1
  155. data/lib/phronomy/multi_agent/store.rb +5 -34
  156. data/lib/phronomy/multi_agent/subagent_history_release.rb +88 -0
  157. data/lib/phronomy/multi_agent/team_cancellation_delivery_error.rb +21 -0
  158. data/lib/phronomy/multi_agent/team_cancellation_request.rb +134 -0
  159. data/lib/phronomy/multi_agent/team_coordinator.rb +174 -27
  160. data/lib/phronomy/persistence_composition/stores.rb +10 -3
  161. data/lib/phronomy/runtime_composition/execution_defaults.rb +18 -0
  162. data/lib/phronomy/storage/backends/in_memory.rb +3 -1
  163. data/lib/phronomy/storage/resource.rb +10 -1
  164. data/lib/phronomy/tools/agent.rb +7 -1
  165. data/lib/phronomy/tools/mcp.rb +210 -91
  166. data/lib/phronomy/tools/mcp_http_close_response.rb +23 -0
  167. data/lib/phronomy/tools/mcp_transport_registry.rb +210 -0
  168. data/lib/phronomy/tools/vector_search.rb +28 -5
  169. data/lib/phronomy/tracing/automatic.rb +8 -1
  170. data/lib/phronomy/version.rb +1 -1
  171. data/lib/phronomy/workflow/execution/workflow.rb +34 -0
  172. data/lib/phronomy/workflow/execution/workflow_execution_environment.rb +1 -0
  173. data/lib/phronomy/workflow/execution/workflow_execution_registry.rb +106 -7
  174. data/lib/phronomy/workflow/execution/workflow_runner.rb +53 -108
  175. data/lib/phronomy/workflow/execution/workflow_terminal_operation.rb +489 -0
  176. data/lib/phronomy/workflow/execution/workflow_terminal_persistence.rb +81 -0
  177. data/lib/phronomy/workflow/execution/workflow_terminal_recovery.rb +38 -0
  178. data/lib/phronomy/workflow/execution/workflow_terminal_recovery_error.rb +34 -0
  179. data/lib/phronomy/workflow/execution/workflow_terminal_recovery_result.rb +56 -0
  180. data/lib/phronomy/workflow/runtime_binding/workflow_engine_environment.rb +10 -1
  181. data/lib/phronomy/workflow/runtime_binding/workflow_task_session.rb +3 -1
  182. data/lib/phronomy/workflow/runtime_binding/workflow_terminal_policy.rb +2 -1
  183. data/scripts/api_snapshot.rb +46 -1
  184. data/sig/_private/phronomy/multi_agent/team_cancellation_request.rbs +19 -0
  185. data/sig/phronomy/agent/approval_recovery.rbs +54 -0
  186. data/sig/phronomy/agent/dispatch_recovery.rbs +49 -0
  187. data/sig/phronomy/agent/execution_contract.rbs +4 -1
  188. data/sig/phronomy/agent/execution_environment.rbs +2 -0
  189. data/sig/phronomy/agent/initial_preparation_recovery.rbs +48 -0
  190. data/sig/phronomy/agent/outcome_recovery.rbs +51 -0
  191. data/sig/phronomy/agent/store.rbs +1 -0
  192. data/sig/phronomy/agent/terminal_persistence_evidence.rbs +111 -0
  193. data/sig/phronomy/agent/terminal_recovery.rbs +46 -0
  194. data/sig/phronomy/agent.rbs +36 -0
  195. data/sig/phronomy/engine/concurrency/timer_bindings.rbs +2 -0
  196. data/sig/phronomy/engine/execution_binding.rbs +2 -1
  197. data/sig/phronomy/engine/execution_receiver.rbs +4 -0
  198. data/sig/phronomy/engine/observability.rbs +22 -1
  199. data/sig/phronomy/execution/execution.rbs +16 -1
  200. data/sig/phronomy/execution/execution_receiver.rbs +12 -0
  201. data/sig/phronomy/execution/execution_retirement.rbs +18 -0
  202. data/sig/phronomy/execution/stopped_terminal_custody.rbs +19 -0
  203. data/sig/phronomy/handoff.rbs +1 -0
  204. data/sig/phronomy/multi_agent/handoff_finalization_error.rbs +18 -0
  205. data/sig/phronomy/multi_agent/store.rbs +1 -1
  206. data/sig/phronomy/multi_agent/team_cancellation_delivery_error.rbs +9 -0
  207. data/sig/phronomy/persistence_composition.rbs +2 -1
  208. data/sig/phronomy/storage/contracts.rbs +2 -1
  209. data/sig/phronomy/tools/mcp.rbs +27 -0
  210. data/sig/phronomy/workflow.rbs +42 -0
  211. metadata +104 -2
@@ -39,16 +39,104 @@ module Phronomy
39
39
  minLength maxLength pattern format default examples
40
40
  ].freeze
41
41
  SUPPORTED_TYPES = %w[string integer number boolean].freeze
42
- MCP_CLEANUP_POOL_SIZE = 2
43
- MCP_CLEANUP_QUEUE_SIZE = 100
44
42
 
45
43
  private_constant :SUPPORTED_SCHEMA_DIALECTS,
46
44
  :SUPPORTED_ROOT_KEYS,
47
45
  :SUPPORTED_PROPERTY_KEYS,
48
46
  :IGNORED_PROPERTY_KEYS,
49
- :SUPPORTED_TYPES,
50
- :MCP_CLEANUP_POOL_SIZE,
51
- :MCP_CLEANUP_QUEUE_SIZE
47
+ :SUPPORTED_TYPES
48
+
49
+ # A process-local view of the transports owned by one Tool or factory.
50
+ class CleanupHandle
51
+ # @api public
52
+ attr_reader :server_origin
53
+
54
+ # @api private
55
+ def initialize(registry, registry_mutex, server_origin:)
56
+ @server_origin = server_origin.dup.freeze
57
+ @registry = registry
58
+ @registry_mutex = registry_mutex
59
+ end
60
+
61
+ # Close through the original Tool's serialized call boundary, even if
62
+ # the host only retained the Runtime. A factory can also own failures.
63
+ # @api public
64
+ def close
65
+ tool = @registry_mutex.synchronize { @tool }
66
+ return tool.close if tool
67
+ Mcp.send(:raise_incomplete!, self)
68
+ end
69
+
70
+ # @api private
71
+ def attach(tool)
72
+ @registry_mutex.synchronize do
73
+ raise Phronomy::ToolError, "MCP cleanup scope already has a Tool" if @tool
74
+ @tool = tool
75
+ end
76
+ end
77
+
78
+ # @api public
79
+ def pending = @registry.pending(self)
80
+
81
+ # Performs a queued first close on the calling thread. A running or
82
+ # completed attempt is never repeated.
83
+ # @api public
84
+ def finish_queued(generation) = @registry.finish_queued(self, generation)
85
+
86
+ # Prepare a transfer of failed cleanup to one process-local recipient.
87
+ # @api public
88
+ def offer_failed(generation, receiver:) = @registry.offer(self, generation, receiver)
89
+
90
+ # @api private
91
+ def check_admission! = @registry.check_admission!
92
+
93
+ # @api private
94
+ def acquire(purpose, &build) = @registry.acquire(self, purpose, &build)
95
+
96
+ # @api private
97
+ def close_entry(entry, primary_error:, async: false)
98
+ @registry.close(entry, primary_error: primary_error, async: async)
99
+ end
100
+ end
101
+
102
+ # Only the designated management recipient can accept. The receipt keeps
103
+ # the original SDK object and both errors available after acceptance.
104
+ class CleanupTransfer
105
+ # @api private
106
+ def initialize(receiver, registry_mutex, &accept)
107
+ @receiver = receiver
108
+ @accept = accept
109
+ @registry_mutex = registry_mutex
110
+ end
111
+
112
+ # @api private
113
+ def receiver?(receiver) = @receiver.equal?(receiver)
114
+
115
+ # @api public
116
+ def accept!(receiver:)
117
+ raise Phronomy::ToolError, "Incorrect MCP transfer receiver" unless receiver?(receiver)
118
+ @registry_mutex.synchronize do
119
+ # Removing the obligation and publishing its receipt form one change.
120
+ Thread.handle_interrupt(Object => :never) do
121
+ @receipt ||= @accept.call
122
+ @accept = nil
123
+ @receipt
124
+ end
125
+ end
126
+ end
127
+ end
128
+
129
+ class CleanupError < Phronomy::ToolError
130
+ attr_reader :cleanup_handle, :pending, :primary_error
131
+
132
+ # @api private
133
+ def initialize(cleanup_handle, pending, primary_error)
134
+ @cleanup_handle = cleanup_handle
135
+ @pending = pending
136
+ @primary_error = primary_error
137
+ super("MCP transport cleanup is incomplete (#{pending.size} retained)", code: "mcp.cleanup_incomplete")
138
+ end
139
+ end
52
140
 
53
141
  class << self
54
142
  # Build a Mcp instance by querying a running MCP server for the
@@ -63,26 +151,71 @@ module Phronomy
63
151
  # @return [Mcp] configured tool instance
64
152
  # @api public
65
153
  def from_server(server_uri, tool_name:, headers: {})
66
- transport = nil
67
- begin
68
- transport = build_transport(server_uri, headers: headers)
69
- client = MCP::Client.new(transport: transport)
70
- client.connect
71
- tool_def = extract_tool_def(client, tool_name.to_s, server_uri)
72
- rescue ArgumentError, Phronomy::ToolError
73
- raise
74
- rescue => e
75
- raise Phronomy::ToolError, "MCP connection failed: #{e.message}"
76
- ensure
77
- close_transport_safely(transport)
154
+ scope = cleanup_scope(server_uri)
155
+ tool_def = Thread.handle_interrupt(Object => :never) do
156
+ entry = scope.acquire(:discovery) do |reservation|
157
+ acquire_transport(server_uri, headers: headers, reservation: reservation)
158
+ end
159
+ primary = nil
160
+ begin
161
+ Thread.handle_interrupt(Object => :immediate) do
162
+ client = MCP::Client.new(transport: entry.transport)
163
+ client.connect
164
+ extract_tool_def(client, tool_name.to_s, server_uri)
165
+ end
166
+ rescue Exception => error # rubocop:disable Lint/RescueException
167
+ primary = error
168
+ raise if !error.is_a?(StandardError) || error.is_a?(ArgumentError) || error.is_a?(Phronomy::ToolError)
169
+ raise Phronomy::ToolError, "MCP connection failed: #{error.message}"
170
+ ensure
171
+ scope.close_entry(entry, primary_error: primary)
172
+ raise_incomplete!(scope, primary) if !primary || primary.is_a?(StandardError)
173
+ end
78
174
  end
79
175
 
80
- build_tool_class(tool_name, server_uri, tool_def, headers: headers).new
176
+ build_tool_class(tool_name, server_uri, tool_def, headers: headers).new(cleanup_handle: scope)
177
+ end
178
+
179
+ # Lookup only. Supplying the originating Runtime also works after shutdown.
180
+ # @api public
181
+ def cleanup_handles(runtime: nil)
182
+ McpTransportRegistry.lookup.call(runtime)&.handles || [].freeze
81
183
  end
82
184
 
83
185
  private
84
186
 
85
- def build_transport(uri, headers: {})
187
+ def cleanup_scope(server_uri)
188
+ McpTransportRegistry.provider.call.cleanup_handle(server_origin: origin_metadata(server_uri).fetch(:server_origin))
189
+ end
190
+
191
+ def origin_metadata(server_uri)
192
+ scheme, rest = server_uri.to_s.split("://", 2)
193
+ server_origin = case scheme
194
+ when "http", "https"
195
+ uri = URI.parse("#{scheme}://#{rest}")
196
+ default_port = (scheme == "https") ? 443 : 80
197
+ suffix = (uri.port == default_port) ? "" : ":#{uri.port}"
198
+ "#{scheme}://#{uri.host}#{suffix}"
199
+ when "stdio"
200
+ command = Shellwords.split(rest.to_s).first
201
+ "stdio://#{command}"
202
+ else
203
+ scheme.to_s
204
+ end
205
+ {transport: scheme&.to_sym, server_origin: server_origin}
206
+ rescue URI::InvalidURIError
207
+ {transport: :unknown, server_origin: "unknown"}
208
+ end
209
+
210
+ def acquire_transport(uri, headers:, reservation:)
211
+ build_transport(uri, headers: headers, reservation: reservation)
212
+ rescue ArgumentError, Phronomy::ToolError
213
+ raise
214
+ rescue => error
215
+ raise Phronomy::ToolError, "MCP connection failed: #{error.message}"
216
+ end
217
+
218
+ def build_transport(uri, headers:, reservation:)
86
219
  scheme, path = uri.split("://", 2)
87
220
  case scheme
88
221
  when "stdio"
@@ -93,7 +226,9 @@ module Phronomy
93
226
 
94
227
  MCP::Client::Stdio.new(command: argv[0], args: argv[1..])
95
228
  when "http", "https"
96
- MCP::Client::HTTP.new(url: uri, headers: headers)
229
+ MCP::Client::HTTP.new(url: uri, headers: headers) do |connection|
230
+ connection.use(McpHttpCloseResponse, reservation)
231
+ end
97
232
  else
98
233
  raise ArgumentError,
99
234
  "Unsupported MCP transport scheme: #{scheme.inspect}. " \
@@ -281,10 +416,10 @@ module Phronomy
281
416
  end
282
417
  end
283
418
 
284
- def close_transport_safely(transport)
285
- transport&.close
286
- rescue
287
- nil
419
+ def raise_incomplete!(scope, primary = nil)
420
+ pending = scope.pending
421
+ return if pending.empty?
422
+ raise CleanupError.new(scope, pending, primary), cause: primary || pending.first[:cleanup_error]
288
423
  end
289
424
  end
290
425
 
@@ -294,29 +429,18 @@ module Phronomy
294
429
  end
295
430
 
296
431
  def approval_metadata
297
- scheme, rest = self.class.instance_variable_get(:@mcp_server_uri).to_s.split("://", 2)
298
- server_origin = case scheme
299
- when "http", "https"
300
- uri = URI.parse("#{scheme}://#{rest}")
301
- default_port = (scheme == "https") ? 443 : 80
302
- suffix = (uri.port == default_port) ? "" : ":#{uri.port}"
303
- "#{scheme}://#{uri.host}#{suffix}"
304
- when "stdio"
305
- command = Shellwords.split(rest.to_s).first
306
- "stdio://#{command}"
307
- else
308
- scheme.to_s
309
- end
310
- {transport: scheme&.to_sym, server_origin: server_origin}
311
- rescue URI::InvalidURIError
312
- {transport: :unknown, server_origin: "unknown"}
432
+ self.class.send(:origin_metadata, self.class.instance_variable_get(:@mcp_server_uri))
313
433
  end
314
434
 
315
435
  # @api private
316
- def initialize
436
+ def initialize(cleanup_handle: nil)
437
+ @cleanup_handle = cleanup_handle || self.class.send(:cleanup_scope, self.class.instance_variable_get(:@mcp_server_uri))
317
438
  @mcp_call_mutex = Mutex.new
318
439
  @mcp_client = nil
319
- build_and_connect_client!
440
+ @mcp_call_mutex.synchronize do
441
+ @cleanup_handle.attach(self)
442
+ build_and_connect_client!
443
+ end
320
444
  end
321
445
 
322
446
  # Executes the remote MCP tool.
@@ -325,21 +449,25 @@ module Phronomy
325
449
  # @api public
326
450
  def execute(cancellation_token: nil, **args)
327
451
  @mcp_call_mutex.synchronize do
452
+ @cleanup_handle.check_admission!
328
453
  ensure_mcp_client!
329
454
  perform_mcp_call(cancellation_token: cancellation_token, args: args)
330
455
  end
331
456
  end
332
457
 
333
- # Closes the currently connected client synchronously. A transport already
334
- # detached after cancellation is owned by the Runtime cleanup pool and is
335
- # drained during Runtime shutdown; this method does not wait for that older
336
- # cleanup operation.
337
- #
338
- # The instance can be used again after close; the next call reconnects.
339
- # @return [void]
458
+ # Management access to this Tool's current and detached generations.
459
+ # @api public
460
+ attr_reader :cleanup_handle
461
+
462
+ # Closes the current connection synchronously. Reports any pending or
463
+ # failed detached cleanup immediately. A later call may reconnect.
464
+ # @raise [CleanupError] if this scope still owns transports
340
465
  # @api public
341
466
  def close
342
- @mcp_call_mutex.synchronize { invalidate_mcp_client! }
467
+ @mcp_call_mutex.synchronize do
468
+ detach_mcp_client!(primary_error: nil)
469
+ self.class.send(:raise_incomplete!, @cleanup_handle)
470
+ end
343
471
  end
344
472
 
345
473
  private
@@ -354,7 +482,7 @@ module Phronomy
354
482
  cancellation: mcp_cancellation
355
483
  )
356
484
  rescue MCP::CancelledError => e
357
- invalidate_mcp_client_after_cancellation!
485
+ detach_mcp_client!(primary_error: e, async: true)
358
486
  message = "MCP tool call was cancelled"
359
487
  message += ": #{e.reason}" if e.respond_to?(:reason) && e.reason
360
488
  raise Phronomy::CancellationError, message
@@ -398,7 +526,8 @@ module Phronomy
398
526
  begin
399
527
  @mcp_client.connect
400
528
  rescue => reconnect_error
401
- invalidate_mcp_client!
529
+ detach_mcp_client!(primary_error: reconnect_error)
530
+ self.class.send(:raise_incomplete!, @cleanup_handle, reconnect_error)
402
531
  raise Phronomy::ToolError,
403
532
  "MCP session expired and reconnection failed: #{reconnect_error.message}"
404
533
  end
@@ -455,48 +584,38 @@ module Phronomy
455
584
  end
456
585
 
457
586
  def build_and_connect_client!
458
- transport = nil
459
- begin
460
- uri = self.class.instance_variable_get(:@mcp_server_uri)
461
- headers = self.class.instance_variable_get(:@mcp_headers) || {}
462
- transport = self.class.send(:build_transport, uri, headers: headers)
463
- client = MCP::Client.new(transport: transport)
464
- client.connect
465
- @mcp_client = client
466
- rescue => e
467
- self.class.send(:close_transport_safely, transport)
468
- raise Phronomy::ToolError, "MCP connection failed: #{e.message}"
587
+ uri = self.class.instance_variable_get(:@mcp_server_uri)
588
+ headers = self.class.instance_variable_get(:@mcp_headers) || {}
589
+ Thread.handle_interrupt(Object => :never) do
590
+ entry = @cleanup_handle.acquire(:connection) do |reservation|
591
+ self.class.send(:acquire_transport, uri, headers: headers, reservation: reservation)
592
+ end
593
+ primary = nil
594
+ begin
595
+ client = Thread.handle_interrupt(Object => :immediate) do
596
+ MCP::Client.new(transport: entry.transport).tap(&:connect)
597
+ end
598
+ @mcp_entry = entry
599
+ @mcp_client = client
600
+ rescue Exception => error # rubocop:disable Lint/RescueException
601
+ primary = error
602
+ raise unless error.is_a?(StandardError)
603
+ raise Phronomy::ToolError, "MCP connection failed: #{error.message}"
604
+ ensure
605
+ unless @mcp_entry.equal?(entry)
606
+ @cleanup_handle.close_entry(entry, primary_error: primary)
607
+ self.class.send(:raise_incomplete!, @cleanup_handle, primary) if !primary || primary.is_a?(StandardError)
608
+ end
609
+ end
469
610
  end
470
611
  end
471
612
 
472
- def invalidate_mcp_client!
473
- old_client = @mcp_client
474
- @mcp_client = nil
475
- self.class.send(:close_transport_safely, old_client&.transport)
476
- end
477
-
478
- def invalidate_mcp_client_after_cancellation!
479
- old_client = @mcp_client
480
- @mcp_client = nil
481
- return unless old_client
482
-
483
- schedule_transport_cleanup(old_client.transport)
484
- end
485
-
486
- def schedule_transport_cleanup(transport)
487
- Phronomy::Execution.submit(
488
- pool_name: :mcp_cleanup,
489
- size: MCP_CLEANUP_POOL_SIZE,
490
- queue_size: MCP_CLEANUP_QUEUE_SIZE,
491
- on_full: :raise
492
- ) do
493
- self.class.send(:close_transport_safely, transport)
494
- end
495
- rescue Phronomy::BackpressureError, Phronomy::PoolShutdownError, Phronomy::RuntimeShutdownError
496
- # During shutdown or an exceptional cleanup burst, prefer a bounded
497
- # synchronous fallback over leaking the child process/socket. Runtime
498
- # can reject acquisition before the cleanup pool itself is consulted.
499
- self.class.send(:close_transport_safely, transport)
613
+ def detach_mcp_client!(primary_error:, async: false)
614
+ Thread.handle_interrupt(Object => :never) do
615
+ entry = @mcp_entry
616
+ @mcp_entry = @mcp_client = nil
617
+ @cleanup_handle.close_entry(entry, primary_error: primary_error, async: async) if entry
618
+ end
500
619
  end
501
620
  end
502
621
  end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+
5
+ module Phronomy
6
+ module Tools
7
+ # The SDK's Faraday customization block installs this observer on the exact
8
+ # connection that sends the session DELETE. Keep only its numerical status.
9
+ # @api private
10
+ class McpHttpCloseResponse < Faraday::Middleware
11
+ def initialize(app, entry)
12
+ super(app)
13
+ @entry = entry
14
+ end
15
+
16
+ def on_complete(env)
17
+ return unless env.method == :delete && @entry.session_id
18
+ return unless env.request_headers["Mcp-Session-Id"] == @entry.session_id
19
+ @entry.http_status = env.status
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,210 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Tools
5
+ # A shutdown participant for one Runtime. A reservation covers the entire
6
+ # lifetime of an SDK transport, including discovery before a Tool exists.
7
+ # @api private
8
+ class McpTransportRegistry
9
+ CAPACITY = 100
10
+ Entry = Struct.new(:scope, :generation, :purpose, :state, :transport,
11
+ :primary_error, :cleanup_error, :session_id, :http_status, :transfer)
12
+ private_constant :Entry
13
+
14
+ class << self
15
+ attr_accessor :provider, :lookup
16
+ end
17
+
18
+ def initialize(&submit)
19
+ @submit = submit
20
+ @mutex = Mutex.new
21
+ @changed = ConditionVariable.new
22
+ @entries = {}
23
+ @generation = 0
24
+ @draining = false
25
+ end
26
+
27
+ def check_admission!
28
+ @mutex.synchronize { ensure_accepting! }
29
+ end
30
+
31
+ def cleanup_handle(server_origin:)
32
+ Mcp::CleanupHandle.new(self, @mutex, server_origin: server_origin)
33
+ end
34
+
35
+ def acquire(scope, purpose)
36
+ # SDK construction allocates a handle; connect starts the transport.
37
+ # Defer asynchronous exceptions until its generation can own that handle.
38
+ Thread.handle_interrupt(Object => :never) do
39
+ entry = @mutex.synchronize do
40
+ ensure_accepting!
41
+ if @entries.size >= CAPACITY
42
+ raise Phronomy::BackpressureError, "MCP transport capacity is exhausted"
43
+ end
44
+ @generation += 1
45
+ @entries[@generation] = Entry.new(scope: scope, generation: @generation,
46
+ purpose: purpose, state: :reserved)
47
+ end
48
+ published = false
49
+ begin
50
+ transport = yield(entry)
51
+ @mutex.synchronize do
52
+ entry.transport = transport
53
+ entry.state = :open
54
+ end
55
+ published = true
56
+ entry
57
+ ensure
58
+ forget(entry) unless published
59
+ end
60
+ end
61
+ end
62
+
63
+ def close(entry, primary_error:, async: false)
64
+ @mutex.synchronize do
65
+ raise Phronomy::ToolError, "MCP transport is already detached" unless entry.state == :open
66
+ entry.primary_error = primary_error
67
+ entry.state = :queued
68
+ end
69
+ if async
70
+ begin
71
+ @submit.call { run_close(entry) }
72
+ rescue
73
+ # A submitter can raise even after dispatch. Both paths must win
74
+ # the same claim before touching the transport.
75
+ run_close(entry)
76
+ end
77
+ else
78
+ run_close(entry)
79
+ end
80
+ end
81
+
82
+ def finish_queued(scope, generation)
83
+ entry = @mutex.synchronize { @entries[generation] }
84
+ return false unless entry && entry.scope.equal?(scope)
85
+ run_close(entry)
86
+ end
87
+
88
+ def pending(scope)
89
+ origin = scope.server_origin
90
+ @mutex.synchronize do
91
+ @entries.values.filter_map do |entry|
92
+ next unless entry.scope.equal?(scope)
93
+ {generation: entry.generation, purpose: entry.purpose, state: entry.state,
94
+ server_origin: origin, transport_id: entry.transport&.object_id, primary_error: entry.primary_error,
95
+ cleanup_error: entry.cleanup_error, http_status: (entry.http_status if entry.state == :failed)}.freeze
96
+ end.freeze
97
+ end
98
+ end
99
+
100
+ def handles
101
+ @mutex.synchronize { @entries.values.map(&:scope).uniq.freeze }
102
+ end
103
+
104
+ def offer(scope, generation, receiver)
105
+ raise ArgumentError, "a transfer receiver is required" unless receiver
106
+ origin = scope.server_origin
107
+ transfer = @mutex.synchronize do
108
+ entry = @entries[generation]
109
+ unless entry&.scope.equal?(scope) && entry.state == :failed
110
+ raise Phronomy::ToolError, "Only a finished, failed transport close can transfer"
111
+ end
112
+ entry.transfer ||= Mcp::CleanupTransfer.new(receiver, @mutex) do
113
+ payload = {transport: entry.transport, generation: entry.generation,
114
+ server_origin: origin, session_id: entry.session_id,
115
+ primary_error: entry.primary_error, cleanup_error: entry.cleanup_error, http_status: entry.http_status}.freeze
116
+ @entries.delete(entry.generation)
117
+ @changed.broadcast
118
+ payload
119
+ end
120
+ end
121
+ raise Phronomy::ToolError, "A different receiver owns this offer" unless transfer.receiver?(receiver)
122
+ transfer
123
+ end
124
+
125
+ def begin_draining
126
+ @mutex.synchronize { @draining = true }
127
+ end
128
+
129
+ # Independent, nonblocking evidence for administrative reconciliation.
130
+ # @api private
131
+ def shutdown_cleanup_ready?
132
+ @mutex.synchronize { @draining && @entries.empty? }
133
+ end
134
+
135
+ def wait_until_idle(deadline)
136
+ @mutex.synchronize do
137
+ until @entries.empty?
138
+ # Open transports still belong to their caller. Failed closes need
139
+ # a recipient. Neither condition can be resolved by a pool drain.
140
+ return false if @entries.any? { |_, entry| [:open, :reserved, :failed].include?(entry.state) }
141
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
142
+ return false unless remaining.positive?
143
+ @changed.wait(@mutex, remaining)
144
+ end
145
+ true
146
+ end
147
+ end
148
+
149
+ private
150
+
151
+ def ensure_accepting!
152
+ raise Phronomy::RuntimeShutdownError, "MCP transport admission has closed" if @draining
153
+ end
154
+
155
+ def run_close(entry)
156
+ Thread.handle_interrupt(Object => :never) do
157
+ claimed = @mutex.synchronize do
158
+ next false unless entry.state == :queued
159
+ entry.state = :closing
160
+ true
161
+ end
162
+ return false unless claimed
163
+ completed = false
164
+ begin
165
+ Thread.handle_interrupt(Object => :immediate) { close_transport(entry) }
166
+ completed = true
167
+ rescue Exception => error # rubocop:disable Lint/RescueException
168
+ failure = error
169
+ raise unless error.is_a?(StandardError)
170
+ ensure
171
+ if completed
172
+ forget(entry)
173
+ else
174
+ # A throw or thread exit can unwind the SDK without an exception
175
+ # object. Only the returned close proves its release condition.
176
+ @mutex.synchronize do
177
+ entry.cleanup_error = failure || Phronomy::ToolError.new("MCP transport close ended without confirmation")
178
+ entry.state = :failed
179
+ @changed.broadcast
180
+ end
181
+ end
182
+ end
183
+ end
184
+ true
185
+ end
186
+
187
+ def close_transport(entry)
188
+ # The HTTP SDK can clear its local session ID even when DELETE fails.
189
+ # Keep it solely for the explicitly accepting management recipient.
190
+ if entry.transport.respond_to?(:session_id)
191
+ entry.session_id = entry.transport.session_id&.dup&.freeze
192
+ end
193
+ entry.transport.close
194
+ if entry.session_id && ![200, 204, 404].include?(entry.http_status)
195
+ status = entry.http_status ? "HTTP #{entry.http_status}" : "no matching DELETE response"
196
+ raise Phronomy::ToolError.new("MCP session termination is unconfirmed (#{status})",
197
+ code: "mcp.session_termination_unconfirmed")
198
+ end
199
+ end
200
+
201
+ def forget(entry)
202
+ @mutex.synchronize do
203
+ entry.state = :released
204
+ @entries.delete(entry.generation)
205
+ @changed.broadcast
206
+ end
207
+ end
208
+ end
209
+ end
210
+ end
@@ -2,7 +2,7 @@
2
2
 
3
3
  module Phronomy
4
4
  module Tools
5
- # A Capability::Base subclass that wraps a {Phronomy::VectorStore::Base} and
5
+ # A Tool::Base subclass that wraps a {Phronomy::VectorStore::Base} and
6
6
  # a {Phronomy::Embeddings::Base} adapter so that an agent can
7
7
  # perform semantic search as a tool call.
8
8
  #
@@ -44,9 +44,18 @@ module Phronomy
44
44
  @k = k
45
45
  end
46
46
 
47
- klass.define_method(:execute) do |query:|
48
- embedding = @embeddings.embed(query)
49
- results = @store.search(query_embedding: embedding, k: @k)
47
+ klass.define_method(:execute) do |query:, cancellation_token: nil|
48
+ cancellation_token&.raise_if_cancelled!
49
+ embedding = if cancellation_token && embed_accepts_token?
50
+ @embeddings.embed(query, cancellation_token)
51
+ else
52
+ @embeddings.embed(query)
53
+ end
54
+
55
+ cancellation_token&.raise_if_cancelled!
56
+ search_args = {query_embedding: embedding, k: @k}
57
+ search_args[:cancellation_token] = cancellation_token if cancellation_token && search_accepts_token?
58
+ results = @store.search(**search_args)
50
59
  return "No results found." if results.empty?
51
60
 
52
61
  results.map.with_index(1) do |r, i|
@@ -62,9 +71,23 @@ module Phronomy
62
71
  end
63
72
 
64
73
  # @api public
65
- def execute(query:)
74
+ def execute(query:, cancellation_token: nil)
66
75
  raise NotImplementedError, "Use VectorSearch.from_store to create a configured instance"
67
76
  end
77
+
78
+ private
79
+
80
+ def embed_accepts_token?
81
+ parameters = @embeddings.method(:embed).parameters
82
+ parameters.any? { |kind, _| kind == :rest } ||
83
+ parameters.count { |kind, _| %i[req opt].include?(kind) } >= 2
84
+ end
85
+
86
+ def search_accepts_token?
87
+ @store.method(:search).parameters.any? do |kind, name|
88
+ kind == :keyrest || (%i[key keyreq].include?(kind) && name == :cancellation_token)
89
+ end
90
+ end
68
91
  end
69
92
  end
70
93
  end