Files
OmniRoute/scripts/ad-hoc/nvidia-startswith-diag.ts
Diego Rodrigues de Sa e Souza 191009dd23 Release v3.8.7 (#2919)
* feat(plugins): WordPress-style plugin system backend

* fix(plugins): address code review feedback

- Path traversal guard: validate entryPoint stays within plugin dir
- install() now handles direct plugin directories (not just parent dirs)
- Non-null assertion replaced with explicit null check
- require efficiency: allowedModules map moved outside function
- Source wrapper: add newlines to prevent trailing comment issues
- Config validation: validate values against configSchema on save
- Dynamic import comment: clarify Node.js caching behavior

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): replace vm with child_process, add auth to all routes

Addresses all remaining code review feedback:

1. **Loader rewrite**: Replaced Node.js vm module with child_process.fork()
   for proper process-level isolation. Complies with Rule 3 (no eval).
   Each plugin runs in a separate Node.js process with IPC communication.

2. **Auth on all routes**: Added requireManagementAuth to all 6 plugin
   API route files (list, install, scan, details, activate, deactivate, config).

3. **Env filtering**: Only safe env vars passed to plugin processes unless
   "env" permission is granted.

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): security + ESM fixes for loader and manager

loader.ts:
- Fix IPC: use process.send()/process.on("message") instead of worker_threads.parentPort
- Fix ESM: write host script as .mjs (not .js) to force ESM execution
- Add timeout: 10s default on callHook() with Promise.race
- Add SIGKILL escalation: SIGTERM first, then SIGKILL after 3s grace
- Fix env filtering: use allowlist (safeKeys) instead of passing all env vars
- Clear timeout on successful IPC response (no timer leak)

manager.ts:
- Fix path traversal: use fs.realpath() instead of startsWith()
- Fix imports: use registerHook/unregisterHooks from hooks.ts
- Register hooks individually via registerHook(event, name, handler)

hooks.ts:
- Copied from feat/plugin-custom-hooks (canonical registry)

* feat(discovery): add discovery tool stub service

Phase 1 scaffold for automated provider discovery:
- DiscoveryConfig, DiscoveryResult types
- probeEndpoint() for URL availability checking
- scanProvider() stub (Phase 2 will implement real scanning)
- getDiscoveryResults() stub
- Default config: disabled (opt-in)

* chore(plugins): slop cleanup — pino logger, remove redundant sorts

- index.ts: replace console.log/error with pino structured logging
- hooks.ts: remove redundant .sort() in emitHookBlocking/runOnResponse (already sorted on registration)
- manager.ts: add readFile import

* test(plugins): add scanner, loader, manager unit tests

- scanner: 9 tests (discovery, hidden dirs, validation, entry point, multiple)
- loader: 5 tests (type contracts, Plugin/PluginContext/PluginResult interfaces)
- manager: 6 tests (singleton, lifecycle methods, error on unknown)
- Total: 20 tests, all passing

* fix(settings): add missing home page pin keys to updateSettingsSchema

* feat(plugins): add i18n keys to all 42 locales

* fix(settings): add missing security keys to updateSettingsSchema and add tests

* fix(usage): analytics route reads combo_name/requested_model from call_logs only

The 3.8.6 variant of #2904 added SELECTs of combo_name/requested_model
against usage_history, but those columns only exist in call_logs (no
migration adds them to usage_history). This returned HTTP 500 on
/api/usage/analytics. Restore the working query shape from the 3.8.7
variant. Fixes 18 failing usage-analytics-route tests.

* fix(types,test): resolve noImplicitAny in progressiveAging + align semaphore test to #2903 gate pruning

- progressiveAging: type compression results so messages[0].content is
  indexable (was TS7053 against {}); restores typecheck:noimplicit:core gate.
- services-branch-hardening: #2903 (perf-ram) prunes idle rate-limit gates
  on zero; assert no-running/empty-queue without assuming the entry persists.

* fix(analytics): address merged review regressions

* fix(executor): normalize max effort for openai shape providers

* Make zero-latency combo optimizations opt-in

* Address zero-latency combo review feedback

* chore(release): sync v3.8.7 touchpoints + credit contributors

