@vellumai/assistant 0.11.0-dev.202607291933.89ba5c5 → 0.11.0-dev.202607292123.71bf9cf

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/openapi.yaml CHANGED
@@ -14833,6 +14833,25 @@ paths:
14833
14833
  properties:
14834
14834
  resolved_endpoint:
14835
14835
  type: string
14836
+ resolved_url:
14837
+ type: string
14838
+ model_id:
14839
+ type: string
14840
+ connection_name:
14841
+ type: string
14842
+ http_status:
14843
+ type: number
14844
+ upstream_error_body:
14845
+ type: string
14846
+ upstream_error_body_state:
14847
+ type: string
14848
+ enum:
14849
+ - captured
14850
+ - empty
14851
+ - truncated
14852
+ - unavailable
14853
+ upstream_error_body_bytes:
14854
+ type: number
14836
14855
  additionalProperties: false
14837
14856
  required:
14838
14857
  - response
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.0-dev.202607291933.89ba5c5",
3
+ "version": "0.11.0-dev.202607292123.71bf9cf",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -25,6 +25,23 @@ import { attachSessionSubcommand } from "./inference-session.js";
25
25
 
26
26
  // ── Types ────────────────────────────────────────────────────────────
27
27
 
28
+ /**
29
+ * Runtime-observed evidence for one inference request: the endpoint the live
30
+ * client resolved to, the URL actually requested (credentials redacted), the
31
+ * model and connection used, the HTTP status, and the verbatim upstream error
32
+ * body. Reported for failures as well as successes.
33
+ */
34
+ interface InferenceEvidence {
35
+ resolved_endpoint?: string;
36
+ resolved_url?: string;
37
+ model_id?: string;
38
+ connection_name?: string;
39
+ http_status?: number;
40
+ upstream_error_body?: string;
41
+ upstream_error_body_state?: string;
42
+ upstream_error_body_bytes?: number;
43
+ }
44
+
28
45
  interface InferenceSendResult {
29
46
  response: string;
30
47
  model: string;
@@ -32,9 +49,20 @@ interface InferenceSendResult {
32
49
  inputTokens: number;
33
50
  outputTokens: number;
34
51
  };
35
- evidence?: {
36
- resolved_endpoint?: string;
37
- };
52
+ evidence?: InferenceEvidence;
53
+ }
54
+
55
+ /** `RouteError.details` payload of a failed `inference_send`. */
56
+ interface InferenceSendErrorDetails {
57
+ error_class?: string;
58
+ error_stack_head?: string;
59
+ evidence?: InferenceEvidence;
60
+ }
61
+
62
+ function asErrorDetails(value: unknown): InferenceSendErrorDetails {
63
+ return value && typeof value === "object"
64
+ ? (value as InferenceSendErrorDetails)
65
+ : {};
38
66
  }
39
67
 
40
68
  const DEFAULT_INFERENCE_IPC_TIMEOUT_MS = 32 * 60 * 1000;
@@ -76,9 +104,15 @@ function parsePositiveIntegerOption(
76
104
  return { ok: true, value };
77
105
  }
78
106
 
