exa-ai 0.12.2 → 0.14.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 (159) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +120 -83
  3. data/exe/exa-ai +45 -152
  4. data/exe/exa-ai-agent-run-create +55 -20
  5. data/exe/exa-ai-agent-run-delete +1 -8
  6. data/exe/exa-ai-agent-run-events +21 -1
  7. data/exe/exa-ai-agent-run-list +1 -1
  8. data/exe/{exa-ai-research-list → exa-ai-agent-run-stop} +31 -32
  9. data/exe/exa-ai-answer +25 -0
  10. data/exe/exa-ai-context +6 -2
  11. data/exe/exa-ai-find-similar +26 -68
  12. data/exe/exa-ai-get-contents +138 -42
  13. data/exe/exa-ai-search +27 -104
  14. data/exe/exa-ai-search-monitor-batch +93 -0
  15. data/exe/exa-ai-search-monitor-create +104 -0
  16. data/exe/exa-ai-search-monitor-delete +69 -0
  17. data/exe/exa-ai-search-monitor-get +69 -0
  18. data/exe/exa-ai-search-monitor-list +73 -0
  19. data/exe/exa-ai-search-monitor-runs-get +68 -0
  20. data/exe/exa-ai-search-monitor-runs-list +75 -0
  21. data/exe/exa-ai-search-monitor-trigger +69 -0
  22. data/exe/exa-ai-search-monitor-update +102 -0
  23. data/lib/exa/cli/base.rb +57 -0
  24. data/lib/exa/cli/contents_flags.rb +199 -0
  25. data/lib/exa/cli/formatters/agent_run_formatter.rb +79 -3
  26. data/lib/exa/cli/formatters/search_formatter.rb +18 -2
  27. data/lib/exa/cli/formatters/search_monitor_formatter.rb +98 -0
  28. data/lib/exa/cli/search_parser.rb +46 -87
  29. data/lib/exa/client.rb +183 -333
  30. data/lib/exa/middleware/raise_error.rb +14 -0
  31. data/lib/exa/resources/agent_run.rb +5 -3
  32. data/lib/exa/resources/agent_run_deletion.rb +17 -0
  33. data/lib/exa/resources/answer.rb +3 -3
  34. data/lib/exa/resources/contents_result.rb +5 -1
  35. data/lib/exa/resources/find_similar_result.rb +5 -1
  36. data/lib/exa/resources/search_monitor.rb +42 -0
  37. data/lib/exa/resources/search_monitor_batch_result.rb +11 -0
  38. data/lib/exa/resources/{research_list.rb → search_monitor_list.rb} +3 -2
  39. data/lib/exa/resources/search_monitor_run.rb +46 -0
  40. data/lib/exa/resources/search_monitor_trigger_result.rb +11 -0
  41. data/lib/exa/resources/search_result.rb +11 -1
  42. data/lib/exa/services/agent_run_cancel.rb +1 -12
  43. data/lib/exa/services/agent_run_create.rb +1 -12
  44. data/lib/exa/services/agent_run_delete.rb +6 -14
  45. data/lib/exa/services/agent_run_events.rb +33 -4
  46. data/lib/exa/services/agent_run_get.rb +1 -12
  47. data/lib/exa/services/agent_run_list.rb +1 -12
  48. data/lib/exa/services/agent_run_stop.rb +21 -0
  49. data/lib/exa/services/agent_run_stream.rb +56 -52
  50. data/lib/exa/services/answer.rb +5 -2
  51. data/lib/exa/services/answer_stream.rb +57 -46
  52. data/lib/exa/services/context.rb +3 -1
  53. data/lib/exa/services/find_similar.rb +9 -2
  54. data/lib/exa/services/get_contents.rb +14 -15
  55. data/lib/exa/services/parameter_converter.rb +128 -111
  56. data/lib/exa/services/search.rb +58 -19
  57. data/lib/exa/services/search_monitors/batch.rb +36 -0
  58. data/lib/exa/services/search_monitors/create.rb +37 -0
  59. data/lib/exa/services/search_monitors/delete.rb +22 -0
  60. data/lib/exa/services/search_monitors/get.rb +22 -0
  61. data/lib/exa/services/search_monitors/list.rb +29 -0
  62. data/lib/exa/services/search_monitors/runs_get.rb +23 -0
  63. data/lib/exa/services/search_monitors/runs_list.rb +29 -0
  64. data/lib/exa/services/search_monitors/trigger.rb +22 -0
  65. data/lib/exa/services/search_monitors/update.rb +42 -0
  66. data/lib/exa/services/search_stream.rb +38 -0
  67. data/lib/exa/version.rb +1 -1
  68. data/lib/exa.rb +18 -56
  69. metadata +31 -94
  70. data/exe/exa-ai-enrichment-cancel +0 -108
  71. data/exe/exa-ai-enrichment-create +0 -226
  72. data/exe/exa-ai-enrichment-delete +0 -122
  73. data/exe/exa-ai-enrichment-get +0 -104
  74. data/exe/exa-ai-enrichment-list +0 -99
  75. data/exe/exa-ai-enrichment-update +0 -171
  76. data/exe/exa-ai-import-create +0 -253
  77. data/exe/exa-ai-import-delete +0 -92
  78. data/exe/exa-ai-import-get +0 -92
  79. data/exe/exa-ai-import-list +0 -72
  80. data/exe/exa-ai-import-update +0 -164
  81. data/exe/exa-ai-monitor-create +0 -223
  82. data/exe/exa-ai-monitor-delete +0 -101
  83. data/exe/exa-ai-monitor-get +0 -92
  84. data/exe/exa-ai-monitor-list +0 -90
  85. data/exe/exa-ai-monitor-runs-get +0 -103
  86. data/exe/exa-ai-monitor-runs-list +0 -110
  87. data/exe/exa-ai-monitor-update +0 -207
  88. data/exe/exa-ai-research-get +0 -109
  89. data/exe/exa-ai-research-start +0 -174
  90. data/exe/exa-ai-webset-cancel +0 -97
  91. data/exe/exa-ai-webset-create +0 -254
  92. data/exe/exa-ai-webset-delete +0 -111
  93. data/exe/exa-ai-webset-get +0 -93
  94. data/exe/exa-ai-webset-item-delete +0 -111
  95. data/exe/exa-ai-webset-item-get +0 -105
  96. data/exe/exa-ai-webset-item-list +0 -108
  97. data/exe/exa-ai-webset-list +0 -91
  98. data/exe/exa-ai-webset-search-cancel +0 -104
  99. data/exe/exa-ai-webset-search-create +0 -247
  100. data/exe/exa-ai-webset-search-get +0 -105
  101. data/exe/exa-ai-webset-update +0 -143
  102. data/lib/exa/cli/formatters/enrichment_formatter.rb +0 -125
  103. data/lib/exa/cli/formatters/import_formatter.rb +0 -153
  104. data/lib/exa/cli/formatters/monitor_formatter.rb +0 -144
  105. data/lib/exa/cli/formatters/monitor_run_formatter.rb +0 -126
  106. data/lib/exa/cli/formatters/research_formatter.rb +0 -124
  107. data/lib/exa/cli/formatters/webset_formatter.rb +0 -134
  108. data/lib/exa/cli/formatters/webset_item_formatter.rb +0 -131
  109. data/lib/exa/cli/formatters/webset_search_formatter.rb +0 -57
  110. data/lib/exa/constants/websets.rb +0 -19
  111. data/lib/exa/resources/import.rb +0 -86
  112. data/lib/exa/resources/import_collection.rb +0 -33
  113. data/lib/exa/resources/monitor.rb +0 -48
  114. data/lib/exa/resources/monitor_collection.rb +0 -30
  115. data/lib/exa/resources/monitor_run.rb +0 -52
  116. data/lib/exa/resources/monitor_run_collection.rb +0 -30
  117. data/lib/exa/resources/research_task.rb +0 -39
  118. data/lib/exa/resources/webset.rb +0 -74
  119. data/lib/exa/resources/webset_collection.rb +0 -33
  120. data/lib/exa/resources/webset_enrichment.rb +0 -71
  121. data/lib/exa/resources/webset_enrichment_collection.rb +0 -28
  122. data/lib/exa/resources/webset_item_collection.rb +0 -33
  123. data/lib/exa/resources/webset_search.rb +0 -112
  124. data/lib/exa/services/research_get.rb +0 -30
  125. data/lib/exa/services/research_list.rb +0 -37
  126. data/lib/exa/services/research_start.rb +0 -26
  127. data/lib/exa/services/websets/cancel.rb +0 -36
  128. data/lib/exa/services/websets/cancel_enrichment.rb +0 -35
  129. data/lib/exa/services/websets/cancel_search.rb +0 -44
  130. data/lib/exa/services/websets/create.rb +0 -45
  131. data/lib/exa/services/websets/create_enrichment.rb +0 -35
  132. data/lib/exa/services/websets/create_search.rb +0 -48
  133. data/lib/exa/services/websets/create_search_validator.rb +0 -128
  134. data/lib/exa/services/websets/create_validator.rb +0 -213
  135. data/lib/exa/services/websets/delete.rb +0 -36
  136. data/lib/exa/services/websets/delete_enrichment.rb +0 -35
  137. data/lib/exa/services/websets/delete_item.rb +0 -20
  138. data/lib/exa/services/websets/get_item.rb +0 -20
  139. data/lib/exa/services/websets/get_search.rb +0 -43
  140. data/lib/exa/services/websets/import_create.rb +0 -40
  141. data/lib/exa/services/websets/import_delete.rb +0 -37
  142. data/lib/exa/services/websets/import_get.rb +0 -37
  143. data/lib/exa/services/websets/import_list.rb +0 -25
  144. data/lib/exa/services/websets/import_update.rb +0 -38
  145. data/lib/exa/services/websets/import_upload.rb +0 -58
  146. data/lib/exa/services/websets/list.rb +0 -25
  147. data/lib/exa/services/websets/list_items.rb +0 -26
  148. data/lib/exa/services/websets/monitors/create.rb +0 -42
  149. data/lib/exa/services/websets/monitors/delete.rb +0 -32
  150. data/lib/exa/services/websets/monitors/get.rb +0 -33
  151. data/lib/exa/services/websets/monitors/list.rb +0 -27
  152. data/lib/exa/services/websets/monitors/runs/get.rb +0 -37
  153. data/lib/exa/services/websets/monitors/runs/list.rb +0 -30
  154. data/lib/exa/services/websets/monitors/update.rb +0 -33
  155. data/lib/exa/services/websets/retrieve.rb +0 -47
  156. data/lib/exa/services/websets/retrieve_enrichment.rb +0 -35
  157. data/lib/exa/services/websets/update.rb +0 -37
  158. data/lib/exa/services/websets/update_enrichment.rb +0 -36
  159. data/lib/exa/services/websets_parameter_converter.rb +0 -45
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "faraday"
4
+ require "json"
4
5
 
