opencode-translate 0.3.2 → 0.3.3

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
@@ -1,179 +1,41 @@
1
1
  # opencode-translate
2
2
 
3
- `opencode-translate` is an OpenCode plugin that lets the user chat in a configured `lang` while the main chat loop and compaction summariser only see English.
4
-
5
- ## What It Does
6
-
7
- - Activates once per root session when any root-session user message contains a trigger keyword such as `$en`.
8
- - Translates user-authored text parts from `lang` 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 `lang` when each text part completes.
12
- - Translates the built-in `question` tool's question text, header, and every option's label and description into `lang` 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
- - Stores assistant text as:
14
-
15
- ```md
16
- <english>
17
-
18
- <!-- oc-translate:{nonce}:start -->
19
- ---
20
-
21
- **Translation ({lang}):**
22
-
23
- <translated>
24
- <!-- oc-translate:{nonce}:end -->
25
- ```
26
-
27
- - Strips that trailer back out before later LLM turns, so the model history stays English-only.
28
-
29
- ## v1 Limits
30
-
31
- - No mid-session toggle off.
32
- - No auto-detection of the user's language. `lang` is required.
33
- - No title translation or title-path English enforcement.
34
- - No subagent translation.
35
- - No translation of tool inputs, tool outputs, or reasoning parts.
36
- - Edited historical translated user messages are passed through as-is instead of being re-translated (the original edited text is what the LLM sees).
37
-
38
- ## Hook Failure Handling
39
-
40
- Hooks never throw. If the translator fails (network error, auth failure, provider 4xx/5xx), the plugin:
41
-
42
- 1. Logs the error via `client.app.log` (visible with `verbose: true`).
43
- 2. Emits a `⚠️ Translation failed: …` synthetic part.
44
- 3. Falls back to sending the original (untranslated) user text to the model.
45
- 4. On activation-turn failure, it also rolls back activation so the next turn retries cleanly.
46
-
47
- A stalled provider request is additionally bounded by a 180s hard timeout per translation call, so a hung upstream cannot block the OpenCode session.
48
-
49
3
  ## Install
50
4
 
51
5
  ```bash
52
- npm install -g opencode-translate
6
+ bun add -g opencode-translate
53
7
  ```
54
8
 
55
- Add it to `~/.config/opencode/opencode.json`:
9
+ ## Setup
56
10
 
57
- ```json
11
+ Add to `~/.config/opencode/opencode.jsonc`:
12
+
13
+ ```jsonc
58
14
  {
59
15
  "plugin": [
60
16
  ["opencode-translate", {
61
- "model": "anthropic/claude-haiku-4-5",
62
- "triggerKeywords": ["$en"],
63
- "lang": "Korean",
64
- "verbose": false
17
+ "model": "anthropic/claude-haiku-4-5", // model to use for translation
18
+ "lang": "Korean" // language you speak
65
19
  }]
66
20
  ]
67
21
  }