79
- function writeCliError(message: string, jsonOutput?: boolean): void {
107
+ function writeCliError(
108
+ message: string,
109
+ jsonOutput?: boolean,
110
+ details?: InferenceSendErrorDetails,
111
+ ): void {
80
112
  if (jsonOutput) {
81
- process.stdout.write(JSON.stringify({ ok: false, error: message }) + "\n");
113
+ process.stdout.write(
114
+ JSON.stringify({ ok: false, error: message, ...details }) + "\n",
115
+ );
82
116
  } else {
83
117
  log.error(message);
84
118
  }
@@ -171,7 +205,11 @@ function attachSendSubcommand(group: Command): void {
171
205
  );
172
206
 
173
207
  if (!ipcResult.ok) {
174
- writeCliError(ipcResult.error ?? "Unknown error occurred", jsonOutput);
208
+ writeCliError(
209
+ ipcResult.error ?? "Unknown error occurred",
210
+ jsonOutput,
211
+ asErrorDetails(ipcResult.errorDetails),
212
+ );
175
213
  return;
176
214
  }
177
215
 
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Tests for per-request provider diagnostics: what URL went out, what came
3
+ * back, and whether a missing upstream error body means "the upstream sent
4
+ * nothing" or "we failed to read it".
5
+ */
6
+
7
+ import { afterAll, describe, expect, test } from "bun:test";
8
+
9
+ import {
10
+ recordProviderRequestDiagnostics,
11
+ redactUrl,
12
+ runWithProviderRequestDiagnostics,
13
+ } from "../request-diagnostics.js";
14
+
15
+ const server = Bun.serve({
16
+ port: 0,
17
+ fetch(req) {
18
+ const { pathname } = new URL(req.url);
19
+ if (pathname === "/empty-404") {
20
+ return new Response(null, { status: 404 });
21
+ }
22
+ if (pathname === "/verbose-404") {
23
+ return new Response(
24
+ JSON.stringify({ error: { code: 404, message: "model not found" } }),
25
+ { status: 404, headers: { "content-type": "application/json" } },
26
+ );
27
+ }
28
+ return new Response("ok");
29
+ },
30
+ });
31
+ const origin = `http://localhost:${server.port}`;
32
+
33
+ afterAll(() => {
34
+ server.stop(true);
35
+ });
36
+
37
+ describe("redactUrl", () => {
38
+ test("masks credential-bearing query parameters and userinfo", () => {
39
+ // GIVEN a Gemini-style URL that carries the API key in the query string
40
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro:streamGenerateContent?key=super-secret&alt=sse`;
41
+
42
+ // WHEN it is redacted for diagnostics
43
+ const redacted = redactUrl(url);
44
+
45
+ // THEN the path and non-credential params survive verbatim
46
+ expect(redacted).toContain(
47
+ "/v1beta/models/gemini-3-pro:streamGenerateContent",
48
+ );
49
+ expect(redacted).toContain("alt=sse");
50
+
51
+ // AND the key is masked
52
+ expect(redacted).toContain("key=REDACTED");
53
+ expect(redacted).not.toContain("super-secret");
54
+ });
55
+ });
56
+
57
+ describe("runWithProviderRequestDiagnostics", () => {
58
+ test("reports the outbound URL, status and verbatim upstream error body", async () => {
59
+ // GIVEN an upstream that answers a request with a non-empty 404 body
60
+ const path = "/verbose-404?key=super-secret";
61
+
62
+ // WHEN the request runs inside a diagnostics scope
63
+ const outcome = await runWithProviderRequestDiagnostics(async () => {
64
+ recordProviderRequestDiagnostics({
65
+ model_id: "gemini-3-pro",
66
+ connection_name: "gemini-personal",
67
+ });
68
+ const response = await fetch(`${origin}${path}`);
69
+ // The SDK's own read must still work after diagnostics captured the body.
70
+ return response.text();
71
+ });
72
+
73
+ // THEN the call's own body read is unaffected
74
+ expect(outcome.ok).toBe(true);
75
+
76
+ // AND the evidence identifies the exact request and the verbatim response
77
+ expect(outcome.diagnostics).toEqual({
78
+ resolved_url: `${origin}/verbose-404?key=REDACTED`,
79
+ model_id: "gemini-3-pro",
80
+ connection_name: "gemini-personal",
81
+ http_status: 404,
82
+ upstream_error_body: JSON.stringify({
83
+ error: { code: 404, message: "model not found" },
84
+ }),
85
+ upstream_error_body_state: "captured",
86
+ upstream_error_body_bytes: 50,
87
+ });
88
+ });
89
+
90
+ test("distinguishes an upstream that sent no body from a body we never captured", async () => {
91
+ // GIVEN an upstream that answers 404 with an empty body
92
+ // WHEN the request runs inside a diagnostics scope
93
+ const outcome = await runWithProviderRequestDiagnostics(() =>
94
+ fetch(`${origin}/empty-404`),
95
+ );
96
+
97
+ // THEN the emptiness is recorded as an observation, not as missing evidence
98
+ expect(outcome.diagnostics.http_status).toBe(404);
99
+ expect(outcome.diagnostics.upstream_error_body_state).toBe("empty");
100
+ expect(outcome.diagnostics.upstream_error_body_bytes).toBe(0);
101
+ expect(outcome.diagnostics.upstream_error_body).toBeUndefined();
102
+ });
103
+
104
+ test("keeps the diagnostics collected before a thrown failure", async () => {
105
+ // GIVEN a request that fails after reaching the upstream
106
+ const boom = new Error("stream aborted");
107
+
108
+ // WHEN it throws inside the diagnostics scope
109
+ const outcome = await runWithProviderRequestDiagnostics(async () => {
110
+ await fetch(`${origin}/verbose-404`);
111
+ throw boom;
112
+ });
113
+
114
+ // THEN the failure is returned with the evidence gathered up to that point
115
+ expect(outcome).toMatchObject({ ok: false, error: boom });
116
+ expect(outcome.diagnostics.resolved_url).toBe(`${origin}/verbose-404`);
117
+ expect(outcome.diagnostics.http_status).toBe(404);
118
+ });
119
+
120
+ test("leaves requests made outside a scope unrecorded", async () => {
121
+ // GIVEN an outer scope whose work finished
122
+ const outer = await runWithProviderRequestDiagnostics(async () => "done");
123
+
124
+ // WHEN a request is made outside any diagnostics scope
125
+ const response = await fetch(`${origin}/verbose-404`);
126
+
127
+ // THEN it still completes normally and records nothing
128
+ expect(response.status).toBe(404);
129
+ expect(outer.diagnostics).toEqual({});
130
+ });
131
+ });
@@ -17,6 +17,7 @@ import {
17
17
  PLACEHOLDER_BLOCKS_OMITTED,
18
18
  PLACEHOLDER_EMPTY_TURN,
19
19
  } from "../placeholder-sentinels.js";
20
+ import { recordProviderRequestDiagnostics } from "../request-diagnostics.js";
20
21
  import { createStreamTimeout } from "../stream-timeout.js";
21
22
  import type {
22
23
  ContentBlock,
@@ -1346,6 +1347,7 @@ export class AnthropicProvider implements Provider {
1346
1347
 
1347
1348
  let response: Anthropic.Message;
1348
1349
  try {
1350
+ recordProviderRequestDiagnostics({ model_id: params.model });
1349
1351
  const requestHeaders = {
1350
1352
  ...this.requestHeaders,
1351
1353
  ...(usageAttributionHeaders ?? {}),
@@ -37,6 +37,7 @@ import {
37
37
  import { listConnections } from "./inference/connections.js";
38
38
  import type { ProvidersConfig } from "./registry.js";
39
39
  import { shouldUseNativeWebSearch } from "./registry.js";
40
+ import { recordProviderRequestDiagnostics } from "./request-diagnostics.js";
40
41
  import type {
41
42
  Message,
42
43
  Provider,
@@ -266,6 +267,12 @@ export class CallSiteRoutingProvider implements Provider {
266
267
  resolved.model,
267
268
  );
268
269
  if (connectionProvider) {
270
+ // The connection whose credential the call authenticates with is only
271
+ // known here, and diagnostics for a failed request are unactionable
272
+ // without it ("which key was this?"). Recorded once the adapter exists,
273
+ // so a connection that fell back to the default transport is not
274
+ // reported as the one that signed the request.
275
+ recordProviderRequestDiagnostics({ connection_name: connectionName });
269
276
  return connectionProvider;
270
277
  }
271
278
  // Soft credential failure: the routed connection yielded no usable
@@ -12,6 +12,7 @@ import { getLogger } from "../../util/logger.js";
12
12
  import { DAILY_LIMIT_PATTERNS } from "../../util/provider-error-patterns.js";
13
13
  import { base64Source, resolveMediaReferences } from "../media-resolve.js";
14
14
  import { PROVIDER_CATALOG } from "../model-catalog.js";
15
+ import { recordProviderRequestDiagnostics } from "../request-diagnostics.js";
15
16
  import { createStreamTimeout } from "../stream-timeout.js";
16
17
  import type {
17
18
  ContentBlock,
@@ -380,6 +381,7 @@ export class GeminiProvider implements Provider {
380
381
  : undefined;
381
382
 
382
383
  try {
384
+ recordProviderRequestDiagnostics({ model_id: activeModel });
383
385
  const geminiContents = this.toGeminiContents(messages, activeModel);
384
386
 
385
387
  const geminiConfig: genai.GenerateContentConfig = {};
@@ -13,6 +13,7 @@ import {
13
13
  } from "../media-resolve.js";
14
14
  import { modelSupportsAudioInput } from "../model-catalog.js";
15
15
  import { PLACEHOLDER_EMPTY_TURN } from "../placeholder-sentinels.js";
16
+ import { recordProviderRequestDiagnostics } from "../request-diagnostics.js";
16
17
  import { createStreamTimeout } from "../stream-timeout.js";
17
18
  import { createToolProgressEmitter } from "../tool-progress-events.js";
18
19
  import type {
@@ -387,6 +388,10 @@ export class OpenAIChatCompletionsProvider implements Provider {
387
388
  modelSupportsAudioInput(modelOverride ?? this.model),
388
389
  );
389
390
 
391
+ recordProviderRequestDiagnostics({
392
+ model_id: modelOverride ?? this.model,
393
+ });
394
+
390
395
  const params: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming =
391
396
  {
392
397
  model: modelOverride ?? this.model,
@@ -8,6 +8,7 @@ import { extractRetryAfterMs } from "../../util/retry.js";
8
8
  import { escapeXmlAttr } from "../../util/xml.js";
9
9
  import { base64Source, resolveMediaReferences } from "../media-resolve.js";
10
10
  import { PROMPT_CACHE_BREAKPOINT_MODEL_IDS } from "../model-catalog.js";
11
+ import { recordProviderRequestDiagnostics } from "../request-diagnostics.js";
11
12
  import { createStreamTimeout } from "../stream-timeout.js";
12
13
  import { createToolProgressEmitter } from "../tool-progress-events.js";
13
14
  import type {
@@ -241,6 +242,7 @@ export class OpenAIResponsesProvider implements Provider {
241
242
 
242
243
  try {
243
244
  const effectiveModel = modelOverride ?? this.model;
245
+ recordProviderRequestDiagnostics({ model_id: effectiveModel });
244
246
  const input = this.toResponsesInput(messages);
245
247
 
246
248
  const params: Record<string, unknown> = {
@@ -22,6 +22,7 @@ import {
22
22
  } from "./connection-resolution.js";
23
23
  import { listConnections } from "./inference/connections.js";
24
24
  import { initializeProviders, listProviders } from "./registry.js";
25
+ import { recordProviderRequestDiagnostics } from "./request-diagnostics.js";
25
26
  import type {
26
27
  ContentBlock,
27
28
  Message,
@@ -221,6 +222,11 @@ export async function resolveConfiguredProvider(
221
222
  );
222
223
  return null;
223
224
  }
225
+ // Which credential signs the request is only known here, and a failed
226
+ // request is unactionable without it ("which key was this?"). Recorded once
227
+ // the adapter exists, so a connection that resolved to nothing is never
228
+ // reported as the one that signed the request.
229
+ recordProviderRequestDiagnostics({ connection_name: connectionName });
224
230
  return {
225
231
  provider: new CallSiteConfiguredProvider(
226
232
  connectionProvider,
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Per-request outbound diagnostics for LLM provider calls.
3
+ *
4
+ * Diagnosing a provider failure requires knowing what the client actually put
5
+ * on the wire: the resolved URL and path, the model ID sent, the connection
6
+ * whose credential was used, the HTTP status, and the verbatim upstream error
7
+ * body. Provider SDKs surface only a fraction of that (`@google/genai`'s
8
+ * `ApiError` carries a status and a message and nothing else), and error
9
+ * normalization collapses the rest, so "404 with an empty body" and "body
10
+ * dropped on the way here" become indistinguishable.
11
+ *
12
+ * A recorder is bound to the async context for the duration of one provider
13
+ * call. Layers that own a fact write it as they learn it (the routing wrapper
14
+ * knows the connection, the provider client knows the model), and the outbound
15
+ * `fetch` instrumentation records the URL, status, and error body observed on
16
+ * the actual request. Nothing here is re-derived from config.
17
+ */
18
+
19
+ import { AsyncLocalStorage } from "node:async_hooks";
20
+
21
+ /**
22
+ * Whether a raw upstream error body was captured, and if not, why. Callers
23
+ * must be able to tell an upstream that answered with no body from one whose
24
+ * body never reached the diagnostics layer, and those point at different bugs.
25
+ */
26
+ export type UpstreamErrorBodyState =
27
+ | "captured"
28
+ | "empty"
29
+ | "truncated"
30
+ | "unavailable";
31
+
32
+ /** Wire-shaped (snake_case) evidence surfaced to diagnostics consumers. */
33
+ export interface ProviderRequestDiagnostics {
34
+ /** Full outbound URL including path, with credential material redacted. */
35
+ resolved_url?: string;
36
+ /** Model ID as sent to the provider, not as requested by the caller. */
37
+ model_id?: string;
38
+ /** `provider_connections` row whose credential authenticated the request. */
39
+ connection_name?: string;
40
+ /** HTTP status of the outbound response. */
41
+ http_status?: number;
42
+ /** Verbatim upstream error body for a non-2xx response. */
43
+ upstream_error_body?: string;
44
+ upstream_error_body_state?: UpstreamErrorBodyState;
45
+ /** Byte length of the upstream error body before any truncation. */
46
+ upstream_error_body_bytes?: number;
47
+ }
48
+
49
+ /**
50
+ * Ceiling on a retained error body. Bodies are recorded verbatim below it;
51
+ * above it the prefix is kept, the state is `truncated`, and the true length
52
+ * is reported in `upstream_error_body_bytes`, so a large HTML error page can
53
+ * neither be mistaken for an empty body nor exhaust memory.
54
+ */
55
+ const MAX_ERROR_BODY_BYTES = 1_048_576;
56
+
57
+ /**
58
+ * Query parameters that carry credential material. Gemini sends the API key as
59
+ * `?key=`, so a URL is only safe to surface after these are masked.
60
+ */
61
+ const CREDENTIAL_QUERY_PARAMS = new Set([
62
+ "key",
63
+ "api_key",
64
+ "apikey",
65
+ "access_token",
66
+ "token",
67
+ ]);
68
+
69
+ const REDACTED = "REDACTED";
70
+
71
+ /** Mask credential material in a URL so it can be recorded and displayed. */
72
+ export function redactUrl(url: string): string {
73
+ let parsed: URL;
74
+ try {
75
+ parsed = new URL(url);
76
+ } catch {
77
+ return url;
78
+ }
79
+ if (parsed.username) {
80
+ parsed.username = REDACTED;
81
+ }
82
+ if (parsed.password) {
83
+ parsed.password = REDACTED;
84
+ }
85
+ for (const name of [...parsed.searchParams.keys()]) {
86
+ if (CREDENTIAL_QUERY_PARAMS.has(name.toLowerCase())) {
87
+ parsed.searchParams.set(name, REDACTED);
88
+ }
89
+ }
90
+ return parsed.toString();
91
+ }
92
+
93
+ class DiagnosticsRecorder {
94
+ private readonly diagnostics: ProviderRequestDiagnostics = {};
95
+
96
+ record(patch: ProviderRequestDiagnostics): void {
97
+ for (const [key, value] of Object.entries(patch)) {
98
+ if (value !== undefined) {
99
+ Object.assign(this.diagnostics, { [key]: value });
100
+ }
101
+ }
102
+ }
103
+
104
+ snapshot(): ProviderRequestDiagnostics {
105
+ return { ...this.diagnostics };
106
+ }
107
+ }
108
+
109
+ const recorderStorage = new AsyncLocalStorage<DiagnosticsRecorder>();
110
+
111
+ /**
112
+ * Record what is known about the in-flight provider request. A no-op outside a
113
+ * {@link runWithProviderRequestDiagnostics} scope, so call sites on hot paths
114
+ * do not need to branch.
115
+ */
116
+ export function recordProviderRequestDiagnostics(
117
+ patch: ProviderRequestDiagnostics,
118
+ ): void {
119
+ recorderStorage.getStore()?.record(patch);
120
+ }
121
+
122
+ /**
123
+ * Run `fn` with a diagnostics recorder bound to its async context and return
124
+ * everything observed, whether `fn` resolved or threw. The failure path is the
125
+ * one that matters: a probe reports the URL and upstream body of the request
126
+ * that failed.
127
+ */
128
+ export async function runWithProviderRequestDiagnostics<T>(
129
+ fn: () => Promise<T>,
130
+ ): Promise<
131
+ | { ok: true; value: T; diagnostics: ProviderRequestDiagnostics }
132
+ | { ok: false; error: unknown; diagnostics: ProviderRequestDiagnostics }
133
+ > {
134
+ installOutboundHttpDiagnostics();
135
+ const recorder = new DiagnosticsRecorder();
136
+ return recorderStorage.run(recorder, async () => {
137
+ try {
138
+ const value = await fn();
139
+ return { ok: true as const, value, diagnostics: recorder.snapshot() };
140
+ } catch (error) {
141
+ return { ok: false as const, error, diagnostics: recorder.snapshot() };
142
+ }
143
+ });
144
+ }
145
+
146
+ let installed = false;
147
+
148
+ /**
149
+ * Wrap `globalThis.fetch` so outbound requests made inside a diagnostics scope
150
+ * report their resolved URL, status, and raw non-2xx body. Instrumenting the
151
+ * global is what makes this uniform across provider SDKs: `@google/genai`
152
+ * offers no `fetch` injection point and exposes neither URL nor body on its
153
+ * errors. Outside a scope the wrapper delegates untouched, and error bodies
154
+ * are read from a `clone()` so the SDK's own read is unaffected.
155
+ */
156
+ export function installOutboundHttpDiagnostics(): void {
157
+ if (installed) {
158
+ return;
159
+ }
160
+ installed = true;
161
+ const originalFetch = globalThis.fetch;
162
+ globalThis.fetch = async function instrumentedFetch(
163
+ input: RequestInfo | URL,
164
+ init?: RequestInit,
165
+ ): Promise<Response> {
166
+ const recorder = recorderStorage.getStore();
167
+ if (!recorder) {
168
+ return originalFetch(input, init);
169
+ }
170
+ const url = requestUrl(input);
171
+ try {
172
+ const response = await originalFetch(input, init);
173
+ recorder.record({
174
+ ...(url ? { resolved_url: redactUrl(url) } : {}),
175
+ http_status: response.status,
176
+ });
177
+ if (!response.ok) {
178
+ recorder.record(await readErrorBody(response));
179
+ }
180
+ return response;
181
+ } catch (error) {
182
+ if (url) {
183
+ recorder.record({ resolved_url: redactUrl(url) });
184
+ }
185
+ throw error;
186
+ }
187
+ } as typeof globalThis.fetch;
188
+ }
189
+
190
+ function requestUrl(input: RequestInfo | URL): string | undefined {
191
+ if (typeof input === "string") {
192
+ return input;
193
+ }
194
+ if (input instanceof URL) {
195
+ return input.toString();
196
+ }
197
+ return typeof input?.url === "string" ? input.url : undefined;
198
+ }
199
+
200
+ async function readErrorBody(
201
+ response: Response,
202
+ ): Promise<ProviderRequestDiagnostics> {
203
+ let body: string;
204
+ try {
205
+ body = await response.clone().text();
206
+ } catch {
207
+ return { upstream_error_body_state: "unavailable" };
208
+ }
209
+ const bytes = Buffer.byteLength(body, "utf8");
210
+ if (bytes === 0) {
211
+ return { upstream_error_body_state: "empty", upstream_error_body_bytes: 0 };
212
+ }
213
+ if (bytes > MAX_ERROR_BODY_BYTES) {
214
+ return {
215
+ upstream_error_body: body.slice(0, MAX_ERROR_BODY_BYTES),
216
+ upstream_error_body_state: "truncated",
217
+ upstream_error_body_bytes: bytes,
218
+ };
219
+ }
220
+ return {
221
+ upstream_error_body: body,
222
+ upstream_error_body_state: "captured",
223
+ upstream_error_body_bytes: bytes,
224
+ };
225
+ }
@@ -24,8 +24,12 @@ import type {
24
24
  // ---------------------------------------------------------------------------
25
25
 
26
26
  let nextResponse: ProviderResponse;
27
+ let sendMessageImpl: (() => Promise<ProviderResponse>) | undefined;
27
28
  let getConfiguredProviderOptions: ConfiguredProviderOptions | undefined;
28
29
  let sendMessageOptions: SendMessageOptions | undefined;
30
+ // Connection the stubbed resolution reports, mirroring the real resolver:
31
+ // the connection is chosen while resolving the provider, not while sending.
32
+ let resolutionConnectionName: string | undefined;
29
33
 
30
34
  mock.module("../../../providers/provider-send-message.js", () => ({
31
35
  getConfiguredProvider: async (
@@ -33,11 +37,16 @@ mock.module("../../../providers/provider-send-message.js", () => ({
33
37
  options: ConfiguredProviderOptions,
34
38
  ) => {
35
39
  getConfiguredProviderOptions = options;
40
+ if (resolutionConnectionName) {
41
+ recordProviderRequestDiagnostics({
42
+ connection_name: resolutionConnectionName,
43
+ });
44
+ }
36
45
  return {
37
46
  name: "stub",
38
47
  sendMessage: async (_messages: unknown, options: SendMessageOptions) => {
39
48
  sendMessageOptions = options;
40
- return nextResponse;
49
+ return sendMessageImpl ? sendMessageImpl() : nextResponse;
41
50
  },
42
51
  };
43
52
  },
@@ -58,7 +67,9 @@ mock.module("../../../config/loader.js", () => ({
58
67
  }));
59
68
 
60
69
  const { ROUTES } = await import("../inference-send-routes.js");
61
- const { BadRequestError } = await import("../errors.js");
70
+ const { BadRequestError, UpstreamProviderError } = await import("../errors.js");
71
+ const { recordProviderRequestDiagnostics } =
72
+ await import("../../../providers/request-diagnostics.js");
62
73
 
63
74
  function inferenceSendHandler() {
64
75
  const route = ROUTES.find((r) => r.operationId === "inference_send");
@@ -81,8 +92,10 @@ function baseResponse(overrides: Partial<ProviderResponse>): ProviderResponse {
81
92
  beforeEach(() => {
82
93
  configuredLlm = LLMSchema.parse({});
83
94
  nextResponse = baseResponse({});
95
+ sendMessageImpl = undefined;
84
96
  getConfiguredProviderOptions = undefined;
85
97
  sendMessageOptions = undefined;
98
+ resolutionConnectionName = undefined;
86
99
  });
87
100
 
88
101
  describe("inference_send profile routing", () => {
@@ -131,6 +144,26 @@ describe("inference_send evidence", () => {
131
144
  });
132
145
  });
133
146
 
147
+ test("surfaces the connection recorded while the provider is resolved", async () => {
148
+ /**
149
+ * Tests that diagnostics recorded during provider resolution reach the
150
+ * evidence payload. The connection backing the request is chosen while
151
+ * resolving the provider, so resolution has to run inside the diagnostics
152
+ * scope or "which key was this?" goes unanswered on every probe.
153
+ */
154
+
155
+ // GIVEN resolution picks a named connection for the request
156
+ resolutionConnectionName = "gemini-personal";
157
+
158
+ // WHEN the inference_send handler processes a request
159
+ const result = (await inferenceSendHandler()({
160
+ body: { message: "hi" },
161
+ })) as { evidence?: { connection_name?: string } };
162
+
163
+ // THEN the evidence names the connection that authenticated the send
164
+ expect(result.evidence?.connection_name).toBe("gemini-personal");
165
+ });
166
+
134
167
  test("omits evidence entirely when the provider surfaces no endpoint", async () => {
135
168
  // GIVEN a provider whose runtime response carries no resolvedEndpoint
136
169
  nextResponse = baseResponse({ resolvedEndpoint: undefined });
@@ -143,6 +176,50 @@ describe("inference_send evidence", () => {
143
176
  // THEN no evidence object is fabricated — the endpoint stays unknown
144
177
  expect(result.evidence).toBeUndefined();
145
178
  });
179
+
180
+ test("reports the outbound request and verbatim upstream body when the send fails", async () => {
181
+ // GIVEN a provider call that reaches the upstream and fails there
182
+ sendMessageImpl = async () => {
183
+ recordProviderRequestDiagnostics({
184
+ resolved_url:
185
+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro:streamGenerateContent?key=REDACTED",
186
+ model_id: "gemini-3-pro",
187
+ connection_name: "gemini-personal",
188
+ http_status: 404,
189
+ upstream_error_body: '{"error":{"code":404}}',
190
+ upstream_error_body_state: "captured",
191
+ upstream_error_body_bytes: 22,
192
+ });
193
+ throw new Error("Gemini API error (404): Not Found");
194
+ };
195
+
196
+ // WHEN the inference_send handler processes a request
197
+ const error = await Promise.resolve(
198
+ inferenceSendHandler()({ body: { message: "hi" } }),
199
+ ).then(
200
+ () => new Error("expected the request to fail"),
201
+ (err: unknown) => err,
202
+ );
203
+
204
+ // THEN the failure carries the evidence needed to diagnose it
205
+ expect(error).toBeInstanceOf(UpstreamProviderError);
206
+ expect(
207
+ (error as InstanceType<typeof UpstreamProviderError>).details,
208
+ ).toEqual({
209
+ error_class: "Error",
210
+ error_stack_head: expect.any(String),
211
+ evidence: {
212
+ resolved_url:
213
+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro:streamGenerateContent?key=REDACTED",
214
+ model_id: "gemini-3-pro",
215
+ connection_name: "gemini-personal",
216
+ http_status: 404,
217
+ upstream_error_body: '{"error":{"code":404}}',
218
+ upstream_error_body_state: "captured",
219
+ upstream_error_body_bytes: 22,
220
+ },
221
+ });
222
+ });
146
223
  });
147
224
 
148
225
  // ---------------------------------------------------------------------------
@@ -139,6 +139,19 @@ export class GatewayTimeoutError extends RouteError {
139
139
  }
140
140
  }
141
141
 
142
+ /**
143
+ * An upstream LLM provider call failed. Carries the per-request diagnostics
144
+ * observed on the wire (resolved URL, model, connection, HTTP status, verbatim
145
+ * upstream error body) in `details` so a caller diagnosing the failure sees
146
+ * what was actually sent and what came back, not just the normalized message.
147
+ */
148
+ export class UpstreamProviderError extends RouteError {
149
+ constructor(message: string, details: unknown) {
150
+ super(message, "UPSTREAM_PROVIDER_ERROR", 502, details);
151
+ this.name = "UpstreamProviderError";
152
+ }
153
+ }
154
+
142
155
  export class InternalError extends RouteError {
143
156
  constructor(message: string) {
144
157
  super(message, "INTERNAL_ERROR", 500);
@@ -16,8 +16,10 @@ import {
16
16
  getConfiguredProvider,
17
17
  userMessage,
18
18
  } from "../../providers/provider-send-message.js";
19
+ import type { ProviderRequestDiagnostics } from "../../providers/request-diagnostics.js";
20
+ import { runWithProviderRequestDiagnostics } from "../../providers/request-diagnostics.js";
19
21
  import { LOCAL_PRINCIPALS } from "../auth/route-policy.js";
20
- import { BadRequestError } from "./errors.js";
22
+ import { BadRequestError, UpstreamProviderError } from "./errors.js";
21
23
  import type { RouteDefinition, RouteHandlerArgs } from "./types.js";
22
24
 
23
25
  // ---------------------------------------------------------------------------
@@ -82,27 +84,39 @@ async function handleInferenceSend({ body = {} }: RouteHandlerArgs) {
82
84
  }
83
85
  }
84
86
 
85
- const provider = await getConfiguredProvider("inference", {
86
- overrideProfile: profile,
87
- selectionSeed,
88
- });
89
- if (!provider) {
90
- throw new BadRequestError(
91
- "No LLM provider is configured. Connect a provider (assistant credentials) or set llm.defaultProvider to choose one.",
92
- );
93
- }
94
-
95
- const response = await provider.sendMessage([userMessage(message)], {
96
- systemPrompt,
97
- config: {
98
- callSite: "inference",
99
- max_tokens: maxTokens,
100
- model,
87
+ // Diagnostics are collected around the send, not inside it, so the failure
88
+ // path carries the same evidence as the success path: a probe of a broken
89
+ // profile must report the URL that was actually requested and the verbatim
90
+ // upstream body, rather than only the message the SDK managed to extract.
91
+ // Provider resolution runs inside the same scope because that is where the
92
+ // connection backing the request is chosen.
93
+ const attempt = await runWithProviderRequestDiagnostics(async () => {
94
+ const provider = await getConfiguredProvider("inference", {
101
95
  overrideProfile: profile,
102
96
  selectionSeed,
103
- },
97
+ });
98
+ if (!provider) {
99
+ throw new BadRequestError(
100
+ "No LLM provider is configured. Connect a provider (assistant credentials) or set llm.defaultProvider to choose one.",
101
+ );
102
+ }
103
+ return provider.sendMessage([userMessage(message)], {
104
+ systemPrompt,
105
+ config: {
106
+ callSite: "inference",
107
+ max_tokens: maxTokens,
108
+ model,
109
+ overrideProfile: profile,
110
+ selectionSeed,
111
+ },
112
+ });
104
113
  });
105
114
 
115
+ if (!attempt.ok) {
116
+ throw upstreamFailure(attempt.error, attempt.diagnostics);
117
+ }
118
+
119
+ const response = attempt.value;
106
120
  const text = extractAllText(response);
107
121
 
108
122
  return {
@@ -120,10 +134,49 @@ async function handleInferenceSend({ body = {} }: RouteHandlerArgs) {
120
134
  // call sites resolve to for the requested profile — not a config re-read.
121
135
  // A caller comparing against a different profile should not assume a match.
122
136
  // Omitted when the provider does not surface an endpoint.
123
- ...(response.resolvedEndpoint !== undefined
124
- ? { evidence: { resolved_endpoint: response.resolvedEndpoint } }
137
+ ...evidencePayload(response.resolvedEndpoint, attempt.diagnostics),
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Merge the endpoint the provider adapter reports with the per-request
143
+ * diagnostics observed on the wire, omitting the key entirely when nothing was
144
+ * observed so consumers can distinguish "no evidence" from "empty evidence".
145
+ */
146
+ function evidencePayload(
147
+ resolvedEndpoint: string | undefined,
148
+ diagnostics: ProviderRequestDiagnostics,
149
+ ): { evidence?: Record<string, unknown> } {
150
+ const evidence = {
151
+ ...(resolvedEndpoint !== undefined
152
+ ? { resolved_endpoint: resolvedEndpoint }
125
153
  : {}),
154
+ ...diagnostics,
126
155
  };
156
+ return Object.keys(evidence).length > 0 ? { evidence } : {};
157
+ }
158
+
159
+ /**
160
+ * Wrap a failed send so the evidence survives the error path. `RouteError`
161
+ * details are mirrored into the HTTP error envelope and the IPC response, so
162
+ * the CLI (and Doctor through it) sees the same fields a successful probe
163
+ * returns.
164
+ */
165
+ function upstreamFailure(
166
+ error: unknown,
167
+ diagnostics: ProviderRequestDiagnostics,
168
+ ): Error {
169
+ if (error instanceof BadRequestError) {
170
+ return error;
171
+ }
172
+ const message = error instanceof Error ? error.message : String(error);
173
+ return new UpstreamProviderError(message, {
174
+ error_class: error instanceof Error ? error.name : "UnknownError",
175
+ ...(error instanceof Error && error.stack
176
+ ? { error_stack_head: error.stack.split("\n").slice(0, 5).join("\n") }
177
+ : {}),
178
+ evidence: evidencePayload(undefined, diagnostics).evidence ?? {},
179
+ });
127
180
  }
128
181
 
129
182
  // ---------------------------------------------------------------------------
@@ -161,6 +214,15 @@ export const ROUTES: RouteDefinition[] = [
161
214
  evidence: z
162
215
  .object({
163
216
  resolved_endpoint: z.string().optional(),
217
+ resolved_url: z.string().optional(),
218
+ model_id: z.string().optional(),
219
+ connection_name: z.string().optional(),
220
+ http_status: z.number().optional(),
221
+ upstream_error_body: z.string().optional(),
222
+ upstream_error_body_state: z
223
+ .enum(["captured", "empty", "truncated", "unavailable"])
224
+ .optional(),
225
+ upstream_error_body_bytes: z.number().optional(),
164
226
  })
165
227
  .optional(),
166
228
  }),