🤯 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(server): drop backend i18n and extract a reusable static i18n extractor (#20631)
Innei4b60cd37ae95
diff --git a/apps/server/src/services/agentSignal/orchestrator.ts b/apps/server/src/services/agentSignal/orchestrator.tsindex ba357b4f284..7205c785949 100644--- a/apps/server/src/services/agentSignal/orchestrator.ts+++ b/apps/server/src/services/agentSignal/orchestrator.ts@@ -28,7 +28,6 @@ import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';import { persistAgentSignalReceipts, projectAgentSignalReceipts } from './services/receiptService';import { createSelfIterationCompletionHandler } from './services/selfIteration/completion';import { createServerSelfReviewBriefWriter } from './services/selfIteration/review/brief';-import { resolveSelfReviewBriefTextTranslator } from './services/selfIteration/review/briefTextTranslator';import { claimNightlyReviewTopics } from './services/selfIteration/review/topicQuota';import { emitSourceEvent } from './sources';import { redisPolicyStateStore } from './store/adapters/redis/policyStateStore';@@ -113,8 +112,6 @@ const createPolicyOptions = (// Idea-only nightly reviews get their Daily Brief from the completion// path; proposal briefs are still written in-run by the review tool.ideasBrief: {- resolveTranslator: () =>- resolveSelfReviewBriefTextTranslator(context.db, context.userId),writer: createServerSelfReviewBriefWriter(context.db,context.userId,diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.tsindex cf12f1a6017..7850293bb92 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts@@ -5,7 +5,6 @@ import type { CompletionCallbackParams } from '../../../policies/completionPolicimport { type AgentSignalReceiptStore, persistAgentSignalReceipts } from '../../receiptService';import type { SelfReviewBriefProjection } from '../review/brief';import { createBriefSelfReviewService } from '../review/brief';-import type { SelfReviewBriefTextTranslator } from '../review/briefText';import type { SelfReviewIdea } from '../review/proposal';import type { Idea } from '../types';import { ReviewRunStatus, Risk } from '../types';@@ -20,8 +19,6 @@ const log = debug('lobe-server:completion-lifecycle');/** Daily Brief deps for nightly reviews that only recorded ideas. */export interface SelfIterationIdeasBriefOptions {- /** Resolves the brief owner's `home` translator; omitted → English resources. */- resolveTranslator?: () => Promise<SelfReviewBriefTextTranslator | undefined>;/** Writer that persists (and dedupes) nightly self-review Daily Briefs. */writer: { writeDailyBrief: (brief: SelfReviewBriefProjection) => Promise<unknown> };}@@ -101,7 +98,6 @@ const writeNightlyIdeasBrief = async ({},reviewWindowEnd,reviewWindowStart,- t: await ideasBrief.resolveTranslator?.(),timezone: 'UTC',userId,});diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.tsindex 0dfaa378344..790f0fed375 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts@@ -5,7 +5,6 @@ import { BriefModel } from '@/database/models/brief';import { ActionStatus, ApplyMode, ReviewRunStatus, Risk, Scope } from '../../types';import { createBriefSelfReviewService, createServerSelfReviewBriefWriter } from '../brief';-import type { SelfReviewBriefTextTranslator } from '../briefText';afterEach(() => {vi.restoreAllMocks();@@ -28,27 +27,6 @@ const getSelfReviewProposal = (brief: ReturnType<ReturnType<typeof createBriefSelfReviewService>['projectNightlyReviewBrief']>,) => getNightlySelfReview(brief)?.selfReviewProposal;-const zhCNBriefText: Record<string, string> = {- 'brief.agentSignal.selfReview.applied.heading': '已更新',- 'brief.agentSignal.selfReview.applied.summary': '已应用 {{count}} 条夜间回顾更新。',- 'brief.agentSignal.selfReview.applied.summary_plural': '已应用 {{count}} 条夜间回顾更新。',- 'brief.agentSignal.selfReview.applied.title': '夜间回顾已更新资源',- 'brief.agentSignal.selfReview.ideas.summary': '已保存夜间回顾记录,供后续查看。',- 'brief.agentSignal.selfReview.ideas.title': '夜间回顾记录',- 'brief.agentSignal.selfReview.proposal.heading': '建议',- 'brief.agentSignal.selfReview.proposal.summary': '有 {{count}} 条夜间回顾建议需要你确认。',- 'brief.agentSignal.selfReview.proposal.summary_plural': '有 {{count}} 条夜间回顾建议需要你确认。',- 'brief.agentSignal.selfReview.proposal.title': '有夜间回顾建议需要确认',-};--const createTranslator =- (resources: Record<string, string>): SelfReviewBriefTextTranslator =>- (key, options = {}) =>- Object.entries(options).reduce(- (content, [name, value]) => content.replace(`{{${name}}}`, value),- resources[key] ?? key,- );-describe('briefSelfReviewService', () => {/*** @example@@ -206,9 +184,9 @@ describe('briefSelfReviewService', () => {/*** @example- * Nightly proposal briefs use server-translated shell text before persistence.+ * Nightly proposal briefs persist source-English shell text around user-authored summaries.*/- it('projects proposal results to Chinese decision briefs', () => {+ it('keeps proposal shell text in English around localized action summaries', () => {const service = createBriefSelfReviewService();const brief = service.projectNightlyReviewBrief({@@ -227,14 +205,13 @@ describe('briefSelfReviewService', () => {},reviewWindowEnd: '2026-05-09T20:00:00.000Z',reviewWindowStart: '2026-05-09T18:00:00.000Z',- t: createTranslator(zhCNBriefText),timezone: 'Asia/Shanghai',userId: 'user-1',});- expect(brief?.title).toBe('有夜间回顾建议需要确认');+ expect(brief?.title).toBe('Dream suggestion needs review');expect(brief?.summary).toBe(- '有 1 条夜间回顾建议需要你确认。\n\n**建议**\n- 检查技能合并建议。',+ '1 dream suggestion needs your review.\n\n**Suggestion**\n- 检查技能合并建议。',);expect(brief?.type).toBe('decision');});@@ -433,10 +410,7 @@ describe('briefSelfReviewService', () => {target: { skillName: `pr-checklist-${index}` },});- const projectCreateSkillProposal = (- count: number,- options: { summary?: string; t?: SelfReviewBriefTextTranslator } = {},- ) => {+ const projectCreateSkillProposal = (count: number, options: { summary?: string } = {}) => {const actions = Array.from({ length: count }, (_, index) => createSkillPlanAction(index + 1));return createBriefSelfReviewService().projectNightlyReviewBrief({@@ -460,7 +434,6 @@ describe('briefSelfReviewService', () => {},reviewWindowEnd: '2026-05-09T20:00:00.000Z',reviewWindowStart: '2026-05-09T18:00:00.000Z',- t: options.t,timezone: 'Asia/Shanghai',userId: 'user-1',});@@ -512,23 +485,6 @@ describe('briefSelfReviewService', () => {);});- /**- * @example- * Specific proposal text is rendered through the owner's translator.- */- it('renders the specific title through the supplied translator', () => {- const brief = projectCreateSkillProposal(2, {- t: createTranslator({- ...zhCNBriefText,- 'brief.agentSignal.selfReview.kind.create_skill.withTarget': '新建技能:{{target}}',- 'brief.agentSignal.selfReview.title.more': '{{title}}(另有 {{count}} 项)',- }),- });-- expect(brief?.title).toBe('新建技能:PR checklist(另有 1 项)');- expect(brief?.title).not.toBe('有夜间回顾建议需要确认');- });-/*** @example* Ideas-only briefs list their ideas instead of "saved dream notes".diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/briefText.test.tsindex d3a652af185..6a5b340500a 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts@@ -1,28 +1,7 @@// @vitest-environment nodeimport { describe, expect, it } from 'vitest';-import { createSelfReviewBriefText, type SelfReviewBriefTextTranslator } from '../briefText';--const zhCN: Record<string, string> = {- 'brief.agentSignal.selfReview.applied.heading': '已更新',- 'brief.agentSignal.selfReview.applied.summary': '已应用 {{count}} 条夜间回顾更新。',- 'brief.agentSignal.selfReview.applied.summary_plural': '已应用 {{count}} 条夜间回顾更新。',- 'brief.agentSignal.selfReview.applied.title': '夜间回顾已更新资源',- 'brief.agentSignal.selfReview.ideas.summary': '已保存夜间回顾记录,供后续查看。',- 'brief.agentSignal.selfReview.ideas.title': '夜间回顾记录',- 'brief.agentSignal.selfReview.proposal.heading': '建议',- 'brief.agentSignal.selfReview.proposal.summary': '有 {{count}} 条夜间回顾建议需要你确认。',- 'brief.agentSignal.selfReview.proposal.summary_plural': '有 {{count}} 条夜间回顾建议需要你确认。',- 'brief.agentSignal.selfReview.proposal.title': '有夜间回顾建议需要确认',-};--const createTranslator =- (resources: Record<string, string>): SelfReviewBriefTextTranslator =>- (key, options = {}) =>- Object.entries(options).reduce(- (content, [name, value]) => content.replace(`{{${name}}}`, value),- resources[key] ?? key,- );+import { createSelfReviewBriefText } from '../briefText';describe('agent signal self-review brief text', () => {/**@@ -51,29 +30,9 @@ describe('agent signal self-review brief text', () => {/*** @example- * Persisted Brief shell text uses the supplied server translator.- */- it('renders proposal text through the supplied translator', () => {- expect(- createSelfReviewBriefText({- actionCounts: { applied: 0, failed: 0, proposed: 1, skipped: 0 },- actionSummaries: { applied: [], failed: [], proposed: ['检查技能合并建议。'] },- outcome: 'proposal',- t: createTranslator(zhCN),- }),- ).toEqual({- priority: 'normal',- summary: '有 1 条夜间回顾建议需要你确认。\n\n**建议**\n- 检查技能合并建议。',- title: '有夜间回顾建议需要确认',- type: 'decision',- });- });-- /**- * @example- * Without a translator the helper falls back to default English locale resources.+ * Applied outcomes render source-English insight text.*/- it('falls back to default English resources', () => {+ it('renders applied text in source English', () => {expect(createSelfReviewBriefText({actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/brief.tsindex 86ee43ade1c..d8c096214d7 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts@@ -9,11 +9,7 @@ import type { LobeChatDatabase } from '@/database/type';import type { EvidenceRef, RunResult } from '../types';import { ActionStatus } from '../types';-import {- createSelfReviewBriefText,- type SelfReviewBriefTextActionSummaries,- type SelfReviewBriefTextTranslator,-} from './briefText';+import { createSelfReviewBriefText, type SelfReviewBriefTextActionSummaries } from './briefText';import type {SelfReviewIdea,SelfReviewProposalMetadata,@@ -295,8 +291,6 @@ export interface ProjectNightlyReviewBriefInput {reviewWindowEnd: string;/** Review window start ISO timestamp. */reviewWindowStart: string;- /** Locale-aware translator for persisted Daily Brief text. */- t?: SelfReviewBriefTextTranslator;/** IANA timezone used for nightly scheduling. */timezone: string;/** User that owns the agent and brief. */@@ -574,7 +568,6 @@ export const createBriefSelfReviewService = () => ({actionSummaries,details: getSelfReviewBriefDetails(metadata),outcome,- t: input.t,});const artifacts = createBriefArtifacts({ ideas: input.ideas, proposal });diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.tsindex 050f0f78cc8..db56c102f8b 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts@@ -4,7 +4,34 @@ import {type SelfReviewBriefDetails,} from '@lobechat/agent-signal/brief';-import home from '@/locales/default/home';+const COPY: Record<string, string> = {+ 'brief.agentSignal.selfReview.applied.heading': 'Updated',+ 'brief.agentSignal.selfReview.applied.summary': '{{count}} dream update was applied.',+ 'brief.agentSignal.selfReview.applied.summary_plural': '{{count}} dream updates were applied.',+ 'brief.agentSignal.selfReview.applied.title': 'Dream updated resources',+ 'brief.agentSignal.selfReview.ideas.summary': 'Saved dream notes for future review.',+ 'brief.agentSignal.selfReview.ideas.title': 'Dream notes',+ 'brief.agentSignal.selfReview.kind.consolidate_skill.plain': 'Merge skills',+ 'brief.agentSignal.selfReview.kind.consolidate_skill.withTarget': 'Merge skills into {{target}}',+ 'brief.agentSignal.selfReview.kind.create_skill.plain': 'New skill',+ 'brief.agentSignal.selfReview.kind.create_skill.withTarget': 'New skill: {{target}}',+ 'brief.agentSignal.selfReview.kind.idea.plain': 'Dream note',+ 'brief.agentSignal.selfReview.kind.idea.withTarget': 'Dream note: {{target}}',+ 'brief.agentSignal.selfReview.kind.other.plain': 'Suggestion',+ 'brief.agentSignal.selfReview.kind.other.withTarget': 'Suggestion: {{target}}',+ 'brief.agentSignal.selfReview.kind.refine_prompt.plain': 'Refine system prompt',+ 'brief.agentSignal.selfReview.kind.refine_skill.plain': 'Refine skill',+ 'brief.agentSignal.selfReview.kind.refine_skill.withTarget': 'Refine skill: {{target}}',+ 'brief.agentSignal.selfReview.kind.write_memory.plain': 'Save memory',+ 'brief.agentSignal.selfReview.kind.write_memory.withTarget': 'Save memory: {{target}}',+ 'brief.agentSignal.selfReview.list.more': '{{count}} more',+ 'brief.agentSignal.selfReview.proposal.heading': 'Suggestion',+ 'brief.agentSignal.selfReview.proposal.summary': '{{count}} dream suggestion needs your review.',+ 'brief.agentSignal.selfReview.proposal.summary_plural':+ '{{count}} dream suggestions need your review.',+ 'brief.agentSignal.selfReview.proposal.title': 'Dream suggestion needs review',+ 'brief.agentSignal.selfReview.title.more': '{{title}} (+{{count}} more)',+};/*** Counts of self-review actions grouped by execution status.@@ -32,14 +59,6 @@ export interface SelfReviewBriefTextActionSummaries {proposed: string[];}-/**- * Translation function used to render persisted Agent Signal Daily Brief text.- */-export interface SelfReviewBriefTextTranslator {- /** Resolves a `home` namespace key with simple string interpolation. */- (key: string, options?: Record<string, string>): string;-}-/*** Input context for deterministic nightly self-review Daily Brief copy.*/@@ -56,8 +75,6 @@ export interface SelfReviewBriefTextInput {details?: SelfReviewBriefDetails;/** Coarse outcome selected by the projection service. */outcome: 'applied' | 'ideas' | 'proposal';- /** Locale-aware translator for the `home` namespace. Defaults to English resources. */- t?: SelfReviewBriefTextTranslator;}/**@@ -74,8 +91,8 @@ export interface SelfReviewBriefText {type: 'decision' | 'insight';}-const defaultTranslate: SelfReviewBriefTextTranslator = (key, options = {}) => {- const template = home[key as keyof typeof home] ?? key;+const t = (key: string, options: Record<string, string> = {}) => {+ const template = COPY[key] ?? key;return Object.entries(options).reduce((content, [name, value]) => content.replace(`{{${name}}}`, value),@@ -83,13 +100,8 @@ const defaultTranslate: SelfReviewBriefTextTranslator = (key, options = {}) => {);};-const actionCountKey = (input: {- count: number;- pluralKey: string;- singularKey: string;- t: SelfReviewBriefTextTranslator;-}) =>- input.t(input.count === 1 ? input.singularKey : input.pluralKey, {+const actionCountKey = (input: { count: number; pluralKey: string; singularKey: string }) =>+ t(input.count === 1 ? input.singularKey : input.pluralKey, {count: String(input.count),});@@ -106,7 +118,7 @@ const withDetails = (summary: string, heading: string, details: string[] = []) =** Use when:* - Nightly self-review projection needs title, summary, type, and priority- * - The output is user-visible and must be translated before persistence+ * - The output is user-visible and persisted in source English** Expects:* - `outcome` and `actionCounts` have already been computed by service policy@@ -116,8 +128,6 @@ const withDetails = (summary: string, heading: string, details: string[] = []) =* - Deterministic brief text without making a model call*/export const createSelfReviewBriefText = (input: SelfReviewBriefTextInput): SelfReviewBriefText => {- const t = input.t ?? defaultTranslate;-const details = input.details;if (input.outcome === 'proposal' && details?.kind === 'proposal') {@@ -129,7 +139,6 @@ export const createSelfReviewBriefText = (input: SelfReviewBriefTextInput): Selfcount: input.actionCounts.proposed,pluralKey: 'brief.agentSignal.selfReview.proposal.summary_plural',singularKey: 'brief.agentSignal.selfReview.proposal.summary',- t,}),title: formatSelfReviewBriefTitle(details, t),type: 'decision',@@ -141,7 +150,6 @@ export const createSelfReviewBriefText = (input: SelfReviewBriefTextInput): Selfcount: input.actionCounts.proposed,pluralKey: 'brief.agentSignal.selfReview.proposal.summary_plural',singularKey: 'brief.agentSignal.selfReview.proposal.summary',- t,});return {@@ -179,7 +187,6 @@ export const createSelfReviewBriefText = (input: SelfReviewBriefTextInput): Selfcount: input.actionCounts.applied,pluralKey: 'brief.agentSignal.selfReview.applied.summary_plural',singularKey: 'brief.agentSignal.selfReview.applied.summary',- t,});return {diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/briefTextTranslator.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/briefTextTranslator.tsdeleted file mode 100644index b4b13d82e9a..00000000000--- a/apps/server/src/services/agentSignal/services/selfIteration/review/briefTextTranslator.ts+++ /dev/null@@ -1,26 +0,0 @@-import { UserModel } from '@/database/models/user';-import type { LobeChatDatabase } from '@/database/type';-import { translation } from '@/libs/i18n/serverTranslation';--import type { SelfReviewBriefTextTranslator } from './briefText';--/**- * Resolves the `home` namespace translator used to render persisted nightly- * self-review Daily Brief text in the brief owner's response language.- *- * Use when:- * - A server path projects a nightly self-review Daily Brief (in-run proposal- * tool, or the completion-side ideas brief)- *- * Returns:- * - A translator for the user's response language, defaulting to en-US- */-export const resolveSelfReviewBriefTextTranslator = async (- db: LobeChatDatabase,- userId: string,-): Promise<SelfReviewBriefTextTranslator> => {- const userInfo = await UserModel.getInfoForAIGeneration(db, userId);- const { t } = await translation('home', userInfo.responseLanguage ?? 'en-US');-- return t;-};diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/server.tsindex 5eebd7ab09a..81dbfc9d476 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts@@ -36,7 +36,6 @@ import type { EvidenceRef } from '../types';import { buildNightlyReviewSourceId, Risk, Scope } from '../types';import type { createServerSelfReviewBriefWriter } from './brief';import { createBriefSelfReviewService } from './brief';-import type { SelfReviewBriefTextTranslator } from './briefText';import type {FeedbackActivityDigest,NightlyReviewManagedSkillSummary,@@ -470,7 +469,6 @@ const updateSelfReviewProposalBrief = async ({export interface ReviewRuntimePrimitiveDeps {agentId: string;briefModel: BriefModel;- briefTextTranslator?: SelfReviewBriefTextTranslator;db: LobeChatDatabase;localDate: string;proposalBriefWriter: ReturnType<typeof createServerSelfReviewBriefWriter>;@@ -499,7 +497,6 @@ export const createReviewRuntimePrimitives = (const {agentId,briefModel,- briefTextTranslator,db,localDate,proposalBriefWriter,@@ -589,7 +586,6 @@ export const createReviewRuntimePrimitives = (result: projection.execution,reviewWindowEnd,reviewWindowStart,- t: briefTextTranslator,timezone: 'UTC',userId,});diff --git a/apps/server/src/services/bot/__tests__/renderHeterogeneousError.test.ts b/apps/server/src/services/bot/__tests__/renderHeterogeneousError.test.tsindex d3360f1ee47..945fc7ab51b 100644--- a/apps/server/src/services/bot/__tests__/renderHeterogeneousError.test.ts+++ b/apps/server/src/services/bot/__tests__/renderHeterogeneousError.test.ts@@ -46,8 +46,9 @@ describe('heterogeneous IM errors', () => {resetsAt: 1789826400,},);- expect(reply).toContain('本周额度已用完');- expect(reply).toContain('2026-09-19 14:00');+ expect(reply).toContain('Weekly allowance exhausted.');+ expect(reply).toContain('Quota resets at 2026-09-19 14:00 (UTC).');+ expect(reply).toContain('Error code: `H2001`');expect(reply).toContain('UTC');expect(reply).not.toContain('E8001');});diff --git a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts b/apps/server/src/services/bot/__tests__/replyTemplate.test.tsindex 0a9c99264b4..c38d7879f6e 100644--- a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts+++ b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts@@ -384,7 +384,7 @@ describe('replyTemplate', () => {},);- it('renders a known request error instead of the attribution fallback', () => {+ it('renders a classified code without dedicated copy through its attribution fallback', () => {const output = renderAgentError('RequestBodyTooLarge','secret upstream payload',@@ -392,10 +392,9 @@ describe('replyTemplate', () => {'en-US','harness',);- expect(output).toContain('request is too large');expect(output).toContain('Error code: `E');expect(output).toContain('op-size');- expect(output).not.toContain('Something went wrong on our side');+ expect(output).not.toContain('Agent Execution Failed');expect(output).not.toContain('secret upstream payload');});@@ -688,7 +687,7 @@ describe('replyTemplate', () => {'en-US','system',);- expect(en).toContain('session state was unavailable');+ expect(en).toContain('A temporary system error occurred.');expect(en).not.toContain('model provider');expect(en).not.toMatch(/switch to a different model/i);expect(en).toContain('op-1');@@ -700,7 +699,7 @@ describe('replyTemplate', () => {'zh-CN','system',);- expect(zh).toContain('会话状态不可用');+ expect(zh).toContain('发生了临时系统错误');});it('still gives ProviderNetworkError the provider-specific network copy', () => {diff --git a/apps/server/src/services/bot/renderHeterogeneousError.ts b/apps/server/src/services/bot/renderHeterogeneousError.tsindex cd6d7e620cc..167bcb0ca42 100644--- a/apps/server/src/services/bot/renderHeterogeneousError.ts+++ b/apps/server/src/services/bot/renderHeterogeneousError.ts@@ -2,18 +2,101 @@ import {getHeterogeneousTypeLabel,isLocalHeterogeneousType,} from '@lobechat/heterogeneous-agents';-import { formatHeteroErrorId, HETERO_ERROR_SPECS } from '@lobechat/heterogeneous-agents/errors';+import {+ formatHeteroErrorId,+ HETERO_ERROR_SPECS,+ type HeteroErrorKind,+} from '@lobechat/heterogeneous-agents/errors';import type { ChatErrorHeterogeneousContext } from '@lobechat/types';-import english from '@/locales/default/modelRuntime';+const COPY: Record<HeteroErrorKind, { description: string; title: string }> = {+ aborted: {+ description: 'This {{agent}} task was stopped. Send a new request when you want to continue.',+ title: 'Task stopped',+ },+ agent_failed: {+ description:+ '{{agent}} stopped without a recognized cause. Share the Operation ID with the bot owner or support to investigate.',+ title: 'Agent task failed',+ },+ auth_required: {+ description: 'Ask the bot owner to sign in again on the device running {{agent}}.',+ title: 'Sign-in required',+ },+ cli_not_found: {+ description:+ 'Ask the bot owner to install or repair {{agent}} on the device running this task.',+ title: 'Agent CLI unavailable',+ },+ credit_limit: {+ description:+ 'Ask the bot owner to add credits to the account used by {{agent}}, or switch models. Waiting for a quota reset will not restore these credits.',+ title: 'Credits exhausted',+ },+ invalid_request: {+ description:+ 'The provider rejected the request sent by {{agent}}. Try a new topic; if it persists, share the Operation ID with support.',+ title: 'Request rejected',+ },+ max_turns: {+ description:+ '{{agent}} reached its step limit before finishing. Split the task into smaller steps, or ask the bot owner to adjust the limit.',+ title: 'Step limit reached',+ },+ model_unavailable: {+ description:+ 'The model selected for {{agent}} is unavailable. Ask the bot owner to choose another model.',+ title: 'Model unavailable',+ },+ network_drop: {+ description:+ '{{agent}} lost its connection before finishing. Retry; if it happens again, ask the bot owner to check the running device’s network and proxy settings.',+ title: 'Connection interrupted',+ },+ resume_cwd_mismatch: {+ description:+ 'Ask the bot owner to restore the working directory used by this {{agent}} session, or start a new topic.',+ title: 'Session directory changed',+ },+ resume_thread_not_found: {+ description:+ '{{agent}} could not find the previous session. Start a new topic and resend the request.',+ title: 'Previous session unavailable',+ },+ server_overloaded: {+ description: 'The provider behind {{agent}} is busy or unavailable. Please try again shortly.',+ title: 'Provider temporarily unavailable',+ },+ server_throttle: {+ description:+ 'The provider is temporarily limiting requests from {{agent}}. Please wait a moment and try again.',+ title: 'Requests temporarily limited',+ },+ unsupported_attachment: {+ description:+ '{{agent}} could not read an attachment. Remove it or convert it to a supported format, then resend the request.',+ title: 'Attachment unsupported',+ },+ usage_limit: {+ description:+ 'The account used by {{agent}} has exhausted its allowance. Wait for the quota to reset, or ask the bot owner to switch to an account or model with available quota.',+ title: 'Usage limit reached',+ },+ working_directory_not_found: {+ description:+ 'The working directory for {{agent}} is missing. Ask the bot owner to restore it or choose an existing directory.',+ title: 'Working directory unavailable',+ },+};-import chinese from '../../../../../locales/zh-CN/modelRuntime.json';-import type { BotReplyLocale } from './platforms/const';+const RATE_LIMIT_WINDOW_COPY = {+ five_hour: 'Session allowance exhausted.',+ seven_day: 'Weekly allowance exhausted.',+};/** Render only allowlisted context. Raw CLI stderr and paths stay in diagnostics. */export const renderHeterogeneousError = (context: ChatErrorHeterogeneousContext | undefined,- lng?: BotReplyLocale,): string | undefined => {if (!context ||@@ -22,16 +105,12 @@ export const renderHeterogeneousError = ()return;const spec = HETERO_ERROR_SPECS[context.kind as keyof typeof HETERO_ERROR_SPECS];- const catalog: Record<string, string> = lng === 'zh-CN' ? chinese : english;- const prefix = `heterogeneous.${spec.kind}`;+ const copy = COPY[spec.kind];const agent = getHeterogeneousTypeLabel(context.agentType) ?? 'Agent';- const lines = [- `**${agent}: ${catalog[`${prefix}.title`]}**`,- catalog[`${prefix}.description`].replaceAll('{{agent}}', agent),- ];+ const lines = [`**${agent}: ${copy.title}**`, copy.description.replaceAll('{{agent}}', agent)];if (spec.kind === 'usage_limit') {if (context.rateLimitType === 'seven_day' || context.rateLimitType === 'five_hour') {- lines.push(catalog[`heterogeneous.window.${context.rateLimitType}`]);+ lines.push(RATE_LIMIT_WINDOW_COPY[context.rateLimitType]);}if (typeof context.resetsAt === 'number' &&@@ -40,9 +119,9 @@ export const renderHeterogeneousError = (context.resetsAt < 8640000000000) {const time = new Date(context.resetsAt * 1000).toISOString().replace('T', ' ').slice(0, 16);- lines.push(catalog['heterogeneous.reset'].replace('{{time}}', time));+ lines.push(`Quota resets at ${time} (UTC).`);}}- lines.push(`${lng === 'zh-CN' ? '错误码' : 'Error code'}: \`${formatHeteroErrorId(spec.kind)}\``);+ lines.push(`Error code: \`${formatHeteroErrorId(spec.kind)}\``);return lines.join('\n');};diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.tsindex c429e6356cb..ce4391890b1 100644--- a/apps/server/src/services/bot/replyTemplate.ts+++ b/apps/server/src/services/bot/replyTemplate.ts@@ -5,9 +5,6 @@ import {} from '@lobechat/model-runtime/errors';import type { ChatErrorBudgetContext, ChatErrorHeterogeneousContext } from '@lobechat/types';-import modelRuntimeEnglish from '@/locales/default/modelRuntime';--import modelRuntimeChinese from '../../../../../locales/zh-CN/modelRuntime.json';import type { StepPresentationData } from '../agentRuntime/types';import { getExtremeAck } from './ackPhrases';// Import from the leaf modules (`const` / `utils`) instead of the@@ -739,7 +736,7 @@ export function renderAgentError(heterogeneous?: ChatErrorHeterogeneousContext,): string {const strings = getSystemStrings(lng);- const heteroReply = renderHeterogeneousError(heterogeneous, lng);+ const heteroReply = renderHeterogeneousError(heterogeneous);if (heteroReply) return appendOperationId(heteroReply, operationId);const normalized = normalizeChatMessageError({@@ -766,14 +763,6 @@ export function renderAgentError(}const friendlyKey = errorType ? FRIENDLY_ERROR_BY_TYPE[errorType] : undefined;- if (!friendlyKey && spec && !spec.isFallback) {- // Reuse the same maintained translations as message error cards. Never- // interpolate raw provider error text into a shared IM channel.- const catalog: Record<string, string> =- lng === 'zh-CN' ? modelRuntimeChinese : modelRuntimeEnglish;- const copy = catalog[spec.code];- if (copy && !copy.includes('{{')) return withReference(`${strings.error}\n${copy}`);- }const stringKey =(friendlyKey && BUDGET_ADMISSION_KEYS.has(friendlyKey) && budget?.budgetTypeAtError? BUDGET_SCOPE_ERROR.get(budget.budgetTypeAtError)diff --git a/apps/server/src/services/goal/goalBriefs.test.ts b/apps/server/src/services/goal/goalBriefs.test.tsindex 2c2e6e65189..8beedb2797a 100644--- a/apps/server/src/services/goal/goalBriefs.test.ts+++ b/apps/server/src/services/goal/goalBriefs.test.ts@@ -148,7 +148,7 @@ describe('goal decision briefs', () => {});describe('machine gate briefs', () => {- it("says the retry follows a fix, in the reader's words", async () => {+ it('says the retry follows a fix in source English regardless of the response language', async () => {await serverDB.insert(userSettings).values({ general: { responseLanguage: 'zh-CN' }, id: userId })@@ -169,9 +169,10 @@ describe('machine gate briefs', () => {});const [brief] = await goalBriefs();- expect(brief.actions![0]).toMatchObject({ key: 'retry', label: '已修好,重试' });- expect(brief.summary).toContain('工作目录 /tmp/x');- expect(brief.summary).toContain('推荐:已修好,重试');+ expect(brief.actions![0]).toMatchObject({ key: 'retry', label: 'I fixed it — retry' });+ expect(brief.summary).toContain('Working directory does not exist: /tmp/x');+ expect(brief.summary).toContain('Recommended: I fixed it — retry');+ expect(brief.title).toBe('Goal "Machine goal" needs your decision');});});diff --git a/apps/server/src/services/goal/goalBriefs.ts b/apps/server/src/services/goal/goalBriefs.tsindex b0f66490129..f59087f0e1c 100644--- a/apps/server/src/services/goal/goalBriefs.ts+++ b/apps/server/src/services/goal/goalBriefs.ts@@ -1,20 +1,18 @@import { GOAL_BRIEF_TRIGGER, GOAL_CLARIFICATION_OPTION } from '@lobechat/const/goal';import type { BriefAction, BriefGoalMetadata, GoalDecisionOption, GoalItem } from '@lobechat/types';-import { coordinatorGateReason, coordinatorReasonCopies } from '@lobechat/utils/goalCopy';+import { coordinatorGateReason } from '@lobechat/utils/goalCopy';import { and, eq, isNull, sql } from 'drizzle-orm';import { BriefModel } from '@/database/models/brief';import { acceptances, briefs } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';-import { translation } from '@/libs/i18n/serverTranslation';-import { SystemAgentService } from '@/server/services/systemAgent';/** Option ids the coordinator writes; anything else is the main Agent's or the planner's. */-const COORDINATOR_OPTION_KEYS: Record<string, string> = {- fail: 'goalProcess.gate.option.fail',- retire: 'goalProcess.gate.option.retire',- retry: 'goalProcess.gate.option.retry',- [GOAL_CLARIFICATION_OPTION.assume]: 'goalProcess.gate.option.assume',+const COORDINATOR_OPTION_LABELS: Record<string, string> = {+ fail: 'Fail goal',+ retire: 'Retire work',+ retry: 'Retry work',+ [GOAL_CLARIFICATION_OPTION.assume]: 'Go with the assumption',};/** How the coordinator words a machine gate's question (see `openFailureDecisionLocked`). */@@ -81,24 +79,13 @@ export class GoalBriefService {/** A failure gate, or a question the main Agent escalated with its own options. */openDecision = async (goal: GoalItem, input: DecisionInput) =>this.safely('openDecision', async () => {- const { t } = await this.chatCopy();- const { t: tHome } = await this.homeCopy();const reason = coordinatorGateReason(input.question) ?? input.question;- // A batch gate lists every blocker it hit at once, joined by `; `; localize- // each so the brief carries no English into a non-English inbox.- const reasonCopies = coordinatorReasonCopies(reason);- const localizedReason = reasonCopies- ? reasonCopies.map((copy) => t(copy.key, copy.params)).join('; ')- : reason;// The machine gate's retry means "I fixed the setup", not "try again".const machine = MACHINE_GATE_TAIL.test(input.question);- const label = (option: GoalDecisionOption) => {- const key =- machine && option.id === 'retry'- ? 'goalProcess.gate.option.fixedRetry'- : COORDINATOR_OPTION_KEYS[option.id];- return key ? t(key) : option.label;- };+ const label = (option: GoalDecisionOption) =>+ machine && option.id === 'retry'+ ? 'I fixed it — retry'+ : (COORDINATOR_OPTION_LABELS[option.id] ?? option.label);const recommended = input.options?.find((o) => o.id === input.recommendedOptionId);const actions: BriefAction[] = [@@ -110,7 +97,7 @@ export class GoalBriefService {})),{key: 'openGoal',- label: tHome('brief.action.openGoal'),+ label: 'Open goal',type: 'link',url: goalPagePath(goal),},@@ -130,12 +117,8 @@ export class GoalBriefService {...(recommended ? { recommendedAction: recommended.id } : {}),},priority: 'urgent',- summary: clip(- recommended- ? `${localizedReason}\n\n${tHome('brief.goal.recommended', { option: label(recommended) })}`- : localizedReason,- ),- title: tHome('brief.goal.decision.title', { goal: goal.title }),+ summary: clip(recommended ? `${reason}\n\nRecommended: ${label(recommended)}` : reason),+ title: `Goal "${goal.title}" needs your decision`,type: 'decision',});});@@ -146,12 +129,11 @@ export class GoalBriefService {*/openClarification = async (goal: GoalItem, decisionIds: string[], questions: string[]) =>this.safely('openClarification', async () => {- const { t: tHome } = await this.homeCopy();await this.create(goal, {actions: [{key: 'answer',- label: tHome('brief.action.answer'),+ label: 'Answer',type: 'link',url: goalPagePath(goal),},@@ -161,7 +143,7 @@ export class GoalBriefService {metadata: { decisionId: decisionIds[0], kind: 'decision' },priority: 'urgent',summary: clip(questions.map((q, i) => `${i + 1}. ${q}`).join('\n')),- title: tHome('brief.goal.clarify.title', { goal: goal.title }),+ title: `Goal "${goal.title}" has questions before it starts`,type: 'decision',});});@@ -176,7 +158,6 @@ export class GoalBriefService {* the next tick retries.*/openSignOff = async (goal: GoalItem, acceptanceId: string): Promise<void> => {- const { t: tHome } = await this.homeCopy();await this.db.transaction(async (tx) => {const [acceptance] = await tx.select({ status: acceptances.status })@@ -199,15 +180,15 @@ export class GoalBriefService {goal,{actions: [- { key: 'signOff', label: tHome('brief.action.signOff'), type: 'resolve' },+ { key: 'signOff', label: 'Sign off', type: 'resolve' },{key: 'requestChanges',- label: tHome('brief.action.requestChanges'),+ label: 'Request changes',type: 'comment',},{key: 'openGoal',- label: tHome('brief.action.openGoal'),+ label: 'Open goal',type: 'link',url: goalPagePath(goal),},@@ -218,8 +199,9 @@ export class GoalBriefService {signOffAcceptanceId: acceptanceId,},priority: 'normal',- summary: tHome('brief.goal.signOff.summary'),- title: tHome('brief.goal.signOff.title', { goal: goal.title }),+ summary:+ 'Goal-level acceptance passed. Sign it off to close the goal, or request changes to send it back.',+ title: `Goal "${goal.title}" is done. Sign it off`,type: 'decision',},briefModel,@@ -307,19 +289,6 @@ export class GoalBriefService {type: input.type,});- private locale?: Promise<string>;-- private readLocale = () => {- this.locale ??= new SystemAgentService(this.db, this.userId, this.workspaceId)- .getUserLocale()- .catch(() => 'en-US');- return this.locale;- };-- private chatCopy = async () => translation('chat', await this.readLocale());-- private homeCopy = async () => translation('home', await this.readLocale());-private safely = async (label: string, run: () => Promise<void>) => {try {await run();diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.tsindex 23a4eea9a8e..2a452be8880 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts@@ -8,7 +8,6 @@ import { AgentOperationModel } from '@/database/models/agentOperation';import { BriefModel } from '@/database/models/brief';import { readAgentSignalMarker } from '@/server/services/agentSignal/operationMarker';import { createServerSelfReviewBriefWriter } from '@/server/services/agentSignal/services/selfIteration/review/brief';-import { resolveSelfReviewBriefTextTranslator } from '@/server/services/agentSignal/services/selfIteration/review/briefTextTranslator';import { createReviewRuntimePrimitives } from '@/server/services/agentSignal/services/selfIteration/review/server';import { SkillManagementDocumentService } from '@/server/services/skillManagement';@@ -44,7 +43,6 @@ export const agentSignalReviewRuntime: ServerRuntimeRegistration = {const service = createReviewRuntimePrimitives({agentId,briefModel: new BriefModel(serverDB, userId, workspaceId),- briefTextTranslator: await resolveSelfReviewBriefTextTranslator(serverDB, userId),db: serverDB,localDate,proposalBriefWriter: createServerSelfReviewBriefWriter(serverDB, userId, workspaceId),diff --git a/eslint.config.mjs b/eslint.config.mjsindex fe4458f0228..a683cff234d 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -157,6 +157,29 @@ const redisAccessRestrictedSyntax = [selector: 'ImportExpression > Literal[value=/^@\\/server\\/modules\\/Redis(?:\\/|$)/]',},];+// Server output is source English. Translation catalogs and runtimes stay with the clients.+const serverI18nMessage =+ 'Server code renders source English and must not load translation catalogs or i18n runtimes.';+const serverI18nRestrictedImportPaths = [+ { message: serverI18nMessage, name: 'i18next' },+ { message: serverI18nMessage, name: 'react-i18next' },+];+const serverI18nRestrictedImportPatterns = [+ {+ group: [+ '@/locales/*',+ '!@/locales/resources',+ '@lobechat/locales',+ '@lobechat/locales/*',+ '!@lobechat/locales/resources',+ '@/libs/i18n',+ '@/libs/i18n/*',+ '**/locales/*/*.json',+ ],+ message: serverI18nMessage,+ },+];+const legacyRawRedisClientConsumers = ['apps/server/src/services/home/index.ts','apps/server/src/services/agent/index.ts',@@ -667,6 +690,22 @@ export default eslint(],},},+ {+ files: ['apps/server/src/**/*.{ts,tsx}'],+ rules: {+ 'no-restricted-imports': [+ 'error',+ {+ ...baseRestrictedImportOptions,+ paths: [...(baseRestrictedImportOptions.paths ?? []), ...serverI18nRestrictedImportPaths],+ patterns: [+ ...(baseRestrictedImportOptions.patterns ?? []),+ ...serverI18nRestrictedImportPatterns,+ ],+ },+ ],+ },+ },{// Redis access boundary for server code (see `redisAccessRestrictedImportPaths`).files: ['apps/server/src/**/*.{ts,tsx}'],@@ -686,10 +725,12 @@ export default eslint(...baseRestrictedImportOptions,paths: [...(baseRestrictedImportOptions.paths ?? []),+ ...serverI18nRestrictedImportPaths,...redisAccessRestrictedImportPaths,],patterns: [...(baseRestrictedImportOptions.patterns ?? []),+ ...serverI18nRestrictedImportPatterns,{group: ['@/server/modules/Redis/*'],message: 'Use domain methods in services/redis.',diff --git a/locales/ar/modelRuntime.json b/locales/ar/modelRuntime.jsonindex fcd8bb7587a..d6057579738 100644--- a/locales/ar/modelRuntime.json+++ b/locales/ar/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "عاد البوابة أو الوكيل المصدر بخطأ. يرجى إعادة المحاولة قريبًا؛ إذا استمرت المشكلة، تحقق من إعدادات الوكيل / نقطة النهاية.","UpstreamHttpError": "عاد المزود بخطأ HTTP دون تفاصيل إضافية. يرجى إعادة المحاولة، أو التحقق من الطلب وإعدادات النموذج.","UpstreamMalformedResponse": "عاد المزود باستجابة غير صالحة لا يمكن تحليلها. يرجى إعادة المحاولة؛ إذا استمرت المشكلة، جرب نموذجًا أو مزودًا مختلفًا.",- "UserConfigError": "إعدادات المزود غير صالحة (عنوان URL الأساسي غير صحيح، متغير بيئة مفقود، قيود المفتاح الافتراضي، إلخ). يرجى مراجعة إعدادات المزود.",- "heterogeneous.aborted.description": "تم إيقاف مهمة {{agent}}. أرسل طلبًا جديدًا عندما تريد المتابعة.",- "heterogeneous.aborted.title": "تم إيقاف المهمة",- "heterogeneous.agent_failed.description": "توقف {{agent}} دون سبب معروف. شارك معرف العملية مع مالك الروبوت أو الدعم للتحقيق.",- "heterogeneous.agent_failed.title": "فشل مهمة الوكيل",- "heterogeneous.auth_required.description": "اطلب من مالك الروبوت تسجيل الدخول مرة أخرى على الجهاز الذي يشغل {{agent}}.",- "heterogeneous.auth_required.title": "مطلوب تسجيل الدخول",- "heterogeneous.cli_not_found.description": "اطلب من مالك الروبوت تثبيت أو إصلاح {{agent}} على الجهاز الذي يشغل هذه المهمة.",- "heterogeneous.cli_not_found.title": "واجهة CLI للوكيل غير متاحة",- "heterogeneous.credit_limit.description": "اطلب من مالك الروبوت إضافة أرصدة إلى الحساب المستخدم بواسطة {{agent}}، أو تبديل النماذج. الانتظار لإعادة تعيين الحصة لن يعيد هذه الأرصدة.",- "heterogeneous.credit_limit.title": "نفدت الأرصدة",- "heterogeneous.invalid_request.description": "رفض المزود الطلب المرسل بواسطة {{agent}}. جرب موضوعًا جديدًا؛ إذا استمر، شارك معرف العملية مع الدعم.",- "heterogeneous.invalid_request.title": "تم رفض الطلب",- "heterogeneous.max_turns.description": "وصل {{agent}} إلى حد الخطوات قبل الانتهاء. قسّم المهمة إلى خطوات أصغر، أو اطلب من مالك الروبوت تعديل الحد.",- "heterogeneous.max_turns.title": "تم الوصول إلى حد الخطوات",- "heterogeneous.model_unavailable.description": "النموذج المحدد لـ {{agent}} غير متاح. اطلب من مالك الروبوت اختيار نموذج آخر.",- "heterogeneous.model_unavailable.title": "النموذج غير متاح",- "heterogeneous.network_drop.description": "فقد {{agent}} الاتصال قبل الانتهاء. حاول مرة أخرى؛ إذا حدث ذلك مرة أخرى، اطلب من مالك الروبوت التحقق من إعدادات الشبكة والوكيل للجهاز الذي يعمل عليه.",- "heterogeneous.network_drop.title": "تم قطع الاتصال",- "heterogeneous.reset": "إعادة تعيين الحصة في {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "اطلب من مالك الروبوت استعادة دليل العمل المستخدم في جلسة {{agent}} هذه، أو ابدأ موضوعًا جديدًا.",- "heterogeneous.resume_cwd_mismatch.title": "تم تغيير دليل الجلسة",- "heterogeneous.resume_thread_not_found.description": "لم يتمكن {{agent}} من العثور على الجلسة السابقة. ابدأ موضوعًا جديدًا وأعد إرسال الطلب.",- "heterogeneous.resume_thread_not_found.title": "الجلسة السابقة غير متاحة",- "heterogeneous.server_overloaded.description": "المزود خلف {{agent}} مشغول أو غير متاح. يرجى المحاولة مرة أخرى قريبًا.",- "heterogeneous.server_overloaded.title": "المزود غير متاح مؤقتًا",- "heterogeneous.server_throttle.description": "يقوم المزود حاليًا بتقييد الطلبات من {{agent}}. يرجى الانتظار قليلاً ثم حاول مرة أخرى.",- "heterogeneous.server_throttle.title": "تم تقييد الطلبات مؤقتًا",- "heterogeneous.unsupported_attachment.description": "لم يتمكن {{agent}} من قراءة المرفق. قم بإزالته أو تحويله إلى تنسيق مدعوم، ثم أعد إرسال الطلب.",- "heterogeneous.unsupported_attachment.title": "المرفق غير مدعوم",- "heterogeneous.usage_limit.description": "الحساب المستخدم بواسطة {{agent}} استنفد مخصصاته. انتظر حتى يتم إعادة تعيين الحصة، أو اطلب من مالك الروبوت التبديل إلى حساب أو نموذج يحتوي على حصة متاحة.",- "heterogeneous.usage_limit.title": "تم الوصول إلى حد الاستخدام",- "heterogeneous.window.five_hour": "تم استنفاد مخصصات الجلسة.",- "heterogeneous.window.seven_day": "تم استنفاد المخصص الأسبوعي.",- "heterogeneous.working_directory_not_found.description": "دليل العمل لـ {{agent}} مفقود. اطلب من مالك الروبوت استعادته أو اختيار دليل موجود.",- "heterogeneous.working_directory_not_found.title": "دليل العمل غير متاح"+ "UserConfigError": "إعدادات المزود غير صالحة (عنوان URL الأساسي غير صحيح، متغير بيئة مفقود، قيود المفتاح الافتراضي، إلخ). يرجى مراجعة إعدادات المزود."}diff --git a/locales/bg-BG/modelRuntime.json b/locales/bg-BG/modelRuntime.jsonindex df39004a407..42c1beb6b94 100644--- a/locales/bg-BG/modelRuntime.json+++ b/locales/bg-BG/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "Горният шлюз или прокси върна грешка. Моля, опитайте отново след малко; ако проблемът продължи, проверете конфигурацията на вашето прокси/крайна точка.","UpstreamHttpError": "Доставчикът върна HTTP грешка без допълнителни подробности. Моля, опитайте отново или проверете вашата заявка и конфигурацията на модела.","UpstreamMalformedResponse": "Доставчикът върна неправилно форматиран отговор, който не може да бъде анализиран. Моля, опитайте отново; ако проблемът продължи, опитайте с друг модел или доставчик.",- "UserConfigError": "Конфигурацията на доставчика е невалидна (неправилен основен URL адрес, липсваща променлива на средата, ограничение на виртуален ключ и др.). Моля, прегледайте настройките на доставчика.",- "heterogeneous.aborted.description": "Тази задача на {{agent}} беше спряна. Изпратете нова заявка, когато искате да продължите.",- "heterogeneous.aborted.title": "Задачата е спряна",- "heterogeneous.agent_failed.description": "{{agent}} спря без разпозната причина. Споделете идентификатора на операцията със собственика на бота или поддръжката за разследване.",- "heterogeneous.agent_failed.title": "Задачата на агента не успя",- "heterogeneous.auth_required.description": "Помолете собственика на бота да влезе отново в устройството, на което работи {{agent}}.",- "heterogeneous.auth_required.title": "Необходим е вход",- "heterogeneous.cli_not_found.description": "Помолете собственика на бота да инсталира или поправи {{agent}} на устройството, на което се изпълнява тази задача.",- "heterogeneous.cli_not_found.title": "CLI на агента не е наличен",- "heterogeneous.credit_limit.description": "Помолете собственика на бота да добави кредити към акаунта, използван от {{agent}}, или да смени модела. Изчакването за нулиране на квотата няма да възстанови тези кредити.",- "heterogeneous.credit_limit.title": "Кредитите са изчерпани",- "heterogeneous.invalid_request.description": "Доставчикът отхвърли заявката, изпратена от {{agent}}. Опитайте нова тема; ако проблемът продължава, споделете идентификатора на операцията с поддръжката.",- "heterogeneous.invalid_request.title": "Заявката е отхвърлена",- "heterogeneous.max_turns.description": "{{agent}} достигна лимита си за стъпки преди да завърши. Разделете задачата на по-малки стъпки или помолете собственика на бота да коригира лимита.",- "heterogeneous.max_turns.title": "Достигнат е лимитът за стъпки",- "heterogeneous.model_unavailable.description": "Избраният модел за {{agent}} не е наличен. Помолете собственика на бота да избере друг модел.",- "heterogeneous.model_unavailable.title": "Моделът не е наличен",- "heterogeneous.network_drop.description": "{{agent}} загуби връзката си преди да завърши. Опитайте отново; ако се случи отново, помолете собственика на бота да провери мрежовите и прокси настройките на работещото устройство.",- "heterogeneous.network_drop.title": "Връзката е прекъсната",- "heterogeneous.reset": "Квотата се нулира в {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Помолете собственика на бота да възстанови работната директория, използвана от тази сесия на {{agent}}, или започнете нова тема.",- "heterogeneous.resume_cwd_mismatch.title": "Работната директория е променена",- "heterogeneous.resume_thread_not_found.description": "{{agent}} не можа да намери предишната сесия. Започнете нова тема и изпратете заявката отново.",- "heterogeneous.resume_thread_not_found.title": "Предишната сесия не е налична",- "heterogeneous.server_overloaded.description": "Доставчикът зад {{agent}} е зает или недостъпен. Моля, опитайте отново след малко.",- "heterogeneous.server_overloaded.title": "Доставчикът временно не е наличен",- "heterogeneous.server_throttle.description": "Доставчикът временно ограничава заявките от {{agent}}. Моля, изчакайте малко и опитайте отново.",- "heterogeneous.server_throttle.title": "Заявките временно са ограничени",- "heterogeneous.unsupported_attachment.description": "{{agent}} не можа да прочете прикачен файл. Премахнете го или го конвертирайте в поддържан формат, след което изпратете заявката отново.",- "heterogeneous.unsupported_attachment.title": "Прикаченият файл не се поддържа",- "heterogeneous.usage_limit.description": "Акаунтът, използван от {{agent}}, е изчерпал своята квота. Изчакайте квотата да се нулира или помолете собственика на бота да премине към акаунт или модел с налична квота.",- "heterogeneous.usage_limit.title": "Достигнат е лимитът за използване",- "heterogeneous.window.five_hour": "Изчерпан е лимитът за сесия.",- "heterogeneous.window.seven_day": "Изчерпан е седмичният лимит.",- "heterogeneous.working_directory_not_found.description": "Работната директория за {{agent}} липсва. Помолете собственика на бота да я възстанови или да избере съществуваща директория.",- "heterogeneous.working_directory_not_found.title": "Работната директория не е налична"+ "UserConfigError": "Конфигурацията на доставчика е невалидна (неправилен основен URL адрес, липсваща променлива на средата, ограничение на виртуален ключ и др.). Моля, прегледайте настройките на доставчика."}diff --git a/locales/de-DE/modelRuntime.json b/locales/de-DE/modelRuntime.jsonindex dd7fb7fb43d..a75c1860cc1 100644--- a/locales/de-DE/modelRuntime.json+++ b/locales/de-DE/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "Das Upstream-Gateway oder der Proxy hat einen Fehler zurückgegeben. Bitte versuchen Sie es in Kürze erneut; falls das Problem weiterhin besteht, überprüfen Sie Ihre Proxy-/Endpunktkonfiguration.","UpstreamHttpError": "Der Anbieter hat einen HTTP-Fehler ohne weitere Details zurückgegeben. Bitte versuchen Sie es erneut oder überprüfen Sie Ihre Anfrage- und Modellkonfiguration.","UpstreamMalformedResponse": "Der Anbieter hat eine fehlerhafte Antwort zurückgegeben, die nicht analysiert werden konnte. Bitte versuchen Sie es erneut; falls das Problem weiterhin besteht, versuchen Sie ein anderes Modell oder einen anderen Anbieter.",- "UserConfigError": "Die Anbieter-Konfiguration ist ungültig (falsche Basis-URL, fehlende Umgebungsvariable, virtuelle Schlüsselbeschränkung usw.). Bitte überprüfen Sie die Anbietereinstellungen.",- "heterogeneous.aborted.description": "Diese {{agent}}-Aufgabe wurde gestoppt. Senden Sie eine neue Anfrage, wenn Sie fortfahren möchten.",- "heterogeneous.aborted.title": "Aufgabe gestoppt",- "heterogeneous.agent_failed.description": "{{agent}} wurde ohne erkennbaren Grund gestoppt. Teilen Sie die Vorgangs-ID mit dem Bot-Besitzer oder dem Support, um dies zu untersuchen.",- "heterogeneous.agent_failed.title": "Agentenaufgabe fehlgeschlagen",- "heterogeneous.auth_required.description": "Bitten Sie den Bot-Besitzer, sich erneut auf dem Gerät anzumelden, auf dem {{agent}} ausgeführt wird.",- "heterogeneous.auth_required.title": "Anmeldung erforderlich",- "heterogeneous.cli_not_found.description": "Bitten Sie den Bot-Besitzer, {{agent}} auf dem Gerät zu installieren oder zu reparieren, auf dem diese Aufgabe ausgeführt wird.",- "heterogeneous.cli_not_found.title": "Agent CLI nicht verfügbar",- "heterogeneous.credit_limit.description": "Bitten Sie den Bot-Besitzer, dem Konto, das von {{agent}} verwendet wird, Guthaben hinzuzufügen, oder wechseln Sie das Modell. Das Warten auf ein Quoten-Reset wird dieses Guthaben nicht wiederherstellen.",- "heterogeneous.credit_limit.title": "Guthaben erschöpft",- "heterogeneous.invalid_request.description": "Der Anbieter hat die von {{agent}} gesendete Anfrage abgelehnt. Versuchen Sie ein neues Thema; wenn das Problem weiterhin besteht, teilen Sie die Vorgangs-ID dem Support mit.",- "heterogeneous.invalid_request.title": "Anfrage abgelehnt",- "heterogeneous.max_turns.description": "{{agent}} hat sein Schritt-Limit erreicht, bevor die Aufgabe abgeschlossen wurde. Teilen Sie die Aufgabe in kleinere Schritte auf oder bitten Sie den Bot-Besitzer, das Limit anzupassen.",- "heterogeneous.max_turns.title": "Schritt-Limit erreicht",- "heterogeneous.model_unavailable.description": "Das für {{agent}} ausgewählte Modell ist nicht verfügbar. Bitten Sie den Bot-Besitzer, ein anderes Modell auszuwählen.",- "heterogeneous.model_unavailable.title": "Modell nicht verfügbar",- "heterogeneous.network_drop.description": "{{agent}} hat die Verbindung verloren, bevor die Aufgabe abgeschlossen wurde. Versuchen Sie es erneut; wenn das Problem weiterhin besteht, bitten Sie den Bot-Besitzer, die Netzwerk- und Proxy-Einstellungen des laufenden Geräts zu überprüfen.",- "heterogeneous.network_drop.title": "Verbindung unterbrochen",- "heterogeneous.reset": "Die Quote wird um {{time}} (UTC) zurückgesetzt.",- "heterogeneous.resume_cwd_mismatch.description": "Bitten Sie den Bot-Besitzer, das Arbeitsverzeichnis wiederherzustellen, das von dieser {{agent}}-Sitzung verwendet wurde, oder starten Sie ein neues Thema.",- "heterogeneous.resume_cwd_mismatch.title": "Sitzungsverzeichnis geändert",- "heterogeneous.resume_thread_not_found.description": "{{agent}} konnte die vorherige Sitzung nicht finden. Starten Sie ein neues Thema und senden Sie die Anfrage erneut.",- "heterogeneous.resume_thread_not_found.title": "Vorherige Sitzung nicht verfügbar",- "heterogeneous.server_overloaded.description": "Der Anbieter hinter {{agent}} ist ausgelastet oder nicht verfügbar. Bitte versuchen Sie es in Kürze erneut.",- "heterogeneous.server_overloaded.title": "Anbieter vorübergehend nicht verfügbar",- "heterogeneous.server_throttle.description": "Der Anbieter begrenzt vorübergehend die Anfragen von {{agent}}. Bitte warten Sie einen Moment und versuchen Sie es erneut.",- "heterogeneous.server_throttle.title": "Anfragen vorübergehend begrenzt",- "heterogeneous.unsupported_attachment.description": "{{agent}} konnte einen Anhang nicht lesen. Entfernen Sie ihn oder konvertieren Sie ihn in ein unterstütztes Format und senden Sie die Anfrage erneut.",- "heterogeneous.unsupported_attachment.title": "Anhang nicht unterstützt",- "heterogeneous.usage_limit.description": "Das Konto, das von {{agent}} verwendet wird, hat sein Kontingent ausgeschöpft. Warten Sie, bis die Quote zurückgesetzt wird, oder bitten Sie den Bot-Besitzer, zu einem Konto oder Modell mit verfügbarem Kontingent zu wechseln.",- "heterogeneous.usage_limit.title": "Nutzungslimit erreicht",- "heterogeneous.window.five_hour": "Sitzungskontingent erschöpft.",- "heterogeneous.window.seven_day": "Wöchentliches Kontingent erschöpft.",- "heterogeneous.working_directory_not_found.description": "Das Arbeitsverzeichnis für {{agent}} fehlt. Bitten Sie den Bot-Besitzer, es wiederherzustellen oder ein vorhandenes Verzeichnis auszuwählen.",- "heterogeneous.working_directory_not_found.title": "Arbeitsverzeichnis nicht verfügbar"+ "UserConfigError": "Die Anbieter-Konfiguration ist ungültig (falsche Basis-URL, fehlende Umgebungsvariable, virtuelle Schlüsselbeschränkung usw.). Bitte überprüfen Sie die Anbietereinstellungen."}diff --git a/locales/en-US/modelRuntime.json b/locales/en-US/modelRuntime.jsonindex 22500ac833a..9ea6686ca87 100644--- a/locales/en-US/modelRuntime.json+++ b/locales/en-US/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "The upstream gateway or proxy returned an error. Please try again shortly; if it persists, check your proxy / endpoint configuration.","UpstreamHttpError": "The provider returned an HTTP error without further detail. Please try again, or check your request and model configuration.","UpstreamMalformedResponse": "The provider returned a malformed response that could not be parsed. Please retry; if it persists, try a different model or provider.",- "UserConfigError": "Provider configuration is invalid (incorrect base URL, missing environment variable, virtual-key restriction, etc.). Please review the provider settings.",- "heterogeneous.aborted.description": "This {{agent}} task was stopped. Send a new request when you want to continue.",- "heterogeneous.aborted.title": "Task stopped",- "heterogeneous.agent_failed.description": "{{agent}} stopped without a recognized cause. Share the Operation ID with the bot owner or support to investigate.",- "heterogeneous.agent_failed.title": "Agent task failed",- "heterogeneous.auth_required.description": "Ask the bot owner to sign in again on the device running {{agent}}.",- "heterogeneous.auth_required.title": "Sign-in required",- "heterogeneous.cli_not_found.description": "Ask the bot owner to install or repair {{agent}} on the device running this task.",- "heterogeneous.cli_not_found.title": "Agent CLI unavailable",- "heterogeneous.credit_limit.description": "Ask the bot owner to add credits to the account used by {{agent}}, or switch models. Waiting for a quota reset will not restore these credits.",- "heterogeneous.credit_limit.title": "Credits exhausted",- "heterogeneous.invalid_request.description": "The provider rejected the request sent by {{agent}}. Try a new topic; if it persists, share the Operation ID with support.",- "heterogeneous.invalid_request.title": "Request rejected",- "heterogeneous.max_turns.description": "{{agent}} reached its step limit before finishing. Split the task into smaller steps, or ask the bot owner to adjust the limit.",- "heterogeneous.max_turns.title": "Step limit reached",- "heterogeneous.model_unavailable.description": "The model selected for {{agent}} is unavailable. Ask the bot owner to choose another model.",- "heterogeneous.model_unavailable.title": "Model unavailable",- "heterogeneous.network_drop.description": "{{agent}} lost its connection before finishing. Retry; if it happens again, ask the bot owner to check the running device’s network and proxy settings.",- "heterogeneous.network_drop.title": "Connection interrupted",- "heterogeneous.reset": "Quota resets at {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Ask the bot owner to restore the working directory used by this {{agent}} session, or start a new topic.",- "heterogeneous.resume_cwd_mismatch.title": "Session directory changed",- "heterogeneous.resume_thread_not_found.description": "{{agent}} could not find the previous session. Start a new topic and resend the request.",- "heterogeneous.resume_thread_not_found.title": "Previous session unavailable",- "heterogeneous.server_overloaded.description": "The provider behind {{agent}} is busy or unavailable. Please try again shortly.",- "heterogeneous.server_overloaded.title": "Provider temporarily unavailable",- "heterogeneous.server_throttle.description": "The provider is temporarily limiting requests from {{agent}}. Please wait a moment and try again.",- "heterogeneous.server_throttle.title": "Requests temporarily limited",- "heterogeneous.unsupported_attachment.description": "{{agent}} could not read an attachment. Remove it or convert it to a supported format, then resend the request.",- "heterogeneous.unsupported_attachment.title": "Attachment unsupported",- "heterogeneous.usage_limit.description": "The account used by {{agent}} has exhausted its allowance. Wait for the quota to reset, or ask the bot owner to switch to an account or model with available quota.",- "heterogeneous.usage_limit.title": "Usage limit reached",- "heterogeneous.window.five_hour": "Session allowance exhausted.",- "heterogeneous.window.seven_day": "Weekly allowance exhausted.",- "heterogeneous.working_directory_not_found.description": "The working directory for {{agent}} is missing. Ask the bot owner to restore it or choose an existing directory.",- "heterogeneous.working_directory_not_found.title": "Working directory unavailable"+ "UserConfigError": "Provider configuration is invalid (incorrect base URL, missing environment variable, virtual-key restriction, etc.). Please review the provider settings."}diff --git a/locales/es-ES/modelRuntime.json b/locales/es-ES/modelRuntime.jsonindex cad0a28d88d..de50e2722f6 100644--- a/locales/es-ES/modelRuntime.json+++ b/locales/es-ES/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "El gateway o proxy del proveedor devolvió un error. Por favor, vuelve a intentarlo en breve; si el problema persiste, verifica tu configuración de proxy/punto final.","UpstreamHttpError": "El proveedor devolvió un error HTTP sin más detalles. Por favor, vuelve a intentarlo, o verifica tu solicitud y configuración del modelo.","UpstreamMalformedResponse": "El proveedor devolvió una respuesta mal formada que no pudo ser analizada. Por favor, vuelve a intentarlo; si el problema persiste, intenta con un modelo o proveedor diferente.",- "UserConfigError": "La configuración del proveedor es inválida (URL base incorrecta, variable de entorno faltante, restricción de clave virtual, etc.). Por favor, revisa la configuración del proveedor.",- "heterogeneous.aborted.description": "Esta tarea de {{agent}} fue detenida. Envía una nueva solicitud cuando quieras continuar.",- "heterogeneous.aborted.title": "Tarea detenida",- "heterogeneous.agent_failed.description": "{{agent}} se detuvo sin una causa reconocida. Comparte el ID de Operación con el propietario del bot o soporte para investigar.",- "heterogeneous.agent_failed.title": "Fallo en la tarea del agente",- "heterogeneous.auth_required.description": "Pide al propietario del bot que inicie sesión nuevamente en el dispositivo que ejecuta {{agent}}.",- "heterogeneous.auth_required.title": "Inicio de sesión requerido",- "heterogeneous.cli_not_found.description": "Pide al propietario del bot que instale o repare {{agent}} en el dispositivo que ejecuta esta tarea.",- "heterogeneous.cli_not_found.title": "CLI del agente no disponible",- "heterogeneous.credit_limit.description": "Pide al propietario del bot que agregue créditos a la cuenta utilizada por {{agent}} o cambie de modelo. Esperar un reinicio de cuota no restaurará estos créditos.",- "heterogeneous.credit_limit.title": "Créditos agotados",- "heterogeneous.invalid_request.description": "El proveedor rechazó la solicitud enviada por {{agent}}. Intenta un nuevo tema; si persiste, comparte el ID de Operación con soporte.",- "heterogeneous.invalid_request.title": "Solicitud rechazada",- "heterogeneous.max_turns.description": "{{agent}} alcanzó su límite de pasos antes de finalizar. Divide la tarea en pasos más pequeños o pide al propietario del bot que ajuste el límite.",- "heterogeneous.max_turns.title": "Límite de pasos alcanzado",- "heterogeneous.model_unavailable.description": "El modelo seleccionado para {{agent}} no está disponible. Pide al propietario del bot que elija otro modelo.",- "heterogeneous.model_unavailable.title": "Modelo no disponible",- "heterogeneous.network_drop.description": "{{agent}} perdió su conexión antes de finalizar. Intenta nuevamente; si vuelve a ocurrir, pide al propietario del bot que revise la red y la configuración del proxy del dispositivo en ejecución.",- "heterogeneous.network_drop.title": "Conexión interrumpida",- "heterogeneous.reset": "La cuota se restablece a las {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Pide al propietario del bot que restaure el directorio de trabajo utilizado por esta sesión de {{agent}} o inicia un nuevo tema.",- "heterogeneous.resume_cwd_mismatch.title": "Directorio de sesión cambiado",- "heterogeneous.resume_thread_not_found.description": "{{agent}} no pudo encontrar la sesión anterior. Inicia un nuevo tema y vuelve a enviar la solicitud.",- "heterogeneous.resume_thread_not_found.title": "Sesión anterior no disponible",- "heterogeneous.server_overloaded.description": "El proveedor detrás de {{agent}} está ocupado o no disponible. Por favor, inténtalo nuevamente en breve.",- "heterogeneous.server_overloaded.title": "Proveedor temporalmente no disponible",- "heterogeneous.server_throttle.description": "El proveedor está limitando temporalmente las solicitudes de {{agent}}. Por favor, espera un momento e inténtalo nuevamente.",- "heterogeneous.server_throttle.title": "Solicitudes temporalmente limitadas",- "heterogeneous.unsupported_attachment.description": "{{agent}} no pudo leer un archivo adjunto. Elimínalo o conviértelo a un formato compatible, luego vuelve a enviar la solicitud.",- "heterogeneous.unsupported_attachment.title": "Archivo adjunto no compatible",- "heterogeneous.usage_limit.description": "La cuenta utilizada por {{agent}} ha agotado su asignación. Espera a que se restablezca la cuota o pide al propietario del bot que cambie a una cuenta o modelo con cuota disponible.",- "heterogeneous.usage_limit.title": "Límite de uso alcanzado",- "heterogeneous.window.five_hour": "Asignación de sesión agotada.",- "heterogeneous.window.seven_day": "Asignación semanal agotada.",- "heterogeneous.working_directory_not_found.description": "El directorio de trabajo para {{agent}} no se encuentra. Pide al propietario del bot que lo restaure o elija un directorio existente.",- "heterogeneous.working_directory_not_found.title": "Directorio de trabajo no disponible"+ "UserConfigError": "La configuración del proveedor es inválida (URL base incorrecta, variable de entorno faltante, restricción de clave virtual, etc.). Por favor, revisa la configuración del proveedor."}diff --git a/locales/fa-IR/modelRuntime.json b/locales/fa-IR/modelRuntime.jsonindex 3a00daf9405..e5b52e09e6b 100644--- a/locales/fa-IR/modelRuntime.json+++ b/locales/fa-IR/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "دروازه یا پراکسی بالادستی خطایی بازگرداند. لطفاً به زودی دوباره تلاش کنید؛ اگر مشکل ادامه داشت، پیکربندی پراکسی/نقطه پایانی خود را بررسی کنید.","UpstreamHttpError": "ارائهدهنده یک خطای HTTP بدون جزئیات بیشتر بازگرداند. لطفاً دوباره تلاش کنید یا درخواست و پیکربندی مدل خود را بررسی کنید.","UpstreamMalformedResponse": "ارائهدهنده یک پاسخ نامعتبر بازگرداند که قابل تجزیه نبود. لطفاً دوباره تلاش کنید؛ اگر مشکل ادامه داشت، از مدل یا ارائهدهنده دیگری استفاده کنید.",- "UserConfigError": "پیکربندی ارائهدهنده نامعتبر است (URL پایه نادرست، متغیر محیطی گمشده، محدودیت کلید مجازی و غیره). لطفاً تنظیمات ارائهدهنده را بررسی کنید.",- "heterogeneous.aborted.description": "این وظیفه {{agent}} متوقف شد. یک درخواست جدید ارسال کنید وقتی که میخواهید ادامه دهید.",- "heterogeneous.aborted.title": "وظیفه متوقف شد",- "heterogeneous.agent_failed.description": "{{agent}} بدون علت شناخته شدهای متوقف شد. شناسه عملیات را با مالک ربات یا پشتیبانی به اشتراک بگذارید تا بررسی شود.",- "heterogeneous.agent_failed.title": "وظیفه عامل ناموفق بود",- "heterogeneous.auth_required.description": "از مالک ربات بخواهید دوباره در دستگاهی که {{agent}} را اجرا میکند وارد شود.",- "heterogeneous.auth_required.title": "ورود مجدد لازم است",- "heterogeneous.cli_not_found.description": "از مالک ربات بخواهید {{agent}} را در دستگاهی که این وظیفه را اجرا میکند نصب یا تعمیر کند.",- "heterogeneous.cli_not_found.title": "CLI عامل در دسترس نیست",- "heterogeneous.credit_limit.description": "از مالک ربات بخواهید به حسابی که توسط {{agent}} استفاده میشود اعتبار اضافه کند، یا مدل را تغییر دهد. انتظار برای بازنشانی سهمیه این اعتبار را بازنمیگرداند.",- "heterogeneous.credit_limit.title": "اعتبارات تمام شده",- "heterogeneous.invalid_request.description": "ارائهدهنده درخواست ارسال شده توسط {{agent}} را رد کرد. یک موضوع جدید را امتحان کنید؛ اگر ادامه داشت، شناسه عملیات را با پشتیبانی به اشتراک بگذارید.",- "heterogeneous.invalid_request.title": "درخواست رد شد",- "heterogeneous.max_turns.description": "{{agent}} قبل از اتمام به حد مجاز مراحل رسید. وظیفه را به مراحل کوچکتر تقسیم کنید یا از مالک ربات بخواهید حد مجاز را تنظیم کند.",- "heterogeneous.max_turns.title": "حد مجاز مراحل رسید",- "heterogeneous.model_unavailable.description": "مدل انتخاب شده برای {{agent}} در دسترس نیست. از مالک ربات بخواهید مدل دیگری را انتخاب کند.",- "heterogeneous.model_unavailable.title": "مدل در دسترس نیست",- "heterogeneous.network_drop.description": "{{agent}} قبل از اتمام اتصال خود را از دست داد. دوباره تلاش کنید؛ اگر دوباره اتفاق افتاد، از مالک ربات بخواهید تنظیمات شبکه و پروکسی دستگاه در حال اجرا را بررسی کند.",- "heterogeneous.network_drop.title": "اتصال قطع شد",- "heterogeneous.reset": "سهمیه در {{time}} (UTC) بازنشانی میشود.",- "heterogeneous.resume_cwd_mismatch.description": "از مالک ربات بخواهید دایرکتوری کاری استفاده شده توسط این جلسه {{agent}} را بازیابی کند، یا یک موضوع جدید شروع کنید.",- "heterogeneous.resume_cwd_mismatch.title": "دایرکتوری جلسه تغییر کرد",- "heterogeneous.resume_thread_not_found.description": "{{agent}} نتوانست جلسه قبلی را پیدا کند. یک موضوع جدید شروع کنید و درخواست را دوباره ارسال کنید.",- "heterogeneous.resume_thread_not_found.title": "جلسه قبلی در دسترس نیست",- "heterogeneous.server_overloaded.description": "ارائهدهنده پشت {{agent}} مشغول یا در دسترس نیست. لطفاً به زودی دوباره تلاش کنید.",- "heterogeneous.server_overloaded.title": "ارائهدهنده موقتاً در دسترس نیست",- "heterogeneous.server_throttle.description": "ارائهدهنده موقتاً درخواستها از {{agent}} را محدود کرده است. لطفاً لحظهای صبر کنید و دوباره تلاش کنید.",- "heterogeneous.server_throttle.title": "درخواستها موقتاً محدود شدهاند",- "heterogeneous.unsupported_attachment.description": "{{agent}} نتوانست یک پیوست را بخواند. آن را حذف کنید یا به یک فرمت پشتیبانی شده تبدیل کنید، سپس درخواست را دوباره ارسال کنید.",- "heterogeneous.unsupported_attachment.title": "پیوست پشتیبانی نمیشود",- "heterogeneous.usage_limit.description": "حساب استفاده شده توسط {{agent}} سهمیه خود را تمام کرده است. منتظر بازنشانی سهمیه بمانید، یا از مالک ربات بخواهید به یک حساب یا مدل با سهمیه موجود تغییر کند.",- "heterogeneous.usage_limit.title": "حد استفاده رسید",- "heterogeneous.window.five_hour": "سهمیه جلسه تمام شد.",- "heterogeneous.window.seven_day": "سهمیه هفتگی تمام شد.",- "heterogeneous.working_directory_not_found.description": "دایرکتوری کاری برای {{agent}} گم شده است. از مالک ربات بخواهید آن را بازیابی کند یا یک دایرکتوری موجود را انتخاب کند.",- "heterogeneous.working_directory_not_found.title": "دایرکتوری کاری در دسترس نیست"+ "UserConfigError": "پیکربندی ارائهدهنده نامعتبر است (URL پایه نادرست، متغیر محیطی گمشده، محدودیت کلید مجازی و غیره). لطفاً تنظیمات ارائهدهنده را بررسی کنید."}diff --git a/locales/fr-FR/modelRuntime.json b/locales/fr-FR/modelRuntime.jsonindex 0265b8efaab..9026c63b220 100644--- a/locales/fr-FR/modelRuntime.json+++ b/locales/fr-FR/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "La passerelle ou le proxy en amont a renvoyé une erreur. Veuillez réessayer sous peu ; si le problème persiste, vérifiez la configuration de votre proxy / point de terminaison.","UpstreamHttpError": "Le fournisseur a renvoyé une erreur HTTP sans plus de détails. Veuillez réessayer ou vérifier votre requête et la configuration du modèle.","UpstreamMalformedResponse": "Le fournisseur a renvoyé une réponse mal formée qui n'a pas pu être analysée. Veuillez réessayer ; si le problème persiste, essayez un autre modèle ou fournisseur.",- "UserConfigError": "La configuration du fournisseur est invalide (URL de base incorrecte, variable d'environnement manquante, restriction de clé virtuelle, etc.). Veuillez vérifier les paramètres du fournisseur.",- "heterogeneous.aborted.description": "Cette tâche {{agent}} a été arrêtée. Envoyez une nouvelle demande lorsque vous souhaitez continuer.",- "heterogeneous.aborted.title": "Tâche arrêtée",- "heterogeneous.agent_failed.description": "{{agent}} s'est arrêté sans cause reconnue. Partagez l'ID d'opération avec le propriétaire du bot ou le support pour enquêter.",- "heterogeneous.agent_failed.title": "Échec de la tâche de l'agent",- "heterogeneous.auth_required.description": "Demandez au propriétaire du bot de se reconnecter sur l'appareil exécutant {{agent}}.",- "heterogeneous.auth_required.title": "Connexion requise",- "heterogeneous.cli_not_found.description": "Demandez au propriétaire du bot d'installer ou de réparer {{agent}} sur l'appareil exécutant cette tâche.",- "heterogeneous.cli_not_found.title": "CLI de l'agent indisponible",- "heterogeneous.credit_limit.description": "Demandez au propriétaire du bot d'ajouter des crédits au compte utilisé par {{agent}}, ou de changer de modèle. Attendre une réinitialisation de quota ne restaurera pas ces crédits.",- "heterogeneous.credit_limit.title": "Crédits épuisés",- "heterogeneous.invalid_request.description": "Le fournisseur a rejeté la demande envoyée par {{agent}}. Essayez un nouveau sujet ; si cela persiste, partagez l'ID d'opération avec le support.",- "heterogeneous.invalid_request.title": "Demande rejetée",- "heterogeneous.max_turns.description": "{{agent}} a atteint sa limite d'étapes avant de terminer. Divisez la tâche en étapes plus petites ou demandez au propriétaire du bot d'ajuster la limite.",- "heterogeneous.max_turns.title": "Limite d'étapes atteinte",- "heterogeneous.model_unavailable.description": "Le modèle sélectionné pour {{agent}} est indisponible. Demandez au propriétaire du bot de choisir un autre modèle.",- "heterogeneous.model_unavailable.title": "Modèle indisponible",- "heterogeneous.network_drop.description": "{{agent}} a perdu sa connexion avant de terminer. Réessayez ; si cela se reproduit, demandez au propriétaire du bot de vérifier les paramètres réseau et proxy de l'appareil en cours d'exécution.",- "heterogeneous.network_drop.title": "Connexion interrompue",- "heterogeneous.reset": "Le quota se réinitialise à {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Demandez au propriétaire du bot de restaurer le répertoire de travail utilisé par cette session {{agent}}, ou commencez un nouveau sujet.",- "heterogeneous.resume_cwd_mismatch.title": "Répertoire de session modifié",- "heterogeneous.resume_thread_not_found.description": "{{agent}} n'a pas pu trouver la session précédente. Commencez un nouveau sujet et renvoyez la demande.",- "heterogeneous.resume_thread_not_found.title": "Session précédente indisponible",- "heterogeneous.server_overloaded.description": "Le fournisseur derrière {{agent}} est occupé ou indisponible. Veuillez réessayer sous peu.",- "heterogeneous.server_overloaded.title": "Fournisseur temporairement indisponible",- "heterogeneous.server_throttle.description": "Le fournisseur limite temporairement les demandes de {{agent}}. Veuillez attendre un moment et réessayer.",- "heterogeneous.server_throttle.title": "Demandes temporairement limitées",- "heterogeneous.unsupported_attachment.description": "{{agent}} n'a pas pu lire une pièce jointe. Supprimez-la ou convertissez-la dans un format pris en charge, puis renvoyez la demande.",- "heterogeneous.unsupported_attachment.title": "Pièce jointe non prise en charge",- "heterogeneous.usage_limit.description": "Le compte utilisé par {{agent}} a épuisé son allocation. Attendez que le quota se réinitialise ou demandez au propriétaire du bot de passer à un compte ou un modèle avec un quota disponible.",- "heterogeneous.usage_limit.title": "Limite d'utilisation atteinte",- "heterogeneous.window.five_hour": "Allocation de session épuisée.",- "heterogeneous.window.seven_day": "Allocation hebdomadaire épuisée.",- "heterogeneous.working_directory_not_found.description": "Le répertoire de travail pour {{agent}} est introuvable. Demandez au propriétaire du bot de le restaurer ou de choisir un répertoire existant.",- "heterogeneous.working_directory_not_found.title": "Répertoire de travail indisponible"+ "UserConfigError": "La configuration du fournisseur est invalide (URL de base incorrecte, variable d'environnement manquante, restriction de clé virtuelle, etc.). Veuillez vérifier les paramètres du fournisseur."}diff --git a/locales/it-IT/modelRuntime.json b/locales/it-IT/modelRuntime.jsonindex 3aa6fa28422..42919f4e5d2 100644--- a/locales/it-IT/modelRuntime.json+++ b/locales/it-IT/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "Il gateway o proxy a monte ha restituito un errore. Riprova tra poco; se il problema persiste, controlla la configurazione del proxy / endpoint.","UpstreamHttpError": "Il provider ha restituito un errore HTTP senza ulteriori dettagli. Riprova o controlla la tua richiesta e la configurazione del modello.","UpstreamMalformedResponse": "Il provider ha restituito una risposta malformata che non può essere analizzata. Riprova; se il problema persiste, prova un modello o un provider diverso.",- "UserConfigError": "La configurazione del provider non è valida (URL di base errato, variabile di ambiente mancante, restrizione virtual-key, ecc.). Rivedi le impostazioni del provider.",- "heterogeneous.aborted.description": "Questo compito di {{agent}} è stato interrotto. Invia una nuova richiesta quando vuoi continuare.",- "heterogeneous.aborted.title": "Compito interrotto",- "heterogeneous.agent_failed.description": "{{agent}} si è fermato senza una causa riconosciuta. Condividi l'ID Operazione con il proprietario del bot o il supporto per indagare.",- "heterogeneous.agent_failed.title": "Compito dell'agente fallito",- "heterogeneous.auth_required.description": "Chiedi al proprietario del bot di accedere nuovamente sul dispositivo che esegue {{agent}}.",- "heterogeneous.auth_required.title": "Accesso richiesto",- "heterogeneous.cli_not_found.description": "Chiedi al proprietario del bot di installare o riparare {{agent}} sul dispositivo che esegue questo compito.",- "heterogeneous.cli_not_found.title": "CLI dell'agente non disponibile",- "heterogeneous.credit_limit.description": "Chiedi al proprietario del bot di aggiungere crediti all'account utilizzato da {{agent}}, o di cambiare modello. Aspettare un reset della quota non ripristinerà questi crediti.",- "heterogeneous.credit_limit.title": "Crediti esauriti",- "heterogeneous.invalid_request.description": "Il provider ha rifiutato la richiesta inviata da {{agent}}. Prova un nuovo argomento; se il problema persiste, condividi l'ID Operazione con il supporto.",- "heterogeneous.invalid_request.title": "Richiesta rifiutata",- "heterogeneous.max_turns.description": "{{agent}} ha raggiunto il limite di passaggi prima di completare. Suddividi il compito in passaggi più piccoli o chiedi al proprietario del bot di regolare il limite.",- "heterogeneous.max_turns.title": "Limite di passaggi raggiunto",- "heterogeneous.model_unavailable.description": "Il modello selezionato per {{agent}} non è disponibile. Chiedi al proprietario del bot di scegliere un altro modello.",- "heterogeneous.model_unavailable.title": "Modello non disponibile",- "heterogeneous.network_drop.description": "{{agent}} ha perso la connessione prima di completare. Riprova; se succede di nuovo, chiedi al proprietario del bot di controllare la rete e le impostazioni del proxy del dispositivo in uso.",- "heterogeneous.network_drop.title": "Connessione interrotta",- "heterogeneous.reset": "La quota si resetta alle {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Chiedi al proprietario del bot di ripristinare la directory di lavoro utilizzata da questa sessione di {{agent}}, o inizia un nuovo argomento.",- "heterogeneous.resume_cwd_mismatch.title": "Directory della sessione cambiata",- "heterogeneous.resume_thread_not_found.description": "{{agent}} non è riuscito a trovare la sessione precedente. Inizia un nuovo argomento e reinvia la richiesta.",- "heterogeneous.resume_thread_not_found.title": "Sessione precedente non disponibile",- "heterogeneous.server_overloaded.description": "Il provider dietro {{agent}} è occupato o non disponibile. Riprova tra poco.",- "heterogeneous.server_overloaded.title": "Provider temporaneamente non disponibile",- "heterogeneous.server_throttle.description": "Il provider sta temporaneamente limitando le richieste da {{agent}}. Attendi un momento e riprova.",- "heterogeneous.server_throttle.title": "Richieste temporaneamente limitate",- "heterogeneous.unsupported_attachment.description": "{{agent}} non è riuscito a leggere un allegato. Rimuovilo o convertilo in un formato supportato, quindi reinvia la richiesta.",- "heterogeneous.unsupported_attachment.title": "Allegato non supportato",- "heterogeneous.usage_limit.description": "L'account utilizzato da {{agent}} ha esaurito la sua quota. Aspetta che la quota si resetti o chiedi al proprietario del bot di passare a un account o modello con una quota disponibile.",- "heterogeneous.usage_limit.title": "Limite di utilizzo raggiunto",- "heterogeneous.window.five_hour": "Quota della sessione esaurita.",- "heterogeneous.window.seven_day": "Quota settimanale esaurita.",- "heterogeneous.working_directory_not_found.description": "La directory di lavoro per {{agent}} è mancante. Chiedi al proprietario del bot di ripristinarla o di scegliere una directory esistente.",- "heterogeneous.working_directory_not_found.title": "Directory di lavoro non disponibile"+ "UserConfigError": "La configurazione del provider non è valida (URL di base errato, variabile di ambiente mancante, restrizione virtual-key, ecc.). Rivedi le impostazioni del provider."}diff --git a/locales/ja-JP/modelRuntime.json b/locales/ja-JP/modelRuntime.jsonindex 4b74c92a193..67e481e7827 100644--- a/locales/ja-JP/modelRuntime.json+++ b/locales/ja-JP/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "上流のゲートウェイまたはプロキシがエラーを返しました。しばらくしてから再試行してください。それでも解決しない場合は、プロキシ/エンドポイントの設定を確認してください。","UpstreamHttpError": "プロバイダーが詳細のないHTTPエラーを返しました。再試行するか、リクエストとモデルの設定を確認してください。","UpstreamMalformedResponse": "プロバイダーが解析できない不正な形式のレスポンスを返しました。再試行してください。それでも解決しない場合は、別のモデルまたはプロバイダーを試してください。",- "UserConfigError": "プロバイダーの設定が無効です(ベースURLの誤り、環境変数の欠如、仮想キーの制限など)。プロバイダーの設定を確認してください。",- "heterogeneous.aborted.description": "この{{agent}}タスクは停止されました。続行したい場合は新しいリクエストを送信してください。",- "heterogeneous.aborted.title": "タスクが停止されました",- "heterogeneous.agent_failed.description": "{{agent}}が原因不明で停止しました。調査のために操作IDをボットの所有者またはサポートに共有してください。",- "heterogeneous.agent_failed.title": "エージェントタスクが失敗しました",- "heterogeneous.auth_required.description": "{{agent}}を実行しているデバイスで再度サインインするようボットの所有者に依頼してください。",- "heterogeneous.auth_required.title": "サインインが必要です",- "heterogeneous.cli_not_found.description": "{{agent}}を実行しているデバイスに{{agent}}をインストールまたは修復するようボットの所有者に依頼してください。",- "heterogeneous.cli_not_found.title": "エージェントCLIが利用できません",- "heterogeneous.credit_limit.description": "{{agent}}が使用しているアカウントにクレジットを追加するか、モデルを切り替えるようボットの所有者に依頼してください。クォータのリセットを待ってもこれらのクレジットは復元されません。",- "heterogeneous.credit_limit.title": "クレジットが使い果たされました",- "heterogeneous.invalid_request.description": "プロバイダーが{{agent}}によって送信されたリクエストを拒否しました。新しいトピックを試してください。それでも解決しない場合は、操作IDをサポートに共有してください。",- "heterogeneous.invalid_request.title": "リクエストが拒否されました",- "heterogeneous.max_turns.description": "{{agent}}が終了する前にステップ制限に達しました。タスクを小さなステップに分割するか、ボットの所有者に制限を調整するよう依頼してください。",- "heterogeneous.max_turns.title": "ステップ制限に達しました",- "heterogeneous.model_unavailable.description": "{{agent}}に選択されたモデルは利用できません。ボットの所有者に別のモデルを選択するよう依頼してください。",- "heterogeneous.model_unavailable.title": "モデルが利用できません",- "heterogeneous.network_drop.description": "{{agent}}が終了する前に接続が失われました。再試行してください。それでも発生する場合は、ボットの所有者に実行中のデバイスのネットワークおよびプロキシ設定を確認するよう依頼してください。",- "heterogeneous.network_drop.title": "接続が中断されました",- "heterogeneous.reset": "クォータは{{time}}(UTC)にリセットされます。",- "heterogeneous.resume_cwd_mismatch.description": "{{agent}}セッションで使用されている作業ディレクトリを復元するか、新しいトピックを開始するようボットの所有者に依頼してください。",- "heterogeneous.resume_cwd_mismatch.title": "セッションディレクトリが変更されました",- "heterogeneous.resume_thread_not_found.description": "{{agent}}は前回のセッションを見つけることができませんでした。新しいトピックを開始してリクエストを再送信してください。",- "heterogeneous.resume_thread_not_found.title": "前回のセッションが利用できません",- "heterogeneous.server_overloaded.description": "{{agent}}の背後にあるプロバイダーがビジー状態または利用できません。しばらくしてから再試行してください。",- "heterogeneous.server_overloaded.title": "プロバイダーが一時的に利用できません",- "heterogeneous.server_throttle.description": "プロバイダーが一時的に{{agent}}からのリクエストを制限しています。少し待ってから再試行してください。",- "heterogeneous.server_throttle.title": "リクエストが一時的に制限されています",- "heterogeneous.unsupported_attachment.description": "{{agent}}は添付ファイルを読み取ることができませんでした。削除するか、サポートされている形式に変換してからリクエストを再送信してください。",- "heterogeneous.unsupported_attachment.title": "添付ファイルがサポートされていません",- "heterogeneous.usage_limit.description": "{{agent}}が使用しているアカウントの許容量が使い果たされました。クォータがリセットされるのを待つか、利用可能なクォータを持つアカウントまたはモデルに切り替えるようボットの所有者に依頼してください。",- "heterogeneous.usage_limit.title": "使用制限に達しました",- "heterogeneous.window.five_hour": "セッションの許容量が使い果たされました。",- "heterogeneous.window.seven_day": "週間許容量が使い果たされました。",- "heterogeneous.working_directory_not_found.description": "{{agent}}の作業ディレクトリが見つかりません。ボットの所有者にそれを復元するか、既存のディレクトリを選択するよう依頼してください。",- "heterogeneous.working_directory_not_found.title": "作業ディレクトリが利用できません"+ "UserConfigError": "プロバイダーの設定が無効です(ベースURLの誤り、環境変数の欠如、仮想キーの制限など)。プロバイダーの設定を確認してください。"}diff --git a/locales/ko-KR/modelRuntime.json b/locales/ko-KR/modelRuntime.jsonindex 1461015621c..16ade391a15 100644--- a/locales/ko-KR/modelRuntime.json+++ b/locales/ko-KR/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "상위 게이트웨이 또는 프록시에서 오류를 반환했습니다. 잠시 후 다시 시도하세요. 문제가 지속되면 프록시/엔드포인트 구성을 확인하세요.","UpstreamHttpError": "제공업체가 추가 세부 정보 없이 HTTP 오류를 반환했습니다. 다시 시도하거나 요청 및 모델 구성을 확인하세요.","UpstreamMalformedResponse": "제공업체가 구문 분석할 수 없는 잘못된 응답을 반환했습니다. 다시 시도하세요. 문제가 지속되면 다른 모델이나 제공업체를 시도하세요.",- "UserConfigError": "제공업체 구성이 잘못되었습니다(잘못된 기본 URL, 누락된 환경 변수, 가상 키 제한 등). 제공업체 설정을 검토하세요.",- "heterogeneous.aborted.description": "이 {{agent}} 작업이 중단되었습니다. 계속하려면 새 요청을 보내세요.",- "heterogeneous.aborted.title": "작업 중단됨",- "heterogeneous.agent_failed.description": "{{agent}}이(가) 인식되지 않은 원인으로 중단되었습니다. 봇 소유자나 지원팀에 운영 ID를 공유하여 조사하세요.",- "heterogeneous.agent_failed.title": "에이전트 작업 실패",- "heterogeneous.auth_required.description": "{{agent}}을(를) 실행 중인 장치에서 다시 로그인하도록 봇 소유자에게 요청하세요.",- "heterogeneous.auth_required.title": "로그인 필요",- "heterogeneous.cli_not_found.description": "{{agent}}을(를) 실행 중인 장치에 설치하거나 복구하도록 봇 소유자에게 요청하세요.",- "heterogeneous.cli_not_found.title": "에이전트 CLI를 사용할 수 없음",- "heterogeneous.credit_limit.description": "{{agent}}이(가) 사용하는 계정에 크레딧을 추가하거나 모델을 전환하도록 봇 소유자에게 요청하세요. 할당량이 재설정되더라도 크레딧은 복구되지 않습니다.",- "heterogeneous.credit_limit.title": "크레딧 소진됨",- "heterogeneous.invalid_request.description": "제공자가 {{agent}}이(가) 보낸 요청을 거부했습니다. 새 주제를 시도하세요. 문제가 지속되면 운영 ID를 지원팀에 공유하세요.",- "heterogeneous.invalid_request.title": "요청 거부됨",- "heterogeneous.max_turns.description": "{{agent}}이(가) 완료되기 전에 단계 한도에 도달했습니다. 작업을 더 작은 단계로 나누거나 봇 소유자에게 한도를 조정하도록 요청하세요.",- "heterogeneous.max_turns.title": "단계 한도 도달",- "heterogeneous.model_unavailable.description": "{{agent}}에 선택된 모델을 사용할 수 없습니다. 봇 소유자에게 다른 모델을 선택하도록 요청하세요.",- "heterogeneous.model_unavailable.title": "모델을 사용할 수 없음",- "heterogeneous.network_drop.description": "{{agent}}이(가) 완료되기 전에 연결이 끊어졌습니다. 다시 시도하세요. 문제가 계속되면 봇 소유자에게 실행 중인 장치의 네트워크 및 프록시 설정을 확인하도록 요청하세요.",- "heterogeneous.network_drop.title": "연결 중단됨",- "heterogeneous.reset": "할당량은 {{time}} (UTC)에 재설정됩니다.",- "heterogeneous.resume_cwd_mismatch.description": "이 {{agent}} 세션에서 사용된 작업 디렉터리를 복원하거나 새 주제를 시작하도록 봇 소유자에게 요청하세요.",- "heterogeneous.resume_cwd_mismatch.title": "세션 디렉터리 변경됨",- "heterogeneous.resume_thread_not_found.description": "{{agent}}이(가) 이전 세션을 찾을 수 없습니다. 새 주제를 시작하고 요청을 다시 보내세요.",- "heterogeneous.resume_thread_not_found.title": "이전 세션을 사용할 수 없음",- "heterogeneous.server_overloaded.description": "{{agent}} 뒤의 제공자가 바쁘거나 사용할 수 없습니다. 잠시 후 다시 시도하세요.",- "heterogeneous.server_overloaded.title": "제공자를 일시적으로 사용할 수 없음",- "heterogeneous.server_throttle.description": "제공자가 {{agent}}의 요청을 일시적으로 제한하고 있습니다. 잠시 기다렸다가 다시 시도하세요.",- "heterogeneous.server_throttle.title": "요청이 일시적으로 제한됨",- "heterogeneous.unsupported_attachment.description": "{{agent}}이(가) 첨부 파일을 읽을 수 없습니다. 이를 제거하거나 지원되는 형식으로 변환한 후 요청을 다시 보내세요.",- "heterogeneous.unsupported_attachment.title": "첨부 파일을 지원하지 않음",- "heterogeneous.usage_limit.description": "{{agent}}이(가) 사용하는 계정이 허용량을 초과했습니다. 할당량이 재설정되기를 기다리거나 봇 소유자에게 사용 가능한 할당량이 있는 계정이나 모델로 전환하도록 요청하세요.",- "heterogeneous.usage_limit.title": "사용 한도 도달",- "heterogeneous.window.five_hour": "세션 허용량 소진됨.",- "heterogeneous.window.seven_day": "주간 허용량 소진됨.",- "heterogeneous.working_directory_not_found.description": "{{agent}}의 작업 디렉터리가 없습니다. 봇 소유자에게 이를 복원하거나 기존 디렉터리를 선택하도록 요청하세요.",- "heterogeneous.working_directory_not_found.title": "작업 디렉터리를 사용할 수 없음"+ "UserConfigError": "제공업체 구성이 잘못되었습니다(잘못된 기본 URL, 누락된 환경 변수, 가상 키 제한 등). 제공업체 설정을 검토하세요."}diff --git a/locales/nl-NL/modelRuntime.json b/locales/nl-NL/modelRuntime.jsonindex 816dff86a15..f9f17d6d7f7 100644--- a/locales/nl-NL/modelRuntime.json+++ b/locales/nl-NL/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "De upstream-gateway of proxy heeft een fout geretourneerd. Probeer het over een tijdje opnieuw; controleer uw proxy-/eindpuntconfiguratie als het probleem aanhoudt.","UpstreamHttpError": "De provider heeft een HTTP-fout geretourneerd zonder verdere details. Probeer het opnieuw, of controleer uw verzoek en modelconfiguratie.","UpstreamMalformedResponse": "De provider heeft een onjuist geformatteerd antwoord geretourneerd dat niet kon worden geparsed. Probeer het opnieuw; probeer een ander model of een andere provider als het probleem aanhoudt.",- "UserConfigError": "De providerconfiguratie is ongeldig (onjuiste basis-URL, ontbrekende omgevingsvariabele, virtuele-sleutelbeperking, enz.). Controleer de providerinstellingen.",- "heterogeneous.aborted.description": "Deze {{agent}}-taak is gestopt. Stuur een nieuwe aanvraag wanneer je wilt doorgaan.",- "heterogeneous.aborted.title": "Taak gestopt",- "heterogeneous.agent_failed.description": "{{agent}} is gestopt zonder een herkende oorzaak. Deel de Operation ID met de bot-eigenaar of ondersteuning om dit te onderzoeken.",- "heterogeneous.agent_failed.title": "Agent-taak mislukt",- "heterogeneous.auth_required.description": "Vraag de bot-eigenaar om opnieuw in te loggen op het apparaat waarop {{agent}} draait.",- "heterogeneous.auth_required.title": "Inloggen vereist",- "heterogeneous.cli_not_found.description": "Vraag de bot-eigenaar om {{agent}} te installeren of te repareren op het apparaat waarop deze taak draait.",- "heterogeneous.cli_not_found.title": "Agent CLI niet beschikbaar",- "heterogeneous.credit_limit.description": "Vraag de bot-eigenaar om tegoeden toe te voegen aan het account dat door {{agent}} wordt gebruikt, of schakel over naar een ander model. Wachten op een quotumreset zal deze tegoeden niet herstellen.",- "heterogeneous.credit_limit.title": "Tegoeden uitgeput",- "heterogeneous.invalid_request.description": "De provider heeft de aanvraag van {{agent}} afgewezen. Probeer een nieuw onderwerp; als het probleem aanhoudt, deel dan de Operation ID met ondersteuning.",- "heterogeneous.invalid_request.title": "Aanvraag afgewezen",- "heterogeneous.max_turns.description": "{{agent}} heeft de limiet voor stappen bereikt voordat de taak voltooid was. Verdeel de taak in kleinere stappen of vraag de bot-eigenaar om de limiet aan te passen.",- "heterogeneous.max_turns.title": "Stappenlimiet bereikt",- "heterogeneous.model_unavailable.description": "Het model dat is geselecteerd voor {{agent}} is niet beschikbaar. Vraag de bot-eigenaar om een ander model te kiezen.",- "heterogeneous.model_unavailable.title": "Model niet beschikbaar",- "heterogeneous.network_drop.description": "{{agent}} heeft de verbinding verloren voordat de taak voltooid was. Probeer het opnieuw; als het probleem zich herhaalt, vraag de bot-eigenaar om de netwerk- en proxy-instellingen van het apparaat te controleren.",- "heterogeneous.network_drop.title": "Verbinding onderbroken",- "heterogeneous.reset": "Quotum wordt gereset om {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Vraag de bot-eigenaar om de werkmap te herstellen die door deze {{agent}}-sessie wordt gebruikt, of begin een nieuw onderwerp.",- "heterogeneous.resume_cwd_mismatch.title": "Sessiemap gewijzigd",- "heterogeneous.resume_thread_not_found.description": "{{agent}} kon de vorige sessie niet vinden. Begin een nieuw onderwerp en stuur de aanvraag opnieuw.",- "heterogeneous.resume_thread_not_found.title": "Vorige sessie niet beschikbaar",- "heterogeneous.server_overloaded.description": "De provider achter {{agent}} is druk of niet beschikbaar. Probeer het over een tijdje opnieuw.",- "heterogeneous.server_overloaded.title": "Provider tijdelijk niet beschikbaar",- "heterogeneous.server_throttle.description": "De provider beperkt tijdelijk aanvragen van {{agent}}. Wacht een moment en probeer het opnieuw.",- "heterogeneous.server_throttle.title": "Aanvragen tijdelijk beperkt",- "heterogeneous.unsupported_attachment.description": "{{agent}} kon een bijlage niet lezen. Verwijder deze of converteer deze naar een ondersteund formaat en stuur de aanvraag opnieuw.",- "heterogeneous.unsupported_attachment.title": "Bijlage niet ondersteund",- "heterogeneous.usage_limit.description": "Het account dat door {{agent}} wordt gebruikt, heeft zijn limiet bereikt. Wacht tot het quotum wordt gereset of vraag de bot-eigenaar om over te schakelen naar een account of model met beschikbaar quotum.",- "heterogeneous.usage_limit.title": "Gebruiksbeperking bereikt",- "heterogeneous.window.five_hour": "Sessielimiet uitgeput.",- "heterogeneous.window.seven_day": "Wekelijkse limiet uitgeput.",- "heterogeneous.working_directory_not_found.description": "De werkmap voor {{agent}} ontbreekt. Vraag de bot-eigenaar om deze te herstellen of een bestaande map te kiezen.",- "heterogeneous.working_directory_not_found.title": "Werkmap niet beschikbaar"+ "UserConfigError": "De providerconfiguratie is ongeldig (onjuiste basis-URL, ontbrekende omgevingsvariabele, virtuele-sleutelbeperking, enz.). Controleer de providerinstellingen."}diff --git a/locales/pl-PL/modelRuntime.json b/locales/pl-PL/modelRuntime.jsonindex 38447ddf3c0..955b697b54f 100644--- a/locales/pl-PL/modelRuntime.json+++ b/locales/pl-PL/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "Bramka upstream lub proxy zwróciły błąd. Proszę spróbować ponownie za chwilę; jeśli problem będzie się powtarzał, sprawdź konfigurację proxy / punktu końcowego.","UpstreamHttpError": "Dostawca zwrócił błąd HTTP bez dodatkowych szczegółów. Proszę spróbować ponownie, lub sprawdzić swoje żądanie i konfigurację modelu.","UpstreamMalformedResponse": "Dostawca zwrócił nieprawidłową odpowiedź, której nie można było przetworzyć. Proszę spróbować ponownie; jeśli problem będzie się powtarzał, spróbuj użyć innego modelu lub dostawcy.",- "UserConfigError": "Konfiguracja dostawcy jest nieprawidłowa (nieprawidłowy podstawowy URL, brakująca zmienna środowiskowa, ograniczenie wirtualnego klucza itp.). Proszę sprawdzić ustawienia dostawcy.",- "heterogeneous.aborted.description": "To zadanie {{agent}} zostało zatrzymane. Wyślij nowe żądanie, gdy chcesz kontynuować.",- "heterogeneous.aborted.title": "Zadanie zatrzymane",- "heterogeneous.agent_failed.description": "{{agent}} zatrzymał się bez rozpoznanej przyczyny. Udostępnij ID operacji właścicielowi bota lub wsparciu technicznemu w celu zbadania problemu.",- "heterogeneous.agent_failed.title": "Zadanie agenta nie powiodło się",- "heterogeneous.auth_required.description": "Poproś właściciela bota o ponowne zalogowanie się na urządzeniu uruchamiającym {{agent}}.",- "heterogeneous.auth_required.title": "Wymagane logowanie",- "heterogeneous.cli_not_found.description": "Poproś właściciela bota o zainstalowanie lub naprawienie {{agent}} na urządzeniu uruchamiającym to zadanie.",- "heterogeneous.cli_not_found.title": "CLI agenta niedostępne",- "heterogeneous.credit_limit.description": "Poproś właściciela bota o dodanie środków na konto używane przez {{agent}} lub o zmianę modelu. Oczekiwanie na reset limitu nie przywróci tych środków.",- "heterogeneous.credit_limit.title": "Środki wyczerpane",- "heterogeneous.invalid_request.description": "Dostawca odrzucił żądanie wysłane przez {{agent}}. Spróbuj nowego tematu; jeśli problem się powtórzy, udostępnij ID operacji wsparciu technicznemu.",- "heterogeneous.invalid_request.title": "Żądanie odrzucone",- "heterogeneous.max_turns.description": "{{agent}} osiągnął limit kroków przed zakończeniem. Podziel zadanie na mniejsze kroki lub poproś właściciela bota o dostosowanie limitu.",- "heterogeneous.max_turns.title": "Osiągnięto limit kroków",- "heterogeneous.model_unavailable.description": "Wybrany model dla {{agent}} jest niedostępny. Poproś właściciela bota o wybór innego modelu.",- "heterogeneous.model_unavailable.title": "Model niedostępny",- "heterogeneous.network_drop.description": "{{agent}} utracił połączenie przed zakończeniem. Spróbuj ponownie; jeśli problem się powtórzy, poproś właściciela bota o sprawdzenie sieci i ustawień proxy na urządzeniu uruchamiającym.",- "heterogeneous.network_drop.title": "Połączenie przerwane",- "heterogeneous.reset": "Limit zostanie zresetowany o {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Poproś właściciela bota o przywrócenie katalogu roboczego używanego w tej sesji {{agent}} lub rozpocznij nowy temat.",- "heterogeneous.resume_cwd_mismatch.title": "Katalog sesji zmieniony",- "heterogeneous.resume_thread_not_found.description": "{{agent}} nie mógł znaleźć poprzedniej sesji. Rozpocznij nowy temat i wyślij żądanie ponownie.",- "heterogeneous.resume_thread_not_found.title": "Poprzednia sesja niedostępna",- "heterogeneous.server_overloaded.description": "Dostawca obsługujący {{agent}} jest zajęty lub niedostępny. Spróbuj ponownie za chwilę.",- "heterogeneous.server_overloaded.title": "Dostawca tymczasowo niedostępny",- "heterogeneous.server_throttle.description": "Dostawca tymczasowo ogranicza żądania od {{agent}}. Poczekaj chwilę i spróbuj ponownie.",- "heterogeneous.server_throttle.title": "Żądania tymczasowo ograniczone",- "heterogeneous.unsupported_attachment.description": "{{agent}} nie mógł odczytać załącznika. Usuń go lub przekonwertuj na obsługiwany format, a następnie wyślij żądanie ponownie.",- "heterogeneous.unsupported_attachment.title": "Załącznik nieobsługiwany",- "heterogeneous.usage_limit.description": "Konto używane przez {{agent}} wyczerpało swój limit. Poczekaj na reset limitu lub poproś właściciela bota o przełączenie na konto lub model z dostępnym limitem.",- "heterogeneous.usage_limit.title": "Osiągnięto limit użycia",- "heterogeneous.window.five_hour": "Wyczerpano limit sesji.",- "heterogeneous.window.seven_day": "Wyczerpano tygodniowy limit.",- "heterogeneous.working_directory_not_found.description": "Katalog roboczy dla {{agent}} jest niedostępny. Poproś właściciela bota o jego przywrócenie lub wybierz istniejący katalog.",- "heterogeneous.working_directory_not_found.title": "Katalog roboczy niedostępny"+ "UserConfigError": "Konfiguracja dostawcy jest nieprawidłowa (nieprawidłowy podstawowy URL, brakująca zmienna środowiskowa, ograniczenie wirtualnego klucza itp.). Proszę sprawdzić ustawienia dostawcy."}diff --git a/locales/pt-BR/modelRuntime.json b/locales/pt-BR/modelRuntime.jsonindex d20f71da76e..056003ed03c 100644--- a/locales/pt-BR/modelRuntime.json+++ b/locales/pt-BR/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "O gateway ou proxy do provedor retornou um erro. Por favor, tente novamente em breve; se o problema persistir, verifique sua configuração de proxy/endpoint.","UpstreamHttpError": "O provedor retornou um erro HTTP sem mais detalhes. Por favor, tente novamente ou verifique sua solicitação e configuração do modelo.","UpstreamMalformedResponse": "O provedor retornou uma resposta malformada que não pôde ser analisada. Por favor, tente novamente; se o problema persistir, tente um modelo ou provedor diferente.",- "UserConfigError": "A configuração do provedor é inválida (URL base incorreta, variável de ambiente ausente, restrição de chave virtual, etc.). Por favor, revise as configurações do provedor.",- "heterogeneous.aborted.description": "Esta tarefa do {{agent}} foi interrompida. Envie uma nova solicitação quando quiser continuar.",- "heterogeneous.aborted.title": "Tarefa interrompida",- "heterogeneous.agent_failed.description": "{{agent}} parou sem uma causa reconhecida. Compartilhe o ID da Operação com o proprietário do bot ou suporte para investigação.",- "heterogeneous.agent_failed.title": "Falha na tarefa do agente",- "heterogeneous.auth_required.description": "Peça ao proprietário do bot para fazer login novamente no dispositivo que está executando o {{agent}}.",- "heterogeneous.auth_required.title": "Login necessário",- "heterogeneous.cli_not_found.description": "Peça ao proprietário do bot para instalar ou reparar o {{agent}} no dispositivo que está executando esta tarefa.",- "heterogeneous.cli_not_found.title": "CLI do agente indisponível",- "heterogeneous.credit_limit.description": "Peça ao proprietário do bot para adicionar créditos à conta usada pelo {{agent}} ou trocar de modelo. Aguardando um reset de cota não restaurará esses créditos.",- "heterogeneous.credit_limit.title": "Créditos esgotados",- "heterogeneous.invalid_request.description": "O provedor rejeitou a solicitação enviada pelo {{agent}}. Tente um novo tópico; se persistir, compartilhe o ID da Operação com o suporte.",- "heterogeneous.invalid_request.title": "Solicitação rejeitada",- "heterogeneous.max_turns.description": "{{agent}} atingiu seu limite de etapas antes de terminar. Divida a tarefa em etapas menores ou peça ao proprietário do bot para ajustar o limite.",- "heterogeneous.max_turns.title": "Limite de etapas atingido",- "heterogeneous.model_unavailable.description": "O modelo selecionado para o {{agent}} está indisponível. Peça ao proprietário do bot para escolher outro modelo.",- "heterogeneous.model_unavailable.title": "Modelo indisponível",- "heterogeneous.network_drop.description": "{{agent}} perdeu a conexão antes de terminar. Tente novamente; se acontecer novamente, peça ao proprietário do bot para verificar a rede e as configurações de proxy do dispositivo em execução.",- "heterogeneous.network_drop.title": "Conexão interrompida",- "heterogeneous.reset": "A cota será redefinida às {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Peça ao proprietário do bot para restaurar o diretório de trabalho usado por esta sessão do {{agent}} ou inicie um novo tópico.",- "heterogeneous.resume_cwd_mismatch.title": "Diretório da sessão alterado",- "heterogeneous.resume_thread_not_found.description": "{{agent}} não conseguiu encontrar a sessão anterior. Inicie um novo tópico e reenvie a solicitação.",- "heterogeneous.resume_thread_not_found.title": "Sessão anterior indisponível",- "heterogeneous.server_overloaded.description": "O provedor por trás do {{agent}} está ocupado ou indisponível. Por favor, tente novamente em breve.",- "heterogeneous.server_overloaded.title": "Provedor temporariamente indisponível",- "heterogeneous.server_throttle.description": "O provedor está limitando temporariamente as solicitações do {{agent}}. Por favor, aguarde um momento e tente novamente.",- "heterogeneous.server_throttle.title": "Solicitações temporariamente limitadas",- "heterogeneous.unsupported_attachment.description": "{{agent}} não conseguiu ler um anexo. Remova-o ou converta-o para um formato compatível e reenvie a solicitação.",- "heterogeneous.unsupported_attachment.title": "Anexo não suportado",- "heterogeneous.usage_limit.description": "A conta usada pelo {{agent}} esgotou sua cota. Aguarde a redefinição da cota ou peça ao proprietário do bot para trocar para uma conta ou modelo com cota disponível.",- "heterogeneous.usage_limit.title": "Limite de uso atingido",- "heterogeneous.window.five_hour": "Cota da sessão esgotada.",- "heterogeneous.window.seven_day": "Cota semanal esgotada.",- "heterogeneous.working_directory_not_found.description": "O diretório de trabalho para o {{agent}} está ausente. Peça ao proprietário do bot para restaurá-lo ou escolher um diretório existente.",- "heterogeneous.working_directory_not_found.title": "Diretório de trabalho indisponível"+ "UserConfigError": "A configuração do provedor é inválida (URL base incorreta, variável de ambiente ausente, restrição de chave virtual, etc.). Por favor, revise as configurações do provedor."}diff --git a/locales/ru-RU/modelRuntime.json b/locales/ru-RU/modelRuntime.jsonindex 50568b0b70b..03681055b79 100644--- a/locales/ru-RU/modelRuntime.json+++ b/locales/ru-RU/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "Верхний шлюз или прокси вернули ошибку. Пожалуйста, повторите попытку позже; если проблема сохраняется, проверьте конфигурацию прокси/конечной точки.","UpstreamHttpError": "Провайдер вернул HTTP-ошибку без дополнительных деталей. Пожалуйста, повторите попытку или проверьте ваш запрос и конфигурацию модели.","UpstreamMalformedResponse": "Провайдер вернул некорректный ответ, который не удалось разобрать. Пожалуйста, повторите попытку; если проблема сохраняется, попробуйте другую модель или провайдера.",- "UserConfigError": "Конфигурация провайдера некорректна (неправильный базовый URL, отсутствует переменная окружения, ограничение виртуального ключа и т.д.). Пожалуйста, проверьте настройки провайдера.",- "heterogeneous.aborted.description": "Эта задача {{agent}} была остановлена. Отправьте новый запрос, когда захотите продолжить.",- "heterogeneous.aborted.title": "Задача остановлена",- "heterogeneous.agent_failed.description": "{{agent}} остановился без распознанной причины. Поделитесь идентификатором операции с владельцем бота или службой поддержки для расследования.",- "heterogeneous.agent_failed.title": "Ошибка задачи агента",- "heterogeneous.auth_required.description": "Попросите владельца бота снова войти в систему на устройстве, где работает {{agent}}.",- "heterogeneous.auth_required.title": "Требуется вход в систему",- "heterogeneous.cli_not_found.description": "Попросите владельца бота установить или восстановить {{agent}} на устройстве, выполняющем эту задачу.",- "heterogeneous.cli_not_found.title": "CLI агента недоступен",- "heterogeneous.credit_limit.description": "Попросите владельца бота добавить кредиты на аккаунт, используемый {{agent}}, или переключиться на другую модель. Ожидание сброса квоты не восстановит эти кредиты.",- "heterogeneous.credit_limit.title": "Кредиты исчерпаны",- "heterogeneous.invalid_request.description": "Провайдер отклонил запрос, отправленный {{agent}}. Попробуйте новую тему; если проблема сохраняется, поделитесь идентификатором операции с поддержкой.",- "heterogeneous.invalid_request.title": "Запрос отклонен",- "heterogeneous.max_turns.description": "{{agent}} достиг предела шагов до завершения. Разбейте задачу на более мелкие шаги или попросите владельца бота настроить предел.",- "heterogeneous.max_turns.title": "Достигнут предел шагов",- "heterogeneous.model_unavailable.description": "Выбранная модель для {{agent}} недоступна. Попросите владельца бота выбрать другую модель.",- "heterogeneous.model_unavailable.title": "Модель недоступна",- "heterogeneous.network_drop.description": "{{agent}} потерял соединение до завершения. Повторите попытку; если это произойдет снова, попросите владельца бота проверить настройки сети и прокси на работающем устройстве.",- "heterogeneous.network_drop.title": "Соединение прервано",- "heterogeneous.reset": "Сброс квоты в {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Попросите владельца бота восстановить рабочую директорию, используемую этой сессией {{agent}}, или начните новую тему.",- "heterogeneous.resume_cwd_mismatch.title": "Рабочая директория изменена",- "heterogeneous.resume_thread_not_found.description": "{{agent}} не смог найти предыдущую сессию. Начните новую тему и отправьте запрос снова.",- "heterogeneous.resume_thread_not_found.title": "Предыдущая сессия недоступна",- "heterogeneous.server_overloaded.description": "Провайдер, поддерживающий {{agent}}, занят или недоступен. Пожалуйста, попробуйте снова через некоторое время.",- "heterogeneous.server_overloaded.title": "Провайдер временно недоступен",- "heterogeneous.server_throttle.description": "Провайдер временно ограничивает запросы от {{agent}}. Пожалуйста, подождите немного и попробуйте снова.",- "heterogeneous.server_throttle.title": "Запросы временно ограничены",- "heterogeneous.unsupported_attachment.description": "{{agent}} не смог прочитать вложение. Удалите его или преобразуйте в поддерживаемый формат, затем отправьте запрос снова.",- "heterogeneous.unsupported_attachment.title": "Вложение не поддерживается",- "heterogeneous.usage_limit.description": "Аккаунт, используемый {{agent}}, исчерпал свою квоту. Подождите сброса квоты или попросите владельца бота переключиться на аккаунт или модель с доступной квотой.",- "heterogeneous.usage_limit.title": "Достигнут предел использования",- "heterogeneous.window.five_hour": "Сессия исчерпала лимит.",- "heterogeneous.window.seven_day": "Еженедельный лимит исчерпан.",- "heterogeneous.working_directory_not_found.description": "Рабочая директория для {{agent}} отсутствует. Попросите владельца бота восстановить её или выбрать существующую директорию.",- "heterogeneous.working_directory_not_found.title": "Рабочая директория недоступна"+ "UserConfigError": "Конфигурация провайдера некорректна (неправильный базовый URL, отсутствует переменная окружения, ограничение виртуального ключа и т.д.). Пожалуйста, проверьте настройки провайдера."}diff --git a/locales/tr-TR/modelRuntime.json b/locales/tr-TR/modelRuntime.jsonindex a6348d66901..e02c4291e52 100644--- a/locales/tr-TR/modelRuntime.json+++ b/locales/tr-TR/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "Yukarı akış ağ geçidi veya proxy bir hata döndürdü. Lütfen kısa bir süre sonra yeniden deneyin; devam ederse proxy / uç nokta yapılandırmanızı kontrol edin.","UpstreamHttpError": "Sağlayıcı ayrıntı vermeden bir HTTP hatası döndürdü. Lütfen yeniden deneyin veya isteğinizi ve model yapılandırmanızı kontrol edin.","UpstreamMalformedResponse": "Sağlayıcı ayrıştırılamayan hatalı biçimlendirilmiş bir yanıt döndürdü. Lütfen yeniden deneyin; devam ederse farklı bir model veya sağlayıcı deneyin.",- "UserConfigError": "Sağlayıcı yapılandırması geçersiz (yanlış temel URL, eksik ortam değişkeni, sanal anahtar kısıtlaması vb.). Lütfen sağlayıcı ayarlarını gözden geçirin.",- "heterogeneous.aborted.description": "Bu {{agent}} görevi durduruldu. Devam etmek istediğinizde yeni bir istek gönderin.",- "heterogeneous.aborted.title": "Görev durduruldu",- "heterogeneous.agent_failed.description": "{{agent}} tanınmayan bir nedenle durdu. İnceleme için İşlem Kimliğini bot sahibine veya desteğe iletin.",- "heterogeneous.agent_failed.title": "Ajan görevi başarısız oldu",- "heterogeneous.auth_required.description": "Bot sahibinden {{agent}} çalıştıran cihazda tekrar oturum açmasını isteyin.",- "heterogeneous.auth_required.title": "Oturum açma gerekli",- "heterogeneous.cli_not_found.description": "Bot sahibinden {{agent}}'i çalıştıran cihazda kurmasını veya onarmasını isteyin.",- "heterogeneous.cli_not_found.title": "Ajan CLI mevcut değil",- "heterogeneous.credit_limit.description": "Bot sahibinden {{agent}} tarafından kullanılan hesaba kredi eklemesini veya modeli değiştirmesini isteyin. Kota sıfırlamasını beklemek bu kredileri geri getirmez.",- "heterogeneous.credit_limit.title": "Krediler tükendi",- "heterogeneous.invalid_request.description": "Sağlayıcı, {{agent}} tarafından gönderilen isteği reddetti. Yeni bir konu deneyin; devam ederse, İşlem Kimliğini desteğe iletin.",- "heterogeneous.invalid_request.title": "İstek reddedildi",- "heterogeneous.max_turns.description": "{{agent}} bitirmeden önce adım limitine ulaştı. Görevi daha küçük adımlara bölün veya bot sahibinden limiti ayarlamasını isteyin.",- "heterogeneous.max_turns.title": "Adım limiti aşıldı",- "heterogeneous.model_unavailable.description": "{{agent}} için seçilen model mevcut değil. Bot sahibinden başka bir model seçmesini isteyin.",- "heterogeneous.model_unavailable.title": "Model mevcut değil",- "heterogeneous.network_drop.description": "{{agent}} bitirmeden önce bağlantısını kaybetti. Tekrar deneyin; tekrar olursa, bot sahibinden çalışan cihazın ağ ve proxy ayarlarını kontrol etmesini isteyin.",- "heterogeneous.network_drop.title": "Bağlantı kesildi",- "heterogeneous.reset": "Kota {{time}} (UTC) saatinde sıfırlanır.",- "heterogeneous.resume_cwd_mismatch.description": "Bot sahibinden bu {{agent}} oturumu tarafından kullanılan çalışma dizinini geri yüklemesini veya yeni bir konu başlatmasını isteyin.",- "heterogeneous.resume_cwd_mismatch.title": "Oturum dizini değişti",- "heterogeneous.resume_thread_not_found.description": "{{agent}} önceki oturumu bulamadı. Yeni bir konu başlatın ve isteği yeniden gönderin.",- "heterogeneous.resume_thread_not_found.title": "Önceki oturum mevcut değil",- "heterogeneous.server_overloaded.description": "{{agent}} arkasındaki sağlayıcı meşgul veya kullanılamıyor. Lütfen kısa bir süre sonra tekrar deneyin.",- "heterogeneous.server_overloaded.title": "Sağlayıcı geçici olarak kullanılamıyor",- "heterogeneous.server_throttle.description": "Sağlayıcı, {{agent}}'den gelen istekleri geçici olarak sınırlıyor. Lütfen bir süre bekleyin ve tekrar deneyin.",- "heterogeneous.server_throttle.title": "İstekler geçici olarak sınırlı",- "heterogeneous.unsupported_attachment.description": "{{agent}} bir eki okuyamadı. Onu kaldırın veya desteklenen bir formata dönüştürün, ardından isteği yeniden gönderin.",- "heterogeneous.unsupported_attachment.title": "Ek desteklenmiyor",- "heterogeneous.usage_limit.description": "{{agent}} tarafından kullanılan hesap, kullanım hakkını tüketti. Kotanın sıfırlanmasını bekleyin veya bot sahibinden kullanılabilir kotaya sahip bir hesap veya model seçmesini isteyin.",- "heterogeneous.usage_limit.title": "Kullanım limiti aşıldı",- "heterogeneous.window.five_hour": "Oturum hakkı tükendi.",- "heterogeneous.window.seven_day": "Haftalık hak tükendi.",- "heterogeneous.working_directory_not_found.description": "{{agent}} için çalışma dizini eksik. Bot sahibinden onu geri yüklemesini veya mevcut bir dizin seçmesini isteyin.",- "heterogeneous.working_directory_not_found.title": "Çalışma dizini mevcut değil"+ "UserConfigError": "Sağlayıcı yapılandırması geçersiz (yanlış temel URL, eksik ortam değişkeni, sanal anahtar kısıtlaması vb.). Lütfen sağlayıcı ayarlarını gözden geçirin."}diff --git a/locales/vi-VN/modelRuntime.json b/locales/vi-VN/modelRuntime.jsonindex 495c36cb0ca..16298de54d3 100644--- a/locales/vi-VN/modelRuntime.json+++ b/locales/vi-VN/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "Cổng hoặc proxy đầu nguồn trả về lỗi. Vui lòng thử lại sau; nếu vấn đề vẫn tiếp diễn, hãy kiểm tra cấu hình proxy/endpoint của bạn.","UpstreamHttpError": "Nhà cung cấp trả về lỗi HTTP mà không có chi tiết thêm. Vui lòng thử lại, hoặc kiểm tra yêu cầu và cấu hình mô hình của bạn.","UpstreamMalformedResponse": "Nhà cung cấp trả về phản hồi không hợp lệ và không thể phân tích. Vui lòng thử lại; nếu vấn đề vẫn tiếp diễn, hãy thử một mô hình hoặc nhà cung cấp khác.",- "UserConfigError": "Cấu hình nhà cung cấp không hợp lệ (URL cơ sở không chính xác, thiếu biến môi trường, hạn chế khóa ảo, v.v.). Vui lòng xem lại cài đặt của nhà cung cấp.",- "heterogeneous.aborted.description": "Nhiệm vụ {{agent}} này đã bị dừng. Gửi một yêu cầu mới khi bạn muốn tiếp tục.",- "heterogeneous.aborted.title": "Nhiệm vụ đã dừng",- "heterogeneous.agent_failed.description": "{{agent}} đã dừng mà không có nguyên nhân được nhận diện. Chia sẻ ID Hoạt động với chủ sở hữu bot hoặc bộ phận hỗ trợ để điều tra.",- "heterogeneous.agent_failed.title": "Nhiệm vụ agent thất bại",- "heterogeneous.auth_required.description": "Yêu cầu chủ sở hữu bot đăng nhập lại trên thiết bị đang chạy {{agent}}.",- "heterogeneous.auth_required.title": "Yêu cầu đăng nhập",- "heterogeneous.cli_not_found.description": "Yêu cầu chủ sở hữu bot cài đặt hoặc sửa chữa {{agent}} trên thiết bị đang chạy nhiệm vụ này.",- "heterogeneous.cli_not_found.title": "CLI của agent không khả dụng",- "heterogeneous.credit_limit.description": "Yêu cầu chủ sở hữu bot thêm tín dụng vào tài khoản được sử dụng bởi {{agent}}, hoặc chuyển đổi mô hình. Chờ đặt lại hạn mức sẽ không khôi phục được tín dụng này.",- "heterogeneous.credit_limit.title": "Hết tín dụng",- "heterogeneous.invalid_request.description": "Nhà cung cấp đã từ chối yêu cầu được gửi bởi {{agent}}. Hãy thử một chủ đề mới; nếu vấn đề vẫn tiếp diễn, chia sẻ ID Hoạt động với bộ phận hỗ trợ.",- "heterogeneous.invalid_request.title": "Yêu cầu bị từ chối",- "heterogeneous.max_turns.description": "{{agent}} đã đạt đến giới hạn bước trước khi hoàn thành. Chia nhỏ nhiệm vụ thành các bước nhỏ hơn hoặc yêu cầu chủ sở hữu bot điều chỉnh giới hạn.",- "heterogeneous.max_turns.title": "Đã đạt giới hạn bước",- "heterogeneous.model_unavailable.description": "Mô hình được chọn cho {{agent}} không khả dụng. Yêu cầu chủ sở hữu bot chọn một mô hình khác.",- "heterogeneous.model_unavailable.title": "Mô hình không khả dụng",- "heterogeneous.network_drop.description": "{{agent}} đã mất kết nối trước khi hoàn thành. Thử lại; nếu vấn đề tiếp diễn, yêu cầu chủ sở hữu bot kiểm tra mạng và cài đặt proxy của thiết bị đang chạy.",- "heterogeneous.network_drop.title": "Kết nối bị gián đoạn",- "heterogeneous.reset": "Hạn mức sẽ được đặt lại vào {{time}} (UTC).",- "heterogeneous.resume_cwd_mismatch.description": "Yêu cầu chủ sở hữu bot khôi phục thư mục làm việc được sử dụng bởi phiên {{agent}} này hoặc bắt đầu một chủ đề mới.",- "heterogeneous.resume_cwd_mismatch.title": "Thư mục phiên đã thay đổi",- "heterogeneous.resume_thread_not_found.description": "{{agent}} không thể tìm thấy phiên trước đó. Bắt đầu một chủ đề mới và gửi lại yêu cầu.",- "heterogeneous.resume_thread_not_found.title": "Phiên trước không khả dụng",- "heterogeneous.server_overloaded.description": "Nhà cung cấp phía sau {{agent}} đang bận hoặc không khả dụng. Vui lòng thử lại sau.",- "heterogeneous.server_overloaded.title": "Nhà cung cấp tạm thời không khả dụng",- "heterogeneous.server_throttle.description": "Nhà cung cấp đang tạm thời giới hạn các yêu cầu từ {{agent}}. Vui lòng chờ một lúc và thử lại.",- "heterogeneous.server_throttle.title": "Yêu cầu tạm thời bị giới hạn",- "heterogeneous.unsupported_attachment.description": "{{agent}} không thể đọc tệp đính kèm. Hãy xóa hoặc chuyển đổi nó sang định dạng được hỗ trợ, sau đó gửi lại yêu cầu.",- "heterogeneous.unsupported_attachment.title": "Tệp đính kèm không được hỗ trợ",- "heterogeneous.usage_limit.description": "Tài khoản được sử dụng bởi {{agent}} đã hết hạn mức. Chờ hạn mức được đặt lại hoặc yêu cầu chủ sở hữu bot chuyển sang tài khoản hoặc mô hình có hạn mức khả dụng.",- "heterogeneous.usage_limit.title": "Đã đạt giới hạn sử dụng",- "heterogeneous.window.five_hour": "Hạn mức phiên đã hết.",- "heterogeneous.window.seven_day": "Hạn mức hàng tuần đã hết.",- "heterogeneous.working_directory_not_found.description": "Thư mục làm việc cho {{agent}} bị thiếu. Yêu cầu chủ sở hữu bot khôi phục hoặc chọn một thư mục hiện có.",- "heterogeneous.working_directory_not_found.title": "Thư mục làm việc không khả dụng"+ "UserConfigError": "Cấu hình nhà cung cấp không hợp lệ (URL cơ sở không chính xác, thiếu biến môi trường, hạn chế khóa ảo, v.v.). Vui lòng xem lại cài đặt của nhà cung cấp."}diff --git a/locales/zh-CN/modelRuntime.json b/locales/zh-CN/modelRuntime.jsonindex a5ffc83073e..8979117e14c 100644--- a/locales/zh-CN/modelRuntime.json+++ b/locales/zh-CN/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "上游网关或代理返回错误。请稍后重试;如果问题仍然存在,请检查您的代理/端点配置。","UpstreamHttpError": "提供商返回了HTTP错误,但未提供进一步详细信息。请重试,或检查您的请求和模型配置。","UpstreamMalformedResponse": "提供商返回了无法解析的格式错误响应。请重试;如果问题仍然存在,请尝试使用其他模型或提供商。",- "UserConfigError": "提供商配置无效(基础URL错误、缺少环境变量、虚拟密钥限制等)。请检查提供商设置。",- "heterogeneous.aborted.description": "本次 {{agent}} 任务已停止。如需继续,请发送新的请求。",- "heterogeneous.aborted.title": "任务已停止",- "heterogeneous.agent_failed.description": "{{agent}} 已停止,目前无法确定具体原因。请将 Operation ID 提供给机器人管理员或支持人员排查。",- "heterogeneous.agent_failed.title": "Agent 任务失败",- "heterogeneous.auth_required.description": "请联系机器人管理员,在运行 {{agent}} 的设备上重新登录。",- "heterogeneous.auth_required.title": "需要重新登录",- "heterogeneous.cli_not_found.description": "请联系机器人管理员,在运行任务的设备上安装或修复 {{agent}}。",- "heterogeneous.cli_not_found.title": "Agent CLI 不可用",- "heterogeneous.credit_limit.description": "请联系机器人管理员,为 {{agent}} 使用的账号补充积分或切换模型。等待额度周期重置不会恢复这部分积分。",- "heterogeneous.credit_limit.title": "积分已耗尽",- "heterogeneous.invalid_request.description": "提供商拒绝了 {{agent}} 发送的请求。请新建话题后重试;若持续发生,请向支持人员提供 Operation ID。",- "heterogeneous.invalid_request.title": "请求被拒绝",- "heterogeneous.max_turns.description": "{{agent}} 在完成任务前达到步骤上限。请拆分任务,或联系机器人管理员调整上限。",- "heterogeneous.max_turns.title": "已达到步骤上限",- "heterogeneous.model_unavailable.description": "{{agent}} 所选的模型当前不可用。请联系机器人管理员切换模型。",- "heterogeneous.model_unavailable.title": "模型不可用",- "heterogeneous.network_drop.description": "{{agent}} 在完成任务前连接中断。请重试;若持续发生,请联系机器人管理员检查运行设备的网络和代理设置。",- "heterogeneous.network_drop.title": "连接中断",- "heterogeneous.reset": "额度恢复时间:{{time}}(UTC)。",- "heterogeneous.resume_cwd_mismatch.description": "请联系机器人管理员恢复本次 {{agent}} 会话原来的工作目录,或新建话题。",- "heterogeneous.resume_cwd_mismatch.title": "会话工作目录已变化",- "heterogeneous.resume_thread_not_found.description": "{{agent}} 找不到原来的会话。请新建话题并重新发送请求。",- "heterogeneous.resume_thread_not_found.title": "原会话不可用",- "heterogeneous.server_overloaded.description": "{{agent}} 的上游服务当前繁忙或不可用,请稍后重试。",- "heterogeneous.server_overloaded.title": "上游服务暂不可用",- "heterogeneous.server_throttle.description": "提供商暂时限制了 {{agent}} 的请求,请稍等片刻后重试。",- "heterogeneous.server_throttle.title": "请求暂时受到限流",- "heterogeneous.unsupported_attachment.description": "{{agent}} 无法读取附件。请移除附件或转换为支持的格式后重新发送。",- "heterogeneous.unsupported_attachment.title": "附件无法读取",- "heterogeneous.usage_limit.description": "{{agent}} 使用的账号额度已耗尽。请等待额度恢复,或联系机器人管理员切换有可用额度的账号或模型。",- "heterogeneous.usage_limit.title": "使用额度已用完",- "heterogeneous.window.five_hour": "当前会话周期额度已用完。",- "heterogeneous.window.seven_day": "本周额度已用完。",- "heterogeneous.working_directory_not_found.description": "{{agent}} 的工作目录不存在。请联系机器人管理员恢复目录,或选择一个现有目录。",- "heterogeneous.working_directory_not_found.title": "工作目录不存在"+ "UserConfigError": "提供商配置无效(基础URL错误、缺少环境变量、虚拟密钥限制等)。请检查提供商设置。"}diff --git a/locales/zh-TW/modelRuntime.json b/locales/zh-TW/modelRuntime.jsonindex 3c298aca45f..cd97275ffe2 100644--- a/locales/zh-TW/modelRuntime.json+++ b/locales/zh-TW/modelRuntime.json@@ -55,40 +55,5 @@"UpstreamGatewayError": "上游網關或代理返回錯誤。請稍後重試;如果問題持續,請檢查您的代理/端點配置。","UpstreamHttpError": "提供者返回了 HTTP 錯誤但未提供更多細節。請重試,或檢查您的請求和模型配置。","UpstreamMalformedResponse": "提供者返回了無法解析的格式錯誤響應。請重試;如果問題持續,請嘗試使用不同的模型或提供者。",- "UserConfigError": "提供者配置無效(基礎 URL 錯誤、缺少環境變數、虛擬金鑰限制等)。請檢查提供者設置。",- "heterogeneous.aborted.description": "此 {{agent}} 任務已停止。當您想繼續時,請發送新請求。",- "heterogeneous.aborted.title": "任務已停止",- "heterogeneous.agent_failed.description": "{{agent}} 在未識別的原因下停止。請將操作 ID 與機器人擁有者或支援團隊分享以進行調查。",- "heterogeneous.agent_failed.title": "代理任務失敗",- "heterogeneous.auth_required.description": "請要求機器人擁有者在運行 {{agent}} 的設備上重新登入。",- "heterogeneous.auth_required.title": "需要登入",- "heterogeneous.cli_not_found.description": "請要求機器人擁有者在運行此任務的設備上安裝或修復 {{agent}}。",- "heterogeneous.cli_not_found.title": "代理 CLI 不可用",- "heterogeneous.credit_limit.description": "請要求機器人擁有者為 {{agent}} 使用的帳戶添加額度,或切換模型。等待配額重置不會恢復這些額度。",- "heterogeneous.credit_limit.title": "額度已用盡",- "heterogeneous.invalid_request.description": "提供者拒絕了 {{agent}} 發送的請求。請嘗試新主題;如果問題持續,請將操作 ID 與支援團隊分享。",- "heterogeneous.invalid_request.title": "請求被拒絕",- "heterogeneous.max_turns.description": "{{agent}} 在完成之前已達到步驟限制。請將任務分成較小的步驟,或請機器人擁有者調整限制。",- "heterogeneous.max_turns.title": "步驟限制已達",- "heterogeneous.model_unavailable.description": "為 {{agent}} 選擇的模型不可用。請要求機器人擁有者選擇其他模型。",- "heterogeneous.model_unavailable.title": "模型不可用",- "heterogeneous.network_drop.description": "{{agent}} 在完成之前失去了連接。請重試;如果再次發生,請要求機器人擁有者檢查運行設備的網絡和代理設置。",- "heterogeneous.network_drop.title": "連接中斷",- "heterogeneous.reset": "配額將於 {{time}} (UTC) 重置。",- "heterogeneous.resume_cwd_mismatch.description": "請要求機器人擁有者恢復此 {{agent}} 會話使用的工作目錄,或開始新主題。",- "heterogeneous.resume_cwd_mismatch.title": "會話目錄已更改",- "heterogeneous.resume_thread_not_found.description": "{{agent}} 無法找到先前的會話。請開始新主題並重新發送請求。",- "heterogeneous.resume_thread_not_found.title": "先前的會話不可用",- "heterogeneous.server_overloaded.description": "{{agent}} 背後的提供者繁忙或不可用。請稍後再試。",- "heterogeneous.server_overloaded.title": "提供者暫時不可用",- "heterogeneous.server_throttle.description": "提供者暫時限制了來自 {{agent}} 的請求。請稍等片刻再試一次。",- "heterogeneous.server_throttle.title": "請求暫時受限",- "heterogeneous.unsupported_attachment.description": "{{agent}} 無法讀取附件。請移除附件或將其轉換為支持的格式,然後重新發送請求。",- "heterogeneous.unsupported_attachment.title": "附件不支持",- "heterogeneous.usage_limit.description": "{{agent}} 使用的帳戶已用盡配額。請等待配額重置,或要求機器人擁有者切換到具有可用配額的帳戶或模型。",- "heterogeneous.usage_limit.title": "使用限制已達",- "heterogeneous.window.five_hour": "會話配額已用盡。",- "heterogeneous.window.seven_day": "每週配額已用盡。",- "heterogeneous.working_directory_not_found.description": "{{agent}} 的工作目錄丟失。請要求機器人擁有者恢復它或選擇現有目錄。",- "heterogeneous.working_directory_not_found.title": "工作目錄不可用"+ "UserConfigError": "提供者配置無效(基礎 URL 錯誤、缺少環境變數、虛擬金鑰限制等)。請檢查提供者設置。"}diff --git a/packages/i18n-extractor/README.md b/packages/i18n-extractor/README.mdnew file mode 100644index 00000000000..cae60bae987--- /dev/null+++ b/packages/i18n-extractor/README.md@@ -0,0 +1,104 @@+# @lobechat/i18n-extractor++Static extraction of the translation keys a TypeScript program can reach. Starting from entry files, it follows runtime imports, finds calls to namespace-branded translators with the type checker, derives the key patterns each call can produce, and projects only the matching keys out of your catalogs.++It fails instead of guessing: opaque keys, erased translator types, unresolved local imports, runtime code hidden behind declaration files, and forbidden imports all stop extraction.++## Marker convention++A translator is any function whose type carries the phantom `__i18nNamespace` property. The property never exists at runtime; it only lets the checker see the namespace through aliases, callbacks, destructuring and package boundaries.++```ts+import type { NamespacedTranslate } from '@lobechat/i18n-extractor/marker';++export interface Translator<N extends string> {+ find: NamespacedTranslate<N, string | undefined>;+ t: NamespacedTranslate<N>;+}+```++- `NamespaceMarker<N>`: `{ readonly __i18nNamespace?: N }`.+- `Namespaced<N, F>`: `F & NamespaceMarker<N>`.+- `NamespacedTranslate<N, Result = string, Options = Record<string, unknown>>`: a branded `(key, options?) => Result`.++Calls whose result type includes `undefined` (such as `find`) are optional: their keys need not exist in the default catalog. Passing a branded translator, or an object whose `t`/`find` fields are branded, into a type without the marker fails with `namespace erased`. `t.call`, `t.apply` and `t.bind` are rejected.++## Key patterns++| Key expression | Retained keys |+| --------------------------------------------------------------------- | ---------------------------------------------------- |+| `'title'`, `const key = 'title'` | exactly `title` |+| `key: 'a' \| 'b'`, `` key: `level.${'low' \| 'high'}` `` | each member |+| `` `status.${code}` `` with `code: string` (or any non-literal value) | every key matching `status\..*` |+| `key: string` | the whole namespace, only with a `dynamicKeys` entry |+| `key: any`, `unknown`, objects | rejected |++## Orchestrator++```ts+import { extractI18n, isUseClientBoundary } from '@lobechat/i18n-extractor';++const { resources, report } = await extractI18n({+ root: '/repo',+ entries: ['src/server.ts'],+ catalog: {+ defaultLanguage: 'en-US',+ languages: () => readLanguages(),+ load: (language, namespace) => readCatalog(language, namespace),+ },+ dynamicKeys: [+ { file: 'src/errors.ts', namespace: 'error', reason: 'Codes arrive from the provider' },+ ],+ graph: { forbiddenImports: [/locales\/.*\.json$/], isBoundary: isUseClientBoundary },+});+```++| Option | Meaning |+| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `root` | Project root; `entries`, `tsconfig`, `dynamicKeys[].file` and report paths are relative to it. |+| `entries` | Files the graph starts from. `listSourceFiles(dir)` helps discover them. |+| `catalog` | `defaultLanguage`, `languages` (array or sync/async function) and `load(language, namespace)` returning a flat `Record<string, string>`. Return `{}` for a missing translation. |+| `dynamicKeys` | Allowlist for unbounded keys, matched by file and namespace. `reason` is required; a missing file fails. |+| `tsconfig` | Defaults to `tsconfig.json`. `compilerOptions` overrides the parsed options. |+| `workspace` | `{ packagesDirs }` (default `['packages']`) for `addWorkspacePaths`, or `false` to disable. |+| `graph` | `forbiddenImports`, `isBoundary`, `skip`, `mustResolve`; see `traceImportGraph`. |+| `extract` | `marker` (default `__i18nNamespace`), `translatorFields` (default `['t', 'find']`), `skip` for files that implement the translator itself. |+| `allowEmpty` | Allow a result with no translation calls. |++Every non-optional pattern must match at least one default-language key. `resources` has the shape `{ [language]: { [namespace]: { [key]: value } } }` for the default language plus every listed language. `report` records the traced file count, boundaries, import edges, call sites with their patterns, and per-namespace key counts, with paths relative to `root`.++## Building blocks++- `traceImportGraph({ root, entries, compilerOptions, forbiddenImports?, isBoundary?, skip?, mustResolve? })` transpiles each file before scanning, so type-only imports never enter the graph. Literal `import()` and `require()` are followed; non-literal ones fail. `node_modules` is not traced. A resolved declaration file fails unless it only declares string constants (a generated text asset). `forbiddenImports` is tested against both the specifier and the resolved real path. By default relative, absolute and `paths`-mapped specifiers must resolve, except asset extensions and `?query` imports. Use `skip` for generated modules.+- `isUseClientBoundary` and `hasDirective(sourceFile, directive)` build boundary predicates. Boundary files are excluded from the graph and from the type-checking program.+- `addWorkspacePaths(root, compilerOptions, { packagesDirs })` maps workspace packages to their source `exports` when they are not linked in `node_modules`, plus `workspace:<name>@<range>` aliases declared in the root manifest's `dependencies`, `overrides` or `pnpm.overrides`.+- `extractTranslationUses(program, files, options)`, `typePatterns(type)`, `selectKeys(keys, patterns)`, `assertBoundedTranslationUses(uses, allowlist)`.+- `renderResourcesModule(resources, exportName?)` and `writeIfChanged(file, content)`.++## CLI++```sh+bun packages/i18n-extractor/src/bin.ts --config i18n.config.ts+node --import tsx packages/i18n-extractor/src/bin.ts --config i18n.config.ts+```++Dependents also get an `i18n-extract` bin. The config module default-exports the `extractI18n` options plus output settings, or a function returning them:++```ts+import { defineConfig } from '@lobechat/i18n-extractor';++export default defineConfig({+ entries: ['src/server.ts'],+ catalog: { defaultLanguage: 'en', languages: ['de'], load: loadCatalog },+ output: 'src/generated/i18n.js',+ report: 'src/generated/i18n-report.json',+});+```++`root` defaults to the config file's directory, and `output` and `report` resolve against it. The output is an ES module exporting `resources` (rename with `exportName`). Both files are written only when their content changes.++## Tests++```sh+cd packages/i18n-extractor && bunx vitest run --silent='passed-only'+```diff --git a/packages/i18n-extractor/package.json b/packages/i18n-extractor/package.jsonnew file mode 100644index 00000000000..dadc22b6f46--- /dev/null+++ b/packages/i18n-extractor/package.json@@ -0,0 +1,24 @@+{+ "name": "@lobechat/i18n-extractor",+ "version": "1.0.0",+ "private": true,+ "description": "Static extraction of the translation keys reachable from TypeScript entry points",+ "exports": {+ ".": "./src/index.ts",+ "./marker": "./src/marker.ts"+ },+ "main": "./src/index.ts",+ "bin": {+ "i18n-extract": "./src/bin.ts"+ },+ "scripts": {+ "test": "vitest run"+ },+ "dependencies": {+ "typescript": "^6.0.3"+ },+ "devDependencies": {+ "@types/node": "^24.13.3",+ "vitest": "5.0.0"+ }+}diff --git a/packages/i18n-extractor/src/bin.ts b/packages/i18n-extractor/src/bin.tsnew file mode 100644index 00000000000..73d62b3eb65--- /dev/null+++ b/packages/i18n-extractor/src/bin.ts@@ -0,0 +1,8 @@+#!/usr/bin/env bun++import { runCli } from './cli';++runCli(process.argv.slice(2)).catch((error) => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/packages/i18n-extractor/src/cli.test.ts b/packages/i18n-extractor/src/cli.test.tsnew file mode 100644index 00000000000..9af38299225--- /dev/null+++ b/packages/i18n-extractor/src/cli.test.ts@@ -0,0 +1,43 @@+import { readFile, stat } from 'node:fs/promises';+import path from 'node:path';++import { expect, it, vi } from 'vitest';++import { runCli } from './cli';+import { createFixture, translatorType } from './testUtils';++it('writes the resources module and report only when they change', async () => {+ vi.spyOn(console, 'info').mockImplementation(() => {});+ const root = await createFixture({+ 'i18n.config.mjs': `export default () => ({+ catalog: {+ defaultLanguage: 'en',+ languages: ['de'],+ load: (language, namespace) => ({ en: { title: 'Title', other: 'Other' }, de: { title: 'Titel' } })[language],+ },+ entries: ['entry.ts'],+ output: 'generated/resources.js',+ report: 'generated/report.json',+});+`,+ 'entry.ts': `${translatorType} declare const t: T<"app">; t("title");`,+ 'tsconfig.json': JSON.stringify({ compilerOptions: { noLib: true, strict: true } }),+ });+ const config = path.join(root, 'i18n.config.mjs');+ const report = await runCli(['--config', config]);+ expect(report.namespaces).toEqual({ app: 1 });+ const output = path.join(root, 'generated/resources.js');+ expect(await readFile(output, 'utf8')).toContain(+ 'export const resources = {"de":{"app":{"title":"Titel"}},"en":{"app":{"title":"Title"}}};',+ );+ expect(JSON.parse(await readFile(path.join(root, 'generated/report.json'), 'utf8'))).toEqual(+ expect.objectContaining({ bytes: report.bytes, files: 1 }),+ );+ const { mtimeMs } = await stat(output);+ await runCli(['-c', config]);+ expect((await stat(output)).mtimeMs).toBe(mtimeMs);+});++it('requires a config path', async () => {+ await expect(runCli([])).rejects.toThrow('Usage: i18n-extract --config <path>');+});diff --git a/packages/i18n-extractor/src/cli.ts b/packages/i18n-extractor/src/cli.tsnew file mode 100644index 00000000000..b2424d9de3f--- /dev/null+++ b/packages/i18n-extractor/src/cli.ts@@ -0,0 +1,47 @@+import path from 'node:path';+import { pathToFileURL } from 'node:url';+import { parseArgs } from 'node:util';++import type { ExtractI18nConfig, I18nReport } from './extractI18n';+import { extractI18n } from './extractI18n';+import { renderResourcesModule, writeIfChanged } from './output';++export interface I18nExtractCliConfig extends Omit<ExtractI18nConfig, 'root'> {+ exportName?: string;+ output: string;+ report?: string;+ root?: string;+}++type ConfigExport =+ I18nExtractCliConfig | (() => I18nExtractCliConfig | Promise<I18nExtractCliConfig>);++export const defineConfig = <T extends ConfigExport>(config: T) => config;++const USAGE = 'Usage: i18n-extract --config <path>';++export const runCli = async (argv: string[]): Promise<I18nReport & { bytes: number }> => {+ const { values } = parseArgs({+ args: argv,+ options: { config: { short: 'c', type: 'string' } },+ strict: true,+ });+ if (!values.config) throw new Error(USAGE);+ const configPath = path.resolve(values.config);+ const exported = ((await import(pathToFileURL(configPath).href)) as { default?: ConfigExport })+ .default;+ if (!exported) throw new Error(`${configPath} has no default export`);+ const config = typeof exported === 'function' ? await exported() : exported;+ const root = path.resolve(path.dirname(configPath), config.root ?? '.');+ const { report, resources } = await extractI18n({ ...config, root });+ const output = renderResourcesModule(resources, config.exportName);+ await writeIfChanged(path.resolve(root, config.output), output);+ const result = { bytes: Buffer.byteLength(output), ...report };+ if (config.report)+ await writeIfChanged(path.resolve(root, config.report), `${JSON.stringify(result, null, 2)}\n`);+ console.info(+ 'i18n-extract:',+ JSON.stringify({ bytes: result.bytes, files: result.files, namespaces: result.namespaces }),+ );+ return result;+};diff --git a/packages/i18n-extractor/src/extract.test.ts b/packages/i18n-extractor/src/extract.test.tsnew file mode 100644index 00000000000..364debe0b66--- /dev/null+++ b/packages/i18n-extractor/src/extract.test.ts@@ -0,0 +1,158 @@+import path from 'node:path';++import ts from 'typescript';+import { describe, expect, it } from 'vitest';++import type { ExtractTranslationUsesOptions } from './extract';+import { assertBoundedTranslationUses, extractTranslationUses, selectKeys } from './extract';+import { createFixture, translatorType } from './testUtils';++const extract = async (code: string, options?: ExtractTranslationUsesOptions) => {+ const root = await createFixture({+ 'entry.ts': `${translatorType}\ndeclare const t: T<'chat'>;\n${code}`,+ });+ const file = path.join(root, 'entry.ts');+ return extractTranslationUses(+ ts.createProgram([file], { noLib: true, strict: true }),+ [file],+ options,+ );+};++describe('extractTranslationUses', () => {+ it('keeps literal aliases and finite unions', async () => {+ const uses = await extract(+ "const alias = t; alias('one'); declare const key: 'two' | 'three'; t(key);",+ );+ expect(uses.flatMap((use) => use.patterns)).toEqual(['one', 'two', 'three']);+ });++ it('retains all matching template keys without retaining another prefix', async () => {+ const uses = await extract(+ 'declare const code: string; const key = `response.${code}`; t(key);',+ );+ expect(selectKeys(['response.401', 'response.500', 'other.401'], uses[0].patterns)).toEqual([+ 'response.401',+ 'response.500',+ ]);+ });++ it('retains template suffixes and the namespace of a passed translator', async () => {+ const uses = await extract(+ 'function render(copy: T<"home">, kind: string) { copy(`brief.${kind}.title`); }',+ );+ expect(uses[0].namespace).toBe('home');+ expect(+ selectKeys(['brief.a.title', 'brief.b.title', 'brief.b.body'], uses[0].patterns),+ ).toEqual(['brief.a.title', 'brief.b.title']);+ });++ it('expands template literal key types', async () => {+ const uses = await extract(+ "declare const level: 'low' | 'high'; declare const key: `level.${typeof level}`; t(key);",+ );+ expect(selectKeys(['level.low', 'level.high', 'level.mid'], uses[0].patterns)).toEqual([+ 'level.high',+ 'level.low',+ ]);+ });++ it('requires explicit registration before retaining an entire namespace for an open string', async () => {+ const uses = await extract('declare const code: string; t(code);');+ expect(uses[0].patterns).toEqual(['.*']);+ expect(() => assertBoundedTranslationUses(uses, [])).toThrow(+ 'unbounded dynamic translation key',+ );+ expect(() =>+ assertBoundedTranslationUses(uses, [+ { file: uses[0].file, namespace: 'chat', reason: 'External error codes' },+ ]),+ ).not.toThrow();+ expect(() =>+ assertBoundedTranslationUses(uses, [+ { file: uses[0].file, namespace: 'home', reason: 'Another catalog' },+ ]),+ ).toThrow('unbounded dynamic translation key');+ });++ it('rejects opaque dynamic keys instead of silently omitting them', async () => {+ await expect(extract('declare const key: any; t(key);')).rejects.toThrow(+ 'Cannot statically classify translation key',+ );+ });++ it('rejects an unresolved namespace', async () => {+ await expect(extract('declare const copy: T<string>; copy("key");')).rejects.toThrow(+ 'unknown translation namespace',+ );+ });++ it('records each namespace of a union-branded translator', async () => {+ const uses = await extract('declare const copy: T<"chat" | "home">; copy("title");');+ expect(uses.map((use) => use.namespace)).toEqual(['chat', 'home']);+ });++ it('rejects losing namespace identity through a callback signature', async () => {+ await expect(+ extract('function forward(copy: (key: string) => string) { copy("lost"); } forward(t);'),+ ).rejects.toThrow('namespace erased');+ });++ it('rejects erasing a translator inside an object', async () => {+ await expect(+ extract(+ 'declare const bundle: { t: T<"chat"> }; const hidden: { t: (key: string) => string } = bundle; hidden.t("lost");',+ ),+ ).rejects.toThrow('namespace erased');+ });++ it('rejects indirect calls that bypass the typed call site', async () => {+ await expect(extract('t.call(undefined, "lost");')).rejects.toThrow(+ 'Unsupported indirect translation call',+ );+ });++ it('preserves optional translators selected with a fallback', async () => {+ const uses = await extract(+ 'declare const supplied: T<"chat"> | undefined; const copy = supplied ?? t; copy("title");',+ );+ expect(uses[0].patterns).toEqual(['title']);+ });++ it('marks calls whose result may be undefined as optional', async () => {+ const uses = await extract(+ 'declare const find: ((key: string) => string | undefined) & { __i18nNamespace?: "chat" }; find("maybe"); t("always");',+ );+ expect(uses.map((use) => use.optional)).toEqual([true, false]);+ });++ it('bounds an opaque interpolation by its fixed prefix', async () => {+ const uses = await extract('declare const key: unknown; t(`response.${key}`);');+ expect(selectKeys(['response.401', 'title'], uses[0].patterns)).toEqual(['response.401']);+ });++ it('allows inferred destructuring and dropping an unused translation method', async () => {+ const uses = await extract(+ 'declare const bundle: { t: T<"chat">; find: T<"chat"> }; const { t: copy } = bundle; copy("one"); const {t: other}: {t: T<"chat">} = bundle; other("two");',+ );+ expect(uses.flatMap((use) => use.patterns)).toEqual(['one', 'two']);+ });++ it('supports a custom marker and translator fields', async () => {+ const root = await createFixture({+ 'entry.ts':+ 'type M<N extends string> = ((key: string) => string) & { __ns?: N }; declare const bundle: { tr: M<"app"> }; const hidden: { tr: (key: string) => string } = bundle;',+ });+ const file = path.join(root, 'entry.ts');+ const program = ts.createProgram([file], { noLib: true, strict: true });+ expect(() => extractTranslationUses(program, [file], { marker: '__ns' })).not.toThrow();+ expect(() =>+ extractTranslationUses(program, [file], { marker: '__ns', translatorFields: ['tr'] }),+ ).toThrow('preserve the __ns marker');+ });++ it('skips files that implement the translator', async () => {+ const uses = await extract('declare const code: any; t(code);', { skip: () => true });+ expect(uses).toEqual([]);+ });+});diff --git a/packages/i18n-extractor/src/extract.ts b/packages/i18n-extractor/src/extract.tsnew file mode 100644index 00000000000..2b3182999e9--- /dev/null+++ b/packages/i18n-extractor/src/extract.ts@@ -0,0 +1,218 @@+import ts from 'typescript';++import { DEFAULT_NAMESPACE_MARKER } from './marker';++export interface TranslationUse {+ file: string;+ line: number;+ namespace: string;+ optional: boolean;+ patterns: string[];+}++export interface DynamicKeyEntry {+ file: string;+ namespace: string;+ reason: string;+}++export interface ExtractTranslationUsesOptions {+ marker?: string;+ skip?: (file: string) => boolean;+ translatorFields?: string[];+}++export const UNBOUNDED_PATTERN = '.*';++export const assertBoundedTranslationUses = (+ uses: TranslationUse[],+ allowlist: DynamicKeyEntry[],+) => {+ for (const use of uses) {+ if (+ use.patterns.includes(UNBOUNDED_PATTERN) &&+ !allowlist.some((entry) => entry.file === use.file && entry.namespace === use.namespace)+ )+ throw new Error(+ `${use.file}:${use.line}: unbounded dynamic translation key in ${use.namespace}; use a fixed prefix, a finite key type, or an explicit allowlist entry`,+ );+ }+};++const escape = (value: string) => value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');+const product = (left: string[], right: string[]) => left.flatMap((a) => right.map((b) => a + b));+const INDIRECT_CALLS = new Set(['apply', 'bind', 'call']);++// Patterns are anchored at selection time. Unknown strings deliberately retain every matching key.+export const typePatterns = (type: ts.Type): string[] => {+ if (type.isUnion()) return [...new Set(type.types.flatMap(typePatterns))];+ if (type.isStringLiteral()) return [escape(type.value)];+ if (type.isNumberLiteral()) return [String(type.value)];+ if (type.flags & ts.TypeFlags.TemplateLiteral) {+ const template = type as ts.TemplateLiteralType;+ return template.types.reduce(+ (patterns, value, i) =>+ product(patterns, typePatterns(value)).map(+ (pattern) => pattern + escape(template.texts[i + 1]),+ ),+ [escape(template.texts[0])],+ );+ }+ if (type.flags & (ts.TypeFlags.String | ts.TypeFlags.Number)) return [UNBOUNDED_PATTERN];+ throw new Error(+ `Cannot statically classify translation key (type flags ${type.flags}); declare a string or template-literal key domain`,+ );+};++export const extractTranslationUses = (+ program: ts.Program,+ files: string[],+ {+ marker: markerName = DEFAULT_NAMESPACE_MARKER,+ skip,+ translatorFields = ['t', 'find'],+ }: ExtractTranslationUsesOptions = {},+): TranslationUse[] => {+ const checker = program.getTypeChecker();+ const uses: TranslationUse[] = [];+ const markerOf = (type: ts.Type) => type.getProperty(markerName);+ const fieldHasMarker = (type: ts.Type, name: string, location: ts.Node) => {+ const field = type.getProperty(name);+ if (!field) return undefined;+ return Boolean(+ markerOf(checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(field, location))),+ );+ };+ const patternsFor = (node: ts.Expression, seen = new Set<ts.Node>()): string[] => {+ if (seen.has(node)) throw new Error('Cyclic translation key initializer');+ seen.add(node);+ if (ts.isStringLiteralLike(node)) return [escape(node.text)];+ if (ts.isTemplateExpression(node))+ return node.templateSpans.reduce(+ (patterns, span) =>+ product(patterns, interpolationPatterns(span.expression, seen)).map(+ (pattern) => pattern + escape(span.literal.text),+ ),+ [escape(node.head.text)],+ );+ const type = checker.getTypeAtLocation(node);+ if (type.flags & ts.TypeFlags.String && ts.isIdentifier(node)) {+ const declaration = checker.getSymbolAtLocation(node)?.valueDeclaration;+ if (+ declaration &&+ ts.isVariableDeclaration(declaration) &&+ declaration.initializer &&+ ts.isVariableDeclarationList(declaration.parent) &&+ declaration.parent.flags & ts.NodeFlags.Const+ )+ return patternsFor(declaration.initializer, seen);+ }+ return typePatterns(type);+ };+ const interpolationPatterns = (node: ts.Expression, seen: Set<ts.Node>): string[] => {+ const type = checker.getTypeAtLocation(node);+ // JS stringifies arbitrary interpolation values; a fixed surrounding pattern still bounds the resource set.+ if (+ type.flags &+ (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Object | ts.TypeFlags.BooleanLike)+ )+ return [UNBOUNDED_PATTERN];+ return patternsFor(node, new Set(seen));+ };+ for (const file of files) {+ if (skip?.(file)) continue;+ const source = program.getSourceFile(file);+ if (!source) throw new Error(`Missing source file in translation program: ${file}`);+ const assertNamespacePreserved = (node: ts.Expression) => {+ const valueType = checker.getTypeAtLocation(node);+ const marker = markerOf(valueType);+ const markedFields = translatorFields.filter((name) => fieldHasMarker(valueType, name, node));+ if (!marker && !markedFields.length) return;+ const inferredBinding = ts.isVariableDeclaration(node.parent) && !node.parent.type;+ const context = inferredBinding+ ? undefined+ : ts.isAsExpression(node.parent)+ ? checker.getTypeAtLocation(node.parent)+ : checker.getContextualType(node);+ if (context) {+ const target = checker.getNonNullableType(context);+ const erased = marker+ ? !markerOf(target)+ : markedFields.some((name) => fieldHasMarker(target, name, node) === false);+ if (erased || target.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))+ throw new Error(+ `Translation namespace erased at ${file}: ${node.getText(source)}; preserve the ${markerName} marker on the receiving type`,+ );+ }+ if (+ marker &&+ ts.isPropertyAccessExpression(node.parent) &&+ INDIRECT_CALLS.has(node.parent.name.text)+ )+ throw new Error(+ `Unsupported indirect translation call in ${file}; call the typed translator directly`,+ );+ };+ const recordCall = (node: ts.CallExpression) => {+ const marker = markerOf(checker.getTypeAtLocation(node.expression));+ if (!marker) return;+ const namespaceType = checker.getNonNullableType(+ checker.getTypeOfSymbolAtLocation(marker, node.expression),+ );+ const namespaces = namespaceType.isUnion() ? namespaceType.types : [namespaceType];+ const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;+ if (!node.arguments[0]) throw new Error(`${file}:${line}: missing translation key`);+ for (const namespace of namespaces) {+ if (!namespace.isStringLiteral())+ throw new Error(`${file}:${line}: unknown translation namespace`);+ try {+ const resultType = checker.getTypeAtLocation(node);+ const optional =+ resultType.isUnion() &&+ resultType.types.some((type) => type.flags & ts.TypeFlags.Undefined);+ uses.push({+ file,+ line,+ namespace: namespace.value,+ optional,+ patterns: patternsFor(node.arguments[0]),+ });+ } catch (error) {+ throw new Error(`${file}:${line}: ${String(error)}`, { cause: error });+ }+ }+ };+ const visit = (node: ts.Node) => {+ const parent = node.parent;+ if (parent) {+ const isIndirectCall =+ ts.isPropertyAccessExpression(parent) && INDIRECT_CALLS.has(parent.name.text);+ // Namespace erasure only happens when a value receives a contextual type.+ // Ordinary property reads and inferred bindings do not need semantic queries.+ const canHaveContext =+ !ts.isPropertyAccessExpression(parent) &&+ !ts.isExpressionStatement(parent) &&+ !(ts.isVariableDeclaration(parent) && (!parent.type || parent.name === node)) &&+ !(ts.isParameter(parent) && parent.name === node) &&+ !(ts.isCallExpression(parent) && parent.expression === node);+ if (+ (canHaveContext || isIndirectCall) &&+ (ts.isIdentifier(node) ||+ ts.isPropertyAccessExpression(node) ||+ ts.isCallExpression(node) ||+ ts.isAwaitExpression(node))+ )+ assertNamespacePreserved(node);+ if (ts.isCallExpression(node)) recordCall(node);+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ }+ return uses;+};++export const selectKeys = (keys: string[], patterns: string[]) => {+ const matchers = patterns.map((pattern) => new RegExp(`^(?:${pattern})$`, 's'));+ return keys.filter((key) => matchers.some((matcher) => matcher.test(key))).sort();+};diff --git a/packages/i18n-extractor/src/extractI18n.test.ts b/packages/i18n-extractor/src/extractI18n.test.tsnew file mode 100644index 00000000000..fcd16a215fe--- /dev/null+++ b/packages/i18n-extractor/src/extractI18n.test.ts@@ -0,0 +1,124 @@+import { writeFile } from 'node:fs/promises';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import type { Catalog, ExtractI18nConfig } from './extractI18n';+import { extractI18n } from './extractI18n';+import { createFixture, translatorType } from './testUtils';++const catalogs: Record<string, Record<string, Catalog>> = {+ 'en-US': {+ home: { 'outer.key': 'Wrapper copy', 'shadowed.key': 'Shadowed copy', 'unused': 'Unused' },+ runtimeError: { Error: 'Default error', Other: 'Other error' },+ },+ 'zh-CN': { runtimeError: { Error: '错误' } },+};++const setup = async () => {+ const root = await createFixture({+ 'src/app/route.ts': 'export { copy } from "@/copy"; export { render } from "@/runtime";',+ 'src/copy.ts': `${translatorType} declare const t: T<"home">; export const copy = () => t("outer.key");`,+ 'tsconfig.json': JSON.stringify({+ compilerOptions: {+ module: 'esnext',+ moduleResolution: 'bundler',+ noLib: true,+ paths: { '@/*': ['./src/*', './upstream/src/*'] },+ strict: true,+ },+ }),+ 'upstream/src/copy.ts': `${translatorType} declare const t: T<"home">; export const copy = () => t("shadowed.key");`,+ 'upstream/src/runtime.ts': `${translatorType} declare const t: T<"runtimeError">; export const render = (code: string) => t(code);`,+ });+ const config: ExtractI18nConfig = {+ catalog: {+ defaultLanguage: 'en-US',+ languages: () => ['zh-CN', 'ja-JP'],+ load: async (language, namespace) => catalogs[language]?.[namespace] ?? {},+ },+ dynamicKeys: [+ {+ file: 'upstream/src/runtime.ts',+ namespace: 'runtimeError',+ reason: 'Provider error codes arrive at runtime',+ },+ ],+ entries: ['src/app/route.ts'],+ root,+ };+ return { config, root };+};++describe('extractI18n', () => {+ it('projects reachable keys for every language and reports call sites', async () => {+ const { config } = await setup();+ const { report, resources } = await extractI18n(config);+ expect(resources).toEqual({+ 'en-US': {+ home: { 'outer.key': 'Wrapper copy' },+ runtimeError: { Error: 'Default error', Other: 'Other error' },+ },+ 'ja-JP': { home: {}, runtimeError: {} },+ 'zh-CN': { home: {}, runtimeError: { Error: '错误' } },+ });+ expect(report.namespaces).toEqual({ home: 1, runtimeError: 2 });+ expect(report.files).toBe(3);+ expect(report.uses).toContainEqual(+ expect.objectContaining({ file: 'upstream/src/runtime.ts', patterns: ['.*'] }),+ );+ expect(report.imports).toContainEqual(+ expect.objectContaining({ from: 'src/app/route.ts', to: 'src/copy.ts' }),+ );+ });++ it('requires an allowlist entry with a reason for unbounded keys', async () => {+ const { config } = await setup();+ await expect(extractI18n({ ...config, dynamicKeys: [] })).rejects.toThrow(+ 'unbounded dynamic translation key',+ );+ await expect(+ extractI18n({+ ...config,+ dynamicKeys: [{ file: 'upstream/src/runtime.ts', namespace: 'runtimeError', reason: ' ' }],+ }),+ ).rejects.toThrow('requires a reason');+ });++ it('rejects stale allowlist entries', async () => {+ const { config } = await setup();+ await expect(+ extractI18n({+ ...config,+ dynamicKeys: [{ file: 'src/missing.ts', namespace: 'home', reason: 'Stale registration' }],+ }),+ ).rejects.toThrow('ENOENT');+ });++ it('rejects required keys missing from the default catalog', async () => {+ const { config, root } = await setup();+ await writeFile(+ path.join(root, 'src/copy.ts'),+ `${translatorType} declare const t: T<"home">; export const copy = () => t("missing.key");`,+ );+ await expect(extractI18n(config)).rejects.toThrow('no en-US translation matches home:missing');+ });++ it('allows optional lookups of keys missing from the default catalog', async () => {+ const { config, root } = await setup();+ await writeFile(+ path.join(root, 'src/copy.ts'),+ 'declare const find: ((key: string) => string | undefined) & { __i18nNamespace?: "home" }; export const copy = () => find("missing.key");',+ );+ const { resources } = await extractI18n(config);+ expect(resources['en-US'].home).toEqual({});+ });++ it('refuses to emit empty resources unless allowed', async () => {+ const { config, root } = await setup();+ await writeFile(path.join(root, 'src/app/route.ts'), 'export const value = 1;');+ await expect(extractI18n(config)).rejects.toThrow('No translation calls found');+ const { resources } = await extractI18n({ ...config, allowEmpty: true, dynamicKeys: [] });+ expect(resources).toEqual({ 'en-US': {}, 'ja-JP': {}, 'zh-CN': {} });+ });+});diff --git a/packages/i18n-extractor/src/extractI18n.ts b/packages/i18n-extractor/src/extractI18n.tsnew file mode 100644index 00000000000..d874fa1eacb--- /dev/null+++ b/packages/i18n-extractor/src/extractI18n.ts@@ -0,0 +1,162 @@+import { realpath } from 'node:fs/promises';+import path from 'node:path';++import ts from 'typescript';++import type { DynamicKeyEntry, ExtractTranslationUsesOptions, TranslationUse } from './extract';+import { assertBoundedTranslationUses, extractTranslationUses, selectKeys } from './extract';+import type {+ AddWorkspacePathsOptions,+ ImportEdge,+ ImportGraph,+ TraceImportGraphOptions,+} from './graph';+import { addWorkspacePaths, traceImportGraph } from './graph';++export type Catalog = Record<string, string>;++export type Resources = Record<string, Record<string, Catalog>>;++export interface CatalogAdapter {+ defaultLanguage: string;+ languages: string[] | (() => Promise<string[]> | string[]);+ load: (language: string, namespace: string) => Promise<Catalog> | Catalog;+}++export interface ExtractI18nConfig {+ allowEmpty?: boolean;+ catalog: CatalogAdapter;+ compilerOptions?: ts.CompilerOptions;+ dynamicKeys?: DynamicKeyEntry[];+ entries: string[];+ extract?: ExtractTranslationUsesOptions;+ graph?: Pick<TraceImportGraphOptions, 'forbiddenImports' | 'isBoundary' | 'mustResolve' | 'skip'>;+ root: string;+ tsconfig?: string;+ workspace?: AddWorkspacePathsOptions | false;+}++export interface I18nReport {+ boundaries: string[];+ files: number;+ imports: ImportEdge[];+ namespaces: Record<string, number>;+ uses: TranslationUse[];+}++export interface ExtractI18nResult {+ report: I18nReport;+ resources: Resources;+}++const readCompilerOptions = (file: string): ts.CompilerOptions => {+ const config = ts.readConfigFile(file, ts.sys.readFile);+ if (config.error)+ throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'));+ return ts.parseJsonConfigFileContent(config.config, ts.sys, path.dirname(file)).options;+};++const createAnalysisProgram = (graph: ImportGraph, compilerOptions: ts.CompilerOptions) => {+ const host = ts.createCompilerHost(compilerOptions);+ const getSourceFile = host.getSourceFile.bind(host);+ const boundaries = new Set(graph.boundaries);+ // Boundary modules resolve as missing so the checker never loads the graph behind them.+ host.getSourceFile = (file, ...args) =>+ boundaries.has(file) ? undefined : getSourceFile(file, ...args);+ return ts.createProgram(graph.files, { ...compilerOptions, noEmit: true }, host);+};++const pick = (values: Catalog, patterns: string[]) =>+ Object.fromEntries(selectKeys(Object.keys(values), patterns).map((key) => [key, values[key]]));++export const extractI18n = async (config: ExtractI18nConfig): Promise<ExtractI18nResult> => {+ const root = await realpath(config.root);+ const compilerOptions: ts.CompilerOptions = {+ ...readCompilerOptions(path.resolve(root, config.tsconfig ?? 'tsconfig.json')),+ ...config.compilerOptions,+ };+ if (config.workspace !== false) await addWorkspacePaths(root, compilerOptions, config.workspace);+ const graph = await traceImportGraph({+ ...config.graph,+ compilerOptions,+ entries: config.entries,+ root,+ });+ const uses = extractTranslationUses(+ createAnalysisProgram(graph, compilerOptions),+ graph.files,+ config.extract,+ );+ const dynamicKeys = await Promise.all(+ (config.dynamicKeys ?? []).map(async (entry) => {+ if (!entry.reason?.trim())+ throw new Error(+ `Dynamic translation key entry ${entry.file} (${entry.namespace}) requires a reason`,+ );+ return { ...entry, file: await realpath(path.resolve(root, entry.file)) };+ }),+ );+ assertBoundedTranslationUses(uses, dynamicKeys);+ if (!uses.length && !config.allowEmpty)+ throw new Error('No translation calls found; refusing to emit empty resources');++ const { catalog } = config;+ const namespaces = [...new Set(uses.map((use) => use.namespace))].sort();+ const defaults: Record<string, Catalog> = {};+ for (const namespace of namespaces)+ defaults[namespace] = await catalog.load(catalog.defaultLanguage, namespace);+ for (const use of uses) {+ if (use.optional) continue;+ const keys = Object.keys(defaults[use.namespace]);+ for (const pattern of use.patterns)+ if (!selectKeys(keys, [pattern]).length)+ throw new Error(+ `${use.file}:${use.line}: no ${catalog.defaultLanguage} translation matches ${use.namespace}:${pattern}`,+ );+ }+ const patterns = Object.fromEntries(+ namespaces.map((namespace) => [+ namespace,+ [+ ...new Set(+ uses.filter((use) => use.namespace === namespace).flatMap((use) => use.patterns),+ ),+ ],+ ]),+ );+ const listed =+ typeof catalog.languages === 'function' ? await catalog.languages() : catalog.languages;+ const languages = [...new Set([catalog.defaultLanguage, ...listed])].sort();+ const resources: Resources = {};+ for (const language of languages) {+ resources[language] = {};+ for (const namespace of namespaces) {+ const values =+ language === catalog.defaultLanguage+ ? defaults[namespace]+ : await catalog.load(language, namespace);+ resources[language][namespace] = pick(values, patterns[namespace]);+ }+ }++ const relative = (file: string) => path.relative(root, file);+ return {+ report: {+ boundaries: graph.boundaries.map(relative),+ files: graph.files.length,+ imports: graph.imports.map((edge) => ({+ ...edge,+ from: relative(edge.from),+ to: relative(edge.to),+ })),+ namespaces: Object.fromEntries(+ namespaces.map((namespace) => [+ namespace,+ Object.keys(resources[catalog.defaultLanguage][namespace]).length,+ ]),+ ),+ uses: uses.map((use) => ({ ...use, file: relative(use.file) })),+ },+ resources,+ };+};diff --git a/packages/i18n-extractor/src/graph.test.ts b/packages/i18n-extractor/src/graph.test.tsnew file mode 100644index 00000000000..9a1017a7fe4--- /dev/null+++ b/packages/i18n-extractor/src/graph.test.ts@@ -0,0 +1,202 @@+import path from 'node:path';++import ts from 'typescript';+import { expect, it } from 'vitest';++import { extractTranslationUses } from './extract';+import { addWorkspacePaths, isUseClientBoundary, listSourceFiles, traceImportGraph } from './graph';+import { createFixture } from './testUtils';++const names = (files: string[]) => files.map((file) => path.basename(file)).sort();++it('traces workspace exports, aliases and re-exports without pulling type-only imports', async () => {+ const root = await createFixture({+ 'entry.ts':+ "import { render } from '@example/copy'; render(); import type { Frontend } from './frontend';",+ 'frontend.ts': "import './unresolvable'; export interface Frontend {}",+ 'packages/copy/package.json': JSON.stringify({+ exports: { '.': './src/index.ts' },+ name: '@example/copy',+ }),+ 'packages/copy/src/index.ts': "export { render } from './render';",+ 'packages/copy/src/render.ts':+ "import { t } from '@/translation'; export const render = () => t('shared.key');",+ 'translation.ts':+ "export declare const t: ((key: string) => string) & { __i18nNamespace?: 'home' };",+ });+ const compilerOptions: ts.CompilerOptions = {+ module: ts.ModuleKind.ESNext,+ moduleResolution: ts.ModuleResolutionKind.Bundler,+ noLib: true,+ paths: { '@/translation': [path.join(root, 'translation.ts')] },+ strict: true,+ };+ await addWorkspacePaths(root, compilerOptions);+ const graph = await traceImportGraph({ compilerOptions, entries: ['entry.ts'], root });+ expect(names(graph.files)).not.toContain('frontend.ts');+ const uses = extractTranslationUses(ts.createProgram(graph.files, compilerOptions), graph.files);+ expect(uses).toEqual([+ expect.objectContaining({ namespace: 'home', patterns: ['shared\\.key'] }),+ ]);+});++it('looks up workspace packages in configurable directories', async () => {+ const root = await createFixture({+ 'entry.ts': "export { render } from '@example/lib';",+ 'libs/nested/lib/package.json': JSON.stringify({+ exports: './src/index.ts',+ name: '@example/lib',+ }),+ 'libs/nested/lib/src/index.ts': 'export const render = () => "copy";',+ });+ const compilerOptions: ts.CompilerOptions = { moduleResolution: ts.ModuleResolutionKind.Bundler };+ await addWorkspacePaths(root, compilerOptions);+ expect(compilerOptions.paths).toBeUndefined();+ await addWorkspacePaths(root, compilerOptions, { packagesDirs: ['libs'] });+ const graph = await traceImportGraph({ compilerOptions, entries: ['entry.ts'], root });+ expect(names(graph.files)).toEqual(['entry.ts', 'index.ts']);+});++it('fails on unresolved dynamic imports', async () => {+ const root = await createFixture({+ 'entry.ts': 'declare const name: string; import(`./${name}`);',+ });+ await expect(+ traceImportGraph({ compilerOptions: {}, entries: ['entry.ts'], root }),+ ).rejects.toThrow('Unresolved dynamic import');+});++it('fails on unresolved local imports but tolerates assets', async () => {+ const root = await createFixture({+ 'asset.ts': "import './styles.css'; import './raw.ts?raw'; import 'external-package';",+ 'entry.ts': "import './missing';",+ });+ await expect(+ traceImportGraph({ compilerOptions: {}, entries: ['entry.ts'], root }),+ ).rejects.toThrow('Unresolved import');+ const graph = await traceImportGraph({ compilerOptions: {}, entries: ['asset.ts'], root });+ expect(names(graph.files)).toEqual(['asset.ts']);+});++it('does not silently skip a workspace export that resolves only to declarations', async () => {+ const root = await createFixture({+ 'entry.ts': "import { render } from '@example/copy'; render();",+ 'packages/copy/index.d.ts': 'export declare function render(): string;',+ 'packages/copy/index.js': 'export const render = () => "copy";',+ 'packages/copy/package.json': JSON.stringify({+ exports: { '.': { default: './index.js', types: './index.d.ts' } },+ name: '@example/copy',+ }),+ });+ const compilerOptions: ts.CompilerOptions = { moduleResolution: ts.ModuleResolutionKind.Bundler };+ await addWorkspacePaths(root, compilerOptions);+ await expect(traceImportGraph({ compilerOptions, entries: ['entry.ts'], root })).rejects.toThrow(+ 'Cannot trace runtime through a declaration file',+ );+});++it('rejects forbidden imports by specifier and by resolved file', async () => {+ const root = await createFixture({+ 'catalog/home.ts': 'export default { title: "Home" };',+ 'direct.ts': "import home from '@/locales/default/home'; console.log(home);",+ 'indirect.ts': "import home from './catalog/home'; console.log(home);",+ });+ const options = {+ compilerOptions: {},+ forbiddenImports: [/locales\/default/, /\/catalog\//],+ root,+ };+ await expect(traceImportGraph({ ...options, entries: ['direct.ts'] })).rejects.toThrow(+ 'Forbidden import',+ );+ await expect(traceImportGraph({ ...options, entries: ['indirect.ts'] })).rejects.toThrow(+ 'Forbidden import',+ );+});++it('stops at client boundaries and follows literal lazy imports', async () => {+ const root = await createFixture({+ 'client.ts': "'use client'; import i18next from 'i18next'; i18next.t('frontend');",+ 'entry.ts':+ "import './client'; export const lazy = () => import('./server'); const legacy = require('./legacy');",+ 'legacy.ts': 'export const value = 2;',+ 'server.ts': 'export const value = 1;',+ });+ const graph = await traceImportGraph({+ compilerOptions: {},+ entries: ['entry.ts'],+ isBoundary: isUseClientBoundary,+ root,+ });+ expect(names(graph.boundaries)).toEqual(['client.ts']);+ expect(names(graph.files)).toEqual(['entry.ts', 'legacy.ts', 'server.ts']);+});++it('skips configured files such as generated output', async () => {+ const root = await createFixture({+ 'entry.ts': "import { resources } from './generated/resources'; console.log(resources);",+ 'generated/resources.d.ts': 'export declare const resources: Record<string, unknown>;',+ 'generated/resources.js': 'export const resources = {};',+ });+ const options = { compilerOptions: {}, entries: ['entry.ts'], root };+ await expect(traceImportGraph(options)).rejects.toThrow('declaration file');+ const graph = await traceImportGraph({+ ...options,+ skip: (file) => file.includes(`${path.sep}generated${path.sep}`),+ });+ expect(names(graph.files)).toEqual(['entry.ts']);+});++it('accepts declarations for text assets generated later in the build', async () => {+ const root = await createFixture({+ 'entry.ts': 'export const page = () => import("./src/app/htmlTemplate");',+ 'src/app/htmlTemplate.d.ts': 'export declare const htmlTemplate: string;',+ });+ const graph = await traceImportGraph({ compilerOptions: {}, entries: ['entry.ts'], root });+ expect(names(graph.files)).toEqual(['entry.ts']);+});++it('rejects runtime declarations that could hide translation calls', async () => {+ const root = await createFixture({+ 'entry.ts': 'export { render } from "./src/render";',+ 'src/render.d.ts': 'export declare function render(): string;',+ });+ await expect(+ traceImportGraph({ compilerOptions: {}, entries: ['entry.ts'], root }),+ ).rejects.toThrow('Cannot trace runtime');+});++it('resolves declared workspace aliases even when installed links point at a stub', async () => {+ const root = await createFixture({+ 'entry.ts': "export { render } from '@example/copy/details';",+ 'node_modules/@example/copy/index.ts': 'export {};',+ 'node_modules/@example/copy/package.json': JSON.stringify({+ exports: { '.': './index.ts' },+ name: '@example/copy',+ }),+ 'package.json': JSON.stringify({+ dependencies: { '@example/copy': 'workspace:@example/implementation@*' },+ }),+ 'packages/copy/package.json': JSON.stringify({+ exports: { './details': { default: './src/details.ts' } },+ name: '@example/implementation',+ }),+ 'packages/copy/src/details.ts': 'export const render = () => "copy";',+ });+ const compilerOptions: ts.CompilerOptions = { moduleResolution: ts.ModuleResolutionKind.Bundler };+ await addWorkspacePaths(root, compilerOptions);+ const graph = await traceImportGraph({ compilerOptions, entries: ['entry.ts'], root });+ expect(names(graph.files)).toContain('details.ts');+});++it('lists source files without tests, declarations or ignored directories', async () => {+ const root = await createFixture({+ 'src/a.ts': '',+ 'src/b.test.ts': '',+ 'src/c.d.ts': '',+ 'src/dist/d.ts': '',+ 'src/nested/e.tsx': '',+ 'src/notes.md': '',+ });+ expect(names(await listSourceFiles(path.join(root, 'src')))).toEqual(['a.ts', 'e.tsx']);+});diff --git a/packages/i18n-extractor/src/graph.ts b/packages/i18n-extractor/src/graph.tsnew file mode 100644index 00000000000..defaa224ead--- /dev/null+++ b/packages/i18n-extractor/src/graph.ts@@ -0,0 +1,322 @@+import { access, readdir, readFile, realpath } from 'node:fs/promises';+import path from 'node:path';++import ts from 'typescript';++export interface ImportEdge {+ from: string;+ specifier: string;+ to: string;+}++export interface ImportGraph {+ boundaries: string[];+ files: string[];+ imports: ImportEdge[];+}++export interface TraceImportGraphOptions {+ compilerOptions: ts.CompilerOptions;+ entries: string[];+ forbiddenImports?: RegExp[];+ isBoundary?: (file: string, sourceFile: ts.SourceFile) => boolean;+ mustResolve?: (specifier: string, file: string) => boolean;+ root: string;+ skip?: (file: string) => boolean;+}++export interface AddWorkspacePathsOptions {+ packagesDirs?: string[];+}++const CODE_FILE = /\.[cm]?[jt]sx?$/;+const DECLARATION_FILE = /\.d\.[cm]?ts$/;+const TEST_FILE = /\.(?:test|spec|d)\.[cm]?tsx?$/;+const IGNORED_DIRECTORIES = new Set(['dist', 'node_modules']);+const ASSET_EXTENSIONS = new Set([+ '.avif',+ '.css',+ '.gif',+ '.gql',+ '.graphql',+ '.html',+ '.ico',+ '.jpeg',+ '.jpg',+ '.json',+ '.less',+ '.md',+ '.mdx',+ '.png',+ '.sass',+ '.scss',+ '.sql',+ '.svg',+ '.toml',+ '.ttf',+ '.txt',+ '.wasm',+ '.webp',+ '.woff',+ '.woff2',+ '.yaml',+ '.yml',+]);++const isMissing = (error: unknown) => (error as NodeJS.ErrnoException).code === 'ENOENT';++const readJson = async <T>(file: string): Promise<T | undefined> => {+ try {+ return JSON.parse(await readFile(file, 'utf8')) as T;+ } catch (error) {+ if (isMissing(error)) return undefined;+ throw error;+ }+};++const scriptKind = (file: string) =>+ file.endsWith('.tsx')+ ? ts.ScriptKind.TSX+ : file.endsWith('.jsx')+ ? ts.ScriptKind.JSX+ : /\.[cm]?js$/.test(file)+ ? ts.ScriptKind.JS+ : ts.ScriptKind.TS;++export const listSourceFiles = async (directory: string): Promise<string[]> => {+ const entries = await readdir(directory, { withFileTypes: true });+ const files = await Promise.all(+ entries+ .filter((entry) => !entry.name.startsWith('.') && !IGNORED_DIRECTORIES.has(entry.name))+ .map(async (entry) => {+ const file = path.join(directory, entry.name);+ if (entry.isDirectory()) return listSourceFiles(file);+ return /\.[cm]?tsx?$/.test(file) && !TEST_FILE.test(file) ? [file] : [];+ }),+ );+ return files.flat().sort();+};++export const hasDirective = (sourceFile: ts.SourceFile, directive: string) => {+ for (const statement of sourceFile.statements) {+ if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression))+ return false;+ if (statement.expression.text === directive) return true;+ }+ return false;+};++export const isUseClientBoundary = (_file: string, sourceFile: ts.SourceFile) =>+ hasDirective(sourceFile, 'use client');++const matchesPathPattern = (specifier: string, pattern: string) => {+ const star = pattern.indexOf('*');+ if (star === -1) return specifier === pattern;+ return (+ specifier.length >= pattern.length - 1 &&+ specifier.startsWith(pattern.slice(0, star)) &&+ specifier.endsWith(pattern.slice(star + 1))+ );+};++export const defaultMustResolve =+ (compilerOptions: ts.CompilerOptions) =>+ (specifier: string): boolean => {+ if (specifier.includes('?') || ASSET_EXTENSIONS.has(path.extname(specifier).toLowerCase()))+ return false;+ if (specifier.startsWith('.') || path.isAbsolute(specifier)) return true;+ return Object.keys(compilerOptions.paths ?? {}).some((pattern) =>+ matchesPathPattern(specifier, pattern),+ );+ };++// Declarations of generated text assets have no executable imports or translation calls.+const isInertDeclaration = (declaration: ts.SourceFile) =>+ declaration.statements.length > 0 &&+ declaration.statements.every(+ (statement) =>+ ts.isVariableStatement(statement) &&+ statement.declarationList.declarations.every(+ (item) => item.type?.kind === ts.SyntaxKind.StringKeyword && !item.initializer,+ ),+ );++const collectSpecifiers = (file: string, ast: ts.SourceFile) => {+ const specifiers: string[] = [];+ const collect = (node: ts.Node) => {+ let argument: ts.Node | undefined;+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier)+ argument = node.moduleSpecifier;+ else if (+ ts.isCallExpression(node) &&+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||+ (ts.isIdentifier(node.expression) && node.expression.text === 'require'))+ )+ argument = node.arguments[0];+ if (argument) {+ if (!ts.isStringLiteralLike(argument))+ throw new Error(`Unresolved dynamic import in ${file}: ${argument.getText(ast)}`);+ specifiers.push(argument.text);+ }+ ts.forEachChild(node, collect);+ };+ collect(ast);+ return specifiers;+};++export const traceImportGraph = async ({+ compilerOptions,+ entries,+ forbiddenImports = [],+ isBoundary,+ mustResolve = defaultMustResolve(compilerOptions),+ root,+ skip,+}: TraceImportGraphOptions): Promise<ImportGraph> => {+ const cache = ts.createModuleResolutionCache(root, (file) => file, compilerOptions);+ const transpileOptions: ts.CompilerOptions = {+ ...compilerOptions,+ jsx: ts.JsxEmit.Preserve,+ module: ts.ModuleKind.ESNext,+ verbatimModuleSyntax: false,+ };+ const seen = new Set<string>();+ const boundaries = new Set<string>();+ const imports: ImportEdge[] = [];+ const assertAllowed = (file: string, reference: string) => {+ if (forbiddenImports.some((pattern) => pattern.test(reference)))+ throw new Error(`Forbidden import: ${file} -> ${reference}`);+ };+ const visit = async (input: string) => {+ const file = await realpath(input);+ if (seen.has(file) || boundaries.has(file) || skip?.(file)) return;+ const source = await readFile(file, 'utf8');+ if (isBoundary) {+ const original = ts.createSourceFile(+ file,+ source,+ ts.ScriptTarget.Latest,+ true,+ scriptKind(file),+ );+ if (isBoundary(file, original)) {+ boundaries.add(file);+ return;+ }+ }+ seen.add(file);+ const output = ts.transpileModule(source, {+ compilerOptions: transpileOptions,+ fileName: file,+ }).outputText;+ const ast = ts.createSourceFile(file, output, ts.ScriptTarget.Latest, true, ts.ScriptKind.JSX);+ for (const specifier of collectSpecifiers(file, ast)) {+ assertAllowed(file, specifier);+ const resolution = ts.resolveModuleName(+ specifier,+ file,+ compilerOptions,+ ts.sys,+ cache,+ ).resolvedModule;+ if (!resolution) {+ if (mustResolve(specifier, file))+ throw new Error(`Unresolved import: ${file} -> ${specifier}`);+ continue;+ }+ const target = await realpath(resolution.resolvedFileName);+ if (skip?.(target)) continue;+ assertAllowed(file, target);+ if (target.includes(`${path.sep}node_modules${path.sep}`)) continue;+ if (DECLARATION_FILE.test(target)) {+ const declaration = ts.createSourceFile(+ target,+ await readFile(target, 'utf8'),+ ts.ScriptTarget.Latest,+ true,+ );+ if (!isInertDeclaration(declaration))+ throw new Error(+ `Cannot trace runtime through a declaration file: ${file} -> ${target}; expose the runtime source to the extractor`,+ );+ continue;+ }+ if (!CODE_FILE.test(target)) continue;+ imports.push({ from: file, specifier, to: target });+ await visit(target);+ }+ };+ for (const entry of entries) await visit(path.resolve(root, entry));+ return { boundaries: [...boundaries].sort(), files: [...seen].sort(), imports };+};++interface RootManifest {+ dependencies?: Record<string, string>;+ overrides?: Record<string, string>;+ pnpm?: { overrides?: Record<string, string> };+}++interface PackageManifest {+ exports?: string | Record<string, string | { default?: string; types?: string }>;+ name?: string;+}++export const addWorkspacePaths = async (+ root: string,+ compilerOptions: ts.CompilerOptions,+ { packagesDirs = ['packages'] }: AddWorkspacePathsOptions = {},+) => {+ const rootManifest = (await readJson<RootManifest>(path.join(root, 'package.json'))) ?? {};+ const aliases = new Map<string, string[]>();+ for (const [name, value] of Object.entries({+ ...rootManifest.dependencies,+ ...rootManifest.overrides,+ ...rootManifest.pnpm?.overrides,+ })) {+ const target = /^workspace:(.+)@[^@]+$/.exec(value)?.[1];+ if (target) aliases.set(target, [...(aliases.get(target) ?? []), name]);+ }+ const register = async (directory: string, manifest: PackageManifest) => {+ if (!manifest.name) return;+ const names = [...(aliases.get(manifest.name) ?? [])];+ // Installed links stay authoritative; only packages missing from node_modules need a source path.+ try {+ await access(path.join(root, 'node_modules', manifest.name, 'package.json'));+ } catch {+ names.push(manifest.name);+ }+ if (!names.length) return;+ const exports =+ typeof manifest.exports === 'string' ? { '.': manifest.exports } : (manifest.exports ?? {});+ for (const [subpath, target] of Object.entries(exports)) {+ const value = typeof target === 'string' ? target : (target.types ?? target.default);+ if (!value) throw new Error(`Unsupported workspace export: ${manifest.name}/${subpath}`);+ for (const packageName of names) {+ const name = packageName + (subpath === '.' ? '' : subpath.slice(1));+ compilerOptions.paths ??= {};+ compilerOptions.paths[name] ??= [path.resolve(directory, value)];+ }+ }+ };+ const visit = async (directory: string) => {+ const manifest = await readJson<PackageManifest>(path.join(directory, 'package.json'));+ if (manifest) return register(directory, manifest);+ let entries;+ try {+ entries = await readdir(directory, { withFileTypes: true });+ } catch (error) {+ if (isMissing(error)) return;+ throw error;+ }+ for (const entry of entries)+ if (+ entry.isDirectory() &&+ !entry.name.startsWith('.') &&+ !IGNORED_DIRECTORIES.has(entry.name) &&+ entry.name !== 'src'+ )+ await visit(path.join(directory, entry.name));+ };+ for (const directory of packagesDirs) await visit(path.resolve(root, directory));+ return compilerOptions;+};diff --git a/packages/i18n-extractor/src/index.ts b/packages/i18n-extractor/src/index.tsnew file mode 100644index 00000000000..30b5d8afe15--- /dev/null+++ b/packages/i18n-extractor/src/index.ts@@ -0,0 +1,36 @@+export type { I18nExtractCliConfig } from './cli';+export { defineConfig, runCli } from './cli';+export type { DynamicKeyEntry, ExtractTranslationUsesOptions, TranslationUse } from './extract';+export {+ assertBoundedTranslationUses,+ extractTranslationUses,+ selectKeys,+ typePatterns,+ UNBOUNDED_PATTERN,+} from './extract';+export type {+ Catalog,+ CatalogAdapter,+ ExtractI18nConfig,+ ExtractI18nResult,+ I18nReport,+ Resources,+} from './extractI18n';+export { extractI18n } from './extractI18n';+export type {+ AddWorkspacePathsOptions,+ ImportEdge,+ ImportGraph,+ TraceImportGraphOptions,+} from './graph';+export {+ addWorkspacePaths,+ defaultMustResolve,+ hasDirective,+ isUseClientBoundary,+ listSourceFiles,+ traceImportGraph,+} from './graph';+export type { Namespaced, NamespacedTranslate, NamespaceMarker } from './marker';+export { DEFAULT_NAMESPACE_MARKER } from './marker';+export { renderResourcesModule, writeIfChanged } from './output';diff --git a/packages/i18n-extractor/src/marker.ts b/packages/i18n-extractor/src/marker.tsnew file mode 100644index 00000000000..347ff32ef40--- /dev/null+++ b/packages/i18n-extractor/src/marker.ts@@ -0,0 +1,13 @@+export const DEFAULT_NAMESPACE_MARKER = '__i18nNamespace';++export interface NamespaceMarker<N extends string> {+ readonly __i18nNamespace?: N;+}++export type Namespaced<N extends string, F> = F & NamespaceMarker<N>;++export type NamespacedTranslate<+ N extends string,+ Result = string,+ Options = Record<string, unknown>,+> = Namespaced<N, (key: string, options?: Options) => Result>;diff --git a/packages/i18n-extractor/src/output.ts b/packages/i18n-extractor/src/output.tsnew file mode 100644index 00000000000..c2cb4b3e2bb--- /dev/null+++ b/packages/i18n-extractor/src/output.ts@@ -0,0 +1,20 @@+import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';+import path from 'node:path';++import type { Resources } from './extractI18n';++export const renderResourcesModule = (resources: Resources, exportName = 'resources') =>+ `// Generated by i18n-extract. Do not edit.\nexport const ${exportName} = ${JSON.stringify(resources)};\n`;++export const writeIfChanged = async (file: string, content: string) => {+ try {+ if ((await readFile(file, 'utf8')) === content) return false;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ await mkdir(path.dirname(file), { recursive: true });+ const temporary = `${file}.${process.pid}.tmp`;+ await writeFile(temporary, content);+ await rename(temporary, file);+ return true;+};diff --git a/packages/i18n-extractor/src/testUtils.ts b/packages/i18n-extractor/src/testUtils.tsnew file mode 100644index 00000000000..fdecba412c1--- /dev/null+++ b/packages/i18n-extractor/src/testUtils.ts@@ -0,0 +1,26 @@+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach } from 'vitest';++const directories: string[] = [];++afterEach(async () => {+ await Promise.all(+ directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })),+ );+});++export const createFixture = async (files: Record<string, string>) => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'i18n-extractor-'));+ directories.push(root);+ for (const [file, content] of Object.entries(files)) {+ await mkdir(path.dirname(path.join(root, file)), { recursive: true });+ await writeFile(path.join(root, file), content);+ }+ return root;+};++export const translatorType =+ 'type T<N extends string> = ((key: string) => string) & { __i18nNamespace?: N };';diff --git a/packages/i18n-extractor/tsconfig.json b/packages/i18n-extractor/tsconfig.jsonnew file mode 100644index 00000000000..91318080992--- /dev/null+++ b/packages/i18n-extractor/tsconfig.json@@ -0,0 +1,8 @@+{+ "compilerOptions": {+ "outDir": "./dist",+ "types": ["node", "vitest/globals"]+ },+ "extends": "../../tsconfig.json",+ "include": ["src/**/*.ts"]+}diff --git a/packages/i18n-extractor/vitest.config.mts b/packages/i18n-extractor/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/i18n-extractor/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});diff --git a/packages/locales/src/default/modelRuntime.ts b/packages/locales/src/default/modelRuntime.tsindex 64d4bc7c69f..1dec300f8f1 100644--- a/packages/locales/src/default/modelRuntime.ts+++ b/packages/locales/src/default/modelRuntime.ts@@ -1,165 +1,114 @@export default {- 'AccountDeactivated':+ AccountDeactivated:'Your account has been deactivated or suspended. This may be due to policy, security, or account review reasons. Please contact the provider support for assistance.',- 'AgentRuntimeError':+ AgentRuntimeError:'Lobe language model runtime execution error. Please troubleshoot or retry based on the following information.',- 'CapabilityNotSupported':+ CapabilityNotSupported:'Sorry, this model does not support the requested capability (such as vision input or tool calling). Please switch to a model that supports it.',- 'ClientLlmExecutorLost':+ ClientLlmExecutorLost:'The device running {{provider}} for this conversation stopped responding before the reply finished — it may have been closed, refreshed or disconnected. Keep the LobeHub window open and try again.',- 'ClientLlmExecutorUnavailable':+ ClientLlmExecutorUnavailable:'{{provider}} can only be reached from your own device, but no open LobeHub window picked up the request. Open LobeHub on the device where {{provider}} runs, then retry.',- 'ClientLlmTimeout':+ ClientLlmTimeout:'{{provider}} on your device did not respond in time. Make sure the model is running and loaded, then try again.',- 'ComfyUIBizError':+ ComfyUIBizError:'An error occurred while requesting the ComfyUI service. Please troubleshoot using the information below or try again.',- 'ComfyUIEmptyResult':+ ComfyUIEmptyResult:'No image was generated by ComfyUI. Please check the model configuration or try again.',- 'ComfyUIModelError': 'Failed to load the ComfyUI model. Please ensure the model file exists.',- 'ComfyUIServiceUnavailable':+ ComfyUIModelError: 'Failed to load the ComfyUI model. Please ensure the model file exists.',+ ComfyUIServiceUnavailable:'Failed to connect to the ComfyUI service. Please ensure it is running properly and the service URL is correctly configured.',- 'ComfyUIUploadFailed':+ ComfyUIUploadFailed:'Failed to upload image to ComfyUI. Please check the server connection or try again.',- 'ComfyUIWorkflowError':+ ComfyUIWorkflowError:'ComfyUI workflow execution failed. Please verify the workflow configuration.',- 'ConnectionCheckFailed':+ ConnectionCheckFailed:'The request returned empty. Please check if the API proxy address does not end with `/v1`.',- 'ContentModeration':+ ContentModeration:'Sorry, the content was rejected by the upstream safety filter. Please revise your prompt and try again.',- 'ContextEnginePipelineError':+ ContextEnginePipelineError:'Failed to assemble the conversation context for this request. Please try again; if it persists, contact support.',- 'ConversationParentMissing':+ ConversationParentMissing:'The conversation context for this message could not be found. Reopen the conversation or start a new topic, then send the request again.',- 'DatabasePersistError':+ DatabasePersistError:'A database operation failed while saving or loading this conversation. Please try again; if it persists, contact support.',- 'ExceededContextWindow':+ ExceededContextWindow:'The current request content exceeds the length that the model can handle. Please reduce the amount of content and try again.',- 'ExceededImageLimit':+ ExceededImageLimit:'This conversation contains more images than the model provider allows in one request. Start a new topic or remove some images, then try again.',- 'ExceededToolLimit':+ ExceededToolLimit:'This run reached its tool-call limit. Break the task into smaller steps, or ask the agent owner to adjust the tool-call limit.',- 'HarnessJsonParseError':+ HarnessJsonParseError:'An internal payload could not be read back, so this operation stopped. Retrying the same request will hit the same failure — please start a new message; if it persists, contact support.',- 'InsufficientQuota':+ InsufficientQuota:"Sorry, the quota for this key has been reached. Please check if your account balance is sufficient or try again after increasing the key's quota.",- 'InvalidBedrockCredentials':+ InvalidBedrockCredentials:'Bedrock authentication failed. Please check the AccessKeyId/SecretAccessKey and retry.',- 'InvalidComfyUIArgs': 'Invalid ComfyUI configuration. Please check the settings and try again.',- 'InvalidGithubCopilotToken':+ InvalidComfyUIArgs: 'Invalid ComfyUI configuration. Please check the settings and try again.',+ InvalidGithubCopilotToken:'GitHub Copilot authentication failed. Ask the bot or agent owner to refresh the GitHub Copilot credentials, then try again.',- 'InvalidGithubToken':+ InvalidGithubToken:'The GitHub Personal Access Token is incorrect or empty. Please check your GitHub Personal Access Token and try again.',- 'InvalidOllamaArgs':+ InvalidOllamaArgs:'Invalid Ollama configuration, please check Ollama configuration and try again',- 'InvalidProviderAPIKey':+ InvalidProviderAPIKey:'{{provider}} API Key is incorrect or empty, please check your {{provider}} API Key and try again',- 'InvalidRequestFormat':+ InvalidRequestFormat:'Sorry, the upstream provider rejected the request as malformed. Please check the input or try a different model.',- 'InvalidVertexCredentials':+ InvalidVertexCredentials:'Vertex authentication failed. Please check your credentials and try again.',- 'LobeHubModelDeprecated':+ LobeHubModelDeprecated:'The selected model is no longer available. Ask the bot or agent owner to select an available model, then try again.',- 'LocationNotSupportError':+ LocationNotSupportError:"We're sorry, your current location does not support this model service. This may be due to regional restrictions or the service not being available. Please confirm if the current location supports using this service, or try using a different location.",- 'ModelEmptyCompletion':+ ModelEmptyCompletion:'The model provider returned an empty response. Even without visible content, this request may still incur charges. You can retry or switch models and try again.',- 'ModelEmptyCompletionWithCost':+ ModelEmptyCompletionWithCost:'The model provider returned an empty response. This request cost {{credits}} credits. Retrying may incur a similar cost, or you can switch models.',- 'ModelRefusal':+ ModelRefusal:'The model declined to answer this request. Try rephrasing it or choose another model.',- 'ModelNotFound':+ ModelNotFound:'Sorry, the requested model could not be found. It may not exist or you may not have the necessary access permissions. Please try again after changing the API Key or adjusting your access permissions.',- 'NoAvailableChannel':+ NoAvailableChannel:'Sorry, the proxy or router has no available channel for the requested model. Please switch the channel/key configuration or try again later.',- 'OllamaBizError':+ OllamaBizError:'Error requesting Ollama service, please troubleshoot or retry based on the following information',- 'OllamaServiceUnavailable':+ OllamaServiceUnavailable:'Ollama service is unavailable. Please check if Ollama is running properly or if the cross-origin configuration of Ollama is set correctly.',- 'OperationInactivityTimeout':+ OperationInactivityTimeout:'The agent operation was idle for too long and was terminated. Please retry the request.',- 'PermissionDenied':+ PermissionDenied:'Sorry, you do not have permission to access this service. Please check if your key has the necessary access rights.',- 'ProviderBizError':+ ProviderBizError:'Error requesting {{provider}} service, please troubleshoot or retry based on the following information',- 'ProviderContentPolicyViolation':+ ProviderContentPolicyViolation:'The provider blocked this request or its output due to content policy. Please revise your prompt and try again.',- 'ProviderNetworkError':+ ProviderNetworkError:'Connection to the provider timed out or was dropped. Please check your network and try again.',- 'ProviderNoImageGenerated':+ ProviderNoImageGenerated:'The provider returned no image for this request. Try rephrasing the request, or choose a model that supports image generation.',- 'RemoteMediaDownloadTimeout':+ RemoteMediaDownloadTimeout:'The provider timed out while downloading an attached image or file. Please try again.',- 'ProviderServiceUnavailable':+ ProviderServiceUnavailable:'The provider is temporarily overloaded or unavailable. Please try again shortly.',- 'QuotaLimitReached':+ QuotaLimitReached:"Sorry, the token usage or request count has reached the quota limit for this key. Please increase the key's quota or try again later.",- 'RateLimitExceeded':+ RateLimitExceeded:"Sorry, the token usage or request count has reached the rate limit for this key. Please try again later or increase the key's quota.",- 'RequestBodyTooLarge':+ RequestBodyTooLarge:'This request is too large for the model provider. Compact the conversation or reduce attached content, then try again.',- 'StateStorePersistError':+ StateStorePersistError:'A temporary issue with the conversation state store interrupted this operation. Please try again; if it persists, contact support.',- 'StateStoreReadError':+ StateStoreReadError:'This operation could not be resumed because its session state was unavailable. Please reopen the conversation to continue; if it persists, contact support.',- 'StreamChunkError':+ StreamChunkError:'Error parsing the message chunk of the streaming request. Please check if the current API interface complies with the standard specifications, or contact your API provider for assistance.',- 'UpstreamGatewayError':+ UpstreamGatewayError:'The upstream gateway or proxy returned an error. Please try again shortly; if it persists, check your proxy / endpoint configuration.',- 'UpstreamHttpError':+ UpstreamHttpError:'The provider returned an HTTP error without further detail. Please try again, or check your request and model configuration.',- 'UpstreamMalformedResponse':+ UpstreamMalformedResponse:'The provider returned a malformed response that could not be parsed. Please retry; if it persists, try a different model or provider.',- 'UserConfigError':+ UserConfigError:'Provider configuration is invalid (incorrect base URL, missing environment variable, virtual-key restriction, etc.). Please review the provider settings.',- 'heterogeneous.auth_required.title': 'Sign-in required',- 'heterogeneous.auth_required.description':- 'Ask the bot owner to sign in again on the device running {{agent}}.',- 'heterogeneous.usage_limit.title': 'Usage limit reached',- 'heterogeneous.usage_limit.description':- 'The account used by {{agent}} has exhausted its allowance. Wait for the quota to reset, or ask the bot owner to switch to an account or model with available quota.',- 'heterogeneous.credit_limit.title': 'Credits exhausted',- 'heterogeneous.credit_limit.description':- 'Ask the bot owner to add credits to the account used by {{agent}}, or switch models. Waiting for a quota reset will not restore these credits.',- 'heterogeneous.server_overloaded.title': 'Provider temporarily unavailable',- 'heterogeneous.server_overloaded.description':- 'The provider behind {{agent}} is busy or unavailable. Please try again shortly.',- 'heterogeneous.server_throttle.title': 'Requests temporarily limited',- 'heterogeneous.server_throttle.description':- 'The provider is temporarily limiting requests from {{agent}}. Please wait a moment and try again.',- 'heterogeneous.network_drop.title': 'Connection interrupted',- 'heterogeneous.network_drop.description':- '{{agent}} lost its connection before finishing. Retry; if it happens again, ask the bot owner to check the running device’s network and proxy settings.',- 'heterogeneous.invalid_request.title': 'Request rejected',- 'heterogeneous.invalid_request.description':- 'The provider rejected the request sent by {{agent}}. Try a new topic; if it persists, share the Operation ID with support.',- 'heterogeneous.unsupported_attachment.title': 'Attachment unsupported',- 'heterogeneous.unsupported_attachment.description':- '{{agent}} could not read an attachment. Remove it or convert it to a supported format, then resend the request.',- 'heterogeneous.aborted.title': 'Task stopped',- 'heterogeneous.aborted.description':- 'This {{agent}} task was stopped. Send a new request when you want to continue.',- 'heterogeneous.max_turns.title': 'Step limit reached',- 'heterogeneous.max_turns.description':- '{{agent}} reached its step limit before finishing. Split the task into smaller steps, or ask the bot owner to adjust the limit.',- 'heterogeneous.resume_thread_not_found.title': 'Previous session unavailable',- 'heterogeneous.resume_thread_not_found.description':- '{{agent}} could not find the previous session. Start a new topic and resend the request.',- 'heterogeneous.resume_cwd_mismatch.title': 'Session directory changed',- 'heterogeneous.resume_cwd_mismatch.description':- 'Ask the bot owner to restore the working directory used by this {{agent}} session, or start a new topic.',- 'heterogeneous.cli_not_found.title': 'Agent CLI unavailable',- 'heterogeneous.cli_not_found.description':- 'Ask the bot owner to install or repair {{agent}} on the device running this task.',- 'heterogeneous.working_directory_not_found.title': 'Working directory unavailable',- 'heterogeneous.working_directory_not_found.description':- 'The working directory for {{agent}} is missing. Ask the bot owner to restore it or choose an existing directory.',- 'heterogeneous.model_unavailable.title': 'Model unavailable',- 'heterogeneous.model_unavailable.description':- 'The model selected for {{agent}} is unavailable. Ask the bot owner to choose another model.',- 'heterogeneous.agent_failed.title': 'Agent task failed',- 'heterogeneous.agent_failed.description':- '{{agent}} stopped without a recognized cause. Share the Operation ID with the bot owner or support to investigate.',- 'heterogeneous.reset': 'Quota resets at {{time}} (UTC).',- 'heterogeneous.window.seven_day': 'Weekly allowance exhausted.',- 'heterogeneous.window.five_hour': 'Session allowance exhausted.',};