🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(onboarding): expose provider collection outcomes (#18308)
Neko3c09a100cc11
diff --git a/apps/server/src/services/understanding/providers/gmail.test.ts b/apps/server/src/services/understanding/providers/gmail.test.tsindex d2068c9ecb6..da65b3061ab 100644--- a/apps/server/src/services/understanding/providers/gmail.test.ts+++ b/apps/server/src/services/understanding/providers/gmail.test.ts@@ -1,3 +1,4 @@+import { ConnectorDataError } from '@lobechat/connector-data';import { afterEach, describe, expect, it, vi } from 'vitest';import { gmailUnderstandingProvider } from './gmail';@@ -55,4 +56,51 @@ describe('gmailUnderstandingProvider', () => {sourceCount: 0,});});++ /** @example A sanitized connector failure remains identifiable in partial diagnostics. */+ it('preserves the connector failure code for failed Gmail searches', async () => {+ const searchMessages = vi+ .fn()+ .mockResolvedValueOnce([+ {+ id: 'message-1',+ labels: ['INBOX'],+ sender: '[email protected]',+ snippet: 'Project update',+ subject: 'Weekly update',+ },+ ])+ .mockRejectedValue(+ new ConnectorDataError({+ code: 'gmail_tool_version_unavailable',+ operation: 'searchMessages',+ provider: 'gmail',+ retryable: false,+ }),+ );++ const result = 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',+ });++ /** @example expect(result.diagnostics.failedCount).toBe(7); */+ expect(result.diagnostics).toMatchObject({ failedCount: 7, succeededCount: 1 });+ /** @example expect(result.diagnostics.errors).toHaveLength(7); */+ expect(result.diagnostics.errors).toHaveLength(7);+ /** @example expect(result.diagnostics.errors[0].code).toBe('gmail_tool_version_unavailable'); */+ expect(result.diagnostics.errors[0]).toMatchObject({+ code: 'gmail_tool_version_unavailable',+ operation: 'receipts',+ retryable: false,+ });+ });});diff --git a/apps/server/src/services/understanding/providers/gmail.ts b/apps/server/src/services/understanding/providers/gmail.tsindex a5f9babc80b..7ea320a85bd 100644--- a/apps/server/src/services/understanding/providers/gmail.ts+++ b/apps/server/src/services/understanding/providers/gmail.ts@@ -25,6 +25,9 @@ const hasGmailReadPermission = (scopes: readonly string[]) =>),);+const getGmailCollectionErrorCode = (reason: unknown) =>+ reason instanceof ConnectorDataError ? reason.code : 'GMAIL_SEARCH_FAILED';+const evidencePriority = ({ labels }: GmailMessage) => {const normalized = new Set(labels.map((label) => label.toUpperCase()));if (normalized.has('CATEGORY_PROMOTIONS')) return 2;@@ -117,7 +120,7 @@ export const gmailUnderstandingProvider: UnderstandingProvider = {result.status === 'rejected'? [{- code: 'GMAIL_SEARCH_FAILED',+ code: getGmailCollectionErrorCode(result.reason),message: 'Gmail search category failed',operation: GMAIL_PROFILE_SEARCHES[index].operation,provider: 'gmail',diff --git a/apps/server/src/services/understanding/sanitizer.test.ts b/apps/server/src/services/understanding/sanitizer.test.tsnew file mode 100644index 00000000000..70eddb8933b--- /dev/null+++ b/apps/server/src/services/understanding/sanitizer.test.ts@@ -0,0 +1,103 @@+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.tsindex 896a2a25aac..346ae73e479 100644--- a/apps/server/src/services/understanding/sanitizer.ts+++ b/apps/server/src/services/understanding/sanitizer.ts@@ -21,60 +21,68 @@ export {export const MAX_AGENT_INPUT_LENGTH = 128_000;export const MAX_SOURCE_BRIEF_LENGTH = 64_000;-const canonicalErrors: Record<string, { code: string; operation: string }> = {- GITHUB_CONTRIBUTORS_FAILED: {- code: 'GITHUB_CONTRIBUTORS_FAILED',- operation: 'contributors',- },- GITHUB_ORGANIZATIONS_FAILED: {- code: 'GITHUB_ORGANIZATIONS_FAILED',- operation: 'organizations',- },- GITHUB_PINNED_REPOSITORIES_FAILED: {- code: 'GITHUB_PINNED_REPOSITORIES_FAILED',- operation: 'pinned_repositories',- },- GITHUB_PROFILE_README_FAILED: {- code: 'GITHUB_PROFILE_README_FAILED',- operation: 'profile_readme',- },- GITHUB_RECENT_CONTRIBUTIONS_FAILED: {- code: 'GITHUB_RECENT_CONTRIBUTIONS_FAILED',- operation: 'recent_contributions',- },- GITHUB_RECENT_PULL_REQUESTS_FAILED: {- code: 'GITHUB_RECENT_PULL_REQUESTS_FAILED',- operation: 'recent_pull_requests',- },- GITHUB_RECENT_REPOSITORIES_FAILED: {- code: 'GITHUB_RECENT_REPOSITORIES_FAILED',- operation: 'recent_repositories',- },- GMAIL_SEARCH_FAILED: { code: 'GMAIL_SEARCH_FAILED', operation: 'search' },- NOTION_PAGE_CONTENT_FAILED: {- code: 'NOTION_PAGE_CONTENT_FAILED',- operation: 'page_content',- },- UNDERSTANDING_PROVIDER_AUTHORIZATION_FAILED: {- code: 'UNDERSTANDING_PROVIDER_AUTHORIZATION_FAILED',- operation: 'authorize',- },- UNDERSTANDING_PROVIDER_COLLECTION_FAILED: {- code: 'UNDERSTANDING_PROVIDER_COLLECTION_FAILED',- operation: 'collect',- },- UNDERSTANDING_PROVIDER_RESOLUTION_FAILED: {- code: 'UNDERSTANDING_PROVIDER_RESOLUTION_FAILED',- operation: 'resolve',- },-};-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,@@ -82,14 +90,12 @@ export const sanitizeProviderDiagnostics = (const trusted = trustedProvider(provider);return {errors: value.errors.slice(0, MAX_COLLECTION_ERRORS).map((error) => {- const canonical = canonicalErrors[error.code] ?? {- code: 'PROVIDER_COLLECTION_FAILED',- operation: 'collection',- };+ const code = sanitizeDiagnosticCode(trusted, error.code);+ const operation = normalizeDiagnosticOperation(error.operation);return {- code: canonical.code.slice(0, MAX_DIAGNOSTIC_CODE_LENGTH),- message: `${trusted} ${canonical.operation} failed`.slice(0, MAX_DIAGNOSTIC_MESSAGE_LENGTH),- operation: canonical.operation.slice(0, MAX_DIAGNOSTIC_OPERATION_LENGTH),+ code,+ message: `${trusted} ${operation} failed`.slice(0, MAX_DIAGNOSTIC_MESSAGE_LENGTH),+ operation,provider: trusted,retryable: Boolean(error.retryable),};@@ -100,6 +106,18 @@ export const sanitizeProviderDiagnostics = (};};+/**+ * 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),@@ -107,6 +125,18 @@ export const boundCanonicalDiagnostics = (value: CollectionDiagnostics): CollectsucceededCount: 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,@@ -114,9 +144,9 @@ export const canonicalCollectionError = (retryable: boolean,): CollectionError => {const trusted = trustedProvider(provider);- const safeOperation = operation.slice(0, MAX_DIAGNOSTIC_OPERATION_LENGTH);+ const safeOperation = normalizeDiagnosticOperation(operation);return {- code: code.slice(0, MAX_DIAGNOSTIC_CODE_LENGTH),+ code: sanitizeDiagnosticCode(trusted, code),message: `${trusted} ${safeOperation} failed`.slice(0, MAX_DIAGNOSTIC_MESSAGE_LENGTH),operation: safeOperation,provider: trusted,diff --git a/apps/server/src/services/understanding/service.test.ts b/apps/server/src/services/understanding/service.test.tsindex 0a971140555..fde16142b7c 100644--- a/apps/server/src/services/understanding/service.test.ts+++ b/apps/server/src/services/understanding/service.test.ts@@ -302,6 +302,8 @@ const createHarness = (initialSession?: OnboardingUnderstandingSession) => {setLatestAssistant: (value: typeof latestAssistant) => (latestAssistant = value),setAssistantMetadata: (id: string, value: OnboardingUnderstandingMessageMetadata) =>assistantMetadata.set(id, value),+ setProvider: (providerId: string, provider: UnderstandingProvider) =>+ providers.set(providerId, provider),setSession: (value: OnboardingUnderstandingSession) => (session = value),sourceStore,sourceStoreFactory,@@ -628,6 +630,61 @@ 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 () => {+ const harness = createHarness(createSession({ gmail: providerState('running', 1) }));+ harness.setProvider('gmail', {+ collect: vi.fn(async () => ({+ context: '',+ diagnostics: {+ errors: [+ {+ code: 'GMAIL_READ_PERMISSION_REQUIRED',+ message: 'raw account-specific details must not be persisted',+ operation: 'permission',+ provider: 'gmail',+ retryable: false,+ },+ ],+ evidenceCount: 0,+ failedCount: 1,+ succeededCount: 0,+ },+ sourceCount: 0,+ })),+ connectionSource: 'composio',+ id: 'gmail',+ });++ await expect(+ harness.service.processProvider({+ providerId: 'gmail',+ revision: 1,+ sessionId: 'session-1',+ topicId: 'topic-1',+ }),+ ).resolves.toMatchObject({ providerId: 'gmail', status: 'failed' });++ /** @example expect(failProvider).toHaveBeenCalledWith({ errors: [...] }); */+ expect(harness.repository.failProvider).toHaveBeenCalledWith({+ errors: [+ {+ code: 'GMAIL_READ_PERMISSION_REQUIRED',+ message: 'gmail permission failed',+ operation: 'permission',+ provider: 'gmail',+ retryable: false,+ },+ ],+ failedCount: 1,+ providerId: 'gmail',+ 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.tsindex 231d5108730..67d5e351e40 100644--- a/apps/server/src/services/understanding/service.ts+++ b/apps/server/src/services/understanding/service.ts@@ -11,7 +11,10 @@ import {UnderstandingResourceNotFoundError,UnderstandingSessionNotFoundError,} from '@lobechat/database';-import { observeOnboardingUnderstandingOperation } from '@lobechat/observability-otel/modules/onboarding-understanding';+import {+ observeOnboardingUnderstandingOperation,+ observeOnboardingUnderstandingProviderCollection,+} from '@lobechat/observability-otel/modules/onboarding-understanding';import {chainUnderstandingDetailedPersona,chainUnderstandingPersona,@@ -615,28 +618,68 @@ export class UnderstandingService {return stale();}- let collected;+ let collection;try {- collected = await observeOnboardingUnderstandingOperation(- { ...operationAttributes, operation: 'provider.collect' },- () =>- provider.collect({+ collection = await observeOnboardingUnderstandingProviderCollection(+ operationAttributes,+ async () => {+ const collected = await provider.collect({connectorData: this.dependencies.connectorData,userId: this.dependencies.userId,- }),+ });+ const context = collected.context.trim().slice(0, MAX_SOURCE_BRIEF_LENGTH);+ const diagnostics = sanitizeProviderDiagnostics(+ input.providerId,+ collected.diagnostics,+ );+ const usable =+ Boolean(context) &&+ collected.sourceCount > 0 &&+ diagnostics.evidenceCount > 0 &&+ diagnostics.succeededCount > 0;+ const outcome = !usable+ ? ('failed' as const)+ : diagnostics.failedCount > 0 || diagnostics.errors.length > 0+ ? ('partial' as const)+ : ('completed' as const);++ return {+ diagnostics: diagnostics.errors,+ evidenceCount: diagnostics.evidenceCount,+ failedCount: diagnostics.failedCount,+ outcome,+ result: { context, diagnostics, sourceCount: collected.sourceCount, usable },+ sourceCount: collected.sourceCount,+ succeededCount: diagnostics.succeededCount,+ };+ },+ (error) => {+ if (!(error instanceof ConnectorDataError)) return;+ return canonicalCollectionError(+ input.providerId,+ error.operation,+ error.code,+ error.retryable,+ );+ },);} catch (error) {if (!(error instanceof ConnectorDataError) || error.retryable) throw error;- return this.recordProviderFailure(input, 0);+ const diagnostic = canonicalCollectionError(+ input.providerId,+ error.operation,+ error.code,+ error.retryable,+ );+ return this.recordProviderFailure(input, 0, {+ errors: [diagnostic],+ evidenceCount: 0,+ failedCount: 1,+ succeededCount: 0,+ });}- const context = collected.context.trim().slice(0, MAX_SOURCE_BRIEF_LENGTH);- const diagnostics = sanitizeProviderDiagnostics(input.providerId, collected.diagnostics);- const usable =- Boolean(context) &&- collected.sourceCount > 0 &&- diagnostics.evidenceCount > 0 &&- diagnostics.succeededCount > 0;+ const { context, diagnostics, sourceCount, usable } = collection;if (!usable)return this.recordProviderFailure(input, diagnostics.succeededCount, diagnostics);@@ -646,7 +689,7 @@ export class UnderstandingService {providerId: input.providerId,revision: input.revision,sessionId: input.sessionId,- sourceCount: collected.sourceCount,+ sourceCount,userId: this.dependencies.userId,};await observeOnboardingUnderstandingOperation(@@ -672,7 +715,7 @@ export class UnderstandingService {failedCount: diagnostics.failedCount,providerId: input.providerId,revision: input.revision,- sourceCount: collected.sourceCount,+ sourceCount,sourceFingerprint,status: 'completed' as const,succeededCount: diagnostics.succeededCount,diff --git a/packages/observability-otel/src/modules/onboarding-understanding/index.test.ts b/packages/observability-otel/src/modules/onboarding-understanding/index.test.tsindex cb4a5871c14..b7603577c43 100644--- a/packages/observability-otel/src/modules/onboarding-understanding/index.test.ts+++ b/packages/observability-otel/src/modules/onboarding-understanding/index.test.ts@@ -3,10 +3,13 @@ import { describe, expect, it } from 'vitest';import {ATTR_ONBOARDING_UNDERSTANDING_OPERATION,ATTR_ONBOARDING_UNDERSTANDING_PROVIDER,+ ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_OUTCOME,ATTR_ONBOARDING_UNDERSTANDING_SESSION_ID,ATTR_ONBOARDING_UNDERSTANDING_STATUS,ATTR_ONBOARDING_UNDERSTANDING_TOPIC_ID,buildOnboardingUnderstandingMetricAttributes,+ buildOnboardingUnderstandingProviderCollectionMetricAttributes,+ buildOnboardingUnderstandingProviderFailureMetricAttributes,buildOnboardingUnderstandingTraceAttributes,} from './index';@@ -47,4 +50,35 @@ describe('onboarding Understanding observability', () => {[ATTR_ONBOARDING_UNDERSTANDING_TOPIC_ID]: 'topic-1',});});++ /** @example expect(attributes).toEqual({ provider: 'gmail', outcome: 'failed' }); */+ it('records provider collection business outcomes without correlation identifiers', () => {+ const attributes = buildOnboardingUnderstandingProviderCollectionMetricAttributes(+ 'gmail',+ 'failed',+ );++ /** @example expect(attributes).not.toHaveProperty('session.id'); */+ expect(attributes).toEqual({+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER]: 'gmail',+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_OUTCOME]: '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',+ operation: 'recent',+ retryable: true,+ });++ /** @example expect(attributes).not.toHaveProperty('error.message'); */+ expect(attributes).toEqual({+ 'onboarding.understanding.failure.code': 'GMAIL_SEARCH_FAILED',+ 'onboarding.understanding.failure.operation': 'recent',+ 'onboarding.understanding.failure.retryable': true,+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER]: 'gmail',+ });+ });});diff --git a/packages/observability-otel/src/modules/onboarding-understanding/index.ts b/packages/observability-otel/src/modules/onboarding-understanding/index.tsindex 424e0843166..4113aaff280 100644--- a/packages/observability-otel/src/modules/onboarding-understanding/index.ts+++ b/packages/observability-otel/src/modules/onboarding-understanding/index.ts@@ -1,4 +1,4 @@-import type { Attributes } from '@opentelemetry/api';+import type { Attributes, Span } from '@opentelemetry/api';import { metrics, SpanStatusCode, trace } from '@opentelemetry/api';const meter = metrics.getMeter('server-services-onboarding-understanding');@@ -11,6 +11,30 @@ export const ATTR_ONBOARDING_UNDERSTANDING_OPERATION ='onboarding.understanding.operation' as const;/** Provider identifier attached to provider-scoped work. */export const ATTR_ONBOARDING_UNDERSTANDING_PROVIDER = 'onboarding.understanding.provider' as const;+/** Business outcome of one provider collection attempt. */+export const ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_OUTCOME =+ 'onboarding.understanding.provider.outcome' as const;+/** Number of evidence items returned by one provider collection attempt. */+export const ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_EVIDENCE_COUNT =+ 'onboarding.understanding.provider.evidence_count' as const;+/** Number of failed provider sub-operations in one collection attempt. */+export const ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_FAILED_COUNT =+ 'onboarding.understanding.provider.failed_count' as const;+/** Number of source items returned by one provider collection attempt. */+export const ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_SOURCE_COUNT =+ 'onboarding.understanding.provider.source_count' as const;+/** 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. */+export const ATTR_ONBOARDING_UNDERSTANDING_FAILURE_CODE =+ 'onboarding.understanding.failure.code' as const;+/** Sanitized 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. */+export const ATTR_ONBOARDING_UNDERSTANDING_FAILURE_RETRYABLE =+ 'onboarding.understanding.failure.retryable' as const;/** Durable session identifier used only for trace correlation. */export const ATTR_ONBOARDING_UNDERSTANDING_SESSION_ID ='onboarding.understanding.session.id' as const;@@ -56,6 +80,38 @@ export type OnboardingUnderstandingOperation =/** Outcome attached to aggregate operation metrics. */export type OnboardingUnderstandingOperationStatus = 'error' | 'success';+/** Business outcome of one provider collection attempt. */+export type OnboardingUnderstandingProviderCollectionOutcome =+ 'completed' | 'error' | 'failed' | 'partial';++/** Low-cardinality diagnostic attached to a provider collection attempt. */+export interface OnboardingUnderstandingProviderCollectionDiagnostic {+ /** Sanitized, bounded failure code owned by the provider integration. */+ code: string;+ /** Sanitized, bounded provider sub-operation. */+ operation: string;+ /** Whether retrying the failed sub-operation can succeed without user action. */+ retryable: boolean;+}++/** Result and telemetry summary returned by an observed provider collection callback. */+export interface OnboardingUnderstandingProviderCollectionResult<Result> {+ /** Sanitized diagnostics produced by the provider collection attempt. */+ diagnostics: readonly OnboardingUnderstandingProviderCollectionDiagnostic[];+ /** Number of evidence items retained by the collection attempt. */+ evidenceCount: number;+ /** Number of failed provider sub-operations. */+ failedCount: number;+ /** Business outcome derived from the usable collected result. */+ outcome: Exclude<OnboardingUnderstandingProviderCollectionOutcome, 'error'>;+ /** Service result returned after telemetry is recorded. */+ result: Result;+ /** Number of source items retained by the collection attempt. */+ sourceCount: number;+ /** Number of successful provider sub-operations. */+ succeededCount: number;+}+/** Context attached to an onboarding Understanding operation. */export interface OnboardingUnderstandingOperationAttributes {/** Stable low-cardinality operation identifier. */@@ -94,6 +150,36 @@ export const endToEndDurationHistogram = meter.createHistogram(},);+/** Count of provider collection attempts grouped by provider and business outcome. */+export const providerCollectionCounter = meter.createCounter(+ 'onboarding_understanding_provider_collections_total',+ {+ description:+ 'Count of onboarding Understanding provider collection attempts grouped by provider and business outcome.',+ unit: '{collection}',+ },+);++/** Duration of provider collection attempts grouped by provider and business outcome. */+export const providerCollectionDurationHistogram = meter.createHistogram(+ 'onboarding_understanding_provider_collection_duration',+ {+ description:+ 'Duration of onboarding Understanding provider collection attempts grouped by provider and business outcome.',+ unit: 'ms',+ },+);++/** Count of sanitized provider collection diagnostics grouped by failure reason. */+export const providerCollectionFailureCounter = meter.createCounter(+ 'onboarding_understanding_provider_collection_failures_total',+ {+ description:+ 'Count of distinct onboarding Understanding provider collection diagnostics grouped by provider, operation, code, and retryability.',+ unit: '{diagnostic}',+ },+);+/*** Builds low-cardinality attributes for aggregate Understanding metrics.*@@ -151,6 +237,155 @@ export const buildOnboardingUnderstandingTraceAttributes = (return result;};+/**+ * Builds low-cardinality attributes for provider collection attempt metrics.+ *+ * Use when:+ * - Recording one provider collection attempt and its duration+ *+ * Expects:+ * - Provider identifiers and outcomes come from bounded internal unions or registries+ *+ * Returns:+ * - Metric-safe provider and outcome attributes without session identifiers+ */+export const buildOnboardingUnderstandingProviderCollectionMetricAttributes = (+ providerId: string,+ outcome: OnboardingUnderstandingProviderCollectionOutcome,+): Attributes => ({+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER]: providerId,+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_OUTCOME]: outcome,+});++/**+ * Builds low-cardinality attributes for one sanitized 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+ *+ * Returns:+ * - Metric-safe provider, failure code, operation, and retryability attributes+ */+export const buildOnboardingUnderstandingProviderFailureMetricAttributes = (+ providerId: string,+ diagnostic: OnboardingUnderstandingProviderCollectionDiagnostic,+): Attributes => ({+ [ATTR_ONBOARDING_UNDERSTANDING_FAILURE_CODE]: diagnostic.code,+ [ATTR_ONBOARDING_UNDERSTANDING_FAILURE_OPERATION]: diagnostic.operation,+ [ATTR_ONBOARDING_UNDERSTANDING_FAILURE_RETRYABLE]: diagnostic.retryable,+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER]: providerId,+});++const recordProviderCollectionDiagnostic = (+ providerId: string,+ diagnostic: OnboardingUnderstandingProviderCollectionDiagnostic,+ span: Span,+) => {+ const attributes = buildOnboardingUnderstandingProviderFailureMetricAttributes(+ providerId,+ diagnostic,+ );+ providerCollectionFailureCounter.add(1, attributes);+ span.addEvent('onboarding.understanding.provider.failure', attributes);+};++/**+ * Observes one provider collection attempt with business-result telemetry.+ *+ * 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+ *+ * Expects:+ * - The callback returns sanitized diagnostics and a business outcome+ * - The optional error classifier returns only bounded, non-sensitive diagnostics+ *+ * Returns:+ * - The callback result while recording both generic operation and provider-specific telemetry+ */+export const observeOnboardingUnderstandingProviderCollection = async <Result>(+ attributes: Omit<OnboardingUnderstandingOperationAttributes, 'operation'>,+ operation: () => Promise<OnboardingUnderstandingProviderCollectionResult<Result>>,+ classifyError?: (+ error: unknown,+ ) => OnboardingUnderstandingProviderCollectionDiagnostic | undefined,+): Promise<Result> => {+ const operationAttributes: OnboardingUnderstandingOperationAttributes = {+ ...attributes,+ operation: 'provider.collect',+ };++ return tracer.startActiveSpan(+ 'onboarding_understanding.provider.collect',+ { attributes: buildOnboardingUnderstandingTraceAttributes(operationAttributes) },+ async (span) => {+ const startedAt = Date.now();+ let operationStatus: OnboardingUnderstandingOperationStatus = 'success';+ let outcome: OnboardingUnderstandingProviderCollectionOutcome = 'error';++ try {+ const observed = await operation();+ outcome = observed.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,+ });++ const distinctDiagnostics = new Map(+ observed.diagnostics.map((diagnostic) => [+ `${diagnostic.code}\u0000${diagnostic.operation}\u0000${diagnostic.retryable}`,+ diagnostic,+ ]),+ );+ for (const diagnostic of distinctDiagnostics.values()) {+ recordProviderCollectionDiagnostic(attributes.providerId ?? 'provider', diagnostic, span);+ }++ if (outcome === 'failed') {+ span.setStatus({ code: SpanStatusCode.ERROR, message: 'provider collection failed' });+ } else {+ span.setStatus({ code: SpanStatusCode.OK });+ }+ return observed.result;+ } catch (error) {+ operationStatus = 'error';+ const diagnostic = classifyError?.(error);+ if (diagnostic) {+ recordProviderCollectionDiagnostic(attributes.providerId ?? 'provider', diagnostic, span);+ }+ const errorType = error instanceof Error ? error.name : typeof error;+ span.setAttributes({+ [ATTR_ONBOARDING_UNDERSTANDING_PROVIDER_OUTCOME]: outcome,+ 'error.type': errorType,+ });+ span.setStatus({ code: SpanStatusCode.ERROR, message: errorType });+ span.recordException(error instanceof Error ? error : String(error));+ throw error;+ } finally {+ const duration = Date.now() - startedAt;+ const providerId = attributes.providerId ?? 'provider';+ const metricAttributes = buildOnboardingUnderstandingMetricAttributes(+ operationAttributes,+ operationStatus,+ );+ const providerMetricAttributes =+ buildOnboardingUnderstandingProviderCollectionMetricAttributes(providerId, outcome);+ operationCounter.add(1, metricAttributes);+ operationDurationHistogram.record(duration, metricAttributes);+ providerCollectionCounter.add(1, providerMetricAttributes);+ providerCollectionDurationHistogram.record(duration, providerMetricAttributes);+ span.end();+ }+ },+ );+};+/*** Observes one asynchronous onboarding Understanding operation.*