Skip to content

Commit dec76cf

Browse files
author
hzq
committed
Finish Responses turns at the validated terminal event
Release the reader without waiting for the upstream connection or its cleanup acknowledgement. Reconcile visible text with the terminal snapshot and keep partial function arguments out of truncated turns. Improvement-Round: 9/10 after v0.0.73
1 parent dcddee4 commit dec76cf

9 files changed

Lines changed: 912 additions & 103 deletions

File tree

‎docs/models.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ your workspace address if your models accept streamed tool calls.
128128
| `byok`, `timeoutMs`, `anthropicVersion` | Unchanged |
129129
| `anthropicInlineToolChanges` | Anthropic Messages only, off by default. Permit `inline-tools-2026-09-15` for verified tool changes in a native bridge continuation. Not needed just to turn all tools off. See [caller tools](harness.md). |
130130

131+
For an `openai-responses` provider the worker finishes on the first complete, consistent [Responses terminal event](https://developers.openai.com/api/docs/guides/streaming-responses). It does not wait for the HTTP connection to close. An item-level `done`, `[DONE]`, or EOF alone cannot authorize a tool call. An incomplete response with reason `max_output_tokens` preserves partial text and reported usage, never partial tool arguments. Other or unspecified incomplete reasons produce `upstream_incomplete`, not a token-limit claim. Text already streamed must agree with the terminal snapshot. A missing suffix is delivered once; out-of-order parts may wait for the snapshot rather than appearing under the wrong item.
132+
131133
## `oaa models`
132134

133135
```bash

‎docs/zh-CN/models.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,8 @@ oaa connect openai --key-env OPENAI_API_KEY --model <模型名>
113113
| `byok`、`timeoutMs`、`anthropicVersion` | 不变 |
114114
| `anthropicInlineToolChanges` | 仅 Anthropic Messages,默认关闭。允许在原生桥接续接中对已核验的工具变更使用 `inline-tools-2026-09-15`。仅禁用全部工具不需要此选项。见[调用方工具](harness.md)。 |
115115

116+
使用 `openai-responses` 提供方时,worker 收到首个完整且与响应状态一致的 [Responses 终态事件](https://developers.openai.com/api/docs/guides/streaming-responses)就结束本轮,不等 HTTP 连接关闭。单个条目的 `done`、`[DONE]` 或连接断开都不能授权执行工具。若中断原因是 `max_output_tokens`,会保留部分文本与已报告的用量,不执行半截工具调用;其他或未说明的中断原因返回 `upstream_incomplete`,不会误报为 token 用尽。 已经输出的文本必须与终态一致;缺失的后缀只补发一次,乱序到达的文本可留到终态按正确顺序交付。
117+
116118
## `oaa models`
117119

118120
```bash

‎src/providers/http-stream.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ async function* responseChunks(
2828
}
2929
} finally {
3030
signal.removeEventListener('abort', cancel);
31-
await reader.cancel().catch(() => {});
31+
// Cancellation closes this reader immediately. A transport (or another tee branch) can
32+
// acknowledge it much later; that acknowledgement is not part of the model's result.
33+
cancel();
3234
reader.releaseLock();
3335
}
3436
}

‎src/providers/model-wire.ts‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,47 @@
11
import type { Usage } from '../core/contracts.js';
2+
import { Fault } from '../core/util.js';
23

34
/*
4-
* Provider wire shapes as the stream decoders in models.ts read them. Only "is a JSON object" is
5+
* Provider wire shapes as the native stream decoders read them. Only "is a JSON object" is
56
* checked up front (modelObject); each field the decoders rely on is checked where it is read.
67
*/
78
export type Wire = Record<string, unknown>;
89

