File size: 15,136 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 | /**
* LocalMainSessionTask - Handles backgrounding the main session query.
*
* When user presses Ctrl+B twice during a query, the session is "backgrounded":
* - The query continues running in the background
* - The UI clears to a fresh prompt
* - A notification is sent when the query completes
*
* This reuses the LocalAgentTask state structure since the behavior is similar.
*/
import type { UUID } from 'crypto'
import { randomBytes } from 'crypto'
import {
OUTPUT_FILE_TAG,
STATUS_TAG,
SUMMARY_TAG,
TASK_ID_TAG,
TASK_NOTIFICATION_TAG,
TOOL_USE_ID_TAG,
} from '../constants/xml.js'
import { type QueryParams, query } from '../query.js'
import { roughTokenCountEstimation } from '../services/tokenEstimation.js'
import type { SetAppState } from '../Task.js'
import { createTaskStateBase } from '../Task.js'
import type {
AgentDefinition,
CustomAgentDefinition,
} from '../tools/AgentTool/loadAgentsDir.js'
import { asAgentId } from '../types/ids.js'
import type { Message } from '../types/message.js'
import { createAbortController } from '../utils/abortController.js'
import {
runWithAgentContext,
type SubagentContext,
} from '../utils/agentContext.js'
import { registerCleanup } from '../utils/cleanupRegistry.js'
import { logForDebugging } from '../utils/debug.js'
import { logError } from '../utils/log.js'
import { enqueuePendingNotification } from '../utils/messageQueueManager.js'
import { emitTaskTerminatedSdk } from '../utils/sdkEventQueue.js'
import {
getAgentTranscriptPath,
recordSidechainTranscript,
} from '../utils/sessionStorage.js'
import {
evictTaskOutput,
getTaskOutputPath,
initTaskOutputAsSymlink,
} from '../utils/task/diskOutput.js'
import { registerTask, updateTaskState } from '../utils/task/framework.js'
import type { LocalAgentTaskState } from './LocalAgentTask/LocalAgentTask.js'
// Main session tasks use LocalAgentTaskState with agentType='main-session'
export type LocalMainSessionTaskState = LocalAgentTaskState & {
agentType: 'main-session'
}
/**
* Default agent definition for main session tasks when no agent is specified.
*/
const DEFAULT_MAIN_SESSION_AGENT: CustomAgentDefinition = {
agentType: 'main-session',
whenToUse: 'Main session query',
source: 'userSettings',
getSystemPrompt: () => '',
}
/**
* Generate a unique task ID for main session tasks.
* Uses 's' prefix to distinguish from agent tasks ('a' prefix).
*/
const TASK_ID_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'
function generateMainSessionTaskId(): string {
const bytes = randomBytes(8)
let id = 's'
for (let i = 0; i < 8; i++) {
id += TASK_ID_ALPHABET[bytes[i]! % TASK_ID_ALPHABET.length]
}
return id
}
/**
* Register a backgrounded main session task.
* Called when the user backgrounds the current session query.
*
* @param description - Description of the task
* @param setAppState - State setter function
* @param mainThreadAgentDefinition - Optional agent definition if running with --agent
* @param existingAbortController - Optional abort controller to reuse (for backgrounding an active query)
* @returns Object with task ID and abort signal for stopping the background query
*/
export function registerMainSessionTask(
description: string,
setAppState: SetAppState,
mainThreadAgentDefinition?: AgentDefinition,
existingAbortController?: AbortController,
): { taskId: string; abortSignal: AbortSignal } {
const taskId = generateMainSessionTaskId()
// Link output to an isolated per-task transcript file (same layout as
// sub-agents). Do NOT use getTranscriptPath() — that's the main session's
// file, and writing there from a background query after /clear would corrupt
// the post-clear conversation. The isolated path lets this task survive
// /clear: the symlink re-link in clearConversation handles session ID changes.
void initTaskOutputAsSymlink(
taskId,
getAgentTranscriptPath(asAgentId(taskId)),
)
// Use the existing abort controller if provided (important for backgrounding an active query)
// This ensures that aborting the task will abort the actual query
const abortController = existingAbortController ?? createAbortController()
const unregisterCleanup = registerCleanup(async () => {
// Clean up on process exit
setAppState(prev => {
const { [taskId]: removed, ...rest } = prev.tasks
return { ...prev, tasks: rest }
})
})
// Use provided agent definition or default
const selectedAgent = mainThreadAgentDefinition ?? DEFAULT_MAIN_SESSION_AGENT
// Create task state - already backgrounded since this is called when user backgrounds
const taskState: LocalMainSessionTaskState = {
...createTaskStateBase(taskId, 'local_agent', description),
type: 'local_agent',
status: 'running',
agentId: taskId,
prompt: description,
selectedAgent,
agentType: 'main-session',
abortController,
unregisterCleanup,
retrieved: false,
lastReportedToolCount: 0,
lastReportedTokenCount: 0,
isBackgrounded: true, // Already backgrounded
pendingMessages: [],
retain: false,
diskLoaded: false,
}
logForDebugging(
`[LocalMainSessionTask] Registering task ${taskId} with description: ${description}`,
)
registerTask(taskState, setAppState)
// Verify task was registered by checking state
setAppState(prev => {
const hasTask = taskId in prev.tasks
logForDebugging(
`[LocalMainSessionTask] After registration, task ${taskId} exists in state: ${hasTask}`,
)
return prev
})
return { taskId, abortSignal: abortController.signal }
}
/**
* Complete the main session task and send notification.
* Called when the backgrounded query finishes.
*/
export function completeMainSessionTask(
taskId: string,
success: boolean,
setAppState: SetAppState,
): void {
let wasBackgrounded = true
let toolUseId: string | undefined
updateTaskState<LocalMainSessionTaskState>(taskId, setAppState, task => {
if (task.status !== 'running') {
return task
}
// Track if task was backgrounded (for notification decision)
wasBackgrounded = task.isBackgrounded ?? true
toolUseId = task.toolUseId
task.unregisterCleanup?.()
return {
...task,
status: success ? 'completed' : 'failed',
endTime: Date.now(),
messages: task.messages?.length ? [task.messages.at(-1)!] : undefined,
}
})
void evictTaskOutput(taskId)
// Only send notification if task is still backgrounded (not foregrounded)
// If foregrounded, user is watching it directly - no notification needed
if (wasBackgrounded) {
enqueueMainSessionNotification(
taskId,
'Background session',
success ? 'completed' : 'failed',
setAppState,
toolUseId,
)
} else {
// Foregrounded: no XML notification (TUI user is watching), but SDK
// consumers still need to see the task_started bookend close.
// Set notified so evictTerminalTask/generateTaskAttachments eviction
// guards pass; the backgrounded path sets this inside
// enqueueMainSessionNotification's check-and-set.
updateTaskState(taskId, setAppState, task => ({ ...task, notified: true }))
emitTaskTerminatedSdk(taskId, success ? 'completed' : 'failed', {
toolUseId,
summary: 'Background session',
})
}
}
/**
* Enqueue a notification about the backgrounded session completing.
*/
function enqueueMainSessionNotification(
taskId: string,
description: string,
status: 'completed' | 'failed',
setAppState: SetAppState,
toolUseId?: string,
): void {
// Atomically check and set notified flag to prevent duplicate notifications.
let shouldEnqueue = false
updateTaskState(taskId, setAppState, task => {
if (task.notified) {
return task
}
shouldEnqueue = true
return { ...task, notified: true }
})
if (!shouldEnqueue) {
return
}
const summary =
status === 'completed'
? `Background session "${description}" completed`
: `Background session "${description}" failed`
const toolUseIdLine = toolUseId
? `\n<${TOOL_USE_ID_TAG}>${toolUseId}</${TOOL_USE_ID_TAG}>`
: ''
const outputPath = getTaskOutputPath(taskId)
const message = `<${TASK_NOTIFICATION_TAG}>
<${TASK_ID_TAG}>${taskId}</${TASK_ID_TAG}>${toolUseIdLine}
<${OUTPUT_FILE_TAG}>${outputPath}</${OUTPUT_FILE_TAG}>
<${STATUS_TAG}>${status}</${STATUS_TAG}>
<${SUMMARY_TAG}>${summary}</${SUMMARY_TAG}>
</${TASK_NOTIFICATION_TAG}>`
enqueuePendingNotification({ value: message, mode: 'task-notification' })
}
/**
* Foreground a main session task - mark it as foregrounded so its output
* appears in the main view. The background query keeps running.
* Returns the task's accumulated messages, or undefined if task not found.
*/
export function foregroundMainSessionTask(
taskId: string,
setAppState: SetAppState,
): Message[] | undefined {
let taskMessages: Message[] | undefined
setAppState(prev => {
const task = prev.tasks[taskId]
if (!task || task.type !== 'local_agent') {
return prev
}
taskMessages = (task as LocalMainSessionTaskState).messages
// Restore previous foregrounded task to background if it exists
const prevId = prev.foregroundedTaskId
const prevTask = prevId ? prev.tasks[prevId] : undefined
const restorePrev =
prevId && prevId !== taskId && prevTask?.type === 'local_agent'
return {
...prev,
foregroundedTaskId: taskId,
tasks: {
...prev.tasks,
...(restorePrev && { [prevId]: { ...prevTask, isBackgrounded: true } }),
[taskId]: { ...task, isBackgrounded: false },
},
}
})
return taskMessages
}
/**
* Check if a task is a main session task (vs a regular agent task).
*/
export function isMainSessionTask(
task: unknown,
): task is LocalMainSessionTaskState {
if (
typeof task !== 'object' ||
task === null ||
!('type' in task) ||
!('agentType' in task)
) {
return false
}
return (
task.type === 'local_agent' &&
(task as LocalMainSessionTaskState).agentType === 'main-session'
)
}
// Max recent activities to keep for display
const MAX_RECENT_ACTIVITIES = 5
type ToolActivity = {
toolName: string
input: Record<string, unknown>
}
/**
* Start a fresh background session with the given messages.
*
* Spawns an independent query() call with the current messages and registers it
* as a background task. The caller's foreground query continues running normally.
*/
export function startBackgroundSession({
messages,
queryParams,
description,
setAppState,
agentDefinition,
}: {
messages: Message[]
queryParams: Omit<QueryParams, 'messages'>
description: string
setAppState: SetAppState
agentDefinition?: AgentDefinition
}): string {
const { taskId, abortSignal } = registerMainSessionTask(
description,
setAppState,
agentDefinition,
)
// Persist the pre-backgrounding conversation to the task's isolated
// transcript so TaskOutput shows context immediately. Subsequent messages
// are written incrementally below.
void recordSidechainTranscript(messages, taskId).catch(err =>
logForDebugging(`bg-session initial transcript write failed: ${err}`),
)
// Wrap in agent context so skill invocations scope to this task's agentId
// (not null). This lets clearInvokedSkills(preservedAgentIds) selectively
// preserve this task's skills across /clear. AsyncLocalStorage isolates
// concurrent async chains — this wrapper doesn't affect the foreground.
const agentContext: SubagentContext = {
agentId: taskId,
agentType: 'subagent',
subagentName: 'main-session',
isBuiltIn: true,
}
void runWithAgentContext(agentContext, async () => {
try {
const bgMessages: Message[] = [...messages]
const recentActivities: ToolActivity[] = []
let toolCount = 0
let tokenCount = 0
let lastRecordedUuid: UUID | null = messages.at(-1)?.uuid ?? null
for await (const event of query({
messages: bgMessages,
...queryParams,
})) {
if (abortSignal.aborted) {
// Aborted mid-stream — completeMainSessionTask won't be reached.
// chat:killAgents path already marked notified + emitted; stopTask path did not.
let alreadyNotified = false
updateTaskState(taskId, setAppState, task => {
alreadyNotified = task.notified === true
return alreadyNotified ? task : { ...task, notified: true }
})
if (!alreadyNotified) {
emitTaskTerminatedSdk(taskId, 'stopped', {
summary: description,
})
}
return
}
if (
event.type !== 'user' &&
event.type !== 'assistant' &&
event.type !== 'system'
) {
continue
}
bgMessages.push(event)
// Per-message write (matches runAgent.ts pattern) — gives live
// TaskOutput progress and keeps the transcript file current even if
// /clear re-links the symlink mid-run.
void recordSidechainTranscript([event], taskId, lastRecordedUuid).catch(
err => logForDebugging(`bg-session transcript write failed: ${err}`),
)
lastRecordedUuid = event.uuid
if (event.type === 'assistant') {
for (const block of event.message.content) {
if (block.type === 'text') {
tokenCount += roughTokenCountEstimation(block.text)
} else if (block.type === 'tool_use') {
toolCount++
const activity: ToolActivity = {
toolName: block.name,
input: block.input as Record<string, unknown>,
}
recentActivities.push(activity)
if (recentActivities.length > MAX_RECENT_ACTIVITIES) {
recentActivities.shift()
}
}
}
}
setAppState(prev => {
const task = prev.tasks[taskId]
if (!task || task.type !== 'local_agent') return prev
const prevProgress = task.progress
if (
prevProgress?.tokenCount === tokenCount &&
prevProgress.toolUseCount === toolCount &&
task.messages === bgMessages
) {
return prev
}
return {
...prev,
tasks: {
...prev.tasks,
[taskId]: {
...task,
progress: {
tokenCount,
toolUseCount: toolCount,
recentActivities:
prevProgress?.toolUseCount === toolCount
? prevProgress.recentActivities
: [...recentActivities],
},
messages: bgMessages,
},
},
}
})
}
completeMainSessionTask(taskId, true, setAppState)
} catch (error) {
logError(error)
completeMainSessionTask(taskId, false, setAppState)
}
})
return taskId
}
|