@openchamber/web 1.21.0 → 1.22.0
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/bin/cli.test.js +35 -0
- package/bin/lib/DOCUMENTATION.md +12 -0
- package/bin/lib/cli-settings-accessors.js +111 -0
- package/bin/lib/cli-settings-accessors.test.js +189 -0
- package/bin/lib/cli-startup.js +29 -9
- package/bin/lib/commands-connect-url.js +12 -14
- package/dist/assets/{CodeMirrorCommentWidgets-C2BopIs3.js → CodeMirrorCommentWidgets-CPvfxh0N.js} +1 -1
- package/dist/assets/CommitSection-CC5mFzO2.js +1 -0
- package/dist/assets/DiffView-6xGdyI0n.js +4 -0
- package/dist/assets/FilesView-Bm3vT63N.js +17 -0
- package/dist/assets/GitView-B6y1Y69c.js +6 -0
- package/dist/assets/{JsonTreeView-osju7J70.js → JsonTreeView-rwHz84MX.js} +1 -1
- package/dist/assets/LinearIssuesView-B0UM_Rkx.js +1 -0
- package/dist/assets/MarkdownImageGallery-sGilV9Hs.js +1 -0
- package/dist/assets/MarkdownRendererImpl--4sRsKBn.js +12 -0
- package/dist/assets/OnboardingScreen-CECL_Cms.js +1 -0
- package/dist/assets/{PatchDiff-Dan3mADn.js → PatchDiff-BGPl1s-U.js} +1 -1
- package/dist/assets/{PierreDiffViewer-CGoI2v0q.js → PierreDiffViewer-Cvz9Z-io.js} +2 -2
- package/dist/assets/PlanView-BFMsnHk3.js +5 -0
- package/dist/assets/SettingsView-_Gtn5SdT.js +28 -0
- package/dist/assets/{SettingsWindow-DXF-MTHG.js → SettingsWindow-C1Qa09YO.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DrCa1JRk.js → ToolOutputDialog-DzQlzMF4.js} +6 -6
- package/dist/assets/{ToolPartDiffPreview-B_tfvlNF.js → ToolPartDiffPreview-DfVOfwHy.js} +2 -2
- package/dist/assets/{VirtualizedFileDiff-CN_BctrR.js → VirtualizedFileDiff-DT5MDv-u.js} +1 -1
- package/dist/assets/WalkthroughView-D8sLH_M8.js +4 -0
- package/dist/assets/{computeVirtualFileMetrics-Gi1d5eU1.js → computeVirtualFileMetrics-DmpLWhll.js} +1 -1
- package/dist/assets/{contextPanelEmbeddedChat-CpzVNWAv.js → contextPanelEmbeddedChat-BK78t3M_.js} +1 -1
- package/dist/assets/de-C3luvSd_.js +9 -0
- package/dist/assets/es-CmU4HLv9.js +15 -0
- package/dist/assets/fr-Bgyni40l.js +13 -0
- package/dist/assets/index-C57jT0Sa.css +1 -0
- package/dist/assets/{index-Brm3X9rs.js → index-CWYs7sMK.js} +1 -1
- package/dist/assets/index-b0zDkWyg.js +7 -0
- package/dist/assets/{isDiffPlainText-pH9kAJQH.js → isDiffPlainText-BO_q5ezD.js} +1 -1
- package/dist/assets/{isFilePlainText-CVKy_dgB.js → isFilePlainText-D8qPqUAf.js} +1 -1
- package/dist/assets/ja-C1ImKinT.js +15 -0
- package/dist/assets/ko-CP7OdxYH.js +15 -0
- package/dist/assets/main-D4rd8Hy5.js +928 -0
- package/dist/assets/{main-vUCh0VB0.js → main-D7fwjW2z.js} +2 -2
- package/dist/assets/{markdown-shiki.worker-CKGJ1J33.js → markdown-shiki.worker-D5fBU-lw.js} +5 -5
- package/dist/assets/markdownCore-BcmkWZPO.js +3 -0
- package/dist/assets/{miniChat-BlzGEYgE.js → miniChat-D5rraz-g.js} +2 -2
- package/dist/assets/{mobile-CkX6H-IT.js → mobile-Cg_DE3KL.js} +2 -2
- package/dist/assets/{patchFileDiff-BCTsE43U.js → patchFileDiff-Bpql0QGw.js} +3 -3
- package/dist/assets/pl-DQYSiGYX.js +15 -0
- package/dist/assets/pt-BR-DytpsW4M.js +15 -0
- package/dist/assets/{renderElectronMiniChatApp-CJYe_KOL.js → renderElectronMiniChatApp-B_Bn7BbN.js} +2 -2
- package/dist/assets/renderMobileApp-DLfxMzGJ.js +25 -0
- package/dist/assets/runtimeEndpointReset-HlRmXFGW.js +16 -0
- package/dist/assets/scheduledTasksApi-BPvxrynl.js +1 -0
- package/dist/assets/{shikiHighlight-BgTPSITe.js → shikiHighlight-CFAVs_lu.js} +1 -1
- package/dist/assets/tr-aizaUvft.js +6 -0
- package/dist/assets/uk-DwnRxJZd.js +15 -0
- package/dist/assets/useAppFontEffects-DWXGRUPZ.js +7310 -0
- package/dist/assets/{useInlineCommentController-DFFv0hae.js → useInlineCommentController-Cc0OCXr0.js} +2 -2
- package/dist/assets/useRootScrollLock-BFZtfciC.js +1 -0
- package/dist/assets/{vendor-base-ui-_6j2xOWl.js → vendor-base-ui-BeMD8X_w.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-DkQX2EBa.js → vendor-codemirror-language-data-BGFszm8n.js} +2 -2
- package/dist/assets/{vendor-floating-ui-core-CXmKXOXc.js → vendor-floating-ui-core-PuGzNPnN.js} +1 -1
- package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-BTvzWks8.js} +1 -1
- package/dist/assets/{vendor-floating-ui-react-dom-DKpLs02S.js → vendor-floating-ui-react-dom-DxYCWdHj.js} +1 -1
- package/dist/assets/{vendor-floating-ui-utils-BzXdqYpP.js → vendor-floating-ui-utils-D6FqdtJt.js} +1 -1
- package/dist/assets/vendor-linkify-it-DZCzzDkK.js +1 -0
- package/dist/assets/vendor-marked-linkify-it-CXI_LHIE.js +1 -0
- package/dist/assets/vendor-uc.micro-BAd0H0z4.js +1 -0
- package/dist/assets/{web-components-DLnGY4fs.js → web-components-CD-GFayc.js} +4 -4
- package/dist/assets/zh-CN-UDNMxm7r.js +15 -0
- package/dist/assets/zh-TW-BsswdYL-.js +15 -0
- package/dist/index.html +5 -5
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/dist/site.webmanifest +1 -1
- package/dist/sw.js +1 -1
- package/package.json +2 -2
- package/public/site.webmanifest +1 -1
- package/server/index.js +6 -2
- package/server/lib/cloudflare-tunnel.js +1 -1
- package/server/lib/dictation/DOCUMENTATION.md +19 -6
- package/server/lib/dictation/local/model-catalog.js +220 -0
- package/server/lib/dictation/local/model-catalog.test.js +42 -0
- package/server/lib/dictation/local/sherpa-tts.js +41 -20
- package/server/lib/dictation/local/worker-process.js +2 -0
- package/server/lib/dictation/runtime.js +4 -0
- package/server/lib/dictation/service.js +27 -4
- package/server/lib/fs/DOCUMENTATION.md +5 -0
- package/server/lib/fs/routes.js +150 -0
- package/server/lib/fs/routes.test.js +308 -3
- package/server/lib/git/DOCUMENTATION.md +4 -3
- package/server/lib/git/service.js +128 -6
- package/server/lib/git/service.test.js +191 -1
- package/server/lib/linear/DOCUMENTATION.md +97 -0
- package/server/lib/linear/OAUTH-BROKER-HANDOFF.md +91 -0
- package/server/lib/linear/auth.js +436 -0
- package/server/lib/linear/auth.test.js +242 -0
- package/server/lib/linear/client.js +191 -0
- package/server/lib/linear/index.js +61 -0
- package/server/lib/linear/issues.js +499 -0
- package/server/lib/linear/issues.test.js +512 -0
- package/server/lib/linear/mapping.js +188 -0
- package/server/lib/linear/mapping.test.js +147 -0
- package/server/lib/linear/oauth.js +345 -0
- package/server/lib/linear/oauth.test.js +166 -0
- package/server/lib/linear/parse.js +23 -0
- package/server/lib/linear/routes.js +432 -0
- package/server/lib/linear/routes.test.js +661 -0
- package/server/lib/linear/status-runtime.js +64 -0
- package/server/lib/linear/status-runtime.test.js +167 -0
- package/server/lib/linear/status.js +280 -0
- package/server/lib/linear/status.test.js +271 -0
- package/server/lib/linear/teams.js +72 -0
- package/server/lib/linear/teams.test.js +94 -0
- package/server/lib/markdown-image-grants/DOCUMENTATION.md +4 -0
- package/server/lib/markdown-image-grants/routes.js +3 -1
- package/server/lib/markdown-image-grants/routes.test.js +14 -0
- package/server/lib/openchamber-sessions/routes.js +4 -1
- package/server/lib/openchamber-sessions/routes.test.js +23 -0
- package/server/lib/opencode/env-runtime.js +17 -1
- package/server/lib/opencode/env-runtime.test.js +56 -0
- package/server/lib/opencode/feature-routes-runtime.js +2 -0
- package/server/lib/opencode/lifecycle.js +48 -9
- package/server/lib/opencode/lifecycle.test.js +125 -1
- package/server/lib/opencode/managed-process-registry.d.ts +13 -0
- package/server/lib/opencode/managed-process-registry.js +213 -163
- package/server/lib/opencode/managed-process-registry.test.mjs +285 -0
- package/server/lib/opencode/project-directory-runtime.js +16 -11
- package/server/lib/opencode/project-directory-runtime.test.js +32 -12
- package/server/lib/opencode/pwa-manifest-routes.js +1 -1
- package/server/lib/opencode/routes-upgrade.test.js +96 -12
- package/server/lib/opencode/routes.js +53 -5
- package/server/lib/opencode/settings-helpers.js +3 -0
- package/server/lib/opencode/settings-helpers.test.js +10 -0
- package/server/lib/opencode/static-routes-runtime.js +3 -3
- package/server/lib/opencode/theme-runtime.js +1 -1
- package/server/lib/opencode/theme-runtime.test.js +129 -0
- package/server/lib/projects/project-config.js +33 -5
- package/server/lib/projects/project-config.test.js +85 -0
- package/server/lib/quota/DOCUMENTATION.md +19 -0
- package/server/lib/quota/providers/copilot.js +26 -10
- package/server/lib/quota/providers/copilot.test.js +78 -0
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +7 -0
- package/server/lib/small-model/DOCUMENTATION.md +11 -5
- package/server/lib/small-model/call.js +64 -20
- package/server/lib/small-model/call.test.js +184 -2
- package/server/lib/tts/DOCUMENTATION.md +1 -0
- package/server/lib/tts/language-detect.js +210 -0
- package/server/lib/tts/language-detect.test.js +76 -0
- package/server/lib/tts/routes.js +23 -1
- package/server/lib/tts/routes.test.js +26 -0
- package/server/lib/tunnels/install-help.js +2 -2
- package/server/lib/tunnels/install-help.test.js +9 -0
- package/server/lib/walkthrough/languages.js +1 -0
- package/dist/assets/CommitSection-HJeMUAWb.js +0 -1
- package/dist/assets/DiffView-D5cvbEPb.js +0 -4
- package/dist/assets/FilesView-DPU8aNPL.js +0 -17
- package/dist/assets/GitView-Ct6xWrVH.js +0 -6
- package/dist/assets/MarkdownImageGallery-EujHSZ2M.js +0 -1
- package/dist/assets/MarkdownRendererImpl-CPzu4kIr.js +0 -12
- package/dist/assets/OnboardingScreen-w2VG4fWY.js +0 -1
- package/dist/assets/PlanView-Dgg-WTEc.js +0 -4
- package/dist/assets/SessionSwitcherDropdown-CJTrc8K7.js +0 -1
- package/dist/assets/SettingsView-D9yRuFZw.js +0 -28
- package/dist/assets/WalkthroughView-D9Q4lr5x.js +0 -4
- package/dist/assets/de-B_LdJwEM.js +0 -9
- package/dist/assets/es-CubfsAYV.js +0 -15
- package/dist/assets/fr-5qJM0nFS.js +0 -13
- package/dist/assets/index-BW82eK5v.css +0 -1
- package/dist/assets/index-rlLjZUM5.js +0 -7
- package/dist/assets/ja-DJYIBUlH.js +0 -15
- package/dist/assets/ko-DcUBkB7y.js +0 -15
- package/dist/assets/main-DLBxKIoX.js +0 -926
- package/dist/assets/markdownCore-DG6GHLF4.js +0 -3
- package/dist/assets/pl-rB6BLcio.js +0 -15
- package/dist/assets/pt-BR-DcwtlO-o.js +0 -15
- package/dist/assets/renderMobileApp-hQJTnr8B.js +0 -25
- package/dist/assets/runtimeEndpointReset-BDh7r8BL.js +0 -15
- package/dist/assets/scheduledTasksApi-CAGPh_gZ.js +0 -1
- package/dist/assets/uk-INZlFD9A.js +0 -15
- package/dist/assets/useAppFontEffects-Cll4gnsh.js +0 -7268
- package/dist/assets/zh-CN-Dzda8xa1.js +0 -15
- package/dist/assets/zh-TW-Cwn3rNYZ.js +0 -15
|
@@ -25,6 +25,13 @@ in shared project config under the project write lock:
|
|
|
25
25
|
from the winner's persisted `nextRunAt`.
|
|
26
26
|
- Project config writes also take a cross-process `.json.lock` file so the
|
|
27
27
|
read-modify-write is serialized across processes, not only within one process.
|
|
28
|
+
- The sharing processes may run different OpenChamber versions. Normalization
|
|
29
|
+
keeps only the fields a build knows, so every writer persists tasks it did
|
|
30
|
+
not change verbatim from disk and swaps only `state` onto a task whose state
|
|
31
|
+
it updated; a task goes out normalized only when it was deliberately
|
|
32
|
+
replaced (upsert, loop adoption). An older server touching the file after a
|
|
33
|
+
run therefore cannot strip fields a newer build added, such as a task's goal
|
|
34
|
+
or auto-accept settings.
|
|
28
35
|
- Lock timeout / filesystem errors on claim, manual-start, or completion state
|
|
29
36
|
writes always release the in-process running slot (via `finally`) and best-effort
|
|
30
37
|
re-arm the **next future** occurrence; they must not leave the task permanently
|
|
@@ -103,18 +103,24 @@ other runtime API.
|
|
|
103
103
|
`https://chatgpt.com/backend-api/codex/responses` with
|
|
104
104
|
`ChatGPT-Account-Id`; expired tokens are refreshed against
|
|
105
105
|
`auth.openai.com` (single-flight) and written back to `auth.json`.
|
|
106
|
-
- **Anthropic** (`type: api`): `/
|
|
106
|
+
- **Anthropic** (`type: api`): `/messages` with `x-api-key`, against
|
|
107
|
+
`provider.anthropic.options.baseURL` when configured (used as-is, matching
|
|
108
|
+
`@ai-sdk/anthropic` — no `/v1` is inserted) or `https://api.anthropic.com/v1`
|
|
109
|
+
otherwise.
|
|
107
110
|
- **Google** (`type: api`): `generateContent` with `x-goog-api-key`; Gemini 3
|
|
108
|
-
uses `thinkingLevel
|
|
111
|
+
uses `thinkingLevel`, Gemini 2.x uses `thinkingBudget: 0`, and all other
|
|
112
|
+
models omit `thinkingConfig` entirely.
|
|
109
113
|
- Everything else: OpenAI-compatible `/chat/completions` against the
|
|
110
114
|
provider's base URL, resolved from (1) `provider.<id>.options.baseURL`
|
|
111
115
|
in the OpenCode config, (2) the hardcoded `https://api.openai.com/v1`
|
|
112
116
|
endpoint, (3) the endpoint OpenCode resolved at runtime, or (4) the
|
|
113
117
|
provider's `api` field from the models.dev catalog. The credential follows
|
|
114
118
|
the same shape: config `options.apiKey`, then the runtime credential, then
|
|
115
|
-
the auth.json entry.
|
|
116
|
-
|
|
117
|
-
|
|
119
|
+
the auth.json entry. `provider.<id>.options.headers` is sent with the
|
|
120
|
+
request and overrides the bearer default, so gateways that authenticate on
|
|
121
|
+
their own header work here exactly as they do in a chat turn. Configured API
|
|
122
|
+
keys and header values honor OpenCode's `{env:NAME}` and `{file:path}`
|
|
123
|
+
substitutions; file contents and resolved credentials remain server-side.
|
|
118
124
|
- The runtime credential is refused for providers listed in
|
|
119
125
|
`OWN_CREDENTIAL_HANDLING`. Their branches need the stored entry rather than
|
|
120
126
|
a bearer token: the clearest case is the ChatGPT-plan `openai` login, whose
|
|
@@ -2,7 +2,7 @@ import fs from 'fs';
|
|
|
2
2
|
import os from 'os';
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import { readAuthFile, writeAuthFile } from '../opencode/auth.js';
|
|
5
|
-
import { readConfig, readConfigLayers } from '../opencode/shared.js';
|
|
5
|
+
import { readConfig, readConfigLayers, isPlainObject } from '../opencode/shared.js';
|
|
6
6
|
import { getCatalogProvider } from './catalog.js';
|
|
7
7
|
import { getAuthEntryForProvider } from './resolve.js';
|
|
8
8
|
import { getRuntimeProvider } from './runtime-providers.js';
|
|
@@ -19,6 +19,18 @@ const DEFAULT_MAX_OUTPUT_TOKENS = 4_000;
|
|
|
19
19
|
|
|
20
20
|
const USER_AGENT = 'opencode/1.0 openchamber';
|
|
21
21
|
|
|
22
|
+
const mergeHeadersCaseInsensitive = (base, overrides) => {
|
|
23
|
+
const merged = { ...base };
|
|
24
|
+
for (const [name, value] of Object.entries(overrides || {})) {
|
|
25
|
+
const existingName = Object.keys(merged).find((key) => key.toLowerCase() === name.toLowerCase());
|
|
26
|
+
if (existingName) {
|
|
27
|
+
delete merged[existingName];
|
|
28
|
+
}
|
|
29
|
+
merged[name] = value;
|
|
30
|
+
}
|
|
31
|
+
return merged;
|
|
32
|
+
};
|
|
33
|
+
|
|
22
34
|
const CODEX_TOKEN_URL = 'https://auth.openai.com/oauth/token';
|
|
23
35
|
const CODEX_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
|
|
24
36
|
const CODEX_RESPONSES_URL = 'https://chatgpt.com/backend-api/codex/responses';
|
|
@@ -157,11 +169,10 @@ const callOpenaiCompatible = async ({ baseURL, headers, modelID, prompt, system,
|
|
|
157
169
|
});
|
|
158
170
|
const response = await fetch(`${trimmedBase}/chat/completions`, {
|
|
159
171
|
method: 'POST',
|
|
160
|
-
headers: {
|
|
172
|
+
headers: mergeHeadersCaseInsensitive({
|
|
161
173
|
'Content-Type': 'application/json',
|
|
162
174
|
Accept: 'application/json',
|
|
163
|
-
|
|
164
|
-
},
|
|
175
|
+
}, headers),
|
|
165
176
|
body: JSON.stringify({
|
|
166
177
|
model: modelID,
|
|
167
178
|
messages: [
|
|
@@ -340,8 +351,11 @@ const callMessages = async ({ url, headers, modelID, prompt, system, maxOutputTo
|
|
|
340
351
|
return text;
|
|
341
352
|
};
|
|
342
353
|
|
|
343
|
-
const callAnthropic = async ({ apiKey, modelID, prompt, system, maxOutputTokens, responseSchema, timeoutMs, signal }) => callMessages({
|
|
344
|
-
|
|
354
|
+
const callAnthropic = async ({ apiKey, baseURL, modelID, prompt, system, maxOutputTokens, responseSchema, timeoutMs, signal }) => callMessages({
|
|
355
|
+
// Matches @ai-sdk/anthropic: baseURL is the full API prefix (commonly
|
|
356
|
+
// already ending in /v1), so it gets /messages appended as-is rather than
|
|
357
|
+
// having /v1/messages appended, which would double up a configured /v1.
|
|
358
|
+
url: `${(baseURL || 'https://api.anthropic.com/v1').replace(/\/+$/, '')}/messages`,
|
|
345
359
|
headers: {
|
|
346
360
|
'x-api-key': apiKey,
|
|
347
361
|
'anthropic-version': '2023-06-01',
|
|
@@ -403,9 +417,10 @@ const getCopilotEndpoint = async ({ baseURL, headers, modelID }) => {
|
|
|
403
417
|
|
|
404
418
|
const callGoogle = async ({ apiKey, modelID, prompt, system, maxOutputTokens, responseSchema, timeoutMs, signal }) => {
|
|
405
419
|
const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(modelID)}:generateContent`;
|
|
406
|
-
const
|
|
407
|
-
|
|
408
|
-
|
|
420
|
+
const lowerModelID = modelID.toLowerCase();
|
|
421
|
+
const thinkingConfig = lowerModelID.startsWith('gemini-3')
|
|
422
|
+
? { thinkingLevel: lowerModelID.includes('flash') ? 'minimal' : 'low' }
|
|
423
|
+
: lowerModelID.startsWith('gemini-2') ? { thinkingBudget: 0 } : null;
|
|
409
424
|
const response = await fetch(url, {
|
|
410
425
|
method: 'POST',
|
|
411
426
|
headers: {
|
|
@@ -415,13 +430,11 @@ const callGoogle = async ({ apiKey, modelID, prompt, system, maxOutputTokens, re
|
|
|
415
430
|
},
|
|
416
431
|
body: JSON.stringify({
|
|
417
432
|
contents: [{ role: 'user', parts: [{ text: prompt }] }],
|
|
418
|
-
...(system
|
|
433
|
+
...(system && { systemInstruction: { parts: [{ text: system }] } }),
|
|
419
434
|
generationConfig: {
|
|
420
435
|
maxOutputTokens,
|
|
421
|
-
thinkingConfig,
|
|
422
|
-
...(responseSchema
|
|
423
|
-
? { responseMimeType: 'application/json', responseSchema: toGoogleSchema(responseSchema) }
|
|
424
|
-
: {}),
|
|
436
|
+
...(thinkingConfig && { thinkingConfig }),
|
|
437
|
+
...(responseSchema && { responseMimeType: 'application/json', responseSchema: toGoogleSchema(responseSchema) }),
|
|
425
438
|
},
|
|
426
439
|
}),
|
|
427
440
|
signal: requestSignal(timeoutMs, signal),
|
|
@@ -508,7 +521,7 @@ const callCodexResponses = async ({ accessToken, accountId, modelID, prompt, sys
|
|
|
508
521
|
// Custom provider configuration support
|
|
509
522
|
// ---------------------------------------------------------------------------
|
|
510
523
|
|
|
511
|
-
const
|
|
524
|
+
const resolveConfigValue = (value, workingDirectory, providerID, headerName = null) => {
|
|
512
525
|
const envMatch = value.match(/^\{env:([^}]+)\}$/i);
|
|
513
526
|
if (envMatch) {
|
|
514
527
|
return process.env[envMatch[1].trim()]?.trim() || null;
|
|
@@ -529,7 +542,12 @@ const resolveConfigApiKey = (value, workingDirectory, providerID) => {
|
|
|
529
542
|
{ config: layers.customConfig, filePath: layers.paths.customPath },
|
|
530
543
|
{ config: layers.projectConfig, filePath: layers.paths.projectPath },
|
|
531
544
|
{ config: layers.userConfig, filePath: layers.paths.userPath },
|
|
532
|
-
].find(({ config }) =>
|
|
545
|
+
].find(({ config }) => {
|
|
546
|
+
const options = config?.provider?.[providerID]?.options;
|
|
547
|
+
return headerName
|
|
548
|
+
? options?.headers?.[headerName] === value
|
|
549
|
+
: options?.apiKey === value;
|
|
550
|
+
});
|
|
533
551
|
resolvedPath = path.resolve(source?.filePath ? path.dirname(source.filePath) : workingDirectory || process.cwd(), configuredPath);
|
|
534
552
|
}
|
|
535
553
|
|
|
@@ -538,10 +556,33 @@ const resolveConfigApiKey = (value, workingDirectory, providerID) => {
|
|
|
538
556
|
if (!key) throw new Error('empty file');
|
|
539
557
|
return key;
|
|
540
558
|
} catch {
|
|
541
|
-
throw new Error(`Failed to resolve configured apiKey file for provider "${providerID}"`);
|
|
559
|
+
throw new Error(`Failed to resolve configured ${headerName ? `header "${headerName}"` : 'apiKey'} file for provider "${providerID}"`);
|
|
542
560
|
}
|
|
543
561
|
};
|
|
544
562
|
|
|
563
|
+
/**
|
|
564
|
+
* `options.headers` from the provider config, with the same `{env:…}`/`{file:…}`
|
|
565
|
+
* substitutions the API key gets.
|
|
566
|
+
*
|
|
567
|
+
* OpenCode sends these on every request, so dropping them here would have the
|
|
568
|
+
* small model authenticating differently from the request path against the same
|
|
569
|
+
* URL. Gateways fronted by an API-management layer reject a bearer-only request
|
|
570
|
+
* outright, because the header is the credential rather than a supplement to it.
|
|
571
|
+
*/
|
|
572
|
+
const readConfiguredHeaders = (providerCfg, workingDirectory, providerID) => {
|
|
573
|
+
const configured = providerCfg?.options?.headers;
|
|
574
|
+
if (!isPlainObject(configured)) return null;
|
|
575
|
+
const headers = {};
|
|
576
|
+
for (const [name, value] of Object.entries(configured)) {
|
|
577
|
+
// Config headers are strings; a malformed entry is skipped rather than
|
|
578
|
+
// stringified into a header the gateway would reject.
|
|
579
|
+
if (String(value) !== value) continue;
|
|
580
|
+
const resolved = resolveConfigValue(value.trim(), workingDirectory, providerID, name);
|
|
581
|
+
if (resolved) headers[name] = resolved;
|
|
582
|
+
}
|
|
583
|
+
return Object.keys(headers).length ? headers : null;
|
|
584
|
+
};
|
|
585
|
+
|
|
545
586
|
const readProviderConfig = (workingDirectory, providerID) => {
|
|
546
587
|
try {
|
|
547
588
|
const config = readConfig(workingDirectory);
|
|
@@ -549,9 +590,10 @@ const readProviderConfig = (workingDirectory, providerID) => {
|
|
|
549
590
|
if (!providerCfg || typeof providerCfg !== 'object') return null;
|
|
550
591
|
const baseURL = typeof providerCfg?.options?.baseURL === 'string' ? providerCfg.options.baseURL.trim() : null;
|
|
551
592
|
const rawApiKey = typeof providerCfg?.options?.apiKey === 'string' ? providerCfg.options.apiKey.trim() : null;
|
|
552
|
-
const apiKey = rawApiKey ?
|
|
593
|
+
const apiKey = rawApiKey ? resolveConfigValue(rawApiKey, workingDirectory, providerID) : null;
|
|
553
594
|
return {
|
|
554
595
|
baseURL,
|
|
596
|
+
headers: readConfiguredHeaders(providerCfg, workingDirectory, providerID),
|
|
555
597
|
// Shape the config-supplied key as a regular api-key auth entry so it
|
|
556
598
|
// can win the precedence check below and flow through the dispatch's
|
|
557
599
|
// `entry.type === 'api' ? entry.key : ...` branch unchanged.
|
|
@@ -706,7 +748,7 @@ export async function callSmallModel({ auth, catalog, workingDirectory, provider
|
|
|
706
748
|
}
|
|
707
749
|
|
|
708
750
|
if (providerID === 'anthropic') {
|
|
709
|
-
return callAnthropic({ apiKey, modelID, prompt, system, maxOutputTokens: tokens, responseSchema, timeoutMs, signal });
|
|
751
|
+
return callAnthropic({ apiKey, baseURL: providerConfig?.baseURL, modelID, prompt, system, maxOutputTokens: tokens, responseSchema, timeoutMs, signal });
|
|
710
752
|
}
|
|
711
753
|
if (providerID === 'google') {
|
|
712
754
|
return callGoogle({ apiKey, modelID, prompt, system, maxOutputTokens: tokens, responseSchema, timeoutMs, signal });
|
|
@@ -751,7 +793,9 @@ export async function callSmallModel({ auth, catalog, workingDirectory, provider
|
|
|
751
793
|
|
|
752
794
|
return callOpenaiCompatible({
|
|
753
795
|
baseURL,
|
|
754
|
-
headers:
|
|
796
|
+
// Configured headers last: a gateway that authenticates on its own header
|
|
797
|
+
// must be able to override the bearer default rather than sit beside it.
|
|
798
|
+
headers: mergeHeadersCaseInsensitive({ Authorization: `Bearer ${apiKey}` }, providerConfig?.headers),
|
|
755
799
|
modelID,
|
|
756
800
|
prompt,
|
|
757
801
|
system,
|
|
@@ -5,11 +5,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
|
5
5
|
|
|
6
6
|
// readConfig reads merged opencode config layers from disk; mock it so each
|
|
7
7
|
// test controls the provider config without touching the filesystem. call.js
|
|
8
|
-
// imports
|
|
9
|
-
// untouched for this file.
|
|
8
|
+
// imports the config readers and a plain-object predicate from shared.js, so
|
|
9
|
+
// the rest of that module is left untouched for this file.
|
|
10
10
|
vi.mock('../opencode/shared.js', () => ({
|
|
11
11
|
readConfig: vi.fn(),
|
|
12
12
|
readConfigLayers: vi.fn(),
|
|
13
|
+
// Pure predicate with no disk access — the real implementation, so header
|
|
14
|
+
// parsing is exercised rather than stubbed.
|
|
15
|
+
isPlainObject: (value) => value instanceof Object && !Array.isArray(value),
|
|
13
16
|
}));
|
|
14
17
|
|
|
15
18
|
vi.mock('./runtime-providers.js', () => ({ getRuntimeProvider: vi.fn(async () => null) }));
|
|
@@ -67,6 +70,7 @@ describe('callSmallModel — custom provider config', () => {
|
|
|
67
70
|
globalThis.fetch = originalFetch;
|
|
68
71
|
vi.restoreAllMocks();
|
|
69
72
|
delete process.env.OPENCHAMBER_TEST_PROVIDER_KEY;
|
|
73
|
+
delete process.env.OPENCHAMBER_TEST_GATEWAY_KEY;
|
|
70
74
|
});
|
|
71
75
|
|
|
72
76
|
describe('config-supplied credentials (no auth.json entry)', () => {
|
|
@@ -122,6 +126,105 @@ describe('callSmallModel — custom provider config', () => {
|
|
|
122
126
|
expect(lastCall(fetchMock).init.headers.Authorization).toBe('Bearer sk-env-key');
|
|
123
127
|
});
|
|
124
128
|
|
|
129
|
+
it('sends configured provider headers alongside the bearer token', async () => {
|
|
130
|
+
process.env.OPENCHAMBER_TEST_GATEWAY_KEY = 'sub-key';
|
|
131
|
+
readConfig.mockReturnValue({
|
|
132
|
+
provider: {
|
|
133
|
+
custom: {
|
|
134
|
+
options: {
|
|
135
|
+
apiKey: 'sk-config',
|
|
136
|
+
baseURL: 'https://proxy.example.test/v1',
|
|
137
|
+
headers: {
|
|
138
|
+
'Ocp-Apim-Subscription-Key': '{env:OPENCHAMBER_TEST_GATEWAY_KEY}',
|
|
139
|
+
'x-tenant': 'team',
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
fetchMock.mockResolvedValue(ok('hello'));
|
|
146
|
+
|
|
147
|
+
await callSmallModel({
|
|
148
|
+
auth: {},
|
|
149
|
+
catalog: {},
|
|
150
|
+
workingDirectory: '/proj',
|
|
151
|
+
providerID: 'custom',
|
|
152
|
+
modelID: 'model',
|
|
153
|
+
prompt: 'hi',
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
const { init } = lastCall(fetchMock);
|
|
157
|
+
expect(init.headers['Ocp-Apim-Subscription-Key']).toBe('sub-key');
|
|
158
|
+
expect(init.headers['x-tenant']).toBe('team');
|
|
159
|
+
expect(init.headers.Authorization).toBe('Bearer sk-config');
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('resolves a relative header file from the config layer that defines it', async () => {
|
|
163
|
+
const configPath = '/config/opencode.json';
|
|
164
|
+
const secretPath = '/config/gateway-key';
|
|
165
|
+
vi.spyOn(fs, 'readFileSync').mockImplementation((filePath) => {
|
|
166
|
+
if (filePath === secretPath) return 'sub-key\n';
|
|
167
|
+
throw new Error(`Unexpected file read: ${filePath}`);
|
|
168
|
+
});
|
|
169
|
+
const provider = {
|
|
170
|
+
custom: {
|
|
171
|
+
options: {
|
|
172
|
+
apiKey: 'sk-config',
|
|
173
|
+
baseURL: 'https://proxy.example.test/v1',
|
|
174
|
+
headers: { 'x-gateway-key': '{file:./gateway-key}' },
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
readConfig.mockReturnValue({ provider });
|
|
179
|
+
readConfigLayers.mockReturnValue({
|
|
180
|
+
customConfig: {},
|
|
181
|
+
projectConfig: {},
|
|
182
|
+
userConfig: { provider },
|
|
183
|
+
paths: { customPath: null, projectPath: '/project/opencode.json', userPath: configPath },
|
|
184
|
+
});
|
|
185
|
+
fetchMock.mockResolvedValue(ok('hello'));
|
|
186
|
+
|
|
187
|
+
await callSmallModel({
|
|
188
|
+
auth: {},
|
|
189
|
+
catalog: {},
|
|
190
|
+
workingDirectory: '/project',
|
|
191
|
+
providerID: 'custom',
|
|
192
|
+
modelID: 'model',
|
|
193
|
+
prompt: 'hi',
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
expect(lastCall(fetchMock).init.headers['x-gateway-key']).toBe('sub-key');
|
|
197
|
+
expect(fs.readFileSync).toHaveBeenCalledWith(secretPath, 'utf8');
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it('overrides Authorization without depending on header-name casing', async () => {
|
|
201
|
+
readConfig.mockReturnValue({
|
|
202
|
+
provider: {
|
|
203
|
+
custom: {
|
|
204
|
+
options: {
|
|
205
|
+
apiKey: 'sk-config',
|
|
206
|
+
baseURL: 'https://proxy.example.test/v1',
|
|
207
|
+
headers: { authorization: 'Basic gateway-token' },
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
},
|
|
211
|
+
});
|
|
212
|
+
fetchMock.mockResolvedValue(ok('hello'));
|
|
213
|
+
|
|
214
|
+
await callSmallModel({
|
|
215
|
+
auth: {},
|
|
216
|
+
catalog: {},
|
|
217
|
+
workingDirectory: '/project',
|
|
218
|
+
providerID: 'custom',
|
|
219
|
+
modelID: 'model',
|
|
220
|
+
prompt: 'hi',
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
const headers = lastCall(fetchMock).init.headers;
|
|
224
|
+
expect(headers.authorization).toBe('Basic gateway-token');
|
|
225
|
+
expect(headers.Authorization).toBeUndefined();
|
|
226
|
+
});
|
|
227
|
+
|
|
125
228
|
it('uses apiKey and baseURL from provider config when no auth.json entry exists', async () => {
|
|
126
229
|
readConfig.mockReturnValue({
|
|
127
230
|
provider: {
|
|
@@ -316,6 +419,69 @@ describe('callSmallModel — custom provider config', () => {
|
|
|
316
419
|
});
|
|
317
420
|
});
|
|
318
421
|
|
|
422
|
+
describe('anthropic provider custom baseURL override', () => {
|
|
423
|
+
const anthropicOk = (text) => ({
|
|
424
|
+
ok: true,
|
|
425
|
+
status: 200,
|
|
426
|
+
json: async () => ({ content: [{ type: 'text', text }] }),
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
it('respects provider.anthropic.options.baseURL over the hardcoded Anthropic endpoint', async () => {
|
|
430
|
+
readConfig.mockReturnValue({
|
|
431
|
+
provider: { anthropic: { options: { baseURL: 'http://127.0.0.1:3456/v1' } } },
|
|
432
|
+
});
|
|
433
|
+
fetchMock.mockResolvedValue(anthropicOk('ok'));
|
|
434
|
+
|
|
435
|
+
await callSmallModel({
|
|
436
|
+
auth: { anthropic: { type: 'api', key: 'dummy' } },
|
|
437
|
+
catalog: {},
|
|
438
|
+
workingDirectory: '/proj',
|
|
439
|
+
providerID: 'anthropic',
|
|
440
|
+
modelID: 'claude-haiku-4-5',
|
|
441
|
+
prompt: 'hi',
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
const { url, init } = lastCall(fetchMock);
|
|
445
|
+
expect(url).toBe('http://127.0.0.1:3456/v1/messages');
|
|
446
|
+
expect(url).not.toContain('api.anthropic.com');
|
|
447
|
+
expect(init.headers['x-api-key']).toBe('dummy');
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
it('uses a bare-host baseURL as-is without inserting /v1, matching @ai-sdk/anthropic', async () => {
|
|
451
|
+
readConfig.mockReturnValue({
|
|
452
|
+
provider: { anthropic: { options: { baseURL: 'http://127.0.0.1:3456' } } },
|
|
453
|
+
});
|
|
454
|
+
fetchMock.mockResolvedValue(anthropicOk('ok'));
|
|
455
|
+
|
|
456
|
+
await callSmallModel({
|
|
457
|
+
auth: { anthropic: { type: 'api', key: 'dummy' } },
|
|
458
|
+
catalog: {},
|
|
459
|
+
workingDirectory: '/proj',
|
|
460
|
+
providerID: 'anthropic',
|
|
461
|
+
modelID: 'claude-haiku-4-5',
|
|
462
|
+
prompt: 'hi',
|
|
463
|
+
});
|
|
464
|
+
|
|
465
|
+
expect(lastCall(fetchMock).url).toBe('http://127.0.0.1:3456/messages');
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
it('falls back to https://api.anthropic.com when no anthropic baseURL override is configured', async () => {
|
|
469
|
+
readConfig.mockReturnValue({});
|
|
470
|
+
fetchMock.mockResolvedValue(anthropicOk('ok'));
|
|
471
|
+
|
|
472
|
+
await callSmallModel({
|
|
473
|
+
auth: { anthropic: { type: 'api', key: 'sk-ant' } },
|
|
474
|
+
catalog: {},
|
|
475
|
+
workingDirectory: '/proj',
|
|
476
|
+
providerID: 'anthropic',
|
|
477
|
+
modelID: 'claude-haiku-4-5',
|
|
478
|
+
prompt: 'hi',
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
expect(lastCall(fetchMock).url).toBe('https://api.anthropic.com/v1/messages');
|
|
482
|
+
});
|
|
483
|
+
});
|
|
484
|
+
|
|
319
485
|
describe('catalog-based base URL (no config override)', () => {
|
|
320
486
|
it('uses the catalog api field when no config baseURL is set', async () => {
|
|
321
487
|
readConfig.mockReturnValue({});
|
|
@@ -536,6 +702,22 @@ describe('callSmallModel — Google thinking configuration', () => {
|
|
|
536
702
|
const body = JSON.parse(lastCall(fetchMock).init.body);
|
|
537
703
|
expect(body.generationConfig.thinkingConfig).toEqual({ thinkingBudget: 0 });
|
|
538
704
|
});
|
|
705
|
+
|
|
706
|
+
it('omits thinkingConfig for other Google/Gemini models', async () => {
|
|
707
|
+
fetchMock.mockResolvedValue(googleResponse('generated commit'));
|
|
708
|
+
|
|
709
|
+
await callSmallModel({
|
|
710
|
+
auth: { google: { type: 'api', key: 'google-key' } },
|
|
711
|
+
catalog: {},
|
|
712
|
+
workingDirectory: '/proj',
|
|
713
|
+
providerID: 'google',
|
|
714
|
+
modelID: 'gemini-1.5-flash',
|
|
715
|
+
prompt: 'generate',
|
|
716
|
+
});
|
|
717
|
+
|
|
718
|
+
const body = JSON.parse(lastCall(fetchMock).init.body);
|
|
719
|
+
expect(body.generationConfig.thinkingConfig).toBeUndefined();
|
|
720
|
+
});
|
|
539
721
|
});
|
|
540
722
|
|
|
541
723
|
describe('callSmallModel — GitHub Copilot endpoint routing', () => {
|
|
@@ -11,6 +11,7 @@ This module provides server-side Text-to-Speech services using OpenAI's TTS API.
|
|
|
11
11
|
- `packages/web/server/lib/text/summarization.js`: Shared text summarization stub and sanitization utilities. It performs no external Zen calls.
|
|
12
12
|
- `packages/web/server/lib/tts/stt.js`: STT proxy for OpenAI-compatible transcription endpoints.
|
|
13
13
|
- `packages/web/server/lib/tts/base-url.js`: shared base URL validation and normalization for custom OpenAI-compatible endpoints.
|
|
14
|
+
- `packages/web/server/lib/tts/language-detect.js`: dependency-free language detection for voice selection (`detectTextLanguage`, `pickVoiceForLanguage`, `languageOfLocale`). Used by the macOS `say` route (`language: 'auto'` switches to an installed voice whose locale matches the text; the response carries `X-Speech-Voice` and `X-Speech-Language`) and by the dictation module's local TTS model choice.
|
|
14
15
|
|
|
15
16
|
## Public exports
|
|
16
17
|
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Language detection for text-to-speech voice selection.
|
|
3
|
+
*
|
|
4
|
+
* Picks the language a piece of chat text is written in so a TTS provider
|
|
5
|
+
* can choose a matching voice or model. Deliberately small and dependency
|
|
6
|
+
* free: the writing system decides most cases outright, and Latin-script
|
|
7
|
+
* languages are told apart by function words and characteristic letters.
|
|
8
|
+
* The answer is a best effort for voice selection, not a linguistic claim —
|
|
9
|
+
* an unknown language falls back to English rather than failing.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const SCRIPT_RANGES = [
|
|
13
|
+
['hangul', /[가-ᄀ-ᇿ-]/g],
|
|
14
|
+
['kana', /[-ヿ]/g],
|
|
15
|
+
['han', /[一-鿿㐀-䶿]/g],
|
|
16
|
+
['cyrillic', /[Ѐ-ӿ]/g],
|
|
17
|
+
['greek', /[Ͱ-Ͽ]/g],
|
|
18
|
+
['arabic', /[-ۿ]/g],
|
|
19
|
+
['hebrew', /[-]/g],
|
|
20
|
+
['thai', /[-]/g],
|
|
21
|
+
['devanagari', /[ऀ-ॿ]/g],
|
|
22
|
+
['latin', /[A-Za-zÀ-ɏ]/g],
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
const SCRIPT_LANGUAGE = {
|
|
26
|
+
hangul: 'ko',
|
|
27
|
+
greek: 'el',
|
|
28
|
+
arabic: 'ar',
|
|
29
|
+
hebrew: 'he',
|
|
30
|
+
thai: 'th',
|
|
31
|
+
devanagari: 'hi',
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
// Letters that only (or overwhelmingly) occur in one language of a script.
|
|
35
|
+
const LATIN_MARKERS = {
|
|
36
|
+
pl: /[łęąńśźż]/i,
|
|
37
|
+
cs: /[řěůťďň]/i,
|
|
38
|
+
tr: /[ğışİ]/,
|
|
39
|
+
pt: /[ãõ]/i,
|
|
40
|
+
es: /[ñ¿¡]/,
|
|
41
|
+
de: /[ß]/,
|
|
42
|
+
fr: /[œ]/i,
|
|
43
|
+
sv: /[å]/i,
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// Frequent function words per language. Scored by whole-word hits; every
|
|
47
|
+
// list has the same length so scores stay comparable.
|
|
48
|
+
const STOPWORDS = {
|
|
49
|
+
en: ['the', 'and', 'is', 'to', 'of', 'that', 'you', 'with', 'for', 'this', 'are', 'it', 'not', 'have', 'can', 'will', 'your', 'from', 'which', 'when'],
|
|
50
|
+
de: ['und', 'der', 'die', 'das', 'ist', 'nicht', 'mit', 'ein', 'eine', 'auch', 'sich', 'auf', 'für', 'wird', 'werden', 'oder', 'aber', 'wenn', 'sind', 'kann'],
|
|
51
|
+
fr: ['le', 'la', 'les', 'et', 'est', 'une', 'des', 'pour', 'que', 'qui', 'dans', 'pas', 'vous', 'sur', 'avec', 'sont', 'nous', 'cette', 'mais', 'plus'],
|
|
52
|
+
es: ['el', 'la', 'los', 'las', 'que', 'es', 'una', 'por', 'para', 'con', 'del', 'como', 'pero', 'más', 'este', 'esta', 'son', 'tiene', 'puede', 'también'],
|
|
53
|
+
it: ['il', 'la', 'che', 'di', 'è', 'una', 'per', 'non', 'con', 'del', 'della', 'come', 'sono', 'anche', 'questo', 'questa', 'gli', 'nel', 'più', 'essere'],
|
|
54
|
+
pt: ['o', 'a', 'os', 'as', 'que', 'é', 'uma', 'para', 'com', 'não', 'do', 'da', 'como', 'mas', 'também', 'este', 'esta', 'são', 'você', 'pode'],
|
|
55
|
+
pl: ['i', 'nie', 'jest', 'się', 'na', 'to', 'że', 'jak', 'ale', 'dla', 'oraz', 'przez', 'czy', 'tym', 'jego', 'można', 'jeśli', 'tego', 'które', 'także'],
|
|
56
|
+
nl: ['de', 'het', 'een', 'en', 'van', 'is', 'niet', 'dat', 'met', 'voor', 'ook', 'zijn', 'maar', 'als', 'wordt', 'deze', 'kan', 'naar', 'bij', 'dan'],
|
|
57
|
+
cs: ['a', 'je', 'se', 'na', 'to', 'že', 'jak', 'ale', 'pro', 'nebo', 'jsou', 'může', 'také', 'tento', 'když', 'jeho', 'které', 'být', 'aby', 'ještě'],
|
|
58
|
+
tr: ['ve', 'bir', 'bu', 'için', 'ile', 'de', 'da', 'ama', 'gibi', 'daha', 'var', 'olarak', 'çok', 'ne', 'her', 'kadar', 'sonra', 'değil', 'olan', 'ise'],
|
|
59
|
+
sv: ['och', 'att', 'det', 'är', 'en', 'som', 'för', 'inte', 'med', 'till', 'den', 'kan', 'har', 'ett', 'men', 'också', 'eller', 'från', 'när', 'vara'],
|
|
60
|
+
uk: ['і', 'та', 'що', 'це', 'не', 'як', 'для', 'він', 'вона', 'але', 'або', 'також', 'тільки', 'вже', 'якщо', 'його', 'цей', 'ця', 'бути', 'коли'],
|
|
61
|
+
ru: ['и', 'что', 'это', 'не', 'как', 'для', 'он', 'она', 'но', 'или', 'также', 'только', 'уже', 'если', 'его', 'этот', 'эта', 'быть', 'когда', 'чтобы'],
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const LATIN_LANGUAGES = ['en', 'de', 'fr', 'es', 'it', 'pt', 'pl', 'nl', 'cs', 'tr', 'sv'];
|
|
65
|
+
const CYRILLIC_LANGUAGES = ['uk', 'ru'];
|
|
66
|
+
|
|
67
|
+
const countMatches = (text, pattern) => {
|
|
68
|
+
const matches = text.match(pattern);
|
|
69
|
+
return matches ? matches.length : 0;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const scoreStopwords = (words, languages) => {
|
|
73
|
+
const scores = {};
|
|
74
|
+
for (const language of languages) {
|
|
75
|
+
const list = new Set(STOPWORDS[language]);
|
|
76
|
+
let hits = 0;
|
|
77
|
+
for (const word of words) {
|
|
78
|
+
if (list.has(word)) hits += 1;
|
|
79
|
+
}
|
|
80
|
+
scores[language] = hits;
|
|
81
|
+
}
|
|
82
|
+
return scores;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const bestOf = (scores, fallback) => {
|
|
86
|
+
let best = fallback;
|
|
87
|
+
let bestScore = 0;
|
|
88
|
+
for (const [language, score] of Object.entries(scores)) {
|
|
89
|
+
if (score > bestScore) {
|
|
90
|
+
best = language;
|
|
91
|
+
bestScore = score;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return best;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const pickByMarkers = (text, markers) => {
|
|
98
|
+
for (const [language, pattern] of Object.entries(markers)) {
|
|
99
|
+
if (pattern.test(text)) return language;
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* @param {string} text
|
|
106
|
+
* @returns {{ language: string, script: string }} BCP-47 primary language subtag and the dominant script.
|
|
107
|
+
*/
|
|
108
|
+
export function detectTextLanguage(text) {
|
|
109
|
+
const source = typeof text === 'string' ? text : '';
|
|
110
|
+
const counts = SCRIPT_RANGES.map(([script, pattern]) => [script, countMatches(source, pattern)]);
|
|
111
|
+
const letters = counts.reduce((sum, [, count]) => sum + count, 0);
|
|
112
|
+
if (letters === 0) return { language: 'en', script: 'latin' };
|
|
113
|
+
|
|
114
|
+
// Kana settles Japanese even when Han dominates the character count.
|
|
115
|
+
const kana = counts.find(([script]) => script === 'kana')?.[1] ?? 0;
|
|
116
|
+
const han = counts.find(([script]) => script === 'han')?.[1] ?? 0;
|
|
117
|
+
if (kana > 0 && kana + han >= letters * 0.3) return { language: 'ja', script: 'kana' };
|
|
118
|
+
if (han > 0 && han >= letters * 0.3) return { language: 'zh', script: 'han' };
|
|
119
|
+
|
|
120
|
+
const [script] = counts.reduce((best, entry) => (entry[1] > best[1] ? entry : best));
|
|
121
|
+
|
|
122
|
+
if (script in SCRIPT_LANGUAGE) return { language: SCRIPT_LANGUAGE[script], script };
|
|
123
|
+
|
|
124
|
+
const words = source.toLowerCase().split(/[^\p{L}\p{M}']+/u).filter(Boolean);
|
|
125
|
+
|
|
126
|
+
if (script === 'cyrillic') {
|
|
127
|
+
const scores = scoreStopwords(words, CYRILLIC_LANGUAGES);
|
|
128
|
+
const ukMarkers = countMatches(source, /[іїєґ]/gi);
|
|
129
|
+
const ruMarkers = countMatches(source, /[ыэъё]/gi);
|
|
130
|
+
// Letters decide: the two alphabets differ in letters that occur in
|
|
131
|
+
// nearly every sentence. Function words only settle a text that shows
|
|
132
|
+
// neither set, and a text with no Russian-only letters is far more
|
|
133
|
+
// likely Ukrainian than the reverse, so that tie goes to Ukrainian.
|
|
134
|
+
if (ukMarkers !== ruMarkers) return { language: ukMarkers > ruMarkers ? 'uk' : 'ru', script };
|
|
135
|
+
if (scores.uk !== scores.ru) return { language: scores.uk > scores.ru ? 'uk' : 'ru', script };
|
|
136
|
+
return { language: ruMarkers > 0 ? 'ru' : 'uk', script };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const scores = scoreStopwords(words, LATIN_LANGUAGES);
|
|
140
|
+
const marked = pickByMarkers(source, LATIN_MARKERS);
|
|
141
|
+
// A characteristic letter outranks stopword counts unless another language
|
|
142
|
+
// clearly dominates the function words (a German text quoting "façade").
|
|
143
|
+
if (marked && scores[marked] * 2 >= scores[bestOf(scores, marked)]) {
|
|
144
|
+
return { language: marked, script };
|
|
145
|
+
}
|
|
146
|
+
return { language: bestOf(scores, 'en'), script };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Map a detected language onto the locales a voice list uses (`uk_UA`,
|
|
151
|
+
* `en_US`...). Returns the preferred locale prefixes in order.
|
|
152
|
+
* @param {string} language
|
|
153
|
+
* @returns {string[]}
|
|
154
|
+
*/
|
|
155
|
+
function localePrefixesForLanguage(language) {
|
|
156
|
+
const table = {
|
|
157
|
+
en: ['en_US', 'en_GB', 'en'],
|
|
158
|
+
uk: ['uk_UA', 'uk'],
|
|
159
|
+
ru: ['ru_RU', 'ru'],
|
|
160
|
+
de: ['de_DE', 'de'],
|
|
161
|
+
fr: ['fr_FR', 'fr_CA', 'fr'],
|
|
162
|
+
es: ['es_ES', 'es_MX', 'es'],
|
|
163
|
+
it: ['it_IT', 'it'],
|
|
164
|
+
pt: ['pt_BR', 'pt_PT', 'pt'],
|
|
165
|
+
pl: ['pl_PL', 'pl'],
|
|
166
|
+
nl: ['nl_NL', 'nl_BE', 'nl'],
|
|
167
|
+
cs: ['cs_CZ', 'cs'],
|
|
168
|
+
tr: ['tr_TR', 'tr'],
|
|
169
|
+
sv: ['sv_SE', 'sv'],
|
|
170
|
+
zh: ['zh_CN', 'zh_TW', 'zh_HK', 'zh'],
|
|
171
|
+
ja: ['ja_JP', 'ja'],
|
|
172
|
+
ko: ['ko_KR', 'ko'],
|
|
173
|
+
el: ['el_GR', 'el'],
|
|
174
|
+
ar: ['ar_001', 'ar_SA', 'ar'],
|
|
175
|
+
he: ['he_IL', 'he'],
|
|
176
|
+
th: ['th_TH', 'th'],
|
|
177
|
+
hi: ['hi_IN', 'hi'],
|
|
178
|
+
};
|
|
179
|
+
return table[language] ?? [language];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Choose a voice for a language from a `say`-style voice list.
|
|
184
|
+
* Prefers an enhanced/premium variant of a matching voice, then any voice of
|
|
185
|
+
* the exact locale, then any voice of the language. Returns null when the
|
|
186
|
+
* list has no voice for that language.
|
|
187
|
+
* @param {string} language
|
|
188
|
+
* @param {ReadonlyArray<{ name: string, locale: string }>} voices
|
|
189
|
+
* @returns {string | null}
|
|
190
|
+
*/
|
|
191
|
+
export function pickVoiceForLanguage(language, voices) {
|
|
192
|
+
const prefixes = localePrefixesForLanguage(language);
|
|
193
|
+
for (const prefix of prefixes) {
|
|
194
|
+
const matching = voices.filter((voice) => voice.locale === prefix || voice.locale.startsWith(`${prefix}_`) || (prefix === language && voice.locale.startsWith(`${language}_`)));
|
|
195
|
+
if (matching.length === 0) continue;
|
|
196
|
+
const enhanced = matching.find((voice) => /\((Enhanced|Premium)\)/i.test(voice.name));
|
|
197
|
+
return (enhanced ?? matching[0]).name;
|
|
198
|
+
}
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Language of a voice, from its locale (`uk_UA` → `uk`).
|
|
204
|
+
* @param {string | null | undefined} locale
|
|
205
|
+
* @returns {string | null}
|
|
206
|
+
*/
|
|
207
|
+
export function languageOfLocale(locale) {
|
|
208
|
+
if (typeof locale !== 'string' || !locale) return null;
|
|
209
|
+
return locale.split(/[_-]/)[0].toLowerCase();
|
|
210
|
+
}
|