Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(models): honor custom limits and API styles
vastsaa93b788e2a15
diff --git a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx b/apps/desktop/src/components/settings/ModelSelectionPanes.tsxindex 31a92cf8a..668a838b2 100644--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx@@ -70,6 +70,24 @@ export type ModelSelection = {setModels: (update: (current: ModelBinding[]) => ModelBinding[]) => void;};+type ModelTokenLimit = "contextWindow" | "maxTokens";++function publishedModelLimit(+ info: ModelInfo | undefined,+ field: ModelTokenLimit,+): number | undefined {+ if (!info) return undefined;+ const published = field === "contextWindow" ? info.limit?.context : info.limit?.output;+ if (published !== undefined) return published;+ // models.dev rows keep the raw record in `limit`; other discovered rows may+ // carry only the runtime's generic safety budget, which is not a published+ // model limit and should not look like one in Settings.+ if (info.catalogSource === "models.dev" || info.source === "discovered") {+ return undefined;+ }+ return field === "contextWindow" ? info.contextWindow : info.maxTokens;+}+/*** Row merging and published-level metadata for one binding list.*@@ -470,7 +488,8 @@ export function ModelSelectionPanes({) : null}</span><span className="provider-models-row-limits">- {formatTokenCount(row.contextWindow)} · {formatTokenCount(row.maxTokens)}+ {formatTokenCount(publishedModelLimit(row.info, "contextWindow"))} ·{" "}+ {formatTokenCount(publishedModelLimit(row.info, "maxTokens"))}</span></label></li>@@ -593,12 +612,21 @@ export function ModelSelectionPanes({const publishedImages = info ? modelMatchesFilter(info, "vision") : false;// The row's published window, so the hint below the field can say// the number still follows it.- const publishedContextWindow = info- ? (info.contextWindow ?? info.limit?.context)- : undefined;+ const publishedContextWindow = publishedModelLimit(info, "contextWindow");+ const publishedMaxTokens = publishedModelLimit(info, "maxTokens");const followsCatalog =binding.contextWindowSource !== "user" &&publishedContextWindow !== undefined;+ const displayedContextWindow =+ binding.contextWindowSource === "catalog" &&+ publishedContextWindow === undefined+ ? undefined+ : binding.contextWindow;+ const displayedMaxTokens =+ binding.maxTokensSource === "catalog" &&+ publishedMaxTokens === undefined+ ? undefined+ : binding.maxTokens;const publishedDocuments = info ? modelMatchesFilter(info, "pdf") : false;const expanded = expandedModelId === binding.id;const imageModelSelected = imageModelIds?.some((modelId) =>@@ -634,8 +662,8 @@ export function ModelSelectionPanes({<span className="provider-chosen-row-alias">{binding.alias.trim()}</span>) : null}<span className="provider-chosen-row-limits">- {formatTokenCount(binding.contextWindow)} ·{" "}- {formatTokenCount(binding.maxTokens)}+ {formatTokenCount(displayedContextWindow)} ·{" "}+ {formatTokenCount(displayedMaxTokens)}</span><buttontype="button"diff --git a/apps/desktop/src/styles/model-config.css b/apps/desktop/src/styles/model-config.cssindex 9b08cd41e..d0b7b70f1 100644--- a/apps/desktop/src/styles/model-config.css+++ b/apps/desktop/src/styles/model-config.css@@ -1760,10 +1760,10 @@/* ------------------------------------------------------------ responsive */-@media (max-width: 940px), (max-height: 800px) {- /* Two panes stop being readable before the dialog itself gets narrow,- and when vertical space is constrained (such as Windows high-DPI scaling)- the stacked layout prevents the panes from being crushed. */+@media (max-width: 940px) {+ /* Stack only when the viewport is too narrow for readable side-by-side+ panes. Short, wide windows keep both lists visible and let each list+ scroll inside its pane. */.provider-setup-field-row,.provider-setup-custom-identity-row,.provider-setup-custom-auth-row {diff --git a/apps/desktop/test/fixtures/dialog-overflow-runner.cjs b/apps/desktop/test/fixtures/dialog-overflow-runner.cjsindex 15f7f9612..aa8add14c 100644--- a/apps/desktop/test/fixtures/dialog-overflow-runner.cjs+++ b/apps/desktop/test/fixtures/dialog-overflow-runner.cjs@@ -80,13 +80,16 @@ app.whenReady().then(async () => {check('rename releases native preview after close', await evaluate('!window.dialogFixture.isBlockingOverlayActive()'));}}- win.setContentSize(1100, 620);+ win.setContentSize(1254, 772);await evaluate('window.dialogFixture.show("models", { theme: "dark", locale: "zh-CN" })');const modelRows = await evaluate(`(() => {+ const panes = document.querySelector('.provider-setup-panes');+ const paneBounds = [...panes.children].map(pane => pane.getBoundingClientRect());const list = document.querySelector('.provider-chosen-list');const bounds = list.getBoundingClientRect();const rows = [...list.querySelectorAll('.provider-chosen-row')];return {+ sideBySide: paneBounds.length === 2 && paneBounds[0].right <= paneBounds[1].left,ids: rows.map(row => row.querySelector('.provider-chosen-row-id')?.textContent),expanded: rows.filter(row => !row.querySelector('.provider-chosen-row-body')?.hidden).length,allVisible: rows.every(row => {@@ -95,6 +98,7 @@ app.whenReady().then(async () => {}),};})()`);+ check('a short but wide viewport keeps both model panes visible', modelRows.sideBySide, modelRows);check('chosen model names are visible before Advanced opens',modelRows.ids.length === 4 && modelRows.ids.every(Boolean) && modelRows.expanded === 0 && modelRows.allVisible,modelRows);@@ -102,6 +106,27 @@ app.whenReady().then(async () => {await click('.provider-chosen-advanced-toggle');check('Advanced still expands one selected model on demand',await evaluate(`document.querySelectorAll('.provider-chosen-row-body:not([hidden])').length === 1 && document.querySelector('.provider-chosen-advanced-toggle').getAttribute('aria-expanded') === 'true'`));+ win.setContentSize(520, 480);+ await evaluate('window.dialogFixture.show("models", { theme: "dark", locale: "zh-CN" })');+ const narrowModelPanes = await evaluate(`(() => {+ const panes = document.querySelector('.provider-setup-panes');+ const surface = document.querySelector('.dialog-fixture-models');+ const paneBounds = [...panes.children].map(pane => pane.getBoundingClientRect());+ const list = document.querySelector('.provider-chosen-list');+ const bounds = surface.getBoundingClientRect();+ return {+ stacked: paneBounds.length === 2 && paneBounds[0].bottom <= paneBounds[1].top,+ contained: bounds.left >= -1 && bounds.right <= innerWidth + 1 &&+ bounds.top >= -1 && bounds.bottom <= innerHeight + 1,+ listCanScroll: list.scrollHeight >= list.clientHeight,+ };+ })()`);+ check('a narrow high-DPI-sized viewport stacks panes and keeps its list reachable',+ narrowModelPanes.stacked && narrowModelPanes.contained && narrowModelPanes.listCanScroll,+ narrowModelPanes);+ await click('.provider-chosen-advanced-toggle');+ check('Advanced stays operable after the narrow viewport stacks the panes',+ await evaluate(`document.querySelectorAll('.provider-chosen-row-body:not([hidden])').length === 1`));writeFileSync(join(process.env.PI_DIALOG_ARTIFACT_DIR, 'results.json'), JSON.stringify(results, null, 2));const failed = results.filter(r => !r.ok).length;console.log('SUMMARY ' + (results.length-failed) + '/' + results.length + ' passed');diff --git a/apps/desktop/test/fixtures/dialog-overflow.jsx b/apps/desktop/test/fixtures/dialog-overflow.jsxindex e057503d8..4724617fd 100644--- a/apps/desktop/test/fixtures/dialog-overflow.jsx+++ b/apps/desktop/test/fixtures/dialog-overflow.jsx@@ -53,7 +53,16 @@ function ModelPickerFixture() {maxTokens: 4_000,}));return (- <div style={{ height: 520, padding: 24 }}>+ <div+ className="dialog-fixture-models"+ style={{+ display: "flex",+ flexDirection: "column",+ height: "min(520px, calc(100vh - 48px))",+ minHeight: 0,+ padding: 24,+ }}+ ><ModelSelectionPanesdiscovery={{ status: "success", source: "remote", models: [], error: "" }}selection={{diff --git a/apps/desktop/test/provider-form-layout.test.mjs b/apps/desktop/test/provider-form-layout.test.mjsindex d0fdb6a04..925c421f9 100644--- a/apps/desktop/test/provider-form-layout.test.mjs+++ b/apps/desktop/test/provider-form-layout.test.mjs@@ -276,11 +276,15 @@ test("empty panes hold their height instead of collapsing", () => {}});-test("the panes stack again before the dialog gets too narrow to read", () => {+test("the panes stack only when the viewport is too narrow to read them side by side", () => {const at = styles.indexOf("@media (max-width: 940px)");assert.notEqual(at, -1, "missing the two-pane fallback breakpoint");const query = styles.slice(at, styles.indexOf("@media", at + 10));- assert.match(query, /\(max-height:\s*800px\)/, "must also stack when vertical height is constrained (#1223)");+ assert.doesNotMatch(+ query.slice(0, query.indexOf("{")),+ /max-height/,+ "a short but wide viewport must keep both panes visible",+ );assert.match(query, /\.provider-setup-field-row[\s\S]*?\{\s*grid-template-columns: minmax\(0, 1fr\)/);// The explicit custom rows must also collapse or Name | URL and Key | Format// stay side-by-side on a stacked dialog.@@ -292,6 +296,7 @@ test("the panes stack again before the dialog gets too narrow to read", () => {query,/\.provider-setup-dialog,\s*\n\s*\.vendor-account-dialog\s*\{[\s\S]*?height: auto/,);+ assert.match(query, /max-height: min\(240px, 30vh\)/);});test("Advanced opens from the dialog header into a separate modal", () => {diff --git a/apps/desktop/test/provider-model-list-refresh.test.mjs b/apps/desktop/test/provider-model-list-refresh.test.mjsindex d10fe2ff6..9bf1cae74 100644--- a/apps/desktop/test/provider-model-list-refresh.test.mjs+++ b/apps/desktop/test/provider-model-list-refresh.test.mjs@@ -83,6 +83,14 @@ test("refresh removes revoked service rows and preserves configured chat binding}const render = () => renderToStaticMarkup(createElement(I18nextProvider, { i18n }, createElement(Picker)));const ids = (html, className) => [...html.matchAll(new RegExp(`<span class="${className}[^"]*">([^<]*)</span>`, "g"))].map((match) => match[1]);+ const limitsFor = (html, idClass, limitClass, modelId) => {+ const row = [...html.matchAll(/<li\b[\s\S]*?<\/li>/g)]+ .map((match) => match[0])+ .find((item) =>+ item.includes(`class="${idClass}`) && item.includes(`>${modelId}</span>`),+ );+ return row?.match(new RegExp(`class="${limitClass}">([^<]*)`))?.[1];+ };const refresh = async () => {const result = await handlers.get(IPC.invoke.providersListModels)({ providerId: row.id, source: "refresh" });discovery = { status: "ready", ...result };@@ -111,12 +119,30 @@ test("refresh removes revoked service rows and preserves configured chat binding[runtime.enrichProvider(row)],), 1_000_000, "context usage follows the selected account binding");served = ["gpt-6-sol", "new-model"];+ row.models.push(bindingForCustomModel("new-model"));const html = await refresh();assert.deepEqual(ids(html, "provider-models-row-id"), served);assert.deepEqual(persisted, row.models);- assert.deepEqual(ids(html, "provider-chosen-row-id"), ["gpt-6-sol", "claude-sonnet-4-5", "gpt-6-astra"]);- assert.deepEqual(composerModelsForProvider(row, discovery.models).map((model) => model.modelId), ["gpt-6-sol", "claude-sonnet-4-5", "gpt-6-astra"]);+ assert.deepEqual(ids(html, "provider-chosen-row-id"), [+ "gpt-6-sol", "claude-sonnet-4-5", "gpt-6-astra", "new-model",+ ]);+ assert.deepEqual(+ composerModelsForProvider(row, discovery.models).map((model) => model.modelId),+ ["gpt-6-sol", "claude-sonnet-4-5", "gpt-6-astra", "new-model"],+ );+ assert.equal(+ limitsFor(html, "provider-models-row-id", "provider-models-row-limits", "new-model"),+ "— · —",+ "an undiscovered model does not present generic runtime defaults as catalog limits",+ );+ assert.equal(+ limitsFor(html, "provider-chosen-row-id", "provider-chosen-row-limits", "new-model"),+ "— · —",+ "an unknown configured model is labeled unknown until its limits are published or overridden",+ );// Offline/manual fallbacks must still expose configured entries for editing.discovery = { ...discovery, source: "fallback", models: [] };- assert.deepEqual(ids(render(), "provider-models-row-id"), ["gpt-6-sol", "claude-sonnet-4-5", "gpt-6-astra"]);+ assert.deepEqual(ids(render(), "provider-models-row-id"), [+ "gpt-6-sol", "claude-sonnet-4-5", "gpt-6-astra", "new-model",+ ]);});diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex 13cbce13e..a9cf6c01d 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -667,13 +667,15 @@ including reasoning-model routes. A resolved model record may explicitly setrole; this override is model-scoped and does not change other providers.A catalog entry may additionally pin a model-level wire API (for example,-`api: "openai-responses"`). When present it wins over the provider-wide-`apiStyle` if compatible with the provider's protocol family (so responses-only-models under an `opencode_go` provider are sent through the Responses adapter-instead of Chat Completions). Foreign catalog wire APIs (such as-`google-generative-ai` or `anthropic-messages` matched on relay endpoints) do-not overwrite an OpenAI-compatible provider's configured wire style (issue #1310).-Without a model-level pin the provider-wide style applies unchanged.+`api: "openai-responses"`). A custom endpoint uses its saved provider-wide+`apiStyle` first because that field records the format the user selected for+that gateway; published model metadata cannot silently retarget it. Other+provider rows may use a model-level pin when its protocol family is compatible,+so responses-only models under an `opencode_go` provider use the Responses+adapter instead of Chat Completions. Foreign catalog wire APIs (such as+`google-generative-ai` or `anthropic-messages` matched on an OpenAI-compatible+relay) do not replace the provider's configured wire style (issue #1310).+Without a model-level pin the provider-wide style applies.This is the **universal escape hatch** guaranteeing market coverage beyond native integrations.diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.mdindex ca251726f..08c40f9bf 100644--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md@@ -69,8 +69,11 @@ entitled to it.mapping, the runtime sends that canonical value through to the adapter ratherthan letting the adapter clamp it to `high`. Existing non-null catalogmappings remain authoritative for providers that translate the level.-- The wire API is derived from the provider's published `npm` adapter- (`apiStyleForAdapter`) and is only editable inside **Advanced**.+- Named service defaults may derive their wire API from the provider's+ published `npm` adapter (`apiStyleForAdapter`). A custom endpoint's saved+ API style is the selected gateway format and takes precedence over a model's+ published adapter; named and OAuth providers may keep a model-level wire API+ pin when their catalog requires it.- A custom model ID is always accepted, so a gateway without a `/models` routestays usable.@@ -355,8 +358,11 @@ Bindings written before either marker preserve their stored window and outputcap, including 128,000 and 8,192, because old records cannot distinguish genericseeds from user choices. Only explicit `catalog` provenance follows latercorrections. Unknown models use conservative-128k / 8.2k limits and are never promoted from an ID pattern alone. Both markers-are optional, so old configs remain readable and downgrade clients ignore them.+128k / 8.2k runtime limits and are never promoted from an ID pattern alone.+Settings shows an em dash for an unpublished limit unless the user explicitly+configured that value; the Advanced inputs retain the conservative runtime+limits until the user edits them. Both markers are optional, so old configs+remain readable and downgrade clients ignore them.The configured user value remains persisted and visible in Advanced settings, butprovider safety does not trust an enlarged override beyond a known publisheddiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex e23753abb..e4c04e776 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -3905,6 +3905,13 @@ default nor provider configuration. OAuth accounts remain in their separate sectand resize; model selection immediately adds or removes its configurationrow. Configuration rows stay compact until expanded; expanding one row doesnot expand or collapse any other row.+- Model rows show the published context and output limits. A generic runtime+ fallback is not shown as a published limit; Settings displays an em dash+ until models.dev publishes a value or the user pins one in Advanced.+- The two model panes remain side by side when the viewport is wide enough,+ including short wide windows; their lists scroll inside the panes. They stack+ only when the viewport is too narrow for readable columns, and their lists+ remain reachable in that layout.- The left-pane list header carries a checkbox that selects or clears everycurrently visible row. A search filter narrows which rows "all" means;already-chosen bindings keep their advanced overrides. The checkbox isdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex c53ac6852..b79a48883 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1101,18 +1101,22 @@ identify the platform validation still needed.- **Status**: Unit-covered (header merge, one-shot stream options, and thecompaction summary request)-#### E2E-005E: Model-level wire API wins over the provider style+#### E2E-005E: Provider and model wire API precedence stays explicit- **Preconditions**: An OpenCode Go provider is configured; a deterministicfixture serves `muse-spark-1.3-contributor` on `/responses` and 500s it on- `/chat/completions`. A second generic provider serves the same model id on- `/chat/completions`.+ `/chat/completions`. A generic provider and a custom endpoint each serve the+ same model id; the custom model metadata pins `openai-completions`, while its+ saved provider style is Responses.- **Steps**: 1) Select the muse model on the OpenCode Go provider and send aturn. 2) Capture the outbound request path. 3) Repeat against the generic- provider with the same model id.+ provider with the same model id. 4) Select the model on the custom endpoint+ and send a turn, then capture its outbound request path.- **Expected**: The OpenCode Go turn posts to `/responses` (the model-level`api: "openai-responses"` pin wins); the generic turn still posts to- `/chat/completions`. Replayed history carries the resolved API.+ `/chat/completions`; the custom endpoint posts to `/responses` because its+ saved provider style wins over the model metadata. Replayed history carries+ the resolved API.- **Specs linked**: `03-runtime/11-provider-model-system.md`,`03-runtime/12-provider-config-schema.md`, ADR 0116- **Acceptance**: F (runtime provider requests)@@ -4833,7 +4837,12 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.inspect the sidecar model snapshot/request metadata. 4) Use Settings → Modelconfiguration to force a models.dev refresh and confirm the new record isvisible without changing the bundled file or writing a user cache. 5) Repeat- with an ID absent from models.dev.+ with an ID absent from models.dev and confirm its limits display as unknown+ in Settings. 6) Open the picker at a wide but short+ viewport (1254 × 772 CSS px): confirm the model panes remain side by side,+ both lists scroll inside their panes, and a selected model's Advanced fields+ are reachable. Narrow the viewport to 520 × 480 CSS px and confirm the panes+ stack while both lists and Advanced remain reachable.- **Expected**: The matching models.dev record is authoritative, including its`limit`, `modalities`, `reasoning_options`, `tool_call`,`structured_output`, dates, and cost fields; no provider secret is sent to@@ -4842,14 +4851,18 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.model shows PDF in its modality metadata; PDF attachments remain bounded filereferences until the selected transport exposes a native PDF block. Aprovider-discovered or explicitly configured ID absent from models.dev remains- runnable with the generic text-only, non-reasoning shape; pi-ai supplies only- the selected wire adapter, OAuth flow, and fallback account IDs. A ChatGPT- Plus/Pro or GitHub Copilot account lists IDs returned by its live account- endpoint; matching models.dev records supply their published metadata, while+ runnable with the generic text-only, non-reasoning shape; Settings shows an+ em dash instead of presenting its 128k / 8.2k runtime fallback as a published+ model limit. Explicit user limits remain visible. pi-ai supplies only+ the selected wire adapter, OAuth flow, and fallback account IDs. The custom+ endpoint keeps its selected API style even if the published model adapter+ differs; named providers may retain a model-level route when required. A+ ChatGPT Plus/Pro or GitHub Copilot account lists IDs returned by its live+ account endpoint; matching models.dev records supply their published metadata, whilelive-only IDs absent from models.dev keep generic chat limits and capabilities.- **Specs linked**: `02-architecture/02-tech-stack.md`,`03-runtime/11-provider-model-system.md`,- `03-runtime/13-model-catalog-and-selection.md`, ADR 0134+ `03-runtime/13-model-catalog-and-selection.md`, ADR `models-dev-catalog-authority`- **Acceptance**: B (model config), C (conversation & stream), Security- **Milestone**: M5- **Status**: Unit-covered (`model-capabilities.test.ts`,diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 97ea2753f..44d8cc3f0 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -34,6 +34,7 @@ This log freezes previously open questions into concrete decisions.| D637 | Remove the Windows frameless resize rim | **Disable the Windows main window's thick frame while retaining Electron 43.6 native frameless edge and corner resizing. Apply a 4 DIP native rounded shape by default; authorized plugin themes may choose an integer radius from 0 to 24 DIP. Keep the D635 minimum-size contract and existing work-panel resize ownership. See ADR 0317 and E2E-167.** | The thick frame paints an unwanted left, bottom, and right rim that themes cannot remove. Native hit testing and shape keep resizing and transparent outer corners without renderer resize IPC. || D638 | Publish native Linux arm64 artifacts | **Amend D126 / D285 / D603 / ADR 0022: tag releases publish native Linux arm64 AppImage, deb, and rpm packages, built on GitHub's native `ubuntu-22.04-arm` runner and carrying an arm64 `pi-desktop-host-core`. The static Linux targets drop their pinned `arch` and take the workflow's `--x64` / `--arm64` flag; `linux.artifactName` becomes `PI-Desktop-<version>-linux-<arch>.AppImage`; each Linux lane verifies its architecture-named updater feed (`latest-linux.yml` on x64, `latest-linux-arm64.yml` on arm64); the ASAR export reads `linux-unpacked` or `linux-arm64-unpacked` and publishes `PI-Desktop-<version>-linux-<arch>.asar`. `pi-host-bundle` builds both Linux architectures and `PUBLISHED_TARGETS` gains `linux-arm64`. Updater ownership, signing, and delivery modes are unchanged. See ADR 0318, issue #1281, and E2E-192a.** | arm64 Linux devices could not install or run the published x64 artifact, and a cross-built or emulated lane would ship a mismatched Rust sidecar. || D639 | models.dev owns published chat-model metadata | **Supersede D136 / D266 and ADR `pi-ai-core-0991-authority` for chat metadata: the bundled and explicitly refreshed models.dev catalog supplies published chat-model limits, modalities, reasoning metadata, names, and prices. Prefer the selected official publisher; when it has no record, accept another publisher only for a safe, unambiguous match, otherwise keep generic metadata. The checked-in preset identities are the priority set; do not assert an unsupported fixed count of 39. Live endpoint/OAuth discovery still owns selectable IDs. Pi remains responsible for OAuth, wire identity, transport and typed non-chat operations, but never supplies sibling chat limits, reasoning or prices. Explicit user binding overrides remain authoritative. No credentials are sent to models.dev; no host schema/protocol or persistence change. See ADR `models-dev-catalog-authority` and E2E-162 / E2E-MODEL-catalog-window-correction-reaches-saved-bindings.** | A Pi sibling default assigned a 272,000-token window to GPT models whose selected models.dev records publish 1,050,000 tokens, changing the Settings display and runtime context budget. |+| D640 | Custom endpoint API style precedence | **A custom endpoint uses the saved provider-row `apiStyle` ahead of a model catalog's adapter API. Named and OAuth providers can continue to use a model-level wire API pin where their published configuration requires a different transport. This keeps a user's explicit endpoint choice stable without removing model-specific routing such as OpenCode Go Responses models. No persisted format or protocol change. See E2E-005E and issue #1313.** | A publisher's adapter default must not silently redirect a custom gateway whose user-selected API format is different. || D450 | Signed macOS GitHub Releases | **Amend D078 / ADR 0022: GitHub tag releases Developer ID-sign, notarize (`notarytool` via electron-builder 26), staple, and Gatekeeper-verify macOS DMG/ZIP before upload, using identity `Developer ID Application: XingYu Liu (DUV63RKYTW)` / team `DUV63RKYTW` from Actions secrets (`CSC_LINK`, `CSC_KEY_PASSWORD`, `APPLE_ID`, `APPLE_APP_SPECIFIC_PASSWORD`, `APPLE_TEAM_ID`). Missing secrets fail the job. Local unsigned packaging without a certificate remains. `workflow_dispatch` may set `sign_macos: false` only for unsigned debug artifacts. Packaged macOS uses in-app `electron-updater` (ZIP + merged `latest-mac.yml`); Linux deb/rpm and Windows portable ZIP stay notify-and-link. No afterPack/afterSign adhoc codesign (ADR 0278).** | Production DMGs must open without a Gatekeeper warning, and signed macOS installs can download and restart into a new tag. See ADR 0289, E2E-196c, E2E-067A. |## B. Secondary implementation defaultsdiff --git a/packages/agent-runtime/src/provider-binding.test.ts b/packages/agent-runtime/src/provider-binding.test.tsindex 46c2d10a6..bc4036443 100644--- a/packages/agent-runtime/src/provider-binding.test.ts+++ b/packages/agent-runtime/src/provider-binding.test.ts@@ -201,6 +201,70 @@ describe("Anthropic runtime endpoint", () => {expect(request?.headers.get("Authorization")).toBeNull();});+ it("does not send the mid-conversation tool-change beta for a models.dev Claude gateway", async () => {+ const provider: RuntimeProviderConfig = {+ ...keyedProvider,+ id: "sub2api-anthropic-gateway",+ vendorKey: "custom",+ name: "sub2api",+ baseUrl: "https://relay.example/v1",+ modelId: "claude-opus-5-5",+ apiStyle: "anthropic_messages",+ supportsReasoning: true,+ supportedThinkingLevels: ["off", "medium"],+ modelConfig: {+ source: "models.dev",+ name: "Claude Opus 5.5",+ baseUrl: "https://relay.example/v1",+ reasoning: true,+ reasoningOptions: [{ type: "effort", values: ["low", "medium", "high"] }],+ thinkingProtocol: "adaptive",+ input: ["text"],+ contextWindow: 200_000,+ maxTokens: 16_000,+ },+ };+ const model = buildProviderModel(provider);+ let request: Request | undefined;+ const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ request = new Request(input, init);+ return new Response(+ JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: "test response" } }),+ { status: 400, headers: { "content-type": "application/json" } },+ );+ });+ const readTool = {+ name: "Read",+ description: "Read a file",+ parameters: { type: "object", properties: { path: { type: "string" } } },+ };++ const result = await createProviderModels(provider, model)+ .streamSimple(+ model,+ {+ messages: [+ { role: "system", content: "system", toolsAdded: [readTool], timestamp: 1 },+ { role: "user", content: "hello", timestamp: 2 },+ ],+ tools: [],+ },+ { fetch, maxRetries: 0 },+ )+ .result();++ expect(result.stopReason).toBe("error");+ expect(+ Object.hasOwn(model.compat ?? {}, "supportsMidConvoSystemMessages"),+ ).toBe(false);+ expect(+ Object.hasOwn(model.compat ?? {}, "supportsMidConvoToolChanges"),+ ).toBe(false);+ expect(request?.headers.get("anthropic-beta") ?? "").not.toMatch(+ /mid-conversation-tool-changes|inline-tools/,+ );+ });+it("uses adaptive thinking for models explicitly marked adaptive", async () => {const provider: RuntimeProviderConfig = {...keyedProvider,@@ -828,6 +892,73 @@ describe("buildProviderModel model-level wire API", () => {expect(model.api).toBe("openai-completions");});+ it("honors the API format selected for a custom endpoint over a model catalog API", () => {+ const provider: RuntimeProviderConfig = {+ ...keyedProvider,+ id: "zhipu-custom-endpoint",+ name: "Zhipu Responses endpoint",+ vendorKey: "custom",+ baseUrl: "https://open.bigmodel.cn/api/v1",+ modelId: "glm-5.3-flash",+ apiStyle: "responses",+ modelConfig: {+ source: "models.dev",+ name: "GLM 5.3 Flash",+ baseUrl: "https://open.bigmodel.cn/api/v1",+ api: "openai-completions",+ reasoning: true,+ input: ["text"],+ contextWindow: 200_000,+ maxTokens: 32_000,+ },+ };++ expect(buildProviderModel(provider).api).toBe("openai-responses");+ });++ it("posts a custom endpoint model to the explicitly selected Responses route", async () => {+ const provider: RuntimeProviderConfig = {+ ...keyedProvider,+ id: "zhipu-custom-endpoint",+ name: "Zhipu Responses endpoint",+ vendorKey: "custom",+ baseUrl: "https://open.bigmodel.cn/api/v1",+ modelId: "glm-5.3-flash",+ apiStyle: "responses",+ modelConfig: {+ source: "models.dev",+ name: "GLM 5.3 Flash",+ baseUrl: "https://open.bigmodel.cn/api/v1",+ api: "openai-completions",+ reasoning: true,+ input: ["text"],+ contextWindow: 200_000,+ maxTokens: 32_000,+ },+ };+ const model = buildProviderModel(provider);+ const urls: string[] = [];+ const fetch = vi.fn(async (input: RequestInfo | URL) => {+ urls.push(input instanceof Request ? input.url : String(input));+ return new Response("bad gateway", { status: 502 });+ });++ const result = await createProviderModels(provider, model)+ .streamSimple(+ model,+ {+ systemPrompt: "system",+ messages: [{ role: "user", content: "hello", timestamp: Date.now() }],+ tools: [],+ },+ { fetch },+ )+ .result();++ expect(result.stopReason).toBe("error");+ expect(urls).toEqual(["https://open.bigmodel.cn/api/v1/responses"]);+ });+it("leaves the same model on completions under other providers (issue #105)", () => {const model = buildProviderModel({...responsesCatalogProvider,diff --git a/packages/agent-runtime/src/provider-binding.ts b/packages/agent-runtime/src/provider-binding.tsindex a8135e18a..5733dd2ee 100644--- a/packages/agent-runtime/src/provider-binding.ts+++ b/packages/agent-runtime/src/provider-binding.ts@@ -198,6 +198,7 @@ function providerRequestTransport(provider: RuntimeProviderConfig) {const modelStyle = resolveApiStyle(provider.modelConfig?.api);const resolvedProviderStyle = resolveApiStyle(provider.apiStyle);const providerStyle = resolvedProviderStyle ?? (provider.apiStyle ? normalizeApiStyle(provider.apiStyle) : undefined);+ const customEndpoint = provider.vendorKey?.trim().toLowerCase() === "custom";const isOpenAiStyle = (style: string | undefined) =>style === "chat_completions" ||style === "responses" ||@@ -208,7 +209,14 @@ function providerRequestTransport(provider: RuntimeProviderConfig) {!modelStyle ||modelStyle === providerStyle ||(isOpenAiStyle(providerStyle) && isOpenAiStyle(modelStyle));- const apiStyle = (isCompatible ? modelStyle : undefined) ?? provider.apiStyle;+ // A custom endpoint's saved API format describes the user's actual gateway.+ // Published model metadata may describe another publisher's default adapter;+ // it cannot silently retarget that request. Other providers may use a+ // compatible model-level pin, such as OpenCode Go's Responses route (#105),+ // but foreign catalog protocols must not replace the provider's wire style.+ const apiStyle = customEndpoint+ ? provider.apiStyle ?? modelStyle+ : (isCompatible ? modelStyle : undefined) ?? provider.apiStyle;return nativeWebSearchTransport({apiStyle,baseUrl: provider.baseUrl ?? provider.modelConfig?.baseUrl ?? apiBindingForStyle(apiStyle).defaultBaseUrl,