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(onboarding): preserve provider failure diagnostics (#18349)

Neko253ff249d13a
diff --git a/apps/server/src/services/understanding/providers/github.test.ts b/apps/server/src/services/understanding/providers/github.test.ts
index 63764ea37e5..adf9c83413d 100644
--- a/apps/server/src/services/understanding/providers/github.test.ts
+++ b/apps/server/src/services/understanding/providers/github.test.ts
@@ -1,3 +1,4 @@
+import { ConnectorDataError } from '@lobechat/connector-data';
import type { GitHubConnectorClient, GitHubUserProfile } from '@lobechat/connector-data/github';
import { describe, expect, it, vi } from 'vitest';
@@ -44,4 +45,56 @@ describe('githubUnderstandingProvider', () => {
sourceCount: 1,
});
});
+
+ /** @example expect(result.diagnostics.errors[0].message).toContain('viewer.repository'); */
+ it('preserves a profile README failure message in provider diagnostics', async () => {
+ // ROOT CAUSE:
+ //
+ // Promise.allSettled exposed the original profile README rejection, but the provider replaced
+ // it with a generic enrichment message before persistence and observability could inspect it.
+ //
+ // Before: "GraphQL FORBIDDEN at viewer.repository" became
+ // "GitHub profile README enrichment failed".
+ //
+ // We fixed this by retaining the rejected ConnectorDataError message in the diagnostic.
+ const upstreamMessage = 'GraphQL FORBIDDEN at viewer.repository(name: profile)';
+ const empty = vi.fn(async () => []);
+ const client = {
+ getUserProfile: vi.fn(async () => ({ externalAccountId: 'account-id', login: 'octocat' })),
+ getUserProfileReadme: vi.fn(async () => {
+ throw new ConnectorDataError({
+ code: 'github_request_failed',
+ message: upstreamMessage,
+ operation: 'ConnectorDataGitHubProfileReadme',
+ provider: 'github',
+ retryable: false,
+ });
+ }),
+ listContributedRepositories: empty,
+ listInfluentialRepositories: empty,
+ listPinnedRepositories: empty,
+ listPinnedContributedRepositories: empty,
+ listRecentContributions: empty,
+ listRecentPullRequests: empty,
+ listRecentRepositories: empty,
+ listRepositoryContributors: empty,
+ listUserOrganizations: empty,
+ } satisfies GitHubConnectorClient;
+
+ const result = await githubUnderstandingProvider.collect({
+ connectorData: {
+ getGitHubClient: vi.fn(async () => client),
+ } as never,
+ userId: 'user-id',
+ });
+
+ /** @example expect(result.diagnostics.errors[0]).toMatchObject({ message: upstreamMessage }); */
+ expect(result.diagnostics.errors[0]).toMatchObject({
+ code: 'GITHUB_PROFILE_README_FAILED',
+ message: upstreamMessage,
+ operation: 'profileReadme',
+ provider: 'github',
+ retryable: false,
+ });
+ });
});
diff --git a/apps/server/src/services/understanding/providers/github.ts b/apps/server/src/services/understanding/providers/github.ts
index 0aa7bce7477..8cb68f2ed41 100644
--- a/apps/server/src/services/understanding/providers/github.ts
+++ b/apps/server/src/services/understanding/providers/github.ts
@@ -1,4 +1,4 @@
-import { ConnectorDataError } from '@lobechat/connector-data';
+import { getConnectorErrorMessage, isConnectorErrorRetryable } from '@lobechat/connector-data';
import type { GitHubUserContext } from '@lobechat/connector-data/github';
import { toGitHubUserContextMarkdown } from '@lobechat/connector-data/github';
@@ -86,10 +86,10 @@ export const githubUnderstandingProvider: UnderstandingProvider = {
return [
{
code: operations[index].code,
- message: operations[index].message,
+ message: getConnectorErrorMessage(result.reason) ?? operations[index].message,
operation: operations[index].key,
provider: 'github',
- retryable: result.reason instanceof ConnectorDataError ? result.reason.retryable : true,
+ retryable: isConnectorErrorRetryable(result.reason),
},
];
});
diff --git a/apps/server/src/services/understanding/providers/gmail.test.ts b/apps/server/src/services/understanding/providers/gmail.test.ts
index da65b3061ab..a9a98cbe0b0 100644
--- a/apps/server/src/services/understanding/providers/gmail.test.ts
+++ b/apps/server/src/services/understanding/providers/gmail.test.ts
@@ -57,8 +57,8 @@ describe('gmailUnderstandingProvider', () => {
});
});
- /** @example A sanitized connector failure remains identifiable in partial diagnostics. */
- it('preserves the connector failure code for failed Gmail searches', async () => {
+ /** @example A connector failure remains identifiable in partial diagnostics. */
+ it('preserves the connector failure code and message for failed Gmail searches', async () => {
const searchMessages = vi
.fn()
.mockResolvedValueOnce([
@@ -73,6 +73,7 @@ describe('gmailUnderstandingProvider', () => {
.mockRejectedValue(
new ConnectorDataError({
code: 'gmail_tool_version_unavailable',
+ message: 'Composio could not resolve Gmail tool version 20260814',
operation: 'searchMessages',
provider: 'gmail',
retryable: false,
@@ -99,8 +100,41 @@ describe('gmailUnderstandingProvider', () => {
/** @example expect(result.diagnostics.errors[0].code).toBe('gmail_tool_version_unavailable'); */
expect(result.diagnostics.errors[0]).toMatchObject({
code: 'gmail_tool_version_unavailable',
+ message: 'Composio could not resolve Gmail tool version 20260814',
operation: 'receipts',
retryable: false,
});
});
+
+ /** @example expect(error.cause).toBe(upstreamError); */
+ it('retains the original retryable error when Gmail evidence collection fails', async () => {
+ const upstreamError = new ConnectorDataError({
+ code: 'gmail_search_failed',
+ message: 'Composio Gmail search timed out',
+ operation: 'searchMessages',
+ provider: 'gmail',
+ retryable: true,
+ });
+ const searchMessages = vi.fn().mockRejectedValueOnce(upstreamError).mockResolvedValue([]);
+
+ const error = await gmailUnderstandingProvider
+ .collect({
+ connectorData: {
+ getGmailClient: vi.fn(async () => ({
+ getAccount: vi.fn(async () => ({
+ externalAccountId: 'gmail-account',
+ scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
+ })),
+ searchMessages,
+ })),
+ } as never,
+ userId: 'user-id',
+ })
+ .catch((reason) => reason);
+
+ /** @example expect(error).toBeInstanceOf(ConnectorDataError); */
+ expect(error).toBeInstanceOf(ConnectorDataError);
+ /** @example expect(error.cause).toBe(upstreamError); */
+ expect(error.cause).toBe(upstreamError);
+ });
});
diff --git a/apps/server/src/services/understanding/providers/gmail.ts b/apps/server/src/services/understanding/providers/gmail.ts
index 7ea320a85bd..1682ff01ff2 100644
--- a/apps/server/src/services/understanding/providers/gmail.ts
+++ b/apps/server/src/services/understanding/providers/gmail.ts
@@ -1,4 +1,8 @@
-import { ConnectorDataError } from '@lobechat/connector-data';
+import {
+ ConnectorDataError,
+ getConnectorErrorMessage,
+ isConnectorErrorRetryable,
+} from '@lobechat/connector-data';
import type { GmailMessage } from '@lobechat/connector-data/gmail';
import { toGmailMessagesXml } from '@lobechat/connector-data/gmail';
@@ -116,16 +120,18 @@ export const gmailUnderstandingProvider: UnderstandingProvider = {
const fulfilled = settled.filter(
(result): result is PromiseFulfilledResult<GmailMessage[]> => result.status === 'fulfilled',
);
+ const rejectedReasons = settled.flatMap((result) =>
+ result.status === 'rejected' ? [result.reason] : [],
+ );
const errors = settled.flatMap((result, index) =>
result.status === 'rejected'
? [
{
code: getGmailCollectionErrorCode(result.reason),
- message: 'Gmail search category failed',
+ message: getConnectorErrorMessage(result.reason) ?? 'Gmail search category failed',
operation: GMAIL_PROFILE_SEARCHES[index].operation,
provider: 'gmail',
- retryable:
- result.reason instanceof ConnectorDataError ? result.reason.retryable : true,
+ retryable: isConnectorErrorRetryable(result.reason),
},
]
: [],
@@ -140,6 +146,7 @@ export const gmailUnderstandingProvider: UnderstandingProvider = {
if (selected.length === 0) {
if (errors.some(({ retryable }) => retryable)) {
throw new ConnectorDataError({
+ cause: rejectedReasons.length === 1 ? rejectedReasons[0] : rejectedReasons,
code: 'gmail_evidence_unavailable',
operation: 'collect',
provider: 'gmail',
diff --git a/apps/server/src/services/understanding/providers/notion.ts b/apps/server/src/services/understanding/providers/notion.ts
index 1889577a3ea..52f37933afb 100644
--- a/apps/server/src/services/understanding/providers/notion.ts
+++ b/apps/server/src/services/understanding/providers/notion.ts
@@ -1,4 +1,4 @@
-import { ConnectorDataError } from '@lobechat/connector-data';
+import { getConnectorErrorMessage, isConnectorErrorRetryable } from '@lobechat/connector-data';
import type { NotionItem, NotionItemContent } from '@lobechat/connector-data/notion';
import type { UnderstandingProvider } from '../types';
@@ -70,10 +70,11 @@ export const notionUnderstandingProvider: UnderstandingProvider = {
return [
{
code: 'NOTION_PAGE_CONTENT_FAILED',
- message: 'Notion page content enrichment failed',
+ message:
+ getConnectorErrorMessage(result.reason) ?? 'Notion page content enrichment failed',
operation: 'page_content',
provider: 'notion',
- retryable: result.reason instanceof ConnectorDataError ? result.reason.retryable : true,
+ retryable: isConnectorErrorRetryable(result.reason),
},
];
});
diff --git a/apps/server/src/services/understanding/providers/twitter.ts b/apps/server/src/services/understanding/providers/twitter.ts
index adb4e1c5cf3..17ceca499e4 100644
--- a/apps/server/src/services/understanding/providers/twitter.ts
+++ b/apps/server/src/services/understanding/providers/twitter.ts
@@ -1,4 +1,4 @@
-import { ConnectorDataError } from '@lobechat/connector-data';
+import { getConnectorErrorMessage, isConnectorErrorRetryable } from '@lobechat/connector-data';
import type { TwitterPost } from '@lobechat/connector-data/twitter';
import type { UnderstandingProvider } from '../types';
@@ -34,10 +34,11 @@ const collectRecentActivity = async (
? [
{
code: 'TWITTER_RECENT_ACTIVITY_FAILED',
- message: 'X recent activity collection failed',
+ message:
+ getConnectorErrorMessage(result.reason) ?? 'X recent activity collection failed',
operation: searches[index].kind,
provider: 'twitter' as const,
- retryable: result.reason instanceof ConnectorDataError ? result.reason.retryable : true,
+ retryable: isConnectorErrorRetryable(result.reason),
},
]
: [],
diff --git a/apps/server/src/services/understanding/sanitizer.test.ts b/apps/server/src/services/understanding/sanitizer.test.ts
deleted file mode 100644
index 70eddb8933b..00000000000
--- a/apps/server/src/services/understanding/sanitizer.test.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import type { CollectionDiagnostics } from '@lobechat/types';
-import { describe, expect, it } from 'vitest';
-
-import { canonicalCollectionError, sanitizeProviderDiagnostics } from './sanitizer';
-
-/** @example describe('sanitizeProviderDiagnostics', () => {}); */
-describe('sanitizeProviderDiagnostics', () => {
- /** @example expect(result.errors[0].code).toBe('GMAIL_READ_PERMISSION_REQUIRED'); */
- it('preserves bounded provider-owned codes and operations while replacing messages', () => {
- // ROOT CAUSE:
- //
- // A fixed diagnostic allowlist converted new internal codes such as
- // GMAIL_READ_PERMISSION_REQUIRED into PROVIDER_COLLECTION_FAILED. This erased the exact
- // business failure needed for persisted diagnostics and observability.
- //
- // We fixed this by accepting bounded identifiers in the active provider namespace while still
- // replacing free-form messages at the service boundary.
- const diagnostics: CollectionDiagnostics = {
- errors: [
- {
- code: 'GMAIL_READ_PERMISSION_REQUIRED',
- message: 'secret upstream response must not survive',
- operation: 'permission',
- provider: 'untrusted-provider',
- retryable: false,
- },
- ],
- evidenceCount: 0,
- failedCount: 1,
- succeededCount: 0,
- };
-
- const result = sanitizeProviderDiagnostics('gmail', diagnostics);
-
- /** @example expect(result.errors[0]).not.toHaveProperty('message', 'secret'); */
- expect(result.errors).toEqual([
- {
- code: 'GMAIL_READ_PERMISSION_REQUIRED',
- message: 'gmail permission failed',
- operation: 'permission',
- provider: 'gmail',
- retryable: false,
- },
- ]);
- });
-
- /** @example expect(result.errors[0].code).toBe('PROVIDER_COLLECTION_FAILED'); */
- it('rejects codes outside the active provider namespace', () => {
- const result = sanitizeProviderDiagnostics('gmail', {
- errors: [
- {
- code: 'UPSTREAM_SECRET_ACCOUNT_IDENTIFIER',
- message: 'raw provider message',
- operation: 'Recent Messages',
- provider: 'gmail',
- retryable: true,
- },
- ],
- evidenceCount: 0,
- failedCount: 1,
- succeededCount: 0,
- });
-
- /** @example expect(result.errors[0].operation).toBe('recent_messages'); */
- expect(result.errors[0]).toEqual({
- code: 'PROVIDER_COLLECTION_FAILED',
- message: 'gmail recent_messages failed',
- operation: 'recent_messages',
- provider: 'gmail',
- retryable: true,
- });
- });
-
- /** @example expect(error.code).toBe('GMAIL_SEARCH_FAILED'); */
- it('normalizes safe connector error codes before persistence', () => {
- const error = canonicalCollectionError('gmail', 'searchMessages', 'gmail_search_failed', true);
-
- /** @example expect(error.message).toBe('gmail search_messages failed'); */
- expect(error).toEqual({
- code: 'GMAIL_SEARCH_FAILED',
- message: 'gmail search_messages failed',
- operation: 'search_messages',
- provider: 'gmail',
- retryable: true,
- });
- });
-
- /** @example expect(error.code).toBe('UNDERSTANDING_WRITING_FAILED'); */
- it('preserves Understanding-owned workflow error codes', () => {
- const error = canonicalCollectionError(
- 'understanding',
- 'writing',
- 'UNDERSTANDING_WRITING_FAILED',
- true,
- );
-
- /** @example expect(error.operation).toBe('writing'); */
- expect(error).toMatchObject({
- code: 'UNDERSTANDING_WRITING_FAILED',
- operation: 'writing',
- });
- });
-});
diff --git a/apps/server/src/services/understanding/sanitizer.ts b/apps/server/src/services/understanding/sanitizer.ts
deleted file mode 100644
index 346ae73e479..00000000000
--- a/apps/server/src/services/understanding/sanitizer.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import {
- type CollectionDiagnostics,
- type CollectionError,
- MAX_COLLECTION_COUNT,
- MAX_COLLECTION_ERRORS,
- MAX_DIAGNOSTIC_CODE_LENGTH,
- MAX_DIAGNOSTIC_MESSAGE_LENGTH,
- MAX_DIAGNOSTIC_OPERATION_LENGTH,
- MAX_PROVIDER_ID_LENGTH,
-} from '@lobechat/types';
-
-export {
- MAX_COLLECTION_COUNT,
- MAX_COLLECTION_ERRORS,
- MAX_DIAGNOSTIC_CODE_LENGTH,
- MAX_DIAGNOSTIC_MESSAGE_LENGTH,
- MAX_DIAGNOSTIC_OPERATION_LENGTH,
- MAX_PROVIDER_ID_LENGTH,
-} from '@lobechat/types';
-
-export const MAX_AGENT_INPUT_LENGTH = 128_000;
-export const MAX_SOURCE_BRIEF_LENGTH = 64_000;
-
-const boundedCount = (value: number) =>
- Number.isFinite(value) ? Math.min(MAX_COLLECTION_COUNT, Math.max(0, Math.floor(value))) : 0;
-
-const trustedProvider = (provider: string) =>
- provider.trim().slice(0, MAX_PROVIDER_ID_LENGTH) || 'provider';
-
-/**
- * Normalizes a diagnostic identifier without retaining free-form text.
- *
- * Before:
- * - "gmail.search-failed"
- *
- * After:
- * - "GMAIL_SEARCH_FAILED"
- */
-const normalizeDiagnosticCode = (value: string) =>
- value
- .trim()
- .toUpperCase()
- .replaceAll(/[^A-Z0-9]+/g, '_')
- .replaceAll(/^_+|_+$/g, '')
- .slice(0, MAX_DIAGNOSTIC_CODE_LENGTH);
-
-/**
- * Normalizes a provider sub-operation without retaining free-form text.
- *
- * Before:
- * - "Recent Messages"
- *
- * After:
- * - "recent_messages"
- */
-const normalizeDiagnosticOperation = (value: string) =>
- value
- .trim()
- .replaceAll(/([a-z0-9])([A-Z])/g, '$1_$2')
- .toLowerCase()
- .replaceAll(/[^a-z0-9]+/g, '_')
- .replaceAll(/^_+|_+$/g, '')
- .slice(0, MAX_DIAGNOSTIC_OPERATION_LENGTH) || 'collection';
-
-const sanitizeDiagnosticCode = (provider: string, value: string) => {
- const normalized = normalizeDiagnosticCode(value);
- const providerPrefix = `${normalizeDiagnosticCode(provider)}_`;
- if (normalized.startsWith(providerPrefix) || normalized.startsWith('UNDERSTANDING_')) {
- return normalized;
- }
- return 'PROVIDER_COLLECTION_FAILED';
-};
-
-/**
- * Sanitizes provider diagnostics for persistence and observability.
- *
- * Use when:
- * - Moving provider collection diagnostics across the service boundary
- *
- * Expects:
- * - Codes are owned by the active provider or the Understanding service
- *
- * Returns:
- * - Bounded counts and identifiers with all free-form messages replaced
- */
-export const sanitizeProviderDiagnostics = (
- provider: string,
- value: CollectionDiagnostics,
-): CollectionDiagnostics => {
- const trusted = trustedProvider(provider);
- return {
- errors: value.errors.slice(0, MAX_COLLECTION_ERRORS).map((error) => {
- const code = sanitizeDiagnosticCode(trusted, error.code);
- const operation = normalizeDiagnosticOperation(error.operation);
- return {
- code,
- message: `${trusted} ${operation} failed`.slice(0, MAX_DIAGNOSTIC_MESSAGE_LENGTH),
- operation,
- provider: trusted,
- retryable: Boolean(error.retryable),
- };
- }),
- evidenceCount: boundedCount(value.evidenceCount),
- failedCount: boundedCount(value.failedCount),
- succeededCount: boundedCount(value.succeededCount),
- };
-};
-
-/**
- * Bounds diagnostics that were already sanitized by the service.
- *
- * Use when:
- * - Reading canonical diagnostics from a trusted internal result
- *
- * Expects:
- * - Error identifiers and messages are already canonical and non-sensitive
- *
- * Returns:
- * - Diagnostics with bounded counts and error cardinality
- */
-export const boundCanonicalDiagnostics = (value: CollectionDiagnostics): CollectionDiagnostics => ({
- errors: value.errors.slice(0, MAX_COLLECTION_ERRORS),
- evidenceCount: boundedCount(value.evidenceCount),
- failedCount: boundedCount(value.failedCount),
- succeededCount: boundedCount(value.succeededCount),
-});
-
-/**
- * Creates one bounded collection error without retaining free-form messages.
- *
- * Use when:
- * - Converting a structured internal or Connector Data error for persistence
- *
- * Expects:
- * - The code is owned by the provider or the Understanding service
- *
- * Returns:
- * - A canonical collection error safe for storage, metrics, and API projection
- */
-export const canonicalCollectionError = (
- provider: string,
- operation: string,
- code: string,
- retryable: boolean,
-): CollectionError => {
- const trusted = trustedProvider(provider);
- const safeOperation = normalizeDiagnosticOperation(operation);
- return {
- code: sanitizeDiagnosticCode(trusted, code),
- message: `${trusted} ${safeOperation} failed`.slice(0, MAX_DIAGNOSTIC_MESSAGE_LENGTH),
- operation: safeOperation,
- provider: trusted,
- retryable,
- };
-};
diff --git a/apps/server/src/services/understanding/service.test.ts b/apps/server/src/services/understanding/service.test.ts
index fde16142b7c..c7f31de71d4 100644
--- a/apps/server/src/services/understanding/service.test.ts
+++ b/apps/server/src/services/understanding/service.test.ts
@@ -630,8 +630,8 @@ describe('UnderstandingService', () => {
expect(harness.repository.completeProvider).toHaveBeenCalledOnce();
});
- /** @example A missing Gmail scope remains an actionable failed-provider diagnostic. */
- it('persists a provider-owned failure code without its free-form message', async () => {
+ /** @example A provider rejection remains actionable in persisted diagnostics. */
+ it('persists the original provider failure message', async () => {
const harness = createHarness(createSession({ gmail: providerState('running', 1) }));
harness.setProvider('gmail', {
collect: vi.fn(async () => ({
@@ -640,7 +640,7 @@ describe('UnderstandingService', () => {
errors: [
{
code: 'GMAIL_READ_PERMISSION_REQUIRED',
- message: 'raw account-specific details must not be persisted',
+ message: 'Gmail rejected the search because scope gmail.readonly is missing',
operation: 'permission',
provider: 'gmail',
retryable: false,
@@ -670,7 +670,7 @@ describe('UnderstandingService', () => {
errors: [
{
code: 'GMAIL_READ_PERMISSION_REQUIRED',
- message: 'gmail permission failed',
+ message: 'Gmail rejected the search because scope gmail.readonly is missing',
operation: 'permission',
provider: 'gmail',
retryable: false,
@@ -685,6 +685,60 @@ describe('UnderstandingService', () => {
});
});
+ /** @example expect(failProvider).toContain('GraphQL FORBIDDEN'); */
+ it('persists a raw non-retryable provider exception without wrapping it', async () => {
+ // ROOT CAUSE:
+ //
+ // Connector retry wrapped terminal upstream exceptions in ConnectorDataError before the
+ // Understanding service observed them. That discarded the original error identity and stack.
+ //
+ // Before: Error("GraphQL FORBIDDEN at viewer.repository") became
+ // ConnectorDataError("github collection failed").
+ //
+ // We fixed this by rethrowing the original exception and converting it only at the DB
+ // diagnostic boundary, where its original message is retained.
+ const harness = createHarness(createSession({ github: providerState('running', 1) }));
+ const upstreamError = Object.assign(
+ new Error('GraphQL FORBIDDEN at viewer.repository(name: profile)'),
+ { status: 403 },
+ );
+ harness.setProvider('github', {
+ collect: vi.fn(async () => {
+ throw upstreamError;
+ }),
+ connectionSource: 'composio',
+ id: 'github',
+ });
+
+ await expect(
+ harness.service.processProvider({
+ providerId: 'github',
+ revision: 1,
+ sessionId: 'session-1',
+ topicId: 'topic-1',
+ }),
+ ).resolves.toMatchObject({ providerId: 'github', status: 'failed' });
+
+ /** @example expect(failProvider).toHaveBeenCalledWith({ errors: [...] }); */
+ expect(harness.repository.failProvider).toHaveBeenCalledWith({
+ errors: [
+ {
+ code: 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',
+ message: upstreamError.message,
+ operation: 'collection',
+ provider: 'github',
+ retryable: false,
+ },
+ ],
+ failedCount: 1,
+ providerId: 'github',
+ revision: 1,
+ sessionId: 'session-1',
+ succeededCount: 0,
+ topicId: 'topic-1',
+ });
+ });
+
it('generates the proposal with the native JSON schema', async () => {
const fingerprint = 'github@1,gmail@1';
const harness = createHarness(
diff --git a/apps/server/src/services/understanding/service.ts b/apps/server/src/services/understanding/service.ts
index 67d5e351e40..e6bd951836d 100644
--- a/apps/server/src/services/understanding/service.ts
+++ b/apps/server/src/services/understanding/service.ts
@@ -1,7 +1,11 @@
import { createHash, randomUUID } from 'node:crypto';
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
-import { ConnectorDataError } from '@lobechat/connector-data';
+import {
+ ConnectorDataError,
+ getConnectorErrorMessage,
+ isConnectorErrorRetryable,
+} from '@lobechat/connector-data';
import {
getUnderstandingSourceFingerprint,
OnboardingUnderstandingRepository,
@@ -23,6 +27,7 @@ import {
} from '@lobechat/prompts';
import type {
CollectionDiagnostics,
+ CollectionError,
ConfirmOnboardingUnderstandingInput,
OnboardingUnderstandingMessageMetadata,
OnboardingUnderstandingPollingResult,
@@ -33,6 +38,7 @@ import type {
UnderstandingPersonaProposal,
} from '@lobechat/types';
import {
+ MAX_COLLECTION_COUNT,
MAX_COLLECTION_ERRORS,
OnboardingUnderstandingMessageMetadataSchema,
projectOnboardingUnderstandingSessionStatus,
@@ -51,18 +57,54 @@ import { AiGenerationService } from '@/server/services/aiGeneration';
import { ConnectorDataService } from '@/server/services/connectorData';
import { understandingProviderMap } from './providers';
-import {
- boundCanonicalDiagnostics,
- canonicalCollectionError,
- MAX_AGENT_INPUT_LENGTH,
- MAX_SOURCE_BRIEF_LENGTH,
- sanitizeProviderDiagnostics,
-} from './sanitizer';
import type { StoredUnderstandingProviderContext } from './sourceStore';
-import { UnderstandingSourceStore } from './sourceStore';
+import { MAX_SOURCE_BRIEF_LENGTH, UnderstandingSourceStore } from './sourceStore';
import type { UnderstandingProvider } from './types';
const BASELINE_MAX_LENGTH = 8_000;
+const MAX_AGENT_INPUT_LENGTH = 128_000;
+
+const boundedCount = (value: number) =>
+ Number.isFinite(value) ? Math.min(MAX_COLLECTION_COUNT, Math.max(0, Math.floor(value))) : 0;
+
+/**
+ * Bounds provider diagnostic counts without changing their error content.
+ *
+ * Use when:
+ * - Moving provider collection diagnostics across the service boundary
+ *
+ * Expects:
+ * - Providers return serializable CollectionError values
+ *
+ * Returns:
+ * - Bounded counts and error cardinality with original diagnostics preserved
+ */
+const boundProviderDiagnostics = (value: CollectionDiagnostics): CollectionDiagnostics => ({
+ errors: value.errors.slice(0, MAX_COLLECTION_ERRORS),
+ evidenceCount: boundedCount(value.evidenceCount),
+ failedCount: boundedCount(value.failedCount),
+ succeededCount: boundedCount(value.succeededCount),
+});
+
+/**
+ * Creates one structured collection error while retaining its original message.
+ *
+ * Use when:
+ * - Converting a structured internal or Connector Data error for persistence
+ *
+ * Expects:
+ * - Provider, operation, and code are supplied by trusted internal code
+ *
+ * Returns:
+ * - A collection error containing the supplied message without replacement
+ */
+const createCollectionError = (
+ provider: string,
+ operation: string,
+ code: string,
+ retryable: boolean,
+ message = `${provider} ${operation} failed`,
+): CollectionError => ({ code, message, operation, provider, retryable });
interface ProviderOperationInput {
providerId: string;
@@ -181,7 +223,7 @@ const sumDiagnostics = (
const terminalSources = Object.values(session.sources).filter(
({ status }) => status === 'completed' || status === 'failed',
);
- return boundCanonicalDiagnostics({
+ return boundProviderDiagnostics({
errors: terminalSources.flatMap(({ errors }) => errors).slice(-MAX_COLLECTION_ERRORS),
evidenceCount: contexts.reduce(
(total, { diagnostics }) => total + diagnostics.evidenceCount,
@@ -235,6 +277,27 @@ const storedProposal = (metadata: unknown) => {
return parsed.success ? parsed.data : undefined;
};
+/**
+ * Normalizes a thrown provider value into the persisted diagnostic shape without replacing its
+ * original message.
+ *
+ * Before:
+ * - `Error("GraphQL FORBIDDEN at viewer.repository")`
+ *
+ * After:
+ * - `{ provider: "github", operation: "collection", message: "GraphQL FORBIDDEN at viewer.repository" }`
+ */
+const createProviderCollectionError = (providerId: string, error: unknown) => {
+ const connectorError = error instanceof ConnectorDataError ? error : undefined;
+ return createCollectionError(
+ providerId,
+ connectorError?.operation ?? 'collection',
+ connectorError?.code ?? 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',
+ isConnectorErrorRetryable(error),
+ getConnectorErrorMessage(error) ?? String(error),
+ );
+};
+
export class UnderstandingService {
constructor(private readonly dependencies: UnderstandingServiceDependencies) {}
@@ -628,10 +691,7 @@ export class UnderstandingService {
userId: this.dependencies.userId,
});
const context = collected.context.trim().slice(0, MAX_SOURCE_BRIEF_LENGTH);
- const diagnostics = sanitizeProviderDiagnostics(
- input.providerId,
- collected.diagnostics,
- );
+ const diagnostics = boundProviderDiagnostics(collected.diagnostics);
const usable =
Boolean(context) &&
collected.sourceCount > 0 &&
@@ -653,24 +713,11 @@ export class UnderstandingService {
succeededCount: diagnostics.succeededCount,
};
},
- (error) => {
- if (!(error instanceof ConnectorDataError)) return;
- return canonicalCollectionError(
- input.providerId,
- error.operation,
- error.code,
- error.retryable,
- );
- },
+ (error) => createProviderCollectionError(input.providerId, error),
);
} catch (error) {
- if (!(error instanceof ConnectorDataError) || error.retryable) throw error;
- const diagnostic = canonicalCollectionError(
- input.providerId,
- error.operation,
- error.code,
- error.retryable,
- );
+ const diagnostic = createProviderCollectionError(input.providerId, error);
+ if (diagnostic.retryable) throw error;
return this.recordProviderFailure(input, 0, {
errors: [diagnostic],
evidenceCount: 0,
@@ -727,7 +774,7 @@ export class UnderstandingService {
try {
return await this.dependencies.repository.failProvider({
errors: [
- canonicalCollectionError(
+ createCollectionError(
input.providerId,
'collection',
'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',
@@ -903,7 +950,7 @@ export class UnderstandingService {
const current = await this.activeSession(topicId, sessionId);
if (current.writing && current.writing.sourceFingerprint !== sourceFingerprint) return;
const session = await this.dependencies.repository.failWriting({
- error: canonicalCollectionError(
+ error: createCollectionError(
'understanding',
'writing',
'UNDERSTANDING_WRITING_FAILED',
@@ -1074,7 +1121,7 @@ export class UnderstandingService {
return;
}
return this.dependencies.repository.failDetailedWriting({
- error: canonicalCollectionError(
+ error: createCollectionError(
'understanding',
'detailed-writing',
'UNDERSTANDING_DETAILED_WRITING_FAILED',
@@ -1116,7 +1163,7 @@ export class UnderstandingService {
const errors = diagnostics?.errors.length
? diagnostics.errors
: [
- canonicalCollectionError(
+ createCollectionError(
input.providerId,
'collection',
'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',
diff --git a/apps/server/src/services/understanding/sourceStore.ts b/apps/server/src/services/understanding/sourceStore.ts
index fa8e00052c3..b0a4fb8ab2d 100644
--- a/apps/server/src/services/understanding/sourceStore.ts
+++ b/apps/server/src/services/understanding/sourceStore.ts
@@ -11,11 +11,12 @@ import { z } from 'zod';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
-import { MAX_SOURCE_BRIEF_LENGTH } from './sanitizer';
-
const SOURCE_STORE_PREFIX = 'onboarding_understanding:context';
const SOURCE_STORE_TTL_SECONDS = 3 * 24 * 60 * 60;
+/** Maximum provider context size accepted by the Understanding source store. */
+export const MAX_SOURCE_BRIEF_LENGTH = 64_000;
+
interface SessionReference {
sessionId: string;
userId: string;
diff --git a/packages/connector-data/src/errors.test.ts b/packages/connector-data/src/errors.test.ts
index eea5017fef3..7d6659e51c6 100644
--- a/packages/connector-data/src/errors.test.ts
+++ b/packages/connector-data/src/errors.test.ts
@@ -3,25 +3,37 @@ import { describe, expect, it } from 'vitest';
import { ConnectorDataError } from './errors';
describe('ConnectorDataError', () => {
- it('exposes a sanitized connector failure contract', () => {
- const unsafeInput = {
+ /** @example expect(error.message).toBe('upstream response body with status=401'); */
+ it('retains the original connector failure message and cause object', () => {
+ // ROOT CAUSE:
+ //
+ // ConnectorDataError previously retained structured metadata but discarded the upstream error
+ // object, so Error.cause could not expose its response, stack, or SDK-specific fields.
+ //
+ // We fixed this by passing the original value directly to the native Error cause option.
+ const cause = new Error('raw upstream failure');
+ const input = {
+ cause,
code: 'github_request_failed',
- message: 'upstream response body with token=secret',
+ message: 'upstream response body with status=401',
operation: 'listRepositories',
provider: 'github',
retryable: false,
} as const;
- const error = new ConnectorDataError(unsafeInput);
+ const error = new ConnectorDataError(input);
+ /** @example expect(error).toBeInstanceOf(Error); */
expect(error).toBeInstanceOf(Error);
+ /** @example expect(error).toMatchObject({ message: input.message }); */
expect(error).toMatchObject({
code: 'github_request_failed',
- message: 'github listRepositories failed',
+ message: input.message,
name: 'ConnectorDataError',
operation: 'listRepositories',
provider: 'github',
retryable: false,
});
- expect(error.message).not.toContain(unsafeInput.message);
+ /** @example expect(error.cause).toBe(cause); */
+ expect(error.cause).toBe(cause);
});
});
diff --git a/packages/connector-data/src/errors.ts b/packages/connector-data/src/errors.ts
index dd3279e8c1e..c8aa8de4b70 100644
--- a/packages/connector-data/src/errors.ts
+++ b/packages/connector-data/src/errors.ts
@@ -1,22 +1,74 @@
import type { ConnectorDataProvider } from './providers';
-/** Options used to create a sanitized Connector Data boundary error. */
+/** Options used to retain a connector failure across collection boundaries. */
export interface ConnectorDataErrorOptions {
+ /** Original upstream error or response retained without cloning or serialization. */
+ cause?: unknown;
+ /** Stable connector-owned failure code. */
code: string;
+ /** Original upstream error message when one is available. */
+ message?: string;
+ /** Connector sub-operation that failed. */
operation: string;
+ /** Connector provider that executed the failed operation. */
provider: ConnectorDataProvider;
+ /** Whether the same operation can succeed without user intervention. */
retryable: boolean;
}
-/** Sanitized provider error safe to propagate across connector collection boundaries. */
+/**
+ * Reads an error message without replacing upstream diagnostic content.
+ *
+ * Use when:
+ * - Persisting a rejected provider sub-operation
+ * - Wrapping an upstream connector failure
+ *
+ * Expects:
+ * - Any thrown JavaScript value
+ *
+ * Returns:
+ * - The original Error message, string value, or undefined when no message exists
+ */
+export const getConnectorErrorMessage = (error: unknown): string | undefined => {
+ if (error instanceof Error) return error.message;
+ if (typeof error === 'string') return error;
+ if (error === undefined) return;
+ if (
+ typeof error === 'object' &&
+ error !== null &&
+ 'message' in error &&
+ typeof error.message === 'string'
+ ) {
+ return error.message;
+ }
+
+ try {
+ return JSON.stringify(error);
+ } catch {
+ return String(error);
+ }
+};
+
+/**
+ * Connector-owned protocol or validation failure with its diagnostic message preserved.
+ *
+ * Use when:
+ * - Reporting a connector failure created by our own protocol or validation code
+ *
+ * Expects:
+ * - Stable provider, operation, code, and retryability metadata
+ *
+ * Returns:
+ * - An Error carrying connector-owned structured metadata
+ */
export class ConnectorDataError extends Error {
readonly code: string;
readonly operation: string;
readonly provider: ConnectorDataProvider;
readonly retryable: boolean;
- constructor({ code, operation, provider, retryable }: ConnectorDataErrorOptions) {
- super(`${provider} ${operation} failed`);
+ constructor({ cause, code, message, operation, provider, retryable }: ConnectorDataErrorOptions) {
+ super(message ?? `${provider} ${operation} failed`, { cause });
this.name = 'ConnectorDataError';
this.code = code;
diff --git a/packages/connector-data/src/github/graphql/client.test.ts b/packages/connector-data/src/github/graphql/client.test.ts
index 66f694523bc..ed338569df0 100644
--- a/packages/connector-data/src/github/graphql/client.test.ts
+++ b/packages/connector-data/src/github/graphql/client.test.ts
@@ -83,7 +83,8 @@ describe('GitHub GraphQL execute', () => {
expect(request).toHaveBeenCalledTimes(2);
});
- it('sanitizes strict schema failures', async () => {
+ /** @example expect(error.message).toContain('upstreamBody'); */
+ it('retains strict schema failure details', async () => {
const transport = createTransport(
vi.fn().mockResolvedValue({
upstreamBody: 'token=secret-upstream-body',
@@ -100,24 +101,27 @@ describe('GitHub GraphQL execute', () => {
}).catch((reason) => reason);
expect(error).toBeInstanceOf(ConnectorDataError);
+ /** @example expect(error.code).toBe('github_response_invalid'); */
expect(error).toMatchObject({
code: 'github_response_invalid',
- message: 'github TestProfile failed',
operation: 'TestProfile',
+ provider: 'github',
retryable: false,
});
+ /** @example expect(error.cause).toBeInstanceOf(z.ZodError); */
+ expect(error.cause).toBeInstanceOf(z.ZodError);
+ /** @example expect(error.message).toContain('upstreamBody'); */
+ expect(error.message).toContain('upstreamBody');
const diagnostic = JSON.stringify({ error, logs: log.mock.calls });
- expect(diagnostic).not.toMatch(/secret-upstream-body|token=|upstreamBody/);
+ expect(diagnostic).not.toMatch(/secret-upstream-body|token=/);
});
- it('sanitizes terminal upstream failures', async () => {
- const transport = createTransport(
- vi
- .fn()
- .mockRejectedValue(
- Object.assign(new Error('401 token=secret-upstream-body'), { status: 401 }),
- ),
- );
+ /** @example expect(error.message).toBe('401 upstream rejected'); */
+ it('retains terminal upstream failure messages', async () => {
+ const upstreamError = Object.assign(new Error('401 token=secret-upstream-body'), {
+ status: 401,
+ });
+ const transport = createTransport(vi.fn().mockRejectedValue(upstreamError));
const error = await execute({
operation: 'TestProfile',
@@ -127,19 +131,13 @@ describe('GitHub GraphQL execute', () => {
variables: {},
}).catch((reason) => reason);
- expect(error).toMatchObject({
- code: 'github_request_failed',
- message: 'github TestProfile failed',
- retryable: false,
- });
+ expect(error).toBe(upstreamError);
expect(log).toHaveBeenCalledWith('GraphQL request failed: %O', {
errorName: 'Error',
operation: 'TestProfile',
status: 401,
});
- expect(JSON.stringify({ error, logs: log.mock.calls })).not.toMatch(
- /secret-upstream-body|token=/,
- );
+ expect(error.message).toContain('secret-upstream-body');
});
it('logs only safe GraphQL error types and paths', async () => {
@@ -177,10 +175,7 @@ describe('GitHub GraphQL execute', () => {
variables: { token: 'secret-variable' },
}).catch((reason) => reason);
- expect(error).toMatchObject({
- code: 'github_request_failed',
- retryable: false,
- });
+ expect(error).toBe(upstreamError);
expect(log).toHaveBeenCalledWith('GraphQL request failed: %O', {
errorName: 'GraphqlResponseError',
errors: [
diff --git a/packages/connector-data/src/github/graphql/client.ts b/packages/connector-data/src/github/graphql/client.ts
index 1696c2a908d..9f48cb39662 100644
--- a/packages/connector-data/src/github/graphql/client.ts
+++ b/packages/connector-data/src/github/graphql/client.ts
@@ -122,47 +122,42 @@ export const execute = async <Response, Variables extends Record<string, unknown
transport,
variables,
}: ExecuteOptions<Response, Variables>): Promise<Response> =>
- withConnectorRetry(
- async () => {
- let response: unknown;
-
- try {
- response = await transport.request({ operation, query, variables });
- } catch (error) {
- const errors = getGraphQLErrors(error);
- const status = getErrorStatus(error);
- log('GraphQL request failed: %O', {
- errorName: getErrorName(error),
- ...(errors === undefined ? {} : { errors }),
- operation,
- ...(status === undefined ? {} : { status }),
- });
- throw error;
- }
-
- const result = schema.safeParse(response);
- if (result.success) return result.data;
-
- log('GraphQL response validation failed: %O', {
- issues: result.error.issues.slice(0, MAX_ISSUES).map(({ code, path }) => ({
- code,
- path: getIssuePath(path),
- })),
- operation,
- });
- throw new ConnectorDataError({
- code: 'github_response_invalid',
+ withConnectorRetry(async () => {
+ let response: unknown;
+
+ try {
+ response = await transport.request({ operation, query, variables });
+ } catch (error) {
+ const errors = getGraphQLErrors(error);
+ const status = getErrorStatus(error);
+ log('GraphQL request failed: %O', {
+ errorName: getErrorName(error),
+ ...(errors === undefined ? {} : { errors }),
operation,
- provider: 'github',
- retryable: false,
+ ...(status === undefined ? {} : { status }),
});
- },
- {
- code: 'github_request_failed',
+ throw error;
+ }
+
+ const result = schema.safeParse(response);
+ if (result.success) return result.data;
+
+ log('GraphQL response validation failed: %O', {
+ issues: result.error.issues.slice(0, MAX_ISSUES).map(({ code, path }) => ({
+ code,
+ path: getIssuePath(path),
+ })),
+ operation,
+ });
+ throw new ConnectorDataError({
+ cause: result.error,
+ code: 'github_response_invalid',
+ message: result.error.message,
operation,
provider: 'github',
- },
- );
+ retryable: false,
+ });
+ });
/** @internal */
export const createOctokitTransport = (accessToken: string): GitHubConnectorTransport => {
diff --git a/packages/connector-data/src/github/loaders.ts b/packages/connector-data/src/github/loaders.ts
index ae1effa7da9..5dcd7cbfbeb 100644
--- a/packages/connector-data/src/github/loaders.ts
+++ b/packages/connector-data/src/github/loaders.ts
@@ -117,11 +117,7 @@ export const loadUserProfile = async (
profileBundle: Awaited<ReturnType<typeof loadProfileBundle>>,
transport: GitHubConnectorTransport,
): Promise<GitHubUserProfile> => {
- const authenticated = await withConnectorRetry(() => transport.getAuthenticatedUser(), {
- code: 'github_request_failed',
- operation: 'getAuthenticatedUser',
- provider: 'github',
- });
+ const authenticated = await withConnectorRetry(() => transport.getAuthenticatedUser());
const { viewer } = profileBundle;
return {
@@ -139,13 +135,8 @@ export const loadUserProfile = async (
export const loadOrganizations = async (
transport: GitHubConnectorTransport,
): Promise<GitHubOrganization[]> => {
- const organizations = await withConnectorRetry(
- () => transport.listUserOrganizations({ perPage: 20 }),
- {
- code: 'github_request_failed',
- operation: 'listUserOrganizations',
- provider: 'github',
- },
+ const organizations = await withConnectorRetry(() =>
+ transport.listUserOrganizations({ perPage: 20 }),
);
return organizations.flatMap((organization) =>
@@ -444,18 +435,12 @@ export const loadRepositoryContributors = async (
const [owner, repositoryName, ...rest] = repository.split('/');
if (!owner || !repositoryName || rest.length > 0) return [];
- const contributors = await withConnectorRetry(
- () =>
- transport.listRepositoryContributors({
- owner,
- perPage: MAX_CONTRIBUTORS,
- repository: repositoryName,
- }),
- {
- code: 'github_request_failed',
- operation: 'listRepositoryContributors',
- provider: 'github',
- },
+ const contributors = await withConnectorRetry(() =>
+ transport.listRepositoryContributors({
+ owner,
+ perPage: MAX_CONTRIBUTORS,
+ repository: repositoryName,
+ }),
);
return contributors.slice(0, MAX_CONTRIBUTORS).map(({ contributions, login }) => ({
diff --git a/packages/connector-data/src/gmail/account.test.ts b/packages/connector-data/src/gmail/account.test.ts
index 1a5d3a305f0..11ce2d39d82 100644
--- a/packages/connector-data/src/gmail/account.test.ts
+++ b/packages/connector-data/src/gmail/account.test.ts
@@ -175,6 +175,8 @@ describe('loadGmailAccount', () => {
operation: 'getAccount',
provider: 'gmail',
});
+ /** @example expect(error.cause).toBe(account); */
+ expect(error.cause).toBe(account);
expect(error.message).not.toMatch(/account-1|EXPIRED|github/);
});
});
diff --git a/packages/connector-data/src/gmail/account.ts b/packages/connector-data/src/gmail/account.ts
index c13a40539fc..862fc2a42fe 100644
--- a/packages/connector-data/src/gmail/account.ts
+++ b/packages/connector-data/src/gmail/account.ts
@@ -92,22 +92,17 @@ export const loadGmailAccount = async ({
}: LoadGmailAccountOptions): Promise<GmailAccount> => {
try {
let cursor: string | undefined;
+ let matchedAccountResponse: unknown;
let ownedAccount: GmailAccount | undefined;
for (let page = 0; page < MAX_ACCOUNT_PAGES; page += 1) {
- const response = await withConnectorRetry(
- () =>
- connectedAccounts.list({
- ...(cursor ? { cursor } : {}),
- limit: MAX_ACCOUNTS_PER_PAGE,
- toolkitSlugs: ['gmail'],
- userIds: [userId],
- }),
- {
- code: 'gmail_account_unavailable',
- operation: 'getAccount',
- provider: 'gmail',
- },
+ const response = await withConnectorRetry(() =>
+ connectedAccounts.list({
+ ...(cursor ? { cursor } : {}),
+ limit: MAX_ACCOUNTS_PER_PAGE,
+ toolkitSlugs: ['gmail'],
+ userIds: [userId],
+ }),
);
const responseRecord = toRecord(response);
const items = responseRecord?.items;
@@ -122,6 +117,7 @@ export const loadGmailAccount = async ({
}
}
if (match) {
+ matchedAccountResponse = match;
ownedAccount = parseAccount(match);
break;
}
@@ -136,6 +132,7 @@ export const loadGmailAccount = async ({
if (!ownedAccount) {
throw new ConnectorDataError({
+ cause: matchedAccountResponse,
code: 'gmail_account_unavailable',
operation: 'getAccount',
provider: 'gmail',
@@ -144,15 +141,13 @@ export const loadGmailAccount = async ({
}
if (ownedAccount.email && ownedAccount.scopes.length > 0) return ownedAccount;
- const detail = parseAccount(
- await withConnectorRetry(() => connectedAccounts.get(connectedAccountId), {
- code: 'gmail_account_unavailable',
- operation: 'getAccount',
- provider: 'gmail',
- }),
+ const detailResponse = await withConnectorRetry(() =>
+ connectedAccounts.get(connectedAccountId),
);
+ const detail = parseAccount(detailResponse);
if (!detail || detail.externalAccountId !== connectedAccountId) {
throw new ConnectorDataError({
+ cause: detailResponse,
code: 'gmail_account_unavailable',
operation: 'getAccount',
provider: 'gmail',
@@ -166,11 +161,6 @@ export const loadGmailAccount = async ({
};
} catch (error) {
if (error instanceof ConnectorDataError) throw error;
- throw new ConnectorDataError({
- code: 'gmail_account_unavailable',
- operation: 'getAccount',
- provider: 'gmail',
- retryable: false,
- });
+ throw error;
}
};
diff --git a/packages/connector-data/src/gmail/client.test.ts b/packages/connector-data/src/gmail/client.test.ts
index 70cfa368810..7623646006d 100644
--- a/packages/connector-data/src/gmail/client.test.ts
+++ b/packages/connector-data/src/gmail/client.test.ts
@@ -68,19 +68,29 @@ describe('createGmailConnectorClient', () => {
},
);
- it('sanitizes resolved and rejected Composio search failures', async () => {
+ /** @example expect(error.message).toContain('token=secret'); */
+ it('retains resolved failures and rethrows rejected Composio errors', async () => {
+ const rejectedError = new Error('account-1 token=secret');
+ const resolvedFailure = { error: 'token=secret', successful: false };
const execute = vi
.fn()
- .mockResolvedValueOnce({ error: 'token=secret', successful: false })
- .mockRejectedValueOnce(new Error('account-1 token=secret'));
+ .mockResolvedValueOnce(resolvedFailure)
+ .mockRejectedValueOnce(rejectedError);
const client = createClient(execute);
- for (let attempt = 0; attempt < 2; attempt += 1) {
- const error = await client.searchMessages({ query: 'receipt' }).catch((reason) => reason);
- expect(error).toBeInstanceOf(ConnectorDataError);
- expect(error.message).toBe('gmail searchMessages failed');
- expect(error.message).not.toMatch(/secret|account-1/);
- }
+ const resolvedError = await client
+ .searchMessages({ query: 'receipt' })
+ .catch((reason) => reason);
+ /** @example expect(resolvedError).toBeInstanceOf(ConnectorDataError); */
+ expect(resolvedError).toBeInstanceOf(ConnectorDataError);
+ /** @example expect(resolvedError.message).toContain('token=secret'); */
+ expect(resolvedError.message).toContain('token=secret');
+ /** @example expect(resolvedError.cause).toBe(resolvedFailure); */
+ expect(resolvedError.cause).toBe(resolvedFailure);
+
+ const thrownError = await client.searchMessages({ query: 'receipt' }).catch((reason) => reason);
+ /** @example expect(thrownError).toBe(rejectedError); */
+ expect(thrownError).toBe(rejectedError);
});
it.each([
diff --git a/packages/connector-data/src/gmail/client.ts b/packages/connector-data/src/gmail/client.ts
index 3c57efe6cc7..0ab2ec435d2 100644
--- a/packages/connector-data/src/gmail/client.ts
+++ b/packages/connector-data/src/gmail/client.ts
@@ -1,4 +1,4 @@
-import { ConnectorDataError } from '../errors';
+import { ConnectorDataError, getConnectorErrorMessage } from '../errors';
import { createRecoverableMemo } from '../memo';
import { withConnectorRetry } from '../retry';
import type { GmailComposioConnectedAccounts } from './account';
@@ -75,6 +75,7 @@ export const createGmailConnectorClient = ({
: undefined;
if (discovered) return discovered;
throw new ConnectorDataError({
+ cause: tool,
code: 'gmail_tool_version_unavailable',
operation: 'searchMessages',
provider: 'gmail',
@@ -95,48 +96,45 @@ export const createGmailConnectorClient = ({
Math.max(1, Math.floor(finiteMaxResults)),
DEFAULT_MAX_RESULTS,
);
- return withConnectorRetry(
- async () => {
- const version = await getToolVersion();
- const response = await composio.tools.execute(SEARCH_TOOL_SLUG, {
- arguments: {
- max_results: boundedMaxResults,
- query: query.slice(0, MAX_QUERY_LENGTH),
- },
- connectedAccountId,
- userId,
- version,
+ return withConnectorRetry(async () => {
+ const version = await getToolVersion();
+ const response = await composio.tools.execute(SEARCH_TOOL_SLUG, {
+ arguments: {
+ max_results: boundedMaxResults,
+ query: query.slice(0, MAX_QUERY_LENGTH),
+ },
+ connectedAccountId,
+ userId,
+ version,
+ });
+ if (
+ typeof response !== 'object' ||
+ response === null ||
+ !('successful' in response) ||
+ response.successful !== true
+ ) {
+ throw new ConnectorDataError({
+ cause: response,
+ code: 'gmail_search_failed',
+ message: getConnectorErrorMessage(response),
+ operation: 'searchMessages',
+ provider: 'gmail',
+ retryable: false,
});
- if (
- typeof response !== 'object' ||
- response === null ||
- !('successful' in response) ||
- response.successful !== true
- ) {
- throw new ConnectorDataError({
- code: 'gmail_search_failed',
- operation: 'searchMessages',
- provider: 'gmail',
- retryable: false,
- });
- }
- const messages = parseGmailMessages(response, { maxCandidates: boundedMaxResults });
- if (!messages) {
- throw new ConnectorDataError({
- code: 'gmail_response_invalid',
- operation: 'searchMessages',
- provider: 'gmail',
- retryable: false,
- });
- }
- return messages;
- },
- {
- code: 'gmail_search_failed',
- operation: 'searchMessages',
- provider: 'gmail',
- },
- );
+ }
+ const messages = parseGmailMessages(response, { maxCandidates: boundedMaxResults });
+ if (!messages) {
+ throw new ConnectorDataError({
+ cause: response,
+ code: 'gmail_response_invalid',
+ message: getConnectorErrorMessage(response),
+ operation: 'searchMessages',
+ provider: 'gmail',
+ retryable: false,
+ });
+ }
+ return messages;
+ });
},
};
};
diff --git a/packages/connector-data/src/notion/client.test.ts b/packages/connector-data/src/notion/client.test.ts
index 21d55887729..2553cb4f406 100644
--- a/packages/connector-data/src/notion/client.test.ts
+++ b/packages/connector-data/src/notion/client.test.ts
@@ -76,15 +76,16 @@ describe('createNotionConnectorClient', () => {
]);
});
- /** @example Failed tool executions expose sanitized connector errors without account details. */
- it('sanitizes Composio execution failures', async () => {
- const client = createClient(
- vi.fn(async () => ({ error: 'token=secret notion-account', successful: false })),
- );
+ /** @example expect(error.message).toContain('notion-account'); */
+ it('retains Composio execution failure details', async () => {
+ const response = { error: 'token=secret notion-account', successful: false };
+ const client = createClient(vi.fn(async () => response));
const error = await client.listItems().catch((reason) => reason);
expect(error).toBeInstanceOf(ConnectorDataError);
expect(error).toMatchObject({ operation: 'listItems', provider: 'notion', retryable: false });
- expect(error.message).not.toMatch(/secret|notion-account/);
+ expect(error.message).toContain('token=secret notion-account');
+ /** @example expect(error.cause).toBe(response); */
+ expect(error.cause).toBe(response);
});
});
diff --git a/packages/connector-data/src/notion/client.ts b/packages/connector-data/src/notion/client.ts
index 34b44c6c6c5..12e2a08b7a9 100644
--- a/packages/connector-data/src/notion/client.ts
+++ b/packages/connector-data/src/notion/client.ts
@@ -1,4 +1,4 @@
-import { ConnectorDataError } from '../errors';
+import { ConnectorDataError, getConnectorErrorMessage } from '../errors';
import { createRecoverableMemo } from '../memo';
import { withConnectorRetry } from '../retry';
import { parseNotionItems, parseNotionPageMarkdown } from './parser';
@@ -68,7 +68,7 @@ const readToolVersion = (value: unknown): string | undefined => {
* - Composio tool metadata exposes explicit versions when `toolVersion` is omitted
*
* Returns:
- * - A client that normalizes SDK response variants and sanitizes failures
+ * - A client that normalizes SDK response variants and retains provider failure messages
*/
export const createNotionConnectorClient = ({
composio,
@@ -90,6 +90,7 @@ export const createNotionConnectorClient = ({
: undefined;
if (discovered) return discovered;
throw new ConnectorDataError({
+ cause: tool,
code: 'notion_tool_version_unavailable',
operation: 'resolveToolVersion',
provider: 'notion',
@@ -100,32 +101,35 @@ export const createNotionConnectorClient = ({
return resolver();
};
- const execute = async (toolSlug: string, operation: string, arguments_: Record<string, unknown>) =>
- withConnectorRetry(
- async () => {
- const response = await composio.tools.execute(toolSlug, {
- arguments: arguments_,
- connectedAccountId,
- userId,
- version: await getToolVersion(toolSlug),
+ const execute = async (
+ toolSlug: string,
+ operation: string,
+ arguments_: Record<string, unknown>,
+ ) =>
+ withConnectorRetry(async () => {
+ const response = await composio.tools.execute(toolSlug, {
+ arguments: arguments_,
+ connectedAccountId,
+ userId,
+ version: await getToolVersion(toolSlug),
+ });
+ if (
+ typeof response !== 'object' ||
+ response === null ||
+ !('successful' in response) ||
+ response.successful !== true
+ ) {
+ throw new ConnectorDataError({
+ cause: response,
+ code: `notion_${operation}_failed`,
+ message: getConnectorErrorMessage(response),
+ operation,
+ provider: 'notion',
+ retryable: false,
});
- if (
- typeof response !== 'object' ||
- response === null ||
- !('successful' in response) ||
- response.successful !== true
- ) {
- throw new ConnectorDataError({
- code: `notion_${operation}_failed`,
- operation,
- provider: 'notion',
- retryable: false,
- });
- }
- return response;
- },
- { code: `notion_${operation}_failed`, operation, provider: 'notion' },
- );
+ }
+ return response;
+ });
return {
getPageMarkdown: async (pageId) => {
@@ -151,7 +155,9 @@ export const createNotionConnectorClient = ({
const items = parseNotionItems(response, boundedMaxResults);
if (!items) {
throw new ConnectorDataError({
+ cause: response,
code: 'notion_response_invalid',
+ message: getConnectorErrorMessage(response),
operation: 'listItems',
provider: 'notion',
retryable: false,
diff --git a/packages/connector-data/src/retry.test.ts b/packages/connector-data/src/retry.test.ts
index 3129c0fed1a..ed0bdd33835 100644
--- a/packages/connector-data/src/retry.test.ts
+++ b/packages/connector-data/src/retry.test.ts
@@ -4,10 +4,7 @@ import { ConnectorDataError } from './errors';
import { withConnectorRetry } from './retry';
const retryOptions = {
- code: 'github_request_failed',
delay: async () => {},
- operation: 'listRepositories',
- provider: 'github',
} as const;
describe('withConnectorRetry', () => {
@@ -23,27 +20,21 @@ describe('withConnectorRetry', () => {
});
it.each([401, 403, 404])('does not retry status %i', async (status) => {
- const operation = vi.fn<() => Promise<never>>().mockRejectedValue({
+ const upstreamError = {
message: 'unsafe upstream response body with token=secret',
status,
- });
+ };
+ const operation = vi.fn<() => Promise<never>>().mockRejectedValue(upstreamError);
- await expect(withConnectorRetry(operation, retryOptions)).rejects.toMatchObject({
- code: 'github_request_failed',
- message: 'github listRepositories failed',
- operation: 'listRepositories',
- provider: 'github',
- retryable: false,
- });
+ await expect(withConnectorRetry(operation, retryOptions)).rejects.toBe(upstreamError);
expect(operation).toHaveBeenCalledTimes(1);
});
it.each([501, 505])('does not retry non-transient server status %i', async (status) => {
- const operation = vi.fn<() => Promise<never>>().mockRejectedValue({ status });
+ const upstreamError = { status };
+ const operation = vi.fn<() => Promise<never>>().mockRejectedValue(upstreamError);
- await expect(withConnectorRetry(operation, retryOptions)).rejects.toBeInstanceOf(
- ConnectorDataError,
- );
+ await expect(withConnectorRetry(operation, retryOptions)).rejects.toBe(upstreamError);
expect(operation).toHaveBeenCalledTimes(1);
});
@@ -58,14 +49,11 @@ describe('withConnectorRetry', () => {
});
it.each([{ code: 'ETIMEDOUT' }, { status: 503 }])(
- 'marks an exhausted transient error as retryable',
+ 'rethrows the original exhausted transient error',
async (upstreamError) => {
const operation = vi.fn<() => Promise<never>>().mockRejectedValue(upstreamError);
- await expect(withConnectorRetry(operation, retryOptions)).rejects.toMatchObject({
- message: 'github listRepositories failed',
- retryable: true,
- });
+ await expect(withConnectorRetry(operation, retryOptions)).rejects.toBe(upstreamError);
expect(operation).toHaveBeenCalledTimes(3);
},
);
@@ -85,30 +73,16 @@ describe('withConnectorRetry', () => {
).rejects.toBe(upstreamError);
});
- it('sanitizes an unknown terminal error', async () => {
- const unsafeMessage = 'upstream response token=secret';
+ /** @example expect(error.message).toBe('upstream response status=401'); */
+ it('retains an unknown terminal error message', async () => {
+ const upstreamMessage = 'upstream response status=401';
+ const upstreamError = new Error(upstreamMessage);
+ /** @example expect(withConnectorRetry(...)).rejects.toBe(upstreamError); */
await expect(
withConnectorRetry(async () => {
- throw new Error(unsafeMessage);
+ throw upstreamError;
}, retryOptions),
- ).rejects.toEqual(
- expect.objectContaining({
- code: 'github_request_failed',
- message: 'github listRepositories failed',
- operation: 'listRepositories',
- provider: 'github',
- retryable: false,
- }),
- );
-
- try {
- await withConnectorRetry(async () => {
- throw new Error(unsafeMessage);
- }, retryOptions);
- } catch (error) {
- expect(error).toBeInstanceOf(ConnectorDataError);
- expect((error as Error).message).not.toContain(unsafeMessage);
- }
+ ).rejects.toBe(upstreamError);
});
});
diff --git a/packages/connector-data/src/retry.ts b/packages/connector-data/src/retry.ts
index a9cbb543b48..a0f555102dd 100644
--- a/packages/connector-data/src/retry.ts
+++ b/packages/connector-data/src/retry.ts
@@ -1,6 +1,4 @@
-import type { ConnectorDataErrorOptions } from './errors';
import { ConnectorDataError } from './errors';
-import type { ConnectorDataProvider } from './providers';
const DEFAULT_ATTEMPTS = 3;
const FIRST_RETRY_DELAY_MS = 250;
@@ -17,10 +15,8 @@ const TRANSIENT_NETWORK_CODES = new Set([
export type ConnectorRetryDelay = (milliseconds: number) => Promise<void>;
export interface ConnectorRetryOptions {
- code: string;
+ /** Delay implementation used between retry attempts. */
delay?: ConnectorRetryDelay;
- operation: string;
- provider: ConnectorDataProvider;
}
const defaultDelay: ConnectorRetryDelay = async (milliseconds) => {
@@ -50,7 +46,20 @@ const getErrorCode = (error: unknown): string | undefined => {
return typeof code === 'string' ? code : undefined;
};
-const isTransientError = (error: unknown) => {
+/**
+ * Determines whether a connector failure can be retried without user intervention.
+ *
+ * Use when:
+ * - Retrying raw upstream failures
+ * - Persisting provider diagnostics after retries finish
+ *
+ * Expects:
+ * - A raw upstream error or connector-owned protocol error
+ *
+ * Returns:
+ * - Whether the failure matches the connector retry policy
+ */
+export const isConnectorErrorRetryable = (error: unknown) => {
if (error instanceof ConnectorDataError) return error.retryable;
const status = getErrorStatus(error);
@@ -64,38 +73,31 @@ const isTransientError = (error: unknown) => {
return code !== undefined && TRANSIENT_NETWORK_CODES.has(code);
};
+/**
+ * Retries transient connector operations and rethrows the original terminal error.
+ *
+ * Use when:
+ * - Calling an external connector transport with bounded retries
+ *
+ * Expects:
+ * - The operation throws its original upstream or connector-owned error
+ *
+ * Returns:
+ * - The successful operation result without wrapping terminal failures
+ */
export const withConnectorRetry = async <T>(
operation: () => Promise<T>,
- { code, delay = defaultDelay, operation: operationName, provider }: ConnectorRetryOptions,
+ { delay = defaultDelay }: ConnectorRetryOptions = {},
): Promise<T> => {
- for (let attempt = 0; attempt < DEFAULT_ATTEMPTS; attempt += 1) {
+ for (let attempt = 0; ; attempt += 1) {
try {
return await operation();
} catch (error) {
- const retryable = isTransientError(error);
+ const retryable = isConnectorErrorRetryable(error);
const canRetry = attempt < DEFAULT_ATTEMPTS - 1 && retryable;
- if (canRetry) {
- await delay(getRetryDelay(attempt));
- continue;
- }
-
- if (error instanceof ConnectorDataError) throw error;
-
- const errorOptions: ConnectorDataErrorOptions = {
- code,
- operation: operationName,
- provider,
- retryable,
- };
- throw new ConnectorDataError(errorOptions);
+ if (!canRetry) throw error;
+ await delay(getRetryDelay(attempt));
}
}
-
- throw new ConnectorDataError({
- code,
- operation: operationName,
- provider,
- retryable: false,
- });
};
diff --git a/packages/connector-data/src/twitter/marketClient.test.ts b/packages/connector-data/src/twitter/marketClient.test.ts
index da77a91ffcd..348759651f7 100644
--- a/packages/connector-data/src/twitter/marketClient.test.ts
+++ b/packages/connector-data/src/twitter/marketClient.test.ts
@@ -54,8 +54,8 @@ describe('createTwitterMarketConnectorClient', () => {
);
});
- /** @example An embedded HTTP 402 records a safe credits-depleted diagnostic. */
- it('logs the safe reason for embedded Market tool failures', async () => {
+ /** @example An embedded HTTP 402 retains its original provider message. */
+ it('logs the original message for embedded Market tool failures', async () => {
// ROOT CAUSE:
//
// Market reports a successful transport envelope while embedding the X provider failure in
@@ -65,17 +65,16 @@ describe('createTwitterMarketConnectorClient', () => {
// Before: `{ success: true, data: { isError: true, statusCode: 402, error: '...' } }`
// became an untraceable `twitter_searchRecentPosts_failed`.
//
- // We now log a bounded `credits_depleted` reason and status without retaining the raw message.
- const client = createClient(
- vi.fn(async () => ({
- data: {
- error: 'Twitter API Error: credits depleted (HTTP 402); token=secret',
- isError: true,
- statusCode: 402,
- },
- success: true,
- })),
- );
+ // We now retain the original embedded provider message in the thrown diagnostic and log entry.
+ const response = {
+ data: {
+ error: 'Twitter API Error: credits depleted (HTTP 402); token=secret',
+ isError: true,
+ statusCode: 402,
+ },
+ success: true,
+ };
+ const client = createClient(vi.fn(async () => response));
const error = await client
.searchRecentPosts({ query: 'from:ada -is:retweet' })
@@ -84,15 +83,17 @@ describe('createTwitterMarketConnectorClient', () => {
expect(error).toBeInstanceOf(ConnectorDataError);
expect(error).toMatchObject({
code: 'twitter_searchRecentPosts_failed',
+ message: 'Twitter API Error: credits depleted (HTTP 402); token=secret',
operation: 'searchRecentPosts',
retryable: false,
});
+ /** @example expect(error.cause).toBe(response); */
+ expect(error.cause).toBe(response);
expect(mocks.log).toHaveBeenCalledWith('Market X tool call failed: %O', {
+ message: 'Twitter API Error: credits depleted (HTTP 402); token=secret',
operation: 'searchRecentPosts',
- reason: 'credits_depleted',
statusCode: 402,
toolName: 'search_tweets',
});
- expect(JSON.stringify(mocks.log.mock.calls)).not.toContain('token=secret');
});
});
diff --git a/packages/connector-data/src/twitter/marketClient.ts b/packages/connector-data/src/twitter/marketClient.ts
index 86ca88e4cce..3b3d802a369 100644
--- a/packages/connector-data/src/twitter/marketClient.ts
+++ b/packages/connector-data/src/twitter/marketClient.ts
@@ -1,7 +1,7 @@
import { toRecord } from '@lobechat/utils/object';
import debug from 'debug';
-import { ConnectorDataError } from '../errors';
+import { ConnectorDataError, getConnectorErrorMessage } from '../errors';
import { withConnectorRetry } from '../retry';
import { parseTwitterPosts, parseTwitterProfile } from './parser';
import type { TwitterConnectorClient } from './types';
@@ -13,22 +13,10 @@ const RECENT_SEARCH_TOOL_NAME = 'search_tweets';
const log = debug('lobe-server:connector-data:twitter');
interface TwitterMarketToolFailure {
- reason: string;
+ message: string;
statusCode?: number;
}
-/** Maps an untrusted provider error to a bounded, non-sensitive diagnostic reason. */
-const readSafeToolFailureReason = (error: string, statusCode?: number): string => {
- const normalizedError = error.toLowerCase();
- if (normalizedError.includes('credits depleted')) return 'credits_depleted';
- if (normalizedError.includes('token expired')) return 'token_expired';
- if (normalizedError.includes('not connected')) return 'not_connected';
- if (normalizedError.includes('rate limit') || statusCode === 429) return 'rate_limited';
- if (statusCode === 402) return 'payment_required';
-
- return 'upstream_error';
-};
-
/** Result returned by one Market X tool execution. */
export interface TwitterMarketToolResult {
/** Provider response payload, when execution reached the provider. */
@@ -53,10 +41,7 @@ export interface CreateTwitterMarketConnectorClientOptions {
}
/**
- * Extracts a bounded diagnostic from an embedded Market X tool error.
- *
- * The upstream message is intentionally mapped to a safe reason instead of being logged verbatim,
- * because provider errors may include credentials or user content.
+ * Extracts the original diagnostic from an embedded Market X tool error.
*/
const readEmbeddedToolFailure = (value: unknown): TwitterMarketToolFailure | undefined => {
const record = toRecord(value);
@@ -67,10 +52,10 @@ const readEmbeddedToolFailure = (value: unknown): TwitterMarketToolFailure | und
: undefined;
if (record.isError !== true && (statusCode === undefined || statusCode < 400)) return;
- const error = typeof record.error === 'string' ? record.error : '';
- const reason = readSafeToolFailureReason(error, statusCode);
+ const message = getConnectorErrorMessage(record.error) ?? getConnectorErrorMessage(value);
+ if (!message) return;
- return { reason, ...(statusCode === undefined ? {} : { statusCode }) };
+ return { message, ...(statusCode === undefined ? {} : { statusCode }) };
};
/**
@@ -85,7 +70,7 @@ const readEmbeddedToolFailure = (value: unknown): TwitterMarketToolFailure | und
* - Tool responses follow the Market skill result contract
*
* Returns:
- * - A client that normalizes Market response variants and sanitizes provider failures
+ * - A client that normalizes Market response variants and retains provider failure messages
*/
export const createTwitterMarketConnectorClient = ({
market,
@@ -95,28 +80,27 @@ export const createTwitterMarketConnectorClient = ({
operation: string,
arguments_: Record<string, unknown>,
) =>
- withConnectorRetry(
- async () => {
- const response = await market.callTool(toolName, arguments_);
- const failure = readEmbeddedToolFailure(response.data);
- if (response.success !== true || failure) {
- log('Market X tool call failed: %O', {
- operation,
- reason: failure?.reason ?? 'market_call_unsuccessful',
- ...(failure?.statusCode === undefined ? {} : { statusCode: failure.statusCode }),
- toolName,
- });
- throw new ConnectorDataError({
- code: `twitter_${operation}_failed`,
- operation,
- provider: 'twitter',
- retryable: false,
- });
- }
- return response.data;
- },
- { code: `twitter_${operation}_failed`, operation, provider: 'twitter' },
- );
+ withConnectorRetry(async () => {
+ const response = await market.callTool(toolName, arguments_);
+ const failure = readEmbeddedToolFailure(response.data);
+ if (response.success !== true || failure) {
+ log('Market X tool call failed: %O', {
+ message: failure?.message ?? getConnectorErrorMessage(response),
+ operation,
+ ...(failure?.statusCode === undefined ? {} : { statusCode: failure.statusCode }),
+ toolName,
+ });
+ throw new ConnectorDataError({
+ cause: response,
+ code: `twitter_${operation}_failed`,
+ message: failure?.message ?? getConnectorErrorMessage(response),
+ operation,
+ provider: 'twitter',
+ retryable: false,
+ });
+ }
+ return response.data;
+ });
return {
getProfile: async () => {
@@ -135,7 +119,9 @@ export const createTwitterMarketConnectorClient = ({
const profile = parseTwitterProfile(response);
if (!profile) {
throw new ConnectorDataError({
+ cause: response,
code: 'twitter_response_invalid',
+ message: getConnectorErrorMessage(response),
operation: 'getProfile',
provider: 'twitter',
retryable: false,
@@ -174,7 +160,9 @@ export const createTwitterMarketConnectorClient = ({
const posts = parseTwitterPosts(response, boundedMaxResults);
if (!posts) {
throw new ConnectorDataError({
+ cause: response,
code: 'twitter_response_invalid',
+ message: getConnectorErrorMessage(response),
operation: 'searchRecentPosts',
provider: 'twitter',
retryable: false,
diff --git a/packages/observability-otel/src/modules/onboarding-understanding/index.test.ts b/packages/observability-otel/src/modules/onboarding-understanding/index.test.ts
index b7603577c43..338b1148914 100644
--- a/packages/observability-otel/src/modules/onboarding-understanding/index.test.ts
+++ b/packages/observability-otel/src/modules/onboarding-understanding/index.test.ts
@@ -1,6 +1,7 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
+ ATTR_ONBOARDING_UNDERSTANDING_FAILURE_MESSAGE,
ATTR_ONBOARDING_UNDERSTANDING_OPERATION,
ATTR_ONBOARDING_UNDERSTANDING_PROVIDER,
ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_OUTCOME,
@@ -10,9 +11,17 @@ import {
buildOnboardingUnderstandingMetricAttributes,
buildOnboardingUnderstandingProviderCollectionMetricAttributes,
buildOnboardingUnderstandingProviderFailureMetricAttributes,
+ buildOnboardingUnderstandingProviderFailureTraceAttributes,
buildOnboardingUnderstandingTraceAttributes,
+ getOnboardingUnderstandingProviderCollectionStatus,
+ observeOnboardingUnderstandingProviderCollection,
+ operationCounter,
} from './index';
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
/** @example describe('onboarding Understanding observability', () => {}); */
describe('onboarding Understanding observability', () => {
/** @example expect(metricAttributes).not.toHaveProperty('session.id'); */
@@ -65,10 +74,69 @@ describe('onboarding Understanding observability', () => {
});
});
+ /** @example expect(status).toBe('failed'); */
+ it('records returned partial and failed provider collections as business failures', () => {
+ const partialStatus = getOnboardingUnderstandingProviderCollectionStatus('partial');
+ const failedStatus = getOnboardingUnderstandingProviderCollectionStatus('failed');
+ const completedStatus = getOnboardingUnderstandingProviderCollectionStatus('completed');
+
+ /** @example expect(partialStatus).toBe('failed'); */
+ expect(partialStatus).toBe('failed');
+ /** @example expect(failedStatus).toBe('failed'); */
+ expect(failedStatus).toBe('failed');
+ /** @example expect(completedStatus).toBe('success'); */
+ expect(completedStatus).toBe('success');
+ });
+
+ /** @example expect(operationCounter.add).toHaveBeenCalledWith(1, { status: 'failed' }); */
+ it('records a normally returned failed collection as failed instead of success or error', async () => {
+ // ROOT CAUSE:
+ //
+ // The observer initialized operationStatus to success and changed it only when the callback
+ // threw. A provider could return outcome=failed without throwing, so the generic operation
+ // counter incorrectly reported a successful provider.collect operation.
+ //
+ // Before: outcome=failed -> onboarding.understanding.status=success.
+ //
+ // We fixed this by mapping returned partial/failed outcomes to the distinct business status
+ // failed while reserving error for thrown exceptions.
+ const add = vi.spyOn(operationCounter, 'add');
+
+ const result = await observeOnboardingUnderstandingProviderCollection(
+ { providerId: 'gmail', sessionId: 'session-1', topicId: 'topic-1' },
+ async () => ({
+ diagnostics: [
+ {
+ code: 'GMAIL_READ_PERMISSION_REQUIRED',
+ message: 'Gmail read permission is missing',
+ operation: 'permission',
+ retryable: false,
+ },
+ ],
+ evidenceCount: 0,
+ failedCount: 1,
+ outcome: 'failed',
+ result: 'failed-result',
+ sourceCount: 0,
+ succeededCount: 0,
+ }),
+ );
+
+ /** @example expect(result).toBe('failed-result'); */
+ expect(result).toBe('failed-result');
+ /** @example expect(add).toHaveBeenCalledWith(1, { status: 'failed' }); */
+ expect(add).toHaveBeenCalledWith(1, {
+ [ATTR_ONBOARDING_UNDERSTANDING_OPERATION]: 'provider.collect',
+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER]: 'gmail',
+ [ATTR_ONBOARDING_UNDERSTANDING_STATUS]: 'failed',
+ });
+ });
+
/** @example expect(attributes).toHaveProperty('failure.code', 'GMAIL_SEARCH_FAILED'); */
it('builds a bounded provider failure reason label set', () => {
const attributes = buildOnboardingUnderstandingProviderFailureMetricAttributes('gmail', {
code: 'GMAIL_SEARCH_FAILED',
+ message: 'Composio rejected the Gmail search request',
operation: 'recent',
retryable: true,
});
@@ -81,4 +149,24 @@ describe('onboarding Understanding observability', () => {
[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER]: 'gmail',
});
});
+
+ /** @example expect(attributes).toHaveProperty('failure.message', upstreamMessage); */
+ it('retains provider failure messages only on trace-event attributes', () => {
+ const upstreamMessage = 'GraphQL FORBIDDEN at viewer.repository(name: profile)';
+ const attributes = buildOnboardingUnderstandingProviderFailureTraceAttributes('github', {
+ code: 'GITHUB_PROFILE_README_FAILED',
+ message: upstreamMessage,
+ operation: 'profileReadme',
+ retryable: false,
+ });
+
+ /** @example expect(attributes[ATTR_FAILURE_MESSAGE]).toBe(upstreamMessage); */
+ expect(attributes).toEqual({
+ 'onboarding.understanding.failure.code': 'GITHUB_PROFILE_README_FAILED',
+ [ATTR_ONBOARDING_UNDERSTANDING_FAILURE_MESSAGE]: upstreamMessage,
+ 'onboarding.understanding.failure.operation': 'profileReadme',
+ 'onboarding.understanding.failure.retryable': false,
+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER]: 'github',
+ });
+ });
});
diff --git a/packages/observability-otel/src/modules/onboarding-understanding/index.ts b/packages/observability-otel/src/modules/onboarding-understanding/index.ts
index 4113aaff280..6f17c2a488b 100644
--- a/packages/observability-otel/src/modules/onboarding-understanding/index.ts
+++ b/packages/observability-otel/src/modules/onboarding-understanding/index.ts
@@ -26,10 +26,13 @@ export const ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_SOURCE_COUNT =
/** Number of successful provider sub-operations in one collection attempt. */
export const ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_SUCCEEDED_COUNT =
'onboarding.understanding.provider.succeeded_count' as const;
-/** Sanitized failure code attached to provider collection diagnostics. */
+/** Failure code attached to provider collection diagnostics. */
export const ATTR_ONBOARDING_UNDERSTANDING_FAILURE_CODE =
'onboarding.understanding.failure.code' as const;
-/** Sanitized provider sub-operation attached to collection diagnostics. */
+/** Original provider error message attached only to trace events. */
+export const ATTR_ONBOARDING_UNDERSTANDING_FAILURE_MESSAGE =
+ 'onboarding.understanding.failure.message' as const;
+/** Provider sub-operation attached to collection diagnostics. */
export const ATTR_ONBOARDING_UNDERSTANDING_FAILURE_OPERATION =
'onboarding.understanding.failure.operation' as const;
/** Whether a provider collection diagnostic is safe to retry. */
@@ -78,17 +81,19 @@ export type OnboardingUnderstandingOperation =
| 'writer.resolve-agent';
/** Outcome attached to aggregate operation metrics. */
-export type OnboardingUnderstandingOperationStatus = 'error' | 'success';
+export type OnboardingUnderstandingOperationStatus = 'error' | 'failed' | 'success';
/** Business outcome of one provider collection attempt. */
export type OnboardingUnderstandingProviderCollectionOutcome =
'completed' | 'error' | 'failed' | 'partial';
-/** Low-cardinality diagnostic attached to a provider collection attempt. */
+/** Provider diagnostic attached to a collection attempt. */
export interface OnboardingUnderstandingProviderCollectionDiagnostic {
- /** Sanitized, bounded failure code owned by the provider integration. */
+ /** Failure code owned by the provider integration. */
code: string;
- /** Sanitized, bounded provider sub-operation. */
+ /** Original error message retained for persistence and trace inspection. */
+ message: string;
+ /** Provider sub-operation. */
operation: string;
/** Whether retrying the failed sub-operation can succeed without user action. */
retryable: boolean;
@@ -96,7 +101,7 @@ export interface OnboardingUnderstandingProviderCollectionDiagnostic {
/** Result and telemetry summary returned by an observed provider collection callback. */
export interface OnboardingUnderstandingProviderCollectionResult<Result> {
- /** Sanitized diagnostics produced by the provider collection attempt. */
+ /** Diagnostics produced by the provider collection attempt. */
diagnostics: readonly OnboardingUnderstandingProviderCollectionDiagnostic[];
/** Number of evidence items retained by the collection attempt. */
evidenceCount: number;
@@ -170,7 +175,7 @@ export const providerCollectionDurationHistogram = meter.createHistogram(
},
);
-/** Count of sanitized provider collection diagnostics grouped by failure reason. */
+/** Count of provider collection diagnostics grouped by failure reason. */
export const providerCollectionFailureCounter = meter.createCounter(
'onboarding_understanding_provider_collection_failures_total',
{
@@ -258,13 +263,29 @@ export const buildOnboardingUnderstandingProviderCollectionMetricAttributes = (
});
/**
- * Builds low-cardinality attributes for one sanitized provider diagnostic.
+ * Maps a returned provider collection outcome to its aggregate operation status.
+ *
+ * Use when:
+ * - Separating business failures from thrown errors in provider collect metrics
+ *
+ * Expects:
+ * - A provider collection outcome returned without throwing
+ *
+ * Returns:
+ * - `success` only for complete collection; `failed` for partial or unusable results
+ */
+export const getOnboardingUnderstandingProviderCollectionStatus = (
+ outcome: Exclude<OnboardingUnderstandingProviderCollectionOutcome, 'error'>,
+): OnboardingUnderstandingOperationStatus => (outcome === 'completed' ? 'success' : 'failed');
+
+/**
+ * Builds low-cardinality metric attributes for one provider diagnostic.
*
* Use when:
* - Recording the reason and sub-operation for a provider collection failure
*
* Expects:
- * - The service has removed untrusted messages and bounded diagnostic identifiers
+ * - Provider, code, operation, and retryability are suitable for metric labels
*
* Returns:
* - Metric-safe provider, failure code, operation, and retryability attributes
@@ -279,17 +300,40 @@ export const buildOnboardingUnderstandingProviderFailureMetricAttributes = (
[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER]: providerId,
});
+/**
+ * Builds trace-event attributes for one provider diagnostic.
+ *
+ * Use when:
+ * - Recording provider failures on a correlated Understanding span
+ *
+ * Expects:
+ * - The diagnostic contains the original provider error message
+ *
+ * Returns:
+ * - Correlation attributes plus the original message for production debugging
+ */
+export const buildOnboardingUnderstandingProviderFailureTraceAttributes = (
+ providerId: string,
+ diagnostic: OnboardingUnderstandingProviderCollectionDiagnostic,
+): Attributes => ({
+ ...buildOnboardingUnderstandingProviderFailureMetricAttributes(providerId, diagnostic),
+ [ATTR_ONBOARDING_UNDERSTANDING_FAILURE_MESSAGE]: diagnostic.message,
+});
+
const recordProviderCollectionDiagnostic = (
providerId: string,
diagnostic: OnboardingUnderstandingProviderCollectionDiagnostic,
span: Span,
) => {
- const attributes = buildOnboardingUnderstandingProviderFailureMetricAttributes(
+ const metricAttributes = buildOnboardingUnderstandingProviderFailureMetricAttributes(
providerId,
diagnostic,
);
- providerCollectionFailureCounter.add(1, attributes);
- span.addEvent('onboarding.understanding.provider.failure', attributes);
+ providerCollectionFailureCounter.add(1, metricAttributes);
+ span.addEvent(
+ 'onboarding.understanding.provider.failure',
+ buildOnboardingUnderstandingProviderFailureTraceAttributes(providerId, diagnostic),
+ );
};
/**
@@ -297,11 +341,11 @@ const recordProviderCollectionDiagnostic = (
*
* Use when:
* - A provider can return an unusable or partially usable result without throwing
- * - Provider outcome, duration, counts, and sanitized failure reasons must be queryable
+ * - Provider outcome, duration, counts, and failure reasons must be queryable
*
* Expects:
- * - The callback returns sanitized diagnostics and a business outcome
- * - The optional error classifier returns only bounded, non-sensitive diagnostics
+ * - The callback returns diagnostics and a business outcome
+ * - The optional error classifier retains the original failure message
*
* Returns:
* - The callback result while recording both generic operation and provider-specific telemetry
@@ -323,23 +367,25 @@ export const observeOnboardingUnderstandingProviderCollection = async <Result>(
{ attributes: buildOnboardingUnderstandingTraceAttributes(operationAttributes) },
async (span) => {
const startedAt = Date.now();
- let operationStatus: OnboardingUnderstandingOperationStatus = 'success';
+ let operationStatus: OnboardingUnderstandingOperationStatus | undefined;
let outcome: OnboardingUnderstandingProviderCollectionOutcome = 'error';
try {
const observed = await operation();
outcome = observed.outcome;
+ operationStatus = getOnboardingUnderstandingProviderCollectionStatus(outcome);
span.setAttributes({
[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_EVIDENCE_COUNT]: observed.evidenceCount,
[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_FAILED_COUNT]: observed.failedCount,
[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_OUTCOME]: outcome,
[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_SOURCE_COUNT]: observed.sourceCount,
[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_SUCCEEDED_COUNT]: observed.succeededCount,
+ [ATTR_ONBOARDING_UNDERSTANDING_STATUS]: operationStatus,
});
const distinctDiagnostics = new Map(
observed.diagnostics.map((diagnostic) => [
- `${diagnostic.code}\u0000${diagnostic.operation}\u0000${diagnostic.retryable}`,
+ `${diagnostic.code}\u0000${diagnostic.operation}\u0000${diagnostic.retryable}\u0000${diagnostic.message}`,
diagnostic,
]),
);
@@ -347,11 +393,7 @@ export const observeOnboardingUnderstandingProviderCollection = async <Result>(
recordProviderCollectionDiagnostic(attributes.providerId ?? 'provider', diagnostic, span);
}
- if (outcome === 'failed') {
- span.setStatus({ code: SpanStatusCode.ERROR, message: 'provider collection failed' });
- } else {
- span.setStatus({ code: SpanStatusCode.OK });
- }
+ span.setStatus({ code: SpanStatusCode.OK });
return observed.result;
} catch (error) {
operationStatus = 'error';
@@ -362,6 +404,7 @@ export const observeOnboardingUnderstandingProviderCollection = async <Result>(
const errorType = error instanceof Error ? error.name : typeof error;
span.setAttributes({
[ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_OUTCOME]: outcome,
+ [ATTR_ONBOARDING_UNDERSTANDING_STATUS]: operationStatus,
'error.type': errorType,
});
span.setStatus({ code: SpanStatusCode.ERROR, message: errorType });
@@ -372,7 +415,7 @@ export const observeOnboardingUnderstandingProviderCollection = async <Result>(
const providerId = attributes.providerId ?? 'provider';
const metricAttributes = buildOnboardingUnderstandingMetricAttributes(
operationAttributes,
- operationStatus,
+ operationStatus ?? 'error',
);
const providerMetricAttributes =
buildOnboardingUnderstandingProviderCollectionMetricAttributes(providerId, outcome);
diff --git a/packages/types/src/understanding.ts b/packages/types/src/understanding.ts
index 04db04ce00d..585da72a406 100644
--- a/packages/types/src/understanding.ts
+++ b/packages/types/src/understanding.ts
@@ -5,7 +5,6 @@ import type { StrictOnly } from './zodStrict';
export const MAX_COLLECTION_COUNT = 1_000_000;
export const MAX_COLLECTION_ERRORS = 16;
export const MAX_DIAGNOSTIC_CODE_LENGTH = 64;
-export const MAX_DIAGNOSTIC_MESSAGE_LENGTH = 160;
export const MAX_DIAGNOSTIC_OPERATION_LENGTH = 64;
export const MAX_PROVIDER_ID_LENGTH = 64;
export const MAX_ANALYSIS_DESCRIPTION_LENGTH = 2000;
@@ -313,7 +312,7 @@ export interface ConfirmOnboardingUnderstandingResult {
export const CollectionErrorSchema = z
.object({
code: z.string().max(MAX_DIAGNOSTIC_CODE_LENGTH),
- message: z.string().max(MAX_DIAGNOSTIC_MESSAGE_LENGTH),
+ message: z.string(),
operation: z.string().max(MAX_DIAGNOSTIC_OPERATION_LENGTH),
provider: z.string().max(MAX_PROVIDER_ID_LENGTH),
retryable: z.boolean(),