- llm.txt → 3.8.7 (Current version + Key Features header)
- CHANGELOG: add Dmitry Kuznetsov & Nikolay Alafuzov to 3.8.6 Hall of Contributors
- version already 3.8.7 across package.json/open-sse/electron/openapi (from #2909)

* fix(cleanup): restore usage history cutoff boundary

* docs(changelog): rank 3.8.6 contributors in a commits table with their PRs

* fix(dashboard): theme ReactFlow Controls +/- buttons for dark mode

* fix(settings): add missing home page pin keys to updateSettingsSchema

* fix(settings): add missing security keys to updateSettingsSchema and add tests

* fix(executor): normalize max effort for openai shape providers

* Make zero-latency combo optimizations opt-in

* Address zero-latency combo review feedback

* fix(analytics): address merged review regressions

* fix(cleanup): restore usage history cutoff boundary

* feat(plugins): WordPress-style plugin system backend

* fix(plugins): address code review feedback

- Path traversal guard: validate entryPoint stays within plugin dir
- install() now handles direct plugin directories (not just parent dirs)
- Non-null assertion replaced with explicit null check
- require efficiency: allowedModules map moved outside function
- Source wrapper: add newlines to prevent trailing comment issues
- Config validation: validate values against configSchema on save
- Dynamic import comment: clarify Node.js caching behavior

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): replace vm with child_process, add auth to all routes

Addresses all remaining code review feedback:

1. **Loader rewrite**: Replaced Node.js vm module with child_process.fork()
   for proper process-level isolation. Complies with Rule 3 (no eval).
   Each plugin runs in a separate Node.js process with IPC communication.

2. **Auth on all routes**: Added requireManagementAuth to all 6 plugin
   API route files (list, install, scan, details, activate, deactivate, config).

3. **Env filtering**: Only safe env vars passed to plugin processes unless
   "env" permission is granted.

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): security + ESM fixes for loader and manager

loader.ts:
- Fix IPC: use process.send()/process.on("message") instead of worker_threads.parentPort
- Fix ESM: write host script as .mjs (not .js) to force ESM execution
- Add timeout: 10s default on callHook() with Promise.race
- Add SIGKILL escalation: SIGTERM first, then SIGKILL after 3s grace
- Fix env filtering: use allowlist (safeKeys) instead of passing all env vars
- Clear timeout on successful IPC response (no timer leak)

manager.ts:
- Fix path traversal: use fs.realpath() instead of startsWith()
- Fix imports: use registerHook/unregisterHooks from hooks.ts
- Register hooks individually via registerHook(event, name, handler)

hooks.ts:
- Copied from feat/plugin-custom-hooks (canonical registry)

* feat(discovery): add discovery tool stub service

Phase 1 scaffold for automated provider discovery:
- DiscoveryConfig, DiscoveryResult types
- probeEndpoint() for URL availability checking
- scanProvider() stub (Phase 2 will implement real scanning)
- getDiscoveryResults() stub
- Default config: disabled (opt-in)

* chore(plugins): slop cleanup — pino logger, remove redundant sorts

- index.ts: replace console.log/error with pino structured logging
- hooks.ts: remove redundant .sort() in emitHookBlocking/runOnResponse (already sorted on registration)
- manager.ts: add readFile import

* test(plugins): add scanner, loader, manager unit tests

- scanner: 9 tests (discovery, hidden dirs, validation, entry point, multiple)
- loader: 5 tests (type contracts, Plugin/PluginContext/PluginResult interfaces)
- manager: 6 tests (singleton, lifecycle methods, error on unknown)
- Total: 20 tests, all passing

* feat(plugins): add i18n keys to all 42 locales

* chore(plugins): remove duplicate migration 059_create_plugins.sql

* chore(plugins): remove duplicate migration 059_create_plugins.sql (post-merge)

