Skip to content

Add generic type parameters to StreamOptions for typed streaming callbacks #819

@threepointone

Description

@threepointone

(via cursor/opus, not sure if we should do this just yet)

Summary

The StreamOptions type currently uses unknown for chunk and final result types, requiring developers to manually type their callbacks or use type assertions.

Current Behavior

export type StreamOptions = {
  onChunk?: (chunk: unknown) => void;
  onDone?: (finalChunk: unknown) => void;
  onError?: (error: string) => void;
};

When using streaming methods, developers must manually type their callbacks:

agent.call("streamNumbers", [10], {
  stream: {
    onChunk: (chunk) => {
      // chunk is unknown, requires cast
      const data = chunk as { number: number };
    }
  }
});

Proposed Change

Add generic type parameters with unknown defaults for backward compatibility:

export type StreamOptions<TChunk = unknown, TFinal = unknown> = {
  onChunk?: (chunk: TChunk) => void;
  onDone?: (finalChunk: TFinal) => void;
  onError?: (error: string) => void;
};

This allows explicit typing when desired:

agent.call("streamNumbers", [10], {
  stream: {
    onChunk: (chunk: { number: number }) => { ... },
    onDone: (final: { total: number }) => { ... }
  }
} as CallOptions<{ number: number }, { total: number }>);

Limitations

This is a partial improvement. True type inference would require:

  1. Extracting chunk/final types from the agent's streaming method signature
  2. Propagating those types through agent.call() to StreamOptions

This is non-trivial because streaming methods have a special signature where StreamingResponse is injected as the first parameter, and the SDK would need to introspect the stream.send() and stream.end() call types.

Backward Compatibility

Fully backward compatible - the default generic parameters are unknown, so existing code continues to work unchanged.

Related Files

  • packages/agents/src/client.ts - StreamOptions and CallOptions types
  • packages/agents/src/react.tsx - useAgent hook

Metadata

Metadata

Assignees

No one assigned

    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