5
6
  module Exa
6
7
  module Middleware
@@ -29,6 +30,10 @@ module Exa
29
30
  handle_error(env, Exa::ServiceUnavailable)
30
31
  when 504
31
32
  handle_error(env, Exa::GatewayTimeout)
33
+ when 400..499
34
+ handle_error(env, Exa::ClientError)
35
+ when 500..599
36
+ handle_error(env, Exa::ServerError)
32
37
  end
33
38
  end
34
39
 
@@ -41,6 +46,7 @@ module Exa
41
46
 
42
47
  def extract_error_message(env)
43
48
  body = env[:body]
49
+ body = parse_streamed_error_body(env) if body.nil? || body == ""
44
50
 
45
51
  if body.is_a?(Hash)
46
52
  # Prioritize "message" field for detailed error descriptions
@@ -54,6 +60,14 @@ module Exa
54
60
 
55
61
  "HTTP #{env[:status]}"
56
62
  end
63
+
64
+ # Streaming requests hand the body to on_data, so the adapter leaves
65
+ # env[:body] empty. Stream services keep error chunks in env[:error_body].
66
+ def parse_streamed_error_body(env)
67
+ JSON.parse(env[:error_body].to_s)
68
+ rescue JSON::ParserError
69
+ nil
70
+ end
57
71
  end
