Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ <h1>patchling</h1>
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.';
}

Expand Down Expand Up @@ -108,7 +108,7 @@ <h1>patchling</h1>
$('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');
};

Expand Down
6 changes: 3 additions & 3 deletions landing/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,7 @@ <h2>The same filter in JavaScript and Python.</h2>
updated = smartapply(diff, files)</pre>
</div>
</div>
<p class="lead" style="margin-top:1rem">Each decision is <code class="inline">{ path, decision, reason, raw, tokens, promptTokens, completionTokens, cached, skippedReason, error, failedOpen }</code>. <code class="inline">decision</code> is <code class="inline">yes</code> or <code class="inline">no</code>. A leading standalone yes or no is required; other wording fails open and is not cached. <code class="inline">skippedReason</code> is <code class="inline">binary</code>, <code class="inline">oversize</code>, <code class="inline">truncated</code>, <code class="inline">ignored</code>, or null. The default model is <code class="inline">xiaomi/mimo-v2.6-flash</code> (<code class="inline">GPTDIFF_FILTER_MODEL</code>). 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 (<code class="inline">skipped_reason</code>, <code class="inline">prompt_tokens</code>, <code class="inline">failed_open</code>, <code class="inline">max_bytes</code>, <code class="inline">max_tokens</code>, <code class="inline">on_oversize</code>, <code class="inline">on_binary</code>). Reported Flask recall 1.0 and 0.8× token figures are UNVERIFIED.</p>
<p class="lead" style="margin-top:1rem">Each decision is <code class="inline">{ path, decision, reason, raw, tokens, promptTokens, completionTokens, cached, skippedReason, error, failedOpen }</code>. <code class="inline">decision</code> is <code class="inline">yes</code> or <code class="inline">no</code>. A leading standalone yes or no is required; other wording fails open and is not cached. <code class="inline">skippedReason</code> is <code class="inline">binary</code>, <code class="inline">oversize</code>, <code class="inline">truncated</code>, <code class="inline">ignored</code>, or null. The default model is <code class="inline">xiaomi/mimo-v2.6-flash</code> (<code class="inline">PATCHLING_FILTER_MODEL</code>). 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 (<code class="inline">skipped_reason</code>, <code class="inline">prompt_tokens</code>, <code class="inline">failed_open</code>, <code class="inline">max_bytes</code>, <code class="inline">max_tokens</code>, <code class="inline">on_oversize</code>, <code class="inline">on_binary</code>). Reported Flask recall 1.0 and 0.8× token figures are UNVERIFIED.</p>
</section>

<section id="why">
Expand Down Expand Up @@ -657,7 +657,7 @@ <h2>Default: NanoGPT. Required: nothing.</h2>
<div class="whygrid">
<div>
<p><b>Why NanoGPT is the default:</b> 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 <b>no backend at all</b>. That's how this page and every demo run. (NanoGPT links here carry our referral code.)</p>
<p><b>Already have a provider?</b> <code class="inline">baseUrl</code> takes any OpenAI-compatible endpoint — OpenAI, OpenRouter, Groq, a vLLM box in your rack, Ollama on localhost. <code class="inline">api.anthropic.com</code> is spoken natively. In Node and Python, <code class="inline">GPTDIFF_LLM_API_KEY</code> and <code class="inline">GPTDIFF_LLM_BASE_URL</code> configure it without touching code.</p>
<p><b>Already have a provider?</b> <code class="inline">baseUrl</code> takes any OpenAI-compatible endpoint — OpenAI, OpenRouter, Groq, a vLLM box in your rack, Ollama on localhost. <code class="inline">api.anthropic.com</code> is spoken natively. In Node and Python, <code class="inline">PATCHLING_LLM_API_KEY</code> and <code class="inline">PATCHLING_LLM_BASE_URL</code> configure it without touching code.</p>
<p><b>And the escape hatch is total.</b> Pass <code class="inline">callLlm</code> (and <code class="inline">callLlmForApply</code>) 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.</p>
</div>
<div class="window">
Expand Down Expand Up @@ -1788,7 +1788,7 @@ <h1>${esc(title)}</h1>${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) {
Expand Down
37 changes: 34 additions & 3 deletions landing/lib/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
}
Expand Down
12 changes: 6 additions & 6 deletions landing/lib/filter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -1269,7 +1269,7 @@ function rejectSnakeCaseOptions(opts) {
* @param {Record<string, string | Uint8Array>} 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}
Expand All @@ -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<FilterRelevantResult>}
* @throws {TypeError} when an option uses the Python snake_case name (`on_binary`, `max_bytes`, ...)
Expand Down Expand Up @@ -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.',
);
}
Expand Down
8 changes: 4 additions & 4 deletions landing/lib/llm.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
37 changes: 34 additions & 3 deletions src/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
}
Expand Down
Loading
Loading