diff --git a/CHANGELOG.md b/CHANGELOG.md index b1561b9..794349f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## Unreleased — env prefix rename + +- **Environment variables are now named `PATCHLING_` instead of `GPTDIFF_`** + (`PATCHLING_MODEL`, `PATCHLING_LLM_BASE_URL`, `PATCHLING_LLM_API_KEY`, + `PATCHLING_FILTER_MODEL`, `PATCHLING_SMARTAPPLY_MODEL`, + `PATCHLING_LIVE`, …), matching patchling-py. The `GPTDIFF_` spellings keep + working as legacy aliases: each is consulted when its `PATCHLING_` name is + unset, and `PATCHLING_` always wins when both are set. + ## [0.3.2] — Unreleased Reject incomplete OpenAI-compatible completions and preserve concurrent disk-cache writes. This version prepares the fixes merged in #16 for a future npm release; it has not been published. diff --git a/README.md b/README.md index 7ba481a..f41e484 100644 --- a/README.md +++ b/README.md @@ -90,14 +90,14 @@ Configuration comes from environment variables (Node) or `setEnv(...)` overrides | Variable | Purpose | Default | | --- | --- | --- | -| `GPTDIFF_LLM_API_KEY` | NanoGPT API key (`sk-nano-…`) | — (required for live calls) | -| `GPTDIFF_LLM_BASE_URL` | OpenAI-compatible base URL | `https://nano-gpt.com/api/v1/` | -| `GPTDIFF_MODEL` | Model id | `deepseek/deepseek-v4.1-flash-1017` | -| `GPTDIFF_FILTER_MODEL` | Cheap model for `filterRelevant` | `xiaomi/mimo-v2.6-flash` | +| `PATCHLING_LLM_API_KEY` | NanoGPT API key (`sk-nano-…`) | — (required for live calls) | +| `PATCHLING_LLM_BASE_URL` | OpenAI-compatible base URL | `https://nano-gpt.com/api/v1/` | +| `PATCHLING_MODEL` | Model id | `deepseek/deepseek-v4.1-flash-1017` | +| `PATCHLING_FILTER_MODEL` | Cheap model for `filterRelevant` | `xiaomi/mimo-v2.6-flash` | ```js import { setEnv } from 'patchling'; -setEnv('GPTDIFF_LLM_API_KEY', 'sk-nano-…'); // browser, no process.env +setEnv('PATCHLING_LLM_API_KEY', 'sk-nano-…'); // browser, no process.env ``` ## Sign in with NanoGPT (OAuth 2.0 + PKCE) @@ -108,7 +108,7 @@ setEnv('GPTDIFF_LLM_API_KEY', 'sk-nano-…'); // browser, no process.env import { registerClient, beginSignIn, completeSignIn } from 'patchling/oauth'; // On page load — finishes the redirect and stores the access token as -// the GPTDIFF_LLM_API_KEY override automatically: +// the PATCHLING_LLM_API_KEY override automatically: await completeSignIn(); // To start sign-in (clientId from a one-time dynamic registration): @@ -138,7 +138,7 @@ Opt-in pass for a large file map. Each candidate file is sent with the task to a import { filterRelevant, buildEnvironment, generateDiff, smartapply } from 'patchling'; const result = await filterRelevant(files, task, { - // model: 'xiaomi/mimo-v2.6-flash', // GPTDIFF_FILTER_MODEL, else this default + // model: 'xiaomi/mimo-v2.6-flash', // PATCHLING_FILTER_MODEL, else this default concurrency: 8, // max in-flight calls // cache: null, // omit for a fresh in-memory cache; a path string persists it // maxBytes: 200000, // 0 or null disables @@ -151,7 +151,7 @@ const diff = await generateDiff(buildEnvironment(result.files), task, { model }) const next = await smartapply(diff, files); ``` -- `opts.model`, `opts.apiKey`, `opts.baseUrl` — same key and base URL resolution as `generateDiff` (`GPTDIFF_LLM_API_KEY`, `GPTDIFF_LLM_BASE_URL`). The model falls back to `GPTDIFF_FILTER_MODEL`, then `xiaomi/mimo-v2.6-flash`. +- `opts.model`, `opts.apiKey`, `opts.baseUrl` — same key and base URL resolution as `generateDiff` (`PATCHLING_LLM_API_KEY`, `PATCHLING_LLM_BASE_URL`). The model falls back to `PATCHLING_FILTER_MODEL`, then `xiaomi/mimo-v2.6-flash`. - `opts.concurrency` — at most this many classifications in flight (default 8). - `opts.cache` — a `RelevanceCache`, a `{ get, set }` object, or a filesystem path (Node writes `{ version: 1, entries }` atomically; a corrupt file is ignored). Omit it, or pass `true`, for a fresh in-memory cache used only by this call. `null` and `false` turn caching off. `createMemoryCache()` builds another memory cache you can share. The key is the SHA-256 of the length-prefixed classification inputs. Each field is written as its UTF-8 byte length, a colon, the bytes, and a newline, in this order: prompt version (`3`), model, output-token limit, the reasoning effort actually sent (`""` when that parameter was omitted or rejected), task, file path, mode (`full`, `truncated`, or `binary`), the preview note (or `""`), and the body that was sent. A later lookup tries the configured effort first, then the empty effort. A full file and a preview truncated to the same bytes do not share a key. Each path is its own decision, including paths with identical contents. A cache read failure is a miss. A cache write failure is logged and the run continues. Fallback and error decisions are not stored. - `opts.maxBytes` — UTF-8 size cap (default 200000). `opts.maxTokens` — input-token cap (default 12000; `ceil(code points / 4)`, so a surrogate pair is one code point). `0` or `null` disables either limit. Token truncation keeps the first `maxTokens * 4` code points. Byte truncation stays on a UTF-8 code-point boundary. diff --git a/index.html b/index.html index a313d89..7fca1d9 100644 --- a/index.html +++ b/index.html @@ -72,7 +72,7 @@

