Skip to content

Missing array bounds checking in LLM provider response handling #11700

Description

@ryan-mt

Summary

The LLM provider SDK code accesses array elements without checking if the array is non-empty, which can cause runtime crashes when the API returns unexpected responses.

Locations

  • packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts:216
  • packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts:435
  • packages/opencode/src/provider/sdk/copilot/responses/openai-responses-language-model.ts:435

Issue

// Line 216 - doGenerate()
const choice = responseBody.choices[0]  // No check if choices array is empty
const content: Array<LanguageModelV2Content> = []
const text = choice.message.content  // Will throw if choice is undefined

// Line 435 - doStream()
const choice = value.choices[0]  // Same issue in streaming
if (choice?.finish_reason != null) {
  // ...
}

If the API returns an empty choices array (which can happen on errors or edge cases), accessing choices[0] returns undefined, and subsequent property access throws "Cannot read property 'message' of undefined".

Impact

  • Severity: Medium
  • Type: Runtime Error
  • Effect: Unhandled exception when API returns empty choices

Suggested Fix

Add bounds checking:

const choice = responseBody.choices[0]
if (!choice) {
  throw new InvalidResponseDataError({
    data: responseBody,
    message: "Response contained no choices"
  })
}

Or use optional chaining with fallback:

const choice = responseBody.choices?.[0]
if (!choice?.message) {
  // Handle empty response case
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions