Sf ai agentforce observability
Agentforce session tracing extraction and analysis. TRIGGER when: user extracts STDM data from Data Cloud, analyzes agent session traces, debugs agent conversations via telemetry, or works with .parquet files from Agentforce. DO NOT TRIGGER when: testing agents (use sf-ai-agentforce-testing), Apex debug logs (use sf-debug), or building agents (use sf-ai-agentforce).
By- name:
- sf-ai-agentforce-observability
- description:
- Agentforce session tracing extraction and analysis. TRIGGER when: user extracts STDM data from Data Cloud, analyzes agent session traces, debugs agent conversations via telemetry, or works with .parquet files from Agentforce. DO NOT TRIGGER when: testing agents (use sf-ai-agentforce-testing), Apex debug logs (use sf-debug), or building agents (use sf-ai-agentforce).
sf-ai-agentforce-observability: Agentforce Session Tracing Extraction & Analysis
Use this skill when the user needs trace-based observability, not just testing: extract Session Tracing Data Model (STDM) records, work with Parquet datasets, reconstruct session timelines, analyze topic/action latency, or debug agent behavior from Data 360 telemetry.
When This Skill Owns the Task
Use sf-ai-agentforce-observability when the work involves:
- Data 360 / Session Tracing extraction
.parquetfiles from Agentforce telemetry- session timeline reconstruction
- trace-driven debugging of topic routing, action failures, or latency
- Polars / PyArrow-based analysis of large telemetry datasets
Delegate elsewhere when the user is:
- formally testing agents → sf-ai-agentforce-testing
- debugging Apex logs → sf-debug
- authoring or reconfiguring the agent itself → sf-ai-agentforce or sf-ai-agentscript
Prerequisites That Must Exist
Before extraction, verify:
- Data 360 is enabled
- Session Tracing is enabled
- the Salesforce Standard Data Model version is sufficient
- Einstein / Agentforce capabilities are enabled in the org
- JWT / ECA auth for Data 360 access is configured
If auth is missing, hand off to:
Deep setup guide:
What This Skill Works With
Core storage / analysis model
- extraction via Data 360 APIs
- Parquet for storage efficiency
- Polars for large-scale lazy analysis
Core STDM entities
At minimum, expect work around:
- session
- interaction / turn
- interaction step
- moment
- message
GenAI Trust Layer / audit records may also be relevant for content-quality and generation debugging.
Full schema:
Required Context to Gather First
Ask for or infer:
- target org alias
- time window or date range
- agent filter, if any
- whether the goal is extraction, summary analysis, or single-session debugging
- output location for extracted data
- whether the user already has Parquet files on disk
Recommended Workflow
1. Verify setup and auth
Confirm Data 360 tracing exists and JWT/ECA auth is working.
2. Choose the extraction mode
| Need | Default approach |
|---|---|
| recent telemetry snapshot | extract last N days |
| focused investigation | filtered extraction by date and agent |
| one broken conversation | extract or debug a single session tree |
| ongoing usage analytics | incremental extraction |
3. Extract to Parquet
Use the provided scripts under scripts/ rather than reimplementing extraction logic.
4. Analyze with Polars
Common analysis goals:
- session volume and duration
- topic distribution
- action step failures
- latency hotspots
- abandonment / escalation patterns
- session-level timeline reconstruction
5. Convert findings into next actions
Typical outcomes:
- topic mismatch → improve routing or descriptions
- action failure → inspect Flow / Apex implementation
- latency issue → optimize downstream action path
- test gap → add targeted agent tests
High-Signal Operational Rules
- treat STDM as read-only telemetry
- expect ingestion lag; this is not perfect real-time debugging
- use date filters and focused extraction to avoid unnecessary volume / query cost
- prefer Parquet over ad hoc JSON for durable analysis
- use lazy Polars patterns for large datasets
Common pitfalls:
- assuming missing data means no issue, when tracing may simply not be enabled
- running huge broad queries without date or agent filters
- trying to fix the agent inside this skill instead of handing off to authoring / testing skills
Output Format
When finishing, report in this order:
- What data was extracted or analyzed
- Scope (org, dates, agent filter, session IDs)
- Key findings
- Likely root causes
- Recommended next skill / next action
Suggested shape:
Observability task: <extract / analyze / debug-session>
Scope: <org, dates, agents, session ids>
Artifacts: <directories / parquet files>
Findings: <latency, routing, action, quality, abandonment patterns>
Root cause: <best current explanation>
Next step: <testing, agent fix, flow fix, apex fix>
Cross-Skill Integration
| Need | Delegate to | Reason |
|---|---|---|
| auth / JWT setup | sf-connected-apps | Data 360 access |
| fix agent routing / behavior | sf-ai-agentscript | authoring corrections |
| formal regression / coverage tests | sf-ai-agentforce-testing | reproducible test loops |
| Flow-backed action debugging | sf-flow | declarative repair |
| Apex-backed action debugging | sf-debug or sf-apex | code / log investigation |
Reference Map
Start here
- README.md
- references/basic-extraction.md
- references/filtered-extraction.md
- references/cli-reference.md
Data model / querying
Analysis / debugging
- references/analysis-cookbook.md
- references/analysis-examples.md
- references/debugging-sessions.md
- references/polars-cheatsheet.md
- references/agent-execution-lifecycle.md
Auth / troubleshooting
- references/auth-setup.md
- references/troubleshooting.md
- references/billing-and-troubleshooting.md
- references/builder-trace-api.md
- scripts/
Score Guide
| Score | Meaning |
|---|---|
| 90+ | strong telemetry-backed diagnosis |
| 75–89 | useful analysis with minor gaps |
| 60–74 | partial visibility only |
| < 60 | insufficient evidence; gather more telemetry |
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Agent Execution Lifecycle — 6-Phase Model
How the Agentforce platform processes each user message internally, based on live Builder trace captures. Maps AgentScript syntax to the 13 real-time trace step types.
Visual version: Generated runtime artifact at
~/.agent/diagrams/agent-execution-lifecycle.htmlwith Mermaid flowcharts, timing bars, and side-by-side script-to-trace mapping.
Data source: Live Builder traces from a test agent, sandbox org, 2026-02-25.
The 6 Phases
Every user message triggers this pipeline:
Phase 1: Input & Init (automatic — platform-managed)
Phase 2: Topic Selection (script-driven — AgentScript start_agent)
↓ Decision: LLM invoked go_* tool?
├─ Yes → Phase 3 + Phase 4
└─ No → Phase 5 (short-circuit)
Phase 3: Topic Transition (automatic — TransitionStep)
Phase 4: Topic Execution (LLM + actions — AgentScript topic)
Phase 5: Trust Layer (automatic — grounding + safety)
Phase 6: Response Delivery (automatic — final message)
Full path (Turn 1): 1 → 2 → 3 → 4 → 5 → 6 — 46 steps, 4.6s Short-circuit (Turn 2): 1 → 2 → 5 → 6 — 15 steps, 2.6s
The short-circuit occurs when the Topic Selector has enough conversation context to respond directly without routing to a topic.
Phase → Step Type Mapping
Phase 1: Input & Init
| Step Type | Count | Duration | Data |
|---|---|---|---|
| UserInputStep | 1 | 0ms | User message text |
| SessionInitialStateStep | 1 | 6ms | Locale, input, conversation context |
Phase 2: Topic Selection
| Step Type | Count | Duration | Data |
|---|---|---|---|
| NodeEntryStateStep | 1 | 5ms | 24 state variables for topic_selector |
| VariableUpdateStep | 3 | ~1ms each | Condition checks (routable_id, mutable_case_id) |
| BeforeReasoningStep | 1 | 5ms | 5 setup actions |
| VariableUpdateStep | 6 | ~1ms each | Progressive instruction assembly |
| BeforeReasoningIterationStep | 1 | 9ms | 8 actions (setup + instruction assembly) |
| EnabledToolsStep | 1 | 2ms | 5 tools (go_product_help, go_escalation, 3 guardrails) |
| LLMStep | 1 | 624ms | Tool invocation: go_product_help |
| VariableUpdateStep | 2 | 0ms | next_topic: "EMPTY" → "product_help" → "EMPTY" |
Phase 3: Topic Transition
| Step Type | Count | Duration | Data |
|---|---|---|---|
| TransitionStep | 1 | 0ms | topic_selector → product_help, type: handoff, mode: manual |
Phase 4: Topic Execution
| Step Type | Count | Duration | Data |
|---|---|---|---|
| NodeEntryStateStep | 1 | 0ms | State inherited from topic_selector |
| BeforeReasoningStep | 1 | 3ms | 3 setup actions |
| VariableUpdateStep | 1 | 0ms | Condition check |
| FunctionStep | 1 | 1313ms | "Update Session Routing" Flow action |
| VariableUpdateStep | 10+ | ~1ms each | session_routed → true, instruction assembly |
| BeforeReasoningIterationStep | 1 | 1363ms | 13 actions total |
| EnabledToolsStep | 1 | 4ms | 7 tools (confirm_at_home, confirm_not_home, wrap_up, exit_to_escalation, 3 guardrails) |
| LLMStep | 1 | 1045ms | Text response: "Are you currently at home..." |
| AfterReasoningStep | 1 | 2ms | turn_count: 0 → 1 |
Phase 5: Trust Layer
| Step Type | Count | Duration | Data |
|---|---|---|---|
| ReasoningStep | 1 | 1003ms | category: GROUNDED, reason: "follows mandatory first question" |
| PlannerResponseStep | 1 | 0ms | safety_score: 0.99, all category_scores: 0 |
Phase 6: Response Delivery
The PlannerResponseStep message is delivered to the user. No additional trace steps.
Script → Trace Mapping Quick Reference
| AgentScript Construct | Trace Step Type | Notes |
|---|---|---|
start_agent entry: |
NodeEntryStateStep | Initializes topic_selector state |
set @variables.x = ... |
VariableUpdateStep | One step per set statement |
instructions: -> with set |
VariableUpdateStep chain | Progressive instruction assembly |
actions: block |
EnabledToolsStep | Lists all available tools for the LLM |
reasoning: |
LLMStep | The actual LLM call with full prompt |
before_reasoning: |
BeforeReasoningStep | Setup actions before LLM call |
after_reasoning: |
AfterReasoningStep | Cleanup after LLM response |
run @actions.X |
FunctionStep | Flow/Apex action execution |
transition to / go_* |
TransitionStep | Topic-to-topic handoff |
if condition |
VariableUpdateStep | Condition → true/false on AgentScriptInternal_condition |
template(...) expression |
VariableUpdateStep | Evaluates template, updates agent_instructions |
Timing Analysis
Turn 1 (Full Path — 46 steps, 4,556ms)
| Component | Duration | Percentage |
|---|---|---|
| LLM calls (624 + 1045ms) | 1,669ms | 37% |
| Action calls (FunctionStep) | 1,313ms | 29% |
| Grounding evaluation | 1,003ms | 22% |
| Overhead (state, transitions) | 571ms | 12% |
Turn 2 (Short-Circuit — 15 steps, 2,564ms)
| Component | Duration | Percentage |
|---|---|---|
| LLM calls (1034ms) | 1,034ms | 40% |
| Action calls | 0ms | 0% |
| Grounding evaluation | 1,241ms | 49% |
| Overhead | 289ms | 11% |
Key insight: Grounding evaluation costs ~1s on every turn — as expensive as an LLM call. It's the fixed cost of Agentforce's safety guarantees.
Conversation Context Growth
The messages_sent[] array in LLMStep grows per turn:
- Turn 1: 3 messages (system prompt, user input, assembled instructions)
- Turn 2: 7 messages (system prompt, Turn 1 user/assistant/tool/assistant, Turn 2 user, instructions)
Each turn adds ~4 messages. After 10 turns, the LLM processes 30+ messages.
Dynamic Instruction Assembly
Each set on AgentScriptInternal_agent_instructions generates one VariableUpdateStep that appends a line via template evaluation. The instructions are reset to "" at the start of each phase and rebuilt from scratch.
Topic Selector assembly (Turn 1, 6 steps):
Step 7: "" → "\nCustomer: Test Customer"
Step 8: → + "This agent specializes in product troubleshooting..."
Step 9: → + "ROUTING:"
Step 10: → + "- ANY product issue → Product Help"
Step 11: → + "- Customer requests human agent → Escalation"
Step 12: → + "- ANY non-product request → Escalation"
The final value becomes the last system message in the LLM prompt.
State Variables (24 at Entry)
Full state captured at NodeEntryStateStep (Turn 1):
| Variable | Type | Initial Value | Purpose |
|---|---|---|---|
authenticated |
boolean | true | Pre-verified in session init |
customer_name |
string | "Test Customer" | Display name for templates |
at_home |
string | "unknown" | Controls instruction branching |
products_fetched |
boolean | false | Gates product lookup |
product_confirmed |
string | "pending" | Product selection state |
session_routed |
boolean | false | Set true after FunctionStep |
turn_count |
integer | 0 | Incremented in after_reasoning |
__user_input__ |
string | "My camera..." | Current message (auto-set) |
__resolved_locale__ |
string | "en_US" | Language for response |
__current_date_time__ |
string | ISO timestamp | Auto-updated each turn |
STDM Span Types (Testing Center Trace View)
When viewing session traces in Testing Center (not Builder), steps are collapsed into 6 color-coded span types:
| Span Type | Color | Maps to Builder Steps |
|---|---|---|
| TOPIC_STEP | Blue | NodeEntryStateStep, TransitionStep |
| LLM_STEP | Purple | LLMStep, EnabledToolsStep |
| ACTION_STEP | Green | FunctionStep |
| TRUST_GUARDRAILS_STEP | Orange | ReasoningStep, PlannerResponseStep |
| SESSION_END | Gray | Session termination |
| SYSTEM_STEP | Light gray | SessionInitialStateStep, VariableUpdateStep |
This mapping is critical for correlating Builder-level debugging with Testing Center trace analysis. A single TOPIC_STEP span in Testing Center may represent multiple NodeEntryStateStep + TransitionStep events at the Builder level.
Related Documents
- builder-trace-api.md — Reverse-engineered API endpoints and capture methodology
- data-model-reference.md — Complete 24-DMO STDM schema (persisted layer)
- query-patterns.md — Data Cloud SQL for persisted trace data
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Analysis Cookbook
Common analysis patterns using Polars for session tracing data.
Getting Started
from pathlib import Path
import polars as pl
# Load data as lazy frames (memory efficient)
data_dir = Path("./stdm_data")
sessions = pl.scan_parquet(data_dir / "sessions" / "**/*.parquet")
interactions = pl.scan_parquet(data_dir / "interactions" / "**/*.parquet")
steps = pl.scan_parquet(data_dir / "steps" / "**/*.parquet")
messages = pl.scan_parquet(data_dir / "messages" / "**/*.parquet")
Session Analysis
Basic Statistics
# Session count by agent
sessions.group_by("ssot__AiAgentApiName__c").agg(
pl.count().alias("session_count")
).sort("session_count", descending=True).collect()
Completion Rate by Agent
sessions.group_by("ssot__AiAgentApiName__c").agg([
pl.count().alias("total"),
pl.col("ssot__AiAgentSessionEndType__c")
.filter(pl.col("ssot__AiAgentSessionEndType__c") == "Completed")
.count().alias("completed")
]).with_columns([
(pl.col("completed") / pl.col("total") * 100).round(1).alias("completion_rate")
]).collect()
Session Duration Analysis
# Note: Requires timestamp parsing
sessions.with_columns([
pl.col("ssot__StartTimestamp__c").str.to_datetime().alias("start"),
pl.col("ssot__EndTimestamp__c").str.to_datetime().alias("end"),
]).with_columns([
(pl.col("end") - pl.col("start")).alias("duration")
]).group_by("ssot__AiAgentApiName__c").agg([
pl.col("duration").mean().alias("avg_duration"),
pl.col("duration").max().alias("max_duration"),
]).collect()
Interaction Analysis
Turns per Session
turns_per_session = (
interactions
.filter(pl.col("ssot__AiAgentInteractionType__c") == "TURN")
.group_by("ssot__AiAgentSessionId__c")
.agg(pl.count().alias("turn_count"))
)
# Distribution
turns_per_session.group_by("turn_count").agg(
pl.count().alias("sessions")
).sort("turn_count").collect()
Topic Routing
# Most common topics
interactions.filter(
pl.col("ssot__AiAgentInteractionType__c") == "TURN"
).group_by("ssot__TopicApiName__c").agg(
pl.count().alias("turn_count"),
pl.col("ssot__AiAgentSessionId__c").n_unique().alias("session_count")
).sort("turn_count", descending=True).collect()
Topic Switches (Multi-Topic Sessions)
# Sessions that used multiple topics
topic_counts = (
interactions
.filter(pl.col("ssot__AiAgentInteractionType__c") == "TURN")
.group_by("ssot__AiAgentSessionId__c")
.agg(pl.col("ssot__TopicApiName__c").n_unique().alias("topic_count"))
)
# Sessions with 2+ topics
topic_counts.filter(pl.col("topic_count") > 1).collect()
Step Analysis
LLM vs Action Ratio
steps.group_by("ssot__AiAgentInteractionStepType__c").agg(
pl.count().alias("count")
).with_columns([
(pl.col("count") / pl.col("count").sum() * 100).round(1).alias("percentage")
]).collect()
Most Used Actions
steps.filter(
pl.col("ssot__AiAgentInteractionStepType__c") == "ACTION_STEP"
).group_by("ssot__Name__c").agg(
pl.count().alias("invocations")
).sort("invocations", descending=True).head(20).collect()
Steps per Turn Distribution
steps_per_turn = (
steps
.group_by("ssot__AiAgentInteractionId__c")
.agg(pl.count().alias("step_count"))
)
steps_per_turn.group_by("step_count").agg(
pl.count().alias("turns")
).sort("step_count").collect()
Action Input/Output Analysis
# Parse JSON in action inputs (example for specific action)
action_steps = steps.filter(
(pl.col("ssot__AiAgentInteractionStepType__c") == "ACTION_STEP") &
(pl.col("ssot__Name__c") == "Get_Order_Status")
).collect()
# Parse inputs
import json
for row in action_steps.iter_rows(named=True):
input_data = json.loads(row["ssot__InputValueText__c"] or "{}")
output_data = json.loads(row["ssot__OutputValueText__c"] or "{}")
print(f"Input: {input_data}, Output: {output_data}")
Message Analysis
Message Length Distribution
messages.with_columns([
pl.col("ssot__ContentText__c").str.len_chars().alias("length")
]).group_by("ssot__AiAgentInteractionMessageType__c").agg([
pl.col("length").mean().alias("avg_length"),
pl.col("length").max().alias("max_length"),
]).collect()
Common User Phrases
# Word frequency in user messages (simple)
user_messages = messages.filter(
pl.col("ssot__AiAgentInteractionMessageType__c") == "INPUT"
).select("ssot__ContentText__c").collect()
# Count words
from collections import Counter
words = Counter()
for row in user_messages.iter_rows(named=True):
content = row["ssot__ContentText__c"] or ""
words.update(content.lower().split())
print(words.most_common(20))
Time-Based Analysis
Sessions by Date
sessions.with_columns([
pl.col("ssot__StartTimestamp__c").str.slice(0, 10).alias("date")
]).group_by("date").agg(
pl.count().alias("sessions")
).sort("date").collect()
Sessions by Hour
sessions.with_columns([
pl.col("ssot__StartTimestamp__c").str.slice(11, 2).alias("hour")
]).group_by("hour").agg(
pl.count().alias("sessions")
).sort("hour").collect()
Day of Week Analysis
# Requires datetime conversion
sessions.with_columns([
pl.col("ssot__StartTimestamp__c")
.str.to_datetime()
.dt.weekday()
.alias("weekday")
]).group_by("weekday").agg(
pl.count().alias("sessions")
).sort("weekday").collect()
Debugging Patterns
Find Failed Sessions
failed = sessions.filter(
pl.col("ssot__AiAgentSessionEndType__c").is_in(["Escalated", "Abandoned", "Failed"])
).sort("ssot__StartTimestamp__c", descending=True).collect()
for row in failed.head(5).iter_rows(named=True):
print(f"Session: {row['ssot__Id__c']}")
print(f" Agent: {row['ssot__AiAgentApiName__c']}")
print(f" End: {row['ssot__AiAgentSessionEndType__c']}")
print()
Session Timeline Reconstruction
def get_timeline(session_id: str) -> pl.DataFrame:
"""Reconstruct message timeline for a session."""
# Get interaction IDs
interaction_df = interactions.filter(
pl.col("ssot__AiAgentSessionId__c") == session_id
).collect()
interaction_ids = interaction_df["ssot__Id__c"].to_list()
# Get messages
msg_df = messages.filter(
pl.col("ssot__AiAgentInteractionId__c").is_in(interaction_ids)
).sort("ssot__MessageSentTimestamp__c").collect()
return msg_df
# Usage
timeline = get_timeline("a0x1234567890ABC")
for row in timeline.iter_rows(named=True):
msg_type = row["ssot__AiAgentInteractionMessageType__c"]
content = row["ssot__ContentText__c"]
icon = "→" if msg_type == "INPUT" else "←"
print(f"{icon} {content[:100]}...")
Performance Tips
Use Lazy Evaluation
# Good: Lazy evaluation, deferred execution
result = (
sessions
.filter(pl.col("ssot__AiAgentApiName__c") == "My_Agent")
.group_by("ssot__AiAgentSessionEndType__c")
.agg(pl.count())
.collect() # Execute here
)
# Avoid: Eager loading of everything
df = pl.read_parquet(data_dir / "sessions" / "**/*.parquet") # Loads all data
result = df.filter(...) # Then filter
Select Only Needed Columns
# Good: Select specific columns
sessions.select([
"ssot__Id__c",
"ssot__AiAgentApiName__c",
"ssot__AiAgentSessionEndType__c"
]).collect()
# Avoid: Select all columns
sessions.collect() # Includes all columns
Use Streaming for Large Results
# For very large datasets
for batch in sessions.collect(streaming=True):
# Process batch
pass
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Analysis Examples
Examples for analyzing extracted STDM data with Polars and the CLI.
CLI Analysis Commands
Summary Statistics
Get high-level overview of extracted data:
stdm-extract analyze --data-dir ./stdm_data
Output:
📊 SESSION SUMMARY
═══════════════════════════════════════════════════════════
Agent Sessions Completed Escalated Completion %
───────────────────────────────────────────────────────────────────────────
Customer_Support_Agent 450 382 45 84.9%
Order_Tracking_Agent 312 298 8 95.5%
FAQ_Agent 156 152 2 97.4%
───────────────────────────────────────────────────────────────────────────
TOTAL 918 832 55 90.6%
Topic Analysis
See which topics handle the most turns:
stdm-extract topics --data-dir ./stdm_data
Output:
📊 TOPIC ROUTING
═══════════════════════════════════════════════════════════
Topic Turns Sessions Avg Turns/Session
───────────────────────────────────────────────────────────────
Order_Status 1234 312 4.0
Return_Policy 856 245 3.5
Account_Help 654 198 3.3
General_FAQ 432 156 2.8
Action Analysis
See which actions are invoked most:
stdm-extract actions --data-dir ./stdm_data
Output:
📊 ACTION INVOCATIONS
═══════════════════════════════════════════════════════════
Action Count Avg/Session
─────────────────────────────────────────────────
Get_Order_Status 1856 2.0
Search_Knowledge_Base 1245 1.4
Create_Case 567 0.6
Update_Contact 234 0.3
Python Analysis
Setup
import polars as pl
from pathlib import Path
data_dir = Path("./stdm_data")
# Lazy loading (memory efficient)
sessions = pl.scan_parquet(data_dir / "sessions" / "**/*.parquet")
interactions = pl.scan_parquet(data_dir / "interactions" / "**/*.parquet")
steps = pl.scan_parquet(data_dir / "steps" / "**/*.parquet")
messages = pl.scan_parquet(data_dir / "messages" / "**/*.parquet")
Session Analysis
Sessions by End Type:
sessions.group_by("ssot__AiAgentSessionEndType__c").agg(
pl.count().alias("count")
).sort("count", descending=True).collect()
Daily Session Trend:
sessions.with_columns(
pl.col("ssot__StartTimestamp__c").str.slice(0, 10).alias("date")
).group_by("date").agg(
pl.count().alias("sessions")
).sort("date").collect()
Hourly Distribution:
sessions.with_columns(
pl.col("ssot__StartTimestamp__c").str.slice(11, 2).alias("hour")
).group_by("hour").agg(
pl.count().alias("sessions")
).sort("hour").collect()
Turn Analysis
Turns Per Session:
turns_per_session = (
interactions
.filter(pl.col("ssot__AiAgentInteractionType__c") == "TURN")
.group_by("ssot__AiAgentSessionId__c")
.agg(pl.count().alias("turns"))
)
# Distribution
turns_per_session.group_by("turns").agg(
pl.count().alias("sessions")
).sort("turns").collect()
Multi-Topic Sessions (Topic Switches):
topic_counts = (
interactions
.filter(pl.col("ssot__AiAgentInteractionType__c") == "TURN")
.group_by("ssot__AiAgentSessionId__c")
.agg(pl.col("ssot__TopicApiName__c").n_unique().alias("topics"))
)
# Sessions with 2+ topics
topic_counts.filter(pl.col("topics") > 1).collect()
Step Analysis
LLM vs Action Ratio:
steps.group_by("ssot__AiAgentInteractionStepType__c").agg(
pl.count().alias("count")
).with_columns(
(pl.col("count") / pl.col("count").sum() * 100).round(1).alias("percent")
).collect()
Most Used Actions:
steps.filter(
pl.col("ssot__AiAgentInteractionStepType__c") == "ACTION_STEP"
).group_by("ssot__Name__c").agg(
pl.count().alias("invocations")
).sort("invocations", descending=True).head(10).collect()
Steps Per Turn:
steps.group_by("ssot__AiAgentInteractionId__c").agg(
pl.count().alias("steps")
).group_by("steps").agg(
pl.count().alias("turns")
).sort("steps").collect()
Message Analysis
Average Message Length by Type:
messages.with_columns(
pl.col("ssot__ContentText__c").str.len_chars().alias("length")
).group_by("ssot__AiAgentInteractionMessageType__c").agg([
pl.col("length").mean().round(0).alias("avg_length"),
pl.col("length").max().alias("max_length"),
]).collect()
Common User Phrases:
user_msgs = messages.filter(
pl.col("ssot__AiAgentInteractionMessageType__c") == "INPUT"
).select("ssot__ContentText__c").collect()
from collections import Counter
words = Counter()
for row in user_msgs.iter_rows(named=True):
text = row["ssot__ContentText__c"] or ""
words.update(text.lower().split())
print(words.most_common(20))
Using the Analyzer Class
The skill includes a helper class for common analyses:
from scripts.analyzer import STDMAnalyzer
analyzer = STDMAnalyzer(Path("./stdm_data"))
# Quick summary
summary = analyzer.session_summary()
print(summary)
# Step breakdown
steps_df = analyzer.step_distribution()
print(steps_df)
# Topic patterns
topics_df = analyzer.topic_analysis()
print(topics_df)
# Find failed sessions
failed = analyzer.find_failed_sessions(limit=10)
print(failed)
Exporting Results
To CSV
result = sessions.group_by(...).agg(...).collect()
result.write_csv("output.csv")
To JSON
result.write_json("output.json")
To Parquet (for further analysis)
result.write_parquet("output.parquet")
Visualization (with Matplotlib)
import matplotlib.pyplot as plt
# Daily trend
daily = sessions.with_columns(
pl.col("ssot__StartTimestamp__c").str.slice(0, 10).alias("date")
).group_by("date").agg(
pl.count().alias("sessions")
).sort("date").collect()
plt.figure(figsize=(12, 4))
plt.bar(daily["date"], daily["sessions"])
plt.xticks(rotation=45)
plt.title("Sessions per Day")
plt.tight_layout()
plt.savefig("daily_trend.png")
See Also
- Polars Cheatsheet - Quick reference
- Analysis Cookbook - More recipes
- Debugging Sessions - Session-level debugging
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Authentication Setup
This skill uses JWT Bearer authentication to access the Data Cloud Query API. Authentication is configured via an External Client App (ECA) in Salesforce.
Prerequisites
- Salesforce CLI installed and authenticated to your org
- OpenSSL for certificate generation
- Data Cloud enabled in your org
- System Administrator profile (or appropriate permissions for ECA setup)
Quick Setup (5 Steps)
Step 1: Generate JWT Certificate
# Create directory for JWT keys
mkdir -p ~/.sf/jwt
# Generate private key and self-signed certificate (valid 1 year)
# Naming convention: {org_alias}-agentforce-observability.key
openssl req -x509 -sha256 -nodes -days 365 \
-newkey rsa:2048 \
-keyout ~/.sf/jwt/YourOrg-agentforce-observability.key \
-out ~/.sf/jwt/YourOrg-agentforce-observability.crt \
-subj "/CN=AgentforceObservability/O=YourOrg"
# Secure the private key (required - Salesforce rejects world-readable keys)
chmod 600 ~/.sf/jwt/YourOrg-agentforce-observability.key
Step 2: Create External Client App
In Salesforce Setup:
- Setup → External Client App Manager → New External Client App
- Fill in the basic details:
| Field | Value |
|---|---|
| Name | Agentforce Observability |
| API Name | Agentforce_Observability |
| Description | JWT Bearer auth for Agentforce STDM extraction via Claude Code |
| Distribution State | Local |
- Click Save
Step 3: Configure OAuth Settings
In the ECA → OAuth Settings tab:
| Setting | Value |
|---|---|
| Enable OAuth | ✅ Checked |
| Callback URL | https://login.salesforce.com/services/oauth2/callback |
| Selected OAuth Scopes | cdp_query_api, refresh_token, offline_access |
| Require PKCE | ❌ Unchecked (not needed for JWT Bearer) |
| Enable Client Credentials Flow | ❌ Optional |
Upload Certificate:
- Check Use digital signatures
- Click Choose File
- Upload
~/.sf/jwt/{org}-agentforce-observability.crt - Click Save
Step 4: Configure App Policies
In the ECA → Policies tab:
| Setting | Value |
|---|---|
| Permitted Users | Admin approved users are pre-authorized |
| IP Relaxation | Relax IP restrictions (for CLI usage) |
Add Your User:
- Click Manage → Manage Profiles or Manage Permission Sets
- Add your user's profile or an appropriate permission set
- Click Save
Step 5: Get Consumer Key & Test
- Go to ECA → OAuth Settings tab
- Copy the Consumer Key (starts with
3MVG9...) - Test authentication:
# Option 1: Pass consumer key directly
python3 scripts/cli.py test-auth \
--org YourOrg \
--consumer-key "3MVG9..."
# Option 2: Use environment variable
export SF_CONSUMER_KEY="3MVG9..."
python3 scripts/cli.py test-auth --org YourOrg
Expected output:
Testing Authentication
Org: YourOrg
Key: /Users/you/.sf/jwt/YourOrg-agentforce-observability.key
Getting org info...
Instance: https://your-org.my.salesforce.com
Username: your.user@example.com
Sandbox: True
Testing token generation...
✓ Token generated
Testing Data Cloud access...
✓ Data Cloud accessible
Authentication successful!
Key Path Resolution
The CLI resolves the private key path in this order:
- Explicit
--key-pathargument (highest priority) - App-specific key:
~/.sf/jwt/{org_alias}-agentforce-observability.key - Generic org key:
~/.sf/jwt/{org_alias}.key(fallback)
Examples
# Uses app-specific key automatically
python3 scripts/cli.py test-auth --org YourOrg --consumer-key "..."
# → Resolves to: ~/.sf/jwt/YourOrg-agentforce-observability.key
# Explicit key path (overrides all defaults)
python3 scripts/cli.py test-auth --org YourOrg \
--consumer-key "..." \
--key-path ~/.sf/jwt/custom-key.key
File Locations
| File | Location | Description |
|---|---|---|
| Private Key | ~/.sf/jwt/{org}-agentforce-observability.key |
RSA private key (chmod 600) |
| Certificate | ~/.sf/jwt/{org}-agentforce-observability.crt |
X.509 cert uploaded to Salesforce |
| Consumer Key | $SF_CONSUMER_KEY or --consumer-key |
From ECA OAuth Settings |
Required OAuth Scopes
| Scope | Purpose | Required |
|---|---|---|
cdp_query_api |
Execute Data Cloud SQL queries | ✅ Yes |
refresh_token, offline_access |
Server-to-server access | ✅ Yes |
cdp_profile_api |
Access profile and DMO metadata | Optional |
Troubleshooting
invalid_grant Error
RuntimeError: Token exchange failed: invalid_grant
Causes & Fixes:
| Cause | Fix |
|---|---|
| Certificate mismatch | Re-upload .crt file to ECA |
| Expired certificate | Regenerate with openssl (see Step 1) |
| User not authorized | Add user to ECA policies (see Step 4) |
| Wrong login URL | Verify sandbox detection is working |
Verify certificate expiry:
openssl x509 -enddate -noout -in ~/.sf/jwt/YourOrg-agentforce-observability.crt
403 Forbidden
RuntimeError: Access denied: Ensure ECA has cdp_query_api scope
Fix: Add cdp_query_api scope to the ECA OAuth Settings.
Key Not Found
FileNotFoundError: Private key not found at ~/.sf/jwt/myorg.key
Causes:
- Key file doesn't exist → Generate with Step 1
- Wrong org alias → Check
sf org listfor correct alias - Using old naming convention → Rename to
{org}-agentforce-observability.key
Permission Denied on Key
PermissionError: [Errno 13] Permission denied: '~/.sf/jwt/...'
Fix:
chmod 600 ~/.sf/jwt/*.key
Sandbox vs Production
The skill automatically detects sandbox orgs:
- Reads
isSandboxfromsf org display --json - Uses
https://test.salesforce.comfor token exchange (sandboxes) - Uses
https://login.salesforce.comfor production
No additional configuration needed.
Security Best Practices
- Protect private keys: Always
chmod 600 ~/.sf/jwt/*.key - Rotate certificates annually: Regenerate before expiration
- Use separate ECAs: One per org/environment for isolation
- Never commit keys: Add
*.keyto.gitignore - Audit access: Review ECA usage in Setup → Security → Connected Apps OAuth Usage
Environment Variables
For automation/CI, set these environment variables:
# Consumer key (org-specific takes priority)
export SF_YOURORG_CONSUMER_KEY="3MVG9..."
# or generic fallback
export SF_CONSUMER_KEY="3MVG9..."
The CLI checks in this order:
--consumer-keyargumentSF_{ORG_ALIAS}_CONSUMER_KEY(uppercase, hyphens to underscores)SF_CONSUMER_KEY
See Also
- sf-connected-apps skill - General ECA patterns
- CLI Reference - All command options
- Troubleshooting - More error solutions
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Basic Extraction Examples
Simple examples to get started with STDM extraction.
Prerequisites
- JWT authentication configured (see Auth Setup)
- Consumer key set:
export SF_CONSUMER_KEY="3MVG9..." - Org alias available in
sf org list
Example 1: Extract Last 7 Days
The simplest extraction - all sessions from the last 7 days:
stdm-extract extract --org prod
Output structure:
./stdm_data/
├── sessions/
│ └── data.parquet
├── interactions/
│ └── data.parquet
├── steps/
│ └── data.parquet
└── messages/
└── data.parquet
Example 2: Extract Last 24 Hours
stdm-extract extract --org prod --days 1
Example 3: Custom Output Directory
stdm-extract extract --org prod --output /data/agentforce/prod
Example 4: Verbose Mode
See detailed progress and timing:
stdm-extract extract --org prod --verbose
Sample output:
🔐 Authenticating to Data Cloud...
Instance URL: https://myorg.my.salesforce.com
📊 Extracting sessions...
Query: SELECT ... FROM ssot__AIAgentSession__dlm WHERE ...
Records: 1,234 (2.3s)
📊 Extracting interactions...
Records: 5,678 (4.1s)
📊 Extracting steps...
Records: 12,345 (8.7s)
📊 Extracting messages...
Records: 9,876 (5.2s)
✅ Extraction complete!
Total records: 29,133
Duration: 20.3s
Output: ./stdm_data/
Example 5: Test Authentication First
Before extracting, verify your setup:
stdm-extract test-auth --org prod
Success:
✅ Authentication successful
Instance URL: https://myorg.my.salesforce.com
Token valid for: 3599 seconds
Failure:
❌ Authentication failed
Error: invalid_grant
Hint: Check certificate expiration with:
openssl x509 -enddate -noout -in ~/.sf/jwt/prod.key
Example 6: Count Records Before Extraction
Check how much data exists without downloading:
stdm-extract count --org prod --dmo sessions
Output:
📊 Record counts for prod:
Sessions: 12,345
Example 7: Extract from Sandbox
Works the same as production - just use the sandbox alias:
# List your orgs
sf org list
# Extract from sandbox
stdm-extract extract --org mysandbox --days 3
What's Next?
- Filtered Extraction - Filter by agent, date range
- Analysis Examples - Analyze extracted data
- Debugging Sessions - Debug specific sessions
Quick Reference
| Task | Command |
|---|---|
| Last 7 days | stdm-extract extract --org prod |
| Last N days | stdm-extract extract --org prod --days N |
| Test auth | stdm-extract test-auth --org prod |
| Check counts | stdm-extract count --org prod |
| Verbose mode | Add --verbose to any command |
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Billing Considerations & Troubleshooting
Billing Considerations
Reference: Billing Considerations for Agentforce Session Tracing
Agentforce Session Tracing consumes Data 360 credits for ingestion, storage, and processing.
Credit Consumption
| Usage Type | Digital Wallet Card | Description |
|---|---|---|
| Batch Data Pipeline | Data Services | Records ingested via data streams. ~24 records per LLM round-trip. Primary cost driver. |
| Data Queries | Data Services | Records processed when running queries, reports, dashboards |
| Streaming Calculated Insights | Data Services | Used for Prompt Builder usage and feedback metrics |
| Storage Beyond Allocation | Data Storage | Storage consumed above allocated amount |
Cost Estimation
Records per session ≈ Turns × 24 (avg per LLM call)
Daily records ≈ Sessions/day × Avg turns × 24
Example:
1,000 sessions/day × 4 turns × 24 = 96,000 records/day ingested
Tip: Use Digital Wallet for near real-time consumption tracking.
Common Issues & Fixes
| Error | Cause | Fix |
|---|---|---|
401 Unauthorized |
JWT auth expired/invalid | Refresh token or reconfigure ECA |
No session data |
Tracing not enabled | Enable Session Tracing in Agent Settings |
Query timeout |
Too much data | Add date filters, use incremental |
Memory error |
Loading all data | Use Polars lazy frames |
Missing DMO |
Wrong API version | Use API v60.0+ |
See references/troubleshooting.md for detailed solutions.
Agentforce Credit Costs (Cross-Reference)
When analyzing traces for performance optimization, understanding credit costs per step type is critical:
| Step Type | Credit Cost | Notes |
|---|---|---|
Framework operations (before/after_reasoning, set, if/else, @utils.*) |
FREE | No credit consumption |
| Prompt Template invocations | 2-16 credits/call | Varies by template complexity |
| Flow/Apex action executions | 20 credits/call | Most expensive step type |
Optimization insight: When trace analysis reveals excessive action calls, consider consolidating multiple Flow actions into a single Apex action or using framework-level set operations where possible.
See sf-ai-agentscript/references/production-gotchas.md for the full credit consumption model and optimization strategies.
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Builder Trace API — Reverse-Engineered Internal Endpoint
How the Agentforce Builder's "Trace" tab renders real-time execution telemetry, the exact internal API endpoints, request/response schemas, and how to capture trace data programmatically.
Status: ✅ Confirmed via live network capture (February 2026).
Two-Layer Trace Architecture
The Agentforce Builder's Trace tab is powered by two distinct systems:
Layer 1: Real-Time Execution Trace (Aura Controller)
The live trace rendered during Builder testing uses an Aura controller action — confirmed via CDP network capture:
| Aspect | Detail |
|---|---|
| Endpoint | serviceComponent://ui.agent.authoring.components.aura.controller.AgentAuthoringController/ACTION$getSimulationPlanTraces |
| Protocol | Aura framework (POST to /aura) |
| Auth | Cookie-based browser session (no explicit Authorization header) |
| Trigger | Called automatically after SSE stream delivers INFORM event |
| Input | { planId, sessionId, version: "1.0" } |
| Output | PlanSuccessResponse with plan[] array of 13 step types |
| Latency | Real-time (called after agent responds) |
| Persistence | Transient — not stored in STDM |
Layer 2: Persisted Session Tracing (STDM in Data Cloud)
After 5-15 minutes, a subset of trace data is persisted to Data Cloud across 24 DMOs:
| Aspect | Detail |
|---|---|
| Storage | Data Cloud (Data 360) |
| Query API | Data Cloud Query API (SQL-like) |
| Auth | JWT Bearer via External Client App |
| Step Types | 5 (vs 13 in real-time trace) |
| Retention | 13 months (prod) / 30 days (sandbox) |
See data-model-reference.md and query-patterns.md for full STDM documentation.
Confirmed Architecture
The Builder uses a two-phase request pattern per user message:
Phase 1: Message Delivery (SSE Stream)
┌─────────────────────────────────────────────────────────────────┐
│ Builder LWC → POST /einstein/ai-agent/v1/sessions/{id}/ │
│ messages/stream │
│ Auth: Bearer token (JWT) │
│ Body: {"message":{"type":"Text","text":"...","sequenceId":"N"}} │
│ │
│ Response: SSE stream with events: │
│ event: TEXT_CHUNK → streaming word-by-word response │
│ event: INFORM → final message + planId + feedbackId │
│ event: END_OF_TURN → turn complete │
└─────────────────────────────────────────────────────────────────┘
│
│ planId from INFORM event
▼
Phase 2: Trace Retrieval (Aura Controller)
┌─────────────────────────────────────────────────────────────────┐
│ Builder LWC → POST /aura │
│ Descriptor: AgentAuthoringController/getSimulationPlanTraces │
│ Auth: Browser cookies (X-SFDC-Page-Cache, X-SFDC-Request-Id) │
│ Params: { planId, sessionId, version: "1.0" } │
│ │
│ Response: PlanSuccessResponse with plan[] array │
│ → 13 step types, full variable state, LLM prompts, timing │
└─────────────────────────────────────────────────────────────────┘
Key discovery: The planId returned in the SSE INFORM event is the same ID used to fetch the trace. This links the message stream to the execution trace.
SSE Stream Schema (/messages/stream)
Request
POST https://api.salesforce.com/einstein/ai-agent/v1/sessions/{sessionId}/messages/stream
Authorization: Bearer {jwt_token}
Content-Type: application/json
x-salesforce-region: us-west-2
X-B3-TraceId: {distributed_trace_id}
X-B3-SpanId: {span_id}
{
"message": {
"type": "Text",
"text": "Where is my order?",
"sequenceId": "1"
}
}
SSE Event Types
| Event Type | Purpose | Key Fields |
|---|---|---|
TEXT_CHUNK |
Streaming response text | offset, message.message (word/phrase) |
INFORM |
Final complete response | message.message, planId, feedbackId, isContentSafe, citedReferences[] |
END_OF_TURN |
Turn completion marker | message.type: "EndOfTurn" |
INFORM Event Schema (Critical — Contains planId)
{
"timestamp": 1772000000000,
"originEventId": "1772000000000-REQ",
"traceId": "00000000000000001234567890abcdef",
"offset": 0,
"message": {
"type": "Inform",
"feedbackId": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"isContentSafe": true,
"message": "I can help you with that. Let me look into it...",
"id": "11111111-2222-3333-4444-555555555555",
"metrics": {},
"planId": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"result": [],
"citedReferences": []
}
}
Note:
planIdandfeedbackIdare identical in the observed capture.
Trace API Schema (getSimulationPlanTraces)
Request (Aura)
POST /aura
Content-Type: application/x-www-form-urlencoded
X-SFDC-Page-Cache: {page_cache_id}
X-SFDC-Request-Id: {request_id}
X-B3-TraceId: {trace_id}
URL-encoded body (decoded):
{
"actions": [{
"id": "48;a",
"descriptor": "serviceComponent://ui.agent.authoring.components.aura.controller.AgentAuthoringController/ACTION$getSimulationPlanTraces",
"callingDescriptor": "UNKNOWN",
"params": {
"planId": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"sessionId": "019xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"version": "1.0"
}
}]
}
Response: PlanSuccessResponse
{
"type": "PlanSuccessResponse",
"planId": "aaaaaaaa-...",
"sessionId": "019xxxxx-...",
"intent": "DefaultTopic",
"topic": "DefaultTopic",
"plan": [
{ "type": "UserInputStep", ... },
{ "type": "SessionInitialStateStep", ... },
{ "type": "EnabledToolsStep", ... },
{ "type": "LLMStep", ... },
...
]
}
Complete Step Type Taxonomy (13 Types)
For the full execution lifecycle and how these steps map to AgentScript syntax, see agent-execution-lifecycle.md.
Captured from a single agent turn (46 steps total):
| Step Type | Count | Description | Key Data Fields |
|---|---|---|---|
VariableUpdateStep |
28 | Variable state change | variable_updates[].{variable_name, variable_past_value, variable_new_value, variable_change_reason, directive_context} |
BeforeReasoningIterationStep |
3 | Pre-iteration setup | agent_name, action_names[] |
NodeEntryStateStep |
2 | Topic/agent entry | agent_name, directive_context, state_variables{} |
BeforeReasoningStep |
2 | Pre-reasoning setup | agent_name, action_names[] |
EnabledToolsStep |
2 | Available tools list | agent_name, enabled_tools[], directive_context |
LLMStep |
2 | LLM call with full prompt | agent_name, prompt_name, prompt_content, execution_latency, messages_sent[], tools_sent[], response_messages[] |
UserInputStep |
1 | User message | message |
SessionInitialStateStep |
1 | Session init state | variable_values{}, directive_context |
TransitionStep |
1 | Topic transition | from_agent, to_agent, current_state{}, transition_type, transition_mode, directive_context |
FunctionStep |
1 | Flow/Apex action | function.{name, input{}, output{}, errors}, executionLatency |
AfterReasoningStep |
1 | Post-reasoning cleanup | agent_name, action_names[] |
ReasoningStep |
1 | Grounding evaluation | category (GROUNDED/UNGROUNDED), reason |
PlannerResponseStep |
1 | Final response | message, responseType, isContentSafe, safetyScore.category_scores{} |
Common Fields (All Step Types)
Every step has:
{
"startExecutionTime": 1772000000000,
"endExecutionTime": 1772000000000,
"type": "StepTypeName"
}
Timestamps are Unix epoch milliseconds.
Detailed Step Schemas
LLMStep (Most Data-Rich)
Contains the full LLM prompt, tool definitions, and response — the most valuable step for debugging.
{
"startExecutionTime": 1772000001000,
"endExecutionTime": 1772000002880,
"type": "LLMStep",
"data": {
"agent_name": "Topic Selector",
"prompt_name": "topic_selector_prompt",
"prompt_content": "[full prompt string, 4000+ chars]",
"prompt_response": null,
"execution_latency": 1879
},
"messages_sent": [
{"role": "system", "content": "Topic Selector & Safety Router..."},
{"role": "user", "content": "I need help with my order"},
{"role": "system", "content": "Customer: Jane Doe..."}
],
"tools_sent": [
"go_order_support",
"go_escalation",
"Inappropriate_Content",
"Prompt_Injection",
"Reverse_Engineering"
],
"response_messages": [
{"role": "assistant", "content": "", "tool_invocation": {"name": "go_order_support", "arguments": "{}"}}
]
}
FunctionStep (Action Execution)
Shows Flow/Apex invocation with input/output:
{
"startExecutionTime": 1772000003000,
"endExecutionTime": 1772000005675,
"type": "FunctionStep",
"function": {
"name": "Get_Order_Status",
"input": {"orderId": "ORD-12345"},
"output": {"status": "Shipped", "trackingNumber": "1Z999..."},
"errors": null
},
"executionLatency": 2675
}
TransitionStep (Topic Routing)
Shows topic-to-topic transitions with full state:
{
"startExecutionTime": 1772000002900,
"endExecutionTime": 1772000002900,
"type": "TransitionStep",
"data": {
"from_agent": "Topic Selector",
"to_agent": "order_support",
"current_state": {"authenticated": true, "customer_name": "Jane Doe", "...": "..."},
"transition_type": "ROUTING",
"transition_mode": "DIRECT",
"directive_context": "on_message"
}
}
PlannerResponseStep (Final Output + Safety)
Contains the safety score breakdown:
{
"startExecutionTime": 1772000006800,
"endExecutionTime": 1772000006800,
"type": "PlannerResponseStep",
"message": "I can help you track your order. Let me look that up...",
"responseType": "Inform",
"isContentSafe": true,
"safetyScore": {
"safetyScore": {
"safety_score": 0.99,
"category_scores": {
"toxicity": 0, "hate": 0, "identity": 0, "violence": 0,
"physical": 0, "sexual": 0, "profanity": 0, "biased": 0
}
}
}
}
ReasoningStep (Grounding Evaluation)
The agent's self-assessment of response quality:
{
"startExecutionTime": 1772000005600,
"endExecutionTime": 1772000006800,
"type": "ReasoningStep",
"category": "GROUNDED",
"reason": "The response follows the mandatory first question as instructed..."
}
Real-Time → STDM Field Mapping (Confirmed)
| Real-Time Step Type (13) | Persisted STDM Step Type (5) | Data Loss |
|---|---|---|
UserInputStep |
AIAgentInteractionMessage (Input type) |
None |
SessionInitialStateStep |
Not directly persisted | Full state lost |
NodeEntryStateStep |
TOPIC_STEP (partially) |
State variables lost |
VariableUpdateStep |
PreStepVariableText__c / PostStepVariableText__c |
Change reasons lost |
BeforeReasoningStep |
Not persisted | Action list lost |
BeforeReasoningIterationStep |
Not persisted | Iteration data lost |
EnabledToolsStep |
Not persisted | Tool list lost |
LLMStep |
LLM_STEP |
Full prompt content lost; only input/output summaries kept |
TransitionStep |
TOPIC_STEP (partially) |
Transition mode/type lost |
FunctionStep |
ACTION_STEP |
Input/output preserved; latency lost |
AfterReasoningStep |
Not persisted | Cleanup data lost |
ReasoningStep |
LLM_STEP (ReactValidationPrompt) |
Grounding category/reason lost |
PlannerResponseStep |
AIAgentInteractionMessage (Output type) |
Safety scores lost; content preserved |
Key finding: The real-time trace contains 13 step types vs 5 in STDM. The most valuable debugging data (full LLM prompts, variable change reasons, safety scores, grounding evaluations) is not persisted to Data Cloud.
Other Discovered Endpoints
postInteractionSummary (Aura)
Called after trace retrieval. Sends the full agent script + conversation back for analytics:
Descriptor: aura://AuthoringAgentFamilyController/ACTION$postInteractionSummary
Params: {
authoringAgentInteractionSummaryInputRepresentation: {
projectId: "{project_id}",
currentAFScript: "[full agent script JSON]",
...
}
}
EvfSdkController/publishEvent (Aura Telemetry)
Client-side observability events tagged COPILOT_O11Y:
Descriptor: aura://EvfSdkController/ACTION$publishEvent
Params: {
event: {
contextualData: {
loggerName: "COPILOT_O11Y",
loggerAppName: "AgentAuthoring:agentAuthoringBuilder"
},
feature: "EINSTEIN_..."
}
}
Auth Patterns (Confirmed)
| Endpoint | Auth Method | Header |
|---|---|---|
SSE Stream (/messages/stream) |
JWT Bearer token | Authorization: Bearer eyJ... |
Aura Trace (/aura + getSimulationPlanTraces) |
Browser cookies | X-SFDC-Page-Cache, X-SFDC-Request-Id (no Authorization header) |
Aura Telemetry (/aura + instrumentation) |
Browser cookies | Same as above |
Important: The trace endpoint (
getSimulationPlanTraces) uses cookie-based auth only. It cannot be called with a standalone JWT token. You must maintain a browser session.
Capture Methodology
Option 1: CLI Preview Commands (Recommended)
The sf agent preview start/send/end commands provide programmatic access to the same v1.1 trace data without browser automation:
# Start session → send utterance → end and get traces
SESSION_ID=$(sf agent preview start --api-name My_Agent --target-org myOrg --json 2>/dev/null | jq -r '.result.sessionId')
PLAN_ID=$(sf agent preview send --session-id "$SESSION_ID" --api-name My_Agent --utterance "test" --target-org myOrg --json 2>/dev/null | jq -r '.result.messages[-1].planId')
TRACES_PATH=$(sf agent preview end --session-id "$SESSION_ID" --api-name My_Agent --target-org myOrg --json 2>/dev/null | jq -r '.result.tracesPath')
# Analyze trace
jq '.' "$TRACES_PATH/$PLAN_ID.json"
For full workflow details, see sf-ai-agentforce-testing Phase F: trace-enriched preview testing. If you use
--authoring-bundleinstead of--api-name, remember thatpreview startnow requires an explicit mode flag:--simulate-actionsor--use-live-actions.
Option 2: Manual HAR Export (Fallback)
- Open DevTools (
Cmd+Opt+I) → Network tab - Enable: ✅ Preserve log, ✅ Disable cache, Filter: Fetch/XHR
- Send test messages in Builder
- Right-click → "Save all as HAR with content"
- Analyze with
jqor the trace analyzer insf-ai-agentforce-testing
Key Findings
- The trace endpoint (
getSimulationPlanTraces) returns the fullPlanSuccessResponsewith 13 step types - CLI approach (
sf agent preview) saves traces as JSON files automatically — no network interception needed - Trace files contain complete LLM prompts, safety scores, grounding assessments, and action I/O
Capture Log
Use this section to track your own capture sessions.
Org: [your org alias]
Agent: [agent API name]
Session ID: [from SSE stream URL]
Plan ID: [from INFORM event planId]
User message: [test utterance]
Total requests: [seen], [captured]
SSE streams: [count]
Step types found: [count]
Steps in trace: [count]
Key findings from initial investigation:
- Architecture is Aura-based (Hypothesis A confirmed)
- SSE stream at
api.salesforce.comdelivers messages; trace is fetched separately via Aura - 13 step types in real-time vs 5 in persisted STDM
- Full LLM prompts, tool lists, and safety scores available only in real-time trace
planIdfrom INFORM event links messages to trace- Cookie auth required for trace (no standalone API access)
Programmatic Access Comparison
| API | Trace Depth | Step Types | Full Prompts | Safety Scores | Auth | Docs |
|---|---|---|---|---|---|---|
| Builder Trace (this doc) | 13 step types, full state | 13 | ✅ Yes | ✅ Yes | Browser cookies | Internal |
| Data Cloud STDM | 5 step types, summaries | 5 | ❌ No | ❌ No | JWT Bearer | query-patterns.md |
| Testing API | Actions + topic only | N/A | ❌ No | ❌ No | OAuth | Salesforce Docs |
| Agent Runtime API | Messages only — no trace | N/A | ❌ No | ❌ No | OAuth | Salesforce Docs |
Related Documents
- Data Model Reference — Complete 24-DMO STDM schema (persisted layer)
- Query Patterns — Data Cloud SQL examples for persisted trace data
- Debugging Sessions — Session timeline reconstruction from STDM
- Auth Setup — JWT Bearer configuration for Data Cloud access
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->CLI Reference
Complete command reference for the stdm-extract CLI tool.
Global Options
| Option | Description |
|---|---|
--help |
Show help message and exit |
--version |
Show version number |
Commands
extract
Extract session tracing data for a date range.
stdm-extract extract --org <alias> [options]
Options:
| Option | Type | Default | Description |
|---|---|---|---|
--org |
String | Required | Salesforce org alias (from sf org list) |
--consumer-key |
String | $SF_CONSUMER_KEY |
ECA consumer key |
--days |
Integer | 7 | Extract last N days |
--since |
DateTime | None | Start date (ISO format) |
--until |
DateTime | Now | End date (ISO format) |
--agent |
String | None | Filter by agent API name (repeatable) |
--output |
Path | ./stdm_data |
Output directory |
--verbose |
Flag | False | Enable verbose logging |
Examples:
# Last 7 days for all agents
stdm-extract extract --org prod
# Specific date range
stdm-extract extract --org prod --since 2026-01-01 --until 2026-01-15
# Filter by agent
stdm-extract extract --org prod --agent Customer_Support_Agent
# Multiple agents
stdm-extract extract --org prod --agent Agent1 --agent Agent2
extract-tree
Extract complete session tree for specific session IDs.
stdm-extract extract-tree --org <alias> --session-ids <ids> [options]
Options:
| Option | Type | Default | Description |
|---|---|---|---|
--org |
String | Required | Salesforce org alias |
--consumer-key |
String | $SF_CONSUMER_KEY |
ECA consumer key |
--session-ids |
String | Required | Comma-separated session IDs |
--output |
Path | ./stdm_data |
Output directory |
--verbose |
Flag | False | Enable verbose logging |
Example:
stdm-extract extract-tree --org prod --session-ids "a0x001,a0x002,a0x003"
extract-incremental
Incremental extraction based on last run timestamp.
stdm-extract extract-incremental --org <alias> [options]
Options:
| Option | Type | Default | Description |
|---|---|---|---|
--org |
String | Required | Salesforce org alias |
--consumer-key |
String | $SF_CONSUMER_KEY |
ECA consumer key |
--output |
Path | ./stdm_data |
Output directory |
--verbose |
Flag | False | Enable verbose logging |
Notes:
- Watermark stored at
~/.sf/observability/{org}/watermark.json - First run extracts last 24 hours
- Subsequent runs extract since last watermark
Example:
# First run: extracts last 24 hours
stdm-extract extract-incremental --org prod
# Subsequent runs: extracts only new data
stdm-extract extract-incremental --org prod
analyze
Generate summary statistics from extracted data.
stdm-extract analyze --data-dir <path> [options]
Options:
| Option | Type | Default | Description |
|---|---|---|---|
--data-dir |
Path | Required | Directory containing Parquet files |
--format |
Choice | table |
Output format: table, json, csv |
Example:
stdm-extract analyze --data-dir ./stdm_data --format table
debug-session
Debug a specific session with full message timeline.
stdm-extract debug-session --data-dir <path> --session-id <id> [options]
Options:
| Option | Type | Default | Description |
|---|---|---|---|
--data-dir |
Path | Required | Directory containing Parquet files |
--session-id |
String | Required | Session ID to debug |
--verbose |
Flag | False | Show step details (LLM, actions) |
--output |
Path | None | Export timeline to JSON |
Example:
# View timeline in terminal
stdm-extract debug-session --data-dir ./stdm_data --session-id "a0x123"
# Export to JSON with full details
stdm-extract debug-session --data-dir ./stdm_data --session-id "a0x123" \
--verbose --output ./debug/session.json
topics
Analyze topic routing patterns.
stdm-extract topics --data-dir <path> [options]
Options:
| Option | Type | Default | Description |
|---|---|---|---|
--data-dir |
Path | Required | Directory containing Parquet files |
--format |
Choice | table |
Output format: table, json |
Example:
stdm-extract topics --data-dir ./stdm_data
actions
Analyze action invocation patterns.
stdm-extract actions --data-dir <path> [options]
Options:
| Option | Type | Default | Description |
|---|---|---|---|
--data-dir |
Path | Required | Directory containing Parquet files |
--agent |
String | None | Filter by agent API name |
--format |
Choice | table |
Output format: table, json |
Example:
stdm-extract actions --data-dir ./stdm_data --agent Customer_Support_Agent
count
Count records in Data Cloud (quick check without extraction).
stdm-extract count --org <alias> [options]
Options:
| Option | Type | Default | Description |
|---|---|---|---|
--org |
String | Required | Salesforce org alias |
--consumer-key |
String | $SF_CONSUMER_KEY |
ECA consumer key |
--dmo |
Choice | sessions |
DMO to count |
Example:
stdm-extract count --org prod --dmo sessions
test-auth
Test authentication to Data Cloud.
stdm-extract test-auth --org <alias> [options]
Options:
| Option | Type | Default | Description |
|---|---|---|---|
--org |
String | Required | Salesforce org alias |
--consumer-key |
String | $SF_CONSUMER_KEY |
ECA consumer key |
Example:
stdm-extract test-auth --org prod
Environment Variables
| Variable | Description |
|---|---|
SF_CONSUMER_KEY |
Default consumer key for ECA |
SF_JWT_KEY_PATH |
Override JWT private key location (default: ~/.sf/jwt/{org}.key) |
Exit Codes
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 2 | Authentication failed |
| 3 | Data not found |
| 4 | Invalid arguments |
See Also
- Auth Setup - Setting up JWT authentication
- Polars Cheatsheet - Quick analysis commands
- Troubleshooting - Common issues
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->STDM Query Walkthrough - Client Demo
Step-by-step queries for exploring Session Tracing Data Model in Data Cloud Query Console.
Data Model Hierarchy
ssot__AIAgentSession__dlm (Session)
└── ssot__AIAgentInteraction__dlm (Turn)
└── ssot__AIAgentInteractionStep__dlm (LLM/Actions)
└── ssot__AIAgentMoment__dlm (Messages)
Tab S1: All Sessions
Purpose: Overview of all agent sessions
-- S1: All Sessions (Overview)
SELECT
ssot__Id__c AS SessionID,
ssot__StartTimestamp__c AS StartTime,
ssot__EndTimestamp__c AS EndTime,
ssot__RelatedMessagingSessionId__c AS MessagingSessionID,
ssot__AiAgentSessionEndType__c AS EndType
FROM ssot__AIAgentSession__dlm
ORDER BY ssot__StartTimestamp__c DESC
LIMIT 100
📋 Copy a SessionID for the next query
Tab S2: Interactions for Session
Purpose: All turns/interactions within a session
-- S2: Interactions for Session
SELECT
ssot__Id__c AS InteractionID,
ssot__AiAgentSessionId__c AS SessionID,
ssot__AiAgentInteractionType__c AS InteractionType,
ssot__TopicApiName__c AS Topic,
ssot__StartTimestamp__c AS StartTime,
ssot__EndTimestamp__c AS EndTime
FROM ssot__AIAgentInteraction__dlm
WHERE ssot__AiAgentSessionId__c = '{{PASTE_SESSION_ID_HERE}}'
ORDER BY ssot__StartTimestamp__c
📋 Copy an InteractionID for S3 and S4
Tab S3: Steps for Interaction
Purpose: LLM reasoning and action execution within a turn
-- S3: Steps for Interaction
SELECT
ssot__Id__c AS StepID,
ssot__AiAgentInteractionId__c AS InteractionID,
ssot__AiAgentInteractionStepType__c AS StepType,
ssot__Name__c AS ActionName,
ssot__InputValueText__c AS InputJSON,
ssot__OutputValueText__c AS OutputJSON
FROM ssot__AIAgentInteractionStep__dlm
WHERE ssot__AiAgentInteractionId__c = '{{PASTE_INTERACTION_ID_HERE}}'
StepType values: LLM_STEP, ACTION_STEP
Tab S4: Messages for Interaction
Purpose: Actual user/agent conversation content
-- S4: Messages for Interaction
SELECT
ssot__Id__c AS MessageID,
ssot__AiAgentInteractionId__c AS InteractionID,
ssot__AiAgentInteractionMessageType__c AS MessageType,
ssot__ContentText__c AS Content,
ssot__MessageSentTimestamp__c AS SentTime
FROM ssot__AIAgentMoment__dlm
WHERE ssot__AiAgentInteractionId__c = '{{PASTE_INTERACTION_ID_HERE}}'
ORDER BY ssot__MessageSentTimestamp__c
MessageType values: INPUT (user), OUTPUT (agent)
Tab A1: Session Summary by End Type
Purpose: Aggregate sessions by how they ended
-- A1: Session Summary by End Type
SELECT
ssot__AiAgentSessionEndType__c AS EndType,
COUNT(*) AS SessionCount
FROM ssot__AIAgentSession__dlm
GROUP BY ssot__AiAgentSessionEndType__c
ORDER BY SessionCount DESC
Tab A2: Topic Usage
Purpose: Which topics handle the most turns
-- A2: Topic Usage Analysis
SELECT
ssot__TopicApiName__c AS Topic,
COUNT(*) AS TurnCount
FROM ssot__AIAgentInteraction__dlm
WHERE ssot__AiAgentInteractionType__c = 'TURN'
GROUP BY ssot__TopicApiName__c
ORDER BY TurnCount DESC
Tab A3: Action Invocations
Purpose: Which actions are called most frequently
-- A3: Action Invocation Frequency
SELECT
ssot__Name__c AS ActionName,
COUNT(*) AS InvocationCount
FROM ssot__AIAgentInteractionStep__dlm
WHERE ssot__AiAgentInteractionStepType__c = 'ACTION_STEP'
GROUP BY ssot__Name__c
ORDER BY InvocationCount DESC
Demo Flow
- S1: Run query, pick an interesting session (look for Escalated/Failed in EndType)
- S2: Paste SessionID, see the conversation turns and topics
- S3: Paste InteractionID, see LLM reasoning + action I/O
- S4: Paste InteractionID, read the actual messages
- A1-A3: Show aggregate insights
Field Reference
| Friendly Name | Actual Field |
|---|---|
| SessionID | ssot__Id__c |
| StartTime | ssot__StartTimestamp__c |
| EndTime | ssot__EndTimestamp__c |
| EndType | ssot__AiAgentSessionEndType__c |
| InteractionID | ssot__Id__c |
| Topic | ssot__TopicApiName__c |
| StepType | ssot__AiAgentInteractionStepType__c |
| ActionName | ssot__Name__c |
| MessageType | ssot__AiAgentInteractionMessageType__c |
| Content | ssot__ContentText__c |
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Session Tracing Data Model (STDM) Reference
Complete documentation of the Agentforce Session Tracing Data Model stored in Salesforce Data Cloud.
Source: Salesforce Help - Data Model for Agentforce Session Tracing
T6 Live API Discovery Summary ✅
Validated: January 30, 2026 | 24 DMOs Found | 233+ Test Points
| Category | DMOs | Status | Notes |
|---|---|---|---|
| Session Tracing | 5 | ✅ All Found | Session, Interaction, Step, Message, Participant |
| Agent Optimizer | 6 | ✅ All Found | Moment, Tag system (5 DMOs) |
| GenAI Audit | 13 | ✅ All Found | Generation, Quality, Feedback, Gateway |
| RAG Quality | 3 | ❌ Not Found | GenAIRetriever* DMOs don't exist |
Key Discoveries:
- Field naming: API uses
AiAgent(lowercase 'i'), notAIAgent - Agent name location: Stored on
Moment, notSession - New channel types:
NGC,Voice,Builder: Voice Preview - New agent types:
AgentforceEmployeeAgent,AgentforceServiceAgent - GenAI detector types:
TOXICITY(9 categories),PII(4 types),PROMPT_DEFENSE,InstructionAdherence
Overview
The STDM captures detailed telemetry from Agentforce agent conversations, enabling:
- Debugging: Understand why an agent behaved a certain way
- Analytics: Measure agent performance and usage patterns
- Optimization: Identify bottlenecks and improvement opportunities
The data model is a collection of DLOs (Data Lake Objects) and DMOs (Data Model Objects) that contain detailed session trace logs of agent behavior. Data is streamed to DLOs in Data 360 and then mapped to the applicable DMOs.
Data Model Hierarchy
The Agentforce Analytics data model consists of two main components:
- Session Tracing Data Model - Detailed turn-by-turn logs
- Optimization Data Model - Moments and tagging for analytics
Session Tracing Data Model
┌─────────────────────────────────────────────────────────────────┐
│ AIAgentSession (Session) │
│ One session = one complete conversation with an agent │
├─────────────────────────────────────────────────────────────────┤
│ ssot__Id__c Primary key │
│ ssot__StartTimestamp__c When session started │
│ ssot__EndTimestamp__c When session ended │
│ ssot__AiAgentSessionEndType__c How session ended │
└──────────────────────┬──────────────────────────────────────────┘
│
┌─────────────────┼─────────────────┬───────────────────┐
│ 1:N │ 1:N │ 1:N │ 1:N
▼ ▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│SessionParti- │ │ Interaction │ │ Moment │ │TagAssociation│
│ cipant │ │ (Turn) │ │ (Summaries) │ │ ✅ NEW │
├──────────────┤ ├──────────────┤ ├──────────────┤ ├──────────────┤
│AiAgentType │ │ TURN / │ │ Request/resp │ │ Links to │
│AiAgentApiName│ │ SESSION_END │ │ summaries │ │ TagDefinition│
│Role │ │ Topic routing│ │ Agent API │ │ & Tag values │
└──────────────┘ └──────┬───────┘ └──────┬───────┘ └──────────────┘
│ │
┌───────────┼────────────────┼─────── N:M junction
│ 1:N │ 1:N ▼
▼ ▼ ┌──────────────┐
┌────────────┐ ┌────────────┐│MomentInter- │
│ Interaction│ │ Interaction││action ✅ NEW │
│ Message │ │ Step │├──────────────┤
├────────────┤ ├────────────┤│Links Moment ↔│
│ Input/ │ │ LLM_STEP ││ Interaction │
│ Output │ │ ACTION_STEP│└──────────────┘
│ messages │ │ TOPIC_STEP │
└────────────┘ │ INTERRUPT │
│ SESSION_END│
└─────┬──────┘
│
│ links via GenerationId
▼
┌────────────────┐
│ GenAIGeneration│
│ (Trust Layer) │
└───────┬────────┘
│
▼
┌────────────────┐
│GenAIContent- │
│ Quality │
│ (Toxicity etc) │
└───────┬────────┘
│
▼
┌────────────────┐
│GenAIContent- │
│ Category │
│ (Detectors) │
└────────────────┘
Key Relationships:
- Session has multiple Participants (user, agent, human handoff)
- Session has multiple Interactions (turns)
- Session has multiple Moments (summaries)
- Each Interaction has Messages (actual user/agent text)
- Each Interaction has Steps (processing logic)
- Steps link to GenAIGeneration for quality metrics
Entity Details
AIAgentSession (ssot__AIAgentSession__dlm) ✅ T6 Verified
Represents an overarching container capturing contiguous interactions with one or more AI agents. A typical session might start when the customer asks their first question and end when the customer closes the agent chat window. Contains 18 fields.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key - unique session identifier | 01999669-0a54-724f-80d6-9cb495a7cee4 |
ssot__StartTimestamp__c |
DateTime | Timestamp when the session began | 2026-01-28T10:15:23.000Z |
ssot__EndTimestamp__c |
DateTime | Timestamp when the session concluded or timed out | 2026-01-28T10:19:55.000Z |
ssot__AiAgentChannelType__c |
Text | Type of communication channel (see table below) | SCRT2 - EmbeddedMessaging |
ssot__AiAgentSessionEndType__c |
Text | How the session ended | NOT_SET |
ssot__VariableText__c |
Text | Key-value pairs of contextual session data | {} |
ssot__SessionOwnerId__c |
Text | ID of the participant who initiated the session | 0051234567890ABC |
ssot__SessionOwnerObject__c |
Text | Name of DMO for Session Owner | Individual |
ssot__IndividualId__c |
Text (Lookup) | Reference to Individual record | a0p... |
ssot__PreviousSessionId__c |
Text (Lookup) | Reference to previous session (multi-agent) | a0x... |
ssot__RelatedMessagingSessionId__c |
Text | ID linking to messaging session origin ✅ | 5701234567890ABC |
ssot__RelatedVoiceCallId__c |
Text | ID linking to voice call origin ✅ | 0Lx... |
ssot__DataSourceId__c |
Text | Data source identifier | null |
ssot__DataSourceObjectId__c |
Text | Data source object identifier | ... |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | null |
KQ_Id__c |
Lookup | Key qualifier for ID | null |
KQ_IndividualId__c |
Lookup | Key qualifier for Individual | null |
KQ_PreviousSessionId__c |
Lookup | Key qualifier for PreviousSession | null |
Session End Types:
| Value | Description |
|---|---|
Completed |
Session resolved successfully |
Escalated |
Transferred to human agent |
Abandoned |
User left without resolution |
Failed |
Session failed due to error |
NOT_SET |
End type not yet determined |
Channel Types (Live API Verified - T6 Discovery):
| Value | Occurrences | Description |
|---|---|---|
E & O |
13,894 | Einstein & Omni-Channel |
Builder |
1,546 | Agent Builder testing |
SCRT2 - EmbeddedMessaging |
957 | Embedded web messaging |
LightningDesktopCopilot |
63 | Desktop copilot integration |
Voice |
41 | Voice/speech channel |
PSTN |
41 | Phone/PSTN channel |
Builder: Voice Preview |
10 | Voice preview in Builder |
NGC |
2 | Next-Gen Cloud (internal) |
AIAgentSessionParticipant (ssot__AIAgentSessionParticipant__dlm) ✅ Verified
Represents an entity (human or AI) that takes part in an AIAgentSession.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0p1234567890ABC |
ssot__AiAgentSessionId__c |
Text (Parent) | Reference to the specific AiAgentSession | a0x1234567890ABC |
ssot__AiAgentType__c |
Text | Type of AI Agent | EinsteinServiceAgent |
ssot__AiAgentTemplateApiName__c |
Text | Template used to create the agent | Service_Agent_Template |
ssot__AiAgentApiName__c |
Text | API name of the AI agent (if participant is AI) | Customer_Support_Agent |
ssot__AiAgentVersionApiName__c |
Text | API name of the AI agent version (if participant is AI) | v1.2.3 |
ssot__StartTimestamp__c |
DateTime | Timestamp when participant joined the session | 2026-01-28T10:15:23.000Z |
ssot__EndTimestamp__c |
DateTime | Timestamp when participant left/stopped interacting | 2026-01-28T10:19:55.000Z |
ssot__ParticipantId__c |
Text | Reference to the record representing the participant | 0051234567890ABC |
ssot__ParticipantObject__c |
Text | Name of DMO for the Participant record (e.g., Individual) |
Individual |
ssot__ParticipantAttributeText__c |
Text | JSON key-value pairs of participant metadata | {} |
ssot__IndividualId__c |
Text (Lookup) | Reference to Individual if participant DMO is Individual | a0i... |
ssot__AiAgentSessionParticipantRole__c |
Text | Role of participant within the session | Owner |
ssot__ExternalSourceId__c |
Text | External system identifier for the participant | ext-123 |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | 00D... |
AI Agent Types (Live API Verified - T6 Discovery):
| Value | Occurrences | Description |
|---|---|---|
EinsteinServiceAgent |
32,255 | Einstein Service Agent for customer support |
AgentforceEmployeeAgent |
314 | Agentforce agent for employee-facing use cases |
AgentforceServiceAgent |
171 | Agentforce service agent (newer platform) |
Employee |
84 | Generic employee-type agent |
Participant Roles (Live API Verified):
| Value | Occurrences | Description |
|---|---|---|
USER |
16,431 | End user participating in the session |
AGENT |
16,393 | AI agent participating in the session |
AIAgentInteraction (ssot__AIAgentInteraction__dlm) ✅ T6 Verified
Represents a segment within a session. It typically begins with a user's request and ends when the AI agent provides a response to that request. Contains 20 fields. Discovery shows 3,536 records in a 30-day window.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0y1234567890ABC |
ssot__AiAgentSessionId__c |
Text (Parent) | Reference to the parent session | a0x1234567890ABC |
ssot__AiAgentInteractionType__c |
Text | Interaction type (TURN, SESSION_END) |
TURN |
ssot__PrevInteractionId__c |
Text (Lookup) | Reference to previous interaction (enables sequencing) | a0y... |
ssot__StartTimestamp__c |
DateTime | Timestamp when the interaction began | 2026-01-28T10:15:23.000Z |
ssot__EndTimestamp__c |
DateTime | Timestamp when the interaction completed | 2026-01-28T10:15:26.000Z |
ssot__TopicApiName__c |
Text | API name of the topic classified for this interaction | Order_Tracking |
ssot__AttributeText__c |
Text | JSON key-value pairs of additional metadata | {"confidence": 0.95} |
ssot__TelemetryTraceId__c |
Text | Identifier for distributed tracing (OpenTelemetry) | abc123def456... |
ssot__TelemetryTraceSpanId__c |
Text | Span ID within distributed tracing context | span_xyz... |
ssot__SessionOwnerId__c |
Text | ID of participant who initiated the session | 005... |
ssot__SessionOwnerObject__c |
Text | DMO name for Session Owner | Individual |
ssot__IndividualId__c |
Text (Lookup) | Reference to Individual record | a0i... |
ssot__DataSourceId__c |
Text | Data source identifier | null |
ssot__DataSourceObjectId__c |
Text | Data source object identifier | ... |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | null |
KQ_* |
Lookup | Key qualifier fields for relationships | null |
Interaction Types (Live API Verified):
| Value | Description |
|---|---|
TURN |
Normal user input → agent response cycle |
SESSION_END |
Final interaction marking session close |
OpenTelemetry Integration: The TelemetryTraceId and TelemetryTraceSpanId fields enable distributed tracing across system components, supporting export to platforms like Datadog, Splunk, and other OTEL-compatible tools.
AIAgentInteractionMessage (ssot__AiAgentInteractionMessage__dlm) ✅ T6 Verified
Represents a single communication provided by the user or generated by the AI agent during a session. Contains 21 fields.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0i1234567890ABC |
ssot__AiAgentInteractionId__c |
Text (Parent) | Reference to the interaction | a0y1234567890ABC |
ssot__AiAgentSessionId__c |
Text (Lookup) | Reference to the session | a0x... |
ssot__AiAgentSessionParticipantId__c |
Text (Lookup) | Participant who sent the message | a0p... |
ssot__AiAgentInteractionMessageType__c |
Text | Message direction (Input/Output) |
Input |
ssot__AiAgentInteractionMsgContentType__c |
Text | MIME content type | text/plain |
ssot__ContentText__c |
Text | Textual content | What is the status of my order? |
ssot__MessageSentTimestamp__c |
DateTime | Exact time when message was sent | 2026-01-28T10:15:23.000Z |
ssot__ParentMessageId__c |
Text (Lookup) | Parent message (for threads) | a0i... |
ssot__SessionOwnerId__c |
Text | ID of session owner participant | 005... |
ssot__SessionOwnerObject__c |
Text | DMO name for Session Owner | Individual |
ssot__IndividualId__c |
Text (Lookup) | Reference to Individual record | a0i... |
ssot__DataSourceId__c |
Text | Data source identifier | null |
ssot__DataSourceObjectId__c |
Text | Data source object identifier | ... |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | null |
KQ_* |
Lookup | Key qualifier fields | null |
Message Types (Live API Verified):
| Value | Occurrences | Description |
|---|---|---|
Input |
16,428 | User message to agent |
Output |
16,390 | Agent response to user |
Content Types (Live API Verified):
| Value | Description |
|---|---|
text/plain |
Plain text message |
application/json |
JSON-formatted content |
Note: InteractionMessage differs from Moment:
- InteractionMessage: Raw user/agent text per turn with threading support
- Moment: Summarized request/response with agent API name
AIAgentInteractionStep (ssot__AIAgentInteractionStep__dlm) ✅ T6 Verified
Represents a discrete action or operation performed during an interaction to fulfill the user's request. Contains 23 fields. Discovery shows 12,318 records in a 30-day window.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0z1234567890ABC |
ssot__AiAgentInteractionId__c |
Text (Parent) | Reference to the interaction this step belongs to | a0y1234567890ABC |
ssot__AiAgentInteractionStepType__c |
Text | Step type (see table below) | LLM_STEP |
ssot__Name__c |
Text | Name of the step/action performed | Get_Order_Status |
ssot__PrevStepId__c |
Text (Lookup) | Reference to previous step (linear sequencing) | a0z... |
ssot__StartTimestamp__c |
DateTime | Timestamp when step execution began | 2026-01-28T10:15:23.000Z |
ssot__EndTimestamp__c |
DateTime | Timestamp when step execution completed | 2026-01-28T10:15:24.000Z |
ssot__InputValueText__c |
Text | Input data provided to the step (JSON) | {"orderId": "12345"} |
ssot__OutputValueText__c |
Text | Output data resulting from step execution (JSON) | {"status": "Shipped"} |
ssot__PreStepVariableText__c |
Text | State of variables before step execution | {"customer_id": "C001"} |
ssot__PostStepVariableText__c |
Text | State of variables after step execution | {"order_status": "Shipped"} |
ssot__ErrorMessageText__c |
Text | Error details if step encountered issues | Action timeout after 30s |
ssot__AttributeText__c |
Text | JSON key-value pairs of additional metadata | {"latency_ms": 150} |
ssot__GenerationId__c |
Text | Reference to GenAIGeneration (LLM steps) | gen_abc123... |
ssot__GenAiGatewayRequestId__c |
Text | Reference to GenAIGatewayRequest (LLM steps) | req_xyz... |
ssot__GenAiGatewayResponseId__c |
Text | Reference to GenAIGatewayResponse (LLM steps) | resp_xyz... |
ssot__TelemetryTraceSpanId__c |
Text | Span ID for distributed tracing (OTEL) | span_abc... |
ssot__DataSourceId__c |
Text | Data source identifier | null |
ssot__DataSourceObjectId__c |
Text | Data source object identifier | ... |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | null |
KQ_* |
Lookup | Key qualifier fields (Id, InteractionId, PrevStepId) | null |
Step Types (Live API Verified - T6 Discovery):
| Value | Occurrences | Description | When Used |
|---|---|---|---|
LLM_STEP |
67,163 | LLM call execution | Intent detection, response generation |
TOPIC_STEP |
16,236 | Topic classification/routing | Determining which topic handles the request |
SESSION_END |
14,990 | Session termination | Final step when session closes |
ACTION_STEP |
13,780 | Function/action execution | Calling flows, Apex actions |
INTERRUPT_STEP |
5 | Interrupt processing | Handling interruptions (rare) |
Common Step Names (Live API Verified):
| Step Name | Step Type | Description |
|---|---|---|
AiCopilot__ReactInitialPrompt |
LLM_STEP | Initial planning/reasoning step |
AiCopilot__ReactTopicPrompt |
LLM_STEP | Topic classification/routing decision |
AiCopilot__ReactValidationPrompt |
LLM_STEP | Response validation (hallucination check) |
CLOSED_USER_REQUEST |
SESSION_END | Session termination by user request |
flash_agent |
LLM_STEP | Flash agent LLM invocation |
{Topic}.{Action} |
ACTION_STEP | Topic-specific actions (e.g., Order_Status.Get_Order) |
Step Naming Convention:
- LLM steps use format:
AiCopilot__{PromptName}or{agent_name} - Action steps use format:
{TopicApiName}.{ActionApiName} - Session end steps:
CLOSED_USER_REQUEST,ESCALATED, etc.
Note: Steps use linear sequencing via PrevStepId. There is no hierarchical parent-child relationship (no ParentStepId field).
GenAI Reference Fields:
The Step entity includes references to every LLM call the reasoning engine makes, enabling joins with feedback data or guardrails metrics:
GenerationId→ Links toGenAIGeneration__dlmfor quality analysisGenAiGatewayRequestId→ Links toGenAIGatewayRequest__dlmfor promptsGenAiGatewayResponseId→ Links toGenAIGatewayResponse__dlmfor raw responses
AIAgentMoment (ssot__AiAgentMoment__dlm) ✅ T6 Verified
Represents summarized request/response pairs for analytics and optimization. Contains 13 fields. Note: The agent API name is stored here (not on Session).
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0m1234567890ABC |
ssot__AiAgentSessionId__c |
Text (Parent) | FK to parent session | a0x1234567890ABC |
ssot__AiAgentApiName__c |
Text | API name of the agent | Customer_Support_Agent |
ssot__AiAgentVersionApiName__c |
Text | Version of the agent | v1.2.3 |
ssot__RequestSummaryText__c |
Text | Summarized user request | User asked about order status |
ssot__ResponseSummaryText__c |
Text | Summarized agent response | Provided tracking info |
ssot__StartTimestamp__c |
DateTime | Moment start time | 2026-01-28T10:15:23.000Z |
ssot__EndTimestamp__c |
DateTime | Moment end time | 2026-01-28T10:15:26.000Z |
ssot__DataSourceId__c |
Text | Data source identifier | null |
ssot__DataSourceObjectId__c |
Text | Data source object identifier | null |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | null |
KQ_* |
Lookup | Key qualifier fields | null |
Moment vs Message:
- Moment: High-level summaries with agent API name for analytics
- InteractionMessage: Raw user/agent text per turn with threading support
AIAgentMomentInteraction (ssot__AiAgentMomentInteraction__dlm) ✅ NEW
Junction table linking Moments to Interactions, enabling many-to-many relationships between high-level summaries and detailed interaction data.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0j1234567890ABC |
ssot__AiAgentMomentId__c |
Text (Lookup) | Reference to the Moment | a0m... |
ssot__AiAgentInteractionId__c |
Text (Lookup) | Reference to the Interaction | a0y... |
ssot__StartTimestamp__c |
DateTime | When this relationship was created | 2026-01-28T10:15:23.000Z |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | 00D... |
AIAgentTagDefinition (ssot__AiAgentTagDefinition__dlm) ✅ Verified
Defines tag metadata and structure for the Agentforce tagging system.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0t1234567890ABC |
ssot__Name__c |
Text | Display name of the tag definition | Escalation_Reason |
ssot__DeveloperName__c |
Text | API-safe name of the tag definition | Escalation_Reason |
ssot__Description__c |
Text | Description of what the tag represents | Reason for agent escalation |
ssot__DataType__c |
Text | Data type of tag values | Text |
ssot__SourceType__c |
Text | How the tag is populated | Generated |
ssot__CreatedDate__c |
DateTime | When the definition was created | 2026-01-15T08:00:00.000Z |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | 00D... |
SourceType Values (Live API Verified):
| Value | Description |
|---|---|
Generated |
System-generated tags |
Predefined |
Admin-defined tags |
DataType Values (Live API Verified):
| Value | Description |
|---|---|
Text |
Text/string values |
Integer |
Numeric values |
AIAgentTag (ssot__AiAgentTag__dlm) ✅ Verified
Stores individual tag values associated with tag definitions.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0u1234567890ABC |
ssot__AiAgentTagDefinitionId__c |
Text (Lookup) | Reference to the tag definition | a0t... |
ssot__Value__c |
Text | The tag value (e.g., rating, category code) | 5 |
ssot__Description__c |
Text | Human-readable description of the tag | Customer frustrated with wait time |
ssot__IsActive__c |
Boolean | Whether the tag is currently active | true |
ssot__CreatedDate__c |
DateTime | When the tag was created | 2026-01-28T10:15:23.000Z |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | 00D... |
Note: The Value field typically contains numeric codes (1-5 for ratings) or short codes, while Description contains the human-readable explanation.
AIAgentTagDefinitionAssociation (ssot__AiAgentTagDefinitionAssociation__dlm) ✅ Verified
Links tag definitions to specific agents or prompt templates, defining which tags apply to which agent configurations.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0w1234567890ABC |
ssot__AiAgentTagDefinitionId__c |
Text (Lookup) | Reference to the tag definition | a0t... |
ssot__AiAgentApiName__c |
Text | API name of the agent this applies to | Customer_Support_Agent |
ssot__AiPromptTemplateId__c |
Text (Lookup) | Reference to prompt template | a0p... |
ssot__CreatedDate__c |
DateTime | When the association was created | 2026-01-15T08:00:00.000Z |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | 00D... |
Use Cases:
- Define which tags are applicable to specific agents
- Link tagging to prompt templates for automatic tag application
- Configure agent-specific quality metrics
AIAgentTagAssociation (ssot__AiAgentTagAssociation__dlm) ✅ Verified
Links tags to sessions and moments, enabling flexible categorization of agent interactions. Contains 15 fields.
| Field API Name | Type | Description | Example |
|---|---|---|---|
ssot__Id__c |
Text | Primary key | a0v1234567890ABC |
ssot__AiAgentSessionId__c |
Text (Lookup) | Reference to the session | a0x... |
ssot__AiAgentMomentId__c |
Text (Lookup) | Reference to the moment | a0m... |
ssot__AiAgentTagDefinitionAssociationId__c |
Text (Lookup) | Reference to tag definition association | a0w... |
ssot__AiAgentTagId__c |
Text (Lookup) | Direct reference to the tag value ✅ NEW | a0u... |
ssot__AssociationReasonText__c |
Text | Reason/context for the tag association ✅ NEW | User expressed frustration |
ssot__CreatedDate__c |
DateTime | When the association was created | 2026-01-28T10:15:23.000Z |
ssot__DataSourceId__c |
Text | Data source identifier | null |
ssot__DataSourceObjectId__c |
Text | Data source object identifier | null |
ssot__InternalOrganizationId__c |
Text | Internal org identifier | null |
KQ_* |
Lookup | Key qualifier fields for relationships | null |
Use Cases:
- Categorize sessions by customer sentiment
- Tag escalation reasons for analytics
- Apply business-specific labels to conversations
- Track tagging rationale via
AssociationReasonText
GenAI Audit & Feedback DMOs ✅ T6 Verified
The GenAI Trust Layer provides comprehensive tracking of LLM calls, quality metrics, and safety detections.
GenAIGeneration (GenAIGeneration__dlm)
Records individual LLM generations. Contains 11 fields.
| Field API Name | Type | Description |
|---|---|---|
generationId__c |
Text | Primary key for joining with Steps |
generationResponseId__c |
Text | Response identifier |
responseText__c |
Text | Raw LLM response text |
maskedResponseText__c |
Text | PII-masked version of response |
responseParameters__c |
Text | Model parameters used |
feature__c |
Text | Feature that triggered generation |
cloud__c |
Text | Cloud identifier |
orgId__c |
Text | Organization ID |
timestamp__c |
DateTime | Generation timestamp |
GenAIContentQuality (GenAIContentQuality__dlm)
Quality assessment for each generation. Contains 10 fields.
| Field API Name | Type | Description |
|---|---|---|
id__c |
Text | Primary key |
parent__c |
Text | FK to GenAIGeneration.generationId__c |
contentType__c |
Text | Type of content assessed |
isToxicityDetected__c |
Boolean | Overall toxicity flag |
feature__c |
Text | Feature identifier |
cloud__c |
Text | Cloud identifier |
orgId__c |
Text | Organization ID |
timestamp__c |
DateTime | Assessment timestamp |
GenAIContentCategory (GenAIContentCategory__dlm)
Detailed detector results per quality assessment. Contains 10 fields.
| Field API Name | Type | Description |
|---|---|---|
id__c |
Text | Primary key |
parent__c |
Text | FK to GenAIContentQuality.id__c |
detectorType__c |
Text | Detector type (see table below) |
category__c |
Text | Detection category/result |
value__c |
Text | Confidence score (0.0-1.0) |
cloud__c |
Text | Cloud identifier |
orgId__c |
Text | Organization ID |
timestamp__c |
DateTime | Detection timestamp |
Detector Types (Live API Verified - T6 Discovery):
| Detector Type | Occurrences | Categories |
|---|---|---|
TOXICITY |
627,603 | hate, identity, physical, profanity, safety_score, sexual, toxicity, violence, 0 |
PROMPT_DEFENSE |
119,050 | aggregatePromptAttackScore, isPromptAttackDetected, 0, 1 |
PII |
27,805 | CREDIT_CARD, EMAIL_ADDRESS, PERSON, US_PHONE_NUMBER |
InstructionAdherence |
16,380 | High, Low, Uncertain |
GenAIGatewayRequest (GenAIGatewayRequest__dlm)
Request details for LLM calls. Contains 30 fields (largest DMO).
| Field API Name | Type | Description |
|---|---|---|
gatewayRequestId__c |
Text | Primary key |
prompt__c |
Text | Full prompt sent to LLM |
maskedPrompt__c |
Text | PII-masked prompt |
model__c |
Text | Model name (e.g., gpt-4) |
provider__c |
Text | Model provider |
temperature__c |
Number | Temperature parameter |
promptTokens__c |
Number | Input token count |
completionTokens__c |
Number | Output token count |
totalTokens__c |
Number | Total tokens |
promptTemplateDevName__c |
Text | Prompt template developer name |
promptTemplateVersionNo__c |
Text | Prompt template version |
enableInputSafetyScoring__c |
Text | Input safety enabled flag |
enableOutputSafetyScoring__c |
Text | Output safety enabled flag |
enablePiiMasking__c |
Text | PII masking enabled flag |
sessionId__c |
Text | Related session ID |
userId__c |
Text | User who triggered request |
appType__c |
Text | Application type |
feature__c |
Text | Feature identifier |
GenAIGatewayResponse (GenAIGatewayResponse__dlm)
Response metadata for LLM calls. Contains 8 fields.
| Field API Name | Type | Description |
|---|---|---|
generationRequestId__c |
Text | FK to GatewayRequest |
generationResponseId__c |
Text | Response identifier |
parameters__c |
Text | Response parameters JSON |
cloud__c |
Text | Cloud identifier |
orgId__c |
Text | Organization ID |
timestamp__c |
DateTime | Response timestamp |
GenAIFeedback (GenAIFeedback__dlm)
User feedback on LLM responses. Contains 16 fields.
| Field API Name | Type | Description |
|---|---|---|
feedbackId__c |
Text | Primary key |
generationId__c |
Text | FK to Generation |
feedback__c |
Text | Feedback value (e.g., GOOD) |
action__c |
Text | User action taken |
source__c |
Text | Feedback source |
userId__c |
Text | User who gave feedback |
appType__c |
Text | Application type |
feature__c |
Text | Feature identifier |
timestamp__c |
DateTime | Feedback timestamp |
Feedback Values:
| Value | Description |
|---|---|
GOOD |
Positive feedback (thumbs up) |
BAD |
Negative feedback (thumbs down) |
GenAIFeedbackDetail (GenAIFeedbackDetail__dlm)
Detailed feedback with free-text comments. Contains 10 fields.
| Field API Name | Type | Description |
|---|---|---|
feedbackDetailId__c |
Text | Primary key |
parent__c |
Text | FK to Feedback |
feedbackText__c |
Text | Free-text feedback comment |
appFeedback__c |
Text | App-specific feedback |
feature__c |
Text | Feature identifier |
Other GenAI DMOs
| DMO Name | Fields | Description |
|---|---|---|
GenAIAppGeneration__dlm |
10 | Application-level generation records |
GenAIGatewayRequestTag__dlm |
9 | Tags for gateway requests |
GenAIGtwyRequestMetadata__dlm |
10 | Request metadata (type, JSON) |
GenAIGtwyObjRecord__dlm |
13 | Object record references |
GenAIGtwyObjRecCitationRef__dlm |
9 | Citation references |
GenAIGtwyRequestLLM__dlm |
0 | LLM-specific request data (empty) |
RAG Quality DMOs ❌ NOT FOUND
The following DMOs were probed but do not exist in the live API:
| DMO Name | Status | Notes |
|---|---|---|
GenAIRetrieverResponse__dlm |
❌ Not Found | Table does not exist |
GenAIRetrieverRequest__dlm |
❌ Not Found | Table does not exist |
GenAIRetrieverQualityMetric__dlm |
❌ Not Found | Table does not exist |
Note: These DMOs may be available in future API versions or require specific enablement.
Data Relationships
-- Session → Interactions
SELECT i.*
FROM ssot__AIAgentInteraction__dlm i
WHERE i.ssot__AiAgentSessionId__c = 'SESSION_ID';
-- Interaction → Steps
SELECT s.*
FROM ssot__AIAgentInteractionStep__dlm s
WHERE s.ssot__AiAgentInteractionId__c = 'INTERACTION_ID';
-- Interaction → Messages
SELECT m.*
FROM ssot__AIAgentMoment__dlm m
WHERE m.ssot__AiAgentInteractionId__c = 'INTERACTION_ID';
Data Volume Considerations
| Scenario | Sessions/Day | Total Records/Day |
|---|---|---|
| Low volume | 100-1K | 10K-100K |
| Medium volume | 1K-10K | 100K-1M |
| High volume | 10K-100K | 1M-10M |
| Enterprise | 100K+ | 10M+ |
Estimation Formula:
Total records ≈ Sessions × Avg turns × (1 + Avg steps + 2)
Example: 10K sessions × 4 turns × 5 = 200K records
Data Retention
Session tracing data in Data Cloud follows the org's data retention policy. Default:
- Production: 13 months
- Sandbox: 30 days
Enabling Session Tracing
- Setup → Agentforce → Settings
- Enable Session Tracing
- Configure which agents to trace
- Wait 5-15 minutes for data to appear in Data Cloud
Related Resources
- Query Patterns - Example queries
- Analysis Cookbook - Common analysis patterns
- Troubleshooting - Common issues
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Debugging Sessions
Examples for debugging specific agent sessions using STDM data.
Finding Sessions to Debug
List Failed/Escalated Sessions
stdm-extract debug-session --data-dir ./stdm_data --list-failed
Output:
Failed/Escalated Sessions (last 10)
═══════════════════════════════════════════════════════════
🔄 a0x001 | Customer_Support_Agent | Escalated | 2026-01-28T10:15
❌ a0x002 | Order_Tracking_Agent | Failed | 2026-01-28T09:45
🔄 a0x003 | Customer_Support_Agent | Escalated | 2026-01-28T08:30
...
To debug a session, run:
stdm-extract debug-session --data-dir ./stdm_data --session-id <ID>
Find via Python
import polars as pl
from pathlib import Path
sessions = pl.scan_parquet(Path("./stdm_data/sessions/**/*.parquet"))
# Failed/escalated sessions
failed = sessions.filter(
pl.col("ssot__AiAgentSessionEndType__c").is_in(["Escalated", "Failed", "Abandoned"])
).sort("ssot__StartTimestamp__c", descending=True).head(10).collect()
for row in failed.iter_rows(named=True):
print(f"{row['ssot__Id__c']} | {row['ssot__AiAgentApiName__c']} | {row['ssot__AiAgentSessionEndType__c']}")
Debug a Specific Session
Basic Timeline
stdm-extract debug-session --data-dir ./stdm_data --session-id "a0x001"
Output:
🔍 SESSION TIMELINE
══════════════════════════════════════════════════════════════════════
Session: a0x001
Agent: Customer_Support_Agent
Started: 2026-01-28T10:15:23.000Z
Ended: 2026-01-28T10:19:55.000Z
End Type: Escalated
──────────────────────────────────────────────────────────────────────
Timeline
──────────────────────────────────────────────────────────────────────
═══ Topic: Order_Status ═══
2026-01-28T10:15:23 → [INPUT]
Where is my order #12345?
2026-01-28T10:15:26 ← [OUTPUT]
I can help you track your order. Let me look that up for you.
Your order #12345 was shipped on January 25th and is expected...
═══ Topic: Return_Policy ═══
2026-01-28T10:16:45 → [INPUT]
I want to return it, it's damaged
2026-01-28T10:16:48 ← [OUTPUT]
I'm sorry to hear that. I can help you start a return. However, I
need to transfer you to a specialist for damaged items...
═══ Topic: Escalation ═══
2026-01-28T10:17:02 → [INPUT]
Yes, please transfer me
2026-01-28T10:17:05 ← [OUTPUT]
I'm transferring you to a customer service representative now.
Verbose Mode (Show Steps)
See LLM reasoning and action details:
stdm-extract debug-session --data-dir ./stdm_data --session-id "a0x001" --verbose
Output (with steps):
2026-01-28T10:15:23 → [INPUT]
Where is my order #12345?
🧠 [LLM_STEP] Intent Detection
⚡ [ACTION_STEP] Get_Order_Status
Input: {"orderId": "12345"}
Output: {"status": "Shipped", "carrier": "UPS", "tracking": "1Z..."}
🧠 [LLM_STEP] Response Generation
2026-01-28T10:15:26 ← [OUTPUT]
I can help you track your order...
Export to JSON
For sharing or further analysis:
stdm-extract debug-session --data-dir ./stdm_data \
--session-id "a0x001" \
--verbose \
--output ./debug/session_a0x001.json
JSON structure:
{
"session": {
"id": "a0x001",
"agent": "Customer_Support_Agent",
"start": "2026-01-28T10:15:23.000Z",
"end": "2026-01-28T10:19:55.000Z",
"end_type": "Escalated"
},
"timeline": [
{
"type": "interaction",
"timestamp": "2026-01-28T10:15:23.000Z",
"interaction_id": "a0y001",
"topic": "Order_Status"
},
{
"type": "message",
"timestamp": "2026-01-28T10:15:23.000Z",
"message_type": "INPUT",
"content": "Where is my order #12345?"
},
{
"type": "step",
"step_type": "ACTION_STEP",
"name": "Get_Order_Status",
"input": "{\"orderId\": \"12345\"}",
"output": "{\"status\": \"Shipped\"...}"
}
]
}
Using the Python Template
For custom timeline analysis:
python3 assets/analysis/message-timeline.py \
--data-dir ./stdm_data \
--session-id "a0x001" \
--verbose
Debug Patterns
Pattern 1: Why Did It Escalate?
Look for:
- Topic switches - Did topics change unexpectedly?
- Action failures - Did an action return an error?
- User frustration - Repeated similar inputs?
# Find the last few messages before escalation
timeline = analyzer.message_timeline("a0x001")
print(timeline.tail(10))
Pattern 2: Action Failure Analysis
# Find action steps with error outputs
steps = pl.read_parquet("./stdm_data/steps/data.parquet")
failed_actions = steps.filter(
(pl.col("ssot__AiAgentInteractionStepType__c") == "ACTION_STEP") &
(pl.col("ssot__OutputValueText__c").str.contains("error|Error|ERROR"))
)
print(failed_actions.select(["ssot__Name__c", "ssot__OutputValueText__c"]))
Pattern 3: Long Sessions
Sessions with many turns often indicate problems:
interactions = pl.read_parquet("./stdm_data/interactions/data.parquet")
long_sessions = interactions.filter(
pl.col("ssot__AiAgentInteractionType__c") == "TURN"
).group_by("ssot__AiAgentSessionId__c").agg(
pl.count().alias("turns")
).filter(pl.col("turns") > 10).collect()
print(f"Sessions with 10+ turns: {len(long_sessions)}")
Pattern 4: Compare Successful vs Failed
sessions = pl.read_parquet("./stdm_data/sessions/data.parquet")
interactions = pl.read_parquet("./stdm_data/interactions/data.parquet")
# Join and compare
joined = sessions.join(
interactions.group_by("ssot__AiAgentSessionId__c").agg(
pl.count().alias("turns")
),
left_on="ssot__Id__c",
right_on="ssot__AiAgentSessionId__c"
)
print(joined.group_by("ssot__AiAgentSessionEndType__c").agg([
pl.col("turns").mean().alias("avg_turns"),
pl.count().alias("sessions")
]))
Bulk Session Debug
Export Multiple Sessions
from pathlib import Path
import json
session_ids = ["a0x001", "a0x002", "a0x003"]
output_dir = Path("./debug")
output_dir.mkdir(exist_ok=True)
for sid in session_ids:
timeline = get_timeline(data, sid)
session_info = get_session_info(data, sid)
with open(output_dir / f"{sid}.json", "w") as f:
json.dump({
"session": session_info,
"timeline": timeline
}, f, indent=2)
print(f"Exported {sid}")
Tips
- Start with list-failed: Find problem sessions quickly
- Use verbose mode: Steps reveal why the agent took certain actions
- Export to JSON: For sharing with team or deeper analysis
- Look at topic switches: Unexpected changes often indicate confusion
- Check action outputs: Failed actions are a common escalation cause
Builder Debugging Views
The Agentforce Builder provides 4 views for real-time trace analysis:
| View | Purpose | Best For |
|---|---|---|
| Interaction Details | Turn-by-turn message flow | Understanding conversation flow |
| Trace Waterfall | Timeline of all steps with duration bars | Performance bottlenecks |
| Variable State | State snapshot at each step | Debugging conditional logic |
| Script View | Side-by-side script + execution highlight | Mapping script to trace |
Tip: Start with Trace Waterfall to identify slow steps, then switch to Variable State to inspect the data flowing through those steps. Use Script View when debugging Agent Script agents to see exactly which DSL line triggered each trace event.
See Also
- Analysis Examples - Aggregate analysis
- Troubleshooting - Common issues
- Data Model Reference - STDM schema
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Filtered Extraction Examples
Examples for extracting specific subsets of session tracing data.
Filter by Agent
Single Agent
Extract only sessions handled by a specific agent:
stdm-extract extract --org prod --agent Customer_Support_Agent
Multiple Agents
Extract sessions from multiple agents:
stdm-extract extract --org prod \
--agent Customer_Support_Agent \
--agent Order_Tracking_Agent \
--agent FAQ_Agent
Note: Agent names are the API Name (e.g., My_Agent), not the label.
Filter by Date Range
Specific Start Date
Extract from a specific date to now:
stdm-extract extract --org prod --since 2026-01-15
Date Range
Extract a specific window:
stdm-extract extract --org prod \
--since 2026-01-01 \
--until 2026-01-15
ISO DateTime Format
For precise timestamps:
stdm-extract extract --org prod \
--since "2026-01-15T00:00:00" \
--until "2026-01-15T23:59:59"
Combine Filters
Agent + Date Range
stdm-extract extract --org prod \
--agent Customer_Support_Agent \
--since 2026-01-01 \
--until 2026-01-15 \
--output ./data/jan-first-half
Extract Specific Sessions
Known Session IDs
When you have specific session IDs to investigate:
stdm-extract extract-tree --org prod \
--session-ids "a0x001,a0x002,a0x003"
This extracts the complete tree for each session:
- Session record
- All interactions (turns)
- All steps (LLM and actions)
- All messages
From a File
If you have session IDs in a file:
# Session IDs file (one per line)
cat session_ids.txt
a0x001
a0x002
a0x003
# Extract using command substitution
stdm-extract extract-tree --org prod \
--session-ids "$(cat session_ids.txt | tr '\n' ',')"
Incremental Extraction
First Run
Extracts last 24 hours and saves watermark:
stdm-extract extract-incremental --org prod
Creates:
~/.sf/observability/prod/watermark.json./stdm_data/(with 24h of data)
Subsequent Runs
Extracts only new data since last run:
stdm-extract extract-incremental --org prod
Watermark file:
{
"last_run": "2026-01-28T10:15:23.000Z",
"sessions_extracted": 1234
}
Force Full Re-extraction
Delete the watermark to reset:
rm ~/.sf/observability/prod/watermark.json
stdm-extract extract-incremental --org prod # Now extracts last 24h
Production Workflow
Daily Extraction Job
#!/bin/bash
# daily-extract.sh
ORG="prod"
OUTPUT_BASE="/data/agentforce"
DATE=$(date +%Y-%m-%d)
# Extract yesterday's data
stdm-extract extract --org $ORG \
--since "$(date -d 'yesterday' +%Y-%m-%d)" \
--until "$DATE" \
--output "$OUTPUT_BASE/$DATE" \
--verbose 2>&1 | tee "$OUTPUT_BASE/logs/$DATE.log"
Scheduled Incremental (Cron)
# Run every hour, extract only new data
0 * * * * /usr/local/bin/stdm-extract extract-incremental --org prod >> /var/log/stdm.log 2>&1
Finding Agent Names
If you're not sure of the exact agent API names:
Option 1: Extract First, Then Filter
# Extract all
stdm-extract extract --org prod --days 1
# Check agent names
python3 -c "
import polars as pl
print(pl.read_parquet('./stdm_data/sessions/data.parquet')
.select('ssot__AiAgentApiName__c')
.unique()
)
"
Option 2: Check in Salesforce
- Setup → Agents
- Click agent → Details tab
- Copy API Name
Tips
- Start small: Test with
--days 1before large extractions - Use incremental: For ongoing monitoring, use
extract-incremental - Separate outputs: Use
--outputto organize by date or environment - Check counts first: Use
countcommand to estimate extraction size
See Also
- Basic Extraction - Simple examples
- Analysis Examples - Analyze filtered data
- CLI Reference - All command options
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Polars Cheatsheet
Quick reference for analyzing STDM data with Polars.
Loading Data
import polars as pl
from pathlib import Path
data_dir = Path("./stdm_data")
# Lazy loading (recommended for large datasets)
sessions = pl.scan_parquet(data_dir / "sessions" / "**/*.parquet")
interactions = pl.scan_parquet(data_dir / "interactions" / "**/*.parquet")
steps = pl.scan_parquet(data_dir / "steps" / "**/*.parquet")
messages = pl.scan_parquet(data_dir / "messages" / "**/*.parquet")
# Eager loading (loads everything into memory)
sessions_df = pl.read_parquet(data_dir / "sessions" / "**/*.parquet")
Basic Operations
Count Records
sessions.select(pl.count()).collect()
# Or
len(sessions.collect())
View Schema
sessions.collect_schema()
Preview Data
sessions.head(5).collect()
sessions.fetch(5) # Faster, doesn't scan full file
Select Columns
sessions.select([
"ssot__Id__c",
"ssot__AiAgentApiName__c",
"ssot__AiAgentSessionEndType__c"
]).collect()
Filtering
Single Condition
sessions.filter(pl.col("ssot__AiAgentApiName__c") == "My_Agent")
Multiple Conditions (AND)
sessions.filter(
(pl.col("ssot__AiAgentApiName__c") == "My_Agent") &
(pl.col("ssot__AiAgentSessionEndType__c") == "Completed")
)
Multiple Conditions (OR)
sessions.filter(
pl.col("ssot__AiAgentSessionEndType__c").is_in(["Escalated", "Failed"])
)
Null Checks
sessions.filter(pl.col("ssot__EndTimestamp__c").is_not_null())
sessions.filter(pl.col("ssot__EndTimestamp__c").is_null())
String Contains
messages.filter(pl.col("ssot__ContentText__c").str.contains("order"))
Aggregation
Group By with Count
sessions.group_by("ssot__AiAgentApiName__c").agg(
pl.count().alias("session_count")
).sort("session_count", descending=True).collect()
Multiple Aggregations
sessions.group_by("ssot__AiAgentApiName__c").agg([
pl.count().alias("total"),
pl.col("ssot__AiAgentSessionEndType__c")
.filter(pl.col("ssot__AiAgentSessionEndType__c") == "Completed")
.count().alias("completed")
]).collect()
Unique Count
interactions.group_by("ssot__AiAgentSessionId__c").agg(
pl.col("ssot__TopicApiName__c").n_unique().alias("topic_count")
).collect()
Joins
Inner Join
sessions.join(
interactions,
left_on="ssot__Id__c",
right_on="ssot__AiAgentSessionId__c",
how="inner"
)
Left Join
sessions.join(
interactions,
left_on="ssot__Id__c",
right_on="ssot__AiAgentSessionId__c",
how="left"
)
Date/Time Operations
Parse Timestamp
sessions.with_columns(
pl.col("ssot__StartTimestamp__c").str.to_datetime().alias("start_dt")
)
Extract Date Parts
sessions.with_columns([
pl.col("ssot__StartTimestamp__c").str.slice(0, 10).alias("date"),
pl.col("ssot__StartTimestamp__c").str.slice(11, 2).alias("hour"),
])
Date Filtering
sessions.filter(
pl.col("ssot__StartTimestamp__c") >= "2026-01-01T00:00:00.000Z"
)
Computed Columns
Add Column
sessions.with_columns(
(pl.col("completed") / pl.col("total") * 100).round(1).alias("completion_rate")
)
String Length
messages.with_columns(
pl.col("ssot__ContentText__c").str.len_chars().alias("msg_length")
)
Conditional Column
sessions.with_columns(
pl.when(pl.col("ssot__AiAgentSessionEndType__c") == "Completed")
.then(pl.lit("Success"))
.otherwise(pl.lit("Failure"))
.alias("outcome")
)
Sorting
Single Column
sessions.sort("ssot__StartTimestamp__c", descending=True)
Multiple Columns
sessions.sort(["ssot__AiAgentApiName__c", "ssot__StartTimestamp__c"])
Output
Collect (Execute)
result = sessions.filter(...).collect() # Returns DataFrame
Write Parquet
result.write_parquet("output.parquet")
Write CSV
result.write_csv("output.csv")
To Python Dict
result.to_dicts() # List of dicts
result.row(0, named=True) # Single row as dict
Performance Tips
1. Use Lazy Evaluation
# Good: Lazy, optimized query plan
result = (
pl.scan_parquet(path)
.filter(...)
.group_by(...)
.agg(...)
.collect()
)
# Avoid: Eager, loads everything
df = pl.read_parquet(path)
result = df.filter(...)
2. Select Early
# Good: Only load needed columns
sessions.select(["ssot__Id__c", "ssot__AiAgentApiName__c"]).filter(...)
# Avoid: Load all, filter later
sessions.filter(...).select(...)
3. Filter Before Join
# Good: Filter before joining
filtered_sessions = sessions.filter(pl.col("ssot__AiAgentApiName__c") == "My_Agent")
filtered_sessions.join(interactions, ...)
# Avoid: Join everything, then filter
sessions.join(interactions, ...).filter(...)
4. Use Streaming for Large Results
# For very large datasets
sessions.collect(streaming=True)
Common Patterns
Session Statistics
sessions.group_by("ssot__AiAgentApiName__c").agg([
pl.count().alias("sessions"),
pl.col("ssot__AiAgentSessionEndType__c")
.filter(pl.col("ssot__AiAgentSessionEndType__c") == "Completed")
.count().alias("completed"),
pl.col("ssot__AiAgentSessionEndType__c")
.filter(pl.col("ssot__AiAgentSessionEndType__c") == "Escalated")
.count().alias("escalated"),
]).collect()
Daily Trend
sessions.with_columns(
pl.col("ssot__StartTimestamp__c").str.slice(0, 10).alias("date")
).group_by("date").agg(
pl.count().alias("sessions")
).sort("date").collect()
Top N Actions
steps.filter(
pl.col("ssot__AiAgentInteractionStepType__c") == "ACTION_STEP"
).group_by("ssot__Name__c").agg(
pl.count().alias("invocations")
).sort("invocations", descending=True).head(10).collect()
See Also
- Analysis Cookbook - Full recipes
- Polars Documentation
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Data Cloud Query Patterns
Common query patterns for extracting and analyzing Agentforce session tracing data.
Official Reference: Get Insights from Agent Session Tracing Data
Basic Extraction Queries
All Sessions (Last 7 Days)
SELECT
ssot__Id__c,
ssot__AiAgentChannelType__c,
ssot__StartTimestamp__c,
ssot__EndTimestamp__c,
ssot__AiAgentSessionEndType__c
FROM ssot__AIAgentSession__dlm
WHERE ssot__StartTimestamp__c >= '2026-01-21T00:00:00.000Z'
ORDER BY ssot__StartTimestamp__c DESC;
Sessions by Agent (via Moment Join)
Note: Agent name is stored on the Moment table, not Session. Use a JOIN to filter by agent.
SELECT DISTINCT s.*
FROM ssot__AIAgentSession__dlm s
JOIN ssot__AiAgentMoment__dlm m
ON m.ssot__AiAgentSessionId__c = s.ssot__Id__c
WHERE m.ssot__AiAgentApiName__c = 'Customer_Support_Agent'
AND s.ssot__StartTimestamp__c >= '2026-01-01T00:00:00.000Z'
ORDER BY s.ssot__StartTimestamp__c DESC;
Failed/Escalated Sessions
SELECT *
FROM ssot__AIAgentSession__dlm
WHERE ssot__AiAgentSessionEndType__c IN ('Escalated', 'Abandoned', 'Failed')
AND ssot__StartTimestamp__c >= '2026-01-01T00:00:00.000Z'
ORDER BY ssot__StartTimestamp__c DESC;
Aggregation Queries
Session Count by Agent (via Moment)
Note: Agent name is on the Moment table. Query Moments and count distinct sessions.
SELECT
ssot__AiAgentApiName__c as agent,
COUNT(DISTINCT ssot__AiAgentSessionId__c) as session_count
FROM ssot__AiAgentMoment__dlm
WHERE ssot__StartTimestamp__c >= '2026-01-01T00:00:00.000Z'
GROUP BY ssot__AiAgentApiName__c
ORDER BY session_count DESC;
End Type Distribution
SELECT
ssot__AiAgentSessionEndType__c as end_type,
COUNT(*) as count
FROM ssot__AIAgentSession__dlm
WHERE ssot__StartTimestamp__c >= '2026-01-01T00:00:00.000Z'
GROUP BY ssot__AiAgentSessionEndType__c;
Topic Usage
SELECT
ssot__TopicApiName__c as topic,
COUNT(*) as turn_count
FROM ssot__AIAgentInteraction__dlm
WHERE ssot__AiAgentInteractionType__c = 'TURN'
GROUP BY ssot__TopicApiName__c
ORDER BY turn_count DESC;
Action Invocation Frequency
SELECT
ssot__Name__c as action_name,
COUNT(*) as invocation_count
FROM ssot__AIAgentInteractionStep__dlm
WHERE ssot__AiAgentInteractionStepType__c = 'ACTION_STEP'
GROUP BY ssot__Name__c
ORDER BY invocation_count DESC;
Relationship Queries
Session with Turn Count
SELECT
s.ssot__Id__c,
s.ssot__AiAgentChannelType__c,
COUNT(i.ssot__Id__c) as turn_count
FROM ssot__AIAgentSession__dlm s
LEFT JOIN ssot__AIAgentInteraction__dlm i
ON i.ssot__AiAgentSessionId__c = s.ssot__Id__c
AND i.ssot__AiAgentInteractionType__c = 'TURN'
WHERE s.ssot__StartTimestamp__c >= '2026-01-01T00:00:00.000Z'
GROUP BY s.ssot__Id__c, s.ssot__AiAgentChannelType__c;
Complete Session Tree
-- Step 1: Get session
SELECT * FROM ssot__AIAgentSession__dlm
WHERE ssot__Id__c = 'a0x1234567890ABC';
-- Step 2: Get interactions
SELECT * FROM ssot__AIAgentInteraction__dlm
WHERE ssot__AiAgentSessionId__c = 'a0x1234567890ABC';
-- Step 3: Get steps (using interaction IDs from step 2)
SELECT * FROM ssot__AIAgentInteractionStep__dlm
WHERE ssot__AiAgentInteractionId__c IN ('a0y...', 'a0y...');
-- Step 4: Get messages (using interaction IDs from step 2)
SELECT * FROM ssot__AIAgentMoment__dlm
WHERE ssot__AiAgentInteractionId__c IN ('a0y...', 'a0y...');
Time-Based Queries
Daily Session Counts
SELECT
SUBSTRING(ssot__StartTimestamp__c, 1, 10) as date,
COUNT(*) as session_count
FROM ssot__AIAgentSession__dlm
WHERE ssot__StartTimestamp__c >= '2026-01-01T00:00:00.000Z'
GROUP BY SUBSTRING(ssot__StartTimestamp__c, 1, 10)
ORDER BY date;
Hourly Distribution
SELECT
SUBSTRING(ssot__StartTimestamp__c, 12, 2) as hour,
COUNT(*) as session_count
FROM ssot__AIAgentSession__dlm
WHERE ssot__StartTimestamp__c >= '2026-01-01T00:00:00.000Z'
GROUP BY SUBSTRING(ssot__StartTimestamp__c, 12, 2)
ORDER BY hour;
Analysis Queries
Sessions with Topic Switches
SELECT
ssot__AiAgentSessionId__c,
COUNT(DISTINCT ssot__TopicApiName__c) as topic_count
FROM ssot__AIAgentInteraction__dlm
WHERE ssot__AiAgentInteractionType__c = 'TURN'
GROUP BY ssot__AiAgentSessionId__c
HAVING COUNT(DISTINCT ssot__TopicApiName__c) > 1;
Long Sessions (Many Turns)
SELECT
ssot__AiAgentSessionId__c,
COUNT(*) as turn_count
FROM ssot__AIAgentInteraction__dlm
WHERE ssot__AiAgentInteractionType__c = 'TURN'
GROUP BY ssot__AiAgentSessionId__c
HAVING COUNT(*) > 10
ORDER BY turn_count DESC;
Actions with High Failure Rate
-- Note: This requires output parsing for error detection
SELECT
ssot__Name__c as action_name,
COUNT(*) as total_invocations,
COUNT(CASE WHEN ssot__OutputValueText__c LIKE '%error%' THEN 1 END) as errors
FROM ssot__AIAgentInteractionStep__dlm
WHERE ssot__AiAgentInteractionStepType__c = 'ACTION_STEP'
GROUP BY ssot__Name__c;
Performance Tips
Use Date Filters Early
-- Good: Filter by date first
WHERE ssot__StartTimestamp__c >= '2026-01-01T00:00:00.000Z'
AND ssot__AiAgentSessionEndType__c = 'Completed'
-- Avoid: No date filter on large tables
WHERE ssot__AiAgentSessionEndType__c = 'Completed'
Limit Result Sets
-- Use LIMIT for exploration
SELECT * FROM ssot__AIAgentSession__dlm
WHERE ssot__StartTimestamp__c >= '2026-01-01T00:00:00.000Z'
ORDER BY ssot__StartTimestamp__c DESC
LIMIT 100;
Select Only Needed Columns
-- Good: Select specific columns
SELECT ssot__Id__c, ssot__AiAgentChannelType__c, ssot__StartTimestamp__c
FROM ssot__AIAgentSession__dlm;
-- Avoid: SELECT * on wide tables
SELECT * FROM ssot__AIAgentInteractionStep__dlm; -- Has large text fields
Official Example Queries (from Salesforce Help)
These are official query patterns from the Salesforce documentation.
Full Session Join (All Entities)
SELECT *
FROM "AiAgentSession__dlm"
JOIN "AiAgentSessionParticipant__dlm"
ON "AiAgentSession__dlm"."id__c" = "AiAgentSessionParticipant__dlm"."aiAgentSessionId__c"
JOIN "AiAgentInteraction__dlm"
ON "AiAgentSession__dlm"."id__c" = "AiAgentInteraction__dlm"."aiAgentSessionId__c"
JOIN "AiAgentInteractionMessage__dlm"
ON "AiAgentInteraction__dlm"."id__c" = "AiAgentInteractionMessage__dlm"."aiAgentInteractionId__c"
JOIN "AiAgentInteractionStep__dlm"
ON "AiAgentInteraction__dlm"."id__c" = "AiAgentInteractionStep__dlm"."aiAgentInteractionId__c"
WHERE "AiAgentSession__dlm"."id__c" = '{{SESSION_ID}}'
LIMIT 10;
Recent Sessions (Last N Days)
SELECT
ssot__Id__c,
ssot__StartTimestamp__c
FROM ssot__AiAgentSession__dlm s
WHERE s.ssot__StartTimestamp__c >= current_date - INTERVAL '7' DAY
ORDER BY s.ssot__StartTimestamp__c DESC;
All Messages in an Interaction
SELECT
ssot__AiAgentInteractionId__c AS InteractionId,
ssot__AiAgentInteractionMessageType__c, -- user or agent
ssot__AiAgentInteractionMsgContentType__c, -- e.g., text
ssot__ContentText__c,
ssot__AiAgentSessionParticipantId__c AS SenderParticipantId,
ssot__ParentMessageId__c -- if part of a thread
FROM "ssot__AiAgentInteractionMessage__dlm"
WHERE ssot__AiAgentInteractionId__c = '{{INTERACTION_ID}}'
ORDER BY ssot__MessageSentTimestamp__c ASC;
Steps with Errors
Find all interaction steps that encountered errors:
SELECT
ssot__AiAgentInteractionId__c AS InteractionId,
ssot__Id__c AS StepId,
ssot__Name__c AS StepName,
ssot__InputValueText__c AS Input,
ssot__ErrorMessageText__c AS StepErrorMessage
FROM "ssot__AiAgentInteractionStep__dlm"
WHERE length(ssot__ErrorMessageText__c) > 0
AND ssot__ErrorMessageText__c != 'NOT_SET'
LIMIT 100;
Join with GenAI Feedback Data
Combine session tracing with feedback and guardrails metrics:
SELECT
ssot__AiAgentInteractionId__c AS InteractionId,
ssot__Name__c AS StepName,
GenAIGatewayRequest__dlm.prompt__c AS Input_Prompt,
GenAIGeneration__dlm.responseText__c AS LLM_Response,
GenAIFeedback__dlm.feedback__c AS Feedback
FROM ssot__AiAgentInteractionStep__dlm
LEFT JOIN GenAIGeneration__dlm
ON ssot__AiAgentInteractionStep__dlm.ssot__GenerationId__c = GenAIGeneration__dlm.generationId__c
LEFT JOIN GenAIGatewayRequest__dlm
ON ssot__AiAgentInteractionStep__dlm.ssot__GenAiGatewayRequestId__c = GenAIGatewayRequest__dlm.gatewayRequestId__c
LEFT JOIN GenAIGatewayResponse__dlm
ON GenAIGatewayRequest__dlm.gatewayRequestId__c = GenAIGatewayResponse__dlm.generationRequestId__c
LEFT JOIN GenAIFeedback__dlm
ON GenAIGeneration__dlm.generationId__c = GenAIFeedback__dlm.generationId__c
WHERE GenAIGatewayResponse__dlm.generationResponseId__c = GenAIGeneration__dlm.generationResponseId__c
LIMIT 100;
Advanced Session Inspection
Full Session Details (All Related Entities)
Join all session tracing entities for complete visibility:
SELECT *
FROM ssot__AiAgentSession__dlm s
JOIN ssot__AiAgentSessionParticipant__dlm sp
ON s.ssot__id__c = sp.ssot__AiAgentSessionId__c
JOIN ssot__AiAgentInteraction__dlm i
ON s.ssot__id__c = i.ssot__AiAgentSessionId__c
JOIN ssot__AiAgentInteractionMessage__dlm im
ON i.ssot__id__c = im.ssot__AiAgentInteractionId__c
JOIN ssot__AiAgentInteractionStep__dlm st
ON i.ssot__id__c = st.ssot__AiAgentInteractionId__c
WHERE s.ssot__id__c = '{{SESSION_ID}}'
LIMIT 100;
Note: This query includes SessionParticipant and InteractionMessage entities not in basic extraction.
Session Insights with CTEs
Use CTEs for complex session analysis with messages and steps:
WITH
-- Store session ID for reuse
params AS (
SELECT '{{SESSION_ID}}' AS session_id
),
-- Get interactions with their messages
interactionsWithMessages AS (
SELECT
i.ssot__Id__c AS InteractionId,
i.ssot__TopicApiName__c AS TopicName,
i.ssot__AiAgentInteractionType__c AS InteractionType,
i.ssot__StartTimestamp__c AS InteractionStartTime,
i.ssot__EndTimestamp__c AS InteractionEndTime,
im.ssot__SentTime__c AS MessageSentTime,
im.ssot__MessageType__c AS InteractionMessageType,
im.ssot__ContextText__c AS ContextText,
NULL AS InteractionStepType,
NULL AS Name,
NULL AS InputValueText,
NULL AS OutputValueText,
NULL AS PreStepVariableText,
NULL AS PostStepVariableText
FROM ssot__AiAgentInteraction__dlm i
JOIN ssot__AiAgentInteractionMessage__dlm im
ON i.ssot__Id__c = im.ssot__AiAgentInteractionId__c
WHERE i.ssot__AiAgentSessionId__c = (SELECT session_id FROM params)
),
-- Get interactions with their steps
interactionsWithSteps AS (
SELECT
i.ssot__Id__c AS InteractionId,
i.ssot__TopicApiName__c AS TopicName,
i.ssot__AiAgentInteractionType__c AS InteractionType,
i.ssot__StartTimestamp__c AS InteractionStartTime,
i.ssot__EndTimestamp__c AS InteractionEndTime,
st.ssot__StartTimestamp__c AS MessageSentTime,
NULL AS InteractionMessageType,
NULL AS ContextText,
st.ssot__AiAgentInteractionStepType__c AS InteractionStepType,
st.ssot__Name__c AS Name,
st.ssot__InputValueText__c AS InputValueText,
st.ssot__OutputValueText__c AS OutputValueText,
st.ssot__PreStepVariableText__c AS PreStepVariableText,
st.ssot__PostStepVariableText__c AS PostStepVariableText
FROM ssot__AiAgentInteraction__dlm i
JOIN ssot__AiAgentInteractionStep__dlm st
ON i.ssot__Id__c = st.ssot__AiAgentInteractionId__c
WHERE i.ssot__AiAgentSessionId__c = (SELECT session_id FROM params)
),
-- Combine messages and steps
combined AS (
SELECT * FROM interactionsWithMessages
UNION ALL
SELECT * FROM interactionsWithSteps
)
-- Final output sorted chronologically
SELECT
TopicName,
InteractionType,
InteractionStartTime,
InteractionEndTime,
MessageSentTime,
InteractionMessageType,
ContextText,
InteractionStepType,
Name,
InputValueText,
OutputValueText,
PreStepVariableText,
PostStepVariableText
FROM combined
ORDER BY MessageSentTime ASC;
Tips for Finding Session IDs:
- For Service Agent: Use
ssot__RelatedMessagingSessionId__cfield onssot__AiAgentSession__dlm - Use start/end timestamp fields to narrow down timeframes
Quality Analysis Queries
Toxic Response Detection
Find generations flagged as toxic and trace back to sessions:
SELECT
i.ssot__AiAgentSessionId__c AS SessionId,
i.ssot__TopicApiName__c AS TopicName,
g.responseText__c AS ResponseText,
c.category__c AS ToxicityCategory,
c.value__c AS ConfidenceScore
FROM GenAIContentQuality__dlm AS q
JOIN GenAIContentCategory__dlm AS c
ON c.parent__c = q.id__c
JOIN GenAIGeneration__dlm AS g
ON g.generationId__c = q.parent__c
JOIN ssot__AiAgentInteractionStep__dlm st
ON st.ssot__GenerationId__c = g.generationId__c
JOIN ssot__AiAgentInteraction__dlm i
ON st.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE
q.isToxicityDetected__c = 'true'
AND TRY_CAST(c.value__c AS DECIMAL) >= 0.5
LIMIT 100;
Join Chain: ContentQuality → ContentCategory → Generation → Step → Interaction → Session
Low Instruction Adherence Detection
Find sessions where agent responses didn't follow instructions well:
SELECT
i.ssot__AiAgentSessionId__c AS SessionId,
i.ssot__TopicApiName__c AS TopicName,
g.responseText__c AS ResponseText,
c.category__c AS AdherenceLevel,
c.value__c AS ConfidenceScore
FROM GenAIContentCategory__dlm AS c
JOIN GenAIGeneration__dlm AS g
ON g.generationId__c = c.parent__c
JOIN ssot__AiAgentInteractionStep__dlm st
ON st.ssot__GenerationId__c = g.generationId__c
JOIN ssot__AiAgentInteraction__dlm i
ON st.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE
c.detectorType__c = 'InstructionAdherence'
AND c.category__c = 'Low'
LIMIT 100;
Detector Types (Live API Verified - T6 Discovery):
| Detector Type | Occurrences | Categories/Values |
|---|---|---|
TOXICITY |
627,603 | hate, identity, physical, profanity, safety_score, sexual, toxicity, violence |
PROMPT_DEFENSE |
119,050 | aggregatePromptAttackScore, isPromptAttackDetected |
PII |
27,805 | CREDIT_CARD, EMAIL_ADDRESS, PERSON, US_PHONE_NUMBER |
InstructionAdherence |
16,380 | High, Low, Uncertain |
Detection Thresholds:
- Toxicity:
value__c >= 0.5indicates toxic content - PII: Any category present indicates PII detection
- PROMPT_DEFENSE:
isPromptAttackDetected=trueindicates attack - InstructionAdherence:
Lowcategory indicates poor adherence
Unresolved Tasks Detection
Find sessions where user requests weren't fully resolved:
SELECT
i.ssot__AiAgentSessionId__c AS SessionId,
i.ssot__TopicApiName__c AS TopicName,
g.responseText__c AS ResponseText,
c.category__c AS ResolutionStatus,
c.value__c AS ConfidenceScore
FROM GenAIContentCategory__dlm AS c
JOIN GenAIGeneration__dlm AS g
ON g.generationId__c = c.parent__c
JOIN ssot__AiAgentInteractionStep__dlm st
ON st.ssot__GenerationId__c = g.generationId__c
JOIN ssot__AiAgentInteraction__dlm i
ON st.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE
c.detectorType__c = 'TaskResolution'
AND c.category__c != 'FULLY_RESOLVED'
LIMIT 100;
PII Detection Analysis ✅ NEW
Find sessions where PII was detected in user inputs or agent responses:
SELECT
c.category__c AS PiiType,
COUNT(*) AS DetectionCount
FROM GenAIContentCategory__dlm c
WHERE c.detectorType__c = 'PII'
AND c.timestamp__c >= current_date - INTERVAL '30' DAY
GROUP BY c.category__c
ORDER BY DetectionCount DESC;
PII Categories:
| Category | Description |
|---|---|
CREDIT_CARD |
Credit card numbers |
EMAIL_ADDRESS |
Email addresses |
PERSON |
Person names |
US_PHONE_NUMBER |
US phone numbers |
Prompt Attack Detection ✅ NEW
Find sessions with potential prompt injection attacks:
SELECT
i.ssot__AiAgentSessionId__c AS SessionId,
i.ssot__TopicApiName__c AS TopicName,
c.category__c AS AttackCategory,
c.value__c AS Score
FROM GenAIContentCategory__dlm c
JOIN GenAIGeneration__dlm g
ON g.generationId__c = c.parent__c
JOIN ssot__AiAgentInteractionStep__dlm st
ON st.ssot__GenerationId__c = g.generationId__c
JOIN ssot__AiAgentInteraction__dlm i
ON st.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE c.detectorType__c = 'PROMPT_DEFENSE'
AND c.category__c = 'isPromptAttackDetected'
AND c.value__c = 'true'
LIMIT 100;
Hallucination Detection (UNGROUNDED Responses)
Find responses flagged as ungrounded by the validation prompt:
-- Note: Uses JSON parsing functions
WITH llmResponses AS (
SELECT
i.ssot__AiAgentSessionId__c AS SessionId,
ssot__InputValueText__c::JSON->'messages'->-1->>'content' AS LastMessage,
ssot__OutputValueText__c::JSON->>'llmResponse' AS llmResponse,
st.ssot__StartTimestamp__c AS InteractionStepStartTime
FROM ssot__AiAgentInteractionStep__dlm st
JOIN ssot__AiAgentInteraction__dlm i
ON st.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE
st.ssot__AiAgentInteractionStepType__c = 'LLM_STEP'
AND st.ssot__Name__c = 'AiCopilot__ReactValidationPrompt'
AND st.ssot__OutputValueText__c LIKE '%UNGROUNDED%'
LIMIT 100
)
SELECT
InteractionStepStartTime,
SessionId,
TRIM('"' FROM SPLIT_PART(SPLIT_PART(LastMessage, '"response": "', 2), '"', 1)) AS AgentResponse,
CAST(llmResponse AS JSON)->>'reason' AS UngroundedReason
FROM llmResponses
ORDER BY InteractionStepStartTime;
Key Step Names for Analysis:
| Step Name | Purpose |
|---|---|
AiCopilot__ReactTopicPrompt |
Topic routing decision |
AiCopilot__ReactInitialPrompt |
Initial planning/reasoning |
AiCopilot__ReactValidationPrompt |
Response validation (hallucination check) |
GenAI Gateway Analysis ✅ NEW
Query patterns for analyzing LLM usage, token consumption, and model performance.
Token Usage by Model
Analyze token consumption across different models:
SELECT
model__c AS Model,
COUNT(*) AS RequestCount,
SUM(promptTokens__c) AS TotalPromptTokens,
SUM(completionTokens__c) AS TotalCompletionTokens,
SUM(totalTokens__c) AS TotalTokens,
AVG(totalTokens__c) AS AvgTokensPerRequest
FROM GenAIGatewayRequest__dlm
WHERE timestamp__c >= current_date - INTERVAL '7' DAY
GROUP BY model__c
ORDER BY TotalTokens DESC;
Prompt Template Usage
Find which prompt templates are most frequently used:
SELECT
promptTemplateDevName__c AS TemplateName,
promptTemplateVersionNo__c AS Version,
COUNT(*) AS UsageCount,
AVG(totalTokens__c) AS AvgTokens
FROM GenAIGatewayRequest__dlm
WHERE timestamp__c >= current_date - INTERVAL '30' DAY
AND promptTemplateDevName__c IS NOT NULL
GROUP BY promptTemplateDevName__c, promptTemplateVersionNo__c
ORDER BY UsageCount DESC;
Safety Configuration Analysis
Analyze which safety features are enabled across requests:
SELECT
enableInputSafetyScoring__c AS InputSafety,
enableOutputSafetyScoring__c AS OutputSafety,
enablePiiMasking__c AS PiiMasking,
COUNT(*) AS RequestCount
FROM GenAIGatewayRequest__dlm
WHERE timestamp__c >= current_date - INTERVAL '7' DAY
GROUP BY enableInputSafetyScoring__c, enableOutputSafetyScoring__c, enablePiiMasking__c
ORDER BY RequestCount DESC;
User Feedback Summary
Analyze user feedback distribution:
SELECT
feedback__c AS FeedbackType,
COUNT(*) AS FeedbackCount
FROM GenAIFeedback__dlm
WHERE timestamp__c >= current_date - INTERVAL '30' DAY
GROUP BY feedback__c
ORDER BY FeedbackCount DESC;
Feedback with Details
Get detailed feedback with user comments:
SELECT
f.feedbackId__c,
f.feedback__c AS FeedbackType,
f.action__c AS UserAction,
fd.feedbackText__c AS UserComment,
f.timestamp__c
FROM GenAIFeedback__dlm f
LEFT JOIN GenAIFeedbackDetail__dlm fd
ON fd.parent__c = f.feedbackId__c
WHERE f.timestamp__c >= current_date - INTERVAL '7' DAY
ORDER BY f.timestamp__c DESC
LIMIT 100;
High-Cost Requests
Find requests with unusually high token consumption:
SELECT
gatewayRequestId__c,
model__c AS Model,
promptTokens__c,
completionTokens__c,
totalTokens__c,
feature__c,
timestamp__c
FROM GenAIGatewayRequest__dlm
WHERE totalTokens__c > 4000
AND timestamp__c >= current_date - INTERVAL '7' DAY
ORDER BY totalTokens__c DESC
LIMIT 50;
Knowledge Retrieval Analysis
Vector Search for Knowledge Gaps
Query the knowledge search index to understand what chunks were retrieved for a user query:
SELECT
v.Score__c AS Score,
kav.Chat_Answer__c AS KnowledgeAnswer,
c.Chunk__c AS ChunkText,
c.SourceRecordId__c AS SourceRecordId,
c.DataSource__c AS DataSource
FROM vector_search(
TABLE("External_Knowledge_Search_Index_index__dlm"),
'{{USER_QUERY}}',
'{{FILTER_CLAUSE}}',
30
) v
INNER JOIN "External_Knowledge_Search_Index_chunk__dlm" c
ON c.RecordId__c = v.RecordId__c
INNER JOIN "{{KNOWLEDGE_ARTICLE_DMO}}" kav
ON c.SourceRecordId__c = kav.Id__c
ORDER BY Score DESC
LIMIT 10;
Parameters:
{{USER_QUERY}}: The search query text{{FILTER_CLAUSE}}: Optional filter like'Country_Code__c=''US'''{{KNOWLEDGE_ARTICLE_DMO}}: Your org's Knowledge DMO name (e.g.,Knowledge_kav_Prod_00D58000000JmkM__dlm)
Improving Knowledge Articles Workflow
- Identify low-quality moments: Agentforce Studio → Observe → Optimization → Insights
- Filter by topic and quality: Topics includes
General_FAQ..., Quality Score < Medium - Get Session ID from Moments view
- Query STDM with session ID to inspect ACTION_STEP
- Examine actionName and actionInput in step output
- Run vector_search with the user query to see retrieved chunks
- Identify SourceRecordId to find knowledge articles needing improvement
Inspecting Action Steps for Knowledge Calls
Find ACTION_STEP details for a session:
SELECT
st.ssot__Name__c AS ActionName,
st.ssot__AiAgentInteractionStepType__c AS StepType,
st.ssot__InputValueText__c AS InputValue,
st.ssot__OutputValueText__c AS OutputValue,
st.ssot__StartTimestamp__c AS StartTime
FROM ssot__AiAgentInteractionStep__dlm st
JOIN ssot__AiAgentInteraction__dlm i
ON st.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE
i.ssot__AiAgentSessionId__c = '{{SESSION_ID}}'
AND st.ssot__AiAgentInteractionStepType__c = 'ACTION_STEP'
ORDER BY st.ssot__StartTimestamp__c;
ACTION_STEP Output Contains:
actionName: The invoked action (e.g.,General_FAQ0_16jWi00000001...)actionInput: Parameters passed to the action- Retrieved knowledge chunks in the response
Advanced CTE Patterns
Complex CTE (Common Table Expression) patterns for advanced session analysis.
CTE Pattern 1: Session Summary with Stats
Aggregate turn counts and step counts per session:
WITH session_stats AS (
SELECT
s.ssot__Id__c,
s.ssot__AiAgentChannelType__c as channel_type,
s.ssot__AiAgentSessionEndType__c as end_type,
COUNT(DISTINCT i.ssot__Id__c) as turn_count,
COUNT(DISTINCT st.ssot__Id__c) as step_count
FROM ssot__AIAgentSession__dlm s
LEFT JOIN ssot__AIAgentInteraction__dlm i
ON i.ssot__AiAgentSessionId__c = s.ssot__Id__c
LEFT JOIN ssot__AIAgentInteractionStep__dlm st
ON st.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE s.ssot__StartTimestamp__c >= current_date - INTERVAL '7' DAY
GROUP BY s.ssot__Id__c, s.ssot__AiAgentChannelType__c, s.ssot__AiAgentSessionEndType__c
)
SELECT * FROM session_stats WHERE turn_count > 5
ORDER BY step_count DESC;
CTE Pattern 2: Error Analysis by Topic
Find which topics have the most action errors:
WITH topic_errors AS (
SELECT
i.ssot__TopicApiName__c as topic,
st.ssot__Name__c as action_name,
st.ssot__ErrorMessageText__c as error
FROM ssot__AIAgentInteractionStep__dlm st
JOIN ssot__AIAgentInteraction__dlm i
ON st.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE length(st.ssot__ErrorMessageText__c) > 0
AND st.ssot__ErrorMessageText__c != 'NOT_SET'
AND st.ssot__StartTimestamp__c >= current_date - INTERVAL '30' DAY
)
SELECT topic, action_name, COUNT(*) as error_count
FROM topic_errors
GROUP BY topic, action_name
ORDER BY error_count DESC;
CTE Pattern 3: Session Timeline Reconstruction
Reconstruct the full timeline of events (messages + steps) for a session:
WITH
params AS (
SELECT '{{SESSION_ID}}' AS session_id
),
session_events AS (
-- Messages
SELECT
'MESSAGE' as event_type,
im.ssot__MessageSentTimestamp__c as timestamp,
im.ssot__AiAgentInteractionMessageType__c as detail,
i.ssot__AiAgentSessionId__c as session_id
FROM ssot__AiAgentInteractionMessage__dlm im
JOIN ssot__AiAgentInteraction__dlm i
ON im.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE i.ssot__AiAgentSessionId__c = (SELECT session_id FROM params)
UNION ALL
-- Steps
SELECT
st.ssot__AiAgentInteractionStepType__c as event_type,
st.ssot__StartTimestamp__c as timestamp,
st.ssot__Name__c as detail,
i.ssot__AiAgentSessionId__c as session_id
FROM ssot__AIAgentInteractionStep__dlm st
JOIN ssot__AiAgentInteraction__dlm i
ON st.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE i.ssot__AiAgentSessionId__c = (SELECT session_id FROM params)
)
SELECT event_type, timestamp, detail
FROM session_events
ORDER BY timestamp ASC;
CTE Pattern 4: Quality Metrics Dashboard
Aggregate quality metrics by detector type:
WITH quality_summary AS (
SELECT
c.detectorType__c,
c.category__c,
COUNT(*) as count,
AVG(TRY_CAST(c.value__c AS DECIMAL)) as avg_score
FROM GenAIContentCategory__dlm c
GROUP BY c.detectorType__c, c.category__c
)
SELECT
detectorType__c as detector,
category__c as category,
count,
ROUND(avg_score, 3) as avg_confidence
FROM quality_summary
ORDER BY detector, count DESC;
Note: This query requires GenAI Trust Layer DMOs to be enabled.
CTE Pattern 5: Topic Routing Analysis
Analyze how users are routed between topics within sessions:
WITH topic_transitions AS (
SELECT
curr.ssot__AiAgentSessionId__c as session_id,
prev.ssot__TopicApiName__c as from_topic,
curr.ssot__TopicApiName__c as to_topic,
curr.ssot__StartTimestamp__c as transition_time
FROM ssot__AIAgentInteraction__dlm curr
JOIN ssot__AIAgentInteraction__dlm prev
ON curr.ssot__PrevInteractionId__c = prev.ssot__Id__c
WHERE curr.ssot__TopicApiName__c != prev.ssot__TopicApiName__c
AND curr.ssot__StartTimestamp__c >= current_date - INTERVAL '30' DAY
)
SELECT
from_topic,
to_topic,
COUNT(*) as transition_count
FROM topic_transitions
GROUP BY from_topic, to_topic
ORDER BY transition_count DESC;
Use Cases:
- Identify common topic escalation paths
- Find topics that frequently need fallback routing
- Understand user journey patterns
Tag System Queries ✅ NEW
Query the Agentforce tagging system for session categorization and analytics.
Get Tag Definitions
List all available tag definitions in the org:
SELECT
ssot__Id__c,
ssot__Name__c,
ssot__DeveloperName__c,
ssot__Description__c,
ssot__DataType__c,
ssot__SourceType__c
FROM ssot__AiAgentTagDefinition__dlm
ORDER BY ssot__CreatedDate__c DESC
LIMIT 50;
Get Tag Values for a Definition
List all values for a specific tag definition:
SELECT
t.ssot__Id__c,
t.ssot__Description__c,
t.ssot__IsActive__c,
td.ssot__Name__c as TagDefinitionName
FROM ssot__AiAgentTag__dlm t
JOIN ssot__AiAgentTagDefinition__dlm td
ON t.ssot__AiAgentTagDefinitionId__c = td.ssot__Id__c
WHERE td.ssot__DeveloperName__c = 'Escalation_Reason'
AND t.ssot__IsActive__c = true
ORDER BY t.ssot__CreatedDate__c DESC;
Sessions with Tag Associations
Find sessions that have been tagged:
SELECT
s.ssot__Id__c AS SessionId,
s.ssot__StartTimestamp__c,
ta.ssot__AiAgentTagDefinitionAssociationId__c AS TagAssociation,
ta.ssot__CreatedDate__c AS TaggedAt
FROM ssot__AIAgentSession__dlm s
JOIN ssot__AiAgentTagAssociation__dlm ta
ON s.ssot__Id__c = ta.ssot__AiAgentSessionId__c
WHERE s.ssot__StartTimestamp__c >= current_date - INTERVAL '7' DAY
ORDER BY s.ssot__StartTimestamp__c DESC
LIMIT 100;
Tag Distribution Analysis
Count sessions by tag:
SELECT
td.ssot__Name__c AS TagName,
COUNT(DISTINCT ta.ssot__AiAgentSessionId__c) AS SessionCount
FROM ssot__AiAgentTagAssociation__dlm ta
JOIN ssot__AiAgentTagDefinitionAssociation__dlm tda
ON ta.ssot__AiAgentTagDefinitionAssociationId__c = tda.ssot__Id__c
JOIN ssot__AiAgentTagDefinition__dlm td
ON tda.ssot__AiAgentTagDefinitionId__c = td.ssot__Id__c
WHERE ta.ssot__CreatedDate__c >= current_date - INTERVAL '30' DAY
GROUP BY td.ssot__Name__c
ORDER BY SessionCount DESC;
Tags by Agent
Find which tags are configured for each agent:
SELECT
tda.ssot__AiAgentApiName__c AS AgentName,
td.ssot__Name__c AS TagName,
td.ssot__DataType__c AS DataType,
td.ssot__SourceType__c AS SourceType
FROM ssot__AiAgentTagDefinitionAssociation__dlm tda
JOIN ssot__AiAgentTagDefinition__dlm td
ON tda.ssot__AiAgentTagDefinitionId__c = td.ssot__Id__c
ORDER BY tda.ssot__AiAgentApiName__c, td.ssot__Name__c;
Tag Values with Ratings
Get tag values (useful for rating-based tags):
SELECT
td.ssot__Name__c AS TagName,
t.ssot__Value__c AS Value,
t.ssot__Description__c AS Description,
t.ssot__IsActive__c AS IsActive
FROM ssot__AiAgentTag__dlm t
JOIN ssot__AiAgentTagDefinition__dlm td
ON t.ssot__AiAgentTagDefinitionId__c = td.ssot__Id__c
WHERE t.ssot__IsActive__c = true
ORDER BY td.ssot__Name__c, t.ssot__Value__c;
Step Analysis Patterns ✅ NEW
Query patterns for analyzing step execution, LLM calls, and action performance.
LLM Step Analysis by Prompt Type
Analyze LLM steps by the prompt type:
SELECT
ssot__Name__c AS PromptName,
COUNT(*) AS Invocations,
AVG(EXTRACT(EPOCH FROM (ssot__EndTimestamp__c - ssot__StartTimestamp__c))) AS AvgDurationSeconds
FROM ssot__AIAgentInteractionStep__dlm
WHERE ssot__AiAgentInteractionStepType__c = 'LLM_STEP'
AND ssot__StartTimestamp__c >= current_date - INTERVAL '7' DAY
AND ssot__Name__c LIKE 'AiCopilot%'
GROUP BY ssot__Name__c
ORDER BY Invocations DESC;
Common LLM Prompts
| Prompt Name | Purpose |
|---|---|
AiCopilot__ReactInitialPrompt |
Initial planning/reasoning |
AiCopilot__ReactTopicPrompt |
Topic classification/routing |
AiCopilot__ReactValidationPrompt |
Response validation (hallucination check) |
Top Actions by Invocation
Find the most frequently called actions:
SELECT
ssot__Name__c AS ActionName,
COUNT(*) AS InvocationCount,
COUNT(CASE WHEN length(ssot__ErrorMessageText__c) > 0
AND ssot__ErrorMessageText__c != 'NOT_SET' THEN 1 END) AS ErrorCount
FROM ssot__AIAgentInteractionStep__dlm
WHERE ssot__AiAgentInteractionStepType__c = 'ACTION_STEP'
AND ssot__StartTimestamp__c >= current_date - INTERVAL '30' DAY
GROUP BY ssot__Name__c
ORDER BY InvocationCount DESC
LIMIT 20;
Step Chain Analysis (Following PrevStepId)
Trace the step execution chain within an interaction:
WITH RECURSIVE step_chain AS (
-- Base: find the first step (no PrevStepId)
SELECT
ssot__Id__c,
ssot__Name__c,
ssot__AiAgentInteractionStepType__c,
ssot__PrevStepId__c,
1 as depth
FROM ssot__AIAgentInteractionStep__dlm
WHERE ssot__AiAgentInteractionId__c = '{{INTERACTION_ID}}'
AND ssot__PrevStepId__c IS NULL
UNION ALL
-- Recursive: follow PrevStepId chain
SELECT
s.ssot__Id__c,
s.ssot__Name__c,
s.ssot__AiAgentInteractionStepType__c,
s.ssot__PrevStepId__c,
sc.depth + 1
FROM ssot__AIAgentInteractionStep__dlm s
JOIN step_chain sc ON s.ssot__PrevStepId__c = sc.ssot__Id__c
WHERE sc.depth < 20
)
SELECT depth, ssot__AiAgentInteractionStepType__c, ssot__Name__c
FROM step_chain
ORDER BY depth;
Note: Steps use linear PrevStepId sequencing. There is no hierarchical parent-child relationship.
Moment-Interaction Junction Queries ✅ NEW
Query the junction table linking Moments to Interactions for many-to-many analysis.
Moments with Their Interactions
Get all interactions associated with a moment:
SELECT
m.ssot__Id__c AS MomentId,
m.ssot__RequestSummaryText__c,
mi.ssot__AiAgentInteractionId__c AS InteractionId,
i.ssot__TopicApiName__c AS Topic
FROM ssot__AiAgentMoment__dlm m
JOIN ssot__AiAgentMomentInteraction__dlm mi
ON m.ssot__Id__c = mi.ssot__AiAgentMomentId__c
JOIN ssot__AIAgentInteraction__dlm i
ON mi.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE m.ssot__StartTimestamp__c >= current_date - INTERVAL '7' DAY
LIMIT 50;
Interactions per Moment (Aggregated)
Count interactions associated with each moment:
SELECT
mi.ssot__AiAgentMomentId__c AS MomentId,
COUNT(*) AS InteractionCount
FROM ssot__AiAgentMomentInteraction__dlm mi
GROUP BY mi.ssot__AiAgentMomentId__c
HAVING COUNT(*) > 1
ORDER BY InteractionCount DESC
LIMIT 20;
Full Session Tree with Moments
Get complete session data including the Moment-Interaction relationship:
SELECT
s.ssot__Id__c AS SessionId,
m.ssot__AiAgentApiName__c AS AgentName,
m.ssot__RequestSummaryText__c AS RequestSummary,
m.ssot__ResponseSummaryText__c AS ResponseSummary,
i.ssot__Id__c AS InteractionId,
i.ssot__TopicApiName__c AS Topic
FROM ssot__AIAgentSession__dlm s
JOIN ssot__AiAgentMoment__dlm m
ON s.ssot__Id__c = m.ssot__AiAgentSessionId__c
LEFT JOIN ssot__AiAgentMomentInteraction__dlm mi
ON m.ssot__Id__c = mi.ssot__AiAgentMomentId__c
LEFT JOIN ssot__AIAgentInteraction__dlm i
ON mi.ssot__AiAgentInteractionId__c = i.ssot__Id__c
WHERE s.ssot__Id__c = '{{SESSION_ID}}'
ORDER BY m.ssot__StartTimestamp__c, i.ssot__StartTimestamp__c;
Entity Relationship Reference
Session Tracing Data Model (STDM)
Session (ssot__AiAgentSession__dlm)
├── SessionParticipant (ssot__AIAgentSessionParticipant__dlm) [1:N]
├── Interaction (ssot__AiAgentInteraction__dlm) [1:N]
│ ├── InteractionMessage (ssot__AiAgentInteractionMessage__dlm) [1:N]
│ └── InteractionStep (ssot__AiAgentInteractionStep__dlm) [1:N]
│ └── → links to GenAIGeneration via GenerationId
├── Moment (ssot__AiAgentMoment__dlm) [1:N]
│ └── MomentInteraction (ssot__AiAgentMomentInteraction__dlm) [N:M junction]
│ └── → links Moment ↔ Interaction
└── TagAssociation (ssot__AiAgentTagAssociation__dlm) [1:N] ✅ NEW
└── → links to TagDefinition & Tag
Tagging Data Model ✅ NEW
TagDefinition (ssot__AiAgentTagDefinition__dlm)
└── Tag (ssot__AiAgentTag__dlm) [1:N]
└── TagAssociation [N:M]
├── → Session (AiAgentSessionId)
└── → Moment (AiAgentMomentId)
Quality Data Model (GenAI Trust Layer) ✅ T6 Verified
GenAIGeneration__dlm
├── GenAIContentQuality__dlm [1:1]
│ └── GenAIContentCategory__dlm [1:N]
│ ├── detectorType__c: 'TOXICITY' | 'PII' | 'PROMPT_DEFENSE' | 'InstructionAdherence'
│ ├── category__c: Result category (see tables below)
│ └── value__c: Confidence score (0.0-1.0, string format)
└── GenAIFeedback__dlm [1:N]
└── GenAIFeedbackDetail__dlm [1:N]
Detector Categories (Live API Verified):
| Detector | Categories |
|---|---|
TOXICITY |
hate, identity, physical, profanity, safety_score, sexual, toxicity, violence |
PII |
CREDIT_CARD, EMAIL_ADDRESS, PERSON, US_PHONE_NUMBER |
PROMPT_DEFENSE |
aggregatePromptAttackScore, isPromptAttackDetected |
InstructionAdherence |
High, Low, Uncertain |
Gateway Data Model (GenAI Request/Response) ✅ T6 Verified
GenAIGatewayRequest__dlm (30 fields)
├── GenAIGatewayResponse__dlm [1:1]
├── GenAIGatewayRequestTag__dlm [1:N]
├── GenAIGtwyRequestMetadata__dlm [1:N]
├── GenAIGtwyObjRecord__dlm [1:N]
│ └── GenAIGtwyObjRecCitationRef__dlm [1:N]
└── GenAIGeneration__dlm [1:N] (via generationGroupId)
Key Join Fields:
ssot__GenerationId__con Steps →generationId__con Generationssot__GenAiGatewayRequestId__con Steps →gatewayRequestId__con GatewayRequestparent__con ContentQuality →generationId__con Generationparent__con ContentCategory →id__con ContentQualityparent__con FeedbackDetail →feedbackId__con Feedback
Template Variables
The query templates use these placeholders:
| Variable | Description | Example |
|---|---|---|
{{START_DATE}} |
Start timestamp | 2026-01-01T00:00:00.000Z |
{{END_DATE}} |
End timestamp | 2026-01-28T23:59:59.000Z |
{{AGENT_NAMES}} |
Comma-separated agent names | 'Agent1', 'Agent2' |
{{SESSION_IDS}} |
Comma-separated session IDs | 'a0x...', 'a0x...' |
{{SESSION_ID}} |
Single session ID | '01999669-0a54-724f-80d6-9cb495a7cee4' |
{{INTERACTION_IDS}} |
Comma-separated interaction IDs | 'a0y...', 'a0y...' |
Open this reference as its own page
<!-- Parent: sf-ai-agentforce-observability/SKILL.md -->Troubleshooting Guide
Common issues and solutions for Agentforce session tracing extraction.
Authentication Issues
401 Unauthorized
Symptom:
RuntimeError: Token exchange failed: invalid_grant
Causes & Solutions:
| Cause | Solution |
|---|---|
| Expired JWT | Check certificate expiration with openssl x509 -enddate -noout -in cert.crt |
| Wrong consumer key | Verify consumer key matches External Client App |
| Certificate mismatch | Re-upload certificate to Salesforce |
| User not authorized | Assign user to Connected App / Permission Set |
Debug Steps:
# Test JWT generation
python3 -c "
from scripts.auth import DataCloudAuth
auth = DataCloudAuth('myorg', 'CONSUMER_KEY')
print(auth.get_token()[:50])
"
# Verify org connection
sf org display --target-org myorg --json
403 Forbidden
Symptom:
RuntimeError: Access denied: Ensure ECA has cdp_query_api scope
Solutions:
Add Required Scopes to External Client App:
cdp_query_apicdp_profile_api
Assign Data 360 Permissions to user:
- Setup → Permission Sets → Data 360 permissions
Enable Data 360 in org:
- Setup → Data 360 → Enable
Data Issues
No Session Data Found
Symptom:
Extracted 0 sessions
Causes & Solutions:
| Cause | Solution |
|---|---|
| Session tracing not enabled | Setup → Agentforce → Enable Session Tracing |
| Wrong date range | Data typically lags 5-15 minutes |
| Wrong agent name | Check exact API name with sf org list metadata --metadata-type Bot --target-org <alias> |
| Sandbox without data | Session tracing may not be enabled in sandbox |
Debug:
# Check if DMO exists and has data
from scripts.datacloud_client import Data360Client
client = Data360Client(auth)
count = client.count("ssot__AIAgentSession__dlm")
print(f"Total sessions in Data 360: {count}")
Query Timeout
Symptom:
RuntimeError: Request timed out after 3 retries
Solutions:
Add date filters to reduce data volume:
extractor.extract_sessions( since=datetime.now() - timedelta(days=1), # Shorter range )Use incremental extraction:
python3 scripts/cli.py extract-incremental --org prodIncrease timeout:
client = DataCloudClient(auth, timeout=300.0) # 5 minutes
Memory Error
Symptom:
MemoryError: Unable to allocate array
Solutions:
Use lazy evaluation:
# Good sessions = pl.scan_parquet(path) result = sessions.filter(...).collect() # Bad sessions = pl.read_parquet(path) # Loads everythingStream to Parquet instead of loading:
client.query_to_parquet(sql, output_path) # Streams, doesn't load allProcess in batches:
for i in range(0, total_sessions, 1000): batch_ids = session_ids[i:i+1000] # Process batch
Extraction Issues
Missing Child Records
Symptom:
Sessions: 1000
Interactions: 0
Steps: 0
Cause: Session IDs not matching in child queries.
Solution:
# Verify session IDs are valid
sessions_df = pl.read_parquet(data_dir / "sessions" / "data.parquet")
print(sessions_df.head()) # Check ssot__Id__c values
# Check if interactions exist for these sessions
interaction_query = f"""
SELECT COUNT(*) FROM ssot__AIAgentInteraction__dlm
WHERE ssot__AiAgentSessionId__c IN ('{session_ids[0]}')
"""
Parquet Write Failure
Symptom:
ArrowInvalid: Could not convert X with type Y
Solutions:
Check for nested/complex types:
# Complex types are serialized to JSON strings if isinstance(value, (dict, list)): value = json.dumps(value)Use explicit schema:
from scripts.models import SCHEMAS client.query_to_parquet(sql, path, schema=SCHEMAS["sessions"])
Analysis Issues
Polars Import Error
Symptom:
ImportError: No module named 'polars'
Solution:
pip install polars pyarrow
Empty DataFrame
Symptom:
analyzer.session_summary() # Returns empty DataFrame
Debug:
# Check if files exist
from pathlib import Path
data_dir = Path("./stdm_data")
print(list(data_dir.glob("**/*.parquet")))
# Check if files have data
import pyarrow.parquet as pq
pf = pq.ParquetFile(data_dir / "sessions" / "data.parquet")
print(f"Rows: {pf.metadata.num_rows}")
Column Not Found
Symptom:
SchemaError: column 'ssot__Id__c' not found
Cause: Parquet file has different column names.
Debug:
# Check actual column names
import pyarrow.parquet as pq
pf = pq.ParquetFile("path/to/file.parquet")
print(pf.schema_arrow)
CLI Issues
Command Not Found
Symptom:
bash: stdm-extract: command not found
Solution:
# Run directly
python3 scripts/cli.py extract --help
# Or install as package (if setup.py exists)
pip install -e .
Environment Variable Not Set
Symptom:
ValueError: Consumer key not found. Set SF_CONSUMER_KEY
Solutions:
Set environment variable:
export SF_CONSUMER_KEY="3MVG9..."Pass via command line:
python3 scripts/cli.py extract --org prod --consumer-key "3MVG9..."Create
.envfile (if using python-dotenv):SF_CONSUMER_KEY=3MVG9...
Data 360 Specific Issues
DMO Not Found
Symptom:
Error: Object ssot__AIAgentSession__dlm not found
Causes:
- Session tracing not enabled - Enable in Agentforce settings
- Wrong API version - Use v66.0 or higher
- Permission issue - User needs Data 360 access
Query Syntax Error
Symptom:
Error: Unexpected token at position X
Common fixes:
| Issue | Fix |
|---|---|
| Single quotes in values | Escape: 'O''Brien' |
| Reserved words | Use backticks: `Order` |
| Date format | Use ISO: '2026-01-28T00:00:00.000Z' |
Lessons Learned (Live Deployment - Jan 2026)
Critical discoveries from live testing against a sandbox org.
API Version: v66.0 Recommended
Problem: Documentation referenced v60.0, but Data 360 Query SQL API requires v64.0+. We recommend v66.0 (Spring '26).
Fix:
# Wrong (v60.0)
url = f"{instance_url}/services/data/v60.0/ssot/querybuilder/execute"
# Correct (v66.0)
url = f"{instance_url}/services/data/v66.0/ssot/query-sql"
Field Naming: AiAgent (lowercase 'i')
Problem: Documentation shows AIAgent but actual schema uses AiAgent.
Wrong:
SELECT ssot__AIAgentSessionId__c FROM ssot__AIAgentInteraction__dlm
Correct:
SELECT ssot__AiAgentSessionId__c FROM ssot__AIAgentInteraction__dlm
Affected fields: All FK references in Interaction, Step, and Moment DMOs.
AIAgentMoment Links to Sessions, Not Interactions
Problem: Documentation implied Moments link to Interactions via AIAgentInteractionId__c.
Reality: AIAgentMoment links directly to Sessions via ssot__AiAgentSessionId__c.
Correct Schema:
AIAgentSession → AIAgentInteraction → AIAgentInteractionStep
↓
AIAgentMoment (links to session, not interaction)
Response Format: Array of Arrays
Problem: Expected array of objects, but v64.0+ returns array of arrays.
v65.0 Response:
{
"metadata": [{"name": "ssot__Id__c"}, {"name": "ssot__Name__c"}],
"data": [
["019abc...", "Session 1"],
["019def...", "Session 2"]
]
}
Fix: Convert using metadata column names:
column_names = [col["name"] for col in metadata]
records = [dict(zip(column_names, row)) for row in data]
External Client App Setup URL
Problem: Documentation had wrong Setup URL.
Wrong: /lightning/setup/ExternalClientAppManager/home
Correct: /lightning/setup/ManageExternalClientApplication/home
Incremental Extraction Overwrites Data
Problem: extract-incremental was overwriting Parquet files instead of appending.
Symptoms:
- Running incremental after full extract → lost all historical data
- Session count dropped from 447 to 17
Fix: Added append + dedupe_key parameters to query_to_parquet():
# Now correctly reads existing, appends new, dedupes by ID
result = client.query_to_parquet(
sql, output_path,
append=True,
dedupe_key="ssot__Id__c"
)
Session End Types All NOT_SET
Observation: 100% of sessions had ssot__AiAgentSessionEndType__c = 'NOT_SET'.
Possible causes:
- Sessions not explicitly closed
- Agent Builder sessions don't track end types
- Potential data quality issue in source org
Recommendation: Investigate session closure patterns in agent configuration.
Getting Help
Debug Mode
# Enable verbose logging
python3 scripts/cli.py extract --org prod --verbose 2>&1 | tee debug.log
Check Data 360 Status
# List available DMOs
python3 -c "
from scripts.auth import Data360Auth
from scripts.datacloud_client import Data360Client
auth = Data360Auth('prod', 'KEY')
client = Data360Client(auth)
dmos = client.list_dmos()
for dmo in dmos:
print(dmo.get('name'))
"
Report Issues
If you encounter issues not covered here:
- Enable verbose mode and capture logs
- Note the error message and stack trace
- Check Data 360 health status
- Contact Salesforce support for API issues
More in this playbook
Sf ai agentforce
Agentforce Builder metadata path for Builder-managed topics/actions, Prompt Builder templates, GenAiFunction/GenAiPlugin, Models API, and custom Lightning types. TRIGGER when: user maintains or configures Builder metadata agents, creates topics/actions, works with Prompt Builder templates, or touches .genAiFunction, .genAiPlugin, or .genAiPromptTemplate metadata XML files. DO NOT TRIGGER when: Agent Script DSL .agent files (use sf-ai-agentscript), agent testing (use sf-ai-agentforce-testing), or persona design (use sf-ai-agentforce-persona).
Agentic workflowsMITSf ai agentforce grid
Use this skill whenever users want to build, inspect, debug, automate, or publish workflows in Agentforce Grid (AI Workbench) using Salesforce plus the Grid MCP or direct Grid REST calls. Trigger it for Grid workbook creation, worksheet setup, Object/Reference/AI/Agent/AgentTest/Evaluation/PromptTemplate/InvocableAction column design, prompt drafting inside Grid, worksheet execution troubleshooting, Grid YAML `apply_grid` specs, and Windows-specific Grid setup issues. Also use it when users mention AI Workbench, Grid Studio, workbook IDs, worksheet IDs, Grid Connect, or ask for recipes like "top opportunities with AI email drafts", "agent test suite in Grid", or "build this worksheet from YAML". Do not use it for generic Salesforce work unrelated to Agentforce Grid.
Agentic workflowsMITSf ai agentforce testing
Agentforce agent testing with dual-track workflow and 100-point scoring. TRIGGER when: user tests Agentforce agents, runs sf agent test commands, creates test specs, validates topic routing, or analyzes agent test coverage. DO NOT TRIGGER when: Apex unit tests (use sf-testing), building agents (use sf-ai-agentforce), or Agent Script DSL (use sf-ai-agentscript).
