Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(sdks): add agent effort param and trace/snapshot endpoints (#4415)

Gergő Móricz7b659034118e
diff --git a/apps/elixir-sdk/generate.exs b/apps/elixir-sdk/generate.exs
index c826dde40..eb21afc26 100644
--- a/apps/elixir-sdk/generate.exs
+++ b/apps/elixir-sdk/generate.exs
@@ -145,7 +145,10 @@ defmodule Firecrawl.Generator do
@type response :: {:ok, Req.Response.t()} | {:error, Exception.t() | Firecrawl.Error.t()}
@base_url "#{base_url}"
- @sdk_origin "[email protected]"
+ # Sourced from mix.exs at compile time so the origin header cannot drift
+ # from the published package version.
+ @version Mix.Project.config()[:version]
+ @sdk_origin "elixir-sdk@" <> @version
defp client(opts) do
api_key =
diff --git a/apps/elixir-sdk/lib/firecrawl.ex b/apps/elixir-sdk/lib/firecrawl.ex
index 216d58e49..fc6f40b2f 100644
--- a/apps/elixir-sdk/lib/firecrawl.ex
+++ b/apps/elixir-sdk/lib/firecrawl.ex
@@ -41,7 +41,10 @@ defmodule Firecrawl do
@type response :: {:ok, Req.Response.t()} | {:error, Exception.t() | Firecrawl.Error.t()}
@base_url "https://api.firecrawl.dev/v2"
- @sdk_origin "[email protected]"
+ # Sourced from mix.exs at compile time so the origin header cannot drift
+ # from the published package version.
+ @version Mix.Project.config()[:version]
+ @sdk_origin "elixir-sdk@" <> @version
defp client(opts) do
api_key =
@@ -529,6 +532,40 @@ defmodule Firecrawl do
end
+ @doc """
+ Get a snapshot of an agent job
+
+ `GET /agent/{jobId}/snapshots/{snapshotId}`
+
+ Tag: Agent
+
+ ## Path Parameters
+
+ * `job_id` - Path parameter `jobId`
+ * `snapshot_id` - Path parameter `snapshotId`
+
+ ## Returns
+
+ * `{:ok, %Req.Response{}}` on success
+ * `{:error, exception}` on HTTP or validation failure
+
+ Success JSON: `%{"success" => true, "id" => "...", "snapshotId" => "...", "snapshot" => "<string content>"}`.
+ """
+ @spec get_agent_snapshot(String.t(), String.t(), keyword()) :: response()
+ def get_agent_snapshot(job_id, snapshot_id, opts \\ []) do
+ Req.get(client(opts), url: "/agent/#{job_id}/snapshots/#{snapshot_id}")
+ end
+
+
+ @doc """
+ Bang variant of `get_agent_snapshot`. Raises on error.
+ """
+ @spec get_agent_snapshot!(String.t(), String.t(), keyword()) :: Req.Response.t()
+ def get_agent_snapshot!(job_id, snapshot_id, opts \\ []) do
+ Req.get!(client(opts), url: "/agent/#{job_id}/snapshots/#{snapshot_id}")
+ end
+
+
@doc """
Get the status of an agent job
@@ -560,6 +597,56 @@ defmodule Firecrawl do
end
+ @doc """
+ Get the execution trace of an agent job
+
+ `GET /agent/{jobId}/trace`
+
+ Tag: Agent
+
+ The trace is only available for agent runs on spark-2.
+
+ ## Path Parameters
+
+ * `job_id` - Path parameter `jobId`
+
+ ## Options
+
+ * `:live_view` - when `true`, the query parameter `liveView=true` is sent and
+ the response may additionally carry `activeBrowserSessions`, a list of
+ `%{"id" => "...", "liveViewUrl" => "...", "viewport" => %{"width" => 1280, "height" => 720}}`
+ entries for the run's live browser sessions.
+
+ ## Returns
+
+ * `{:ok, %Req.Response{}}` on success
+ * `{:error, exception}` on HTTP or validation failure
+
+ Success JSON: `%{"success" => true, "id" => "...", "events" => [...], "creditsUsed" => 5}`.
+
+ Each event has a `type` field (e.g. `"run.started"`, `"tool_call.started"`,
+ `"artifact.updated"`) plus the base fields `schemaVersion`, `eventId`, `runId`,
+ `occurredAt`, `producerSequence`, and `agent`.
+ """
+ @spec get_agent_trace(String.t(), keyword()) :: response()
+ def get_agent_trace(job_id, opts \\ []) do
+ {live_view, opts} = Keyword.pop(opts, :live_view, false)
+ params = if live_view, do: [{"liveView", "true"}], else: []
+ Req.get(client(opts), url: "/agent/#{job_id}/trace", params: params)
+ end
+
+
+ @doc """
+ Bang variant of `get_agent_trace`. Raises on error.
+ """
+ @spec get_agent_trace!(String.t(), keyword()) :: Req.Response.t()
+ def get_agent_trace!(job_id, opts \\ []) do
+ {live_view, opts} = Keyword.pop(opts, :live_view, false)
+ params = if live_view, do: [{"liveView", "true"}], else: []
+ Req.get!(client(opts), url: "/agent/#{job_id}/trace", params: params)
+ end
+
+
@doc """
Get the errors of a batch scrape job
@@ -1347,6 +1434,7 @@ defmodule Firecrawl do
@start_agent_schema NimbleOptions.new!([
audit_metadata: [type: :keyword_list, keys: [username: [type: :string, required: true]], doc: "User attribution to include with SIEM logging events."],
+ effort: [type: {:in, ["low", "medium", "high"]}, doc: "Reasoning effort for the agent task. Every level runs spark-2."],
max_credits: [type: {:or, [:integer, :float]}, doc: "Maximum credits to spend on this agent task. Defaults to 2500 if not set. Values above 2,500 are always billed as paid requests."],
model: [type: {:or, [{:in, [:"spark-1-mini", :"spark-1-pro", :"spark-2"]}, :string]}, doc: "The model to use for the agent task. spark-1-pro (default) offers higher accuracy for complex tasks, spark-1-mini is 60% cheaper than spark-1-pro, spark-2 handles most tasks"],
prompt: [type: :string, required: true, doc: "The prompt describing what data to extract"],
@@ -1355,7 +1443,7 @@ defmodule Firecrawl do
urls: [type: {:list, :string}, doc: "Optional list of URLs to constrain the agent to"]
])
- @start_agent_key_mapping %{audit_metadata: "auditMetadata", max_credits: "maxCredits", model: "model", prompt: "prompt", schema: "schema", strict_constrain_to_urls: "strictConstrainToURLs", urls: "urls"}
+ @start_agent_key_mapping %{audit_metadata: "auditMetadata", effort: "effort", max_credits: "maxCredits", model: "model", prompt: "prompt", schema: "schema", strict_constrain_to_urls: "strictConstrainToURLs", urls: "urls"}
@doc """
Start an agent task for agentic data extraction
diff --git a/apps/elixir-sdk/mix.exs b/apps/elixir-sdk/mix.exs
index 6f95af7f0..9bdd1a28c 100644
--- a/apps/elixir-sdk/mix.exs
+++ b/apps/elixir-sdk/mix.exs
@@ -1,7 +1,7 @@
defmodule Firecrawl.MixProject do
use Mix.Project
- @version "1.9.2"
+ @version "1.10.0"
@source_url "https://github.com/firecrawl/firecrawl/tree/main/apps/elixir-sdk"
def project do
diff --git a/apps/elixir-sdk/test/firecrawl_test.exs b/apps/elixir-sdk/test/firecrawl_test.exs
index 89e70c556..5a00e53d0 100644
--- a/apps/elixir-sdk/test/firecrawl_test.exs
+++ b/apps/elixir-sdk/test/firecrawl_test.exs
@@ -140,6 +140,173 @@ defmodule FirecrawlTest do
"Expected connection error, got validation error: #{inspect(err)}"
end
+ test "start_agent sends effort in the request body" do
+ parent = self()
+
+ adapter = fn request ->
+ send(parent, {:request, request})
+
+ resp = Req.Response.new(
+ status: 200,
+ headers: %{"content-type" => ["application/json"]},
+ body: Jason.encode!(%{"success" => true, "id" => "agent-job"})
+ )
+
+ {request, resp}
+ end
+
+ assert {:ok, %Req.Response{status: 200}} =
+ Firecrawl.start_agent(
+ [prompt: "find pricing", effort: "high"],
+ api_key: "test-key",
+ adapter: adapter
+ )
+
+ assert_receive {:request, request}
+
+ body =
+ cond do
+ is_binary(request.body) -> Jason.decode!(request.body)
+ is_map(request.body) -> request.body
+ true -> request.options[:json]
+ end
+
+ assert body["effort"] == "high"
+ assert body["prompt"] == "find pricing"
+ # @sdk_origin is built from the mix.exs @version so the two cannot drift
+ assert body["origin"] == "elixir-sdk@" <> Mix.Project.config()[:version]
+ end
+
+ test "start_agent rejects invalid effort values" do
+ Application.put_env(:firecrawl, :api_key, "test-key")
+ on_exit(fn -> Application.delete_env(:firecrawl, :api_key) end)
+
+ assert {:error, %NimbleOptions.ValidationError{}} =
+ Firecrawl.start_agent(prompt: "test", effort: "ultra")
+ end
+
+ test "get_agent_trace hits /v2/agent/:id/trace" do
+ parent = self()
+
+ adapter = fn request ->
+ send(parent, {:request, request})
+
+ resp = Req.Response.new(
+ status: 200,
+ headers: %{"content-type" => ["application/json"]},
+ body:
+ Jason.encode!(%{
+ "success" => true,
+ "id" => "job-123",
+ "events" => [
+ %{
+ "type" => "run.started",
+ "schemaVersion" => 1,
+ "eventId" => "evt-1",
+ "runId" => "job-123",
+ "occurredAt" => "2026-08-26T00:00:00Z",
+ "producerSequence" => 0,
+ "agent" => %{"id" => "agent", "name" => "spark-2"}
+ }
+ ],
+ "creditsUsed" => 5
+ })
+ )
+
+ {request, resp}
+ end
+
+ assert {:ok, %Req.Response{status: 200}} =
+ Firecrawl.get_agent_trace("job-123", api_key: "test-key", adapter: adapter)
+
+ assert_receive {:request, request}
+ assert request.url.path == "/v2/agent/job-123/trace"
+ refute Map.has_key?(URI.decode_query(request.url.query || ""), "liveView")
+ end
+
+ test "get_agent_trace sends liveView=true query param when live_view: true" do
+ parent = self()
+
+ adapter = fn request ->
+ send(parent, {:request, request})
+
+ resp = Req.Response.new(
+ status: 200,
+ headers: %{"content-type" => ["application/json"]},
+ body:
+ Jason.encode!(%{
+ "success" => true,
+ "id" => "job-123",
+ "events" => [],
+ "creditsUsed" => 5,
+ "activeBrowserSessions" => [
+ %{
+ "id" => "sess-1",
+ "liveViewUrl" => "https://example.com/live",
+ "viewport" => %{"width" => 1280, "height" => 720}
+ }
+ ]
+ })
+ )
+
+ {request, resp}
+ end
+
+ assert {:ok, %Req.Response{status: 200}} =
+ Firecrawl.get_agent_trace("job-123",
+ live_view: true,
+ api_key: "test-key",
+ adapter: adapter
+ )
+
+ assert_receive {:request, request}
+ assert request.url.path == "/v2/agent/job-123/trace"
+ assert URI.decode_query(request.url.query || "")["liveView"] == "true"
+ end
+
+ test "get_agent_trace! returns the response on success" do
+ adapter = fn request ->
+ resp = Req.Response.new(
+ status: 200,
+ headers: %{"content-type" => ["application/json"]},
+ body: Jason.encode!(%{"success" => true, "id" => "job-123", "events" => [], "creditsUsed" => 5})
+ )
+
+ {request, resp}
+ end
+
+ assert %Req.Response{status: 200} =
+ Firecrawl.get_agent_trace!("job-123", api_key: "test-key", adapter: adapter)
+ end
+
+ test "get_agent_snapshot hits /v2/agent/:id/snapshots/:snapshot_id" do
+ parent = self()
+
+ adapter = fn request ->
+ send(parent, {:request, request})
+
+ resp = Req.Response.new(
+ status: 200,
+ headers: %{"content-type" => ["application/json"]},
+ body:
+ Jason.encode!(%{
+ "success" => true,
+ "id" => "job-123",
+ "snapshotId" => "snap-456",
+ "snapshot" => "snapshot content"
+ })
+ )
+
+ {request, resp}
+ end
+
+ assert {:ok, %Req.Response{status: 200}} =
+ Firecrawl.get_agent_snapshot("job-123", "snap-456", api_key: "test-key", adapter: adapter)
+
+ assert_receive {:request, request}
+ assert request.url.path == "/v2/agent/job-123/snapshots/snap-456"
+ end
+
test "accepts string values for enum params (sitemap)" do
Application.put_env(:firecrawl, :api_key, "test-key")
on_exit(fn -> Application.delete_env(:firecrawl, :api_key) end)
@@ -443,7 +610,11 @@ defmodule FirecrawlTest do
{:parse_file, 3},
{:parse_file!, 1},
{:parse_file!, 2},
- {:parse_file!, 3}
+ {:parse_file!, 3},
+ {:get_agent_trace, 2},
+ {:get_agent_trace!, 2},
+ {:get_agent_snapshot, 3},
+ {:get_agent_snapshot!, 3}
]
for {name, arity} <- expected do
diff --git a/apps/go-sdk/agent_test.go b/apps/go-sdk/agent_test.go
new file mode 100644
index 000000000..8bf3a4581
--- /dev/null
+++ b/apps/go-sdk/agent_test.go
@@ -0,0 +1,341 @@
+package firecrawl
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/firecrawl/firecrawl/apps/go-sdk/option"
+)
+
+// capturedRequest ferries the request the httptest handler received to the
+// test goroutine over a channel. Plain shared variables would trip the race
+// detector (the handler runs on its own goroutine), and t.Fatal inside the
+// handler would Goexit without writing a response, surfacing as a connection
+// error instead of the assertion message.
+type capturedRequest struct {
+ method string
+ path string
+ query string
+ body string
+}
+
+func captureRequest(r *http.Request) capturedRequest {
+ c := capturedRequest{method: r.Method, path: r.URL.Path, query: r.URL.RawQuery}
+ if r.Body != nil {
+ data, _ := io.ReadAll(r.Body)
+ c.body = string(data)
+ }
+ return c
+}
+
+func TestStartAgentSendsEffort(t *testing.T) {
+ captured := make(chan capturedRequest, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ captured <- captureRequest(r)
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"success":true,"id":"job-123"}`))
+ }))
+ defer server.Close()
+
+ client, err := NewClient(
+ option.WithAPIKey("fc-test"),
+ option.WithAPIURL(server.URL),
+ )
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ resp, err := client.StartAgent(context.Background(), &AgentOptions{
+ Prompt: "find pricing",
+ Model: String("spark-2"),
+ Effort: String("high"),
+ })
+ if err != nil {
+ t.Fatalf("StartAgent: %v", err)
+ }
+
+ req := <-captured
+ if req.method != http.MethodPost || req.path != "/v2/agent" {
+ t.Errorf("unexpected request: %s %s", req.method, req.path)
+ }
+ if resp.ID != "job-123" {
+ t.Errorf("id = %q, want job-123", resp.ID)
+ }
+ if !strings.Contains(req.body, `"effort":"high"`) {
+ t.Errorf("request body missing effort: %q", req.body)
+ }
+ if !strings.Contains(req.body, `"model":"spark-2"`) {
+ t.Errorf("request body missing model: %q", req.body)
+ }
+}
+
+func TestStartAgentOmitsEffortWhenUnset(t *testing.T) {
+ captured := make(chan capturedRequest, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ captured <- captureRequest(r)
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"success":true,"id":"job-123"}`))
+ }))
+ defer server.Close()
+
+ client, err := NewClient(
+ option.WithAPIKey("fc-test"),
+ option.WithAPIURL(server.URL),
+ )
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ if _, err := client.StartAgent(context.Background(), &AgentOptions{Prompt: "find pricing"}); err != nil {
+ t.Fatalf("StartAgent: %v", err)
+ }
+
+ req := <-captured
+ if strings.Contains(req.body, `"effort"`) {
+ t.Errorf("request body should omit effort: %q", req.body)
+ }
+}
+
+func TestGetAgentTraceParsesEvents(t *testing.T) {
+ captured := make(chan capturedRequest, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ captured <- captureRequest(r)
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "id": "job-123",
+ "creditsUsed": 5,
+ "events": [
+ {
+ "type": "run.started",
+ "schemaVersion": 1,
+ "eventId": "evt-1",
+ "runId": "job-123",
+ "occurredAt": "2026-08-26T10:00:00Z",
+ "producerSequence": 1,
+ "agent": {"id": "agent-1", "role": "primary", "name": "spark-2"}
+ },
+ {
+ "type": "artifact.updated",
+ "schemaVersion": 1,
+ "eventId": "evt-2",
+ "runId": "job-123",
+ "occurredAt": "2026-08-26T10:00:05Z",
+ "producerSequence": 2,
+ "agent": {"id": "agent-1", "role": "primary", "name": "spark-2"},
+ "artifact": {
+ "kind": "json",
+ "artifactId": "art-1",
+ "path": "plans",
+ "snapshotId": "snap-1",
+ "change": "updated",
+ "changedFields": ["plans"],
+ "itemCount": 3,
+ "sourceToolCallId": "tc-1"
+ }
+ }
+ ]
+ }`))
+ }))
+ defer server.Close()
+
+ client, err := NewClient(
+ option.WithAPIKey("fc-test"),
+ option.WithAPIURL(server.URL),
+ )
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ trace, err := client.GetAgentTrace(context.Background(), "job-123", false)
+ if err != nil {
+ t.Fatalf("GetAgentTrace: %v", err)
+ }
+
+ req := <-captured
+ if req.method != http.MethodGet || req.path != "/v2/agent/job-123/trace" {
+ t.Errorf("unexpected request: %s %s", req.method, req.path)
+ }
+ if req.query != "" {
+ t.Errorf("unexpected query params: %q", req.query)
+ }
+ if !trace.Success || trace.ID != "job-123" {
+ t.Fatalf("trace = %+v", trace)
+ }
+ if trace.CreditsUsed == nil || *trace.CreditsUsed != 5 {
+ t.Fatalf("creditsUsed = %v, want 5", trace.CreditsUsed)
+ }
+ if len(trace.Events) != 2 {
+ t.Fatalf("events len = %d, want 2", len(trace.Events))
+ }
+
+ started := trace.Events[0]
+ if started.Type != "run.started" || started.EventID != "evt-1" || started.RunID != "job-123" {
+ t.Fatalf("run.started event = %+v", started)
+ }
+ if started.SchemaVersion != 1 || started.ProducerSequence != 1 || started.OccurredAt != "2026-08-26T10:00:00Z" {
+ t.Fatalf("run.started base fields = %+v", started)
+ }
+ if started.Agent.ID != "agent-1" || started.Agent.Role != "primary" || started.Agent.Name != "spark-2" {
+ t.Fatalf("run.started agent = %+v", started.Agent)
+ }
+
+ updated := trace.Events[1]
+ if updated.Type != "artifact.updated" || updated.Artifact == nil {
+ t.Fatalf("artifact.updated event = %+v", updated)
+ }
+ artifact := updated.Artifact
+ if artifact.Kind != "json" || artifact.ArtifactID != "art-1" || artifact.SnapshotID != "snap-1" || artifact.Change != "updated" {
+ t.Fatalf("artifact = %+v", artifact)
+ }
+ if artifact.Path != "plans" || artifact.SourceToolCallID != "tc-1" {
+ t.Fatalf("artifact = %+v", artifact)
+ }
+ if len(artifact.ChangedFields) != 1 || artifact.ChangedFields[0] != "plans" {
+ t.Fatalf("changedFields = %v", artifact.ChangedFields)
+ }
+ if artifact.ItemCount == nil || *artifact.ItemCount != 3 {
+ t.Fatalf("itemCount = %v, want 3", artifact.ItemCount)
+ }
+}
+
+func TestGetAgentTraceSendsLiveView(t *testing.T) {
+ captured := make(chan capturedRequest, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ captured <- captureRequest(r)
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "id": "job-123",
+ "events": [],
+ "activeBrowserSessions": [
+ {
+ "id": "session-1",
+ "liveViewUrl": "https://live.firecrawl.dev/session-1",
+ "viewport": {"width": 1280, "height": 720}
+ }
+ ]
+ }`))
+ }))
+ defer server.Close()
+
+ client, err := NewClient(
+ option.WithAPIKey("fc-test"),
+ option.WithAPIURL(server.URL),
+ )
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ trace, err := client.GetAgentTrace(context.Background(), "job-123", true)
+ if err != nil {
+ t.Fatalf("GetAgentTrace: %v", err)
+ }
+
+ req := <-captured
+ if req.method != http.MethodGet || req.path != "/v2/agent/job-123/trace" {
+ t.Errorf("unexpected request: %s %s", req.method, req.path)
+ }
+ if req.query != "liveView=true" {
+ t.Errorf("liveView query param = %q, want true", req.query)
+ }
+ if len(trace.ActiveBrowserSessions) != 1 {
+ t.Fatalf("activeBrowserSessions len = %d, want 1", len(trace.ActiveBrowserSessions))
+ }
+ session := trace.ActiveBrowserSessions[0]
+ if session.ID != "session-1" || session.LiveViewURL != "https://live.firecrawl.dev/session-1" {
+ t.Fatalf("session = %+v", session)
+ }
+ if session.Viewport.Width != 1280 || session.Viewport.Height != 720 {
+ t.Fatalf("viewport = %+v", session.Viewport)
+ }
+}
+
+func TestGetAgentTraceRequiresJobID(t *testing.T) {
+ client, err := NewClient(
+ option.WithAPIKey("fc-test"),
+ option.WithAPIURL("http://localhost:0"),
+ )
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ if _, err := client.GetAgentTrace(context.Background(), "", false); err == nil {
+ t.Fatalf("expected error for empty job ID")
+ }
+}
+
+func TestGetAgentSnapshotParsesResponse(t *testing.T) {
+ captured := make(chan capturedRequest, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ captured <- captureRequest(r)
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{
+ "success": true,
+ "id": "job-123",
+ "snapshotId": "snap-1",
+ "snapshot": "{\"plans\":[{\"name\":\"pro\",\"price\":\"$20\"}]}"
+ }`))
+ }))
+ defer server.Close()
+
+ client, err := NewClient(
+ option.WithAPIKey("fc-test"),
+ option.WithAPIURL(server.URL),
+ )
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ snapshot, err := client.GetAgentSnapshot(context.Background(), "job-123", "snap-1")
+ if err != nil {
+ t.Fatalf("GetAgentSnapshot: %v", err)
+ }
+
+ req := <-captured
+ if req.method != http.MethodGet || req.path != "/v2/agent/job-123/snapshots/snap-1" {
+ t.Errorf("unexpected request: %s %s", req.method, req.path)
+ }
+ if !snapshot.Success || snapshot.ID != "job-123" || snapshot.SnapshotID != "snap-1" {
+ t.Fatalf("snapshot = %+v", snapshot)
+ }
+ if !strings.Contains(snapshot.Snapshot, `"plans"`) {
+ t.Errorf("snapshot content = %q", snapshot.Snapshot)
+ }
+}
+
+func TestGetAgentSnapshotRequiresIDs(t *testing.T) {
+ client, err := NewClient(
+ option.WithAPIKey("fc-test"),
+ option.WithAPIURL("http://localhost:0"),
+ )
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+
+ if _, err := client.GetAgentSnapshot(context.Background(), "", "snap-1"); err == nil {
+ t.Fatalf("expected error for empty job ID")
+ }
+ if _, err := client.GetAgentSnapshot(context.Background(), "job-123", ""); err == nil {
+ t.Fatalf("expected error for empty snapshot ID")
+ }
+}
diff --git a/apps/go-sdk/firecrawl.go b/apps/go-sdk/firecrawl.go
index 409bb2e9a..5eba69099 100644
--- a/apps/go-sdk/firecrawl.go
+++ b/apps/go-sdk/firecrawl.go
@@ -795,6 +795,50 @@ func (c *Client) CancelAgent(ctx context.Context, jobID string) (map[string]inte
return resp, nil
}
+// GetAgentTrace gets the event trace of an agent task. When liveView is true,
+// the response also includes any active browser sessions with live view URLs.
+func (c *Client) GetAgentTrace(ctx context.Context, jobID string, liveView bool) (*AgentTraceResponse, error) {
+ if jobID == "" {
+ return nil, &FirecrawlError{Message: "job ID is required"}
+ }
+
+ path := "/v2/agent/" + jobID + "/trace"
+ if liveView {
+ path += "?liveView=true"
+ }
+ raw, err := c.http.get(ctx, path)
+ if err != nil {
+ return nil, err
+ }
+
+ var resp AgentTraceResponse
+ if err := json.Unmarshal(raw, &resp); err != nil {
+ return nil, &FirecrawlError{Message: fmt.Sprintf("failed to decode response: %v", err)}
+ }
+ return &resp, nil
+}
+
+// GetAgentSnapshot gets a snapshot of an agent task.
+func (c *Client) GetAgentSnapshot(ctx context.Context, jobID string, snapshotID string) (*AgentSnapshotResponse, error) {
+ if jobID == "" {
+ return nil, &FirecrawlError{Message: "job ID is required"}
+ }
+ if snapshotID == "" {
+ return nil, &FirecrawlError{Message: "snapshot ID is required"}
+ }
+
+ raw, err := c.http.get(ctx, "/v2/agent/"+jobID+"/snapshots/"+snapshotID)
+ if err != nil {
+ return nil, err
+ }
+
+ var resp AgentSnapshotResponse
+ if err := json.Unmarshal(raw, &resp); err != nil {
+ return nil, &FirecrawlError{Message: fmt.Sprintf("failed to decode response: %v", err)}
+ }
+ return &resp, nil
+}
+
// ================================================================
// BROWSER
// ================================================================
diff --git a/apps/go-sdk/models.go b/apps/go-sdk/models.go
index f65ff0918..49b853cc7 100644
--- a/apps/go-sdk/models.go
+++ b/apps/go-sdk/models.go
@@ -623,6 +623,7 @@ type AgentStatusResponse struct {
Error string `json:"error,omitempty"`
Data interface{} `json:"data,omitempty"`
Model string `json:"model,omitempty"`
+ Effort string `json:"effort,omitempty"`
ExpiresAt string `json:"expiresAt,omitempty"`
CreditsUsed *int `json:"creditsUsed,omitempty"`
}
@@ -632,6 +633,94 @@ func (a *AgentStatusResponse) IsDone() bool {
return a.Status == "completed" || a.Status == "failed" || a.Status == "cancelled"
}
+// AgentTraceResponse is returned when fetching the event trace of an agent task.
+type AgentTraceResponse struct {
+ Success bool `json:"success"`
+ ID string `json:"id,omitempty"`
+ Events []AgentTraceEvent `json:"events,omitempty"`
+ CreditsUsed *int `json:"creditsUsed,omitempty"`
+ ActiveBrowserSessions []AgentTraceActiveBrowserSession `json:"activeBrowserSessions,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// AgentTraceActiveBrowserSession represents a live browser session attached to
+// an agent run.
+type AgentTraceActiveBrowserSession struct {
+ ID string `json:"id"`
+ LiveViewURL string `json:"liveViewUrl,omitempty"`
+ Viewport AgentTraceViewport `json:"viewport,omitempty"`
+}
+
+// AgentTraceViewport represents the viewport dimensions of a live browser session.
+type AgentTraceViewport struct {
+ Width int `json:"width"`
+ Height int `json:"height"`
+}
+
+// AgentTraceEvent represents a single event in an agent run trace. The Type
+// field discriminates the event kind (e.g. "run.started", "tool_call.finished",
+// "artifact.updated"); only the fields relevant to that kind are set.
+type AgentTraceEvent struct {
+ Type string `json:"type"`
+ SchemaVersion int `json:"schemaVersion"`
+ EventID string `json:"eventId"`
+ RunID string `json:"runId"`
+ OccurredAt string `json:"occurredAt"`
+ ProducerSequence int `json:"producerSequence"`
+ Agent AgentTraceAgentIdentity `json:"agent"`
+ Reason string `json:"reason,omitempty"`
+ Outcome string `json:"outcome,omitempty"`
+ Error *AgentTraceError `json:"error,omitempty"`
+ DurationMs *int64 `json:"durationMs,omitempty"`
+ SessionID string `json:"sessionId,omitempty"`
+ Phase string `json:"phase,omitempty"`
+ Message string `json:"message,omitempty"`
+ Text string `json:"text,omitempty"`
+ ToolCallID string `json:"toolCallId,omitempty"`
+ ToolName string `json:"toolName,omitempty"`
+ Parameters interface{} `json:"parameters,omitempty"`
+ Result interface{} `json:"result,omitempty"`
+ Artifact *AgentTraceArtifactChange `json:"artifact,omitempty"`
+}
+
+// AgentTraceAgentIdentity identifies the agent that produced a trace event.
+type AgentTraceAgentIdentity struct {
+ ID string `json:"id"`
+ Role string `json:"role"`
+ Name string `json:"name"`
+ ParentID string `json:"parentId,omitempty"`
+}
+
+// AgentTraceError represents an error attached to a trace event.
+type AgentTraceError struct {
+ Code string `json:"code"`
+ Source string `json:"source"`
+ Retryable bool `json:"retryable"`
+ Message string `json:"message"`
+}
+
+// AgentTraceArtifactChange describes the artifact mutation reported by an
+// "artifact.updated" trace event.
+type AgentTraceArtifactChange struct {
+ Kind string `json:"kind"`
+ ArtifactID string `json:"artifactId"`
+ Path string `json:"path,omitempty"`
+ SnapshotID string `json:"snapshotId"`
+ Change string `json:"change"`
+ ChangedFields []string `json:"changedFields,omitempty"`
+ ItemCount *int `json:"itemCount,omitempty"`
+ SourceToolCallID string `json:"sourceToolCallId,omitempty"`
+}
+
+// AgentSnapshotResponse is returned when fetching a snapshot of an agent task.
+type AgentSnapshotResponse struct {
+ Success bool `json:"success"`
+ ID string `json:"id,omitempty"`
+ SnapshotID string `json:"snapshotId,omitempty"`
+ Snapshot string `json:"snapshot,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
// BrowserCreateResponse is returned when creating a browser session.
type BrowserCreateResponse struct {
Success bool `json:"success"`
diff --git a/apps/go-sdk/options.go b/apps/go-sdk/options.go
index f16df8111..b9533aa4c 100644
--- a/apps/go-sdk/options.go
+++ b/apps/go-sdk/options.go
@@ -187,8 +187,11 @@ type AgentOptions struct {
MaxCredits *int `json:"maxCredits,omitempty"`
StrictConstrainToURLs *bool `json:"strictConstrainToURLs,omitempty"`
Model *string `json:"model,omitempty"`
- Webhook *WebhookConfig `json:"webhook,omitempty"`
- AuditMetadata *AuditMetadata `json:"auditMetadata,omitempty"`
+ // Effort sets the reasoning budget for the agent. Valid values are "low",
+ // "medium", and "high". Every effort level runs spark-2.
+ Effort *string `json:"effort,omitempty"`
+ Webhook *WebhookConfig `json:"webhook,omitempty"`
+ AuditMetadata *AuditMetadata `json:"auditMetadata,omitempty"`
}
// AuditMetadata identifies the user associated with a SIEM logging event.
diff --git a/apps/go-sdk/version.go b/apps/go-sdk/version.go
index 186497366..a9d6c41f7 100644
--- a/apps/go-sdk/version.go
+++ b/apps/go-sdk/version.go
@@ -9,4 +9,4 @@ package firecrawl
// Bump this when preparing a new release. The publish-go-sdk GitHub workflow
// reads this value and creates the corresponding monorepo-prefixed tag on
// merge to main.
-const Version = "1.12.0"
+const Version = "1.13.0"
diff --git a/apps/java-sdk/README.md b/apps/java-sdk/README.md
index 0a80b015a..27cdccc45 100644
--- a/apps/java-sdk/README.md
+++ b/apps/java-sdk/README.md
@@ -82,13 +82,13 @@ Before using the Java SDK, ensure you have the following installed:
### Gradle (Kotlin DSL)
```kotlin
-implementation("com.firecrawl:firecrawl-java:1.6.0")
+implementation("com.firecrawl:firecrawl-java:1.16.0")
```
### Gradle (Groovy)
```groovy
-implementation 'com.firecrawl:firecrawl-java:1.6.0'
+implementation 'com.firecrawl:firecrawl-java:1.16.0'
```
### Maven
@@ -97,7 +97,7 @@ implementation 'com.firecrawl:firecrawl-java:1.6.0'
<dependency>
<groupId>com.firecrawl</groupId>
<artifactId>firecrawl-java</artifactId>
- <version>1.6.0</version>
+ <version>1.16.0</version>
</dependency>
```
@@ -430,14 +430,14 @@ gradle build
```bash
gradle jar
-# Output: build/libs/firecrawl-java-1.6.0.jar
+# Output: build/libs/firecrawl-java-1.16.0.jar
```
### Install Locally
```bash
gradle publishToMavenLocal
-# Now available as: com.firecrawl:firecrawl-java:1.6.0 in local Maven repository
+# Now available as: com.firecrawl:firecrawl-java:1.16.0 in local Maven repository
```
## Running Tests
diff --git a/apps/java-sdk/build.gradle.kts b/apps/java-sdk/build.gradle.kts
index 3d268db2a..c76d95af2 100644
--- a/apps/java-sdk/build.gradle.kts
+++ b/apps/java-sdk/build.gradle.kts
@@ -4,7 +4,7 @@ plugins {
}
group = "com.firecrawl"
-version = "1.15.0"
+version = "1.16.0"
java {
sourceCompatibility = JavaVersion.VERSION_11
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java b/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java
index 3b725f3b3..5e11711e1 100644
--- a/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java
+++ b/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java
@@ -37,7 +37,7 @@ import java.util.concurrent.ForkJoinPool;
public class FirecrawlClient {
private static final String DEFAULT_API_URL = "https://api.firecrawl.dev";
- private static final String SDK_ORIGIN = "[email protected]";
+ private static final String SDK_ORIGIN = "[email protected]";
private static final long DEFAULT_TIMEOUT_MS = 300_000; // 5 minutes
private static final int DEFAULT_MAX_RETRIES = 3;
private static final double DEFAULT_BACKOFF_FACTOR = 0.5;
@@ -687,6 +687,46 @@ public class FirecrawlClient {
return http.delete("/v2/agent/" + jobId, Map.class);
}
+ /**
+ * Gets the event trace of an agent task.
+ *
+ * @param jobId the agent job ID
+ * @return the agent trace response
+ */
+ public AgentTraceResponse getAgentTrace(String jobId) {
+ return getAgentTrace(jobId, false);
+ }
+
+ /**
+ * Gets the event trace of an agent task, optionally including live view URLs
+ * for active browser sessions.
+ *
+ * @param jobId the agent job ID
+ * @param liveView whether to include active browser sessions with live view URLs
+ * @return the agent trace response
+ */
+ public AgentTraceResponse getAgentTrace(String jobId, boolean liveView) {
+ Objects.requireNonNull(jobId, "Job ID is required");
+ String endpoint = "/v2/agent/" + jobId + "/trace";
+ if (liveView) {
+ endpoint += "?liveView=true";
+ }
+ return http.get(endpoint, AgentTraceResponse.class);
+ }
+
+ /**
+ * Gets a snapshot of an agent task.
+ *
+ * @param jobId the agent job ID
+ * @param snapshotId the snapshot ID
+ * @return the agent snapshot response
+ */
+ public AgentSnapshotResponse getAgentSnapshot(String jobId, String snapshotId) {
+ Objects.requireNonNull(jobId, "Job ID is required");
+ Objects.requireNonNull(snapshotId, "Snapshot ID is required");
+ return http.get("/v2/agent/" + jobId + "/snapshots/" + snapshotId, AgentSnapshotResponse.class);
+ }
+
// ================================================================
// BROWSER
// ================================================================
@@ -1196,6 +1236,39 @@ public class FirecrawlClient {
return CompletableFuture.supplyAsync(() -> cancelAgent(jobId), asyncExecutor);
}
+ /**
+ * Asynchronously gets the event trace of an agent task.
+ *
+ * @param jobId the agent job ID
+ * @return a CompletableFuture that resolves to the AgentTraceResponse
+ */
+ public CompletableFuture<AgentTraceResponse> getAgentTraceAsync(String jobId) {
+ return CompletableFuture.supplyAsync(() -> getAgentTrace(jobId), asyncExecutor);
+ }
+
+ /**
+ * Asynchronously gets the event trace of an agent task, optionally including
+ * live view URLs for active browser sessions.
+ *
+ * @param jobId the agent job ID
+ * @param liveView whether to include active browser sessions with live view URLs
+ * @return a CompletableFuture that resolves to the AgentTraceResponse
+ */
+ public CompletableFuture<AgentTraceResponse> getAgentTraceAsync(String jobId, boolean liveView) {
+ return CompletableFuture.supplyAsync(() -> getAgentTrace(jobId, liveView), asyncExecutor);
+ }
+
+ /**
+ * Asynchronously gets a snapshot of an agent task.
+ *
+ * @param jobId the agent job ID
+ * @param snapshotId the snapshot ID
+ * @return a CompletableFuture that resolves to the AgentSnapshotResponse
+ */
+ public CompletableFuture<AgentSnapshotResponse> getAgentSnapshotAsync(String jobId, String snapshotId) {
+ return CompletableFuture.supplyAsync(() -> getAgentSnapshot(jobId, snapshotId), asyncExecutor);
+ }
+
/**
* Asynchronously gets concurrency info.
*
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentOptions.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentOptions.java
index a738a57bf..336a85f06 100644
--- a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentOptions.java
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentOptions.java
@@ -18,6 +18,7 @@ public class AgentOptions {
private Integer maxCredits;
private Boolean strictConstrainToURLs;
private String model;
+ private String effort;
private WebhookConfig webhook;
private AuditMetadata auditMetadata;
@@ -30,6 +31,7 @@ public class AgentOptions {
public Integer getMaxCredits() { return maxCredits; }
public Boolean getStrictConstrainToURLs() { return strictConstrainToURLs; }
public String getModel() { return model; }
+ public String getEffort() { return effort; }
public WebhookConfig getWebhook() { return webhook; }
@JsonProperty("auditMetadata")
public AuditMetadata getAuditMetadata() { return auditMetadata; }
@@ -44,6 +46,7 @@ public class AgentOptions {
private Integer maxCredits;
private Boolean strictConstrainToURLs;
private String model;
+ private String effort;
private WebhookConfig webhook;
private AuditMetadata auditMetadata;
@@ -63,6 +66,8 @@ public class AgentOptions {
public Builder strictConstrainToURLs(Boolean strictConstrainToURLs) { this.strictConstrainToURLs = strictConstrainToURLs; return this; }
/** Agent model: "spark-1-pro" (default), "spark-1-mini", or "spark-2". */
public Builder model(String model) { this.model = model; return this; }
+ /** Reasoning effort: "low", "medium", or "high". Sets the reasoning budget (every level runs spark-2). */
+ public Builder effort(String effort) { this.effort = effort; return this; }
/** Webhook configuration. */
public Builder webhook(WebhookConfig webhook) { this.webhook = webhook; return this; }
/** User attribution to include with SIEM logging events. */
@@ -80,6 +85,7 @@ public class AgentOptions {
o.maxCredits = this.maxCredits;
o.strictConstrainToURLs = this.strictConstrainToURLs;
o.model = this.model;
+ o.effort = this.effort;
o.webhook = this.webhook;
o.auditMetadata = this.auditMetadata;
return o;
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentSnapshotResponse.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentSnapshotResponse.java
new file mode 100644
index 000000000..b79a1c449
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentSnapshotResponse.java
@@ -0,0 +1,27 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * Response from the agent snapshot endpoint.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentSnapshotResponse {
+
+ private boolean success;
+ private String id;
+ private String snapshotId;
+ private String snapshot;
+ private String error;
+
+ public boolean isSuccess() { return success; }
+ public String getId() { return id; }
+ public String getSnapshotId() { return snapshotId; }
+ public String getSnapshot() { return snapshot; }
+ public String getError() { return error; }
+
+ @Override
+ public String toString() {
+ return "AgentSnapshotResponse{success=" + success + ", id=" + id + ", snapshotId=" + snapshotId + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentStatusResponse.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentStatusResponse.java
index 4a761013f..f1a28ccbf 100644
--- a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentStatusResponse.java
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentStatusResponse.java
@@ -13,6 +13,7 @@ public class AgentStatusResponse {
private String error;
private Object data;
private String model;
+ private String effort;
private String expiresAt;
private Integer creditsUsed;
@@ -21,6 +22,8 @@ public class AgentStatusResponse {
public String getError() { return error; }
public Object getData() { return data; }
public String getModel() { return model; }
+ /** The effort the job ran with; only present for runs that specified it. */
+ public String getEffort() { return effort; }
public String getExpiresAt() { return expiresAt; }
public Integer getCreditsUsed() { return creditsUsed; }
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceActiveBrowserSession.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceActiveBrowserSession.java
new file mode 100644
index 000000000..28c9bc8d6
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceActiveBrowserSession.java
@@ -0,0 +1,23 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * An active browser session attached to an agent run, with a live view URL.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentTraceActiveBrowserSession {
+
+ private String id;
+ private String liveViewUrl;
+ private AgentTraceViewport viewport;
+
+ public String getId() { return id; }
+ public String getLiveViewUrl() { return liveViewUrl; }
+ public AgentTraceViewport getViewport() { return viewport; }
+
+ @Override
+ public String toString() {
+ return "AgentTraceActiveBrowserSession{id=" + id + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceAgentIdentity.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceAgentIdentity.java
new file mode 100644
index 000000000..e8c7d415b
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceAgentIdentity.java
@@ -0,0 +1,25 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * Identity of the agent that produced a trace event.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentTraceAgentIdentity {
+
+ private String id;
+ private String role;
+ private String name;
+ private String parentId;
+
+ public String getId() { return id; }
+ public String getRole() { return role; }
+ public String getName() { return name; }
+ public String getParentId() { return parentId; }
+
+ @Override
+ public String toString() {
+ return "AgentTraceAgentIdentity{id=" + id + ", role=" + role + ", name=" + name + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceArtifactChange.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceArtifactChange.java
new file mode 100644
index 000000000..2f965799c
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceArtifactChange.java
@@ -0,0 +1,34 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import java.util.List;
+
+/**
+ * Describes a change to an artifact in an agent trace event.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentTraceArtifactChange {
+
+ private String kind;
+ private String artifactId;
+ private String path;
+ private String snapshotId;
+ private String change;
+ private List<String> changedFields;
+ private Integer itemCount;
+ private String sourceToolCallId;
+
+ public String getKind() { return kind; }
+ public String getArtifactId() { return artifactId; }
+ public String getPath() { return path; }
+ public String getSnapshotId() { return snapshotId; }
+ public String getChange() { return change; }
+ public List<String> getChangedFields() { return changedFields; }
+ public Integer getItemCount() { return itemCount; }
+ public String getSourceToolCallId() { return sourceToolCallId; }
+
+ @Override
+ public String toString() {
+ return "AgentTraceArtifactChange{kind=" + kind + ", artifactId=" + artifactId + ", change=" + change + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceError.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceError.java
new file mode 100644
index 000000000..80d1a401e
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceError.java
@@ -0,0 +1,25 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * Structured error carried by agent trace events.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentTraceError {
+
+ private String code;
+ private String source;
+ private boolean retryable;
+ private String message;
+
+ public String getCode() { return code; }
+ public String getSource() { return source; }
+ public boolean isRetryable() { return retryable; }
+ public String getMessage() { return message; }
+
+ @Override
+ public String toString() {
+ return "AgentTraceError{code=" + code + ", source=" + source + ", retryable=" + retryable + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceEvent.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceEvent.java
new file mode 100644
index 000000000..0f646cd6b
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceEvent.java
@@ -0,0 +1,69 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * A single event in an agent run trace.
+ *
+ * <p>Models all event kinds in one class; per-type fields are null when not
+ * applicable. Known {@code type} values: {@code run.started},
+ * {@code run.cancel_requested}, {@code run.finished}, {@code agent.started},
+ * {@code agent.finished}, {@code browser.session.started},
+ * {@code browser.session.finished}, {@code progress.reported},
+ * {@code reasoning.summary}, {@code tool_call.started},
+ * {@code tool_call.finished}, {@code artifact.updated}, {@code error.occurred}.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentTraceEvent {
+
+ private String type;
+
+ // Base fields present on every event
+ private int schemaVersion;
+ private String eventId;
+ private String runId;
+ private String occurredAt;
+ private long producerSequence;
+ private AgentTraceAgentIdentity agent;
+
+ // Per-type fields (nullable)
+ private String reason;
+ private String outcome;
+ private AgentTraceError error;
+ private Long durationMs;
+ private String sessionId;
+ private String phase;
+ private String message;
+ private String text;
+ private String toolCallId;
+ private String toolName;
+ private Object parameters;
+ private Object result;
+ private AgentTraceArtifactChange artifact;
+
+ public String getType() { return type; }
+ public int getSchemaVersion() { return schemaVersion; }
+ public String getEventId() { return eventId; }
+ public String getRunId() { return runId; }
+ public String getOccurredAt() { return occurredAt; }
+ public long getProducerSequence() { return producerSequence; }
+ public AgentTraceAgentIdentity getAgent() { return agent; }
+ public String getReason() { return reason; }
+ public String getOutcome() { return outcome; }
+ public AgentTraceError getError() { return error; }
+ public Long getDurationMs() { return durationMs; }
+ public String getSessionId() { return sessionId; }
+ public String getPhase() { return phase; }
+ public String getMessage() { return message; }
+ public String getText() { return text; }
+ public String getToolCallId() { return toolCallId; }
+ public String getToolName() { return toolName; }
+ public Object getParameters() { return parameters; }
+ public Object getResult() { return result; }
+ public AgentTraceArtifactChange getArtifact() { return artifact; }
+
+ @Override
+ public String toString() {
+ return "AgentTraceEvent{type=" + type + ", eventId=" + eventId + ", occurredAt=" + occurredAt + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceResponse.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceResponse.java
new file mode 100644
index 000000000..cf7276b54
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceResponse.java
@@ -0,0 +1,31 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import java.util.List;
+
+/**
+ * Response from the agent trace endpoint.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentTraceResponse {
+
+ private boolean success;
+ private String id;
+ private List<AgentTraceEvent> events;
+ private Integer creditsUsed;
+ private List<AgentTraceActiveBrowserSession> activeBrowserSessions;
+ private String error;
+
+ public boolean isSuccess() { return success; }
+ public String getId() { return id; }
+ public List<AgentTraceEvent> getEvents() { return events; }
+ public Integer getCreditsUsed() { return creditsUsed; }
+ public List<AgentTraceActiveBrowserSession> getActiveBrowserSessions() { return activeBrowserSessions; }
+ public String getError() { return error; }
+
+ @Override
+ public String toString() {
+ return "AgentTraceResponse{success=" + success + ", id=" + id + ", events="
+ + (events != null ? events.size() : 0) + "}";
+ }
+}
diff --git a/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceViewport.java b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceViewport.java
new file mode 100644
index 000000000..e91f903c5
--- /dev/null
+++ b/apps/java-sdk/src/main/java/com/firecrawl/models/AgentTraceViewport.java
@@ -0,0 +1,21 @@
+package com.firecrawl.models;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * Viewport dimensions of an agent browser session.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AgentTraceViewport {
+
+ private int width;
+ private int height;
+
+ public int getWidth() { return width; }
+ public int getHeight() { return height; }
+
+ @Override
+ public String toString() {
+ return "AgentTraceViewport{width=" + width + ", height=" + height + "}";
+ }
+}
diff --git a/apps/java-sdk/src/test/java/com/firecrawl/AgentMockTest.java b/apps/java-sdk/src/test/java/com/firecrawl/AgentMockTest.java
new file mode 100644
index 000000000..a5c2d201b
--- /dev/null
+++ b/apps/java-sdk/src/test/java/com/firecrawl/AgentMockTest.java
@@ -0,0 +1,201 @@
+package com.firecrawl;
+
+import com.firecrawl.client.FirecrawlClient;
+import com.firecrawl.models.AgentOptions;
+import com.firecrawl.models.AgentResponse;
+import com.firecrawl.models.AgentSnapshotResponse;
+import com.firecrawl.models.AgentTraceEvent;
+import com.firecrawl.models.AgentTraceResponse;
+import com.sun.net.httpserver.HttpServer;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Agent endpoint tests against a local mock HTTP server.
+ *
+ * Verifies request serialization (effort parameter, query params) and
+ * response parsing for the agent trace and snapshot endpoints without
+ * requiring a live API key.
+ */
+class AgentMockTest {
+
+ private HttpServer server;
+ private FirecrawlClient client;
+ private final AtomicReference<String> lastRequestBody = new AtomicReference<>();
+ private final AtomicReference<String> lastRequestPath = new AtomicReference<>();
+
+ @BeforeEach
+ void setup() throws IOException {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+
+ server.createContext("/v2/agent", exchange -> {
+ lastRequestPath.set(exchange.getRequestURI().toString());
+ lastRequestBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
+ respond(exchange, 200, "{\"success\":true,\"id\":\"job-123\"}");
+ });
+
+ server.createContext("/v2/agent/job-123/trace", exchange -> {
+ lastRequestPath.set(exchange.getRequestURI().toString());
+ respond(exchange, 200, "{"
+ + "\"success\":true,"
+ + "\"id\":\"job-123\","
+ + "\"creditsUsed\":5,"
+ + "\"events\":["
+ + " {\"type\":\"run.started\",\"schemaVersion\":1,\"eventId\":\"evt-1\",\"runId\":\"job-123\","
+ + " \"occurredAt\":\"2026-01-01T00:00:00Z\",\"producerSequence\":1,"
+ + " \"agent\":{\"id\":\"agent-1\",\"role\":\"primary\",\"name\":\"Spark\",\"parentId\":null}},"
+ + " {\"type\":\"tool_call.started\",\"schemaVersion\":1,\"eventId\":\"evt-2\",\"runId\":\"job-123\","
+ + " \"occurredAt\":\"2026-01-01T00:00:01Z\",\"producerSequence\":2,"
+ + " \"agent\":{\"id\":\"agent-1\",\"role\":\"primary\",\"name\":\"Spark\"},"
+ + " \"toolCallId\":\"tc-1\",\"toolName\":\"scrape\",\"parameters\":{\"url\":\"https://example.com\"}},"
+ + " {\"type\":\"artifact.updated\",\"schemaVersion\":1,\"eventId\":\"evt-3\",\"runId\":\"job-123\","
+ + " \"occurredAt\":\"2026-01-01T00:00:02Z\",\"producerSequence\":3,"
+ + " \"agent\":{\"id\":\"agent-1\",\"role\":\"primary\",\"name\":\"Spark\"},"
+ + " \"artifact\":{\"kind\":\"data\",\"artifactId\":\"art-1\",\"path\":\"result\",\"snapshotId\":\"snap-1\","
+ + " \"change\":\"created\",\"changedFields\":[\"title\"],\"itemCount\":1,\"sourceToolCallId\":\"tc-1\"}}"
+ + "],"
+ + "\"activeBrowserSessions\":[{\"id\":\"sess-1\",\"liveViewUrl\":\"https://live.example.com/sess-1\","
+ + "\"viewport\":{\"width\":1280,\"height\":720}}]"
+ + "}");
+ });
+
+ server.createContext("/v2/agent/job-123/snapshots/snap-1", exchange -> {
+ lastRequestPath.set(exchange.getRequestURI().toString());
+ respond(exchange, 200, "{\"success\":true,\"id\":\"job-123\",\"snapshotId\":\"snap-1\","
+ + "\"snapshot\":\"snapshot content here\"}");
+ });
+
+ server.start();
+ client = FirecrawlClient.builder()
+ .apiKey("fc-test-key")
+ .apiUrl("http://127.0.0.1:" + server.getAddress().getPort())
+ .build();
+ }
+
+ @AfterEach
+ void teardown() {
+ server.stop(0);
+ }
+
+ private static void respond(com.sun.net.httpserver.HttpExchange exchange, int status, String body) throws IOException {
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().set("Content-Type", "application/json");
+ exchange.sendResponseHeaders(status, bytes.length);
+ try (OutputStream os = exchange.getResponseBody()) {
+ os.write(bytes);
+ }
+ }
+
+ @Test
+ void testStartAgentSendsEffort() {
+ AgentResponse response = client.startAgent(
+ AgentOptions.builder()
+ .prompt("Research Firecrawl features")
+ .model("spark-2")
+ .effort("high")
+ .build());
+
+ assertTrue(response.isSuccess());
+ assertEquals("job-123", response.getId());
+
+ String body = lastRequestBody.get();
+ assertNotNull(body, "Request body should have been captured");
+ assertTrue(body.contains("\"effort\":\"high\""),
+ "Request body should contain effort: " + body);
+ assertTrue(body.contains("\"model\":\"spark-2\""),
+ "Request body should contain model: " + body);
+ assertTrue(body.contains("\"prompt\":\"Research Firecrawl features\""),
+ "Request body should contain prompt: " + body);
+ }
+
+ @Test
+ void testStartAgentOmitsEffortWhenNotSet() {
+ client.startAgent(AgentOptions.builder().prompt("Hello").build());
+
+ String body = lastRequestBody.get();
+ assertNotNull(body);
+ assertFalse(body.contains("effort"), "Request body should not contain effort: " + body);
+ }
+
+ @Test
+ void testGetAgentTraceParsesEvents() {
+ AgentTraceResponse trace = client.getAgentTrace("job-123");
+
+ assertEquals("/v2/agent/job-123/trace", lastRequestPath.get(),
+ "Should not send liveView param by default");
+
+ assertTrue(trace.isSuccess());
+ assertEquals("job-123", trace.getId());
+ assertEquals(5, trace.getCreditsUsed());
+ assertNotNull(trace.getEvents());
+ assertEquals(3, trace.getEvents().size());
+
+ AgentTraceEvent started = trace.getEvents().get(0);
+ assertEquals("run.started", started.getType());
+ assertEquals(1, started.getSchemaVersion());
+ assertEquals("evt-1", started.getEventId());
+ assertEquals("job-123", started.getRunId());
+ assertEquals("2026-01-01T00:00:00Z", started.getOccurredAt());
+ assertEquals(1L, started.getProducerSequence());
+ assertNotNull(started.getAgent());
+ assertEquals("agent-1", started.getAgent().getId());
+ assertEquals("primary", started.getAgent().getRole());
+ assertEquals("Spark", started.getAgent().getName());
+
+ AgentTraceEvent toolCall = trace.getEvents().get(1);
+ assertEquals("tool_call.started", toolCall.getType());
+ assertEquals("tc-1", toolCall.getToolCallId());
+ assertEquals("scrape", toolCall.getToolName());
+ assertNotNull(toolCall.getParameters());
+
+ AgentTraceEvent artifact = trace.getEvents().get(2);
+ assertEquals("artifact.updated", artifact.getType());
+ assertNotNull(artifact.getArtifact());
+ assertEquals("art-1", artifact.getArtifact().getArtifactId());
+ assertEquals("snap-1", artifact.getArtifact().getSnapshotId());
+ assertEquals("created", artifact.getArtifact().getChange());
+ assertEquals(java.util.List.of("title"), artifact.getArtifact().getChangedFields());
+ assertEquals(1, artifact.getArtifact().getItemCount());
+ assertEquals("tc-1", artifact.getArtifact().getSourceToolCallId());
+
+ // liveView not requested: activeBrowserSessions may still parse if present
+ assertNotNull(trace.getActiveBrowserSessions());
+ assertEquals("sess-1", trace.getActiveBrowserSessions().get(0).getId());
+ assertEquals(1280, trace.getActiveBrowserSessions().get(0).getViewport().getWidth());
+ assertEquals(720, trace.getActiveBrowserSessions().get(0).getViewport().getHeight());
+ }
+
+ @Test
+ void testGetAgentTraceWithLiveView() {
+ AgentTraceResponse trace = client.getAgentTrace("job-123", true);
+
+ assertEquals("/v2/agent/job-123/trace?liveView=true", lastRequestPath.get(),
+ "Should append liveView=true query param");
+ assertTrue(trace.isSuccess());
+ assertNotNull(trace.getActiveBrowserSessions());
+ assertEquals(1, trace.getActiveBrowserSessions().size());
+ assertEquals("https://live.example.com/sess-1",
+ trace.getActiveBrowserSessions().get(0).getLiveViewUrl());
+ }
+
+ @Test
+ void testGetAgentSnapshot() {
+ AgentSnapshotResponse snapshot = client.getAgentSnapshot("job-123", "snap-1");
+
+ assertEquals("/v2/agent/job-123/snapshots/snap-1", lastRequestPath.get());
+ assertTrue(snapshot.isSuccess());
+ assertEquals("job-123", snapshot.getId());
+ assertEquals("snap-1", snapshot.getSnapshotId());
+ assertEquals("snapshot content here", snapshot.getSnapshot());
+ assertNull(snapshot.getError());
+ }
+}
diff --git a/apps/js-sdk/firecrawl/package.json b/apps/js-sdk/firecrawl/package.json
index 276ed946b..b75edc94b 100644
--- a/apps/js-sdk/firecrawl/package.json
+++ b/apps/js-sdk/firecrawl/package.json
@@ -1,6 +1,6 @@
{
"name": "@mendable/firecrawl-js",
- "version": "4.35.0",
+ "version": "4.36.0",
"description": "JavaScript SDK for the Firecrawl API: web scraping, crawling, web search, and scientific literature search over a research paper index of PubMed, bioRxiv, medRxiv and arXiv abstracts",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-effort-trace.unit.test.ts b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-effort-trace.unit.test.ts
new file mode 100644
index 000000000..2a2638e25
--- /dev/null
+++ b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-effort-trace.unit.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, test } from "@jest/globals";
+import {
+ startAgent,
+ getAgentTrace,
+ getAgentSnapshot,
+} from "../../../v2/methods/agent";
+import type { AgentTraceEvent } from "../../../v2/types";
+
+describe("v2.agent unit", () => {
+ test("startAgent forwards effort in request payload", async () => {
+ const post = jest.fn().mockResolvedValue({
+ status: 200,
+ data: { success: true, id: "agent-job" },
+ });
+
+ await startAgent({ post } as any, {
+ prompt: "Find the pricing",
+ effort: "high",
+ });
+
+ expect(post).toHaveBeenCalledWith("/v2/agent", {
+ prompt: "Find the pricing",
+ effort: "high",
+ });
+ });
+
+ test("startAgent omits effort when unset", async () => {
+ const post = jest.fn().mockResolvedValue({
+ status: 200,
+ data: { success: true, id: "agent-job" },
+ });
+
+ await startAgent({ post } as any, { prompt: "Find the pricing" });
+
+ expect(post).toHaveBeenCalledWith("/v2/agent", {
+ prompt: "Find the pricing",
+ });
+ });
+
+ test("getAgentTrace hits the trace endpoint and returns typed events", async () => {
+ const runStarted: AgentTraceEvent = {
+ schemaVersion: 1,
+ eventId: "018f3c5e-0000-7000-8000-000000000000",
+ runId: "018f3c5e-0000-7000-8000-000000000001",
+ occurredAt: "2026-08-26T12:00:00+00:00",
+ producerSequence: 1,
+ agent: {
+ id: "018f3c5e-0000-7000-8000-000000000002",
+ role: "orchestrator",
+ name: "main",
+ },
+ type: "run.started",
+ };
+ const artifactUpdated: AgentTraceEvent = {
+ schemaVersion: 1,
+ eventId: "018f3c5e-0000-7000-8000-000000000010",
+ runId: "018f3c5e-0000-7000-8000-000000000001",
+ occurredAt: "2026-08-26T12:00:01+00:00",
+ producerSequence: 2,
+ agent: {
+ id: "018f3c5e-0000-7000-8000-000000000002",
+ role: "orchestrator",
+ name: "main",
+ },
+ type: "artifact.updated",
+ artifact: {
+ kind: "json",
+ artifactId: "result",
+ snapshotId: "018f3c5e-0000-7000-8000-000000000003",
+ change: "partial",
+ },
+ };
+ const get = jest.fn().mockResolvedValue({
+ status: 200,
+ data: {
+ success: true,
+ id: "agent-job",
+ events: [runStarted, artifactUpdated],
+ creditsUsed: 5,
+ },
+ });
+
+ const trace = await getAgentTrace({ get } as any, "agent-job");
+
+ expect(get).toHaveBeenCalledWith("/v2/agent/agent-job/trace");
+ expect(trace.events).toHaveLength(2);
+ expect(trace.events![0].type).toBe("run.started");
+ expect(trace.events![1].type).toBe("artifact.updated");
+ if (trace.events![1].type === "artifact.updated") {
+ expect(trace.events![1].artifact.snapshotId).toBe(
+ "018f3c5e-0000-7000-8000-000000000003",
+ );
+ }
+ expect(trace.creditsUsed).toBe(5);
+ });
+
+ test("getAgentTrace appends liveView query param when requested", async () => {
+ const get = jest.fn().mockResolvedValue({
+ status: 200,
+ data: {
+ success: true,
+ id: "agent-job",
+ events: [],
+ creditsUsed: 0,
+ activeBrowserSessions: [
+ {
+ id: "sess-1",
+ liveViewUrl: "https://browser.example.com/sess-1",
+ viewport: { width: 1280, height: 720 },
+ },
+ ],
+ },
+ });
+
+ const trace = await getAgentTrace({ get } as any, "agent-job", {
+ liveView: true,
+ });
+
+ expect(get).toHaveBeenCalledWith("/v2/agent/agent-job/trace?liveView=true");
+ expect(trace.activeBrowserSessions).toHaveLength(1);
+ expect(trace.activeBrowserSessions![0].viewport.width).toBe(1280);
+ });
+
+ test("getAgentSnapshot hits the snapshot endpoint", async () => {
+ const get = jest.fn().mockResolvedValue({
+ status: 200,
+ data: {
+ success: true,
+ id: "agent-job",
+ snapshotId: "snap-1",
+ snapshot: '{"price": 42}',
+ },
+ });
+
+ const snapshot = await getAgentSnapshot({ get } as any, "agent-job", "snap-1");
+
+ expect(get).toHaveBeenCalledWith("/v2/agent/agent-job/snapshots/snap-1");
+ expect(snapshot.snapshot).toBe('{"price": 42}');
+ });
+});
diff --git a/apps/js-sdk/firecrawl/src/v2/client.ts b/apps/js-sdk/firecrawl/src/v2/client.ts
index ba6d6b245..e38659f51 100644
--- a/apps/js-sdk/firecrawl/src/v2/client.ts
+++ b/apps/js-sdk/firecrawl/src/v2/client.ts
@@ -26,7 +26,7 @@ import {
batchScrape as batchWaiter,
} from "./methods/batch";
import { startExtract, getExtractStatus, extract as extractWaiter } from "./methods/extract";
-import { startAgent, getAgentStatus, cancelAgent, agent as agentWaiter } from "./methods/agent";
+import { startAgent, getAgentStatus, getAgentTrace, getAgentSnapshot, cancelAgent, agent as agentWaiter } from "./methods/agent";
import {
browser as browserMethod,
browserExecute,
@@ -68,6 +68,8 @@ import type {
ExtractResponse,
AgentResponse,
AgentStatusResponse,
+ AgentTraceResponse,
+ AgentSnapshotResponse,
CrawlOptions,
BatchScrapeOptions,
PaginationConfig,
@@ -535,6 +537,22 @@ export class FirecrawlClient {
async cancelAgent(jobId: string): Promise<boolean> {
return cancelAgent(this.http, jobId);
}
+ /**
+ * Get the execution trace of an agent job (spark-2 runs only).
+ * @param jobId Agent job id.
+ * @param options.liveView Also include currently active browser sessions with live view URLs.
+ */
+ async getAgentTrace(jobId: string, options?: { liveView?: boolean }): Promise<AgentTraceResponse> {
+ return getAgentTrace(this.http, jobId, options);
+ }
+ /**
+ * Get the full content of an artifact snapshot referenced by a trace event.
+ * @param jobId Agent job id.
+ * @param snapshotId Snapshot id from an artifact.updated trace event.
+ */
+ async getAgentSnapshot(jobId: string, snapshotId: string): Promise<AgentSnapshotResponse> {
+ return getAgentSnapshot(this.http, jobId, snapshotId);
+ }
// Browser
/**
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/agent.ts b/apps/js-sdk/firecrawl/src/v2/methods/agent.ts
index aed8bcc22..1a2a116b7 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/agent.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/agent.ts
@@ -1,4 +1,4 @@
-import { type AgentResponse, type AgentStatusResponse, type AgentWebhookConfig, type AuditMetadata, type ThreatProtectionOptions } from "../types";
+import { type AgentEffort, type AgentResponse, type AgentSnapshotResponse, type AgentStatusResponse, type AgentTraceResponse, type AgentWebhookConfig, type AuditMetadata, type ThreatProtectionOptions } from "../types";
import { HttpClient } from "../utils/httpClient";
import { normalizeAxiosError, throwForBadResponse } from "../utils/errorHandler";
import { isZodSchema, zodSchemaToJsonSchema } from "../../utils/zodSchemaToJson";
@@ -13,6 +13,7 @@ function prepareAgentPayload(args: {
maxCredits?: number;
strictConstrainToURLs?: boolean;
model?: "spark-1-pro" | "spark-1-mini" | "spark-2";
+ effort?: AgentEffort;
webhook?: string | AgentWebhookConfig;
threatProtection?: ThreatProtectionOptions;
auditMetadata?: AuditMetadata;
@@ -28,6 +29,7 @@ function prepareAgentPayload(args: {
if (args.maxCredits !== null && args.maxCredits !== undefined) body.maxCredits = args.maxCredits;
if (args.strictConstrainToURLs !== null && args.strictConstrainToURLs !== undefined) body.strictConstrainToURLs = args.strictConstrainToURLs;
if (args.model !== null && args.model !== undefined) body.model = args.model;
+ if (args.effort !== null && args.effort !== undefined) body.effort = args.effort;
if (args.webhook != null) body.webhook = args.webhook;
if (args.threatProtection != null)
body.threatProtection = args.threatProtection;
@@ -84,6 +86,37 @@ export async function agent(
return waitAgent(http, jobId, args.pollInterval ?? 2, args.timeout);
}
+export async function getAgentTrace(
+ http: HttpClient,
+ jobId: string,
+ options?: { liveView?: boolean }
+): Promise<AgentTraceResponse> {
+ try {
+ const query = options?.liveView ? "?liveView=true" : "";
+ const res = await http.get<AgentTraceResponse>(`/v2/agent/${jobId}/trace${query}`);
+ if (res.status !== 200) throwForBadResponse(res, "agent trace");
+ return res.data;
+ } catch (err: any) {
+ if (err?.isAxiosError) return normalizeAxiosError(err, "agent trace");
+ throw err;
+ }
+}
+
+export async function getAgentSnapshot(
+ http: HttpClient,
+ jobId: string,
+ snapshotId: string
+): Promise<AgentSnapshotResponse> {
+ try {
+ const res = await http.get<AgentSnapshotResponse>(`/v2/agent/${jobId}/snapshots/${snapshotId}`);
+ if (res.status !== 200) throwForBadResponse(res, "agent snapshot");
+ return res.data;
+ } catch (err: any) {
+ if (err?.isAxiosError) return normalizeAxiosError(err, "agent snapshot");
+ throw err;
+ }
+}
+
export async function cancelAgent(http: HttpClient, jobId: string): Promise<boolean> {
try {
const res = await http.delete<{ success: boolean }>(`/v2/agent/${jobId}`);
diff --git a/apps/js-sdk/firecrawl/src/v2/types.ts b/apps/js-sdk/firecrawl/src/v2/types.ts
index 66c26c771..65a76f896 100644
--- a/apps/js-sdk/firecrawl/src/v2/types.ts
+++ b/apps/js-sdk/firecrawl/src/v2/types.ts
@@ -1328,10 +1328,174 @@ export interface AgentStatusResponse {
* names makes every future model a type error at the call site.
*/
model?: "spark-1-pro" | "spark-1-mini" | "spark-2" | (string & {});
+ /**
+ * Reasoning effort the job ran with. Only set for runs that specified it;
+ * older rows and default runs have no effort.
+ */
+ effort?: "low" | "medium" | "high";
expiresAt: string;
creditsUsed?: number;
}
+/** Reasoning effort for agent jobs. Every level runs spark-2. */
+export type AgentEffort = "low" | "medium" | "high";
+
+export type AgentTraceAgentRole = "orchestrator" | "subagent" | "browser" | "system";
+
+export interface AgentTraceAgentIdentity {
+ id: string;
+ role: AgentTraceAgentRole;
+ name: string;
+ parentId?: string;
+}
+
+export interface AgentTraceError {
+ code: "cancelled" | "credit_limit_reached" | "parent_finished" | "refused" | "internal";
+ source: "agent" | "tool" | "billing" | "system";
+ retryable: boolean;
+ message: string;
+}
+
+export interface AgentTraceArtifactChange {
+ kind: "json" | "markdown" | "html" | "screenshot" | "text";
+ artifactId: string;
+ path?: string;
+ /** Fetch the full content via getAgentSnapshot(jobId, snapshotId). */
+ snapshotId: string;
+ change: "init" | "partial" | "append" | "modify" | "update";
+ changedFields?: string[];
+ itemCount?: number;
+ sourceToolCallId?: string;
+}
+
+interface AgentTraceEventBase {
+ schemaVersion: 1;
+ eventId: string;
+ runId: string;
+ occurredAt: string;
+ producerSequence: number;
+ agent: AgentTraceAgentIdentity;
+}
+
+export interface AgentTraceRunStartedEvent extends AgentTraceEventBase {
+ type: "run.started";
+}
+
+export interface AgentTraceRunCancelRequestedEvent extends AgentTraceEventBase {
+ type: "run.cancel_requested";
+ reason: "user";
+}
+
+export interface AgentTraceRunFinishedEvent extends AgentTraceEventBase {
+ type: "run.finished";
+ outcome: "succeeded" | "failed" | "cancelled" | "refused" | "credit_limit_reached";
+ /** The canonical schema always writes this key (nullable), but older rows may omit it. */
+ error?: AgentTraceError | null;
+}
+
+export interface AgentTraceAgentStartedEvent extends AgentTraceEventBase {
+ type: "agent.started";
+}
+
+export interface AgentTraceAgentFinishedEvent extends AgentTraceEventBase {
+ type: "agent.finished";
+ outcome: "succeeded" | "failed" | "cancelled" | "refused";
+ durationMs: number;
+ /** The canonical schema always writes this key (nullable), but older rows may omit it. */
+ error?: AgentTraceError | null;
+}
+
+export interface AgentTraceBrowserSessionStartedEvent extends AgentTraceEventBase {
+ type: "browser.session.started";
+ sessionId: string;
+}
+
+export interface AgentTraceBrowserSessionFinishedEvent extends AgentTraceEventBase {
+ type: "browser.session.finished";
+ sessionId: string;
+ durationMs: number;
+}
+
+export interface AgentTraceProgressReportedEvent extends AgentTraceEventBase {
+ type: "progress.reported";
+ phase: "planning" | "working" | "finalizing";
+ message: string;
+}
+
+export interface AgentTraceReasoningSummaryEvent extends AgentTraceEventBase {
+ type: "reasoning.summary";
+ text: string;
+}
+
+export interface AgentTraceToolCallStartedEvent extends AgentTraceEventBase {
+ type: "tool_call.started";
+ toolCallId: string;
+ toolName: string;
+ parameters: unknown;
+}
+
+export interface AgentTraceToolCallFinishedEvent extends AgentTraceEventBase {
+ type: "tool_call.finished";
+ toolCallId: string;
+ toolName: string;
+ result: unknown;
+}
+
+export interface AgentTraceArtifactUpdatedEvent extends AgentTraceEventBase {
+ type: "artifact.updated";
+ artifact: AgentTraceArtifactChange;
+}
+
+export interface AgentTraceErrorOccurredEvent extends AgentTraceEventBase {
+ type: "error.occurred";
+ error: AgentTraceError;
+}
+
+/**
+ * One event in an agent job's trace. Mirrors the canonical event schema of
+ * the agent service (schemaVersion 1); `usage.recorded` events are withheld
+ * server-side and `agent.started` carries no model name.
+ */
+export type AgentTraceEvent =
+ | AgentTraceRunStartedEvent
+ | AgentTraceRunCancelRequestedEvent
+ | AgentTraceRunFinishedEvent
+ | AgentTraceAgentStartedEvent
+ | AgentTraceAgentFinishedEvent
+ | AgentTraceBrowserSessionStartedEvent
+ | AgentTraceBrowserSessionFinishedEvent
+ | AgentTraceProgressReportedEvent
+ | AgentTraceReasoningSummaryEvent
+ | AgentTraceToolCallStartedEvent
+ | AgentTraceToolCallFinishedEvent
+ | AgentTraceArtifactUpdatedEvent
+ | AgentTraceErrorOccurredEvent;
+
+export interface AgentTraceActiveBrowserSession {
+ id: string;
+ liveViewUrl: string;
+ viewport: { width: number; height: number };
+}
+
+export interface AgentTraceResponse {
+ success: boolean;
+ id?: string;
+ events?: AgentTraceEvent[];
+ creditsUsed?: number;
+ /** Present only when the trace was requested with liveView: true. */
+ activeBrowserSessions?: AgentTraceActiveBrowserSession[];
+ error?: string;
+}
+
+export interface AgentSnapshotResponse {
+ success: boolean;
+ id?: string;
+ snapshotId?: string;
+ /** Full artifact content as a JSON/string blob. */
+ snapshot?: string;
+ error?: string;
+}
+
export interface AgentOptions {
model: "FIRE-1" | "v3-beta";
}
diff --git a/apps/php-sdk/CHANGELOG.md b/apps/php-sdk/CHANGELOG.md
index 8ff0f2778..57be4dbbe 100644
--- a/apps/php-sdk/CHANGELOG.md
+++ b/apps/php-sdk/CHANGELOG.md
@@ -5,6 +5,18 @@ All notable changes to the Firecrawl PHP SDK will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.14.0] - 2026-08-26
+
+### Added
+- Agent `effort` option ("low", "medium", "high") on `AgentOptions` to set the
+ reasoning budget (every level runs spark-2), and `AgentStatusResponse::getEffort()`
+ exposing the effort a job ran with.
+- `getAgentTrace()` returning an `AgentTraceResponse` with typed `AgentTraceEvent`
+ models for every trace event kind, plus `activeBrowserSessions` with live view
+ URLs when the `liveView` query parameter is requested.
+- `getAgentSnapshot()` returning an `AgentSnapshotResponse` with the snapshot
+ content of an artifact produced by an agent task.
+
## [1.13.0] - 2026-08-21
### Added
diff --git a/apps/php-sdk/src/Client/FirecrawlClient.php b/apps/php-sdk/src/Client/FirecrawlClient.php
index 9437701d3..c03d77e18 100644
--- a/apps/php-sdk/src/Client/FirecrawlClient.php
+++ b/apps/php-sdk/src/Client/FirecrawlClient.php
@@ -9,7 +9,9 @@ use Firecrawl\Version;
use Firecrawl\Exceptions\JobTimeoutException;
use Firecrawl\Models\AgentOptions;
use Firecrawl\Models\AgentResponse;
+use Firecrawl\Models\AgentSnapshotResponse;
use Firecrawl\Models\AgentStatusResponse;
+use Firecrawl\Models\AgentTraceResponse;
use Firecrawl\Models\BatchScrapeJob;
use Firecrawl\Models\BatchScrapeOptions;
use Firecrawl\Models\BatchScrapeResponse;
@@ -633,6 +635,31 @@ final class FirecrawlClient
return $this->http->delete("/v2/agent/{$jobId}");
}
+ /**
+ * Get the execution trace of an agent task.
+ *
+ * When $liveView is true, the response also carries the run's currently
+ * active browser sessions with live view URLs.
+ */
+ public function getAgentTrace(string $jobId, bool $liveView = false): AgentTraceResponse
+ {
+ return AgentTraceResponse::fromArray(
+ $this->http->get("/v2/agent/{$jobId}/trace" . $this->query([
+ 'liveView' => $liveView ? 'true' : null,
+ ])),
+ );
+ }
+
+ /**
+ * Get a snapshot of an artifact produced by an agent task.
+ */
+ public function getAgentSnapshot(string $jobId, string $snapshotId): AgentSnapshotResponse
+ {
+ return AgentSnapshotResponse::fromArray(
+ $this->http->get("/v2/agent/{$jobId}/snapshots/{$snapshotId}"),
+ );
+ }
+
// ================================================================
// BROWSER
// ================================================================
diff --git a/apps/php-sdk/src/Models/AgentOptions.php b/apps/php-sdk/src/Models/AgentOptions.php
index 439ea2c8c..13a336cfe 100644
--- a/apps/php-sdk/src/Models/AgentOptions.php
+++ b/apps/php-sdk/src/Models/AgentOptions.php
@@ -9,6 +9,8 @@ final class AgentOptions
/**
* @param list<string>|null $urls
* @param array<string, mixed>|null $schema
+ * @param string|null $effort Reasoning budget: "low", "medium",
+ * or "high". Every level runs spark-2.
* @param AuditMetadata|null $auditMetadata
*/
private function __construct(
@@ -19,6 +21,7 @@ final class AgentOptions
private readonly ?int $maxCredits = null,
private readonly ?bool $strictConstrainToURLs = null,
private readonly ?string $model = null,
+ private readonly ?string $effort = null,
private readonly ?WebhookConfig $webhook = null,
private readonly ?AuditMetadata $auditMetadata = null,
) {}
@@ -26,6 +29,8 @@ final class AgentOptions
/**
* @param list<string>|null $urls
* @param array<string, mixed>|null $schema
+ * @param string|null $effort Reasoning budget: "low", "medium",
+ * or "high". Every level runs spark-2.
* @param AuditMetadata|null $auditMetadata
*/
public static function with(
@@ -36,12 +41,13 @@ final class AgentOptions
?int $maxCredits = null,
?bool $strictConstrainToURLs = null,
?string $model = null,
+ ?string $effort = null,
?WebhookConfig $webhook = null,
?AuditMetadata $auditMetadata = null,
): self {
return new self(
$urls, $prompt, $schema, $integration,
- $maxCredits, $strictConstrainToURLs, $model, $webhook, $auditMetadata,
+ $maxCredits, $strictConstrainToURLs, $model, $effort, $webhook, $auditMetadata,
);
}
@@ -56,6 +62,7 @@ final class AgentOptions
'maxCredits' => $this->maxCredits,
'strictConstrainToURLs' => $this->strictConstrainToURLs,
'model' => $this->model,
+ 'effort' => $this->effort,
'webhook' => $this->webhook?->toArray(),
'auditMetadata' => $this->auditMetadata?->toArray(),
];
diff --git a/apps/php-sdk/src/Models/AgentSnapshotResponse.php b/apps/php-sdk/src/Models/AgentSnapshotResponse.php
new file mode 100644
index 000000000..3471b4b5c
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentSnapshotResponse.php
@@ -0,0 +1,53 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+final class AgentSnapshotResponse
+{
+ public function __construct(
+ private readonly bool $success = false,
+ private readonly ?string $id = null,
+ private readonly ?string $snapshotId = null,
+ private readonly ?string $snapshot = null,
+ private readonly ?string $error = null,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ return new self(
+ success: (bool) ($data['success'] ?? false),
+ id: $data['id'] ?? null,
+ snapshotId: $data['snapshotId'] ?? null,
+ snapshot: isset($data['snapshot']) ? (string) $data['snapshot'] : null,
+ error: $data['error'] ?? null,
+ );
+ }
+
+ public function isSuccess(): bool
+ {
+ return $this->success;
+ }
+
+ public function getId(): ?string
+ {
+ return $this->id;
+ }
+
+ public function getSnapshotId(): ?string
+ {
+ return $this->snapshotId;
+ }
+
+ public function getSnapshot(): ?string
+ {
+ return $this->snapshot;
+ }
+
+ public function getError(): ?string
+ {
+ return $this->error;
+ }
+}
diff --git a/apps/php-sdk/src/Models/AgentStatusResponse.php b/apps/php-sdk/src/Models/AgentStatusResponse.php
index bf5850f82..0209a3714 100644
--- a/apps/php-sdk/src/Models/AgentStatusResponse.php
+++ b/apps/php-sdk/src/Models/AgentStatusResponse.php
@@ -12,6 +12,7 @@ final class AgentStatusResponse
private readonly ?string $error = null,
private readonly mixed $data = null,
private readonly ?string $model = null,
+ private readonly ?string $effort = null,
private readonly ?string $expiresAt = null,
private readonly ?int $creditsUsed = null,
) {}
@@ -25,6 +26,7 @@ final class AgentStatusResponse
error: $raw['error'] ?? null,
data: $raw['data'] ?? null,
model: $raw['model'] ?? null,
+ effort: $raw['effort'] ?? null,
expiresAt: $raw['expiresAt'] ?? null,
creditsUsed: isset($raw['creditsUsed']) ? (int) $raw['creditsUsed'] : null,
);
@@ -60,6 +62,15 @@ final class AgentStatusResponse
return $this->model;
}
+ /**
+ * The effort ("low", "medium", or "high") the job ran with. Only present
+ * for runs that specified one.
+ */
+ public function getEffort(): ?string
+ {
+ return $this->effort;
+ }
+
public function getExpiresAt(): ?string
{
return $this->expiresAt;
diff --git a/apps/php-sdk/src/Models/AgentTraceActiveBrowserSession.php b/apps/php-sdk/src/Models/AgentTraceActiveBrowserSession.php
new file mode 100644
index 000000000..4f2c2fae1
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentTraceActiveBrowserSession.php
@@ -0,0 +1,41 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+final class AgentTraceActiveBrowserSession
+{
+ public function __construct(
+ private readonly ?string $id = null,
+ private readonly ?string $liveViewUrl = null,
+ private readonly ?AgentTraceViewport $viewport = null,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ return new self(
+ id: $data['id'] ?? null,
+ liveViewUrl: $data['liveViewUrl'] ?? null,
+ viewport: isset($data['viewport']) && is_array($data['viewport'])
+ ? AgentTraceViewport::fromArray($data['viewport'])
+ : null,
+ );
+ }
+
+ public function getId(): ?string
+ {
+ return $this->id;
+ }
+
+ public function getLiveViewUrl(): ?string
+ {
+ return $this->liveViewUrl;
+ }
+
+ public function getViewport(): ?AgentTraceViewport
+ {
+ return $this->viewport;
+ }
+}
diff --git a/apps/php-sdk/src/Models/AgentTraceAgentIdentity.php b/apps/php-sdk/src/Models/AgentTraceAgentIdentity.php
new file mode 100644
index 000000000..fc959f4b6
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentTraceAgentIdentity.php
@@ -0,0 +1,46 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+final class AgentTraceAgentIdentity
+{
+ public function __construct(
+ private readonly ?string $id = null,
+ private readonly ?string $role = null,
+ private readonly ?string $name = null,
+ private readonly ?string $parentId = null,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ return new self(
+ id: $data['id'] ?? null,
+ role: $data['role'] ?? null,
+ name: $data['name'] ?? null,
+ parentId: $data['parentId'] ?? null,
+ );
+ }
+
+ public function getId(): ?string
+ {
+ return $this->id;
+ }
+
+ public function getRole(): ?string
+ {
+ return $this->role;
+ }
+
+ public function getName(): ?string
+ {
+ return $this->name;
+ }
+
+ public function getParentId(): ?string
+ {
+ return $this->parentId;
+ }
+}
diff --git a/apps/php-sdk/src/Models/AgentTraceArtifactChange.php b/apps/php-sdk/src/Models/AgentTraceArtifactChange.php
new file mode 100644
index 000000000..5fd0d3932
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentTraceArtifactChange.php
@@ -0,0 +1,78 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+final class AgentTraceArtifactChange
+{
+ /** @param list<string>|null $changedFields */
+ public function __construct(
+ private readonly ?string $kind = null,
+ private readonly ?string $artifactId = null,
+ private readonly ?string $path = null,
+ private readonly ?string $snapshotId = null,
+ private readonly ?string $change = null,
+ private readonly ?array $changedFields = null,
+ private readonly ?int $itemCount = null,
+ private readonly ?string $sourceToolCallId = null,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ return new self(
+ kind: $data['kind'] ?? null,
+ artifactId: $data['artifactId'] ?? null,
+ path: $data['path'] ?? null,
+ snapshotId: $data['snapshotId'] ?? null,
+ change: $data['change'] ?? null,
+ changedFields: isset($data['changedFields']) && is_array($data['changedFields'])
+ ? array_values($data['changedFields'])
+ : null,
+ itemCount: isset($data['itemCount']) ? (int) $data['itemCount'] : null,
+ sourceToolCallId: $data['sourceToolCallId'] ?? null,
+ );
+ }
+
+ public function getKind(): ?string
+ {
+ return $this->kind;
+ }
+
+ public function getArtifactId(): ?string
+ {
+ return $this->artifactId;
+ }
+
+ public function getPath(): ?string
+ {
+ return $this->path;
+ }
+
+ public function getSnapshotId(): ?string
+ {
+ return $this->snapshotId;
+ }
+
+ public function getChange(): ?string
+ {
+ return $this->change;
+ }
+
+ /** @return list<string>|null */
+ public function getChangedFields(): ?array
+ {
+ return $this->changedFields;
+ }
+
+ public function getItemCount(): ?int
+ {
+ return $this->itemCount;
+ }
+
+ public function getSourceToolCallId(): ?string
+ {
+ return $this->sourceToolCallId;
+ }
+}
diff --git a/apps/php-sdk/src/Models/AgentTraceError.php b/apps/php-sdk/src/Models/AgentTraceError.php
new file mode 100644
index 000000000..a8091f958
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentTraceError.php
@@ -0,0 +1,46 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+final class AgentTraceError
+{
+ public function __construct(
+ private readonly ?string $code = null,
+ private readonly ?string $source = null,
+ private readonly bool $retryable = false,
+ private readonly ?string $message = null,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ return new self(
+ code: $data['code'] ?? null,
+ source: $data['source'] ?? null,
+ retryable: (bool) ($data['retryable'] ?? false),
+ message: $data['message'] ?? null,
+ );
+ }
+
+ public function getCode(): ?string
+ {
+ return $this->code;
+ }
+
+ public function getSource(): ?string
+ {
+ return $this->source;
+ }
+
+ public function isRetryable(): bool
+ {
+ return $this->retryable;
+ }
+
+ public function getMessage(): ?string
+ {
+ return $this->message;
+ }
+}
diff --git a/apps/php-sdk/src/Models/AgentTraceEvent.php b/apps/php-sdk/src/Models/AgentTraceEvent.php
new file mode 100644
index 000000000..4f3b6d6c1
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentTraceEvent.php
@@ -0,0 +1,169 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+/**
+ * A single agent trace event. One model covers every event `type`
+ * (run.started, tool_call.finished, artifact.updated, ...); fields that do
+ * not apply to a given type stay null.
+ */
+final class AgentTraceEvent
+{
+ public function __construct(
+ private readonly ?string $type = null,
+ private readonly ?int $schemaVersion = null,
+ private readonly ?string $eventId = null,
+ private readonly ?string $runId = null,
+ private readonly ?string $occurredAt = null,
+ private readonly ?int $producerSequence = null,
+ private readonly ?AgentTraceAgentIdentity $agent = null,
+ private readonly ?string $reason = null,
+ private readonly ?string $outcome = null,
+ private readonly ?AgentTraceError $error = null,
+ private readonly ?int $durationMs = null,
+ private readonly ?string $sessionId = null,
+ private readonly ?string $phase = null,
+ private readonly ?string $message = null,
+ private readonly ?string $text = null,
+ private readonly ?string $toolCallId = null,
+ private readonly ?string $toolName = null,
+ private readonly mixed $parameters = null,
+ private readonly mixed $result = null,
+ private readonly ?AgentTraceArtifactChange $artifact = null,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ return new self(
+ type: $data['type'] ?? null,
+ schemaVersion: isset($data['schemaVersion']) ? (int) $data['schemaVersion'] : null,
+ eventId: $data['eventId'] ?? null,
+ runId: $data['runId'] ?? null,
+ occurredAt: $data['occurredAt'] ?? null,
+ producerSequence: isset($data['producerSequence']) ? (int) $data['producerSequence'] : null,
+ agent: isset($data['agent']) && is_array($data['agent'])
+ ? AgentTraceAgentIdentity::fromArray($data['agent'])
+ : null,
+ reason: $data['reason'] ?? null,
+ outcome: $data['outcome'] ?? null,
+ error: isset($data['error']) && is_array($data['error'])
+ ? AgentTraceError::fromArray($data['error'])
+ : null,
+ durationMs: isset($data['durationMs']) ? (int) $data['durationMs'] : null,
+ sessionId: $data['sessionId'] ?? null,
+ phase: $data['phase'] ?? null,
+ message: $data['message'] ?? null,
+ text: $data['text'] ?? null,
+ toolCallId: $data['toolCallId'] ?? null,
+ toolName: $data['toolName'] ?? null,
+ parameters: $data['parameters'] ?? null,
+ result: $data['result'] ?? null,
+ artifact: isset($data['artifact']) && is_array($data['artifact'])
+ ? AgentTraceArtifactChange::fromArray($data['artifact'])
+ : null,
+ );
+ }
+
+ public function getType(): ?string
+ {
+ return $this->type;
+ }
+
+ public function getSchemaVersion(): ?int
+ {
+ return $this->schemaVersion;
+ }
+
+ public function getEventId(): ?string
+ {
+ return $this->eventId;
+ }
+
+ public function getRunId(): ?string
+ {
+ return $this->runId;
+ }
+
+ public function getOccurredAt(): ?string
+ {
+ return $this->occurredAt;
+ }
+
+ public function getProducerSequence(): ?int
+ {
+ return $this->producerSequence;
+ }
+
+ public function getAgent(): ?AgentTraceAgentIdentity
+ {
+ return $this->agent;
+ }
+
+ public function getReason(): ?string
+ {
+ return $this->reason;
+ }
+
+ public function getOutcome(): ?string
+ {
+ return $this->outcome;
+ }
+
+ public function getError(): ?AgentTraceError
+ {
+ return $this->error;
+ }
+
+ public function getDurationMs(): ?int
+ {
+ return $this->durationMs;
+ }
+
+ public function getSessionId(): ?string
+ {
+ return $this->sessionId;
+ }
+
+ public function getPhase(): ?string
+ {
+ return $this->phase;
+ }
+
+ public function getMessage(): ?string
+ {
+ return $this->message;
+ }
+
+ public function getText(): ?string
+ {
+ return $this->text;
+ }
+
+ public function getToolCallId(): ?string
+ {
+ return $this->toolCallId;
+ }
+
+ public function getToolName(): ?string
+ {
+ return $this->toolName;
+ }
+
+ public function getParameters(): mixed
+ {
+ return $this->parameters;
+ }
+
+ public function getResult(): mixed
+ {
+ return $this->result;
+ }
+
+ public function getArtifact(): ?AgentTraceArtifactChange
+ {
+ return $this->artifact;
+ }
+}
diff --git a/apps/php-sdk/src/Models/AgentTraceResponse.php b/apps/php-sdk/src/Models/AgentTraceResponse.php
new file mode 100644
index 000000000..5bfc0453b
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentTraceResponse.php
@@ -0,0 +1,84 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+final class AgentTraceResponse
+{
+ /**
+ * @param list<AgentTraceEvent> $events
+ * @param list<AgentTraceActiveBrowserSession> $activeBrowserSessions
+ */
+ public function __construct(
+ private readonly bool $success = false,
+ private readonly ?string $id = null,
+ private readonly array $events = [],
+ private readonly ?int $creditsUsed = null,
+ private readonly array $activeBrowserSessions = [],
+ private readonly ?string $error = null,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ $events = [];
+ if (isset($data['events']) && is_array($data['events'])) {
+ foreach ($data['events'] as $event) {
+ if (is_array($event)) {
+ $events[] = AgentTraceEvent::fromArray($event);
+ }
+ }
+ }
+
+ $activeBrowserSessions = [];
+ if (isset($data['activeBrowserSessions']) && is_array($data['activeBrowserSessions'])) {
+ foreach ($data['activeBrowserSessions'] as $session) {
+ if (is_array($session)) {
+ $activeBrowserSessions[] = AgentTraceActiveBrowserSession::fromArray($session);
+ }
+ }
+ }
+
+ return new self(
+ success: (bool) ($data['success'] ?? false),
+ id: $data['id'] ?? null,
+ events: $events,
+ creditsUsed: isset($data['creditsUsed']) ? (int) $data['creditsUsed'] : null,
+ activeBrowserSessions: $activeBrowserSessions,
+ error: $data['error'] ?? null,
+ );
+ }
+
+ public function isSuccess(): bool
+ {
+ return $this->success;
+ }
+
+ public function getId(): ?string
+ {
+ return $this->id;
+ }
+
+ /** @return list<AgentTraceEvent> */
+ public function getEvents(): array
+ {
+ return $this->events;
+ }
+
+ public function getCreditsUsed(): ?int
+ {
+ return $this->creditsUsed;
+ }
+
+ /** @return list<AgentTraceActiveBrowserSession> */
+ public function getActiveBrowserSessions(): array
+ {
+ return $this->activeBrowserSessions;
+ }
+
+ public function getError(): ?string
+ {
+ return $this->error;
+ }
+}
diff --git a/apps/php-sdk/src/Models/AgentTraceViewport.php b/apps/php-sdk/src/Models/AgentTraceViewport.php
new file mode 100644
index 000000000..1cb6e3d00
--- /dev/null
+++ b/apps/php-sdk/src/Models/AgentTraceViewport.php
@@ -0,0 +1,32 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Firecrawl\Models;
+
+final class AgentTraceViewport
+{
+ public function __construct(
+ private readonly int $width = 0,
+ private readonly int $height = 0,
+ ) {}
+
+ /** @param array<string, mixed> $data */
+ public static function fromArray(array $data): self
+ {
+ return new self(
+ width: (int) ($data['width'] ?? 0),
+ height: (int) ($data['height'] ?? 0),
+ );
+ }
+
+ public function getWidth(): int
+ {
+ return $this->width;
+ }
+
+ public function getHeight(): int
+ {
+ return $this->height;
+ }
+}
diff --git a/apps/php-sdk/src/Version.php b/apps/php-sdk/src/Version.php
index 82890da06..90a3898fc 100644
--- a/apps/php-sdk/src/Version.php
+++ b/apps/php-sdk/src/Version.php
@@ -6,5 +6,5 @@ namespace Firecrawl;
final class Version
{
- public const SDK_VERSION = '1.13.0';
+ public const SDK_VERSION = '1.14.0';
}
diff --git a/apps/php-sdk/tests/Unit/AgentTest.php b/apps/php-sdk/tests/Unit/AgentTest.php
new file mode 100644
index 000000000..6fb29798a
--- /dev/null
+++ b/apps/php-sdk/tests/Unit/AgentTest.php
@@ -0,0 +1,257 @@
+<?php
+
+declare(strict_types=1);
+
+use Firecrawl\Exceptions\FirecrawlException;
+use Firecrawl\Models\AgentOptions;
+use Firecrawl\Models\AgentStatusResponse;
+use GuzzleHttp\Psr7\Response;
+
+it('sends the effort parameter when starting an agent', function (): void {
+ $history = new ArrayObject();
+ $client = fakeFirecrawlClient([
+ new Response(200, [], json_encode(['success' => true, 'id' => 'agent-123'])),
+ ], $history);
+
+ $response = $client->startAgent(AgentOptions::with(
+ prompt: 'find pricing',
+ effort: 'high',
+ ));
+
+ expect($response->isSuccess())->toBeTrue();
+ expect($response->getId())->toBe('agent-123');
+
+ $request = $history[0]['request'];
+ expect($request->getUri()->getPath())->toBe('/v2/agent');
+
+ $body = json_decode((string) $request->getBody(), true);
+ expect($body['prompt'])->toBe('find pricing');
+ expect($body['effort'])->toBe('high');
+});
+
+it('omits the effort parameter when not set', function (): void {
+ $history = new ArrayObject();
+ $client = fakeFirecrawlClient([
+ new Response(200, [], json_encode(['success' => true, 'id' => 'agent-123'])),
+ ], $history);
+
+ $client->startAgent(AgentOptions::with(prompt: 'find pricing', model: 'spark-2'));
+
+ $body = json_decode((string) $history[0]['request']->getBody(), true);
+ expect($body)->not->toHaveKey('effort');
+ expect($body['model'])->toBe('spark-2');
+});
+
+it('hydrates the effort on AgentStatusResponse', function (): void {
+ $withEffort = AgentStatusResponse::fromArray([
+ 'success' => true,
+ 'status' => 'completed',
+ 'model' => 'spark-2',
+ 'effort' => 'medium',
+ 'expiresAt' => '2026-09-01T00:00:00Z',
+ ]);
+
+ expect($withEffort->getEffort())->toBe('medium');
+ expect($withEffort->getModel())->toBe('spark-2');
+
+ $withoutEffort = AgentStatusResponse::fromArray([
+ 'success' => true,
+ 'status' => 'completed',
+ ]);
+
+ expect($withoutEffort->getEffort())->toBeNull();
+});
+
+it('parses agent trace events and sends the liveView query param', function (): void {
+ $history = new ArrayObject();
+ $client = fakeFirecrawlClient([
+ new Response(200, [], json_encode([
+ 'success' => true,
+ 'id' => 'agent-123',
+ 'events' => [
+ [
+ 'type' => 'run.started',
+ 'schemaVersion' => 1,
+ 'eventId' => 'evt-1',
+ 'runId' => 'agent-123',
+ 'occurredAt' => '2026-08-26T10:00:00Z',
+ 'producerSequence' => 1,
+ 'agent' => ['id' => 'agent-root', 'role' => 'root', 'name' => 'root', 'parentId' => null],
+ ],
+ [
+ 'type' => 'tool_call.started',
+ 'schemaVersion' => 1,
+ 'eventId' => 'evt-2',
+ 'runId' => 'agent-123',
+ 'occurredAt' => '2026-08-26T10:00:01Z',
+ 'producerSequence' => 2,
+ 'agent' => ['id' => 'agent-root', 'role' => 'root', 'name' => 'root'],
+ 'toolCallId' => 'call-1',
+ 'toolName' => 'scrape',
+ 'parameters' => ['url' => 'https://example.com'],
+ ],
+ [
+ 'type' => 'artifact.updated',
+ 'schemaVersion' => 1,
+ 'eventId' => 'evt-3',
+ 'runId' => 'agent-123',
+ 'occurredAt' => '2026-08-26T10:00:02Z',
+ 'producerSequence' => 3,
+ 'agent' => ['id' => 'agent-root', 'role' => 'root', 'name' => 'root'],
+ 'artifact' => [
+ 'kind' => 'table',
+ 'artifactId' => 'art-1',
+ 'path' => 'pricing',
+ 'snapshotId' => 'snap-1',
+ 'change' => 'rows_added',
+ 'changedFields' => ['price'],
+ 'itemCount' => 3,
+ 'sourceToolCallId' => 'call-1',
+ ],
+ ],
+ [
+ 'type' => 'error.occurred',
+ 'schemaVersion' => 1,
+ 'eventId' => 'evt-4',
+ 'runId' => 'agent-123',
+ 'occurredAt' => '2026-08-26T10:00:03Z',
+ 'producerSequence' => 4,
+ 'agent' => ['id' => 'agent-root', 'role' => 'root', 'name' => 'root'],
+ 'error' => [
+ 'code' => 'SCRAPE_FAILED',
+ 'source' => 'tool',
+ 'retryable' => true,
+ 'message' => 'scrape timed out',
+ ],
+ ],
+ ],
+ 'creditsUsed' => 5,
+ 'activeBrowserSessions' => [
+ [
+ 'id' => 'session-1',
+ 'liveViewUrl' => 'https://liveview.firecrawl.dev/session-1',
+ 'viewport' => ['width' => 1280, 'height' => 720],
+ ],
+ ],
+ ])),
+ ], $history);
+
+ $trace = $client->getAgentTrace('agent-123', liveView: true);
+
+ $request = $history[0]['request'];
+ expect($request->getMethod())->toBe('GET');
+ expect($request->getUri()->getPath())->toBe('/v2/agent/agent-123/trace');
+ expect($request->getUri()->getQuery())->toBe('liveView=true');
+
+ expect($trace->isSuccess())->toBeTrue();
+ expect($trace->getId())->toBe('agent-123');
+ expect($trace->getCreditsUsed())->toBe(5);
+ expect($trace->getEvents())->toHaveCount(4);
+
+ $started = $trace->getEvents()[0];
+ expect($started->getType())->toBe('run.started');
+ expect($started->getSchemaVersion())->toBe(1);
+ expect($started->getEventId())->toBe('evt-1');
+ expect($started->getRunId())->toBe('agent-123');
+ expect($started->getOccurredAt())->toBe('2026-08-26T10:00:00Z');
+ expect($started->getProducerSequence())->toBe(1);
+ expect($started->getAgent()->getId())->toBe('agent-root');
+ expect($started->getAgent()->getRole())->toBe('root');
+ expect($started->getAgent()->getParentId())->toBeNull();
+ expect($started->getError())->toBeNull();
+ expect($started->getArtifact())->toBeNull();
+
+ $toolCall = $trace->getEvents()[1];
+ expect($toolCall->getType())->toBe('tool_call.started');
+ expect($toolCall->getToolCallId())->toBe('call-1');
+ expect($toolCall->getToolName())->toBe('scrape');
+ expect($toolCall->getParameters())->toBe(['url' => 'https://example.com']);
+ expect($toolCall->getResult())->toBeNull();
+
+ $artifact = $trace->getEvents()[2]->getArtifact();
+ expect($artifact->getKind())->toBe('table');
+ expect($artifact->getArtifactId())->toBe('art-1');
+ expect($artifact->getPath())->toBe('pricing');
+ expect($artifact->getSnapshotId())->toBe('snap-1');
+ expect($artifact->getChange())->toBe('rows_added');
+ expect($artifact->getChangedFields())->toBe(['price']);
+ expect($artifact->getItemCount())->toBe(3);
+ expect($artifact->getSourceToolCallId())->toBe('call-1');
+
+ $error = $trace->getEvents()[3]->getError();
+ expect($error->getCode())->toBe('SCRAPE_FAILED');
+ expect($error->getSource())->toBe('tool');
+ expect($error->isRetryable())->toBeTrue();
+ expect($error->getMessage())->toBe('scrape timed out');
+
+ $sessions = $trace->getActiveBrowserSessions();
+ expect($sessions)->toHaveCount(1);
+ expect($sessions[0]->getId())->toBe('session-1');
+ expect($sessions[0]->getLiveViewUrl())->toBe('https://liveview.firecrawl.dev/session-1');
+ expect($sessions[0]->getViewport()->getWidth())->toBe(1280);
+ expect($sessions[0]->getViewport()->getHeight())->toBe(720);
+});
+
+it('omits the liveView query param by default', function (): void {
+ $history = new ArrayObject();
+ $client = fakeFirecrawlClient([
+ new Response(200, [], json_encode([
+ 'success' => true,
+ 'id' => 'agent-123',
+ 'events' => [],
+ 'creditsUsed' => 0,
+ ])),
+ ], $history);
+
+ $trace = $client->getAgentTrace('agent-123');
+
+ expect($history[0]['request']->getUri()->getQuery())->toBe('');
+ expect($trace->getEvents())->toBe([]);
+ expect($trace->getActiveBrowserSessions())->toBe([]);
+});
+
+it('surfaces agent trace errors', function (): void {
+ $client = fakeFirecrawlClient([
+ new Response(404, [], json_encode([
+ 'success' => false,
+ 'error' => 'Agent job not found',
+ ])),
+ ]);
+
+ $client->getAgentTrace('agent-missing');
+})->throws(FirecrawlException::class, 'Agent job not found');
+
+it('parses an agent snapshot', function (): void {
+ $history = new ArrayObject();
+ $client = fakeFirecrawlClient([
+ new Response(200, [], json_encode([
+ 'success' => true,
+ 'id' => 'agent-123',
+ 'snapshotId' => 'snap-1',
+ 'snapshot' => '[{"price": "$10"}]',
+ ])),
+ ], $history);
+
+ $snapshot = $client->getAgentSnapshot('agent-123', 'snap-1');
+
+ $request = $history[0]['request'];
+ expect($request->getMethod())->toBe('GET');
+ expect($request->getUri()->getPath())->toBe('/v2/agent/agent-123/snapshots/snap-1');
+
+ expect($snapshot->isSuccess())->toBeTrue();
+ expect($snapshot->getId())->toBe('agent-123');
+ expect($snapshot->getSnapshotId())->toBe('snap-1');
+ expect($snapshot->getSnapshot())->toBe('[{"price": "$10"}]');
+ expect($snapshot->getError())->toBeNull();
+});
+
+it('surfaces agent snapshot errors', function (): void {
+ $client = fakeFirecrawlClient([
+ new Response(404, [], json_encode([
+ 'success' => false,
+ 'error' => 'Agent job not found',
+ ])),
+ ]);
+
+ $client->getAgentSnapshot('agent-missing', 'snap-1');
+})->throws(FirecrawlException::class, 'Agent job not found');
diff --git a/apps/python-sdk/firecrawl/__init__.py b/apps/python-sdk/firecrawl/__init__.py
index ef319169f..c841a54f7 100644
--- a/apps/python-sdk/firecrawl/__init__.py
+++ b/apps/python-sdk/firecrawl/__init__.py
@@ -18,7 +18,7 @@ from .v1 import (
V1ChangeTrackingOptions,
)
-__version__ = "4.38.0"
+__version__ = "4.39.0"
# Define the logger for the Firecrawl project
logger: logging.Logger = logging.getLogger("firecrawl")
diff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_request_preparation.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_request_preparation.py
index 1dcdcc616..3c58b1c3a 100644
--- a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_request_preparation.py
+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_request_preparation.py
@@ -368,3 +368,176 @@ class TestAgentResponseParsing:
)
assert response.model == "spark-3"
+
+
+class TestAgentEffort:
+ """Unit tests for the agent effort parameter."""
+
+ @pytest.mark.parametrize("effort", ["low", "medium", "high"])
+ def test_effort_forwarded_verbatim(self, effort):
+ """Every documented effort level reaches the request body."""
+ data = _prepare_agent_request(None, prompt="Effort test", effort=effort)
+
+ assert data["effort"] == effort
+
+ def test_effort_omitted_when_unset(self):
+ data = _prepare_agent_request(None, prompt="Effort test")
+
+ assert "effort" not in data
+
+ def test_status_payload_parses_effort(self):
+ """The status response carries the effort the run used."""
+ response = AgentResponse(
+ **{
+ "success": True,
+ "id": "job-1",
+ "status": "completed",
+ "model": "spark-2",
+ "effort": "high",
+ }
+ )
+
+ assert response.effort == "high"
+
+
+class TestAgentTraceAndSnapshotParsing:
+ """Unit tests for parsing agent trace and snapshot payloads."""
+
+ BASE_EVENT = {
+ "schemaVersion": 1,
+ "eventId": "018f3c5e-0000-7000-8000-000000000000",
+ "runId": "018f3c5e-0000-7000-8000-000000000001",
+ "occurredAt": "2026-08-26T12:00:00+00:00",
+ "producerSequence": 1,
+ "agent": {
+ "id": "018f3c5e-0000-7000-8000-000000000002",
+ "role": "orchestrator",
+ "name": "main",
+ },
+ }
+
+ def test_trace_parses_representative_events(self):
+ from firecrawl.v2.types import AgentTraceResponse
+
+ events = [
+ {"type": "run.started"},
+ {"type": "run.cancel_requested", "reason": "user"},
+ {
+ "type": "run.finished",
+ "outcome": "credit_limit_reached",
+ "error": {
+ "code": "credit_limit_reached",
+ "source": "billing",
+ "retryable": False,
+ "message": "out of credits",
+ },
+ },
+ {"type": "agent.started"},
+ {
+ "type": "agent.finished",
+ "outcome": "succeeded",
+ "durationMs": 1234,
+ "error": None,
+ },
+ {"type": "browser.session.started", "sessionId": "sess-1"},
+ {"type": "browser.session.finished", "sessionId": "sess-1", "durationMs": 42},
+ {"type": "progress.reported", "phase": "working", "message": "reading"},
+ {"type": "reasoning.summary", "text": "thinking"},
+ {
+ "type": "tool_call.started",
+ "toolCallId": "tc-1",
+ "toolName": "scrape",
+ "parameters": {"url": "https://example.com"},
+ },
+ {
+ "type": "tool_call.finished",
+ "toolCallId": "tc-1",
+ "toolName": "scrape",
+ "result": {"ok": True},
+ },
+ {
+ "type": "artifact.updated",
+ "artifact": {
+ "kind": "json",
+ "artifactId": "result",
+ "path": "/workspace/data.json",
+ "snapshotId": "018f3c5e-0000-7000-8000-000000000003",
+ "change": "partial",
+ "changedFields": ["price"],
+ "itemCount": 3,
+ "sourceToolCallId": "tc-1",
+ },
+ },
+ {
+ "type": "error.occurred",
+ "error": {
+ "code": "internal",
+ "source": "system",
+ "retryable": True,
+ "message": "boom",
+ },
+ },
+ ]
+
+ response = AgentTraceResponse(
+ **{
+ "success": True,
+ "id": "job-1",
+ "events": [{**self.BASE_EVENT, **e} for e in events],
+ "creditsUsed": 5,
+ "activeBrowserSessions": [
+ {
+ "id": "sess-1",
+ "liveViewUrl": "https://browser.example.com/sess-1",
+ "viewport": {"width": 1280, "height": 720},
+ }
+ ],
+ }
+ )
+
+ assert len(response.events) == 13
+ assert response.events[0].type == "run.started"
+ assert response.events[4].duration_ms == 1234
+ assert response.events[4].error is None
+ artifact = response.events[11].artifact
+ assert artifact.snapshot_id == "018f3c5e-0000-7000-8000-000000000003"
+ assert artifact.change == "partial"
+ assert artifact.changed_fields == ["price"]
+ assert response.events[12].error.code == "internal"
+ assert response.credits_used == 5
+ assert response.active_browser_sessions[0].viewport.width == 1280
+
+ def test_snapshot_payload_parses(self):
+ from firecrawl.v2.types import AgentSnapshotResponse
+
+ response = AgentSnapshotResponse(
+ **{
+ "success": True,
+ "id": "job-1",
+ "snapshotId": "snap-1",
+ "snapshot": '{"price": 42}',
+ }
+ )
+
+ assert response.snapshot_id == "snap-1"
+ assert response.snapshot == '{"price": 42}'
+
+ def test_trace_parses_terminal_events_without_error_key(self):
+ """Terminal events missing the error key still parse (older rows)."""
+ from firecrawl.v2.types import AgentTraceResponse
+
+ events = [
+ {"type": "run.finished", "outcome": "succeeded"},
+ {"type": "agent.finished", "outcome": "succeeded", "durationMs": 7},
+ ]
+
+ response = AgentTraceResponse(
+ **{
+ "success": True,
+ "id": "job-1",
+ "events": [{**self.BASE_EVENT, **e} for e in events],
+ }
+ )
+
+ assert response.events[0].error is None
+ assert response.events[1].error is None
diff --git a/apps/python-sdk/firecrawl/client.py b/apps/python-sdk/firecrawl/client.py
index b648b4bef..42b16ce2d 100644
--- a/apps/python-sdk/firecrawl/client.py
+++ b/apps/python-sdk/firecrawl/client.py
@@ -97,6 +97,8 @@ class V2Proxy:
self.start_agent = client_instance.start_agent
self.get_agent_status = client_instance.get_agent_status
self.cancel_agent = client_instance.cancel_agent
+ self.get_agent_trace = client_instance.get_agent_trace
+ self.get_agent_snapshot = client_instance.get_agent_snapshot
self.start_batch_scrape = client_instance.start_batch_scrape
self.get_batch_scrape_status = client_instance.get_batch_scrape_status
@@ -185,6 +187,8 @@ class AsyncV2Proxy:
self.start_agent = client_instance.start_agent
self.get_agent_status = client_instance.get_agent_status
self.cancel_agent = client_instance.cancel_agent
+ self.get_agent_trace = client_instance.get_agent_trace
+ self.get_agent_snapshot = client_instance.get_agent_snapshot
self.start_batch_scrape = client_instance.start_batch_scrape
self.get_batch_scrape_status = client_instance.get_batch_scrape_status
@@ -307,6 +311,8 @@ class Firecrawl:
self.start_agent = self._v2_client.start_agent
self.get_agent_status = self._v2_client.get_agent_status
self.cancel_agent = self._v2_client.cancel_agent
+ self.get_agent_trace = self._v2_client.get_agent_trace
+ self.get_agent_snapshot = self._v2_client.get_agent_snapshot
self.agent = self._v2_client.agent
self.get_concurrency = self._v2_client.get_concurrency
@@ -442,6 +448,8 @@ class AsyncFirecrawl:
self.start_agent = self._v2_client.start_agent
self.get_agent_status = self._v2_client.get_agent_status
self.cancel_agent = self._v2_client.cancel_agent
+ self.get_agent_trace = self._v2_client.get_agent_trace
+ self.get_agent_snapshot = self._v2_client.get_agent_snapshot
self.agent = self._v2_client.agent
self.get_concurrency = self._v2_client.get_concurrency
diff --git a/apps/python-sdk/firecrawl/v2/client.py b/apps/python-sdk/firecrawl/v2/client.py
index 8c8f1ccbf..e24aee9f7 100644
--- a/apps/python-sdk/firecrawl/v2/client.py
+++ b/apps/python-sdk/firecrawl/v2/client.py
@@ -1398,6 +1398,7 @@ class FirecrawlClient:
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -1411,6 +1412,7 @@ class FirecrawlClient:
integration: Integration tag/name
max_credits: Maximum credits to use (optional)
model: Model to use for the agent ("spark-1-pro" (default), "spark-1-mini", or "spark-2")
+ effort: Reasoning effort for the agent ("low", "medium", or "high")
webhook: Webhook URL or configuration for notifications
threat_protection: Enterprise per-request override of the team's
threat protection policy
@@ -1427,6 +1429,7 @@ class FirecrawlClient:
max_credits=max_credits,
strict_constrain_to_urls=strict_constrain_to_urls,
model=model,
+ effort=effort,
webhook=webhook,
threat_protection=threat_protection,
audit_metadata=audit_metadata,
@@ -1444,6 +1447,7 @@ class FirecrawlClient:
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -1459,6 +1463,7 @@ class FirecrawlClient:
timeout: Maximum seconds to wait (None for no timeout)
max_credits: Maximum credits to use (optional)
model: Model to use for the agent ("spark-1-pro" (default), "spark-1-mini", or "spark-2")
+ effort: Reasoning effort for the agent ("low", "medium", or "high")
webhook: Webhook URL or configuration for notifications
threat_protection: Enterprise per-request override of the team's
threat protection policy
@@ -1477,6 +1482,7 @@ class FirecrawlClient:
max_credits=max_credits,
strict_constrain_to_urls=strict_constrain_to_urls,
model=model,
+ effort=effort,
webhook=webhook,
threat_protection=threat_protection,
audit_metadata=audit_metadata,
@@ -1504,6 +1510,30 @@ class FirecrawlClient:
"""
return agent_module.cancel_agent(self.http_client, job_id)
+ def get_agent_trace(self, job_id: str, *, live_view: bool = False):
+ """Get the execution trace of an agent job (spark-2 runs only).
+
+ Args:
+ job_id: Agent job ID
+ live_view: Also include currently active browser sessions with live view URLs
+
+ Returns:
+ AgentTraceResponse with the ordered trace events
+ """
+ return agent_module.get_agent_trace(self.http_client, job_id, live_view=live_view)
+
+ def get_agent_snapshot(self, job_id: str, snapshot_id: str):
+ """Get the full content of an artifact snapshot referenced by a trace event.
+
+ Args:
+ job_id: Agent job ID
+ snapshot_id: Snapshot ID from an artifact.updated trace event
+
+ Returns:
+ AgentSnapshotResponse with the snapshot content
+ """
+ return agent_module.get_agent_snapshot(self.http_client, job_id, snapshot_id)
+
def get_concurrency(self):
"""Get current concurrency and maximum allowed for this team/key (v2)."""
return usage_methods.get_concurrency(self.http_client)
diff --git a/apps/python-sdk/firecrawl/v2/client_async.py b/apps/python-sdk/firecrawl/v2/client_async.py
index 42b901bc3..28df0cc87 100644
--- a/apps/python-sdk/firecrawl/v2/client_async.py
+++ b/apps/python-sdk/firecrawl/v2/client_async.py
@@ -735,6 +735,7 @@ class AsyncFirecrawlClient:
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -750,6 +751,7 @@ class AsyncFirecrawlClient:
max_credits=max_credits,
strict_constrain_to_urls=strict_constrain_to_urls,
model=model,
+ effort=effort,
webhook=webhook,
threat_protection=threat_protection,
audit_metadata=audit_metadata,
@@ -768,6 +770,7 @@ class AsyncFirecrawlClient:
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -781,6 +784,7 @@ class AsyncFirecrawlClient:
max_credits=max_credits,
strict_constrain_to_urls=strict_constrain_to_urls,
model=model,
+ effort=effort,
webhook=webhook,
threat_protection=threat_protection,
audit_metadata=audit_metadata,
@@ -797,6 +801,34 @@ class AsyncFirecrawlClient:
"""
return await async_agent.cancel_agent(self.async_http_client, job_id)
+ async def get_agent_trace(self, job_id: str, *, live_view: bool = False):
+ """Get the execution trace of an agent job (spark-2 runs only).
+
+ Args:
+ job_id: Agent job ID
+ live_view: Also include currently active browser sessions with live view URLs
+
+ Returns:
+ AgentTraceResponse with the ordered trace events
+ """
+ return await async_agent.get_agent_trace(
+ self.async_http_client, job_id, live_view=live_view
+ )
+
+ async def get_agent_snapshot(self, job_id: str, snapshot_id: str):
+ """Get the full content of an artifact snapshot referenced by a trace event.
+
+ Args:
+ job_id: Agent job ID
+ snapshot_id: Snapshot ID from an artifact.updated trace event
+
+ Returns:
+ AgentSnapshotResponse with the snapshot content
+ """
+ return await async_agent.get_agent_snapshot(
+ self.async_http_client, job_id, snapshot_id
+ )
+
# Browser
async def browser(
self,
diff --git a/apps/python-sdk/firecrawl/v2/methods/agent.py b/apps/python-sdk/firecrawl/v2/methods/agent.py
index 7d6e63e63..06e21481d 100644
--- a/apps/python-sdk/firecrawl/v2/methods/agent.py
+++ b/apps/python-sdk/firecrawl/v2/methods/agent.py
@@ -1,7 +1,14 @@
from typing import Any, Dict, List, Literal, Optional, Union
import time
-from ..types import AgentResponse, AgentWebhookConfig, AuditMetadata, ThreatProtectionOptions
+from ..types import (
+ AgentResponse,
+ AgentSnapshotResponse,
+ AgentTraceResponse,
+ AgentWebhookConfig,
+ AuditMetadata,
+ ThreatProtectionOptions,
+)
from ..utils.http_client import HttpClient
from ..utils.error_handler import handle_response_error
from ..utils.validation import _normalize_schema
@@ -16,6 +23,7 @@ def _prepare_agent_request(
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -41,6 +49,8 @@ def _prepare_agent_request(
body["strictConstrainToURLs"] = strict_constrain_to_urls
if model is not None:
body["model"] = model
+ if effort is not None:
+ body["effort"] = effort
if webhook is not None:
if isinstance(webhook, str):
body["webhook"] = webhook
@@ -74,6 +84,7 @@ def start_agent(
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -86,6 +97,7 @@ def start_agent(
max_credits=max_credits,
strict_constrain_to_urls=strict_constrain_to_urls,
model=model,
+ effort=effort,
webhook=webhook,
threat_protection=threat_protection,
audit_metadata=audit_metadata,
@@ -134,6 +146,7 @@ def agent(
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -147,6 +160,7 @@ def agent(
max_credits=max_credits,
strict_constrain_to_urls=strict_constrain_to_urls,
model=model,
+ effort=effort,
webhook=webhook,
threat_protection=threat_protection,
audit_metadata=audit_metadata,
@@ -157,6 +171,46 @@ def agent(
return wait_agent(client, job_id, poll_interval=poll_interval, timeout=timeout)
+def get_agent_trace(
+ client: HttpClient,
+ job_id: str,
+ *,
+ live_view: bool = False,
+) -> AgentTraceResponse:
+ """Get the execution trace of an agent job (spark-2 runs only).
+
+ Args:
+ client: HTTP client instance
+ job_id: ID of the agent job
+ live_view: Also include currently active browser sessions with live view URLs
+ """
+ endpoint = f"/v2/agent/{job_id}/trace"
+ if live_view:
+ endpoint += "?liveView=true"
+ resp = client.get(endpoint)
+ if not resp.ok:
+ handle_response_error(resp, "agent-trace")
+ return AgentTraceResponse(**resp.json())
+
+
+def get_agent_snapshot(
+ client: HttpClient,
+ job_id: str,
+ snapshot_id: str,
+) -> AgentSnapshotResponse:
+ """Get the full content of an artifact snapshot referenced by a trace event.
+
+ Args:
+ client: HTTP client instance
+ job_id: ID of the agent job
+ snapshot_id: Snapshot ID from an artifact.updated trace event
+ """
+ resp = client.get(f"/v2/agent/{job_id}/snapshots/{snapshot_id}")
+ if not resp.ok:
+ handle_response_error(resp, "agent-snapshot")
+ return AgentSnapshotResponse(**resp.json())
+
+
def cancel_agent(client: HttpClient, job_id: str) -> bool:
"""
Cancel a running agent job.
diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/agent.py b/apps/python-sdk/firecrawl/v2/methods/aio/agent.py
index 8ddab3409..300b789b1 100644
--- a/apps/python-sdk/firecrawl/v2/methods/aio/agent.py
+++ b/apps/python-sdk/firecrawl/v2/methods/aio/agent.py
@@ -1,7 +1,14 @@
from typing import Any, Dict, List, Literal, Optional, Union
import asyncio
-from ...types import AgentResponse, AgentWebhookConfig, AuditMetadata, ThreatProtectionOptions
+from ...types import (
+ AgentResponse,
+ AgentSnapshotResponse,
+ AgentTraceResponse,
+ AgentWebhookConfig,
+ AuditMetadata,
+ ThreatProtectionOptions,
+)
from ...utils.error_handler import handle_response_error
from ...utils.http_client_async import AsyncHttpClient
from ...utils.validation import _normalize_schema
@@ -16,6 +23,7 @@ def _prepare_agent_request(
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -41,6 +49,8 @@ def _prepare_agent_request(
body["strictConstrainToURLs"] = strict_constrain_to_urls
if model is not None:
body["model"] = model
+ if effort is not None:
+ body["effort"] = effort
if webhook is not None:
if isinstance(webhook, str):
body["webhook"] = webhook
@@ -74,6 +84,7 @@ async def start_agent(
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -86,6 +97,7 @@ async def start_agent(
max_credits=max_credits,
strict_constrain_to_urls=strict_constrain_to_urls,
model=model,
+ effort=effort,
webhook=webhook,
threat_protection=threat_protection,
audit_metadata=audit_metadata,
@@ -134,6 +146,7 @@ async def agent(
max_credits: Optional[int] = None,
strict_constrain_to_urls: Optional[bool] = None,
model: Optional[Literal["spark-1-pro", "spark-1-mini", "spark-2"]] = None,
+ effort: Optional[Literal["low", "medium", "high"]] = None,
webhook: Optional[Union[str, AgentWebhookConfig]] = None,
threat_protection: Optional[ThreatProtectionOptions] = None,
audit_metadata: Optional[AuditMetadata] = None,
@@ -147,6 +160,7 @@ async def agent(
max_credits=max_credits,
strict_constrain_to_urls=strict_constrain_to_urls,
model=model,
+ effort=effort,
webhook=webhook,
threat_protection=threat_protection,
audit_metadata=audit_metadata,
@@ -157,6 +171,46 @@ async def agent(
return await wait_agent(client, job_id, poll_interval=poll_interval, timeout=timeout)
+async def get_agent_trace(
+ client: AsyncHttpClient,
+ job_id: str,
+ *,
+ live_view: bool = False,
+) -> AgentTraceResponse:
+ """Get the execution trace of an agent job (spark-2 runs only).
+
+ Args:
+ client: Async HTTP client instance
+ job_id: ID of the agent job
+ live_view: Also include currently active browser sessions with live view URLs
+ """
+ endpoint = f"/v2/agent/{job_id}/trace"
+ if live_view:
+ endpoint += "?liveView=true"
+ resp = await client.get(endpoint)
+ if not resp.ok:
+ handle_response_error(resp, "agent-trace")
+ return AgentTraceResponse(**resp.json())
+
+
+async def get_agent_snapshot(
+ client: AsyncHttpClient,
+ job_id: str,
+ snapshot_id: str,
+) -> AgentSnapshotResponse:
+ """Get the full content of an artifact snapshot referenced by a trace event.
+
+ Args:
+ client: Async HTTP client instance
+ job_id: ID of the agent job
+ snapshot_id: Snapshot ID from an artifact.updated trace event
+ """
+ resp = await client.get(f"/v2/agent/{job_id}/snapshots/{snapshot_id}")
+ if not resp.ok:
+ handle_response_error(resp, "agent-snapshot")
+ return AgentSnapshotResponse(**resp.json())
+
+
async def cancel_agent(client: AsyncHttpClient, job_id: str) -> bool:
"""
Cancel a running agent job.
diff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.py
index 695226171..b2ac2f5ca 100644
--- a/apps/python-sdk/firecrawl/v2/types.py
+++ b/apps/python-sdk/firecrawl/v2/types.py
@@ -7,6 +7,11 @@ This module contains clean, modern type definitions for the v2 API.
import warnings
from datetime import datetime
from typing import Any, Dict, Generic, List, Literal, Optional, TypeVar, Union
+
+try:
+ from typing import Annotated
+except ImportError: # Python 3.8
+ from typing_extensions import Annotated
import logging
from pydantic import (
BaseModel,
@@ -1452,10 +1457,210 @@ class AgentResponse(BaseModel):
# models ship without an SDK release, so a narrow type turns an unknown
# model name into a ValidationError on every status poll.
model: Optional[str] = None
+ # Reasoning effort the job ran with; only set for runs that specified it.
+ effort: Optional[Literal["low", "medium", "high"]] = None
expires_at: Optional[datetime] = None
credits_used: Optional[int] = None
+# Agent trace types (GET /v2/agent/{job_id}/trace).
+# These mirror the agent service's canonical event schema (schemaVersion 1):
+# usage.recorded events are withheld server-side and agent.started carries no
+# model name.
+
+
+class AgentTraceAgentIdentity(BaseModel):
+ """Which agent produced a trace event."""
+
+ model_config = {"populate_by_name": True}
+
+ id: str
+ role: Literal["orchestrator", "subagent", "browser", "system"]
+ name: str
+ parent_id: Optional[str] = Field(default=None, alias="parentId")
+
+
+class AgentTraceError(BaseModel):
+ """Structured error attached to terminal/error trace events."""
+
+ code: Literal[
+ "cancelled", "credit_limit_reached", "parent_finished", "refused", "internal"
+ ]
+ source: Literal["agent", "tool", "billing", "system"]
+ retryable: bool
+ message: str
+
+
+class AgentTraceArtifactChange(BaseModel):
+ """Reference to an artifact snapshot; fetch content via get_agent_snapshot."""
+
+ model_config = {"populate_by_name": True}
+
+ kind: Literal["json", "markdown", "html", "screenshot", "text"]
+ artifact_id: str = Field(alias="artifactId")
+ path: Optional[str] = None
+ snapshot_id: str = Field(alias="snapshotId")
+ change: Literal["init", "partial", "append", "modify", "update"]
+ changed_fields: Optional[List[str]] = Field(default=None, alias="changedFields")
+ item_count: Optional[int] = Field(default=None, alias="itemCount")
+ source_tool_call_id: Optional[str] = Field(default=None, alias="sourceToolCallId")
+
+
+class AgentTraceEventBase(BaseModel):
+ """Fields every trace event carries."""
+
+ model_config = {"populate_by_name": True}
+
+ schema_version: Literal[1] = Field(alias="schemaVersion")
+ event_id: str = Field(alias="eventId")
+ run_id: str = Field(alias="runId")
+ occurred_at: datetime = Field(alias="occurredAt")
+ producer_sequence: int = Field(alias="producerSequence")
+ agent: AgentTraceAgentIdentity
+
+
+class AgentTraceRunStartedEvent(AgentTraceEventBase):
+ type: Literal["run.started"]
+
+
+class AgentTraceRunCancelRequestedEvent(AgentTraceEventBase):
+ type: Literal["run.cancel_requested"]
+ reason: Literal["user"]
+
+
+class AgentTraceRunFinishedEvent(AgentTraceEventBase):
+ type: Literal["run.finished"]
+ outcome: Literal["succeeded", "failed", "cancelled", "refused", "credit_limit_reached"]
+ # The canonical schema always writes this key (nullable), but default it so
+ # a trace with the key absent still parses instead of raising.
+ error: Optional[AgentTraceError] = None
+
+
+class AgentTraceAgentStartedEvent(AgentTraceEventBase):
+ type: Literal["agent.started"]
+
+
+class AgentTraceAgentFinishedEvent(AgentTraceEventBase):
+ type: Literal["agent.finished"]
+ outcome: Literal["succeeded", "failed", "cancelled", "refused"]
+ duration_ms: int = Field(alias="durationMs")
+ # See AgentTraceRunFinishedEvent.error for why this has a default.
+ error: Optional[AgentTraceError] = None
+
+
+class AgentTraceBrowserSessionStartedEvent(AgentTraceEventBase):
+ type: Literal["browser.session.started"]
+ session_id: str = Field(alias="sessionId")
+
+
+class AgentTraceBrowserSessionFinishedEvent(AgentTraceEventBase):
+ type: Literal["browser.session.finished"]
+ session_id: str = Field(alias="sessionId")
+ duration_ms: int = Field(alias="durationMs")
+
+
+class AgentTraceProgressReportedEvent(AgentTraceEventBase):
+ type: Literal["progress.reported"]
+ phase: Literal["planning", "working", "finalizing"]
+ message: str
+
+
+class AgentTraceReasoningSummaryEvent(AgentTraceEventBase):
+ type: Literal["reasoning.summary"]
+ text: str
+
+
+class AgentTraceToolCallStartedEvent(AgentTraceEventBase):
+ type: Literal["tool_call.started"]
+ tool_call_id: str = Field(alias="toolCallId")
+ tool_name: str = Field(alias="toolName")
+ # Required key on the wire (zod `.json()`), values may be null: Field(...)
+ # keeps the key required so a malformed event cannot silently pass.
+ parameters: Any = Field(...)
+
+
+class AgentTraceToolCallFinishedEvent(AgentTraceEventBase):
+ type: Literal["tool_call.finished"]
+ tool_call_id: str = Field(alias="toolCallId")
+ tool_name: str = Field(alias="toolName")
+ # See AgentTraceToolCallStartedEvent.parameters.
+ result: Any = Field(...)
+
+
+class AgentTraceArtifactUpdatedEvent(AgentTraceEventBase):
+ type: Literal["artifact.updated"]
+ artifact: AgentTraceArtifactChange
+
+
+class AgentTraceErrorOccurredEvent(AgentTraceEventBase):
+ type: Literal["error.occurred"]
+ error: AgentTraceError
+
+
+# Discriminated on the wire's `type` tag so generated schemas expose the
+# discriminator and validation dispatches on it directly.
+AgentTraceEvent = Annotated[
+ Union[
+ AgentTraceRunStartedEvent,
+ AgentTraceRunCancelRequestedEvent,
+ AgentTraceRunFinishedEvent,
+ AgentTraceAgentStartedEvent,
+ AgentTraceAgentFinishedEvent,
+ AgentTraceBrowserSessionStartedEvent,
+ AgentTraceBrowserSessionFinishedEvent,
+ AgentTraceProgressReportedEvent,
+ AgentTraceReasoningSummaryEvent,
+ AgentTraceToolCallStartedEvent,
+ AgentTraceToolCallFinishedEvent,
+ AgentTraceArtifactUpdatedEvent,
+ AgentTraceErrorOccurredEvent,
+ ],
+ Field(discriminator="type"),
+]
+
+
+class AgentTraceViewport(BaseModel):
+ width: int
+ height: int
+
+
+class AgentTraceActiveBrowserSession(BaseModel):
+ """Live browser session, present only when trace is requested with live_view."""
+
+ model_config = {"populate_by_name": True}
+
+ id: str
+ live_view_url: str = Field(alias="liveViewUrl")
+ viewport: AgentTraceViewport
+
+
+class AgentTraceResponse(BaseModel):
+ """Response from GET /v2/agent/{job_id}/trace."""
+
+ model_config = {"populate_by_name": True}
+
+ success: Optional[bool] = None
+ id: Optional[str] = None
+ events: Optional[List[AgentTraceEvent]] = None
+ credits_used: Optional[int] = Field(default=None, alias="creditsUsed")
+ active_browser_sessions: Optional[List[AgentTraceActiveBrowserSession]] = Field(
+ default=None, alias="activeBrowserSessions"
+ )
+ error: Optional[str] = None
+
+
+class AgentSnapshotResponse(BaseModel):
+ """Response from GET /v2/agent/{job_id}/snapshots/{snapshot_id}."""
+
+ model_config = {"populate_by_name": True}
+
+ success: Optional[bool] = None
+ id: Optional[str] = None
+ snapshot_id: Optional[str] = Field(default=None, alias="snapshotId")
+ snapshot: Optional[str] = None
+ error: Optional[str] = None
+
+
# Browser types
class BrowserCreateResponse(BaseModel):
"""Response from creating a browser session."""
diff --git a/apps/ruby-sdk/lib/firecrawl.rb b/apps/ruby-sdk/lib/firecrawl.rb
index b6398d36c..ea9be7b6d 100644
--- a/apps/ruby-sdk/lib/firecrawl.rb
+++ b/apps/ruby-sdk/lib/firecrawl.rb
@@ -25,6 +25,8 @@ require_relative "firecrawl/models/parse_options"
require_relative "firecrawl/models/agent_options"
require_relative "firecrawl/models/agent_response"
require_relative "firecrawl/models/agent_status_response"
+require_relative "firecrawl/models/agent_trace_response"
+require_relative "firecrawl/models/agent_snapshot_response"
require_relative "firecrawl/models/concurrency_check"
require_relative "firecrawl/models/credit_usage"
require_relative "firecrawl/models/monitor"
diff --git a/apps/ruby-sdk/lib/firecrawl/client.rb b/apps/ruby-sdk/lib/firecrawl/client.rb
index d7829677b..9a8f012c9 100644
--- a/apps/ruby-sdk/lib/firecrawl/client.rb
+++ b/apps/ruby-sdk/lib/firecrawl/client.rb
@@ -493,6 +493,31 @@ module Firecrawl
@http.delete("/v2/agent/#{job_id}")
end
+ # Gets the trace of an agent task.
+ #
+ # @param job_id [String] the agent job ID
+ # @param live_view [Boolean] include live view URLs for active browser sessions
+ # @return [Models::AgentTraceResponse]
+ def get_agent_trace(job_id, live_view: false)
+ raise ArgumentError, "Job ID is required" if job_id.nil?
+
+ raw = @http.get("/v2/agent/#{job_id}/trace#{query(liveView: live_view ? true : nil)}")
+ Models::AgentTraceResponse.new(raw)
+ end
+
+ # Gets a snapshot of an agent task.
+ #
+ # @param job_id [String] the agent job ID
+ # @param snapshot_id [String] the snapshot ID
+ # @return [Models::AgentSnapshotResponse]
+ def get_agent_snapshot(job_id, snapshot_id)
+ raise ArgumentError, "Job ID is required" if job_id.nil?
+ raise ArgumentError, "Snapshot ID is required" if snapshot_id.nil?
+
+ raw = @http.get("/v2/agent/#{job_id}/snapshots/#{snapshot_id}")
+ Models::AgentSnapshotResponse.new(raw)
+ end
+
# ================================================================
# USAGE & METRICS
# ================================================================
diff --git a/apps/ruby-sdk/lib/firecrawl/models/agent_options.rb b/apps/ruby-sdk/lib/firecrawl/models/agent_options.rb
index c87edef31..65473bd5c 100644
--- a/apps/ruby-sdk/lib/firecrawl/models/agent_options.rb
+++ b/apps/ruby-sdk/lib/firecrawl/models/agent_options.rb
@@ -3,10 +3,13 @@
module Firecrawl
module Models
# Options for starting an agent task.
+ #
+ # effort: valid values are "low", "medium", and "high"; sets the reasoning
+ # budget for the run (every level runs spark-2).
class AgentOptions
FIELDS = %i[
urls prompt schema integration max_credits
- strict_constrain_to_urls model webhook audit_metadata
+ strict_constrain_to_urls model effort webhook audit_metadata
].freeze
attr_reader(*FIELDS)
@@ -28,6 +31,7 @@ module Firecrawl
"maxCredits" => max_credits,
"strictConstrainToURLs" => strict_constrain_to_urls,
"model" => model,
+ "effort" => effort,
"webhook" => webhook.is_a?(Hash) ? webhook : webhook&.to_h,
"auditMetadata" => audit_metadata&.to_h,
}.compact
diff --git a/apps/ruby-sdk/lib/firecrawl/models/agent_snapshot_response.rb b/apps/ruby-sdk/lib/firecrawl/models/agent_snapshot_response.rb
new file mode 100644
index 000000000..7309e9760
--- /dev/null
+++ b/apps/ruby-sdk/lib/firecrawl/models/agent_snapshot_response.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module Firecrawl
+ module Models
+ # Snapshot response for an agent task.
+ class AgentSnapshotResponse
+ attr_reader :success, :id, :snapshot_id, :snapshot, :error
+
+ def initialize(raw)
+ @success = raw["success"]
+ @id = raw["id"]
+ @snapshot_id = raw["snapshotId"]
+ @snapshot = raw["snapshot"]
+ @error = raw["error"]
+ end
+
+ def to_s
+ "AgentSnapshotResponse{id=#{id}, snapshot_id=#{snapshot_id}, success=#{success}}"
+ end
+ end
+ end
+end
diff --git a/apps/ruby-sdk/lib/firecrawl/models/agent_status_response.rb b/apps/ruby-sdk/lib/firecrawl/models/agent_status_response.rb
index a29cc57e7..b2eb09671 100644
--- a/apps/ruby-sdk/lib/firecrawl/models/agent_status_response.rb
+++ b/apps/ruby-sdk/lib/firecrawl/models/agent_status_response.rb
@@ -4,13 +4,15 @@ module Firecrawl
module Models
# Status response for monitoring agent tasks.
class AgentStatusResponse
- attr_reader :status, :data, :credits_used, :expires_at
+ attr_reader :status, :data, :credits_used, :expires_at, :effort
def initialize(raw)
@status = raw["status"]
@data = raw["data"]
@credits_used = raw["creditsUsed"]
@expires_at = raw["expiresAt"]
+ # The effort the job ran with; only present for runs that specified it.
+ @effort = raw["effort"]
end
def done?
diff --git a/apps/ruby-sdk/lib/firecrawl/models/agent_trace_response.rb b/apps/ruby-sdk/lib/firecrawl/models/agent_trace_response.rb
new file mode 100644
index 000000000..ff7379c7a
--- /dev/null
+++ b/apps/ruby-sdk/lib/firecrawl/models/agent_trace_response.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+module Firecrawl
+ module Models
+ # Trace response for an agent task.
+ #
+ # Events are raw hashes: each carries a "type" (e.g. "run.started",
+ # "agent.finished", "tool_call.started") plus base fields like
+ # "schemaVersion", "eventId", "runId", "occurredAt", "producerSequence",
+ # and "agent".
+ class AgentTraceResponse
+ attr_reader :success, :id, :events, :active_browser_sessions, :credits_used, :error
+
+ def initialize(raw)
+ @success = raw["success"]
+ @id = raw["id"]
+ @events = raw["events"]
+ @active_browser_sessions = raw["activeBrowserSessions"]
+ @credits_used = raw["creditsUsed"]
+ @error = raw["error"]
+ end
+
+ def to_s
+ "AgentTraceResponse{id=#{id}, success=#{success}}"
+ end
+ end
+ end
+end
diff --git a/apps/ruby-sdk/lib/firecrawl/version.rb b/apps/ruby-sdk/lib/firecrawl/version.rb
index b14207c3e..9b550d10f 100644
--- a/apps/ruby-sdk/lib/firecrawl/version.rb
+++ b/apps/ruby-sdk/lib/firecrawl/version.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
module Firecrawl
- VERSION = "1.14.0"
+ VERSION = "1.15.0"
end
diff --git a/apps/ruby-sdk/test/firecrawl/client_test.rb b/apps/ruby-sdk/test/firecrawl/client_test.rb
index 6282c4c4c..a35717c72 100644
--- a/apps/ruby-sdk/test/firecrawl/client_test.rb
+++ b/apps/ruby-sdk/test/firecrawl/client_test.rb
@@ -636,6 +636,95 @@ class ClientTest < Minitest::Test
assert_raises(ArgumentError) { Firecrawl::Models::AgentOptions.new }
end
+ def test_start_agent_with_effort
+ stub_request(:post, "#{BASE_URL}/v2/agent")
+ .with { |req| body = JSON.parse(req.body); body["effort"] == "high" && body["model"] == "spark-1-pro" }
+ .to_return(
+ status: 200,
+ body: JSON.generate(success: true, id: "agent-effort"),
+ headers: { "Content-Type" => "application/json" }
+ )
+
+ options = Firecrawl::Models::AgentOptions.new(prompt: "Find pricing info", model: "spark-1-pro", effort: "high")
+ response = @client.start_agent(options)
+ assert_equal "agent-effort", response.id
+ end
+
+ def test_get_agent_status_with_effort
+ stub_request(:get, "#{BASE_URL}/v2/agent/agent-effort")
+ .to_return(
+ status: 200,
+ body: JSON.generate(status: "completed", effort: "high"),
+ headers: { "Content-Type" => "application/json" }
+ )
+
+ status = @client.get_agent_status("agent-effort")
+ assert_equal "completed", status.status
+ assert_equal "high", status.effort
+ end
+
+ def test_get_agent_trace
+ stub_request(:get, "#{BASE_URL}/v2/agent/agent-123/trace")
+ .to_return(
+ status: 200,
+ body: JSON.generate(
+ success: true,
+ id: "agent-123",
+ events: [{ type: "run.started" }, { type: "run.finished" }],
+ creditsUsed: 5
+ ),
+ headers: { "Content-Type" => "application/json" }
+ )
+
+ trace = @client.get_agent_trace("agent-123")
+ assert_instance_of Firecrawl::Models::AgentTraceResponse, trace
+ assert_equal true, trace.success
+ assert_equal "agent-123", trace.id
+ assert_equal 5, trace.credits_used
+ assert_equal 2, trace.events.size
+ assert_equal "run.started", trace.events.first["type"]
+ assert_nil trace.active_browser_sessions
+ end
+
+ def test_get_agent_trace_with_live_view
+ stub_request(:get, "#{BASE_URL}/v2/agent/agent-123/trace")
+ .with(query: { liveView: "true" })
+ .to_return(
+ status: 200,
+ body: JSON.generate(
+ success: true,
+ id: "agent-123",
+ events: [],
+ creditsUsed: 5,
+ activeBrowserSessions: [
+ { id: "bs-1", liveViewUrl: "https://live.example.com/bs-1", viewport: { width: 1280, height: 720 } }
+ ]
+ ),
+ headers: { "Content-Type" => "application/json" }
+ )
+
+ trace = @client.get_agent_trace("agent-123", live_view: true)
+ assert_equal 1, trace.active_browser_sessions.size
+ assert_equal "https://live.example.com/bs-1", trace.active_browser_sessions.first["liveViewUrl"]
+ assert_equal 1280, trace.active_browser_sessions.first["viewport"]["width"]
+ end
+
+ def test_get_agent_snapshot
+ stub_request(:get, "#{BASE_URL}/v2/agent/agent-123/snapshots/snap-1")
+ .to_return(
+ status: 200,
+ body: JSON.generate(success: true, id: "agent-123", snapshotId: "snap-1", snapshot: "<html>snapshot</html>"),
+ headers: { "Content-Type" => "application/json" }
+ )
+
+ snapshot = @client.get_agent_snapshot("agent-123", "snap-1")
+ assert_instance_of Firecrawl::Models::AgentSnapshotResponse, snapshot
+ assert_equal true, snapshot.success
+ assert_equal "agent-123", snapshot.id
+ assert_equal "snap-1", snapshot.snapshot_id
+ assert_equal "<html>snapshot</html>", snapshot.snapshot
+ end
+
# ================================================================
# USAGE & METRICS
# ================================================================
@@ -875,6 +964,17 @@ class ClientTest < Minitest::Test
assert_equal "spark-1-pro", h["model"]
end
+ def test_agent_options_to_h_with_effort
+ opts = Firecrawl::Models::AgentOptions.new(
+ prompt: "Find data",
+ model: "spark-1-pro",
+ effort: "high"
+ )
+ h = opts.to_h
+ assert_equal "spark-1-pro", h["model"]
+ assert_equal "high", h["effort"]
+ end
+
def test_audit_metadata_to_h
metadata = Firecrawl::Models::AuditMetadata.new(username: "[email protected]")
serialized = { "username" => "[email protected]" }
diff --git a/apps/rust-sdk/CHANGELOG.md b/apps/rust-sdk/CHANGELOG.md
index ac2fa6914..650d2452b 100644
--- a/apps/rust-sdk/CHANGELOG.md
+++ b/apps/rust-sdk/CHANGELOG.md
@@ -1,5 +1,17 @@
## CHANGELOG
+## [2.17.0] - 2026-08-26
+
+### Added
+
+- Added `AgentOptions::effort` (`AgentEffort`) for the agent reasoning budget,
+ and `AgentStatusResponse::effort` for the effort a run used.
+- Added `Client::get_agent_trace` returning the job's execution trace as typed
+ `AgentTraceEvent`s (canonical event schema v1), with optional live-view
+ browser sessions.
+- Added `Client::get_agent_snapshot` returning the full content of an artifact
+ snapshot referenced by an `artifact.updated` trace event.
+
## [2.16.1] - 2026-08-26
### Fixed
diff --git a/apps/rust-sdk/Cargo.lock b/apps/rust-sdk/Cargo.lock
index 8e1ffe827..7d4576703 100644
--- a/apps/rust-sdk/Cargo.lock
+++ b/apps/rust-sdk/Cargo.lock
@@ -250,7 +250,7 @@ checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "firecrawl"
-version = "2.16.1"
+version = "2.17.0"
dependencies = [
"mockito",
"reqwest",
diff --git a/apps/rust-sdk/Cargo.toml b/apps/rust-sdk/Cargo.toml
index 874e495e8..676ef549d 100644
--- a/apps/rust-sdk/Cargo.toml
+++ b/apps/rust-sdk/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "firecrawl"
-version = "2.16.1"
+version = "2.17.0"
edition = "2021"
license = "MIT"
homepage = "https://www.firecrawl.dev/"
diff --git a/apps/rust-sdk/src/agent.rs b/apps/rust-sdk/src/agent.rs
index 789235868..c283a61d3 100644
--- a/apps/rust-sdk/src/agent.rs
+++ b/apps/rust-sdk/src/agent.rs
@@ -4,7 +4,7 @@
//! to accomplish complex tasks that may require multiple page interactions.
use crate::client::Client;
-use crate::types::{AgentModel, AgentWebhookConfig};
+use crate::types::{AgentEffort, AgentModel, AgentWebhookConfig};
use crate::{AuditMetadata, FirecrawlError};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -39,6 +39,9 @@ pub struct AgentOptions {
/// Agent model to use. Defaults to `spark-1-pro` server-side when unset.
pub model: Option<AgentModel>,
+ /// Reasoning effort for the agent task. Every level runs spark-2.
+ pub effort: Option<AgentEffort>,
+
/// Webhook configuration for agent notifications.
pub webhook: Option<AgentWebhookConfig>,
@@ -95,12 +98,292 @@ pub struct AgentStatusResponse {
pub data: Option<Value>,
/// Model used for the agent task.
pub model: Option<AgentModel>,
+ /// Reasoning effort the task ran with, if one was requested.
+ pub effort: Option<AgentEffort>,
/// Expiry time of the task data.
pub expires_at: Option<String>,
/// Credits used by the agent task.
pub credits_used: Option<u32>,
}
+// Agent trace types (GET /v2/agent/:id/trace). These mirror the agent
+// service's canonical event schema (schemaVersion 1): usage.recorded events
+// are withheld server-side and agent.started carries no model name.
+
+/// Which agent produced a trace event.
+#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentTraceAgentIdentity {
+ pub id: String,
+ pub role: AgentTraceAgentRole,
+ pub name: String,
+ #[serde(default)]
+ pub parent_id: Option<String>,
+}
+
+/// Role of the agent that produced a trace event.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum AgentTraceAgentRole {
+ Orchestrator,
+ Subagent,
+ Browser,
+ System,
+}
+
+/// Structured error attached to terminal and error trace events.
+#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentTraceError {
+ pub code: AgentTraceErrorCode,
+ pub source: AgentTraceErrorSource,
+ pub retryable: bool,
+ pub message: String,
+}
+
+/// Machine-readable trace error code.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum AgentTraceErrorCode {
+ Cancelled,
+ CreditLimitReached,
+ ParentFinished,
+ Refused,
+ Internal,
+}
+
+/// Where a trace error originated.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum AgentTraceErrorSource {
+ Agent,
+ Tool,
+ Billing,
+ System,
+}
+
+/// Reference to an artifact snapshot; fetch the content with
+/// [`Client::get_agent_snapshot`].
+#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentTraceArtifactChange {
+ pub kind: AgentTraceArtifactKind,
+ pub artifact_id: String,
+ #[serde(default)]
+ pub path: Option<String>,
+ pub snapshot_id: String,
+ pub change: AgentTraceArtifactChangeKind,
+ #[serde(default)]
+ pub changed_fields: Option<Vec<String>>,
+ #[serde(default)]
+ pub item_count: Option<u64>,
+ #[serde(default)]
+ pub source_tool_call_id: Option<String>,
+}
+
+/// Kind of artifact content behind a snapshot.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum AgentTraceArtifactKind {
+ Json,
+ Markdown,
+ Html,
+ Screenshot,
+ Text,
+}
+
+/// How an artifact changed in an artifact.updated event.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum AgentTraceArtifactChangeKind {
+ Init,
+ Partial,
+ Append,
+ Modify,
+ Update,
+}
+
+/// Fields every trace event carries.
+#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentTraceEventBase {
+ /// Canonical event schema version (1 at the time of writing).
+ pub schema_version: u32,
+ pub event_id: String,
+ pub run_id: String,
+ /// ISO 8601 timestamp with offset.
+ pub occurred_at: String,
+ pub producer_sequence: u64,
+ pub agent: AgentTraceAgentIdentity,
+}
+
+macro_rules! trace_event_struct {
+ ($name:ident { $( $(#[$meta:meta])* $field:ident : $ty:ty ),* $(,)? }) => {
+ #[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
+ #[serde(rename_all = "camelCase")]
+ pub struct $name {
+ #[serde(flatten)]
+ pub base: AgentTraceEventBase,
+ $( $(#[$meta])* pub $field : $ty ),*
+ }
+ };
+ ($name:ident) => {
+ #[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
+ #[serde(rename_all = "camelCase")]
+ pub struct $name {
+ #[serde(flatten)]
+ pub base: AgentTraceEventBase,
+ }
+ };
+}
+
+trace_event_struct!(AgentTraceRunStartedEvent);
+trace_event_struct!(AgentTraceRunCancelRequestedEvent {
+ /// Always "user" at present.
+ reason: String
+});
+trace_event_struct!(AgentTraceRunFinishedEvent {
+ outcome: AgentTraceRunOutcome,
+ error: Option<AgentTraceError>
+});
+trace_event_struct!(AgentTraceAgentStartedEvent);
+trace_event_struct!(AgentTraceAgentFinishedEvent {
+ outcome: AgentTraceAgentOutcome,
+ duration_ms: u64,
+ error: Option<AgentTraceError>
+});
+trace_event_struct!(AgentTraceBrowserSessionStartedEvent { session_id: String });
+trace_event_struct!(AgentTraceBrowserSessionFinishedEvent {
+ session_id: String,
+ duration_ms: u64
+});
+trace_event_struct!(AgentTraceProgressReportedEvent {
+ phase: AgentTraceProgressPhase,
+ message: String
+});
+trace_event_struct!(AgentTraceReasoningSummaryEvent { text: String });
+trace_event_struct!(AgentTraceToolCallStartedEvent {
+ tool_call_id: String,
+ tool_name: String,
+ parameters: Value
+});
+trace_event_struct!(AgentTraceToolCallFinishedEvent {
+ tool_call_id: String,
+ tool_name: String,
+ result: Value
+});
+trace_event_struct!(AgentTraceArtifactUpdatedEvent {
+ artifact: AgentTraceArtifactChange
+});
+trace_event_struct!(AgentTraceErrorOccurredEvent {
+ error: AgentTraceError
+});
+
+/// Terminal outcome of a run.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum AgentTraceRunOutcome {
+ Succeeded,
+ Failed,
+ Cancelled,
+ Refused,
+ CreditLimitReached,
+}
+
+/// Terminal outcome of a single agent.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum AgentTraceAgentOutcome {
+ Succeeded,
+ Failed,
+ Cancelled,
+ Refused,
+}
+
+/// Phase a progress.reported event belongs to.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum AgentTraceProgressPhase {
+ Planning,
+ Working,
+ Finalizing,
+}
+
+/// One event in an agent job's execution trace.
+#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
+#[serde(tag = "type")]
+pub enum AgentTraceEvent {
+ #[serde(rename = "run.started")]
+ RunStarted(AgentTraceRunStartedEvent),
+ #[serde(rename = "run.cancel_requested")]
+ RunCancelRequested(AgentTraceRunCancelRequestedEvent),
+ #[serde(rename = "run.finished")]
+ RunFinished(AgentTraceRunFinishedEvent),
+ #[serde(rename = "agent.started")]
+ AgentStarted(AgentTraceAgentStartedEvent),
+ #[serde(rename = "agent.finished")]
+ AgentFinished(AgentTraceAgentFinishedEvent),
+ #[serde(rename = "browser.session.started")]
+ BrowserSessionStarted(AgentTraceBrowserSessionStartedEvent),
+ #[serde(rename = "browser.session.finished")]
+ BrowserSessionFinished(AgentTraceBrowserSessionFinishedEvent),
+ #[serde(rename = "progress.reported")]
+ ProgressReported(AgentTraceProgressReportedEvent),
+ #[serde(rename = "reasoning.summary")]
+ ReasoningSummary(AgentTraceReasoningSummaryEvent),
+ #[serde(rename = "tool_call.started")]
+ ToolCallStarted(AgentTraceToolCallStartedEvent),
+ #[serde(rename = "tool_call.finished")]
+ ToolCallFinished(AgentTraceToolCallFinishedEvent),
+ #[serde(rename = "artifact.updated")]
+ ArtifactUpdated(AgentTraceArtifactUpdatedEvent),
+ #[serde(rename = "error.occurred")]
+ ErrorOccurred(AgentTraceErrorOccurredEvent),
+}
+
+/// Live browser session, present only when the trace is requested with
+/// live view enabled.
+#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentTraceActiveBrowserSession {
+ pub id: String,
+ pub live_view_url: String,
+ pub viewport: AgentTraceViewport,
+}
+
+/// Browser viewport dimensions.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+pub struct AgentTraceViewport {
+ pub width: u32,
+ pub height: u32,
+}
+
+/// Response from getting an agent job's execution trace.
+#[serde_with::skip_serializing_none]
+#[derive(Deserialize, Serialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentTraceResponse {
+ pub success: bool,
+ pub id: Option<String>,
+ pub events: Option<Vec<AgentTraceEvent>>,
+ pub credits_used: Option<u32>,
+ pub active_browser_sessions: Option<Vec<AgentTraceActiveBrowserSession>>,
+ pub error: Option<String>,
+}
+
+/// Response from getting an artifact snapshot of an agent job.
+#[serde_with::skip_serializing_none]
+#[derive(Deserialize, Serialize, Debug, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentSnapshotResponse {
+ pub success: bool,
+ pub id: Option<String>,
+ pub snapshot_id: Option<String>,
+ /// Full artifact content as a JSON/string blob.
+ pub snapshot: Option<String>,
+ pub error: Option<String>,
+}
+
impl Client {
/// Starts an agent task asynchronously.
///
@@ -205,6 +488,83 @@ impl Client {
.await
}
+ /// Gets the execution trace of an agent task (spark-2 runs only).
+ ///
+ /// # Arguments
+ ///
+ /// * `id` - The agent task ID.
+ /// * `live_view` - Also include currently active browser sessions with
+ /// live view URLs.
+ ///
+ /// # Returns
+ ///
+ /// An `AgentTraceResponse` containing the ordered trace events.
+ pub async fn get_agent_trace(
+ &self,
+ id: impl AsRef<str>,
+ live_view: bool,
+ ) -> Result<AgentTraceResponse, FirecrawlError> {
+ let path = if live_view {
+ format!("/agent/{}/trace?liveView=true", id.as_ref())
+ } else {
+ format!("/agent/{}/trace", id.as_ref())
+ };
+
+ let response = self
+ .client
+ .get(self.url(&path))
+ .headers(self.prepare_headers(None))
+ .send()
+ .await
+ .map_err(|e| {
+ FirecrawlError::HttpError(format!("Getting agent trace {}", id.as_ref()), e)
+ })?;
+
+ self.handle_response(response, format!("agent trace {}", id.as_ref()))
+ .await
+ }
+
+ /// Gets the full content of an artifact snapshot referenced by a trace
+ /// event.
+ ///
+ /// # Arguments
+ ///
+ /// * `id` - The agent task ID.
+ /// * `snapshot_id` - Snapshot ID from an `artifact.updated` trace event.
+ ///
+ /// # Returns
+ ///
+ /// An `AgentSnapshotResponse` containing the snapshot content.
+ pub async fn get_agent_snapshot(
+ &self,
+ id: impl AsRef<str>,
+ snapshot_id: impl AsRef<str>,
+ ) -> Result<AgentSnapshotResponse, FirecrawlError> {
+ let response = self
+ .client
+ .get(self.url(&format!(
+ "/agent/{}/snapshots/{}",
+ id.as_ref(),
+ snapshot_id.as_ref()
+ )))
+ .headers(self.prepare_headers(None))
+ .send()
+ .await
+ .map_err(|e| {
+ FirecrawlError::HttpError(
+ format!(
+ "Getting agent snapshot {} of {}",
+ snapshot_id.as_ref(),
+ id.as_ref()
+ ),
+ e,
+ )
+ })?;
+
+ self.handle_response(response, format!("agent snapshot {}", id.as_ref()))
+ .await
+ }
+
/// Runs an agent task and waits for completion.
///
/// This method starts an agent task and polls until it completes, fails, or times out.
@@ -527,6 +887,229 @@ mod tests {
mock.assert();
}
+ #[test]
+ fn test_trace_events_deserialize_every_type() {
+ let base = json!({
+ "schemaVersion": 1,
+ "eventId": "018f3c5e-0000-7000-8000-000000000000",
+ "runId": "018f3c5e-0000-7000-8000-000000000001",
+ "occurredAt": "2026-08-26T12:00:00+00:00",
+ "producerSequence": 1,
+ "agent": {
+ "id": "018f3c5e-0000-7000-8000-000000000002",
+ "role": "orchestrator",
+ "name": "main"
+ }
+ });
+ let cases = [
+ ("run.started", json!({})),
+ ("run.cancel_requested", json!({"reason": "user"})),
+ (
+ "run.finished",
+ json!({"outcome": "credit_limit_reached", "error": {
+ "code": "credit_limit_reached",
+ "source": "billing",
+ "retryable": false,
+ "message": "out of credits"
+ }}),
+ ),
+ ("agent.started", json!({})),
+ (
+ "agent.finished",
+ json!({"outcome": "succeeded", "durationMs": 1234, "error": null}),
+ ),
+ ("browser.session.started", json!({"sessionId": "sess-1"})),
+ (
+ "browser.session.finished",
+ json!({"sessionId": "sess-1", "durationMs": 42}),
+ ),
+ (
+ "progress.reported",
+ json!({"phase": "working", "message": "reading page"}),
+ ),
+ ("reasoning.summary", json!({"text": "thinking"})),
+ (
+ "tool_call.started",
+ json!({"toolCallId": "tc-1", "toolName": "scrape", "parameters": {"url": "https://example.com"}}),
+ ),
+ (
+ "tool_call.finished",
+ json!({"toolCallId": "tc-1", "toolName": "scrape", "result": {"ok": true}}),
+ ),
+ (
+ "artifact.updated",
+ json!({"artifact": {
+ "kind": "json",
+ "artifactId": "result",
+ "path": "/workspace/data.json",
+ "snapshotId": "018f3c5e-0000-7000-8000-000000000003",
+ "change": "partial",
+ "changedFields": ["price"],
+ "itemCount": 3,
+ "sourceToolCallId": "tc-1"
+ }}),
+ ),
+ (
+ "error.occurred",
+ json!({"error": {
+ "code": "internal",
+ "source": "system",
+ "retryable": true,
+ "message": "boom"
+ }}),
+ ),
+ ];
+
+ for (event_type, extra) in cases {
+ let mut value = base.clone();
+ value
+ .as_object_mut()
+ .unwrap()
+ .extend(extra.as_object().unwrap().clone());
+ value["type"] = json!(event_type);
+
+ let event: AgentTraceEvent = serde_json::from_value(value.clone())
+ .unwrap_or_else(|e| panic!("{event_type} should deserialize: {e}"));
+ let round_tripped = serde_json::to_value(&event).unwrap();
+ assert_eq!(round_tripped["type"], json!(event_type));
+ }
+ }
+
+ #[tokio::test]
+ async fn test_get_agent_trace_with_mock() {
+ let mut server = mockito::Server::new_async().await;
+
+ let mock = server
+ .mock("GET", "/v2/agent/agent-123/trace")
+ .with_status(200)
+ .with_header("content-type", "application/json")
+ .with_body(
+ json!({
+ "success": true,
+ "id": "agent-123",
+ "events": [{
+ "schemaVersion": 1,
+ "eventId": "018f3c5e-0000-7000-8000-000000000000",
+ "runId": "018f3c5e-0000-7000-8000-000000000001",
+ "occurredAt": "2026-08-26T12:00:00+00:00",
+ "producerSequence": 1,
+ "agent": {
+ "id": "018f3c5e-0000-7000-8000-000000000002",
+ "role": "orchestrator",
+ "name": "main"
+ },
+ "type": "run.started"
+ }],
+ "creditsUsed": 5
+ })
+ .to_string(),
+ )
+ .create();
+
+ let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
+ let trace = client.get_agent_trace("agent-123", false).await.unwrap();
+
+ assert!(trace.success);
+ let events = trace.events.unwrap();
+ assert_eq!(events.len(), 1);
+ assert!(matches!(events[0], AgentTraceEvent::RunStarted(_)));
+ assert_eq!(trace.credits_used, Some(5));
+ assert!(trace.active_browser_sessions.is_none());
+ mock.assert();
+ }
+
+ #[tokio::test]
+ async fn test_get_agent_trace_with_live_view() {
+ let mut server = mockito::Server::new_async().await;
+
+ let mock = server
+ .mock("GET", "/v2/agent/agent-123/trace")
+ .match_query(Matcher::UrlEncoded("liveView".into(), "true".into()))
+ .with_status(200)
+ .with_header("content-type", "application/json")
+ .with_body(
+ json!({
+ "success": true,
+ "id": "agent-123",
+ "events": [],
+ "creditsUsed": 0,
+ "activeBrowserSessions": [{
+ "id": "sess-1",
+ "liveViewUrl": "https://browser.example.com/sess-1",
+ "viewport": {"width": 1280, "height": 720}
+ }]
+ })
+ .to_string(),
+ )
+ .create();
+
+ let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
+ let trace = client.get_agent_trace("agent-123", true).await.unwrap();
+
+ let sessions = trace.active_browser_sessions.unwrap();
+ assert_eq!(sessions.len(), 1);
+ assert_eq!(sessions[0].viewport.width, 1280);
+ mock.assert();
+ }
+
+ #[tokio::test]
+ async fn test_get_agent_snapshot_with_mock() {
+ let mut server = mockito::Server::new_async().await;
+
+ let mock = server
+ .mock(
+ "GET",
+ "/v2/agent/agent-123/snapshots/018f3c5e-0000-7000-8000-000000000003",
+ )
+ .with_status(200)
+ .with_header("content-type", "application/json")
+ .with_body(
+ json!({
+ "success": true,
+ "id": "agent-123",
+ "snapshotId": "018f3c5e-0000-7000-8000-000000000003",
+ "snapshot": "{\"price\": 42}"
+ })
+ .to_string(),
+ )
+ .create();
+
+ let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
+ let snapshot = client
+ .get_agent_snapshot("agent-123", "018f3c5e-0000-7000-8000-000000000003")
+ .await
+ .unwrap();
+
+ assert!(snapshot.success);
+ assert_eq!(snapshot.snapshot.unwrap(), "{\"price\": 42}");
+ mock.assert();
+ }
+
+ #[tokio::test]
+ async fn test_start_agent_sends_effort() {
+ let mut server = mockito::Server::new_async().await;
+
+ let mock = server
+ .mock("POST", "/v2/agent")
+ .match_body(Matcher::PartialJson(json!({"effort": "high"})))
+ .with_status(200)
+ .with_header("content-type", "application/json")
+ .with_body(json!({"success": true, "id": "agent-123"}).to_string())
+ .create();
+
+ let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
+ let options = AgentOptions {
+ prompt: "Find the contact information".to_string(),
+ effort: Some(AgentEffort::High),
+ ..Default::default()
+ };
+
+ let response = client.start_agent(options).await.unwrap();
+
+ assert!(response.success);
+ mock.assert();
+ }
+
#[tokio::test]
async fn test_get_agent_status_with_mock() {
let mut server = mockito::Server::new_async().await;
diff --git a/apps/rust-sdk/src/types.rs b/apps/rust-sdk/src/types.rs
index 4b027d34d..5fc37f622 100644
--- a/apps/rust-sdk/src/types.rs
+++ b/apps/rust-sdk/src/types.rs
@@ -1006,6 +1006,26 @@ pub enum AgentModel {
Unknown,
}
+/// Agent reasoning effort. Every level runs spark-2; the effort sets the
+/// reasoning budget inside it.
+#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum AgentEffort {
+ Low,
+ Medium,
+ High,
+ /// An effort level this SDK release does not know about.
+ ///
+ /// Read-only catch-all, same rationale as `AgentModel::Unknown`: the
+ /// server ships effort levels without an SDK release, and an exhaustive
+ /// enum would fail the whole `AgentStatusResponse` parse — and therefore
+ /// the status wait loop — the first time an unrecognized value came back.
+ /// Do not send this variant in a request; it serializes to `"unknown"`,
+ /// which the API rejects.
+ #[serde(other)]
+ Unknown,
+}
+
/// Search source types.
#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
@@ -1115,6 +1135,24 @@ mod tests {
assert_eq!(parsed, AgentModel::Unknown);
}
+ #[test]
+ fn test_agent_effort_unknown_degrades_instead_of_failing_the_parse() {
+ // Same as the model catch-all: an effort level the server ships before
+ // this SDK knows about must not take down status polling.
+ let parsed: AgentEffort =
+ serde_json::from_str("\"extreme\"").expect("unknown effort should deserialize");
+ assert_eq!(parsed, AgentEffort::Unknown);
+ for (name, expected) in [
+ ("low", AgentEffort::Low),
+ ("medium", AgentEffort::Medium),
+ ("high", AgentEffort::High),
+ ] {
+ let parsed: AgentEffort = serde_json::from_str(&format!("\"{name}\""))
+ .unwrap_or_else(|e| panic!("{name} should deserialize: {e}"));
+ assert_eq!(parsed, expected);
+ }
+ }
+
#[test]
fn test_full_document_with_array_metadata() {
let json = json!({