58
72
  end
59
73
  end
@@ -2,9 +2,9 @@ module Exa
2
2
  module Resources
3
3
  class AgentRun < Struct.new(
4
4
  :id, :object, :status, :stop_reason, :created_at, :completed_at,
5
- :request, :output, :usage, :cost_dollars, keyword_init: true
5
+ :request, :output, :usage, :cost_dollars, :error, keyword_init: true
6
6
  )
7
- def initialize(id:, object:, status:, stop_reason: nil, created_at: nil, completed_at: nil, request: nil, output: nil, usage: nil, cost_dollars: nil)
7
+ def initialize(id:, object:, status:, stop_reason: nil, created_at: nil, completed_at: nil, request: nil, output: nil, usage: nil, cost_dollars: nil, error: nil)
8
8
  super
9
9
  freeze
10
10
  end
@@ -22,7 +22,8 @@ module Exa
22
22
  request: body["request"],
23
23
  output: body["output"],
24
24
  usage: body["usage"],
25
- cost_dollars: body["costDollars"]
25
+ cost_dollars: body["costDollars"],
26
+ error: body["error"]
26
27
  )
27
28
  end
28
29
 
@@ -47,6 +48,7 @@ module Exa
47
48
  result[:output] = output if output
48
49
  result[:usage] = usage if usage
49
50
  result[:cost_dollars] = cost_dollars if cost_dollars
51
+ result[:error] = error if error
50
52
  result
