Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion skills/skills/langbot-mcp-ops/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ execution, not the individual model/tool call outcome. Calls without a recorded
execution link are excluded when an execution filter is active.

Session lists support `bot_ids`, `pipeline_ids`, `start_time`, `end_time`,
`user_query`, `is_active`, and pagination. For execution status or real/debug
`user_query`, `launcher_id`, `is_active`, and pagination. For execution status or real/debug
filters, use `get_monitoring_executions`; HTTP `/monitoring/sessions` rejects
them. In HTTP `/monitoring/data`, `sessions` and `totalCount.sessions` use only
bot/pipeline/time filters; execution filters apply to the other records.
Expand Down
3 changes: 3 additions & 0 deletions src/langbot/pkg/api/http/controller/groups/monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ async def get_sessions(request_context: RequestContext) -> str:
start_time_str = quart.request.args.get('startTime')
end_time_str = quart.request.args.get('endTime')
user_query = quart.request.args.get('userQuery')
launcher_id = quart.request.args.get('launcherId') or quart.request.args.get('groupId')
is_active_str = quart.request.args.get('isActive')
limit, offset = self.ap.monitoring_service.normalize_page_window(
quart.request.args.get('limit', 100), quart.request.args.get('offset', 0)
Expand All @@ -375,6 +376,7 @@ async def get_sessions(request_context: RequestContext) -> str:
start_time=start_time,
end_time=end_time,
user_query=user_query,
launcher_id=launcher_id,
is_active=is_active,
limit=limit,
offset=offset,
Expand Down Expand Up @@ -756,6 +758,7 @@ async def export_data(request_context: RequestContext) -> tuple[str, int]:
'is_active',
'platform',
'user_id',
'user_name',
]
elif export_type == 'feedback':
data = await self.ap.monitoring_service.export_feedback(
Expand Down
39 changes: 39 additions & 0 deletions src/langbot/pkg/api/http/service/monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -2348,6 +2348,42 @@ async def reset_session_context(self, context: TenantContext, bot_id: str, sessi
raise LookupError('Session not found')
# Legacy sessions use uppercase PERSON/GROUP; envelope IDs use lowercase.
conversation = re.sub(r'^(PERSON|GROUP)_', lambda match: match[1].lower() + '_', session_id)
if conversation.startswith('group_') and '#' not in conversation:
session_model = persistence_monitoring.MonitoringSession
user_id = (
await execute(
sqlalchemy.select(session_model.user_id)
.where(
session_model.workspace_uuid == workspace,
session_model.bot_id == bot_id,
session_model.session_id == session_id,
session_model.user_id.is_not(None),
session_model.user_id != '',
)
.limit(1)
)
).scalar_one_or_none()
if not user_id:
msg_model = persistence_monitoring.MonitoringMessage
user_id = (
await execute(
sqlalchemy.select(msg_model.user_id)
.where(
msg_model.workspace_uuid == workspace,
msg_model.bot_id == bot_id,
msg_model.session_id == session_id,
sqlalchemy.func.coalesce(msg_model.role, 'user') != 'assistant',
msg_model.user_id.is_not(None),
msg_model.user_id != '',
)
.order_by(msg_model.timestamp.desc())
.limit(1)
)
).scalar_one_or_none()
if user_id and conversation.endswith(f'_{user_id}'):
stripped = conversation[: -(len(str(user_id)) + 1)]
if stripped != 'group':
conversation = stripped
run = persistence_agent_run.AgentRun
busy = (
await execute(
Expand Down Expand Up @@ -2403,6 +2439,7 @@ async def get_sessions(
start_time: datetime.datetime | None = None,
end_time: datetime.datetime | None = None,
user_query: str | None = None,
launcher_id: str | None = None,
is_active: bool | None = None,
limit: int = 100,
offset: int = 0,
Expand All @@ -2418,6 +2455,7 @@ async def get_sessions(
start_time=start_time,
end_time=end_time,
user_query=user_query,
launcher_id=launcher_id,
is_active=is_active,
),
limit,
Expand Down Expand Up @@ -3185,6 +3223,7 @@ async def export_sessions(
'is_active': str(row[0].is_active if isinstance(row, tuple) else row.is_active),
'platform': row[0].platform if isinstance(row, tuple) else row.platform,
'user_id': row[0].user_id if isinstance(row, tuple) else row.user_id,
'user_name': row[0].user_name if isinstance(row, tuple) else row.user_name,
}
for row in rows
]
Expand Down
14 changes: 13 additions & 1 deletion src/langbot/pkg/api/http/service/monitoring_execution_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,18 @@ def _conversation_message_queries(self, workspace, bot_ids):
),
),
)
monitoring_session = sa.case(
(
sa.and_(
conversation.like('group\\_%', escape='\\'),
~conversation.like('%#%', escape='\\'),
EventLog.actor_id.is_not(None),
EventLog.actor_id != '',
),
conversation + sa.literal('_') + EventLog.actor_id,
),
else_=conversation,
)
values = {
'id': EventLog.event_id,
'workspace_uuid': EventLog.workspace_id,
Expand All @@ -152,7 +164,7 @@ def _conversation_message_queries(self, workspace, bot_ids):
self._execution_json_text(EventLog.metadata_json, ('routes', 0, 'target_type')), ''
),
'message_content': sa.func.coalesce(EventLog.input_json, EventLog.input_summary, ''),
'session_id': conversation,
'session_id': monitoring_session,
'status': sa.func.coalesce(self._execution_json_text(EventLog.metadata_json, 'status'), 'success'),
'level': sa.literal('info'),
'platform': self._execution_json_text(EventLog.metadata_json, 'platform'),
Expand Down
4 changes: 2 additions & 2 deletions src/langbot/pkg/api/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ async def get_sandbox_diagnostics(kind: typing.Literal['status', 'sessions', 'er
return _dump(ap.box_service.get_recent_errors(context))

@mcp.tool(
description='Read bounded Workspace runtime records. Message image URLs may be renewed through the connected OneBot peer without downloading images or rewriting stored records; URLs remain temporary. LLM calls include optional details (timing in ms, complete provider usage, structured error); older records have null details. Filters follow the monitoring service: bot_ids, pipeline_ids, session_ids, start_time, end_time, mode (all/real/debug), execution_statuses (owning execution status groups), knowledge_base_id, user_query, is_active as supported by the record kind. Sessions read stored conversation summaries and do not support mode or execution_statuses.'
description='Read bounded Workspace runtime records. Message image URLs may be renewed through the connected OneBot peer without downloading images or rewriting stored records; URLs remain temporary. LLM calls include optional details (timing in ms, complete provider usage, structured error); older records have null details. Filters follow the monitoring service: bot_ids, pipeline_ids, session_ids, start_time, end_time, mode (all/real/debug), execution_statuses (owning execution status groups), knowledge_base_id, user_query, launcher_id, is_active as supported by the record kind. Sessions read stored conversation summaries and do not support mode or execution_statuses.'
)
async def get_monitoring_records(
kind: typing.Literal['messages', 'llm_calls', 'tool_calls', 'embedding_calls', 'sessions', 'errors'],
Expand All @@ -245,7 +245,7 @@ async def get_monitoring_records(
allowed.add('knowledge_base_id')
if kind == 'sessions':
allowed -= {'mode', 'execution_statuses'}
allowed |= {'user_query', 'is_active'}
allowed |= {'user_query', 'launcher_id', 'is_active'}
kwargs = dict(filters or {})
if set(kwargs) - allowed:
raise ValueError('Unsupported monitoring filter')
Expand Down
29 changes: 29 additions & 0 deletions src/langbot/pkg/persistence/session_summary_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class SessionListFilter:
start_time: datetime.datetime | None = None
end_time: datetime.datetime | None = None
user_query: str | None = None
launcher_id: str | None = None
is_active: bool | None = None


Expand Down Expand Up @@ -43,3 +44,31 @@ class SessionSummaryChange:
def message_source_key(message_id: str) -> str:
"""Distinct message records remain distinct even when they share an event."""
return f'message:{message_id}'


def build_monitoring_session_id(
launcher_type: object,
launcher_id: object,
sender_id: object = None,
) -> str:
"""Build the canonical monitoring session ID without altering conversation keys."""
launcher_type_value = launcher_type.value if hasattr(launcher_type, 'value') else str(launcher_type)
if launcher_type_value == 'group' and sender_id is not None:
sender_text = str(sender_id).strip()
if sender_text:
return f'group_{launcher_id}_{sender_text}'
return f'{launcher_type_value}_{launcher_id}'


def monitoring_session_id_from_conversation(
conversation_id: str | None,
actor_id: object = None,
) -> str:
"""Map a conversation key and optional actor ID to the monitoring session ID."""
if not conversation_id:
return ''
if conversation_id.startswith('group_') and '#' not in conversation_id:
launcher_id = conversation_id.removeprefix('group_')
if launcher_id:
return build_monitoring_session_id('group', launcher_id, actor_id)
return conversation_id
25 changes: 25 additions & 0 deletions src/langbot/pkg/persistence/session_summary_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,31 @@ async def list_page(
if filters.user_query and filters.user_query.strip():
pattern = f'%{filters.user_query.strip()}%'
conditions.append(sa.or_(model.user_id.ilike(pattern), model.user_name.ilike(pattern)))
if filters.launcher_id and filters.launcher_id.strip():
raw_launcher = filters.launcher_id.strip()
normalized = raw_launcher
for prefix in ('group_', 'GROUP_', 'person_', 'PERSON_'):
if raw_launcher.startswith(prefix) and len(raw_launcher) > len(prefix):
normalized = raw_launcher[len(prefix) :]
break
escaped = normalized.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
conditions.append(
sa.or_(
model.session_id.in_(
(
raw_launcher,
f'group_{normalized}',
f'GROUP_{normalized}',
f'person_{normalized}',
f'PERSON_{normalized}',
)
),
model.session_id.like(f'group_{escaped}\\_%', escape='\\'),
model.session_id.like(f'GROUP_{escaped}\\_%', escape='\\'),
model.session_id.like(f'group_{escaped}#%', escape='\\'),
model.session_id.like(f'GROUP_{escaped}#%', escape='\\'),
)
)
if filters.is_active is not None:
conditions.append(model.is_active == filters.is_active)
async with self._session_scope(workspace) as session:
Expand Down
25 changes: 20 additions & 5 deletions src/langbot/pkg/persistence/session_summary_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@

from ..entity.persistence.monitoring import MonitoringSession, MonitoringSessionReceipt
from .datetime_utils import as_naive_utc
from .session_summary_contract import SessionSummaryChange, message_source_key
from .session_summary_contract import (
SessionSummaryChange,
message_source_key,
monitoring_session_id_from_conversation,
)


SESSION_KEY = ['workspace_uuid', 'bot_id', 'session_id']
Expand Down Expand Up @@ -47,7 +51,7 @@ def ingress_summary_change(workspace: str, row) -> SessionSummaryChange:
return SessionSummaryChange(
workspace=workspace,
bot_id=row['bot_id'],
session_id=row['conversation_id'] or '',
session_id=monitoring_session_id_from_conversation(row['conversation_id'], row['actor_id']),
source_key=f'event:{row["event_id"]}',
timestamp=row['event_time'] or row['created_at'],
bot_name=metadata.get('bot_name') or '',
Expand Down Expand Up @@ -265,9 +269,20 @@ async def apply_once(self, session: AsyncSession, change: SessionSummaryChange,
)
if state['covered']:
return False
if state['session_id'] is not None and state['session_id'] != identity:
raise ValueError('An ingress event cannot belong to two conversations')
claimed = state['session_id'] is None
previous_owner = state['session_id']
if previous_owner is not None and previous_owner != identity:
if (
previous_owner.startswith('group_')
and '#' not in previous_owner
and change.user_id not in (None, '')
and identity == f'{previous_owner}_{change.user_id}'
):
deltas[previous_owner] = deltas.get(previous_owner, 0) - 1
claimed = True
else:
raise ValueError('An ingress event cannot belong to two conversations')
else:
claimed = previous_owner is None
elif change.role != 'assistant':
# Legacy message.id matching is part of the historical detail contract.
for event_id in sorted({change.source_key.removeprefix('message:'), change.event_id} - {None}):
Expand Down
Loading
Loading