Cosmo Docs
Desktop App

ChatManager

LLM session management, streaming, tool execution, and memory

packages/desktop/src/main/chat-manager.ts manages all AI chat interactions in the desktop app. It owns session state, connects MCP tools, streams LLM responses, and persists conversation history.

Session Lifecycle

createSession(opts?)

Creates a new chat session. Options:

FieldTypeDescription
systemPromptstring?Custom system prompt override
titlestring?Initial session title
userIdstring?User context
orgIdstring?Organisation context
hiddenboolean?Exclude from session list (e.g. onboarding)
onboardingboolean?Mark as an onboarding session

Returns SessionInfo with id, title, createdAt, lastUsedAt, messageCount.

Sessions are persisted to userData/cosmo-chat-sessions.json.

sendMessage(sessionId, content, context?, model?)

Async generator that yields ChatEvent objects as the LLM streams its response.

Event types:

TypePayloadDescription
text{ text }Partial text chunk
thinking{ thinking }Extended thinking content (Opus)
tool_call{ toolName, toolCallId, toolArgs }LLM invoked a tool
tool_result{ toolName, result }Tool execution completed
tool_confirm{ toolName, toolCallId, toolArgs, confirmId, risk, explanation, tier }Tool awaiting user confirmation
title-updated{ title }Session title auto-generated
done{ usage }Stream finished; includes token counts
error{ message }Error during generation

stopGeneration(sessionId)

Aborts the AbortController tied to the active stream for a session.

generateTitle(sessionId, userMsg, assistantMsg)

Calls the LLM with a compact prompt to produce a short (≤6 words) session title. Fires title-updated event back to the renderer.

extractAndSaveMemory(sessionId)

Called at onboarding completion. Sends a structured extraction prompt to the LLM asking it to produce JSON with fields: name, company, role, useCase, painPoints, preferences. Stores the result via OnboardingManager.

MCP Engine Initialisation

Each session gets its own @cosmohq/core engine instance. On session creation, connectCloudConnectors(engine, orgId) is called to attach all of the org's active MCP connectors.

Auth Mode Routing

Auth ModeTransportHow credentials are obtained
SERVER_MEDIATEDSTDIO / SSEFetches OAuth tokens from GET /api/v1/connectors/:id/credentials
REMOTE_OAUTHHTTP (streamable)Loads tokens from userData/mcp-tokens/{instanceId}.json
API_KEYSTDIOPasses key directly as env var
NONESTDIONo credentials required

Tool Delegates

ChatManager wires AI tool calls to real app features via delegate factories. Each delegate implements ToolDelegate from @cosmohq/core.

buildTaskDelegate(orgId)

ToolAction
create_taskPOST /api/v1/tasks
update_taskPATCH /api/v1/tasks/:id
delete_taskDELETE /api/v1/tasks/:id
list_tasksGET /api/v1/tasks
reprioritize_tasksPOST /api/v1/tasks/reprioritize

buildWorkspaceDelegate(orgId)

ToolAction
create_workspacePOST /api/v1/workspaces
list_workspacesGET /api/v1/workspaces
set_active_workspaceUpdates session context

buildTeamDelegate(orgId)

ToolAction
list_teamsGET /api/v1/teams
list_team_membersGET /api/v1/teams/:id/members
add_team_memberPOST /api/v1/teams/:id/members
remove_team_memberDELETE /api/v1/teams/:id/members/:userId

buildArtifactDelegate(orgId)

ToolAction
create_artifactArtifactManager.create() + emits artifacts:created
update_artifactArtifactManager.update()
list_artifactsArtifactManager.list()
move_artifactArtifactManager.move()

buildFeedbackDelegate()

Exposes cosmo_feedback_submit which forwards structured survey responses to PostHog.

Tool Confirmation

Tools that could be destructive (shell commands, operations guarded by billing tiers) emit a tool_confirm event with a confirmId. Execution is paused until the renderer calls chat:confirm-tool with { confirmId, approved: boolean }.

Advisory Cards

After every assistant turn, ChatManager inspects the final message for structured advisory content and emits it as ChatEvent segments:

TypePurpose
next_actionsSuggested follow-up actions surfaced in the Hub
heads_upWarnings or important notices
connector_requiredPrompts user to add a specific MCP connector

Silent Tools

Two tools are handled silently (no UI shown):

ToolEffect
cosmo_use_modelUpgrades the active model for the remainder of the session
cosmo_use_skillInvokes a skill from the skill registry

Session Persistence

Sessions and messages are saved to:

userData/
└── cosmo-chat-sessions.json   ← Array of { id, title, messages, ... }

resetEngines() disconnects all MCP clients and clears engine instances. clearAll() also deletes the session file.