51
53
  end
52
54
  end
@@ -0,0 +1,17 @@
1
+ module Exa
2
+ module Resources
3
+ # Result of DELETE /agent/runs/{id}: {id, object: "agent_run.deleted", deleted: true}.
4
+ class AgentRunDeletion < Struct.new(:id, :object, :deleted, keyword_init: true)
5
+ def initialize(id:, object:, deleted:)
6
+ super
7
+ freeze
8
+ end
9
+
10
+ def deleted? = deleted == true
11
+
12
+ def to_h
13
+ { id: id, object: object, deleted: deleted }
14
+ end
15
+ end
16
+ end
17
+ end
@@ -6,14 +6,14 @@ module Exa
6
6
  #
7
7
  # This class wraps the JSON response from the /answer endpoint and provides
8
8
  # a Ruby-friendly interface for accessing the generated answer and citations.
9
- class Answer < Struct.new(:answer, :citations, :cost_dollars, keyword_init: true)
10
- def initialize(answer:, citations: [], cost_dollars: nil)
9
+ class Answer < Struct.new(:answer, :citations, :cost_dollars, :request_id, keyword_init: true)
10
+ def initialize(answer:, citations: [], cost_dollars: nil, request_id: nil)
11
11
  super
12
12
  freeze
13
13
  end
14
14
 
15
15
  def to_h
16
- { answer: answer, citations: citations, cost_dollars: cost_dollars }
16
+ { answer: answer, citations: citations, cost_dollars: cost_dollars, request_id: request_id }
17
17
  end
18
18
  end
19
19
  end
@@ -4,15 +4,19 @@ module Exa
4
4
  #
5
5
  # This class wraps the JSON response from the /contents endpoint and provides
6
6
  # a Ruby-friendly interface for accessing content results and metadata.
7
+ #
8
+ # The context field is deprecated in the API. Use the highlights or text
9
+ # of each result instead.
7
10
  class ContentsResult < Struct.new(
8
11
  :results,
9
12
  :request_id,
10
13
  :context,
11
14
  :statuses,
12
15
  :cost_dollars,
16
+ :search_time,
13
17
  keyword_init: true
14
18
  )
15
- def initialize(results:, request_id: nil, context: nil, statuses: nil, cost_dollars: nil)
19
+ def initialize(results:, request_id: nil, context: nil, statuses: nil, cost_dollars: nil, search_time: nil)
16
20
  super
17
21
  freeze
18
22
  end
@@ -4,14 +4,18 @@ module Exa
4
4
  #
5
5
  # This class wraps the JSON response from the /findSimilar endpoint and provides
6
6
  # a Ruby-friendly interface for accessing similar results and metadata.
7
+ #
8
+ # The context field is deprecated in the API. Use the highlights or text
9
+ # of each result instead.
7
10
  class FindSimilarResult < Struct.new(
8
11
  :results,
9
12
  :request_id,
10
13
  :context,
11
14
  :cost_dollars,
15
+ :search_time,
12
16
  keyword_init: true
13
17
  )
14
- def initialize(results:, request_id: nil, context: nil, cost_dollars: nil)
18
+ def initialize(results:, request_id: nil, context: nil, cost_dollars: nil, search_time: nil)
15
19
  super
16
20
  freeze
17
21
  end
@@ -0,0 +1,42 @@
1
+ module Exa
2
+ module Resources
3
+ # A scheduled Exa search that sends new results to a webhook (/monitors).
4
+ class SearchMonitor < Struct.new(
5
+ :id, :name, :status, :search, :trigger, :webhook, :output_schema,
6
+ :metadata, :next_run_at, :created_at, :updated_at, :webhook_secret,
7
+ keyword_init: true
8
+ )
9
+ def initialize(id:, name: nil, status: nil, search: nil, trigger: nil, webhook: nil, output_schema: nil,
10
+ metadata: nil, next_run_at: nil, created_at: nil, updated_at: nil, webhook_secret: nil)
11
+ super
12
+ freeze
13
+ end
14
+
15
+ # Build from a raw API response body (camelCase keys).
16
+ def self.from_response(body)
17
+ new(
18
+ id: body["id"],
19
+ name: body["name"],
20
+ status: body["status"],
21
+ search: body["search"],
22
+ trigger: body["trigger"],
23
+ webhook: body["webhook"],
24
+ output_schema: body["outputSchema"],
25
+ metadata: body["metadata"],
26
+ next_run_at: body["nextRunAt"],
27
+ created_at: body["createdAt"],
28
+ updated_at: body["updatedAt"],
29
+ webhook_secret: body["webhookSecret"]
30
+ )
31
+ end
32
+
33
+ def active? = status == "active"
34
+ def paused? = status == "paused"
35
+ def disabled? = status == "disabled"
36
+
37
+ def to_h
38
+ super.compact
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,11 @@
1
+ module Exa
2
+ module Resources
3
+ # Result of POST /monitors/batch. Repeat the call until has_more is false.
4
+ class SearchMonitorBatchResult < Struct.new(:action, :affected, :ids, :dry_run, :has_more, keyword_init: true)
5
+ def initialize(action:, affected:, ids:, dry_run:, has_more:)
6
+ super
7
+ freeze
8
+ end
9
+ end
10
+ end
11
+ end
@@ -1,6 +1,7 @@
1
1
  module Exa
