Class: ActionAgent::Api::AgentsController

Inherits:
BaseController show all
Defined in:
app/controllers/action_agent/api/agents_controller.rb

Constant Summary collapse

LIST_SORTS =

Ranking for the agent cards. Every dimension except "recent" reads the scorecard, which is computed in Ruby over both execution sources, so the ordering is applied there rather than in the SQL scope.

{
  "recent" => "Recently updated",
  "popular" => "Most runs",
  "longest" => "Longest average",
  "cost" => "Highest cost",
  "tokens" => "Most tokens"
}.freeze
DEFAULT_LIST_SORT =
"recent"

Instance Method Summary collapse

Methods inherited from ActionAgent::ApplicationController

allow_unauthenticated_access

Instance Method Details

#analyticsObject

GET /api/agents/:id/analytics



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'app/controllers/action_agent/api/agents_controller.rb', line 202

def analytics
  days = (params[:days] || 30).to_i
  start_date = days.days.ago.beginning_of_day

  runs = @agent.agent_runs.where("created_at >= ?", start_date)

  # Calculate stats
  total_runs = runs.count
  completed_runs = runs.where(status: :complete).count
  failed_runs = runs.where(status: :failed).count
  avg_duration = runs.where.not(duration_ms: nil).average(:duration_ms)&.round || 0
  total_tokens = runs.sum(:total_tokens)
  avg_tokens = total_runs > 0 ? (total_tokens.to_f / total_runs).round : 0

  # Runs by day
  runs_by_day = runs.group("DATE(created_at)")
    .select("DATE(created_at) as date, COUNT(*) as count, SUM(total_tokens) as tokens")
    .order("date")
    .map { |r| { date: r.date.to_s, count: r.count, tokens: r.tokens || 0 } }

  # Status breakdown
  status_breakdown = runs.group(:status).count.transform_keys(&:to_s)

  # Recent errors
  recent_errors = runs.failed_runs.recent.limit(5).map do |run|
    {
      id: run.id,
      error: run.error_message&.truncate(200),
      created_at: run.created_at
    }
  end

  render json: {
    period_days: days,
    summary: {
      total_runs: total_runs,
      completed_runs: completed_runs,
      failed_runs: failed_runs,
      success_rate: total_runs > 0 ? ((completed_runs.to_f / total_runs) * 100).round(1) : 0,
      avg_duration_ms: avg_duration,
      total_tokens: total_tokens,
      avg_tokens_per_run: avg_tokens
    },
    runs_by_day: runs_by_day,
    status_breakdown: status_breakdown,
    recent_errors: recent_errors
  }
end

#createObject

POST /api/agents



70
71
72
73
74
75
76
77
78
# File 'app/controllers/action_agent/api/agents_controller.rb', line 70

def create
  @agent = owner_agents.build(agent_params)

  if @agent.save
    render json: { agent: agent_json(@agent, include_details: true) }, status: :created
  else
    render json: { errors: @agent.errors.full_messages }, status: :unprocessable_entity
  end
end

#destroyObject

DELETE /api/agents/:id



90
91
92
93
# File 'app/controllers/action_agent/api/agents_controller.rb', line 90

def destroy
  @agent.destroy
  render json: { success: true }
end

#duplicateObject

POST /api/agents/:id/duplicate



174
175
176
177
178
179
180
181
182
# File 'app/controllers/action_agent/api/agents_controller.rb', line 174

def duplicate
  new_agent = @agent.dup
  new_agent.name = "#{@agent.name} (Copy)"
  new_agent.slug = nil # Will be auto-generated
  new_agent.status = :draft
  new_agent.save!

  render json: { agent: agent_json(new_agent, include_details: true) }, status: :created
end

#executeObject

POST /api/agents/:id/execute



150
151
152
153
154
155
156
157
158
159
# File 'app/controllers/action_agent/api/agents_controller.rb', line 150

def execute
  run = @agent.execute(
    params[:prompt],
    action: params[:action_name],
    **params.fetch(:params, {}).to_unsafe_h.symbolize_keys
  )
  record_execution_usage

  render json: { run: run.summary }, status: :accepted
end

#exportObject

GET /api/agents/:id/export



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'app/controllers/action_agent/api/agents_controller.rb', line 185

def export
  render json: {
    agent: agent_json(@agent, include_details: true),
    code: @agent.to_agent_class_code,
    manifest: {
      name: @agent.slug,
      version: "1.0.0",
      model: "#{@agent.provider}/#{@agent.model}",
      description: @agent.description,
      instructions: @agent.instructions,
      tools: @agent.tools,
      config: @agent.model_config
    }
  }
end

#indexObject

GET /api/agents



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'app/controllers/action_agent/api/agents_controller.rb', line 24

