a2a-rails 0.3.0 → 0.5.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.
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module A2A
6
+ module Rails
7
+ # A normal, non-terminal Handler outcome. Never inferred from a Hash key.
8
+ class InputRequired
9
+ attr_reader :text
10
+
11
+ def initialize(text, data: nil)
12
+ unless text.is_a?(String) && !text.strip.empty?
13
+ raise ArgumentError, "InputRequired text must be a nonempty String"
14
+ end
15
+ unless data.nil? || data.is_a?(Hash)
16
+ raise ArgumentError, "InputRequired data must be a JSON object"
17
+ end
18
+ @text = text.dup.freeze
19
+ @data = data.nil? ? nil : copy_json(data)
20
+ freeze
21
+ end
22
+
23
+ def parts
24
+ result = [{ text: @text.dup }]
25
+ result << { data: copy_json(@data), media_type: "application/json" } unless @data.nil?
26
+ result
27
+ end
28
+
29
+ private
30
+
31
+ def copy_json(value)
32
+ case value
33
+ when Hash
34
+ value.each_with_object({}) do |(key, nested), result|
35
+ raise ArgumentError, "InputRequired JSON keys must be Strings" unless key.is_a?(String)
36
+ result[key.dup] = copy_json(nested)
37
+ end
38
+ when Array then value.map { |item| copy_json(item) }
39
+ when String then value.dup
40
+ when Integer, TrueClass, FalseClass, NilClass then value
41
+ when Float
42
+ raise ArgumentError, "InputRequired JSON numbers must be finite" unless value.finite?
43
+ value
44
+ else
45
+ raise ArgumentError, "InputRequired data must contain JSON values"
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -5,6 +5,7 @@ require "rack"
5
5
  require "stringio"
6
6
  require_relative "adapter"
7
7
  require_relative "task_mapper"
8
+ require_relative "part_data"
8
9
 
9
10
  module A2A
10
11
  module Rails
@@ -90,8 +91,26 @@ module A2A
90
91
  request = env.fetch("a2a.request")
91
92
  validate_request!(request)
92
93
 
93
- result = @request_handler.call(operation: operation, params: request.to_h)
94
+ params = request.to_h
95
+ if operation == "SendMessage"
96
+ # The binding retains the parsed original params before Definition
97
+ # recursively removes nil values. Preserve Data only after the
98
+ # usual SDK validation; Rails still validates its input contract.
99
+ params = PartData.restore_request(params, env["a2a.body"])
100
+ end
101
+ result = @request_handler.call(operation: operation, params: params)
94
102
  schema(RESPONSE_SCHEMAS.fetch(operation), result)
103
+ rescue A2A::Rails::InvalidAgentResponseError
104
+ raise A2A::InvalidAgentResponseError.new
105
+ rescue A2A::Rails::TaskStorePayloadLimitError
106
+ raise A2A::InvalidParamsError.new("Task history or payload limit reached; cancel and start a new Task")
107
+ rescue A2A::Rails::TaskNotResumableError => error
108
+ if Task::TERMINAL_STATES.include?(error.state)
109
+ raise A2A::UnsupportedOperationError.new(message: "Terminal Task cannot accept new input")
110
+ end
111
+ raise A2A::InvalidParamsError.new("Task does not accept new input in its current state")
112
+ rescue A2A::Rails::TaskContinuationUnavailableError
113
+ raise A2A::UnsupportedOperationError.new(message: "Task has no resumable execution metadata")
95
114
  rescue A2A::Rails::TaskNotFoundError => error
96
115
  raise A2A::TaskNotFoundError.new(error.task_id)
97
116
  rescue A2A::Rails::TaskNotCancelableError => error
@@ -128,7 +147,9 @@ module A2A
128
147
  def schema(name, value)
129
148
  object = A2A::Protocol::JsonSchema[name].new(value)
130
149
  object.valid!
131
- object
150
+ # Return the SDK-normalized protocol shape, with only opaque Data
151
+ # restored. The SDK binding remains responsible for JSON-RPC output.
152
+ PartData.restore_response(name, object.to_h, value)
132
153
  end
133
154
  end
134
155
  end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ module A2A
