Repository Public
1import AstraCore2import Foundation3import Testing4@testable import AstraProviders56// Reasoning replay in tool cycles. What a provider wants to see again with a tool-calling turn rides on7// `ToolCall.providerState`: emitted on `.toolCallCompleted`, stored by the app, encoded back into the next request.8// The stream shapes below are the ones captured live on 2026-11-21 / 2026-11-22, shortened.910private func sse(_ chunks: [String]) -> FixtureTransport.Reply {11 FixtureTransport.Reply(headers: ["Content-Type": "text/event-stream"], body: chunks.map { "data: \($0)\n\n" }.joined())12}1314private func state(_ format: String, _ payload: JSONValue) -> JSONValue { ["format": .string(format), "payload": payload] }1516/// The second leg of a tool cycle, built the way the app builds it: the completed calls go back unchanged.17private func secondLeg(_ adapter: Adapter, model: String? = nil, text: String = "", calls: [ToolCall], reasoning: ReasoningEffort? = .medium) -> GenerationRequest {18 GenerationRequest(model: ModelRef(provider: adapter.kind, modelID: model ?? adapter.model, endpointID: adapter == .custom ? "ep1" : nil),19 messages: [.user("What is the weather in Paris?"), .assistant(text, toolCalls: calls)] + calls.map { .tool("18 C, cloudy", callID: $0.id, name: $0.name) },20 parameters: GenerationParameters(reasoning: reasoning), tools: [weatherTool])21}2223private func completedCalls(_ c: Collected) -> [ToolCall] { c.outcome.toolCalls }2425private struct ChatCase: Sendable, CustomTestStringConvertible {26 var adapter: Adapter27 var stream: [String]28 var expected: JSONValue29 /// The assistant message of the next request must contain this.30 var check: @Sendable (JSONValue) -> Bool31 var testDescription: String { adapter.rawValue }3233 static let toolCall = #"{"index":0,"id":"call_1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"}}"#34 static let end = #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":9,"completion_tokens":20}}"#3536 static let all: [ChatCase] = [37 ChatCase(adapter: .mistral, stream: [38 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":[{"type":"thinking","thinking":[{"type":"text","text":"The user wants"}],"closed":true}]},"finish_reason":null}]}"#,39 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"content":[{"type":"thinking","thinking":[{"type":"text","text":" the weather in Paris."}],"closed":true}]},"finish_reason":null}]}"#,40 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[\#(toolCall)]},"finish_reason":null}]}"#, end, "[DONE]"],41 expected: state("mistral.thinking", "The user wants the weather in Paris.")) { message in42 message["content"] == [["type": "thinking", "thinking": [["type": "text", "text": "The user wants the weather in Paris."]]]]43 },44 ChatCase(adapter: .deepSeek, stream: [45 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":null,"reasoning_content":""},"finish_reason":null}],"usage":null}"#,46 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"content":null,"reasoning_content":"Need the tool"},"finish_reason":null}],"usage":null}"#,47 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"content":null,"reasoning_content":" for Paris."},"finish_reason":null}],"usage":null}"#,48 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[\#(toolCall)]},"finish_reason":null}],"usage":null}"#, end, "[DONE]"],49 expected: state("deepseek.reasoning_content", "Need the tool for Paris.")) { $0["reasoning_content"] == "Need the tool for Paris." },50 ChatCase(adapter: .moonshot, stream: [51 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}"#,52 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"reasoning_content":"The user wants"},"finish_reason":null}]}"#,53 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"reasoning_content":" Paris weather."},"finish_reason":null}]}"#,54 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[\#(toolCall)]},"finish_reason":null}]}"#,55 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls","usage":{"prompt_tokens":9,"completion_tokens":20}}]}"#, "[DONE]"],56 expected: state("moonshot.reasoning_content", "The user wants Paris weather.")) { $0["reasoning_content"] == "The user wants Paris weather." },57 ChatCase(adapter: .cerebras, stream: [58 #"{"id":"r1","choices":[{"delta":{"role":"assistant"},"index":0}],"model":"m"}"#,59 #"{"id":"r1","choices":[{"delta":{"reasoning":"Call get_weather"},"index":0}],"model":"m"}"#,60 #"{"id":"r1","choices":[{"delta":{"reasoning":" with Paris."},"index":0}],"model":"m"}"#,61 #"{"id":"r1","choices":[{"delta":{"tool_calls":[\#(toolCall)]},"index":0}],"model":"m"}"#, end, "[DONE]"],62 expected: state("cerebras.reasoning", "Call get_weather with Paris.")) { $0["reasoning"] == "Call get_weather with Paris." && $0["reasoning_content"] == nil },63 // OpenRouter: summary chunks of one entry are joined; an encrypted entry and a signed text entry stay separate, in order.64 ChatCase(adapter: .openRouter, stream: [65 #"{"id":"r1","model":"m","provider":"OpenAI","choices":[{"index":0,"delta":{"role":"assistant","content":"","reasoning":"**Plan**","reasoning_details":[{"type":"reasoning.summary","summary":"**Plan**","format":"openai-responses-v1","index":0}]},"finish_reason":null}]}"#,66 #"{"id":"r1","model":"m","provider":"OpenAI","choices":[{"index":0,"delta":{"reasoning":" call it","reasoning_details":[{"type":"reasoning.summary","summary":" call it","format":"openai-responses-v1","index":0}]},"finish_reason":null}]}"#,67 #"{"id":"r1","model":"m","provider":"OpenAI","choices":[{"index":0,"delta":{"reasoning_details":[{"type":"reasoning.encrypted","data":"CIPHERTEXT_A","id":"rs_1","format":"openai-responses-v1","index":1}]},"finish_reason":null}]}"#,68 #"{"id":"r1","model":"m","provider":"OpenAI","choices":[{"index":0,"delta":{"reasoning_details":[{"type":"reasoning.text","text":"Signed","signature":null,"format":"anthropic-claude-v1","index":2}]},"finish_reason":null}]}"#,69 #"{"id":"r1","model":"m","provider":"OpenAI","choices":[{"index":0,"delta":{"reasoning_details":[{"type":"reasoning.text","text":" thought","signature":"SIG_B","format":"anthropic-claude-v1","index":2}]},"finish_reason":null}]}"#,70 #"{"id":"r1","model":"m","provider":"OpenAI","choices":[{"index":0,"delta":{"tool_calls":[\#(toolCall)]},"finish_reason":null}]}"#, end, "[DONE]"],71 expected: state("openrouter.reasoning_details", [72 ["type": "reasoning.summary", "summary": "**Plan** call it", "format": "openai-responses-v1", "index": 0],73 ["type": "reasoning.encrypted", "data": "CIPHERTEXT_A", "id": "rs_1", "format": "openai-responses-v1", "index": 1],74 ["type": "reasoning.text", "text": "Signed thought", "signature": "SIG_B", "format": "anthropic-claude-v1", "index": 2]])) { message in75 message["reasoning_details"]?.arrayValue?.count == 3 && message["reasoning_details"]?[1]?["data"] == "CIPHERTEXT_A" && message["reasoning_details"]?[2]?["signature"] == "SIG_B"76 },77 ]78}7980@Suite("Reasoning replay in tool cycles")81struct ReasoningReplayTests {82 // MARK: Chat Completions dialects8384 @Test(arguments: ChatCase.all)85 fileprivate func chatDialectEmitsStateAndSendsItBack(c: ChatCase) async throws {86 let first = await collect(c.adapter.make(FixtureTransport(sse(c.stream))).stream(request(c.adapter.kind, c.adapter.model, tools: [weatherTool])))87 expectWellFormed(first)88 let calls = completedCalls(first)89 #expect(calls == [ToolCall(id: "call_1", name: "get_weather", arguments: ["city": "Paris"], providerState: c.expected)])90 #expect(!first.reasoning.isEmpty) // the reasoning was also shown as it streamed9192 // The app stores the calls and reads them back: the state survives that.93 let stored = try JSONDecoder().decode([ToolCall].self, from: JSONEncoder().encode(calls))94 let transport = FixtureTransport(.sse(c.adapter.textFixture))95 let second = await collect(c.adapter.make(transport).stream(secondLeg(c.adapter, calls: stored)))96 expectWellFormed(second)97 let assistant = try #require(transport.body()["messages"]?[1])98 #expect(assistant["role"] == "assistant")99 #expect(c.check(assistant), "\(assistant.serialized().prefix(300))")100 #expect(assistant["tool_calls"]?[0]?["id"] == "call_1")101 // The state itself is not a wire field, and nothing of it is in the URL or the headers.102 let raw = String(decoding: transport.requests[0].httpBody ?? Data(), as: UTF8.self)103 #expect(!raw.contains("providerState") && !raw.contains(#""format":"\#(c.expected["format"]?.stringValue ?? "")""#))104 }105106 @Test func turnStateRidesOnTheFirstCallOnly() async {107 let stream = [#"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"Two cities."},"finish_reason":null}]}"#,108 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"a","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"}},{"index":1,"id":"b","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Rome\"}"}}]},"finish_reason":"tool_calls"}]}"#, "[DONE]"]109 let c = await collect(Adapter.deepSeek.make(FixtureTransport(sse(stream))).stream(request(.deepSeek, "deepseek-flash", tools: [weatherTool])))110 #expect(c.outcome.toolCalls.map(\.providerState) == [state("deepseek.reasoning_content", "Two cities."), nil])111 // Either call of the turn brings the state back, whatever order the app kept them in.112 let transport = FixtureTransport(.sse("deepseek_text.sse"))113 _ = await collect(Adapter.deepSeek.make(transport).stream(secondLeg(.deepSeek, calls: c.outcome.toolCalls.reversed())))114 #expect(transport.body()["messages"]?[1]?["reasoning_content"] == "Two cities.")115 }116117 @Test func mistralReplaysThinkingAheadOfTheTurnText() async {118 let call = ToolCall(id: "UbtVXGGSM", name: "get_weather", arguments: ["city": "Paris"], providerState: state("mistral.thinking", "Check the tool."))119 let transport = FixtureTransport(.sse("mistral_text.sse"))120 _ = await collect(Adapter.mistral.make(transport).stream(secondLeg(.mistral, model: "mistral-small-latest", text: "Let me check.", calls: [call], reasoning: .high)))121 #expect(transport.body()["messages"]?[1]?["content"] == [["type": "thinking", "thinking": [["type": "text", "text": "Check the tool."]]], ["type": "text", "text": "Let me check."]])122 #expect(transport.body()["reasoning_effort"] == "high")123 }124125 @Test func deepSeekFallsBackToTheEmptyStringWithoutState() async {126 let transport = FixtureTransport(.sse("deepseek_text.sse"))127 let old = ToolCall(id: "call_1", name: "get_weather", arguments: ["city": "Paris"])128 let fresh = ToolCall(id: "call_2", name: "get_weather", arguments: ["city": "Rome"], providerState: state("deepseek.reasoning_content", "Rome next."))129 let messages: [PromptMessage] = [.user("Paris?"), .assistant("", toolCalls: [old]), .tool("18 C", callID: "call_1", name: "get_weather"), .assistant("18 C in Paris."),130 .user("Rome?"), .assistant("", toolCalls: [fresh]), .tool("24 C", callID: "call_2", name: "get_weather")]131 _ = await collect(Adapter.deepSeek.make(transport).stream(GenerationRequest(model: ModelRef(provider: .deepSeek, modelID: "deepseek-flash"), messages: messages, tools: [weatherTool])))132 let wire = transport.body()["messages"]?.arrayValue ?? []133 #expect(wire.filter { $0["role"] == "assistant" }.map { $0["reasoning_content"]?.stringValue } == ["", "", "Rome next."])134 }135136 // MARK: Anthropic137138 @Test func anthropicKeepsSignedThinkingBlocksAndSendsThemBack() async throws {139 let first = await collect(Adapter.anthropic.make(FixtureTransport(.sse("anthropic_thinking_tool.sse"))).stream(request(.anthropic, "claude-haiku-5-5", tools: [weatherTool])))140 expectWellFormed(first)141 let call = try #require(first.outcome.toolCalls.first)142 let blocks = try #require(call.providerState?["payload"]?.arrayValue)143 #expect(call.providerState?["format"] == "anthropic.thinking")144 #expect(blocks.count == 1)145 #expect(blocks[0]["type"] == "thinking")146 #expect(blocks[0]["signature"]?.stringValue?.hasPrefix("SIGNATURE_PLACEHOLDER") == true)147 #expect(blocks[0]["thinking"]?.stringValue == first.reasoning) // the block's text is exactly what streamed148149 let transport = FixtureTransport(.sse("anthropic_text.sse"))150 _ = await collect(Adapter.anthropic.make(transport).stream(secondLeg(.anthropic, model: "claude-haiku-5-5", text: first.text, calls: first.outcome.toolCalls)))151 let content = try #require(transport.body()["messages"]?[1]?["content"]?.arrayValue)152 #expect(content.first == blocks[0]) // verbatim, ahead of everything else in the turn153 #expect(content.last?["type"] == "tool_use")154 #expect(content.count == (first.text.isEmpty ? 2 : 3))155 // A block that no longer matches its conversation is dropped by the API instead of failing the request.156 #expect(transport.body()["thinking"]?["block_binding"] == ["prefix_mismatch_behavior": "drop_block"])157 #expect(transport.requests[0].value(forHTTPHeaderField: "anthropic-beta") == "thinking-binding-controls-2026-08-01")158 }159160 @Test func anthropicReplaysOnlyTheToolCycleInProgress() {161 let block: JSONValue = ["type": "thinking", "thinking": "t", "signature": "SIG"]162 let redacted: JSONValue = ["type": "redacted_thinking", "data": "opaque"]163 func call(_ id: String, _ blocks: [JSONValue]) -> ToolCall { ToolCall(id: id, name: "get_weather", arguments: ["city": "Paris"], providerState: state("anthropic.thinking", .array(blocks))) }164 let messages: [PromptMessage] = [165 .user("Paris?"), .assistant("", toolCalls: [call("toolu_1", [block])]), .tool("18 C", callID: "toolu_1", name: "get_weather"), .assistant("18 C."),166 .user("Rome and Oslo?"), .assistant("Checking.", toolCalls: [call("toolu_2", [block, redacted]), call("toolu_3", [block])]),167 .tool("24 C", callID: "toolu_2", name: "get_weather"), .tool("3 C", callID: "toolu_3", name: "get_weather"),168 ]169 let wire = AnthropicProvider.messages(messages)170 // The finished cycle goes back without thinking: its answer turn has no call to carry blocks, and a gap in the middle is refused.171 #expect(wire[1]["content"]?.arrayValue?.map { $0["type"]?.stringValue } == ["tool_use"])172 // The cycle in progress: thinking, text, tool_use, then the interleaved thinking of the second call.173 #expect(wire[5]["content"]?.arrayValue?.map { $0["type"]?.stringValue } == ["thinking", "redacted_thinking", "text", "tool_use", "thinking", "tool_use"])174 #expect(wire[5]["content"]?[1] == redacted)175 }176177 @Test func anthropicRecoversWhenTheAPIRefusesAReplayedBlock() async {178 let block: JSONValue = ["type": "thinking", "thinking": "t", "signature": "SIG"]179 let call = ToolCall(id: "toolu_1", name: "get_weather", arguments: ["city": "Paris"], providerState: state("anthropic.thinking", [block]))180 let refused = FixtureTransport.Reply.json(400, #"{"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation. Remove the block, or set `thinking.block_binding.prefix_mismatch_behavior` to \"drop_block\"."},"request_id":"req_1"}"#)181 var transport = FixtureTransport(refused, .sse("anthropic_text.sse"))182 var c = await collect(Adapter.anthropic.make(transport).stream(secondLeg(.anthropic, model: "claude-haiku-5-5", calls: [call])))183 expectWellFormed(c)184 #expect(transport.requests.count == 2)185 #expect(transport.body(1)["messages"]?[1]?["content"]?.arrayValue?.map { $0["type"]?.stringValue } == ["tool_use"])186 #expect(transport.body(1)["thinking"]?["block_binding"] == nil)187 #expect(transport.body(1)["thinking"]?["type"] == "adaptive") // thinking itself stays on188 #expect(transport.requests[1].value(forHTTPHeaderField: "anthropic-beta") == nil)189190 // A model or platform without the binding control: the control goes, the blocks stay.191 let noControl = FixtureTransport.Reply.json(400, #"{"type":"error","error":{"type":"invalid_request_error","message":"thinking.block_binding: Extra inputs are not permitted"},"request_id":"req_2"}"#)192 transport = FixtureTransport(noControl, .sse("anthropic_text.sse"))193 c = await collect(Adapter.anthropic.make(transport).stream(secondLeg(.anthropic, model: "claude-haiku-5-5", calls: [call])))194 expectWellFormed(c)195 #expect(transport.body(1)["thinking"]?["block_binding"] == nil)196 #expect(transport.body(1)["messages"]?[1]?["content"]?[0] == block)197 #expect(transport.requests[1].value(forHTTPHeaderField: "anthropic-beta") == nil)198199 // Budget-based thinking (Haiku 4.5) does not take the control at all: blocks are replayed without it.200 transport = FixtureTransport(.sse("anthropic_text.sse"))201 _ = await collect(Adapter.anthropic.make(transport).stream(secondLeg(.anthropic, model: "claude-haiku-4-5", calls: [call], reasoning: .low)))202 #expect(transport.body()["thinking"]?["type"] == "enabled")203 #expect(transport.body()["thinking"]?["block_binding"] == nil)204 #expect(transport.body()["messages"]?[1]?["content"]?[0] == block)205 #expect(transport.requests[0].value(forHTTPHeaderField: "anthropic-beta") == nil)206 }207208 // MARK: Gemini209210 @Test func geminiSignatureSurvivesARestart() throws {211 var decoder = GeminiStreamDecoder(modelID: "gemini-3.1-flash-lite", signatures: ThoughtSignatureStore())212 var events: [StreamEvent] = []213 var parser = SSEParser()214 for line in Fixtures.text("gemini_tool_parallel.sse").components(separatedBy: "\n") {215 if let event = parser.feed(line) { events += try decoder.consume(event.data) }216 }217 let calls = events.compactMap { event -> ToolCall? in if case .toolCallCompleted(let c) = event { return c }; return nil }218 #expect(calls.count == 2)219 // Per call: only the first call of the turn came with a signature.220 #expect(calls[0].providerState?["format"] == "gemini.thoughtSignature")221 let signature = try #require(calls[0].providerState?["payload"]?.stringValue)222 #expect(signature.hasPrefix("SIGNATURE_PLACEHOLDER"))223 #expect(calls[1].providerState == nil)224225 // A new process: the in-memory store is empty, the stored calls are all there is.226 let stored = try JSONDecoder().decode([ToolCall].self, from: JSONEncoder().encode(calls))227 let history: [PromptMessage] = [.user("Paris and Rome?"), .assistant("", toolCalls: stored)] + stored.map { .tool("18 C", callID: $0.id, name: $0.name) }228 let parts = GeminiProvider.contents(history, signatures: ThoughtSignatureStore())[1]["parts"]?.arrayValue ?? []229 #expect(parts[0]["thoughtSignature"] == .string(signature))230 #expect(parts[1]["thoughtSignature"] == nil)231232 // Fallbacks for a call without state: the in-memory copy, then the documented placeholder.233 let bare = stored.map { ToolCall(id: $0.id, name: $0.name, arguments: $0.arguments) }234 let memory = ThoughtSignatureStore()235 memory.store("FROM_MEMORY", for: bare[0].id)236 let bareHistory: [PromptMessage] = [.user("Paris and Rome?"), .assistant("", toolCalls: bare)]237 #expect(GeminiProvider.contents(bareHistory, signatures: memory)[1]["parts"]?[0]?["thoughtSignature"] == "FROM_MEMORY")238 #expect(GeminiProvider.contents(bareHistory, signatures: ThoughtSignatureStore())[1]["parts"]?[0]?["thoughtSignature"] == .string(GeminiProvider.signaturePlaceholder))239 }240241 // MARK: Responses API (OpenAI, xAI)242243 static let responsesEvents: [(String, String)] = [244 ("response.created", #"{"type":"response.created","response":{"id":"resp_1","model":"m"}}"#),245 ("response.output_item.added", #"{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[],"content":[],"encrypted_content":"ENCRYPTED_REASONING_PLACEHOLDER"}}"#),246 ("response.output_item.done", #"{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"Odd, so Paris."}],"content":[],"encrypted_content":"ENCRYPTED_REASONING_PLACEHOLDER","status":"completed"}}"#),247 ("response.output_item.added", #"{"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get_weather","arguments":""}}"#),248 ("response.function_call_arguments.delta", #"{"type":"response.function_call_arguments.delta","item_id":"fc_1","delta":"{\"city\":\"Paris\"}"}"#),249 ("response.output_item.done", #"{"type":"response.output_item.done","output_index":1,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get_weather","arguments":"{\"city\":\"Paris\"}"}}"#),250 ("response.completed", #"{"type":"response.completed","response":{"id":"resp_1","model":"m","usage":{"input_tokens":9,"output_tokens":30,"output_tokens_details":{"reasoning_tokens":19}}}}"#),251 ]252253 @Test(arguments: [Adapter.openAI, .xAI])254 func responsesKeepEncryptedReasoningAndSendItBack(adapter: Adapter) async throws {255 let body = Self.responsesEvents.map { "event: \($0.0)\ndata: \($0.1)\n\n" }.joined()256 let first = await collect(adapter.make(FixtureTransport(.init(headers: ["Content-Type": "text/event-stream"], body: body))).stream(request(adapter.kind, adapter.model, tools: [weatherTool])))257 expectWellFormed(first)258 let format = adapter == .openAI ? "openai.reasoning" : "xai.reasoning"259 let item: JSONValue = ["type": "reasoning", "id": "rs_1", "summary": [["type": "summary_text", "text": "Odd, so Paris."]], "encrypted_content": "ENCRYPTED_REASONING_PLACEHOLDER"]260 #expect(first.outcome.toolCalls == [ToolCall(id: "call_1", name: "get_weather", arguments: ["city": "Paris"], providerState: state(format, [item]))])261 #expect(!first.reasoning.contains("ENCRYPTED"))262263 let transport = FixtureTransport(.sse(adapter.textFixture))264 _ = await collect(adapter.make(transport).stream(secondLeg(adapter, text: "Checking.", calls: first.outcome.toolCalls)))265 let input = try #require(transport.body()["input"]?.arrayValue)266 // The turn's output order: reasoning, message, function call; then the tool output.267 #expect(input.dropFirst().map { $0["type"]?.stringValue ?? $0["role"]?.stringValue } == ["reasoning", "assistant", "function_call", "function_call_output"])268 #expect(input[1] == item)269 #expect(transport.body()["store"] == false)270 #expect(transport.body()["include"] == nil) // nothing extra is requested: the ciphertext comes by default when nothing is stored271272 // Ciphertext never crosses providers: the other Responses provider ignores this state.273 let other: Adapter = adapter == .openAI ? .xAI : .openAI274 let foreign = FixtureTransport(.sse(other.textFixture))275 _ = await collect(other.make(foreign).stream(secondLeg(other, calls: first.outcome.toolCalls)))276 #expect((foreign.body()["input"]?.arrayValue ?? []).allSatisfy { $0["type"] != "reasoning" })277 }278279 @Test func responsesDropReplayedReasoningTheProviderRefuses() async {280 let item: JSONValue = ["type": "reasoning", "id": "rs_1", "summary": [], "encrypted_content": "CIPHERTEXT"]281 let call = ToolCall(id: "call_1", name: "get_weather", arguments: ["city": "Paris"], providerState: state("openai.reasoning", [item]))282 let refused = FixtureTransport.Reply.json(400, #"{"error":{"message":"The encrypted content for item rs_1 could not be verified.","type":"invalid_request_error","param":"input","code":"invalid_encrypted_content"}}"#)283 let transport = FixtureTransport(refused, .sse("openai_text.sse"))284 let c = await collect(Adapter.openAI.make(transport).stream(secondLeg(.openAI, calls: [call])))285 expectWellFormed(c)286 #expect(transport.requests.count == 2)287 #expect((transport.body(1)["input"]?.arrayValue ?? []).map { $0["type"]?.stringValue ?? $0["role"]?.stringValue } == ["user", "function_call", "function_call_output"])288 }289290 @Test func reasoningWithoutCiphertextIsNotKept() throws {291 // A reasoning item that carries no encrypted content cannot be replayed when nothing is stored: no state.292 var decoder = ResponsesStreamDecoder(modelID: "m", stateFormat: "xai.reasoning")293 var events: [StreamEvent] = []294 for (name, data) in Self.responsesEvents { events += try decoder.consume(SSEEvent(event: name, data: data.replacingOccurrences(of: #","encrypted_content":"ENCRYPTED_REASONING_PLACEHOLDER""#, with: ""))) }295 #expect(events.contains(.toolCallCompleted(ToolCall(id: "call_1", name: "get_weather", arguments: ["city": "Paris"]))))296 }297298 // MARK: Every adapter299300 @Test(arguments: Adapter.allCases)301 func callsWithoutStateStillEncodeAValidRequest(adapter: Adapter) async throws {302 // A conversation stored by a build that had no provider state: plain tool calls, a full cycle, reasoning on.303 let transport = FixtureTransport(.sse(adapter.textFixture))304 let calls = [ToolCall(id: "call_abc123", name: "get_weather", arguments: ["city": "Paris"])]305 let c = await collect(adapter.make(transport).stream(secondLeg(adapter, text: "Let me check.", calls: calls)))306 expectWellFormed(c)307 #expect(transport.requests.count == 1)308 let raw = String(decoding: transport.requests[0].httpBody ?? Data(), as: UTF8.self)309 #expect(JSONValue.parse(raw) != nil)310 for marker in [#""type":"thinking""#, #""type":"redacted_thinking""#, #""type":"reasoning""#, "reasoning_details", "block_binding", "providerState"] {311 #expect(!raw.contains(marker), "\(adapter.rawValue) sent \(marker) for a call without state")312 }313 #expect(raw.contains("call_abc123") || adapter == .google) // Gemini keys the call by name when the id is not its own314 #expect(raw.contains("get_weather"))315 #expect(transport.requests[0].value(forHTTPHeaderField: "anthropic-beta") == nil)316 }317318 @Test(arguments: Adapter.allCases)319 func stateFromAnotherProviderIsIgnored(adapter: Adapter) async {320 // The user switched models in the middle of a conversation: every other provider's state must be inert.321 let foreign: [JSONValue] = [state("mistral.thinking", "FOREIGN_THINKING"), state("deepseek.reasoning_content", "FOREIGN_REASONING"), state("anthropic.thinking", [["type": "thinking", "thinking": "FOREIGN_BLOCK", "signature": "FOREIGN_SIG"]]),322 state("openai.reasoning", [["type": "reasoning", "id": "rs_x", "summary": [], "encrypted_content": "FOREIGN_CIPHER"]]), state("gemini.thoughtSignature", "FOREIGN_SIGNATURE"),323 state("openrouter.reasoning_details", [["type": "reasoning.encrypted", "data": "FOREIGN_DETAILS"]]), ["unexpected": true], "not an object"]324 let own = ["mistral": "mistral.", "deepSeek": "deepseek.", "anthropic": "anthropic.", "openAI": "openai.", "google": "gemini.", "openRouter": "openrouter."][adapter.rawValue]325 for value in foreign where !(own.map { value["format"]?.stringValue?.hasPrefix($0) ?? false } ?? false) {326 let transport = FixtureTransport(.sse(adapter.textFixture))327 let call = ToolCall(id: "call_abc123", name: "get_weather", arguments: ["city": "Paris"], providerState: value)328 let c = await collect(adapter.make(transport).stream(secondLeg(adapter, calls: [call])))329 expectWellFormed(c)330 #expect(!String(decoding: transport.requests[0].httpBody ?? Data(), as: UTF8.self).contains("FOREIGN"))331 }332 }333334 // MARK: Bounds and privacy335336 @Test func oversizedStateIsDropped() async {337 #expect(ProviderState.make("x", .string(String(repeating: "a", count: 300_000))) == nil)338 #expect(ProviderState.make("x", .string(String(repeating: "a", count: 200_000))) != nil)339 #expect(ProviderState.make("x", "") == nil)340 #expect(ProviderState.make("x", []) == nil)341 // A provider that streams an enormous reasoning trace: the call still completes, without state, and the next342 // request takes the same path as a call that never had any.343 let huge = String(repeating: "x", count: 30_000)344 let chunks = [#"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}"#]345 + (0..<10).map { _ in #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"reasoning_content":"\#(huge)"},"finish_reason":null}]}"# }346 + [#"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[\#(ChatCase.toolCall)]},"finish_reason":"tool_calls"}]}"#, "[DONE]"]347 let c = await collect(Adapter.deepSeek.make(FixtureTransport(sse(chunks))).stream(request(.deepSeek, "deepseek-flash", tools: [weatherTool])))348 expectWellFormed(c)349 #expect(c.outcome.toolCalls == [ToolCall(id: "call_1", name: "get_weather", arguments: ["city": "Paris"])])350 #expect(c.reasoning.count == 300_000) // what the user saw is not truncated; only the replay copy is dropped351 let transport = FixtureTransport(.sse("deepseek_text.sse"))352 _ = await collect(Adapter.deepSeek.make(transport).stream(secondLeg(.deepSeek, calls: c.outcome.toolCalls)))353 #expect(transport.body()["messages"]?[1]?["reasoning_content"] == "")354 }355356 @Test(arguments: [Adapter.anthropic, .openAI, .deepSeek, .mistral, .openRouter])357 func stateNeverReachesErrorsOrDiagnostics(adapter: Adapter) async {358 let secret = "REPLAY-STATE-7731"359 let formats: [Adapter: JSONValue] = [.anthropic: state("anthropic.thinking", [["type": "thinking", "thinking": .string(secret), "signature": .string(secret)]]),360 .openAI: state("openai.reasoning", [["type": "reasoning", "id": "rs_1", "summary": [], "encrypted_content": .string(secret)]]),361 .deepSeek: state("deepseek.reasoning_content", .string(secret)), .mistral: state("mistral.thinking", .string(secret)),362 .openRouter: state("openrouter.reasoning_details", [["type": "reasoning.encrypted", "data": .string(secret)]])]363 let call = ToolCall(id: "call_1", name: "get_weather", arguments: ["city": "Paris"], providerState: formats[adapter])364 let diagnostics = RecordingDiagnostics()365 var seen: [String] = []366 for status in [400, 401, 429, 500] {367 let transport = FixtureTransport(.json(status, adapter.errorBody(type: "error", message: "Something failed.")))368 let c = await collect(adapter.make(transport, diagnostics: diagnostics).stream(secondLeg(adapter, calls: [call])))369 #expect(c.error != nil)370 #expect(String(decoding: transport.requests[0].httpBody ?? Data(), as: UTF8.self).contains(secret)) // it was sent to the provider...371 #expect(transport.requests[0].url?.absoluteString.contains(secret) == false)372 #expect((transport.requests[0].allHTTPHeaderFields ?? [:]).values.allSatisfy { !$0.contains(secret) })373 seen += [c.error?.message ?? "", c.error?.title ?? "", String(describing: c.error)]374 }375 seen += diagnostics.records.map { String(describing: $0) }376 for text in seen { #expect(!text.contains(secret)) } // ...and nowhere else377 }378}379