/ utils / task / outputFormatting.ts
outputFormatting.ts
 1  import { validateBoundedIntEnvVar } from '../envValidation.js'
 2  import { getTaskOutputPath } from './diskOutput.js'
 3  
 4  export const TASK_MAX_OUTPUT_UPPER_LIMIT = 160_000
 5  export const TASK_MAX_OUTPUT_DEFAULT = 32_000
 6  
 7  export function getMaxTaskOutputLength(): number {
 8    const result = validateBoundedIntEnvVar(
 9      'TASK_MAX_OUTPUT_LENGTH',
10      process.env.TASK_MAX_OUTPUT_LENGTH,
11      TASK_MAX_OUTPUT_DEFAULT,
12      TASK_MAX_OUTPUT_UPPER_LIMIT,
13    )
14    return result.effective
15  }
16  
17  /**
18   * Format task output for API consumption, truncating if too large.
19   * When truncated, includes a header with the file path and returns
20   * the last N characters that fit within the limit.
21   */
22  export function formatTaskOutput(
23    output: string,
24    taskId: string,
25  ): { content: string; wasTruncated: boolean } {
26    const maxLen = getMaxTaskOutputLength()
27  
28    if (output.length <= maxLen) {
29      return { content: output, wasTruncated: false }
30    }
31  
32    const filePath = getTaskOutputPath(taskId)
33    const header = `[Truncated. Full output: ${filePath}]\n\n`
34    const availableSpace = maxLen - header.length
35    const truncated = output.slice(-availableSpace)
36  
37    return { content: header + truncated, wasTruncated: true }
38  }