Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
e9a2d53
1
Parent(s): b7980f7
backend stabilization
Browse filesFiles changed (18)
- agents/nexus_checkpoint.py+21-1
- agents/nexus_customer.py+2-2
- agents/nexus_master.py+3-2
- agents/tools/nexus_tools.py+12-2
- alembic/versions/1536118577ca_add_nexus_checkpoint_writes.pyAdded+40
- api/v1/dashboard.py+10-7
- api/v1/tickets.py+6-2
- core/observability.py+12-3
- core/tasks.py+2-2
- frontend/apps/customer/src/App.tsx-1
- frontend/apps/customer/src/components/Dashboard.tsx+3-2
- frontend/apps/customer/src/components/ThreadView.tsx+1-1
- frontend/apps/customer/src/components/TicketList.tsx+2-3
- frontend/packages/shared/src/contexts/AuthContext.tsx+13-6
- models/__init__.py+3-1
- models/nexus_checkpoint.py+15-1
- schemas/ticket.py+2
- tmp_get_token.pyAdded+30
10 unmodified lines1112131415161765 unmodified lines83848586878810 unmodified linesfrom langgraph.checkpoint.serde.jsonplus import JsonPlusSerializerfrom sqlalchemy import select, update, insertfrom core.database import async_session_factoryfrom models.nexus_checkpoint import NexusCheckpointclass SQLAlchemySaver(BaseCheckpointSaver):"""65 unmodified linesawait session.commit()return {"configurable": {"thread_id": thread_id, "checkpoint_id": checkpoint_id}}# Sync methods are required by the interface but we'll focus on asyncdef get_tuple(self, config: Dict[str, Any]) -> Optional[CheckpointTuple]:10 unmodified lines1112131415161765 unmodified lines838485868788899091929394959697989910010110210310410510610710810 unmodified linesfrom langgraph.checkpoint.serde.jsonplus import JsonPlusSerializerfrom sqlalchemy import select, update, insertfrom core.database import async_session_factoryfrom models.nexus_checkpoint import NexusCheckpoint, NexusCheckpointWriteclass SQLAlchemySaver(BaseCheckpointSaver):"""65 unmodified linesawait session.commit()return {"configurable": {"thread_id": thread_id, "checkpoint_id": checkpoint_id}}async def aput_writes(self, config: Dict[str, Any], writes: List[tuple[str, Any]], task_id: str) -> None:"""Persists intermediate task writes to support modern LangGraph async cycles."""thread_id = config["configurable"]["thread_id"]checkpoint_id = config["configurable"]["checkpoint_id"]async with async_session_factory() as session:for idx, (channel, value) in enumerate(writes):stmt = insert(NexusCheckpointWrite).values(thread_id=str(thread_id),checkpoint_id=str(checkpoint_id),task_id=str(task_id),idx=idx,channel=channel,value=self.serde.dumps(value))await session.execute(stmt)await session.commit()# Sync methods are required by the interface but we'll focus on asyncdef get_tuple(self, config: Dict[str, Any]) -> Optional[CheckpointTuple]:
110 unmodified lines111112113114115116117118119120121122123124110 unmodified linespriority=params.get("priority", "MEDIUM"))))# NEW: Conversational Ticket Discussion/Updateselif tool_name == "UPDATE_TICKET":task_calls.append((call_id, update_ticket_tool(ticket_id=params.get("ticket_id"),comment=params.get("comment"),workspace_id=ws_id,user_id=state.get("user_id"),status=params.get("status"))))else:110 unmodified lines111112113114115116117118119120121122123124110 unmodified linespriority=params.get("priority", "MEDIUM"))))elif tool_name == "UPDATE_TICKET":task_calls.append((call_id, update_ticket_tool(ticket_id=params.get("ticket_id"),comment=params.get("comment"),workspace_id=ws_id,user_id=state.get("user_id"),status=params.get("status"),role=role)))else:
217 unmodified lines21821922022122222322432 unmodified lines257258259260261262263217 unmodified linesif action["tool"] == "ASSIGN_TICKET":write_tasks.append(assign_ticket_tool(state.get("ticket_id"), state.get("target_user_id"), ws_id))elif action["tool"] == "UPDATE_STATUS":write_tasks.append(update_ticket_status_tool(state.get("ticket_id"), state.get("target_status"), ws_id))elif action["tool"] == "REMEDIATE":rem = action.get("params") or {}write_tasks.append(dynamic_remediation_tool(action["action"], rem, ws_id))32 unmodified linescomment=params.get("comment"),workspace_id=ws_id,user_id=state.get("user_id"),status=params.get("status"))))elif tool_name == "ANALYTICS":task_calls.append((call_id, nexus_analytics_tool(ws_id, role=role)))217 unmodified lines21821922022122222322432 unmodified lines257258259260261262263264217 unmodified linesif action["tool"] == "ASSIGN_TICKET":write_tasks.append(assign_ticket_tool(state.get("ticket_id"), state.get("target_user_id"), ws_id))elif action["tool"] == "UPDATE_STATUS":write_tasks.append(update_ticket_status_tool(state.get("ticket_id"), state.get("target_status"), ws_id, role=state.get("user_role")))elif action["tool"] == "REMEDIATE":rem = action.get("params") or {}write_tasks.append(dynamic_remediation_tool(action["action"], rem, ws_id))32 unmodified linescomment=params.get("comment"),workspace_id=ws_id,user_id=state.get("user_id"),status=params.get("status"),role=role)))elif tool_name == "ANALYTICS":task_calls.append((call_id, nexus_analytics_tool(ws_id, role=role)))
107 unmodified lines10810911011111211311431 unmodified lines146147148149150151359 unmodified lines51151251351451551651717 unmodified lines535536537538539540107 unmodified lineslogger.info(f"Ticket created via AI: {new_ticket.id}")return f"Successfully created ticket: **{new_ticket.title}** (ID: `{new_ticket.id}`). Status is OPEN."async def update_ticket_tool(ticket_id: str, comment: str, workspace_id: UUID, user_id: UUID, status: Optional[str] = None) -> str:"""Update a ticket by adding a comment or changing its status."""31 unmodified lineselif "OPEN" in s_norm: target_status = TicketStatus.OPENelif "ACKNOWLEDGED" in s_norm: target_status = TicketStatus.ACKNOWLEDGEDif target_status:ticket.status = target_status359 unmodified linesawait db.commit()return f"Ticket {ticket_id} successfully assigned to user {user_id}."async def update_ticket_status_tool(ticket_id: UUID, new_status: str, workspace_id: UUID) -> str:"""Update a ticket's status (e.g. to RESOLVED)."""17 unmodified lineselif "IN_PROGRESS" in s_norm: target_status = TicketStatus.IN_PROGRESSelif "ACKNOWLEDGED" in s_norm: target_status = TicketStatus.ACKNOWLEDGEDif not target_status:raise ValueError(f"Unknown status: {new_status}")107 unmodified lines10810911011111211311431 unmodified lines146147148149150151152153154155156359 unmodified lines51651751851952052152217 unmodified lines540541542543544545546547548549550107 unmodified lineslogger.info(f"Ticket created via AI: {new_ticket.id}")return f"Successfully created ticket: **{new_ticket.title}** (ID: `{new_ticket.id}`). Status is OPEN."async def update_ticket_tool(ticket_id: str, comment: str, workspace_id: UUID, user_id: UUID, status: Optional[str] = None, role: str = "customer_user") -> str:"""Update a ticket by adding a comment or changing its status."""31 unmodified lineselif "OPEN" in s_norm: target_status = TicketStatus.OPENelif "ACKNOWLEDGED" in s_norm: target_status = TicketStatus.ACKNOWLEDGED# POLICY ENFORCEMENT: Only staff can RESOLVE or CLOSEis_staff = "3sc" in role.lower()if (target_status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]) and not is_staff:return f"Permission Denied: Only 3SC Support Staff can mark a ticket as {target_status.value.upper()}. Your comment has been added, but the status remains {old_status.value.upper()}."if target_status:ticket.status = target_status359 unmodified linesawait db.commit()return f"Ticket {ticket_id} successfully assigned to user {user_id}."async def update_ticket_status_tool(ticket_id: UUID, new_status: str, workspace_id: UUID, role: str = "customer_user") -> str:"""Update a ticket's status (e.g. to RESOLVED)."""17 unmodified lineselif "IN_PROGRESS" in s_norm: target_status = TicketStatus.IN_PROGRESSelif "ACKNOWLEDGED" in s_norm: target_status = TicketStatus.ACKNOWLEDGED# POLICY ENFORCEMENT: Only staff can RESOLVE or CLOSEis_staff = "3sc" in role.lower()if (target_status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]) and not is_staff:return f"Permission Denied: Only 3SC Support Staff can mark a ticket as {target_status.value.upper()}. Transition refused."if not target_status:raise ValueError(f"Unknown status: {new_status}")
12345678910111213141516171819202122232425262728293031323334353637383940"""add_nexus_checkpoint_writes
Revision ID: 1536118577caRevises: a1f8e2c3d4b5Create Date: 2026-04-05 17:31:48.954591
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = '1536118577ca'down_revision: Union[str, None] = 'a1f8e2c3d4b5'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.create_table('nexus_checkpoint_writes', sa.Column('thread_id', sa.String(), nullable=False), sa.Column('checkpoint_id', sa.String(), nullable=False), sa.Column('task_id', sa.String(), nullable=False), sa.Column('idx', sa.Integer(), nullable=False), sa.Column('channel', sa.String(), nullable=False), sa.Column('value', sa.LargeBinary(), nullable=False), sa.PrimaryKeyConstraint('thread_id', 'checkpoint_id', 'task_id', 'idx') ) op.drop_index('ix_users_email_lower', table_name='users') # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.create_index('ix_users_email_lower', 'users', [sa.text('lower(email::text)')], unique=True) op.drop_table('nexus_checkpoint_writes') # ### end Alembic commands ###65 unmodified lines66676869707110 unmodified lines82838485868731 unmodified lines11912012112212312412512612712812913013113213313413513665 unmodified linesmetrics_stmt = select(func.avg(func.extract('epoch', Ticket.resolved_at - Ticket.created_at) / 3600).label("avg_res"),func.avg(func.cast(Ticket.ai_metadata['rating'].astext, Float)).label("avg_csat"),func.count(Ticket.id).filter((Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED])) &(Ticket.sla_deadline < now)10 unmodified linesavg_res = m_row.avg_res or 0.0avg_csat = m_row.avg_csat or 0.0breach_count = m_row.breached_count or 0# 3. Personalized Open Count31 unmodified lines"total_tickets": total,"by_status": counts,"workspace_id": target_ws,"my_open_count": my_open_count}if is_staff:# Staff get the full forensic payloadresponse.update({"personnel_load": personnel_load,"performance": {"avg_resolution_hours": round(avg_res, 1),"csat_score": round(avg_csat, 1),"sla_breached_count": breach_count}})return response65 unmodified lines6667686970717210 unmodified lines8384858687888931 unmodified lines12112212312412512612712812913013113213313413513613713813965 unmodified linesmetrics_stmt = select(func.avg(func.extract('epoch', Ticket.resolved_at - Ticket.created_at) / 3600).label("avg_res"),func.avg(func.cast(Ticket.ai_metadata['rating'].astext, Float)).label("avg_csat"),func.count(Ticket.id).filter(Ticket.ai_metadata['rating'].isnot(None)).label("rated_count"),func.count(Ticket.id).filter((Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED])) &(Ticket.sla_deadline < now)10 unmodified linesavg_res = m_row.avg_res or 0.0avg_csat = m_row.avg_csat or 0.0rated_count = m_row.rated_count or 0breach_count = m_row.breached_count or 0# 3. Personalized Open Count31 unmodified lines"total_tickets": total,"by_status": counts,"workspace_id": target_ws,"my_open_count": my_open_count,"performance": {"avg_resolution_hours": round(avg_res, 1),"csat_score": round(avg_csat, 1),"rated_count": rated_count,"sla_breached_count": breach_count}}if is_staff:# Staff get the full forensic payloadresponse.update({"personnel_load": personnel_load})return response
110 unmodified lines111112113114115116117314 unmodified lines432433434435436437438110 unmodified linesdup_res = await db.execute(dup_stmt)setattr(ticket, "duplicate_of_title", dup_res.scalar_one_or_none())# 7. Metadata Sanitization & Internal Flag Injectioncreator_role = ticket.creator.role if ticket.creator else Noneis_internal = creator_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]setattr(ticket, "creator_name", ticket.creator.full_name if ticket.creator else "System")314 unmodified linescreator_name=t_obj.creator.full_name if t_obj.creator else "System",assigned_name=t_obj.assignee.full_name if t_obj.assignee else None,is_escalated=t_obj.is_escalated,score=round(norm_score, 1) # Display as e.g. 98.5)final_results.append(result_item)110 unmodified lines111112113114115116117118119120314 unmodified lines435436437438439440441442110 unmodified linesdup_res = await db.execute(dup_stmt)setattr(ticket, "duplicate_of_title", dup_res.scalar_one_or_none())# 7. Ownership Identity (Frontend Sync)setattr(ticket, "is_mine", ticket.created_by == user.id)# 8. Metadata Sanitization & Internal Flag Injectioncreator_role = ticket.creator.role if ticket.creator else Noneis_internal = creator_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]setattr(ticket, "creator_name", ticket.creator.full_name if ticket.creator else "System")314 unmodified linescreator_name=t_obj.creator.full_name if t_obj.creator else "System",assigned_name=t_obj.assignee.full_name if t_obj.assignee else None,is_escalated=t_obj.is_escalated,score=round(norm_score, 1), # Display as e.g. 98.5is_mine=t_obj.created_by == current_user.id)final_results.append(result_item)
86 unmodified lines8788899091929394953 unmodified lines9910010110286 unmodified linesfrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporterfrom opentelemetry.instrumentation.fastapi import FastAPIInstrumentor# Set global TracerProviderprovider = TracerProvider()# Use Console Exporting for local development# In production, this would be an OTLP exporter to Jaeger/Datadog/NewRelic3 unmodified lines# Auto-instrument FastAPI routesFastAPIInstrumentor.instrument_app(app)logger.info("OpenTelemetry Global Trace Provider configured and hooked to FastAPI")86 unmodified lines878889909192939495969798991001011021031043 unmodified lines10810911011186 unmodified linesfrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporterfrom opentelemetry.instrumentation.fastapi import FastAPIInstrumentorfrom opentelemetry.sdk.resources import SERVICE_NAME, Resourcefrom core.config import get_settingssettings = get_settings()# Define the Resource (Service Name)resource = Resource(attributes={SERVICE_NAME: settings.APP_NAME})# Set global TracerProvider with the Resourceprovider = TracerProvider(resource=resource)# Use Console Exporting for local development# In production, this would be an OTLP exporter to Jaeger/Datadog/NewRelic3 unmodified lines# Auto-instrument FastAPI routesFastAPIInstrumentor.instrument_app(app)logger.info(f"OpenTelemetry Trace Provider configured for service: {settings.APP_NAME}")
625 unmodified lines626627628629630631632633625 unmodified linesselect(func.count(Ticket.id)).where(Ticket.workspace_id == w_id,Ticket.priority == 'urgent',Ticket.status != 'closed',Ticket.updated_at >= fifteen_mins_ago))625 unmodified lines626627628629630631632633625 unmodified linesselect(func.count(Ticket.id)).where(Ticket.workspace_id == w_id,Ticket.priority == TicketPriority.P0,Ticket.status != TicketStatus.CLOSED,Ticket.updated_at >= fifteen_mins_ago))
102 unmodified lines103104105106107108109102 unmodified linessetSelectedTicket={setSelectedTicket}tickets={tickets}loading={ticketsLoading}user={user}/>)}{active === "thread" && selectedTicket && (102 unmodified lines103104105106107108102 unmodified linessetSelectedTicket={setSelectedTicket}tickets={tickets}loading={ticketsLoading}/>)}{active === "thread" && selectedTicket && (
30 unmodified lines31323334353637383930 unmodified linesconst [kbLoading, setKbLoading] = useState(false);const [stats, setStats] = useState<any>(null);const userTickets = user ? tickets.filter(t => t.created_by === user.id) : [];const activeTickets = userTickets.filter(t => t.status.toLowerCase() === "open" || t.status.toLowerCase() === "in_progress").sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());useEffect(() => {30 unmodified lines3132333435363738394030 unmodified linesconst [kbLoading, setKbLoading] = useState(false);const [stats, setStats] = useState<any>(null);const isAdmin = user?.role?.toLowerCase().includes('admin');const userTickets = user ? (isAdmin ? tickets : tickets.filter(t => t.is_mine)) : [];const activeTickets = userTickets.filter(t => t.status.toLowerCase() === "open" || t.status.toLowerCase() === "in_progress" || t.status.toLowerCase() === "acknowledged").sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());useEffect(() => {
197 unmodified lines198199200201202203204197 unmodified linesheaders: { 'Content-Type': 'multipart/form-data' }});const downloadUrl = `/api/v1/workspace/attachments/${resp.data.id}/download`;const markdownImage = `\n\n`;if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, markdownImage));197 unmodified lines198199200201202203204197 unmodified linesheaders: { 'Content-Type': 'multipart/form-data' }});const downloadUrl = `/api/v1/tickets/attachments/${resp.data.id}/download`;const markdownImage = `\n\n`;if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, markdownImage));
19 unmodified lines2021222324252627282930313218 unmodified lines5152535455565719 unmodified linessetSelectedTicket: (ticket: any) => void;tickets: any[];loading: boolean;user: any;}const STATUSES = ["OPEN", "ACKNOWLEDGED", "IN_PROGRESS", "RESOLVED", "CLOSED"];const PRIORITIES = ["P0", "P1", "P2", "P3"];export const TicketList: React.FC<TicketListProps> = ({ setActive, setSelectedTicket, tickets, loading, user }) => {const [viewMode, setViewMode] = useState<"ALL" | "MINE">("ALL");const [searchQuery, setSearchQuery] = useState("");const [creatorFilter, setCreatorFilter] = useState("");18 unmodified linesconst filtered = tickets.filter(t => {// 1. View Mode (All vs Mine)if (viewMode === "MINE" && t.created_by !== user.id) return false;// 2. Statusif (statusFilter !== "ALL" && t.status.toUpperCase() !== statusFilter) return false;19 unmodified lines20212223242526272829303118 unmodified lines5051525354555619 unmodified linessetSelectedTicket: (ticket: any) => void;tickets: any[];loading: boolean;}const STATUSES = ["OPEN", "ACKNOWLEDGED", "IN_PROGRESS", "RESOLVED", "CLOSED"];const PRIORITIES = ["P0", "P1", "P2", "P3"];export const TicketList: React.FC<TicketListProps> = ({ setActive, setSelectedTicket, tickets, loading }) => {const [viewMode, setViewMode] = useState<"ALL" | "MINE">("ALL");const [searchQuery, setSearchQuery] = useState("");const [creatorFilter, setCreatorFilter] = useState("");18 unmodified linesconst filtered = tickets.filter(t => {// 1. View Mode (All vs Mine)if (viewMode === "MINE" && !t.is_mine) return false;// 2. Statusif (statusFilter !== "ALL" && t.status.toUpperCase() !== statusFilter) return false;
26 unmodified lines27282930313233343536375 unmodified lines4344454647484953 unmodified lines10310410510610710826 unmodified linesexport const AuthContext = createContext<AuthContextType | undefined>(undefined);export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {const [auth, setAuth] = useState<AuthState>({user: null,token: localStorage.getItem('token'),loading: false,error: null,});const hasRole = useCallback((roles: string | string[]) => {5 unmodified linesconst fetchProfile = useCallback(async () => {try {const resp = await api.get('auth/me');setAuth(prev => ({ ...prev, user: resp.data, loading: false }));} catch (err: any) {if (err.response?.status === 401) {localStorage.removeItem('token');53 unmodified lines} finally {localStorage.removeItem('token');localStorage.removeItem('refresh_token');setAuth({ user: null, token: null, loading: false, error: null });window.location.href = '/';}26 unmodified lines2728293031323334353637383940415 unmodified lines47484950515253545553 unmodified lines10911011111211311411526 unmodified linesexport const AuthContext = createContext<AuthContextType | undefined>(undefined);export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {const [auth, setAuth] = useState<AuthState>(() => {const savedToken = localStorage.getItem('token');const savedUser = localStorage.getItem('user');return {user: savedUser ? JSON.parse(savedUser) : null,token: savedToken,loading: false,error: null,};});const hasRole = useCallback((roles: string | string[]) => {5 unmodified linesconst fetchProfile = useCallback(async () => {try {const resp = await api.get('auth/me');const userData = resp.data;localStorage.setItem('user', JSON.stringify(userData));setAuth(prev => ({ ...prev, user: userData, loading: false }));} catch (err: any) {if (err.response?.status === 401) {localStorage.removeItem('token');53 unmodified lines} finally {localStorage.removeItem('token');localStorage.removeItem('refresh_token');localStorage.removeItem('user');setAuth({ user: null, token: null, loading: false, error: null });window.location.href = '/';}
22 unmodified lines23242526272813 unmodified lines424344454622 unmodified linesfrom models.knowledge_insight_ticket import KnowledgeInsightTicketfrom models.meta_infra_health import MetaInfraHealthfrom models.nexus_semantic_cache import NexusSemanticCache__all__ = ["Workspace",13 unmodified lines"RemediationHook", "RemediationActionType","MetaInfraHealth","KnowledgeInsight", "InsightType", "InsightStatus", "KnowledgeInsightTicket","NexusSemanticCache"]22 unmodified lines2324252627282913 unmodified lines43444546474822 unmodified linesfrom models.knowledge_insight_ticket import KnowledgeInsightTicketfrom models.meta_infra_health import MetaInfraHealthfrom models.nexus_semantic_cache import NexusSemanticCachefrom models.nexus_checkpoint import NexusCheckpoint, NexusCheckpointWrite__all__ = ["Workspace",13 unmodified lines"RemediationHook", "RemediationActionType","MetaInfraHealth","KnowledgeInsight", "InsightType", "InsightStatus", "KnowledgeInsightTicket","NexusSemanticCache","NexusCheckpoint", "NexusCheckpointWrite"]
123412 unmodified lines171819from sqlalchemy import Column, String, LargeBinaryfrom sqlalchemy.dialects.postgresql import UUIDfrom core.database import Base12 unmodified lines# Serialized statecheckpoint_data = Column(LargeBinary, nullable=False)metadata_data = Column(LargeBinary, nullable=True)123412 unmodified lines1718192021222324252627282930313233from sqlalchemy import Column, String, LargeBinary, Integerfrom sqlalchemy.dialects.postgresql import UUIDfrom core.database import Base12 unmodified lines# Serialized statecheckpoint_data = Column(LargeBinary, nullable=False)metadata_data = Column(LargeBinary, nullable=True)class NexusCheckpointWrite(Base):"""Stores intermediate task writes for LangGraph async execution."""__tablename__ = "nexus_checkpoint_writes"thread_id = Column(String, primary_key=True)checkpoint_id = Column(String, primary_key=True)task_id = Column(String, primary_key=True)idx = Column(Integer, primary_key=True)channel = Column(String, nullable=False)value = Column(LargeBinary, nullable=False)
50 unmodified lines51525354555623 unmodified lines80818283848550 unmodified linesrating: Optional[int] = Nonecreated_at: datetimeupdated_at: datetimemodel_config = ConfigDict(from_attributes=True)23 unmodified linesassigned_name: Optional[str] = Noneis_escalated: Optional[datetime] = Nonescore: floatclass TicketSearchResponse(BaseModel):results: List[TicketSearchResult]50 unmodified lines5152535455565723 unmodified lines8182838485868750 unmodified linesrating: Optional[int] = Nonecreated_at: datetimeupdated_at: datetimeis_mine: bool = Falsemodel_config = ConfigDict(from_attributes=True)23 unmodified linesassigned_name: Optional[str] = Noneis_escalated: Optional[datetime] = Nonescore: floatis_mine: bool = Falseclass TicketSearchResponse(BaseModel):results: List[TicketSearchResult]
123456789101112131415161718192021222324252627282930
import asynciofrom core.security import create_access_tokenfrom core.database import async_session_factoryfrom sqlalchemy import selectfrom models.user import User, UserRolefrom models.user_workspace import UserWorkspace
async def get_token(): async with async_session_factory() as db: # Fetch ANSELL ADMIN u_res = await db.execute(select(User).where(User.email == "admin@ansell.com")) user = u_res.scalar_one_or_none() if not user: print("User not found") return
# Fetch association assoc_res = await db.execute(select(UserWorkspace).where(UserWorkspace.user_id == user.id)) assoc = assoc_res.scalar_one_or_none() token = create_access_token( subject=str(user.id), workspace_id=str(assoc.workspace_id), role=assoc.role ) print(f"TOKEN: {token}")
if __name__ == "__main__": asyncio.run(get_token())agents/nexus_checkpoint.py+21-1
agents/nexus_customer.py+2-2
agents/nexus_master.py+3-2
agents/tools/nexus_tools.py+12-2
alembic/versions/1536118577ca_add_nexus_checkpoint_writes.pyAdded+40
api/v1/dashboard.py+10-7
api/v1/tickets.py+6-2
core/observability.py+12-3
core/tasks.py+2-2
frontend/apps/customer/src/App.tsx-1
frontend/apps/customer/src/components/Dashboard.tsx+3-2
frontend/apps/customer/src/components/ThreadView.tsx+1-1
frontend/apps/customer/src/components/TicketList.tsx+2-3
frontend/packages/shared/src/contexts/AuthContext.tsx+13-6
models/__init__.py+3-1
models/nexus_checkpoint.py+15-1
schemas/ticket.py+2
tmp_get_token.pyAdded+30