Skip to content

fix(provider): parse Pollinations reasoning and tool calls - #867

Merged
mdev34-lab merged 2 commits into
dev-vibecodedfrom
arena/0234a291-silvercode
Nov 27, 2026
Merged

mdev34-lab merged 2 commits into
dev-vibecodedfrom
arena/0234a291-silvercode

Conversation

@mdev34-lab

Copy link
Copy Markdown
Owner

Issue for this PR

Fixes #866

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Pollinations remains on @ai-sdk/openai-compatible, but its model is now wrapped at the provider boundary with a Pollinations-only AI SDK v3 middleware. This keeps the global OpenAI-compatible adapter and the TUI unchanged.

The affected community model places a secondary text protocol inside OpenAI message.content: <think>...</think> reasoning plus exact {name,message} and {name,arguments} envelopes. The generic OpenAI-compatible adapter correctly treated that field as text, so SilverCode never received native reasoning or tool-call events.

The middleware:

  • maps leading protocol reasoning blocks to native reasoning content/events;
  • unwraps exact { "name": null, "message": string } assistant envelopes;
  • promotes exact { "name": string, "arguments": object } envelopes only when the named function was offered in that request;
  • emits standard AI SDK tool-call content so the existing SilverCode authorization/execution lifecycle handles it;
  • assembles fragmented streaming text before parsing, preserving protocol order and changing the finish reason to tool-calls when appropriate;
  • handles equivalent non-streaming output;
  • preserves normal prose, ordinary JSON, ambiguous objects, malformed JSON, and quoted <think> examples;
  • raises a protocol error for unterminated leading reasoning or a protocol-shaped request for an unavailable tool.

Investigation

I inspected Pollinations' current source and API documentation at gen.pollinations.ai, including the Chat Completions path, community endpoint proxying, GLM 5.3 Flash routing, reasoning transforms, and OpenAI response contracts. Pollinations' documented gateway response is standard OpenAI Chat Completions. For community proxy models, however, the upstream model's content can itself contain the observed secondary protocol; this survives the gateway in message.content. AI SDK v3 therefore sees ordinary text, and SilverCode's normal event conversion has no structured call to dispatch.

The fixture is explicitly labelled as a sanitized transcription of the issue's observed response, not a raw live HTTP capture. This environment had no POLLINATIONS_API_KEY, and outbound access to gen.pollinations.ai was unavailable, so I could not truthfully capture headers/bodies or compare live streaming and non-streaming calls. No credential or authorization header is stored.

How did you verify your code works?

Run locally with Bun 1.3.14; no cloud CI was used.

  • bun test test/provider/pollinations-protocol.test.ts test/provider/pollinations.test.ts test/provider/pollinations-provider.test.ts: 19 pass, 0 fail.
  • bun test test/server/httpapi-provider.test.ts: 7 pass, 1 pre-existing skip, 0 fail.
  • NODE_OPTIONS=--max-old-space-size=8192 bun typecheck in packages/opencode: pass.
  • bunx oxlint packages/opencode/src/provider/pollinations-protocol.ts packages/opencode/test/provider/pollinations-protocol.test.ts: 0 warnings, 0 errors.
  • Prettier check on all changed TypeScript/JSON files: pass.
  • bun test test/provider: attempted, but the sandbox run timed out after 30 minutes. Before timeout it reported one timing-sensitive pre-existing failure in header-timeout.test.ts; the focused Pollinations tests passed separately.

Regression coverage asserts native internal content/events, including assistant unwrapping, reasoning, validated finish calls, fragmented streaming markers/arguments, non-streaming conversion, mixed output, normal text, ordinary JSON, malformed/ambiguous data, unavailable tools, finish reason, and event order.

Self-review

Reviewed against the fixed base 1792c472a80309660bb7ac4a06915cc074884b0b for correctness, architecture, security, and scope. Corrections made during review:

  • constrained parsing to leading protocol-shaped output so quoted tags in prose remain visible;
  • required exact envelope keys and object arguments;
  • allowlisted tool names from the per-request tool catalog;
  • made malformed/ambiguous JSON remain text while malformed leading protocol raises a clear error;
  • fixed stream pull behavior for chunks that are buffered without immediate output;
  • stabilized synthetic call IDs independently of whitespace chunks;
  • kept the implementation provider-local and avoided a parallel execution path.

Screenshots / recordings

No screenshot is attached. A real Pollinations TUI interaction could not be performed without a credential/network access, and presenting fixture-backed output as live evidence would be misleading. The change does not alter TUI rendering; it changes the AI SDK events entering the existing TUI/session pipeline. This limitation should be resolved by a credentialed reviewer before merge.

@github-actions

Copy link
Copy Markdown

Thanks for your contribution!

This PR doesn't have a linked issue. All PRs must reference an existing issue.