4
+ module Rails
5
+ module Protocol
6
+ # Local compatibility boundary for agent2agent 2.0's recursive nil
7
+ # compaction. Protocol fields still use the SDK's normalization; only
8
+ # Part content is restored from the original plain-Ruby representation.
9
+ # In particular, this does not change metadata serialization.
10
+ module PartData
11
+ CONTENT_FIELDS = %w[text data raw url].freeze
12
+
13
+ module_function
14
+
15
+ def restore_request(params, original)
16
+ return params unless params.is_a?(Hash) && original.is_a?(Hash)
17
+
18
+ restore_message(params["message"], original["message"], request: true)
19
+ params
20
+ end
21
+
22
+ def restore_response(name, normalized, original)
23
+ case name
24
+ when "Send Message Response"
25
+ restore_message(normalized["message"], original["message"])
26
+ restore_task(normalized["task"], original["task"])
27
+ when "Task"
28
+ restore_task(normalized, original)
29
+ when "List Tasks Response"
30
+ each_pair(normalized["tasks"], original["tasks"]) do |task, source|
31
+ restore_task(task, source)
32
+ end
33
+ end
34
+ normalized
35
+ end
36
+
37
+ def restore_task(task, original)
38
+ return unless task.is_a?(Hash) && original.is_a?(Hash)
39
+
40
+ each_pair(task["history"], original["history"]) do |message, source|
41
+ restore_message(message, source)
42
+ end
43
+ each_pair(task["artifacts"], original["artifacts"]) do |artifact, source|
44
+ restore_message(artifact, source)
45
+ end
46
+ status = task["status"]
47
+ source_status = original["status"]
48
+ if status.is_a?(Hash) && source_status.is_a?(Hash)
49
+ restore_message(status["message"], source_status["message"])
50
+ end
51
+ end
52
+
53
+ def restore_message(message, original, request: false)
54
+ return unless message.is_a?(Hash) && original.is_a?(Hash)
55
+
56
+ each_pair(message["parts"], original["parts"]) do |part, source|
57
+ next unless part.is_a?(Hash) && source.is_a?(Hash)
58
+
59
+ # Preserve original kind-field presence so the Rails input contract
60
+ # can reject ambiguous Parts even when one field is JSON null.
61
+ fields = request ? CONTENT_FIELDS : ["data"]
62
+ fields.each { |field| part[field] = copy(source[field]) if source.key?(field) }
63
+ next unless request && source.key?("data")
64
+
65
+ # Accept the same alternate spelling as the SDK, but avoid
66
+ # choosing a Data media type based on field order.
67
+ keys = %w[mediaType media_type].select { |key| source.key?(key) }
68
+ if keys.size > 1
69
+ raise InvalidRequestError, "Data Part must not specify mediaType more than once"
70
+ end
71
+ part["mediaType"] = source.fetch(keys.first) if keys.one?
72
+ end
73
+ end
74
+
75
+ def each_pair(values, originals)
76
+ return unless values.is_a?(Array) && originals.is_a?(Array)
77
+
78
+ values.each_with_index { |value, index| yield value, originals[index] }
79
+ end
80
+
81
+ def copy(value)
82
+ Marshal.load(Marshal.dump(value))
83
+ end
84
+
85
+ private_class_method :restore_task, :restore_message, :each_pair, :copy
86
+ end
87
+ end
88
+ end
89
+ end
@@ -34,8 +34,9 @@ module A2A
34
34
 
35
35
  def send_message(params)
36
36
  @dispatcher.validate!
37
- history_length = history_length(params)
38
- message, context_id = normalize_message(params)
37
+ history_length = history_length(params.fetch("configuration", {}))
38
+ message, context_id, task_id = normalize_message(params)
39
+ return resume_message(task_id, message, context_id, history_length) if task_id
39
40
 
40
41
  # Direct Message is an explicit host-side choice, never inferred
41
42
  # from an untrusted client flag or forced by the protocol adapter.
@@ -43,11 +44,27 @@ module A2A
43
44
  return send_direct_message(message, context_id)
44
45
  end
45
46
 
46
- task = @lifecycle.create(message: message, context_id: context_id)
47
+ preflight = nil
48
+ routing_error = nil
49
+ task = @lifecycle.create(message: message, context_id: context_id) do |draft|
50
+ next unless message.fetch(:parts).any? { |part| part.key?(:data) }
51
+
52
+ # The router gets the final task context, but unsupported Data
53
+ # must not create a Task or consume the owner's storage quota.
54
+ begin
55
+ preflight = @dispatcher.plan(message: message, context: execution_context(draft))
56
+ rescue UnsupportedSkillInputError => error
57
+ raise ContentTypeNotSupportedError, error.message
58
+ rescue StandardError => error
59
+ routing_error = error
60
+ end
61
+ end
47
62
  context = execution_context(task)