patchling

const authStatus = $('authStatus'); function markSignedIn(source) { - const key = getEnv('GPTDIFF_LLM_API_KEY'); + const key = getEnv('PATCHLING_LLM_API_KEY'); authStatus.textContent = key ? `Signed in (${source}). Ready to call NanoGPT.` : 'Not signed in.'; } @@ -108,7 +108,7 @@

patchling

$('useKeyBtn').onclick = () => { const key = $('apiKey').value.trim(); if (!key) return; - setEnv('GPTDIFF_LLM_API_KEY', key); + setEnv('PATCHLING_LLM_API_KEY', key); markSignedIn('manual key'); }; diff --git a/landing/index.html b/landing/index.html index e54a34d..e0dc4af 100644 --- a/landing/index.html +++ b/landing/index.html @@ -606,7 +606,7 @@

The same filter in JavaScript and Python.

updated = smartapply(diff, files) -

Each decision is { path, decision, reason, raw, tokens, promptTokens, completionTokens, cached, skippedReason, error, failedOpen }. decision is yes or no. A leading standalone yes or no is required; other wording fails open and is not cached. skippedReason is binary, oversize, truncated, ignored, or null. The default model is xiaomi/mimo-v2.6-flash (GPTDIFF_FILTER_MODEL). The cache key hashes prompt version 3, the model, the output-token limit, the reasoning effort actually sent, the task, the file path, the mode (`full`, `truncated`, or `binary`), the preview note, and the body that was sent (`byteLength:utf8` for each field). Token estimates use `ceil(code points / 4)`. Python uses the same fields in snake_case (skipped_reason, prompt_tokens, failed_open, max_bytes, max_tokens, on_oversize, on_binary). Reported Flask recall 1.0 and 0.8× token figures are UNVERIFIED.

+

Each decision is { path, decision, reason, raw, tokens, promptTokens, completionTokens, cached, skippedReason, error, failedOpen }. decision is yes or no. A leading standalone yes or no is required; other wording fails open and is not cached. skippedReason is binary, oversize, truncated, ignored, or null. The default model is xiaomi/mimo-v2.6-flash (PATCHLING_FILTER_MODEL). The cache key hashes prompt version 3, the model, the output-token limit, the reasoning effort actually sent, the task, the file path, the mode (`full`, `truncated`, or `binary`), the preview note, and the body that was sent (`byteLength:utf8` for each field). Token estimates use `ceil(code points / 4)`. Python uses the same fields in snake_case (skipped_reason, prompt_tokens, failed_open, max_bytes, max_tokens, on_oversize, on_binary). Reported Flask recall 1.0 and 0.8× token figures are UNVERIFIED.

@@ -657,7 +657,7 @@

Default: NanoGPT. Required: nothing.

Why NanoGPT is the default: it's the only setup that works everywhere patchling runs. One pay-per-use key covers 600+ models, and OAuth (PKCE) works from a static page — the token is issued to your visitor's browser, so you can ship an AI-edit feature with no backend at all. That's how this page and every demo run. (NanoGPT links here carry our referral code.)

-

Already have a provider? baseUrl takes any OpenAI-compatible endpoint — OpenAI, OpenRouter, Groq, a vLLM box in your rack, Ollama on localhost. api.anthropic.com is spoken natively. In Node and Python, GPTDIFF_LLM_API_KEY and GPTDIFF_LLM_BASE_URL configure it without touching code.

+

Already have a provider? baseUrl takes any OpenAI-compatible endpoint — OpenAI, OpenRouter, Groq, a vLLM box in your rack, Ollama on localhost. api.anthropic.com is spoken natively. In Node and Python, PATCHLING_LLM_API_KEY and PATCHLING_LLM_BASE_URL configure it without touching code.

And the escape hatch is total. Pass callLlm (and callLlmForApply) and patchling makes no network calls of its own — your gateway, your retries, your logging, your mocks in CI. The demo above runs on exactly this: its "model" is a canned reply.

@@ -1788,7 +1788,7 @@

${esc(title)}