* fix(sse): guard non-string error.code in proxyFetch + harden model parsing (#2463) (#2923)

Integrated into release/v3.8.7

* fix(docker): add runner-web stage with Playwright Chromium (#2832) (#2846)

Integrated into release/v3.8.7

* docs(changelog): document NVIDIA NIM and error code type-crash fix (#2463)

* test: ignore NVIDIA_BASE_URL and NVIDIA_MODEL in env contract check

---------

Co-authored-by: oyi77 <oyi77@users.noreply.github.com>
Co-authored-by: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>
Co-authored-by: Apostol Apostolov <theapoapostolov@gmail.com>
Co-authored-by: Halil Tezcan KARABULUT <info@hlltzcnkb.com>
Co-authored-by: R.D. <rogerproself@gmail.com>
2026-05-29 19:54:00 -03:00

184 lines
8.1 KiB
TypeScript

/**
* Diagnóstico NVIDIA NIM — `s.startsWith is not a function` (issue #2463 / report 3.8.5+)
*
* Como rodar (a chave NUNCA é commitada — vem por env):
* NVIDIA_API_KEY="nvapi-..." node --import tsx/esm scripts/ad-hoc/nvidia-startswith-diag.ts
*
* Opcional — apontar para outra base/model:
* NVIDIA_BASE_URL="https://integrate.api.nvidia.com/v1/chat/completions"
* NVIDIA_MODEL="openai/gpt-oss-120b"
*
* O que ele faz:
* Parte A — Validação real via validateProviderApiKey() (caminho do botão "testar conexão").
* Parte B — Sanidade do upstream: POST direto na NVIDIA (isola a chave/model do nosso pipeline).
* Parte C — Probes de type-crash SEM chave: alimenta model malformado em resolveModelAlias +
* replica o strip de prefixo de chatCore.ts:3316 e parseModel(), capturando o stack
* NÃO-minificado (rodamos contra a fonte TS) para cravar a linha exata do startsWith.
*
* Parte C não precisa de chave — prova quais linhas são vulneráveis hoje.
*/
const KEY = process.env.NVIDIA_API_KEY ?? "";
const BASE_URL = process.env.NVIDIA_BASE_URL || "https://integrate.api.nvidia.com/v1/chat/completions";
const MODEL = process.env.NVIDIA_MODEL || "openai/gpt-oss-120b";
const line = (s = "") => console.log(s);
const hr = () => line("─".repeat(72));
function show(label: string, value: unknown) {
line(` ${label}: ${typeof value === "string" ? value : JSON.stringify(value)}`);
}
// ──────────────────────────────────────────────────────────────────────────
// Parte A — validateProviderApiKey (caminho de validação/teste de conexão)
// ──────────────────────────────────────────────────────────────────────────
async function partA() {
hr();
line("PARTE A — validateProviderApiKey({ provider: 'nvidia' })");
hr();
if (!KEY) {
line(" ⏭ pulada — defina NVIDIA_API_KEY para rodar.");
return;
}
try {
const { validateProviderApiKey } = await import("../../src/lib/providers/validation.ts");
const providerSpecificData = { baseUrl: BASE_URL };
const result = await validateProviderApiKey({
provider: "nvidia",
apiKey: KEY,
providerSpecificData,
});
line(" ✅ validateProviderApiKey retornou (sem crash):");
show("resultado", result);
if (typeof (result as any)?.error === "string" && (result as any).error.includes("startsWith")) {
line(" ⚠️ A mensagem de erro contém 'startsWith' → crash CAPTURADO dentro do try/catch da validação.");
}
} catch (err: any) {
line(" ❌ validateProviderApiKey LANÇOU (crash não tratado):");
line(` ${err?.message}`);
line(err?.stack ?? String(err));
}
}
// ──────────────────────────────────────────────────────────────────────────
// Parte B — sanidade do upstream NVIDIA (isola chave/model do nosso pipeline)
// ──────────────────────────────────────────────────────────────────────────
async function partB() {
hr();
line("PARTE B — POST direto no upstream NVIDIA (sanidade da chave/model)");
hr();
if (!KEY) {
line(" ⏭ pulada — defina NVIDIA_API_KEY para rodar.");
return;
}
const url = BASE_URL.endsWith("/chat/completions") ? BASE_URL : `${BASE_URL}/chat/completions`;
show("url", url);
show("model", MODEL);
try {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${KEY}` },
body: JSON.stringify({
model: MODEL,
messages: [{ role: "user", content: "ping" }],
max_tokens: 1,
}),
});
const text = await res.text();
show("status", res.status);
line(` body (256): ${text.slice(0, 256)}`);
if (res.ok) line(" ✅ upstream OK — chave e model válidos.");
else if (res.status === 401 || res.status === 403) line(" ❌ chave inválida (401/403).");
else line(" ⚠️ não-OK não-auth — chave provavelmente válida, ver corpo.");
} catch (err: any) {
line(` ❌ fetch falhou: ${err?.message}`);
}
}
// ──────────────────────────────────────────────────────────────────────────
// Parte C — probes de type-crash (sem chave) — crava a linha do startsWith
// ──────────────────────────────────────────────────────────────────────────
async function partC() {
hr();
line("PARTE C — probes de type-crash (resolveModelAlias + strip chatCore:3316 + parseModel)");
hr();
const { resolveModelAlias } = await import("../../open-sse/services/modelDeprecation.ts");
const { parseModel } = await import("../../open-sse/services/model.ts");
// Replica EXATA do trecho de chatCore.ts:3315-3320 (feature #1261), sem guard.
function stripPrefixLikeChatCore(effectiveModel: any, provider: string, alias?: string) {
let finalModelToUpstream = effectiveModel;
if (finalModelToUpstream.startsWith(`${provider}/`)) {
finalModelToUpstream = finalModelToUpstream.slice(provider.length + 1);
} else if (alias && finalModelToUpstream.startsWith(`${alias}/`)) {
finalModelToUpstream = finalModelToUpstream.slice(alias.length + 1);
}
return finalModelToUpstream;
}
const inputs: Array<{ label: string; model: any }> = [
{ label: "string normal (multi-barra NVIDIA)", model: "nvidia/openai/gpt-oss-120b" },
{ label: "objeto {} (UI bug / providerSpecificData mal salvo)", model: {} },
{ label: "objeto {id: '...'}", model: { id: "openai/gpt-oss-120b" } },
{ label: "number", model: 123 },
{ label: "array", model: ["openai/gpt-oss-120b"] },
{ label: "null", model: null },
{ label: "undefined", model: undefined },
];
for (const { label, model } of inputs) {
line("");
line(` ▶ input: ${label} (typeof=${typeof model})`);
// 1) resolveModelAlias — deixa não-string passar? (if (!modelId) return modelId)
let effective: any;
try {
effective = resolveModelAlias(model as any);
line(` resolveModelAlias → ${typeof effective} ${JSON.stringify(effective)}`);
} catch (err: any) {
line(` resolveModelAlias THROW: ${err?.message}`);
effective = model;
}
// 2) strip de prefixo (chatCore:3316) — captura o stack EXATO
try {
const out = stripPrefixLikeChatCore(effective, "nvidia", "nvidia");
line(` chatCore strip → ${JSON.stringify(out)} ✅ sem crash`);
} catch (err: any) {
line(` ❌ chatCore:3316 strip THROW: ${err?.message}`);
const at = (err?.stack ?? "").split("\n").find((l: string) => l.includes(".ts"));
if (at) line(` ${at.trim()}`);
}
// 3) parseModel (model.ts:315) — captura o stack EXATO
try {
const parsed = parseModel(model as any);
line(` parseModel → ${JSON.stringify(parsed)} ✅ sem crash`);
} catch (err: any) {
line(` ❌ model.ts parseModel THROW: ${err?.message}`);
const at = (err?.stack ?? "").split("\n").find((l: string) => l.includes("model.ts"));
if (at) line(` ${at.trim()}`);
}
}
}
async function main() {
line("");
line("NVIDIA NIM — diagnóstico `startsWith is not a function`");
show("NVIDIA_API_KEY presente", KEY ? `sim (${KEY.slice(0, 6)}…)` : "não");
show("BASE_URL", BASE_URL);
show("MODEL", MODEL);
line("");
await partA();
await partB();
await partC();
hr();
line("FIM.");
}
main().catch((e) => {
console.error("erro fatal no diagnóstico:", e);
process.exit(1);
});