48
63
 
49
64
  plan = begin
50
- @dispatcher.plan(message: message, context: context)
65
+ raise routing_error if routing_error
66
+
67
+ preflight || @dispatcher.plan(message: message, context: context)
51
68
  rescue RejectedTask => error
52
69
  task = @lifecycle.reject(task.fetch(:id), error)
53
70
  nil
@@ -56,29 +73,59 @@ module A2A
56
73
  nil
57
74
  end
58
75
 
59
- if plan&.async?
60
- task = enqueue_async_task(task, plan)
61
- elsif plan
62
- @lifecycle.start(task.fetch(:id))
63
- task = begin
64
- result = @dispatcher.execute(plan: plan, message: message, context: context)
65
- @lifecycle.complete(task.fetch(:id), result)
66
- rescue RejectedTask => error
67
- @lifecycle.reject(task.fetch(:id), error)
76
+ if plan
77
+ begin
78
+ task = @lifecycle.configure_execution(task.fetch(:id), plan: plan,
79
+ message_id: message.fetch(:message_id))
68
80
  rescue StandardError => error
81
+ # A configuration/migration failure must not leave an initial
82
+ # submitted Task that nobody can execute. No turn exists yet.
69
83
  @lifecycle.fail(task.fetch(:id), error)
84
+ raise
70
85
  end
86
+ task = execute_task(task, plan, message)
71
87
  end
72
88
 
73
89
  { "task" => @task_mapper.dump(task, history_length: history_length, include_artifacts: true) }
74
90
  end
75
91
 
92
+ def resume_message(task_id, message, context_id, history_length)
93
+ accepted = @lifecycle.resume(task_id, message: message, context_id: context_id)
94
+ task = accepted.fetch(:task)
95
+ if accepted.fetch(:accepted)
96
+ execution = task.fetch(:execution)
97
+ plan = ExecutionPlan.new(agent_class_name: execution[:agent_class_name],
98
+ skill_id: execution.fetch(:skill_id), execution_mode: execution.fetch(:execution_mode).to_sym)
99
+ task = execute_task(task, plan, message)
100
+ end
101
+ { "task" => @task_mapper.dump(task, history_length: history_length, include_artifacts: true) }
102
+ end
103
+
104
+ def execute_task(task, plan, message)
105
+ return enqueue_async_task(task, plan) if plan.async?
106
+
107
+ task_id = task.fetch(:id)
108
+ turn_id = task.dig(:execution, :turn_id)
109
+ claimed = @lifecycle.claim_execution(task_id, turn_id: turn_id)
110
+ return @lifecycle.find(task_id) unless claimed
111
+
112
+ begin
113
+ result = @dispatcher.execute(plan: plan, message: message, context: execution_context(claimed))
114
+ @lifecycle.complete(task_id, result, turn_id: turn_id)
115
+ rescue RejectedTask => error
116
+ @lifecycle.reject(task_id, error, turn_id: turn_id)
117
+ rescue StandardError => error
118
+ @lifecycle.fail(task_id, error, turn_id: turn_id)
119
+ end
120
+ end
121
+
76
122
  def enqueue_async_task(task, plan)
77
123
  arguments = TaskExecutionArguments.new(
78
124
  task_id: task.fetch(:id),
79
125
  principal_id: @lifecycle.principal_id,
80
126
  agent_class_name: plan.agent_class_name,
81
- skill_id: plan.skill_id
127
+ skill_id: plan.skill_id,
128
+ turn_id: task.dig(:execution, :turn_id)
82
129
  )
83
130
  job = @task_job.perform_later(**arguments.to_h)
84
131
  enqueue_error = job.respond_to?(:enqueue_error) ? job.enqueue_error : nil
@@ -91,10 +138,11 @@ module A2A
91
138
 
92
139
  @lifecycle.fail(
93
140
  task.fetch(:id),
94
- enqueue_error || ConfigurationError.new("Task execution job was not enqueued")
141
+ enqueue_error || ConfigurationError.new("Task execution job was not enqueued"),
142
+ turn_id: task.dig(:execution, :turn_id)
95
143
  )
96
144
  rescue StandardError => error
97
- @lifecycle.fail(task.fetch(:id), error)
145
+ @lifecycle.fail(task.fetch(:id), error, turn_id: task.dig(:execution, :turn_id))
98
146
  end
99
147
 
100
148
  def execution_context(task)
