@vellumai/assistant 0.11.1-dev.202608041836.2a522b8 → 0.11.1-dev.202608042001.feb8dd6
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/package.json +1 -1
- package/src/__tests__/compactor-truncation-pairing.test.ts +368 -0
- package/src/__tests__/history-repair.test.ts +39 -0
- package/src/agent/history-repair/history-repair.ts +8 -0
- package/src/context/compactor.ts +41 -4
- package/src/persistence/migrations/361-normalize-managed-connection-rows.test.ts +168 -0
- package/src/persistence/migrations/361-normalize-managed-connection-rows.ts +76 -0
- package/src/persistence/steps.ts +9 -0
- package/src/providers/__tests__/vellum-connection-routing.test.ts +5 -10
- package/src/providers/inference/adapter-factory.ts +4 -3
- package/src/providers/openai/__tests__/orphan-tool-result-guard.test.ts +478 -0
- package/src/providers/openai/chat-completions-provider.ts +46 -30
- package/src/providers/openai/orphaned-tool-result.ts +79 -0
- package/src/providers/openai/responses-provider.ts +50 -24
- package/src/providers/vellum-model-routing.ts +6 -7
- package/src/runtime/routes/inference-provider-connection-routes.ts +0 -16
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { type DrizzleDb, getSqliteFrom } from "../db-connection.js";
|
|
2
|
+
|
|
3
|
+
const VELLUM_PROVIDER = "vellum";
|
|
4
|
+
const PLATFORM_AUTH_JSON = JSON.stringify({ type: "platform" });
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Reconcile `provider_connections` rows so platform auth and provider
|
|
8
|
+
* "vellum" always pair. The two columns record the same fact (the managed,
|
|
9
|
+
* platform-billed route); auth derivation sets them together and the
|
|
10
|
+
* connection routes reject writes that split them, but rows written before
|
|
11
|
+
* that guard can disagree. The provider column is the authoritative managed
|
|
12
|
+
* signal (`isVellumManagedConnection`), so mismatched rows must converge:
|
|
13
|
+
*
|
|
14
|
+
* - Platform auth with any other provider: the provider becomes "vellum".
|
|
15
|
+
* These rows dispatch through the managed proxy (transport selection keys
|
|
16
|
+
* on the managed identity), so normalizing the provider preserves billing
|
|
17
|
+
* and transport behavior, while normalizing the auth instead would
|
|
18
|
+
* silently turn a platform-billed row into a keyless BYOK row. This also
|
|
19
|
+
* heals a stuck pre-consolidation canonical row (name "vellum", concrete
|
|
20
|
+
* provider, platform auth) that boot seeding skips because its provider
|
|
21
|
+
* differs from the sentinel.
|
|
22
|
+
* - Provider "vellum" with any other auth: the auth becomes
|
|
23
|
+
* `{"type":"platform"}`. A vellum row means the managed route by
|
|
24
|
+
* definition, and non-platform auth on it never yields a usable adapter.
|
|
25
|
+
*
|
|
26
|
+
* Rows whose auth column is not valid JSON are left alone (the DB loaders
|
|
27
|
+
* already treat them as invalid). Idempotent: a reconciled row matches
|
|
28
|
+
* neither rule, and the table-exists guard covers databases from before
|
|
29
|
+
* migration 243.
|
|
30
|
+
*/
|
|
31
|
+
export function migrateNormalizeManagedConnectionRows(
|
|
32
|
+
database: DrizzleDb,
|
|
33
|
+
): void {
|
|
34
|
+
const raw = getSqliteFrom(database);
|
|
35
|
+
|
|
36
|
+
const tableExists = raw
|
|
37
|
+
.query(
|
|
38
|
+
`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'provider_connections'`,
|
|
39
|
+
)
|
|
40
|
+
.get();
|
|
41
|
+
if (!tableExists) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const rows = raw
|
|
46
|
+
.query(`SELECT name, provider, auth FROM provider_connections`)
|
|
47
|
+
.all() as Array<{ name: string; provider: string; auth: string }>;
|
|
48
|
+
|
|
49
|
+
const now = Date.now();
|
|
50
|
+
for (const row of rows) {
|
|
51
|
+
let authType: unknown;
|
|
52
|
+
try {
|
|
53
|
+
const parsed: unknown = JSON.parse(row.auth);
|
|
54
|
+
authType =
|
|
55
|
+
parsed !== null && typeof parsed === "object"
|
|
56
|
+
? (parsed as { type?: unknown }).type
|
|
57
|
+
: undefined;
|
|
58
|
+
} catch {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (authType === "platform" && row.provider !== VELLUM_PROVIDER) {
|
|
63
|
+
raw
|
|
64
|
+
.prepare(
|
|
65
|
+
`UPDATE provider_connections SET provider = ?, updated_at = ? WHERE name = ?`,
|
|
66
|
+
)
|
|
67
|
+
.run(VELLUM_PROVIDER, now, row.name);
|
|
68
|
+
} else if (row.provider === VELLUM_PROVIDER && authType !== "platform") {
|
|
69
|
+
raw
|
|
70
|
+
.prepare(
|
|
71
|
+
`UPDATE provider_connections SET auth = ?, updated_at = ? WHERE name = ?`,
|
|
72
|
+
)
|
|
73
|
+
.run(PLATFORM_AUTH_JSON, now, row.name);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
package/src/persistence/steps.ts
CHANGED
|
@@ -468,6 +468,7 @@ import { migrateMoveMemorySegmentsToMemoryDb } from "./migrations/357-move-memor
|
|
|
468
468
|
import { migrateMoveMemoryEmbeddingsToMemoryDb } from "./migrations/358-move-memory-embeddings-to-memory-db.js";
|
|
469
469
|
import { migrateMoveMemorySummariesToMemoryDb } from "./migrations/359-move-memory-summaries-to-memory-db.js";
|
|
470
470
|
import { migrateAddDocumentWorkspacePath } from "./migrations/360-add-document-workspace-path.js";
|
|
471
|
+
import { migrateNormalizeManagedConnectionRows } from "./migrations/361-normalize-managed-connection-rows.js";
|
|
471
472
|
import type { MigrationStep } from "./migrations/run-migrations.js";
|
|
472
473
|
|
|
473
474
|
export const migrationSteps: MigrationStep[] = [
|
|
@@ -1543,4 +1544,12 @@ export const migrationSteps: MigrationStep[] = [
|
|
|
1543
1544
|
],
|
|
1544
1545
|
},
|
|
1545
1546
|
migrateAddDocumentWorkspacePath,
|
|
1547
|
+
{
|
|
1548
|
+
name: "migrateNormalizeManagedConnectionRows",
|
|
1549
|
+
run: migrateNormalizeManagedConnectionRows,
|
|
1550
|
+
// The table-exists guard treats a missing table as nothing-to-do, so
|
|
1551
|
+
// without this dependency a failed table creation followed by repair
|
|
1552
|
+
// would permanently checkpoint the normalization as a no-op.
|
|
1553
|
+
dependsOn: ["migrateCreateProviderConnections"],
|
|
1554
|
+
},
|
|
1546
1555
|
];
|
|
@@ -44,16 +44,11 @@ const resolvedAuth: ResolvedAuth = {
|
|
|
44
44
|
describe("vellum connection routing", () => {
|
|
45
45
|
test("isVellumManagedConnection identifies the sentinel connection", () => {
|
|
46
46
|
expect(isVellumManagedConnection(vellumConnection)).toBe(true);
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
).toBe(false);
|
|
53
|
-
// `vellum` provider with non-platform auth is not a managed vellum route.
|
|
54
|
-
expect(
|
|
55
|
-
isVellumManagedConnection({ provider: "vellum", auth: { type: "none" } }),
|
|
56
|
-
).toBe(false);
|
|
47
|
+
// The provider column alone decides: a concrete provider is never the
|
|
48
|
+
// managed route (platform auth always pairs with provider "vellum";
|
|
49
|
+
// DB migration 361 reconciles stored rows).
|
|
50
|
+
expect(isVellumManagedConnection({ provider: "fireworks" })).toBe(false);
|
|
51
|
+
expect(isVellumManagedConnection({ provider: "vellum" })).toBe(true);
|
|
57
52
|
});
|
|
58
53
|
|
|
59
54
|
test("the vellum sentinel is not a real provider without an override", () => {
|
|
@@ -34,6 +34,7 @@ import { RetryProvider } from "../retry.js";
|
|
|
34
34
|
import { TogetherProvider } from "../together/client.js";
|
|
35
35
|
import type { Provider } from "../types.js";
|
|
36
36
|
import { UsageTrackingProvider } from "../usage-tracking.js";
|
|
37
|
+
import { isVellumManagedConnection } from "../vellum-model-routing.js";
|
|
37
38
|
import { VercelAIGatewayProvider } from "../vercel-ai-gateway/client.js";
|
|
38
39
|
import type { ResolvedAuth } from "./auth.js";
|
|
39
40
|
import type { ProviderConnection } from "./auth.js";
|
|
@@ -262,9 +263,9 @@ export function createAdapterFromConnection(
|
|
|
262
263
|
// Usage-attribution headers (`X-Vellum-*`) are only meaningful when the
|
|
263
264
|
// request is routed through the Vellum-managed proxy. They carry billing
|
|
264
265
|
// metadata for our own backend. Forwarding them to a third-party endpoint
|
|
265
|
-
// would leak internal Vellum metadata, so gate on the
|
|
266
|
-
//
|
|
267
|
-
const isManagedProxy = connection
|
|
266
|
+
// would leak internal Vellum metadata, so gate on the managed connection
|
|
267
|
+
// identity, the only route that flows through our proxy.
|
|
268
|
+
const isManagedProxy = isVellumManagedConnection(connection);
|
|
268
269
|
return new UsageTrackingProvider(
|
|
269
270
|
new RetryProvider(adapter, {
|
|
270
271
|
forwardUsageAttributionHeaders: isManagedProxy,
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serialization guard for orphaned tool results on the OpenAI providers.
|
|
3
|
+
*
|
|
4
|
+
* Both transports validate pairing server-side: the Responses API rejects a
|
|
5
|
+
* `function_call_output` whose `call_id` was not emitted as a `function_call`
|
|
6
|
+
* earlier in the request, and the Chat Completions API rejects a tool-role
|
|
7
|
+
* message whose `tool_call_id` is not in a preceding assistant message's
|
|
8
|
+
* `tool_calls`. A `tool_result` with no backward match in the request (e.g.
|
|
9
|
+
* its `tool_use` truncated away) is therefore degraded into plain user text
|
|
10
|
+
* with an `[orphaned tool result]` prefix, preserving the information while
|
|
11
|
+
* keeping the request valid. Paired results serialize unchanged.
|
|
12
|
+
*/
|
|
13
|
+
import { describe, expect, test } from "bun:test";
|
|
14
|
+
|
|
15
|
+
import type { Message } from "../../types.js";
|
|
16
|
+
import { OpenAIChatCompletionsProvider } from "../chat-completions-provider.js";
|
|
17
|
+
import { OpenAIResponsesProvider } from "../responses-provider.js";
|
|
18
|
+
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
// Responses transport harness
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
type ResponsesStreamEvent = { type: string; [key: string]: unknown };
|
|
24
|
+
|
|
25
|
+
const RESPONSES_OK_EVENTS: ResponsesStreamEvent[] = [
|
|
26
|
+
{ type: "response.output_text.delta", delta: "ok" },
|
|
27
|
+
{
|
|
28
|
+
type: "response.completed",
|
|
29
|
+
response: {
|
|
30
|
+
model: "gpt-5.2",
|
|
31
|
+
status: "completed",
|
|
32
|
+
output: [],
|
|
33
|
+
usage: { input_tokens: 10, output_tokens: 2 },
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
function makeEventStream(
|
|
39
|
+
events: ResponsesStreamEvent[],
|
|
40
|
+
): AsyncIterable<ResponsesStreamEvent> {
|
|
41
|
+
return {
|
|
42
|
+
async *[Symbol.asyncIterator]() {
|
|
43
|
+
for (const event of events) {
|
|
44
|
+
yield event;
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Swap `responses.create` for a canned stream that records request params. */
|
|
51
|
+
function stubResponsesCreate(provider: OpenAIResponsesProvider): {
|
|
52
|
+
input: () => unknown[];
|
|
53
|
+
} {
|
|
54
|
+
let captured: unknown;
|
|
55
|
+
const inner = provider as unknown as {
|
|
56
|
+
client: {
|
|
57
|
+
responses: {
|
|
58
|
+
create: (
|
|
59
|
+
params: unknown,
|
|
60
|
+
) => Promise<AsyncIterable<ResponsesStreamEvent>>;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
inner.client.responses.create = async (params) => {
|
|
65
|
+
captured = params;
|
|
66
|
+
return makeEventStream(RESPONSES_OK_EVENTS);
|
|
67
|
+
};
|
|
68
|
+
return {
|
|
69
|
+
input: () => (captured as { input: unknown[] }).input,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
// Chat Completions transport harness
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
type ChatChunk = {
|
|
78
|
+
choices: Array<{
|
|
79
|
+
delta: { content?: string | null };
|
|
80
|
+
finish_reason?: string | null;
|
|
81
|
+
}>;
|
|
82
|
+
usage?: { prompt_tokens: number; completion_tokens: number };
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const CHAT_OK_CHUNKS: ChatChunk[] = [
|
|
86
|
+
{
|
|
87
|
+
choices: [{ delta: { content: "ok" }, finish_reason: "stop" }],
|
|
88
|
+
usage: { prompt_tokens: 10, completion_tokens: 2 },
|
|
89
|
+
},
|
|
90
|
+
];
|
|
91
|
+
|
|
92
|
+
function makeChunkStream(chunks: ChatChunk[]): AsyncIterable<ChatChunk> {
|
|
93
|
+
return {
|
|
94
|
+
async *[Symbol.asyncIterator]() {
|
|
95
|
+
for (const chunk of chunks) {
|
|
96
|
+
yield chunk;
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
type ChatMessageParam = {
|
|
103
|
+
role: string;
|
|
104
|
+
content: string | Array<Record<string, unknown>>;
|
|
105
|
+
tool_call_id?: string;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/** Swap chat `create` for a canned stream that records request params. */
|
|
109
|
+
function stubChatCreate(provider: OpenAIChatCompletionsProvider): {
|
|
110
|
+
messages: () => ChatMessageParam[];
|
|
111
|
+
} {
|
|
112
|
+
let captured: unknown;
|
|
113
|
+
const inner = provider as unknown as {
|
|
114
|
+
client: {
|
|
115
|
+
chat: {
|
|
116
|
+
completions: {
|
|
117
|
+
create: (params: unknown) => Promise<AsyncIterable<ChatChunk>>;
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
inner.client.chat.completions.create = async (params) => {
|
|
123
|
+
captured = params;
|
|
124
|
+
return makeChunkStream(CHAT_OK_CHUNKS);
|
|
125
|
+
};
|
|
126
|
+
return {
|
|
127
|
+
messages: () => (captured as { messages: ChatMessageParam[] }).messages,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
// Fixtures
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Persisted tool id shapes: `call_` is the Responses-native pass-through
|
|
137
|
+
* (conversations that always ran on this transport), `toolu_` is an
|
|
138
|
+
* Anthropic-shaped history routed to an OpenAI call site (cross-provider
|
|
139
|
+
* routing, e.g. a compaction call over imported history). The guard must be
|
|
140
|
+
* id-format-agnostic, so every case runs across both.
|
|
141
|
+
*/
|
|
142
|
+
const ID_SHAPES = [
|
|
143
|
+
{ label: "call_ ids", pairedId: "call_paired", orphanId: "call_orphan" },
|
|
144
|
+
{ label: "toolu_ ids", pairedId: "toolu_paired", orphanId: "toolu_orphan" },
|
|
145
|
+
] as const;
|
|
146
|
+
|
|
147
|
+
/** History whose tool_result is paired with a preceding tool_use. */
|
|
148
|
+
function pairedHistory(id: string): Message[] {
|
|
149
|
+
return [
|
|
150
|
+
{ role: "user", content: [{ type: "text", text: "Read the file" }] },
|
|
151
|
+
{
|
|
152
|
+
role: "assistant",
|
|
153
|
+
content: [
|
|
154
|
+
{
|
|
155
|
+
type: "tool_use",
|
|
156
|
+
id,
|
|
157
|
+
name: "file_read",
|
|
158
|
+
input: { path: "/tmp/a" },
|
|
159
|
+
},
|
|
160
|
+
],
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
role: "user",
|
|
164
|
+
content: [
|
|
165
|
+
{
|
|
166
|
+
type: "tool_result",
|
|
167
|
+
tool_use_id: id,
|
|
168
|
+
content: "file contents",
|
|
169
|
+
},
|
|
170
|
+
],
|
|
171
|
+
},
|
|
172
|
+
];
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* History whose leading tool_result has no matching tool_use anywhere in
|
|
177
|
+
* the request (the shape a pairing-blind front truncation produces).
|
|
178
|
+
*/
|
|
179
|
+
function orphanHistory(id: string): Message[] {
|
|
180
|
+
return [
|
|
181
|
+
{
|
|
182
|
+
role: "user",
|
|
183
|
+
content: [
|
|
184
|
+
{
|
|
185
|
+
type: "tool_result",
|
|
186
|
+
tool_use_id: id,
|
|
187
|
+
content: "stranded output",
|
|
188
|
+
},
|
|
189
|
+
{ type: "text", text: "continue from here" },
|
|
190
|
+
],
|
|
191
|
+
},
|
|
192
|
+
{ role: "assistant", content: [{ type: "text", text: "continuing" }] },
|
|
193
|
+
{ role: "user", content: [{ type: "text", text: "thanks" }] },
|
|
194
|
+
];
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* A tool_result that arrives BEFORE its tool_use in the request order. The
|
|
199
|
+
* API contract only accepts backward matches, so this is orphaned too.
|
|
200
|
+
*/
|
|
201
|
+
function forwardReferenceHistory(): Message[] {
|
|
202
|
+
return [
|
|
203
|
+
{
|
|
204
|
+
role: "user",
|
|
205
|
+
content: [
|
|
206
|
+
{
|
|
207
|
+
type: "tool_result",
|
|
208
|
+
tool_use_id: "call_later",
|
|
209
|
+
content: "premature output",
|
|
210
|
+
},
|
|
211
|
+
{ type: "text", text: "odd ordering" },
|
|
212
|
+
],
|
|
213
|
+
},
|
|
214
|
+
{
|
|
215
|
+
role: "assistant",
|
|
216
|
+
content: [
|
|
217
|
+
{
|
|
218
|
+
type: "tool_use",
|
|
219
|
+
id: "call_later",
|
|
220
|
+
name: "file_read",
|
|
221
|
+
input: { path: "/tmp/b" },
|
|
222
|
+
},
|
|
223
|
+
],
|
|
224
|
+
},
|
|
225
|
+
{
|
|
226
|
+
role: "user",
|
|
227
|
+
content: [
|
|
228
|
+
{
|
|
229
|
+
type: "tool_result",
|
|
230
|
+
tool_use_id: "call_later",
|
|
231
|
+
content: "real output",
|
|
232
|
+
},
|
|
233
|
+
],
|
|
234
|
+
},
|
|
235
|
+
];
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ---------------------------------------------------------------------------
|
|
239
|
+
// Responses transport
|
|
240
|
+
// ---------------------------------------------------------------------------
|
|
241
|
+
|
|
242
|
+
describe("OpenAIResponsesProvider orphan tool_result guard", () => {
|
|
243
|
+
for (const shape of ID_SHAPES) {
|
|
244
|
+
test(`emits function_call_output for a paired tool_result (${shape.label})`, async () => {
|
|
245
|
+
const provider = new OpenAIResponsesProvider("sk-test", "gpt-5.2");
|
|
246
|
+
const stub = stubResponsesCreate(provider);
|
|
247
|
+
|
|
248
|
+
await provider.sendMessage(pairedHistory(shape.pairedId));
|
|
249
|
+
|
|
250
|
+
const input = stub.input() as Array<Record<string, unknown>>;
|
|
251
|
+
expect(input).toHaveLength(3);
|
|
252
|
+
expect(input[1]).toEqual({
|
|
253
|
+
type: "function_call",
|
|
254
|
+
call_id: shape.pairedId,
|
|
255
|
+
name: "file_read",
|
|
256
|
+
arguments: '{"path":"/tmp/a"}',
|
|
257
|
+
});
|
|
258
|
+
expect(input[2]).toEqual({
|
|
259
|
+
type: "function_call_output",
|
|
260
|
+
call_id: shape.pairedId,
|
|
261
|
+
output: "file contents",
|
|
262
|
+
});
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
test(`degrades an orphaned tool_result to user text instead of function_call_output (${shape.label})`, async () => {
|
|
266
|
+
const provider = new OpenAIResponsesProvider("sk-test", "gpt-5.2");
|
|
267
|
+
const stub = stubResponsesCreate(provider);
|
|
268
|
+
|
|
269
|
+
await provider.sendMessage(orphanHistory(shape.orphanId));
|
|
270
|
+
|
|
271
|
+
const input = stub.input() as Array<Record<string, unknown>>;
|
|
272
|
+
// No function_call_output items at all: the only tool_result was
|
|
273
|
+
// orphaned.
|
|
274
|
+
expect(input.some((item) => item.type === "function_call_output")).toBe(
|
|
275
|
+
false,
|
|
276
|
+
);
|
|
277
|
+
|
|
278
|
+
// The orphan's content is preserved as prefixed text inside the user
|
|
279
|
+
// message, alongside the message's own text.
|
|
280
|
+
const firstUser = input[0] as {
|
|
281
|
+
type: string;
|
|
282
|
+
role: string;
|
|
283
|
+
content: Array<{ type: string; text?: string }>;
|
|
284
|
+
};
|
|
285
|
+
expect(firstUser.type).toBe("message");
|
|
286
|
+
expect(firstUser.role).toBe("user");
|
|
287
|
+
const texts = firstUser.content.map((part) => part.text ?? "");
|
|
288
|
+
expect(texts).toContain("continue from here");
|
|
289
|
+
expect(texts).toContain("[orphaned tool result] stranded output");
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
test("treats a forward-referencing tool_result as orphaned, keeps the backward match", async () => {
|
|
294
|
+
const provider = new OpenAIResponsesProvider("sk-test", "gpt-5.2");
|
|
295
|
+
const stub = stubResponsesCreate(provider);
|
|
296
|
+
|
|
297
|
+
await provider.sendMessage(forwardReferenceHistory());
|
|
298
|
+
|
|
299
|
+
const input = stub.input() as Array<Record<string, unknown>>;
|
|
300
|
+
const outputs = input.filter(
|
|
301
|
+
(item) => item.type === "function_call_output",
|
|
302
|
+
);
|
|
303
|
+
// Only the tool_result AFTER the function_call serializes as an output.
|
|
304
|
+
expect(outputs).toEqual([
|
|
305
|
+
{
|
|
306
|
+
type: "function_call_output",
|
|
307
|
+
call_id: "call_later",
|
|
308
|
+
output: "real output",
|
|
309
|
+
},
|
|
310
|
+
]);
|
|
311
|
+
// The premature result is degraded into the first user message.
|
|
312
|
+
const firstUser = input[0] as {
|
|
313
|
+
content: Array<{ type: string; text?: string }>;
|
|
314
|
+
};
|
|
315
|
+
const texts = firstUser.content.map((part) => part.text ?? "");
|
|
316
|
+
expect(texts).toContain("[orphaned tool result] premature output");
|
|
317
|
+
});
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
// ---------------------------------------------------------------------------
|
|
321
|
+
// Chat Completions transport
|
|
322
|
+
// ---------------------------------------------------------------------------
|
|
323
|
+
|
|
324
|
+
describe("OpenAIChatCompletionsProvider orphan tool_result guard", () => {
|
|
325
|
+
function makeProvider(): OpenAIChatCompletionsProvider {
|
|
326
|
+
return new OpenAIChatCompletionsProvider("sk-test", "test-model", {
|
|
327
|
+
providerName: "openai",
|
|
328
|
+
providerLabel: "OpenAI",
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
for (const shape of ID_SHAPES) {
|
|
333
|
+
test(`emits a tool message for a paired tool_result (${shape.label})`, async () => {
|
|
334
|
+
const provider = makeProvider();
|
|
335
|
+
const stub = stubChatCreate(provider);
|
|
336
|
+
|
|
337
|
+
await provider.sendMessage(pairedHistory(shape.pairedId));
|
|
338
|
+
|
|
339
|
+
const sent = stub.messages();
|
|
340
|
+
const toolMessages = sent.filter((message) => message.role === "tool");
|
|
341
|
+
expect(toolMessages).toEqual([
|
|
342
|
+
{
|
|
343
|
+
role: "tool",
|
|
344
|
+
tool_call_id: shape.pairedId,
|
|
345
|
+
content: "file contents",
|
|
346
|
+
},
|
|
347
|
+
]);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
test(`degrades an orphaned tool_result to user text instead of a tool message (${shape.label})`, async () => {
|
|
351
|
+
const provider = makeProvider();
|
|
352
|
+
const stub = stubChatCreate(provider);
|
|
353
|
+
|
|
354
|
+
await provider.sendMessage(orphanHistory(shape.orphanId));
|
|
355
|
+
|
|
356
|
+
const sent = stub.messages();
|
|
357
|
+
expect(sent.some((message) => message.role === "tool")).toBe(false);
|
|
358
|
+
|
|
359
|
+
const firstUser = sent.find((message) => message.role === "user");
|
|
360
|
+
expect(firstUser).toBeDefined();
|
|
361
|
+
const content = firstUser!.content;
|
|
362
|
+
const texts = Array.isArray(content)
|
|
363
|
+
? content.map((part) => (part.text as string) ?? "")
|
|
364
|
+
: [content];
|
|
365
|
+
expect(texts).toContain("continue from here");
|
|
366
|
+
expect(texts).toContain("[orphaned tool result] stranded output");
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
test("treats a forward-referencing tool_result as orphaned, keeps the backward match", async () => {
|
|
371
|
+
const provider = makeProvider();
|
|
372
|
+
const stub = stubChatCreate(provider);
|
|
373
|
+
|
|
374
|
+
await provider.sendMessage(forwardReferenceHistory());
|
|
375
|
+
|
|
376
|
+
const sent = stub.messages();
|
|
377
|
+
const toolMessages = sent.filter((message) => message.role === "tool");
|
|
378
|
+
expect(toolMessages).toEqual([
|
|
379
|
+
{
|
|
380
|
+
role: "tool",
|
|
381
|
+
tool_call_id: "call_later",
|
|
382
|
+
content: "real output",
|
|
383
|
+
},
|
|
384
|
+
]);
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
// ---------------------------------------------------------------------------
|
|
389
|
+
// Cross-transport agreement
|
|
390
|
+
// ---------------------------------------------------------------------------
|
|
391
|
+
|
|
392
|
+
describe("orphan degradation agrees across both OpenAI transports", () => {
|
|
393
|
+
/** Every degraded orphan text a request carried, in request order. */
|
|
394
|
+
async function responsesOrphanTexts(history: Message[]): Promise<string[]> {
|
|
395
|
+
const provider = new OpenAIResponsesProvider("sk-test", "gpt-5.2");
|
|
396
|
+
const stub = stubResponsesCreate(provider);
|
|
397
|
+
await provider.sendMessage(history);
|
|
398
|
+
const input = stub.input() as Array<Record<string, unknown>>;
|
|
399
|
+
return input
|
|
400
|
+
.flatMap((item) =>
|
|
401
|
+
Array.isArray(item.content) ? (item.content as unknown[]) : [],
|
|
402
|
+
)
|
|
403
|
+
.map((part) => (part as { text?: string }).text ?? "")
|
|
404
|
+
.filter((text) => text.startsWith("[orphaned"));
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async function chatOrphanTexts(history: Message[]): Promise<string[]> {
|
|
408
|
+
const provider = new OpenAIChatCompletionsProvider(
|
|
409
|
+
"sk-test",
|
|
410
|
+
"test-model",
|
|
411
|
+
{
|
|
412
|
+
providerName: "openai",
|
|
413
|
+
providerLabel: "OpenAI",
|
|
414
|
+
},
|
|
415
|
+
);
|
|
416
|
+
const stub = stubChatCreate(provider);
|
|
417
|
+
await provider.sendMessage(history);
|
|
418
|
+
return (
|
|
419
|
+
stub
|
|
420
|
+
.messages()
|
|
421
|
+
// A user message carrying a single text part serializes as a plain
|
|
422
|
+
// string on this transport rather than a one-element array.
|
|
423
|
+
.flatMap((message) =>
|
|
424
|
+
Array.isArray(message.content)
|
|
425
|
+
? (message.content as unknown[]).map(
|
|
426
|
+
(part) => (part as { text?: string }).text ?? "",
|
|
427
|
+
)
|
|
428
|
+
: [String(message.content ?? "")],
|
|
429
|
+
)
|
|
430
|
+
.filter((text) => text.startsWith("[orphaned"))
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// The detection rule and the degraded wording live in one shared helper
|
|
435
|
+
// (`serializeToolResult`), so the two transports cannot drift into
|
|
436
|
+
// different markers for the same input. Byte equality is the assertion:
|
|
437
|
+
// re-inlining the rule in one converter and editing it there fails here,
|
|
438
|
+
// which is the regression this pins.
|
|
439
|
+
test("both transports degrade the same orphan to byte-identical text", async () => {
|
|
440
|
+
const history = orphanHistory("call_orphan");
|
|
441
|
+
|
|
442
|
+
const [fromResponses, fromChat] = await Promise.all([
|
|
443
|
+
responsesOrphanTexts(history),
|
|
444
|
+
chatOrphanTexts(history),
|
|
445
|
+
]);
|
|
446
|
+
|
|
447
|
+
expect(fromResponses).toEqual(["[orphaned tool result] stranded output"]);
|
|
448
|
+
expect(fromChat).toEqual(fromResponses);
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
test("both transports carry an executor failure into the same degraded text", async () => {
|
|
452
|
+
// `is_error` prefixing is part of the shared payload rule, so it must
|
|
453
|
+
// survive degradation identically on both transports.
|
|
454
|
+
const history: Message[] = [
|
|
455
|
+
{
|
|
456
|
+
role: "user",
|
|
457
|
+
content: [
|
|
458
|
+
{
|
|
459
|
+
type: "tool_result",
|
|
460
|
+
tool_use_id: "call_orphan",
|
|
461
|
+
content: "boom",
|
|
462
|
+
is_error: true,
|
|
463
|
+
},
|
|
464
|
+
],
|
|
465
|
+
},
|
|
466
|
+
{ role: "assistant", content: [{ type: "text", text: "continuing" }] },
|
|
467
|
+
{ role: "user", content: [{ type: "text", text: "thanks" }] },
|
|
468
|
+
];
|
|
469
|
+
|
|
470
|
+
const [fromResponses, fromChat] = await Promise.all([
|
|
471
|
+
responsesOrphanTexts(history),
|
|
472
|
+
chatOrphanTexts(history),
|
|
473
|
+
]);
|
|
474
|
+
|
|
475
|
+
expect(fromResponses).toEqual(["[orphaned tool result] [ERROR] boom"]);
|
|
476
|
+
expect(fromChat).toEqual(fromResponses);
|
|
477
|
+
});
|
|
478
|
+
});
|