fix(tools): handle binary file downloads in tool execution

Merged
JE
6mo ago
+529-37

Summary

  • File-download actions (e.g. googledrive_unified_download_file) serve raw binary with the file's own MIME type and a Content-Disposition header. Both execution paths called response.json() unconditionally and raised SyntaxError: Unexpected token '%' on the first non-JSON byte: RpcClient.rpcAction (src/rpc-client.ts) and RequestBuilder.execute (src/requestBuilder.ts). Every StackOneToolSet unified action runs through the RPC path, so downloads failed outright.
  • Both paths now branch on Content-Type: JSON media types (application/json and +json suffixes) are parsed as before; any other type returns the file as { content: Buffer, contentType, statusCode, headers, fileName }, matching the StackOne generated SDKs' download response shape. fileName is parsed from Content-Disposition (including RFC 5987 filename*).
  • Shared logic lives in src/utils/binary-response.ts. The public isBinaryDownloadResult type guard and BinaryDownloadResult type let callers narrow the result without casts.
  • Existing JSON responses are unchanged.

Note: content holds raw bytes (a Buffer) and is not JSON-serializable — callers that re-serialize tool results (e.g. for an LLM) should handle that key. This is the node port of StackOneHQ/stackone-ai-python#190.


Summary by cubic

Fixes tool execution to correctly handle binary file downloads by detecting Content-Type and returning raw bytes plus metadata instead of parsing JSON. This unblocks all *_unified_download_file actions over RPC and HTTP (e.g. googledrive_unified_download_file).

  • Bug Fixes
    • Branch on Content-Type: parse JSON for application/json and +json; otherwise return BinaryDownloadResult { content: Buffer, contentType, statusCode, headers, fileName }. Non-JSON error bodies now raise StackOneAPIError (not SyntaxError).
    • Shared helpers in src/utils/binary-response.ts (isJsonContentType, isBinaryDownloadResult, filename parsing incl. RFC 5987 with safe fallback) used by both RpcClient.actions.rpcAction and RequestBuilder.execute; JSON behavior unchanged.
    • Exported isBinaryDownloadResult and BinaryDownloadResult from the public API; widened rpcAction return type to RpcActionResponse | BinaryDownloadResult and updated tests to narrow with the guard; added README docs.
    • Note: content is a Buffer and not JSON-serializable; encode or omit when forwarding to an LLM.