🤯 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
♻️ refactor: add shared guard helpers (#15122)
YuTengjing0e346c5b72d5
diff --git a/.agents/skills/typescript/SKILL.md b/.agents/skills/typescript/SKILL.mdindex 6fe15909dc6..30d67293e00 100644--- a/.agents/skills/typescript/SKILL.md+++ b/.agents/skills/typescript/SKILL.md@@ -48,6 +48,7 @@ user-invocable: false- Replace magic numbers/strings with well-named constants- Defer formatting to tooling- Prefer **named exports** over `export default` — keeps refactor renames and IDE auto-import in sync, and avoids the `default` re-naming drift you get with `import Foo from './foo'`. Reserve `export default` for files where the framework requires it (Next.js page/route/layout, React.lazy targets, config files like `vitest.config.ts`)+- Before adding local helpers for common guards/parsing/normalization (record checks, string extraction, empty-string handling, timing helpers, JSON-safe utilities, etc.), search `packages/utils` first. If the helper already exists or clearly belongs there, import it from `@lobechat/utils` (or the relevant `@lobechat/utils/*` subpath) instead of duplicating tiny helpers across feature files.## UI and Themingdiff --git a/packages/model-runtime/src/providers/deepseek/sanitizePayload.ts b/packages/model-runtime/src/providers/deepseek/sanitizePayload.tsindex 7f5428157d5..a46b857c0ce 100644--- a/packages/model-runtime/src/providers/deepseek/sanitizePayload.ts+++ b/packages/model-runtime/src/providers/deepseek/sanitizePayload.ts@@ -1,3 +1,5 @@+import { isPlainRecord } from '@lobechat/utils';+const HIGH_SURROGATE_START = 0xd8_00;const HIGH_SURROGATE_END = 0xdb_ff;const LOW_SURROGATE_START = 0xdc_00;@@ -40,13 +42,6 @@ const sanitizeDeepSeekJsonString = (value: string) => {return sanitized;};-const isPlainRecord = (value: unknown): value is Record<string, unknown> => {- if (!value || typeof value !== 'object') return false;-- const prototype = Object.getPrototypeOf(value);- return prototype === Object.prototype || prototype === null;-};-const setIfChanged = (target: Record<string, unknown>,source: Record<string, unknown>,diff --git a/packages/model-runtime/src/providers/xai/index.ts b/packages/model-runtime/src/providers/xai/index.tsindex 371382fcfad..1afa8d156cd 100644--- a/packages/model-runtime/src/providers/xai/index.ts+++ b/packages/model-runtime/src/providers/xai/index.ts@@ -1,3 +1,4 @@+import { isRecord } from '@lobechat/utils';import { ModelProvider } from 'model-bank';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';@@ -39,9 +40,6 @@ const pruneUnsupportedChatCompletionParameters = (payload: ChatStreamPayload) =>return stripUnsupportedPenaltyParameters(payload);};-const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null && !Array.isArray(value);-const hasSlashDelimitedEnumValue = (value: unknown) =>Array.isArray(value) && value.some((item) => typeof item === 'string' && item.includes('/'));diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.tsindex dfe9ed72361..7ffbda94672 100644--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts@@ -1,3 +1,5 @@+import { toRecord } from '@lobechat/utils';+import { AgentRuntimeErrorType } from '../types/error';const NON_RETRYABLE_ERROR_TYPES = new Set<string>([AgentRuntimeErrorType.ExceededContextWindow]);@@ -76,9 +78,6 @@ const NON_RETRYABLE_MESSAGE_PATTERNS = ['unrecognized request argument',];-const toRecord = (value: unknown): Record<string, unknown> | undefined =>- value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;-const collectErrorStrings = (value: unknown,visited = new WeakSet<object>(),@@ -96,6 +95,13 @@ const collectErrorStrings = (].filter(Boolean);}+ if (Array.isArray(value)) {+ if (visited.has(value)) return [];+ visited.add(value);++ return value.flatMap((item) => collectErrorStrings(item, visited, depth + 1));+ }+const objectValue = toRecord(value);if (!objectValue) return [];if (visited.has(objectValue)) return [];@@ -116,6 +122,13 @@ const collectStatusCodes = (depth = 0,): number[] => {if (depth > 4 || value === undefined || value === null) return [];+ if (Array.isArray(value)) {+ if (visited.has(value)) return [];+ visited.add(value);++ return value.flatMap((item) => collectStatusCodes(item, visited, depth + 1));+ }+const objectValue = toRecord(value);if (!objectValue) return [];if (visited.has(objectValue)) return [];diff --git a/packages/utils/src/object.test.ts b/packages/utils/src/object.test.tsindex 25a14072822..541489b537a 100644--- a/packages/utils/src/object.test.ts+++ b/packages/utils/src/object.test.ts@@ -1,6 +1,17 @@import { describe, expect, it } from 'vitest';-import { cleanObject } from './object';+import {+ cleanObject,+ isNonEmptyString,+ isObjectLike,+ isPlainRecord,+ isRecord,+ isTrimmedNonEmptyString,+ pickNonEmptyString,+ pickString,+ pickTrimmedString,+ toRecord,+} from './object';describe('cleanObject', () => {it('should remove null, undefined and empty string fields', () => {@@ -17,3 +28,95 @@ describe('cleanObject', () => {expect(res).toEqual({ a: 1, e: 0, f: false, abc: {} });});});++describe('record guards', () => {+ class Example {}++ const nullPrototypeObject = Object.create(null) as Record<string, unknown>;+ nullPrototypeObject.value = true;++ it('should detect non-null objects including arrays as object-like values', () => {+ expect(isObjectLike({ value: true })).toBe(true);+ expect(isObjectLike([1, 2, 3])).toBe(true);+ expect(isObjectLike(nullPrototypeObject)).toBe(true);+ expect(isObjectLike(new Example())).toBe(true);+ expect(isObjectLike(null)).toBe(false);+ expect(isObjectLike('value')).toBe(false);+ });++ it('should detect non-null non-array objects as records', () => {+ expect(isRecord({ value: true })).toBe(true);+ expect(isRecord(nullPrototypeObject)).toBe(true);+ expect(isRecord(new Example())).toBe(true);+ expect(isRecord(new Error('error'))).toBe(true);+ expect(isRecord(new Date('2026-01-01T00:00:00.000Z'))).toBe(true);+ });++ it('should reject primitives, nullish values, and arrays as records', () => {+ expect(isRecord(null)).toBe(false);+ expect(isRecord(undefined)).toBe(false);+ expect(isRecord('value')).toBe(false);+ expect(isRecord(1)).toBe(false);+ expect(isRecord(true)).toBe(false);+ expect(isRecord([1, 2, 3])).toBe(false);+ });++ it('should detect only prototype-plain records', () => {+ expect(isPlainRecord({ value: true })).toBe(true);+ expect(isPlainRecord(nullPrototypeObject)).toBe(true);++ expect(isPlainRecord(new Example())).toBe(false);+ expect(isPlainRecord(new Error('error'))).toBe(false);+ expect(isPlainRecord(new Date('2026-01-01T00:00:00.000Z'))).toBe(false);+ expect(isPlainRecord([1, 2, 3])).toBe(false);+ expect(isPlainRecord(null)).toBe(false);+ });++ it('should return records or undefined', () => {+ const record = { value: true };++ expect(toRecord(record)).toBe(record);+ expect(toRecord([record])).toBeUndefined();+ expect(toRecord(null)).toBeUndefined();+ });+});++describe('string guards', () => {+ it('should pick strings without filtering empty values', () => {+ expect(pickString('')).toBe('');+ expect(pickString(' ')).toBe(' ');+ expect(pickString('value')).toBe('value');+ expect(pickString(1)).toBeUndefined();+ });++ it('should detect and pick raw non-empty strings', () => {+ expect(isNonEmptyString('')).toBe(false);+ expect(isNonEmptyString(' ')).toBe(true);+ expect(isNonEmptyString('value')).toBe(true);+ expect(isNonEmptyString(null)).toBe(false);++ expect(pickNonEmptyString('')).toBeUndefined();+ expect(pickNonEmptyString(' ')).toBe(' ');+ expect(pickNonEmptyString('value')).toBe('value');+ });++ it('should detect trimmed non-empty strings while preserving predicate input', () => {+ const value = ' value ' as unknown;++ expect(isTrimmedNonEmptyString('')).toBe(false);+ expect(isTrimmedNonEmptyString(' ')).toBe(false);+ expect(isTrimmedNonEmptyString(value)).toBe(true);+ expect(isTrimmedNonEmptyString(null)).toBe(false);++ if (isTrimmedNonEmptyString(value)) {+ expect(value).toBe(' value ');+ }+ });++ it('should pick trimmed strings', () => {+ expect(pickTrimmedString('')).toBeUndefined();+ expect(pickTrimmedString(' ')).toBeUndefined();+ expect(pickTrimmedString(' value ')).toBe('value');+ expect(pickTrimmedString(1)).toBeUndefined();+ });+});diff --git a/packages/utils/src/object.ts b/packages/utils/src/object.tsindex 1a7ac7e7129..59c24316600 100644--- a/packages/utils/src/object.ts+++ b/packages/utils/src/object.ts@@ -1,5 +1,55 @@import { isNil, omitBy } from 'es-toolkit/compat';+export type UnknownRecord = Record<PropertyKey, unknown>;++/**+ * Checks for any non-null object, including arrays.+ *+ * Prefer `isRecord` for normal object maps. Use this only when unknown object-shaped payloads+ * must be preserved instead of being classified as empty or invalid.+ */+export const isObjectLike = (value: unknown): value is UnknownRecord =>+ typeof value === 'object' && value !== null;++/**+ * Checks for non-null, non-array objects.+ *+ * This intentionally accepts class instances, `Error`, `Date`, and null-prototype objects. Use+ * `isPlainRecord` when prototype-strict plain object semantics are required.+ */+export const isRecord = (value: unknown): value is UnknownRecord =>+ isObjectLike(value) && !Array.isArray(value);++export const isPlainRecord = (value: unknown): value is UnknownRecord => {+ if (!isRecord(value)) return false;++ const prototype = Object.getPrototypeOf(value);+ return prototype === Object.prototype || prototype === null;+};++export const toRecord = (value: unknown): UnknownRecord | undefined =>+ isRecord(value) ? value : undefined;++export const pickString = (value: unknown): string | undefined =>+ typeof value === 'string' ? value : undefined;++export const isNonEmptyString = (value: unknown): value is string =>+ typeof value === 'string' && value.length > 0;++export const pickNonEmptyString = (value: unknown): string | undefined =>+ isNonEmptyString(value) ? value : undefined;++export const isTrimmedNonEmptyString = (value: unknown): value is string =>+ typeof value === 'string' && value.trim().length > 0;++export const pickTrimmedString = (value: unknown): string | undefined => {+ const stringValue = pickString(value);+ if (stringValue === undefined) return undefined;++ const trimmed = stringValue.trim();+ return trimmed.length > 0 ? trimmed : undefined;+};+/*** Clean empty values (undefined, null, empty string) from an object* @param obj The object to cleandiff --git a/packages/utils/src/timing.ts b/packages/utils/src/timing.tsindex d41e0bdffe8..f09c0111f5e 100644--- a/packages/utils/src/timing.ts+++ b/packages/utils/src/timing.ts@@ -1,5 +1,7 @@import debug from 'debug';+import { isRecord, pickString } from './object';+export interface TimingContext {requestId: string;startedAt: number;@@ -28,9 +30,6 @@ export const createTimingRequestId = () =>globalThis.crypto?.randomUUID?.() ??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;-const isRecord = (value: unknown): value is Record<string, unknown> =>- !!value && typeof value === 'object';-export const getTimingErrorMetadata = (error: unknown): TimingMetadata => {if (error instanceof Error) {return {@@ -41,7 +40,7 @@ export const getTimingErrorMetadata = (error: unknown): TimingMetadata => {if (isRecord(error)) {return {- errorType: typeof error.errorType === 'string' ? error.errorType : undefined,+ errorType: pickString(error.errorType),status: typeof error.status === 'number' ? error.status : undefined,};}diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.tsindex 0ad1d9c6ee9..8832c60d68b 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts@@ -6,6 +6,7 @@ import {} from '@lobechat/builtin-tool-web-onboarding';import { buildAgentMarketplaceToolResult } from '@lobechat/builtin-tool-web-onboarding/agentMarketplace';import type { OnboardingAgentMarketplacePickSnapshot } from '@lobechat/types';+import { pickString } from '@lobechat/utils';import { installMarketplaceAgents } from '@/services/installMarketplaceAgents';import { topicService } from '@/services/topic';@@ -39,8 +40,6 @@ const isAgentMarketplaceCall = (identifier: string, apiName?: string) =>const isStringArray = (value: unknown): value is string[] =>Array.isArray(value) && value.every((item) => typeof item === 'string');-const pickString = (value: unknown) => (typeof value === 'string' ? value : undefined);-const resolveMarketplacePickBase = (payload: Record<string, unknown>,requestArgs?: Record<string, unknown>,diff --git a/src/libs/editor/hasMeaningfulEditorContent.test.ts b/src/libs/editor/hasMeaningfulEditorContent.test.tsindex e81d57e89ce..8c036262530 100644--- a/src/libs/editor/hasMeaningfulEditorContent.test.ts+++ b/src/libs/editor/hasMeaningfulEditorContent.test.ts@@ -45,4 +45,9 @@ describe('hasMeaningfulEditorContent', () => {}),).toBe(true);});++ it('should preserve unknown array-shaped editor payloads as meaningful', () => {+ expect(hasMeaningfulEditorContent([])).toBe(true);+ expect(hasMeaningfulEditorContent({ root: [] })).toBe(true);+ });});diff --git a/src/libs/editor/hasMeaningfulEditorContent.ts b/src/libs/editor/hasMeaningfulEditorContent.tsindex 9c2434912ad..c9e2015cd86 100644--- a/src/libs/editor/hasMeaningfulEditorContent.ts+++ b/src/libs/editor/hasMeaningfulEditorContent.ts@@ -1,17 +1,16 @@-const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null;+import { isObjectLike } from '@lobechat/utils';export const hasMeaningfulEditorContent = (editorData: unknown): boolean => {- if (!isRecord(editorData)) return false;+ if (!isObjectLike(editorData)) return false;const root = editorData.root;// Unknown shapes are treated as meaningful so callers do not drop data they// cannot safely classify.- if (!isRecord(root) || !Array.isArray(root.children)) return true;+ if (!isObjectLike(root) || !Array.isArray(root.children)) return true;const walk = (node: unknown): boolean => {- if (!isRecord(node)) return false;+ if (!isObjectLike(node)) return false;if (typeof node.text === 'string' && node.text.trim().length > 0) return true;diff --git a/src/libs/editor/normalizeDiffNodes.ts b/src/libs/editor/normalizeDiffNodes.tsindex e93c3c416c9..4d4c7567f5d 100644--- a/src/libs/editor/normalizeDiffNodes.ts+++ b/src/libs/editor/normalizeDiffNodes.ts@@ -1,3 +1,5 @@+import { isRecord } from '@lobechat/utils';+type DiffType =| 'add'| 'listItemAdd'@@ -26,9 +28,6 @@ interface SerializedDiffNodeLike extends Record<string, unknown> {type: 'diff';}-const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null && !Array.isArray(value);-const isDiffNode = (value: unknown): value is SerializedDiffNodeLike =>isRecord(value) && value.type === 'diff';diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.tsindex 29bb1f33ef1..e1e214cac79 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts@@ -12,7 +12,7 @@ import {createAgentSignalMemoryWriterSystemRole,} from '@lobechat/prompts';import { LayersEnum, RequestTrigger, ThreadType } from '@lobechat/types';-import { nanoid } from '@lobechat/utils';+import { isRecord, nanoid, pickTrimmedString } from '@lobechat/utils';import { PluginModel } from '@/database/models/plugin';import { ThreadModel } from '@/database/models/thread';@@ -178,11 +178,8 @@ const hasFailedMemoryWrite = (state: AgentState) => {);};-const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null && !Array.isArray(value);-const getString = (value: unknown) => {- return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;+ return pickTrimmedString(value);};const parseToolArguments = (value: unknown): Record<string, unknown> | undefined => {diff --git a/src/server/services/agentSignal/services/selfIteration/execute.ts b/src/server/services/agentSignal/services/selfIteration/execute.tsindex ef2f9ba9fbd..7520e1cb5f8 100644--- a/src/server/services/agentSignal/services/selfIteration/execute.ts+++ b/src/server/services/agentSignal/services/selfIteration/execute.ts@@ -14,6 +14,7 @@ import {} from '@lobechat/prompts';import type { ChatToolPayload, MessageToolCall, ModelUsage } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';+import { isTrimmedNonEmptyString, toRecord } from '@lobechat/utils';import type { NightlyReviewContext } from './review/collect';import type { SelfReviewIdea, SelfReviewProposalBaseSnapshot } from './review/proposal';@@ -460,15 +461,11 @@ const createRuntimePrompt = (input: ExecuteSelfIterationInput) =>window: getIterationWindow(input),});-const toNullableString = (value: unknown) =>- typeof value === 'string' && value.trim().length > 0 ? value : undefined;+const toNullableString = (value: unknown) => (isTrimmedNonEmptyString(value) ? value : undefined);const toBoolean = (value: unknown) => (typeof value === 'boolean' ? value : undefined);-const toRecord = (value: unknown): Record<string, unknown> =>- value && typeof value === 'object' && !Array.isArray(value)- ? (value as Record<string, unknown>)- : {};+const toRecordOrEmpty = (value: unknown) => toRecord(value) ?? {};const toUnknownArray = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);@@ -478,7 +475,7 @@ const toStringArray = (value: unknown) =>const toEvidenceRefs = (value: unknown): EvidenceRef[] =>Array.isArray(value)? value.flatMap((item) => {- const record = toRecord(item);+ const record = toRecordOrEmpty(item);const id = toNullableString(record.id);const type = toNullableString(record.type);@@ -519,7 +516,7 @@ const toRisk = (value: unknown): Risk => {};const toTarget = (value: unknown): ActionTarget | undefined => {- const record = toRecord(value);+ const record = toRecordOrEmpty(value);const target: ActionTarget = {memoryId: toNullableString(record.memoryId),skillDocumentId: toNullableString(record.skillDocumentId),@@ -536,7 +533,7 @@ const toTarget = (value: unknown): ActionTarget | undefined => {const normalizeProposalActions = (value: unknown) =>toUnknownArray(value).map((item) => {- const record = toRecord(item);+ const record = toRecordOrEmpty(item);return {...record,@@ -585,7 +582,7 @@ const toSelfFeedbackIntent = (args: Record<string, unknown>): SelfFeedbackIntentdowngradeReason: toDowngradeReason(args.downgradeReason),intentType: toIntentType(args.intentType),mode: 'reflection',- operation: toRecord(args.operation) as SelfFeedbackIntent['operation'],+ operation: toRecordOrEmpty(args.operation) as SelfFeedbackIntent['operation'],urgency: toUrgency(args.urgency),});@@ -606,7 +603,7 @@ const parseToolArguments = (value: string | undefined): Record<string, unknown>try {const parsed = JSON.parse(value) as unknown;- return toRecord(parsed);+ return toRecordOrEmpty(parsed);} catch {return {};}@@ -684,7 +681,7 @@ const withUser = <TInput extends ToolWriteInput>(}) as TInput;const toBaseSnapshot = (value: unknown): SelfReviewProposalBaseSnapshot => {- const record = toRecord(value);+ const record = toRecordOrEmpty(value);return {absent: toBoolean(record.absent),@@ -819,7 +816,7 @@ const executeRuntimeTool = async (toolCall.id,{actions: normalizeProposalActions(args.actions),- metadata: toRecord(args.metadata),+ metadata: toRecordOrEmpty(args.metadata),},),),diff --git a/src/server/services/agentSignal/services/selfIteration/feedback/handler.ts b/src/server/services/agentSignal/services/selfIteration/feedback/handler.tsindex d1e27ccfc6d..16cdacbb637 100644--- a/src/server/services/agentSignal/services/selfIteration/feedback/handler.ts+++ b/src/server/services/agentSignal/services/selfIteration/feedback/handler.ts@@ -1,6 +1,7 @@import type { SourceAgentSelfFeedbackIntentDeclared } from '@lobechat/agent-signal/source';import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import type { ModelRuntime } from '@lobechat/model-runtime';+import { isNonEmptyString } from '@lobechat/utils';import { defineSourceHandler } from '../../../runtime/middleware';import type { AgentSignalReceipt } from '../../receiptService';@@ -233,9 +234,6 @@ export interface CreateSelfFeedbackIntentSourceHandlerDependencies {writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;}-const isNonEmptyString = (value: unknown): value is string =>- typeof value === 'string' && value.length > 0;-const isValidConfidence = (value: unknown): value is number =>typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;diff --git a/src/server/services/agentSignal/services/selfIteration/projection.ts b/src/server/services/agentSignal/services/selfIteration/projection.tsindex 266c0f9d36c..8bf507b191f 100644--- a/src/server/services/agentSignal/services/selfIteration/projection.ts+++ b/src/server/services/agentSignal/services/selfIteration/projection.ts@@ -1,4 +1,5 @@import type { ChatToolPayload } from '@lobechat/types';+import { pickTrimmedString, toRecord } from '@lobechat/utils';import type {SelfReviewIdea,@@ -199,40 +200,38 @@ const parseToolArguments = (value: string | undefined): Record<string, unknown>try {const parsed = JSON.parse(value) as unknown;- return parsed && typeof parsed === 'object' && !Array.isArray(parsed)- ? (parsed as Record<string, unknown>)- : {};+ return toRecordOrEmpty(parsed);} catch {return {};}};-const getString = (value: unknown) =>- typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;-const getBoolean = (value: unknown) => (typeof value === 'boolean' ? value : undefined);const getStringArray = (value: unknown) =>- Array.isArray(value) ? value.flatMap((item) => (getString(item) ? [getString(item)!] : [])) : [];+ Array.isArray(value)+ ? value.flatMap((item) => {+ const text = pickTrimmedString(item);+ return text ? [text] : [];+ })+ : [];-const getRecord = (value: unknown): Record<string, unknown> =>- value && typeof value === 'object' && !Array.isArray(value)- ? (value as Record<string, unknown>)- : {};+const toRecordOrEmpty = (value: unknown): Record<string, unknown> =>+ (toRecord(value) as Record<string, unknown> | undefined) ?? {};const getBaseSnapshot = (value: unknown): SelfReviewProposalBaseSnapshot | undefined => {- const record = getRecord(value);+ const record = toRecordOrEmpty(value);if (Object.keys(record).length === 0) return;return {absent: getBoolean(record.absent),- agentDocumentId: getString(record.agentDocumentId),- contentHash: getString(record.contentHash),- documentId: getString(record.documentId),- documentUpdatedAt: getString(record.documentUpdatedAt),+ agentDocumentId: pickTrimmedString(record.agentDocumentId),+ contentHash: pickTrimmedString(record.contentHash),+ documentId: pickTrimmedString(record.documentId),+ documentUpdatedAt: pickTrimmedString(record.documentUpdatedAt),managed: getBoolean(record.managed),- skillName: getString(record.skillName),- targetTitle: getString(record.targetTitle),+ skillName: pickTrimmedString(record.skillName),+ targetTitle: pickTrimmedString(record.targetTitle),targetType: record.targetType === 'skill' ? 'skill' : undefined,writable: getBoolean(record.writable),};@@ -309,7 +308,7 @@ const getIdempotencyKey = ({toolCall?: ChatToolPayload;toolName: string;}) =>- getString(args.idempotencyKey) ??+ pickTrimmedString(args.idempotencyKey) ??outcomeFallbackIdempotencyKey({sourceId,toolCallId: toolCall?.id,@@ -329,17 +328,17 @@ const outcomeFallbackIdempotencyKey = ({const getSkillCreateOperation = (args: Record<string, unknown>, userId: string) => ({domain: 'skill' as const,input: {- bodyMarkdown: getString(args.bodyMarkdown),- description: getString(args.description),- name: getString(args.name),- title: getString(args.title),+ bodyMarkdown: pickTrimmedString(args.bodyMarkdown),+ description: pickTrimmedString(args.description),+ name: pickTrimmedString(args.name),+ title: pickTrimmedString(args.title),userId,},operation: 'create' as const,});const getMemoryWriteOperation = (args: Record<string, unknown>, userId: string) => {- const content = getString(args.content);+ const content = pickTrimmedString(args.content);if (!content) return;return {@@ -350,14 +349,14 @@ const getMemoryWriteOperation = (args: Record<string, unknown>, userId: string)};const getSkillRefineOperation = (args: Record<string, unknown>, userId: string) => {- const skillDocumentId = getString(args.skillDocumentId);+ const skillDocumentId = pickTrimmedString(args.skillDocumentId);if (!skillDocumentId) return;return {domain: 'skill' as const,input: {- bodyMarkdown: getString(args.bodyMarkdown),- description: getString(args.description),+ bodyMarkdown: pickTrimmedString(args.bodyMarkdown),+ description: pickTrimmedString(args.description),skillDocumentId,userId,},@@ -368,19 +367,19 @@ const getSkillRefineOperation = (args: Record<string, unknown>, userId: string)const toEvidenceRefs = (value: unknown): ActionPlan['evidenceRefs'] =>Array.isArray(value)? value.flatMap((item) => {- const record = getRecord(item);- const id = getString(record.id);- const type = getString(record.type);+ const record = toRecordOrEmpty(item);+ const id = pickTrimmedString(record.id);+ const type = pickTrimmedString(record.type);return id && type ? [{ id, type: type as ActionPlan['evidenceRefs'][number]['type'] }] : [];}): [];const toTarget = (value: unknown): ActionTarget | undefined => {- const record = getRecord(value);- const memoryId = getString(record.memoryId);- const skillDocumentId = getString(record.skillDocumentId);- const skillName = getString(record.skillName);+ const record = toRecordOrEmpty(value);+ const memoryId = pickTrimmedString(record.memoryId);+ const skillDocumentId = pickTrimmedString(record.skillDocumentId);+ const skillName = pickTrimmedString(record.skillName);const targetReadonly = getBoolean(record.targetReadonly);if (!memoryId && !skillDocumentId && !skillName && targetReadonly === undefined) return;@@ -412,43 +411,43 @@ const toConfidence = (value: unknown) =>typeof value === 'number' && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 1;const toSkillOperation = (value: unknown, userId: string): ActionPlan['operation'] => {- const record = getRecord(value);+ const record = toRecordOrEmpty(value);if (record.domain !== 'skill') return;- const input = getRecord(record.input);+ const input = toRecordOrEmpty(record.input);if (record.operation === 'create') {return {domain: 'skill',input: {- bodyMarkdown: getString(input.bodyMarkdown),- description: getString(input.description),- name: getString(input.name),- title: getString(input.title),- userId: getString(input.userId) ?? userId,+ bodyMarkdown: pickTrimmedString(input.bodyMarkdown),+ description: pickTrimmedString(input.description),+ name: pickTrimmedString(input.name),+ title: pickTrimmedString(input.title),+ userId: pickTrimmedString(input.userId) ?? userId,},operation: 'create',};}if (record.operation === 'refine') {- const skillDocumentId = getString(input.skillDocumentId);+ const skillDocumentId = pickTrimmedString(input.skillDocumentId);if (!skillDocumentId) return;return {domain: 'skill',input: {- bodyMarkdown: getString(input.bodyMarkdown),- patch: getString(input.patch),+ bodyMarkdown: pickTrimmedString(input.bodyMarkdown),+ patch: pickTrimmedString(input.patch),skillDocumentId,- userId: getString(input.userId) ?? userId,+ userId: pickTrimmedString(input.userId) ?? userId,},operation: 'refine',};}if (record.operation === 'consolidate') {- const canonicalSkillDocumentId = getString(input.canonicalSkillDocumentId);+ const canonicalSkillDocumentId = pickTrimmedString(input.canonicalSkillDocumentId);const sourceSkillIds = getStringArray(input.sourceSkillIds);if (!canonicalSkillDocumentId || sourceSkillIds.length === 0) return;@@ -456,12 +455,12 @@ const toSkillOperation = (value: unknown, userId: string): ActionPlan['operationdomain: 'skill',input: {approval: { source: 'proposal' },- bodyMarkdown: getString(input.bodyMarkdown),+ bodyMarkdown: pickTrimmedString(input.bodyMarkdown),canonicalSkillDocumentId,- description: getString(input.description),+ description: pickTrimmedString(input.description),sourceSkillIds,sourceSnapshots: getBaseSnapshots(input.sourceSnapshots),- userId: getString(input.userId) ?? userId,+ userId: pickTrimmedString(input.userId) ?? userId,},operation: 'consolidate',};@@ -524,10 +523,10 @@ const getProjectionActionFromRaw = ({rawAction: unknown;userId: string;}): SelfReviewProposalPlan['actions'][number] | undefined => {- const record = getRecord(rawAction);+ const record = toRecordOrEmpty(rawAction);const actionType = getRawActionType(record.actionType);const idempotencyKey =- getString(record.idempotencyKey) ?? `${fallbackIdempotencyKey}:action:${index + 1}`;+ pickTrimmedString(record.idempotencyKey) ?? `${fallbackIdempotencyKey}:action:${index + 1}`;if (!actionType || actionType === 'proposal_only') return;@@ -543,7 +542,7 @@ const getProjectionActionFromRaw = ({applyMode: toApplyMode(record.applyMode, outcome),confidence: toConfidence(record.confidence),dedupeKey:- getString(record.dedupeKey) ??+ pickTrimmedString(record.dedupeKey) ??(target?.skillDocumentId? `skill:${target.skillDocumentId}`: target?.skillName@@ -553,7 +552,8 @@ const getProjectionActionFromRaw = ({: actionType),evidenceRefs: toEvidenceRefs(record.evidenceRefs),idempotencyKey,- rationale: getString(record.rationale) ?? outcome.summary ?? 'Self-review proposal action.',+ rationale:+ pickTrimmedString(record.rationale) ?? outcome.summary ?? 'Self-review proposal action.',risk: toRisk(record.risk),...(operation ? { operation } : {}),...(target ? { target } : {}),@@ -604,7 +604,7 @@ const getIdeaFromRaw = ({index: number;rawAction: unknown;}): SelfReviewIdea | undefined => {- const record = getRecord(rawAction);+ const record = toRecordOrEmpty(rawAction);if (getRawActionType(record.actionType) !== 'proposal_only') return;const target = toTarget(record.target);@@ -612,11 +612,11 @@ const getIdeaFromRaw = ({return {evidenceRefs: toEvidenceRefs(record.evidenceRefs),idempotencyKey:- getString(record.idempotencyKey) ?? `${fallbackIdempotencyKey}:idea:${index + 1}`,- rationale: getString(record.rationale) ?? 'SelfIteration self-review idea.',+ pickTrimmedString(record.idempotencyKey) ?? `${fallbackIdempotencyKey}:idea:${index + 1}`,+ rationale: pickTrimmedString(record.rationale) ?? 'SelfIteration self-review idea.',risk: toRisk(record.risk),...(target ? { target } : {}),- ...(getString(record.title) ? { title: getString(record.title) } : {}),+ ...(pickTrimmedString(record.title) ? { title: pickTrimmedString(record.title) } : {}),};};@@ -676,13 +676,13 @@ const getProjectionAction = ({userId: string;}): SelfReviewProposalPlan['actions'][number] => {const actionType = getActionType(toolName);- const skillDocumentId = getString(args.skillDocumentId) ?? outcome.resourceId;- const skillName = getString(args.name);+ const skillDocumentId = pickTrimmedString(args.skillDocumentId) ?? outcome.resourceId;+ const skillName = pickTrimmedString(args.name);const baseSnapshot = getBaseSnapshot(args.baseSnapshot);const baseAction = {applyMode: outcome.status === 'proposed' ? ApplyMode.ProposalOnly : ApplyMode.AutoApply,confidence: 1,- dedupeKey: getString(args.proposalKey) ?? outcome.resourceId ?? idempotencyKey,+ dedupeKey: pickTrimmedString(args.proposalKey) ?? outcome.resourceId ?? idempotencyKey,evidenceRefs: [],idempotencyKey,rationale: outcome.summary ?? 'Self-review tool write outcome.',diff --git a/src/server/services/agentSignal/services/selfIteration/reflection/handler.ts b/src/server/services/agentSignal/services/selfIteration/reflection/handler.tsindex 9e85da5606c..4803db6bd6d 100644--- a/src/server/services/agentSignal/services/selfIteration/reflection/handler.ts+++ b/src/server/services/agentSignal/services/selfIteration/reflection/handler.ts@@ -1,6 +1,7 @@import type { SourceAgentSelfReflectionRequested } from '@lobechat/agent-signal/source';import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import type { ModelRuntime } from '@lobechat/model-runtime';+import { isNonEmptyString } from '@lobechat/utils';import { defineSourceHandler } from '../../../runtime/middleware';import type { AgentSignalReceipt } from '../../receiptService';@@ -212,9 +213,6 @@ export interface CreateSelfReflectionSourceHandlerDependencies {writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;}-const isNonEmptyString = (value: unknown): value is string =>- typeof value === 'string' && value.length > 0;-const isSelfReflectionScopeType = (value: unknown): value is SelfReflectionSourceScopeType =>value === 'topic' || value === 'task' || value === 'operation';diff --git a/src/server/services/agentSignal/services/selfIteration/review/collect.ts b/src/server/services/agentSignal/services/selfIteration/review/collect.tsindex a0346a76d1e..9c6c2746701 100644--- a/src/server/services/agentSignal/services/selfIteration/review/collect.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/collect.ts@@ -1,5 +1,6 @@import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';+import { pickString, toRecord } from '@lobechat/utils';import type { AgentSignalDocumentActivityRow } from '@/database/models/agentSignal/reviewContext';@@ -791,13 +792,6 @@ const createEmptyProposalActivity = (): ProposalActivityDigest => ({supersededCount: 0,});-const toRecord = (value: unknown): Record<string, unknown> | undefined =>- value && typeof value === 'object' && !Array.isArray(value)- ? (value as Record<string, unknown>)- : undefined;--const toString = (value: unknown) => (typeof value === 'string' ? value : undefined);-const toStringArray = (value: unknown) =>Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];@@ -806,8 +800,8 @@ const toEvidenceRefs = (value: unknown, fallbackReceiptId: string): EvidenceRef[const refs = value.flatMap((item): EvidenceRef[] => {const record = toRecord(item);- const id = toString(record?.id);- const type = toString(record?.type);+ const id = pickString(record?.id);+ const type = pickString(record?.type);if (!id) return [];@@ -836,10 +830,10 @@ const toIntentTarget = (value: unknown): SelfFeedbackIntent['target'] | undefineif (!record) return;return {- memoryId: toString(record.memoryId),+ memoryId: pickString(record.memoryId),readonly: typeof record.readonly === 'boolean' ? record.readonly : undefined,- skillDocumentId: toString(record.skillDocumentId),- skillName: toString(record.skillName),+ skillDocumentId: pickString(record.skillDocumentId),+ skillName: pickString(record.skillName),taskIds: toStringArray(record.taskIds),topicIds: toStringArray(record.topicIds),};@@ -862,11 +856,11 @@ const toReflectionIntent = (if (!record || record.mode !== 'reflection') return;const intentType = isIntentType(record.intentType) ? record.intentType : undefined;- const rationale = toString(record.rationale);+ const rationale = pickString(record.rationale);if (!intentType || !rationale) return;return normalizeReflectionIntent({- actionType: toString(record.actionType),+ actionType: pickString(record.actionType),confidence: typeof record.confidence === 'number' ? record.confidence : undefined,downgradeReason:record.downgradeReason === 'approval_required' ||@@ -875,14 +869,14 @@ const toReflectionIntent = (? record.downgradeReason: undefined,evidenceRefs: toEvidenceRefs(record.evidenceRefs, receipt.id),- idempotencyKey: toString(record.idempotencyKey) ?? receipt.id,+ idempotencyKey: pickString(record.idempotencyKey) ?? receipt.id,intentType,mode: 'reflection',operation: toRecord(record.operation) as SelfFeedbackIntent['operation'],rationale,risk: isRisk(record.risk) ? record.risk : 'medium',target: toIntentTarget(record.target),- title: toString(record.title),+ title: pickString(record.title),urgency: isUrgency(record.urgency) ? record.urgency : 'later',});};diff --git a/src/server/services/agentSignal/services/selfIteration/review/handler.ts b/src/server/services/agentSignal/services/selfIteration/review/handler.tsindex 99cf774c14d..28a8a57d499 100644--- a/src/server/services/agentSignal/services/selfIteration/review/handler.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/handler.ts@@ -2,6 +2,7 @@ import type { SourceAgentNightlyReviewRequested } from '@lobechat/agent-signal/simport { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';+import { isNonEmptyString } from '@lobechat/utils';import { defineSourceHandler } from '../../../runtime/middleware';import type { AgentSignalReceipt } from '../../receiptService';@@ -104,9 +105,6 @@ export interface CreateNightlyReviewSourceHandlerDependencies {writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;}-const isNonEmptyString = (value: unknown): value is string =>- typeof value === 'string' && value.length > 0;-interface NightlyReviewSpanLike {setAttribute: (key: string, value: string | number | boolean) => void;}diff --git a/src/server/services/agentSignal/services/selfIteration/review/proposal.ts b/src/server/services/agentSignal/services/selfIteration/review/proposal.tsindex b2e3e79593e..14d6474b1d4 100644--- a/src/server/services/agentSignal/services/selfIteration/review/proposal.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/proposal.ts@@ -1,4 +1,5 @@import type { BriefAction } from '@lobechat/types';+import { isTrimmedNonEmptyString } from '@lobechat/utils';import { z } from 'zod';import type {@@ -313,8 +314,6 @@ const getMergeableProposalSnapshotError = (action: SelfReviewProposalActionPlan)const isMergeableProposalAction = (actionType: string) =>actionType === 'create_skill' || actionType === 'refine_skill';-const hasRequiredString = (value: unknown) => typeof value === 'string' && value.trim().length > 0;-const hasCompleteMergeableSnapshot = (actionType: string,snapshot: SelfReviewProposalBaseSnapshot | undefined,@@ -323,16 +322,16 @@ const hasCompleteMergeableSnapshot = (if (actionType === 'refine_skill') {return (- hasRequiredString(snapshot.agentDocumentId) &&- hasRequiredString(snapshot.documentId) &&- hasRequiredString(snapshot.contentHash) &&+ isTrimmedNonEmptyString(snapshot.agentDocumentId) &&+ isTrimmedNonEmptyString(snapshot.documentId) &&+ isTrimmedNonEmptyString(snapshot.contentHash) &&snapshot.managed === true &&snapshot.writable === true);}if (actionType === 'create_skill') {- return snapshot.absent === true && hasRequiredString(snapshot.skillName);+ return snapshot.absent === true && isTrimmedNonEmptyString(snapshot.skillName);}return false;diff --git a/src/server/services/agentSignal/services/selfIteration/review/proposalApply.ts b/src/server/services/agentSignal/services/selfIteration/review/proposalApply.tsindex 2f9358d6640..a59ff391951 100644--- a/src/server/services/agentSignal/services/selfIteration/review/proposalApply.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/proposalApply.ts@@ -1,5 +1,6 @@import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';+import { pickString, pickTrimmedString } from '@lobechat/utils';import type { ToolSet, ToolWriteResult } from '../tools/shared';import type { RunResult } from '../types';@@ -66,14 +67,6 @@ const toApplyResult = (summary,});-const getOptionalString = (value: unknown) => (typeof value === 'string' ? value : undefined);--const getRequiredString = (value: unknown) => {- const text = getOptionalString(value)?.trim();-- return text || undefined;-};-const mapToolStatus = (result: ToolWriteResult): SelfReviewProposalActionApplyResult['status'] => {if (result.status === 'applied') return 'applied';if (result.status === 'deduped') return 'deduped';@@ -165,9 +158,9 @@ const prepareToolAction = (}const operationInput = action.operation.input as unknown as Record<string, unknown>;- const bodyMarkdown = getRequiredString(operationInput.bodyMarkdown);- const canonicalSkillDocumentId = getRequiredString(operationInput.canonicalSkillDocumentId);- const description = getOptionalString(operationInput.description);+ const bodyMarkdown = pickTrimmedString(operationInput.bodyMarkdown);+ const canonicalSkillDocumentId = pickTrimmedString(operationInput.canonicalSkillDocumentId);+ const description = pickString(operationInput.description);if (!bodyMarkdown || !canonicalSkillDocumentId) {return toApplyResult(@@ -208,9 +201,9 @@ const prepareToolAction = (const operation = action.operation;const operationInput = operation.input as unknown as Record<string, unknown>;- const bodyMarkdown = getRequiredString(operation.input.bodyMarkdown);- const description = getOptionalString(operationInput.description);- const skillDocumentId = getRequiredString(operation.input.skillDocumentId);+ const bodyMarkdown = pickTrimmedString(operation.input.bodyMarkdown);+ const description = pickString(operationInput.description);+ const skillDocumentId = pickTrimmedString(operation.input.skillDocumentId);if (!bodyMarkdown || !skillDocumentId) {return toApplyResult(@@ -246,10 +239,10 @@ const prepareToolAction = (}const operation = action.operation;- const bodyMarkdown = getRequiredString(operation.input.bodyMarkdown);- const description = getOptionalString(operation.input.description);- const name = getRequiredString(operation.input.name);- const title = getOptionalString(operation.input.title);+ const bodyMarkdown = pickTrimmedString(operation.input.bodyMarkdown);+ const description = pickString(operation.input.description);+ const name = pickTrimmedString(operation.input.name);+ const title = pickString(operation.input.title);if (!bodyMarkdown || !name) {return toApplyResult(diff --git a/src/server/services/agentSignal/services/selfIteration/review/proposalPreflight.ts b/src/server/services/agentSignal/services/selfIteration/review/proposalPreflight.tsindex eb00ee1c4d5..a69143c6154 100644--- a/src/server/services/agentSignal/services/selfIteration/review/proposalPreflight.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/proposalPreflight.ts@@ -1,3 +1,5 @@+import { isRecord, isTrimmedNonEmptyString, pickTrimmedString } from '@lobechat/utils';+import type {SelfReviewProposalAction,SelfReviewProposalBaseSnapshot,@@ -77,45 +79,36 @@ export const createSelfReviewProposalPreflightService = (},});-const hasRequiredString = (value: unknown): value is string =>- typeof value === 'string' && value.trim().length > 0;-const getOperationInputString = (action: SelfReviewProposalAction, key: string) => {const input = action.operation?.input;- if (!input || typeof input !== 'object' || !(key in input)) return;-- const record = input as unknown as Record<string, unknown>;- const value = record[key];+ if (!isRecord(input) || !(key in input)) return;- return hasRequiredString(value) ? value.trim() : undefined;+ return pickTrimmedString(input[key]);};const getOperationInputStringArray = (action: SelfReviewProposalAction, key: string) => {const input = action.operation?.input;- if (!input || typeof input !== 'object' || !(key in input)) return [];+ if (!isRecord(input) || !(key in input)) return [];- const record = input as unknown as Record<string, unknown>;- const value = record[key];+ const value = input[key];return Array.isArray(value)- ? value.flatMap((item) => (hasRequiredString(item) ? [item.trim()] : []))+ ? value.flatMap((item) => {+ const text = pickTrimmedString(item);+ return text ? [text] : [];+ }): [];};const getOperationInputSnapshots = (action: SelfReviewProposalAction, key: string) => {const input = action.operation?.input;- if (!input || typeof input !== 'object' || !(key in input)) return [];+ if (!isRecord(input) || !(key in input)) return [];- const record = input as unknown as Record<string, unknown>;- const value = record[key];+ const value = input[key];return Array.isArray(value)- ? value.flatMap((item) =>- item && typeof item === 'object' && !Array.isArray(item)- ? [item as SelfReviewProposalBaseSnapshot]- : [],- )+ ? value.flatMap((item) => (isRecord(item) ? [item as SelfReviewProposalBaseSnapshot] : [])): [];};@@ -127,9 +120,9 @@ const isCompleteRefineSnapshot = (documentId: string;} =>snapshot.targetType === 'skill' &&- hasRequiredString(snapshot.agentDocumentId) &&- hasRequiredString(snapshot.contentHash) &&- hasRequiredString(snapshot.documentId) &&+ isTrimmedNonEmptyString(snapshot.agentDocumentId) &&+ isTrimmedNonEmptyString(snapshot.contentHash) &&+ isTrimmedNonEmptyString(snapshot.documentId) &&snapshot.managed === true &&snapshot.writable === true;@@ -185,7 +178,7 @@ const checkCreateSkillAction = async (if (baseSnapshot.targetType !== 'skill' ||baseSnapshot.absent !== true ||- !hasRequiredString(baseSnapshot.skillName)+ !isTrimmedNonEmptyString(baseSnapshot.skillName)) {return { allowed: false, reason: 'snapshot_incomplete' };}diff --git a/src/server/services/agentSignal/services/selfIteration/review/server.ts b/src/server/services/agentSignal/services/selfIteration/review/server.tsindex 7bcc6ae86bb..76ed8d0c0e1 100644--- a/src/server/services/agentSignal/services/selfIteration/review/server.ts+++ b/src/server/services/agentSignal/services/selfIteration/review/server.ts@@ -1,6 +1,7 @@import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';+import { pickTrimmedString, toRecord } from '@lobechat/utils';import { AgentSignalNightlyReviewModel } from '@/database/models/agentSignal/nightlyReview';import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';@@ -251,24 +252,24 @@ const createRefineProposalAction = (target: { skillDocumentId: input.skillDocumentId },});-const getRecord = (value: unknown): Record<string, unknown> =>- value && typeof value === 'object' && !Array.isArray(value)- ? (value as Record<string, unknown>)- : {};--const getString = (value: unknown) =>- typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;+const toRecordOrEmpty = (value: unknown): Record<string, unknown> =>+ (toRecord(value) as Record<string, unknown> | undefined) ?? {};const getStringArray = (value: unknown) =>- Array.isArray(value) ? value.flatMap((item) => (getString(item) ? [getString(item)!] : [])) : [];+ Array.isArray(value)+ ? value.flatMap((item) => {+ const text = pickTrimmedString(item);+ return text ? [text] : [];+ })+ : [];const getBriefMetadataWithProposal = (brief: BriefItem,proposal: SelfReviewProposalMetadata,): BriefItem['metadata'] => {- const metadata = getRecord(brief.metadata);- const agentSignal = getRecord(metadata.agentSignal);- const nightlySelfReview = getRecord(agentSignal.nightlySelfReview);+ const metadata = toRecordOrEmpty(brief.metadata);+ const agentSignal = toRecordOrEmpty(metadata.agentSignal);+ const nightlySelfReview = toRecordOrEmpty(agentSignal.nightlySelfReview);return {...metadata,@@ -309,15 +310,17 @@ const collectPlanEvidenceRefs = (plan: ReturnType<typeof projectRun>['projection};const getProposalActionSnapshotInput = (action: Record<string, unknown>) => {- const operation = getRecord(action.operation);- const operationInput = getRecord(operation.input);- const target = getRecord(action.target);+ const operation = toRecordOrEmpty(action.operation);+ const operationInput = toRecordOrEmpty(operation.input);+ const target = toRecordOrEmpty(action.target);return {...operationInput,- name: getString(operationInput.name) ?? getString(target.skillName),- skillDocumentId: getString(operationInput.skillDocumentId) ?? getString(target.skillDocumentId),- title: getString(operationInput.title) ?? getString(target.skillName),+ name: pickTrimmedString(operationInput.name) ?? pickTrimmedString(target.skillName),+ skillDocumentId:+ pickTrimmedString(operationInput.skillDocumentId) ??+ pickTrimmedString(target.skillDocumentId),+ title: pickTrimmedString(operationInput.title) ?? pickTrimmedString(target.skillName),};};@@ -338,13 +341,13 @@ const withCompleteProposalSnapshots = async ({const actions = await Promise.all(input.actions.map(async (rawAction) => {- const action = getRecord(rawAction);+ const action = toRecordOrEmpty(rawAction);const actionType = action.actionType;if (actionType === 'consolidate_skill') {- const operation = getRecord(action.operation);- const operationInput = getRecord(operation.input);- const canonicalSkillDocumentId = getString(operationInput.canonicalSkillDocumentId);+ const operation = toRecordOrEmpty(action.operation);+ const operationInput = toRecordOrEmpty(operation.input);+ const canonicalSkillDocumentId = pickTrimmedString(operationInput.canonicalSkillDocumentId);const sourceSkillIds = getStringArray(operationInput.sourceSkillIds);const sourceSnapshots = await Promise.all(sourceSkillIds.map((skillDocumentId) =>diff --git a/src/server/services/document/diff/json.ts b/src/server/services/document/diff/json.tsindex e91d06385e3..68360a91331 100644--- a/src/server/services/document/diff/json.ts+++ b/src/server/services/document/diff/json.ts@@ -1,8 +1,6 @@+import { isRecord } from '@lobechat/utils';import { create, type Delta, patch as patchDelta } from 'jsondiffpatch';-const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null && !Array.isArray(value);-const createHashComparable = (value: unknown): unknown => {if (Array.isArray(value)) {return value.map(createHashComparable);diff --git a/src/server/services/onboarding/index.ts b/src/server/services/onboarding/index.tsindex 386a1fb22b2..5b0e830339f 100644--- a/src/server/services/onboarding/index.ts+++ b/src/server/services/onboarding/index.ts@@ -19,7 +19,7 @@ import {RECOMMENDED_DISCOVERY_USER_MESSAGES,SAVE_USER_QUESTION_FIELDS,} from '@lobechat/types';-import { merge } from '@lobechat/utils';+import { isRecord, merge, pickTrimmedString } from '@lobechat/utils';import { and, count, eq, sql } from 'drizzle-orm';import { AgentModel } from '@/database/models/agent';@@ -63,24 +63,9 @@ const formatNaturalList = (items: string[]) => {const isStructuredField = (value: string): value is SaveUserQuestionField =>SAVE_USER_QUESTION_FIELDS.includes(value as SaveUserQuestionField);-const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null && !Array.isArray(value);+const normalizeTitle = (value: unknown) => pickTrimmedString(value);-const normalizeTitle = (value: unknown) => {- if (typeof value !== 'string') return undefined;-- const trimmed = value.trim();-- return trimmed.length > 0 ? trimmed : undefined;-};--const normalizeUserInfoField = (value: unknown) => {- if (typeof value !== 'string') return undefined;-- const trimmed = value.trim();-- return trimmed || undefined;-};+const normalizeUserInfoField = (value: unknown) => pickTrimmedString(value);const normalizeStringArray = (value: unknown) =>Array.isArray(value)diff --git a/src/server/services/onboarding/nodeHandlers.ts b/src/server/services/onboarding/nodeHandlers.tsindex 13f5f2b1ccb..620baa10197 100644--- a/src/server/services/onboarding/nodeHandlers.ts+++ b/src/server/services/onboarding/nodeHandlers.ts@@ -3,8 +3,9 @@ import type {UserAgentOnboardingDraft,UserAgentOnboardingNode,} from '@lobechat/types';+import { isRecord } from '@lobechat/utils';-import { getScopedPatch, isRecord, normalizeFromSchema } from './nodeSchema';+import { getScopedPatch, normalizeFromSchema } from './nodeSchema';type OnboardingPatchInput = Record<string, unknown>;type DraftKey = keyof UserAgentOnboardingDraft;diff --git a/src/server/services/onboarding/nodeSchema.ts b/src/server/services/onboarding/nodeSchema.tsindex 9fdecdba005..ec203d24ad6 100644--- a/src/server/services/onboarding/nodeSchema.ts+++ b/src/server/services/onboarding/nodeSchema.ts@@ -1,4 +1,5 @@import type { UserAgentOnboardingDraft, UserAgentOnboardingNode } from '@lobechat/types';+import { isRecord, pickTrimmedString } from '@lobechat/utils';type FieldType = 'string' | 'string[]';@@ -68,10 +69,7 @@ export const NODE_SCHEMAS: Partial<Record<UserAgentOnboardingNode, NodeSchema>>},};-export const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null && !Array.isArray(value);--export const sanitizeText = (value?: string) => value?.trim() || undefined;+export const sanitizeText = (value?: string) => pickTrimmedString(value);const sanitizeTextList = (items?: unknown[], max = 8) =>(items ?? [])diff --git a/src/server/workflows-hono/agent-signal/handlers/scheduleNightlyReview.ts b/src/server/workflows-hono/agent-signal/handlers/scheduleNightlyReview.tsindex 026ba453044..296c3e66fd8 100644--- a/src/server/workflows-hono/agent-signal/handlers/scheduleNightlyReview.ts+++ b/src/server/workflows-hono/agent-signal/handlers/scheduleNightlyReview.ts@@ -1,5 +1,6 @@import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';+import { isRecord } from '@lobechat/utils';import type { Context } from 'hono';import { getServerDB } from '@/database/server';@@ -37,10 +38,6 @@ export interface ScheduleNightlyReviewPayload {whitelist?: string[];}-const isRecord = (value: unknown): value is Record<PropertyKey, unknown> => {- return typeof value === 'object' && value !== null;-};-const readPositiveInteger = (value: unknown, fallback: number) => {return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : fallback;};diff --git a/src/utils/skillMarkdown.ts b/src/utils/skillMarkdown.tsindex 309d3fff10c..79057c2726c 100644--- a/src/utils/skillMarkdown.ts+++ b/src/utils/skillMarkdown.ts@@ -1,3 +1,4 @@+import { isRecord, pickString } from '@lobechat/utils';import { parse } from 'yaml';const SKILL_INDEX_FILENAME = 'SKILL.md';@@ -96,9 +97,6 @@ const stringifyMetadataValue = (value: unknown): string => {return JSON.stringify(value);};-const isRecord = (value: unknown): value is Record<string, unknown> =>- !!value && typeof value === 'object' && !Array.isArray(value);-const isValidSkillName = (name: string): boolean =>!!name &&name.length <= MAX_SKILL_NAME_LENGTH &&@@ -113,7 +111,7 @@ const readFrontmatterStringField = (field: keyof SkillMarkdownFrontmatterFields,): string | undefined => {const value = data[field];- return typeof value === 'string' ? value.trim() : undefined;+ return pickString(value)?.trim();};export const parseSkillMarkdownFrontmatterFields = (