Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(heterogeneous-agent): make the server-default binding usable end to end (#18621)

LiJian5cf4638a1c65
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts
index 5c13a6290e4..c7c49c03d68 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts
@@ -81,9 +81,41 @@ describe('codexDriver provider binding', () => {
max_context_window: 1_048_576,
shell_type: 'unified_exec',
slug: `lobehub/${selectedModel}`,
+ supports_parallel_tool_calls: true,
supports_reasoning_summary_parameter: false,
truncation_policy: { limit: 10_000, mode: truncationMode },
});
+ // The whole key set, not a sample. codex-cli rejects the catalog outright
+ // on a field it requires and we do not write β€” it failed to parse for
+ // `supports_parallel_tool_calls` while the `toMatchObject` above passed,
+ // because a partial match cannot see what is missing. Any key added or
+ // dropped here should be a decision, so it fails this list first.
+ expect(Object.keys(model).sort()).toEqual([
+ 'apply_patch_tool_type',
+ 'availability_nux',
+ 'base_instructions',
+ 'context_window',
+ 'default_reasoning_level',
+ 'default_reasoning_summary',
+ 'default_verbosity',
+ 'description',
+ 'display_name',
+ 'effective_context_window_percent',
+ 'experimental_supported_tools',
+ 'input_modalities',
+ 'max_context_window',
+ 'priority',
+ 'shell_type',
+ 'slug',
+ 'support_verbosity',
+ 'supported_in_api',
+ 'supported_reasoning_levels',
+ 'supports_parallel_tool_calls',
+ 'supports_reasoning_summary_parameter',
+ 'truncation_policy',
+ 'upgrade',
+ 'visibility',
+ ]);
expect(
model.supported_reasoning_levels.map(({ effort }: { effort: string }) => effort),
).toEqual(reasoningLevels);
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts
index bd5d4ae6f24..c7b33102b46 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts
@@ -146,6 +146,18 @@ const buildServerDefaultModelCatalog = (
support_verbosity: false,
supported_in_api: true,
supported_reasoning_levels: supportedReasoningLevels,
+ // Required by codex-cli's catalog schema β€” it has no serde default, so
+ // omitting it fails the whole file to parse ("missing field
+ // `supports_parallel_tool_calls`") before the agent ever starts, with
+ // nothing in the message tying it to this builder.
+ //
+ // `true` because the relay genuinely fans out: the responses encoder
+ // walks its whole tool map and emits one `function_call` output item
+ // per call, each with its own `output_index`. Codex may also send
+ // `parallel_tool_calls` back on the request; `normalizeResponsesRequest`
+ // reads only the fields it knows, so that is dropped rather than
+ // forwarded to an upstream that might reject it.
+ supports_parallel_tool_calls: true,
supports_reasoning_summary_parameter: false,
truncation_policy: { limit: 10_000, mode: metadata.truncationMode },
upgrade: null,
diff --git a/packages/model-runtime/src/providers/volcengine/index.test.ts b/packages/model-runtime/src/providers/volcengine/index.test.ts
index 74fc837faa2..f3778935249 100644
--- a/packages/model-runtime/src/providers/volcengine/index.test.ts
+++ b/packages/model-runtime/src/providers/volcengine/index.test.ts
@@ -121,5 +121,44 @@ describe('LobeVolcengineAI - custom features', () => {
expect(calledPayload.thinking).toEqual({ type: 'enabled' });
expect(calledPayload.reasoning.effort).toBe('high');
});
+
+ /**
+ * `adaptive` is in the runtime's own `thinking.type` union β€” it is Anthropic's
+ * "let the model decide" β€” and Ark answers it with
+ * `invalid value adaptive`, failing the whole request.
+ *
+ * It is not a synthetic input: `/api/v1/anthropic` relays an Anthropic
+ * client's body, and Claude Code sends `thinking: {type: 'adaptive'}` on
+ * every request whatever model it has been pointed at. Both model families
+ * are covered because they take different branches here β€” the reasoning-effort
+ * family used to fall past its `disabled` / `enabled` cases, and everything
+ * else skipped the branch entirely.
+ */
+ it.each(['doubao-seed-2-1-pro-260628', 'deepseek-v4-pro-260425'])(
+ 'drops a thinking type Ark does not accept, for %s',
+ async (model) => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model,
+ thinking: { type: 'adaptive' },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload).not.toHaveProperty('thinking');
+ },
+ );
+
+ it('still honours reasoning_effort when the thinking type was dropped', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'deepseek-v4-pro-260425',
+ reasoning_effort: 'low',
+ thinking: { type: 'adaptive' },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.thinking).toEqual({ type: 'enabled' });
+ expect(calledPayload.reasoning_effort).toBe('low');
+ });
});
});
diff --git a/packages/model-runtime/src/providers/volcengine/index.ts b/packages/model-runtime/src/providers/volcengine/index.ts
index a6d1c9eaffe..99daade7fc3 100644
--- a/packages/model-runtime/src/providers/volcengine/index.ts
+++ b/packages/model-runtime/src/providers/volcengine/index.ts
@@ -12,13 +12,36 @@ const isVolcengineReasoningEffortModel = (model: string) => {
return normalizedModel.includes('deepseek-v4') || normalizedModel.includes('glm-5-2');
};
+/**
+ * `thinking.type` values Ark accepts. The runtime's own union is wider β€” it also
+ * carries `adaptive`, which is Anthropic's "let the model decide" and which Ark
+ * rejects outright:
+ *
+ * The parameter `type` specified in the request are not valid:
+ * invalid value adaptive.
+ *
+ * That reached here from a real caller, not a hypothetical one: `/api/v1/anthropic`
+ * relays an Anthropic client's request body, and Claude Code sends
+ * `thinking: {type: 'adaptive'}` on every request regardless of which model it
+ * has been pointed at. Forwarding whatever arrived turned that into a 400 on
+ * every turn.
+ *
+ * Anything outside this set is dropped rather than translated. Omitting the
+ * field leaves Ark on the model's own default, which is what "let the model
+ * decide" asks for β€” and unlike a guessed mapping it cannot fail the request.
+ */
+const ARK_THINKING_TYPES = new Set(['enabled', 'disabled']);
+
+const arkThinking = (thinking: any) =>
+ ARK_THINKING_TYPES.has(thinking?.type) ? thinking : undefined;
+
const resolveVolcengineReasoningParams = (
model: string,
thinking: any,
reasoning_effort: any,
isResponses = false,
) => {
- let targetThinking = thinking;
+ let targetThinking = arkThinking(thinking);
let targetReasoningEffort = reasoning_effort;
if (isVolcengineReasoningEffortModel(model)) {
diff --git a/packages/openapi/src/routes/anthropic.route.ts b/packages/openapi/src/routes/anthropic.route.ts
index 1a8fdd78faf..9f1cc3b1c4f 100644
--- a/packages/openapi/src/routes/anthropic.route.ts
+++ b/packages/openapi/src/routes/anthropic.route.ts
@@ -11,6 +11,7 @@ import type { HeteroOperationJwtClaims } from '@/libs/trpc/utils/internalJwt';
import { requireHeteroModelInvocation } from '../middleware/hetero-operation-auth';
import {
+ describeRelayFailure,
encodeAnthropicStream,
invokeServerDefaultModel,
normalizeAnthropicRequest,
@@ -35,15 +36,32 @@ app.post('/v1/messages', requireHeteroModelInvocation, async (c) => {
}
const workspaceId = context.get('workspaceId');
const requestModel = formatServerDefaultHeterogeneousModel(claims.model);
- const { response } = await invokeServerDefaultModel({
- agentType: 'claude-code',
- model: claims.model,
- payload: normalizeAnthropicRequest(request, SERVER_DEFAULT_MODEL_ALIAS),
- signal: c.req.raw.signal,
- userId: String(context.get('userId')),
- workspaceId: typeof workspaceId === 'string' ? workspaceId : undefined,
- });
- return new Response(encodeAnthropicStream(response.body!, requestModel), {
+
+ // Anything the model runtime throws has to be turned into an Anthropic error
+ // envelope here. Letting it escape hands the client a bodyless 500 β€” see
+ // `describeRelayFailure` for what that cost.
+ let body: ReadableStream<Uint8Array> | null;
+ try {
+ const { response } = await invokeServerDefaultModel({
+ agentType: 'claude-code',
+ model: claims.model,
+ payload: normalizeAnthropicRequest(request, SERVER_DEFAULT_MODEL_ALIAS),
+ signal: c.req.raw.signal,
+ userId: String(context.get('userId')),
+ workspaceId: typeof workspaceId === 'string' ? workspaceId : undefined,
+ });
+ body = response.body;
+ } catch (error) {
+ const { message, status } = describeRelayFailure(error);
+ return c.json({ error: { message, type: 'api_error' }, type: 'error' }, status);
+ }
+ if (!body) {
+ return c.json(
+ { error: { message: 'Upstream returned no stream', type: 'api_error' }, type: 'error' },
+ 502,
+ );
+ }
+ return new Response(encodeAnthropicStream(body, requestModel), {
headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'text/event-stream' },
});
});
diff --git a/packages/openapi/src/routes/heterogeneous-relay.route.test.ts b/packages/openapi/src/routes/heterogeneous-relay.route.test.ts
new file mode 100644
index 00000000000..fb2da3bfd47
--- /dev/null
+++ b/packages/openapi/src/routes/heterogeneous-relay.route.test.ts
@@ -0,0 +1,86 @@
+import type { MiddlewareHandler } from 'hono';
+import { Hono } from 'hono';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as HeterogeneousDirectService from '../services/heterogeneous-direct.service';
+
+const invokeServerDefaultModel = vi.hoisted(() => vi.fn());
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromServerConfig: vi.fn(),
+ resolveServerDefaultHeterogeneousModel: vi.fn(),
+}));
+vi.mock('../middleware/hetero-operation-auth', () => {
+ const requireHeteroModelInvocation: MiddlewareHandler = async (c, next) => {
+ c.set(
+ 'heteroOperationClaims' as never,
+ { model: 'deepseek-v4-pro', provider_id: 'lobehub' } as never,
+ );
+ c.set('userId' as never, 'user-1' as never);
+ await next();
+ };
+
+ return { requireHeteroModelInvocation };
+});
+vi.mock('../services/heterogeneous-direct.service', async (importOriginal) => {
+ const actual = await importOriginal<typeof HeterogeneousDirectService>();
+ return { ...actual, invokeServerDefaultModel };
+});
+
+const [{ default: anthropicRoutes }, { default: openaiRoutes }] = await Promise.all([
+ import('./anthropic.route'),
+ import('./openai.route'),
+]);
+
+const app = new Hono();
+app.route('/anthropic', anthropicRoutes);
+app.route('/openai', openaiRoutes);
+
+const runtimeFailure = {
+ error: { message: 'invalid value adaptive' },
+ errorType: 'ProviderBizError',
+ provider: 'volcengine',
+};
+const failureMessage = '[volcengine] ProviderBizError: invalid value adaptive';
+
+describe('heterogeneous relay route failures', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ invokeServerDefaultModel.mockRejectedValue(runtimeFailure);
+ });
+
+ it('returns an Anthropic error envelope when model invocation rejects', async () => {
+ const response = await app.request('/anthropic/v1/messages', {
+ body: JSON.stringify({
+ messages: [{ content: 'hello', role: 'user' }],
+ model: 'lobehub/deepseek-v4-pro',
+ stream: true,
+ }),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ });
+
+ expect(response.status).toBe(502);
+ await expect(response.json()).resolves.toEqual({
+ error: { message: failureMessage, type: 'api_error' },
+ type: 'error',
+ });
+ });
+
+ it('returns an OpenAI error envelope when model invocation rejects', async () => {
+ const response = await app.request('/openai/v1/responses', {
+ body: JSON.stringify({
+ input: 'hello',
+ model: 'lobehub/deepseek-v4-pro',
+ stream: true,
+ }),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ });
+
+ expect(response.status).toBe(502);
+ await expect(response.json()).resolves.toEqual({
+ error: { message: failureMessage, type: 'api_error' },
+ });
+ });
+});
diff --git a/packages/openapi/src/routes/openai.route.ts b/packages/openapi/src/routes/openai.route.ts
index 9f7031b76e6..68bde20d1dc 100644
--- a/packages/openapi/src/routes/openai.route.ts
+++ b/packages/openapi/src/routes/openai.route.ts
@@ -11,6 +11,7 @@ import type { HeteroOperationJwtClaims } from '@/libs/trpc/utils/internalJwt';
import { requireHeteroModelInvocation } from '../middleware/hetero-operation-auth';
import {
+ describeRelayFailure,
encodeResponsesStream,
invokeServerDefaultModel,
normalizeResponsesRequest,
@@ -35,15 +36,28 @@ app.post('/v1/responses', requireHeteroModelInvocation, async (c) => {
}
const workspaceId = context.get('workspaceId');
const requestModel = formatServerDefaultHeterogeneousModel(claims.model);
- const { response } = await invokeServerDefaultModel({
- agentType: 'codex',
- model: claims.model,
- payload: normalizeResponsesRequest(request, SERVER_DEFAULT_MODEL_ALIAS),
- signal: c.req.raw.signal,
- userId: String(context.get('userId')),
- workspaceId: typeof workspaceId === 'string' ? workspaceId : undefined,
- });
- return new Response(encodeResponsesStream(response.body!, requestModel), {
+
+ // Same reasoning as the Anthropic relay: an escaping runtime rejection reaches
+ // the client as a bodyless 500. See `describeRelayFailure`.
+ let body: ReadableStream<Uint8Array> | null;
+ try {
+ const { response } = await invokeServerDefaultModel({
+ agentType: 'codex',
+ model: claims.model,
+ payload: normalizeResponsesRequest(request, SERVER_DEFAULT_MODEL_ALIAS),
+ signal: c.req.raw.signal,
+ userId: String(context.get('userId')),
+ workspaceId: typeof workspaceId === 'string' ? workspaceId : undefined,
+ });
+ body = response.body;
+ } catch (error) {
+ const { message, status } = describeRelayFailure(error);
+ return c.json({ error: { message, type: 'api_error' } }, status);
+ }
+ if (!body) {
+ return c.json({ error: { message: 'Upstream returned no stream', type: 'api_error' } }, 502);
+ }
+ return new Response(encodeResponsesStream(body, requestModel), {
headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'text/event-stream' },
});
});
diff --git a/packages/openapi/src/services/heterogeneous-direct.service.test.ts b/packages/openapi/src/services/heterogeneous-direct.service.test.ts
index 77a2dd75ce6..2b726f8c71e 100644
--- a/packages/openapi/src/services/heterogeneous-direct.service.test.ts
+++ b/packages/openapi/src/services/heterogeneous-direct.service.test.ts
@@ -6,6 +6,7 @@ import {
} from '@/server/modules/ModelRuntime';
import {
+ describeRelayFailure,
encodeAnthropicStream,
encodeResponsesStream,
invokeServerDefaultModel,
@@ -60,7 +61,7 @@ describe('heterogeneous direct invocation protocol', () => {
vi.clearAllMocks();
});
- it('invokes Claude Code through an Anthropic-compatible LobeHub relay model', async () => {
+ it('preserves adaptive thinking through the Anthropic relay for a compatible model', async () => {
const chat = vi.fn().mockResolvedValue(new Response('stream'));
vi.mocked(resolveServerDefaultHeterogeneousModel).mockResolvedValue({
model: 'claude-sonnet-4-6',
@@ -74,12 +75,15 @@ describe('heterogeneous direct invocation protocol', () => {
const result = await invokeServerDefaultModel({
agentType: 'claude-code',
model: 'claude-sonnet-4-6',
- payload: {
- messages: [],
- model: 'lobehub-default',
- stream: true,
- thinking: { type: 'adaptive' },
- },
+ payload: normalizeAnthropicRequest(
+ {
+ messages: [],
+ model: 'lobehub-default',
+ stream: true,
+ thinking: { type: 'adaptive' },
+ },
+ 'lobehub-default',
+ ),
signal: new AbortController().signal,
userId: 'user-1',
});
@@ -90,12 +94,12 @@ describe('heterogeneous direct invocation protocol', () => {
'claude-sonnet-4-6',
);
expect(chat).toHaveBeenCalledWith(
- {
+ expect.objectContaining({
messages: [],
model: 'claude-sonnet-4-6',
stream: true,
thinking: { type: 'adaptive' },
- },
+ }),
expect.any(Object),
);
});
@@ -352,6 +356,38 @@ describe('heterogeneous direct invocation protocol', () => {
expect(payload.messages[3].reasoning?.responseItems).toEqual([secondReasoning]);
});
+ it('groups parallel Responses function calls before their contiguous outputs', () => {
+ const reasoning = {
+ encrypted_content: 'encrypted-parallel',
+ id: 'reasoning-parallel',
+ status: 'completed',
+ summary: [{ text: 'parallel thought', type: 'summary_text' }],
+ type: 'reasoning',
+ };
+ const payload = normalizeResponsesRequest(
+ {
+ input: [
+ reasoning,
+ { arguments: '{"q":"x"}', call_id: 'call-1', name: 'search', type: 'function_call' },
+ { arguments: '{"path":"/tmp"}', call_id: 'call-2', name: 'read', type: 'function_call' },
+ { call_id: 'call-1', output: 'search result', type: 'function_call_output' },
+ { call_id: 'call-2', output: 'file result', type: 'function_call_output' },
+ ],
+ },
+ 'lobehub-default',
+ );
+
+ expect(payload.messages.map(({ role }) => role)).toEqual(['assistant', 'tool', 'tool']);
+ expect(payload.messages[0]).toMatchObject({
+ reasoning: { responseItems: [reasoning] },
+ tool_calls: [{ id: 'call-1' }, { id: 'call-2' }],
+ });
+ expect(payload.messages.slice(1).map(({ tool_call_id }) => tool_call_id)).toEqual([
+ 'call-1',
+ 'call-2',
+ ]);
+ });
+
it('parses the final protocol event without a trailing newline', async () => {
const encoder = new TextEncoder();
const source = new ReadableStream<Uint8Array>({
@@ -626,3 +662,52 @@ describe('heterogeneous direct invocation protocol', () => {
expect(completed?.data.response.output).toEqual([reasoningItem]);
});
});
+
+/**
+ * `runtime.chat` rejects with a plain `{ error, errorType, provider }` object
+ * rather than an `Error`. Hono cannot serialise that, so before this helper an
+ * uncaught rejection reached the client as a 500 with an EMPTY body β€” which is
+ * how a Volcengine `invalid value adaptive` looked to Claude Code:
+ * `API Error: 500 status code (no body)`, retried for 98 seconds.
+ */
+describe('describeRelayFailure', () => {
+ it('carries the provider’s own words out of a runtime rejection', () => {
+ expect(
+ describeRelayFailure({
+ error: {
+ message:
+ 'The parameter `type` specified in the request are not valid: invalid value adaptive.',
+ },
+ errorType: 'ProviderBizError',
+ provider: 'volcengine',
+ }),
+ ).toEqual({
+ message:
+ '[volcengine] ProviderBizError: The parameter `type` specified in the request are not valid: invalid value adaptive.',
+ status: 502,
+ });
+ });
+
+ it('falls back to the serialized body when the provider names no message', () => {
+ const { message } = describeRelayFailure({
+ error: { code: 'InvalidParameter' },
+ errorType: 'ProviderBizError',
+ provider: 'volcengine',
+ });
+
+ expect(message).toContain('InvalidParameter');
+ });
+
+ it('still says something for a plain Error', () => {
+ expect(describeRelayFailure(new Error('socket hang up'))).toEqual({
+ message: 'socket hang up',
+ status: 502,
+ });
+ });
+
+ it('never returns an empty message, whatever it was handed', () => {
+ for (const thrown of [undefined, null, '', 0, {}]) {
+ expect(describeRelayFailure(thrown).message).not.toBe('');
+ }
+ });
+});
diff --git a/packages/openapi/src/services/heterogeneous-direct.service.ts b/packages/openapi/src/services/heterogeneous-direct.service.ts
index 34f4de7c41f..d4634021f62 100644
--- a/packages/openapi/src/services/heterogeneous-direct.service.ts
+++ b/packages/openapi/src/services/heterogeneous-direct.service.ts
@@ -205,18 +205,30 @@ export const normalizeResponsesRequest = (request: Record<string, unknown>, mode
>[number],
);
} else if (item.type === 'function_call' && typeof item.call_id === 'string') {
- messages.push({
- content: '',
- role: 'assistant',
- ...takePendingReasoning(),
- tool_calls: [
- {
- function: { arguments: String(item.arguments || ''), name: String(item.name || '') },
- id: item.call_id,
- type: 'function',
- },
- ],
- });
+ const toolCall = {
+ function: { arguments: String(item.arguments || ''), name: String(item.name || '') },
+ id: item.call_id,
+ type: 'function' as const,
+ };
+ const previousMessage = messages.at(-1);
+
+ // Responses history records every parallel call before their outputs.
+ // Chat Completions requires those calls in one assistant message, followed
+ // by the contiguous batch of tool-result messages.
+ if (
+ !pendingReasoningItems?.length &&
+ previousMessage?.role === 'assistant' &&
+ previousMessage.tool_calls?.length
+ ) {
+ previousMessage.tool_calls.push(toolCall);
+ } else {
+ messages.push({
+ content: '',
+ role: 'assistant',
+ ...takePendingReasoning(),
+ tool_calls: [toolCall],
+ });
+ }
} else if (item.type === 'function_call_output' && typeof item.call_id === 'string') {
messages.push({
content: String(item.output || ''),
@@ -900,3 +912,50 @@ export const invokeServerDefaultModel = async (params: {
if (!response.body) throw new Error('Model runtime returned an empty stream');
return { model, response };
};
+
+const readMessage = (value: unknown): string | undefined => {
+ if (typeof value === 'string') return value;
+ if (!isRecord(value)) return undefined;
+ if (typeof value.message === 'string') return value.message;
+ return undefined;
+};
+
+/**
+ * Describe a failed relay in terms its caller can act on.
+ *
+ * `runtime.chat` rejects with a plain `{ error, errorType, provider }` object
+ * rather than an `Error`, and Hono's default handler cannot serialise that: an
+ * uncaught one leaves the client a **500 with an empty body**. That is how an
+ * Ark rejection ("The parameter `type` specified in the request are not valid:
+ * invalid value adaptive") reached Claude Code β€” as `API Error: 500 status code
+ * (no body)`, retried for a minute and a half because nothing in the response
+ * said it could never succeed.
+ *
+ * The upstream's own status is deliberately not forwarded: `handleOpenAIError`
+ * keeps the provider's error body and drops the status whenever there is one,
+ * so any status here would be invented. 502 says what is actually known β€” the
+ * request reached us, and the hop past us failed β€” and the message carries the
+ * provider's own words, which is the part that was missing.
+ */
+export const describeRelayFailure = (error: unknown) => {
+ const payload = isRecord(error) ? error : undefined;
+ const message =
+ readMessage(payload) ??
+ readMessage(payload?.error) ??
+ (payload?.error === undefined ? undefined : JSON.stringify(payload.error)) ??
+ String(error);
+ const provider = typeof payload?.provider === 'string' ? payload.provider : undefined;
+ const errorType = payload?.errorType;
+
+ return {
+ // Never empty. A blank message here would put the caller back where the
+ // bodyless 500 left it β€” a failure with no way to tell what failed β€” and
+ // `String(error)` is blank for a thrown empty string.
+ message:
+ [provider && `[${provider}]`, errorType && `${String(errorType)}:`, message]
+ .filter(Boolean)
+ .join(' ')
+ .trim() || 'Model runtime failed without a message',
+ status: 502 as const,
+ };
+};