Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
76 commits
Select commit Hold shift + click to select a range
94c70db
fix(heartbeat): pause, resume and terminate record the verified princ…
mrveiss Nov 8, 2026
537bc8b
fix(heartbeat): regenerate api types (#21136)
mrveiss Nov 8, 2026
63dec16
chore(types): regenerate api.ts for HeartbeatConfigResponse.paused_by…
mrveiss Nov 8, 2026
5dd5967
fix(heartbeat): record control audit durably after commit; show actor…
mrveiss Nov 8, 2026
27938ad
fix(heartbeat): write the control audit record before the change and …
mrveiss Nov 8, 2026
adf4fdb
Merge remote-tracking branch 'origin/main' into issue-21136
mrveiss Nov 8, 2026
92d8df0
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
d1585e2
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
72c14ec
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
6533400
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
157d7e6
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
43a46a4
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
5993df8
fix(dashboard): agent feeds are measured or not reported (#21270)
mrveiss Nov 9, 2026
dd91a53
Merge remote-tracking branch 'origin/main' into issue-21270
mrveiss Nov 9, 2026
43a0797
fix(dashboard): agent feeds are measured or not reported (#21270)
mrveiss Nov 9, 2026
c0b1548
fix(dashboard): one strict history reader, batched feeds, per-record …
mrveiss Nov 9, 2026
d394869
Merge remote-tracking branch 'origin/main' into issue-21270
mrveiss Nov 9, 2026
c27effe
chore(types): regenerate api.ts for activityWindowStart (#21270)
mrveiss Nov 9, 2026
383a540
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
5304bf7
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
059f72c
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
5e13fd7
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
f3020c4
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 10, 2026
552974d
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 10, 2026
faacb2f
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 10, 2026
7a975b1
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 10, 2026
7c29018
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 10, 2026
3d7d791
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 10, 2026
0ed3694
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 10, 2026
e31038c
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 10, 2026
6681ba0
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 11, 2026
bfc48e9
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 11, 2026
34ec926
Merge main into issue-21036-fleet-skip-unenrolled (auto-sync) [skip ci]
github-actions[bot] Nov 11, 2026
9a88736
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 11, 2026
6b7f0bf
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 11, 2026
fc8c368
Merge main into issue-21036-fleet-skip-unenrolled (auto-sync) [skip ci]
github-actions[bot] Nov 11, 2026
b038d2f
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 11, 2026
fa1e86f
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 11, 2026
793e553
Merge main into issue-21036-fleet-skip-unenrolled (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
287f4f4
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
649a80c
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
cfd0f30
Merge main into issue-21036-fleet-skip-unenrolled (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
5ddc0a4
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
bc717a0
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
5dde3a6
Merge main into issue-21036-fleet-skip-unenrolled (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
46de677
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
d80b4a9
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
6f4bdb5
revert: restore #21094 after its in-train revert in #21335 (#21036)
mrveiss Nov 12, 2026
ac23381
test(agent-activity): cover the timeline not-reported branch (#21270)
mrveiss Nov 12, 2026
3321184
fix(heartbeat): one accurate paused_by_name description and a route-l…
mrveiss Nov 12, 2026
fea7b5d
refactor(agent-activity): import TaskStatus from autobot_shared (#21270)
mrveiss Nov 12, 2026
70a8e8f
test(agent-activity): drive the real fallback route through the feed …
mrveiss Nov 12, 2026
9eee214
fix(slm): tests resolve the SLM self node and external URL instead of…
mrveiss Nov 12, 2026
ff6b6a1
test(slm): cover the no-self-node branch and duplicate-address self n…
mrveiss Nov 12, 2026
d241a57
fix(slm): one deterministic SLM self-node lookup for update-all and s…
mrveiss Nov 12, 2026
11b2e0d
test(company-os): route-level actor and unauthenticated tests for the…
mrveiss Nov 12, 2026
9370285
Merge main into issue-21036-fleet-skip-unenrolled (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
4aa81f1
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
1ed7346
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
1e78b76
Merge #21277 @ 70a8e8f2cf into the merge train
mrveiss Nov 12, 2026
875e57b
Merge main into the merge train
mrveiss Nov 12, 2026
b9e5c83
Merge main into issue-21036-fleet-skip-unenrolled (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
9c3cf77
Merge main into issue-21136 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
3e17c49
Merge #21094 @ d241a5770e into the merge train
mrveiss Nov 12, 2026
8ae4b3d
Merge #21148 @ 11b2e0df80 into the merge train
mrveiss Nov 12, 2026
67d8cf2
test(agents): pin the feed tests to a fixed clock and make the null-t…
mrveiss Nov 12, 2026
523ece9
fix(agents): skip feed records with overflowing or non-finite duratio…
mrveiss Nov 12, 2026
fefbdba
Merge #21094 @ b9e5c83b20 into the merge train
mrveiss Nov 12, 2026
1863d01
Merge #21148 @ 9c3cf775af into the merge train
mrveiss Nov 12, 2026
aa0300e
Merge main into issue-21270
mrveiss Nov 12, 2026
3929d36
fix(agents): validate duration via the helper, clamp negatives, summa…
mrveiss Nov 12, 2026
b03acca
Merge #21277 @ 3929d362a1 into the merge train
mrveiss Nov 12, 2026
7c2c871
Merge main into the merge train
mrveiss Nov 12, 2026
9e553f9
Merge train #21382 (T117) into the merge train
mrveiss Nov 12, 2026
0ec796b
Merge main into issue-21270 (auto-sync) [skip ci]
github-actions[bot] Nov 12, 2026
3788d11
Merge #21277 @ 0ec796bd7c into the merge train
mrveiss Nov 12, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions autobot-backend/api/agent_org.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
from autobot_shared.error_boundaries import ErrorCategory, with_error_handling
from autobot_shared.logging_manager import get_logger
from llc.services.agent_hire_service import HireApprovalRequiredError
from services.agent_activity_feed import get_agent_feeds, with_feed
from services.agent_org_service import AgentOrgService
from services.delegation_service import DelegationService
from user_management.services import TenantContext
Expand Down Expand Up @@ -86,8 +87,6 @@ def _fallback_agents_from_registry() -> List[Dict[str, Any]]:
"status": profile.availability_status,
# #17514: the registry counts no tasks, so its success_rate is a starting
# default until tasks run; activity fields are not reported (None).
"recentTasks": [],
"activityTimeline": [],
}
)
return agents
Expand Down Expand Up @@ -150,7 +149,9 @@ async def get_agents_status(
# The in-memory registry holds platform agents only (no company), which every
# signed-in caller may see (#19246), so this fallback needs no tenant filter.
logger.debug("PG unavailable — returning in-memory agents for /agents/status (#10511)")
agents = _fallback_agents_from_registry()
fallback = _fallback_agents_from_registry()
feeds = await get_agent_feeds([a["id"] for a in fallback]) # #21270: same feed as the PG path
agents = [with_feed(a, feeds[a["id"]]) for a in fallback]

items = [AgentStatusItem(**a) for a in agents]
return AgentStatusListResponse(agents=items, total=len(items))
Expand Down
215 changes: 109 additions & 106 deletions autobot-backend/api/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,24 @@
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from api.schemas_system import (
from api.heartbeat_responses import (
_run_to_response,
_state_to_response,
_wakeup_to_response,
)
from api.schemas_heartbeat import (
AgentErrorRequest,
AgentPauseRequest,
AgentRecoverRequest,
AgentResumeRequest,
AgentTerminateRequest,
HeartbeatConfigRequest,
HeartbeatConfigResponse,
)
from api.schemas_system import (
HeartbeatRunResponse,
HeartbeatTriggerResponse,
HeartbeatWakeupQueuedResponse,
RunEventResponse,
WakeupRequestCreate,
WakeupRequestResponse,
)
Expand All @@ -38,15 +44,18 @@
from autobot_shared.auth.permissions import is_admin_role
from autobot_shared.error_boundaries import ErrorCategory, with_error_handling
from autobot_shared.logging_manager import get_logger
from autobot_shared.principal import resolve_principal_id
from autobot_shared.time_utils import now_utc
from llc.services.member_standing import display_name_of
from models.heartbeat import (
AgentRuntimeState,
AgentWakeupRequest,
HeartbeatRun,
HeartbeatRunEvent,
HeartbeatStatus,
WakeupTrigger,
)
from services.audit.audit import record_committed
from services.audit.taxonomy import AuditAction, AuditCategory, AuditEvent, action_name
from services.heartbeat_scheduler import HeartbeatScheduler, _get_or_create_state

logger = get_logger(__name__)
Expand Down Expand Up @@ -85,7 +94,7 @@ async def get_heartbeat_config(
"""Return heartbeat config and runtime state for an agent (#1407)."""
state = await _get_or_create_state(session, agent_id)
await session.commit()
return _state_to_response(state)
return await _state_response(session, state)


@router.put("/{agent_id}/config", response_model=HeartbeatConfigResponse)
Expand Down Expand Up @@ -120,7 +129,7 @@ async def update_config(
await scheduler.disable_agent(agent_id)
elif body.heartbeat_enabled and was_enabled:
await scheduler.enable_agent(agent_id, body.heartbeat_interval_seconds)
return _state_to_response(state)
return await _state_response(session, state)


@router.patch("/{agent_id}/session", response_model=HeartbeatConfigResponse)
Expand All @@ -145,7 +154,7 @@ async def update_session(
state.extra = body["extra"]
await session.commit()
await session.refresh(state)
return _state_to_response(state)
return await _state_response(session, state)


@router.get("/{agent_id}/runs", response_model=List[HeartbeatRunResponse])
Expand Down Expand Up @@ -262,6 +271,33 @@ async def trigger_manual(
return {"agent_id": agent_id, "status": "triggered"}


def _actor_id(user: Any) -> str:
"""The verified caller's principal id, from the auth dependency only (#21136)."""
claims = user if isinstance(user, dict) else vars(user)
return resolve_principal_id(claims) or str(claims.get("username") or "unknown")


async def _audit_control(actor: str, action: AuditAction, agent_id: str, reason: str | None = None) -> None:
"""Durably record who paused, resumed or terminated an agent BEFORE the change (#21136, #20557).

Resume clears the row, so this event is the only record of the resumer: it is the awaited,
bounded ``record_committed`` write, not the fire-and-forget bus. As on the secrets routes
(``api/secrets_audit.py``), a write that fails (returns False) raises 503 and nothing is changed.
"""
recorded = await record_committed(
AuditEvent(
category=AuditCategory.SECURITY,
action=action_name(action),
actor_id=actor,
resource_type="agent_heartbeat",
resource_id=agent_id,
metadata={"reason": reason} if reason else None,
)
)
if not recorded:
raise HTTPException(status_code=503, detail="Audit trail unavailable; nothing was changed")


@router.post("/{agent_id}/pause", response_model=HeartbeatConfigResponse)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
Expand All @@ -284,16 +320,19 @@ async def pause_agent(
if state.status == HeartbeatStatus.TERMINATED.value:
raise HTTPException(status_code=409, detail="Agent is terminated; cannot pause")
if state.status == HeartbeatStatus.PAUSED.value:
return _state_to_response(state)
return await _state_response(session, state)
# The verified caller is the only actor; body.paused_by is never trusted (#21136).
actor = _actor_id(_user)
await _audit_control(actor, AuditAction.AGENT_PAUSE, agent_id, body.reason)
state.status = HeartbeatStatus.PAUSED.value
state.paused_reason = body.reason
state.paused_at = now_utc()
state.paused_by = body.paused_by or "user"
state.paused_by = actor
await session.commit()
await session.refresh(state)
await scheduler.disable_agent(agent_id)
logger.info("Agent %s paused by %s: %s", agent_id, state.paused_by, state.paused_reason)
return _state_to_response(state)
return await _state_response(session, state)


async def _request_skill_approval_for_resume(agent_id: str, paused_by: str, requested_by: str) -> str:
Expand All @@ -315,6 +354,37 @@ async def _request_skill_approval_for_resume(agent_id: str, paused_by: str, requ
return result.approval_id or ""


def _require_resumable(state: AgentRuntimeState) -> None:
"""Raise 409 unless the agent is PAUSED."""
if state.status == HeartbeatStatus.TERMINATED.value:
raise HTTPException(status_code=409, detail="Agent is terminated; cannot resume")
if state.status != HeartbeatStatus.PAUSED.value:
raise HTTPException(status_code=409, detail=f"Agent is not paused (status={state.status})")


async def _queue_system_pause_resume(agent_id: str, paused_by: str, user: Any) -> Any:
"""A 202 response when a non-admin resumes a system-paused agent (GH#8734), else None.

``user`` is a dict with ``role`` and ``username`` keys, or an object with those attributes.
"""
from fastapi.responses import JSONResponse

if not paused_by.startswith("system:"):
return None
claims = user if isinstance(user, dict) else vars(user)
if is_admin_role(claims.get("role", "")):
return None
approval_id = await _request_skill_approval_for_resume(agent_id, paused_by, claims.get("username", ""))
return JSONResponse(
status_code=202,
content={
"approval_id": approval_id,
"status": "pending",
"message": f"Agent was paused by {paused_by}; resume request queued for admin approval",
},
)


@router.post("/{agent_id}/resume", response_model=HeartbeatConfigResponse)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
Expand All @@ -337,38 +407,23 @@ async def resume_agent(
User-paused agents can be resumed by any authenticated user.
DISABLED and TERMINATED agents are not affected — use PUT /config instead.
"""
from fastapi.responses import JSONResponse

state = await _get_or_create_state(session, agent_id)
if state.status == HeartbeatStatus.TERMINATED.value:
raise HTTPException(status_code=409, detail="Agent is terminated; cannot resume")
if state.status != HeartbeatStatus.PAUSED.value:
raise HTTPException(status_code=409, detail=f"Agent is not paused (status={state.status})")
# System-enforced pauses use the SkillApproval governance workflow (GH#8734).
# _user is always a Dict with keys "role" (str) and "username" (str).
paused_by = state.paused_by or ""
if paused_by.startswith("system:"):
username = _user.get("username", "") if isinstance(_user, dict) else getattr(_user, "username", "")
user_role = _user.get("role", "") if isinstance(_user, dict) else getattr(_user, "role", "")
if not is_admin_role(user_role):
approval_id = await _request_skill_approval_for_resume(agent_id, paused_by, username)
return JSONResponse(
status_code=202,
content={
"approval_id": approval_id,
"status": "pending",
"message": (f"Agent was paused by {paused_by}; resume request queued for admin approval"),
},
)
_require_resumable(state)
queued = await _queue_system_pause_resume(agent_id, state.paused_by or "", _user)
if queued is not None:
return queued
# No resumer column on the row (would need a migration); this event names the caller.
resumer = _actor_id(_user)
await _audit_control(resumer, AuditAction.AGENT_RESUME, agent_id)
state.status = HeartbeatStatus.ACTIVE.value
state.paused_reason = None
state.paused_at = None
state.paused_by = None
await session.commit()
await session.refresh(state)
await scheduler.enable_agent(agent_id, state.heartbeat_interval_seconds)
logger.info("Agent %s resumed", agent_id)
return _state_to_response(state)
logger.info("Agent %s resumed by %s", agent_id, resumer)
return await _state_response(session, state)


@router.post("/{agent_id}/terminate", response_model=HeartbeatConfigResponse)
Expand All @@ -391,19 +446,18 @@ async def terminate_agent(
"""
state = await _get_or_create_state(session, agent_id)
if state.status == HeartbeatStatus.TERMINATED.value:
return _state_to_response(state)
return await _state_response(session, state)
actor = _actor_id(_user)
await _audit_control(actor, AuditAction.AGENT_TERMINATE, agent_id, body.reason)
state.status = HeartbeatStatus.TERMINATED.value
state.paused_reason = body.reason
state.paused_at = now_utc()
# _user is always a Dict; "id" key does not exist — use "username" (P1)
state.paused_by = (
_user.get("username", "unknown") if isinstance(_user, dict) else getattr(_user, "username", "unknown")
)
state.paused_by = actor
await session.commit()
await session.refresh(state)
await scheduler.disable_agent(agent_id)
logger.info("Agent %s terminated: %s", agent_id, body.reason)
return _state_to_response(state)
return await _state_response(session, state)


@router.post("/{agent_id}/error", response_model=HeartbeatConfigResponse)
Expand All @@ -429,7 +483,7 @@ async def set_agent_error(
if state.status == HeartbeatStatus.TERMINATED.value:
raise HTTPException(status_code=409, detail="Agent is terminated; cannot set error state")
if state.status == HeartbeatStatus.ERROR.value:
return _state_to_response(state)
return await _state_response(session, state)
state.status = HeartbeatStatus.ERROR.value
state.error_detail = body.error_detail
state.error_at = now_utc()
Expand All @@ -438,7 +492,7 @@ async def set_agent_error(
await session.refresh(state)
await scheduler.disable_agent(agent_id)
logger.info("Agent %s entered error state: code=%s detail=%s", agent_id, state.error_code, state.error_detail)
return _state_to_response(state)
return await _state_response(session, state)


@router.post("/{agent_id}/recover", response_model=HeartbeatConfigResponse)
Expand Down Expand Up @@ -470,73 +524,22 @@ async def recover_agent(
await session.refresh(state)
await scheduler.enable_agent(agent_id, state.heartbeat_interval_seconds)
logger.info("Agent %s recovered from error state", agent_id)
return _state_to_response(state)


def _state_to_response(state: AgentRuntimeState) -> HeartbeatConfigResponse:
"""Convert AgentRuntimeState ORM row to Pydantic response (#1407, GH#6476, MVA-1411)."""
return HeartbeatConfigResponse(
agent_id=state.agent_id,
heartbeat_enabled=state.heartbeat_enabled,
status=state.status,
paused_reason=state.paused_reason,
paused_at=(state.paused_at.isoformat() if state.paused_at else None),
paused_by=state.paused_by,
error_detail=state.error_detail,
error_at=(state.error_at.isoformat() if state.error_at else None),
error_code=state.error_code,
heartbeat_interval_seconds=state.heartbeat_interval_seconds,
max_run_duration_seconds=state.max_run_duration_seconds,
current_task_id=state.current_task_id,
last_heartbeat_at=(state.last_heartbeat_at.isoformat() if state.last_heartbeat_at else None),
session_params=state.session_params,
extra=state.extra,
created_at=(state.created_at.isoformat() if state.created_at else None),
updated_at=(state.updated_at.isoformat() if state.updated_at else None),
)
return await _state_response(session, state)


def _run_to_response(run: HeartbeatRun) -> HeartbeatRunResponse:
"""Convert HeartbeatRun ORM row to Pydantic response (#1407)."""
return HeartbeatRunResponse(
id=str(run.id),
agent_id=run.agent_id,
status=run.status,
trigger=run.trigger,
wakeup_context=run.wakeup_context,
started_at=(run.started_at.isoformat() if run.started_at else None),
finished_at=(run.finished_at.isoformat() if run.finished_at else None),
tokens_used=run.tokens_used,
cost_usd=run.cost_usd,
model=run.model,
provider=run.provider,
error_message=run.error_message,
created_at=(run.created_at.isoformat() if run.created_at else None),
events=[_event_to_response(e) for e in (run.events or [])],
)

async def _paused_by_name(session: AsyncSession, paused_by: str | None) -> str | None:
"""The display name of the user whose principal id is ``paused_by``, or None (#21136).

def _event_to_response(event: HeartbeatRunEvent) -> RunEventResponse:
"""Convert HeartbeatRunEvent ORM row to Pydantic response (#1407)."""
return RunEventResponse(
id=str(event.id),
event_type=event.event_type,
message=event.message,
payload=event.payload,
occurred_at=event.occurred_at,
)
None for no actor, a ``system:*`` actor, a legacy free-text actor, or an unknown user; the
client then shows the system label or the raw value.
"""
try:
user_id = uuid.UUID(paused_by or "")
except ValueError:
return None
return await display_name_of(session, user_id)


def _wakeup_to_response(req: AgentWakeupRequest) -> WakeupRequestResponse:
"""Convert AgentWakeupRequest ORM row to Pydantic response (#1407)."""
return WakeupRequestResponse(
id=str(req.id),
agent_id=req.agent_id,
priority=req.priority,
context=req.context,
reason=req.reason,
consumed=req.consumed_at is not None,
consumed_at=(req.consumed_at.isoformat() if req.consumed_at else None),
created_at=(req.created_at.isoformat() if req.created_at else None),
merged_count=req.merged_count if req.merged_count is not None else 0,
)
async def _state_response(session: AsyncSession, state: AgentRuntimeState) -> HeartbeatConfigResponse:
"""The response for ``state`` with the actor's display name resolved from the user record (#21136)."""
return _state_to_response(state, await _paused_by_name(session, state.paused_by))
Loading
Loading