diff --git a/README.md b/README.md index ba964f8..0fce74f 100644 --- a/README.md +++ b/README.md @@ -297,3 +297,38 @@ For detailed documentation on using Lara CLI: - [Xcode Stringsdict Files Guide](docs/config/files/xcode-stringsdict-files.md) - Complete guide for Xcode .stringsdict plural files - [Xcode String Catalogs Guide](docs/config/files/xcode-xcstrings-files.md) - Complete guide for Xcode .xcstrings String Catalogs - [TXT Files Guide](docs/config/files/txt-files.md) - Complete guide for plain text files + +## Lara Think + +Use `--reasoning` to select Think; `--reasoning-effort` accepts `low`, `medium`, +or `high` (default **high**). Without Think, Lara Base is used. + +```sh +lara-cli translate --text "Hello" --source en --target it --reasoning --reasoning-effort medium +lara-cli translate --file messages.json --source en --target it --reasoning --reasoning-effort low +lara-cli translate --reasoning --reasoning-effort high --force +``` + +For project translations, save the settings in `lara.yaml`: + +```yaml +translation: + reasoning: true + reasoningEffort: high +``` + +Explicit flags override project settings. `--no-reasoning` disables Think and +discards the inherited level. An explicitly supplied level requires Think to +be enabled; `--no-reasoning --reasoning-effort low` is an error. Direct text/file +modes ignore project configuration. Use lowercase level values. + +These options apply to all existing text, file and project translation paths, +including batches and retries. Use `--force` to retranslate existing project +entries after changing model or level. Think requests allow 300 seconds per +request; Base retains 30 seconds. Retries can extend total run time. + +If Lara reports that reasoning was not applied, the translation is retained +and a warning is printed to stderr; stdout and translated files keep their +existing format. Usage metrics are enabled by default, subject to the opt-out +settings described in Usage Metrics above. When enabled, they record the effective +requested level and reported fallback, without translation content. diff --git a/docs/commands/translate.md b/docs/commands/translate.md index 303c85d..89923c6 100644 --- a/docs/commands/translate.md +++ b/docs/commands/translate.md @@ -15,6 +15,9 @@ lara-cli translate [options] | `-t, --target ` | Comma-separated list of target locales to translate to | | `-p, --paths ` | Comma-separated list of specific file paths to translate (overrides config) | | `-f, --force` | Force retranslation of all content, even if unchanged | +| `--reasoning` | Use Lara Think; defaults to high effort | +| `--no-reasoning` | Disable Think, overriding project configuration | +| `--reasoning-effort ` | Think effort: `low`, `medium`, or `high`; requires Think to be enabled | | `--no-trace` | Prevent server-side storage of translated content | | `--orphan-keys ` | `keep` or `delete`. What to do with keys that exist only in target files. Overrides `translation.orphanKeys` in `lara.yaml` for this run. Cannot be combined with `--file` or `--text` | | `-h, --help` | Display help information | @@ -162,6 +165,34 @@ Use `--force` when you need to: - Fix translation errors by regenerating all translations - Reset translations after configuration changes +## Lara Think + +By default, translations use Lara Base. Enable Lara Think for project, text, or file translations: + +```bash +lara-cli translate --reasoning --reasoning-effort medium +lara-cli translate --text "Hello" --source en --target it --reasoning +lara-cli translate --file messages.json --source en --target it --reasoning --reasoning-effort low +``` + +For project translations, save the settings in the existing `translation` section of `lara.yaml`: + +```yaml +translation: + reasoning: true + reasoningEffort: high +``` + +- Effort accepts lowercase `low`, `medium`, or `high`. Think defaults to `high` when no effort is specified. +- Explicit CLI flags override project settings. `--no-reasoning` disables Think and discards the inherited effort. An explicitly supplied effort requires Think to be enabled, either with `--reasoning` or in project configuration; `--no-reasoning --reasoning-effort low` is an error. +- Direct `--text` and `--file` modes ignore project translation settings: enable Think with CLI flags. +- Model or effort changes do not invalidate existing translations. Use `--force` to retranslate existing project entries. +- Each Think API request has a 300-second timeout; Base requests retain 30 seconds. Files and target locales use separate requests, and a file may need multiple batches. Each retry has its own timeout, so total run time can be longer. The timeout is automatic and cannot be configured in YAML. +- If the server reports that Think was not applied, the CLI retains the returned translation and prints a warning to stderr without changing stdout or file formats. This alone does not trigger a retry or fail the command. +- When [usage metrics](../../README.md#usage-metrics) are enabled, command metadata records `reasoning`, the requested `reasoningEffort`, and `reasoningFallback: true` if a fallback was reported, without translation content. + +See [Lara Think configuration](../config/structure.md#lara-think) for configuration defaults and overrides. + ## No-Trace Mode Use `--no-trace` to prevent the translation API from storing or logging your content server-side. This is useful when translating sensitive or confidential content. A no-trace run is also left out of the CLI's [usage metrics](../../README.md#usage-metrics) entirely. @@ -240,6 +271,9 @@ Only [supported file formats](../config/formats.md) are accepted (JSON, PO, XML, | `-o, --output ` | Output file path (only with `--file`) | | `-m, --translation-memories ` | Translation Memory IDs (comma-separated) | | `-g, --glossaries ` | Glossary IDs (comma-separated) | +| `--reasoning` | Use Lara Think; defaults to high effort | +| `--no-reasoning` | Disable Lara Think | +| `--reasoning-effort ` | `low`, `medium`, or `high`; requires `--reasoning` in direct mode | | `--no-trace` | Prevent server-side storage of translated content | ### Using Translation Memories & Glossaries @@ -263,6 +297,7 @@ Use `lara-cli memory` and `lara-cli glossary` to list available IDs. | Translation instructions | Yes | No | | Multiple target locales per invocation | Yes | No (one at a time) | | Translation Memories & Glossaries | Yes | Yes | +| Lara Think | CLI flags or `translation` settings in YAML | CLI flags only | ### Prerequisites diff --git a/docs/config/README.md b/docs/config/README.md index 886fe74..6a9ccae 100644 --- a/docs/config/README.md +++ b/docs/config/README.md @@ -23,6 +23,7 @@ glossaries: - gls_xyz789 noTrace: false translation: + reasoning: false batchSize: 50 orphanKeys: keep files: @@ -38,11 +39,25 @@ files: Lara CLI supports multiple file formats. See [Supported Formats](./formats.md) for a complete list and format-specific guides like [PO Files](./po-files.md). +## Lara Think + +To use Think for project translations, update the existing `translation` section: + +```yaml +translation: + reasoning: true + reasoningEffort: high +``` + +Effort accepts `low`, `medium`, or `high` and defaults to `high` when Think is enabled. Without `reasoning: true`, the CLI uses Lara Base. Explicit CLI flags override these settings; direct `--text` and `--file` modes use CLI flags instead of YAML. + +See [Lara Think configuration](./structure.md#lara-think) for validation, timeout, and fallback behavior. + ## Configuration Sections The configuration is divided into several sections: -- **[Configuration Schema](./structure.md)** - Schema structure and organization of the configuration file, including [translation batching](./structure.md#translation-batching) and [orphan key handling](./structure.md#orphan-keys) +- **[Configuration Schema](./structure.md)** - Schema structure and organization of the configuration file, including [Lara Think](./structure.md#lara-think), [translation batching](./structure.md#translation-batching), and [orphan key handling](./structure.md#orphan-keys) - **[Supported Formats](./formats.md)** - List of supported file formats - **[Locales](./locales.md)** - Source and target language configuration - **[Files](./files.md)** - File paths and exclusion patterns diff --git a/docs/config/structure.md b/docs/config/structure.md index 440b843..33129f0 100644 --- a/docs/config/structure.md +++ b/docs/config/structure.md @@ -14,7 +14,7 @@ lara.yaml ├── memories # Translation memory settings ├── glossaries # Terminology settings ├── noTrace # No-trace mode (no server-side storage, no usage metrics) -├── translation # Translation tuning (batch size, orphan key handling) +├── translation # Translation tuning (Think, batch size, orphan key handling) └── files # File path and processing rules ``` @@ -54,6 +54,8 @@ noTrace: false # Translation tuning translation: + reasoning: true # Enable Lara Think (default: false) + reasoningEffort: high # low | medium | high (default when Think is enabled: high) batchSize: 50 # Max keys sent per translation request (default: 50) orphanKeys: keep # What to do with target-only keys: keep | delete (default: keep) @@ -118,6 +120,34 @@ Configuration settings follow a specific inheritance pattern: This allows for progressive refinement of translation instructions and rules. +## Lara Think + +The optional `translation.reasoning` setting selects Lara Think for project translations. It defaults to `false` (Lara Base). Existing configuration files continue to use Base without changes. + +```yaml +translation: + reasoning: true + reasoningEffort: medium +``` + +`reasoningEffort` accepts lowercase `low`, `medium`, or `high`. Omit it to use `high` when Think is enabled. If `reasoningEffort` is set, Think must be enabled; to disable Think in YAML, set `reasoning: false` and remove `reasoningEffort`. + +Explicit flags on [`translate`](../commands/translate.md#lara-think) override YAML settings: + +```bash +lara-cli translate --reasoning-effort low # Override effort when Think is enabled in YAML +lara-cli translate --no-reasoning # Disable Think and discard inherited effort +lara-cli translate --reasoning --force # Retranslate existing project entries with Think +``` + +An explicitly supplied effort cannot be combined with `--no-reasoning`. Direct `--text` and `--file` modes ignore project translation settings and require `--reasoning` to enable Think. + +Think settings are preserved across batches and retries. The timeout is 300 seconds per Think API request, compared with 30 seconds for Base. Each batch and retry has its own timeout; this is not a total timeout for a file or command, and it is not configurable in YAML. + +If Lara reports that Think was not applied, the returned translation is retained and a warning is printed to stderr. The fallback alone does not trigger a retry or fail the command. When [usage metrics](../../README.md#usage-metrics) are enabled, they record the requested reasoning settings and whether a fallback occurred, without translation content. + +Changing Think settings does not retranslate unchanged entries automatically: use `--force` when you want to apply the new model or effort to existing translations. + ## Translation Batching When a single file contains multiple translatable keys, Lara CLI sends them together in a single API request instead of one request per key. This reduces round trips and makes translation noticeably faster on large files. @@ -181,4 +211,4 @@ Each section of the configuration has its own detailed documentation: - [Files Configuration](./files.md) - [Instructions Configuration](./instructions.md) - [Translation Memories Configuration](./memories.md) -- [Glossaries Configuration](./glossaries.md) \ No newline at end of file +- [Glossaries Configuration](./glossaries.md) diff --git a/package.json b/package.json index 06abc9a..1ec0343 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@translated/lara-cli", "type": "module", - "version": "1.7.3", + "version": "1.8.0", "description": "CLI tool for automated i18n file translation using Lara Translate", "repository": { "type": "git", @@ -44,13 +44,13 @@ "@babel/types": "^7.29.0", "@inquirer/core": "^10.3.2", "@inquirer/prompts": "^7.10.1", - "@translated/lara": "^1.18.0", + "@translated/lara": "^1.18.2", "commander": "^14.0.3", "dotenv": "^17.3.1", "fast-xml-parser": "^5.5.9", "flat": "^6.0.1", "gettext-parser": "^8.0.0", - "glob": "^13.0.6", + "glob": "^14.0.2", "ora": "^8.2.0", "picomatch": "^4.0.4", "proper-lockfile": "^4.1.2", @@ -98,6 +98,7 @@ }, "pnpm": { "overrides": { + "minimatch@>=7.0.0 <11.0.1": "^11.0.1", "brace-expansion@<1.1.18": "^1.1.18", "brace-expansion@>=5.0.0 <5.0.9": "^5.0.9", "form-data@>=4.0.0 <4.0.6": ">=4.0.6", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c83812e..8fc6823 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5,6 +5,7 @@ settings: excludeLinksFromLockfile: false overrides: + minimatch@>=7.0.0 <11.0.1: ^11.0.1 brace-expansion@<1.1.18: ^1.1.18 brace-expansion@>=5.0.0 <5.0.9: ^5.0.9 form-data@>=4.0.0 <4.0.6: '>=4.0.6' @@ -36,8 +37,8 @@ importers: specifier: ^7.10.1 version: 7.10.1(@types/node@24.12.0) '@translated/lara': - specifier: ^1.18.0 - version: 1.18.0 + specifier: ^1.18.2 + version: 1.18.2 commander: specifier: ^14.0.3 version: 14.0.3 @@ -54,8 +55,8 @@ importers: specifier: ^8.0.0 version: 8.0.0 glob: - specifier: ^13.0.6 - version: 13.0.6 + specifier: ^14.0.2 + version: 14.0.4 ora: specifier: ^8.2.0 version: 8.2.0 @@ -521,6 +522,9 @@ packages: '@types/node': optional: true + '@isaacs/nonrecursive-glob-match@1.1.0': + resolution: {integrity: sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==} + '@jridgewell/gen-mapping@0.3.13': resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} @@ -665,8 +669,8 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} - '@translated/lara@1.18.0': - resolution: {integrity: sha512-EmNU7oZzlTOKABv/54QVBo96tol4cDqWSN61kAm1zfppxcVk4WcQATWl0uasiLb+jHJRpoTat3++THwjtcMwUA==} + '@translated/lara@1.18.2': + resolution: {integrity: sha512-9C/AdZeoqpPPY8cXH265mejyH7rWaQHlAsR8ayzYIsRgrFrDtPPO5OgKBjd/lizOk0WZP14avTDfsLEQfMue9Q==} engines: {node: '>=12.*'} '@types/chai@5.2.3': @@ -1172,8 +1176,8 @@ packages: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} - glob@13.0.6: - resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} + glob@14.0.4: + resolution: {integrity: sha512-mMiwNKoJZ4HAIRVJxotO6LsNRReA30gQwP9E2/p94tfLv+jygCNpKDjhhSL6OLY6LE371EZm5EAf7RpYuUqlsw==} engines: {node: 18 || 20 || >=22} globals@14.0.0: @@ -1545,9 +1549,9 @@ packages: resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==} engines: {node: '>=18'} - minimatch@10.2.4: - resolution: {integrity: sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==} - engines: {node: 18 || 20 || >=22} + minimatch@11.0.5: + resolution: {integrity: sha512-snPlVppFcYWfLLFQGhDxUyBcHNtMlWmn3jtj7pEaO+DP8pqL0IvAzXhMYmn1z9ASNtgmwLBdFxSf4tMUB0OTKA==} + engines: {node: 20 || >=22} minimatch@3.1.5: resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} @@ -1610,8 +1614,8 @@ packages: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} - path-scurry@2.0.2: - resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} + path-scurry@3.0.0: + resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==} engines: {node: 18 || 20 || >=22} pathe@2.0.3: @@ -2271,6 +2275,8 @@ snapshots: optionalDependencies: '@types/node': 24.12.0 + '@isaacs/nonrecursive-glob-match@1.1.0': {} + '@jridgewell/gen-mapping@0.3.13': dependencies: '@jridgewell/sourcemap-codec': 1.5.5 @@ -2364,7 +2370,7 @@ snapshots: '@standard-schema/spec@1.1.0': {} - '@translated/lara@1.18.0': + '@translated/lara@1.18.2': dependencies: form-data: 4.0.6 @@ -2481,7 +2487,7 @@ snapshots: '@typescript-eslint/types': 8.57.2 '@typescript-eslint/visitor-keys': 8.57.2 debug: 4.4.3 - minimatch: 10.2.4 + minimatch: 11.0.5 semver: 7.7.4 tinyglobby: 0.2.15 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -2932,11 +2938,11 @@ snapshots: dependencies: is-glob: 4.0.3 - glob@13.0.6: + glob@14.0.4: dependencies: - minimatch: 10.2.4 + minimatch: 11.0.5 minipass: 7.1.3 - path-scurry: 2.0.2 + path-scurry: 3.0.0 globals@14.0.0: {} @@ -3421,8 +3427,9 @@ snapshots: mimic-function@5.0.1: {} - minimatch@10.2.4: + minimatch@11.0.5: dependencies: + '@isaacs/nonrecursive-glob-match': 1.1.0 brace-expansion: 5.0.12 minimatch@3.1.5: @@ -3484,7 +3491,7 @@ snapshots: path-key@3.1.1: {} - path-scurry@2.0.2: + path-scurry@3.0.0: dependencies: lru-cache: 11.2.7 minipass: 7.1.3 diff --git a/src/__tests__/integration/direct-translate.integration.test.ts b/src/__tests__/integration/direct-translate.integration.test.ts index 0f07397..09dd4b5 100644 --- a/src/__tests__/integration/direct-translate.integration.test.ts +++ b/src/__tests__/integration/direct-translate.integration.test.ts @@ -4,7 +4,7 @@ import { existsSync } from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; -import { executeCommand, mockTranslate } from './test-helpers.js'; +import { executeCommand, mockTranslate, mockTranslateBatchWithFallback } from './test-helpers.js'; import translateCommand from '../../cli/cmd/translate/translate.js'; import { ConfigProvider } from '#modules/config/config.provider.js'; @@ -60,7 +60,135 @@ describe('Direct Translation Integration Tests', () => { (ConfigProvider as any).instance = null; }); + it('passes Think through direct file translation', async () => { + const file = path.join(testDir, 'hello.txt'); + await writeFile(file, 'Hello'); + await executeCommand(translateCommand, [ + '--file', + file, + '--source', + 'en', + '--target', + 'it', + '--reasoning', + '--reasoning-effort', + 'medium', + ]); + expect(mockTranslate.mock.lastCall?.[3]).toMatchObject({ + reasoning: true, + reasoningEffort: 'medium', + }); + }); + it.each([ + [[], true, 'low'], + [['--reasoning-effort', 'medium'], true, 'medium'], + [['--no-reasoning'], false, undefined], + ] as const)( + 'resolves project Think flags %s for all targets', + async (flags, reasoning, reasoningEffort) => { + await mkdir(path.join(testDir, 'locales')); + await writeFile( + path.join(testDir, 'locales/en.json'), + JSON.stringify({ hello: 'Hello', world: 'World' }) + ); + await writeFile( + path.join(testDir, 'lara.yaml'), + `version: 1.0.0 +locales: + source: en + target: [it, fr] +translation: + reasoning: true + reasoningEffort: low +files: + json: + include: [locales/[locale].json] +`.replace('include: [locales/[locale].json]', 'include: ["locales/[locale].json"]') + ); + mockTranslate.mockClear(); + mockTranslateBatchWithFallback.mockClear(); + await executeCommand(translateCommand, [...flags]); + const calls = [...mockTranslate.mock.calls, ...mockTranslateBatchWithFallback.mock.calls]; + expect(new Set(calls.map((call) => call[2]))).toEqual(new Set(['it', 'fr'])); + expect(calls.length).toBeGreaterThan(0); + for (const call of calls) expect(call[3]).toMatchObject({ reasoning, reasoningEffort }); + } + ); + describe('text mode', () => { + it.each(['low', 'medium', 'high'])('passes Think %s through text mode', async (level) => { + await executeCommand(translateCommand, [ + '--text', + 'Hello', + '--source', + 'en', + '--target', + 'it', + '--reasoning', + '--reasoning-effort', + level, + ]); + expect(mockTranslate).toHaveBeenLastCalledWith( + expect.anything(), + 'en', + 'it', + expect.objectContaining({ reasoning: true, reasoningEffort: level }) + ); + }); + it('defaults Think to high and allows explicit Base', async () => { + await executeCommand(translateCommand, [ + '--text', + 'Hello', + '--source', + 'en', + '--target', + 'it', + '--reasoning', + ]); + expect(mockTranslate.mock.lastCall?.[3]).toMatchObject({ + reasoning: true, + reasoningEffort: 'high', + }); + await executeCommand(translateCommand, [ + '--text', + 'Hello', + '--source', + 'en', + '--target', + 'it', + '--no-reasoning', + ]); + expect(mockTranslate.mock.lastCall?.[3]?.reasoning).toBe(false); + }); + it('rejects an explicit level with --no-reasoning', async () => { + await expect( + executeCommand(translateCommand, [ + '--text', + 'Hello', + '--source', + 'en', + '--target', + 'it', + '--no-reasoning', + '--reasoning-effort', + 'low', + ]) + ).rejects.toThrow(); + }); + it('rejects a level without Think', async () => { + await expect( + executeCommand(translateCommand, [ + '--text', + 'Hello', + '--source', + 'en', + '--target', + 'it', + '--reasoning-effort', + 'low', + ]) + ).rejects.toThrow(); + }); it('should translate text and output to stdout', async () => { await executeCommand(translateCommand, [ '--text', diff --git a/src/__tests__/translation/think.http.test.ts b/src/__tests__/translation/think.http.test.ts new file mode 100644 index 0000000..b6a9b44 --- /dev/null +++ b/src/__tests__/translation/think.http.test.ts @@ -0,0 +1,95 @@ +import { createServer } from 'node:http'; +import { beforeEach, afterEach, it, expect, vi } from 'vitest'; +import { TranslationService } from '../../modules/translation/translation.service.js'; +import * as metrics from '../../modules/metrics/metrics.js'; + +let server: ReturnType; +let bodies: any[]; +let fallback: boolean; +let failBatch: boolean; +let service: TranslationService; +beforeEach(async () => { + bodies = []; + fallback = false; + failBatch = false; + vi.stubEnv('DO_NOT_TRACK', '1'); + vi.stubEnv('LARA_ACCESS_KEY_ID', 'test'); + vi.stubEnv('LARA_ACCESS_KEY_SECRET', 'test'); + server = createServer(async (req, res) => { + let data = ''; + for await (const chunk of req) data += chunk; + res.setHeader('Content-Type', 'application/json'); + if (req.url === '/v2/auth') { + const token = `x.${Buffer.from(JSON.stringify({ exp: 4102444800 })).toString('base64url')}.x`; + res.end(JSON.stringify({ token })); + return; + } + const body = JSON.parse(data); + bodies.push(body); + if (failBatch && body.q.length > 1) { + res.statusCode = 500; + res.end(JSON.stringify({ error: { type: 'ServerError', message: 'batch failed' } })); + return; + } + res.end( + JSON.stringify({ + translation: body.q, + ...(fallback + ? { + warnings: { + reasoning: { applied: false, error: { status_code: 503, message: 'unavailable' } }, + }, + } + : {}), + }) + '\n' + ); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + vi.stubEnv('LARA_SERVER_URL', `http://127.0.0.1:${(server.address() as { port: number }).port}`); + (TranslationService as any).instance = undefined; + service = TranslationService.getInstance(); +}); +afterEach(async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + (TranslationService as any).instance = undefined; +}); +const blocks = [{ text: 'Hello', translatable: true }]; +it.each(['low', 'medium', 'high'] as const)('sends %s through the real SDK', async (level) => { + await service.translate(blocks, 'en', 'it', { reasoning: true, reasoningEffort: level }); + expect(bodies[0]).toMatchObject({ reasoning: true, effort: level }); +}); +it('defaults to high, keeps Base unchanged, and configures connection deadlines', async () => { + const create = vi.spyOn(service as any, 'createClient'); + await service.translate(blocks, 'en', 'it', { reasoning: true }); + expect(create).toHaveBeenCalledWith(300_000); + expect((service as any).thinkClient.client.timeout).toBe(300_000); + expect((service as any).client.client.timeout).toBe(30_000); + expect(bodies[0].effort).toBe('high'); + await service.translate(blocks, 'en', 'it', {}); + expect(bodies[1]).not.toHaveProperty('effort'); +}); +it('rejects effort without Think before HTTP', async () => { + await expect(service.translate(blocks, 'en', 'it', { reasoningEffort: 'low' })).rejects.toThrow(); + expect(bodies).toHaveLength(0); +}); +it('keeps translation and reports fallback without logging content', async () => { + fallback = true; + const warning = vi.spyOn(console, 'error').mockImplementation(() => {}); + const context = vi.spyOn(metrics, 'setContext'); + expect(await service.translate(blocks, 'en', 'it', { reasoning: true })).toEqual(blocks); + expect(warning).toHaveBeenCalledWith(expect.stringContaining('not applied')); + expect(context).toHaveBeenCalledWith({ reasoningFallback: true }); +}); +it('retains effort across batch retries and per-item fallback', async () => { + failBatch = true; + const result = await service.translateBatchWithFallback([...blocks, ...blocks], 'en', 'it', { + reasoning: true, + reasoningEffort: 'medium', + }); + expect(result).toHaveLength(2); + expect(bodies).toHaveLength(7); + expect(bodies.every((body) => body.reasoning === true && body.effort === 'medium')).toBe(true); +}); diff --git a/src/__tests__/utils/config-think.test.ts b/src/__tests__/utils/config-think.test.ts new file mode 100644 index 0000000..1ad1ad3 --- /dev/null +++ b/src/__tests__/utils/config-think.test.ts @@ -0,0 +1,20 @@ +import { it, expect } from 'vitest'; +import { Config } from '../../modules/config/config.types.js'; +const base = { + version: '1.0.0', + locales: { source: 'en', target: ['it'] }, + files: { json: { include: ['locales/[locale].json'] } }, +}; +it('preserves old configs and accepts all Think levels', () => { + expect(Config.parse(base).translation.reasoning).toBeUndefined(); + for (const reasoningEffort of ['low', 'medium', 'high']) { + expect( + Config.parse({ ...base, translation: { reasoning: true, reasoningEffort } }).translation + ).toMatchObject({ reasoning: true, reasoningEffort }); + } +}); +it.each(['HIGH', 'invalid', null, 1])('rejects invalid configured effort %s', (reasoningEffort) => { + expect( + Config.safeParse({ ...base, translation: { reasoning: true, reasoningEffort } }).success + ).toBe(false); +}); diff --git a/src/cli/cmd/init/init.ts b/src/cli/cmd/init/init.ts index 25dbce8..d8ff43f 100644 --- a/src/cli/cmd/init/init.ts +++ b/src/cli/cmd/init/init.ts @@ -195,7 +195,11 @@ function handleNonInteractiveMode(options: InitOptions): ConfigType { memories: options.translationMemories, glossaries: options.glossaries, noTrace: !options.trace, - translation: { batchSize: DEFAULT_BATCH_SIZE, orphanKeys: DEFAULT_ORPHAN_KEYS }, + translation: { + reasoning: false, + batchSize: DEFAULT_BATCH_SIZE, + orphanKeys: DEFAULT_ORPHAN_KEYS, + }, files: groupPathsByExtension(options.paths), }; } @@ -258,7 +262,11 @@ async function handleInteractiveMode(options: InitOptions): Promise memories: [], glossaries: [], noTrace: !options.trace, - translation: { batchSize: DEFAULT_BATCH_SIZE, orphanKeys: DEFAULT_ORPHAN_KEYS }, + translation: { + reasoning: false, + batchSize: DEFAULT_BATCH_SIZE, + orphanKeys: DEFAULT_ORPHAN_KEYS, + }, files: groupPathsByExtension(inputPaths), }; } diff --git a/src/cli/cmd/translate/translate.ts b/src/cli/cmd/translate/translate.ts index f32413e..db7c9b5 100644 --- a/src/cli/cmd/translate/translate.ts +++ b/src/cli/cmd/translate/translate.ts @@ -30,6 +30,8 @@ import * as metrics from '#modules/metrics/metrics.js'; import { ParserFactory } from '../../../parsers/parser.factory.js'; type TranslateOptions = { + reasoning?: boolean; + reasoningEffort?: 'low' | 'medium' | 'high'; target: string[]; paths: string[]; force: boolean; @@ -112,6 +114,15 @@ export default new Command() 'Glossary IDs to use (separated by a comma, a space or a combination of both). Only with --file or --text.' ).argParser((value) => value.split(COMMA_AND_SPACE_REGEX)) ) + .addOption(new Option('--reasoning', 'Use Lara Think (default effort: high)').default(undefined)) + .addOption(new Option('--no-reasoning', 'Disable Lara Think, overriding project configuration')) + .addOption( + new Option('--reasoning-effort ', 'Lara Think reasoning level; requires Think').choices([ + 'low', + 'medium', + 'high', + ]) + ) .addOption(new Option('--no-trace', 'Prevent server-side storage of translated content')) .addOption( new Option( @@ -148,6 +159,11 @@ async function runTranslate(options: TranslateOptions): Promise { // Existing config-based flow const config = ConfigProvider.getInstance().getConfig(); + const reasoning = options.reasoning ?? config.translation.reasoning; + const reasoningEffort = + options.reasoningEffort ?? + (options.reasoning === false ? undefined : config.translation.reasoningEffort); + Object.assign(options, resolveReasoningOptions(reasoning, reasoningEffort)); if (options.target.includes(config.locales.source)) { throw new Error(Messages.errors.sourceLocaleInTarget); @@ -250,8 +266,19 @@ function validateAndDetectMode(options: TranslateOptions): TranslateMode { return options.text ? 'text' : 'file'; } +export function resolveReasoningOptions( + reasoning?: boolean, + reasoningEffort?: 'low' | 'medium' | 'high' +): LaraTranslateOptions { + if (reasoningEffort !== undefined && reasoning !== true) { + throw new Error('reasoning effort requires reasoning: true (use --reasoning)'); + } + return { reasoning, reasoningEffort: reasoning ? (reasoningEffort ?? 'high') : undefined }; +} + function buildTranslateOptions(options: TranslateOptions): LaraTranslateOptions { return { + ...resolveReasoningOptions(options.reasoning, options.reasoningEffort), adaptTo: options.translationMemories ?? [], glossaries: options.glossaries && options.glossaries.length > 0 ? options.glossaries : undefined, @@ -392,6 +419,8 @@ async function handleFileType( const fileInstructionConfig = fileConfig.fileInstructions.find((fc) => fc.path === inputPath); const translationEngine = new TranslationEngine({ + reasoning: options.reasoning, + reasoningEffort: options.reasoningEffort, sourceLocale, targetLocales, inputPath, diff --git a/src/modules/config/config.types.ts b/src/modules/config/config.types.ts index 1846a37..2dcc469 100644 --- a/src/modules/config/config.types.ts +++ b/src/modules/config/config.types.ts @@ -95,6 +95,8 @@ const Config = z translation: z .object({ + reasoning: z.boolean().optional(), + reasoningEffort: z.enum(['low', 'medium', 'high']).optional(), batchSize: z.number().int().positive().default(DEFAULT_BATCH_SIZE), orphanKeys: z.enum(ORPHAN_KEYS_MODES).default(DEFAULT_ORPHAN_KEYS), }) diff --git a/src/modules/metrics/metrics.ts b/src/modules/metrics/metrics.ts index 748802d..e1d0623 100644 --- a/src/modules/metrics/metrics.ts +++ b/src/modules/metrics/metrics.ts @@ -101,6 +101,9 @@ function authSuccessFile(dir: string, accountId: string): string { /** What a command tells the metrics module about itself while it runs. */ export type RunContext = { + reasoning?: boolean; + reasoningEffort?: 'low' | 'medium' | 'high'; + reasoningFallback?: boolean; /** Which entry point the user reached for. Also decides `feature`. */ mode?: 'text' | 'file' | 'config'; sourceLang?: string; diff --git a/src/modules/translation/translation.engine.ts b/src/modules/translation/translation.engine.ts index 6ab0d80..62a014a 100644 --- a/src/modules/translation/translation.engine.ts +++ b/src/modules/translation/translation.engine.ts @@ -21,6 +21,8 @@ export type TranslationEngineOptions = { inputPath: string; + reasoning?: boolean; + reasoningEffort?: TranslateOptions['reasoningEffort']; forceTranslation: boolean; lockedKeys: string[]; @@ -66,6 +68,8 @@ export class TranslationEngine { private readonly inputPath: string; + private readonly reasoning: Pick; + private readonly forceTranslation: boolean; private readonly lockedPatterns: Matcher[]; @@ -102,6 +106,7 @@ export class TranslationEngine { this.inputPath = options.inputPath; + this.reasoning = { reasoning: options.reasoning, reasoningEffort: options.reasoningEffort }; this.forceTranslation = options.forceTranslation; this.lockedPatterns = options.lockedKeys.map((pattern) => picomatch(pattern)); @@ -413,6 +418,7 @@ export class TranslationEngine { contentType: string ): TranslateOptions { return { + ...this.reasoning, instructions: instruction ? [instruction] : undefined, adaptTo: this.translationMemoryIds.length > 0 ? this.translationMemoryIds : [], // Always pass an array for adaptTo; an empty array prevents Lara from using translation memories when none are explicitly selected glossaries: this.glossaryIds.length > 0 ? this.glossaryIds : undefined, diff --git a/src/modules/translation/translation.service.ts b/src/modules/translation/translation.service.ts index eed4ecc..6d8833b 100644 --- a/src/modules/translation/translation.service.ts +++ b/src/modules/translation/translation.service.ts @@ -57,6 +57,7 @@ export class TranslationService { private static instance: TranslationService; private readonly client: Translator; + private thinkClient?: Translator; private constructor() { this.client = this.createClient(REQUEST_TIMEOUT_MS); @@ -125,6 +126,15 @@ export class TranslationService { targetLocale: string, options: TranslateOptions ): Promise { + if (options.reasoningEffort !== undefined && options.reasoning !== true) { + throw new Error('reasoningEffort requires reasoning: true'); + } + if (options.reasoning) + options = { ...options, reasoningEffort: options.reasoningEffort ?? 'high' }; + metrics.setContext({ + reasoning: options.reasoning, + reasoningEffort: options.reasoning ? (options.reasoningEffort ?? 'high') : undefined, + }); const maxRetries = 5; let attempt = 0; @@ -133,8 +143,22 @@ export class TranslationService { // A real API answer is the only proof the credentials are good: the CLI // has no login step, so reporting() turns the answer into an auth event. const response = await this.reporting( - this.client.translate(textBlocks, sourceLocale, targetLocale, options) + (options.reasoning + ? (this.thinkClient ??= this.createClient(300_000)) + : this.client + ).translate(textBlocks, sourceLocale, targetLocale, options) ); + if (response.warnings?.reasoning?.applied === false) { + console.error( + 'Warning: Lara Think was not applied; the server returned a standard translation.' + ); + metrics.setContext({ reasoningFallback: true }); + } + if (response.warnings?.reasoning?.warnings?.length) { + console.error( + 'Warning: Lara returned reasoning warnings; translation may have reduced context.' + ); + } metrics.recordTranslated(textBlocks.reduce((total, block) => total + block.text.length, 0)); return response.translation; } catch (error) {