68
22
  ```
69
23
 
70
- Then make sure the translator provider has credentials. Any of these work:
71
-
72
- ```bash
73
- opencode auth login anthropic
74
- export ANTHROPIC_API_KEY=...
75
- ```
24
+ ## Usage
76
25
 
77
- Put the trigger in the message where translation should begin. Earlier messages in the session are left as-is:
26
+ Prefix any message with `$en` to activate translation for that session.
78
27
 
79
- ```text
80
- $en 프로젝트 루트의 package.json을 읽고 요약해줘
81
28
  ```
82
-
83
- ## Options
84
-
85
- | Option | Type | Default |
86
- | --- | --- | --- |
87
- | `model` | string | Required |
88
- | `triggerKeywords` | string[] | `[$en]` |
89
- | `lang` | string | Required |
90
- | `apiKey` | string | `undefined` |
91
- | `verbose` | boolean | `false` |
92
-
93
- Set `model` to the translator model in `provider/model-id` form, such as `"anthropic/claude-haiku-4-5"`.
94
-
95
- Set `lang` to the full name of the language the user reads and writes, such as `"Korean"`, `"Japanese"`, or `"Brazilian Portuguese"`. The value is injected directly into translation prompts, so language code mapping is not required.
96
-
97
- ## Privacy
98
-
99
- Using this plugin means text goes to two model providers per turn:
100
-
101
- - the normal OpenCode chat provider
102
- - the configured `model` provider
103
-
104
- If you need strict single-provider or self-hosted-only behavior, do not enable this plugin.
105
-
106
- ## Authentication
107
-
108
- Translator requests are made through the AI SDK directly, but provider setup mirrors OpenCode's resolved provider metadata from `client.provider.list()`: provider/model package metadata, configured provider options, model headers, resolved env/API keys, and plugin-auth-loader options that OpenCode exposes there.
109
-
110
- For OAuth records that OpenCode does not expose through the plugin SDK, the plugin reads OpenCode auth content/files and adapts the request only where direct AI SDK calls need it.
111
-
112
- ## Anthropic OAuth Support
113
-
114
- If `model` uses Anthropic and OpenCode auth is backed by Anthropic OAuth (Claude Pro/Max), the plugin reuses those OAuth credentials for translation requests.
115
-
116
- Anthropic's `/v1/messages` endpoint rejects OAuth-authenticated requests that do not match the Claude Code CLI fingerprint (response: `429 rate_limit_error` with an empty `"Error"` message). To pass, the plugin applies the same transformation that `@ex-machina/opencode-anthropic-auth` uses for OpenCode's main chat, but only for its own translator requests:
117
-
118
- - `user-agent: claude-cli/2.1.87 (external, cli)`
119
- - Required `anthropic-beta` headers (`oauth-2025-04-20`, `interleaved-thinking-2025-05-14`)
120
- - `?beta=true` appended to the `/v1/messages` URL
121
- - `x-anthropic-billing-header` block prepended to `system[]` (deterministic CCH of the first user message)
122
- - `"You are a Claude agent, built on Anthropic's Claude Agent SDK."` injected as the next `system[]` block
123
-
124
- The technique and constants are documented in https://github.com/ex-machina-co/opencode-anthropic-auth. See `src/anthropic-oauth.ts`.
125
-
126
- Tradeoffs:
127
-
128
- - Relies on an undocumented Anthropic OAuth request shape. Anthropic can change this at any time and force the plugin to stop using OAuth.
129
- - OpenCode upstream removed Anthropic OAuth support for legal / policy reasons. Installing this plugin reintroduces an equivalent code path in your environment.
130
- - Translator requests contribute to your Claude Pro/Max rate limit alongside OpenCode's main chat.
131
-
132
- If you prefer a plain API key, set `ANTHROPIC_API_KEY`, use `opencode auth login anthropic`, or pass `apiKey` in plugin options.
133
-
134
- ## OpenAI OAuth Support
135
-
136
- If `model` uses OpenAI and OpenCode auth is backed by the ChatGPT/Codex OAuth flow, the plugin reuses those OAuth credentials for translation requests.
137
-
138
- For OAuth-backed OpenAI requests, the plugin routes the OpenAI AI SDK request to `https://chatgpt.com/backend-api/codex/responses`, adds the required Codex beta/originator headers, normalizes the request body to Codex's expected typed `input` shape, and converts Codex SSE responses back to JSON for translation calls. This supports models such as `openai/gpt-5.5` when your ChatGPT plan has access.
139
-
140
- For OpenAI, an OAuth record from `opencode auth login openai` takes precedence over `OPENAI_API_KEY` and plugin `apiKey`. API keys are only used when no OpenAI OAuth record is available.
141
-
142
- ## Manual Smoke Test
143
-
144
- 1. Install the plugin and configure `lang: "Korean"`.
145
- 2. Start a new session and send `$en 프로젝트 루트의 package.json을 읽고 요약해줘`.
146
- 3. Confirm the activation banner appears.
147
- 4. Confirm the `→ EN: ...` preview appears under the user message.
148
- 5. Confirm assistant text streams in English, then gains a translated trailer when the text part finishes.
149
- 6. Confirm later messages in the same session translate without repeating `$en`.
150
- 7. Confirm editing a historical translated user message falls back to the edited text being sent as-is (with a log entry visible under `verbose: true`).
151
- 8. Confirm task-tool child sessions are not translated.
152
- 9. Confirm the title remains in the source language in v1.
153
-
154
- ## Development
155
-
156
- ```bash
157
- bun install
158
- bun run check # biome format + lint + organize imports (write)
159
- bun run typecheck # tsgo (@typescript/native-preview, TS v7 beta)
160
- bun test
161
- ```
162
-
163
- To only verify without writing:
164
-
165
- ```bash
166
- bun run check:ci
29
+ $en 프로젝트 루트의 package.json을 읽고 요약해줘
167
30
  ```
168
31
 