2
2
  module Resources
3
- class ResearchList < Struct.new(:data, :has_more, :next_cursor, keyword_init: true)
3
+ # One page of search monitors (GET /monitors) or of their runs (GET /monitors/{id}/runs).
4
+ class SearchMonitorList < Struct.new(:data, :has_more, :next_cursor, keyword_init: true)
4
5
  def initialize(data:, has_more:, next_cursor: nil)
5
6
  super
6
7
  freeze
@@ -8,7 +9,7 @@ module Exa
8
9
 
9
10
  def to_h
10
11
  {
11
- data: data.map { |item| item.respond_to?(:to_h) ? item.to_h : item },
12
+ data: data.map(&:to_h),
12
13
  has_more: has_more,
13
14
  next_cursor: next_cursor
14
15
  }
@@ -0,0 +1,46 @@
1
+ module Exa
2
+ module Resources
3
+ # One run of a search monitor (/monitors/{id}/runs).
4
+ class SearchMonitorRun < Struct.new(
5
+ :id, :monitor_id, :status, :output, :fail_reason, :started_at, :completed_at,
6
+ :failed_at, :cancelled_at, :duration_ms, :created_at, :updated_at,
7
+ keyword_init: true
8
+ )
9
+ def initialize(id:, monitor_id: nil, status: nil, output: nil, fail_reason: nil, started_at: nil, completed_at: nil,
10
+ failed_at: nil, cancelled_at: nil, duration_ms: nil, created_at: nil, updated_at: nil)
11
+ super
12
+ freeze
13
+ end
14
+
15
+ # Build from a raw API response body (camelCase keys).
16
+ def self.from_response(body)
17
+ new(
18
+ id: body["id"],
19
+ monitor_id: body["monitorId"],
20
+ status: body["status"],
21
+ output: body["output"],
22
+ fail_reason: body["failReason"],
23
+ started_at: body["startedAt"],
24
+ completed_at: body["completedAt"],
25
+ failed_at: body["failedAt"],
26
+ cancelled_at: body["cancelledAt"],
27
+ duration_ms: body["durationMs"],
28
+ created_at: body["createdAt"],
29
+ updated_at: body["updatedAt"]
30
+ )
31
+ end
32
+
33
+ def pending? = status == "pending"
34
+ def running? = status == "running"
35
+ def completed? = status == "completed"
36
+ def failed? = status == "failed"
37
+ def cancelled? = status == "cancelled"
38
+
39
+ def finished? = completed? || failed? || cancelled?
40
+
41
+ def to_h
42
+ super.compact
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,11 @@
1
+ module Exa
2
+ module Resources
3
+ # Result of POST /monitors/{id}/trigger.
4
+ class SearchMonitorTriggerResult < Struct.new(:triggered, keyword_init: true)
5
+ def initialize(triggered:)
6
+ super
7
+ freeze
8
+ end
9
+ end
10
+ end
11
+ end
@@ -4,6 +4,12 @@ module Exa
4
4
  #
5
5
  # This class wraps the JSON response from the /search endpoint and provides
6
6
  # a Ruby-friendly interface for accessing search results and metadata.
7
+ #
8
+ # Deprecated fields, kept for compatibility:
9
+ # - resolved_search_type: the API marks resolvedSearchType deprecated. It
10
+ # may be an empty string; do not branch on it.
11
+ # - search_type: searchType is not in the API spec.
12
+ # - context: deprecated. Use the highlights or text of each result.
7
13
  class SearchResult < Struct.new(
8
14
  :results,
9
15
  :request_id,
@@ -12,9 +18,13 @@ module Exa
12
18
  :context,
13
19
  :cost_dollars,
14
20
  :output,
21
+ :warnings,
22
+ :notices,
23
+ :search_time,
15
24
  keyword_init: true
16
25
  )