@@ -102,7 +150,9 @@ module A2A
102
150
  task_id: task.fetch(:id),
103
151
  context_id: task.fetch(:context_id),
104
152
  principal_id: @lifecycle.principal_id,
105
- idempotency_key: task.fetch(:id)
153
+ idempotency_key: task.fetch(:id),
154
+ execution_turn_id: task.dig(:execution, :turn_id),
155
+ history: copy(task.fetch(:history, []))
106
156
  }
107
157
  end
108
158
 
@@ -111,7 +161,7 @@ module A2A
111
161
  rescue StandardError
112
162
  # The selector is host application code and may raise with secrets.
113
163
  # No Task exists yet to record the failure as a Task status.
114
- raise A2A::InvalidAgentResponseError.new
164
+ raise InvalidAgentResponseError
115
165
  end
116
166
 
117
167
  def send_direct_message(message, context_id)
@@ -121,10 +171,12 @@ module A2A
121
171
  context: { task_id: nil, context_id: context_id }
122
172
  )
123
173
  { "message" => @task_mapper.dump_direct_message(result, context_id: context_id) }
174
+ rescue UnsupportedSkillInputError => error
175
+ raise ContentTypeNotSupportedError, error.message
124
176
  rescue StandardError
125
177
  # No Task exists to record a FAILED status. Never send application
126
178
  # exception details or unsupported result values to A2A callers.
127
- raise A2A::InvalidAgentResponseError.new
179
+ raise InvalidAgentResponseError
128
180
  end
129
181
 
130
182
  def get_task(params)
@@ -194,12 +246,11 @@ module A2A
194
246
  raise InvalidRequestError, "message metadata must be an object"
195
247
  end
196
248
 
197
- if task_id.is_a?(String) && !task_id.empty?
198
- @lifecycle.find(task_id)
199
- raise TaskContinuationNotSupportedError, "Task continuation is not supported in v0.1"
200
- end
201
249
 
202
- normalized_parts = parts.map { |part| normalize_text_part(part) }
250
+ normalized_parts = parts.map { |part| normalize_part(part) }
251
+ if normalized_parts.any? { |part| part.key?(:data) } && normalized_parts.any? { |part| part.key?(:text) }
252
+ raise ContentTypeNotSupportedError, "Text and JSON Data Parts cannot be mixed in one Message"
253
+ end
203
254
  message = {
204
255
  message_id: message_id,
205
256
  role: :user,
@@ -207,30 +258,58 @@ module A2A
207
258
  metadata: copy(metadata || {})
208
259
  }
209
260
 
210
- [message, context_id]
261
+ [message, context_id, task_id.to_s.empty? ? nil : task_id]
211
262
  end
212
263
 
213
- def normalize_text_part(part)
214
- unless part.is_a?(Hash) && part["text"].is_a?(String) && (part.keys & %w[data raw url]).empty?
215
- raise ContentTypeNotSupportedError, "Only text Parts are supported in v0.1"
264
+ def normalize_part(part)
265
+ types = part.is_a?(Hash) ? part.keys & %w[text data raw url] : []
266
+ if types.size > 1
267
+ raise InvalidRequestError, "Each Part must specify exactly one content kind"
216
268
  end
217
- media_type = part["mediaType"]
218
- unless media_type.nil? || media_type.is_a?(String)
219
- raise InvalidRequestError, "mediaType must be a String"
269
+
270
+ normalized = case types.first
271
+ when "data"
272
+ normalize_data_part(part)
273
+ when "text"
274
+ normalize_text_part(part)
275
+ else
276
+ raise ContentTypeNotSupportedError, "Only text and JSON Data Parts are supported"
220
277
  end
278
+
221
279
  metadata = part["metadata"]
222
280
  unless metadata.nil? || metadata.is_a?(Hash)
223
281
  raise InvalidRequestError, "part metadata must be an object"
224
282
  end
225
-
226
- normalized = {
227
- text: part["text"],
228
- media_type: part["mediaType"].to_s.empty? ? "text/plain" : part["mediaType"]
229
- }
230
283
  normalized[:metadata] = copy(metadata) if metadata
231
284
  normalized
232
285
  end
233
286
 
