π€― 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(runtime): vendor shared helpers into model-runtime / agent-runtime / context-engine (#21412)
Arvin Xucbe6ddd3e93b
diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.jsonindex 3d3bc0ba130..5e6fc973876 100644--- a/packages/agent-runtime/package.json+++ b/packages/agent-runtime/package.json@@ -9,13 +9,16 @@"test:coverage": "vitest --coverage --silent='passed-only'"},"dependencies": {- "@lobechat/utils": "workspace:*",+ "@lobechat/context-engine": "workspace:*",+ "@lobechat/types": "workspace:*","ajv": "^8.20.0",- "p-map": "^7.0.5"+ "es-toolkit": "^1.50.0",+ "p-map": "^7.0.5",+ "partial-json": "^0.1.7"},"devDependencies": {- "@lobechat/context-engine": "workspace:*",- "@lobechat/types": "workspace:*","openai": "^6.45.0"- }+ },+ "license": "MIT",+ "homepage": "https://github.com/lobehub/lobehub/tree/canary/packages/agent-runtime"}diff --git a/packages/agent-runtime/src/agents/graph/GraphAgent.ts b/packages/agent-runtime/src/agents/graph/GraphAgent.tsindex 9f99e42f1db..34dabbb1aa7 100644--- a/packages/agent-runtime/src/agents/graph/GraphAgent.ts+++ b/packages/agent-runtime/src/agents/graph/GraphAgent.ts@@ -1,9 +1,9 @@import { ToolNameResolver } from '@lobechat/context-engine';import type { AgentGraph, AgentGraphEdge, AgentGraphNode } from '@lobechat/types';import { AGENT_GRAPH_ROOT_NODE_ID } from '@lobechat/types/agent/graph';-import { toJsonSafe } from '@lobechat/utils/json';-import type { UnknownRecord } from '@lobechat/utils/object';-import { isRecord } from '@lobechat/utils/object';+import { toJsonSafe } from '../../utils/json';+import type { UnknownRecord } from '../../utils/object';+import { isRecord } from '../../utils/object';import Ajv from 'ajv';import type {diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.tsindex 51473a31e31..9d0633f09a4 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts@@ -6,8 +6,8 @@ import type {ModelReasoning,ModelUsage,} from '@lobechat/types';-import { serializePartsForStorage } from '@lobechat/utils/multimodalContent';-import { sanitizeToolCallArguments } from '@lobechat/utils/sanitizeToolCallArguments';+import { serializePartsForStorage } from '../utils/multimodalContent';+import { sanitizeToolCallArguments } from '../utils/sanitizeToolCallArguments';import { UsageCounter } from '../core/UsageCounter';import type { AgentRuntimeHost, LLMAttemptOutput } from '../transport';diff --git a/packages/agent-runtime/src/utils/json.ts b/packages/agent-runtime/src/utils/json.tsnew file mode 100644index 00000000000..38a2bda79cf--- /dev/null+++ b/packages/agent-runtime/src/utils/json.ts@@ -0,0 +1,36 @@+export type JsonSafeValue =+ boolean | null | number | string | readonly JsonSafeValue[] | JsonSafeObject;++export interface JsonSafeObject {+ readonly [key: string]: JsonSafeValue;+}++export const safeJsonStringify = (value: unknown): string => {+ const seen = new WeakSet<object>();++ try {+ return (+ JSON.stringify(value, (_key, item) => {+ if (typeof item === 'bigint') return item.toString();+ if (typeof item === 'object' && item !== null) {+ if (seen.has(item as object)) return '[Circular]';+ seen.add(item as object);+ }+ return item;+ }) ?? 'null'+ );+ } catch {+ return JSON.stringify({+ message: 'Failed to serialize JSON value',+ name: 'JsonSerializationFailure',+ });+ }+};++export const toJsonSafe = (value: unknown): JsonSafeValue => {+ try {+ return JSON.parse(safeJsonStringify(value)) as JsonSafeValue;+ } catch {+ return String(value);+ }+};diff --git a/packages/agent-runtime/src/utils/messageSelectors.ts b/packages/agent-runtime/src/utils/messageSelectors.tsindex 5dc74c2c47f..6977804d035 100644--- a/packages/agent-runtime/src/utils/messageSelectors.ts+++ b/packages/agent-runtime/src/utils/messageSelectors.ts@@ -1,5 +1,5 @@import type { StepActivatedSkill, StepContextTodos, UIChatMessage } from '@lobechat/types';-import { isNonEmptyString, isPlainRecord } from '@lobechat/utils/object';+import { isNonEmptyString, isPlainRecord } from './object';/*** Wire-format tool identifiers that carry skill activations in theirdiff --git a/packages/agent-runtime/src/utils/multimodalContent.ts b/packages/agent-runtime/src/utils/multimodalContent.tsnew file mode 100644index 00000000000..5444defde72--- /dev/null+++ b/packages/agent-runtime/src/utils/multimodalContent.ts@@ -0,0 +1,25 @@+import type { MessageContentPart } from '@lobechat/types';++/**+ * Serialize message content parts to JSON string for storage+ */+export function serializePartsForStorage(parts: MessageContentPart[]): string {+ return JSON.stringify(parts);+}++/**+ * Deserialize content string to message content parts+ * Returns null if content is not valid JSON array of parts+ */+export function deserializeParts(content: string): MessageContentPart[] | null {+ try {+ const parsed = JSON.parse(content);+ // Validate it's an array with valid part structure+ if (Array.isArray(parsed) && parsed.length > 0 && parsed[0]?.type) {+ return parsed as MessageContentPart[];+ }+ } catch {+ // Not JSON, treat as plain text+ }+ return null;+}diff --git a/packages/agent-runtime/src/utils/object.ts b/packages/agent-runtime/src/utils/object.tsnew file mode 100644index 00000000000..59c24316600--- /dev/null+++ b/packages/agent-runtime/src/utils/object.ts@@ -0,0 +1,60 @@+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 clean+ * @returns The cleaned object+ */+export const cleanObject = <T extends Record<string, any>>(obj: T): T => {+ return omitBy(obj, (value) => isNil(value) || value === '') as T;+};diff --git a/packages/agent-runtime/src/utils/safeParseJSON.ts b/packages/agent-runtime/src/utils/safeParseJSON.tsnew file mode 100644index 00000000000..c67c2942242--- /dev/null+++ b/packages/agent-runtime/src/utils/safeParseJSON.ts@@ -0,0 +1,22 @@+import { parse } from 'partial-json';++export const safeParseJSON = <T = Record<string, any>>(text?: string) => {+ if (typeof text !== 'string') return undefined;++ let json: T;+ try {+ json = JSON.parse(text);+ } catch {+ return undefined;+ }++ return json;+};++export const safeParsePartialJSON = <T = Record<string, any>>(text?: string): T | undefined => {+ try {+ return parse(text || '{}') as T;+ } catch {+ return undefined;+ }+};diff --git a/packages/agent-runtime/src/utils/sanitizeToolCallArguments.ts b/packages/agent-runtime/src/utils/sanitizeToolCallArguments.tsnew file mode 100644index 00000000000..5f45e79047b--- /dev/null+++ b/packages/agent-runtime/src/utils/sanitizeToolCallArguments.ts@@ -0,0 +1,29 @@+import { safeParseJSON, safeParsePartialJSON } from './safeParseJSON';++/**+ * Ensure a tool_call `arguments` string is always valid JSON before it+ * enters history or gets replayed to providers.+ *+ * Strict providers (e.g. NVIDIA NIM) validate the full message history on+ * every request. A single malformed `arguments` string β even one produced+ * many turns ago β causes a 400 on the entire request, terminating the op+ * and wasting all accumulated tokens. See .+ *+ * Behavior:+ * - Valid JSON β returned as-is (preserves prompt-cache keys).+ * - Recoverable via partial-json β re-stringified.+ * - Unrecoverable β "{}" so the tool_call structure survives and the+ * model can replan on the next turn.+ */+export const sanitizeToolCallArguments = (argsStr: string | undefined): string => {+ if (typeof argsStr !== 'string' || argsStr.length === 0) return '{}';++ if (safeParseJSON(argsStr) !== undefined) return argsStr;++ const recovered = safeParsePartialJSON(argsStr);+ if (recovered !== undefined && typeof recovered === 'object' && recovered !== null) {+ return JSON.stringify(recovered);+ }++ return '{}';+};diff --git a/packages/context-engine/package.json b/packages/context-engine/package.jsonindex 5829897951d..bc6cf817e18 100644--- a/packages/context-engine/package.json+++ b/packages/context-engine/package.json@@ -22,13 +22,14 @@"test:update": "vitest -u"},"dependencies": {- "@lobechat/const": "workspace:*",- "@lobechat/database": "workspace:*",+ "@lobechat/agent-templates": "workspace:*","@lobechat/prompts": "workspace:*",+ "@lobechat/types": "workspace:*","@lobechat/utils": "workspace:*","debug": "^4.4.3","es-toolkit": "^1.49.0","immer": "^10.2.0",+ "mime": "^4.1.0","partial-json": "^0.1.7","tokenx": "^1.3.0","ts-md5": "^2.0.1",@@ -37,7 +38,8 @@"xastscript": "^4.0.0"},"devDependencies": {- "@lobechat/types": "workspace:*","@types/debug": "^4.1.13"- }+ },+ "license": "MIT",+ "homepage": "https://github.com/lobehub/lobehub/tree/canary/packages/context-engine"}diff --git a/packages/context-engine/src/const/mediaRef.ts b/packages/context-engine/src/const/mediaRef.tsnew file mode 100644index 00000000000..0459f67b4b5--- /dev/null+++ b/packages/context-engine/src/const/mediaRef.ts@@ -0,0 +1,28 @@+export type MediaFileType = 'audio' | 'image' | 'video';++interface CreateMediaFileRefOptions {+ index: number;+ messageId?: string;+ type: MediaFileType;+}++export const createMediaLocalRef = (type: MediaFileType, index: number) => `${type}_${index + 1}`;++const hashMessageId = (messageId: string) => {+ let hash = 2166136261;++ for (const char of messageId) {+ hash ^= char.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }++ return (hash >>> 0).toString(36).slice(0, 6);+};++export const createMediaMessageRef = (messageId: string) => `msg_${hashMessageId(messageId)}`;++export const createMediaFileRef = ({ index, messageId, type }: CreateMediaFileRefOptions) => {+ const localRef = createMediaLocalRef(type, index);++ return messageId ? `${createMediaMessageRef(messageId)}.${localRef}` : localRef;+};diff --git a/packages/context-engine/src/const/message.ts b/packages/context-engine/src/const/message.tsnew file mode 100644index 00000000000..1c195c3ab5e--- /dev/null+++ b/packages/context-engine/src/const/message.ts@@ -0,0 +1,11 @@+export const LOADING_FLAT = '...';++export const MESSAGE_CANCEL_FLAT = 'canceled';++export const MESSAGE_THREAD_DIVIDER_ID = '__THREAD_DIVIDER__';++export const MESSAGE_WELCOME_GUIDE_ID = 'welcome';++export const THREAD_DRAFT_ID = '__THREAD_DRAFT_ID__';++export const MESSAGE_FLAGGED_THINKING = 'FLAGGED_THINKING';diff --git a/packages/context-engine/src/const/plugin.ts b/packages/context-engine/src/const/plugin.tsnew file mode 100644index 00000000000..670bd087f2c--- /dev/null+++ b/packages/context-engine/src/const/plugin.ts@@ -0,0 +1,53 @@+export const PLUGIN_SCHEMA_SEPARATOR = '____';+export const PLUGIN_SCHEMA_API_MD5_PREFIX = 'MD5HASH_';++/**+ * Canonical parse for a raw `TOOL_NAME_MAX_LENGTH` value β the length at which a+ * function-call tool name is compressed into an opaque `MD5HASH_β¦` name, `0`+ * turning that compression off.+ *+ * Returns `undefined` for unset / unparseable / negative input, meaning "not+ * configured": callers fall back to the default rather than failing, because a+ * typo in this var must never take a deployment down.+ *+ * Lives here, in a leaf module, because the var is read from two sides:+ * `ToolNameResolver` reads `process.env` directly on the server, while the app+ * ships the value to the browser with the global server config (the+ * client-driven chat path generates tool names where `process.env` isn't+ * visible). Parsing it with two different rule sets would let one env value mean+ * two different things, and the same tool could get different names on each side.+ */+export const parseToolNameMaxLength = (raw: string | undefined): number | undefined => {+ if (raw === undefined || raw === '') return undefined;+ const parsed = Number.parseInt(raw, 10);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;+};++export const ARTIFACT_TAG = 'lobeArtifact';+export const ARTIFACT_THINKING_TAG = 'lobeThinking';+export const MENTION_TAG = 'mention';+export const THINKING_TAG = 'think';+export const LOCAL_FILE_TAG = 'localFile';+export const SKILL_TAG = 'skill';+export const TASK_TAG = 'task';+/** Provider activity (CI failure, review feedback) injected into a conversation by the SCM integration. */+export const SCM_EVENT_TAG = 'scmEvent';+/** One goal manager planning turn: why it started, what changed since the last one, and the standing contract. */+export const GOAL_TURN_TAG = 'goalTurn';+export const TOOL_TAG = 'tool';+export const USER_FEEDBACK_TAG = 'user_feedback';+// https://regex101.com/r/TwzTkf/2+export const ARTIFACT_TAG_REGEX = /<lobeArtifact\b[^>]*>(?<content>[\S\s]*?)(?:<\/lobeArtifact>|$)/;++// https://regex101.com/r/r9gqGg/1+export const ARTIFACT_TAG_CLOSED_REGEX = /<lobeArtifact\b[^>]*>([\S\s]*?)<\/lobeArtifact>/;++// https://regex101.com/r/AvPA2g/1+export const ARTIFACT_THINKING_TAG_REGEX = /<lobeThinking\b[^>]*>([\S\s]*?)(?:<\/lobeThinking>|$)/;++export const THINKING_TAG_REGEX = /<think\b[^>]*>([\S\s]*?)(?:<\/think>|$)/;++export const MENTION_TAG_REGEX = /<mention\b[^>]*>([\S\s]*?)(?:<\/mention>|$)/;++export const AGENTS_TAG = 'lobeAgents';+export const AGENTS_TAG_REGEX = /<lobeAgents\b[^>]*(?:\/>|>([\S\s]*?)(?:<\/lobeAgents>|$))/;diff --git a/packages/context-engine/src/engine/tools/ToolNameResolver.ts b/packages/context-engine/src/engine/tools/ToolNameResolver.tsindex 8baa69c9a07..1c14a30c576 100644--- a/packages/context-engine/src/engine/tools/ToolNameResolver.ts+++ b/packages/context-engine/src/engine/tools/ToolNameResolver.ts@@ -1,4 +1,4 @@-import { parseToolNameMaxLength } from '@lobechat/const/plugin';+import { parseToolNameMaxLength } from '../../const/plugin';import { Md5 } from 'ts-md5';import type { ChatToolPayload, MessageToolCall } from '@/types/index';diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.config.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.config.test.tsindex a578122676d..93bd0596192 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.config.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.config.test.ts@@ -1,4 +1,4 @@-import { parseToolNameMaxLength } from '@lobechat/const/plugin';+import { parseToolNameMaxLength } from '../../../const/plugin';import { afterEach, describe, expect, it } from 'vitest';import { getToolNameMaxLength, setToolNameMaxLength, ToolNameResolver } from '../ToolNameResolver';diff --git a/packages/context-engine/src/policies/agentDocumentLoadPolicy.ts b/packages/context-engine/src/policies/agentDocumentLoadPolicy.tsnew file mode 100644index 00000000000..74f5769dff3--- /dev/null+++ b/packages/context-engine/src/policies/agentDocumentLoadPolicy.ts@@ -0,0 +1,96 @@+// Vendored from packages/database/src/models/agentDocuments/policy/loadPolicy.ts.+// context-engine needs the load-rule matching at assembly time, and reaching into+// another package's source over a relative path blocks package extraction.+// The database copy stays in place for now; folding it back is tracked separately.++import { DocumentLoadRule } from '@lobechat/agent-templates';++export type AgentDocumentLoadRule = 'always' | 'by-keywords' | 'by-regexp' | 'by-time-range';++export interface AgentDocumentLoadRules {+ keywordMatchMode?: 'all' | 'any';+ keywords?: string[];+ maxTokens?: number;+ priority?: number;+ regexp?: string;+ rule?: AgentDocumentLoadRule;+ timeRange?: {+ from?: string;+ to?: string;+ };+}++export interface AgentDocumentPolicyEvaluationContext {+ currentTime?: Date;+ currentUserMessage?: string;+}++export interface AgentContextDocumentRuleInput {+ loadRules?: AgentDocumentLoadRules;+}++const normalizeLoadRule = (rule?: string): AgentDocumentLoadRule | undefined => {+ switch (rule) {+ case DocumentLoadRule.ALWAYS:+ case DocumentLoadRule.BY_KEYWORDS:+ case DocumentLoadRule.BY_REGEXP:+ case DocumentLoadRule.BY_TIME_RANGE: {+ return rule;+ }+ default: {+ return undefined;+ }+ }+};++export const matchesLoadRules = (+ doc: AgentContextDocumentRuleInput,+ context: AgentDocumentPolicyEvaluationContext,+): boolean => {+ const rules = doc.loadRules;+ const loadRule = normalizeLoadRule(rules?.rule);++ if (!loadRule) return true;++ switch (loadRule) {+ case 'always': {+ return true;+ }+ case 'by-keywords': {+ const userMessage = context.currentUserMessage?.toLowerCase();+ const keywords = rules?.keywords?.map((k) => k.toLowerCase()).filter(Boolean) || [];+ if (!userMessage || keywords.length === 0) return false;++ if (rules?.keywordMatchMode === 'all') {+ return keywords.every((keyword) => userMessage.includes(keyword));+ }++ return keywords.some((keyword) => userMessage.includes(keyword));+ }+ case 'by-regexp': {+ if (!rules?.regexp || !context.currentUserMessage) return false;+ try {+ return new RegExp(rules.regexp, 'i').test(context.currentUserMessage);+ } catch {+ return false;+ }+ }+ case 'by-time-range': {+ const now = context.currentTime || new Date();+ const from = rules?.timeRange?.from+ ? Date.parse(rules.timeRange.from)+ : Number.NEGATIVE_INFINITY;+ const to = rules?.timeRange?.to ? Date.parse(rules.timeRange.to) : Number.POSITIVE_INFINITY;+ if (Number.isNaN(from) || Number.isNaN(to)) return false;+ const current = now.getTime();+ return current >= from && current <= to;+ }+ }+};++export const shouldInjectDocument = (+ doc: AgentContextDocumentRuleInput,+ context: AgentDocumentPolicyEvaluationContext,+): boolean => {+ return matchesLoadRules(doc, context);+};diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.tsindex 9dd32c60acb..97c5871aa25 100644--- a/packages/context-engine/src/processors/MessageContent.ts+++ b/packages/context-engine/src/processors/MessageContent.ts@@ -1,7 +1,7 @@-import { createMediaFileRef } from '@lobechat/const/mediaRef';+import { createMediaFileRef } from '../const/mediaRef';import { filesPrompts } from '@lobechat/prompts';import type { ChatAudioItem, MessageContentPart } from '@lobechat/types';-import { normalizeAudioDurationMs } from '@lobechat/utils/audio';+import { normalizeAudioDurationMs } from '../utils/audio';import { imageUrlToBase64 } from '@lobechat/utils/imageToBase64';import { parseDataUri } from '@lobechat/utils/uriParser';import { isDesktopLocalStaticServerUrl } from '@lobechat/utils/url';diff --git a/packages/context-engine/src/processors/PlaceholderMessageFilter.ts b/packages/context-engine/src/processors/PlaceholderMessageFilter.tsindex e8112adf1db..6d4eb14b68a 100644--- a/packages/context-engine/src/processors/PlaceholderMessageFilter.ts+++ b/packages/context-engine/src/processors/PlaceholderMessageFilter.ts@@ -1,4 +1,4 @@-import { LOADING_FLAT } from '@lobechat/const';+import { LOADING_FLAT } from '../const/message';import debug from 'debug';import { BaseProcessor } from '../base/BaseProcessor';diff --git a/packages/context-engine/src/processors/PlaceholderVariables.ts b/packages/context-engine/src/processors/PlaceholderVariables.tsindex 115a907adcc..ae3e9b7bf69 100644--- a/packages/context-engine/src/processors/PlaceholderVariables.ts+++ b/packages/context-engine/src/processors/PlaceholderVariables.ts@@ -1,5 +1,5 @@-import { PLUGIN_SCHEMA_SEPARATOR } from '@lobechat/const/plugin';-import { truncateSurrogateSafe } from '@lobechat/utils';+import { PLUGIN_SCHEMA_SEPARATOR } from '../const/plugin';+import { truncateSurrogateSafe } from '../utils/truncateSurrogateSafe';import debug from 'debug';import { BaseProcessor } from '../base/BaseProcessor';diff --git a/packages/context-engine/src/processors/ToolCall.ts b/packages/context-engine/src/processors/ToolCall.tsindex 0dd53f2e983..8771e38aed5 100644--- a/packages/context-engine/src/processors/ToolCall.ts+++ b/packages/context-engine/src/processors/ToolCall.ts@@ -1,4 +1,4 @@-import { sanitizeToolCallArguments } from '@lobechat/utils';+import { sanitizeToolCallArguments } from '../utils/sanitizeToolCallArguments';import debug from 'debug';import { BaseProcessor } from '../base/BaseProcessor';diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.tsindex 73310f869ee..9104e95aa1e 100644--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts@@ -1,4 +1,4 @@-import { createMediaFileRef } from '@lobechat/const/mediaRef';+import { createMediaFileRef } from '../../const/mediaRef';import type { ChatAudioItem, ChatImageItem, ChatVideoItem, UIChatMessage } from '@lobechat/types';import { describe, expect, it, vi } from 'vitest';diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts b/packages/context-engine/src/providers/AgentDocumentInjector/shared.tsindex 919b3c47379..7cc9671d635 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts@@ -3,8 +3,8 @@ import type { AgentDocumentPolicyLoad } from '@lobechat/types';import type {AgentDocumentLoadRule,AgentDocumentLoadRules,-} from '../../../../database/src/models/agentDocuments/policy/loadPolicy';-import { matchesLoadRules } from '../../../../database/src/models/agentDocuments/policy/loadPolicy';+} from '../../policies/agentDocumentLoadPolicy';+import { matchesLoadRules } from '../../policies/agentDocumentLoadPolicy';export type { AgentDocumentLoadRule, AgentDocumentLoadRules };export type { AgentDocumentPolicyLoad };diff --git a/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts b/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.tsindex 874fdb7901b..6073bf84be0 100644--- a/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts+++ b/packages/context-engine/src/tokenAccounting/attachmentTokenBuckets.ts@@ -8,8 +8,8 @@ import type {UIChatMessage,UploadFileItem,} from '@lobechat/types';-import { estimateAudioInputTokens } from '@lobechat/utils/audio';-import { getMimeType } from '@lobechat/utils/mimeType';+import { estimateAudioInputTokens } from '../utils/audio';+import { getMimeType } from '../utils/mimeType';import { estimateTokenCount } from 'tokenx';const ESTIMATE_INPUT_MESSAGE_ID = '__cost_estimate_input__';diff --git a/packages/context-engine/src/utils/audio.ts b/packages/context-engine/src/utils/audio.tsnew file mode 100644index 00000000000..6480342de66--- /dev/null+++ b/packages/context-engine/src/utils/audio.ts@@ -0,0 +1,85 @@+export const DEFAULT_AUDIO_INPUT_TOKEN_ESTIMATE = 1000;++export type AudioTokenEstimateSource = 'duration' | 'fallback' | 'mixed' | 'none';++export interface AudioInputTokenEstimate {+ durationItemCount: number;+ fallbackItemCount: number;+ source: AudioTokenEstimateSource;+ tokens: number;+}++export interface AudioTokenEstimateOptions {+ /** Conservative per-item fallback used when duration or the model rate is unavailable. */+ fallbackTokensPerItem?: number;+ /** Model-specific audio input token rate. Invalid or non-positive values are ignored. */+ tokensPerSecond?: number;+}++export const normalizeAudioDurationMs = (value: unknown): number | undefined => {+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined;++ return Math.ceil(value);+};++export const normalizeAudioTokensPerSecond = (value: unknown): number | undefined => {+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined;++ return value;+};++/**+ * Reads only the supported duration field from file metadata. Other metadata must never be+ * materialized onto chat audio items.+ */+export const readAudioDurationMs = (metadata: unknown): number | undefined => {+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return undefined;++ return normalizeAudioDurationMs((metadata as { durationMs?: unknown }).durationMs);+};++/**+ * Estimates audio input tokens without inspecting or fetching media URLs.+ *+ * Duration-based estimates are rounded up per item, but duration is an untrusted client hint and+ * therefore cannot reduce an estimate below the conservative fixed fallback. Items without both a+ * valid duration and a valid model rate use that fallback directly so pre-flight checks never+ * silently treat audio as free.+ */+export const estimateAudioInputTokens = (+ items: ReadonlyArray<{ durationMs?: unknown }>,+ options: AudioTokenEstimateOptions = {},+): AudioInputTokenEstimate => {+ const tokensPerSecond = normalizeAudioTokensPerSecond(options.tokensPerSecond);+ const fallbackTokensPerItem =+ normalizeAudioTokensPerSecond(options.fallbackTokensPerItem) ??+ DEFAULT_AUDIO_INPUT_TOKEN_ESTIMATE;+ let durationItemCount = 0;+ let fallbackItemCount = 0;+ let tokens = 0;++ for (const item of items) {+ const durationMs = normalizeAudioDurationMs(item.durationMs);++ if (durationMs !== undefined && tokensPerSecond !== undefined) {+ const durationTokens = Math.ceil((durationMs / 1000) * tokensPerSecond);+ tokens += Math.max(durationTokens, Math.ceil(fallbackTokensPerItem));+ durationItemCount += 1;+ continue;+ }++ tokens += Math.ceil(fallbackTokensPerItem);+ fallbackItemCount += 1;+ }++ const source: AudioTokenEstimateSource =+ durationItemCount > 0 && fallbackItemCount > 0+ ? 'mixed'+ : durationItemCount > 0+ ? 'duration'+ : fallbackItemCount > 0+ ? 'fallback'+ : 'none';++ return { durationItemCount, fallbackItemCount, source, tokens };+};diff --git a/packages/context-engine/src/utils/mimeType.ts b/packages/context-engine/src/utils/mimeType.tsnew file mode 100644index 00000000000..19add37b126--- /dev/null+++ b/packages/context-engine/src/utils/mimeType.ts@@ -0,0 +1,130 @@+import mime from 'mime';++// Extensions where mime-db has no entry (or a wrong one) but a specific+// text/x-* mime helps downstream language detection.+const CUSTOM_MIME_TYPES: Record<string, string> = {+ '.clj': 'text/x-clojure',+ '.ex': 'text/x-elixir',+ '.exs': 'text/x-elixir',+ '.go': 'text/x-go',+ '.hs': 'text/x-haskell',+ '.kt': 'text/x-kotlin',+ '.lua': 'text/x-lua',+ '.pl': 'text/x-perl',+ '.py': 'text/x-python',+ '.r': 'text/x-r',+ '.rb': 'text/x-ruby',+ '.rs': 'text/x-rust',+ '.scala': 'text/x-scala',+ '.svelte': 'text/x-svelte',+ '.swift': 'text/x-swift',+ '.sv': 'text/x-systemverilog',+ '.v': 'text/x-verilog',+ '.vue': 'text/x-vue',+};++const SNIFF_BYTES = 8192;+const TEXT_FALLBACK_MIME = 'text/plain; charset=utf-8';+const BINARY_FALLBACK_MIME = 'application/octet-stream';++// mime.getType returns bare types (e.g. 'application/json'); text-like+// responses need an explicit charset for the renderer.+const TEXT_MIME_PATTERN =+ /^(?:text\/|application\/(?:ecmascript|graphql|javascript|json|toml|xhtml\+xml|xml|yaml))/;++// SVG is text on disk but must keep its registered type: browsers only render+// it as an image from `image/svg+xml`, never from text/plain or application/xml.+// Other `+xml` types (atom, rss, β¦) stay on the text downgrade so text previews+// keep working for them.+const SVG_MIME = 'image/svg+xml';++const withCharset = (mimeType: string): string =>+ TEXT_MIME_PATTERN.test(mimeType) && !mimeType.includes('charset=')+ ? `${mimeType}; charset=utf-8`+ : mimeType;++const getExtension = (filePath: string): string => {+ const fileName = filePath.replace(/^.*[/\\]/s, '');+ const dotIndex = fileName.lastIndexOf('.');++ return dotIndex > 0 ? fileName.slice(dotIndex).toLowerCase() : '';+};++const lookupExtensionMime = (filePath: string): string | null => {+ const ext = getExtension(filePath);+ return CUSTOM_MIME_TYPES[ext] ?? mime.getType(filePath);+};++// Trimmed binary sniff: any null byte in the first 8KB β binary. Enough to+// disambiguate text sources from binary payloads for the downgrade rule.+const looksBinary = (buffer: Uint8Array): boolean => {+ const limit = Math.min(buffer.byteLength, SNIFF_BYTES);+ for (let i = 0; i < limit; i++) {+ if (buffer[i] === 0) return true;+ }+ return false;+};++/**+ * Sync extension-only lookup. Falls back to `application/octet-stream` for+ * unknown extensions. Use this when a file buffer isn't available (URL input,+ * TRPC payload, filename-only records).+ */+export const getMimeType = (filePath: string): string => {+ return lookupExtensionMime(filePath) || BINARY_FALLBACK_MIME;+};++/**+ * Extension-only lookup with charset appended for text mimes. Returns+ * `undefined` for unknown extensions so the caller can leave `Content-Type`+ * unset instead of forcing a download via `application/octet-stream`.+ * Use this for HTTP responses over known-closed asset sets (Vite output,+ * bundled resources, β¦).+ */+export const tryGetMimeType = (filePath: string): string | undefined => {+ const detected = lookupExtensionMime(filePath);+ return detected ? withCharset(detected) : undefined;+};++/**+ * Resolve a MIME type from a file path and its content buffer.+ *+ * Extension alone is ambiguous β `.ts` is `video/mp2t` in mime-db and also a+ * TypeScript source; a `.pdf` header is printable ASCII for the first bytes.+ * Trust magic bytes first, then fall back to the extension, and let a text+ * sniff overrule mime-db when the two disagree.+ *+ * 1. `fileTypeFromBuffer()` β magic-byte detection. Authoritative when it+ * matches: real MPEG-TS media wins here regardless of extension. The one+ * exception is a generic `application/xml` match, which yields to the+ * `.svg` extension (an SVG with an `<?xml` prolog).+ * 2. Extension lookup (custom map + `mime.getType`) β the only signal for+ * text formats file-type can't fingerprint (json/css/md/svg/β¦).+ * - Text mime β use as-is (with charset appended).+ * - `image/svg+xml` β use as-is; it is text but must render as an image.+ * - Binary mime + non-empty buffer that sniffs as text β downgrade to+ * text/plain. Saves TypeScript source from mime-db's `video/mp2t`.+ * - Otherwise β use the extension mime.+ * 3. No extension mapping β sniff-based fallback.+ */+export const resolveMimeType = async (filePath: string, buffer: Uint8Array): Promise<string> => {+ const { fileTypeFromBuffer } = await import('file-type');+ const detected = await fileTypeFromBuffer(buffer);+ const fromExtension = lookupExtensionMime(filePath);+ if (detected?.mime) {+ // file-type fingerprints any `<?xml` prolog as generic application/xml,+ // which would hide an SVG's image/svg+xml; the extension is more specific.+ if (detected.mime === 'application/xml' && fromExtension === SVG_MIME) return SVG_MIME;+ return detected.mime;+ }++ const isBinary = looksBinary(buffer);+ if (fromExtension) {+ if (TEXT_MIME_PATTERN.test(fromExtension)) return withCharset(fromExtension);+ if (fromExtension === SVG_MIME) return SVG_MIME;+ if (buffer.byteLength > 0 && !isBinary) return TEXT_FALLBACK_MIME;+ return fromExtension;+ }++ return isBinary ? BINARY_FALLBACK_MIME : TEXT_FALLBACK_MIME;+};diff --git a/packages/context-engine/src/utils/safeParseJSON.ts b/packages/context-engine/src/utils/safeParseJSON.tsnew file mode 100644index 00000000000..c67c2942242--- /dev/null+++ b/packages/context-engine/src/utils/safeParseJSON.ts@@ -0,0 +1,22 @@+import { parse } from 'partial-json';++export const safeParseJSON = <T = Record<string, any>>(text?: string) => {+ if (typeof text !== 'string') return undefined;++ let json: T;+ try {+ json = JSON.parse(text);+ } catch {+ return undefined;+ }++ return json;+};++export const safeParsePartialJSON = <T = Record<string, any>>(text?: string): T | undefined => {+ try {+ return parse(text || '{}') as T;+ } catch {+ return undefined;+ }+};diff --git a/packages/context-engine/src/utils/sanitizeToolCallArguments.ts b/packages/context-engine/src/utils/sanitizeToolCallArguments.tsnew file mode 100644index 00000000000..5f45e79047b--- /dev/null+++ b/packages/context-engine/src/utils/sanitizeToolCallArguments.ts@@ -0,0 +1,29 @@+import { safeParseJSON, safeParsePartialJSON } from './safeParseJSON';++/**+ * Ensure a tool_call `arguments` string is always valid JSON before it+ * enters history or gets replayed to providers.+ *+ * Strict providers (e.g. NVIDIA NIM) validate the full message history on+ * every request. A single malformed `arguments` string β even one produced+ * many turns ago β causes a 400 on the entire request, terminating the op+ * and wasting all accumulated tokens. See .+ *+ * Behavior:+ * - Valid JSON β returned as-is (preserves prompt-cache keys).+ * - Recoverable via partial-json β re-stringified.+ * - Unrecoverable β "{}" so the tool_call structure survives and the+ * model can replan on the next turn.+ */+export const sanitizeToolCallArguments = (argsStr: string | undefined): string => {+ if (typeof argsStr !== 'string' || argsStr.length === 0) return '{}';++ if (safeParseJSON(argsStr) !== undefined) return argsStr;++ const recovered = safeParsePartialJSON(argsStr);+ if (recovered !== undefined && typeof recovered === 'object' && recovered !== null) {+ return JSON.stringify(recovered);+ }++ return '{}';+};diff --git a/packages/context-engine/src/utils/truncateSurrogateSafe.ts b/packages/context-engine/src/utils/truncateSurrogateSafe.tsnew file mode 100644index 00000000000..ebae4a3c587--- /dev/null+++ b/packages/context-engine/src/utils/truncateSurrogateSafe.ts@@ -0,0 +1,23 @@+/**+ * Truncate a string to at most `maxLength` UTF-16 code units without letting+ * the cut split a surrogate pair.+ *+ * A bare `String#slice` can cut an astral-plane character (e.g. emoji) in+ * half, leaving a lone high surrogate at the end of the result.+ * `JSON.stringify` escapes it as an unpaired `\ud8xx`, which PostgreSQL's+ * jsonb parser rejects β so embedding a naively truncated preview in a jsonb+ * write fails the whole statement. Dropping that final code unit keeps the+ * result valid UTF-16.+ *+ * Scope: this only guards the boundary the cut itself creates (a trailing+ * high surrogate β one that pre-existed at the end of a short input is+ * trimmed the same way). Interior lone surrogates in already-invalid input+ * are `sanitizeUTF8`'s job, not this function's.+ */+export const truncateSurrogateSafe = (content: string, maxLength: number): string => {+ const sliced = content.slice(0, maxLength);+ const lastCode = sliced.charCodeAt(sliced.length - 1);++ // 0xD800β0xDBFF = high surrogate left at the cut, i.e. we split a pair+ return lastCode >= 0xd8_00 && lastCode <= 0xdb_ff ? sliced.slice(0, -1) : sliced;+};diff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.jsonindex 1fcc3d2d407..b387a2a5444 100644--- a/packages/model-runtime/package.json+++ b/packages/model-runtime/package.json@@ -38,10 +38,13 @@"@lobechat/business-model-runtime": "workspace:*","@lobechat/const": "workspace:*","@lobechat/ssrf-safe-fetch": "workspace:*",- "@lobechat/utils": "workspace:*",+ "@lobechat/types": "workspace:*","async-retry": "^1.3.3",+ "buffer.js": "npm:buffer@^6.0.3","dayjs": "^1.11.21","debug": "^4.4.3",+ "es-toolkit": "^1.50.0",+ "file-type": "^21.3.4","immer": "^10.2.0","langfuse": "^3.38.20","langfuse-core": "^3.38.20",@@ -54,10 +57,9 @@"type-fest": "^5.7.0","url-join": "^5.0.0"},- "devDependencies": {- "@lobechat/types": "workspace:*"- },"peerDependencies": {"zod": "^4.4.3"- }+ },+ "license": "MIT",+ "homepage": "https://github.com/lobehub/lobehub/tree/canary/packages/model-runtime"}diff --git a/packages/model-runtime/src/const/currency.ts b/packages/model-runtime/src/const/currency.tsnew file mode 100644index 00000000000..414118be7b0--- /dev/null+++ b/packages/model-runtime/src/const/currency.ts@@ -0,0 +1,4 @@+// in 2025.10.22+export const USD_TO_CNY = 7.12;++export const CREDITS_PER_DOLLAR = 1_000_000;diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex e9f987bf7b2..861e6468dbd 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -1,5 +1,5 @@import type { ModelPerformance, ModelUsage, TracePayload } from '@lobechat/types';-import { createTimingHelpers, getDurationMs } from '@lobechat/utils';+import { createTimingHelpers, getDurationMs } from '../utils/timing';import type { ClientOptions } from 'openai';import type { LobeBedrockAIParams } from '../providers/bedrock';diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex df22bb63f19..5d5fa866505 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -4,7 +4,7 @@import type { GoogleGenAIOptions } from '@google/genai';import type { ModelPricingContext, RouterRuntimeRequestContext } from '@lobechat/types';import { AgentRuntimeErrorType } from '@lobechat/types';-import { createTimingHelpers, getDurationMs } from '@lobechat/utils';+import { createTimingHelpers, getDurationMs } from '../../utils/timing';import debug from 'debug';import { nanoid } from 'nanoid';diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.test.tsindex 94d6bdc21f0..ac006d71b7f 100644--- a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts@@ -1,4 +1,4 @@-import { imageUrlToBase64 } from '@lobechat/utils';+import { imageUrlToBase64 } from '../../utils/imageToBase64';import type { OpenAI } from 'openai';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -13,7 +13,7 @@ import {// Mock the parseDataUri function since it's an implementation detailvi.mock('../../utils/uriParser');-vi.mock('@lobechat/utils', async (importOriginal) => ({+vi.mock('../../utils/imageToBase64', async (importOriginal) => ({...((await importOriginal()) as object),imageUrlToBase64: vi.fn(),}));diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.tsindex 06b592c3562..15a15dd2565 100644--- a/packages/model-runtime/src/core/contextBuilders/anthropic.ts+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.ts@@ -1,5 +1,6 @@import type Anthropic from '@anthropic-ai/sdk';-import { imageUrlToBase64, resolveImageMimeTypeFromBase64 } from '@lobechat/utils';+import { imageUrlToBase64 } from '../../utils/imageToBase64';+import { resolveImageMimeTypeFromBase64 } from '../../utils/imageMimeType';import type OpenAI from 'openai';import type { OpenAIChatMessage, UserMessageContentPart } from '../../types';diff --git a/packages/model-runtime/src/core/contextBuilders/google.test.ts b/packages/model-runtime/src/core/contextBuilders/google.test.tsindex a7573d4830b..6ee128a5117 100644--- a/packages/model-runtime/src/core/contextBuilders/google.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/google.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import * as imageToBase64Module from '@lobechat/utils';+import * as imageToBase64Module from '../../utils/imageToBase64';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { ChatCompletionTool, OpenAIChatMessage, UserMessageContentPart } from '../../types';diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.tsindex 239bf6a12db..79a998f3584 100644--- a/packages/model-runtime/src/core/contextBuilders/google.ts+++ b/packages/model-runtime/src/core/contextBuilders/google.ts@@ -4,7 +4,8 @@ import type {Part,Tool as GoogleFunctionCallTool,} from '@google/genai';-import { imageUrlToBase64, resolveImageMimeTypeFromBase64 } from '@lobechat/utils';+import { imageUrlToBase64 } from '../../utils/imageToBase64';+import { resolveImageMimeTypeFromBase64 } from '../../utils/imageMimeType';import type { ChatCompletionTool, OpenAIChatMessage, UserMessageContentPart } from '../../types';import { safeParseJSON } from '../../utils/safeParseJSON';diff --git a/packages/model-runtime/src/core/contextBuilders/openai.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.test.tsindex bb54f670454..be2e4d8c0ef 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.test.ts@@ -1,4 +1,5 @@-import { imageUrlToBase64, videoUrlToBase64 } from '@lobechat/utils';+import { imageUrlToBase64 } from '../../utils/imageToBase64';+import { videoUrlToBase64 } from '../../utils/videoToBase64';import type OpenAI from 'openai';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -15,8 +16,10 @@ import {} from './openai';// 樑ζδΎθ΅-vi.mock('@lobechat/utils', () => ({+vi.mock('../../utils/imageToBase64', () => ({imageUrlToBase64: vi.fn(),+}));+vi.mock('../../utils/videoToBase64', () => ({videoUrlToBase64: vi.fn(),}));vi.mock('../../utils/uriParser');diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.tsindex e725001e380..6abdb039603 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts@@ -1,4 +1,5 @@-import { imageUrlToBase64, videoUrlToBase64 } from '@lobechat/utils';+import { imageUrlToBase64 } from '../../utils/imageToBase64';+import { videoUrlToBase64 } from '../../utils/videoToBase64';import { Buffer } from 'buffer.js';import type OpenAI from 'openai';import { toFile } from 'openai';diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/client.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/client.tsindex 8c70da05bf4..2989a16f413 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/client.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/client.ts@@ -1,4 +1,4 @@-import { isRecord } from '@lobechat/utils';+import { isRecord } from '../../utils/object';import OpenAI from 'openai';/** Preserves flat JSON errors returned by OpenAI-compatible providers. */diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.test.tsindex 449d1e5f7c3..442b895358e 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import * as imageToBase64Module from '@lobechat/utils';+import * as imageToBase64Module from '../../utils/imageToBase64';import type OpenAI from 'openai';import { beforeEach, describe, expect, it, vi } from 'vitest';diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.tsindex 9533bfff366..145d27d8115 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts@@ -1,4 +1,4 @@-import { cleanObject } from '@lobechat/utils/object';+import { cleanObject } from '../../utils/object';import createDebug from 'debug';import type { RuntimeImageGenParamsValue } from 'model-bank';import type OpenAI from 'openai';diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/decide/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/index.tsindex 9dc14aa6b14..a03a2ac5a1a 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/decide/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/index.ts@@ -1,6 +1,6 @@import type { ModelUsage } from '@lobechat/types';import { AgentRuntimeErrorType } from '@lobechat/types';-import { isRecord } from '@lobechat/utils/object';+import { isRecord } from '../../../utils/object';import createDebug from 'debug';import { DECISION_MODEL_SUFFIX } from 'model-bank';import type OpenAI from 'openai';diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.tsindex 32f728b16b2..13768cdf8db 100644--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts@@ -1,4 +1,4 @@-import { CREDITS_PER_DOLLAR, USD_TO_CNY } from '@lobechat/const/currency';+import { CREDITS_PER_DOLLAR, USD_TO_CNY } from '../../../const/currency';import type { ModelTokensUsage } from '@lobechat/types';import debug from 'debug';import type {diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.tsindex 4ba2eebb5c5..99fb85e3fe1 100644--- a/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/computeImageCost.ts@@ -1,4 +1,4 @@-import { CREDITS_PER_DOLLAR } from '@lobechat/const/currency';+import { CREDITS_PER_DOLLAR } from '../../../const/currency';import debug from 'debug';import type { FixedPricingUnit, LookupPricingUnit, Pricing } from 'model-bank';diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.tsindex 002e83d1cd3..1fe94e0a419 100644--- a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.ts@@ -1,4 +1,4 @@-import { CREDITS_PER_DOLLAR, USD_TO_CNY } from '@lobechat/const/currency';+import { CREDITS_PER_DOLLAR, USD_TO_CNY } from '../../../const/currency';import debug from 'debug';import type {FixedPricingUnit,diff --git a/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.tsindex ec7c5d56452..3597a96077e 100644--- a/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/estimateChatCost.ts@@ -3,7 +3,7 @@ import {type AudioTokenEstimateSource,estimateAudioInputTokens,normalizeAudioTokensPerSecond,-} from '@lobechat/utils/audio';+} from '../../../utils/audio';import type { Pricing, PricingUnitName } from 'model-bank';import { estimateTokenCount } from 'tokenx';diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.tsindex 2a7a86a9681..39dccbd3131 100644--- a/packages/model-runtime/src/errors/normalizeChatMessageError.ts+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.ts@@ -1,5 +1,5 @@import { AgentRuntimeErrorType, ChatErrorType, type ChatMessageError } from '@lobechat/types';-import { isRecord } from '@lobechat/utils/object';+import { isRecord } from '../utils/object';import { refineErrorCode } from './refine';import { getErrorCodeSpec } from './specs';diff --git a/packages/model-runtime/src/providers/bedrock/providerDiagnostics.ts b/packages/model-runtime/src/providers/bedrock/providerDiagnostics.tsindex 7cb21c5ea54..87db525b8dd 100644--- a/packages/model-runtime/src/providers/bedrock/providerDiagnostics.ts+++ b/packages/model-runtime/src/providers/bedrock/providerDiagnostics.ts@@ -1,4 +1,4 @@-import { toRecord } from '@lobechat/utils/object';+import { toRecord } from '../../utils/object';import {appendProviderResponseEvent,diff --git a/packages/model-runtime/src/providers/bfl/createImage.test.ts b/packages/model-runtime/src/providers/bfl/createImage.test.tsindex ffe230ebc7c..404d612a5cf 100644--- a/packages/model-runtime/src/providers/bfl/createImage.test.ts+++ b/packages/model-runtime/src/providers/bfl/createImage.test.ts@@ -7,7 +7,7 @@ import { createBflImage } from './createImage';import { BflStatusResponse } from './types';// Mock external dependencies-vi.mock('@lobechat/utils', () => ({+vi.mock('../../utils/imageToBase64', () => ({imageUrlToBase64: vi.fn(),}));@@ -189,7 +189,7 @@ describe('createBflImage', () => {it('should convert single imageUrl to image_prompt base64', async () => {// Arrangeconst { parseDataUri } = await import('../../utils/uriParser');- const { imageUrlToBase64 } = await import('@lobechat/utils');+ const { imageUrlToBase64 } = await import('../../utils/imageToBase64');const { asyncifyPolling } = await import('../../utils/asyncifyPolling');const mockParseDataUri = vi.mocked(parseDataUri);@@ -292,7 +292,7 @@ describe('createBflImage', () => {it('should convert multiple imageUrls for Kontext models', async () => {// Arrangeconst { parseDataUri } = await import('../../utils/uriParser');- const { imageUrlToBase64 } = await import('@lobechat/utils');+ const { imageUrlToBase64 } = await import('../../utils/imageToBase64');const { asyncifyPolling } = await import('../../utils/asyncifyPolling');const mockParseDataUri = vi.mocked(parseDataUri);@@ -352,7 +352,7 @@ describe('createBflImage', () => {it('should limit imageUrls to maximum 4 images', async () => {// Arrangeconst { parseDataUri } = await import('../../utils/uriParser');- const { imageUrlToBase64 } = await import('@lobechat/utils');+ const { imageUrlToBase64 } = await import('../../utils/imageToBase64');const { asyncifyPolling } = await import('../../utils/asyncifyPolling');const mockParseDataUri = vi.mocked(parseDataUri);diff --git a/packages/model-runtime/src/providers/comfyui/__tests__/index.test.ts b/packages/model-runtime/src/providers/comfyui/__tests__/index.test.tsindex 71ca21859d7..1e3a8d3a246 100644--- a/packages/model-runtime/src/providers/comfyui/__tests__/index.test.ts+++ b/packages/model-runtime/src/providers/comfyui/__tests__/index.test.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport type { ComfyUIKeyVault } from '@lobechat/types';-import { createBasicAuthCredentials } from '@lobechat/utils';+import { createBasicAuthCredentials } from '../../../utils/base64';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { CreateImagePayload } from '../../../types/image';diff --git a/packages/model-runtime/src/providers/comfyui/index.ts b/packages/model-runtime/src/providers/comfyui/index.tsindex b85a5f20749..e7a95ee6531 100644--- a/packages/model-runtime/src/providers/comfyui/index.ts+++ b/packages/model-runtime/src/providers/comfyui/index.ts@@ -1,5 +1,5 @@import type { ComfyUIKeyVault } from '@lobechat/types';-import { createBasicAuthCredentials } from '@lobechat/utils';+import { createBasicAuthCredentials } from '../../utils/base64';import debug from 'debug';import type { LobeRuntimeAI } from '../../core/BaseAI';diff --git a/packages/model-runtime/src/providers/deepseek/sanitizePayload.ts b/packages/model-runtime/src/providers/deepseek/sanitizePayload.tsindex a46b857c0ce..71cae4356ce 100644--- a/packages/model-runtime/src/providers/deepseek/sanitizePayload.ts+++ b/packages/model-runtime/src/providers/deepseek/sanitizePayload.ts@@ -1,4 +1,4 @@-import { isPlainRecord } from '@lobechat/utils';+import { isPlainRecord } from '../../utils/object';const HIGH_SURROGATE_START = 0xd8_00;const HIGH_SURROGATE_END = 0xdb_ff;diff --git a/packages/model-runtime/src/providers/google/createImage.test.ts b/packages/model-runtime/src/providers/google/createImage.test.tsindex c6cd67f3e6a..d41c992e1ce 100644--- a/packages/model-runtime/src/providers/google/createImage.test.ts+++ b/packages/model-runtime/src/providers/google/createImage.test.ts@@ -1,7 +1,7 @@// @vitest-environment nodeimport type { GoogleGenAI } from '@google/genai';import { MediaModality } from '@google/genai';-import * as imageToBase64Module from '@lobechat/utils';+import * as imageToBase64Module from '../../utils/imageToBase64';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { CreateImagePayload } from '../../types/image';diff --git a/packages/model-runtime/src/providers/google/createVideo.test.ts b/packages/model-runtime/src/providers/google/createVideo.test.tsindex 3522fd12317..8b6c4231017 100644--- a/packages/model-runtime/src/providers/google/createVideo.test.ts+++ b/packages/model-runtime/src/providers/google/createVideo.test.ts@@ -28,7 +28,7 @@ vi.mock('../../utils/uriParser', () => ({}),}));-vi.mock('@lobechat/utils', () => ({+vi.mock('../../utils/imageToBase64', () => ({imageUrlToBase64: vi.fn(async (_url) => ({base64: 'mock-base64-data',mimeType: 'image/jpeg',diff --git a/packages/model-runtime/src/providers/ollama/index.test.ts b/packages/model-runtime/src/providers/ollama/index.test.tsindex 30c2ab0b94d..067e51fd183 100644--- a/packages/model-runtime/src/providers/ollama/index.test.ts+++ b/packages/model-runtime/src/providers/ollama/index.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { imageUrlToBase64 } from '@lobechat/utils';+import { imageUrlToBase64 } from '../../utils/imageToBase64';import { ModelProvider } from 'model-bank';import { Ollama } from 'ollama/browser';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -10,8 +10,8 @@ import * as debugStreamModule from '../../utils/debugStream';import { LobeOllamaAI, params } from './index';vi.mock('ollama/browser');-vi.mock('@lobechat/utils', async () => {- const actual = await vi.importActual('@lobechat/utils');+vi.mock('../../utils/imageToBase64', async () => {+ const actual = await vi.importActual('../../utils/imageToBase64');return {...actual,imageUrlToBase64: vi.fn(),diff --git a/packages/model-runtime/src/providers/ollama/index.ts b/packages/model-runtime/src/providers/ollama/index.tsindex 861cd280242..0e1c76f0ab4 100644--- a/packages/model-runtime/src/providers/ollama/index.ts+++ b/packages/model-runtime/src/providers/ollama/index.ts@@ -1,5 +1,5 @@import type { ChatModelCard } from '@lobechat/types';-import { imageUrlToBase64 } from '@lobechat/utils';+import { imageUrlToBase64 } from '../../utils/imageToBase64';import { ModelProvider } from 'model-bank';import type { ChatResponse, Tool } from 'ollama/browser';import { Ollama } from 'ollama/browser';diff --git a/packages/model-runtime/src/providers/opencodeCodingPlan/index.ts b/packages/model-runtime/src/providers/opencodeCodingPlan/index.tsindex 46c1043efe4..939dc943648 100644--- a/packages/model-runtime/src/providers/opencodeCodingPlan/index.ts+++ b/packages/model-runtime/src/providers/opencodeCodingPlan/index.ts@@ -1,4 +1,4 @@-import { pickNonEmptyString } from '@lobechat/utils/object';+import { pickNonEmptyString } from '../../utils/object';import { LOBE_DEFAULT_MODEL_LIST, ModelProvider } from 'model-bank';import type OpenAI from 'openai';diff --git a/packages/model-runtime/src/providers/xai/index.ts b/packages/model-runtime/src/providers/xai/index.tsindex 5e4f16c77ad..3ce1fdd612c 100644--- a/packages/model-runtime/src/providers/xai/index.ts+++ b/packages/model-runtime/src/providers/xai/index.ts@@ -1,4 +1,4 @@-import { isRecord } from '@lobechat/utils';+import { isRecord } from '../../utils/object';import { ModelProvider } from 'model-bank';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';diff --git a/packages/model-runtime/src/utils/audio.ts b/packages/model-runtime/src/utils/audio.tsnew file mode 100644index 00000000000..6480342de66--- /dev/null+++ b/packages/model-runtime/src/utils/audio.ts@@ -0,0 +1,85 @@+export const DEFAULT_AUDIO_INPUT_TOKEN_ESTIMATE = 1000;++export type AudioTokenEstimateSource = 'duration' | 'fallback' | 'mixed' | 'none';++export interface AudioInputTokenEstimate {+ durationItemCount: number;+ fallbackItemCount: number;+ source: AudioTokenEstimateSource;+ tokens: number;+}++export interface AudioTokenEstimateOptions {+ /** Conservative per-item fallback used when duration or the model rate is unavailable. */+ fallbackTokensPerItem?: number;+ /** Model-specific audio input token rate. Invalid or non-positive values are ignored. */+ tokensPerSecond?: number;+}++export const normalizeAudioDurationMs = (value: unknown): number | undefined => {+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined;++ return Math.ceil(value);+};++export const normalizeAudioTokensPerSecond = (value: unknown): number | undefined => {+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined;++ return value;+};++/**+ * Reads only the supported duration field from file metadata. Other metadata must never be+ * materialized onto chat audio items.+ */+export const readAudioDurationMs = (metadata: unknown): number | undefined => {+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return undefined;++ return normalizeAudioDurationMs((metadata as { durationMs?: unknown }).durationMs);+};++/**+ * Estimates audio input tokens without inspecting or fetching media URLs.+ *+ * Duration-based estimates are rounded up per item, but duration is an untrusted client hint and+ * therefore cannot reduce an estimate below the conservative fixed fallback. Items without both a+ * valid duration and a valid model rate use that fallback directly so pre-flight checks never+ * silently treat audio as free.+ */+export const estimateAudioInputTokens = (+ items: ReadonlyArray<{ durationMs?: unknown }>,+ options: AudioTokenEstimateOptions = {},+): AudioInputTokenEstimate => {+ const tokensPerSecond = normalizeAudioTokensPerSecond(options.tokensPerSecond);+ const fallbackTokensPerItem =+ normalizeAudioTokensPerSecond(options.fallbackTokensPerItem) ??+ DEFAULT_AUDIO_INPUT_TOKEN_ESTIMATE;+ let durationItemCount = 0;+ let fallbackItemCount = 0;+ let tokens = 0;++ for (const item of items) {+ const durationMs = normalizeAudioDurationMs(item.durationMs);++ if (durationMs !== undefined && tokensPerSecond !== undefined) {+ const durationTokens = Math.ceil((durationMs / 1000) * tokensPerSecond);+ tokens += Math.max(durationTokens, Math.ceil(fallbackTokensPerItem));+ durationItemCount += 1;+ continue;+ }++ tokens += Math.ceil(fallbackTokensPerItem);+ fallbackItemCount += 1;+ }++ const source: AudioTokenEstimateSource =+ durationItemCount > 0 && fallbackItemCount > 0+ ? 'mixed'+ : durationItemCount > 0+ ? 'duration'+ : fallbackItemCount > 0+ ? 'fallback'+ : 'none';++ return { durationItemCount, fallbackItemCount, source, tokens };+};diff --git a/packages/model-runtime/src/utils/base64.ts b/packages/model-runtime/src/utils/base64.tsnew file mode 100644index 00000000000..a26d32a55be--- /dev/null+++ b/packages/model-runtime/src/utils/base64.ts@@ -0,0 +1,70 @@+/**+ * Cross-platform base64 encoding utility+ * Works in both browser and Node.js environments+ */++import { Buffer } from 'buffer.js';++/**+ * Encode raw bytes to base64+ * @param bytes - The bytes to encode+ * @returns Base64 encoded string+ */+export const bytesToBase64 = (bytes: Uint8Array): string => {+ if (typeof btoa === 'function') {+ // Browser environment: `btoa` wants a Latin1 binary string; build it in+ // chunks because `String.fromCharCode(...bytes)` overflows the argument+ // limit on large payloads.+ let binary = '';+ const chunkSize = 8192;+ for (let index = 0; index < bytes.byteLength; index += chunkSize) {+ binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize));+ }+ return btoa(binary);+ } else {+ // Node.js environment+ return Buffer.from(bytes).toString('base64');+ }+};++/**+ * Decode a base64 string to raw bytes+ * @param input - The base64 string to decode+ * @returns Decoded bytes+ */+export const base64ToBytes = (input: string): Uint8Array => {+ if (typeof atob === 'function') {+ // Browser environment: `atob` yields a Latin1 binary string, one char per byte.+ const binary = atob(input);+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));+ } else {+ // Node.js environment+ return new Uint8Array(Buffer.from(input, 'base64'));+ }+};++/**+ * Encode a string to base64+ * @param input - The string to encode+ * @returns Base64 encoded string+ */+export const encodeToBase64 = (input: string): string =>+ bytesToBase64(new TextEncoder().encode(input));++/**+ * Decode a base64 string+ * @param input - The base64 string to decode+ * @returns Decoded string+ */+export const decodeFromBase64 = (input: string): string =>+ new TextDecoder().decode(base64ToBytes(input));++/**+ * Create Basic Authentication header value+ * @param username - Username for authentication+ * @param password - Password for authentication+ * @returns Base64 encoded credentials for Basic auth+ */+export const createBasicAuthCredentials = (username: string, password: string): string => {+ return encodeToBase64(`${username}:${password}`);+};diff --git a/packages/model-runtime/src/utils/imageMimeType.ts b/packages/model-runtime/src/utils/imageMimeType.tsnew file mode 100644index 00000000000..45064a5efee--- /dev/null+++ b/packages/model-runtime/src/utils/imageMimeType.ts@@ -0,0 +1,86 @@+import { fileTypeFromBuffer } from 'file-type';++const normalizeMimeType = (mimeType: string | null | undefined): string => {+ return mimeType?.split(';')[0]?.trim().toLowerCase() ?? '';+};++const getBytes = (input: ArrayBuffer | Uint8Array): Uint8Array =>+ input instanceof Uint8Array ? input : new Uint8Array(input);++const normalizeDetectedMimeType = (mimeType: string | undefined): string | undefined => {+ const normalizedMimeType = normalizeMimeType(mimeType);++ return normalizedMimeType || undefined;+};++const normalizeDetectedImageMimeType = (mimeType: string | undefined): string | undefined => {+ const normalizedMimeType = normalizeDetectedMimeType(mimeType);++ if (!normalizedMimeType?.startsWith('image/')) return undefined;++ return normalizedMimeType === 'image/jpg' ? 'image/jpeg' : normalizedMimeType;+};++const decodeBase64Header = (base64: string): Uint8Array | undefined => {+ const header = base64.replaceAll(/\s/g, '').slice(0, 64);+ if (!header) return undefined;++ try {+ const binary = atob(header);+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));+ } catch {+ return undefined;+ }+};++export const inferMimeTypeFromBytes = async (+ input: ArrayBuffer | Uint8Array,+): Promise<string | undefined> => {+ const fileType = await fileTypeFromBuffer(getBytes(input));++ return normalizeDetectedMimeType(fileType?.mime);+};++export const inferImageMimeTypeFromBytes = async (+ input: ArrayBuffer | Uint8Array,+): Promise<string | undefined> => {+ return normalizeDetectedImageMimeType(await inferMimeTypeFromBytes(input));+};++export const inferImageMimeTypeFromBase64 = async (base64: string | null | undefined) => {+ if (!base64) return undefined;++ const bytes = decodeBase64Header(base64);+ if (!bytes) return undefined;++ return await inferImageMimeTypeFromBytes(bytes);+};++export const resolveImageMimeTypeFromBytes = async (+ declaredMimeType: string | null | undefined,+ input: ArrayBuffer | Uint8Array,+): Promise<string | undefined> => {+ return (+ (await inferImageMimeTypeFromBytes(input)) ??+ normalizeDetectedImageMimeType(declaredMimeType ?? undefined)+ );+};++export const resolveImageMimeTypeFromBase64 = async (+ declaredMimeType: string | null | undefined,+ base64: string | null | undefined,+): Promise<string | undefined> => {+ return (+ (await inferImageMimeTypeFromBase64(base64)) ??+ normalizeDetectedImageMimeType(declaredMimeType ?? undefined)+ );+};++export const resolveMimeTypeFromBytes = async (+ declaredMimeType: string | null | undefined,+ input: ArrayBuffer | Uint8Array,+): Promise<string> => {+ const declared = normalizeMimeType(declaredMimeType);++ return (await inferMimeTypeFromBytes(input)) ?? (declared || 'application/octet-stream');+};diff --git a/packages/model-runtime/src/utils/imageToBase64.ts b/packages/model-runtime/src/utils/imageToBase64.tsnew file mode 100644index 00000000000..bd2868c0765--- /dev/null+++ b/packages/model-runtime/src/utils/imageToBase64.ts@@ -0,0 +1,85 @@+import { Buffer } from 'buffer.js';++import { resolveMimeTypeFromBytes } from './imageMimeType';+import { readBlobWithLimit } from './readBlobWithLimit';++export { readBlobWithLimit } from './readBlobWithLimit';++export const imageToBase64 = ({+ size,+ img,+ type = 'image/webp',+}: {+ img: HTMLImageElement;+ size: number;+ type?: string;+}) => {+ const canvas = document.createElement('canvas');+ const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;+ let startX = 0;+ let startY = 0;++ if (img.width > img.height) {+ startX = (img.width - img.height) / 2;+ } else {+ startY = (img.height - img.width) / 2;+ }++ canvas.width = size;+ canvas.height = size;++ ctx.drawImage(+ img,+ startX,+ startY,+ Math.min(img.width, img.height),+ Math.min(img.width, img.height),+ 0,+ 0,+ size,+ size,+ );++ return canvas.toDataURL(type);+};++export interface ImageUrlToBase64Options {+ /** Abort the download once the response exceeds this many bytes. */+ maxBytes?: number;+}++/**+ * Convert image URL to base64+ * Uses SSRF-safe fetch on server-side to prevent SSRF attacks+ */+export const imageUrlToBase64 = async (+ imageUrl: string,+ options: ImageUrlToBase64Options = {},+): Promise<{ base64: string; mimeType: string }> => {+ try {+ const isServer = typeof window === 'undefined';++ // Use SSRF-safe fetch on server-side to prevent SSRF attacks+ const res = isServer+ ? await import('@lobechat/ssrf-safe-fetch').then((m) => m.ssrfSafeFetch(imageUrl))+ : await fetch(imageUrl);++ const blob = options.maxBytes+ ? await readBlobWithLimit(res, options.maxBytes)+ : await res.blob();+ const arrayBuffer = await blob.arrayBuffer();+ const mimeType = await resolveMimeTypeFromBytes(blob.type, arrayBuffer);++ // Client-side uses btoa, server-side uses Buffer+ const base64 = isServer+ ? Buffer.from(arrayBuffer).toString('base64')+ : btoa(+ new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), ''),+ );++ return { base64, mimeType };+ } catch (error) {+ console.error('Error converting image to base64:', error);+ throw error;+ }+};diff --git a/packages/model-runtime/src/utils/object.ts b/packages/model-runtime/src/utils/object.tsnew file mode 100644index 00000000000..59c24316600--- /dev/null+++ b/packages/model-runtime/src/utils/object.ts@@ -0,0 +1,60 @@+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 clean+ * @returns The cleaned object+ */+export const cleanObject = <T extends Record<string, any>>(obj: T): T => {+ return omitBy(obj, (value) => isNil(value) || value === '') as T;+};diff --git a/packages/model-runtime/src/utils/readBlobWithLimit.ts b/packages/model-runtime/src/utils/readBlobWithLimit.tsnew file mode 100644index 00000000000..1553b2614bf--- /dev/null+++ b/packages/model-runtime/src/utils/readBlobWithLimit.ts@@ -0,0 +1,53 @@+const sizeLimitError = (maxBytes: number) =>+ new RangeError(`Remote binary exceeds the ${maxBytes}-byte download limit`);++/**+ * Read a response body while enforcing a byte limit, including chunked responses.+ *+ * Use when:+ * - Downloading a remote file into memory for a bounded preview or conversion.+ *+ * Expects:+ * - An unread response and a positive maximum byte count.+ *+ * Returns:+ * - A blob, or throws RangeError after cancelling an oversized response.+ */+export const readBlobWithLimit = async (response: Response, maxBytes: number): Promise<Blob> => {+ const declaredLength = Number(response.headers.get('content-length'));+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {+ await response.body?.cancel().catch(() => {});+ throw sizeLimitError(maxBytes);+ }++ if (!response.body) {+ const blob = await response.blob();+ if (blob.size > maxBytes) throw sizeLimitError(maxBytes);+ return blob;+ }++ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let receivedBytes = 0;++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ receivedBytes += value.byteLength;+ if (receivedBytes > maxBytes) {+ await reader.cancel();+ throw sizeLimitError(maxBytes);+ }+ chunks.push(value);+ }++ const bytes = new Uint8Array(receivedBytes);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }++ return new Blob([bytes], { type: response.headers.get('content-type') || '' });+};diff --git a/packages/model-runtime/src/utils/referenceImageCache.test.ts b/packages/model-runtime/src/utils/referenceImageCache.test.tsindex 6bf29ca1e59..2f7d1c42ff4 100644--- a/packages/model-runtime/src/utils/referenceImageCache.test.ts+++ b/packages/model-runtime/src/utils/referenceImageCache.test.ts@@ -1,4 +1,4 @@-import { imageUrlToBase64 } from '@lobechat/utils';+import { imageUrlToBase64 } from './imageToBase64';import { beforeEach, describe, expect, it, vi } from 'vitest';import {@@ -8,7 +8,7 @@ import {referenceImageUrlToBase64,} from './referenceImageCache';-vi.mock('@lobechat/utils', () => ({ imageUrlToBase64: vi.fn() }));+vi.mock('./imageToBase64', () => ({ imageUrlToBase64: vi.fn() }));const createCache = (now = () => 0) => {const cache = new DownloadCache({ maxEntryBytes: 10, maxTotalBytes: 12, ttlMs: 1000 }, now);diff --git a/packages/model-runtime/src/utils/referenceImageCache.ts b/packages/model-runtime/src/utils/referenceImageCache.tsindex 5e2acbfdb56..9922de0f1ec 100644--- a/packages/model-runtime/src/utils/referenceImageCache.ts+++ b/packages/model-runtime/src/utils/referenceImageCache.ts@@ -1,4 +1,4 @@-import { imageUrlToBase64 } from '@lobechat/utils';+import { imageUrlToBase64 } from './imageToBase64';import type { Buffer } from 'buffer.js';/**diff --git a/packages/model-runtime/src/utils/routeFallback.ts b/packages/model-runtime/src/utils/routeFallback.tsindex a31ad26875b..e27f1621414 100644--- a/packages/model-runtime/src/utils/routeFallback.ts+++ b/packages/model-runtime/src/utils/routeFallback.ts@@ -1,4 +1,4 @@-import { toRecord } from '@lobechat/utils';+import { toRecord } from './object';import { getErrorCodeSpec } from '../errors/specs';import { AgentRuntimeErrorType } from '../types/error';diff --git a/packages/model-runtime/src/utils/timing.ts b/packages/model-runtime/src/utils/timing.tsnew file mode 100644index 00000000000..ff9d563691d--- /dev/null+++ b/packages/model-runtime/src/utils/timing.ts@@ -0,0 +1,261 @@+import debug from 'debug';++import { isRecord, pickString } from './object';++export interface TimingContext {+ requestId: string;+ startedAt: number;+}++export interface TimingMetadata {+ [key: string]: unknown;+}++export interface TimingParams {+ timingRequestId?: string;+ timingStartedAt?: number;+}++export interface TimingSink {+ log: (event: string, metadata?: TimingMetadata) => void;+}++export type TimingLogger = (formatter: string, ...args: unknown[]) => void;++export const createDebugTimingLogger = (namespace: string): TimingLogger => debug(namespace);++export const getDurationMs = (startedAt: number) => Date.now() - startedAt;++export const formatElapsedClockTime = (ms: number) => {+ const normalizedMs = Math.max(0, ms);+ const totalSeconds = Math.floor(normalizedMs / 1000);+ const days = Math.floor(totalSeconds / 86_400);+ const hours = Math.floor((totalSeconds % 86_400) / 3600);+ const minutes = Math.floor((totalSeconds % 3600) / 60);+ const seconds = totalSeconds % 60;+ const mm = String(minutes).padStart(2, '0');+ const ss = String(seconds).padStart(2, '0');++ if (days > 0) return `${days}d ${String(hours).padStart(2, '0')}:${mm}:${ss}`;+ return hours > 0 ? `${hours}:${mm}:${ss}` : `${mm}:${ss}`;+};++const DURATION_UNITS = [+ { ms: 86_400_000, suffix: 'd' },+ { ms: 3_600_000, suffix: 'h' },+ { ms: 60_000, suffix: 'm' },+ { ms: 1000, suffix: 's' },+] as const;++export interface FormatDurationOptions {+ /**+ * Smallest unit to print. By default seconds are shown below one hour and+ * dropped above it, where they only add noise.+ */+ minUnit?: 'm' | 's';+ /** Zero-pad every unit after the first (`1h 04m`), keeping live timers from jittering. */+ pad?: boolean;+ /** Drop zero-valued trailing units (`1h` instead of `1h 0m`). */+ trimZero?: boolean;+}++/**+ * Compact unit duration: `42s` Β· `3m 7s` Β· `1h 23m` Β· `1d 21h 23m`. Hours roll over+ * into days, so a long-running span never reads as `221h 29m`. The input is floored+ * to the smallest printed unit; round it first when the caller wants rounding.+ */+export const formatDuration = (ms: number, options: FormatDurationOptions = {}): string => {+ const { minUnit, pad, trimZero } = options;+ const total = Math.max(0, ms);+ const lastSuffix = minUnit ?? (total < 3_600_000 ? 's' : 'm');+ const lastIndex = DURATION_UNITS.findIndex((unit) => unit.suffix === lastSuffix);+ const largestIndex = DURATION_UNITS.findIndex((unit) => total >= unit.ms);+ const firstIndex = largestIndex === -1 ? lastIndex : Math.min(largestIndex, lastIndex);++ let remaining = total;+ const parts = DURATION_UNITS.slice(firstIndex, lastIndex + 1).map((unit, index) => {+ const value = Math.floor(remaining / unit.ms);+ remaining -= value * unit.ms;+ return {+ suffix: unit.suffix,+ text: pad && index > 0 ? String(value).padStart(2, '0') : String(value),+ value,+ };+ });++ while (trimZero && parts.length > 1 && parts.at(-1)!.value === 0) parts.pop();++ return parts.map((part) => `${part.text}${part.suffix}`).join(' ');+};++export const createTimingRequestId = () =>+ globalThis.crypto?.randomUUID?.() ??+ `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;++export const getTimingErrorMetadata = (error: unknown): TimingMetadata => {+ if (error instanceof Error) {+ return {+ errorMessage: error.message,+ errorName: error.name,+ };+ }++ if (isRecord(error)) {+ return {+ errorType: pickString(error.errorType),+ status: typeof error.status === 'number' ? error.status : undefined,+ };+ }++ return { errorMessage: String(error) };+};++export const toTimingContext = (params?: TimingParams): TimingContext | undefined =>+ params?.timingRequestId+ ? { requestId: params.timingRequestId, startedAt: params.timingStartedAt ?? Date.now() }+ : undefined;++export const logTiming = (+ logger: TimingLogger,+ context: TimingContext | undefined,+ event: string,+ metadata?: TimingMetadata,+) => {+ if (!context) return;++ const totalMs = getDurationMs(context.startedAt);+ if (metadata) {+ logger('[%s] %s totalMs=%d %O', context.requestId, event, totalMs, metadata);+ return;+ }++ logger('[%s] %s totalMs=%d', context.requestId, event, totalMs);+};++export const logTimingSink = (+ timing: TimingSink | undefined,+ event: string,+ metadata?: TimingMetadata,+) => {+ timing?.log(event, metadata);+};++export const markTimingStageDone = (+ logger: TimingLogger,+ context: TimingContext | undefined,+ stage: string,+ metadata?: TimingMetadata,+) => {+ if (!context) return;++ logTiming(logger, context, `${stage}:done`, {+ ...metadata,+ stageMs: 0,+ });+};++export const markTimingSinkStageDone = (+ timing: TimingSink | undefined,+ stage: string,+ metadata?: TimingMetadata,+) => {+ logTimingSink(timing, `${stage}:done`, {+ ...metadata,+ stageMs: 0,+ });+};++export const runTimedStage = async <T>(+ logger: TimingLogger,+ context: TimingContext | undefined,+ stage: string,+ task: () => T | Promise<T>,+ metadata?: TimingMetadata,+): Promise<Awaited<T>> => {+ if (!context) return await task();++ const startedAt = Date.now();+ logTiming(logger, context, `${stage}:start`, metadata);++ try {+ const result = await task();+ logTiming(logger, context, `${stage}:done`, {+ ...metadata,+ stageMs: getDurationMs(startedAt),+ });++ return result;+ } catch (error) {+ logTiming(logger, context, `${stage}:error`, {+ ...metadata,+ ...getTimingErrorMetadata(error),+ stageMs: getDurationMs(startedAt),+ });++ throw error;+ }+};++export const runTimedSinkStage = async <T>(+ timing: TimingSink | undefined,+ stage: string,+ task: () => T | Promise<T>,+ metadata?: TimingMetadata,+): Promise<Awaited<T>> => {+ if (!timing) return await task();++ const startedAt = Date.now();+ logTimingSink(timing, `${stage}:start`, metadata);++ try {+ const result = await task();+ logTimingSink(timing, `${stage}:done`, {+ ...metadata,+ stageMs: getDurationMs(startedAt),+ });++ return result;+ } catch (error) {+ logTimingSink(timing, `${stage}:error`, {+ ...metadata,+ ...getTimingErrorMetadata(error),+ stageMs: getDurationMs(startedAt),+ });++ throw error;+ }+};++export const createPrefixedTimingContext = (+ logger: TimingLogger,+ context: TimingContext | undefined,+ prefix: string,+): TimingSink | undefined =>+ context+ ? {+ log: (event: string, metadata?: TimingMetadata) => {+ logTiming(logger, context, `${prefix}.${event}`, metadata);+ },+ }+ : undefined;++export const createTimingHelpers = (namespace: string) => {+ const logger = createDebugTimingLogger(namespace);++ return {+ createPrefixedTimingContext: (context: TimingContext | undefined, prefix: string) =>+ createPrefixedTimingContext(logger, context, prefix),+ logger,+ logTiming: (context: TimingContext | undefined, event: string, metadata?: TimingMetadata) =>+ logTiming(logger, context, event, metadata),+ markStageDone: (context: TimingContext | undefined, stage: string, metadata?: TimingMetadata) =>+ markTimingStageDone(logger, context, stage, metadata),+ runTimedStage: <T>(+ context: TimingContext | undefined,+ stage: string,+ task: () => T | Promise<T>,+ metadata?: TimingMetadata,+ ) => runTimedStage(logger, context, stage, task, metadata),+ toTimingContext,+ };+};diff --git a/packages/model-runtime/src/utils/videoToBase64.ts b/packages/model-runtime/src/utils/videoToBase64.tsnew file mode 100644index 00000000000..54417e6a13b--- /dev/null+++ b/packages/model-runtime/src/utils/videoToBase64.ts@@ -0,0 +1,44 @@+/**+ * Convert video URL to base64 data URL with SSRF protection+ * Uses SSRF-safe fetch to prevent SSRF attacks+ */+export const videoUrlToBase64 = async (+ videoUrl: string,+): Promise<{ base64: string; mimeType: string }> => {+ try {+ const isServer = typeof window === 'undefined';++ // Use SSRF-safe fetch to prevent SSRF attacks+ const response = isServer+ ? await import('@lobechat/ssrf-safe-fetch').then((m) =>+ m.ssrfSafeFetch(videoUrl, {+ signal: AbortSignal.timeout(30_000), // 30 seconds+ }),+ )+ : await fetch(videoUrl);++ if (!response.ok) {+ throw new Error(`Failed to fetch video: ${response.status} ${response.statusText}`);+ }++ const contentType = response.headers.get('content-type');+ if (!contentType || !contentType.startsWith('video/')) {+ throw new Error('URL does not point to a valid video file');+ }++ const arrayBuffer = await response.arrayBuffer();+ const base64 = isServer+ ? Buffer.from(arrayBuffer).toString('base64')+ : btoa(+ new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), ''),+ );++ return {+ base64,+ mimeType: contentType,+ };+ } catch (error) {+ console.error('Error converting video to base64:', error);+ throw error;+ }+};