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:
| Field | Type | Description |
|---|---|---|
systemPrompt | string? | Custom system prompt override |
title | string? | Initial session title |
userId | string? | User context |
orgId | string? | Organisation context |
hidden | boolean? | Exclude from session list (e.g. onboarding) |
onboarding | boolean? | 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:
| Type | Payload | Description |
|---|---|---|
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 Mode | Transport | How credentials are obtained |
|---|---|---|
SERVER_MEDIATED | STDIO / SSE | Fetches OAuth tokens from GET /api/v1/connectors/:id/credentials |
REMOTE_OAUTH | HTTP (streamable) | Loads tokens from userData/mcp-tokens/{instanceId}.json |
API_KEY | STDIO | Passes key directly as env var |
NONE | STDIO | No 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)
| Tool | Action |
|---|---|
create_task | POST /api/v1/tasks |
update_task | PATCH /api/v1/tasks/:id |
delete_task | DELETE /api/v1/tasks/:id |
list_tasks | GET /api/v1/tasks |
reprioritize_tasks | POST /api/v1/tasks/reprioritize |
buildWorkspaceDelegate(orgId)
| Tool | Action |
|---|---|
create_workspace | POST /api/v1/workspaces |
list_workspaces | GET /api/v1/workspaces |
set_active_workspace | Updates session context |
buildTeamDelegate(orgId)
| Tool | Action |
|---|---|
list_teams | GET /api/v1/teams |
list_team_members | GET /api/v1/teams/:id/members |
add_team_member | POST /api/v1/teams/:id/members |
remove_team_member | DELETE /api/v1/teams/:id/members/:userId |
buildArtifactDelegate(orgId)
| Tool | Action |
|---|---|
create_artifact | ArtifactManager.create() + emits artifacts:created |
update_artifact | ArtifactManager.update() |
list_artifacts | ArtifactManager.list() |
move_artifact | ArtifactManager.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:
| Type | Purpose |
|---|---|
next_actions | Suggested follow-up actions surfaced in the Hub |
heads_up | Warnings or important notices |
connector_required | Prompts user to add a specific MCP connector |
Silent Tools
Two tools are handled silently (no UI shown):
| Tool | Effect |
|---|---|
cosmo_use_model | Upgrades the active model for the remainder of the session |
cosmo_use_skill | Invokes 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.