287
+ def normalize_data_part(part)
288
+ data = part["data"]
289
+ unless data.is_a?(Hash)
290
+ raise InvalidRequestError, "Data Part input must be a JSON object"
291
+ end
292
+
293
+ media_type = part.fetch("mediaType", Skill::DATA_INPUT_MODE)
294
+ unless media_type == Skill::DATA_INPUT_MODE
295
+ raise ContentTypeNotSupportedError, "Data Part mediaType must be application/json when specified"
296
+ end
297
+
298
+ { data: copy(data), media_type: media_type }
299
+ end
300
+
301
+ def normalize_text_part(part)
302
+ unless part["text"].is_a?(String)
303
+ raise ContentTypeNotSupportedError, "Text Part content must be a String"
304
+ end
305
+
306
+ media_type = part["mediaType"]
307
+ unless media_type.nil? || media_type.is_a?(String)
308
+ raise InvalidRequestError, "mediaType must be a String"
309
+ end
310
+ { text: part["text"], media_type: media_type.to_s.empty? ? "text/plain" : media_type }
311
+ end
312
+
234
313
  def validate_list_filters!(params)
235
314
  if params.key?("contextId") && !params["contextId"].nil? && !params["contextId"].is_a?(String)
236
315
  raise InvalidRequestError, "contextId must be a String"
@@ -9,6 +9,7 @@ module A2A
9
9
  STATE_TO_WIRE = {
10
10
  submitted: "TASK_STATE_SUBMITTED",
11
11
  working: "TASK_STATE_WORKING",
12
+ input_required: "TASK_STATE_INPUT_REQUIRED",
12
13
  completed: "TASK_STATE_COMPLETED",
13
14
  failed: "TASK_STATE_FAILED",
14
15
  rejected: "TASK_STATE_REJECTED",
@@ -25,7 +26,13 @@ module A2A
25
26
 
26
27
  if task.key?(:history)
27
28
  history = project_history(task[:history], history_length)
28
- result["history"] = history.map { |message| dump_message(message) }
29
+ result["history"] = history.map do |message|
30
+ value = dump_message(message)
31
+ if message[:role].to_s == "agent"
32
+ value.merge!("taskId" => task.fetch(:id), "contextId" => task.fetch(:context_id))
33
+ end
34
+ value
35
+ end
29
36
  end
30
37
 
31
38
  if include_artifacts && task.key?(:artifacts)
@@ -70,11 +77,15 @@ module A2A
70
77
  }
71
78
 
72
79
  if status[:message]
73
- result["message"] = {
80
+ result["message"] = if status[:message].is_a?(Hash)
81
+ dump_message(status[:message]).merge("taskId" => task.fetch(:id), "contextId" => task.fetch(:context_id))
82
+ else
83
+ {
74
84
  "messageId" => "status-#{task.fetch(:id)}-#{status.fetch(:state)}",
75
85
  "role" => "ROLE_AGENT",
76
86
  "parts" => [{ "text" => status[:message].to_s }]
77
- }
87
+ }
88
+ end
78
89
  end
79
90
 
80
91
  result.compact
@@ -83,7 +94,7 @@ module A2A
83
94
  def dump_message(message)
84
95
  result = {
85
96
  "messageId" => message.fetch(:message_id),
86
- "role" => message.fetch(:role) == :agent ? "ROLE_AGENT" : "ROLE_USER",
97
+ "role" => message.fetch(:role).to_s == "agent" ? "ROLE_AGENT" : "ROLE_USER",
87
98
  "parts" => message.fetch(:parts).map { |part| dump_part(part) }
88
99
  }
89
100
  result["metadata"] = copy(message[:metadata]) if message.key?(:metadata)
@@ -104,7 +115,7 @@ module A2A
104
115
  result["raw"] = part[:raw] if part.key?(:raw)
105
116
  result["url"] = part[:url] if part.key?(:url)
106
117
  result["filename"] = part[:filename] if part.key?(:filename)
107
- if part.key?(:raw) || part.key?(:url)
118
+ if part.key?(:raw) || part.key?(:url) || part.key?(:data)
108
119
  result["mediaType"] = part[:media_type] if part.key?(:media_type)
109
120
  end
110
121
  result["metadata"] = copy(part[:metadata]) if part.key?(:metadata)
@@ -3,6 +3,8 @@
3
3
  module A2A
4
4
  module Rails
5
5
  class Skill
6
+ DATA_INPUT_MODE = "application/json"
7
+
6
8
  attr_reader :id, :name, :description, :tags, :handler, :examples, :input_modes, :output_modes, :execution_mode
7
9
 
8
10
  def initialize(id:, description:, tags:, handler:, name: nil, examples: nil, input_modes: nil, output_modes: nil, execution_mode: nil)