17
- def initialize(results:, request_id: nil, resolved_search_type: nil, search_type: nil, context: nil, cost_dollars: nil, output: nil)
26
+ def initialize(results:, request_id: nil, resolved_search_type: nil, search_type: nil, context: nil, cost_dollars: nil, output: nil,
27
+ warnings: nil, notices: nil, search_time: nil)
18
28
  super
19
29
  freeze
20
30
  end
@@ -14,18 +14,7 @@ module Exa
14
14
  response = @connection.post("/agent/runs/#{@run_id}/cancel", {})
15
15
  body = response.body
16
16
 
17
- Resources::AgentRun.new(
18
- id: body["id"],
19
- object: body["object"],
20
- status: body["status"],
21
- stop_reason: body["stopReason"],
22
- created_at: body["createdAt"],
23
- completed_at: body["completedAt"],
24
- request: body["request"],
25
- output: body["output"],
26
- usage: body["usage"],
27
- cost_dollars: body["costDollars"]
28
- )
17
+ Resources::AgentRun.from_response(body)
29
18
  end
30
19
  end
31
20
  end
@@ -15,18 +15,7 @@ module Exa
15
15
  response = @connection.post("/agent/runs", ParameterConverter.convert(@params))
16
16
  body = response.body
17
17
 
18
- Resources::AgentRun.new(
19
- id: body["id"],
20
- object: body["object"],
21
- status: body["status"],
22
- stop_reason: body["stopReason"],
23
- created_at: body["createdAt"],
24
- completed_at: body["completedAt"],
25
- request: body["request"],
26
- output: body["output"],
27
- usage: body["usage"],
28
- cost_dollars: body["costDollars"]
29
- )
18
+ Resources::AgentRun.from_response(body)
30
19
  end
31
20
  end
32
21
  end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../resources/agent_run"
3
+ require_relative "../resources/agent_run_deletion"
4
4
 
5
5
  module Exa
6
6
  module Services
@@ -11,25 +11,17 @@ module Exa
11
11
  end
12
12
 
13
13
  def call
14
- response = @connection.delete("/agent/runs/#{@run_id}")
15
- body = response.body
14
+ body = @connection.delete("/agent/runs/#{@run_id}").body
16
15
 
17
- # ponytail: 204-vs-200 unconfirmed; nil-guarded. Confirm against live API.
16
+ # A successful DELETE with no body still means the run was deleted.
18
17
  if body.nil? || body.empty?
19
- return Resources::AgentRun.new(id: @run_id, object: "agent_run", status: "deleted")
18
+ return Resources::AgentRunDeletion.new(id: @run_id, object: "agent_run.deleted", deleted: true)
20
19
  end
21
20
 