169
- ### Release
32
+ All subsequent messages in the same session are translated automatically — no need to repeat `$en`.
170
33
 
171
- `main` 브랜치에 푸시될 때 `package.json`의 `version`이 npm에 아직 없는 값이면, `.github/workflows/publish.yml`이 자동으로:
172
-
173
- 1. `biome check`, `tsgo`, `bun test` 실행
174
- 2. `npm publish --provenance --access public`
175
- 3. `vX.Y.Z` git 태그와 GitHub Release 생성
176
-
177
- 버전을 올리려면 `package.json`의 `version`만 수정해 main에 merge 하세요. 이미 publish된 버전이면 workflow는 publish를 건너뜁니다.
34
+ ## Options
178
35
 
179
- `docs/spec.en.md` is the source of truth for behavior.
36
+ | Option | Type | Default | Description |
37
+ | --- | --- | --- | --- |
38
+ | `model` | string | required | Translator model in `provider/model-id` form |
39
+ | `lang` | string | required | Language you speak (e.g. `"Korean"`, `"Japanese"`) |
40
+ | `trigger` | string[] | `["$en"]` | Keywords that activate translation |
41
+ | `verbose` | boolean | `false` | Print translation logs |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-translate",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "OpenCode plugin that lets the user chat in a configured language while the main chat loop only sees English.",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -42,7 +42,7 @@ async function activateFromTrigger(
42
42
  if (resolved.state || !resolved.canActivate)
43
43
  return { state: resolved.state, activatedThisTurn: false, aborted: false }
44
44
 
45
- const match = findTriggerMatch(output.parts as TextPartLike[], ctx.options.triggerKeywords)
45
+ const match = findTriggerMatch(output.parts as TextPartLike[], ctx.options.trigger)
46
46
  if (!match) return { activatedThisTurn: false, aborted: false }
47
47
 
48
48
  const part = output.parts[match.partArrayIndex] as TextPartLike & { text: string }
@@ -5,14 +5,14 @@ function escapeRegex(value: string): string {
5
5
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
6
6
  }
7
7
 