9-
export type ResponsesEvent = Wire & { response?: { error?: { message?: unknown } }; error?: Wire };
10-
export type ResponsesFinal = { output?: unknown; usage?: Usage; status?: unknown };
10+
export function modelFrame<T extends object = Wire>(data: string): T {
11+
let value: unknown;
12+
try {
13+
value = JSON.parse(data);
14+
} catch {
15+
// Malformed JSON is reported as invalid_model_result below.
16+
}
17+
if (value && typeof value === 'object' && !Array.isArray(value)) return value as T;
18+
throw new Fault('invalid_model_result', 'Provider stream contains an invalid JSON object.', 502);
19+
}
20+
21+
export function modelObject<T extends object = Wire>(value: unknown): T {
22+
if (!value || typeof value !== 'object' || Array.isArray(value))
23+
throw new Fault('invalid_model_result', 'Provider returned a malformed protocol object.', 502);
24+
return value as T;
25+
}
26+
27+
export function tokenCount(value: unknown): number | undefined {
28+
if (value === undefined) return undefined;
29+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
30+
throw new Fault('invalid_model_result', 'Provider returned an invalid token count.', 502);
31+
return value;
32+
}
33+
34+
export function modelUsage(
35+
input: number | undefined,
36+
output: number | undefined,
37+
total?: number,
38+
): Usage | null {
39+
if (input === undefined || output === undefined) return null;
40+
const count = total ?? input + output;
41+
if (!Number.isSafeInteger(count) || count < input + output)
42+
throw new Fault('invalid_model_result', 'Provider returned inconsistent token counts.', 502);
43+
return { input_tokens: input, output_tokens: output, total_tokens: count };
44+
}
1145