def index
  @agents = owner_agents.order(updated_at: :desc)

  # Filter by status
  @agents = @agents.where(status: params[:status]) if params[:status].present?

  # Filter by provider
  @agents = @agents.where(provider: params[:provider]) if params[:provider].present?

  # Search by name
  # LOWER(...) LIKE rather than ILIKE: the dashboard is not
  # PostgreSQL-only.
  if params[:q].present?
    @agents = @agents.where("LOWER(name) LIKE ?", "%#{params[:q].to_s.downcase}%")
  end

  scorecards = AgentScorecard.for_agents(@agents)
  cards = sort_cards(
    @agents.map { |agent| agent_json(agent).merge(stats: scorecards[agent.id]) },
    params[:sort]
  )

  render json: {
    agents: cards,
    meta: {
      total: cards.size,
      sorts: LIST_SORTS,
      sort: list_sort(params[:sort]),
      providers: Agent::PROVIDERS,
      preset_types: Agent::PRESET_TYPES,
      instruction_sets: Agent::INSTRUCTION_SETS,
      available_tools: Agent::AVAILABLE_TOOLS
    }
  }
end

#presetsObject

GET /api/agents/presets



252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'app/controllers/action_agent/api/agents_controller.rb', line 252

def presets
  presets = Agent::PRESET_TYPES.map do |preset|
    {
      id: preset,
      name: preset.titleize,
      appearance: default_appearance_for(preset),
      suggested_tools: suggested_tools_for(preset),
      suggested_instructions: suggested_instructions_for(preset)
    }
  end

  render json: { presets: presets }
end

#restoreObject

POST /api/agents/:id/restore



105
106
107
108
109
110
# File 'app/controllers/action_agent/api/agents_controller.rb', line 105

def restore
  version = @agent.agent_versions.find(params[:version_id])
  @agent.restore_from_version!(version)

  render json: { agent: agent_json(@agent, include_details: true) }
end

#runsObject

GET /api/agents/:id/runs Every execution of this agent, whoever ran it: dashboard runs and SDK-reported traces in one list, discriminated by source. Agents observed from telemetry have no AgentRun rows at all, so a runs-only list showed them as empty while their scorecard reported real traffic.



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'app/controllers/action_agent/api/agents_controller.rb', line 117

def runs
  minutes = params[:minutes].presence&.then { |m| m.to_i.clamp(1, 60 * 24 * 90) }
  page = (params[:page] || 1).to_i
  per_page = (params[:per_page] || 20).to_i

  executions = AgentExecutions.new(
    agents: [ @agent ],
    owner: current_owner,
    window_minutes: minutes,
    source: params[:source],
    status: params[:status],
    sort: params[:sort]
  ).page(page: page, per_page: per_page)

  # One digest->version map for the page; labels each run's instructions
  # with the agent version that introduced them where one matches.
  digest_versions = @agent.instructions_digest_versions
  runs_by_id = AgentRun.where(id: executions[:rows].select { |r| r.source == "dashboard" }.map(&:id))
    .index_by(&:id)

  render json: {
    runs: executions[:rows].map { |row| serialize_execution(row, runs_by_id, digest_versions) },
    meta: {
      page: page,
      per_page: per_page,
      total: executions[:total],
      sources: AgentExecutions::SOURCES,
      sorts: AgentExecutions::SORTS
    }
  }
end

#showObject

GET /api/agents/:id



61
62
63
64
65
66
67
# File 'app/controllers/action_agent/api/agents_controller.rb', line 61

def show
  render json: {
    agent: agent_json(@agent, include_details: true),
    versions: @agent.agent_versions.recent.limit(10).map { |v| version_json(v) },
    recent_runs: @agent.agent_runs.recent.limit(5).map(&:summary)
  }
end

#testObject

POST /api/agents/:id/test



162
163
164
165
166
167
168
169
170
171
# File 'app/controllers/action_agent/api/agents_controller.rb', line 162

def test
  run = @agent.test_execute(
    params[:prompt],
    action: params[:action_name],
    **params.fetch(:params, {}).to_unsafe_h.symbolize_keys
  )
  record_execution_usage

  render json: { run: run.summary, output: run.output }
end

#updateObject

PATCH /api/agents/:id



81
82
83
84
85
86
87
# File 'app/controllers/action_agent/api/agents_controller.rb', line 81

def update
  if @agent.update(agent_params)
    render json: { agent: agent_json(@agent, include_details: true) }
  else
    render json: { errors: @agent.errors.full_messages }, status: :unprocessable_entity
  end
end

#versionsObject

GET /api/agents/:id/versions



96
97
98
99
100
101
102
# File 'app/controllers/action_agent/api/agents_controller.rb', line 96

def versions
  @versions = @agent.agent_versions.recent

  render json: {
    versions: @versions.map { |v| version_json(v, include_diff: true) }
  }
end