8
- export function findTriggerMatch(parts: TextPartLike[], triggerKeywords: string[]): TriggerMatch | undefined {
8
+ export function findTriggerMatch(parts: TextPartLike[], trigger: string[]): TriggerMatch | undefined {
9
9
  let eligibleIndex = 0
10
10
  for (let partArrayIndex = 0; partArrayIndex < parts.length; partArrayIndex += 1) {
11
11
  const part = parts[partArrayIndex]
12
12
  if (!isUserAuthoredTextPart(part)) continue
13
13
 
14
14
  let bestForPart: TriggerMatch | undefined
15
- for (const keyword of triggerKeywords) {
15
+ for (const keyword of trigger) {
16
16
  const pattern = new RegExp(`(^|[ \\t\\r\\n\\f\\v])${escapeRegex(keyword)}(?=$|[ \\t\\r\\n\\f\\v])`)
17
17
  const match = pattern.exec(part.text)
18
18
  if (!match) continue
package/src/auth/index.ts CHANGED
@@ -10,7 +10,6 @@ import {
10
10
  type PluginClientLike,
11
11
  type ProviderInfo,
12
12
  parseTranslatorModel,
13
- type ResolvedTranslateOptions,
14
13
  unwrapData,
15
14
  } from "../constants"
16
15
  import { buildOAuthFetch } from "./oauth-fetch"
@@ -67,11 +66,7 @@ async function getProvider(client: PluginClientLike, providerID: string): Promis
67
66
  }
68
67
  }
69
68
 
70
- export function createCredentialResolver(
71
- client: PluginClientLike,
72
- options: ResolvedTranslateOptions,
73
- deps: AuthDependencies = {},
74
- ) {
69
+ export function createCredentialResolver(client: PluginClientLike, deps: AuthDependencies = {}) {
75
70
  const credentialCache = new Map<string, ResolvedCredential>()
76
71
  const oauthRefreshInflight = new Map<string, Promise<OAuthInfo>>()
77
72
  const runtime: AuthRuntime = {
@@ -133,12 +128,6 @@ export function createCredentialResolver(
133
128
  }
134
129
  if (cached && !(providerID === "openai" && cached.mode === "oauth" && authInfo?.type !== "oauth")) return cached
135
130
 
136
- if (options.apiKey) {
137
- const resolved = { providerID, provider, authInfo, apiKey: options.apiKey, mode: "apiKey" as const }
138
- credentialCache.set(providerID, resolved)
139
- return resolved
140
- }
141
-
142
131
  const providerKey = normalizeProviderKey(provider?.key)
143
132
  if (providerKey) {
144
133
  const resolved = { providerID, provider, authInfo, apiKey: providerKey, mode: "apiKey" as const }
@@ -13,7 +13,7 @@ export function buildInboundTranslationError(userLanguage: string, reason: strin
13
13
 
14
14
  export function buildAuthUnavailableError(providerID: string, envVar: string): Error {
15
15
  return new Error(
16
- `[${PLUGIN_NAME}:AUTH_UNAVAILABLE] No credential found for provider "${providerID}". Set ${envVar} in the environment, run "opencode auth login ${providerID}", or set options.apiKey in opencode.json.`,
16
+ `[${PLUGIN_NAME}:AUTH_UNAVAILABLE] No credential found for provider "${providerID}". Set ${envVar} in the environment or run "opencode auth login ${providerID}".`,
17
17
  )
18
18
  }
19
19
 
@@ -1,4 +1,4 @@
1
- import { AUTH_ENV_FALLBACK, DEFAULT_TRIGGER_KEYWORDS, PLUGIN_NAME } from "./plugin"
1
+ import { AUTH_ENV_FALLBACK, DEFAULT_TRIGGER, PLUGIN_NAME } from "./plugin"
2
2
  import type { ProviderInfo, ResolvedTranslateOptions } from "./types"
3
3
 
4
4
  export function resolveOptions(options: Record<string, unknown>): ResolvedTranslateOptions {
@@ -22,15 +22,14 @@ export function resolveOptions(options: Record<string, unknown>): ResolvedTransl
22
22
  )
23
23
  }
24
24
 
25
- const triggerKeywords = Array.isArray(options.triggerKeywords)
26
- ? options.triggerKeywords.filter((value): value is string => typeof value === "string" && value.length > 0)
27
- : DEFAULT_TRIGGER_KEYWORDS
25
+ const trigger = Array.isArray(options.trigger)
26
+ ? options.trigger.filter((value): value is string => typeof value === "string" && value.length > 0)
27
+ : DEFAULT_TRIGGER
28
28
 
29
29
  return {
30
30
  model,
31
- triggerKeywords: triggerKeywords.length > 0 ? triggerKeywords : [...DEFAULT_TRIGGER_KEYWORDS],
31
+ trigger: trigger.length > 0 ? trigger : [...DEFAULT_TRIGGER],
32
32
  lang,
33
- apiKey: typeof options.apiKey === "string" && options.apiKey.length > 0 ? options.apiKey : undefined,
34
33
  verbose: options.verbose === true,
35
34
  }
36
35
  }
@@ -1,7 +1,7 @@
1
1
  export const PLUGIN_NAME = "opencode-translate"
2
2
  export const SPEC_VERSION = 2
3
3
  export const LLM_LANGUAGE = "English"
4
- export const DEFAULT_TRIGGER_KEYWORDS = ["$en"]
4
+ export const DEFAULT_TRIGGER = ["$en"]
5
5
  export const OAUTH_DUMMY_KEY = "opencode-oauth-dummy-key"
6
6
  export const NONCE_PATTERN = /^[0-9a-f]{32}$/
7
7
  export const FAILURE_NOTICE = "_Translation unavailable for this segment._"
@@ -6,9 +6,8 @@ type ProviderSource = "env" | "config" | "custom" | "api"
6
6
 
7
7
  export interface ResolvedTranslateOptions {
8
8
  model: string
9
- triggerKeywords: string[]
9
+ trigger: string[]
10
10
  lang: string
11
- apiKey?: string
12
11
  verbose: boolean
13
12
  }
14
13
 
@@ -62,7 +62,7 @@ export function createTranslator(
62
62
  const sleepImpl = deps.sleep ?? ((ms: number) => sleep(ms))
63
63
  const now = deps.now ?? (() => Date.now())
64
64
  const generateTextImpl = deps.generateTextImpl ?? generateText
65
- const credentialResolver = deps.credentialResolver ?? createCredentialResolver(client, options)
65
+ const credentialResolver = deps.credentialResolver ?? createCredentialResolver(client)
66
66
  const timeoutMs = deps.timeoutMs ?? DEFAULT_TRANSLATE_TIMEOUT_MS
67
67
 
68
68
  async function translateText(input: TranslateTextInput): Promise<string> {