1246
type ChatToolDelta = {
1347
index?: unknown;

‎src/providers/models.ts‎

Lines changed: 15 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,9 @@ import type {
1010
ChatChunk,
1111
GeminiCall,
1212
GeminiChunk,
13-
ResponsesEvent,
14-
ResponsesFinal,
15-
Wire,
1613
} from './model-wire.js';
14+
import { modelFrame, modelObject, modelUsage, tokenCount } from './model-wire.js';
15+
import { readResponsesTurn } from './responses-turn.js';
1716
import type { ProviderConfig } from '../config/config.js';
1817
import { validateEndpoint } from '../config/config.js';
1918
import { Fault, checkAbort } from '../core/util.js';
@@ -62,42 +61,6 @@ export interface ModelDriver {
6261
withApiKey?(apiKey: string): ModelDriver;
6362
}
6463

65-
function modelFrame<T extends object = Wire>(data: string): T {
66-
let value: unknown;
67-
try {
68-
value = JSON.parse(data);
69-
} catch {
70-
// Malformed JSON is reported as invalid_model_result below.
71-
}
72-
if (value && typeof value === 'object' && !Array.isArray(value)) return value as T;
73-
throw new Fault('invalid_model_result', 'Provider stream contains an invalid JSON object.', 502);
74-
}
75-
76-
function modelObject<T extends object = Wire>(value: unknown): T {
77-
if (!value || typeof value !== 'object' || Array.isArray(value))
78-
throw new Fault('invalid_model_result', 'Provider returned a malformed protocol object.', 502);
79-
return value as T;
80-
}
81-
82-
function tokenCount(value: unknown): number | undefined {
83-
if (value === undefined) return undefined;
84-
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
85-
throw new Fault('invalid_model_result', 'Provider returned an invalid token count.', 502);
86-
return value;
87-
}
88-
89-
function modelUsage(
90-
input: number | undefined,
91-
output: number | undefined,
92-
total?: number,
93-
): ModelResult['usage'] {
94-
if (input === undefined || output === undefined) return null;
95-
const count = total ?? input + output;
96-
if (!Number.isSafeInteger(count) || count < input + output)
97-
throw new Fault('invalid_model_result', 'Provider returned inconsistent token counts.', 502);
98-
return { input_tokens: input, output_tokens: output, total_tokens: count };
99-
}
100-
10164
// Responses API 里可以原样(或去掉输出专有字段后)作为下一轮输入重放的条目类型。
10265
const REPLAYABLE_RESPONSE_ITEMS = new Set([
10366
'message',
@@ -339,66 +302,19 @@ export class OpenAIModel implements ModelDriver {
339302
signal,
340303
connected,
341304
);
342-
let final: ResponsesFinal | undefined;
343-
for await (const frame of readSseStream(response, signal)) {
344-
if (frame.data === '[DONE]') break;
345-
if (!frame.data) continue;
346-
const event = modelFrame<ResponsesEvent>(frame.data);
347-
if (event.type === 'response.output_text.delta') delta(String(event.delta ?? ''));
348-
else if (event.type === 'response.completed' || event.type === 'response.incomplete')
349-
final = modelObject<ResponsesFinal>(event.response);
350-
else if (event.type === 'response.failed')
351-
throw new Fault(
352-
'upstream_failed',
353-
String(event.response?.error?.message ?? 'Upstream response failed.'),
354-
502,
355-
);
356-
else if (event.type === 'error' || frame.event === 'error')
357-
throw new Fault(
358-
'upstream_failed',
359-
String(event.message ?? event.error?.message ?? 'Upstream stream reported an error.'),
360-
502,
361-
);
362-
}
363-
if (!final)
364-
throw new Fault('upstream_truncated', 'Upstream ended without a terminal response.', 502);
365-
if (!Array.isArray(final.output))
366-
throw new Fault(
367-
'invalid_model_result',
368-
'Provider returned a malformed protocol object.',
369-
502,
370-
);
371-
const output = final.output.map((item) => modelObject(item));
372-
const calls: ToolCall[] = output
373-
.filter((x) => x.type === 'function_call')
374-
.map((c) => ({
375-
id: String(c.call_id),
376-
name: String(c.name),
377-
arguments: parseToolArguments(String(c.name), String(c.arguments ?? '')),
378-
}));
379-
const text = output
380-
.filter((x) => x.type === 'message')
381-
.flatMap((x) => (Array.isArray(x.content) ? x.content : []))
382-
.filter((x) => x?.type === 'output_text')
383-
.map((x) => String(x.text ?? ''))
384-
.join('');
385-
return {
386-
text,
387-
calls,
388-
providerItems: final.output,
389-
providerState: captureProviderState(this.config, agent, prefix(), final.output, {
390-
text,
391-
calls,
392-
}),
393-
usage: final.usage
394-
? {
395-
input_tokens: final.usage.input_tokens,
396-
output_tokens: final.usage.output_tokens,
397-
total_tokens: final.usage.total_tokens,
398-
}
399-
: null,
400-
finish: final.status === 'incomplete' ? 'length' : calls.length ? 'tool_calls' : 'stop',
401-
};
305+
const { items, suffix, ...turn } = await readResponsesTurn(response, signal, delta);
306+
const result = items
307+
? {
308+
...turn,
309+
providerItems: items,
310+
providerState: captureProviderState(this.config, agent, prefix(), items, {
311+
text: turn.text,
312+
calls: turn.calls,
313+
}),
314+
}
315+
: turn;
316+
if (suffix) delta(suffix);
317+
return result;
402318
}
403319
private async callChat(
404320
agent: AgentDefinition,

‎src/providers/responses-text.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import { AGENT_LIMITS } from '../core/limits.js';
2+
import { Fault } from '../core/util.js';
3+
import type { Wire } from './model-wire.js';
4+
5+
const invalid = (message: string) => new Fault('invalid_model_result', message, 502);
6+
const checkLength = (length: number) => {
7+
if (length > AGENT_LIMITS.outputTextChars)
8+
throw new Fault('output_too_large', 'Model output exceeds limit.', 413);
9+
};
10+
const record = (v: unknown): v is Wire => !!v && typeof v === 'object' && !Array.isArray(v);
11+
function partText(p: unknown): string | undefined {
12+
if (!record(p) || typeof p.type !== 'string') return;
13+
return p.type !== 'output_text' ? '' : typeof p.text === 'string' ? p.text : undefined;
14+
}
15+
export function responseMessageText(item: unknown): string | undefined {
16+
if (!record(item) || typeof item.type !== 'string') return;
17+
// An input-shaped record is not assistant text. Native bridge admission checks its authority.
18+
if (item.type !== 'message' || (item.role != null && item.role !== 'assistant')) return '';
19+
if (!Array.isArray(item.content)) return;
20+
const chunks: string[] = [];
21+
for (const part of item.content) {
22+
const projected = partText(part);
23+
if (projected === undefined) return;
24+
if (projected) chunks.push(projected);
25+
}
26+
return chunks.join('');
27+
}
28+
29+
/** The gateway can append public text, not retract it. Stream a known contiguous prefix;
30+
* leave interleaved or missing pieces to the authoritative terminal snapshot. */
31+
export class ResponsesText {
32+
private readonly chunks: string[] = [];
33+
private length = 0;
34+
private item = 0;
35+
private part = 0;
36+
private itemFrom = 0;
37+
private partFrom = 0;
38+
private mode?: 'indexed' | 'flat';
39+
private held = false;
40+
private sawText = false;
41+
constructor(private readonly emit: (s: string) => void) {}
42+
private matches(text: string | undefined, from: number, exact: boolean) {
43+
if (text === undefined) return false;
44+
let offset = 0;
45+
for (let i = from; i < this.chunks.length; i++) {
46+
const chunk = this.chunks[i]!;
47+
if (!text.startsWith(chunk, offset)) return false;
48+
offset += chunk.length;
49+
}
50+
return !exact || offset === text.length;
51+
}
52+
observe(e: Wire) {
53+
if (e.type === 'response.output_text.delta') {
54+
if (typeof e.delta !== 'string')
55+
throw invalid('Responses output_text delta must be a string.');
56+
if (!e.delta) return;
57+
this.sawText = true;
58+
if (this.held) return;
59+
const mode =
60+
e.output_index === undefined && e.content_index === undefined ? 'flat' : 'indexed';
61+
if (
62+
(this.mode && this.mode !== mode) ||
63+
(mode === 'indexed' &&
64+
((e.output_index ?? 0) !== this.item || (e.content_index ?? 0) !== this.part))
65+
) {
66+
this.held = true;
67+
return;
68+
}
69+
this.mode = mode;
70+
this.length += e.delta.length;
71+
checkLength(this.length);
72+
this.chunks.push(e.delta);
73+
this.emit(e.delta);
74+
return;
75+
}
76+
if (this.held || this.mode === 'flat' || e.output_index !== this.item) return;
77+
// Item/part completion only establishes ordering for subsequent deltas, never tool authority.
78+
if (e.type === 'response.output_item.done' && e.item) {
79+
if (!this.matches(responseMessageText(e.item), this.itemFrom, true)) {
80+
this.held = true;
81+
return;
82+
}
83+
this.item++;
84+
this.part = 0;
85+
this.itemFrom = this.partFrom = this.chunks.length;
86+
} else if (e.type === 'response.content_part.done' && e.content_index === this.part && e.part) {
87+
if (!this.matches(partText(e.part), this.partFrom, true)) {
88+
this.held = true;
89+
return;
90+
}
91+
this.part++;
92+
this.partFrom = this.chunks.length;
93+
}
94+
}
95+
finish(text: string, truncated: boolean): { text: string; suffix?: string } {
96+
if (!this.sawText) return { text };
97+
checkLength(text.length);
98+
if (this.matches(text, 0, false))
99+
return text.length > this.length ? { text, suffix: text.slice(this.length) } : { text };
100+
if (truncated && text.length < this.length) {
101+
const seen = this.chunks.join('');
102+
if (seen.startsWith(text)) return { text: seen };
103+
}
104+
throw invalid('Responses terminal text conflicts with text already streamed.');
105+
}
106+
}

0 commit comments

Comments
 (0)