opencode-translate 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ysm-dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # opencode-translate
2
+
3
+ `opencode-translate` is an OpenCode plugin that lets the user chat in a configured `sourceLanguage` while the main chat loop and compaction summariser only see English.
4
+
5
+ ## What It Does
6
+
7
+ - Activates once per root session when the first user message contains a trigger keyword such as `$en`.
8
+ - Translates user-authored text parts from `sourceLanguage` to English before the main LLM sees them.
9
+ - Stores the original user text, plus a cached English translation in part metadata.
10
+ - Shows a visible `→ EN: ...` preview under each translated user text part.
11
+ - Translates assistant text parts from English into `displayLanguage` when each text part completes.
12
+ - Stores assistant text as:
13
+
14
+ ```md
15
+ <english>
16
+
17
+ <!-- oc-translate:{nonce}:start -->
18
+ ---
19
+
20
+ **{displayLanguageLabel}:**
21
+
22
+ <translated>
23
+ <!-- oc-translate:{nonce}:end -->
24
+ ```
25
+
26
+ - Strips that trailer back out before later LLM turns, so the model history stays English-only.
27
+
28
+ ## v1 Limits
29
+
30
+ - No mid-session toggle off.
31
+ - No auto-detection of source or display language.
32
+ - No title translation or title-path English enforcement.
33
+ - No subagent translation.
34
+ - No translation of tool inputs, tool outputs, or reasoning parts.
35
+ - No self-healing for edited historical translated user messages. Those abort with a stale-cache error.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ npm install -g opencode-translate
41
+ ```
42
+
43
+ Add it to `~/.config/opencode/opencode.json`:
44
+
45
+ ```json
46
+ {
47
+ "plugin": [
48
+ ["opencode-translate", {
49
+ "translatorModel": "anthropic/claude-haiku-4-5",
50
+ "triggerKeywords": ["$en"],
51
+ "sourceLanguage": "ko",
52
+ "displayLanguage": "ko",
53
+ "verbose": false
54
+ }]
55
+ ]
56
+ }
57
+ ```
58
+
59
+ Then make sure the translator provider has credentials. Any of these work:
60
+
61
+ ```bash
62
+ opencode auth login anthropic
63
+ export ANTHROPIC_API_KEY=...
64
+ ```
65
+
66
+ Start a brand-new session and put the trigger in the first message:
67
+
68
+ ```text
69
+ $en 프로젝트 루트의 package.json을 읽고 요약해줘
70
+ ```
71
+
72
+ ## Options
73
+
74
+ | Option | Type | Default |
75
+ | --- | --- | --- |
76
+ | `translatorModel` | string | `anthropic/claude-haiku-4-5` |
77
+ | `triggerKeywords` | string[] | `[$en]` |
78
+ | `sourceLanguage` | string | `en` |
79
+ | `displayLanguage` | string | `en` |
80
+ | `apiKey` | string | `undefined` |
81
+ | `verbose` | boolean | `false` |
82
+
83
+ ## Privacy
84
+
85
+ Using this plugin means text goes to two model providers per turn:
86
+
87
+ - the normal OpenCode chat provider
88
+ - the configured `translatorModel` provider
89
+
90
+ If you need strict single-provider or self-hosted-only behavior, do not enable this plugin.
91
+
92
+ ## Anthropic OAuth Warning
93
+
94
+ If `translatorModel` uses Anthropic and OpenCode auth is backed by Anthropic OAuth, this plugin will attempt to reuse those OAuth credentials for translation requests.
95
+
96
+ - This depends on undocumented Anthropic OAuth request shapes.
97
+ - OpenCode upstream removed Anthropic OAuth support for legal / policy reasons.
98
+ - `opencode-translate` does not spoof Claude CLI headers or reintroduce the evasions upstream removed.
99
+
100
+ If you do not want that risk, use a plain API key for Anthropic or choose a different translator provider.
101
+
102
+ ## Manual Smoke Test
103
+
104
+ 1. Install the plugin and configure `sourceLanguage: "ko"`, `displayLanguage: "ko"`.
105
+ 2. Start a new session and send `$en 프로젝트 루트의 package.json을 읽고 요약해줘`.
106
+ 3. Confirm the activation banner appears.
107
+ 4. Confirm the `→ EN: ...` preview appears under the user message.
108
+ 5. Confirm assistant text streams in English, then gains a translated trailer when the text part finishes.
109
+ 6. Confirm later messages in the same session translate without repeating `$en`.
110
+ 7. Confirm editing a historical translated user message aborts with the stale-cache error.
111
+ 8. Confirm task-tool child sessions are not translated.
112
+ 9. Confirm the title remains in the source language in v1.
113
+
114
+ ## Development
115
+
116
+ ```bash
117
+ bun install
118
+ bun run check # biome format + lint + organize imports (write)
119
+ bun run typecheck # tsgo (@typescript/native-preview, TS v7 beta)
120
+ bun test
121
+ ```
122
+
123
+ To only verify without writing:
124
+
125
+ ```bash
126
+ bun run check:ci
127
+ ```
128
+
129
+ ### Release
130
+
131
+ `main` 브랜치에 푸시될 때 `package.json`의 `version`이 npm에 아직 없는 값이면, `.github/workflows/publish.yml`이 자동으로:
132
+
133
+ 1. `biome check`, `tsgo`, `bun test` 실행
134
+ 2. `npm publish --provenance --access public`
135
+ 3. `vX.Y.Z` git 태그와 GitHub Release 생성
136
+
137
+ 버전을 올리려면 `package.json`의 `version`만 수정해 main에 merge 하세요. 이미 publish된 버전이면 workflow는 publish를 건너뜁니다.
138
+
139
+ `docs/spec.en.md` is the source of truth for behavior.
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "opencode-translate",
3
+ "version": "0.0.1",
4
+ "description": "OpenCode plugin that lets the user chat in a configured source language while the main chat loop only sees English.",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ysm-dev/opencode-translate.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/ysm-dev/opencode-translate/issues"
14
+ },
15
+ "homepage": "https://github.com/ysm-dev/opencode-translate#readme",
16
+ "keywords": [
17
+ "opencode",
18
+ "opencode-plugin",
19
+ "translate",
20
+ "translation",
21
+ "i18n"
22
+ ],
23
+ "files": [
24
+ "src",
25
+ "LICENSE",
26
+ "README.md"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "scripts": {
32
+ "typecheck": "tsgo --noEmit",
33
+ "format": "biome format --write .",
34
+ "format:check": "biome format .",
35
+ "lint": "biome lint --write .",
36
+ "lint:check": "biome lint .",
37
+ "check": "biome check --write .",
38
+ "check:ci": "biome check .",
39
+ "test": "bun test"
40
+ },
41
+ "peerDependencies": {
42
+ "@opencode-ai/plugin": ">=1.14.0"
43
+ },
44
+ "dependencies": {
45
+ "@ai-sdk/amazon-bedrock": "^4.0.0",
46
+ "@ai-sdk/anthropic": "^3.0.0",
47
+ "@ai-sdk/google": "^3.0.0",
48
+ "@ai-sdk/google-vertex": "^4.0.0",
49
+ "@ai-sdk/openai": "^3.0.0",
50
+ "@ai-sdk/openai-compatible": "^2.0.0",
51
+ "ai": "^6.0.0"
52
+ },
53
+ "devDependencies": {
54
+ "@biomejs/biome": "^2.4.12",
55
+ "@opencode-ai/plugin": "^1.14.20",
56
+ "@types/node": "^25.6.0",
57
+ "@typescript/native-preview": "beta",
58
+ "bun-types": "^1.3.13"
59
+ }
60
+ }
@@ -0,0 +1,408 @@
1
+ import { randomBytes } from "node:crypto"
2
+ import type { Hooks, PluginInput, PluginOptions } from "@opencode-ai/plugin"
3
+ import {
4
+ buildInboundTranslationError,
5
+ buildStaleCacheError,
6
+ isTextPart,
7
+ isTranslateStateRecord,
8
+ isUserAuthoredTextPart,
9
+ LLM_LANGUAGE,
10
+ type MessageWithPartsLike,
11
+ NONCE_PATTERN,
12
+ normalizeReason,
13
+ PLUGIN_NAME,
14
+ type PluginClientLike,
15
+ parseTranslatorModel,
16
+ type ResolvedTranslateOptions,
17
+ resolveOptions,
18
+ SPEC_VERSION,
19
+ type StoredTextMetadata,
20
+ type TextPartLike,
21
+ type TranslateState,
22
+ unwrapData,
23
+ } from "./constants"
24
+ import { composeTranslatedAssistantText, composeTranslationFailureText, extractEnglishHistoryText } from "./formatting"
25
+ import { getDisplayLanguageLabel } from "./labels"
26
+ import { createSyntheticPartID, createTranslator, hashText } from "./translator"
27
+
28
+ const sessionStateCache = new Map<string, TranslateState | null>()
29
+
30
+ export function __resetActivationCacheForTest() {
31
+ sessionStateCache.clear()
32
+ }
33
+
34
+ interface ResolvedSessionState {
35
+ sessionActive: boolean
36
+ canActivate: boolean
37
+ state?: TranslateState
38
+ storedMessages: MessageWithPartsLike[]
39
+ }
40
+
41
+ interface TriggerMatch {
42
+ partArrayIndex: number
43
+ eligibleIndex: number
44
+ keyword: string
45
+ offset: number
46
+ }
47
+
48
+ interface HookDependencies {
49
+ translator?: {
50
+ translateText(input: {
51
+ text: string
52
+ sourceLanguage: string
53
+ targetLanguage: string
54
+ direction: "inbound" | "outbound"
55
+ }): Promise<string>
56
+ }
57
+ }
58
+
59
+ function logError(client: PluginClientLike, error: unknown) {
60
+ return client.app.log({
61
+ body: {
62
+ service: PLUGIN_NAME,
63
+ level: "error",
64
+ message: normalizeReason(error),
65
+ },
66
+ })
67
+ }
68
+
69
+ function createState(options: ResolvedTranslateOptions): TranslateState {
70
+ return {
71
+ translate_enabled: true,
72
+ translate_source_lang: options.sourceLanguage,
73
+ translate_display_lang: options.displayLanguage,
74
+ translate_llm_lang: LLM_LANGUAGE,
75
+ translate_nonce: randomBytes(16).toString("hex"),
76
+ }
77
+ }
78
+
79
+ function createActivationBannerText(options: ResolvedTranslateOptions): string {
80
+ const { modelID } = parseTranslatorModel(options.translatorModel)
81
+ return `✓ Translation mode enabled · translator: ${modelID} · source: ${options.sourceLanguage} · display: ${options.displayLanguage}`
82
+ }
83
+
84
+ function asMetadata(part: TextPartLike): StoredTextMetadata {
85
+ return (part.metadata ?? {}) as StoredTextMetadata
86
+ }
87
+
88
+ function extractStateFromMetadata(metadata: StoredTextMetadata | undefined): TranslateState | undefined {
89
+ if (!isTranslateStateRecord(metadata)) return undefined
90
+ return {
91
+ translate_enabled: true,
92
+ translate_source_lang: metadata.translate_source_lang,
93
+ translate_display_lang: metadata.translate_display_lang,
94
+ translate_llm_lang: LLM_LANGUAGE,
95
+ translate_nonce: metadata.translate_nonce,
96
+ }
97
+ }
98
+
99
+ export function extractStoredState(messages: MessageWithPartsLike[]): TranslateState | undefined {
100
+ let fallback: TranslateState | undefined
101
+
102
+ for (const message of messages) {
103
+ for (const part of message.parts) {
104
+ if (!isTextPart(part)) continue
105
+ const metadata = asMetadata(part)
106
+ const state = extractStateFromMetadata(metadata)
107
+ if (!state) continue
108
+ if (metadata.translate_role === "activation_banner") return state
109
+ if (message.info.role === "user" && part.synthetic !== true && fallback === undefined) {
110
+ fallback = state
111
+ }
112
+ }
113
+ }
114
+
115
+ return fallback
116
+ }
117
+
118
+ function mergeTranslatedMetadata(state: TranslateState, part: TextPartLike, english: string): Record<string, unknown> {
119
+ return {
120
+ ...(part.metadata ?? {}),
121
+ ...state,
122
+ translate_source_hash: hashText(part.text ?? ""),
123
+ translate_en: english,
124
+ }
125
+ }
126
+
127
+ function createSyntheticTextPart(
128
+ sessionID: string,
129
+ messageID: string,
130
+ text: string,
131
+ metadata: Record<string, unknown>,
132
+ ): TextPartLike {
133
+ return {
134
+ id: createSyntheticPartID(),
135
+ sessionID,
136
+ messageID,
137
+ type: "text",
138
+ text,
139
+ synthetic: true,
140
+ ignored: true,
141
+ metadata,
142
+ }
143
+ }
144
+
145
+ function escapeRegex(value: string): string {
146
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
147
+ }
148
+
149
+ export function findTriggerMatch(parts: TextPartLike[], triggerKeywords: string[]): TriggerMatch | undefined {
150
+ let eligibleIndex = 0
151
+ for (let partArrayIndex = 0; partArrayIndex < parts.length; partArrayIndex += 1) {
152
+ const part = parts[partArrayIndex]
153
+ if (!isUserAuthoredTextPart(part)) continue
154
+
155
+ let bestForPart: TriggerMatch | undefined
156
+ for (let keywordIndex = 0; keywordIndex < triggerKeywords.length; keywordIndex += 1) {
157
+ const keyword = triggerKeywords[keywordIndex]
158
+ const pattern = new RegExp(`(^|[ \\t\\r\\n\\f\\v])${escapeRegex(keyword)}(?=$|[ \\t\\r\\n\\f\\v])`)
159
+ const match = pattern.exec(part.text)
160
+ if (!match) continue
161
+ const offset = match.index + match[1].length
162
+ if (!bestForPart || offset < bestForPart.offset) {
163
+ bestForPart = {
164
+ partArrayIndex,
165
+ eligibleIndex,
166
+ keyword,
167
+ offset,
168
+ }
169
+ }
170
+ }
171
+
172
+ if (bestForPart) return bestForPart
173
+ eligibleIndex += 1
174
+ }
175
+
176
+ return undefined
177
+ }
178
+
179
+ export function stripTriggerKeyword(text: string, keyword: string, offset: number): string {
180
+ const lineStart = text.lastIndexOf("\n", offset - 1) + 1
181
+ const nextNewline = text.indexOf("\n", offset)
182
+ const lineEnd = nextNewline === -1 ? text.length : nextNewline
183
+ const line = text.slice(lineStart, lineEnd)
184
+ const localOffset = offset - lineStart
185
+
186
+ let rewrittenLine: string
187
+ if (localOffset === 0 && line.startsWith(`${keyword} `)) {
188
+ rewrittenLine = line.slice(keyword.length + 1)
189
+ } else if (
190
+ localOffset + keyword.length === line.length &&
191
+ localOffset > 0 &&
192
+ line.slice(localOffset - 1, localOffset) === " "
193
+ ) {
194
+ rewrittenLine = line.slice(0, localOffset - 1)
195
+ } else if (
196
+ localOffset > 0 &&
197
+ line.slice(localOffset - 1, localOffset) === " " &&
198
+ line.slice(localOffset + keyword.length, localOffset + keyword.length + 1) === " "
199
+ ) {
200
+ rewrittenLine = `${line.slice(0, localOffset - 1)} ${line.slice(localOffset + keyword.length + 1)}`
201
+ } else {
202
+ rewrittenLine = `${line.slice(0, localOffset)}${line.slice(localOffset + keyword.length)}`
203
+ }
204
+
205
+ return `${text.slice(0, lineStart)}${rewrittenLine}${text.slice(lineEnd)}`
206
+ }
207
+
208
+ async function resolveSessionState(
209
+ client: PluginClientLike,
210
+ directory: string | undefined,
211
+ sessionID: string,
212
+ ): Promise<ResolvedSessionState> {
213
+ const session = unwrapData(
214
+ await client.session.get({
215
+ path: { id: sessionID },
216
+ query: { ...(directory ? { directory } : {}) },
217
+ throwOnError: true,
218
+ }),
219
+ )
220
+ if (session.parentID != null) {
221
+ sessionStateCache.set(sessionID, null)
222
+ return { sessionActive: false, canActivate: false, storedMessages: [] }
223
+ }
224
+
225
+ const storedMessages = unwrapData(
226
+ await client.session.messages({
227
+ path: { id: sessionID },
228
+ query: { ...(directory ? { directory } : {}) },
229
+ throwOnError: true,
230
+ }),
231
+ )
232
+ const state = extractStoredState(storedMessages)
233
+ sessionStateCache.set(sessionID, state ?? null)
234
+
235
+ return {
236
+ sessionActive: Boolean(state),
237
+ canActivate: storedMessages.length === 0,
238
+ state: state ?? undefined,
239
+ storedMessages,
240
+ }
241
+ }
242
+
243
+ function shouldRequireCache(part: TextPartLike): boolean {
244
+ return isUserAuthoredTextPart(part) && part.text.trim().length > 0
245
+ }
246
+
247
+ export function createHooks(ctx: PluginInput, rawOptions: PluginOptions = {}, deps: HookDependencies = {}): Hooks {
248
+ if (process.env.OPENCODE_TRANSLATE_DISABLE === "1") {
249
+ return {}
250
+ }
251
+
252
+ const client = ctx.client as unknown as PluginClientLike
253
+ const options = resolveOptions(rawOptions)
254
+ const translator = deps.translator ?? createTranslator(client, options)
255
+
256
+ return {
257
+ "chat.message": async (input, output) => {
258
+ const resolved = await resolveSessionState(client, ctx.directory, input.sessionID)
259
+ let activeState = resolved.state
260
+ let activatedThisTurn = false
261
+
262
+ if (!activeState && resolved.canActivate) {
263
+ const match = findTriggerMatch(output.parts as TextPartLike[], options.triggerKeywords)
264
+ if (match) {
265
+ const part = output.parts[match.partArrayIndex] as TextPartLike & { text: string }
266
+ part.text = stripTriggerKeyword(part.text, match.keyword, match.offset)
267
+ activeState = createState(options)
268
+ if (!NONCE_PATTERN.test(activeState.translate_nonce)) {
269
+ throw new Error("Generated invalid translation nonce")
270
+ }
271
+ activatedThisTurn = true
272
+ sessionStateCache.set(input.sessionID, activeState)
273
+ }
274
+ }
275
+
276
+ if (!activeState) return
277
+
278
+ const nextParts: TextPartLike[] = []
279
+ let eligibleIndex = 0
280
+
281
+ for (const part of output.parts as TextPartLike[]) {
282
+ nextParts.push(part)
283
+ if (!isUserAuthoredTextPart(part)) continue
284
+
285
+ const currentEligibleIndex = eligibleIndex
286
+ eligibleIndex += 1
287
+ if (part.text.trim().length === 0) continue
288
+
289
+ try {
290
+ const english = await translator.translateText({
291
+ text: part.text,
292
+ sourceLanguage: activeState.translate_source_lang,
293
+ targetLanguage: LLM_LANGUAGE,
294
+ direction: "inbound",
295
+ })
296
+
297
+ const sourceHash = hashText(part.text)
298
+ part.metadata = {
299
+ ...(part.metadata ?? {}),
300
+ ...mergeTranslatedMetadata(activeState, part, english),
301
+ }
302
+
303
+ nextParts.push(
304
+ createSyntheticTextPart(part.sessionID, part.messageID, `→ EN: ${english}`, {
305
+ translate_role: "translation_preview",
306
+ translate_nonce: activeState.translate_nonce,
307
+ translate_source_hash: sourceHash,
308
+ translate_part_index: currentEligibleIndex,
309
+ }),
310
+ )
311
+ } catch (error) {
312
+ if (
313
+ error instanceof Error &&
314
+ (error.message.includes(":AUTH_UNAVAILABLE]") || error.message.includes(":OAUTH_REFRESH_FAILED]"))
315
+ ) {
316
+ throw error
317
+ }
318
+ throw buildInboundTranslationError(activeState.translate_source_lang, normalizeReason(error))
319
+ }
320
+ }
321
+
322
+ if (activatedThisTurn) {
323
+ nextParts.push(
324
+ createSyntheticTextPart(input.sessionID, output.message.id, createActivationBannerText(options), {
325
+ ...activeState,
326
+ translate_role: "activation_banner",
327
+ translate_spec_version: SPEC_VERSION,
328
+ }),
329
+ )
330
+ }
331
+
332
+ output.parts.splice(0, output.parts.length, ...(nextParts as typeof output.parts))
333
+ },
334
+ "experimental.chat.messages.transform": async (_input, output) => {
335
+ const sessionID = output.messages[0]?.info.sessionID
336
+ if (!sessionID) return
337
+
338
+ const resolved = await resolveSessionState(client, ctx.directory, sessionID)
339
+ const activeState = resolved.state
340
+ if (!activeState) return
341
+
342
+ for (const message of output.messages as MessageWithPartsLike[]) {
343
+ if (message.info.role === "user") {
344
+ for (const part of message.parts) {
345
+ if (!isTextPart(part)) continue
346
+ if (!shouldRequireCache(part)) continue
347
+ const metadata = asMetadata(part)
348
+ const sourceHash = hashText(part.text)
349
+ if (
350
+ metadata.translate_enabled === true &&
351
+ metadata.translate_nonce === activeState.translate_nonce &&
352
+ metadata.translate_source_hash === sourceHash &&
353
+ typeof metadata.translate_en === "string"
354
+ ) {
355
+ part.text = metadata.translate_en
356
+ continue
357
+ }
358
+
359
+ throw buildStaleCacheError()
360
+ }
361
+ }
362
+
363
+ if (message.info.role === "assistant") {
364
+ for (const part of message.parts) {
365
+ if (!isTextPart(part)) continue
366
+ part.text = extractEnglishHistoryText(part.text, activeState.translate_nonce)
367
+ }
368
+ }
369
+ }
370
+ },
371
+ "experimental.text.complete": async (input, output) => {
372
+ const resolved = await resolveSessionState(client, ctx.directory, input.sessionID)
373
+ const activeState = resolved.state
374
+ if (!activeState) return
375
+
376
+ const message = unwrapData(
377
+ await client.session.message({
378
+ path: { id: input.sessionID, messageID: input.messageID },
379
+ query: { ...(ctx.directory ? { directory: ctx.directory } : {}) },
380
+ throwOnError: true,
381
+ }),
382
+ ) as MessageWithPartsLike & { info: Record<string, unknown> }
383
+
384
+ if (message.info.role !== "assistant") return
385
+ if (message.info.summary === true) return
386
+ if (activeState.translate_display_lang === LLM_LANGUAGE || output.text.length === 0) return
387
+
388
+ try {
389
+ const translated = await translator.translateText({
390
+ text: output.text,
391
+ sourceLanguage: LLM_LANGUAGE,
392
+ targetLanguage: activeState.translate_display_lang,
393
+ direction: "outbound",
394
+ })
395
+
396
+ output.text = composeTranslatedAssistantText(
397
+ output.text,
398
+ getDisplayLanguageLabel(activeState.translate_display_lang),
399
+ translated,
400
+ activeState.translate_nonce,
401
+ )
402
+ } catch (error) {
403
+ output.text = composeTranslationFailureText(output.text, activeState.translate_nonce)
404
+ await logError(client, error)
405
+ }
406
+ },
407
+ }
408
+ }