Please:

  1. Open an issue describing the bug/feature (if one doesn't exist)
  2. Add Fixes #<number> or Closes #<number> to this PR description

See CONTRIBUTING.md for details.

@github-actions

Copy link
Copy Markdown

This PR doesn't fully meet our contributing guidelines and PR template.

What needs to be fixed:

  • PR description is missing required template sections. Please use the PR template.

Please edit this PR description to address the above within 2 hours, or it will be automatically closed.

If you believe this was flagged incorrectly, please let a maintainer know.

@kilo-code-bot

kilo-code-bot Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: 1 Issue Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 1
SUGGESTION 0
Issue Details (click to expand)

WARNING

File Line Issue
packages/opencode/src/provider/pollinations-protocol.ts 178 Escaped quotes inside JSON strings are mishandled in readJSONObject
Files Reviewed (5 files)
  • PLAN.md
  • packages/opencode/src/provider/pollinations-protocol.ts - 1 issue
  • packages/opencode/src/provider/provider.ts
  • packages/opencode/test/fixtures/pollinations/glm-5.3-flash-observed.json
  • packages/opencode/test/provider/pollinations-protocol.test.ts

Fix these issues in Kilo Cloud

Previous Review Summary (commit 7e31e8e)

Current summary above is authoritative. Previous snapshots are kept for context only.

Previous review (commit 7e31e8e)

Status: 1 Issue Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 1
SUGGESTION 0
Issue Details (click to expand)

WARNING

File Line Issue
packages/opencode/src/provider/pollinations-protocol.ts 178 Escaped quotes inside JSON strings are mishandled in readJSONObject
Files Reviewed (5 files)
  • PLAN.md
  • packages/opencode/src/provider/pollinations-protocol.ts - 1 issue
  • packages/opencode/src/provider/provider.ts
  • packages/opencode/test/fixtures/pollinations/glm-5.3-flash-observed.json
  • packages/opencode/test/provider/pollinations-protocol.test.ts

Fix these issues in Kilo Cloud


Reviewed by free · Input: 103.4K · Output: 24.3K · Cached: 221.6K

@mdev34-lab mdev34-lab left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

The provider-local middleware is the right integration point, and the focused tests/typecheck are useful. I found two correctness issues in the parser that should be fixed before merge:

  1. JSON string escaping is broken in readJSONObject; escaped quotes terminate the string state early and can prevent valid envelopes from being parsed.
  2. The scanner promotes any nested object matching the tool envelope, even when it is merely part of an ordinary JSON object or other text. That can turn an example/data payload into an actual tool invocation. Only top-level protocol envelopes in the expected sequence should be eligible for promotion.

Verification: the PR's typecheck workflow passed. The Linux unit-test job timed out at 20 minutes after reporting 5,161 passes, 25 skips, 1 todo and 0 failures; Windows unit tests passed. This is inconclusive for the full suite, not evidence of a test failure. The author-reported focused Pollinations tests passed, but live API verification remains unavailable as documented.

Please add regression tests for escaped quotes and nested/embedded tool-shaped JSON before merging.

@mdev34-lab mdev34-lab left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up review

The two findings from my previous pass are fixed in 0953f4f: the JSON string escape state is now correct, and complete non-envelope objects are consumed atomically. The added regression tests cover both. I found two remaining parser-boundary cases that still need attention:

  1. If readJSONObject fails on a malformed outer object, the scanner falls back to advancing one character at a time. It can then parse a valid tool-shaped object nested inside that malformed object and dispatch it. The current malformed-input test has no nested object, so it misses this case.
  2. After a leading <think>...</think> block, arbitrary prose is accepted before a later {...} envelope. That later object is promoted to a tool call even if it is merely an example embedded in the assistant's prose. The scanner also recognizes subsequent <think> markers anywhere after the first one. Require protocol envelopes/markers to occur at the expected top-level boundaries (at minimum, only whitespace between protocol segments); otherwise preserve the remainder as text.

CI on this head: typecheck passed. Linux unit tests timed out at 20 minutes. Windows unit tests failed on an unrelated-looking packages/script subprocess-diagnostics test (genuine git error keeps its stderr...) timing out after 15 seconds; this still leaves CI red and should be rerun on a less-contended runner or explained. Focused Pollinations test results are author-reported, not independently reproduced here.

I would not merge until the two parser cases have regression coverage and CI has a clean run.

segments.push({ type: "text", text: content.slice(cursor, json.end) })
cursor = json.end
continue
}

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still exploitable on malformed outer JSON: when readJSONObject returns undefined, execution reaches the character-by-character fallback below. For example, {"broken": {"name":"finish","arguments":{}} (missing the outer closing brace) fails as a whole, but the scanner advances into the nested object and can decode/dispatch finish. The current malformed test only uses a truncated scalar value, so it does not cover nested braces. On a failed top-level JSON parse, preserve the entire malformed candidate as text or fail closed; do not resume scanning inside it. Add a malformed-outer-with-valid-nested-tool regression test.


const start = cursor
cursor++
while (cursor < content.length && !content.startsWith("<think>", cursor) && content[cursor] !== "{") cursor++

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Protocol boundary is still too permissive: after the first <think>...</think> block, this loop treats any later {...} as a possible envelope, regardless of intervening prose. For example, <think>reason</think>Here is an example: {"name":"finish","arguments":{}} becomes a real finish call even though the object is embedded in ordinary assistant prose. Likewise, subsequent <think> markers are recognized anywhere in the remainder. If the format is concatenated protocol segments, require only permitted separators (normally whitespace) between them; once ordinary prose appears, leave the remainder untouched as text. Add tests for a tool-shaped JSON example and a quoted <think> example after an initial reasoning block.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant