task-session.ts
1 import { genId } from '@/lib/id' 2 import { WORKSPACE_DIR } from '@/lib/server/data-dir' 3 import type { Agent } from '@/types' 4 import { getEnabledCapabilitySelection } from '@/lib/capability-selection' 5 import { applyResolvedRoute, resolvePrimaryAgentRoute } from '@/lib/server/agents/agent-runtime-config' 6 import { saveSession } from '@/lib/server/sessions/session-repository' 7 8 export function createAgentTaskSession( 9 agent: Agent, 10 task: string, 11 parentSessionId?: string, 12 cwd?: string, 13 routePreferences?: { 14 preferredGatewayTags?: string[] 15 preferredGatewayUseCase?: string | null 16 } | null, 17 ): string { 18 const sessionId = genId() 19 const preferredGatewayTags = Array.isArray(routePreferences?.preferredGatewayTags) 20 ? routePreferences.preferredGatewayTags.filter((tag) => typeof tag === 'string' && tag.trim()) 21 : [] 22 const resolvedRoute = resolvePrimaryAgentRoute(agent, undefined, { 23 preferredGatewayTags, 24 preferredGatewayUseCase: routePreferences?.preferredGatewayUseCase || null, 25 }) 26 27 const session = applyResolvedRoute({ 28 id: sessionId, 29 name: `[Task] ${agent.name}: ${task.slice(0, 40)}`, 30 cwd: cwd || WORKSPACE_DIR, 31 user: 'system', 32 provider: agent.provider, 33 model: agent.model, 34 credentialId: agent.credentialId || null, 35 fallbackCredentialIds: agent.fallbackCredentialIds || [], 36 apiEndpoint: agent.apiEndpoint || null, 37 gatewayProfileId: agent.gatewayProfileId || null, 38 routePreferredGatewayTags: preferredGatewayTags, 39 routePreferredGatewayUseCase: routePreferences?.preferredGatewayUseCase || null, 40 claudeSessionId: null, 41 codexThreadId: null, 42 opencodeSessionId: null, 43 geminiSessionId: null, 44 copilotSessionId: null, 45 droidSessionId: null, 46 cursorSessionId: null, 47 qwenSessionId: null, 48 acpSessionId: null, 49 delegateResumeIds: { 50 claudeCode: null, 51 codex: null, 52 opencode: null, 53 gemini: null, 54 copilot: null, 55 droid: null, 56 cursor: null, 57 qwen: null, 58 }, 59 messages: [], 60 createdAt: Date.now(), 61 lastActiveAt: Date.now(), 62 sessionType: 'human', 63 agentId: agent.id, 64 parentSessionId: parentSessionId || null, 65 ...getEnabledCapabilitySelection(agent), 66 heartbeatEnabled: false, 67 }, resolvedRoute) 68 69 saveSession(sessionId, session) 70 return sessionId 71 }