${cards}`; setMode("demo"); try { // Finish an OAuth redirect if one is in flight (also sets the library's - // GPTDIFF_LLM_API_KEY override). + // PATCHLING_LLM_API_KEY override). const token = await completeSignIn(); if (token) { setKey(token); $("realdetails").open = true; } // toggle handler flips to real mode } catch (e) { diff --git a/landing/lib/env.js b/landing/lib/env.js index b556f77..9111aa5 100644 --- a/landing/lib/env.js +++ b/landing/lib/env.js @@ -4,10 +4,34 @@ * In Node, reads from `process.env`. In the browser there is no `process`, so * callers can register overrides (e.g. values obtained via OAuth sign-in) * through `setEnv`, which are consulted first. + * + * Configuration variables carry the `PATCHLING_` prefix (for example + * `PATCHLING_MODEL`). The historical `GPTDIFF_` spellings from the project's + * gptdiff days remain as legacy aliases: when a `PATCHLING_*` variable is + * unset, its `GPTDIFF_*` spelling is consulted, and the `PATCHLING_` + * spelling always wins when both are set. */ const overrides = Object.create(null); +const PREFIX = 'PATCHLING_'; +const LEGACY_PREFIX = 'GPTDIFF_'; + +/** + * Return the spellings to try for `name`, most preferred first. + * @param {string} name + * @returns {string[]} + */ +function candidateNames(name) { + if (name.startsWith(PREFIX)) { + return [name, LEGACY_PREFIX + name.slice(PREFIX.length)]; + } + if (name.startsWith(LEGACY_PREFIX)) { + return [PREFIX + name.slice(LEGACY_PREFIX.length), name]; + } + return [name]; +} + /** * Set an environment-style override (used in the browser where there is no * `process.env`). Pass `undefined` to clear an override. @@ -24,14 +48,21 @@ export function setEnv(name, value) { /** * Read an environment variable. Overrides take precedence over `process.env`. + * `PATCHLING_*` variables also resolve through their legacy `GPTDIFF_*` + * alias (and vice versa), with the `PATCHLING_` spelling taking precedence. * @param {string} name * @param {string} [fallback] * @returns {string | undefined} */ export function getEnv(name, fallback = undefined) { - if (name in overrides) return overrides[name]; - if (typeof process !== 'undefined' && process.env && name in process.env) { - return process.env[name]; + const names = candidateNames(name); + for (const candidate of names) { + if (candidate in overrides) return overrides[candidate]; + } + if (typeof process !== 'undefined' && process.env) { + for (const candidate of names) { + if (candidate in process.env) return process.env[candidate]; + } } return fallback; } diff --git a/landing/lib/filter.js b/landing/lib/filter.js index db62af4..e1fe7ce 100644 --- a/landing/lib/filter.js +++ b/landing/lib/filter.js @@ -17,7 +17,7 @@ import { swallowReasoning } from './text.js'; import { callLlm as defaultCallLlm, resolveApiKey, resolveBaseUrl } from './llm.js'; import { getEnv } from './env.js'; -/** Cheap default for yes/no classification. Override with GPTDIFF_FILTER_MODEL. */ +/** Cheap default for yes/no classification. Override with PATCHLING_FILTER_MODEL. */ export const DEFAULT_FILTER_MODEL = 'xiaomi/mimo-v2.6-flash'; /** In-flight classifications per call when `concurrency` is omitted. */ @@ -595,7 +595,7 @@ function checkPolicy(name, value) { * @returns {string} */ function resolveFilterModel(model) { - return model || getEnv('GPTDIFF_FILTER_MODEL') || DEFAULT_FILTER_MODEL; + return model || getEnv('PATCHLING_FILTER_MODEL') || DEFAULT_FILTER_MODEL; } /** @@ -1269,7 +1269,7 @@ function rejectSnakeCaseOptions(opts) { * @param {Record} files * @param {string} task * @param {object} [opts] - * @param {string} [opts.model] `GPTDIFF_FILTER_MODEL`, else {@link DEFAULT_FILTER_MODEL} + * @param {string} [opts.model] `PATCHLING_FILTER_MODEL`, else {@link DEFAULT_FILTER_MODEL} * @param {number} [opts.concurrency] max in-flight calls (default {@link DEFAULT_FILTER_CONCURRENCY}) * @param {RelevanceCache | string | boolean | null | { get: Function, put?: Function, set?: Function }} [opts.cache] * @param {number | null} [opts.maxBytes] UTF-8 cap; `0` or `null` disables; default {@link DEFAULT_FILTER_MAX_BYTES} @@ -1284,8 +1284,8 @@ function rejectSnakeCaseOptions(opts) { * `true` or omitted uses {@link DEFAULT_IGNORE_PATTERNS}. `false` or `null` classifies every path. * An array replaces the default list. * @param {(decision: RelevanceDecision) => void} [opts.onDecision] called as each file finishes (completion order) - * @param {string} [opts.apiKey] `GPTDIFF_LLM_API_KEY` when omitted - * @param {string} [opts.baseUrl] `GPTDIFF_LLM_BASE_URL` when omitted + * @param {string} [opts.apiKey] `PATCHLING_LLM_API_KEY` when omitted + * @param {string} [opts.baseUrl] `PATCHLING_LLM_BASE_URL` when omitted * @param {Function} [opts.callLlm] injectable client (tests) * @returns {Promise} * @throws {TypeError} when an option uses the Python snake_case name (`on_binary`, `max_bytes`, ...) @@ -1485,7 +1485,7 @@ export async function filterRelevant(files, task, opts = {}) { } if (needsCall && !apiKey) { throw new Error( - 'GPTDIFF_LLM_API_KEY is required for the relevance filter. ' + 'PATCHLING_LLM_API_KEY is required for the relevance filter. ' + 'Set it in the environment or pass apiKey.', ); } diff --git a/landing/lib/llm.js b/landing/lib/llm.js index 418074d..25c0390 100644 --- a/landing/lib/llm.js +++ b/landing/lib/llm.js @@ -308,22 +308,22 @@ export async function callLlm({ /** * Resolve the effective API key, preferring an explicit override then the - * GPTDIFF_LLM_API_KEY environment variable. + * PATCHLING_LLM_API_KEY environment variable. * @param {string} [apiKey] * @returns {string | undefined} */ export function resolveApiKey(apiKey) { - return apiKey || getEnv('GPTDIFF_LLM_API_KEY'); + return apiKey || getEnv('PATCHLING_LLM_API_KEY'); } /** * Resolve the effective base URL, preferring an explicit override then the - * GPTDIFF_LLM_BASE_URL environment variable, then the NanoGPT default. + * PATCHLING_LLM_BASE_URL environment variable, then the NanoGPT default. * @param {string} [baseUrl] * @returns {string} */ export function resolveBaseUrl(baseUrl) { - return baseUrl || getEnv('GPTDIFF_LLM_BASE_URL', DEFAULT_BASE_URL) || DEFAULT_BASE_URL; + return baseUrl || getEnv('PATCHLING_LLM_BASE_URL', DEFAULT_BASE_URL) || DEFAULT_BASE_URL; } export { domainForUrl }; diff --git a/package.json b/package.json index eba16a0..77cc097 100644 --- a/package.json +++ b/package.json @@ -33,8 +33,8 @@ }, "scripts": { "prepublishOnly": "npm test", - "test": "node --test", - "test:live": "GPTDIFF_LIVE=1 node --test test/live.test.js", + "test": "node --import ./test/setup.js --test", + "test:live": "PATCHLING_LIVE=1 node --test test/live.test.js", "test:live:llm": "LIVE_LLM=1 node --test test/live-smartapply.test.js", "test:live:filter": "LIVE_LLM=1 node --test test/live-filter.test.js", "benchmark": "node benchmark/run.js", diff --git a/src/env.js b/src/env.js index b556f77..9111aa5 100644 --- a/src/env.js +++ b/src/env.js @@ -4,10 +4,34 @@ * In Node, reads from `process.env`. In the browser there is no `process`, so * callers can register overrides (e.g. values obtained via OAuth sign-in) * through `setEnv`, which are consulted first. + * + * Configuration variables carry the `PATCHLING_` prefix (for example + * `PATCHLING_MODEL`). The historical `GPTDIFF_` spellings from the project's + * gptdiff days remain as legacy aliases: when a `PATCHLING_*` variable is + * unset, its `GPTDIFF_*` spelling is consulted, and the `PATCHLING_` + * spelling always wins when both are set. */ const overrides = Object.create(null); +const PREFIX = 'PATCHLING_'; +const LEGACY_PREFIX = 'GPTDIFF_'; + +/** + * Return the spellings to try for `name`, most preferred first. + * @param {string} name + * @returns {string[]} + */ +function candidateNames(name) { + if (name.startsWith(PREFIX)) { + return [name, LEGACY_PREFIX + name.slice(PREFIX.length)]; + } + if (name.startsWith(LEGACY_PREFIX)) { + return [PREFIX + name.slice(LEGACY_PREFIX.length), name]; + } + return [name]; +} + /** * Set an environment-style override (used in the browser where there is no * `process.env`). Pass `undefined` to clear an override. @@ -24,14 +48,21 @@ export function setEnv(name, value) { /** * Read an environment variable. Overrides take precedence over `process.env`. + * `PATCHLING_*` variables also resolve through their legacy `GPTDIFF_*` + * alias (and vice versa), with the `PATCHLING_` spelling taking precedence. * @param {string} name * @param {string} [fallback] * @returns {string | undefined} */ export function getEnv(name, fallback = undefined) { - if (name in overrides) return overrides[name]; - if (typeof process !== 'undefined' && process.env && name in process.env) { - return process.env[name]; + const names = candidateNames(name); + for (const candidate of names) { + if (candidate in overrides) return overrides[candidate]; + } + if (typeof process !== 'undefined' && process.env) { + for (const candidate of names) { + if (candidate in process.env) return process.env[candidate]; + } } return fallback; } diff --git a/src/filter.d.ts b/src/filter.d.ts index c9f6cd4..9f939cd 100644 --- a/src/filter.d.ts +++ b/src/filter.d.ts @@ -83,7 +83,7 @@ export function isIgnoredPath(filePath: string, patterns?: string[]): boolean; * @param {Record} files * @param {string} task * @param {object} [opts] - * @param {string} [opts.model] `GPTDIFF_FILTER_MODEL`, else {@link DEFAULT_FILTER_MODEL} + * @param {string} [opts.model] `PATCHLING_FILTER_MODEL`, else {@link DEFAULT_FILTER_MODEL} * @param {number} [opts.concurrency] max in-flight calls (default {@link DEFAULT_FILTER_CONCURRENCY}) * @param {RelevanceCache | string | boolean | null | { get: Function, put?: Function, set?: Function }} [opts.cache] * @param {number | null} [opts.maxBytes] UTF-8 cap; `0` or `null` disables; default {@link DEFAULT_FILTER_MAX_BYTES} @@ -98,8 +98,8 @@ export function isIgnoredPath(filePath: string, patterns?: string[]): boolean; * `true` or omitted uses {@link DEFAULT_IGNORE_PATTERNS}. `false` or `null` classifies every path. * An array replaces the default list. * @param {(decision: RelevanceDecision) => void} [opts.onDecision] called as each file finishes (completion order) - * @param {string} [opts.apiKey] `GPTDIFF_LLM_API_KEY` when omitted - * @param {string} [opts.baseUrl] `GPTDIFF_LLM_BASE_URL` when omitted + * @param {string} [opts.apiKey] `PATCHLING_LLM_API_KEY` when omitted + * @param {string} [opts.baseUrl] `PATCHLING_LLM_BASE_URL` when omitted * @param {Function} [opts.callLlm] injectable client (tests) * @returns {Promise} * @throws {TypeError} when an option uses the Python snake_case name (`on_binary`, `max_bytes`, ...) @@ -141,7 +141,7 @@ export function formatFilterSummary(result: FilterRelevantResult, verbose?: bool * @returns {Promise} */ export function dumpDecisions(result: FilterRelevantResult, path: string): Promise; -/** Cheap default for yes/no classification. Override with GPTDIFF_FILTER_MODEL. */ +/** Cheap default for yes/no classification. Override with PATCHLING_FILTER_MODEL. */ export const DEFAULT_FILTER_MODEL: "xiaomi/mimo-v2.6-flash"; /** In-flight classifications per call when `concurrency` is omitted. */ export const DEFAULT_FILTER_CONCURRENCY: 8; diff --git a/src/filter.js b/src/filter.js index db62af4..e1fe7ce 100644 --- a/src/filter.js +++ b/src/filter.js @@ -17,7 +17,7 @@ import { swallowReasoning } from './text.js'; import { callLlm as defaultCallLlm, resolveApiKey, resolveBaseUrl } from './llm.js'; import { getEnv } from './env.js'; -/** Cheap default for yes/no classification. Override with GPTDIFF_FILTER_MODEL. */ +/** Cheap default for yes/no classification. Override with PATCHLING_FILTER_MODEL. */ export const DEFAULT_FILTER_MODEL = 'xiaomi/mimo-v2.6-flash'; /** In-flight classifications per call when `concurrency` is omitted. */ @@ -595,7 +595,7 @@ function checkPolicy(name, value) { * @returns {string} */ function resolveFilterModel(model) { - return model || getEnv('GPTDIFF_FILTER_MODEL') || DEFAULT_FILTER_MODEL; + return model || getEnv('PATCHLING_FILTER_MODEL') || DEFAULT_FILTER_MODEL; } /** @@ -1269,7 +1269,7 @@ function rejectSnakeCaseOptions(opts) { * @param {Record} files * @param {string} task * @param {object} [opts] - * @param {string} [opts.model] `GPTDIFF_FILTER_MODEL`, else {@link DEFAULT_FILTER_MODEL} + * @param {string} [opts.model] `PATCHLING_FILTER_MODEL`, else {@link DEFAULT_FILTER_MODEL} * @param {number} [opts.concurrency] max in-flight calls (default {@link DEFAULT_FILTER_CONCURRENCY}) * @param {RelevanceCache | string | boolean | null | { get: Function, put?: Function, set?: Function }} [opts.cache] * @param {number | null} [opts.maxBytes] UTF-8 cap; `0` or `null` disables; default {@link DEFAULT_FILTER_MAX_BYTES} @@ -1284,8 +1284,8 @@ function rejectSnakeCaseOptions(opts) { * `true` or omitted uses {@link DEFAULT_IGNORE_PATTERNS}. `false` or `null` classifies every path. * An array replaces the default list. * @param {(decision: RelevanceDecision) => void} [opts.onDecision] called as each file finishes (completion order) - * @param {string} [opts.apiKey] `GPTDIFF_LLM_API_KEY` when omitted - * @param {string} [opts.baseUrl] `GPTDIFF_LLM_BASE_URL` when omitted + * @param {string} [opts.apiKey] `PATCHLING_LLM_API_KEY` when omitted + * @param {string} [opts.baseUrl] `PATCHLING_LLM_BASE_URL` when omitted * @param {Function} [opts.callLlm] injectable client (tests) * @returns {Promise} * @throws {TypeError} when an option uses the Python snake_case name (`on_binary`, `max_bytes`, ...) @@ -1485,7 +1485,7 @@ export async function filterRelevant(files, task, opts = {}) { } if (needsCall && !apiKey) { throw new Error( - 'GPTDIFF_LLM_API_KEY is required for the relevance filter. ' + 'PATCHLING_LLM_API_KEY is required for the relevance filter. ' + 'Set it in the environment or pass apiKey.', ); } diff --git a/src/gptdiff.js b/src/gptdiff.js index 0fda65a..b2fb44e 100644 --- a/src/gptdiff.js +++ b/src/gptdiff.js @@ -109,7 +109,7 @@ export function buildEnvironment(filesDict, opts) { } function resolveModel(model) { - return model || getEnv('GPTDIFF_MODEL', DEFAULT_MODEL) || DEFAULT_MODEL; + return model || getEnv('PATCHLING_MODEL', DEFAULT_MODEL) || DEFAULT_MODEL; } function usageFrom(response) { diff --git a/src/llm.d.ts b/src/llm.d.ts index c45d0a2..7fd1804 100644 --- a/src/llm.d.ts +++ b/src/llm.d.ts @@ -44,14 +44,14 @@ export function callLlm({ apiKey, baseUrl, model, messages, maxTokens, temperatu }>; /** * Resolve the effective API key, preferring an explicit override then the - * GPTDIFF_LLM_API_KEY environment variable. + * PATCHLING_LLM_API_KEY environment variable. * @param {string} [apiKey] * @returns {string | undefined} */ export function resolveApiKey(apiKey?: string): string | undefined; /** * Resolve the effective base URL, preferring an explicit override then the - * GPTDIFF_LLM_BASE_URL environment variable, then the NanoGPT default. + * PATCHLING_LLM_BASE_URL environment variable, then the NanoGPT default. * @param {string} [baseUrl] * @returns {string} */ diff --git a/src/llm.js b/src/llm.js index 418074d..25c0390 100644 --- a/src/llm.js +++ b/src/llm.js @@ -308,22 +308,22 @@ export async function callLlm({ /** * Resolve the effective API key, preferring an explicit override then the - * GPTDIFF_LLM_API_KEY environment variable. + * PATCHLING_LLM_API_KEY environment variable. * @param {string} [apiKey] * @returns {string | undefined} */ export function resolveApiKey(apiKey) { - return apiKey || getEnv('GPTDIFF_LLM_API_KEY'); + return apiKey || getEnv('PATCHLING_LLM_API_KEY'); } /** * Resolve the effective base URL, preferring an explicit override then the - * GPTDIFF_LLM_BASE_URL environment variable, then the NanoGPT default. + * PATCHLING_LLM_BASE_URL environment variable, then the NanoGPT default. * @param {string} [baseUrl] * @returns {string} */ export function resolveBaseUrl(baseUrl) { - return baseUrl || getEnv('GPTDIFF_LLM_BASE_URL', DEFAULT_BASE_URL) || DEFAULT_BASE_URL; + return baseUrl || getEnv('PATCHLING_LLM_BASE_URL', DEFAULT_BASE_URL) || DEFAULT_BASE_URL; } export { domainForUrl }; diff --git a/src/oauth.d.ts b/src/oauth.d.ts index 9457778..cf513a5 100644 --- a/src/oauth.d.ts +++ b/src/oauth.d.ts @@ -93,7 +93,7 @@ export function beginSignIn({ clientId, redirectUri, scope, redirect, }?: { /** * Complete the sign-in after NanoGPT redirects back with `?code=...&state=...`. * Validates state, exchanges the code, registers the access token as the - * GPTDIFF_LLM_API_KEY override, and clears the URL query string. + * PATCHLING_LLM_API_KEY override, and clears the URL query string. * * @param {object} [opts] * @param {string} [opts.search] query string to parse (defaults to window.location.search) diff --git a/src/oauth.js b/src/oauth.js index 50f4f87..435db9e 100644 --- a/src/oauth.js +++ b/src/oauth.js @@ -10,7 +10,7 @@ * * The low-level functions are environment-agnostic. The high-level * `beginSignIn` / `completeSignIn` helpers drive the browser redirect flow and - * stash the returned access token as the GPTDIFF_LLM_API_KEY override so the + * stash the returned access token as the PATCHLING_LLM_API_KEY override so the * rest of gptdiff-js can use it transparently. */ @@ -223,7 +223,7 @@ export async function beginSignIn({ /** * Complete the sign-in after NanoGPT redirects back with `?code=...&state=...`. * Validates state, exchanges the code, registers the access token as the - * GPTDIFF_LLM_API_KEY override, and clears the URL query string. + * PATCHLING_LLM_API_KEY override, and clears the URL query string. * * @param {object} [opts] * @param {string} [opts.search] query string to parse (defaults to window.location.search) @@ -254,7 +254,7 @@ export async function completeSignIn({ search, fetchImpl } = {}) { }); window.sessionStorage.removeItem(STORAGE_KEY); - setEnv('GPTDIFF_LLM_API_KEY', tokenResponse.access_token); + setEnv('PATCHLING_LLM_API_KEY', tokenResponse.access_token); // Clean the code/state out of the URL. const cleanUrl = window.location.origin + window.location.pathname; diff --git a/test/env-prefix.test.js b/test/env-prefix.test.js new file mode 100644 index 0000000..7201ee9 --- /dev/null +++ b/test/env-prefix.test.js @@ -0,0 +1,60 @@ +// PATCHLING_ is the canonical env prefix; GPTDIFF_ remains a legacy alias. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { getEnv, setEnv } from '../src/env.js'; + +const VARS = ['PATCHLING_MODEL', 'GPTDIFF_MODEL', 'PATCHLING_LLM_API_KEY', 'GPTDIFF_LLM_API_KEY']; + +function clean() { + for (const v of VARS) { + delete process.env[v]; + setEnv(v, undefined); + } +} + +test('patchling name read from process.env', () => { + clean(); + process.env.PATCHLING_MODEL = 'new-model'; + assert.equal(getEnv('PATCHLING_MODEL'), 'new-model'); + clean(); +}); + +test('legacy gptdiff spelling still resolves', () => { + clean(); + process.env.GPTDIFF_MODEL = 'legacy-model'; + assert.equal(getEnv('PATCHLING_MODEL'), 'legacy-model'); + clean(); +}); + +test('patchling spelling wins over legacy', () => { + clean(); + process.env.PATCHLING_MODEL = 'new-model'; + process.env.GPTDIFF_MODEL = 'legacy-model'; + assert.equal(getEnv('PATCHLING_MODEL'), 'new-model'); + clean(); +}); + +test('legacy lookup also prefers patchling', () => { + clean(); + process.env.PATCHLING_LLM_API_KEY = 'new-key'; + process.env.GPTDIFF_LLM_API_KEY = 'legacy-key'; + assert.equal(getEnv('GPTDIFF_LLM_API_KEY'), 'new-key'); + clean(); +}); + +test('setEnv override registered under the legacy name', () => { + clean(); + setEnv('GPTDIFF_MODEL', 'override-model'); + assert.equal(getEnv('PATCHLING_MODEL'), 'override-model'); + clean(); +}); + +test('unprefixed names untouched', () => { + clean(); + process.env.ANTHROPIC_BUDGET_TOKENS = '1024'; + assert.equal(getEnv('ANTHROPIC_BUDGET_TOKENS'), '1024'); + assert.equal(getEnv('PATCHLING_NOT_A_REAL_VAR', 'fallback'), 'fallback'); + delete process.env.ANTHROPIC_BUDGET_TOKENS; + clean(); +}); diff --git a/test/filter_relevant.test.js b/test/filter_relevant.test.js index 581e5ac..9b065e8 100644 --- a/test/filter_relevant.test.js +++ b/test/filter_relevant.test.js @@ -550,9 +550,9 @@ test('zero disables both size limits', async () => { }); test('missing api key throws only when a call is required', async () => withEnv(async () => { - const prev = process.env.GPTDIFF_LLM_API_KEY; - delete process.env.GPTDIFF_LLM_API_KEY; - setEnv('GPTDIFF_LLM_API_KEY', undefined); + const prev = process.env.PATCHLING_LLM_API_KEY; + delete process.env.PATCHLING_LLM_API_KEY; + setEnv('PATCHLING_LLM_API_KEY', undefined); try { const skipped = await filterRelevant({ 'bin.dat': '\0' }, 'task', { model: 'm', @@ -568,19 +568,19 @@ test('missing api key throws only when a call is required', async () => withEnv( cache: false, callLlm: () => { throw new Error('should not be called'); }, }), - /GPTDIFF_LLM_API_KEY/, + /PATCHLING_LLM_API_KEY/, ); } finally { - setEnv('GPTDIFF_LLM_API_KEY', undefined); - if (prev === undefined) delete process.env.GPTDIFF_LLM_API_KEY; - else process.env.GPTDIFF_LLM_API_KEY = prev; + setEnv('PATCHLING_LLM_API_KEY', undefined); + if (prev === undefined) delete process.env.PATCHLING_LLM_API_KEY; + else process.env.PATCHLING_LLM_API_KEY = prev; } })); test('cached files do not need an api key', async () => withEnv(async () => { - const prev = process.env.GPTDIFF_LLM_API_KEY; - delete process.env.GPTDIFF_LLM_API_KEY; - setEnv('GPTDIFF_LLM_API_KEY', undefined); + const prev = process.env.PATCHLING_LLM_API_KEY; + delete process.env.PATCHLING_LLM_API_KEY; + setEnv('PATCHLING_LLM_API_KEY', undefined); let n = 0; const mock = llm(() => { n += 1; @@ -596,9 +596,9 @@ test('cached files do not need an api key', async () => withEnv(async () => { assert.equal(result.decisions[0].cached, true); assert.equal(result.decisions[0].decision, 'no'); } finally { - setEnv('GPTDIFF_LLM_API_KEY', undefined); - if (prev === undefined) delete process.env.GPTDIFF_LLM_API_KEY; - else process.env.GPTDIFF_LLM_API_KEY = prev; + setEnv('PATCHLING_LLM_API_KEY', undefined); + if (prev === undefined) delete process.env.PATCHLING_LLM_API_KEY; + else process.env.PATCHLING_LLM_API_KEY = prev; } })); @@ -633,12 +633,12 @@ test('invalid arguments throw', async () => { ); }); -test('model defaults to GPTDIFF_FILTER_MODEL, else xiaomi/mimo-v2.6-flash', async () => withEnv(async () => { - const prevFilter = process.env.GPTDIFF_FILTER_MODEL; - const prevBase = process.env.GPTDIFF_LLM_BASE_URL; - delete process.env.GPTDIFF_FILTER_MODEL; - setEnv('GPTDIFF_FILTER_MODEL', undefined); - setEnv('GPTDIFF_LLM_BASE_URL', 'https://example.test/v1/'); +test('model defaults to PATCHLING_FILTER_MODEL, else xiaomi/mimo-v2.6-flash', async () => withEnv(async () => { + const prevFilter = process.env.PATCHLING_FILTER_MODEL; + const prevBase = process.env.PATCHLING_LLM_BASE_URL; + delete process.env.PATCHLING_FILTER_MODEL; + setEnv('PATCHLING_FILTER_MODEL', undefined); + setEnv('PATCHLING_LLM_BASE_URL', 'https://example.test/v1/'); const seen = []; const mock = llm((req) => { seen.push(req); @@ -650,7 +650,7 @@ test('model defaults to GPTDIFF_FILTER_MODEL, else xiaomi/mimo-v2.6-flash', asyn apiKey: 'from-arg', callLlm: mock.fn, }); - setEnv('GPTDIFF_FILTER_MODEL', 'env-filter-model'); + setEnv('PATCHLING_FILTER_MODEL', 'env-filter-model'); const named = await filterRelevant({ 'a.py': 'x = 1\n' }, 'task', { cache: false, apiKey: 'from-arg', @@ -674,12 +674,12 @@ test('model defaults to GPTDIFF_FILTER_MODEL, else xiaomi/mimo-v2.6-flash', asyn }); assert.ok(gemini.calls[0].messages[1].content.startsWith('You are a relevance filter')); } finally { - setEnv('GPTDIFF_FILTER_MODEL', undefined); - setEnv('GPTDIFF_LLM_BASE_URL', undefined); - if (prevFilter === undefined) delete process.env.GPTDIFF_FILTER_MODEL; - else process.env.GPTDIFF_FILTER_MODEL = prevFilter; - if (prevBase === undefined) delete process.env.GPTDIFF_LLM_BASE_URL; - else process.env.GPTDIFF_LLM_BASE_URL = prevBase; + setEnv('PATCHLING_FILTER_MODEL', undefined); + setEnv('PATCHLING_LLM_BASE_URL', undefined); + if (prevFilter === undefined) delete process.env.PATCHLING_FILTER_MODEL; + else process.env.PATCHLING_FILTER_MODEL = prevFilter; + if (prevBase === undefined) delete process.env.PATCHLING_LLM_BASE_URL; + else process.env.PATCHLING_LLM_BASE_URL = prevBase; } assert.equal(DEFAULT_FILTER_MODEL, 'xiaomi/mimo-v2.6-flash'); assert.equal(DEFAULT_FILTER_MAX_BYTES, 200_000); diff --git a/test/live-filter.test.js b/test/live-filter.test.js index c1c9c19..4e960bd 100644 --- a/test/live-filter.test.js +++ b/test/live-filter.test.js @@ -3,26 +3,26 @@ * * Skipped unless both of these are set: * LIVE_LLM=1 - * GPTDIFF_LLM_API_KEY= + * PATCHLING_LLM_API_KEY= * * `npm test` / CI does not set LIVE_LLM, so this file makes no network calls * there. Run it with: npm run test:live:filter * - * Model defaults to the cheap filter model (override with GPTDIFF_FILTER_MODEL). - * Base URL is the package default (override GPTDIFF_LLM_BASE_URL). + * Model defaults to the cheap filter model (override with PATCHLING_FILTER_MODEL). + * Base URL is the package default (override PATCHLING_LLM_BASE_URL). */ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { filterRelevant, buildEnvironment, DEFAULT_FILTER_MODEL } from '../src/index.js'; -const apiKey = process.env.GPTDIFF_LLM_API_KEY; +const apiKey = process.env.PATCHLING_LLM_API_KEY; const LIVE = process.env.LIVE_LLM === '1' && !!apiKey; -const MODEL = process.env.GPTDIFF_FILTER_MODEL || DEFAULT_FILTER_MODEL; +const MODEL = process.env.PATCHLING_FILTER_MODEL || DEFAULT_FILTER_MODEL; test( 'live: filterRelevant keeps the greeting file and drops the unrelated one', { - skip: LIVE ? false : 'set LIVE_LLM=1 and GPTDIFF_LLM_API_KEY to run', + skip: LIVE ? false : 'set LIVE_LLM=1 and PATCHLING_LLM_API_KEY to run', timeout: 120_000, }, async () => { diff --git a/test/live-smartapply.test.js b/test/live-smartapply.test.js index d2ce99f..b86a9fe 100644 --- a/test/live-smartapply.test.js +++ b/test/live-smartapply.test.js @@ -3,13 +3,13 @@ * * Skipped unless both of these are set: * LIVE_LLM=1 - * GPTDIFF_LLM_API_KEY= + * PATCHLING_LLM_API_KEY= * * `npm test` / CI does not set LIVE_LLM, so this file makes no network calls * there. Run the suite with: npm run test:live:llm * - * Model defaults to the package default (override with GPTDIFF_MODEL). - * Base URL defaults to https://nano-gpt.com/api/v1/ (override GPTDIFF_LLM_BASE_URL). + * Model defaults to the package default (override with PATCHLING_MODEL). + * Base URL defaults to https://nano-gpt.com/api/v1/ (override PATCHLING_LLM_BASE_URL). */ import { test } from 'node:test'; import assert from 'node:assert/strict'; @@ -22,14 +22,14 @@ const cases = JSON.parse( readFileSync(new URL('./fixtures/smartapply-live-cases.json', import.meta.url), 'utf8'), ); -const apiKey = process.env.GPTDIFF_LLM_API_KEY; +const apiKey = process.env.PATCHLING_LLM_API_KEY; const LIVE = process.env.LIVE_LLM === '1' && !!apiKey; -const MODEL = process.env.GPTDIFF_MODEL || DEFAULT_MODEL; +const MODEL = process.env.PATCHLING_MODEL || DEFAULT_MODEL; test( 'live: smartapply NanoGPT cases', { - skip: LIVE ? false : 'set LIVE_LLM=1 and GPTDIFF_LLM_API_KEY to run', + skip: LIVE ? false : 'set LIVE_LLM=1 and PATCHLING_LLM_API_KEY to run', timeout: 300_000, }, async () => { diff --git a/test/live.test.js b/test/live.test.js index 75e48f5..15973eb 100644 --- a/test/live.test.js +++ b/test/live.test.js @@ -2,11 +2,11 @@ * Live integration tests against NanoGPT. * * These are SKIPPED unless both of these are set: - * GPTDIFF_LIVE=1 - * GPTDIFF_LLM_API_KEY= (e.g. sk-nano-... from OAuth sign-in) + * PATCHLING_LIVE=1 + * PATCHLING_LLM_API_KEY= (e.g. sk-nano-... from OAuth sign-in) * - * Model defaults to deepseek/deepseek-v4.1-flash-1017 (override with GPTDIFF_MODEL). - * Base URL defaults to https://nano-gpt.com/api/v1/ (override GPTDIFF_LLM_BASE_URL). + * Model defaults to deepseek/deepseek-v4.1-flash-1017 (override with PATCHLING_MODEL). + * Base URL defaults to https://nano-gpt.com/api/v1/ (override PATCHLING_LLM_BASE_URL). * * Run with: npm run test:live */ @@ -15,12 +15,12 @@ import assert from 'node:assert/strict'; import { generateDiff, smartapply, applyDiff, buildEnvironment } from '../src/index.js'; import { DEFAULT_MODEL } from '../src/env.js'; -const LIVE = process.env.GPTDIFF_LIVE === '1' && !!process.env.GPTDIFF_LLM_API_KEY; -const MODEL = process.env.GPTDIFF_MODEL || DEFAULT_MODEL; +const LIVE = process.env.PATCHLING_LIVE === '1' && !!process.env.PATCHLING_LLM_API_KEY; +const MODEL = process.env.PATCHLING_MODEL || DEFAULT_MODEL; test( 'live: generateDiff produces an applicable diff for a one-line change', - { skip: LIVE ? false : 'set GPTDIFF_LIVE=1 and GPTDIFF_LLM_API_KEY to run' }, + { skip: LIVE ? false : 'set PATCHLING_LIVE=1 and PATCHLING_LLM_API_KEY to run' }, async () => { const files = { 'greet.py': 'def greet():\n print("hello")\n' }; const environment = buildEnvironment(files); @@ -36,7 +36,7 @@ test( test( 'live: smartapply applies an LLM-resolved diff', - { skip: LIVE ? false : 'set GPTDIFF_LIVE=1 and GPTDIFF_LLM_API_KEY to run' }, + { skip: LIVE ? false : 'set PATCHLING_LIVE=1 and PATCHLING_LLM_API_KEY to run' }, async () => { const files = { 'greet.py': 'def greet():\n print("hello")\n' }; const diff = `diff --git a/greet.py b/greet.py diff --git a/test/setup.js b/test/setup.js new file mode 100644 index 0000000..ed94a69 --- /dev/null +++ b/test/setup.js @@ -0,0 +1,16 @@ +// Test setup: keep tests hermetic against ambient patchling configuration. +// +// Patchling is configured entirely through `PATCHLING_*` environment +// variables (with `GPTDIFF_*` legacy aliases), so a value present on the +// host — for example a CI secret exported under the legacy name — must not +// leak into tests that assume a variable is unset. Tests that need a +// variable set it explicitly. This mirrors the autouse scrub fixture in +// patchling-py's tests/conftest.py. +// +// Loaded via `node --import` (see the `test` script in package.json) so it +// runs in every test-runner child process before the test file itself. +for (const name of Object.keys(process.env)) { + if (name.startsWith('PATCHLING_') || name.startsWith('GPTDIFF_')) { + delete process.env[name]; + } +}