opencode-translate 0.1.1 → 0.1.2

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/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  - Stores the original user text, plus a cached English translation in part metadata.
10
10
  - Shows a visible `→ EN: ...` preview under each translated user text part.
11
11
  - Translates assistant text parts from English into `displayLanguage` when each text part completes.
12
- - Translates the built-in `question` tool's question text, header, and every option's label and description into `displayLanguage` so the TUI confirmation dialog is in the user's language. The tool output string returned to the LLM is restored to English, keeping the chat history English-only.
12
+ - Translates the built-in `question` tool's question text, header, and every option's label and description into `displayLanguage` so the TUI confirmation dialog is in the user's language. The tool output string returned to the LLM is restored to English, including translation of non-empty custom answers.
13
13
  - Stores assistant text as:
14
14
 
15
15
  ```md
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-translate",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "OpenCode plugin that lets the user chat in a configured source language while the main chat loop only sees English.",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
package/src/activation.ts CHANGED
@@ -555,35 +555,36 @@ export function createHooks(ctx: PluginInput, rawOptions: PluginOptions = {}, de
555
555
  },
556
556
  // Translate the built-in `question` tool so the TUI dialog renders in
557
557
  // the user's displayLanguage. The tool output string is restored back
558
- // to English in `tool.execute.after` so the main LLM context stays
559
- // English-only.
558
+ // to English in `tool.execute.after`; typed custom answers also go
559
+ // through the inbound user-message translation path.
560
560
  "tool.execute.before": async (input, output) => {
561
561
  try {
562
562
  if (input.tool !== QUESTION_TOOL_ID) return
563
563
  const resolved = await resolveSessionState(client, ctx.directory, input.sessionID)
564
564
  const activeState = resolved.state
565
565
  if (!activeState) return
566
- if (activeState.translate_display_lang === LLM_LANGUAGE) return
567
566
 
568
567
  const args = output.args as unknown
569
568
  if (!isQuestionArgs(args)) return
570
569
 
571
570
  const original = snapshotQuestions(args)
572
- try {
573
- await translateQuestionArgs(args, (text) =>
574
- translator.translateText({
575
- text,
576
- sourceLanguage: LLM_LANGUAGE,
577
- targetLanguage: activeState.translate_display_lang,
578
- direction: "outbound",
579
- }),
580
- )
581
- } catch (error) {
582
- // Translation failed: restore the originals so the dialog at least
583
- // renders in English instead of a half-translated mess.
584
- args.questions.splice(0, args.questions.length, ...snapshotQuestions({ questions: original }))
585
- await logError(client, error)
586
- return
571
+ if (activeState.translate_display_lang !== LLM_LANGUAGE) {
572
+ try {
573
+ await translateQuestionArgs(args, (text) =>
574
+ translator.translateText({
575
+ text,
576
+ sourceLanguage: LLM_LANGUAGE,
577
+ targetLanguage: activeState.translate_display_lang,
578
+ direction: "outbound",
579
+ }),
580
+ )
581
+ } catch (error) {
582
+ // Translation failed: restore the originals so the dialog at least
583
+ // renders in English instead of a half-translated mess.
584
+ args.questions.splice(0, args.questions.length, ...snapshotQuestions({ questions: original }))
585
+ await logError(client, error)
586
+ return
587
+ }
587
588
  }
588
589
 
589
590
  const translated = snapshotQuestions(args)
@@ -598,7 +599,32 @@ export function createHooks(ctx: PluginInput, rawOptions: PluginOptions = {}, de
598
599
  const snapshot = questionSnapshots.get(input.callID)
599
600
  if (!snapshot) return
600
601
  questionSnapshots.delete(input.callID)
601
- restoreQuestionOutput(output as QuestionToolOutput, snapshot)
602
+ const resolved = await resolveSessionState(client, ctx.directory, input.sessionID)
603
+ const activeState = resolved.state
604
+ const translateCustomAnswer =
605
+ activeState && activeState.translate_source_lang !== LLM_LANGUAGE
606
+ ? (text: string) =>
607
+ translator.translateText({
608
+ text,
609
+ sourceLanguage: activeState.translate_source_lang,
610
+ targetLanguage: LLM_LANGUAGE,
611
+ direction: "inbound",
612
+ })
613
+ : undefined
614
+
615
+ await restoreQuestionOutput(output as QuestionToolOutput, snapshot, {
616
+ ...(translateCustomAnswer ? { translateCustomAnswer } : {}),
617
+ onTranslationError: async (error) => {
618
+ if (!activeState) {
619
+ await logError(client, error)
620
+ return
621
+ }
622
+ await logError(
623
+ client,
624
+ buildInboundTranslationError(activeState.translate_source_lang, normalizeReason(error)),
625
+ )
626
+ },
627
+ })
602
628
  } catch (error) {
603
629
  await logError(client, error)
604
630
  }
@@ -9,8 +9,10 @@
9
9
  // 3. OpenCode publishes `question.asked`; the TUI shows the translated
10
10
  // dialog and the user picks an option (or types a custom answer).
11
11
  // 4. `tool.execute.after` hook reverses the substitution using the
12
- // snapshot we captured in step 2, so the tool output string delivered
13
- // back to the LLM stays in English.
12
+ // snapshot we captured in step 2. Selected options are restored by
13
+ // label mapping; non-empty custom answers are translated like normal
14
+ // user messages, so the output delivered back to the LLM stays in
15
+ // English.
14
16
  //
15
17
  // A per-callID snapshot is kept so mapping a user-selected translated label
16
18
  // back to its original English label is deterministic.
@@ -35,6 +37,11 @@ export interface QuestionToolOutput {
35
37
  metadata?: { answers?: readonly (readonly string[])[] } | Record<string, unknown>
36
38
  }
37
39
 
40
+ export interface RestoreQuestionOutputOptions {
41
+ translateCustomAnswer?: (text: string) => Promise<string>
42
+ onTranslationError?: (error: unknown) => Promise<void> | void
43
+ }
44
+
38
45
  function cloneQuestion(q: TextRecord): TextRecord {
39
46
  return {
40
47
  question: q.question,
@@ -80,9 +87,8 @@ async function assignTranslation(
80
87
  container[key] = unwrapEchoedTextEnvelope(translated)
81
88
  }
82
89
 
83
- // Translate every display-facing string in `args` in parallel. Returns the
84
- // snapshot of the translated form so the caller can pair it with the
85
- // pre-translation snapshot taken with `snapshotQuestions`.
90
+ // Translate every display-facing string in `args` in parallel. The caller can
91
+ // snapshot the translated form afterward with `snapshotQuestions`.
86
92
  export async function translateQuestionArgs(
87
93
  args: QuestionArgs,
88
94
  translate: (text: string) => Promise<string>,
@@ -101,44 +107,61 @@ export async function translateQuestionArgs(
101
107
  await Promise.all(jobs)
102
108
  }
103
109
 
104
- // Given the user-selected labels (`answers`), find the matching translated
105
- // option and return its original English label. If no match (e.g. a custom
106
- // free-text answer), return the label verbatim so the LLM still sees what
107
- // the user actually typed.
108
- function restoreLabel(
110
+ // Given a user-selected label, find the matching translated option and return
111
+ // its original English label. If no match exists, OpenCode only gives us the
112
+ // raw answer string, so treat non-empty text as a custom answer and translate
113
+ // it through the same source-language -> English path as normal user messages.
114
+ async function restoreLabel(
109
115
  selectedLabel: string,
110
116
  translatedOptions: readonly OptionRecord[],
111
117
  originalOptions: readonly OptionRecord[],
112
- ): string {
118
+ options: RestoreQuestionOutputOptions,
119
+ ): Promise<string> {
113
120
  const idx = translatedOptions.findIndex((option) => option.label === selectedLabel)
114
- if (idx < 0) return selectedLabel
115
- return originalOptions[idx]?.label ?? selectedLabel
121
+ if (idx >= 0) return originalOptions[idx]?.label ?? selectedLabel
122
+ if (!options.translateCustomAnswer || selectedLabel.trim().length === 0) return selectedLabel
123
+
124
+ try {
125
+ const translated = await options.translateCustomAnswer(selectedLabel)
126
+ return unwrapEchoedTextEnvelope(translated)
127
+ } catch (error) {
128
+ await options.onTranslationError?.(error)
129
+ return selectedLabel
130
+ }
116
131
  }
117
132
 
118
133
  // Reconstruct the exact output string the question tool would have produced
119
134
  // if it had been called with the original English args. Mirrors the format
120
135
  // in `packages/opencode/src/tool/question.ts` (as of opencode 1.14.x).
121
- export function buildRestoredOutput(
136
+ export async function buildRestoredOutput(
122
137
  original: readonly TextRecord[],
123
138
  translated: readonly TextRecord[],
124
139
  answers: readonly (readonly string[])[],
125
- ): string {
126
- const formatted = original
127
- .map((q, i) => {
140
+ options: RestoreQuestionOutputOptions = {},
141
+ ): Promise<string> {
142
+ const formattedParts = await Promise.all(
143
+ original.map(async (q, i) => {
128
144
  const selected = answers[i] ?? []
129
145
  const translatedOptions = translated[i]?.options ?? []
130
146
  const originalOptions = q.options
131
- const restored = selected.map((label) => restoreLabel(label, translatedOptions, originalOptions))
147
+ const restored = await Promise.all(
148
+ selected.map((label) => restoreLabel(label, translatedOptions, originalOptions, options)),
149
+ )
132
150
  const rendered = restored.length > 0 ? restored.join(", ") : "Unanswered"
133
151
  return `"${q.question}"="${rendered}"`
134
- })
135
- .join(", ")
152
+ }),
153
+ )
154
+ const formatted = formattedParts.join(", ")
136
155
  return `User has answered your questions: ${formatted}. You can now continue with the user's answers in mind.`
137
156
  }
138
157
 
139
- export function restoreQuestionOutput(output: QuestionToolOutput, snapshot: QuestionSnapshot): void {
158
+ export async function restoreQuestionOutput(
159
+ output: QuestionToolOutput,
160
+ snapshot: QuestionSnapshot,
161
+ options: RestoreQuestionOutputOptions = {},
162
+ ): Promise<void> {
140
163
  if (typeof output.output !== "string") return
141
164
  const answersRaw = (output.metadata as { answers?: readonly (readonly string[])[] } | undefined)?.answers
142
165
  const answers = Array.isArray(answersRaw) ? answersRaw : []
143
- output.output = buildRestoredOutput(snapshot.original, snapshot.translated, answers)
166
+ output.output = await buildRestoredOutput(snapshot.original, snapshot.translated, answers, options)
144
167
  }