@robota-sdk/agent-provider-openai 3.0.0-beta.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +417 -0
- package/LICENSE +661 -0
- package/README.md +198 -0
- package/dist/node/index.cjs +3 -0
- package/dist/node/index.d.cts +332 -0
- package/dist/node/index.d.cts.map +1 -0
- package/dist/node/index.d.ts +332 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node/index.js +4 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/loggers/index.cjs +1 -0
- package/dist/node/loggers/index.d.cts +94 -0
- package/dist/node/loggers/index.d.cts.map +1 -0
- package/dist/node/loggers/index.d.ts +94 -0
- package/dist/node/loggers/index.d.ts.map +1 -0
- package/dist/node/loggers/index.js +2 -0
- package/dist/node/loggers/index.js.map +1 -0
- package/dist/node/payload-logger-n89AQdUn.d.cts +63 -0
- package/dist/node/payload-logger-n89AQdUn.d.cts.map +1 -0
- package/dist/node/payload-logger-n89AQdUn.d.ts +63 -0
- package/dist/node/payload-logger-n89AQdUn.d.ts.map +1 -0
- package/dist/node/rolldown-runtime-CMqjfN_6.cjs +1 -0
- package/package.json +104 -0
- package/src/index.ts +1 -0
- package/src/openai/__tests__/abort-signal-wire.test.ts +210 -0
- package/src/openai/__tests__/durable-operation-wire.test.ts +38 -0
- package/src/openai/__tests__/endpoint-provenance.test.ts +44 -0
- package/src/openai/__tests__/extra-body.test.ts +507 -0
- package/src/openai/__tests__/mixed-tool-content.test.ts +103 -0
- package/src/openai/__tests__/parallel-tool-policy.test.ts +398 -0
- package/src/openai/__tests__/provider-errors.test.ts +143 -0
- package/src/openai/__tests__/request-format.test.ts +59 -0
- package/src/openai/__tests__/strict-tools-closure.test.ts +183 -0
- package/src/openai/__tests__/tool-schema-projection.test.ts +316 -0
- package/src/openai/__tests__/trace-context-wire.test.ts +114 -0
- package/src/openai/adapter.test.ts +494 -0
- package/src/openai/adapter.ts +145 -0
- package/src/openai/chat-completions-chat.ts +232 -0
- package/src/openai/executor-integration.test.ts +213 -0
- package/src/openai/extra-body.ts +120 -0
- package/src/openai/index.ts +19 -0
- package/src/openai/interfaces/payload-logger.ts +50 -0
- package/src/openai/loggers/console-payload-logger.test.ts +173 -0
- package/src/openai/loggers/console-payload-logger.ts +96 -0
- package/src/openai/loggers/console.ts +9 -0
- package/src/openai/loggers/file-payload-logger.test.ts +243 -0
- package/src/openai/loggers/file-payload-logger.ts +125 -0
- package/src/openai/loggers/file.ts +9 -0
- package/src/openai/loggers/index.ts +12 -0
- package/src/openai/loggers/sanitize-openai-log-data.test.ts +89 -0
- package/src/openai/loggers/sanitize-openai-log-data.ts +14 -0
- package/src/openai/message-converter.ts +27 -0
- package/src/openai/model-effort-table.ts +19 -0
- package/src/openai/model-effort-verification-config.test.ts +45 -0
- package/src/openai/model-effort-verification-config.ts +35 -0
- package/src/openai/openai-request-format.ts +116 -0
- package/src/openai/parallel-tool-policy.ts +25 -0
- package/src/openai/parsers/response-parser.test.ts +407 -0
- package/src/openai/parsers/response-parser.ts +48 -0
- package/src/openai/provider-definition.test.ts +74 -0
- package/src/openai/provider-definition.ts +149 -0
- package/src/openai/provider.test.ts +1717 -0
- package/src/openai/provider.ts +417 -0
- package/src/openai/reasoning-effort.test.ts +272 -0
- package/src/openai/reasoning-effort.ts +49 -0
- package/src/openai/request-id.ts +39 -0
- package/src/openai/request-options.ts +14 -0
- package/src/openai/responses-chat.ts +292 -0
- package/src/openai/responses-converter.ts +132 -0
- package/src/openai/responses-parser.test.ts +219 -0
- package/src/openai/responses-parser.ts +361 -0
- package/src/openai/responses-stream-utils.ts +45 -0
- package/src/openai/responses-types.ts +219 -0
- package/src/openai/streaming/stream-assembler.ts +3 -0
- package/src/openai/types/api-types.ts +113 -0
- package/src/openai/types.ts +263 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { closeObjectSchemas } from '@robota-sdk/agent-core';
|
|
2
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { OpenAIProvider } from '../provider';
|
|
5
|
+
|
|
6
|
+
import type { IToolSchema, TUniversalMessage } from '@robota-sdk/agent-core';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* MCP-005 (TC-08) — `strictTools` no longer closes schemas inside `responses-converter.ts`; the
|
|
10
|
+
* projection step (`AbstractAIProvider.projectTools()`, `STRICT_TOOL_SCHEMA_PROFILE`) runs BEFORE the
|
|
11
|
+
* converter now. This test drives the real `OpenAIProvider` end to end (profile → projector →
|
|
12
|
+
* converter) over a fake Responses client and asserts the request's `parameters` is byte-identical to
|
|
13
|
+
* today's `closeObjectSchemas(input, { requireAllProperties: true, optionalAsNullable: true })` for a
|
|
14
|
+
* fixture the projector does not reject — the capability-preservation premise GATE-WRITE recorded.
|
|
15
|
+
*
|
|
16
|
+
* PROV-007's original story stays true below: strict mode does not accept an arbitrary JSON Schema —
|
|
17
|
+
* every object node, nested included, must carry `additionalProperties: false` and list all of its
|
|
18
|
+
* properties in `required` — so a schema that is correct for this repository was rejected whenever a
|
|
19
|
+
* caller opted in, root included.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
vi.mock('openai', () => {
|
|
23
|
+
const MockOpenAI = vi.fn().mockImplementation(() => ({
|
|
24
|
+
chat: { completions: { create: vi.fn() } },
|
|
25
|
+
responses: { create: vi.fn() },
|
|
26
|
+
}));
|
|
27
|
+
return { default: MockOpenAI };
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
interface IFakeOpenAIClient {
|
|
31
|
+
responses: { create: ReturnType<typeof vi.fn> };
|
|
32
|
+
chat: { completions: { create: ReturnType<typeof vi.fn> } };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function createUserMessage(content: string): TUniversalMessage {
|
|
36
|
+
return { id: 'msg-1', state: 'complete' as const, role: 'user', content, timestamp: new Date() };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function fakeResponsesResult(): Record<string, unknown> {
|
|
40
|
+
return {
|
|
41
|
+
id: 'resp-strict-tools-closure',
|
|
42
|
+
model: 'gpt-4o',
|
|
43
|
+
output_text: '',
|
|
44
|
+
output: [],
|
|
45
|
+
status: 'completed',
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function sendChat(
|
|
50
|
+
provider: OpenAIProvider,
|
|
51
|
+
tools: IToolSchema[],
|
|
52
|
+
): Promise<Record<string, unknown>> {
|
|
53
|
+
const client = (provider as unknown as { client: IFakeOpenAIClient }).client;
|
|
54
|
+
client.responses.create.mockResolvedValue(fakeResponsesResult());
|
|
55
|
+
await provider.chat([createUserMessage('hello')], { model: 'gpt-4o', tools });
|
|
56
|
+
const [requestParams] = client.responses.create.mock.calls[
|
|
57
|
+
client.responses.create.mock.calls.length - 1
|
|
58
|
+
] as [Record<string, unknown>];
|
|
59
|
+
return requestParams;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The same request through the Chat Completions surface (the default once `baseURL` is set). */
|
|
63
|
+
async function sendChatCompletions(
|
|
64
|
+
provider: OpenAIProvider,
|
|
65
|
+
tools: IToolSchema[],
|
|
66
|
+
): Promise<Record<string, unknown>> {
|
|
67
|
+
const client = (provider as unknown as { client: IFakeOpenAIClient }).client;
|
|
68
|
+
client.chat.completions.create.mockResolvedValue({
|
|
69
|
+
id: 'chatcmpl-strict-tools',
|
|
70
|
+
object: 'chat.completion',
|
|
71
|
+
created: 1,
|
|
72
|
+
model: 'gpt-4o',
|
|
73
|
+
choices: [{ index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }],
|
|
74
|
+
});
|
|
75
|
+
await provider.chat([createUserMessage('hello')], { model: 'gpt-4o', tools });
|
|
76
|
+
const calls = client.chat.completions.create.mock.calls;
|
|
77
|
+
const [requestParams] = calls[calls.length - 1] as [Record<string, unknown>];
|
|
78
|
+
return requestParams;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const NESTED_TOOL: IToolSchema = {
|
|
82
|
+
name: 'create_user',
|
|
83
|
+
description: 'Creates a user',
|
|
84
|
+
parameters: {
|
|
85
|
+
type: 'object',
|
|
86
|
+
additionalProperties: true,
|
|
87
|
+
properties: {
|
|
88
|
+
email: { type: 'string' },
|
|
89
|
+
profile: {
|
|
90
|
+
type: 'object',
|
|
91
|
+
additionalProperties: true,
|
|
92
|
+
properties: { nickname: { type: 'string' }, bio: { type: 'string' } },
|
|
93
|
+
required: ['nickname'],
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
required: ['email'],
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const FLAT_TOOL: IToolSchema = {
|
|
101
|
+
name: 'ping',
|
|
102
|
+
description: 'Pings',
|
|
103
|
+
parameters: { type: 'object', additionalProperties: true, properties: {}, required: [] },
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
describe('MCP-005 TC-08 — the strict path (profile → projector → converter)', () => {
|
|
107
|
+
it('closes and completes every object node, root and nested, byte-identical to closeObjectSchemas', async () => {
|
|
108
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', strictTools: true });
|
|
109
|
+
const requestParams = await sendChat(provider, [NESTED_TOOL]);
|
|
110
|
+
const [tool] = requestParams.tools as Array<Record<string, unknown>>;
|
|
111
|
+
|
|
112
|
+
expect(tool.strict).toBe(true);
|
|
113
|
+
expect(tool.parameters).toEqual(
|
|
114
|
+
closeObjectSchemas(NESTED_TOOL.parameters, {
|
|
115
|
+
requireAllProperties: true,
|
|
116
|
+
optionalAsNullable: true,
|
|
117
|
+
}),
|
|
118
|
+
);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('is not only about nesting — an open ROOT is refused too', async () => {
|
|
122
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', strictTools: true });
|
|
123
|
+
const requestParams = await sendChat(provider, [FLAT_TOOL]);
|
|
124
|
+
const [tool] = requestParams.tools as Array<Record<string, unknown>>;
|
|
125
|
+
|
|
126
|
+
expect((tool.parameters as Record<string, unknown>).additionalProperties).toBe(false);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('leaves the description byte-identical for a fixture with no lossy strip', async () => {
|
|
130
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', strictTools: true });
|
|
131
|
+
const requestParams = await sendChat(provider, [NESTED_TOOL]);
|
|
132
|
+
const [tool] = requestParams.tools as Array<Record<string, unknown>>;
|
|
133
|
+
|
|
134
|
+
expect(tool.description).toBe(NESTED_TOOL.description);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
describe('MCP-005 TC-08 — the non-strict path carries the permissive projection', () => {
|
|
139
|
+
it('forwards the schema unchanged and sends strict: false', async () => {
|
|
140
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', strictTools: false });
|
|
141
|
+
const requestParams = await sendChat(provider, [NESTED_TOOL]);
|
|
142
|
+
const [tool] = requestParams.tools as Array<Record<string, unknown>>;
|
|
143
|
+
|
|
144
|
+
expect(tool.strict).toBe(false);
|
|
145
|
+
expect(tool.parameters).toEqual(NESTED_TOOL.parameters);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it('treats an unset strictTools as non-strict', async () => {
|
|
149
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test' });
|
|
150
|
+
const requestParams = await sendChat(provider, [NESTED_TOOL]);
|
|
151
|
+
const [tool] = requestParams.tools as Array<Record<string, unknown>>;
|
|
152
|
+
|
|
153
|
+
expect(tool.strict).toBe(false);
|
|
154
|
+
expect(tool.parameters).toEqual(NESTED_TOOL.parameters);
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
describe('strictTools on the Chat Completions surface (#3209)', () => {
|
|
159
|
+
const GATEWAY = { apiKey: 'sk-test', baseURL: 'https://gateway.example/v1' };
|
|
160
|
+
|
|
161
|
+
it('declares each function strict, with the same closed schema the Responses surface sends', async () => {
|
|
162
|
+
const provider = new OpenAIProvider({ ...GATEWAY, strictTools: true });
|
|
163
|
+
const requestParams = await sendChatCompletions(provider, [NESTED_TOOL]);
|
|
164
|
+
const [tool] = requestParams.tools as Array<{ function: Record<string, unknown> }>;
|
|
165
|
+
|
|
166
|
+
expect(tool?.function.strict).toBe(true);
|
|
167
|
+
expect(tool?.function.parameters).toEqual(
|
|
168
|
+
closeObjectSchemas(NESTED_TOOL.parameters, {
|
|
169
|
+
requireAllProperties: true,
|
|
170
|
+
optionalAsNullable: true,
|
|
171
|
+
}),
|
|
172
|
+
);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('sends no strict key when strictTools is off', async () => {
|
|
176
|
+
const provider = new OpenAIProvider(GATEWAY);
|
|
177
|
+
const requestParams = await sendChatCompletions(provider, [NESTED_TOOL]);
|
|
178
|
+
const [tool] = requestParams.tools as Array<{ function: Record<string, unknown> }>;
|
|
179
|
+
|
|
180
|
+
expect(tool?.function).not.toHaveProperty('strict');
|
|
181
|
+
expect(tool?.function.parameters).toEqual(NESTED_TOOL.parameters);
|
|
182
|
+
});
|
|
183
|
+
});
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP-005 (TC-08) — conformance: the real `OpenAIProvider` over the shared MCP-005 fixture set.
|
|
3
|
+
*
|
|
4
|
+
* With `strictTools` off both the Responses and Chat Completions surfaces carry the permissive
|
|
5
|
+
* projection; with it on both carry the strict projection (§ Profiles — both surfaces honor
|
|
6
|
+
* `strictTools` identically). Adopted/adapted fixtures reach the request in projected form (compared
|
|
7
|
+
* against `projectToolSchema` directly, not hand-computed); rejected fixtures are absent; one
|
|
8
|
+
* `tool_schema_quarantined` warn per absent fixture names it. Both `chat` and `chatStream` request
|
|
9
|
+
* paths of each converter are exercised.
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
PERMISSIVE_TOOL_SCHEMA_PROFILE,
|
|
13
|
+
projectToolSchema,
|
|
14
|
+
setGlobalLoggerSink,
|
|
15
|
+
STRICT_TOOL_SCHEMA_PROFILE,
|
|
16
|
+
} from '@robota-sdk/agent-core';
|
|
17
|
+
import { loadToolSchemaProjectionFixtures } from '@robota-sdk/agent-core/testing';
|
|
18
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
19
|
+
|
|
20
|
+
import { OpenAIProvider } from '../provider';
|
|
21
|
+
|
|
22
|
+
import type { IToolSchema, ILogger, TUniversalMessage } from '@robota-sdk/agent-core';
|
|
23
|
+
|
|
24
|
+
vi.mock('openai', () => {
|
|
25
|
+
const MockOpenAI = vi.fn().mockImplementation(() => ({
|
|
26
|
+
chat: { completions: { create: vi.fn() } },
|
|
27
|
+
responses: { create: vi.fn() },
|
|
28
|
+
}));
|
|
29
|
+
return { default: MockOpenAI };
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const fixtures = loadToolSchemaProjectionFixtures();
|
|
33
|
+
const PERMISSIVE_PROFILE = { ...PERMISSIVE_TOOL_SCHEMA_PROFILE, providerName: 'openai' };
|
|
34
|
+
const STRICT_PROFILE = { ...STRICT_TOOL_SCHEMA_PROFILE, providerName: 'openai' };
|
|
35
|
+
|
|
36
|
+
function recordingSink(): { sink: ILogger; lines: string[] } {
|
|
37
|
+
const lines: string[] = [];
|
|
38
|
+
const record =
|
|
39
|
+
(level: string) =>
|
|
40
|
+
(...args: unknown[]): void => {
|
|
41
|
+
lines.push(`${level} ${args.map((value) => String(value)).join(' ')}`);
|
|
42
|
+
};
|
|
43
|
+
return {
|
|
44
|
+
lines,
|
|
45
|
+
sink: {
|
|
46
|
+
debug: record('debug'),
|
|
47
|
+
info: record('info'),
|
|
48
|
+
warn: record('warn'),
|
|
49
|
+
error: record('error'),
|
|
50
|
+
log: record('log'),
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function createUserMessage(content: string): TUniversalMessage {
|
|
56
|
+
return { id: 'msg-1', state: 'complete' as const, role: 'user', content, timestamp: new Date() };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface IFakeClient {
|
|
60
|
+
responses: { create: ReturnType<typeof vi.fn> };
|
|
61
|
+
chat: { completions: { create: ReturnType<typeof vi.fn> } };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function fakeClient(provider: OpenAIProvider): IFakeClient {
|
|
65
|
+
return (provider as unknown as { client: IFakeClient }).client;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function respondResponses(client: IFakeClient): void {
|
|
69
|
+
client.responses.create.mockResolvedValue({
|
|
70
|
+
id: 'resp-tool-schema-projection',
|
|
71
|
+
model: 'gpt-4o',
|
|
72
|
+
output_text: '',
|
|
73
|
+
output: [],
|
|
74
|
+
status: 'completed',
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function respondChatCompletions(client: IFakeClient): void {
|
|
79
|
+
client.chat.completions.create.mockResolvedValue({
|
|
80
|
+
id: 'chatcmpl-tool-schema-projection',
|
|
81
|
+
object: 'chat.completion',
|
|
82
|
+
created: Date.now(),
|
|
83
|
+
model: 'gpt-4',
|
|
84
|
+
choices: [
|
|
85
|
+
{
|
|
86
|
+
index: 0,
|
|
87
|
+
message: { role: 'assistant', content: '', refusal: null },
|
|
88
|
+
finish_reason: 'stop',
|
|
89
|
+
logprobs: null,
|
|
90
|
+
},
|
|
91
|
+
],
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function* streamResponsesResult() {
|
|
96
|
+
yield {
|
|
97
|
+
type: 'response.completed',
|
|
98
|
+
response: { id: 'resp-stream', output_text: '', output: [], status: 'completed' },
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function* streamChatCompletionsResult() {
|
|
103
|
+
yield {
|
|
104
|
+
id: 'chunk-1',
|
|
105
|
+
object: 'chat.completion.chunk',
|
|
106
|
+
created: Date.now(),
|
|
107
|
+
model: 'gpt-4',
|
|
108
|
+
choices: [{ index: 0, delta: { content: '' }, finish_reason: 'stop', logprobs: null }],
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
interface ISentTool {
|
|
113
|
+
name: string;
|
|
114
|
+
description: string;
|
|
115
|
+
parameters: unknown;
|
|
116
|
+
/** Whether the tool was declared strict on the wire (absent counts as not strict). */
|
|
117
|
+
strict: boolean;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function sentToolsFromResponses(client: IFakeClient): ISentTool[] {
|
|
121
|
+
const [requestParams] = client.responses.create.mock.calls[
|
|
122
|
+
client.responses.create.mock.calls.length - 1
|
|
123
|
+
] as [
|
|
124
|
+
{
|
|
125
|
+
tools?: Array<{ name: string; description: string; parameters: unknown; strict?: boolean }>;
|
|
126
|
+
},
|
|
127
|
+
];
|
|
128
|
+
return (requestParams.tools ?? []).map((tool) => ({
|
|
129
|
+
name: tool.name,
|
|
130
|
+
description: tool.description,
|
|
131
|
+
parameters: tool.parameters,
|
|
132
|
+
strict: tool.strict === true,
|
|
133
|
+
}));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function sentToolsFromChatCompletions(client: IFakeClient): ISentTool[] {
|
|
137
|
+
const [requestParams] = client.chat.completions.create.mock.calls[
|
|
138
|
+
client.chat.completions.create.mock.calls.length - 1
|
|
139
|
+
] as [
|
|
140
|
+
{
|
|
141
|
+
tools?: Array<{
|
|
142
|
+
function: { name: string; description: string; parameters: unknown; strict?: boolean };
|
|
143
|
+
}>;
|
|
144
|
+
},
|
|
145
|
+
];
|
|
146
|
+
return (requestParams.tools ?? []).map((tool) => ({
|
|
147
|
+
name: tool.function.name,
|
|
148
|
+
description: tool.function.description,
|
|
149
|
+
parameters: tool.function.parameters,
|
|
150
|
+
strict: tool.function.strict === true,
|
|
151
|
+
}));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
describe.each([
|
|
155
|
+
{
|
|
156
|
+
apiSurface: 'responses' as const,
|
|
157
|
+
respond: respondResponses,
|
|
158
|
+
sentTools: sentToolsFromResponses,
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
apiSurface: 'chat-completions' as const,
|
|
162
|
+
respond: respondChatCompletions,
|
|
163
|
+
sentTools: sentToolsFromChatCompletions,
|
|
164
|
+
},
|
|
165
|
+
])(
|
|
166
|
+
'MCP-005 TC-08 — OpenAI $apiSurface, permissive profile (strictTools off)',
|
|
167
|
+
({ apiSurface, respond, sentTools }) => {
|
|
168
|
+
afterEach(() => {
|
|
169
|
+
setGlobalLoggerSink(undefined);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('reaches the request in projected form for adopted/adapted fixtures', async () => {
|
|
173
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', apiSurface });
|
|
174
|
+
const client = fakeClient(provider);
|
|
175
|
+
respond(client);
|
|
176
|
+
|
|
177
|
+
const tools: IToolSchema[] = [
|
|
178
|
+
fixtures.subsetOnly,
|
|
179
|
+
fixtures.unknownKeywords,
|
|
180
|
+
fixtures.arrayItemsObject,
|
|
181
|
+
];
|
|
182
|
+
await provider.chat([createUserMessage('hello')], { model: 'gpt-4o', tools });
|
|
183
|
+
|
|
184
|
+
const sent = sentTools(client);
|
|
185
|
+
expect(sent).toHaveLength(3);
|
|
186
|
+
expect(sent.every((tool) => !tool.strict)).toBe(true);
|
|
187
|
+
for (const [index, tool] of tools.entries()) {
|
|
188
|
+
const projection = projectToolSchema(tool, PERMISSIVE_PROFILE);
|
|
189
|
+
expect(sent[index]?.parameters).toEqual(projection.tool.parameters);
|
|
190
|
+
expect(sent[index]?.description).toEqual(projection.tool.description);
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('omits a rejected fixture and reports one quarantine warn (chat)', async () => {
|
|
195
|
+
const recorder = recordingSink();
|
|
196
|
+
setGlobalLoggerSink(recorder.sink);
|
|
197
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', apiSurface });
|
|
198
|
+
const client = fakeClient(provider);
|
|
199
|
+
respond(client);
|
|
200
|
+
|
|
201
|
+
const tools = [...fixtures.oneInvalidAmongMany] as IToolSchema[];
|
|
202
|
+
await provider.chat([createUserMessage('hello')], { model: 'gpt-4o', tools });
|
|
203
|
+
|
|
204
|
+
const sent = sentTools(client);
|
|
205
|
+
expect(sent.map((tool) => tool.name)).toEqual(['good_tool_one', 'good_tool_two']);
|
|
206
|
+
|
|
207
|
+
const quarantineLines = recorder.lines.filter((line) =>
|
|
208
|
+
line.includes('tool_schema_quarantined'),
|
|
209
|
+
);
|
|
210
|
+
expect(quarantineLines).toHaveLength(1);
|
|
211
|
+
expect(quarantineLines[0]).toContain('provider=openai');
|
|
212
|
+
expect(quarantineLines[0]).toContain('tool=bad_tool');
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it('every documented rejection kind is absent from the request', async () => {
|
|
216
|
+
const recorder = recordingSink();
|
|
217
|
+
setGlobalLoggerSink(recorder.sink);
|
|
218
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', apiSurface });
|
|
219
|
+
const client = fakeClient(provider);
|
|
220
|
+
respond(client);
|
|
221
|
+
|
|
222
|
+
const rejected: IToolSchema[] = [
|
|
223
|
+
fixtures.rootAnyOf,
|
|
224
|
+
fixtures.prototypeKey,
|
|
225
|
+
fixtures.deepNesting,
|
|
226
|
+
fixtures.oversized,
|
|
227
|
+
];
|
|
228
|
+
await provider.chat([createUserMessage('hello')], { model: 'gpt-4o', tools: rejected });
|
|
229
|
+
|
|
230
|
+
expect(sentTools(client)).toHaveLength(0);
|
|
231
|
+
const quarantineLines = recorder.lines.filter((line) =>
|
|
232
|
+
line.includes('tool_schema_quarantined'),
|
|
233
|
+
);
|
|
234
|
+
expect(quarantineLines).toHaveLength(rejected.length);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it('projects tools on the chatStream request path too', async () => {
|
|
238
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', apiSurface });
|
|
239
|
+
const client = fakeClient(provider);
|
|
240
|
+
if (apiSurface === 'responses') {
|
|
241
|
+
client.responses.create.mockResolvedValue(streamResponsesResult());
|
|
242
|
+
} else {
|
|
243
|
+
client.chat.completions.create.mockResolvedValue(streamChatCompletionsResult());
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const tools = [...fixtures.oneInvalidAmongMany] as IToolSchema[];
|
|
247
|
+
for await (const _chunk of provider.chatStream([createUserMessage('hello')], {
|
|
248
|
+
model: 'gpt-4o',
|
|
249
|
+
tools,
|
|
250
|
+
})) {
|
|
251
|
+
// drain
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const sent = sentTools(client);
|
|
255
|
+
expect(sent.map((tool) => tool.name)).toEqual(['good_tool_one', 'good_tool_two']);
|
|
256
|
+
expect(sent.every((tool) => !tool.strict)).toBe(true);
|
|
257
|
+
});
|
|
258
|
+
},
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
describe.each([
|
|
262
|
+
{
|
|
263
|
+
apiSurface: 'responses' as const,
|
|
264
|
+
respond: respondResponses,
|
|
265
|
+
sentTools: sentToolsFromResponses,
|
|
266
|
+
},
|
|
267
|
+
{
|
|
268
|
+
apiSurface: 'chat-completions' as const,
|
|
269
|
+
respond: respondChatCompletions,
|
|
270
|
+
sentTools: sentToolsFromChatCompletions,
|
|
271
|
+
},
|
|
272
|
+
])(
|
|
273
|
+
'MCP-005 TC-08 — OpenAI $apiSurface, strict profile (strictTools on)',
|
|
274
|
+
({ apiSurface, respond, sentTools }) => {
|
|
275
|
+
it('reaches the request in strictly-projected form', async () => {
|
|
276
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', apiSurface, strictTools: true });
|
|
277
|
+
const client = fakeClient(provider);
|
|
278
|
+
respond(client);
|
|
279
|
+
|
|
280
|
+
const tools: IToolSchema[] = [fixtures.subsetOnly, fixtures.nestedAnyOfOptional];
|
|
281
|
+
await provider.chat([createUserMessage('hello')], { model: 'gpt-4o', tools });
|
|
282
|
+
|
|
283
|
+
const sent = sentTools(client);
|
|
284
|
+
expect(sent).toHaveLength(2);
|
|
285
|
+
for (const [index, tool] of tools.entries()) {
|
|
286
|
+
const projection = projectToolSchema(tool, STRICT_PROFILE);
|
|
287
|
+
expect(sent[index]?.parameters).toEqual(projection.tool.parameters);
|
|
288
|
+
expect(sent[index]?.description).toEqual(projection.tool.description);
|
|
289
|
+
expect(sent[index]?.strict).toBe(true);
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it('projects strictly on the chatStream request path too', async () => {
|
|
294
|
+
const provider = new OpenAIProvider({ apiKey: 'sk-test', apiSurface, strictTools: true });
|
|
295
|
+
const client = fakeClient(provider);
|
|
296
|
+
if (apiSurface === 'responses') {
|
|
297
|
+
client.responses.create.mockResolvedValue(streamResponsesResult());
|
|
298
|
+
} else {
|
|
299
|
+
client.chat.completions.create.mockResolvedValue(streamChatCompletionsResult());
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const tools: IToolSchema[] = [fixtures.subsetOnly];
|
|
303
|
+
for await (const _chunk of provider.chatStream([createUserMessage('hello')], {
|
|
304
|
+
model: 'gpt-4o',
|
|
305
|
+
tools,
|
|
306
|
+
})) {
|
|
307
|
+
// drain
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const sent = sentTools(client);
|
|
311
|
+
const projection = projectToolSchema(fixtures.subsetOnly, STRICT_PROFILE);
|
|
312
|
+
expect(sent[0]?.parameters).toEqual(projection.tool.parameters);
|
|
313
|
+
expect(sent[0]?.strict).toBe(true);
|
|
314
|
+
});
|
|
315
|
+
},
|
|
316
|
+
);
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trusted `traceparent` on the wire: captured at the SDK's own fetch, for every call site on both
|
|
3
|
+
* API surfaces.
|
|
4
|
+
*/
|
|
5
|
+
import OpenAI from 'openai';
|
|
6
|
+
import { describe, expect, it } from 'vitest';
|
|
7
|
+
|
|
8
|
+
import { OpenAIProvider } from '../provider';
|
|
9
|
+
|
|
10
|
+
import type { IChatOptions, IOutboundTraceContext, TUniversalMessage } from '@robota-sdk/agent-core';
|
|
11
|
+
|
|
12
|
+
const TRACEPARENT = '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01';
|
|
13
|
+
|
|
14
|
+
const completion = {
|
|
15
|
+
id: 'c1', object: 'chat.completion', created: 0, model: 'gpt-test',
|
|
16
|
+
choices: [{ index: 0, message: { role: 'assistant', content: 'hi' }, finish_reason: 'stop' }],
|
|
17
|
+
};
|
|
18
|
+
const completionChunks = [
|
|
19
|
+
{ id: 'c1', object: 'chat.completion.chunk', created: 0, model: 'gpt-test', choices: [{ index: 0, delta: { role: 'assistant', content: 'hi' }, finish_reason: null }] },
|
|
20
|
+
{ id: 'c1', object: 'chat.completion.chunk', created: 0, model: 'gpt-test', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
|
|
21
|
+
];
|
|
22
|
+
const response = {
|
|
23
|
+
id: 'resp_1', object: 'response', created_at: 0, model: 'gpt-test', status: 'completed',
|
|
24
|
+
output: [{ type: 'message', id: 'msg_1', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'hi', annotations: [] }] }],
|
|
25
|
+
usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
|
|
26
|
+
};
|
|
27
|
+
const responseEvents = [
|
|
28
|
+
{ type: 'response.output_text.delta', item_id: 'msg_1', output_index: 0, content_index: 0, delta: 'hi', sequence_number: 1 },
|
|
29
|
+
{ type: 'response.completed', response, sequence_number: 2 },
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
function sse(events: readonly object[], done: boolean): string {
|
|
33
|
+
return events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('') + (done ? 'data: [DONE]\n\n' : '');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function wire(baseURL?: string) {
|
|
37
|
+
const seen: Array<{ url: string; traceparent: string | null }> = [];
|
|
38
|
+
const fetch = async (url: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
|
39
|
+
const target = String(url);
|
|
40
|
+
seen.push({ url: target, traceparent: new Headers(init?.headers as HeadersInit).get('traceparent') });
|
|
41
|
+
const body = JSON.parse(String(init?.body)) as { stream?: boolean };
|
|
42
|
+
const responses = target.endsWith('/responses');
|
|
43
|
+
if (body.stream) {
|
|
44
|
+
return new Response(sse(responses ? responseEvents : completionChunks, !responses), {
|
|
45
|
+
status: 200, headers: { 'content-type': 'text/event-stream', 'x-request-id': 'req_1' },
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return new Response(JSON.stringify(responses ? response : completion), {
|
|
49
|
+
status: 200, headers: { 'content-type': 'application/json', 'x-request-id': 'req_1' },
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
const client = new OpenAI({ apiKey: 'test-key', ...(baseURL ? { baseURL } : {}), fetch: fetch as never, maxRetries: 0 });
|
|
53
|
+
return { client, seen };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const messages: TUniversalMessage[] = [{ id: 'u1', role: 'user', content: 'hello', state: 'complete', timestamp: new Date() }];
|
|
57
|
+
|
|
58
|
+
function traceTo(...allowedOrigins: string[]): IOutboundTraceContext {
|
|
59
|
+
return { traceparent: TRACEPARENT, allowedOrigins };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** chat() without and with a delta callback, then chatStream(): every call site of one surface. */
|
|
63
|
+
async function everyCallSite(provider: OpenAIProvider, options: IChatOptions): Promise<void> {
|
|
64
|
+
await provider.chat(messages, { model: 'gpt-test', ...options });
|
|
65
|
+
await provider.chat(messages, { model: 'gpt-test', onTextDelta: () => undefined, ...options });
|
|
66
|
+
for await (const _chunk of provider.chatStream(messages, { model: 'gpt-test', ...options })) {
|
|
67
|
+
// drain
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
describe('OpenAI trusted trace context', () => {
|
|
72
|
+
for (const apiSurface of ['chat-completions', 'responses'] as const) {
|
|
73
|
+
it(`sends traceparent from every ${apiSurface} call site when the client origin is listed`, async () => {
|
|
74
|
+
const { client, seen } = wire('https://gateway.example.com/v1');
|
|
75
|
+
const provider = new OpenAIProvider({ client, apiSurface });
|
|
76
|
+
const raw: unknown[] = [];
|
|
77
|
+
await everyCallSite(provider, {
|
|
78
|
+
outboundTraceContext: traceTo('https://gateway.example.com'),
|
|
79
|
+
onProviderNativeRawPayload: (event) => raw.push(event),
|
|
80
|
+
});
|
|
81
|
+
expect(provider.canPropagateTraceContext()).toBe(true);
|
|
82
|
+
expect(seen).toHaveLength(3);
|
|
83
|
+
expect(seen.map((request) => request.traceparent)).toEqual([TRACEPARENT, TRACEPARENT, TRACEPARENT]);
|
|
84
|
+
expect(raw.length).toBeGreaterThan(0);
|
|
85
|
+
expect(JSON.stringify(raw)).not.toContain('traceparent');
|
|
86
|
+
expect(JSON.stringify(raw)).not.toContain(TRACEPARENT);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it(`sends nothing from ${apiSurface} to the default vendor origin unless it is listed`, async () => {
|
|
90
|
+
const unlisted = wire();
|
|
91
|
+
await everyCallSite(new OpenAIProvider({ client: unlisted.client, apiSurface }), {
|
|
92
|
+
outboundTraceContext: traceTo('https://gateway.example.com'),
|
|
93
|
+
});
|
|
94
|
+
expect(unlisted.seen.map((request) => request.traceparent)).toEqual([null, null, null]);
|
|
95
|
+
|
|
96
|
+
const listed = wire();
|
|
97
|
+
await everyCallSite(new OpenAIProvider({ client: listed.client, apiSurface }), {
|
|
98
|
+
outboundTraceContext: traceTo('https://api.openai.com'),
|
|
99
|
+
});
|
|
100
|
+
expect(listed.seen.map((request) => request.traceparent)).toEqual([TRACEPARENT, TRACEPARENT, TRACEPARENT]);
|
|
101
|
+
|
|
102
|
+
const none = wire();
|
|
103
|
+
await everyCallSite(new OpenAIProvider({ client: none.client, apiSurface }), {});
|
|
104
|
+
expect(none.seen.map((request) => request.traceparent)).toEqual([null, null, null]);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
it('cannot propagate through an executor or a client whose base URL is unreadable', () => {
|
|
109
|
+
const executor = { name: 'remote', version: '1', executeChat: async () => ({}), supportsTools: () => true, validateConfig: () => true };
|
|
110
|
+
expect(new OpenAIProvider({ executor } as never).canPropagateTraceContext()).toBe(false);
|
|
111
|
+
const opaque = { chat: { completions: { create: () => undefined } } } as unknown as OpenAI;
|
|
112
|
+
expect(new OpenAIProvider({ client: opaque }).canPropagateTraceContext()).toBe(false);
|
|
113
|
+
});
|
|
114
|
+
});
|