22
- Resources::AgentRun.new(
21
+ Resources::AgentRunDeletion.new(
23
22
  id: body["id"],
24
23
  object: body["object"],
25
- status: body["status"],
26
- stop_reason: body["stopReason"],
27
- created_at: body["createdAt"],
28
- completed_at: body["completedAt"],
29
- request: body["request"],
30
- output: body["output"],
31
- usage: body["usage"],
32
- cost_dollars: body["costDollars"]
24
+ deleted: body["deleted"]
33
25
  )
34
26
  end
35
27
  end
@@ -1,28 +1,57 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "agent_run_stream"
3
4
  require_relative "../resources/agent_run_event_list"
4
5
 
5
6
  module Exa
6
7
  module Services
7
8
  class AgentRunEvents
8
- def initialize(connection, run_id:, **params)
9
+ def initialize(connection, run_id:, last_event_id: nil, **params)
9
10
  @connection = connection
10
11
  @run_id = run_id
12
+ @last_event_id = last_event_id
11
13
  @params = params
12
14
  end
13
15
 
14
16
  def call
17
+ return replay_events if @last_event_id
18
+
15
19
  response = @connection.get("/agent/runs/#{@run_id}/events", @params)
16
- body = response.body
20
+ event_list_from_json(response.body)
21
+ end
17
22
 
18
- # Confirmed live: GET /agent/runs/{id}/events returns a paginated list
19
- # {object: "list", data: [...], hasMore, nextCursor}.
23
+ private
24
+
25
+ # Confirmed live: GET /agent/runs/{id}/events returns a paginated list
26
+ # {object: "list", data: [...], hasMore, nextCursor}.
27
+ def event_list_from_json(body)
20
28
  Resources::AgentRunEventList.new(
21
29
  data: body["data"] || [],
22
30
  has_more: body["hasMore"],
23
31
  next_cursor: body["nextCursor"]
24
32
  )
25
33
  end
34
+
35
+ # Replays the events after @last_event_id as server-sent events. Reads
36
+ # the whole response, then returns the same list shape as JSON mode,
37
+ # with items {"id", "event", "data"}. SSE replay has no cursor, so
38
+ # has_more is false and next_cursor is nil. If the server ignores the
39
+ # Accept header and answers with JSON, the JSON middleware has already
40
+ # parsed it into a Hash, which is read as in JSON mode.
41
+ def replay_events
42
+ response = @connection.get("/agent/runs/#{@run_id}/events", @params) do |req|
43
+ req.headers["Accept"] = "text/event-stream"
44
+ req.headers["Last-Event-ID"] = @last_event_id.to_s
45
+ end
46
+
47
+ return event_list_from_json(response.body) unless response.body.is_a?(String)
48
+
49
+ frames = response.body.gsub("\r\n", "\n").split("\n\n")
50
+ parsed_frames = frames.filter_map { |frame| AgentRunStream.parse_frame(frame) }
51
+ events = parsed_frames.map { |event_type, data, event_id| { "id" => event_id, "event" => event_type, "data" => data } }
52
+
53
+ Resources::AgentRunEventList.new(data: events, has_more: false, next_cursor: nil)
54
+ end
26
55
  end
27
56
  end
28
57
  end
@@ -15,18 +15,7 @@ module Exa
15
15
  response = @connection.get("/agent/runs/#{@run_id}", @params)
16
16
  body = response.body
17
17
 
18
- Resources::AgentRun.new(
19
- id: body["id"],
20
- object: body["object"],
21
- status: body["status"],
22
- stop_reason: body["stopReason"],
23
- created_at: body["createdAt"],
24
- completed_at: body["completedAt"],
25
- request: body["request"],
26
- output: body["output"],
27
- usage: body["usage"],
28
- cost_dollars: body["costDollars"]
29
- )
18
+ Resources::AgentRun.from_response(body)
30
19
  end
31
20
  end
32
21
  end
@@ -16,18 +16,7 @@ module Exa
16
16
  body = response.body
17
17
 
18
18
  data = body["data"].map do |run_data|
19
- Resources::AgentRun.new(
20
- id: run_data["id"],
21
- object: run_data["object"],
22
- status: run_data["status"],
23
- stop_reason: run_data["stopReason"],
24
- created_at: run_data["createdAt"],
25
- completed_at: run_data["completedAt"],
26
- request: run_data["request"],
27
- output: run_data["output"],
28
- usage: run_data["usage"],
29
- cost_dollars: run_data["costDollars"]
30
- )
19
+ Resources::AgentRun.from_response(run_data)
31
20
  end
32
21
 
33
22
  Resources::AgentRunList.new(
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../resources/agent_run"
4
+
5
+ module Exa
6
+ module Services
7
+ # Ends a run early and keeps the results gathered so far. The spec gives
8
+ # this endpoint no request body, so none is sent.
9
+ class AgentRunStop
10
+ def initialize(connection, run_id:)
11
+ @connection = connection
12
+ @run_id = run_id
13
+ end
14
+
15
+ def call
16
+ response = @connection.post("/agent/runs/#{@run_id}/stop")
17
+ Resources::AgentRun.from_response(response.body)
18
+ end
19
+ end
20
+ end
21
+ end
@@ -2,7 +2,7 @@ require "json"
2
2
  require_relative "parameter_converter"
3
3
  require_relative "../resources/agent_run"
4
4
 
5
- # ponytail: copied AnswerStream's SSE parser rather than extracting a shared module — agent frames add event:/id: lines and the two may diverge. Extract only if a third SSE consumer appears.
5
+ # ponytail: parse_frame now has three callers (this class, AnswerStream and AgentRunEvents) and stays here; no separate SSE module.
6
6
 
7
7
  module Exa
8
8
  module Services
@@ -14,9 +14,47 @@ module Exa
14
14
  @params = params
15
15
  end
16
16
 
17
- # Streams SSE frames to the block as (event_type, data). Returns the final
18
- # AgentRun built from the terminal event's payload (completed/failed/
19
- # cancelled), or nil if the stream ended before a terminal event arrived.
17
+ # Parses one SSE frame (the lines between two blank lines) and returns
18
+ # [event_type, data, event_id], or nil when the frame has no data line or
19
+ # its data is not valid JSON. Reads "id:", "event:" and "data:" with or
20
+ # without the one space after the colon, skips comment lines that start
21
+ # with ":", and joins several data lines with "\n" as the SSE format says.
22
+ # The event name and id are stripped of surrounding whitespace.
23
+ def self.parse_frame(frame)
24
+ event_type = nil
25
+ event_id = nil
26
+ data_lines = []
27
+
28
+ frame.split("\n").each do |line|
29
+ # A stream that ends between "\r" and "\n" leaves a "\r" behind.
30
+ line = line.chomp("\r")
31
+ next if line.start_with?(":")
32
+
33
+ field, value = line.split(":", 2)
34
+ next if value.nil?
35
+
36
+ # The SSE format allows one optional space after the colon.
37
+ value = value.delete_prefix(" ")
38
+ case field
39
+ when "event" then event_type = value.strip
40
+ when "id" then event_id = value.strip
41
+ when "data" then data_lines << value
42
+ end
43
+ end
44
+
45
+ return nil if data_lines.empty?
46
+
47
+ [event_type, JSON.parse(data_lines.join("\n")), event_id]
48
+ rescue JSON::ParserError
49
+ nil
50
+ end
51
+
52
+ # Streams SSE frames to the block as (event_type, data, event_id). Blocks
53
+ # and procs that take only (event_type, data) keep working; a lambda
54
+ # must accept three arguments. Returns the
55
+ # final AgentRun built from the terminal event's payload (completed/
56
+ # failed/cancelled), or nil if the stream ended before a terminal event
57
+ # arrived.
20
58
  def call(&block)
21
59
  raise ArgumentError, "block required for streaming" unless block_given?
22
60
 
@@ -24,28 +62,35 @@ module Exa
24
62
  @final_payload = nil
25
63
 
26
64
  # Capture the terminal payload as it streams, then forward to the caller.
27
- interceptor = proc do |event_type, data|
65
+ interceptor = proc do |event_type, data, event_id|
28
66
  @final_payload = data if TERMINAL_EVENTS.include?(event_type)
29
- block.call(event_type, data)
67
+ block.call(event_type, data, event_id)
30
68
  end
31
69
 
32
70
  body = ParameterConverter.convert(@params)
33
71
 
34
72
  @connection.post("/agent/runs", body) do |req|
35
73
  req.headers["Accept"] = "text/event-stream"
36
- req.options.on_data = proc do |chunk|
37
- @buffer += chunk
74
+ req.options.on_data = proc do |chunk, _size, env|
75
+ next env[:error_body] = "#{env[:error_body]}#{chunk}" if env&.status.to_i >= 400
76
+
77
+ # Normalise CRLF line endings. A "\r" at the end of one chunk joins
78
+ # its "\n" here once the next chunk arrives.
79
+ @buffer = (@buffer + chunk).gsub("\r\n", "\n")
38
80
  process_sse_buffer(&interceptor)
39
81
  end
40
82
  end
41
83
 
42
- process_remaining_buffer(&interceptor) if @buffer.length.positive?
84
+ event = self.class.parse_frame(@buffer)
85
+ interceptor.call(*event) if event
43
86
 
44
87
  @final_payload && Resources::AgentRun.from_response(@final_payload)
45
88
  end
46
89
 
47
90
  private
48
91
 
92
+ # Yields each complete frame in the buffer and keeps the incomplete
93
+ # tail for the next chunk.
49
94
  def process_sse_buffer
50
95
  return if @buffer.empty?
51
96
 
@@ -60,49 +105,8 @@ module Exa
60
105
  end
61
106
 
62
107
  complete_parts.each do |frame|
63
- next if frame.empty?
64
-
65
- event_type = nil
66
- data_json = nil
67
-
68
- frame.split("\n").each do |line|
69
- if line.start_with?("event: ")
70
- event_type = line.sub(/^event: /, "").strip
71
- elsif line.start_with?("data: ")
72
- data_json = line.sub(/^data: /, "").strip
73
- end
74
- end
75
-
76
- next if data_json.nil?
77
-
78
- begin
79
- data = JSON.parse(data_json)
80
- yield(event_type, data)
81
- rescue JSON::ParserError
82
- # Skip lines that aren't valid JSON
83
- end
84
- end
85
- end
86
-
87
- def process_remaining_buffer
88
- event_type = nil
89
- data_json = nil
90
-
91
- @buffer.split("\n").each do |line|
92
- if line.start_with?("event: ")
93
- event_type = line.sub(/^event: /, "").strip
94
- elsif line.start_with?("data: ")
95
- data_json = line.sub(/^data: /, "").strip
96
- end
97
- end
98
-
99
- return if data_json.nil?
100
-
101
- begin
102
- data = JSON.parse(data_json)
103
- yield(event_type, data)
104
- rescue JSON::ParserError
105
- # Skip lines that aren't valid JSON
108
+ event = self.class.parse_frame(frame)
109
+ yield(*event) if event
106
110
  end
107
111
  end
108
112
  end